repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
18
188
func_name
stringlengths
7
127
whole_func_string
stringlengths
77
3.91k
language
stringclasses
1 value
func_code_string
stringlengths
77
3.91k
func_code_tokens
listlengths
20
745
func_documentation_string
stringlengths
61
1.98k
func_documentation_tokens
listlengths
1
477
split_name
stringclasses
1 value
func_code_url
stringlengths
111
288
albfernandez/itext2
src/main/java/com/lowagie/text/xml/xmp/XmpSchema.java
XmpSchema.setProperty
public Object setProperty(String key, LangAlt value) { return super.setProperty(key, value.toString()); }
java
public Object setProperty(String key, LangAlt value) { return super.setProperty(key, value.toString()); }
[ "public", "Object", "setProperty", "(", "String", "key", ",", "LangAlt", "value", ")", "{", "return", "super", ".", "setProperty", "(", "key", ",", "value", ".", "toString", "(", ")", ")", ";", "}" ]
@see java.util.Properties#setProperty(java.lang.String, java.lang.String) @param key @param value @return the previous property (null if there wasn't one)
[ "@see", "java", ".", "util", ".", "Properties#setProperty", "(", "java", ".", "lang", ".", "String", "java", ".", "lang", ".", "String", ")" ]
train
https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/xml/xmp/XmpSchema.java#L138-L140
UrielCh/ovh-java-sdk
ovh-java-sdk-hostingweb/src/main/java/net/minidev/ovh/api/ApiOvhHostingweb.java
ApiOvhHostingweb.serviceName_database_name_dump_GET
public ArrayList<Long> serviceName_database_name_dump_GET(String serviceName, String name, Date creationDate, Date deletionDate, OvhDateEnum type) throws IOException { String qPath = "/hosting/web/{serviceName}/database/{name}/dump"; StringBuilder sb = path(qPath, serviceName, name); query(sb, "creationDate", creationDate); query(sb, "deletionDate", deletionDate); query(sb, "type", type); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t3); }
java
public ArrayList<Long> serviceName_database_name_dump_GET(String serviceName, String name, Date creationDate, Date deletionDate, OvhDateEnum type) throws IOException { String qPath = "/hosting/web/{serviceName}/database/{name}/dump"; StringBuilder sb = path(qPath, serviceName, name); query(sb, "creationDate", creationDate); query(sb, "deletionDate", deletionDate); query(sb, "type", type); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t3); }
[ "public", "ArrayList", "<", "Long", ">", "serviceName_database_name_dump_GET", "(", "String", "serviceName", ",", "String", "name", ",", "Date", "creationDate", ",", "Date", "deletionDate", ",", "OvhDateEnum", "type", ")", "throws", "IOException", "{", "String", "...
Dump available for your databases REST: GET /hosting/web/{serviceName}/database/{name}/dump @param type [required] Filter the value of type property (=) @param deletionDate [required] Filter the value of deletionDate property (like) @param creationDate [required] Filter the value of creationDate property (like) @param serviceName [required] The internal name of your hosting @param name [required] Database name (like mydb.mysql.db or mydb.postgres.db)
[ "Dump", "available", "for", "your", "databases" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-hostingweb/src/main/java/net/minidev/ovh/api/ApiOvhHostingweb.java#L1179-L1187
cdapio/tigon
tigon-yarn/src/main/java/co/cask/tigon/internal/io/DatumWriterGenerator.java
DatumWriterGenerator.generateConstructor
private void generateConstructor() { Method constructor = getMethod(void.class, "<init>", Schema.class, FieldAccessorFactory.class); // Constructor(Schema schema, FieldAccessorFactory accessorFactory) GeneratorAdapter mg = new GeneratorAdapter(Opcodes.ACC_PUBLIC, constructor, null, null, classWriter); // super(); // Calling Object constructor mg.loadThis(); mg.invokeConstructor(Type.getType(Object.class), getMethod(void.class, "<init>")); // if (!SCHEMA_HASH.equals(schema.getSchemaHash().toString())) { throw IllegalArgumentException } mg.getStatic(classType, "SCHEMA_HASH", Type.getType(String.class)); mg.loadArg(0); mg.invokeVirtual(Type.getType(Schema.class), getMethod(SchemaHash.class, "getSchemaHash")); mg.invokeVirtual(Type.getType(SchemaHash.class), getMethod(String.class, "toString")); mg.invokeVirtual(Type.getType(String.class), getMethod(boolean.class, "equals", Object.class)); Label hashEquals = mg.newLabel(); mg.ifZCmp(GeneratorAdapter.NE, hashEquals); mg.throwException(Type.getType(IllegalArgumentException.class), "Schema not match."); mg.mark(hashEquals); // this.schema = schema; mg.loadThis(); mg.loadArg(0); mg.putField(classType, "schema", Type.getType(Schema.class)); // For each record field that needs an accessor, get the accessor and store it in field. for (Map.Entry<TypeToken<?>, String> entry : fieldAccessorRequests.entries()) { String fieldAccessorName = getFieldAccessorName(entry.getKey(), entry.getValue()); classWriter.visitField(Opcodes.ACC_PRIVATE + Opcodes.ACC_FINAL, fieldAccessorName, Type.getDescriptor(FieldAccessor.class), null, null); // this.fieldAccessorName // = accessorFactory.getFieldAccessor(TypeToken.of(Class.forName("className")), "fieldName"); mg.loadThis(); mg.loadArg(1); mg.push(entry.getKey().getRawType().getName()); mg.invokeStatic(Type.getType(Class.class), getMethod(Class.class, "forName", String.class)); mg.invokeStatic(Type.getType(TypeToken.class), getMethod(TypeToken.class, "of", Class.class)); mg.push(entry.getValue()); mg.invokeInterface(Type.getType(FieldAccessorFactory.class), getMethod(FieldAccessor.class, "getFieldAccessor", TypeToken.class, String.class)); mg.putField(classType, fieldAccessorName, Type.getType(FieldAccessor.class)); } mg.returnValue(); mg.endMethod(); }
java
private void generateConstructor() { Method constructor = getMethod(void.class, "<init>", Schema.class, FieldAccessorFactory.class); // Constructor(Schema schema, FieldAccessorFactory accessorFactory) GeneratorAdapter mg = new GeneratorAdapter(Opcodes.ACC_PUBLIC, constructor, null, null, classWriter); // super(); // Calling Object constructor mg.loadThis(); mg.invokeConstructor(Type.getType(Object.class), getMethod(void.class, "<init>")); // if (!SCHEMA_HASH.equals(schema.getSchemaHash().toString())) { throw IllegalArgumentException } mg.getStatic(classType, "SCHEMA_HASH", Type.getType(String.class)); mg.loadArg(0); mg.invokeVirtual(Type.getType(Schema.class), getMethod(SchemaHash.class, "getSchemaHash")); mg.invokeVirtual(Type.getType(SchemaHash.class), getMethod(String.class, "toString")); mg.invokeVirtual(Type.getType(String.class), getMethod(boolean.class, "equals", Object.class)); Label hashEquals = mg.newLabel(); mg.ifZCmp(GeneratorAdapter.NE, hashEquals); mg.throwException(Type.getType(IllegalArgumentException.class), "Schema not match."); mg.mark(hashEquals); // this.schema = schema; mg.loadThis(); mg.loadArg(0); mg.putField(classType, "schema", Type.getType(Schema.class)); // For each record field that needs an accessor, get the accessor and store it in field. for (Map.Entry<TypeToken<?>, String> entry : fieldAccessorRequests.entries()) { String fieldAccessorName = getFieldAccessorName(entry.getKey(), entry.getValue()); classWriter.visitField(Opcodes.ACC_PRIVATE + Opcodes.ACC_FINAL, fieldAccessorName, Type.getDescriptor(FieldAccessor.class), null, null); // this.fieldAccessorName // = accessorFactory.getFieldAccessor(TypeToken.of(Class.forName("className")), "fieldName"); mg.loadThis(); mg.loadArg(1); mg.push(entry.getKey().getRawType().getName()); mg.invokeStatic(Type.getType(Class.class), getMethod(Class.class, "forName", String.class)); mg.invokeStatic(Type.getType(TypeToken.class), getMethod(TypeToken.class, "of", Class.class)); mg.push(entry.getValue()); mg.invokeInterface(Type.getType(FieldAccessorFactory.class), getMethod(FieldAccessor.class, "getFieldAccessor", TypeToken.class, String.class)); mg.putField(classType, fieldAccessorName, Type.getType(FieldAccessor.class)); } mg.returnValue(); mg.endMethod(); }
[ "private", "void", "generateConstructor", "(", ")", "{", "Method", "constructor", "=", "getMethod", "(", "void", ".", "class", ",", "\"<init>\"", ",", "Schema", ".", "class", ",", "FieldAccessorFactory", ".", "class", ")", ";", "// Constructor(Schema schema, Field...
Generates the constructor. The constructor generated has signature {@code (Schema, FieldAccessorFactory)}.
[ "Generates", "the", "constructor", ".", "The", "constructor", "generated", "has", "signature", "{" ]
train
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-yarn/src/main/java/co/cask/tigon/internal/io/DatumWriterGenerator.java#L180-L228
aws/aws-sdk-java
aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/TransactionWriteRequest.java
TransactionWriteRequest.addConditionCheck
public TransactionWriteRequest addConditionCheck(Object key, DynamoDBTransactionWriteExpression transactionWriteExpression, ReturnValuesOnConditionCheckFailure returnValuesOnConditionCheckFailure) { transactionWriteOperations.add(new TransactionWriteOperation(key, TransactionWriteOperationType.ConditionCheck, transactionWriteExpression, returnValuesOnConditionCheckFailure)); return this; }
java
public TransactionWriteRequest addConditionCheck(Object key, DynamoDBTransactionWriteExpression transactionWriteExpression, ReturnValuesOnConditionCheckFailure returnValuesOnConditionCheckFailure) { transactionWriteOperations.add(new TransactionWriteOperation(key, TransactionWriteOperationType.ConditionCheck, transactionWriteExpression, returnValuesOnConditionCheckFailure)); return this; }
[ "public", "TransactionWriteRequest", "addConditionCheck", "(", "Object", "key", ",", "DynamoDBTransactionWriteExpression", "transactionWriteExpression", ",", "ReturnValuesOnConditionCheckFailure", "returnValuesOnConditionCheckFailure", ")", "{", "transactionWriteOperations", ".", "ad...
Adds conditionCheck operation (to be executed on the object represented by key) to the list of transaction write operations. transactionWriteExpression is used to condition check on the object represented by key. returnValuesOnConditionCheckFailure specifies which attributes values (of existing item) should be returned if condition check fails.
[ "Adds", "conditionCheck", "operation", "(", "to", "be", "executed", "on", "the", "object", "represented", "by", "key", ")", "to", "the", "list", "of", "transaction", "write", "operations", ".", "transactionWriteExpression", "is", "used", "to", "condition", "chec...
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/TransactionWriteRequest.java#L141-L146
spotbugs/spotbugs
spotbugs/src/main/java/edu/umd/cs/findbugs/BugInstance.java
BugInstance.addSourceLine
@Nonnull public BugInstance addSourceLine(ClassContext classContext, PreorderVisitor visitor, int pc) { SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(classContext, visitor, pc); if (sourceLineAnnotation != null) { add(sourceLineAnnotation); } return this; }
java
@Nonnull public BugInstance addSourceLine(ClassContext classContext, PreorderVisitor visitor, int pc) { SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(classContext, visitor, pc); if (sourceLineAnnotation != null) { add(sourceLineAnnotation); } return this; }
[ "@", "Nonnull", "public", "BugInstance", "addSourceLine", "(", "ClassContext", "classContext", ",", "PreorderVisitor", "visitor", ",", "int", "pc", ")", "{", "SourceLineAnnotation", "sourceLineAnnotation", "=", "SourceLineAnnotation", ".", "fromVisitedInstruction", "(", ...
Add a source line annotation for instruction whose PC is given in the method that the given visitor is currently visiting. Note that if the method does not have line number information, then no source line annotation will be added. @param classContext the ClassContext @param visitor a PreorderVisitor that is currently visiting the method @param pc bytecode offset of the instruction @return this object
[ "Add", "a", "source", "line", "annotation", "for", "instruction", "whose", "PC", "is", "given", "in", "the", "method", "that", "the", "given", "visitor", "is", "currently", "visiting", ".", "Note", "that", "if", "the", "method", "does", "not", "have", "lin...
train
https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/BugInstance.java#L1631-L1638
Mozu/mozu-java
mozu-java-core/src/main/java/com/mozu/api/urls/commerce/orders/DigitalPackageUrl.java
DigitalPackageUrl.getDigitalPackageUrl
public static MozuUrl getDigitalPackageUrl(String digitalPackageId, String orderId, String responseFields) { UrlFormatter formatter = new UrlFormatter("/api/commerce/orders/{orderId}/digitalpackages/{digitalPackageId}?responseFields={responseFields}"); formatter.formatUrl("digitalPackageId", digitalPackageId); formatter.formatUrl("orderId", orderId); formatter.formatUrl("responseFields", responseFields); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
java
public static MozuUrl getDigitalPackageUrl(String digitalPackageId, String orderId, String responseFields) { UrlFormatter formatter = new UrlFormatter("/api/commerce/orders/{orderId}/digitalpackages/{digitalPackageId}?responseFields={responseFields}"); formatter.formatUrl("digitalPackageId", digitalPackageId); formatter.formatUrl("orderId", orderId); formatter.formatUrl("responseFields", responseFields); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
[ "public", "static", "MozuUrl", "getDigitalPackageUrl", "(", "String", "digitalPackageId", ",", "String", "orderId", ",", "String", "responseFields", ")", "{", "UrlFormatter", "formatter", "=", "new", "UrlFormatter", "(", "\"/api/commerce/orders/{orderId}/digitalpackages/{di...
Get Resource Url for GetDigitalPackage @param digitalPackageId This parameter supplies package ID to get fulfillment actions for the digital package. @param orderId Unique identifier of the order. @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss. @return String Resource Url
[ "Get", "Resource", "Url", "for", "GetDigitalPackage" ]
train
https://github.com/Mozu/mozu-java/blob/5beadde73601a859f845e3e2fc1077b39c8bea83/mozu-java-core/src/main/java/com/mozu/api/urls/commerce/orders/DigitalPackageUrl.java#L37-L44
Azure/azure-sdk-for-java
policy/resource-manager/v2016_12_01/src/main/java/com/microsoft/azure/management/policy/v2016_12_01/implementation/PolicyDefinitionsInner.java
PolicyDefinitionsInner.createOrUpdateAtManagementGroupAsync
public Observable<PolicyDefinitionInner> createOrUpdateAtManagementGroupAsync(String policyDefinitionName, String managementGroupId, PolicyDefinitionInner parameters) { return createOrUpdateAtManagementGroupWithServiceResponseAsync(policyDefinitionName, managementGroupId, parameters).map(new Func1<ServiceResponse<PolicyDefinitionInner>, PolicyDefinitionInner>() { @Override public PolicyDefinitionInner call(ServiceResponse<PolicyDefinitionInner> response) { return response.body(); } }); }
java
public Observable<PolicyDefinitionInner> createOrUpdateAtManagementGroupAsync(String policyDefinitionName, String managementGroupId, PolicyDefinitionInner parameters) { return createOrUpdateAtManagementGroupWithServiceResponseAsync(policyDefinitionName, managementGroupId, parameters).map(new Func1<ServiceResponse<PolicyDefinitionInner>, PolicyDefinitionInner>() { @Override public PolicyDefinitionInner call(ServiceResponse<PolicyDefinitionInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "PolicyDefinitionInner", ">", "createOrUpdateAtManagementGroupAsync", "(", "String", "policyDefinitionName", ",", "String", "managementGroupId", ",", "PolicyDefinitionInner", "parameters", ")", "{", "return", "createOrUpdateAtManagementGroupWithServic...
Creates or updates a policy definition at management group level. @param policyDefinitionName The name of the policy definition to create. @param managementGroupId The ID of the management group. @param parameters The policy definition properties. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PolicyDefinitionInner object
[ "Creates", "or", "updates", "a", "policy", "definition", "at", "management", "group", "level", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/policy/resource-manager/v2016_12_01/src/main/java/com/microsoft/azure/management/policy/v2016_12_01/implementation/PolicyDefinitionsInner.java#L477-L484
Activiti/Activiti
activiti-engine/src/main/java/org/activiti/engine/impl/util/BitMaskUtil.java
BitMaskUtil.isBitOn
public static boolean isBitOn(int value, int bitNumber) { if (bitNumber <= 0 || bitNumber > 8) { throw new IllegalArgumentException("Only bits 1 through 8 are supported"); } return ((value & MASKS[bitNumber - 1]) == MASKS[bitNumber - 1]); }
java
public static boolean isBitOn(int value, int bitNumber) { if (bitNumber <= 0 || bitNumber > 8) { throw new IllegalArgumentException("Only bits 1 through 8 are supported"); } return ((value & MASKS[bitNumber - 1]) == MASKS[bitNumber - 1]); }
[ "public", "static", "boolean", "isBitOn", "(", "int", "value", ",", "int", "bitNumber", ")", "{", "if", "(", "bitNumber", "<=", "0", "||", "bitNumber", ">", "8", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Only bits 1 through 8 are supported\""...
Check if the bit is set to '1' @param value integer to check bit @param number of bit to check (right first bit starting at 1)
[ "Check", "if", "the", "bit", "is", "set", "to", "1" ]
train
https://github.com/Activiti/Activiti/blob/82e2b2cd2083b2f734ca0efc7815389c0f2517d9/activiti-engine/src/main/java/org/activiti/engine/impl/util/BitMaskUtil.java#L81-L87
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/concurrent/ThreadLocalRandom.java
ThreadLocalRandom.internalNextInt
final int internalNextInt(int origin, int bound) { int r = mix32(nextSeed()); if (origin < bound) { int n = bound - origin, m = n - 1; if ((n & m) == 0) r = (r & m) + origin; else if (n > 0) { for (int u = r >>> 1; u + m - (r = u % n) < 0; u = mix32(nextSeed()) >>> 1) ; r += origin; } else { while (r < origin || r >= bound) r = mix32(nextSeed()); } } return r; }
java
final int internalNextInt(int origin, int bound) { int r = mix32(nextSeed()); if (origin < bound) { int n = bound - origin, m = n - 1; if ((n & m) == 0) r = (r & m) + origin; else if (n > 0) { for (int u = r >>> 1; u + m - (r = u % n) < 0; u = mix32(nextSeed()) >>> 1) ; r += origin; } else { while (r < origin || r >= bound) r = mix32(nextSeed()); } } return r; }
[ "final", "int", "internalNextInt", "(", "int", "origin", ",", "int", "bound", ")", "{", "int", "r", "=", "mix32", "(", "nextSeed", "(", ")", ")", ";", "if", "(", "origin", "<", "bound", ")", "{", "int", "n", "=", "bound", "-", "origin", ",", "m",...
The form of nextInt used by IntStream Spliterators. Exactly the same as long version, except for types. @param origin the least value, unless greater than bound @param bound the upper bound (exclusive), must not equal origin @return a pseudorandom value
[ "The", "form", "of", "nextInt", "used", "by", "IntStream", "Spliterators", ".", "Exactly", "the", "same", "as", "long", "version", "except", "for", "types", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/concurrent/ThreadLocalRandom.java#L239-L258
raydac/java-binary-block-parser
jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPUtils.java
JBBPUtils.packInt
public static int packInt(final byte[] array, final JBBPIntCounter position, final int value) { if ((value & 0xFFFFFF80) == 0) { array[position.getAndIncrement()] = (byte) value; return 1; } else if ((value & 0xFFFF0000) == 0) { array[position.getAndIncrement()] = (byte) 0x80; array[position.getAndIncrement()] = (byte) (value >>> 8); array[position.getAndIncrement()] = (byte) value; return 3; } array[position.getAndIncrement()] = (byte) 0x81; array[position.getAndIncrement()] = (byte) (value >>> 24); array[position.getAndIncrement()] = (byte) (value >>> 16); array[position.getAndIncrement()] = (byte) (value >>> 8); array[position.getAndIncrement()] = (byte) value; return 5; }
java
public static int packInt(final byte[] array, final JBBPIntCounter position, final int value) { if ((value & 0xFFFFFF80) == 0) { array[position.getAndIncrement()] = (byte) value; return 1; } else if ((value & 0xFFFF0000) == 0) { array[position.getAndIncrement()] = (byte) 0x80; array[position.getAndIncrement()] = (byte) (value >>> 8); array[position.getAndIncrement()] = (byte) value; return 3; } array[position.getAndIncrement()] = (byte) 0x81; array[position.getAndIncrement()] = (byte) (value >>> 24); array[position.getAndIncrement()] = (byte) (value >>> 16); array[position.getAndIncrement()] = (byte) (value >>> 8); array[position.getAndIncrement()] = (byte) value; return 5; }
[ "public", "static", "int", "packInt", "(", "final", "byte", "[", "]", "array", ",", "final", "JBBPIntCounter", "position", ",", "final", "int", "value", ")", "{", "if", "(", "(", "value", "&", "0xFFFFFF80", ")", "==", "0", ")", "{", "array", "[", "po...
Pack an integer value and save that into a byte array since defined position. @param array a byte array where to write the packed data, it must not be null @param position the position of the first byte of the packed value, it must not be null @param value the value to be packed @return number of bytes written into the array, the position will be increased
[ "Pack", "an", "integer", "value", "and", "save", "that", "into", "a", "byte", "array", "since", "defined", "position", "." ]
train
https://github.com/raydac/java-binary-block-parser/blob/6d98abcab01e0c72d525ebcc9e7b694f9ce49f5b/jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPUtils.java#L127-L143
apache/flink
flink-runtime/src/main/java/org/apache/flink/runtime/jobgraph/JobVertex.java
JobVertex.getInvokableClass
public Class<? extends AbstractInvokable> getInvokableClass(ClassLoader cl) { if (cl == null) { throw new NullPointerException("The classloader must not be null."); } if (invokableClassName == null) { return null; } try { return Class.forName(invokableClassName, true, cl).asSubclass(AbstractInvokable.class); } catch (ClassNotFoundException e) { throw new RuntimeException("The user-code class could not be resolved.", e); } catch (ClassCastException e) { throw new RuntimeException("The user-code class is no subclass of " + AbstractInvokable.class.getName(), e); } }
java
public Class<? extends AbstractInvokable> getInvokableClass(ClassLoader cl) { if (cl == null) { throw new NullPointerException("The classloader must not be null."); } if (invokableClassName == null) { return null; } try { return Class.forName(invokableClassName, true, cl).asSubclass(AbstractInvokable.class); } catch (ClassNotFoundException e) { throw new RuntimeException("The user-code class could not be resolved.", e); } catch (ClassCastException e) { throw new RuntimeException("The user-code class is no subclass of " + AbstractInvokable.class.getName(), e); } }
[ "public", "Class", "<", "?", "extends", "AbstractInvokable", ">", "getInvokableClass", "(", "ClassLoader", "cl", ")", "{", "if", "(", "cl", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"The classloader must not be null.\"", ")", ";", "}...
Returns the invokable class which represents the task of this vertex @param cl The classloader used to resolve user-defined classes @return The invokable class, <code>null</code> if it is not set
[ "Returns", "the", "invokable", "class", "which", "represents", "the", "task", "of", "this", "vertex" ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/jobgraph/JobVertex.java#L257-L274
gallandarakhneorg/afc
core/text/src/main/java/org/arakhne/afc/text/TextUtil.java
TextUtil.join
@Pure public static <T> String join(char leftSeparator, char rightSeparator, @SuppressWarnings("unchecked") T... strs) { final StringBuilder buffer = new StringBuilder(); for (final Object s : strs) { buffer.append(leftSeparator); if (s != null) { buffer.append(s.toString()); } buffer.append(rightSeparator); } return buffer.toString(); }
java
@Pure public static <T> String join(char leftSeparator, char rightSeparator, @SuppressWarnings("unchecked") T... strs) { final StringBuilder buffer = new StringBuilder(); for (final Object s : strs) { buffer.append(leftSeparator); if (s != null) { buffer.append(s.toString()); } buffer.append(rightSeparator); } return buffer.toString(); }
[ "@", "Pure", "public", "static", "<", "T", ">", "String", "join", "(", "char", "leftSeparator", ",", "char", "rightSeparator", ",", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "T", "...", "strs", ")", "{", "final", "StringBuilder", "buffer", "=", "...
Merge the given strings with to separators. The separators are used to delimit the groups of characters. <p>Examples: <ul> <li><code>merge('{','}',"a","b","cd")</code> returns the string <code>"{a}{b}{cd}"</code></li> <li><code>merge('{','}',"a{bcd")</code> returns the string <code>"{a{bcd}"</code></li> </ul> @param <T> is the type of the parameters. @param leftSeparator is the left separator to use. @param rightSeparator is the right separator to use. @param strs is the array of strings. @return the string with merged strings. @since 4.0
[ "Merge", "the", "given", "strings", "with", "to", "separators", ".", "The", "separators", "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#L889-L900
looly/hutool
hutool-core/src/main/java/cn/hutool/core/img/ImgUtil.java
ImgUtil.rotate
public static void rotate(Image image, int degree, OutputStream out) throws IORuntimeException { writeJpg(rotate(image, degree), getImageOutputStream(out)); }
java
public static void rotate(Image image, int degree, OutputStream out) throws IORuntimeException { writeJpg(rotate(image, degree), getImageOutputStream(out)); }
[ "public", "static", "void", "rotate", "(", "Image", "image", ",", "int", "degree", ",", "OutputStream", "out", ")", "throws", "IORuntimeException", "{", "writeJpg", "(", "rotate", "(", "image", ",", "degree", ")", ",", "getImageOutputStream", "(", "out", ")"...
旋转图片为指定角度<br> 此方法不会关闭输出流 @param image 目标图像 @param degree 旋转角度 @param out 输出流 @since 3.2.2 @throws IORuntimeException IO异常
[ "旋转图片为指定角度<br", ">", "此方法不会关闭输出流" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/img/ImgUtil.java#L1030-L1032
alkacon/opencms-core
src/org/opencms/xml/content/CmsXmlContentPropertyHelper.java
CmsXmlContentPropertyHelper.getIdForUri
public static CmsUUID getIdForUri(CmsObject cms, String uri) throws CmsException { return cms.readResource(uri).getStructureId(); }
java
public static CmsUUID getIdForUri(CmsObject cms, String uri) throws CmsException { return cms.readResource(uri).getStructureId(); }
[ "public", "static", "CmsUUID", "getIdForUri", "(", "CmsObject", "cms", ",", "String", "uri", ")", "throws", "CmsException", "{", "return", "cms", ".", "readResource", "(", "uri", ")", ".", "getStructureId", "(", ")", ";", "}" ]
Looks up an URI in the sitemap and returns either a sitemap entry id (if the URI is a sitemap URI) or the structure id of a resource (if the URI is a VFS path).<p> @param cms the current CMS context @param uri the URI to look up @return a sitemap entry id or a structure id @throws CmsException if something goes wrong
[ "Looks", "up", "an", "URI", "in", "the", "sitemap", "and", "returns", "either", "a", "sitemap", "entry", "id", "(", "if", "the", "URI", "is", "a", "sitemap", "URI", ")", "or", "the", "structure", "id", "of", "a", "resource", "(", "if", "the", "URI", ...
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/xml/content/CmsXmlContentPropertyHelper.java#L198-L201
thymeleaf/thymeleaf-spring
thymeleaf-spring4/src/main/java/org/thymeleaf/spring4/processor/SpringErrorClassTagProcessor.java
SpringErrorClassTagProcessor.computeBindStatus
private static BindStatus computeBindStatus(final IExpressionContext context, final IProcessableElementTag tag) { /* * First, try to obtain an already-existing BindStatus resulting from the execution of a th:field attribute * in the same element. */ final BindStatus bindStatus = (BindStatus) context.getVariable(SpringContextVariableNames.SPRING_FIELD_BIND_STATUS); if (bindStatus != null) { return bindStatus; } /* * It seems no th:field was executed on the same element, so we must rely on the "name" attribute (probably * specified by hand or by a th:name). No th:field was executed, so no BindStatus available -- we'll have to * build it ourselves. */ final String fieldName = tag.getAttributeValue("name"); if (StringUtils.isEmptyOrWhitespace(fieldName)) { return null; } final VariableExpression boundExpression = (VariableExpression) context.getVariable(SpringContextVariableNames.SPRING_BOUND_OBJECT_EXPRESSION); if (boundExpression == null) { // No bound expression, so just use the field name return FieldUtils.getBindStatusFromParsedExpression(context, false, fieldName); } // Bound object and field object names might intersect (e.g. th:object="a.b", name="b.c"), and we must compute // the real 'bindable' name ("a.b.c") by only using the first token in the bound object name, appending the // rest of the field name: "a" + "b.c" -> "a.b.c" final String boundExpressionStr = boundExpression.getExpression(); final String computedFieldName; if (boundExpressionStr.indexOf('.') == -1) { computedFieldName = boundExpressionStr + '.' + fieldName; // we append because we will use no form root afterwards } else { computedFieldName = boundExpressionStr.substring(0, boundExpressionStr.indexOf('.')) + '.' + fieldName; } // We set "useRoot" to false because we have already computed that part return FieldUtils.getBindStatusFromParsedExpression(context, false, computedFieldName); }
java
private static BindStatus computeBindStatus(final IExpressionContext context, final IProcessableElementTag tag) { /* * First, try to obtain an already-existing BindStatus resulting from the execution of a th:field attribute * in the same element. */ final BindStatus bindStatus = (BindStatus) context.getVariable(SpringContextVariableNames.SPRING_FIELD_BIND_STATUS); if (bindStatus != null) { return bindStatus; } /* * It seems no th:field was executed on the same element, so we must rely on the "name" attribute (probably * specified by hand or by a th:name). No th:field was executed, so no BindStatus available -- we'll have to * build it ourselves. */ final String fieldName = tag.getAttributeValue("name"); if (StringUtils.isEmptyOrWhitespace(fieldName)) { return null; } final VariableExpression boundExpression = (VariableExpression) context.getVariable(SpringContextVariableNames.SPRING_BOUND_OBJECT_EXPRESSION); if (boundExpression == null) { // No bound expression, so just use the field name return FieldUtils.getBindStatusFromParsedExpression(context, false, fieldName); } // Bound object and field object names might intersect (e.g. th:object="a.b", name="b.c"), and we must compute // the real 'bindable' name ("a.b.c") by only using the first token in the bound object name, appending the // rest of the field name: "a" + "b.c" -> "a.b.c" final String boundExpressionStr = boundExpression.getExpression(); final String computedFieldName; if (boundExpressionStr.indexOf('.') == -1) { computedFieldName = boundExpressionStr + '.' + fieldName; // we append because we will use no form root afterwards } else { computedFieldName = boundExpressionStr.substring(0, boundExpressionStr.indexOf('.')) + '.' + fieldName; } // We set "useRoot" to false because we have already computed that part return FieldUtils.getBindStatusFromParsedExpression(context, false, computedFieldName); }
[ "private", "static", "BindStatus", "computeBindStatus", "(", "final", "IExpressionContext", "context", ",", "final", "IProcessableElementTag", "tag", ")", "{", "/*\n * First, try to obtain an already-existing BindStatus resulting from the execution of a th:field attribute\n ...
/* There are two scenarios for a th:errorclass to appear in: one is in an element for which a th:field has already been executed, in which case we already have a BindStatus to check for errors; and the other one is an element for which a th:field has not been executed, but which should have a "name" attribute (either directly or as the result of executing a th:name) -- in this case, we'll have to build the BuildStatus ourselves.
[ "/", "*", "There", "are", "two", "scenarios", "for", "a", "th", ":", "errorclass", "to", "appear", "in", ":", "one", "is", "in", "an", "element", "for", "which", "a", "th", ":", "field", "has", "already", "been", "executed", "in", "which", "case", "w...
train
https://github.com/thymeleaf/thymeleaf-spring/blob/9aa15a19017a0938e57646e3deefb8a90ab78dcb/thymeleaf-spring4/src/main/java/org/thymeleaf/spring4/processor/SpringErrorClassTagProcessor.java#L145-L189
apache/incubator-gobblin
gobblin-aws/src/main/java/org/apache/gobblin/aws/GobblinAWSClusterLauncher.java
GobblinAWSClusterLauncher.setupGobblinCluster
@VisibleForTesting String setupGobblinCluster() throws IOException { final String uuid = UUID.randomUUID().toString(); // Create security group // TODO: Make security group restrictive final String securityGroupName = "GobblinSecurityGroup_" + uuid; this.awsSdkClient.createSecurityGroup(securityGroupName, "Gobblin cluster security group"); this.awsSdkClient.addPermissionsToSecurityGroup(securityGroupName, "0.0.0.0/0", "tcp", 0, 65535); // Create key value pair final String keyName = "GobblinKey_" + uuid; final String material = this.awsSdkClient.createKeyValuePair(keyName); LOGGER.debug("Material is: " + material); FileUtils.writeStringToFile(new File(keyName + ".pem"), material); // Get all availability zones in the region. Currently, we will only use first final List<AvailabilityZone> availabilityZones = this.awsSdkClient.getAvailabilityZones(); // Launch Cluster Master final String clusterId = launchClusterMaster(uuid, keyName, securityGroupName, availabilityZones.get(0)); // Launch WorkUnit runners launchWorkUnitRunners(uuid, keyName, securityGroupName, availabilityZones.get(0)); return clusterId; }
java
@VisibleForTesting String setupGobblinCluster() throws IOException { final String uuid = UUID.randomUUID().toString(); // Create security group // TODO: Make security group restrictive final String securityGroupName = "GobblinSecurityGroup_" + uuid; this.awsSdkClient.createSecurityGroup(securityGroupName, "Gobblin cluster security group"); this.awsSdkClient.addPermissionsToSecurityGroup(securityGroupName, "0.0.0.0/0", "tcp", 0, 65535); // Create key value pair final String keyName = "GobblinKey_" + uuid; final String material = this.awsSdkClient.createKeyValuePair(keyName); LOGGER.debug("Material is: " + material); FileUtils.writeStringToFile(new File(keyName + ".pem"), material); // Get all availability zones in the region. Currently, we will only use first final List<AvailabilityZone> availabilityZones = this.awsSdkClient.getAvailabilityZones(); // Launch Cluster Master final String clusterId = launchClusterMaster(uuid, keyName, securityGroupName, availabilityZones.get(0)); // Launch WorkUnit runners launchWorkUnitRunners(uuid, keyName, securityGroupName, availabilityZones.get(0)); return clusterId; }
[ "@", "VisibleForTesting", "String", "setupGobblinCluster", "(", ")", "throws", "IOException", "{", "final", "String", "uuid", "=", "UUID", ".", "randomUUID", "(", ")", ".", "toString", "(", ")", ";", "// Create security group", "// TODO: Make security group restrictiv...
Setup the Gobblin AWS cluster. @throws IOException If there's anything wrong setting up the AWS cluster
[ "Setup", "the", "Gobblin", "AWS", "cluster", "." ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-aws/src/main/java/org/apache/gobblin/aws/GobblinAWSClusterLauncher.java#L406-L437
trustathsh/ifmapj
src/main/java/de/hshannover/f4/trust/ifmapj/messages/Requests.java
Requests.createPublishNotify
public static PublishNotify createPublishNotify(Identifier i1, Document md) { return createPublishNotify(i1, null, md); }
java
public static PublishNotify createPublishNotify(Identifier i1, Document md) { return createPublishNotify(i1, null, md); }
[ "public", "static", "PublishNotify", "createPublishNotify", "(", "Identifier", "i1", ",", "Document", "md", ")", "{", "return", "createPublishNotify", "(", "i1", ",", "null", ",", "md", ")", ";", "}" ]
Create a new {@link PublishNotify} instance that is used to publish metadata to an {@link Identifier}. @param i1 the {@link Identifier} to which the given metadata is published to @param md the metadata that shall be published @return the new {@link PublishNotify} instance
[ "Create", "a", "new", "{", "@link", "PublishNotify", "}", "instance", "that", "is", "used", "to", "publish", "metadata", "to", "an", "{", "@link", "Identifier", "}", "." ]
train
https://github.com/trustathsh/ifmapj/blob/44ece9e95a3d2a1b7019573ba6178598a6cbdaa3/src/main/java/de/hshannover/f4/trust/ifmapj/messages/Requests.java#L470-L472
Azure/azure-sdk-for-java
containerregistry/resource-manager/v2018_02_01_preview/src/main/java/com/microsoft/azure/management/containerregistry/v2018_02_01_preview/implementation/RegistriesInner.java
RegistriesInner.getBuildSourceUploadUrl
public SourceUploadDefinitionInner getBuildSourceUploadUrl(String resourceGroupName, String registryName) { return getBuildSourceUploadUrlWithServiceResponseAsync(resourceGroupName, registryName).toBlocking().single().body(); }
java
public SourceUploadDefinitionInner getBuildSourceUploadUrl(String resourceGroupName, String registryName) { return getBuildSourceUploadUrlWithServiceResponseAsync(resourceGroupName, registryName).toBlocking().single().body(); }
[ "public", "SourceUploadDefinitionInner", "getBuildSourceUploadUrl", "(", "String", "resourceGroupName", ",", "String", "registryName", ")", "{", "return", "getBuildSourceUploadUrlWithServiceResponseAsync", "(", "resourceGroupName", ",", "registryName", ")", ".", "toBlocking", ...
Get the upload location for the user to be able to upload the source. @param resourceGroupName The name of the resource group to which the container registry belongs. @param registryName The name of the container registry. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the SourceUploadDefinitionInner object if successful.
[ "Get", "the", "upload", "location", "for", "the", "user", "to", "be", "able", "to", "upload", "the", "source", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/containerregistry/resource-manager/v2018_02_01_preview/src/main/java/com/microsoft/azure/management/containerregistry/v2018_02_01_preview/implementation/RegistriesInner.java#L1894-L1896
geomajas/geomajas-project-client-gwt2
impl/src/main/java/org/geomajas/gwt2/client/service/JsonService.java
JsonService.isNullObject
public static boolean isNullObject(JSONObject jsonObject, String key) throws JSONException { checkArguments(jsonObject, key); JSONValue value = jsonObject.get(key); boolean isNull = false; if (value == null || value.isNull() != null) { isNull = true; } return isNull; }
java
public static boolean isNullObject(JSONObject jsonObject, String key) throws JSONException { checkArguments(jsonObject, key); JSONValue value = jsonObject.get(key); boolean isNull = false; if (value == null || value.isNull() != null) { isNull = true; } return isNull; }
[ "public", "static", "boolean", "isNullObject", "(", "JSONObject", "jsonObject", ",", "String", "key", ")", "throws", "JSONException", "{", "checkArguments", "(", "jsonObject", ",", "key", ")", ";", "JSONValue", "value", "=", "jsonObject", ".", "get", "(", "key...
checks if a certain object value is null. @param jsonObject The object to get the key value from. @param key The name of the key to search the value for. @throws JSONException In case something went wrong while parsing.
[ "checks", "if", "a", "certain", "object", "value", "is", "null", "." ]
train
https://github.com/geomajas/geomajas-project-client-gwt2/blob/bd8d7904e861fa80522eed7b83c4ea99844180c7/impl/src/main/java/org/geomajas/gwt2/client/service/JsonService.java#L358-L367
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/util/NetworkUtils.java
NetworkUtils.setLearningRate
public static void setLearningRate(MultiLayerNetwork net, ISchedule newLrSchedule) { setLearningRate(net, Double.NaN, newLrSchedule); }
java
public static void setLearningRate(MultiLayerNetwork net, ISchedule newLrSchedule) { setLearningRate(net, Double.NaN, newLrSchedule); }
[ "public", "static", "void", "setLearningRate", "(", "MultiLayerNetwork", "net", ",", "ISchedule", "newLrSchedule", ")", "{", "setLearningRate", "(", "net", ",", "Double", ".", "NaN", ",", "newLrSchedule", ")", ";", "}" ]
Set the learning rate schedule for all layers in the network to the specified schedule. This schedule will replace any/all existing schedules, and also any fixed learning rate values.<br> Note that the iteration/epoch counts will <i>not</i> be reset. Use {@link MultiLayerConfiguration#setIterationCount(int)} and {@link MultiLayerConfiguration#setEpochCount(int)} if this is required @param newLrSchedule New learning rate schedule for all layers
[ "Set", "the", "learning", "rate", "schedule", "for", "all", "layers", "in", "the", "network", "to", "the", "specified", "schedule", ".", "This", "schedule", "will", "replace", "any", "/", "all", "existing", "schedules", "and", "also", "any", "fixed", "learni...
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/util/NetworkUtils.java#L161-L163
alkacon/opencms-core
src/org/opencms/i18n/CmsEncoder.java
CmsEncoder.createString
public static String createString(byte[] bytes, String encoding) { String enc = encoding.intern(); if (enc != OpenCms.getSystemInfo().getDefaultEncoding()) { enc = lookupEncoding(enc, null); } if (enc != null) { try { return new String(bytes, enc); } catch (UnsupportedEncodingException e) { // this can _never_ happen since the charset was looked up first } } else { if (LOG.isWarnEnabled()) { LOG.warn(Messages.get().getBundle().key(Messages.ERR_UNSUPPORTED_VM_ENCODING_1, encoding)); } enc = OpenCms.getSystemInfo().getDefaultEncoding(); try { return new String(bytes, enc); } catch (UnsupportedEncodingException e) { // this can also _never_ happen since the default encoding is always valid } } // this code is unreachable in practice LOG.error(Messages.get().getBundle().key(Messages.ERR_ENCODING_ISSUES_1, encoding)); return null; }
java
public static String createString(byte[] bytes, String encoding) { String enc = encoding.intern(); if (enc != OpenCms.getSystemInfo().getDefaultEncoding()) { enc = lookupEncoding(enc, null); } if (enc != null) { try { return new String(bytes, enc); } catch (UnsupportedEncodingException e) { // this can _never_ happen since the charset was looked up first } } else { if (LOG.isWarnEnabled()) { LOG.warn(Messages.get().getBundle().key(Messages.ERR_UNSUPPORTED_VM_ENCODING_1, encoding)); } enc = OpenCms.getSystemInfo().getDefaultEncoding(); try { return new String(bytes, enc); } catch (UnsupportedEncodingException e) { // this can also _never_ happen since the default encoding is always valid } } // this code is unreachable in practice LOG.error(Messages.get().getBundle().key(Messages.ERR_ENCODING_ISSUES_1, encoding)); return null; }
[ "public", "static", "String", "createString", "(", "byte", "[", "]", "bytes", ",", "String", "encoding", ")", "{", "String", "enc", "=", "encoding", ".", "intern", "(", ")", ";", "if", "(", "enc", "!=", "OpenCms", ".", "getSystemInfo", "(", ")", ".", ...
Creates a String out of a byte array with the specified encoding, falling back to the system default in case the encoding name is not valid.<p> Use this method as a replacement for <code>new String(byte[], encoding)</code> to avoid possible encoding problems.<p> @param bytes the bytes to decode @param encoding the encoding scheme to use for decoding the bytes @return the bytes decoded to a String
[ "Creates", "a", "String", "out", "of", "a", "byte", "array", "with", "the", "specified", "encoding", "falling", "back", "to", "the", "system", "default", "in", "case", "the", "encoding", "name", "is", "not", "valid", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/i18n/CmsEncoder.java#L213-L239
ist-dresden/composum
sling/core/commons/src/main/java/com/composum/sling/core/InheritedValues.java
InheritedValues.findOriginAndValue
public HierarchyScanResult findOriginAndValue(String name, Class<?> type) { Object value; findEntryPoint(); String path = getRelativePath(name); for (Resource parent = entryPoint; parent != null; parent = parent.getParent()) { ValueMap parentProps = parent.adaptTo(ValueMap.class); if (parentProps != null) { value = parentProps.get(path, type); if (value != null) { return new HierarchyScanResult(parent, value); } } if (exitPoint != null && parent.getPath().equals(exitPoint.getPath())) { break; } } return null; }
java
public HierarchyScanResult findOriginAndValue(String name, Class<?> type) { Object value; findEntryPoint(); String path = getRelativePath(name); for (Resource parent = entryPoint; parent != null; parent = parent.getParent()) { ValueMap parentProps = parent.adaptTo(ValueMap.class); if (parentProps != null) { value = parentProps.get(path, type); if (value != null) { return new HierarchyScanResult(parent, value); } } if (exitPoint != null && parent.getPath().equals(exitPoint.getPath())) { break; } } return null; }
[ "public", "HierarchyScanResult", "findOriginAndValue", "(", "String", "name", ",", "Class", "<", "?", ">", "type", ")", "{", "Object", "value", ";", "findEntryPoint", "(", ")", ";", "String", "path", "=", "getRelativePath", "(", "name", ")", ";", "for", "(...
Searches the value along the repositories hierarchy by the entry point and path determined before. @param name the property name or path @param type the expected type of the value @return the value found or <code>null</code> if no such value found in one of the appropriate parent nodes
[ "Searches", "the", "value", "along", "the", "repositories", "hierarchy", "by", "the", "entry", "point", "and", "path", "determined", "before", "." ]
train
https://github.com/ist-dresden/composum/blob/ebc79f559f6022c935240c19102539bdfb1bd1e2/sling/core/commons/src/main/java/com/composum/sling/core/InheritedValues.java#L155-L172
spotbugs/spotbugs
spotbugs/src/main/java/edu/umd/cs/findbugs/Project.java
Project.makeAbsoluteCwdCandidates
private List<String> makeAbsoluteCwdCandidates(String fileName) { List<String> candidates = new ArrayList<>(); boolean hasProtocol = (URLClassPath.getURLProtocol(fileName) != null); if (hasProtocol) { candidates.add(fileName); return candidates; } if (new File(fileName).isAbsolute()) { candidates.add(fileName); return candidates; } for (File currentWorkingDirectory : currentWorkingDirectoryList) { File relativeToCurrent = new File(currentWorkingDirectory, fileName); if (relativeToCurrent.exists()) { candidates.add(relativeToCurrent.toString()); } } if (candidates.isEmpty()) { candidates.add(fileName); } return candidates; }
java
private List<String> makeAbsoluteCwdCandidates(String fileName) { List<String> candidates = new ArrayList<>(); boolean hasProtocol = (URLClassPath.getURLProtocol(fileName) != null); if (hasProtocol) { candidates.add(fileName); return candidates; } if (new File(fileName).isAbsolute()) { candidates.add(fileName); return candidates; } for (File currentWorkingDirectory : currentWorkingDirectoryList) { File relativeToCurrent = new File(currentWorkingDirectory, fileName); if (relativeToCurrent.exists()) { candidates.add(relativeToCurrent.toString()); } } if (candidates.isEmpty()) { candidates.add(fileName); } return candidates; }
[ "private", "List", "<", "String", ">", "makeAbsoluteCwdCandidates", "(", "String", "fileName", ")", "{", "List", "<", "String", ">", "candidates", "=", "new", "ArrayList", "<>", "(", ")", ";", "boolean", "hasProtocol", "=", "(", "URLClassPath", ".", "getURLP...
Make the given filename absolute relative to the current working directory candidates. If the given filename exists in more than one of the working directories, a list of these existing absolute paths is returned. The returned list is guaranteed to be non-empty. The returned paths might exist or not exist and might be relative or absolute. @return A list of at least one candidate path for the given filename.
[ "Make", "the", "given", "filename", "absolute", "relative", "to", "the", "current", "working", "directory", "candidates", "." ]
train
https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/Project.java#L988-L1014
ArcBees/gwtquery
gwtquery-core/src/main/java/com/google/gwt/query/client/plugins/widgets/WidgetsUtils.java
WidgetsUtils.hideAndAfter
public static void hideAndAfter(Element e, Widget widget) { assert e != null && widget != null; if ($(e).widget() != null && $(e).widget().isAttached()) { replaceWidget($(e).widget(), widget, false); } else { detachWidget(widget); hideAndAfter(e, widget.getElement()); attachWidget(widget, getFirstParentWidget(widget)); } }
java
public static void hideAndAfter(Element e, Widget widget) { assert e != null && widget != null; if ($(e).widget() != null && $(e).widget().isAttached()) { replaceWidget($(e).widget(), widget, false); } else { detachWidget(widget); hideAndAfter(e, widget.getElement()); attachWidget(widget, getFirstParentWidget(widget)); } }
[ "public", "static", "void", "hideAndAfter", "(", "Element", "e", ",", "Widget", "widget", ")", "{", "assert", "e", "!=", "null", "&&", "widget", "!=", "null", ";", "if", "(", "$", "(", "e", ")", ".", "widget", "(", ")", "!=", "null", "&&", "$", "...
Append a widget to a dom element, and hide it. Element classes will be copied to the new widget.
[ "Append", "a", "widget", "to", "a", "dom", "element", "and", "hide", "it", ".", "Element", "classes", "will", "be", "copied", "to", "the", "new", "widget", "." ]
train
https://github.com/ArcBees/gwtquery/blob/93e02bc8eb030081061c56134ebee1f585981107/gwtquery-core/src/main/java/com/google/gwt/query/client/plugins/widgets/WidgetsUtils.java#L50-L59
RobotiumTech/robotium
robotium-solo/src/main/java/com/robotium/solo/Solo.java
Solo.waitForText
public boolean waitForText(String text, int minimumNumberOfMatches, long timeout, boolean scroll, boolean onlyVisible) { if(config.commandLogging){ Log.d(config.commandLoggingTag, "waitForText(\""+text+"\", "+minimumNumberOfMatches+", "+timeout+", "+scroll+", "+onlyVisible+")"); } return (waiter.waitForText(text, minimumNumberOfMatches, timeout, scroll, onlyVisible, true) != null); }
java
public boolean waitForText(String text, int minimumNumberOfMatches, long timeout, boolean scroll, boolean onlyVisible) { if(config.commandLogging){ Log.d(config.commandLoggingTag, "waitForText(\""+text+"\", "+minimumNumberOfMatches+", "+timeout+", "+scroll+", "+onlyVisible+")"); } return (waiter.waitForText(text, minimumNumberOfMatches, timeout, scroll, onlyVisible, true) != null); }
[ "public", "boolean", "waitForText", "(", "String", "text", ",", "int", "minimumNumberOfMatches", ",", "long", "timeout", ",", "boolean", "scroll", ",", "boolean", "onlyVisible", ")", "{", "if", "(", "config", ".", "commandLogging", ")", "{", "Log", ".", "d",...
Waits for the specified text to appear. @param text the text to wait for, specified as a regular expression @param minimumNumberOfMatches the minimum number of matches that are expected to be found. {@code 0} means any number of matches @param timeout the the amount of time in milliseconds to wait @param scroll {@code true} if scrolling should be performed @param onlyVisible {@code true} if only visible text views should be waited for @return {@code true} if text is displayed and {@code false} if it is not displayed before the timeout
[ "Waits", "for", "the", "specified", "text", "to", "appear", "." ]
train
https://github.com/RobotiumTech/robotium/blob/75e567c38f26a6a87dc8bef90b3886a20e28d291/robotium-solo/src/main/java/com/robotium/solo/Solo.java#L436-L442
Azure/azure-sdk-for-java
iothub/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/iothub/v2018_04_01/implementation/CertificatesInner.java
CertificatesInner.generateVerificationCode
public CertificateWithNonceDescriptionInner generateVerificationCode(String resourceGroupName, String resourceName, String certificateName, String ifMatch) { return generateVerificationCodeWithServiceResponseAsync(resourceGroupName, resourceName, certificateName, ifMatch).toBlocking().single().body(); }
java
public CertificateWithNonceDescriptionInner generateVerificationCode(String resourceGroupName, String resourceName, String certificateName, String ifMatch) { return generateVerificationCodeWithServiceResponseAsync(resourceGroupName, resourceName, certificateName, ifMatch).toBlocking().single().body(); }
[ "public", "CertificateWithNonceDescriptionInner", "generateVerificationCode", "(", "String", "resourceGroupName", ",", "String", "resourceName", ",", "String", "certificateName", ",", "String", "ifMatch", ")", "{", "return", "generateVerificationCodeWithServiceResponseAsync", "...
Generate verification code for proof of possession flow. Generates verification code for proof of possession flow. The verification code will be used to generate a leaf certificate. @param resourceGroupName The name of the resource group that contains the IoT hub. @param resourceName The name of the IoT hub. @param certificateName The name of the certificate @param ifMatch ETag of the Certificate. @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorDetailsException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the CertificateWithNonceDescriptionInner object if successful.
[ "Generate", "verification", "code", "for", "proof", "of", "possession", "flow", ".", "Generates", "verification", "code", "for", "proof", "of", "possession", "flow", ".", "The", "verification", "code", "will", "be", "used", "to", "generate", "a", "leaf", "cert...
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/iothub/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/iothub/v2018_04_01/implementation/CertificatesInner.java#L592-L594
sarl/sarl
contribs/io.sarl.pythongenerator/io.sarl.pythongenerator.generator/src/io/sarl/pythongenerator/generator/generator/PyGenerator.java
PyGenerator._before
protected void _before(SarlCapacityUses uses, IExtraLanguageGeneratorContext context) { // Rename the function in order to produce the good features at the calls. for (final JvmTypeReference capacity : uses.getCapacities()) { final JvmType type = capacity.getType(); if (type instanceof JvmDeclaredType) { computeCapacityFunctionMarkers((JvmDeclaredType) type); } } }
java
protected void _before(SarlCapacityUses uses, IExtraLanguageGeneratorContext context) { // Rename the function in order to produce the good features at the calls. for (final JvmTypeReference capacity : uses.getCapacities()) { final JvmType type = capacity.getType(); if (type instanceof JvmDeclaredType) { computeCapacityFunctionMarkers((JvmDeclaredType) type); } } }
[ "protected", "void", "_before", "(", "SarlCapacityUses", "uses", ",", "IExtraLanguageGeneratorContext", "context", ")", "{", "// Rename the function in order to produce the good features at the calls.", "for", "(", "final", "JvmTypeReference", "capacity", ":", "uses", ".", "g...
Mark the functions of the used capacities in order to have a valid feature call within the code. @param uses the capacity uses. @param context the context.
[ "Mark", "the", "functions", "of", "the", "used", "capacities", "in", "order", "to", "have", "a", "valid", "feature", "call", "within", "the", "code", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/contribs/io.sarl.pythongenerator/io.sarl.pythongenerator.generator/src/io/sarl/pythongenerator/generator/generator/PyGenerator.java#L1035-L1043
Whiley/WhileyCompiler
src/main/java/wyc/io/WhileyFileParser.java
WhileyFileParser.parseAccessExpression
private Expr parseAccessExpression(EnclosingScope scope, boolean terminated) { int start = index; Expr lhs = parseTermExpression(scope, terminated); Token token; while ((token = tryAndMatchOnLine(LeftSquare)) != null || (token = tryAndMatch(terminated, Dot, MinusGreater, ColonColon)) != null) { switch (token.kind) { case LeftSquare: // NOTE: expression guaranteed to be terminated by ']'. Expr rhs = parseAdditiveExpression(scope, true); // This is a plain old array access expression match(RightSquare); lhs = new Expr.ArrayAccess(Type.Void, lhs, rhs); break; case MinusGreater: lhs = new Expr.Dereference(Type.Void, lhs); // Fall through case Dot: // At this point, we could have a field access, or a // method/function invocation. Therefore, we start by // parsing the field access and then check whether or not its an // invocation. lhs = parseDotAccess(lhs, scope, terminated); break; case ColonColon: // At this point, we have a qualified access. index = start; lhs = parseQualifiedAccess(scope, terminated); break; } // Attached source information lhs = annotateSourceLocation(lhs,start); } return lhs; }
java
private Expr parseAccessExpression(EnclosingScope scope, boolean terminated) { int start = index; Expr lhs = parseTermExpression(scope, terminated); Token token; while ((token = tryAndMatchOnLine(LeftSquare)) != null || (token = tryAndMatch(terminated, Dot, MinusGreater, ColonColon)) != null) { switch (token.kind) { case LeftSquare: // NOTE: expression guaranteed to be terminated by ']'. Expr rhs = parseAdditiveExpression(scope, true); // This is a plain old array access expression match(RightSquare); lhs = new Expr.ArrayAccess(Type.Void, lhs, rhs); break; case MinusGreater: lhs = new Expr.Dereference(Type.Void, lhs); // Fall through case Dot: // At this point, we could have a field access, or a // method/function invocation. Therefore, we start by // parsing the field access and then check whether or not its an // invocation. lhs = parseDotAccess(lhs, scope, terminated); break; case ColonColon: // At this point, we have a qualified access. index = start; lhs = parseQualifiedAccess(scope, terminated); break; } // Attached source information lhs = annotateSourceLocation(lhs,start); } return lhs; }
[ "private", "Expr", "parseAccessExpression", "(", "EnclosingScope", "scope", ",", "boolean", "terminated", ")", "{", "int", "start", "=", "index", ";", "Expr", "lhs", "=", "parseTermExpression", "(", "scope", ",", "terminated", ")", ";", "Token", "token", ";", ...
Parse an <i>access expression</i>, which has the form: <pre> AccessExpr::= PrimaryExpr | AccessExpr '[' AdditiveExpr ']' | AccessExpr '[' AdditiveExpr ".." AdditiveExpr ']' | AccessExpr '.' Identifier | AccessExpr '.' Identifier '(' [ Expr (',' Expr)* ] ')' | AccessExpr "->" Identifier </pre> <p> Access expressions are challenging for several reasons. First, they are <i>left-recursive</i>, making them more difficult to parse correctly. Secondly, there are several different forms above and, of these, some generate multiple AST nodes as well (see below). </p> <p> This parser attempts to construct the most accurate AST possible and this requires disambiguating otherwise identical forms. For example, an expression of the form "aaa.bbb.ccc" can correspond to either a field access, or a constant expression (e.g. with a package/module specifier). Likewise, an expression of the form "aaa.bbb.ccc()" can correspond to an indirect function/method call, or a direct function/method call with a package/module specifier. To disambiguate these forms, the parser relies on the fact any sequence of field-accesses must begin with a local variable. </p> @param scope The enclosing scope for this statement, which determines the set of visible (i.e. declared) variables and also the current indentation level. @param terminated This indicates that the expression is known to be terminated (or not). An expression that's known to be terminated is one which is guaranteed to be followed by something. This is important because it means that we can ignore any newline characters encountered in parsing this expression, and that we'll never overrun the end of the expression (i.e. because there's guaranteed to be something which terminates this expression). A classic situation where terminated is true is when parsing an expression surrounded in braces. In such case, we know the right-brace will always terminate this expression. @return
[ "Parse", "an", "<i", ">", "access", "expression<", "/", "i", ">", "which", "has", "the", "form", ":" ]
train
https://github.com/Whiley/WhileyCompiler/blob/680f8a657d3fc286f8cc422755988b6d74ab3f4c/src/main/java/wyc/io/WhileyFileParser.java#L2194-L2230
lucee/Lucee
core/src/main/java/lucee/transformer/bytecode/util/ASMUtil.java
ASMUtil.getAttributeString
public static String getAttributeString(Tag tag, String attrName, String defaultValue) { Literal lit = getAttributeLiteral(tag, attrName, null); if (lit == null) return defaultValue; return lit.getString(); }
java
public static String getAttributeString(Tag tag, String attrName, String defaultValue) { Literal lit = getAttributeLiteral(tag, attrName, null); if (lit == null) return defaultValue; return lit.getString(); }
[ "public", "static", "String", "getAttributeString", "(", "Tag", "tag", ",", "String", "attrName", ",", "String", "defaultValue", ")", "{", "Literal", "lit", "=", "getAttributeLiteral", "(", "tag", ",", "attrName", ",", "null", ")", ";", "if", "(", "lit", "...
extract the content of a attribut @param cfxdTag @param attrName @return attribute value @throws EvaluatorException
[ "extract", "the", "content", "of", "a", "attribut" ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/transformer/bytecode/util/ASMUtil.java#L357-L361
f2prateek/dart
henson/src/main/java/dart/henson/Bundler.java
Bundler.put
public Bundler put(String key, Parcelable value) { delegate.putParcelable(key, value); return this; }
java
public Bundler put(String key, Parcelable value) { delegate.putParcelable(key, value); return this; }
[ "public", "Bundler", "put", "(", "String", "key", ",", "Parcelable", "value", ")", "{", "delegate", ".", "putParcelable", "(", "key", ",", "value", ")", ";", "return", "this", ";", "}" ]
Inserts a Parcelable value into the mapping of the underlying Bundle, replacing any existing value for the given key. Either key or value may be null. @param key a String, or null @param value a Parcelable object, or null @return this bundler instance to chain method calls
[ "Inserts", "a", "Parcelable", "value", "into", "the", "mapping", "of", "the", "underlying", "Bundle", "replacing", "any", "existing", "value", "for", "the", "given", "key", ".", "Either", "key", "or", "value", "may", "be", "null", "." ]
train
https://github.com/f2prateek/dart/blob/7163b1b148e5141817975ae7dad99d58a8589aeb/henson/src/main/java/dart/henson/Bundler.java#L348-L351
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/multimap/impl/ValueCollectionFactory.java
ValueCollectionFactory.createCollection
public static <T> Collection<T> createCollection(Collection collection) { MultiMapConfig.ValueCollectionType collectionType = findCollectionType(collection); if (collection.isEmpty()) { return emptyCollection(collectionType); } return createCollection(collectionType, collection.size()); }
java
public static <T> Collection<T> createCollection(Collection collection) { MultiMapConfig.ValueCollectionType collectionType = findCollectionType(collection); if (collection.isEmpty()) { return emptyCollection(collectionType); } return createCollection(collectionType, collection.size()); }
[ "public", "static", "<", "T", ">", "Collection", "<", "T", ">", "createCollection", "(", "Collection", "collection", ")", "{", "MultiMapConfig", ".", "ValueCollectionType", "collectionType", "=", "findCollectionType", "(", "collection", ")", ";", "if", "(", "col...
Creates a same type collection with the given collection depending on the {@link com.hazelcast.config.MultiMapConfig#valueCollectionType}. @param collection to be asked to return a new appropriate implementation instance according to {@link MultiMapConfig.ValueCollectionType} @return {@link java.util.Set} or {@link java.util.List} depending on the collectionType argument @throws java.lang.IllegalArgumentException if collectionType is unknown
[ "Creates", "a", "same", "type", "collection", "with", "the", "given", "collection", "depending", "on", "the", "{", "@link", "com", ".", "hazelcast", ".", "config", ".", "MultiMapConfig#valueCollectionType", "}", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/multimap/impl/ValueCollectionFactory.java#L59-L65
spotbugs/spotbugs
eclipsePlugin/src/edu/umd/cs/findbugs/plugin/eclipse/quickfix/util/ASTUtil.java
ASTUtil.getStatement
public static Statement getStatement(CompilationUnit compilationUnit, MethodDeclaration method, int startLine, int endLine) throws StatementNotFoundException { requireNonNull(compilationUnit, "compilation unit"); requireNonNull(method, "method declaration"); Statement statement = searchStatement(compilationUnit, method.getBody().statements(), startLine, endLine); if (statement == null) { throw new StatementNotFoundException(compilationUnit, startLine, endLine); } return statement; }
java
public static Statement getStatement(CompilationUnit compilationUnit, MethodDeclaration method, int startLine, int endLine) throws StatementNotFoundException { requireNonNull(compilationUnit, "compilation unit"); requireNonNull(method, "method declaration"); Statement statement = searchStatement(compilationUnit, method.getBody().statements(), startLine, endLine); if (statement == null) { throw new StatementNotFoundException(compilationUnit, startLine, endLine); } return statement; }
[ "public", "static", "Statement", "getStatement", "(", "CompilationUnit", "compilationUnit", ",", "MethodDeclaration", "method", ",", "int", "startLine", ",", "int", "endLine", ")", "throws", "StatementNotFoundException", "{", "requireNonNull", "(", "compilationUnit", ",...
Return the first <CODE>Statement</CODE> found, that is between the specified start and end line. @param compilationUnit @param method @param startLine @param endLine @return @throws StatementNotFoundException @throws StatementNotFoundException
[ "Return", "the", "first", "<CODE", ">", "Statement<", "/", "CODE", ">", "found", "that", "is", "between", "the", "specified", "start", "and", "end", "line", "." ]
train
https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/eclipsePlugin/src/edu/umd/cs/findbugs/plugin/eclipse/quickfix/util/ASTUtil.java#L394-L404
mapsforge/mapsforge
mapsforge-core/src/main/java/org/mapsforge/core/util/MercatorProjection.java
MercatorProjection.pixelYToTileY
public static int pixelYToTileY(double pixelY, byte zoomLevel, int tileSize) { return (int) Math.min(Math.max(pixelY / tileSize, 0), Math.pow(2, zoomLevel) - 1); }
java
public static int pixelYToTileY(double pixelY, byte zoomLevel, int tileSize) { return (int) Math.min(Math.max(pixelY / tileSize, 0), Math.pow(2, zoomLevel) - 1); }
[ "public", "static", "int", "pixelYToTileY", "(", "double", "pixelY", ",", "byte", "zoomLevel", ",", "int", "tileSize", ")", "{", "return", "(", "int", ")", "Math", ".", "min", "(", "Math", ".", "max", "(", "pixelY", "/", "tileSize", ",", "0", ")", ",...
Converts a pixel Y coordinate to the tile Y number. @param pixelY the pixel Y coordinate that should be converted. @param zoomLevel the zoom level at which the coordinate should be converted. @return the tile Y number.
[ "Converts", "a", "pixel", "Y", "coordinate", "to", "the", "tile", "Y", "number", "." ]
train
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-core/src/main/java/org/mapsforge/core/util/MercatorProjection.java#L433-L435
b3dgs/lionengine
lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/transition/MapTileTransitionModel.java
MapTileTransitionModel.updateNeigbor
private void updateNeigbor(Collection<Tile> resolved, Collection<Tile> toResolve, Tile tile, Tile neighbor, int ox, int oy) { final String group = mapGroup.getGroup(tile); final String neighborGroup = mapGroup.getGroup(neighbor); final Transition transitionA = getTransition(tile, neighborGroup); final Transition transitionB = getTransition(neighbor, group); if (transitionA != null && transitionB != null) { final TransitionType transitionTypeA = transitionA.getType(); final TransitionType transitionTypeB = transitionB.getType(); final TransitionType newType = getTransition(transitionTypeA, transitionTypeB, ox, oy); if (newType != null) { final Transition newTransition = new Transition(newType, transitionA.getOut(), transitionB.getIn()); updateTransition(resolved, toResolve, tile, neighbor, neighborGroup, newTransition); } } }
java
private void updateNeigbor(Collection<Tile> resolved, Collection<Tile> toResolve, Tile tile, Tile neighbor, int ox, int oy) { final String group = mapGroup.getGroup(tile); final String neighborGroup = mapGroup.getGroup(neighbor); final Transition transitionA = getTransition(tile, neighborGroup); final Transition transitionB = getTransition(neighbor, group); if (transitionA != null && transitionB != null) { final TransitionType transitionTypeA = transitionA.getType(); final TransitionType transitionTypeB = transitionB.getType(); final TransitionType newType = getTransition(transitionTypeA, transitionTypeB, ox, oy); if (newType != null) { final Transition newTransition = new Transition(newType, transitionA.getOut(), transitionB.getIn()); updateTransition(resolved, toResolve, tile, neighbor, neighborGroup, newTransition); } } }
[ "private", "void", "updateNeigbor", "(", "Collection", "<", "Tile", ">", "resolved", ",", "Collection", "<", "Tile", ">", "toResolve", ",", "Tile", "tile", ",", "Tile", "neighbor", ",", "int", "ox", ",", "int", "oy", ")", "{", "final", "String", "group",...
Update neighbor. @param resolved The resolved tiles. @param toResolve Tiles to resolve after. @param tile The tile reference. @param neighbor The neighbor reference. @param ox The horizontal offset to update. @param oy The vertical offset to update.
[ "Update", "neighbor", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/transition/MapTileTransitionModel.java#L220-L245
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/lossfunctions/impl/LossMixtureDensity.java
LossMixtureDensity.computeScoreArray
@Override public INDArray computeScoreArray(INDArray labels, INDArray preOutput, IActivation activationFn, INDArray mask) { labels = labels.castTo(preOutput.dataType()); //No-op if already correct dtype INDArray output = activationFn.getActivation(preOutput.dup(), false); MixtureDensityComponents mdc = extractComponents(output); INDArray scoreArr = negativeLogLikelihood(labels, mdc.alpha, mdc.mu, mdc.sigma); if (mask != null) { LossUtil.applyMask(scoreArr, mask); } return scoreArr; }
java
@Override public INDArray computeScoreArray(INDArray labels, INDArray preOutput, IActivation activationFn, INDArray mask) { labels = labels.castTo(preOutput.dataType()); //No-op if already correct dtype INDArray output = activationFn.getActivation(preOutput.dup(), false); MixtureDensityComponents mdc = extractComponents(output); INDArray scoreArr = negativeLogLikelihood(labels, mdc.alpha, mdc.mu, mdc.sigma); if (mask != null) { LossUtil.applyMask(scoreArr, mask); } return scoreArr; }
[ "@", "Override", "public", "INDArray", "computeScoreArray", "(", "INDArray", "labels", ",", "INDArray", "preOutput", ",", "IActivation", "activationFn", ",", "INDArray", "mask", ")", "{", "labels", "=", "labels", ".", "castTo", "(", "preOutput", ".", "dataType",...
This method returns the score for each of the given outputs against the given set of labels. For a mixture density network, this is done by extracting the "alpha", "mu", and "sigma" components of each gaussian and computing the negative log likelihood that the labels fall within a linear combination of these gaussian distributions. The smaller the negative log likelihood, the higher the probability that the given labels actually would fall within the distribution. Therefore by minimizing the negative log likelihood, we get to a position of highest probability that the gaussian mixture explains the phenomenon. @param labels Labels give the sample output that the network should be trying to converge on. @param preOutput The output of the last layer (before applying the activation function). @param activationFn The activation function of the current layer. @param mask Mask to apply to score evaluation (not supported for this cost function). @return
[ "This", "method", "returns", "the", "score", "for", "each", "of", "the", "given", "outputs", "against", "the", "given", "set", "of", "labels", ".", "For", "a", "mixture", "density", "network", "this", "is", "done", "by", "extracting", "the", "alpha", "mu",...
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/lossfunctions/impl/LossMixtureDensity.java#L203-L215
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/MariaDbClob.java
MariaDbClob.getSubString
public String getSubString(long pos, int length) throws SQLException { if (pos < 1) { throw ExceptionMapper.getSqlException("position must be >= 1"); } if (length < 0) { throw ExceptionMapper.getSqlException("length must be > 0"); } try { String val = toString(); return val.substring((int) pos - 1, Math.min((int) pos - 1 + length, val.length())); } catch (Exception e) { throw new SQLException(e); } }
java
public String getSubString(long pos, int length) throws SQLException { if (pos < 1) { throw ExceptionMapper.getSqlException("position must be >= 1"); } if (length < 0) { throw ExceptionMapper.getSqlException("length must be > 0"); } try { String val = toString(); return val.substring((int) pos - 1, Math.min((int) pos - 1 + length, val.length())); } catch (Exception e) { throw new SQLException(e); } }
[ "public", "String", "getSubString", "(", "long", "pos", ",", "int", "length", ")", "throws", "SQLException", "{", "if", "(", "pos", "<", "1", ")", "{", "throw", "ExceptionMapper", ".", "getSqlException", "(", "\"position must be >= 1\"", ")", ";", "}", "if",...
Get sub string. @param pos position @param length length of sub string @return substring @throws SQLException if pos is less than 1 or length is less than 0
[ "Get", "sub", "string", "." ]
train
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/MariaDbClob.java#L118-L134
liferay/com-liferay-commerce
commerce-wish-list-service/src/main/java/com/liferay/commerce/wish/list/service/persistence/impl/CommerceWishListPersistenceImpl.java
CommerceWishListPersistenceImpl.findByG_U_D
@Override public List<CommerceWishList> findByG_U_D(long groupId, long userId, boolean defaultWishList, int start, int end) { return findByG_U_D(groupId, userId, defaultWishList, start, end, null); }
java
@Override public List<CommerceWishList> findByG_U_D(long groupId, long userId, boolean defaultWishList, int start, int end) { return findByG_U_D(groupId, userId, defaultWishList, start, end, null); }
[ "@", "Override", "public", "List", "<", "CommerceWishList", ">", "findByG_U_D", "(", "long", "groupId", ",", "long", "userId", ",", "boolean", "defaultWishList", ",", "int", "start", ",", "int", "end", ")", "{", "return", "findByG_U_D", "(", "groupId", ",", ...
Returns a range of all the commerce wish lists where groupId = &#63; and userId = &#63; and defaultWishList = &#63;. <p> Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommerceWishListModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. </p> @param groupId the group ID @param userId the user ID @param defaultWishList the default wish list @param start the lower bound of the range of commerce wish lists @param end the upper bound of the range of commerce wish lists (not inclusive) @return the range of matching commerce wish lists
[ "Returns", "a", "range", "of", "all", "the", "commerce", "wish", "lists", "where", "groupId", "=", "&#63", ";", "and", "userId", "=", "&#63", ";", "and", "defaultWishList", "=", "&#63", ";", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-wish-list-service/src/main/java/com/liferay/commerce/wish/list/service/persistence/impl/CommerceWishListPersistenceImpl.java#L3673-L3677
openengsb/openengsb
components/ekb/transformation-wonderland/src/main/java/org/openengsb/core/ekb/transformation/wonderland/internal/operation/SplitOperation.java
SplitOperation.performSplitting
private String performSplitting(String source, String splitString, String indexString) throws TransformationOperationException { try { Integer index = Integer.parseInt(indexString); return source.split(splitString)[index]; } catch (NumberFormatException e) { throw new TransformationOperationException("The given result index parameter is not a number"); } catch (IndexOutOfBoundsException e) { throw new TransformationOperationException( "The split result does not have that much results for the index parameter"); } }
java
private String performSplitting(String source, String splitString, String indexString) throws TransformationOperationException { try { Integer index = Integer.parseInt(indexString); return source.split(splitString)[index]; } catch (NumberFormatException e) { throw new TransformationOperationException("The given result index parameter is not a number"); } catch (IndexOutOfBoundsException e) { throw new TransformationOperationException( "The split result does not have that much results for the index parameter"); } }
[ "private", "String", "performSplitting", "(", "String", "source", ",", "String", "splitString", ",", "String", "indexString", ")", "throws", "TransformationOperationException", "{", "try", "{", "Integer", "index", "=", "Integer", ".", "parseInt", "(", "indexString",...
Performs the actual splitting operation. Throws a TransformationOperationException if the index string is not a number or causes an IndexOutOfBoundsException.
[ "Performs", "the", "actual", "splitting", "operation", ".", "Throws", "a", "TransformationOperationException", "if", "the", "index", "string", "is", "not", "a", "number", "or", "causes", "an", "IndexOutOfBoundsException", "." ]
train
https://github.com/openengsb/openengsb/blob/d39058000707f617cd405629f9bc7f17da7b414a/components/ekb/transformation-wonderland/src/main/java/org/openengsb/core/ekb/transformation/wonderland/internal/operation/SplitOperation.java#L71-L82
apache/groovy
src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
DefaultGroovyMethods.setMetaClass
public static void setMetaClass(GroovyObject self, MetaClass metaClass) { // this method was introduced as to prevent from a stack overflow, described in GROOVY-5285 if (metaClass instanceof HandleMetaClass) metaClass = ((HandleMetaClass)metaClass).getAdaptee(); self.setMetaClass(metaClass); disablePrimitiveOptimization(self); }
java
public static void setMetaClass(GroovyObject self, MetaClass metaClass) { // this method was introduced as to prevent from a stack overflow, described in GROOVY-5285 if (metaClass instanceof HandleMetaClass) metaClass = ((HandleMetaClass)metaClass).getAdaptee(); self.setMetaClass(metaClass); disablePrimitiveOptimization(self); }
[ "public", "static", "void", "setMetaClass", "(", "GroovyObject", "self", ",", "MetaClass", "metaClass", ")", "{", "// this method was introduced as to prevent from a stack overflow, described in GROOVY-5285", "if", "(", "metaClass", "instanceof", "HandleMetaClass", ")", "metaCl...
Set the metaclass for a GroovyObject. @param self the object whose metaclass we want to set @param metaClass the new metaclass value @since 2.0.0
[ "Set", "the", "metaclass", "for", "a", "GroovyObject", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L17309-L17316
albfernandez/itext2
src/main/java/com/lowagie/text/pdf/PdfAction.java
PdfAction.createLaunch
public static PdfAction createLaunch(String application, String parameters, String operation, String defaultDir) { return new PdfAction(application, parameters, operation, defaultDir); }
java
public static PdfAction createLaunch(String application, String parameters, String operation, String defaultDir) { return new PdfAction(application, parameters, operation, defaultDir); }
[ "public", "static", "PdfAction", "createLaunch", "(", "String", "application", ",", "String", "parameters", ",", "String", "operation", ",", "String", "defaultDir", ")", "{", "return", "new", "PdfAction", "(", "application", ",", "parameters", ",", "operation", ...
Launches an application or a document. @param application the application to be launched or the document to be opened or printed. @param parameters (Windows-specific) A parameter string to be passed to the application. It can be <CODE>null</CODE>. @param operation (Windows-specific) the operation to perform: "open" - Open a document, "print" - Print a document. It can be <CODE>null</CODE>. @param defaultDir (Windows-specific) the default directory in standard DOS syntax. It can be <CODE>null</CODE>. @return a Launch action
[ "Launches", "an", "application", "or", "a", "document", "." ]
train
https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/PdfAction.java#L261-L263
pgjdbc/pgjdbc
pgjdbc/src/main/java/org/postgresql/sspi/SSPIClient.java
SSPIClient.continueSSPI
@Override public void continueSSPI(int msgLength) throws SQLException, IOException { if (sspiContext == null) { throw new IllegalStateException("Cannot continue SSPI authentication that we didn't begin"); } LOGGER.log(Level.FINEST, "Continuing SSPI negotiation"); /* Read the response token from the server */ byte[] receivedToken = pgStream.receive(msgLength); SecBufferDesc continueToken = new SecBufferDesc(Sspi.SECBUFFER_TOKEN, receivedToken); sspiContext.initialize(sspiContext.getHandle(), continueToken, targetName); /* * Now send the response token. If negotiation is complete there may be zero bytes to send, in * which case we shouldn't send a reply as the server is not expecting one; see fe-auth.c in * libpq for details. */ byte[] responseToken = sspiContext.getToken(); if (responseToken.length > 0) { sendSSPIResponse(responseToken); LOGGER.log(Level.FINEST, "Sent SSPI negotiation continuation message"); } else { LOGGER.log(Level.FINEST, "SSPI authentication complete, no reply required"); } }
java
@Override public void continueSSPI(int msgLength) throws SQLException, IOException { if (sspiContext == null) { throw new IllegalStateException("Cannot continue SSPI authentication that we didn't begin"); } LOGGER.log(Level.FINEST, "Continuing SSPI negotiation"); /* Read the response token from the server */ byte[] receivedToken = pgStream.receive(msgLength); SecBufferDesc continueToken = new SecBufferDesc(Sspi.SECBUFFER_TOKEN, receivedToken); sspiContext.initialize(sspiContext.getHandle(), continueToken, targetName); /* * Now send the response token. If negotiation is complete there may be zero bytes to send, in * which case we shouldn't send a reply as the server is not expecting one; see fe-auth.c in * libpq for details. */ byte[] responseToken = sspiContext.getToken(); if (responseToken.length > 0) { sendSSPIResponse(responseToken); LOGGER.log(Level.FINEST, "Sent SSPI negotiation continuation message"); } else { LOGGER.log(Level.FINEST, "SSPI authentication complete, no reply required"); } }
[ "@", "Override", "public", "void", "continueSSPI", "(", "int", "msgLength", ")", "throws", "SQLException", ",", "IOException", "{", "if", "(", "sspiContext", "==", "null", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Cannot continue SSPI authentication...
Continue an existing authentication conversation with the back-end in resonse to an authentication request of type AUTH_REQ_GSS_CONT. @param msgLength Length of message to read, excluding length word and message type word @throws SQLException if something wrong happens @throws IOException if something wrong happens
[ "Continue", "an", "existing", "authentication", "conversation", "with", "the", "back", "-", "end", "in", "resonse", "to", "an", "authentication", "request", "of", "type", "AUTH_REQ_GSS_CONT", "." ]
train
https://github.com/pgjdbc/pgjdbc/blob/95ba7b261e39754674c5817695ae5ebf9a341fae/pgjdbc/src/main/java/org/postgresql/sspi/SSPIClient.java#L181-L209
xiaosunzhu/resource-utils
src/main/java/net/sunyijun/resource/config/Configs.java
Configs.getSelfConfigDecimal
public static BigDecimal getSelfConfigDecimal(String configAbsoluteClassPath, IConfigKey key) { OneProperties configs = otherConfigs.get(configAbsoluteClassPath); if (configs == null) { addSelfConfigs(configAbsoluteClassPath, null); configs = otherConfigs.get(configAbsoluteClassPath); if (configs == null) { return VOID_CONFIGS.getDecimalConfig(key); } } return configs.getDecimalConfig(key); }
java
public static BigDecimal getSelfConfigDecimal(String configAbsoluteClassPath, IConfigKey key) { OneProperties configs = otherConfigs.get(configAbsoluteClassPath); if (configs == null) { addSelfConfigs(configAbsoluteClassPath, null); configs = otherConfigs.get(configAbsoluteClassPath); if (configs == null) { return VOID_CONFIGS.getDecimalConfig(key); } } return configs.getDecimalConfig(key); }
[ "public", "static", "BigDecimal", "getSelfConfigDecimal", "(", "String", "configAbsoluteClassPath", ",", "IConfigKey", "key", ")", "{", "OneProperties", "configs", "=", "otherConfigs", ".", "get", "(", "configAbsoluteClassPath", ")", ";", "if", "(", "configs", "==",...
Get self config decimal. @param configAbsoluteClassPath config path. @param key config key in configAbsoluteClassPath config file @return config BigDecimal value. Return null if not add config file or not config in config file. @see #addSelfConfigs(String, OneProperties)
[ "Get", "self", "config", "decimal", "." ]
train
https://github.com/xiaosunzhu/resource-utils/blob/4f2bf3f36df10195a978f122ed682ba1eb0462b5/src/main/java/net/sunyijun/resource/config/Configs.java#L293-L303
alkacon/opencms-core
src/org/opencms/ui/apps/modules/edit/CmsEditModuleForm.java
CmsEditModuleForm.addDependency
void addDependency(String moduleName, String version) { try { m_dependencies.addComponent( new CmsRemovableFormRow<CmsModuleDependencyWidget>( CmsModuleDependencyWidget.create( new CmsModuleDependency(moduleName, new CmsModuleVersion(version))), "")); } catch (Exception e) { CmsErrorDialog.showErrorDialog(e); } }
java
void addDependency(String moduleName, String version) { try { m_dependencies.addComponent( new CmsRemovableFormRow<CmsModuleDependencyWidget>( CmsModuleDependencyWidget.create( new CmsModuleDependency(moduleName, new CmsModuleVersion(version))), "")); } catch (Exception e) { CmsErrorDialog.showErrorDialog(e); } }
[ "void", "addDependency", "(", "String", "moduleName", ",", "String", "version", ")", "{", "try", "{", "m_dependencies", ".", "addComponent", "(", "new", "CmsRemovableFormRow", "<", "CmsModuleDependencyWidget", ">", "(", "CmsModuleDependencyWidget", ".", "create", "(...
Adds a new module dependency widget.<p> @param moduleName the module name @param version the module version
[ "Adds", "a", "new", "module", "dependency", "widget", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/apps/modules/edit/CmsEditModuleForm.java#L667-L678
sarl/sarl
main/coreplugins/io.sarl.lang/src/io/sarl/lang/jvmmodel/SARLJvmModelInferrer.java
SARLJvmModelInferrer.inferFunctionReturnType
protected JvmTypeReference inferFunctionReturnType(XtendFunction source, JvmOperation target, JvmOperation overriddenOperation) { // The return type is explicitly given if (source.getReturnType() != null) { return ensureValidType(source.eResource(), source.getReturnType()); } // An super operation was detected => reuse its return type. if (overriddenOperation != null) { final JvmTypeReference type = overriddenOperation.getReturnType(); //return cloneWithProxiesFromOtherResource(type, target); return this.typeReferences.createDelegateTypeReference(type); } // Return type is inferred from the operation's expression. final XExpression expression = source.getExpression(); JvmTypeReference returnType = null; if (expression != null && ((!(expression instanceof XBlockExpression)) || (!((XBlockExpression) expression).getExpressions().isEmpty()))) { returnType = inferFunctionReturnType(expression); } return ensureValidType(source.eResource(), returnType); }
java
protected JvmTypeReference inferFunctionReturnType(XtendFunction source, JvmOperation target, JvmOperation overriddenOperation) { // The return type is explicitly given if (source.getReturnType() != null) { return ensureValidType(source.eResource(), source.getReturnType()); } // An super operation was detected => reuse its return type. if (overriddenOperation != null) { final JvmTypeReference type = overriddenOperation.getReturnType(); //return cloneWithProxiesFromOtherResource(type, target); return this.typeReferences.createDelegateTypeReference(type); } // Return type is inferred from the operation's expression. final XExpression expression = source.getExpression(); JvmTypeReference returnType = null; if (expression != null && ((!(expression instanceof XBlockExpression)) || (!((XBlockExpression) expression).getExpressions().isEmpty()))) { returnType = inferFunctionReturnType(expression); } return ensureValidType(source.eResource(), returnType); }
[ "protected", "JvmTypeReference", "inferFunctionReturnType", "(", "XtendFunction", "source", ",", "JvmOperation", "target", ",", "JvmOperation", "overriddenOperation", ")", "{", "// The return type is explicitly given", "if", "(", "source", ".", "getReturnType", "(", ")", ...
Infer the return type for the given source function. @param source the source function. @param target the target operation. @param overriddenOperation reference to the overridden operation. @return the inferred return type. @since 0.7
[ "Infer", "the", "return", "type", "for", "the", "given", "source", "function", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.lang/src/io/sarl/lang/jvmmodel/SARLJvmModelInferrer.java#L3643-L3665
Comcast/jrugged
jrugged-core/src/main/java/org/fishwife/jrugged/CircuitBreakerFactory.java
CircuitBreakerFactory.getLongPropertyOverrideValue
private Long getLongPropertyOverrideValue(String name, String key) { if (properties != null) { String propertyName = getPropertyName(name, key); String propertyOverrideValue = properties.getProperty(propertyName); if (propertyOverrideValue != null) { try { return Long.parseLong(propertyOverrideValue); } catch (NumberFormatException e) { logger.error("Could not parse property override key={}, value={}", key, propertyOverrideValue); } } } return null; }
java
private Long getLongPropertyOverrideValue(String name, String key) { if (properties != null) { String propertyName = getPropertyName(name, key); String propertyOverrideValue = properties.getProperty(propertyName); if (propertyOverrideValue != null) { try { return Long.parseLong(propertyOverrideValue); } catch (NumberFormatException e) { logger.error("Could not parse property override key={}, value={}", key, propertyOverrideValue); } } } return null; }
[ "private", "Long", "getLongPropertyOverrideValue", "(", "String", "name", ",", "String", "key", ")", "{", "if", "(", "properties", "!=", "null", ")", "{", "String", "propertyName", "=", "getPropertyName", "(", "name", ",", "key", ")", ";", "String", "propert...
Get an {@link Long} property override value. @param name the {@link CircuitBreaker} name. @param key the property override key. @return the property override value, or null if it is not found.
[ "Get", "an", "{" ]
train
https://github.com/Comcast/jrugged/blob/b6a5147c68ee733faf5616d49800abcbba67afe9/jrugged-core/src/main/java/org/fishwife/jrugged/CircuitBreakerFactory.java#L199-L216
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/ThreadSafety.java
ThreadSafety.getMarkerOrAcceptedAnnotation
public AnnotationInfo getMarkerOrAcceptedAnnotation(Symbol sym, VisitorState state) { String nameStr = sym.flatName().toString(); AnnotationInfo known = knownTypes.getKnownSafeClasses().get(nameStr); if (known != null) { return known; } return getAnnotation( sym, ImmutableSet.copyOf(Sets.union(markerAnnotations, acceptedAnnotations)), state); }
java
public AnnotationInfo getMarkerOrAcceptedAnnotation(Symbol sym, VisitorState state) { String nameStr = sym.flatName().toString(); AnnotationInfo known = knownTypes.getKnownSafeClasses().get(nameStr); if (known != null) { return known; } return getAnnotation( sym, ImmutableSet.copyOf(Sets.union(markerAnnotations, acceptedAnnotations)), state); }
[ "public", "AnnotationInfo", "getMarkerOrAcceptedAnnotation", "(", "Symbol", "sym", ",", "VisitorState", "state", ")", "{", "String", "nameStr", "=", "sym", ".", "flatName", "(", ")", ".", "toString", "(", ")", ";", "AnnotationInfo", "known", "=", "knownTypes", ...
Gets the {@link Symbol}'s annotation info, either from a marker annotation on the symbol, from an accepted annotation on the symbol, or from the list of well-known types.
[ "Gets", "the", "{" ]
train
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/ThreadSafety.java#L651-L659
bingoohuang/spring-rest-client
src/main/java/com/github/bingoohuang/springrestclient/spring/ClassPathSpringRestClientScanner.java
ClassPathSpringRestClientScanner.registerFilters
public void registerFilters() { addExcludeFilter(new TypeFilter() { @Override public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) { return !metadataReader.getClassMetadata().isInterface(); } }); addIncludeFilter(new AnnotationTypeFilter(SpringRestClientEnabled.class)); }
java
public void registerFilters() { addExcludeFilter(new TypeFilter() { @Override public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) { return !metadataReader.getClassMetadata().isInterface(); } }); addIncludeFilter(new AnnotationTypeFilter(SpringRestClientEnabled.class)); }
[ "public", "void", "registerFilters", "(", ")", "{", "addExcludeFilter", "(", "new", "TypeFilter", "(", ")", "{", "@", "Override", "public", "boolean", "match", "(", "MetadataReader", "metadataReader", ",", "MetadataReaderFactory", "metadataReaderFactory", ")", "{", ...
Configures parent scanner to search for the right interfaces. It can search for all interfaces or just for those that extends a markerInterface or/and those annotated with the annotationClass
[ "Configures", "parent", "scanner", "to", "search", "for", "the", "right", "interfaces", ".", "It", "can", "search", "for", "all", "interfaces", "or", "just", "for", "those", "that", "extends", "a", "markerInterface", "or", "/", "and", "those", "annotated", "...
train
https://github.com/bingoohuang/spring-rest-client/blob/50766ec010063102f56650350d893c924658fa6b/src/main/java/com/github/bingoohuang/springrestclient/spring/ClassPathSpringRestClientScanner.java#L32-L40
gallandarakhneorg/afc
advanced/mathfx/src/main/java/org/arakhne/afc/math/geometry/d2/ifx/Circle2ifx.java
Circle2ifx.radiusProperty
@Pure public IntegerProperty radiusProperty() { if (this.radius == null) { this.radius = new SimpleIntegerProperty(this, MathFXAttributeNames.RADIUS) { @Override protected void invalidated() { if (get() < 0) { set(0); } } }; } return this.radius; }
java
@Pure public IntegerProperty radiusProperty() { if (this.radius == null) { this.radius = new SimpleIntegerProperty(this, MathFXAttributeNames.RADIUS) { @Override protected void invalidated() { if (get() < 0) { set(0); } } }; } return this.radius; }
[ "@", "Pure", "public", "IntegerProperty", "radiusProperty", "(", ")", "{", "if", "(", "this", ".", "radius", "==", "null", ")", "{", "this", ".", "radius", "=", "new", "SimpleIntegerProperty", "(", "this", ",", "MathFXAttributeNames", ".", "RADIUS", ")", "...
Replies the property that is the radius of the circle. @return the radius property.
[ "Replies", "the", "property", "that", "is", "the", "radius", "of", "the", "circle", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/mathfx/src/main/java/org/arakhne/afc/math/geometry/d2/ifx/Circle2ifx.java#L199-L212
alkacon/opencms-core
src/org/opencms/db/CmsPublishList.java
CmsPublishList.containsSubResources
protected boolean containsSubResources(CmsObject cms, CmsResource folder) throws CmsException { String folderPath = cms.getSitePath(folder); List<CmsResource> subResources = cms.readResources(folderPath, CmsResourceFilter.ALL, true); for (CmsResource resource : subResources) { if (!containsResource(resource)) { return false; } } return true; }
java
protected boolean containsSubResources(CmsObject cms, CmsResource folder) throws CmsException { String folderPath = cms.getSitePath(folder); List<CmsResource> subResources = cms.readResources(folderPath, CmsResourceFilter.ALL, true); for (CmsResource resource : subResources) { if (!containsResource(resource)) { return false; } } return true; }
[ "protected", "boolean", "containsSubResources", "(", "CmsObject", "cms", ",", "CmsResource", "folder", ")", "throws", "CmsException", "{", "String", "folderPath", "=", "cms", ".", "getSitePath", "(", "folder", ")", ";", "List", "<", "CmsResource", ">", "subResou...
Checks if the publish list contains all sub-resources of a given folder.<p> @param cms the current CMS context @param folder the folder for which the check should be performed @return true if the publish list contains all sub-resources of a given folder @throws CmsException if something goes wrong
[ "Checks", "if", "the", "publish", "list", "contains", "all", "sub", "-", "resources", "of", "a", "given", "folder", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsPublishList.java#L624-L634
virgo47/javasimon
console-embed/src/main/java/org/javasimon/console/reflect/GetterFactory.java
GetterFactory.getGettersAsMap
private static Map<String, Getter> getGettersAsMap(Class type) { Map<String, Getter> typeGetters = GETTER_CACHE.get(type); if (typeGetters == null) { typeGetters = new HashMap<>(); for (Method method : type.getMethods()) { if (isGetterMethod(method)) { String propertyName = getPropertyName(method); Class propertyType = method.getReturnType(); //noinspection unchecked typeGetters.put(propertyName, new Getter(propertyName, propertyType, getSubType(type, propertyName), method)); } } GETTER_CACHE.put(type, typeGetters); } return typeGetters; }
java
private static Map<String, Getter> getGettersAsMap(Class type) { Map<String, Getter> typeGetters = GETTER_CACHE.get(type); if (typeGetters == null) { typeGetters = new HashMap<>(); for (Method method : type.getMethods()) { if (isGetterMethod(method)) { String propertyName = getPropertyName(method); Class propertyType = method.getReturnType(); //noinspection unchecked typeGetters.put(propertyName, new Getter(propertyName, propertyType, getSubType(type, propertyName), method)); } } GETTER_CACHE.put(type, typeGetters); } return typeGetters; }
[ "private", "static", "Map", "<", "String", ",", "Getter", ">", "getGettersAsMap", "(", "Class", "type", ")", "{", "Map", "<", "String", ",", "Getter", ">", "typeGetters", "=", "GETTER_CACHE", ".", "get", "(", "type", ")", ";", "if", "(", "typeGetters", ...
Extract all getters for given class. @param type Class @return Map property name &rarr; Getter
[ "Extract", "all", "getters", "for", "given", "class", "." ]
train
https://github.com/virgo47/javasimon/blob/17dfaa93cded9ce8ef64a134b28ccbf4d0284d2f/console-embed/src/main/java/org/javasimon/console/reflect/GetterFactory.java#L88-L103
ZuInnoTe/hadoopcryptoledger
inputformat/src/main/java/org/zuinnote/hadoop/bitcoin/format/common/BitcoinBlockReader.java
BitcoinBlockReader.parseAuxPOWBranch
public BitcoinAuxPOWBranch parseAuxPOWBranch(ByteBuffer rawByteBuffer) { byte[] noOfLinksVarInt=BitcoinUtil.convertVarIntByteBufferToByteArray(rawByteBuffer); long currentNoOfLinks=BitcoinUtil.getVarInt(noOfLinksVarInt); ArrayList<byte[]> links = new ArrayList((int)currentNoOfLinks); for (int i=0;i<currentNoOfLinks;i++) { byte[] currentLink = new byte[32]; rawByteBuffer.get(currentLink,0,32); links.add(currentLink); } byte[] branchSideBitmask=new byte[4]; rawByteBuffer.get(branchSideBitmask,0,4); return new BitcoinAuxPOWBranch(noOfLinksVarInt, links, branchSideBitmask); }
java
public BitcoinAuxPOWBranch parseAuxPOWBranch(ByteBuffer rawByteBuffer) { byte[] noOfLinksVarInt=BitcoinUtil.convertVarIntByteBufferToByteArray(rawByteBuffer); long currentNoOfLinks=BitcoinUtil.getVarInt(noOfLinksVarInt); ArrayList<byte[]> links = new ArrayList((int)currentNoOfLinks); for (int i=0;i<currentNoOfLinks;i++) { byte[] currentLink = new byte[32]; rawByteBuffer.get(currentLink,0,32); links.add(currentLink); } byte[] branchSideBitmask=new byte[4]; rawByteBuffer.get(branchSideBitmask,0,4); return new BitcoinAuxPOWBranch(noOfLinksVarInt, links, branchSideBitmask); }
[ "public", "BitcoinAuxPOWBranch", "parseAuxPOWBranch", "(", "ByteBuffer", "rawByteBuffer", ")", "{", "byte", "[", "]", "noOfLinksVarInt", "=", "BitcoinUtil", ".", "convertVarIntByteBufferToByteArray", "(", "rawByteBuffer", ")", ";", "long", "currentNoOfLinks", "=", "Bitc...
Parse an AUXPowBranch @param rawByteBuffer ByteBuffer from which the AuxPOWBranch should be parsed @return AuxPOWBranch
[ "Parse", "an", "AUXPowBranch" ]
train
https://github.com/ZuInnoTe/hadoopcryptoledger/blob/5c9bfb61dd1a82374cd0de8413a7c66391ee4414/inputformat/src/main/java/org/zuinnote/hadoop/bitcoin/format/common/BitcoinBlockReader.java#L260-L273
google/closure-compiler
src/com/google/debugging/sourcemap/SourceMapGeneratorV3.java
SourceMapGeneratorV3.setWrapperPrefix
@Override public void setWrapperPrefix(String prefix) { // Determine the current line and character position. int prefixLine = 0; int prefixIndex = 0; for (int i = 0; i < prefix.length(); ++i) { if (prefix.charAt(i) == '\n') { prefixLine++; prefixIndex = 0; } else { prefixIndex++; } } prefixPosition = new FilePosition(prefixLine, prefixIndex); }
java
@Override public void setWrapperPrefix(String prefix) { // Determine the current line and character position. int prefixLine = 0; int prefixIndex = 0; for (int i = 0; i < prefix.length(); ++i) { if (prefix.charAt(i) == '\n') { prefixLine++; prefixIndex = 0; } else { prefixIndex++; } } prefixPosition = new FilePosition(prefixLine, prefixIndex); }
[ "@", "Override", "public", "void", "setWrapperPrefix", "(", "String", "prefix", ")", "{", "// Determine the current line and character position.", "int", "prefixLine", "=", "0", ";", "int", "prefixIndex", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "...
Sets the prefix used for wrapping the generated source file before it is written. This ensures that the source map is adjusted for the change in character offsets. @param prefix The prefix that is added before the generated source code.
[ "Sets", "the", "prefix", "used", "for", "wrapping", "the", "generated", "source", "file", "before", "it", "is", "written", ".", "This", "ensures", "that", "the", "source", "map", "is", "adjusted", "for", "the", "change", "in", "character", "offsets", "." ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/debugging/sourcemap/SourceMapGeneratorV3.java#L166-L182
aws/aws-sdk-java
aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/AmazonS3Client.java
AmazonS3Client.createSigner
protected Signer createSigner(final Request<?> request, final String bucketName, final String key) { return createSigner(request, bucketName, key, false); }
java
protected Signer createSigner(final Request<?> request, final String bucketName, final String key) { return createSigner(request, bucketName, key, false); }
[ "protected", "Signer", "createSigner", "(", "final", "Request", "<", "?", ">", "request", ",", "final", "String", "bucketName", ",", "final", "String", "key", ")", "{", "return", "createSigner", "(", "request", ",", "bucketName", ",", "key", ",", "false", ...
Returns a "complete" S3 specific signer, taking into the S3 bucket, key, and the current S3 client configuration into account.
[ "Returns", "a", "complete", "S3", "specific", "signer", "taking", "into", "the", "S3", "bucket", "key", "and", "the", "current", "S3", "client", "configuration", "into", "account", "." ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/AmazonS3Client.java#L3975-L3979
alipay/sofa-rpc
core/common/src/main/java/com/alipay/sofa/rpc/common/cache/ReflectCache.java
ReflectCache.putMethodSigsCache
public static void putMethodSigsCache(String serviceName, String methodName, String[] argSigs) { ConcurrentHashMap<String, String[]> cacheSigs = NOT_OVERLOAD_METHOD_SIGS_CACHE.get(serviceName); if (cacheSigs == null) { cacheSigs = new ConcurrentHashMap<String, String[]>(); ConcurrentHashMap<String, String[]> old = NOT_OVERLOAD_METHOD_SIGS_CACHE .putIfAbsent(serviceName, cacheSigs); if (old != null) { cacheSigs = old; } } cacheSigs.putIfAbsent(methodName, argSigs); }
java
public static void putMethodSigsCache(String serviceName, String methodName, String[] argSigs) { ConcurrentHashMap<String, String[]> cacheSigs = NOT_OVERLOAD_METHOD_SIGS_CACHE.get(serviceName); if (cacheSigs == null) { cacheSigs = new ConcurrentHashMap<String, String[]>(); ConcurrentHashMap<String, String[]> old = NOT_OVERLOAD_METHOD_SIGS_CACHE .putIfAbsent(serviceName, cacheSigs); if (old != null) { cacheSigs = old; } } cacheSigs.putIfAbsent(methodName, argSigs); }
[ "public", "static", "void", "putMethodSigsCache", "(", "String", "serviceName", ",", "String", "methodName", ",", "String", "[", "]", "argSigs", ")", "{", "ConcurrentHashMap", "<", "String", ",", "String", "[", "]", ">", "cacheSigs", "=", "NOT_OVERLOAD_METHOD_SI...
往缓存里放入方法参数签名 @param serviceName 服务名(非接口名) @param methodName 方法名 @param argSigs 方法参数签名
[ "往缓存里放入方法参数签名" ]
train
https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/core/common/src/main/java/com/alipay/sofa/rpc/common/cache/ReflectCache.java#L211-L222
j256/ormlite-android
src/main/java/com/j256/ormlite/android/DatabaseTableConfigUtil.java
DatabaseTableConfigUtil.configFromField
private static DatabaseFieldConfig configFromField(DatabaseType databaseType, String tableName, Field field) throws SQLException { if (configFieldNums == null) { return DatabaseFieldConfig.fromField(databaseType, tableName, field); } /* * This, unfortunately, we can't get around. This creates a AnnotationFactory, an array of AnnotationMember * fields, and possibly another array of AnnotationMember values. This creates a lot of GC'd objects. */ DatabaseField databaseField = field.getAnnotation(DatabaseField.class); DatabaseFieldConfig config = null; try { if (databaseField != null) { config = buildConfig(databaseField, tableName, field); } } catch (Exception e) { // ignored so we will configure normally below } if (config == null) { /* * We configure this the old way because we might be using javax annotations, have a ForeignCollectionField, * or may still be using the deprecated annotations. At this point we know that there isn't a @DatabaseField * or we can't do our reflection hacks for some reason. */ return DatabaseFieldConfig.fromField(databaseType, tableName, field); } else { workedC++; return config; } }
java
private static DatabaseFieldConfig configFromField(DatabaseType databaseType, String tableName, Field field) throws SQLException { if (configFieldNums == null) { return DatabaseFieldConfig.fromField(databaseType, tableName, field); } /* * This, unfortunately, we can't get around. This creates a AnnotationFactory, an array of AnnotationMember * fields, and possibly another array of AnnotationMember values. This creates a lot of GC'd objects. */ DatabaseField databaseField = field.getAnnotation(DatabaseField.class); DatabaseFieldConfig config = null; try { if (databaseField != null) { config = buildConfig(databaseField, tableName, field); } } catch (Exception e) { // ignored so we will configure normally below } if (config == null) { /* * We configure this the old way because we might be using javax annotations, have a ForeignCollectionField, * or may still be using the deprecated annotations. At this point we know that there isn't a @DatabaseField * or we can't do our reflection hacks for some reason. */ return DatabaseFieldConfig.fromField(databaseType, tableName, field); } else { workedC++; return config; } }
[ "private", "static", "DatabaseFieldConfig", "configFromField", "(", "DatabaseType", "databaseType", ",", "String", "tableName", ",", "Field", "field", ")", "throws", "SQLException", "{", "if", "(", "configFieldNums", "==", "null", ")", "{", "return", "DatabaseFieldC...
Extract our configuration information from the field by looking for a {@link DatabaseField} annotation.
[ "Extract", "our", "configuration", "information", "from", "the", "field", "by", "looking", "for", "a", "{" ]
train
https://github.com/j256/ormlite-android/blob/e82327a868ae242f994730fe2389f79684d7bcab/src/main/java/com/j256/ormlite/android/DatabaseTableConfigUtil.java#L253-L286
apereo/cas
support/cas-server-support-ldap-core/src/main/java/org/apereo/cas/util/LdapUtils.java
LdapUtils.getBoolean
public static Boolean getBoolean(final LdapEntry ctx, final String attribute, final Boolean nullValue) { val v = getString(ctx, attribute, nullValue.toString()); if (v != null) { return v.equalsIgnoreCase(Boolean.TRUE.toString()); } return nullValue; }
java
public static Boolean getBoolean(final LdapEntry ctx, final String attribute, final Boolean nullValue) { val v = getString(ctx, attribute, nullValue.toString()); if (v != null) { return v.equalsIgnoreCase(Boolean.TRUE.toString()); } return nullValue; }
[ "public", "static", "Boolean", "getBoolean", "(", "final", "LdapEntry", "ctx", ",", "final", "String", "attribute", ",", "final", "Boolean", "nullValue", ")", "{", "val", "v", "=", "getString", "(", "ctx", ",", "attribute", ",", "nullValue", ".", "toString",...
Reads a Boolean value from the LdapEntry. @param ctx the ldap entry @param attribute the attribute name @param nullValue the value which should be returning in case of a null value @return {@code true} if the attribute's value matches (case-insensitive) {@code "true"}, otherwise false
[ "Reads", "a", "Boolean", "value", "from", "the", "LdapEntry", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-ldap-core/src/main/java/org/apereo/cas/util/LdapUtils.java#L148-L154
netty/netty
codec-http/src/main/java/io/netty/handler/codec/http/HttpHeaders.java
HttpHeaders.getHeader
@Deprecated public static String getHeader(HttpMessage message, CharSequence name, String defaultValue) { return message.headers().get(name, defaultValue); }
java
@Deprecated public static String getHeader(HttpMessage message, CharSequence name, String defaultValue) { return message.headers().get(name, defaultValue); }
[ "@", "Deprecated", "public", "static", "String", "getHeader", "(", "HttpMessage", "message", ",", "CharSequence", "name", ",", "String", "defaultValue", ")", "{", "return", "message", ".", "headers", "(", ")", ".", "get", "(", "name", ",", "defaultValue", ")...
@deprecated Use {@link #get(CharSequence, String)} instead. Returns the header value with the specified header name. If there are more than one header value for the specified header name, the first value is returned. @return the header value or the {@code defaultValue} if there is no such header
[ "@deprecated", "Use", "{", "@link", "#get", "(", "CharSequence", "String", ")", "}", "instead", "." ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec-http/src/main/java/io/netty/handler/codec/http/HttpHeaders.java#L589-L592
depsypher/pngtastic
src/main/java/com/googlecode/pngtastic/core/processing/PngtasticFilterHandler.java
PngtasticFilterHandler.filter
@Override public void filter(byte[] line, byte[] previousLine, int sampleBitCount) throws PngException { PngFilterType filterType = PngFilterType.forValue(line[0]); line[0] = 0; PngFilterType previousFilterType = PngFilterType.forValue(previousLine[0]); previousLine[0] = 0; switch (filterType) { case NONE: break; case SUB: { byte[] original = line.clone(); int previous = -(Math.max(1, sampleBitCount / 8) - 1); for (int x = 1, a = previous; x < line.length; x++, a++) { line[x] = (byte) (original[x] - ((a < 0) ? 0 : original[a])); } break; } case UP: { for (int x = 1; x < line.length; x++) { line[x] = (byte) (line[x] - previousLine[x]); } break; } case AVERAGE: { byte[] original = line.clone(); int previous = -(Math.max(1, sampleBitCount / 8) - 1); for (int x = 1, a = previous; x < line.length; x++, a++) { line[x] = (byte) (original[x] - ((0xFF & original[(a < 0) ? 0 : a]) + (0xFF & previousLine[x])) / 2); } break; } case PAETH: { byte[] original = line.clone(); int previous = -(Math.max(1, sampleBitCount / 8) - 1); for (int x = 1, a = previous; x < line.length; x++, a++) { int result = this.paethPredictor(original, previousLine, x, a); line[x] = (byte) (original[x] - result); } break; } default: throw new PngException("Unrecognized filter type " + filterType); } line[0] = filterType.getValue(); previousLine[0] = previousFilterType.getValue(); }
java
@Override public void filter(byte[] line, byte[] previousLine, int sampleBitCount) throws PngException { PngFilterType filterType = PngFilterType.forValue(line[0]); line[0] = 0; PngFilterType previousFilterType = PngFilterType.forValue(previousLine[0]); previousLine[0] = 0; switch (filterType) { case NONE: break; case SUB: { byte[] original = line.clone(); int previous = -(Math.max(1, sampleBitCount / 8) - 1); for (int x = 1, a = previous; x < line.length; x++, a++) { line[x] = (byte) (original[x] - ((a < 0) ? 0 : original[a])); } break; } case UP: { for (int x = 1; x < line.length; x++) { line[x] = (byte) (line[x] - previousLine[x]); } break; } case AVERAGE: { byte[] original = line.clone(); int previous = -(Math.max(1, sampleBitCount / 8) - 1); for (int x = 1, a = previous; x < line.length; x++, a++) { line[x] = (byte) (original[x] - ((0xFF & original[(a < 0) ? 0 : a]) + (0xFF & previousLine[x])) / 2); } break; } case PAETH: { byte[] original = line.clone(); int previous = -(Math.max(1, sampleBitCount / 8) - 1); for (int x = 1, a = previous; x < line.length; x++, a++) { int result = this.paethPredictor(original, previousLine, x, a); line[x] = (byte) (original[x] - result); } break; } default: throw new PngException("Unrecognized filter type " + filterType); } line[0] = filterType.getValue(); previousLine[0] = previousFilterType.getValue(); }
[ "@", "Override", "public", "void", "filter", "(", "byte", "[", "]", "line", ",", "byte", "[", "]", "previousLine", ",", "int", "sampleBitCount", ")", "throws", "PngException", "{", "PngFilterType", "filterType", "=", "PngFilterType", ".", "forValue", "(", "l...
{@inheritDoc} The bytes are named as follows (x = current, a = previous, b = above, c = previous and above) <pre> c b a x </pre>
[ "{", "@inheritDoc", "}" ]
train
https://github.com/depsypher/pngtastic/blob/13fd2a63dd8b2febd7041273889a1bba4f2a6a07/src/main/java/com/googlecode/pngtastic/core/processing/PngtasticFilterHandler.java#L86-L134
Codearte/catch-exception
catch-exception/src/main/java/com/googlecode/catchexception/CatchException.java
CatchException.verifyException
public static void verifyException(ThrowingCallable actor, Class<? extends Exception> clazz) { validateArguments(actor, clazz); catchException(actor, clazz, true); }
java
public static void verifyException(ThrowingCallable actor, Class<? extends Exception> clazz) { validateArguments(actor, clazz); catchException(actor, clazz, true); }
[ "public", "static", "void", "verifyException", "(", "ThrowingCallable", "actor", ",", "Class", "<", "?", "extends", "Exception", ">", "clazz", ")", "{", "validateArguments", "(", "actor", ",", "clazz", ")", ";", "catchException", "(", "actor", ",", "clazz", ...
Use it to verify that an exception of specific type is thrown and to get access to the thrown exception (for further verifications). The following example verifies that obj.doX() throws a MyException: <code>verifyException(obj, MyException.class).doX(); // catch and verify assert "foobar".equals(caughtException().getMessage()); // further analysis </code> If <code>doX()</code> does not throw a <code>MyException</code>, then a {@link ExceptionNotThrownAssertionError} is thrown. Otherwise the thrown exception can be retrieved via {@link #caughtException()}. @param actor The instance that shall be proxied. Must not be <code>null</code>. @param clazz The type of the exception that shall be thrown by the underlying object. Must not be <code>null</code>.
[ "Use", "it", "to", "verify", "that", "an", "exception", "of", "specific", "type", "is", "thrown", "and", "to", "get", "access", "to", "the", "thrown", "exception", "(", "for", "further", "verifications", ")", "." ]
train
https://github.com/Codearte/catch-exception/blob/8cfb1c0a68661ef622011484ff0061b41796b165/catch-exception/src/main/java/com/googlecode/catchexception/CatchException.java#L267-L270
FedericoPecora/meta-csp-framework
src/main/java/org/metacsp/multi/spatioTemporal/paths/TrajectoryEnvelope.java
TrajectoryEnvelope.makeInnerFootprint
public Geometry makeInnerFootprint(double x, double y, double theta) { AffineTransformation at = new AffineTransformation(); at.rotate(theta); at.translate(x,y); Geometry rect = at.transform(innerFootprint); return rect; }
java
public Geometry makeInnerFootprint(double x, double y, double theta) { AffineTransformation at = new AffineTransformation(); at.rotate(theta); at.translate(x,y); Geometry rect = at.transform(innerFootprint); return rect; }
[ "public", "Geometry", "makeInnerFootprint", "(", "double", "x", ",", "double", "y", ",", "double", "theta", ")", "{", "AffineTransformation", "at", "=", "new", "AffineTransformation", "(", ")", ";", "at", ".", "rotate", "(", "theta", ")", ";", "at", ".", ...
Returns a {@link Geometry} representing the inner footprint of the robot in a given pose. @param x The x coordinate of the pose used to create the inner footprint. @param y The y coordinate of the pose used to create the inner footprint. @param theta The orientation of the pose used to create the inner footprint. @return A {@link Geometry} representing the footprint of the inner robot in a given pose.
[ "Returns", "a", "{" ]
train
https://github.com/FedericoPecora/meta-csp-framework/blob/42aaef2e2b76d0f738427f0dd9653c4f62b40517/src/main/java/org/metacsp/multi/spatioTemporal/paths/TrajectoryEnvelope.java#L646-L652
super-csv/super-csv
super-csv-java8/src/main/java/org/supercsv/cellprocessor/time/FmtPeriod.java
FmtPeriod.execute
public Object execute(final Object value, final CsvContext context) { validateInputNotNull(value, context); if( !(value instanceof Period) ) { throw new SuperCsvCellProcessorException(Period.class, value, context, this); } final Period period = (Period) value; final String result = period.toString(); return next.execute(result, context); }
java
public Object execute(final Object value, final CsvContext context) { validateInputNotNull(value, context); if( !(value instanceof Period) ) { throw new SuperCsvCellProcessorException(Period.class, value, context, this); } final Period period = (Period) value; final String result = period.toString(); return next.execute(result, context); }
[ "public", "Object", "execute", "(", "final", "Object", "value", ",", "final", "CsvContext", "context", ")", "{", "validateInputNotNull", "(", "value", ",", "context", ")", ";", "if", "(", "!", "(", "value", "instanceof", "Period", ")", ")", "{", "throw", ...
{@inheritDoc} @throws SuperCsvCellProcessorException if value is null or not a Period
[ "{", "@inheritDoc", "}" ]
train
https://github.com/super-csv/super-csv/blob/f18db724674dc1c4116e25142c1b5403ebf43e96/super-csv-java8/src/main/java/org/supercsv/cellprocessor/time/FmtPeriod.java#L60-L69
hypercube1024/firefly
firefly-common/src/main/java/com/firefly/utils/lang/AtomicBiInteger.java
AtomicBiInteger.compareAndSet
public boolean compareAndSet(int expectHi, int hi, int expectLo, int lo) { long encoded = encode(expectHi, expectLo); long update = encode(hi, lo); return compareAndSet(encoded, update); }
java
public boolean compareAndSet(int expectHi, int hi, int expectLo, int lo) { long encoded = encode(expectHi, expectLo); long update = encode(hi, lo); return compareAndSet(encoded, update); }
[ "public", "boolean", "compareAndSet", "(", "int", "expectHi", ",", "int", "hi", ",", "int", "expectLo", ",", "int", "lo", ")", "{", "long", "encoded", "=", "encode", "(", "expectHi", ",", "expectLo", ")", ";", "long", "update", "=", "encode", "(", "hi"...
Atomically sets the hi and lo values to the given updated values only if the current hi and lo values {@code ==} the expected hi and lo values. @param expectHi the expected hi value @param hi the new hi value @param expectLo the expected lo value @param lo the new lo value @return {@code true} if successful. False return indicates that the actual hi and lo values were not equal to the expected hi and lo value.
[ "Atomically", "sets", "the", "hi", "and", "lo", "values", "to", "the", "given", "updated", "values", "only", "if", "the", "current", "hi", "and", "lo", "values", "{", "@code", "==", "}", "the", "expected", "hi", "and", "lo", "values", "." ]
train
https://github.com/hypercube1024/firefly/blob/ed3fc75b7c54a65b1e7d8141d01b49144bb423a3/firefly-common/src/main/java/com/firefly/utils/lang/AtomicBiInteger.java#L131-L135
mebigfatguy/fb-contrib
src/main/java/com/mebigfatguy/fbcontrib/detect/CopiedOverriddenMethod.java
CopiedOverriddenMethod.sameAccess
private static boolean sameAccess(int parentAccess, int childAccess) { return ((parentAccess & (Const.ACC_PUBLIC | Const.ACC_PROTECTED)) == (childAccess & (Const.ACC_PUBLIC | Const.ACC_PROTECTED))); }
java
private static boolean sameAccess(int parentAccess, int childAccess) { return ((parentAccess & (Const.ACC_PUBLIC | Const.ACC_PROTECTED)) == (childAccess & (Const.ACC_PUBLIC | Const.ACC_PROTECTED))); }
[ "private", "static", "boolean", "sameAccess", "(", "int", "parentAccess", ",", "int", "childAccess", ")", "{", "return", "(", "(", "parentAccess", "&", "(", "Const", ".", "ACC_PUBLIC", "|", "Const", ".", "ACC_PROTECTED", ")", ")", "==", "(", "childAccess", ...
determines if two access flags contain the same access modifiers @param parentAccess the access flags of the parent method @param childAccess the access flats of the child method @return whether the access modifiers are the same
[ "determines", "if", "two", "access", "flags", "contain", "the", "same", "access", "modifiers" ]
train
https://github.com/mebigfatguy/fb-contrib/blob/3b5203196f627b399fbcea3c2ab2b1f4e56cc7b8/src/main/java/com/mebigfatguy/fbcontrib/detect/CopiedOverriddenMethod.java#L255-L257
ineunetOS/knife-commons
knife-commons-utils/src/main/java/com/ineunet/knife/util/StringUtils.java
StringUtils.indexOfAny
public static int indexOfAny(String str, String searchChars) { if (isEmpty(str) || isEmpty(searchChars)) { return INDEX_NOT_FOUND; } return indexOfAny(str, searchChars.toCharArray()); }
java
public static int indexOfAny(String str, String searchChars) { if (isEmpty(str) || isEmpty(searchChars)) { return INDEX_NOT_FOUND; } return indexOfAny(str, searchChars.toCharArray()); }
[ "public", "static", "int", "indexOfAny", "(", "String", "str", ",", "String", "searchChars", ")", "{", "if", "(", "isEmpty", "(", "str", ")", "||", "isEmpty", "(", "searchChars", ")", ")", "{", "return", "INDEX_NOT_FOUND", ";", "}", "return", "indexOfAny",...
<p>Search a String to find the first index of any character in the given set of characters.</p> <p>A <code>null</code> String will return <code>-1</code>. A <code>null</code> search string will return <code>-1</code>.</p> <pre> StringUtils.indexOfAny(null, *) = -1 StringUtils.indexOfAny("", *) = -1 StringUtils.indexOfAny(*, null) = -1 StringUtils.indexOfAny(*, "") = -1 StringUtils.indexOfAny("zzabyycdxx", "za") = 0 StringUtils.indexOfAny("zzabyycdxx", "by") = 3 StringUtils.indexOfAny("aba","z") = -1 </pre> @param str the String to check, may be null @param searchChars the chars to search for, may be null @return the index of any of the chars, -1 if no match or null input @since 2.0
[ "<p", ">", "Search", "a", "String", "to", "find", "the", "first", "index", "of", "any", "character", "in", "the", "given", "set", "of", "characters", ".", "<", "/", "p", ">" ]
train
https://github.com/ineunetOS/knife-commons/blob/eae9e59afa020a00ae8977c10d43ac8ae46ae236/knife-commons-utils/src/main/java/com/ineunet/knife/util/StringUtils.java#L1351-L1356
hsiafan/apk-parser
src/main/java/net/dongliu/apk/parser/cert/asn1/ber/InputStreamBerDataValueReader.java
InputStreamBerDataValueReader.readDataValue
@SuppressWarnings("resource") private static BerDataValue readDataValue(InputStream input) throws BerDataValueFormatException { RecordingInputStream in = new RecordingInputStream(input); try { int firstIdentifierByte = in.read(); if (firstIdentifierByte == -1) { // End of input return null; } int tagNumber = readTagNumber(in, firstIdentifierByte); int firstLengthByte = in.read(); if (firstLengthByte == -1) { throw new BerDataValueFormatException("Missing length"); } boolean constructed = BerEncoding.isConstructed((byte) firstIdentifierByte); int contentsLength; int contentsOffsetInDataValue; if ((firstLengthByte & 0x80) == 0) { // short form length contentsLength = readShortFormLength(firstLengthByte); contentsOffsetInDataValue = in.getReadByteCount(); skipDefiniteLengthContents(in, contentsLength); } else if ((firstLengthByte & 0xff) != 0x80) { // long form length contentsLength = readLongFormLength(in, firstLengthByte); contentsOffsetInDataValue = in.getReadByteCount(); skipDefiniteLengthContents(in, contentsLength); } else { // indefinite length contentsOffsetInDataValue = in.getReadByteCount(); contentsLength = constructed ? skipConstructedIndefiniteLengthContents(in) : skipPrimitiveIndefiniteLengthContents(in); } byte[] encoded = in.getReadBytes(); ByteBuffer encodedContents = ByteBuffer.wrap(encoded, contentsOffsetInDataValue, contentsLength); return new BerDataValue( ByteBuffer.wrap(encoded), encodedContents, BerEncoding.getTagClass((byte) firstIdentifierByte), constructed, tagNumber); } catch (IOException e) { throw new BerDataValueFormatException("Failed to read data value", e); } }
java
@SuppressWarnings("resource") private static BerDataValue readDataValue(InputStream input) throws BerDataValueFormatException { RecordingInputStream in = new RecordingInputStream(input); try { int firstIdentifierByte = in.read(); if (firstIdentifierByte == -1) { // End of input return null; } int tagNumber = readTagNumber(in, firstIdentifierByte); int firstLengthByte = in.read(); if (firstLengthByte == -1) { throw new BerDataValueFormatException("Missing length"); } boolean constructed = BerEncoding.isConstructed((byte) firstIdentifierByte); int contentsLength; int contentsOffsetInDataValue; if ((firstLengthByte & 0x80) == 0) { // short form length contentsLength = readShortFormLength(firstLengthByte); contentsOffsetInDataValue = in.getReadByteCount(); skipDefiniteLengthContents(in, contentsLength); } else if ((firstLengthByte & 0xff) != 0x80) { // long form length contentsLength = readLongFormLength(in, firstLengthByte); contentsOffsetInDataValue = in.getReadByteCount(); skipDefiniteLengthContents(in, contentsLength); } else { // indefinite length contentsOffsetInDataValue = in.getReadByteCount(); contentsLength = constructed ? skipConstructedIndefiniteLengthContents(in) : skipPrimitiveIndefiniteLengthContents(in); } byte[] encoded = in.getReadBytes(); ByteBuffer encodedContents = ByteBuffer.wrap(encoded, contentsOffsetInDataValue, contentsLength); return new BerDataValue( ByteBuffer.wrap(encoded), encodedContents, BerEncoding.getTagClass((byte) firstIdentifierByte), constructed, tagNumber); } catch (IOException e) { throw new BerDataValueFormatException("Failed to read data value", e); } }
[ "@", "SuppressWarnings", "(", "\"resource\"", ")", "private", "static", "BerDataValue", "readDataValue", "(", "InputStream", "input", ")", "throws", "BerDataValueFormatException", "{", "RecordingInputStream", "in", "=", "new", "RecordingInputStream", "(", "input", ")", ...
Returns the next data value or {@code null} if end of input has been reached. @throws BerDataValueFormatException if the value being read is malformed.
[ "Returns", "the", "next", "data", "value", "or", "{", "@code", "null", "}", "if", "end", "of", "input", "has", "been", "reached", "." ]
train
https://github.com/hsiafan/apk-parser/blob/8993ddd52017b37b8f2e784ae0a15417d9ede932/src/main/java/net/dongliu/apk/parser/cert/asn1/ber/InputStreamBerDataValueReader.java#L48-L100
Ordinastie/MalisisCore
src/main/java/net/malisis/core/util/TileEntityUtils.java
TileEntityUtils.getTileEntity
public static <T> T getTileEntity(Class<T> clazz, IBlockAccess world, BlockPos pos) { if (world == null) return null; TileEntity te = world.getTileEntity(pos); return te != null && clazz.isAssignableFrom(te.getClass()) ? Silenced.get(() -> clazz.cast(te)) : null; }
java
public static <T> T getTileEntity(Class<T> clazz, IBlockAccess world, BlockPos pos) { if (world == null) return null; TileEntity te = world.getTileEntity(pos); return te != null && clazz.isAssignableFrom(te.getClass()) ? Silenced.get(() -> clazz.cast(te)) : null; }
[ "public", "static", "<", "T", ">", "T", "getTileEntity", "(", "Class", "<", "T", ">", "clazz", ",", "IBlockAccess", "world", ",", "BlockPos", "pos", ")", "{", "if", "(", "world", "==", "null", ")", "return", "null", ";", "TileEntity", "te", "=", "wor...
Gets the {@link TileEntity} of type <b>T</b> at the specified {@link BlockPos}.<br> If no <code>TileEntity</code> was found at the coordinates, or if the <code>TileEntity</code> is not of type <b>T</b>, returns <code>null</code> instead. @param <T> type of TileEntity requested @param clazz the class of the TileEntity @param world the world @param pos the pos @return the tile entity at the coordinates, or null if no tile entity, or not of type T
[ "Gets", "the", "{", "@link", "TileEntity", "}", "of", "type", "<b", ">", "T<", "/", "b", ">", "at", "the", "specified", "{", "@link", "BlockPos", "}", ".", "<br", ">", "If", "no", "<code", ">", "TileEntity<", "/", "code", ">", "was", "found", "at",...
train
https://github.com/Ordinastie/MalisisCore/blob/4f8e1fa462d5c372fc23414482ba9f429881cc54/src/main/java/net/malisis/core/util/TileEntityUtils.java#L61-L68
Bedework/bw-util
bw-util-options/src/main/java/org/bedework/util/options/Options.java
Options.toXml
public void toXml(final OptionElement root, final OutputStream str) throws OptionsException { Writer wtr = null; try { XmlEmit xml = new XmlEmit(true); wtr = new OutputStreamWriter(str); xml.startEmit(wtr); xml.openTag(outerTag); for (OptionElement oe: root.getChildren()) { childToXml(oe, xml); } xml.closeTag(outerTag); } catch (OptionsException ce) { throw ce; } catch (Throwable t) { throw new OptionsException(t); } finally { if (wtr != null) { try { wtr.close(); } catch (Throwable t) {} } } }
java
public void toXml(final OptionElement root, final OutputStream str) throws OptionsException { Writer wtr = null; try { XmlEmit xml = new XmlEmit(true); wtr = new OutputStreamWriter(str); xml.startEmit(wtr); xml.openTag(outerTag); for (OptionElement oe: root.getChildren()) { childToXml(oe, xml); } xml.closeTag(outerTag); } catch (OptionsException ce) { throw ce; } catch (Throwable t) { throw new OptionsException(t); } finally { if (wtr != null) { try { wtr.close(); } catch (Throwable t) {} } } }
[ "public", "void", "toXml", "(", "final", "OptionElement", "root", ",", "final", "OutputStream", "str", ")", "throws", "OptionsException", "{", "Writer", "wtr", "=", "null", ";", "try", "{", "XmlEmit", "xml", "=", "new", "XmlEmit", "(", "true", ")", ";", ...
Emit the options as xml. @param root @param str @throws OptionsException
[ "Emit", "the", "options", "as", "xml", "." ]
train
https://github.com/Bedework/bw-util/blob/f51de4af3d7eb88fe63a0e22be8898a16c6cc3ad/bw-util-options/src/main/java/org/bedework/util/options/Options.java#L202-L229
killbilling/recurly-java-library
src/main/java/com/ning/billing/recurly/RecurlyClient.java
RecurlyClient.getAccountBalance
public AccountBalance getAccountBalance(final String accountCode) { return doGET(Account.ACCOUNT_RESOURCE + "/" + accountCode + AccountBalance.ACCOUNT_BALANCE_RESOURCE, AccountBalance.class); }
java
public AccountBalance getAccountBalance(final String accountCode) { return doGET(Account.ACCOUNT_RESOURCE + "/" + accountCode + AccountBalance.ACCOUNT_BALANCE_RESOURCE, AccountBalance.class); }
[ "public", "AccountBalance", "getAccountBalance", "(", "final", "String", "accountCode", ")", "{", "return", "doGET", "(", "Account", ".", "ACCOUNT_RESOURCE", "+", "\"/\"", "+", "accountCode", "+", "AccountBalance", ".", "ACCOUNT_BALANCE_RESOURCE", ",", "AccountBalance...
Get Account Balance <p> Retrieves the remaining balance on the account @param accountCode recurly account id @return the updated AccountBalance if success, null otherwise
[ "Get", "Account", "Balance", "<p", ">", "Retrieves", "the", "remaining", "balance", "on", "the", "account" ]
train
https://github.com/killbilling/recurly-java-library/blob/5e05eedd91885a51e1aa8293bd41139d082cf7f4/src/main/java/com/ning/billing/recurly/RecurlyClient.java#L337-L339
apache/incubator-druid
core/src/main/java/org/apache/druid/java/util/common/io/NativeIO.java
NativeIO.trySyncFileRange
private static void trySyncFileRange(int fd, long offset, long nbytes, int flags) { if (!initialized || !syncFileRangePossible || fd < 0) { return; } try { int ret_code = sync_file_range(fd, offset, nbytes, flags); if (ret_code != 0) { log.warn("failed on syncing fd [%d], offset [%d], bytes [%d], ret_code [%d], errno [%d]", fd, offset, nbytes, ret_code, Native.getLastError()); return; } } catch (UnsupportedOperationException uoe) { log.warn(uoe, "sync_file_range is not supported"); syncFileRangePossible = false; } catch (UnsatisfiedLinkError nle) { log.warn(nle, "sync_file_range failed on fd [%d], offset [%d], bytes [%d]", fd, offset, nbytes); syncFileRangePossible = false; } catch (Exception e) { log.warn(e, "Unknown exception: sync_file_range failed on fd [%d], offset [%d], bytes [%d]", fd, offset, nbytes); syncFileRangePossible = false; } }
java
private static void trySyncFileRange(int fd, long offset, long nbytes, int flags) { if (!initialized || !syncFileRangePossible || fd < 0) { return; } try { int ret_code = sync_file_range(fd, offset, nbytes, flags); if (ret_code != 0) { log.warn("failed on syncing fd [%d], offset [%d], bytes [%d], ret_code [%d], errno [%d]", fd, offset, nbytes, ret_code, Native.getLastError()); return; } } catch (UnsupportedOperationException uoe) { log.warn(uoe, "sync_file_range is not supported"); syncFileRangePossible = false; } catch (UnsatisfiedLinkError nle) { log.warn(nle, "sync_file_range failed on fd [%d], offset [%d], bytes [%d]", fd, offset, nbytes); syncFileRangePossible = false; } catch (Exception e) { log.warn(e, "Unknown exception: sync_file_range failed on fd [%d], offset [%d], bytes [%d]", fd, offset, nbytes); syncFileRangePossible = false; } }
[ "private", "static", "void", "trySyncFileRange", "(", "int", "fd", ",", "long", "offset", ",", "long", "nbytes", ",", "int", "flags", ")", "{", "if", "(", "!", "initialized", "||", "!", "syncFileRangePossible", "||", "fd", "<", "0", ")", "{", "return", ...
Sync part of an open file to the file system. @param fd The file descriptor of the source file. @param offset The offset within the file. @param nbytes The number of bytes to be synced. @param flags Signal how to synchronize
[ "Sync", "part", "of", "an", "open", "file", "to", "the", "file", "system", "." ]
train
https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/core/src/main/java/org/apache/druid/java/util/common/io/NativeIO.java#L167-L193
paymill/paymill-java
src/main/java/com/paymill/services/RefundService.java
RefundService.refundTransaction
public Refund refundTransaction( String transactionId, Integer amount ) { return this.refundTransaction( new Transaction( transactionId ), amount, null ); }
java
public Refund refundTransaction( String transactionId, Integer amount ) { return this.refundTransaction( new Transaction( transactionId ), amount, null ); }
[ "public", "Refund", "refundTransaction", "(", "String", "transactionId", ",", "Integer", "amount", ")", "{", "return", "this", ".", "refundTransaction", "(", "new", "Transaction", "(", "transactionId", ")", ",", "amount", ",", "null", ")", ";", "}" ]
This function refunds a {@link Transaction} that has been created previously and was refunded in parts or wasn't refunded at all. The inserted amount will be refunded to the credit card / direct debit of the original {@link Transaction}. There will be some fees for the merchant for every refund. <p> Note: <ul> <li>You can refund parts of a transaction until the transaction amount is fully refunded. But be careful there will be a fee for every refund</li> <li>There is no need to define a currency for refunds, because they will be in the same currency as the original transaction</li> </ul> @param transactionId Id of {@link Transaction}, which will be refunded. @param amount Amount (in cents) which will be charged. @return A {@link Refund} for the given {@link Transaction}.
[ "This", "function", "refunds", "a", "{" ]
train
https://github.com/paymill/paymill-java/blob/17281a0d4376c76f1711af9f09bfc138c90ba65a/src/main/java/com/paymill/services/RefundService.java#L134-L136
spring-projects/spring-android
spring-android-core/src/main/java/org/springframework/util/ReflectionUtils.java
ReflectionUtils.doWithFields
public static void doWithFields(Class<?> clazz, FieldCallback fc, FieldFilter ff) throws IllegalArgumentException { // Keep backing up the inheritance hierarchy. Class<?> targetClass = clazz; do { Field[] fields = targetClass.getDeclaredFields(); for (Field field : fields) { // Skip static and final fields. if (ff != null && !ff.matches(field)) { continue; } try { fc.doWith(field); } catch (IllegalAccessException ex) { throw new IllegalStateException("Shouldn't be illegal to access field '" + field.getName() + "': " + ex); } } targetClass = targetClass.getSuperclass(); } while (targetClass != null && targetClass != Object.class); }
java
public static void doWithFields(Class<?> clazz, FieldCallback fc, FieldFilter ff) throws IllegalArgumentException { // Keep backing up the inheritance hierarchy. Class<?> targetClass = clazz; do { Field[] fields = targetClass.getDeclaredFields(); for (Field field : fields) { // Skip static and final fields. if (ff != null && !ff.matches(field)) { continue; } try { fc.doWith(field); } catch (IllegalAccessException ex) { throw new IllegalStateException("Shouldn't be illegal to access field '" + field.getName() + "': " + ex); } } targetClass = targetClass.getSuperclass(); } while (targetClass != null && targetClass != Object.class); }
[ "public", "static", "void", "doWithFields", "(", "Class", "<", "?", ">", "clazz", ",", "FieldCallback", "fc", ",", "FieldFilter", "ff", ")", "throws", "IllegalArgumentException", "{", "// Keep backing up the inheritance hierarchy.", "Class", "<", "?", ">", "targetCl...
Invoke the given callback on all fields in the target class, going up the class hierarchy to get all declared fields. @param clazz the target class to analyze @param fc the callback to invoke for each field @param ff the filter that determines the fields to apply the callback to
[ "Invoke", "the", "given", "callback", "on", "all", "fields", "in", "the", "target", "class", "going", "up", "the", "class", "hierarchy", "to", "get", "all", "declared", "fields", "." ]
train
https://github.com/spring-projects/spring-android/blob/941296e152d49a40e0745a3e81628a974f72b7e4/spring-android-core/src/main/java/org/springframework/util/ReflectionUtils.java#L567-L589
dlew/joda-time-android
library/src/main/java/net/danlew/android/joda/DateUtils.java
DateUtils.getRelativeTimeSpanString
public static CharSequence getRelativeTimeSpanString(Context ctx, ReadableInstant time, boolean withPreposition) { String result; LocalDate now = LocalDate.now(); LocalDate timeDate = new LocalDate(time); int prepositionId; if (Days.daysBetween(now, timeDate).getDays() == 0) { // Same day int flags = FORMAT_SHOW_TIME; result = formatDateRange(ctx, time, time, flags); prepositionId = R.string.joda_time_android_preposition_for_time; } else if (Years.yearsBetween(now, timeDate).getYears() != 0) { // Different years int flags = FORMAT_SHOW_DATE | FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE; result = formatDateRange(ctx, time, time, flags); // This is a date (like "10/31/2008" so use the date preposition) prepositionId = R.string.joda_time_android_preposition_for_date; } else { // Default int flags = FORMAT_SHOW_DATE | FORMAT_ABBREV_MONTH; result = formatDateRange(ctx, time, time, flags); prepositionId = R.string.joda_time_android_preposition_for_date; } if (withPreposition) { result = ctx.getString(prepositionId, result); } return result; }
java
public static CharSequence getRelativeTimeSpanString(Context ctx, ReadableInstant time, boolean withPreposition) { String result; LocalDate now = LocalDate.now(); LocalDate timeDate = new LocalDate(time); int prepositionId; if (Days.daysBetween(now, timeDate).getDays() == 0) { // Same day int flags = FORMAT_SHOW_TIME; result = formatDateRange(ctx, time, time, flags); prepositionId = R.string.joda_time_android_preposition_for_time; } else if (Years.yearsBetween(now, timeDate).getYears() != 0) { // Different years int flags = FORMAT_SHOW_DATE | FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE; result = formatDateRange(ctx, time, time, flags); // This is a date (like "10/31/2008" so use the date preposition) prepositionId = R.string.joda_time_android_preposition_for_date; } else { // Default int flags = FORMAT_SHOW_DATE | FORMAT_ABBREV_MONTH; result = formatDateRange(ctx, time, time, flags); prepositionId = R.string.joda_time_android_preposition_for_date; } if (withPreposition) { result = ctx.getString(prepositionId, result); } return result; }
[ "public", "static", "CharSequence", "getRelativeTimeSpanString", "(", "Context", "ctx", ",", "ReadableInstant", "time", ",", "boolean", "withPreposition", ")", "{", "String", "result", ";", "LocalDate", "now", "=", "LocalDate", ".", "now", "(", ")", ";", "LocalD...
Returns a relative time string to display the time expressed by millis. See {@link android.text.format.DateUtils#getRelativeTimeSpanString} for full docs. @param withPreposition If true, the string returned will include the correct preposition ("at 9:20am", "on 10/12/2008" or "on May 29").
[ "Returns", "a", "relative", "time", "string", "to", "display", "the", "time", "expressed", "by", "millis", "." ]
train
https://github.com/dlew/joda-time-android/blob/5bf96f6ef4ea63ee91e73e1e528896fa00108dec/library/src/main/java/net/danlew/android/joda/DateUtils.java#L363-L395
nguillaumin/slick2d-maven
slick2d-hiero/src/main/java/org/newdawn/slick/tools/hiero/truetype/TTFSubSetFile.java
TTFSubSetFile.writeUShort
private void writeUShort(int pos, int s) { byte b1 = (byte)((s >> 8) & 0xff); byte b2 = (byte)(s & 0xff); output[pos] = b1; output[pos + 1] = b2; }
java
private void writeUShort(int pos, int s) { byte b1 = (byte)((s >> 8) & 0xff); byte b2 = (byte)(s & 0xff); output[pos] = b1; output[pos + 1] = b2; }
[ "private", "void", "writeUShort", "(", "int", "pos", ",", "int", "s", ")", "{", "byte", "b1", "=", "(", "byte", ")", "(", "(", "s", ">>", "8", ")", "&", "0xff", ")", ";", "byte", "b2", "=", "(", "byte", ")", "(", "s", "&", "0xff", ")", ";",...
Appends a USHORT to the output array, at the given position without changing currentPos @param pos The position to write to @param s The short to be written
[ "Appends", "a", "USHORT", "to", "the", "output", "array", "at", "the", "given", "position", "without", "changing", "currentPos" ]
train
https://github.com/nguillaumin/slick2d-maven/blob/8251f88a0ed6a70e726d2468842455cd1f80893f/slick2d-hiero/src/main/java/org/newdawn/slick/tools/hiero/truetype/TTFSubSetFile.java#L825-L830
marklogic/java-client-api
marklogic-client-api/src/main/java/com/marklogic/client/query/StructuredQueryBuilder.java
StructuredQueryBuilder.wordConstraint
public StructuredQueryDefinition wordConstraint(String constraintName, double weight, String... words) { return new WordConstraintQuery(constraintName, weight, words); }
java
public StructuredQueryDefinition wordConstraint(String constraintName, double weight, String... words) { return new WordConstraintQuery(constraintName, weight, words); }
[ "public", "StructuredQueryDefinition", "wordConstraint", "(", "String", "constraintName", ",", "double", "weight", ",", "String", "...", "words", ")", "{", "return", "new", "WordConstraintQuery", "(", "constraintName", ",", "weight", ",", "words", ")", ";", "}" ]
Matches the container specified by the constraint when it has at least one of the criteria words. @param constraintName the constraint definition @param weight the multiplier for the match in the document ranking @param words the possible words to match @return the StructuredQueryDefinition for the word constraint query
[ "Matches", "the", "container", "specified", "by", "the", "constraint", "when", "it", "has", "at", "least", "one", "of", "the", "criteria", "words", "." ]
train
https://github.com/marklogic/java-client-api/blob/acf60229a928abd4a8cc4b21b641d56957467da7/marklogic-client-api/src/main/java/com/marklogic/client/query/StructuredQueryBuilder.java#L1067-L1069
OpenLiberty/open-liberty
dev/com.ibm.ws.jaxrs.2.0.common/src/org/apache/cxf/jaxrs/utils/ThreadLocalProxyCopyOnWriteArrayList.java
ThreadLocalProxyCopyOnWriteArrayList.lastIndexOf
private static int lastIndexOf(Object o, Object[] elements, int index) { if (o == null) { for (int i = index; i >= 0; i--) if (elements[i] == null) return i; } else { for (int i = index; i >= 0; i--) if (o.equals(elements[i])) return i; } return -1; }
java
private static int lastIndexOf(Object o, Object[] elements, int index) { if (o == null) { for (int i = index; i >= 0; i--) if (elements[i] == null) return i; } else { for (int i = index; i >= 0; i--) if (o.equals(elements[i])) return i; } return -1; }
[ "private", "static", "int", "lastIndexOf", "(", "Object", "o", ",", "Object", "[", "]", "elements", ",", "int", "index", ")", "{", "if", "(", "o", "==", "null", ")", "{", "for", "(", "int", "i", "=", "index", ";", "i", ">=", "0", ";", "i", "--"...
static version of lastIndexOf. @param o element to search for @param elements the array @param index first index to search @return index of element, or -1 if absent
[ "static", "version", "of", "lastIndexOf", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jaxrs.2.0.common/src/org/apache/cxf/jaxrs/utils/ThreadLocalProxyCopyOnWriteArrayList.java#L142-L153
aws/aws-sdk-java
aws-java-sdk-codepipeline/src/main/java/com/amazonaws/services/codepipeline/model/ActionDeclaration.java
ActionDeclaration.withConfiguration
public ActionDeclaration withConfiguration(java.util.Map<String, String> configuration) { setConfiguration(configuration); return this; }
java
public ActionDeclaration withConfiguration(java.util.Map<String, String> configuration) { setConfiguration(configuration); return this; }
[ "public", "ActionDeclaration", "withConfiguration", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "configuration", ")", "{", "setConfiguration", "(", "configuration", ")", ";", "return", "this", ";", "}" ]
<p> The action declaration's configuration. </p> @param configuration The action declaration's configuration. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "The", "action", "declaration", "s", "configuration", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-codepipeline/src/main/java/com/amazonaws/services/codepipeline/model/ActionDeclaration.java#L236-L239
Netflix/spectator
spectator-api/src/main/java/com/netflix/spectator/api/patterns/CardinalityLimiters.java
CardinalityLimiters.mostFrequent
static Function<String, String> mostFrequent(int n, Clock clock) { return new MostFrequentLimiter(Math.min(n, MAX_LIMIT), clock); }
java
static Function<String, String> mostFrequent(int n, Clock clock) { return new MostFrequentLimiter(Math.min(n, MAX_LIMIT), clock); }
[ "static", "Function", "<", "String", ",", "String", ">", "mostFrequent", "(", "int", "n", ",", "Clock", "clock", ")", "{", "return", "new", "MostFrequentLimiter", "(", "Math", ".", "min", "(", "n", ",", "MAX_LIMIT", ")", ",", "clock", ")", ";", "}" ]
Allows the clock to be specified for testing. See {@link #mostFrequent(int)} for details on the usage.
[ "Allows", "the", "clock", "to", "be", "specified", "for", "testing", ".", "See", "{" ]
train
https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-api/src/main/java/com/netflix/spectator/api/patterns/CardinalityLimiters.java#L138-L140
Azure/azure-sdk-for-java
compute/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/compute/v2017_12_01/implementation/VirtualMachineScaleSetsInner.java
VirtualMachineScaleSetsInner.forceRecoveryServiceFabricPlatformUpdateDomainWalkAsync
public Observable<RecoveryWalkResponseInner> forceRecoveryServiceFabricPlatformUpdateDomainWalkAsync(String resourceGroupName, String vmScaleSetName, int platformUpdateDomain) { return forceRecoveryServiceFabricPlatformUpdateDomainWalkWithServiceResponseAsync(resourceGroupName, vmScaleSetName, platformUpdateDomain).map(new Func1<ServiceResponse<RecoveryWalkResponseInner>, RecoveryWalkResponseInner>() { @Override public RecoveryWalkResponseInner call(ServiceResponse<RecoveryWalkResponseInner> response) { return response.body(); } }); }
java
public Observable<RecoveryWalkResponseInner> forceRecoveryServiceFabricPlatformUpdateDomainWalkAsync(String resourceGroupName, String vmScaleSetName, int platformUpdateDomain) { return forceRecoveryServiceFabricPlatformUpdateDomainWalkWithServiceResponseAsync(resourceGroupName, vmScaleSetName, platformUpdateDomain).map(new Func1<ServiceResponse<RecoveryWalkResponseInner>, RecoveryWalkResponseInner>() { @Override public RecoveryWalkResponseInner call(ServiceResponse<RecoveryWalkResponseInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "RecoveryWalkResponseInner", ">", "forceRecoveryServiceFabricPlatformUpdateDomainWalkAsync", "(", "String", "resourceGroupName", ",", "String", "vmScaleSetName", ",", "int", "platformUpdateDomain", ")", "{", "return", "forceRecoveryServiceFabricPlatfo...
Manual platform update domain walk to update virtual machines in a service fabric virtual machine scale set. @param resourceGroupName The name of the resource group. @param vmScaleSetName The name of the VM scale set. @param platformUpdateDomain The platform update domain for which a manual recovery walk is requested @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the RecoveryWalkResponseInner object
[ "Manual", "platform", "update", "domain", "walk", "to", "update", "virtual", "machines", "in", "a", "service", "fabric", "virtual", "machine", "scale", "set", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/compute/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/compute/v2017_12_01/implementation/VirtualMachineScaleSetsInner.java#L4384-L4391
Stratio/stratio-connector-commons
connector-commons/src/main/java/com/stratio/connector/commons/engine/CommonsStorageEngine.java
CommonsStorageEngine.truncate
@Override public final void truncate(ClusterName targetCluster, TableName tableName) throws UnsupportedException, ExecutionException { try { connectionHandler.startJob(targetCluster.getName()); if (logger.isDebugEnabled()) { logger.debug( "Tuncating table [" + tableName.getName() + "] in cluster [" + targetCluster.getName() + "]"); } truncate(tableName, connectionHandler.getConnection(targetCluster.getName())); if (logger.isDebugEnabled()) { logger.debug("The table [" + tableName.getName() + "] has been successfully truncated in cluster [" + targetCluster.getName() + "]"); } } finally { connectionHandler.endJob(targetCluster.getName()); } }
java
@Override public final void truncate(ClusterName targetCluster, TableName tableName) throws UnsupportedException, ExecutionException { try { connectionHandler.startJob(targetCluster.getName()); if (logger.isDebugEnabled()) { logger.debug( "Tuncating table [" + tableName.getName() + "] in cluster [" + targetCluster.getName() + "]"); } truncate(tableName, connectionHandler.getConnection(targetCluster.getName())); if (logger.isDebugEnabled()) { logger.debug("The table [" + tableName.getName() + "] has been successfully truncated in cluster [" + targetCluster.getName() + "]"); } } finally { connectionHandler.endJob(targetCluster.getName()); } }
[ "@", "Override", "public", "final", "void", "truncate", "(", "ClusterName", "targetCluster", ",", "TableName", "tableName", ")", "throws", "UnsupportedException", ",", "ExecutionException", "{", "try", "{", "connectionHandler", ".", "startJob", "(", "targetCluster", ...
This method deletes all the rows of a table. @param targetCluster Target cluster. @param tableName Target table name including fully qualified including catalog. @throws UnsupportedException @throws ExecutionException
[ "This", "method", "deletes", "all", "the", "rows", "of", "a", "table", "." ]
train
https://github.com/Stratio/stratio-connector-commons/blob/d7cc66cb9591344a13055962e87a91f01c3707d1/connector-commons/src/main/java/com/stratio/connector/commons/engine/CommonsStorageEngine.java#L196-L215
JOML-CI/JOML
src/org/joml/Matrix3f.java
Matrix3f.rotateTowards
public Matrix3f rotateTowards(float dirX, float dirY, float dirZ, float upX, float upY, float upZ) { return rotateTowards(dirX, dirY, dirZ, upX, upY, upZ, this); }
java
public Matrix3f rotateTowards(float dirX, float dirY, float dirZ, float upX, float upY, float upZ) { return rotateTowards(dirX, dirY, dirZ, upX, upY, upZ, this); }
[ "public", "Matrix3f", "rotateTowards", "(", "float", "dirX", ",", "float", "dirY", ",", "float", "dirZ", ",", "float", "upX", ",", "float", "upY", ",", "float", "upZ", ")", "{", "return", "rotateTowards", "(", "dirX", ",", "dirY", ",", "dirZ", ",", "up...
Apply a model transformation to this matrix for a right-handed coordinate system, that aligns the local <code>+Z</code> axis with <code>direction</code>. <p> If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookat matrix, then the new matrix will be <code>M * L</code>. So when transforming a vector <code>v</code> with the new matrix by using <code>M * L * v</code>, the lookat transformation will be applied first! <p> In order to set the matrix to a rotation transformation without post-multiplying it, use {@link #rotationTowards(float, float, float, float, float, float) rotationTowards()}. <p> This method is equivalent to calling: <code>mul(new Matrix3f().lookAlong(-dirX, -dirY, -dirZ, upX, upY, upZ).invert())</code> @see #rotateTowards(Vector3fc, Vector3fc) @see #rotationTowards(float, float, float, float, float, float) @param dirX the x-coordinate of the direction to rotate towards @param dirY the y-coordinate of the direction to rotate towards @param dirZ the z-coordinate of the direction to rotate towards @param upX the x-coordinate of the up vector @param upY the y-coordinate of the up vector @param upZ the z-coordinate of the up vector @return this
[ "Apply", "a", "model", "transformation", "to", "this", "matrix", "for", "a", "right", "-", "handed", "coordinate", "system", "that", "aligns", "the", "local", "<code", ">", "+", "Z<", "/", "code", ">", "axis", "with", "<code", ">", "direction<", "/", "co...
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix3f.java#L3922-L3924
OpenNTF/JavascriptAggregator
jaggr-core/src/main/java/com/ibm/jaggr/core/impl/cache/CacheManagerImpl.java
CacheManagerImpl.serializeCache
@Override public void serializeCache() { final String sourceMethod = "serializeCache"; //$NON-NLS-1$ // Queue up the serialization behind any pending cache file creations. Future<Void> future = _aggregator.getExecutors().getFileCreateExecutor().submit(new Callable<Void>() { public Void call() { // Synchronize on the cache object to keep the scheduled cache sync thread and // the thread processing servlet destroy from colliding. synchronized(cacheSerializerSyncObj) { File cacheFile = new File(_directory, CACHE_META_FILENAME); File controlFile = new File(new File(_directory, ".."), CacheControl.CONTROL_SERIALIZATION_FILENAME); //$NON-NLS-1$ try { // Serialize the cache ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(cacheFile)); os.writeObject(_cache.get()); os.close(); // Serialize the control object to the parent directory so the // aggregator can manage the cache primer os = new ObjectOutputStream(new FileOutputStream(controlFile)); os.writeObject(_cache.get().getControlObj()); os.close(); } catch(Exception e) { throw new RuntimeException(e); } } return null; } }); // Wait for the serialization to complete before returning. try { SignalUtil.get(future, sourceClass, sourceMethod); } catch (Exception e) { if (log.isLoggable(Level.SEVERE)) log.log(Level.SEVERE, e.getMessage(), e); throw new RuntimeException(e); } }
java
@Override public void serializeCache() { final String sourceMethod = "serializeCache"; //$NON-NLS-1$ // Queue up the serialization behind any pending cache file creations. Future<Void> future = _aggregator.getExecutors().getFileCreateExecutor().submit(new Callable<Void>() { public Void call() { // Synchronize on the cache object to keep the scheduled cache sync thread and // the thread processing servlet destroy from colliding. synchronized(cacheSerializerSyncObj) { File cacheFile = new File(_directory, CACHE_META_FILENAME); File controlFile = new File(new File(_directory, ".."), CacheControl.CONTROL_SERIALIZATION_FILENAME); //$NON-NLS-1$ try { // Serialize the cache ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(cacheFile)); os.writeObject(_cache.get()); os.close(); // Serialize the control object to the parent directory so the // aggregator can manage the cache primer os = new ObjectOutputStream(new FileOutputStream(controlFile)); os.writeObject(_cache.get().getControlObj()); os.close(); } catch(Exception e) { throw new RuntimeException(e); } } return null; } }); // Wait for the serialization to complete before returning. try { SignalUtil.get(future, sourceClass, sourceMethod); } catch (Exception e) { if (log.isLoggable(Level.SEVERE)) log.log(Level.SEVERE, e.getMessage(), e); throw new RuntimeException(e); } }
[ "@", "Override", "public", "void", "serializeCache", "(", ")", "{", "final", "String", "sourceMethod", "=", "\"serializeCache\"", ";", "//$NON-NLS-1$\r", "// Queue up the serialization behind any pending cache file creations.\r", "Future", "<", "Void", ">", "future", "=", ...
Serializes the specified cache object to the sepecified directory. Note that we actually serialize a clone of the specified cache because some of the objects that are serialized require synchronization and we don't want to cause service threads to block while we are doing file I/O.
[ "Serializes", "the", "specified", "cache", "object", "to", "the", "sepecified", "directory", ".", "Note", "that", "we", "actually", "serialize", "a", "clone", "of", "the", "specified", "cache", "because", "some", "of", "the", "objects", "that", "are", "seriali...
train
https://github.com/OpenNTF/JavascriptAggregator/blob/9f47a96d778251638b1df9a368462176216d5b29/jaggr-core/src/main/java/com/ibm/jaggr/core/impl/cache/CacheManagerImpl.java#L288-L326
albfernandez/itext2
src/main/java/com/lowagie/text/Image.java
Image.scaleToFit
public void scaleToFit(float fitWidth, float fitHeight) { scalePercent(100); float percentX = (fitWidth * 100) / getScaledWidth(); float percentY = (fitHeight * 100) / getScaledHeight(); scalePercent(percentX < percentY ? percentX : percentY); setWidthPercentage(0); }
java
public void scaleToFit(float fitWidth, float fitHeight) { scalePercent(100); float percentX = (fitWidth * 100) / getScaledWidth(); float percentY = (fitHeight * 100) / getScaledHeight(); scalePercent(percentX < percentY ? percentX : percentY); setWidthPercentage(0); }
[ "public", "void", "scaleToFit", "(", "float", "fitWidth", ",", "float", "fitHeight", ")", "{", "scalePercent", "(", "100", ")", ";", "float", "percentX", "=", "(", "fitWidth", "*", "100", ")", "/", "getScaledWidth", "(", ")", ";", "float", "percentY", "=...
Scales the image so that it fits a certain width and height. @param fitWidth the width to fit @param fitHeight the height to fit
[ "Scales", "the", "image", "so", "that", "it", "fits", "a", "certain", "width", "and", "height", "." ]
train
https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/Image.java#L1313-L1319
pip-services3-java/pip-services3-commons-java
src/org/pipservices3/commons/refer/DependencyResolver.java
DependencyResolver.getRequired
public List<Object> getRequired(String name) throws ReferenceException { Object locator = find(name); if (locator == null) throw new ReferenceException(null, name); return _references.getRequired(locator); }
java
public List<Object> getRequired(String name) throws ReferenceException { Object locator = find(name); if (locator == null) throw new ReferenceException(null, name); return _references.getRequired(locator); }
[ "public", "List", "<", "Object", ">", "getRequired", "(", "String", "name", ")", "throws", "ReferenceException", "{", "Object", "locator", "=", "find", "(", "name", ")", ";", "if", "(", "locator", "==", "null", ")", "throw", "new", "ReferenceException", "(...
Gets all required dependencies by their name. At least one dependency must present. If no dependencies was found it throws a ReferenceException @param name the dependency name to locate. @return a list with found dependencies. @throws ReferenceException when no single component reference is found
[ "Gets", "all", "required", "dependencies", "by", "their", "name", ".", "At", "least", "one", "dependency", "must", "present", ".", "If", "no", "dependencies", "was", "found", "it", "throws", "a", "ReferenceException" ]
train
https://github.com/pip-services3-java/pip-services3-commons-java/blob/a8a0c3e5ec58f0663c295aa855c6b3afad2af86a/src/org/pipservices3/commons/refer/DependencyResolver.java#L196-L202
facebookarchive/hive-dwrf
hive-dwrf-shims/src/main/java/org/apache/hadoop/hive/ql/io/slice/Slice.java
Slice.setFloat
public void setFloat(int index, float value) { checkIndexLength(index, SizeOf.SIZE_OF_FLOAT); unsafe.putFloat(base, address + index, value); }
java
public void setFloat(int index, float value) { checkIndexLength(index, SizeOf.SIZE_OF_FLOAT); unsafe.putFloat(base, address + index, value); }
[ "public", "void", "setFloat", "(", "int", "index", ",", "float", "value", ")", "{", "checkIndexLength", "(", "index", ",", "SizeOf", ".", "SIZE_OF_FLOAT", ")", ";", "unsafe", ".", "putFloat", "(", "base", ",", "address", "+", "index", ",", "value", ")", ...
Sets the specified 32-bit float at the specified absolute {@code index} in this buffer. @throws IndexOutOfBoundsException if the specified {@code index} is less than {@code 0} or {@code index + 4} is greater than {@code this.length()}
[ "Sets", "the", "specified", "32", "-", "bit", "float", "at", "the", "specified", "absolute", "{", "@code", "index", "}", "in", "this", "buffer", "." ]
train
https://github.com/facebookarchive/hive-dwrf/blob/a7b4fcf28a57e006a2fc041d40cf7e5ad16e6b45/hive-dwrf-shims/src/main/java/org/apache/hadoop/hive/ql/io/slice/Slice.java#L459-L463
eFaps/eFaps-Kernel
src/main/java/org/efaps/admin/index/Index.java
Index.getAnalyzer
public static Analyzer getAnalyzer() throws EFapsException { IAnalyzerProvider provider = null; if (EFapsSystemConfiguration.get().containsAttributeValue(KernelSettings.INDEXANALYZERPROVCLASS)) { final String clazzname = EFapsSystemConfiguration.get().getAttributeValue( KernelSettings.INDEXANALYZERPROVCLASS); try { final Class<?> clazz = Class.forName(clazzname, false, EFapsClassLoader.getInstance()); provider = (IAnalyzerProvider) clazz.newInstance(); } catch (final ClassNotFoundException | InstantiationException | IllegalAccessException e) { throw new EFapsException(Index.class, "Could not instanciate IAnalyzerProvider", e); } } else { provider = new IAnalyzerProvider() { @Override public Analyzer getAnalyzer() { return new StandardAnalyzer(SpanishAnalyzer.getDefaultStopSet()); } }; } return provider.getAnalyzer(); }
java
public static Analyzer getAnalyzer() throws EFapsException { IAnalyzerProvider provider = null; if (EFapsSystemConfiguration.get().containsAttributeValue(KernelSettings.INDEXANALYZERPROVCLASS)) { final String clazzname = EFapsSystemConfiguration.get().getAttributeValue( KernelSettings.INDEXANALYZERPROVCLASS); try { final Class<?> clazz = Class.forName(clazzname, false, EFapsClassLoader.getInstance()); provider = (IAnalyzerProvider) clazz.newInstance(); } catch (final ClassNotFoundException | InstantiationException | IllegalAccessException e) { throw new EFapsException(Index.class, "Could not instanciate IAnalyzerProvider", e); } } else { provider = new IAnalyzerProvider() { @Override public Analyzer getAnalyzer() { return new StandardAnalyzer(SpanishAnalyzer.getDefaultStopSet()); } }; } return provider.getAnalyzer(); }
[ "public", "static", "Analyzer", "getAnalyzer", "(", ")", "throws", "EFapsException", "{", "IAnalyzerProvider", "provider", "=", "null", ";", "if", "(", "EFapsSystemConfiguration", ".", "get", "(", ")", ".", "containsAttributeValue", "(", "KernelSettings", ".", "IN...
Gets the analyzer. @return the analyzer @throws EFapsException on error
[ "Gets", "the", "analyzer", "." ]
train
https://github.com/eFaps/eFaps-Kernel/blob/04b96548f518c2386a93f5ec2b9349f9b9063859/src/main/java/org/efaps/admin/index/Index.java#L63-L87
sarl/sarl
contribs/io.sarl.pythongenerator/io.sarl.pythongenerator.generator/src/io/sarl/pythongenerator/generator/generator/PyGenerator.java
PyGenerator._generate
protected void _generate(SarlClass clazz, IExtraLanguageGeneratorContext context) { final JvmDeclaredType jvmType = getJvmModelAssociations().getInferredType(clazz); final PyAppendable appendable = createAppendable(jvmType, context); if (generateTypeDeclaration( this.qualifiedNameProvider.getFullyQualifiedName(clazz).toString(), clazz.getName(), clazz.isAbstract(), getSuperTypes(clazz.getExtends(), clazz.getImplements()), getTypeBuilder().getDocumentation(clazz), true, clazz.getMembers(), appendable, context, null)) { final QualifiedName name = getQualifiedNameProvider().getFullyQualifiedName(clazz); writeFile(name, appendable, context); } }
java
protected void _generate(SarlClass clazz, IExtraLanguageGeneratorContext context) { final JvmDeclaredType jvmType = getJvmModelAssociations().getInferredType(clazz); final PyAppendable appendable = createAppendable(jvmType, context); if (generateTypeDeclaration( this.qualifiedNameProvider.getFullyQualifiedName(clazz).toString(), clazz.getName(), clazz.isAbstract(), getSuperTypes(clazz.getExtends(), clazz.getImplements()), getTypeBuilder().getDocumentation(clazz), true, clazz.getMembers(), appendable, context, null)) { final QualifiedName name = getQualifiedNameProvider().getFullyQualifiedName(clazz); writeFile(name, appendable, context); } }
[ "protected", "void", "_generate", "(", "SarlClass", "clazz", ",", "IExtraLanguageGeneratorContext", "context", ")", "{", "final", "JvmDeclaredType", "jvmType", "=", "getJvmModelAssociations", "(", ")", ".", "getInferredType", "(", "clazz", ")", ";", "final", "PyAppe...
Generate the given object. @param clazz the class. @param context the context.
[ "Generate", "the", "given", "object", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/contribs/io.sarl.pythongenerator/io.sarl.pythongenerator.generator/src/io/sarl/pythongenerator/generator/generator/PyGenerator.java#L672-L685
stephenc/simple-java-mail
src/main/java/org/codemonkey/simplejavamail/Mailer.java
Mailer.prepareMessage
private Message prepareMessage(final Email email, final MimeMultipart multipartRoot) throws MessagingException, UnsupportedEncodingException { final Message message = new MimeMessage(session); message.setSubject(email.getSubject()); message.setFrom(new InternetAddress(email.getFromRecipient().getAddress(), email.getFromRecipient().getName())); message.setContent(multipartRoot); message.setSentDate(new Date()); return message; }
java
private Message prepareMessage(final Email email, final MimeMultipart multipartRoot) throws MessagingException, UnsupportedEncodingException { final Message message = new MimeMessage(session); message.setSubject(email.getSubject()); message.setFrom(new InternetAddress(email.getFromRecipient().getAddress(), email.getFromRecipient().getName())); message.setContent(multipartRoot); message.setSentDate(new Date()); return message; }
[ "private", "Message", "prepareMessage", "(", "final", "Email", "email", ",", "final", "MimeMultipart", "multipartRoot", ")", "throws", "MessagingException", ",", "UnsupportedEncodingException", "{", "final", "Message", "message", "=", "new", "MimeMessage", "(", "sessi...
Creates a new {@link MimeMessage} instance and prepares it in the email structure, so that it can be filled and send. @param email The email message from which the subject and From-address are extracted. @param multipartRoot The root of the email which holds everything (filled with some email data). @return Een geprepareerde {@link Message} instantie, klaar om gevuld en verzonden te worden. @throws MessagingException Kan gegooid worden als het message niet goed behandelt wordt. @throws UnsupportedEncodingException Zie {@link InternetAddress#InternetAddress(String, String)}.
[ "Creates", "a", "new", "{", "@link", "MimeMessage", "}", "instance", "and", "prepares", "it", "in", "the", "email", "structure", "so", "that", "it", "can", "be", "filled", "and", "send", "." ]
train
https://github.com/stephenc/simple-java-mail/blob/8c5897e6bbc23c11e7c7eb5064f407625c653923/src/main/java/org/codemonkey/simplejavamail/Mailer.java#L288-L296
alkacon/opencms-core
src/org/opencms/search/CmsSearchManager.java
CmsSearchManager.rebuildAllIndexes
public void rebuildAllIndexes(I_CmsReport report) throws CmsException { try { SEARCH_MANAGER_LOCK.lock(); CmsMessageContainer container = null; for (int i = 0, n = m_indexes.size(); i < n; i++) { // iterate all configured search indexes I_CmsSearchIndex searchIndex = m_indexes.get(i); try { // update the index updateIndex(searchIndex, report, null); } catch (CmsException e) { container = new CmsMessageContainer( Messages.get(), Messages.ERR_INDEX_REBUILD_ALL_1, new Object[] {searchIndex.getName()}); LOG.error( Messages.get().getBundle().key(Messages.ERR_INDEX_REBUILD_ALL_1, searchIndex.getName()), e); } } // clean up the extraction result cache cleanExtractionCache(); if (container != null) { // throw stored exception throw new CmsSearchException(container); } } finally { SEARCH_MANAGER_LOCK.unlock(); } }
java
public void rebuildAllIndexes(I_CmsReport report) throws CmsException { try { SEARCH_MANAGER_LOCK.lock(); CmsMessageContainer container = null; for (int i = 0, n = m_indexes.size(); i < n; i++) { // iterate all configured search indexes I_CmsSearchIndex searchIndex = m_indexes.get(i); try { // update the index updateIndex(searchIndex, report, null); } catch (CmsException e) { container = new CmsMessageContainer( Messages.get(), Messages.ERR_INDEX_REBUILD_ALL_1, new Object[] {searchIndex.getName()}); LOG.error( Messages.get().getBundle().key(Messages.ERR_INDEX_REBUILD_ALL_1, searchIndex.getName()), e); } } // clean up the extraction result cache cleanExtractionCache(); if (container != null) { // throw stored exception throw new CmsSearchException(container); } } finally { SEARCH_MANAGER_LOCK.unlock(); } }
[ "public", "void", "rebuildAllIndexes", "(", "I_CmsReport", "report", ")", "throws", "CmsException", "{", "try", "{", "SEARCH_MANAGER_LOCK", ".", "lock", "(", ")", ";", "CmsMessageContainer", "container", "=", "null", ";", "for", "(", "int", "i", "=", "0", ",...
Rebuilds (if required creates) all configured indexes.<p> @param report the report object to write messages (or <code>null</code>) @throws CmsException if something goes wrong
[ "Rebuilds", "(", "if", "required", "creates", ")", "all", "configured", "indexes", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/search/CmsSearchManager.java#L1667-L1698
elki-project/elki
elki-logging/src/main/java/de/lmu/ifi/dbs/elki/logging/LoggingUtil.java
LoggingUtil.logExpensive
public static void logExpensive(Level level, String message) { LogRecord rec = new ELKILogRecord(level, message); String[] caller = inferCaller(); if(caller != null) { rec.setSourceClassName(caller[0]); rec.setSourceMethodName(caller[1]); Logger logger = Logger.getLogger(caller[0]); logger.log(rec); } else { Logger.getAnonymousLogger().log(rec); } }
java
public static void logExpensive(Level level, String message) { LogRecord rec = new ELKILogRecord(level, message); String[] caller = inferCaller(); if(caller != null) { rec.setSourceClassName(caller[0]); rec.setSourceMethodName(caller[1]); Logger logger = Logger.getLogger(caller[0]); logger.log(rec); } else { Logger.getAnonymousLogger().log(rec); } }
[ "public", "static", "void", "logExpensive", "(", "Level", "level", ",", "String", "message", ")", "{", "LogRecord", "rec", "=", "new", "ELKILogRecord", "(", "level", ",", "message", ")", ";", "String", "[", "]", "caller", "=", "inferCaller", "(", ")", ";...
Expensive logging function that is convenient, but should only be used in rare conditions. For 'frequent' logging, use more efficient techniques, such as explained in the {@link de.lmu.ifi.dbs.elki.logging logging package documentation}. @param level Logging level @param message Message to log.
[ "Expensive", "logging", "function", "that", "is", "convenient", "but", "should", "only", "be", "used", "in", "rare", "conditions", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-logging/src/main/java/de/lmu/ifi/dbs/elki/logging/LoggingUtil.java#L79-L91
vvakame/JsonPullParser
jsonpullparser-core/src/main/java/net/vvakame/util/jsonpullparser/util/JsonUtil.java
JsonUtil.putBooleanList
public static void putBooleanList(Writer writer, List<Boolean> values) throws IOException { if (values == null) { writer.write("null"); } else { startArray(writer); for (int i = 0; i < values.size(); i++) { put(writer, values.get(i)); if (i != values.size() - 1) { addSeparator(writer); } } endArray(writer); } }
java
public static void putBooleanList(Writer writer, List<Boolean> values) throws IOException { if (values == null) { writer.write("null"); } else { startArray(writer); for (int i = 0; i < values.size(); i++) { put(writer, values.get(i)); if (i != values.size() - 1) { addSeparator(writer); } } endArray(writer); } }
[ "public", "static", "void", "putBooleanList", "(", "Writer", "writer", ",", "List", "<", "Boolean", ">", "values", ")", "throws", "IOException", "{", "if", "(", "values", "==", "null", ")", "{", "writer", ".", "write", "(", "\"null\"", ")", ";", "}", "...
Writes the given value with the given writer. @param writer @param values @throws IOException @author vvakame
[ "Writes", "the", "given", "value", "with", "the", "given", "writer", "." ]
train
https://github.com/vvakame/JsonPullParser/blob/fce183ca66354723323a77f2ae8cb5222b5836bc/jsonpullparser-core/src/main/java/net/vvakame/util/jsonpullparser/util/JsonUtil.java#L548-L561
UrielCh/ovh-java-sdk
ovh-java-sdk-licensedirectadmin/src/main/java/net/minidev/ovh/api/ApiOvhLicensedirectadmin.java
ApiOvhLicensedirectadmin.serviceName_confirmTermination_POST
public String serviceName_confirmTermination_POST(String serviceName, String commentary, OvhTerminationFutureUseEnum futureUse, OvhTerminationReasonEnum reason, String token) throws IOException { String qPath = "/license/directadmin/{serviceName}/confirmTermination"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "commentary", commentary); addBody(o, "futureUse", futureUse); addBody(o, "reason", reason); addBody(o, "token", token); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, String.class); }
java
public String serviceName_confirmTermination_POST(String serviceName, String commentary, OvhTerminationFutureUseEnum futureUse, OvhTerminationReasonEnum reason, String token) throws IOException { String qPath = "/license/directadmin/{serviceName}/confirmTermination"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "commentary", commentary); addBody(o, "futureUse", futureUse); addBody(o, "reason", reason); addBody(o, "token", token); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, String.class); }
[ "public", "String", "serviceName_confirmTermination_POST", "(", "String", "serviceName", ",", "String", "commentary", ",", "OvhTerminationFutureUseEnum", "futureUse", ",", "OvhTerminationReasonEnum", "reason", ",", "String", "token", ")", "throws", "IOException", "{", "St...
Confirm termination of your service REST: POST /license/directadmin/{serviceName}/confirmTermination @param futureUse What next after your termination request @param reason Reason of your termination request @param commentary Commentary about your termination request @param token [required] The termination token sent by mail to the admin contact @param serviceName [required] The name of your DirectAdmin license
[ "Confirm", "termination", "of", "your", "service" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-licensedirectadmin/src/main/java/net/minidev/ovh/api/ApiOvhLicensedirectadmin.java#L68-L78
datumbox/datumbox-framework
datumbox-framework-core/src/main/java/com/datumbox/framework/core/statistics/sampling/StratifiedSampling.java
StratifiedSampling.xbarStd
public static double xbarStd(TransposeDataCollection sampleDataCollection, AssociativeArray nh, AssociativeArray populationNh) { return Math.sqrt(xbarVariance(sampleDataCollection, nh, populationNh)); }
java
public static double xbarStd(TransposeDataCollection sampleDataCollection, AssociativeArray nh, AssociativeArray populationNh) { return Math.sqrt(xbarVariance(sampleDataCollection, nh, populationNh)); }
[ "public", "static", "double", "xbarStd", "(", "TransposeDataCollection", "sampleDataCollection", ",", "AssociativeArray", "nh", ",", "AssociativeArray", "populationNh", ")", "{", "return", "Math", ".", "sqrt", "(", "xbarVariance", "(", "sampleDataCollection", ",", "nh...
Calculates Standard Deviation for Xbar @param sampleDataCollection @param nh @param populationNh @return
[ "Calculates", "Standard", "Deviation", "for", "Xbar" ]
train
https://github.com/datumbox/datumbox-framework/blob/909dff0476e80834f05ecdde0624dd2390e9b0ca/datumbox-framework-core/src/main/java/com/datumbox/framework/core/statistics/sampling/StratifiedSampling.java#L203-L205
gitblit/fathom
fathom-x509/src/main/java/fathom/x509/X509Utils.java
X509Utils.newSSLCertificate
public static X509Certificate newSSLCertificate(X509Metadata sslMetadata, PrivateKey caPrivateKey, X509Certificate caCert, File targetStoreFile, X509Log x509log) { try { KeyPair pair = newKeyPair(); X500Name webDN = buildDistinguishedName(sslMetadata); X500Name issuerDN = new X500Name(PrincipalUtil.getIssuerX509Principal(caCert).getName()); X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder( issuerDN, BigInteger.valueOf(System.currentTimeMillis()), sslMetadata.notBefore, sslMetadata.notAfter, webDN, pair.getPublic()); JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils(); certBuilder.addExtension(X509Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(pair.getPublic())); certBuilder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(false)); certBuilder.addExtension(X509Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(caCert.getPublicKey())); // support alternateSubjectNames for SSL certificates List<GeneralName> altNames = new ArrayList<GeneralName>(); if (isIpAddress(sslMetadata.commonName)) { altNames.add(new GeneralName(GeneralName.iPAddress, sslMetadata.commonName)); } if (altNames.size() > 0) { GeneralNames subjectAltName = new GeneralNames(altNames.toArray(new GeneralName[altNames.size()])); certBuilder.addExtension(X509Extension.subjectAlternativeName, false, subjectAltName); } ContentSigner caSigner = new JcaContentSignerBuilder(SIGNING_ALGORITHM) .setProvider(BC).build(caPrivateKey); X509Certificate cert = new JcaX509CertificateConverter().setProvider(BC) .getCertificate(certBuilder.build(caSigner)); cert.checkValidity(new Date()); cert.verify(caCert.getPublicKey()); // Save to keystore KeyStore serverStore = openKeyStore(targetStoreFile, sslMetadata.password); serverStore.setKeyEntry(sslMetadata.commonName, pair.getPrivate(), sslMetadata.password.toCharArray(), new Certificate[]{cert, caCert}); saveKeyStore(targetStoreFile, serverStore, sslMetadata.password); x509log.log(MessageFormat.format("New SSL certificate {0,number,0} [{1}]", cert.getSerialNumber(), cert.getSubjectDN().getName())); // update serial number in metadata object sslMetadata.serialNumber = cert.getSerialNumber().toString(); return cert; } catch (Throwable t) { throw new RuntimeException("Failed to generate SSL certificate!", t); } }
java
public static X509Certificate newSSLCertificate(X509Metadata sslMetadata, PrivateKey caPrivateKey, X509Certificate caCert, File targetStoreFile, X509Log x509log) { try { KeyPair pair = newKeyPair(); X500Name webDN = buildDistinguishedName(sslMetadata); X500Name issuerDN = new X500Name(PrincipalUtil.getIssuerX509Principal(caCert).getName()); X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder( issuerDN, BigInteger.valueOf(System.currentTimeMillis()), sslMetadata.notBefore, sslMetadata.notAfter, webDN, pair.getPublic()); JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils(); certBuilder.addExtension(X509Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(pair.getPublic())); certBuilder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(false)); certBuilder.addExtension(X509Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(caCert.getPublicKey())); // support alternateSubjectNames for SSL certificates List<GeneralName> altNames = new ArrayList<GeneralName>(); if (isIpAddress(sslMetadata.commonName)) { altNames.add(new GeneralName(GeneralName.iPAddress, sslMetadata.commonName)); } if (altNames.size() > 0) { GeneralNames subjectAltName = new GeneralNames(altNames.toArray(new GeneralName[altNames.size()])); certBuilder.addExtension(X509Extension.subjectAlternativeName, false, subjectAltName); } ContentSigner caSigner = new JcaContentSignerBuilder(SIGNING_ALGORITHM) .setProvider(BC).build(caPrivateKey); X509Certificate cert = new JcaX509CertificateConverter().setProvider(BC) .getCertificate(certBuilder.build(caSigner)); cert.checkValidity(new Date()); cert.verify(caCert.getPublicKey()); // Save to keystore KeyStore serverStore = openKeyStore(targetStoreFile, sslMetadata.password); serverStore.setKeyEntry(sslMetadata.commonName, pair.getPrivate(), sslMetadata.password.toCharArray(), new Certificate[]{cert, caCert}); saveKeyStore(targetStoreFile, serverStore, sslMetadata.password); x509log.log(MessageFormat.format("New SSL certificate {0,number,0} [{1}]", cert.getSerialNumber(), cert.getSubjectDN().getName())); // update serial number in metadata object sslMetadata.serialNumber = cert.getSerialNumber().toString(); return cert; } catch (Throwable t) { throw new RuntimeException("Failed to generate SSL certificate!", t); } }
[ "public", "static", "X509Certificate", "newSSLCertificate", "(", "X509Metadata", "sslMetadata", ",", "PrivateKey", "caPrivateKey", ",", "X509Certificate", "caCert", ",", "File", "targetStoreFile", ",", "X509Log", "x509log", ")", "{", "try", "{", "KeyPair", "pair", "...
Creates a new SSL certificate signed by the CA private key and stored in keyStore. @param sslMetadata @param caPrivateKey @param caCert @param targetStoreFile @param x509log
[ "Creates", "a", "new", "SSL", "certificate", "signed", "by", "the", "CA", "private", "key", "and", "stored", "in", "keyStore", "." ]
train
https://github.com/gitblit/fathom/blob/f2f820eb16e9fea1e36ad4eda4ed51b35f056538/fathom-x509/src/main/java/fathom/x509/X509Utils.java#L542-L595
devnied/EMV-NFC-Paycard-Enrollment
library/src/main/java/com/github/devnied/emvnfccard/parser/apdu/impl/DataFactory.java
DataFactory.getDate
private static Date getDate(final AnnotationData pAnnotation, final BitUtils pBit) { Date date = null; if (pAnnotation.getDateStandard() == BCD_DATE) { date = pBit.getNextDate(pAnnotation.getSize(), pAnnotation.getFormat(), true); } else if (pAnnotation.getDateStandard() == CPCL_DATE) { date = calculateCplcDate(pBit.getNextByte(pAnnotation.getSize())); } else { date = pBit.getNextDate(pAnnotation.getSize(), pAnnotation.getFormat()); } return date; }
java
private static Date getDate(final AnnotationData pAnnotation, final BitUtils pBit) { Date date = null; if (pAnnotation.getDateStandard() == BCD_DATE) { date = pBit.getNextDate(pAnnotation.getSize(), pAnnotation.getFormat(), true); } else if (pAnnotation.getDateStandard() == CPCL_DATE) { date = calculateCplcDate(pBit.getNextByte(pAnnotation.getSize())); } else { date = pBit.getNextDate(pAnnotation.getSize(), pAnnotation.getFormat()); } return date; }
[ "private", "static", "Date", "getDate", "(", "final", "AnnotationData", "pAnnotation", ",", "final", "BitUtils", "pBit", ")", "{", "Date", "date", "=", "null", ";", "if", "(", "pAnnotation", ".", "getDateStandard", "(", ")", "==", "BCD_DATE", ")", "{", "da...
Method to get a date from the bytes array @param pAnnotation annotation data @param pBit table bytes @return The date read of null
[ "Method", "to", "get", "a", "date", "from", "the", "bytes", "array" ]
train
https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/parser/apdu/impl/DataFactory.java#L66-L76
jboss-integration/fuse-bxms-integ
switchyard/switchyard-component-common-knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/KnowledgeSwitchYardScanner.java
KnowledgeSwitchYardScanner.toLoggersModel
protected LoggersModel toLoggersModel(Logger[] loggerAnnotations, KnowledgeNamespace knowledgeNamespace) { if (loggerAnnotations == null || loggerAnnotations.length == 0) { return null; } LoggersModel loggersModel = new V1LoggersModel(knowledgeNamespace.uri()); for (Logger loggerAnnotation : loggerAnnotations) { LoggerModel loggerModel = new V1LoggerModel(knowledgeNamespace.uri()); int interval = loggerAnnotation.interval(); if (interval > -1) { loggerModel.setInterval(interval); } String log = loggerAnnotation.log(); if (!UNDEFINED.equals(log)) { loggerModel.setLog(log); } LoggerType loggerType = loggerAnnotation.type(); if (!LoggerType.THREADED_FILE.equals(loggerType)) { loggerModel.setType(loggerType); } loggersModel.addLogger(loggerModel); } return loggersModel; }
java
protected LoggersModel toLoggersModel(Logger[] loggerAnnotations, KnowledgeNamespace knowledgeNamespace) { if (loggerAnnotations == null || loggerAnnotations.length == 0) { return null; } LoggersModel loggersModel = new V1LoggersModel(knowledgeNamespace.uri()); for (Logger loggerAnnotation : loggerAnnotations) { LoggerModel loggerModel = new V1LoggerModel(knowledgeNamespace.uri()); int interval = loggerAnnotation.interval(); if (interval > -1) { loggerModel.setInterval(interval); } String log = loggerAnnotation.log(); if (!UNDEFINED.equals(log)) { loggerModel.setLog(log); } LoggerType loggerType = loggerAnnotation.type(); if (!LoggerType.THREADED_FILE.equals(loggerType)) { loggerModel.setType(loggerType); } loggersModel.addLogger(loggerModel); } return loggersModel; }
[ "protected", "LoggersModel", "toLoggersModel", "(", "Logger", "[", "]", "loggerAnnotations", ",", "KnowledgeNamespace", "knowledgeNamespace", ")", "{", "if", "(", "loggerAnnotations", "==", "null", "||", "loggerAnnotations", ".", "length", "==", "0", ")", "{", "re...
Converts logger annotations to loggers model. @param loggerAnnotations annotations @param knowledgeNamespace knowledgeNamespace @return model
[ "Converts", "logger", "annotations", "to", "loggers", "model", "." ]
train
https://github.com/jboss-integration/fuse-bxms-integ/blob/ca5c012bf867ea15d1250f0991af3cd7e708aaaf/switchyard/switchyard-component-common-knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/KnowledgeSwitchYardScanner.java#L181-L203
spotbugs/spotbugs
spotbugs/src/main/java/edu/umd/cs/findbugs/ba/Frame.java
Frame.getStackValue
public ValueType getStackValue(int loc) throws DataflowAnalysisException { if (!isValid()) { throw new DataflowAnalysisException("Accessing TOP or BOTTOM frame!"); } int stackDepth = getStackDepth(); if (loc >= stackDepth) { throw new DataflowAnalysisException("not enough values on stack: access=" + loc + ", avail=" + stackDepth); } if (loc < 0) { throw new DataflowAnalysisException("can't get position " + loc + " of stack"); } int pos = slotList.size() - (loc + 1); return slotList.get(pos); }
java
public ValueType getStackValue(int loc) throws DataflowAnalysisException { if (!isValid()) { throw new DataflowAnalysisException("Accessing TOP or BOTTOM frame!"); } int stackDepth = getStackDepth(); if (loc >= stackDepth) { throw new DataflowAnalysisException("not enough values on stack: access=" + loc + ", avail=" + stackDepth); } if (loc < 0) { throw new DataflowAnalysisException("can't get position " + loc + " of stack"); } int pos = slotList.size() - (loc + 1); return slotList.get(pos); }
[ "public", "ValueType", "getStackValue", "(", "int", "loc", ")", "throws", "DataflowAnalysisException", "{", "if", "(", "!", "isValid", "(", ")", ")", "{", "throw", "new", "DataflowAnalysisException", "(", "\"Accessing TOP or BOTTOM frame!\"", ")", ";", "}", "int",...
Get a value on the operand stack. @param loc the stack location, counting downwards from the top (location 0)
[ "Get", "a", "value", "on", "the", "operand", "stack", "." ]
train
https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/ba/Frame.java#L241-L254
jhg023/SimpleNet
src/main/java/simplenet/packet/Packet.java
Packet.putLong
public Packet putLong(long l, ByteOrder order) { var buffer = HEAP_BUFFER_POOL.take(Long.BYTES); var array = buffer.putLong(order == ByteOrder.LITTLE_ENDIAN ? Long.reverseBytes(l) : l).array(); try { return enqueue(Arrays.copyOfRange(array, 0, Long.BYTES)); } finally { HEAP_BUFFER_POOL.give(buffer); } }
java
public Packet putLong(long l, ByteOrder order) { var buffer = HEAP_BUFFER_POOL.take(Long.BYTES); var array = buffer.putLong(order == ByteOrder.LITTLE_ENDIAN ? Long.reverseBytes(l) : l).array(); try { return enqueue(Arrays.copyOfRange(array, 0, Long.BYTES)); } finally { HEAP_BUFFER_POOL.give(buffer); } }
[ "public", "Packet", "putLong", "(", "long", "l", ",", "ByteOrder", "order", ")", "{", "var", "buffer", "=", "HEAP_BUFFER_POOL", ".", "take", "(", "Long", ".", "BYTES", ")", ";", "var", "array", "=", "buffer", ".", "putLong", "(", "order", "==", "ByteOr...
Writes a single {@code long} with the specified {@link ByteOrder} to this {@link Packet}'s payload. @param l A {@code long}. @param order The internal byte order of the {@code long}. @return The {@link Packet} to allow for chained writes.
[ "Writes", "a", "single", "{", "@code", "long", "}", "with", "the", "specified", "{", "@link", "ByteOrder", "}", "to", "this", "{", "@link", "Packet", "}", "s", "payload", "." ]
train
https://github.com/jhg023/SimpleNet/blob/a5b55cbfe1768c6a28874f12adac3c748f2b509a/src/main/java/simplenet/packet/Packet.java#L259-L268
threerings/narya
core/src/main/java/com/threerings/crowd/chat/client/ChatDirector.java
ChatDirector.requestSpeak
public void requestSpeak (SpeakService speakService, String message, byte mode) { if (speakService == null) { if (_place == null) { return; } speakService = _place.speakService; } // make sure they can say what they want to say message = filter(message, null, true); if (message == null) { return; } // dispatch a speak request using the supplied speak service speakService.speak(message, mode); }
java
public void requestSpeak (SpeakService speakService, String message, byte mode) { if (speakService == null) { if (_place == null) { return; } speakService = _place.speakService; } // make sure they can say what they want to say message = filter(message, null, true); if (message == null) { return; } // dispatch a speak request using the supplied speak service speakService.speak(message, mode); }
[ "public", "void", "requestSpeak", "(", "SpeakService", "speakService", ",", "String", "message", ",", "byte", "mode", ")", "{", "if", "(", "speakService", "==", "null", ")", "{", "if", "(", "_place", "==", "null", ")", "{", "return", ";", "}", "speakServ...
Requests that a speak message with the specified mode be generated and delivered via the supplied speak service instance (which will be associated with a particular "speak object"). The message will first be validated by all registered {@link ChatFilter}s (and possibly vetoed) before being dispatched. @param speakService the speak service to use when generating the speak request or null if we should speak in the current "place". @param message the contents of the speak message. @param mode a speech mode that will be interpreted by the {@link ChatDisplay} implementations that eventually display this speak message.
[ "Requests", "that", "a", "speak", "message", "with", "the", "specified", "mode", "be", "generated", "and", "delivered", "via", "the", "supplied", "speak", "service", "instance", "(", "which", "will", "be", "associated", "with", "a", "particular", "speak", "obj...
train
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/crowd/chat/client/ChatDirector.java#L453-L470
m-m-m/util
nls/src/main/java/net/sf/mmm/util/nls/base/NlsBundleHelper.java
NlsBundleHelper.isNlsBundleMethod
public boolean isNlsBundleMethod(Method method, boolean ignoreIllegalMethods) { Class<?> declaringClass = method.getDeclaringClass(); assert (declaringClass.isInterface()); if (NlsMessage.class.equals(method.getReturnType())) { assert (NlsBundle.class.isAssignableFrom(declaringClass)); return true; } else if (!declaringClass.isAssignableFrom(NlsBundle.class)) { if (!ignoreIllegalMethods) { throw new IllegalArgumentException(declaringClass.getName() + "." + method.getName()); } } return false; }
java
public boolean isNlsBundleMethod(Method method, boolean ignoreIllegalMethods) { Class<?> declaringClass = method.getDeclaringClass(); assert (declaringClass.isInterface()); if (NlsMessage.class.equals(method.getReturnType())) { assert (NlsBundle.class.isAssignableFrom(declaringClass)); return true; } else if (!declaringClass.isAssignableFrom(NlsBundle.class)) { if (!ignoreIllegalMethods) { throw new IllegalArgumentException(declaringClass.getName() + "." + method.getName()); } } return false; }
[ "public", "boolean", "isNlsBundleMethod", "(", "Method", "method", ",", "boolean", "ignoreIllegalMethods", ")", "{", "Class", "<", "?", ">", "declaringClass", "=", "method", ".", "getDeclaringClass", "(", ")", ";", "assert", "(", "declaringClass", ".", "isInterf...
This method determines if the given {@link Method} is a regular {@link NlsBundle}-method. @param method the {@link Method} to check. @param ignoreIllegalMethods - {@code true} if illegal methods (non NlsBundleMethods other than those defined by {@link Object}) should be ignored, {@code false} if they should cause an exception. @return {@code true} if the given {@link Method} is a legal {@link NlsBundle} method, {@code false} otherwise (e.g. for {@code toString()}).
[ "This", "method", "determines", "if", "the", "given", "{", "@link", "Method", "}", "is", "a", "regular", "{", "@link", "NlsBundle", "}", "-", "method", "." ]
train
https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/nls/src/main/java/net/sf/mmm/util/nls/base/NlsBundleHelper.java#L183-L196
twitter/cloudhopper-commons
ch-commons-util/src/main/java/com/cloudhopper/commons/util/HexUtil.java
HexUtil.appendHexString
static public void appendHexString(StringBuilder buffer, byte value) { assertNotNull(buffer); int nibble = (value & 0xF0) >>> 4; buffer.append(HEX_TABLE[nibble]); nibble = (value & 0x0F); buffer.append(HEX_TABLE[nibble]); }
java
static public void appendHexString(StringBuilder buffer, byte value) { assertNotNull(buffer); int nibble = (value & 0xF0) >>> 4; buffer.append(HEX_TABLE[nibble]); nibble = (value & 0x0F); buffer.append(HEX_TABLE[nibble]); }
[ "static", "public", "void", "appendHexString", "(", "StringBuilder", "buffer", ",", "byte", "value", ")", "{", "assertNotNull", "(", "buffer", ")", ";", "int", "nibble", "=", "(", "value", "&", "0xF0", ")", ">>>", "4", ";", "buffer", ".", "append", "(", ...
Appends 2 characters to a StringBuilder with the byte in a "Big Endian" hexidecimal format. For example, a byte 0x34 will be appended as a String in format "34". A byte of value 0 will be appended as "00". @param buffer The StringBuilder the byte value in hexidecimal format will be appended to. If the buffer is null, this method will throw a NullPointerException. @param value The byte value that will be converted to a hexidecimal String.
[ "Appends", "2", "characters", "to", "a", "StringBuilder", "with", "the", "byte", "in", "a", "Big", "Endian", "hexidecimal", "format", ".", "For", "example", "a", "byte", "0x34", "will", "be", "appended", "as", "a", "String", "in", "format", "34", ".", "A...
train
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-util/src/main/java/com/cloudhopper/commons/util/HexUtil.java#L144-L150