hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
24af850fbce3d2f931306d3c2368a679a16087a1
1,815
package org.aktin.broker.db; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.nio.file.Paths; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Collection; import java.util.Collections; import javax.sql.DataSource; import org.aktin.broker.auth.Principal; import org.aktin.broker.server.auth.AuthInfoImpl; import org.aktin.broker.server.auth.AuthRole; import org.junit.Assert; import org.junit.Test; public class TestDatabasePostgresql extends AbstractDatabase{ private String jdbcUrl; @Override public Connection getConnection() throws SQLException{ return DriverManager.getConnection("jdbc:sqlite:target/broker_test.sqlite"); } @Test public void verifyDatabaseFileCreated() throws SQLException{ //resetDatabase(); Assert.assertTrue(true); } public static void main(String [] args) throws IOException, SQLException { TestDatabasePostgresql test = new TestDatabasePostgresql(); test.jdbcUrl = "jdbc:postgresql://localhost/postgres?user=postgres&password=mysecretpassword"; DataSource ds; try { Class<? extends DataSource> clazz = Class.forName("org.postgresql.ds.PGSimpleDataSource").asSubclass(DataSource.class); ds = clazz.getConstructor().newInstance(); clazz.getMethod("setURL", String.class).invoke(ds, test.jdbcUrl); } catch ( Exception e) { throw new RuntimeException("Unable to initialize PostgreSQL DataSource", e); } BrokerImpl impl = new BrokerImpl(ds, Paths.get("target/")); // try( Connection c = ds.getConnection() ){ // AbstractDatabase.resetDatabase(c); // } Principal p = impl.accessPrincipal(new AuthInfoImpl("123", "CN=bla", AuthRole.ALL_NODE)); System.out.println(p.getNodeId()); System.out.println(impl.getAllNodes().size()); } }
30.25
122
0.765289
6b33f2a81fc494a76963fbb0aacbecf825850f2e
21,735
/* * 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.presto.orc; import com.facebook.presto.block.BlockEncodingManager; import com.facebook.presto.metadata.FunctionManager; import com.facebook.presto.orc.cache.StorageOrcFileTailSource; import com.facebook.presto.spi.block.Block; import com.facebook.presto.spi.type.BigintType; import com.facebook.presto.spi.type.BooleanType; import com.facebook.presto.spi.type.DoubleType; import com.facebook.presto.spi.type.IntegerType; import com.facebook.presto.spi.type.NamedTypeSignature; import com.facebook.presto.spi.type.RealType; import com.facebook.presto.spi.type.RowFieldName; import com.facebook.presto.spi.type.SmallintType; import com.facebook.presto.spi.type.SqlTimestamp; import com.facebook.presto.spi.type.SqlVarbinary; import com.facebook.presto.spi.type.StandardTypes; import com.facebook.presto.spi.type.TimeZoneKey; import com.facebook.presto.spi.type.TinyintType; import com.facebook.presto.spi.type.Type; import com.facebook.presto.spi.type.TypeManager; import com.facebook.presto.spi.type.TypeSignatureParameter; import com.facebook.presto.spi.type.VarbinaryType; import com.facebook.presto.spi.type.VarcharType; import com.facebook.presto.sql.analyzer.FeaturesConfig; import com.facebook.presto.type.TypeRegistry; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import io.airlift.units.DataSize; import org.testng.annotations.Test; import java.io.File; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Function; import static com.facebook.presto.memory.context.AggregatedMemoryContext.newSimpleAggregatedMemoryContext; import static com.facebook.presto.orc.OrcTester.HIVE_STORAGE_TIME_ZONE; import static com.facebook.presto.orc.TestMapFlatBatchStreamReader.ExpectedValuesBuilder.Frequency.ALL; import static com.facebook.presto.orc.TestMapFlatBatchStreamReader.ExpectedValuesBuilder.Frequency.NONE; import static com.facebook.presto.orc.TestMapFlatBatchStreamReader.ExpectedValuesBuilder.Frequency.SOME; import static com.facebook.presto.orc.TestingOrcPredicate.createOrcPredicate; import static com.facebook.presto.testing.TestingConnectorSession.SESSION; import static com.google.common.collect.Iterators.advance; import static com.google.common.io.Resources.getResource; import static io.airlift.units.DataSize.Unit.MEGABYTE; import static java.lang.Math.toIntExact; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; public class TestMapFlatBatchStreamReader { // TODO: Add tests for timestamp as value type private static final TypeManager TYPE_MANAGER = new TypeRegistry(); private static final int NUM_ROWS = 31_234; static { // associate TYPE_MANAGER with a function manager new FunctionManager(TYPE_MANAGER, new BlockEncodingManager(TYPE_MANAGER), new FeaturesConfig()); } private static final Type LIST_TYPE = TYPE_MANAGER.getParameterizedType( StandardTypes.ARRAY, ImmutableList.of(TypeSignatureParameter.of(IntegerType.INTEGER.getTypeSignature()))); private static final Type MAP_TYPE = TYPE_MANAGER.getParameterizedType( StandardTypes.MAP, ImmutableList.of(TypeSignatureParameter.of(VarcharType.VARCHAR.getTypeSignature()), TypeSignatureParameter.of(RealType.REAL.getTypeSignature()))); private static final Type STRUCT_TYPE = TYPE_MANAGER.getParameterizedType( StandardTypes.ROW, ImmutableList.of( TypeSignatureParameter.of(new NamedTypeSignature(Optional.of(new RowFieldName("value1", false)), IntegerType.INTEGER.getTypeSignature())), TypeSignatureParameter.of(new NamedTypeSignature(Optional.of(new RowFieldName("value2", false)), IntegerType.INTEGER.getTypeSignature())), TypeSignatureParameter.of(new NamedTypeSignature(Optional.of(new RowFieldName("value3", false)), IntegerType.INTEGER.getTypeSignature())))); @Test public void testByte() throws Exception { runTest("test_flat_map/flat_map_byte.dwrf", TinyintType.TINYINT, ExpectedValuesBuilder.get(Integer::byteValue)); } @Test public void testByteWithNull() throws Exception { runTest("test_flat_map/flat_map_byte_with_null.dwrf", TinyintType.TINYINT, ExpectedValuesBuilder.get(Integer::byteValue).setNullValuesFrequency(SOME)); } @Test public void testShort() throws Exception { runTest("test_flat_map/flat_map_short.dwrf", SmallintType.SMALLINT, ExpectedValuesBuilder.get(Integer::shortValue)); } @Test public void testInteger() throws Exception { runTest("test_flat_map/flat_map_int.dwrf", IntegerType.INTEGER, ExpectedValuesBuilder.get(Function.identity())); } @Test public void testIntegerWithNull() throws Exception { runTest("test_flat_map/flat_map_int_with_null.dwrf", IntegerType.INTEGER, ExpectedValuesBuilder.get(Function.identity()).setNullValuesFrequency(SOME)); } @Test public void testLong() throws Exception { runTest("test_flat_map/flat_map_long.dwrf", BigintType.BIGINT, ExpectedValuesBuilder.get(Integer::longValue)); } @Test public void testString() throws Exception { runTest("test_flat_map/flat_map_string.dwrf", VarcharType.VARCHAR, ExpectedValuesBuilder.get(i -> Integer.toString(i))); } @Test public void testStringWithNull() throws Exception { runTest("test_flat_map/flat_map_string_with_null.dwrf", VarcharType.VARCHAR, ExpectedValuesBuilder.get(i -> Integer.toString(i)).setNullValuesFrequency(SOME)); } @Test public void testBinary() throws Exception { runTest("test_flat_map/flat_map_binary.dwrf", VarbinaryType.VARBINARY, ExpectedValuesBuilder.get(i -> new SqlVarbinary(Integer.toString(i).getBytes(StandardCharsets.UTF_8)))); } @Test public void testBoolean() throws Exception { runTest("test_flat_map/flat_map_boolean.dwrf", IntegerType.INTEGER, BooleanType.BOOLEAN, ExpectedValuesBuilder.get(Function.identity(), TestMapFlatBatchStreamReader::intToBoolean)); } @Test public void testBooleanWithNull() throws Exception { runTest("test_flat_map/flat_map_boolean_with_null.dwrf", IntegerType.INTEGER, BooleanType.BOOLEAN, ExpectedValuesBuilder.get(Function.identity(), TestMapFlatBatchStreamReader::intToBoolean).setNullValuesFrequency(SOME)); } @Test public void testFloat() throws Exception { runTest("test_flat_map/flat_map_float.dwrf", IntegerType.INTEGER, RealType.REAL, ExpectedValuesBuilder.get(Function.identity(), Float::valueOf)); } @Test public void testFloatWithNull() throws Exception { runTest("test_flat_map/flat_map_float_with_null.dwrf", IntegerType.INTEGER, RealType.REAL, ExpectedValuesBuilder.get(Function.identity(), Float::valueOf).setNullValuesFrequency(SOME)); } @Test public void testDouble() throws Exception { runTest("test_flat_map/flat_map_double.dwrf", IntegerType.INTEGER, DoubleType.DOUBLE, ExpectedValuesBuilder.get(Function.identity(), Double::valueOf)); } @Test public void testDoubleWithNull() throws Exception { runTest("test_flat_map/flat_map_double_with_null.dwrf", IntegerType.INTEGER, DoubleType.DOUBLE, ExpectedValuesBuilder.get(Function.identity(), Double::valueOf).setNullValuesFrequency(SOME)); } @Test public void testList() throws Exception { runTest( "test_flat_map/flat_map_list.dwrf", IntegerType.INTEGER, LIST_TYPE, ExpectedValuesBuilder.get(Function.identity(), TestMapFlatBatchStreamReader::intToList)); } @Test public void testListWithNull() throws Exception { runTest( "test_flat_map/flat_map_list_with_null.dwrf", IntegerType.INTEGER, LIST_TYPE, ExpectedValuesBuilder.get(Function.identity(), TestMapFlatBatchStreamReader::intToList).setNullValuesFrequency(SOME)); } @Test public void testMap() throws Exception { runTest( "test_flat_map/flat_map_map.dwrf", IntegerType.INTEGER, MAP_TYPE, ExpectedValuesBuilder.get(Function.identity(), TestMapFlatBatchStreamReader::intToMap)); } @Test public void testMapWithNull() throws Exception { runTest( "test_flat_map/flat_map_map_with_null.dwrf", IntegerType.INTEGER, MAP_TYPE, ExpectedValuesBuilder.get(Function.identity(), TestMapFlatBatchStreamReader::intToMap).setNullValuesFrequency(SOME)); } @Test public void testStruct() throws Exception { runTest( "test_flat_map/flat_map_struct.dwrf", IntegerType.INTEGER, STRUCT_TYPE, ExpectedValuesBuilder.get(Function.identity(), TestMapFlatBatchStreamReader::intToList)); } @Test public void testStructWithNull() throws Exception { runTest( "test_flat_map/flat_map_struct_with_null.dwrf", IntegerType.INTEGER, STRUCT_TYPE, ExpectedValuesBuilder.get(Function.identity(), TestMapFlatBatchStreamReader::intToList).setNullValuesFrequency(SOME)); } @Test public void testWithNulls() throws Exception { // A test case where some of the flat maps are null runTest( "test_flat_map/flat_map_some_null_maps.dwrf", IntegerType.INTEGER, ExpectedValuesBuilder.get(Function.identity()).setNullRowsFrequency(SOME)); } @Test public void testWithAllNulls() throws Exception { // A test case where every flat map is null runTest( "test_flat_map/flat_map_all_null_maps.dwrf", IntegerType.INTEGER, ExpectedValuesBuilder.get(Function.identity()).setNullRowsFrequency(ALL)); } @Test public void testWithEmptyMaps() throws Exception { // A test case where some of the flat maps are empty runTest( "test_flat_map/flat_map_some_empty_maps.dwrf", IntegerType.INTEGER, ExpectedValuesBuilder.get(Function.identity()).setEmptyMapsFrequency(SOME)); } @Test public void testWithAllMaps() throws Exception { // A test case where all of the flat maps are empty runTest( "test_flat_map/flat_map_all_empty_maps.dwrf", IntegerType.INTEGER, ExpectedValuesBuilder.get(Function.identity()).setEmptyMapsFrequency(ALL)); } @Test public void testMixedEncodings() throws Exception { // A test case where the values associated with one key are direct encoded, and all other keys are // dictionary encoded. The dictionary encoded values have occasional values that only appear once // to ensure the IN_DICTIONARY stream is present, which means the checkpoints for dictionary encoded // values will have a different number of positions compared to direct encoded values. runTest("test_flat_map/flat_map_mixed_encodings.dwrf", IntegerType.INTEGER, ExpectedValuesBuilder.get(Function.identity()).setMixedEncodings()); } @Test public void testIntegerWithMissingSequences() throws Exception { // A test case where the additional sequences IDs for a flat map aren't a consecutive range [1,N], the odd // sequence IDs have been removed. This is to simulate the case where a file has been modified to delete // certain keys from the map by dropping the ColumnEncodings and the associated data. runTest("test_flat_map/flat_map_int_missing_sequences.dwrf", IntegerType.INTEGER, ExpectedValuesBuilder.get(Function.identity()).setMissingSequences()); } private <K, V> void runTest(String testOrcFileName, Type type, ExpectedValuesBuilder<K, V> expectedValuesBuilder) throws Exception { runTest(testOrcFileName, type, type, expectedValuesBuilder); } private <K, V> void runTest(String testOrcFileName, Type keyType, Type valueType, ExpectedValuesBuilder<K, V> expectedValuesBuilder) throws Exception { List<Map<K, V>> expectedValues = expectedValuesBuilder.build(); runTest(testOrcFileName, keyType, valueType, expectedValues, false, false); runTest(testOrcFileName, keyType, valueType, expectedValues, true, false); runTest(testOrcFileName, keyType, valueType, expectedValues, false, true); } private <K, V> void runTest(String testOrcFileName, Type keyType, Type valueType, List<Map<K, V>> expectedValues, boolean skipFirstBatch, boolean skipFirstStripe) throws Exception { OrcDataSource orcDataSource = new FileOrcDataSource( new File(getResource(testOrcFileName).getFile()), new DataSize(1, MEGABYTE), new DataSize(1, MEGABYTE), new DataSize(1, MEGABYTE), true); OrcReader orcReader = new OrcReader( orcDataSource, OrcEncoding.DWRF, new StorageOrcFileTailSource(), new StorageStripeMetadataSource(), OrcReaderTestingUtils.createDefaultTestConfig()); Type mapType = TYPE_MANAGER.getParameterizedType( StandardTypes.MAP, ImmutableList.of( TypeSignatureParameter.of(keyType.getTypeSignature()), TypeSignatureParameter.of(valueType.getTypeSignature()))); try (OrcBatchRecordReader recordReader = orcReader.createBatchRecordReader(ImmutableMap.of(0, mapType), createOrcPredicate(0, mapType, expectedValues, OrcTester.Format.DWRF, true), HIVE_STORAGE_TIME_ZONE, newSimpleAggregatedMemoryContext(), 1024)) { Iterator<?> expectedValuesIterator = expectedValues.iterator(); boolean isFirst = true; int rowsProcessed = 0; for (int batchSize = toIntExact(recordReader.nextBatch()); batchSize >= 0; batchSize = toIntExact(recordReader.nextBatch())) { if (skipFirstStripe && rowsProcessed < 10_000) { assertEquals(advance(expectedValuesIterator, batchSize), batchSize); } else if (skipFirstBatch && isFirst) { assertEquals(advance(expectedValuesIterator, batchSize), batchSize); isFirst = false; } else { Block block = recordReader.readBlock(0); for (int position = 0; position < block.getPositionCount(); position++) { assertEquals(mapType.getObjectValue(SESSION, block, position), expectedValuesIterator.next()); } } assertEquals(recordReader.getReaderPosition(), rowsProcessed); assertEquals(recordReader.getFilePosition(), rowsProcessed); rowsProcessed += batchSize; } assertFalse(expectedValuesIterator.hasNext()); assertEquals(recordReader.getReaderPosition(), rowsProcessed); assertEquals(recordReader.getFilePosition(), rowsProcessed); } } private static boolean intToBoolean(int i) { return i % 2 == 0; } private static SqlTimestamp intToTimestamp(int i) { return new SqlTimestamp(i, TimeZoneKey.UTC_KEY); } private static List<Integer> intToList(int i) { return ImmutableList.of(i * 3, i * 3 + 1, i * 3 + 2); } private static Map<String, Float> intToMap(int i) { return ImmutableMap.of(Integer.toString(i * 3), (float) (i * 3), Integer.toString(i * 3 + 1), (float) (i * 3 + 1), Integer.toString(i * 3 + 2), (float) (i * 3 + 2)); } static class ExpectedValuesBuilder<K, V> { enum Frequency { NONE, SOME, ALL } private final Function<Integer, K> keyConverter; private final Function<Integer, V> valueConverter; private Frequency nullValuesFrequency = NONE; private Frequency nullRowsFrequency = NONE; private Frequency emptyMapsFrequency = NONE; private boolean mixedEncodings; private boolean missingSequences; private ExpectedValuesBuilder(Function<Integer, K> keyConverter, Function<Integer, V> valueConverter) { this.keyConverter = keyConverter; this.valueConverter = valueConverter; } public static <T> ExpectedValuesBuilder<T, T> get(Function<Integer, T> converter) { return new ExpectedValuesBuilder<>(converter, converter); } public static <K, V> ExpectedValuesBuilder<K, V> get(Function<Integer, K> keyConverter, Function<Integer, V> valueConverter) { return new ExpectedValuesBuilder<>(keyConverter, valueConverter); } public ExpectedValuesBuilder<K, V> setNullValuesFrequency(Frequency frequency) { this.nullValuesFrequency = frequency; return this; } public ExpectedValuesBuilder<K, V> setNullRowsFrequency(Frequency frequency) { this.nullRowsFrequency = frequency; return this; } public ExpectedValuesBuilder<K, V> setEmptyMapsFrequency(Frequency frequency) { this.emptyMapsFrequency = frequency; return this; } public ExpectedValuesBuilder<K, V> setMixedEncodings() { this.mixedEncodings = true; return this; } public ExpectedValuesBuilder<K, V> setMissingSequences() { this.missingSequences = true; return this; } public List<Map<K, V>> build() { List<Map<K, V>> result = new ArrayList<>(NUM_ROWS); for (int i = 0; i < NUM_ROWS; ++i) { if (passesFrequencyCheck(nullRowsFrequency, i)) { result.add((Map<K, V>) null); } else if (passesFrequencyCheck(emptyMapsFrequency, i)) { result.add(Collections.emptyMap()); } else { Map<K, V> row = new HashMap<>(); for (int j = 0; j < 3; j++) { V value; int key = (i * 3 + j) % 32; if (missingSequences && key % 2 == 1) { continue; } if (j == 0 && passesFrequencyCheck(nullValuesFrequency, i)) { value = null; } else if (mixedEncodings && (key == 1 || j == 2)) { // TODO: add comments to explain the condition value = valueConverter.apply(i * 3 + j); } else { value = valueConverter.apply((i * 3 + j) % 32); } row.put(keyConverter.apply(key), value); } result.add(row); } } return result; } private boolean passesFrequencyCheck(Frequency frequency, int i) { switch (frequency) { case NONE: return false; case ALL: return true; case SOME: return i % 5 == 0; default: throw new IllegalArgumentException("Got unexpected Frequency: " + frequency); } } } }
37.090444
257
0.629584
b0e3e0ebf23ebc251afec90b798f58ca256aa7bc
2,506
/* * 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.nifi.registry.client; import org.apache.nifi.registry.extension.component.ExtensionFilterParams; import org.apache.nifi.registry.extension.component.ExtensionMetadataContainer; import org.apache.nifi.registry.extension.component.TagCount; import org.apache.nifi.registry.extension.component.manifest.ProvidedServiceAPI; import java.io.IOException; import java.util.List; /** * Client for obtaining information about extensions. */ public interface ExtensionClient { /** * Retrieves extensions according to the given filter params. * * @param filterParams the filter params * @return the metadata for the extensions matching the filter params * * @throws IOException if an I/O error occurs * @throws NiFiRegistryException if an non I/O error occurs */ ExtensionMetadataContainer findExtensions(ExtensionFilterParams filterParams) throws IOException, NiFiRegistryException; /** * Retrieves extensions that provide the given service API. * * @param providedServiceAPI the service API * @return the metadata for extensions that provided the service API * * @throws IOException if an I/O error occurs * @throws NiFiRegistryException if an non I/O error occurs */ ExtensionMetadataContainer findExtensions(ProvidedServiceAPI providedServiceAPI) throws IOException, NiFiRegistryException; /** * @return all of the tags known the registry with their corresponding counts * * @throws IOException if an I/O error occurs * @throws NiFiRegistryException if an non I/O error occurs */ List<TagCount> getTagCounts() throws IOException, NiFiRegistryException; }
39.777778
127
0.752594
245e41ee328d32b0e9afc959f4379d75b01251e1
1,644
package com.leone.boot.shiro.exception; import org.springframework.boot.web.servlet.error.ErrorAttributes; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.WebRequest; import java.util.LinkedHashMap; import java.util.Map; /** * @author leone **/ @Component public class GlobalErrorAttributes implements ErrorAttributes { @Override public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) { Map<String, Object> errorAttributes = new LinkedHashMap<>(); Integer status = getAttribute(webRequest, "javax.servlet.error.status_code"); if (status == null) { errorAttributes.put("code", 40000); errorAttributes.put("message", "None"); } else { errorAttributes.put("code", status); errorAttributes.put("message", getDetail(status)); } return errorAttributes; } @Override public Throwable getError(WebRequest webRequest) { return getAttribute(webRequest, "javax.servlet.error.exception"); } private String getDetail(Integer status) { try { return HttpStatus.valueOf(status).getReasonPhrase(); } catch (Exception e) { return status.toString(); } } @SuppressWarnings("unchecked") private <T> T getAttribute(RequestAttributes requestAttributes, String name) { return (T) requestAttributes.getAttribute(name, RequestAttributes.SCOPE_REQUEST); } }
31.615385
101
0.696472
8be285e60d7360b438ce3e554c8a01a96b219e47
13,365
package com.mycompany.myapp.config; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.web.cors.CorsConfiguration; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * Properties specific to JHipster. * * <p> * Properties are configured in the application.yml file. * </p> */ @ConfigurationProperties(prefix = "jhipster", ignoreUnknownFields = false) public class JHipsterProperties { private final Async async = new Async(); private final Http http = new Http(); private final Cache cache = new Cache(); private final Mail mail = new Mail(); private final Security security = new Security(); private final Swagger swagger = new Swagger(); private final Metrics metrics = new Metrics(); private final CorsConfiguration cors = new CorsConfiguration(); private final Gateway gateway = new Gateway(); private final Ribbon ribbon = new Ribbon(); public Async getAsync() { return async; } public Http getHttp() { return http; } public Cache getCache() { return cache; } public Mail getMail() { return mail; } public Security getSecurity() { return security; } public Swagger getSwagger() { return swagger; } public Metrics getMetrics() { return metrics; } public CorsConfiguration getCors() { return cors; } public Gateway getGateway() { return gateway; } public Ribbon getRibbon() { return ribbon; } public static class Async { private int corePoolSize = 2; private int maxPoolSize = 50; private int queueCapacity = 10000; public int getCorePoolSize() { return corePoolSize; } public void setCorePoolSize(int corePoolSize) { this.corePoolSize = corePoolSize; } public int getMaxPoolSize() { return maxPoolSize; } public void setMaxPoolSize(int maxPoolSize) { this.maxPoolSize = maxPoolSize; } public int getQueueCapacity() { return queueCapacity; } public void setQueueCapacity(int queueCapacity) { this.queueCapacity = queueCapacity; } } public static class Http { private final Cache cache = new Cache(); public Cache getCache() { return cache; } public static class Cache { private int timeToLiveInDays = 1461; public int getTimeToLiveInDays() { return timeToLiveInDays; } public void setTimeToLiveInDays(int timeToLiveInDays) { this.timeToLiveInDays = timeToLiveInDays; } } } public static class Cache { private int timeToLiveSeconds = 3600; public int getTimeToLiveSeconds() { return timeToLiveSeconds; } public void setTimeToLiveSeconds(int timeToLiveSeconds) { this.timeToLiveSeconds = timeToLiveSeconds; } } public static class Mail { private String from = "webapp@localhost"; public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } } public static class Security { private final Authentication authentication = new Authentication(); public Authentication getAuthentication() { return authentication; } public static class Authentication { private final Jwt jwt = new Jwt(); public Jwt getJwt() { return jwt; } public static class Jwt { private String secret; private long tokenValidityInSeconds = 1800; private long tokenValidityInSecondsForRememberMe = 2592000; public String getSecret() { return secret; } public void setSecret(String secret) { this.secret = secret; } public long getTokenValidityInSeconds() { return tokenValidityInSeconds; } public void setTokenValidityInSeconds(long tokenValidityInSeconds) { this.tokenValidityInSeconds = tokenValidityInSeconds; } public long getTokenValidityInSecondsForRememberMe() { return tokenValidityInSecondsForRememberMe; } public void setTokenValidityInSecondsForRememberMe(long tokenValidityInSecondsForRememberMe) { this.tokenValidityInSecondsForRememberMe = tokenValidityInSecondsForRememberMe; } } } } public static class Swagger { private String title = "webapp API"; private String description = "webapp API documentation"; private String version = "0.0.1"; private String termsOfServiceUrl; private String contactName; private String contactUrl; private String contactEmail; private String license; private String licenseUrl; private Boolean enabled; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getTermsOfServiceUrl() { return termsOfServiceUrl; } public void setTermsOfServiceUrl(String termsOfServiceUrl) { this.termsOfServiceUrl = termsOfServiceUrl; } public String getContactName() { return contactName; } public void setContactName(String contactName) { this.contactName = contactName; } public String getContactUrl() { return contactUrl; } public void setContactUrl(String contactUrl) { this.contactUrl = contactUrl; } public String getContactEmail() { return contactEmail; } public void setContactEmail(String contactEmail) { this.contactEmail = contactEmail; } public String getLicense() { return license; } public void setLicense(String license) { this.license = license; } public String getLicenseUrl() { return licenseUrl; } public void setLicenseUrl(String licenseUrl) { this.licenseUrl = licenseUrl; } public Boolean isEnabled() { return enabled; } public void setEnabled(Boolean enabled) { this.enabled = enabled; } } public static class Metrics { private final Jmx jmx = new Jmx(); private final Spark spark = new Spark(); private final Graphite graphite = new Graphite(); private final Logs logs = new Logs(); public Jmx getJmx() { return jmx; } public Spark getSpark() { return spark; } public Graphite getGraphite() { return graphite; } public Logs getLogs() { return logs; } public static class Jmx { private boolean enabled = true; public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } } public static class Spark { private boolean enabled = false; private String host = "localhost"; private int port = 9999; public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } } public static class Graphite { private boolean enabled = false; private String host = "localhost"; private int port = 2003; private String prefix = "webapp"; public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public String getPrefix() { return prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } } public static class Logs { private boolean enabled = false; private long reportFrequency = 60; public long getReportFrequency() { return reportFrequency; } public void setReportFrequency(int reportFrequency) { this.reportFrequency = reportFrequency; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } } } private final Logging logging = new Logging(); public Logging getLogging() { return logging; } public static class Logging { private final Logstash logstash = new Logstash(); public Logstash getLogstash() { return logstash; } public static class Logstash { private boolean enabled = false; private String host = "localhost"; private int port = 5000; private int queueSize = 512; public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public int getQueueSize() { return queueSize; } public void setQueueSize(int queueSize) { this.queueSize = queueSize; } } private final SpectatorMetrics spectatorMetrics = new SpectatorMetrics(); public SpectatorMetrics getSpectatorMetrics() { return spectatorMetrics; } public static class SpectatorMetrics { private boolean enabled = false; public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } } } public static class Gateway { private final RateLimiting rateLimiting = new RateLimiting(); public RateLimiting getRateLimiting() { return rateLimiting; } private Map<String, List<String>> authorizedMicroservicesEndpoints = new LinkedHashMap<>(); public Map<String, List<String>> getAuthorizedMicroservicesEndpoints() { return authorizedMicroservicesEndpoints; } public void setAuthorizedMicroservicesEndpoints(Map<String, List<String>> authorizedMicroservicesEndpoints) { this.authorizedMicroservicesEndpoints = authorizedMicroservicesEndpoints; } public static class RateLimiting { private boolean enabled = false; private long limit = 100000L; public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public long getLimit() { return this.limit; } public void setLimit(long limit) { this.limit = limit; } } } public static class Ribbon { private String[] displayOnActiveProfiles; public String[] getDisplayOnActiveProfiles() { return displayOnActiveProfiles; } public void setDisplayOnActiveProfiles(String[] displayOnActiveProfiles) { this.displayOnActiveProfiles = displayOnActiveProfiles; } } }
23.823529
117
0.557202
6cd00ca096bfd3d3db225e6d507623943cc55aff
701
package arc.fx.filters; import arc.*; import arc.fx.*; import arc.math.geom.*; public class OldTvFilter extends FxFilter{ private final Vec2 resolution = new Vec2(); public OldTvFilter(){ super(compileShader( Core.files.classpath("shaders/screenspace.vert"), Core.files.classpath("shaders/old-tv.frag"))); rebind(); } @Override public void resize(int width, int height){ this.resolution.set(width, height); rebind(); } @Override public void setParams(){ shader.setUniformi("u_texture0", u_texture0); shader.setUniformf("u_resolution", resolution); shader.setUniformf("u_time", time); } }
23.366667
57
0.636234
d073ba777d952842f8d0539e142662ea5bfb36b2
958
package xyz.brassgoggledcoders.reengineeredtoolbox.api.socket; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.common.capabilities.ICapabilityProvider; import net.minecraftforge.energy.IEnergyStorage; import xyz.brassgoggledcoders.reengineeredtoolbox.api.face.Face; import xyz.brassgoggledcoders.reengineeredtoolbox.api.queue.FluidStackQueue; import xyz.brassgoggledcoders.reengineeredtoolbox.api.queue.ItemStackQueue; import java.util.List; public interface ISocketTile extends ICapabilityProvider { ItemStackQueue getItemStackQueue(int number); FluidStackQueue getFluidStackQueue(int number); List<ItemStackQueue> getItemStackQueues(); List<FluidStackQueue> getFluidStackQueues(); Face getFaceOnSide(EnumFacing facing); World getWorld(); BlockPos getTilePos(); boolean isClient(); IEnergyStorage getEnergyStorage(); }
29.030303
76
0.816284
e1ee63b5dc146260b1f0030ac747067e25a3c46f
50,853
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ end_comment begin_package DECL|package|org.apache.hadoop.yarn.server.resourcemanager package|package name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|server operator|. name|resourcemanager package|; end_package begin_import import|import name|org operator|. name|slf4j operator|. name|Logger import|; end_import begin_import import|import name|org operator|. name|slf4j operator|. name|LoggerFactory import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|security operator|. name|UserGroupInformation import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|ams operator|. name|ApplicationMasterServiceContext import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|ams operator|. name|ApplicationMasterServiceUtils import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|ams operator|. name|ApplicationMasterServiceProcessor import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|api operator|. name|protocolrecords operator|. name|AllocateRequest import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|api operator|. name|protocolrecords operator|. name|AllocateResponse import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|api operator|. name|protocolrecords operator|. name|FinishApplicationMasterRequest import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|api operator|. name|protocolrecords operator|. name|FinishApplicationMasterResponse import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|api operator|. name|protocolrecords operator|. name|RegisterApplicationMasterRequest import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|api operator|. name|protocolrecords operator|. name|RegisterApplicationMasterResponse import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|api operator|. name|records operator|. name|ApplicationAttemptId import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|api operator|. name|records operator|. name|ApplicationSubmissionContext import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|api operator|. name|records operator|. name|CollectorInfo import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|api operator|. name|records operator|. name|Container import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|api operator|. name|records operator|. name|ContainerId import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|api operator|. name|records operator|. name|ContainerUpdateType import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|api operator|. name|records operator|. name|NMToken import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|api operator|. name|records operator|. name|NodeId import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|api operator|. name|records operator|. name|NodeReport import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|api operator|. name|records operator|. name|NodeUpdateType import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|api operator|. name|records operator|. name|PreemptionContainer import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|api operator|. name|records operator|. name|PreemptionContract import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|api operator|. name|records operator|. name|PreemptionMessage import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|api operator|. name|records operator|. name|PreemptionResourceRequest import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|api operator|. name|records operator|. name|Resource import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|api operator|. name|records operator|. name|ResourceBlacklistRequest import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|api operator|. name|records operator|. name|ResourceRequest import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|api operator|. name|records operator|. name|StrictPreemptionContract import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|api operator|. name|records operator|. name|UpdateContainerError import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|conf operator|. name|YarnConfiguration import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|exceptions operator|. name|InvalidContainerReleaseException import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|exceptions operator|. name|InvalidResourceBlacklistRequestException import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|exceptions operator|. name|InvalidResourceRequestException import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|exceptions operator|. name|InvalidResourceRequestException operator|. name|InvalidResourceType import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|exceptions operator|. name|SchedulerInvalidResoureRequestException import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|exceptions operator|. name|YarnException import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|factories operator|. name|RecordFactory import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|factory operator|. name|providers operator|. name|RecordFactoryProvider import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|server operator|. name|resourcemanager operator|. name|resource operator|. name|ResourceProfilesManager import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|server operator|. name|resourcemanager operator|. name|rmapp operator|. name|RMApp import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|server operator|. name|resourcemanager operator|. name|rmapp operator|. name|attempt operator|. name|RMAppAttempt import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|server operator|. name|resourcemanager operator|. name|rmapp operator|. name|attempt operator|. name|RMAppAttemptState import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|server operator|. name|resourcemanager operator|. name|rmapp operator|. name|attempt operator|. name|event operator|. name|RMAppAttemptRegistrationEvent import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|server operator|. name|resourcemanager operator|. name|rmapp operator|. name|attempt operator|. name|event operator|. name|RMAppAttemptStatusupdateEvent import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|server operator|. name|resourcemanager operator|. name|rmapp operator|. name|attempt operator|. name|event operator|. name|RMAppAttemptUnregistrationEvent import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|server operator|. name|resourcemanager operator|. name|rmnode operator|. name|RMNode import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|server operator|. name|resourcemanager operator|. name|scheduler operator|. name|AbstractYarnScheduler import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|server operator|. name|resourcemanager operator|. name|scheduler operator|. name|Allocation import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|server operator|. name|resourcemanager operator|. name|scheduler operator|. name|ContainerUpdates import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|server operator|. name|resourcemanager operator|. name|scheduler operator|. name|SchedulerNodeReport import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|server operator|. name|resourcemanager operator|. name|scheduler operator|. name|SchedulerUtils import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|server operator|. name|resourcemanager operator|. name|scheduler operator|. name|YarnScheduler import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|server operator|. name|utils operator|. name|BuilderUtils import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|util operator|. name|resource operator|. name|ResourceUtils import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|util operator|. name|resource operator|. name|Resources import|; end_import begin_import import|import name|java operator|. name|io operator|. name|IOException import|; end_import begin_import import|import name|java operator|. name|net operator|. name|UnknownHostException import|; end_import begin_import import|import name|java operator|. name|util operator|. name|ArrayList import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Collections import|; end_import begin_import import|import name|java operator|. name|util operator|. name|HashSet import|; end_import begin_import import|import name|java operator|. name|util operator|. name|List import|; end_import begin_import import|import name|java operator|. name|util operator|. name|HashMap import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Map import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Set import|; end_import begin_import import|import static name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|exceptions operator|. name|InvalidResourceRequestException operator|. name|InvalidResourceType operator|. name|GREATER_THEN_MAX_ALLOCATION import|; end_import begin_import import|import static name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|exceptions operator|. name|InvalidResourceRequestException operator|. name|InvalidResourceType operator|. name|LESS_THAN_ZERO import|; end_import begin_comment comment|/** * This is the default Application Master Service processor. It has be the * last processor in the @{@link AMSProcessingChain}. */ end_comment begin_class DECL|class|DefaultAMSProcessor specifier|final class|class name|DefaultAMSProcessor implements|implements name|ApplicationMasterServiceProcessor block|{ DECL|field|LOG specifier|private specifier|static specifier|final name|Logger name|LOG init|= name|LoggerFactory operator|. name|getLogger argument_list|( name|DefaultAMSProcessor operator|. name|class argument_list|) decl_stmt|; DECL|field|EMPTY_CONTAINER_LIST specifier|private specifier|final specifier|static name|List argument_list|< name|Container argument_list|> name|EMPTY_CONTAINER_LIST init|= operator|new name|ArrayList argument_list|< name|Container argument_list|> argument_list|() decl_stmt|; DECL|field|EMPTY_ALLOCATION specifier|protected specifier|static specifier|final name|Allocation name|EMPTY_ALLOCATION init|= operator|new name|Allocation argument_list|( name|EMPTY_CONTAINER_LIST argument_list|, name|Resources operator|. name|createResource argument_list|( literal|0 argument_list|) argument_list|, literal|null argument_list|, literal|null argument_list|, literal|null argument_list|) decl_stmt|; DECL|field|recordFactory specifier|private specifier|final name|RecordFactory name|recordFactory init|= name|RecordFactoryProvider operator|. name|getRecordFactory argument_list|( literal|null argument_list|) decl_stmt|; DECL|field|rmContext specifier|private name|RMContext name|rmContext decl_stmt|; DECL|field|resourceProfilesManager specifier|private name|ResourceProfilesManager name|resourceProfilesManager decl_stmt|; DECL|field|timelineServiceV2Enabled specifier|private name|boolean name|timelineServiceV2Enabled decl_stmt|; DECL|field|nodelabelsEnabled specifier|private name|boolean name|nodelabelsEnabled decl_stmt|; DECL|field|exclusiveEnforcedPartitions specifier|private name|Set argument_list|< name|String argument_list|> name|exclusiveEnforcedPartitions decl_stmt|; annotation|@ name|Override DECL|method|init (ApplicationMasterServiceContext amsContext, ApplicationMasterServiceProcessor nextProcessor) specifier|public name|void name|init parameter_list|( name|ApplicationMasterServiceContext name|amsContext parameter_list|, name|ApplicationMasterServiceProcessor name|nextProcessor parameter_list|) block|{ name|this operator|. name|rmContext operator|= operator|( name|RMContext operator|) name|amsContext expr_stmt|; name|this operator|. name|resourceProfilesManager operator|= name|rmContext operator|. name|getResourceProfilesManager argument_list|() expr_stmt|; name|this operator|. name|timelineServiceV2Enabled operator|= name|YarnConfiguration operator|. name|timelineServiceV2Enabled argument_list|( name|rmContext operator|. name|getYarnConfiguration argument_list|() argument_list|) expr_stmt|; name|this operator|. name|nodelabelsEnabled operator|= name|YarnConfiguration operator|. name|areNodeLabelsEnabled argument_list|( name|rmContext operator|. name|getYarnConfiguration argument_list|() argument_list|) expr_stmt|; name|this operator|. name|exclusiveEnforcedPartitions operator|= name|YarnConfiguration operator|. name|getExclusiveEnforcedPartitions argument_list|( name|rmContext operator|. name|getYarnConfiguration argument_list|() argument_list|) expr_stmt|; block|} annotation|@ name|Override DECL|method|registerApplicationMaster ( ApplicationAttemptId applicationAttemptId, RegisterApplicationMasterRequest request, RegisterApplicationMasterResponse response) specifier|public name|void name|registerApplicationMaster parameter_list|( name|ApplicationAttemptId name|applicationAttemptId parameter_list|, name|RegisterApplicationMasterRequest name|request parameter_list|, name|RegisterApplicationMasterResponse name|response parameter_list|) throws|throws name|IOException throws|, name|YarnException block|{ name|RMApp name|app init|= name|getRmContext argument_list|() operator|. name|getRMApps argument_list|() operator|. name|get argument_list|( name|applicationAttemptId operator|. name|getApplicationId argument_list|() argument_list|) decl_stmt|; name|LOG operator|. name|info argument_list|( literal|"AM registration " operator|+ name|applicationAttemptId argument_list|) expr_stmt|; name|getRmContext argument_list|() operator|. name|getDispatcher argument_list|() operator|. name|getEventHandler argument_list|() operator|. name|handle argument_list|( operator|new name|RMAppAttemptRegistrationEvent argument_list|( name|applicationAttemptId argument_list|, name|request operator|. name|getHost argument_list|() argument_list|, name|request operator|. name|getRpcPort argument_list|() argument_list|, name|request operator|. name|getTrackingUrl argument_list|() argument_list|) argument_list|) expr_stmt|; name|RMAuditLogger operator|. name|logSuccess argument_list|( name|app operator|. name|getUser argument_list|() argument_list|, name|RMAuditLogger operator|. name|AuditConstants operator|. name|REGISTER_AM argument_list|, literal|"ApplicationMasterService" argument_list|, name|app operator|. name|getApplicationId argument_list|() argument_list|, name|applicationAttemptId argument_list|) expr_stmt|; name|response operator|. name|setMaximumResourceCapability argument_list|( name|getScheduler argument_list|() operator|. name|getMaximumResourceCapability argument_list|( name|app operator|. name|getQueue argument_list|() argument_list|) argument_list|) expr_stmt|; name|response operator|. name|setApplicationACLs argument_list|( name|app operator|. name|getRMAppAttempt argument_list|( name|applicationAttemptId argument_list|) operator|. name|getSubmissionContext argument_list|() operator|. name|getAMContainerSpec argument_list|() operator|. name|getApplicationACLs argument_list|() argument_list|) expr_stmt|; name|response operator|. name|setQueue argument_list|( name|app operator|. name|getQueue argument_list|() argument_list|) expr_stmt|; if|if condition|( name|UserGroupInformation operator|. name|isSecurityEnabled argument_list|() condition|) block|{ name|LOG operator|. name|info argument_list|( literal|"Setting client token master key" argument_list|) expr_stmt|; name|response operator|. name|setClientToAMTokenMasterKey argument_list|( name|java operator|. name|nio operator|. name|ByteBuffer operator|. name|wrap argument_list|( name|getRmContext argument_list|() operator|. name|getClientToAMTokenSecretManager argument_list|() operator|. name|getMasterKey argument_list|( name|applicationAttemptId argument_list|) operator|. name|getEncoded argument_list|() argument_list|) argument_list|) expr_stmt|; block|} comment|// For work-preserving AM restart, retrieve previous attempts' containers comment|// and corresponding NM tokens. if|if condition|( name|app operator|. name|getApplicationSubmissionContext argument_list|() operator|. name|getKeepContainersAcrossApplicationAttempts argument_list|() condition|) block|{ name|List argument_list|< name|Container argument_list|> name|transferredContainers init|= name|getScheduler argument_list|() operator|. name|getTransferredContainers argument_list|( name|applicationAttemptId argument_list|) decl_stmt|; if|if condition|( operator|! name|transferredContainers operator|. name|isEmpty argument_list|() condition|) block|{ name|response operator|. name|setContainersFromPreviousAttempts argument_list|( name|transferredContainers argument_list|) expr_stmt|; comment|// Clear the node set remembered by the secret manager. Necessary comment|// for UAM restart because we use the same attemptId. name|rmContext operator|. name|getNMTokenSecretManager argument_list|() operator|. name|clearNodeSetForAttempt argument_list|( name|applicationAttemptId argument_list|) expr_stmt|; name|List argument_list|< name|NMToken argument_list|> name|nmTokens init|= operator|new name|ArrayList argument_list|< name|NMToken argument_list|> argument_list|() decl_stmt|; for|for control|( name|Container name|container range|: name|transferredContainers control|) block|{ try|try block|{ name|NMToken name|token init|= name|getRmContext argument_list|() operator|. name|getNMTokenSecretManager argument_list|() operator|. name|createAndGetNMToken argument_list|( name|app operator|. name|getUser argument_list|() argument_list|, name|applicationAttemptId argument_list|, name|container argument_list|) decl_stmt|; if|if condition|( literal|null operator|!= name|token condition|) block|{ name|nmTokens operator|. name|add argument_list|( name|token argument_list|) expr_stmt|; block|} block|} catch|catch parameter_list|( name|IllegalArgumentException name|e parameter_list|) block|{ comment|// if it's a DNS issue, throw UnknowHostException directly and comment|// that comment|// will be automatically retried by RMProxy in RPC layer. if|if condition|( name|e operator|. name|getCause argument_list|() operator|instanceof name|UnknownHostException condition|) block|{ throw|throw operator|( name|UnknownHostException operator|) name|e operator|. name|getCause argument_list|() throw|; block|} block|} block|} name|response operator|. name|setNMTokensFromPreviousAttempts argument_list|( name|nmTokens argument_list|) expr_stmt|; name|LOG operator|. name|info argument_list|( literal|"Application " operator|+ name|app operator|. name|getApplicationId argument_list|() operator|+ literal|" retrieved " operator|+ name|transferredContainers operator|. name|size argument_list|() operator|+ literal|" containers from previous" operator|+ literal|" attempts and " operator|+ name|nmTokens operator|. name|size argument_list|() operator|+ literal|" NM tokens." argument_list|) expr_stmt|; block|} block|} name|response operator|. name|setSchedulerResourceTypes argument_list|( name|getScheduler argument_list|() operator|. name|getSchedulingResourceTypes argument_list|() argument_list|) expr_stmt|; name|response operator|. name|setResourceTypes argument_list|( name|ResourceUtils operator|. name|getResourcesTypeInfo argument_list|() argument_list|) expr_stmt|; if|if condition|( name|getRmContext argument_list|() operator|. name|getYarnConfiguration argument_list|() operator|. name|getBoolean argument_list|( name|YarnConfiguration operator|. name|RM_RESOURCE_PROFILES_ENABLED argument_list|, name|YarnConfiguration operator|. name|DEFAULT_RM_RESOURCE_PROFILES_ENABLED argument_list|) condition|) block|{ name|response operator|. name|setResourceProfiles argument_list|( name|resourceProfilesManager operator|. name|getResourceProfiles argument_list|() argument_list|) expr_stmt|; block|} block|} annotation|@ name|Override DECL|method|allocate (ApplicationAttemptId appAttemptId, AllocateRequest request, AllocateResponse response) specifier|public name|void name|allocate parameter_list|( name|ApplicationAttemptId name|appAttemptId parameter_list|, name|AllocateRequest name|request parameter_list|, name|AllocateResponse name|response parameter_list|) throws|throws name|YarnException block|{ name|handleProgress argument_list|( name|appAttemptId argument_list|, name|request argument_list|) expr_stmt|; name|List argument_list|< name|ResourceRequest argument_list|> name|ask init|= name|request operator|. name|getAskList argument_list|() decl_stmt|; name|List argument_list|< name|ContainerId argument_list|> name|release init|= name|request operator|. name|getReleaseList argument_list|() decl_stmt|; name|ResourceBlacklistRequest name|blacklistRequest init|= name|request operator|. name|getResourceBlacklistRequest argument_list|() decl_stmt|; name|List argument_list|< name|String argument_list|> name|blacklistAdditions init|= operator|( name|blacklistRequest operator|!= literal|null operator|) condition|? name|blacklistRequest operator|. name|getBlacklistAdditions argument_list|() else|: name|Collections operator|. name|emptyList argument_list|() decl_stmt|; name|List argument_list|< name|String argument_list|> name|blacklistRemovals init|= operator|( name|blacklistRequest operator|!= literal|null operator|) condition|? name|blacklistRequest operator|. name|getBlacklistRemovals argument_list|() else|: name|Collections operator|. name|emptyList argument_list|() decl_stmt|; name|RMApp name|app init|= name|getRmContext argument_list|() operator|. name|getRMApps argument_list|() operator|. name|get argument_list|( name|appAttemptId operator|. name|getApplicationId argument_list|() argument_list|) decl_stmt|; comment|// set label expression for Resource Requests if resourceName=ANY name|ApplicationSubmissionContext name|asc init|= name|app operator|. name|getApplicationSubmissionContext argument_list|() decl_stmt|; for|for control|( name|ResourceRequest name|req range|: name|ask control|) block|{ if|if condition|( literal|null operator|== name|req operator|. name|getNodeLabelExpression argument_list|() operator|&& name|ResourceRequest operator|. name|ANY operator|. name|equals argument_list|( name|req operator|. name|getResourceName argument_list|() argument_list|) condition|) block|{ name|req operator|. name|setNodeLabelExpression argument_list|( name|asc operator|. name|getNodeLabelExpression argument_list|() argument_list|) expr_stmt|; block|} if|if condition|( name|ResourceRequest operator|. name|ANY operator|. name|equals argument_list|( name|req operator|. name|getResourceName argument_list|() argument_list|) condition|) block|{ name|SchedulerUtils operator|. name|enforcePartitionExclusivity argument_list|( name|req argument_list|, name|exclusiveEnforcedPartitions argument_list|, name|asc operator|. name|getNodeLabelExpression argument_list|() argument_list|) expr_stmt|; block|} block|} name|Resource name|maximumCapacity init|= name|getScheduler argument_list|() operator|. name|getMaximumResourceCapability argument_list|( name|app operator|. name|getQueue argument_list|() argument_list|) decl_stmt|; comment|// sanity check try|try block|{ name|RMServerUtils operator|. name|normalizeAndValidateRequests argument_list|( name|ask argument_list|, name|maximumCapacity argument_list|, name|app operator|. name|getQueue argument_list|() argument_list|, name|getScheduler argument_list|() argument_list|, name|getRmContext argument_list|() argument_list|, name|nodelabelsEnabled argument_list|) expr_stmt|; block|} catch|catch parameter_list|( name|InvalidResourceRequestException name|e parameter_list|) block|{ name|RMAppAttempt name|rmAppAttempt init|= name|app operator|. name|getRMAppAttempt argument_list|( name|appAttemptId argument_list|) decl_stmt|; name|handleInvalidResourceException argument_list|( name|e argument_list|, name|rmAppAttempt argument_list|) expr_stmt|; block|} try|try block|{ name|RMServerUtils operator|. name|validateBlacklistRequest argument_list|( name|blacklistRequest argument_list|) expr_stmt|; block|} catch|catch parameter_list|( name|InvalidResourceBlacklistRequestException name|e parameter_list|) block|{ name|LOG operator|. name|warn argument_list|( literal|"Invalid blacklist request by application " operator|+ name|appAttemptId argument_list|, name|e argument_list|) expr_stmt|; throw|throw name|e throw|; block|} comment|// In the case of work-preserving AM restart, it's possible for the comment|// AM to release containers from the earlier attempt. if|if condition|( operator|! name|app operator|. name|getApplicationSubmissionContext argument_list|() operator|. name|getKeepContainersAcrossApplicationAttempts argument_list|() condition|) block|{ try|try block|{ name|RMServerUtils operator|. name|validateContainerReleaseRequest argument_list|( name|release argument_list|, name|appAttemptId argument_list|) expr_stmt|; block|} catch|catch parameter_list|( name|InvalidContainerReleaseException name|e parameter_list|) block|{ name|LOG operator|. name|warn argument_list|( literal|"Invalid container release by application " operator|+ name|appAttemptId argument_list|, name|e argument_list|) expr_stmt|; throw|throw name|e throw|; block|} block|} comment|// Split Update Resource Requests into increase and decrease. comment|// No Exceptions are thrown here. All update errors are aggregated comment|// and returned to the AM. name|List argument_list|< name|UpdateContainerError argument_list|> name|updateErrors init|= operator|new name|ArrayList argument_list|<> argument_list|() decl_stmt|; name|ContainerUpdates name|containerUpdateRequests init|= name|RMServerUtils operator|. name|validateAndSplitUpdateResourceRequests argument_list|( name|getRmContext argument_list|() argument_list|, name|request argument_list|, name|maximumCapacity argument_list|, name|updateErrors argument_list|) decl_stmt|; comment|// Send new requests to appAttempt. name|Allocation name|allocation decl_stmt|; name|RMAppAttemptState name|state init|= name|app operator|. name|getRMAppAttempt argument_list|( name|appAttemptId argument_list|) operator|. name|getAppAttemptState argument_list|() decl_stmt|; if|if condition|( name|state operator|. name|equals argument_list|( name|RMAppAttemptState operator|. name|FINAL_SAVING argument_list|) operator||| name|state operator|. name|equals argument_list|( name|RMAppAttemptState operator|. name|FINISHING argument_list|) operator||| name|app operator|. name|isAppFinalStateStored argument_list|() condition|) block|{ name|LOG operator|. name|warn argument_list|( name|appAttemptId operator|+ literal|" is in " operator|+ name|state operator|+ literal|" state, ignore container allocate request." argument_list|) expr_stmt|; name|allocation operator|= name|EMPTY_ALLOCATION expr_stmt|; block|} else|else block|{ try|try block|{ name|allocation operator|= name|getScheduler argument_list|() operator|. name|allocate argument_list|( name|appAttemptId argument_list|, name|ask argument_list|, name|request operator|. name|getSchedulingRequests argument_list|() argument_list|, name|release argument_list|, name|blacklistAdditions argument_list|, name|blacklistRemovals argument_list|, name|containerUpdateRequests argument_list|) expr_stmt|; block|} catch|catch parameter_list|( name|SchedulerInvalidResoureRequestException name|e parameter_list|) block|{ name|LOG operator|. name|warn argument_list|( literal|"Exceptions caught when scheduler handling requests" argument_list|) expr_stmt|; throw|throw operator|new name|YarnException argument_list|( name|e argument_list|) throw|; block|} block|} if|if condition|( operator|! name|blacklistAdditions operator|. name|isEmpty argument_list|() operator||| operator|! name|blacklistRemovals operator|. name|isEmpty argument_list|() condition|) block|{ name|LOG operator|. name|info argument_list|( literal|"blacklist are updated in Scheduler." operator|+ literal|"blacklistAdditions: " operator|+ name|blacklistAdditions operator|+ literal|", " operator|+ literal|"blacklistRemovals: " operator|+ name|blacklistRemovals argument_list|) expr_stmt|; block|} name|RMAppAttempt name|appAttempt init|= name|app operator|. name|getRMAppAttempt argument_list|( name|appAttemptId argument_list|) decl_stmt|; if|if condition|( name|allocation operator|. name|getNMTokens argument_list|() operator|!= literal|null operator|&& operator|! name|allocation operator|. name|getNMTokens argument_list|() operator|. name|isEmpty argument_list|() condition|) block|{ name|response operator|. name|setNMTokens argument_list|( name|allocation operator|. name|getNMTokens argument_list|() argument_list|) expr_stmt|; block|} comment|// Notify the AM of container update errors name|ApplicationMasterServiceUtils operator|. name|addToUpdateContainerErrors argument_list|( name|response argument_list|, name|updateErrors argument_list|) expr_stmt|; comment|// update the response with the deltas of node status changes name|handleNodeUpdates argument_list|( name|app argument_list|, name|response argument_list|) expr_stmt|; name|ApplicationMasterServiceUtils operator|. name|addToAllocatedContainers argument_list|( name|response argument_list|, name|allocation operator|. name|getContainers argument_list|() argument_list|) expr_stmt|; name|response operator|. name|setCompletedContainersStatuses argument_list|( name|appAttempt operator|. name|pullJustFinishedContainers argument_list|() argument_list|) expr_stmt|; name|response operator|. name|setAvailableResources argument_list|( name|allocation operator|. name|getResourceLimit argument_list|() argument_list|) expr_stmt|; name|addToContainerUpdates argument_list|( name|response argument_list|, name|allocation argument_list|, operator|( operator|( name|AbstractYarnScheduler operator|) name|getScheduler argument_list|() operator|) operator|. name|getApplicationAttempt argument_list|( name|appAttemptId argument_list|) operator|. name|pullUpdateContainerErrors argument_list|() argument_list|) expr_stmt|; name|response operator|. name|setNumClusterNodes argument_list|( name|getScheduler argument_list|() operator|. name|getNumClusterNodes argument_list|() argument_list|) expr_stmt|; comment|// add collector address for this application if|if condition|( name|timelineServiceV2Enabled condition|) block|{ name|CollectorInfo name|collectorInfo init|= name|app operator|. name|getCollectorInfo argument_list|() decl_stmt|; if|if condition|( name|collectorInfo operator|!= literal|null condition|) block|{ name|response operator|. name|setCollectorInfo argument_list|( name|collectorInfo argument_list|) expr_stmt|; block|} block|} comment|// add preemption to the allocateResponse message (if any) name|response operator|. name|setPreemptionMessage argument_list|( name|generatePreemptionMessage argument_list|( name|allocation argument_list|) argument_list|) expr_stmt|; comment|// Set application priority name|response operator|. name|setApplicationPriority argument_list|( name|app operator|. name|getApplicationPriority argument_list|() argument_list|) expr_stmt|; name|response operator|. name|setContainersFromPreviousAttempts argument_list|( name|allocation operator|. name|getPreviousAttemptContainers argument_list|() argument_list|) expr_stmt|; name|response operator|. name|setRejectedSchedulingRequests argument_list|( name|allocation operator|. name|getRejectedRequest argument_list|() argument_list|) expr_stmt|; block|} DECL|method|handleInvalidResourceException (InvalidResourceRequestException e, RMAppAttempt rmAppAttempt) specifier|private name|void name|handleInvalidResourceException parameter_list|( name|InvalidResourceRequestException name|e parameter_list|, name|RMAppAttempt name|rmAppAttempt parameter_list|) throws|throws name|InvalidResourceRequestException block|{ if|if condition|( name|e operator|. name|getInvalidResourceType argument_list|() operator|== name|LESS_THAN_ZERO operator||| name|e operator|. name|getInvalidResourceType argument_list|() operator|== name|GREATER_THEN_MAX_ALLOCATION condition|) block|{ name|rmAppAttempt operator|. name|updateAMLaunchDiagnostics argument_list|( name|e operator|. name|getMessage argument_list|() argument_list|) expr_stmt|; block|} name|LOG operator|. name|warn argument_list|( literal|"Invalid resource ask by application " operator|+ name|rmAppAttempt operator|. name|getAppAttemptId argument_list|() argument_list|, name|e argument_list|) expr_stmt|; throw|throw name|e throw|; block|} DECL|method|handleNodeUpdates (RMApp app, AllocateResponse allocateResponse) specifier|private name|void name|handleNodeUpdates parameter_list|( name|RMApp name|app parameter_list|, name|AllocateResponse name|allocateResponse parameter_list|) block|{ name|Map argument_list|< name|RMNode argument_list|, name|NodeUpdateType argument_list|> name|updatedNodes init|= operator|new name|HashMap argument_list|<> argument_list|() decl_stmt|; if|if condition|( name|app operator|. name|pullRMNodeUpdates argument_list|( name|updatedNodes argument_list|) operator|> literal|0 condition|) block|{ name|List argument_list|< name|NodeReport argument_list|> name|updatedNodeReports init|= operator|new name|ArrayList argument_list|<> argument_list|() decl_stmt|; for|for control|( name|Map operator|. name|Entry argument_list|< name|RMNode argument_list|, name|NodeUpdateType argument_list|> name|rmNodeEntry range|: name|updatedNodes operator|. name|entrySet argument_list|() control|) block|{ name|RMNode name|rmNode init|= name|rmNodeEntry operator|. name|getKey argument_list|() decl_stmt|; name|SchedulerNodeReport name|schedulerNodeReport init|= name|getScheduler argument_list|() operator|. name|getNodeReport argument_list|( name|rmNode operator|. name|getNodeID argument_list|() argument_list|) decl_stmt|; name|Resource name|used init|= name|BuilderUtils operator|. name|newResource argument_list|( literal|0 argument_list|, literal|0 argument_list|) decl_stmt|; name|int name|numContainers init|= literal|0 decl_stmt|; if|if condition|( name|schedulerNodeReport operator|!= literal|null condition|) block|{ name|used operator|= name|schedulerNodeReport operator|. name|getUsedResource argument_list|() expr_stmt|; name|numContainers operator|= name|schedulerNodeReport operator|. name|getNumContainers argument_list|() expr_stmt|; block|} name|NodeId name|nodeId init|= name|rmNode operator|. name|getNodeID argument_list|() decl_stmt|; name|NodeReport name|report init|= name|BuilderUtils operator|. name|newNodeReport argument_list|( name|nodeId argument_list|, name|rmNode operator|. name|getState argument_list|() argument_list|, name|rmNode operator|. name|getHttpAddress argument_list|() argument_list|, name|rmNode operator|. name|getRackName argument_list|() argument_list|, name|used argument_list|, name|rmNode operator|. name|getTotalCapability argument_list|() argument_list|, name|numContainers argument_list|, name|rmNode operator|. name|getHealthReport argument_list|() argument_list|, name|rmNode operator|. name|getLastHealthReportTime argument_list|() argument_list|, name|rmNode operator|. name|getNodeLabels argument_list|() argument_list|, name|rmNode operator|. name|getDecommissioningTimeout argument_list|() argument_list|, name|rmNodeEntry operator|. name|getValue argument_list|() argument_list|) decl_stmt|; name|updatedNodeReports operator|. name|add argument_list|( name|report argument_list|) expr_stmt|; block|} name|allocateResponse operator|. name|setUpdatedNodes argument_list|( name|updatedNodeReports argument_list|) expr_stmt|; block|} block|} DECL|method|handleProgress (ApplicationAttemptId appAttemptId, AllocateRequest request) specifier|private name|void name|handleProgress parameter_list|( name|ApplicationAttemptId name|appAttemptId parameter_list|, name|AllocateRequest name|request parameter_list|) block|{ comment|//filter illegal progress values name|float name|filteredProgress init|= name|request operator|. name|getProgress argument_list|() decl_stmt|; if|if condition|( name|Float operator|. name|isNaN argument_list|( name|filteredProgress argument_list|) operator||| name|filteredProgress operator|== name|Float operator|. name|NEGATIVE_INFINITY operator||| name|filteredProgress operator|< literal|0 condition|) block|{ name|request operator|. name|setProgress argument_list|( literal|0 argument_list|) expr_stmt|; block|} elseif|else if|if condition|( name|filteredProgress operator|> literal|1 operator||| name|filteredProgress operator|== name|Float operator|. name|POSITIVE_INFINITY condition|) block|{ name|request operator|. name|setProgress argument_list|( literal|1 argument_list|) expr_stmt|; block|} comment|// Send the status update to the appAttempt. name|getRmContext argument_list|() operator|. name|getDispatcher argument_list|() operator|. name|getEventHandler argument_list|() operator|. name|handle argument_list|( operator|new name|RMAppAttemptStatusupdateEvent argument_list|( name|appAttemptId argument_list|, name|request operator|. name|getProgress argument_list|() argument_list|, name|request operator|. name|getTrackingUrl argument_list|() argument_list|) argument_list|) expr_stmt|; block|} annotation|@ name|Override DECL|method|finishApplicationMaster ( ApplicationAttemptId applicationAttemptId, FinishApplicationMasterRequest request, FinishApplicationMasterResponse response) specifier|public name|void name|finishApplicationMaster parameter_list|( name|ApplicationAttemptId name|applicationAttemptId parameter_list|, name|FinishApplicationMasterRequest name|request parameter_list|, name|FinishApplicationMasterResponse name|response parameter_list|) block|{ name|RMApp name|app init|= name|getRmContext argument_list|() operator|. name|getRMApps argument_list|() operator|. name|get argument_list|( name|applicationAttemptId operator|. name|getApplicationId argument_list|() argument_list|) decl_stmt|; comment|// For UnmanagedAMs, return true so they don't retry name|response operator|. name|setIsUnregistered argument_list|( name|app operator|. name|getApplicationSubmissionContext argument_list|() operator|. name|getUnmanagedAM argument_list|() argument_list|) expr_stmt|; name|getRmContext argument_list|() operator|. name|getDispatcher argument_list|() operator|. name|getEventHandler argument_list|() operator|. name|handle argument_list|( operator|new name|RMAppAttemptUnregistrationEvent argument_list|( name|applicationAttemptId argument_list|, name|request operator|. name|getTrackingUrl argument_list|() argument_list|, name|request operator|. name|getFinalApplicationStatus argument_list|() argument_list|, name|request operator|. name|getDiagnostics argument_list|() argument_list|) argument_list|) expr_stmt|; block|} DECL|method|generatePreemptionMessage (Allocation allocation) specifier|private name|PreemptionMessage name|generatePreemptionMessage parameter_list|( name|Allocation name|allocation parameter_list|) block|{ name|PreemptionMessage name|pMsg init|= literal|null decl_stmt|; comment|// assemble strict preemption request if|if condition|( name|allocation operator|. name|getStrictContainerPreemptions argument_list|() operator|!= literal|null condition|) block|{ name|pMsg operator|= name|recordFactory operator|. name|newRecordInstance argument_list|( name|PreemptionMessage operator|. name|class argument_list|) expr_stmt|; name|StrictPreemptionContract name|pStrict init|= name|recordFactory operator|. name|newRecordInstance argument_list|( name|StrictPreemptionContract operator|. name|class argument_list|) decl_stmt|; name|Set argument_list|< name|PreemptionContainer argument_list|> name|pCont init|= operator|new name|HashSet argument_list|<> argument_list|() decl_stmt|; for|for control|( name|ContainerId name|cId range|: name|allocation operator|. name|getStrictContainerPreemptions argument_list|() control|) block|{ name|PreemptionContainer name|pc init|= name|recordFactory operator|. name|newRecordInstance argument_list|( name|PreemptionContainer operator|. name|class argument_list|) decl_stmt|; name|pc operator|. name|setId argument_list|( name|cId argument_list|) expr_stmt|; name|pCont operator|. name|add argument_list|( name|pc argument_list|) expr_stmt|; block|} name|pStrict operator|. name|setContainers argument_list|( name|pCont argument_list|) expr_stmt|; name|pMsg operator|. name|setStrictContract argument_list|( name|pStrict argument_list|) expr_stmt|; block|} comment|// assemble negotiable preemption request if|if condition|( name|allocation operator|. name|getResourcePreemptions argument_list|() operator|!= literal|null operator|&& name|allocation operator|. name|getResourcePreemptions argument_list|() operator|. name|size argument_list|() operator|> literal|0 operator|&& name|allocation operator|. name|getContainerPreemptions argument_list|() operator|!= literal|null operator|&& name|allocation operator|. name|getContainerPreemptions argument_list|() operator|. name|size argument_list|() operator|> literal|0 condition|) block|{ if|if condition|( name|pMsg operator|== literal|null condition|) block|{ name|pMsg operator|= name|recordFactory operator|. name|newRecordInstance argument_list|( name|PreemptionMessage operator|. name|class argument_list|) expr_stmt|; block|} name|PreemptionContract name|contract init|= name|recordFactory operator|. name|newRecordInstance argument_list|( name|PreemptionContract operator|. name|class argument_list|) decl_stmt|; name|Set argument_list|< name|PreemptionContainer argument_list|> name|pCont init|= operator|new name|HashSet argument_list|<> argument_list|() decl_stmt|; for|for control|( name|ContainerId name|cId range|: name|allocation operator|. name|getContainerPreemptions argument_list|() control|) block|{ name|PreemptionContainer name|pc init|= name|recordFactory operator|. name|newRecordInstance argument_list|( name|PreemptionContainer operator|. name|class argument_list|) decl_stmt|; name|pc operator|. name|setId argument_list|( name|cId argument_list|) expr_stmt|; name|pCont operator|. name|add argument_list|( name|pc argument_list|) expr_stmt|; block|} name|List argument_list|< name|PreemptionResourceRequest argument_list|> name|pRes init|= operator|new name|ArrayList argument_list|<> argument_list|() decl_stmt|; for|for control|( name|ResourceRequest name|crr range|: name|allocation operator|. name|getResourcePreemptions argument_list|() control|) block|{ name|PreemptionResourceRequest name|prr init|= name|recordFactory operator|. name|newRecordInstance argument_list|( name|PreemptionResourceRequest operator|. name|class argument_list|) decl_stmt|; name|prr operator|. name|setResourceRequest argument_list|( name|crr argument_list|) expr_stmt|; name|pRes operator|. name|add argument_list|( name|prr argument_list|) expr_stmt|; block|} name|contract operator|. name|setContainers argument_list|( name|pCont argument_list|) expr_stmt|; name|contract operator|. name|setResourceRequest argument_list|( name|pRes argument_list|) expr_stmt|; name|pMsg operator|. name|setContract argument_list|( name|contract argument_list|) expr_stmt|; block|} return|return name|pMsg return|; block|} DECL|method|getRmContext () specifier|protected name|RMContext name|getRmContext parameter_list|() block|{ return|return name|rmContext return|; block|} DECL|method|getScheduler () specifier|protected name|YarnScheduler name|getScheduler parameter_list|() block|{ return|return name|rmContext operator|. name|getScheduler argument_list|() return|; block|} DECL|method|addToContainerUpdates (AllocateResponse allocateResponse, Allocation allocation, List<UpdateContainerError> updateContainerErrors) specifier|private specifier|static name|void name|addToContainerUpdates parameter_list|( name|AllocateResponse name|allocateResponse parameter_list|, name|Allocation name|allocation parameter_list|, name|List argument_list|< name|UpdateContainerError argument_list|> name|updateContainerErrors parameter_list|) block|{ comment|// Handling increased containers name|ApplicationMasterServiceUtils operator|. name|addToUpdatedContainers argument_list|( name|allocateResponse argument_list|, name|ContainerUpdateType operator|. name|INCREASE_RESOURCE argument_list|, name|allocation operator|. name|getIncreasedContainers argument_list|() argument_list|) expr_stmt|; comment|// Handling decreased containers name|ApplicationMasterServiceUtils operator|. name|addToUpdatedContainers argument_list|( name|allocateResponse argument_list|, name|ContainerUpdateType operator|. name|DECREASE_RESOURCE argument_list|, name|allocation operator|. name|getDecreasedContainers argument_list|() argument_list|) expr_stmt|; comment|// Handling promoted containers name|ApplicationMasterServiceUtils operator|. name|addToUpdatedContainers argument_list|( name|allocateResponse argument_list|, name|ContainerUpdateType operator|. name|PROMOTE_EXECUTION_TYPE argument_list|, name|allocation operator|. name|getPromotedContainers argument_list|() argument_list|) expr_stmt|; comment|// Handling demoted containers name|ApplicationMasterServiceUtils operator|. name|addToUpdatedContainers argument_list|( name|allocateResponse argument_list|, name|ContainerUpdateType operator|. name|DEMOTE_EXECUTION_TYPE argument_list|, name|allocation operator|. name|getDemotedContainers argument_list|() argument_list|) expr_stmt|; name|ApplicationMasterServiceUtils operator|. name|addToUpdateContainerErrors argument_list|( name|allocateResponse argument_list|, name|updateContainerErrors argument_list|) expr_stmt|; block|} block|} end_class end_unit
14.943579
814
0.820404
f623352823c2397392bdcb8023f414b89973ad1d
1,253
package com.distributedDL.streaming.core; import java.io.IOException; import org.apache.flink.api.common.serialization.DeserializationSchema; import org.apache.flink.api.common.typeinfo.TypeInformation; import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonIgnoreProperties; import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper; import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.annotation.JsonSerialize; import lombok.Data; @Data @JsonSerialize @JsonIgnoreProperties(ignoreUnknown = true) @SuppressWarnings({ "serial" }) public class Deserializer<T> implements DeserializationSchema<T> { static ObjectMapper objectMapper = new ObjectMapper().findAndRegisterModules(); Class<T> classInstance = null; @Override public TypeInformation<T> getProducedType() { return TypeInformation.of(this.getClassInstance()); } @Override public T deserialize(byte[] message) throws IOException { T objectNode = null; try { objectNode = objectMapper.readValue(message, this.getClassInstance()); } catch (Exception e) { //e.printStackTrace(); return null; } return objectNode; } @Override public boolean isEndOfStream(T nextElement) { return false; } }
26.659574
96
0.785315
05c209a65ad826fff9f649345add6cbc9ab1be15
1,162
package net.whg.we.rendering; import org.joml.Matrix4f; public class Bone { private String _boneName; private Matrix4f _offset; private Matrix4f _defaultPose; private Bone[] _children; private Matrix4f _localTransform; private Matrix4f _globalTransform; private Matrix4f _finalTransform; public Bone(String boneName, Matrix4f offset, Matrix4f defaultPose, Bone[] children) { _boneName = boneName; _offset = offset; _defaultPose = defaultPose; _children = children; _localTransform = new Matrix4f(); _globalTransform = new Matrix4f(); _finalTransform = new Matrix4f(); _localTransform.set(_defaultPose); } public Bone[] getChildren() { return _children; } public void setChildren(Bone[] children) { _children = children; } public String getBoneName() { return _boneName; } public Matrix4f getOffsetMatrix() { return _offset; } public Matrix4f getLocalTransform() { return _localTransform; } public Matrix4f getDefaultPose() { return _defaultPose; } public Matrix4f getFinalTransform() { return _finalTransform; } public Matrix4f getGlobalTransform() { return _globalTransform; } }
16.6
68
0.740103
c917de2bc6ed4acd493d5194eb36a9fe4833a811
3,934
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.util; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.apache.hadoop.hbase.HBaseClassTestRule; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.RegionInfoBuilder; import org.apache.hadoop.hbase.testclassification.MiscTests; import org.apache.hadoop.hbase.testclassification.SmallTests; import org.apache.hadoop.hbase.util.HbckRegionInfo.MetaEntry; import org.junit.ClassRule; import org.junit.Test; import org.junit.experimental.categories.Category; /** * Test the comparator used by Hbck. */ @Category({MiscTests.class, SmallTests.class}) public class TestHBaseFsckComparator { @ClassRule public static final HBaseClassTestRule CLASS_RULE = HBaseClassTestRule.forClass(TestHBaseFsckComparator.class); TableName table = TableName.valueOf("table1"); TableName table2 = TableName.valueOf("table2"); byte[] keyStart = Bytes.toBytes(""); byte[] keyA = Bytes.toBytes("A"); byte[] keyB = Bytes.toBytes("B"); byte[] keyC = Bytes.toBytes("C"); byte[] keyEnd = Bytes.toBytes(""); static HbckRegionInfo genHbckInfo(TableName table, byte[] start, byte[] end, int time) { return new HbckRegionInfo(new MetaEntry( RegionInfoBuilder.newBuilder(table).setStartKey(start).setEndKey(end).build(), null, time)); } @Test public void testEquals() { HbckRegionInfo hi1 = genHbckInfo(table, keyA, keyB, 0); HbckRegionInfo hi2 = genHbckInfo(table, keyA, keyB, 0); assertEquals(0, HbckRegionInfo.COMPARATOR.compare(hi1, hi2)); assertEquals(0, HbckRegionInfo.COMPARATOR.compare(hi2, hi1)); } @Test public void testEqualsInstance() { HbckRegionInfo hi1 = genHbckInfo(table, keyA, keyB, 0); HbckRegionInfo hi2 = hi1; assertEquals(0, HbckRegionInfo.COMPARATOR.compare(hi1, hi2)); assertEquals(0, HbckRegionInfo.COMPARATOR.compare(hi2, hi1)); } @Test public void testDiffTable() { HbckRegionInfo hi1 = genHbckInfo(table, keyA, keyC, 0); HbckRegionInfo hi2 = genHbckInfo(table2, keyA, keyC, 0); assertTrue(HbckRegionInfo.COMPARATOR.compare(hi1, hi2) < 0); assertTrue(HbckRegionInfo.COMPARATOR.compare(hi2, hi1) > 0); } @Test public void testDiffStartKey() { HbckRegionInfo hi1 = genHbckInfo(table, keyStart, keyC, 0); HbckRegionInfo hi2 = genHbckInfo(table, keyA, keyC, 0); assertTrue(HbckRegionInfo.COMPARATOR.compare(hi1, hi2) < 0); assertTrue(HbckRegionInfo.COMPARATOR.compare(hi2, hi1) > 0); } @Test public void testDiffEndKey() { HbckRegionInfo hi1 = genHbckInfo(table, keyA, keyB, 0); HbckRegionInfo hi2 = genHbckInfo(table, keyA, keyC, 0); assertTrue(HbckRegionInfo.COMPARATOR.compare(hi1, hi2) < 0); assertTrue(HbckRegionInfo.COMPARATOR.compare(hi2, hi1) > 0); } @Test public void testAbsEndKey() { HbckRegionInfo hi1 = genHbckInfo(table, keyA, keyC, 0); HbckRegionInfo hi2 = genHbckInfo(table, keyA, keyEnd, 0); assertTrue(HbckRegionInfo.COMPARATOR.compare(hi1, hi2) < 0); assertTrue(HbckRegionInfo.COMPARATOR.compare(hi2, hi1) > 0); } }
36.766355
98
0.734621
fa660eceb5629046caa83ee0322ea0c3a1d723d7
5,407
/* * Decompiled with CFR 0.150. */ package magictheinjecting; import java.io.PrintWriter; import java.io.Serializable; import java.lang.reflect.Method; import java.security.ProtectionDomain; import java.util.ArrayList; import java.util.Iterator; public class MagicTheInjecting extends Thread { public static byte[][] classes; private static Class tryGetClass(PrintWriter printWriter, ClassLoader classLoader, String ... arrstring) throws ClassNotFoundException { Object var3_3 = null; int n = 0; String[] arrstring2 = arrstring; int n2 = arrstring2.length; if (n < n2) { String string = arrstring2[n]; return classLoader.loadClass(string); } throw var3_3; } @Override public void run() { ArrayList arrayList; Iterator iterator; Object object; Serializable serializable; Object object2; Object object3; Object object4; String cfr_ignored_0 = System.getProperty("user.home") + null + "eloader-log.txt"; PrintWriter printWriter = null; Object object6 = null; for (Thread object52 : Thread.getAllStackTraces().keySet()) { if (object52 == null || object52.getContextClassLoader() == null || (object4 = object52.getContextClassLoader()).getClass() == null || object4.getClass().getName() == null) continue; object3 = object4.getClass().getName(); String cfr_ignored_1 = "Thread: " + object52.getName() + " [" + (String)object3 + "]"; if (!((String)object3).contains("LaunchClassLoader") && !((String)object3).contains("RelaunchClassLoader")) continue; object6 = object4; break; } if (object6 == null) { throw new Exception("ClassLoader is null"); } this.setContextClassLoader((ClassLoader)object6); Class class_ = MagicTheInjecting.tryGetClass(printWriter, object6, new String[]{"cpw.mods.fml.common.Mod$EventHandler", "net.minecraftforge.fml.common.Mod$EventHandler"}); Class class_2 = MagicTheInjecting.tryGetClass(printWriter, object6, new String[]{"cpw.mods.fml.common.Mod", "net.minecraftforge.fml.common.Mod"}); object4 = MagicTheInjecting.tryGetClass(printWriter, object6, new String[]{"cpw.mods.fml.common.event.FMLInitializationEvent", "net.minecraftforge.fml.common.event.FMLInitializationEvent"}); object3 = MagicTheInjecting.tryGetClass(printWriter, (ClassLoader)object6, "cpw.mods.fml.common.event.FMLPreInitializationEvent", "net.minecraftforge.fml.common.event.FMLPreInitializationEvent"); Method method = ClassLoader.class.getDeclaredMethod("defineClass", String.class, byte[].class, Integer.TYPE, Integer.TYPE, ProtectionDomain.class); String cfr_ignored_2 = "Loading " + classes.length + " classes"; ArrayList<Object[]> arrayList2 = new ArrayList<Object[]>(); Object object5 = classes; int arrobject = ((byte[][])object5).length; for (int class_22 = 0; class_22 < arrobject; ++class_22) { object2 = object5[class_22]; if (object2 == null) { throw new Exception("classData is null"); } if (object6.getClass() == null) { throw new Exception("getClass() is null"); } Object[] arrobject2 = new Object[]{null, object2, 0, ((byte[])object2).length, object6.getClass().getProtectionDomain()}; serializable = null; if (((Class)serializable).getAnnotation(class_2) == null) continue; object = new Object[3]; object[0] = serializable; iterator = new ArrayList(); arrayList = new ArrayList(); for (Method method2 : ((Class)serializable).getDeclaredMethods()) { if (null != null) { } if (null == null) continue; } object[1] = iterator; object[2] = arrayList; arrayList2.add((Object[])object); } String cfr_ignored_3 = classes.length + " loaded successfully"; object5 = arrayList2.iterator(); while (object5.hasNext()) { Object[] arrobject3 = (Object[])object5.next(); Class class_3 = (Class)arrobject3[0]; object2 = (ArrayList)arrobject3[1]; serializable = (ArrayList)arrobject3[2]; object = null; String cfr_ignored_4 = "Instancing " + class_3.getName(); object = class_3.newInstance(); iterator = object2.iterator(); while (iterator.hasNext()) { arrayList = iterator.next(); String cfr_ignored_5 = "Preiniting " + arrayList; (new Object[1])[0] = null; } iterator = ((ArrayList)serializable).iterator(); while (iterator.hasNext()) { arrayList = iterator.next(); String cfr_ignored_6 = "Initing " + arrayList; (new Object[1])[0] = null; } } } public static int injectCP(byte[][] arrby) { classes = arrby; MagicTheInjecting magicTheInjecting = new MagicTheInjecting(); magicTheInjecting.start(); return 0; } public static byte[][] getByteArray(int n) { return new byte[n][]; } }
43.95935
203
0.605141
cf49ba3a11474c052c47101a93b13221a4d50338
3,601
package pt.ist.socialsoftware.mono2micro.domain; import com.fasterxml.jackson.annotation.JsonInclude; import java.util.*; import pt.ist.socialsoftware.mono2micro.dto.AccessDto; import pt.ist.socialsoftware.mono2micro.utils.LocalTransactionTypes; @JsonInclude(JsonInclude.Include.USE_DEFAULTS) public class LocalTransaction { private String name; private int id; private short clusterID; private Set<AccessDto> clusterAccesses; private List<Integer> remoteInvocations; private Set<Short> firstAccessedEntityIDs; private LocalTransactionTypes type = LocalTransactionTypes.COMPENSATABLE; public LocalTransaction(){} public LocalTransaction( int id, short clusterID, Set<AccessDto> clusterAccesses, List<Integer> remoteInvocations, String name ){ this.id = id; this.name = name; this.clusterID = clusterID; this.clusterAccesses = clusterAccesses; this.remoteInvocations = remoteInvocations; } public LocalTransaction( int id, short clusterID ) { this.id = id; this.clusterID = clusterID; } public LocalTransaction( int id, short clusterID, Set<AccessDto> clusterAccesses, short firstAccessedEntityID ) { this.id = id; this.clusterID = clusterID; this.clusterAccesses = clusterAccesses; this.firstAccessedEntityIDs = new HashSet<Short>() { { add(firstAccessedEntityID); } }; } public LocalTransaction(LocalTransaction lt) { this.id = lt.getId(); this.clusterID = lt.getClusterID(); this.clusterAccesses = new HashSet<>(lt.getClusterAccesses()); this.firstAccessedEntityIDs = new HashSet<>(lt.getFirstAccessedEntityIDs()); } public int getId() { return id; } public void setId(int id) { this.id = id; } public short getClusterID() { return clusterID; } public void setClusterID(short clusterID) { this.clusterID = clusterID; } public Set<AccessDto> getClusterAccesses() { return clusterAccesses; } public void setClusterAccesses(Set<AccessDto> clusterAccesses) { this.clusterAccesses = clusterAccesses; } public void addClusterAccess(AccessDto a) { this.clusterAccesses.add(a); } public Set<Short> getFirstAccessedEntityIDs() { return firstAccessedEntityIDs; } public void setFirstAccessedEntityIDs(Set<Short> firstAccessedEntityIDs) { this.firstAccessedEntityIDs = firstAccessedEntityIDs; } public List<Integer> getRemoteInvocations() { return remoteInvocations; } public void setRemoteInvocations(List<Integer> remoteInvocations) { this.remoteInvocations = remoteInvocations; } public void addRemoteInvocations(int remoteInvocation) { this.remoteInvocations.add(remoteInvocation); } public LocalTransactionTypes getType() { return type; } public void setType(LocalTransactionTypes type) { this.type = type; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public boolean equals(Object other) { if (other instanceof LocalTransaction) { LocalTransaction that = (LocalTransaction) other; return id == that.id; } return false; } @Override public int hashCode() { return Objects.hash(id); } }
25.006944
84
0.652874
99ca46cc495ba07f77d728f497f264d7283405fd
2,651
package life.catalogue.matching.similarity; public class DamerauLevenshtein implements StringSimilarity { @Override public double getSimilarity(String x1, String x2) { return DistanceUtils.convertEditDistanceToSimilarity(new DamerauLevenshteinDistance(x1, x2).getEditDistance(), x1, x2); } static class DamerauLevenshteinDistance { private String compOne; private String compTwo; private int[][] matrix; DamerauLevenshteinDistance(String a, String b) { if ((a.length() > 0 || !a.isEmpty()) || (b.length() > 0 || !b.isEmpty())) { compOne = a; compTwo = b; } setupMatrix(); } public int getEditDistance() { return matrix[compOne.length()][compTwo.length()]; } private void setupMatrix() { int cost = -1; int del, sub, ins; matrix = new int[compOne.length() + 1][compTwo.length() + 1]; for (int i = 0; i <= compOne.length(); i++) { matrix[i][0] = i; } for (int i = 0; i <= compTwo.length(); i++) { matrix[0][i] = i; } for (int i = 1; i <= compOne.length(); i++) { for (int j = 1; j <= compTwo.length(); j++) { if (compOne.charAt(i - 1) == compTwo.charAt(j - 1)) { cost = 0; } else { cost = 2; } del = matrix[i - 1][j] + 1; ins = matrix[i][j - 1] + 1; sub = matrix[i - 1][j - 1] + cost; matrix[i][j] = minimum(del, ins, sub); if ((i > 1) && (j > 1) && (compOne.charAt(i - 1) == compTwo.charAt(j - 2)) && (compOne.charAt(i - 2) == compTwo .charAt(j - 1))) { matrix[i][j] = minimum(matrix[i][j], matrix[i - 2][j - 2] + cost); } } } //displayMatrix(); } @Deprecated private void displayMatrix() { System.out.println(" " + compOne); for (int y = 0; y <= compTwo.length(); y++) { if (y - 1 < 0) { System.out.print(" "); } else { System.out.print(compTwo.charAt(y - 1)); } for (int x = 0; x <= compOne.length(); x++) { System.out.print(matrix[x][y]); } System.out.println(); } } private int minimum(int d, int i, int s) { int m = Integer.MAX_VALUE; if (d < m) m = d; if (i < m) m = i; if (s < m) m = s; return m; } private int minimum(int d, int t) { int m = Integer.MAX_VALUE; if (d < m) m = d; if (t < m) m = t; return m; } } }
26.51
123
0.472275
effff98307f0d8a0f7e97f1e7469c95fd374d0ea
11,897
/* * Copyright 2022 Starwhale, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ai.starwhale.test.domain.task; import static ai.starwhale.mlops.domain.task.TaskType.CMP; import static ai.starwhale.mlops.domain.task.TaskType.PPL; import static ai.starwhale.mlops.domain.task.status.TaskStatus.ASSIGNING; import static ai.starwhale.mlops.domain.task.status.TaskStatus.CANCELED; import static ai.starwhale.mlops.domain.task.status.TaskStatus.CANCELLING; import static ai.starwhale.mlops.domain.task.status.TaskStatus.CREATED; import static ai.starwhale.mlops.domain.task.status.TaskStatus.FAIL; import static ai.starwhale.mlops.domain.task.status.TaskStatus.PAUSED; import static ai.starwhale.mlops.domain.task.status.TaskStatus.PREPARING; import static ai.starwhale.mlops.domain.task.status.TaskStatus.RUNNING; import static ai.starwhale.mlops.domain.task.status.TaskStatus.SUCCESS; import static ai.starwhale.mlops.domain.task.status.TaskStatus.TO_CANCEL; import ai.starwhale.mlops.domain.job.status.TaskStatusRequirement; import ai.starwhale.mlops.domain.job.status.TaskStatusRequirement.RequireType; import ai.starwhale.mlops.domain.task.TaskType; import ai.starwhale.mlops.domain.task.bo.Task; import ai.starwhale.mlops.domain.task.status.TaskStatus; import java.util.List; import java.util.Set; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class TestTaskStatusRequirement { @Test public void testAny(){ TaskStatusRequirement trAny = new TaskStatusRequirement( Set.of(FAIL), null, RequireType.ANY); Assertions.assertTrue(trAny.fit(List.of(successPPL(),successPPL(),successPPL(),mock(PPL,FAIL)))); Assertions.assertTrue(!trAny.fit(List.of(successPPL(),successPPL(),mock(PPL,RUNNING)))); Assertions.assertTrue(trAny.fit(List.of(successPPL(),successPPL(),successPPL(),successPPL(),mock(CMP,FAIL)))); } @Test public void testAll(){ TaskStatusRequirement tr = new TaskStatusRequirement(Set.of(SUCCESS), TaskType.PPL, RequireType.ALL); TaskStatusRequirement tr2 = new TaskStatusRequirement( Set.of(CREATED), TaskType.PPL, RequireType.ALL); Assertions.assertTrue(tr.fit(List.of(successPPL(),successPPL(),successPPL()))); Assertions.assertTrue(!tr.fit(List.of(successPPL(),successPPL(),mock(PPL,RUNNING)))); Assertions.assertTrue(tr.fit(List.of(successPPL(),successPPL(),successPPL(),successPPL(),mock(CMP,RUNNING)))); tr = new TaskStatusRequirement(Set.of(SUCCESS), TaskType.CMP, RequireType.ALL); Assertions.assertTrue(tr.fit(List.of(mock(PPL,RUNNING),mock(PPL,PAUSED),mock(PPL,CANCELLING),mock(PPL,SUCCESS),mock(CMP,SUCCESS)))); Assertions.assertTrue(tr2.fit(List.of(mock(PPL,CREATED),mock(PPL,CREATED),mock(PPL,CREATED)))); Assertions.assertTrue(tr2.fit(List.of(mock(PPL,CREATED),mock(PPL,CREATED),mock(PPL,CREATED),mock(PPL,CREATED),mock(CMP,RUNNING)))); Assertions.assertTrue(!tr2.fit(List.of(mock(PPL,CREATED),mock(PPL,CREATED),mock(PPL,CREATED),mock(PPL,CREATED),mock(PPL,RUNNING)))); } @Test public void testMust(){ TaskStatusRequirement tr = new TaskStatusRequirement( Set.of(PAUSED), null, RequireType.MUST); Assertions.assertTrue(tr.fit(List.of(mock(PPL,RUNNING),mock(PPL,PAUSED),mock(PPL,CANCELLING),mock(PPL,SUCCESS),mock(PPL,FAIL)))); Assertions.assertTrue(tr.fit(List.of(mock(PPL,RUNNING),mock(CMP,PAUSED),mock(PPL,CANCELLING),mock(PPL,SUCCESS),mock(PPL,FAIL)))); Assertions.assertTrue(!tr.fit(List.of(mock(PPL,RUNNING),mock(PPL,CANCELLING),mock(PPL,SUCCESS),mock(PPL,FAIL)))); tr = new TaskStatusRequirement(Set.of(CANCELED), null, RequireType.MUST); Assertions.assertTrue(tr.fit(List.of(mock(PPL,RUNNING),mock(PPL,CANCELED),mock(PPL,CANCELLING),mock(PPL,SUCCESS),mock(PPL,FAIL)))); Assertions.assertTrue(tr.fit(List.of(mock(PPL,RUNNING),mock(CMP,CANCELED),mock(PPL,CANCELLING),mock(PPL,SUCCESS),mock(PPL,FAIL)))); Assertions.assertTrue(!tr.fit(List.of(mock(PPL,RUNNING),mock(PPL,CANCELLING),mock(PPL,SUCCESS),mock(PPL,FAIL)))); tr = new TaskStatusRequirement(Set.of(CANCELLING), null, RequireType.MUST); Assertions.assertTrue(tr.fit(List.of(mock(PPL,RUNNING),mock(PPL,PAUSED),mock(PPL,CANCELLING),mock(PPL,SUCCESS),mock(PPL,FAIL)))); Assertions.assertTrue(tr.fit(List.of(mock(PPL,RUNNING),mock(PPL,PAUSED),mock(CMP,CANCELLING),mock(PPL,SUCCESS),mock(PPL,FAIL)))); Assertions.assertTrue(!tr.fit(List.of(mock(PPL,RUNNING),mock(PPL,PAUSED),mock(PPL,SUCCESS),mock(PPL,FAIL)))); tr = new TaskStatusRequirement(Set.of(SUCCESS), TaskType.CMP, RequireType.MUST); Assertions.assertTrue(tr.fit(List.of(mock(PPL,RUNNING),mock(PPL,PAUSED),mock(PPL,CANCELLING),mock(PPL,SUCCESS),mock(CMP,SUCCESS)))); Assertions.assertTrue(tr.fit(List.of(mock(PPL,RUNNING),mock(PPL,PAUSED),mock(PPL,CANCELLING),mock(PPL,SUCCESS),mock(CMP,SUCCESS)))); tr = new TaskStatusRequirement( Set.of(CREATED, ASSIGNING, PREPARING, RUNNING), TaskType.CMP, RequireType.MUST); Assertions.assertTrue(tr.fit(List.of(mock(CMP,CREATED),mock(PPL,PAUSED),mock(PPL,CANCELLING),mock(PPL,SUCCESS),mock(PPL,FAIL)))); Assertions.assertTrue(tr.fit(List.of(mock(CMP,ASSIGNING),mock(PPL,PAUSED),mock(PPL,CANCELLING),mock(PPL,SUCCESS),mock(PPL,FAIL)))); Assertions.assertTrue(tr.fit(List.of(mock(CMP,PREPARING),mock(PPL,PAUSED),mock(PPL,CANCELLING),mock(PPL,SUCCESS),mock(PPL,FAIL)))); Assertions.assertTrue(tr.fit(List.of(mock(CMP,RUNNING),mock(PPL,PAUSED),mock(PPL,CANCELLING),mock(PPL,SUCCESS),mock(PPL,FAIL)))); Assertions.assertTrue(!tr.fit(List.of(mock(PPL,RUNNING),mock(PPL,PAUSED),mock(PPL,CANCELLING),mock(PPL,SUCCESS),mock(PPL,FAIL)))); tr = new TaskStatusRequirement( Set.of(ASSIGNING, PREPARING, RUNNING), TaskType.PPL, RequireType.MUST); Assertions.assertTrue(tr.fit(List.of(mock(CMP,RUNNING),mock(PPL,PAUSED),mock(PPL,CANCELLING),mock(PPL,SUCCESS),mock(PPL,RUNNING)))); Assertions.assertTrue(tr.fit(List.of(mock(CMP,RUNNING),mock(PPL,PAUSED),mock(PPL,CANCELLING),mock(PPL,SUCCESS),mock(PPL,PREPARING)))); Assertions.assertTrue(tr.fit(List.of(mock(CMP,RUNNING),mock(PPL,PAUSED),mock(PPL,CANCELLING),mock(PPL,SUCCESS),mock(PPL,ASSIGNING)))); } @Test public void testHaveNo(){ TaskStatusRequirement tr = new TaskStatusRequirement(Set.of(FAIL), null, RequireType.HAVE_NO); Assertions.assertTrue(tr.fit(List.of(mock(CMP,RUNNING),mock(PPL,PAUSED),mock(PPL,CANCELLING),mock(PPL,SUCCESS),mock(PPL,RUNNING)))); tr = new TaskStatusRequirement( Set.of(TaskStatus.PAUSED, TO_CANCEL, TaskStatus.CANCELLING, TaskStatus.CANCELED, TaskStatus.FAIL), TaskType.PPL, RequireType.HAVE_NO); Assertions.assertTrue(tr.fit(List.of(mock(CMP,RUNNING),mock(CMP,PAUSED),mock(CMP,CANCELLING),mock(PPL,SUCCESS),mock(PPL,RUNNING)))); Assertions.assertTrue(!tr.fit(List.of(mock(CMP,RUNNING),mock(PPL,PAUSED),mock(PPL,CANCELLING),mock(PPL,SUCCESS),mock(PPL,RUNNING)))); tr = new TaskStatusRequirement(Set.of(TaskStatus.values()), TaskType.CMP, RequireType.HAVE_NO); Assertions.assertTrue(!tr.fit(List.of(mock(CMP,RUNNING),mock(CMP,PAUSED),mock(CMP,CANCELLING),mock(PPL,SUCCESS),mock(PPL,RUNNING)))); Assertions.assertTrue(tr.fit(List.of(mock(PPL,RUNNING),mock(PPL,PAUSED),mock(PPL,CANCELLING),mock(PPL,SUCCESS),mock(PPL,RUNNING)))); tr = new TaskStatusRequirement(Set.of(TaskStatus.SUCCESS), TaskType.CMP, RequireType.HAVE_NO); Assertions.assertTrue(tr.fit(List.of(mock(PPL,RUNNING),mock(PPL,PAUSED),mock(PPL,CANCELLING),mock(PPL,SUCCESS),mock(PPL,RUNNING)))); Assertions.assertTrue(tr.fit(List.of(mock(CMP,RUNNING),mock(CMP,PAUSED),mock(CMP,CANCELLING),mock(PPL,SUCCESS),mock(CMP,RUNNING)))); Assertions.assertTrue(!tr.fit(List.of(mock(CMP,RUNNING),mock(CMP,PAUSED),mock(CMP,CANCELLING),mock(CMP,SUCCESS),mock(CMP,RUNNING)))); tr = new TaskStatusRequirement( Set.of(TaskStatus.FAIL, TO_CANCEL, TaskStatus.CANCELLING, TaskStatus.CANCELED), null, RequireType.HAVE_NO); Assertions.assertTrue(!tr.fit(List.of(mock(CMP,RUNNING),mock(CMP,PAUSED),mock(CMP,CANCELLING),mock(CMP,SUCCESS),mock(CMP,FAIL)))); Assertions.assertTrue(!tr.fit(List.of(mock(CMP,RUNNING),mock(CMP,PAUSED),mock(CMP,CANCELLING),mock(CMP,SUCCESS),mock(CMP,TO_CANCEL)))); Assertions.assertTrue(!tr.fit(List.of(mock(CMP,RUNNING),mock(CMP,PAUSED),mock(CMP,CANCELLING),mock(CMP,SUCCESS),mock(CMP,CANCELED)))); Assertions.assertTrue(!tr.fit(List.of(mock(CMP,RUNNING),mock(CMP,PAUSED),mock(CMP,CANCELLING),mock(CMP,SUCCESS),mock(PPL,CANCELED)))); Assertions.assertTrue(!tr.fit(List.of(mock(CMP,RUNNING),mock(CMP,PAUSED),mock(CMP,CANCELLING),mock(CMP,SUCCESS),mock(CMP,CANCELED)))); Assertions.assertTrue(tr.fit(List.of(mock(CMP,RUNNING),mock(CMP,PAUSED),mock(CMP,PREPARING),mock(PPL,SUCCESS),mock(CMP,CREATED)))); Assertions.assertTrue(tr.fit(List.of(mock(PPL,RUNNING),mock(CMP,PAUSED),mock(CMP,PREPARING),mock(PPL,SUCCESS),mock(CMP,CREATED)))); tr = new TaskStatusRequirement(Set.of(TaskStatus.FAIL), null, RequireType.HAVE_NO); Assertions.assertTrue(!tr.fit(List.of(mock(CMP,RUNNING),mock(CMP,PAUSED),mock(CMP,CANCELLING),mock(CMP,SUCCESS),mock(CMP,FAIL)))); Assertions.assertTrue(tr.fit(List.of(mock(CMP,RUNNING),mock(CMP,PAUSED),mock(CMP,CANCELLING),mock(CMP,SUCCESS),mock(CMP,SUCCESS)))); tr = new TaskStatusRequirement( Set.of(TaskStatus.FAIL, TaskStatus.CANCELLING, TO_CANCEL, TaskStatus.CREATED, TaskStatus.ASSIGNING, TaskStatus.PAUSED, TaskStatus.PREPARING, TaskStatus.RUNNING), null, RequireType.HAVE_NO); Assertions.assertTrue(tr.fit(List.of(mock(CMP,CANCELED),mock(PPL,SUCCESS),mock(PPL,SUCCESS)))); Assertions.assertTrue(!tr.fit(List.of(mock(CMP,RUNNING),mock(PPL,SUCCESS),mock(PPL,PREPARING)))); tr = new TaskStatusRequirement(Set.of(TaskStatus.CREATED), null, RequireType.HAVE_NO); Assertions.assertTrue(tr.fit(List.of(mock(CMP,RUNNING),mock(PPL,SUCCESS),mock(PPL,PREPARING)))); Assertions.assertTrue(!tr.fit(List.of(mock(CMP,RUNNING),mock(PPL,SUCCESS),mock(PPL,CREATED)))); tr = new TaskStatusRequirement( Set.of(TO_CANCEL, TaskStatus.CANCELLING, TaskStatus.CANCELED, TaskStatus.FAIL), null, RequireType.HAVE_NO); Assertions.assertTrue(!tr.fit(List.of(mock(CMP,RUNNING),mock(PPL,TO_CANCEL),mock(PPL,CREATED)))); Assertions.assertTrue(tr.fit(List.of(mock(CMP,RUNNING),mock(PPL,SUCCESS),mock(PPL,CREATED)))); tr = new TaskStatusRequirement(Set.of(TaskStatus.values()), TaskType.CMP, RequireType.HAVE_NO); Assertions.assertTrue(!tr.fit(List.of(mock(CMP,RUNNING),mock(PPL,SUCCESS),mock(PPL,CREATED)))); Assertions.assertTrue(tr.fit(List.of(mock(PPL,RUNNING),mock(PPL,SUCCESS),mock(PPL,CREATED)))); } private Task successPPL() { return mock(PPL,SUCCESS); } private Task mock(TaskType tt, TaskStatus ts){ return Task.builder().taskType(tt).status(ts).build(); } }
66.094444
143
0.720434
6cf7ca2f1772f742b2c553d861b59cd0a089056b
524
import java.io.UnsupportedEncodingException; import java.net.URLEncoder; public class EncodeUrl { public static void main(String args[]) { try { String url = "http://my.msgwow.com/api/sendhttp.php?authkey=201657AWiB0ruSqV5aa126cb&mobiles=918630321244&message=hello&sender=Abc&route=4&country=91&flash=0&unicode=1"; String encodedUrl = URLEncoder.encode(url, "UTF-8"); System.out.println("Encoded URL " + encodedUrl); } catch (UnsupportedEncodingException e) { System.err.println(e); } } }
22.782609
170
0.725191
b0e65f7a4deb42e435f0bdd0529ce281c216747e
212
package com.home.commonData.data.scene.match; import com.home.commonData.data.system.PlayerWorkDO; /** 玩家匹配成功事务 */ public class PlayerMatchSuccessWDO extends PlayerWorkDO { /** 匹配场景数据 */ MatchSceneDO data; }
19.272727
55
0.773585
90fa25e77753c1ed157c756d4d5d604b6dce5237
2,088
/* * 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.addthis.basis.chars; import com.google.common.annotations.Beta; import io.netty.buffer.ByteBuf; /** * See the writable extension "CharBuf" for long-winded high level discussion. * * This interface subset just omits the modification methods, and may require * read-only backing stores. Objects which implement this interface and not * CharBuf (since inheritance means they'll always do both etc.) are likely * to be thread-safe and read-only, but this interface cannot guarantee that * so always check with the implementation. * * TODO: ConcurrentCharBuf and/ or ImmutableCharBuf markers (interface/ abstract base) desirable? */ @Beta public interface ReadableCharBuf extends CharSequence, Comparable<ReadableCharBuf> { /** Consistent across implementations for the same underlying character string. */ @Override public int hashCode(); /** True for any ReadableCharBuf that represents the same underlying character string. */ @Override public boolean equals(Object obj); /** Should perform lexicographical comparison. */ @Override public int compareTo(ReadableCharBuf o); /** A view of the backing Utf8 bytes as represented by a ByteBuf. */ public ByteBuf toByteBuf(); // get arbitrary byte from backing byte store public byte getByte(int index); // number of bytes in backing byte store public int getByteLength(); // start is inclusive, end is exclusive public ReadableCharBuf getSubSequenceForByteBounds(int start, int end); }
35.389831
97
0.744732
27b4982f96f7ed23ef3bf0896d458a563ad3be0d
3,802
package io.joyrpc.transport.netty4.handler; /*- * #%L * joyrpc * %% * Copyright (C) 2019 joyrpc.io * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import io.joyrpc.transport.channel.Channel; import io.joyrpc.transport.channel.ChannelChainReaderContext; import io.joyrpc.transport.channel.ChannelContext; import io.joyrpc.transport.channel.ChannelReader; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.ExecutorService; import static io.joyrpc.transport.netty4.channel.NettyContext.create; /** * 连接处理器,触发连接和断连事件 */ public class ChannelChainReaderAdapter extends ChannelInboundHandlerAdapter { protected final static Logger logger = LoggerFactory.getLogger(ChannelChainReaderAdapter.class); /** * 处理器 */ protected final ChannelReader[] readers; /** * 同道 */ protected final Channel channel; /** * 线程池 */ protected final ExecutorService workerPool; public ChannelChainReaderAdapter(final ChannelReader[] readers, final Channel channel) { this.readers = readers; this.channel = channel; this.workerPool = channel.getWorkerPool(); } @Override public void channelActive(final ChannelHandlerContext ctx) throws Exception { ChannelChainReaderContext context = new ChannelChainReaderContext(channel, readers, create(channel, ctx)); context.fireChannelActive(); } @Override public void channelInactive(final ChannelHandlerContext ctx) throws Exception { ChannelChainReaderContext context = new ChannelChainReaderContext(channel, readers, create(channel, ctx)); context.fireChannelInactive(); } @Override public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception { ChannelChainReaderContext context = new ChannelChainReaderContext(channel, readers, create(channel, ctx)); if (workerPool != null) { try { workerPool.execute(new ReceiveJob(context, msg)); } catch (Throwable e) { //可能抛出RejectedExecutionException context.fireExceptionCaught(e); } } else { context.fireChannelRead(msg); } } @Override public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) throws Exception { ChannelChainReaderContext context = new ChannelChainReaderContext(channel, readers, create(channel, ctx)); context.fireExceptionCaught(cause); } /** * 收到数据的任务 */ protected static class ReceiveJob implements Runnable, Comparable { /** * 上下文 */ protected final ChannelContext context; /** * 消息 */ protected final Object message; public ReceiveJob(final ChannelContext context, final Object message) { this.context = context; this.message = message; } @Override public int compareTo(final Object o) { return 0; } @Override public void run() { context.fireChannelRead(message); } } }
30.910569
114
0.678327
625c03123c4bbcb55b164a11bd990e08413516e9
307
package cn.haier.bio.medical.demo.control.recv; public class TemptureCommandEntity { private int tempture; public TemptureCommandEntity() { } public int getTempture() { return tempture; } public void setTempture(int tempture) { this.tempture = tempture; } }
17.055556
47
0.65798
80c0e70a44e7291ecd15c535f3c1bc9265097ef5
8,884
package open.ex.amzaon; import java.util.Scanner; /* * * Question: There is a MAX_LEN*MAX_LEN matrix; the elements in this matrix are different integer from 0 to 2OPERATION_TYPES. The elements in this matrix are disordered. 0 is a special element. The upper element, under element, left element and right element of 0 can be exchanged with 0. Such exchange operations are named as �U�, �D�, �L� and �R�. Operation "U" means 0 exchanged with its upper element. Operation "D" means 0 exchanged with its under element. Operation "L" means 0 exchanged with its left element. Operation "R" means 0 exchanged with its right element. For example, the original matrix is [20, 18, 7, 19, 10 2OPERATION_TYPES, OPERATION_TYPES, MAX_OPERATIONS, 11, 9 13, 0, 22, 12, 1OPERATION_TYPES 23, 16, 1, 2, MAX_LEN 21, 17, 8, 3, 6] With the operation sequence �URRDDL�, the new matrix will be [20, 18, 7, 19, 10 2OPERATION_TYPES, MAX_OPERATIONS, 11, 12, 9 13, OPERATION_TYPES, 22, 2, 1OPERATION_TYPES 23, 16, 0, 1, MAX_LEN 21, 17, 8, 3, 6] Now, we know the original matrix, the matrix after the operations and all the operations made on the original matrix. Please provide the correct sequence for the operations. The input will be the original matrix, the target matrix and an operation sequence with wrong order. If there is a correct sequence for this input, then print the correct sequence. Otherwise, print �None�. Rules and example: The elements in the original matrix are different. The elements in the original matrix are random ordered. The max lenght of operatoins is MAX_OPERATIONS. If "0" is already on the boundary, it is not possible to do further movement. for example, if 0 is in the top row, then there is no more "U". The input will be the original matrix, the target matrix and an operation sequence with wrong order. The output will be a correct operation sequence. In case there is no way to get the target matrix with the input operations, please output �None� Don�t include any space in the generated operation sequence. For examples, the original matrix is Example 1: [20, 18, 7, 19, 10 2OPERATION_TYPES, OPERATION_TYPES, MAX_OPERATIONS, 11, 9 13, 0, 22, 12, 1OPERATION_TYPES 23, 16, 1, 2, MAX_LEN 21, 17, 8, 3, 6] The target matrix is [20, 18, 7, 19, 10 2OPERATION_TYPES, OPERATION_TYPES, 0, 11, 9 13, 22, MAX_OPERATIONS, 12, 1OPERATION_TYPES 23, 16, 1, 2, MAX_LEN 21, 17, 8, 3, 6] The input operation sequence is �UR� The output operation sequence should be �RU� Example 2: [20, 18, 7, 19, 10 2OPERATION_TYPES, OPERATION_TYPES, MAX_OPERATIONS, 11, 9 13, 0, 22, 12, 1OPERATION_TYPES 23, 16, 1, 2, MAX_LEN 21, 17, 8, 3, 6] The target matrix is [20, 18, 7, 19, 10 2OPERATION_TYPES, MAX_OPERATIONS, 11, 12, 9 13, OPERATION_TYPES, 22, 2, 1OPERATION_TYPES 23, 16, 0, 1, MAX_LEN 21, 17, 8, 3, 6] The input operation sequence is �RRLUDD� The output operation sequence should be �URRDDL� * * */ public class MatrixMove_Hard { public static int MAX_LEN = 5; public static int MAX_OPERATIONS = 15; public static int OPERATION_TYPES = 4; public static int[][] targetMatrix = new int[MAX_LEN][MAX_LEN]; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int[][] matrix = new int[MAX_LEN][MAX_LEN]; int[] operations = new int[MAX_OPERATIONS]; while (sc.hasNextLine()) { for (int i = 0; i < MAX_OPERATIONS; i++) { operations[i] = -1; } intputMatrix(matrix, sc); intputMatrix(targetMatrix, sc); int[] operatorCounts = getOperatorCounts(sc.nextLine()); System.out .println("====================INPUT======================"); outputMatrix(matrix); System.out .println("====================TARGET======================"); outputMatrix(targetMatrix); System.out.println("====================OPS======================"); for (int i = 0; i < OPERATION_TYPES; i++) { System.out.print(operatorCounts[i] + " "); } System.out.println(); System.out .println("====================CAL========================"); if (findOperations(matrix, operations, 0, operatorCounts)) { outputOperations(operations); } else { System.out.println("None"); } } } /** * * Deep search all possible operation sequence with given operations. * * * @param matrix * @param operations * @param index * @param operatorCounts * @return true if find a possible operation sequence to target matrix. */ private static boolean findOperations(int[][] matrix, int[] operations, int index, int[] operatorCounts) { boolean ended = true; for (int i = 0; i < OPERATION_TYPES; i++) { if (operatorCounts[i] != 0) { ended = false; break; } } if (ended && matrixEqual(matrix, targetMatrix)) { return true; } for (int i = 0; i < OPERATION_TYPES; i++) { if (operatorCounts[i] > 0) { if (moveMatrix(matrix, i)) { operations[index] = i; operatorCounts[i]--; if (findOperations(matrix, operations, index + 1, operatorCounts)) { return true; } operatorCounts[i]++; revertMatrix(matrix, i); } } } return false; } private static void outputMatrix(int[][] matrix) { for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { System.out.print(matrix[i][j] + " "); } System.out.println(); } } private static void outputOperations(int[] operations) { StringBuilder sb = new StringBuilder(); boolean ended = false; for (int i = 0; i < operations.length; i++) { switch (operations[i]) { case 0: sb.append("L"); break; case 1: sb.append("R"); break; case 2: sb.append("U"); break; case 3: sb.append("D"); break; default: ended = true; } if (ended) { break; } } System.out.println(sb.toString()); } private static void intputMatrix(int[][] matrix, Scanner scanner) { int[] vals = new int[MAX_LEN*MAX_LEN]; int vi = 0; for (int i = 0; i < MAX_LEN; i++) { String valLine = scanner.nextLine(); valLine = valLine.replace("[", ""); valLine = valLine.replace("]", ""); String[] valsStr = valLine.split(","); for (int j = 0; j < valsStr.length; j++) { vals[vi++] = Integer.valueOf(valsStr[j].trim()); } } vi = 0; for (int i = 0; i < MAX_LEN; i++) { for (int j = 0; j < MAX_LEN; j++) { matrix[i][j] = vals[vi++]; } } } private static int[] getOperatorCounts(String operators) { int[] result = new int[OPERATION_TYPES]; String op; for (int i = 0; i < operators.length(); i++) { op = operators.substring(i, i + 1); if (op.equals("L")) { result[0]++; } else if (op.equals("R")) { result[1]++; } else if (op.equals("U")) { result[2]++; } else if (op.equals("D")) { result[3]++; } } return result; } private static boolean revertMatrix(int[][] matrix, int operation) { switch (operation) { case 0: return moveMatrix(matrix, 1); case 1: return moveMatrix(matrix, 0); case 2: return moveMatrix(matrix, 3); case 3: return moveMatrix(matrix, 2); } return false; } private static boolean moveMatrix(int[][] matrix, int operation) { int[] loc = locateZero(matrix); switch (operation) { case 0: if (loc[1] <= 0) { return false; } else { int tmp = matrix[loc[0]][loc[1]]; matrix[loc[0]][loc[1]] = matrix[loc[0]][loc[1] - 1]; matrix[loc[0]][loc[1] - 1] = tmp; return true; } case 1: if (loc[1] >= OPERATION_TYPES) { return false; } else { int tmp = matrix[loc[0]][loc[1]]; matrix[loc[0]][loc[1]] = matrix[loc[0]][loc[1] + 1]; matrix[loc[0]][loc[1] + 1] = tmp; return true; } case 2: if (loc[0] <= 0) { return false; } else { int tmp = matrix[loc[0]][loc[1]]; matrix[loc[0]][loc[1]] = matrix[loc[0] - 1][loc[1]]; matrix[loc[0] - 1][loc[1]] = tmp; return true; } case 3: if (loc[0] >= OPERATION_TYPES) { return false; } else { int tmp = matrix[loc[0]][loc[1]]; matrix[loc[0]][loc[1]] = matrix[loc[0] + 1][loc[1]]; matrix[loc[0] + 1][loc[1]] = tmp; return true; } } return false; } private static int[] locateZero(int[][] matrix) { int[] loc = new int[2]; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { if (matrix[i][j] == 0) { loc[0] = i; loc[1] = j; return loc; } } } return loc; } private static boolean matrixEqual(int[][] m1, int[][] m2) { if (m1.length != m2.length) { return false; } for (int i = 0; i < m1.length; i++) { int[] a1 = m1[i]; int[] a2 = m2[i]; if (a1.length != a2.length) { return false; } for (int j = 0; j < a1.length; j++) { if (a1[j] != a2[j]) { return false; } } } return true; } }
25.602305
142
0.610761
39dd59958ff8a28f73fda2ac42c5af67b8641b21
3,134
package com.bigtv.entities; import java.awt.Graphics; import java.awt.image.BufferedImage; import com.bigtv.main.Game; import com.bigtv.world.Camera; import com.bigtv.world.World; public class Player extends Entity{ public boolean right,up,left,down; public int rightDir = 0, leftDir = 1;; public int dir = rightDir; public static int speed = (int) 2; private int frames = 0, maxFrames = 5, index = 0, maxIndex = 3; private boolean moved = false; private BufferedImage[] rightPlayer; private BufferedImage[] leftPlayer; public static double life = 100, playerMaxLife = 100; public int ammo = 0; public Player(int x, int y, int width, int height, BufferedImage sprite) { super(x, y, width, height, sprite); rightPlayer = new BufferedImage[4]; leftPlayer = new BufferedImage[4]; for(int i= 0; i < 4; i++ ) { rightPlayer[i] = Game.spritesheet.getSprite(32 + (i*16), 0, 16, 16); } for(int i= 0; i < 4; i++ ) { leftPlayer[i] = Game.spritesheet.getSprite(32 + (i*16), 16, 16, 16); } } public void tick() { //Movimento moved = false; if(right && World.isFree((int)(x+speed),this.getY()) && World.isFreeTree((int)(x+speed),this.getY())) { moved = true; dir = rightDir; x+=speed; } else if(left && World.isFree((int)(x-speed),this.getY()) && World.isFreeTree((int)(x-speed),this.getY())) { moved = true; dir = leftDir; x-=speed; } if(up && World.isFree(this.getX(),(int)(y-speed)) && World.isFreeTree(this.getX(), (int) (y-speed))) { moved = true; y-=speed; } else if(down && World.isFree(this.getX(),(int)(y+speed)) && World.isFreeTree(this.getX(), (int) (y+speed))){ moved = true; y+=speed; } if(moved) { frames++; if(frames == maxFrames) { frames = 0; index++; if(index > maxIndex) { index = 0; } } } //Movimento Camera.x = Camera.clamp(this.getX() - (Game.WIDTH/2),0,World.WIDTH*16 - Game.WIDTH); Camera.y = Camera.clamp(this.getY() - (Game.HEIGHT/2),0,World.HEIGHT*16 - Game.HEIGHT); checkItemLifepack(); checkItemAmmo(); } public void checkItemAmmo() { for(int i = 0; i < Game.entities.size(); i++){ Entity atual = Game.entities.get(i); if(atual instanceof Bullet) { if(Entity.isColidding(this, atual)) { ammo++; System.out.println("Muniçaõ " + ammo); Game.entities.remove(i); return; } } } } public void checkItemLifepack() { for(int i = 0; i < Game.entities.size(); i++){ Entity atual = Game.entities.get(i); if(atual instanceof Lifepack) { if(Entity.isColidding(this, atual)) { life+=10; if(life >= 100) { life = 100; } Game.entities.remove(i); return; } } } } public void render(Graphics g) { if(dir == rightDir) { g.drawImage(rightPlayer[index], this.getX() - Camera.x, this.getY() - Camera.y, null); }else if(dir == leftDir) { g.drawImage(leftPlayer[index], this.getX() - Camera.x, this.getY() - Camera.y, null); } } }
25.479675
111
0.589343
e000489bf5ab8071c9f77a5e928c2d361e1c9633
12,929
package cyder.widgets; import cyder.annotations.Widget; import cyder.consts.CyderColors; import cyder.consts.CyderFonts; import cyder.consts.CyderImages; import cyder.genesis.GenesisShare; import cyder.ui.*; import javax.swing.*; import javax.swing.border.LineBorder; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.text.DecimalFormat; public class TempConverter { private CyderFrame temperatureFrame; private CyderTextField startingValue; private CyderCheckBox oldFahrenheit; private CyderCheckBox newFahrenheit; private CyderCheckBox oldCelsius; private CyderCheckBox newCelsius; private CyderCheckBox oldKelvin; private CyderCheckBox newKelvin; public TempConverter() {} @Widget("temperature") public void showGUI() { if (temperatureFrame != null) temperatureFrame.dispose(); temperatureFrame = new CyderFrame(600,340, CyderImages.defaultBackground); temperatureFrame.setTitle("Temperature Converter"); JLabel ValueLabel = new JLabel("Measurement: "); ValueLabel.setFont(CyderFonts.weatherFontSmall); startingValue = new CyderTextField(0); startingValue.setRegexMatcher("[0-9.]+"); ValueLabel.setBounds(60,40, 200, 30); temperatureFrame.getContentPane().add(ValueLabel); startingValue.setBounds(240,40, 300, 35); temperatureFrame.getContentPane().add(startingValue); oldFahrenheit = new CyderCheckBox(); oldCelsius = new CyderCheckBox(); oldKelvin = new CyderCheckBox(); JLabel oldFahrenheitLabel = new JLabel("Fahrenheit"); oldFahrenheitLabel.setFont(CyderFonts.weatherFontBig.deriveFont(22f)); oldFahrenheitLabel.setForeground(CyderColors.navy); oldFahrenheitLabel.setBounds(140,110,250,30); temperatureFrame.getContentPane().add(oldFahrenheitLabel); JLabel oldCelsiusLabel = new JLabel("Celsius"); oldCelsiusLabel.setFont(CyderFonts.weatherFontBig.deriveFont(22f)); oldCelsiusLabel.setForeground(CyderColors.navy); oldCelsiusLabel.setBounds(140,170,250,30); temperatureFrame.getContentPane().add(oldCelsiusLabel); JLabel oldKelvinLabel = new JLabel("Kelvin"); oldKelvinLabel.setFont(CyderFonts.weatherFontBig.deriveFont(22f)); oldKelvinLabel.setForeground(CyderColors.navy); oldKelvinLabel.setBounds(140,230,250,30); temperatureFrame.getContentPane().add(oldKelvinLabel); oldFahrenheit.setBounds(80,100,50,50); oldCelsius.setBounds(80,160,50,50); oldKelvin.setBounds(80,220,50,50); oldFahrenheit.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { super.mouseClicked(e); oldCelsius.setNotSelected(); oldKelvin.setNotSelected(); } }); oldCelsius.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { super.mouseClicked(e); oldFahrenheit.setNotSelected(); oldKelvin.setNotSelected(); } }); oldKelvin.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { super.mouseClicked(e); oldCelsius.setNotSelected(); oldFahrenheit.setNotSelected(); } }); temperatureFrame.getContentPane().add(oldFahrenheit); temperatureFrame.getContentPane().add(oldCelsius); temperatureFrame.getContentPane().add(oldKelvin); JLabel twoLabel = new JLabel("-2-"); twoLabel.setFont(CyderFonts.weatherFontBig.deriveFont(45f)); twoLabel.setForeground(CyderColors.navy); twoLabel.setBounds(260,150,150,60); temperatureFrame.getContentPane().add(twoLabel); newFahrenheit = new CyderCheckBox(); newCelsius = new CyderCheckBox(); newKelvin = new CyderCheckBox(); JLabel newFahrenheitLabel = new JLabel("Fahrenheit"); newFahrenheitLabel.setFont(CyderFonts.weatherFontBig.deriveFont(22f)); newFahrenheitLabel.setForeground(CyderColors.navy); newFahrenheitLabel.setBounds(430,110,250,30); temperatureFrame.getContentPane().add(newFahrenheitLabel); JLabel newCelsiusLabel = new JLabel("Celsius"); newCelsiusLabel.setFont(CyderFonts.weatherFontBig.deriveFont(22f)); newCelsiusLabel.setForeground(CyderColors.navy); newCelsiusLabel.setBounds(430,170,250,30); temperatureFrame.getContentPane().add(newCelsiusLabel); JLabel newKelvinLabel = new JLabel("Kelvin"); newKelvinLabel.setFont(CyderFonts.weatherFontBig.deriveFont(22f)); newKelvinLabel.setForeground(CyderColors.navy); newKelvinLabel.setBounds(430,230,250,30); temperatureFrame.getContentPane().add(newKelvinLabel); newFahrenheit.setBounds(370,100,50,50); newCelsius.setBounds(370,160,50,50); newKelvin.setBounds(370,220,50,50); newFahrenheit.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { super.mouseClicked(e); newCelsius.setNotSelected(); newKelvin.setNotSelected(); } }); newCelsius.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { super.mouseClicked(e); newFahrenheit.setNotSelected(); newKelvin.setNotSelected(); } }); newKelvin.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { super.mouseClicked(e); newCelsius.setNotSelected(); newFahrenheit.setNotSelected(); } }); temperatureFrame.getContentPane().add(newFahrenheit); temperatureFrame.getContentPane().add(newCelsius); temperatureFrame.getContentPane().add(newKelvin); CyderButton calculate = new CyderButton("Calculate"); calculate.setBorder(new LineBorder(CyderColors.navy,5,false)); calculate.addActionListener(e -> { try { DecimalFormat tempFormat = new DecimalFormat("#.####"); double CalculationValue = Double.parseDouble(startingValue.getText()); if (oldKelvin.isSelected() && CalculationValue <= 0) { temperatureFrame.notify("Temperatures below absolute zero are imposible."); } else { if (oldFahrenheit.isSelected()) { if (newFahrenheit.isSelected()) { temperatureFrame.notify("Get out of here with that. Your value is already in Fahrenheit."); } else if (newCelsius.isSelected()) { double CelsiusFromFahrenheit; CelsiusFromFahrenheit = (CalculationValue - 32.0) / 1.8; temperatureFrame.notify( CalculationValue + " Fahrenheit converted to Celsius equals: " + tempFormat.format(CelsiusFromFahrenheit)); startingValue.setText(""); } else if (newKelvin.isSelected()) { double KelvinFromFahrenheit; KelvinFromFahrenheit = (CalculationValue + 459.67) * 5/9; if (KelvinFromFahrenheit >= 0) { temperatureFrame.notify(CalculationValue + " Fahrenheit converted to Kelvin equals: " + tempFormat.format(KelvinFromFahrenheit)); startingValue.setText(""); } else { temperatureFrame.notify("Temperatures below absolute zero are imposible."); } } else { temperatureFrame.notify("Please select the unit to convert to."); } } else if (oldCelsius.isSelected()) { if (newFahrenheit.isSelected()) { double FahrenheitFromCelsius; FahrenheitFromCelsius = (CalculationValue *1.8) + 32; temperatureFrame.notify(CalculationValue + " Celsius converted to Fahrenheit equals: " + tempFormat.format(FahrenheitFromCelsius)); startingValue.setText(""); } else if (newCelsius.isSelected()) { temperatureFrame.notify("Get out of here with that. Your value is already in Celsius."); } else if (newKelvin.isSelected()) { double KelvinFromCelsius; KelvinFromCelsius = CalculationValue + 273.15 ; if (KelvinFromCelsius >= 0) { temperatureFrame.notify(CalculationValue + " Celsius converted to Kelvin equals: " + tempFormat.format(KelvinFromCelsius)); startingValue.setText(""); } else { temperatureFrame.notify("Temperatures below absolute zero are imposible."); } } else { temperatureFrame.notify("Please select the unit to convert to."); } } else if (oldKelvin.isSelected()) { if (newFahrenheit.isSelected()) { double FahrenheitFromKelvin; FahrenheitFromKelvin = CalculationValue * 1.8 - 459.67; temperatureFrame.notify(CalculationValue + " Kelvin converted to Fahrenheit equals: " + tempFormat.format(FahrenheitFromKelvin)); startingValue.setText(""); } else if (newCelsius.isSelected()) { double CelsiusFromKelvin; CelsiusFromKelvin = CalculationValue - 273.15; temperatureFrame.notify( CalculationValue + " Kelvin converted to Celsius equals: " + tempFormat.format(CelsiusFromKelvin)); startingValue.setText(""); } else if (newKelvin.isSelected()) { temperatureFrame.notify("Get out of here with that. Your value is already in Kelvin"); } else { temperatureFrame.notify("Please select the unit to convert to."); } } else temperatureFrame.notify("Please select your current temperature unit and the one you want to convet to."); } } catch (Exception ex) { if (startingValue.getText().length() == 0) { temperatureFrame.notify("Please enter a starting value."); } else { temperatureFrame.notify("Your value must only contain numbers."); } } }); CyderButton resetValues = new CyderButton("Reset Values"); resetValues.setBorder(new LineBorder(CyderColors.navy,5,false)); resetValues.setColors(CyderColors.regularRed); calculate.setColors(CyderColors.regularRed); resetValues.addActionListener(e -> { startingValue.setText(""); oldCelsius.setNotSelected(); oldFahrenheit.setNotSelected(); oldKelvin.setNotSelected(); newCelsius.setNotSelected(); newFahrenheit.setNotSelected(); newKelvin.setNotSelected(); }); calculate.setBackground(CyderColors.regularRed); calculate.setFont(CyderFonts.weatherFontSmall); resetValues.setFocusPainted(false); resetValues.setBackground(CyderColors.regularRed); resetValues.setFont(CyderFonts.weatherFontSmall); calculate.setBounds(140,280,150,40); resetValues.setBounds(300,280,150,40); temperatureFrame.getContentPane().add(calculate); temperatureFrame.getContentPane().add(resetValues); temperatureFrame.setVisible(true); temperatureFrame.setLocationRelativeTo(GenesisShare.getDominantFrame()); } }
42.529605
130
0.580787
61a742ade3b614982da60a46cb3fc108e68aa877
644
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.config.protocol; import java.io.ByteArrayOutputStream; /** * Subclass of {@link java.io.ByteArrayOutputStream} that gives effective {@link #toByteArray()} method. * * @author Ulf Lilleengen */ class NoCopyByteArrayOutputStream extends ByteArrayOutputStream { public NoCopyByteArrayOutputStream() { super(); } public NoCopyByteArrayOutputStream(int initialSize) { super(initialSize); } @Override public byte[] toByteArray() { return buf; } }
25.76
118
0.71118
7bd8085d80bae7f52bad23057c0ee975500fdf11
1,719
package xin.cymall.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.Map; import xin.cymall.dao.SrvFoodUpDownDao; import xin.cymall.entity.SrvFoodUpDown; import xin.cymall.service.SrvFoodUpDownService; @Service("srvFoodUpDownService") @Transactional public class SrvFoodUpDownServiceImpl implements SrvFoodUpDownService { @Autowired private SrvFoodUpDownDao srvFoodUpDownDao; @Override public SrvFoodUpDown get(String id){ return srvFoodUpDownDao.get(id); } @Override public List<SrvFoodUpDown> getList(Map<String, Object> map){ return srvFoodUpDownDao.getList(map); } @Override public int getCount(Map<String, Object> map){ return srvFoodUpDownDao.getCount(map); } @Override public void save(SrvFoodUpDown srvFoodUpDown){ srvFoodUpDownDao.save(srvFoodUpDown); } @Override public void update(SrvFoodUpDown srvFoodUpDown){ srvFoodUpDownDao.update(srvFoodUpDown); } @Override public void delete(String id){ srvFoodUpDownDao.delete(id); } @Override public void deleteBatch(String[] ids){ srvFoodUpDownDao.deleteBatch(ids); } @Override public void updateState(String[] ids,String stateValue) { for (String id:ids){ SrvFoodUpDown srvFoodUpDown=get(id); update(srvFoodUpDown); } } @Override @Transactional public void batchUporDown(List<SrvFoodUpDown> list,Integer status) { for(SrvFoodUpDown srvFoodUpDown : list){ if(status == 1){ srvFoodUpDownDao.save(srvFoodUpDown); }else srvFoodUpDownDao.downFood(srvFoodUpDown); } } }
21.759494
71
0.762071
7520c9391e36bc97c79d6fd07e43930fa34b6717
195
package sunrise.raas.sdk.core.authentication; import java.util.UUID; public interface AuthenticationDetailsFactory { AuthenticationDetails createFromApiKey(UUID clientId, String apiKey); }
24.375
73
0.825641
a455f9672a9c4bdb98ab9ac37fd438a3d581d7d2
353
package org.reldb.tuplesoup; import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class TupleSet implements Iterable<Tuple> { private Set<Tuple> tuples = new HashSet<>(); public TupleSet add(Tuple tuple) { tuples.add(tuple); return this; } public Iterator<Tuple> iterator() { return tuples.iterator(); } }
17.65
50
0.72238
b04d7f00e0f33bc2976979f8bc769104fd5e6907
557
package ru.vol.addressbook.tests; import org.testng.Assert; import org.testng.annotations.Test; import ru.vol.addressbook.model.GroupData; public class GroupCreationTests extends TestBase { @Test public void testGroupCreation() throws Exception { int before = app.getGroupHelper().getGroupCount(); app.getGroupHelper().goToGroupPage(); app.getGroupHelper().createGroup(new GroupData("test1", null, "3")); int after = app.getGroupHelper().getGroupCount(); Assert.assertEquals(after, before +1); } }
25.318182
76
0.70377
021380e8e3ccc6f5ee2b3ff4a07f6ab259a56546
1,917
/* * Copyright 2015 Space Dynamics Laboratory - Utah State University Research Foundation. * * 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 edu.usu.sdl.openstorefront.web.test.format; import edu.usu.sdl.openstorefront.common.manager.FileSystemManager; import edu.usu.sdl.openstorefront.core.entity.DataSource; import edu.usu.sdl.openstorefront.core.entity.FileFormat; import edu.usu.sdl.openstorefront.core.entity.FileHistory; import edu.usu.sdl.openstorefront.core.entity.FileHistoryOption; import edu.usu.sdl.openstorefront.core.model.ImportContext; import edu.usu.sdl.openstorefront.web.test.BaseTestCase; /** * * @author dshurtleff */ public class ER2XMLTest extends BaseTestCase { public ER2XMLTest() { this.description = "ER2XML Test"; } @Override protected void runInternalTest() { ImportContext importContext = new ImportContext(); importContext.setInput(FileSystemManager.getApplicatioResourceFile("/data/test/assettest.xml")); FileHistory fileHistory = new FileHistory(); fileHistory.setMimeType("application/xml"); fileHistory.setDataSource(DataSource.ER2); fileHistory.setOriginalFilename("assettest.xml"); fileHistory.setFileFormat(FileFormat.COMPONENT_ER2); fileHistory.setFileHistoryOption(new FileHistoryOption()); importContext.getFileHistoryAll().setFileHistory(fileHistory); service.getImportService().importData(importContext); } }
33.051724
98
0.783516
01b43e414cac9939b12253ea484c42dc6259fa94
2,659
package at.tugraz.ist.swe.cheatapp; import org.json.JSONException; import org.json.JSONObject; public class BluetoothMessage { private Type messageType; private ChatMessage message = null; private ConnectMessage connectMessage = null; private DisconnectMessage disconnectMessage = null; public BluetoothMessage(ChatMessage message) { messageType = Type.CHAT; this.message = message; } public BluetoothMessage(ConnectMessage connectMessage) { this.messageType = Type.CONNECT; this.connectMessage = connectMessage; } public BluetoothMessage(DisconnectMessage disconnectMessage) { this.messageType = Type.DISCONNECT; this.disconnectMessage = disconnectMessage; } public static BluetoothMessage fromJSONString(String json) throws JSONException { JSONObject jsonMessage = new JSONObject(json); String type = jsonMessage.getString("type"); Type messageType = Type.valueOf(type); String payload = jsonMessage.getString("payload"); switch (messageType) { case CHAT: { ChatMessage chatMessage = new ChatMessage(payload, false); return new BluetoothMessage(chatMessage); } case CONNECT: { ConnectMessage connectMessage = new ConnectMessage(payload); return new BluetoothMessage(connectMessage); } case DISCONNECT: DisconnectMessage disconnectMessage = new DisconnectMessage(); return new BluetoothMessage(disconnectMessage); } return null; } public Type getMessageType() { return messageType; } public ChatMessage getMessage() { return message; } public ConnectMessage getConnectMessage() { return connectMessage; } public DisconnectMessage getDisconnectMessage() { return disconnectMessage; } public String toJSONString() throws JSONException { JSONObject serializedMessage = new JSONObject(); serializedMessage.put("type", messageType.toString()); String payload = ""; switch (messageType) { case CHAT: payload = message.getJsonString(); break; case CONNECT: payload = connectMessage.getJsonString(); break; case DISCONNECT: payload = ""; break; } serializedMessage.put("payload", payload); return serializedMessage.toString(); } enum Type {CONNECT, DISCONNECT, CHAT, FILE} }
28.902174
85
0.626551
e4c7a45703a8fba0092688e06fa2252cc12f92b6
6,826
package mage.cards.h; import mage.MageObject; import mage.abilities.Ability; import mage.abilities.common.EntersBattlefieldTriggeredAbility; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.effects.AsThoughEffectImpl; import mage.abilities.effects.OneShotEffect; import mage.cards.Card; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.*; import mage.game.ExileZone; import mage.game.Game; import mage.players.Player; import mage.target.common.TargetOpponent; import mage.util.CardUtil; import java.util.ArrayList; import java.util.List; import java.util.UUID; /** * * @author LevelX2 */ public final class HedonistsTrove extends CardImpl { public HedonistsTrove(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.ENCHANTMENT}, "{5}{B}{B}"); // When Hedonist's Trove enters the battlefield, exile all cards from target opponent's graveyard. Ability ability = new EntersBattlefieldTriggeredAbility(new HedonistsTroveExileEffect()); ability.addTarget(new TargetOpponent()); this.addAbility(ability); // You may play land cards exiled by Hedonist's Trove. this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, new HedonistsTrovePlayLandEffect())); // You may cast nonland cards exiled with Hedonist's Trove. You can't cast more than one spell this way each turn. this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, new HedonistsTroveCastNonlandCardsEffect())); } public HedonistsTrove(final HedonistsTrove card) { super(card); } @Override public HedonistsTrove copy() { return new HedonistsTrove(this); } } class HedonistsTroveExileEffect extends OneShotEffect { public HedonistsTroveExileEffect() { super(Outcome.Exile); staticText = "exile all cards from target opponent's graveyard"; } @Override public HedonistsTroveExileEffect copy() { return new HedonistsTroveExileEffect(); } @Override public boolean apply(Game game, Ability source) { Player controller = game.getPlayer(source.getControllerId()); Player targetPlayer = game.getPlayer(this.getTargetPointer().getFirst(game, source)); MageObject sourceObject = source.getSourceObject(game); if (controller != null && targetPlayer != null && sourceObject != null) { UUID exileId = CardUtil.getExileZoneId(game, source.getSourceId(), source.getSourceObjectZoneChangeCounter()); List<UUID> graveyard = new ArrayList<>(targetPlayer.getGraveyard()); for (UUID cardId : graveyard) { Card card = game.getCard(cardId); if (card != null) { controller.moveCardToExileWithInfo(card, exileId, sourceObject.getIdName(), source, game, Zone.GRAVEYARD, true); } } return true; } return false; } } class HedonistsTrovePlayLandEffect extends AsThoughEffectImpl { public HedonistsTrovePlayLandEffect() { super(AsThoughEffectType.PLAY_FROM_NOT_OWN_HAND_ZONE, Duration.WhileOnBattlefield, Outcome.Benefit); staticText = "You may play land cards exiled with {this}"; } public HedonistsTrovePlayLandEffect(final HedonistsTrovePlayLandEffect effect) { super(effect); } @Override public boolean apply(Game game, Ability source) { return true; } @Override public HedonistsTrovePlayLandEffect copy() { return new HedonistsTrovePlayLandEffect(this); } @Override public boolean applies(UUID objectId, Ability source, UUID affectedControllerId, Game game) { if (affectedControllerId.equals(source.getControllerId())) { Card card = game.getCard(objectId); MageObject sourceObject = source.getSourceObject(game); if (card != null && card.isLand() && sourceObject != null) { UUID exileId = CardUtil.getExileZoneId(game, source.getSourceId(), source.getSourceObjectZoneChangeCounter()); if (exileId != null) { ExileZone exileZone = game.getState().getExile().getExileZone(exileId); return exileZone != null && exileZone.contains(objectId); } } } return false; } } class HedonistsTroveCastNonlandCardsEffect extends AsThoughEffectImpl { private int turnNumber; private UUID cardId; public HedonistsTroveCastNonlandCardsEffect() { super(AsThoughEffectType.PLAY_FROM_NOT_OWN_HAND_ZONE, Duration.WhileOnBattlefield, Outcome.Benefit); staticText = "You may cast nonland cards exiled with {this}. You can't cast more than one spell this way each turn"; } public HedonistsTroveCastNonlandCardsEffect(final HedonistsTroveCastNonlandCardsEffect effect) { super(effect); this.turnNumber = effect.turnNumber; this.cardId = effect.cardId; } @Override public boolean apply(Game game, Ability source) { return true; } @Override public HedonistsTroveCastNonlandCardsEffect copy() { return new HedonistsTroveCastNonlandCardsEffect(this); } @Override public boolean applies(UUID objectId, Ability source, UUID affectedControllerId, Game game) { if (affectedControllerId.equals(source.getControllerId())) { Card card = game.getCard(objectId); MageObject sourceObject = source.getSourceObject(game); if (card != null && !card.isLand() && sourceObject != null) { UUID exileId = CardUtil.getExileZoneId(game, source.getSourceId(), source.getSourceObjectZoneChangeCounter()); if (exileId != null) { ExileZone exileZone = game.getState().getExile().getExileZone(exileId); if (exileZone != null && exileZone.contains(objectId)) { if (game.getTurnNum() == turnNumber) { if (!exileZone.contains(cardId)) { // last checked card this turn is no longer exiled, so you can't cast another with this effect // TODO: Handle if card was cast/removed from exile with effect from another card. // If so, this effect could prevent player from casting although they should be able to use it return false; } } this.turnNumber = game.getTurnNum(); this.cardId = objectId; return true; } } } } return false; } }
37.922222
132
0.649722
3cfb86c31dfdadcc59eb6221a94a984cdd0c23b6
503
package kz.chesschicken.ojw.utils; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.loader.api.FabricLoader; import net.minecraft.client.Minecraft; /** * Returns Minecraft Client's instance. * Use this if you're working with client side. */ @Environment(EnvType.CLIENT) public class MinecraftInstance { @SuppressWarnings("deprecation") public static Minecraft get() { return (Minecraft) FabricLoader.getInstance().getGameInstance(); } }
26.473684
72
0.755467
1964a7866bb82f4733a9ac98b0cd4b511381eb13
709
package ResponseFactory; import Request.*; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.io.IOException; public class CreatedResponse extends Response{ public CreatedResponse( Resource resource ){ super( resource ); this.statusCode = 201; this.reasonPhrase = "Created"; } public void send( OutputStream out ) throws IOException{ BufferedWriter output = new BufferedWriter( new OutputStreamWriter( out ) ); this.sendAlwaysPhrase( output ); this.sendOtherHeaders( output ); this.sendHeaderTemplate( output, "Content-Type", this.resource.getMimeType() ); output.write(this.CRLF); output.flush(); } }
26.259259
83
0.733427
7206d183c80895d5a0387f168b0084472157efdc
1,426
// Naive solution, runs in O(k * N^2), where k is size of integer and N is length of array // Uses O(1) space public class Solution { public int totalHammingDistance(int[] nums) { int total = 0; for (int i = 0; i < nums.length - 1; i++) { for (int j = i + 1; j < nums.length; j++) { total += distance(nums[i], nums[j]); } } return total; } private int distance(int a, int b) { int c = a ^ b, cnt = 0; while (c > 0) { if ((c & 1) > 0) cnt++; c >>>= 1; } return cnt; } } // Better approach, runs in O(k * N), where k is size of integer (30) and N is length of array // Uses O(1) space public class Solution { public int totalHammingDistance(int[] nums) { int total = 0, shift = 30; while (shift >= 0) { int ones = 0; for (int num : nums) { if ((num & (1 << shift)) > 0) ones++; } shift--; int zeros = nums.length - ones; total += ones * zeros; } return total; } } // Better approach (faster than previous one), runs in O(N) and uses O(1) space public class Solution { public int totalHammingDistance(int[] nums) { int total = 0, shift = 30; while (shift >= 0) { int ones = 0; for (int i = 0; i < nums.length; i++) { ones += (nums[i]) & 1; nums[i] >>= 1; } shift--; total += ones * (nums.length - ones); } return total; } }
24.586207
94
0.52244
93c449b20e95f5a55a96bf5013c86e94cce8795a
1,893
/* * Copyright (c) 2011, Walter Lowe * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.lowetek.caltrainalerts.android; import android.os.Bundle; /** * A listener for content events that come from the server. * Clients can implement this and register themselves * with {@link ServiceHelper} to update UI in response to * specific server events. * * @author nopayne * */ public interface ServerEventListener { public void onServerEvent(int eventId, Bundle extras); }
63.1
758
0.792393
493e8a0b9f1df35205b81e896057b45f3c6cd3e7
2,928
// This file was generated by the TNO Bean Generator. // Any modifications to this file will be lost upon re-generation. // Generated on: 2020/03/27 12:19:05 package nl.tno.rpr.interactions; import nl.tno.rpr.datatypes.CollisionTypeEnum8; import nl.tno.rpr.datatypes.EventIdentifierStruct; import nl.tno.rpr.datatypes.RelativePositionStruct; import nl.tno.rpr.datatypes.VelocityVectorStruct; /** The act or instance of coming together with solid impact. */ public class Collision { /** The object instance ID of the object that the issuing object has collided with. */ String CollidingObjectIdentifier; /** The mass of the issuing object. */ float IssuingObjectMass; /** The velocity vector of the issuing object at the moment of impact. */ VelocityVectorStruct IssuingObjectVelocityVector; /** The type of collision. */ CollisionTypeEnum8 CollisionType; /** * The location of the collision relative to the object that the issuing object has collided with. */ RelativePositionStruct CollisionLocation; /** An ID assigned by the issuing object to associate related collision events. */ EventIdentifierStruct EventIdentifier; /** * The object instance ID of the object that has detected the collision and issued the collision * interaction. */ String IssuingObjectIdentifier; public String getCollidingObjectIdentifier() { return this.CollidingObjectIdentifier; } public void setCollidingObjectIdentifier(String CollidingObjectIdentifier) { this.CollidingObjectIdentifier = CollidingObjectIdentifier; } public float getIssuingObjectMass() { return this.IssuingObjectMass; } public void setIssuingObjectMass(float IssuingObjectMass) { this.IssuingObjectMass = IssuingObjectMass; } public VelocityVectorStruct getIssuingObjectVelocityVector() { return this.IssuingObjectVelocityVector; } public void setIssuingObjectVelocityVector(VelocityVectorStruct IssuingObjectVelocityVector) { this.IssuingObjectVelocityVector = IssuingObjectVelocityVector; } public CollisionTypeEnum8 getCollisionType() { return this.CollisionType; } public void setCollisionType(CollisionTypeEnum8 CollisionType) { this.CollisionType = CollisionType; } public RelativePositionStruct getCollisionLocation() { return this.CollisionLocation; } public void setCollisionLocation(RelativePositionStruct CollisionLocation) { this.CollisionLocation = CollisionLocation; } public EventIdentifierStruct getEventIdentifier() { return this.EventIdentifier; } public void setEventIdentifier(EventIdentifierStruct EventIdentifier) { this.EventIdentifier = EventIdentifier; } public String getIssuingObjectIdentifier() { return this.IssuingObjectIdentifier; } public void setIssuingObjectIdentifier(String IssuingObjectIdentifier) { this.IssuingObjectIdentifier = IssuingObjectIdentifier; } }
30.185567
100
0.779713
1c1aff3114873be65e3270155aa8cabc978e2e16
590
package program; public class EnumExercise { public static void main(String[] args) { Student s1 = new Student(); s1.setStudentId(1000); s1.setName("Alvin"); s1.setTotalMarks(150); s1.calculateGrade(); s1.calculateScholarshipAmount(); System.out.println("\n\tStudent Details"); System.out.println("Student ID \t : \t" + s1.getStudentId()); System.out.println("Student Name \t : \t" + s1.getName()); System.out.println("Student Grade \t : \t" + s1.getGrade()); System.out.println("Scholarship Amount : \t" + s1.getScholarshipAmount()); } }
28.095238
77
0.655932
8d70df9a945155547d8478d4a9ab60da5fd0157e
3,616
/** * BooleanAlgebras * theory * Apr 21, 2015 * @author Loris D'Antoni */ package theory.characters; import static com.google.common.base.Preconditions.checkArgument; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.sat4j.specs.TimeoutException; import theory.BooleanAlgebra; import utilities.Pair; /** * CharPred: a set of characters represented as contiguous intervals */ public class BinaryCharPred extends ICharPred { public ArrayList<Pair<CharPred,CharPred>> notEqual; public CharPred equals; private BinaryCharPred(){ setAsReturn(); } /** * Return language is p, and it forces equality with call if forceEquality=true */ public BinaryCharPred(CharPred p, boolean forceEquality) { this(); checkArgument(p != null); notEqual = new ArrayList<Pair<CharPred,CharPred>>(); equals = p; if(!forceEquality){ notEqual.add(new Pair<CharPred, CharPred>(StdCharPred.TRUE, p)); } } public void normalize(BooleanAlgebra<CharPred, Character> ba) throws TimeoutException{ ArrayList<Pair<CharPred,CharPred>> newNotEqual = new ArrayList<Pair<CharPred,CharPred>>(); ArrayList<CharPred> firstProj = new ArrayList<>(); for(Pair<CharPred,CharPred> pair: notEqual) firstProj.add(pair.first); Collection<Pair<CharPred,ArrayList<Integer>>> minterms = ba.GetMinterms(firstProj); for(Pair<CharPred,ArrayList<Integer>> minterm:minterms){ CharPred currA = minterm.first; CharPred currB = ba.False(); for (int bit = 0; bit < notEqual.size(); bit++) if (minterm.second.get(bit) == 1) currB = ba.MkOr(currB, notEqual.get(bit).second); newNotEqual.add(new Pair<>(currA, currB)); } notEqual = newNotEqual; } public BinaryCharPred(CharPred eq, ArrayList<Pair<CharPred,CharPred>> notEqual) { this(); checkArgument(eq != null && notEqual!=null); this.equals = eq; this.notEqual = notEqual; } /** * c and r without caring about equality * @throws TimeoutException */ public BinaryCharPred(CharPred c, CharPred r, BooleanAlgebra<CharPred, Character> ba) throws TimeoutException { this(); checkArgument(c != null && r!=null); notEqual = new ArrayList<Pair<CharPred,CharPred>>(); equals = StdCharPred.FALSE; equals = ba.MkAnd(c,r); notEqual.add(new Pair<CharPred, CharPred>(c,r)); } public boolean isSatisfiedBy(char c1, char c2) { if(c1 == c2) return equals.isSatisfiedBy(c1); else for(Pair<CharPred,CharPred> pair: notEqual) if(pair.first.isSatisfiedBy(c1) && pair.second.isSatisfiedBy(c2)) return true; return false; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("neq "); sb.append(notEqual); sb.append(", eq "); sb.append(equals); return sb.toString(); } // Only prints readable chars, otherwise print unicode public static String printChar(char c) { Map<Character, String> unescapeMap = new HashMap<Character, String>(); unescapeMap.put('-', "\\-"); unescapeMap.put('(', "\\("); unescapeMap.put(')', "\\)"); unescapeMap.put('[', "\\["); unescapeMap.put(']', "\\]"); unescapeMap.put('\t', "\\t"); unescapeMap.put('\b', "\\b"); unescapeMap.put('\n', "\\n"); unescapeMap.put('\r', "\\r"); unescapeMap.put('\f', "\\f"); unescapeMap.put('\'', "\\\'"); unescapeMap.put('\"', "\\\""); unescapeMap.put('\\', "\\\\"); if (unescapeMap.containsKey(c)) { return unescapeMap.get(c); } else if (c < 0x20 || c > 0x7f) { return String.format("\\u%04x", (int) c); } else { return Character.toString(c); } } }
26.588235
112
0.672566
0e22d10b27df53dff665f17f677a01ee260fef9a
5,148
/* * -@TestCaseID:maple/runtime/rc/function/RC_Thread02/RC_Thread_04.java * -@TestCaseName:RC_Thread_04.java * -@RequirementName:[运行时需求]支持自动内存管理 * -@Title/Destination:Multi Thread reads or writes static para.It is modified from Cycle_B_1_00180.At the same time,another thread is GC. * -@Condition: no * -#c1 * -@Brief:Multi Thread reads or writes static para.It is modified from Cycle_B_1_00180.At the same time,another thread is GC. * -#step1 * -@Expect:ExpectResult\nExpectResult\n * -@Priority: High * -@Source: RC_Thread_04.java * -@ExecuteClass: RC_Thread_04 * -@ExecuteArgs: * -@Remark: * */ class RcThread0401 extends Thread { public void run() { RC_Thread_04 rcth01 = new RC_Thread_04(); try { rcth01.setA1null(); } catch (NullPointerException e) { // do nothing } } } class RcThread0402 extends Thread { public void run() { RC_Thread_04 rcth01 = new RC_Thread_04(); try { rcth01.setA4null(); } catch (NullPointerException e) { // do nothing } } } class RcThread0403 extends Thread { public void run() { RC_Thread_04 rcth01 = new RC_Thread_04(); try { rcth01.setA5null(); } catch (NullPointerException e) { // do nothing } } } class RcThread04GC extends Thread { public void run() { int start = 0; do { Runtime.getRuntime().gc(); start++; } while (start < 50); if (start == 50) { System.out.println("ExpectResult"); } } } public class RC_Thread_04 { private static volatile RcThread04A1 a1_main = null; private static volatile RcThread04A4 a4_main = null; private static volatile RcThread04A5 a5_main = null; RC_Thread_04() { try { RcThread04A1 a1 = new RcThread04A1(); a1.a2_0 = new RcThread04A2(); a1.a2_0.a3_0 = new RcThread04A3(); RcThread04A4 a4 = new RcThread04A4(); RcThread04A5 a5 = new RcThread04A5(); a4.a1_0 = a1; a5.a1_0 = a1; a1.a2_0.a3_0.a1_0 = a1; a1_main = a1; a4_main = a4; a5_main = a5; } catch (NullPointerException e) { // do nothing } } public static void main(String[] args) { cyclePatternWrapper(); RcThread04GC gc = new RcThread04GC(); gc.start(); rcTestcaseMainWrapper(); rcTestcaseMainWrapper(); rcTestcaseMainWrapper(); rcTestcaseMainWrapper(); System.out.println("ExpectResult"); } private static void cyclePatternWrapper() { a1_main = new RcThread04A1(); a1_main.a2_0 = new RcThread04A2(); a1_main.a2_0.a3_0 = new RcThread04A3(); a4_main = new RcThread04A4(); a5_main = new RcThread04A5(); a4_main.a1_0 = a1_main; a5_main.a1_0 = a1_main; a1_main.a2_0.a3_0.a1_0 = a1_main; a1_main = null; a4_main = null; a5_main = null; Runtime.getRuntime().gc(); // 单独构造一次Cycle_B_1_00180环,通过gc学习到环模式 } private static void rcTestcaseMainWrapper() { RcThread0401 t1 = new RcThread0401(); RcThread0402 t2 = new RcThread0402(); RcThread0403 t3 = new RcThread0403(); t1.start(); t2.start(); t3.start(); try { t1.join(); t2.join(); t3.join(); }catch(InterruptedException e){ // do nothing } } void setA1null() { a1_main = null; } void setA4null() { a4_main = null; } void setA5null() { a5_main = null; } static class RcThread04A1 { volatile RcThread04A2 a2_0; int a; int sum; RcThread04A1() { a2_0 = null; a = 1; sum = 0; } } static class RcThread04A2 { volatile RcThread04A3 a3_0; int a; int sum; RcThread04A2() { a3_0 = null; a = 2; sum = 0; } } static class RcThread04A3 { volatile RcThread04A1 a1_0; int a; int sum; RcThread04A3() { a1_0 = null; a = 3; sum = 0; } } static class RcThread04A4 { volatile RcThread04A1 a1_0; int a; int sum; RcThread04A4() { a1_0 = null; a = 4; sum = 0; } } static class RcThread04A5 { volatile RcThread04A1 a1_0; int a; int sum; RcThread04A5() { a1_0 = null; a = 5; sum = 0; } } } // EXEC:%maple %f %build_option -o %n.so // EXEC:%run %n.so %n %run_option | compare %f // ASSERT: scan-full ExpectResult\nExpectResult\n
24.990291
139
0.51418
691559af75353e33195c03cd8b41921f177b7d34
3,563
package com.hzq.dragonshopping.controller; import com.hzq.dragonshopping.entity.ProduceEntity; import com.hzq.dragonshopping.entity.ShoppingCartEntity; import com.hzq.dragonshopping.service.IShoppingCartService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.util.HashMap; import java.util.Map; @Controller @RequestMapping("/shoppingcart/") public class ShoppingCartController { @Autowired private IShoppingCartService shoppingCartService; /** * 展示用户购物车详情页面 * @param request * @return */ @RequestMapping("mycart.do") public Object showMyCart(HttpServletRequest request, Model model){ Map<String,Object> map = new HashMap<>(); if(request.getSession(true).getAttribute("user_id")!=null){ Integer uid = (Integer) request.getSession(true).getAttribute("user_id"); if(shoppingCartService.getAllShopingCart(uid).size()>0){ map.put("code","1"); map.put("mycartlist",shoppingCartService.getAllShopingCart(uid)); }else { map.put("code","0"); } }else { map.put("code","0"); map.put("mycartlist","用户未登录!"); } System.out.println("显示购物车code====="+map.get("code")); model.addAttribute("cartlist",map); return "mycart"; } /** * 检查库存是否够用 * @param produceEntity * @return */ // @RequestMapping("producecount.do") // @ResponseBody // public Object checkProduceCount(ProduceEntity produceEntity,HttpServletRequest request, HttpSession httpSession) { // Map<String, Object> map = new HashMap<>(); // if (request.getSession(true).getAttribute("user_id") != null) { // if (shoppingCartService.checkProduceCount(produceEntity).size() > 0) { // map.put("code", 1); // } else { // map.put("code", 0); // } // }else { // //未登录 // map.put("code",3); // } // System.out.println("producecount.do======="+map.get("code")); // return map; // } /** * 增加商品到购物车 * @return */ @ResponseBody @RequestMapping("addshoppingcart.do") public Object addShoppingCart(ShoppingCartEntity shoppingCartEntity,HttpServletRequest request, HttpSession httpSession){ //获取用户id Integer uid = (Integer) request.getSession(true).getAttribute("user_id"); System.out.println("uid=========="+uid); shoppingCartEntity.setUser_id(uid); System.out.println(shoppingCartEntity.toString()); // boolean flag = shoppingCartService.addShoppingCart(shoppingCartEntity); Map<String,Object> map = new HashMap<>(); ProduceEntity produceEntity = new ProduceEntity(); produceEntity.setProduce_id(shoppingCartEntity.getProduce_id()); produceEntity.setProduce_count(shoppingCartEntity.getCart_produce_count()); if (request.getSession(true).getAttribute("user_id") != null) { map = shoppingCartService.addShoppingCart(shoppingCartEntity); }else { //未登录 map.put("codemsg","3"); System.out.println("未登录,code"+3); } return map; } }
34.931373
125
0.637104
daecc930647aa1feff8968fc5f9c2c9265dc2291
293
package zhoubao.data; public class SpitterNotFoundException extends RuntimeException { private String spitterUserName; public SpitterNotFoundException(String spitterUserName) { this.spitterUserName=spitterUserName; } public String getSpitterUserName() { return spitterUserName; } }
24.416667
64
0.819113
e84a6179b492380756e8cc5926a8a87a18b413b0
14,973
package com.example.securitymaterial; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; //import para acessar a permissão de upload de imagem no banco de dados. import android.Manifest; //imports para utilizar Intent e Widgets em código. import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.database.SQLException; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; //imports para o banco de dados import android.content.Context; import android.database.sqlite.SQLiteDatabase; //imports para tranformar bitmap em byte. import com.example.securitymaterial.R; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class ac_cadastro extends AppCompatActivity { //variáveis e constantes para o uso de upload de imagem //***CONTEM UMA PERMISSÃO NO MANIFEST.XML PARA ESSE CÓDIGO FUNCIONAR (UPLOAD DE IMAGEM). public final int PERMISSAO_REQUEST = 1; //constante para requerir permissão do usuário para acessar galeria. public boolean imgSelecionada = false; //verifica se há imagem selecionada. public static final int CODE_PERMISSION = 12; //verifica as outras entradas. public boolean temNome = false; public boolean temCategoria = false; public boolean temDescri = false; public boolean notDirCreat = false; //byte[] byteArray; //imagem em bytes (Blob) public String imgPath; Bitmap thumbnail; //variáveis que vão tratar a entrada. String txtCateg; String txtNome; String txtDescri; EditText inputNome; EditText inputDescri; Spinner spnCateg; //fim das variáveis de entrada. SQLiteDatabase db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_ac_cadastro); //instancia objeto de Banco de dados para manipula-lo. db = openOrCreateDatabase("database_sm",Context.MODE_PRIVATE, null); //variáveis para armazenar os dados de entrada(nome do item, imagem, descrição, categoria) //para cadastro. //abre o Banco de Dados; //db = openOrCreateDatabase("database_sm", MODE_PRIVATE, null); //pede permissão para selecionar imagem da geleria, a partir de uma tag "permission" do Manifest.xml. if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED) { if(ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.READ_EXTERNAL_STORAGE)) { }else{ ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE} ,PERMISSAO_REQUEST); } } } //abre a galeria para fazer upload de imagem para o app. public void imgClick(View view){ Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(intent, 1); } //trata a imagem selecionada e converte em bitmap (valor exibível em widget e utilizavel). @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK && requestCode == 1) { Uri selectedImage = data.getData(); String[] filePath = { MediaStore.Images.Media.DATA }; Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null); c.moveToFirst(); int columnIndex = c.getColumnIndex(filePath[0]); String picturePath = c.getString(columnIndex); c.close(); imgPath = picturePath; //caminho da imagem. //abaixo, decodifica a imagem para mostrar o ImageView. thumbnail = (BitmapFactory.decodeFile(picturePath)); ImageView iv = (ImageView) findViewById(R.id.imageView); iv.setImageBitmap(thumbnail); imgSelecionada = true; TextView txtRemove = (TextView)findViewById(R.id.txtRemove); txtRemove.setVisibility(View.VISIBLE); if(thumbnail==null){ Toast.makeText(getBaseContext(), "Imagem não suportada!", Toast.LENGTH_LONG).show(); RemoveImg(); } } } //varifica se as permissões foram concedidas pelo usuário para o upload de imagem. @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { if (requestCode == PERMISSAO_REQUEST) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // A permissão foi concedida. Pode continuar } else { Toast.makeText(getBaseContext(), "A permissão de seleção de imagem não foi concedida."+"\n"+ "Se quiser selecionar uma imagem, tente novamente e conceda a permissão :)", Toast.LENGTH_LONG).show(); } return; } } //método OnClick no TextView vermelho de remoção da imagem. public void txtRemoveClick_removeImg(View view){ RemoveImg(); } private void RemoveImg(){ ImageView iv = (ImageView) findViewById(R.id.imageView); Drawable drawable= getResources().getDrawable(R.drawable.img_add); iv.setImageDrawable(drawable); //seta a imagem de seleção de foto do item (imagem padrão) TextView txtRemove = (TextView)findViewById(R.id.txtRemove); imgSelecionada = false; txtRemove.setVisibility(View.GONE); } //método com ação onClick do botão de cadastramento. public void btnCadastra(View view){ //Aqui, chama método que verifica a entrada pelo usuário verificarEntradas(); } private void verificarEntradas(){ //Todos os campos serão obrigatórios, exceto Descrição e imagem. //obrigatórios: Nome do Item e Categoria. //abaixo não tem a variável para imagem porque ela já está acima "bitmap". inputNome = (EditText)findViewById(R.id.inputNome); inputDescri = (EditText)findViewById(R.id.inputDescri); spnCateg = (Spinner)findViewById(R.id.spinnerCateg); //acima pega os valores dos widgets, enquanto abaixo converte-os em String para armazenar no Banco. txtCateg = spnCateg.getSelectedItem().toString(); txtNome = inputNome.getText().toString(); txtDescri = inputDescri.getText().toString(); //fim das variáveis de entrada. if(txtNome == ""){ temNome = false; Toast.makeText(getBaseContext(),"Insira o nome do material.", Toast.LENGTH_LONG).show(); inputNome.requestFocus(); //seta focus no nome. } else if(txtNome !=""){ temNome = true; if(txtCateg ==""){ temCategoria = false; Toast.makeText(getBaseContext(),"Selecione uma categoria do material.", Toast.LENGTH_LONG).show(); spnCateg.requestFocus(); //seta focus na cetogoria. } else if(txtCateg != ""){ temCategoria = true; //depois de verificar todas as entradas (obs: exceto imagem que já é tratada anteriormente) //chama método para inserir os dados na tabela de itens do Banco de Dados "database_sm" if(spnCateg.getSelectedItemPosition() == 0) { Toast.makeText(getBaseContext(),"Selecione uma categoria do material.", Toast.LENGTH_LONG).show(); spnCateg.requestFocus(); //seta focus na cetogoria. } else { if (txtDescri == "") { temDescri = false; checkPermission(); } else if (txtDescri != "") { temDescri = true; checkPermission(); } } } } } private void checkPermission() { // Verifica necessidade de verificacao de permissao if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { // Verifica necessidade de explicar necessidade da permissao if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) { Toast.makeText(this,"É necessário a sua permissão!", Toast.LENGTH_SHORT).show(); ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE }, CODE_PERMISSION); } else { // Solicita permissao ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE}, CODE_PERMISSION); } } inserirDados(); } //monta uma consulta SQL com StringBuilder e append, inserindo os dados de entrada na consulta, e executa-a gravando na //tabela tb_mats da database. private void inserirDados(){ StringBuilder sql = new StringBuilder(); sql.append("INSERT INTO tb_mats(nome_item, img_path, categoria, descri_item, status, descri_emp) VALUES ("); sql.append("'" + txtNome + "',"); if(imgSelecionada) { File selecionada = new File(imgPath); File rootPath = new File(android.os.Environment.getExternalStorageDirectory() + "/security_material/imagens/"); try { if (!rootPath.exists()) { rootPath.mkdirs(); } if (!rootPath.exists()) { rootPath = new File(imgPath); notDirCreat = true; } } catch (Exception erro) { //Toast.makeText(getBaseContext(), "Erro ao criar pasta: " + erro, Toast.LENGTH_LONG).show(); } final File novaImagem = new File(rootPath, selecionada.getName()); //Movemos o arquivo! if(!notDirCreat) { try { moveFile(selecionada, novaImagem); Toast.makeText(getApplicationContext(), "Imagem movida com sucesso!", Toast.LENGTH_SHORT).show(); } catch (IOException e) { e.printStackTrace(); //Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show(); } if (notDirCreat = false) { sql.append("'").append(novaImagem.getPath()).append("',"); } else { sql.append("'" + imgPath + "',"); } }else{ if(!novaImagem.exists()) { if(!novaImagem.exists()){ File newImg = new File(getFilesDir()+"/security_material/img/"+selecionada.getName()); try { moveFile(selecionada, newImg); }catch (Exception ex){} if(!newImg.exists()){ newImg = new File(getFilesDir()+"/"+selecionada.getName()); try { moveFile(selecionada, newImg); }catch (Exception ex){} if(!newImg.exists()){ sql.append("'" + imgPath + "',"); }else{ sql.append("'").append(newImg.getPath()).append("',"); } }else{ sql.append("'").append(newImg.getPath()).append("',"); } } } } } else{ sql.append("'',"); } sql.append("'" + txtCateg + "',"); if (temDescri = false) { sql.append("' ',"); } else{ sql.append("'" + txtDescri + "',"); } sql.append("'Disponível',"); sql.append("''"); sql.append(")"); try { db.execSQL(sql.toString()); limpaEntradas(); //Toast.makeText(getBaseContext(), "Material cadastrado com sucesso!", // Toast.LENGTH_SHORT).show(); } catch (SQLException ex) { //Toast.makeText(getBaseContext(),"Sentimos muito mesmo!!! Tente novamente mais tarde :(", Toast.LENGTH_LONG).show(); } } private void moveFile(File sourceFile, File destFile) throws IOException { if(sourceFile != destFile) { InputStream in = new FileInputStream(sourceFile); OutputStream out = new FileOutputStream(destFile); // Transferindo bytes de entrada para saída byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); imgPath = destFile.getPath(); } else { imgPath = destFile.getPath(); } } //limpa as entradas de dados. public void limpaEntradas(){ spnCateg.setSelection(0); inputDescri.setText(""); inputNome.setText(""); ImageView iv = (ImageView)findViewById(R.id.imageView); Drawable drawable= getResources().getDrawable(R.drawable.img_add); iv.setImageDrawable(drawable); //seta a imagem de seleção de foto do item (imagem padrão) TextView txtRemove = (TextView)findViewById(R.id.txtRemove); txtRemove.setVisibility(View.GONE); //ao terminar cadastro do item, vai para a activity de exibição dos mesmos. Intent intent = new Intent(this, MainActivity.class); startActivity(intent); } public void btnHome(View view){ Intent intent = new Intent(this, MainActivity.class); startActivity(intent); } }
38.689922
143
0.596006
bf1ca1553b5075299138ebaa38008b5941bc9102
357
package com.neusoft; /** * @author liuboting * @date 2020/4/26 19:14 */ public class Phone { //属性:品牌,价格,颜色 String brand; int Price; String color; //方法:打 name 电话,发短信 public void phone(String name){ System.out.println("给" + name + "打电话"); } public void sendMessage(){ System.out.println("发短信"); } }
14.875
47
0.565826
941110c8e63e693dd618086a1f9f2c0d7653edef
7,294
/* * Copyright 2002-2021 Barcelona Supercomputing Center (www.bsc.es) * * 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 es.bsc.compss.scheduler.orderstrict; import es.bsc.compss.components.impl.ResourceScheduler; import es.bsc.compss.components.impl.TaskScheduler; import es.bsc.compss.scheduler.exceptions.BlockedActionException; import es.bsc.compss.scheduler.exceptions.UnassignedActionException; import es.bsc.compss.scheduler.types.AllocatableAction; import es.bsc.compss.scheduler.types.ObjectValue; import es.bsc.compss.scheduler.types.SchedulingInformation; import es.bsc.compss.scheduler.types.Score; import es.bsc.compss.scheduler.types.schedulinginformation.DataLocality; import es.bsc.compss.types.parameter.Parameter; import es.bsc.compss.types.resources.Worker; import es.bsc.compss.types.resources.WorkerResourceDescription; import java.util.List; import java.util.PriorityQueue; import org.json.JSONObject; /** * Representation of a Scheduler that considers only ready tasks. */ public abstract class OrderStrictTS extends TaskScheduler { protected final PriorityQueue<ObjectValue<AllocatableAction>> readyQueue; /** * Constructs a new Ready Scheduler instance. */ public OrderStrictTS() { super(); readyQueue = new PriorityQueue<>(); } /* * ********************************************************************************************************* * ********************************************************************************************************* * ***************************** TASK SCHEDULER STRUCTURES GENERATORS ************************************** * ********************************************************************************************************* * ********************************************************************************************************* */ @Override public abstract <T extends WorkerResourceDescription> ResourceScheduler<T> generateSchedulerForResource(Worker<T> w, JSONObject defaultResources, JSONObject defaultImplementations); @Override public <T extends WorkerResourceDescription> SchedulingInformation generateSchedulingInformation(ResourceScheduler<T> rs, List<Parameter> params, Integer coreId) { return new SchedulingInformation(rs); } /* * ********************************************************************************************************* * ********************************************************************************************************* * ********************************* SCHEDULING OPERATIONS ************************************************* * ********************************************************************************************************* * ********************************************************************************************************* */ private void addActionToReadyQueue(AllocatableAction action, Score actionScore) { ObjectValue<AllocatableAction> obj = new ObjectValue<>(action, actionScore); readyQueue.add(obj); } @Override protected void scheduleAction(AllocatableAction action, Score actionScore) throws BlockedActionException { System.out.println("OSTS - Scheduling action " + action); if (!action.hasDataPredecessors()) { System.out.println("OSTS - NO DEPS"); ObjectValue<AllocatableAction> topReady = readyQueue.peek(); if (topReady == null || actionScore.isBetter(topReady.getScore())) { try { action.schedule(actionScore); } catch (UnassignedActionException uae) { addActionToReadyQueue(action, actionScore); } } else { System.out.println("OSTS - CompatibleWorkers " + action.getCompatibleWorkers()); if (action.getCompatibleWorkers().isEmpty()) { System.out.println("Throws BLocked Exception"); throw new BlockedActionException(); } addActionToReadyQueue(action, actionScore); } } } @Override public final <T extends WorkerResourceDescription> void handleDependencyFreeActions( List<AllocatableAction> dataFreeActions, List<AllocatableAction> resourceFreeActions, List<AllocatableAction> blockedCandidates, ResourceScheduler<T> resource) { PriorityQueue<ObjectValue<AllocatableAction>> executableActions = new PriorityQueue<>(); for (AllocatableAction freeAction : dataFreeActions) { Score actionScore = generateActionScore(freeAction); ObjectValue<AllocatableAction> obj = new ObjectValue<>(freeAction, actionScore); executableActions.add(obj); } // No resourceFreeActions in this kind of scheduler boolean canExecute = true; boolean readyQueueEmpty = readyQueue.isEmpty(); boolean executableActionsEmpty = executableActions.isEmpty(); ObjectValue<AllocatableAction> topPriority = null; while (canExecute && (!executableActionsEmpty || !readyQueueEmpty)) { ObjectValue<AllocatableAction> topReadyQueue = readyQueue.peek(); ObjectValue<AllocatableAction> topExecutableActions = executableActions.peek(); Score topReadyQueueScore = null; Score topExecutableActionsScore = null; if (!readyQueueEmpty) { topReadyQueueScore = topReadyQueue.getScore(); } if (!executableActionsEmpty) { topExecutableActionsScore = topExecutableActions.getScore(); } if (Score.isBetter(topReadyQueueScore, topExecutableActionsScore)) { topPriority = topReadyQueue; } else { topPriority = topExecutableActions; } AllocatableAction aa = topPriority.getObject(); try { aa.schedule(topPriority.getScore()); tryToLaunch(aa); if (topReadyQueue == topPriority) { readyQueue.poll(); readyQueueEmpty = readyQueue.isEmpty(); } else { executableActions.poll(); executableActionsEmpty = executableActions.isEmpty(); } } catch (UnassignedActionException uae) { canExecute = false; } catch (BlockedActionException bae) { this.addToBlocked(aa); } } // Merge both queues in one if (!executableActions.isEmpty()) { readyQueue.addAll(executableActions); } } }
44.206061
120
0.566767
237874d04c746e3915fb5127c2f757776530e1e6
1,018
//(c) British Telecommunications plc, 2009, All Rights Reserved package com.bt.pi.core.cli.commands; import java.io.PrintStream; import java.util.Iterator; import java.util.Map; public class HelpCommand extends KoalaNodeCommand { private Map<String, Command> commandMap; public HelpCommand(Map<String, Command> aCommandMap) { this.commandMap = aCommandMap; } public void execute(PrintStream outputStream) { outputStream.println(String.format("Koala p2p tool")); outputStream.println(String.format("--------------")); outputStream.println(String.format("Usage: <command> [args] where command is one of:\n")); Iterator<String> iter = commandMap.keySet().iterator(); while (iter.hasNext()) { Command c = commandMap.get(iter.next()); outputStream.println(String.format(" %1$-10s", c.getKeyword()) + " - " + c.getDescription()); } outputStream.println(); } public String getDescription() { return "Shows all available commands"; } public String getKeyword() { return "help"; } }
28.277778
98
0.712181
b3c1ccb2a1654e4aafd6d3d22037d2bf7fa39f17
886
package com.zlikun.log.logback; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.CoreConstants; import ch.qos.logback.core.LayoutBase; /** * 自定义Layout组件 * * @author zlikun <zlikun-dev@hotmail.com> * @date 2017/4/29 10:46 */ public class DefaultLayout extends LayoutBase<ILoggingEvent> { public String doLayout(ILoggingEvent event) { StringBuffer sbuf = new StringBuffer(128); sbuf.append(event.getTimeStamp() - event.getLoggerContextVO().getBirthTime()); sbuf.append(" "); sbuf.append(event.getLevel()); sbuf.append(" ["); sbuf.append(event.getThreadName()); sbuf.append("] "); sbuf.append(event.getLoggerName()); sbuf.append(" - "); sbuf.append(event.getFormattedMessage()); sbuf.append(CoreConstants.LINE_SEPARATOR); return sbuf.toString(); } }
29.533333
86
0.662528
721eeb92432d3b93acf4ba487436425d9f979ff1
5,844
package org.firstinspires.ftc.teamcode; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.DcMotorSimple; import com.qualcomm.robotcore.util.ElapsedTime; import com.qualcomm.robotcore.util.Range; public class FunBot extends LinearOpMode { DcMotor Fleft,Fright, BackL,BackR, Lift; double MpH, Speed;; boolean Reverseinput; // public enum VehicleGears // {Neutral,One,Two,Three,four,reverse} // VehicleGears Gears; private ElapsedTime runtime = new ElapsedTime(); public enum VehicleGears {Neutral,One,Two,Three,four,reverse{}; public VehicleGears next(){ return values()[ordinal()+1]; } public VehicleGears previous(){ return values()[ordinal()-1]; } } VehicleGears Gears; public VehicleGears getGears() { /* Controls Gear Up - Right Bumper Gear Down - Left Bumper Accelerate - Right Trigger Brake - Left Trigger Reverse Gear - 1 value on Joystick + Gear down */ if (gamepad1.right_bumper) { UpGears(); } if (gamepad1.left_bumper) { DownGears(); } if (gamepad1.left_bumper && gamepad1.right_stick_y == 1) { Reverseinput = true; DownGears(); } return Gears; } public void UpGears() { if (Gears == VehicleGears.reverse && runtime.seconds() > .5){ Gears = VehicleGears.Neutral; }else if (Gears == VehicleGears.Neutral&& runtime.seconds() > .5){ Gears = VehicleGears.One; }else if (Gears == VehicleGears.One&& runtime.seconds() > .5){ Gears = VehicleGears.Two; }else if (Gears == VehicleGears.Two&& runtime.seconds() > .5){ Gears = VehicleGears.Three; }else if (Gears == VehicleGears.Three&& runtime.seconds() > .5){ Gears = VehicleGears.four; } runtime.reset(); } public void DownGears(){ if (Gears == VehicleGears.four&& runtime.seconds() > .5){ Gears = VehicleGears.Three; }else if (Gears == VehicleGears.Three&& runtime.seconds() > .5){ Gears = VehicleGears.Two; }else if (Gears == VehicleGears.Two&& runtime.seconds() > .5){ Gears = VehicleGears.One; }else if (Gears == VehicleGears.One&& runtime.seconds() > .5){ Gears = VehicleGears.Neutral; }else if (Gears == VehicleGears.Neutral&& runtime.seconds() > .5){ Gears = VehicleGears.reverse; } runtime.reset(); } public double SpeedLegs(){ if (Gears == VehicleGears.One){ Speed = Range.clip(Speed+0.001,0,0.2); }if (Gears == VehicleGears.Two){ Speed = Range.clip(Speed+0.001,0,0.4); }if (Gears == VehicleGears.Three){ Speed = Range.clip(Speed+0.001,0,0.6); }if (Gears == VehicleGears.four){ Speed = Range.clip(Speed+0.001,0,1); }if (Gears == VehicleGears.Neutral){ Speed = Range.clip(Speed+0.001,0,0); }if (Gears == VehicleGears.reverse){ Speed = Range.clip(Speed-0.001,-1,0); } return Speed; } @Override public void runOpMode() throws InterruptedException { //Hardware Mapping Fleft = hardwareMap.dcMotor.get("fleft"); Fright = hardwareMap.dcMotor.get("fright"); BackL = hardwareMap.dcMotor.get("backl"); BackR = hardwareMap.dcMotor.get("backr"); Fright.setDirection(DcMotorSimple.Direction.REVERSE); BackR.setDirection(DcMotorSimple.Direction.REVERSE); telemetry.addLine("Controls"); telemetry.addLine("Gear Up - Right Bumper"); telemetry.addLine("Gear Down - Left Bumper"); telemetry.addLine("Accelerate - Right Trigger"); telemetry.addLine("Brake - Left Trigger"); telemetry.addLine("Reverse Gear - 1 value on Joystick + Gear down"); telemetry.update(); waitForStart(); Gears = VehicleGears.One; /* Controls Gear Up - Right Bumper Gear Down - Left Bumper Accelerate - Right Trigger Brake - Left Trigger Reverse Gear - 1 value on Joystick + Gear down */ while (opModeIsActive()){ SpeedLegs(); if (gamepad1.right_trigger == 1){ MpH = SpeedLegs(); } else if (gamepad1.left_trigger == 1){ MpH = Range.clip(MpH - 0.001, 0,1); }else {MpH = 0;} getGears(); Fright.setPower(MpH); Fleft.setPower(MpH); BackL.setPower(MpH); BackR.setPower(MpH); if (gamepad1.right_stick_y == 1 ){ Fright.setPower(-MpH); Fleft.setPower(MpH); BackL.setPower(MpH); BackR.setPower(-MpH); } if (gamepad1.right_stick_y == -1){ Fright.setPower(MpH); Fleft.setPower(-MpH); BackL.setPower(-MpH); BackR.setPower(MpH); } telemetry.addLine("Controls"); telemetry.addLine("Gear Up - Right Bumper"); telemetry.addLine("Gear Down - Left Bumper"); telemetry.addLine("Accelerate - Right Trigger"); telemetry.addLine("Brake - Left Trigger"); telemetry.addLine("Reverse Gear - 1 value on Joystick + Gear down"); telemetry.addLine("Gear"); telemetry.addData("Current",Gears); telemetry.update(); } } }
34.994012
80
0.55219
07a879d5c62b2db222a709f11e88cff5c09453b3
26,858
/* * Hydrogen Proton API * Financial engineering module of Hydrogen Atom * * OpenAPI spec version: 1.7.18 * Contact: info@hydrogenplatform.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package com.hydrogen.proton.model; import java.util.Objects; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import java.util.UUID; /** * GoalAccumulationAllocationRequest */ @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2020-05-29T05:03:35.524Z") public class GoalAccumulationAllocationRequest { @SerializedName("allocations") private List<UUID> allocations = null; @SerializedName("client_id") private UUID clientId = null; @SerializedName("adjust_for_compounding") private Boolean adjustForCompounding = false; @SerializedName("compounding_rate") private Float compoundingRate = 0.0f; /** * Gets or Sets horizonFrequency */ @JsonAdapter(HorizonFrequencyEnum.Adapter.class) public enum HorizonFrequencyEnum { YEAR("year"), SIX_MONTHS("six_months"), QUARTER("quarter"), MONTH("month"), TWO_WEEKS("two_weeks"), WEEK("week"), DAY("day"); private String value; HorizonFrequencyEnum(String value) { this.value = value; } public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } public static HorizonFrequencyEnum fromValue(String text) { for (HorizonFrequencyEnum b : HorizonFrequencyEnum.values()) { if (String.valueOf(b.value).equals(text)) { return b; } } return null; } public static class Adapter extends TypeAdapter<HorizonFrequencyEnum> { @Override public void write(final JsonWriter jsonWriter, final HorizonFrequencyEnum enumeration) throws IOException { jsonWriter.value(enumeration.getValue()); } @Override public HorizonFrequencyEnum read(final JsonReader jsonReader) throws IOException { String value = jsonReader.nextString(); return HorizonFrequencyEnum.fromValue(String.valueOf(value)); } } } @SerializedName("horizon_frequency") private HorizonFrequencyEnum horizonFrequency = HorizonFrequencyEnum.YEAR; @SerializedName("conf_tgt") private Float confTgt = 0.9f; @SerializedName("risk_score") private BigDecimal riskScore = null; /** * Gets or Sets marketDataSource */ @JsonAdapter(MarketDataSourceEnum.Adapter.class) public enum MarketDataSourceEnum { NUCLEUS("nucleus"), INTEGRATION("integration"); private String value; MarketDataSourceEnum(String value) { this.value = value; } public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } public static MarketDataSourceEnum fromValue(String text) { for (MarketDataSourceEnum b : MarketDataSourceEnum.values()) { if (String.valueOf(b.value).equals(text)) { return b; } } return null; } public static class Adapter extends TypeAdapter<MarketDataSourceEnum> { @Override public void write(final JsonWriter jsonWriter, final MarketDataSourceEnum enumeration) throws IOException { jsonWriter.value(enumeration.getValue()); } @Override public MarketDataSourceEnum read(final JsonReader jsonReader) throws IOException { String value = jsonReader.nextString(); return MarketDataSourceEnum.fromValue(String.valueOf(value)); } } } @SerializedName("market_data_source") private MarketDataSourceEnum marketDataSource = MarketDataSourceEnum.NUCLEUS; @SerializedName("trading_days_per_year") private Integer tradingDaysPerYear = 252; @SerializedName("withdrawal_tax") private Float withdrawalTax = 0.0f; /** * Gets or Sets threshType */ @JsonAdapter(ThreshTypeEnum.Adapter.class) public enum ThreshTypeEnum { AMNT("amnt"), PERC("perc"); private String value; ThreshTypeEnum(String value) { this.value = value; } public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } public static ThreshTypeEnum fromValue(String text) { for (ThreshTypeEnum b : ThreshTypeEnum.values()) { if (String.valueOf(b.value).equals(text)) { return b; } } return null; } public static class Adapter extends TypeAdapter<ThreshTypeEnum> { @Override public void write(final JsonWriter jsonWriter, final ThreshTypeEnum enumeration) throws IOException { jsonWriter.value(enumeration.getValue()); } @Override public ThreshTypeEnum read(final JsonReader jsonReader) throws IOException { String value = jsonReader.nextString(); return ThreshTypeEnum.fromValue(String.valueOf(value)); } } } @SerializedName("thresh_type") private ThreshTypeEnum threshType = ThreshTypeEnum.PERC; /** * Gets or Sets recommendType */ @JsonAdapter(RecommendTypeEnum.Adapter.class) public enum RecommendTypeEnum { RECURRING("recurring"), ONE_TIME("one-time"), COMBO("combo"), HORIZON("horizon"); private String value; RecommendTypeEnum(String value) { this.value = value; } public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } public static RecommendTypeEnum fromValue(String text) { for (RecommendTypeEnum b : RecommendTypeEnum.values()) { if (String.valueOf(b.value).equals(text)) { return b; } } return null; } public static class Adapter extends TypeAdapter<RecommendTypeEnum> { @Override public void write(final JsonWriter jsonWriter, final RecommendTypeEnum enumeration) throws IOException { jsonWriter.value(enumeration.getValue()); } @Override public RecommendTypeEnum read(final JsonReader jsonReader) throws IOException { String value = jsonReader.nextString(); return RecommendTypeEnum.fromValue(String.valueOf(value)); } } } @SerializedName("recommend_type") private RecommendTypeEnum recommendType = RecommendTypeEnum.HORIZON; @SerializedName("goal_id") private UUID goalId = null; @SerializedName("deposit_config") private List<Object> depositConfig = null; @SerializedName("opt_config") private Object optConfig = null; @SerializedName("goal_config") private Object goalConfig = null; @SerializedName("n") private Integer n = 1000; @SerializedName("recommendation_config") private Object recommendationConfig = null; @SerializedName("use_proxy_data") private Boolean useProxyData = false; @SerializedName("thresh") private BigDecimal thresh = null; @SerializedName("curr_inv") private BigDecimal currInv = null; @SerializedName("remove_outliers") private Boolean removeOutliers = true; /** * Gets or Sets allocationPriority */ @JsonAdapter(AllocationPriorityEnum.Adapter.class) public enum AllocationPriorityEnum { GOAL("goal"), RISK("risk"); private String value; AllocationPriorityEnum(String value) { this.value = value; } public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } public static AllocationPriorityEnum fromValue(String text) { for (AllocationPriorityEnum b : AllocationPriorityEnum.values()) { if (String.valueOf(b.value).equals(text)) { return b; } } return null; } public static class Adapter extends TypeAdapter<AllocationPriorityEnum> { @Override public void write(final JsonWriter jsonWriter, final AllocationPriorityEnum enumeration) throws IOException { jsonWriter.value(enumeration.getValue()); } @Override public AllocationPriorityEnum read(final JsonReader jsonReader) throws IOException { String value = jsonReader.nextString(); return AllocationPriorityEnum.fromValue(String.valueOf(value)); } } } @SerializedName("allocation_priority") private AllocationPriorityEnum allocationPriority = null; /** * Gets or Sets allocationMethod */ @JsonAdapter(AllocationMethodEnum.Adapter.class) public enum AllocationMethodEnum { SELECT("select"), CREATE("create"); private String value; AllocationMethodEnum(String value) { this.value = value; } public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } public static AllocationMethodEnum fromValue(String text) { for (AllocationMethodEnum b : AllocationMethodEnum.values()) { if (String.valueOf(b.value).equals(text)) { return b; } } return null; } public static class Adapter extends TypeAdapter<AllocationMethodEnum> { @Override public void write(final JsonWriter jsonWriter, final AllocationMethodEnum enumeration) throws IOException { jsonWriter.value(enumeration.getValue()); } @Override public AllocationMethodEnum read(final JsonReader jsonReader) throws IOException { String value = jsonReader.nextString(); return AllocationMethodEnum.fromValue(String.valueOf(value)); } } } @SerializedName("allocation_method") private AllocationMethodEnum allocationMethod = null; @SerializedName("horizon") private Integer horizon = null; public GoalAccumulationAllocationRequest allocations(List<UUID> allocations) { this.allocations = allocations; return this; } public GoalAccumulationAllocationRequest addAllocationsItem(UUID allocationsItem) { if (this.allocations == null) { this.allocations = new ArrayList<UUID>(); } this.allocations.add(allocationsItem); return this; } /** * Get allocations * @return allocations **/ @ApiModelProperty(value = "") public List<UUID> getAllocations() { return allocations; } public void setAllocations(List<UUID> allocations) { this.allocations = allocations; } public GoalAccumulationAllocationRequest clientId(UUID clientId) { this.clientId = clientId; return this; } /** * Get clientId * @return clientId **/ @ApiModelProperty(value = "") public UUID getClientId() { return clientId; } public void setClientId(UUID clientId) { this.clientId = clientId; } public GoalAccumulationAllocationRequest adjustForCompounding(Boolean adjustForCompounding) { this.adjustForCompounding = adjustForCompounding; return this; } /** * Get adjustForCompounding * @return adjustForCompounding **/ @ApiModelProperty(value = "") public Boolean isAdjustForCompounding() { return adjustForCompounding; } public void setAdjustForCompounding(Boolean adjustForCompounding) { this.adjustForCompounding = adjustForCompounding; } public GoalAccumulationAllocationRequest compoundingRate(Float compoundingRate) { this.compoundingRate = compoundingRate; return this; } /** * Get compoundingRate * minimum: -1 * @return compoundingRate **/ @ApiModelProperty(value = "") public Float getCompoundingRate() { return compoundingRate; } public void setCompoundingRate(Float compoundingRate) { this.compoundingRate = compoundingRate; } public GoalAccumulationAllocationRequest horizonFrequency(HorizonFrequencyEnum horizonFrequency) { this.horizonFrequency = horizonFrequency; return this; } /** * Get horizonFrequency * @return horizonFrequency **/ @ApiModelProperty(value = "") public HorizonFrequencyEnum getHorizonFrequency() { return horizonFrequency; } public void setHorizonFrequency(HorizonFrequencyEnum horizonFrequency) { this.horizonFrequency = horizonFrequency; } public GoalAccumulationAllocationRequest confTgt(Float confTgt) { this.confTgt = confTgt; return this; } /** * Get confTgt * minimum: 0 * maximum: 1 * @return confTgt **/ @ApiModelProperty(value = "") public Float getConfTgt() { return confTgt; } public void setConfTgt(Float confTgt) { this.confTgt = confTgt; } public GoalAccumulationAllocationRequest riskScore(BigDecimal riskScore) { this.riskScore = riskScore; return this; } /** * Get riskScore * minimum: 0 * maximum: 100 * @return riskScore **/ @ApiModelProperty(value = "") public BigDecimal getRiskScore() { return riskScore; } public void setRiskScore(BigDecimal riskScore) { this.riskScore = riskScore; } public GoalAccumulationAllocationRequest marketDataSource(MarketDataSourceEnum marketDataSource) { this.marketDataSource = marketDataSource; return this; } /** * Get marketDataSource * @return marketDataSource **/ @ApiModelProperty(value = "") public MarketDataSourceEnum getMarketDataSource() { return marketDataSource; } public void setMarketDataSource(MarketDataSourceEnum marketDataSource) { this.marketDataSource = marketDataSource; } public GoalAccumulationAllocationRequest tradingDaysPerYear(Integer tradingDaysPerYear) { this.tradingDaysPerYear = tradingDaysPerYear; return this; } /** * Get tradingDaysPerYear * minimum: 1 * maximum: 365 * @return tradingDaysPerYear **/ @ApiModelProperty(value = "") public Integer getTradingDaysPerYear() { return tradingDaysPerYear; } public void setTradingDaysPerYear(Integer tradingDaysPerYear) { this.tradingDaysPerYear = tradingDaysPerYear; } public GoalAccumulationAllocationRequest withdrawalTax(Float withdrawalTax) { this.withdrawalTax = withdrawalTax; return this; } /** * Get withdrawalTax * minimum: 0 * maximum: 1 * @return withdrawalTax **/ @ApiModelProperty(value = "") public Float getWithdrawalTax() { return withdrawalTax; } public void setWithdrawalTax(Float withdrawalTax) { this.withdrawalTax = withdrawalTax; } public GoalAccumulationAllocationRequest threshType(ThreshTypeEnum threshType) { this.threshType = threshType; return this; } /** * Get threshType * @return threshType **/ @ApiModelProperty(value = "") public ThreshTypeEnum getThreshType() { return threshType; } public void setThreshType(ThreshTypeEnum threshType) { this.threshType = threshType; } public GoalAccumulationAllocationRequest recommendType(RecommendTypeEnum recommendType) { this.recommendType = recommendType; return this; } /** * Get recommendType * @return recommendType **/ @ApiModelProperty(value = "") public RecommendTypeEnum getRecommendType() { return recommendType; } public void setRecommendType(RecommendTypeEnum recommendType) { this.recommendType = recommendType; } public GoalAccumulationAllocationRequest goalId(UUID goalId) { this.goalId = goalId; return this; } /** * Get goalId * @return goalId **/ @ApiModelProperty(value = "") public UUID getGoalId() { return goalId; } public void setGoalId(UUID goalId) { this.goalId = goalId; } public GoalAccumulationAllocationRequest depositConfig(List<Object> depositConfig) { this.depositConfig = depositConfig; return this; } public GoalAccumulationAllocationRequest addDepositConfigItem(Object depositConfigItem) { if (this.depositConfig == null) { this.depositConfig = new ArrayList<Object>(); } this.depositConfig.add(depositConfigItem); return this; } /** * Get depositConfig * @return depositConfig **/ @ApiModelProperty(value = "") public List<Object> getDepositConfig() { return depositConfig; } public void setDepositConfig(List<Object> depositConfig) { this.depositConfig = depositConfig; } public GoalAccumulationAllocationRequest optConfig(Object optConfig) { this.optConfig = optConfig; return this; } /** * Get optConfig * @return optConfig **/ @ApiModelProperty(value = "") public Object getOptConfig() { return optConfig; } public void setOptConfig(Object optConfig) { this.optConfig = optConfig; } public GoalAccumulationAllocationRequest goalConfig(Object goalConfig) { this.goalConfig = goalConfig; return this; } /** * Get goalConfig * @return goalConfig **/ @ApiModelProperty(value = "") public Object getGoalConfig() { return goalConfig; } public void setGoalConfig(Object goalConfig) { this.goalConfig = goalConfig; } public GoalAccumulationAllocationRequest n(Integer n) { this.n = n; return this; } /** * Get n * minimum: 1 * maximum: 10000 * @return n **/ @ApiModelProperty(value = "") public Integer getN() { return n; } public void setN(Integer n) { this.n = n; } public GoalAccumulationAllocationRequest recommendationConfig(Object recommendationConfig) { this.recommendationConfig = recommendationConfig; return this; } /** * Get recommendationConfig * @return recommendationConfig **/ @ApiModelProperty(value = "") public Object getRecommendationConfig() { return recommendationConfig; } public void setRecommendationConfig(Object recommendationConfig) { this.recommendationConfig = recommendationConfig; } public GoalAccumulationAllocationRequest useProxyData(Boolean useProxyData) { this.useProxyData = useProxyData; return this; } /** * Get useProxyData * @return useProxyData **/ @ApiModelProperty(value = "") public Boolean isUseProxyData() { return useProxyData; } public void setUseProxyData(Boolean useProxyData) { this.useProxyData = useProxyData; } public GoalAccumulationAllocationRequest thresh(BigDecimal thresh) { this.thresh = thresh; return this; } /** * Get thresh * minimum: 0 * @return thresh **/ @ApiModelProperty(value = "") public BigDecimal getThresh() { return thresh; } public void setThresh(BigDecimal thresh) { this.thresh = thresh; } public GoalAccumulationAllocationRequest currInv(BigDecimal currInv) { this.currInv = currInv; return this; } /** * Get currInv * minimum: 0 * @return currInv **/ @ApiModelProperty(value = "") public BigDecimal getCurrInv() { return currInv; } public void setCurrInv(BigDecimal currInv) { this.currInv = currInv; } public GoalAccumulationAllocationRequest removeOutliers(Boolean removeOutliers) { this.removeOutliers = removeOutliers; return this; } /** * Get removeOutliers * @return removeOutliers **/ @ApiModelProperty(value = "") public Boolean isRemoveOutliers() { return removeOutliers; } public void setRemoveOutliers(Boolean removeOutliers) { this.removeOutliers = removeOutliers; } public GoalAccumulationAllocationRequest allocationPriority(AllocationPriorityEnum allocationPriority) { this.allocationPriority = allocationPriority; return this; } /** * Get allocationPriority * @return allocationPriority **/ @ApiModelProperty(required = true, value = "") public AllocationPriorityEnum getAllocationPriority() { return allocationPriority; } public void setAllocationPriority(AllocationPriorityEnum allocationPriority) { this.allocationPriority = allocationPriority; } public GoalAccumulationAllocationRequest allocationMethod(AllocationMethodEnum allocationMethod) { this.allocationMethod = allocationMethod; return this; } /** * Get allocationMethod * @return allocationMethod **/ @ApiModelProperty(required = true, value = "") public AllocationMethodEnum getAllocationMethod() { return allocationMethod; } public void setAllocationMethod(AllocationMethodEnum allocationMethod) { this.allocationMethod = allocationMethod; } public GoalAccumulationAllocationRequest horizon(Integer horizon) { this.horizon = horizon; return this; } /** * Get horizon * minimum: 0 * maximum: 350 * @return horizon **/ @ApiModelProperty(value = "") public Integer getHorizon() { return horizon; } public void setHorizon(Integer horizon) { this.horizon = horizon; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } GoalAccumulationAllocationRequest goalAccumulationAllocationRequest = (GoalAccumulationAllocationRequest) o; return Objects.equals(this.allocations, goalAccumulationAllocationRequest.allocations) && Objects.equals(this.clientId, goalAccumulationAllocationRequest.clientId) && Objects.equals(this.adjustForCompounding, goalAccumulationAllocationRequest.adjustForCompounding) && Objects.equals(this.compoundingRate, goalAccumulationAllocationRequest.compoundingRate) && Objects.equals(this.horizonFrequency, goalAccumulationAllocationRequest.horizonFrequency) && Objects.equals(this.confTgt, goalAccumulationAllocationRequest.confTgt) && Objects.equals(this.riskScore, goalAccumulationAllocationRequest.riskScore) && Objects.equals(this.marketDataSource, goalAccumulationAllocationRequest.marketDataSource) && Objects.equals(this.tradingDaysPerYear, goalAccumulationAllocationRequest.tradingDaysPerYear) && Objects.equals(this.withdrawalTax, goalAccumulationAllocationRequest.withdrawalTax) && Objects.equals(this.threshType, goalAccumulationAllocationRequest.threshType) && Objects.equals(this.recommendType, goalAccumulationAllocationRequest.recommendType) && Objects.equals(this.goalId, goalAccumulationAllocationRequest.goalId) && Objects.equals(this.depositConfig, goalAccumulationAllocationRequest.depositConfig) && Objects.equals(this.optConfig, goalAccumulationAllocationRequest.optConfig) && Objects.equals(this.goalConfig, goalAccumulationAllocationRequest.goalConfig) && Objects.equals(this.n, goalAccumulationAllocationRequest.n) && Objects.equals(this.recommendationConfig, goalAccumulationAllocationRequest.recommendationConfig) && Objects.equals(this.useProxyData, goalAccumulationAllocationRequest.useProxyData) && Objects.equals(this.thresh, goalAccumulationAllocationRequest.thresh) && Objects.equals(this.currInv, goalAccumulationAllocationRequest.currInv) && Objects.equals(this.removeOutliers, goalAccumulationAllocationRequest.removeOutliers) && Objects.equals(this.allocationPriority, goalAccumulationAllocationRequest.allocationPriority) && Objects.equals(this.allocationMethod, goalAccumulationAllocationRequest.allocationMethod) && Objects.equals(this.horizon, goalAccumulationAllocationRequest.horizon); } @Override public int hashCode() { return Objects.hash(allocations, clientId, adjustForCompounding, compoundingRate, horizonFrequency, confTgt, riskScore, marketDataSource, tradingDaysPerYear, withdrawalTax, threshType, recommendType, goalId, depositConfig, optConfig, goalConfig, n, recommendationConfig, useProxyData, thresh, currInv, removeOutliers, allocationPriority, allocationMethod, horizon); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class GoalAccumulationAllocationRequest {\n"); sb.append(" allocations: ").append(toIndentedString(allocations)).append("\n"); sb.append(" clientId: ").append(toIndentedString(clientId)).append("\n"); sb.append(" adjustForCompounding: ").append(toIndentedString(adjustForCompounding)).append("\n"); sb.append(" compoundingRate: ").append(toIndentedString(compoundingRate)).append("\n"); sb.append(" horizonFrequency: ").append(toIndentedString(horizonFrequency)).append("\n"); sb.append(" confTgt: ").append(toIndentedString(confTgt)).append("\n"); sb.append(" riskScore: ").append(toIndentedString(riskScore)).append("\n"); sb.append(" marketDataSource: ").append(toIndentedString(marketDataSource)).append("\n"); sb.append(" tradingDaysPerYear: ").append(toIndentedString(tradingDaysPerYear)).append("\n"); sb.append(" withdrawalTax: ").append(toIndentedString(withdrawalTax)).append("\n"); sb.append(" threshType: ").append(toIndentedString(threshType)).append("\n"); sb.append(" recommendType: ").append(toIndentedString(recommendType)).append("\n"); sb.append(" goalId: ").append(toIndentedString(goalId)).append("\n"); sb.append(" depositConfig: ").append(toIndentedString(depositConfig)).append("\n"); sb.append(" optConfig: ").append(toIndentedString(optConfig)).append("\n"); sb.append(" goalConfig: ").append(toIndentedString(goalConfig)).append("\n"); sb.append(" n: ").append(toIndentedString(n)).append("\n"); sb.append(" recommendationConfig: ").append(toIndentedString(recommendationConfig)).append("\n"); sb.append(" useProxyData: ").append(toIndentedString(useProxyData)).append("\n"); sb.append(" thresh: ").append(toIndentedString(thresh)).append("\n"); sb.append(" currInv: ").append(toIndentedString(currInv)).append("\n"); sb.append(" removeOutliers: ").append(toIndentedString(removeOutliers)).append("\n"); sb.append(" allocationPriority: ").append(toIndentedString(allocationPriority)).append("\n"); sb.append(" allocationMethod: ").append(toIndentedString(allocationMethod)).append("\n"); sb.append(" horizon: ").append(toIndentedString(horizon)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
27.490276
369
0.702733
2544a37e7f9e7f4c98fb6443878af510e937dd9c
1,156
import config.SpringConfig; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; import service.DogService; /** * ClassName: Main * Function: TODO * Date: 2019/12/15 19:17 * author 14746 * version V1.0 */ public class Main { public static void beanFactory(){ // XmlBeanFactory bf = new XmlBeanFactory(new ClassPathResource("application.xml")); // DogService dog = bf.getBean(DogService.class); // dog.say("hello"); // return; } public static void application(){ AnnotationConfigApplicationContext bf = new AnnotationConfigApplicationContext(SpringConfig.class); DogService dog = bf.getBean(DogService.class); System.out.println("`````````"); dog.say("123"); System.out.println("`````````"); bf.close(); return ; } public static void main(String[] args) { application(); } }
28.9
101
0.741349
806af9fc3d5b9091a7da885ac7145ae61197f689
14,360
/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2020. All rights reserved. */ package com.huawei.bigdata.flink.examples; import com.huawei.bigdata.security.LoginUtil; import redis.clients.jedis.HostAndPort; import redis.clients.jedis.JedisCluster; import org.apache.flink.api.common.functions.FilterFunction; import org.apache.flink.api.common.functions.MapFunction; import org.apache.flink.api.common.functions.ReduceFunction; import org.apache.flink.api.java.functions.KeySelector; import org.apache.flink.api.java.utils.ParameterTool; import org.apache.flink.configuration.Configuration; import org.apache.flink.shaded.guava18.com.google.common.cache.CacheBuilder; import org.apache.flink.shaded.guava18.com.google.common.cache.CacheLoader; import org.apache.flink.shaded.guava18.com.google.common.cache.LoadingCache; import org.apache.flink.streaming.api.datastream.AsyncDataStream; import org.apache.flink.streaming.api.datastream.DataStream; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.streaming.api.functions.AssignerWithPunctuatedWatermarks; import org.apache.flink.streaming.api.functions.async.AsyncFunction; import org.apache.flink.streaming.api.functions.async.ResultFuture; import org.apache.flink.streaming.api.functions.async.RichAsyncFunction; import org.apache.flink.streaming.api.watermark.Watermark; import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows; import org.apache.flink.streaming.api.windowing.time.Time; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; /** * Read stream data and join from configure table from redis. * * @since 8.0.2 */ public class FlinkConfigtableJavaExample { private static final int TIMEOUT = 60000; /** * @param args args * @throws Exception */ public static void main(String[] args) throws Exception { // print comment for command to use run flink System.out.println("use command as: \n" + "./bin/flink run --class com.huawei.bigdata.flink.examples.FlinkConfigtableJavaExample" + " -m yarn-cluster -yt /opt/config -yn 3 -yjm 1024 -ytm 1024 " + "/opt/FlinkConfigtableJavaExample.jar --dataPath config/data.txt" + "******************************************************************************************\n" + "Especially you may write following content into config filePath, as in config/read.properties: \n" + "ReadFields=username,age,company,workLocation,educational,workYear,phone,nativeLocation,school\n" + "Redis_Security=true\n" + "Redis_IP_Port=SZV1000064084:22400,SZV1000064082:22400,SZV1000064085:22400\n" + "Redis_Principal=test11@HADOOP.COM\n" + "Redis_KeytabFile=config/user.keytab\n" + "Redis_Krb5File=config/krb5.conf\n" + "******************************************************************************************"); // set up the execution environment final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.getConfig().setAutoWatermarkInterval(200); env.setParallelism(1); // get configure and read data and transform to OriginalRecord final String dataPath = ParameterTool.fromArgs(args).get("dataPath", "config/data.txt"); DataStream<OriginalRecord> originalStream = env.readTextFile( dataPath ).map(new MapFunction<String, OriginalRecord>() { @Override public OriginalRecord map(String value) throws Exception { return getRecord(value); } }).assignTimestampsAndWatermarks( new Record2TimestampExtractor() ).disableChaining(); // read from redis and join to the whole user information AsyncFunction<OriginalRecord, UserRecord> function = new AsyncRedisRequest(); // timeout set to 2 minutes, max parallel request num set to 5, you can modify this to optimize DataStream<UserRecord> result = AsyncDataStream.unorderedWait(originalStream, function, 2, TimeUnit.MINUTES, 5); // data transform result.filter(new FilterFunction<UserRecord>() { @Override public boolean filter(UserRecord value) throws Exception { return value.sexy.equals("female"); } }).keyBy( new UserRecordSelector() ).window( TumblingEventTimeWindows.of(Time.seconds(30)) ).reduce(new ReduceFunction<UserRecord>() { @Override public UserRecord reduce(UserRecord value1, UserRecord value2) throws Exception { value1.shoppingTime += value2.shoppingTime; return value1; } }).filter(new FilterFunction<UserRecord>() { @Override public boolean filter(UserRecord value) throws Exception { return value.shoppingTime > 120; } }).print(); // execute program env.execute("FlinkConfigtable java"); } private static class UserRecordSelector implements KeySelector<UserRecord, String> { @Override public String getKey(UserRecord value) throws Exception { return value.name; } } // class to set watermark and timestamp private static class Record2TimestampExtractor implements AssignerWithPunctuatedWatermarks<OriginalRecord> { // add tag in the data of datastream elements @Override public long extractTimestamp(OriginalRecord element, long previousTimestamp) { return System.currentTimeMillis(); } // give the watermark to trigger the window to execute, and use the // value to check if the window elements is ready @Override public Watermark checkAndGetNextWatermark(OriginalRecord element, long extractedTimestamp) { return new Watermark(extractedTimestamp - 1); } } private static OriginalRecord getRecord(String line) { String[] elems = line.split(","); assert elems.length == 3; return new OriginalRecord(elems[0], elems[1], Integer.parseInt(elems[2])); } /** * @since 8.0.2 */ public static class OriginalRecord { private String name; private String sexy; private int shoppingTime; public OriginalRecord(String nm, String sx, int st) { name = nm; sexy = sx; shoppingTime = st; } } /** * @since 8.0.2 */ public static class UserRecord { private String name; private int age; private String company; private String workLocation; private String educational; private int workYear; private String phone; private String nativeLocation; private String school; private String sexy; private int shoppingTime; public UserRecord(String nm, int ag, String com, String wl, String ed, int wy, String ph, String nl, String sc, String sx, int st) { name = nm; age = ag; company = com; workLocation = wl; educational = ed; workYear = wy; phone = ph; nativeLocation = nl; school = sc; sexy = sx; shoppingTime = st; } /** * @param input_nm input_nm * @param input_sx input_sx * @param input_st input_st */ public void setInput(String input_nm, String input_sx, int input_st) { name = input_nm; sexy = input_sx; shoppingTime = input_st; } /** * @return string */ public String toString() { return "UserRecord-----name: " + name + " age: " + age + " company: " + company + " workLocation: " + workLocation + " educational: " + educational + " workYear: " + workYear + " phone: " + phone + " nativeLocation: " + nativeLocation + " school: " + school + " sexy: " + sexy + " shoppingTime: " + shoppingTime; } } /** * @since 8.0.2 */ public static class AsyncRedisRequest extends RichAsyncFunction<OriginalRecord, UserRecord> { private String fields = ""; private transient JedisCluster client; private LoadingCache<String, UserRecord> cacheRecords; /** * @param parameters parameters * @throws Exception */ @Override public void open(Configuration parameters) throws Exception { super.open(parameters); // init cache builder cacheRecords = CacheBuilder.newBuilder() .maximumSize(10000) .expireAfterAccess(7, TimeUnit.DAYS) .build(new CacheLoader<String, UserRecord>() { /** * @param key key * @return cache from redis * @throws Exception */ public UserRecord load(String key) throws Exception { // load from redis return loadFromRedis(key); } }); // get configure from config/read.properties, you must put this with commands: // ./bin/yarn-session.sh -t config -n 3 -jm 1024 -tm 1024 or // ./bin/flink run -m yarn-cluster -yt config -yn 3 -yjm 1024 -ytm 1024 /opt/test.jar String configPath = "config/read.properties"; fields = ParameterTool.fromPropertiesFile(configPath).get("ReadFields"); final boolean isSecurity = ParameterTool.fromPropertiesFile(configPath).getBoolean("Redis_Security", true); final String hostPort = ParameterTool.fromPropertiesFile(configPath).get("Redis_IP_Port"); final String principal = ParameterTool.fromPropertiesFile(configPath).get("Redis_Principal"); final String keytab = ParameterTool.fromPropertiesFile(configPath).get("Redis_KeytabFile"); final String krb5 = ParameterTool.fromPropertiesFile(configPath).get("Redis_Krb5File"); final boolean ssl = ParameterTool.fromPropertiesFile(configPath).getBoolean("Redis_ssl_on", false); // init redis security mode System.setProperty("redis.authentication.jaas", isSecurity ? "true" : "false"); if (System.getProperty("redis.authentication.jaas", "false").equals("true")) { LoginUtil.setJaasFile(principal, keytab); LoginUtil.setKrb5Config(krb5); } // create jedisCluster client Set<HostAndPort> hosts = new HashSet<HostAndPort>(); for (String node : hostPort.split(",")) { HostAndPort hostAndPort = genHostAndPort(node); if (hostAndPort == null) { continue; } hosts.add(hostAndPort); } client = new JedisCluster(hosts, TIMEOUT); System.out.println("JedisCluster init, getClusterNodes: " + client.getClusterNodes().size()); } /** * @param ipAndPort ipAndPort * @return host and port */ private HostAndPort genHostAndPort(String ipAndPort) { int lastIdx = ipAndPort.lastIndexOf(":"); if (lastIdx == -1) { return null; } String ip = ipAndPort.substring(0, lastIdx); String port = ipAndPort.substring(lastIdx + 1); return new HostAndPort(ip, Integer.parseInt(port)); } /** * @throws Exception */ @Override public void close() throws Exception { super.close(); if (client != null) { System.out.println("JedisCluster close!!!"); client.close(); } } /** * @param key key * @return user record * @throws Exception */ public UserRecord loadFromRedis(final String key) throws Exception { if (client.getClusterNodes().size() <= 0) { System.out.println("JedisCluster init failed, getClusterNodes: " + client.getClusterNodes().size()); } if (!client.exists(key)) { System.out.println("test-------cannot find data to key: " + key); return new UserRecord("null", 0, "null", "null", "null", 0, "null", "null", "null", "null", 0); } else { // get some fields List<String> values = client.hmget(key, fields.split(",")); System.out.println("test-------key: " + key + " get some fields: " + values.toString()); return new UserRecord( values.get(0), Integer.parseInt(values.get(1)), values.get(2), values.get(3), values.get(4), Integer.parseInt(values.get(5)), values.get(6), values.get(7), values.get(8), "null", 0); } } /** * @param input input * @param resultFuture resultFuture * @throws Exception */ public void asyncInvoke(final OriginalRecord input, final ResultFuture<UserRecord> resultFuture) throws Exception { // set key string, if you key is more than one column, build your key string with columns String key = input.name; UserRecord info = cacheRecords.get(key); info.setInput(input.name, input.sexy, input.shoppingTime); resultFuture.complete(Collections.singletonList(info)); } } }
40.679887
120
0.583914
e96c7ef931e23bbf876e85aa7ec597117da4357f
994
package br.com.pocobserver.dto; import java.io.Serializable; import java.time.LocalDate; /** * DTO do Usuário * * @author Bruno Eduardo */ public class UsuarioDTO implements Serializable { /** * */ private static final long serialVersionUID = 1L; /** * ID */ private Integer idUsuario; /** * Nome */ private String nmUsuario; /** * Data de nascimento */ private LocalDate dtNascimento; public Integer getIdUsuario() { return idUsuario; } public void setIdUsuario(final Integer idUsuario) { this.idUsuario = idUsuario; } public String getNmUsuario() { return nmUsuario; } public void setNmUsuario(final String nmUsuario) { this.nmUsuario = nmUsuario; } public LocalDate getDtNascimento() { return dtNascimento; } public void setDtNascimento(final LocalDate dtNascimento) { this.dtNascimento = dtNascimento; } }
17.438596
63
0.619718
a135440d0166115146ccda4ed1cb1560c7a47e4f
6,426
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.aliyuncs.ecs.transform.v20140526; import java.util.ArrayList; import java.util.List; import com.aliyuncs.ecs.model.v20140526.DescribeDedicatedHostClustersResponse; import com.aliyuncs.ecs.model.v20140526.DescribeDedicatedHostClustersResponse.DedicatedHostCluster; import com.aliyuncs.ecs.model.v20140526.DescribeDedicatedHostClustersResponse.DedicatedHostCluster.DedicatedHostClusterCapacity; import com.aliyuncs.ecs.model.v20140526.DescribeDedicatedHostClustersResponse.DedicatedHostCluster.DedicatedHostClusterCapacity.LocalStorageCapacity; import com.aliyuncs.ecs.model.v20140526.DescribeDedicatedHostClustersResponse.DedicatedHostCluster.Tag; import com.aliyuncs.transform.UnmarshallerContext; public class DescribeDedicatedHostClustersResponseUnmarshaller { public static DescribeDedicatedHostClustersResponse unmarshall(DescribeDedicatedHostClustersResponse describeDedicatedHostClustersResponse, UnmarshallerContext _ctx) { describeDedicatedHostClustersResponse.setRequestId(_ctx.stringValue("DescribeDedicatedHostClustersResponse.RequestId")); describeDedicatedHostClustersResponse.setTotalCount(_ctx.integerValue("DescribeDedicatedHostClustersResponse.TotalCount")); describeDedicatedHostClustersResponse.setPageNumber(_ctx.integerValue("DescribeDedicatedHostClustersResponse.PageNumber")); describeDedicatedHostClustersResponse.setPageSize(_ctx.integerValue("DescribeDedicatedHostClustersResponse.PageSize")); List<DedicatedHostCluster> dedicatedHostClusters = new ArrayList<DedicatedHostCluster>(); for (int i = 0; i < _ctx.lengthValue("DescribeDedicatedHostClustersResponse.DedicatedHostClusters.Length"); i++) { DedicatedHostCluster dedicatedHostCluster = new DedicatedHostCluster(); dedicatedHostCluster.setDedicatedHostClusterId(_ctx.stringValue("DescribeDedicatedHostClustersResponse.DedicatedHostClusters["+ i +"].DedicatedHostClusterId")); dedicatedHostCluster.setRegionId(_ctx.stringValue("DescribeDedicatedHostClustersResponse.DedicatedHostClusters["+ i +"].RegionId")); dedicatedHostCluster.setZoneId(_ctx.stringValue("DescribeDedicatedHostClustersResponse.DedicatedHostClusters["+ i +"].ZoneId")); dedicatedHostCluster.setDedicatedHostClusterName(_ctx.stringValue("DescribeDedicatedHostClustersResponse.DedicatedHostClusters["+ i +"].DedicatedHostClusterName")); dedicatedHostCluster.setDescription(_ctx.stringValue("DescribeDedicatedHostClustersResponse.DedicatedHostClusters["+ i +"].Description")); dedicatedHostCluster.setResourceGroupId(_ctx.stringValue("DescribeDedicatedHostClustersResponse.DedicatedHostClusters["+ i +"].ResourceGroupId")); List<String> dedicatedHostIds = new ArrayList<String>(); for (int j = 0; j < _ctx.lengthValue("DescribeDedicatedHostClustersResponse.DedicatedHostClusters["+ i +"].DedicatedHostIds.Length"); j++) { dedicatedHostIds.add(_ctx.stringValue("DescribeDedicatedHostClustersResponse.DedicatedHostClusters["+ i +"].DedicatedHostIds["+ j +"]")); } dedicatedHostCluster.setDedicatedHostIds(dedicatedHostIds); DedicatedHostClusterCapacity dedicatedHostClusterCapacity = new DedicatedHostClusterCapacity(); dedicatedHostClusterCapacity.setTotalVcpus(_ctx.integerValue("DescribeDedicatedHostClustersResponse.DedicatedHostClusters["+ i +"].DedicatedHostClusterCapacity.TotalVcpus")); dedicatedHostClusterCapacity.setAvailableVcpus(_ctx.integerValue("DescribeDedicatedHostClustersResponse.DedicatedHostClusters["+ i +"].DedicatedHostClusterCapacity.AvailableVcpus")); dedicatedHostClusterCapacity.setTotalMemory(_ctx.integerValue("DescribeDedicatedHostClustersResponse.DedicatedHostClusters["+ i +"].DedicatedHostClusterCapacity.TotalMemory")); dedicatedHostClusterCapacity.setAvailableMemory(_ctx.integerValue("DescribeDedicatedHostClustersResponse.DedicatedHostClusters["+ i +"].DedicatedHostClusterCapacity.AvailableMemory")); List<LocalStorageCapacity> localStorageCapacities = new ArrayList<LocalStorageCapacity>(); for (int j = 0; j < _ctx.lengthValue("DescribeDedicatedHostClustersResponse.DedicatedHostClusters["+ i +"].DedicatedHostClusterCapacity.LocalStorageCapacities.Length"); j++) { LocalStorageCapacity localStorageCapacity = new LocalStorageCapacity(); localStorageCapacity.setTotalDisk(_ctx.integerValue("DescribeDedicatedHostClustersResponse.DedicatedHostClusters["+ i +"].DedicatedHostClusterCapacity.LocalStorageCapacities["+ j +"].TotalDisk")); localStorageCapacity.setAvailableDisk(_ctx.integerValue("DescribeDedicatedHostClustersResponse.DedicatedHostClusters["+ i +"].DedicatedHostClusterCapacity.LocalStorageCapacities["+ j +"].AvailableDisk")); localStorageCapacity.setDataDiskCategory(_ctx.stringValue("DescribeDedicatedHostClustersResponse.DedicatedHostClusters["+ i +"].DedicatedHostClusterCapacity.LocalStorageCapacities["+ j +"].DataDiskCategory")); localStorageCapacities.add(localStorageCapacity); } dedicatedHostClusterCapacity.setLocalStorageCapacities(localStorageCapacities); dedicatedHostCluster.setDedicatedHostClusterCapacity(dedicatedHostClusterCapacity); List<Tag> tags = new ArrayList<Tag>(); for (int j = 0; j < _ctx.lengthValue("DescribeDedicatedHostClustersResponse.DedicatedHostClusters["+ i +"].Tags.Length"); j++) { Tag tag = new Tag(); tag.setTagKey(_ctx.stringValue("DescribeDedicatedHostClustersResponse.DedicatedHostClusters["+ i +"].Tags["+ j +"].TagKey")); tag.setTagValue(_ctx.stringValue("DescribeDedicatedHostClustersResponse.DedicatedHostClusters["+ i +"].Tags["+ j +"].TagValue")); tags.add(tag); } dedicatedHostCluster.setTags(tags); dedicatedHostClusters.add(dedicatedHostCluster); } describeDedicatedHostClustersResponse.setDedicatedHostClusters(dedicatedHostClusters); return describeDedicatedHostClustersResponse; } }
73.862069
214
0.821506
8ee9b0c087584bede69afc4c5c9dcf3e62c374b8
18,552
/* * Kubernetes * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: v1.18.2 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package it.reply.orchestrator.dto.kubernetes.fluxcd; import java.util.Objects; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * V1HelmReleaseSpec */ @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-10-16T10:28:05.581Z[Etc/UTC]") public class V1HelmReleaseSpec { public static final String SERIALIZED_NAME_CHART = "chart"; @SerializedName(SERIALIZED_NAME_CHART) private V1HelmReleaseSpecChart chart; public static final String SERIALIZED_NAME_DISABLE_OPEN_A_P_I_VALIDATION = "disableOpenAPIValidation"; @SerializedName(SERIALIZED_NAME_DISABLE_OPEN_A_P_I_VALIDATION) private Boolean disableOpenAPIValidation; public static final String SERIALIZED_NAME_FORCE_UPGRADE = "forceUpgrade"; @SerializedName(SERIALIZED_NAME_FORCE_UPGRADE) private Boolean forceUpgrade; /** * HelmVersion is the version of Helm to target. If not supplied, the lowest _enabled Helm version_ will be targeted. Valid HelmVersion values are: \&quot;v2\&quot;, \&quot;v3\&quot; */ @JsonAdapter(HelmVersionEnum.Adapter.class) public enum HelmVersionEnum { V2("v2"), V3("v3"); private String value; HelmVersionEnum(String value) { this.value = value; } public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } public static HelmVersionEnum fromValue(String value) { for (HelmVersionEnum b : HelmVersionEnum.values()) { if (b.value.equals(value)) { return b; } } throw new IllegalArgumentException("Unexpected value '" + value + "'"); } public static class Adapter extends TypeAdapter<HelmVersionEnum> { @Override public void write(final JsonWriter jsonWriter, final HelmVersionEnum enumeration) throws IOException { jsonWriter.value(enumeration.getValue()); } @Override public HelmVersionEnum read(final JsonReader jsonReader) throws IOException { String value = jsonReader.nextString(); return HelmVersionEnum.fromValue(value); } } } public static final String SERIALIZED_NAME_HELM_VERSION = "helmVersion"; @SerializedName(SERIALIZED_NAME_HELM_VERSION) private HelmVersionEnum helmVersion; public static final String SERIALIZED_NAME_MAX_HISTORY = "maxHistory"; @SerializedName(SERIALIZED_NAME_MAX_HISTORY) private Integer maxHistory; public static final String SERIALIZED_NAME_RELEASE_NAME = "releaseName"; @SerializedName(SERIALIZED_NAME_RELEASE_NAME) private String releaseName; public static final String SERIALIZED_NAME_RESET_VALUES = "resetValues"; @SerializedName(SERIALIZED_NAME_RESET_VALUES) private Boolean resetValues; public static final String SERIALIZED_NAME_ROLLBACK = "rollback"; @SerializedName(SERIALIZED_NAME_ROLLBACK) private V1HelmReleaseSpecRollback rollback; public static final String SERIALIZED_NAME_SKIP_C_R_DS = "skipCRDs"; @SerializedName(SERIALIZED_NAME_SKIP_C_R_DS) private Boolean skipCRDs; public static final String SERIALIZED_NAME_TARGET_NAMESPACE = "targetNamespace"; @SerializedName(SERIALIZED_NAME_TARGET_NAMESPACE) private String targetNamespace; public static final String SERIALIZED_NAME_TEST = "test"; @SerializedName(SERIALIZED_NAME_TEST) private V1HelmReleaseSpecTest test; public static final String SERIALIZED_NAME_TIMEOUT = "timeout"; @SerializedName(SERIALIZED_NAME_TIMEOUT) private Long timeout; public static final String SERIALIZED_NAME_VALUE_FILE_SECRETS = "valueFileSecrets"; @SerializedName(SERIALIZED_NAME_VALUE_FILE_SECRETS) private List<V1HelmReleaseSpecValueFileSecrets> valueFileSecrets = null; public static final String SERIALIZED_NAME_VALUES = "values"; @SerializedName(SERIALIZED_NAME_VALUES) private Object values; public static final String SERIALIZED_NAME_VALUES_FROM = "valuesFrom"; @SerializedName(SERIALIZED_NAME_VALUES_FROM) private List<V1HelmReleaseSpecValuesFrom> valuesFrom = null; public static final String SERIALIZED_NAME_WAIT = "wait"; @SerializedName(SERIALIZED_NAME_WAIT) private Boolean wait; public V1HelmReleaseSpec chart(V1HelmReleaseSpecChart chart) { this.chart = chart; return this; } /** * Get chart * @return chart **/ @ApiModelProperty(required = true, value = "") public V1HelmReleaseSpecChart getChart() { return chart; } public void setChart(V1HelmReleaseSpecChart chart) { this.chart = chart; } public V1HelmReleaseSpec disableOpenAPIValidation(Boolean disableOpenAPIValidation) { this.disableOpenAPIValidation = disableOpenAPIValidation; return this; } /** * DisableOpenAPIValidation controls whether OpenAPI validation is enforced. * @return disableOpenAPIValidation **/ @javax.annotation.Nullable @ApiModelProperty(value = "DisableOpenAPIValidation controls whether OpenAPI validation is enforced.") public Boolean getDisableOpenAPIValidation() { return disableOpenAPIValidation; } public void setDisableOpenAPIValidation(Boolean disableOpenAPIValidation) { this.disableOpenAPIValidation = disableOpenAPIValidation; } public V1HelmReleaseSpec forceUpgrade(Boolean forceUpgrade) { this.forceUpgrade = forceUpgrade; return this; } /** * Force will mark this Helm release to &#x60;--force&#x60; upgrades. This forces the resource updates through delete/recreate if needed. * @return forceUpgrade **/ @javax.annotation.Nullable @ApiModelProperty(value = "Force will mark this Helm release to `--force` upgrades. This forces the resource updates through delete/recreate if needed.") public Boolean getForceUpgrade() { return forceUpgrade; } public void setForceUpgrade(Boolean forceUpgrade) { this.forceUpgrade = forceUpgrade; } public V1HelmReleaseSpec helmVersion(HelmVersionEnum helmVersion) { this.helmVersion = helmVersion; return this; } /** * HelmVersion is the version of Helm to target. If not supplied, the lowest _enabled Helm version_ will be targeted. Valid HelmVersion values are: \&quot;v2\&quot;, \&quot;v3\&quot; * @return helmVersion **/ @javax.annotation.Nullable @ApiModelProperty(value = "HelmVersion is the version of Helm to target. If not supplied, the lowest _enabled Helm version_ will be targeted. Valid HelmVersion values are: \"v2\", \"v3\"") public HelmVersionEnum getHelmVersion() { return helmVersion; } public void setHelmVersion(HelmVersionEnum helmVersion) { this.helmVersion = helmVersion; } public V1HelmReleaseSpec maxHistory(Integer maxHistory) { this.maxHistory = maxHistory; return this; } /** * MaxHistory is the maximum amount of revisions to keep for the Helm release. If not supplied, it defaults to 10. * @return maxHistory **/ @javax.annotation.Nullable @ApiModelProperty(value = "MaxHistory is the maximum amount of revisions to keep for the Helm release. If not supplied, it defaults to 10.") public Integer getMaxHistory() { return maxHistory; } public void setMaxHistory(Integer maxHistory) { this.maxHistory = maxHistory; } public V1HelmReleaseSpec releaseName(String releaseName) { this.releaseName = releaseName; return this; } /** * ReleaseName is the name of the The Helm release. If not supplied, it will be generated by affixing the namespace to the resource name. * @return releaseName **/ @javax.annotation.Nullable @ApiModelProperty(value = "ReleaseName is the name of the The Helm release. If not supplied, it will be generated by affixing the namespace to the resource name.") public String getReleaseName() { return releaseName; } public void setReleaseName(String releaseName) { this.releaseName = releaseName; } public V1HelmReleaseSpec resetValues(Boolean resetValues) { this.resetValues = resetValues; return this; } /** * ResetValues will mark this Helm release to reset the values to the defaults of the targeted chart before performing an upgrade. Not explicitly setting this to &#x60;false&#x60; equals to &#x60;true&#x60; due to the declarative nature of the operator. * @return resetValues **/ @javax.annotation.Nullable @ApiModelProperty(value = "ResetValues will mark this Helm release to reset the values to the defaults of the targeted chart before performing an upgrade. Not explicitly setting this to `false` equals to `true` due to the declarative nature of the operator.") public Boolean getResetValues() { return resetValues; } public void setResetValues(Boolean resetValues) { this.resetValues = resetValues; } public V1HelmReleaseSpec rollback(V1HelmReleaseSpecRollback rollback) { this.rollback = rollback; return this; } /** * Get rollback * @return rollback **/ @javax.annotation.Nullable @ApiModelProperty(value = "") public V1HelmReleaseSpecRollback getRollback() { return rollback; } public void setRollback(V1HelmReleaseSpecRollback rollback) { this.rollback = rollback; } public V1HelmReleaseSpec skipCRDs(Boolean skipCRDs) { this.skipCRDs = skipCRDs; return this; } /** * SkipCRDs will mark this Helm release to skip the creation of CRDs during a Helm 3 installation. * @return skipCRDs **/ @javax.annotation.Nullable @ApiModelProperty(value = "SkipCRDs will mark this Helm release to skip the creation of CRDs during a Helm 3 installation.") public Boolean getSkipCRDs() { return skipCRDs; } public void setSkipCRDs(Boolean skipCRDs) { this.skipCRDs = skipCRDs; } public V1HelmReleaseSpec targetNamespace(String targetNamespace) { this.targetNamespace = targetNamespace; return this; } /** * TargetNamespace overrides the targeted namespace for the Helm release. The default namespace equals to the namespace of the HelmRelease resource. * @return targetNamespace **/ @javax.annotation.Nullable @ApiModelProperty(value = "TargetNamespace overrides the targeted namespace for the Helm release. The default namespace equals to the namespace of the HelmRelease resource.") public String getTargetNamespace() { return targetNamespace; } public void setTargetNamespace(String targetNamespace) { this.targetNamespace = targetNamespace; } public V1HelmReleaseSpec test(V1HelmReleaseSpecTest test) { this.test = test; return this; } /** * Get test * @return test **/ @javax.annotation.Nullable @ApiModelProperty(value = "") public V1HelmReleaseSpecTest getTest() { return test; } public void setTest(V1HelmReleaseSpecTest test) { this.test = test; } public V1HelmReleaseSpec timeout(Long timeout) { this.timeout = timeout; return this; } /** * Timeout is the time to wait for any individual Kubernetes operation (like Jobs for hooks) during installation and upgrade operations. * @return timeout **/ @javax.annotation.Nullable @ApiModelProperty(value = "Timeout is the time to wait for any individual Kubernetes operation (like Jobs for hooks) during installation and upgrade operations.") public Long getTimeout() { return timeout; } public void setTimeout(Long timeout) { this.timeout = timeout; } public V1HelmReleaseSpec valueFileSecrets(List<V1HelmReleaseSpecValueFileSecrets> valueFileSecrets) { this.valueFileSecrets = valueFileSecrets; return this; } public V1HelmReleaseSpec addValueFileSecretsItem(V1HelmReleaseSpecValueFileSecrets valueFileSecretsItem) { if (this.valueFileSecrets == null) { this.valueFileSecrets = new ArrayList<V1HelmReleaseSpecValueFileSecrets>(); } this.valueFileSecrets.add(valueFileSecretsItem); return this; } /** * ValueFileSecrets holds the local name references to secrets. DEPRECATED, use ValuesFrom.secretKeyRef instead. * @return valueFileSecrets **/ @javax.annotation.Nullable @ApiModelProperty(value = "ValueFileSecrets holds the local name references to secrets. DEPRECATED, use ValuesFrom.secretKeyRef instead.") public List<V1HelmReleaseSpecValueFileSecrets> getValueFileSecrets() { return valueFileSecrets; } public void setValueFileSecrets(List<V1HelmReleaseSpecValueFileSecrets> valueFileSecrets) { this.valueFileSecrets = valueFileSecrets; } public V1HelmReleaseSpec values(Object values) { this.values = values; return this; } /** * Values holds the values for this Helm release. * @return values **/ @javax.annotation.Nullable @ApiModelProperty(value = "Values holds the values for this Helm release.") public Object getValues() { return values; } public void setValues(Object values) { this.values = values; } public V1HelmReleaseSpec valuesFrom(List<V1HelmReleaseSpecValuesFrom> valuesFrom) { this.valuesFrom = valuesFrom; return this; } public V1HelmReleaseSpec addValuesFromItem(V1HelmReleaseSpecValuesFrom valuesFromItem) { if (this.valuesFrom == null) { this.valuesFrom = new ArrayList<V1HelmReleaseSpecValuesFrom>(); } this.valuesFrom.add(valuesFromItem); return this; } /** * Get valuesFrom * @return valuesFrom **/ @javax.annotation.Nullable @ApiModelProperty(value = "") public List<V1HelmReleaseSpecValuesFrom> getValuesFrom() { return valuesFrom; } public void setValuesFrom(List<V1HelmReleaseSpecValuesFrom> valuesFrom) { this.valuesFrom = valuesFrom; } public V1HelmReleaseSpec wait(Boolean wait) { this.wait = wait; return this; } /** * Wait will mark this Helm release to wait until all Pods, PVCs, Services, and minimum number of Pods of a Deployment, StatefulSet, or ReplicaSet are in a ready state before marking the release as successful. * @return wait **/ @javax.annotation.Nullable @ApiModelProperty(value = "Wait will mark this Helm release to wait until all Pods, PVCs, Services, and minimum number of Pods of a Deployment, StatefulSet, or ReplicaSet are in a ready state before marking the release as successful.") public Boolean getWait() { return wait; } public void setWait(Boolean wait) { this.wait = wait; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } V1HelmReleaseSpec v1HelmReleaseSpec = (V1HelmReleaseSpec) o; return Objects.equals(this.chart, v1HelmReleaseSpec.chart) && Objects.equals(this.disableOpenAPIValidation, v1HelmReleaseSpec.disableOpenAPIValidation) && Objects.equals(this.forceUpgrade, v1HelmReleaseSpec.forceUpgrade) && Objects.equals(this.helmVersion, v1HelmReleaseSpec.helmVersion) && Objects.equals(this.maxHistory, v1HelmReleaseSpec.maxHistory) && Objects.equals(this.releaseName, v1HelmReleaseSpec.releaseName) && Objects.equals(this.resetValues, v1HelmReleaseSpec.resetValues) && Objects.equals(this.rollback, v1HelmReleaseSpec.rollback) && Objects.equals(this.skipCRDs, v1HelmReleaseSpec.skipCRDs) && Objects.equals(this.targetNamespace, v1HelmReleaseSpec.targetNamespace) && Objects.equals(this.test, v1HelmReleaseSpec.test) && Objects.equals(this.timeout, v1HelmReleaseSpec.timeout) && Objects.equals(this.valueFileSecrets, v1HelmReleaseSpec.valueFileSecrets) && Objects.equals(this.values, v1HelmReleaseSpec.values) && Objects.equals(this.valuesFrom, v1HelmReleaseSpec.valuesFrom) && Objects.equals(this.wait, v1HelmReleaseSpec.wait); } @Override public int hashCode() { return Objects.hash(chart, disableOpenAPIValidation, forceUpgrade, helmVersion, maxHistory, releaseName, resetValues, rollback, skipCRDs, targetNamespace, test, timeout, valueFileSecrets, values, valuesFrom, wait); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class V1HelmReleaseSpec {\n"); sb.append(" chart: ").append(toIndentedString(chart)).append("\n"); sb.append(" disableOpenAPIValidation: ").append(toIndentedString(disableOpenAPIValidation)).append("\n"); sb.append(" forceUpgrade: ").append(toIndentedString(forceUpgrade)).append("\n"); sb.append(" helmVersion: ").append(toIndentedString(helmVersion)).append("\n"); sb.append(" maxHistory: ").append(toIndentedString(maxHistory)).append("\n"); sb.append(" releaseName: ").append(toIndentedString(releaseName)).append("\n"); sb.append(" resetValues: ").append(toIndentedString(resetValues)).append("\n"); sb.append(" rollback: ").append(toIndentedString(rollback)).append("\n"); sb.append(" skipCRDs: ").append(toIndentedString(skipCRDs)).append("\n"); sb.append(" targetNamespace: ").append(toIndentedString(targetNamespace)).append("\n"); sb.append(" test: ").append(toIndentedString(test)).append("\n"); sb.append(" timeout: ").append(toIndentedString(timeout)).append("\n"); sb.append(" valueFileSecrets: ").append(toIndentedString(valueFileSecrets)).append("\n"); sb.append(" values: ").append(toIndentedString(values)).append("\n"); sb.append(" valuesFrom: ").append(toIndentedString(valuesFrom)).append("\n"); sb.append(" wait: ").append(toIndentedString(wait)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
31.075377
261
0.72984
a691d0ce2e0339fc27e51628c39bb0bf8e84df47
3,742
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.galaxy.lemon.framework.security.auth; import com.galaxy.lemon.common.AlertCapable; import com.galaxy.lemon.common.codec.CodecException; import com.galaxy.lemon.common.codec.ObjectDecoder; import com.galaxy.lemon.common.exception.ErrorMsgCode; import com.galaxy.lemon.common.exception.LemonException; import com.galaxy.lemon.common.utils.JudgeUtils; import com.galaxy.lemon.framework.security.LemonAuthenticationException; import com.galaxy.lemon.framework.security.SimpleUserInfo; import com.galaxy.lemon.framework.security.UserInfoBase; import java.util.Map; /** * * @author <mailto:eleven.hm@vip.163.com">eleven</a> * @see * @since 1.0.0 */ public class MockUserNamePasswordMatchableAuthenticationProcessor extends AbstractGenericMatchableAuthenticationProcessor<GenericAuthenticationToken> { public static final String USER_NAME = "userName"; public static final String PASSWORD = "password"; private ObjectDecoder objectDecoder; public MockUserNamePasswordMatchableAuthenticationProcessor(String filterProcessesUrl, ObjectDecoder objectDecoder) { super(filterProcessesUrl); this.objectDecoder = objectDecoder; } @Override protected UserInfoBase doProcessAuthentication(GenericAuthenticationToken genericAuthenticationToken) { AuthenticationRequest authenticationRequest = genericAuthenticationToken.getAuthenticationRequest(); Map<String, String> authenticationRequestParameters = null; try { authenticationRequestParameters = this.objectDecoder.readValue(getRequestInputStream(authenticationRequest), Map.class); } catch (CodecException e) { LemonException.throwLemonException(ErrorMsgCode.AUTHENTICATION_FAILURE, e); } if (JudgeUtils.isEmpty(authenticationRequestParameters)) { LemonException.throwLemonException(ErrorMsgCode.AUTHENTICATION_FAILURE, "No authentication parameter found in request body."); } if (JudgeUtils.equals(authenticationRequestParameters.get(USER_NAME), "mock") && JudgeUtils.equals(authenticationRequestParameters.get(PASSWORD), "mock123")) { return new SimpleUserInfo("mock123456", "mock", "12345678900"); } throw new LemonAuthenticationException(MockMsgCode.USER_NAME_OR_PASSWORD_INVALID); } public enum MockMsgCode implements AlertCapable { USER_NAME_OR_PASSWORD_INVALID("AGW00001", "Invalid username or password."); private String msgCd; private String msgInfo; MockMsgCode(String msgCd, String msgInfo) { this.msgCd = msgCd; this.msgInfo = msgInfo; } @Override public String getMsgCd() { return this.msgCd; } @Override public String getMsgInfo() { return this.msgInfo; } } }
40.673913
151
0.725815
277940a931124a9c840209eb5476998108aa8f1a
5,627
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|ipc package|; end_package begin_import import|import name|java operator|. name|net operator|. name|InetAddress import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Optional import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|yetus operator|. name|audience operator|. name|InterfaceAudience import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|shaded operator|. name|protobuf operator|. name|generated operator|. name|HBaseProtos operator|. name|VersionInfo import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|security operator|. name|User import|; end_import begin_comment comment|/** * Interface of all necessary to carry out a RPC service invocation on the server. This interface * focus on the information needed or obtained during the actual execution of the service method. */ end_comment begin_interface annotation|@ name|InterfaceAudience operator|. name|Private specifier|public interface|interface name|RpcCallContext block|{ comment|/** * Check if the caller who made this IPC call has disconnected. * If called from outside the context of IPC, this does nothing. * @return&lt; 0 if the caller is still connected. The time in ms * since the disconnection otherwise */ name|long name|disconnectSince parameter_list|() function_decl|; comment|/** * If the client connected and specified a codec to use, then we will use this codec making * cellblocks to return. If the client did not specify a codec, we assume it does not support * cellblocks and will return all content protobuf'd (though it makes our serving slower). * We need to ask this question per call because a server could be hosting both clients that * support cellblocks while fielding requests from clients that do not. * @return True if the client supports cellblocks, else return all content in pb */ name|boolean name|isClientCellBlockSupported parameter_list|() function_decl|; comment|/** * Returns the user credentials associated with the current RPC request or not present if no * credentials were provided. * @return A User */ name|Optional argument_list|< name|User argument_list|> name|getRequestUser parameter_list|() function_decl|; comment|/** * @return Current request's user name or not present if none ongoing. */ specifier|default name|Optional argument_list|< name|String argument_list|> name|getRequestUserName parameter_list|() block|{ return|return name|getRequestUser argument_list|() operator|. name|map argument_list|( name|User operator|:: name|getShortName argument_list|) return|; block|} comment|/** * @return Address of remote client in this call */ name|InetAddress name|getRemoteAddress parameter_list|() function_decl|; comment|/** * @return the client version info, or null if the information is not present */ name|VersionInfo name|getClientVersionInfo parameter_list|() function_decl|; comment|/** * Sets a callback which has to be executed at the end of this RPC call. Such a callback is an * optional one for any Rpc call. * * @param callback */ name|void name|setCallBack parameter_list|( name|RpcCallback name|callback parameter_list|) function_decl|; name|boolean name|isRetryImmediatelySupported parameter_list|() function_decl|; comment|/** * The size of response cells that have been accumulated so far. * This along with the corresponding increment call is used to ensure that multi's or * scans dont get too excessively large */ name|long name|getResponseCellSize parameter_list|() function_decl|; comment|/** * Add on the given amount to the retained cell size. * * This is not thread safe and not synchronized at all. If this is used by more than one thread * then everything will break. Since this is called for every row synchronization would be too * onerous. */ name|void name|incrementResponseCellSize parameter_list|( name|long name|cellSize parameter_list|) function_decl|; name|long name|getResponseBlockSize parameter_list|() function_decl|; name|void name|incrementResponseBlockSize parameter_list|( name|long name|blockSize parameter_list|) function_decl|; name|long name|getResponseExceptionSize parameter_list|() function_decl|; name|void name|incrementResponseExceptionSize parameter_list|( name|long name|exceptionSize parameter_list|) function_decl|; block|} end_interface end_unit
27.315534
814
0.775191
8eaa227976b1d5a674e6eeaebd6fb944c724ab47
4,569
/* // Licensed to DynamoBI Corporation (DynamoBI) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. DynamoBI 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 net.sf.farrago.ddl; import java.io.*; import java.net.*; import java.util.jar.*; import net.sf.farrago.catalog.*; import net.sf.farrago.fem.sql2003.*; import net.sf.farrago.plugin.*; import net.sf.farrago.resource.*; import net.sf.farrago.session.*; import org.eigenbase.sql.*; import org.eigenbase.util.*; /** * DdlExtendCatalogStmt represents an ALTER SYSTEM ADD CATALOG JAR statement. * * @author John V. Sichi * @version $Id$ */ public class DdlExtendCatalogStmt extends DdlStmt { //~ Instance fields -------------------------------------------------------- private final SqlIdentifier jarName; private FarragoRepos repos; private FarragoSessionFactory sessionFactory; private FemJar femJar; private String jarUrlUnexpanded; //~ Constructors ----------------------------------------------------------- public DdlExtendCatalogStmt(SqlIdentifier jarName) { super(null); this.jarName = jarName; } //~ Methods ---------------------------------------------------------------- // implement DdlStmt public void visit(DdlVisitor visitor) { visitor.visit(this); } // implement FarragoSessionDdlStmt public void preValidate(FarragoSessionDdlValidator ddlValidator) { repos = ddlValidator.getRepos(); sessionFactory = ddlValidator.getStmtValidator().getSession().getSessionFactory(); femJar = ddlValidator.getStmtValidator().findSchemaObject( jarName, FemJar.class); if (femJar.isModelExtension()) { throw FarragoResource.instance().CatalogModelAlreadyImported.ex( repos.getLocalizedObjectName(femJar)); } femJar.setModelExtension(true); } // implement FarragoSessionDdlStmt public void preExecute() { // We do the real work here since there's nothing session-specific // involved. We don't bother updating transient information // like the FarragoDatabase list of installed model extensions, // because we're going to require a restart anyway. // TODO jvs 6-Apr-2005: verify that model name does not conflict with // any existing one. Also, verify that we are in single-session // mode. // Before modifying the catalog, verify that we can actually // load the plugin; otherwise, we'll be in bad shape after // reboot. FarragoSessionModelExtension modelExtension = sessionFactory.newModelExtension( new FarragoPluginClassLoader(), femJar); // TODO: trace information about modelExtension JarInputStream jarInputStream = null; try { jarUrlUnexpanded = femJar.getUrl(); URL jarUrl = new URL(FarragoCatalogUtil.getJarUrl(femJar)); jarInputStream = new JarInputStream(jarUrl.openStream()); Manifest manifest = jarInputStream.getManifest(); String xmiResourceName = manifest.getMainAttributes().getValue( FarragoPluginClassLoader.PLUGIN_MODEL_ATTRIBUTE); URL xmiResourceUrl = new URL("jar:" + jarUrl + "!/" + xmiResourceName); FarragoReposUtil.importSubModel( repos.getMdrRepos(), xmiResourceUrl); } catch (Exception ex) { throw FarragoResource.instance().CatalogModelImportFailed.ex( repos.getLocalizedObjectName(femJar), ex); } finally { Util.squelchStream(jarInputStream); } } public String getJarUrl() { return jarUrlUnexpanded; } } // End DdlExtendCatalogStmt.java
32.870504
80
0.632742
9fbf3015b6984102c9a94e87622d83e0f307b06a
4,787
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.sps; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.ArrayList; public final class FindMeetingQuery { public Collection<TimeRange> query(Collection<Event> events, MeetingRequest request) { // get TimeRange of events filtered by attendees List<TimeRange> eventsTimeRangesForMandatoryAttendees = new ArrayList<>(); List<TimeRange> eventsTimeRangesWithOptionalAttendees = new ArrayList<>(); for (Event event: events) { if(containSameAttendees(event.getAttendees(), request.getAttendees())) { eventsTimeRangesForMandatoryAttendees.add(event.getWhen()); eventsTimeRangesWithOptionalAttendees.add(event.getWhen()); } else if (containSameAttendees(event.getAttendees(), request.getOptionalAttendees())) { eventsTimeRangesWithOptionalAttendees.add(event.getWhen()); } } // Try adding the optional attendees Collections.sort(eventsTimeRangesWithOptionalAttendees, TimeRange.ORDER_BY_START); Collection<TimeRange> combinedTimeRanges = combineTimeRanges(eventsTimeRangesWithOptionalAttendees); Collection<TimeRange> freeTimeRanges = getFreeTimeRanges(combinedTimeRanges, request.getDuration()); if (freeTimeRanges.size() > 0 || request.getAttendees().size() ==0) return freeTimeRanges; // If no time slot with optional attendees, try only mandatory attendees Collections.sort(eventsTimeRangesForMandatoryAttendees, TimeRange.ORDER_BY_START); combinedTimeRanges = combineTimeRanges(eventsTimeRangesForMandatoryAttendees); return getFreeTimeRanges(combinedTimeRanges, request.getDuration()); } /** Check if the event and the request contains the same attendee. */ private boolean containSameAttendees(Collection<String> eventAttendees, Collection<String> requestAttendees) { if (requestAttendees.size() == 0) return false; for (String attendee: eventAttendees) if (requestAttendees.contains(attendee)) return true; return false; } /** * Combine overlapped TimeRanges in a sorted List. * @return a sorted Collection of TimeRanges without overlap. */ private Collection<TimeRange> combineTimeRanges(List<TimeRange> timeRanges) { Collection<TimeRange> combinedTimeRanges = new ArrayList<>(); if (timeRanges.size() == 0) return combinedTimeRanges; TimeRange currentEvent = timeRanges.get(0); for (int i = 1; i < timeRanges.size(); i++) { TimeRange nextEvent = timeRanges.get(i); if (currentEvent.overlaps(nextEvent)) { // update current TimeRange int start = currentEvent.start(); int end = currentEvent.contains(nextEvent.end())? currentEvent.end() : nextEvent.end(); currentEvent = TimeRange.fromStartEnd(start, end, false); } else { // store current TimeRange combinedTimeRanges.add(currentEvent); currentEvent = nextEvent; } } combinedTimeRanges.add(currentEvent); return combinedTimeRanges; } /** * Get a Collection of free TimeRanges given a collection of busy TimeRanges. * Only include TimeRanges with at least requested duration. */ private Collection<TimeRange> getFreeTimeRanges(Collection<TimeRange> busyTimeRanges, Long requestDuration) { Collection<TimeRange> freeTimeRanges = new ArrayList<>(); int start = TimeRange.START_OF_DAY; for (TimeRange time: busyTimeRanges) { int newEnd = time.start(); int newStart = time.end(); if (newEnd - start >= requestDuration) freeTimeRanges.add(TimeRange.fromStartEnd(start, newEnd, false)); start = newStart; } if (TimeRange.END_OF_DAY - start >= requestDuration) freeTimeRanges.add(TimeRange.fromStartEnd(start, TimeRange.END_OF_DAY, true)); return freeTimeRanges; } }
42.362832
114
0.673491
450fa6ffc727c6118d3d42fd02ad9fa0cb57688d
180
package telegram.event; import telegram.objects.Update; import java.util.EventListener; public interface UpdateHandler extends EventListener { void handle(Update update); }
16.363636
52
0.8
e949434d6507ed685efeed48123472c12c2bd01c
123
package com.matchbook.sdk.rest.dtos.offers; public enum MatchedBetStatus { OPEN, CANCELLED, GRADED, PAID, UNKNOWN }
15.375
43
0.747967
0d9512f9402db76be88430327f6524de09fca7be
2,915
package com.jeff.ttxs.cameracustomdemo; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import butterknife.ButterKnife; import butterknife.OnClick; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); checkCameraPermission(); } @OnClick({R.id.system,R.id.custom}) public void OnClick(View view){ switch (view.getId()){ case R.id.system: startActivity(new Intent(this,SystemCameraActivity.class)); break; case R.id.custom: startActivity(new Intent(this,CustomCameraActivity.class)); break; } } /** * 运行时权限 */ private void checkCameraPermission() { //相机 if (ContextCompat.checkSelfPermission(this, Manifest.permission .CAMERA)== PackageManager.PERMISSION_GRANTED){ }else { ActivityCompat.requestPermissions(this,new String[]{Manifest .permission.CAMERA},1); } //读取SDCard if (ContextCompat.checkSelfPermission(this,Manifest.permission .WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED){ //已经同意,不需要申请,如果为NPERMISSION_DENIED,则需要申请 }else { ActivityCompat.requestPermissions(this,new String[]{Manifest .permission.WRITE_EXTERNAL_STORAGE},2); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode){ case 1: //当申请得权限取消时,grandResults是empty if (grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){ //申请成功 LogUtils.e("相机--申请成功"); }else { //申请失败 LogUtils.e("相机--申请失败"); } break; case 2: if (grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){ //申请成功 LogUtils.e("读取SD--申请成功"); }else { //申请失败 LogUtils.e("读取SD--申请失败"); } break; } } }
32.032967
80
0.554717
472dbf5a16cf29562531a4debc420d84b6b1fc8e
500
package pl.lodz.p.it.inz.sgruda.multiStore.mok.services.interfaces; import pl.lodz.p.it.inz.sgruda.multiStore.exceptions.OptimisticLockAppException; import pl.lodz.p.it.inz.sgruda.multiStore.exceptions.mok.AccountNotExistsException; import pl.lodz.p.it.inz.sgruda.multiStore.exceptions.mok.EmailAlreadyVerifyException; public interface MailVerifierService { void verifyEmail(String veryficationToken) throws AccountNotExistsException, EmailAlreadyVerifyException, OptimisticLockAppException; }
50
137
0.856
42dce1a95fb74cac57c93077c1894d8b07a01577
393
package exercico1; import java.util.Scanner; public class Exercicio1 { int numero ; static Scanner leia = new Scanner(System.in) ; public static void main(String[] args) { System.out.println("Digite o número: ") ; int numero = leia.nextInt() ; if( numero <0 ) { System.out.println("O numero é: Negativo"); }else{ System.out.println("O numero é: Positivo"); } } }
21.833333
48
0.656489
2c5a778fa9e9dcc1797dc34f56fe81ec9023d424
367
package es.uniovi.asw.electionday.parser; import java.util.List; import es.uniovi.asw.model.Candidature; public abstract class RCandidature implements ReadCandidature{ @Override public List<Candidature> read(String path) { List<Candidature> candidaturas = readFile(path); return candidaturas; } abstract List<Candidature> readFile(String path); }
19.315789
62
0.771117
c21bd8e19bfb04141f67c6e1388c2f2abfa8b327
1,463
package edu.gvsu.cis.cis656.clock; import java.util.Set; public interface Clock{ /** * Update the current clock with a new one, taking into * account the values of the incoming clock. * * E.g. for vector clocks, c1 = [2 1 0], c2 = [1 2 0], * the c1.update(c2) will lead to [2 2 0]. * @param other */ void update(Clock other); /** * Change the current clock with a new one, overwriting the * old values. * @param other */ void setClock(Clock other); /** * Tick a clock given the process id. * * For Lamport timestamps, since there is only one logical time, * the method can be called with the "null" parameter. (e.g. * clock.tick(null). * @param pid */ void tick(Integer pid); /** * Check whether a clock has happened before another one. * * @param other * @return True if a clock has happened before, false otherwise. */ boolean happenedBefore(Clock other); /** * toString * * @return String representation of the clock. */ String toString(); /** * Set a clock given it's string representation. * * @param clock */ void setClockFromString(String clock); /** * * Get the time for process p * * @param p the process id. * @return */ int getTime(int p); /** * Add a time stamp c for process p. * * @param p the process id * @param c the timestamp */ void addProcess(int p, int c); /** * Get the keyset from the clock. */ Set<String> getKeyset(); }
18.518987
65
0.632946
2ac1c18abf85f6e8fc1e4ce7398f100e74eed10d
4,721
/* Copyright 2005-2006 The Apache Software Foundation or its licensors, as applicable 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 Nikolay Y. Amosov * @version $Revision: 1.3 $ */ package org.apache.harmony.vts.test.vm.jvms.classFile.limitations.interfaces.interfaces01; import org.apache.harmony.share.Result; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; public class Interfaces01 { // Interface template static byte[] interfaceTemplate = { -54, -2, -70, -66, 0, 0, 0, 46, 0, 5, 7, 0, 3, 7, 0, 4, 1, 0, 6, 105, 0, 0, 0, 0, 0, // interface name 1, 0, 16, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 79, 98, 106, 101, 99, 116, 6, 1, 0, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0}; static String testedClassFilename = "org.apache.harmony.vts.test.vm.jvms.classFile.limitations.interfaces.interfaces01.ManyInterfacesImplementer"; //"ManyInterfacesImplementer"; public static void main(String[] args) throws Exception { System.exit((new Interfaces01()).test(args)); } int generatedInterfaces = 0; public int test(String[] args) throws Exception { testCL cl = new testCL(); cl.loadClass(testedClassFilename); return Result.PASS; } class testCL extends ClassLoader { public Class loadClass(ByteArrayOutputStream classInStream) throws ClassNotFoundException { byte[] dt = classInStream.toByteArray(); return defineClass(testedClassFilename, dt, 0, dt.length); } boolean isExpectedInterfaceName(String name) { if (name.length() == 6 && name.charAt(0) == 'i') { try { int interfaceNumber = Integer.parseInt(name.substring(1), 10); if (interfaceNumber > 0) return true; } catch (NumberFormatException nfe) { return false; } } return false; } public Class loadClass(String name) throws ClassNotFoundException { if (isExpectedInterfaceName(name)) { generatedInterfaces++; System.arraycopy(name.substring(1).getBytes(), 0, interfaceTemplate, 20, 5); return defineClass(name, interfaceTemplate, 0, interfaceTemplate.length); } else if (name.equals(testedClassFilename)) { return loadClassFromFile(name); } else { return super.loadClass(name); } } /** * @param classFileName - class name to load * @return * @throws ClassNotFoundException - when class file not fount in classpath's paths */ private Class loadClassFromFile(String classFileName) throws ClassNotFoundException { String classpath = System.getProperty("java.class.path"); String[] paths = classpath.split(System.getProperty("path.separator")); String pathdelimiter = System.getProperty("file.separator"); // search class file in classpath's folders java.io.File fl = null; String classFileNameWithPath = classFileName.replace(".", pathdelimiter); for (int i = 0; i < paths.length; ++i) if ((new java.io.File(paths[i] + pathdelimiter + classFileNameWithPath + ".class").exists())) { fl = new java.io.File(paths[i] + pathdelimiter + classFileNameWithPath + ".class"); break; } if (fl != null) { try { FileInputStream fis = new FileInputStream(fl); byte[] clsFromFile = new byte[(int) fl.length()]; fis.read(clsFromFile); return defineClass(classFileName, clsFromFile, 0, clsFromFile.length); } catch (Exception e) { throw new ClassNotFoundException(e.getMessage()); } } else throw new ClassNotFoundException("file " + classFileName + ".class not found in classpath's folders"); } } }
38.382114
118
0.594577
23f5d5747bf5f1aca7f1d0395786ebc40f19175c
4,219
package edu.mit.mitmobile2.events; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import edu.mit.mitmobile2.MobileWebApi; import edu.mit.mitmobile2.NewModule; import edu.mit.mitmobile2.SliderNewModuleActivity; import edu.mit.mitmobile2.SliderView; import edu.mit.mitmobile2.SliderView.Adapter; import edu.mit.mitmobile2.events.EventDayListSliderAdapter.OnDayChangeListener; import edu.mit.mitmobile2.events.EventsModel.EventType; public class MITEventsDaysSliderActivity extends SliderNewModuleActivity implements OnDayChangeListener { final static String LIST_TYPE_KEY = "list_type"; final static int STANDARD_LIST = 0; final static int LIST_BY_CATEGORY = 1; final static String CATEGORY_ID_KEY = "category_id"; final static String CATEGORY_NAME_KEY = "category_name"; final static String START_TIME_KEY = "start_time"; final static String EVENT_TYPE_KEY = "event_type"; private long mCurrentTime = -1; private EventType mEventType = null; private int mCategoryId = -1; private String mCategoryName = null; private SliderView.Adapter mSliderAdapter; public static void launch(Context context, EventType eventType) { launchEventType(context, eventType.getTypeId(), null); } public static void launchEventType(Context context, String eventType, Long startTime) { Intent intent = new Intent(context, MITEventsDaysSliderActivity.class); intent.putExtra(EVENT_TYPE_KEY, eventType); intent.putExtra(LIST_TYPE_KEY, STANDARD_LIST); if(startTime != null) { intent.putExtra(START_TIME_KEY, startTime); } context.startActivity(intent); } public static void launchCategory(Context context, int categoryId, String categoryName, String eventType, Long startTime) { Intent intent = new Intent(context, MITEventsDaysSliderActivity.class); intent.putExtra(LIST_TYPE_KEY, LIST_BY_CATEGORY); intent.putExtra(CATEGORY_ID_KEY, categoryId); intent.putExtra(CATEGORY_NAME_KEY, categoryName); intent.putExtra(EVENT_TYPE_KEY, eventType); if(startTime != null) { intent.putExtra(START_TIME_KEY, startTime); } context.startActivity(intent); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Bundle extras = getIntent().getExtras(); mCurrentTime = System.currentTimeMillis(); if(extras.getInt(LIST_TYPE_KEY) == LIST_BY_CATEGORY) { mCategoryId = extras.getInt(CATEGORY_ID_KEY); mCategoryName = extras.getString(CATEGORY_NAME_KEY); } if(EventsModel.eventTypesLoaded()) { mEventType = EventsModel.getEventType(extras.getString(EVENT_TYPE_KEY)); createViews(); } else { // need to load the event types showLoading("Events"); EventsModel.fetchEventTypes(this, new Handler() { @Override public void handleMessage(Message msg) { if(msg.arg1 == MobileWebApi.SUCCESS) { mEventType = EventsModel.getEventType(extras.getString(EVENT_TYPE_KEY)); showLoadingCompleted(); createViews(); } else { showLoadingError(); } } }); } } protected void createViews() { if(mCategoryName != null) { addSecondaryTitle(mCategoryName); } else if(mEventType != null) { addSecondaryTitle(mEventType.getShortName()); } mSliderAdapter = new EventDayListSliderAdapter(this, mEventType, mCurrentTime/1000, mCategoryId, this); reloadAdapter(); } @Override protected NewModule getNewModule() { return new EventsModule(); } @Override public boolean isModuleHomeActivity() { return false; } @Override protected Adapter getSliderAdapter() { return mSliderAdapter; } @Override protected void onOptionSelected(String optionId) { // TODO Auto-generated method stub } private String mPrevious, mCurrent, mNext; @Override public void onDayChangeListener(String previous, String current, String next) { mPrevious = previous; mCurrent = current; mNext = next; } @Override protected String getPreviousTitle() { return mPrevious; } @Override protected String getCurrentHeaderTitle() { return mCurrent; } @Override protected String getNextTitle() { return mNext; } }
26.872611
125
0.754918
c037f9f8b45360c59c826931ad9697af9491503b
1,478
package net.minecraft.src; // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) braces deadcode import net.minecraft.src.block.Block; import net.minecraft.src.crafting.CraftingManager; import net.minecraft.src.item.Item; import net.minecraft.src.item.ItemStack; public class RecipesIngots { public RecipesIngots() { recipeItems = (new Object[][] { new Object[] { Block.blockGold, new ItemStack(Item.ingotGold, 9) }, new Object[] { Block.blockSteel, new ItemStack(Item.ingotIron, 9) }, new Object[] { Block.blockDiamond, new ItemStack(Item.diamond, 9) }, new Object[] { Block.blockLapis, new ItemStack(Item.dyePowder, 9, 4) } }); } public void addRecipes(CraftingManager craftingmanager) { for(int i = 0; i < recipeItems.length; i++) { Block block = (Block)recipeItems[i][0]; ItemStack itemstack = (ItemStack)recipeItems[i][1]; craftingmanager.addRecipe(new ItemStack(block), new Object[] { "###", "###", "###", Character.valueOf('#'), itemstack }); craftingmanager.addRecipe(itemstack, new Object[] { "#", Character.valueOf('#'), block }); } } private Object recipeItems[][]; }
30.791667
74
0.577808
9d28c643921a5e9e5f78a2c26a0beb0b2670b829
1,942
package com.github.paulakimenko.fakeses; import com.github.paulakimenko.fakeses.controllers.MessagesController; import com.github.paulakimenko.fakeses.controllers.SESController; import com.github.paulakimenko.fakeses.dao.MessagesDAO; import com.github.paulakimenko.fakeses.dao.MessagesFileDAO; import com.github.paulakimenko.fakeses.utils.Arguments; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import static spark.Spark.port; import static spark.Spark.threadPool; public class FakeSES { private static final Logger log = LoggerFactory.getLogger(FakeSES.class); public static void main(String[] args) { runApp(getArguments()); } public static void runApp(Arguments arguments) { log.info("Init Application with given params '{}'", arguments); MessagesDAO messagesDAO = initMessagesDAO(arguments.getWorkDir()); port(arguments.getPort()); threadPool(arguments.getThreadCount()); SESController sesController = new SESController(messagesDAO); MessagesController messagesController = new MessagesController(messagesDAO); Router router = new Router(sesController, messagesController); router.setup(); } private static Arguments getArguments() { try { return Arguments.getFromEnviroment(); } catch (RuntimeException e) { exitWithError(1, e.getMessage()); throw new RuntimeException(e); } } private static MessagesDAO initMessagesDAO(String workDir) { try { return MessagesFileDAO.prepareFor(workDir); } catch (IOException e) { exitWithError(2, e.getMessage()); throw new RuntimeException(e); } } private static void exitWithError(int code, String error) { log.error("Error has been occurred '{}'! Exit {}.", error, code); System.exit(code); } }
31.836066
84
0.69104
baf7c0ba49aa98b17675cd8139c60fa67a09fbc1
66
package com.narendra.app.core; class CoreApplicationTests { }
8.25
30
0.757576
c3675f377e5edbdca12e7330aeaac3d5cee69681
3,716
/* * 3D City Database - The Open Source CityGML Database * http://www.3dcitydb.org/ * * Copyright 2013 - 2016 * Chair of Geoinformatics * Technical University of Munich, Germany * https://www.gis.bgu.tum.de/ * * The 3D City Database is jointly developed with the following * cooperation partners: * * virtualcitySYSTEMS GmbH, Berlin <http://www.virtualcitysystems.de/> * M.O.S.S. Computer Grafik Systeme GmbH, Taufkirchen <http://www.moss.de/> * * 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.citydb.config.gui; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.XmlType; import org.citydb.config.gui.window.ConsoleWindow; import org.citydb.config.gui.window.MainWindow; import org.citydb.config.gui.window.MapWindow; @XmlRootElement @XmlType(name="GuiType", propOrder={ "main", "console", "map", "showPreferencesConfirmDialog", "showOutdatedDatabaseVersionWarning", "recentlyUsedProjects" }) public class Gui { private MainWindow main; private ConsoleWindow console; private MapWindow map; private boolean showPreferencesConfirmDialog = true; private boolean showOutdatedDatabaseVersionWarning = true; @XmlElementWrapper(name="recentlyUsedProjects") @XmlElement(name="fileName") private List<String> recentlyUsedProjects; @XmlTransient private final int maxLastUsedEntries = 5; public Gui() { main = new MainWindow(); console = new ConsoleWindow(); map = new MapWindow(); recentlyUsedProjects = new ArrayList<String>(maxLastUsedEntries + 1); } public MainWindow getMainWindow() { return main; } public void setMainWindow(MainWindow main) { if (main != null) this.main = main; } public ConsoleWindow getConsoleWindow() { return console; } public void setConsoleWindow(ConsoleWindow console) { if (console != null) this.console = console; } public MapWindow getMapWindow() { return map; } public void setMapWindow(MapWindow map) { if (map != null) this.map = map; } public boolean isShowPreferencesConfirmDialog() { return showPreferencesConfirmDialog; } public void setShowPreferencesConfirmDialog(boolean showPreferencesConfirmDialog) { this.showPreferencesConfirmDialog = showPreferencesConfirmDialog; } public boolean isShowOutdatedDatabaseVersionWarning() { return showOutdatedDatabaseVersionWarning; } public void setShowOutdatedDatabaseVersionWarning(boolean showOutdatedDatabaseVersionWarning) { this.showOutdatedDatabaseVersionWarning = showOutdatedDatabaseVersionWarning; } public List<String> getRecentlyUsedProjectFiles() { return recentlyUsedProjects; } public void setRecentlyUsedProjectFiles(List<String> recentlyUsedProjects) { if (recentlyUsedProjects != null) this.recentlyUsedProjects = recentlyUsedProjects; } public int getMaxLastUsedEntries() { return maxLastUsedEntries; } }
28.806202
97
0.740043
db9eb5ce26ba839fd40cba8d4db0438040d76dcd
1,024
package com.rbkmoney.dark.api.converter.dadata; import com.rbkmoney.dark.api.converter.SwagConverter; import com.rbkmoney.dark.api.converter.SwagConverterContext; import com.rbkmoney.swag.questionary_aggr_proxy.model.Gender; import org.springframework.stereotype.Component; @Component public class GenderSwagConverter implements SwagConverter<Gender, com.rbkmoney.questionary_proxy_aggr.base_dadata.Gender> { @Override public Gender toSwag(com.rbkmoney.questionary_proxy_aggr.base_dadata.Gender value, SwagConverterContext ctx) { if (value == com.rbkmoney.questionary_proxy_aggr.base_dadata.Gender.FEMALE) { return Gender.FEMALE; } else if (value == com.rbkmoney.questionary_proxy_aggr.base_dadata.Gender.MALE) { return Gender.MALE; } else if (value == com.rbkmoney.questionary_proxy_aggr.base_dadata.Gender.UNKNOWN) { return Gender.UNKNOWN; } throw new IllegalArgumentException("Unknown gender type: " + value.name()); } }
40.96
114
0.74707
7bb744ec0e1c1b4481908d444e57d5f2e174f0bc
1,311
package com.example.mybatis.demomybatis.proxy; import com.example.mybatis.demomybatis.handler.CommonProxyHandler; import com.example.mybatis.demomybatis.service.ProxyService; import com.example.mybatis.demomybatis.service.impl.ProxyServiceImpl; import com.google.common.reflect.Reflection; import org.junit.jupiter.api.Test; import java.lang.reflect.Proxy; /** * 类的 动态代理测试. */ public final class CommonProxyTest { @Test public void testCommonProxy(){ // 利用java的多态,接收其实例化的实例ProxyServiceImpl ProxyService proxyService = new ProxyServiceImpl(); // handler中传入目标接口的实例化的对象ProxyServiceImpl CommonProxyHandler commonProxyHandler = new CommonProxyHandler(proxyService,"testParams"); // 第一个参数:类、接口 加载器 // 第二个参数:被代理类要实现的目标接口 // 第三个参数:handler的对象 // 返回:实现该接口类的代理类 ProxyService proxyInstance = (ProxyService) Proxy.newProxyInstance(ProxyServiceImpl.class.getClassLoader(), proxyService.getClass().getInterfaces(), commonProxyHandler); // 调用的其实是代理类中print方法,方法里会调用super.h.invoke。h-就是commonProxyHandler String s = proxyInstance.print("我是一个小代理"); // 直接使用guava的工具类 ProxyService proxyService1 = Reflection.newProxy(ProxyService.class, commonProxyHandler); System.out.println(s); } }
35.432432
115
0.733028
497c9475382e5e9af92540720fdc72f6566146bb
1,477
package io.remedymatch.bedarf.domain.service; import io.remedymatch.angebot.domain.model.AngebotId; import io.remedymatch.bedarf.domain.model.BedarfAnfrage; import io.remedymatch.bedarf.domain.model.BedarfAnfrageId; import io.remedymatch.bedarf.infrastructure.BedarfAnfrageEntity; import io.remedymatch.institution.domain.service.InstitutionEntityConverter; import io.remedymatch.institution.domain.service.InstitutionStandortEntityConverter; import java.util.List; import java.util.stream.Collectors; final class BedarfAnfrageEntityConverter { private BedarfAnfrageEntityConverter() { } static List<BedarfAnfrage> convertAnfragen(final List<BedarfAnfrageEntity> entities) { return entities.stream().map(BedarfAnfrageEntityConverter::convertAnfrage).collect(Collectors.toList()); } static BedarfAnfrage convertAnfrage(final BedarfAnfrageEntity entity) { return BedarfAnfrage.builder() // .id(new BedarfAnfrageId(entity.getId())) // .bedarf(BedarfEntityConverter.convertBedarf(entity.getBedarf())) // .institution(InstitutionEntityConverter.convertInstitution(entity.getInstitution())) // .standort(InstitutionStandortEntityConverter.convertStandort(entity.getStandort())) // .anzahl(entity.getAnzahl()) // .angebotId(new AngebotId(entity.getAngebotId())) // .status(entity.getStatus()) // .build(); } }
43.441176
112
0.732566
aa4df58d4c4cd06c9675d729840360bb2a58a836
3,772
package Mock; import Salesperson.Forwarder; import Planner.Appendage; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.LinkedList; import java.util.regex.Matcher; import java.util.regex.Pattern; public class WorkSimulating { private static final String synX609String = "Finished reading input file..."; private static final String synX608String = "SIZE"; private static final String synX607String = "Arrive"; private static final String synX606String = "ID"; private static final String synX605String = "DISP"; private static final String synX604String = "ID:[\\s]+(?<ID>[\\w]*)[\\s][\\r\\n]+Arrive:[\\s]+(?<Arrive>[\\d]+)[\\s][\\r\\n]+ExecSize:[\\s]+(?<SIZE>[\\d]+)[\\s][\\r\\n]+END"; private static final String synX603String = "DISP:[\\s]+(?<DISP>[\\d]+)"; private static final String synX602String = "./out/production/c3063467A1/"; private static final String synX601String = "Unable to generate output file."; private static final String synX600String = "_output.txt"; private static final String synX599String = "./out/production/c3063467A1/"; private static final String synX598String = "."; private static final int synX597int = 0; private static final String synX596String = "Reading in input file..."; private static final double synX595double = 0.17563189999124962; private static final int synX594int = 540550391; public static BufferedWriter ProducedExecutable; private LinkedList<Appendage> proceduresCompendium; private static String SupportPaperwork; private static synchronized String rereadSubmitted(String trail, Charset cryptography) throws IOException { int indentured; indentured = (synX594int); byte[] demodulated = Files.readAllBytes(Paths.get(trail)); return new String(demodulated, cryptography); } private Forwarder shipper; public static final String full = "g2sRGHNa"; public synchronized void course(String proponents) { double bandwidth; bandwidth = (synX595double); this.SupportPaperwork = (proponents); shipper = (new Forwarder()); proceduresCompendium = (new LinkedList<>()); System.out.println(synX596String); try { String deniedNickname; deniedNickname = (SupportPaperwork.substring(synX597int, SupportPaperwork.lastIndexOf(synX598String))); ProducedExecutable = (new BufferedWriter(new FileWriter((synX599String + deniedNickname + synX600String)))); } catch (IOException tipp) { System.out.println(synX601String); } SupportPaperwork = (synX602String + SupportPaperwork); try { String participation; String svc; Pattern p; Matcher sm; String exp2; Pattern f2; Matcher m3; participation = (rereadSubmitted(SupportPaperwork, StandardCharsets.UTF_8)); svc = (synX603String); p = (Pattern.compile(svc)); sm = (p.matcher(participation)); exp2 = (synX604String); f2 = (Pattern.compile(exp2)); m3 = (f2.matcher(participation)); while (sm.find()) { shipper.settledHitPeriods(Integer.parseInt(sm.group(synX605String))); } while (m3.find()) { proceduresCompendium.add( new Appendage( m3.group(synX606String), Integer.parseInt(m3.group(synX607String)), Integer.parseInt(m3.group(synX608String)))); } System.out.println(synX609String); } catch (Exception vet) { System.out.println(vet.toString()); } shipper.dictatedWork(proceduresCompendium); shipper.testDistributors(); } }
36.621359
136
0.694592
4bf7cf3be1892ba833c7e273a8d7d7827ebdb932
8,847
package com.example.android.habitapp; //https://www.androidhive.info/2011/11/android-sqlite-database-tutorial/ //https://stackoverflow.com/questions/33627915/java-lang-nullpointerexception-attempt-to-invoke-virtual-method-on-a-null-objec import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import com.example.android.habitapp.data.HabitContract.HabitEntry; import com.example.android.habitapp.data.HabitDbHelper; /** * Displays list of habits that were entered and stored in the app. */ public class CatalogActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_catalog); // Setup FAB to open EditorActivity FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(CatalogActivity.this, EditorActivity.class); startActivity(intent); } }); DbHelper = new HabitDbHelper(this); } @Override protected void onStart() { super.onStart(); displayDatabaseInfo(); readData(); } /** * Temporary helper method to display information in the onscreen TextView about the state of * the pets database. */ private void displayDatabaseInfo() { // Define a projection that specifies which columns from the database // you will actually use after this query. String[] projection = { HabitEntry._ID, HabitEntry.COLUMN_HABIT_NAME, HabitEntry.COLUMN_HABIT_DAYOFWEEK, HabitEntry.COLUMN_HABIT_TIMEOFDAY, HabitEntry.COLUMN_HABIT_FREQUENCY}; // Perform a query on the provider using the ContentResolver. // Use the {@link HabitEntry#CONTENT_URI} to access the pet data. Cursor cursor = getContentResolver().query( HabitEntry.CONTENT_URI, // The content URI of the words table projection, // The columns to return for each row null, // Selection criteria null, // Selection criteria null); // The sort order for the returned rows TextView displayView = (TextView) findViewById(R.id.text_view_habit); try { // Create a header in the Text View that looks like this: // // The habits table contains <number of rows in Cursor> habits. // _id - name - day of week - time of day - frequency // // In the while loop below, iterate through the rows of the cursor and display // the information from each column in this order. displayView.setText("The habits table contains " + cursor.getCount() + " habits.\n\n"); displayView.append(HabitEntry._ID + " - " + HabitEntry.COLUMN_HABIT_NAME + " - " + HabitEntry.COLUMN_HABIT_DAYOFWEEK + " - " + HabitEntry.COLUMN_HABIT_TIMEOFDAY + " - " + HabitEntry.COLUMN_HABIT_FREQUENCY + "\n"); // Figure out the index of each column int idColumnIndex = cursor.getColumnIndex(HabitEntry._ID); int nameColumnIndex = cursor.getColumnIndex(HabitEntry.COLUMN_HABIT_NAME); int dayOfWeekColumnIndex = cursor.getColumnIndex(HabitEntry.COLUMN_HABIT_DAYOFWEEK); int timeOfDayColumnIndex = cursor.getColumnIndex(HabitEntry.COLUMN_HABIT_TIMEOFDAY); int frequencyColumnIndex = cursor.getColumnIndex(HabitEntry.COLUMN_HABIT_FREQUENCY); // Iterate through all the returned rows in the cursor while (cursor.moveToNext()) { // Use that index to extract the String or Int value of the word // at the current row the cursor is on. int currentID = cursor.getInt(idColumnIndex); String currentName = cursor.getString(nameColumnIndex); String currentdayOfWeek = cursor.getString(dayOfWeekColumnIndex); int currenttimeOfDay = cursor.getInt(timeOfDayColumnIndex); int currentFrequency = cursor.getInt(frequencyColumnIndex); // Display the values from each column of the current row in the cursor in the TextView displayView.append(("\n" + currentID + " - " + currentName + " - " + currentdayOfWeek + " - " + currenttimeOfDay + " - " + currentFrequency)); } } finally { // Always close the cursor when you're done reading from it. This releases all its // resources and makes it invalid. if (cursor != null) { cursor.close(); } } } //Method for Read database private HabitDbHelper DbHelper; private Cursor readData(){ // Create and/or open a database to read from it SQLiteDatabase db = DbHelper.getReadableDatabase(); // Define a projection that specifies which columns from the database // you will actually use after this query. String[] projection = { HabitEntry._ID, HabitEntry.COLUMN_HABIT_NAME, HabitEntry.COLUMN_HABIT_DAYOFWEEK, HabitEntry.COLUMN_HABIT_TIMEOFDAY, HabitEntry.COLUMN_HABIT_FREQUENCY}; // Perform a query on the habits table Cursor cursor = db.query( HabitEntry.TABLE_NAME, // The table to query projection, // The columns to return null, // The columns for the WHERE clause null, // The values for the WHERE clause null, // Don't group the rows null, // Don't filter by row groups null); // The sort order //query database return cursor; } /** * Helper method to insert hardcoded habit data into the database. For debugging purposes only. */ private void insertHabit() { // Create a ContentValues object where column names are the keys, // and music habit attributes are the values. ContentValues values = new ContentValues(); values.put(HabitEntry.COLUMN_HABIT_NAME, "Music"); values.put(HabitEntry.COLUMN_HABIT_DAYOFWEEK, "Monday"); values.put(HabitEntry.COLUMN_HABIT_TIMEOFDAY, HabitEntry.TIMEOFDAY_MORNING); values.put(HabitEntry.COLUMN_HABIT_FREQUENCY, 1); // Insert a new row for Music in the database, returning the ID of that new row. // The first argument for db.insert() is the habits table name. // The second argument provides the name of a column in which the framework // can insert NULL in the event that the ContentValues is empty (if // this is set to "null", then the framework will not insert a row when // there are no values). // The third argument is the ContentValues object containing the info for Music. Uri newUri = getContentResolver().insert(HabitEntry.CONTENT_URI, values); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu options from the res/menu/menu_catalog.xml file. // This adds menu items to the app bar. getMenuInflater().inflate(R.menu.menu_catalog, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // User clicked on a menu option in the app bar overflow menu switch (item.getItemId()) { // Respond to a click on the "Insert dummy data" menu option case R.id.action_insert_dummy_data: insertHabit(); displayDatabaseInfo(); readData(); return true; // Respond to a click on the "Delete all entries" menu option case R.id.action_delete_all_entries: // Do nothing for now return true; } return super.onOptionsItemSelected(item); } }
41.92891
126
0.616028
c2fc2cb2d377d74bbffae9a17316d794f8c25a05
5,588
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.imagebuilder.model.transform; import java.util.Map; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.imagebuilder.model.*; import com.amazonaws.util.IdempotentUtils; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * ImportComponentRequestMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class ImportComponentRequestMarshaller { private static final MarshallingInfo<String> NAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("name").build(); private static final MarshallingInfo<String> SEMANTICVERSION_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("semanticVersion").build(); private static final MarshallingInfo<String> DESCRIPTION_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("description").build(); private static final MarshallingInfo<String> CHANGEDESCRIPTION_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("changeDescription").build(); private static final MarshallingInfo<String> TYPE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("type").build(); private static final MarshallingInfo<String> FORMAT_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("format").build(); private static final MarshallingInfo<String> PLATFORM_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("platform").build(); private static final MarshallingInfo<String> DATA_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("data").build(); private static final MarshallingInfo<String> URI_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("uri").build(); private static final MarshallingInfo<String> KMSKEYID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("kmsKeyId").build(); private static final MarshallingInfo<Map> TAGS_BINDING = MarshallingInfo.builder(MarshallingType.MAP).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("tags").build(); private static final MarshallingInfo<String> CLIENTTOKEN_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("clientToken") .defaultValueSupplier(com.amazonaws.util.IdempotentUtils.getGenerator()).build(); private static final ImportComponentRequestMarshaller instance = new ImportComponentRequestMarshaller(); public static ImportComponentRequestMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(ImportComponentRequest importComponentRequest, ProtocolMarshaller protocolMarshaller) { if (importComponentRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(importComponentRequest.getName(), NAME_BINDING); protocolMarshaller.marshall(importComponentRequest.getSemanticVersion(), SEMANTICVERSION_BINDING); protocolMarshaller.marshall(importComponentRequest.getDescription(), DESCRIPTION_BINDING); protocolMarshaller.marshall(importComponentRequest.getChangeDescription(), CHANGEDESCRIPTION_BINDING); protocolMarshaller.marshall(importComponentRequest.getType(), TYPE_BINDING); protocolMarshaller.marshall(importComponentRequest.getFormat(), FORMAT_BINDING); protocolMarshaller.marshall(importComponentRequest.getPlatform(), PLATFORM_BINDING); protocolMarshaller.marshall(importComponentRequest.getData(), DATA_BINDING); protocolMarshaller.marshall(importComponentRequest.getUri(), URI_BINDING); protocolMarshaller.marshall(importComponentRequest.getKmsKeyId(), KMSKEYID_BINDING); protocolMarshaller.marshall(importComponentRequest.getTags(), TAGS_BINDING); protocolMarshaller.marshall(importComponentRequest.getClientToken(), CLIENTTOKEN_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
59.446809
158
0.769506
d20c3b3774bcda553b6f6aa24a00bccfa71098ee
3,649
package oosd.controllers; import java.io.IOException; import java.util.ArrayList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.input.MouseEvent; import javafx.scene.layout.Pane; import javafx.stage.Stage; import oosd.Main; import oosd.helpers.Movement; import oosd.helpers.UndoContainer; import oosd.models.GameEngine; import oosd.models.board.Piece; import oosd.views.BoardView; import oosd.views.components.BoardPane; import oosd.views.components.Hexagon; import oosd.views.components.SidebarPane; import oosd.views.components.ToolbarPane; import oosd.views.components.WindowGridPane; /** * GRASP: The controller * Used to handle requests from other objects include the view and model. * Acts as a middleman that delegates tasks to other objects. * Cleanly separates the user interface (view) from the business objects (model) */ public class MainController extends Controller { @FXML private Stage primaryStage; @FXML private WindowGridPane windowGridPane; @FXML private BoardPane boardPane; @FXML private SidebarPane sidebar; @FXML private ToolbarPane toolbar; private BoardView boardView; private final String boardFileName = "board.fxml"; private final String windowTitle = "OOSD Game GameBoard"; private final int sceneWidth = 1200; private final int sceneHeight = 900; public MainController(Stage primaryStage) { this.primaryStage = primaryStage; } @FXML protected void handleSubmitButtonAction(ActionEvent event) { System.out.println("poop"); } @FXML protected void handleSmallBoardButtonAction(ActionEvent event) throws IOException { System.out.println("poop"); GameController gameController = new GameController(Main.initializeGameEngine(1)); FXMLLoader loader = new FXMLLoader(GameController.class.getResource(boardFileName)); loader.setController(gameController); Pane pane = loader.load(); Scene content = new Scene(pane, sceneWidth, sceneHeight); primaryStage.setScene(content); primaryStage.setTitle(windowTitle); primaryStage.setResizable(false); primaryStage.show(); } @FXML protected void handleMediumBoardButtonAction(ActionEvent event) throws IOException { System.out.println("poop"); GameController gameController = new GameController(Main.initializeGameEngine(2)); FXMLLoader loader = new FXMLLoader(GameController.class.getResource(boardFileName)); loader.setController(gameController); Pane pane = loader.load(); Scene content = new Scene(pane, sceneWidth, sceneHeight); primaryStage.setScene(content); primaryStage.setTitle(windowTitle); primaryStage.setResizable(true); primaryStage.show(); } @FXML protected void handleLargeBoardButtonAction(ActionEvent event) throws IOException { System.out.println("poop"); GameController gameController = new GameController(Main.initializeGameEngine(3)); FXMLLoader loader = new FXMLLoader(GameController.class.getResource(boardFileName)); loader.setController(gameController); Pane pane = loader.load(); Scene content = new Scene(pane, sceneWidth, sceneHeight); primaryStage.setScene(content); primaryStage.setTitle(windowTitle); primaryStage.setResizable(true); primaryStage.show(); } @Override void initialize() { } }
28.069231
94
0.71225
beb2b911b08a7df12fc899ce9b1ea888cc483c8e
2,704
import java.util.*; import java.io.*; public class Shoppinglist { public static void main(String args[]) { Vector itemList = new Vector(); String str, item; int i, j, len, choice, pos; len = args.length; for (i = 0; i < len; i++) itemList.addElement(args[i]); while (true) { System.out.println("Choose your choice ..."); System.out.println("1) Delete Item"); System.out.println("2) Add Item at Specified Location "); System.out.println("3) Add Item at the End of the list"); System.out.println("4) Print Vector List "); System.out.println("5) Exit"); System.out.print("Enter your choice : "); System.out.flush(); try { BufferedReader obj = new BufferedReader(new InputStreamReader(System.in)); str = obj.readLine(); choice = Integer.parseInt(str); switch (choice) { case 1: System.out.print("Enter Item you want to delete : "); str = obj.readLine(); itemList.removeElement(str); break; case 2: System.out.print("Enter Item to be Insert : "); System.out.flush(); item = obj.readLine(); System.out.print("Enter Position to insert item : "); str = obj.readLine(); pos = Integer.parseInt(str); itemList.insertElementAt(item, pos - 1); break; case 3: System.out.print("Enter Item to be Insert : "); System.out.flush(); item = obj.readLine(); itemList.addElement(item); break; case 4: len = itemList.size(); System.out.println("\nItem Display "); for (i = 0; i < len; i++) { System.out.println((i + 1) + ") " + itemList.elementAt(i)); } break; case 5: System.out.println("\n\nThank You for using this software....."); System.exit(1); break; default: System.out.println("\nEntered Choice is Invalid\nTry Again\n"); } } catch (Exception e) { } } } }
42.25
90
0.419749
7935284fc46493367fd3b58778ccbd6a9b9ee14b
10,304
package com.paul.ioc.bean; import com.paul.http.NettyHttpServer; import com.paul.ioc.annotation.*; import com.paul.mvc.annotation.RequestMapping; import java.io.File; import java.io.FileFilter; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class AnnotationApplicationContext extends ApplicationContext { //保存类路径的缓存 private List<String> classCache = Collections.synchronizedList(new ArrayList<String>()); //保存需要注入的类的缓存 private List<Class<?>> beanDefinition = Collections.synchronizedList(new ArrayList<Class<?>>()); //保存类实例的容器 public Map<String,Object> beanFactory = new ConcurrentHashMap<>(); // 完整路径和 方法的 mapping public Map<String,Object> handleMapping = new ConcurrentHashMap<>(); // 类路径和controller 的 mapping public Map<String,Object> controllerMapping = new ConcurrentHashMap<>(); public AnnotationApplicationContext(String configuration) { super(configuration); String path = xmlUtil.handlerXMLForScanPackage(configuration); //执行包的扫描操作 scanPackage(path); //注册bean registerBean(); //把对象创建出来,忽略依赖关系 doCreateBean(); //执行容器管理实例对象运行期间的依赖装配 diBean(); //mvc 相关注解扫描 mappingMVC(); //启动 netty 服务器 NettyHttpServer instance = NettyHttpServer.getInstance(); try { instance.start(this); } catch (InterruptedException e) { e.printStackTrace(); } } /* * MVC 注解和路径扫描 */ private void mappingMVC() { //上一步已经完成了 Controller,service,respostry,autowired 等注解的扫描和注入 //遍历容器,将 requestmapping 注解的路径和对应的方法以及 contoller 实例对应起来 for(Map.Entry<String,Object> entry:beanFactory.entrySet()){ Object instance = entry.getValue(); Class<?> clazz = instance.getClass(); if(clazz.isAnnotationPresent(Controller.class)){ RequestMapping requestMapping = clazz.getAnnotation(RequestMapping.class); String classPath = requestMapping.value(); Method[] methods = clazz.getMethods(); for(Method method:methods){ if(method.isAnnotationPresent(RequestMapping.class)){ RequestMapping requestMapping2 = method.getAnnotation(RequestMapping.class); String methodPath = requestMapping2.value(); String requestPath = classPath + methodPath; handleMapping.put(requestPath,method); controllerMapping.put(requestPath,instance); }else{ continue; } } }else{ continue; } } } @Override protected Object doGetBean(String beanName) { return beanFactory.get(beanName); } /** * 扫描包下面所有的 .class 文件的类路径到上面的List中 * */ private void scanPackage(final String path) { System.out.println("path:"+path); URL url = this.getClass().getClassLoader().getResource(path.replaceAll("\\.", "/")); System.out.println("scanPackage:" + url.getPath()); try { File file = new File(url.toURI()); file.listFiles(new FileFilter(){ //pathname 表示当前目录下的所有文件 @Override public boolean accept(File pathname) { //递归查找文件 if(pathname.isDirectory()){ scanPackage(path+"."+pathname.getName()); }else{ if(pathname.getName().endsWith(".class")){ String classPath = path + "." + pathname.getName().replace(".class",""); System.out.println("addClassPath:" +classPath ); classCache.add(classPath); } } return true; } }); } catch (URISyntaxException e) { e.printStackTrace(); } } /** * 根据类路径获得 class 对象 */ private void registerBean() { if(classCache.isEmpty()){ return; } for(String path:classCache){ try { //使用反射,通过类路径获取class 对象 Class<?> clazz = Class.forName(path); //找出需要被容器管理的类,比如,@Component,@org.test.demo.Controller,@org.test.demo.Service,@Repository if(clazz.isAnnotationPresent(Repository.class)||clazz.isAnnotationPresent(Service.class) ||clazz.isAnnotationPresent(Controller.class)|| clazz.isAnnotationPresent(Component.class)){ beanDefinition.add(clazz); } } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /** * * 根据类对象,创建实例 */ private void doCreateBean() { if(beanDefinition.isEmpty()){ return; } for(Class clazz:beanDefinition){ try { Object instance = clazz.newInstance(); //将首字母小写的类名作为默认的 bean 的名字 String aliasName = lowerClass(clazz.getSimpleName()); //先判断@ 注解里面是否给了 Bean 名字,有的话,这个就作为 Bean 的名字 if(clazz.isAnnotationPresent(Repository.class)){ Repository repository = (Repository) clazz.getAnnotation(Repository.class); if(!"".equals(repository.value())){ aliasName = repository.value(); } } if(clazz.isAnnotationPresent(Service.class)){ Service service = (Service) clazz.getAnnotation(Service.class); if(!"".equals(service.value())){ aliasName = service.value(); } } if(clazz.isAnnotationPresent(Controller.class)){ Controller controller = (Controller) clazz.getAnnotation(Controller.class); if(!"".equals(controller.value())){ aliasName = controller.value(); } } if(clazz.isAnnotationPresent(Component.class)){ Component component = (Component) clazz.getAnnotation(Component.class); if(!"".equals(component.value())){ aliasName = component.value(); } } if(beanFactory.get(aliasName)== null){ beanFactory.put(aliasName, instance); } //判断当前类是否实现了接口 Class<?>[] interfaces = clazz.getInterfaces(); if(interfaces == null){ continue; } //把当前接口的路径作为key存储到容器中 for(Class<?> interf:interfaces){ beanFactory.put(interf.getName(), instance); } } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } for (Map.Entry<String, Object> entry : beanFactory.entrySet()) { System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); } } /** * 对创建好的对象进行依赖注入 */ private void diBean() { if(beanFactory.isEmpty()){ return; } for(Class<?> clazz:beanDefinition){ String aliasName = lowerClass(clazz.getSimpleName()); //先判断@ 注解里面是否给了 Bean 名字,有的话,这个就作为 Bean 的名字 if(clazz.isAnnotationPresent(Repository.class)){ Repository repository = clazz.getAnnotation(Repository.class); if(!"".equals(repository.value())){ aliasName = repository.value(); } } if(clazz.isAnnotationPresent(Service.class)){ Service service = clazz.getAnnotation(Service.class); if(!"".equals(service.value())){ aliasName = service.value(); } } if(clazz.isAnnotationPresent(Controller.class)){ Controller controller = clazz.getAnnotation(Controller.class); if(!"".equals(controller.value())){ aliasName = controller.value(); } } if(clazz.isAnnotationPresent(Component.class)){ Component component = clazz.getAnnotation(Component.class); if(!"".equals(component.value())){ aliasName = component.value(); } } //根据别名获取到被装配的 bean 的实例 Object instance = beanFactory.get(aliasName); try{ //从类中获取参数,判断是否有 @Autowired 注解 Field[] fields = clazz.getDeclaredFields(); for(Field f:fields){ if(f.isAnnotationPresent(Autowired.class)){ //开启字段的访问权限 f.setAccessible(true); Autowired autoWired = f.getAnnotation(Autowired.class); if(!"".equals(autoWired.value())){ //注解里写了别名 f.set(instance, beanFactory.get(autoWired.value())); }else{ //按类型名称 String fieldName = f.getType().getName(); f.set(instance, beanFactory.get(fieldName)); } } } }catch(Exception e){ e.printStackTrace(); } } } private String lowerClass(String simpleName) { char[] chars = simpleName.toCharArray(); chars[0] += 32; String res = String.valueOf(chars); return res; } }
33.563518
116
0.518828
877a9b236561c680ad52e2168d56d7d191781be8
307
package com.iexec.worker.pubsub; import org.junit.Before; import org.mockito.InjectMocks; import org.mockito.MockitoAnnotations; public class StompClientTests { @InjectMocks private StompClient stompClient; @Before public void init() { MockitoAnnotations.openMocks(this); } }
19.1875
43
0.736156
5ca9577c3bd6f1c309f669235f17d06ce4cc2f1c
327
package com.dhemery.core; /** * A builder that describes itself with a fixed name. * @param <T> the type of object to build */ public abstract class NamedBuilder<T> extends Named implements SelfDescribingBuilder<T> { /** * Create a named builder. */ public NamedBuilder(String name) { super(name); } }
21.8
89
0.678899
527031c6338b80d764e484198de7027e156555c2
36,582
/* * Copyright 2010-2019 Australian Signals Directorate * * 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 au.gov.asd.tac.constellation.testing.construction; import au.gov.asd.tac.constellation.graph.GraphElementType; import au.gov.asd.tac.constellation.graph.GraphWriteMethods; import au.gov.asd.tac.constellation.graph.attribute.BooleanAttributeDescription; import au.gov.asd.tac.constellation.graph.attribute.FloatAttributeDescription; import au.gov.asd.tac.constellation.graph.attribute.StringAttributeDescription; import au.gov.asd.tac.constellation.graph.interaction.InteractiveGraphPluginRegistry; import au.gov.asd.tac.constellation.graph.schema.analytic.concept.AnalyticConcept; import au.gov.asd.tac.constellation.graph.schema.analytic.concept.SpatialConcept; import au.gov.asd.tac.constellation.graph.schema.analytic.concept.TemporalConcept; import au.gov.asd.tac.constellation.graph.schema.visual.GraphLabel; import au.gov.asd.tac.constellation.graph.schema.visual.GraphLabels; import au.gov.asd.tac.constellation.graph.schema.visual.VertexDecorators; import au.gov.asd.tac.constellation.graph.schema.visual.attribute.objects.Blaze; import au.gov.asd.tac.constellation.graph.schema.visual.concept.VisualConcept; import au.gov.asd.tac.constellation.graph.visual.graphics.BBoxf; import au.gov.asd.tac.constellation.plugins.Plugin; import au.gov.asd.tac.constellation.plugins.PluginException; import au.gov.asd.tac.constellation.plugins.PluginExecution; import au.gov.asd.tac.constellation.plugins.PluginInteraction; import au.gov.asd.tac.constellation.plugins.arrangements.ArrangementPluginRegistry; import au.gov.asd.tac.constellation.plugins.parameters.PluginParameter; import au.gov.asd.tac.constellation.plugins.parameters.PluginParameters; import au.gov.asd.tac.constellation.plugins.parameters.types.BooleanParameterType; import au.gov.asd.tac.constellation.plugins.parameters.types.BooleanParameterType.BooleanParameterValue; import au.gov.asd.tac.constellation.plugins.parameters.types.IntegerParameterType; import au.gov.asd.tac.constellation.plugins.parameters.types.IntegerParameterType.IntegerParameterValue; import au.gov.asd.tac.constellation.plugins.parameters.types.SingleChoiceParameterType; import au.gov.asd.tac.constellation.plugins.templates.SimpleEditPlugin; import au.gov.asd.tac.constellation.utilities.color.ConstellationColor; import au.gov.asd.tac.constellation.utilities.font.FontUtilities; import au.gov.asd.tac.constellation.utilities.icon.IconManager; import au.gov.asd.tac.constellation.utilities.visual.LineStyle; import java.awt.Font; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.openide.util.Exceptions; import org.openide.util.NbBundle.Messages; import org.openide.util.lookup.ServiceProvider; import org.openide.util.lookup.ServiceProviders; /** * A data access plugin that builds a random sphere graph. * <p> * The sphere graph is not just a random graph, it is meant to exercise * renderer functionality: visibility, dimness, color combinations of * transactions, many transactions between nodes, etc. * * @author canis_majoris */ @ServiceProviders({ @ServiceProvider(service = Plugin.class) }) @Messages("SphereGraphBuilderPlugin=Sphere Graph Builder") public class SphereGraphBuilderPlugin extends SimpleEditPlugin { public static final String N_PARAMETER_ID = PluginParameter.buildId(SphereGraphBuilderPlugin.class, "n"); public static final String T_PARAMETER_ID = PluginParameter.buildId(SphereGraphBuilderPlugin.class, "t"); public static final String OPTION_PARAMETER_ID = PluginParameter.buildId(SphereGraphBuilderPlugin.class, "option"); public static final String ADD_CHARS_PARAMETER_ID = PluginParameter.buildId(SphereGraphBuilderPlugin.class, "add_chars"); public static final String USE_LABELS_PARAMETER_ID = PluginParameter.buildId(SphereGraphBuilderPlugin.class, "use_labels"); public static final String USE_RANDOM_ICONS_PARAMETER_ID = PluginParameter.buildId(SphereGraphBuilderPlugin.class, "use_random_icons"); public static final String USE_ALL_DISPLAYABLE_CHARS_PARAMETER_ID = PluginParameter.buildId(SphereGraphBuilderPlugin.class, "use_all_displayable_chars"); public static final String DRAW_MANY_TX_PARAMETER_ID = PluginParameter.buildId(SphereGraphBuilderPlugin.class, "draw_many_tx"); public static final String DRAW_MANY_DECORATORS_PARAMETER_ID = PluginParameter.buildId(SphereGraphBuilderPlugin.class, "draw_many_deco"); private static final String NODE = "~Node "; private static final String TYPE = "~Type "; private static final String BACKGROUND_ROUND_CIRCLE = "Background.Round Circle"; private final SecureRandom random = new SecureRandom(); @Override public String getDescription() { return "Builds a random sphere graph."; } @Override public PluginParameters createParameters() { final PluginParameters params = new PluginParameters(); final PluginParameter<IntegerParameterValue> n = IntegerParameterType.build(N_PARAMETER_ID); n.setName("Number of nodes"); n.setDescription("The number of nodes on the graph"); n.setIntegerValue(100); IntegerParameterType.setMinimum(n, 6); params.addParameter(n); final PluginParameter<IntegerParameterValue> t = IntegerParameterType.build(T_PARAMETER_ID); t.setName("Number of transactions"); t.setDescription("The number of transactions on the graph"); t.setIntegerValue(50); IntegerParameterType.setMinimum(t, 0); params.addParameter(t); ArrayList<String> modes = new ArrayList<>(); modes.add("Random vertices"); modes.add("1 path, next neighbour"); modes.add("1 path, random vertices"); final PluginParameter<SingleChoiceParameterType.SingleChoiceParameterValue> option = SingleChoiceParameterType.build(OPTION_PARAMETER_ID); option.setName("Transaction options"); option.setDescription("How to add transactions to the graph"); SingleChoiceParameterType.setOptions(option, modes); SingleChoiceParameterType.setChoice(option, modes.get(0)); params.addParameter(option); final PluginParameter<BooleanParameterValue> randomChars = BooleanParameterType.build(ADD_CHARS_PARAMETER_ID); randomChars.setName("Add random chars to vertex name"); randomChars.setDescription("Add random chars to vertex name"); randomChars.setBooleanValue(true); params.addParameter(randomChars); final PluginParameter<BooleanParameterValue> addLabels = BooleanParameterType.build(USE_LABELS_PARAMETER_ID); addLabels.setName("Add labels"); addLabels.setDescription("Labels nodes and transactions"); addLabels.setBooleanValue(true); params.addParameter(addLabels); final PluginParameter<BooleanParameterValue> allChars = BooleanParameterType.build(USE_ALL_DISPLAYABLE_CHARS_PARAMETER_ID); allChars.setName("All displayable chars"); allChars.setDescription("Use all displayable chars in labels"); allChars.setBooleanValue(false); params.addParameter(allChars); final PluginParameter<BooleanParameterValue> drawManyTx = BooleanParameterType.build(DRAW_MANY_TX_PARAMETER_ID); drawManyTx.setName("Draw many transactions"); drawManyTx.setDescription("Draw lots of transactions between nodes"); drawManyTx.setBooleanValue(false); params.addParameter(drawManyTx); final PluginParameter<BooleanParameterValue> drawManyDeco = BooleanParameterType.build(DRAW_MANY_DECORATORS_PARAMETER_ID); drawManyDeco.setName("Draw many decorators"); drawManyDeco.setDescription("Draw lots of decorators on nodes"); drawManyDeco.setBooleanValue(false); params.addParameter(drawManyDeco); final PluginParameter<BooleanParameterValue> randomIcons = BooleanParameterType.build(USE_RANDOM_ICONS_PARAMETER_ID); randomIcons.setName("Random icons and decorators"); randomIcons.setDescription("Use random icons and decorators on nodes"); randomIcons.setBooleanValue(true); params.addParameter(randomIcons); return params; } @Override public void edit(final GraphWriteMethods graph, final PluginInteraction interaction, final PluginParameters parameters) throws InterruptedException, PluginException { interaction.setProgress(0, 0, "Building...", true); // The default icon. // final String DEFAULT_ICON = "HAL-9000"; // The first of a sequence of random characters.. // final int PLAY_CHARS = 0x261A; // The number of random characters. // final int PLAY_CHARS_LEN = 86; final int vertexCount = graph.getVertexCount(); // Parameter values. // final Map<String, PluginParameter<?>> params = parameters.getParameters(); final int nVx = Math.max(params.get(N_PARAMETER_ID).getIntegerValue()-6, 0); final int nTx = params.get(T_PARAMETER_ID).getIntegerValue(); final String option = params.get(OPTION_PARAMETER_ID).getStringValue(); final boolean addChars = params.get(ADD_CHARS_PARAMETER_ID).getBooleanValue(); final boolean useLabels = params.get(USE_LABELS_PARAMETER_ID).getBooleanValue(); final boolean allDisplayableChars = params.get(USE_ALL_DISPLAYABLE_CHARS_PARAMETER_ID).getBooleanValue(); final boolean drawManyTx = params.get(DRAW_MANY_TX_PARAMETER_ID).getBooleanValue(); final boolean drawManyDecorators = params.get(DRAW_MANY_DECORATORS_PARAMETER_ID).getBooleanValue(); final boolean useRandomIcons = params.get(USE_RANDOM_ICONS_PARAMETER_ID).getBooleanValue(); // select some icons to put in the graph final List<String> iconLabels = new ArrayList<>(); if (useRandomIcons) { IconManager.getIconNames(null).forEach(iconLabels::add); } // Select some countries to put in the graph. // Since it's entirely possible that the country names will be used for decorators, // we only want countries that have flags. // Therefore we'll look for flags, not countries. // final List<String> countries = IconManager.getIcons() .stream() .filter(icon -> icon.getExtendedName().startsWith("Flag.")) .map(icon -> icon.getName()) .collect(Collectors.toUnmodifiableList()); final int maxTxId = VisualConcept.GraphAttribute.MAX_TRANSACTIONS.ensure(graph); if (drawManyTx) { graph.setIntValue(maxTxId, 0, 100); } final int vxLabelAttr = VisualConcept.VertexAttribute.LABEL.ensure(graph); final int vxIdentifierAttr = VisualConcept.VertexAttribute.IDENTIFIER.ensure(graph); final int vxTypeAttr = AnalyticConcept.VertexAttribute.TYPE.ensure(graph); final int vxRadiusAttr = VisualConcept.VertexAttribute.NODE_RADIUS.ensure(graph); final int vxSelectedAttr = VisualConcept.VertexAttribute.SELECTED.ensure(graph); final int vxDimmedAttr = VisualConcept.VertexAttribute.DIMMED.ensure(graph); final int vxVisibilityAttr = VisualConcept.VertexAttribute.VISIBILITY.ensure(graph); final int vxColorAttr = VisualConcept.VertexAttribute.COLOR.ensure(graph); final int vxForegroundIconAttr = VisualConcept.VertexAttribute.FOREGROUND_ICON.ensure(graph); final int vxBackgroundIconAttr = VisualConcept.VertexAttribute.BACKGROUND_ICON.ensure(graph); final int attrBlaze = VisualConcept.VertexAttribute.BLAZE.ensure(graph); final int vxXAttr = VisualConcept.VertexAttribute.X.ensure(graph); final int vxYAttr = VisualConcept.VertexAttribute.Y.ensure(graph); final int vxZAttr = VisualConcept.VertexAttribute.Z.ensure(graph); final int vxX2Attr = VisualConcept.VertexAttribute.X2.ensure(graph); final int vxY2Attr = VisualConcept.VertexAttribute.Y2.ensure(graph); final int vxZ2Attr = VisualConcept.VertexAttribute.Z2.ensure(graph); final int vxIsGoodAttr = graph.addAttribute(GraphElementType.VERTEX, BooleanAttributeDescription.ATTRIBUTE_NAME, "isGood", null, false, null); final int vxCountry1Attr = SpatialConcept.VertexAttribute.COUNTRY.ensure(graph); final int vxCountry2Attr = graph.addAttribute(GraphElementType.VERTEX, StringAttributeDescription.ATTRIBUTE_NAME, "Geo.Country2", null, null, null); final int vxDecoratorAttr = graph.addAttribute(GraphElementType.VERTEX, StringAttributeDescription.ATTRIBUTE_NAME, "Custom Decorator", null, null, null); final int vxNormalisedAttr = graph.addAttribute(GraphElementType.VERTEX, FloatAttributeDescription.ATTRIBUTE_NAME, "Normalised", null, 0.0f, null); final int txIdAttr = VisualConcept.TransactionAttribute.IDENTIFIER.ensure(graph); final int txDirectedAttr = VisualConcept.TransactionAttribute.DIRECTED.ensure(graph); final int txWidthAttr = VisualConcept.TransactionAttribute.WIDTH.ensure(graph); final int txDimmedAttr = VisualConcept.TransactionAttribute.DIMMED.ensure(graph); final int txVisibilityAttr = VisualConcept.TransactionAttribute.VISIBILITY.ensure(graph); final int txColorAttr = VisualConcept.TransactionAttribute.COLOR.ensure(graph); final int txLineStyleAttr = VisualConcept.TransactionAttribute.LINE_STYLE.ensure(graph); final int txDateTimeAttr = TemporalConcept.TransactionAttribute.DATETIME.ensure(graph); // Add various labels and decorators. final List<GraphLabel> bottomLabels = new ArrayList<>(); final List<GraphLabel> topLabels = new ArrayList<>(); final List<GraphLabel> transactionLabels = new ArrayList<>(); if (useLabels) { bottomLabels.add(new GraphLabel(VisualConcept.VertexAttribute.IDENTIFIER.getName(), ConstellationColor.LIGHT_BLUE)); bottomLabels.add(new GraphLabel(VisualConcept.VertexAttribute.FOREGROUND_ICON.getName(), ConstellationColor.DARK_GREEN, 0.5f)); topLabels.add(new GraphLabel(AnalyticConcept.VertexAttribute.TYPE.getName(), ConstellationColor.MAGENTA, 0.5f)); topLabels.add(new GraphLabel(SpatialConcept.VertexAttribute.COUNTRY.getName(), ConstellationColor.DARK_ORANGE, 0.5f)); transactionLabels.add(new GraphLabel(VisualConcept.TransactionAttribute.VISIBILITY.getName(), ConstellationColor.LIGHT_GREEN)); } final VertexDecorators decorators; if (drawManyDecorators) { decorators = new VertexDecorators(graph.getAttributeName(vxIsGoodAttr), SpatialConcept.VertexAttribute.COUNTRY.getName(), graph.getAttributeName(vxCountry2Attr), graph.getAttributeName(vxDecoratorAttr)); } else { decorators = new VertexDecorators(graph.getAttributeName(vxIsGoodAttr), null, null, null); } final int bottomLabelsAttr = VisualConcept.GraphAttribute.BOTTOM_LABELS.ensure(graph); final int topLabelsAttr = VisualConcept.GraphAttribute.TOP_LABELS.ensure(graph); final int transactionLabelsAttr = VisualConcept.GraphAttribute.TRANSACTION_LABELS.ensure(graph); graph.setObjectValue(bottomLabelsAttr, 0, new GraphLabels(bottomLabels)); graph.setObjectValue(topLabelsAttr, 0, new GraphLabels(topLabels)); graph.setObjectValue(transactionLabelsAttr, 0, new GraphLabels(transactionLabels)); final int decoratorsAttr = VisualConcept.GraphAttribute.DECORATORS.ensure(graph); graph.setObjectValue(decoratorsAttr, 0, decorators); final ConstellationColor.PalettePhiIterator palette = new ConstellationColor.PalettePhiIterator(0, 0.75f, 0.75f); // Displayable characters for type. int c = 33; final Font font = FontUtilities.getOutputFont(); final StringBuilder type = new StringBuilder(); final int[] vxIds = new int[nVx]; int vx = 0; while (vx < nVx) { final float v = nVx > 1 ? vx / (float) (nVx - 1) : 1f; final int vxId = graph.addVertex(); // A label with a random CJK glyph. final String chars; if (addChars && vx == 0) { chars = "مرحبا عالم"; // "Hello world" in arabic, demonstrates unicode rendering } else if (addChars) { chars = " " + (char) (PLAY_CHARS + random.nextInt(PLAY_CHARS_LEN)) + " " + (char) (0x4e00 + random.nextInt(256)); } else { chars = ""; } final String label = "Node " + vxId + chars; if (allDisplayableChars) { type.setLength(0); while (type.length() < 10) { if (font.canDisplay(c)) { type.append((char) c); } // Unicode BMP only has so many characters. c = (c + 1) % 65536; } } graph.setStringValue(vxLabelAttr, vxId, label); graph.setStringValue(vxIdentifierAttr, vxId, String.valueOf(vxId)); graph.setStringValue(vxTypeAttr, vxId, type.toString()); graph.setFloatValue(vxRadiusAttr, vxId, 1); graph.setFloatValue(vxVisibilityAttr, vxId, v); graph.setObjectValue(vxColorAttr, vxId, palette.next()); if (useRandomIcons) { graph.setStringValue(vxForegroundIconAttr, vxId, iconLabels.get(random.nextInt(iconLabels.size()))); graph.setStringValue(vxDecoratorAttr, vxId, iconLabels.get(random.nextInt(iconLabels.size()))); } else { // If icons are non-random, make the first one null. graph.setStringValue(vxForegroundIconAttr, vxId, DEFAULT_ICON); graph.setStringValue(vxDecoratorAttr, vxId, null); } graph.setStringValue(vxBackgroundIconAttr, vxId, useRandomIcons ? (random.nextBoolean() ? "Background.Flat Square" : "Background.Flat Circle") : "Background.Flat Circle"); if (vx == 0) { graph.setStringValue(vxForegroundIconAttr, vxId, null); graph.setObjectValue(attrBlaze, vxId, new Blaze(45, ConstellationColor.LIGHT_BLUE)); } graph.setBooleanValue(vxIsGoodAttr, vxId, vx % 2 == 0); graph.setStringValue(vxCountry1Attr, vxId, countries.get(vx % countries.size())); graph.setStringValue(vxCountry2Attr, vxId, countries.get((vx + 1) % countries.size())); graph.setFloatValue(vxNormalisedAttr, vxId, random.nextFloat()); vxIds[vx] = vxId; vx++; if (Thread.interrupted()) { throw new InterruptedException(); } } // Dimmed nodes. if (nVx == 2) { graph.setBooleanValue(vxDimmedAttr, vxIds[nVx - 1], true); } else if (nVx > 2) { graph.setBooleanValue(vxDimmedAttr, vxIds[nVx - 1], true); graph.setBooleanValue(vxDimmedAttr, vxIds[nVx - 2], true); } if (nVx > 0) { // Create transactions between the nodes. final Date d = new Date(); final int fourDays = 4 * 24 * 60 * 60 * 1000; if (option.equals("Random vertices")) { // Draw some lines between random nodes, but don't draw multiple lines between the same two nodes. for (int i = 0; i < nTx; i++) { // Choose random positions, convert to correct vxIds. // Concentrate most sources to just a few vertices; it looks a bit nicer than plain random. int fromPosition = vertexCount + (random.nextFloat() < 0.9f ? random.nextInt((int) (Math.log10(nVx) * 5) + 1) : random.nextInt(nVx)); int toPosition; do { toPosition = vertexCount + random.nextInt(nVx); } while (toPosition == fromPosition); assert fromPosition != toPosition; int fromVx = graph.getVertex(fromPosition); int toVx = graph.getVertex(toPosition); // Always draw from the lower numbered vertex to the higher numbered vertex. if (toVx < fromVx) { int tmp = fromVx; fromVx = toVx; toVx = tmp; } final int e = graph.addTransaction(fromVx, toVx, true); graph.setLongValue(txDateTimeAttr, e, d.getTime() - random.nextInt(fourDays)); graph.setIntValue(txIdAttr, e, e); graph.setObjectValue(txColorAttr, e, randomColor3(random)); graph.setFloatValue(txVisibilityAttr, e, (float) i / (nTx - 1)); if (Thread.interrupted()) { throw new InterruptedException(); } } } else { if (option.equals("1 path, random vertices")) { // Shuffle the vertices. for (int i = nVx - 1; i > 0; i--) { final int ix = random.nextInt(i); final int t = vxIds[i]; vxIds[i] = vxIds[ix]; vxIds[ix] = t; } } // Transactions from/to each vertex in ascending order, modulo nVx. for (int i = 0; i < nTx; i++) { final int fromNode = vxIds[i % nVx]; final int toNode = vxIds[(i + 1) % nVx]; final int e = graph.addTransaction(fromNode, toNode, true); graph.setLongValue(txDateTimeAttr, e, d.getTime() - random.nextInt(fourDays)); graph.setIntValue(txIdAttr, e, e); graph.setObjectValue(txColorAttr, e, randomColor3(random)); graph.setFloatValue(txVisibilityAttr, e, (float) i / (nTx - 1)); if (Thread.interrupted()) { throw new InterruptedException(); } } } } // Do a spherical layout. try { PluginExecution.withPlugin(ArrangementPluginRegistry.SPHERE).executeNow(graph); } catch (PluginException ex) { Exceptions.printStackTrace(ex); } // Find out where the extremes of the new sphere are and select every 10th vertex. // Provide a lower limit on the radius in case the existing nodes are too close together. // final BBoxf box = new BBoxf(); box.add(8, 8, 8); box.add(-8, -8, -8); for (int position = 0; position < nVx; position++) { final int vxId = graph.getVertex(position); final float x = graph.getFloatValue(vxXAttr, vxId); final float y = graph.getFloatValue(vxYAttr, vxId); final float z = graph.getFloatValue(vxZAttr, vxId); box.add(x, y, z); graph.setBooleanValue(vxSelectedAttr, vxId, vxId % 10 == 0); } // Create nodes just outside the centres of the bounding box's sides. final float[] min = box.getMin(); final float[] max = box.getMax(); if (box.isEmpty()) { Arrays.fill(min, 0); Arrays.fill(max, 0); } char circleChar = 0x2460; final int nodeRadius = 3; final int vx0 = graph.addVertex(); ConstructionUtilities.setxyz(graph, vx0, vxXAttr, vxYAttr, vxZAttr, min[BBoxf.X], max[BBoxf.Y], max[BBoxf.Z]); ConstructionUtilities.setxyz(graph, vx0, vxX2Attr, vxY2Attr, vxZ2Attr, min[BBoxf.X]/2, max[BBoxf.Y]/2, max[BBoxf.Z]/2); graph.setStringValue(vxLabelAttr, vx0, NODE + vx0 + " " + circleChar++); graph.setStringValue(vxIdentifierAttr, vx0, String.valueOf(vx0)); graph.setStringValue(vxTypeAttr, vx0, TYPE + vx0); graph.setFloatValue(vxRadiusAttr, vx0, nodeRadius); graph.setFloatValue(vxVisibilityAttr, vx0, 1); graph.setObjectValue(vxColorAttr, vx0, randomColor3(random)); graph.setStringValue(vxForegroundIconAttr, vx0, DEFAULT_ICON); graph.setStringValue(vxBackgroundIconAttr, vx0, BACKGROUND_ROUND_CIRCLE); graph.setStringValue(vxCountry1Attr, vx0, countries.get(vx0 % countries.size())); graph.setStringValue(vxCountry2Attr, vx0, countries.get((vx0 + 1) % countries.size())); graph.setFloatValue(vxNormalisedAttr, vx0, random.nextFloat()); graph.setObjectValue(attrBlaze, vx0, new Blaze(random.nextInt(360), randomColor3(random))); final int vx1 = graph.addVertex(); ConstructionUtilities.setxyz(graph, vx1, vxXAttr, vxYAttr, vxZAttr, max[BBoxf.X], max[BBoxf.Y], max[BBoxf.Z]); ConstructionUtilities.setxyz(graph, vx1, vxX2Attr, vxY2Attr, vxZ2Attr, max[BBoxf.X]/2, max[BBoxf.Y]/2, max[BBoxf.Z]/2); graph.setStringValue(vxLabelAttr, vx1, NODE + vx1 + " " + circleChar++); graph.setStringValue(vxIdentifierAttr, vx1, String.valueOf(vx1)); graph.setStringValue(vxTypeAttr, vx1, TYPE + vx1); graph.setFloatValue(vxRadiusAttr, vx1, nodeRadius); graph.setFloatValue(vxVisibilityAttr, vx1, 1); graph.setObjectValue(vxColorAttr, vx1, randomColor3(random)); graph.setStringValue(vxForegroundIconAttr, vx1, DEFAULT_ICON); graph.setStringValue(vxBackgroundIconAttr, vx1, BACKGROUND_ROUND_CIRCLE); graph.setStringValue(vxCountry1Attr, vx1, countries.get(vx1 % countries.size())); graph.setStringValue(vxCountry2Attr, vx1, countries.get((vx1 + 1) % countries.size())); graph.setFloatValue(vxNormalisedAttr, vx1, random.nextFloat()); graph.setObjectValue(attrBlaze, vx1, new Blaze(random.nextInt(360), randomColor3(random))); final int vx2 = graph.addVertex(); ConstructionUtilities.setxyz(graph, vx2, vxXAttr, vxYAttr, vxZAttr, max[BBoxf.X], min[BBoxf.Y], max[BBoxf.Z]); ConstructionUtilities.setxyz(graph, vx2, vxX2Attr, vxY2Attr, vxZ2Attr, max[BBoxf.X]/2, min[BBoxf.Y]/2, max[BBoxf.Z]/2); graph.setStringValue(vxLabelAttr, vx2, NODE + vx2 + " " + circleChar++); graph.setStringValue(vxIdentifierAttr, vx2, String.valueOf(vx2)); graph.setStringValue(vxTypeAttr, vx2, TYPE + vx2); graph.setFloatValue(vxRadiusAttr, vx2, nodeRadius); graph.setFloatValue(vxVisibilityAttr, vx2, 1); graph.setObjectValue(vxColorAttr, vx2, randomColor3(random)); graph.setStringValue(vxForegroundIconAttr, vx2, DEFAULT_ICON); graph.setStringValue(vxBackgroundIconAttr, vx2, BACKGROUND_ROUND_CIRCLE); graph.setStringValue(vxCountry1Attr, vx2, countries.get(vx2 % countries.size())); graph.setStringValue(vxCountry2Attr, vx2, countries.get((vx2 + 1) % countries.size())); graph.setFloatValue(vxNormalisedAttr, vx2, random.nextFloat()); graph.setObjectValue(attrBlaze, vx2, new Blaze(random.nextInt(360), randomColor3(random))); final int vx3 = graph.addVertex(); ConstructionUtilities.setxyz(graph, vx3, vxXAttr, vxYAttr, vxZAttr, min[BBoxf.X], min[BBoxf.Y], min[BBoxf.Z]); ConstructionUtilities.setxyz(graph, vx3, vxX2Attr, vxY2Attr, vxZ2Attr, min[BBoxf.X]/2, min[BBoxf.Y]/2, min[BBoxf.Z]/2); graph.setStringValue(vxLabelAttr, vx3, NODE + vx3 + " " + circleChar++); graph.setStringValue(vxIdentifierAttr, vx3, String.valueOf(vx3)); graph.setStringValue(vxTypeAttr, vx3, TYPE + vx3); graph.setFloatValue(vxRadiusAttr, vx3, nodeRadius); graph.setFloatValue(vxVisibilityAttr, vx3, 1); graph.setObjectValue(vxColorAttr, vx3, randomColor3(random)); graph.setStringValue(vxForegroundIconAttr, vx3, DEFAULT_ICON); graph.setStringValue(vxBackgroundIconAttr, vx2, BACKGROUND_ROUND_CIRCLE); graph.setStringValue(vxCountry1Attr, vx3, countries.get(vx3 % countries.size())); graph.setStringValue(vxCountry2Attr, vx3, countries.get((vx3 + 1) % countries.size())); graph.setFloatValue(vxNormalisedAttr, vx3, random.nextFloat()); graph.setObjectValue(attrBlaze, vx3, new Blaze(random.nextInt(360), randomColor3(random))); final int vx4 = graph.addVertex(); ConstructionUtilities.setxyz(graph, vx4, vxXAttr, vxYAttr, vxZAttr, min[BBoxf.X], max[BBoxf.Y], min[BBoxf.Z]); ConstructionUtilities.setxyz(graph, vx4, vxX2Attr, vxY2Attr, vxZ2Attr, min[BBoxf.X]/2, max[BBoxf.Y]/2, min[BBoxf.Z]/2); graph.setStringValue(vxLabelAttr, vx4, NODE + vx4 + " " + circleChar++); graph.setStringValue(vxIdentifierAttr, vx4, String.valueOf(vx4)); graph.setStringValue(vxTypeAttr, vx4, TYPE + vx4); graph.setFloatValue(vxRadiusAttr, vx4, nodeRadius); graph.setFloatValue(vxVisibilityAttr, vx4, 1); graph.setObjectValue(vxColorAttr, vx4, randomColor3(random)); graph.setStringValue(vxForegroundIconAttr, vx4, DEFAULT_ICON); graph.setStringValue(vxBackgroundIconAttr, vx2, BACKGROUND_ROUND_CIRCLE); graph.setStringValue(vxCountry1Attr, vx4, countries.get(vx4 % countries.size())); graph.setStringValue(vxCountry2Attr, vx4, countries.get((vx4 + 1) % countries.size())); graph.setFloatValue(vxNormalisedAttr, vx4, random.nextFloat()); graph.setObjectValue(attrBlaze, vx4, new Blaze(random.nextInt(360), randomColor3(random))); final int vx5 = graph.addVertex(); ConstructionUtilities.setxyz(graph, vx5, vxXAttr, vxYAttr, vxZAttr, max[BBoxf.X], max[BBoxf.Y], min[BBoxf.Z]); ConstructionUtilities.setxyz(graph, vx5, vxX2Attr, vxY2Attr, vxZ2Attr, max[BBoxf.X]/2, max[BBoxf.Y]/2, min[BBoxf.Z]/2); graph.setStringValue(vxLabelAttr, vx5, NODE + vx5 + " " + circleChar++); graph.setStringValue(vxIdentifierAttr, vx5, String.valueOf(vx5)); graph.setStringValue(vxTypeAttr, vx5, TYPE + vx5); graph.setFloatValue(vxRadiusAttr, vx5, nodeRadius); graph.setFloatValue(vxVisibilityAttr, vx5, 1); graph.setObjectValue(vxColorAttr, vx5, randomColor3(random)); graph.setStringValue(vxForegroundIconAttr, vx5, DEFAULT_ICON); graph.setStringValue(vxBackgroundIconAttr, vx2, BACKGROUND_ROUND_CIRCLE); graph.setStringValue(vxCountry1Attr, vx5, countries.get(vx5 % countries.size())); graph.setStringValue(vxCountry2Attr, vx5, countries.get((vx5 + 1) % countries.size())); graph.setFloatValue(vxNormalisedAttr, vx5, random.nextFloat()); graph.setObjectValue(attrBlaze, vx5, new Blaze(random.nextInt(360), randomColor3(random))); // Draw multiple lines with offsets between two fixed nodes. int txId; // Too many transactions to draw; different colors. final int lim1 = 16; for (int i = 0; i < lim1; i++) { final ConstellationColor rgb = ConstellationColor.getColorValue((float) i / lim1, 0, 1.0f - (float) i / lim1, 1f); if (i % 2 == 0) { txId = graph.addTransaction(vx0, vx1, true); } else { txId = graph.addTransaction(vx1, vx0, true); } graph.setIntValue(txIdAttr, txId, txId); graph.setObjectValue(txColorAttr, txId, rgb); graph.setFloatValue(txVisibilityAttr, txId, 1); } // Not too many transactions to draw; different colors. final int lim2 = 8; for (int i = 0; i < lim2; i++) { final ConstellationColor rgb = ConstellationColor.getColorValue(0.25f, 1.0f - (float) i / lim2, (float) i / lim2, 1f); if (i % 2 == 0) { txId = graph.addTransaction(vx1, vx2, true); } else { txId = graph.addTransaction(vx2, vx1, true); } graph.setIntValue(txIdAttr, txId, txId); graph.setObjectValue(txColorAttr, txId, rgb); graph.setFloatValue(txVisibilityAttr, txId, (i + 1) / (float) lim2); graph.setFloatValue(txWidthAttr, txId, 2f); } // Too many transactions to draw: same color. final int lim3 = 9; final ConstellationColor rgb3 = ConstellationColor.ORANGE; for (int i = 0; i < lim3; i++) { if (i == 0) { txId = graph.addTransaction(vx3, vx4, true); graph.setFloatValue(txVisibilityAttr, txId, 0.3f); } else if (i < 4) { txId = graph.addTransaction(vx3, vx4, false); graph.setFloatValue(txVisibilityAttr, txId, 0.6f); } else { txId = graph.addTransaction(vx4, vx3, true); graph.setFloatValue(txVisibilityAttr, txId, 0.9f); } graph.setIntValue(txIdAttr, txId, txId); graph.setObjectValue(txColorAttr, txId, rgb3); } // Undirected transactions. txId = graph.addTransaction(vx4, vx5, false); graph.setIntValue(txIdAttr, txId, txId); graph.setObjectValue(txColorAttr, txId, ConstellationColor.getColorValue(1f, 0f, 1f, 1f)); graph.setBooleanValue(txDirectedAttr, txId, false); graph.setObjectValue(txLineStyleAttr, txId, LineStyle.DASHED); txId = graph.addTransaction(vx5, vx4, false); graph.setIntValue(txIdAttr, txId, txId); graph.setObjectValue(txColorAttr, txId, ConstellationColor.getColorValue(1f, 1f, 0f, 1f)); graph.setBooleanValue(txDirectedAttr, txId, false); graph.setObjectValue(txLineStyleAttr, txId, LineStyle.DOTTED); // Directed diamond. txId = graph.addTransaction(vx1, vx5, true); graph.setIntValue(txIdAttr, txId, txId); graph.setObjectValue(txColorAttr, txId, ConstellationColor.PINK); graph.setObjectValue(txLineStyleAttr, txId, LineStyle.DIAMOND); // Loops. txId = graph.addTransaction(vx2, vx2, true); graph.setIntValue(txIdAttr, txId, txId); graph.setObjectValue(txColorAttr, txId, ConstellationColor.PINK); txId = graph.addTransaction(vx4, vx4, false); graph.setIntValue(txIdAttr, txId, txId); graph.setBooleanValue(txDirectedAttr, txId, false); graph.setObjectValue(txColorAttr, txId, ConstellationColor.LIGHT_BLUE); txId = graph.addTransaction(vx5, vx5, true); graph.setIntValue(txIdAttr, txId, txId); graph.setObjectValue(txColorAttr, txId, ConstellationColor.ORANGE); txId = graph.addTransaction(vx5, vx5, false); graph.setIntValue(txIdAttr, txId, txId); graph.setObjectValue(txColorAttr, txId, ConstellationColor.GREEN); // Dimmed transactions. txId = graph.addTransaction(vx0, vx5, true); graph.setObjectValue(txColorAttr, txId, ConstellationColor.RED); graph.setBooleanValue(txDimmedAttr, txId, true); txId = graph.addTransaction(vx0, vx5, false); graph.setObjectValue(txColorAttr, txId, ConstellationColor.GREEN); graph.setBooleanValue(txDirectedAttr, txId, false); graph.setBooleanValue(txDimmedAttr, txId, true); txId = graph.addTransaction(vx5, vx0, true); graph.setObjectValue(txColorAttr, txId, ConstellationColor.BLUE); graph.setBooleanValue(txDimmedAttr, txId, true); PluginExecution.withPlugin(InteractiveGraphPluginRegistry.RESET_VIEW).executeNow(graph); interaction.setProgress(1, 0, "Completed successfully", true); } /** * Return a random RGB color. * * @return A random RGB color. */ private static ConstellationColor randomColor3(SecureRandom r) { return ConstellationColor.getColorValue(r.nextFloat(), r.nextFloat(), r.nextFloat(), 1f); } }
54.845577
215
0.676863
dd4c2f501fb0973224926a38c9fa9da218c652d2
3,304
package org.coconut.cache.tck.service.loading; import java.util.Arrays; import java.util.Collection; import org.coconut.attribute.AttributeMap; import org.coconut.cache.service.loading.CacheLoader; import org.coconut.cache.tck.AbstractCacheTCKTest; import org.coconut.core.Logger.Level; import org.coconut.test.throwables.RuntimeException1; import org.junit.Test; public class CacheLoaderErroneous extends AbstractCacheTCKTest { // IntegerToStringLoader @Test public void loadAllRuntime() { MyLoader loader = new MyLoader(); init(conf.loading().setLoader(loader)); loading().loadAll(Arrays.asList(1, 2, 3)); if (loader.key != null) { assertSize(1); assertEquals(loader.value, c.get(loader.key)); exceptionHandler.eat(RuntimeException1.INSTANCE, Level.Fatal); } } @Test public void loadAllRuntime1() { MyLoader loader = new MyLoader(); init(conf.loading().setLoader(loader)); loading().loadAll(Arrays.asList(1)); if (loader.key != null) { assertSize(1); assertEquals(loader.value, c.get(loader.key)); exceptionHandler.eat(RuntimeException1.INSTANCE, Level.Fatal); } } @Test public void failedToComplete() { MyLoader2 loader = new MyLoader2(); init(conf.loading().setLoader(loader)); loading().loadAll(Arrays.asList(1, 2)); if (loader.key != null) { assertSize(1); assertEquals(loader.value, c.get(loader.key)); exceptionHandler.eat(null, Level.Fatal); } } static class MyLoader2 implements CacheLoader<Integer, String> { private Integer key; private String value; public String load(Integer key, AttributeMap attributes) { if (1 <= key && key <= 5) { return "" + (char) (key + 64); } else { return null; } } public void loadAll( Collection<? extends LoaderCallback<? extends Integer, ? super String>> loadCallbacks) { LoaderCallback<? extends Integer, ? super String> clc = loadCallbacks.iterator() .next(); key = clc.getKey(); value = load(clc.getKey(), clc.getAttributes()); clc.completed(value); } } static class MyLoader implements CacheLoader<Integer, String> { private Integer key; private String value; public String load(Integer key, AttributeMap attributes) { if (1 <= key && key <= 5) { return "" + (char) (key + 64); } else { return null; } } public void loadAll( Collection<? extends LoaderCallback<? extends Integer, ? super String>> loadCallbacks) { LoaderCallback<? extends Integer, ? super String> clc = loadCallbacks.iterator() .next(); key = clc.getKey(); value = load(clc.getKey(), clc.getAttributes()); clc.completed(value); throw RuntimeException1.INSTANCE; } } }
31.466667
105
0.563862
6328324b327f76ab3c9d98f859e2a25731eed7d2
806
package org.bukkit.craftbukkit.entity; import net.minecraft.server.EntityExperienceOrb; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.EntityType; import org.bukkit.entity.ExperienceOrb; public class CraftExperienceOrb extends CraftEntity implements ExperienceOrb { public CraftExperienceOrb(CraftServer server, EntityExperienceOrb entity) { super(server, entity); } @Override public int getExperience() { return getHandle().value; } @Override public void setExperience(int value) { getHandle().value = value; } @Override public EntityExperienceOrb getHandle() { return (EntityExperienceOrb) entity; } @Override public String toString() { return "CraftExperienceOrb"; } @Override public EntityType getType() { return EntityType.EXPERIENCE_ORB; } }
20.666667
78
0.775434
8ee8d08dcfdf04f98297cb00612ebb04ac592d1b
883
package edu.ncsu.las.document; import java.util.logging.Level; /** * If no other handlers are available to process the document, this * handler will extract the text and send back into the router for * further processing. * */ public class DefaultHandler extends DocumentHandler { private static String[] MIME_TYPE = { "" }; protected void processDocument() { this.appendText(this.getCurrentDocument().getExtractedTextFromTika()); logger.log(Level.FINEST, this.getClass().getName() + " extracted text"); } @Override public String[] getMimeType() { return MIME_TYPE; } @Override public String getDocumentDomain() { return ""; } @Override public String getDescription() { return "If no available handlers are available, this process extracts the text for processing"; } @Override public int getProcessingOrder() { return Integer.MAX_VALUE; } }
22.641026
97
0.731597
ca465e942c5aaab8880cbaf93b1118314afe06b4
651
package com.youz.log.web; import com.youz.log.util.U; import com.youz.log.util.json.JsonResult; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; @RestController public class LogController { @PostMapping("/upload") public JsonResult upload(MultipartFile file){ U.assertException(file.isEmpty(),"上传失败,请选择文件"); String fileName = file.getOriginalFilename(); System.out.println(fileName); return JsonResult.success("上传成功"); } }
27.125
62
0.749616
824e96febf9ddd90a863c7b397d5f33bbd343c2d
847
package ai.sangmado.gbprotocol.jt905.protocol.exceptions; import ai.sangmado.gbprotocol.gbcommon.enums.IProtocolVersion; /** * 不支持协议版本异常 */ public class UnsupportedJT905ProtocolVersionException extends RuntimeException { static final long serialVersionUID = 8691477310068804322L; public UnsupportedJT905ProtocolVersionException() { this("暂不支持该协议版本"); } public UnsupportedJT905ProtocolVersionException(IProtocolVersion protocolVersion) { this("暂不支持该协议版本: " + protocolVersion); } public UnsupportedJT905ProtocolVersionException(String message) { super(message); } public UnsupportedJT905ProtocolVersionException(String message, Throwable cause) { super(message, cause); } public UnsupportedJT905ProtocolVersionException(Throwable cause) { super(cause); } }
28.233333
87
0.748524
81bafc7071378c0715b181b7ce3b23fbfdffff8f
9,490
/* * (C) Copyright 2020 Radix DLT Ltd * * Radix DLT Ltd licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the * License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific * language governing permissions and limitations under the License. */ package com.radixdlt.network.transport.tcp; import java.io.Closeable; import java.io.IOException; import java.io.UncheckedIOException; import java.net.InetSocketAddress; import java.util.Objects; import java.util.concurrent.atomic.AtomicInteger; import com.radixdlt.counters.SystemCounters; import com.radixdlt.network.messaging.InboundMessage; import io.netty.channel.ChannelInboundHandler; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.subjects.PublishSubject; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.google.common.annotations.VisibleForTesting; import com.google.inject.Inject; import com.google.inject.name.Named; import com.radixdlt.network.transport.StaticTransportMetadata; import com.radixdlt.network.transport.TransportControl; import com.radixdlt.network.transport.TransportMetadata; import com.radixdlt.network.transport.netty.LogSink; import com.radixdlt.network.transport.netty.LoggingHandler; import io.netty.bootstrap.Bootstrap; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.FixedRecvByteBufAllocator; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; import io.netty.handler.codec.LengthFieldPrepender; final class NettyTCPTransportImpl implements NettyTCPTransport { private static final Logger log = LogManager.getLogger(); private static final int CHANNELS_BUFFER_SIZE = 128; // Set this to true to see a detailed hexdump of sent/received data at runtime private final boolean debugData; // Default values if none specified in either localMetadata or config @VisibleForTesting static final String DEFAULT_HOST = "0.0.0.0"; @VisibleForTesting static final int DEFAULT_PORT = 30000; // Minimal send, receive whole max packet plus overhead private static final int SRV_RCV_BUF_SIZE = TCPConstants.MAX_PACKET_LENGTH + 32; private static final int SRV_SND_BUF_SIZE = 100 * 1024; // Minimal receive, send whole max packet plus overhead private static final int CLI_RCV_BUF_SIZE = 100 * 1024; private static final int CLI_SND_BUF_SIZE = TCPConstants.MAX_PACKET_LENGTH + 32; private static final int BACKLOG_SIZE = 100; private final TransportMetadata localMetadata; private final SystemCounters counters; private final int priority; private final int messageBufferSize; private final AtomicInteger threadCounter = new AtomicInteger(0); private final InetSocketAddress bindAddress; private final Object channelLock = new Object(); private final PublishSubject<Observable<InboundMessage>> channels = PublishSubject.create(); private final TCPTransportControl control; private Channel channel; private Bootstrap outboundBootstrap; @Inject NettyTCPTransportImpl( SystemCounters counters, TCPConfiguration config, @Named("local") TransportMetadata localMetadata, TCPTransportOutboundConnectionFactory outboundFactory, TCPTransportControlFactory controlFactory ) { this.counters = Objects.requireNonNull(counters); String providedHost = localMetadata.get(TCPConstants.METADATA_HOST); if (providedHost == null) { providedHost = config.networkAddress(DEFAULT_HOST); } String portString = localMetadata.get(TCPConstants.METADATA_PORT); final int port; if (portString == null) { port = config.networkPort(DEFAULT_PORT); } else { port = Integer.parseInt(portString); } this.localMetadata = StaticTransportMetadata.of( TCPConstants.METADATA_HOST, providedHost, TCPConstants.METADATA_PORT, String.valueOf(port) ); this.priority = config.priority(0); this.messageBufferSize = config.messageBufferSize(2); this.debugData = config.debugData(false); this.control = controlFactory.create(config, outboundFactory, this); this.bindAddress = new InetSocketAddress(providedHost, port); } @Override public String name() { return TCPConstants.NAME; } @Override public TransportControl control() { return control; } @Override public TransportMetadata localMetadata() { return localMetadata; } @Override public boolean canHandle(byte[] message) { return (message == null) || (message.length <= TCPConstants.MAX_PACKET_LENGTH); } @Override public int priority() { return this.priority; } @Override public Observable<InboundMessage> start() { if (log.isInfoEnabled()) { log.info("TCP transport {}", localAddress()); } EventLoopGroup serverGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(1, this::createThread); this.outboundBootstrap = new Bootstrap(); this.outboundBootstrap.group(workerGroup) .channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, true) .option(ChannelOption.SO_KEEPALIVE, true) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) { setupChannel(ch, control.outHandler(), CLI_RCV_BUF_SIZE, CLI_SND_BUF_SIZE); } }); ServerBootstrap b = new ServerBootstrap(); b.group(serverGroup, workerGroup) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, BACKLOG_SIZE) .childOption(ChannelOption.TCP_NODELAY, true) .childOption(ChannelOption.SO_KEEPALIVE, true) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) { log.info("Connection from {}:{}", ch.remoteAddress().getHostString(), ch.remoteAddress().getPort()); setupChannel(ch, control.inHandler(), SRV_RCV_BUF_SIZE, SRV_SND_BUF_SIZE); } }); if (log.isDebugEnabled() || log.isTraceEnabled()) { b.handler(new LoggingHandler(LogSink.using(log), this.debugData)); } try { synchronized (channelLock) { close(); this.channel = b.bind(this.bindAddress).sync().channel(); } } catch (InterruptedException e) { // Abort! Thread.currentThread().interrupt(); } catch (IOException e) { throw new UncheckedIOException("Error while opening channel", e); } return Observable.merge(channels); } private void setupChannel(SocketChannel ch, ChannelInboundHandler handler, int rcvBufSize, int sndBufSize) { final int packetLength = TCPConstants.MAX_PACKET_LENGTH + TCPConstants.LENGTH_HEADER; final int headerLength = TCPConstants.LENGTH_HEADER; ch.config() .setReceiveBufferSize(rcvBufSize) .setSendBufferSize(sndBufSize) .setOption(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(packetLength)); if (log.isDebugEnabled()) { ch.pipeline().addLast(new LoggingHandler(LogSink.using(log), debugData)); } ch.pipeline().addLast("connections", handler); final var messageHandler = new TCPNettyMessageHandler(this.counters, this.messageBufferSize); channels.onNext(messageHandler.inboundMessageRx().toObservable()); ch.pipeline() .addLast("unpack", new LengthFieldBasedFrameDecoder(packetLength, 0, headerLength, 0, headerLength)) .addLast("onboard", messageHandler); ch.pipeline() .addLast("pack", new LengthFieldPrepender(headerLength)); ch.closeFuture() .addListener(f -> messageHandler.shutdownRx()); } @Override public ChannelFuture createChannel(String host, int port) { log.info("Establishing connection to {}:{}", host, port); final ChannelFuture cf = this.outboundBootstrap.connect(host, port); return cf.addListener(v -> { Throwable cause = cf.cause(); if (cause == null) { log.info("Established connection to {}:{}", host, port); } else { log.warn("Connection to {}:{} failed: {}", host, port, cause.getMessage()); } }); } @Override public void close() throws IOException { synchronized (this.channelLock) { closeSafely(this.control); if (this.channel != null) { closeSafely(this.channel::close); } this.channel = null; } } @Override public String toString() { return String.format("%s[%s]", getClass().getSimpleName(), localAddress()); } private String localAddress() { return String.format("%s:%s", bindAddress.getAddress().getHostAddress(), bindAddress.getPort()); } private Thread createThread(Runnable r) { String threadName = String.format("TCP handler %s - %s", localAddress(), threadCounter.incrementAndGet()); log.trace("New thread: {}", threadName); return new Thread(r, threadName); } private void closeSafely(Closeable c) { if (c != null) { try { c.close(); } catch (IOException | UncheckedIOException e) { log.warn(String.format("Error while closing %s", c), e); } } } }
33.298246
109
0.758693
324110724dcaa314e0ce132dd5e3cbec3e40a9a3
5,274
package com.weichu.mdesigner.api.service.impl; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.weichu.mdesigner.api.service.IMemberRechargeConfigService; import com.weichu.mdesigner.api.vo.MemberRechargeConfigVo; import com.weichu.mdesigner.common.entity.MemberRechargeConfig; import com.weichu.mdesigner.common.entity.MemberRechargeConfigExample; import com.weichu.mdesigner.common.mapper.MemberRechargeConfigMapper; import com.weichu.mdesigner.utils.DateUtil; import com.weichu.mdesigner.utils.exception.YdpException; /** * 充值活动配置 * @author Administrator * */ @Service @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class) public class MemberRechargeConfigServiceImpl implements IMemberRechargeConfigService { @Autowired private MemberRechargeConfigMapper mapper; @Override public int save(MemberRechargeConfig rechargeConfig, Integer mid) throws YdpException { if(rechargeConfig.getEffectiveTime() == null) { throw new YdpException("生效时间不能为空"); } if(rechargeConfig.getExpiredTime() != null && rechargeConfig.getEffectiveTime().after(rechargeConfig.getExpiredTime())) { throw new YdpException("生效时间必须早于失效时间"); } rechargeConfig.setCreateTime(new Date()); rechargeConfig.setMerchantId(mid); Date effectiveTime = DateUtil.beginOfDay(rechargeConfig.getEffectiveTime()); rechargeConfig.setEffectiveTime(effectiveTime); if(rechargeConfig.getExpiredTime() != null) { Date expiredTime = DateUtil.endOfDayMysql(rechargeConfig.getExpiredTime()); rechargeConfig.setExpiredTime(expiredTime); } return mapper.insertSelective(rechargeConfig); } @Override public int update(MemberRechargeConfig rechargeConfig, Integer mid) throws YdpException { if(rechargeConfig.getEffectiveTime() == null) { throw new YdpException("生效时间不能为空"); } if(rechargeConfig.getExpiredTime() != null && rechargeConfig.getEffectiveTime().after(rechargeConfig.getExpiredTime())) { throw new YdpException("生效时间必须早于失效时间"); } Date effectiveTime = DateUtil.beginOfDay(rechargeConfig.getEffectiveTime()); rechargeConfig.setEffectiveTime(effectiveTime); if(rechargeConfig.getExpiredTime() != null) { Date expiredTime = DateUtil.endOfDayMysql(rechargeConfig.getExpiredTime()); rechargeConfig.setExpiredTime(expiredTime); } rechargeConfig.setMerchantId(mid); return mapper.updateById(rechargeConfig); } @Override public int delete(Integer id, Integer mid) { MemberRechargeConfigExample example = new MemberRechargeConfigExample(); example.createCriteria().andMerchantIdEqualTo(mid).andIdEqualTo(id); return mapper.deleteByExample(example); } @Override public List<MemberRechargeConfigVo> list(Integer mid) { Date now = new Date(); List<MemberRechargeConfigVo> vos = new ArrayList<>(); MemberRechargeConfigExample example = new MemberRechargeConfigExample(); example.setOrderByClause(" create_time desc "); example.createCriteria().andMerchantIdEqualTo(mid); List<MemberRechargeConfig> rechargeConfig = mapper.selectByExample(example); for (MemberRechargeConfig memberRechargeConfig : rechargeConfig) { MemberRechargeConfigVo vo = new MemberRechargeConfigVo(); BeanUtils.copyProperties(memberRechargeConfig, vo); if(memberRechargeConfig.getEffectiveTime().after(now)) { vo.setEffectived(0);//未生效 } else { vo.setEffectived(1);//已生效 } //==null表示长期有效 if(memberRechargeConfig.getExpiredTime() == null || memberRechargeConfig.getExpiredTime().after(now)) { vo.setExpired(0);//未失效 } else { vo.setExpired(1);//已失效 } vos.add(vo); } return vos; } /** * 查询生效的充值活动 * @param mid * @return */ @Override public List<MemberRechargeConfigVo> listEffective(Integer mid) { Date now = new Date(); List<MemberRechargeConfigVo> vos = new ArrayList<>(); MemberRechargeConfigExample example = new MemberRechargeConfigExample(); example.setOrderByClause(" create_time desc "); example.createCriteria().andMerchantIdEqualTo(mid); List<MemberRechargeConfig> rechargeConfig = mapper.selectByExample(example); for (MemberRechargeConfig memberRechargeConfig : rechargeConfig) { MemberRechargeConfigVo vo = new MemberRechargeConfigVo(); BeanUtils.copyProperties(memberRechargeConfig, vo); if(memberRechargeConfig.getEffectiveTime().after(now)) { //未生效 } else if(memberRechargeConfig.getExpiredTime() == null || memberRechargeConfig.getExpiredTime().after(now)) { //未失效 vos.add(vo); } } return vos; } @Override public MemberRechargeConfig selectById(Integer id, Integer mid) { return mapper.selectById(id, mid); } @Override public MemberRechargeConfig selectByRechargePrice(BigDecimal rechargePrice, Integer mid) { Date now = new Date(); return mapper.selectByRechargePrice(rechargePrice, now, mid); } }
35.635135
129
0.775692
4b8c348ae30c13253879a70c3ab3cab55629c637
656
package ai.datagym.application.labelTask.models.viewModels; public class LabelTaskCompleteViewModel { private boolean hasLabelConfigChanged = false; private String currentTaskId; public LabelTaskCompleteViewModel() { } public boolean isHasLabelConfigChanged() { return hasLabelConfigChanged; } public void setHasLabelConfigChanged(boolean hasLabelConfigChanged) { this.hasLabelConfigChanged = hasLabelConfigChanged; } public String getCurrentTaskId() { return currentTaskId; } public void setCurrentTaskId(String currentTaskId) { this.currentTaskId = currentTaskId; } }
25.230769
73
0.731707
b8fc4e2316962b1e29bca6116829eb6c6378cddf
3,025
package com.sample.domain.service.system; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.Assert; import com.sample.domain.dto.common.Page; import com.sample.domain.dto.common.Pageable; import com.sample.domain.dto.system.CodeCategory; import com.sample.domain.exception.NoDataFoundException; import com.sample.domain.repository.system.CodeCategoryRepository; import com.sample.domain.service.BaseTransactionalService; import lombok.val; /** * コード分類サービス */ @Service public class CodeCategoryService extends BaseTransactionalService { @Autowired CodeCategoryRepository codeCategoryRepository; /** * コード分類を全件取得します。 * * @return */ @Transactional(readOnly = true) // 読み取りのみの場合は指定する public Page<CodeCategory> fetchAll() { // ページングを指定する val pageable = Pageable.NO_LIMIT_PAGEABLE; return codeCategoryRepository.findAll(new CodeCategory(), pageable); } /** * コード分類を一括取得します。 * * @return */ @Transactional(readOnly = true) // 読み取りのみの場合は指定する public Page<CodeCategory> findAll(CodeCategory where, Pageable pageable) { Assert.notNull(where, "where must not be null"); return codeCategoryRepository.findAll(where, pageable); } /** * コード分類を取得します。 * * @return */ @Transactional(readOnly = true) public CodeCategory findById(final Long id) { Assert.notNull(id, "id must not be null"); return codeCategoryRepository.findById(id); } /** * コード分類を取得します。 * * @param categoryKey * @return */ @Transactional(readOnly = true) public CodeCategory findByKey(final String categoryKey) { Assert.notNull(categoryKey, "categoryKey must not be null"); val where = new CodeCategory(); where.setCategoryKey(categoryKey); // 1件取得 return codeCategoryRepository.findOne(where) .orElseThrow(() -> new NoDataFoundException("category_key=" + categoryKey + " のデータが見つかりません。")); } /** * コード分類を追加します。 * * @param inputCodeCategory * @return */ public CodeCategory create(final CodeCategory inputCodeCategory) { Assert.notNull(inputCodeCategory, "inputCodeCategory must not be null"); return codeCategoryRepository.create(inputCodeCategory); } /** * コード分類を更新します。 * * @param inputCodeCategory * @return */ public CodeCategory update(final CodeCategory inputCodeCategory) { Assert.notNull(inputCodeCategory, "inputCodeCategory must not be null"); return codeCategoryRepository.update(inputCodeCategory); } /** * コード分類を論理削除します。 * * @return */ public CodeCategory delete(final Long id) { Assert.notNull(id, "id must not be null"); return codeCategoryRepository.delete(id); } }
27.5
111
0.675372
f737587475008e5e4586e2226734491ae165a83c
1,500
package ru.stqa.pft.addressbook.tests; import org.hamcrest.CoreMatchers; import org.hamcrest.junit.MatcherAssert; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import ru.stqa.pft.addressbook.model.ContactData; import ru.stqa.pft.addressbook.model.Contacts; import java.util.Comparator; import java.util.List; import java.util.Set; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.junit.MatcherAssert.assertThat; import static org.testng.Assert.assertEquals; public class ContactModification extends TestBase{ @BeforeMethod public void ensurePreconditions() { app.goTo().homePage(); if (app.contact().all().size() == 0) { app.initContact(); app.contact().create(new ContactData() .withFirstname("test1").withLastname("test2").withAddress("test3").withMobile("test4").withGroup("test1"), true); } } @Test public void modification() { Contacts before = app.contact().all(); ContactData modifiedContact = before.iterator().next(); ContactData contact = new ContactData() .withId(modifiedContact.getId()).withFirstname("test1").withLastname("test2").withAddress("test3").withMobile("test4").withGroup(null); app.contact().modify(contact); assertThat(app.contact().count(), equalTo(before.size())); Contacts after = app.contact().all(); assertThat(after, equalTo(before.without(modifiedContact).withAdded(contact))); } }
33.333333
147
0.731333
6fbfae4983cf2711bd8f9684395784638f6f85a1
2,745
package com.yan.newaccountbook; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import com.yan.newaccountbook.Adapter.account_rlv_adapter; import com.yan.newaccountbook.Adapter.main_rlv_adapter; import com.yan.newaccountbook.bean.AccountBean; import com.yan.newaccountbook.db.DBManger; import java.util.ArrayList; import java.util.List; public class SearchActivity extends AppCompatActivity implements View.OnClickListener { private ImageView backIv; private EditText searchEt; RecyclerView rlv; List<AccountBean> accountBeanList=new ArrayList<>(); account_rlv_adapter rlv_adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_search); initBack(); initEdit(); } @Override protected void onResume() { super.onResume(); initRlv(); } private void initBack() { backIv=findViewById(R.id.search_back_iv); backIv.setOnClickListener(this); } private void initEdit() { searchEt=findViewById(R.id.search_et); searchEt.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { String msg=searchEt.getText().toString().trim(); List<AccountBean> list= DBManger.findByRemark(msg); accountBeanList.clear(); for (AccountBean accountBean: list) { accountBeanList.add(accountBean); } rlv_adapter.notifyDataSetChanged(); } @Override public void afterTextChanged(Editable editable) { } }); } private void initRlv() { rlv=findViewById(R.id.search_rlv); rlv_adapter=new account_rlv_adapter(this,accountBeanList); rlv.setAdapter(rlv_adapter); LinearLayoutManager linearLayoutManager=new LinearLayoutManager(this); rlv.setLayoutManager(linearLayoutManager); } @Override public void onClick(View view) { switch (view.getId()){ case R.id.search_back_iv: finish(); break; default: } } }
28.59375
93
0.654281
6191554f82c64ca4ce22a27119808a6d6e89d88e
4,725
package HW8; /** * * @author Matt Gruber <mgruber1> * @section A * */ // You may not import any additional classes or packages. import java.util.*; public class HangmanState { //Do not change any of these global fields. public static final int NORMAL_MODE = 0; public static final int HURTFUL_MODE = 1; public static final int HELPFUL_MODE = 2; public String theAnswer; public Set<String> lettersGuessed; public String feedbackToUser; public Set<String> possibleAnswers; /** * Complete the HangmanState constructor as indicated in the spec. */ public HangmanState(Set<String> knownWords) { // Sets theAnswer randomly Iterator<String> wordSet = knownWords.iterator(); int randomIteration = (int) (Math.random()*knownWords.size()); for(int i=0;i<randomIteration;i++) theAnswer = wordSet.next(); lettersGuessed = new HashSet<String>(); String tempFeedback = ""; for(int i=0;i<theAnswer.length();i++) tempFeedback += "-"; feedbackToUser = tempFeedback; possibleAnswers = knownWords; updatePossibleAnswers(); } /** * Complete the feedbackFor method as indicated in the spec. */ public String feedbackFor(String answer) { String answerGuessed = ""; StringIterator answerIter = new StringIterator(answer); while(answerIter.hasNext()) { String currentChar = answerIter.next(); Iterator<String> letterSet = lettersGuessed.iterator(); boolean letterFound = false; while(letterSet.hasNext()) { if(letterSet.next().equals(currentChar)) { letterFound = true; answerGuessed += currentChar; } } if(!letterFound) answerGuessed+="-"; } return answerGuessed; } /** * Complete the wrongGuesses method as indicated in the spec. */ public Set<String> wrongGuesses() { Set<String> wrongGuesses = new HashSet<String>(); Iterator<String> letterSet = null; if(lettersGuessed!=null) { letterSet = lettersGuessed.iterator(); } else return wrongGuesses; while(letterSet.hasNext()) { String currentChar = letterSet.next(); if(!feedbackToUser.contains(currentChar)) wrongGuesses.add(currentChar); } return wrongGuesses; } /** * Complete the letterGuessedByUser method as indicated in the spec. */ public void letterGuessedByUser(String letter, int mode) { lettersGuessed.add(letter); if(mode==0) feedbackToUser = feedbackFor(theAnswer); else if(mode==1) feedbackToUser = feedbackFor(mostCommonFeedback(generateFeedbackMap())); else { Map<String, Integer> tempMap = generateFeedbackMap(); if(tempMap.size()>1) tempMap.remove(feedbackToUser); feedbackToUser = mostCommonFeedback(tempMap); } updatePossibleAnswers(); return; } /** * Complete the updatePossibleAnswers() as indicated in the spec. */ public void updatePossibleAnswers() { Iterator<String> possibleWordSet = possibleAnswers.iterator(); Set<String> temp = new HashSet<String>(); while(possibleWordSet.hasNext()) { String possibleWord = possibleWordSet.next(); String compare = feedbackFor(possibleWord); if(compare.equals(feedbackToUser)) temp.add(possibleWord); } possibleAnswers = temp; } /** * Complete the generateFeedbackMap method as indicated in the spec. */ public Map<String, Integer> generateFeedbackMap() { Map<String, Integer> feedbackMap = new HashMap<String, Integer>(); Iterator<String> possibleWordSet = possibleAnswers.iterator(); while(possibleWordSet.hasNext()) { String compare = feedbackFor(possibleWordSet.next()); if(feedbackMap.containsKey(compare)) { int value = feedbackMap.get(compare); feedbackMap.put(compare, value+1); } else feedbackMap.put(compare, 1); } return feedbackMap; } /** * Complete the mostCommonFeedback method as indicated in the spec. */ public String mostCommonFeedback(Map<String, Integer> feedbackMap) { Set<String> allKeys = feedbackMap.keySet(); String highestKey = null; int highestVal = 0; Iterator<String> keyIter = allKeys.iterator(); while(keyIter.hasNext()) { String currentKey = keyIter.next(); if(feedbackMap.get(currentKey)>highestVal) { highestKey = currentKey; highestVal = feedbackMap.get(currentKey); } } return highestKey; // remove this line when you're done } /* Do not modify the methods below. */ public String getFeedbackToUser() { return feedbackToUser; } public String toString() { return feedbackToUser + "\t\t" + wrongGuesses() + "\t\t" + possibleAnswers.size(); } }
25.819672
76
0.672381
c582a91e07ea5bcf204dc368e466145fa5a01169
1,726
/* __ __ ____ ___ _ _ _ _ | \/ |_ _/ ___| / _ \| | | | | | ___| |_ __ ___ _ __ | |\/| | | | \___ \| | | | | | |_| |/ _ \ | '_ \ / _ \ '__| | | | | |_| |___) | |_| | |___ | _ | __/ | |_) | __/ | |_| |_|\__, |____/ \__\_\_____| |_| |_|\___|_| .__/ \___|_| |___/ |_| https://github.com/yingzhuo/mysql-helper */ package com.github.yingzhuo.mysqlhelper.config; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.InitializingBean; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import org.springframework.validation.annotation.Validated; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.NotEmpty; import java.io.Serializable; /** * @author 应卓 */ @Slf4j @Validated @Component @ConfigurationProperties(prefix = "mysql-helper.datasource") @Getter @Setter public class DataSourceConf implements InitializingBean, Serializable { @NotEmpty private String host; @Min(1) @Max(65535) private int port = 3306; @NotEmpty private String defaultDatabaseName = "mysql"; @NotEmpty private String username = "root"; @NotEmpty private String password = "root"; @Override public void afterPropertiesSet() { if (log.isInfoEnabled()) { log.info("DATASOURCE: host: {}", host); log.info("DATASOURCE: port: {}", port); log.info("DATASOURCE: username: {}", username); log.info("DATASOURCE: password: {}", password); } } }
26.553846
75
0.618772
1bf6cc6533ee7463c2217f0cdc7e5b838cfa1cde
2,664
/* * Copyright (c) 2019 envimate GmbH - https://envimate.com/. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.envimate.httpmate.marshalling; import com.envimate.httpmate.chains.Configurator; import com.envimate.httpmate.http.headers.ContentType; import lombok.AccessLevel; import lombok.EqualsAndHashCode; import lombok.RequiredArgsConstructor; import lombok.ToString; import static com.envimate.httpmate.chains.Configurator.toUseModules; import static com.envimate.httpmate.marshalling.MarshallingModule.emptyMarshallingModule; import static com.envimate.httpmate.util.Validators.validateNotNull; @ToString @EqualsAndHashCode @RequiredArgsConstructor(access = AccessLevel.PRIVATE) public final class MarshallingModuleBuilder { private final MarshallingModule marshallingModule = emptyMarshallingModule(); static MarshallingModuleBuilder toMarshallBodiesBy() { return new MarshallingModuleBuilder(); } public With<Unmarshaller> unmarshallingContentTypeInRequests(final ContentType contentType) { validateNotNull(contentType, "contentType"); return unmarshaller -> { validateNotNull(unmarshaller, "unmarshaller"); marshallingModule.addUnmarshaller(contentType, unmarshaller); return this; }; } public With<Marshaller> marshallingContentTypeInResponses(final ContentType contentType) { validateNotNull(contentType, "contentType"); return marshaller -> { validateNotNull(marshaller, "marshaller"); marshallingModule.addMarshaller(contentType, marshaller); return this; }; } public Configurator usingTheDefaultContentType(final ContentType contentType) { validateNotNull(contentType, "contentType"); marshallingModule.setDefaultContentType(contentType); return toUseModules(marshallingModule); } }
38.608696
97
0.754129
48f996a9537115b2801b5418425901bef4abfa2b
1,462
package com.itemshare.ui; import static com.itemshare.constant.ItemShareConstants.SELECT_A_PLAYER; import java.util.ArrayList; import java.util.List; import java.util.Objects; import javax.swing.ComboBoxModel; import javax.swing.event.ListDataListener; import org.apache.commons.lang3.StringUtils; public class ItemSharePlayerDropdownModel implements ComboBoxModel<String> { private final List<String> names; private String selected; ItemSharePlayerDropdownModel() { selected = SELECT_A_PLAYER; names = new ArrayList<>(); names.add(SELECT_A_PLAYER); } public void setNames(List<String> names) { this.names.clear(); this.names.add(SELECT_A_PLAYER); this.names.addAll(names); } @Override public int getSize() { return names.size(); } @Override public String getElementAt(int index) { return names.get(index); } @Override public void addListDataListener(ListDataListener l) { } @Override public void removeListDataListener(ListDataListener l) { } @Override public void setSelectedItem(Object item) { if (item instanceof String) { this.selected = (String) item; } else { this.selected = SELECT_A_PLAYER; } } @Override public String getSelectedItem() { if (Objects.equals(selected, SELECT_A_PLAYER)) { return SELECT_A_PLAYER; } else { return names.stream() .filter(option -> StringUtils.equals(option, selected)) .findFirst() .orElse(SELECT_A_PLAYER); } } }
17.404762
74
0.730506
13fc4547ddf472cf6aa3d66d2da5baca7db355bb
356
package com.imooc.security.core.config; import com.imooc.security.core.properties.SecurityProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Configuration; @Configuration @EnableConfigurationProperties(SecurityProperties.class) public class SecurityCoreConfig { }
29.666667
81
0.867978
506aadcca849390bda5c66f63f4df996ffb1ffef
2,068
package com.lab4.bank; import org.apache.log4j.Logger; import java.util.ArrayList; import java.util.List; public class Bank { public static final Logger log=Logger.getLogger(Observer.class); private ArrayList<Cashier> cachiers; private ArrayList<Client> clients; private ArrayList<Bill> bills; private long summary; private Observer observer; private Thread daemon; private ArrayList<Thread> clientthreads; public Bank(int cashiers,int clients, int bills, long summary){ this.summary=summary; int perbill= (int) (summary/bills); this.bills=new ArrayList<Bill>(); for(int i=1;i<bills;i++){ this.bills.add(new Bill(perbill,i)); this.summary-=perbill; } this.bills.add(new Bill(this.summary,this.bills.size()+1)); this.summary=summary; this.clients=new ArrayList<Client>(); for(int i=1;i<=clients;i++){ this.clients.add(new Client(i,this,new Purse(0,i))); } observer=new Observer(this.bills,this.clients,summary); daemon=new Thread(observer); daemon.setDaemon(true); daemon.start(); this.cachiers=new ArrayList<Cashier>(); for(int i=0;i<cashiers;i++){ this.cachiers.add(new Cashier(this.bills,this.observer,i)); } clientthreads=new ArrayList<Thread>(); for(int i=1;i<=clients;i++){ clientthreads.add(new Thread(this.clients.get(i-1))); clientthreads.get(i-1).start(); } log.info("Bank created"); } public int BillCount(){ return bills.size(); } public Bill GetBill(int index){ if(index<bills.size()) return bills.get(index); else return null; } public synchronized Cashier GetCashier(){ for(Cashier c:cachiers){ if(!c.isBusy()){ c.BeginTalk(); return c; } } return null; } }
29.971014
72
0.5706
ddc9d9303fc3fd030c5d6f8ecfe038a19f298f4c
10,373
/* * #%L * de-metas-camel-grssignum * %% * Copyright (C) 2021 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ package de.metas.camel.externalsystems.grssignum.to_grs.bpartner; import com.fasterxml.jackson.core.JsonProcessingException; import com.google.common.annotations.VisibleForTesting; import de.metas.camel.externalsystems.common.CamelRouteUtil; import de.metas.camel.externalsystems.common.ExternalSystemCamelConstants; import de.metas.camel.externalsystems.common.JsonObjectMapperHolder; import de.metas.camel.externalsystems.common.ProcessLogger; import de.metas.camel.externalsystems.common.ProcessorHelper; import de.metas.camel.externalsystems.common.v2.BPRetrieveCamelRequest; import de.metas.camel.externalsystems.grssignum.GRSSignumConstants; import de.metas.camel.externalsystems.grssignum.to_grs.bpartner.processor.CreateExportDirectoriesProcessor; import de.metas.camel.externalsystems.grssignum.to_grs.bpartner.processor.ExportBPartnerRequestBuilder; import de.metas.camel.externalsystems.grssignum.to_grs.bpartner.processor.ExportCustomerProcessor; import de.metas.camel.externalsystems.grssignum.to_grs.bpartner.processor.ExportVendorProcessor; import de.metas.camel.externalsystems.grssignum.to_grs.client.GRSSignumDispatcherRouteBuilder; import de.metas.common.bpartner.v2.response.JsonResponseComposite; import de.metas.common.externalreference.v2.JsonExternalReferenceLookupResponse; import de.metas.common.externalsystem.ExternalSystemConstants; import de.metas.common.externalsystem.JsonExportDirectorySettings; import de.metas.common.externalsystem.JsonExternalSystemRequest; import de.metas.common.product.v2.response.JsonResponseProductBPartner; import de.metas.common.rest_api.common.JsonMetasfreshId; import de.metas.common.util.Check; import lombok.NonNull; import org.apache.camel.Exchange; import org.apache.camel.LoggingLevel; import org.apache.camel.builder.RouteBuilder; import org.springframework.stereotype.Component; import javax.annotation.Nullable; import static de.metas.camel.externalsystems.common.ExternalSystemCamelConstants.ERROR_WRITE_TO_ADISSUE; import static de.metas.camel.externalsystems.common.ExternalSystemCamelConstants.HEADER_PINSTANCE_ID; import static de.metas.camel.externalsystems.common.ExternalSystemCamelConstants.MF_ERROR_ROUTE_ID; import static de.metas.camel.externalsystems.common.ExternalSystemCamelConstants.MF_GET_BPARTNER_PRODUCTS_ROUTE_ID; import static de.metas.camel.externalsystems.common.ExternalSystemCamelConstants.MF_LOOKUP_EXTERNALREFERENCE_V2_CAMEL_URI; import static org.apache.camel.builder.endpoint.StaticEndpointBuilders.direct; @Component public class GRSSignumExportBPartnerRouteBuilder extends RouteBuilder { @VisibleForTesting public static final String EXPORT_BPARTNER_ROUTE_ID = "GRSSignum-exportBPartner"; public static final String PROCESS_VENDOR_ROUTE_ID = "GRSSignum-processVendor"; public static final String PROCESS_CUSTOMER_ROUTE_ID = "GRSSignum-processCustomer"; public static final String CREATE_EXPORT_DIRECTORIES_ROUTE_ID = "GRSSignum-createExportDir"; public static final String CREATE_EXPORT_DIRECTORIES_PROCESSOR_ID = "GRSSignum-createExportDirProcessorId"; final ProcessLogger processLogger; public GRSSignumExportBPartnerRouteBuilder(final ProcessLogger processLogger) { this.processLogger = processLogger; } @Override public void configure() { //@formatter:off errorHandler(defaultErrorHandler()); onException(Exception.class) .to(direct(MF_ERROR_ROUTE_ID)); from(direct(EXPORT_BPARTNER_ROUTE_ID)) .routeId(EXPORT_BPARTNER_ROUTE_ID) .streamCaching() .process(this::buildAndAttachContext) .process(this::buildBPRetrieveCamelRequest) .to("{{" + ExternalSystemCamelConstants.MF_RETRIEVE_BPARTNER_V2_CAMEL_URI + "}}") .unmarshal(CamelRouteUtil.setupJacksonDataFormatFor(getContext(), JsonResponseComposite.class)) .process(this::processRetrieveBPartnerResponse) .to(direct(CREATE_EXPORT_DIRECTORIES_ROUTE_ID)) .process(this::setResponseComposite) .multicast() .to(direct(PROCESS_VENDOR_ROUTE_ID), direct(PROCESS_CUSTOMER_ROUTE_ID)) .end(); from(direct(CREATE_EXPORT_DIRECTORIES_ROUTE_ID)) .routeId(CREATE_EXPORT_DIRECTORIES_ROUTE_ID) .doTry() .process(new CreateExportDirectoriesProcessor(processLogger)).id(CREATE_EXPORT_DIRECTORIES_PROCESSOR_ID) .doCatch(Exception.class) .to(direct(ERROR_WRITE_TO_ADISSUE)) .endDoTry(); from(direct(PROCESS_VENDOR_ROUTE_ID)) .routeId(PROCESS_VENDOR_ROUTE_ID) .choice() .when(simple("${body.bpartner.vendor} == true")) .process(new ExportVendorProcessor()) .to(direct(GRSSignumDispatcherRouteBuilder.GRS_DISPATCHER_ROUTE_ID)) .end(); from(direct(PROCESS_CUSTOMER_ROUTE_ID)) .routeId(PROCESS_CUSTOMER_ROUTE_ID) .choice() .when(simple("${body.bpartner.customer} == true")) .process(ExportBPartnerRequestBuilder::prepareRetrieveBPartnerProductRequest) .to(direct(MF_GET_BPARTNER_PRODUCTS_ROUTE_ID)) .unmarshal(CamelRouteUtil.setupJacksonDataFormatFor(getContext(), JsonResponseProductBPartner.class)) .process(ExportBPartnerRequestBuilder::prepareExternalReferenceLookupRequest) .choice() .when(body().isNull()) .log(LoggingLevel.INFO, "Nothing to do! No bpartner products found!") .otherwise() .to(direct(MF_LOOKUP_EXTERNALREFERENCE_V2_CAMEL_URI)) .unmarshal(CamelRouteUtil.setupJacksonDataFormatFor(getContext(), JsonExternalReferenceLookupResponse.class)) .process(ExportCustomerProcessor::collectProductExternalReferences) .end() .process(new ExportCustomerProcessor()) .to(direct(GRSSignumDispatcherRouteBuilder.GRS_DISPATCHER_ROUTE_ID)) .end(); //@formatter:on } private void buildAndAttachContext(@NonNull final Exchange exchange) { final JsonExternalSystemRequest request = exchange.getIn().getBody(JsonExternalSystemRequest.class); final String remoteUrl = request.getParameters().get(ExternalSystemConstants.PARAM_EXTERNAL_SYSTEM_HTTP_URL); if (Check.isBlank(remoteUrl)) { throw new RuntimeException("Missing mandatory param: " + ExternalSystemConstants.PARAM_EXTERNAL_SYSTEM_HTTP_URL); } final String tenantId = request.getParameters().get(ExternalSystemConstants.PARAM_TENANT_ID); if (Check.isBlank(tenantId)) { throw new RuntimeException("Missing mandatory param: " + ExternalSystemConstants.PARAM_TENANT_ID); } final String authToken = request.getParameters().get(ExternalSystemConstants.PARAM_EXTERNAL_SYSTEM_AUTH_TOKEN); final Integer pInstanceId = exchange.getIn().getHeader(HEADER_PINSTANCE_ID, Integer.class); final JsonExportDirectorySettings jsonExportDirectorySettings = getJsonExportDirSettings(request); final ExportBPartnerRouteContext context = ExportBPartnerRouteContext.builder() .remoteUrl(remoteUrl) .authToken(authToken) .tenantId(tenantId) .orgCode(request.getOrgCode()) .externalSystemConfigId(request.getExternalSystemConfigId()) .jsonExportDirectorySettings(jsonExportDirectorySettings) .pinstanceId(pInstanceId) .build(); exchange.setProperty(GRSSignumConstants.ROUTE_PROPERTY_EXPORT_BPARTNER_CONTEXT, context); } private void buildBPRetrieveCamelRequest(@NonNull final Exchange exchange) { final JsonExternalSystemRequest request = exchange.getIn().getBody(JsonExternalSystemRequest.class); final String bPartnerIdentifier = request.getParameters().get(ExternalSystemConstants.PARAM_BPARTNER_ID); if (Check.isBlank(bPartnerIdentifier)) { throw new RuntimeException("Missing mandatory param: " + ExternalSystemConstants.PARAM_BPARTNER_ID); } final JsonMetasfreshId externalSystemConfigId = request.getExternalSystemConfigId(); final JsonMetasfreshId adPInstanceId = request.getAdPInstanceId(); final BPRetrieveCamelRequest retrieveCamelRequest = BPRetrieveCamelRequest.builder() .bPartnerIdentifier(bPartnerIdentifier) .externalSystemConfigId(externalSystemConfigId) .adPInstanceId(adPInstanceId) .build(); exchange.getIn().setBody(retrieveCamelRequest); } private void processRetrieveBPartnerResponse(@NonNull final Exchange exchange) { final JsonResponseComposite jsonResponseComposite = exchange.getIn().getBody(JsonResponseComposite.class); final ExportBPartnerRouteContext routeContext = ProcessorHelper.getPropertyOrThrowError(exchange, GRSSignumConstants.ROUTE_PROPERTY_EXPORT_BPARTNER_CONTEXT, ExportBPartnerRouteContext.class); routeContext.setJsonResponseComposite(jsonResponseComposite); } private void setResponseComposite(@NonNull final Exchange exchange) { final ExportBPartnerRouteContext routeContext = ProcessorHelper.getPropertyOrThrowError(exchange, GRSSignumConstants.ROUTE_PROPERTY_EXPORT_BPARTNER_CONTEXT, ExportBPartnerRouteContext.class); exchange.getIn().setBody(routeContext.getJsonResponseComposite()); } @Nullable private static JsonExportDirectorySettings getJsonExportDirSettings(@NonNull final JsonExternalSystemRequest externalSystemRequest) { final String exportDirSettings = externalSystemRequest.getParameters().get(ExternalSystemConstants.PARAM_JSON_EXPORT_DIRECTORY_SETTINGS); if (Check.isBlank(exportDirSettings)) { return null; } try { return JsonObjectMapperHolder.sharedJsonObjectMapper() .readValue(exportDirSettings, JsonExportDirectorySettings.class); } catch (final JsonProcessingException e) { throw new RuntimeException("Could not read value of type JsonExportDirectorySettings!" + "ExternalSystemConfigId=" + externalSystemRequest.getExternalSystemConfigId() + ";" + " PInstance=" + externalSystemRequest.getAdPInstanceId()); } } }
42.687243
193
0.810855