hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
5
1.02k
max_stars_repo_name
stringlengths
4
126
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
list
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
5
1.02k
max_issues_repo_name
stringlengths
4
114
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
list
max_issues_count
float64
1
92.2k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
5
1.02k
max_forks_repo_name
stringlengths
4
136
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
list
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2.55
99.9
max_line_length
int64
3
1k
alphanum_fraction
float64
0.25
1
index
int64
0
1M
content
stringlengths
3
1.05M
923e3565b1f1bb8cef756d46dfd3fa2e346e143c
8,634
java
Java
aacs/android/app-components/alexa-auto-comms-ui/src/main/java/com/amazon/alexa/auto/comms/ui/db/ConnectedBTDeviceRepository.java
alexa/aac-sdk
9324a7776da8b2d2210b76a88330c3f695d9b9f6
[ "Apache-2.0" ]
139
2018-08-09T15:14:05.000Z
2019-06-21T20:47:58.000Z
aacs/android/app-components/alexa-auto-comms-ui/src/main/java/com/amazon/alexa/auto/comms/ui/db/ConnectedBTDeviceRepository.java
chris19930209/alexa-auto-sdk
9324a7776da8b2d2210b76a88330c3f695d9b9f6
[ "Apache-2.0" ]
2
2018-09-04T23:43:24.000Z
2019-01-30T20:38:13.000Z
aacs/android/app-components/alexa-auto-comms-ui/src/main/java/com/amazon/alexa/auto/comms/ui/db/ConnectedBTDeviceRepository.java
chris19930209/alexa-auto-sdk
9324a7776da8b2d2210b76a88330c3f695d9b9f6
[ "Apache-2.0" ]
60
2018-08-09T22:28:37.000Z
2019-06-25T07:06:17.000Z
43.386935
119
0.639217
1,000,670
package com.amazon.alexa.auto.comms.ui.db; import android.content.Context; import android.os.AsyncTask; import android.os.Handler; import android.os.Looper; import android.util.Log; import androidx.lifecycle.LiveData; import androidx.room.Room; import org.greenrobot.eventbus.EventBus; import java.util.List; public class ConnectedBTDeviceRepository { private String CONNECTED_DB_NAME = "db_connected_bt_device"; private String DB_NAME = "db_bt_device"; private ConnectedBTDeviceDatabase connectedBTDeviceDatabase; private BTDeviceDatabase btDeviceDatabase; private Handler mHandler; private static ConnectedBTDeviceRepository sInstance; private String TAG = ConnectedBTDeviceRepository.class.getSimpleName(); public static ConnectedBTDeviceRepository getInstance(Context context) { if (sInstance == null) { sInstance = new ConnectedBTDeviceRepository(context); } return sInstance; } private ConnectedBTDeviceRepository(Context context) { connectedBTDeviceDatabase = Room.databaseBuilder(context, ConnectedBTDeviceDatabase.class, CONNECTED_DB_NAME).build(); btDeviceDatabase = Room.databaseBuilder(context, BTDeviceDatabase.class, DB_NAME).build(); mHandler = new Handler(Looper.getMainLooper()); } public LiveData<List<ConnectedBTDevice>> getDescConnectedDevices() { return connectedBTDeviceDatabase.connectedBTDeviceDao().getDescConnectedDevices(); } public LiveData<List<ConnectedBTDevice>> getConnectedDevices() { return connectedBTDeviceDatabase.connectedBTDeviceDao().getConnectedDevices(); } public List<ConnectedBTDevice> getConnectedDevicesSync() { return connectedBTDeviceDatabase.connectedBTDeviceDao().getConnectedDevicesSync(); } public ConnectedBTDevice getConnectedDeviceByAddressSync(String deviceAddress) { return connectedBTDeviceDatabase.connectedBTDeviceDao().getConnectedDeviceByAddress(deviceAddress); } public void setConnectedDeviceToPrimary(String deviceAddress) { new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... voids) { Log.i(TAG, "setConnectedDeviceToPrimary: " + deviceAddress); ConnectedBTDevice previousRecord = connectedBTDeviceDatabase.connectedBTDeviceDao().getConnectedDeviceByAddress(deviceAddress); if (previousRecord != null) { connectedBTDeviceDatabase.connectedBTDeviceDao().deleteConnectedBTDevice(previousRecord); ConnectedBTDevice connectedBTDevice = new ConnectedBTDevice(); connectedBTDevice.setDeviceAddress(previousRecord.getDeviceAddress()); connectedBTDevice.setDeviceName(previousRecord.getDeviceName()); connectedBTDevice.setContactsUploadPermission(previousRecord.getContactsUploadPermission()); Log.i(TAG, "Inserting bt connected device entry: " + connectedBTDevice.getDeviceAddress()); connectedBTDeviceDatabase.connectedBTDeviceDao().insertConnectedBTDevice(connectedBTDevice); EventBus.getDefault().post(new PrimaryPhoneChangeMessage(connectedBTDevice, false)); } return null; } }.execute(); } public void insertEntry(final BTDevice device) { new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... voids) { boolean isNewDevice = true; if (connectedBTDeviceDatabase.connectedBTDeviceDao().getConnectedDeviceByAddress( device.getDeviceAddress()) != null) { ConnectedBTDevice previousRecord = connectedBTDeviceDatabase.connectedBTDeviceDao().getConnectedDeviceByAddress( device.getDeviceAddress()); connectedBTDeviceDatabase.connectedBTDeviceDao().deleteConnectedBTDevice(previousRecord); Log.i(TAG, "Deleting previous bt record: " + device.getDeviceAddress()); isNewDevice = false; } BTDevice btDevice = btDeviceDatabase.btDeviceDao().getBTDeviceByAddressSync(device.getDeviceAddress()); ConnectedBTDevice connectedBTDevice = new ConnectedBTDevice(); connectedBTDevice.setDeviceAddress(btDevice.getDeviceAddress()); connectedBTDevice.setDeviceName(btDevice.getDeviceName()); connectedBTDevice.setContactsUploadPermission(btDevice.getContactsUploadPermission()); Log.i(TAG, "Inserting bt connected device entry: " + connectedBTDevice.getDeviceAddress()); connectedBTDeviceDatabase.connectedBTDeviceDao().insertConnectedBTDevice(connectedBTDevice); EventBus.getDefault().post(new PrimaryPhoneChangeMessage(connectedBTDevice, isNewDevice)); return null; } }.execute(); } public void deleteEntry(final ConnectedBTDevice entry) { new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... voids) { connectedBTDeviceDatabase.connectedBTDeviceDao().deleteConnectedBTDevice(entry); List<ConnectedBTDevice> listData = getConnectedDevicesSync(); if (listData != null && listData.size() > 0) { int index = listData.size() - 1; EventBus.getDefault().post(new PrimaryPhoneChangeMessage(listData.get(index), false)); } else { EventBus.getDefault().post(new PrimaryPhoneChangeMessage(null, false)); } return null; } }.execute(); } public void updateContactsPermission(final String deviceAddress, final String permission) { new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... voids) { ConnectedBTDevice device = connectedBTDeviceDatabase.connectedBTDeviceDao().getConnectedDeviceByAddress(deviceAddress); device.setContactsUploadPermission(permission); connectedBTDeviceDatabase.connectedBTDeviceDao().updateConnectedBTDevice(device); return null; } }.execute(); } public void findConnectedBTDeviceEntry(BTDevice entry) { new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... voids) { ConnectedBTDevice targetDevice = connectedBTDeviceDatabase.connectedBTDeviceDao().getConnectedDeviceByAddress( entry.getDeviceAddress()); mHandler.post(new Runnable() { @Override public void run() { if (targetDevice != null) { EventBus.getDefault().post(new ConnectedBTDeviceDiscoveryMessage(targetDevice, true)); } else { EventBus.getDefault().post(new ConnectedBTDeviceDiscoveryMessage(null, false)); } } }); return null; } }.execute(); } /** * Connected Bluetooth Device Discovery Message */ public static class ConnectedBTDeviceDiscoveryMessage { private ConnectedBTDevice device; private boolean isFound; public ConnectedBTDeviceDiscoveryMessage(ConnectedBTDevice device, boolean isFound) { this.device = device; this.isFound = isFound; } public ConnectedBTDevice getBConnectedBTDevice() { return this.device; } public Boolean isFound() { return this.isFound; } } /** * Primary Phone Change Discovery Message */ public static class PrimaryPhoneChangeMessage { private ConnectedBTDevice device; private boolean isNewDevice; public PrimaryPhoneChangeMessage(ConnectedBTDevice device, boolean newDevice) { this.isNewDevice = newDevice; this.device = device; } public ConnectedBTDevice getConnectedBTDevice() { return this.device; } public boolean getIsNewDevice() {return this.isNewDevice;} } }
923e35b7711d1d4bde98a5abc17edb471f489155
16,305
java
Java
integrations/cdi/datasource-hikaricp/src/main/java/io/helidon/integrations/datasource/hikaricp/cdi/HikariCPBackedDataSourceExtension.java
fastso/helidon
7db5f4e980772afcadced7f9b7e01163e809bf94
[ "Apache-2.0" ]
null
null
null
integrations/cdi/datasource-hikaricp/src/main/java/io/helidon/integrations/datasource/hikaricp/cdi/HikariCPBackedDataSourceExtension.java
fastso/helidon
7db5f4e980772afcadced7f9b7e01163e809bf94
[ "Apache-2.0" ]
null
null
null
integrations/cdi/datasource-hikaricp/src/main/java/io/helidon/integrations/datasource/hikaricp/cdi/HikariCPBackedDataSourceExtension.java
fastso/helidon
7db5f4e980772afcadced7f9b7e01163e809bf94
[ "Apache-2.0" ]
null
null
null
44.793956
114
0.598037
1,000,671
/* * Copyright (c) 2018, 2019 Oracle and/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. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.helidon.integrations.datasource.hikaricp.cdi; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.sql.Connection; import java.util.AbstractMap.SimpleImmutableEntry; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Optional; import java.util.Properties; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.annotation.sql.DataSourceDefinition; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.event.Observes; import javax.enterprise.inject.literal.NamedLiteral; import javax.enterprise.inject.spi.AfterBeanDiscovery; import javax.enterprise.inject.spi.Annotated; import javax.enterprise.inject.spi.BeforeBeanDiscovery; import javax.enterprise.inject.spi.Extension; import javax.enterprise.inject.spi.InjectionPoint; import javax.enterprise.inject.spi.ProcessAnnotatedType; import javax.enterprise.inject.spi.ProcessInjectionPoint; import javax.enterprise.inject.spi.WithAnnotations; import javax.inject.Named; import javax.sql.DataSource; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import org.eclipse.microprofile.config.Config; import org.eclipse.microprofile.config.ConfigProvider; import org.eclipse.microprofile.config.spi.ConfigSource; /** * An {@link Extension} that arranges for named {@link DataSource} * injection points to be satisfied. */ public class HikariCPBackedDataSourceExtension implements Extension { private static final Pattern DATASOURCE_NAME_PATTERN = Pattern.compile("^(?:javax\\.sql\\.|com\\.zaxxer\\.hikari\\.Hikari)DataSource\\.([^.]+)\\.(.*)$"); private final Map<String, Properties> masterProperties; private final Config config; /** * Creates a new {@link HikariCPBackedDataSourceExtension}. */ public HikariCPBackedDataSourceExtension() { super(); this.masterProperties = new HashMap<>(); this.config = ConfigProvider.getConfig(); } private void beforeBeanDiscovery(@Observes final BeforeBeanDiscovery event) { final Set<? extends String> allPropertyNames = this.getPropertyNames(); if (allPropertyNames != null && !allPropertyNames.isEmpty()) { for (final String propertyName : allPropertyNames) { final Optional<String> propertyValue = this.config.getOptionalValue(propertyName, String.class); if (propertyValue != null && propertyValue.isPresent()) { final Matcher matcher = DATASOURCE_NAME_PATTERN.matcher(propertyName); assert matcher != null; if (matcher.matches()) { final String dataSourceName = matcher.group(1); Properties properties = this.masterProperties.get(dataSourceName); if (properties == null) { properties = new Properties(); this.masterProperties.put(dataSourceName, properties); } final String dataSourcePropertyName = matcher.group(2); properties.setProperty(dataSourcePropertyName, propertyValue.get()); } } } } } private void processAnnotatedType(@Observes @WithAnnotations(DataSourceDefinition.class) final ProcessAnnotatedType<?> event) { if (event != null) { final Annotated annotated = event.getAnnotatedType(); if (annotated != null) { final Set<? extends DataSourceDefinition> dataSourceDefinitions = annotated.getAnnotations(DataSourceDefinition.class); if (dataSourceDefinitions != null && !dataSourceDefinitions.isEmpty()) { for (final DataSourceDefinition dsd : dataSourceDefinitions) { assert dsd != null; final Entry<? extends String, ? extends Properties> entry = toProperties(dsd); if (entry != null) { final String dataSourceName = entry.getKey(); if (dataSourceName != null && !this.masterProperties.containsKey(dataSourceName)) { this.masterProperties.put(dataSourceName, entry.getValue()); } } } } } } } private <T extends DataSource> void processInjectionPoint(@Observes final ProcessInjectionPoint<?, T> event) { if (event != null) { final InjectionPoint injectionPoint = event.getInjectionPoint(); if (injectionPoint != null) { final Type type = injectionPoint.getType(); if (type instanceof Class && DataSource.class.isAssignableFrom((Class<?>) type)) { final Set<? extends Annotation> qualifiers = injectionPoint.getQualifiers(); for (final Annotation qualifier : qualifiers) { if (qualifier instanceof Named) { final String dataSourceName = ((Named) qualifier).value(); if (dataSourceName != null && !dataSourceName.isEmpty()) { // The injection point might reference // a data source name that wasn't // present in a MicroProfile // ConfigSource initially. Some // ConfigSources that Helidon provides // can automatically synthesize // configuration property values upon // first lookup. So we give those // ConfigSources a chance to bootstrap // here by issuing a request for a // commonly present data source // property value. this.config.getOptionalValue("javax.sql.DataSource." + dataSourceName + ".dataSourceClassName", String.class); } } } } } } } private void afterBeanDiscovery(@Observes final AfterBeanDiscovery event) { if (event != null) { final Set<? extends Entry<? extends String, ? extends Properties>> masterPropertiesEntries = this.masterProperties.entrySet(); if (masterPropertiesEntries != null && !masterPropertiesEntries.isEmpty()) { for (final Entry<? extends String, ? extends Properties> entry : masterPropertiesEntries) { if (entry != null) { event.<HikariDataSource>addBean() .addQualifier(NamedLiteral.of(entry.getKey())) // ...and Default and Any? .addTransitiveTypeClosure(HikariDataSource.class) .beanClass(HikariDataSource.class) .scope(ApplicationScoped.class) .createWith(ignored -> new HikariDataSource(new HikariConfig(entry.getValue()))) .destroyWith((dataSource, ignored) -> dataSource.close()); } } } } this.masterProperties.clear(); } private Set<String> getPropertyNames() { // The MicroProfile Config specification does not say whether // property names must be cached or must not be cached // (https://github.com/eclipse/microprofile-config/issues/370). // It is implied in the MicroProfile Google group // (https://groups.google.com/d/msg/microprofile/tvjgSR9qL2Q/M2TNUQrOAQAJ), // but not in the specification, that ConfigSources can be // mutable and dynamic. Consequently one would expect their // property names to come and go. Because of this we have to // make sure to get all property names from all ConfigSources // "by hand". // // (The MicroProfile Config specification also does not say // whether a ConfigSource is thread-safe // (https://github.com/eclipse/microprofile-config/issues/369), // so iteration over its coming-and-going dynamic property // names may be problematic, but there's nothing we can do.) // // As of this writing, the Helidon MicroProfile Config // implementation caches all property names up front, which // may not be correct, but is also not forbidden. final Set<String> returnValue; final Set<String> propertyNames = getPropertyNames(this.config.getConfigSources()); if (propertyNames == null || propertyNames.isEmpty()) { returnValue = Collections.emptySet(); } else { returnValue = Collections.unmodifiableSet(propertyNames); } return returnValue; } private static Set<String> getPropertyNames(final Iterable<? extends ConfigSource> configSources) { final Set<String> returnValue = new HashSet<>(); if (configSources != null) { for (final ConfigSource configSource : configSources) { if (configSource != null) { final Set<String> configSourcePropertyNames = configSource.getPropertyNames(); if (configSourcePropertyNames != null && !configSourcePropertyNames.isEmpty()) { returnValue.addAll(configSourcePropertyNames); } } } } return Collections.unmodifiableSet(returnValue); } private static Entry<String, Properties> toProperties(final DataSourceDefinition dsd) { Objects.requireNonNull(dsd); final String dataSourceName = dsd.name(); final Properties properties = new Properties(); final Entry<String, Properties> returnValue = new SimpleImmutableEntry<>(dataSourceName, properties); final String[] propertyStrings = dsd.properties(); assert propertyStrings != null; for (final String propertyString : propertyStrings) { assert propertyString != null; final int equalsIndex = propertyString.indexOf('='); if (equalsIndex > 0 && equalsIndex < propertyString.length()) { final String name = propertyString.substring(0, equalsIndex); assert name != null; final String value = propertyString.substring(equalsIndex + 1); assert value != null; properties.setProperty("dataSource." + name, value); } } // See https://github.com/brettwooldridge/HikariCP#configuration-knobs-baby. properties.setProperty("dataSourceClassName", dsd.className()); // initialPoolSize -> (ignored) // maxStatements -> (ignored) // transactional -> (ignored, I guess, until I figure out what to do about XA) // minPoolSize -> minimumIdle final int minPoolSize = dsd.minPoolSize(); if (minPoolSize >= 0) { properties.setProperty("dataSource.minimumIdle", String.valueOf(minPoolSize)); } // maxPoolSize -> maximumPoolSize final int maxPoolSize = dsd.maxPoolSize(); if (maxPoolSize >= 0) { properties.setProperty("dataSource.maximumPoolSize", String.valueOf(maxPoolSize)); } // loginTimeout -> connectionTimeout final int loginTimeout = dsd.loginTimeout(); if (loginTimeout > 0) { properties.setProperty("dataSource.connectionTimeout", String.valueOf(loginTimeout)); } // maxIdleTime -> idleTimeout final int maxIdleTime = dsd.maxIdleTime(); if (maxIdleTime >= 0) { properties.setProperty("dataSource.idleTimeout", String.valueOf(maxIdleTime)); } // password -> password // // Note: *not* dataSource.password final String password = dsd.password(); assert password != null; if (!password.isEmpty()) { properties.setProperty("dataSource.password", password); } // isolationLevel -> transactionIsolation final int isolationLevel = dsd.isolationLevel(); if (isolationLevel >= 0) { final String propertyValue; switch (isolationLevel) { case Connection.TRANSACTION_NONE: propertyValue = "TRANSACTION_NONE"; break; case Connection.TRANSACTION_READ_UNCOMMITTED: propertyValue = "TRANSACTION_READ_UNCOMMITTED"; break; case Connection.TRANSACTION_READ_COMMITTED: propertyValue = "TRANSACTION_READ_COMMITTED"; break; case Connection.TRANSACTION_REPEATABLE_READ: propertyValue = "TRANSACTION_REPEATABLE_READ"; break; case Connection.TRANSACTION_SERIALIZABLE: propertyValue = "TRANSACTION_SERIALIZABLE"; break; default: propertyValue = null; throw new IllegalStateException("Unexpected isolation level: " + isolationLevel); } properties.setProperty("dataSource.transactionIsolation", propertyValue); } // user -> dataSource.username // // This one's a bit odd. Note that this does NOT map to // dataSource.user! final String user = dsd.user(); assert user != null; if (!user.isEmpty()) { properties.setProperty("dataSource.username", user); } // databaseName -> dataSource.databaseName (standard DataSource property) final String databaseName = dsd.databaseName(); assert databaseName != null; if (!databaseName.isEmpty()) { properties.setProperty("datasource.databaseName", databaseName); } // description -> dataSource.description (standard DataSource property) final String description = dsd.description(); assert description != null; if (!description.isEmpty()) { properties.setProperty("datasource.description", description); } // portNumber -> dataSource.portNumber (standard DataSource property) final int portNumber = dsd.portNumber(); if (portNumber >= 0) { properties.setProperty("datasource.portNumber", String.valueOf(portNumber)); } // serverName -> dataSource.serverName (standard DataSource property) final String serverName = dsd.serverName(); assert serverName != null; if (!serverName.isEmpty()) { properties.setProperty("datasource.serverName", serverName); } // url -> dataSource.url (standard DataSource property) final String url = dsd.url(); assert url != null; if (!url.isEmpty()) { properties.setProperty("datasource.url", url); } return returnValue; } }
923e36f19f44e6a15f3bb66b7baf7b07a80c0b75
318
java
Java
app/src/test/java/com/forme/yeo/pocketmoney/ExampleUnitTest.java
exia56/PocketMoney
b6d2323a2fc533808bd5defc6f5e0a4592c68346
[ "MIT" ]
null
null
null
app/src/test/java/com/forme/yeo/pocketmoney/ExampleUnitTest.java
exia56/PocketMoney
b6d2323a2fc533808bd5defc6f5e0a4592c68346
[ "MIT" ]
null
null
null
app/src/test/java/com/forme/yeo/pocketmoney/ExampleUnitTest.java
exia56/PocketMoney
b6d2323a2fc533808bd5defc6f5e0a4592c68346
[ "MIT" ]
null
null
null
21.2
78
0.694969
1,000,672
package com.forme.yeo.pocketmoney; import org.junit.Test; import static org.junit.Assert.*; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
923e37128c85370bf0283adbfc9e9411cdd28266
7,743
java
Java
main/plugins/org.talend.designer.core/src/main/java/org/talend/designer/core/utils/JavaSampleCodeFactory.java
coheigea/tdi-studio-se
c4cd4df0fc841c497b51718e623145d29d0bf030
[ "Apache-2.0" ]
114
2015-03-05T15:34:59.000Z
2022-02-22T03:48:44.000Z
main/plugins/org.talend.designer.core/src/main/java/org/talend/designer/core/utils/JavaSampleCodeFactory.java
coheigea/tdi-studio-se
c4cd4df0fc841c497b51718e623145d29d0bf030
[ "Apache-2.0" ]
1,137
2015-03-04T01:35:42.000Z
2022-03-29T06:03:17.000Z
main/plugins/org.talend.designer.core/src/main/java/org/talend/designer/core/utils/JavaSampleCodeFactory.java
coheigea/tdi-studio-se
c4cd4df0fc841c497b51718e623145d29d0bf030
[ "Apache-2.0" ]
219
2015-01-21T10:42:18.000Z
2022-02-17T07:57:20.000Z
41.18617
178
0.550174
1,000,673
// ============================================================================ // // Copyright (C) 2006-2021 Talend Inc. - www.talend.com // // This source code is available under agreement available at // %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt // // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France // // ============================================================================ package org.talend.designer.core.utils; import java.util.List; import org.eclipse.gef.commands.Command; import org.eclipse.jface.dialogs.MessageDialog; import org.talend.core.model.components.ComponentCategory; import org.talend.core.model.metadata.IMetadataColumn; import org.talend.core.model.metadata.IMetadataTable; import org.talend.designer.core.i18n.Messages; import org.talend.designer.core.ui.editor.cmd.PropertyChangeCommand; import org.talend.designer.core.ui.editor.nodes.Node; /** * DOC YeXiaowei class global comment. Detailled comment */ public final class JavaSampleCodeFactory implements ISampleCodeFactory { private JavaSampleCodeFactory() { } private static JavaSampleCodeFactory instance = null; public static JavaSampleCodeFactory getInstance() { if (instance == null) { instance = new JavaSampleCodeFactory(); } return instance; } /* * (non-Javadoc) * * @see * org.talend.designer.core.utils.ISampleCodeFactory#generateCode(org.talend.designer.core.ui.editor.nodes.Node) */ @Override public Command generateCodeForParameters(final Node node) { String uniqueName = node.getUniqueName(); // see feature 4131 if (uniqueName.startsWith("tJavaRow_")) { //$NON-NLS-1$ // Generate code for tJavaRow component String codeString = generateJavaRowCode(node); if (codeString != null) { return new PropertyChangeCommand(node, "CODE", codeString); //$NON-NLS-1$ } } return null; } /** * * DOC YeXiaowei Comment method "generateJavaRowCode". Generates Java code for the tJavaRow component in DI and BD. * * @param node * @return */ private String generateJavaRowCode(final Node node) { boolean isSparkNode = false; String sparkMapType = "MAP"; //$NON-NLS-1$ ComponentCategory componentCategory = ComponentCategory.getComponentCategoryFromName(node.getComponent().getType()); String primeVlue = "// code sample:\r\n" + "//\r\n" + "// multiply by 2 the row identifier\r\n" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + "// output_row.id = input_row.id * 2;\r\n" + "//\r\n" + "// lowercase the name\r\n" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + "// output_row.name = input_row.name.toLowerCase();"; //$NON-NLS-1$ if (ComponentCategory.CATEGORY_4_SPARK == componentCategory || ComponentCategory.CATEGORY_4_SPARKSTREAMING == componentCategory) { isSparkNode = true; sparkMapType = node.getPropertyValue("MAPTYPE").toString(); //$NON-NLS-1$ primeVlue = "// Please add an input to the component to generate a sample code\r\n"; //$NON-NLS-1$ } if (node.getMetadataList() == null || node.getMetadataList().get(0) == null) { return primeVlue; } if (node.getIncomingConnections() == null || node.getIncomingConnections().isEmpty() || node.getIncomingConnections().get(0).getMetadataTable() == null) { return primeVlue; } IMetadataTable inputTable = node.getIncomingConnections().get(0).getMetadataTable(); List<IMetadataColumn> inputColumns = inputTable.getListColumns(); IMetadataTable outputTable = node.getMetadataList().get(0); List<IMetadataColumn> outputColumns = outputTable.getListColumns(); if (inputColumns == null || inputColumns.isEmpty() || outputColumns == null || outputColumns.isEmpty()) { return primeVlue; } String javaEnding = ";"; //$NON-NLS-1$ String lineSeparator = System.getProperty("line.separator"); //$NON-NLS-1$ StringBuilder builder = new StringBuilder(); boolean isSelect = MessageDialog.openQuestion(null, null, Messages.getString("JavaSampleCodeFactory.askRegenerateCode")); //$NON-NLS-1$ if (isSelect) { // Add simple comment builder.append(Messages.getString("JavaSampleCodeFactory.schema")).append(lineSeparator); //$NON-NLS-1$ int inputRowsLength = inputColumns.size(); int ouputRowsLength = outputColumns.size(); if (inputRowsLength == 0 || ouputRowsLength == 0) { return null; } if (isSparkNode && (sparkMapType.equalsIgnoreCase("FLATMAP"))) { //$NON-NLS-1$ builder.append("Output output = new Output();\r\n"); //$NON-NLS-1$ } if (inputRowsLength >= ouputRowsLength) { for (int i = 0; i < inputRowsLength; i++) { String inputLabel = inputColumns.get(i).getLabel(); String outputLabel = null; if (i > ouputRowsLength - 1) { outputLabel = outputColumns.get(ouputRowsLength - 1).getLabel(); } else { outputLabel = outputColumns.get(i).getLabel(); } if (isSparkNode) { builder.append("output.").append(outputLabel).append(" = ").append("input.").append(inputLabel).append( //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ javaEnding); } else { builder.append("output_row.").append(outputLabel).append(" = ").append("input_row.").append(inputLabel).append( //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ javaEnding); } builder.append(lineSeparator); } } else { for (int i = 0; i < ouputRowsLength; i++) { String outputLabel = outputColumns.get(i).getLabel(); String inputLabel = null; if (i > inputRowsLength - 1) { inputLabel = inputColumns.get(inputRowsLength - 1).getLabel(); } else { inputLabel = inputColumns.get(i).getLabel(); } if (isSparkNode) { builder.append("output.").append(outputLabel).append(" = ").append("input.").append(inputLabel).append( //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ javaEnding); } else { builder.append("output_row.").append(outputLabel).append(" = ").append("input_row.").append(inputLabel).append( //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ javaEnding); } builder.append(lineSeparator); } } if (isSparkNode && (sparkMapType.equalsIgnoreCase("FLATMAP"))) { //$NON-NLS-1$ builder.append("outputList.add(output);\r\n"); //$NON-NLS-1$ } return builder.toString(); } else { return null; } } }
923e371ead5889918b837032aa6e224f9f15088d
18,602
java
Java
bundle/edu.gemini.pot/src/main/java/edu/gemini/pot/sp/ISPFactory.java
jocelynferrara/ocs
446c8a8e03d86bd341ac024fae6811ecb643e185
[ "BSD-3-Clause" ]
13
2015-02-04T21:33:56.000Z
2020-04-10T01:37:41.000Z
bundle/edu.gemini.pot/src/main/java/edu/gemini/pot/sp/ISPFactory.java
jocelynferrara/ocs
446c8a8e03d86bd341ac024fae6811ecb643e185
[ "BSD-3-Clause" ]
1,169
2015-01-02T13:20:50.000Z
2022-03-21T12:01:59.000Z
bundle/edu.gemini.pot/src/main/java/edu/gemini/pot/sp/ISPFactory.java
jocelynferrara/ocs
446c8a8e03d86bd341ac024fae6811ecb643e185
[ "BSD-3-Clause" ]
13
2015-04-07T18:01:55.000Z
2021-02-03T12:57:58.000Z
40.79386
155
0.657779
1,000,674
package edu.gemini.pot.sp; import edu.gemini.spModel.core.SPProgramID; import edu.gemini.spModel.data.ISPDataObject; import edu.gemini.spModel.gemini.obscomp.SPProgram; import edu.gemini.spModel.gemini.plan.NightlyRecord; import edu.gemini.spModel.obs.SPObservation; import edu.gemini.spModel.obscomp.SPGroup; import edu.gemini.shared.util.immutable.Option; import java.util.List; /** * This is the interface used for the creation of science programs * nodes. The factory creates concrete products of a single kind. */ public interface ISPFactory { /** * Returns a string hint for the type of concrete products * produced by the factory. */ String getType(); /** * Creates an ISPProgram using the default initializer for programs. * * @param key key to use for this node (if <code>null</code> a * new key will be assigned) * @param progID the program ID to use */ ISPProgram createProgram(SPNodeKey key, SPProgramID progID); /** * Creates an ISPProgram using the provided initializer (overriding * the default initializer for programs). * * @param init the <code>ISPNodeInitializer</code> to use when initializing * the newly created node; will be used instead of any default initializer * @param key key to use for this node (if <code>null</code> a * new key will be assigned) * @param progID the program ID to use */ ISPProgram createProgram(ISPNodeInitializer<ISPProgram, SPProgram> init, SPNodeKey key, SPProgramID progID); /** * Creates an ISPProgram that is a deep copy of the given <code>program</code>. * All nodes have identical keys and the program shares the same LifespanId. * This copy is intended for transactional updates. That is, a duplicate * is made and updated and if successful swapped in for the existing * version of the program. */ ISPProgram copyWithSameKeys(ISPProgram program); /** * Creates a duplicate program with the same node keys as for * {@link #copyWithSameKeys}, but assigns a new LifecycleId. This version * of copy is intended to be used when a program is transported to a new * database. */ ISPProgram copyWithNewLifespanId(ISPProgram program); /** * Creates a copy of the program that is identical in structure and data to * the given <code>program</code> but with all new node keys and a new * program id. */ ISPProgram copyWithNewKeys(ISPProgram program, SPProgramID newProgID); ISPConflictFolder createConflictFolder(ISPProgram prog, SPNodeKey key) throws SPUnknownIDException; ISPConflictFolder createConflictFolderCopy(ISPProgram prog, ISPConflictFolder folder, boolean preserveKeys) throws SPUnknownIDException; /** * Creates an ISPTemplateFolder using the default initializer for template * folders. * * @param prog the program with which this folder should be associated * * @param key key to use for this node (if <code>null</code> a * new key will be assigned) * * @throws SPUnknownIDException if the given <code>progKey</code> refers * to a program that is not known by this factory */ ISPTemplateFolder createTemplateFolder(ISPProgram prog, SPNodeKey key) throws SPUnknownIDException; /** * Creates an ISPTemplateFolder that is a deep copy of the given * <code>folder</code>. * * @param prog the program with which this folder should be associated * * @param folder the folder to copy * * @param preserveKeys whether the copied folder will have unique keys * or will copy the keys of the source <code>folder</code> * * @throws SPUnknownIDException if the given <code>progKey</code> refers * to a program that is not known by this factory */ ISPTemplateFolder createTemplateFolderCopy(ISPProgram prog, ISPTemplateFolder folder, boolean preserveKeys) throws SPUnknownIDException; /** * Creates an ISPTemplateGroup using the default initializer for template * groups. * * @param prog the program with which this template group should be associated * * @param key key to use for this node (if <code>null</code> a new key will * be assigned) * * @throws SPUnknownIDException if the given <code>progKey</code> refers * to a program that is not known by this factory */ ISPTemplateGroup createTemplateGroup(ISPProgram prog, SPNodeKey key) throws SPUnknownIDException; /** * Creates an ISPTemplateGroup that is a deep copy of the given * <code>group</code>. * * @param prog the program with which this group should be associated * * @param group the group to copy * * @param preserveKeys whether the copied group will have unique keys * or will copy the keys of the source <code>group</code> * * @throws SPUnknownIDException if the given <code>progKey</code> refers * to a program that is not known by this factory */ ISPTemplateGroup createTemplateGroupCopy(ISPProgram prog, ISPTemplateGroup group, boolean preserveKeys) throws SPUnknownIDException; /** * Creates an ISPTemplateParameters using the default initializer for * template parameters. * * @param prog the program with which this template parameters should be * associated * * @param key key to use for this node (if <code>null</code> a new key will * be assigned) * * @throws SPUnknownIDException if the given <code>progKey</code> refers * to a program that is not known by this factory */ ISPTemplateParameters createTemplateParameters(ISPProgram prog, SPNodeKey key) throws SPUnknownIDException; /** * Creates an ISPTemplateParameters that is a deep copy of the given * <code>parameters</code>. * * @param prog the program with which this parameters should be associated * * @param parameters the parameters to copy * * @param preserveKeys whether the copied parameters will have unique keys * or will copy the keys of the source <code>parameters</code> * * @throws SPUnknownIDException if the given <code>progKey</code> refers * to a program that is not known by this factory */ ISPTemplateParameters createTemplateParametersCopy(ISPProgram prog, ISPTemplateParameters parameters, boolean preserveKeys) throws SPUnknownIDException; /** * Creates an ISPNightlyRecord using the default initializer for nightly * plans. * * @param planID the plan ID to use * @param key key to use for this node (if <code>null</code> a * new key will be assigned) */ ISPNightlyRecord createNightlyRecord(SPNodeKey key, SPProgramID planID); /** * Creates an ISPNightlyRecord using the provided initializer (overriding * the default initializer for nightly plans). * * @param init the <code>ISPNodeInitializer</code> to use when initializing * the newly created node; will be used instead of any registered * default initializer * @param key key to use for this node (if <code>null</code> a * new key will be assigned) */ ISPNightlyRecord createNightlyRecord(ISPNodeInitializer<ISPNightlyRecord, NightlyRecord> init, SPNodeKey key, SPProgramID planID); /** * Creates an ISPNightlyRecord that is a deep copy of the given <code>nightly plan</code>. */ ISPNightlyRecord renameNightlyRecord(ISPNightlyRecord plan, SPNodeKey key, SPProgramID planID); /** * Creates an ISPObservation using the default initializer for observations * associated with the given instrument (if provided).. * * @param prog the program with which this observation should be associated * * @param inst the instrument to add to this observation, if any. This will * be used for instrument-specific observation initialization. * * @param key key to use for this node (if <code>null</code> a * new key will be assigned) * * @throws SPUnknownIDException if the given <code>progKey</code> refers * to a program that is not known by this factory */ ISPObservation createObservation(ISPProgram prog, Option<Instrument> inst, SPNodeKey key) throws SPException; /** * Creates an ISPObservation using the default initializer for observations * associated with the given instrument (if provided).. * * @param prog the program with which this observation should be associated * @param index the index of the observation inside of the program * (or -1 to automatically generate a new index) * @param inst the instrument to add to this observation, if any. This will * be used for instrument-specific observation initialization * @param key key to use for this node (if <code>null</code> a * new key will be assigned) * * @throws SPUnknownIDException if the given <code>progKey</code> refers * to a program that is not known by this factory */ ISPObservation createObservation(ISPProgram prog, int index, Option<Instrument> inst, SPNodeKey key) throws SPException; /** * Creates an ISPObservation using the provided initializer (overriding * the default initializer for observations). * * @param prog the program with which this observation should be associated * * @param index the index of the observation inside of the program * (or -1 to automatically generate a new index) * * @param init the <code>ISPNodeInitializer</code> to use when initializing * the newly created node; will be used instead of any registered * default initializer * * @param key key to use for this node (if <code>null</code> a * new key will be assigned) * * @throws SPUnknownIDException if the given <code>progKey</code> refers * to a program that is not known by this factory */ ISPObservation createObservation(ISPProgram prog, int index, ISPNodeInitializer<ISPObservation, SPObservation> init, SPNodeKey key) throws SPException; /** * Creates an ISPObservation that is a deep copy of the given * <code>observation</code>. * * @param prog the program with which this observation should be associated * * @param observation the observation to copy * * @param preserveKeys whether the copied observation will have unique keys * or will copy the keys of the source <code>observation</code> * * @throws SPUnknownIDException if the given <code>progKey</code> refers * to a program that is not known by this factory */ ISPObservation createObservationCopy(ISPProgram prog, ISPObservation observation, boolean preserveKeys) throws SPException; ISPObsQaLog createObsQaLog(ISPProgram prog, SPNodeKey key) throws SPUnknownIDException; ISPObsQaLog createObsQaLogCopy(ISPProgram prog, ISPObsQaLog log, boolean preserveKeys) throws SPUnknownIDException; ISPObsExecLog createObsExecLog(ISPProgram prog, SPNodeKey key) throws SPUnknownIDException; ISPObsExecLog createObsExecLogCopy(ISPProgram prog, ISPObsExecLog log, boolean preserveKeys) throws SPUnknownIDException; /** * Creates an ISPObsComponent using the default initializer for the given * component <code>type</code>. * * @param prog the program with which this component should be associated * * @param type the type that distinguishes this observation component * from others (for example, "target environment" or "niri") * * @param key key to use for this node (if <code>null</code> a * new key will be assigned) * * @throws SPUnknownIDException if the given <code>progKey</code> refers * to a program that is not known by this factory */ ISPObsComponent createObsComponent(ISPProgram prog, SPComponentType type, SPNodeKey key) throws SPUnknownIDException; /** * Creates an ISPObsComponent using the given initializer. * * @param prog the program with which this component should be associated * * @param type the type that distinguishes this observation component from * others (for example, "target environment" or "niri") * * @param init the <code>ISPNodeInitializer</code> to use when initializing * the newly created component; will be used instead of any registered * default initializer * * @param key key to use for this node (if <code>null</code> a * new key will be assigned) * * @throws SPUnknownIDException if the given <code>progKey</code> refers * to a program that is not known by this factory */ ISPObsComponent createObsComponent(ISPProgram prog, SPComponentType type, ISPNodeInitializer<ISPObsComponent, ? extends ISPDataObject> init, SPNodeKey key) throws SPUnknownIDException; /** * Creates an ISPObsComponent that is a deep copy of the given * <code>component</code>. * * @param prog the program with which this component should be associated * * @param component the component to copy * * @param preserveKeys whether the copied component will have unique keys * or will copy the keys of the source <code>component</code> * * @throws SPUnknownIDException if the given <code>progKey</code> refers * to a program that is not known by this factory */ ISPObsComponent createObsComponentCopy(ISPProgram prog, ISPObsComponent component, boolean preserveKeys) throws SPUnknownIDException; /** * Creates an ISPSeqComponent using the default initializer for the given * component <code>type</code>. * * @param prog the program with which this component should be associated * * @param type the type that distinguies this sequence component * from others (for example, "offset" or "niri") * * @param key key to use for this node (if <code>null</code> a * new key will be assigned) * * @throws SPUnknownIDException if the given <code>progKey</code> refers * to a program that is not known by this factory */ ISPSeqComponent createSeqComponent(ISPProgram prog, SPComponentType type, SPNodeKey key) throws SPUnknownIDException; /** * Creates an ISPSeqComponent using the given initializer. * * @param prog the program with which this component should be associated * * @param type the type that distinguies this sequence component from * others (for example, "offset" or "niri") * * @param init the <code>ISPNodeInitializer</code> to use when initializing * the newly created component; will be used instead of any registered * default initializer * * @param key key to use for this node (if <code>null</code> a * new key will be assigned) * * @throws SPUnknownIDException if the given <code>progKey</code> refers * to a program that is not known by this factory */ ISPSeqComponent createSeqComponent(ISPProgram prog, SPComponentType type, ISPNodeInitializer<ISPSeqComponent, ? extends ISPSeqObject> init, SPNodeKey key) throws SPUnknownIDException; /** * Creates an ISPSeqComponent that is a deep copy of the given * <code>component</code>. * * @param prog the key of the program with which this component should * be associated * * @param component the component to copy * * @param preserveKeys whether the copied component will have unique keys * or will copy the keys of the source <code>component</code> * * @throws SPUnknownIDException if the given <code>progKey</code> refers * to a program that is not known by this factory */ ISPSeqComponent createSeqComponentCopy(ISPProgram prog, ISPSeqComponent component, boolean preserveKeys) throws SPUnknownIDException; /** * Creates an ISPGroup using the provided node key. * * @param prog the program with which this group should be associated * * @param key key to use for this node (if <code>null</code> a * new key will be assigned) * * @throws SPUnknownIDException if the given <code>progKey</code> refers * to a program that is not known by this factory */ ISPGroup createGroup(ISPProgram prog, SPNodeKey key) throws SPUnknownIDException; /** * Creates an ISPGroup using the provided initializer (overriding * the default initializer for groups). * * @param prog the program with which this group should be associated * * @param init the <code>ISPNodeInitializer</code> to use when initializing * the newly created node; will be used instead of any registered * default initializer * * @param key key to use for this node (if <code>null</code> a * new key will be assigned) * * @throws SPUnknownIDException if the given <code>progKey</code> refers * to a program that is not known by this factory */ ISPGroup createGroup(ISPProgram prog, ISPNodeInitializer<ISPGroup, SPGroup> init, SPNodeKey key) throws SPUnknownIDException; /** * Creates a deep copy of the given <code>group</code> */ ISPGroup createGroupCopy(ISPProgram prog, ISPGroup ispGroup, boolean preserveKeys) throws SPUnknownIDException; }
923e3749ece3641f51ee5e5d858412f3cb6789af
3,145
java
Java
app/src/main/java/com/abplus/qiitaly/app/NavigationDrawerFragment.java
kazhida/Qiitaly
37d982f5d80fbf5f62674bcf8e9a26b31431214a
[ "Apache-2.0" ]
1
2015-05-07T00:50:58.000Z
2015-05-07T00:50:58.000Z
app/src/main/java/com/abplus/qiitaly/app/NavigationDrawerFragment.java
kazhida/Qiitaly
37d982f5d80fbf5f62674bcf8e9a26b31431214a
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/abplus/qiitaly/app/NavigationDrawerFragment.java
kazhida/Qiitaly
37d982f5d80fbf5f62674bcf8e9a26b31431214a
[ "Apache-2.0" ]
null
null
null
29.669811
112
0.623847
1,000,675
package com.abplus.qiitaly.app; import android.app.Activity; import android.app.ActionBar; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import butterknife.ButterKnife; import butterknife.InjectView; import org.jetbrains.annotations.NotNull; public class NavigationDrawerFragment extends Fragment { @InjectView(R.id.list_view) ListView screenList; @InjectView(R.id.logout_button) View logoutButton; public static interface Callback { void onItemSelected(int position); void onLogout(); } private Callback callback; @Override public View onCreateView(@NotNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_navigation_drawer, container, false); ButterKnife.inject(this, view); return view; } @Override public void onActivityCreated (Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); ScreenAdapter adapter = new ScreenAdapter(); screenList.setAdapter(adapter); screenList.setOnItemClickListener(adapter); screenList.setItemChecked(0, true); logoutButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(@NotNull View v) { if (callback != null) { callback.onLogout(); } } }); } public void selectItem(int position) { if (screenList != null) { screenList.setItemChecked(position, true); } if (callback != null) { callback.onItemSelected(position); } } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { callback = (Callback) activity; } catch (ClassCastException e) { throw new ClassCastException("Activity must implement NavigationDrawerCallbacks."); } } @Override public void onDetach() { super.onDetach(); callback = null; } private ActionBar getActionBar() { return getActivity().getActionBar(); } private class ScreenAdapter extends ArrayAdapter<String> implements AdapterView.OnItemClickListener { ScreenAdapter() { super( getActionBar().getThemedContext(), android.R.layout.simple_list_item_activated_1, android.R.id.text1, new String[]{ getString(R.string.title_home), getString(R.string.title_users), getString(R.string.title_tags), } ); } @Override public void onItemClick(@NotNull AdapterView<?> parent, @NotNull View view, int position, long id) { selectItem(position); } } }
923e37ba4a109178018ed93193adeaa728128da5
2,334
java
Java
java/server/test/org/openqa/grid/e2e/misc/Issue1586.java
chromium-googlesource-mirror/selenium
fcf26da81afa5d3e8edfc776f558eebf2e7d28b3
[ "Apache-2.0" ]
null
null
null
java/server/test/org/openqa/grid/e2e/misc/Issue1586.java
chromium-googlesource-mirror/selenium
fcf26da81afa5d3e8edfc776f558eebf2e7d28b3
[ "Apache-2.0" ]
null
null
null
java/server/test/org/openqa/grid/e2e/misc/Issue1586.java
chromium-googlesource-mirror/selenium
fcf26da81afa5d3e8edfc776f558eebf2e7d28b3
[ "Apache-2.0" ]
null
null
null
32.416667
116
0.724936
1,000,676
package org.openqa.grid.e2e.misc; import java.net.MalformedURLException; import java.net.URL; import org.openqa.grid.common.GridRole; import org.openqa.grid.e2e.utils.GridTestHelper; import org.openqa.grid.e2e.utils.RegistryTestHelper; import org.openqa.grid.internal.utils.GridHubConfiguration; import org.openqa.grid.internal.utils.SelfRegisteringRemote; import org.openqa.grid.web.Hub; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.net.PortProber; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; // see http://code.google.com/p/selenium/issues/detail?id=1586 public class Issue1586 { private Hub hub; private URL hubURL; @BeforeClass(alwaysRun = true) public void prepare() throws Exception { GridHubConfiguration config = new GridHubConfiguration(); config.setPort(PortProber.findFreePort()); hub = new Hub(config); hubURL = hub.getUrl(); hub.start(); // register a webdriver SelfRegisteringRemote webdriver = GridTestHelper.getRemoteWithoutCapabilities(hub.getUrl(), GridRole.WEBDRIVER); webdriver.addBrowser(DesiredCapabilities.firefox(), 1); webdriver.startRemoteServer(); webdriver.sendRegistrationRequest(); RegistryTestHelper.waitForNode(hub.getRegistry(), 1); } @Test public void test() throws MalformedURLException, InterruptedException { DesiredCapabilities ff = DesiredCapabilities.firefox(); WebDriver driver = null; try { driver = new RemoteWebDriver(new URL(hubURL + "/grid/driver"), ff); for (int i = 0; i < 20; i++) { driver.get("http://code.google.com/p/selenium/"); WebElement keywordInput = driver.findElement(By.name("q")); keywordInput.clear(); keywordInput.sendKeys("test"); WebElement submitButton = driver.findElement(By.name("projectsearch")); submitButton.click(); driver.getCurrentUrl(); // fails here } } finally { if (driver != null) { driver.quit(); } } } @AfterClass(alwaysRun = true) public void stop() throws Exception { hub.stop(); } }
923e38101de1dde2b0ff0f9e0ef701fd0b49255c
682
java
Java
src/Arrays/Exercicio.java
allan201gf/FundamentosJava
75f743fbbe1467655cc134b79e3bc7e550ad7bff
[ "MIT" ]
null
null
null
src/Arrays/Exercicio.java
allan201gf/FundamentosJava
75f743fbbe1467655cc134b79e3bc7e550ad7bff
[ "MIT" ]
null
null
null
src/Arrays/Exercicio.java
allan201gf/FundamentosJava
75f743fbbe1467655cc134b79e3bc7e550ad7bff
[ "MIT" ]
null
null
null
20.666667
57
0.564516
1,000,677
package Arrays; import java.util.Arrays; public class Exercicio { public static void main(String[] args) { double[] notasAlunoA = new double[3]; notasAlunoA[0] = 7.9; notasAlunoA[1] = 8; notasAlunoA[2] = 6.7; String dadosArray = Arrays.toString(notasAlunoA); System.out.println(dadosArray); // Coletando a media do array double total = 0; for (int i = 0; i < notasAlunoA.length; i++) { total += notasAlunoA[i]; } System.out.println(total / notasAlunoA.length); // Outra forma de iniciar um array double[] notasAlunoB = { 6.9, 8,9, 5.5, 10 }; } }
923e388fe308b2e8de9c626020d02393363d918b
550
java
Java
app/src/main/java/com/ewgvip/buyer/android/models/GradeNameBean.java
ewgcat/ewgbuyer
3be0e195b4e0187ce5458b7604fb33d1398e586e
[ "Apache-2.0" ]
6
2016-11-15T03:15:47.000Z
2018-02-07T08:43:44.000Z
app/src/main/java/com/ewgvip/buyer/android/models/GradeNameBean.java
ewgcat/ewgbuyer
3be0e195b4e0187ce5458b7604fb33d1398e586e
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/ewgvip/buyer/android/models/GradeNameBean.java
ewgcat/ewgbuyer
3be0e195b4e0187ce5458b7604fb33d1398e586e
[ "Apache-2.0" ]
null
null
null
23.913043
56
0.449091
1,000,678
package com.ewgvip.buyer.android.models; /** * Created by Administrator on 2016/7/18. */ public class GradeNameBean { public String icon; public String name; public GradeNameBean(String icon, String name) { this.icon = icon; this.name = name; } @Override public String toString() { return "GradeNameBean{" + "icon='" + icon + '\'' + ", name='" + name + '\'' + '}'; } }
923e3b5054d596c63a22294f319665f0725ac4e2
1,086
java
Java
server/metrics/promql/src/main/java/com/alipay/sofa/lookout/server/prom/util/NoopUtils.java
hutaishi/sofa-lookout
bff2f47a09869988a0a45f4ed420db7adcd5b3b4
[ "Apache-2.0" ]
177
2019-05-14T12:29:29.000Z
2022-03-29T00:21:03.000Z
server/metrics/promql/src/main/java/com/alipay/sofa/lookout/server/prom/util/NoopUtils.java
hutaishi/sofa-lookout
bff2f47a09869988a0a45f4ed420db7adcd5b3b4
[ "Apache-2.0" ]
37
2019-05-21T08:53:54.000Z
2022-03-10T08:24:56.000Z
server/metrics/promql/src/main/java/com/alipay/sofa/lookout/server/prom/util/NoopUtils.java
hutaishi/sofa-lookout
bff2f47a09869988a0a45f4ed420db7adcd5b3b4
[ "Apache-2.0" ]
57
2019-05-14T08:46:41.000Z
2022-03-12T08:03:47.000Z
31.941176
75
0.702578
1,000,679
/* * 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.alipay.sofa.lookout.server.prom.util; /** * @author xiangfeng.xzc * @date 2018/10/17 */ public final class NoopUtils { private NoopUtils() { } public static void noop() { boolean x = false; while (x) { break; } } }
923e3bc89d26ab74d0d5562ca5c953dfa781b14e
3,335
java
Java
src/main/java/com/supervisor/sdk/datasource/conditions/pgsql/PgFilter.java
my-supervisor/my-supervisor
ba6ecc4a3373cd439586a72a8e9fc035b09a3f2b
[ "CC-BY-3.0" ]
3
2022-01-31T20:40:22.000Z
2022-02-11T04:15:44.000Z
src/main/java/com/supervisor/sdk/datasource/conditions/pgsql/PgFilter.java
my-supervisor/my-supervisor
ba6ecc4a3373cd439586a72a8e9fc035b09a3f2b
[ "CC-BY-3.0" ]
33
2022-01-31T20:40:16.000Z
2022-02-21T01:57:51.000Z
src/main/java/com/supervisor/sdk/datasource/conditions/pgsql/PgFilter.java
my-supervisor/my-supervisor
ba6ecc4a3373cd439586a72a8e9fc035b09a3f2b
[ "CC-BY-3.0" ]
null
null
null
26.054688
128
0.716042
1,000,680
package com.supervisor.sdk.datasource.conditions.pgsql; import com.supervisor.sdk.datasource.comparators.Matcher; import com.supervisor.sdk.datasource.comparators.pgsql.PgSmartMatcher; import com.supervisor.sdk.datasource.conditions.Condition; import com.supervisor.sdk.datasource.conditions.Filter; import com.supervisor.sdk.datasource.conditions.GroupedCondition; import com.supervisor.sdk.metadata.FieldMetadata; import com.supervisor.sdk.metadata.MethodReferenceUtils; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public final class PgFilter<A1> implements Filter<A1> { protected final Class<A1> clazz; protected final ConditionOperator operator; protected final List<Condition> conditions; public PgFilter(final Class<A1> clazz) { this(clazz, ConditionOperator.AND); } public PgFilter(final Class<A1> clazz, final ConditionOperator operator, final List<Condition> conditions) { this.clazz = clazz; this.operator = operator; this.conditions = conditions; } public PgFilter(final Class<A1> clazz, final ConditionOperator operator) { this(clazz, operator, new ArrayList<>()); } public PgFilter(final Class<A1> clazz, final ConditionOperator operator, final Condition condition) throws IOException { this(clazz, operator); this.conditions.add(condition); } @Override public Filter<A1> add(final MethodReferenceUtils.MethodRefWithoutArg<A1> methodRef, final Matcher matcher) throws IOException { Condition newCondition = new PgSimpleCondition( clazz, methodRef, new PgSmartMatcher(clazz, methodRef, matcher) ); return add(newCondition); } @Override public Filter<A1> add(final FieldMetadata field, final Matcher matcher) throws IOException { Condition newCondition = new PgSimpleCondition( field, new PgSmartMatcher(field, matcher) ); return add(newCondition); } @Override public Filter<A1> add(final Condition condition) throws IOException { // vérifier que cette condition n'existe pas déjà boolean exists = conditions.stream() .anyMatch(c -> c.equals(condition)); if(!exists) { this.conditions.add(condition); } return this; } @Override public Filter<A1> append(Filter<A1> filter) throws IOException { this.conditions.add(filter.condition()); return this; } private Condition join(Condition right, Condition left){ Condition newCondition = Condition.EMPTY; switch (operator) { case AND: newCondition = new PgAnd(right, left); break; case OR: newCondition = new PgOr(right, left); break; default: break; } return newCondition; } @Override public Condition condition() throws IOException { Condition condition = Condition.EMPTY; if(conditions.size() == 1) condition = conditions.get(0); else if(conditions.size() > 1) { for (Condition left : conditions) { condition = join(condition, left); } condition = new GroupedCondition(condition); } return condition; } @Override public Filter<A1> copy() { List<Condition> conditions = this.conditions.stream() .collect(Collectors.toList()); return new PgFilter<>(clazz, operator, conditions); } }
923e3d3832a7ccd083d95f2bc93a798cbc9511f0
686
java
Java
src/DesignPattern/StructurePattern/AdapterDesign/RiskManagement.java
Kingwentao/DesignPatternOfBeauty
08d672f18ce920482a54a27079745e865e88a64b
[ "Apache-2.0" ]
3
2020-01-11T06:09:54.000Z
2021-04-07T09:11:52.000Z
src/DesignPattern/StructurePattern/AdapterDesign/RiskManagement.java
Kingwentao/DesignPatternOfBeauty
08d672f18ce920482a54a27079745e865e88a64b
[ "Apache-2.0" ]
null
null
null
src/DesignPattern/StructurePattern/AdapterDesign/RiskManagement.java
Kingwentao/DesignPatternOfBeauty
08d672f18ce920482a54a27079745e865e88a64b
[ "Apache-2.0" ]
null
null
null
24.5
70
0.705539
1,000,681
package DesignPattern.StructurePattern.AdapterDesign; import java.util.ArrayList; import java.util.List; /** * author: WentaoKing * created on: 2020/3/4 * description: 扩展性更好,更加符合开闭原则,如果添加一个新的敏感词过滤系统 * 这个类完全不需要改动;而且基于接口而非实现编程,代码的可测试性更好。 */ public class RiskManagement { private List<ISensitiveWordsFilter> filters = new ArrayList<>(); public void addSensitiveWordFilters(ISensitiveWordsFilter filter){ filters.add(filter); } public String filterSensitiveWordsFilter(String text){ String makeText = text; for (ISensitiveWordsFilter filter: filters){ makeText = filter.filter(text); } return makeText; } }
923e3d57b8e87d19bca85cc589d14192c5aa65ec
273
java
Java
springboot-webflux/src/main/java/com/duanndz/webflux/models/User.java
duannd/java-tutorials
f3f52c017bea429542d69f805bbd8ccccaef8894
[ "Unlicense" ]
1
2020-04-21T11:38:50.000Z
2020-04-21T11:38:50.000Z
springboot-webflux/src/main/java/com/duanndz/webflux/models/User.java
duannd/java-tutorials
f3f52c017bea429542d69f805bbd8ccccaef8894
[ "Unlicense" ]
null
null
null
springboot-webflux/src/main/java/com/duanndz/webflux/models/User.java
duannd/java-tutorials
f3f52c017bea429542d69f805bbd8ccccaef8894
[ "Unlicense" ]
null
null
null
13.65
45
0.725275
1,000,682
package com.duanndz.webflux.models; import lombok.*; import javax.validation.constraints.NotBlank; @Getter @Setter @NoArgsConstructor @AllArgsConstructor @ToString(of = {"id", "name"}) public class User { private Long id; @NotBlank private String name; }
923e3dd1afcfa3843eefa29178a6747e20fe9053
898
java
Java
learning-demo/src/test/java/com/tangcheng/learning/concurrent/CalculatorTest.java
helloworldtang/ch6_2_3
f61936dc5b5ece9f2df538d02d6ce35a1e73209b
[ "Apache-2.0" ]
29
2017-08-24T05:40:18.000Z
2022-03-06T03:32:00.000Z
learning-demo/src/test/java/com/tangcheng/learning/concurrent/CalculatorTest.java
helloworldtang/ch6_2_3
f61936dc5b5ece9f2df538d02d6ce35a1e73209b
[ "Apache-2.0" ]
null
null
null
learning-demo/src/test/java/com/tangcheng/learning/concurrent/CalculatorTest.java
helloworldtang/ch6_2_3
f61936dc5b5ece9f2df538d02d6ce35a1e73209b
[ "Apache-2.0" ]
20
2017-10-10T22:29:51.000Z
2022-03-06T03:31:59.000Z
30.066667
85
0.736142
1,000,683
package com.tangcheng.learning.concurrent; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinTask; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; /** * spring-boot-cookbook * * @author : hzdkv@example.com * @version : 2017-06-15 11:40 */ @RunWith(SpringJUnit4ClassRunner.class) public class CalculatorTest { @Test public void compute() throws Exception { long begin = System.currentTimeMillis(); ForkJoinPool forkJoinPool = new ForkJoinPool(); ForkJoinTask<Integer> result = forkJoinPool.submit(new Calculator(0, 10000)); System.out.println("cost:" + (System.currentTimeMillis() - begin)); assertThat(result.get(), is(49995000)); } }
923e3e867c10f0899d6b85f41a24e9778f2fa98c
1,894
java
Java
jExample/src/jexample/parts/Fog.java
YvesBoyadjian/Koin3D
b49547f938886261dc9feae3c2f63f19680a2cfa
[ "BSD-3-Clause" ]
14
2018-06-29T21:55:55.000Z
2021-12-30T12:18:21.000Z
jExample/src/jexample/parts/Fog.java
YvesBoyadjian/Koin3D
b49547f938886261dc9feae3c2f63f19680a2cfa
[ "BSD-3-Clause" ]
null
null
null
jExample/src/jexample/parts/Fog.java
YvesBoyadjian/Koin3D
b49547f938886261dc9feae3c2f63f19680a2cfa
[ "BSD-3-Clause" ]
4
2018-11-15T02:00:18.000Z
2021-12-12T05:42:31.000Z
24.282051
68
0.728089
1,000,684
/** * */ package jexample.parts; import jscenegraph.coin3d.fxviz.nodes.SoShadowDirectionalLight; import jscenegraph.coin3d.fxviz.nodes.SoShadowGroup; import jscenegraph.database.inventor.nodes.SoCube; import jscenegraph.database.inventor.nodes.SoDirectionalLight; import jscenegraph.database.inventor.nodes.SoEnvironment; import jscenegraph.database.inventor.nodes.SoMaterial; import jscenegraph.database.inventor.nodes.SoNode; import jscenegraph.database.inventor.nodes.SoSeparator; import jscenegraph.database.inventor.nodes.SoTranslation; /** * @author Yves Boyadjian * */ public class Fog { public static SoNode getScene() { SoSeparator sep1 = new SoSeparator(); SoShadowGroup sep = new SoShadowGroup(); sep.quality.setValue(1.0f); sep.precision.setValue(0.2f); sep.intensity.setValue(1.0f); sep.threshold.setValue(0.9f); sep.epsilon.setValue(3.0e-6f); sep.smoothBorder.setValue(1.0f); SoEnvironment en = new SoEnvironment(); en.fogType.setValue(SoEnvironment.FogType.FOG); en.fogVisibility.setValue(10.0f); en.fogColor.setValue(0, 1, 0); en.attenuation.setValue(0, 0, 0.0001f); sep1.addChild(en); SoShadowDirectionalLight light = new SoShadowDirectionalLight(); sep.addChild(light); SoSeparator waterSeparator = new SoSeparator(); SoTranslation tr = new SoTranslation(); tr.translation.setValue(0, 0, - 10); waterSeparator.addChild(tr); SoMaterial mat = new SoMaterial(); mat.diffuseColor.setValue(1, 0, 0); mat.transparency.setValue(0.5f); mat.ambientColor.setValue(0, 0, 0); mat.specularColor.setValue(1.0f, 1.0f, 1.0f); mat.shininess.setValue(0.5f); waterSeparator.addChild(mat); SoCube cube = new SoCube(); cube.height.setValue(100); waterSeparator.addChild(cube); sep.addChild(waterSeparator); sep1.addChild(sep); return sep1; } }
923e3edc683bab12bfbe70a26e19766e9d6c7cfa
132
java
Java
backend/src/main/java/com/inpieasy/entities/DefianceStatus.java
mcurvello/inpieasy
a0af488de1a7ef13a23f7d7eef1af811176d0be6
[ "MIT" ]
null
null
null
backend/src/main/java/com/inpieasy/entities/DefianceStatus.java
mcurvello/inpieasy
a0af488de1a7ef13a23f7d7eef1af811176d0be6
[ "MIT" ]
null
null
null
backend/src/main/java/com/inpieasy/entities/DefianceStatus.java
mcurvello/inpieasy
a0af488de1a7ef13a23f7d7eef1af811176d0be6
[ "MIT" ]
null
null
null
18.857143
66
0.818182
1,000,685
package com.inpieasy.entities; public enum DefianceStatus { NOT_SENDED, SENDED_UNDER_ANALYSIS, SUCCESSFULLY_ACHIEVED, DENIED; }
923e3f19c7c2b83d65c22b40303a972ba71b88ce
5,777
java
Java
src/main/java/de/l3s/souza/EventKG/queriesGenerator/nlp/NaturalLanguageQuery.java
tarcisiosouza/EC-QA
e633ee3bde5148641db74801b392e3815ba38b25
[ "MIT" ]
13
2018-12-10T20:51:39.000Z
2022-03-28T21:22:17.000Z
src/main/java/de/l3s/souza/EventKG/queriesGenerator/nlp/NaturalLanguageQuery.java
tarcisiosouza/EC-QA
e633ee3bde5148641db74801b392e3815ba38b25
[ "MIT" ]
null
null
null
src/main/java/de/l3s/souza/EventKG/queriesGenerator/nlp/NaturalLanguageQuery.java
tarcisiosouza/EC-QA
e633ee3bde5148641db74801b392e3815ba38b25
[ "MIT" ]
4
2019-01-08T15:42:02.000Z
2019-12-17T14:02:23.000Z
26.995327
160
0.652934
1,000,686
package de.l3s.souza.EventKG.queriesGenerator.nlp; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.StringTokenizer; public class NaturalLanguageQuery { private String questionType; private String timeFilterExpression; private Map<String,String> givenVariables; private Map<String,Relation> relations; private ArrayList<String> variables; public String getQueryType() { return questionType; } public ArrayList<String> getVariables() { return variables; } public void setVariables(ArrayList<String> variables) { this.variables = variables; } public Map<String, String> getGivenVariables() { return givenVariables; } public void setGivenVariables(Map<String, String> givenVariables) { this.givenVariables = givenVariables; } public String getTimeFilterExpression() { return timeFilterExpression; } public void setTimeFilterExpression(String timeFilterExpression) { this.timeFilterExpression = timeFilterExpression; } public NaturalLanguageQuery() { questionType =""; variables = new ArrayList<String>(); timeFilterExpression = ""; relations = new HashMap<String,Relation> (); givenVariables = new HashMap<String,String>(); } public String getQuestionType() { return questionType; } public void setQuestionType(String questionType) { this.questionType = questionType; } public Map<String, Relation> getRelations() { return relations; } public void setQueryType(String clause) { switch (clause) { case "select": { questionType = "What "; break; } case "ask": { questionType = "Did "; break; } case "count": { questionType = "How many "; break; } } } public void setRelationById (String id, Relation r) { relations.put(id, r); } public void setVariablesRelations () { } @Override public String toString() { String naturalLanguageVars = ""; String naturalLanguageGivenVars = ""; HashMap<String,Entity> vars = new HashMap<String,Entity>(); String naturalLanguagePredicates = ""; int relationNumber = 1; String role ; String type ; for (Entry<String, Relation> entry: relations.entrySet()) { Relation r = entry.getValue(); Entity object = r.getObject(); Entity subject = r.getSubject(); if (object.isVar() && !vars.containsKey(object.getVarName())) { role = r.getRoleType().replaceAll("dbo:", ""); type = subject.getType().replaceAll("dbo:", ""); vars.put(object.getVarName(),object); if (subject.isVar()) naturalLanguagePredicates = naturalLanguagePredicates + object.getVarName() + " was the " + role + " of " + type + " " + subject.getVarName() + "\n"; else { String labelSubj = subject.getLabel(); naturalLanguagePredicates = naturalLanguagePredicates + object.getVarName() + " was the " + role + " of " + labelSubj + "\n"; } relationNumber++; continue; } if (subject.isVar() && !vars.containsKey(subject.getVarName())) { role = r.getRoleType().replaceAll("dbo:", ""); type = subject.getType().replaceAll("dbo:", ""); vars.put(subject.getVarName(),subject); if (object.isVar()) naturalLanguagePredicates = naturalLanguagePredicates + object.getVarName() + " was the " + role + " of " + type + " " + subject.getVarName() + "\n"; else { String labelObj = object.getLabel(); naturalLanguagePredicates = naturalLanguagePredicates + labelObj + " was the " + role + " of " + type + " " + subject.getVarName() + "\n"; } relationNumber++; continue; } } /*if (questionType.contains("What") || questionType.contains("How many")) {*/ for (Entry<String,Entity> entry : vars.entrySet()) { type = entry.getValue().getType().replaceAll("dbo:", ""); if (entry.getValue().isEvent()) { if (entry.getValue().isCountVar()) naturalLanguageVars = naturalLanguageVars + entry.getValue().getVarName() +" is a "+type + "(How many " + type + ")\n"; else naturalLanguageVars = naturalLanguageVars + entry.getValue().getVarName() +" is a "+type + "\n" ; } else { if (entry.getValue().isCountVar()) naturalLanguageVars = naturalLanguageVars + entry.getValue().getVarName() +" is a "+type + "(How many " + type + ")\n"; else naturalLanguageVars = naturalLanguageVars + entry.getValue().getVarName() +" is a "+type + "\n"; } } if (vars.size()<=1) { for (int i=0;i<variables.size();i++) { if (variables.contains("StartTime")) naturalLanguageVars = naturalLanguageVars + " " + variables.get(i) + " is the start date filter of " + variables.get(i).replaceAll("StartTime", "") + "\n"; if (variables.contains("EndTime")) naturalLanguageVars = naturalLanguageVars + " " + variables.get(i) + " is the end date filter of " + variables.get(i).replaceAll("EndTime", "") + "\n"; } } //} for (Entry<String,String> variable:givenVariables.entrySet()) { naturalLanguageGivenVars = naturalLanguageGivenVars + variable.getKey() + " is given: " + variable.getValue() + "\n"; } String previousString = naturalLanguageVars + naturalLanguagePredicates + naturalLanguageGivenVars + timeFilterExpression + "\n"; StringTokenizer token = new StringTokenizer (previousString,"\n"); String finalString = ""; while (token.hasMoreTokens()) { String current = token.nextToken(); if (!current.contains("rdf:type")) finalString = finalString + current + "\n"; } /* if (timeFilterExpression.length() < 14 && timeFilterExpression.contains("filter in")) finalString = "";*/ return finalString + "\n"; } }
923e3f44cf3c82cdc2a00edc039ebf40c3b94531
16,494
java
Java
ea2ddl-dao/src/main/java/jp/sourceforge/ea2ddl/dao/cbean/cq/bs/AbstractBsTConnectorconstraintCQ.java
taktos/ea2ddl
282aa6c851be220441ee50df5c18ff575dfbe9ac
[ "Apache-2.0" ]
null
null
null
ea2ddl-dao/src/main/java/jp/sourceforge/ea2ddl/dao/cbean/cq/bs/AbstractBsTConnectorconstraintCQ.java
taktos/ea2ddl
282aa6c851be220441ee50df5c18ff575dfbe9ac
[ "Apache-2.0" ]
3
2015-07-01T10:33:38.000Z
2016-07-13T06:57:57.000Z
ea2ddl-dao/src/main/java/jp/sourceforge/ea2ddl/dao/cbean/cq/bs/AbstractBsTConnectorconstraintCQ.java
taktos/ea2ddl
282aa6c851be220441ee50df5c18ff575dfbe9ac
[ "Apache-2.0" ]
null
null
null
39.45933
127
0.608827
1,000,687
package jp.sourceforge.ea2ddl.dao.cbean.cq.bs; import java.util.Collection; import org.seasar.dbflute.cbean.*; import org.seasar.dbflute.cbean.ckey.*; import org.seasar.dbflute.cbean.coption.*; import org.seasar.dbflute.cbean.cvalue.ConditionValue; import org.seasar.dbflute.cbean.sqlclause.SqlClause; import org.seasar.dbflute.dbmeta.DBMetaProvider; import jp.sourceforge.ea2ddl.dao.allcommon.*; import jp.sourceforge.ea2ddl.dao.cbean.*; import jp.sourceforge.ea2ddl.dao.cbean.cq.*; /** * The abstract condition-query of t_connectorconstraint. * @author DBFlute(AutoGenerator) */ public abstract class AbstractBsTConnectorconstraintCQ extends AbstractConditionQuery { // =================================================================================== // Attribute // ========= protected final DBMetaProvider _dbmetaProvider = new DBMetaInstanceHandler(); // =================================================================================== // Constructor // =========== public AbstractBsTConnectorconstraintCQ(ConditionQuery childQuery, SqlClause sqlClause, String aliasName, int nestLevel) { super(childQuery, sqlClause, aliasName, nestLevel); } // =================================================================================== // DBMeta Provider // =============== @Override protected DBMetaProvider getDBMetaProvider() { return _dbmetaProvider; } // =================================================================================== // Table Name // ========== public String getTableDbName() { return "t_connectorconstraint"; } public String getTableSqlName() { return "t_connectorconstraint"; } // =================================================================================== // Query // ===== /** * Equal(=). And NullIgnored, OnlyOnceRegistered. {UQ : INTEGER} * @param connectorid The value of connectorid as equal. */ public void setConnectorid_Equal(java.lang.Integer connectorid) { regConnectorid(CK_EQ, connectorid); } /** * NotEqual(!=). And NullIgnored, OnlyOnceRegistered. * @param connectorid The value of connectorid as notEqual. */ public void setConnectorid_NotEqual(java.lang.Integer connectorid) { regConnectorid(CK_NE, connectorid); } /** * GreaterThan(&gt;). And NullIgnored, OnlyOnceRegistered. * @param connectorid The value of connectorid as greaterThan. */ public void setConnectorid_GreaterThan(java.lang.Integer connectorid) { regConnectorid(CK_GT, connectorid); } /** * LessThan(&lt;). And NullIgnored, OnlyOnceRegistered. * @param connectorid The value of connectorid as lessThan. */ public void setConnectorid_LessThan(java.lang.Integer connectorid) { regConnectorid(CK_LT, connectorid); } /** * GreaterEqual(&gt;=). And NullIgnored, OnlyOnceRegistered. * @param connectorid The value of connectorid as greaterEqual. */ public void setConnectorid_GreaterEqual(java.lang.Integer connectorid) { regConnectorid(CK_GE, connectorid); } /** * LessEqual(&lt;=). And NullIgnored, OnlyOnceRegistered. * @param connectorid The value of connectorid as lessEqual. */ public void setConnectorid_LessEqual(java.lang.Integer connectorid) { regConnectorid(CK_LE, connectorid); } /** * InScope(in (1, 2)). And NullIgnored, NullElementIgnored, SeveralRegistered. * @param connectoridList The collection of connectorid as inScope. */ public void setConnectorid_InScope(Collection<java.lang.Integer> connectoridList) { regConnectorid(CK_INS, cTL(connectoridList)); } /** * IsNull(is null). And OnlyOnceRegistered. */ public void setConnectorid_IsNull() { regConnectorid(CK_ISN, DOBJ); } /** * IsNotNull(is not null). And OnlyOnceRegistered. */ public void setConnectorid_IsNotNull() { regConnectorid(CK_ISNN, DOBJ); } protected void regConnectorid(ConditionKey k, Object v) { regQ(k, v, getCValueConnectorid(), "ConnectorID"); } abstract protected ConditionValue getCValueConnectorid(); /** * Equal(=). And NullOrEmptyIgnored, OnlyOnceRegistered. {UQ : VARCHAR(255)} * @param constraint The value of constraint as equal. */ public void setConstraint_Equal(String constraint) { regConstraint(CK_EQ, fRES(constraint)); } /** * NotEqual(!=). And NullOrEmptyIgnored, OnlyOnceRegistered. * @param constraint The value of constraint as notEqual. */ public void setConstraint_NotEqual(String constraint) { regConstraint(CK_NE, fRES(constraint)); } /** * GreaterThan(&gt;). And NullOrEmptyIgnored, OnlyOnceRegistered. * @param constraint The value of constraint as greaterThan. */ public void setConstraint_GreaterThan(String constraint) { regConstraint(CK_GT, fRES(constraint)); } /** * LessThan(&lt;). And NullOrEmptyIgnored, OnlyOnceRegistered. * @param constraint The value of constraint as lessThan. */ public void setConstraint_LessThan(String constraint) { regConstraint(CK_LT, fRES(constraint)); } /** * GreaterEqual(&gt;=). And NullOrEmptyIgnored, OnlyOnceRegistered. * @param constraint The value of constraint as greaterEqual. */ public void setConstraint_GreaterEqual(String constraint) { regConstraint(CK_GE, fRES(constraint)); } /** * LessEqual(&lt;=). And NullOrEmptyIgnored, OnlyOnceRegistered. * @param constraint The value of constraint as lessEqual. */ public void setConstraint_LessEqual(String constraint) { regConstraint(CK_LE, fRES(constraint)); } /** * PrefixSearch(like 'xxx%'). And NullOrEmptyIgnored, OnlyOnceRegistered. * @param constraint The value of constraint as prefixSearch. */ public void setConstraint_PrefixSearch(String constraint) { regConstraint(CK_PS, fRES(constraint)); } /** * InScope(in ('a', 'b')). And NullOrEmptyIgnored, NullOrEmptyElementIgnored, SeveralRegistered. * @param constraintList The collection of constraint as inScope. */ public void setConstraint_InScope(Collection<String> constraintList) { regConstraint(CK_INS, cTL(constraintList)); } /** * LikeSearch(like 'xxx%' escape ...). And NullOrEmptyIgnored, SeveralRegistered. * @param constraint The value of constraint as likeSearch. * @param likeSearchOption The option of like-search. (NotNull) */ public void setConstraint_LikeSearch(String constraint, LikeSearchOption likeSearchOption) { regLSQ(CK_LS, fRES(constraint), getCValueConstraint(), "Constraint", likeSearchOption); } /** * NotLikeSearch(not like 'xxx%' escape ...). And NullOrEmptyIgnored, SeveralRegistered. * @param constraint The value of constraint as notLikeSearch. * @param likeSearchOption The option of not-like-search. (NotNull) */ public void setConstraint_NotLikeSearch(String constraint, LikeSearchOption likeSearchOption) { regLSQ(CK_NLS, fRES(constraint), getCValueConstraint(), "Constraint", likeSearchOption); } /** * IsNull(is null). And OnlyOnceRegistered. */ public void setConstraint_IsNull() { regConstraint(CK_ISN, DOBJ); } /** * IsNotNull(is not null). And OnlyOnceRegistered. */ public void setConstraint_IsNotNull() { regConstraint(CK_ISNN, DOBJ); } protected void regConstraint(ConditionKey k, Object v) { regQ(k, v, getCValueConstraint(), "Constraint"); } abstract protected ConditionValue getCValueConstraint(); /** * Equal(=). And NullOrEmptyIgnored, OnlyOnceRegistered. {VARCHAR(50)} * @param constrainttype The value of constrainttype as equal. */ public void setConstrainttype_Equal(String constrainttype) { regConstrainttype(CK_EQ, fRES(constrainttype)); } /** * NotEqual(!=). And NullOrEmptyIgnored, OnlyOnceRegistered. * @param constrainttype The value of constrainttype as notEqual. */ public void setConstrainttype_NotEqual(String constrainttype) { regConstrainttype(CK_NE, fRES(constrainttype)); } /** * GreaterThan(&gt;). And NullOrEmptyIgnored, OnlyOnceRegistered. * @param constrainttype The value of constrainttype as greaterThan. */ public void setConstrainttype_GreaterThan(String constrainttype) { regConstrainttype(CK_GT, fRES(constrainttype)); } /** * LessThan(&lt;). And NullOrEmptyIgnored, OnlyOnceRegistered. * @param constrainttype The value of constrainttype as lessThan. */ public void setConstrainttype_LessThan(String constrainttype) { regConstrainttype(CK_LT, fRES(constrainttype)); } /** * GreaterEqual(&gt;=). And NullOrEmptyIgnored, OnlyOnceRegistered. * @param constrainttype The value of constrainttype as greaterEqual. */ public void setConstrainttype_GreaterEqual(String constrainttype) { regConstrainttype(CK_GE, fRES(constrainttype)); } /** * LessEqual(&lt;=). And NullOrEmptyIgnored, OnlyOnceRegistered. * @param constrainttype The value of constrainttype as lessEqual. */ public void setConstrainttype_LessEqual(String constrainttype) { regConstrainttype(CK_LE, fRES(constrainttype)); } /** * PrefixSearch(like 'xxx%'). And NullOrEmptyIgnored, OnlyOnceRegistered. * @param constrainttype The value of constrainttype as prefixSearch. */ public void setConstrainttype_PrefixSearch(String constrainttype) { regConstrainttype(CK_PS, fRES(constrainttype)); } /** * InScope(in ('a', 'b')). And NullOrEmptyIgnored, NullOrEmptyElementIgnored, SeveralRegistered. * @param constrainttypeList The collection of constrainttype as inScope. */ public void setConstrainttype_InScope(Collection<String> constrainttypeList) { regConstrainttype(CK_INS, cTL(constrainttypeList)); } /** * LikeSearch(like 'xxx%' escape ...). And NullOrEmptyIgnored, SeveralRegistered. * @param constrainttype The value of constrainttype as likeSearch. * @param likeSearchOption The option of like-search. (NotNull) */ public void setConstrainttype_LikeSearch(String constrainttype, LikeSearchOption likeSearchOption) { regLSQ(CK_LS, fRES(constrainttype), getCValueConstrainttype(), "ConstraintType", likeSearchOption); } /** * NotLikeSearch(not like 'xxx%' escape ...). And NullOrEmptyIgnored, SeveralRegistered. * @param constrainttype The value of constrainttype as notLikeSearch. * @param likeSearchOption The option of not-like-search. (NotNull) */ public void setConstrainttype_NotLikeSearch(String constrainttype, LikeSearchOption likeSearchOption) { regLSQ(CK_NLS, fRES(constrainttype), getCValueConstrainttype(), "ConstraintType", likeSearchOption); } /** * IsNull(is null). And OnlyOnceRegistered. */ public void setConstrainttype_IsNull() { regConstrainttype(CK_ISN, DOBJ); } /** * IsNotNull(is not null). And OnlyOnceRegistered. */ public void setConstrainttype_IsNotNull() { regConstrainttype(CK_ISNN, DOBJ); } protected void regConstrainttype(ConditionKey k, Object v) { regQ(k, v, getCValueConstrainttype(), "ConstraintType"); } abstract protected ConditionValue getCValueConstrainttype(); /** * Equal(=). And NullOrEmptyIgnored, OnlyOnceRegistered. {LONGCHAR(2147483647)} * @param notes The value of notes as equal. */ public void setNotes_Equal(String notes) { regNotes(CK_EQ, fRES(notes)); } /** * NotEqual(!=). And NullOrEmptyIgnored, OnlyOnceRegistered. * @param notes The value of notes as notEqual. */ public void setNotes_NotEqual(String notes) { regNotes(CK_NE, fRES(notes)); } /** * GreaterThan(&gt;). And NullOrEmptyIgnored, OnlyOnceRegistered. * @param notes The value of notes as greaterThan. */ public void setNotes_GreaterThan(String notes) { regNotes(CK_GT, fRES(notes)); } /** * LessThan(&lt;). And NullOrEmptyIgnored, OnlyOnceRegistered. * @param notes The value of notes as lessThan. */ public void setNotes_LessThan(String notes) { regNotes(CK_LT, fRES(notes)); } /** * GreaterEqual(&gt;=). And NullOrEmptyIgnored, OnlyOnceRegistered. * @param notes The value of notes as greaterEqual. */ public void setNotes_GreaterEqual(String notes) { regNotes(CK_GE, fRES(notes)); } /** * LessEqual(&lt;=). And NullOrEmptyIgnored, OnlyOnceRegistered. * @param notes The value of notes as lessEqual. */ public void setNotes_LessEqual(String notes) { regNotes(CK_LE, fRES(notes)); } /** * PrefixSearch(like 'xxx%'). And NullOrEmptyIgnored, OnlyOnceRegistered. * @param notes The value of notes as prefixSearch. */ public void setNotes_PrefixSearch(String notes) { regNotes(CK_PS, fRES(notes)); } /** * InScope(in ('a', 'b')). And NullOrEmptyIgnored, NullOrEmptyElementIgnored, SeveralRegistered. * @param notesList The collection of notes as inScope. */ public void setNotes_InScope(Collection<String> notesList) { regNotes(CK_INS, cTL(notesList)); } /** * LikeSearch(like 'xxx%' escape ...). And NullOrEmptyIgnored, SeveralRegistered. * @param notes The value of notes as likeSearch. * @param likeSearchOption The option of like-search. (NotNull) */ public void setNotes_LikeSearch(String notes, LikeSearchOption likeSearchOption) { regLSQ(CK_LS, fRES(notes), getCValueNotes(), "Notes", likeSearchOption); } /** * NotLikeSearch(not like 'xxx%' escape ...). And NullOrEmptyIgnored, SeveralRegistered. * @param notes The value of notes as notLikeSearch. * @param likeSearchOption The option of not-like-search. (NotNull) */ public void setNotes_NotLikeSearch(String notes, LikeSearchOption likeSearchOption) { regLSQ(CK_NLS, fRES(notes), getCValueNotes(), "Notes", likeSearchOption); } /** * IsNull(is null). And OnlyOnceRegistered. */ public void setNotes_IsNull() { regNotes(CK_ISN, DOBJ); } /** * IsNotNull(is not null). And OnlyOnceRegistered. */ public void setNotes_IsNotNull() { regNotes(CK_ISNN, DOBJ); } protected void regNotes(ConditionKey k, Object v) { regQ(k, v, getCValueNotes(), "Notes"); } abstract protected ConditionValue getCValueNotes(); // =================================================================================== // Very Internal // ============= // Very Internal (for Suppressing Warn about 'Not Use Import') String xCB() { return TConnectorconstraintCB.class.getName(); } String xCQ() { return TConnectorconstraintCQ.class.getName(); } String xLSO() { return LikeSearchOption.class.getName(); } }
923e3f526bb510d4f5e9d946dfe6aade15c6ab24
9,024
java
Java
app/src/main/java/com/bitmastro/playMusicAlarm/SetAlarm.java
BitMastro/play_music_alarm
2c42b3106cb95a44452feb5f7fcbac2af41ab41f
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/bitmastro/playMusicAlarm/SetAlarm.java
BitMastro/play_music_alarm
2c42b3106cb95a44452feb5f7fcbac2af41ab41f
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/bitmastro/playMusicAlarm/SetAlarm.java
BitMastro/play_music_alarm
2c42b3106cb95a44452feb5f7fcbac2af41ab41f
[ "Apache-2.0" ]
null
null
null
30.798635
80
0.728945
1,000,688
/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.bitmastro.playMusicAlarm; import android.app.ActionBar; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.media.AudioManager; import android.os.Bundle; import android.os.Vibrator; import android.preference.CheckBoxPreference; import android.preference.Preference; import android.preference.PreferenceActivity; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; /** * Manages each alarm */ public class SetAlarm extends PreferenceActivity implements Preference.OnPreferenceChangeListener { private static final String KEY_CURRENT_ALARM = "currentAlarm"; private static final String KEY_ORIGINAL_ALARM = "originalAlarm"; private CheckBoxPreference mEnabledPref; private TimePreference mTimePref; private NumberPickerDialogPreference mDurationPref; private SeekBarDialogPreference mVolumePref; private CheckBoxPreference mVibratePref; private RepeatPreference mRepeatPref; private int mId; private Alarm mOriginalAlarm; @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); // Override the default content view. setContentView(R.layout.set_alarm); ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); // TODO Stop using preferences for this view. Save on done, not after // each change. addPreferencesFromResource(R.xml.alarm_prefs); // Get each preference so we can retrieve the value later. mEnabledPref = (CheckBoxPreference) findPreference("enabled"); mEnabledPref.setOnPreferenceChangeListener(this); mTimePref = (TimePreference) findPreference("time"); mTimePref.setOnPreferenceChangeListener(this); mDurationPref = (NumberPickerDialogPreference) findPreference("duration"); mDurationPref.setOnPreferenceChangeListener(this); mVolumePref = (SeekBarDialogPreference) findPreference("volume"); int streamMaxVolume = ((AudioManager) getSystemService(Context.AUDIO_SERVICE)) .getStreamMaxVolume(AudioManager.STREAM_MUSIC); mVolumePref.setMaxValue(streamMaxVolume); mVolumePref.setOnPreferenceChangeListener(this); mVibratePref = (CheckBoxPreference) findPreference("vibrate"); mVibratePref.setOnPreferenceChangeListener(this); Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); if (!v.hasVibrator()) { getPreferenceScreen().removePreference(mVibratePref); } mRepeatPref = (RepeatPreference) findPreference("setRepeat"); mRepeatPref.setOnPreferenceChangeListener(this); Intent i = getIntent(); Alarm alarm = i.getParcelableExtra(Alarms.ALARM_INTENT_EXTRA); if (alarm == null) { // No alarm means create a new alarm. alarm = new Alarm(); } mOriginalAlarm = alarm; // Populate the prefs with the original alarm data. updatePrefs also // sets mId so it must be called before checking mId below. updatePrefs(mOriginalAlarm); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.menu_delete) { deleteAlarm(); return true; } else if (item.getItemId() == R.id.menu_save) { save(); return true; } else if (item.getItemId() == android.R.id.home) { save(); finish(); return true; } else if (item.getItemId() == R.id.menu_revert) { revert(); return true; } return super.onOptionsItemSelected(item); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.set_alarm_context, menu); return true; } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelable(KEY_ORIGINAL_ALARM, mOriginalAlarm); outState.putParcelable(KEY_CURRENT_ALARM, buildAlarmFromUi()); } @Override protected void onRestoreInstanceState(Bundle state) { super.onRestoreInstanceState(state); Alarm alarmFromBundle = state.getParcelable(KEY_ORIGINAL_ALARM); if (alarmFromBundle != null) { mOriginalAlarm = alarmFromBundle; } alarmFromBundle = state.getParcelable(KEY_CURRENT_ALARM); if (alarmFromBundle != null) { updatePrefs(alarmFromBundle); } } public boolean onPreferenceChange(final Preference p, Object newValue) { mEnabledPref.setChecked(true); return true; } private void updatePrefs(Alarm alarm) { mId = alarm.id; mEnabledPref.setChecked(alarm.enabled); mTimePref.setHour(alarm.hour); mTimePref.setMinute(alarm.minutes); mRepeatPref.setDaysOfWeek(alarm.daysOfWeek); mVibratePref.setChecked(alarm.vibrate); // Give the alert uri to the preference. mDurationPref.setValue(alarm.duration); mVolumePref.setValue(alarm.volume); } @Override public void onBackPressed() { save(); super.onBackPressed(); } private long saveAlarm(Alarm alarm) { if (alarm == null) { alarm = buildAlarmFromUi(); } long time; if (alarm.id == -1) { time = Alarms.addAlarm(this, alarm); // addAlarm populates the alarm with the new id. Update mId so that // changes to other preferences update the new alarm. mId = alarm.id; } else { time = Alarms.setAlarm(this, alarm); } return time; } private Alarm buildAlarmFromUi() { Alarm alarm = new Alarm(); alarm.id = mId; alarm.enabled = mEnabledPref.isChecked(); alarm.hour = mTimePref.getHour(); alarm.minutes = mTimePref.getMinute(); alarm.daysOfWeek = mRepeatPref.getDaysOfWeek(); alarm.vibrate = mVibratePref.isChecked(); alarm.duration = mDurationPref.getValue(); alarm.volume = mVolumePref.getValue(); return alarm; } private void deleteAlarm() { if (mId == -1) { // Unedited, newly created alarms don't require confirmation finish(); } else { new AlertDialog.Builder(this) .setTitle(getString(R.string.delete_alarm)) .setMessage(getString(R.string.delete_alarm_confirm)) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface d, int w) { Alarms.deleteAlarm(SetAlarm.this, mId); finish(); } }).setNegativeButton(android.R.string.cancel, null) .show(); } } private void revert() { int newId = mId; // "Revert" on a newly created alarm should delete it. if (mOriginalAlarm.id == -1) { Alarms.deleteAlarm(SetAlarm.this, newId); } else { saveAlarm(mOriginalAlarm); } updatePrefs(mOriginalAlarm); } /** * Store any changes to the alarm and exit the activity. Show a toast if the * alarm is enabled with the time remaining until alarm */ private void save() { long time = saveAlarm(null); if (mEnabledPref.isChecked()) { popAlarmSetToast(SetAlarm.this, time); } } /** * Display a toast that tells the user how long until the alarm goes off. * This helps prevent "am/pm" mistakes. */ static void popAlarmSetToast(Context context, int hour, int minute, Alarm.DaysOfWeek daysOfWeek) { popAlarmSetToast(context, Alarms.calculateAlarm(hour, minute, daysOfWeek) .getTimeInMillis()); } static void popAlarmSetToast(Context context, long timeInMillis) { String toastText = formatToast(context, timeInMillis); Toast toast = Toast.makeText(context, toastText, Toast.LENGTH_LONG); ToastMaster.setToast(toast); toast.show(); } /** * format "Alarm set for 2 days 7 hours and 53 minutes from now" */ static String formatToast(Context context, long timeInMillis) { long delta = timeInMillis - System.currentTimeMillis(); long hours = delta / (1000 * 60 * 60); long minutes = delta / (1000 * 60) % 60; long days = hours / 24; hours = hours % 24; String daySeq = (days == 0) ? "" : (days == 1) ? context .getString(R.string.day) : context.getString(R.string.days, Long.toString(days)); String minSeq = (minutes == 0) ? "" : (minutes == 1) ? context .getString(R.string.minute) : context.getString( R.string.minutes, Long.toString(minutes)); String hourSeq = (hours == 0) ? "" : (hours == 1) ? context .getString(R.string.hour) : context.getString(R.string.hours, Long.toString(hours)); boolean dispDays = days > 0; boolean dispHour = hours > 0; boolean dispMinute = minutes > 0; int index = (dispDays ? 1 : 0) | (dispHour ? 2 : 0) | (dispMinute ? 4 : 0); String[] formats = context.getResources().getStringArray( R.array.alarm_set); return String.format(formats[index], daySeq, hourSeq, minSeq); } }
923e3fcff43d6df9005dc61e579a2df02c041c3c
6,416
java
Java
src/main/java/com/stripe/model/EventDataClassLookup.java
Dima2022/stripe-java
e12f34ca521c38ad9e824c5a291d98b6c9d33818
[ "MIT" ]
540
2015-01-09T15:09:34.000Z
2022-03-29T15:00:26.000Z
src/main/java/com/stripe/model/EventDataClassLookup.java
Dima2022/stripe-java
e12f34ca521c38ad9e824c5a291d98b6c9d33818
[ "MIT" ]
825
2015-01-05T19:25:18.000Z
2022-03-31T21:31:29.000Z
src/main/java/com/stripe/model/EventDataClassLookup.java
Dima2022/stripe-java
e12f34ca521c38ad9e824c5a291d98b6c9d33818
[ "MIT" ]
315
2015-01-22T05:28:10.000Z
2022-03-23T07:49:57.000Z
50.920635
98
0.752961
1,000,689
// File generated from our OpenAPI spec package com.stripe.model; import java.util.HashMap; import java.util.Map; /** * Event data class look up used in {@link EventDataDeserializer}. The key to look up is `object` * string of the model. */ final class EventDataClassLookup { private static final Map<String, Class<? extends StripeObject>> classLookup = new HashMap<>(); static { classLookup.put("account", Account.class); classLookup.put("account_link", AccountLink.class); classLookup.put("alipay_account", AlipayAccount.class); classLookup.put("apple_pay_domain", ApplePayDomain.class); classLookup.put("application", Application.class); classLookup.put("application_fee", ApplicationFee.class); classLookup.put("balance", Balance.class); classLookup.put("balance_transaction", BalanceTransaction.class); classLookup.put("bank_account", BankAccount.class); classLookup.put("bitcoin_receiver", BitcoinReceiver.class); classLookup.put("bitcoin_transaction", BitcoinTransaction.class); classLookup.put("capability", Capability.class); classLookup.put("card", Card.class); classLookup.put("charge", Charge.class); classLookup.put("connect_collection_transfer", ConnectCollectionTransfer.class); classLookup.put("country_spec", CountrySpec.class); classLookup.put("coupon", Coupon.class); classLookup.put("credit_note", CreditNote.class); classLookup.put("credit_note_line_item", CreditNoteLineItem.class); classLookup.put("customer", Customer.class); classLookup.put("customer_balance_transaction", CustomerBalanceTransaction.class); classLookup.put("discount", Discount.class); classLookup.put("dispute", Dispute.class); classLookup.put("ephemeral_key", EphemeralKey.class); classLookup.put("event", Event.class); classLookup.put("exchange_rate", ExchangeRate.class); classLookup.put("fee_refund", FeeRefund.class); classLookup.put("file", File.class); classLookup.put("file_link", FileLink.class); classLookup.put("invoice", Invoice.class); classLookup.put("invoiceitem", InvoiceItem.class); classLookup.put("issuer_fraud_record", IssuerFraudRecord.class); classLookup.put("item", LineItem.class); classLookup.put("line_item", InvoiceLineItem.class); classLookup.put("login_link", LoginLink.class); classLookup.put("mandate", Mandate.class); classLookup.put("order", Order.class); classLookup.put("order_item", OrderItem.class); classLookup.put("order_return", OrderReturn.class); classLookup.put("payment_intent", PaymentIntent.class); classLookup.put("payment_method", PaymentMethod.class); classLookup.put("payout", Payout.class); classLookup.put("person", Person.class); classLookup.put("plan", Plan.class); classLookup.put("platform_tax_fee", PlatformTaxFee.class); classLookup.put("price", Price.class); classLookup.put("product", Product.class); classLookup.put("promotion_code", PromotionCode.class); classLookup.put("quote", Quote.class); classLookup.put("recipient", Recipient.class); classLookup.put("refund", Refund.class); classLookup.put("reserve_transaction", ReserveTransaction.class); classLookup.put("review", Review.class); classLookup.put("setup_attempt", SetupAttempt.class); classLookup.put("setup_intent", SetupIntent.class); classLookup.put("shipping_rate", ShippingRate.class); classLookup.put("sku", Sku.class); classLookup.put("source", Source.class); classLookup.put("source_mandate_notification", SourceMandateNotification.class); classLookup.put("source_transaction", SourceTransaction.class); classLookup.put("subscription", Subscription.class); classLookup.put("subscription_item", SubscriptionItem.class); classLookup.put("subscription_schedule", SubscriptionSchedule.class); classLookup.put("tax_code", TaxCode.class); classLookup.put("tax_deducted_at_source", TaxDeductedAtSource.class); classLookup.put("tax_id", TaxId.class); classLookup.put("tax_rate", TaxRate.class); classLookup.put("three_d_secure", ThreeDSecure.class); classLookup.put("token", Token.class); classLookup.put("topup", Topup.class); classLookup.put("transfer", Transfer.class); classLookup.put("transfer_reversal", TransferReversal.class); classLookup.put("usage_record", UsageRecord.class); classLookup.put("usage_record_summary", UsageRecordSummary.class); classLookup.put("webhook_endpoint", WebhookEndpoint.class); classLookup.put( "billing_portal.configuration", com.stripe.model.billingportal.Configuration.class); classLookup.put("billing_portal.session", com.stripe.model.billingportal.Session.class); classLookup.put("checkout.session", com.stripe.model.checkout.Session.class); classLookup.put( "identity.verification_report", com.stripe.model.identity.VerificationReport.class); classLookup.put( "identity.verification_session", com.stripe.model.identity.VerificationSession.class); classLookup.put("issuing.authorization", com.stripe.model.issuing.Authorization.class); classLookup.put("issuing.card", com.stripe.model.issuing.Card.class); classLookup.put("issuing.cardholder", com.stripe.model.issuing.Cardholder.class); classLookup.put("issuing.dispute", com.stripe.model.issuing.Dispute.class); classLookup.put("issuing.transaction", com.stripe.model.issuing.Transaction.class); classLookup.put("radar.early_fraud_warning", com.stripe.model.radar.EarlyFraudWarning.class); classLookup.put("radar.value_list", com.stripe.model.radar.ValueList.class); classLookup.put("radar.value_list_item", com.stripe.model.radar.ValueListItem.class); classLookup.put("reporting.report_run", com.stripe.model.reporting.ReportRun.class); classLookup.put("reporting.report_type", com.stripe.model.reporting.ReportType.class); classLookup.put("scheduled_query_run", com.stripe.model.sigma.ScheduledQueryRun.class); classLookup.put("terminal.connection_token", com.stripe.model.terminal.ConnectionToken.class); classLookup.put("terminal.location", com.stripe.model.terminal.Location.class); classLookup.put("terminal.reader", com.stripe.model.terminal.Reader.class); } public static Class<? extends StripeObject> findClass(String objectType) { return classLookup.get(objectType); } }
923e411e446d157b16c8e59cefbef7291a870cdb
2,904
java
Java
src/main/java/com/genersoft/iot/vmp/common/VideoManagerConstants.java
walkTtalk/wvp-GB28181-pro
f52be3039975b41f24f8df02b71b60911aa7c63a
[ "MIT" ]
1
2022-02-24T03:52:51.000Z
2022-02-24T03:52:51.000Z
src/main/java/com/genersoft/iot/vmp/common/VideoManagerConstants.java
walkTtalk/wvp-GB28181-pro
f52be3039975b41f24f8df02b71b60911aa7c63a
[ "MIT" ]
null
null
null
src/main/java/com/genersoft/iot/vmp/common/VideoManagerConstants.java
walkTtalk/wvp-GB28181-pro
f52be3039975b41f24f8df02b71b60911aa7c63a
[ "MIT" ]
null
null
null
36.759494
91
0.747934
1,000,690
package com.genersoft.iot.vmp.common; /** * @description: 定义常量 * @author: swwheihei * @date: 2019年5月30日 下午3:04:04 * */ public class VideoManagerConstants { public static final String WVP_SERVER_PREFIX = "VMP_SIGNALLING_SERVER_INFO_"; public static final String WVP_SERVER_STREAM_PREFIX = "VMP_SIGNALLING_STREAM_"; public static final String MEDIA_SERVER_PREFIX = "VMP_MEDIA_SERVER_"; public static final String MEDIA_SERVER_KEEPALIVE_PREFIX = "VMP_MEDIA_SERVER_KEEPALIVE_"; public static final String MEDIA_SERVERS_ONLINE_PREFIX = "VMP_MEDIA_ONLINE_SERVERS_"; public static final String MEDIA_STREAM_PREFIX = "VMP_MEDIA_STREAM"; public static final String DEVICE_PREFIX = "VMP_DEVICE_"; public static final String CACHEKEY_PREFIX = "VMP_CHANNEL_"; public static final String KEEPLIVEKEY_PREFIX = "VMP_KEEPALIVE_"; // 此处多了一个_,暂不修改 public static final String PLAYER_PREFIX = "VMP_PLAYER_"; public static final String PLAY_BLACK_PREFIX = "VMP_PLAYBACK_"; public static final String DOWNLOAD_PREFIX = "VMP_DOWNLOAD_"; public static final String PLATFORM_KEEPALIVE_PREFIX = "VMP_PLATFORM_KEEPALIVE_"; public static final String PLATFORM_CATCH_PREFIX = "VMP_PLATFORM_CATCH_"; public static final String PLATFORM_REGISTER_PREFIX = "VMP_PLATFORM_REGISTER_"; public static final String PLATFORM_REGISTER_INFO_PREFIX = "VMP_PLATFORM_REGISTER_INFO_"; public static final String PLATFORM_SEND_RTP_INFO_PREFIX = "VMP_PLATFORM_SEND_RTP_INFO_"; public static final String EVENT_ONLINE_REGISTER = "1"; public static final String EVENT_ONLINE_KEEPLIVE = "2"; public static final String EVENT_ONLINE_MESSAGE = "3"; public static final String EVENT_OUTLINE_UNREGISTER = "1"; public static final String EVENT_OUTLINE_TIMEOUT = "2"; public static final String MEDIA_SSRC_USED_PREFIX = "VMP_MEDIA_USED_SSRC_"; public static final String MEDIA_TRANSACTION_USED_PREFIX = "VMP_MEDIA_TRANSACTION_"; public static final String SIP_CSEQ_PREFIX = "VMP_SIP_CSEQ_"; public static final String SIP_SN_PREFIX = "VMP_SIP_SN_"; public static final String SIP_SUBSCRIBE_PREFIX = "VMP_SIP_SUBSCRIBE_"; public static final String SYSTEM_INFO_CPU_PREFIX = "VMP_SYSTEM_INFO_CPU_"; public static final String SYSTEM_INFO_MEM_PREFIX = "VMP_SYSTEM_INFO_MEM_"; public static final String SYSTEM_INFO_NET_PREFIX = "VMP_SYSTEM_INFO_NET_"; //************************** redis 消息********************************* public static final String WVP_MSG_STREAM_CHANGE_PREFIX = "WVP_MSG_STREAM_CHANGE_"; public static final String WVP_MSG_GPS_PREFIX = "VM_MSG_GPS"; //************************** 第三方 **************************************** public static final String WVP_STREAM_GB_ID_PREFIX = "memberNo_"; public static final String WVP_STREAM_GPS_MSG_PREFIX = "WVP_STREAM_GPS_MSG_"; }
923e41dd7e6f29eadd437c01e70ec7449b40f976
228
java
Java
app/src/main/java/com/ron/fp/ui/signin/SigninMvpView.java
daupawar/MvpDagger2
34f50f0a8f281287992de686cb1e9b84a1177142
[ "Apache-2.0" ]
2
2017-05-20T06:51:32.000Z
2017-09-21T07:15:51.000Z
app/src/main/java/com/ron/fp/ui/signin/SigninMvpView.java
daupawar/MvpDagger2
34f50f0a8f281287992de686cb1e9b84a1177142
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/ron/fp/ui/signin/SigninMvpView.java
daupawar/MvpDagger2
34f50f0a8f281287992de686cb1e9b84a1177142
[ "Apache-2.0" ]
null
null
null
15.2
48
0.701754
1,000,691
package com.ron.fp.ui.signin; import com.ron.fp.ui.base.MvpView; /** * Created by Rohan Pawar on 11/05/17. */ public interface SigninMvpView extends MvpView { void onLoginSuccess(); void onFailure(Throwable e); }
923e42aa4124bb6940a6ec75cf5a2a7b9ffcd4ff
1,770
java
Java
src/main/java/net/theopalgames/polywindow/swing/SwingFontRenderer.java
TheOpalGames/PolyWindow
52039c72dfdd3a128674a12e46bada22917fc0b3
[ "MIT" ]
null
null
null
src/main/java/net/theopalgames/polywindow/swing/SwingFontRenderer.java
TheOpalGames/PolyWindow
52039c72dfdd3a128674a12e46bada22917fc0b3
[ "MIT" ]
null
null
null
src/main/java/net/theopalgames/polywindow/swing/SwingFontRenderer.java
TheOpalGames/PolyWindow
52039c72dfdd3a128674a12e46bada22917fc0b3
[ "MIT" ]
null
null
null
31.052632
104
0.644068
1,000,692
package net.theopalgames.polywindow.swing; import net.theopalgames.polywindow.FontRenderer; import java.awt.*; import java.awt.font.FontRenderContext; public class SwingFontRenderer extends FontRenderer { public FontRenderContext frc = new FontRenderContext(null, true, true); public SwingFontRenderer(SwingWindow h) { super(h); } @Override public void drawString(double x, double y, double z, double sX, double sY, String s) { throw new UnsupportedOperationException("The Swing renderer does not support 3D!"); } @Override public void drawString(double x, double y, double sX, double sY, String s) { SwingWindow home = (SwingWindow) this.home; home.graphics.setFont(home.graphics.getFont().deriveFont(Font.BOLD, (float) sX * 32)); home.graphics.drawString(process(s), (int)(x - 1 * sX), (int)(y + 17 * sY)); } @Override public double getStringSizeX(double sX, String s) { SwingWindow home = (SwingWindow) this.home; home.graphics.setFont(home.graphics.getFont().deriveFont(Font.BOLD, (float) sX * 32)); return ((SwingWindow) this.home).graphics.getFont().getStringBounds(process(s), frc).getWidth(); } @Override public double getStringSizeY(double sY, String s) { SwingWindow home = (SwingWindow) this.home; home.graphics.setFont(home.graphics.getFont().deriveFont(Font.BOLD, (float) sY * 32)); return ((SwingWindow) this.home).graphics.getFont().getSize() / 3.0; } public String process(String s) { while (s.contains("\u00A7")) { int in = s.indexOf("\u00A7"); s = s.substring(0, in) + s.substring(in + 13); } return s; } }
923e42e45c19e0d7b1d3a5c2436ee7a7c673f405
1,709
java
Java
auth-server/src/main/java/com/fp/auth/service/impl/RoleServiceImpl.java
s2288156/fast-platform
73ab99541ab03de7c521b378d06613eaafdc8879
[ "Apache-2.0" ]
null
null
null
auth-server/src/main/java/com/fp/auth/service/impl/RoleServiceImpl.java
s2288156/fast-platform
73ab99541ab03de7c521b378d06613eaafdc8879
[ "Apache-2.0" ]
null
null
null
auth-server/src/main/java/com/fp/auth/service/impl/RoleServiceImpl.java
s2288156/fast-platform
73ab99541ab03de7c521b378d06613eaafdc8879
[ "Apache-2.0" ]
null
null
null
29.982456
138
0.732007
1,000,693
package com.fp.auth.service.impl; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.fp.auth.dao.mapper.RoleMapper; import com.fp.auth.domain.dataobject.RoleDO; import com.fp.auth.domain.form.InsertRole; import com.fp.auth.service.IRoleService; import com.fp.mybatis.base.PageInfo; import com.fp.tool.ex.BizException; import com.fp.tool.ex.ResultCodeEnum; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; /** * @author wcy */ @Service public class RoleServiceImpl implements IRoleService { @Autowired private RoleMapper roleMapper; @Override public boolean existRoles(List<String> roleIds) { Integer rolesCount = roleMapper.selectCount(new LambdaQueryWrapper<RoleDO>().in(RoleDO::getId, roleIds)); return rolesCount == roleIds.size(); } @Override public List<RoleDO> getUserRoles(String userId) { return roleMapper.listUserRoles(userId); } @Override public int insert(InsertRole role) { if (existForName(role.getName())) { throw new BizException(ResultCodeEnum.ROLE_EXIST); } return roleMapper.insert(role.convert2RoleDO()); } @Override public Page<RoleDO> pageRoles(PageInfo pageInfo) { return roleMapper.pageRoles(pageInfo); } private boolean existForName(String name) { Optional<RoleDO> optional = Optional.ofNullable(roleMapper.selectOne(new LambdaQueryWrapper<RoleDO>().eq(RoleDO::getName, name))); return optional.isPresent(); } }
923e44380a547571ba02e5d1f4afec1ac187ceda
987
java
Java
src/main/java/mythicbotany/mjoellnir/MjoellnirRuneOutput.java
RDKRACZ/MythicBotany
70391b9ddce3b656cab988923bbb8c0f22a7fed3
[ "Apache-2.0" ]
8
2020-11-12T20:41:18.000Z
2022-03-29T13:55:14.000Z
src/main/java/mythicbotany/mjoellnir/MjoellnirRuneOutput.java
RDKRACZ/MythicBotany
70391b9ddce3b656cab988923bbb8c0f22a7fed3
[ "Apache-2.0" ]
91
2020-10-14T18:13:21.000Z
2022-03-24T19:32:42.000Z
src/main/java/mythicbotany/mjoellnir/MjoellnirRuneOutput.java
RDKRACZ/MythicBotany
70391b9ddce3b656cab988923bbb8c0f22a7fed3
[ "Apache-2.0" ]
11
2020-09-29T14:22:38.000Z
2021-12-19T12:09:38.000Z
30.84375
92
0.77001
1,000,694
package mythicbotany.mjoellnir; import com.google.common.collect.ImmutableList; import mythicbotany.ModBlocks; import mythicbotany.MythicBotany; import mythicbotany.rune.SpecialRuneOutput; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import java.util.List; public class MjoellnirRuneOutput extends SpecialRuneOutput { public static final MjoellnirRuneOutput INSTANCE = new MjoellnirRuneOutput(); private MjoellnirRuneOutput() { super(new ResourceLocation(MythicBotany.getInstance().modid, "mjoellnir")); } @Override public void apply(World world, BlockPos center, List<ItemStack> consumedStacks) { BlockMjoellnir.putInWorld(new ItemStack(ModBlocks.mjoellnir), world, center, false); } @Override public List<ItemStack> getJeiOutputItems() { return ImmutableList.of(new ItemStack(ModBlocks.mjoellnir)); } }
923e444e30b278a07993da14a89417987d006a6c
1,072
java
Java
pandaria-mongo/src/main/java/com/github/jakimli/pandaria/domain/MongoQueryContext.java
meixuesong/pandaria
e36e310ac52dd63724fd66ad52565e7af805a836
[ "MIT" ]
72
2018-10-05T06:35:41.000Z
2021-12-17T09:42:50.000Z
pandaria-mongo/src/main/java/com/github/jakimli/pandaria/domain/MongoQueryContext.java
meixuesong/pandaria
e36e310ac52dd63724fd66ad52565e7af805a836
[ "MIT" ]
7
2018-12-19T07:49:22.000Z
2020-10-15T14:14:15.000Z
pandaria-mongo/src/main/java/com/github/jakimli/pandaria/domain/MongoQueryContext.java
meixuesong/pandaria
e36e310ac52dd63724fd66ad52565e7af805a836
[ "MIT" ]
24
2018-10-10T01:02:43.000Z
2020-10-07T13:56:56.000Z
21.44
65
0.66791
1,000,695
package com.github.jakimli.pandaria.domain; import com.github.jakimli.pandaria.domain.wait.Waitable; import com.mongodb.BasicDBList; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; @Component @Scope("cucumber-glue") public class MongoQueryContext implements Waitable<BasicDBList> { private String collection; @Autowired MongoClient mongo; private BasicDBList result; private String filter; public void collection(String collection) { this.collection = collection; } @Override public void retry() { find(); } @Override public BasicDBList result() { return this.result; } public BasicDBList find() { if (filter != null) { result = mongo.find(collection, filter); } else { result = mongo.findAll(collection); } return result; } public void filter(String filter) { this.filter = filter; } }
923e454351eceb0d04d82d7775e0516e9fa100b9
6,765
java
Java
core/src/main/java/com/linecorp/armeria/client/endpoint/dns/DnsEndpointGroupBuilder.java
georgecao/armeria
316c027b1edca783f64fc1c6342ce456f845e6e3
[ "Apache-2.0" ]
2
2021-12-22T01:14:30.000Z
2021-12-22T01:14:48.000Z
core/src/main/java/com/linecorp/armeria/client/endpoint/dns/DnsEndpointGroupBuilder.java
georgecao/armeria
316c027b1edca783f64fc1c6342ce456f845e6e3
[ "Apache-2.0" ]
null
null
null
core/src/main/java/com/linecorp/armeria/client/endpoint/dns/DnsEndpointGroupBuilder.java
georgecao/armeria
316c027b1edca783f64fc1c6342ce456f845e6e3
[ "Apache-2.0" ]
1
2020-06-20T16:08:38.000Z
2020-06-20T16:08:38.000Z
37.17033
110
0.701404
1,000,696
/* * Copyright 2018 LINE Corporation * * LINE Corporation 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: * * 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.linecorp.armeria.client.endpoint.dns; import static com.google.common.base.Preconditions.checkArgument; import static java.util.Objects.requireNonNull; import java.net.IDN; import java.net.InetSocketAddress; import java.time.Duration; import javax.annotation.Nullable; import com.google.common.base.Ascii; import com.google.common.collect.ImmutableList; import com.linecorp.armeria.client.Endpoint; import com.linecorp.armeria.client.endpoint.EndpointSelectionStrategy; import com.linecorp.armeria.client.retry.Backoff; import com.linecorp.armeria.common.CommonPools; import com.linecorp.armeria.internal.common.util.TransportType; import io.netty.channel.EventLoop; import io.netty.resolver.dns.DnsNameResolverBuilder; import io.netty.resolver.dns.DnsServerAddressStreamProvider; import io.netty.resolver.dns.DnsServerAddressStreamProviders; import io.netty.resolver.dns.DnsServerAddresses; abstract class DnsEndpointGroupBuilder { private final String hostname; @Nullable private EventLoop eventLoop; private int minTtl = 1; private int maxTtl = Integer.MAX_VALUE; private long queryTimeoutMillis = 5000; // 5 seconds private DnsServerAddressStreamProvider serverAddressStreamProvider = DnsServerAddressStreamProviders.platformDefault(); private Backoff backoff = Backoff.exponential(1000, 32000).withJitter(0.2); private EndpointSelectionStrategy selectionStrategy = EndpointSelectionStrategy.weightedRoundRobin(); DnsEndpointGroupBuilder(String hostname) { this.hostname = Ascii.toLowerCase(IDN.toASCII(requireNonNull(hostname, "hostname"), IDN.ALLOW_UNASSIGNED)); } final String hostname() { return hostname; } final EventLoop eventLoop() { if (eventLoop != null) { return eventLoop; } else { return CommonPools.workerGroup().next(); } } /** * Sets the {@link EventLoop} to use for sending DNS queries. */ public DnsEndpointGroupBuilder eventLoop(EventLoop eventLoop) { requireNonNull(eventLoop, "eventLoop"); checkArgument(TransportType.isSupported(eventLoop), "unsupported event loop type: %s", eventLoop); this.eventLoop = eventLoop; return this; } final int minTtl() { return minTtl; } final int maxTtl() { return maxTtl; } /** * Sets the minimum and maximum TTL of the DNS records (in seconds). If the TTL of the DNS record returned * by the DNS server is less than the minimum TTL or greater than the maximum TTL, the TTL from the DNS * server will be ignored and {@code minTtl} or {@code maxTtl} will be used respectively. The default * {@code minTtl} and {@code maxTtl} are {@code 1} and {@link Integer#MAX_VALUE}, which practically tells * to respect the server TTL. */ public DnsEndpointGroupBuilder ttl(int minTtl, int maxTtl) { checkArgument(minTtl > 0 && minTtl <= maxTtl, "minTtl: %s, maxTtl: %s (expected: 1 <= minTtl <= maxTtl)", minTtl, maxTtl); this.minTtl = minTtl; this.maxTtl = maxTtl; return this; } /** * Sets the timeout of the DNS query performed by this endpoint group. {@code 0} disables the timeout. * * @see DnsNameResolverBuilder#queryTimeoutMillis(long) */ public DnsEndpointGroupBuilder queryTimeout(Duration queryTimeout) { requireNonNull(queryTimeout, "queryTimeout"); checkArgument(!queryTimeout.isNegative(), "queryTimeout: %s (expected: >= 0)", queryTimeout); return queryTimeoutMillis(queryTimeout.toMillis()); } /** * Sets the timeout of the DNS query performed by this endpoint group in milliseconds. * {@code 0} disables the timeout. * * @see DnsNameResolverBuilder#queryTimeoutMillis(long) */ public DnsEndpointGroupBuilder queryTimeoutMillis(long queryTimeoutMillis) { checkArgument(queryTimeoutMillis >= 0, "queryTimeoutMillis: %s (expected: >= 0)", queryTimeoutMillis); this.queryTimeoutMillis = queryTimeoutMillis; return this; } final long queryTimeoutMillis() { return queryTimeoutMillis; } final DnsServerAddressStreamProvider serverAddressStreamProvider() { return serverAddressStreamProvider; } /** * Sets the DNS server addresses to send queries to. Operating system default is used by default. */ public DnsEndpointGroupBuilder serverAddresses(InetSocketAddress... serverAddresses) { return serverAddresses(ImmutableList.copyOf(requireNonNull(serverAddresses, "serverAddresses"))); } /** * Sets the DNS server addresses to send queries to. Operating system default is used by default. */ public DnsEndpointGroupBuilder serverAddresses(Iterable<InetSocketAddress> serverAddresses) { requireNonNull(serverAddresses, "serverAddresses"); final DnsServerAddresses addrs = DnsServerAddresses.sequential(serverAddresses); serverAddressStreamProvider = hostname -> addrs.stream(); return this; } final Backoff backoff() { return backoff; } /** * Sets the {@link Backoff} that determines how much delay should be inserted between queries when a DNS * server sent an error response. {@code Backoff.exponential(1000, 32000).withJitter(0.2)} is used by * default. */ public DnsEndpointGroupBuilder backoff(Backoff backoff) { this.backoff = requireNonNull(backoff, "backoff"); return this; } /** * Sets the {@link EndpointSelectionStrategy} that deteremines the enumeration order of {@link Endpoint}s. */ public DnsEndpointGroupBuilder selectionStrategy(EndpointSelectionStrategy selectionStrategy) { this.selectionStrategy = requireNonNull(selectionStrategy, "selectionStrategy"); return this; } final EndpointSelectionStrategy selectionStrategy() { return selectionStrategy; } }
923e4625e469045e1bd89f9b54bf94f559f82721
873
java
Java
Challenges_01/src/com/tts/BarkingDog.java
jordanmor/tts-java-challenges
1e2218755b4a43e6624987d54ae93aa70d2437eb
[ "MIT" ]
null
null
null
Challenges_01/src/com/tts/BarkingDog.java
jordanmor/tts-java-challenges
1e2218755b4a43e6624987d54ae93aa70d2437eb
[ "MIT" ]
null
null
null
Challenges_01/src/com/tts/BarkingDog.java
jordanmor/tts-java-challenges
1e2218755b4a43e6624987d54ae93aa70d2437eb
[ "MIT" ]
null
null
null
31.178571
118
0.725086
1,000,697
package com.tts; /* We have a dog that likes to bark. We need to wake up if the dog is barking at night! Write a method shouldWakeUp that has 2 parameters. 1st parameter should be of type boolean and be named barking it represents if our dog is currently barking. 2nd parameter represents the hour of the day and is of type int with the name hourOfDay and has a valid range of 0-23. We have to wake up if the dog is barking before 8 or after 22 hours so in that case return true. In all other cases return false. If the hourOfDay parameter is less than 0 or greater than 23 return false. */ public class BarkingDog { public static boolean shouldWakeUp(boolean barking, int hourOfDay) { if(hourOfDay < 0 || hourOfDay > 23) { return false; } else if((barking && hourOfDay < 8) || (barking && hourOfDay > 22)) { return true; } return false; } }
923e463f4bd0817dac2dbefad47b3c85af1a99bf
3,598
java
Java
src/main/java/org/jenkinsci/plugins/ghprb/GhprbRepositoryCache.java
pgressa/ghprb-plugin
e286b7db4ef217d92c6576f75aea8943a2ec1aff
[ "MIT" ]
null
null
null
src/main/java/org/jenkinsci/plugins/ghprb/GhprbRepositoryCache.java
pgressa/ghprb-plugin
e286b7db4ef217d92c6576f75aea8943a2ec1aff
[ "MIT" ]
null
null
null
src/main/java/org/jenkinsci/plugins/ghprb/GhprbRepositoryCache.java
pgressa/ghprb-plugin
e286b7db4ef217d92c6576f75aea8943a2ec1aff
[ "MIT" ]
null
null
null
35.009709
141
0.749861
1,000,698
package org.jenkinsci.plugins.ghprb; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; import hudson.model.AbstractProject; import java.util.Collections; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; /** * Singleton cache which caches GhprbRepository and provides thread-safe access. * * We have to keep the project name for further pruning because actual setup of relations forbids us * to effectively maintain content. The relation is: Project -> Trigger -> Repository but not backwards. * * @author Pavol Gressa <anpch@example.com> */ public class GhprbRepositoryCache { private static final Logger logger = Logger.getLogger(GhprbRepositoryCache.class.getName()); private static GhprbRepositoryCache cache = new GhprbRepositoryCache(); public static GhprbRepositoryCache get(){ return cache; } // repo-name : ( project name : ghprb-repo ) private final Map<String,Map<String,GhprbRepository>> repoCache = Maps.newHashMap(); public boolean containsGhprRepository(AbstractProject project){ GhprbTrigger trigger = (GhprbTrigger) project.getTrigger(GhprbTrigger.class); return trigger != null && trigger.getGhprb() != null; } public synchronized void putProject(AbstractProject project){ // Resolve cache structure GhprbRepository repository = getRepositoryProject(project); if (repository == null){ logger.log(Level.SEVERE, "Project: {0} doesn't contain the GhprbTrigger - GitHub Pull request builder is not enabled!",project.getName()); return; } Map<String,GhprbRepository> repositories = repoCache.get(repository.getName()); if(repositories == null){ // create repository projects cache repositories = Maps.newHashMap(); repoCache.put(repository.getName(), repositories); }else{ // or remove for project for update if(repositories.containsKey(project.getName())) remove(repository.getName(),project.getName()); } // update logger.log(Level.INFO,"Register project: {0} for callback from: {1} repo", new Object[]{project.getName(),repository.getName()}); repositories.put(project.getName(), repository); } public synchronized Set<GhprbRepository> getRepoSet(String repoName){ Set<GhprbRepository> set = null; if(repoCache.containsKey(repoName)){ Map<String,GhprbRepository> map = repoCache.get(repoName); set = ImmutableSet.copyOf(map.values()); }else{ set = Collections.<GhprbRepository>emptySet(); } logger.log(Level.INFO,"For {0} {1} has been found",new Object[]{repoName,set.size()}); return set; } public synchronized void removeProject(AbstractProject project, String jobName){ // Resolve cache structure GhprbRepository repository = getRepositoryProject(project); if (repository != null){ remove(repository.getName(),jobName); } } public synchronized void removeProject(AbstractProject project){ removeProject(project,project.getName()); } private void remove(String repoName, String projectName){ // Load cache for particular Map<String,GhprbRepository> projects = repoCache.get(repoName); if(projects != null){ logger.log(Level.INFO,"From {0} remove callback for {1}",new Object[]{repoName,projectName}); projects.remove(projectName); } } private GhprbRepository getRepositoryProject(AbstractProject project){ // check for further processing GhprbTrigger trigger = (GhprbTrigger) project.getTrigger(GhprbTrigger.class); if (trigger == null || trigger.getGhprb() == null){ return null; } return trigger.getGhprb().getRepository(); } }
923e464e9a1871d5d659529a0832f6616aac8761
5,619
java
Java
app/src/main/java/be/ugent/zeus/hydra/feed/preferences/HomeFeedSelectFragment.java
ZeusWPI/hydra-android
b160a774c0b84410ba64045766d452ef5bc317c2
[ "MIT" ]
15
2016-02-16T18:57:49.000Z
2020-06-03T12:43:53.000Z
app/src/main/java/be/ugent/zeus/hydra/feed/preferences/HomeFeedSelectFragment.java
ZeusWPI/hydra-android
b160a774c0b84410ba64045766d452ef5bc317c2
[ "MIT" ]
221
2015-12-01T16:32:07.000Z
2022-03-22T19:52:15.000Z
app/src/main/java/be/ugent/zeus/hydra/feed/preferences/HomeFeedSelectFragment.java
ZeusWPI/hydra-android
b160a774c0b84410ba64045766d452ef5bc317c2
[ "MIT" ]
15
2015-10-20T08:49:29.000Z
2021-11-25T17:08:33.000Z
37.46
132
0.700836
1,000,699
/* * Copyright (c) 2021 The Hydra authors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package be.ugent.zeus.hydra.feed.preferences; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Pair; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.preference.PreferenceManager; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import java.util.*; import java.util.stream.Collectors; import be.ugent.zeus.hydra.R; import be.ugent.zeus.hydra.common.ui.recyclerview.adapters.MultiSelectAdapter; import be.ugent.zeus.hydra.common.ui.recyclerview.viewholders.DataViewHolder; import be.ugent.zeus.hydra.common.ui.recyclerview.viewholders.DescriptionMultiSelectListViewHolder; import be.ugent.zeus.hydra.common.utils.PreferencesUtils; import be.ugent.zeus.hydra.common.utils.ViewUtils; import static be.ugent.zeus.hydra.feed.HomeFeedFragment.PREF_DISABLED_CARD_TYPES; /** * Enables choosing the home feed card types. * * @author Niko Strijbol */ public class HomeFeedSelectFragment extends Fragment { private final Map<String, String> valueMapper = new HashMap<>(); private FeedOptionsAdapter adapter; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_home_feed_select, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); RecyclerView recyclerView = view.findViewById(R.id.recycler_view); adapter = new FeedOptionsAdapter(); recyclerView.setAdapter(adapter); recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); //TODO improve how this is saved. String[] values = getResources().getStringArray(R.array.card_types_names); String[] descriptions = getResources().getStringArray(R.array.card_types_descriptions); String[] ints = getResources().getStringArray(R.array.card_types_nr); List<Tuple> itemTuples = new ArrayList<>(); valueMapper.clear(); for (int i = 0; i < values.length; i++) { valueMapper.put(values[i], ints[i]); itemTuples.add(new Tuple(values[i], descriptions[i])); } List<String> cardTypesList = Arrays.asList(ints); Set<Integer> unwanted = PreferencesUtils.getStringSet(getContext(), PREF_DISABLED_CARD_TYPES).stream() .map(cardTypesList::indexOf) .filter(integer -> integer != -1) // Non-existing ones are gone .collect(Collectors.toSet()); adapter.submitData(itemTuples, unwanted, true); } @Override public void onPause() { super.onPause(); //Save the settings. //We save which cards we DON'T want, so we need to inverse it. List<Pair<Tuple, Boolean>> values = adapter.getItemsAndState(); Set<String> disabled = new HashSet<>(); for (Pair<Tuple, Boolean> value : values) { if (!value.second) { disabled.add(valueMapper.get(value.first.getTitle())); } } SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(requireContext()); preferences.edit().putStringSet(PREF_DISABLED_CARD_TYPES, disabled).apply(); } private static class Tuple { private final String title; private final String description; private Tuple(String title, String description) { this.title = title; this.description = description; } public String getTitle() { return title; } public String getDescription() { return description; } } private static class FeedOptionsAdapter extends MultiSelectAdapter<Tuple> { @NonNull @Override public DataViewHolder<Tuple> onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { return new DescriptionMultiSelectListViewHolder<>( ViewUtils.inflate(parent, R.layout.item_checkbox_string_description), this, Tuple::getTitle, Tuple::getDescription ); } } }
923e46a3c2848d7f3d16110b0e7201533e82c75d
2,264
java
Java
panc/src/main/java/org/quattor/pan/utils/XmlUtils.java
itkovian/pan
7a08df6fa9b4c390320a8ff34fad9b9550164644
[ "Apache-2.0" ]
6
2017-07-25T01:53:30.000Z
2021-12-24T11:44:38.000Z
panc/src/main/java/org/quattor/pan/utils/XmlUtils.java
itkovian/pan
7a08df6fa9b4c390320a8ff34fad9b9550164644
[ "Apache-2.0" ]
152
2015-01-02T22:46:27.000Z
2022-02-18T13:36:39.000Z
panc/src/main/java/org/quattor/pan/utils/XmlUtils.java
itkovian/pan
7a08df6fa9b4c390320a8ff34fad9b9550164644
[ "Apache-2.0" ]
13
2015-03-03T15:34:25.000Z
2019-11-08T18:06:33.000Z
34.30303
95
0.681537
1,000,700
package org.quattor.pan.utils; import static org.quattor.pan.utils.MessageUtils.MSG_MISSING_SAX_TRANSFORMER; import static org.quattor.pan.utils.MessageUtils.MSG_UNEXPECTED_EXCEPTION_WHILE_WRITING_OUTPUT; import java.util.Properties; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.sax.TransformerHandler; import org.quattor.pan.exceptions.CompilerError; public class XmlUtils { private XmlUtils() { } public static TransformerHandler getSaxTransformerHandler() { try { // Generate the transformer factory. Need to guarantee that we get a // SAXTransformerFactory. TransformerFactory factory = TransformerFactory.newInstance(); if (!factory.getFeature(SAXTransformerFactory.FEATURE)) { throw CompilerError.create(MSG_MISSING_SAX_TRANSFORMER); } // Only set the indentation if the returned TransformerFactory // supports it. try { factory.setAttribute("indent-number", Integer.valueOf(4)); } catch (IllegalArgumentException consumed) { } // Can safely cast the factory to a SAX-specific one. Get the // handler to feed with SAX events. SAXTransformerFactory saxfactory = (SAXTransformerFactory) factory; TransformerHandler handler = saxfactory.newTransformerHandler(); // Set parameters of the embedded transformer. Transformer transformer = handler.getTransformer(); Properties properties = new Properties(); properties.setProperty(OutputKeys.INDENT, "yes"); properties.setProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperties(properties); return handler; } catch (TransformerConfigurationException tce) { Error error = CompilerError .create(MSG_UNEXPECTED_EXCEPTION_WHILE_WRITING_OUTPUT); error.initCause(tce); throw error; } } }
923e46e22f4e6367475f7dd56e7d284efafb97f9
11,321
java
Java
Java/Eta/Applications/Examples/src/main/java/com/refinitiv/eta/examples/codec/FilterListCodec.java
Georggi/Real-Time-SDK
2afc005be700d93dd8f80d92d8dd80b41120e096
[ "Apache-2.0" ]
107
2015-07-27T23:43:04.000Z
2019-01-03T07:11:27.000Z
Java/Eta/Applications/Examples/src/main/java/com/refinitiv/eta/examples/codec/FilterListCodec.java
Georggi/Real-Time-SDK
2afc005be700d93dd8f80d92d8dd80b41120e096
[ "Apache-2.0" ]
91
2015-07-28T15:40:43.000Z
2018-12-31T09:37:19.000Z
Java/Eta/Applications/Examples/src/main/java/com/refinitiv/eta/examples/codec/FilterListCodec.java
Georggi/Real-Time-SDK
2afc005be700d93dd8f80d92d8dd80b41120e096
[ "Apache-2.0" ]
68
2015-07-27T08:35:47.000Z
2019-01-01T07:59:39.000Z
42.242537
155
0.718488
1,000,701
/*|----------------------------------------------------------------------------- *| This source code is provided under the Apache 2.0 license -- *| and is provided AS IS with no warranty or guarantee of fit for purpose. -- *| See the project's LICENSE.md for details. -- *| Copyright (C) 2019-2022 Refinitiv. All rights reserved. -- *|----------------------------------------------------------------------------- */ package com.refinitiv.eta.examples.codec; import com.refinitiv.eta.codec.CodecFactory; import com.refinitiv.eta.codec.CodecReturnCodes; import com.refinitiv.eta.codec.DataTypes; import com.refinitiv.eta.codec.DecodeIterator; import com.refinitiv.eta.codec.EncodeIterator; import com.refinitiv.eta.codec.FieldListFlags; import com.refinitiv.eta.codec.FilterEntry; import com.refinitiv.eta.codec.FilterEntryActions; import com.refinitiv.eta.codec.FilterEntryFlags; import com.refinitiv.eta.codec.FilterList; /** * This is used for encoding and decoding a FilterList Container Type. */ public class FilterListCodec { int exampleEncode(EncodeIterator encIter) { ElementListCodec elementListCodec = new ElementListCodec(); // the element list codec FieldListCodec fieldListCodec = new FieldListCodec(); // the field list codec boolean success = true; /* use this to store and check return codes */ int retVal; /* create and initialize our filter list structure */ FilterList filterList = CodecFactory.createFilterList(); /* create a single FilterEntry and use this for all filter list entry encodings*/ FilterEntry filterEntry = CodecFactory.createFilterEntry(); /* populate filter list structure prior to call to EncodeFilterInit */ /* NOTE: the key names used for this example may not correspond to actual name values */ /* indicate that a total count hint will be encoded */ filterList.flags(FieldListFlags.NONE); /* populate filter list's containerType. Since the majority of the items in the filter list are element lists, we'll choose that as the container type*/ filterList.containerType(DataTypes.ELEMENT_LIST); /* begin encoding of filter list - assumes that (*encIter) is already populated with buffer and version information, store return value to determine success or failure */ if ((retVal = filterList.encodeInit(encIter)) < CodecReturnCodes.SUCCESS) { /* error condition - switch our success value to false so we can roll back */ /* print out message with return value string, value, and text */ System.out.printf("Error %s (%d) encountered with EncodeFilterListInit. Error Text: %s\n", CodecReturnCodes.toString(retVal), retVal, CodecReturnCodes.info(retVal)); return retVal; } /* FilterListInit encoding was successful */ System.out.printf("\tFilterList Header Encoded\n"); /*FIRST FILTER ENTRY: encode entry from element list*/ filterEntry.id(1); filterEntry.containerType(DataTypes.ELEMENT_LIST); filterEntry.action(FilterEntryActions.UPDATE); /*get ready to encode first filter entry*/ if((retVal = filterEntry.encodeInit(encIter, 100)) < CodecReturnCodes.SUCCESS) { System.out.printf("Error %s (%d) encountered with EncodeFilterEntryInit. Error Text: %s\n", CodecReturnCodes.toString(retVal), retVal, CodecReturnCodes.info(retVal)); return retVal; } /* now encode nested container using its own specific encode methods*/ System.out.printf("\tEncoding Filter Entry (id: %d) containing an encoded element list", filterEntry.id()); System.out.printf("\n\tElementList Encoding Begin\n"); if ((retVal = elementListCodec.exampleEncode(encIter)) < CodecReturnCodes.SUCCESS) { System.out.printf("Error encoding element list.\n"); System.out.printf("Error %s (%d) encountered with exampleEncodeElementList. Error Text: %s\n", CodecReturnCodes.toString(retVal), retVal, CodecReturnCodes.info(retVal)); return retVal; } // the filter entry containing an element list has been encoded. mark it complete if ((retVal = filterEntry.encodeComplete(encIter, success)) < CodecReturnCodes.SUCCESS) { System.out.printf("Error %s (%d) encountered with EncodeFilterEntryComplete. Error Text: %s\n", CodecReturnCodes.toString(retVal), retVal, CodecReturnCodes.info(retVal)); return retVal; } System.out.printf("\n\tFilter Entry (id: %d) Encoding Complete\n", filterEntry.id()); /*SECOND FILTER ENTRY: encode entry from field list*/ filterEntry.clear(); filterEntry.id(2); filterEntry.containerType(DataTypes.FIELD_LIST); /*need to set the filter entry flag for container type since this entry is type field list, and the container type of the filter list is element list.*/ filterEntry.flags(FilterEntryFlags.HAS_CONTAINER_TYPE); filterEntry.action(FilterEntryActions.UPDATE); /*get ready to encode second filter entry*/ if((retVal = filterEntry.encodeInit(encIter, 100)) < CodecReturnCodes.SUCCESS) { System.out.printf("Error %s (%d) encountered with EncodeFilterEntryInit. Error Text: %s\n", CodecReturnCodes.toString(retVal), retVal, CodecReturnCodes.info(retVal)); return retVal; } /* now encode nested container using its own specific encode fucntions*/ System.out.printf("\tEncoding Filter Entry (id: %d) containing an encoded field list", filterEntry.id()); System.out.printf("\n\tFieldList Encoding Begin\n"); if ((retVal = fieldListCodec.exampleEncode(encIter)) < CodecReturnCodes.SUCCESS) { System.out.printf("Error encoding field list.\n"); System.out.printf("Error %s (%d) encountered with exampleEncodeFieldList. Error Text: %s\n", CodecReturnCodes.toString(retVal), retVal, CodecReturnCodes.info(retVal)); return retVal; } /*the filter entry containing a field list has been encoded. mark it complete*/ if ((retVal = filterEntry.encodeComplete(encIter, success)) < CodecReturnCodes.SUCCESS) { System.out.printf("Error %s (%d) encountered with EncodeFilterEntryComplete. Error Text: %s\n", CodecReturnCodes.toString(retVal), retVal, CodecReturnCodes.info(retVal)); return retVal; } System.out.printf("\n\tFilter Entry (id: %d) Encoding Complete\n", filterEntry.id()); /*THIRD FILTER ENTRY: encode entry from element list*/ filterEntry.clear(); filterEntry.id(3); filterEntry.containerType(DataTypes.ELEMENT_LIST); filterEntry.action(FilterEntryActions.UPDATE); /*get ready to encode third filter entry*/ if((retVal = filterEntry.encodeInit(encIter, 100)) < CodecReturnCodes.SUCCESS) { System.out.printf("Error %s (%d) encountered with EncodeFilterEntryInit. Error Text: %s\n", CodecReturnCodes.toString(retVal), retVal, CodecReturnCodes.info(retVal)); return retVal; } /* now encode nested container using its own specific encode methods*/ System.out.printf("\tEncoding Filter Entry (id: %d) containing an encoded element list", filterEntry.id()); System.out.printf("\n\tElementList Encoding Begin\n"); if ((retVal = elementListCodec.exampleEncode(encIter)) < CodecReturnCodes.SUCCESS) { System.out.printf("Error encoding element list.\n"); System.out.printf("Error %s (%d) encountered with exampleEncodeElementList. Error Text: %s\n", CodecReturnCodes.toString(retVal), retVal, CodecReturnCodes.info(retVal)); return retVal; } // the filter entry containing an element list has been encoded. mark it complete if ((retVal = filterEntry.encodeComplete(encIter, success)) < CodecReturnCodes.SUCCESS) { System.out.printf("Error %s (%d) encountered with EncodeFilterEntryComplete. Error Text: %s\n", CodecReturnCodes.toString(retVal), retVal, CodecReturnCodes.info(retVal)); return retVal; } System.out.printf("\n\tFilter Entry (id: %d) Encoding Complete", filterEntry.id()); /* complete filter list encoding. If success parameter is true, this will finalize encoding. If success parameter is false, this will roll back encoding prior to EncodeFilterListInit */ if ((retVal = filterList.encodeComplete(encIter, true)) < CodecReturnCodes.SUCCESS) { System.out.printf("Error %s (%d) encountered with EncodeFilterListComplete. Error Text: %s\n", CodecReturnCodes.toString(retVal), retVal, CodecReturnCodes.info(retVal)); return retVal; } System.out.printf("\n\tFilterList Encoding Complete\n"); return CodecReturnCodes.SUCCESS; } int exampleDecode(DecodeIterator decIter) { ElementListCodec elementListCodec = new ElementListCodec(); // the element list codec FieldListCodec fieldListCodec = new FieldListCodec(); // the field list codec /* used to store and check return codes */ int retVal; /* create our filter list to decode into */ FilterList filterList = CodecFactory.createFilterList(); /*create filter list entry to decode into */ FilterEntry filterEntry = CodecFactory.createFilterEntry(); /*used to check the data type of the filter list entries*/ int cType; /* decode contents into the filter list structure */ /* decode our filter list header */ if ((retVal = filterList.decode(decIter)) < CodecReturnCodes.SUCCESS) { /* decoding failures tend to be unrecoverable */ System.out.printf("Error %s (%d) encountered with DecodeFilterList. Error Text: %s\n", CodecReturnCodes.toString(retVal), retVal, CodecReturnCodes.info(retVal)); return retVal; } System.out.printf("\tFilterList Header Decoded \n"); /* decode each filter list entry */ /* since this succeeded, we can decode fields until we reach the end of the fields - until CodecReturnCodes.END_OF_CONTAINER is returned */ while ((retVal = filterEntry.decode(decIter)) != CodecReturnCodes.END_OF_CONTAINER) { if (retVal < CodecReturnCodes.SUCCESS) { System.out.printf("Error %s (%d) encountered with DecodeFilterEntry. Error Text: %s\n", CodecReturnCodes.toString(retVal), retVal, CodecReturnCodes.info(retVal)); return retVal; } /* Continue decoding field entries. */ System.out.printf("\tDecoding Filter Entry (id: %d)\n", filterEntry.id()); /*check the filter entry's container type, and use the appropriate decoding method. since our filter-list-encode exmample only encodes elements list and field list, we only test for those two cases*/ cType = filterEntry.containerType(); switch(cType) { case DataTypes.ELEMENT_LIST: if ((retVal = elementListCodec.exampleDecode(decIter)) < CodecReturnCodes.SUCCESS) { System.out.printf("Error %s (%d) encountered with exampleDecodeElementList. Error Text: %s\n", CodecReturnCodes.toString(retVal), retVal, CodecReturnCodes.info(retVal)); return retVal; } break; case DataTypes.FIELD_LIST: if ((retVal = fieldListCodec.exampleDecode(decIter)) < CodecReturnCodes.SUCCESS) { System.out.printf("Error %s (%d) encountered with exampleDecodeFieldList. Error Text: %s\n", CodecReturnCodes.toString(retVal), retVal, CodecReturnCodes.info(retVal)); return retVal; } break; default: break; } System.out.printf("\tFilter Entry (id: %d) Decoding Complete\n", filterEntry.id()); filterEntry.clear(); } System.out.printf("\tFilterList Decoding Complete\n"); return CodecReturnCodes.SUCCESS; } }
923e479c36cfee7e7b84e0f98bc4a195531838a2
3,529
java
Java
src/java/com/mozilla/bagheera/hazelcast/persistence/NoOpMapStore.java
mozilla/SocorroSearchService
31bbd79d3fc824492f3d4b2f0e18de6044ea61ea
[ "Apache-2.0" ]
null
null
null
src/java/com/mozilla/bagheera/hazelcast/persistence/NoOpMapStore.java
mozilla/SocorroSearchService
31bbd79d3fc824492f3d4b2f0e18de6044ea61ea
[ "Apache-2.0" ]
1
2019-02-17T17:43:57.000Z
2019-02-17T17:43:57.000Z
src/java/com/mozilla/bagheera/hazelcast/persistence/NoOpMapStore.java
mozilla/SocorroSearchService
31bbd79d3fc824492f3d4b2f0e18de6044ea61ea
[ "Apache-2.0" ]
1
2019-11-02T23:23:55.000Z
2019-11-02T23:23:55.000Z
29.90678
112
0.646075
1,000,702
/* * Copyright 2011 Mozilla Foundation * * 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.mozilla.bagheera.hazelcast.persistence; import java.util.Collection; import java.util.Map; import java.util.Set; import org.apache.log4j.Logger; import com.hazelcast.core.MapStore; import com.mozilla.bagheera.model.RequestData; /** * An implementation of Hazelcast's MapStore interface that only logs when * methods are called with parameter values. This is only used for debugging and * testing. */ public class NoOpMapStore implements MapStore<String, RequestData> { private static final Logger LOG = Logger.getLogger(NoOpMapStore.class); /* * (non-Javadoc) * * @see com.hazelcast.core.MapLoader#load(java.lang.Object) */ @Override public RequestData load(String key) { LOG.info(String.format("load called\nkey: %s", key)); return null; } /* * (non-Javadoc) * * @see com.hazelcast.core.MapLoader#loadAll(java.util.Collection) */ @Override public Map<String, RequestData> loadAll(Collection<String> keys) { LOG.info(String.format("loadAll called with %d keys", keys.size())); return null; } /* * (non-Javadoc) * * @see com.hazelcast.core.MapStore#store(java.lang.Object, * java.lang.Object) */ @Override public void store(String key, RequestData value) { byte[] payload = value.getPayload(); if (payload != null) { LOG.info(String.format("%s %d \"%s\"", new Object[] { value.getIpAddress(), payload.length, value.getUserAgent() })); } else { LOG.info(String.format("%s 0 \"%s\"", new Object[] { value.getIpAddress(), value.getUserAgent() })); } } /* * (non-Javadoc) * * @see com.hazelcast.core.MapStore#storeAll(java.util.Map) */ @Override public void storeAll(Map<String, RequestData> map) { LOG.info(String.format("storeAll called with %d entries", map.size())); for (Map.Entry<String, RequestData> entry : map.entrySet()) { store(entry.getKey(), entry.getValue()); } } /* * (non-Javadoc) * * @see com.hazelcast.core.MapStore#delete(java.lang.Object) */ @Override public void delete(String key) { LOG.info(String.format("delete called\nkey: %s", key)); } /* * (non-Javadoc) * * @see com.hazelcast.core.MapStore#deleteAll(java.util.Collection) */ @Override public void deleteAll(Collection<String> keys) { LOG.info(String.format("storeAll called with %d entries", keys.size())); } @Override public Set<String> loadAllKeys() { return null; } }
923e47bf085f41c5ff9ab4ab5d4a99da404c60ad
6,799
java
Java
open-metadata-implementation/adapters/open-connectors/governance-daemon-connectors/data-platform-connectors/cassandra-open-metadata-connector/src/main/java/org/odpi/openmetadata/adapters/connectors/cassandra/CassandraStoreConnector.java
ruxandraRosu/egeria
f3906b67455fc0cd94df6480aefd45060690094e
[ "Apache-2.0" ]
null
null
null
open-metadata-implementation/adapters/open-connectors/governance-daemon-connectors/data-platform-connectors/cassandra-open-metadata-connector/src/main/java/org/odpi/openmetadata/adapters/connectors/cassandra/CassandraStoreConnector.java
ruxandraRosu/egeria
f3906b67455fc0cd94df6480aefd45060690094e
[ "Apache-2.0" ]
2
2019-09-24T18:35:21.000Z
2019-09-24T19:48:48.000Z
open-metadata-implementation/adapters/open-connectors/governance-daemon-connectors/data-platform-connectors/cassandra-open-metadata-connector/src/main/java/org/odpi/openmetadata/adapters/connectors/cassandra/CassandraStoreConnector.java
ruxandraRosu/egeria
f3906b67455fc0cd94df6480aefd45060690094e
[ "Apache-2.0" ]
null
null
null
35.596859
122
0.615532
1,000,703
/* SPDX-License-Identifier: Apache-2.0 */ /* Copyright Contributors to the ODPi Egeria project. */ package org.odpi.openmetadata.adapters.connectors.cassandra; import com.datastax.driver.core.*; import org.odpi.openmetadata.adapters.connectors.cassandra.auditlog.CassandraConnectorAuditCode; import org.odpi.openmetadata.frameworks.connectors.ConnectorBase; import org.odpi.openmetadata.frameworks.connectors.properties.ConnectionProperties; import org.odpi.openmetadata.frameworks.connectors.properties.EndpointProperties; import org.odpi.openmetadata.repositoryservices.auditlog.OMRSAuditLog; import org.odpi.openmetadata.repositoryservices.connectors.auditable.AuditableConnector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The type Cassandra store connector. */ public class CassandraStoreConnector extends ConnectorBase implements AuditableConnector { private static final Logger log = LoggerFactory.getLogger(CassandraStoreConnector.class); private OMRSAuditLog omrsAuditLog; private CassandraConnectorAuditCode auditLog; private String serverAddress = null; private String clusterName = null; private String username = null; private String password = null; private Cluster cluster; private Session session; /** * Initialize the connector. * * @param connectorInstanceId - unique id for the connector instance - useful for messages etc * @param connectionProperties - POJO for the configuration used to create the connector. */ @Override public void initialize(String connectorInstanceId, ConnectionProperties connectionProperties) { final String actionDescription = "initialize"; this.connectorInstanceId = connectorInstanceId; this.connectionProperties = connectionProperties; EndpointProperties endpoint = connectionProperties.getEndpoint(); super.initialize(connectorInstanceId, connectionProperties); if (omrsAuditLog != null) { auditLog = CassandraConnectorAuditCode.CONNECTOR_INITIALIZING; omrsAuditLog.logRecord( actionDescription, auditLog.getLogMessageId(), auditLog.getSeverity(), auditLog.getFormattedLogMessage(), null, auditLog.getSystemAction(), auditLog.getUserAction()); } if (endpoint != null) { serverAddress = endpoint.getAddress(); if (serverAddress != null) { log.info("The connecting cassandra cluster server address is: {}.", serverAddress); } else { log.error("Errors in the Cassandra server configuration. The address of the server cannot be extracted."); if (omrsAuditLog != null) { auditLog = CassandraConnectorAuditCode.CONNECTOR_SERVER_CONFIGURATION_ERROR; omrsAuditLog.logRecord(actionDescription, auditLog.getLogMessageId(), auditLog.getSeverity(), auditLog.getFormattedLogMessage(), null, auditLog.getSystemAction(), auditLog.getUserAction()); } } } else { log.error("Errors in Cassandra server address. The endpoint containing the server address is invalid."); if (omrsAuditLog != null) { auditLog = CassandraConnectorAuditCode.CONNECTOR_SERVER_ADDRESS_ERROR; omrsAuditLog.logRecord(actionDescription, auditLog.getLogMessageId(), auditLog.getSeverity(), auditLog.getFormattedLogMessage(), null, auditLog.getSystemAction(), auditLog.getUserAction()); } } startCassandraConnection(); if (cluster.getClusterName().equals(clusterName) && omrsAuditLog != null) { auditLog = CassandraConnectorAuditCode.CONNECTOR_INITIALIZED; omrsAuditLog.logRecord(actionDescription, auditLog.getLogMessageId(), auditLog.getSeverity(), auditLog.getFormattedLogMessage(), null, auditLog.getSystemAction(), auditLog.getUserAction()); } } /** * Set up the Cassandra Cluster Connection */ public void startCassandraConnection() { this.cluster = Cluster.builder() .addContactPoint(serverAddress) .withClusterName(clusterName) .withCredentials(username, password) .build(); session = cluster.connect(); } /** * Provide Cassandra Session. * * @return Cassandra session. */ public Session getSession() { return this.session; } /** * Terminate Cassandra cluster. */ public void shutdown() { String actionDescription = "Shut down the Cassandra connection."; session.close(); cluster.close(); auditLog = CassandraConnectorAuditCode.CONNECTOR_SHUTDOWN; omrsAuditLog.logRecord(actionDescription, auditLog.getLogMessageId(), auditLog.getSeverity(), auditLog.getFormattedLogMessage(), null, auditLog.getSystemAction(), auditLog.getUserAction()); } /** * Pass the instance of OMRS Audit Log * * @param auditLog audit log object */ @Override public void setAuditLog(OMRSAuditLog auditLog) { this.omrsAuditLog = auditLog; } /** * Register listener. * * @param cassandraStoreListener the cassandra store listener */ public void registerListener(CassandraStoreListener cassandraStoreListener) { if (cassandraStoreListener != null) { this.cluster.register(cassandraStoreListener); log.info("Registering cassandra cluster listener: {}", cassandraStoreListener.toString()); } else { String actionDescription = "Error in registering cassandra store listener."; auditLog = CassandraConnectorAuditCode.CONNECTOR_REGISTER_LISTENER_ERROR; omrsAuditLog.logRecord(actionDescription, auditLog.getLogMessageId(), auditLog.getSeverity(), auditLog.getFormattedLogMessage(), null, auditLog.getSystemAction(), auditLog.getUserAction()); } } }
923e47e9e4e06303d3669cd7756e73690cb20236
36,010
java
Java
src/com/scm/dao/domain/InventoryMasterMftgAudit.java
theoka81/mycoe-newtest-repo
c12139b9104735d59c81200f9376bb56aef45180
[ "MIT" ]
null
null
null
src/com/scm/dao/domain/InventoryMasterMftgAudit.java
theoka81/mycoe-newtest-repo
c12139b9104735d59c81200f9376bb56aef45180
[ "MIT" ]
null
null
null
src/com/scm/dao/domain/InventoryMasterMftgAudit.java
theoka81/mycoe-newtest-repo
c12139b9104735d59c81200f9376bb56aef45180
[ "MIT" ]
null
null
null
24.249158
103
0.7594
1,000,704
package com.scm.dao.domain; import java.io.Serializable; import javax.persistence.*; import java.sql.Timestamp; /** * The persistent class for the InventoryMasterMftgAudits database table. * */ @Entity @Table(name="InventoryMasterMftgAudits") @NamedQuery(name="InventoryMasterMftgAudit.findAll", query="SELECT i FROM InventoryMasterMftgAudit i") public class InventoryMasterMftgAudit implements Serializable { private static final Long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="AuditId", unique=true, nullable=false) private Long auditId; @Column(name="AbcCode1MarginInventory") private String abcCode1MarginInventory; @Column(name="AbcCode1SalesInventory") private String abcCode1SalesInventory; @Column(name="AbcCode3InvestmentInventory") private String abcCode3InvestmentInventory; @Column(name="AbcCodeOverrideIndicator") private String abcCodeOverrideIndicator; @Column(name="Action") private String action; @Column(name="ActiveIngredientFlag") private String activeIngredientFlag; @Column(name="AllowShippingofHeldLots") private String allowShippingofHeldLots; @Column(name="ApsPlanningUom") private String apsPlanningUom; @Column(name="AtoForecastControl") private String atoForecastControl; @Column(name="AtpComponents") private String atpComponents; @Column(name="AtpRuleName") private String atpRuleName; @Column(name="BackordersAllowed", nullable=false) private Boolean backordersAllowed; @Column(name="BestBeforeDefaultDays") private Long bestBeforeDefaultDays; @Column(name="BulkPackedFlag", nullable=false) private Boolean bulkPackedFlag; @Column(name="CheckAtp") private String checkAtp; @Column(name="CheckAvailability", nullable=false) private Boolean checkAvailability; @Column(name="CommitmentDateMethod") private String commitmentDateMethod; @Column(name="CommitmentMethod") private String commitmentMethod; @Column(name="CommitmentSpecificDays") private Long commitmentSpecificDays; @Column(name="ComponentType") private String componentType; @Column(name="Composition") private String composition; @Column(name="ConstraintsFlag") private String constraintsFlag; @Column(name="Consumable") private String consumable; @Column(name="ContractItem") private String contractItem; @Column(name="CoProductsByProductsIntermediate") private String coProductsByProductsIntermediate; @Column(name="CountryofOriginRequiredFlag") private String countryofOriginRequiredFlag; @Column(name="CreatedBySystemUserId") private Long createdBySystemUserId; @Column(name="CrossDockingFlag") private String crossDockingFlag; @Column(name="CumulativeThresholdUnitofMeasure") private String cumulativeThresholdUnitofMeasure; @Column(name="DateTime") private Timestamp dateTime; @Column(name="DeferDamperDays") private Long deferDamperDays; @Column(name="DemandFlowEndItemFlag") private String demandFlowEndItemFlag; @Column(name="DualPickingProcessOption") private String dualPickingProcessOption; @Column(name="DualTolerance") private Long dualTolerance; @Column(name="DualUnitOfMeasureItem") private String dualUnitOfMeasureItem; @Column(name="ExpediteDamperDays") private Long expediteDamperDays; @Column(name="ExplodeItem") private String explodeItem; @Column(name="FixedorVariableLeadtime") private Long fixedorVariableLeadtime; @Column(name="FreezeTimeFenceDays") private Long freezeTimeFenceDays; @Column(name="FromGrade") private String fromGrade; @Column(name="FromPotency") private String fromPotency; @Column(name="GradeControl") private String gradeControl; @Column(name="GradePotencyPricing") private Long gradePotencyPricing; @Column(name="Id", nullable=false) private Long id; @Column(name="IsActive", nullable=false) private Boolean isActive; @Column(name="IsDeleted", nullable=false) private Boolean isDeleted; @Column(name="IsLocked") private Boolean isLocked; @Column(name="IssueTypeCode") private String issueTypeCode; @Column(name="ItemFlashMessage") private String itemFlashMessage; @Column(name="ItemId") private Long itemId; @Column(name="ItemNo") private String itemNo; @Column(name="KanbanExplodetoLowerLevel") private String kanbanExplodetoLowerLevel; @Column(name="KanbanItem") private String kanbanItem; @Column(name="LayerCodeSource") private String layerCodeSource; @Column(name="LeadtimeCumulative") private Long leadtimeCumulative; @Column(name="LeadtimeLevel") private Long leadtimeLevel; @Column(name="LeadtimeMFG") private Long leadtimeMFG; @Column(name="LeadtimePerUnit") private String leadtimePerUnit; @Column(name="LeanManufacturingFlag") private String leanManufacturingFlag; @Column(name="LevelInventoryCost") private Long levelInventoryCost; @Column(name="LevelPurchasePrice") private Long levelPurchasePrice; @Column(name="LevelSalesBasePrice") private Long levelSalesBasePrice; @Column(name="LineCellIdentifier") private String lineCellIdentifier; @Column(name="LineType") private String lineType; @Column(name="LotAuditFlag") private String lotAuditFlag; @Column(name="LotEffectiveDefaultDays") private Long lotEffectiveDefaultDays; @Column(name="LotExpiratonDateCalculationMethod") private Long lotExpiratonDateCalculationMethod; @Column(name="LotNoPreAssignment") private String lotNoPreAssignment; @Column(name="LotStatusCodeExpanded") private String lotStatusCodeExpanded; @Column(name="LowLevelCode") private Long lowLevelCode; @Column(name="MakeBuyCode") private Long makeBuyCode; @Column(name="MarginMaintenancePercentage") private String marginMaintenancePercentage; @Column(name="MaterialStatus") private String materialStatus; @Column(name="MatrixControlled") private String matrixControlled; @Column(name="MaximumCumulativeThreshold") private String maximumCumulativeThreshold; @Column(name="MaximumOperationalThreshold") private String maximumOperationalThreshold; @Column(name="MessageTimeFenceDays") private Long messageTimeFenceDays; @Column(name="MethodConfiguratorCosting") private String methodConfiguratorCosting; @Column(name="MinimumCumulativeThreshold") private String minimumCumulativeThreshold; @Column(name="MinimumOperationalThreshold") private String minimumOperationalThreshold; @Column(name="ModifiedBySystemUserId") private Long modifiedBySystemUserId; @Column(name="ModifiedValues") private String modifiedValues; private Long MPSMRPTimeFence4; @Column(name="OperationalThresholdUnitofMeasure") private String operationalThresholdUnitofMeasure; @Column(name="OrderPolicyCode") private Long orderPolicyCode; @Column(name="OrderWith") private String orderWith; @Column(name="PercentMargin") private String percentMargin; @Column(name="PlannerNo") private Long plannerNo; @Column(name="PlanningCode") private Long planningCode; @Column(name="PlanningTimeFenceDays") private Long planningTimeFenceDays; @Column(name="PlanningTimeFenceRule") private String planningTimeFenceRule; @Column(name="PotencyControl") private String potencyControl; @Column(name="PrintMessage") private String printMessage; @Column(name="PriorityOneAlertLevel") private String priorityOneAlertLevel; @Column(name="PriorityTwoAlertLevel") private String priorityTwoAlertLevel; @Column(name="ProductionNoControlled") private String productionNoControlled; @Column(name="PurchasingEffectiveDays") private Long purchasingEffectiveDays; @Column(name="QuantityAccountingCost") private Long quantityAccountingCost; @Column(name="QuantityMfgLeadtime") private Long quantityMfgLeadtime; @Column(name="RestrictWorkOrderLotAssignment") private String restrictWorkOrderLotAssignment; @Column(name="RoundtoWholeNo") private Long roundtoWholeNo; @Column(name="SafetyLeadtime") private Long safetyLeadtime; @Column(name="Segment1") private String segment1; @Column(name="Segment10") private String segment10; @Column(name="Segment2") private String segment2; @Column(name="Segment3") private String segment3; @Column(name="Segment4") private String segment4; @Column(name="Segment5") private String segment5; @Column(name="Segment6") private String segment6; @Column(name="Segment7") private String segment7; @Column(name="Segment8") private String segment8; @Column(name="Segment9") private String segment9; @Column(name="SellableItem") private String sellableItem; @Column(name="SellByDefaultDays") private Long sellByDefaultDays; @Column(name="ShipmentLeadtimeOffset") private Long shipmentLeadtimeOffset; @Column(name="SpecialLotFormat") private String specialLotFormat; @Column(name="StandardGrade") private String standardGrade; @Column(name="StandardPotency") private String standardPotency; @Column(name="StandardUnitofMeasureConversion") private String standardUnitofMeasureConversion; @Column(name="StockingType") private String stockingType; @Column(name="SystemUserId") private Long systemUserId; @Column(name="Template") private String template; @Column(name="ThruGrade") private String thruGrade; @Column(name="ThruPotency") private String thruPotency; @Column(name="TotalProductCycleTime") private String totalProductCycleTime; @Column(name="UserLotDate1DefaultDays") private Long userLotDate1DefaultDays; @Column(name="UserLotDate2DefaultDays") private Long userLotDate2DefaultDays; @Column(name="UserLotDate3DefaultDays") private Long userLotDate3DefaultDays; @Column(name="UserLotDate4DefaultDays") private Long userLotDate4DefaultDays; @Column(name="UserLotDate5DefaultDays") private Long userLotDate5DefaultDays; @Column(name="ValueOrderPolicy") private Long valueOrderPolicy; @Column(name="VendorManagedInventory") private String vendorManagedInventory; public InventoryMasterMftgAudit() { } public Long getAuditId() { return this.auditId; } public void setAuditId(Long auditId) { this.auditId = auditId; } public String getAbcCode1MarginInventory() { return this.abcCode1MarginInventory; } public void setAbcCode1MarginInventory(String abcCode1MarginInventory) { this.abcCode1MarginInventory = abcCode1MarginInventory; } public String getAbcCode1SalesInventory() { return this.abcCode1SalesInventory; } public void setAbcCode1SalesInventory(String abcCode1SalesInventory) { this.abcCode1SalesInventory = abcCode1SalesInventory; } public String getAbcCode3InvestmentInventory() { return this.abcCode3InvestmentInventory; } public void setAbcCode3InvestmentInventory(String abcCode3InvestmentInventory) { this.abcCode3InvestmentInventory = abcCode3InvestmentInventory; } public String getAbcCodeOverrideIndicator() { return this.abcCodeOverrideIndicator; } public void setAbcCodeOverrideIndicator(String abcCodeOverrideIndicator) { this.abcCodeOverrideIndicator = abcCodeOverrideIndicator; } public String getAction() { return this.action; } public void setAction(String action) { this.action = action; } public String getActiveIngredientFlag() { return this.activeIngredientFlag; } public void setActiveIngredientFlag(String activeIngredientFlag) { this.activeIngredientFlag = activeIngredientFlag; } public String getAllowShippingofHeldLots() { return this.allowShippingofHeldLots; } public void setAllowShippingofHeldLots(String allowShippingofHeldLots) { this.allowShippingofHeldLots = allowShippingofHeldLots; } public String getApsPlanningUom() { return this.apsPlanningUom; } public void setApsPlanningUom(String apsPlanningUom) { this.apsPlanningUom = apsPlanningUom; } public String getAtoForecastControl() { return this.atoForecastControl; } public void setAtoForecastControl(String atoForecastControl) { this.atoForecastControl = atoForecastControl; } public String getAtpComponents() { return this.atpComponents; } public void setAtpComponents(String atpComponents) { this.atpComponents = atpComponents; } public String getAtpRuleName() { return this.atpRuleName; } public void setAtpRuleName(String atpRuleName) { this.atpRuleName = atpRuleName; } public Boolean getBackordersAllowed() { return this.backordersAllowed; } public void setBackordersAllowed(Boolean backordersAllowed) { this.backordersAllowed = backordersAllowed; } public Long getBestBeforeDefaultDays() { return this.bestBeforeDefaultDays; } public void setBestBeforeDefaultDays(Long bestBeforeDefaultDays) { this.bestBeforeDefaultDays = bestBeforeDefaultDays; } public Boolean getBulkPackedFlag() { return this.bulkPackedFlag; } public void setBulkPackedFlag(Boolean bulkPackedFlag) { this.bulkPackedFlag = bulkPackedFlag; } public String getCheckAtp() { return this.checkAtp; } public void setCheckAtp(String checkAtp) { this.checkAtp = checkAtp; } public Boolean getCheckAvailability() { return this.checkAvailability; } public void setCheckAvailability(Boolean checkAvailability) { this.checkAvailability = checkAvailability; } public String getCommitmentDateMethod() { return this.commitmentDateMethod; } public void setCommitmentDateMethod(String commitmentDateMethod) { this.commitmentDateMethod = commitmentDateMethod; } public String getCommitmentMethod() { return this.commitmentMethod; } public void setCommitmentMethod(String commitmentMethod) { this.commitmentMethod = commitmentMethod; } public Long getCommitmentSpecificDays() { return this.commitmentSpecificDays; } public void setCommitmentSpecificDays(Long commitmentSpecificDays) { this.commitmentSpecificDays = commitmentSpecificDays; } public String getComponentType() { return this.componentType; } public void setComponentType(String componentType) { this.componentType = componentType; } public String getComposition() { return this.composition; } public void setComposition(String composition) { this.composition = composition; } public String getConstraintsFlag() { return this.constraintsFlag; } public void setConstraintsFlag(String constraintsFlag) { this.constraintsFlag = constraintsFlag; } public String getConsumable() { return this.consumable; } public void setConsumable(String consumable) { this.consumable = consumable; } public String getContractItem() { return this.contractItem; } public void setContractItem(String contractItem) { this.contractItem = contractItem; } public String getCoProductsByProductsIntermediate() { return this.coProductsByProductsIntermediate; } public void setCoProductsByProductsIntermediate(String coProductsByProductsIntermediate) { this.coProductsByProductsIntermediate = coProductsByProductsIntermediate; } public String getCountryofOriginRequiredFlag() { return this.countryofOriginRequiredFlag; } public void setCountryofOriginRequiredFlag(String countryofOriginRequiredFlag) { this.countryofOriginRequiredFlag = countryofOriginRequiredFlag; } public Long getCreatedBySystemUserId() { return this.createdBySystemUserId; } public void setCreatedBySystemUserId(Long createdBySystemUserId) { this.createdBySystemUserId = createdBySystemUserId; } public String getCrossDockingFlag() { return this.crossDockingFlag; } public void setCrossDockingFlag(String crossDockingFlag) { this.crossDockingFlag = crossDockingFlag; } public String getCumulativeThresholdUnitofMeasure() { return this.cumulativeThresholdUnitofMeasure; } public void setCumulativeThresholdUnitofMeasure(String cumulativeThresholdUnitofMeasure) { this.cumulativeThresholdUnitofMeasure = cumulativeThresholdUnitofMeasure; } public Timestamp getDateTime() { return this.dateTime; } public void setDateTime(Timestamp dateTime) { this.dateTime = dateTime; } public Long getDeferDamperDays() { return this.deferDamperDays; } public void setDeferDamperDays(Long deferDamperDays) { this.deferDamperDays = deferDamperDays; } public String getDemandFlowEndItemFlag() { return this.demandFlowEndItemFlag; } public void setDemandFlowEndItemFlag(String demandFlowEndItemFlag) { this.demandFlowEndItemFlag = demandFlowEndItemFlag; } public String getDualPickingProcessOption() { return this.dualPickingProcessOption; } public void setDualPickingProcessOption(String dualPickingProcessOption) { this.dualPickingProcessOption = dualPickingProcessOption; } public Long getDualTolerance() { return this.dualTolerance; } public void setDualTolerance(Long dualTolerance) { this.dualTolerance = dualTolerance; } public String getDualUnitOfMeasureItem() { return this.dualUnitOfMeasureItem; } public void setDualUnitOfMeasureItem(String dualUnitOfMeasureItem) { this.dualUnitOfMeasureItem = dualUnitOfMeasureItem; } public Long getExpediteDamperDays() { return this.expediteDamperDays; } public void setExpediteDamperDays(Long expediteDamperDays) { this.expediteDamperDays = expediteDamperDays; } public String getExplodeItem() { return this.explodeItem; } public void setExplodeItem(String explodeItem) { this.explodeItem = explodeItem; } public Long getFixedorVariableLeadtime() { return this.fixedorVariableLeadtime; } public void setFixedorVariableLeadtime(Long fixedorVariableLeadtime) { this.fixedorVariableLeadtime = fixedorVariableLeadtime; } public Long getFreezeTimeFenceDays() { return this.freezeTimeFenceDays; } public void setFreezeTimeFenceDays(Long freezeTimeFenceDays) { this.freezeTimeFenceDays = freezeTimeFenceDays; } public String getFromGrade() { return this.fromGrade; } public void setFromGrade(String fromGrade) { this.fromGrade = fromGrade; } public String getFromPotency() { return this.fromPotency; } public void setFromPotency(String fromPotency) { this.fromPotency = fromPotency; } public String getGradeControl() { return this.gradeControl; } public void setGradeControl(String gradeControl) { this.gradeControl = gradeControl; } public Long getGradePotencyPricing() { return this.gradePotencyPricing; } public void setGradePotencyPricing(Long gradePotencyPricing) { this.gradePotencyPricing = gradePotencyPricing; } public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public Boolean getIsActive() { return this.isActive; } public void setIsActive(Boolean isActive) { this.isActive = isActive; } public Boolean getIsDeleted() { return this.isDeleted; } public void setIsDeleted(Boolean isDeleted) { this.isDeleted = isDeleted; } public Boolean getIsLocked() { return this.isLocked; } public void setIsLocked(Boolean isLocked) { this.isLocked = isLocked; } public String getIssueTypeCode() { return this.issueTypeCode; } public void setIssueTypeCode(String issueTypeCode) { this.issueTypeCode = issueTypeCode; } public String getItemFlashMessage() { return this.itemFlashMessage; } public void setItemFlashMessage(String itemFlashMessage) { this.itemFlashMessage = itemFlashMessage; } public Long getItemId() { return this.itemId; } public void setItemId(Long itemId) { this.itemId = itemId; } public String getItemNo() { return this.itemNo; } public void setItemNo(String itemNo) { this.itemNo = itemNo; } public String getKanbanExplodetoLowerLevel() { return this.kanbanExplodetoLowerLevel; } public void setKanbanExplodetoLowerLevel(String kanbanExplodetoLowerLevel) { this.kanbanExplodetoLowerLevel = kanbanExplodetoLowerLevel; } public String getKanbanItem() { return this.kanbanItem; } public void setKanbanItem(String kanbanItem) { this.kanbanItem = kanbanItem; } public String getLayerCodeSource() { return this.layerCodeSource; } public void setLayerCodeSource(String layerCodeSource) { this.layerCodeSource = layerCodeSource; } public Long getLeadtimeCumulative() { return this.leadtimeCumulative; } public void setLeadtimeCumulative(Long leadtimeCumulative) { this.leadtimeCumulative = leadtimeCumulative; } public Long getLeadtimeLevel() { return this.leadtimeLevel; } public void setLeadtimeLevel(Long leadtimeLevel) { this.leadtimeLevel = leadtimeLevel; } public Long getLeadtimeMFG() { return this.leadtimeMFG; } public void setLeadtimeMFG(Long leadtimeMFG) { this.leadtimeMFG = leadtimeMFG; } public String getLeadtimePerUnit() { return this.leadtimePerUnit; } public void setLeadtimePerUnit(String leadtimePerUnit) { this.leadtimePerUnit = leadtimePerUnit; } public String getLeanManufacturingFlag() { return this.leanManufacturingFlag; } public void setLeanManufacturingFlag(String leanManufacturingFlag) { this.leanManufacturingFlag = leanManufacturingFlag; } public Long getLevelInventoryCost() { return this.levelInventoryCost; } public void setLevelInventoryCost(Long levelInventoryCost) { this.levelInventoryCost = levelInventoryCost; } public Long getLevelPurchasePrice() { return this.levelPurchasePrice; } public void setLevelPurchasePrice(Long levelPurchasePrice) { this.levelPurchasePrice = levelPurchasePrice; } public Long getLevelSalesBasePrice() { return this.levelSalesBasePrice; } public void setLevelSalesBasePrice(Long levelSalesBasePrice) { this.levelSalesBasePrice = levelSalesBasePrice; } public String getLineCellIdentifier() { return this.lineCellIdentifier; } public void setLineCellIdentifier(String lineCellIdentifier) { this.lineCellIdentifier = lineCellIdentifier; } public String getLineType() { return this.lineType; } public void setLineType(String lineType) { this.lineType = lineType; } public String getLotAuditFlag() { return this.lotAuditFlag; } public void setLotAuditFlag(String lotAuditFlag) { this.lotAuditFlag = lotAuditFlag; } public Long getLotEffectiveDefaultDays() { return this.lotEffectiveDefaultDays; } public void setLotEffectiveDefaultDays(Long lotEffectiveDefaultDays) { this.lotEffectiveDefaultDays = lotEffectiveDefaultDays; } public Long getLotExpiratonDateCalculationMethod() { return this.lotExpiratonDateCalculationMethod; } public void setLotExpiratonDateCalculationMethod(Long lotExpiratonDateCalculationMethod) { this.lotExpiratonDateCalculationMethod = lotExpiratonDateCalculationMethod; } public String getLotNoPreAssignment() { return this.lotNoPreAssignment; } public void setLotNoPreAssignment(String lotNoPreAssignment) { this.lotNoPreAssignment = lotNoPreAssignment; } public String getLotStatusCodeExpanded() { return this.lotStatusCodeExpanded; } public void setLotStatusCodeExpanded(String lotStatusCodeExpanded) { this.lotStatusCodeExpanded = lotStatusCodeExpanded; } public Long getLowLevelCode() { return this.lowLevelCode; } public void setLowLevelCode(Long lowLevelCode) { this.lowLevelCode = lowLevelCode; } public Long getMakeBuyCode() { return this.makeBuyCode; } public void setMakeBuyCode(Long makeBuyCode) { this.makeBuyCode = makeBuyCode; } public String getMarginMaintenancePercentage() { return this.marginMaintenancePercentage; } public void setMarginMaintenancePercentage(String marginMaintenancePercentage) { this.marginMaintenancePercentage = marginMaintenancePercentage; } public String getMaterialStatus() { return this.materialStatus; } public void setMaterialStatus(String materialStatus) { this.materialStatus = materialStatus; } public String getMatrixControlled() { return this.matrixControlled; } public void setMatrixControlled(String matrixControlled) { this.matrixControlled = matrixControlled; } public String getMaximumCumulativeThreshold() { return this.maximumCumulativeThreshold; } public void setMaximumCumulativeThreshold(String maximumCumulativeThreshold) { this.maximumCumulativeThreshold = maximumCumulativeThreshold; } public String getMaximumOperationalThreshold() { return this.maximumOperationalThreshold; } public void setMaximumOperationalThreshold(String maximumOperationalThreshold) { this.maximumOperationalThreshold = maximumOperationalThreshold; } public Long getMessageTimeFenceDays() { return this.messageTimeFenceDays; } public void setMessageTimeFenceDays(Long messageTimeFenceDays) { this.messageTimeFenceDays = messageTimeFenceDays; } public String getMethodConfiguratorCosting() { return this.methodConfiguratorCosting; } public void setMethodConfiguratorCosting(String methodConfiguratorCosting) { this.methodConfiguratorCosting = methodConfiguratorCosting; } public String getMinimumCumulativeThreshold() { return this.minimumCumulativeThreshold; } public void setMinimumCumulativeThreshold(String minimumCumulativeThreshold) { this.minimumCumulativeThreshold = minimumCumulativeThreshold; } public String getMinimumOperationalThreshold() { return this.minimumOperationalThreshold; } public void setMinimumOperationalThreshold(String minimumOperationalThreshold) { this.minimumOperationalThreshold = minimumOperationalThreshold; } public Long getModifiedBySystemUserId() { return this.modifiedBySystemUserId; } public void setModifiedBySystemUserId(Long modifiedBySystemUserId) { this.modifiedBySystemUserId = modifiedBySystemUserId; } public String getModifiedValues() { return this.modifiedValues; } public void setModifiedValues(String modifiedValues) { this.modifiedValues = modifiedValues; } public Long getMPSMRPTimeFence4() { return this.MPSMRPTimeFence4; } public void setMPSMRPTimeFence4(Long MPSMRPTimeFence4) { this.MPSMRPTimeFence4 = MPSMRPTimeFence4; } public String getOperationalThresholdUnitofMeasure() { return this.operationalThresholdUnitofMeasure; } public void setOperationalThresholdUnitofMeasure(String operationalThresholdUnitofMeasure) { this.operationalThresholdUnitofMeasure = operationalThresholdUnitofMeasure; } public Long getOrderPolicyCode() { return this.orderPolicyCode; } public void setOrderPolicyCode(Long orderPolicyCode) { this.orderPolicyCode = orderPolicyCode; } public String getOrderWith() { return this.orderWith; } public void setOrderWith(String orderWith) { this.orderWith = orderWith; } public String getPercentMargin() { return this.percentMargin; } public void setPercentMargin(String percentMargin) { this.percentMargin = percentMargin; } public Long getPlannerNo() { return this.plannerNo; } public void setPlannerNo(Long plannerNo) { this.plannerNo = plannerNo; } public Long getPlanningCode() { return this.planningCode; } public void setPlanningCode(Long planningCode) { this.planningCode = planningCode; } public Long getPlanningTimeFenceDays() { return this.planningTimeFenceDays; } public void setPlanningTimeFenceDays(Long planningTimeFenceDays) { this.planningTimeFenceDays = planningTimeFenceDays; } public String getPlanningTimeFenceRule() { return this.planningTimeFenceRule; } public void setPlanningTimeFenceRule(String planningTimeFenceRule) { this.planningTimeFenceRule = planningTimeFenceRule; } public String getPotencyControl() { return this.potencyControl; } public void setPotencyControl(String potencyControl) { this.potencyControl = potencyControl; } public String getPrintMessage() { return this.printMessage; } public void setPrintMessage(String printMessage) { this.printMessage = printMessage; } public String getPriorityOneAlertLevel() { return this.priorityOneAlertLevel; } public void setPriorityOneAlertLevel(String priorityOneAlertLevel) { this.priorityOneAlertLevel = priorityOneAlertLevel; } public String getPriorityTwoAlertLevel() { return this.priorityTwoAlertLevel; } public void setPriorityTwoAlertLevel(String priorityTwoAlertLevel) { this.priorityTwoAlertLevel = priorityTwoAlertLevel; } public String getProductionNoControlled() { return this.productionNoControlled; } public void setProductionNoControlled(String productionNoControlled) { this.productionNoControlled = productionNoControlled; } public Long getPurchasingEffectiveDays() { return this.purchasingEffectiveDays; } public void setPurchasingEffectiveDays(Long purchasingEffectiveDays) { this.purchasingEffectiveDays = purchasingEffectiveDays; } public Long getQuantityAccountingCost() { return this.quantityAccountingCost; } public void setQuantityAccountingCost(Long quantityAccountingCost) { this.quantityAccountingCost = quantityAccountingCost; } public Long getQuantityMfgLeadtime() { return this.quantityMfgLeadtime; } public void setQuantityMfgLeadtime(Long quantityMfgLeadtime) { this.quantityMfgLeadtime = quantityMfgLeadtime; } public String getRestrictWorkOrderLotAssignment() { return this.restrictWorkOrderLotAssignment; } public void setRestrictWorkOrderLotAssignment(String restrictWorkOrderLotAssignment) { this.restrictWorkOrderLotAssignment = restrictWorkOrderLotAssignment; } public Long getRoundtoWholeNo() { return this.roundtoWholeNo; } public void setRoundtoWholeNo(Long roundtoWholeNo) { this.roundtoWholeNo = roundtoWholeNo; } public Long getSafetyLeadtime() { return this.safetyLeadtime; } public void setSafetyLeadtime(Long safetyLeadtime) { this.safetyLeadtime = safetyLeadtime; } public String getSegment1() { return this.segment1; } public void setSegment1(String segment1) { this.segment1 = segment1; } public String getSegment10() { return this.segment10; } public void setSegment10(String segment10) { this.segment10 = segment10; } public String getSegment2() { return this.segment2; } public void setSegment2(String segment2) { this.segment2 = segment2; } public String getSegment3() { return this.segment3; } public void setSegment3(String segment3) { this.segment3 = segment3; } public String getSegment4() { return this.segment4; } public void setSegment4(String segment4) { this.segment4 = segment4; } public String getSegment5() { return this.segment5; } public void setSegment5(String segment5) { this.segment5 = segment5; } public String getSegment6() { return this.segment6; } public void setSegment6(String segment6) { this.segment6 = segment6; } public String getSegment7() { return this.segment7; } public void setSegment7(String segment7) { this.segment7 = segment7; } public String getSegment8() { return this.segment8; } public void setSegment8(String segment8) { this.segment8 = segment8; } public String getSegment9() { return this.segment9; } public void setSegment9(String segment9) { this.segment9 = segment9; } public String getSellableItem() { return this.sellableItem; } public void setSellableItem(String sellableItem) { this.sellableItem = sellableItem; } public Long getSellByDefaultDays() { return this.sellByDefaultDays; } public void setSellByDefaultDays(Long sellByDefaultDays) { this.sellByDefaultDays = sellByDefaultDays; } public Long getShipmentLeadtimeOffset() { return this.shipmentLeadtimeOffset; } public void setShipmentLeadtimeOffset(Long shipmentLeadtimeOffset) { this.shipmentLeadtimeOffset = shipmentLeadtimeOffset; } public String getSpecialLotFormat() { return this.specialLotFormat; } public void setSpecialLotFormat(String specialLotFormat) { this.specialLotFormat = specialLotFormat; } public String getStandardGrade() { return this.standardGrade; } public void setStandardGrade(String standardGrade) { this.standardGrade = standardGrade; } public String getStandardPotency() { return this.standardPotency; } public void setStandardPotency(String standardPotency) { this.standardPotency = standardPotency; } public String getStandardUnitofMeasureConversion() { return this.standardUnitofMeasureConversion; } public void setStandardUnitofMeasureConversion(String standardUnitofMeasureConversion) { this.standardUnitofMeasureConversion = standardUnitofMeasureConversion; } public String getStockingType() { return this.stockingType; } public void setStockingType(String stockingType) { this.stockingType = stockingType; } public Long getSystemUserId() { return this.systemUserId; } public void setSystemUserId(Long systemUserId) { this.systemUserId = systemUserId; } public String getTemplate() { return this.template; } public void setTemplate(String template) { this.template = template; } public String getThruGrade() { return this.thruGrade; } public void setThruGrade(String thruGrade) { this.thruGrade = thruGrade; } public String getThruPotency() { return this.thruPotency; } public void setThruPotency(String thruPotency) { this.thruPotency = thruPotency; } public String getTotalProductCycleTime() { return this.totalProductCycleTime; } public void setTotalProductCycleTime(String totalProductCycleTime) { this.totalProductCycleTime = totalProductCycleTime; } public Long getUserLotDate1DefaultDays() { return this.userLotDate1DefaultDays; } public void setUserLotDate1DefaultDays(Long userLotDate1DefaultDays) { this.userLotDate1DefaultDays = userLotDate1DefaultDays; } public Long getUserLotDate2DefaultDays() { return this.userLotDate2DefaultDays; } public void setUserLotDate2DefaultDays(Long userLotDate2DefaultDays) { this.userLotDate2DefaultDays = userLotDate2DefaultDays; } public Long getUserLotDate3DefaultDays() { return this.userLotDate3DefaultDays; } public void setUserLotDate3DefaultDays(Long userLotDate3DefaultDays) { this.userLotDate3DefaultDays = userLotDate3DefaultDays; } public Long getUserLotDate4DefaultDays() { return this.userLotDate4DefaultDays; } public void setUserLotDate4DefaultDays(Long userLotDate4DefaultDays) { this.userLotDate4DefaultDays = userLotDate4DefaultDays; } public Long getUserLotDate5DefaultDays() { return this.userLotDate5DefaultDays; } public void setUserLotDate5DefaultDays(Long userLotDate5DefaultDays) { this.userLotDate5DefaultDays = userLotDate5DefaultDays; } public Long getValueOrderPolicy() { return this.valueOrderPolicy; } public void setValueOrderPolicy(Long valueOrderPolicy) { this.valueOrderPolicy = valueOrderPolicy; } public String getVendorManagedInventory() { return this.vendorManagedInventory; } public void setVendorManagedInventory(String vendorManagedInventory) { this.vendorManagedInventory = vendorManagedInventory; } }
923e485ccfd2b80a0a2dfc981c3d4008605bdffb
14,920
java
Java
tornadofaces/src/main/java/io/tornadofaces/json/JSONML.java
edvin/tornadofaces
38e176c9ce4b519ab4feefbba9667278d512e673
[ "Apache-2.0" ]
4
2015-02-25T12:31:17.000Z
2020-04-27T20:17:07.000Z
tornadofaces/src/main/java/io/tornadofaces/json/JSONML.java
edvin/tornadofaces
38e176c9ce4b519ab4feefbba9667278d512e673
[ "Apache-2.0" ]
4
2015-02-25T18:04:45.000Z
2016-06-20T08:01:21.000Z
tornadofaces/src/main/java/io/tornadofaces/json/JSONML.java
edvin/tornadofaces
38e176c9ce4b519ab4feefbba9667278d512e673
[ "Apache-2.0" ]
3
2015-02-25T12:37:40.000Z
2016-08-19T07:31:39.000Z
32.791209
94
0.507708
1,000,705
package io.tornadofaces.json; /* Copyright (c) 2008 JSON.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software shall be used for Good, not Evil. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import java.util.Iterator; /** * This provides static methods to convert an XML text into a JSONArray or * JSONObject, and to covert a JSONArray or JSONObject into an XML text using * the JsonML transform. * @author JSON.org * @version 2008-11-20 */ public class JSONML { /** * Parse XML values and store them in a JSONArray. * @param x The XMLTokener containing the source string. * @param arrayForm true if array form, false if object form. * @param ja The JSONArray that is containing the current tag or null * if we are at the outermost level. * @return A JSONArray if the value is the outermost tag, otherwise null. * @throws JSONException */ private static Object parse(XMLTokener x, boolean arrayForm, JSONArray ja) throws JSONException { String attribute; char c; String closeTag = null; int i; JSONArray newja = null; JSONObject newjo = null; Object token; String tagName = null; // Test for and skip past these forms: // <!-- ... --> // <![ ... ]]> // <! ... > // <? ... ?> while (true) { token = x.nextContent(); if (token == XML.LT) { token = x.nextToken(); if (token instanceof Character) { if (token == XML.SLASH) { // Close tag </ token = x.nextToken(); if (!(token instanceof String)) { throw new JSONException( "Expected a closing name instead of '" + token + "'."); } if (x.nextToken() != XML.GT) { throw x.syntaxError("Misshaped close tag"); } return token; } else if (token == XML.BANG) { // <! c = x.next(); if (c == '-') { if (x.next() == '-') { x.skipPast("-->"); } x.back(); } else if (c == '[') { token = x.nextToken(); if (token.equals("CDATA") && x.next() == '[') { if (ja != null) { ja.put(x.nextCDATA()); } } else { throw x.syntaxError("Expected 'CDATA['"); } } else { i = 1; do { token = x.nextMeta(); if (token == null) { throw x.syntaxError("Missing '>' after '<!'."); } else if (token == XML.LT) { i += 1; } else if (token == XML.GT) { i -= 1; } } while (i > 0); } } else if (token == XML.QUEST) { // <? x.skipPast("?>"); } else { throw x.syntaxError("Misshaped tag"); } // Open tag < } else { if (!(token instanceof String)) { throw x.syntaxError("Bad tagName '" + token + "'."); } tagName = (String)token; newja = new JSONArray(); newjo = new JSONObject(); if (arrayForm) { newja.put(tagName); if (ja != null) { ja.put(newja); } } else { newjo.put("tagName", tagName); if (ja != null) { ja.put(newjo); } } token = null; for (;;) { if (token == null) { token = x.nextToken(); } if (token == null) { throw x.syntaxError("Misshaped tag"); } if (!(token instanceof String)) { break; } // attribute = value attribute = (String)token; if (!arrayForm && (attribute == "tagName" || attribute == "childNode")) { throw x.syntaxError("Reserved attribute."); } token = x.nextToken(); if (token == XML.EQ) { token = x.nextToken(); if (!(token instanceof String)) { throw x.syntaxError("Missing value"); } newjo.accumulate(attribute, JSONObject.stringToValue((String)token)); token = null; } else { newjo.accumulate(attribute, ""); } } if (arrayForm && newjo.length() > 0) { newja.put(newjo); } // Empty tag <.../> if (token == XML.SLASH) { if (x.nextToken() != XML.GT) { throw x.syntaxError("Misshaped tag"); } if (ja == null) { if (arrayForm) { return newja; } else { return newjo; } } // Content, between <...> and </...> } else { if (token != XML.GT) { throw x.syntaxError("Misshaped tag"); } closeTag = (String)parse(x, arrayForm, newja); if (closeTag != null) { if (!closeTag.equals(tagName)) { throw x.syntaxError("Mismatched '" + tagName + "' and '" + closeTag + "'"); } tagName = null; if (!arrayForm && newja.length() > 0) { newjo.put("childNodes", newja); } if (ja == null) { if (arrayForm) { return newja; } else { return newjo; } } } } } } else { if (ja != null) { ja.put(token instanceof String ? JSONObject.stringToValue((String)token) : token); } } } } /** * Convert a well-formed (but not necessarily valid) XML string into a * JSONArray using the JsonML transform. Each XML tag is represented as * a JSONArray in which the first element is the tag name. If the tag has * attributesByClass, then the second element will be JSONObject containing the * name/value pairs. If the tag contains children, then strings and * JSONArrays will represent the child tags. * Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored. * @param string The source string. * @return A JSONArray containing the structured data from the XML string. * @throws JSONException */ public static JSONArray toJSONArray(String string) throws JSONException { return toJSONArray(new XMLTokener(string)); } /** * Convert a well-formed (but not necessarily valid) XML string into a * JSONArray using the JsonML transform. Each XML tag is represented as * a JSONArray in which the first element is the tag name. If the tag has * attributesByClass, then the second element will be JSONObject containing the * name/value pairs. If the tag contains children, then strings and * JSONArrays will represent the child content and tags. * Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored. * @param x An XMLTokener. * @return A JSONArray containing the structured data from the XML string. * @throws JSONException */ public static JSONArray toJSONArray(XMLTokener x) throws JSONException { return (JSONArray)parse(x, true, null); } /** * Convert a well-formed (but not necessarily valid) XML string into a * JSONObject using the JsonML transform. Each XML tag is represented as * a JSONObject with a "tagName" property. If the tag has attributesByClass, then * the attributesByClass will be in the JSONObject as properties. If the tag * contains children, the object will have a "childNodes" property which * will be an array of strings and JsonML JSONObjects. * Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored. * @param x An XMLTokener of the XML source text. * @return A JSONObject containing the structured data from the XML string. * @throws JSONException */ public static JSONObject toJSONObject(XMLTokener x) throws JSONException { return (JSONObject)parse(x, false, null); } /** * Convert a well-formed (but not necessarily valid) XML string into a * JSONObject using the JsonML transform. Each XML tag is represented as * a JSONObject with a "tagName" property. If the tag has attributesByClass, then * the attributesByClass will be in the JSONObject as properties. If the tag * contains children, the object will have a "childNodes" property which * will be an array of strings and JsonML JSONObjects. * Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored. * @param string The XML source text. * @return A JSONObject containing the structured data from the XML string. * @throws JSONException */ public static JSONObject toJSONObject(String string) throws JSONException { return toJSONObject(new XMLTokener(string)); } /** * Reverse the JSONML transformation, making an XML text from a JSONArray. * @param ja A JSONArray. * @return An XML string. * @throws JSONException */ public static String toString(JSONArray ja) throws JSONException { Object e; int i; JSONObject jo; String k; Iterator keys; int length; StringBuffer sb = new StringBuffer(); String tagName; String v; // Emit <tagName tagName = ja.getString(0); XML.noSpace(tagName); tagName = XML.escape(tagName); sb.append('<'); sb.append(tagName); e = ja.opt(1); if (e instanceof JSONObject) { i = 2; jo = (JSONObject)e; // Emit the attributesByClass keys = jo.keys(); while (keys.hasNext()) { k = keys.next().toString(); XML.noSpace(k); v = jo.optString(k); if (v != null) { sb.append(' '); sb.append(XML.escape(k)); sb.append('='); sb.append('"'); sb.append(XML.escape(v)); sb.append('"'); } } } else { i = 1; } //Emit content in body length = ja.length(); if (i >= length) { sb.append('/'); sb.append('>'); } else { sb.append('>'); do { e = ja.get(i); i += 1; if (e != null) { if (e instanceof String) { sb.append(XML.escape(e.toString())); } else if (e instanceof JSONObject) { sb.append(toString((JSONObject)e)); } else if (e instanceof JSONArray) { sb.append(toString((JSONArray)e)); } } } while (i < length); sb.append('<'); sb.append('/'); sb.append(tagName); sb.append('>'); } return sb.toString(); } /** * Reverse the JSONML transformation, making an XML text from a JSONObject. * The JSONObject must contain a "tagName" property. If it has children, * then it must have a "childNodes" property containing an array of objects. * The other properties are attributesByClass with string values. * @param jo A JSONObject. * @return An XML string. * @throws JSONException */ public static String toString(JSONObject jo) throws JSONException { StringBuffer sb = new StringBuffer(); Object e; int i; JSONArray ja; String k; Iterator keys; int len; String tagName; String v; //Emit <tagName tagName = jo.optString("tagName"); if (tagName == null) { return XML.escape(jo.toString()); } XML.noSpace(tagName); tagName = XML.escape(tagName); sb.append('<'); sb.append(tagName); //Emit the attributesByClass keys = jo.keys(); while (keys.hasNext()) { k = keys.next().toString(); if (!k.equals("tagName") && !k.equals("childNodes")) { XML.noSpace(k); v = jo.optString(k); if (v != null) { sb.append(' '); sb.append(XML.escape(k)); sb.append('='); sb.append('"'); sb.append(XML.escape(v)); sb.append('"'); } } } //Emit content in body ja = jo.optJSONArray("childNodes"); if (ja == null) { sb.append('/'); sb.append('>'); } else { sb.append('>'); len = ja.length(); for (i = 0; i < len; i += 1) { e = ja.get(i); if (e != null) { if (e instanceof String) { sb.append(XML.escape(e.toString())); } else if (e instanceof JSONObject) { sb.append(toString((JSONObject)e)); } else if (e instanceof JSONArray) { sb.append(toString((JSONArray)e)); } } } sb.append('<'); sb.append('/'); sb.append(tagName); sb.append('>'); } return sb.toString(); } }
923e48e3a2dfef8e375111a45c347f9a146f856b
216
java
Java
src/tile/WhiteTileLight_LT.java
wiresboy/Java-Game-APCS
f2471fd3230db11caf174736acb5f9678b3263c2
[ "MIT" ]
1
2015-01-24T23:22:39.000Z
2015-01-24T23:22:39.000Z
src/tile/WhiteTileLight_LT.java
wiresboy/Java-Game-APCS
f2471fd3230db11caf174736acb5f9678b3263c2
[ "MIT" ]
2
2015-03-25T15:52:11.000Z
2015-05-04T17:49:08.000Z
src/tile/WhiteTileLight_LT.java
wiresboy/Java-Game-APCS
f2471fd3230db11caf174736acb5f9678b3263c2
[ "MIT" ]
null
null
null
15.428571
60
0.75
1,000,706
package tile; import util.EnumSide; public class WhiteTileLight_LT extends WallLight { @Override public String getId(){ return "25"; } @Override public boolean isPortalable(EnumSide sides){ return true; } }
923e49bd990d32b94932da215774d46dcbcf02aa
1,121
java
Java
java/src/main/java/com/codurance/training/tasks/actions/impl/ActionCheck.java
nekitboy/task-list
547527bf5fa64ac4ae574c8e5f1a93e47f564265
[ "MIT" ]
null
null
null
java/src/main/java/com/codurance/training/tasks/actions/impl/ActionCheck.java
nekitboy/task-list
547527bf5fa64ac4ae574c8e5f1a93e47f564265
[ "MIT" ]
null
null
null
java/src/main/java/com/codurance/training/tasks/actions/impl/ActionCheck.java
nekitboy/task-list
547527bf5fa64ac4ae574c8e5f1a93e47f564265
[ "MIT" ]
null
null
null
27.341463
87
0.669045
1,000,707
package com.codurance.training.tasks.actions.impl; import com.codurance.training.tasks.Console; import com.codurance.training.tasks.Project; import com.codurance.training.tasks.Task; import com.codurance.training.tasks.actions.Action; import com.codurance.training.tasks.actions.ActionStatus; import java.util.Map; public class ActionCheck extends Action { private final boolean isDone; public ActionCheck(Console console, String command, boolean isDone) { super(console, command); this.isDone = isDone; } /** * Checks or Unchecks task * * @param projects projects pool * @param tasks tasks pool * @return status of action execution */ @Override public ActionStatus execute(Map<String, Project> projects, Map<Long, Task> tasks) { int id = Integer.parseInt(command); Task task = tasks.get((long) id); if (task != null) { task.setDone(isDone); return ActionStatus.NONE; } console.printError("Could not find a task with an ID of %d.", id); return ActionStatus.NONE; } }
923e4b03c7ed5850fc3f24e591a45f62c1fdcb39
2,505
java
Java
jvm/examples/src/main/java/pt/isel/pc/demos/li51d/synchronizers/DemoSemaphore4.java
isel-leic-pc/s2021i-li51d-li51n
10a50e00bdda7ae1ac0fef09e729840ea0f9a359
[ "Apache-2.0" ]
26
2020-10-05T13:36:51.000Z
2021-10-10T23:17:17.000Z
jvm/examples/src/main/java/pt/isel/pc/demos/li51d/synchronizers/DemoSemaphore4.java
isel-leic-pc/s2021i-li51d-li51n
10a50e00bdda7ae1ac0fef09e729840ea0f9a359
[ "Apache-2.0" ]
null
null
null
jvm/examples/src/main/java/pt/isel/pc/demos/li51d/synchronizers/DemoSemaphore4.java
isel-leic-pc/s2021i-li51d-li51n
10a50e00bdda7ae1ac0fef09e729840ea0f9a359
[ "Apache-2.0" ]
3
2020-10-19T22:55:32.000Z
2020-11-05T23:55:45.000Z
28.465909
99
0.53493
1,000,708
package pt.isel.pc.demos.li51d.synchronizers; import pt.isel.pc.utils.NodeLinkedList; import pt.isel.pc.utils.Timeouts; public class DemoSemaphore4 { static class Request { final int units; Request(int units) { this.units = units; } } private int units; private final NodeLinkedList<Request> queue = new NodeLinkedList<>(); private final Object monitor = new Object(); public DemoSemaphore4(int initialUnits) { this.units = initialUnits; } public boolean acquire(int requestedUnits, long timeoutInMs) throws InterruptedException { synchronized (monitor) { // fast-path if (queue.isEmpty() && units >= requestedUnits) { units -= requestedUnits; return true; } if (Timeouts.noWait(timeoutInMs)) { return false; } final long deadline = Timeouts.start(timeoutInMs); long remaining = Timeouts.remaining(deadline); NodeLinkedList.Node<Request> localRequest = queue.enqueue(new Request(requestedUnits)); while (true) { try { monitor.wait(remaining); } catch (InterruptedException e) { queue.remove(localRequest); notifyIfNeeded(); throw e; } if (queue.isHeadNode(localRequest) && units >= requestedUnits) { units -= requestedUnits; queue.remove(localRequest); notifyIfNeeded(); return true; } remaining = Timeouts.remaining(deadline); if (Timeouts.isTimeout(remaining)) { queue.remove(localRequest); notifyIfNeeded(); return false; } } } } public void release(int releasedUnits) { synchronized (monitor) { units += releasedUnits; notifyIfNeeded(); } } private void notifyIfNeeded() { if (queue.isNotEmpty() && units >= queue.getHeadValue().units) { monitor.notifyAll(); } } } /* units = 2 queue = [T0-request(5), T1-request(1)]( release(4) -> units = 6, notifyAll() T1 observes state and calls wait again T0 observes state queue = [T1-request(1)], units = 1 -> notifyAll() T1 observes state */
923e4b6649f954a8e4d7c308b2829fb4eef5f866
30,942
java
Java
gemfirexd/core/src/main/java/com/pivotal/gemfirexd/internal/impl/sql/execute/CreateTableConstantAction.java
xyxiaoyou/snappy-store
013ff282f888878cc99600e260ec1cde60112304
[ "Apache-2.0" ]
38
2016-01-04T01:31:40.000Z
2020-04-07T06:35:36.000Z
gemfirexd/core/src/main/java/com/pivotal/gemfirexd/internal/impl/sql/execute/CreateTableConstantAction.java
xyxiaoyou/snappy-store
013ff282f888878cc99600e260ec1cde60112304
[ "Apache-2.0" ]
261
2016-01-07T09:14:26.000Z
2019-12-05T10:15:56.000Z
gemfirexd/core/src/main/java/com/pivotal/gemfirexd/internal/impl/sql/execute/CreateTableConstantAction.java
xyxiaoyou/snappy-store
013ff282f888878cc99600e260ec1cde60112304
[ "Apache-2.0" ]
22
2016-03-09T05:47:09.000Z
2020-04-02T17:55:30.000Z
39.117573
168
0.705061
1,000,709
/* Derby - Class com.pivotal.gemfirexd.internal.impl.sql.execute.CreateTableConstantAction 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. */ /* * Changes for GemFireXD distributed data platform (some marked by "GemStone changes") * * Portions Copyright (c) 2010-2015 Pivotal Software, 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. See accompanying * LICENSE file. */ package com.pivotal.gemfirexd.internal.impl.sql.execute; import java.sql.Types; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.Properties; // GemStone changes BEGIN import com.gemstone.gemfire.cache.AttributesFactory; import com.gemstone.gemfire.cache.CustomEvictionAttributes; import com.gemstone.gemfire.cache.DataPolicy; import com.gemstone.gemfire.cache.EvictionAlgorithm; import com.gemstone.gemfire.cache.EvictionAttributes; import com.gemstone.gemfire.cache.PartitionAttributes; import com.gemstone.gemfire.cache.PartitionAttributesFactory; import com.gemstone.gemfire.cache.RegionAttributes; import com.gemstone.gemfire.internal.cache.EvictionAttributesImpl; import com.gemstone.gemfire.internal.cache.GemFireCacheImpl; import com.gemstone.gemfire.internal.cache.TXStateInterface; import com.pivotal.gemfirexd.internal.catalog.UUID; import com.pivotal.gemfirexd.internal.engine.Misc; import com.pivotal.gemfirexd.internal.engine.GfxdConstants; import com.pivotal.gemfirexd.internal.engine.access.GemFireTransaction; import com.pivotal.gemfirexd.internal.engine.access.index.GfxdIndexManager; import com.pivotal.gemfirexd.internal.engine.distributed.utils.GemFireXDUtils; import com.pivotal.gemfirexd.internal.engine.management.GfxdManagementService; import com.pivotal.gemfirexd.internal.engine.management.GfxdResourceEvent; import com.pivotal.gemfirexd.internal.engine.sql.catalog.DistributionDescriptor; import com.pivotal.gemfirexd.internal.engine.sql.catalog.ExtraTableInfo; import com.pivotal.gemfirexd.internal.engine.store.GemFireContainer; import com.pivotal.gemfirexd.internal.engine.store.GemFireStore; import com.pivotal.gemfirexd.internal.iapi.error.StandardException; import com.pivotal.gemfirexd.internal.iapi.services.io.FormatableBitSet; import com.pivotal.gemfirexd.internal.iapi.services.sanity.SanityManager; import com.pivotal.gemfirexd.internal.iapi.sql.Activation; import com.pivotal.gemfirexd.internal.iapi.sql.conn.LanguageConnectionContext; import com.pivotal.gemfirexd.internal.iapi.sql.conn.StatementContext; import com.pivotal.gemfirexd.internal.iapi.sql.depend.DependencyManager; import com.pivotal.gemfirexd.internal.iapi.sql.dictionary.ColumnDescriptor; import com.pivotal.gemfirexd.internal.iapi.sql.dictionary.ColumnDescriptorList; import com.pivotal.gemfirexd.internal.iapi.sql.dictionary.ConglomerateDescriptor; import com.pivotal.gemfirexd.internal.iapi.sql.dictionary.ConglomerateDescriptorList; import com.pivotal.gemfirexd.internal.iapi.sql.dictionary.DataDescriptorGenerator; import com.pivotal.gemfirexd.internal.iapi.sql.dictionary.DataDictionary; import com.pivotal.gemfirexd.internal.iapi.sql.dictionary.SchemaDescriptor; import com.pivotal.gemfirexd.internal.iapi.sql.dictionary.TableDescriptor; import com.pivotal.gemfirexd.internal.iapi.sql.execute.ConstantAction; import com.pivotal.gemfirexd.internal.iapi.sql.execute.ExecIndexRow; import com.pivotal.gemfirexd.internal.iapi.sql.execute.ExecRow; import com.pivotal.gemfirexd.internal.iapi.store.access.TransactionController; import com.pivotal.gemfirexd.internal.iapi.types.RowLocation; import com.pivotal.gemfirexd.internal.iapi.types.TypeId; import com.pivotal.gemfirexd.internal.impl.sql.compile.CreateTableNode; import com.pivotal.gemfirexd.internal.shared.common.reference.SQLState; // GemStone changes END /** * This class describes actions that are ALWAYS performed for a * CREATE TABLE Statement at Execution time. * */ // GemStone changes BEGIN //made public public final // GemStone changes END class CreateTableConstantAction extends DDLConstantAction { private char lockGranularity; private boolean onCommitDeleteRows; //If true, on commit delete rows else on commit preserve rows of temporary table. private boolean onRollbackDeleteRows; //If true, on rollback delete rows from temp table if it was logically modified in that UOW. true is the only supported value private String tableName; private String schemaName; private int tableType; private ColumnInfo[] columnInfo; private CreateConstraintConstantAction[] constraintActions; private Properties properties; //used only when queryExpression is not null i.e. for 'create table as select *' query private String generatedSqlTextForCTAS; /** * Make the ConstantAction for a CREATE TABLE statement. * * @param schemaName name for the schema that table lives in. * @param tableName Name of table. * @param tableType Type of table (e.g., BASE, global temporary table). * @param columnInfo Information on all the columns in the table. * (REMIND tableDescriptor ignored) * @param constraintActions CreateConstraintConstantAction[] for constraints * @param properties Optional table properties * @param lockGranularity The lock granularity. * @param onCommitDeleteRows If true, on commit delete rows else on commit preserve rows of temporary table. * @param onRollbackDeleteRows If true, on rollback, delete rows from temp tables which were logically modified. true is the only supported value * @param generatedSqlTextForCTAS If the query is of the from 'create table t1 as select * from t2' this will contain a SQL text * containing actual column info instead of the select clause */ CreateTableConstantAction( String schemaName, String tableName, int tableType, ColumnInfo[] columnInfo, CreateConstraintConstantAction[] constraintActions, Properties properties, char lockGranularity, boolean onCommitDeleteRows, boolean onRollbackDeleteRows, String generatedSqlTextForCTAS) { this.schemaName = schemaName; this.tableName = tableName; this.tableType = tableType; this.columnInfo = columnInfo; // GemStone changes BEGIN // no constraints will be executed in the loner mode if (Misc.getMemStoreBooting().isHadoopGfxdLonerMode() && constraintActions != null) { // execute only the primary key constraints. Having the primary key //constraint allows us to parse the key of an entry ArrayList<CreateConstraintConstantAction> pkConstraints = new ArrayList<CreateConstraintConstantAction>(1); for(CreateConstraintConstantAction constraint : constraintActions) { if(constraint.getConstraintType() == DataDictionary.PRIMARYKEY_CONSTRAINT) { pkConstraints.add(constraint); } } this.constraintActions = pkConstraints.toArray(new CreateConstraintConstantAction[pkConstraints.size()]); } else { this.constraintActions = constraintActions; } // GemStone changes END this.properties = properties; this.lockGranularity = lockGranularity; this.onCommitDeleteRows = onCommitDeleteRows; this.onRollbackDeleteRows = onRollbackDeleteRows; this.generatedSqlTextForCTAS = generatedSqlTextForCTAS; if (SanityManager.DEBUG) { //GemStone changes BEGIN /* original code if (tableType == TableDescriptor.BASE_TABLE_TYPE && lockGranularity != TableDescriptor.TABLE_LOCK_GRANULARITY && */ if ((tableType == TableDescriptor.BASE_TABLE_TYPE || tableType == TableDescriptor.COLUMN_TABLE_TYPE) && lockGranularity != TableDescriptor.TABLE_LOCK_GRANULARITY && //GemStone changes END lockGranularity != TableDescriptor.ROW_LOCK_GRANULARITY) { SanityManager.THROWASSERT( "Unexpected value for lockGranularity = " + lockGranularity); } if (tableType == TableDescriptor.GLOBAL_TEMPORARY_TABLE_TYPE && onRollbackDeleteRows == false) { SanityManager.THROWASSERT( "Unexpected value for onRollbackDeleteRows = " + onRollbackDeleteRows); } SanityManager.ASSERT(schemaName != null, "SchemaName is null"); } } // OBJECT METHODS public String toString() { if (tableType == TableDescriptor.GLOBAL_TEMPORARY_TABLE_TYPE) return constructToString("DECLARE GLOBAL TEMPORARY TABLE ", tableName); else return constructToString("CREATE TABLE ", tableName); } // INTERFACE METHODS /** * This is the guts of the Execution-time logic for CREATE TABLE. * * @see ConstantAction#executeConstantAction * * @exception StandardException Thrown on failure */ public void executeConstantAction( Activation activation ) throws StandardException { TableDescriptor td; UUID toid; SchemaDescriptor schemaDescriptor; ColumnDescriptor columnDescriptor; ExecRow template; LanguageConnectionContext lcc = activation.getLanguageConnectionContext(); DataDictionary dd = lcc.getDataDictionary(); DependencyManager dm = dd.getDependencyManager(); TransactionController tc = lcc.getTransactionExecute(); /* Mark the activation as being for create table */ activation.setForCreateTable(); // setup for create conglomerate call: // o create row template to tell the store what type of rows this // table holds. // o create array of collation id's to tell collation id of each // column in table. template = RowUtil.getEmptyValueRow(columnInfo.length, lcc); int[] collation_ids = new int[columnInfo.length]; for (int ix = 0; ix < columnInfo.length; ix++) { ColumnInfo col_info = columnInfo[ix]; // Get a template value for each column if (col_info.defaultValue != null) { /* If there is a default value, use it, otherwise use null */ template.setColumn(ix + 1, col_info.defaultValue); } else { template.setColumn(ix + 1, col_info.dataType.getNull()); } // get collation info for each column. collation_ids[ix] = col_info.dataType.getCollationType(); // Gemfire changes BEGIN // Do not allow CHAR(0) to get through here // (CREATE TABLE ... AS SELECT '' FROM X) causes a CHAR(0) column to be created if ((col_info.dataType.getTypeId() == TypeId.CHAR_ID) && (col_info.dataType.getMaximumWidth()==0)) { // This column has a max width of zero! Throw error. throw StandardException.newException(SQLState.LANG_INVALID_COLUMN_LENGTH, "0"); } //Gemfire changes END } // GemStone changes BEGIN if (this.properties == null) { this.properties = new Properties(); } this.properties.put(DataDictionary.MODULE, dd); // get the DistributionDescriptor final DistributionDescriptor distributionDesc = (DistributionDescriptor) this.properties.get(GfxdConstants.DISTRIBUTION_DESCRIPTOR_KEY); if (this.tableType != TableDescriptor.GLOBAL_TEMPORARY_TABLE_TYPE) { assert distributionDesc != null; dd.startWriting(lcc); } else { properties.put(GfxdConstants.PROPERTY_SCHEMA_NAME, this.schemaName); properties.put(GfxdConstants.PROPERTY_TABLE_NAME, tableName); } final boolean isHadoopLoner = Misc.getMemStoreBooting() .isHadoopGfxdLonerMode(); if (isHadoopLoner) { // remove all the region attributes and only keep the neccessary ones for the loner mode RegionAttributes<?, ?> regionAttributes = (RegionAttributes<?, ?>)properties .get(GfxdConstants.REGION_ATTRIBUTES_KEY); AttributesFactory attribFactory = new AttributesFactory(); attribFactory.setHDFSStoreName(regionAttributes.getHDFSStoreName()); // remove local persistence policy DataPolicy dp = regionAttributes.getDataPolicy(); if (dp == DataPolicy.HDFS_PERSISTENT_PARTITION) { dp = DataPolicy.HDFS_PARTITION; } attribFactory.setDataPolicy(dp); // if overflow is enabled, disable it. EvictionAttributes ea = new EvictionAttributesImpl(). setAlgorithm(EvictionAlgorithm.LRU_HEAP); attribFactory.setEvictionAttributes(ea); PartitionAttributes prAttributes = regionAttributes.getPartitionAttributes(); if(prAttributes != null) { PartitionAttributesFactory paf = new PartitionAttributesFactory(prAttributes); paf.setColocatedWith(null); attribFactory.setPartitionAttributes(paf.create()); } RegionAttributes<?, ?> updatedregionAttributes = attribFactory.create(); properties.put(GfxdConstants.REGION_ATTRIBUTES_KEY, updatedregionAttributes); } RegionAttributes<?, ?> regionAttributes = (RegionAttributes<?, ?>)properties .get(GfxdConstants.REGION_ATTRIBUTES_KEY); if (regionAttributes != null) { DataPolicy dp = regionAttributes.getDataPolicy(); if (!isHadoopLoner && dp == DataPolicy.HDFS_PARTITION && !distributionDesc.getPersistence()) { activation.addWarning(StandardException.newWarning( SQLState.HDFS_REGION_NOT_PERSISTENT, tableName)); } } // GemStone changes END /* create the conglomerate to hold the table's rows * RESOLVE - If we ever have a conglomerate creator * that lets us specify the conglomerate number then * we will need to handle it here. */ long conglomId = tc.createConglomerate( "heap", // we're requesting a heap conglomerate template.getRowArray(), // row template null, //column sort order - not required for heap collation_ids, properties, // properties tableType == TableDescriptor.GLOBAL_TEMPORARY_TABLE_TYPE ? (TransactionController.IS_TEMPORARY | TransactionController.IS_KEPT) : TransactionController.IS_DEFAULT); /* ** Inform the data dictionary that we are about to write to it. ** There are several calls to data dictionary "get" methods here ** that might be done in "read" mode in the data dictionary, but ** it seemed safer to do this whole operation in "write" mode. ** ** We tell the data dictionary we're done writing at the end of ** the transaction. */ // GemStone changes BEGIN // take DD lock before createConglomerate since former will // take table lock /* if ( tableType != TableDescriptor.GLOBAL_TEMPORARY_TABLE_TYPE ) dd.startWriting(lcc); */ // GemStone changes END SchemaDescriptor sd; if (tableType == TableDescriptor.GLOBAL_TEMPORARY_TABLE_TYPE) sd = dd.getSchemaDescriptor(schemaName, tc, true); else sd = getSchemaDescriptorForCreate(dd, activation, schemaName); // // Create a new table descriptor. // DataDescriptorGenerator ddg = dd.getDataDescriptorGenerator(); if ( tableType != TableDescriptor.GLOBAL_TEMPORARY_TABLE_TYPE ) { td = ddg.newTableDescriptor(tableName, sd, tableType, lockGranularity, TableDescriptor.DEFAULT_ROW_LEVEL_SECURITY_ENABLED); // GemStone changes BEGIN // set the DistributionDescriptor before calling dd.addDescriptor() td.setDistributionDescriptor(distributionDesc); // GemStone changes END dd.addDescriptor(td, sd, DataDictionary.SYSTABLES_CATALOG_NUM, false, tc); } else { td = ddg.newTableDescriptor(tableName, sd, tableType, onCommitDeleteRows, onRollbackDeleteRows); // GemStone changes BEGIN // set the DistributionDescriptor before calling dd.addDescriptor() td.setDistributionDescriptor(distributionDesc); // GemStone changes END td.setUUID(dd.getUUIDFactory().createUUID()); } toid = td.getUUID(); // Save the TableDescriptor off in the Activation activation.setDDLTableDescriptor(td); /* NOTE: We must write the columns out to the system * tables before any of the conglomerates, including * the heap, since we read the columns before the * conglomerates when building a TableDescriptor. * This will hopefully reduce the probability of * a deadlock involving those system tables. */ // for each column, stuff system.column int index = 1; ColumnDescriptor[] cdlArray = new ColumnDescriptor[columnInfo.length]; for (int ix = 0; ix < columnInfo.length; ix++) { UUID defaultUUID = columnInfo[ix].newDefaultUUID; /* Generate a UUID for the default, if one exists * and there is no default id yet. */ if (columnInfo[ix].defaultInfo != null && defaultUUID == null) { defaultUUID = dd.getUUIDFactory().createUUID(); } if (columnInfo[ix].autoincInc != 0)//dealing with autoinc column // GemStone changes BEGIN { // add warning for non-default increment/start since // it not implemented /* if (columnInfo[ix].hasAutoIncStart) { activation.addWarning(StandardException.newWarning( SQLState.AUTOINCREMENT_GIVEN_START_NOT_SUPPORTED, columnInfo[ix].autoincStart, td.getQualifiedName())); } */ if (columnInfo[ix].hasAutoIncInc && !columnInfo[ix].isGeneratedByDefault) { activation.addWarning(StandardException.newWarning( SQLState.AUTOINCREMENT_GIVEN_INCREMENT_NOT_SUPPORTED, columnInfo[ix].autoincInc, td.getQualifiedName())); } // GemStone changes END columnDescriptor = new ColumnDescriptor( columnInfo[ix].name, index++, columnInfo[ix].dataType, columnInfo[ix].defaultValue, columnInfo[ix].defaultInfo, td, defaultUUID, columnInfo[ix].autoincStart, columnInfo[ix].autoincInc, columnInfo[ix].autoinc_create_or_modify_Start_Increment, columnInfo[ix].isGeneratedByDefault ); // GemStone changes BEGIN } // GemStone changes END else columnDescriptor = new ColumnDescriptor( columnInfo[ix].name, index++, columnInfo[ix].dataType, columnInfo[ix].defaultValue, columnInfo[ix].defaultInfo, td, defaultUUID, columnInfo[ix].autoincStart, columnInfo[ix].autoincInc, columnInfo[ix].isGeneratedByDefault ); cdlArray[ix] = columnDescriptor; } if ( tableType != TableDescriptor.GLOBAL_TEMPORARY_TABLE_TYPE ) { dd.addDescriptorArray(cdlArray, td, DataDictionary.SYSCOLUMNS_CATALOG_NUM, false, tc); } // now add the column descriptors to the table. ColumnDescriptorList cdl = td.getColumnDescriptorList(); for (int i = 0; i < cdlArray.length; i++) cdl.add(cdlArray[i]); // // Create a conglomerate desciptor with the conglomId filled in and // add it. // // RESOLVE: Get information from the conglomerate descriptor which // was provided. // ConglomerateDescriptor cgd = //(original code) ddg.newConglomerateDescriptor(conglomId, null, false, null, false, null, toid, ddg.newConglomerateDescriptor(conglomId, schemaName+"."+tableName, false, null, false, null, toid, sd.getUUID()); if ( tableType != TableDescriptor.GLOBAL_TEMPORARY_TABLE_TYPE ) { dd.addDescriptor(cgd, sd, DataDictionary.SYSCONGLOMERATES_CATALOG_NUM, false, tc); } // add the newly added conglomerate to the table descriptor ConglomerateDescriptorList conglomList = td.getConglomerateDescriptorList(); conglomList.add(cgd); // GemStone changes BEGIN if ( tableType != TableDescriptor.GLOBAL_TEMPORARY_TABLE_TYPE ) { // resolve the column positions distributionDesc.resolveColumnPositions(td); // set extra table info into the container ExtraTableInfo.newExtraTableInfo(dd, td, lcc.getContextManager(), 1 /* schema version starts from 1 */, null, true); } boolean hasFk = false; // Gemstone changes -End /* Create any constraints */ if (constraintActions != null) { /* ** Do everything but FK constraints first, ** then FK constraints on 2nd pass. */ for (int conIndex = 0; conIndex < constraintActions.length; conIndex++) { // skip fks if (!constraintActions[conIndex].isForeignKeyConstraint()) { // GemStone changes BEGIN constraintActions[conIndex].setSkipPopulatingIndexes(true); // GemStone changes END constraintActions[conIndex].executeConstantAction(activation); } } for (int conIndex = 0; conIndex < constraintActions.length; conIndex++) { // only foreign keys if (constraintActions[conIndex].isForeignKeyConstraint()) { // GemStone changes BEGIN hasFk = true; constraintActions[conIndex].setSkipPopulatingIndexes(true); // GemStone changes END constraintActions[conIndex].executeConstantAction(activation); } } } // // The table itself can depend on the user defined types of its columns. // adjustUDTDependencies( lcc, dd, td, columnInfo, false ); if ( tableType == TableDescriptor.GLOBAL_TEMPORARY_TABLE_TYPE ) { lcc.addDeclaredGlobalTempTable(td, conglomId); } // GemStone changes BEGIN if (tableType != TableDescriptor.GLOBAL_TEMPORARY_TABLE_TYPE) { // setup the various properties of GemFireContainer; // this also sets up the GfxdIndexManager for global indexes while // local indexes are attached at commit time final GemFireTransaction tran = (GemFireTransaction)tc; final GemFireContainer container = GemFireContainer.getGemFireContainer( td, tran); final GfxdIndexManager indexManager = container.setup(td, dd, lcc, tran, hasFk, distributionDesc, activation, cdl); //defect #49367. FK constraint not supported with custom eviction for cheetah CustomEvictionAttributes customEvictionAttrs = container.getRegionAttributes().getCustomEvictionAttributes(); if (customEvictionAttrs != null && hasFk) { throw StandardException.newException(SQLState.FOREIGN_KEY_CONSTRAINT_NOT_SUPPORTED_WITH_EVICTION); } // check if this table is colocated with another final PartitionAttributes<?, ?> pattrs; final String colocatedWith; if (container.getRegion() != null && (pattrs = container.getRegion().getPartitionAttributes()) != null && (colocatedWith = pattrs.getColocatedWith()) != null && colocatedWith.length() > 0) { this.colocatedWithTable = Misc .getFullTableNameFromRegionPath(colocatedWith); } // load the local indexes after region population to avoid missing data // loaded from disk (#42308, doing that via onEvent route is difficult // since LocalRegion is not available there and we will need dummy // EntryEvents) if (GemFireXDUtils.TraceIndex) { GfxdIndexManager.traceIndex("CreateTable::executeConstantAction " + "indexManager=%s, constraintAction=%s and skipRegionInit=%s " + "for table=%s", indexManager, constraintActions, lcc.skipRegionInitialization(), td.getQualifiedName()); } if (indexManager != null && this.constraintActions != null) { if (lcc.skipRegionInitialization()) { // only lock for container GII and also refresh the index list // at commit when releasing the lock indexManager.invalidateFor(lcc); } else { boolean lockedForIndexes = false; Collection<LoadIndexData> loadData; for (CreateConstraintConstantAction action : this.constraintActions) { loadData = action.getLoadIndexData(); if (loadData != null) { for (LoadIndexData load : loadData) { if (!lockedForIndexes) { lockedForIndexes = true; // next lock for container GII and also refresh the index list // at commit when releasing the lock indexManager.invalidateFor(lcc); } load.loadIndexConglomerate(lcc, tc, td, indexManager); } loadData.clear(); } } } } // add dependency of this statement since GFXD properties like server // groups can change for a VM so its best to recompile after drop table dm.addDependency(activation.getPreparedStatement(), td, lcc .getContextManager()); // Change added in r42445 // skip these warnings on accessor (aka peer clients) if (!container.isAccessorForRegion()) { final GemFireCacheImpl cache = Misc.getGemFireCache(); for (String id : container.getRegionAttributes().getGatewaySenderIds()) { if (cache.getGatewaySender(id) == null) { StringBuilder sb = new StringBuilder(); for (com.gemstone.gemfire.cache.wan.GatewaySender s : cache .getAllGatewaySenders()) { sb.append(s.getId()).append(","); } activation.addWarning(StandardException.newWarning( SQLState.LANG_NO_LOCAL_GATEWAYSENDER_ASYNCEVENTLISTENER, new Object[] { id, container.getQualifiedTableName(), "GatewaySenders", sb.toString() }, null)); } } for (Object id : container.getRegionAttributes().getAsyncEventQueueIds()) { if (cache.getAsyncEventQueue((String)id) == null) { StringBuilder sb = new StringBuilder(); for (com.gemstone.gemfire.cache.asyncqueue.AsyncEventQueue q : cache .getAsyncEventQueues()) { sb.append(q.getId()).append(","); } activation.addWarning(StandardException.newWarning( SQLState.LANG_NO_LOCAL_GATEWAYSENDER_ASYNCEVENTLISTENER, new Object[] { id, container.getQualifiedTableName(), "AsyncEventListeners", sb.toString() }, null)); } } } // Fix for #48445 if (!container.getRegionAttributes().getGatewaySenderIds().isEmpty()) { Iterator<ColumnDescriptor> itr = td.getColumnDescriptorList() .iterator(); while (itr.hasNext()) { ColumnDescriptor cd = itr.next(); if (cd.isAutoincAlways() && (cd.getType().getJDBCTypeId() == Types.INTEGER)) { throw StandardException.newException(SQLState.LANG_AI_INVALID_TYPE_WITH_GATEWAYSENDER, cd.getColumnName()); } } } // Create Table MBean now if management is not disabled // NOTE: We can(should?) actually use the DistributionDescriptor by // passing it to handleEvent here rather than taking it later via // GemFireContainer -> ExtraTableInfo -> TableDescriptor if (container.isApplicationTable()) { GfxdManagementService.handleEvent(GfxdResourceEvent.TABLE__CREATE, new Object[] {container}); } } // GemStone changes END if (!("SYSSTAT".equalsIgnoreCase(this.schemaName) || Misc.isSnappyHiveMetaTable((this.schemaName)) || GemFireXDUtils.TraceConglom)) { SanityManager.DEBUG_PRINT( "info:" + GfxdConstants.TRACE_CONGLOM, "Created table " + td.getQualifiedName() + " with UUID: " + td.getUUID()); } if (GemFireXDUtils.TraceConglom) { SanityManager.DEBUG_PRINT(GfxdConstants.TRACE_CONGLOM, "Created table with descriptor:\n" + td); } } /** if this table is colocated with another; used during DDL replay */ private String colocatedWithTable; /** true if this table is a user created normal table */ public boolean isReplayable() { return (this.tableType == TableDescriptor.BASE_TABLE_TYPE/*GemStone changes BEGIN*/ || this.tableType == TableDescriptor.COLUMN_TABLE_TYPE/*GemStone changes END*/); } @Override public final String getSchemaName() { return this.schemaName; } @Override public final String getTableName() { return this.tableName; } public final String getColocatedWithTable() { return this.colocatedWithTable; } /** * Returns the generated SQL text passed from * {@link CreateTableNode#makeConstantAction()} in case of DDL such as * 'create table t2 as select * from t1'. The generated SQL text will * contain actual column information instead of 'select' clause. * Returns null, if the DDL does not contain select clause * <p>See {@link CreateTableNode#getSQLTextForCTAS(ColumnInfo[])} */ public String getSQLTextForCTAS() { return generatedSqlTextForCTAS; } /** * Encapsulate data to load index at commit time. */ public static final class LoadIndexData { private final CreateIndexConstantAction indexAction; private final FormatableBitSet zeroBasedBitSet; private final ExecRow[] baseRows; private final ExecIndexRow[] indexRows; private final RowLocation[] rl; public LoadIndexData(CreateIndexConstantAction indexAction, FormatableBitSet zeroBasedBitSet, ExecRow[] baseRows, ExecIndexRow[] indexRows, RowLocation[] rl) { this.indexAction = indexAction; this.zeroBasedBitSet = zeroBasedBitSet; this.baseRows = baseRows; this.indexRows = indexRows; this.rl = rl; } private final void loadIndexConglomerate(LanguageConnectionContext lcc, TransactionController tc, TableDescriptor td, GfxdIndexManager indexManager) throws StandardException { this.indexAction.loadIndexConglomerate(lcc, tc, td, indexManager, this.zeroBasedBitSet, this.baseRows, this.indexRows, this.rl, false); } } // GemStone changes END }
923e4c4ec7ec9ddc2dff37f9db33d87d206f79fd
2,362
java
Java
server/catgenome/src/main/java/com/epam/catgenome/entity/externaldb/DimEntity.java
lizaveta-vlasova/NGB
11ebd2ecb6fbe4d58a7eca2152eda03458b5767b
[ "MIT" ]
143
2016-12-08T07:57:45.000Z
2022-02-16T01:47:47.000Z
server/catgenome/src/main/java/com/epam/catgenome/entity/externaldb/DimEntity.java
lizaveta-vlasova/NGB
11ebd2ecb6fbe4d58a7eca2152eda03458b5767b
[ "MIT" ]
480
2017-02-21T12:26:43.000Z
2022-03-30T13:36:17.000Z
server/catgenome/src/main/java/com/epam/catgenome/entity/externaldb/DimEntity.java
lizaveta-vlasova/NGB
11ebd2ecb6fbe4d58a7eca2152eda03458b5767b
[ "MIT" ]
54
2016-10-28T16:13:21.000Z
2022-03-04T16:49:23.000Z
26.840909
81
0.684589
1,000,710
/* * MIT License * * Copyright (c) 2016 EPAM Systems * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.epam.catgenome.entity.externaldb; /** * <p> * Entity for control dim (pdb and uniprot start/end) * </p> */ public class DimEntity { private String compound; private String chainId; private Integer pdbStart; private Integer pdbEnd; private Integer unpStart; private Integer unpEnd; public String getCompound() { return compound; } public void setCompound(String compound) { this.compound = compound; } public String getChainId() { return chainId; } public void setChainId(String chainId) { this.chainId = chainId; } public Integer getPdbStart() { return pdbStart; } public void setPdbStart(Integer pdbStart) { this.pdbStart = pdbStart; } public Integer getPdbEnd() { return pdbEnd; } public void setPdbEnd(Integer pdbEnd) { this.pdbEnd = pdbEnd; } public Integer getUnpStart() { return unpStart; } public void setUnpStart(Integer unpStart) { this.unpStart = unpStart; } public Integer getUnpEnd() { return unpEnd; } public void setUnpEnd(Integer unpEnd) { this.unpEnd = unpEnd; } }
923e4d00bfcd7b19367d6ce40790238a7b427f5e
1,976
java
Java
nd4j/nd4j-backends/nd4j-backend-impls/nd4j-cuda/src/main/java/org/nd4j/jita/memory/MemoryProvider.java
zhangy10/deeplearning4j
9d31156ce600dee6ce4a7fac28286ebbaa211164
[ "Apache-2.0" ]
13,006
2015-02-13T18:35:31.000Z
2022-03-18T12:11:44.000Z
nd4j/nd4j-backends/nd4j-backend-impls/nd4j-cuda/src/main/java/org/nd4j/jita/memory/MemoryProvider.java
zhangy10/deeplearning4j
9d31156ce600dee6ce4a7fac28286ebbaa211164
[ "Apache-2.0" ]
5,319
2015-02-13T08:21:46.000Z
2019-06-12T14:56:50.000Z
nd4j/nd4j-backends/nd4j-backend-impls/nd4j-cuda/src/main/java/org/nd4j/jita/memory/MemoryProvider.java
zhangy10/deeplearning4j
9d31156ce600dee6ce4a7fac28286ebbaa211164
[ "Apache-2.0" ]
4,719
2015-02-13T22:48:55.000Z
2022-03-22T07:25:36.000Z
33.508475
97
0.667678
1,000,711
/******************************************************************************* * Copyright (c) 2015-2018 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ package org.nd4j.jita.memory; import org.nd4j.jita.allocator.enums.AllocationStatus; import org.nd4j.jita.allocator.impl.AllocationPoint; import org.nd4j.jita.allocator.impl.AllocationShape; import org.nd4j.jita.allocator.pointers.PointersPair; /** * This interface describes 2 basic methods to work with memory: malloc and free. * * @author dycjh@example.com */ public interface MemoryProvider { /** * This method provides PointersPair to memory chunk specified by AllocationShape * * @param shape shape of desired memory chunk * @param point target AllocationPoint structure * @param location either HOST or DEVICE * @return */ PointersPair malloc(AllocationShape shape, AllocationPoint point, AllocationStatus location); /** * This method frees specific chunk of memory, described by AllocationPoint passed in * * @param point */ void free(AllocationPoint point); /** * This method checks specified device for specified amount of memory * * @param deviceId * @param requiredMemory * @return */ boolean pingDeviceForFreeMemory(Integer deviceId, long requiredMemory); void purgeCache(); }
923e4ed4dc84eff361b689fdfec44e387f70ae74
3,228
java
Java
src/main/java/io/github/flibio/winterwonderland/ToggleCommand.java
Flibio/WinterWonderland
d805f10abea4f80af85008b26a974da3de707cf5
[ "MIT" ]
1
2015-11-20T03:56:17.000Z
2015-11-20T03:56:17.000Z
src/main/java/io/github/flibio/winterwonderland/ToggleCommand.java
Flibio/WinterWonderland
d805f10abea4f80af85008b26a974da3de707cf5
[ "MIT" ]
1
2015-12-17T03:26:56.000Z
2015-12-20T14:28:12.000Z
src/main/java/io/github/flibio/winterwonderland/ToggleCommand.java
Flibio/WinterWonderland
d805f10abea4f80af85008b26a974da3de707cf5
[ "MIT" ]
null
null
null
45.464789
148
0.718092
1,000,712
/* * This file is part of WinterWonderland, licensed under the MIT License (MIT). * * Copyright (c) 2015 - 2016 Flibio * Copyright (c) Contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package io.github.flibio.winterwonderland; import io.github.flibio.winterwonderland.FileManager.FileType; import org.spongepowered.api.command.CommandException; import org.spongepowered.api.command.CommandResult; import org.spongepowered.api.command.CommandSource; import org.spongepowered.api.command.args.CommandContext; import org.spongepowered.api.command.spec.CommandExecutor; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.format.TextColors; public class ToggleCommand implements CommandExecutor { private Text prefix = Text.of(TextColors.AQUA, "Winter Wonderland: ", TextColors.WHITE); @Override public CommandResult execute(CommandSource source, CommandContext args) throws CommandException { if (!(source instanceof Player)) { source.sendMessage(Text.builder("You must be a player to use /winter!").color(TextColors.RED).build()); return CommandResult.success(); } Player player = (Player) source; String uuid = player.getUniqueId().toString(); if (Main.access.playerData.getNode(uuid) == null) { source.sendMessage(Text.builder("An error has occurred!").color(TextColors.RED).build()); return CommandResult.success(); } else { boolean value = Main.access.playerData.getNode(uuid).getBoolean(); Main.access.playerData.getNode(uuid).setValue(!value); Main.access.fileManager.saveFile(FileType.DATA, Main.access.playerData); if (value) { player.sendMessage(prefix.toBuilder().append(Text.of(TextColors.RED, "Turned off ", TextColors.WHITE, "snow placement!")).build()); } else { player.sendMessage(prefix.toBuilder().append(Text.of(TextColors.GREEN, "Turned on ", TextColors.WHITE, "snow placement!")).build()); } } return CommandResult.success(); } }
923e4faee3f5c71bb7537a0259ddf0c1f5733484
239
java
Java
effective-java/src/main/java/chapter4/item13/package2/Class2.java
wuxinshui/noob
d4ac9fcc911964ee8b41d6bd4daceb86f892f6be
[ "Apache-2.0" ]
4
2017-06-16T03:35:19.000Z
2019-06-13T15:31:55.000Z
effective-java/src/main/java/chapter4/item13/package2/Class2.java
wuxinshui/noob
d4ac9fcc911964ee8b41d6bd4daceb86f892f6be
[ "Apache-2.0" ]
null
null
null
effective-java/src/main/java/chapter4/item13/package2/Class2.java
wuxinshui/noob
d4ac9fcc911964ee8b41d6bd4daceb86f892f6be
[ "Apache-2.0" ]
1
2017-11-11T09:04:51.000Z
2017-11-11T09:04:51.000Z
18.384615
44
0.644351
1,000,713
package chapter4.item13.package2; /** * Created by Administrator on 2017/3/8. */ public class Class2 { public static void main(String[] args) { //默认访问级别:包级私有的。只能在同一个包内访问,不能跨包访问 //Class1 class1=new Class1(); } }
923e509a9d7e9e597722d1d4622ca19c66df129b
2,148
java
Java
src/main/java/com/jzy/model/vo/Speed.java
ShiverZm/Assistant-Online-Working-System
be2e39dde4b5fafc6180f5e50a214dca050b19b4
[ "MIT" ]
4
2020-03-29T17:40:34.000Z
2021-12-10T01:33:47.000Z
src/main/java/com/jzy/model/vo/Speed.java
ShiverZm/Assistant-Online-Working-System
be2e39dde4b5fafc6180f5e50a214dca050b19b4
[ "MIT" ]
null
null
null
src/main/java/com/jzy/model/vo/Speed.java
ShiverZm/Assistant-Online-Working-System
be2e39dde4b5fafc6180f5e50a214dca050b19b4
[ "MIT" ]
4
2020-05-27T14:34:15.000Z
2021-12-12T08:40:09.000Z
22.610526
73
0.5554
1,000,714
package com.jzy.model.vo; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; /** * @author JinZhiyun * @version 1.0 * @ClassName Speed * @description 数据处理速度的封装 * @date 2019/12/2 16:01 **/ @EqualsAndHashCode(callSuper = true) @ToString(callSuper = true) @Data public class Speed extends Time { private static final long serialVersionUID = -6511341868845659672L; protected static String COUNT_UNIT = "条"; protected static String SEPARATOR = "/"; protected static String PER_HOUR = COUNT_UNIT + SEPARATOR + HOUR; protected static String PER_MINUTE = COUNT_UNIT + SEPARATOR + MINUTE; protected static String PER_SECOND = COUNT_UNIT + SEPARATOR + SECOND; /** * 处理的数据总数 */ protected long count; /** * 每秒执行多少条 */ private long speedPerSecond; /** * 每分钟执行多少条 */ private long speedPerMinute; /** * 每小时执行多少条 */ private long speedPerHour; /** * xx条/分、xx条/秒、.... */ private String parsedSpeed; @Override public String parseSpeed() { super.parseTime(); if (count > 0) { if (totalHour > 0) { speedPerHour = (long) (count / totalHour); } if (totalMinute > 0) { speedPerMinute = (long) (count / totalMinute); } if (totalSecond > 0) { speedPerSecond = (long) (count / totalSecond); } if (totalHour >= 2) { //小时级别耗时,大于等于两小时,输出xx条/小时 parsedSpeed = speedPerHour + PER_HOUR; return parsedSpeed; } if (totalMinute >= 2) { //分钟级别耗时,大于等于两分钟,输出xx条/分钟 parsedSpeed = speedPerMinute + PER_MINUTE; return parsedSpeed; } //秒级别耗时,大于等于两秒,输出xx条/秒 parsedSpeed = speedPerSecond + PER_SECOND; } else { parsedSpeed = 0 + PER_SECOND; } return parsedSpeed; } public Speed(long count, long milliSecond) { super(milliSecond); this.count = count; } }
923e510b2db569c2225e5205ca0bb5197cbdf1c2
426
java
Java
tapestry-json/src/main/java/org/apache/tapestry5/json/exceptions/JSONArrayIndexOutOfBoundsException.java
shisheng-1/tapestry-5
28ac1aebdf09d27611d111c702266b12e10b074c
[ "Apache-2.0" ]
72
2015-02-23T16:30:56.000Z
2022-03-30T03:42:27.000Z
tapestry-json/src/main/java/org/apache/tapestry5/json/exceptions/JSONArrayIndexOutOfBoundsException.java
shisheng-1/tapestry-5
28ac1aebdf09d27611d111c702266b12e10b074c
[ "Apache-2.0" ]
7
2016-03-03T10:21:45.000Z
2021-12-02T20:03:17.000Z
tapestry-json/src/main/java/org/apache/tapestry5/json/exceptions/JSONArrayIndexOutOfBoundsException.java
shisheng-1/tapestry-5
28ac1aebdf09d27611d111c702266b12e10b074c
[ "Apache-2.0" ]
87
2015-02-20T09:17:50.000Z
2022-01-31T12:11:24.000Z
19.363636
86
0.706573
1,000,715
package org.apache.tapestry5.json.exceptions; public class JSONArrayIndexOutOfBoundsException extends ArrayIndexOutOfBoundsException { private static final long serialVersionUID = -53336156278974940L; private final int index; public JSONArrayIndexOutOfBoundsException(int index) { super(index); this.index = index; } public int getIndex() { return this.index; } }
923e52164aefdc79fdfe0e934919404bb370cc1b
1,528
java
Java
magiccube-engine/src/main/java/com/missfresh/magiccube/engine/ISmallToolEngine.java
Eillot/MagicCube
4f387a8d643cfb69f15bf2c985102c66cb636c88
[ "Apache-2.0" ]
null
null
null
magiccube-engine/src/main/java/com/missfresh/magiccube/engine/ISmallToolEngine.java
Eillot/MagicCube
4f387a8d643cfb69f15bf2c985102c66cb636c88
[ "Apache-2.0" ]
null
null
null
magiccube-engine/src/main/java/com/missfresh/magiccube/engine/ISmallToolEngine.java
Eillot/MagicCube
4f387a8d643cfb69f15bf2c985102c66cb636c88
[ "Apache-2.0" ]
null
null
null
19.589744
175
0.603403
1,000,716
package com.simon.magiccube.engine; import com.simon.magiccube.dao.domain.SmallTool; import java.util.List; /** * @version: java version 1.8+ * @Author : simon * @Explain : * @contact: * @Time : 2019/12/28 3:10 PM * @File : ISmallToolEngine * @Software: IntelliJ IDEA 2018.1.8 */ public interface ISmallToolEngine { /** * 通过ID查询单条数据 * * @param id 主键 * @return 实例对象 */ SmallTool SmallToolQueryById(Integer id); /** * 通过实体作为筛选条件查询 * * @return 对象列表 */ List<SmallTool> SmallToolQueryAll(SmallTool smallTool); /** * 新增数据 * * @return 影响行数 */ int SmallToolInsert(SmallTool smallTool); /** * 修改数据 * * @return 影响行数 */ int SmallToolUpdate(SmallTool smallTool); /** * 通过主键删除数据 * * @param id 主键 * @return 影响行数 */ int SmallToolDeleteById(Integer id); /** * 小工具执行http请求 * @param requestType * @param interUrl * @param parameter * @return */ Object excuteHttpSmallTool(String requestType,String runEnv, String interUrl, String parameter); /** * 小工具执行dubbo请求 * @param interUrl * @param method * @param zkAddress * @param zkVertion * @param paramTypes * @param params * @param applicationName * @return */ Object excuteDubboSmallTool(String interUrl, String method, String zkAddress,String group, String zkVertion, String[] paramTypes, Object[] params, String applicationName); }
923e52c9b80fa1d25b44c2ed370b7284e4c8f6eb
7,283
java
Java
XYZReader/src/main/java/com/example/xyzreader/ui/ArticleDetailFragment.java
scyanh/XYZReader
c561abeab4f4e65649b3744c84b1d8b8fece6777
[ "Apache-2.0" ]
1
2017-08-18T03:21:23.000Z
2017-08-18T03:21:23.000Z
XYZReader/src/main/java/com/example/xyzreader/ui/ArticleDetailFragment.java
scyanh/XYZReader
c561abeab4f4e65649b3744c84b1d8b8fece6777
[ "Apache-2.0" ]
null
null
null
XYZReader/src/main/java/com/example/xyzreader/ui/ArticleDetailFragment.java
scyanh/XYZReader
c561abeab4f4e65649b3744c84b1d8b8fece6777
[ "Apache-2.0" ]
null
null
null
36.054455
108
0.610875
1,000,717
package com.example.xyzreader.ui; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.app.ShareCompat; import android.support.v4.content.Loader; import android.text.Html; import android.text.format.DateUtils; import android.text.method.LinkMovementMethod; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.android.volley.VolleyError; import com.android.volley.toolbox.ImageLoader; import com.example.xyzreader.R; import com.example.xyzreader.data.ArticleLoader; /** * A fragment representing a single Article detail screen. This fragment is * either contained in a {@link ArticleListActivity} in two-pane mode (on * tablets) or a {@link ArticleDetailActivity} on handsets. */ public class ArticleDetailFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> { private static final String TAG = "ArticleDetailFragment"; public static final String ARG_ITEM_ID = "item_id"; private static final float PARALLAX_FACTOR = 1.25f; private Cursor mCursor; private long mItemId; private View mRootView; private ImageView mPhotoView; /** * Mandatory empty constructor for the fragment manager to instantiate the * fragment (e.g. upon screen orientation changes). */ public ArticleDetailFragment() { } public static ArticleDetailFragment newInstance(long itemId) { Bundle arguments = new Bundle(); arguments.putLong(ARG_ITEM_ID, itemId); ArticleDetailFragment fragment = new ArticleDetailFragment(); fragment.setArguments(arguments); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments().containsKey(ARG_ITEM_ID)) { mItemId = getArguments().getLong(ARG_ITEM_ID); } setHasOptionsMenu(true); } public ArticleDetailActivity getActivityCast() { return (ArticleDetailActivity) getActivity(); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // In support library r8, calling initLoader for a fragment in a FragmentPagerAdapter in // the fragment's onCreate may cause the same LoaderManager to be dealt to multiple // fragments because their mIndex is -1 (haven't been added to the activity yet). Thus, // we do this in onActivityCreated. getLoaderManager().initLoader(0, null, this); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = inflater.inflate(R.layout.fragment_article_detail, container, false); mPhotoView = (ImageView) mRootView.findViewById(R.id.photo); mRootView.findViewById(R.id.share_fab).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startActivity(Intent.createChooser(ShareCompat.IntentBuilder.from(getActivity()) .setType("text/plain") .setText("Some sample text") .getIntent(), getString(R.string.action_share))); } }); bindViews(); return mRootView; } static float progress(float v, float min, float max) { return constrain((v - min) / (max - min), 0, 1); } static float constrain(float val, float min, float max) { if (val < min) { return min; } else if (val > max) { return max; } else { return val; } } private void bindViews() { if (mRootView == null) { return; } TextView titleView = (TextView) mRootView.findViewById(R.id.article_title); TextView bylineView = (TextView) mRootView.findViewById(R.id.article_byline); bylineView.setMovementMethod(new LinkMovementMethod()); TextView bodyView = (TextView) mRootView.findViewById(R.id.article_body); if (mCursor != null) { mRootView.setAlpha(0); mRootView.setVisibility(View.VISIBLE); mRootView.animate().alpha(1); titleView.setText(mCursor.getString(ArticleLoader.Query.TITLE)); bylineView.setText(Html.fromHtml( DateUtils.getRelativeTimeSpanString( mCursor.getLong(ArticleLoader.Query.PUBLISHED_DATE), System.currentTimeMillis(), DateUtils.HOUR_IN_MILLIS, DateUtils.FORMAT_ABBREV_ALL).toString() + " by <font color='#ffffff'>" + mCursor.getString(ArticleLoader.Query.AUTHOR) + "</font>")); bodyView.setText(Html.fromHtml(mCursor.getString(ArticleLoader.Query.BODY))); ImageLoaderHelper.getInstance(getActivity()).getImageLoader() .get(mCursor.getString(ArticleLoader.Query.PHOTO_URL), new ImageLoader.ImageListener() { @Override public void onResponse(ImageLoader.ImageContainer imageContainer, boolean b) { Bitmap bitmap = imageContainer.getBitmap(); if (bitmap != null) { //Palette p = Palette.generate(bitmap, 12); //mMutedColor = p.getDarkMutedColor(0xFF333333); mPhotoView.setImageBitmap(imageContainer.getBitmap()); /*mRootView.findViewById(R.id.meta_bar) .setBackgroundColor(mMutedColor); updateStatusBar();*/ } } @Override public void onErrorResponse(VolleyError volleyError) { } }); } else { mRootView.setVisibility(View.GONE); titleView.setText("N/A"); bylineView.setText("N/A" ); bodyView.setText("N/A"); } } @Override public Loader<Cursor> onCreateLoader(int i, Bundle bundle) { return ArticleLoader.newInstanceForItemId(getActivity(), mItemId); } @Override public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) { if (!isAdded()) { if (cursor != null) { cursor.close(); } return; } mCursor = cursor; if (mCursor != null && !mCursor.moveToFirst()) { Log.e(TAG, "Error reading item detail cursor"); mCursor.close(); mCursor = null; } bindViews(); } @Override public void onLoaderReset(Loader<Cursor> cursorLoader) { mCursor = null; bindViews(); } }
923e53b371b7a2fc9b8ac3555fbade9c7e9c67b4
10,470
java
Java
box2d/src/main/net/dermetfan/gdx/physics/box2d/PositionController.java
abysl/libgdx-utils
964a238db6171634ba00a9796ef05234500fb80c
[ "Apache-2.0" ]
7
2019-09-23T17:06:00.000Z
2021-08-20T11:55:52.000Z
box2d/src/main/net/dermetfan/gdx/physics/box2d/PositionController.java
abysl/libgdx-utils
964a238db6171634ba00a9796ef05234500fb80c
[ "Apache-2.0" ]
1
2020-09-11T11:37:30.000Z
2020-09-12T08:22:04.000Z
box2d/src/main/net/dermetfan/gdx/physics/box2d/PositionController.java
abysl/libgdx-utils
964a238db6171634ba00a9796ef05234500fb80c
[ "Apache-2.0" ]
2
2020-12-08T12:53:48.000Z
2020-12-09T10:07:31.000Z
32.230769
170
0.704057
1,000,718
/** Copyright 2015 Robin Stumm (efpyi@example.com, http://dermetfan.net) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.dermetfan.gdx.physics.box2d; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.World; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.Pools; import net.dermetfan.utils.Function; /** moves a body to a position using forces * @author dermetfan * @since 0.11.1 */ public abstract class PositionController { /** shared instance for internal use */ protected static final Vector2 vec2 = new Vector2(); /** returns the argument if it is a PositionController */ public static final Function<Object, PositionController> defaultUserDataAccessor = new Function<Object, PositionController>() { @Override public PositionController apply(Object arg) { return arg instanceof PositionController ? (PositionController) arg : null; } }; /** the Function used to extract a PositionController out of a Body's user data */ private static Function<Object, PositionController> userDataAccessor = defaultUserDataAccessor; /** Calls {@link #applyForceToCenter(Body, boolean) applyForceToCenter} for every Body with a PositionController in its user data. * The PositionController is accessed using the {@link #userDataAccessor}. * @param world the world which Bodies to iterate over */ public static void applyForceToCenter(World world, boolean wake) { @SuppressWarnings("unchecked") Array<Body> bodies = Pools.obtain(Array.class); world.getBodies(bodies); for(Body body : bodies) { PositionController controller = userDataAccessor.apply(body.getUserData()); if(controller != null) controller.applyForceToCenter(body, wake); } bodies.clear(); Pools.free(bodies); } /** @param point the world point at which the force should be applied * @return the force to apply at the given point */ public abstract Vector2 calculateForce(Body body, Vector2 point); /** @return the force to apply at the center of mass of the Body */ public abstract Vector2 calculateForceToCenter(Body body); /** applies the necessary force at the given point * @param point the world point at which to apply the force * @return the force applied, calculated by {@link #calculateForce(Body, Vector2)} */ public Vector2 applyForce(Body body, Vector2 point, boolean wake) { Vector2 force = calculateForce(body, point); body.applyForce(force, point, wake); return force; } /** applies the necessary force at the center of mass of the Body * @return the force applied, calculated by {@link #calculateForceToCenter(Body)} */ public Vector2 applyForceToCenter(Body body, boolean wake) { Vector2 force = calculateForceToCenter(body); body.applyForceToCenter(force, wake); return force; } // getters and setters /** @return the {@link #userDataAccessor} */ public static Function<Object, PositionController> getUserDataAccessor() { return userDataAccessor; } /** @param userDataAccessor The {@link #userDataAccessor} to set. If null, {@link #defaultUserDataAccessor} is set. */ public static void setUserDataAccessor(Function<Object, PositionController> userDataAccessor) { PositionController.userDataAccessor = userDataAccessor != null ? userDataAccessor : defaultUserDataAccessor; } /** the proportional control loop component * @author dermetfan * @since 0.11.1 */ public static class P extends PositionController { /** @param gain the gain * @param pos the current position * @param dest the setpoint * @return gain * error */ public static float calculateForce(float gain, float pos, float dest) { return gain * (dest - pos); } /** @see #calculateForce(float, float, float) * @return {@link #vec2} */ public static Vector2 calculateForce(float gainX, float gainY, float x, float y, float destX, float destY) { return vec2.set(calculateForce(gainX, x, destX), calculateForce(gainY, y, destY)); } /** @see #calculateForce(float, float, float, float, float, float) */ public static Vector2 calculateForce(Vector2 gain, Vector2 pos, Vector2 dest) { return calculateForce(gain.x, gain.y, pos.x, pos.y, dest.x, dest.y); } /** the gain */ private Vector2 gain; /** the setpoint */ private Vector2 destination; /** @param gain the gain on both axes * @param destination the {@link #destination} */ public P(float gain, Vector2 destination) { this(new Vector2(gain, gain), destination); } /** @param gain the {@link #gain} * @param destination the {@link #destination} */ public P(Vector2 gain, Vector2 destination) { this.gain = gain; this.destination = destination; } @Override public Vector2 calculateForce(Body body, Vector2 point) { return calculateForce(gain, point, destination); } @Override public Vector2 calculateForceToCenter(Body body) { return calculateForce(gain, body.getWorldCenter(), destination); } // getters and setters /** @return the {@link #gain} */ public Vector2 getGain() { return gain; } /** @param gain the {@link #gain} to set */ public void setGain(Vector2 gain) { this.gain = gain; } /** @return the {@link #destination} */ public Vector2 getDestination() { return destination; } /** @param destination the {@link #destination} to set */ public void setDestination(Vector2 destination) { this.destination = destination; } } /** the derivative control loop component * @author dermetfan * @since 0.11.1 */ public static class D extends PositionController { /** @param gain the gain * @param vel the velocity * @return {@code gain * -vel} */ public static float calculateForce(float gain, float vel) { return gain * -vel; } /** @see #calculateForce(float, float) * @return {@link #vec2} */ public static Vector2 calculateForce(float gainX, float gainY, float velX, float velY) { return vec2.set(calculateForce(gainX, velX), calculateForce(gainY, velY)); } /** @see #calculateForce(float, float, float, float) */ public static Vector2 calculateForce(Vector2 gain, Vector2 vel) { return calculateForce(gain.x, gain.y, vel.x, vel.y); } /** the gain */ private Vector2 gain; /** @param gain the gain on both axes */ public D(float gain) { this(new Vector2(gain, gain)); } /** @param gain the {@link #gain} */ public D(Vector2 gain) { this.gain = gain; } @Override public Vector2 calculateForce(Body body, Vector2 point) { return calculateForce(gain, body.getLinearVelocityFromWorldPoint(point)); } @Override public Vector2 calculateForceToCenter(Body body) { return calculateForce(gain, body.getLinearVelocity()); } // getters and setters /** @return the {@link #gain} */ public Vector2 getGain() { return gain; } /** @param gain the {@link #gain} to set*/ public void setGain(Vector2 gain) { this.gain = gain; } } /** a proportional-derivative controller * @author dermetfan * @since 0.11.1 * @see P * @see D */ public static class PD extends PositionController { /** @see P#calculateForce(float, float, float) * @see D#calculateForce(float, float) */ public static float calculateForce(float gainP, float gainD, float pos, float dest, float vel) { return P.calculateForce(gainP, pos, dest) + D.calculateForce(gainD, vel); } /** @see #calculateForce(float, float, float, float, float) */ public static Vector2 calculateForce(float gainPX, float gainPY, float gainDX, float gainDY, float posX, float posY, float destX, float destY, float velX, float velY) { return vec2.set(calculateForce(gainPX, gainDX, posX, destX, velX), calculateForce(gainPY, gainDY, posY, destY, velY)); } /** @see #calculateForce(float, float, float, float, float, float, float, float, float, float) */ public static Vector2 calculateForce(Vector2 gainP, Vector2 gainD, Vector2 pos, Vector2 dest, Vector2 vel) { return calculateForce(gainP.x, gainP.y, gainD.x, gainD.y, pos.x, pos.y, dest.x, dest.y, vel.x, vel.y); } /** the gain of the proportional component */ private Vector2 gainP; /** the gain of the derivative component */ private Vector2 gainD; /** the setpoint */ private Vector2 destination; /** @param gainP the proportional gain on both axes * @param gainD the derivative gain on both axes * @param destination the {@link #destination} */ public PD(float gainP, float gainD, Vector2 destination) { this(new Vector2(gainP, gainP), new Vector2(gainD, gainD), destination); } /** @param gainP the {@link #gainP} * @param gainD the {@link #gainD} * @param destination the {@link #destination} */ public PD(Vector2 gainP, Vector2 gainD, Vector2 destination) { this.gainP = gainP; this.gainD = gainD; this.destination = destination; } @Override public Vector2 calculateForce(Body body, Vector2 point) { return calculateForce(gainP, gainD, point, destination, body.getLinearVelocityFromWorldPoint(point)); } @Override public Vector2 calculateForceToCenter(Body body) { return calculateForce(gainP, gainD, body.getWorldCenter(), destination, body.getLinearVelocity()); } // getters and setters /** @return the {@link #gainP} */ public Vector2 getGainP() { return gainP; } /** @param gainP the {@link #gainP} to set */ public void setGainP(Vector2 gainP) { this.gainP = gainP; } /** @return the {@link #gainD} */ public Vector2 getGainD() { return gainD; } /** @param gainD the {@link #gainD} to set */ public void setGainD(Vector2 gainD) { this.gainD = gainD; } /** @return the {@link #destination} */ public Vector2 getDestination() { return destination; } /** @param destination the {@link #destination} to set */ public void setDestination(Vector2 destination) { this.destination = destination; } } }
923e53db69ae8db6d61b97236da93089baebf243
144
java
Java
protocol/protocol-reader-runtime/src/org/jetbrains/jsonProtocol/Request.java
develar/chromedevtools
432da766271737a0a78dd16534f1dca39bb52a09
[ "BSD-3-Clause" ]
2
2016-08-24T21:52:50.000Z
2017-04-07T17:57:18.000Z
protocol/protocol-reader-runtime/src/org/jetbrains/jsonProtocol/Request.java
develar/chromedevtools
432da766271737a0a78dd16534f1dca39bb52a09
[ "BSD-3-Clause" ]
null
null
null
protocol/protocol-reader-runtime/src/org/jetbrains/jsonProtocol/Request.java
develar/chromedevtools
432da766271737a0a78dd16534f1dca39bb52a09
[ "BSD-3-Clause" ]
null
null
null
14.4
35
0.743056
1,000,719
package org.jetbrains.jsonProtocol; public interface Request { CharSequence toJson(); String getMethodName(); void finalize(int id); }
923e55445c91ffa53974c4913f79c0a78a643662
2,970
java
Java
net/src/main/java/com/zrzhen/zetty/net/ExecutorUtil.java
Socrates2017/Zetty
213fba3b3bc4965c3f51bacf444bfbd8aa674188
[ "Apache-2.0" ]
5
2019-11-24T07:19:18.000Z
2021-01-11T07:56:43.000Z
net/src/main/java/com/zrzhen/zetty/net/ExecutorUtil.java
Socrates2017/zetty
213fba3b3bc4965c3f51bacf444bfbd8aa674188
[ "Apache-2.0" ]
8
2020-03-04T23:51:41.000Z
2021-12-09T21:57:40.000Z
net/src/main/java/com/zrzhen/zetty/net/ExecutorUtil.java
Socrates2017/zetty
213fba3b3bc4965c3f51bacf444bfbd8aa674188
[ "Apache-2.0" ]
2
2020-05-21T05:50:14.000Z
2021-01-18T05:23:42.000Z
33
88
0.488215
1,000,720
package com.zrzhen.zetty.net; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; /** * @author chenanlian * 线程池工具类 */ public class ExecutorUtil { private static final Logger log = LoggerFactory.getLogger(ExecutorUtil.class); public static ThreadPoolExecutor channelExcutor = new ThreadPoolExecutor( Runtime.getRuntime().availableProcessors() + 1, Runtime.getRuntime().availableProcessors() * 2 + 1, 1, TimeUnit.MINUTES, new ArrayBlockingQueue(1000), new ThreadFactory() { private AtomicInteger count = new AtomicInteger(0); @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); String threadName = "channelExcutor-" + count.addAndGet(1); t.setName(threadName); return t; } }, new RejectedExecutionHandler() { @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { log.warn("触发日志线程池拒绝策略"); try { executor.getQueue().put(r); /* * 如果任务量不大,可以用无界队列,如果任务量非常大,要用有界队列,防止OOM * 如果任务量很大,还要求每个任务都处理成功,要对提交的任务进行阻塞提交,重写拒绝机制,改为阻塞提交。保证不抛弃一个任务 */ } catch (InterruptedException e) { log.error(e.getMessage(), e); } } } ); public static ThreadPoolExecutor processorExcutor = new ThreadPoolExecutor( 10, 200, 1, TimeUnit.MINUTES, new ArrayBlockingQueue(100), new ThreadFactory() { private AtomicInteger count = new AtomicInteger(0); @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); String threadName = "processorExcutor-" + count.addAndGet(1); t.setName(threadName); return t; } }, new RejectedExecutionHandler() { @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { log.warn("触发日志线程池拒绝策略"); try { executor.getQueue().put(r); /* * 如果任务量不大,可以用无界队列,如果任务量非常大,要用有界队列,防止OOM * 如果任务量很大,还要求每个任务都处理成功,要对提交的任务进行阻塞提交,重写拒绝机制,改为阻塞提交。保证不抛弃一个任务 */ } catch (InterruptedException e) { log.error(e.getMessage(), e); } } } ); }
923e55a7f8893c851f8580f57d0057312fec15c4
6,884
java
Java
spring-context-support/src/main/java/org/springframework/cache/caffeine/CaffeineCacheManager.java
yangfancoming/spring-5.1.x
db4c2cbcaf8ba58f43463eff865d46bdbd742064
[ "Apache-2.0" ]
null
null
null
spring-context-support/src/main/java/org/springframework/cache/caffeine/CaffeineCacheManager.java
yangfancoming/spring-5.1.x
db4c2cbcaf8ba58f43463eff865d46bdbd742064
[ "Apache-2.0" ]
null
null
null
spring-context-support/src/main/java/org/springframework/cache/caffeine/CaffeineCacheManager.java
yangfancoming/spring-5.1.x
db4c2cbcaf8ba58f43463eff865d46bdbd742064
[ "Apache-2.0" ]
1
2021-06-05T07:25:05.000Z
2021-06-05T07:25:05.000Z
31.290909
108
0.743899
1,000,721
package org.springframework.cache.caffeine; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import com.github.benmanes.caffeine.cache.CacheLoader; import com.github.benmanes.caffeine.cache.Caffeine; import com.github.benmanes.caffeine.cache.CaffeineSpec; import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.ObjectUtils; /** * {@link CacheManager} implementation that lazily builds {@link CaffeineCache} * instances for each {@link #getCache} request. Also supports a 'static' mode * where the set of cache names is pre-defined through {@link #setCacheNames}, * with no dynamic creation of further cache regions at runtime. * * xmlBeanDefinitionReaderThe configuration of the underlying cache can be fine-tuned through a * {@link Caffeine} builder or {@link CaffeineSpec}, passed into this * CacheManager through {@link #setCaffeine}/{@link #setCaffeineSpec}. * A {@link CaffeineSpec}-compliant expression value can also be applied * via the {@link #setCacheSpecification "cacheSpecification"} bean property. * * xmlBeanDefinitionReaderRequires Caffeine 2.1 or higher. * * @author Ben Manes * @author Stephane Nicoll * @since 4.3 * @see CaffeineCache */ public class CaffeineCacheManager implements CacheManager { private final ConcurrentMap<String, Cache> cacheMap = new ConcurrentHashMap<>(16); private boolean dynamic = true; private Caffeine<Object, Object> cacheBuilder = Caffeine.newBuilder(); @Nullable private CacheLoader<Object, Object> cacheLoader; private boolean allowNullValues = true; /** * Construct a dynamic CaffeineCacheManager, * lazily creating cache instances as they are being requested. */ public CaffeineCacheManager() { } /** * Construct a static CaffeineCacheManager, * managing caches for the specified cache names only. */ public CaffeineCacheManager(String... cacheNames) { setCacheNames(Arrays.asList(cacheNames)); } /** * Specify the set of cache names for this CacheManager's 'static' mode. * xmlBeanDefinitionReaderThe number of caches and their names will be fixed after a call to this method, * with no creation of further cache regions at runtime. * xmlBeanDefinitionReaderCalling this with a {@code null} collection argument resets the * mode to 'dynamic', allowing for further creation of caches again. */ public void setCacheNames(@Nullable Collection<String> cacheNames) { if (cacheNames != null) { for (String name : cacheNames) { this.cacheMap.put(name, createCaffeineCache(name)); } this.dynamic = false; } else { this.dynamic = true; } } /** * Set the Caffeine to use for building each individual * {@link CaffeineCache} instance. * @see #createNativeCaffeineCache * @see com.github.benmanes.caffeine.cache.Caffeine#build() */ public void setCaffeine(Caffeine<Object, Object> caffeine) { Assert.notNull(caffeine, "Caffeine must not be null"); doSetCaffeine(caffeine); } /** * Set the {@link CaffeineSpec} to use for building each individual * {@link CaffeineCache} instance. * @see #createNativeCaffeineCache * @see com.github.benmanes.caffeine.cache.Caffeine#from(CaffeineSpec) */ public void setCaffeineSpec(CaffeineSpec caffeineSpec) { doSetCaffeine(Caffeine.from(caffeineSpec)); } /** * Set the Caffeine cache specification String to use for building each * individual {@link CaffeineCache} instance. The given value needs to * comply with Caffeine's {@link CaffeineSpec} (see its javadoc). * @see #createNativeCaffeineCache * @see com.github.benmanes.caffeine.cache.Caffeine#from(String) */ public void setCacheSpecification(String cacheSpecification) { doSetCaffeine(Caffeine.from(cacheSpecification)); } /** * Set the Caffeine CacheLoader to use for building each individual * {@link CaffeineCache} instance, turning it into a LoadingCache. * @see #createNativeCaffeineCache * @see com.github.benmanes.caffeine.cache.Caffeine#build(CacheLoader) * @see com.github.benmanes.caffeine.cache.LoadingCache */ public void setCacheLoader(CacheLoader<Object, Object> cacheLoader) { if (!ObjectUtils.nullSafeEquals(this.cacheLoader, cacheLoader)) { this.cacheLoader = cacheLoader; refreshKnownCaches(); } } /** * Specify whether to accept and convert {@code null} values for all caches * in this cache manager. * xmlBeanDefinitionReaderDefault is "true", despite Caffeine itself not supporting {@code null} values. * An internal holder object will be used to store user-level {@code null}s. */ public void setAllowNullValues(boolean allowNullValues) { if (this.allowNullValues != allowNullValues) { this.allowNullValues = allowNullValues; refreshKnownCaches(); } } /** * Return whether this cache manager accepts and converts {@code null} values * for all of its caches. */ public boolean isAllowNullValues() { return this.allowNullValues; } @Override public Collection<String> getCacheNames() { return Collections.unmodifiableSet(this.cacheMap.keySet()); } @Override @Nullable public Cache getCache(String name) { Cache cache = this.cacheMap.get(name); if (cache == null && this.dynamic) { synchronized (this.cacheMap) { cache = this.cacheMap.get(name); if (cache == null) { cache = createCaffeineCache(name); this.cacheMap.put(name, cache); } } } return cache; } /** * Create a new CaffeineCache instance for the specified cache name. * @param name the name of the cache * @return the Spring CaffeineCache adapter (or a decorator thereof) */ protected Cache createCaffeineCache(String name) { return new CaffeineCache(name, createNativeCaffeineCache(name), isAllowNullValues()); } /** * Create a native Caffeine Cache instance for the specified cache name. * @param name the name of the cache * @return the native Caffeine Cache instance */ protected com.github.benmanes.caffeine.cache.Cache<Object, Object> createNativeCaffeineCache(String name) { if (this.cacheLoader != null) { return this.cacheBuilder.build(this.cacheLoader); } else { return this.cacheBuilder.build(); } } private void doSetCaffeine(Caffeine<Object, Object> cacheBuilder) { if (!ObjectUtils.nullSafeEquals(this.cacheBuilder, cacheBuilder)) { this.cacheBuilder = cacheBuilder; refreshKnownCaches(); } } /** * Create the known caches again with the current state of this manager. */ private void refreshKnownCaches() { for (Map.Entry<String, Cache> entry : this.cacheMap.entrySet()) { entry.setValue(createCaffeineCache(entry.getKey())); } } }
923e5614e3e1a7b13a180a8395aaaa2c085ec8e4
1,276
java
Java
quicksort.java
amritbhat786/DocIT
0e19ac35c4ebbf083c238748de9fd3db4b023d56
[ "MIT" ]
1
2017-09-30T08:48:32.000Z
2017-09-30T08:48:32.000Z
quicksort.java
amritbhat786/DocIT
0e19ac35c4ebbf083c238748de9fd3db4b023d56
[ "MIT" ]
null
null
null
quicksort.java
amritbhat786/DocIT
0e19ac35c4ebbf083c238748de9fd3db4b023d56
[ "MIT" ]
null
null
null
24.538462
88
0.484326
1,000,722
package sortingalogorithm; /** * * InsertionSort. * * @version 1.0 2017/05/24 * @author ALEX-CHUN-YU * */ public class QuickSort { /** * @param data number sequence * @param start left * @param end right * @return return sort number sequence */ public static int[] getQucikSort(final int start, final int end, final int[] data) { //length limit if (start >= end) { return data; } int left = start, right = end - 1, pivot = data[end]; //Don't allow equal ! while (right > left) { while (data[left] < pivot && right > left) { left++; } while (data[right] > pivot && right > left) { right--; } //Swap int template = data[left]; data[left] = data[right]; data[right] = template; } if (data[left] >= pivot) { //Swap int template = data[left]; data[left] = data[end]; data[end] = template; } else { //Last Number left++; } //Recursive (pivot left and right) getQucikSort(start, left - 1, data); getQucikSort(left + 1, end, data); return data; } }
923e56b17164afdf8b3380dd5997ecf6842b861a
1,458
java
Java
ql/src/java/org/apache/hadoop/hive/ql/io/orc/RecordReader.java
manbuyun/hive
cdb1052e24ca493c6486fef3dd8956dde61be834
[ "Apache-2.0" ]
4,140
2015-01-07T11:57:35.000Z
2022-03-31T06:26:22.000Z
ql/src/java/org/apache/hadoop/hive/ql/io/orc/RecordReader.java
manbuyun/hive
cdb1052e24ca493c6486fef3dd8956dde61be834
[ "Apache-2.0" ]
1,779
2015-05-27T04:32:42.000Z
2022-03-31T18:53:19.000Z
ql/src/java/org/apache/hadoop/hive/ql/io/orc/RecordReader.java
manbuyun/hive
cdb1052e24ca493c6486fef3dd8956dde61be834
[ "Apache-2.0" ]
3,958
2015-01-01T15:14:49.000Z
2022-03-30T21:08:32.000Z
33.906977
75
0.733882
1,000,723
/* * 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.hive.ql.io.orc; import java.io.IOException; import org.apache.hadoop.hive.ql.exec.vector.VectorizedRowBatch; /** * A row-by-row iterator for ORC files. */ public interface RecordReader extends org.apache.orc.RecordReader { /** * Does the reader have more rows available. * @return true if there are more rows * @throws java.io.IOException */ boolean hasNext() throws IOException; /** * Read the next row. * @param previous a row object that can be reused by the reader * @return the row that was read * @throws java.io.IOException */ Object next(Object previous) throws IOException; }
923e5709c9841d51c04dcdacdbeb0cbce37d9920
2,440
java
Java
src/main/java/com/github/joschi/jadconfig/repositories/EnvironmentRepository.java
joschi/JadConf
00260619b2066b59a48726c1854ba5e9a466fc3e
[ "Apache-2.0" ]
13
2015-02-08T22:11:49.000Z
2020-11-04T03:26:00.000Z
src/main/java/com/github/joschi/jadconfig/repositories/EnvironmentRepository.java
joschi/JadConf
00260619b2066b59a48726c1854ba5e9a466fc3e
[ "Apache-2.0" ]
33
2015-06-04T08:23:26.000Z
2021-03-01T04:01:43.000Z
src/main/java/com/github/joschi/jadconfig/repositories/EnvironmentRepository.java
joschi/JadConf
00260619b2066b59a48726c1854ba5e9a466fc3e
[ "Apache-2.0" ]
5
2015-11-17T13:00:39.000Z
2020-12-16T08:14:29.000Z
28.045977
91
0.647951
1,000,724
package com.github.joschi.jadconfig.repositories; import com.github.joschi.jadconfig.Repository; import com.github.joschi.jadconfig.RepositoryException; /** * {@link Repository} class providing access to environment variables. * <p/> * All keys are being looked up in upper case unless deactivated with the appropriate * constructor ({@link EnvironmentRepository#EnvironmentRepository(boolean)}. * <p/> * A prefix for all key lookups can be defined with {@link #EnvironmentRepository(String)}. * The default prefix is empty. * * @see System#getenv() * @see System#getenv(String) */ public class EnvironmentRepository implements Repository { private final String prefix; private final boolean upperCase; /** * Creates a new instance of {@link EnvironmentRepository} with the default settings, * i. e. no prefix and keys looked up in upper case. */ public EnvironmentRepository() { this(""); } /** * Creates a new instance of {@link EnvironmentRepository} with the given prefix. * * @param prefix The prefix used for key lookups, e. g. {@code "MY_APP_"}. */ public EnvironmentRepository(final String prefix) { this(prefix, true); } /** * Creates a new instance of {@link EnvironmentRepository} with an empty prefix. * * @param upperCase Whether keys should be looked up in upper case. */ public EnvironmentRepository(final boolean upperCase) { this("", upperCase); } /** * Creates a new instance of {@link EnvironmentRepository} with the given prefix. * * @param prefix The prefix used for key lookups, e. g. {@code "MY_APP_"}. * @param upperCase Whether keys should be looked up in upper case. */ public EnvironmentRepository(final String prefix, boolean upperCase) { this.prefix = prefix; this.upperCase = upperCase; } @Override public void open() throws RepositoryException { // NOP } @Override public String read(final String name) { final String envName; if (upperCase) { envName = (prefix + name).toUpperCase(); } else { envName = prefix + name; } return System.getenv(envName); } @Override public void close() throws RepositoryException { // NOP } public int size() { return System.getenv().size(); } }
923e5751e81034ee0e28f6d92de15b81808ed676
235
java
Java
test/CallMethod.java
daikimiura/jarvis
f62635913e80f8c8c0dd12374662e723c991d8e2
[ "MIT" ]
5
2019-12-14T16:44:38.000Z
2021-06-24T05:56:14.000Z
test/CallMethod.java
daikimiura/merah
f62635913e80f8c8c0dd12374662e723c991d8e2
[ "MIT" ]
null
null
null
test/CallMethod.java
daikimiura/merah
f62635913e80f8c8c0dd12374662e723c991d8e2
[ "MIT" ]
null
null
null
19.583333
42
0.629787
1,000,725
class CallMethod { public static void main(String[] args){ sub(1, "hogehoge"); } public static void sub(int a, String b){ System.out.println("sub() is called"); System.out.println(a); System.out.println(b); } }
923e5779741eda189abebd1621e49702c7071c43
3,775
java
Java
lib/src/main/java/com/futurewei/alcor/common/db/ignite/MockIgniteServer.java
haboy52581/alcor
9f32721615f2e7bf52773d3da5eb9f1205e8bbe1
[ "Apache-2.0" ]
null
null
null
lib/src/main/java/com/futurewei/alcor/common/db/ignite/MockIgniteServer.java
haboy52581/alcor
9f32721615f2e7bf52773d3da5eb9f1205e8bbe1
[ "Apache-2.0" ]
1
2020-05-27T17:50:09.000Z
2020-05-27T17:50:09.000Z
lib/src/main/java/com/futurewei/alcor/common/db/ignite/MockIgniteServer.java
haboy52581/alcor
9f32721615f2e7bf52773d3da5eb9f1205e8bbe1
[ "Apache-2.0" ]
1
2020-05-26T16:33:32.000Z
2020-05-26T16:33:32.000Z
35.613208
132
0.661457
1,000,726
/* Copyright 2019 The Alcor Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.futurewei.alcor.common.db.ignite; import org.apache.ignite.Ignite; import org.apache.ignite.IgniteCache; import org.apache.ignite.IgniteException; import org.apache.ignite.Ignition; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.internal.IgniteKernal; import org.apache.ignite.internal.processors.cache.IgniteCacheProxyImpl; import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi; import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder; import org.junit.AfterClass; import org.junit.BeforeClass; import java.util.Collections; import java.util.Optional; import java.util.function.Consumer; public class MockIgniteServer { private static final String LOCAL_ADDRESS = "127.0.0.1"; private static final int LISTEN_PORT = 11801; private static final int LISTEN_PORT_RANGE = 10; private static Ignite igniteServer = null; @BeforeClass public static void init() { if (igniteServer == null) { try { org.apache.ignite.configuration.IgniteConfiguration cfg = new org.apache.ignite.configuration.IgniteConfiguration(); // make this ignite server isolated TcpDiscoveryVmIpFinder ipFinder = new TcpDiscoveryVmIpFinder(); ipFinder.setAddresses(Collections.singletonList(LOCAL_ADDRESS + ":" + LISTEN_PORT + ".." + (LISTEN_PORT+LISTEN_PORT_RANGE))); TcpDiscoverySpi tcpDiscoverySpi = new TcpDiscoverySpi(); tcpDiscoverySpi.setIpFinder(ipFinder); tcpDiscoverySpi.setLocalAddress(LOCAL_ADDRESS); tcpDiscoverySpi.setLocalPort(LISTEN_PORT); tcpDiscoverySpi.setLocalPortRange(LISTEN_PORT_RANGE); cfg.setDiscoverySpi(tcpDiscoverySpi); // cfg.setPeerClassLoadingEnabled(true); igniteServer = Ignition.start(cfg); //Properties properties = System.getProperties(); //properties.setProperty("ignite.port", String.valueOf(ListenPort)); } catch (IgniteException e) { throw new RuntimeException(e); } } } @AfterClass public static void close() { // if(igniteServer != null){ // igniteServer.close(); // igniteServer = null; // } } public static Ignite getIgnite(){ if(igniteServer == null){ // if no need create a real ignite server, we return a mock Ignite client return new IgniteNodeClientMock(); } return igniteServer; } /** * mock a {@link Ignite} class for unit test * */ private static class IgniteNodeClientMock extends IgniteKernal { public IgniteNodeClientMock() { } @Override public <K, V> IgniteCache<K, V> getOrCreateCache(String cacheName) { return new IgniteCacheProxyImpl(); } @Override public <K, V> IgniteCache<K, V> getOrCreateCache(CacheConfiguration<K, V> var1) { return new IgniteCacheProxyImpl(); } } }
923e57cd9cc61f6b780bdcd1ac65a5fc8809abba
3,445
java
Java
mymall-product/src/main/java/zwf/mymall/product/controller/PmsBrandController.java
zwf-leaves/mymall
a20f643e28a7b3e908004df4e639e04c21c8ec9a
[ "Apache-2.0" ]
null
null
null
mymall-product/src/main/java/zwf/mymall/product/controller/PmsBrandController.java
zwf-leaves/mymall
a20f643e28a7b3e908004df4e639e04c21c8ec9a
[ "Apache-2.0" ]
null
null
null
mymall-product/src/main/java/zwf/mymall/product/controller/PmsBrandController.java
zwf-leaves/mymall
a20f643e28a7b3e908004df4e639e04c21c8ec9a
[ "Apache-2.0" ]
null
null
null
29.470085
125
0.672274
1,000,727
package zwf.mymall.product.controller; import java.util.Arrays; import java.util.Map; //import org.apache.shiro.authz.annotation.RequiresPermissions;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import zwf.mymall.common.valid.AddGroup; import zwf.mymall.common.valid.UpdataStatus; import zwf.mymall.common.valid.UpdateGroup; import zwf.mymall.product.entity.PmsBrandEntity; import zwf.mymall.product.service.PmsBrandService; import zwf.mymall.common.utils.PageUtils; import zwf.mymall.common.utils.R; import javax.validation.Valid; /** * 品牌 * * @author zwf * @email kenaa@example.com * @date 2020-12-08 11:16:02 */ @RestController @RequestMapping("product/brand") public class PmsBrandController { @Autowired private PmsBrandService pmsBrandService; /** * 列表 */ @RequestMapping("/list") //@RequiresPermissions("product:pmsbrand:list") public R list(@RequestParam Map<String, Object> params) { PageUtils page = pmsBrandService.queryPage(params); return R.ok().put("page", page); } /** * 信息 */ @RequestMapping("/info/{brandId}") //@RequiresPermissions("product:pmsbrand:info") public R info(@PathVariable("brandId") Long brandId) { PmsBrandEntity pmsBrand = pmsBrandService.getById(brandId); return R.ok().put("data", pmsBrand); } /** * 保存 */ @RequestMapping("/save") //@RequiresPermissions("product:pmsbrand:save") public R save(@Validated(value = {AddGroup.class}) @RequestBody PmsBrandEntity pmsBrand/*BindingResult result*/) { // Map<String,String> map=new HashMap(); // if(result.hasErrors()){ // List<FieldError> fieldErrors = result.getFieldErrors(); // fieldErrors.forEach((item)->{ // map.put(item.getField(),item.getDefaultMessage()); // }); // return R.error(400,"提交de数据不合法").put("data",map); // }else { // pmsBrandService.save(pmsBrand); // System.out.println(pmsBrand + "oooo"); // return R.ok(); // } pmsBrandService.save(pmsBrand); return R.ok(); } /** *修改状态 */ @RequestMapping("/update/status") //@RequiresPermissions("product:pmsbrand:update") public R updateStatus(@Validated(value = {UpdataStatus.class}) @RequestBody PmsBrandEntity pmsBrand) { pmsBrandService.updateById(pmsBrand); return R.ok(); } /** * 修改 */ @RequestMapping("/update") //@RequiresPermissions("product:pmsbrand:update") public R update(@Validated(value = {UpdateGroup.class}) @RequestBody PmsBrandEntity pmsBrand) { pmsBrandService.updateDetail(pmsBrand); return R.ok(); } /** * 删除 */ @RequestMapping("/delete") //@RequiresPermissions("product:pmsbrand:delete") public R delete(@RequestBody Long[] brandIds) { pmsBrandService.removeByIds(Arrays.asList(brandIds)); return R.ok(); } }
923e5bef7272484a640314945f5ce433d9957b65
1,965
java
Java
CatEye/src/com/zhc/test/Test.java
z1820418897/ssm
87bb2633973baf4cde404f96bfdafaa8bb732adb
[ "Apache-2.0" ]
null
null
null
CatEye/src/com/zhc/test/Test.java
z1820418897/ssm
87bb2633973baf4cde404f96bfdafaa8bb732adb
[ "Apache-2.0" ]
null
null
null
CatEye/src/com/zhc/test/Test.java
z1820418897/ssm
87bb2633973baf4cde404f96bfdafaa8bb732adb
[ "Apache-2.0" ]
null
null
null
33.87931
123
0.506361
1,000,728
package com.zhc.test; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Test { public static void main(String[] args) { int count = 2000; CyclicBarrier cyclicBarrier = new CyclicBarrier(count); ExecutorService executorService = Executors.newFixedThreadPool(count); System.out.println("开始创建线程"); for (int i = 0; i < count; i++) executorService.execute(new Test().new Task(cyclicBarrier)); System.out.println("创建完毕 执行"); executorService.shutdown(); /*while (!executorService.isTerminated()) { try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } */ } public class Task implements Runnable { private CyclicBarrier cyclicBarrier; public Task(CyclicBarrier cyclicBarrier) { this.cyclicBarrier = cyclicBarrier; } @Override public void run() { try { // 等待所有任务准备就绪 cyclicBarrier.await(); // 测试内容 Map<String,Integer> map=new HashMap(); map.put("limit", 10); map.put("page", 1); long a= System.currentTimeMillis(); String s = SendFromMsg.sendHttpPostRequest("http://10.10.2.176/CatEye/cateye/data", new String[]{},map); System.out.println("---"+System.currentTimeMillis()+"***"+((Long)System.currentTimeMillis()-a)+s); } catch (Exception e) { e.printStackTrace(); } } } }
923e5bf13ad3e9ee4bd22df47f9941b0f9e5759d
547
java
Java
src/main/java/im/bci/jb3/wro/WroConfiguration.java
gartcimore/jb3
ec48e9b11f2b23bae04165b3bf3011c565365ab0
[ "MIT" ]
null
null
null
src/main/java/im/bci/jb3/wro/WroConfiguration.java
gartcimore/jb3
ec48e9b11f2b23bae04165b3bf3011c565365ab0
[ "MIT" ]
null
null
null
src/main/java/im/bci/jb3/wro/WroConfiguration.java
gartcimore/jb3
ec48e9b11f2b23bae04165b3bf3011c565365ab0
[ "MIT" ]
null
null
null
27.35
77
0.844607
1,000,729
package im.bci.jb3.wro; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WroConfiguration implements WebMvcConfigurer { @Autowired private WroInterceptor interceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(interceptor); } }
923e5c08415c6d7d7a372d58f02e4a89c340894a
1,031
java
Java
src/interfaces/ILuceneQuerySearcher.java
MacHundt/e4
e0b0c2e5bc471e54e96e2c1c91d3d5ac11ce4b4d
[ "Apache-2.0" ]
null
null
null
src/interfaces/ILuceneQuerySearcher.java
MacHundt/e4
e0b0c2e5bc471e54e96e2c1c91d3d5ac11ce4b4d
[ "Apache-2.0" ]
null
null
null
src/interfaces/ILuceneQuerySearcher.java
MacHundt/e4
e0b0c2e5bc471e54e96e2c1c91d3d5ac11ce4b4d
[ "Apache-2.0" ]
null
null
null
24.547619
84
0.737148
1,000,730
package interfaces; import java.util.ArrayList; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; public interface ILuceneQuerySearcher { ILuceneQuerySearcher instance = null; public void initQuerySearcher(IndexSearcher searcher, Analyzer analyzer); /** * This method performs a lucene <code>query</code> * and retrieves the <code>topX</code> results as an array of <code>ScoreDoc</code> * @param query * @param int - topX * @return */ public ScoreDoc[] searchTop(Query query, int topX); /** * This method performs a lucene <code>query</code> * and retrieves all results as an array of <code>ScoreDoc</code> * @param query * @return ScoreDoc[] */ public ScoreDoc[] searchAll(Query query); public ScoreDoc[] fuseQuery(Query query1, Query query2); public ScoreDoc[] fuseQueries(ArrayList<Query> queries); public void changeAnalyzer(Analyzer newAnalyzer); }
923e5dc2ae7b445dfccd871560025cb9e5c89f0f
1,620
java
Java
src/test/java/com/darian/darianlucenefile/other/RegularExpressionsUtilsTest_1.java
Darian1996/darian-lucene-file
731d56688e759622b17b56a1c67441d260f27d75
[ "Apache-2.0" ]
2
2020-06-01T02:52:27.000Z
2021-01-25T05:48:10.000Z
src/test/java/com/darian/darianlucenefile/other/RegularExpressionsUtilsTest_1.java
Darian1996/darian-lucene-file
731d56688e759622b17b56a1c67441d260f27d75
[ "Apache-2.0" ]
null
null
null
src/test/java/com/darian/darianlucenefile/other/RegularExpressionsUtilsTest_1.java
Darian1996/darian-lucene-file
731d56688e759622b17b56a1c67441d260f27d75
[ "Apache-2.0" ]
1
2021-07-23T02:59:35.000Z
2021-07-23T02:59:35.000Z
40.5
138
0.614815
1,000,731
package com.darian.darianlucenefile.other; import org.junit.Test; import java.util.regex.Matcher; import java.util.regex.Pattern; /*** * * * @author <a href="mailto:envkt@example.com">Darian</a> * @date 2020/5/10 14:31 */ public class RegularExpressionsUtilsTest_1 { @Test public void test() { System.out.println("sdfa dsoaifo sojafiasdf \n dsafasdfa" .replaceAll("\\s+", " ")); } @Test public void test2() { String htmlStr = " Darian: 自动生成目录20172017-01-工程化专题Maven-James.md <a href=\"https://github" + ".com/Darian1996/docs/tree/master/2017/2017-01-工程化专题/Maven-James.md\" target=\"_blank\">GitHub</a> <a " + "href=\"https://gitee.com/Darian1996/docs/tree/master/2017/2017-01-工程化专题/Maven-James.md\" target=\"_blank\">Gitee</a> " + " <a href=\"https://www.darian.top/contentDetail" + ".html?cache=true&filePathSubDocsFilePath=_2017_2017-01-工程化专题_Maven-James.md\" " + "target=\"_blank\">top_doc</a>2017-05-01-什么是性能优化-james什么是性能优化.md <a href=\"https://github" + ".com/Darian1996/docs/tree/master/2017/2017-05-01-什么是性能优化-james/什么是性能优化.md\" target=\"_blank\">GitHub</a> <a " + "href=\"https://gitee.com/Darian1996/docs/tree/master/2017/2017-"; String regEx_html = "<[^>]+>"; //定义HTML标签的正则表达式 Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE); Matcher m_html = p_html.matcher(htmlStr); htmlStr = m_html.replaceAll(""); //过滤html标签 System.out.println(htmlStr); } }
923e5e2714fa54c347cc831c95a98544c344d864
346
java
Java
JavaOrbit-server/src/main/java/de/tr7zw/javaorbit/server/player/Clan.java
tr7zw/JavaOrb
586ff8bd23839eda7d2a9742b615171ee4be0353
[ "MIT" ]
7
2019-01-31T17:01:52.000Z
2021-06-13T00:52:33.000Z
JavaOrbit-server/src/main/java/de/tr7zw/javaorbit/server/player/Clan.java
tr7zw/JavaOrb
586ff8bd23839eda7d2a9742b615171ee4be0353
[ "MIT" ]
9
2019-05-07T06:10:32.000Z
2022-02-08T23:10:15.000Z
JavaOrbit-server/src/main/java/de/tr7zw/javaorbit/server/player/Clan.java
tr7zw/JavaOrb
586ff8bd23839eda7d2a9742b615171ee4be0353
[ "MIT" ]
3
2020-02-23T16:13:15.000Z
2022-01-21T12:06:19.000Z
18.210526
80
0.797688
1,000,732
package de.tr7zw.javaorbit.server.player; import java.util.concurrent.atomic.AtomicInteger; import lombok.AllArgsConstructor; import lombok.Getter; @Getter @AllArgsConstructor public class Clan { @Getter private static final AtomicInteger counteter = new AtomicInteger(1000); private int id; private String name; private String tag; }
923e5e28de704bd73d0feaa356c93080775fe86c
13,423
java
Java
net/minecraft/block/BlockSkull.java
xWhitey/Zamorozka-0.5.3-src
7d42b78de5780009f1fd824a26e68f24f46e0455
[ "WTFPL" ]
11
2021-04-25T19:10:32.000Z
2022-03-16T15:40:15.000Z
src/net/minecraft/block/BlockSkull.java
creepyCaller/minecraft-analysis
15b6effaf577593b957310f8813f2def17091ffa
[ "MIT" ]
1
2021-04-25T19:16:25.000Z
2021-07-18T17:33:49.000Z
src/net/minecraft/block/BlockSkull.java
creepyCaller/minecraft-analysis
15b6effaf577593b957310f8813f2def17091ffa
[ "MIT" ]
6
2021-04-25T19:10:33.000Z
2022-03-03T14:20:51.000Z
39.248538
295
0.651121
1,000,733
package net.minecraft.block; import com.google.common.base.Predicate; import java.util.Random; import javax.annotation.Nullable; import net.minecraft.advancements.CriteriaTriggers; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyBool; import net.minecraft.block.properties.PropertyDirection; import net.minecraft.block.state.BlockFaceShape; import net.minecraft.block.state.BlockStateContainer; import net.minecraft.block.state.BlockWorldState; import net.minecraft.block.state.IBlockState; import net.minecraft.block.state.pattern.BlockMaterialMatcher; import net.minecraft.block.state.pattern.BlockPattern; import net.minecraft.block.state.pattern.BlockStateMatcher; import net.minecraft.block.state.pattern.FactoryBlockPattern; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.boss.EntityWither; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTUtil; import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntitySkull; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.Mirror; import net.minecraft.util.Rotation; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.text.translation.I18n; import net.minecraft.world.EnumDifficulty; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; public class BlockSkull extends BlockContainer { public static final PropertyDirection FACING = BlockDirectional.FACING; public static final PropertyBool NODROP = PropertyBool.create("nodrop"); private static final Predicate<BlockWorldState> IS_WITHER_SKELETON = new Predicate<BlockWorldState>() { public boolean apply(@Nullable BlockWorldState p_apply_1_) { return p_apply_1_.getBlockState() != null && p_apply_1_.getBlockState().getBlock() == Blocks.SKULL && p_apply_1_.getTileEntity() instanceof TileEntitySkull && ((TileEntitySkull)p_apply_1_.getTileEntity()).getSkullType() == 1; } }; protected static final AxisAlignedBB DEFAULT_AABB = new AxisAlignedBB(0.25D, 0.0D, 0.25D, 0.75D, 0.5D, 0.75D); protected static final AxisAlignedBB NORTH_AABB = new AxisAlignedBB(0.25D, 0.25D, 0.5D, 0.75D, 0.75D, 1.0D); protected static final AxisAlignedBB SOUTH_AABB = new AxisAlignedBB(0.25D, 0.25D, 0.0D, 0.75D, 0.75D, 0.5D); protected static final AxisAlignedBB WEST_AABB = new AxisAlignedBB(0.5D, 0.25D, 0.25D, 1.0D, 0.75D, 0.75D); protected static final AxisAlignedBB EAST_AABB = new AxisAlignedBB(0.0D, 0.25D, 0.25D, 0.5D, 0.75D, 0.75D); private BlockPattern witherBasePattern; private BlockPattern witherPattern; protected BlockSkull() { super(Material.CIRCUITS); this.setDefaultState(this.blockState.getBaseState().withProperty(FACING, EnumFacing.NORTH).withProperty(NODROP, Boolean.valueOf(false))); } /** * Gets the localized name of this block. Used for the statistics page. */ public String getLocalizedName() { return I18n.translateToLocal("tile.skull.skeleton.name"); } /** * Used to determine ambient occlusion and culling when rebuilding chunks for render */ public boolean isOpaqueCube(IBlockState state) { return false; } public boolean isFullCube(IBlockState state) { return false; } public boolean func_190946_v(IBlockState p_190946_1_) { return true; } public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos) { switch ((EnumFacing)state.getValue(FACING)) { case UP: default: return DEFAULT_AABB; case NORTH: return NORTH_AABB; case SOUTH: return SOUTH_AABB; case WEST: return WEST_AABB; case EAST: return EAST_AABB; } } /** * Called by ItemBlocks just before a block is actually set in the world, to allow for adjustments to the * IBlockstate */ public IBlockState onBlockPlaced(World worldIn, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer) { return this.getDefaultState().withProperty(FACING, placer.getHorizontalFacing()).withProperty(NODROP, Boolean.valueOf(false)); } /** * Returns a new instance of a block's tile entity class. Called on placing the block. */ public TileEntity createNewTileEntity(World worldIn, int meta) { return new TileEntitySkull(); } public ItemStack getItem(World worldIn, BlockPos pos, IBlockState state) { int i = 0; TileEntity tileentity = worldIn.getTileEntity(pos); if (tileentity instanceof TileEntitySkull) { i = ((TileEntitySkull)tileentity).getSkullType(); } return new ItemStack(Items.SKULL, 1, i); } /** * Spawns this Block's drops into the World as EntityItems. */ public void dropBlockAsItemWithChance(World worldIn, BlockPos pos, IBlockState state, float chance, int fortune) { } public void onBlockHarvested(World worldIn, BlockPos pos, IBlockState state, EntityPlayer player) { if (player.capabilities.isCreativeMode) { state = state.withProperty(NODROP, Boolean.valueOf(true)); worldIn.setBlockState(pos, state, 4); } super.onBlockHarvested(worldIn, pos, state, player); } /** * Called serverside after this block is replaced with another in Chunk, but before the Tile Entity is updated */ public void breakBlock(World worldIn, BlockPos pos, IBlockState state) { if (!worldIn.isRemote) { if (!((Boolean)state.getValue(NODROP)).booleanValue()) { TileEntity tileentity = worldIn.getTileEntity(pos); if (tileentity instanceof TileEntitySkull) { TileEntitySkull tileentityskull = (TileEntitySkull)tileentity; ItemStack itemstack = this.getItem(worldIn, pos, state); if (tileentityskull.getSkullType() == 3 && tileentityskull.getPlayerProfile() != null) { itemstack.setTagCompound(new NBTTagCompound()); NBTTagCompound nbttagcompound = new NBTTagCompound(); NBTUtil.writeGameProfile(nbttagcompound, tileentityskull.getPlayerProfile()); itemstack.getTagCompound().setTag("SkullOwner", nbttagcompound); } spawnAsEntity(worldIn, pos, itemstack); } } super.breakBlock(worldIn, pos, state); } } /** * Get the Item that this Block should drop when harvested. */ public Item getItemDropped(IBlockState state, Random rand, int fortune) { return Items.SKULL; } public boolean canDispenserPlace(World worldIn, BlockPos pos, ItemStack stack) { if (stack.getMetadata() == 1 && pos.getY() >= 2 && worldIn.getDifficulty() != EnumDifficulty.PEACEFUL && !worldIn.isRemote) { return this.getWitherBasePattern().match(worldIn, pos) != null; } else { return false; } } public void checkWitherSpawn(World worldIn, BlockPos pos, TileEntitySkull te) { if (te.getSkullType() == 1 && pos.getY() >= 2 && worldIn.getDifficulty() != EnumDifficulty.PEACEFUL && !worldIn.isRemote) { BlockPattern blockpattern = this.getWitherPattern(); BlockPattern.PatternHelper blockpattern$patternhelper = blockpattern.match(worldIn, pos); if (blockpattern$patternhelper != null) { for (int i = 0; i < 3; ++i) { BlockWorldState blockworldstate = blockpattern$patternhelper.translateOffset(i, 0, 0); worldIn.setBlockState(blockworldstate.getPos(), blockworldstate.getBlockState().withProperty(NODROP, Boolean.valueOf(true)), 2); } for (int j = 0; j < blockpattern.getPalmLength(); ++j) { for (int k = 0; k < blockpattern.getThumbLength(); ++k) { BlockWorldState blockworldstate1 = blockpattern$patternhelper.translateOffset(j, k, 0); worldIn.setBlockState(blockworldstate1.getPos(), Blocks.AIR.getDefaultState(), 2); } } BlockPos blockpos = blockpattern$patternhelper.translateOffset(1, 0, 0).getPos(); EntityWither entitywither = new EntityWither(worldIn); BlockPos blockpos1 = blockpattern$patternhelper.translateOffset(1, 2, 0).getPos(); entitywither.setLocationAndAngles((double)blockpos1.getX() + 0.5D, (double)blockpos1.getY() + 0.55D, (double)blockpos1.getZ() + 0.5D, blockpattern$patternhelper.getForwards().getAxis() == EnumFacing.Axis.X ? 0.0F : 90.0F, 0.0F); entitywither.renderYawOffset = blockpattern$patternhelper.getForwards().getAxis() == EnumFacing.Axis.X ? 0.0F : 90.0F; entitywither.ignite(); for (EntityPlayerMP entityplayermp : worldIn.getEntitiesWithinAABB(EntityPlayerMP.class, entitywither.getEntityBoundingBox().expandXyz(50.0D))) { CriteriaTriggers.field_192133_m.func_192229_a(entityplayermp, entitywither); } worldIn.spawnEntityInWorld(entitywither); for (int l = 0; l < 120; ++l) { worldIn.spawnParticle(EnumParticleTypes.SNOWBALL, (double)blockpos.getX() + worldIn.rand.nextDouble(), (double)(blockpos.getY() - 2) + worldIn.rand.nextDouble() * 3.9D, (double)blockpos.getZ() + worldIn.rand.nextDouble(), 0.0D, 0.0D, 0.0D); } for (int i1 = 0; i1 < blockpattern.getPalmLength(); ++i1) { for (int j1 = 0; j1 < blockpattern.getThumbLength(); ++j1) { BlockWorldState blockworldstate2 = blockpattern$patternhelper.translateOffset(i1, j1, 0); worldIn.notifyNeighborsRespectDebug(blockworldstate2.getPos(), Blocks.AIR, false); } } } } } /** * Convert the given metadata into a BlockState for this Block */ public IBlockState getStateFromMeta(int meta) { return this.getDefaultState().withProperty(FACING, EnumFacing.getFront(meta & 7)).withProperty(NODROP, Boolean.valueOf((meta & 8) > 0)); } /** * Convert the BlockState into the correct metadata value */ public int getMetaFromState(IBlockState state) { int i = 0; i = i | ((EnumFacing)state.getValue(FACING)).getIndex(); if (((Boolean)state.getValue(NODROP)).booleanValue()) { i |= 8; } return i; } /** * Returns the blockstate with the given rotation from the passed blockstate. If inapplicable, returns the passed * blockstate. */ public IBlockState withRotation(IBlockState state, Rotation rot) { return state.withProperty(FACING, rot.rotate((EnumFacing)state.getValue(FACING))); } /** * Returns the blockstate with the given mirror of the passed blockstate. If inapplicable, returns the passed * blockstate. */ public IBlockState withMirror(IBlockState state, Mirror mirrorIn) { return state.withRotation(mirrorIn.toRotation((EnumFacing)state.getValue(FACING))); } protected BlockStateContainer createBlockState() { return new BlockStateContainer(this, new IProperty[] {FACING, NODROP}); } protected BlockPattern getWitherBasePattern() { if (this.witherBasePattern == null) { this.witherBasePattern = FactoryBlockPattern.start().aisle(" ", "###", "~#~").where('#', BlockWorldState.hasState(BlockStateMatcher.forBlock(Blocks.SOUL_SAND))).where('~', BlockWorldState.hasState(BlockMaterialMatcher.forMaterial(Material.AIR))).build(); } return this.witherBasePattern; } protected BlockPattern getWitherPattern() { if (this.witherPattern == null) { this.witherPattern = FactoryBlockPattern.start().aisle("^^^", "###", "~#~").where('#', BlockWorldState.hasState(BlockStateMatcher.forBlock(Blocks.SOUL_SAND))).where('^', IS_WITHER_SKELETON).where('~', BlockWorldState.hasState(BlockMaterialMatcher.forMaterial(Material.AIR))).build(); } return this.witherPattern; } public BlockFaceShape func_193383_a(IBlockAccess p_193383_1_, IBlockState p_193383_2_, BlockPos p_193383_3_, EnumFacing p_193383_4_) { return BlockFaceShape.UNDEFINED; } }
923e5fd92b8a0ce0bdca9219514a9690202f2e87
2,234
java
Java
src/main/java/Test.java
Subh0m0y/Data-Structures
52202a5cb749d697c952d68315263de18317e1eb
[ "MIT" ]
2
2017-02-27T14:42:06.000Z
2018-04-26T08:34:59.000Z
src/main/java/Test.java
Subh0m0y/Data-Structures
52202a5cb749d697c952d68315263de18317e1eb
[ "MIT" ]
null
null
null
src/main/java/Test.java
Subh0m0y/Data-Structures
52202a5cb749d697c952d68315263de18317e1eb
[ "MIT" ]
null
null
null
37.864407
77
0.687556
1,000,734
/* * The MIT License (MIT) * Copyright (c) 2016-2017 Subhomoy Haldar * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ import com.github.subh0m0y.datastructures.queues.PriorityQueue; import com.github.subh0m0y.datastructures.utils.ArrayUtil; import java.util.Comparator; import java.util.Random; /** * @author Subhomoy Haldar * @version 2017.02.05 */ public class Test { private static final int SIZE = 1_000_000; private static Integer[] array = new Integer[SIZE]; public static void main(String[] args) { for (int i = 0; i < SIZE; i++) { array[i] = i; } ArrayUtil.shuffle(args, new Random()); long time = System.nanoTime(); pqSort(); // around 2.2 s //Arrays.sort(array); // around 0.02 s (yes I know, stop laughing) time = System.nanoTime() - time; assert ArrayUtil.isSorted(array, Comparator.naturalOrder()); System.out.println(time * 1e-9); } private static void pqSort() { PriorityQueue<Integer> queue = new PriorityQueue<>(SIZE); for (Integer element : array) { queue.enqueue(element); } array = queue.toArray(array); } }
923e612cf4a284d51e9090cc73de17807e749d9a
1,464
java
Java
core/src/main/java/com/huawei/openstack4j/model/workflow/WorkbookDefinition.java
wuchen-huawei/huaweicloud-sdk-java
1e4b76c737d23c5d5df59405015ea136651b6fc1
[ "Apache-2.0" ]
46
2018-09-30T08:55:22.000Z
2021-11-07T20:02:57.000Z
core/src/main/java/com/huawei/openstack4j/model/workflow/WorkbookDefinition.java
wuchen-huawei/huaweicloud-sdk-java
1e4b76c737d23c5d5df59405015ea136651b6fc1
[ "Apache-2.0" ]
18
2019-04-11T02:37:30.000Z
2021-04-30T09:03:38.000Z
core/src/main/java/com/huawei/openstack4j/model/workflow/WorkbookDefinition.java
wuchen-huawei/huaweicloud-sdk-java
1e4b76c737d23c5d5df59405015ea136651b6fc1
[ "Apache-2.0" ]
42
2019-01-22T07:54:00.000Z
2021-12-13T01:14:14.000Z
48.8
85
0.395492
1,000,735
/******************************************************************************* * Copyright 2016 ContainX and OpenStack4j * * 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.huawei.openstack4j.model.workflow; /** * A workbook definition. * * @author Renat Akhmerov */ public interface WorkbookDefinition extends Definition { }
923e6200de24a7a4e4762407e69712566ad4dc2b
2,367
java
Java
spring-cloud-vault-config/src/main/java/org/springframework/cloud/vault/config/PropertyNameTransformer.java
axbg/spring-cloud-vault
18bf2eb63a90e4c7a35a5c0763500ac55f792186
[ "Apache-2.0" ]
182
2017-04-05T00:57:06.000Z
2022-03-13T09:17:15.000Z
spring-cloud-vault-config/src/main/java/org/springframework/cloud/vault/config/PropertyNameTransformer.java
axbg/spring-cloud-vault
18bf2eb63a90e4c7a35a5c0763500ac55f792186
[ "Apache-2.0" ]
501
2017-03-30T19:53:54.000Z
2022-03-22T10:18:47.000Z
spring-cloud-vault-config/src/main/java/org/springframework/cloud/vault/config/PropertyNameTransformer.java
axbg/spring-cloud-vault
18bf2eb63a90e4c7a35a5c0763500ac55f792186
[ "Apache-2.0" ]
141
2017-04-05T14:21:19.000Z
2022-03-04T16:22:50.000Z
29.5875
87
0.736798
1,000,736
/* * Copyright 2016-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 org.springframework.cloud.vault.config; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import org.springframework.util.Assert; import org.springframework.vault.core.util.PropertyTransformer; /** * {@link PropertyTransformer} to transform a {@link Map} of properties by applying key * name translation. * * <p> * Existing keys will be transformed to a target key name while retaining the original * value. Key name translation will leave other, not specified key names untouched. * * @author Mark Paluch */ public class PropertyNameTransformer implements PropertyTransformer { private final Map<String, String> nameMapping = new HashMap<>(); /** * Create a new {@link PropertyNameTransformer}. */ public PropertyNameTransformer() { } /** * Adds a key name transformation by providing a {@code sourceKeyName} and a * {@code targetKeyName}. * @param sourceKeyName must not be empty or {@literal null}. * @param targetKeyName must not be empty or {@literal null}. */ public void addKeyTransformation(String sourceKeyName, String targetKeyName) { Assert.hasText(sourceKeyName, "Source key name must not be empty"); Assert.hasText(targetKeyName, "Target key name must not be empty"); this.nameMapping.put(sourceKeyName, targetKeyName); } @Override public Map<String, Object> transformProperties(Map<String, ? extends Object> input) { Map<String, Object> transformed = new LinkedHashMap<>(input.size(), 1); for (String key : input.keySet()) { String translatedKey = key; if (this.nameMapping.containsKey(key)) { translatedKey = this.nameMapping.get(key); } transformed.put(translatedKey, input.get(key)); } return transformed; } }
923e623c021583473bcf3a84598a2151c8bb67f0
1,883
java
Java
equivalence-itests/src/main/java/com/pragmaticobjects/oo/equivalence/itests/classes/AbstractNode.java
pragmatic-objects/oo-equivalence
f0f0839297518a6627bda76f7237a2f51cc13191
[ "MIT" ]
5
2019-08-16T10:22:13.000Z
2021-08-23T20:20:41.000Z
equivalence-itests/src/main/java/com/pragmaticobjects/oo/equivalence/itests/classes/AbstractNode.java
pragmatic-objects/oo-equivalence
f0f0839297518a6627bda76f7237a2f51cc13191
[ "MIT" ]
96
2019-07-26T21:06:03.000Z
2021-07-28T05:30:36.000Z
equivalence-itests/src/main/java/com/pragmaticobjects/oo/equivalence/itests/classes/AbstractNode.java
pragmatic-objects/oo-equivalence
f0f0839297518a6627bda76f7237a2f51cc13191
[ "MIT" ]
null
null
null
40.06383
80
0.613383
1,000,737
/*- * =========================================================================== * equivalence-itests * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * Copyright (C) 2019 - 2020 Kapralov Sergey * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * ============================================================================ */ package com.pragmaticobjects.oo.equivalence.itests.classes; import com.pragmaticobjects.oo.equivalence.base.EObjectHint; /** * * @author skapral * @param <T> type */ public @EObjectHint abstract class AbstractNode<T> implements Node<T> { protected final T value; public AbstractNode(T value) { this.value = value; } @Override public final T value() { return value; } }
923e634982e3d6aaa57d474461c99a446c9d1b8e
1,434
java
Java
src/main/java/com/dgex/backend/controller/ServerManageController.java
DigitalGoldExchange/tgxc_app_api
90239756033b128da5975bf37ba8ea50da5d8328
[ "MIT" ]
null
null
null
src/main/java/com/dgex/backend/controller/ServerManageController.java
DigitalGoldExchange/tgxc_app_api
90239756033b128da5975bf37ba8ea50da5d8328
[ "MIT" ]
null
null
null
src/main/java/com/dgex/backend/controller/ServerManageController.java
DigitalGoldExchange/tgxc_app_api
90239756033b128da5975bf37ba8ea50da5d8328
[ "MIT" ]
null
null
null
35.85
100
0.755927
1,000,738
package com.dgex.backend.controller; import com.dgex.backend.repository.ServerManageRepository; import com.dgex.backend.response.CommonResult; import com.dgex.backend.response.SingleResult; import com.dgex.backend.service.ResponseService; import com.dgex.backend.service.ServerManageService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.*; @Api(tags = {"ServerManage : 서버(ServerManage)"}) @RequiredArgsConstructor @RestController @RequestMapping(value = "/serverManage") public class ServerManageController { private final ServerManageService serverManageService; private final ResponseService responseService; private final ServerManageRepository serverManageRepository; @ApiOperation(value = "회원 수정", notes = "회원 정보를 수정한다.") @PostMapping(value = "/update") public CommonResult update( @RequestParam(value = "userId", required = false) Integer userId, @RequestParam(value = "status", required = false) String status ) { serverManageService.update(userId, status); return responseService.getSuccessResult(); } @ApiOperation(value = "단건 조회") @GetMapping(value = "/getOne") public SingleResult<Object> getOne( ) { return responseService.getSingleResult(serverManageRepository.findByDeleteDatetimeIsNull()); } }
923e63756bc799b296825dea5fd32f28224f9c7b
1,461
java
Java
Javanewfeature/src/main/java/luozix/start/nashorn/MyClassFilterTest.java
PeterXiao/jmh-and-javanew
e78abdf151763d568cb16261166bb3d198e43731
[ "Apache-2.0" ]
1
2021-03-01T08:33:42.000Z
2021-03-01T08:33:42.000Z
Javanewfeature/src/main/java/luozix/start/nashorn/MyClassFilterTest.java
PeterXiao/jmh-and-javanew
e78abdf151763d568cb16261166bb3d198e43731
[ "Apache-2.0" ]
6
2021-03-10T23:33:09.000Z
2022-03-31T20:01:07.000Z
Javanewfeature/src/main/java/luozix/start/nashorn/MyClassFilterTest.java
PeterXiao/jmh-and-javanew
e78abdf151763d568cb16261166bb3d198e43731
[ "Apache-2.0" ]
1
2021-03-01T08:33:44.000Z
2021-03-01T08:33:44.000Z
27.314815
76
0.654237
1,000,739
/** * @Title: MyClassFilterTest.java * @Package luozix.start.nashorn * @Description: TODO(用一句话描述该文件做什么) * @author xiaoyu lyhxr@example.com * @date 2021年2月10日 下午1:36:35 * @version V1.0 */ package luozix.start.nashorn; /** * @ClassName: MyClassFilterTest * @Description: TODO(这里用一句话描述这个类的作用) * @author xiaoyu lyhxr@example.com * @date 2021年2月10日 下午1:36:35 * */ //import javax.script.ScriptEngine; //import jdk.nashorn.api.scripting.ClassFilter; //import jdk.nashorn.api.scripting.NashornScriptEngineFactory; // //public class MyClassFilterTest { // // class MyCF implements ClassFilter { // @Override // public boolean exposeToScripts(String s) { // if (s.compareTo("java.io.File") == 0) return false; // return true; // } // } // // public void testClassFilter() { // // final String script = // "print(java.lang.System.getProperty(\"java.home\"));" + // "print(\"Create file variable\");" + // "var File = Java.type(\"java.io.File\");"; // // NashornScriptEngineFactory factory = new NashornScriptEngineFactory(); // // ScriptEngine engine = factory.getScriptEngine( // new MyClassFilterTest.MyCF()); // try { // engine.eval(script); // } catch (Exception e) { // System.out.println("Exception caught: " + e.toString()); // } // } // // public static void main(String[] args) { // MyClassFilterTest myApp = new MyClassFilterTest(); // myApp.testClassFilter(); // } //}
923e63791f0ecb380dec7a3bda1711a1323c4fa3
972
java
Java
sabot/kernel/src/main/java/com/dremio/exec/store/PartitionNotFoundException.java
geetek/dremio-oss
812c7f32f9437df52b1d7bd8d5c45f9a79b6e9d2
[ "Apache-2.0" ]
1,085
2017-07-19T15:08:38.000Z
2022-03-29T13:35:07.000Z
sabot/kernel/src/main/java/com/dremio/exec/store/PartitionNotFoundException.java
geetek/dremio-oss
812c7f32f9437df52b1d7bd8d5c45f9a79b6e9d2
[ "Apache-2.0" ]
20
2017-07-19T20:16:27.000Z
2021-12-02T10:56:25.000Z
sabot/kernel/src/main/java/com/dremio/exec/store/PartitionNotFoundException.java
geetek/dremio-oss
812c7f32f9437df52b1d7bd8d5c45f9a79b6e9d2
[ "Apache-2.0" ]
398
2017-07-19T18:12:58.000Z
2022-03-30T09:37:40.000Z
28.588235
75
0.734568
1,000,740
/* * Copyright (C) 2017-2019 Dremio Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dremio.exec.store; public class PartitionNotFoundException extends Exception { public PartitionNotFoundException() { } public PartitionNotFoundException(String s) { super(s); } public PartitionNotFoundException(Exception ex) { super(ex); } public PartitionNotFoundException(String s, Exception ex) { super(s, ex); } }
923e648b4d8afb8384ef6d1815b0157c23492681
768
java
Java
brix-core/src/main/java/org/brixcms/web/nodepage/PageParametersRequestHandler.java
dsimko/brix-cms
73074b68500c47721a528f887add54867ba13c2e
[ "Apache-2.0" ]
65
2015-03-05T16:50:11.000Z
2021-12-20T21:59:44.000Z
brix-core/src/main/java/org/brixcms/web/nodepage/PageParametersRequestHandler.java
dsimko/brix-cms
73074b68500c47721a528f887add54867ba13c2e
[ "Apache-2.0" ]
52
2015-10-09T08:07:29.000Z
2021-09-21T14:32:11.000Z
brix-core/src/main/java/org/brixcms/web/nodepage/PageParametersRequestHandler.java
dsimko/brix-cms
73074b68500c47721a528f887add54867ba13c2e
[ "Apache-2.0" ]
39
2015-04-06T03:22:17.000Z
2022-02-28T07:13:45.000Z
34.909091
75
0.764323
1,000,741
/** * 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.brixcms.web.nodepage; import org.apache.wicket.request.IRequestHandler; public interface PageParametersRequestHandler extends IRequestHandler { BrixPageParameters getPageParameters(); }
923e64f3cee53f0a99b2dae3493419e6224b92c8
234
java
Java
src/main/java/es/upm/miw/pd/abstractfactory/concrete1/ProductB1.java
helderhernandez/apaw
9ce56e826dfbd3d9f788342b0cac2b4530f4867a
[ "MIT" ]
33
2019-08-21T19:40:35.000Z
2022-03-29T16:01:16.000Z
src/main/java/es/upm/miw/pd/abstractfactory/concrete1/ProductB1.java
helderhernandez/apaw
9ce56e826dfbd3d9f788342b0cac2b4530f4867a
[ "MIT" ]
null
null
null
src/main/java/es/upm/miw/pd/abstractfactory/concrete1/ProductB1.java
helderhernandez/apaw
9ce56e826dfbd3d9f788342b0cac2b4530f4867a
[ "MIT" ]
32
2019-09-30T07:43:27.000Z
2022-03-29T16:01:28.000Z
18
49
0.67094
1,000,742
package es.upm.miw.pd.abstractfactory.concrete1; import es.upm.miw.pd.abstractfactory.ProductB; public class ProductB1 implements ProductB { @Override public String view() { return "ProductB1"; } }
923e651fc0048b5bd324d7861e7ed741b5c654ea
4,419
java
Java
aliyun-java-sdk-r-kvstore/src/main/java/com/aliyuncs/r_kvstore/transform/v20150101/DescribePriceResponseUnmarshaller.java
caojiele/aliyun-openapi-java-sdk
ecc1c949681276b3eed2500ec230637b039771b8
[ "Apache-2.0" ]
1
2022-02-12T06:01:36.000Z
2022-02-12T06:01:36.000Z
aliyun-java-sdk-r-kvstore/src/main/java/com/aliyuncs/r_kvstore/transform/v20150101/DescribePriceResponseUnmarshaller.java
caojiele/aliyun-openapi-java-sdk
ecc1c949681276b3eed2500ec230637b039771b8
[ "Apache-2.0" ]
27
2021-06-11T21:08:40.000Z
2022-03-11T21:25:09.000Z
aliyun-java-sdk-r-kvstore/src/main/java/com/aliyuncs/r_kvstore/transform/v20150101/DescribePriceResponseUnmarshaller.java
caojiele/aliyun-openapi-java-sdk
ecc1c949681276b3eed2500ec230637b039771b8
[ "Apache-2.0" ]
1
2020-03-05T07:30:16.000Z
2020-03-05T07:30:16.000Z
48.032609
120
0.752206
1,000,743
/* * 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.r_kvstore.transform.v20150101; import java.util.ArrayList; import java.util.List; import com.aliyuncs.r_kvstore.model.v20150101.DescribePriceResponse; import com.aliyuncs.r_kvstore.model.v20150101.DescribePriceResponse.Order; import com.aliyuncs.r_kvstore.model.v20150101.DescribePriceResponse.Order.Coupon; import com.aliyuncs.r_kvstore.model.v20150101.DescribePriceResponse.Rule; import com.aliyuncs.r_kvstore.model.v20150101.DescribePriceResponse.SubOrder; import com.aliyuncs.transform.UnmarshallerContext; public class DescribePriceResponseUnmarshaller { public static DescribePriceResponse unmarshall(DescribePriceResponse describePriceResponse, UnmarshallerContext _ctx) { describePriceResponse.setRequestId(_ctx.stringValue("DescribePriceResponse.RequestId")); describePriceResponse.setOrderParams(_ctx.stringValue("DescribePriceResponse.OrderParams")); Order order = new Order(); order.setOriginalAmount(_ctx.stringValue("DescribePriceResponse.Order.OriginalAmount")); order.setTradeAmount(_ctx.stringValue("DescribePriceResponse.Order.TradeAmount")); order.setDiscountAmount(_ctx.stringValue("DescribePriceResponse.Order.DiscountAmount")); order.setCurrency(_ctx.stringValue("DescribePriceResponse.Order.Currency")); order.setHandlingFeeAmount(_ctx.stringValue("DescribePriceResponse.Order.HandlingFeeAmount")); List<String> ruleIds1 = new ArrayList<String>(); for (int i = 0; i < _ctx.lengthValue("DescribePriceResponse.Order.RuleIds.Length"); i++) { ruleIds1.add(_ctx.stringValue("DescribePriceResponse.Order.RuleIds["+ i +"]")); } order.setRuleIds1(ruleIds1); List<Coupon> coupons = new ArrayList<Coupon>(); for (int i = 0; i < _ctx.lengthValue("DescribePriceResponse.Order.Coupons.Length"); i++) { Coupon coupon = new Coupon(); coupon.setCouponNo(_ctx.stringValue("DescribePriceResponse.Order.Coupons["+ i +"].CouponNo")); coupon.setName(_ctx.stringValue("DescribePriceResponse.Order.Coupons["+ i +"].Name")); coupon.setDescription(_ctx.stringValue("DescribePriceResponse.Order.Coupons["+ i +"].Description")); coupon.setIsSelected(_ctx.stringValue("DescribePriceResponse.Order.Coupons["+ i +"].IsSelected")); coupons.add(coupon); } order.setCoupons(coupons); describePriceResponse.setOrder(order); List<Rule> rules = new ArrayList<Rule>(); for (int i = 0; i < _ctx.lengthValue("DescribePriceResponse.Rules.Length"); i++) { Rule rule = new Rule(); rule.setRuleDescId(_ctx.longValue("DescribePriceResponse.Rules["+ i +"].RuleDescId")); rule.setName(_ctx.stringValue("DescribePriceResponse.Rules["+ i +"].Name")); rule.setTitle(_ctx.stringValue("DescribePriceResponse.Rules["+ i +"].Title")); rules.add(rule); } describePriceResponse.setRules(rules); List<SubOrder> subOrders = new ArrayList<SubOrder>(); for (int i = 0; i < _ctx.lengthValue("DescribePriceResponse.SubOrders.Length"); i++) { SubOrder subOrder = new SubOrder(); subOrder.setOriginalAmount(_ctx.stringValue("DescribePriceResponse.SubOrders["+ i +"].OriginalAmount")); subOrder.setTradeAmount(_ctx.stringValue("DescribePriceResponse.SubOrders["+ i +"].TradeAmount")); subOrder.setDiscountAmount(_ctx.stringValue("DescribePriceResponse.SubOrders["+ i +"].DiscountAmount")); subOrder.setInstanceId(_ctx.stringValue("DescribePriceResponse.SubOrders["+ i +"].InstanceId")); List<String> ruleIds = new ArrayList<String>(); for (int j = 0; j < _ctx.lengthValue("DescribePriceResponse.SubOrders["+ i +"].RuleIds.Length"); j++) { ruleIds.add(_ctx.stringValue("DescribePriceResponse.SubOrders["+ i +"].RuleIds["+ j +"]")); } subOrder.setRuleIds(ruleIds); subOrders.add(subOrder); } describePriceResponse.setSubOrders(subOrders); return describePriceResponse; } }
923e66688cea64bdfb02073f0c8dd1d72b56bdf5
1,442
java
Java
modules/adwords_appengine/src/main/java/com/google/api/ads/adwords/jaxws/v201402/mcm/TriggerTimeSpec.java
david-gorisse/googleads-java-lib
03b8c7e83bc5a361e374d345afdd93290d143c34
[ "Apache-2.0" ]
null
null
null
modules/adwords_appengine/src/main/java/com/google/api/ads/adwords/jaxws/v201402/mcm/TriggerTimeSpec.java
david-gorisse/googleads-java-lib
03b8c7e83bc5a361e374d345afdd93290d143c34
[ "Apache-2.0" ]
null
null
null
modules/adwords_appengine/src/main/java/com/google/api/ads/adwords/jaxws/v201402/mcm/TriggerTimeSpec.java
david-gorisse/googleads-java-lib
03b8c7e83bc5a361e374d345afdd93290d143c34
[ "Apache-2.0" ]
null
null
null
20.309859
95
0.540915
1,000,744
package com.google.api.ads.adwords.jaxws.v201402.mcm; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for TriggerTimeSpec. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="TriggerTimeSpec"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="ALL_TIME"/> * &lt;enumeration value="CUSTOM_TIME"/> * &lt;enumeration value="LAST_24_HOURS"/> * &lt;enumeration value="LAST_7_DAYS"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "TriggerTimeSpec") @XmlEnum public enum TriggerTimeSpec { /** * * Get alerts triggered at any time. * * */ ALL_TIME, /** * * Get alerts triggered since {@link AlertQuery#triggerTime}. * * */ CUSTOM_TIME, /** * * Get alerts triggered within the last 24 hours. * * */ LAST_24_HOURS, /** * * Get alerts triggered within the last 7 days. * * */ LAST_7_DAYS; public String value() { return name(); } public static TriggerTimeSpec fromValue(String v) { return valueOf(v); } }
923e672f74aa5905cef9a1933a6312ab0a01c5e9
379
java
Java
src/main/java/ohtu/ts/ui/BookTipUI.java
Robustic/ohtu-ts
1e36ff7c589b9196becf959db4fb0d12a881b8a6
[ "MIT" ]
null
null
null
src/main/java/ohtu/ts/ui/BookTipUI.java
Robustic/ohtu-ts
1e36ff7c589b9196becf959db4fb0d12a881b8a6
[ "MIT" ]
null
null
null
src/main/java/ohtu/ts/ui/BookTipUI.java
Robustic/ohtu-ts
1e36ff7c589b9196becf959db4fb0d12a881b8a6
[ "MIT" ]
null
null
null
21.055556
45
0.588391
1,000,745
package ohtu.ts.ui; import ohtu.ts.domain.Book; import ohtu.ts.domain.ReadingTip; import ohtu.ts.io.IO; public class BookTipUI implements TipUI { @Override public ReadingTip getTipFromUser(IO io) { return new Book( io.readLine("Otsikko: "), io.readLine("Kirjoittaja: "), io.readLine("ISBN: ") ); } }
923e675e66931967dad896f599681c967e3d89bb
10,894
java
Java
core/generator/source/jetbrains/mps/generator/impl/plan/EngagedGeneratorCollector.java
trespasserw/MPS
dbc5c76496e8ccef46dd420eefcd5089b1bc234b
[ "Apache-2.0" ]
null
null
null
core/generator/source/jetbrains/mps/generator/impl/plan/EngagedGeneratorCollector.java
trespasserw/MPS
dbc5c76496e8ccef46dd420eefcd5089b1bc234b
[ "Apache-2.0" ]
null
null
null
core/generator/source/jetbrains/mps/generator/impl/plan/EngagedGeneratorCollector.java
trespasserw/MPS
dbc5c76496e8ccef46dd420eefcd5089b1bc234b
[ "Apache-2.0" ]
null
null
null
37.958188
180
0.720213
1,000,746
/* * Copyright 2003-2020 JetBrains s.r.o. * * 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 jetbrains.mps.generator.impl.plan; import jetbrains.mps.generator.runtime.TemplateModule; import jetbrains.mps.smodel.language.GeneratorRuntime; import jetbrains.mps.smodel.language.LanguageRegistry; import jetbrains.mps.smodel.language.LanguageRuntime; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.mps.openapi.language.SLanguage; import org.jetbrains.mps.openapi.model.SModel; import org.jetbrains.mps.openapi.module.SModuleReference; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Queue; import java.util.Set; import java.util.function.Consumer; import java.util.stream.Collectors; /** * Find out generators for a model according to set of languages model actually uses. * NOTE, this is internal facility and NOT AN API. Made public for the sake of debug/info actions. * @author Artem Tikhomirov */ public final class EngagedGeneratorCollector { private static final Logger LOG = LogManager.getLogger(GenerationPlan.class); @NotNull private final SModel myModel; private final List<SLanguage> myAdditionalLanguages; private final LanguageRegistry myLanguageRegistry; private Collection<SLanguage> myDirectLangUse; private Collection<TemplateModule> myEngagedGenerators; private final Set<SLanguage> myBadLanguages = new HashSet<>(); // all generators found during the process, with possible duplicates // e.g. L1 with G1 and L2 with G2, both G1 and G2 extend G3, which would show up twice in this case private final List<EngagedGenerator> myEngagedTrace = new ArrayList<>(); /** * @deprecated use the cons with {@code LanguageRegistry}. There's no use for additionalLanguages (generation parameters shall fade away; could get replaced with GP if necessary) */ @Deprecated(since = "2020.3", forRemoval = true) public EngagedGeneratorCollector(@NotNull SModel model, @Nullable Collection<SLanguage> additionalLanguages) { myLanguageRegistry = LanguageRegistry.getInstance(); myModel = model; myAdditionalLanguages = additionalLanguages == null ? Collections.emptyList() : new ArrayList<>(additionalLanguages); } public EngagedGeneratorCollector(@NotNull LanguageRegistry languageRegistry, @NotNull SModel model) { myLanguageRegistry = languageRegistry; myModel = model; myAdditionalLanguages = Collections.emptyList(); } /** * @return list of languages actually used in the model, including those specified with 'engaged on generation' model property. */ public Collection<SLanguage> getDirectlyUsedLanguages() { if (myDirectLangUse == null) { myDirectLangUse = ModelContentUtil.getUsedLanguages(myModel); } return myDirectLangUse; } /** * @return list of used languages including additional languages supplied {@linkplain EngagedGeneratorCollector externally} (if any) */ public Collection<SLanguage> getAllLanguages() { if (myAdditionalLanguages.isEmpty()) { return getDirectlyUsedLanguages(); } Collection<SLanguage> l1 = getDirectlyUsedLanguages(); ArrayList<SLanguage> rv = new ArrayList<>(l1.size() + myAdditionalLanguages.size()); rv.addAll(l1); rv.addAll(myAdditionalLanguages); return rv; } public Collection<TemplateModule> getGenerators() { if (myEngagedGenerators == null) { myEngagedGenerators = build(); } return myEngagedGenerators; } @NotNull private Collection<TemplateModule> build() { myBadLanguages.clear(); myEngagedTrace.clear(); final Collection<SLanguage> initialLanguages = getAllLanguages(); Queue<EngagedLanguage> queue = new ArrayDeque<>(resolveLanguages(initialLanguages, null, null)); // XXX could have used Set<SLanguage> here, but it's not easy to get SLanguage from LanguageRuntime (which I use to walk extended langs) Set<String> processedLanguages = new HashSet<>(toQualifiedName(initialLanguages)); // set of languages either used (and/or demanded) explicitly in the model we're about to generate, // and languages that may appear during generation process (e.g. by applying some of generators) Set<EngagedLanguage> participatingLanguages = new HashSet<>(queue); while (!queue.isEmpty()) { EngagedLanguage next = queue.remove(); for (LanguageRuntime extendedLang : next.getLanguage().getExtendedLanguages()) { if (processedLanguages.add(extendedLang.getNamespace())) { final EngagedLanguage engaged = new EngagedLanguage(extendedLang, next, "EXTENDS"); participatingLanguages.add(engaged); queue.add(engaged); } } HashSet<EngagedLanguage> targetLanguages = new HashSet<>(); // collect extra languages from generator module description myEngagedTrace.addAll(collectGeneratorsAndTargetLanguages(next, targetLanguages)); for (EngagedLanguage t : targetLanguages) { if (processedLanguages.add(t.getName())) { participatingLanguages.add(t); queue.add(t); } } } // collect unique template models ArrayList<TemplateModule> all = new ArrayList<>(); HashSet<SModuleReference> processedGenerators = new HashSet<>(myEngagedTrace.size() * 2); for (EngagedGenerator m : myEngagedTrace) { final TemplateModule tm = m.getGenerator(); if (processedGenerators.add(tm.getModuleReference())) { all.add(tm); } } return Collections.unmodifiableList(all); } private List<EngagedGenerator> collectGeneratorsAndTargetLanguages(EngagedLanguage lang, Set<EngagedLanguage> targetLanguages) { Collection<? extends GeneratorRuntime> generators = lang.getLanguage().getGenerators(); if (generators == null) { return Collections.emptyList(); } ArrayList<EngagedGenerator> langGenerators = new ArrayList<>(2 + generators.size()); // collect extra languages from generator module description for (GeneratorRuntime gr : generators) { if (false == gr instanceof TemplateModule) { continue; } final TemplateModule generator = (TemplateModule) gr; EngagedGenerator eg = new EngagedGenerator(generator, lang, "OWNED"); langGenerators.add(eg); // handle Used languages targetLanguages.addAll(resolveLanguages(generator.getTargetLanguages(), eg, "GENERATES INTO")); // // handle referenced generators for (TemplateModule tm : generator.getExtendedGenerators()) { langGenerators.add(new EngagedGenerator(tm, eg, "EXTENDED GENERATOR")); } for (TemplateModule tm : generator.getEmployedGenerators()) { langGenerators.add(new EngagedGenerator(tm, eg, "EMPLOYED GENERATOR")); } } return langGenerators; } private Collection<EngagedLanguage> resolveLanguages(Collection<SLanguage> languages, EngagedElement origin, Object engagementKind) { ArrayList<EngagedLanguage> rv = new ArrayList<>(languages.size()); final LinkedHashSet<SLanguage> toResolve = new LinkedHashSet<>(languages); for (SLanguage next : toResolve) { if (myBadLanguages.contains(next)) { // do not resolve more than once continue; } LanguageRuntime language = myLanguageRegistry.getLanguage(next); if (language == null) { if (origin == null) { final String msg = "Model %s uses language %s which is missing (likely is not yet generated or is a bootstrap dependency)"; LOG.error(String.format(msg, myModel.getName(), next)); } else { String msg = "One of generators engaged for model %s needs ('%s') missing language %s. Please check generator %s"; LOG.error(String.format(msg, myModel.getName(), engagementKind, next, origin.getName())); } myBadLanguages.add(next); } else { rv.add(new EngagedLanguage(language, origin, engagementKind)); } } return rv; } /** * Pumps debug information about engaged generators and the way they got activated as a string. * I know it's better to provide some sort of structured info, but now seems not worth the effort. */ public void dump(Consumer<String> traceConsumer) { myEngagedTrace.forEach(l -> traceConsumer.accept(" " + l)); } // cease existence once we get rid of strings completely private static Collection<String> toQualifiedName(Collection<SLanguage> languages) { return languages.stream().map(SLanguage::getQualifiedName).collect(Collectors.toList()); } private abstract static class EngagedElement { protected final EngagedElement myOrigin; protected final Object myEngagementKind; protected EngagedElement(EngagedElement origin, Object engagementKind) { myOrigin = origin; myEngagementKind = engagementKind; } public abstract String getName(); public EngagedElement getOrigin() { return myOrigin; } @Override public String toString() { String msg = myOrigin == null ? "%s: %s" : "%s: %s as %s through [%s]"; return String.format(msg, getClass().getSimpleName(), getName(), myEngagementKind, myOrigin); } } private static class EngagedLanguage extends EngagedElement { private final LanguageRuntime myLang; EngagedLanguage(@NotNull LanguageRuntime lang, @Nullable EngagedElement origin, @Nullable Object engagementKind) { super(origin, engagementKind); myLang = lang; } public LanguageRuntime getLanguage() { return myLang; } // official lang name aka namespace public String getName() { return myLang.getNamespace(); } } private static class EngagedGenerator extends EngagedElement { private final TemplateModule myGenerator; EngagedGenerator(@NotNull TemplateModule generator, @NotNull EngagedElement origin, @Nullable Object engagementKind) { super(origin, engagementKind); myGenerator = generator; } public TemplateModule getGenerator() { return myGenerator; } public String getName() { return myGenerator.getAlias(); } } }
923e687500c14e02ddf8e084354b4effa0deb4fa
55,488
java
Java
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/ParentQueue.java
pranavbheda/hadoop
64f36b9543c011ce2f1f7d1e10da0eab88a0759d
[ "Apache-2.0", "BSD-2-Clause", "MIT", "MIT-0", "ECL-2.0", "BSD-3-Clause" ]
13
2017-03-07T04:29:42.000Z
2021-12-07T06:59:51.000Z
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/ParentQueue.java
pranavbheda/hadoop
64f36b9543c011ce2f1f7d1e10da0eab88a0759d
[ "Apache-2.0", "BSD-2-Clause", "MIT", "MIT-0", "ECL-2.0", "BSD-3-Clause" ]
15
2020-10-12T00:52:41.000Z
2021-08-08T03:58:42.000Z
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/ParentQueue.java
BobWuFall/hadoop
f5e49bc3d46aa98678ef5d15240afa65de29339d
[ "Apache-2.0" ]
10
2017-04-23T09:55:08.000Z
2021-12-31T18:42:41.000Z
38.884373
101
0.672974
1,000,747
/** * 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.yarn.server.resourcemanager.scheduler.capacity; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.hadoop.classification.InterfaceAudience.Private; import org.apache.hadoop.classification.InterfaceStability.Evolving; import org.apache.hadoop.security.AccessControlException; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.authorize.AccessControlList; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ContainerStatus; import org.apache.hadoop.yarn.api.records.ExecutionType; import org.apache.hadoop.yarn.api.records.QueueACL; import org.apache.hadoop.yarn.api.records.QueueInfo; import org.apache.hadoop.yarn.api.records.QueueState; import org.apache.hadoop.yarn.api.records.QueueUserACLInfo; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.api.records.ResourceInformation; import org.apache.hadoop.yarn.factories.RecordFactory; import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider; import org.apache.hadoop.yarn.security.AccessType; import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerEventType; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerState; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ActiveUsersManager; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.NodeType; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceLimits; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerApplicationAttempt; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerUtils; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.activities.ActivitiesLogger; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.activities.ActivityDiagnosticConstant; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.activities.ActivityState; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.activities.AllocationState; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.policy.QueueOrderingPolicy; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.ContainerAllocationProposal; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.ResourceCommitRequest; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.SchedulerContainer; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.fica.FiCaSchedulerApp; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.fica.FiCaSchedulerNode; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.placement.CandidateNodeSet; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.placement.CandidateNodeSetUtils; import org.apache.hadoop.yarn.util.UnitsConversionUtil; import org.apache.hadoop.yarn.util.resource.ResourceCalculator; import org.apache.hadoop.yarn.util.resource.ResourceUtils; import org.apache.hadoop.yarn.util.resource.Resources; @Private @Evolving public class ParentQueue extends AbstractCSQueue { private static final Logger LOG = LoggerFactory.getLogger(ParentQueue.class); protected final List<CSQueue> childQueues; private final boolean rootQueue; private volatile int numApplications; private final CapacitySchedulerContext scheduler; private final RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); private QueueOrderingPolicy queueOrderingPolicy; private long lastSkipQueueDebugLoggingTimestamp = -1; private int runnableApps; public ParentQueue(CapacitySchedulerContext cs, String queueName, CSQueue parent, CSQueue old) throws IOException { super(cs, queueName, parent, old); this.scheduler = cs; this.rootQueue = (parent == null); float rawCapacity = cs.getConfiguration().getNonLabeledQueueCapacity(getQueuePath()); if (rootQueue && (rawCapacity != CapacitySchedulerConfiguration.MAXIMUM_CAPACITY_VALUE)) { throw new IllegalArgumentException("Illegal " + "capacity of " + rawCapacity + " for queue " + queueName + ". Must be " + CapacitySchedulerConfiguration.MAXIMUM_CAPACITY_VALUE); } this.childQueues = new ArrayList<>(); setupQueueConfigs(cs.getClusterResource()); LOG.info("Initialized parent-queue " + queueName + " name=" + queueName + ", fullname=" + getQueuePath()); } // returns what is configured queue ordering policy private String getQueueOrderingPolicyConfigName() { return queueOrderingPolicy == null ? null : queueOrderingPolicy.getConfigName(); } protected void setupQueueConfigs(Resource clusterResource) throws IOException { writeLock.lock(); try { super.setupQueueConfigs(clusterResource); StringBuilder aclsString = new StringBuilder(); for (Map.Entry<AccessType, AccessControlList> e : acls.entrySet()) { aclsString.append(e.getKey() + ":" + e.getValue().getAclString()); } StringBuilder labelStrBuilder = new StringBuilder(); if (accessibleLabels != null) { for (String s : accessibleLabels) { labelStrBuilder.append(s) .append(","); } } // Initialize queue ordering policy queueOrderingPolicy = csContext.getConfiguration().getQueueOrderingPolicy( getQueuePath(), parent == null ? null : ((ParentQueue) parent).getQueueOrderingPolicyConfigName()); queueOrderingPolicy.setQueues(childQueues); LOG.info(queueName + ", capacity=" + this.queueCapacities.getCapacity() + ", absoluteCapacity=" + this.queueCapacities.getAbsoluteCapacity() + ", maxCapacity=" + this.queueCapacities.getMaximumCapacity() + ", absoluteMaxCapacity=" + this.queueCapacities .getAbsoluteMaximumCapacity() + ", state=" + getState() + ", acls=" + aclsString + ", labels=" + labelStrBuilder.toString() + "\n" + ", reservationsContinueLooking=" + reservationsContinueLooking + ", orderingPolicy=" + getQueueOrderingPolicyConfigName() + ", priority=" + priority); } finally { writeLock.unlock(); } } private static float PRECISION = 0.0005f; // 0.05% precision void setChildQueues(Collection<CSQueue> childQueues) { writeLock.lock(); try { // Validate float childCapacities = 0; Resource minResDefaultLabel = Resources.createResource(0, 0); for (CSQueue queue : childQueues) { childCapacities += queue.getCapacity(); Resources.addTo(minResDefaultLabel, queue.getQueueResourceQuotas() .getConfiguredMinResource()); // If any child queue is using percentage based capacity model vs parent // queues' absolute configuration or vice versa, throw back an // exception. if (!queueName.equals("root") && getCapacity() != 0f && !queue.getQueueResourceQuotas().getConfiguredMinResource() .equals(Resources.none())) { throw new IllegalArgumentException("Parent queue '" + getQueuePath() + "' and child queue '" + queue.getQueuePath() + "' should use either percentage based capacity" + " configuration or absolute resource together."); } } float delta = Math.abs(1.0f - childCapacities); // crude way to check // allow capacities being set to 0, and enforce child 0 if parent is 0 if ((minResDefaultLabel.equals(Resources.none()) && (queueCapacities.getCapacity() > 0) && (delta > PRECISION)) || ((queueCapacities.getCapacity() == 0) && (childCapacities > 0))) { throw new IllegalArgumentException("Illegal" + " capacity of " + childCapacities + " for children of queue " + queueName); } // check label capacities for (String nodeLabel : queueCapacities.getExistingNodeLabels()) { float capacityByLabel = queueCapacities.getCapacity(nodeLabel); // check children's labels float sum = 0; Resource minRes = Resources.createResource(0, 0); Resource resourceByLabel = labelManager.getResourceByLabel(nodeLabel, scheduler.getClusterResource()); for (CSQueue queue : childQueues) { sum += queue.getQueueCapacities().getCapacity(nodeLabel); // If any child queue of a label is using percentage based capacity // model vs parent queues' absolute configuration or vice versa, throw // back an exception if (!queueName.equals("root") && !this.capacityConfigType .equals(queue.getCapacityConfigType())) { throw new IllegalArgumentException("Parent queue '" + getQueuePath() + "' and child queue '" + queue.getQueuePath() + "' should use either percentage based capacity" + "configuration or absolute resource together for label:" + nodeLabel); } // Accumulate all min/max resource configured for all child queues. Resources.addTo(minRes, queue.getQueueResourceQuotas() .getConfiguredMinResource(nodeLabel)); } if ((minResDefaultLabel.equals(Resources.none()) && capacityByLabel > 0 && Math.abs(1.0f - sum) > PRECISION) || (capacityByLabel == 0) && (sum > 0)) { throw new IllegalArgumentException( "Illegal" + " capacity of " + sum + " for children of queue " + queueName + " for label=" + nodeLabel); } // Ensure that for each parent queue: parent.min-resource >= // Σ(child.min-resource). Resource parentMinResource = queueResourceQuotas .getConfiguredMinResource(nodeLabel); if (!parentMinResource.equals(Resources.none()) && Resources.lessThan( resourceCalculator, resourceByLabel, parentMinResource, minRes)) { throw new IllegalArgumentException("Parent Queues" + " capacity: " + parentMinResource + " is less than" + " to its children:" + minRes + " for queue:" + queueName); } } this.childQueues.clear(); this.childQueues.addAll(childQueues); if (LOG.isDebugEnabled()) { LOG.debug("setChildQueues: " + getChildQueuesToPrint()); } } finally { writeLock.unlock(); } } @Override public QueueInfo getQueueInfo( boolean includeChildQueues, boolean recursive) { readLock.lock(); try { QueueInfo queueInfo = getQueueInfo(); List<QueueInfo> childQueuesInfo = new ArrayList<>(); if (includeChildQueues) { for (CSQueue child : childQueues) { // Get queue information recursively? childQueuesInfo.add(child.getQueueInfo(recursive, recursive)); } } queueInfo.setChildQueues(childQueuesInfo); return queueInfo; } finally { readLock.unlock(); } } private QueueUserACLInfo getUserAclInfo( UserGroupInformation user) { readLock.lock(); try { QueueUserACLInfo userAclInfo = recordFactory.newRecordInstance( QueueUserACLInfo.class); List<QueueACL> operations = new ArrayList<QueueACL>(); for (QueueACL operation : QueueACL.values()) { if (hasAccess(operation, user)) { operations.add(operation); } } userAclInfo.setQueueName(getQueuePath()); userAclInfo.setUserAcls(operations); return userAclInfo; } finally { readLock.unlock(); } } @Override public List<QueueUserACLInfo> getQueueUserAclInfo( UserGroupInformation user) { readLock.lock(); try { List<QueueUserACLInfo> userAcls = new ArrayList<>(); // Add parent queue acls userAcls.add(getUserAclInfo(user)); // Add children queue acls for (CSQueue child : childQueues) { userAcls.addAll(child.getQueueUserAclInfo(user)); } return userAcls; } finally { readLock.unlock(); } } public String toString() { return queueName + ": " + "numChildQueue= " + childQueues.size() + ", " + "capacity=" + queueCapacities.getCapacity() + ", " + "absoluteCapacity=" + queueCapacities.getAbsoluteCapacity() + ", " + "usedResources=" + queueUsage.getUsed() + "usedCapacity=" + getUsedCapacity() + ", " + "numApps=" + getNumApplications() + ", " + "numContainers=" + getNumContainers(); } @Override public void reinitialize(CSQueue newlyParsedQueue, Resource clusterResource) throws IOException { writeLock.lock(); try { // Sanity check if (!(newlyParsedQueue instanceof ParentQueue) || !newlyParsedQueue .getQueuePath().equals(getQueuePath())) { throw new IOException( "Trying to reinitialize " + getQueuePath() + " from " + newlyParsedQueue.getQueuePath()); } ParentQueue newlyParsedParentQueue = (ParentQueue) newlyParsedQueue; // Set new configs setupQueueConfigs(clusterResource); // Re-configure existing child queues and add new ones // The CS has already checked to ensure all existing child queues are present! Map<String, CSQueue> currentChildQueues = getQueuesMap(childQueues); Map<String, CSQueue> newChildQueues = getQueuesMap( newlyParsedParentQueue.childQueues); for (Map.Entry<String, CSQueue> e : newChildQueues.entrySet()) { String newChildQueueName = e.getKey(); CSQueue newChildQueue = e.getValue(); CSQueue childQueue = currentChildQueues.get(newChildQueueName); // Check if the child-queue already exists if (childQueue != null) { // Check if the child-queue has been converted into parent queue or // parent Queue has been converted to child queue. The CS has already // checked to ensure that this child-queue is in STOPPED state if // Child queue has been converted to ParentQueue. if ((childQueue instanceof LeafQueue && newChildQueue instanceof ParentQueue) || (childQueue instanceof ParentQueue && newChildQueue instanceof LeafQueue)) { // We would convert this LeafQueue to ParentQueue, or vice versa. // consider this as the combination of DELETE then ADD. newChildQueue.setParent(this); currentChildQueues.put(newChildQueueName, newChildQueue); // inform CapacitySchedulerQueueManager CapacitySchedulerQueueManager queueManager = this.csContext.getCapacitySchedulerQueueManager(); queueManager.addQueue(newChildQueueName, newChildQueue); continue; } // Re-init existing queues childQueue.reinitialize(newChildQueue, clusterResource); LOG.info(getQueuePath() + ": re-configured queue: " + childQueue); } else{ // New child queue, do not re-init // Set parent to 'this' newChildQueue.setParent(this); // Save in list of current child queues currentChildQueues.put(newChildQueueName, newChildQueue); LOG.info( getQueuePath() + ": added new child queue: " + newChildQueue); } } // remove the deleted queue in the refreshed xml. for (Iterator<Map.Entry<String, CSQueue>> itr = currentChildQueues .entrySet().iterator(); itr.hasNext();) { Map.Entry<String, CSQueue> e = itr.next(); String queueName = e.getKey(); if (!newChildQueues.containsKey(queueName)) { itr.remove(); } } // Re-sort all queues childQueues.clear(); childQueues.addAll(currentChildQueues.values()); // Make sure we notifies QueueOrderingPolicy queueOrderingPolicy.setQueues(childQueues); } finally { writeLock.unlock(); } } private Map<String, CSQueue> getQueuesMap(List<CSQueue> queues) { Map<String, CSQueue> queuesMap = new HashMap<String, CSQueue>(); for (CSQueue queue : queues) { queuesMap.put(queue.getQueuePath(), queue); } return queuesMap; } @Override public void submitApplication(ApplicationId applicationId, String user, String queue) throws AccessControlException { writeLock.lock(); try { // Sanity check validateSubmitApplication(applicationId, user, queue); addApplication(applicationId, user); } finally { writeLock.unlock(); } // Inform the parent queue if (parent != null) { try { parent.submitApplication(applicationId, user, queue); } catch (AccessControlException ace) { LOG.info("Failed to submit application to parent-queue: " + parent.getQueuePath(), ace); removeApplication(applicationId, user); throw ace; } } } public void validateSubmitApplication(ApplicationId applicationId, String userName, String queue) throws AccessControlException { writeLock.lock(); try { if (queue.equals(queueName)) { throw new AccessControlException( "Cannot submit application " + "to non-leaf queue: " + queueName); } if (getState() != QueueState.RUNNING) { throw new AccessControlException("Queue " + getQueuePath() + " is STOPPED. Cannot accept submission of application: " + applicationId); } } finally { writeLock.unlock(); } } @Override public void submitApplicationAttempt(FiCaSchedulerApp application, String userName) { // submit attempt logic. } @Override public void submitApplicationAttempt(FiCaSchedulerApp application, String userName, boolean isMoveApp) { throw new UnsupportedOperationException("Submission of application attempt" + " to parent queue is not supported"); } @Override public void finishApplicationAttempt(FiCaSchedulerApp application, String queue) { // finish attempt logic. } private void addApplication(ApplicationId applicationId, String user) { writeLock.lock(); try { ++numApplications; LOG.info( "Application added -" + " appId: " + applicationId + " user: " + user + " leaf-queue of parent: " + getQueuePath() + " #applications: " + getNumApplications()); } finally { writeLock.unlock(); } } @Override public void finishApplication(ApplicationId application, String user) { removeApplication(application, user); appFinished(); // Inform the parent queue if (parent != null) { parent.finishApplication(application, user); } } private void removeApplication(ApplicationId applicationId, String user) { writeLock.lock(); try { --numApplications; LOG.info("Application removed -" + " appId: " + applicationId + " user: " + user + " leaf-queue of parent: " + getQueuePath() + " #applications: " + getNumApplications()); } finally { writeLock.unlock(); } } private String getParentName() { return getParent() != null ? getParent().getQueuePath() : ""; } @Override public CSAssignment assignContainers(Resource clusterResource, CandidateNodeSet<FiCaSchedulerNode> candidates, ResourceLimits resourceLimits, SchedulingMode schedulingMode) { FiCaSchedulerNode node = CandidateNodeSetUtils.getSingleNode(candidates); // if our queue cannot access this node, just return if (schedulingMode == SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY && !accessibleToPartition(candidates.getPartition())) { if (LOG.isDebugEnabled()) { long now = System.currentTimeMillis(); // Do logging every 1 sec to avoid excessive logging. if (now - this.lastSkipQueueDebugLoggingTimestamp > 1000) { LOG.debug("Skip this queue=" + getQueuePath() + ", because it is not able to access partition=" + candidates .getPartition()); this.lastSkipQueueDebugLoggingTimestamp = now; } } ActivitiesLogger.QUEUE.recordQueueActivity(activitiesManager, node, getParentName(), getQueuePath(), ActivityState.REJECTED, ActivityDiagnosticConstant.QUEUE_NOT_ABLE_TO_ACCESS_PARTITION); if (rootQueue) { ActivitiesLogger.NODE.finishSkippedNodeAllocation(activitiesManager, node); } return CSAssignment.NULL_ASSIGNMENT; } // Check if this queue need more resource, simply skip allocation if this // queue doesn't need more resources. if (!super.hasPendingResourceRequest(candidates.getPartition(), clusterResource, schedulingMode)) { if (LOG.isDebugEnabled()) { long now = System.currentTimeMillis(); // Do logging every 1 sec to avoid excessive logging. if (now - this.lastSkipQueueDebugLoggingTimestamp > 1000) { LOG.debug("Skip this queue=" + getQueuePath() + ", because it doesn't need more resource, schedulingMode=" + schedulingMode.name() + " node-partition=" + candidates .getPartition()); this.lastSkipQueueDebugLoggingTimestamp = now; } } ActivitiesLogger.QUEUE.recordQueueActivity(activitiesManager, node, getParentName(), getQueuePath(), ActivityState.SKIPPED, ActivityDiagnosticConstant.QUEUE_DO_NOT_NEED_MORE_RESOURCE); if (rootQueue) { ActivitiesLogger.NODE.finishSkippedNodeAllocation(activitiesManager, node); } return CSAssignment.NULL_ASSIGNMENT; } CSAssignment assignment = new CSAssignment(Resources.createResource(0, 0), NodeType.NODE_LOCAL); while (canAssign(clusterResource, node)) { LOG.debug("Trying to assign containers to child-queue of {}", getQueuePath()); // Are we over maximum-capacity for this queue? // This will also consider parent's limits and also continuous reservation // looking if (!super.canAssignToThisQueue(clusterResource, candidates.getPartition(), resourceLimits, Resources .createResource(getMetrics().getReservedMB(), getMetrics().getReservedVirtualCores()), schedulingMode)) { ActivitiesLogger.QUEUE.recordQueueActivity(activitiesManager, node, getParentName(), getQueuePath(), ActivityState.REJECTED, ActivityDiagnosticConstant.QUEUE_HIT_MAX_CAPACITY_LIMIT); if (rootQueue) { ActivitiesLogger.NODE.finishSkippedNodeAllocation(activitiesManager, node); } break; } // Schedule CSAssignment assignedToChild = assignContainersToChildQueues( clusterResource, candidates, resourceLimits, schedulingMode); assignment.setType(assignedToChild.getType()); assignment.setRequestLocalityType( assignedToChild.getRequestLocalityType()); assignment.setExcessReservation(assignedToChild.getExcessReservation()); assignment.setContainersToKill(assignedToChild.getContainersToKill()); assignment.setFulfilledReservation( assignedToChild.isFulfilledReservation()); assignment.setFulfilledReservedContainer( assignedToChild.getFulfilledReservedContainer()); // Done if no child-queue assigned anything if (Resources.greaterThan(resourceCalculator, clusterResource, assignedToChild.getResource(), Resources.none())) { ActivitiesLogger.QUEUE.recordQueueActivity(activitiesManager, node, getParentName(), getQueuePath(), ActivityState.ACCEPTED, ActivityDiagnosticConstant.EMPTY); boolean isReserved = assignedToChild.getAssignmentInformation().getReservationDetails() != null && !assignedToChild.getAssignmentInformation() .getReservationDetails().isEmpty(); if (rootQueue) { ActivitiesLogger.NODE.finishAllocatedNodeAllocation( activitiesManager, node, assignedToChild.getAssignmentInformation() .getFirstAllocatedOrReservedContainerId(), isReserved ? AllocationState.RESERVED : AllocationState.ALLOCATED); } // Track resource utilization in this pass of the scheduler Resources.addTo(assignment.getResource(), assignedToChild.getResource()); Resources.addTo(assignment.getAssignmentInformation().getAllocated(), assignedToChild.getAssignmentInformation().getAllocated()); Resources.addTo(assignment.getAssignmentInformation().getReserved(), assignedToChild.getAssignmentInformation().getReserved()); assignment.getAssignmentInformation().incrAllocations( assignedToChild.getAssignmentInformation().getNumAllocations()); assignment.getAssignmentInformation().incrReservations( assignedToChild.getAssignmentInformation().getNumReservations()); assignment.getAssignmentInformation().getAllocationDetails().addAll( assignedToChild.getAssignmentInformation() .getAllocationDetails()); assignment.getAssignmentInformation().getReservationDetails().addAll( assignedToChild.getAssignmentInformation() .getReservationDetails()); assignment.setIncreasedAllocation( assignedToChild.isIncreasedAllocation()); if (LOG.isDebugEnabled()) { LOG.debug("assignedContainer reserved=" + isReserved + " queue=" + getQueuePath() + " usedCapacity=" + getUsedCapacity() + " absoluteUsedCapacity=" + getAbsoluteUsedCapacity() + " used=" + queueUsage.getUsed() + " cluster=" + clusterResource); LOG.debug( "ParentQ=" + getQueuePath() + " assignedSoFarInThisIteration=" + assignment.getResource() + " usedCapacity=" + getUsedCapacity() + " absoluteUsedCapacity=" + getAbsoluteUsedCapacity()); } } else{ assignment.setSkippedType(assignedToChild.getSkippedType()); ActivitiesLogger.QUEUE.recordQueueActivity(activitiesManager, node, getParentName(), getQueuePath(), ActivityState.SKIPPED, ActivityDiagnosticConstant.EMPTY); if (rootQueue) { ActivitiesLogger.NODE.finishSkippedNodeAllocation(activitiesManager, node); } break; } /* * Previously here, we can allocate more than one container for each * allocation under rootQ. Now this logic is not proper any more * in global scheduling world. * * So here do not try to allocate more than one container for each * allocation, let top scheduler make the decision. */ break; } return assignment; } private boolean canAssign(Resource clusterResource, FiCaSchedulerNode node) { // When node == null means global scheduling is enabled, always return true if (null == node) { return true; } // Two conditions need to meet when trying to allocate: // 1) Node doesn't have reserved container // 2) Node's available-resource + killable-resource should > 0 boolean accept = node.getReservedContainer() == null && Resources .greaterThanOrEqual(resourceCalculator, clusterResource, Resources .add(node.getUnallocatedResource(), node.getTotalKillableResources()), minimumAllocation); if (!accept) { ActivitiesLogger.QUEUE.recordQueueActivity(activitiesManager, node, getParentName(), getQueuePath(), ActivityState.REJECTED, () -> node.getReservedContainer() != null ? ActivityDiagnosticConstant. QUEUE_SKIPPED_BECAUSE_SINGLE_NODE_RESERVED : ActivityDiagnosticConstant. QUEUE_SKIPPED_BECAUSE_SINGLE_NODE_RESOURCE_INSUFFICIENT); if (rootQueue) { ActivitiesLogger.NODE.finishSkippedNodeAllocation(activitiesManager, node); } } return accept; } private ResourceLimits getResourceLimitsOfChild(CSQueue child, Resource clusterResource, Resource parentLimits, String nodePartition) { // Set resource-limit of a given child, child.limit = // min(my.limit - my.used + child.used, child.max) // Parent available resource = parent-limit - parent-used-resource Resource parentMaxAvailableResource = Resources.subtract( parentLimits, queueUsage.getUsed(nodePartition)); // Deduct killable from used Resources.addTo(parentMaxAvailableResource, getTotalKillableResource(nodePartition)); // Child's limit = parent-available-resource + child-used Resource childLimit = Resources.add(parentMaxAvailableResource, child.getQueueResourceUsage().getUsed(nodePartition)); // Get child's max resource Resource childConfiguredMaxResource = child .getEffectiveMaxCapacityDown(nodePartition, minimumAllocation); // Child's limit should be capped by child configured max resource childLimit = Resources.min(resourceCalculator, clusterResource, childLimit, childConfiguredMaxResource); // Normalize before return childLimit = Resources.roundDown(resourceCalculator, childLimit, minimumAllocation); return new ResourceLimits(childLimit); } private Iterator<CSQueue> sortAndGetChildrenAllocationIterator( String partition) { return queueOrderingPolicy.getAssignmentIterator(partition); } private CSAssignment assignContainersToChildQueues(Resource cluster, CandidateNodeSet<FiCaSchedulerNode> candidates, ResourceLimits limits, SchedulingMode schedulingMode) { CSAssignment assignment = CSAssignment.NULL_ASSIGNMENT; printChildQueues(); // Try to assign to most 'under-served' sub-queue for (Iterator<CSQueue> iter = sortAndGetChildrenAllocationIterator( candidates.getPartition()); iter.hasNext(); ) { CSQueue childQueue = iter.next(); LOG.debug("Trying to assign to queue: {} stats: {}", childQueue.getQueuePath(), childQueue); // Get ResourceLimits of child queue before assign containers ResourceLimits childLimits = getResourceLimitsOfChild(childQueue, cluster, limits.getNetLimit(), candidates.getPartition()); CSAssignment childAssignment = childQueue.assignContainers(cluster, candidates, childLimits, schedulingMode); if(LOG.isDebugEnabled()) { LOG.debug("Assigned to queue: " + childQueue.getQueuePath() + " stats: " + childQueue + " --> " + childAssignment.getResource() + ", " + childAssignment.getType()); } if (Resources.greaterThan( resourceCalculator, cluster, childAssignment.getResource(), Resources.none())) { assignment = childAssignment; break; } else if (childAssignment.getSkippedType() == CSAssignment.SkippedType.QUEUE_LIMIT) { if (assignment.getSkippedType() != CSAssignment.SkippedType.QUEUE_LIMIT) { assignment = childAssignment; } Resource blockedHeadroom = null; if (childQueue instanceof LeafQueue) { blockedHeadroom = childLimits.getHeadroom(); } else { blockedHeadroom = childLimits.getBlockedHeadroom(); } Resource resourceToSubtract = Resources.max(resourceCalculator, cluster, blockedHeadroom, Resources.none()); limits.addBlockedHeadroom(resourceToSubtract); if(LOG.isDebugEnabled()) { LOG.debug("Decrease parentLimits " + limits.getLimit() + " for " + this.getQueuePath() + " by " + resourceToSubtract + " as childQueue=" + childQueue.getQueuePath() + " is blocked"); } } } return assignment; } String getChildQueuesToPrint() { StringBuilder sb = new StringBuilder(); for (CSQueue q : childQueues) { sb.append(q.getQueuePath() + "usedCapacity=(" + q.getUsedCapacity() + "), " + " label=(" + StringUtils.join(q.getAccessibleNodeLabels().iterator(), ",") + ")"); } return sb.toString(); } private void printChildQueues() { if (LOG.isDebugEnabled()) { LOG.debug("printChildQueues - queue: " + getQueuePath() + " child-queues: " + getChildQueuesToPrint()); } } private void internalReleaseResource(Resource clusterResource, FiCaSchedulerNode node, Resource releasedResource) { writeLock.lock(); try { super.releaseResource(clusterResource, releasedResource, node.getPartition()); LOG.debug("completedContainer {}, cluster={}", this, clusterResource); } finally { writeLock.unlock(); } } @Override public void completedContainer(Resource clusterResource, FiCaSchedulerApp application, FiCaSchedulerNode node, RMContainer rmContainer, ContainerStatus containerStatus, RMContainerEventType event, CSQueue completedChildQueue, boolean sortQueues) { if (application != null) { internalReleaseResource(clusterResource, node, rmContainer.getContainer().getResource()); // Inform the parent if (parent != null) { // complete my parent parent.completedContainer(clusterResource, application, node, rmContainer, null, event, this, sortQueues); } } } @Override public void updateClusterResource(Resource clusterResource, ResourceLimits resourceLimits) { writeLock.lock(); try { // Update effective capacity in all parent queue. Set<String> configuredNodelabels = csContext.getConfiguration() .getConfiguredNodeLabels(getQueuePath()); for (String label : configuredNodelabels) { calculateEffectiveResourcesAndCapacity(label, clusterResource); } // Update all children for (CSQueue childQueue : childQueues) { // Get ResourceLimits of child queue before assign containers ResourceLimits childLimits = getResourceLimitsOfChild(childQueue, clusterResource, resourceLimits.getLimit(), RMNodeLabelsManager.NO_LABEL); childQueue.updateClusterResource(clusterResource, childLimits); } CSQueueUtils.updateQueueStatistics(resourceCalculator, clusterResource, this, labelManager, null); // Update configured capacity/max-capacity for default partition only CSQueueUtils.updateConfiguredCapacityMetrics(resourceCalculator, labelManager.getResourceByLabel(null, clusterResource), RMNodeLabelsManager.NO_LABEL, this); } finally { writeLock.unlock(); } } @Override public boolean hasChildQueues() { return true; } private void calculateEffectiveResourcesAndCapacity(String label, Resource clusterResource) { // For root queue, ensure that max/min resource is updated to latest // cluster resource. Resource resourceByLabel = labelManager.getResourceByLabel(label, clusterResource); if (getQueuePath().equals("root")) { queueResourceQuotas.setConfiguredMinResource(label, resourceByLabel); queueResourceQuotas.setConfiguredMaxResource(label, resourceByLabel); queueResourceQuotas.setEffectiveMinResource(label, resourceByLabel); queueResourceQuotas.setEffectiveMaxResource(label, resourceByLabel); queueCapacities.setAbsoluteCapacity(label, 1.0f); } // Total configured min resources of direct children of this given parent // queue. Resource configuredMinResources = Resource.newInstance(0L, 0); for (CSQueue childQueue : getChildQueues()) { Resources.addTo(configuredMinResources, childQueue.getQueueResourceQuotas().getConfiguredMinResource(label)); } // Factor to scale down effective resource: When cluster has sufficient // resources, effective_min_resources will be same as configured // min_resources. Resource numeratorForMinRatio = null; ResourceCalculator rc = this.csContext.getResourceCalculator(); if (getQueuePath().equals("root")) { if (!resourceByLabel.equals(Resources.none()) && Resources.lessThan(rc, clusterResource, resourceByLabel, configuredMinResources)) { numeratorForMinRatio = resourceByLabel; } } else { if (Resources.lessThan(rc, clusterResource, queueResourceQuotas.getEffectiveMinResource(label), configuredMinResources)) { numeratorForMinRatio = queueResourceQuotas .getEffectiveMinResource(label); } } Map<String, Float> effectiveMinRatioPerResource = getEffectiveMinRatioPerResource( configuredMinResources, numeratorForMinRatio); // loop and do this for all child queues for (CSQueue childQueue : getChildQueues()) { Resource minResource = childQueue.getQueueResourceQuotas() .getConfiguredMinResource(label); // Update effective resource (min/max) to each child queue. if (childQueue.getCapacityConfigType() .equals(CapacityConfigType.ABSOLUTE_RESOURCE)) { childQueue.getQueueResourceQuotas().setEffectiveMinResource(label, getMinResourceNormalized( childQueue.getQueuePath(), effectiveMinRatioPerResource, minResource)); // Max resource of a queue should be a minimum of {configuredMaxRes, // parentMaxRes}. parentMaxRes could be configured value. But if not // present could also be taken from effective max resource of parent. Resource parentMaxRes = queueResourceQuotas .getConfiguredMaxResource(label); if (parent != null && parentMaxRes.equals(Resources.none())) { parentMaxRes = parent.getQueueResourceQuotas() .getEffectiveMaxResource(label); } // Minimum of {childMaxResource, parentMaxRes}. However if // childMaxResource is empty, consider parent's max resource alone. Resource childMaxResource = childQueue.getQueueResourceQuotas() .getConfiguredMaxResource(label); Resource effMaxResource = Resources.min(resourceCalculator, resourceByLabel, childMaxResource.equals(Resources.none()) ? parentMaxRes : childMaxResource, parentMaxRes); childQueue.getQueueResourceQuotas().setEffectiveMaxResource(label, Resources.clone(effMaxResource)); // In cases where we still need to update some units based on // percentage, we have to calculate percentage and update. deriveCapacityFromAbsoluteConfigurations(label, clusterResource, rc, childQueue); } else { childQueue.getQueueResourceQuotas().setEffectiveMinResource(label, Resources.multiply(resourceByLabel, childQueue.getQueueCapacities().getAbsoluteCapacity(label))); childQueue.getQueueResourceQuotas().setEffectiveMaxResource(label, Resources.multiply(resourceByLabel, childQueue.getQueueCapacities() .getAbsoluteMaximumCapacity(label))); } if (LOG.isDebugEnabled()) { LOG.debug("Updating effective min resource for queue:" + childQueue.getQueuePath() + " as effMinResource=" + childQueue.getQueueResourceQuotas().getEffectiveMinResource(label) + "and Updating effective max resource as effMaxResource=" + childQueue.getQueueResourceQuotas() .getEffectiveMaxResource(label)); } } } private Resource getMinResourceNormalized(String name, Map<String, Float> effectiveMinRatio, Resource minResource) { Resource ret = Resource.newInstance(minResource); int maxLength = ResourceUtils.getNumberOfCountableResourceTypes(); for (int i = 0; i < maxLength; i++) { ResourceInformation nResourceInformation = minResource .getResourceInformation(i); Float ratio = effectiveMinRatio.get(nResourceInformation.getName()); if (ratio != null) { ret.setResourceValue(i, (long) (nResourceInformation.getValue() * ratio.floatValue())); if (LOG.isDebugEnabled()) { LOG.debug("Updating min resource for Queue: " + name + " as " + ret.getResourceInformation(i) + ", Actual resource: " + nResourceInformation.getValue() + ", ratio: " + ratio.floatValue()); } } } return ret; } private Map<String, Float> getEffectiveMinRatioPerResource( Resource configuredMinResources, Resource numeratorForMinRatio) { Map<String, Float> effectiveMinRatioPerResource = new HashMap<>(); if (numeratorForMinRatio != null) { int maxLength = ResourceUtils.getNumberOfCountableResourceTypes(); for (int i = 0; i < maxLength; i++) { ResourceInformation nResourceInformation = numeratorForMinRatio .getResourceInformation(i); ResourceInformation dResourceInformation = configuredMinResources .getResourceInformation(i); long nValue = nResourceInformation.getValue(); long dValue = UnitsConversionUtil.convert( dResourceInformation.getUnits(), nResourceInformation.getUnits(), dResourceInformation.getValue()); if (dValue != 0) { effectiveMinRatioPerResource.put(nResourceInformation.getName(), (float) nValue / dValue); } } } return effectiveMinRatioPerResource; } private void deriveCapacityFromAbsoluteConfigurations(String label, Resource clusterResource, ResourceCalculator rc, CSQueue childQueue) { /* * In case when queues are configured with absolute resources, it is better * to update capacity/max-capacity etc w.r.t absolute resource as well. In * case of computation, these values wont be used any more. However for * metrics and UI, its better these values are pre-computed here itself. */ // 1. Update capacity as a float based on parent's minResource childQueue.getQueueCapacities().setCapacity(label, rc.divide(clusterResource, childQueue.getQueueResourceQuotas().getEffectiveMinResource(label), getQueueResourceQuotas().getEffectiveMinResource(label))); // 2. Update max-capacity as a float based on parent's maxResource childQueue.getQueueCapacities().setMaximumCapacity(label, rc.divide(clusterResource, childQueue.getQueueResourceQuotas().getEffectiveMaxResource(label), getQueueResourceQuotas().getEffectiveMaxResource(label))); // 3. Update absolute capacity as a float based on parent's minResource and // cluster resource. childQueue.getQueueCapacities().setAbsoluteCapacity(label, childQueue.getQueueCapacities().getCapacity(label) * getQueueCapacities().getAbsoluteCapacity(label)); // 4. Update absolute max-capacity as a float based on parent's maxResource // and cluster resource. childQueue.getQueueCapacities().setAbsoluteMaximumCapacity(label, childQueue.getQueueCapacities().getMaximumCapacity(label) * getQueueCapacities().getAbsoluteMaximumCapacity(label)); // Re-visit max applications for a queue based on absolute capacity if // needed. if (childQueue instanceof LeafQueue) { LeafQueue leafQueue = (LeafQueue) childQueue; CapacitySchedulerConfiguration conf = csContext.getConfiguration(); int maxApplications = conf.getMaximumApplicationsPerQueue(childQueue.getQueuePath()); if (maxApplications < 0) { int maxGlobalPerQueueApps = conf.getGlobalMaximumApplicationsPerQueue(); if (maxGlobalPerQueueApps > 0) { maxApplications = (int) (maxGlobalPerQueueApps * childQueue.getQueueCapacities().getAbsoluteCapacity(label)); } else { maxApplications = (int) (conf.getMaximumSystemApplications() * childQueue.getQueueCapacities().getAbsoluteCapacity(label)); } } leafQueue.setMaxApplications(maxApplications); int maxApplicationsPerUser = Math.min(maxApplications, (int) (maxApplications * (leafQueue.getUsersManager().getUserLimit() / 100.0f) * leafQueue.getUsersManager().getUserLimitFactor())); leafQueue.setMaxApplicationsPerUser(maxApplicationsPerUser); LOG.info("LeafQueue:" + leafQueue.getQueuePath() + ", maxApplications=" + maxApplications + ", maxApplicationsPerUser=" + maxApplicationsPerUser + ", Abs Cap:" + childQueue.getQueueCapacities().getAbsoluteCapacity(label) + ", Cap: " + childQueue.getQueueCapacities().getCapacity(label) + ", MaxCap : " + childQueue.getQueueCapacities().getMaximumCapacity(label)); } } @Override public List<CSQueue> getChildQueues() { readLock.lock(); try { return new ArrayList<CSQueue>(childQueues); } finally { readLock.unlock(); } } @Override public void recoverContainer(Resource clusterResource, SchedulerApplicationAttempt attempt, RMContainer rmContainer) { if (rmContainer.getState().equals(RMContainerState.COMPLETED)) { return; } if (rmContainer.getExecutionType() != ExecutionType.GUARANTEED) { return; } // Careful! Locking order is important! writeLock.lock(); try { FiCaSchedulerNode node = scheduler.getNode( rmContainer.getContainer().getNodeId()); allocateResource(clusterResource, rmContainer.getContainer().getResource(), node.getPartition()); } finally { writeLock.unlock(); } if (parent != null) { parent.recoverContainer(clusterResource, attempt, rmContainer); } } @Override public ActiveUsersManager getAbstractUsersManager() { // Should never be called since all applications are submitted to LeafQueues return null; } @Override public void collectSchedulerApplications( Collection<ApplicationAttemptId> apps) { readLock.lock(); try { for (CSQueue queue : childQueues) { queue.collectSchedulerApplications(apps); } } finally { readLock.unlock(); } } @Override public void attachContainer(Resource clusterResource, FiCaSchedulerApp application, RMContainer rmContainer) { if (application != null) { FiCaSchedulerNode node = scheduler.getNode(rmContainer.getContainer().getNodeId()); allocateResource(clusterResource, rmContainer.getContainer() .getResource(), node.getPartition()); LOG.info("movedContainer" + " queueMoveIn=" + getQueuePath() + " usedCapacity=" + getUsedCapacity() + " absoluteUsedCapacity=" + getAbsoluteUsedCapacity() + " used=" + queueUsage.getUsed() + " cluster=" + clusterResource); // Inform the parent if (parent != null) { parent.attachContainer(clusterResource, application, rmContainer); } } } @Override public void detachContainer(Resource clusterResource, FiCaSchedulerApp application, RMContainer rmContainer) { if (application != null) { FiCaSchedulerNode node = scheduler.getNode(rmContainer.getContainer().getNodeId()); super.releaseResource(clusterResource, rmContainer.getContainer().getResource(), node.getPartition()); LOG.info("movedContainer" + " queueMoveOut=" + getQueuePath() + " usedCapacity=" + getUsedCapacity() + " absoluteUsedCapacity=" + getAbsoluteUsedCapacity() + " used=" + queueUsage.getUsed() + " cluster=" + clusterResource); // Inform the parent if (parent != null) { parent.detachContainer(clusterResource, application, rmContainer); } } } public int getNumApplications() { return numApplications; } void allocateResource(Resource clusterResource, Resource resource, String nodePartition) { writeLock.lock(); try { super.allocateResource(clusterResource, resource, nodePartition); /** * check if we need to kill (killable) containers if maximum resource violated. * Doing this because we will deduct killable resource when going from root. * For example: * <pre> * Root * / \ * a b * / \ * a1 a2 * </pre> * * a: max=10G, used=10G, killable=2G * a1: used=8G, killable=2G * a2: used=2G, pending=2G, killable=0G * * When we get queue-a to allocate resource, even if queue-a * reaches its max resource, we deduct its used by killable, so we can allocate * at most 2G resources. ResourceLimits passed down to a2 has headroom set to 2G. * * If scheduler finds a 2G available resource in existing cluster, and assigns it * to a2, now a2's used= 2G + 2G = 4G, and a's used = 8G + 4G = 12G > 10G * * When this happens, we have to preempt killable container (on same or different * nodes) of parent queue to avoid violating parent's max resource. */ if (!queueResourceQuotas.getEffectiveMaxResource(nodePartition) .equals(Resources.none())) { if (Resources.lessThan(resourceCalculator, clusterResource, queueResourceQuotas.getEffectiveMaxResource(nodePartition), queueUsage.getUsed(nodePartition))) { killContainersToEnforceMaxQueueCapacity(nodePartition, clusterResource); } } else { if (getQueueCapacities() .getAbsoluteMaximumCapacity(nodePartition) < getQueueCapacities() .getAbsoluteUsedCapacity(nodePartition)) { killContainersToEnforceMaxQueueCapacity(nodePartition, clusterResource); } } } finally { writeLock.unlock(); } } private void killContainersToEnforceMaxQueueCapacity(String partition, Resource clusterResource) { Iterator<RMContainer> killableContainerIter = getKillableContainers( partition); if (!killableContainerIter.hasNext()) { return; } Resource partitionResource = labelManager.getResourceByLabel(partition, null); Resource maxResource = getEffectiveMaxCapacity(partition); while (Resources.greaterThan(resourceCalculator, partitionResource, queueUsage.getUsed(partition), maxResource)) { RMContainer toKillContainer = killableContainerIter.next(); FiCaSchedulerApp attempt = csContext.getApplicationAttempt( toKillContainer.getContainerId().getApplicationAttemptId()); FiCaSchedulerNode node = csContext.getNode( toKillContainer.getAllocatedNode()); if (null != attempt && null != node) { LeafQueue lq = attempt.getCSLeafQueue(); lq.completedContainer(clusterResource, attempt, node, toKillContainer, SchedulerUtils.createPreemptedContainerStatus( toKillContainer.getContainerId(), SchedulerUtils.PREEMPTED_CONTAINER), RMContainerEventType.KILL, null, false); LOG.info("Killed container=" + toKillContainer.getContainerId() + " from queue=" + lq.getQueuePath() + " to make queue=" + this .getQueuePath() + "'s max-capacity enforced"); } if (!killableContainerIter.hasNext()) { break; } } } public void apply(Resource cluster, ResourceCommitRequest<FiCaSchedulerApp, FiCaSchedulerNode> request) { if (request.anythingAllocatedOrReserved()) { ContainerAllocationProposal<FiCaSchedulerApp, FiCaSchedulerNode> allocation = request.getFirstAllocatedOrReservedContainer(); SchedulerContainer<FiCaSchedulerApp, FiCaSchedulerNode> schedulerContainer = allocation.getAllocatedOrReservedContainer(); // Do not modify queue when allocation from reserved container if (allocation.getAllocateFromReservedContainer() == null) { writeLock.lock(); try { // Book-keeping // Note: Update headroom to account for current allocation too... allocateResource(cluster, allocation.getAllocatedOrReservedResource(), schedulerContainer.getNodePartition()); LOG.info("assignedContainer" + " queue=" + getQueuePath() + " usedCapacity=" + getUsedCapacity() + " absoluteUsedCapacity=" + getAbsoluteUsedCapacity() + " used=" + queueUsage.getUsed() + " cluster=" + cluster); } finally { writeLock.unlock(); } } } if (parent != null) { parent.apply(cluster, request); } } @Override public void stopQueue() { this.writeLock.lock(); try { if (getNumApplications() > 0) { updateQueueState(QueueState.DRAINING); } else { updateQueueState(QueueState.STOPPED); } if (getChildQueues() != null) { for(CSQueue child : getChildQueues()) { child.stopQueue(); } } } finally { this.writeLock.unlock(); } } public QueueOrderingPolicy getQueueOrderingPolicy() { return queueOrderingPolicy; } @Override int getNumRunnableApps() { readLock.lock(); try { return runnableApps; } finally { readLock.unlock(); } } void incrementRunnableApps() { writeLock.lock(); try { runnableApps++; } finally { writeLock.unlock(); } } void decrementRunnableApps() { writeLock.lock(); try { runnableApps--; } finally { writeLock.unlock(); } } }
923e68df13e6294c8f443f770824e816f3a80005
4,491
java
Java
modules/measure/src/test/java/com/opengamma/strata/measure/swap/SwapTradeCalculationsTest.java
LALAYANG/Strata
7a3f9613913b383446d862c4606b5fbf59aaa213
[ "Apache-2.0" ]
696
2015-07-15T12:09:50.000Z
2022-03-27T15:05:05.000Z
modules/measure/src/test/java/com/opengamma/strata/measure/swap/SwapTradeCalculationsTest.java
LALAYANG/Strata
7a3f9613913b383446d862c4606b5fbf59aaa213
[ "Apache-2.0" ]
562
2015-07-17T11:31:08.000Z
2022-03-29T16:15:39.000Z
modules/measure/src/test/java/com/opengamma/strata/measure/swap/SwapTradeCalculationsTest.java
LALAYANG/Strata
7a3f9613913b383446d862c4606b5fbf59aaa213
[ "Apache-2.0" ]
315
2015-07-18T20:53:45.000Z
2022-03-06T02:04:13.000Z
54.768293
106
0.799377
1,000,748
/* * Copyright (C) 2016 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.strata.measure.swap; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; import com.google.common.collect.ImmutableList; import com.opengamma.strata.basics.currency.MultiCurrencyAmount; import com.opengamma.strata.data.scenario.DoubleScenarioArray; import com.opengamma.strata.data.scenario.MultiCurrencyScenarioArray; import com.opengamma.strata.data.scenario.ScenarioArray; import com.opengamma.strata.data.scenario.ScenarioMarketData; import com.opengamma.strata.market.amount.CashFlows; import com.opengamma.strata.market.explain.ExplainMap; import com.opengamma.strata.market.param.CurrencyParameterSensitivities; import com.opengamma.strata.market.sensitivity.PointSensitivities; import com.opengamma.strata.measure.rate.RatesMarketDataLookup; import com.opengamma.strata.pricer.rate.RatesProvider; import com.opengamma.strata.pricer.swap.DiscountingSwapTradePricer; import com.opengamma.strata.product.swap.ResolvedSwapTrade; /** * Test {@link SwapTradeCalculations}. */ public class SwapTradeCalculationsTest { private static final ResolvedSwapTrade RTRADE = SwapTradeCalculationFunctionTest.RTRADE; private static final RatesMarketDataLookup RATES_LOOKUP = SwapTradeCalculationFunctionTest.RATES_LOOKUP; //------------------------------------------------------------------------- @Test public void test_presentValue() { ScenarioMarketData md = SwapTradeCalculationFunctionTest.marketData(); RatesProvider provider = RATES_LOOKUP.marketDataView(md.scenario(0)).ratesProvider(); DiscountingSwapTradePricer pricer = DiscountingSwapTradePricer.DEFAULT; MultiCurrencyAmount expectedPv = pricer.presentValue(RTRADE, provider); ExplainMap expectedExplainPv = pricer.explainPresentValue(RTRADE, provider); double expectedParRate = pricer.parRate(RTRADE, provider); double expectedParSpread = pricer.parSpread(RTRADE, provider); CashFlows expectedCashFlows = pricer.cashFlows(RTRADE, provider); MultiCurrencyAmount expectedCurrencyExposure = pricer.currencyExposure(RTRADE, provider); MultiCurrencyAmount expectedCurrentCash = pricer.currentCash(RTRADE, provider); assertThat(SwapTradeCalculations.DEFAULT.presentValue(RTRADE, RATES_LOOKUP, md)) .isEqualTo(MultiCurrencyScenarioArray.of(ImmutableList.of(expectedPv))); assertThat(SwapTradeCalculations.DEFAULT.explainPresentValue(RTRADE, RATES_LOOKUP, md)) .isEqualTo(ScenarioArray.of(ImmutableList.of(expectedExplainPv))); assertThat(SwapTradeCalculations.DEFAULT.parRate(RTRADE, RATES_LOOKUP, md)) .isEqualTo(DoubleScenarioArray.of(ImmutableList.of(expectedParRate))); assertThat(SwapTradeCalculations.DEFAULT.parSpread(RTRADE, RATES_LOOKUP, md)) .isEqualTo(DoubleScenarioArray.of(ImmutableList.of(expectedParSpread))); assertThat(SwapTradeCalculations.DEFAULT.cashFlows(RTRADE, RATES_LOOKUP, md)) .isEqualTo(ScenarioArray.of(ImmutableList.of(expectedCashFlows))); assertThat(SwapTradeCalculations.DEFAULT.currencyExposure(RTRADE, RATES_LOOKUP, md)) .isEqualTo(MultiCurrencyScenarioArray.of(ImmutableList.of(expectedCurrencyExposure))); assertThat(SwapTradeCalculations.DEFAULT.currentCash(RTRADE, RATES_LOOKUP, md)) .isEqualTo(MultiCurrencyScenarioArray.of(ImmutableList.of(expectedCurrentCash))); } @Test public void test_pv01() { ScenarioMarketData md = SwapTradeCalculationFunctionTest.marketData(); RatesProvider provider = RATES_LOOKUP.marketDataView(md.scenario(0)).ratesProvider(); DiscountingSwapTradePricer pricer = DiscountingSwapTradePricer.DEFAULT; PointSensitivities pvPointSens = pricer.presentValueSensitivity(RTRADE, provider); CurrencyParameterSensitivities pvParamSens = provider.parameterSensitivity(pvPointSens); MultiCurrencyAmount expectedPv01Cal = pvParamSens.total().multipliedBy(1e-4); CurrencyParameterSensitivities expectedPv01CalBucketed = pvParamSens.multipliedBy(1e-4); assertThat(SwapTradeCalculations.DEFAULT.pv01CalibratedSum(RTRADE, RATES_LOOKUP, md)) .isEqualTo(MultiCurrencyScenarioArray.of(ImmutableList.of(expectedPv01Cal))); assertThat(SwapTradeCalculations.DEFAULT.pv01CalibratedBucketed(RTRADE, RATES_LOOKUP, md)) .isEqualTo(ScenarioArray.of(ImmutableList.of(expectedPv01CalBucketed))); } }
923e68e1c9b672ef55b5bd37ed627a38f582101a
9,673
java
Java
core/common/src/test/java/org/onosproject/store/trivial/SimpleHostStore.java
mary-grace/onos
c0e351f8b84537bb7562e148d4cb2b9f06e8a727
[ "Apache-2.0" ]
1,091
2015-01-06T11:10:40.000Z
2022-03-30T09:09:05.000Z
core/common/src/test/java/org/onosproject/store/trivial/SimpleHostStore.java
mary-grace/onos
c0e351f8b84537bb7562e148d4cb2b9f06e8a727
[ "Apache-2.0" ]
39
2015-02-13T19:58:32.000Z
2022-03-02T02:38:07.000Z
core/common/src/test/java/org/onosproject/store/trivial/SimpleHostStore.java
mary-grace/onos
c0e351f8b84537bb7562e148d4cb2b9f06e8a727
[ "Apache-2.0" ]
914
2015-01-05T19:42:35.000Z
2022-03-30T09:25:18.000Z
34.546429
95
0.608084
1,000,749
/* * Copyright 2015-present Open Networking 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 org.onosproject.store.trivial; import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Multimap; import org.onlab.packet.IpAddress; import org.onlab.packet.MacAddress; import org.onlab.packet.VlanId; import org.onosproject.net.Annotations; import org.onosproject.net.ConnectPoint; import org.onosproject.net.DefaultAnnotations; import org.onosproject.net.DefaultHost; import org.onosproject.net.DeviceId; import org.onosproject.net.Host; import org.onosproject.net.HostId; import org.onosproject.net.HostLocation; import org.onosproject.net.host.HostDescription; import org.onosproject.net.host.HostEvent; import org.onosproject.net.host.HostStore; import org.onosproject.net.host.HostStoreDelegate; import org.onosproject.net.provider.ProviderId; import org.onosproject.store.AbstractStore; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Deactivate; import org.slf4j.Logger; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import static org.onosproject.net.DefaultAnnotations.merge; import static org.onosproject.net.host.HostEvent.Type.HOST_ADDED; import static org.onosproject.net.host.HostEvent.Type.HOST_MOVED; import static org.onosproject.net.host.HostEvent.Type.HOST_REMOVED; import static org.onosproject.net.host.HostEvent.Type.HOST_UPDATED; import static org.slf4j.LoggerFactory.getLogger; // TODO: multi-provider, annotation not supported. /** * Manages inventory of end-station hosts using trivial in-memory * implementation. */ @Component(immediate = true, service = HostStore.class) public class SimpleHostStore extends AbstractStore<HostEvent, HostStoreDelegate> implements HostStore { private final Logger log = getLogger(getClass()); // Host inventory private final Map<HostId, StoredHost> hosts = new ConcurrentHashMap<>(2000000, 0.75f, 16); // Hosts tracked by their location private final Multimap<ConnectPoint, Host> locations = HashMultimap.create(); @Activate public void activate() { log.info("Started"); } @Deactivate public void deactivate() { log.info("Stopped"); } @Override public HostEvent createOrUpdateHost(ProviderId providerId, HostId hostId, HostDescription hostDescription, boolean replaceIps) { //TODO We need a way to detect conflicting changes and abort update. StoredHost host = hosts.get(hostId); HostEvent hostEvent; if (host == null) { hostEvent = createHost(providerId, hostId, hostDescription); } else { hostEvent = updateHost(providerId, host, hostDescription, replaceIps); } notifyDelegate(hostEvent); return hostEvent; } // creates a new host and sends HOST_ADDED private HostEvent createHost(ProviderId providerId, HostId hostId, HostDescription descr) { StoredHost newhost = new StoredHost(providerId, hostId, descr.hwAddress(), descr.vlan(), descr.location(), ImmutableSet.copyOf(descr.ipAddress()), descr.configured(), descr.annotations()); synchronized (this) { hosts.put(hostId, newhost); locations.put(descr.location(), newhost); } return new HostEvent(HOST_ADDED, newhost); } // checks for type of update to host, sends appropriate event private HostEvent updateHost(ProviderId providerId, StoredHost host, HostDescription descr, boolean replaceIps) { HostEvent event; if (!host.location().equals(descr.location())) { host.setLocation(descr.location()); return new HostEvent(HOST_MOVED, host); } if (host.ipAddresses().containsAll(descr.ipAddress()) && descr.annotations().keys().isEmpty()) { return null; } final Set<IpAddress> addresses; if (replaceIps) { addresses = ImmutableSet.copyOf(descr.ipAddress()); } else { addresses = new HashSet<>(host.ipAddresses()); addresses.addAll(descr.ipAddress()); } Annotations annotations = merge((DefaultAnnotations) host.annotations(), descr.annotations()); StoredHost updated = new StoredHost(providerId, host.id(), host.mac(), host.vlan(), descr.location(), addresses, descr.configured(), annotations); event = new HostEvent(HOST_UPDATED, updated); synchronized (this) { hosts.put(host.id(), updated); locations.remove(host.location(), host); locations.put(updated.location(), updated); } return event; } @Override public HostEvent removeHost(HostId hostId) { synchronized (this) { Host host = hosts.remove(hostId); if (host != null) { locations.remove((host.location()), host); HostEvent hostEvent = new HostEvent(HOST_REMOVED, host); notifyDelegate(hostEvent); return hostEvent; } return null; } } @Override public HostEvent removeIp(HostId hostId, IpAddress ipAddress) { // TODO implement this return null; } @Override public void appendLocation(HostId hostId, HostLocation location) { hosts.get(hostId).locations().add(location); } @Override public void removeLocation(HostId hostId, HostLocation location) { hosts.get(hostId).locations().remove(location); } @Override public int getHostCount() { return hosts.size(); } @Override public Iterable<Host> getHosts() { return ImmutableSet.copyOf(hosts.values()); } @Override public Host getHost(HostId hostId) { return hosts.get(hostId); } @Override public Set<Host> getHosts(VlanId vlanId) { Set<Host> vlanset = new HashSet<>(); for (Host h : hosts.values()) { if (h.vlan().equals(vlanId)) { vlanset.add(h); } } return vlanset; } @Override public Set<Host> getHosts(MacAddress mac) { Set<Host> macset = new HashSet<>(); for (Host h : hosts.values()) { if (h.mac().equals(mac)) { macset.add(h); } } return macset; } @Override public Set<Host> getHosts(IpAddress ip) { Set<Host> ipset = new HashSet<>(); for (Host h : hosts.values()) { if (h.ipAddresses().contains(ip)) { ipset.add(h); } } return ipset; } @Override public Set<Host> getConnectedHosts(ConnectPoint connectPoint) { return ImmutableSet.copyOf(locations.get(connectPoint)); } @Override public Set<Host> getConnectedHosts(DeviceId deviceId) { Set<Host> hostset = new HashSet<>(); for (ConnectPoint p : locations.keySet()) { if (p.deviceId().equals(deviceId)) { hostset.addAll(locations.get(p)); } } return hostset; } // Auxiliary extension to allow location to mutate. private static final class StoredHost extends DefaultHost { private HostLocation location; /** * Creates an end-station host using the supplied information. * * @param providerId provider identity * @param id host identifier * @param mac host MAC address * @param vlan host VLAN identifier * @param location host location * @param ips host IP addresses * @param annotations optional key/value annotations */ public StoredHost(ProviderId providerId, HostId id, MacAddress mac, VlanId vlan, HostLocation location, Set<IpAddress> ips, boolean configured, Annotations... annotations) { super(providerId, id, mac, vlan, location, ips, configured, annotations); this.location = location; } void setLocation(HostLocation location) { this.location = location; } @Override public HostLocation location() { return location; } } }
923e695d2c76b4b01a2a4ac960c3545d0a3f7252
290
java
Java
ssm-chapter11/src/main/java/com/learn/ssm/chapter11/aop/verifier/impl/RoleVerifierImpl.java
luonianxin/SSM-Study
2648f77d5260b0f571937932d5076a79e2acdea6
[ "MIT" ]
1
2020-09-30T06:31:14.000Z
2020-09-30T06:31:14.000Z
ssm-chapter11/src/main/java/com/learn/ssm/chapter11/aop/verifier/impl/RoleVerifierImpl.java
luonianxin/ssm-study
ce70b0ab6b60a79d07c3eb4eef43322888e8bfb8
[ "MIT" ]
null
null
null
ssm-chapter11/src/main/java/com/learn/ssm/chapter11/aop/verifier/impl/RoleVerifierImpl.java
luonianxin/ssm-study
ce70b0ab6b60a79d07c3eb4eef43322888e8bfb8
[ "MIT" ]
null
null
null
26.363636
57
0.755172
1,000,750
package com.learn.ssm.chapter11.aop.verifier.impl; import com.learn.ssm.chapter11.aop.verifier.RoleVerifier; import com.learn.ssm.chapter11.game.pojo.Role; public class RoleVerifierImpl implements RoleVerifier { public boolean verify(Role role) { return role != null; } }
923e6a2c11d2a8335487f192d072296c0a05baba
13,862
java
Java
src/main/java/com/networknt/oas/model/Schema.java
BalloonWen/openapi-parser
33077a69679a82e1d22affcb20ebf0fd888468f0
[ "Apache-2.0" ]
null
null
null
src/main/java/com/networknt/oas/model/Schema.java
BalloonWen/openapi-parser
33077a69679a82e1d22affcb20ebf0fd888468f0
[ "Apache-2.0" ]
null
null
null
src/main/java/com/networknt/oas/model/Schema.java
BalloonWen/openapi-parser
33077a69679a82e1d22affcb20ebf0fd888468f0
[ "Apache-2.0" ]
null
null
null
30.332604
84
0.794474
1,000,751
package com.networknt.oas.model; import java.util.List; import java.util.Map; import javax.annotation.Generated; import com.networknt.jsonoverlay.IJsonOverlay; import com.networknt.jsonoverlay.IModelPart; public interface Schema extends IJsonOverlay<Schema>, IModelPart<OpenApi3, Schema> { String getName(); // Title @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") String getTitle(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void setTitle(String title); // MultipleOf @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") Number getMultipleOf(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void setMultipleOf(Number multipleOf); // Maximum @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") Number getMaximum(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void setMaximum(Number maximum); // ExclusiveMaximum @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") Boolean getExclusiveMaximum(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") boolean isExclusiveMaximum(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void setExclusiveMaximum(Boolean exclusiveMaximum); // Minimum @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") Number getMinimum(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void setMinimum(Number minimum); // ExclusiveMinimum @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") Boolean getExclusiveMinimum(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") boolean isExclusiveMinimum(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void setExclusiveMinimum(Boolean exclusiveMinimum); // MaxLength @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") Integer getMaxLength(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void setMaxLength(Integer maxLength); // MinLength @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") Integer getMinLength(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void setMinLength(Integer minLength); // Pattern @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") String getPattern(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void setPattern(String pattern); // MaxItems @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") Integer getMaxItems(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void setMaxItems(Integer maxItems); // MinItems @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") Integer getMinItems(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void setMinItems(Integer minItems); // UniqueItems @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") Boolean getUniqueItems(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") boolean isUniqueItems(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void setUniqueItems(Boolean uniqueItems); // MaxProperties @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") Integer getMaxProperties(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void setMaxProperties(Integer maxProperties); // MinProperties @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") Integer getMinProperties(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void setMinProperties(Integer minProperties); // RequiredField @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") List<String> getRequiredFields(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") List<String> getRequiredFields(boolean elaborate); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") boolean hasRequiredFields(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") String getRequiredField(int index); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void setRequiredFields(List<String> requiredFields); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void setRequiredField(int index, String requiredField); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void addRequiredField(String requiredField); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void insertRequiredField(int index, String requiredField); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void removeRequiredField(int index); // Enum @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") List<Object> getEnums(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") List<Object> getEnums(boolean elaborate); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") boolean hasEnums(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") Object getEnum(int index); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void setEnums(List<Object> enums); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void setEnum(int index, Object enumValue); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void addEnum(Object enumValue); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void insertEnum(int index, Object enumValue); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void removeEnum(int index); // Type @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") String getType(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void setType(String type); // AllOfSchema @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") List<Schema> getAllOfSchemas(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") List<Schema> getAllOfSchemas(boolean elaborate); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") boolean hasAllOfSchemas(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") Schema getAllOfSchema(int index); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void setAllOfSchemas(List<Schema> allOfSchemas); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void setAllOfSchema(int index, Schema allOfSchema); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void addAllOfSchema(Schema allOfSchema); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void insertAllOfSchema(int index, Schema allOfSchema); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void removeAllOfSchema(int index); // OneOfSchema @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") List<Schema> getOneOfSchemas(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") List<Schema> getOneOfSchemas(boolean elaborate); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") boolean hasOneOfSchemas(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") Schema getOneOfSchema(int index); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void setOneOfSchemas(List<Schema> oneOfSchemas); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void setOneOfSchema(int index, Schema oneOfSchema); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void addOneOfSchema(Schema oneOfSchema); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void insertOneOfSchema(int index, Schema oneOfSchema); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void removeOneOfSchema(int index); // AnyOfSchema @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") List<Schema> getAnyOfSchemas(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") List<Schema> getAnyOfSchemas(boolean elaborate); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") boolean hasAnyOfSchemas(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") Schema getAnyOfSchema(int index); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void setAnyOfSchemas(List<Schema> anyOfSchemas); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void setAnyOfSchema(int index, Schema anyOfSchema); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void addAnyOfSchema(Schema anyOfSchema); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void insertAnyOfSchema(int index, Schema anyOfSchema); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void removeAnyOfSchema(int index); // NotSchema @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") Schema getNotSchema(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") Schema getNotSchema(boolean elaborate); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void setNotSchema(Schema notSchema); // ItemsSchema @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") Schema getItemsSchema(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") Schema getItemsSchema(boolean elaborate); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void setItemsSchema(Schema itemsSchema); // Property @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") Map<String, Schema> getProperties(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") Map<String, Schema> getProperties(boolean elaborate); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") boolean hasProperties(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") boolean hasProperty(String name); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") Schema getProperty(String name); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void setProperties(Map<String, Schema> properties); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void setProperty(String name, Schema property); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void removeProperty(String name); // AdditionalPropertiesSchema @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") Schema getAdditionalPropertiesSchema(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") Schema getAdditionalPropertiesSchema(boolean elaborate); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void setAdditionalPropertiesSchema(Schema additionalPropertiesSchema); // AdditionalProperties @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") Boolean getAdditionalProperties(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") boolean isAdditionalProperties(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void setAdditionalProperties(Boolean additionalProperties); // Description @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") String getDescription(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void setDescription(String description); // Format @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") String getFormat(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void setFormat(String format); // Default @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") Object getDefault(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void setDefault(Object defaultValue); // Nullable @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") Boolean getNullable(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") boolean isNullable(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void setNullable(Boolean nullable); // Discriminator @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") Discriminator getDiscriminator(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") Discriminator getDiscriminator(boolean elaborate); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void setDiscriminator(Discriminator discriminator); // ReadOnly @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") Boolean getReadOnly(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") boolean isReadOnly(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void setReadOnly(Boolean readOnly); // WriteOnly @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") Boolean getWriteOnly(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") boolean isWriteOnly(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void setWriteOnly(Boolean writeOnly); // Xml @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") Xml getXml(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") Xml getXml(boolean elaborate); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void setXml(Xml xml); // ExternalDocs @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") ExternalDocs getExternalDocs(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") ExternalDocs getExternalDocs(boolean elaborate); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void setExternalDocs(ExternalDocs externalDocs); // Example @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") Object getExample(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void setExample(Object example); // Deprecated @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") Boolean getDeprecated(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") boolean isDeprecated(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void setDeprecated(Boolean deprecated); // Extension @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") Map<String, Object> getExtensions(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") Map<String, Object> getExtensions(boolean elaborate); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") boolean hasExtensions(); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") boolean hasExtension(String name); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") Object getExtension(String name); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void setExtensions(Map<String, Object> extensions); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void setExtension(String name, Object extension); @Generated("com.reprezen.jsonoverlay.gen.CodeGenerator") void removeExtension(String name); }
923e6a59265eb2e32f945b120e11a8b523379b86
1,019
java
Java
src/test/java/ch/heigvd/res/chill/domain/MichaelDaSilva/PizzaTest.java
VictorTruan/Teaching-HEIGVD-RES-2019-Chill
14ee9ad573ee0bd618c7e1d110bca5e74424e20c
[ "MIT" ]
4
2019-02-23T19:26:03.000Z
2019-03-02T12:16:21.000Z
src/test/java/ch/heigvd/res/chill/domain/MichaelDaSilva/PizzaTest.java
VictorTruan/Teaching-HEIGVD-RES-2019-Chill
14ee9ad573ee0bd618c7e1d110bca5e74424e20c
[ "MIT" ]
493
2019-02-15T12:21:20.000Z
2021-09-30T07:34:44.000Z
src/test/java/ch/heigvd/res/chill/domain/MichaelDaSilva/PizzaTest.java
VictorTruan/Teaching-HEIGVD-RES-2019-Chill
14ee9ad573ee0bd618c7e1d110bca5e74424e20c
[ "MIT" ]
108
2019-02-15T12:17:21.000Z
2021-02-26T09:13:28.000Z
35.137931
80
0.73209
1,000,752
package ch.heigvd.res.chill.domain.MichaelDaSilva; import ch.heigvd.res.chill.domain.Bartender; import ch.heigvd.res.chill.protocol.OrderRequest; import ch.heigvd.res.chill.protocol.OrderResponse; import org.junit.jupiter.api.Test; import java.math.BigDecimal; import static org.junit.jupiter.api.Assertions.assertEquals; class PizzaTest { @Test void theNameAndPriceForPizzaShouldBeCorrect() { Pizza food = new Pizza(); assertEquals(food.getPrice(), Pizza.PRICE); assertEquals(food.getName(), Pizza.NAME); } @Test void aBartenderShouldAcceptAnOrderForPizza() { Bartender mikeMcMike = new Bartender(); String productName = "ch.heigvd.res.chill.domain.MichaelDaSilva.Pizza"; OrderRequest request = new OrderRequest(2, productName); OrderResponse response = mikeMcMike.order(request); BigDecimal expectedTotalPrice = Pizza.PRICE.multiply(new BigDecimal(2)); assertEquals(expectedTotalPrice, response.getTotalPrice()); } }
923e6a7af7a1912c8244e1c4c8ebe0d76d309002
2,823
java
Java
src/main/java/com/boyarsky/dapos/core/repository/currency/XodusCurrencyHolderRepository.java
AndrewBoyarsky/DPoSBlockchain
2376035bd9bf7518e4e55b5f16e5c15b659481fe
[ "Apache-2.0" ]
2
2020-08-05T08:14:35.000Z
2021-11-11T13:22:26.000Z
src/main/java/com/boyarsky/dapos/core/repository/currency/XodusCurrencyHolderRepository.java
AndrewBoyarsky/DPoSBlockchain
2376035bd9bf7518e4e55b5f16e5c15b659481fe
[ "Apache-2.0" ]
1
2020-05-30T13:50:16.000Z
2020-05-30T13:50:16.000Z
src/main/java/com/boyarsky/dapos/core/repository/currency/XodusCurrencyHolderRepository.java
AndrewBoyarsky/DPoSBlockchain
2376035bd9bf7518e4e55b5f16e5c15b659481fe
[ "Apache-2.0" ]
1
2021-11-11T13:22:28.000Z
2021-11-11T13:22:28.000Z
41.514706
173
0.75062
1,000,753
package com.boyarsky.dapos.core.repository.currency; import com.boyarsky.dapos.core.model.account.AccountId; import com.boyarsky.dapos.core.model.currency.CurrencyHolder; import com.boyarsky.dapos.core.repository.DbParam; import com.boyarsky.dapos.core.repository.DbParamImpl; import com.boyarsky.dapos.core.repository.Pagination; import com.boyarsky.dapos.core.repository.XodusAbstractRepository; import com.boyarsky.dapos.core.repository.XodusRepoContext; import com.boyarsky.dapos.core.repository.aop.Transactional; import com.boyarsky.dapos.utils.CollectionUtils; import com.boyarsky.dapos.utils.Convert; import jetbrains.exodus.entitystore.Entity; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import java.util.List; @Repository public class XodusCurrencyHolderRepository extends XodusAbstractRepository<CurrencyHolder> implements CurrencyHolderRepository { @Autowired XodusCurrencyHolderRepository(XodusRepoContext context) { super("currency_holder", true, context); } @Override protected void storeToDbEntity(Entity e, CurrencyHolder currencyHolder) { e.setProperty("account", Convert.toHexString(currencyHolder.getHolder().getAddressBytes())); e.setProperty("currency", currencyHolder.getCurrencyId()); e.setProperty("amount", currencyHolder.getAmount()); } @Override protected CurrencyHolder doMap(Entity e) { AccountId account = AccountId.fromBytes(Convert.parseHexString((String) e.getProperty("account"))); Long currency = (Long) e.getProperty("currency"); Long amount = (Long) e.getProperty("amount"); return new CurrencyHolder(0, account, currency, amount); } @Override @Transactional(readonly = true) public CurrencyHolder get(AccountId account, long currencyId) { return CollectionUtils.requireAtMostOne(getAll(new DbParamImpl("account", Convert.toHexString(account.getAddressBytes())), new DbParamImpl("currency", currencyId))); } @Override @Transactional(readonly = true) public List<CurrencyHolder> getAllForCurrency(long currencyId, Pagination pagination) { return getAll(pagination, new DbParamImpl("currency", currencyId)); } @Override protected List<DbParam> idParams(CurrencyHolder value) { return List.of( new DbParamImpl("account", Convert.toHexString(value.getHolder().getAddressBytes())), new DbParamImpl("currency", value.getCurrencyId()) ); } @Override @Transactional(readonly = true) public List<CurrencyHolder> getAllByAccount(AccountId accountId, Pagination pagination) { return getAll(pagination, new DbParamImpl("account", Convert.toHexString(accountId.getAddressBytes()))); } }
923e6b57050388cb0dc4e73cfbc3e361171b5f38
1,432
java
Java
tokamak-core/src/main/java/com/wrmsr/tokamak/core/type/hier/simple/time/LocalTimeType.java
wrmsr/tokamak
3ebf3395c5bb78b80e0445199958cb81f4cf9be8
[ "Apache-2.0" ]
3
2019-07-29T06:18:02.000Z
2022-02-28T01:33:20.000Z
tokamak-core/src/main/java/com/wrmsr/tokamak/core/type/hier/simple/time/LocalTimeType.java
wrmsr/tokamak
3ebf3395c5bb78b80e0445199958cb81f4cf9be8
[ "Apache-2.0" ]
4
2021-12-09T19:26:33.000Z
2022-01-21T23:26:31.000Z
tokamak-core/src/main/java/com/wrmsr/tokamak/core/type/hier/simple/time/LocalTimeType.java
wrmsr/tokamak
3ebf3395c5bb78b80e0445199958cb81f4cf9be8
[ "Apache-2.0" ]
null
null
null
29.22449
151
0.733939
1,000,754
/* * 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.wrmsr.tokamak.core.type.hier.simple.time; import com.wrmsr.tokamak.core.type.TypeConstructor; import com.wrmsr.tokamak.core.type.TypeRegistration; import javax.annotation.concurrent.Immutable; import java.lang.reflect.Type; import java.time.LocalTime; import java.util.Optional; @Immutable public final class LocalTimeType implements TimeType { public static final String NAME = "LocalTime"; public static final LocalTimeType INSTANCE = new LocalTimeType(); public static final TypeRegistration REGISTRATION = new TypeRegistration(NAME, LocalTimeType.class, LocalTime.class, TypeConstructor.of(INSTANCE)); public LocalTimeType() { } @Override public String getName() { return NAME; } @Override public Optional<Type> toReflect() { return Optional.of(LocalTime.class); } }
923e6b8d2cbdf717675fcd6421b37bae1ffb7187
5,924
java
Java
src/main/java/gocardless/http/HttpClient.java
gocardless/gocardless-legacy-java
5074fd2452402ad5be18f1667a1fe3748b2a383d
[ "MIT" ]
1
2018-02-06T11:55:56.000Z
2018-02-06T11:55:56.000Z
src/main/java/gocardless/http/HttpClient.java
gocardless/gocardless-legacy-java
5074fd2452402ad5be18f1667a1fe3748b2a383d
[ "MIT" ]
null
null
null
src/main/java/gocardless/http/HttpClient.java
gocardless/gocardless-legacy-java
5074fd2452402ad5be18f1667a1fe3748b2a383d
[ "MIT" ]
2
2019-04-23T03:20:06.000Z
2021-03-17T18:24:33.000Z
32.729282
111
0.6737
1,000,755
package gocardless.http; import static java.lang.String.format; import gocardless.GoCardless; import gocardless.exception.GoCardlessException; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import javax.net.ssl.HttpsURLConnection; import org.apache.commons.codec.binary.Base64; public class HttpClient { public final static HttpClient DEFAULT = new HttpClient(); public static final String CHARSET = "UTF-8"; public static final String CONTENT_TYPE = "application/json"; public static final String USER_AGENT = format("gocardless-java/%s", GoCardless.VERSION); public static final Map<String, String> BASE_HEADERS = headers(); protected enum RequestMethod {GET, POST, PUT}; protected int connectTimeout = 30000; // 30 second default protected int readTimeout = 60000; // 60 second default public HttpClient() { } public String get(String url, Map<String, String> headers) { return request(RequestMethod.GET, url, headers, null); } public String post(String url, Map<String, String> headers, String payload) { return request(RequestMethod.POST, url, headers, payload); } public String put(String url, Map<String, String> headers, String payload) { return request(RequestMethod.PUT, url, headers, payload); } public static String url(String url, Map<String, String> params) { if (params == null || params.isEmpty()) { return url; } return format("%s?%s", url, createQuery(params)); } public static Map<String, String> basicAuth(String username, String password) { String basicAuth = Base64.encodeBase64String(format("%s:%s", username, password).getBytes()); Map<String, String> headers = new HashMap<String, String>(); headers.put("Authorization", "Basic " + basicAuth); return headers; } public int getConnectTimeout() { return connectTimeout; } public void setConnectTimeout(int connectTimeout) { this.connectTimeout = connectTimeout; } public int getReadTimeout() { return readTimeout; } public void setReadTimeout(int readTimeout) { this.readTimeout = readTimeout; } protected String request(RequestMethod method, String url, Map<String, String> headers, String payload) { HttpsURLConnection conn = null; try { conn = createConnection(url); headers = (headers != null) ? headers : new HashMap<String, String>(); for(Map.Entry<String, String> header: headers.entrySet()) { conn.setRequestProperty(header.getKey(), header.getValue()); } if (method.equals(RequestMethod.GET)) { conn.setRequestMethod("GET"); } else if (method.equals(RequestMethod.POST)) { conn.setRequestMethod("POST"); writeOutput(conn, payload); } else if (method.equals(RequestMethod.PUT)) { conn.setRequestMethod("PUT"); writeOutput(conn, payload); } else { throw new GoCardlessException(format("Unsupported Request Method [method: %s, url: %s]", method, url)); } int statusCode = conn.getResponseCode(); //triggers the request if (statusCode < 200 || statusCode >= 300) { throw new GoCardlessException(url, statusCode, getResponse(conn.getErrorStream())); } return getResponse(conn.getInputStream()); } catch (IOException ex) { throw new GoCardlessException(format("Failed request [url: %s]", url), ex); } finally { if (conn != null) { conn.disconnect(); } } } protected void writeOutput(URLConnection connection, String payload) throws IOException { if (payload != null) { connection.setDoOutput(true); OutputStream output = null; try { output = connection.getOutputStream(); output.write(payload.getBytes(CHARSET)); } finally { if (output != null) output.close(); } } } /** * See http://stackoverflow.com/questions/309424/in-java-how-do-i-read-convert-an-inputstream-to-a-string */ protected String getResponse(java.io.InputStream response) throws IOException { try { return new java.util.Scanner(response, CHARSET).useDelimiter("\\A").next(); } finally { response.close(); } } protected HttpsURLConnection createConnection(String url) throws IOException { HttpsURLConnection conn = (HttpsURLConnection) new URL(url).openConnection(); conn.setConnectTimeout(connectTimeout); conn.setReadTimeout(readTimeout); conn.setUseCaches(false); for(Map.Entry<String, String> header: BASE_HEADERS.entrySet()) { conn.setRequestProperty(header.getKey(), header.getValue()); } return conn; } protected static String createQuery(Map<String, String> params) { if (params == null) { return ""; } try { StringBuffer query = new StringBuffer(); for(Entry<String, String> entry: params.entrySet()) { if (query.length() > 0) { query.append("&"); } String encodedKey = URLEncoder.encode(entry.getKey(), CHARSET); String encodedValue = URLEncoder.encode(entry.getValue(), CHARSET); query.append(String.format("%s=%s", encodedKey, encodedValue)); } return query.toString(); } catch (UnsupportedEncodingException ex) { throw new RuntimeException("Failed to encode params " + params.toString(), ex); } } protected static Map<String, String> headers() { Map<String, String> headers = new HashMap<String, String>(); headers.put("Accept", format("%s", CONTENT_TYPE)); headers.put("Content-Type", format("%s;charset=%s", CONTENT_TYPE, CHARSET)); headers.put("User-Agent", USER_AGENT); return headers; } }
923e6c80886bdf9247eef5ecaa9ab9cf605f24f0
1,097
java
Java
apps/apps-book/Java8TheCompleteReference/intro/src/org/gamegogo/TheCollectionsFramework/Legacy/PropDemoDef.java
reyou/Ggg.Java
8698a43dc0e23e9fe09d7e489289cfae62e01c5b
[ "Apache-2.0" ]
null
null
null
apps/apps-book/Java8TheCompleteReference/intro/src/org/gamegogo/TheCollectionsFramework/Legacy/PropDemoDef.java
reyou/Ggg.Java
8698a43dc0e23e9fe09d7e489289cfae62e01c5b
[ "Apache-2.0" ]
null
null
null
apps/apps-book/Java8TheCompleteReference/intro/src/org/gamegogo/TheCollectionsFramework/Legacy/PropDemoDef.java
reyou/Ggg.Java
8698a43dc0e23e9fe09d7e489289cfae62e01c5b
[ "Apache-2.0" ]
null
null
null
37.827586
110
0.62443
1,000,756
package org.gamegogo.TheCollectionsFramework.Legacy; // Use a default property list. import java.util.*; class PropDemoDef { public static void main(String args[]) { Properties defList = new Properties(); defList.put("Florida", "Tallahassee"); defList.put("Wisconsin", "Madison"); Properties capitals = new Properties(defList); capitals.put("Illinois", "Springfield"); capitals.put("Missouri", "Jefferson City"); capitals.put("Washington", "Olympia"); capitals.put("California", "Sacramento"); capitals.put("Indiana", "Indianapolis"); // Get a set-view of the keys. Set<?> states = capitals.keySet(); // Show all of the states and capitals. for (Object name : states) { System.out.println("The capital of " + name + " is " + capitals.getProperty((String) name) + "."); } System.out.println(); // Florida will now be found in the default list. String str = capitals.getProperty("Florida"); System.out.println("The capital of Florida is " + str + "."); } }
923e6d2eee509c88821e7ae111c05e86f523931c
1,755
java
Java
ktlsh/src/test/java/app/keve/ktlsh/testutil/TestUtil.java
kevemueller/kTLSH
ee9cf02d1603e26c9fbce1120589c6482e3197ac
[ "Apache-2.0" ]
2
2020-08-05T17:02:00.000Z
2021-09-14T15:51:53.000Z
ktlsh/src/test/java/app/keve/ktlsh/testutil/TestUtil.java
kevemueller/kTLSH
ee9cf02d1603e26c9fbce1120589c6482e3197ac
[ "Apache-2.0" ]
1
2020-08-05T17:20:31.000Z
2020-10-13T11:08:27.000Z
ktlsh/src/test/java/app/keve/ktlsh/testutil/TestUtil.java
kevemueller/kTLSH
ee9cf02d1603e26c9fbce1120589c6482e3197ac
[ "Apache-2.0" ]
null
null
null
27.421875
75
0.679772
1,000,757
/* * Copyright 2020 Keve Müller * * 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 app.keve.ktlsh.testutil; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.Security; import app.keve.ktlsh.TLSHUtil; import app.keve.ktlsh.spi.TMProvider; /** * Utility functions for tests. * * @author keve * */ public final class TestUtil { private TestUtil() { } /** * Register K provider as well as TM provider. */ public static void registerProvider() { TLSHUtil.registerProvider(); Security.addProvider(new TMProvider()); } /** * Return the name of the TM provider. * * @return the name */ public static String providerNameTM() { return TMProvider.NAME; } /** * Get a SecureRandom instance. * * @return the instance * @throws NoSuchAlgorithmException if none can be found */ public static SecureRandom rnd() throws NoSuchAlgorithmException { final String os = System.getProperty("os.name").toLowerCase(); return os.contains("win") ? SecureRandom.getInstanceStrong() : SecureRandom.getInstance("NativePRNGNonBlocking"); } }
923e6db5c56fe0d9a996d3f3f46d4d15a715e1b7
231
java
Java
medico.ui/src/main/java/com/sonar/vishal/ui/definition/GenericStructure.java
vishalsonar/medico
04d696a1180c73abb1ed78931c7bc8b52e63f5a1
[ "Apache-2.0" ]
null
null
null
medico.ui/src/main/java/com/sonar/vishal/ui/definition/GenericStructure.java
vishalsonar/medico
04d696a1180c73abb1ed78931c7bc8b52e63f5a1
[ "Apache-2.0" ]
15
2021-01-02T14:59:19.000Z
2021-12-04T07:43:15.000Z
medico.ui/src/main/java/com/sonar/vishal/ui/definition/GenericStructure.java
vishalsonar/medico
04d696a1180c73abb1ed78931c7bc8b52e63f5a1
[ "Apache-2.0" ]
null
null
null
17.769231
53
0.78355
1,000,758
package com.sonar.vishal.ui.definition; public interface GenericStructure extends Structure { public void action(int token); public void buttonOneaction(); public void buttonTwoaction(); public void buttonThreeaction(); }
923e6e94c473526bee4e8b02f8509888596c61d4
182
java
Java
src/main/java/de/tum/in/www1/artemis/exception/QuizSubmissionException.java
mahdi-dhaini/Artemis
6d63c0eb7c8057dcead9dc16348de7ebba5e7ee3
[ "MIT" ]
213
2019-06-20T19:22:05.000Z
2022-03-29T14:49:53.000Z
src/main/java/de/tum/in/www1/artemis/exception/QuizSubmissionException.java
mahdi-dhaini/Artemis
6d63c0eb7c8057dcead9dc16348de7ebba5e7ee3
[ "MIT" ]
2,992
2019-06-19T13:40:38.000Z
2022-03-31T21:17:12.000Z
src/main/java/de/tum/in/www1/artemis/exception/QuizSubmissionException.java
mahdi-dhaini/Artemis
6d63c0eb7c8057dcead9dc16348de7ebba5e7ee3
[ "MIT" ]
365
2019-07-30T11:30:58.000Z
2022-03-22T07:23:16.000Z
20.222222
56
0.736264
1,000,759
package de.tum.in.www1.artemis.exception; public class QuizSubmissionException extends Throwable { public QuizSubmissionException(String error) { super(error); } }
923e6f1d78003f6cca1494358282facd5d44f3c8
1,857
java
Java
subprojects/snapshots/src/main/java/org/gradle/internal/snapshot/RelativePathStringTracker.java
jdai8/gradle
0fdb1f3ff5c4e8f3444e14e5cdaa6775f1189a5d
[ "Apache-2.0" ]
2
2018-02-10T18:44:02.000Z
2018-03-25T07:17:04.000Z
subprojects/snapshots/src/main/java/org/gradle/internal/snapshot/RelativePathStringTracker.java
jdai8/gradle
0fdb1f3ff5c4e8f3444e14e5cdaa6775f1189a5d
[ "Apache-2.0" ]
12
2020-07-11T15:43:32.000Z
2020-10-13T23:39:44.000Z
subprojects/snapshots/src/main/java/org/gradle/internal/snapshot/RelativePathStringTracker.java
jdai8/gradle
0fdb1f3ff5c4e8f3444e14e5cdaa6775f1189a5d
[ "Apache-2.0" ]
1
2022-01-12T12:33:48.000Z
2022-01-12T12:33:48.000Z
29.951613
114
0.669359
1,000,760
/* * Copyright 2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.internal.snapshot; import com.google.common.collect.Lists; import java.util.Deque; /** * Holds a reference to a relative path {@link String} when visiting a {@link CompleteFileSystemLocationSnapshot}. * * If you need to keep track of individual path segments use {@link RelativePathSegmentsTracker} instead. */ public class RelativePathStringTracker { private final Deque<String> relativePathStrings = Lists.newLinkedList(); private boolean root = true; public void enter(CompleteFileSystemLocationSnapshot snapshot) { enter(snapshot.getName()); } public void enter(String name) { if (!root) { String previous = relativePathStrings.peekLast(); if (previous == null) { relativePathStrings.addLast(name); } else { relativePathStrings.addLast(previous + '/' + name); } } root = false; } public void leave() { if (!relativePathStrings.isEmpty()) { relativePathStrings.removeLast(); } } public boolean isRoot() { return root; } public String getRelativePathString() { return relativePathStrings.getLast(); } }
923e6f299ec58ed711936415aed9b3e2fb468700
2,350
java
Java
plugin/trino-raptor-legacy/src/main/java/io/trino/plugin/raptor/legacy/storage/organization/OrganizationSet.java
julian-cn/trino
3082ef8475f67132f0be0f82809d86460fb975ee
[ "Apache-2.0" ]
3,603
2020-12-27T23:06:56.000Z
2022-03-31T22:17:28.000Z
plugin/trino-raptor-legacy/src/main/java/io/trino/plugin/raptor/legacy/storage/organization/OrganizationSet.java
julian-cn/trino
3082ef8475f67132f0be0f82809d86460fb975ee
[ "Apache-2.0" ]
4,549
2019-01-21T02:50:11.000Z
2020-12-27T20:38:26.000Z
plugin/trino-raptor-legacy/src/main/java/io/trino/plugin/raptor/legacy/storage/organization/OrganizationSet.java
julian-cn/trino
3082ef8475f67132f0be0f82809d86460fb975ee
[ "Apache-2.0" ]
954
2020-12-28T02:03:33.000Z
2022-03-31T14:21:35.000Z
27.97619
95
0.641277
1,000,761
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.trino.plugin.raptor.legacy.storage.organization; import java.util.Objects; import java.util.OptionalInt; import java.util.Set; import java.util.UUID; import static com.google.common.base.MoreObjects.toStringHelper; import static java.util.Objects.requireNonNull; public class OrganizationSet { private final long tableId; private final Set<UUID> shards; private final OptionalInt bucketNumber; public OrganizationSet(long tableId, Set<UUID> shards, OptionalInt bucketNumber) { this.tableId = tableId; this.shards = requireNonNull(shards, "shards is null"); this.bucketNumber = requireNonNull(bucketNumber, "bucketNumber is null"); } public long getTableId() { return tableId; } public Set<UUID> getShards() { return shards; } public OptionalInt getBucketNumber() { return bucketNumber; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } OrganizationSet that = (OrganizationSet) o; return tableId == that.tableId && Objects.equals(shards, that.shards) && Objects.equals(bucketNumber, that.bucketNumber); } @Override public int hashCode() { return Objects.hash(tableId, shards, bucketNumber); } @Override public String toString() { return toStringHelper(this) .add("tableId", tableId) .add("shards", shards) .add("bucketNumber", bucketNumber.isPresent() ? bucketNumber.getAsInt() : null) .omitNullValues() .toString(); } }
923e70db342b0ed391d3c249d42ee8c0a5a40cc5
9,310
java
Java
app/src/main/java/com/nicodelee/beautyarticle/ui/view/fragment/FunFragment.java
rizhilee/Beautyacticle
ce0d97612a80cb24202599d86baf6bd81bc9fc65
[ "Apache-2.0" ]
363
2015-03-18T10:02:24.000Z
2015-10-27T06:43:03.000Z
app/src/main/java/com/nicodelee/beautyarticle/ui/view/fragment/FunFragment.java
NicodeLee/BeautyarticlePro
26eeed598a99d9e494ed959e339ebf55e1d4f97d
[ "Apache-2.0" ]
2
2015-08-28T10:12:37.000Z
2015-09-11T08:42:47.000Z
app/src/main/java/com/nicodelee/beautyarticle/ui/view/fragment/FunFragment.java
NicodeLee/BeautyarticlePro
26eeed598a99d9e494ed959e339ebf55e1d4f97d
[ "Apache-2.0" ]
74
2015-05-21T12:16:13.000Z
2015-10-20T02:06:39.000Z
37.389558
100
0.7116
1,000,762
package com.nicodelee.beautyarticle.ui.view.fragment; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Typeface; import android.net.Uri; import android.os.Bundle; import android.support.design.widget.TextInputLayout; import android.support.v4.widget.NestedScrollView; import android.support.v7.app.AlertDialog; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.RelativeLayout; import android.widget.TextView; import butterknife.Bind; import butterknife.BindString; import butterknife.ButterKnife; import butterknife.OnClick; import com.github.clans.fab.FloatingActionMenu; import com.nicodelee.beautyarticle.R; import com.nicodelee.beautyarticle.app.APP; import com.nicodelee.beautyarticle.app.BaseFragment; import com.nicodelee.beautyarticle.bus.CropEvent; import com.nicodelee.beautyarticle.ui.view.activity.CameraActivity; import com.nicodelee.beautyarticle.ui.view.activity.CropAct; import com.nicodelee.beautyarticle.ui.view.activity.FunTemplateAct; import com.nicodelee.beautyarticle.utils.AndroidUtils; import com.nicodelee.beautyarticle.utils.DevicesUtil; import com.nicodelee.beautyarticle.utils.Logger; import com.nicodelee.beautyarticle.utils.SharImageHelper; import com.nicodelee.beautyarticle.utils.ShareHelper; import com.nicodelee.beautyarticle.utils.TimeUtils; import com.nicodelee.beautyarticle.viewhelper.LayoutToImage; import com.nicodelee.beautyarticle.viewhelper.VerticalTextView; import com.nicodelee.utils.StringUtils; import com.nicodelee.utils.WeakHandler; import com.nicodelee.view.CircularImage; import com.nicodelee.view.CropImageView; import java.io.File; import java.util.ArrayList; import me.nereo.multi_image_selector.MultiImageSelectorActivity; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; import static butterknife.ButterKnife.findById; public class FunFragment extends BaseFragment { @Bind(R.id.sc_fun) NestedScrollView scFun; @Bind(R.id.rl_fun) RelativeLayout rlFun; @Bind(R.id.tv_desc) VerticalTextView tvDesc; @Bind(R.id.tv_title) TextView tvTitle; @Bind(R.id.fl_menu) FloatingActionMenu famFun; @Bind(R.id.iv_fun) CircularImage ivFun; @BindString(R.string.article) String acticle; @BindString(R.string.acticle_title) String acticleTitle; @Bind(R.id.tv_day) TextView tvDay; @Bind(R.id.tv_month) TextView tvMonth; @Bind(R.id.tv_year) TextView tvYear; private LayoutToImage layoutToImage; private LayoutInflater inflater; private String title, desc; private static final int REQUEST_IMAGE = 2; private static final int REQUEST_PORTRAIT_FFC = 3; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_fun, container, false); ButterKnife.bind(this, view); init(); return view; } private void init() { inflater = LayoutInflater.from(mActivity); famFun.setClosedOnTouchOutside(true); tvTitle.setText(acticleTitle); tvDesc.setTextSize(DevicesUtil.sp2px(mActivity, 16)); tvDesc.setLineWidth(DevicesUtil.dip2px(mActivity, 24)); Typeface face = Typeface.createFromAsset(mActivity.getAssets(), "fonts/fun_font.TTF"); tvDesc.setTextColor(R.color.templage_title); tvDesc.setTypeface(face); tvDesc.setText(acticle); String date = TimeUtils.dateToCnDate(TimeUtils.getCurentData()); tvDay.setText(TimeUtils.getDay(date)); tvMonth.setText(TimeUtils.getMonth(date)); tvYear.setText(TimeUtils.getYear(date)); rlFun.setLayoutParams( new FrameLayout.LayoutParams(DevicesUtil.screenWidth, ViewGroup.LayoutParams.MATCH_PARENT)); layoutToImage = new LayoutToImage(scFun); } @OnClick({ R.id.fb_share, R.id.fb_make, R.id.iv_fun, R.id.fb_more }) public void Click(View view) { famFun.close(true); switch (view.getId()) { case R.id.fb_share: final SharImageHelper sharImageHelper = new SharImageHelper(); Observable.create(new Observable.OnSubscribe<Bitmap>() { @Override public void call(Subscriber<? super Bitmap> subscriber) { Bitmap bitmap = layoutToImage.convertlayout(); sharImageHelper.saveBitmap(bitmap, SharImageHelper.sharePicName); subscriber.onNext(bitmap); subscriber.onCompleted(); } }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Bitmap>() { @Override public void call(Bitmap bitmap) { ShareHelper.showUp(mActivity, sharImageHelper.getShareMod(bitmap)); } }); break; case R.id.fb_make: showEdDialig(); break; case R.id.fb_more: skipIntent(FunTemplateAct.class, false); break; case R.id.iv_fun: showChiocePicDialog(); break; } } private void showEdDialig() { View etView = inflater.inflate(R.layout.item_fun_et, null); final TextInputLayout inputTitle = findById(etView, R.id.textInput_title); final TextInputLayout inputDesc = findById(etView, R.id.textInput_desc); inputTitle.setHint("想个好标题"); inputDesc.setHint("说说图片的故事"); final EditText etTitle = inputTitle.getEditText(); final EditText etDesc = inputDesc.getEditText(); etTitle.setText(title); etDesc.setText(desc); new AlertDialog.Builder(mActivity).setMessage("发挥你聪明才智") .setView(etView) .setNegativeButton("放弃", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .setPositiveButton("发表", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { title = etTitle.getText().toString().trim(); desc = etDesc.getText().toString().trim(); if (!TextUtils.isEmpty(title) && !TextUtils.isEmpty(desc)) { tvTitle.setText(title); tvDesc.setText(desc); } dialog.dismiss(); } }) .create() .show(); new WeakHandler().postDelayed(new Runnable() { @Override public void run() { InputMethodManager inputManager = (InputMethodManager) etTitle.getContext() .getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.showSoftInput(etTitle, 0); } }, 200); } private void showChiocePicDialog() { String[] items = new String[] { "拍照", "相册" }; new AlertDialog.Builder(mActivity).setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case 0: Intent i = new CameraActivity.IntentBuilder(getActivity()).skipConfirm() .facing(CameraActivity.Facing.BACK) .to(new File(AndroidUtils.IMAGE_CACHE_PATH, "nicodelee.jpg")) .debug() .updateMediaStore() .build(); startActivityForResult(i, REQUEST_PORTRAIT_FFC); break; case 1: int selectedMode = MultiImageSelectorActivity.MODE_SINGLE; MultiImageSelectorActivity.startSelect(FunFragment.this, REQUEST_IMAGE, 1, selectedMode); break; } } }).create().show(); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { Logger.e( String.format("requestCode = %s, resultCode= %s, data= %s", requestCode, resultCode, data)); if (resultCode != mActivity.RESULT_OK) return; CropEvent cropEvent = new CropEvent(); cropEvent.setCropMode(CropImageView.CropMode.CIRCLE); if (requestCode == REQUEST_IMAGE) { ArrayList<String> mSelectPath = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT); cropEvent.setImagePath(mSelectPath.get(0)); EventBus.getDefault().postSticky(cropEvent); skipIntent(CropAct.class, false); } else if (requestCode == REQUEST_PORTRAIT_FFC) {//拍照直接返回的 String path = data.getData() + ""; Logger.e(String.format("path = %s", path)); if (!StringUtils.isEmpty(path)) { String url = path.substring(path.lastIndexOf("//") + 1); cropEvent.setImagePath(url); EventBus.getDefault().postSticky(cropEvent); skipIntent(CropAct.class, false); } } } @Subscribe(sticky = true, threadMode = ThreadMode.MAIN) public void onEvent(Bitmap corpBitmap) { ivFun.setImageBitmap(corpBitmap); } @Subscribe(sticky = true, threadMode = ThreadMode.MAIN) public void onEvent(Uri uri) { APP.getInstance().imageLoader.displayImage(uri + "", ivFun, APP.options); } @Override public void onDestroyView() { super.onDestroyView(); ButterKnife.unbind(this); } }
923e718ac8c9c4e2f4ec8b5e73d39bc1215f909a
2,114
java
Java
src/main/java/com/agoda/fetcher/FileFetcher.java
vaibhavsdl/FileDownloader
ec7175aa0df58e35b675114bfef28a587532489c
[ "MIT" ]
null
null
null
src/main/java/com/agoda/fetcher/FileFetcher.java
vaibhavsdl/FileDownloader
ec7175aa0df58e35b675114bfef28a587532489c
[ "MIT" ]
3
2021-12-10T01:12:21.000Z
2021-12-14T21:18:07.000Z
src/main/java/com/agoda/fetcher/FileFetcher.java
vaibhavsdl/FileDownloader
ec7175aa0df58e35b675114bfef28a587532489c
[ "MIT" ]
null
null
null
34.655738
134
0.626301
1,000,763
package com.agoda.fetcher; import com.agoda.service.FileDownloader; import com.agoda.util.FileUtility; import java.net.URI; import java.util.List; import java.util.Map; import static com.agoda.constants.ApplicationConstants.SUPPORTED_PROTOCOL_MAP; import static com.agoda.constants.LoggingConstants.ERROR_LOGGER; import static com.agoda.constants.LoggingConstants.INFO_LOGGER; /** * The base class which controls all file downloading as per the service associated with the protocol */ public class FileFetcher { /** * Downloads files to local directory, uses corresponding service to each protocol file * * @param urlList list of urls which have to be downloaded * @param downloadFolderPath the local folder where files needs to be downloaded */ public static void downloadFilesFromUrls(List<String> urlList, String downloadFolderPath) { Map<String, List<URI>> fileProtocolMap = FileUtility.groupFilesByProtocol(urlList); for(Map.Entry<String, List<URI>> entry : fileProtocolMap.entrySet()) { String protocol = entry.getKey(); List<URI> fileUrlList = entry.getValue(); if(SUPPORTED_PROTOCOL_MAP.containsKey(protocol)) { INFO_LOGGER.info("Downloading file from protocol : " + protocol); try { Class<FileDownloader> protocolClass = (Class<FileDownloader>) Class.forName(SUPPORTED_PROTOCOL_MAP.get(protocol)); FileDownloader fileDownloader = protocolClass.newInstance(); for(URI fileUrl : fileUrlList) { fileDownloader.downloadFile(downloadFolderPath, fileUrl); } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) { ERROR_LOGGER.error(ex); } } else { INFO_LOGGER.info("Protocol " + protocol + " is not supported!"); } } } }
923e724d99c3b488a37361d50087a6c2f7e2ad8f
1,349
java
Java
app/src/main/java/com/farukydnn/weatherplus/core/network/enums/RequestURL.java
farukydnn/WeatherPlus
9b4a89dc3a8281ae9f8a59a8c6a687790168c0e1
[ "Apache-2.0" ]
11
2017-11-11T01:06:26.000Z
2020-03-11T13:19:15.000Z
app/src/main/java/com/farukydnn/weatherplus/core/network/enums/RequestURL.java
farukydnn/WeatherPlus
9b4a89dc3a8281ae9f8a59a8c6a687790168c0e1
[ "Apache-2.0" ]
1
2020-09-02T01:58:18.000Z
2020-09-02T01:58:18.000Z
app/src/main/java/com/farukydnn/weatherplus/core/network/enums/RequestURL.java
farukydnn/WeatherPlus
9b4a89dc3a8281ae9f8a59a8c6a687790168c0e1
[ "Apache-2.0" ]
4
2017-09-23T10:28:41.000Z
2018-08-30T20:13:04.000Z
17.075949
64
0.462565
1,000,764
package com.farukydnn.weatherplus.core.network.enums; import java.util.Locale; public enum RequestURL { BaseURL { @Override public String toString() { return "http://api.openweathermap.org/data/2.5/"; } }, AppId { @Override public String toString() { return "&APPID=3b17492d0ec2d9ff74a940f6f6c30d10"; } }, Weather { @Override public String toString() { return "weather?"; } }, Forecast { @Override public String toString() { return "forecast?"; } }, QueryQ { @Override public String toString() { return "q="; } }, QueryId { @Override public String toString() { return "id="; } }, QueryLat { @Override public String toString() { return "lat="; } }, QueryLon { @Override public String toString() { return "&lon="; } }, Units { @Override public String toString() { return "&units=metric"; } }, Lang { @Override public String toString() { return "&lang=" + Locale.getDefault().getLanguage(); } } }
923e726cc80b56a6182781951a6ff867292051e2
22,845
java
Java
DevoxxClientMobile/src/main/java/com/devoxx/util/DevoxxNotifications.java
jperedadnr/MyDevoxxGluon
ea2a3feedb78c28d5b2f0a314e2e58cbf7e50270
[ "BSD-3-Clause" ]
38
2016-11-10T17:22:34.000Z
2022-02-15T21:38:48.000Z
DevoxxClientMobile/src/main/java/com/devoxx/util/DevoxxNotifications.java
jperedadnr/MyDevoxxGluon
ea2a3feedb78c28d5b2f0a314e2e58cbf7e50270
[ "BSD-3-Clause" ]
120
2016-11-13T22:39:31.000Z
2019-11-05T17:39:19.000Z
DevoxxClientMobile/src/main/java/com/devoxx/util/DevoxxNotifications.java
jperedadnr/MyDevoxxGluon
ea2a3feedb78c28d5b2f0a314e2e58cbf7e50270
[ "BSD-3-Clause" ]
18
2016-10-31T13:04:27.000Z
2019-02-16T11:12:58.000Z
47.006173
153
0.649201
1,000,765
/* * Copyright (c) 2016, 2018 Gluon Software * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation and/or other materials provided * with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * 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 com.devoxx.util; import com.devoxx.DevoxxView; import com.devoxx.model.Conference; import com.devoxx.model.Session; import com.devoxx.service.Service; import com.devoxx.views.SessionPresenter; import com.devoxx.views.helper.Util; import com.gluonhq.charm.down.Services; import com.gluonhq.charm.down.plugins.LocalNotificationsService; import com.gluonhq.charm.down.plugins.Notification; import javafx.beans.InvalidationListener; import javafx.collections.ListChangeListener; import javax.inject.Inject; import javax.inject.Singleton; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.logging.Level; import java.util.logging.Logger; import static com.devoxx.util.DevoxxLogging.LOGGING_ENABLED; import static java.time.temporal.ChronoUnit.SECONDS; @Singleton public class DevoxxNotifications { private static final Logger LOG = Logger.getLogger(DevoxxNotifications.class.getName()); public static final String GCM_SENDER_ID = "945674729015"; private static final String ID_START = "START_"; private static final String ID_VOTE = "VOTE_"; private static final String ID_RATE = "RATE_"; private final static String TITLE_RATE_DEVOXX = DevoxxBundle.getString("OTN.VISUALS.RATE_DEVOXX"); private final static String TITLE_VOTE_SESSION = DevoxxBundle.getString("OTN.VISUALS.VOTE_NOW"); private final static String TITLE_SESSION_STARTS = DevoxxBundle.getString("OTN.VISUALS.SESSION_STARTING_SOON"); private final static int SHOW_VOTE_NOTIFICATION = -2; // show vote notification two minutes before session ends private final static int SHOW_SESSION_START_NOTIFICATION = -15; // show session start warning 15 minutes before posted start time private final Map<String, Notification> startSessionNotificationMap = new HashMap<>(); private final Map<String, Notification> voteSessionNotificationMap = new HashMap<>(); private final Map<String, Notification> ratingNotificationMap = new HashMap<>(); private final Map<String, Notification> dummyNotificationMap = new HashMap<>(); private InvalidationListener ratingListener; private ListChangeListener<Session> favoriteSessionsListener; @Inject private Service service; private final Optional<LocalNotificationsService> notificationsService; private boolean startup; private boolean authenticatedStartup; public DevoxxNotifications() { notificationsService = Services.get(LocalNotificationsService.class); } /** * For a new Favorite Session, we create two local notifications: * - One notification will be triggered by the device before the session starts * - One notification will be triggered by the device right before the session ends * * We create the notifications and schedule them on the device, but only for future events. * * @param session The new favored session */ public final void addFavoriteSessionNotifications(Session session) { final String sessionId = session.getTalk().getId(); if (!startSessionNotificationMap.containsKey(sessionId)) { createStartNotification(session).ifPresent(notification -> { startSessionNotificationMap.put(sessionId, notification); notificationsService.ifPresent(n -> n.getNotifications().add(notification)); }); } if (!voteSessionNotificationMap.containsKey(sessionId)) { createVoteNotification(session).ifPresent(notification -> { voteSessionNotificationMap.put(sessionId, notification); notificationsService.ifPresent(n -> n.getNotifications().add(notification)); }); } } public void addRatingNotification(Conference conference) { if (!ratingNotificationMap.containsKey(conference.getId())) { createRatingNotification(conference).ifPresent(notification -> { ratingNotificationMap.put(conference.getId(), notification); notificationsService.ifPresent(n -> n.getNotifications().add(notification)); }); } } /** * If a favorite session is removed as favorite, both start and vote notifications * should be cancelled on the device * @param session session removed as favorite */ public final void removeFavoriteSessionNotifications(Session session) { final Notification startNotification = startSessionNotificationMap.remove(session.getTalk().getId()); if (startNotification != null) { notificationsService.ifPresent(n -> n.getNotifications().remove(startNotification)); } final Notification voteNotification = voteSessionNotificationMap.remove(session.getTalk().getId()); if (voteNotification != null) { notificationsService.ifPresent(n -> n.getNotifications().remove(voteNotification)); } } /** * Called when the application starts, allows retrieving the rating * notifications, and restoring the notifications map */ public void preloadRatingNotifications() { if (LOGGING_ENABLED) { LOG.log(Level.INFO, "Preload of rating notifications started"); } startup = true; ratingListener = observable -> { if (service.retrieveSessions().size() > 0) { addAlreadyRatingNotifications(); service.retrieveSessions().removeListener(ratingListener); } }; service.retrieveSessions().addListener(ratingListener); } /** * Called when the application starts, allows retrieving the favorite * notifications, and restoring the notifications map */ public void preloadFavoriteSessions() { if (LOGGING_ENABLED) { LOG.log(Level.INFO, "Preload of favored sessions started"); } if (service.isAuthenticated()) { authenticatedStartup = true; favoriteSessionsListener = (ListChangeListener.Change<? extends Session> c) -> { while (c.next()) { if (c.wasAdded()) { for (Session session : c.getAddedSubList()) { if (LOGGING_ENABLED) { LOG.log(Level.INFO, String.format("Adding notification %s", session.getTalk().getId())); } addAlreadyFavoredSessionNotifications(session); } } } }; service.retrieveFavoredSessions().addListener(favoriteSessionsListener); // we don't make call to preloadRatingNotifications from DevoxxService#retrieveSessionsInternal // when the user is authenticated and try to fuse the flow with that of FavoriteNotifications preloadRatingNotifications(); } } /** * Called after the application has started and pre-loading the favored sessions * ends. At this point, we have all the notifications available, and we can remove * the listener (so new notifications are not treated as already scheduled) and * send them to the Local Notifications service at once */ public void preloadingNotificationsDone() { if (favoriteSessionsListener != null) { service.retrieveFavoredSessions().removeListener(favoriteSessionsListener); favoriteSessionsListener = null; } if (ratingListener != null) { service.retrieveSessions().removeListener(ratingListener); ratingListener = null; } if (! dummyNotificationMap.isEmpty()) { // 1. Add all dummy notifications to the notification map at once. // These need to be present all the time (as notifications will // be opened always some time after they were delivered). // Adding these dummy notifications doesn't schedule them on the // device and it doesn't cause duplicate exceptions notificationsService.ifPresent(ns -> ns.getNotifications().addAll(dummyNotificationMap.values())); } // process notifications at once List<Notification> notificationList = new ArrayList<>(); notificationList.addAll(startSessionNotificationMap.values()); notificationList.addAll(voteSessionNotificationMap.values()); notificationList.addAll(ratingNotificationMap.values()); if (! notificationList.isEmpty()) { // 2. Schedule only real future notifications final ZonedDateTime now = ZonedDateTime.now(service.getConference().getConferenceZoneId()); notificationsService.ifPresent(ns -> { for (Notification n : notificationList) { if (n.getDateTime() != null && n.getDateTime().isAfter(now)) { // Remove notification before scheduling it again, // to avoid duplicate exception final Notification dummyN = dummyNotificationMap.get(n.getId()); if (dummyN != null) { if (LOGGING_ENABLED) { LOG.log(Level.INFO, String.format("Removing notification %s", n.getId())); } ns.getNotifications().remove(dummyN); } if (LOGGING_ENABLED) { LOG.log(Level.INFO, String.format("Adding favored notification %s", n.getId())); } ns.getNotifications().add(n); } } }); } dummyNotificationMap.clear(); startup = false; authenticatedStartup = false; if (LOGGING_ENABLED) { LOG.log(Level.INFO, "Preload of favored sessions ended"); } } /** * Creates a notification that will be triggered by the device before the session starts * @param session the favored session * @return a notification if the event is in the future */ private Optional<Notification> createStartNotification(Session session) { final ZonedDateTime now = ZonedDateTime.now(service.getConference().getConferenceZoneId()); // Add notification 15 min before session starts or during authenticatedStartup ZonedDateTime dateTimeStart = session.getStartDate().plusMinutes(SHOW_SESSION_START_NOTIFICATION); if (DevoxxSettings.NOTIFICATION_TESTS) { dateTimeStart = dateTimeStart.minus(DevoxxSettings.NOTIFICATION_OFFSET, SECONDS); if (LOGGING_ENABLED) { LOG.log(Level.INFO, String.format("Start notification scheduled at: %s", dateTimeStart)); } } // add the notification for new ones if they haven't started yet if (dateTimeStart.isAfter(now) || authenticatedStartup) { return Optional.of(getStartNotification(session, dateTimeStart)); } return Optional.empty(); } /** * Creates a notification that will be triggered by the device right before the session ends * @param session the favored session * @return a notification if the session wasn't added yet and it was already scheduled or * the event is in the future */ private Optional<Notification> createVoteNotification(Session session) { final ZonedDateTime now = ZonedDateTime.now(service.getConference().getConferenceZoneId()); // Add notification 2 min before session ends ZonedDateTime dateTimeVote = session.getEndDate().plusMinutes(SHOW_VOTE_NOTIFICATION); if (DevoxxSettings.NOTIFICATION_TESTS) { dateTimeVote = dateTimeVote.minus(DevoxxSettings.NOTIFICATION_OFFSET, SECONDS); if (LOGGING_ENABLED) { LOG.log(Level.INFO, String.format("Vote notification scheduled at: %s", dateTimeVote)); } } // add the notification if the session hasn't finished yet or during authenticatedStartup if (dateTimeVote.isAfter(now) || authenticatedStartup) { return Optional.of(getVoteNotification(session, dateTimeVote)); } return Optional.empty(); } /** * Creates a notification that will be triggered by the device right before the end of the conference * @param conference Conference for which the notification has to be triggered * @return a notification if the session wasn't added yet and it was already scheduled or * the event is in the future */ private Optional<Notification> createRatingNotification(Conference conference) { final ZonedDateTime now = ZonedDateTime.now(conference.getConferenceZoneId()); // Add notification an hour before the last session begins ZonedDateTime dateTimeRating = Util.findLastSessionOfLastDay(service).getStartDate().minusHours(1); if (DevoxxSettings.NOTIFICATION_TESTS) { dateTimeRating = dateTimeRating.minus(DevoxxSettings.NOTIFICATION_OFFSET, SECONDS); if (LOGGING_ENABLED) { LOG.log(Level.INFO, String.format("Rating notification scheduled at: %s", dateTimeRating)); } } // add the notification if the time is in future or is startup is true if (dateTimeRating.isAfter(now) || startup) { return Optional.of(getRatingNotification(conference, dateTimeRating)); } return Optional.empty(); } /** * For an already favored session, we create two local notifications. * * These notifications are not sent to the Local Notification service yet: * this will be done when calling {@link #preloadingNotificationsDone()}. * * We don't schedule them again on the device, but we add these notifications to the * notifications map, so in case they are delivered, their runnable is available. * * @param session The already favored session */ private void addAlreadyFavoredSessionNotifications(Session session) { final String sessionId = session.getTalk().getId(); final ZonedDateTime now = ZonedDateTime.now(service.getConference().getConferenceZoneId()); // Add notification 15 min before session starts ZonedDateTime dateTimeStart = session.getStartDate().plusMinutes(SHOW_SESSION_START_NOTIFICATION); if (DevoxxSettings.NOTIFICATION_TESTS) { dateTimeStart = dateTimeStart.minus(DevoxxSettings.NOTIFICATION_OFFSET, SECONDS); } if (dateTimeStart.isAfter(now) || authenticatedStartup) { if (!startSessionNotificationMap.containsKey(sessionId)) { dummyNotificationMap.put(ID_START + sessionId, getStartNotification(session, null)); // Add notification createStartNotification(session).ifPresent(n -> { if (LOGGING_ENABLED) { LOG.log(Level.INFO, String.format("Adding start notification %s", n.getId())); } startSessionNotificationMap.put(sessionId, n); }); } } // Add notification 2 min before session ends ZonedDateTime dateTimeVote = session.getEndDate().plusMinutes(SHOW_VOTE_NOTIFICATION); if (DevoxxSettings.NOTIFICATION_TESTS) { dateTimeVote = dateTimeVote.minus(DevoxxSettings.NOTIFICATION_OFFSET, SECONDS); } if (dateTimeVote.isAfter(now) || authenticatedStartup) { if (!voteSessionNotificationMap.containsKey(sessionId)) { dummyNotificationMap.put(ID_VOTE + sessionId, getVoteNotification(session, null)); createVoteNotification(session).ifPresent(n -> { if (LOGGING_ENABLED) { LOG.log(Level.INFO, String.format("Adding vote notification %s", n.getId())); } voteSessionNotificationMap.put(sessionId, n); }); } } } private void addAlreadyRatingNotifications() { final Conference conference = service.getConference(); final ZonedDateTime now = ZonedDateTime.now(service.getConference().getConferenceZoneId()); // Add notification an hour before the last session begins ZonedDateTime dateTimeRating = Util.findLastSessionOfLastDay(service).getStartDate().minusHours(1); if (DevoxxSettings.NOTIFICATION_TESTS) { dateTimeRating = dateTimeRating.minus(DevoxxSettings.NOTIFICATION_OFFSET, SECONDS); } // add the notification if the time is in future if (dateTimeRating.isAfter(now) || startup) { if (!ratingNotificationMap.containsKey(conference.getId())) { dummyNotificationMap.put(ID_RATE + conference.getId(), getRatingNotification(conference, null)); createRatingNotification(conference).ifPresent(n -> { if (LOGGING_ENABLED) { LOG.log(Level.INFO, String.format("Adding rating notification %s", n.getId())); } ratingNotificationMap.put(conference.getId(), n); }); } } } /** * Creates a notification that will be triggered by the device before the session starts * * @param session the favored session * @param dateTimeStart the session's start zoned date time. If null, this notification won't be * scheduled on the device * @return a local notification */ private Notification getStartNotification(Session session, ZonedDateTime dateTimeStart) { return new Notification( ID_START + session.getTalk().getId(), TITLE_SESSION_STARTS, DevoxxBundle.getString("OTN.VISUALS.IS_ABOUT_TO_START"+(session.hasRoomName()?"_IN_ROOM":""), session.getTitle(), session.getRoomName()), DevoxxNotifications.class.getResourceAsStream("/icon.png"), dateTimeStart, () -> { if (LOGGING_ENABLED) { LOG.log(Level.INFO, String.format("Running start notification %s", session.getTalk().getId())); } DevoxxView.SESSION.switchView().ifPresent(presenter -> { SessionPresenter sessionPresenter = (SessionPresenter) presenter; sessionPresenter.showSession(session); }); }); } /** * Creates a notification that will be triggered by the device right before the session ends * @param session the favored session * @param dateTimeVote the session's end zoned date time. If null, this notification won't be * scheduled on the device * @return a local notification */ private Notification getVoteNotification(Session session, ZonedDateTime dateTimeVote) { return new Notification( ID_VOTE + session.getTalk().getId(), TITLE_VOTE_SESSION, DevoxxBundle.getString("OTN.VISUALS.CAST_YOUR_VOTE_ON", session.getTitle()), DevoxxNotifications.class.getResourceAsStream("/icon.png"), dateTimeVote, () -> { if (LOGGING_ENABLED) { LOG.log(Level.INFO, String.format("Running vote notification %s", session.getTalk().getId())); } // first go to the session DevoxxView.SESSION.switchView().ifPresent(presenter -> { SessionPresenter sessionPresenter = (SessionPresenter) presenter; sessionPresenter.showSession(session, SessionPresenter.Pane.VOTE); }); }); } /** * Creates a notification that will be triggered by the device at the end of a conference, * requesting users to rate for the app * @param conference Conference for which the notification is to be scheduled * @param dateTimeRating Zoned date time at which the notification is to be shown. * If null, this notification won't be scheduled on the device * @return a local notification */ private Notification getRatingNotification(Conference conference, ZonedDateTime dateTimeRating) { return new Notification( ID_RATE + conference.getId(), TITLE_RATE_DEVOXX, DevoxxBundle.getString("OTN.VISUALS.HELP_US_IMPROVE_DEVOXX"), DevoxxNotifications.class.getResourceAsStream("/icon.png"), dateTimeRating, () -> { if (LOGGING_ENABLED) { LOG.log(Level.INFO, String.format("Running rating notification %s", conference.getId())); } DevoxxView.SESSIONS.switchView(); } ); } }
923e72715e72aa724b289b1b8836ef95a621f6d8
2,672
java
Java
KFC/KFCTester.java
addcninblue/cs
6b724aed7ab4824a6d3879ae54323fd3534874ff
[ "Apache-2.0" ]
null
null
null
KFC/KFCTester.java
addcninblue/cs
6b724aed7ab4824a6d3879ae54323fd3534874ff
[ "Apache-2.0" ]
null
null
null
KFC/KFCTester.java
addcninblue/cs
6b724aed7ab4824a6d3879ae54323fd3534874ff
[ "Apache-2.0" ]
null
null
null
36.108108
88
0.506737
1,000,766
import java.util.Scanner; /** * Testing KFC class * * @author (Lucy) * @version (1.0) */ public class KFCTester { public static void main(String[] args) { Scanner input = new Scanner(System.in); KFC chickenWing = new KFC(); boolean cont = true; while(cont == true) { System.out.println(); System.out.println("KFC EMPLOYEE DATABASE"); System.out.println("To print employee payroll, press 1."); System.out.println("To add an employee, press 2."); System.out.println("To remove an employee, press 3."); System.out.println("To give all employee a raise, press 4."); System.out.println("To give a raise to an individual employee, press 5."); System.out.println("To exit the database, press any key."); System.out.print("Enter your selection: "); int selection = input.nextInt(); if (selection == 1) { System.out.format("%35s\n", "Employee Wages"); System.out.format("%20s | %10s | %10s\n", "Employees", "Hours", "Wage"); chickenWing.printPayroll(); } else if (selection == 2) { System.out.print("Enter employee name: "); String name = input.next(); System.out.print("Enter employee wage: "); double wage = input.nextDouble(); Employee channingTatum = new Employee(name, wage); System.out.print("Enter number of hours worked: "); int hours = input.nextInt(); channingTatum.setHours(hours); chickenWing.addEmployee(channingTatum); } else if (selection == 3) { System.out.print("Enter employee name for termination: "); String name = input.next(); chickenWing.remove(name); } else if (selection == 4) { System.out.print("Enter hourly wage increase: "); double increase = input.nextDouble(); chickenWing.raiseForAll(increase); } else if (selection == 5) { System.out.print("Enter employee name for a raise: "); String name = input.next(); System.out.print("Enter hourly wage increase: "); double increase = input.nextDouble(); chickenWing.raiseIndividually(name, increase); } else cont = false; } } }
923e73766289d0fbbe08d5701a54574cc96cee2f
4,997
java
Java
benchmark_projects/ganttproject/ganttproject/src/main/java/net/sourceforge/ganttproject/chart/gantt/GanttChartSelection.java
arisaghafari/CodART
c8560d7525d445b4d94037e1b93f7383a08f75d9
[ "MIT" ]
18
2020-11-26T08:31:27.000Z
2022-03-28T07:35:41.000Z
benchmark_projects/ganttproject/ganttproject/src/main/java/net/sourceforge/ganttproject/chart/gantt/GanttChartSelection.java
arisaghafari/CodART
c8560d7525d445b4d94037e1b93f7383a08f75d9
[ "MIT" ]
82
2020-12-25T08:26:27.000Z
2022-03-25T06:11:36.000Z
benchmark_projects/ganttproject/ganttproject/src/main/java/net/sourceforge/ganttproject/chart/gantt/GanttChartSelection.java
arisaghafari/CodART
c8560d7525d445b4d94037e1b93f7383a08f75d9
[ "MIT" ]
59
2020-11-26T08:31:42.000Z
2022-02-04T11:09:03.000Z
39.039063
180
0.795878
1,000,767
/* Copyright 2014 BarD Software s.r.o This file is part of GanttProject, an opensource project management tool. GanttProject is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. GanttProject 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 GanttProject. If not, see <http://www.gnu.org/licenses/>. */ package net.sourceforge.ganttproject.chart.gantt; import com.google.common.base.Function; import com.google.common.collect.Lists; import net.sourceforge.ganttproject.AbstractChartImplementation.ChartSelectionImpl; import net.sourceforge.ganttproject.GPLogger; import net.sourceforge.ganttproject.GPTransferable; import net.sourceforge.ganttproject.GanttTreeTable; import net.sourceforge.ganttproject.GanttTreeTableModel; import net.sourceforge.ganttproject.IGanttProject; import net.sourceforge.ganttproject.TreeTableContainer; import net.sourceforge.ganttproject.task.Task; import net.sourceforge.ganttproject.task.TaskManager; import net.sourceforge.ganttproject.task.algorithm.RetainRootsAlgorithm; import org.jdesktop.swingx.treetable.DefaultMutableTreeTableNode; import java.awt.*; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.ClipboardOwner; import java.awt.datatransfer.Transferable; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * Implementation of ChartSelection on Gantt chart. * * @author dbarashev (Dmitry Barashev) */ public class GanttChartSelection extends ChartSelectionImpl implements ClipboardOwner { private static final Function<DefaultMutableTreeTableNode, DefaultMutableTreeTableNode> getParentNode = new Function<DefaultMutableTreeTableNode, DefaultMutableTreeTableNode>() { @Override public DefaultMutableTreeTableNode apply(DefaultMutableTreeTableNode node) { return (DefaultMutableTreeTableNode) node.getParent(); } }; private final RetainRootsAlgorithm<DefaultMutableTreeTableNode> myRetainRootsAlgorithm = new RetainRootsAlgorithm<DefaultMutableTreeTableNode>(); private final TreeTableContainer<Task, GanttTreeTable, GanttTreeTableModel> myTree; private final TaskManager myTaskManager; private final IGanttProject myProject; private ClipboardContents myClipboardContents; private Function<? super DefaultMutableTreeTableNode, ? extends Task> getTaskFromNode = new Function<DefaultMutableTreeTableNode, Task>() { @Override public Task apply(DefaultMutableTreeTableNode node) { return (Task) node.getUserObject(); } }; GanttChartSelection(IGanttProject project, TreeTableContainer<Task, GanttTreeTable, GanttTreeTableModel> treeView, TaskManager taskManager) { myTree = treeView; myTaskManager = taskManager; myProject = project; } @Override public boolean isEmpty() { return myTree.getSelectedNodes().length == 0; } @Override public void startCopyClipboardTransaction() { super.startCopyClipboardTransaction(); myClipboardContents = buildClipboardContents(); myClipboardContents.copy(); exportTasksIntoSystemClipboard(); } private void exportTasksIntoSystemClipboard() { Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(new GPTransferable(myClipboardContents), this); } @Override public void startMoveClipboardTransaction() { super.startMoveClipboardTransaction(); myClipboardContents = buildClipboardContents(); myClipboardContents.cut(); exportTasksIntoSystemClipboard(); } public ClipboardContents buildClipboardContents() { DefaultMutableTreeTableNode[] selectedNodes = myTree.getSelectedNodes(); GPLogger.getLogger("Clipboard").fine(String.format("Selected nodes: %s", Arrays.asList(selectedNodes))); List<DefaultMutableTreeTableNode> selectedRoots = Lists.newArrayList(); myRetainRootsAlgorithm.run(selectedNodes, getParentNode, selectedRoots); GPLogger.getLogger("Clipboard").fine(String.format("Roots: %s", selectedRoots)); ClipboardContents result = new ClipboardContents(myTaskManager); result.addTasks(Lists.transform(selectedRoots, getTaskFromNode)); return result; } List<Task> paste(Task target) { if (myClipboardContents == null) { return Collections.emptyList(); } ClipboardTaskProcessor processor = new ClipboardTaskProcessor(myTaskManager); processor.setTaskCopyNameOption(myTaskManager.getTaskCopyNamePrefixOption()); return processor.pasteAsSibling(target, myClipboardContents); } @Override public void lostOwnership(Clipboard clipboard, Transferable contents) { // Do nothing } }
923e76334e416f8578d61755a269b1465fe67560
765
java
Java
hub-saml-test-utils/src/main/java/uk/gov/ida/saml/core/test/builders/StatusMessageBuilder.java
karlbaker02/verify-hub
c18b5cc5cc3563639e9e849ee519640e5d6b3a05
[ "MIT" ]
10
2017-12-08T17:13:09.000Z
2020-11-20T11:05:12.000Z
hub-saml-test-utils/src/main/java/uk/gov/ida/saml/core/test/builders/StatusMessageBuilder.java
karlbaker02/verify-hub
c18b5cc5cc3563639e9e849ee519640e5d6b3a05
[ "MIT" ]
212
2017-12-11T09:53:52.000Z
2022-03-31T00:27:54.000Z
hub-saml-test-utils/src/main/java/uk/gov/ida/saml/core/test/builders/StatusMessageBuilder.java
karlbaker02/verify-hub
c18b5cc5cc3563639e9e849ee519640e5d6b3a05
[ "MIT" ]
6
2017-12-08T17:13:22.000Z
2021-04-10T18:07:44.000Z
26.37931
102
0.735948
1,000,768
package uk.gov.ida.saml.core.test.builders; import org.opensaml.saml.saml2.core.StatusMessage; import uk.gov.ida.saml.core.OpenSamlXmlObjectFactory; public class StatusMessageBuilder { private static OpenSamlXmlObjectFactory openSamlXmlObjectFactory = new OpenSamlXmlObjectFactory(); private String message = "default message"; public static StatusMessageBuilder aStatusMessage() { return new StatusMessageBuilder(); } public StatusMessage build() { StatusMessage statusCode = openSamlXmlObjectFactory.createStatusMessage(); statusCode.setMessage(message); return statusCode; } public StatusMessageBuilder withMessage(String message) { this.message = message; return this; } }
923e7714a0607de56ce127cd675dba1572bade59
4,326
java
Java
src/main/java/com/qouteall/imm_ptl_peripheral/altius_world/WorldCreationDimensionHelper.java
PolymorphicApe/ImmersivePortalsModForForge
f078a43e522975f3b3a155010b6f76ecdad7c95a
[ "Apache-2.0" ]
68
2019-11-24T15:07:15.000Z
2022-03-15T05:43:53.000Z
src/main/java/com/qouteall/imm_ptl_peripheral/altius_world/WorldCreationDimensionHelper.java
PolymorphicApe/ImmersivePortalsModForForge
f078a43e522975f3b3a155010b6f76ecdad7c95a
[ "Apache-2.0" ]
303
2019-11-27T15:39:31.000Z
2022-03-07T15:17:42.000Z
src/main/java/com/qouteall/imm_ptl_peripheral/altius_world/WorldCreationDimensionHelper.java
PolymorphicApe/ImmersivePortalsModForForge
f078a43e522975f3b3a155010b6f76ecdad7c95a
[ "Apache-2.0" ]
40
2020-04-23T17:51:38.000Z
2022-03-15T05:41:54.000Z
44.142857
160
0.731854
1,000,769
package com.qouteall.imm_ptl_peripheral.altius_world; import com.google.gson.JsonElement; import com.mojang.serialization.DataResult; import com.mojang.serialization.JsonOps; import com.mojang.serialization.Lifecycle; import com.qouteall.imm_ptl_peripheral.ducks.IECreateWorldScreen; import com.qouteall.immersive_portals.Helper; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.screen.CreateWorldScreen; import net.minecraft.command.Commands; import net.minecraft.resources.DataPackRegistries; import net.minecraft.resources.IResourceManager; import net.minecraft.resources.ResourcePackList; import net.minecraft.server.MinecraftServer; import net.minecraft.util.Util; import net.minecraft.util.datafix.codec.DatapackCodec; import net.minecraft.util.registry.DynamicRegistries; import net.minecraft.util.registry.WorldGenSettingsExport; import net.minecraft.util.registry.WorldSettingsImport; import net.minecraft.world.gen.settings.DimensionGeneratorSettings; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; public class WorldCreationDimensionHelper { public static IResourceManager fetchResourceManager( ResourcePackList resourcePackManager, DatapackCodec dataPackSettings ) { final Minecraft client = Minecraft.getInstance(); Helper.log("Getting Dimension List"); DatapackCodec dataPackSettings2 = MinecraftServer.func_240772_a_( resourcePackManager, dataPackSettings, true ); CompletableFuture<DataPackRegistries> completableFuture = DataPackRegistries.func_240961_a_( resourcePackManager.func_232623_f_(), Commands.EnvironmentType.INTEGRATED, 2, Util.getServerExecutor(), client ); client.driveUntil(completableFuture::isDone); DataPackRegistries serverResourceManager = null; try { serverResourceManager = (DataPackRegistries) completableFuture.get(); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } return serverResourceManager.func_240970_h_(); } public static DimensionGeneratorSettings getPopulatedGeneratorOptions( DynamicRegistries.Impl registryTracker, IResourceManager resourceManager, DimensionGeneratorSettings generatorOptions ) { WorldGenSettingsExport<JsonElement> registryReadingOps = WorldGenSettingsExport.func_240896_a_(JsonOps.INSTANCE, registryTracker); WorldSettingsImport<JsonElement> registryOps = WorldSettingsImport.func_244335_a(JsonOps.INSTANCE, (IResourceManager) resourceManager, registryTracker); DataResult<DimensionGeneratorSettings> dataResult = DimensionGeneratorSettings.field_236201_a_.encodeStart(registryReadingOps, generatorOptions) .setLifecycle(Lifecycle.stable()) .flatMap((jsonElement) -> { return DimensionGeneratorSettings.field_236201_a_.parse(registryOps, jsonElement); }); DimensionGeneratorSettings result = (DimensionGeneratorSettings) dataResult.resultOrPartial( Util.func_240982_a_( "Error reading worldgen settings after loading data packs: ", Helper::log ) ).orElse(generatorOptions); return result; } public static DimensionGeneratorSettings getPopulatedGeneratorOptions(CreateWorldScreen createWorldScreen, DimensionGeneratorSettings rawGeneratorOptions) { IECreateWorldScreen ieCreateWorldScreen = (IECreateWorldScreen) createWorldScreen; IResourceManager resourceManager = fetchResourceManager( ieCreateWorldScreen.portal_getResourcePackManager(), ieCreateWorldScreen.portal_getDataPackSettings() ); final DynamicRegistries.Impl registryTracker = createWorldScreen.field_238934_c_.func_239055_b_(); DimensionGeneratorSettings populatedGeneratorOptions = getPopulatedGeneratorOptions( registryTracker, resourceManager, rawGeneratorOptions ); return populatedGeneratorOptions; } }