repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
218
func_name
stringlengths
4
140
whole_func_string
stringlengths
153
5.32k
language
stringclasses
1 value
func_code_string
stringlengths
72
4k
func_code_tokens
sequencelengths
20
832
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
sequencelengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
102
339
jenkinsci/jenkins
core/src/main/java/jenkins/util/SystemProperties.java
SystemProperties.getString
public static String getString(String key, @CheckForNull String def, Level logLevel) { """ Gets the system property indicated by the specified key, or a default value. This behaves just like {@link System#getProperty(java.lang.String, java.lang.String)}, except that it also consults the {@link ServletContext}'s "init" parameters. @param key the name of the system property. @param def a default value. @param logLevel the level of the log if the provided key is not found. @return the string value of the system property, or {@code null} if the property is missing and the default value is {@code null}. @exception NullPointerException if {@code key} is {@code null}. @exception IllegalArgumentException if {@code key} is empty. """ String value = System.getProperty(key); // keep passing on any exceptions if (value != null) { if (LOGGER.isLoggable(logLevel)) { LOGGER.log(logLevel, "Property (system): {0} => {1}", new Object[] {key, value}); } return value; } value = handler.getString(key); if (value != null) { if (LOGGER.isLoggable(logLevel)) { LOGGER.log(logLevel, "Property (context): {0} => {1}", new Object[]{key, value}); } return value; } value = def; if (LOGGER.isLoggable(logLevel)) { LOGGER.log(logLevel, "Property (default): {0} => {1}", new Object[] {key, value}); } return value; }
java
public static String getString(String key, @CheckForNull String def, Level logLevel) { String value = System.getProperty(key); // keep passing on any exceptions if (value != null) { if (LOGGER.isLoggable(logLevel)) { LOGGER.log(logLevel, "Property (system): {0} => {1}", new Object[] {key, value}); } return value; } value = handler.getString(key); if (value != null) { if (LOGGER.isLoggable(logLevel)) { LOGGER.log(logLevel, "Property (context): {0} => {1}", new Object[]{key, value}); } return value; } value = def; if (LOGGER.isLoggable(logLevel)) { LOGGER.log(logLevel, "Property (default): {0} => {1}", new Object[] {key, value}); } return value; }
[ "public", "static", "String", "getString", "(", "String", "key", ",", "@", "CheckForNull", "String", "def", ",", "Level", "logLevel", ")", "{", "String", "value", "=", "System", ".", "getProperty", "(", "key", ")", ";", "// keep passing on any exceptions", "if", "(", "value", "!=", "null", ")", "{", "if", "(", "LOGGER", ".", "isLoggable", "(", "logLevel", ")", ")", "{", "LOGGER", ".", "log", "(", "logLevel", ",", "\"Property (system): {0} => {1}\"", ",", "new", "Object", "[", "]", "{", "key", ",", "value", "}", ")", ";", "}", "return", "value", ";", "}", "value", "=", "handler", ".", "getString", "(", "key", ")", ";", "if", "(", "value", "!=", "null", ")", "{", "if", "(", "LOGGER", ".", "isLoggable", "(", "logLevel", ")", ")", "{", "LOGGER", ".", "log", "(", "logLevel", ",", "\"Property (context): {0} => {1}\"", ",", "new", "Object", "[", "]", "{", "key", ",", "value", "}", ")", ";", "}", "return", "value", ";", "}", "value", "=", "def", ";", "if", "(", "LOGGER", ".", "isLoggable", "(", "logLevel", ")", ")", "{", "LOGGER", ".", "log", "(", "logLevel", ",", "\"Property (default): {0} => {1}\"", ",", "new", "Object", "[", "]", "{", "key", ",", "value", "}", ")", ";", "}", "return", "value", ";", "}" ]
Gets the system property indicated by the specified key, or a default value. This behaves just like {@link System#getProperty(java.lang.String, java.lang.String)}, except that it also consults the {@link ServletContext}'s "init" parameters. @param key the name of the system property. @param def a default value. @param logLevel the level of the log if the provided key is not found. @return the string value of the system property, or {@code null} if the property is missing and the default value is {@code null}. @exception NullPointerException if {@code key} is {@code null}. @exception IllegalArgumentException if {@code key} is empty.
[ "Gets", "the", "system", "property", "indicated", "by", "the", "specified", "key", "or", "a", "default", "value", ".", "This", "behaves", "just", "like", "{", "@link", "System#getProperty", "(", "java", ".", "lang", ".", "String", "java", ".", "lang", ".", "String", ")", "}", "except", "that", "it", "also", "consults", "the", "{", "@link", "ServletContext", "}", "s", "init", "parameters", "." ]
train
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/jenkins/util/SystemProperties.java#L238-L260
voldemort/voldemort
src/java/voldemort/store/stats/ClientSocketStats.java
ClientSocketStats.recordCheckoutTimeUs
public void recordCheckoutTimeUs(SocketDestination dest, long checkoutTimeUs) { """ Record the checkout wait time in us @param dest Destination of the socket to checkout. Will actually record if null. Otherwise will call this on self and corresponding child with this param null. @param checkoutTimeUs The number of us to wait before getting a socket """ if(dest != null) { getOrCreateNodeStats(dest).recordCheckoutTimeUs(null, checkoutTimeUs); recordCheckoutTimeUs(null, checkoutTimeUs); } else { this.checkoutTimeRequestCounter.addRequest(checkoutTimeUs * Time.NS_PER_US); } }
java
public void recordCheckoutTimeUs(SocketDestination dest, long checkoutTimeUs) { if(dest != null) { getOrCreateNodeStats(dest).recordCheckoutTimeUs(null, checkoutTimeUs); recordCheckoutTimeUs(null, checkoutTimeUs); } else { this.checkoutTimeRequestCounter.addRequest(checkoutTimeUs * Time.NS_PER_US); } }
[ "public", "void", "recordCheckoutTimeUs", "(", "SocketDestination", "dest", ",", "long", "checkoutTimeUs", ")", "{", "if", "(", "dest", "!=", "null", ")", "{", "getOrCreateNodeStats", "(", "dest", ")", ".", "recordCheckoutTimeUs", "(", "null", ",", "checkoutTimeUs", ")", ";", "recordCheckoutTimeUs", "(", "null", ",", "checkoutTimeUs", ")", ";", "}", "else", "{", "this", ".", "checkoutTimeRequestCounter", ".", "addRequest", "(", "checkoutTimeUs", "*", "Time", ".", "NS_PER_US", ")", ";", "}", "}" ]
Record the checkout wait time in us @param dest Destination of the socket to checkout. Will actually record if null. Otherwise will call this on self and corresponding child with this param null. @param checkoutTimeUs The number of us to wait before getting a socket
[ "Record", "the", "checkout", "wait", "time", "in", "us" ]
train
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/stats/ClientSocketStats.java#L265-L272
zaproxy/zaproxy
src/org/parosproxy/paros/view/WorkbenchPanel.java
WorkbenchPanel.addPanel
private static void addPanel(TabbedPanel2 tabbedPanel, AbstractPanel panel, boolean visible) { """ Adds the given {@code panel} to the given {@code tabbedPanel}. @param tabbedPanel the tabbed panel to add the panel @param panel the panel to add @param visible {@code true} if the panel should be visible, {@code false} otherwise. @see #addPanels(TabbedPanel2, List, boolean) """ if (visible) { tabbedPanel.addTab(panel); } else { tabbedPanel.addTabHidden(panel); } }
java
private static void addPanel(TabbedPanel2 tabbedPanel, AbstractPanel panel, boolean visible) { if (visible) { tabbedPanel.addTab(panel); } else { tabbedPanel.addTabHidden(panel); } }
[ "private", "static", "void", "addPanel", "(", "TabbedPanel2", "tabbedPanel", ",", "AbstractPanel", "panel", ",", "boolean", "visible", ")", "{", "if", "(", "visible", ")", "{", "tabbedPanel", ".", "addTab", "(", "panel", ")", ";", "}", "else", "{", "tabbedPanel", ".", "addTabHidden", "(", "panel", ")", ";", "}", "}" ]
Adds the given {@code panel} to the given {@code tabbedPanel}. @param tabbedPanel the tabbed panel to add the panel @param panel the panel to add @param visible {@code true} if the panel should be visible, {@code false} otherwise. @see #addPanels(TabbedPanel2, List, boolean)
[ "Adds", "the", "given", "{", "@code", "panel", "}", "to", "the", "given", "{", "@code", "tabbedPanel", "}", "." ]
train
https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/parosproxy/paros/view/WorkbenchPanel.java#L893-L899
Azure/azure-sdk-for-java
datalakestore/resource-manager/v2016_11_01/src/main/java/com/microsoft/azure/management/datalakestore/v2016_11_01/implementation/TrustedIdProvidersInner.java
TrustedIdProvidersInner.createOrUpdate
public TrustedIdProviderInner createOrUpdate(String resourceGroupName, String accountName, String trustedIdProviderName, CreateOrUpdateTrustedIdProviderParameters parameters) { """ Creates or updates the specified trusted identity provider. During update, the trusted identity provider with the specified name will be replaced with this new provider. @param resourceGroupName The name of the Azure resource group. @param accountName The name of the Data Lake Store account. @param trustedIdProviderName The name of the trusted identity provider. This is used for differentiation of providers in the account. @param parameters Parameters supplied to create or replace the trusted identity provider. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the TrustedIdProviderInner object if successful. """ return createOrUpdateWithServiceResponseAsync(resourceGroupName, accountName, trustedIdProviderName, parameters).toBlocking().single().body(); }
java
public TrustedIdProviderInner createOrUpdate(String resourceGroupName, String accountName, String trustedIdProviderName, CreateOrUpdateTrustedIdProviderParameters parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, accountName, trustedIdProviderName, parameters).toBlocking().single().body(); }
[ "public", "TrustedIdProviderInner", "createOrUpdate", "(", "String", "resourceGroupName", ",", "String", "accountName", ",", "String", "trustedIdProviderName", ",", "CreateOrUpdateTrustedIdProviderParameters", "parameters", ")", "{", "return", "createOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "accountName", ",", "trustedIdProviderName", ",", "parameters", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Creates or updates the specified trusted identity provider. During update, the trusted identity provider with the specified name will be replaced with this new provider. @param resourceGroupName The name of the Azure resource group. @param accountName The name of the Data Lake Store account. @param trustedIdProviderName The name of the trusted identity provider. This is used for differentiation of providers in the account. @param parameters Parameters supplied to create or replace the trusted identity provider. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the TrustedIdProviderInner object if successful.
[ "Creates", "or", "updates", "the", "specified", "trusted", "identity", "provider", ".", "During", "update", "the", "trusted", "identity", "provider", "with", "the", "specified", "name", "will", "be", "replaced", "with", "this", "new", "provider", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/datalakestore/resource-manager/v2016_11_01/src/main/java/com/microsoft/azure/management/datalakestore/v2016_11_01/implementation/TrustedIdProvidersInner.java#L228-L230
gallandarakhneorg/afc
core/vmutils/src/main/java/org/arakhne/afc/vmutil/asserts/AssertMessages.java
AssertMessages.tooSmallArrayParameter
@Pure public static String tooSmallArrayParameter(int parameterIndex, int currentSize, int expectedSize) { """ Size of the array parameter is too small. @param parameterIndex the index of the formal parameter. @param currentSize current size of the array. @param expectedSize expected size. @return the error message. """ return msg("A5", parameterIndex, currentSize, expectedSize); //$NON-NLS-1$ }
java
@Pure public static String tooSmallArrayParameter(int parameterIndex, int currentSize, int expectedSize) { return msg("A5", parameterIndex, currentSize, expectedSize); //$NON-NLS-1$ }
[ "@", "Pure", "public", "static", "String", "tooSmallArrayParameter", "(", "int", "parameterIndex", ",", "int", "currentSize", ",", "int", "expectedSize", ")", "{", "return", "msg", "(", "\"A5\"", ",", "parameterIndex", ",", "currentSize", ",", "expectedSize", ")", ";", "//$NON-NLS-1$", "}" ]
Size of the array parameter is too small. @param parameterIndex the index of the formal parameter. @param currentSize current size of the array. @param expectedSize expected size. @return the error message.
[ "Size", "of", "the", "array", "parameter", "is", "too", "small", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/vmutils/src/main/java/org/arakhne/afc/vmutil/asserts/AssertMessages.java#L316-L319
Azure/azure-sdk-for-java
edgegateway/resource-manager/v2019_03_01/src/main/java/com/microsoft/azure/management/edgegateway/v2019_03_01/implementation/DevicesInner.java
DevicesInner.beginInstallUpdatesAsync
public Observable<Void> beginInstallUpdatesAsync(String deviceName, String resourceGroupName) { """ Installs the updates on the data box edge/gateway device. @param deviceName The device name. @param resourceGroupName The resource group name. @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceResponse} object if successful. """ return beginInstallUpdatesWithServiceResponseAsync(deviceName, resourceGroupName).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); }
java
public Observable<Void> beginInstallUpdatesAsync(String deviceName, String resourceGroupName) { return beginInstallUpdatesWithServiceResponseAsync(deviceName, resourceGroupName).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Void", ">", "beginInstallUpdatesAsync", "(", "String", "deviceName", ",", "String", "resourceGroupName", ")", "{", "return", "beginInstallUpdatesWithServiceResponseAsync", "(", "deviceName", ",", "resourceGroupName", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "Void", ">", ",", "Void", ">", "(", ")", "{", "@", "Override", "public", "Void", "call", "(", "ServiceResponse", "<", "Void", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Installs the updates on the data box edge/gateway device. @param deviceName The device name. @param resourceGroupName The resource group name. @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceResponse} object if successful.
[ "Installs", "the", "updates", "on", "the", "data", "box", "edge", "/", "gateway", "device", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/edgegateway/resource-manager/v2019_03_01/src/main/java/com/microsoft/azure/management/edgegateway/v2019_03_01/implementation/DevicesInner.java#L1535-L1542
twitter/cloudhopper-commons
ch-commons-util/src/main/java/com/cloudhopper/commons/util/ByteUtil.java
ByteUtil.encodeHex
@Deprecated public static String encodeHex(byte[] data, char delimiter) { """ Encodes a byte array into a hex string (hex dump). @deprecated Please see class HexUtil """ // the result StringBuilder result = new StringBuilder(); short val = 0; // encode each byte into a hex dump for (int i = 0; i < data.length; i++) { val = decodeUnsigned(data[i]); result.append(padLeading(Integer.toHexString((int) val), 2)); result.append(delimiter); } // return encoded text return result.toString(); }
java
@Deprecated public static String encodeHex(byte[] data, char delimiter) { // the result StringBuilder result = new StringBuilder(); short val = 0; // encode each byte into a hex dump for (int i = 0; i < data.length; i++) { val = decodeUnsigned(data[i]); result.append(padLeading(Integer.toHexString((int) val), 2)); result.append(delimiter); } // return encoded text return result.toString(); }
[ "@", "Deprecated", "public", "static", "String", "encodeHex", "(", "byte", "[", "]", "data", ",", "char", "delimiter", ")", "{", "// the result", "StringBuilder", "result", "=", "new", "StringBuilder", "(", ")", ";", "short", "val", "=", "0", ";", "// encode each byte into a hex dump", "for", "(", "int", "i", "=", "0", ";", "i", "<", "data", ".", "length", ";", "i", "++", ")", "{", "val", "=", "decodeUnsigned", "(", "data", "[", "i", "]", ")", ";", "result", ".", "append", "(", "padLeading", "(", "Integer", ".", "toHexString", "(", "(", "int", ")", "val", ")", ",", "2", ")", ")", ";", "result", ".", "append", "(", "delimiter", ")", ";", "}", "// return encoded text", "return", "result", ".", "toString", "(", ")", ";", "}" ]
Encodes a byte array into a hex string (hex dump). @deprecated Please see class HexUtil
[ "Encodes", "a", "byte", "array", "into", "a", "hex", "string", "(", "hex", "dump", ")", "." ]
train
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-util/src/main/java/com/cloudhopper/commons/util/ByteUtil.java#L156-L172
paypal/SeLion
dataproviders/src/main/java/com/paypal/selion/platform/dataprovider/impl/ReflectionUtils.java
ReflectionUtils.instantiatePrimitiveArray
public static Object instantiatePrimitiveArray(Class<?> type, String[] values) { """ This helper method facilitates creation of primitive arrays and pre-populates them with the set of String values provided. @param type The type of the array to create. Note that this method will only accept primitive types (as the name suggests) i.e., only int[],float[], boolean[] and so on. @param values A {@link String} array that represents the set of values that should be used to pre-populate the newly constructed array. @return An array of the type that was specified. """ logger.entering(new Object[] { type, values }); validateParams(type, values); checkArgument(isPrimitiveArray(type), type + " is NOT a primitive array type."); Class<?> componentType = type.getComponentType(); Object arrayToReturn = Array.newInstance(componentType, values.length); Method parserMethod = getParserMethod(componentType); for (int i = 0; i < values.length; i++) { try { Array.set(arrayToReturn, i, parserMethod.invoke(arrayToReturn, values[i])); } catch (ArrayIndexOutOfBoundsException | IllegalArgumentException | IllegalAccessException | InvocationTargetException e) { throw new ReflectionException(e); } } logger.exiting(arrayToReturn); return arrayToReturn; }
java
public static Object instantiatePrimitiveArray(Class<?> type, String[] values) { logger.entering(new Object[] { type, values }); validateParams(type, values); checkArgument(isPrimitiveArray(type), type + " is NOT a primitive array type."); Class<?> componentType = type.getComponentType(); Object arrayToReturn = Array.newInstance(componentType, values.length); Method parserMethod = getParserMethod(componentType); for (int i = 0; i < values.length; i++) { try { Array.set(arrayToReturn, i, parserMethod.invoke(arrayToReturn, values[i])); } catch (ArrayIndexOutOfBoundsException | IllegalArgumentException | IllegalAccessException | InvocationTargetException e) { throw new ReflectionException(e); } } logger.exiting(arrayToReturn); return arrayToReturn; }
[ "public", "static", "Object", "instantiatePrimitiveArray", "(", "Class", "<", "?", ">", "type", ",", "String", "[", "]", "values", ")", "{", "logger", ".", "entering", "(", "new", "Object", "[", "]", "{", "type", ",", "values", "}", ")", ";", "validateParams", "(", "type", ",", "values", ")", ";", "checkArgument", "(", "isPrimitiveArray", "(", "type", ")", ",", "type", "+", "\" is NOT a primitive array type.\"", ")", ";", "Class", "<", "?", ">", "componentType", "=", "type", ".", "getComponentType", "(", ")", ";", "Object", "arrayToReturn", "=", "Array", ".", "newInstance", "(", "componentType", ",", "values", ".", "length", ")", ";", "Method", "parserMethod", "=", "getParserMethod", "(", "componentType", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "values", ".", "length", ";", "i", "++", ")", "{", "try", "{", "Array", ".", "set", "(", "arrayToReturn", ",", "i", ",", "parserMethod", ".", "invoke", "(", "arrayToReturn", ",", "values", "[", "i", "]", ")", ")", ";", "}", "catch", "(", "ArrayIndexOutOfBoundsException", "|", "IllegalArgumentException", "|", "IllegalAccessException", "|", "InvocationTargetException", "e", ")", "{", "throw", "new", "ReflectionException", "(", "e", ")", ";", "}", "}", "logger", ".", "exiting", "(", "arrayToReturn", ")", ";", "return", "arrayToReturn", ";", "}" ]
This helper method facilitates creation of primitive arrays and pre-populates them with the set of String values provided. @param type The type of the array to create. Note that this method will only accept primitive types (as the name suggests) i.e., only int[],float[], boolean[] and so on. @param values A {@link String} array that represents the set of values that should be used to pre-populate the newly constructed array. @return An array of the type that was specified.
[ "This", "helper", "method", "facilitates", "creation", "of", "primitive", "arrays", "and", "pre", "-", "populates", "them", "with", "the", "set", "of", "String", "values", "provided", "." ]
train
https://github.com/paypal/SeLion/blob/694d12d0df76db48d0360b16192770c6a4fbdfd2/dataproviders/src/main/java/com/paypal/selion/platform/dataprovider/impl/ReflectionUtils.java#L161-L180
raydac/java-binary-block-parser
jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPDslBuilder.java
JBBPDslBuilder.BitArray
public JBBPDslBuilder BitArray(final JBBPBitNumber bits, final String sizeExpression) { """ Add anonymous bit array with size calculated through expression. @param bits length of the field, must not be null @param sizeExpression expression to be used to calculate array size, must not be null @return the builder instance, must not be null """ return this.BitArray(null, bits, assertExpressionChars(sizeExpression)); }
java
public JBBPDslBuilder BitArray(final JBBPBitNumber bits, final String sizeExpression) { return this.BitArray(null, bits, assertExpressionChars(sizeExpression)); }
[ "public", "JBBPDslBuilder", "BitArray", "(", "final", "JBBPBitNumber", "bits", ",", "final", "String", "sizeExpression", ")", "{", "return", "this", ".", "BitArray", "(", "null", ",", "bits", ",", "assertExpressionChars", "(", "sizeExpression", ")", ")", ";", "}" ]
Add anonymous bit array with size calculated through expression. @param bits length of the field, must not be null @param sizeExpression expression to be used to calculate array size, must not be null @return the builder instance, must not be null
[ "Add", "anonymous", "bit", "array", "with", "size", "calculated", "through", "expression", "." ]
train
https://github.com/raydac/java-binary-block-parser/blob/6d98abcab01e0c72d525ebcc9e7b694f9ce49f5b/jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPDslBuilder.java#L699-L701
aspectran/aspectran
web/src/main/java/com/aspectran/web/service/AspectranWebService.java
AspectranWebService.create
private static AspectranWebService create(ServletContext servletContext, String aspectranConfigParam) { """ Returns a new instance of {@code AspectranWebService}. @param servletContext the servlet context @param aspectranConfigParam the parameter for aspectran configuration @return the instance of {@code AspectranWebService} """ AspectranConfig aspectranConfig; if (aspectranConfigParam != null) { try { aspectranConfig = new AspectranConfig(aspectranConfigParam); } catch (AponParseException e) { throw new AspectranServiceException("Error parsing '" + ASPECTRAN_CONFIG_PARAM + "' initialization parameter for Aspectran Configuration", e); } } else { aspectranConfig = new AspectranConfig(); } ContextConfig contextConfig = aspectranConfig.touchContextConfig(); String rootFile = contextConfig.getRootFile(); if (!StringUtils.hasText(rootFile) && !contextConfig.hasAspectranParameters()) { contextConfig.setRootFile(DEFAULT_APP_CONFIG_ROOT_FILE); } AspectranWebService service = new AspectranWebService(servletContext); service.prepare(aspectranConfig); service.setDefaultServletHttpRequestHandler(servletContext); WebConfig webConfig = aspectranConfig.getWebConfig(); if (webConfig != null) { applyWebConfig(service, webConfig); } setServiceStateListener(service); return service; }
java
private static AspectranWebService create(ServletContext servletContext, String aspectranConfigParam) { AspectranConfig aspectranConfig; if (aspectranConfigParam != null) { try { aspectranConfig = new AspectranConfig(aspectranConfigParam); } catch (AponParseException e) { throw new AspectranServiceException("Error parsing '" + ASPECTRAN_CONFIG_PARAM + "' initialization parameter for Aspectran Configuration", e); } } else { aspectranConfig = new AspectranConfig(); } ContextConfig contextConfig = aspectranConfig.touchContextConfig(); String rootFile = contextConfig.getRootFile(); if (!StringUtils.hasText(rootFile) && !contextConfig.hasAspectranParameters()) { contextConfig.setRootFile(DEFAULT_APP_CONFIG_ROOT_FILE); } AspectranWebService service = new AspectranWebService(servletContext); service.prepare(aspectranConfig); service.setDefaultServletHttpRequestHandler(servletContext); WebConfig webConfig = aspectranConfig.getWebConfig(); if (webConfig != null) { applyWebConfig(service, webConfig); } setServiceStateListener(service); return service; }
[ "private", "static", "AspectranWebService", "create", "(", "ServletContext", "servletContext", ",", "String", "aspectranConfigParam", ")", "{", "AspectranConfig", "aspectranConfig", ";", "if", "(", "aspectranConfigParam", "!=", "null", ")", "{", "try", "{", "aspectranConfig", "=", "new", "AspectranConfig", "(", "aspectranConfigParam", ")", ";", "}", "catch", "(", "AponParseException", "e", ")", "{", "throw", "new", "AspectranServiceException", "(", "\"Error parsing '\"", "+", "ASPECTRAN_CONFIG_PARAM", "+", "\"' initialization parameter for Aspectran Configuration\"", ",", "e", ")", ";", "}", "}", "else", "{", "aspectranConfig", "=", "new", "AspectranConfig", "(", ")", ";", "}", "ContextConfig", "contextConfig", "=", "aspectranConfig", ".", "touchContextConfig", "(", ")", ";", "String", "rootFile", "=", "contextConfig", ".", "getRootFile", "(", ")", ";", "if", "(", "!", "StringUtils", ".", "hasText", "(", "rootFile", ")", "&&", "!", "contextConfig", ".", "hasAspectranParameters", "(", ")", ")", "{", "contextConfig", ".", "setRootFile", "(", "DEFAULT_APP_CONFIG_ROOT_FILE", ")", ";", "}", "AspectranWebService", "service", "=", "new", "AspectranWebService", "(", "servletContext", ")", ";", "service", ".", "prepare", "(", "aspectranConfig", ")", ";", "service", ".", "setDefaultServletHttpRequestHandler", "(", "servletContext", ")", ";", "WebConfig", "webConfig", "=", "aspectranConfig", ".", "getWebConfig", "(", ")", ";", "if", "(", "webConfig", "!=", "null", ")", "{", "applyWebConfig", "(", "service", ",", "webConfig", ")", ";", "}", "setServiceStateListener", "(", "service", ")", ";", "return", "service", ";", "}" ]
Returns a new instance of {@code AspectranWebService}. @param servletContext the servlet context @param aspectranConfigParam the parameter for aspectran configuration @return the instance of {@code AspectranWebService}
[ "Returns", "a", "new", "instance", "of", "{", "@code", "AspectranWebService", "}", "." ]
train
https://github.com/aspectran/aspectran/blob/2d758a2a28b71ee85b42823c12dc44674d7f2c70/web/src/main/java/com/aspectran/web/service/AspectranWebService.java#L280-L310
j256/ormlite-core
src/main/java/com/j256/ormlite/table/TableUtils.java
TableUtils.createTable
public static <T> int createTable(ConnectionSource connectionSource, DatabaseTableConfig<T> tableConfig) throws SQLException { """ Issue the database statements to create the table associated with a table configuration. @param connectionSource connectionSource Associated connection source. @param tableConfig Hand or spring wired table configuration. If null then the class must have {@link DatabaseField} annotations. @return The number of statements executed to do so. """ Dao<T, ?> dao = DaoManager.createDao(connectionSource, tableConfig); return doCreateTable(dao, false); }
java
public static <T> int createTable(ConnectionSource connectionSource, DatabaseTableConfig<T> tableConfig) throws SQLException { Dao<T, ?> dao = DaoManager.createDao(connectionSource, tableConfig); return doCreateTable(dao, false); }
[ "public", "static", "<", "T", ">", "int", "createTable", "(", "ConnectionSource", "connectionSource", ",", "DatabaseTableConfig", "<", "T", ">", "tableConfig", ")", "throws", "SQLException", "{", "Dao", "<", "T", ",", "?", ">", "dao", "=", "DaoManager", ".", "createDao", "(", "connectionSource", ",", "tableConfig", ")", ";", "return", "doCreateTable", "(", "dao", ",", "false", ")", ";", "}" ]
Issue the database statements to create the table associated with a table configuration. @param connectionSource connectionSource Associated connection source. @param tableConfig Hand or spring wired table configuration. If null then the class must have {@link DatabaseField} annotations. @return The number of statements executed to do so.
[ "Issue", "the", "database", "statements", "to", "create", "the", "table", "associated", "with", "a", "table", "configuration", "." ]
train
https://github.com/j256/ormlite-core/blob/154d85bbb9614a0ea65a012251257831fb4fba21/src/main/java/com/j256/ormlite/table/TableUtils.java#L88-L92
JOML-CI/JOML
src/org/joml/Matrix4x3f.java
Matrix4x3f.rotateAround
public Matrix4x3f rotateAround(Quaternionfc quat, float ox, float oy, float oz, Matrix4x3f dest) { """ /* (non-Javadoc) @see org.joml.Matrix4x3fc#rotateAround(org.joml.Quaternionfc, float, float, float, org.joml.Matrix4x3f) """ if ((properties & PROPERTY_IDENTITY) != 0) return rotationAround(quat, ox, oy, oz); return rotateAroundAffine(quat, ox, oy, oz, dest); }
java
public Matrix4x3f rotateAround(Quaternionfc quat, float ox, float oy, float oz, Matrix4x3f dest) { if ((properties & PROPERTY_IDENTITY) != 0) return rotationAround(quat, ox, oy, oz); return rotateAroundAffine(quat, ox, oy, oz, dest); }
[ "public", "Matrix4x3f", "rotateAround", "(", "Quaternionfc", "quat", ",", "float", "ox", ",", "float", "oy", ",", "float", "oz", ",", "Matrix4x3f", "dest", ")", "{", "if", "(", "(", "properties", "&", "PROPERTY_IDENTITY", ")", "!=", "0", ")", "return", "rotationAround", "(", "quat", ",", "ox", ",", "oy", ",", "oz", ")", ";", "return", "rotateAroundAffine", "(", "quat", ",", "ox", ",", "oy", ",", "oz", ",", "dest", ")", ";", "}" ]
/* (non-Javadoc) @see org.joml.Matrix4x3fc#rotateAround(org.joml.Quaternionfc, float, float, float, org.joml.Matrix4x3f)
[ "/", "*", "(", "non", "-", "Javadoc", ")" ]
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4x3f.java#L4055-L4059
Berico-Technologies/CLAVIN
src/main/java/com/bericotech/clavin/resolver/LuceneLocationResolver.java
LuceneLocationResolver.resolveLocations
@Override @Deprecated public List<ResolvedLocation> resolveLocations(List<LocationOccurrence> locations, boolean fuzzy) throws IOException, ParseException { """ Resolves the supplied list of location names into {@link ResolvedLocation}s containing {@link com.bericotech.clavin.gazetteer.GeoName} objects. Calls {@link com.bericotech.clavin.gazetteer.query.Gazetteer#getClosestLocations} on each location name to find all possible matches, then uses heuristics to select the best match for each by calling {@link ClavinLocationResolver#pickBestCandidates}. @param locations list of location names to be resolved @param fuzzy switch for turning on/off fuzzy matching @return list of {@link ResolvedLocation} objects @throws ParseException @throws IOException @deprecated 2.0.0 Use {@link ClavinLocationResolver#resolveLocations(java.util.List, boolean)} or {@link ClavinLocationResolver#resolveLocations(java.util.List, int, int, boolean)} """ logger.warn("LuceneLocationResolver is deprecated. Use ClavinLocationResolver."); try { return delegate.resolveLocations(locations, maxHitDepth, maxContextWindow, fuzzy); } catch (ClavinException ce) { Throwable t = ce.getCause(); if (t instanceof ParseException) { throw (ParseException)t; } else if (t instanceof IOException) { throw (IOException)t; } else { throw new IllegalStateException("Error resolving locations.", ce); } } }
java
@Override @Deprecated public List<ResolvedLocation> resolveLocations(List<LocationOccurrence> locations, boolean fuzzy) throws IOException, ParseException { logger.warn("LuceneLocationResolver is deprecated. Use ClavinLocationResolver."); try { return delegate.resolveLocations(locations, maxHitDepth, maxContextWindow, fuzzy); } catch (ClavinException ce) { Throwable t = ce.getCause(); if (t instanceof ParseException) { throw (ParseException)t; } else if (t instanceof IOException) { throw (IOException)t; } else { throw new IllegalStateException("Error resolving locations.", ce); } } }
[ "@", "Override", "@", "Deprecated", "public", "List", "<", "ResolvedLocation", ">", "resolveLocations", "(", "List", "<", "LocationOccurrence", ">", "locations", ",", "boolean", "fuzzy", ")", "throws", "IOException", ",", "ParseException", "{", "logger", ".", "warn", "(", "\"LuceneLocationResolver is deprecated. Use ClavinLocationResolver.\"", ")", ";", "try", "{", "return", "delegate", ".", "resolveLocations", "(", "locations", ",", "maxHitDepth", ",", "maxContextWindow", ",", "fuzzy", ")", ";", "}", "catch", "(", "ClavinException", "ce", ")", "{", "Throwable", "t", "=", "ce", ".", "getCause", "(", ")", ";", "if", "(", "t", "instanceof", "ParseException", ")", "{", "throw", "(", "ParseException", ")", "t", ";", "}", "else", "if", "(", "t", "instanceof", "IOException", ")", "{", "throw", "(", "IOException", ")", "t", ";", "}", "else", "{", "throw", "new", "IllegalStateException", "(", "\"Error resolving locations.\"", ",", "ce", ")", ";", "}", "}", "}" ]
Resolves the supplied list of location names into {@link ResolvedLocation}s containing {@link com.bericotech.clavin.gazetteer.GeoName} objects. Calls {@link com.bericotech.clavin.gazetteer.query.Gazetteer#getClosestLocations} on each location name to find all possible matches, then uses heuristics to select the best match for each by calling {@link ClavinLocationResolver#pickBestCandidates}. @param locations list of location names to be resolved @param fuzzy switch for turning on/off fuzzy matching @return list of {@link ResolvedLocation} objects @throws ParseException @throws IOException @deprecated 2.0.0 Use {@link ClavinLocationResolver#resolveLocations(java.util.List, boolean)} or {@link ClavinLocationResolver#resolveLocations(java.util.List, int, int, boolean)}
[ "Resolves", "the", "supplied", "list", "of", "location", "names", "into", "{", "@link", "ResolvedLocation", "}", "s", "containing", "{", "@link", "com", ".", "bericotech", ".", "clavin", ".", "gazetteer", ".", "GeoName", "}", "objects", "." ]
train
https://github.com/Berico-Technologies/CLAVIN/blob/f73c741f33a01b91aa5b06e71860bc354ef3010d/src/main/java/com/bericotech/clavin/resolver/LuceneLocationResolver.java#L113-L129
b3dgs/lionengine
lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/collision/CollisionGroupConfig.java
CollisionGroupConfig.imports
public static CollisionGroupConfig imports(Xml root, MapTileCollision map) { """ Create the collision group data from node. @param root The node root reference (must not be <code>null</code>). @param map The map reference (must not be <code>null</code>). @return The collisions group data. @throws LionEngineException If unable to read node. """ Check.notNull(root); Check.notNull(map); final Collection<Xml> childrenCollision = root.getChildren(NODE_COLLISION); final Map<String, CollisionGroup> groups = new HashMap<>(childrenCollision.size()); for (final Xml node : childrenCollision) { final Collection<Xml> childrenFormula = node.getChildren(CollisionFormulaConfig.NODE_FORMULA); final Collection<CollisionFormula> formulas = new ArrayList<>(childrenFormula.size()); for (final Xml formula : childrenFormula) { final String formulaName = formula.getText(); formulas.add(map.getCollisionFormula(formulaName)); } final String groupName = node.readString(ATT_GROUP); final CollisionGroup collision = new CollisionGroup(groupName, formulas); groups.put(groupName, collision); } return new CollisionGroupConfig(groups); }
java
public static CollisionGroupConfig imports(Xml root, MapTileCollision map) { Check.notNull(root); Check.notNull(map); final Collection<Xml> childrenCollision = root.getChildren(NODE_COLLISION); final Map<String, CollisionGroup> groups = new HashMap<>(childrenCollision.size()); for (final Xml node : childrenCollision) { final Collection<Xml> childrenFormula = node.getChildren(CollisionFormulaConfig.NODE_FORMULA); final Collection<CollisionFormula> formulas = new ArrayList<>(childrenFormula.size()); for (final Xml formula : childrenFormula) { final String formulaName = formula.getText(); formulas.add(map.getCollisionFormula(formulaName)); } final String groupName = node.readString(ATT_GROUP); final CollisionGroup collision = new CollisionGroup(groupName, formulas); groups.put(groupName, collision); } return new CollisionGroupConfig(groups); }
[ "public", "static", "CollisionGroupConfig", "imports", "(", "Xml", "root", ",", "MapTileCollision", "map", ")", "{", "Check", ".", "notNull", "(", "root", ")", ";", "Check", ".", "notNull", "(", "map", ")", ";", "final", "Collection", "<", "Xml", ">", "childrenCollision", "=", "root", ".", "getChildren", "(", "NODE_COLLISION", ")", ";", "final", "Map", "<", "String", ",", "CollisionGroup", ">", "groups", "=", "new", "HashMap", "<>", "(", "childrenCollision", ".", "size", "(", ")", ")", ";", "for", "(", "final", "Xml", "node", ":", "childrenCollision", ")", "{", "final", "Collection", "<", "Xml", ">", "childrenFormula", "=", "node", ".", "getChildren", "(", "CollisionFormulaConfig", ".", "NODE_FORMULA", ")", ";", "final", "Collection", "<", "CollisionFormula", ">", "formulas", "=", "new", "ArrayList", "<>", "(", "childrenFormula", ".", "size", "(", ")", ")", ";", "for", "(", "final", "Xml", "formula", ":", "childrenFormula", ")", "{", "final", "String", "formulaName", "=", "formula", ".", "getText", "(", ")", ";", "formulas", ".", "add", "(", "map", ".", "getCollisionFormula", "(", "formulaName", ")", ")", ";", "}", "final", "String", "groupName", "=", "node", ".", "readString", "(", "ATT_GROUP", ")", ";", "final", "CollisionGroup", "collision", "=", "new", "CollisionGroup", "(", "groupName", ",", "formulas", ")", ";", "groups", ".", "put", "(", "groupName", ",", "collision", ")", ";", "}", "return", "new", "CollisionGroupConfig", "(", "groups", ")", ";", "}" ]
Create the collision group data from node. @param root The node root reference (must not be <code>null</code>). @param map The map reference (must not be <code>null</code>). @return The collisions group data. @throws LionEngineException If unable to read node.
[ "Create", "the", "collision", "group", "data", "from", "node", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/collision/CollisionGroupConfig.java#L92-L117
RestComm/sipunit
src/main/java/org/cafesip/sipunit/SipStack.java
SipStack.createSipPhone
public SipPhone createSipPhone(String host, String me) throws InvalidArgumentException, ParseException { """ This method is the equivalent to the other createSipPhone() method, but using the default transport (UDP/IP) and the default SIP port number (5060). @param host host name or address of the SIP proxy to use. The proxy is used for registering and outbound calling on a per-call basis. If this parameter is a null value, any registration requests will be sent to the "host" part of the "me" parameter (see below) and any attempt to make an outbound call via proxy will fail. If a host name is given here, it must resolve to a valid, reachable DNS address. @param me "Address of Record" URI of the phone user. Each SipPhone is associated with one user. This parameter is used in the "from" header field. @return A new SipPhone object. @throws InvalidArgumentException @throws ParseException """ return createSipPhone(host, PROTOCOL_UDP, DEFAULT_PORT, me); }
java
public SipPhone createSipPhone(String host, String me) throws InvalidArgumentException, ParseException { return createSipPhone(host, PROTOCOL_UDP, DEFAULT_PORT, me); }
[ "public", "SipPhone", "createSipPhone", "(", "String", "host", ",", "String", "me", ")", "throws", "InvalidArgumentException", ",", "ParseException", "{", "return", "createSipPhone", "(", "host", ",", "PROTOCOL_UDP", ",", "DEFAULT_PORT", ",", "me", ")", ";", "}" ]
This method is the equivalent to the other createSipPhone() method, but using the default transport (UDP/IP) and the default SIP port number (5060). @param host host name or address of the SIP proxy to use. The proxy is used for registering and outbound calling on a per-call basis. If this parameter is a null value, any registration requests will be sent to the "host" part of the "me" parameter (see below) and any attempt to make an outbound call via proxy will fail. If a host name is given here, it must resolve to a valid, reachable DNS address. @param me "Address of Record" URI of the phone user. Each SipPhone is associated with one user. This parameter is used in the "from" header field. @return A new SipPhone object. @throws InvalidArgumentException @throws ParseException
[ "This", "method", "is", "the", "equivalent", "to", "the", "other", "createSipPhone", "()", "method", "but", "using", "the", "default", "transport", "(", "UDP", "/", "IP", ")", "and", "the", "default", "SIP", "port", "number", "(", "5060", ")", "." ]
train
https://github.com/RestComm/sipunit/blob/18a6be2e29be3fbdc14226e8c41b25e2d57378b1/src/main/java/org/cafesip/sipunit/SipStack.java#L303-L306
OpenLiberty/open-liberty
dev/com.ibm.ws.webcontainer.security/src/com/ibm/ws/webcontainer/security/internal/SRTServletRequestUtils.java
SRTServletRequestUtils.setPrivateAttribute
public static void setPrivateAttribute(HttpServletRequest req, String key, Object object) { """ Set a private attribute in the request (if applicable). If the request object is of an unexpected type, no operation occurs. @param req @param key @param object @see IPrivateRequestAttributes#setPrivateAttribute(String, Object) """ HttpServletRequest sr = getWrappedServletRequestObject(req); if (sr instanceof IPrivateRequestAttributes) { ((IPrivateRequestAttributes) sr).setPrivateAttribute(key, object); } else { if (tc.isDebugEnabled()) { Tr.debug(tc, "getPrivateAttribute called for non-IPrivateRequestAttributes object", req); } } }
java
public static void setPrivateAttribute(HttpServletRequest req, String key, Object object) { HttpServletRequest sr = getWrappedServletRequestObject(req); if (sr instanceof IPrivateRequestAttributes) { ((IPrivateRequestAttributes) sr).setPrivateAttribute(key, object); } else { if (tc.isDebugEnabled()) { Tr.debug(tc, "getPrivateAttribute called for non-IPrivateRequestAttributes object", req); } } }
[ "public", "static", "void", "setPrivateAttribute", "(", "HttpServletRequest", "req", ",", "String", "key", ",", "Object", "object", ")", "{", "HttpServletRequest", "sr", "=", "getWrappedServletRequestObject", "(", "req", ")", ";", "if", "(", "sr", "instanceof", "IPrivateRequestAttributes", ")", "{", "(", "(", "IPrivateRequestAttributes", ")", "sr", ")", ".", "setPrivateAttribute", "(", "key", ",", "object", ")", ";", "}", "else", "{", "if", "(", "tc", ".", "isDebugEnabled", "(", ")", ")", "{", "Tr", ".", "debug", "(", "tc", ",", "\"getPrivateAttribute called for non-IPrivateRequestAttributes object\"", ",", "req", ")", ";", "}", "}", "}" ]
Set a private attribute in the request (if applicable). If the request object is of an unexpected type, no operation occurs. @param req @param key @param object @see IPrivateRequestAttributes#setPrivateAttribute(String, Object)
[ "Set", "a", "private", "attribute", "in", "the", "request", "(", "if", "applicable", ")", ".", "If", "the", "request", "object", "is", "of", "an", "unexpected", "type", "no", "operation", "occurs", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.webcontainer.security/src/com/ibm/ws/webcontainer/security/internal/SRTServletRequestUtils.java#L57-L66
shapesecurity/shape-functional-java
src/main/java/com/shapesecurity/functional/data/ImmutableList.java
ImmutableList.from
@Nonnull @SafeVarargs public static <A> ImmutableList<A> from(@Nonnull A... el) { """ A helper constructor to create a potentially empty {@link ImmutableList}. @param el Elements of the list @param <A> The type of elements @return a <code>ImmutableList</code> of type <code>A</code>. """ return fromBounded(el, 0, el.length); }
java
@Nonnull @SafeVarargs public static <A> ImmutableList<A> from(@Nonnull A... el) { return fromBounded(el, 0, el.length); }
[ "@", "Nonnull", "@", "SafeVarargs", "public", "static", "<", "A", ">", "ImmutableList", "<", "A", ">", "from", "(", "@", "Nonnull", "A", "...", "el", ")", "{", "return", "fromBounded", "(", "el", ",", "0", ",", "el", ".", "length", ")", ";", "}" ]
A helper constructor to create a potentially empty {@link ImmutableList}. @param el Elements of the list @param <A> The type of elements @return a <code>ImmutableList</code> of type <code>A</code>.
[ "A", "helper", "constructor", "to", "create", "a", "potentially", "empty", "{", "@link", "ImmutableList", "}", "." ]
train
https://github.com/shapesecurity/shape-functional-java/blob/02edea5a901b8603f6a852478ec009857fa012d6/src/main/java/com/shapesecurity/functional/data/ImmutableList.java#L170-L174
dustin/java-memcached-client
src/main/java/net/spy/memcached/MemcachedClient.java
MemcachedClient.asyncCAS
@Override public <T> OperationFuture<CASResponse> asyncCAS(String key, long casId, T value, Transcoder<T> tc) { """ Asynchronous CAS operation. @param <T> @param key the key @param casId the CAS identifier (from a gets operation) @param value the new value @param tc the transcoder to serialize and unserialize the value @return a future that will indicate the status of the CAS @throws IllegalStateException in the rare circumstance where queue is too full to accept any more requests """ return asyncCAS(key, casId, 0, value, tc); }
java
@Override public <T> OperationFuture<CASResponse> asyncCAS(String key, long casId, T value, Transcoder<T> tc) { return asyncCAS(key, casId, 0, value, tc); }
[ "@", "Override", "public", "<", "T", ">", "OperationFuture", "<", "CASResponse", ">", "asyncCAS", "(", "String", "key", ",", "long", "casId", ",", "T", "value", ",", "Transcoder", "<", "T", ">", "tc", ")", "{", "return", "asyncCAS", "(", "key", ",", "casId", ",", "0", ",", "value", ",", "tc", ")", ";", "}" ]
Asynchronous CAS operation. @param <T> @param key the key @param casId the CAS identifier (from a gets operation) @param value the new value @param tc the transcoder to serialize and unserialize the value @return a future that will indicate the status of the CAS @throws IllegalStateException in the rare circumstance where queue is too full to accept any more requests
[ "Asynchronous", "CAS", "operation", "." ]
train
https://github.com/dustin/java-memcached-client/blob/c232307ad8e0c7ccc926e495dd7d5aad2d713318/src/main/java/net/spy/memcached/MemcachedClient.java#L601-L605
knightliao/disconf
disconf-client/src/main/java/com/baidu/disconf/client/addons/properties/ReloadingPropertyPlaceholderConfigurer.java
ReloadingPropertyPlaceholderConfigurer.addDependency
private void addDependency(DynamicProperty dynamic, String placeholder) { """ 建立 placeholder 与 dynamic 的对应关系 @param dynamic @param placeholder """ List<DynamicProperty> l = placeholderToDynamics.get(placeholder); if (l == null) { l = new ArrayList<DynamicProperty>(); placeholderToDynamics.put(placeholder, l); } if (!l.contains(dynamic)) { l.add(dynamic); } dynamic.addPlaceholder(placeholder); }
java
private void addDependency(DynamicProperty dynamic, String placeholder) { List<DynamicProperty> l = placeholderToDynamics.get(placeholder); if (l == null) { l = new ArrayList<DynamicProperty>(); placeholderToDynamics.put(placeholder, l); } if (!l.contains(dynamic)) { l.add(dynamic); } dynamic.addPlaceholder(placeholder); }
[ "private", "void", "addDependency", "(", "DynamicProperty", "dynamic", ",", "String", "placeholder", ")", "{", "List", "<", "DynamicProperty", ">", "l", "=", "placeholderToDynamics", ".", "get", "(", "placeholder", ")", ";", "if", "(", "l", "==", "null", ")", "{", "l", "=", "new", "ArrayList", "<", "DynamicProperty", ">", "(", ")", ";", "placeholderToDynamics", ".", "put", "(", "placeholder", ",", "l", ")", ";", "}", "if", "(", "!", "l", ".", "contains", "(", "dynamic", ")", ")", "{", "l", ".", "add", "(", "dynamic", ")", ";", "}", "dynamic", ".", "addPlaceholder", "(", "placeholder", ")", ";", "}" ]
建立 placeholder 与 dynamic 的对应关系 @param dynamic @param placeholder
[ "建立", "placeholder", "与", "dynamic", "的对应关系" ]
train
https://github.com/knightliao/disconf/blob/d413cbce9334fe38a5a24982ce4db3a6ed8e98ea/disconf-client/src/main/java/com/baidu/disconf/client/addons/properties/ReloadingPropertyPlaceholderConfigurer.java#L333-L343
wcm-io/wcm-io-handler
media/src/main/java/io/wcm/handler/media/markup/MediaMarkupBuilderUtil.java
MediaMarkupBuilderUtil.getMediaformatDimension
public static @NotNull Dimension getMediaformatDimension(@NotNull Media media) { """ Get dimension from first media format defined in media args. Fall back to dummy min. dimension if none specified. @param media Media metadata @return Dimension """ // Create dummy image element to be displayed in Edit mode as placeholder. MediaArgs mediaArgs = media.getMediaRequest().getMediaArgs(); MediaFormat[] mediaFormats = mediaArgs.getMediaFormats(); // detect width/height - either from media args, or from first media format long width = mediaArgs.getFixedWidth(); long height = mediaArgs.getFixedHeight(); if ((width == 0 || height == 0) && mediaFormats != null && mediaFormats.length > 0) { MediaFormat firstMediaFormat = mediaArgs.getMediaFormats()[0]; Dimension dimension = firstMediaFormat.getMinDimension(); if (dimension != null) { width = dimension.getWidth(); height = dimension.getHeight(); } } // fallback to min width/height if (width == 0) { width = MediaMarkupBuilder.DUMMY_MIN_DIMENSION; } if (height == 0) { height = MediaMarkupBuilder.DUMMY_MIN_DIMENSION; } return new Dimension(width, height); }
java
public static @NotNull Dimension getMediaformatDimension(@NotNull Media media) { // Create dummy image element to be displayed in Edit mode as placeholder. MediaArgs mediaArgs = media.getMediaRequest().getMediaArgs(); MediaFormat[] mediaFormats = mediaArgs.getMediaFormats(); // detect width/height - either from media args, or from first media format long width = mediaArgs.getFixedWidth(); long height = mediaArgs.getFixedHeight(); if ((width == 0 || height == 0) && mediaFormats != null && mediaFormats.length > 0) { MediaFormat firstMediaFormat = mediaArgs.getMediaFormats()[0]; Dimension dimension = firstMediaFormat.getMinDimension(); if (dimension != null) { width = dimension.getWidth(); height = dimension.getHeight(); } } // fallback to min width/height if (width == 0) { width = MediaMarkupBuilder.DUMMY_MIN_DIMENSION; } if (height == 0) { height = MediaMarkupBuilder.DUMMY_MIN_DIMENSION; } return new Dimension(width, height); }
[ "public", "static", "@", "NotNull", "Dimension", "getMediaformatDimension", "(", "@", "NotNull", "Media", "media", ")", "{", "// Create dummy image element to be displayed in Edit mode as placeholder.", "MediaArgs", "mediaArgs", "=", "media", ".", "getMediaRequest", "(", ")", ".", "getMediaArgs", "(", ")", ";", "MediaFormat", "[", "]", "mediaFormats", "=", "mediaArgs", ".", "getMediaFormats", "(", ")", ";", "// detect width/height - either from media args, or from first media format", "long", "width", "=", "mediaArgs", ".", "getFixedWidth", "(", ")", ";", "long", "height", "=", "mediaArgs", ".", "getFixedHeight", "(", ")", ";", "if", "(", "(", "width", "==", "0", "||", "height", "==", "0", ")", "&&", "mediaFormats", "!=", "null", "&&", "mediaFormats", ".", "length", ">", "0", ")", "{", "MediaFormat", "firstMediaFormat", "=", "mediaArgs", ".", "getMediaFormats", "(", ")", "[", "0", "]", ";", "Dimension", "dimension", "=", "firstMediaFormat", ".", "getMinDimension", "(", ")", ";", "if", "(", "dimension", "!=", "null", ")", "{", "width", "=", "dimension", ".", "getWidth", "(", ")", ";", "height", "=", "dimension", ".", "getHeight", "(", ")", ";", "}", "}", "// fallback to min width/height", "if", "(", "width", "==", "0", ")", "{", "width", "=", "MediaMarkupBuilder", ".", "DUMMY_MIN_DIMENSION", ";", "}", "if", "(", "height", "==", "0", ")", "{", "height", "=", "MediaMarkupBuilder", ".", "DUMMY_MIN_DIMENSION", ";", "}", "return", "new", "Dimension", "(", "width", ",", "height", ")", ";", "}" ]
Get dimension from first media format defined in media args. Fall back to dummy min. dimension if none specified. @param media Media metadata @return Dimension
[ "Get", "dimension", "from", "first", "media", "format", "defined", "in", "media", "args", ".", "Fall", "back", "to", "dummy", "min", ".", "dimension", "if", "none", "specified", "." ]
train
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/media/src/main/java/io/wcm/handler/media/markup/MediaMarkupBuilderUtil.java#L151-L177
looly/hutool
hutool-core/src/main/java/cn/hutool/core/map/MapUtil.java
MapUtil.getFloat
public static Float getFloat(Map<?, ?> map, Object key) { """ 获取Map指定key的值,并转换为Float @param map Map @param key 键 @return 值 @since 4.0.6 """ return get(map, key, Float.class); }
java
public static Float getFloat(Map<?, ?> map, Object key) { return get(map, key, Float.class); }
[ "public", "static", "Float", "getFloat", "(", "Map", "<", "?", ",", "?", ">", "map", ",", "Object", "key", ")", "{", "return", "get", "(", "map", ",", "key", ",", "Float", ".", "class", ")", ";", "}" ]
获取Map指定key的值,并转换为Float @param map Map @param key 键 @return 值 @since 4.0.6
[ "获取Map指定key的值,并转换为Float" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/map/MapUtil.java#L792-L794
FedericoPecora/meta-csp-framework
src/main/java/org/metacsp/multi/spatioTemporal/paths/PoseSteering.java
PoseSteering.interpolate
public PoseSteering interpolate(PoseSteering p2, double ratio) { """ Computes the {@link PoseSteering} between this {@link PoseSteering} and a given {@link PoseSteering} via bilinear interpolation. @param p2 The second {@link PoseSteering} used for interpolation. @param ratio Parameter in [0,1] used for bilinear interpolation. @return The {@link PoseSteering} between this {@link PoseSteering} and a given {@link PoseSteering} via bilinear interpolation. """ Pose interp = this.getPose().interpolate(p2.getPose(), ratio); return new PoseSteering(interp, Pose.lerpDegrees(getSteering(),p2.getSteering(),ratio)); }
java
public PoseSteering interpolate(PoseSteering p2, double ratio) { Pose interp = this.getPose().interpolate(p2.getPose(), ratio); return new PoseSteering(interp, Pose.lerpDegrees(getSteering(),p2.getSteering(),ratio)); }
[ "public", "PoseSteering", "interpolate", "(", "PoseSteering", "p2", ",", "double", "ratio", ")", "{", "Pose", "interp", "=", "this", ".", "getPose", "(", ")", ".", "interpolate", "(", "p2", ".", "getPose", "(", ")", ",", "ratio", ")", ";", "return", "new", "PoseSteering", "(", "interp", ",", "Pose", ".", "lerpDegrees", "(", "getSteering", "(", ")", ",", "p2", ".", "getSteering", "(", ")", ",", "ratio", ")", ")", ";", "}" ]
Computes the {@link PoseSteering} between this {@link PoseSteering} and a given {@link PoseSteering} via bilinear interpolation. @param p2 The second {@link PoseSteering} used for interpolation. @param ratio Parameter in [0,1] used for bilinear interpolation. @return The {@link PoseSteering} between this {@link PoseSteering} and a given {@link PoseSteering} via bilinear interpolation.
[ "Computes", "the", "{" ]
train
https://github.com/FedericoPecora/meta-csp-framework/blob/42aaef2e2b76d0f738427f0dd9653c4f62b40517/src/main/java/org/metacsp/multi/spatioTemporal/paths/PoseSteering.java#L135-L138
geomajas/geomajas-project-client-gwt2
common-gwt/command/src/main/java/org/geomajas/gwt/client/command/GwtCommandDispatcher.java
GwtCommandDispatcher.isEqual
private boolean isEqual(Object o1, Object o2) { """ Checks whether 2 objects are equal. Null-safe, 2 null objects are considered equal. @param o1 first object to compare @param o2 second object to compare @return true if object are equal, false otherwise """ return o1 == null ? o2 == null : o1.equals(o2); }
java
private boolean isEqual(Object o1, Object o2) { return o1 == null ? o2 == null : o1.equals(o2); }
[ "private", "boolean", "isEqual", "(", "Object", "o1", ",", "Object", "o2", ")", "{", "return", "o1", "==", "null", "?", "o2", "==", "null", ":", "o1", ".", "equals", "(", "o2", ")", ";", "}" ]
Checks whether 2 objects are equal. Null-safe, 2 null objects are considered equal. @param o1 first object to compare @param o2 second object to compare @return true if object are equal, false otherwise
[ "Checks", "whether", "2", "objects", "are", "equal", ".", "Null", "-", "safe", "2", "null", "objects", "are", "considered", "equal", "." ]
train
https://github.com/geomajas/geomajas-project-client-gwt2/blob/bd8d7904e861fa80522eed7b83c4ea99844180c7/common-gwt/command/src/main/java/org/geomajas/gwt/client/command/GwtCommandDispatcher.java#L686-L688
vdmeer/skb-java-base
src/main/java/de/vandermeer/skb/base/managers/MessageMgr.java
MessageMgr.createWarningMessage
public static Message5WH createWarningMessage(String what, Object ... obj) { """ Creates a new warning message. @param what the what part of the message (what has happened) @param obj objects to add to the message @return new information message """ return new Message5WH_Builder().addWhat(FormattingTupleWrapper.create(what, obj)).setType(E_MessageType.WARNING).build(); }
java
public static Message5WH createWarningMessage(String what, Object ... obj){ return new Message5WH_Builder().addWhat(FormattingTupleWrapper.create(what, obj)).setType(E_MessageType.WARNING).build(); }
[ "public", "static", "Message5WH", "createWarningMessage", "(", "String", "what", ",", "Object", "...", "obj", ")", "{", "return", "new", "Message5WH_Builder", "(", ")", ".", "addWhat", "(", "FormattingTupleWrapper", ".", "create", "(", "what", ",", "obj", ")", ")", ".", "setType", "(", "E_MessageType", ".", "WARNING", ")", ".", "build", "(", ")", ";", "}" ]
Creates a new warning message. @param what the what part of the message (what has happened) @param obj objects to add to the message @return new information message
[ "Creates", "a", "new", "warning", "message", "." ]
train
https://github.com/vdmeer/skb-java-base/blob/6d845bcc482aa9344d016e80c0c3455aeae13a13/src/main/java/de/vandermeer/skb/base/managers/MessageMgr.java#L112-L114
wcm-io/wcm-io-wcm
commons/src/main/java/io/wcm/wcm/commons/caching/ModificationDate.java
ModificationDate.get
@SuppressWarnings("null") public static @Nullable Date get(@Nullable Resource resource) { """ Looks for either jcr:lastModified or cq:lastModified property in the given resource, which can be either the jcr:content-ode of a cq-page, or a rendition node @param resource a resource with a cq:lastModified property *and/or* a file/jcr:content subnode with a jcr:lastModified property @return the date or null if last modified property could not be found """ if (resource == null) { return null; } ValueMap resourceProperties = resource.getValueMap(); // get the cq:lastModified property from the resource (used in jcr:content nodes of cq pages) Date cqModified = resourceProperties != null ? resourceProperties.get(NameConstants.PN_PAGE_LAST_MOD, Date.class) : null; // try to find a jcr:lastModified property that is used for binary uploads or cq paragraphs Date resourceModified = getResourceMetadataModificationTime(resource); // get the most recent date of both return mostRecent(cqModified, resourceModified); }
java
@SuppressWarnings("null") public static @Nullable Date get(@Nullable Resource resource) { if (resource == null) { return null; } ValueMap resourceProperties = resource.getValueMap(); // get the cq:lastModified property from the resource (used in jcr:content nodes of cq pages) Date cqModified = resourceProperties != null ? resourceProperties.get(NameConstants.PN_PAGE_LAST_MOD, Date.class) : null; // try to find a jcr:lastModified property that is used for binary uploads or cq paragraphs Date resourceModified = getResourceMetadataModificationTime(resource); // get the most recent date of both return mostRecent(cqModified, resourceModified); }
[ "@", "SuppressWarnings", "(", "\"null\"", ")", "public", "static", "@", "Nullable", "Date", "get", "(", "@", "Nullable", "Resource", "resource", ")", "{", "if", "(", "resource", "==", "null", ")", "{", "return", "null", ";", "}", "ValueMap", "resourceProperties", "=", "resource", ".", "getValueMap", "(", ")", ";", "// get the cq:lastModified property from the resource (used in jcr:content nodes of cq pages)", "Date", "cqModified", "=", "resourceProperties", "!=", "null", "?", "resourceProperties", ".", "get", "(", "NameConstants", ".", "PN_PAGE_LAST_MOD", ",", "Date", ".", "class", ")", ":", "null", ";", "// try to find a jcr:lastModified property that is used for binary uploads or cq paragraphs", "Date", "resourceModified", "=", "getResourceMetadataModificationTime", "(", "resource", ")", ";", "// get the most recent date of both", "return", "mostRecent", "(", "cqModified", ",", "resourceModified", ")", ";", "}" ]
Looks for either jcr:lastModified or cq:lastModified property in the given resource, which can be either the jcr:content-ode of a cq-page, or a rendition node @param resource a resource with a cq:lastModified property *and/or* a file/jcr:content subnode with a jcr:lastModified property @return the date or null if last modified property could not be found
[ "Looks", "for", "either", "jcr", ":", "lastModified", "or", "cq", ":", "lastModified", "property", "in", "the", "given", "resource", "which", "can", "be", "either", "the", "jcr", ":", "content", "-", "ode", "of", "a", "cq", "-", "page", "or", "a", "rendition", "node" ]
train
https://github.com/wcm-io/wcm-io-wcm/blob/8eff9434f2f4b6462fdb718f8769ad793c55b8d7/commons/src/main/java/io/wcm/wcm/commons/caching/ModificationDate.java#L69-L84
sarl/sarl
sre/io.janusproject/io.janusproject.plugin/src/io/janusproject/kernel/bic/InternalEventBusSkill.java
InternalEventBusSkill.runDestructionStage
private void runDestructionStage(Event event) { """ This function runs the destruction of the agent. @param event the {@link Destroy} occurrence. """ // Immediate synchronous dispatching of Destroy event try { setOwnerState(OwnerState.DYING); try { this.eventDispatcher.immediateDispatch(event); } finally { setOwnerState(OwnerState.DEAD); } } catch (Exception e) { // Log the exception final Logging loggingCapacity = getLoggingSkill(); if (loggingCapacity != null) { loggingCapacity.error(Messages.InternalEventBusSkill_4, e); } else { final LogRecord record = new LogRecord(Level.SEVERE, Messages.InternalEventBusSkill_4); this.logger.getKernelLogger().log( this.logger.prepareLogRecord(record, this.logger.getKernelLogger().getName(), Throwables.getRootCause(e))); } } }
java
private void runDestructionStage(Event event) { // Immediate synchronous dispatching of Destroy event try { setOwnerState(OwnerState.DYING); try { this.eventDispatcher.immediateDispatch(event); } finally { setOwnerState(OwnerState.DEAD); } } catch (Exception e) { // Log the exception final Logging loggingCapacity = getLoggingSkill(); if (loggingCapacity != null) { loggingCapacity.error(Messages.InternalEventBusSkill_4, e); } else { final LogRecord record = new LogRecord(Level.SEVERE, Messages.InternalEventBusSkill_4); this.logger.getKernelLogger().log( this.logger.prepareLogRecord(record, this.logger.getKernelLogger().getName(), Throwables.getRootCause(e))); } } }
[ "private", "void", "runDestructionStage", "(", "Event", "event", ")", "{", "// Immediate synchronous dispatching of Destroy event", "try", "{", "setOwnerState", "(", "OwnerState", ".", "DYING", ")", ";", "try", "{", "this", ".", "eventDispatcher", ".", "immediateDispatch", "(", "event", ")", ";", "}", "finally", "{", "setOwnerState", "(", "OwnerState", ".", "DEAD", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "// Log the exception", "final", "Logging", "loggingCapacity", "=", "getLoggingSkill", "(", ")", ";", "if", "(", "loggingCapacity", "!=", "null", ")", "{", "loggingCapacity", ".", "error", "(", "Messages", ".", "InternalEventBusSkill_4", ",", "e", ")", ";", "}", "else", "{", "final", "LogRecord", "record", "=", "new", "LogRecord", "(", "Level", ".", "SEVERE", ",", "Messages", ".", "InternalEventBusSkill_4", ")", ";", "this", ".", "logger", ".", "getKernelLogger", "(", ")", ".", "log", "(", "this", ".", "logger", ".", "prepareLogRecord", "(", "record", ",", "this", ".", "logger", ".", "getKernelLogger", "(", ")", ".", "getName", "(", ")", ",", "Throwables", ".", "getRootCause", "(", "e", ")", ")", ")", ";", "}", "}", "}" ]
This function runs the destruction of the agent. @param event the {@link Destroy} occurrence.
[ "This", "function", "runs", "the", "destruction", "of", "the", "agent", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/sre/io.janusproject/io.janusproject.plugin/src/io/janusproject/kernel/bic/InternalEventBusSkill.java#L272-L293
dlemmermann/CalendarFX
CalendarFXRecurrence/src/main/java/com/google/ical/values/PeriodValueImpl.java
PeriodValueImpl.createFromDuration
public static PeriodValue createFromDuration(DateValue start, DateValue dur) { """ returns a period with the given start date and duration. @param start non null. @param dur a positive duration represented as a DateValue. """ DateValue end = TimeUtils.add(start, dur); if (end instanceof TimeValue && !(start instanceof TimeValue)) { start = TimeUtils.dayStart(start); } return new PeriodValueImpl(start, end); }
java
public static PeriodValue createFromDuration(DateValue start, DateValue dur) { DateValue end = TimeUtils.add(start, dur); if (end instanceof TimeValue && !(start instanceof TimeValue)) { start = TimeUtils.dayStart(start); } return new PeriodValueImpl(start, end); }
[ "public", "static", "PeriodValue", "createFromDuration", "(", "DateValue", "start", ",", "DateValue", "dur", ")", "{", "DateValue", "end", "=", "TimeUtils", ".", "add", "(", "start", ",", "dur", ")", ";", "if", "(", "end", "instanceof", "TimeValue", "&&", "!", "(", "start", "instanceof", "TimeValue", ")", ")", "{", "start", "=", "TimeUtils", ".", "dayStart", "(", "start", ")", ";", "}", "return", "new", "PeriodValueImpl", "(", "start", ",", "end", ")", ";", "}" ]
returns a period with the given start date and duration. @param start non null. @param dur a positive duration represented as a DateValue.
[ "returns", "a", "period", "with", "the", "given", "start", "date", "and", "duration", "." ]
train
https://github.com/dlemmermann/CalendarFX/blob/f2b91c2622c3f29d004485b6426b23b86c331f96/CalendarFXRecurrence/src/main/java/com/google/ical/values/PeriodValueImpl.java#L49-L55
khuxtable/seaglass
src/main/java/com/seaglasslookandfeel/painter/TitlePaneCloseButtonPainter.java
TitlePaneCloseButtonPainter.decodeMarkBorder
private Shape decodeMarkBorder(int width, int height) { """ Create the shape for the mark border. @param width the width. @param height the height. @return the shape of the mark border. """ int left = (width - 3) / 2 - 5; int top = (height - 2) / 2 - 5; path.reset(); path.moveTo(left + 1, top + 0); path.lineTo(left + 3, top + 0); path.pointAt(left + 4, top + 1); path.pointAt(left + 5, top + 2); path.pointAt(left + 6, top + 1); path.moveTo(left + 7, top + 0); path.lineTo(left + 9, top + 0); path.pointAt(left + 10, top + 1); path.pointAt(left + 9, top + 2); path.pointAt(left + 8, top + 3); path.moveTo(left + 7, top + 4); path.lineTo(left + 7, top + 5); path.pointAt(left + 8, top + 6); path.pointAt(left + 9, top + 7); path.pointAt(left + 10, top + 8); path.moveTo(left + 9, top + 9); path.lineTo(left + 7, top + 9); path.pointAt(left + 6, top + 8); path.pointAt(left + 5, top + 7); path.pointAt(left + 4, top + 8); path.moveTo(left + 3, top + 9); path.lineTo(left + 1, top + 9); path.pointAt(left + 0, top + 8); path.pointAt(left + 1, top + 7); path.pointAt(left + 2, top + 6); path.moveTo(left + 3, top + 5); path.lineTo(left + 3, top + 4); path.pointAt(left + 2, top + 3); path.pointAt(left + 1, top + 2); path.pointAt(left + 0, top + 1); return path; }
java
private Shape decodeMarkBorder(int width, int height) { int left = (width - 3) / 2 - 5; int top = (height - 2) / 2 - 5; path.reset(); path.moveTo(left + 1, top + 0); path.lineTo(left + 3, top + 0); path.pointAt(left + 4, top + 1); path.pointAt(left + 5, top + 2); path.pointAt(left + 6, top + 1); path.moveTo(left + 7, top + 0); path.lineTo(left + 9, top + 0); path.pointAt(left + 10, top + 1); path.pointAt(left + 9, top + 2); path.pointAt(left + 8, top + 3); path.moveTo(left + 7, top + 4); path.lineTo(left + 7, top + 5); path.pointAt(left + 8, top + 6); path.pointAt(left + 9, top + 7); path.pointAt(left + 10, top + 8); path.moveTo(left + 9, top + 9); path.lineTo(left + 7, top + 9); path.pointAt(left + 6, top + 8); path.pointAt(left + 5, top + 7); path.pointAt(left + 4, top + 8); path.moveTo(left + 3, top + 9); path.lineTo(left + 1, top + 9); path.pointAt(left + 0, top + 8); path.pointAt(left + 1, top + 7); path.pointAt(left + 2, top + 6); path.moveTo(left + 3, top + 5); path.lineTo(left + 3, top + 4); path.pointAt(left + 2, top + 3); path.pointAt(left + 1, top + 2); path.pointAt(left + 0, top + 1); return path; }
[ "private", "Shape", "decodeMarkBorder", "(", "int", "width", ",", "int", "height", ")", "{", "int", "left", "=", "(", "width", "-", "3", ")", "/", "2", "-", "5", ";", "int", "top", "=", "(", "height", "-", "2", ")", "/", "2", "-", "5", ";", "path", ".", "reset", "(", ")", ";", "path", ".", "moveTo", "(", "left", "+", "1", ",", "top", "+", "0", ")", ";", "path", ".", "lineTo", "(", "left", "+", "3", ",", "top", "+", "0", ")", ";", "path", ".", "pointAt", "(", "left", "+", "4", ",", "top", "+", "1", ")", ";", "path", ".", "pointAt", "(", "left", "+", "5", ",", "top", "+", "2", ")", ";", "path", ".", "pointAt", "(", "left", "+", "6", ",", "top", "+", "1", ")", ";", "path", ".", "moveTo", "(", "left", "+", "7", ",", "top", "+", "0", ")", ";", "path", ".", "lineTo", "(", "left", "+", "9", ",", "top", "+", "0", ")", ";", "path", ".", "pointAt", "(", "left", "+", "10", ",", "top", "+", "1", ")", ";", "path", ".", "pointAt", "(", "left", "+", "9", ",", "top", "+", "2", ")", ";", "path", ".", "pointAt", "(", "left", "+", "8", ",", "top", "+", "3", ")", ";", "path", ".", "moveTo", "(", "left", "+", "7", ",", "top", "+", "4", ")", ";", "path", ".", "lineTo", "(", "left", "+", "7", ",", "top", "+", "5", ")", ";", "path", ".", "pointAt", "(", "left", "+", "8", ",", "top", "+", "6", ")", ";", "path", ".", "pointAt", "(", "left", "+", "9", ",", "top", "+", "7", ")", ";", "path", ".", "pointAt", "(", "left", "+", "10", ",", "top", "+", "8", ")", ";", "path", ".", "moveTo", "(", "left", "+", "9", ",", "top", "+", "9", ")", ";", "path", ".", "lineTo", "(", "left", "+", "7", ",", "top", "+", "9", ")", ";", "path", ".", "pointAt", "(", "left", "+", "6", ",", "top", "+", "8", ")", ";", "path", ".", "pointAt", "(", "left", "+", "5", ",", "top", "+", "7", ")", ";", "path", ".", "pointAt", "(", "left", "+", "4", ",", "top", "+", "8", ")", ";", "path", ".", "moveTo", "(", "left", "+", "3", ",", "top", "+", "9", ")", ";", "path", ".", "lineTo", "(", "left", "+", "1", ",", "top", "+", "9", ")", ";", "path", ".", "pointAt", "(", "left", "+", "0", ",", "top", "+", "8", ")", ";", "path", ".", "pointAt", "(", "left", "+", "1", ",", "top", "+", "7", ")", ";", "path", ".", "pointAt", "(", "left", "+", "2", ",", "top", "+", "6", ")", ";", "path", ".", "moveTo", "(", "left", "+", "3", ",", "top", "+", "5", ")", ";", "path", ".", "lineTo", "(", "left", "+", "3", ",", "top", "+", "4", ")", ";", "path", ".", "pointAt", "(", "left", "+", "2", ",", "top", "+", "3", ")", ";", "path", ".", "pointAt", "(", "left", "+", "1", ",", "top", "+", "2", ")", ";", "path", ".", "pointAt", "(", "left", "+", "0", ",", "top", "+", "1", ")", ";", "return", "path", ";", "}" ]
Create the shape for the mark border. @param width the width. @param height the height. @return the shape of the mark border.
[ "Create", "the", "shape", "for", "the", "mark", "border", "." ]
train
https://github.com/khuxtable/seaglass/blob/f25ecba622923d7b29b64cb7d6068dd8005989b3/src/main/java/com/seaglasslookandfeel/painter/TitlePaneCloseButtonPainter.java#L258-L295
Carbonado/Carbonado
src/main/java/com/amazon/carbonado/repo/jdbc/WhereBuilder.java
WhereBuilder.appendExists
public void appendExists(Filter<S> filter) throws FetchException { """ Generate SQL of the form "WHERE EXISTS (SELECT * FROM ...)" This is necessary for DELETE statements which operate against joined tables. """ mStatementBuilder.append(" WHERE "); mStatementBuilder.append("EXISTS (SELECT * FROM"); JDBCStorableInfo<S> info; final JDBCRepository repo = mStatementBuilder.getRepository(); try { info = repo.examineStorable(filter.getStorableType()); } catch (RepositoryException e) { throw repo.toFetchException(e); } JoinNode jn; try { JoinNodeBuilder jnb = new JoinNodeBuilder(repo, info, mAliasGenerator); filter.accept(jnb, null); jn = jnb.getRootJoinNode(); } catch (UndeclaredThrowableException e) { throw repo.toFetchException(e); } jn.appendFullJoinTo(mStatementBuilder); mStatementBuilder.append(" WHERE "); { int i = 0; for (JDBCStorableProperty<S> property : info.getPrimaryKeyProperties().values()) { if (i > 0) { mStatementBuilder.append(" AND "); } mStatementBuilder.append(mJoinNode.getAlias()); mStatementBuilder.append('.'); mStatementBuilder.append(property.getColumnName()); mStatementBuilder.append('='); mStatementBuilder.append(jn.getAlias()); mStatementBuilder.append('.'); mStatementBuilder.append(property.getColumnName()); i++; } } mStatementBuilder.append(" AND ("); WhereBuilder<S> wb = new WhereBuilder<S>(mStatementBuilder, jn, mAliasGenerator); FetchException e = filter.accept(wb, null); if (e != null) { throw e; } // Transfer property filters so that the values are extracted properly. mPropertyFilters.addAll(wb.mPropertyFilters); mPropertyFilterNullable.addAll(wb.mPropertyFilterNullable); mStatementBuilder.append(')'); mStatementBuilder.append(')'); }
java
public void appendExists(Filter<S> filter) throws FetchException { mStatementBuilder.append(" WHERE "); mStatementBuilder.append("EXISTS (SELECT * FROM"); JDBCStorableInfo<S> info; final JDBCRepository repo = mStatementBuilder.getRepository(); try { info = repo.examineStorable(filter.getStorableType()); } catch (RepositoryException e) { throw repo.toFetchException(e); } JoinNode jn; try { JoinNodeBuilder jnb = new JoinNodeBuilder(repo, info, mAliasGenerator); filter.accept(jnb, null); jn = jnb.getRootJoinNode(); } catch (UndeclaredThrowableException e) { throw repo.toFetchException(e); } jn.appendFullJoinTo(mStatementBuilder); mStatementBuilder.append(" WHERE "); { int i = 0; for (JDBCStorableProperty<S> property : info.getPrimaryKeyProperties().values()) { if (i > 0) { mStatementBuilder.append(" AND "); } mStatementBuilder.append(mJoinNode.getAlias()); mStatementBuilder.append('.'); mStatementBuilder.append(property.getColumnName()); mStatementBuilder.append('='); mStatementBuilder.append(jn.getAlias()); mStatementBuilder.append('.'); mStatementBuilder.append(property.getColumnName()); i++; } } mStatementBuilder.append(" AND ("); WhereBuilder<S> wb = new WhereBuilder<S>(mStatementBuilder, jn, mAliasGenerator); FetchException e = filter.accept(wb, null); if (e != null) { throw e; } // Transfer property filters so that the values are extracted properly. mPropertyFilters.addAll(wb.mPropertyFilters); mPropertyFilterNullable.addAll(wb.mPropertyFilterNullable); mStatementBuilder.append(')'); mStatementBuilder.append(')'); }
[ "public", "void", "appendExists", "(", "Filter", "<", "S", ">", "filter", ")", "throws", "FetchException", "{", "mStatementBuilder", ".", "append", "(", "\" WHERE \"", ")", ";", "mStatementBuilder", ".", "append", "(", "\"EXISTS (SELECT * FROM\"", ")", ";", "JDBCStorableInfo", "<", "S", ">", "info", ";", "final", "JDBCRepository", "repo", "=", "mStatementBuilder", ".", "getRepository", "(", ")", ";", "try", "{", "info", "=", "repo", ".", "examineStorable", "(", "filter", ".", "getStorableType", "(", ")", ")", ";", "}", "catch", "(", "RepositoryException", "e", ")", "{", "throw", "repo", ".", "toFetchException", "(", "e", ")", ";", "}", "JoinNode", "jn", ";", "try", "{", "JoinNodeBuilder", "jnb", "=", "new", "JoinNodeBuilder", "(", "repo", ",", "info", ",", "mAliasGenerator", ")", ";", "filter", ".", "accept", "(", "jnb", ",", "null", ")", ";", "jn", "=", "jnb", ".", "getRootJoinNode", "(", ")", ";", "}", "catch", "(", "UndeclaredThrowableException", "e", ")", "{", "throw", "repo", ".", "toFetchException", "(", "e", ")", ";", "}", "jn", ".", "appendFullJoinTo", "(", "mStatementBuilder", ")", ";", "mStatementBuilder", ".", "append", "(", "\" WHERE \"", ")", ";", "{", "int", "i", "=", "0", ";", "for", "(", "JDBCStorableProperty", "<", "S", ">", "property", ":", "info", ".", "getPrimaryKeyProperties", "(", ")", ".", "values", "(", ")", ")", "{", "if", "(", "i", ">", "0", ")", "{", "mStatementBuilder", ".", "append", "(", "\" AND \"", ")", ";", "}", "mStatementBuilder", ".", "append", "(", "mJoinNode", ".", "getAlias", "(", ")", ")", ";", "mStatementBuilder", ".", "append", "(", "'", "'", ")", ";", "mStatementBuilder", ".", "append", "(", "property", ".", "getColumnName", "(", ")", ")", ";", "mStatementBuilder", ".", "append", "(", "'", "'", ")", ";", "mStatementBuilder", ".", "append", "(", "jn", ".", "getAlias", "(", ")", ")", ";", "mStatementBuilder", ".", "append", "(", "'", "'", ")", ";", "mStatementBuilder", ".", "append", "(", "property", ".", "getColumnName", "(", ")", ")", ";", "i", "++", ";", "}", "}", "mStatementBuilder", ".", "append", "(", "\" AND (\"", ")", ";", "WhereBuilder", "<", "S", ">", "wb", "=", "new", "WhereBuilder", "<", "S", ">", "(", "mStatementBuilder", ",", "jn", ",", "mAliasGenerator", ")", ";", "FetchException", "e", "=", "filter", ".", "accept", "(", "wb", ",", "null", ")", ";", "if", "(", "e", "!=", "null", ")", "{", "throw", "e", ";", "}", "// Transfer property filters so that the values are extracted properly.\r", "mPropertyFilters", ".", "addAll", "(", "wb", ".", "mPropertyFilters", ")", ";", "mPropertyFilterNullable", ".", "addAll", "(", "wb", ".", "mPropertyFilterNullable", ")", ";", "mStatementBuilder", ".", "append", "(", "'", "'", ")", ";", "mStatementBuilder", ".", "append", "(", "'", "'", ")", ";", "}" ]
Generate SQL of the form "WHERE EXISTS (SELECT * FROM ...)" This is necessary for DELETE statements which operate against joined tables.
[ "Generate", "SQL", "of", "the", "form", "WHERE", "EXISTS", "(", "SELECT", "*", "FROM", "...", ")", "This", "is", "necessary", "for", "DELETE", "statements", "which", "operate", "against", "joined", "tables", "." ]
train
https://github.com/Carbonado/Carbonado/blob/eee29b365a61c8f03e1a1dc6bed0692e6b04b1db/src/main/java/com/amazon/carbonado/repo/jdbc/WhereBuilder.java#L82-L141
Azure/azure-sdk-for-java
batch/data-plane/src/main/java/com/microsoft/azure/batch/ComputeNodeOperations.java
ComputeNodeOperations.updateComputeNodeUser
public void updateComputeNodeUser(String poolId, String nodeId, String userName, String password, DateTime expiryTime, Iterable<BatchClientBehavior> additionalBehaviors) throws BatchErrorException, IOException { """ Updates the specified user account on the specified compute node. @param poolId The ID of the pool that contains the compute node. @param nodeId The ID of the compute node where the user account will be updated. @param userName The name of the user account to update. @param password The password of the account. If null, the password is removed. @param expiryTime The time at which the account should expire. If null, the expiry time is replaced with its default value. @param additionalBehaviors A collection of {@link BatchClientBehavior} instances that are applied to the Batch service request. @throws BatchErrorException Exception thrown when an error response is received from the Batch service. @throws IOException Exception thrown when there is an error in serialization/deserialization of data sent to/received from the Batch service. """ NodeUpdateUserParameter param = new NodeUpdateUserParameter(); param.withPassword(password); param.withExpiryTime(expiryTime); updateComputeNodeUser(poolId, nodeId, userName, param, additionalBehaviors); }
java
public void updateComputeNodeUser(String poolId, String nodeId, String userName, String password, DateTime expiryTime, Iterable<BatchClientBehavior> additionalBehaviors) throws BatchErrorException, IOException { NodeUpdateUserParameter param = new NodeUpdateUserParameter(); param.withPassword(password); param.withExpiryTime(expiryTime); updateComputeNodeUser(poolId, nodeId, userName, param, additionalBehaviors); }
[ "public", "void", "updateComputeNodeUser", "(", "String", "poolId", ",", "String", "nodeId", ",", "String", "userName", ",", "String", "password", ",", "DateTime", "expiryTime", ",", "Iterable", "<", "BatchClientBehavior", ">", "additionalBehaviors", ")", "throws", "BatchErrorException", ",", "IOException", "{", "NodeUpdateUserParameter", "param", "=", "new", "NodeUpdateUserParameter", "(", ")", ";", "param", ".", "withPassword", "(", "password", ")", ";", "param", ".", "withExpiryTime", "(", "expiryTime", ")", ";", "updateComputeNodeUser", "(", "poolId", ",", "nodeId", ",", "userName", ",", "param", ",", "additionalBehaviors", ")", ";", "}" ]
Updates the specified user account on the specified compute node. @param poolId The ID of the pool that contains the compute node. @param nodeId The ID of the compute node where the user account will be updated. @param userName The name of the user account to update. @param password The password of the account. If null, the password is removed. @param expiryTime The time at which the account should expire. If null, the expiry time is replaced with its default value. @param additionalBehaviors A collection of {@link BatchClientBehavior} instances that are applied to the Batch service request. @throws BatchErrorException Exception thrown when an error response is received from the Batch service. @throws IOException Exception thrown when there is an error in serialization/deserialization of data sent to/received from the Batch service.
[ "Updates", "the", "specified", "user", "account", "on", "the", "specified", "compute", "node", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/ComputeNodeOperations.java#L162-L168
EdwardRaff/JSAT
JSAT/src/jsat/distributions/kernels/PukKernel.java
PukKernel.setOmega
public void setOmega(double omega) { """ Sets the omega parameter value, which controls the shape of the kernel @param omega the positive parameter value """ if(omega <= 0 || Double.isNaN(omega) || Double.isInfinite(omega)) throw new ArithmeticException("omega must be positive, not " + omega); this.omega = omega; this.cnst = Math.sqrt(Math.pow(2, 1/omega)-1); }
java
public void setOmega(double omega) { if(omega <= 0 || Double.isNaN(omega) || Double.isInfinite(omega)) throw new ArithmeticException("omega must be positive, not " + omega); this.omega = omega; this.cnst = Math.sqrt(Math.pow(2, 1/omega)-1); }
[ "public", "void", "setOmega", "(", "double", "omega", ")", "{", "if", "(", "omega", "<=", "0", "||", "Double", ".", "isNaN", "(", "omega", ")", "||", "Double", ".", "isInfinite", "(", "omega", ")", ")", "throw", "new", "ArithmeticException", "(", "\"omega must be positive, not \"", "+", "omega", ")", ";", "this", ".", "omega", "=", "omega", ";", "this", ".", "cnst", "=", "Math", ".", "sqrt", "(", "Math", ".", "pow", "(", "2", ",", "1", "/", "omega", ")", "-", "1", ")", ";", "}" ]
Sets the omega parameter value, which controls the shape of the kernel @param omega the positive parameter value
[ "Sets", "the", "omega", "parameter", "value", "which", "controls", "the", "shape", "of", "the", "kernel" ]
train
https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/distributions/kernels/PukKernel.java#L47-L53
liferay/com-liferay-commerce
commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceOrderPersistenceImpl.java
CommerceOrderPersistenceImpl.findByUserId
@Override public List<CommerceOrder> findByUserId(long userId) { """ Returns all the commerce orders where userId = &#63;. @param userId the user ID @return the matching commerce orders """ return findByUserId(userId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null); }
java
@Override public List<CommerceOrder> findByUserId(long userId) { return findByUserId(userId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null); }
[ "@", "Override", "public", "List", "<", "CommerceOrder", ">", "findByUserId", "(", "long", "userId", ")", "{", "return", "findByUserId", "(", "userId", ",", "QueryUtil", ".", "ALL_POS", ",", "QueryUtil", ".", "ALL_POS", ",", "null", ")", ";", "}" ]
Returns all the commerce orders where userId = &#63;. @param userId the user ID @return the matching commerce orders
[ "Returns", "all", "the", "commerce", "orders", "where", "userId", "=", "&#63", ";", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceOrderPersistenceImpl.java#L2015-L2018
cdk/cdk
base/valencycheck/src/main/java/org/openscience/cdk/tools/SaturationChecker.java
SaturationChecker.isSaturated
@Override public boolean isSaturated(IAtom atom, IAtomContainer ac) throws CDKException { """ Checks whether an Atom is saturated by comparing it with known AtomTypes. """ IAtomType[] atomTypes = getAtomTypeFactory(atom.getBuilder()).getAtomTypes(atom.getSymbol()); if (atomTypes.length == 0) return true; double bondOrderSum = ac.getBondOrderSum(atom); IBond.Order maxBondOrder = ac.getMaximumBondOrder(atom); Integer hcount = atom.getImplicitHydrogenCount() == CDKConstants.UNSET ? 0 : atom.getImplicitHydrogenCount(); Integer charge = atom.getFormalCharge() == CDKConstants.UNSET ? 0 : atom.getFormalCharge(); try { logger.debug("*** Checking saturation of atom ", atom.getSymbol(), "" + ac.indexOf(atom) + " ***"); logger.debug("bondOrderSum: " + bondOrderSum); logger.debug("maxBondOrder: " + maxBondOrder); logger.debug("hcount: " + hcount); } catch (Exception exc) { logger.debug(exc); } for (int f = 0; f < atomTypes.length; f++) { if (bondOrderSum - charge + hcount == atomTypes[f].getBondOrderSum() && !BondManipulator.isHigherOrder(maxBondOrder, atomTypes[f].getMaxBondOrder())) { logger.debug("*** Good ! ***"); return true; } } logger.debug("*** Bad ! ***"); return false; }
java
@Override public boolean isSaturated(IAtom atom, IAtomContainer ac) throws CDKException { IAtomType[] atomTypes = getAtomTypeFactory(atom.getBuilder()).getAtomTypes(atom.getSymbol()); if (atomTypes.length == 0) return true; double bondOrderSum = ac.getBondOrderSum(atom); IBond.Order maxBondOrder = ac.getMaximumBondOrder(atom); Integer hcount = atom.getImplicitHydrogenCount() == CDKConstants.UNSET ? 0 : atom.getImplicitHydrogenCount(); Integer charge = atom.getFormalCharge() == CDKConstants.UNSET ? 0 : atom.getFormalCharge(); try { logger.debug("*** Checking saturation of atom ", atom.getSymbol(), "" + ac.indexOf(atom) + " ***"); logger.debug("bondOrderSum: " + bondOrderSum); logger.debug("maxBondOrder: " + maxBondOrder); logger.debug("hcount: " + hcount); } catch (Exception exc) { logger.debug(exc); } for (int f = 0; f < atomTypes.length; f++) { if (bondOrderSum - charge + hcount == atomTypes[f].getBondOrderSum() && !BondManipulator.isHigherOrder(maxBondOrder, atomTypes[f].getMaxBondOrder())) { logger.debug("*** Good ! ***"); return true; } } logger.debug("*** Bad ! ***"); return false; }
[ "@", "Override", "public", "boolean", "isSaturated", "(", "IAtom", "atom", ",", "IAtomContainer", "ac", ")", "throws", "CDKException", "{", "IAtomType", "[", "]", "atomTypes", "=", "getAtomTypeFactory", "(", "atom", ".", "getBuilder", "(", ")", ")", ".", "getAtomTypes", "(", "atom", ".", "getSymbol", "(", ")", ")", ";", "if", "(", "atomTypes", ".", "length", "==", "0", ")", "return", "true", ";", "double", "bondOrderSum", "=", "ac", ".", "getBondOrderSum", "(", "atom", ")", ";", "IBond", ".", "Order", "maxBondOrder", "=", "ac", ".", "getMaximumBondOrder", "(", "atom", ")", ";", "Integer", "hcount", "=", "atom", ".", "getImplicitHydrogenCount", "(", ")", "==", "CDKConstants", ".", "UNSET", "?", "0", ":", "atom", ".", "getImplicitHydrogenCount", "(", ")", ";", "Integer", "charge", "=", "atom", ".", "getFormalCharge", "(", ")", "==", "CDKConstants", ".", "UNSET", "?", "0", ":", "atom", ".", "getFormalCharge", "(", ")", ";", "try", "{", "logger", ".", "debug", "(", "\"*** Checking saturation of atom \"", ",", "atom", ".", "getSymbol", "(", ")", ",", "\"\"", "+", "ac", ".", "indexOf", "(", "atom", ")", "+", "\" ***\"", ")", ";", "logger", ".", "debug", "(", "\"bondOrderSum: \"", "+", "bondOrderSum", ")", ";", "logger", ".", "debug", "(", "\"maxBondOrder: \"", "+", "maxBondOrder", ")", ";", "logger", ".", "debug", "(", "\"hcount: \"", "+", "hcount", ")", ";", "}", "catch", "(", "Exception", "exc", ")", "{", "logger", ".", "debug", "(", "exc", ")", ";", "}", "for", "(", "int", "f", "=", "0", ";", "f", "<", "atomTypes", ".", "length", ";", "f", "++", ")", "{", "if", "(", "bondOrderSum", "-", "charge", "+", "hcount", "==", "atomTypes", "[", "f", "]", ".", "getBondOrderSum", "(", ")", "&&", "!", "BondManipulator", ".", "isHigherOrder", "(", "maxBondOrder", ",", "atomTypes", "[", "f", "]", ".", "getMaxBondOrder", "(", ")", ")", ")", "{", "logger", ".", "debug", "(", "\"*** Good ! ***\"", ")", ";", "return", "true", ";", "}", "}", "logger", ".", "debug", "(", "\"*** Bad ! ***\"", ")", ";", "return", "false", ";", "}" ]
Checks whether an Atom is saturated by comparing it with known AtomTypes.
[ "Checks", "whether", "an", "Atom", "is", "saturated", "by", "comparing", "it", "with", "known", "AtomTypes", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/base/valencycheck/src/main/java/org/openscience/cdk/tools/SaturationChecker.java#L161-L186
paymill/paymill-java
src/main/java/com/paymill/services/TransactionService.java
TransactionService.createWithPaymentAndClient
public Transaction createWithPaymentAndClient( String paymentId, String clientId, Integer amount, String currency, String description ) { """ Executes a {@link Transaction} with {@link Payment} for the given amount in the given currency. @param paymentId The Id of a PAYMILL {@link Payment} representing credit card or direct debit. @param clientId The Id of a PAYMILL {@link Client} which have to be charged. @param amount Amount (in cents) which will be charged. @param currency ISO 4217 formatted currency code. @param description A short description for the transaction. @return {@link Transaction} object indicating whether a the call was successful or not. """ return this.createWithPaymentAndClient( new Payment( paymentId ), new Client( clientId ), amount, currency, description ); }
java
public Transaction createWithPaymentAndClient( String paymentId, String clientId, Integer amount, String currency, String description ) { return this.createWithPaymentAndClient( new Payment( paymentId ), new Client( clientId ), amount, currency, description ); }
[ "public", "Transaction", "createWithPaymentAndClient", "(", "String", "paymentId", ",", "String", "clientId", ",", "Integer", "amount", ",", "String", "currency", ",", "String", "description", ")", "{", "return", "this", ".", "createWithPaymentAndClient", "(", "new", "Payment", "(", "paymentId", ")", ",", "new", "Client", "(", "clientId", ")", ",", "amount", ",", "currency", ",", "description", ")", ";", "}" ]
Executes a {@link Transaction} with {@link Payment} for the given amount in the given currency. @param paymentId The Id of a PAYMILL {@link Payment} representing credit card or direct debit. @param clientId The Id of a PAYMILL {@link Client} which have to be charged. @param amount Amount (in cents) which will be charged. @param currency ISO 4217 formatted currency code. @param description A short description for the transaction. @return {@link Transaction} object indicating whether a the call was successful or not.
[ "Executes", "a", "{" ]
train
https://github.com/paymill/paymill-java/blob/17281a0d4376c76f1711af9f09bfc138c90ba65a/src/main/java/com/paymill/services/TransactionService.java#L325-L327
aws/aws-sdk-java
aws-java-sdk-sqs/src/main/java/com/amazonaws/services/sqs/model/Message.java
Message.getMessageAttributes
public java.util.Map<String, MessageAttributeValue> getMessageAttributes() { """ <p> Each message attribute consists of a <code>Name</code>, <code>Type</code>, and <code>Value</code>. For more information, see <a href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-message-attributes.html" >Amazon SQS Message Attributes</a> in the <i>Amazon Simple Queue Service Developer Guide</i>. </p> @return Each message attribute consists of a <code>Name</code>, <code>Type</code>, and <code>Value</code>. For more information, see <a href= "http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-message-attributes.html" >Amazon SQS Message Attributes</a> in the <i>Amazon Simple Queue Service Developer Guide</i>. """ if (messageAttributes == null) { messageAttributes = new com.amazonaws.internal.SdkInternalMap<String, MessageAttributeValue>(); } return messageAttributes; }
java
public java.util.Map<String, MessageAttributeValue> getMessageAttributes() { if (messageAttributes == null) { messageAttributes = new com.amazonaws.internal.SdkInternalMap<String, MessageAttributeValue>(); } return messageAttributes; }
[ "public", "java", ".", "util", ".", "Map", "<", "String", ",", "MessageAttributeValue", ">", "getMessageAttributes", "(", ")", "{", "if", "(", "messageAttributes", "==", "null", ")", "{", "messageAttributes", "=", "new", "com", ".", "amazonaws", ".", "internal", ".", "SdkInternalMap", "<", "String", ",", "MessageAttributeValue", ">", "(", ")", ";", "}", "return", "messageAttributes", ";", "}" ]
<p> Each message attribute consists of a <code>Name</code>, <code>Type</code>, and <code>Value</code>. For more information, see <a href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-message-attributes.html" >Amazon SQS Message Attributes</a> in the <i>Amazon Simple Queue Service Developer Guide</i>. </p> @return Each message attribute consists of a <code>Name</code>, <code>Type</code>, and <code>Value</code>. For more information, see <a href= "http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-message-attributes.html" >Amazon SQS Message Attributes</a> in the <i>Amazon Simple Queue Service Developer Guide</i>.
[ "<p", ">", "Each", "message", "attribute", "consists", "of", "a", "<code", ">", "Name<", "/", "code", ">", "<code", ">", "Type<", "/", "code", ">", "and", "<code", ">", "Value<", "/", "code", ">", ".", "For", "more", "information", "see", "<a", "href", "=", "http", ":", "//", "docs", ".", "aws", ".", "amazon", ".", "com", "/", "AWSSimpleQueueService", "/", "latest", "/", "SQSDeveloperGuide", "/", "sqs", "-", "message", "-", "attributes", ".", "html", ">", "Amazon", "SQS", "Message", "Attributes<", "/", "a", ">", "in", "the", "<i", ">", "Amazon", "Simple", "Queue", "Service", "Developer", "Guide<", "/", "i", ">", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-sqs/src/main/java/com/amazonaws/services/sqs/model/Message.java#L674-L679
loldevs/riotapi
rest/src/main/java/net/boreeas/riotapi/rest/ThrottledApiHandler.java
ThrottledApiHandler.getSummonerNames
public Future<Map<Integer, String>> getSummonerNames(Integer... ids) { """ Retrieve summoner names for the specified ids @param ids The ids to lookup @return A map, mapping user ids to summoner names @see <a href=https://developer.riotgames.com/api/methods#!/620/1934>Official API documentation</a> """ return new ApiFuture<>(() -> handler.getSummonerNames(ids)); }
java
public Future<Map<Integer, String>> getSummonerNames(Integer... ids) { return new ApiFuture<>(() -> handler.getSummonerNames(ids)); }
[ "public", "Future", "<", "Map", "<", "Integer", ",", "String", ">", ">", "getSummonerNames", "(", "Integer", "...", "ids", ")", "{", "return", "new", "ApiFuture", "<>", "(", "(", ")", "->", "handler", ".", "getSummonerNames", "(", "ids", ")", ")", ";", "}" ]
Retrieve summoner names for the specified ids @param ids The ids to lookup @return A map, mapping user ids to summoner names @see <a href=https://developer.riotgames.com/api/methods#!/620/1934>Official API documentation</a>
[ "Retrieve", "summoner", "names", "for", "the", "specified", "ids" ]
train
https://github.com/loldevs/riotapi/blob/0b8aac407aa5289845f249024f9732332855544f/rest/src/main/java/net/boreeas/riotapi/rest/ThrottledApiHandler.java#L1151-L1153
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/ValueEnforcer.java
ValueEnforcer.isBetweenExclusive
public static float isBetweenExclusive (final float fValue, final String sName, final float fLowerBoundExclusive, final float fUpperBoundExclusive) { """ Check if <code>nValue &gt; nLowerBoundInclusive &amp;&amp; nValue &lt; nUpperBoundInclusive</code> @param fValue Value @param sName Name @param fLowerBoundExclusive Lower bound @param fUpperBoundExclusive Upper bound @return The value """ if (isEnabled ()) return isBetweenExclusive (fValue, () -> sName, fLowerBoundExclusive, fUpperBoundExclusive); return fValue; }
java
public static float isBetweenExclusive (final float fValue, final String sName, final float fLowerBoundExclusive, final float fUpperBoundExclusive) { if (isEnabled ()) return isBetweenExclusive (fValue, () -> sName, fLowerBoundExclusive, fUpperBoundExclusive); return fValue; }
[ "public", "static", "float", "isBetweenExclusive", "(", "final", "float", "fValue", ",", "final", "String", "sName", ",", "final", "float", "fLowerBoundExclusive", ",", "final", "float", "fUpperBoundExclusive", ")", "{", "if", "(", "isEnabled", "(", ")", ")", "return", "isBetweenExclusive", "(", "fValue", ",", "(", ")", "->", "sName", ",", "fLowerBoundExclusive", ",", "fUpperBoundExclusive", ")", ";", "return", "fValue", ";", "}" ]
Check if <code>nValue &gt; nLowerBoundInclusive &amp;&amp; nValue &lt; nUpperBoundInclusive</code> @param fValue Value @param sName Name @param fLowerBoundExclusive Lower bound @param fUpperBoundExclusive Upper bound @return The value
[ "Check", "if", "<code", ">", "nValue", "&gt", ";", "nLowerBoundInclusive", "&amp", ";", "&amp", ";", "nValue", "&lt", ";", "nUpperBoundInclusive<", "/", "code", ">" ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/ValueEnforcer.java#L2899-L2907
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/utils/TransformationUtils.java
TransformationUtils.getWorldToPixel
public static AffineTransform getWorldToPixel( Envelope worldEnvelope, Rectangle pixelRectangle ) { """ Get the affine transform that brings from the world envelope to the rectangle. @param worldEnvelope the envelope. @param pixelRectangle the destination rectangle. @return the transform. """ double width = pixelRectangle.getWidth(); double worldWidth = worldEnvelope.getWidth(); double height = pixelRectangle.getHeight(); double worldHeight = worldEnvelope.getHeight(); AffineTransform translate = AffineTransform.getTranslateInstance(-worldEnvelope.getMinX(), -worldEnvelope.getMinY()); AffineTransform scale = AffineTransform.getScaleInstance(width / worldWidth, height / worldHeight); AffineTransform mirror_y = new AffineTransform(1, 0, 0, -1, 0, pixelRectangle.getHeight()); AffineTransform world2pixel = new AffineTransform(mirror_y); world2pixel.concatenate(scale); world2pixel.concatenate(translate); return world2pixel; }
java
public static AffineTransform getWorldToPixel( Envelope worldEnvelope, Rectangle pixelRectangle ) { double width = pixelRectangle.getWidth(); double worldWidth = worldEnvelope.getWidth(); double height = pixelRectangle.getHeight(); double worldHeight = worldEnvelope.getHeight(); AffineTransform translate = AffineTransform.getTranslateInstance(-worldEnvelope.getMinX(), -worldEnvelope.getMinY()); AffineTransform scale = AffineTransform.getScaleInstance(width / worldWidth, height / worldHeight); AffineTransform mirror_y = new AffineTransform(1, 0, 0, -1, 0, pixelRectangle.getHeight()); AffineTransform world2pixel = new AffineTransform(mirror_y); world2pixel.concatenate(scale); world2pixel.concatenate(translate); return world2pixel; }
[ "public", "static", "AffineTransform", "getWorldToPixel", "(", "Envelope", "worldEnvelope", ",", "Rectangle", "pixelRectangle", ")", "{", "double", "width", "=", "pixelRectangle", ".", "getWidth", "(", ")", ";", "double", "worldWidth", "=", "worldEnvelope", ".", "getWidth", "(", ")", ";", "double", "height", "=", "pixelRectangle", ".", "getHeight", "(", ")", ";", "double", "worldHeight", "=", "worldEnvelope", ".", "getHeight", "(", ")", ";", "AffineTransform", "translate", "=", "AffineTransform", ".", "getTranslateInstance", "(", "-", "worldEnvelope", ".", "getMinX", "(", ")", ",", "-", "worldEnvelope", ".", "getMinY", "(", ")", ")", ";", "AffineTransform", "scale", "=", "AffineTransform", ".", "getScaleInstance", "(", "width", "/", "worldWidth", ",", "height", "/", "worldHeight", ")", ";", "AffineTransform", "mirror_y", "=", "new", "AffineTransform", "(", "1", ",", "0", ",", "0", ",", "-", "1", ",", "0", ",", "pixelRectangle", ".", "getHeight", "(", ")", ")", ";", "AffineTransform", "world2pixel", "=", "new", "AffineTransform", "(", "mirror_y", ")", ";", "world2pixel", ".", "concatenate", "(", "scale", ")", ";", "world2pixel", ".", "concatenate", "(", "translate", ")", ";", "return", "world2pixel", ";", "}" ]
Get the affine transform that brings from the world envelope to the rectangle. @param worldEnvelope the envelope. @param pixelRectangle the destination rectangle. @return the transform.
[ "Get", "the", "affine", "transform", "that", "brings", "from", "the", "world", "envelope", "to", "the", "rectangle", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/TransformationUtils.java#L42-L55
DV8FromTheWorld/JDA
src/main/java/net/dv8tion/jda/core/MessageBuilder.java
MessageBuilder.appendCodeBlock
public MessageBuilder appendCodeBlock(CharSequence text, CharSequence language) { """ Appends a code-block to the Message. <br>Discord uses <a href="https://highlightjs.org/">Highlight.js</a> for its language highlighting support. You can find out what specific languages are supported <a href="https://github.com/isagalaev/highlight.js/tree/master/src/languages">here</a>. @param text the code to append @param language the language of the code. If unknown use an empty string @return The MessageBuilder instance. Useful for chaining. """ builder.append("```").append(language).append('\n').append(text).append("\n```"); return this; }
java
public MessageBuilder appendCodeBlock(CharSequence text, CharSequence language) { builder.append("```").append(language).append('\n').append(text).append("\n```"); return this; }
[ "public", "MessageBuilder", "appendCodeBlock", "(", "CharSequence", "text", ",", "CharSequence", "language", ")", "{", "builder", ".", "append", "(", "\"```\"", ")", ".", "append", "(", "language", ")", ".", "append", "(", "'", "'", ")", ".", "append", "(", "text", ")", ".", "append", "(", "\"\\n```\"", ")", ";", "return", "this", ";", "}" ]
Appends a code-block to the Message. <br>Discord uses <a href="https://highlightjs.org/">Highlight.js</a> for its language highlighting support. You can find out what specific languages are supported <a href="https://github.com/isagalaev/highlight.js/tree/master/src/languages">here</a>. @param text the code to append @param language the language of the code. If unknown use an empty string @return The MessageBuilder instance. Useful for chaining.
[ "Appends", "a", "code", "-", "block", "to", "the", "Message", ".", "<br", ">", "Discord", "uses", "<a", "href", "=", "https", ":", "//", "highlightjs", ".", "org", "/", ">", "Highlight", ".", "js<", "/", "a", ">", "for", "its", "language", "highlighting", "support", ".", "You", "can", "find", "out", "what", "specific", "languages", "are", "supported", "<a", "href", "=", "https", ":", "//", "github", ".", "com", "/", "isagalaev", "/", "highlight", ".", "js", "/", "tree", "/", "master", "/", "src", "/", "languages", ">", "here<", "/", "a", ">", "." ]
train
https://github.com/DV8FromTheWorld/JDA/blob/8ecbbe354d03f6bf448411bba573d0d4c268b560/src/main/java/net/dv8tion/jda/core/MessageBuilder.java#L345-L349
alkacon/opencms-core
src/org/opencms/ui/CmsVaadinUtils.java
CmsVaadinUtils.getBootstrapScript
public static String getBootstrapScript(CmsObject cms, String elementId, String servicePath) throws Exception { """ Returns the Javascript code to use for initializing a Vaadin UI.<p> @param cms the CMS context @param elementId the id of the DOM element in which to initialize the UI @param servicePath the UI servlet path @return the Javascript code to initialize Vaadin @throws Exception if something goes wrong """ String script = BOOTSTRAP_SCRIPT; CmsMacroResolver resolver = new CmsMacroResolver(); String context = OpenCms.getSystemInfo().getContextPath(); String vaadinDir = CmsStringUtil.joinPaths(context, "VAADIN/"); String vaadinVersion = Version.getFullVersion(); String vaadinServlet = CmsStringUtil.joinPaths(context, servicePath); String vaadinBootstrap = CmsStringUtil.joinPaths(context, "VAADIN/vaadinBootstrap.js"); resolver.addMacro("vaadinDir", vaadinDir); resolver.addMacro("vaadinVersion", vaadinVersion); resolver.addMacro("elementId", elementId); resolver.addMacro("vaadinServlet", vaadinServlet); resolver.addMacro("vaadinBootstrap", vaadinBootstrap); script = resolver.resolveMacros(script); return script; }
java
public static String getBootstrapScript(CmsObject cms, String elementId, String servicePath) throws Exception { String script = BOOTSTRAP_SCRIPT; CmsMacroResolver resolver = new CmsMacroResolver(); String context = OpenCms.getSystemInfo().getContextPath(); String vaadinDir = CmsStringUtil.joinPaths(context, "VAADIN/"); String vaadinVersion = Version.getFullVersion(); String vaadinServlet = CmsStringUtil.joinPaths(context, servicePath); String vaadinBootstrap = CmsStringUtil.joinPaths(context, "VAADIN/vaadinBootstrap.js"); resolver.addMacro("vaadinDir", vaadinDir); resolver.addMacro("vaadinVersion", vaadinVersion); resolver.addMacro("elementId", elementId); resolver.addMacro("vaadinServlet", vaadinServlet); resolver.addMacro("vaadinBootstrap", vaadinBootstrap); script = resolver.resolveMacros(script); return script; }
[ "public", "static", "String", "getBootstrapScript", "(", "CmsObject", "cms", ",", "String", "elementId", ",", "String", "servicePath", ")", "throws", "Exception", "{", "String", "script", "=", "BOOTSTRAP_SCRIPT", ";", "CmsMacroResolver", "resolver", "=", "new", "CmsMacroResolver", "(", ")", ";", "String", "context", "=", "OpenCms", ".", "getSystemInfo", "(", ")", ".", "getContextPath", "(", ")", ";", "String", "vaadinDir", "=", "CmsStringUtil", ".", "joinPaths", "(", "context", ",", "\"VAADIN/\"", ")", ";", "String", "vaadinVersion", "=", "Version", ".", "getFullVersion", "(", ")", ";", "String", "vaadinServlet", "=", "CmsStringUtil", ".", "joinPaths", "(", "context", ",", "servicePath", ")", ";", "String", "vaadinBootstrap", "=", "CmsStringUtil", ".", "joinPaths", "(", "context", ",", "\"VAADIN/vaadinBootstrap.js\"", ")", ";", "resolver", ".", "addMacro", "(", "\"vaadinDir\"", ",", "vaadinDir", ")", ";", "resolver", ".", "addMacro", "(", "\"vaadinVersion\"", ",", "vaadinVersion", ")", ";", "resolver", ".", "addMacro", "(", "\"elementId\"", ",", "elementId", ")", ";", "resolver", ".", "addMacro", "(", "\"vaadinServlet\"", ",", "vaadinServlet", ")", ";", "resolver", ".", "addMacro", "(", "\"vaadinBootstrap\"", ",", "vaadinBootstrap", ")", ";", "script", "=", "resolver", ".", "resolveMacros", "(", "script", ")", ";", "return", "script", ";", "}" ]
Returns the Javascript code to use for initializing a Vaadin UI.<p> @param cms the CMS context @param elementId the id of the DOM element in which to initialize the UI @param servicePath the UI servlet path @return the Javascript code to initialize Vaadin @throws Exception if something goes wrong
[ "Returns", "the", "Javascript", "code", "to", "use", "for", "initializing", "a", "Vaadin", "UI", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/CmsVaadinUtils.java#L498-L515
ops4j/org.ops4j.base
ops4j-base-monitors/src/main/java/org/ops4j/monitors/stream/StreamMonitorRouter.java
StreamMonitorRouter.notifyError
public void notifyError( URL resource, String message ) { """ Notify the monitor of the an error during the download process. @param resource the name of the remote resource. @param message a non-localized message describing the problem in english. """ synchronized( m_Monitors ) { for( StreamMonitor monitor : m_Monitors ) { monitor.notifyError( resource, message ); } } }
java
public void notifyError( URL resource, String message ) { synchronized( m_Monitors ) { for( StreamMonitor monitor : m_Monitors ) { monitor.notifyError( resource, message ); } } }
[ "public", "void", "notifyError", "(", "URL", "resource", ",", "String", "message", ")", "{", "synchronized", "(", "m_Monitors", ")", "{", "for", "(", "StreamMonitor", "monitor", ":", "m_Monitors", ")", "{", "monitor", ".", "notifyError", "(", "resource", ",", "message", ")", ";", "}", "}", "}" ]
Notify the monitor of the an error during the download process. @param resource the name of the remote resource. @param message a non-localized message describing the problem in english.
[ "Notify", "the", "monitor", "of", "the", "an", "error", "during", "the", "download", "process", "." ]
train
https://github.com/ops4j/org.ops4j.base/blob/b0e742c0d9511f6b19ca64da2ebaf30b7a47256a/ops4j-base-monitors/src/main/java/org/ops4j/monitors/stream/StreamMonitorRouter.java#L88-L97
petergeneric/stdlib
guice/common/src/main/java/com/peterphi/std/guice/common/ClassScanner.java
ClassScanner.getClasses
public List<Class<?>> getClasses(final String pkg, boolean recursive) { """ Find all the classes in a package @param pkg @param recursive @return """ return getClasses(pkg, recursive, null); }
java
public List<Class<?>> getClasses(final String pkg, boolean recursive) { return getClasses(pkg, recursive, null); }
[ "public", "List", "<", "Class", "<", "?", ">", ">", "getClasses", "(", "final", "String", "pkg", ",", "boolean", "recursive", ")", "{", "return", "getClasses", "(", "pkg", ",", "recursive", ",", "null", ")", ";", "}" ]
Find all the classes in a package @param pkg @param recursive @return
[ "Find", "all", "the", "classes", "in", "a", "package" ]
train
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/common/src/main/java/com/peterphi/std/guice/common/ClassScanner.java#L95-L98
Appendium/objectlabkit
datecalc-common/src/main/java/net/objectlab/kit/datecalc/common/AbstractDateCalculator.java
AbstractDateCalculator.moveByTenor
@Override public DateCalculator<E> moveByTenor(final Tenor tenor, final int spotLag) { """ move the current date by a given tenor, this means that if a date is either a 'weekend' or holiday, it will be skipped acording to the holiday handler and not count towards the number of days to move. @param tenor the tenor. @param spotLag number of days to "spot" days, this can vary from one market to the other. @return the current businessCalendar (so one can do calendar.moveByTenor(StandardTenor.T_2M).getCurrentBusinessDate();) """ if (tenor == null) { throw new IllegalArgumentException("Tenor cannot be null"); } TenorCode tenorCode = tenor.getCode(); if (tenorCode != TenorCode.OVERNIGHT && tenorCode != TenorCode.TOM_NEXT /*&& spotLag != 0*/) { // get to the Spot date first: moveToSpotDate(spotLag); } int unit = tenor.getUnits(); if (tenorCode == TenorCode.WEEK) { tenorCode = TenorCode.DAY; unit *= DAYS_IN_WEEK; } if (tenorCode == TenorCode.YEAR) { tenorCode = TenorCode.MONTH; unit *= MONTHS_IN_YEAR; } return applyTenor(tenorCode, unit); }
java
@Override public DateCalculator<E> moveByTenor(final Tenor tenor, final int spotLag) { if (tenor == null) { throw new IllegalArgumentException("Tenor cannot be null"); } TenorCode tenorCode = tenor.getCode(); if (tenorCode != TenorCode.OVERNIGHT && tenorCode != TenorCode.TOM_NEXT /*&& spotLag != 0*/) { // get to the Spot date first: moveToSpotDate(spotLag); } int unit = tenor.getUnits(); if (tenorCode == TenorCode.WEEK) { tenorCode = TenorCode.DAY; unit *= DAYS_IN_WEEK; } if (tenorCode == TenorCode.YEAR) { tenorCode = TenorCode.MONTH; unit *= MONTHS_IN_YEAR; } return applyTenor(tenorCode, unit); }
[ "@", "Override", "public", "DateCalculator", "<", "E", ">", "moveByTenor", "(", "final", "Tenor", "tenor", ",", "final", "int", "spotLag", ")", "{", "if", "(", "tenor", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Tenor cannot be null\"", ")", ";", "}", "TenorCode", "tenorCode", "=", "tenor", ".", "getCode", "(", ")", ";", "if", "(", "tenorCode", "!=", "TenorCode", ".", "OVERNIGHT", "&&", "tenorCode", "!=", "TenorCode", ".", "TOM_NEXT", "/*&& spotLag != 0*/", ")", "{", "// get to the Spot date first:\r", "moveToSpotDate", "(", "spotLag", ")", ";", "}", "int", "unit", "=", "tenor", ".", "getUnits", "(", ")", ";", "if", "(", "tenorCode", "==", "TenorCode", ".", "WEEK", ")", "{", "tenorCode", "=", "TenorCode", ".", "DAY", ";", "unit", "*=", "DAYS_IN_WEEK", ";", "}", "if", "(", "tenorCode", "==", "TenorCode", ".", "YEAR", ")", "{", "tenorCode", "=", "TenorCode", ".", "MONTH", ";", "unit", "*=", "MONTHS_IN_YEAR", ";", "}", "return", "applyTenor", "(", "tenorCode", ",", "unit", ")", ";", "}" ]
move the current date by a given tenor, this means that if a date is either a 'weekend' or holiday, it will be skipped acording to the holiday handler and not count towards the number of days to move. @param tenor the tenor. @param spotLag number of days to "spot" days, this can vary from one market to the other. @return the current businessCalendar (so one can do calendar.moveByTenor(StandardTenor.T_2M).getCurrentBusinessDate();)
[ "move", "the", "current", "date", "by", "a", "given", "tenor", "this", "means", "that", "if", "a", "date", "is", "either", "a", "weekend", "or", "holiday", "it", "will", "be", "skipped", "acording", "to", "the", "holiday", "handler", "and", "not", "count", "towards", "the", "number", "of", "days", "to", "move", "." ]
train
https://github.com/Appendium/objectlabkit/blob/cd649bce7a32e4e926520e62cb765f3b1d451594/datecalc-common/src/main/java/net/objectlab/kit/datecalc/common/AbstractDateCalculator.java#L145-L168
optimaize/anythingworks
client/rest/src/main/java/com/optimaize/anythingworks/client/rest/http/RestHttpClientImpl.java
RestHttpClientImpl.deserializeResult
private <T> T deserializeResult(Response response, @Nullable String envelopeFieldName, TypeRef returnType) throws WebApplicationException { """ Deserialize response body as received from the server to Java object according to the Content-Type (only JSON is supported for now). """ String contentType = readContentType(response); String body = readBody(response); if (contentType.startsWith("application/json")) { try { if (envelopeFieldName!=null) { return jsonMarshaller.deserializeEnveloped(body, envelopeFieldName, returnType); } else { return jsonMarshaller.deserialize(body, returnType); } } catch (JsonMarshallingException e) { String msg = "Failed unmarshalling JSON data from server to object: "+e.getMessage(); // throw new ClientErrorException(Response.Status.BAD_REQUEST, e); Retry retry; if (response.getStatusInfo().getFamily() == Response.Status.Family.SERVER_ERROR) { //it is likely that the server can handle it next time, and there won't be an error at all. //then there won't be a problem unmarshalling the error info either. retry = Retry.now(); } else { //success: no, because it's unlikely the server sends a different response next time. //client error: no, because the client's data is wrong anyway, we just can't understand the detail // why it's wrong, but it's still wrong next time. // this could happen when the client uses an outdated protocol. server rejects it, and // the client can't even understand (the detail of) the response. retry = Retry.no(); } throw new ClientServiceException( new RestFaultInfo( "Protocol", Blame.CLIENT, msg, ""+ErrorCodes.Client.UNMARSHALLING_FAILED.getCode(), null, retry, retry, response.getStatusInfo().getStatusCode(), response.getStatusInfo().getReasonPhrase() ), e ); } } else if (returnType.getType().equals(String.class)) { // Expecting string, return the raw response body. return (T) body; } else { String msg = "Client requested content type >>>"+ACCEPT+"<<< but server sent >>>\"" + contentType + "\"<<< and that is not supported for type: " + returnType.getType(); // throw new NotSupportedException(msg); throw new BadResponseServiceException( new RestFaultInfo("BadResponse", Blame.SERVER, msg, ""+ErrorCodes.Server.BAD_RESPONSE.getCode(), null, Retry.no(), Retry.no(), response.getStatusInfo().getStatusCode(), response.getStatusInfo().getReasonPhrase() ) ); } }
java
private <T> T deserializeResult(Response response, @Nullable String envelopeFieldName, TypeRef returnType) throws WebApplicationException { String contentType = readContentType(response); String body = readBody(response); if (contentType.startsWith("application/json")) { try { if (envelopeFieldName!=null) { return jsonMarshaller.deserializeEnveloped(body, envelopeFieldName, returnType); } else { return jsonMarshaller.deserialize(body, returnType); } } catch (JsonMarshallingException e) { String msg = "Failed unmarshalling JSON data from server to object: "+e.getMessage(); // throw new ClientErrorException(Response.Status.BAD_REQUEST, e); Retry retry; if (response.getStatusInfo().getFamily() == Response.Status.Family.SERVER_ERROR) { //it is likely that the server can handle it next time, and there won't be an error at all. //then there won't be a problem unmarshalling the error info either. retry = Retry.now(); } else { //success: no, because it's unlikely the server sends a different response next time. //client error: no, because the client's data is wrong anyway, we just can't understand the detail // why it's wrong, but it's still wrong next time. // this could happen when the client uses an outdated protocol. server rejects it, and // the client can't even understand (the detail of) the response. retry = Retry.no(); } throw new ClientServiceException( new RestFaultInfo( "Protocol", Blame.CLIENT, msg, ""+ErrorCodes.Client.UNMARSHALLING_FAILED.getCode(), null, retry, retry, response.getStatusInfo().getStatusCode(), response.getStatusInfo().getReasonPhrase() ), e ); } } else if (returnType.getType().equals(String.class)) { // Expecting string, return the raw response body. return (T) body; } else { String msg = "Client requested content type >>>"+ACCEPT+"<<< but server sent >>>\"" + contentType + "\"<<< and that is not supported for type: " + returnType.getType(); // throw new NotSupportedException(msg); throw new BadResponseServiceException( new RestFaultInfo("BadResponse", Blame.SERVER, msg, ""+ErrorCodes.Server.BAD_RESPONSE.getCode(), null, Retry.no(), Retry.no(), response.getStatusInfo().getStatusCode(), response.getStatusInfo().getReasonPhrase() ) ); } }
[ "private", "<", "T", ">", "T", "deserializeResult", "(", "Response", "response", ",", "@", "Nullable", "String", "envelopeFieldName", ",", "TypeRef", "returnType", ")", "throws", "WebApplicationException", "{", "String", "contentType", "=", "readContentType", "(", "response", ")", ";", "String", "body", "=", "readBody", "(", "response", ")", ";", "if", "(", "contentType", ".", "startsWith", "(", "\"application/json\"", ")", ")", "{", "try", "{", "if", "(", "envelopeFieldName", "!=", "null", ")", "{", "return", "jsonMarshaller", ".", "deserializeEnveloped", "(", "body", ",", "envelopeFieldName", ",", "returnType", ")", ";", "}", "else", "{", "return", "jsonMarshaller", ".", "deserialize", "(", "body", ",", "returnType", ")", ";", "}", "}", "catch", "(", "JsonMarshallingException", "e", ")", "{", "String", "msg", "=", "\"Failed unmarshalling JSON data from server to object: \"", "+", "e", ".", "getMessage", "(", ")", ";", "// throw new ClientErrorException(Response.Status.BAD_REQUEST, e);", "Retry", "retry", ";", "if", "(", "response", ".", "getStatusInfo", "(", ")", ".", "getFamily", "(", ")", "==", "Response", ".", "Status", ".", "Family", ".", "SERVER_ERROR", ")", "{", "//it is likely that the server can handle it next time, and there won't be an error at all.", "//then there won't be a problem unmarshalling the error info either.", "retry", "=", "Retry", ".", "now", "(", ")", ";", "}", "else", "{", "//success: no, because it's unlikely the server sends a different response next time.", "//client error: no, because the client's data is wrong anyway, we just can't understand the detail", "// why it's wrong, but it's still wrong next time.", "// this could happen when the client uses an outdated protocol. server rejects it, and", "// the client can't even understand (the detail of) the response.", "retry", "=", "Retry", ".", "no", "(", ")", ";", "}", "throw", "new", "ClientServiceException", "(", "new", "RestFaultInfo", "(", "\"Protocol\"", ",", "Blame", ".", "CLIENT", ",", "msg", ",", "\"\"", "+", "ErrorCodes", ".", "Client", ".", "UNMARSHALLING_FAILED", ".", "getCode", "(", ")", ",", "null", ",", "retry", ",", "retry", ",", "response", ".", "getStatusInfo", "(", ")", ".", "getStatusCode", "(", ")", ",", "response", ".", "getStatusInfo", "(", ")", ".", "getReasonPhrase", "(", ")", ")", ",", "e", ")", ";", "}", "}", "else", "if", "(", "returnType", ".", "getType", "(", ")", ".", "equals", "(", "String", ".", "class", ")", ")", "{", "// Expecting string, return the raw response body.", "return", "(", "T", ")", "body", ";", "}", "else", "{", "String", "msg", "=", "\"Client requested content type >>>\"", "+", "ACCEPT", "+", "\"<<< but server sent >>>\\\"\"", "+", "contentType", "+", "\"\\\"<<< and that is not supported for type: \"", "+", "returnType", ".", "getType", "(", ")", ";", "// throw new NotSupportedException(msg);", "throw", "new", "BadResponseServiceException", "(", "new", "RestFaultInfo", "(", "\"BadResponse\"", ",", "Blame", ".", "SERVER", ",", "msg", ",", "\"\"", "+", "ErrorCodes", ".", "Server", ".", "BAD_RESPONSE", ".", "getCode", "(", ")", ",", "null", ",", "Retry", ".", "no", "(", ")", ",", "Retry", ".", "no", "(", ")", ",", "response", ".", "getStatusInfo", "(", ")", ".", "getStatusCode", "(", ")", ",", "response", ".", "getStatusInfo", "(", ")", ".", "getReasonPhrase", "(", ")", ")", ")", ";", "}", "}" ]
Deserialize response body as received from the server to Java object according to the Content-Type (only JSON is supported for now).
[ "Deserialize", "response", "body", "as", "received", "from", "the", "server", "to", "Java", "object", "according", "to", "the", "Content", "-", "Type", "(", "only", "JSON", "is", "supported", "for", "now", ")", "." ]
train
https://github.com/optimaize/anythingworks/blob/23e5f1c63cd56d935afaac4ad033c7996b32a1f2/client/rest/src/main/java/com/optimaize/anythingworks/client/rest/http/RestHttpClientImpl.java#L249-L304
kuali/kc-s2sgen
coeus-s2sgen-impl/src/main/java/org/kuali/coeus/s2sgen/impl/generate/support/RRBudget10V1_3Generator.java
RRBudget10V1_3Generator.setBudgetYearDataType
private void setBudgetYearDataType(RRBudget1013 rrBudget,BudgetPeriodDto periodInfo) { """ This method gets BudgetYearDataType details like BudgetPeriodStartDate,BudgetPeriodEndDate,BudgetPeriod KeyPersons,OtherPersonnel,TotalCompensation,Equipment,ParticipantTraineeSupportCosts,Travel,OtherDirectCosts DirectCosts,IndirectCosts,CognizantFederalAgency,TotalCosts based on BudgetPeriodInfo for the RRBudget1013. @param periodInfo (BudgetPeriodInfo) budget period entry. """ BudgetYearDataType budgetYear = rrBudget.addNewBudgetYear(); if (periodInfo != null) { budgetYear.setBudgetPeriodStartDate(s2SDateTimeService.convertDateToCalendar(periodInfo.getStartDate())); budgetYear.setBudgetPeriodEndDate(s2SDateTimeService.convertDateToCalendar(periodInfo.getEndDate())); budgetYear.setKeyPersons(getKeyPersons(periodInfo)); budgetYear.setOtherPersonnel(getOtherPersonnel(periodInfo)); if (periodInfo.getTotalCompensation() != null) { budgetYear.setTotalCompensation(periodInfo .getTotalCompensation().bigDecimalValue()); } budgetYear.setEquipment(getEquipment(periodInfo)); budgetYear.setTravel(getTravel(periodInfo)); budgetYear .setParticipantTraineeSupportCosts(getParticipantTraineeSupportCosts(periodInfo)); budgetYear.setOtherDirectCosts(getOtherDirectCosts(periodInfo)); BigDecimal directCosts = periodInfo.getDirectCostsTotal() .bigDecimalValue(); budgetYear.setDirectCosts(directCosts); IndirectCosts indirectCosts = getIndirectCosts(periodInfo); if (indirectCosts != null) { budgetYear.setIndirectCosts(indirectCosts); budgetYear.setTotalCosts(periodInfo.getDirectCostsTotal().bigDecimalValue().add(indirectCosts.getTotalIndirectCosts())); }else{ budgetYear.setTotalCosts(periodInfo.getDirectCostsTotal().bigDecimalValue()); } budgetYear.setCognizantFederalAgency(periodInfo .getCognizantFedAgency()); } }
java
private void setBudgetYearDataType(RRBudget1013 rrBudget,BudgetPeriodDto periodInfo) { BudgetYearDataType budgetYear = rrBudget.addNewBudgetYear(); if (periodInfo != null) { budgetYear.setBudgetPeriodStartDate(s2SDateTimeService.convertDateToCalendar(periodInfo.getStartDate())); budgetYear.setBudgetPeriodEndDate(s2SDateTimeService.convertDateToCalendar(periodInfo.getEndDate())); budgetYear.setKeyPersons(getKeyPersons(periodInfo)); budgetYear.setOtherPersonnel(getOtherPersonnel(periodInfo)); if (periodInfo.getTotalCompensation() != null) { budgetYear.setTotalCompensation(periodInfo .getTotalCompensation().bigDecimalValue()); } budgetYear.setEquipment(getEquipment(periodInfo)); budgetYear.setTravel(getTravel(periodInfo)); budgetYear .setParticipantTraineeSupportCosts(getParticipantTraineeSupportCosts(periodInfo)); budgetYear.setOtherDirectCosts(getOtherDirectCosts(periodInfo)); BigDecimal directCosts = periodInfo.getDirectCostsTotal() .bigDecimalValue(); budgetYear.setDirectCosts(directCosts); IndirectCosts indirectCosts = getIndirectCosts(periodInfo); if (indirectCosts != null) { budgetYear.setIndirectCosts(indirectCosts); budgetYear.setTotalCosts(periodInfo.getDirectCostsTotal().bigDecimalValue().add(indirectCosts.getTotalIndirectCosts())); }else{ budgetYear.setTotalCosts(periodInfo.getDirectCostsTotal().bigDecimalValue()); } budgetYear.setCognizantFederalAgency(periodInfo .getCognizantFedAgency()); } }
[ "private", "void", "setBudgetYearDataType", "(", "RRBudget1013", "rrBudget", ",", "BudgetPeriodDto", "periodInfo", ")", "{", "BudgetYearDataType", "budgetYear", "=", "rrBudget", ".", "addNewBudgetYear", "(", ")", ";", "if", "(", "periodInfo", "!=", "null", ")", "{", "budgetYear", ".", "setBudgetPeriodStartDate", "(", "s2SDateTimeService", ".", "convertDateToCalendar", "(", "periodInfo", ".", "getStartDate", "(", ")", ")", ")", ";", "budgetYear", ".", "setBudgetPeriodEndDate", "(", "s2SDateTimeService", ".", "convertDateToCalendar", "(", "periodInfo", ".", "getEndDate", "(", ")", ")", ")", ";", "budgetYear", ".", "setKeyPersons", "(", "getKeyPersons", "(", "periodInfo", ")", ")", ";", "budgetYear", ".", "setOtherPersonnel", "(", "getOtherPersonnel", "(", "periodInfo", ")", ")", ";", "if", "(", "periodInfo", ".", "getTotalCompensation", "(", ")", "!=", "null", ")", "{", "budgetYear", ".", "setTotalCompensation", "(", "periodInfo", ".", "getTotalCompensation", "(", ")", ".", "bigDecimalValue", "(", ")", ")", ";", "}", "budgetYear", ".", "setEquipment", "(", "getEquipment", "(", "periodInfo", ")", ")", ";", "budgetYear", ".", "setTravel", "(", "getTravel", "(", "periodInfo", ")", ")", ";", "budgetYear", ".", "setParticipantTraineeSupportCosts", "(", "getParticipantTraineeSupportCosts", "(", "periodInfo", ")", ")", ";", "budgetYear", ".", "setOtherDirectCosts", "(", "getOtherDirectCosts", "(", "periodInfo", ")", ")", ";", "BigDecimal", "directCosts", "=", "periodInfo", ".", "getDirectCostsTotal", "(", ")", ".", "bigDecimalValue", "(", ")", ";", "budgetYear", ".", "setDirectCosts", "(", "directCosts", ")", ";", "IndirectCosts", "indirectCosts", "=", "getIndirectCosts", "(", "periodInfo", ")", ";", "if", "(", "indirectCosts", "!=", "null", ")", "{", "budgetYear", ".", "setIndirectCosts", "(", "indirectCosts", ")", ";", "budgetYear", ".", "setTotalCosts", "(", "periodInfo", ".", "getDirectCostsTotal", "(", ")", ".", "bigDecimalValue", "(", ")", ".", "add", "(", "indirectCosts", ".", "getTotalIndirectCosts", "(", ")", ")", ")", ";", "}", "else", "{", "budgetYear", ".", "setTotalCosts", "(", "periodInfo", ".", "getDirectCostsTotal", "(", ")", ".", "bigDecimalValue", "(", ")", ")", ";", "}", "budgetYear", ".", "setCognizantFederalAgency", "(", "periodInfo", ".", "getCognizantFedAgency", "(", ")", ")", ";", "}", "}" ]
This method gets BudgetYearDataType details like BudgetPeriodStartDate,BudgetPeriodEndDate,BudgetPeriod KeyPersons,OtherPersonnel,TotalCompensation,Equipment,ParticipantTraineeSupportCosts,Travel,OtherDirectCosts DirectCosts,IndirectCosts,CognizantFederalAgency,TotalCosts based on BudgetPeriodInfo for the RRBudget1013. @param periodInfo (BudgetPeriodInfo) budget period entry.
[ "This", "method", "gets", "BudgetYearDataType", "details", "like", "BudgetPeriodStartDate", "BudgetPeriodEndDate", "BudgetPeriod", "KeyPersons", "OtherPersonnel", "TotalCompensation", "Equipment", "ParticipantTraineeSupportCosts", "Travel", "OtherDirectCosts", "DirectCosts", "IndirectCosts", "CognizantFederalAgency", "TotalCosts", "based", "on", "BudgetPeriodInfo", "for", "the", "RRBudget1013", "." ]
train
https://github.com/kuali/kc-s2sgen/blob/2886380e1e3cb8bdd732ba99b2afa6ffc630bb37/coeus-s2sgen-impl/src/main/java/org/kuali/coeus/s2sgen/impl/generate/support/RRBudget10V1_3Generator.java#L149-L179
FasterXML/woodstox
src/main/java/com/ctc/wstx/sr/BasicStreamReader.java
BasicStreamReader.setProperty
@Override public boolean setProperty(String name, Object value) { """ @param name Name of the property to set @param value Value to set property to. @return True, if the specified property was <b>succesfully</b> set to specified value; false if its value was not changed """ boolean ok = mConfig.setProperty(name, value); /* To make [WSTX-50] work fully dynamically (i.e. allow * setting BASE_URL after stream reader has been constructed) * need to force */ if (ok && WstxInputProperties.P_BASE_URL.equals(name)) { // Easiest to just access from config: may come in as a String etc mInput.overrideSource(mConfig.getBaseURL()); } return ok; }
java
@Override public boolean setProperty(String name, Object value) { boolean ok = mConfig.setProperty(name, value); /* To make [WSTX-50] work fully dynamically (i.e. allow * setting BASE_URL after stream reader has been constructed) * need to force */ if (ok && WstxInputProperties.P_BASE_URL.equals(name)) { // Easiest to just access from config: may come in as a String etc mInput.overrideSource(mConfig.getBaseURL()); } return ok; }
[ "@", "Override", "public", "boolean", "setProperty", "(", "String", "name", ",", "Object", "value", ")", "{", "boolean", "ok", "=", "mConfig", ".", "setProperty", "(", "name", ",", "value", ")", ";", "/* To make [WSTX-50] work fully dynamically (i.e. allow\n * setting BASE_URL after stream reader has been constructed)\n * need to force\n */", "if", "(", "ok", "&&", "WstxInputProperties", ".", "P_BASE_URL", ".", "equals", "(", "name", ")", ")", "{", "// Easiest to just access from config: may come in as a String etc", "mInput", ".", "overrideSource", "(", "mConfig", ".", "getBaseURL", "(", ")", ")", ";", "}", "return", "ok", ";", "}" ]
@param name Name of the property to set @param value Value to set property to. @return True, if the specified property was <b>succesfully</b> set to specified value; false if its value was not changed
[ "@param", "name", "Name", "of", "the", "property", "to", "set", "@param", "value", "Value", "to", "set", "property", "to", "." ]
train
https://github.com/FasterXML/woodstox/blob/ffcaabdc06672d9564c48c25d601d029b7fd6548/src/main/java/com/ctc/wstx/sr/BasicStreamReader.java#L1302-L1315
Cornutum/tcases
tcases-io/src/main/java/org/cornutum/tcases/io/SystemInputJson.java
SystemInputJson.addAnnotations
private static JsonObjectBuilder addAnnotations( JsonObjectBuilder builder, IAnnotated annotated) { """ Add any annotatations from the given Annotated object to the given JsonObjectBuilder. """ JsonObjectBuilder annotations = Json.createObjectBuilder(); toStream( annotated.getAnnotations()).forEach( name -> annotations.add( name, annotated.getAnnotation( name))); JsonObject json = annotations.build(); if( !json.isEmpty()) { builder.add( HAS_KEY, json); } return builder; }
java
private static JsonObjectBuilder addAnnotations( JsonObjectBuilder builder, IAnnotated annotated) { JsonObjectBuilder annotations = Json.createObjectBuilder(); toStream( annotated.getAnnotations()).forEach( name -> annotations.add( name, annotated.getAnnotation( name))); JsonObject json = annotations.build(); if( !json.isEmpty()) { builder.add( HAS_KEY, json); } return builder; }
[ "private", "static", "JsonObjectBuilder", "addAnnotations", "(", "JsonObjectBuilder", "builder", ",", "IAnnotated", "annotated", ")", "{", "JsonObjectBuilder", "annotations", "=", "Json", ".", "createObjectBuilder", "(", ")", ";", "toStream", "(", "annotated", ".", "getAnnotations", "(", ")", ")", ".", "forEach", "(", "name", "->", "annotations", ".", "add", "(", "name", ",", "annotated", ".", "getAnnotation", "(", "name", ")", ")", ")", ";", "JsonObject", "json", "=", "annotations", ".", "build", "(", ")", ";", "if", "(", "!", "json", ".", "isEmpty", "(", ")", ")", "{", "builder", ".", "add", "(", "HAS_KEY", ",", "json", ")", ";", "}", "return", "builder", ";", "}" ]
Add any annotatations from the given Annotated object to the given JsonObjectBuilder.
[ "Add", "any", "annotatations", "from", "the", "given", "Annotated", "object", "to", "the", "given", "JsonObjectBuilder", "." ]
train
https://github.com/Cornutum/tcases/blob/21e15cf107fa149620c40f4bda1829c1224fcfb1/tcases-io/src/main/java/org/cornutum/tcases/io/SystemInputJson.java#L142-L154
samskivert/pythagoras
src/main/java/pythagoras/f/Rectangles.java
Rectangles.pointRectDistance
public static float pointRectDistance (IRectangle r, IPoint p) { """ Returns the Euclidean distance between the given point and the nearest point inside the bounds of the given rectangle. If the supplied point is inside the rectangle, the distance will be zero. """ return FloatMath.sqrt(pointRectDistanceSq(r, p)); }
java
public static float pointRectDistance (IRectangle r, IPoint p) { return FloatMath.sqrt(pointRectDistanceSq(r, p)); }
[ "public", "static", "float", "pointRectDistance", "(", "IRectangle", "r", ",", "IPoint", "p", ")", "{", "return", "FloatMath", ".", "sqrt", "(", "pointRectDistanceSq", "(", "r", ",", "p", ")", ")", ";", "}" ]
Returns the Euclidean distance between the given point and the nearest point inside the bounds of the given rectangle. If the supplied point is inside the rectangle, the distance will be zero.
[ "Returns", "the", "Euclidean", "distance", "between", "the", "given", "point", "and", "the", "nearest", "point", "inside", "the", "bounds", "of", "the", "given", "rectangle", ".", "If", "the", "supplied", "point", "is", "inside", "the", "rectangle", "the", "distance", "will", "be", "zero", "." ]
train
https://github.com/samskivert/pythagoras/blob/b8fea743ee8a7d742ad9c06ee4f11f50571fbd32/src/main/java/pythagoras/f/Rectangles.java#L68-L70
googlegenomics/utils-java
src/main/java/com/google/cloud/genomics/utils/GenomicsFactory.java
GenomicsFactory.fromApplicationDefaultCredential
public <T extends AbstractGoogleJsonClient.Builder> T fromApplicationDefaultCredential(T builder) { """ Prepare an AbstractGoogleJsonClient.Builder using the Application Default Credential. @param builder The builder to be prepared. @return The passed in builder, for easy chaining. """ Preconditions.checkNotNull(builder); return fromCredential(builder, CredentialFactory.getApplicationDefaultCredential()); }
java
public <T extends AbstractGoogleJsonClient.Builder> T fromApplicationDefaultCredential(T builder) { Preconditions.checkNotNull(builder); return fromCredential(builder, CredentialFactory.getApplicationDefaultCredential()); }
[ "public", "<", "T", "extends", "AbstractGoogleJsonClient", ".", "Builder", ">", "T", "fromApplicationDefaultCredential", "(", "T", "builder", ")", "{", "Preconditions", ".", "checkNotNull", "(", "builder", ")", ";", "return", "fromCredential", "(", "builder", ",", "CredentialFactory", ".", "getApplicationDefaultCredential", "(", ")", ")", ";", "}" ]
Prepare an AbstractGoogleJsonClient.Builder using the Application Default Credential. @param builder The builder to be prepared. @return The passed in builder, for easy chaining.
[ "Prepare", "an", "AbstractGoogleJsonClient", ".", "Builder", "using", "the", "Application", "Default", "Credential", "." ]
train
https://github.com/googlegenomics/utils-java/blob/7205d5b4e4f61fc6b93acb4bdd76b93df5b5f612/src/main/java/com/google/cloud/genomics/utils/GenomicsFactory.java#L426-L429
TheCoder4eu/BootsFaces-OSP
src/main/java/net/bootsfaces/listeners/AddResourcesListener.java
AddResourcesListener.processEvent
public void processEvent(SystemEvent event) throws AbortProcessingException { """ Trigger adding the resources if and only if the event has been fired by UIViewRoot. """ FacesContext context = FacesContext.getCurrentInstance(); UIViewRoot root = context.getViewRoot(); // render the resources only if there is at least one bsf component if (ensureExistBootsfacesComponent(root, context)) { addCSS(root, context); addJavascript(root, context); addMetaTags(root, context); } }
java
public void processEvent(SystemEvent event) throws AbortProcessingException { FacesContext context = FacesContext.getCurrentInstance(); UIViewRoot root = context.getViewRoot(); // render the resources only if there is at least one bsf component if (ensureExistBootsfacesComponent(root, context)) { addCSS(root, context); addJavascript(root, context); addMetaTags(root, context); } }
[ "public", "void", "processEvent", "(", "SystemEvent", "event", ")", "throws", "AbortProcessingException", "{", "FacesContext", "context", "=", "FacesContext", ".", "getCurrentInstance", "(", ")", ";", "UIViewRoot", "root", "=", "context", ".", "getViewRoot", "(", ")", ";", "// render the resources only if there is at least one bsf component", "if", "(", "ensureExistBootsfacesComponent", "(", "root", ",", "context", ")", ")", "{", "addCSS", "(", "root", ",", "context", ")", ";", "addJavascript", "(", "root", ",", "context", ")", ";", "addMetaTags", "(", "root", ",", "context", ")", ";", "}", "}" ]
Trigger adding the resources if and only if the event has been fired by UIViewRoot.
[ "Trigger", "adding", "the", "resources", "if", "and", "only", "if", "the", "event", "has", "been", "fired", "by", "UIViewRoot", "." ]
train
https://github.com/TheCoder4eu/BootsFaces-OSP/blob/d1a70952bc240979b5272fa4fe1c7f100873add0/src/main/java/net/bootsfaces/listeners/AddResourcesListener.java#L131-L141
twitter/twitter-korean-text
src/main/java/com/twitter/penguin/korean/util/CharacterUtils.java
CharacterUtils.toChars
public final int toChars(int[] src, int srcOff, int srcLen, char[] dest, int destOff) { """ Converts a sequence of unicode code points to a sequence of Java characters. @return the number of chars written to the destination buffer """ if (srcLen < 0) { throw new IllegalArgumentException("srcLen must be >= 0"); } int written = 0; for (int i = 0; i < srcLen; ++i) { written += Character.toChars(src[srcOff + i], dest, destOff + written); } return written; }
java
public final int toChars(int[] src, int srcOff, int srcLen, char[] dest, int destOff) { if (srcLen < 0) { throw new IllegalArgumentException("srcLen must be >= 0"); } int written = 0; for (int i = 0; i < srcLen; ++i) { written += Character.toChars(src[srcOff + i], dest, destOff + written); } return written; }
[ "public", "final", "int", "toChars", "(", "int", "[", "]", "src", ",", "int", "srcOff", ",", "int", "srcLen", ",", "char", "[", "]", "dest", ",", "int", "destOff", ")", "{", "if", "(", "srcLen", "<", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"srcLen must be >= 0\"", ")", ";", "}", "int", "written", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "srcLen", ";", "++", "i", ")", "{", "written", "+=", "Character", ".", "toChars", "(", "src", "[", "srcOff", "+", "i", "]", ",", "dest", ",", "destOff", "+", "written", ")", ";", "}", "return", "written", ";", "}" ]
Converts a sequence of unicode code points to a sequence of Java characters. @return the number of chars written to the destination buffer
[ "Converts", "a", "sequence", "of", "unicode", "code", "points", "to", "a", "sequence", "of", "Java", "characters", "." ]
train
https://github.com/twitter/twitter-korean-text/blob/95bbe21fcc62fa7bf50b769ae80a5734fef6b903/src/main/java/com/twitter/penguin/korean/util/CharacterUtils.java#L153-L162
mongodb/stitch-android-sdk
core/services/mongodb-remote/src/main/java/com/mongodb/stitch/core/services/mongodb/remote/sync/internal/ChangeEvents.java
ChangeEvents.changeEventForLocalReplace
static ChangeEvent<BsonDocument> changeEventForLocalReplace( final MongoNamespace namespace, final BsonValue documentId, final BsonDocument document, final boolean writePending ) { """ Generates a change event for a local replacement of a document in the given namespace referring to the given document _id. @param namespace the namespace where the document was inserted. @param documentId the _id of the document that was updated. @param document the replacement document. @return a change event for a local replacement of a document in the given namespace referring to the given document _id. """ return new ChangeEvent<>( new BsonDocument(), OperationType.REPLACE, document, namespace, new BsonDocument("_id", documentId), null, writePending); }
java
static ChangeEvent<BsonDocument> changeEventForLocalReplace( final MongoNamespace namespace, final BsonValue documentId, final BsonDocument document, final boolean writePending ) { return new ChangeEvent<>( new BsonDocument(), OperationType.REPLACE, document, namespace, new BsonDocument("_id", documentId), null, writePending); }
[ "static", "ChangeEvent", "<", "BsonDocument", ">", "changeEventForLocalReplace", "(", "final", "MongoNamespace", "namespace", ",", "final", "BsonValue", "documentId", ",", "final", "BsonDocument", "document", ",", "final", "boolean", "writePending", ")", "{", "return", "new", "ChangeEvent", "<>", "(", "new", "BsonDocument", "(", ")", ",", "OperationType", ".", "REPLACE", ",", "document", ",", "namespace", ",", "new", "BsonDocument", "(", "\"_id\"", ",", "documentId", ")", ",", "null", ",", "writePending", ")", ";", "}" ]
Generates a change event for a local replacement of a document in the given namespace referring to the given document _id. @param namespace the namespace where the document was inserted. @param documentId the _id of the document that was updated. @param document the replacement document. @return a change event for a local replacement of a document in the given namespace referring to the given document _id.
[ "Generates", "a", "change", "event", "for", "a", "local", "replacement", "of", "a", "document", "in", "the", "given", "namespace", "referring", "to", "the", "given", "document", "_id", "." ]
train
https://github.com/mongodb/stitch-android-sdk/blob/159b9334b1f1a827285544be5ee20cdf7b04e4cc/core/services/mongodb-remote/src/main/java/com/mongodb/stitch/core/services/mongodb/remote/sync/internal/ChangeEvents.java#L93-L107
davetcc/tcMenu
tcMenuCodePluginApi/src/main/java/com/thecoderscorner/menu/pluginapi/AbstractCodeCreator.java
AbstractCodeCreator.findPropertyValueAsIntWithDefault
public int findPropertyValueAsIntWithDefault(String name, int defVal) { """ Find the integer value of a property or a default if it is not set @param name the property name @param defVal the default value @return the properties integer value or the default """ return properties().stream() .filter(p->name.equals(p.getName())) .map(CreatorProperty::getLatestValueAsInt) .findFirst().orElse(defVal); }
java
public int findPropertyValueAsIntWithDefault(String name, int defVal) { return properties().stream() .filter(p->name.equals(p.getName())) .map(CreatorProperty::getLatestValueAsInt) .findFirst().orElse(defVal); }
[ "public", "int", "findPropertyValueAsIntWithDefault", "(", "String", "name", ",", "int", "defVal", ")", "{", "return", "properties", "(", ")", ".", "stream", "(", ")", ".", "filter", "(", "p", "->", "name", ".", "equals", "(", "p", ".", "getName", "(", ")", ")", ")", ".", "map", "(", "CreatorProperty", "::", "getLatestValueAsInt", ")", ".", "findFirst", "(", ")", ".", "orElse", "(", "defVal", ")", ";", "}" ]
Find the integer value of a property or a default if it is not set @param name the property name @param defVal the default value @return the properties integer value or the default
[ "Find", "the", "integer", "value", "of", "a", "property", "or", "a", "default", "if", "it", "is", "not", "set" ]
train
https://github.com/davetcc/tcMenu/blob/61546e4b982b25ceaff384073fe9ec1fff55e64a/tcMenuCodePluginApi/src/main/java/com/thecoderscorner/menu/pluginapi/AbstractCodeCreator.java#L177-L182
looly/hutool
hutool-core/src/main/java/cn/hutool/core/thread/ThreadUtil.java
ThreadUtil.newExecutor
public static ThreadPoolExecutor newExecutor(int corePoolSize, int maximumPoolSize) { """ 获得一个新的线程池<br> 如果maximumPoolSize =》 corePoolSize,在没有新任务加入的情况下,多出的线程将最多保留60s @param corePoolSize 初始线程池大小 @param maximumPoolSize 最大线程池大小 @return {@link ThreadPoolExecutor} """ return ExecutorBuilder.create().setCorePoolSize(corePoolSize).setMaxPoolSize(maximumPoolSize).build(); }
java
public static ThreadPoolExecutor newExecutor(int corePoolSize, int maximumPoolSize) { return ExecutorBuilder.create().setCorePoolSize(corePoolSize).setMaxPoolSize(maximumPoolSize).build(); }
[ "public", "static", "ThreadPoolExecutor", "newExecutor", "(", "int", "corePoolSize", ",", "int", "maximumPoolSize", ")", "{", "return", "ExecutorBuilder", ".", "create", "(", ")", ".", "setCorePoolSize", "(", "corePoolSize", ")", ".", "setMaxPoolSize", "(", "maximumPoolSize", ")", ".", "build", "(", ")", ";", "}" ]
获得一个新的线程池<br> 如果maximumPoolSize =》 corePoolSize,在没有新任务加入的情况下,多出的线程将最多保留60s @param corePoolSize 初始线程池大小 @param maximumPoolSize 最大线程池大小 @return {@link ThreadPoolExecutor}
[ "获得一个新的线程池<br", ">", "如果maximumPoolSize", "=", "》", "corePoolSize,在没有新任务加入的情况下,多出的线程将最多保留60s" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/thread/ThreadUtil.java#L59-L61
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/spider/ShardCache.java
ShardCache.addShardStart
private void addShardStart(TableDefinition tableDef, int shardNumber, Date shardDate) { """ Create a local transaction to add the register the given shard, then cache it. """ SpiderTransaction spiderTran = new SpiderTransaction(); spiderTran.addShardStart(tableDef, shardNumber, shardDate); Tenant tenant = Tenant.getTenant(tableDef); DBTransaction dbTran = DBService.instance(tenant).startTransaction(); spiderTran.applyUpdates(dbTran); DBService.instance(tenant).commit(dbTran); synchronized (this) { cacheShardValue(tableDef, shardNumber, shardDate); } }
java
private void addShardStart(TableDefinition tableDef, int shardNumber, Date shardDate) { SpiderTransaction spiderTran = new SpiderTransaction(); spiderTran.addShardStart(tableDef, shardNumber, shardDate); Tenant tenant = Tenant.getTenant(tableDef); DBTransaction dbTran = DBService.instance(tenant).startTransaction(); spiderTran.applyUpdates(dbTran); DBService.instance(tenant).commit(dbTran); synchronized (this) { cacheShardValue(tableDef, shardNumber, shardDate); } }
[ "private", "void", "addShardStart", "(", "TableDefinition", "tableDef", ",", "int", "shardNumber", ",", "Date", "shardDate", ")", "{", "SpiderTransaction", "spiderTran", "=", "new", "SpiderTransaction", "(", ")", ";", "spiderTran", ".", "addShardStart", "(", "tableDef", ",", "shardNumber", ",", "shardDate", ")", ";", "Tenant", "tenant", "=", "Tenant", ".", "getTenant", "(", "tableDef", ")", ";", "DBTransaction", "dbTran", "=", "DBService", ".", "instance", "(", "tenant", ")", ".", "startTransaction", "(", ")", ";", "spiderTran", ".", "applyUpdates", "(", "dbTran", ")", ";", "DBService", ".", "instance", "(", "tenant", ")", ".", "commit", "(", "dbTran", ")", ";", "synchronized", "(", "this", ")", "{", "cacheShardValue", "(", "tableDef", ",", "shardNumber", ",", "shardDate", ")", ";", "}", "}" ]
Create a local transaction to add the register the given shard, then cache it.
[ "Create", "a", "local", "transaction", "to", "add", "the", "register", "the", "given", "shard", "then", "cache", "it", "." ]
train
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/spider/ShardCache.java#L142-L152
google/error-prone-javac
src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/HtmlDocletWriter.java
HtmlDocletWriter.getPackageLink
public Content getPackageLink(PackageDoc pkg, String label) { """ Return the link to the given package. @param pkg the package to link to. @param label the label for the link. @return a content tree for the package link. """ return getPackageLink(pkg, new StringContent(label)); }
java
public Content getPackageLink(PackageDoc pkg, String label) { return getPackageLink(pkg, new StringContent(label)); }
[ "public", "Content", "getPackageLink", "(", "PackageDoc", "pkg", ",", "String", "label", ")", "{", "return", "getPackageLink", "(", "pkg", ",", "new", "StringContent", "(", "label", ")", ")", ";", "}" ]
Return the link to the given package. @param pkg the package to link to. @param label the label for the link. @return a content tree for the package link.
[ "Return", "the", "link", "to", "the", "given", "package", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/HtmlDocletWriter.java#L948-L950
ngageoint/geopackage-java
src/main/java/mil/nga/geopackage/db/SQLUtils.java
SQLUtils.closeResultSet
public static void closeResultSet(ResultSet resultSet, String sql) { """ Close the ResultSet @param resultSet result set @param sql sql statement """ if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { log.log(Level.WARNING, "Failed to close SQL ResultSet: " + sql, e); } } }
java
public static void closeResultSet(ResultSet resultSet, String sql) { if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { log.log(Level.WARNING, "Failed to close SQL ResultSet: " + sql, e); } } }
[ "public", "static", "void", "closeResultSet", "(", "ResultSet", "resultSet", ",", "String", "sql", ")", "{", "if", "(", "resultSet", "!=", "null", ")", "{", "try", "{", "resultSet", ".", "close", "(", ")", ";", "}", "catch", "(", "SQLException", "e", ")", "{", "log", ".", "log", "(", "Level", ".", "WARNING", ",", "\"Failed to close SQL ResultSet: \"", "+", "sql", ",", "e", ")", ";", "}", "}", "}" ]
Close the ResultSet @param resultSet result set @param sql sql statement
[ "Close", "the", "ResultSet" ]
train
https://github.com/ngageoint/geopackage-java/blob/889bffb5d18330a3f4bd89443acf7959ebe3a376/src/main/java/mil/nga/geopackage/db/SQLUtils.java#L553-L562
sdl/Testy
src/main/java/com/sdl/selenium/web/WebLocatorAbstractBuilder.java
WebLocatorAbstractBuilder.setText
@SuppressWarnings("unchecked") public <T extends WebLocatorAbstractBuilder> T setText(String text, final SearchType... searchTypes) { """ <p><b>Used for finding element process (to generate xpath address)</b></p> @param text with which to identify the item @param searchTypes type search text element: see more details see {@link SearchType} @param <T> the element which calls this method @return this element """ pathBuilder.setText(text, searchTypes); return (T) this; }
java
@SuppressWarnings("unchecked") public <T extends WebLocatorAbstractBuilder> T setText(String text, final SearchType... searchTypes) { pathBuilder.setText(text, searchTypes); return (T) this; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "<", "T", "extends", "WebLocatorAbstractBuilder", ">", "T", "setText", "(", "String", "text", ",", "final", "SearchType", "...", "searchTypes", ")", "{", "pathBuilder", ".", "setText", "(", "text", ",", "searchTypes", ")", ";", "return", "(", "T", ")", "this", ";", "}" ]
<p><b>Used for finding element process (to generate xpath address)</b></p> @param text with which to identify the item @param searchTypes type search text element: see more details see {@link SearchType} @param <T> the element which calls this method @return this element
[ "<p", ">", "<b", ">", "Used", "for", "finding", "element", "process", "(", "to", "generate", "xpath", "address", ")", "<", "/", "b", ">", "<", "/", "p", ">" ]
train
https://github.com/sdl/Testy/blob/b3ae061554016f926f04694a39ff00dab7576609/src/main/java/com/sdl/selenium/web/WebLocatorAbstractBuilder.java#L194-L198
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/DateFormat.java
DateFormat.getInstance
static final public DateFormat getInstance(Calendar cal) { """ Returns a default date/time formatter that uses the SHORT style for both the date and the time. @param cal The calendar system for which a date/time format is desired. """ return getInstance(cal, ULocale.getDefault(Category.FORMAT)); }
java
static final public DateFormat getInstance(Calendar cal) { return getInstance(cal, ULocale.getDefault(Category.FORMAT)); }
[ "static", "final", "public", "DateFormat", "getInstance", "(", "Calendar", "cal", ")", "{", "return", "getInstance", "(", "cal", ",", "ULocale", ".", "getDefault", "(", "Category", ".", "FORMAT", ")", ")", ";", "}" ]
Returns a default date/time formatter that uses the SHORT style for both the date and the time. @param cal The calendar system for which a date/time format is desired.
[ "Returns", "a", "default", "date", "/", "time", "formatter", "that", "uses", "the", "SHORT", "style", "for", "both", "the", "date", "and", "the", "time", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/DateFormat.java#L1889-L1891
jbundle/jbundle
base/base/src/main/java/org/jbundle/base/field/event/ReadSecondaryHandler.java
ReadSecondaryHandler.addFieldSeqPair
public MoveOnValidHandler addFieldSeqPair(int iDestFieldSeq, int iSourceFieldSeq, boolean bMoveToDependent, boolean bMoveBackOnChange) { """ Add a destination/source field pair (on valid record, move dest to source). @param iDestFieldSeq The destination field. @param iSourceFieldSeq The source field. @param bMoveToDependent If true adds a MoveOnValidHandler to the secondary record. @param bMoveBackOnChange If true, adds a CopyFieldHandler to the destination field (moves to the source). """ // BaseField will return iSourceFieldSeq if m_OwnerField is 'Y'es return this.addFieldPair(this.getOwner().getRecord().getField(iDestFieldSeq), m_record.getField(iSourceFieldSeq), bMoveToDependent, bMoveBackOnChange, null, null); }
java
public MoveOnValidHandler addFieldSeqPair(int iDestFieldSeq, int iSourceFieldSeq, boolean bMoveToDependent, boolean bMoveBackOnChange) { // BaseField will return iSourceFieldSeq if m_OwnerField is 'Y'es return this.addFieldPair(this.getOwner().getRecord().getField(iDestFieldSeq), m_record.getField(iSourceFieldSeq), bMoveToDependent, bMoveBackOnChange, null, null); }
[ "public", "MoveOnValidHandler", "addFieldSeqPair", "(", "int", "iDestFieldSeq", ",", "int", "iSourceFieldSeq", ",", "boolean", "bMoveToDependent", ",", "boolean", "bMoveBackOnChange", ")", "{", "// BaseField will return iSourceFieldSeq if m_OwnerField is 'Y'es", "return", "this", ".", "addFieldPair", "(", "this", ".", "getOwner", "(", ")", ".", "getRecord", "(", ")", ".", "getField", "(", "iDestFieldSeq", ")", ",", "m_record", ".", "getField", "(", "iSourceFieldSeq", ")", ",", "bMoveToDependent", ",", "bMoveBackOnChange", ",", "null", ",", "null", ")", ";", "}" ]
Add a destination/source field pair (on valid record, move dest to source). @param iDestFieldSeq The destination field. @param iSourceFieldSeq The source field. @param bMoveToDependent If true adds a MoveOnValidHandler to the secondary record. @param bMoveBackOnChange If true, adds a CopyFieldHandler to the destination field (moves to the source).
[ "Add", "a", "destination", "/", "source", "field", "pair", "(", "on", "valid", "record", "move", "dest", "to", "source", ")", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/field/event/ReadSecondaryHandler.java#L251-L254
Alluxio/alluxio
core/server/common/src/main/java/alluxio/util/TarUtils.java
TarUtils.readTarGz
public static void readTarGz(Path dirPath, InputStream input) throws IOException { """ Reads a gzipped tar archive from a stream and writes it to the given path. @param dirPath the path to write the archive to @param input the input stream """ InputStream zipStream = new GzipCompressorInputStream(input); TarArchiveInputStream archiveStream = new TarArchiveInputStream(zipStream); TarArchiveEntry entry; while ((entry = (TarArchiveEntry) archiveStream.getNextEntry()) != null) { File outputFile = new File(dirPath.toFile(), entry.getName()); if (entry.isDirectory()) { outputFile.mkdirs(); } else { outputFile.getParentFile().mkdirs(); try (FileOutputStream fileOut = new FileOutputStream(outputFile)) { IOUtils.copy(archiveStream, fileOut); } } } }
java
public static void readTarGz(Path dirPath, InputStream input) throws IOException { InputStream zipStream = new GzipCompressorInputStream(input); TarArchiveInputStream archiveStream = new TarArchiveInputStream(zipStream); TarArchiveEntry entry; while ((entry = (TarArchiveEntry) archiveStream.getNextEntry()) != null) { File outputFile = new File(dirPath.toFile(), entry.getName()); if (entry.isDirectory()) { outputFile.mkdirs(); } else { outputFile.getParentFile().mkdirs(); try (FileOutputStream fileOut = new FileOutputStream(outputFile)) { IOUtils.copy(archiveStream, fileOut); } } } }
[ "public", "static", "void", "readTarGz", "(", "Path", "dirPath", ",", "InputStream", "input", ")", "throws", "IOException", "{", "InputStream", "zipStream", "=", "new", "GzipCompressorInputStream", "(", "input", ")", ";", "TarArchiveInputStream", "archiveStream", "=", "new", "TarArchiveInputStream", "(", "zipStream", ")", ";", "TarArchiveEntry", "entry", ";", "while", "(", "(", "entry", "=", "(", "TarArchiveEntry", ")", "archiveStream", ".", "getNextEntry", "(", ")", ")", "!=", "null", ")", "{", "File", "outputFile", "=", "new", "File", "(", "dirPath", ".", "toFile", "(", ")", ",", "entry", ".", "getName", "(", ")", ")", ";", "if", "(", "entry", ".", "isDirectory", "(", ")", ")", "{", "outputFile", ".", "mkdirs", "(", ")", ";", "}", "else", "{", "outputFile", ".", "getParentFile", "(", ")", ".", "mkdirs", "(", ")", ";", "try", "(", "FileOutputStream", "fileOut", "=", "new", "FileOutputStream", "(", "outputFile", ")", ")", "{", "IOUtils", ".", "copy", "(", "archiveStream", ",", "fileOut", ")", ";", "}", "}", "}", "}" ]
Reads a gzipped tar archive from a stream and writes it to the given path. @param dirPath the path to write the archive to @param input the input stream
[ "Reads", "a", "gzipped", "tar", "archive", "from", "a", "stream", "and", "writes", "it", "to", "the", "given", "path", "." ]
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/common/src/main/java/alluxio/util/TarUtils.java#L70-L85
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/io/file/PathHelper.java
PathHelper.getOutputStream
@Nullable public static OutputStream getOutputStream (@Nonnull final Path aFile) { """ Get an output stream for writing to a file. @param aFile The file to write to. May not be <code>null</code>. @return <code>null</code> if the file could not be opened """ return getOutputStream (aFile, EAppend.DEFAULT); }
java
@Nullable public static OutputStream getOutputStream (@Nonnull final Path aFile) { return getOutputStream (aFile, EAppend.DEFAULT); }
[ "@", "Nullable", "public", "static", "OutputStream", "getOutputStream", "(", "@", "Nonnull", "final", "Path", "aFile", ")", "{", "return", "getOutputStream", "(", "aFile", ",", "EAppend", ".", "DEFAULT", ")", ";", "}" ]
Get an output stream for writing to a file. @param aFile The file to write to. May not be <code>null</code>. @return <code>null</code> if the file could not be opened
[ "Get", "an", "output", "stream", "for", "writing", "to", "a", "file", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/io/file/PathHelper.java#L330-L334
reactiverse/reactive-pg-client
src/main/java/io/reactiverse/pgclient/impl/PgConnectionUriParser.java
PgConnectionUriParser.doParse
private static void doParse(String connectionUri, JsonObject configuration) { """ execute the parsing process and store options in the configuration """ Pattern pattern = Pattern.compile(FULL_URI_REGEX); Matcher matcher = pattern.matcher(connectionUri); if (matcher.matches()) { // parse the user and password parseUserandPassword(matcher.group(USER_INFO_GROUP), configuration); // parse the IP address/host/unix domainSocket address parseNetLocation(matcher.group(NET_LOCATION_GROUP), configuration); // parse the port parsePort(matcher.group(PORT_GROUP), configuration); // parse the database name parseDatabaseName(matcher.group(DATABASE_GROUP), configuration); // parse the parameters parseParameters(matcher.group(PARAMETER_GROUP), configuration); } else { throw new IllegalArgumentException("Wrong syntax of connection URI"); } }
java
private static void doParse(String connectionUri, JsonObject configuration) { Pattern pattern = Pattern.compile(FULL_URI_REGEX); Matcher matcher = pattern.matcher(connectionUri); if (matcher.matches()) { // parse the user and password parseUserandPassword(matcher.group(USER_INFO_GROUP), configuration); // parse the IP address/host/unix domainSocket address parseNetLocation(matcher.group(NET_LOCATION_GROUP), configuration); // parse the port parsePort(matcher.group(PORT_GROUP), configuration); // parse the database name parseDatabaseName(matcher.group(DATABASE_GROUP), configuration); // parse the parameters parseParameters(matcher.group(PARAMETER_GROUP), configuration); } else { throw new IllegalArgumentException("Wrong syntax of connection URI"); } }
[ "private", "static", "void", "doParse", "(", "String", "connectionUri", ",", "JsonObject", "configuration", ")", "{", "Pattern", "pattern", "=", "Pattern", ".", "compile", "(", "FULL_URI_REGEX", ")", ";", "Matcher", "matcher", "=", "pattern", ".", "matcher", "(", "connectionUri", ")", ";", "if", "(", "matcher", ".", "matches", "(", ")", ")", "{", "// parse the user and password", "parseUserandPassword", "(", "matcher", ".", "group", "(", "USER_INFO_GROUP", ")", ",", "configuration", ")", ";", "// parse the IP address/host/unix domainSocket address", "parseNetLocation", "(", "matcher", ".", "group", "(", "NET_LOCATION_GROUP", ")", ",", "configuration", ")", ";", "// parse the port", "parsePort", "(", "matcher", ".", "group", "(", "PORT_GROUP", ")", ",", "configuration", ")", ";", "// parse the database name", "parseDatabaseName", "(", "matcher", ".", "group", "(", "DATABASE_GROUP", ")", ",", "configuration", ")", ";", "// parse the parameters", "parseParameters", "(", "matcher", ".", "group", "(", "PARAMETER_GROUP", ")", ",", "configuration", ")", ";", "}", "else", "{", "throw", "new", "IllegalArgumentException", "(", "\"Wrong syntax of connection URI\"", ")", ";", "}", "}" ]
execute the parsing process and store options in the configuration
[ "execute", "the", "parsing", "process", "and", "store", "options", "in", "the", "configuration" ]
train
https://github.com/reactiverse/reactive-pg-client/blob/be75cc5462f0945f81d325f58db5f297403067bf/src/main/java/io/reactiverse/pgclient/impl/PgConnectionUriParser.java#L57-L80
iipc/webarchive-commons
src/main/java/org/archive/io/GenerationFileHandler.java
GenerationFileHandler.rotate
public GenerationFileHandler rotate(String storeSuffix, String activeSuffix) throws IOException { """ Move the current file to a new filename with the storeSuffix in place of the activeSuffix; continuing logging to a new file under the original filename. @param storeSuffix Suffix to put in place of <code>activeSuffix</code> @param activeSuffix Suffix to replace with <code>storeSuffix</code>. @return GenerationFileHandler instance. @throws IOException """ return rotate(storeSuffix, activeSuffix, false); }
java
public GenerationFileHandler rotate(String storeSuffix, String activeSuffix) throws IOException { return rotate(storeSuffix, activeSuffix, false); }
[ "public", "GenerationFileHandler", "rotate", "(", "String", "storeSuffix", ",", "String", "activeSuffix", ")", "throws", "IOException", "{", "return", "rotate", "(", "storeSuffix", ",", "activeSuffix", ",", "false", ")", ";", "}" ]
Move the current file to a new filename with the storeSuffix in place of the activeSuffix; continuing logging to a new file under the original filename. @param storeSuffix Suffix to put in place of <code>activeSuffix</code> @param activeSuffix Suffix to replace with <code>storeSuffix</code>. @return GenerationFileHandler instance. @throws IOException
[ "Move", "the", "current", "file", "to", "a", "new", "filename", "with", "the", "storeSuffix", "in", "place", "of", "the", "activeSuffix", ";", "continuing", "logging", "to", "a", "new", "file", "under", "the", "original", "filename", "." ]
train
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/io/GenerationFileHandler.java#L91-L95
hibernate/hibernate-ogm
infinispan-embedded/src/main/java/org/hibernate/ogm/datastore/infinispan/configuration/impl/InfinispanConfiguration.java
InfinispanConfiguration.initConfiguration
public void initConfiguration(Map<?, ?> configurationMap) { """ Initialize the internal values form the given {@link Map}. @param configurationMap The values to use as configuration """ ConfigurationPropertyReader propertyReader = new ConfigurationPropertyReader( configurationMap ); this.configUrl = propertyReader .property( InfinispanProperties.CONFIGURATION_RESOURCE_NAME, URL.class ) .withDefault( InfinispanConfiguration.class.getClassLoader().getResource( INFINISPAN_DEFAULT_CONFIG ) ) .getValue(); this.jndi = propertyReader .property( InfinispanProperties.CACHE_MANAGER_JNDI_NAME, String.class ) .getValue(); log.tracef( "Initializing Infinispan from configuration file at %1$s", configUrl ); }
java
public void initConfiguration(Map<?, ?> configurationMap) { ConfigurationPropertyReader propertyReader = new ConfigurationPropertyReader( configurationMap ); this.configUrl = propertyReader .property( InfinispanProperties.CONFIGURATION_RESOURCE_NAME, URL.class ) .withDefault( InfinispanConfiguration.class.getClassLoader().getResource( INFINISPAN_DEFAULT_CONFIG ) ) .getValue(); this.jndi = propertyReader .property( InfinispanProperties.CACHE_MANAGER_JNDI_NAME, String.class ) .getValue(); log.tracef( "Initializing Infinispan from configuration file at %1$s", configUrl ); }
[ "public", "void", "initConfiguration", "(", "Map", "<", "?", ",", "?", ">", "configurationMap", ")", "{", "ConfigurationPropertyReader", "propertyReader", "=", "new", "ConfigurationPropertyReader", "(", "configurationMap", ")", ";", "this", ".", "configUrl", "=", "propertyReader", ".", "property", "(", "InfinispanProperties", ".", "CONFIGURATION_RESOURCE_NAME", ",", "URL", ".", "class", ")", ".", "withDefault", "(", "InfinispanConfiguration", ".", "class", ".", "getClassLoader", "(", ")", ".", "getResource", "(", "INFINISPAN_DEFAULT_CONFIG", ")", ")", ".", "getValue", "(", ")", ";", "this", ".", "jndi", "=", "propertyReader", ".", "property", "(", "InfinispanProperties", ".", "CACHE_MANAGER_JNDI_NAME", ",", "String", ".", "class", ")", ".", "getValue", "(", ")", ";", "log", ".", "tracef", "(", "\"Initializing Infinispan from configuration file at %1$s\"", ",", "configUrl", ")", ";", "}" ]
Initialize the internal values form the given {@link Map}. @param configurationMap The values to use as configuration
[ "Initialize", "the", "internal", "values", "form", "the", "given", "{", "@link", "Map", "}", "." ]
train
https://github.com/hibernate/hibernate-ogm/blob/9ea971df7c27277029006a6f748d8272fb1d69d2/infinispan-embedded/src/main/java/org/hibernate/ogm/datastore/infinispan/configuration/impl/InfinispanConfiguration.java#L59-L72
phax/ph-commons
ph-dao/src/main/java/com/helger/dao/wal/AbstractWALDAO.java
AbstractWALDAO.markAsChanged
@MustBeLocked (ELockType.WRITE) @OverridingMethodsMustInvokeSuper protected void markAsChanged (@Nonnull final DATATYPE aModifiedElement, @Nonnull final EDAOActionType eActionType) { """ This method must be called every time something changed in the DAO. It triggers the writing to a file if auto-save is active. This method must be called within a write-lock as it is not locked! @param aModifiedElement The modified data element. May not be <code>null</code>. @param eActionType The action that was performed. May not be <code>null</code>. """ ValueEnforcer.notNull (aModifiedElement, "ModifiedElement"); ValueEnforcer.notNull (eActionType, "ActionType"); // Convert single item to list markAsChanged (new CommonsArrayList <> (aModifiedElement), eActionType); }
java
@MustBeLocked (ELockType.WRITE) @OverridingMethodsMustInvokeSuper protected void markAsChanged (@Nonnull final DATATYPE aModifiedElement, @Nonnull final EDAOActionType eActionType) { ValueEnforcer.notNull (aModifiedElement, "ModifiedElement"); ValueEnforcer.notNull (eActionType, "ActionType"); // Convert single item to list markAsChanged (new CommonsArrayList <> (aModifiedElement), eActionType); }
[ "@", "MustBeLocked", "(", "ELockType", ".", "WRITE", ")", "@", "OverridingMethodsMustInvokeSuper", "protected", "void", "markAsChanged", "(", "@", "Nonnull", "final", "DATATYPE", "aModifiedElement", ",", "@", "Nonnull", "final", "EDAOActionType", "eActionType", ")", "{", "ValueEnforcer", ".", "notNull", "(", "aModifiedElement", ",", "\"ModifiedElement\"", ")", ";", "ValueEnforcer", ".", "notNull", "(", "eActionType", ",", "\"ActionType\"", ")", ";", "// Convert single item to list", "markAsChanged", "(", "new", "CommonsArrayList", "<>", "(", "aModifiedElement", ")", ",", "eActionType", ")", ";", "}" ]
This method must be called every time something changed in the DAO. It triggers the writing to a file if auto-save is active. This method must be called within a write-lock as it is not locked! @param aModifiedElement The modified data element. May not be <code>null</code>. @param eActionType The action that was performed. May not be <code>null</code>.
[ "This", "method", "must", "be", "called", "every", "time", "something", "changed", "in", "the", "DAO", ".", "It", "triggers", "the", "writing", "to", "a", "file", "if", "auto", "-", "save", "is", "active", ".", "This", "method", "must", "be", "called", "within", "a", "write", "-", "lock", "as", "it", "is", "not", "locked!" ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-dao/src/main/java/com/helger/dao/wal/AbstractWALDAO.java#L1102-L1111
apache/incubator-gobblin
gobblin-core/src/main/java/org/apache/gobblin/config/ConfigBuilder.java
ConfigBuilder.loadProps
public ConfigBuilder loadProps(Properties props, String scopePrefix) { """ Loads properties which have a given name prefix into the config. The following restrictions apply: <ul> <li>No property can have a name that is equal to the prefix <li>After removal of the prefix, the remaining property name should start with a letter. </ul> @param props the collection from where to load the properties @param scopePrefix only properties with this prefix will be considered. The prefix will be removed from the names of the keys added to the {@link Config} object. The prefix can be an empty string but cannot be null. """ Preconditions.checkNotNull(props); Preconditions.checkNotNull(scopePrefix); int scopePrefixLen = scopePrefix.length(); for (Map.Entry<Object, Object> propEntry : props.entrySet()) { String propName = propEntry.getKey().toString(); if (propName.startsWith(scopePrefix)) { String scopedName = propName.substring(scopePrefixLen); if (scopedName.isEmpty()) { throw new RuntimeException("Illegal scoped property:" + propName); } if (!Character.isAlphabetic(scopedName.charAt(0))) { throw new RuntimeException( "Scoped name for property " + propName + " should start with a character: " + scopedName); } this.primitiveProps.put(scopedName, propEntry.getValue()); } } return this; }
java
public ConfigBuilder loadProps(Properties props, String scopePrefix) { Preconditions.checkNotNull(props); Preconditions.checkNotNull(scopePrefix); int scopePrefixLen = scopePrefix.length(); for (Map.Entry<Object, Object> propEntry : props.entrySet()) { String propName = propEntry.getKey().toString(); if (propName.startsWith(scopePrefix)) { String scopedName = propName.substring(scopePrefixLen); if (scopedName.isEmpty()) { throw new RuntimeException("Illegal scoped property:" + propName); } if (!Character.isAlphabetic(scopedName.charAt(0))) { throw new RuntimeException( "Scoped name for property " + propName + " should start with a character: " + scopedName); } this.primitiveProps.put(scopedName, propEntry.getValue()); } } return this; }
[ "public", "ConfigBuilder", "loadProps", "(", "Properties", "props", ",", "String", "scopePrefix", ")", "{", "Preconditions", ".", "checkNotNull", "(", "props", ")", ";", "Preconditions", ".", "checkNotNull", "(", "scopePrefix", ")", ";", "int", "scopePrefixLen", "=", "scopePrefix", ".", "length", "(", ")", ";", "for", "(", "Map", ".", "Entry", "<", "Object", ",", "Object", ">", "propEntry", ":", "props", ".", "entrySet", "(", ")", ")", "{", "String", "propName", "=", "propEntry", ".", "getKey", "(", ")", ".", "toString", "(", ")", ";", "if", "(", "propName", ".", "startsWith", "(", "scopePrefix", ")", ")", "{", "String", "scopedName", "=", "propName", ".", "substring", "(", "scopePrefixLen", ")", ";", "if", "(", "scopedName", ".", "isEmpty", "(", ")", ")", "{", "throw", "new", "RuntimeException", "(", "\"Illegal scoped property:\"", "+", "propName", ")", ";", "}", "if", "(", "!", "Character", ".", "isAlphabetic", "(", "scopedName", ".", "charAt", "(", "0", ")", ")", ")", "{", "throw", "new", "RuntimeException", "(", "\"Scoped name for property \"", "+", "propName", "+", "\" should start with a character: \"", "+", "scopedName", ")", ";", "}", "this", ".", "primitiveProps", ".", "put", "(", "scopedName", ",", "propEntry", ".", "getValue", "(", ")", ")", ";", "}", "}", "return", "this", ";", "}" ]
Loads properties which have a given name prefix into the config. The following restrictions apply: <ul> <li>No property can have a name that is equal to the prefix <li>After removal of the prefix, the remaining property name should start with a letter. </ul> @param props the collection from where to load the properties @param scopePrefix only properties with this prefix will be considered. The prefix will be removed from the names of the keys added to the {@link Config} object. The prefix can be an empty string but cannot be null.
[ "Loads", "properties", "which", "have", "a", "given", "name", "prefix", "into", "the", "config", ".", "The", "following", "restrictions", "apply", ":", "<ul", ">", "<li", ">", "No", "property", "can", "have", "a", "name", "that", "is", "equal", "to", "the", "prefix", "<li", ">", "After", "removal", "of", "the", "prefix", "the", "remaining", "property", "name", "should", "start", "with", "a", "letter", ".", "<", "/", "ul", ">" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core/src/main/java/org/apache/gobblin/config/ConfigBuilder.java#L56-L78
Abnaxos/markdown-doclet
doclet/jdk8/src/main/java/ch/raffael/mddoclet/mdtaglet/argval/PredefinedArgumentValidators.java
PredefinedArgumentValidators.inRange
public static ArgumentValidator inRange(int expectedMin, int expectedMax) { """ Creates a {@link ArgumentValidator} which checks for _expectedMin <= #arguments <= expectedMax_. @param expectedMin the minimum number of expected arguments @param expectedMax the maximum number of expected arguments @return an ArgumentValidator """ return inRange(expectedMin, expectedMax, MessageFormat.format("{0}..{1}",expectedMin, expectedMax)); }
java
public static ArgumentValidator inRange(int expectedMin, int expectedMax) { return inRange(expectedMin, expectedMax, MessageFormat.format("{0}..{1}",expectedMin, expectedMax)); }
[ "public", "static", "ArgumentValidator", "inRange", "(", "int", "expectedMin", ",", "int", "expectedMax", ")", "{", "return", "inRange", "(", "expectedMin", ",", "expectedMax", ",", "MessageFormat", ".", "format", "(", "\"{0}..{1}\"", ",", "expectedMin", ",", "expectedMax", ")", ")", ";", "}" ]
Creates a {@link ArgumentValidator} which checks for _expectedMin <= #arguments <= expectedMax_. @param expectedMin the minimum number of expected arguments @param expectedMax the maximum number of expected arguments @return an ArgumentValidator
[ "Creates", "a", "{", "@link", "ArgumentValidator", "}", "which", "checks", "for", "_expectedMin", "<", "=", "#arguments", "<", "=", "expectedMax_", "." ]
train
https://github.com/Abnaxos/markdown-doclet/blob/e98a9630206fc9c8d813cf2349ff594be8630054/doclet/jdk8/src/main/java/ch/raffael/mddoclet/mdtaglet/argval/PredefinedArgumentValidators.java#L215-L217
apache/flink
flink-runtime/src/main/java/org/apache/flink/runtime/metrics/groups/AbstractMetricGroup.java
AbstractMetricGroup.getMetricIdentifier
public String getMetricIdentifier(String metricName, CharacterFilter filter, int reporterIndex) { """ Returns the fully qualified metric name using the configured delimiter for the reporter with the given index, for example {@code "host-7.taskmanager-2.window_word_count.my-mapper.metricName"}. @param metricName metric name @param filter character filter which is applied to the scope components if not null. @param reporterIndex index of the reporter whose delimiter should be used @return fully qualified metric name """ if (scopeStrings.length == 0 || (reporterIndex < 0 || reporterIndex >= scopeStrings.length)) { char delimiter = registry.getDelimiter(); String newScopeString; if (filter != null) { newScopeString = ScopeFormat.concat(filter, delimiter, scopeComponents); metricName = filter.filterCharacters(metricName); } else { newScopeString = ScopeFormat.concat(delimiter, scopeComponents); } return newScopeString + delimiter + metricName; } else { char delimiter = registry.getDelimiter(reporterIndex); if (scopeStrings[reporterIndex] == null) { if (filter != null) { scopeStrings[reporterIndex] = ScopeFormat.concat(filter, delimiter, scopeComponents); } else { scopeStrings[reporterIndex] = ScopeFormat.concat(delimiter, scopeComponents); } } if (filter != null) { metricName = filter.filterCharacters(metricName); } return scopeStrings[reporterIndex] + delimiter + metricName; } }
java
public String getMetricIdentifier(String metricName, CharacterFilter filter, int reporterIndex) { if (scopeStrings.length == 0 || (reporterIndex < 0 || reporterIndex >= scopeStrings.length)) { char delimiter = registry.getDelimiter(); String newScopeString; if (filter != null) { newScopeString = ScopeFormat.concat(filter, delimiter, scopeComponents); metricName = filter.filterCharacters(metricName); } else { newScopeString = ScopeFormat.concat(delimiter, scopeComponents); } return newScopeString + delimiter + metricName; } else { char delimiter = registry.getDelimiter(reporterIndex); if (scopeStrings[reporterIndex] == null) { if (filter != null) { scopeStrings[reporterIndex] = ScopeFormat.concat(filter, delimiter, scopeComponents); } else { scopeStrings[reporterIndex] = ScopeFormat.concat(delimiter, scopeComponents); } } if (filter != null) { metricName = filter.filterCharacters(metricName); } return scopeStrings[reporterIndex] + delimiter + metricName; } }
[ "public", "String", "getMetricIdentifier", "(", "String", "metricName", ",", "CharacterFilter", "filter", ",", "int", "reporterIndex", ")", "{", "if", "(", "scopeStrings", ".", "length", "==", "0", "||", "(", "reporterIndex", "<", "0", "||", "reporterIndex", ">=", "scopeStrings", ".", "length", ")", ")", "{", "char", "delimiter", "=", "registry", ".", "getDelimiter", "(", ")", ";", "String", "newScopeString", ";", "if", "(", "filter", "!=", "null", ")", "{", "newScopeString", "=", "ScopeFormat", ".", "concat", "(", "filter", ",", "delimiter", ",", "scopeComponents", ")", ";", "metricName", "=", "filter", ".", "filterCharacters", "(", "metricName", ")", ";", "}", "else", "{", "newScopeString", "=", "ScopeFormat", ".", "concat", "(", "delimiter", ",", "scopeComponents", ")", ";", "}", "return", "newScopeString", "+", "delimiter", "+", "metricName", ";", "}", "else", "{", "char", "delimiter", "=", "registry", ".", "getDelimiter", "(", "reporterIndex", ")", ";", "if", "(", "scopeStrings", "[", "reporterIndex", "]", "==", "null", ")", "{", "if", "(", "filter", "!=", "null", ")", "{", "scopeStrings", "[", "reporterIndex", "]", "=", "ScopeFormat", ".", "concat", "(", "filter", ",", "delimiter", ",", "scopeComponents", ")", ";", "}", "else", "{", "scopeStrings", "[", "reporterIndex", "]", "=", "ScopeFormat", ".", "concat", "(", "delimiter", ",", "scopeComponents", ")", ";", "}", "}", "if", "(", "filter", "!=", "null", ")", "{", "metricName", "=", "filter", ".", "filterCharacters", "(", "metricName", ")", ";", "}", "return", "scopeStrings", "[", "reporterIndex", "]", "+", "delimiter", "+", "metricName", ";", "}", "}" ]
Returns the fully qualified metric name using the configured delimiter for the reporter with the given index, for example {@code "host-7.taskmanager-2.window_word_count.my-mapper.metricName"}. @param metricName metric name @param filter character filter which is applied to the scope components if not null. @param reporterIndex index of the reporter whose delimiter should be used @return fully qualified metric name
[ "Returns", "the", "fully", "qualified", "metric", "name", "using", "the", "configured", "delimiter", "for", "the", "reporter", "with", "the", "given", "index", "for", "example", "{", "@code", "host", "-", "7", ".", "taskmanager", "-", "2", ".", "window_word_count", ".", "my", "-", "mapper", ".", "metricName", "}", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/metrics/groups/AbstractMetricGroup.java#L253-L278
landawn/AbacusUtil
src/com/landawn/abacus/util/StringUtil.java
StringUtil.removeEndIgnoreCase
public static String removeEndIgnoreCase(final String str, final String removeStr) { """ <p> Case insensitive removal of a substring if it is at the end of a source string, otherwise returns the source string. </p> <p> A {@code null} source string will return {@code null}. An empty ("") source string will return the empty string. A {@code null} search string will return the source string. </p> <pre> N.removeEndIgnoreCase(null, *) = null N.removeEndIgnoreCase("", *) = "" N.removeEndIgnoreCase(*, null) = * N.removeEndIgnoreCase("www.domain.com", ".com.") = "www.domain.com" N.removeEndIgnoreCase("www.domain.com", ".com") = "www.domain" N.removeEndIgnoreCase("www.domain.com", "domain") = "www.domain.com" N.removeEndIgnoreCase("abc", "") = "abc" N.removeEndIgnoreCase("www.domain.com", ".COM") = "www.domain") N.removeEndIgnoreCase("www.domain.COM", ".com") = "www.domain") </pre> @param str the source String to search, may be null @param removeStr the String to search for (case insensitive) and remove, may be null @return the substring with the string removed if found, {@code null} if null String input @since 2.4 """ if (N.isNullOrEmpty(str) || N.isNullOrEmpty(removeStr)) { return str; } if (endsWithIgnoreCase(str, removeStr)) { return str.substring(0, str.length() - removeStr.length()); } return str; }
java
public static String removeEndIgnoreCase(final String str, final String removeStr) { if (N.isNullOrEmpty(str) || N.isNullOrEmpty(removeStr)) { return str; } if (endsWithIgnoreCase(str, removeStr)) { return str.substring(0, str.length() - removeStr.length()); } return str; }
[ "public", "static", "String", "removeEndIgnoreCase", "(", "final", "String", "str", ",", "final", "String", "removeStr", ")", "{", "if", "(", "N", ".", "isNullOrEmpty", "(", "str", ")", "||", "N", ".", "isNullOrEmpty", "(", "removeStr", ")", ")", "{", "return", "str", ";", "}", "if", "(", "endsWithIgnoreCase", "(", "str", ",", "removeStr", ")", ")", "{", "return", "str", ".", "substring", "(", "0", ",", "str", ".", "length", "(", ")", "-", "removeStr", ".", "length", "(", ")", ")", ";", "}", "return", "str", ";", "}" ]
<p> Case insensitive removal of a substring if it is at the end of a source string, otherwise returns the source string. </p> <p> A {@code null} source string will return {@code null}. An empty ("") source string will return the empty string. A {@code null} search string will return the source string. </p> <pre> N.removeEndIgnoreCase(null, *) = null N.removeEndIgnoreCase("", *) = "" N.removeEndIgnoreCase(*, null) = * N.removeEndIgnoreCase("www.domain.com", ".com.") = "www.domain.com" N.removeEndIgnoreCase("www.domain.com", ".com") = "www.domain" N.removeEndIgnoreCase("www.domain.com", "domain") = "www.domain.com" N.removeEndIgnoreCase("abc", "") = "abc" N.removeEndIgnoreCase("www.domain.com", ".COM") = "www.domain") N.removeEndIgnoreCase("www.domain.COM", ".com") = "www.domain") </pre> @param str the source String to search, may be null @param removeStr the String to search for (case insensitive) and remove, may be null @return the substring with the string removed if found, {@code null} if null String input @since 2.4
[ "<p", ">", "Case", "insensitive", "removal", "of", "a", "substring", "if", "it", "is", "at", "the", "end", "of", "a", "source", "string", "otherwise", "returns", "the", "source", "string", ".", "<", "/", "p", ">" ]
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/StringUtil.java#L1278-L1288
mockito/mockito
src/main/java/org/mockito/internal/configuration/plugins/PluginInitializer.java
PluginInitializer.loadImpl
public <T> T loadImpl(Class<T> service) { """ Equivalent to {@link java.util.ServiceLoader#load} but without requiring Java 6 / Android 2.3 (Gingerbread). """ ClassLoader loader = Thread.currentThread().getContextClassLoader(); if (loader == null) { loader = ClassLoader.getSystemClassLoader(); } Enumeration<URL> resources; try { resources = loader.getResources("mockito-extensions/" + service.getName()); } catch (IOException e) { throw new IllegalStateException("Failed to load " + service, e); } try { String classOrAlias = new PluginFinder(pluginSwitch).findPluginClass(Iterables.toIterable(resources)); if (classOrAlias != null) { if (classOrAlias.equals(alias)) { classOrAlias = plugins.getDefaultPluginClass(alias); } Class<?> pluginClass = loader.loadClass(classOrAlias); Object plugin = pluginClass.newInstance(); return service.cast(plugin); } return null; } catch (Exception e) { throw new IllegalStateException( "Failed to load " + service + " implementation declared in " + resources, e); } }
java
public <T> T loadImpl(Class<T> service) { ClassLoader loader = Thread.currentThread().getContextClassLoader(); if (loader == null) { loader = ClassLoader.getSystemClassLoader(); } Enumeration<URL> resources; try { resources = loader.getResources("mockito-extensions/" + service.getName()); } catch (IOException e) { throw new IllegalStateException("Failed to load " + service, e); } try { String classOrAlias = new PluginFinder(pluginSwitch).findPluginClass(Iterables.toIterable(resources)); if (classOrAlias != null) { if (classOrAlias.equals(alias)) { classOrAlias = plugins.getDefaultPluginClass(alias); } Class<?> pluginClass = loader.loadClass(classOrAlias); Object plugin = pluginClass.newInstance(); return service.cast(plugin); } return null; } catch (Exception e) { throw new IllegalStateException( "Failed to load " + service + " implementation declared in " + resources, e); } }
[ "public", "<", "T", ">", "T", "loadImpl", "(", "Class", "<", "T", ">", "service", ")", "{", "ClassLoader", "loader", "=", "Thread", ".", "currentThread", "(", ")", ".", "getContextClassLoader", "(", ")", ";", "if", "(", "loader", "==", "null", ")", "{", "loader", "=", "ClassLoader", ".", "getSystemClassLoader", "(", ")", ";", "}", "Enumeration", "<", "URL", ">", "resources", ";", "try", "{", "resources", "=", "loader", ".", "getResources", "(", "\"mockito-extensions/\"", "+", "service", ".", "getName", "(", ")", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Failed to load \"", "+", "service", ",", "e", ")", ";", "}", "try", "{", "String", "classOrAlias", "=", "new", "PluginFinder", "(", "pluginSwitch", ")", ".", "findPluginClass", "(", "Iterables", ".", "toIterable", "(", "resources", ")", ")", ";", "if", "(", "classOrAlias", "!=", "null", ")", "{", "if", "(", "classOrAlias", ".", "equals", "(", "alias", ")", ")", "{", "classOrAlias", "=", "plugins", ".", "getDefaultPluginClass", "(", "alias", ")", ";", "}", "Class", "<", "?", ">", "pluginClass", "=", "loader", ".", "loadClass", "(", "classOrAlias", ")", ";", "Object", "plugin", "=", "pluginClass", ".", "newInstance", "(", ")", ";", "return", "service", ".", "cast", "(", "plugin", ")", ";", "}", "return", "null", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Failed to load \"", "+", "service", "+", "\" implementation declared in \"", "+", "resources", ",", "e", ")", ";", "}", "}" ]
Equivalent to {@link java.util.ServiceLoader#load} but without requiring Java 6 / Android 2.3 (Gingerbread).
[ "Equivalent", "to", "{" ]
train
https://github.com/mockito/mockito/blob/c5e2b80af76e3192cae7c9550b70c4d1ab312034/src/main/java/org/mockito/internal/configuration/plugins/PluginInitializer.java#L30-L57
santhosh-tekuri/jlibs
core/src/main/java/jlibs/core/lang/BeanUtil.java
BeanUtil.getGetterMethod
public static Method getGetterMethod(Class<?> beanClass, String property, Class propertyType) { """ Returns getter method for <code>property</code> in specified <code>beanClass</code> @param beanClass bean class @param property name of the property @param propertyType type of the property. This is used to compute getter method name. @return getter method. null if <code>property</code> is not found @see #getGetterMethod(Class, String) """ try{ try{ if(propertyType==boolean.class) return beanClass.getMethod(IS+getMethodSuffix(property)); }catch(NoSuchMethodException ignore){ // ignore } return beanClass.getMethod(GET+getMethodSuffix(property)); }catch(NoSuchMethodException ex){ return null; } }
java
public static Method getGetterMethod(Class<?> beanClass, String property, Class propertyType){ try{ try{ if(propertyType==boolean.class) return beanClass.getMethod(IS+getMethodSuffix(property)); }catch(NoSuchMethodException ignore){ // ignore } return beanClass.getMethod(GET+getMethodSuffix(property)); }catch(NoSuchMethodException ex){ return null; } }
[ "public", "static", "Method", "getGetterMethod", "(", "Class", "<", "?", ">", "beanClass", ",", "String", "property", ",", "Class", "propertyType", ")", "{", "try", "{", "try", "{", "if", "(", "propertyType", "==", "boolean", ".", "class", ")", "return", "beanClass", ".", "getMethod", "(", "IS", "+", "getMethodSuffix", "(", "property", ")", ")", ";", "}", "catch", "(", "NoSuchMethodException", "ignore", ")", "{", "// ignore", "}", "return", "beanClass", ".", "getMethod", "(", "GET", "+", "getMethodSuffix", "(", "property", ")", ")", ";", "}", "catch", "(", "NoSuchMethodException", "ex", ")", "{", "return", "null", ";", "}", "}" ]
Returns getter method for <code>property</code> in specified <code>beanClass</code> @param beanClass bean class @param property name of the property @param propertyType type of the property. This is used to compute getter method name. @return getter method. null if <code>property</code> is not found @see #getGetterMethod(Class, String)
[ "Returns", "getter", "method", "for", "<code", ">", "property<", "/", "code", ">", "in", "specified", "<code", ">", "beanClass<", "/", "code", ">" ]
train
https://github.com/santhosh-tekuri/jlibs/blob/59c28719f054123cf778278154e1b92e943ad232/core/src/main/java/jlibs/core/lang/BeanUtil.java#L120-L132
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/util/JsonUtil.java
JsonUtil.getString
public static String getString(JsonObject object, String field, String defaultValue) { """ Returns a field in a Json object as a string. @param object the Json Object @param field the field in the Json object to return @param defaultValue a default value for the field if the field value is null @return the Json field value as a string """ final JsonValue value = object.get(field); if (value == null || value.isNull()) { return defaultValue; } else { return value.asString(); } }
java
public static String getString(JsonObject object, String field, String defaultValue) { final JsonValue value = object.get(field); if (value == null || value.isNull()) { return defaultValue; } else { return value.asString(); } }
[ "public", "static", "String", "getString", "(", "JsonObject", "object", ",", "String", "field", ",", "String", "defaultValue", ")", "{", "final", "JsonValue", "value", "=", "object", ".", "get", "(", "field", ")", ";", "if", "(", "value", "==", "null", "||", "value", ".", "isNull", "(", ")", ")", "{", "return", "defaultValue", ";", "}", "else", "{", "return", "value", ".", "asString", "(", ")", ";", "}", "}" ]
Returns a field in a Json object as a string. @param object the Json Object @param field the field in the Json object to return @param defaultValue a default value for the field if the field value is null @return the Json field value as a string
[ "Returns", "a", "field", "in", "a", "Json", "object", "as", "a", "string", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/util/JsonUtil.java#L182-L189
spotbugs/spotbugs
spotbugs/src/main/java/edu/umd/cs/findbugs/SourceLineAnnotation.java
SourceLineAnnotation.createUnknown
@Nonnull public static SourceLineAnnotation createUnknown(@DottedClassName String className, String sourceFile, int startBytecode, int endBytecode) { """ Factory method to create an unknown source line annotation. This variant is used when bytecode offsets are known, but not source lines. @param className the class name @param sourceFile the source file name @return the SourceLineAnnotation """ SourceLineAnnotation result = new SourceLineAnnotation(className, sourceFile, -1, -1, startBytecode, endBytecode); // result.setDescription("SOURCE_LINE_UNKNOWN"); return result; }
java
@Nonnull public static SourceLineAnnotation createUnknown(@DottedClassName String className, String sourceFile, int startBytecode, int endBytecode) { SourceLineAnnotation result = new SourceLineAnnotation(className, sourceFile, -1, -1, startBytecode, endBytecode); // result.setDescription("SOURCE_LINE_UNKNOWN"); return result; }
[ "@", "Nonnull", "public", "static", "SourceLineAnnotation", "createUnknown", "(", "@", "DottedClassName", "String", "className", ",", "String", "sourceFile", ",", "int", "startBytecode", ",", "int", "endBytecode", ")", "{", "SourceLineAnnotation", "result", "=", "new", "SourceLineAnnotation", "(", "className", ",", "sourceFile", ",", "-", "1", ",", "-", "1", ",", "startBytecode", ",", "endBytecode", ")", ";", "// result.setDescription(\"SOURCE_LINE_UNKNOWN\");", "return", "result", ";", "}" ]
Factory method to create an unknown source line annotation. This variant is used when bytecode offsets are known, but not source lines. @param className the class name @param sourceFile the source file name @return the SourceLineAnnotation
[ "Factory", "method", "to", "create", "an", "unknown", "source", "line", "annotation", ".", "This", "variant", "is", "used", "when", "bytecode", "offsets", "are", "known", "but", "not", "source", "lines", "." ]
train
https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/SourceLineAnnotation.java#L206-L211
JodaOrg/joda-money
src/main/java/org/joda/money/BigMoney.java
BigMoney.ofMinor
public static BigMoney ofMinor(CurrencyUnit currency, long amountMinor) { """ Obtains an instance of {@code BigMoney} from an amount in minor units. <p> This allows you to create an instance with a specific currency and amount expressed in terms of the minor unit. The scale of the money will be that of the currency, such as 2 for USD or 0 for JPY. <p> For example, if constructing US Dollars, the input to this method represents cents. Note that when a currency has zero decimal places, the major and minor units are the same. For example, {@code ofMinor(USD, 2595)} creates the instance {@code USD 25.95}. @param currency the currency, not null @param amountMinor the amount of money in the minor division of the currency @return the new instance, never null """ MoneyUtils.checkNotNull(currency, "CurrencyUnit must not be null"); return BigMoney.of(currency, BigDecimal.valueOf(amountMinor, currency.getDecimalPlaces())); }
java
public static BigMoney ofMinor(CurrencyUnit currency, long amountMinor) { MoneyUtils.checkNotNull(currency, "CurrencyUnit must not be null"); return BigMoney.of(currency, BigDecimal.valueOf(amountMinor, currency.getDecimalPlaces())); }
[ "public", "static", "BigMoney", "ofMinor", "(", "CurrencyUnit", "currency", ",", "long", "amountMinor", ")", "{", "MoneyUtils", ".", "checkNotNull", "(", "currency", ",", "\"CurrencyUnit must not be null\"", ")", ";", "return", "BigMoney", ".", "of", "(", "currency", ",", "BigDecimal", ".", "valueOf", "(", "amountMinor", ",", "currency", ".", "getDecimalPlaces", "(", ")", ")", ")", ";", "}" ]
Obtains an instance of {@code BigMoney} from an amount in minor units. <p> This allows you to create an instance with a specific currency and amount expressed in terms of the minor unit. The scale of the money will be that of the currency, such as 2 for USD or 0 for JPY. <p> For example, if constructing US Dollars, the input to this method represents cents. Note that when a currency has zero decimal places, the major and minor units are the same. For example, {@code ofMinor(USD, 2595)} creates the instance {@code USD 25.95}. @param currency the currency, not null @param amountMinor the amount of money in the minor division of the currency @return the new instance, never null
[ "Obtains", "an", "instance", "of", "{", "@code", "BigMoney", "}", "from", "an", "amount", "in", "minor", "units", ".", "<p", ">", "This", "allows", "you", "to", "create", "an", "instance", "with", "a", "specific", "currency", "and", "amount", "expressed", "in", "terms", "of", "the", "minor", "unit", ".", "The", "scale", "of", "the", "money", "will", "be", "that", "of", "the", "currency", "such", "as", "2", "for", "USD", "or", "0", "for", "JPY", ".", "<p", ">", "For", "example", "if", "constructing", "US", "Dollars", "the", "input", "to", "this", "method", "represents", "cents", ".", "Note", "that", "when", "a", "currency", "has", "zero", "decimal", "places", "the", "major", "and", "minor", "units", "are", "the", "same", ".", "For", "example", "{", "@code", "ofMinor", "(", "USD", "2595", ")", "}", "creates", "the", "instance", "{", "@code", "USD", "25", ".", "95", "}", "." ]
train
https://github.com/JodaOrg/joda-money/blob/e1f2de75aa36610a695358696c8a88a18ca66cde/src/main/java/org/joda/money/BigMoney.java#L213-L216
adobe/htl-tck
src/main/java/io/sightly/tck/html/HTMLExtractor.java
HTMLExtractor.hasAttributeValue
public static boolean hasAttributeValue(String url, String markup, String selector, String attributeName, String attributeValue) { """ Checks if any of the elements matched by the {@code selector} contain the attribute {@code attributeName} with value {@code attributeValue}. The {@code url} is used only for caching purposes, to avoid parsing multiple times the markup returned for the same resource. @param url the url that identifies the markup @param markup the markup @param selector the selector used for retrieval @param attributeName the attribute's name @param attributeValue the attribute's value @return {@code true} if the attribute was found and has the specified value, {@code false} otherwise """ ensureMarkup(url, markup); Document document = documents.get(url); Elements elements = document.select(selector); return !elements.isEmpty() && elements.hasAttr(attributeName) && attributeValue.equals(elements.attr(attributeName)); }
java
public static boolean hasAttributeValue(String url, String markup, String selector, String attributeName, String attributeValue) { ensureMarkup(url, markup); Document document = documents.get(url); Elements elements = document.select(selector); return !elements.isEmpty() && elements.hasAttr(attributeName) && attributeValue.equals(elements.attr(attributeName)); }
[ "public", "static", "boolean", "hasAttributeValue", "(", "String", "url", ",", "String", "markup", ",", "String", "selector", ",", "String", "attributeName", ",", "String", "attributeValue", ")", "{", "ensureMarkup", "(", "url", ",", "markup", ")", ";", "Document", "document", "=", "documents", ".", "get", "(", "url", ")", ";", "Elements", "elements", "=", "document", ".", "select", "(", "selector", ")", ";", "return", "!", "elements", ".", "isEmpty", "(", ")", "&&", "elements", ".", "hasAttr", "(", "attributeName", ")", "&&", "attributeValue", ".", "equals", "(", "elements", ".", "attr", "(", "attributeName", ")", ")", ";", "}" ]
Checks if any of the elements matched by the {@code selector} contain the attribute {@code attributeName} with value {@code attributeValue}. The {@code url} is used only for caching purposes, to avoid parsing multiple times the markup returned for the same resource. @param url the url that identifies the markup @param markup the markup @param selector the selector used for retrieval @param attributeName the attribute's name @param attributeValue the attribute's value @return {@code true} if the attribute was found and has the specified value, {@code false} otherwise
[ "Checks", "if", "any", "of", "the", "elements", "matched", "by", "the", "{", "@code", "selector", "}", "contain", "the", "attribute", "{", "@code", "attributeName", "}", "with", "value", "{", "@code", "attributeValue", "}", ".", "The", "{", "@code", "url", "}", "is", "used", "only", "for", "caching", "purposes", "to", "avoid", "parsing", "multiple", "times", "the", "markup", "returned", "for", "the", "same", "resource", "." ]
train
https://github.com/adobe/htl-tck/blob/2043a9616083c06cefbd685798c9a2b2ac2ea98e/src/main/java/io/sightly/tck/html/HTMLExtractor.java#L109-L114
JoeKerouac/utils
src/main/java/com/joe/utils/reflect/ReflectUtil.java
ReflectUtil.getMethod
public static Method getMethod(Class<?> clazz, String methodName, Class<?>... parameterTypes) { """ 获取指定类型中指定的方法(无法获取本类未覆写过的父类方法) @param clazz 类型 @param methodName 方法名 @param parameterTypes 方法参数类型 @return 指定方法,获取不到时会抛出异常 """ Assert.notNull(clazz, "类型不能为空"); Assert.notNull(methodName, "方法名不能为空"); return METHOD_CACHE.compute(new MethodKey(methodName, clazz, parameterTypes), (k, v) -> { if (v == null) { try { return allowAccess(clazz.getDeclaredMethod(methodName, parameterTypes)); } catch (NoSuchMethodException e) { log.error( StringUtils.format("类[{0}]中不存在方法名为[{1}]、方法列表为[{2}]的方法", clazz, methodName, parameterTypes == null ? "null" : Arrays.toString(parameterTypes))); throw new ReflectException( StringUtils.format("类[{0}]中不存在方法名为[{1}]、方法列表为[{2}]的方法", clazz, methodName, parameterTypes == null ? "null" : Arrays.toString(parameterTypes)), e); } } else { return v; } }); }
java
public static Method getMethod(Class<?> clazz, String methodName, Class<?>... parameterTypes) { Assert.notNull(clazz, "类型不能为空"); Assert.notNull(methodName, "方法名不能为空"); return METHOD_CACHE.compute(new MethodKey(methodName, clazz, parameterTypes), (k, v) -> { if (v == null) { try { return allowAccess(clazz.getDeclaredMethod(methodName, parameterTypes)); } catch (NoSuchMethodException e) { log.error( StringUtils.format("类[{0}]中不存在方法名为[{1}]、方法列表为[{2}]的方法", clazz, methodName, parameterTypes == null ? "null" : Arrays.toString(parameterTypes))); throw new ReflectException( StringUtils.format("类[{0}]中不存在方法名为[{1}]、方法列表为[{2}]的方法", clazz, methodName, parameterTypes == null ? "null" : Arrays.toString(parameterTypes)), e); } } else { return v; } }); }
[ "public", "static", "Method", "getMethod", "(", "Class", "<", "?", ">", "clazz", ",", "String", "methodName", ",", "Class", "<", "?", ">", "...", "parameterTypes", ")", "{", "Assert", ".", "notNull", "(", "clazz", ",", "\"类型不能为空\");", "", "", "Assert", ".", "notNull", "(", "methodName", ",", "\"方法名不能为空\");", "", "", "return", "METHOD_CACHE", ".", "compute", "(", "new", "MethodKey", "(", "methodName", ",", "clazz", ",", "parameterTypes", ")", ",", "(", "k", ",", "v", ")", "->", "{", "if", "(", "v", "==", "null", ")", "{", "try", "{", "return", "allowAccess", "(", "clazz", ".", "getDeclaredMethod", "(", "methodName", ",", "parameterTypes", ")", ")", ";", "}", "catch", "(", "NoSuchMethodException", "e", ")", "{", "log", ".", "error", "(", "StringUtils", ".", "format", "(", "\"类[{0}]中不存在方法名为[{1}]、方法列表为[{2}]的方法\", clazz, methodName,", "", "", "", "", "", "parameterTypes", "==", "null", "?", "\"null\"", ":", "Arrays", ".", "toString", "(", "parameterTypes", ")", ")", ")", ";", "throw", "new", "ReflectException", "(", "StringUtils", ".", "format", "(", "\"类[{0}]中不存在方法名为[{1}]、方法列表为[{2}]的方法\", clazz, methodName,", "", "", "", "", "", "parameterTypes", "==", "null", "?", "\"null\"", ":", "Arrays", ".", "toString", "(", "parameterTypes", ")", ")", ",", "e", ")", ";", "}", "}", "else", "{", "return", "v", ";", "}", "}", ")", ";", "}" ]
获取指定类型中指定的方法(无法获取本类未覆写过的父类方法) @param clazz 类型 @param methodName 方法名 @param parameterTypes 方法参数类型 @return 指定方法,获取不到时会抛出异常
[ "获取指定类型中指定的方法(无法获取本类未覆写过的父类方法)" ]
train
https://github.com/JoeKerouac/utils/blob/45e1b2dc4d736956674fc4dcbe6cf84eaee69278/src/main/java/com/joe/utils/reflect/ReflectUtil.java#L214-L235
epierce/cas-server-extension-token
src/main/java/edu/clayton/cas/support/token/util/Crypto.java
Crypto.decryptEncodedStringWithKey
public static String decryptEncodedStringWithKey(String string, Key key) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException { """ Decrypts a {@link Base64} encoded encrypted string. @param string The encoded string to decrypt. @param key The {@link Key} to use for decryption. @return The decrypted string. @throws NoSuchPaddingException @throws NoSuchAlgorithmException @throws InvalidKeyException @throws BadPaddingException @throws IllegalBlockSizeException """ String decryptedString; log.debug("Base64 string = `{}`", string); byte[] decryptedStringData; byte[] rawData = Base64.decodeBase64(string); byte[] iv = new byte[16]; byte[] cipherText = new byte[rawData.length - iv.length]; System.arraycopy(rawData, 0, iv, 0, 16); System.arraycopy(rawData, 16, cipherText, 0, cipherText.length); log.debug("iv = `{}`", Crypto.toHex(iv)); log.debug("cipherText.length = `{}`", cipherText.length); log.debug("cipherText = \n{}", Crypto.toHex(cipherText)); SecretKeySpec skey = new SecretKeySpec(key.data(), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, skey, new IvParameterSpec(iv)); decryptedStringData = cipher.doFinal(cipherText); decryptedString = new String(decryptedStringData); return decryptedString; }
java
public static String decryptEncodedStringWithKey(String string, Key key) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException { String decryptedString; log.debug("Base64 string = `{}`", string); byte[] decryptedStringData; byte[] rawData = Base64.decodeBase64(string); byte[] iv = new byte[16]; byte[] cipherText = new byte[rawData.length - iv.length]; System.arraycopy(rawData, 0, iv, 0, 16); System.arraycopy(rawData, 16, cipherText, 0, cipherText.length); log.debug("iv = `{}`", Crypto.toHex(iv)); log.debug("cipherText.length = `{}`", cipherText.length); log.debug("cipherText = \n{}", Crypto.toHex(cipherText)); SecretKeySpec skey = new SecretKeySpec(key.data(), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, skey, new IvParameterSpec(iv)); decryptedStringData = cipher.doFinal(cipherText); decryptedString = new String(decryptedStringData); return decryptedString; }
[ "public", "static", "String", "decryptEncodedStringWithKey", "(", "String", "string", ",", "Key", "key", ")", "throws", "NoSuchPaddingException", ",", "NoSuchAlgorithmException", ",", "InvalidKeyException", ",", "BadPaddingException", ",", "IllegalBlockSizeException", ",", "InvalidAlgorithmParameterException", "{", "String", "decryptedString", ";", "log", ".", "debug", "(", "\"Base64 string = `{}`\"", ",", "string", ")", ";", "byte", "[", "]", "decryptedStringData", ";", "byte", "[", "]", "rawData", "=", "Base64", ".", "decodeBase64", "(", "string", ")", ";", "byte", "[", "]", "iv", "=", "new", "byte", "[", "16", "]", ";", "byte", "[", "]", "cipherText", "=", "new", "byte", "[", "rawData", ".", "length", "-", "iv", ".", "length", "]", ";", "System", ".", "arraycopy", "(", "rawData", ",", "0", ",", "iv", ",", "0", ",", "16", ")", ";", "System", ".", "arraycopy", "(", "rawData", ",", "16", ",", "cipherText", ",", "0", ",", "cipherText", ".", "length", ")", ";", "log", ".", "debug", "(", "\"iv = `{}`\"", ",", "Crypto", ".", "toHex", "(", "iv", ")", ")", ";", "log", ".", "debug", "(", "\"cipherText.length = `{}`\"", ",", "cipherText", ".", "length", ")", ";", "log", ".", "debug", "(", "\"cipherText = \\n{}\"", ",", "Crypto", ".", "toHex", "(", "cipherText", ")", ")", ";", "SecretKeySpec", "skey", "=", "new", "SecretKeySpec", "(", "key", ".", "data", "(", ")", ",", "\"AES\"", ")", ";", "Cipher", "cipher", "=", "Cipher", ".", "getInstance", "(", "\"AES/CBC/PKCS5Padding\"", ")", ";", "cipher", ".", "init", "(", "Cipher", ".", "DECRYPT_MODE", ",", "skey", ",", "new", "IvParameterSpec", "(", "iv", ")", ")", ";", "decryptedStringData", "=", "cipher", ".", "doFinal", "(", "cipherText", ")", ";", "decryptedString", "=", "new", "String", "(", "decryptedStringData", ")", ";", "return", "decryptedString", ";", "}" ]
Decrypts a {@link Base64} encoded encrypted string. @param string The encoded string to decrypt. @param key The {@link Key} to use for decryption. @return The decrypted string. @throws NoSuchPaddingException @throws NoSuchAlgorithmException @throws InvalidKeyException @throws BadPaddingException @throws IllegalBlockSizeException
[ "Decrypts", "a", "{", "@link", "Base64", "}", "encoded", "encrypted", "string", "." ]
train
https://github.com/epierce/cas-server-extension-token/blob/b63399e6b516a25f624d09161466db87fcec974b/src/main/java/edu/clayton/cas/support/token/util/Crypto.java#L136-L166
facebookarchive/hadoop-20
src/core/org/apache/hadoop/io/DataTransferHeaderOptions.java
DataTransferHeaderOptions.setBits
protected static long setBits(long num, int start, int len, long value) { """ Sets specific bits of a specific number. @param num The number to set bits. @param start Index of the rightmost bit we want to set. 0-based. @param len How many bits we want to set. @param value The value we want to set to. @return The number after changing specific bits. """ // Get rid of illegal bits of value: value = value & ((1L<<len)-1); long val_mask = value << start; long zero_mask = ~( ((1L << len) -1) << start ); return ( num & zero_mask ) | val_mask; }
java
protected static long setBits(long num, int start, int len, long value){ // Get rid of illegal bits of value: value = value & ((1L<<len)-1); long val_mask = value << start; long zero_mask = ~( ((1L << len) -1) << start ); return ( num & zero_mask ) | val_mask; }
[ "protected", "static", "long", "setBits", "(", "long", "num", ",", "int", "start", ",", "int", "len", ",", "long", "value", ")", "{", "// Get rid of illegal bits of value:", "value", "=", "value", "&", "(", "(", "1L", "<<", "len", ")", "-", "1", ")", ";", "long", "val_mask", "=", "value", "<<", "start", ";", "long", "zero_mask", "=", "~", "(", "(", "(", "1L", "<<", "len", ")", "-", "1", ")", "<<", "start", ")", ";", "return", "(", "num", "&", "zero_mask", ")", "|", "val_mask", ";", "}" ]
Sets specific bits of a specific number. @param num The number to set bits. @param start Index of the rightmost bit we want to set. 0-based. @param len How many bits we want to set. @param value The value we want to set to. @return The number after changing specific bits.
[ "Sets", "specific", "bits", "of", "a", "specific", "number", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/io/DataTransferHeaderOptions.java#L136-L143
xcesco/kripton
kripton-processor/src/main/java/com/abubusoft/kripton/processor/sharedprefs/BindSharedPreferencesBuilder.java
BindSharedPreferencesBuilder.generateRefresh
private static void generateRefresh(String sharedPreferenceName, String className) { """ Generate refresh. @param sharedPreferenceName the shared preference name @param className the class name """ MethodSpec.Builder method = MethodSpec.methodBuilder("refresh").addModifiers(Modifier.PUBLIC).addJavadoc("force to refresh values\n").returns(className(className)); method.addStatement("createPrefs()"); method.addStatement("return this"); builder.addMethod(method.build()); }
java
private static void generateRefresh(String sharedPreferenceName, String className) { MethodSpec.Builder method = MethodSpec.methodBuilder("refresh").addModifiers(Modifier.PUBLIC).addJavadoc("force to refresh values\n").returns(className(className)); method.addStatement("createPrefs()"); method.addStatement("return this"); builder.addMethod(method.build()); }
[ "private", "static", "void", "generateRefresh", "(", "String", "sharedPreferenceName", ",", "String", "className", ")", "{", "MethodSpec", ".", "Builder", "method", "=", "MethodSpec", ".", "methodBuilder", "(", "\"refresh\"", ")", ".", "addModifiers", "(", "Modifier", ".", "PUBLIC", ")", ".", "addJavadoc", "(", "\"force to refresh values\\n\"", ")", ".", "returns", "(", "className", "(", "className", ")", ")", ";", "method", ".", "addStatement", "(", "\"createPrefs()\"", ")", ";", "method", ".", "addStatement", "(", "\"return this\"", ")", ";", "builder", ".", "addMethod", "(", "method", ".", "build", "(", ")", ")", ";", "}" ]
Generate refresh. @param sharedPreferenceName the shared preference name @param className the class name
[ "Generate", "refresh", "." ]
train
https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sharedprefs/BindSharedPreferencesBuilder.java#L521-L527
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/model/FindByIndexOptions.java
FindByIndexOptions.useIndex
public FindByIndexOptions useIndex(String designDocument, String indexName) { """ Specify a specific index to run the query against @param designDocument set the design document to use @param indexName set the index name to use @return this to set additional options """ assertNotNull(designDocument, "designDocument"); assertNotNull(indexName, "indexName"); JsonArray index = new JsonArray(); index.add(new JsonPrimitive(designDocument)); index.add(new JsonPrimitive(indexName)); this.useIndex = index; return this; }
java
public FindByIndexOptions useIndex(String designDocument, String indexName) { assertNotNull(designDocument, "designDocument"); assertNotNull(indexName, "indexName"); JsonArray index = new JsonArray(); index.add(new JsonPrimitive(designDocument)); index.add(new JsonPrimitive(indexName)); this.useIndex = index; return this; }
[ "public", "FindByIndexOptions", "useIndex", "(", "String", "designDocument", ",", "String", "indexName", ")", "{", "assertNotNull", "(", "designDocument", ",", "\"designDocument\"", ")", ";", "assertNotNull", "(", "indexName", ",", "\"indexName\"", ")", ";", "JsonArray", "index", "=", "new", "JsonArray", "(", ")", ";", "index", ".", "add", "(", "new", "JsonPrimitive", "(", "designDocument", ")", ")", ";", "index", ".", "add", "(", "new", "JsonPrimitive", "(", "indexName", ")", ")", ";", "this", ".", "useIndex", "=", "index", ";", "return", "this", ";", "}" ]
Specify a specific index to run the query against @param designDocument set the design document to use @param indexName set the index name to use @return this to set additional options
[ "Specify", "a", "specific", "index", "to", "run", "the", "query", "against" ]
train
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/model/FindByIndexOptions.java#L128-L136
apache/flink
flink-yarn/src/main/java/org/apache/flink/yarn/Utils.java
Utils.deleteApplicationFiles
public static void deleteApplicationFiles(final Map<String, String> env) { """ Deletes the YARN application files, e.g., Flink binaries, libraries, etc., from the remote filesystem. @param env The environment variables. """ final String applicationFilesDir = env.get(YarnConfigKeys.FLINK_YARN_FILES); if (!StringUtils.isNullOrWhitespaceOnly(applicationFilesDir)) { final org.apache.flink.core.fs.Path path = new org.apache.flink.core.fs.Path(applicationFilesDir); try { final org.apache.flink.core.fs.FileSystem fileSystem = path.getFileSystem(); if (!fileSystem.delete(path, true)) { LOG.error("Deleting yarn application files under {} was unsuccessful.", applicationFilesDir); } } catch (final IOException e) { LOG.error("Could not properly delete yarn application files directory {}.", applicationFilesDir, e); } } else { LOG.debug("No yarn application files directory set. Therefore, cannot clean up the data."); } }
java
public static void deleteApplicationFiles(final Map<String, String> env) { final String applicationFilesDir = env.get(YarnConfigKeys.FLINK_YARN_FILES); if (!StringUtils.isNullOrWhitespaceOnly(applicationFilesDir)) { final org.apache.flink.core.fs.Path path = new org.apache.flink.core.fs.Path(applicationFilesDir); try { final org.apache.flink.core.fs.FileSystem fileSystem = path.getFileSystem(); if (!fileSystem.delete(path, true)) { LOG.error("Deleting yarn application files under {} was unsuccessful.", applicationFilesDir); } } catch (final IOException e) { LOG.error("Could not properly delete yarn application files directory {}.", applicationFilesDir, e); } } else { LOG.debug("No yarn application files directory set. Therefore, cannot clean up the data."); } }
[ "public", "static", "void", "deleteApplicationFiles", "(", "final", "Map", "<", "String", ",", "String", ">", "env", ")", "{", "final", "String", "applicationFilesDir", "=", "env", ".", "get", "(", "YarnConfigKeys", ".", "FLINK_YARN_FILES", ")", ";", "if", "(", "!", "StringUtils", ".", "isNullOrWhitespaceOnly", "(", "applicationFilesDir", ")", ")", "{", "final", "org", ".", "apache", ".", "flink", ".", "core", ".", "fs", ".", "Path", "path", "=", "new", "org", ".", "apache", ".", "flink", ".", "core", ".", "fs", ".", "Path", "(", "applicationFilesDir", ")", ";", "try", "{", "final", "org", ".", "apache", ".", "flink", ".", "core", ".", "fs", ".", "FileSystem", "fileSystem", "=", "path", ".", "getFileSystem", "(", ")", ";", "if", "(", "!", "fileSystem", ".", "delete", "(", "path", ",", "true", ")", ")", "{", "LOG", ".", "error", "(", "\"Deleting yarn application files under {} was unsuccessful.\"", ",", "applicationFilesDir", ")", ";", "}", "}", "catch", "(", "final", "IOException", "e", ")", "{", "LOG", ".", "error", "(", "\"Could not properly delete yarn application files directory {}.\"", ",", "applicationFilesDir", ",", "e", ")", ";", "}", "}", "else", "{", "LOG", ".", "debug", "(", "\"No yarn application files directory set. Therefore, cannot clean up the data.\"", ")", ";", "}", "}" ]
Deletes the YARN application files, e.g., Flink binaries, libraries, etc., from the remote filesystem. @param env The environment variables.
[ "Deletes", "the", "YARN", "application", "files", "e", ".", "g", ".", "Flink", "binaries", "libraries", "etc", ".", "from", "the", "remote", "filesystem", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-yarn/src/main/java/org/apache/flink/yarn/Utils.java#L182-L197
ronmamo/reflections
src/main/java/org/reflections/Reflections.java
Reflections.collect
public Reflections collect(final File file) { """ merges saved Reflections resources from the given file, using the serializer configured in this instance's Configuration <p> useful if you know the serialized resource location and prefer not to look it up the classpath """ FileInputStream inputStream = null; try { inputStream = new FileInputStream(file); return collect(inputStream); } catch (FileNotFoundException e) { throw new ReflectionsException("could not obtain input stream from file " + file, e); } finally { Utils.close(inputStream); } }
java
public Reflections collect(final File file) { FileInputStream inputStream = null; try { inputStream = new FileInputStream(file); return collect(inputStream); } catch (FileNotFoundException e) { throw new ReflectionsException("could not obtain input stream from file " + file, e); } finally { Utils.close(inputStream); } }
[ "public", "Reflections", "collect", "(", "final", "File", "file", ")", "{", "FileInputStream", "inputStream", "=", "null", ";", "try", "{", "inputStream", "=", "new", "FileInputStream", "(", "file", ")", ";", "return", "collect", "(", "inputStream", ")", ";", "}", "catch", "(", "FileNotFoundException", "e", ")", "{", "throw", "new", "ReflectionsException", "(", "\"could not obtain input stream from file \"", "+", "file", ",", "e", ")", ";", "}", "finally", "{", "Utils", ".", "close", "(", "inputStream", ")", ";", "}", "}" ]
merges saved Reflections resources from the given file, using the serializer configured in this instance's Configuration <p> useful if you know the serialized resource location and prefer not to look it up the classpath
[ "merges", "saved", "Reflections", "resources", "from", "the", "given", "file", "using", "the", "serializer", "configured", "in", "this", "instance", "s", "Configuration", "<p", ">", "useful", "if", "you", "know", "the", "serialized", "resource", "location", "and", "prefer", "not", "to", "look", "it", "up", "the", "classpath" ]
train
https://github.com/ronmamo/reflections/blob/084cf4a759a06d88e88753ac00397478c2e0ed52/src/main/java/org/reflections/Reflections.java#L341-L351
anotheria/configureme
src/main/java/org/configureme/util/StringUtils.java
StringUtils.replaceOnce
public static String replaceOnce(final String src, final String toReplace, final String with) { """ Replace once in source {@link java.lang.String} some {@link java.lang.String} with new {@link java.lang.String}. @param src source string @param toReplace string to replace @param with new string @return {@link java.lang.String} after replacement """ final int index = src.indexOf(toReplace); if (index == -1) return src; String s = src.substring(0, index); s += with; s += src.substring(index + toReplace.length(), src.length()); return s; }
java
public static String replaceOnce(final String src, final String toReplace, final String with) { final int index = src.indexOf(toReplace); if (index == -1) return src; String s = src.substring(0, index); s += with; s += src.substring(index + toReplace.length(), src.length()); return s; }
[ "public", "static", "String", "replaceOnce", "(", "final", "String", "src", ",", "final", "String", "toReplace", ",", "final", "String", "with", ")", "{", "final", "int", "index", "=", "src", ".", "indexOf", "(", "toReplace", ")", ";", "if", "(", "index", "==", "-", "1", ")", "return", "src", ";", "String", "s", "=", "src", ".", "substring", "(", "0", ",", "index", ")", ";", "s", "+=", "with", ";", "s", "+=", "src", ".", "substring", "(", "index", "+", "toReplace", ".", "length", "(", ")", ",", "src", ".", "length", "(", ")", ")", ";", "return", "s", ";", "}" ]
Replace once in source {@link java.lang.String} some {@link java.lang.String} with new {@link java.lang.String}. @param src source string @param toReplace string to replace @param with new string @return {@link java.lang.String} after replacement
[ "Replace", "once", "in", "source", "{", "@link", "java", ".", "lang", ".", "String", "}", "some", "{", "@link", "java", ".", "lang", ".", "String", "}", "with", "new", "{", "@link", "java", ".", "lang", ".", "String", "}", "." ]
train
https://github.com/anotheria/configureme/blob/1f52dd9109349623190586bdf5a592de8016e1fa/src/main/java/org/configureme/util/StringUtils.java#L307-L316
Red5/red5-io
src/main/java/org/red5/io/object/Serializer.java
Serializer.writeIterator
protected static void writeIterator(Output out, Iterator<Object> it) { """ Writes an iterator out to the output @param out Output writer @param it Iterator to write """ log.trace("writeIterator"); // Create LinkedList of collection we iterate thru and write it out later LinkedList<Object> list = new LinkedList<Object>(); while (it.hasNext()) { list.addLast(it.next()); } // Write out collection out.writeArray(list); }
java
protected static void writeIterator(Output out, Iterator<Object> it) { log.trace("writeIterator"); // Create LinkedList of collection we iterate thru and write it out later LinkedList<Object> list = new LinkedList<Object>(); while (it.hasNext()) { list.addLast(it.next()); } // Write out collection out.writeArray(list); }
[ "protected", "static", "void", "writeIterator", "(", "Output", "out", ",", "Iterator", "<", "Object", ">", "it", ")", "{", "log", ".", "trace", "(", "\"writeIterator\"", ")", ";", "// Create LinkedList of collection we iterate thru and write it out later", "LinkedList", "<", "Object", ">", "list", "=", "new", "LinkedList", "<", "Object", ">", "(", ")", ";", "while", "(", "it", ".", "hasNext", "(", ")", ")", "{", "list", ".", "addLast", "(", "it", ".", "next", "(", ")", ")", ";", "}", "// Write out collection", "out", ".", "writeArray", "(", "list", ")", ";", "}" ]
Writes an iterator out to the output @param out Output writer @param it Iterator to write
[ "Writes", "an", "iterator", "out", "to", "the", "output" ]
train
https://github.com/Red5/red5-io/blob/9bbbc506423c5a8f18169d46d400df56c0072a33/src/main/java/org/red5/io/object/Serializer.java#L278-L287
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/reflect/TypeUtils.java
TypeUtils.appendAllTo
private static <T> StringBuilder appendAllTo(final StringBuilder buf, final String sep, final T... types) { """ Append {@code types} to {@code buf} with separator {@code sep}. @param buf destination @param sep separator @param types to append @return {@code buf} @since 3.2 """ Validate.notEmpty(Validate.noNullElements(types)); if (types.length > 0) { buf.append(toString(types[0])); for (int i = 1; i < types.length; i++) { buf.append(sep).append(toString(types[i])); } } return buf; }
java
private static <T> StringBuilder appendAllTo(final StringBuilder buf, final String sep, final T... types) { Validate.notEmpty(Validate.noNullElements(types)); if (types.length > 0) { buf.append(toString(types[0])); for (int i = 1; i < types.length; i++) { buf.append(sep).append(toString(types[i])); } } return buf; }
[ "private", "static", "<", "T", ">", "StringBuilder", "appendAllTo", "(", "final", "StringBuilder", "buf", ",", "final", "String", "sep", ",", "final", "T", "...", "types", ")", "{", "Validate", ".", "notEmpty", "(", "Validate", ".", "noNullElements", "(", "types", ")", ")", ";", "if", "(", "types", ".", "length", ">", "0", ")", "{", "buf", ".", "append", "(", "toString", "(", "types", "[", "0", "]", ")", ")", ";", "for", "(", "int", "i", "=", "1", ";", "i", "<", "types", ".", "length", ";", "i", "++", ")", "{", "buf", ".", "append", "(", "sep", ")", ".", "append", "(", "toString", "(", "types", "[", "i", "]", ")", ")", ";", "}", "}", "return", "buf", ";", "}" ]
Append {@code types} to {@code buf} with separator {@code sep}. @param buf destination @param sep separator @param types to append @return {@code buf} @since 3.2
[ "Append", "{" ]
train
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/reflect/TypeUtils.java#L1882-L1891
loldevs/riotapi
rtmp/src/main/java/net/boreeas/riotapi/rtmp/services/LoginService.java
LoginService.performLcdsHeartBeat
public String performLcdsHeartBeat(long accountId, String sessionToken, int heartBeatCount) { """ Perform a heartbeat @param accountId The user id @param sessionToken The token for the current session @param heartBeatCount The amount of heartbeats that have been sent @return A string """ return performLcdsHeartBeat(accountId, sessionToken, heartBeatCount, new Date()); }
java
public String performLcdsHeartBeat(long accountId, String sessionToken, int heartBeatCount) { return performLcdsHeartBeat(accountId, sessionToken, heartBeatCount, new Date()); }
[ "public", "String", "performLcdsHeartBeat", "(", "long", "accountId", ",", "String", "sessionToken", ",", "int", "heartBeatCount", ")", "{", "return", "performLcdsHeartBeat", "(", "accountId", ",", "sessionToken", ",", "heartBeatCount", ",", "new", "Date", "(", ")", ")", ";", "}" ]
Perform a heartbeat @param accountId The user id @param sessionToken The token for the current session @param heartBeatCount The amount of heartbeats that have been sent @return A string
[ "Perform", "a", "heartbeat" ]
train
https://github.com/loldevs/riotapi/blob/0b8aac407aa5289845f249024f9732332855544f/rtmp/src/main/java/net/boreeas/riotapi/rtmp/services/LoginService.java#L57-L59
jenkinsci/jenkins
core/src/main/java/hudson/security/SecurityRealm.java
SecurityRealm.findBean
public static <T> T findBean(Class<T> type, ApplicationContext context) { """ Picks up the instance of the given type from the spring context. If there are multiple beans of the same type or if there are none, this method treats that as an {@link IllegalArgumentException}. This method is intended to be used to pick up a Acegi object from spring once the bean definition file is parsed. """ Map m = context.getBeansOfType(type); switch(m.size()) { case 0: throw new IllegalArgumentException("No beans of "+type+" are defined"); case 1: return type.cast(m.values().iterator().next()); default: throw new IllegalArgumentException("Multiple beans of "+type+" are defined: "+m); } }
java
public static <T> T findBean(Class<T> type, ApplicationContext context) { Map m = context.getBeansOfType(type); switch(m.size()) { case 0: throw new IllegalArgumentException("No beans of "+type+" are defined"); case 1: return type.cast(m.values().iterator().next()); default: throw new IllegalArgumentException("Multiple beans of "+type+" are defined: "+m); } }
[ "public", "static", "<", "T", ">", "T", "findBean", "(", "Class", "<", "T", ">", "type", ",", "ApplicationContext", "context", ")", "{", "Map", "m", "=", "context", ".", "getBeansOfType", "(", "type", ")", ";", "switch", "(", "m", ".", "size", "(", ")", ")", "{", "case", "0", ":", "throw", "new", "IllegalArgumentException", "(", "\"No beans of \"", "+", "type", "+", "\" are defined\"", ")", ";", "case", "1", ":", "return", "type", ".", "cast", "(", "m", ".", "values", "(", ")", ".", "iterator", "(", ")", ".", "next", "(", ")", ")", ";", "default", ":", "throw", "new", "IllegalArgumentException", "(", "\"Multiple beans of \"", "+", "type", "+", "\" are defined: \"", "+", "m", ")", ";", "}", "}" ]
Picks up the instance of the given type from the spring context. If there are multiple beans of the same type or if there are none, this method treats that as an {@link IllegalArgumentException}. This method is intended to be used to pick up a Acegi object from spring once the bean definition file is parsed.
[ "Picks", "up", "the", "instance", "of", "the", "given", "type", "from", "the", "spring", "context", ".", "If", "there", "are", "multiple", "beans", "of", "the", "same", "type", "or", "if", "there", "are", "none", "this", "method", "treats", "that", "as", "an", "{", "@link", "IllegalArgumentException", "}", "." ]
train
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/security/SecurityRealm.java#L425-L435
Samsung/GearVRf
GVRf/Extensions/script/src/main/java/org/gearvrf/script/javascript/ExternalScriptable.java
ExternalScriptable.put
public void put(int index, Scriptable start, Object value) { """ Sets the value of the indexed property, creating it if need be. @param index the numeric index for the property @param start the object whose property is being set @param value value to set the property to """ if (start == this) { synchronized (this) { indexedProps.put(new Integer(index), value); } } else { start.put(index, start, value); } }
java
public void put(int index, Scriptable start, Object value) { if (start == this) { synchronized (this) { indexedProps.put(new Integer(index), value); } } else { start.put(index, start, value); } }
[ "public", "void", "put", "(", "int", "index", ",", "Scriptable", "start", ",", "Object", "value", ")", "{", "if", "(", "start", "==", "this", ")", "{", "synchronized", "(", "this", ")", "{", "indexedProps", ".", "put", "(", "new", "Integer", "(", "index", ")", ",", "value", ")", ";", "}", "}", "else", "{", "start", ".", "put", "(", "index", ",", "start", ",", "value", ")", ";", "}", "}" ]
Sets the value of the indexed property, creating it if need be. @param index the numeric index for the property @param start the object whose property is being set @param value value to set the property to
[ "Sets", "the", "value", "of", "the", "indexed", "property", "creating", "it", "if", "need", "be", "." ]
train
https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Extensions/script/src/main/java/org/gearvrf/script/javascript/ExternalScriptable.java#L200-L208
xm-online/xm-commons
xm-commons-permission/src/main/java/com/icthh/xm/commons/permission/repository/PermittedRepository.java
PermittedRepository.findAll
public <T> List<T> findAll(Class<T> entityClass, String privilegeKey) { """ Find all permitted entities. @param entityClass the entity class to get @param privilegeKey the privilege key for permission lookup @param <T> the type of entity @return list of permitted entities """ return findAll(null, entityClass, privilegeKey).getContent(); }
java
public <T> List<T> findAll(Class<T> entityClass, String privilegeKey) { return findAll(null, entityClass, privilegeKey).getContent(); }
[ "public", "<", "T", ">", "List", "<", "T", ">", "findAll", "(", "Class", "<", "T", ">", "entityClass", ",", "String", "privilegeKey", ")", "{", "return", "findAll", "(", "null", ",", "entityClass", ",", "privilegeKey", ")", ".", "getContent", "(", ")", ";", "}" ]
Find all permitted entities. @param entityClass the entity class to get @param privilegeKey the privilege key for permission lookup @param <T> the type of entity @return list of permitted entities
[ "Find", "all", "permitted", "entities", "." ]
train
https://github.com/xm-online/xm-commons/blob/43eb2273adb96f40830d7b905ee3a767b8715caf/xm-commons-permission/src/main/java/com/icthh/xm/commons/permission/repository/PermittedRepository.java#L60-L62
google/error-prone-javac
src/jdk.compiler/share/classes/com/sun/tools/javac/comp/DeferredAttr.java
DeferredAttr.attribSpeculativeLambda
JCLambda attribSpeculativeLambda(JCLambda that, Env<AttrContext> env, ResultInfo resultInfo) { """ Performs speculative attribution of a lambda body and returns the speculative lambda tree, in the absence of a target-type. Since {@link Attr#visitLambda(JCLambda)} cannot type-check lambda bodies w/o a suitable target-type, this routine 'unrolls' the lambda by turning it into a regular block, speculatively type-checks the block and then puts back the pieces. """ ListBuffer<JCStatement> stats = new ListBuffer<>(); stats.addAll(that.params); if (that.getBodyKind() == JCLambda.BodyKind.EXPRESSION) { stats.add(make.Return((JCExpression)that.body)); } else { stats.add((JCBlock)that.body); } JCBlock lambdaBlock = make.Block(0, stats.toList()); Env<AttrContext> localEnv = attr.lambdaEnv(that, env); try { localEnv.info.returnResult = resultInfo; JCBlock speculativeTree = (JCBlock)attribSpeculative(lambdaBlock, localEnv, resultInfo); List<JCVariableDecl> args = speculativeTree.getStatements().stream() .filter(s -> s.hasTag(Tag.VARDEF)) .map(t -> (JCVariableDecl)t) .collect(List.collector()); JCTree lambdaBody = speculativeTree.getStatements().last(); if (lambdaBody.hasTag(Tag.RETURN)) { lambdaBody = ((JCReturn)lambdaBody).expr; } JCLambda speculativeLambda = make.Lambda(args, lambdaBody); attr.preFlow(speculativeLambda); flow.analyzeLambda(env, speculativeLambda, make, false); return speculativeLambda; } finally { localEnv.info.scope.leave(); } }
java
JCLambda attribSpeculativeLambda(JCLambda that, Env<AttrContext> env, ResultInfo resultInfo) { ListBuffer<JCStatement> stats = new ListBuffer<>(); stats.addAll(that.params); if (that.getBodyKind() == JCLambda.BodyKind.EXPRESSION) { stats.add(make.Return((JCExpression)that.body)); } else { stats.add((JCBlock)that.body); } JCBlock lambdaBlock = make.Block(0, stats.toList()); Env<AttrContext> localEnv = attr.lambdaEnv(that, env); try { localEnv.info.returnResult = resultInfo; JCBlock speculativeTree = (JCBlock)attribSpeculative(lambdaBlock, localEnv, resultInfo); List<JCVariableDecl> args = speculativeTree.getStatements().stream() .filter(s -> s.hasTag(Tag.VARDEF)) .map(t -> (JCVariableDecl)t) .collect(List.collector()); JCTree lambdaBody = speculativeTree.getStatements().last(); if (lambdaBody.hasTag(Tag.RETURN)) { lambdaBody = ((JCReturn)lambdaBody).expr; } JCLambda speculativeLambda = make.Lambda(args, lambdaBody); attr.preFlow(speculativeLambda); flow.analyzeLambda(env, speculativeLambda, make, false); return speculativeLambda; } finally { localEnv.info.scope.leave(); } }
[ "JCLambda", "attribSpeculativeLambda", "(", "JCLambda", "that", ",", "Env", "<", "AttrContext", ">", "env", ",", "ResultInfo", "resultInfo", ")", "{", "ListBuffer", "<", "JCStatement", ">", "stats", "=", "new", "ListBuffer", "<>", "(", ")", ";", "stats", ".", "addAll", "(", "that", ".", "params", ")", ";", "if", "(", "that", ".", "getBodyKind", "(", ")", "==", "JCLambda", ".", "BodyKind", ".", "EXPRESSION", ")", "{", "stats", ".", "add", "(", "make", ".", "Return", "(", "(", "JCExpression", ")", "that", ".", "body", ")", ")", ";", "}", "else", "{", "stats", ".", "add", "(", "(", "JCBlock", ")", "that", ".", "body", ")", ";", "}", "JCBlock", "lambdaBlock", "=", "make", ".", "Block", "(", "0", ",", "stats", ".", "toList", "(", ")", ")", ";", "Env", "<", "AttrContext", ">", "localEnv", "=", "attr", ".", "lambdaEnv", "(", "that", ",", "env", ")", ";", "try", "{", "localEnv", ".", "info", ".", "returnResult", "=", "resultInfo", ";", "JCBlock", "speculativeTree", "=", "(", "JCBlock", ")", "attribSpeculative", "(", "lambdaBlock", ",", "localEnv", ",", "resultInfo", ")", ";", "List", "<", "JCVariableDecl", ">", "args", "=", "speculativeTree", ".", "getStatements", "(", ")", ".", "stream", "(", ")", ".", "filter", "(", "s", "->", "s", ".", "hasTag", "(", "Tag", ".", "VARDEF", ")", ")", ".", "map", "(", "t", "->", "(", "JCVariableDecl", ")", "t", ")", ".", "collect", "(", "List", ".", "collector", "(", ")", ")", ";", "JCTree", "lambdaBody", "=", "speculativeTree", ".", "getStatements", "(", ")", ".", "last", "(", ")", ";", "if", "(", "lambdaBody", ".", "hasTag", "(", "Tag", ".", "RETURN", ")", ")", "{", "lambdaBody", "=", "(", "(", "JCReturn", ")", "lambdaBody", ")", ".", "expr", ";", "}", "JCLambda", "speculativeLambda", "=", "make", ".", "Lambda", "(", "args", ",", "lambdaBody", ")", ";", "attr", ".", "preFlow", "(", "speculativeLambda", ")", ";", "flow", ".", "analyzeLambda", "(", "env", ",", "speculativeLambda", ",", "make", ",", "false", ")", ";", "return", "speculativeLambda", ";", "}", "finally", "{", "localEnv", ".", "info", ".", "scope", ".", "leave", "(", ")", ";", "}", "}" ]
Performs speculative attribution of a lambda body and returns the speculative lambda tree, in the absence of a target-type. Since {@link Attr#visitLambda(JCLambda)} cannot type-check lambda bodies w/o a suitable target-type, this routine 'unrolls' the lambda by turning it into a regular block, speculatively type-checks the block and then puts back the pieces.
[ "Performs", "speculative", "attribution", "of", "a", "lambda", "body", "and", "returns", "the", "speculative", "lambda", "tree", "in", "the", "absence", "of", "a", "target", "-", "type", ".", "Since", "{" ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/DeferredAttr.java#L435-L463
hageldave/ImagingKit
ImagingKit_Core/src/main/java/hageldave/imagingkit/core/scientific/ColorPixel.java
ColorPixel.convertRange
public ColorPixel convertRange(double lowerLimitNow, double upperLimitNow, double lowerLimitAfter, double upperLimitAfter) { """ Converts the pixels RGB channel values from one value range to another. Alpha is preserved. <p> Suppose we know the pixels value range is currently from -10 to 10, and we want to change that value range to 0.0 to 1.0, then the call would look like this:<br> {@code convertRange(-10,10, 0,1)}.<br> A channel value of -10 would then be 0, a channel value of 0 would then be 0.5, a channel value 20 would then be 1.5 (even though it is out of range). @param lowerLimitNow the lower limit of the currently assumed value range @param upperLimitNow the upper limit of the currently assumed value range @param lowerLimitAfter the lower limit of the desired value range @param upperLimitAfter the upper limit of the desired value range @return this pixel for chaining. @see #scale(double) """ // double currentRange = upperLimitNow-lowerLimitNow; // double newRange = upperLimitAfter-lowerLimitAfter; // double scaling = newRange/currentRange; double scaling = (upperLimitAfter-lowerLimitAfter)/(upperLimitNow-lowerLimitNow); setRGB_fromDouble_preserveAlpha( lowerLimitAfter+(r_asDouble()-lowerLimitNow)*scaling, lowerLimitAfter+(g_asDouble()-lowerLimitNow)*scaling, lowerLimitAfter+(b_asDouble()-lowerLimitNow)*scaling); return this; }
java
public ColorPixel convertRange(double lowerLimitNow, double upperLimitNow, double lowerLimitAfter, double upperLimitAfter){ // double currentRange = upperLimitNow-lowerLimitNow; // double newRange = upperLimitAfter-lowerLimitAfter; // double scaling = newRange/currentRange; double scaling = (upperLimitAfter-lowerLimitAfter)/(upperLimitNow-lowerLimitNow); setRGB_fromDouble_preserveAlpha( lowerLimitAfter+(r_asDouble()-lowerLimitNow)*scaling, lowerLimitAfter+(g_asDouble()-lowerLimitNow)*scaling, lowerLimitAfter+(b_asDouble()-lowerLimitNow)*scaling); return this; }
[ "public", "ColorPixel", "convertRange", "(", "double", "lowerLimitNow", ",", "double", "upperLimitNow", ",", "double", "lowerLimitAfter", ",", "double", "upperLimitAfter", ")", "{", "//\t\tdouble currentRange = upperLimitNow-lowerLimitNow;", "//\t\tdouble newRange = upperLimitAfter-lowerLimitAfter;", "//\t\tdouble scaling = newRange/currentRange;", "double", "scaling", "=", "(", "upperLimitAfter", "-", "lowerLimitAfter", ")", "/", "(", "upperLimitNow", "-", "lowerLimitNow", ")", ";", "setRGB_fromDouble_preserveAlpha", "(", "lowerLimitAfter", "+", "(", "r_asDouble", "(", ")", "-", "lowerLimitNow", ")", "*", "scaling", ",", "lowerLimitAfter", "+", "(", "g_asDouble", "(", ")", "-", "lowerLimitNow", ")", "*", "scaling", ",", "lowerLimitAfter", "+", "(", "b_asDouble", "(", ")", "-", "lowerLimitNow", ")", "*", "scaling", ")", ";", "return", "this", ";", "}" ]
Converts the pixels RGB channel values from one value range to another. Alpha is preserved. <p> Suppose we know the pixels value range is currently from -10 to 10, and we want to change that value range to 0.0 to 1.0, then the call would look like this:<br> {@code convertRange(-10,10, 0,1)}.<br> A channel value of -10 would then be 0, a channel value of 0 would then be 0.5, a channel value 20 would then be 1.5 (even though it is out of range). @param lowerLimitNow the lower limit of the currently assumed value range @param upperLimitNow the upper limit of the currently assumed value range @param lowerLimitAfter the lower limit of the desired value range @param upperLimitAfter the upper limit of the desired value range @return this pixel for chaining. @see #scale(double)
[ "Converts", "the", "pixels", "RGB", "channel", "values", "from", "one", "value", "range", "to", "another", ".", "Alpha", "is", "preserved", ".", "<p", ">", "Suppose", "we", "know", "the", "pixels", "value", "range", "is", "currently", "from", "-", "10", "to", "10", "and", "we", "want", "to", "change", "that", "value", "range", "to", "0", ".", "0", "to", "1", ".", "0", "then", "the", "call", "would", "look", "like", "this", ":", "<br", ">", "{", "@code", "convertRange", "(", "-", "10", "10", "0", "1", ")", "}", ".", "<br", ">", "A", "channel", "value", "of", "-", "10", "would", "then", "be", "0", "a", "channel", "value", "of", "0", "would", "then", "be", "0", ".", "5", "a", "channel", "value", "20", "would", "then", "be", "1", ".", "5", "(", "even", "though", "it", "is", "out", "of", "range", ")", "." ]
train
https://github.com/hageldave/ImagingKit/blob/3837c7d550a12cf4dc5718b644ced94b97f52668/ImagingKit_Core/src/main/java/hageldave/imagingkit/core/scientific/ColorPixel.java#L277-L287
google/j2objc
jre_emul/android/platform/libcore/luni/src/main/java/javax/xml/xpath/XPathFactoryFinder.java
XPathFactoryFinder.which
private static String which(String classname, ClassLoader loader) { """ <p>Search the specified classloader for the given classname.</p> @param classname the fully qualified name of the class to search for @param loader the classloader to search @return the source location of the resource, or null if it wasn't found """ String classnameAsResource = classname.replace('.', '/') + ".class"; if (loader==null) loader = ClassLoader.getSystemClassLoader(); URL it = loader.getResource(classnameAsResource); return it != null ? it.toString() : null; }
java
private static String which(String classname, ClassLoader loader) { String classnameAsResource = classname.replace('.', '/') + ".class"; if (loader==null) loader = ClassLoader.getSystemClassLoader(); URL it = loader.getResource(classnameAsResource); return it != null ? it.toString() : null; }
[ "private", "static", "String", "which", "(", "String", "classname", ",", "ClassLoader", "loader", ")", "{", "String", "classnameAsResource", "=", "classname", ".", "replace", "(", "'", "'", ",", "'", "'", ")", "+", "\".class\"", ";", "if", "(", "loader", "==", "null", ")", "loader", "=", "ClassLoader", ".", "getSystemClassLoader", "(", ")", ";", "URL", "it", "=", "loader", ".", "getResource", "(", "classnameAsResource", ")", ";", "return", "it", "!=", "null", "?", "it", ".", "toString", "(", ")", ":", "null", ";", "}" ]
<p>Search the specified classloader for the given classname.</p> @param classname the fully qualified name of the class to search for @param loader the classloader to search @return the source location of the resource, or null if it wasn't found
[ "<p", ">", "Search", "the", "specified", "classloader", "for", "the", "given", "classname", ".", "<", "/", "p", ">" ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/luni/src/main/java/javax/xml/xpath/XPathFactoryFinder.java#L363-L369
alkacon/opencms-core
src/org/opencms/configuration/CmsElementWithSubElementsParamConfigHelper.java
CmsElementWithSubElementsParamConfigHelper.addRules
public void addRules(Digester digester) { """ Adds the configuration parsing rules to the digester.<p> @param digester the digester to which the rules should be added """ digester.addRule(m_basePath, new Rule() { @SuppressWarnings("synthetic-access") @Override public void begin(String namespace, String name, Attributes attributes) throws Exception { I_CmsConfigurationParameterHandler config = (I_CmsConfigurationParameterHandler)(m_class.newInstance()); config.initConfiguration(); getDigester().push(config); } @Override public void end(String namespace, String name) throws Exception { getDigester().pop(); } }); for (String elem : m_subElements) { digester.addRule(m_basePath + "/" + elem, new Rule() { @Override public void body(String namespace, String name, String text) throws Exception { I_CmsConfigurationParameterHandler handler = (I_CmsConfigurationParameterHandler)(getDigester().peek()); handler.addConfigurationParameter(name, text); } }); } }
java
public void addRules(Digester digester) { digester.addRule(m_basePath, new Rule() { @SuppressWarnings("synthetic-access") @Override public void begin(String namespace, String name, Attributes attributes) throws Exception { I_CmsConfigurationParameterHandler config = (I_CmsConfigurationParameterHandler)(m_class.newInstance()); config.initConfiguration(); getDigester().push(config); } @Override public void end(String namespace, String name) throws Exception { getDigester().pop(); } }); for (String elem : m_subElements) { digester.addRule(m_basePath + "/" + elem, new Rule() { @Override public void body(String namespace, String name, String text) throws Exception { I_CmsConfigurationParameterHandler handler = (I_CmsConfigurationParameterHandler)(getDigester().peek()); handler.addConfigurationParameter(name, text); } }); } }
[ "public", "void", "addRules", "(", "Digester", "digester", ")", "{", "digester", ".", "addRule", "(", "m_basePath", ",", "new", "Rule", "(", ")", "{", "@", "SuppressWarnings", "(", "\"synthetic-access\"", ")", "@", "Override", "public", "void", "begin", "(", "String", "namespace", ",", "String", "name", ",", "Attributes", "attributes", ")", "throws", "Exception", "{", "I_CmsConfigurationParameterHandler", "config", "=", "(", "I_CmsConfigurationParameterHandler", ")", "(", "m_class", ".", "newInstance", "(", ")", ")", ";", "config", ".", "initConfiguration", "(", ")", ";", "getDigester", "(", ")", ".", "push", "(", "config", ")", ";", "}", "@", "Override", "public", "void", "end", "(", "String", "namespace", ",", "String", "name", ")", "throws", "Exception", "{", "getDigester", "(", ")", ".", "pop", "(", ")", ";", "}", "}", ")", ";", "for", "(", "String", "elem", ":", "m_subElements", ")", "{", "digester", ".", "addRule", "(", "m_basePath", "+", "\"/\"", "+", "elem", ",", "new", "Rule", "(", ")", "{", "@", "Override", "public", "void", "body", "(", "String", "namespace", ",", "String", "name", ",", "String", "text", ")", "throws", "Exception", "{", "I_CmsConfigurationParameterHandler", "handler", "=", "(", "I_CmsConfigurationParameterHandler", ")", "(", "getDigester", "(", ")", ".", "peek", "(", ")", ")", ";", "handler", ".", "addConfigurationParameter", "(", "name", ",", "text", ")", ";", "}", "}", ")", ";", "}", "}" ]
Adds the configuration parsing rules to the digester.<p> @param digester the digester to which the rules should be added
[ "Adds", "the", "configuration", "parsing", "rules", "to", "the", "digester", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/configuration/CmsElementWithSubElementsParamConfigHelper.java#L78-L110
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/db/cql/CQLSchemaManager.java
CQLSchemaManager.createCQLTable
public void createCQLTable(String storeName, boolean bBinaryValues) { """ Create a CQL table with the given name. For backward compatibility with the Thrift API, all tables look like this: <pre> CREATE TABLE "<i>keyspace</i>"."<i>name</i>" ( key text, column1 text, value text, // or blob based on bBinaryValues PRIMARY KEY(key, column1) ) WITH COMPACT STORAGE [WITH <i>prop</i> AND <i>prop</i> AND ...] </pre> Where the WITH <i>prop</i> clauses come from configuration parameters. @param storeName Name of table (unquoted) to create. @param bBinaryValues True if store's values will be binary. """ String tableName = CQLService.storeToCQLName(storeName); m_logger.info("Creating CQL table {}", tableName); StringBuffer cql = new StringBuffer(); cql.append("CREATE TABLE "); cql.append(qualifiedTableName(tableName)); cql.append("(key text,column1 text,value "); if (bBinaryValues) { cql.append("blob,"); } else { cql.append("text,"); } cql.append("PRIMARY KEY(key,column1)) WITH COMPACT STORAGE "); cql.append(tablePropertiesToCQLString(storeName)); cql.append(";"); executeCQL(cql.toString()); }
java
public void createCQLTable(String storeName, boolean bBinaryValues) { String tableName = CQLService.storeToCQLName(storeName); m_logger.info("Creating CQL table {}", tableName); StringBuffer cql = new StringBuffer(); cql.append("CREATE TABLE "); cql.append(qualifiedTableName(tableName)); cql.append("(key text,column1 text,value "); if (bBinaryValues) { cql.append("blob,"); } else { cql.append("text,"); } cql.append("PRIMARY KEY(key,column1)) WITH COMPACT STORAGE "); cql.append(tablePropertiesToCQLString(storeName)); cql.append(";"); executeCQL(cql.toString()); }
[ "public", "void", "createCQLTable", "(", "String", "storeName", ",", "boolean", "bBinaryValues", ")", "{", "String", "tableName", "=", "CQLService", ".", "storeToCQLName", "(", "storeName", ")", ";", "m_logger", ".", "info", "(", "\"Creating CQL table {}\"", ",", "tableName", ")", ";", "StringBuffer", "cql", "=", "new", "StringBuffer", "(", ")", ";", "cql", ".", "append", "(", "\"CREATE TABLE \"", ")", ";", "cql", ".", "append", "(", "qualifiedTableName", "(", "tableName", ")", ")", ";", "cql", ".", "append", "(", "\"(key text,column1 text,value \"", ")", ";", "if", "(", "bBinaryValues", ")", "{", "cql", ".", "append", "(", "\"blob,\"", ")", ";", "}", "else", "{", "cql", ".", "append", "(", "\"text,\"", ")", ";", "}", "cql", ".", "append", "(", "\"PRIMARY KEY(key,column1)) WITH COMPACT STORAGE \"", ")", ";", "cql", ".", "append", "(", "tablePropertiesToCQLString", "(", "storeName", ")", ")", ";", "cql", ".", "append", "(", "\";\"", ")", ";", "executeCQL", "(", "cql", ".", "toString", "(", ")", ")", ";", "}" ]
Create a CQL table with the given name. For backward compatibility with the Thrift API, all tables look like this: <pre> CREATE TABLE "<i>keyspace</i>"."<i>name</i>" ( key text, column1 text, value text, // or blob based on bBinaryValues PRIMARY KEY(key, column1) ) WITH COMPACT STORAGE [WITH <i>prop</i> AND <i>prop</i> AND ...] </pre> Where the WITH <i>prop</i> clauses come from configuration parameters. @param storeName Name of table (unquoted) to create. @param bBinaryValues True if store's values will be binary.
[ "Create", "a", "CQL", "table", "with", "the", "given", "name", ".", "For", "backward", "compatibility", "with", "the", "Thrift", "API", "all", "tables", "look", "like", "this", ":", "<pre", ">", "CREATE", "TABLE", "<i", ">", "keyspace<", "/", "i", ">", ".", "<i", ">", "name<", "/", "i", ">", "(", "key", "text", "column1", "text", "value", "text", "//", "or", "blob", "based", "on", "bBinaryValues", "PRIMARY", "KEY", "(", "key", "column1", ")", ")", "WITH", "COMPACT", "STORAGE", "[", "WITH", "<i", ">", "prop<", "/", "i", ">", "AND", "<i", ">", "prop<", "/", "i", ">", "AND", "...", "]", "<", "/", "pre", ">", "Where", "the", "WITH", "<i", ">", "prop<", "/", "i", ">", "clauses", "come", "from", "configuration", "parameters", "." ]
train
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/db/cql/CQLSchemaManager.java#L127-L144
Javacord/Javacord
javacord-api/src/main/java/org/javacord/api/entity/message/embed/EmbedBuilder.java
EmbedBuilder.setFooter
public EmbedBuilder setFooter(String text, String iconUrl) { """ Sets the footer of the embed. @param text The text of the footer. @param iconUrl The url of the footer's icon. @return The current instance in order to chain call methods. """ delegate.setFooter(text, iconUrl); return this; }
java
public EmbedBuilder setFooter(String text, String iconUrl) { delegate.setFooter(text, iconUrl); return this; }
[ "public", "EmbedBuilder", "setFooter", "(", "String", "text", ",", "String", "iconUrl", ")", "{", "delegate", ".", "setFooter", "(", "text", ",", "iconUrl", ")", ";", "return", "this", ";", "}" ]
Sets the footer of the embed. @param text The text of the footer. @param iconUrl The url of the footer's icon. @return The current instance in order to chain call methods.
[ "Sets", "the", "footer", "of", "the", "embed", "." ]
train
https://github.com/Javacord/Javacord/blob/915aad084dc5e863284267529d0dccd625fc6886/javacord-api/src/main/java/org/javacord/api/entity/message/embed/EmbedBuilder.java#L119-L122
paypal/SeLion
client/src/main/java/com/paypal/selion/internal/platform/pageyaml/YamlV2Reader.java
YamlV2Reader.getGuiMap
@Override public Map<String, String> getGuiMap(String locale) { """ The user needs to provide the locale for which data needs to be read. After successfully reading the data from the input stream, it is placed in the hash map and returned to the users. If the locale provided is not set for a certain element it will fall back to the default locale that is set in the Yaml. If default locale is not provided in the Yaml it will use US. @param locale Signifies the language or site language to read. """ return getGuiMap(locale, WebDriverPlatform.UNDEFINED); }
java
@Override public Map<String, String> getGuiMap(String locale) { return getGuiMap(locale, WebDriverPlatform.UNDEFINED); }
[ "@", "Override", "public", "Map", "<", "String", ",", "String", ">", "getGuiMap", "(", "String", "locale", ")", "{", "return", "getGuiMap", "(", "locale", ",", "WebDriverPlatform", ".", "UNDEFINED", ")", ";", "}" ]
The user needs to provide the locale for which data needs to be read. After successfully reading the data from the input stream, it is placed in the hash map and returned to the users. If the locale provided is not set for a certain element it will fall back to the default locale that is set in the Yaml. If default locale is not provided in the Yaml it will use US. @param locale Signifies the language or site language to read.
[ "The", "user", "needs", "to", "provide", "the", "locale", "for", "which", "data", "needs", "to", "be", "read", ".", "After", "successfully", "reading", "the", "data", "from", "the", "input", "stream", "it", "is", "placed", "in", "the", "hash", "map", "and", "returned", "to", "the", "users", "." ]
train
https://github.com/paypal/SeLion/blob/694d12d0df76db48d0360b16192770c6a4fbdfd2/client/src/main/java/com/paypal/selion/internal/platform/pageyaml/YamlV2Reader.java#L64-L67
Mozu/mozu-java
mozu-javaasync-core/src/main/java/com/mozu/api/urls/commerce/quotes/OrderItemUrl.java
OrderItemUrl.getQuoteItemsByQuoteNameUrl
public static MozuUrl getQuoteItemsByQuoteNameUrl(Integer customerAccountId, String filter, Integer pageSize, String quoteName, String responseFields, String sortBy, Integer startIndex) { """ Get Resource Url for GetQuoteItemsByQuoteName @param customerAccountId The unique identifier of the customer account for which to retrieve wish lists. @param filter A set of filter expressions representing the search parameters for a query. This parameter is optional. Refer to [Sorting and Filtering](../../../../Developer/api-guides/sorting-filtering.htm) for a list of supported filters. @param pageSize When creating paged results from a query, this value indicates the zero-based offset in the complete result set where the returned entities begin. For example, with this parameter set to 25, to get the 51st through the 75th items, set startIndex to 50. @param quoteName @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss. @param sortBy The element to sort the results by and the channel in which the results appear. Either ascending (a-z) or descending (z-a) channel. Optional. Refer to [Sorting and Filtering](../../../../Developer/api-guides/sorting-filtering.htm) for more information. @param startIndex When creating paged results from a query, this value indicates the zero-based offset in the complete result set where the returned entities begin. For example, with pageSize set to 25, to get the 51st through the 75th items, set this parameter to 50. @return String Resource Url """ UrlFormatter formatter = new UrlFormatter("/api/commerce/quotes/customers/{customerAccountId}/{quoteName}/items?startIndex={startIndex}&pageSize={pageSize}&sortBy={sortBy}&filter={filter}&responseFields={responseFields}"); formatter.formatUrl("customerAccountId", customerAccountId); formatter.formatUrl("filter", filter); formatter.formatUrl("pageSize", pageSize); formatter.formatUrl("quoteName", quoteName); formatter.formatUrl("responseFields", responseFields); formatter.formatUrl("sortBy", sortBy); formatter.formatUrl("startIndex", startIndex); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
java
public static MozuUrl getQuoteItemsByQuoteNameUrl(Integer customerAccountId, String filter, Integer pageSize, String quoteName, String responseFields, String sortBy, Integer startIndex) { UrlFormatter formatter = new UrlFormatter("/api/commerce/quotes/customers/{customerAccountId}/{quoteName}/items?startIndex={startIndex}&pageSize={pageSize}&sortBy={sortBy}&filter={filter}&responseFields={responseFields}"); formatter.formatUrl("customerAccountId", customerAccountId); formatter.formatUrl("filter", filter); formatter.formatUrl("pageSize", pageSize); formatter.formatUrl("quoteName", quoteName); formatter.formatUrl("responseFields", responseFields); formatter.formatUrl("sortBy", sortBy); formatter.formatUrl("startIndex", startIndex); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
[ "public", "static", "MozuUrl", "getQuoteItemsByQuoteNameUrl", "(", "Integer", "customerAccountId", ",", "String", "filter", ",", "Integer", "pageSize", ",", "String", "quoteName", ",", "String", "responseFields", ",", "String", "sortBy", ",", "Integer", "startIndex", ")", "{", "UrlFormatter", "formatter", "=", "new", "UrlFormatter", "(", "\"/api/commerce/quotes/customers/{customerAccountId}/{quoteName}/items?startIndex={startIndex}&pageSize={pageSize}&sortBy={sortBy}&filter={filter}&responseFields={responseFields}\"", ")", ";", "formatter", ".", "formatUrl", "(", "\"customerAccountId\"", ",", "customerAccountId", ")", ";", "formatter", ".", "formatUrl", "(", "\"filter\"", ",", "filter", ")", ";", "formatter", ".", "formatUrl", "(", "\"pageSize\"", ",", "pageSize", ")", ";", "formatter", ".", "formatUrl", "(", "\"quoteName\"", ",", "quoteName", ")", ";", "formatter", ".", "formatUrl", "(", "\"responseFields\"", ",", "responseFields", ")", ";", "formatter", ".", "formatUrl", "(", "\"sortBy\"", ",", "sortBy", ")", ";", "formatter", ".", "formatUrl", "(", "\"startIndex\"", ",", "startIndex", ")", ";", "return", "new", "MozuUrl", "(", "formatter", ".", "getResourceUrl", "(", ")", ",", "MozuUrl", ".", "UrlLocation", ".", "TENANT_POD", ")", ";", "}" ]
Get Resource Url for GetQuoteItemsByQuoteName @param customerAccountId The unique identifier of the customer account for which to retrieve wish lists. @param filter A set of filter expressions representing the search parameters for a query. This parameter is optional. Refer to [Sorting and Filtering](../../../../Developer/api-guides/sorting-filtering.htm) for a list of supported filters. @param pageSize When creating paged results from a query, this value indicates the zero-based offset in the complete result set where the returned entities begin. For example, with this parameter set to 25, to get the 51st through the 75th items, set startIndex to 50. @param quoteName @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss. @param sortBy The element to sort the results by and the channel in which the results appear. Either ascending (a-z) or descending (z-a) channel. Optional. Refer to [Sorting and Filtering](../../../../Developer/api-guides/sorting-filtering.htm) for more information. @param startIndex When creating paged results from a query, this value indicates the zero-based offset in the complete result set where the returned entities begin. For example, with pageSize set to 25, to get the 51st through the 75th items, set this parameter to 50. @return String Resource Url
[ "Get", "Resource", "Url", "for", "GetQuoteItemsByQuoteName" ]
train
https://github.com/Mozu/mozu-java/blob/5beadde73601a859f845e3e2fc1077b39c8bea83/mozu-javaasync-core/src/main/java/com/mozu/api/urls/commerce/quotes/OrderItemUrl.java#L65-L76
wildfly/wildfly-core
controller/src/main/java/org/jboss/as/controller/registry/OperationTransformerRegistry.java
OperationTransformerRegistry.resolveResourceTransformer
public ResourceTransformerEntry resolveResourceTransformer(final PathAddress address, final PlaceholderResolver placeholderResolver) { """ Resolve a resource transformer for a given address. @param address the address @param placeholderResolver a placeholder resolver used to resolve children of a placeholder registration @return the resource transformer """ return resolveResourceTransformer(address.iterator(), null, placeholderResolver); }
java
public ResourceTransformerEntry resolveResourceTransformer(final PathAddress address, final PlaceholderResolver placeholderResolver) { return resolveResourceTransformer(address.iterator(), null, placeholderResolver); }
[ "public", "ResourceTransformerEntry", "resolveResourceTransformer", "(", "final", "PathAddress", "address", ",", "final", "PlaceholderResolver", "placeholderResolver", ")", "{", "return", "resolveResourceTransformer", "(", "address", ".", "iterator", "(", ")", ",", "null", ",", "placeholderResolver", ")", ";", "}" ]
Resolve a resource transformer for a given address. @param address the address @param placeholderResolver a placeholder resolver used to resolve children of a placeholder registration @return the resource transformer
[ "Resolve", "a", "resource", "transformer", "for", "a", "given", "address", "." ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/registry/OperationTransformerRegistry.java#L95-L97
cdk/cdk
tool/formula/src/main/java/org/openscience/cdk/tools/manipulator/MolecularFormulaManipulator.java
MolecularFormulaManipulator.getElementCount
public static int getElementCount(IMolecularFormula formula, IElement element) { """ Checks a set of Nodes for the occurrence of the isotopes in the molecular formula from a particular IElement. It returns 0 if the element does not exist. The search is based only on the IElement. @param formula The MolecularFormula to check @param element The IElement object @return The occurrence of this element in this molecular formula """ int count = 0; for (IIsotope isotope : formula.isotopes()) { if (isotope.getSymbol().equals(element.getSymbol())) count += formula.getIsotopeCount(isotope); } return count; }
java
public static int getElementCount(IMolecularFormula formula, IElement element) { int count = 0; for (IIsotope isotope : formula.isotopes()) { if (isotope.getSymbol().equals(element.getSymbol())) count += formula.getIsotopeCount(isotope); } return count; }
[ "public", "static", "int", "getElementCount", "(", "IMolecularFormula", "formula", ",", "IElement", "element", ")", "{", "int", "count", "=", "0", ";", "for", "(", "IIsotope", "isotope", ":", "formula", ".", "isotopes", "(", ")", ")", "{", "if", "(", "isotope", ".", "getSymbol", "(", ")", ".", "equals", "(", "element", ".", "getSymbol", "(", ")", ")", ")", "count", "+=", "formula", ".", "getIsotopeCount", "(", "isotope", ")", ";", "}", "return", "count", ";", "}" ]
Checks a set of Nodes for the occurrence of the isotopes in the molecular formula from a particular IElement. It returns 0 if the element does not exist. The search is based only on the IElement. @param formula The MolecularFormula to check @param element The IElement object @return The occurrence of this element in this molecular formula
[ "Checks", "a", "set", "of", "Nodes", "for", "the", "occurrence", "of", "the", "isotopes", "in", "the", "molecular", "formula", "from", "a", "particular", "IElement", ".", "It", "returns", "0", "if", "the", "element", "does", "not", "exist", ".", "The", "search", "is", "based", "only", "on", "the", "IElement", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/tool/formula/src/main/java/org/openscience/cdk/tools/manipulator/MolecularFormulaManipulator.java#L127-L134