repository_name
stringlengths
7
54
func_path_in_repository
stringlengths
18
218
func_name
stringlengths
5
140
whole_func_string
stringlengths
79
3.99k
language
stringclasses
1 value
func_code_string
stringlengths
79
3.99k
func_code_tokens
listlengths
20
624
func_documentation_string
stringlengths
61
1.96k
func_documentation_tokens
listlengths
1
478
split_name
stringclasses
1 value
func_code_url
stringlengths
107
339
m-m-m/util
pojopath/src/main/java/net/sf/mmm/util/pojo/path/base/AbstractPojoPathNavigator.java
AbstractPojoPathNavigator.getPath
private CachingPojoPath getPath(Object pojo, String pojoPath, PojoPathMode mode, PojoPathContext context) { if (pojo == null) { if (mode == PojoPathMode.RETURN_IF_NULL) { return null; } else if (mode == PojoPathMode.RETURN_IF_NULL) { throw new PojoPathCreationException(null, pojoPath); } else { throw new PojoPathSegmentIsNullException(null, pojoPath); } } PojoPathState state = createState(pojo, pojoPath, mode, context); return getRecursive(pojoPath, context, state); }
java
private CachingPojoPath getPath(Object pojo, String pojoPath, PojoPathMode mode, PojoPathContext context) { if (pojo == null) { if (mode == PojoPathMode.RETURN_IF_NULL) { return null; } else if (mode == PojoPathMode.RETURN_IF_NULL) { throw new PojoPathCreationException(null, pojoPath); } else { throw new PojoPathSegmentIsNullException(null, pojoPath); } } PojoPathState state = createState(pojo, pojoPath, mode, context); return getRecursive(pojoPath, context, state); }
[ "private", "CachingPojoPath", "getPath", "(", "Object", "pojo", ",", "String", "pojoPath", ",", "PojoPathMode", "mode", ",", "PojoPathContext", "context", ")", "{", "if", "(", "pojo", "==", "null", ")", "{", "if", "(", "mode", "==", "PojoPathMode", ".", "RETURN_IF_NULL", ")", "{", "return", "null", ";", "}", "else", "if", "(", "mode", "==", "PojoPathMode", ".", "RETURN_IF_NULL", ")", "{", "throw", "new", "PojoPathCreationException", "(", "null", ",", "pojoPath", ")", ";", "}", "else", "{", "throw", "new", "PojoPathSegmentIsNullException", "(", "null", ",", "pojoPath", ")", ";", "}", "}", "PojoPathState", "state", "=", "createState", "(", "pojo", ",", "pojoPath", ",", "mode", ",", "context", ")", ";", "return", "getRecursive", "(", "pojoPath", ",", "context", ",", "state", ")", ";", "}" ]
This method contains the internal implementation of {@link #get(Object, String, PojoPathMode, PojoPathContext)}. @param pojo is the initial {@link net.sf.mmm.util.pojo.api.Pojo} to operate on. @param pojoPath is the {@link net.sf.mmm.util.pojo.path.api.PojoPath} to navigate. @param mode is the {@link PojoPathMode mode} that determines how to deal with {@code null} values. @param context is the {@link PojoPathContext} for this operation. @return the {@link CachingPojoPath} for the given {@code pojoPath}.
[ "This", "method", "contains", "the", "internal", "implementation", "of", "{", "@link", "#get", "(", "Object", "String", "PojoPathMode", "PojoPathContext", ")", "}", "." ]
train
https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/pojopath/src/main/java/net/sf/mmm/util/pojo/path/base/AbstractPojoPathNavigator.java#L281-L294
Coveros/selenified
src/main/java/com/coveros/selenified/element/Element.java
Element.isSelect
private boolean isSelect(String action, String expected) { // wait for element to be displayed if (!is.select()) { reporter.fail(action, expected, Element.CANT_SELECT + prettyOutput() + NOT_A_SELECT); // indicates element not an input return false; } return true; }
java
private boolean isSelect(String action, String expected) { // wait for element to be displayed if (!is.select()) { reporter.fail(action, expected, Element.CANT_SELECT + prettyOutput() + NOT_A_SELECT); // indicates element not an input return false; } return true; }
[ "private", "boolean", "isSelect", "(", "String", "action", ",", "String", "expected", ")", "{", "// wait for element to be displayed", "if", "(", "!", "is", ".", "select", "(", ")", ")", "{", "reporter", ".", "fail", "(", "action", ",", "expected", ",", "Element", ".", "CANT_SELECT", "+", "prettyOutput", "(", ")", "+", "NOT_A_SELECT", ")", ";", "// indicates element not an input", "return", "false", ";", "}", "return", "true", ";", "}" ]
Determines if the element is a select. @param action - what action is occurring @param expected - what is the expected result @return Boolean: is the element enabled?
[ "Determines", "if", "the", "element", "is", "a", "select", "." ]
train
https://github.com/Coveros/selenified/blob/396cc1f010dd69eed33cc5061c41253de246a4cd/src/main/java/com/coveros/selenified/element/Element.java#L675-L683
Azure/azure-sdk-for-java
containerservice/resource-manager/v2019_02_01/src/main/java/com/microsoft/azure/management/containerservice/v2019_02_01/implementation/ManagedClustersInner.java
ManagedClustersInner.updateTagsAsync
public Observable<ManagedClusterInner> updateTagsAsync(String resourceGroupName, String resourceName) { return updateTagsWithServiceResponseAsync(resourceGroupName, resourceName).map(new Func1<ServiceResponse<ManagedClusterInner>, ManagedClusterInner>() { @Override public ManagedClusterInner call(ServiceResponse<ManagedClusterInner> response) { return response.body(); } }); }
java
public Observable<ManagedClusterInner> updateTagsAsync(String resourceGroupName, String resourceName) { return updateTagsWithServiceResponseAsync(resourceGroupName, resourceName).map(new Func1<ServiceResponse<ManagedClusterInner>, ManagedClusterInner>() { @Override public ManagedClusterInner call(ServiceResponse<ManagedClusterInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "ManagedClusterInner", ">", "updateTagsAsync", "(", "String", "resourceGroupName", ",", "String", "resourceName", ")", "{", "return", "updateTagsWithServiceResponseAsync", "(", "resourceGroupName", ",", "resourceName", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "ManagedClusterInner", ">", ",", "ManagedClusterInner", ">", "(", ")", "{", "@", "Override", "public", "ManagedClusterInner", "call", "(", "ServiceResponse", "<", "ManagedClusterInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Updates tags on a managed cluster. Updates a managed cluster with the specified tags. @param resourceGroupName The name of the resource group. @param resourceName The name of the managed cluster resource. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Updates", "tags", "on", "a", "managed", "cluster", ".", "Updates", "a", "managed", "cluster", "with", "the", "specified", "tags", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/containerservice/resource-manager/v2019_02_01/src/main/java/com/microsoft/azure/management/containerservice/v2019_02_01/implementation/ManagedClustersInner.java#L1040-L1047
samskivert/pythagoras
src/main/java/pythagoras/f/Lines.java
Lines.pointSegDist
public static float pointSegDist (float px, float py, float x1, float y1, float x2, float y2) { return FloatMath.sqrt(pointSegDistSq(px, py, x1, y1, x2, y2)); }
java
public static float pointSegDist (float px, float py, float x1, float y1, float x2, float y2) { return FloatMath.sqrt(pointSegDistSq(px, py, x1, y1, x2, y2)); }
[ "public", "static", "float", "pointSegDist", "(", "float", "px", ",", "float", "py", ",", "float", "x1", ",", "float", "y1", ",", "float", "x2", ",", "float", "y2", ")", "{", "return", "FloatMath", ".", "sqrt", "(", "pointSegDistSq", "(", "px", ",", "py", ",", "x1", ",", "y1", ",", "x2", ",", "y2", ")", ")", ";", "}" ]
Returns the distance between the specified point and the specified line segment.
[ "Returns", "the", "distance", "between", "the", "specified", "point", "and", "the", "specified", "line", "segment", "." ]
train
https://github.com/samskivert/pythagoras/blob/b8fea743ee8a7d742ad9c06ee4f11f50571fbd32/src/main/java/pythagoras/f/Lines.java#L121-L123
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/inverse/InvertMatrix.java
InvertMatrix.pinvert
public static INDArray pinvert(INDArray arr, boolean inPlace) { // TODO : do it natively instead of relying on commons-maths RealMatrix realMatrix = CheckUtil.convertToApacheMatrix(arr); QRDecomposition decomposition = new QRDecomposition(realMatrix, 0); DecompositionSolver solver = decomposition.getSolver(); if (!solver.isNonSingular()) { throw new IllegalArgumentException("invalid array: must be singular matrix"); } RealMatrix pinvRM = solver.getInverse(); INDArray pseudoInverse = CheckUtil.convertFromApacheMatrix(pinvRM, arr.dataType()); if (inPlace) arr.assign(pseudoInverse); return pseudoInverse; }
java
public static INDArray pinvert(INDArray arr, boolean inPlace) { // TODO : do it natively instead of relying on commons-maths RealMatrix realMatrix = CheckUtil.convertToApacheMatrix(arr); QRDecomposition decomposition = new QRDecomposition(realMatrix, 0); DecompositionSolver solver = decomposition.getSolver(); if (!solver.isNonSingular()) { throw new IllegalArgumentException("invalid array: must be singular matrix"); } RealMatrix pinvRM = solver.getInverse(); INDArray pseudoInverse = CheckUtil.convertFromApacheMatrix(pinvRM, arr.dataType()); if (inPlace) arr.assign(pseudoInverse); return pseudoInverse; }
[ "public", "static", "INDArray", "pinvert", "(", "INDArray", "arr", ",", "boolean", "inPlace", ")", "{", "// TODO : do it natively instead of relying on commons-maths", "RealMatrix", "realMatrix", "=", "CheckUtil", ".", "convertToApacheMatrix", "(", "arr", ")", ";", "QRDecomposition", "decomposition", "=", "new", "QRDecomposition", "(", "realMatrix", ",", "0", ")", ";", "DecompositionSolver", "solver", "=", "decomposition", ".", "getSolver", "(", ")", ";", "if", "(", "!", "solver", ".", "isNonSingular", "(", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"invalid array: must be singular matrix\"", ")", ";", "}", "RealMatrix", "pinvRM", "=", "solver", ".", "getInverse", "(", ")", ";", "INDArray", "pseudoInverse", "=", "CheckUtil", ".", "convertFromApacheMatrix", "(", "pinvRM", ",", "arr", ".", "dataType", "(", ")", ")", ";", "if", "(", "inPlace", ")", "arr", ".", "assign", "(", "pseudoInverse", ")", ";", "return", "pseudoInverse", ";", "}" ]
Calculates pseudo inverse of a matrix using QR decomposition @param arr the array to invert @return the pseudo inverted matrix
[ "Calculates", "pseudo", "inverse", "of", "a", "matrix", "using", "QR", "decomposition" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/inverse/InvertMatrix.java#L76-L96
eclipse/hawkbit
hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/UserDetailsFormatter.java
UserDetailsFormatter.loadAndFormatUsername
public static String loadAndFormatUsername(final String username, final int expectedNameLength) { final UserDetails userDetails = loadUserByUsername(username); return formatUserName(expectedNameLength, userDetails); }
java
public static String loadAndFormatUsername(final String username, final int expectedNameLength) { final UserDetails userDetails = loadUserByUsername(username); return formatUserName(expectedNameLength, userDetails); }
[ "public", "static", "String", "loadAndFormatUsername", "(", "final", "String", "username", ",", "final", "int", "expectedNameLength", ")", "{", "final", "UserDetails", "userDetails", "=", "loadUserByUsername", "(", "username", ")", ";", "return", "formatUserName", "(", "expectedNameLength", ",", "userDetails", ")", ";", "}" ]
Load user details by the user name and format the user name. If the loaded {@link UserDetails} is not an instance of a {@link UserPrincipal}, then just the {@link UserDetails#getUsername()} will return. If first and last name available, they will combined. Otherwise the {@link UserPrincipal#getLoginname()} will formatted. The formatted name is reduced to 100 characters. @param username the user name @param expectedNameLength the name size of each name part @return the formatted user name (max expectedNameLength characters) cannot be <null>
[ "Load", "user", "details", "by", "the", "user", "name", "and", "format", "the", "user", "name", ".", "If", "the", "loaded", "{", "@link", "UserDetails", "}", "is", "not", "an", "instance", "of", "a", "{", "@link", "UserPrincipal", "}", "then", "just", "the", "{", "@link", "UserDetails#getUsername", "()", "}", "will", "return", "." ]
train
https://github.com/eclipse/hawkbit/blob/9884452ad42f3b4827461606d8a9215c8625a7fe/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/UserDetailsFormatter.java#L113-L116
wisdom-framework/wisdom
framework/thymeleaf-template-engine/src/main/java/org/wisdom/template/thymeleaf/impl/WisdomMessageResolver.java
WisdomMessageResolver.resolveMessage
@Override public MessageResolution resolveMessage(Arguments arguments, String key, Object[] messageParameters) { Locale[] locales = getLocales(); String message = i18n.get(locales, key, messageParameters); // Same policy as the Thymeleaf standard message resolver. if (message == null) { return null; } return new MessageResolution(message); }
java
@Override public MessageResolution resolveMessage(Arguments arguments, String key, Object[] messageParameters) { Locale[] locales = getLocales(); String message = i18n.get(locales, key, messageParameters); // Same policy as the Thymeleaf standard message resolver. if (message == null) { return null; } return new MessageResolution(message); }
[ "@", "Override", "public", "MessageResolution", "resolveMessage", "(", "Arguments", "arguments", ",", "String", "key", ",", "Object", "[", "]", "messageParameters", ")", "{", "Locale", "[", "]", "locales", "=", "getLocales", "(", ")", ";", "String", "message", "=", "i18n", ".", "get", "(", "locales", ",", "key", ",", "messageParameters", ")", ";", "// Same policy as the Thymeleaf standard message resolver.", "if", "(", "message", "==", "null", ")", "{", "return", "null", ";", "}", "return", "new", "MessageResolution", "(", "message", ")", ";", "}" ]
<p> Resolve the message, returning a {@link MessageResolution} object. </p> <p> If the message cannot be resolved, this method should return null. </p> @param arguments the {@link Arguments} object being used for template processing @param key the message key @param messageParameters the (optional) message parameters @return a {@link MessageResolution} object containing the resolved message, {@literal null} is returned when the resolver cannot retrieve a message for the given key. This policy is compliant with the (Thymeleaf) standard message resolver.
[ "<p", ">", "Resolve", "the", "message", "returning", "a", "{", "@link", "MessageResolution", "}", "object", ".", "<", "/", "p", ">", "<p", ">", "If", "the", "message", "cannot", "be", "resolved", "this", "method", "should", "return", "null", ".", "<", "/", "p", ">" ]
train
https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/framework/thymeleaf-template-engine/src/main/java/org/wisdom/template/thymeleaf/impl/WisdomMessageResolver.java#L63-L76
sagiegurari/fax4j
src/main/java/org/fax4j/spi/FaxClientSpiFactory.java
FaxClientSpiFactory.createChildFaxClientSpi
public static FaxClientSpi createChildFaxClientSpi(String type,Properties configuration) { //create fax client SPI FaxClientSpi faxClientSpi=FaxClientSpiFactory.createFaxClientSpiImpl(type,configuration,true); return faxClientSpi; }
java
public static FaxClientSpi createChildFaxClientSpi(String type,Properties configuration) { //create fax client SPI FaxClientSpi faxClientSpi=FaxClientSpiFactory.createFaxClientSpiImpl(type,configuration,true); return faxClientSpi; }
[ "public", "static", "FaxClientSpi", "createChildFaxClientSpi", "(", "String", "type", ",", "Properties", "configuration", ")", "{", "//create fax client SPI", "FaxClientSpi", "faxClientSpi", "=", "FaxClientSpiFactory", ".", "createFaxClientSpiImpl", "(", "type", ",", "configuration", ",", "true", ")", ";", "return", "faxClientSpi", ";", "}" ]
This function creates a new fax client SPI based on the provided configuration.<br> This is an internal framework method and should not be invoked by classes outside the fax4j framework. @param type The fax client type (may be null for default type) @param configuration The fax client configuration (may be null) @return The fax client SPI instance
[ "This", "function", "creates", "a", "new", "fax", "client", "SPI", "based", "on", "the", "provided", "configuration", ".", "<br", ">", "This", "is", "an", "internal", "framework", "method", "and", "should", "not", "be", "invoked", "by", "classes", "outside", "the", "fax4j", "framework", "." ]
train
https://github.com/sagiegurari/fax4j/blob/42fa51acabe7bf279e27ab3dd1cf76146b27955f/src/main/java/org/fax4j/spi/FaxClientSpiFactory.java#L217-L223
ops4j/org.ops4j.base
ops4j-base-lang/src/main/java/org/ops4j/lang/PreConditionException.java
PreConditionException.validateGreaterThan
public static void validateGreaterThan( Number value, Number limit, String identifier ) throws PreConditionException { if( value.doubleValue() > limit.doubleValue() ) { return; } throw new PreConditionException( identifier + " was not greater than " + limit + ". Was: " + value ); }
java
public static void validateGreaterThan( Number value, Number limit, String identifier ) throws PreConditionException { if( value.doubleValue() > limit.doubleValue() ) { return; } throw new PreConditionException( identifier + " was not greater than " + limit + ". Was: " + value ); }
[ "public", "static", "void", "validateGreaterThan", "(", "Number", "value", ",", "Number", "limit", ",", "String", "identifier", ")", "throws", "PreConditionException", "{", "if", "(", "value", ".", "doubleValue", "(", ")", ">", "limit", ".", "doubleValue", "(", ")", ")", "{", "return", ";", "}", "throw", "new", "PreConditionException", "(", "identifier", "+", "\" was not greater than \"", "+", "limit", "+", "\". Was: \"", "+", "value", ")", ";", "}" ]
Validates that the value is greater than a limit. <p/> This method ensures that <code>value > limit</code>. @param identifier The name of the object. @param limit The limit that the value must exceed. @param value The value to be tested. @throws PreConditionException if the condition is not met.
[ "Validates", "that", "the", "value", "is", "greater", "than", "a", "limit", ".", "<p", "/", ">", "This", "method", "ensures", "that", "<code", ">", "value", ">", "limit<", "/", "code", ">", "." ]
train
https://github.com/ops4j/org.ops4j.base/blob/b0e742c0d9511f6b19ca64da2ebaf30b7a47256a/ops4j-base-lang/src/main/java/org/ops4j/lang/PreConditionException.java#L127-L135
jnr/jnr-x86asm
src/main/java/jnr/x86asm/SerializerIntrinsics.java
SerializerIntrinsics.pcmpestrm
public final void pcmpestrm(XMMRegister dst, XMMRegister src, Immediate imm8) { emitX86(INST_PCMPESTRM, dst, src, imm8); }
java
public final void pcmpestrm(XMMRegister dst, XMMRegister src, Immediate imm8) { emitX86(INST_PCMPESTRM, dst, src, imm8); }
[ "public", "final", "void", "pcmpestrm", "(", "XMMRegister", "dst", ",", "XMMRegister", "src", ",", "Immediate", "imm8", ")", "{", "emitX86", "(", "INST_PCMPESTRM", ",", "dst", ",", "src", ",", "imm8", ")", ";", "}" ]
Packed Compare Explicit Length Strings, Return Mask (SSE4.2).
[ "Packed", "Compare", "Explicit", "Length", "Strings", "Return", "Mask", "(", "SSE4", ".", "2", ")", "." ]
train
https://github.com/jnr/jnr-x86asm/blob/fdcf68fb3dae49e607a49e33399e3dad1ada5536/src/main/java/jnr/x86asm/SerializerIntrinsics.java#L6540-L6543
elki-project/elki
elki-clustering/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/subspace/PROCLUS.java
PROCLUS.findDimensions
private long[][] findDimensions(ArrayDBIDs medoids, Relation<V> database, DistanceQuery<V> distFunc, RangeQuery<V> rangeQuery) { // get localities DataStore<DBIDs> localities = getLocalities(medoids, distFunc, rangeQuery); // compute x_ij = avg distance from points in l_i to medoid m_i final int dim = RelationUtil.dimensionality(database); final int numc = medoids.size(); double[][] averageDistances = new double[numc][]; for(DBIDArrayIter iter = medoids.iter(); iter.valid(); iter.advance()) { V medoid_i = database.get(iter); DBIDs l_i = localities.get(iter); double[] x_i = new double[dim]; for(DBIDIter qr = l_i.iter(); qr.valid(); qr.advance()) { V o = database.get(qr); for(int d = 0; d < dim; d++) { x_i[d] += Math.abs(medoid_i.doubleValue(d) - o.doubleValue(d)); } } for(int d = 0; d < dim; d++) { x_i[d] /= l_i.size(); } averageDistances[iter.getOffset()] = x_i; } List<DoubleIntInt> z_ijs = computeZijs(averageDistances, dim); return computeDimensionMap(z_ijs, dim, numc); }
java
private long[][] findDimensions(ArrayDBIDs medoids, Relation<V> database, DistanceQuery<V> distFunc, RangeQuery<V> rangeQuery) { // get localities DataStore<DBIDs> localities = getLocalities(medoids, distFunc, rangeQuery); // compute x_ij = avg distance from points in l_i to medoid m_i final int dim = RelationUtil.dimensionality(database); final int numc = medoids.size(); double[][] averageDistances = new double[numc][]; for(DBIDArrayIter iter = medoids.iter(); iter.valid(); iter.advance()) { V medoid_i = database.get(iter); DBIDs l_i = localities.get(iter); double[] x_i = new double[dim]; for(DBIDIter qr = l_i.iter(); qr.valid(); qr.advance()) { V o = database.get(qr); for(int d = 0; d < dim; d++) { x_i[d] += Math.abs(medoid_i.doubleValue(d) - o.doubleValue(d)); } } for(int d = 0; d < dim; d++) { x_i[d] /= l_i.size(); } averageDistances[iter.getOffset()] = x_i; } List<DoubleIntInt> z_ijs = computeZijs(averageDistances, dim); return computeDimensionMap(z_ijs, dim, numc); }
[ "private", "long", "[", "]", "[", "]", "findDimensions", "(", "ArrayDBIDs", "medoids", ",", "Relation", "<", "V", ">", "database", ",", "DistanceQuery", "<", "V", ">", "distFunc", ",", "RangeQuery", "<", "V", ">", "rangeQuery", ")", "{", "// get localities", "DataStore", "<", "DBIDs", ">", "localities", "=", "getLocalities", "(", "medoids", ",", "distFunc", ",", "rangeQuery", ")", ";", "// compute x_ij = avg distance from points in l_i to medoid m_i", "final", "int", "dim", "=", "RelationUtil", ".", "dimensionality", "(", "database", ")", ";", "final", "int", "numc", "=", "medoids", ".", "size", "(", ")", ";", "double", "[", "]", "[", "]", "averageDistances", "=", "new", "double", "[", "numc", "]", "[", "", "]", ";", "for", "(", "DBIDArrayIter", "iter", "=", "medoids", ".", "iter", "(", ")", ";", "iter", ".", "valid", "(", ")", ";", "iter", ".", "advance", "(", ")", ")", "{", "V", "medoid_i", "=", "database", ".", "get", "(", "iter", ")", ";", "DBIDs", "l_i", "=", "localities", ".", "get", "(", "iter", ")", ";", "double", "[", "]", "x_i", "=", "new", "double", "[", "dim", "]", ";", "for", "(", "DBIDIter", "qr", "=", "l_i", ".", "iter", "(", ")", ";", "qr", ".", "valid", "(", ")", ";", "qr", ".", "advance", "(", ")", ")", "{", "V", "o", "=", "database", ".", "get", "(", "qr", ")", ";", "for", "(", "int", "d", "=", "0", ";", "d", "<", "dim", ";", "d", "++", ")", "{", "x_i", "[", "d", "]", "+=", "Math", ".", "abs", "(", "medoid_i", ".", "doubleValue", "(", "d", ")", "-", "o", ".", "doubleValue", "(", "d", ")", ")", ";", "}", "}", "for", "(", "int", "d", "=", "0", ";", "d", "<", "dim", ";", "d", "++", ")", "{", "x_i", "[", "d", "]", "/=", "l_i", ".", "size", "(", ")", ";", "}", "averageDistances", "[", "iter", ".", "getOffset", "(", ")", "]", "=", "x_i", ";", "}", "List", "<", "DoubleIntInt", ">", "z_ijs", "=", "computeZijs", "(", "averageDistances", ",", "dim", ")", ";", "return", "computeDimensionMap", "(", "z_ijs", ",", "dim", ",", "numc", ")", ";", "}" ]
Determines the set of correlated dimensions for each medoid in the specified medoid set. @param medoids the set of medoids @param database the database containing the objects @param distFunc the distance function @return the set of correlated dimensions for each medoid in the specified medoid set
[ "Determines", "the", "set", "of", "correlated", "dimensions", "for", "each", "medoid", "in", "the", "specified", "medoid", "set", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-clustering/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/subspace/PROCLUS.java#L378-L405
sdl/odata
odata_renderer/src/main/java/com/sdl/odata/renderer/json/writer/JsonWriter.java
JsonWriter.writeJson
private String writeJson(Object data, Map<String, Object> meta) throws IOException, NoSuchFieldException, IllegalAccessException, ODataEdmException, ODataRenderException { ByteArrayOutputStream stream = new ByteArrayOutputStream(); jsonGenerator = JSON_FACTORY.createGenerator(stream, JsonEncoding.UTF8); jsonGenerator.writeStartObject(); // Write @odata constants entitySet = (data instanceof List) ? getEntitySet((List<?>) data) : getEntitySet(data); jsonGenerator.writeStringField(CONTEXT, contextURL); // Write @odata.count if requested and provided. if (hasCountOption(odataUri) && data instanceof List && meta != null && meta.containsKey("count")) { long count; Object countObj = meta.get("count"); if (countObj instanceof Integer) { count = ((Integer) countObj).longValue(); } else { count = (long) countObj; } jsonGenerator.writeNumberField(COUNT, count); } if (!(data instanceof List)) { if (entitySet != null) { jsonGenerator.writeStringField(ID, String.format("%s(%s)", getEntityName(entityDataModel, data), formatEntityKey(entityDataModel, data))); } else { jsonGenerator.writeStringField(ID, String.format("%s", getEntityName(entityDataModel, data))); } } // Write feed if (data instanceof List) { marshallEntities((List<?>) data); } else { marshall(data, this.entityDataModel.getType(data.getClass())); } jsonGenerator.writeEndObject(); jsonGenerator.close(); return stream.toString(StandardCharsets.UTF_8.name()); }
java
private String writeJson(Object data, Map<String, Object> meta) throws IOException, NoSuchFieldException, IllegalAccessException, ODataEdmException, ODataRenderException { ByteArrayOutputStream stream = new ByteArrayOutputStream(); jsonGenerator = JSON_FACTORY.createGenerator(stream, JsonEncoding.UTF8); jsonGenerator.writeStartObject(); // Write @odata constants entitySet = (data instanceof List) ? getEntitySet((List<?>) data) : getEntitySet(data); jsonGenerator.writeStringField(CONTEXT, contextURL); // Write @odata.count if requested and provided. if (hasCountOption(odataUri) && data instanceof List && meta != null && meta.containsKey("count")) { long count; Object countObj = meta.get("count"); if (countObj instanceof Integer) { count = ((Integer) countObj).longValue(); } else { count = (long) countObj; } jsonGenerator.writeNumberField(COUNT, count); } if (!(data instanceof List)) { if (entitySet != null) { jsonGenerator.writeStringField(ID, String.format("%s(%s)", getEntityName(entityDataModel, data), formatEntityKey(entityDataModel, data))); } else { jsonGenerator.writeStringField(ID, String.format("%s", getEntityName(entityDataModel, data))); } } // Write feed if (data instanceof List) { marshallEntities((List<?>) data); } else { marshall(data, this.entityDataModel.getType(data.getClass())); } jsonGenerator.writeEndObject(); jsonGenerator.close(); return stream.toString(StandardCharsets.UTF_8.name()); }
[ "private", "String", "writeJson", "(", "Object", "data", ",", "Map", "<", "String", ",", "Object", ">", "meta", ")", "throws", "IOException", ",", "NoSuchFieldException", ",", "IllegalAccessException", ",", "ODataEdmException", ",", "ODataRenderException", "{", "ByteArrayOutputStream", "stream", "=", "new", "ByteArrayOutputStream", "(", ")", ";", "jsonGenerator", "=", "JSON_FACTORY", ".", "createGenerator", "(", "stream", ",", "JsonEncoding", ".", "UTF8", ")", ";", "jsonGenerator", ".", "writeStartObject", "(", ")", ";", "// Write @odata constants", "entitySet", "=", "(", "data", "instanceof", "List", ")", "?", "getEntitySet", "(", "(", "List", "<", "?", ">", ")", "data", ")", ":", "getEntitySet", "(", "data", ")", ";", "jsonGenerator", ".", "writeStringField", "(", "CONTEXT", ",", "contextURL", ")", ";", "// Write @odata.count if requested and provided.", "if", "(", "hasCountOption", "(", "odataUri", ")", "&&", "data", "instanceof", "List", "&&", "meta", "!=", "null", "&&", "meta", ".", "containsKey", "(", "\"count\"", ")", ")", "{", "long", "count", ";", "Object", "countObj", "=", "meta", ".", "get", "(", "\"count\"", ")", ";", "if", "(", "countObj", "instanceof", "Integer", ")", "{", "count", "=", "(", "(", "Integer", ")", "countObj", ")", ".", "longValue", "(", ")", ";", "}", "else", "{", "count", "=", "(", "long", ")", "countObj", ";", "}", "jsonGenerator", ".", "writeNumberField", "(", "COUNT", ",", "count", ")", ";", "}", "if", "(", "!", "(", "data", "instanceof", "List", ")", ")", "{", "if", "(", "entitySet", "!=", "null", ")", "{", "jsonGenerator", ".", "writeStringField", "(", "ID", ",", "String", ".", "format", "(", "\"%s(%s)\"", ",", "getEntityName", "(", "entityDataModel", ",", "data", ")", ",", "formatEntityKey", "(", "entityDataModel", ",", "data", ")", ")", ")", ";", "}", "else", "{", "jsonGenerator", ".", "writeStringField", "(", "ID", ",", "String", ".", "format", "(", "\"%s\"", ",", "getEntityName", "(", "entityDataModel", ",", "data", ")", ")", ")", ";", "}", "}", "// Write feed", "if", "(", "data", "instanceof", "List", ")", "{", "marshallEntities", "(", "(", "List", "<", "?", ">", ")", "data", ")", ";", "}", "else", "{", "marshall", "(", "data", ",", "this", ".", "entityDataModel", ".", "getType", "(", "data", ".", "getClass", "(", ")", ")", ")", ";", "}", "jsonGenerator", ".", "writeEndObject", "(", ")", ";", "jsonGenerator", ".", "close", "(", ")", ";", "return", "stream", ".", "toString", "(", "StandardCharsets", ".", "UTF_8", ".", "name", "(", ")", ")", ";", "}" ]
Write the given data to the JSON stream. The data to write will be either a single entity or a feed depending on whether it is a single object or list. @param data The given data. @param meta Additional values to write. @return The written JSON stream. @throws ODataRenderException if unable to render
[ "Write", "the", "given", "data", "to", "the", "JSON", "stream", ".", "The", "data", "to", "write", "will", "be", "either", "a", "single", "entity", "or", "a", "feed", "depending", "on", "whether", "it", "is", "a", "single", "object", "or", "list", "." ]
train
https://github.com/sdl/odata/blob/eb747d73e9af0f4e59a25b82ed656e526a7e2189/odata_renderer/src/main/java/com/sdl/odata/renderer/json/writer/JsonWriter.java#L168-L215
liferay/com-liferay-commerce
commerce-user-segment-service/src/main/java/com/liferay/commerce/user/segment/service/persistence/impl/CommerceUserSegmentEntryPersistenceImpl.java
CommerceUserSegmentEntryPersistenceImpl.removeByG_K
@Override public CommerceUserSegmentEntry removeByG_K(long groupId, String key) throws NoSuchUserSegmentEntryException { CommerceUserSegmentEntry commerceUserSegmentEntry = findByG_K(groupId, key); return remove(commerceUserSegmentEntry); }
java
@Override public CommerceUserSegmentEntry removeByG_K(long groupId, String key) throws NoSuchUserSegmentEntryException { CommerceUserSegmentEntry commerceUserSegmentEntry = findByG_K(groupId, key); return remove(commerceUserSegmentEntry); }
[ "@", "Override", "public", "CommerceUserSegmentEntry", "removeByG_K", "(", "long", "groupId", ",", "String", "key", ")", "throws", "NoSuchUserSegmentEntryException", "{", "CommerceUserSegmentEntry", "commerceUserSegmentEntry", "=", "findByG_K", "(", "groupId", ",", "key", ")", ";", "return", "remove", "(", "commerceUserSegmentEntry", ")", ";", "}" ]
Removes the commerce user segment entry where groupId = &#63; and key = &#63; from the database. @param groupId the group ID @param key the key @return the commerce user segment entry that was removed
[ "Removes", "the", "commerce", "user", "segment", "entry", "where", "groupId", "=", "&#63", ";", "and", "key", "=", "&#63", ";", "from", "the", "database", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-user-segment-service/src/main/java/com/liferay/commerce/user/segment/service/persistence/impl/CommerceUserSegmentEntryPersistenceImpl.java#L1142-L1149
kikinteractive/ice
ice/src/main/java/com/kik/config/ice/internal/MethodIdProxyFactory.java
MethodIdProxyFactory.getProxy
public static <C> C getProxy(final Class<C> configInterface, final Optional<String> scopeNameOpt) { final ClassAndScope key = new ClassAndScope(configInterface, scopeNameOpt); final C methodIdProxy; if (proxyMap.containsKey(key)) { methodIdProxy = (C) proxyMap.get(key); } else { methodIdProxy = createMethodIdProxy(configInterface, scopeNameOpt); proxyMap.put(key, methodIdProxy); } return methodIdProxy; }
java
public static <C> C getProxy(final Class<C> configInterface, final Optional<String> scopeNameOpt) { final ClassAndScope key = new ClassAndScope(configInterface, scopeNameOpt); final C methodIdProxy; if (proxyMap.containsKey(key)) { methodIdProxy = (C) proxyMap.get(key); } else { methodIdProxy = createMethodIdProxy(configInterface, scopeNameOpt); proxyMap.put(key, methodIdProxy); } return methodIdProxy; }
[ "public", "static", "<", "C", ">", "C", "getProxy", "(", "final", "Class", "<", "C", ">", "configInterface", ",", "final", "Optional", "<", "String", ">", "scopeNameOpt", ")", "{", "final", "ClassAndScope", "key", "=", "new", "ClassAndScope", "(", "configInterface", ",", "scopeNameOpt", ")", ";", "final", "C", "methodIdProxy", ";", "if", "(", "proxyMap", ".", "containsKey", "(", "key", ")", ")", "{", "methodIdProxy", "=", "(", "C", ")", "proxyMap", ".", "get", "(", "key", ")", ";", "}", "else", "{", "methodIdProxy", "=", "createMethodIdProxy", "(", "configInterface", ",", "scopeNameOpt", ")", ";", "proxyMap", ".", "put", "(", "key", ",", "methodIdProxy", ")", ";", "}", "return", "methodIdProxy", ";", "}" ]
Produces a proxy impl of a configuration interface to identify methods called on it
[ "Produces", "a", "proxy", "impl", "of", "a", "configuration", "interface", "to", "identify", "methods", "called", "on", "it" ]
train
https://github.com/kikinteractive/ice/blob/0c58d7bf2d9f6504892d0768d6022fcfa6df7514/ice/src/main/java/com/kik/config/ice/internal/MethodIdProxyFactory.java#L50-L63
Azure/azure-sdk-for-java
mediaservices/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/implementation/StreamingEndpointsInner.java
StreamingEndpointsInner.beginScale
public void beginScale(String resourceGroupName, String accountName, String streamingEndpointName) { beginScaleWithServiceResponseAsync(resourceGroupName, accountName, streamingEndpointName).toBlocking().single().body(); }
java
public void beginScale(String resourceGroupName, String accountName, String streamingEndpointName) { beginScaleWithServiceResponseAsync(resourceGroupName, accountName, streamingEndpointName).toBlocking().single().body(); }
[ "public", "void", "beginScale", "(", "String", "resourceGroupName", ",", "String", "accountName", ",", "String", "streamingEndpointName", ")", "{", "beginScaleWithServiceResponseAsync", "(", "resourceGroupName", ",", "accountName", ",", "streamingEndpointName", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Scale StreamingEndpoint. Scales an existing StreamingEndpoint. @param resourceGroupName The name of the resource group within the Azure subscription. @param accountName The Media Services account name. @param streamingEndpointName The name of the StreamingEndpoint. @throws IllegalArgumentException thrown if parameters fail the validation @throws ApiErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
[ "Scale", "StreamingEndpoint", ".", "Scales", "an", "existing", "StreamingEndpoint", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/mediaservices/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/implementation/StreamingEndpointsInner.java#L1644-L1646
smartsheet-platform/smartsheet-java-sdk
src/main/java/com/smartsheet/api/internal/SheetColumnResourcesImpl.java
SheetColumnResourcesImpl.updateColumn
public Column updateColumn(long sheetId, Column column) throws SmartsheetException { Util.throwIfNull(column); return this.updateResource("sheets/" + sheetId + "/columns/" + column.getId(), Column.class, column); }
java
public Column updateColumn(long sheetId, Column column) throws SmartsheetException { Util.throwIfNull(column); return this.updateResource("sheets/" + sheetId + "/columns/" + column.getId(), Column.class, column); }
[ "public", "Column", "updateColumn", "(", "long", "sheetId", ",", "Column", "column", ")", "throws", "SmartsheetException", "{", "Util", ".", "throwIfNull", "(", "column", ")", ";", "return", "this", ".", "updateResource", "(", "\"sheets/\"", "+", "sheetId", "+", "\"/columns/\"", "+", "column", ".", "getId", "(", ")", ",", "Column", ".", "class", ",", "column", ")", ";", "}" ]
Update a column. It mirrors to the following Smartsheet REST API method: PUT /sheets/{sheetId}/columns/{columnId} Exceptions: IllegalArgumentException : if any argument is null InvalidRequestException : if there is any problem with the REST API request AuthorizationException : if there is any problem with the REST API authorization(access token) ResourceNotFoundException : if the resource can not be found ServiceUnavailableException : if the REST API service is not available (possibly due to rate limiting) SmartsheetRestException : if there is any other REST API related error occurred during the operation SmartsheetException : if there is any other error occurred during the operation @param sheetId the sheetId @param column the column to update limited to the following attributes: index (column's new index in the sheet), title, sheetId, type, options (optional), symbol (optional), systemColumnType (optional), autoNumberFormat (optional) @return the updated sheet (note that if there is no such resource, this method will throw ResourceNotFoundException rather than returning null). @throws SmartsheetException the smartsheet exception
[ "Update", "a", "column", "." ]
train
https://github.com/smartsheet-platform/smartsheet-java-sdk/blob/f60e264412076271f83b65889ef9b891fad83df8/src/main/java/com/smartsheet/api/internal/SheetColumnResourcesImpl.java#L152-L155
spring-projects/spring-hateoas
src/main/java/org/springframework/hateoas/client/Hop.java
Hop.withParameter
public Hop withParameter(String name, Object value) { Assert.hasText(name, "Name must not be null or empty!"); HashMap<String, Object> parameters = new HashMap<>(this.parameters); parameters.put(name, value); return new Hop(this.rel, parameters, this.headers); }
java
public Hop withParameter(String name, Object value) { Assert.hasText(name, "Name must not be null or empty!"); HashMap<String, Object> parameters = new HashMap<>(this.parameters); parameters.put(name, value); return new Hop(this.rel, parameters, this.headers); }
[ "public", "Hop", "withParameter", "(", "String", "name", ",", "Object", "value", ")", "{", "Assert", ".", "hasText", "(", "name", ",", "\"Name must not be null or empty!\"", ")", ";", "HashMap", "<", "String", ",", "Object", ">", "parameters", "=", "new", "HashMap", "<>", "(", "this", ".", "parameters", ")", ";", "parameters", ".", "put", "(", "name", ",", "value", ")", ";", "return", "new", "Hop", "(", "this", ".", "rel", ",", "parameters", ",", "this", ".", "headers", ")", ";", "}" ]
Add one parameter to the map of parameters. @param name must not be {@literal null} or empty. @param value can be {@literal null}. @return
[ "Add", "one", "parameter", "to", "the", "map", "of", "parameters", "." ]
train
https://github.com/spring-projects/spring-hateoas/blob/70ebff9309f086cd8d6a97daf67e0dc215c87d9c/src/main/java/org/springframework/hateoas/client/Hop.java#L79-L87
Samsung/GearVRf
GVRf/Extensions/widgetLib/src/org/gearvrf/widgetlib/log/Log.java
Log.wtf
public static int wtf(String tag, String msg) { return wtf(SUBSYSTEM.MAIN, tag, msg); }
java
public static int wtf(String tag, String msg) { return wtf(SUBSYSTEM.MAIN, tag, msg); }
[ "public", "static", "int", "wtf", "(", "String", "tag", ",", "String", "msg", ")", "{", "return", "wtf", "(", "SUBSYSTEM", ".", "MAIN", ",", "tag", ",", "msg", ")", ";", "}" ]
What a Terrible Failure: Report a condition that should never happen. The error will always be logged at level ASSERT with the call stack and with {@link SUBSYSTEM#MAIN} as default one. @param tag Used to identify the source of a log message. It usually identifies the class or activity where the log call occurs. @param msg The message you would like logged. @return
[ "What", "a", "Terrible", "Failure", ":", "Report", "a", "condition", "that", "should", "never", "happen", ".", "The", "error", "will", "always", "be", "logged", "at", "level", "ASSERT", "with", "the", "call", "stack", "and", "with", "{" ]
train
https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Extensions/widgetLib/src/org/gearvrf/widgetlib/log/Log.java#L353-L355
liferay/com-liferay-commerce
commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPDefinitionPersistenceImpl.java
CPDefinitionPersistenceImpl.fetchByC_ERC
@Override public CPDefinition fetchByC_ERC(long companyId, String externalReferenceCode) { return fetchByC_ERC(companyId, externalReferenceCode, true); }
java
@Override public CPDefinition fetchByC_ERC(long companyId, String externalReferenceCode) { return fetchByC_ERC(companyId, externalReferenceCode, true); }
[ "@", "Override", "public", "CPDefinition", "fetchByC_ERC", "(", "long", "companyId", ",", "String", "externalReferenceCode", ")", "{", "return", "fetchByC_ERC", "(", "companyId", ",", "externalReferenceCode", ",", "true", ")", ";", "}" ]
Returns the cp definition where companyId = &#63; and externalReferenceCode = &#63; or returns <code>null</code> if it could not be found. Uses the finder cache. @param companyId the company ID @param externalReferenceCode the external reference code @return the matching cp definition, or <code>null</code> if a matching cp definition could not be found
[ "Returns", "the", "cp", "definition", "where", "companyId", "=", "&#63", ";", "and", "externalReferenceCode", "=", "&#63", ";", "or", "returns", "<code", ">", "null<", "/", "code", ">", "if", "it", "could", "not", "be", "found", ".", "Uses", "the", "finder", "cache", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPDefinitionPersistenceImpl.java#L5232-L5236
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/factory/BaseNDArrayFactory.java
BaseNDArrayFactory.randn
@Override public INDArray randn(long rows, long columns, long seed) { Nd4j.getRandom().setSeed(seed); return randn(new long[] {rows, columns}, Nd4j.getRandom()); }
java
@Override public INDArray randn(long rows, long columns, long seed) { Nd4j.getRandom().setSeed(seed); return randn(new long[] {rows, columns}, Nd4j.getRandom()); }
[ "@", "Override", "public", "INDArray", "randn", "(", "long", "rows", ",", "long", "columns", ",", "long", "seed", ")", "{", "Nd4j", ".", "getRandom", "(", ")", ".", "setSeed", "(", "seed", ")", ";", "return", "randn", "(", "new", "long", "[", "]", "{", "rows", ",", "columns", "}", ",", "Nd4j", ".", "getRandom", "(", ")", ")", ";", "}" ]
Random normal using the specified seed @param rows the number of rows in the matrix @param columns the number of columns in the matrix @return
[ "Random", "normal", "using", "the", "specified", "seed" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/factory/BaseNDArrayFactory.java#L536-L540
nyla-solutions/nyla
nyla.solutions.core/src/main/java/nyla/solutions/core/util/Cryption.java
Cryption.interpret
public static String interpret(String text) { if (text == null) return null; if (isEncrypted(text)) { try { text = text.substring(CRYPTION_PREFIX.length()); text = getCanonical().decryptText(text); } catch (Exception e) { throw new ConfigException("Cannot interpret:" + text, e); } } return text; }
java
public static String interpret(String text) { if (text == null) return null; if (isEncrypted(text)) { try { text = text.substring(CRYPTION_PREFIX.length()); text = getCanonical().decryptText(text); } catch (Exception e) { throw new ConfigException("Cannot interpret:" + text, e); } } return text; }
[ "public", "static", "String", "interpret", "(", "String", "text", ")", "{", "if", "(", "text", "==", "null", ")", "return", "null", ";", "if", "(", "isEncrypted", "(", "text", ")", ")", "{", "try", "{", "text", "=", "text", ".", "substring", "(", "CRYPTION_PREFIX", ".", "length", "(", ")", ")", ";", "text", "=", "getCanonical", "(", ")", ".", "decryptText", "(", "text", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "ConfigException", "(", "\"Cannot interpret:\"", "+", "text", ",", "e", ")", ";", "}", "}", "return", "text", ";", "}" ]
If the text is encrypted the decrypted value is returned. If the text is not encrypted to original text is returned. @param text the string values (encrypt or decrypted). Encrypted are prefixed with {cryption} @return if the value starts with the {cryption} prefix the encrypted value is return, else the given value is returned
[ "If", "the", "text", "is", "encrypted", "the", "decrypted", "value", "is", "returned", ".", "If", "the", "text", "is", "not", "encrypted", "to", "original", "text", "is", "returned", "." ]
train
https://github.com/nyla-solutions/nyla/blob/38d5b843c76eae9762bbca20453ed0f0ad8412a9/nyla.solutions.core/src/main/java/nyla/solutions/core/util/Cryption.java#L286-L305
joniles/mpxj
src/main/java/net/sf/mpxj/mpp/MPPUtility.java
MPPUtility.dumpBlockData
public static void dumpBlockData(int headerSize, int blockSize, byte[] data) { if (data != null) { System.out.println(ByteArrayHelper.hexdump(data, 0, headerSize, false)); int index = headerSize; while (index < data.length) { System.out.println(ByteArrayHelper.hexdump(data, index, blockSize, false)); index += blockSize; } } }
java
public static void dumpBlockData(int headerSize, int blockSize, byte[] data) { if (data != null) { System.out.println(ByteArrayHelper.hexdump(data, 0, headerSize, false)); int index = headerSize; while (index < data.length) { System.out.println(ByteArrayHelper.hexdump(data, index, blockSize, false)); index += blockSize; } } }
[ "public", "static", "void", "dumpBlockData", "(", "int", "headerSize", ",", "int", "blockSize", ",", "byte", "[", "]", "data", ")", "{", "if", "(", "data", "!=", "null", ")", "{", "System", ".", "out", ".", "println", "(", "ByteArrayHelper", ".", "hexdump", "(", "data", ",", "0", ",", "headerSize", ",", "false", ")", ")", ";", "int", "index", "=", "headerSize", ";", "while", "(", "index", "<", "data", ".", "length", ")", "{", "System", ".", "out", ".", "println", "(", "ByteArrayHelper", ".", "hexdump", "(", "data", ",", "index", ",", "blockSize", ",", "false", ")", ")", ";", "index", "+=", "blockSize", ";", "}", "}", "}" ]
Dumps the contents of a structured block made up from a header and fixed sized records. @param headerSize header zie @param blockSize block size @param data data block
[ "Dumps", "the", "contents", "of", "a", "structured", "block", "made", "up", "from", "a", "header", "and", "fixed", "sized", "records", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpp/MPPUtility.java#L1256-L1268
stratosphere/stratosphere
stratosphere-core/src/main/java/eu/stratosphere/types/StringValue.java
StringValue.setValue
public void setValue(StringValue value, int offset, int len) { Validate.notNull(value); setValue(value.value, offset, len); }
java
public void setValue(StringValue value, int offset, int len) { Validate.notNull(value); setValue(value.value, offset, len); }
[ "public", "void", "setValue", "(", "StringValue", "value", ",", "int", "offset", ",", "int", "len", ")", "{", "Validate", ".", "notNull", "(", "value", ")", ";", "setValue", "(", "value", ".", "value", ",", "offset", ",", "len", ")", ";", "}" ]
Sets the value of the StringValue to a substring of the given string. @param value The new string value. @param offset The position to start the substring. @param len The length of the substring.
[ "Sets", "the", "value", "of", "the", "StringValue", "to", "a", "substring", "of", "the", "given", "string", "." ]
train
https://github.com/stratosphere/stratosphere/blob/c543a08f9676c5b2b0a7088123bd6e795a8ae0c8/stratosphere-core/src/main/java/eu/stratosphere/types/StringValue.java#L166-L169
googleads/googleads-java-lib
modules/ads_lib/src/main/java/com/google/api/ads/adwords/lib/utils/BatchJobUploader.java
BatchJobUploader.initiateResumableUpload
private URI initiateResumableUpload(URI batchJobUploadUrl) throws BatchJobException { // This follows the Google Cloud Storage guidelines for initiating resumable uploads: // https://cloud.google.com/storage/docs/resumable-uploads-xml HttpRequestFactory requestFactory = httpTransport.createRequestFactory( req -> { HttpHeaders headers = createHttpHeaders(); headers.setContentLength(0L); headers.set("x-goog-resumable", "start"); req.setHeaders(headers); req.setLoggingEnabled(true); }); try { HttpRequest httpRequest = requestFactory.buildPostRequest(new GenericUrl(batchJobUploadUrl), new EmptyContent()); HttpResponse response = httpRequest.execute(); if (response.getHeaders() == null || response.getHeaders().getLocation() == null) { throw new BatchJobException( "Initiate upload failed. Resumable upload URI was not in the response."); } return URI.create(response.getHeaders().getLocation()); } catch (IOException e) { throw new BatchJobException("Failed to initiate upload", e); } }
java
private URI initiateResumableUpload(URI batchJobUploadUrl) throws BatchJobException { // This follows the Google Cloud Storage guidelines for initiating resumable uploads: // https://cloud.google.com/storage/docs/resumable-uploads-xml HttpRequestFactory requestFactory = httpTransport.createRequestFactory( req -> { HttpHeaders headers = createHttpHeaders(); headers.setContentLength(0L); headers.set("x-goog-resumable", "start"); req.setHeaders(headers); req.setLoggingEnabled(true); }); try { HttpRequest httpRequest = requestFactory.buildPostRequest(new GenericUrl(batchJobUploadUrl), new EmptyContent()); HttpResponse response = httpRequest.execute(); if (response.getHeaders() == null || response.getHeaders().getLocation() == null) { throw new BatchJobException( "Initiate upload failed. Resumable upload URI was not in the response."); } return URI.create(response.getHeaders().getLocation()); } catch (IOException e) { throw new BatchJobException("Failed to initiate upload", e); } }
[ "private", "URI", "initiateResumableUpload", "(", "URI", "batchJobUploadUrl", ")", "throws", "BatchJobException", "{", "// This follows the Google Cloud Storage guidelines for initiating resumable uploads:", "// https://cloud.google.com/storage/docs/resumable-uploads-xml", "HttpRequestFactory", "requestFactory", "=", "httpTransport", ".", "createRequestFactory", "(", "req", "->", "{", "HttpHeaders", "headers", "=", "createHttpHeaders", "(", ")", ";", "headers", ".", "setContentLength", "(", "0L", ")", ";", "headers", ".", "set", "(", "\"x-goog-resumable\"", ",", "\"start\"", ")", ";", "req", ".", "setHeaders", "(", "headers", ")", ";", "req", ".", "setLoggingEnabled", "(", "true", ")", ";", "}", ")", ";", "try", "{", "HttpRequest", "httpRequest", "=", "requestFactory", ".", "buildPostRequest", "(", "new", "GenericUrl", "(", "batchJobUploadUrl", ")", ",", "new", "EmptyContent", "(", ")", ")", ";", "HttpResponse", "response", "=", "httpRequest", ".", "execute", "(", ")", ";", "if", "(", "response", ".", "getHeaders", "(", ")", "==", "null", "||", "response", ".", "getHeaders", "(", ")", ".", "getLocation", "(", ")", "==", "null", ")", "{", "throw", "new", "BatchJobException", "(", "\"Initiate upload failed. Resumable upload URI was not in the response.\"", ")", ";", "}", "return", "URI", ".", "create", "(", "response", ".", "getHeaders", "(", ")", ".", "getLocation", "(", ")", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "BatchJobException", "(", "\"Failed to initiate upload\"", ",", "e", ")", ";", "}", "}" ]
Initiates the resumable upload by sending a request to Google Cloud Storage. @param batchJobUploadUrl the {@code uploadUrl} of a {@code BatchJob} @return the URI for the initiated resumable upload
[ "Initiates", "the", "resumable", "upload", "by", "sending", "a", "request", "to", "Google", "Cloud", "Storage", "." ]
train
https://github.com/googleads/googleads-java-lib/blob/967957cc4f6076514e3a7926fe653e4f1f7cc9c9/modules/ads_lib/src/main/java/com/google/api/ads/adwords/lib/utils/BatchJobUploader.java#L165-L190
craterdog/java-security-framework
java-certificate-management-providers/src/main/java/craterdog/security/RsaCertificateManager.java
RsaCertificateManager.encodeSigningRequest
public String encodeSigningRequest(PKCS10CertificationRequest csr) { logger.entry(); try (StringWriter swriter = new StringWriter(); PemWriter pwriter = new PemWriter(swriter)) { pwriter.writeObject(new PemObject("CERTIFICATE REQUEST", csr.getEncoded())); pwriter.flush(); String result = swriter.toString(); logger.exit(); return result; } catch (IOException e) { RuntimeException exception = new RuntimeException("An unexpected exception occurred while attempting to encode a certificate signing request.", e); logger.error(exception.toString()); throw exception; } }
java
public String encodeSigningRequest(PKCS10CertificationRequest csr) { logger.entry(); try (StringWriter swriter = new StringWriter(); PemWriter pwriter = new PemWriter(swriter)) { pwriter.writeObject(new PemObject("CERTIFICATE REQUEST", csr.getEncoded())); pwriter.flush(); String result = swriter.toString(); logger.exit(); return result; } catch (IOException e) { RuntimeException exception = new RuntimeException("An unexpected exception occurred while attempting to encode a certificate signing request.", e); logger.error(exception.toString()); throw exception; } }
[ "public", "String", "encodeSigningRequest", "(", "PKCS10CertificationRequest", "csr", ")", "{", "logger", ".", "entry", "(", ")", ";", "try", "(", "StringWriter", "swriter", "=", "new", "StringWriter", "(", ")", ";", "PemWriter", "pwriter", "=", "new", "PemWriter", "(", "swriter", ")", ")", "{", "pwriter", ".", "writeObject", "(", "new", "PemObject", "(", "\"CERTIFICATE REQUEST\"", ",", "csr", ".", "getEncoded", "(", ")", ")", ")", ";", "pwriter", ".", "flush", "(", ")", ";", "String", "result", "=", "swriter", ".", "toString", "(", ")", ";", "logger", ".", "exit", "(", ")", ";", "return", "result", ";", "}", "catch", "(", "IOException", "e", ")", "{", "RuntimeException", "exception", "=", "new", "RuntimeException", "(", "\"An unexpected exception occurred while attempting to encode a certificate signing request.\"", ",", "e", ")", ";", "logger", ".", "error", "(", "exception", ".", "toString", "(", ")", ")", ";", "throw", "exception", ";", "}", "}" ]
This method encodes a certificate signing request (CSR) into a string for transport purposes. This is a convenience method that really should be part of the <code>CertificateManagement</code> interface except that it depends on a Bouncy Castle class in the signature. The java security framework does not have a similar class so it has been left out of the interface. @param csr The certificate signing request. @return The encoded certificate signing request string.
[ "This", "method", "encodes", "a", "certificate", "signing", "request", "(", "CSR", ")", "into", "a", "string", "for", "transport", "purposes", ".", "This", "is", "a", "convenience", "method", "that", "really", "should", "be", "part", "of", "the", "<code", ">", "CertificateManagement<", "/", "code", ">", "interface", "except", "that", "it", "depends", "on", "a", "Bouncy", "Castle", "class", "in", "the", "signature", ".", "The", "java", "security", "framework", "does", "not", "have", "a", "similar", "class", "so", "it", "has", "been", "left", "out", "of", "the", "interface", "." ]
train
https://github.com/craterdog/java-security-framework/blob/a5634c19812d473b608bc11060f5cbb4b4b0b5da/java-certificate-management-providers/src/main/java/craterdog/security/RsaCertificateManager.java#L220-L233
micronaut-projects/micronaut-core
inject/src/main/java/io/micronaut/context/AbstractBeanDefinition.java
AbstractBeanDefinition.warnMissingProperty
@SuppressWarnings("unused") @Internal protected final void warnMissingProperty(Class type, String method, String property) { if (LOG.isWarnEnabled()) { LOG.warn("Configuration property [{}] could not be set as the underlying method [{}] does not exist on builder [{}]. This usually indicates the configuration option was deprecated and has been removed by the builder implementation (potentially a third-party library).", property, method, type); } }
java
@SuppressWarnings("unused") @Internal protected final void warnMissingProperty(Class type, String method, String property) { if (LOG.isWarnEnabled()) { LOG.warn("Configuration property [{}] could not be set as the underlying method [{}] does not exist on builder [{}]. This usually indicates the configuration option was deprecated and has been removed by the builder implementation (potentially a third-party library).", property, method, type); } }
[ "@", "SuppressWarnings", "(", "\"unused\"", ")", "@", "Internal", "protected", "final", "void", "warnMissingProperty", "(", "Class", "type", ",", "String", "method", ",", "String", "property", ")", "{", "if", "(", "LOG", ".", "isWarnEnabled", "(", ")", ")", "{", "LOG", ".", "warn", "(", "\"Configuration property [{}] could not be set as the underlying method [{}] does not exist on builder [{}]. This usually indicates the configuration option was deprecated and has been removed by the builder implementation (potentially a third-party library).\"", ",", "property", ",", "method", ",", "type", ")", ";", "}", "}" ]
Allows printing warning messages produced by the compiler. @param type The type @param method The method @param property The property
[ "Allows", "printing", "warning", "messages", "produced", "by", "the", "compiler", "." ]
train
https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/inject/src/main/java/io/micronaut/context/AbstractBeanDefinition.java#L417-L423
leancloud/java-sdk-all
android-sdk/mixpush-android/src/main/java/cn/leancloud/AVMixPushManager.java
AVMixPushManager.registerHMSPush
public static void registerHMSPush(Application application, String profile) { if (null == application) { throw new IllegalArgumentException("[HMS] context cannot be null."); } if (!isHuaweiPhone()) { printErrorLog("[HMS] register error, is not huawei phone!"); return; } if (!checkHuaweiManifest(application)) { printErrorLog("[HMS] register error, mainifest is incomplete!"); return; } hwDeviceProfile = profile; boolean hmsInitResult = com.huawei.android.hms.agent.HMSAgent.init(application); if (!hmsInitResult) { LOGGER.e("failed to init HMSAgent."); } LOGGER.d("[HMS] start register HMS push"); }
java
public static void registerHMSPush(Application application, String profile) { if (null == application) { throw new IllegalArgumentException("[HMS] context cannot be null."); } if (!isHuaweiPhone()) { printErrorLog("[HMS] register error, is not huawei phone!"); return; } if (!checkHuaweiManifest(application)) { printErrorLog("[HMS] register error, mainifest is incomplete!"); return; } hwDeviceProfile = profile; boolean hmsInitResult = com.huawei.android.hms.agent.HMSAgent.init(application); if (!hmsInitResult) { LOGGER.e("failed to init HMSAgent."); } LOGGER.d("[HMS] start register HMS push"); }
[ "public", "static", "void", "registerHMSPush", "(", "Application", "application", ",", "String", "profile", ")", "{", "if", "(", "null", "==", "application", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"[HMS] context cannot be null.\"", ")", ";", "}", "if", "(", "!", "isHuaweiPhone", "(", ")", ")", "{", "printErrorLog", "(", "\"[HMS] register error, is not huawei phone!\"", ")", ";", "return", ";", "}", "if", "(", "!", "checkHuaweiManifest", "(", "application", ")", ")", "{", "printErrorLog", "(", "\"[HMS] register error, mainifest is incomplete!\"", ")", ";", "return", ";", "}", "hwDeviceProfile", "=", "profile", ";", "boolean", "hmsInitResult", "=", "com", ".", "huawei", ".", "android", ".", "hms", ".", "agent", ".", "HMSAgent", ".", "init", "(", "application", ")", ";", "if", "(", "!", "hmsInitResult", ")", "{", "LOGGER", ".", "e", "(", "\"failed to init HMSAgent.\"", ")", ";", "}", "LOGGER", ".", "d", "(", "\"[HMS] start register HMS push\"", ")", ";", "}" ]
初始化方法,建议在 Application onCreate 里面调用 @param application @param profile 华为推送配置
[ "初始化方法,建议在", "Application", "onCreate", "里面调用" ]
train
https://github.com/leancloud/java-sdk-all/blob/323f8e7ee38051b1350790e5192304768c5c9f5f/android-sdk/mixpush-android/src/main/java/cn/leancloud/AVMixPushManager.java#L107-L129
intellimate/Izou
src/main/java/org/intellimate/izou/security/AudioPermissionModule.java
AudioPermissionModule.registerOrThrow
private void registerOrThrow(AddOnModel addOn, String permissionMessage) throws IzouSoundPermissionException{ Function<PluginDescriptor, Boolean> checkPlayPermission = descriptor -> { if (descriptor.getAddOnProperties() == null) throw new IzouPermissionException("addon_config.properties not found for addon:" + addOn); try { return descriptor.getAddOnProperties().getProperty("audio_output") != null && descriptor.getAddOnProperties().getProperty("audio_output").trim().equals("true") && descriptor.getAddOnProperties().getProperty("audio_usage_descripton") != null && !descriptor.getAddOnProperties().getProperty("audio_usage_descripton").trim().equals("null") && !descriptor.getAddOnProperties().getProperty("audio_usage_descripton").trim().isEmpty(); } catch (NullPointerException e) { return false; } }; registerOrThrow(addOn, () -> new IzouSoundPermissionException(permissionMessage), checkPlayPermission); }
java
private void registerOrThrow(AddOnModel addOn, String permissionMessage) throws IzouSoundPermissionException{ Function<PluginDescriptor, Boolean> checkPlayPermission = descriptor -> { if (descriptor.getAddOnProperties() == null) throw new IzouPermissionException("addon_config.properties not found for addon:" + addOn); try { return descriptor.getAddOnProperties().getProperty("audio_output") != null && descriptor.getAddOnProperties().getProperty("audio_output").trim().equals("true") && descriptor.getAddOnProperties().getProperty("audio_usage_descripton") != null && !descriptor.getAddOnProperties().getProperty("audio_usage_descripton").trim().equals("null") && !descriptor.getAddOnProperties().getProperty("audio_usage_descripton").trim().isEmpty(); } catch (NullPointerException e) { return false; } }; registerOrThrow(addOn, () -> new IzouSoundPermissionException(permissionMessage), checkPlayPermission); }
[ "private", "void", "registerOrThrow", "(", "AddOnModel", "addOn", ",", "String", "permissionMessage", ")", "throws", "IzouSoundPermissionException", "{", "Function", "<", "PluginDescriptor", ",", "Boolean", ">", "checkPlayPermission", "=", "descriptor", "->", "{", "if", "(", "descriptor", ".", "getAddOnProperties", "(", ")", "==", "null", ")", "throw", "new", "IzouPermissionException", "(", "\"addon_config.properties not found for addon:\"", "+", "addOn", ")", ";", "try", "{", "return", "descriptor", ".", "getAddOnProperties", "(", ")", ".", "getProperty", "(", "\"audio_output\"", ")", "!=", "null", "&&", "descriptor", ".", "getAddOnProperties", "(", ")", ".", "getProperty", "(", "\"audio_output\"", ")", ".", "trim", "(", ")", ".", "equals", "(", "\"true\"", ")", "&&", "descriptor", ".", "getAddOnProperties", "(", ")", ".", "getProperty", "(", "\"audio_usage_descripton\"", ")", "!=", "null", "&&", "!", "descriptor", ".", "getAddOnProperties", "(", ")", ".", "getProperty", "(", "\"audio_usage_descripton\"", ")", ".", "trim", "(", ")", ".", "equals", "(", "\"null\"", ")", "&&", "!", "descriptor", ".", "getAddOnProperties", "(", ")", ".", "getProperty", "(", "\"audio_usage_descripton\"", ")", ".", "trim", "(", ")", ".", "isEmpty", "(", ")", ";", "}", "catch", "(", "NullPointerException", "e", ")", "{", "return", "false", ";", "}", "}", ";", "registerOrThrow", "(", "addOn", ",", "(", ")", "->", "new", "IzouSoundPermissionException", "(", "permissionMessage", ")", ",", "checkPlayPermission", ")", ";", "}" ]
registers the AddOn or throws the Exception @param addOn the AddOn to register @param permissionMessage the message of the exception @throws IzouSoundPermissionException if not eligible for registering
[ "registers", "the", "AddOn", "or", "throws", "the", "Exception" ]
train
https://github.com/intellimate/Izou/blob/40a808b97998e17655c4a78e30ce7326148aed27/src/main/java/org/intellimate/izou/security/AudioPermissionModule.java#L54-L70
heinrichreimer/material-drawer
library/src/main/java/com/heinrichreimersoftware/materialdrawer/structure/DrawerProfile.java
DrawerProfile.setBackground
public DrawerProfile setBackground(Context context, Bitmap background) { mBackground = new BitmapDrawable(context.getResources(), background); notifyDataChanged(); return this; }
java
public DrawerProfile setBackground(Context context, Bitmap background) { mBackground = new BitmapDrawable(context.getResources(), background); notifyDataChanged(); return this; }
[ "public", "DrawerProfile", "setBackground", "(", "Context", "context", ",", "Bitmap", "background", ")", "{", "mBackground", "=", "new", "BitmapDrawable", "(", "context", ".", "getResources", "(", ")", ",", "background", ")", ";", "notifyDataChanged", "(", ")", ";", "return", "this", ";", "}" ]
Sets a background to the drawer profile @param background Background to set
[ "Sets", "a", "background", "to", "the", "drawer", "profile" ]
train
https://github.com/heinrichreimer/material-drawer/blob/7c2406812d73f710ef8bb73d4a0f4bbef3b275ce/library/src/main/java/com/heinrichreimersoftware/materialdrawer/structure/DrawerProfile.java#L194-L198
iig-uni-freiburg/SEWOL
ext/org/deckfour/xes/out/XMxmlSerializer.java
XMxmlSerializer.addAttributes
protected void addAttributes(SXTag node, Collection<XAttribute> attributes) throws IOException { SXTag data = node.addChildNode("Data"); addAttributes(data, "", attributes); }
java
protected void addAttributes(SXTag node, Collection<XAttribute> attributes) throws IOException { SXTag data = node.addChildNode("Data"); addAttributes(data, "", attributes); }
[ "protected", "void", "addAttributes", "(", "SXTag", "node", ",", "Collection", "<", "XAttribute", ">", "attributes", ")", "throws", "IOException", "{", "SXTag", "data", "=", "node", ".", "addChildNode", "(", "\"Data\"", ")", ";", "addAttributes", "(", "data", ",", "\"\"", ",", "attributes", ")", ";", "}" ]
Helper method, adds attributes to a tag. @param node The tag to add attributes to. @param attributes The attributes to add.
[ "Helper", "method", "adds", "attributes", "to", "a", "tag", "." ]
train
https://github.com/iig-uni-freiburg/SEWOL/blob/e791cb07a6e62ecf837d760d58a25f32fbf6bbca/ext/org/deckfour/xes/out/XMxmlSerializer.java#L232-L236
datoin/http-requests
src/main/java/org/datoin/net/http/Request.java
Request.getResponse
protected Response getResponse(HttpEntity entity, RequestBuilder req) { CloseableHttpClient client = getClient(); initHeaders(req); req.setEntity(entity); CloseableHttpResponse resp = null; Response response = null; try { final HttpUriRequest uriRequest = req.build(); resp = client.execute(uriRequest); response = new Response(resp); response.setMethod(Methods.POST.getMethod()); response.setRequestLine(uriRequest.getRequestLine().toString()); } catch (Exception e) { // TODO: log the error e.printStackTrace(); } finally { try { client.close(); } catch (IOException e) { e.printStackTrace(); } } return response; }
java
protected Response getResponse(HttpEntity entity, RequestBuilder req) { CloseableHttpClient client = getClient(); initHeaders(req); req.setEntity(entity); CloseableHttpResponse resp = null; Response response = null; try { final HttpUriRequest uriRequest = req.build(); resp = client.execute(uriRequest); response = new Response(resp); response.setMethod(Methods.POST.getMethod()); response.setRequestLine(uriRequest.getRequestLine().toString()); } catch (Exception e) { // TODO: log the error e.printStackTrace(); } finally { try { client.close(); } catch (IOException e) { e.printStackTrace(); } } return response; }
[ "protected", "Response", "getResponse", "(", "HttpEntity", "entity", ",", "RequestBuilder", "req", ")", "{", "CloseableHttpClient", "client", "=", "getClient", "(", ")", ";", "initHeaders", "(", "req", ")", ";", "req", ".", "setEntity", "(", "entity", ")", ";", "CloseableHttpResponse", "resp", "=", "null", ";", "Response", "response", "=", "null", ";", "try", "{", "final", "HttpUriRequest", "uriRequest", "=", "req", ".", "build", "(", ")", ";", "resp", "=", "client", ".", "execute", "(", "uriRequest", ")", ";", "response", "=", "new", "Response", "(", "resp", ")", ";", "response", ".", "setMethod", "(", "Methods", ".", "POST", ".", "getMethod", "(", ")", ")", ";", "response", ".", "setRequestLine", "(", "uriRequest", ".", "getRequestLine", "(", ")", ".", "toString", "(", ")", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "// TODO: log the error", "e", ".", "printStackTrace", "(", ")", ";", "}", "finally", "{", "try", "{", "client", ".", "close", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "}", "return", "response", ";", "}" ]
get response from preconfigured http entity and request builder @param entity : http entity to be used in request @param req : request builder object to build the http request @return : Response object prepared after executing the request
[ "get", "response", "from", "preconfigured", "http", "entity", "and", "request", "builder" ]
train
https://github.com/datoin/http-requests/blob/660a4bc516c594f321019df94451fead4dea19b6/src/main/java/org/datoin/net/http/Request.java#L455-L478
apache/flink
flink-runtime/src/main/java/org/apache/flink/runtime/taskexecutor/slot/TaskSlotTable.java
TaskSlotTable.markSlotInactive
public boolean markSlotInactive(AllocationID allocationId, Time slotTimeout) throws SlotNotFoundException { checkInit(); TaskSlot taskSlot = getTaskSlot(allocationId); if (taskSlot != null) { if (taskSlot.markInactive()) { // register a timeout to free the slot timerService.registerTimeout(allocationId, slotTimeout.getSize(), slotTimeout.getUnit()); return true; } else { return false; } } else { throw new SlotNotFoundException(allocationId); } }
java
public boolean markSlotInactive(AllocationID allocationId, Time slotTimeout) throws SlotNotFoundException { checkInit(); TaskSlot taskSlot = getTaskSlot(allocationId); if (taskSlot != null) { if (taskSlot.markInactive()) { // register a timeout to free the slot timerService.registerTimeout(allocationId, slotTimeout.getSize(), slotTimeout.getUnit()); return true; } else { return false; } } else { throw new SlotNotFoundException(allocationId); } }
[ "public", "boolean", "markSlotInactive", "(", "AllocationID", "allocationId", ",", "Time", "slotTimeout", ")", "throws", "SlotNotFoundException", "{", "checkInit", "(", ")", ";", "TaskSlot", "taskSlot", "=", "getTaskSlot", "(", "allocationId", ")", ";", "if", "(", "taskSlot", "!=", "null", ")", "{", "if", "(", "taskSlot", ".", "markInactive", "(", ")", ")", "{", "// register a timeout to free the slot", "timerService", ".", "registerTimeout", "(", "allocationId", ",", "slotTimeout", ".", "getSize", "(", ")", ",", "slotTimeout", ".", "getUnit", "(", ")", ")", ";", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}", "else", "{", "throw", "new", "SlotNotFoundException", "(", "allocationId", ")", ";", "}", "}" ]
Marks the slot under the given allocation id as inactive. If the slot could not be found, then a {@link SlotNotFoundException} is thrown. @param allocationId to identify the task slot to mark as inactive @param slotTimeout until the slot times out @throws SlotNotFoundException if the slot could not be found for the given allocation id @return True if the slot could be marked inactive
[ "Marks", "the", "slot", "under", "the", "given", "allocation", "id", "as", "inactive", ".", "If", "the", "slot", "could", "not", "be", "found", "then", "a", "{", "@link", "SlotNotFoundException", "}", "is", "thrown", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/taskexecutor/slot/TaskSlotTable.java#L259-L276
jeremybrooks/jinx
src/main/java/net/jeremybrooks/jinx/Jinx.java
Jinx.flickrUpload
public <T> T flickrUpload(Map<String, String> params, byte[] photoData, Class<T> tClass) throws JinxException { if (this.oAuthAccessToken == null) { throw new JinxException("Jinx has not been configured with an OAuth Access Token."); } params.put("api_key", getApiKey()); return uploadOrReplace(params, photoData, tClass, new OAuthRequest(Verb.POST, FLICKR_PHOTO_UPLOAD_URL)); }
java
public <T> T flickrUpload(Map<String, String> params, byte[] photoData, Class<T> tClass) throws JinxException { if (this.oAuthAccessToken == null) { throw new JinxException("Jinx has not been configured with an OAuth Access Token."); } params.put("api_key", getApiKey()); return uploadOrReplace(params, photoData, tClass, new OAuthRequest(Verb.POST, FLICKR_PHOTO_UPLOAD_URL)); }
[ "public", "<", "T", ">", "T", "flickrUpload", "(", "Map", "<", "String", ",", "String", ">", "params", ",", "byte", "[", "]", "photoData", ",", "Class", "<", "T", ">", "tClass", ")", "throws", "JinxException", "{", "if", "(", "this", ".", "oAuthAccessToken", "==", "null", ")", "{", "throw", "new", "JinxException", "(", "\"Jinx has not been configured with an OAuth Access Token.\"", ")", ";", "}", "params", ".", "put", "(", "\"api_key\"", ",", "getApiKey", "(", ")", ")", ";", "return", "uploadOrReplace", "(", "params", ",", "photoData", ",", "tClass", ",", "new", "OAuthRequest", "(", "Verb", ".", "POST", ",", "FLICKR_PHOTO_UPLOAD_URL", ")", ")", ";", "}" ]
Upload a photo or video to Flickr. <br> Do not call this directly. Use the {@link net.jeremybrooks.jinx.api.PhotosUploadApi} class. @param params request parameters. @param photoData photo or video data to upload. @param tClass the class that will be returned. @param <T> type of the class returned. @return an instance of the specified class containing data from Flickr. @throws JinxException if there are any errors.
[ "Upload", "a", "photo", "or", "video", "to", "Flickr", ".", "<br", ">", "Do", "not", "call", "this", "directly", ".", "Use", "the", "{", "@link", "net", ".", "jeremybrooks", ".", "jinx", ".", "api", ".", "PhotosUploadApi", "}", "class", "." ]
train
https://github.com/jeremybrooks/jinx/blob/ab7a4b7462d08bcbfd9b98bd3f5029771c20f6c6/src/main/java/net/jeremybrooks/jinx/Jinx.java#L593-L599
Stratio/stratio-cassandra
src/java/org/apache/cassandra/io/sstable/CQLSSTableWriter.java
CQLSSTableWriter.rawAddRow
public CQLSSTableWriter rawAddRow(List<ByteBuffer> values) throws InvalidRequestException, IOException { if (values.size() != boundNames.size()) throw new InvalidRequestException(String.format("Invalid number of arguments, expecting %d values but got %d", boundNames.size(), values.size())); QueryOptions options = QueryOptions.forInternalCalls(null, values); List<ByteBuffer> keys = insert.buildPartitionKeyNames(options); Composite clusteringPrefix = insert.createClusteringPrefix(options); long now = System.currentTimeMillis() * 1000; UpdateParameters params = new UpdateParameters(insert.cfm, options, insert.getTimestamp(now, options), insert.getTimeToLive(options), Collections.<ByteBuffer, CQL3Row>emptyMap()); try { for (ByteBuffer key : keys) { if (writer.shouldStartNewRow() || !key.equals(writer.currentKey().getKey())) writer.newRow(key); insert.addUpdateForKey(writer.currentColumnFamily(), key, clusteringPrefix, params, false); } return this; } catch (BufferedWriter.SyncException e) { // If we use a BufferedWriter and had a problem writing to disk, the IOException has been // wrapped in a SyncException (see BufferedWriter below). We want to extract that IOE. throw (IOException)e.getCause(); } }
java
public CQLSSTableWriter rawAddRow(List<ByteBuffer> values) throws InvalidRequestException, IOException { if (values.size() != boundNames.size()) throw new InvalidRequestException(String.format("Invalid number of arguments, expecting %d values but got %d", boundNames.size(), values.size())); QueryOptions options = QueryOptions.forInternalCalls(null, values); List<ByteBuffer> keys = insert.buildPartitionKeyNames(options); Composite clusteringPrefix = insert.createClusteringPrefix(options); long now = System.currentTimeMillis() * 1000; UpdateParameters params = new UpdateParameters(insert.cfm, options, insert.getTimestamp(now, options), insert.getTimeToLive(options), Collections.<ByteBuffer, CQL3Row>emptyMap()); try { for (ByteBuffer key : keys) { if (writer.shouldStartNewRow() || !key.equals(writer.currentKey().getKey())) writer.newRow(key); insert.addUpdateForKey(writer.currentColumnFamily(), key, clusteringPrefix, params, false); } return this; } catch (BufferedWriter.SyncException e) { // If we use a BufferedWriter and had a problem writing to disk, the IOException has been // wrapped in a SyncException (see BufferedWriter below). We want to extract that IOE. throw (IOException)e.getCause(); } }
[ "public", "CQLSSTableWriter", "rawAddRow", "(", "List", "<", "ByteBuffer", ">", "values", ")", "throws", "InvalidRequestException", ",", "IOException", "{", "if", "(", "values", ".", "size", "(", ")", "!=", "boundNames", ".", "size", "(", ")", ")", "throw", "new", "InvalidRequestException", "(", "String", ".", "format", "(", "\"Invalid number of arguments, expecting %d values but got %d\"", ",", "boundNames", ".", "size", "(", ")", ",", "values", ".", "size", "(", ")", ")", ")", ";", "QueryOptions", "options", "=", "QueryOptions", ".", "forInternalCalls", "(", "null", ",", "values", ")", ";", "List", "<", "ByteBuffer", ">", "keys", "=", "insert", ".", "buildPartitionKeyNames", "(", "options", ")", ";", "Composite", "clusteringPrefix", "=", "insert", ".", "createClusteringPrefix", "(", "options", ")", ";", "long", "now", "=", "System", ".", "currentTimeMillis", "(", ")", "*", "1000", ";", "UpdateParameters", "params", "=", "new", "UpdateParameters", "(", "insert", ".", "cfm", ",", "options", ",", "insert", ".", "getTimestamp", "(", "now", ",", "options", ")", ",", "insert", ".", "getTimeToLive", "(", "options", ")", ",", "Collections", ".", "<", "ByteBuffer", ",", "CQL3Row", ">", "emptyMap", "(", ")", ")", ";", "try", "{", "for", "(", "ByteBuffer", "key", ":", "keys", ")", "{", "if", "(", "writer", ".", "shouldStartNewRow", "(", ")", "||", "!", "key", ".", "equals", "(", "writer", ".", "currentKey", "(", ")", ".", "getKey", "(", ")", ")", ")", "writer", ".", "newRow", "(", "key", ")", ";", "insert", ".", "addUpdateForKey", "(", "writer", ".", "currentColumnFamily", "(", ")", ",", "key", ",", "clusteringPrefix", ",", "params", ",", "false", ")", ";", "}", "return", "this", ";", "}", "catch", "(", "BufferedWriter", ".", "SyncException", "e", ")", "{", "// If we use a BufferedWriter and had a problem writing to disk, the IOException has been", "// wrapped in a SyncException (see BufferedWriter below). We want to extract that IOE.", "throw", "(", "IOException", ")", "e", ".", "getCause", "(", ")", ";", "}", "}" ]
Adds a new row to the writer given already serialized values. <p> This is a shortcut for {@code rawAddRow(Arrays.asList(values))}. @param values the row values (corresponding to the bind variables of the insertion statement used when creating by this writer) as binary. @return this writer.
[ "Adds", "a", "new", "row", "to", "the", "writer", "given", "already", "serialized", "values", ".", "<p", ">", "This", "is", "a", "shortcut", "for", "{", "@code", "rawAddRow", "(", "Arrays", ".", "asList", "(", "values", "))", "}", "." ]
train
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/io/sstable/CQLSSTableWriter.java#L201-L234
b3dgs/lionengine
lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/MapTileAppenderModel.java
MapTileAppenderModel.appendMap
private void appendMap(MapTile other, int offsetX, int offsetY) { for (int v = 0; v < other.getInTileHeight(); v++) { final int ty = offsetY + v; for (int h = 0; h < other.getInTileWidth(); h++) { final int tx = offsetX + h; final Tile tile = other.getTile(h, v); if (tile != null) { final double x = tx * (double) map.getTileWidth(); final double y = ty * (double) map.getTileHeight(); map.setTile(map.createTile(tile.getSheet(), tile.getNumber(), x, y)); } } } }
java
private void appendMap(MapTile other, int offsetX, int offsetY) { for (int v = 0; v < other.getInTileHeight(); v++) { final int ty = offsetY + v; for (int h = 0; h < other.getInTileWidth(); h++) { final int tx = offsetX + h; final Tile tile = other.getTile(h, v); if (tile != null) { final double x = tx * (double) map.getTileWidth(); final double y = ty * (double) map.getTileHeight(); map.setTile(map.createTile(tile.getSheet(), tile.getNumber(), x, y)); } } } }
[ "private", "void", "appendMap", "(", "MapTile", "other", ",", "int", "offsetX", ",", "int", "offsetY", ")", "{", "for", "(", "int", "v", "=", "0", ";", "v", "<", "other", ".", "getInTileHeight", "(", ")", ";", "v", "++", ")", "{", "final", "int", "ty", "=", "offsetY", "+", "v", ";", "for", "(", "int", "h", "=", "0", ";", "h", "<", "other", ".", "getInTileWidth", "(", ")", ";", "h", "++", ")", "{", "final", "int", "tx", "=", "offsetX", "+", "h", ";", "final", "Tile", "tile", "=", "other", ".", "getTile", "(", "h", ",", "v", ")", ";", "if", "(", "tile", "!=", "null", ")", "{", "final", "double", "x", "=", "tx", "*", "(", "double", ")", "map", ".", "getTileWidth", "(", ")", ";", "final", "double", "y", "=", "ty", "*", "(", "double", ")", "map", ".", "getTileHeight", "(", ")", ";", "map", ".", "setTile", "(", "map", ".", "createTile", "(", "tile", ".", "getSheet", "(", ")", ",", "tile", ".", "getNumber", "(", ")", ",", "x", ",", "y", ")", ")", ";", "}", "}", "}", "}" ]
Append the map at specified offset. @param other The map to append. @param offsetX The horizontal offset. @param offsetY The vertical offset.
[ "Append", "the", "map", "at", "specified", "offset", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/MapTileAppenderModel.java#L67-L84
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/UnicodeSet.java
UnicodeSet.stripFrom
@Deprecated public String stripFrom(CharSequence source, boolean matches) { StringBuilder result = new StringBuilder(); for (int pos = 0; pos < source.length();) { int inside = findIn(source, pos, !matches); result.append(source.subSequence(pos, inside)); pos = findIn(source, inside, matches); // get next start } return result.toString(); }
java
@Deprecated public String stripFrom(CharSequence source, boolean matches) { StringBuilder result = new StringBuilder(); for (int pos = 0; pos < source.length();) { int inside = findIn(source, pos, !matches); result.append(source.subSequence(pos, inside)); pos = findIn(source, inside, matches); // get next start } return result.toString(); }
[ "@", "Deprecated", "public", "String", "stripFrom", "(", "CharSequence", "source", ",", "boolean", "matches", ")", "{", "StringBuilder", "result", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "int", "pos", "=", "0", ";", "pos", "<", "source", ".", "length", "(", ")", ";", ")", "{", "int", "inside", "=", "findIn", "(", "source", ",", "pos", ",", "!", "matches", ")", ";", "result", ".", "append", "(", "source", ".", "subSequence", "(", "pos", ",", "inside", ")", ")", ";", "pos", "=", "findIn", "(", "source", ",", "inside", ",", "matches", ")", ";", "// get next start", "}", "return", "result", ".", "toString", "(", ")", ";", "}" ]
Strips code points from source. If matches is true, script all that match <i>this</i>. If matches is false, then strip all that <i>don't</i> match. @param source The source of the CharSequence to strip from. @param matches A boolean to either strip all that matches or don't match with the current UnicodeSet object. @return The string after it has been stripped. @deprecated This API is ICU internal only. Use replaceFrom. @hide original deprecated declaration @hide draft / provisional / internal are hidden on Android
[ "Strips", "code", "points", "from", "source", ".", "If", "matches", "is", "true", "script", "all", "that", "match", "<i", ">", "this<", "/", "i", ">", ".", "If", "matches", "is", "false", "then", "strip", "all", "that", "<i", ">", "don", "t<", "/", "i", ">", "match", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/UnicodeSet.java#L4644-L4653
roboconf/roboconf-platform
core/roboconf-core/src/main/java/net/roboconf/core/utils/UriUtils.java
UriUtils.buildNewURI
public static URI buildNewURI( URI referenceUri, String uriSuffix ) throws URISyntaxException { if( uriSuffix == null ) throw new IllegalArgumentException( "The URI suffix cannot be null." ); uriSuffix = uriSuffix.replaceAll( "\\\\", "/" ); URI importUri = null; try { // Absolute URL ? importUri = urlToUri( new URL( uriSuffix )); } catch( Exception e ) { try { // Relative URL ? if( ! referenceUri.toString().endsWith( "/" ) && ! uriSuffix.startsWith( "/" )) referenceUri = new URI( referenceUri.toString() + "/" ); importUri = referenceUri.resolve( new URI( null, uriSuffix, null )); } catch( Exception e2 ) { String msg = "An URI could not be built from the URI " + referenceUri.toString() + " and the suffix " + uriSuffix + "."; throw new URISyntaxException( msg, e2.getMessage()); } } return importUri.normalize(); }
java
public static URI buildNewURI( URI referenceUri, String uriSuffix ) throws URISyntaxException { if( uriSuffix == null ) throw new IllegalArgumentException( "The URI suffix cannot be null." ); uriSuffix = uriSuffix.replaceAll( "\\\\", "/" ); URI importUri = null; try { // Absolute URL ? importUri = urlToUri( new URL( uriSuffix )); } catch( Exception e ) { try { // Relative URL ? if( ! referenceUri.toString().endsWith( "/" ) && ! uriSuffix.startsWith( "/" )) referenceUri = new URI( referenceUri.toString() + "/" ); importUri = referenceUri.resolve( new URI( null, uriSuffix, null )); } catch( Exception e2 ) { String msg = "An URI could not be built from the URI " + referenceUri.toString() + " and the suffix " + uriSuffix + "."; throw new URISyntaxException( msg, e2.getMessage()); } } return importUri.normalize(); }
[ "public", "static", "URI", "buildNewURI", "(", "URI", "referenceUri", ",", "String", "uriSuffix", ")", "throws", "URISyntaxException", "{", "if", "(", "uriSuffix", "==", "null", ")", "throw", "new", "IllegalArgumentException", "(", "\"The URI suffix cannot be null.\"", ")", ";", "uriSuffix", "=", "uriSuffix", ".", "replaceAll", "(", "\"\\\\\\\\\"", ",", "\"/\"", ")", ";", "URI", "importUri", "=", "null", ";", "try", "{", "// Absolute URL ?", "importUri", "=", "urlToUri", "(", "new", "URL", "(", "uriSuffix", ")", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "try", "{", "// Relative URL ?", "if", "(", "!", "referenceUri", ".", "toString", "(", ")", ".", "endsWith", "(", "\"/\"", ")", "&&", "!", "uriSuffix", ".", "startsWith", "(", "\"/\"", ")", ")", "referenceUri", "=", "new", "URI", "(", "referenceUri", ".", "toString", "(", ")", "+", "\"/\"", ")", ";", "importUri", "=", "referenceUri", ".", "resolve", "(", "new", "URI", "(", "null", ",", "uriSuffix", ",", "null", ")", ")", ";", "}", "catch", "(", "Exception", "e2", ")", "{", "String", "msg", "=", "\"An URI could not be built from the URI \"", "+", "referenceUri", ".", "toString", "(", ")", "+", "\" and the suffix \"", "+", "uriSuffix", "+", "\".\"", ";", "throw", "new", "URISyntaxException", "(", "msg", ",", "e2", ".", "getMessage", "(", ")", ")", ";", "}", "}", "return", "importUri", ".", "normalize", "(", ")", ";", "}" ]
Builds an URI from an URI and a suffix. <p> This suffix can be an absolute URL, or a relative path with respect to the first URI. In this case, the suffix is resolved with respect to the URI. </p> <p> If the suffix is already an URL, its is returned.<br> If the suffix is a relative file path and cannot be resolved, an exception is thrown. </p> <p> The returned URI is normalized. </p> @param referenceUri the reference URI (can be null) @param uriSuffix the URI suffix (not null) @return the new URI @throws URISyntaxException if the resolution failed
[ "Builds", "an", "URI", "from", "an", "URI", "and", "a", "suffix", "." ]
train
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/utils/UriUtils.java#L122-L151
graphql-java/graphql-java
src/main/java/graphql/execution/instrumentation/fieldvalidation/SimpleFieldValidation.java
SimpleFieldValidation.addRule
public SimpleFieldValidation addRule(ExecutionPath fieldPath, BiFunction<FieldAndArguments, FieldValidationEnvironment, Optional<GraphQLError>> rule) { rules.put(fieldPath, rule); return this; }
java
public SimpleFieldValidation addRule(ExecutionPath fieldPath, BiFunction<FieldAndArguments, FieldValidationEnvironment, Optional<GraphQLError>> rule) { rules.put(fieldPath, rule); return this; }
[ "public", "SimpleFieldValidation", "addRule", "(", "ExecutionPath", "fieldPath", ",", "BiFunction", "<", "FieldAndArguments", ",", "FieldValidationEnvironment", ",", "Optional", "<", "GraphQLError", ">", ">", "rule", ")", "{", "rules", ".", "put", "(", "fieldPath", ",", "rule", ")", ";", "return", "this", ";", "}" ]
Adds the rule against the field address path. If the rule returns an error, it will be added to the list of errors @param fieldPath the path to the field @param rule the rule function @return this validator
[ "Adds", "the", "rule", "against", "the", "field", "address", "path", ".", "If", "the", "rule", "returns", "an", "error", "it", "will", "be", "added", "to", "the", "list", "of", "errors" ]
train
https://github.com/graphql-java/graphql-java/blob/9214b6044317849388bd88a14b54fc1c18c9f29f/src/main/java/graphql/execution/instrumentation/fieldvalidation/SimpleFieldValidation.java#L34-L37
bazaarvoice/emodb
common/stash/src/main/java/com/bazaarvoice/emodb/common/stash/RestartingS3InputStream.java
RestartingS3InputStream.reopenS3InputStream
private void reopenS3InputStream() throws IOException { // First attempt to close the existing input stream try { closeS3InputStream(); } catch (IOException ignore) { // Ignore this exception; we're re-opening because there was in issue with the existing stream // in the first place. } InputStream remainingIn = null; int attempt = 0; while (remainingIn == null) { try { S3Object s3Object = _s3.getObject( new GetObjectRequest(_bucket, _key) .withRange(_pos, _length - 1)); // Range is inclusive, hence length-1 remainingIn = s3Object.getObjectContent(); } catch (AmazonClientException e) { // Allow up to 3 retries attempt += 1; if (!e.isRetryable() || attempt == 4) { throw e; } // Back-off on each retry try { Thread.sleep(200 * attempt); } catch (InterruptedException interrupt) { throw Throwables.propagate(interrupt); } } } _in = remainingIn; }
java
private void reopenS3InputStream() throws IOException { // First attempt to close the existing input stream try { closeS3InputStream(); } catch (IOException ignore) { // Ignore this exception; we're re-opening because there was in issue with the existing stream // in the first place. } InputStream remainingIn = null; int attempt = 0; while (remainingIn == null) { try { S3Object s3Object = _s3.getObject( new GetObjectRequest(_bucket, _key) .withRange(_pos, _length - 1)); // Range is inclusive, hence length-1 remainingIn = s3Object.getObjectContent(); } catch (AmazonClientException e) { // Allow up to 3 retries attempt += 1; if (!e.isRetryable() || attempt == 4) { throw e; } // Back-off on each retry try { Thread.sleep(200 * attempt); } catch (InterruptedException interrupt) { throw Throwables.propagate(interrupt); } } } _in = remainingIn; }
[ "private", "void", "reopenS3InputStream", "(", ")", "throws", "IOException", "{", "// First attempt to close the existing input stream", "try", "{", "closeS3InputStream", "(", ")", ";", "}", "catch", "(", "IOException", "ignore", ")", "{", "// Ignore this exception; we're re-opening because there was in issue with the existing stream", "// in the first place.", "}", "InputStream", "remainingIn", "=", "null", ";", "int", "attempt", "=", "0", ";", "while", "(", "remainingIn", "==", "null", ")", "{", "try", "{", "S3Object", "s3Object", "=", "_s3", ".", "getObject", "(", "new", "GetObjectRequest", "(", "_bucket", ",", "_key", ")", ".", "withRange", "(", "_pos", ",", "_length", "-", "1", ")", ")", ";", "// Range is inclusive, hence length-1", "remainingIn", "=", "s3Object", ".", "getObjectContent", "(", ")", ";", "}", "catch", "(", "AmazonClientException", "e", ")", "{", "// Allow up to 3 retries", "attempt", "+=", "1", ";", "if", "(", "!", "e", ".", "isRetryable", "(", ")", "||", "attempt", "==", "4", ")", "{", "throw", "e", ";", "}", "// Back-off on each retry", "try", "{", "Thread", ".", "sleep", "(", "200", "*", "attempt", ")", ";", "}", "catch", "(", "InterruptedException", "interrupt", ")", "{", "throw", "Throwables", ".", "propagate", "(", "interrupt", ")", ";", "}", "}", "}", "_in", "=", "remainingIn", ";", "}" ]
Re-opens the input stream, starting at the first unread byte.
[ "Re", "-", "opens", "the", "input", "stream", "starting", "at", "the", "first", "unread", "byte", "." ]
train
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/common/stash/src/main/java/com/bazaarvoice/emodb/common/stash/RestartingS3InputStream.java#L137-L172
wildfly/wildfly-core
controller/src/main/java/org/jboss/as/controller/registry/NotificationHandlerNodeSubregistry.java
NotificationHandlerNodeSubregistry.unregisterEntry
void unregisterEntry(ListIterator<PathElement> iterator, String value, ConcreteNotificationHandlerRegistration.NotificationHandlerEntry entry) { NotificationHandlerNodeRegistry registry = childRegistries.get(value); if (registry == null) { return; } registry.unregisterEntry(iterator, entry); }
java
void unregisterEntry(ListIterator<PathElement> iterator, String value, ConcreteNotificationHandlerRegistration.NotificationHandlerEntry entry) { NotificationHandlerNodeRegistry registry = childRegistries.get(value); if (registry == null) { return; } registry.unregisterEntry(iterator, entry); }
[ "void", "unregisterEntry", "(", "ListIterator", "<", "PathElement", ">", "iterator", ",", "String", "value", ",", "ConcreteNotificationHandlerRegistration", ".", "NotificationHandlerEntry", "entry", ")", "{", "NotificationHandlerNodeRegistry", "registry", "=", "childRegistries", ".", "get", "(", "value", ")", ";", "if", "(", "registry", "==", "null", ")", "{", "return", ";", "}", "registry", ".", "unregisterEntry", "(", "iterator", ",", "entry", ")", ";", "}" ]
Get the registry child for the given {@code elementValue} and traverse it to unregister the entry.
[ "Get", "the", "registry", "child", "for", "the", "given", "{" ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/registry/NotificationHandlerNodeSubregistry.java#L82-L88
playn/playn
core/src/playn/core/Keyboard.java
Keyboard.isKey
public static KeyEvent isKey (Key key, Event event) { if (event instanceof KeyEvent && ((KeyEvent)event).key == key) { return (KeyEvent)event; } else { return null; } }
java
public static KeyEvent isKey (Key key, Event event) { if (event instanceof KeyEvent && ((KeyEvent)event).key == key) { return (KeyEvent)event; } else { return null; } }
[ "public", "static", "KeyEvent", "isKey", "(", "Key", "key", ",", "Event", "event", ")", "{", "if", "(", "event", "instanceof", "KeyEvent", "&&", "(", "(", "KeyEvent", ")", "event", ")", ".", "key", "==", "key", ")", "{", "return", "(", "KeyEvent", ")", "event", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
A collector function for key events for {@code key}. Use it to obtain only events for a particular key like so: <pre>{@code Input.keyboardEvents.collect(ev -> Keyboard.isKey(Key.X, ev)).connect(event -> { // handle the 'x' key being pressed or released }); }</pre>
[ "A", "collector", "function", "for", "key", "events", "for", "{", "@code", "key", "}", ".", "Use", "it", "to", "obtain", "only", "events", "for", "a", "particular", "key", "like", "so", ":" ]
train
https://github.com/playn/playn/blob/7e7a9d048ba6afe550dc0cdeaca3e1d5b0d01c66/core/src/playn/core/Keyboard.java#L141-L147
davidcarboni/restolino
src/main/java/com/github/davidcarboni/restolino/api/Router.java
Router.doMethod
void doMethod(HttpServletRequest request, HttpServletResponse response, HttpMethod httpMethod) { // Locate a request handler: String requestPath = mapRequestPath(request); Route route = api.get(requestPath); try { if (route != null && route.requestHandlers.containsKey(httpMethod)) { handleRequest(request, response, route, httpMethod); } else { handleNotFound(request, response); } } catch (Throwable t) { // Chances are the exception we've actually caught is the reflection // one from Method.invoke(...) Throwable caught = t; if (InvocationTargetException.class.isAssignableFrom(t.getClass())) { caught = t.getCause(); } RequestHandler requestHandler = (route == null ? null : route.requestHandlers.get(httpMethod)); handleError(request, response, requestHandler, caught); } }
java
void doMethod(HttpServletRequest request, HttpServletResponse response, HttpMethod httpMethod) { // Locate a request handler: String requestPath = mapRequestPath(request); Route route = api.get(requestPath); try { if (route != null && route.requestHandlers.containsKey(httpMethod)) { handleRequest(request, response, route, httpMethod); } else { handleNotFound(request, response); } } catch (Throwable t) { // Chances are the exception we've actually caught is the reflection // one from Method.invoke(...) Throwable caught = t; if (InvocationTargetException.class.isAssignableFrom(t.getClass())) { caught = t.getCause(); } RequestHandler requestHandler = (route == null ? null : route.requestHandlers.get(httpMethod)); handleError(request, response, requestHandler, caught); } }
[ "void", "doMethod", "(", "HttpServletRequest", "request", ",", "HttpServletResponse", "response", ",", "HttpMethod", "httpMethod", ")", "{", "// Locate a request handler:", "String", "requestPath", "=", "mapRequestPath", "(", "request", ")", ";", "Route", "route", "=", "api", ".", "get", "(", "requestPath", ")", ";", "try", "{", "if", "(", "route", "!=", "null", "&&", "route", ".", "requestHandlers", ".", "containsKey", "(", "httpMethod", ")", ")", "{", "handleRequest", "(", "request", ",", "response", ",", "route", ",", "httpMethod", ")", ";", "}", "else", "{", "handleNotFound", "(", "request", ",", "response", ")", ";", "}", "}", "catch", "(", "Throwable", "t", ")", "{", "// Chances are the exception we've actually caught is the reflection", "// one from Method.invoke(...)", "Throwable", "caught", "=", "t", ";", "if", "(", "InvocationTargetException", ".", "class", ".", "isAssignableFrom", "(", "t", ".", "getClass", "(", ")", ")", ")", "{", "caught", "=", "t", ".", "getCause", "(", ")", ";", "}", "RequestHandler", "requestHandler", "=", "(", "route", "==", "null", "?", "null", ":", "route", ".", "requestHandlers", ".", "get", "(", "httpMethod", ")", ")", ";", "handleError", "(", "request", ",", "response", ",", "requestHandler", ",", "caught", ")", ";", "}", "}" ]
GO! @param request The request. @param response The response.
[ "GO!" ]
train
https://github.com/davidcarboni/restolino/blob/3f84ece1bd016fbb597c624d46fcca5a2580a33d/src/main/java/com/github/davidcarboni/restolino/api/Router.java#L322-L349
facebookarchive/hadoop-20
src/core/org/apache/hadoop/util/MRAsyncDiskService.java
MRAsyncDiskService.awaitTermination
public synchronized boolean awaitTermination(long milliseconds) throws InterruptedException { boolean result = asyncDiskService.awaitTermination(milliseconds); if (result) { LOG.info("Deleting toBeDeleted directory."); for (int v = 0; v < volumes.length; v++) { Path p = new Path(volumes[v], TOBEDELETED); try { localFileSystem.delete(p, true); } catch (IOException e) { LOG.warn("Cannot cleanup " + p + " " + StringUtils.stringifyException(e)); } } } return result; }
java
public synchronized boolean awaitTermination(long milliseconds) throws InterruptedException { boolean result = asyncDiskService.awaitTermination(milliseconds); if (result) { LOG.info("Deleting toBeDeleted directory."); for (int v = 0; v < volumes.length; v++) { Path p = new Path(volumes[v], TOBEDELETED); try { localFileSystem.delete(p, true); } catch (IOException e) { LOG.warn("Cannot cleanup " + p + " " + StringUtils.stringifyException(e)); } } } return result; }
[ "public", "synchronized", "boolean", "awaitTermination", "(", "long", "milliseconds", ")", "throws", "InterruptedException", "{", "boolean", "result", "=", "asyncDiskService", ".", "awaitTermination", "(", "milliseconds", ")", ";", "if", "(", "result", ")", "{", "LOG", ".", "info", "(", "\"Deleting toBeDeleted directory.\"", ")", ";", "for", "(", "int", "v", "=", "0", ";", "v", "<", "volumes", ".", "length", ";", "v", "++", ")", "{", "Path", "p", "=", "new", "Path", "(", "volumes", "[", "v", "]", ",", "TOBEDELETED", ")", ";", "try", "{", "localFileSystem", ".", "delete", "(", "p", ",", "true", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "LOG", ".", "warn", "(", "\"Cannot cleanup \"", "+", "p", "+", "\" \"", "+", "StringUtils", ".", "stringifyException", "(", "e", ")", ")", ";", "}", "}", "}", "return", "result", ";", "}" ]
Wait for the termination of the thread pools. @param milliseconds The number of milliseconds to wait @return true if all thread pools are terminated within time limit @throws InterruptedException
[ "Wait", "for", "the", "termination", "of", "the", "thread", "pools", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/util/MRAsyncDiskService.java#L157-L172
phax/ph-commons
ph-security/src/main/java/com/helger/security/certificate/CertificateHelper.java
CertificateHelper.convertStringToCertficate
@Nullable public static X509Certificate convertStringToCertficate (@Nullable final String sCertString) throws CertificateException { if (StringHelper.hasNoText (sCertString)) { // No string -> no certificate return null; } final CertificateFactory aCertificateFactory = getX509CertificateFactory (); // Convert certificate string to an object try { return _str2cert (sCertString, aCertificateFactory); } catch (final IllegalArgumentException | CertificateException ex) { // In some weird configurations, the result string is a hex encoded // certificate instead of the string // -> Try to work around it if (LOGGER.isDebugEnabled ()) LOGGER.debug ("Failed to decode provided X.509 certificate string: " + sCertString); String sHexDecodedString; try { sHexDecodedString = new String (StringHelper.getHexDecoded (sCertString), CERT_CHARSET); } catch (final IllegalArgumentException ex2) { // Can happen, when the source string has an odd length (like 3 or 117). // In this case the original exception is rethrown throw ex; } return _str2cert (sHexDecodedString, aCertificateFactory); } }
java
@Nullable public static X509Certificate convertStringToCertficate (@Nullable final String sCertString) throws CertificateException { if (StringHelper.hasNoText (sCertString)) { // No string -> no certificate return null; } final CertificateFactory aCertificateFactory = getX509CertificateFactory (); // Convert certificate string to an object try { return _str2cert (sCertString, aCertificateFactory); } catch (final IllegalArgumentException | CertificateException ex) { // In some weird configurations, the result string is a hex encoded // certificate instead of the string // -> Try to work around it if (LOGGER.isDebugEnabled ()) LOGGER.debug ("Failed to decode provided X.509 certificate string: " + sCertString); String sHexDecodedString; try { sHexDecodedString = new String (StringHelper.getHexDecoded (sCertString), CERT_CHARSET); } catch (final IllegalArgumentException ex2) { // Can happen, when the source string has an odd length (like 3 or 117). // In this case the original exception is rethrown throw ex; } return _str2cert (sHexDecodedString, aCertificateFactory); } }
[ "@", "Nullable", "public", "static", "X509Certificate", "convertStringToCertficate", "(", "@", "Nullable", "final", "String", "sCertString", ")", "throws", "CertificateException", "{", "if", "(", "StringHelper", ".", "hasNoText", "(", "sCertString", ")", ")", "{", "// No string -> no certificate", "return", "null", ";", "}", "final", "CertificateFactory", "aCertificateFactory", "=", "getX509CertificateFactory", "(", ")", ";", "// Convert certificate string to an object", "try", "{", "return", "_str2cert", "(", "sCertString", ",", "aCertificateFactory", ")", ";", "}", "catch", "(", "final", "IllegalArgumentException", "|", "CertificateException", "ex", ")", "{", "// In some weird configurations, the result string is a hex encoded", "// certificate instead of the string", "// -> Try to work around it", "if", "(", "LOGGER", ".", "isDebugEnabled", "(", ")", ")", "LOGGER", ".", "debug", "(", "\"Failed to decode provided X.509 certificate string: \"", "+", "sCertString", ")", ";", "String", "sHexDecodedString", ";", "try", "{", "sHexDecodedString", "=", "new", "String", "(", "StringHelper", ".", "getHexDecoded", "(", "sCertString", ")", ",", "CERT_CHARSET", ")", ";", "}", "catch", "(", "final", "IllegalArgumentException", "ex2", ")", "{", "// Can happen, when the source string has an odd length (like 3 or 117).", "// In this case the original exception is rethrown", "throw", "ex", ";", "}", "return", "_str2cert", "(", "sHexDecodedString", ",", "aCertificateFactory", ")", ";", "}", "}" ]
Convert the passed String to an X.509 certificate. @param sCertString The original text string. May be <code>null</code> or empty. The String must be ISO-8859-1 encoded for the binary certificate to be read! @return <code>null</code> if the passed string is <code>null</code> or empty @throws CertificateException In case the passed string cannot be converted to an X.509 certificate. @throws IllegalArgumentException If the input string is e.g. invalid Base64 encoded.
[ "Convert", "the", "passed", "String", "to", "an", "X", ".", "509", "certificate", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-security/src/main/java/com/helger/security/certificate/CertificateHelper.java#L246-L284
apache/groovy
src/main/java/org/codehaus/groovy/runtime/ResourceGroovyMethods.java
ResourceGroovyMethods.newInputStream
public static BufferedInputStream newInputStream(URL url) throws MalformedURLException, IOException { return new BufferedInputStream(configuredInputStream(null, url)); }
java
public static BufferedInputStream newInputStream(URL url) throws MalformedURLException, IOException { return new BufferedInputStream(configuredInputStream(null, url)); }
[ "public", "static", "BufferedInputStream", "newInputStream", "(", "URL", "url", ")", "throws", "MalformedURLException", ",", "IOException", "{", "return", "new", "BufferedInputStream", "(", "configuredInputStream", "(", "null", ",", "url", ")", ")", ";", "}" ]
Creates a buffered input stream for this URL. @param url a URL @return a BufferedInputStream for the URL @throws MalformedURLException is thrown if the URL is not well formed @throws IOException if an I/O error occurs while creating the input stream @since 1.5.2
[ "Creates", "a", "buffered", "input", "stream", "for", "this", "URL", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/ResourceGroovyMethods.java#L2195-L2197
Azure/azure-sdk-for-java
appservice/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/appservice/v2018_02_01/implementation/AppServiceCertificateOrdersInner.java
AppServiceCertificateOrdersInner.createOrUpdate
public AppServiceCertificateOrderInner createOrUpdate(String resourceGroupName, String certificateOrderName, AppServiceCertificateOrderInner certificateDistinguishedName) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, certificateOrderName, certificateDistinguishedName).toBlocking().last().body(); }
java
public AppServiceCertificateOrderInner createOrUpdate(String resourceGroupName, String certificateOrderName, AppServiceCertificateOrderInner certificateDistinguishedName) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, certificateOrderName, certificateDistinguishedName).toBlocking().last().body(); }
[ "public", "AppServiceCertificateOrderInner", "createOrUpdate", "(", "String", "resourceGroupName", ",", "String", "certificateOrderName", ",", "AppServiceCertificateOrderInner", "certificateDistinguishedName", ")", "{", "return", "createOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "certificateOrderName", ",", "certificateDistinguishedName", ")", ".", "toBlocking", "(", ")", ".", "last", "(", ")", ".", "body", "(", ")", ";", "}" ]
Create or update a certificate purchase order. Create or update a certificate purchase order. @param resourceGroupName Name of the resource group to which the resource belongs. @param certificateOrderName Name of the certificate order. @param certificateDistinguishedName Distinguished name to to use for the certificate order. @throws IllegalArgumentException thrown if parameters fail the validation @throws DefaultErrorResponseException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the AppServiceCertificateOrderInner object if successful.
[ "Create", "or", "update", "a", "certificate", "purchase", "order", ".", "Create", "or", "update", "a", "certificate", "purchase", "order", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/appservice/v2018_02_01/implementation/AppServiceCertificateOrdersInner.java#L594-L596
Azure/azure-sdk-for-java
cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java
ModelsImpl.listClosedListsWithServiceResponseAsync
public Observable<ServiceResponse<List<ClosedListEntityExtractor>>> listClosedListsWithServiceResponseAsync(UUID appId, String versionId, ListClosedListsOptionalParameter listClosedListsOptionalParameter) { if (this.client.endpoint() == null) { throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null."); } if (appId == null) { throw new IllegalArgumentException("Parameter appId is required and cannot be null."); } if (versionId == null) { throw new IllegalArgumentException("Parameter versionId is required and cannot be null."); } final Integer skip = listClosedListsOptionalParameter != null ? listClosedListsOptionalParameter.skip() : null; final Integer take = listClosedListsOptionalParameter != null ? listClosedListsOptionalParameter.take() : null; return listClosedListsWithServiceResponseAsync(appId, versionId, skip, take); }
java
public Observable<ServiceResponse<List<ClosedListEntityExtractor>>> listClosedListsWithServiceResponseAsync(UUID appId, String versionId, ListClosedListsOptionalParameter listClosedListsOptionalParameter) { if (this.client.endpoint() == null) { throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null."); } if (appId == null) { throw new IllegalArgumentException("Parameter appId is required and cannot be null."); } if (versionId == null) { throw new IllegalArgumentException("Parameter versionId is required and cannot be null."); } final Integer skip = listClosedListsOptionalParameter != null ? listClosedListsOptionalParameter.skip() : null; final Integer take = listClosedListsOptionalParameter != null ? listClosedListsOptionalParameter.take() : null; return listClosedListsWithServiceResponseAsync(appId, versionId, skip, take); }
[ "public", "Observable", "<", "ServiceResponse", "<", "List", "<", "ClosedListEntityExtractor", ">", ">", ">", "listClosedListsWithServiceResponseAsync", "(", "UUID", "appId", ",", "String", "versionId", ",", "ListClosedListsOptionalParameter", "listClosedListsOptionalParameter", ")", "{", "if", "(", "this", ".", "client", ".", "endpoint", "(", ")", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Parameter this.client.endpoint() is required and cannot be null.\"", ")", ";", "}", "if", "(", "appId", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Parameter appId is required and cannot be null.\"", ")", ";", "}", "if", "(", "versionId", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Parameter versionId is required and cannot be null.\"", ")", ";", "}", "final", "Integer", "skip", "=", "listClosedListsOptionalParameter", "!=", "null", "?", "listClosedListsOptionalParameter", ".", "skip", "(", ")", ":", "null", ";", "final", "Integer", "take", "=", "listClosedListsOptionalParameter", "!=", "null", "?", "listClosedListsOptionalParameter", ".", "take", "(", ")", ":", "null", ";", "return", "listClosedListsWithServiceResponseAsync", "(", "appId", ",", "versionId", ",", "skip", ",", "take", ")", ";", "}" ]
Gets information about the closedlist models. @param appId The application ID. @param versionId The version ID. @param listClosedListsOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the List&lt;ClosedListEntityExtractor&gt; object
[ "Gets", "information", "about", "the", "closedlist", "models", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java#L1866-L1880
Azure/azure-sdk-for-java
logic/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/logic/v2016_06_01/implementation/IntegrationAccountAssembliesInner.java
IntegrationAccountAssembliesInner.createOrUpdateAsync
public Observable<AssemblyDefinitionInner> createOrUpdateAsync(String resourceGroupName, String integrationAccountName, String assemblyArtifactName, AssemblyDefinitionInner assemblyArtifact) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, integrationAccountName, assemblyArtifactName, assemblyArtifact).map(new Func1<ServiceResponse<AssemblyDefinitionInner>, AssemblyDefinitionInner>() { @Override public AssemblyDefinitionInner call(ServiceResponse<AssemblyDefinitionInner> response) { return response.body(); } }); }
java
public Observable<AssemblyDefinitionInner> createOrUpdateAsync(String resourceGroupName, String integrationAccountName, String assemblyArtifactName, AssemblyDefinitionInner assemblyArtifact) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, integrationAccountName, assemblyArtifactName, assemblyArtifact).map(new Func1<ServiceResponse<AssemblyDefinitionInner>, AssemblyDefinitionInner>() { @Override public AssemblyDefinitionInner call(ServiceResponse<AssemblyDefinitionInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "AssemblyDefinitionInner", ">", "createOrUpdateAsync", "(", "String", "resourceGroupName", ",", "String", "integrationAccountName", ",", "String", "assemblyArtifactName", ",", "AssemblyDefinitionInner", "assemblyArtifact", ")", "{", "return", "createOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "integrationAccountName", ",", "assemblyArtifactName", ",", "assemblyArtifact", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "AssemblyDefinitionInner", ">", ",", "AssemblyDefinitionInner", ">", "(", ")", "{", "@", "Override", "public", "AssemblyDefinitionInner", "call", "(", "ServiceResponse", "<", "AssemblyDefinitionInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Create or update an assembly for an integration account. @param resourceGroupName The resource group name. @param integrationAccountName The integration account name. @param assemblyArtifactName The assembly artifact name. @param assemblyArtifact The assembly artifact. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the AssemblyDefinitionInner object
[ "Create", "or", "update", "an", "assembly", "for", "an", "integration", "account", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/logic/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/logic/v2016_06_01/implementation/IntegrationAccountAssembliesInner.java#L307-L314
Azure/azure-sdk-for-java
cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java
ModelsImpl.updatePatternAnyEntityRoleWithServiceResponseAsync
public Observable<ServiceResponse<OperationStatus>> updatePatternAnyEntityRoleWithServiceResponseAsync(UUID appId, String versionId, UUID entityId, UUID roleId, UpdatePatternAnyEntityRoleOptionalParameter updatePatternAnyEntityRoleOptionalParameter) { if (this.client.endpoint() == null) { throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null."); } if (appId == null) { throw new IllegalArgumentException("Parameter appId is required and cannot be null."); } if (versionId == null) { throw new IllegalArgumentException("Parameter versionId is required and cannot be null."); } if (entityId == null) { throw new IllegalArgumentException("Parameter entityId is required and cannot be null."); } if (roleId == null) { throw new IllegalArgumentException("Parameter roleId is required and cannot be null."); } final String name = updatePatternAnyEntityRoleOptionalParameter != null ? updatePatternAnyEntityRoleOptionalParameter.name() : null; return updatePatternAnyEntityRoleWithServiceResponseAsync(appId, versionId, entityId, roleId, name); }
java
public Observable<ServiceResponse<OperationStatus>> updatePatternAnyEntityRoleWithServiceResponseAsync(UUID appId, String versionId, UUID entityId, UUID roleId, UpdatePatternAnyEntityRoleOptionalParameter updatePatternAnyEntityRoleOptionalParameter) { if (this.client.endpoint() == null) { throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null."); } if (appId == null) { throw new IllegalArgumentException("Parameter appId is required and cannot be null."); } if (versionId == null) { throw new IllegalArgumentException("Parameter versionId is required and cannot be null."); } if (entityId == null) { throw new IllegalArgumentException("Parameter entityId is required and cannot be null."); } if (roleId == null) { throw new IllegalArgumentException("Parameter roleId is required and cannot be null."); } final String name = updatePatternAnyEntityRoleOptionalParameter != null ? updatePatternAnyEntityRoleOptionalParameter.name() : null; return updatePatternAnyEntityRoleWithServiceResponseAsync(appId, versionId, entityId, roleId, name); }
[ "public", "Observable", "<", "ServiceResponse", "<", "OperationStatus", ">", ">", "updatePatternAnyEntityRoleWithServiceResponseAsync", "(", "UUID", "appId", ",", "String", "versionId", ",", "UUID", "entityId", ",", "UUID", "roleId", ",", "UpdatePatternAnyEntityRoleOptionalParameter", "updatePatternAnyEntityRoleOptionalParameter", ")", "{", "if", "(", "this", ".", "client", ".", "endpoint", "(", ")", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Parameter this.client.endpoint() is required and cannot be null.\"", ")", ";", "}", "if", "(", "appId", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Parameter appId is required and cannot be null.\"", ")", ";", "}", "if", "(", "versionId", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Parameter versionId is required and cannot be null.\"", ")", ";", "}", "if", "(", "entityId", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Parameter entityId is required and cannot be null.\"", ")", ";", "}", "if", "(", "roleId", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Parameter roleId is required and cannot be null.\"", ")", ";", "}", "final", "String", "name", "=", "updatePatternAnyEntityRoleOptionalParameter", "!=", "null", "?", "updatePatternAnyEntityRoleOptionalParameter", ".", "name", "(", ")", ":", "null", ";", "return", "updatePatternAnyEntityRoleWithServiceResponseAsync", "(", "appId", ",", "versionId", ",", "entityId", ",", "roleId", ",", "name", ")", ";", "}" ]
Update an entity role for a given entity. @param appId The application ID. @param versionId The version ID. @param entityId The entity ID. @param roleId The entity role ID. @param updatePatternAnyEntityRoleOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the OperationStatus object
[ "Update", "an", "entity", "role", "for", "a", "given", "entity", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java#L12908-L12927
looly/hutool
hutool-http/src/main/java/cn/hutool/http/HttpConnection.java
HttpConnection.setHttpsInfo
public HttpConnection setHttpsInfo(HostnameVerifier hostnameVerifier, SSLSocketFactory ssf) throws HttpException { final HttpURLConnection conn = this.conn; if (conn instanceof HttpsURLConnection) { // Https请求 final HttpsURLConnection httpsConn = (HttpsURLConnection) conn; // 验证域 httpsConn.setHostnameVerifier(null != hostnameVerifier ? hostnameVerifier : new TrustAnyHostnameVerifier()); if (null == ssf) { try { if (StrUtil.equalsIgnoreCase("dalvik", System.getProperty("java.vm.name"))) { // 兼容android低版本SSL连接 ssf = new AndroidSupportSSLFactory(); } else { ssf = SSLSocketFactoryBuilder.create().build(); } } catch (KeyManagementException | NoSuchAlgorithmException e) { throw new HttpException(e); } } httpsConn.setSSLSocketFactory(ssf); } return this; }
java
public HttpConnection setHttpsInfo(HostnameVerifier hostnameVerifier, SSLSocketFactory ssf) throws HttpException { final HttpURLConnection conn = this.conn; if (conn instanceof HttpsURLConnection) { // Https请求 final HttpsURLConnection httpsConn = (HttpsURLConnection) conn; // 验证域 httpsConn.setHostnameVerifier(null != hostnameVerifier ? hostnameVerifier : new TrustAnyHostnameVerifier()); if (null == ssf) { try { if (StrUtil.equalsIgnoreCase("dalvik", System.getProperty("java.vm.name"))) { // 兼容android低版本SSL连接 ssf = new AndroidSupportSSLFactory(); } else { ssf = SSLSocketFactoryBuilder.create().build(); } } catch (KeyManagementException | NoSuchAlgorithmException e) { throw new HttpException(e); } } httpsConn.setSSLSocketFactory(ssf); } return this; }
[ "public", "HttpConnection", "setHttpsInfo", "(", "HostnameVerifier", "hostnameVerifier", ",", "SSLSocketFactory", "ssf", ")", "throws", "HttpException", "{", "final", "HttpURLConnection", "conn", "=", "this", ".", "conn", ";", "if", "(", "conn", "instanceof", "HttpsURLConnection", ")", "{", "// Https请求\r", "final", "HttpsURLConnection", "httpsConn", "=", "(", "HttpsURLConnection", ")", "conn", ";", "// 验证域\r", "httpsConn", ".", "setHostnameVerifier", "(", "null", "!=", "hostnameVerifier", "?", "hostnameVerifier", ":", "new", "TrustAnyHostnameVerifier", "(", ")", ")", ";", "if", "(", "null", "==", "ssf", ")", "{", "try", "{", "if", "(", "StrUtil", ".", "equalsIgnoreCase", "(", "\"dalvik\"", ",", "System", ".", "getProperty", "(", "\"java.vm.name\"", ")", ")", ")", "{", "// 兼容android低版本SSL连接\r", "ssf", "=", "new", "AndroidSupportSSLFactory", "(", ")", ";", "}", "else", "{", "ssf", "=", "SSLSocketFactoryBuilder", ".", "create", "(", ")", ".", "build", "(", ")", ";", "}", "}", "catch", "(", "KeyManagementException", "|", "NoSuchAlgorithmException", "e", ")", "{", "throw", "new", "HttpException", "(", "e", ")", ";", "}", "}", "httpsConn", ".", "setSSLSocketFactory", "(", "ssf", ")", ";", "}", "return", "this", ";", "}" ]
设置https请求参数<br> 有些时候htts请求会出现com.sun.net.ssl.internal.www.protocol.https.HttpsURLConnectionOldImpl的实现,此为sun内部api,按照普通http请求处理 @param hostnameVerifier 域名验证器,非https传入null @param ssf SSLSocketFactory,非https传入null @return this @throws HttpException KeyManagementException和NoSuchAlgorithmException异常包装
[ "设置https请求参数<br", ">", "有些时候htts请求会出现com", ".", "sun", ".", "net", ".", "ssl", ".", "internal", ".", "www", ".", "protocol", ".", "https", ".", "HttpsURLConnectionOldImpl的实现,此为sun内部api,按照普通http请求处理" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-http/src/main/java/cn/hutool/http/HttpConnection.java#L261-L285
b3log/latke
latke-core/src/main/java/org/b3log/latke/repository/jdbc/JdbcRepository.java
JdbcRepository.buildOrderBy
private void buildOrderBy(final StringBuilder orderByBuilder, final Map<String, SortDirection> sorts) { boolean isFirst = true; String querySortDirection; for (final Map.Entry<String, SortDirection> sort : sorts.entrySet()) { if (isFirst) { orderByBuilder.append(" ORDER BY "); isFirst = false; } else { orderByBuilder.append(", "); } if (sort.getValue().equals(SortDirection.ASCENDING)) { querySortDirection = "ASC"; } else { querySortDirection = "DESC"; } orderByBuilder.append(sort.getKey()).append(" ").append(querySortDirection); } }
java
private void buildOrderBy(final StringBuilder orderByBuilder, final Map<String, SortDirection> sorts) { boolean isFirst = true; String querySortDirection; for (final Map.Entry<String, SortDirection> sort : sorts.entrySet()) { if (isFirst) { orderByBuilder.append(" ORDER BY "); isFirst = false; } else { orderByBuilder.append(", "); } if (sort.getValue().equals(SortDirection.ASCENDING)) { querySortDirection = "ASC"; } else { querySortDirection = "DESC"; } orderByBuilder.append(sort.getKey()).append(" ").append(querySortDirection); } }
[ "private", "void", "buildOrderBy", "(", "final", "StringBuilder", "orderByBuilder", ",", "final", "Map", "<", "String", ",", "SortDirection", ">", "sorts", ")", "{", "boolean", "isFirst", "=", "true", ";", "String", "querySortDirection", ";", "for", "(", "final", "Map", ".", "Entry", "<", "String", ",", "SortDirection", ">", "sort", ":", "sorts", ".", "entrySet", "(", ")", ")", "{", "if", "(", "isFirst", ")", "{", "orderByBuilder", ".", "append", "(", "\" ORDER BY \"", ")", ";", "isFirst", "=", "false", ";", "}", "else", "{", "orderByBuilder", ".", "append", "(", "\", \"", ")", ";", "}", "if", "(", "sort", ".", "getValue", "(", ")", ".", "equals", "(", "SortDirection", ".", "ASCENDING", ")", ")", "{", "querySortDirection", "=", "\"ASC\"", ";", "}", "else", "{", "querySortDirection", "=", "\"DESC\"", ";", "}", "orderByBuilder", ".", "append", "(", "sort", ".", "getKey", "(", ")", ")", ".", "append", "(", "\" \"", ")", ".", "append", "(", "querySortDirection", ")", ";", "}", "}" ]
Builds 'ORDER BY' part with the specified order by build and sorts. @param orderByBuilder the specified order by builder @param sorts the specified sorts
[ "Builds", "ORDER", "BY", "part", "with", "the", "specified", "order", "by", "build", "and", "sorts", "." ]
train
https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/repository/jdbc/JdbcRepository.java#L619-L638
powermock/powermock
powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/PowerMock.java
PowerMock.createNicePartialMock
public static <T> T createNicePartialMock(Class<T> type, String methodName, Class<?>[] methodParameterTypes, Object[] constructorArguments, Class<?>[] constructorParameterTypes) { ConstructorArgs constructorArgs = new ConstructorArgs(Whitebox.getConstructor(type, constructorParameterTypes), constructorArguments); return doMockSpecific(type, new NiceMockStrategy(), new String[]{methodName}, constructorArgs, methodParameterTypes); }
java
public static <T> T createNicePartialMock(Class<T> type, String methodName, Class<?>[] methodParameterTypes, Object[] constructorArguments, Class<?>[] constructorParameterTypes) { ConstructorArgs constructorArgs = new ConstructorArgs(Whitebox.getConstructor(type, constructorParameterTypes), constructorArguments); return doMockSpecific(type, new NiceMockStrategy(), new String[]{methodName}, constructorArgs, methodParameterTypes); }
[ "public", "static", "<", "T", ">", "T", "createNicePartialMock", "(", "Class", "<", "T", ">", "type", ",", "String", "methodName", ",", "Class", "<", "?", ">", "[", "]", "methodParameterTypes", ",", "Object", "[", "]", "constructorArguments", ",", "Class", "<", "?", ">", "[", "]", "constructorParameterTypes", ")", "{", "ConstructorArgs", "constructorArgs", "=", "new", "ConstructorArgs", "(", "Whitebox", ".", "getConstructor", "(", "type", ",", "constructorParameterTypes", ")", ",", "constructorArguments", ")", ";", "return", "doMockSpecific", "(", "type", ",", "new", "NiceMockStrategy", "(", ")", ",", "new", "String", "[", "]", "{", "methodName", "}", ",", "constructorArgs", ",", "methodParameterTypes", ")", ";", "}" ]
A utility method that may be used to nicely mock several methods in an easy way (by just passing in the method names of the method you wish to mock). Use this to handle overloaded methods <i>and</i> overloaded constructors. The mock object created will support mocking of final and native methods and invokes a specific constructor based on the supplied argument values. @param <T> the type of the mock object @param type the type of the mock object @param methodName The names of the methods that should be mocked. If {@code null}, then this method will have the same effect as just calling {@link #createMock(Class, Method...)} with the second parameter as {@code new Method[0]} (i.e. all methods in that class will be mocked). @param methodParameterTypes Parameter types that defines the method. Note that this is only needed to separate overloaded methods. @param constructorArguments The constructor arguments that will be used to invoke a certain constructor. @param constructorParameterTypes Parameter types that defines the constructor that should be invoked. Note that this is only needed to separate overloaded constructors. @return the mock object.
[ "A", "utility", "method", "that", "may", "be", "used", "to", "nicely", "mock", "several", "methods", "in", "an", "easy", "way", "(", "by", "just", "passing", "in", "the", "method", "names", "of", "the", "method", "you", "wish", "to", "mock", ")", ".", "Use", "this", "to", "handle", "overloaded", "methods", "<i", ">", "and<", "/", "i", ">", "overloaded", "constructors", ".", "The", "mock", "object", "created", "will", "support", "mocking", "of", "final", "and", "native", "methods", "and", "invokes", "a", "specific", "constructor", "based", "on", "the", "supplied", "argument", "values", "." ]
train
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/PowerMock.java#L1128-L1134
playn/playn
core/src/playn/core/Assets.java
Assets.getRemoteImage
public Image getRemoteImage (String url, int width, int height) { Exception error = new Exception( "Remote image loading not yet supported: " + url + "@" + width + "x" + height); ImageImpl image = createImage(false, width, height, url); image.fail(error); return image; }
java
public Image getRemoteImage (String url, int width, int height) { Exception error = new Exception( "Remote image loading not yet supported: " + url + "@" + width + "x" + height); ImageImpl image = createImage(false, width, height, url); image.fail(error); return image; }
[ "public", "Image", "getRemoteImage", "(", "String", "url", ",", "int", "width", ",", "int", "height", ")", "{", "Exception", "error", "=", "new", "Exception", "(", "\"Remote image loading not yet supported: \"", "+", "url", "+", "\"@\"", "+", "width", "+", "\"x\"", "+", "height", ")", ";", "ImageImpl", "image", "=", "createImage", "(", "false", ",", "width", ",", "height", ",", "url", ")", ";", "image", ".", "fail", "(", "error", ")", ";", "return", "image", ";", "}" ]
Asynchronously loads and returns the image at the specified URL. The width and height of the image will be the supplied {@code width} and {@code height} until the image is loaded. <em>Note:</em> on non-HTML platforms, this spawns a new thread for each loaded image. Thus, attempts to load large numbers of remote images simultaneously may result in poor performance.
[ "Asynchronously", "loads", "and", "returns", "the", "image", "at", "the", "specified", "URL", ".", "The", "width", "and", "height", "of", "the", "image", "will", "be", "the", "supplied", "{" ]
train
https://github.com/playn/playn/blob/7e7a9d048ba6afe550dc0cdeaca3e1d5b0d01c66/core/src/playn/core/Assets.java#L85-L91
Mozu/mozu-java
mozu-java-core/src/main/java/com/mozu/api/urls/commerce/catalog/admin/attributedefinition/attributes/AttributeVocabularyValueUrl.java
AttributeVocabularyValueUrl.deleteAttributeVocabularyValueLocalizedContentUrl
public static MozuUrl deleteAttributeVocabularyValueLocalizedContentUrl(String attributeFQN, String localeCode, String value) { UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/admin/attributedefinition/attributes/{attributeFQN}/VocabularyValues/{value}/LocalizedContent/{localeCode}"); formatter.formatUrl("attributeFQN", attributeFQN); formatter.formatUrl("localeCode", localeCode); formatter.formatUrl("value", value); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
java
public static MozuUrl deleteAttributeVocabularyValueLocalizedContentUrl(String attributeFQN, String localeCode, String value) { UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/admin/attributedefinition/attributes/{attributeFQN}/VocabularyValues/{value}/LocalizedContent/{localeCode}"); formatter.formatUrl("attributeFQN", attributeFQN); formatter.formatUrl("localeCode", localeCode); formatter.formatUrl("value", value); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
[ "public", "static", "MozuUrl", "deleteAttributeVocabularyValueLocalizedContentUrl", "(", "String", "attributeFQN", ",", "String", "localeCode", ",", "String", "value", ")", "{", "UrlFormatter", "formatter", "=", "new", "UrlFormatter", "(", "\"/api/commerce/catalog/admin/attributedefinition/attributes/{attributeFQN}/VocabularyValues/{value}/LocalizedContent/{localeCode}\"", ")", ";", "formatter", ".", "formatUrl", "(", "\"attributeFQN\"", ",", "attributeFQN", ")", ";", "formatter", ".", "formatUrl", "(", "\"localeCode\"", ",", "localeCode", ")", ";", "formatter", ".", "formatUrl", "(", "\"value\"", ",", "value", ")", ";", "return", "new", "MozuUrl", "(", "formatter", ".", "getResourceUrl", "(", ")", ",", "MozuUrl", ".", "UrlLocation", ".", "TENANT_POD", ")", ";", "}" ]
Get Resource Url for DeleteAttributeVocabularyValueLocalizedContent @param attributeFQN Fully qualified name for an attribute. @param localeCode The two character country code that sets the locale, such as US for United States. Sites, tenants, and catalogs use locale codes for localizing content, such as translated product text per supported country. @param value The value string to create. @return String Resource Url
[ "Get", "Resource", "Url", "for", "DeleteAttributeVocabularyValueLocalizedContent" ]
train
https://github.com/Mozu/mozu-java/blob/5beadde73601a859f845e3e2fc1077b39c8bea83/mozu-java-core/src/main/java/com/mozu/api/urls/commerce/catalog/admin/attributedefinition/attributes/AttributeVocabularyValueUrl.java#L187-L194
roboconf/roboconf-platform
core/roboconf-core/src/main/java/net/roboconf/core/utils/Utils.java
Utils.logException
public static void logException( Logger logger, Level logLevel, Throwable t, String message ) { if( logger.isLoggable( logLevel )) { StringBuilder sb = new StringBuilder(); if( message != null ) { sb.append( message ); sb.append( "\n" ); } sb.append( writeExceptionButDoNotUseItForLogging( t )); logger.log( logLevel, sb.toString()); } }
java
public static void logException( Logger logger, Level logLevel, Throwable t, String message ) { if( logger.isLoggable( logLevel )) { StringBuilder sb = new StringBuilder(); if( message != null ) { sb.append( message ); sb.append( "\n" ); } sb.append( writeExceptionButDoNotUseItForLogging( t )); logger.log( logLevel, sb.toString()); } }
[ "public", "static", "void", "logException", "(", "Logger", "logger", ",", "Level", "logLevel", ",", "Throwable", "t", ",", "String", "message", ")", "{", "if", "(", "logger", ".", "isLoggable", "(", "logLevel", ")", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "if", "(", "message", "!=", "null", ")", "{", "sb", ".", "append", "(", "message", ")", ";", "sb", ".", "append", "(", "\"\\n\"", ")", ";", "}", "sb", ".", "append", "(", "writeExceptionButDoNotUseItForLogging", "(", "t", ")", ")", ";", "logger", ".", "log", "(", "logLevel", ",", "sb", ".", "toString", "(", ")", ")", ";", "}", "}" ]
Logs an exception with the given logger and the given level. <p> Writing a stack trace may be time-consuming in some environments. To prevent useless computing, this method checks the current log level before trying to log anything. </p> @param logger the logger @param t an exception or a throwable @param logLevel the log level (see {@link Level}) @param message a message to insert before the stack trace
[ "Logs", "an", "exception", "with", "the", "given", "logger", "and", "the", "given", "level", ".", "<p", ">", "Writing", "a", "stack", "trace", "may", "be", "time", "-", "consuming", "in", "some", "environments", ".", "To", "prevent", "useless", "computing", "this", "method", "checks", "the", "current", "log", "level", "before", "trying", "to", "log", "anything", ".", "<", "/", "p", ">" ]
train
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/utils/Utils.java#L1099-L1111
Quickhull3d/quickhull3d
src/main/java/com/github/quickhull3d/QuickHull3D.java
QuickHull3D.build
public void build(Point3d[] points, int nump) throws IllegalArgumentException { if (nump < 4) { throw new IllegalArgumentException("Less than four input points specified"); } if (points.length < nump) { throw new IllegalArgumentException("Point array too small for specified number of points"); } initBuffers(nump); setPoints(points, nump); buildHull(); }
java
public void build(Point3d[] points, int nump) throws IllegalArgumentException { if (nump < 4) { throw new IllegalArgumentException("Less than four input points specified"); } if (points.length < nump) { throw new IllegalArgumentException("Point array too small for specified number of points"); } initBuffers(nump); setPoints(points, nump); buildHull(); }
[ "public", "void", "build", "(", "Point3d", "[", "]", "points", ",", "int", "nump", ")", "throws", "IllegalArgumentException", "{", "if", "(", "nump", "<", "4", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Less than four input points specified\"", ")", ";", "}", "if", "(", "points", ".", "length", "<", "nump", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Point array too small for specified number of points\"", ")", ";", "}", "initBuffers", "(", "nump", ")", ";", "setPoints", "(", "points", ",", "nump", ")", ";", "buildHull", "(", ")", ";", "}" ]
Constructs the convex hull of a set of points. @param points input points @param nump number of input points @throws IllegalArgumentException the number of input points is less than four or greater then the length of <code>points</code>, or the points appear to be coincident, colinear, or coplanar.
[ "Constructs", "the", "convex", "hull", "of", "a", "set", "of", "points", "." ]
train
https://github.com/Quickhull3d/quickhull3d/blob/3f80953b86c46385e84730e5d2a1745cbfa12703/src/main/java/com/github/quickhull3d/QuickHull3D.java#L499-L509
google/jimfs
jimfs/src/main/java/com/google/common/jimfs/FileSystemView.java
FileSystemView.newDirectoryStream
public DirectoryStream<Path> newDirectoryStream( JimfsPath dir, DirectoryStream.Filter<? super Path> filter, Set<? super LinkOption> options, JimfsPath basePathForStream) throws IOException { Directory file = (Directory) lookUpWithLock(dir, options).requireDirectory(dir).file(); FileSystemView view = new FileSystemView(store, file, basePathForStream); JimfsSecureDirectoryStream stream = new JimfsSecureDirectoryStream(view, filter, state()); return store.supportsFeature(Feature.SECURE_DIRECTORY_STREAM) ? stream : new DowngradedDirectoryStream(stream); }
java
public DirectoryStream<Path> newDirectoryStream( JimfsPath dir, DirectoryStream.Filter<? super Path> filter, Set<? super LinkOption> options, JimfsPath basePathForStream) throws IOException { Directory file = (Directory) lookUpWithLock(dir, options).requireDirectory(dir).file(); FileSystemView view = new FileSystemView(store, file, basePathForStream); JimfsSecureDirectoryStream stream = new JimfsSecureDirectoryStream(view, filter, state()); return store.supportsFeature(Feature.SECURE_DIRECTORY_STREAM) ? stream : new DowngradedDirectoryStream(stream); }
[ "public", "DirectoryStream", "<", "Path", ">", "newDirectoryStream", "(", "JimfsPath", "dir", ",", "DirectoryStream", ".", "Filter", "<", "?", "super", "Path", ">", "filter", ",", "Set", "<", "?", "super", "LinkOption", ">", "options", ",", "JimfsPath", "basePathForStream", ")", "throws", "IOException", "{", "Directory", "file", "=", "(", "Directory", ")", "lookUpWithLock", "(", "dir", ",", "options", ")", ".", "requireDirectory", "(", "dir", ")", ".", "file", "(", ")", ";", "FileSystemView", "view", "=", "new", "FileSystemView", "(", "store", ",", "file", ",", "basePathForStream", ")", ";", "JimfsSecureDirectoryStream", "stream", "=", "new", "JimfsSecureDirectoryStream", "(", "view", ",", "filter", ",", "state", "(", ")", ")", ";", "return", "store", ".", "supportsFeature", "(", "Feature", ".", "SECURE_DIRECTORY_STREAM", ")", "?", "stream", ":", "new", "DowngradedDirectoryStream", "(", "stream", ")", ";", "}" ]
Creates a new directory stream for the directory located by the given path. The given {@code basePathForStream} is that base path that the returned stream will use. This will be the same as {@code dir} except for streams created relative to another secure stream.
[ "Creates", "a", "new", "directory", "stream", "for", "the", "directory", "located", "by", "the", "given", "path", ".", "The", "given", "{" ]
train
https://github.com/google/jimfs/blob/3eadff747a3afa7b498030f420d2d04ce700534a/jimfs/src/main/java/com/google/common/jimfs/FileSystemView.java#L119-L131
DDTH/ddth-dao
ddth-dao-core/src/main/java/com/github/ddth/dao/jdbc/GenericMultiBoJdbcDao.java
GenericMultiBoJdbcDao.addDelegateDao
@SuppressWarnings("unchecked") public <T> GenericMultiBoJdbcDao addDelegateDao(String className, IGenericBoDao<T> dao) throws ClassNotFoundException { Class<T> clazz = (Class<T>) Class.forName(className); return addDelegateDao(clazz, dao); }
java
@SuppressWarnings("unchecked") public <T> GenericMultiBoJdbcDao addDelegateDao(String className, IGenericBoDao<T> dao) throws ClassNotFoundException { Class<T> clazz = (Class<T>) Class.forName(className); return addDelegateDao(clazz, dao); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "<", "T", ">", "GenericMultiBoJdbcDao", "addDelegateDao", "(", "String", "className", ",", "IGenericBoDao", "<", "T", ">", "dao", ")", "throws", "ClassNotFoundException", "{", "Class", "<", "T", ">", "clazz", "=", "(", "Class", "<", "T", ">", ")", "Class", ".", "forName", "(", "className", ")", ";", "return", "addDelegateDao", "(", "clazz", ",", "dao", ")", ";", "}" ]
Add a delegate dao to mapping list. @param className @param dao @return @throws ClassNotFoundException
[ "Add", "a", "delegate", "dao", "to", "mapping", "list", "." ]
train
https://github.com/DDTH/ddth-dao/blob/8d059ddf641a1629aa53851f9d1b41abf175a180/ddth-dao-core/src/main/java/com/github/ddth/dao/jdbc/GenericMultiBoJdbcDao.java#L88-L93
jMotif/GI
src/main/java/net/seninp/gi/sequitur/SAXSymbol.java
SAXSymbol.join
public static void join(SAXSymbol left, SAXSymbol right) { // System.out.println(" performing the join of " + getPayload(left) + " and " // + getPayload(right)); // check for an OLD digram existence - i.e. left must have a next symbol // if .n exists then we are joining TERMINAL symbols within the string, and must clean-up the // old digram if (left.n != null) { // System.out.println(" " + getPayload(left) // + " use to be in the digram table, cleaning up"); left.deleteDigram(); } // re-link left and right left.n = right; right.p = left; }
java
public static void join(SAXSymbol left, SAXSymbol right) { // System.out.println(" performing the join of " + getPayload(left) + " and " // + getPayload(right)); // check for an OLD digram existence - i.e. left must have a next symbol // if .n exists then we are joining TERMINAL symbols within the string, and must clean-up the // old digram if (left.n != null) { // System.out.println(" " + getPayload(left) // + " use to be in the digram table, cleaning up"); left.deleteDigram(); } // re-link left and right left.n = right; right.p = left; }
[ "public", "static", "void", "join", "(", "SAXSymbol", "left", ",", "SAXSymbol", "right", ")", "{", "// System.out.println(\" performing the join of \" + getPayload(left) + \" and \"\r", "// + getPayload(right));\r", "// check for an OLD digram existence - i.e. left must have a next symbol\r", "// if .n exists then we are joining TERMINAL symbols within the string, and must clean-up the\r", "// old digram\r", "if", "(", "left", ".", "n", "!=", "null", ")", "{", "// System.out.println(\" \" + getPayload(left)\r", "// + \" use to be in the digram table, cleaning up\");\r", "left", ".", "deleteDigram", "(", ")", ";", "}", "// re-link left and right\r", "left", ".", "n", "=", "right", ";", "right", ".", "p", "=", "left", ";", "}" ]
Links left and right symbols together, i.e. removes this symbol from the string, also removing any old digram from the hash table. @param left the left symbol. @param right the right symbol.
[ "Links", "left", "and", "right", "symbols", "together", "i", ".", "e", ".", "removes", "this", "symbol", "from", "the", "string", "also", "removing", "any", "old", "digram", "from", "the", "hash", "table", "." ]
train
https://github.com/jMotif/GI/blob/381212dd4f193246a6df82bd46f0d2bcd04a68d6/src/main/java/net/seninp/gi/sequitur/SAXSymbol.java#L66-L83
OpenLiberty/open-liberty
dev/com.ibm.ws.kernel.feature.cmdline/src/com/ibm/ws/kernel/feature/internal/generator/ManifestFileProcessor.java
ManifestFileProcessor.getCoreFeatureDir
public File getCoreFeatureDir() { File featureDir = null; File installDir = Utils.getInstallDir(); if (installDir != null) { featureDir = new File(installDir, FEATURE_DIR); } if (featureDir == null) { throw new RuntimeException("Feature Directory not found"); } return featureDir; }
java
public File getCoreFeatureDir() { File featureDir = null; File installDir = Utils.getInstallDir(); if (installDir != null) { featureDir = new File(installDir, FEATURE_DIR); } if (featureDir == null) { throw new RuntimeException("Feature Directory not found"); } return featureDir; }
[ "public", "File", "getCoreFeatureDir", "(", ")", "{", "File", "featureDir", "=", "null", ";", "File", "installDir", "=", "Utils", ".", "getInstallDir", "(", ")", ";", "if", "(", "installDir", "!=", "null", ")", "{", "featureDir", "=", "new", "File", "(", "installDir", ",", "FEATURE_DIR", ")", ";", "}", "if", "(", "featureDir", "==", "null", ")", "{", "throw", "new", "RuntimeException", "(", "\"Feature Directory not found\"", ")", ";", "}", "return", "featureDir", ";", "}" ]
Retrieves the Liberty core features directory. @return The Liberty core features directory
[ "Retrieves", "the", "Liberty", "core", "features", "directory", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.kernel.feature.cmdline/src/com/ibm/ws/kernel/feature/internal/generator/ManifestFileProcessor.java#L439-L452
aws/aws-sdk-java
aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/internal/crypto/ContentCryptoMaterial.java
ContentCryptoMaterial.create
static ContentCryptoMaterial create(SecretKey cek, byte[] iv, EncryptionMaterials kekMaterials, S3CryptoScheme scheme, CryptoConfiguration config, AWSKMS kms, AmazonWebServiceRequest req) { return doCreate(cek, iv, kekMaterials, scheme.getContentCryptoScheme(), scheme, config, kms, req); }
java
static ContentCryptoMaterial create(SecretKey cek, byte[] iv, EncryptionMaterials kekMaterials, S3CryptoScheme scheme, CryptoConfiguration config, AWSKMS kms, AmazonWebServiceRequest req) { return doCreate(cek, iv, kekMaterials, scheme.getContentCryptoScheme(), scheme, config, kms, req); }
[ "static", "ContentCryptoMaterial", "create", "(", "SecretKey", "cek", ",", "byte", "[", "]", "iv", ",", "EncryptionMaterials", "kekMaterials", ",", "S3CryptoScheme", "scheme", ",", "CryptoConfiguration", "config", ",", "AWSKMS", "kms", ",", "AmazonWebServiceRequest", "req", ")", "{", "return", "doCreate", "(", "cek", ",", "iv", ",", "kekMaterials", ",", "scheme", ".", "getContentCryptoScheme", "(", ")", ",", "scheme", ",", "config", ",", "kms", ",", "req", ")", ";", "}" ]
Returns a new instance of <code>ContentCryptoMaterial</code> for the input parameters using the specified s3 crypto scheme. Note network calls are involved if the CEK is to be protected by KMS. @param cek content encrypting key @param iv initialization vector @param kekMaterials kek encryption material used to secure the CEK; can be KMS enabled. @param scheme s3 crypto scheme to be used for the content crypto material by providing the content crypto scheme, key wrapping scheme and mechanism for secure randomness @param config crypto configuration @param kms reference to the KMS client @param req originating service request
[ "Returns", "a", "new", "instance", "of", "<code", ">", "ContentCryptoMaterial<", "/", "code", ">", "for", "the", "input", "parameters", "using", "the", "specified", "s3", "crypto", "scheme", ".", "Note", "network", "calls", "are", "involved", "if", "the", "CEK", "is", "to", "be", "protected", "by", "KMS", "." ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/internal/crypto/ContentCryptoMaterial.java#L768-L775
jenkinsci/jenkins
core/src/main/java/jenkins/model/ParameterizedJobMixIn.java
ParameterizedJobMixIn.scheduleBuild2
public static @CheckForNull Queue.Item scheduleBuild2(final Job<?,?> job, int quietPeriod, Action... actions) { if (!(job instanceof ParameterizedJob)) { return null; } return new ParameterizedJobMixIn() { @Override protected Job asJob() { return job; } }.scheduleBuild2(quietPeriod == -1 ? ((ParameterizedJob) job).getQuietPeriod() : quietPeriod, Arrays.asList(actions)); }
java
public static @CheckForNull Queue.Item scheduleBuild2(final Job<?,?> job, int quietPeriod, Action... actions) { if (!(job instanceof ParameterizedJob)) { return null; } return new ParameterizedJobMixIn() { @Override protected Job asJob() { return job; } }.scheduleBuild2(quietPeriod == -1 ? ((ParameterizedJob) job).getQuietPeriod() : quietPeriod, Arrays.asList(actions)); }
[ "public", "static", "@", "CheckForNull", "Queue", ".", "Item", "scheduleBuild2", "(", "final", "Job", "<", "?", ",", "?", ">", "job", ",", "int", "quietPeriod", ",", "Action", "...", "actions", ")", "{", "if", "(", "!", "(", "job", "instanceof", "ParameterizedJob", ")", ")", "{", "return", "null", ";", "}", "return", "new", "ParameterizedJobMixIn", "(", ")", "{", "@", "Override", "protected", "Job", "asJob", "(", ")", "{", "return", "job", ";", "}", "}", ".", "scheduleBuild2", "(", "quietPeriod", "==", "-", "1", "?", "(", "(", "ParameterizedJob", ")", "job", ")", ".", "getQuietPeriod", "(", ")", ":", "quietPeriod", ",", "Arrays", ".", "asList", "(", "actions", ")", ")", ";", "}" ]
Convenience method to schedule a build. Useful for {@link Trigger} implementations, for example. If you need to wait for the build to start (or finish), use {@link Queue.Item#getFuture}. @param job a job which might be schedulable @param quietPeriod seconds to wait before starting; use {@code -1} to use the job’s default settings @param actions various actions to associate with the scheduling, such as {@link ParametersAction} or {@link CauseAction} @return a newly created, or reused, queue item if the job could be scheduled; null if it was refused for some reason (e.g., some {@link Queue.QueueDecisionHandler} rejected it), or if {@code job} is not a {@link ParameterizedJob} or it is not {@link Job#isBuildable}) @since 1.621
[ "Convenience", "method", "to", "schedule", "a", "build", ".", "Useful", "for", "{" ]
train
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/jenkins/model/ParameterizedJobMixIn.java#L137-L146
auth0/auth0-java
src/main/java/com/auth0/client/auth/AuthorizeUrlBuilder.java
AuthorizeUrlBuilder.withParameter
public AuthorizeUrlBuilder withParameter(String name, String value) { assertNotNull(name, "name"); assertNotNull(value, "value"); parameters.put(name, value); return this; }
java
public AuthorizeUrlBuilder withParameter(String name, String value) { assertNotNull(name, "name"); assertNotNull(value, "value"); parameters.put(name, value); return this; }
[ "public", "AuthorizeUrlBuilder", "withParameter", "(", "String", "name", ",", "String", "value", ")", "{", "assertNotNull", "(", "name", ",", "\"name\"", ")", ";", "assertNotNull", "(", "value", ",", "\"value\"", ")", ";", "parameters", ".", "put", "(", "name", ",", "value", ")", ";", "return", "this", ";", "}" ]
Sets an additional parameter. @param name name of the parameter @param value value of the parameter to set @return the builder instance
[ "Sets", "an", "additional", "parameter", "." ]
train
https://github.com/auth0/auth0-java/blob/b7bc099ee9c6cde5a87c4ecfebc6d811aeb1027c/src/main/java/com/auth0/client/auth/AuthorizeUrlBuilder.java#L111-L116
spotbugs/spotbugs
eclipsePlugin/src/de/tobject/findbugs/actions/FindBugsAction.java
FindBugsAction.work
protected void work(IWorkbenchPart part, final IResource resource, final List<WorkItem> resources) { FindBugsJob runFindBugs = new StartedFromViewJob("Finding bugs in " + resource.getName() + "...", resource, resources, part); runFindBugs.scheduleInteractive(); }
java
protected void work(IWorkbenchPart part, final IResource resource, final List<WorkItem> resources) { FindBugsJob runFindBugs = new StartedFromViewJob("Finding bugs in " + resource.getName() + "...", resource, resources, part); runFindBugs.scheduleInteractive(); }
[ "protected", "void", "work", "(", "IWorkbenchPart", "part", ",", "final", "IResource", "resource", ",", "final", "List", "<", "WorkItem", ">", "resources", ")", "{", "FindBugsJob", "runFindBugs", "=", "new", "StartedFromViewJob", "(", "\"Finding bugs in \"", "+", "resource", ".", "getName", "(", ")", "+", "\"...\"", ",", "resource", ",", "resources", ",", "part", ")", ";", "runFindBugs", ".", "scheduleInteractive", "(", ")", ";", "}" ]
Run a FindBugs analysis on the given resource, displaying a progress monitor. @param part @param resources The resource to run the analysis on.
[ "Run", "a", "FindBugs", "analysis", "on", "the", "given", "resource", "displaying", "a", "progress", "monitor", "." ]
train
https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/eclipsePlugin/src/de/tobject/findbugs/actions/FindBugsAction.java#L167-L170
Azure/azure-sdk-for-java
sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/ElasticPoolActivitiesInner.java
ElasticPoolActivitiesInner.listByElasticPoolAsync
public Observable<List<ElasticPoolActivityInner>> listByElasticPoolAsync(String resourceGroupName, String serverName, String elasticPoolName) { return listByElasticPoolWithServiceResponseAsync(resourceGroupName, serverName, elasticPoolName).map(new Func1<ServiceResponse<List<ElasticPoolActivityInner>>, List<ElasticPoolActivityInner>>() { @Override public List<ElasticPoolActivityInner> call(ServiceResponse<List<ElasticPoolActivityInner>> response) { return response.body(); } }); }
java
public Observable<List<ElasticPoolActivityInner>> listByElasticPoolAsync(String resourceGroupName, String serverName, String elasticPoolName) { return listByElasticPoolWithServiceResponseAsync(resourceGroupName, serverName, elasticPoolName).map(new Func1<ServiceResponse<List<ElasticPoolActivityInner>>, List<ElasticPoolActivityInner>>() { @Override public List<ElasticPoolActivityInner> call(ServiceResponse<List<ElasticPoolActivityInner>> response) { return response.body(); } }); }
[ "public", "Observable", "<", "List", "<", "ElasticPoolActivityInner", ">", ">", "listByElasticPoolAsync", "(", "String", "resourceGroupName", ",", "String", "serverName", ",", "String", "elasticPoolName", ")", "{", "return", "listByElasticPoolWithServiceResponseAsync", "(", "resourceGroupName", ",", "serverName", ",", "elasticPoolName", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "List", "<", "ElasticPoolActivityInner", ">", ">", ",", "List", "<", "ElasticPoolActivityInner", ">", ">", "(", ")", "{", "@", "Override", "public", "List", "<", "ElasticPoolActivityInner", ">", "call", "(", "ServiceResponse", "<", "List", "<", "ElasticPoolActivityInner", ">", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Returns elastic pool activities. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server. @param elasticPoolName The name of the elastic pool for which to get the current activity. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the List&lt;ElasticPoolActivityInner&gt; object
[ "Returns", "elastic", "pool", "activities", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/ElasticPoolActivitiesInner.java#L99-L106
loldevs/riotapi
rest/src/main/java/net/boreeas/riotapi/rest/ThrottledApiHandler.java
ThrottledApiHandler.getLeagueEntries
public Future<List<LeagueItem>> getLeagueEntries(String teamId) { return new ApiFuture<>(() -> handler.getLeagueEntries(teamId)); }
java
public Future<List<LeagueItem>> getLeagueEntries(String teamId) { return new ApiFuture<>(() -> handler.getLeagueEntries(teamId)); }
[ "public", "Future", "<", "List", "<", "LeagueItem", ">", ">", "getLeagueEntries", "(", "String", "teamId", ")", "{", "return", "new", "ApiFuture", "<>", "(", "(", ")", "->", "handler", ".", "getLeagueEntries", "(", "teamId", ")", ")", ";", "}" ]
Get a listing of all league entries in the team's leagues @param teamId The id of the team @return A list of league entries @see <a href=https://developer.riotgames.com/api/methods#!/593/1861>Official API documentation</a>
[ "Get", "a", "listing", "of", "all", "league", "entries", "in", "the", "team", "s", "leagues" ]
train
https://github.com/loldevs/riotapi/blob/0b8aac407aa5289845f249024f9732332855544f/rest/src/main/java/net/boreeas/riotapi/rest/ThrottledApiHandler.java#L285-L287
gallandarakhneorg/afc
core/text/src/main/java/org/arakhne/afc/text/TextUtil.java
TextUtil.splitBrackets
@Pure @Inline(value = "textUtil.split('{', '}', $1)", imported = {TextUtil.class}) public static String[] splitBrackets(String str) { return split('{', '}', str); }
java
@Pure @Inline(value = "textUtil.split('{', '}', $1)", imported = {TextUtil.class}) public static String[] splitBrackets(String str) { return split('{', '}', str); }
[ "@", "Pure", "@", "Inline", "(", "value", "=", "\"textUtil.split('{', '}', $1)\"", ",", "imported", "=", "{", "TextUtil", ".", "class", "}", ")", "public", "static", "String", "[", "]", "splitBrackets", "(", "String", "str", ")", "{", "return", "split", "(", "'", "'", ",", "'", "'", ",", "str", ")", ";", "}" ]
Split the given string according to brackets. The brackets are used to delimit the groups of characters. <p>Examples: <ul> <li><code>splitBrackets("{a}{b}{cd}")</code> returns the array <code>["a","b","cd"]</code></li> <li><code>splitBrackets("abcd")</code> returns the array <code>["abcd"]</code></li> <li><code>splitBrackets("a{bcd")</code> returns the array <code>["a","bcd"]</code></li> </ul> @param str is the strig with brackets. @return the groups of strings
[ "Split", "the", "given", "string", "according", "to", "brackets", ".", "The", "brackets", "are", "used", "to", "delimit", "the", "groups", "of", "characters", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/text/src/main/java/org/arakhne/afc/text/TextUtil.java#L613-L617
VoltDB/voltdb
src/hsqldb19b3/org/hsqldb_voltpatches/TransactionManager.java
TransactionManager.mergeRolledBackTransaction
void mergeRolledBackTransaction(Object[] list, int start, int limit) { for (int i = start; i < limit; i++) { RowAction rowact = (RowAction) list[i]; if (rowact == null || rowact.type == RowActionBase.ACTION_NONE || rowact.type == RowActionBase.ACTION_DELETE_FINAL) { continue; } Row row = rowact.memoryRow; if (row == null) { PersistentStore store = rowact.session.sessionData.getRowStore(rowact.table); row = (Row) store.get(rowact.getPos(), false); } if (row == null) { continue; } synchronized (row) { rowact.mergeRollback(row); } } // } catch (Throwable t) { // System.out.println("throw in merge"); // t.printStackTrace(); // } }
java
void mergeRolledBackTransaction(Object[] list, int start, int limit) { for (int i = start; i < limit; i++) { RowAction rowact = (RowAction) list[i]; if (rowact == null || rowact.type == RowActionBase.ACTION_NONE || rowact.type == RowActionBase.ACTION_DELETE_FINAL) { continue; } Row row = rowact.memoryRow; if (row == null) { PersistentStore store = rowact.session.sessionData.getRowStore(rowact.table); row = (Row) store.get(rowact.getPos(), false); } if (row == null) { continue; } synchronized (row) { rowact.mergeRollback(row); } } // } catch (Throwable t) { // System.out.println("throw in merge"); // t.printStackTrace(); // } }
[ "void", "mergeRolledBackTransaction", "(", "Object", "[", "]", "list", ",", "int", "start", ",", "int", "limit", ")", "{", "for", "(", "int", "i", "=", "start", ";", "i", "<", "limit", ";", "i", "++", ")", "{", "RowAction", "rowact", "=", "(", "RowAction", ")", "list", "[", "i", "]", ";", "if", "(", "rowact", "==", "null", "||", "rowact", ".", "type", "==", "RowActionBase", ".", "ACTION_NONE", "||", "rowact", ".", "type", "==", "RowActionBase", ".", "ACTION_DELETE_FINAL", ")", "{", "continue", ";", "}", "Row", "row", "=", "rowact", ".", "memoryRow", ";", "if", "(", "row", "==", "null", ")", "{", "PersistentStore", "store", "=", "rowact", ".", "session", ".", "sessionData", ".", "getRowStore", "(", "rowact", ".", "table", ")", ";", "row", "=", "(", "Row", ")", "store", ".", "get", "(", "rowact", ".", "getPos", "(", ")", ",", "false", ")", ";", "}", "if", "(", "row", "==", "null", ")", "{", "continue", ";", "}", "synchronized", "(", "row", ")", "{", "rowact", ".", "mergeRollback", "(", "row", ")", ";", "}", "}", "// } catch (Throwable t) {", "// System.out.println(\"throw in merge\");", "// t.printStackTrace();", "// }", "}" ]
merge a given list of transaction rollback action with given timestamp
[ "merge", "a", "given", "list", "of", "transaction", "rollback", "action", "with", "given", "timestamp" ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/TransactionManager.java#L625-L657
spring-projects/spring-android
spring-android-rest-template/src/main/java/org/springframework/http/HttpHeaders.java
HttpHeaders.getFirstDate
public long getFirstDate(String headerName) { String headerValue = getFirst(headerName); if (headerValue == null) { return -1; } for (String dateFormat : DATE_FORMATS) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat, Locale.US); simpleDateFormat.setTimeZone(GMT); try { return simpleDateFormat.parse(headerValue).getTime(); } catch (ParseException e) { // ignore } } throw new IllegalArgumentException("Cannot parse date value \"" + headerValue + "\" for \"" + headerName + "\" header"); }
java
public long getFirstDate(String headerName) { String headerValue = getFirst(headerName); if (headerValue == null) { return -1; } for (String dateFormat : DATE_FORMATS) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat, Locale.US); simpleDateFormat.setTimeZone(GMT); try { return simpleDateFormat.parse(headerValue).getTime(); } catch (ParseException e) { // ignore } } throw new IllegalArgumentException("Cannot parse date value \"" + headerValue + "\" for \"" + headerName + "\" header"); }
[ "public", "long", "getFirstDate", "(", "String", "headerName", ")", "{", "String", "headerValue", "=", "getFirst", "(", "headerName", ")", ";", "if", "(", "headerValue", "==", "null", ")", "{", "return", "-", "1", ";", "}", "for", "(", "String", "dateFormat", ":", "DATE_FORMATS", ")", "{", "SimpleDateFormat", "simpleDateFormat", "=", "new", "SimpleDateFormat", "(", "dateFormat", ",", "Locale", ".", "US", ")", ";", "simpleDateFormat", ".", "setTimeZone", "(", "GMT", ")", ";", "try", "{", "return", "simpleDateFormat", ".", "parse", "(", "headerValue", ")", ".", "getTime", "(", ")", ";", "}", "catch", "(", "ParseException", "e", ")", "{", "// ignore", "}", "}", "throw", "new", "IllegalArgumentException", "(", "\"Cannot parse date value \\\"\"", "+", "headerValue", "+", "\"\\\" for \\\"\"", "+", "headerName", "+", "\"\\\" header\"", ")", ";", "}" ]
Parse the first header value for the given header name as a date, return -1 if there is no value, or raise {@link IllegalArgumentException} if the value cannot be parsed as a date.
[ "Parse", "the", "first", "header", "value", "for", "the", "given", "header", "name", "as", "a", "date", "return", "-", "1", "if", "there", "is", "no", "value", "or", "raise", "{" ]
train
https://github.com/spring-projects/spring-android/blob/941296e152d49a40e0745a3e81628a974f72b7e4/spring-android-rest-template/src/main/java/org/springframework/http/HttpHeaders.java#L886-L903
stevespringett/Alpine
alpine/src/main/java/alpine/crypto/DataEncryption.java
DataEncryption.decryptAsString
public static String decryptAsString(final SecretKey secretKey, final String encryptedText) throws Exception { return new String(decryptAsBytes(secretKey, Base64.getDecoder().decode(encryptedText))); }
java
public static String decryptAsString(final SecretKey secretKey, final String encryptedText) throws Exception { return new String(decryptAsBytes(secretKey, Base64.getDecoder().decode(encryptedText))); }
[ "public", "static", "String", "decryptAsString", "(", "final", "SecretKey", "secretKey", ",", "final", "String", "encryptedText", ")", "throws", "Exception", "{", "return", "new", "String", "(", "decryptAsBytes", "(", "secretKey", ",", "Base64", ".", "getDecoder", "(", ")", ".", "decode", "(", "encryptedText", ")", ")", ")", ";", "}" ]
Decrypts the specified string using AES-256. The encryptedText is expected to be the Base64 encoded representation of the encrypted bytes generated from {@link #encryptAsString(String)}. @param secretKey the secret key to decrypt with @param encryptedText the text to decrypt @return the decrypted string @throws Exception a number of exceptions may be thrown @since 1.3.0
[ "Decrypts", "the", "specified", "string", "using", "AES", "-", "256", ".", "The", "encryptedText", "is", "expected", "to", "be", "the", "Base64", "encoded", "representation", "of", "the", "encrypted", "bytes", "generated", "from", "{" ]
train
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/crypto/DataEncryption.java#L161-L163
Appendium/objectlabkit
utils/src/main/java/net/objectlab/kit/util/ObjectUtil.java
ObjectUtil.equalsValue
public static boolean equalsValue(final Object o1, final Object o2) { if (o1 == null) { return o2 == null; } return o1.equals(o2); }
java
public static boolean equalsValue(final Object o1, final Object o2) { if (o1 == null) { return o2 == null; } return o1.equals(o2); }
[ "public", "static", "boolean", "equalsValue", "(", "final", "Object", "o1", ",", "final", "Object", "o2", ")", "{", "if", "(", "o1", "==", "null", ")", "{", "return", "o2", "==", "null", ";", "}", "return", "o1", ".", "equals", "(", "o2", ")", ";", "}" ]
Return true if o1 equals (according to {@link Object#equals(Object)}) o2. Also returns true if o1 is null and o2 is null! Is safe on either o1 or o2 being null.
[ "Return", "true", "if", "o1", "equals", "(", "according", "to", "{" ]
train
https://github.com/Appendium/objectlabkit/blob/cd649bce7a32e4e926520e62cb765f3b1d451594/utils/src/main/java/net/objectlab/kit/util/ObjectUtil.java#L69-L74
Azure/azure-sdk-for-java
keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java
KeyVaultClientBaseImpl.importCertificate
public CertificateBundle importCertificate(String vaultBaseUrl, String certificateName, String base64EncodedCertificate, String password, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map<String, String> tags) { return importCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, base64EncodedCertificate, password, certificatePolicy, certificateAttributes, tags).toBlocking().single().body(); }
java
public CertificateBundle importCertificate(String vaultBaseUrl, String certificateName, String base64EncodedCertificate, String password, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map<String, String> tags) { return importCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, base64EncodedCertificate, password, certificatePolicy, certificateAttributes, tags).toBlocking().single().body(); }
[ "public", "CertificateBundle", "importCertificate", "(", "String", "vaultBaseUrl", ",", "String", "certificateName", ",", "String", "base64EncodedCertificate", ",", "String", "password", ",", "CertificatePolicy", "certificatePolicy", ",", "CertificateAttributes", "certificateAttributes", ",", "Map", "<", "String", ",", "String", ">", "tags", ")", "{", "return", "importCertificateWithServiceResponseAsync", "(", "vaultBaseUrl", ",", "certificateName", ",", "base64EncodedCertificate", ",", "password", ",", "certificatePolicy", ",", "certificateAttributes", ",", "tags", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Imports a certificate into a specified key vault. Imports an existing valid certificate, containing a private key, into Azure Key Vault. The certificate to be imported can be in either PFX or PEM format. If the certificate is in PEM format the PEM file must contain the key as well as x509 certificates. This operation requires the certificates/import permission. @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. @param certificateName The name of the certificate. @param base64EncodedCertificate Base64 encoded representation of the certificate object to import. This certificate needs to contain the private key. @param password If the private key in base64EncodedCertificate is encrypted, the password used for encryption. @param certificatePolicy The management policy for the certificate. @param certificateAttributes The attributes of the certificate (optional). @param tags Application specific metadata in the form of key-value pairs. @throws IllegalArgumentException thrown if parameters fail the validation @throws KeyVaultErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the CertificateBundle object if successful.
[ "Imports", "a", "certificate", "into", "a", "specified", "key", "vault", ".", "Imports", "an", "existing", "valid", "certificate", "containing", "a", "private", "key", "into", "Azure", "Key", "Vault", ".", "The", "certificate", "to", "be", "imported", "can", "be", "in", "either", "PFX", "or", "PEM", "format", ".", "If", "the", "certificate", "is", "in", "PEM", "format", "the", "PEM", "file", "must", "contain", "the", "key", "as", "well", "as", "x509", "certificates", ".", "This", "operation", "requires", "the", "certificates", "/", "import", "permission", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java#L6786-L6788
UrielCh/ovh-java-sdk
ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java
ApiOvhTelephony.billingAccount_portability_id_document_documentId_GET
public OvhPortabilityDocument billingAccount_portability_id_document_documentId_GET(String billingAccount, Long id, Long documentId) throws IOException { String qPath = "/telephony/{billingAccount}/portability/{id}/document/{documentId}"; StringBuilder sb = path(qPath, billingAccount, id, documentId); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhPortabilityDocument.class); }
java
public OvhPortabilityDocument billingAccount_portability_id_document_documentId_GET(String billingAccount, Long id, Long documentId) throws IOException { String qPath = "/telephony/{billingAccount}/portability/{id}/document/{documentId}"; StringBuilder sb = path(qPath, billingAccount, id, documentId); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhPortabilityDocument.class); }
[ "public", "OvhPortabilityDocument", "billingAccount_portability_id_document_documentId_GET", "(", "String", "billingAccount", ",", "Long", "id", ",", "Long", "documentId", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/telephony/{billingAccount}/portability/{id}/document/{documentId}\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "billingAccount", ",", "id", ",", "documentId", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"GET\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhPortabilityDocument", ".", "class", ")", ";", "}" ]
Get this object properties REST: GET /telephony/{billingAccount}/portability/{id}/document/{documentId} @param billingAccount [required] The name of your billingAccount @param id [required] The ID of the portability @param documentId [required] Identifier of the document
[ "Get", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java#L271-L276
alibaba/canal
client-adapter/elasticsearch/src/main/java/com/alibaba/otter/canal/client/adapter/es/service/ESSyncService.java
ESSyncService.mainTableInsert
private void mainTableInsert(ESSyncConfig config, Dml dml, Map<String, Object> data) { ESMapping mapping = config.getEsMapping(); String sql = mapping.getSql(); String condition = ESSyncUtil.pkConditionSql(mapping, data); sql = ESSyncUtil.appendCondition(sql, condition); DataSource ds = DatasourceConfig.DATA_SOURCES.get(config.getDataSourceKey()); if (logger.isTraceEnabled()) { logger.trace("Main table insert to es index by query sql, destination:{}, table: {}, index: {}, sql: {}", config.getDestination(), dml.getTable(), mapping.get_index(), sql.replace("\n", " ")); } Util.sqlRS(ds, sql, rs -> { try { while (rs.next()) { Map<String, Object> esFieldData = new LinkedHashMap<>(); Object idVal = esTemplate.getESDataFromRS(mapping, rs, esFieldData); if (logger.isTraceEnabled()) { logger.trace( "Main table insert to es index by query sql, destination:{}, table: {}, index: {}, id: {}", config.getDestination(), dml.getTable(), mapping.get_index(), idVal); } esTemplate.insert(mapping, idVal, esFieldData); } } catch (Exception e) { throw new RuntimeException(e); } return 0; }); }
java
private void mainTableInsert(ESSyncConfig config, Dml dml, Map<String, Object> data) { ESMapping mapping = config.getEsMapping(); String sql = mapping.getSql(); String condition = ESSyncUtil.pkConditionSql(mapping, data); sql = ESSyncUtil.appendCondition(sql, condition); DataSource ds = DatasourceConfig.DATA_SOURCES.get(config.getDataSourceKey()); if (logger.isTraceEnabled()) { logger.trace("Main table insert to es index by query sql, destination:{}, table: {}, index: {}, sql: {}", config.getDestination(), dml.getTable(), mapping.get_index(), sql.replace("\n", " ")); } Util.sqlRS(ds, sql, rs -> { try { while (rs.next()) { Map<String, Object> esFieldData = new LinkedHashMap<>(); Object idVal = esTemplate.getESDataFromRS(mapping, rs, esFieldData); if (logger.isTraceEnabled()) { logger.trace( "Main table insert to es index by query sql, destination:{}, table: {}, index: {}, id: {}", config.getDestination(), dml.getTable(), mapping.get_index(), idVal); } esTemplate.insert(mapping, idVal, esFieldData); } } catch (Exception e) { throw new RuntimeException(e); } return 0; }); }
[ "private", "void", "mainTableInsert", "(", "ESSyncConfig", "config", ",", "Dml", "dml", ",", "Map", "<", "String", ",", "Object", ">", "data", ")", "{", "ESMapping", "mapping", "=", "config", ".", "getEsMapping", "(", ")", ";", "String", "sql", "=", "mapping", ".", "getSql", "(", ")", ";", "String", "condition", "=", "ESSyncUtil", ".", "pkConditionSql", "(", "mapping", ",", "data", ")", ";", "sql", "=", "ESSyncUtil", ".", "appendCondition", "(", "sql", ",", "condition", ")", ";", "DataSource", "ds", "=", "DatasourceConfig", ".", "DATA_SOURCES", ".", "get", "(", "config", ".", "getDataSourceKey", "(", ")", ")", ";", "if", "(", "logger", ".", "isTraceEnabled", "(", ")", ")", "{", "logger", ".", "trace", "(", "\"Main table insert to es index by query sql, destination:{}, table: {}, index: {}, sql: {}\"", ",", "config", ".", "getDestination", "(", ")", ",", "dml", ".", "getTable", "(", ")", ",", "mapping", ".", "get_index", "(", ")", ",", "sql", ".", "replace", "(", "\"\\n\"", ",", "\" \"", ")", ")", ";", "}", "Util", ".", "sqlRS", "(", "ds", ",", "sql", ",", "rs", "->", "{", "try", "{", "while", "(", "rs", ".", "next", "(", ")", ")", "{", "Map", "<", "String", ",", "Object", ">", "esFieldData", "=", "new", "LinkedHashMap", "<>", "(", ")", ";", "Object", "idVal", "=", "esTemplate", ".", "getESDataFromRS", "(", "mapping", ",", "rs", ",", "esFieldData", ")", ";", "if", "(", "logger", ".", "isTraceEnabled", "(", ")", ")", "{", "logger", ".", "trace", "(", "\"Main table insert to es index by query sql, destination:{}, table: {}, index: {}, id: {}\"", ",", "config", ".", "getDestination", "(", ")", ",", "dml", ".", "getTable", "(", ")", ",", "mapping", ".", "get_index", "(", ")", ",", "idVal", ")", ";", "}", "esTemplate", ".", "insert", "(", "mapping", ",", "idVal", ",", "esFieldData", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "return", "0", ";", "}", ")", ";", "}" ]
主表(单表)复杂字段insert @param config es配置 @param dml dml信息 @param data 单行dml数据
[ "主表", "(", "单表", ")", "复杂字段insert" ]
train
https://github.com/alibaba/canal/blob/8f088cddc0755f4350c5aaae95c6e4002d90a40f/client-adapter/elasticsearch/src/main/java/com/alibaba/otter/canal/client/adapter/es/service/ESSyncService.java#L455-L489
facebookarchive/hadoop-20
src/hdfs/org/apache/hadoop/hdfs/server/namenode/CorruptReplicasMap.java
CorruptReplicasMap.isReplicaCorrupt
boolean isReplicaCorrupt(Block blk, DatanodeDescriptor node) { Collection<DatanodeDescriptor> nodes = getNodes(blk); return ((nodes != null) && (nodes.contains(node))); }
java
boolean isReplicaCorrupt(Block blk, DatanodeDescriptor node) { Collection<DatanodeDescriptor> nodes = getNodes(blk); return ((nodes != null) && (nodes.contains(node))); }
[ "boolean", "isReplicaCorrupt", "(", "Block", "blk", ",", "DatanodeDescriptor", "node", ")", "{", "Collection", "<", "DatanodeDescriptor", ">", "nodes", "=", "getNodes", "(", "blk", ")", ";", "return", "(", "(", "nodes", "!=", "null", ")", "&&", "(", "nodes", ".", "contains", "(", "node", ")", ")", ")", ";", "}" ]
Check if replica belonging to Datanode is corrupt @param blk Block to check @param node DatanodeDescriptor which holds the replica @return true if replica is corrupt, false if does not exists in this map
[ "Check", "if", "replica", "belonging", "to", "Datanode", "is", "corrupt" ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/server/namenode/CorruptReplicasMap.java#L121-L124
zeroturnaround/zt-zip
src/main/java/org/zeroturnaround/zip/ZipUtil.java
ZipUtil.unpackEntry
public static boolean unpackEntry(ZipFile zf, String name, File file) { try { return doUnpackEntry(zf, name, file); } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } }
java
public static boolean unpackEntry(ZipFile zf, String name, File file) { try { return doUnpackEntry(zf, name, file); } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } }
[ "public", "static", "boolean", "unpackEntry", "(", "ZipFile", "zf", ",", "String", "name", ",", "File", "file", ")", "{", "try", "{", "return", "doUnpackEntry", "(", "zf", ",", "name", ",", "file", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "ZipExceptionUtil", ".", "rethrow", "(", "e", ")", ";", "}", "}" ]
Unpacks a single file from a ZIP archive to a file. @param zf ZIP file. @param name entry name. @param file target file to be created or overwritten. @return <code>true</code> if the entry was found and unpacked, <code>false</code> if the entry was not found.
[ "Unpacks", "a", "single", "file", "from", "a", "ZIP", "archive", "to", "a", "file", "." ]
train
https://github.com/zeroturnaround/zt-zip/blob/abb4dc43583e4d19339c0c021035019798970a13/src/main/java/org/zeroturnaround/zip/ZipUtil.java#L368-L375
hellosign/hellosign-java-sdk
src/main/java/com/hellosign/sdk/resource/Event.java
Event.isValid
public boolean isValid(String apiKey) throws HelloSignException { if (apiKey == null || apiKey == "") { return false; } try { Mac sha256HMAC = Mac.getInstance(HASH_ALGORITHM); SecretKeySpec secretKey = new SecretKeySpec(apiKey.getBytes(), HASH_ALGORITHM); sha256HMAC.init(secretKey); String data = String.valueOf(getLong(EVENT_TIME)) + getType(); String computedHash = bytesToHex(sha256HMAC.doFinal(data.getBytes())); String providedHash = getString(EVENT_HASH); return computedHash.equalsIgnoreCase(providedHash); } catch (InvalidKeyException e) { throw new HelloSignException("Invalid API Key (" + e.getMessage() + "): " + apiKey); } catch (IllegalArgumentException e) { throw new HelloSignException("Invalid API Key (" + e.getMessage() + "): " + apiKey); } catch (NoSuchAlgorithmException e) { throw new HelloSignException("Unable to process API key", e); } }
java
public boolean isValid(String apiKey) throws HelloSignException { if (apiKey == null || apiKey == "") { return false; } try { Mac sha256HMAC = Mac.getInstance(HASH_ALGORITHM); SecretKeySpec secretKey = new SecretKeySpec(apiKey.getBytes(), HASH_ALGORITHM); sha256HMAC.init(secretKey); String data = String.valueOf(getLong(EVENT_TIME)) + getType(); String computedHash = bytesToHex(sha256HMAC.doFinal(data.getBytes())); String providedHash = getString(EVENT_HASH); return computedHash.equalsIgnoreCase(providedHash); } catch (InvalidKeyException e) { throw new HelloSignException("Invalid API Key (" + e.getMessage() + "): " + apiKey); } catch (IllegalArgumentException e) { throw new HelloSignException("Invalid API Key (" + e.getMessage() + "): " + apiKey); } catch (NoSuchAlgorithmException e) { throw new HelloSignException("Unable to process API key", e); } }
[ "public", "boolean", "isValid", "(", "String", "apiKey", ")", "throws", "HelloSignException", "{", "if", "(", "apiKey", "==", "null", "||", "apiKey", "==", "\"\"", ")", "{", "return", "false", ";", "}", "try", "{", "Mac", "sha256HMAC", "=", "Mac", ".", "getInstance", "(", "HASH_ALGORITHM", ")", ";", "SecretKeySpec", "secretKey", "=", "new", "SecretKeySpec", "(", "apiKey", ".", "getBytes", "(", ")", ",", "HASH_ALGORITHM", ")", ";", "sha256HMAC", ".", "init", "(", "secretKey", ")", ";", "String", "data", "=", "String", ".", "valueOf", "(", "getLong", "(", "EVENT_TIME", ")", ")", "+", "getType", "(", ")", ";", "String", "computedHash", "=", "bytesToHex", "(", "sha256HMAC", ".", "doFinal", "(", "data", ".", "getBytes", "(", ")", ")", ")", ";", "String", "providedHash", "=", "getString", "(", "EVENT_HASH", ")", ";", "return", "computedHash", ".", "equalsIgnoreCase", "(", "providedHash", ")", ";", "}", "catch", "(", "InvalidKeyException", "e", ")", "{", "throw", "new", "HelloSignException", "(", "\"Invalid API Key (\"", "+", "e", ".", "getMessage", "(", ")", "+", "\"): \"", "+", "apiKey", ")", ";", "}", "catch", "(", "IllegalArgumentException", "e", ")", "{", "throw", "new", "HelloSignException", "(", "\"Invalid API Key (\"", "+", "e", ".", "getMessage", "(", ")", "+", "\"): \"", "+", "apiKey", ")", ";", "}", "catch", "(", "NoSuchAlgorithmException", "e", ")", "{", "throw", "new", "HelloSignException", "(", "\"Unable to process API key\"", ",", "e", ")", ";", "}", "}" ]
Returns true if the event hash matches the computed hash using the provided API key. @param apiKey String api key. @return true if the hashes match, false otherwise @throws HelloSignException thrown if there is a problem parsing the API key.
[ "Returns", "true", "if", "the", "event", "hash", "matches", "the", "computed", "hash", "using", "the", "provided", "API", "key", "." ]
train
https://github.com/hellosign/hellosign-java-sdk/blob/08fa7aeb3b0c68ddb6c7ea797d114d55d36d36b1/src/main/java/com/hellosign/sdk/resource/Event.java#L317-L336
infinispan/infinispan
extended-statistics/src/main/java/org/infinispan/stats/CacheStatisticManager.java
CacheStatisticManager.markAsWriteTransaction
public final void markAsWriteTransaction(GlobalTransaction globalTransaction, boolean local) { TransactionStatistics txs = getTransactionStatistic(globalTransaction, local); if (txs == null) { log.markUnexistingTransactionAsWriteTransaction(globalTransaction == null ? "null" : globalTransaction.globalId()); return; } txs.markAsUpdateTransaction(); }
java
public final void markAsWriteTransaction(GlobalTransaction globalTransaction, boolean local) { TransactionStatistics txs = getTransactionStatistic(globalTransaction, local); if (txs == null) { log.markUnexistingTransactionAsWriteTransaction(globalTransaction == null ? "null" : globalTransaction.globalId()); return; } txs.markAsUpdateTransaction(); }
[ "public", "final", "void", "markAsWriteTransaction", "(", "GlobalTransaction", "globalTransaction", ",", "boolean", "local", ")", "{", "TransactionStatistics", "txs", "=", "getTransactionStatistic", "(", "globalTransaction", ",", "local", ")", ";", "if", "(", "txs", "==", "null", ")", "{", "log", ".", "markUnexistingTransactionAsWriteTransaction", "(", "globalTransaction", "==", "null", "?", "\"null\"", ":", "globalTransaction", ".", "globalId", "(", ")", ")", ";", "return", ";", "}", "txs", ".", "markAsUpdateTransaction", "(", ")", ";", "}" ]
Marks the transaction as a write transaction (instead of a read only transaction) @param local {@code true} if it is a local transaction.
[ "Marks", "the", "transaction", "as", "a", "write", "transaction", "(", "instead", "of", "a", "read", "only", "transaction", ")" ]
train
https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/extended-statistics/src/main/java/org/infinispan/stats/CacheStatisticManager.java#L156-L163
lightblueseas/swing-components
src/main/java/de/alpharogroup/swing/tree/JTreeExtensions.java
JTreeExtensions.expandAll
public static void expandAll(JTree tree, TreePath path, boolean expand) { TreeNode node = (TreeNode)path.getLastPathComponent(); if (node.getChildCount() >= 0) { Enumeration<?> enumeration = node.children(); while (enumeration.hasMoreElements()) { TreeNode n = (TreeNode)enumeration.nextElement(); TreePath p = path.pathByAddingChild(n); expandAll(tree, p, expand); } } if (expand) { tree.expandPath(path); } else { tree.collapsePath(path); } }
java
public static void expandAll(JTree tree, TreePath path, boolean expand) { TreeNode node = (TreeNode)path.getLastPathComponent(); if (node.getChildCount() >= 0) { Enumeration<?> enumeration = node.children(); while (enumeration.hasMoreElements()) { TreeNode n = (TreeNode)enumeration.nextElement(); TreePath p = path.pathByAddingChild(n); expandAll(tree, p, expand); } } if (expand) { tree.expandPath(path); } else { tree.collapsePath(path); } }
[ "public", "static", "void", "expandAll", "(", "JTree", "tree", ",", "TreePath", "path", ",", "boolean", "expand", ")", "{", "TreeNode", "node", "=", "(", "TreeNode", ")", "path", ".", "getLastPathComponent", "(", ")", ";", "if", "(", "node", ".", "getChildCount", "(", ")", ">=", "0", ")", "{", "Enumeration", "<", "?", ">", "enumeration", "=", "node", ".", "children", "(", ")", ";", "while", "(", "enumeration", ".", "hasMoreElements", "(", ")", ")", "{", "TreeNode", "n", "=", "(", "TreeNode", ")", "enumeration", ".", "nextElement", "(", ")", ";", "TreePath", "p", "=", "path", ".", "pathByAddingChild", "(", "n", ")", ";", "expandAll", "(", "tree", ",", "p", ",", "expand", ")", ";", "}", "}", "if", "(", "expand", ")", "{", "tree", ".", "expandPath", "(", "path", ")", ";", "}", "else", "{", "tree", ".", "collapsePath", "(", "path", ")", ";", "}", "}" ]
Expand all nodes recursive @param tree the tree @param path the path @param expand the flag to expand or collapse
[ "Expand", "all", "nodes", "recursive" ]
train
https://github.com/lightblueseas/swing-components/blob/4045e85cabd8f0ce985cbfff134c3c9873930c79/src/main/java/de/alpharogroup/swing/tree/JTreeExtensions.java#L51-L75
google/error-prone-javac
src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/Gen.java
Gen.makeNewArray
Item makeNewArray(DiagnosticPosition pos, Type type, int ndims) { Type elemtype = types.elemtype(type); if (types.dimensions(type) > ClassFile.MAX_DIMENSIONS) { log.error(pos, "limit.dimensions"); nerrs++; } int elemcode = Code.arraycode(elemtype); if (elemcode == 0 || (elemcode == 1 && ndims == 1)) { code.emitAnewarray(makeRef(pos, elemtype), type); } else if (elemcode == 1) { code.emitMultianewarray(ndims, makeRef(pos, type), type); } else { code.emitNewarray(elemcode, type); } return items.makeStackItem(type); }
java
Item makeNewArray(DiagnosticPosition pos, Type type, int ndims) { Type elemtype = types.elemtype(type); if (types.dimensions(type) > ClassFile.MAX_DIMENSIONS) { log.error(pos, "limit.dimensions"); nerrs++; } int elemcode = Code.arraycode(elemtype); if (elemcode == 0 || (elemcode == 1 && ndims == 1)) { code.emitAnewarray(makeRef(pos, elemtype), type); } else if (elemcode == 1) { code.emitMultianewarray(ndims, makeRef(pos, type), type); } else { code.emitNewarray(elemcode, type); } return items.makeStackItem(type); }
[ "Item", "makeNewArray", "(", "DiagnosticPosition", "pos", ",", "Type", "type", ",", "int", "ndims", ")", "{", "Type", "elemtype", "=", "types", ".", "elemtype", "(", "type", ")", ";", "if", "(", "types", ".", "dimensions", "(", "type", ")", ">", "ClassFile", ".", "MAX_DIMENSIONS", ")", "{", "log", ".", "error", "(", "pos", ",", "\"limit.dimensions\"", ")", ";", "nerrs", "++", ";", "}", "int", "elemcode", "=", "Code", ".", "arraycode", "(", "elemtype", ")", ";", "if", "(", "elemcode", "==", "0", "||", "(", "elemcode", "==", "1", "&&", "ndims", "==", "1", ")", ")", "{", "code", ".", "emitAnewarray", "(", "makeRef", "(", "pos", ",", "elemtype", ")", ",", "type", ")", ";", "}", "else", "if", "(", "elemcode", "==", "1", ")", "{", "code", ".", "emitMultianewarray", "(", "ndims", ",", "makeRef", "(", "pos", ",", "type", ")", ",", "type", ")", ";", "}", "else", "{", "code", ".", "emitNewarray", "(", "elemcode", ",", "type", ")", ";", "}", "return", "items", ".", "makeStackItem", "(", "type", ")", ";", "}" ]
Generate code to create an array with given element type and number of dimensions.
[ "Generate", "code", "to", "create", "an", "array", "with", "given", "element", "type", "and", "number", "of", "dimensions", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/Gen.java#L1760-L1775
playn/playn
android/src/playn/android/AndroidAudio.java
AndroidAudio.createSound
public SoundImpl<?> createSound(FileDescriptor fd, long offset, long length) { PooledSound sound = new PooledSound(pool.load(fd, offset, length, 1)); loadingSounds.put(sound.soundId, sound); return sound; }
java
public SoundImpl<?> createSound(FileDescriptor fd, long offset, long length) { PooledSound sound = new PooledSound(pool.load(fd, offset, length, 1)); loadingSounds.put(sound.soundId, sound); return sound; }
[ "public", "SoundImpl", "<", "?", ">", "createSound", "(", "FileDescriptor", "fd", ",", "long", "offset", ",", "long", "length", ")", "{", "PooledSound", "sound", "=", "new", "PooledSound", "(", "pool", ".", "load", "(", "fd", ",", "offset", ",", "length", ",", "1", ")", ")", ";", "loadingSounds", ".", "put", "(", "sound", ".", "soundId", ",", "sound", ")", ";", "return", "sound", ";", "}" ]
Creates a sound instance from the supplied file descriptor offset.
[ "Creates", "a", "sound", "instance", "from", "the", "supplied", "file", "descriptor", "offset", "." ]
train
https://github.com/playn/playn/blob/7e7a9d048ba6afe550dc0cdeaca3e1d5b0d01c66/android/src/playn/android/AndroidAudio.java#L134-L138
jbundle/jbundle
base/message/trx/src/main/java/org/jbundle/base/message/trx/message/external/convert/xml/XmlConvertToMessage.java
XmlConvertToMessage.unmarshalRootElement
public Object unmarshalRootElement(Reader inStream, BaseXmlTrxMessageIn soapTrxMessage) throws Exception { String xml = Utility.transferURLStream(null, null, inStream, null); soapTrxMessage.getMessage().setXML(xml); return xml; }
java
public Object unmarshalRootElement(Reader inStream, BaseXmlTrxMessageIn soapTrxMessage) throws Exception { String xml = Utility.transferURLStream(null, null, inStream, null); soapTrxMessage.getMessage().setXML(xml); return xml; }
[ "public", "Object", "unmarshalRootElement", "(", "Reader", "inStream", ",", "BaseXmlTrxMessageIn", "soapTrxMessage", ")", "throws", "Exception", "{", "String", "xml", "=", "Utility", ".", "transferURLStream", "(", "null", ",", "null", ",", "inStream", ",", "null", ")", ";", "soapTrxMessage", ".", "getMessage", "(", ")", ".", "setXML", "(", "xml", ")", ";", "return", "xml", ";", "}" ]
Create the root element for this message. You must override this. @return The root element.
[ "Create", "the", "root", "element", "for", "this", "message", ".", "You", "must", "override", "this", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/message/trx/src/main/java/org/jbundle/base/message/trx/message/external/convert/xml/XmlConvertToMessage.java#L59-L65
facebookarchive/hadoop-20
src/contrib/corona/src/java/org/apache/hadoop/util/CoronaSerializer.java
CoronaSerializer.readToken
public void readToken(String parentFieldName, JsonToken expectedToken) throws IOException { JsonToken currentToken = jsonParser.nextToken(); if (currentToken != expectedToken) { throw new IOException("Expected a " + expectedToken.toString() + " token when reading the value of the field: " + parentFieldName + " but found a " + currentToken.toString() + " token"); } }
java
public void readToken(String parentFieldName, JsonToken expectedToken) throws IOException { JsonToken currentToken = jsonParser.nextToken(); if (currentToken != expectedToken) { throw new IOException("Expected a " + expectedToken.toString() + " token when reading the value of the field: " + parentFieldName + " but found a " + currentToken.toString() + " token"); } }
[ "public", "void", "readToken", "(", "String", "parentFieldName", ",", "JsonToken", "expectedToken", ")", "throws", "IOException", "{", "JsonToken", "currentToken", "=", "jsonParser", ".", "nextToken", "(", ")", ";", "if", "(", "currentToken", "!=", "expectedToken", ")", "{", "throw", "new", "IOException", "(", "\"Expected a \"", "+", "expectedToken", ".", "toString", "(", ")", "+", "\" token when reading the value of the field: \"", "+", "parentFieldName", "+", "\" but found a \"", "+", "currentToken", ".", "toString", "(", ")", "+", "\" token\"", ")", ";", "}", "}" ]
This is a helper method that reads a JSON token using a JsonParser instance, and throws an exception if the next token is not the same as the token we expect. @param parentFieldName The name of the field @param expectedToken The expected token @throws IOException
[ "This", "is", "a", "helper", "method", "that", "reads", "a", "JSON", "token", "using", "a", "JsonParser", "instance", "and", "throws", "an", "exception", "if", "the", "next", "token", "is", "not", "the", "same", "as", "the", "token", "we", "expect", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/corona/src/java/org/apache/hadoop/util/CoronaSerializer.java#L121-L131
sebastiangraf/treetank
interfacemodules/jax-rx/src/main/java/org/treetank/service/jaxrx/util/WorkerHelper.java
WorkerHelper.shredInputStream
public static void shredInputStream(final INodeWriteTrx wtx, final InputStream value, final EShredderInsert child) { final XMLInputFactory factory = XMLInputFactory.newInstance(); factory.setProperty(XMLInputFactory.SUPPORT_DTD, false); XMLEventReader parser; try { parser = factory.createXMLEventReader(value); } catch (final XMLStreamException xmlse) { throw new WebApplicationException(xmlse); } try { final XMLShredder shredder = new XMLShredder(wtx, parser, child); shredder.call(); } catch (final Exception exce) { throw new WebApplicationException(exce); } }
java
public static void shredInputStream(final INodeWriteTrx wtx, final InputStream value, final EShredderInsert child) { final XMLInputFactory factory = XMLInputFactory.newInstance(); factory.setProperty(XMLInputFactory.SUPPORT_DTD, false); XMLEventReader parser; try { parser = factory.createXMLEventReader(value); } catch (final XMLStreamException xmlse) { throw new WebApplicationException(xmlse); } try { final XMLShredder shredder = new XMLShredder(wtx, parser, child); shredder.call(); } catch (final Exception exce) { throw new WebApplicationException(exce); } }
[ "public", "static", "void", "shredInputStream", "(", "final", "INodeWriteTrx", "wtx", ",", "final", "InputStream", "value", ",", "final", "EShredderInsert", "child", ")", "{", "final", "XMLInputFactory", "factory", "=", "XMLInputFactory", ".", "newInstance", "(", ")", ";", "factory", ".", "setProperty", "(", "XMLInputFactory", ".", "SUPPORT_DTD", ",", "false", ")", ";", "XMLEventReader", "parser", ";", "try", "{", "parser", "=", "factory", ".", "createXMLEventReader", "(", "value", ")", ";", "}", "catch", "(", "final", "XMLStreamException", "xmlse", ")", "{", "throw", "new", "WebApplicationException", "(", "xmlse", ")", ";", "}", "try", "{", "final", "XMLShredder", "shredder", "=", "new", "XMLShredder", "(", "wtx", ",", "parser", ",", "child", ")", ";", "shredder", ".", "call", "(", ")", ";", "}", "catch", "(", "final", "Exception", "exce", ")", "{", "throw", "new", "WebApplicationException", "(", "exce", ")", ";", "}", "}" ]
Shreds a given InputStream @param wtx current write transaction reference @param value InputStream to be shred
[ "Shreds", "a", "given", "InputStream" ]
train
https://github.com/sebastiangraf/treetank/blob/9b96d631b6c2a8502a0cc958dcb02bd6a6fd8b60/interfacemodules/jax-rx/src/main/java/org/treetank/service/jaxrx/util/WorkerHelper.java#L91-L108
lessthanoptimal/BoofCV
main/boofcv-recognition/src/main/java/boofcv/alg/tracker/tld/TldDetection.java
TldDetection.selectBestRegionsFern
protected void selectBestRegionsFern(double totalP, double totalN) { for( int i = 0; i < fernInfo.size; i++ ) { TldRegionFernInfo info = fernInfo.get(i); double probP = info.sumP/totalP; double probN = info.sumN/totalN; // only consider regions with a higher P likelihood if( probP > probN ) { // reward regions with a large difference between the P and N values storageMetric.add(-(probP-probN)); storageRect.add( info.r ); } } // Select the N regions with the highest fern probability if( config.maximumCascadeConsider < storageMetric.size ) { int N = Math.min(config.maximumCascadeConsider, storageMetric.size); storageIndexes.resize(storageMetric.size); QuickSelect.selectIndex(storageMetric.data, N - 1, storageMetric.size, storageIndexes.data); for( int i = 0; i < N; i++ ) { fernRegions.add(storageRect.get(storageIndexes.get(i))); } } else { fernRegions.addAll(storageRect); } }
java
protected void selectBestRegionsFern(double totalP, double totalN) { for( int i = 0; i < fernInfo.size; i++ ) { TldRegionFernInfo info = fernInfo.get(i); double probP = info.sumP/totalP; double probN = info.sumN/totalN; // only consider regions with a higher P likelihood if( probP > probN ) { // reward regions with a large difference between the P and N values storageMetric.add(-(probP-probN)); storageRect.add( info.r ); } } // Select the N regions with the highest fern probability if( config.maximumCascadeConsider < storageMetric.size ) { int N = Math.min(config.maximumCascadeConsider, storageMetric.size); storageIndexes.resize(storageMetric.size); QuickSelect.selectIndex(storageMetric.data, N - 1, storageMetric.size, storageIndexes.data); for( int i = 0; i < N; i++ ) { fernRegions.add(storageRect.get(storageIndexes.get(i))); } } else { fernRegions.addAll(storageRect); } }
[ "protected", "void", "selectBestRegionsFern", "(", "double", "totalP", ",", "double", "totalN", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "fernInfo", ".", "size", ";", "i", "++", ")", "{", "TldRegionFernInfo", "info", "=", "fernInfo", ".", "get", "(", "i", ")", ";", "double", "probP", "=", "info", ".", "sumP", "/", "totalP", ";", "double", "probN", "=", "info", ".", "sumN", "/", "totalN", ";", "// only consider regions with a higher P likelihood", "if", "(", "probP", ">", "probN", ")", "{", "// reward regions with a large difference between the P and N values", "storageMetric", ".", "add", "(", "-", "(", "probP", "-", "probN", ")", ")", ";", "storageRect", ".", "add", "(", "info", ".", "r", ")", ";", "}", "}", "// Select the N regions with the highest fern probability", "if", "(", "config", ".", "maximumCascadeConsider", "<", "storageMetric", ".", "size", ")", "{", "int", "N", "=", "Math", ".", "min", "(", "config", ".", "maximumCascadeConsider", ",", "storageMetric", ".", "size", ")", ";", "storageIndexes", ".", "resize", "(", "storageMetric", ".", "size", ")", ";", "QuickSelect", ".", "selectIndex", "(", "storageMetric", ".", "data", ",", "N", "-", "1", ",", "storageMetric", ".", "size", ",", "storageIndexes", ".", "data", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "N", ";", "i", "++", ")", "{", "fernRegions", ".", "add", "(", "storageRect", ".", "get", "(", "storageIndexes", ".", "get", "(", "i", ")", ")", ")", ";", "}", "}", "else", "{", "fernRegions", ".", "addAll", "(", "storageRect", ")", ";", "}", "}" ]
compute the probability that each region is the target conditional upon this image the sumP and sumN are needed for image conditional probability NOTE: This is a big change from the original paper
[ "compute", "the", "probability", "that", "each", "region", "is", "the", "target", "conditional", "upon", "this", "image", "the", "sumP", "and", "sumN", "are", "needed", "for", "image", "conditional", "probability" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/tracker/tld/TldDetection.java#L189-L217
duracloud/duracloud
durastore/src/main/java/org/duracloud/durastore/rest/SpaceRest.java
SpaceRest.updateSpaceACLs
@Path("/acl/{spaceID}") @POST public Response updateSpaceACLs(@PathParam("spaceID") String spaceID, @QueryParam("storeID") String storeID) { String msg = "update space ACLs(" + spaceID + ", " + storeID + ")"; try { log.debug(msg); return doUpdateSpaceACLs(spaceID, storeID); } catch (ResourceNotFoundException e) { return responseNotFound(msg, e, NOT_FOUND); } catch (ResourceException e) { return responseBad(msg, e, INTERNAL_SERVER_ERROR); } catch (Exception e) { return responseBad(msg, e, INTERNAL_SERVER_ERROR); } }
java
@Path("/acl/{spaceID}") @POST public Response updateSpaceACLs(@PathParam("spaceID") String spaceID, @QueryParam("storeID") String storeID) { String msg = "update space ACLs(" + spaceID + ", " + storeID + ")"; try { log.debug(msg); return doUpdateSpaceACLs(spaceID, storeID); } catch (ResourceNotFoundException e) { return responseNotFound(msg, e, NOT_FOUND); } catch (ResourceException e) { return responseBad(msg, e, INTERNAL_SERVER_ERROR); } catch (Exception e) { return responseBad(msg, e, INTERNAL_SERVER_ERROR); } }
[ "@", "Path", "(", "\"/acl/{spaceID}\"", ")", "@", "POST", "public", "Response", "updateSpaceACLs", "(", "@", "PathParam", "(", "\"spaceID\"", ")", "String", "spaceID", ",", "@", "QueryParam", "(", "\"storeID\"", ")", "String", "storeID", ")", "{", "String", "msg", "=", "\"update space ACLs(\"", "+", "spaceID", "+", "\", \"", "+", "storeID", "+", "\")\"", ";", "try", "{", "log", ".", "debug", "(", "msg", ")", ";", "return", "doUpdateSpaceACLs", "(", "spaceID", ",", "storeID", ")", ";", "}", "catch", "(", "ResourceNotFoundException", "e", ")", "{", "return", "responseNotFound", "(", "msg", ",", "e", ",", "NOT_FOUND", ")", ";", "}", "catch", "(", "ResourceException", "e", ")", "{", "return", "responseBad", "(", "msg", ",", "e", ",", "INTERNAL_SERVER_ERROR", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "return", "responseBad", "(", "msg", ",", "e", ",", "INTERNAL_SERVER_ERROR", ")", ";", "}", "}" ]
This method sets the ACLs associated with a space. Only values included in the ACLs headers will be updated, others will be removed. @return 200 response
[ "This", "method", "sets", "the", "ACLs", "associated", "with", "a", "space", ".", "Only", "values", "included", "in", "the", "ACLs", "headers", "will", "be", "updated", "others", "will", "be", "removed", "." ]
train
https://github.com/duracloud/duracloud/blob/dc4f3a1716d43543cc3b2e1880605f9389849b66/durastore/src/main/java/org/duracloud/durastore/rest/SpaceRest.java#L288-L307
eclipse/xtext-extras
org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/typesystem/references/UnboundTypeReference.java
UnboundTypeReference.canResolveTo
public boolean canResolveTo(LightweightTypeReference reference) { if (internalIsResolved()) return reference.isAssignableFrom(resolvedTo, new TypeConformanceComputationArgument(false, true, true, true, false, false /* TODO do we need to support synonmys here? */)); List<LightweightBoundTypeArgument> hints = getAllHints(); if (!hints.isEmpty() && hasSignificantHints(hints)) { return canResolveTo(reference, hints); } return false; }
java
public boolean canResolveTo(LightweightTypeReference reference) { if (internalIsResolved()) return reference.isAssignableFrom(resolvedTo, new TypeConformanceComputationArgument(false, true, true, true, false, false /* TODO do we need to support synonmys here? */)); List<LightweightBoundTypeArgument> hints = getAllHints(); if (!hints.isEmpty() && hasSignificantHints(hints)) { return canResolveTo(reference, hints); } return false; }
[ "public", "boolean", "canResolveTo", "(", "LightweightTypeReference", "reference", ")", "{", "if", "(", "internalIsResolved", "(", ")", ")", "return", "reference", ".", "isAssignableFrom", "(", "resolvedTo", ",", "new", "TypeConformanceComputationArgument", "(", "false", ",", "true", ",", "true", ",", "true", ",", "false", ",", "false", "/* TODO do we need to support synonmys here? */", ")", ")", ";", "List", "<", "LightweightBoundTypeArgument", ">", "hints", "=", "getAllHints", "(", ")", ";", "if", "(", "!", "hints", ".", "isEmpty", "(", ")", "&&", "hasSignificantHints", "(", "hints", ")", ")", "{", "return", "canResolveTo", "(", "reference", ",", "hints", ")", ";", "}", "return", "false", ";", "}" ]
Returns true if the existing hints would allow to resolve to the given reference.
[ "Returns", "true", "if", "the", "existing", "hints", "would", "allow", "to", "resolve", "to", "the", "given", "reference", "." ]
train
https://github.com/eclipse/xtext-extras/blob/451359541295323a29f5855e633f770cec02069a/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/typesystem/references/UnboundTypeReference.java#L147-L155
brunocvcunha/inutils4j
src/main/java/org/brunocvcunha/inutils4j/MyNumberUtils.java
MyNumberUtils.randomIntBetween
public static int randomIntBetween(int min, int max) { Random rand = new Random(); return rand.nextInt((max - min) + 1) + min; }
java
public static int randomIntBetween(int min, int max) { Random rand = new Random(); return rand.nextInt((max - min) + 1) + min; }
[ "public", "static", "int", "randomIntBetween", "(", "int", "min", ",", "int", "max", ")", "{", "Random", "rand", "=", "new", "Random", "(", ")", ";", "return", "rand", ".", "nextInt", "(", "(", "max", "-", "min", ")", "+", "1", ")", "+", "min", ";", "}" ]
Returns an integer between interval @param min Minimum value @param max Maximum value @return int number
[ "Returns", "an", "integer", "between", "interval" ]
train
https://github.com/brunocvcunha/inutils4j/blob/223c4443c2cee662576ce644e552588fa114aa94/src/main/java/org/brunocvcunha/inutils4j/MyNumberUtils.java#L34-L37
js-lib-com/commons
src/main/java/js/util/Classes.java
Classes.getResourceAsStream
public static InputStream getResourceAsStream(String name) { Params.notNullOrEmpty(name, "Resource name"); // not documented behavior: accept but ignore trailing path separator if(name.charAt(0) == '/') { name = name.substring(1); } InputStream stream = getResourceAsStream(name, new ClassLoader[] { Thread.currentThread().getContextClassLoader(), Classes.class.getClassLoader(), ClassLoader.getSystemClassLoader() }); if(stream == null) { throw new NoSuchBeingException("Resource |%s| not found.", name); } return stream; }
java
public static InputStream getResourceAsStream(String name) { Params.notNullOrEmpty(name, "Resource name"); // not documented behavior: accept but ignore trailing path separator if(name.charAt(0) == '/') { name = name.substring(1); } InputStream stream = getResourceAsStream(name, new ClassLoader[] { Thread.currentThread().getContextClassLoader(), Classes.class.getClassLoader(), ClassLoader.getSystemClassLoader() }); if(stream == null) { throw new NoSuchBeingException("Resource |%s| not found.", name); } return stream; }
[ "public", "static", "InputStream", "getResourceAsStream", "(", "String", "name", ")", "{", "Params", ".", "notNullOrEmpty", "(", "name", ",", "\"Resource name\"", ")", ";", "// not documented behavior: accept but ignore trailing path separator\r", "if", "(", "name", ".", "charAt", "(", "0", ")", "==", "'", "'", ")", "{", "name", "=", "name", ".", "substring", "(", "1", ")", ";", "}", "InputStream", "stream", "=", "getResourceAsStream", "(", "name", ",", "new", "ClassLoader", "[", "]", "{", "Thread", ".", "currentThread", "(", ")", ".", "getContextClassLoader", "(", ")", ",", "Classes", ".", "class", ".", "getClassLoader", "(", ")", ",", "ClassLoader", ".", "getSystemClassLoader", "(", ")", "}", ")", ";", "if", "(", "stream", "==", "null", ")", "{", "throw", "new", "NoSuchBeingException", "(", "\"Resource |%s| not found.\"", ",", "name", ")", ";", "}", "return", "stream", ";", "}" ]
Retrieve resource, identified by qualified name, as input stream. This method does its best to load requested resource but throws exception if fail. Resource is loaded using {@link ClassLoader#getResourceAsStream(String)} and <code>name</code> argument should follow Java class loader convention: it is always considered as absolute path, that is, should contain package but does not start with leading path separator, e.g. <code>js/fop/config.xml</code> . <p> Resource is searched into next class loaders, in given order: <ul> <li>current thread context class loader, <li>this utility class loader, <li>system class loader, as returned by {@link ClassLoader#getSystemClassLoader()} </ul> @param name resource qualified name, using path separators instead of dots. @return resource input stream. @throws IllegalArgumentException if <code>name</code> argument is null or empty. @throws NoSuchBeingException if resource not found.
[ "Retrieve", "resource", "identified", "by", "qualified", "name", "as", "input", "stream", ".", "This", "method", "does", "its", "best", "to", "load", "requested", "resource", "but", "throws", "exception", "if", "fail", ".", "Resource", "is", "loaded", "using", "{", "@link", "ClassLoader#getResourceAsStream", "(", "String", ")", "}", "and", "<code", ">", "name<", "/", "code", ">", "argument", "should", "follow", "Java", "class", "loader", "convention", ":", "it", "is", "always", "considered", "as", "absolute", "path", "that", "is", "should", "contain", "package", "but", "does", "not", "start", "with", "leading", "path", "separator", "e", ".", "g", ".", "<code", ">", "js", "/", "fop", "/", "config", ".", "xml<", "/", "code", ">", ".", "<p", ">", "Resource", "is", "searched", "into", "next", "class", "loaders", "in", "given", "order", ":", "<ul", ">", "<li", ">", "current", "thread", "context", "class", "loader", "<li", ">", "this", "utility", "class", "loader", "<li", ">", "system", "class", "loader", "as", "returned", "by", "{", "@link", "ClassLoader#getSystemClassLoader", "()", "}", "<", "/", "ul", ">" ]
train
https://github.com/js-lib-com/commons/blob/f8c64482142b163487745da74feb106f0765c16b/src/main/java/js/util/Classes.java#L1035-L1051
JOML-CI/JOML
src/org/joml/Quaternionf.java
Quaternionf.nlerpIterative
public static Quaternionfc nlerpIterative(Quaternionf[] qs, float[] weights, float dotThreshold, Quaternionf dest) { dest.set(qs[0]); float w = weights[0]; for (int i = 1; i < qs.length; i++) { float w0 = w; float w1 = weights[i]; float rw1 = w1 / (w0 + w1); w += w1; dest.nlerpIterative(qs[i], rw1, dotThreshold); } return dest; }
java
public static Quaternionfc nlerpIterative(Quaternionf[] qs, float[] weights, float dotThreshold, Quaternionf dest) { dest.set(qs[0]); float w = weights[0]; for (int i = 1; i < qs.length; i++) { float w0 = w; float w1 = weights[i]; float rw1 = w1 / (w0 + w1); w += w1; dest.nlerpIterative(qs[i], rw1, dotThreshold); } return dest; }
[ "public", "static", "Quaternionfc", "nlerpIterative", "(", "Quaternionf", "[", "]", "qs", ",", "float", "[", "]", "weights", ",", "float", "dotThreshold", ",", "Quaternionf", "dest", ")", "{", "dest", ".", "set", "(", "qs", "[", "0", "]", ")", ";", "float", "w", "=", "weights", "[", "0", "]", ";", "for", "(", "int", "i", "=", "1", ";", "i", "<", "qs", ".", "length", ";", "i", "++", ")", "{", "float", "w0", "=", "w", ";", "float", "w1", "=", "weights", "[", "i", "]", ";", "float", "rw1", "=", "w1", "/", "(", "w0", "+", "w1", ")", ";", "w", "+=", "w1", ";", "dest", ".", "nlerpIterative", "(", "qs", "[", "i", "]", ",", "rw1", ",", "dotThreshold", ")", ";", "}", "return", "dest", ";", "}" ]
Interpolate between all of the quaternions given in <code>qs</code> via iterative non-spherical linear interpolation using the specified interpolation factors <code>weights</code>, and store the result in <code>dest</code>. <p> This method will interpolate between each two successive quaternions via {@link #nlerpIterative(Quaternionfc, float, float)} using their relative interpolation weights. <p> Reference: <a href="http://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions#answer-62356">http://gamedev.stackexchange.com/</a> @param qs the quaternions to interpolate over @param weights the weights of each individual quaternion in <code>qs</code> @param dotThreshold the threshold for the dot product of each two interpolated quaternions above which {@link #nlerpIterative(Quaternionfc, float, float)} performs another iteration of a small-step linear interpolation @param dest will hold the result @return dest
[ "Interpolate", "between", "all", "of", "the", "quaternions", "given", "in", "<code", ">", "qs<", "/", "code", ">", "via", "iterative", "non", "-", "spherical", "linear", "interpolation", "using", "the", "specified", "interpolation", "factors", "<code", ">", "weights<", "/", "code", ">", "and", "store", "the", "result", "in", "<code", ">", "dest<", "/", "code", ">", ".", "<p", ">", "This", "method", "will", "interpolate", "between", "each", "two", "successive", "quaternions", "via", "{", "@link", "#nlerpIterative", "(", "Quaternionfc", "float", "float", ")", "}", "using", "their", "relative", "interpolation", "weights", ".", "<p", ">", "Reference", ":", "<a", "href", "=", "http", ":", "//", "gamedev", ".", "stackexchange", ".", "com", "/", "questions", "/", "62354", "/", "method", "-", "for", "-", "interpolation", "-", "between", "-", "3", "-", "quaternions#answer", "-", "62356", ">", "http", ":", "//", "gamedev", ".", "stackexchange", ".", "com", "/", "<", "/", "a", ">" ]
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Quaternionf.java#L2056-L2067
mapbox/mapbox-java
services-geojson/src/main/java/com/mapbox/geojson/Point.java
Point.fromLngLat
public static Point fromLngLat( @FloatRange(from = MIN_LONGITUDE, to = MAX_LONGITUDE) double longitude, @FloatRange(from = MIN_LATITUDE, to = MAX_LATITUDE) double latitude) { List<Double> coordinates = CoordinateShifterManager.getCoordinateShifter().shiftLonLat(longitude, latitude); return new Point(TYPE, null, coordinates); }
java
public static Point fromLngLat( @FloatRange(from = MIN_LONGITUDE, to = MAX_LONGITUDE) double longitude, @FloatRange(from = MIN_LATITUDE, to = MAX_LATITUDE) double latitude) { List<Double> coordinates = CoordinateShifterManager.getCoordinateShifter().shiftLonLat(longitude, latitude); return new Point(TYPE, null, coordinates); }
[ "public", "static", "Point", "fromLngLat", "(", "@", "FloatRange", "(", "from", "=", "MIN_LONGITUDE", ",", "to", "=", "MAX_LONGITUDE", ")", "double", "longitude", ",", "@", "FloatRange", "(", "from", "=", "MIN_LATITUDE", ",", "to", "=", "MAX_LATITUDE", ")", "double", "latitude", ")", "{", "List", "<", "Double", ">", "coordinates", "=", "CoordinateShifterManager", ".", "getCoordinateShifter", "(", ")", ".", "shiftLonLat", "(", "longitude", ",", "latitude", ")", ";", "return", "new", "Point", "(", "TYPE", ",", "null", ",", "coordinates", ")", ";", "}" ]
Create a new instance of this class defining a longitude and latitude value in that respective order. Longitude values are limited to a -180 to 180 range and latitude's limited to -90 to 90 as the spec defines. While no limit is placed on decimal precision, for performance reasons when serializing and deserializing it is suggested to limit decimal precision to within 6 decimal places. @param longitude a double value between -180 to 180 representing the x position of this point @param latitude a double value between -90 to 90 representing the y position of this point @return a new instance of this class defined by the values passed inside this static factory method @since 3.0.0
[ "Create", "a", "new", "instance", "of", "this", "class", "defining", "a", "longitude", "and", "latitude", "value", "in", "that", "respective", "order", ".", "Longitude", "values", "are", "limited", "to", "a", "-", "180", "to", "180", "range", "and", "latitude", "s", "limited", "to", "-", "90", "to", "90", "as", "the", "spec", "defines", ".", "While", "no", "limit", "is", "placed", "on", "decimal", "precision", "for", "performance", "reasons", "when", "serializing", "and", "deserializing", "it", "is", "suggested", "to", "limit", "decimal", "precision", "to", "within", "6", "decimal", "places", "." ]
train
https://github.com/mapbox/mapbox-java/blob/c0be138f462f91441388584c668f3760ba0e18e2/services-geojson/src/main/java/com/mapbox/geojson/Point.java#L101-L108
xerial/snappy-java
src/main/java/org/xerial/snappy/Snappy.java
Snappy.rawCompress
public static int rawCompress(Object input, int inputOffset, int inputLength, byte[] output, int outputOffset) throws IOException { if (input == null || output == null) { throw new NullPointerException("input or output is null"); } int compressedSize = impl .rawCompress(input, inputOffset, inputLength, output, outputOffset); return compressedSize; }
java
public static int rawCompress(Object input, int inputOffset, int inputLength, byte[] output, int outputOffset) throws IOException { if (input == null || output == null) { throw new NullPointerException("input or output is null"); } int compressedSize = impl .rawCompress(input, inputOffset, inputLength, output, outputOffset); return compressedSize; }
[ "public", "static", "int", "rawCompress", "(", "Object", "input", ",", "int", "inputOffset", ",", "int", "inputLength", ",", "byte", "[", "]", "output", ",", "int", "outputOffset", ")", "throws", "IOException", "{", "if", "(", "input", "==", "null", "||", "output", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"input or output is null\"", ")", ";", "}", "int", "compressedSize", "=", "impl", ".", "rawCompress", "(", "input", ",", "inputOffset", ",", "inputLength", ",", "output", ",", "outputOffset", ")", ";", "return", "compressedSize", ";", "}" ]
Compress the input buffer [offset,... ,offset+length) contents, then write the compressed data to the output buffer[offset, ...) @param input input array. This MUST be a primitive array type @param inputOffset byte offset at the output array @param inputLength byte length of the input data @param output output array. This MUST be a primitive array type @param outputOffset byte offset at the output array @return byte size of the compressed data @throws IOException
[ "Compress", "the", "input", "buffer", "[", "offset", "...", "offset", "+", "length", ")", "contents", "then", "write", "the", "compressed", "data", "to", "the", "output", "buffer", "[", "offset", "...", ")" ]
train
https://github.com/xerial/snappy-java/blob/9df6ed7bbce88186c82f2e7cdcb7b974421b3340/src/main/java/org/xerial/snappy/Snappy.java#L438-L448
Azure/azure-sdk-for-java
labservices/resource-manager/v2018_10_15/src/main/java/com/microsoft/azure/management/labservices/v2018_10_15/implementation/GlobalUsersInner.java
GlobalUsersInner.beginStartEnvironment
public void beginStartEnvironment(String userName, String environmentId) { beginStartEnvironmentWithServiceResponseAsync(userName, environmentId).toBlocking().single().body(); }
java
public void beginStartEnvironment(String userName, String environmentId) { beginStartEnvironmentWithServiceResponseAsync(userName, environmentId).toBlocking().single().body(); }
[ "public", "void", "beginStartEnvironment", "(", "String", "userName", ",", "String", "environmentId", ")", "{", "beginStartEnvironmentWithServiceResponseAsync", "(", "userName", ",", "environmentId", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Starts an environment by starting all resources inside the environment. This operation can take a while to complete. @param userName The name of the user. @param environmentId The resourceId of the environment @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
[ "Starts", "an", "environment", "by", "starting", "all", "resources", "inside", "the", "environment", ".", "This", "operation", "can", "take", "a", "while", "to", "complete", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/labservices/resource-manager/v2018_10_15/src/main/java/com/microsoft/azure/management/labservices/v2018_10_15/implementation/GlobalUsersInner.java#L1149-L1151
jnr/jnr-x86asm
src/main/java/jnr/x86asm/Asm.java
Asm.tword_ptr
public static final Mem tword_ptr(Register base, Register index, int shift, long disp) { return _ptr_build(base, index, shift, disp, SIZE_TWORD); }
java
public static final Mem tword_ptr(Register base, Register index, int shift, long disp) { return _ptr_build(base, index, shift, disp, SIZE_TWORD); }
[ "public", "static", "final", "Mem", "tword_ptr", "(", "Register", "base", ",", "Register", "index", ",", "int", "shift", ",", "long", "disp", ")", "{", "return", "_ptr_build", "(", "base", ",", "index", ",", "shift", ",", "disp", ",", "SIZE_TWORD", ")", ";", "}" ]
Create tword (10 Bytes) pointer operand (used for 80 bit floating points).
[ "Create", "tword", "(", "10", "Bytes", ")", "pointer", "operand", "(", "used", "for", "80", "bit", "floating", "points", ")", "." ]
train
https://github.com/jnr/jnr-x86asm/blob/fdcf68fb3dae49e607a49e33399e3dad1ada5536/src/main/java/jnr/x86asm/Asm.java#L575-L577
Mozu/mozu-java
mozu-java-core/src/main/java/com/mozu/api/urls/commerce/shipping/admin/profiles/ShippingInclusionRuleUrl.java
ShippingInclusionRuleUrl.deleteShippingInclusionRuleUrl
public static MozuUrl deleteShippingInclusionRuleUrl(String id, String profilecode) { UrlFormatter formatter = new UrlFormatter("/api/commerce/shipping/admin/profiles/{profilecode}/rules/shippinginclusions/{id}"); formatter.formatUrl("id", id); formatter.formatUrl("profilecode", profilecode); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
java
public static MozuUrl deleteShippingInclusionRuleUrl(String id, String profilecode) { UrlFormatter formatter = new UrlFormatter("/api/commerce/shipping/admin/profiles/{profilecode}/rules/shippinginclusions/{id}"); formatter.formatUrl("id", id); formatter.formatUrl("profilecode", profilecode); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
[ "public", "static", "MozuUrl", "deleteShippingInclusionRuleUrl", "(", "String", "id", ",", "String", "profilecode", ")", "{", "UrlFormatter", "formatter", "=", "new", "UrlFormatter", "(", "\"/api/commerce/shipping/admin/profiles/{profilecode}/rules/shippinginclusions/{id}\"", ")", ";", "formatter", ".", "formatUrl", "(", "\"id\"", ",", "id", ")", ";", "formatter", ".", "formatUrl", "(", "\"profilecode\"", ",", "profilecode", ")", ";", "return", "new", "MozuUrl", "(", "formatter", ".", "getResourceUrl", "(", ")", ",", "MozuUrl", ".", "UrlLocation", ".", "TENANT_POD", ")", ";", "}" ]
Get Resource Url for DeleteShippingInclusionRule @param id Unique identifier of the customer segment to retrieve. @param profilecode The unique, user-defined code of the profile with which the shipping inclusion rule is associated. @return String Resource Url
[ "Get", "Resource", "Url", "for", "DeleteShippingInclusionRule" ]
train
https://github.com/Mozu/mozu-java/blob/5beadde73601a859f845e3e2fc1077b39c8bea83/mozu-java-core/src/main/java/com/mozu/api/urls/commerce/shipping/admin/profiles/ShippingInclusionRuleUrl.java#L82-L88
csc19601128/Phynixx
phynixx/phynixx-watchdog/src/main/java/org/csc/phynixx/watchdog/RestartCondition.java
RestartCondition.checkCondition
public boolean checkCondition() { // assure that the checkinterval is elapsed ..... if (super.checkCondition()) { return true; } if (this.watchdogReference.isStale()) { return false; } Watchdog wd = this.watchdogReference.getWatchdog(); //log.info("Checking "+this+"\n watched WD is alive="+watchedWatchdog.isAlive()+" is killed="+watchedWatchdog.isKilled()+" WD-Thead="+this.watchedWatchdog.getThreadHandle()); if (!wd.isAlive()) { if (log.isInfoEnabled()) { String logString = "RestartCondition :: Watchdog " + wd.getThreadHandle() + " is not alive "; log.info(new CheckConditionFailedLog(this, logString).toString()); } return false; } return true; }
java
public boolean checkCondition() { // assure that the checkinterval is elapsed ..... if (super.checkCondition()) { return true; } if (this.watchdogReference.isStale()) { return false; } Watchdog wd = this.watchdogReference.getWatchdog(); //log.info("Checking "+this+"\n watched WD is alive="+watchedWatchdog.isAlive()+" is killed="+watchedWatchdog.isKilled()+" WD-Thead="+this.watchedWatchdog.getThreadHandle()); if (!wd.isAlive()) { if (log.isInfoEnabled()) { String logString = "RestartCondition :: Watchdog " + wd.getThreadHandle() + " is not alive "; log.info(new CheckConditionFailedLog(this, logString).toString()); } return false; } return true; }
[ "public", "boolean", "checkCondition", "(", ")", "{", "// assure that the checkinterval is elapsed .....", "if", "(", "super", ".", "checkCondition", "(", ")", ")", "{", "return", "true", ";", "}", "if", "(", "this", ".", "watchdogReference", ".", "isStale", "(", ")", ")", "{", "return", "false", ";", "}", "Watchdog", "wd", "=", "this", ".", "watchdogReference", ".", "getWatchdog", "(", ")", ";", "//log.info(\"Checking \"+this+\"\\n watched WD is alive=\"+watchedWatchdog.isAlive()+\" is killed=\"+watchedWatchdog.isKilled()+\" WD-Thead=\"+this.watchedWatchdog.getThreadHandle());", "if", "(", "!", "wd", ".", "isAlive", "(", ")", ")", "{", "if", "(", "log", ".", "isInfoEnabled", "(", ")", ")", "{", "String", "logString", "=", "\"RestartCondition :: Watchdog \"", "+", "wd", ".", "getThreadHandle", "(", ")", "+", "\" is not alive \"", ";", "log", ".", "info", "(", "new", "CheckConditionFailedLog", "(", "this", ",", "logString", ")", ".", "toString", "(", ")", ")", ";", "}", "return", "false", ";", "}", "return", "true", ";", "}" ]
Not synchronized as to be meant for the watch dog exclusively Do not call it not synchronized
[ "Not", "synchronized", "as", "to", "be", "meant", "for", "the", "watch", "dog", "exclusively" ]
train
https://github.com/csc19601128/Phynixx/blob/a26c03bc229a8882c647799834115bec6bdc0ac8/phynixx/phynixx-watchdog/src/main/java/org/csc/phynixx/watchdog/RestartCondition.java#L50-L72
alibaba/canal
driver/src/main/java/com/alibaba/otter/canal/parse/driver/mysql/utils/ByteHelper.java
ByteHelper.readUnsignedIntLittleEndian
public static long readUnsignedIntLittleEndian(byte[] data, int index) { long result = (long) (data[index] & 0xFF) | (long) ((data[index + 1] & 0xFF) << 8) | (long) ((data[index + 2] & 0xFF) << 16) | (long) ((data[index + 3] & 0xFF) << 24); return result; }
java
public static long readUnsignedIntLittleEndian(byte[] data, int index) { long result = (long) (data[index] & 0xFF) | (long) ((data[index + 1] & 0xFF) << 8) | (long) ((data[index + 2] & 0xFF) << 16) | (long) ((data[index + 3] & 0xFF) << 24); return result; }
[ "public", "static", "long", "readUnsignedIntLittleEndian", "(", "byte", "[", "]", "data", ",", "int", "index", ")", "{", "long", "result", "=", "(", "long", ")", "(", "data", "[", "index", "]", "&", "0xFF", ")", "|", "(", "long", ")", "(", "(", "data", "[", "index", "+", "1", "]", "&", "0xFF", ")", "<<", "8", ")", "|", "(", "long", ")", "(", "(", "data", "[", "index", "+", "2", "]", "&", "0xFF", ")", "<<", "16", ")", "|", "(", "long", ")", "(", "(", "data", "[", "index", "+", "3", "]", "&", "0xFF", ")", "<<", "24", ")", ";", "return", "result", ";", "}" ]
Read 4 bytes in Little-endian byte order. @param data, the original byte array @param index, start to read from. @return
[ "Read", "4", "bytes", "in", "Little", "-", "endian", "byte", "order", "." ]
train
https://github.com/alibaba/canal/blob/8f088cddc0755f4350c5aaae95c6e4002d90a40f/driver/src/main/java/com/alibaba/otter/canal/parse/driver/mysql/utils/ByteHelper.java#L45-L49
looly/hutool
hutool-core/src/main/java/cn/hutool/core/util/NumberUtil.java
NumberUtil.isLessOrEqual
public static boolean isLessOrEqual(BigDecimal bigNum1, BigDecimal bigNum2) { Assert.notNull(bigNum1); Assert.notNull(bigNum2); return bigNum1.compareTo(bigNum2) <= 0; }
java
public static boolean isLessOrEqual(BigDecimal bigNum1, BigDecimal bigNum2) { Assert.notNull(bigNum1); Assert.notNull(bigNum2); return bigNum1.compareTo(bigNum2) <= 0; }
[ "public", "static", "boolean", "isLessOrEqual", "(", "BigDecimal", "bigNum1", ",", "BigDecimal", "bigNum2", ")", "{", "Assert", ".", "notNull", "(", "bigNum1", ")", ";", "Assert", ".", "notNull", "(", "bigNum2", ")", ";", "return", "bigNum1", ".", "compareTo", "(", "bigNum2", ")", "<=", "0", ";", "}" ]
比较大小,参数1&lt;=参数2 返回true @param bigNum1 数字1 @param bigNum2 数字2 @return 是否小于等于 @since 3,0.9
[ "比较大小,参数1&lt", ";", "=", "参数2", "返回true" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/NumberUtil.java#L1664-L1668
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/BasePrepareStatement.java
BasePrepareStatement.setClob
public void setClob(final int parameterIndex, final Clob clob) throws SQLException { if (clob == null) { setNull(parameterIndex, ColumnType.BLOB); return; } setParameter(parameterIndex, new ReaderParameter(clob.getCharacterStream(), clob.length(), noBackslashEscapes)); hasLongData = true; }
java
public void setClob(final int parameterIndex, final Clob clob) throws SQLException { if (clob == null) { setNull(parameterIndex, ColumnType.BLOB); return; } setParameter(parameterIndex, new ReaderParameter(clob.getCharacterStream(), clob.length(), noBackslashEscapes)); hasLongData = true; }
[ "public", "void", "setClob", "(", "final", "int", "parameterIndex", ",", "final", "Clob", "clob", ")", "throws", "SQLException", "{", "if", "(", "clob", "==", "null", ")", "{", "setNull", "(", "parameterIndex", ",", "ColumnType", ".", "BLOB", ")", ";", "return", ";", "}", "setParameter", "(", "parameterIndex", ",", "new", "ReaderParameter", "(", "clob", ".", "getCharacterStream", "(", ")", ",", "clob", ".", "length", "(", ")", ",", "noBackslashEscapes", ")", ")", ";", "hasLongData", "=", "true", ";", "}" ]
Sets the designated parameter to the given <code>java.sql.Clob</code> object. The driver converts this to an SQL <code>CLOB</code> value when it sends it to the database. @param parameterIndex the first parameter is 1, the second is 2, ... @param clob a <code>Clob</code> object that maps an SQL <code>CLOB</code> value @throws SQLException if parameterIndex does not correspond to a parameter marker in the SQL statement; if a database access error occurs or this method is called on a closed <code>PreparedStatement</code>
[ "Sets", "the", "designated", "parameter", "to", "the", "given", "<code", ">", "java", ".", "sql", ".", "Clob<", "/", "code", ">", "object", ".", "The", "driver", "converts", "this", "to", "an", "SQL", "<code", ">", "CLOB<", "/", "code", ">", "value", "when", "it", "sends", "it", "to", "the", "database", "." ]
train
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/BasePrepareStatement.java#L390-L399
ehcache/ehcache3
impl/src/main/java/org/ehcache/impl/internal/resilience/AbstractResilienceStrategy.java
AbstractResilienceStrategy.pacedErrorLog
protected void pacedErrorLog(String message, StoreAccessException e) { pacer.pacedCall(() -> LOGGER.error(message + " - Similar messages will be suppressed for 30 seconds", e), () -> LOGGER.debug(message, e)); }
java
protected void pacedErrorLog(String message, StoreAccessException e) { pacer.pacedCall(() -> LOGGER.error(message + " - Similar messages will be suppressed for 30 seconds", e), () -> LOGGER.debug(message, e)); }
[ "protected", "void", "pacedErrorLog", "(", "String", "message", ",", "StoreAccessException", "e", ")", "{", "pacer", ".", "pacedCall", "(", "(", ")", "->", "LOGGER", ".", "error", "(", "message", "+", "\" - Similar messages will be suppressed for 30 seconds\"", ",", "e", ")", ",", "(", ")", "->", "LOGGER", ".", "debug", "(", "message", ",", "e", ")", ")", ";", "}" ]
Log messages in error at worst every 30 seconds. Log everything at debug level. @param message message to log @param e exception to log
[ "Log", "messages", "in", "error", "at", "worst", "every", "30", "seconds", ".", "Log", "everything", "at", "debug", "level", "." ]
train
https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/impl/internal/resilience/AbstractResilienceStrategy.java#L178-L180