repository_name
stringlengths
7
54
func_path_in_repository
stringlengths
18
218
func_name
stringlengths
5
140
whole_func_string
stringlengths
79
3.99k
language
stringclasses
1 value
func_code_string
stringlengths
79
3.99k
func_code_tokens
listlengths
20
624
func_documentation_string
stringlengths
61
1.96k
func_documentation_tokens
listlengths
1
478
split_name
stringclasses
1 value
func_code_url
stringlengths
107
339
SeleniumHQ/selenium
java/client/src/org/openqa/selenium/remote/http/HttpRequest.java
HttpRequest.addQueryParameter
public HttpRequest addQueryParameter(String name, String value) { queryParameters.put( Objects.requireNonNull(name, "Name must be set"), Objects.requireNonNull(value, "Value must be set")); return this; }
java
public HttpRequest addQueryParameter(String name, String value) { queryParameters.put( Objects.requireNonNull(name, "Name must be set"), Objects.requireNonNull(value, "Value must be set")); return this; }
[ "public", "HttpRequest", "addQueryParameter", "(", "String", "name", ",", "String", "value", ")", "{", "queryParameters", ".", "put", "(", "Objects", ".", "requireNonNull", "(", "name", ",", "\"Name must be set\"", ")", ",", "Objects", ".", "requireNonNull", "(", "value", ",", "\"Value must be set\"", ")", ")", ";", "return", "this", ";", "}" ]
Set a query parameter, adding to existing values if present. The implementation will ensure that the name and value are properly encoded.
[ "Set", "a", "query", "parameter", "adding", "to", "existing", "values", "if", "present", ".", "The", "implementation", "will", "ensure", "that", "the", "name", "and", "value", "are", "properly", "encoded", "." ]
train
https://github.com/SeleniumHQ/selenium/blob/7af172729f17b20269c8ca4ea6f788db48616535/java/client/src/org/openqa/selenium/remote/http/HttpRequest.java#L61-L66
StanKocken/EfficientAdapter
efficientadapter/src/main/java/com/skocken/efficientadapter/lib/util/ViewHelper.java
ViewHelper.setText
public static void setText(EfficientCacheView cacheView, int viewId, CharSequence text) { View view = cacheView.findViewByIdEfficient(viewId); if (view instanceof TextView) { ((TextView) view).setText(text); } }
java
public static void setText(EfficientCacheView cacheView, int viewId, CharSequence text) { View view = cacheView.findViewByIdEfficient(viewId); if (view instanceof TextView) { ((TextView) view).setText(text); } }
[ "public", "static", "void", "setText", "(", "EfficientCacheView", "cacheView", ",", "int", "viewId", ",", "CharSequence", "text", ")", "{", "View", "view", "=", "cacheView", ".", "findViewByIdEfficient", "(", "viewId", ")", ";", "if", "(", "view", "instanceof", "TextView", ")", "{", "(", "(", "TextView", ")", "view", ")", ".", "setText", "(", "text", ")", ";", "}", "}" ]
Equivalent to calling TextView.setText @param cacheView The cache of views to get the view from @param viewId The id of the view whose text should change @param text The new text for the view
[ "Equivalent", "to", "calling", "TextView", ".", "setText" ]
train
https://github.com/StanKocken/EfficientAdapter/blob/0bcc3a20182cbce9d7901e1e2a9104251637167d/efficientadapter/src/main/java/com/skocken/efficientadapter/lib/util/ViewHelper.java#L115-L120
mozilla/rhino
src/org/mozilla/javascript/NativeSet.java
NativeSet.loadFromIterable
static void loadFromIterable(Context cx, Scriptable scope, ScriptableObject set, Object arg1) { if ((arg1 == null) || Undefined.instance.equals(arg1)) { return; } // Call the "[Symbol.iterator]" property as a function. Object ito = ScriptRuntime.callIterator(arg1, cx, scope); if (Undefined.instance.equals(ito)) { // Per spec, ignore if the iterator returns undefined return; } // Find the "add" function of our own prototype, since it might have // been replaced. Since we're not fully constructed yet, create a dummy instance // so that we can get our own prototype. ScriptableObject dummy = ensureScriptableObject(cx.newObject(scope, set.getClassName())); final Callable add = ScriptRuntime.getPropFunctionAndThis(dummy.getPrototype(), "add", cx, scope); // Clean up the value left around by the previous function ScriptRuntime.lastStoredScriptable(cx); // Finally, run through all the iterated values and add them! try (IteratorLikeIterable it = new IteratorLikeIterable(cx, scope, ito)) { for (Object val : it) { final Object finalVal = val == Scriptable.NOT_FOUND ? Undefined.instance : val; add.call(cx, scope, set, new Object[]{finalVal}); } } }
java
static void loadFromIterable(Context cx, Scriptable scope, ScriptableObject set, Object arg1) { if ((arg1 == null) || Undefined.instance.equals(arg1)) { return; } // Call the "[Symbol.iterator]" property as a function. Object ito = ScriptRuntime.callIterator(arg1, cx, scope); if (Undefined.instance.equals(ito)) { // Per spec, ignore if the iterator returns undefined return; } // Find the "add" function of our own prototype, since it might have // been replaced. Since we're not fully constructed yet, create a dummy instance // so that we can get our own prototype. ScriptableObject dummy = ensureScriptableObject(cx.newObject(scope, set.getClassName())); final Callable add = ScriptRuntime.getPropFunctionAndThis(dummy.getPrototype(), "add", cx, scope); // Clean up the value left around by the previous function ScriptRuntime.lastStoredScriptable(cx); // Finally, run through all the iterated values and add them! try (IteratorLikeIterable it = new IteratorLikeIterable(cx, scope, ito)) { for (Object val : it) { final Object finalVal = val == Scriptable.NOT_FOUND ? Undefined.instance : val; add.call(cx, scope, set, new Object[]{finalVal}); } } }
[ "static", "void", "loadFromIterable", "(", "Context", "cx", ",", "Scriptable", "scope", ",", "ScriptableObject", "set", ",", "Object", "arg1", ")", "{", "if", "(", "(", "arg1", "==", "null", ")", "||", "Undefined", ".", "instance", ".", "equals", "(", "arg1", ")", ")", "{", "return", ";", "}", "// Call the \"[Symbol.iterator]\" property as a function.", "Object", "ito", "=", "ScriptRuntime", ".", "callIterator", "(", "arg1", ",", "cx", ",", "scope", ")", ";", "if", "(", "Undefined", ".", "instance", ".", "equals", "(", "ito", ")", ")", "{", "// Per spec, ignore if the iterator returns undefined", "return", ";", "}", "// Find the \"add\" function of our own prototype, since it might have", "// been replaced. Since we're not fully constructed yet, create a dummy instance", "// so that we can get our own prototype.", "ScriptableObject", "dummy", "=", "ensureScriptableObject", "(", "cx", ".", "newObject", "(", "scope", ",", "set", ".", "getClassName", "(", ")", ")", ")", ";", "final", "Callable", "add", "=", "ScriptRuntime", ".", "getPropFunctionAndThis", "(", "dummy", ".", "getPrototype", "(", ")", ",", "\"add\"", ",", "cx", ",", "scope", ")", ";", "// Clean up the value left around by the previous function", "ScriptRuntime", ".", "lastStoredScriptable", "(", "cx", ")", ";", "// Finally, run through all the iterated values and add them!", "try", "(", "IteratorLikeIterable", "it", "=", "new", "IteratorLikeIterable", "(", "cx", ",", "scope", ",", "ito", ")", ")", "{", "for", "(", "Object", "val", ":", "it", ")", "{", "final", "Object", "finalVal", "=", "val", "==", "Scriptable", ".", "NOT_FOUND", "?", "Undefined", ".", "instance", ":", "val", ";", "add", ".", "call", "(", "cx", ",", "scope", ",", "set", ",", "new", "Object", "[", "]", "{", "finalVal", "}", ")", ";", "}", "}", "}" ]
If an "iterable" object was passed to the constructor, there are many many things to do. This is common code with NativeWeakSet.
[ "If", "an", "iterable", "object", "was", "passed", "to", "the", "constructor", "there", "are", "many", "many", "things", "to", "do", ".", "This", "is", "common", "code", "with", "NativeWeakSet", "." ]
train
https://github.com/mozilla/rhino/blob/fa8a86df11d37623f5faa8d445a5876612bc47b0/src/org/mozilla/javascript/NativeSet.java#L155-L184
JodaOrg/joda-time
src/main/java/org/joda/time/format/PeriodFormatterBuilder.java
PeriodFormatterBuilder.appendSuffix
public PeriodFormatterBuilder appendSuffix(String[] regularExpressions, String[] suffixes) { if (regularExpressions == null || suffixes == null || regularExpressions.length < 1 || regularExpressions.length != suffixes.length) { throw new IllegalArgumentException(); } return appendSuffix(new RegExAffix(regularExpressions, suffixes)); }
java
public PeriodFormatterBuilder appendSuffix(String[] regularExpressions, String[] suffixes) { if (regularExpressions == null || suffixes == null || regularExpressions.length < 1 || regularExpressions.length != suffixes.length) { throw new IllegalArgumentException(); } return appendSuffix(new RegExAffix(regularExpressions, suffixes)); }
[ "public", "PeriodFormatterBuilder", "appendSuffix", "(", "String", "[", "]", "regularExpressions", ",", "String", "[", "]", "suffixes", ")", "{", "if", "(", "regularExpressions", "==", "null", "||", "suffixes", "==", "null", "||", "regularExpressions", ".", "length", "<", "1", "||", "regularExpressions", ".", "length", "!=", "suffixes", ".", "length", ")", "{", "throw", "new", "IllegalArgumentException", "(", ")", ";", "}", "return", "appendSuffix", "(", "new", "RegExAffix", "(", "regularExpressions", ",", "suffixes", ")", ")", ";", "}" ]
Append a field suffix which applies only to the last appended field. If the field is not printed, neither is the suffix. <p> The value is converted to String. During parsing, the suffix is selected based on the match with the regular expression. The index of the first regular expression that matches value converted to String nominates the suffix. If none of the regular expressions match the value converted to String then the last suffix is selected. <p> An example usage for English might look like this: <pre> appendSuffix(new String[] { &quot;&circ;1$&quot;, &quot;.*&quot; }, new String[] { &quot; year&quot;, &quot; years&quot; }) </pre> <p> Please note that for languages with simple mapping (singular and plural suffix only - like the one above) the {@link #appendSuffix(String, String)} method will result in a slightly faster formatter and that {@link #appendSuffix(String[], String[])} method should be only used when the mapping between values and prefixes is more complicated than the difference between singular and plural. @param regularExpressions an array of regular expressions, at least one element, length has to match the length of suffixes parameter @param suffixes an array of suffixes, at least one element, length has to match the length of regularExpressions parameter @return this PeriodFormatterBuilder @throws IllegalStateException if no field exists to append to @see #appendPrefix @since 2.5
[ "Append", "a", "field", "suffix", "which", "applies", "only", "to", "the", "last", "appended", "field", ".", "If", "the", "field", "is", "not", "printed", "neither", "is", "the", "suffix", ".", "<p", ">", "The", "value", "is", "converted", "to", "String", ".", "During", "parsing", "the", "suffix", "is", "selected", "based", "on", "the", "match", "with", "the", "regular", "expression", ".", "The", "index", "of", "the", "first", "regular", "expression", "that", "matches", "value", "converted", "to", "String", "nominates", "the", "suffix", ".", "If", "none", "of", "the", "regular", "expressions", "match", "the", "value", "converted", "to", "String", "then", "the", "last", "suffix", "is", "selected", ".", "<p", ">", "An", "example", "usage", "for", "English", "might", "look", "like", "this", ":" ]
train
https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/format/PeriodFormatterBuilder.java#L667-L673
jenkinsci/jenkins
core/src/main/java/hudson/util/ArgumentListBuilder.java
ArgumentListBuilder.addKeyValuePairsFromPropertyString
public ArgumentListBuilder addKeyValuePairsFromPropertyString(String prefix, String properties, VariableResolver<String> vr, Set<String> propsToMask) throws IOException { if(properties==null) return this; properties = Util.replaceMacro(properties, propertiesGeneratingResolver(vr)); for (Entry<Object,Object> entry : Util.loadProperties(properties).entrySet()) { addKeyValuePair(prefix, (String)entry.getKey(), entry.getValue().toString(), (propsToMask != null) && propsToMask.contains(entry.getKey())); } return this; }
java
public ArgumentListBuilder addKeyValuePairsFromPropertyString(String prefix, String properties, VariableResolver<String> vr, Set<String> propsToMask) throws IOException { if(properties==null) return this; properties = Util.replaceMacro(properties, propertiesGeneratingResolver(vr)); for (Entry<Object,Object> entry : Util.loadProperties(properties).entrySet()) { addKeyValuePair(prefix, (String)entry.getKey(), entry.getValue().toString(), (propsToMask != null) && propsToMask.contains(entry.getKey())); } return this; }
[ "public", "ArgumentListBuilder", "addKeyValuePairsFromPropertyString", "(", "String", "prefix", ",", "String", "properties", ",", "VariableResolver", "<", "String", ">", "vr", ",", "Set", "<", "String", ">", "propsToMask", ")", "throws", "IOException", "{", "if", "(", "properties", "==", "null", ")", "return", "this", ";", "properties", "=", "Util", ".", "replaceMacro", "(", "properties", ",", "propertiesGeneratingResolver", "(", "vr", ")", ")", ";", "for", "(", "Entry", "<", "Object", ",", "Object", ">", "entry", ":", "Util", ".", "loadProperties", "(", "properties", ")", ".", "entrySet", "(", ")", ")", "{", "addKeyValuePair", "(", "prefix", ",", "(", "String", ")", "entry", ".", "getKey", "(", ")", ",", "entry", ".", "getValue", "(", ")", ".", "toString", "(", ")", ",", "(", "propsToMask", "!=", "null", ")", "&&", "propsToMask", ".", "contains", "(", "entry", ".", "getKey", "(", ")", ")", ")", ";", "}", "return", "this", ";", "}" ]
Adds key value pairs as "-Dkey=value -Dkey=value ..." by parsing a given string using {@link Properties} with masking. @param prefix The '-D' portion of the example. Defaults to -D if null. @param properties The persisted form of {@link Properties}. For example, "abc=def\nghi=jkl". Can be null, in which case this method becomes no-op. @param vr {@link VariableResolver} to resolve variables in properties string. @param propsToMask Set containing key names to mark as masked in the argument list. Key names that do not exist in the set will be added unmasked. @since 1.378
[ "Adds", "key", "value", "pairs", "as", "-", "Dkey", "=", "value", "-", "Dkey", "=", "value", "...", "by", "parsing", "a", "given", "string", "using", "{", "@link", "Properties", "}", "with", "masking", "." ]
train
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/util/ArgumentListBuilder.java#L227-L236
xmlet/XsdAsmFaster
src/main/java/org/xmlet/xsdasmfaster/classes/XsdAsmInterfaces.java
XsdAsmInterfaces.generateSequenceMethod
private void generateSequenceMethod(ClassWriter classWriter, String className, String javaType, String addingChildName, String typeName, String nextTypeName, String apiName) { String type = getFullClassTypeName(typeName, apiName); String nextType = getFullClassTypeName(nextTypeName, apiName); String nextTypeDesc = getFullClassTypeNameDesc(nextTypeName, apiName); String addingType = getFullClassTypeName(addingChildName, apiName); javaType = javaType == null ? JAVA_STRING_DESC : javaType; MethodVisitor mVisitor = classWriter.visitMethod(ACC_PUBLIC, firstToLower(addingChildName), "(" + javaType + ")" + nextTypeDesc, "(" + javaType + ")L" + nextType + "<TZ;>;", null); mVisitor.visitLocalVariable(firstToLower(addingChildName), JAVA_STRING_DESC, null, new Label(), new Label(),1); mVisitor.visitCode(); mVisitor.visitTypeInsn(NEW, addingType); mVisitor.visitInsn(DUP); mVisitor.visitVarInsn(ALOAD, 0); mVisitor.visitVarInsn(ALOAD, 0); mVisitor.visitFieldInsn(GETFIELD, type, "visitor", elementVisitorTypeDesc); mVisitor.visitInsn(ICONST_1); mVisitor.visitMethodInsn(INVOKESPECIAL, addingType, CONSTRUCTOR, "(" + elementTypeDesc + elementVisitorTypeDesc + "Z)V", false); mVisitor.visitVarInsn(ALOAD, 1); mVisitor.visitMethodInsn(INVOKEVIRTUAL, addingType, "text", "(" + JAVA_OBJECT_DESC + ")" + elementTypeDesc, false); mVisitor.visitTypeInsn(CHECKCAST, addingType); mVisitor.visitMethodInsn(INVOKEVIRTUAL, addingType, "__", "()" + elementTypeDesc, false); mVisitor.visitInsn(POP); mVisitor.visitTypeInsn(NEW, nextType); mVisitor.visitInsn(DUP); mVisitor.visitVarInsn(ALOAD, 0); mVisitor.visitFieldInsn(GETFIELD, type, "parent", elementTypeDesc); mVisitor.visitVarInsn(ALOAD, 0); mVisitor.visitFieldInsn(GETFIELD, type, "visitor", elementVisitorTypeDesc); if (className.equals(nextTypeName)){ mVisitor.visitInsn(ICONST_0); } else { mVisitor.visitInsn(ICONST_1); } mVisitor.visitMethodInsn(INVOKESPECIAL, nextType, CONSTRUCTOR, "(" + elementTypeDesc + elementVisitorTypeDesc + "Z)V", false); mVisitor.visitInsn(ARETURN); mVisitor.visitMaxs(5, 2); mVisitor.visitEnd(); }
java
private void generateSequenceMethod(ClassWriter classWriter, String className, String javaType, String addingChildName, String typeName, String nextTypeName, String apiName) { String type = getFullClassTypeName(typeName, apiName); String nextType = getFullClassTypeName(nextTypeName, apiName); String nextTypeDesc = getFullClassTypeNameDesc(nextTypeName, apiName); String addingType = getFullClassTypeName(addingChildName, apiName); javaType = javaType == null ? JAVA_STRING_DESC : javaType; MethodVisitor mVisitor = classWriter.visitMethod(ACC_PUBLIC, firstToLower(addingChildName), "(" + javaType + ")" + nextTypeDesc, "(" + javaType + ")L" + nextType + "<TZ;>;", null); mVisitor.visitLocalVariable(firstToLower(addingChildName), JAVA_STRING_DESC, null, new Label(), new Label(),1); mVisitor.visitCode(); mVisitor.visitTypeInsn(NEW, addingType); mVisitor.visitInsn(DUP); mVisitor.visitVarInsn(ALOAD, 0); mVisitor.visitVarInsn(ALOAD, 0); mVisitor.visitFieldInsn(GETFIELD, type, "visitor", elementVisitorTypeDesc); mVisitor.visitInsn(ICONST_1); mVisitor.visitMethodInsn(INVOKESPECIAL, addingType, CONSTRUCTOR, "(" + elementTypeDesc + elementVisitorTypeDesc + "Z)V", false); mVisitor.visitVarInsn(ALOAD, 1); mVisitor.visitMethodInsn(INVOKEVIRTUAL, addingType, "text", "(" + JAVA_OBJECT_DESC + ")" + elementTypeDesc, false); mVisitor.visitTypeInsn(CHECKCAST, addingType); mVisitor.visitMethodInsn(INVOKEVIRTUAL, addingType, "__", "()" + elementTypeDesc, false); mVisitor.visitInsn(POP); mVisitor.visitTypeInsn(NEW, nextType); mVisitor.visitInsn(DUP); mVisitor.visitVarInsn(ALOAD, 0); mVisitor.visitFieldInsn(GETFIELD, type, "parent", elementTypeDesc); mVisitor.visitVarInsn(ALOAD, 0); mVisitor.visitFieldInsn(GETFIELD, type, "visitor", elementVisitorTypeDesc); if (className.equals(nextTypeName)){ mVisitor.visitInsn(ICONST_0); } else { mVisitor.visitInsn(ICONST_1); } mVisitor.visitMethodInsn(INVOKESPECIAL, nextType, CONSTRUCTOR, "(" + elementTypeDesc + elementVisitorTypeDesc + "Z)V", false); mVisitor.visitInsn(ARETURN); mVisitor.visitMaxs(5, 2); mVisitor.visitEnd(); }
[ "private", "void", "generateSequenceMethod", "(", "ClassWriter", "classWriter", ",", "String", "className", ",", "String", "javaType", ",", "String", "addingChildName", ",", "String", "typeName", ",", "String", "nextTypeName", ",", "String", "apiName", ")", "{", "String", "type", "=", "getFullClassTypeName", "(", "typeName", ",", "apiName", ")", ";", "String", "nextType", "=", "getFullClassTypeName", "(", "nextTypeName", ",", "apiName", ")", ";", "String", "nextTypeDesc", "=", "getFullClassTypeNameDesc", "(", "nextTypeName", ",", "apiName", ")", ";", "String", "addingType", "=", "getFullClassTypeName", "(", "addingChildName", ",", "apiName", ")", ";", "javaType", "=", "javaType", "==", "null", "?", "JAVA_STRING_DESC", ":", "javaType", ";", "MethodVisitor", "mVisitor", "=", "classWriter", ".", "visitMethod", "(", "ACC_PUBLIC", ",", "firstToLower", "(", "addingChildName", ")", ",", "\"(\"", "+", "javaType", "+", "\")\"", "+", "nextTypeDesc", ",", "\"(\"", "+", "javaType", "+", "\")L\"", "+", "nextType", "+", "\"<TZ;>;\"", ",", "null", ")", ";", "mVisitor", ".", "visitLocalVariable", "(", "firstToLower", "(", "addingChildName", ")", ",", "JAVA_STRING_DESC", ",", "null", ",", "new", "Label", "(", ")", ",", "new", "Label", "(", ")", ",", "1", ")", ";", "mVisitor", ".", "visitCode", "(", ")", ";", "mVisitor", ".", "visitTypeInsn", "(", "NEW", ",", "addingType", ")", ";", "mVisitor", ".", "visitInsn", "(", "DUP", ")", ";", "mVisitor", ".", "visitVarInsn", "(", "ALOAD", ",", "0", ")", ";", "mVisitor", ".", "visitVarInsn", "(", "ALOAD", ",", "0", ")", ";", "mVisitor", ".", "visitFieldInsn", "(", "GETFIELD", ",", "type", ",", "\"visitor\"", ",", "elementVisitorTypeDesc", ")", ";", "mVisitor", ".", "visitInsn", "(", "ICONST_1", ")", ";", "mVisitor", ".", "visitMethodInsn", "(", "INVOKESPECIAL", ",", "addingType", ",", "CONSTRUCTOR", ",", "\"(\"", "+", "elementTypeDesc", "+", "elementVisitorTypeDesc", "+", "\"Z)V\"", ",", "false", ")", ";", "mVisitor", ".", "visitVarInsn", "(", "ALOAD", ",", "1", ")", ";", "mVisitor", ".", "visitMethodInsn", "(", "INVOKEVIRTUAL", ",", "addingType", ",", "\"text\"", ",", "\"(\"", "+", "JAVA_OBJECT_DESC", "+", "\")\"", "+", "elementTypeDesc", ",", "false", ")", ";", "mVisitor", ".", "visitTypeInsn", "(", "CHECKCAST", ",", "addingType", ")", ";", "mVisitor", ".", "visitMethodInsn", "(", "INVOKEVIRTUAL", ",", "addingType", ",", "\"__\"", ",", "\"()\"", "+", "elementTypeDesc", ",", "false", ")", ";", "mVisitor", ".", "visitInsn", "(", "POP", ")", ";", "mVisitor", ".", "visitTypeInsn", "(", "NEW", ",", "nextType", ")", ";", "mVisitor", ".", "visitInsn", "(", "DUP", ")", ";", "mVisitor", ".", "visitVarInsn", "(", "ALOAD", ",", "0", ")", ";", "mVisitor", ".", "visitFieldInsn", "(", "GETFIELD", ",", "type", ",", "\"parent\"", ",", "elementTypeDesc", ")", ";", "mVisitor", ".", "visitVarInsn", "(", "ALOAD", ",", "0", ")", ";", "mVisitor", ".", "visitFieldInsn", "(", "GETFIELD", ",", "type", ",", "\"visitor\"", ",", "elementVisitorTypeDesc", ")", ";", "if", "(", "className", ".", "equals", "(", "nextTypeName", ")", ")", "{", "mVisitor", ".", "visitInsn", "(", "ICONST_0", ")", ";", "}", "else", "{", "mVisitor", ".", "visitInsn", "(", "ICONST_1", ")", ";", "}", "mVisitor", ".", "visitMethodInsn", "(", "INVOKESPECIAL", ",", "nextType", ",", "CONSTRUCTOR", ",", "\"(\"", "+", "elementTypeDesc", "+", "elementVisitorTypeDesc", "+", "\"Z)V\"", ",", "false", ")", ";", "mVisitor", ".", "visitInsn", "(", "ARETURN", ")", ";", "mVisitor", ".", "visitMaxs", "(", "5", ",", "2", ")", ";", "mVisitor", ".", "visitEnd", "(", ")", ";", "}" ]
<xs:element name="personInfo"> <xs:complexType> <xs:sequence> <xs:element name="firstName" type="xs:string"/> (...) Generates the method present in the sequence interface for a sequence element. Example: PersonInfoFirstName firstName(String firstName); @param classWriter The {@link ClassWriter} of the sequence interface. @param className The name of the class which contains the sequence. @param javaType The java type of the current sequence value. @param addingChildName The name of the child to be added. Based in the example above, it would be firstName. @param typeName The name of the current type, which would be PersonInfo based on the above example. @param nextTypeName The name of the next type, which would be PersonInfoFirstName based on the above example. @param apiName The name of the generated fluent interface.
[ "<xs", ":", "element", "name", "=", "personInfo", ">", "<xs", ":", "complexType", ">", "<xs", ":", "sequence", ">", "<xs", ":", "element", "name", "=", "firstName", "type", "=", "xs", ":", "string", "/", ">", "(", "...", ")", "Generates", "the", "method", "present", "in", "the", "sequence", "interface", "for", "a", "sequence", "element", ".", "Example", ":", "PersonInfoFirstName", "firstName", "(", "String", "firstName", ")", ";" ]
train
https://github.com/xmlet/XsdAsmFaster/blob/ccb78f9dd4b957ad5ac1ca349eaf24338c421e94/src/main/java/org/xmlet/xsdasmfaster/classes/XsdAsmInterfaces.java#L526-L566
joelittlejohn/jsonschema2pojo
jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/rules/TypeRule.java
TypeRule.getIntegerType
private JType getIntegerType(JCodeModel owner, JsonNode node, GenerationConfig config) { if (config.isUseBigIntegers()) { return unboxIfNecessary(owner.ref(BigInteger.class), config); } else if (config.isUseLongIntegers() || node.has("minimum") && node.get("minimum").isLong() || node.has("maximum") && node.get("maximum") .isLong()) { return unboxIfNecessary(owner.ref(Long.class), config); } else { return unboxIfNecessary(owner.ref(Integer.class), config); } }
java
private JType getIntegerType(JCodeModel owner, JsonNode node, GenerationConfig config) { if (config.isUseBigIntegers()) { return unboxIfNecessary(owner.ref(BigInteger.class), config); } else if (config.isUseLongIntegers() || node.has("minimum") && node.get("minimum").isLong() || node.has("maximum") && node.get("maximum") .isLong()) { return unboxIfNecessary(owner.ref(Long.class), config); } else { return unboxIfNecessary(owner.ref(Integer.class), config); } }
[ "private", "JType", "getIntegerType", "(", "JCodeModel", "owner", ",", "JsonNode", "node", ",", "GenerationConfig", "config", ")", "{", "if", "(", "config", ".", "isUseBigIntegers", "(", ")", ")", "{", "return", "unboxIfNecessary", "(", "owner", ".", "ref", "(", "BigInteger", ".", "class", ")", ",", "config", ")", ";", "}", "else", "if", "(", "config", ".", "isUseLongIntegers", "(", ")", "||", "node", ".", "has", "(", "\"minimum\"", ")", "&&", "node", ".", "get", "(", "\"minimum\"", ")", ".", "isLong", "(", ")", "||", "node", ".", "has", "(", "\"maximum\"", ")", "&&", "node", ".", "get", "(", "\"maximum\"", ")", ".", "isLong", "(", ")", ")", "{", "return", "unboxIfNecessary", "(", "owner", ".", "ref", "(", "Long", ".", "class", ")", ",", "config", ")", ";", "}", "else", "{", "return", "unboxIfNecessary", "(", "owner", ".", "ref", "(", "Integer", ".", "class", ")", ",", "config", ")", ";", "}", "}" ]
Returns the JType for an integer field. Handles type lookup and unboxing.
[ "Returns", "the", "JType", "for", "an", "integer", "field", ".", "Handles", "type", "lookup", "and", "unboxing", "." ]
train
https://github.com/joelittlejohn/jsonschema2pojo/blob/0552b80db93214eb186e4ae45b40866cc1e7eb84/jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/rules/TypeRule.java#L146-L157
Omertron/api-themoviedb
src/main/java/com/omertron/themoviedbapi/methods/TmdbEpisodes.java
TmdbEpisodes.getEpisodeInfo
public TVEpisodeInfo getEpisodeInfo(int tvID, int seasonNumber, int episodeNumber, String language, String... appendToResponse) throws MovieDbException { TmdbParameters parameters = new TmdbParameters(); parameters.add(Param.ID, tvID); parameters.add(Param.SEASON_NUMBER, seasonNumber); parameters.add(Param.EPISODE_NUMBER, episodeNumber); parameters.add(Param.LANGUAGE, language); parameters.add(Param.APPEND, appendToResponse); URL url = new ApiUrl(apiKey, MethodBase.EPISODE).buildUrl(parameters); String webpage = httpTools.getRequest(url); try { return MAPPER.readValue(webpage, TVEpisodeInfo.class); } catch (IOException ex) { throw new MovieDbException(ApiExceptionType.MAPPING_FAILED, "Failed to get TV Episode Info", url, ex); } }
java
public TVEpisodeInfo getEpisodeInfo(int tvID, int seasonNumber, int episodeNumber, String language, String... appendToResponse) throws MovieDbException { TmdbParameters parameters = new TmdbParameters(); parameters.add(Param.ID, tvID); parameters.add(Param.SEASON_NUMBER, seasonNumber); parameters.add(Param.EPISODE_NUMBER, episodeNumber); parameters.add(Param.LANGUAGE, language); parameters.add(Param.APPEND, appendToResponse); URL url = new ApiUrl(apiKey, MethodBase.EPISODE).buildUrl(parameters); String webpage = httpTools.getRequest(url); try { return MAPPER.readValue(webpage, TVEpisodeInfo.class); } catch (IOException ex) { throw new MovieDbException(ApiExceptionType.MAPPING_FAILED, "Failed to get TV Episode Info", url, ex); } }
[ "public", "TVEpisodeInfo", "getEpisodeInfo", "(", "int", "tvID", ",", "int", "seasonNumber", ",", "int", "episodeNumber", ",", "String", "language", ",", "String", "...", "appendToResponse", ")", "throws", "MovieDbException", "{", "TmdbParameters", "parameters", "=", "new", "TmdbParameters", "(", ")", ";", "parameters", ".", "add", "(", "Param", ".", "ID", ",", "tvID", ")", ";", "parameters", ".", "add", "(", "Param", ".", "SEASON_NUMBER", ",", "seasonNumber", ")", ";", "parameters", ".", "add", "(", "Param", ".", "EPISODE_NUMBER", ",", "episodeNumber", ")", ";", "parameters", ".", "add", "(", "Param", ".", "LANGUAGE", ",", "language", ")", ";", "parameters", ".", "add", "(", "Param", ".", "APPEND", ",", "appendToResponse", ")", ";", "URL", "url", "=", "new", "ApiUrl", "(", "apiKey", ",", "MethodBase", ".", "EPISODE", ")", ".", "buildUrl", "(", "parameters", ")", ";", "String", "webpage", "=", "httpTools", ".", "getRequest", "(", "url", ")", ";", "try", "{", "return", "MAPPER", ".", "readValue", "(", "webpage", ",", "TVEpisodeInfo", ".", "class", ")", ";", "}", "catch", "(", "IOException", "ex", ")", "{", "throw", "new", "MovieDbException", "(", "ApiExceptionType", ".", "MAPPING_FAILED", ",", "\"Failed to get TV Episode Info\"", ",", "url", ",", "ex", ")", ";", "}", "}" ]
Get the primary information about a TV episode by combination of a season and episode number. @param tvID @param seasonNumber @param episodeNumber @param language @param appendToResponse @return @throws MovieDbException
[ "Get", "the", "primary", "information", "about", "a", "TV", "episode", "by", "combination", "of", "a", "season", "and", "episode", "number", "." ]
train
https://github.com/Omertron/api-themoviedb/blob/bf132d7c7271734e13b58ba3bc92bba46f220118/src/main/java/com/omertron/themoviedbapi/methods/TmdbEpisodes.java#L78-L94
Netflix/conductor
client/src/main/java/com/netflix/conductor/client/http/TaskClient.java
TaskClient.logMessageForTask
public void logMessageForTask(String taskId, String logMessage) { Preconditions.checkArgument(StringUtils.isNotBlank(taskId), "Task id cannot be blank"); postForEntityWithRequestOnly("tasks/" + taskId + "/log", logMessage); }
java
public void logMessageForTask(String taskId, String logMessage) { Preconditions.checkArgument(StringUtils.isNotBlank(taskId), "Task id cannot be blank"); postForEntityWithRequestOnly("tasks/" + taskId + "/log", logMessage); }
[ "public", "void", "logMessageForTask", "(", "String", "taskId", ",", "String", "logMessage", ")", "{", "Preconditions", ".", "checkArgument", "(", "StringUtils", ".", "isNotBlank", "(", "taskId", ")", ",", "\"Task id cannot be blank\"", ")", ";", "postForEntityWithRequestOnly", "(", "\"tasks/\"", "+", "taskId", "+", "\"/log\"", ",", "logMessage", ")", ";", "}" ]
Log execution messages for a task. @param taskId id of the task @param logMessage the message to be logged
[ "Log", "execution", "messages", "for", "a", "task", "." ]
train
https://github.com/Netflix/conductor/blob/78fae0ed9ddea22891f9eebb96a2ec0b2783dca0/client/src/main/java/com/netflix/conductor/client/http/TaskClient.java#L288-L291
netscaler/nitro
src/main/java/com/citrix/netscaler/nitro/resource/config/ssl/sslocspresponder.java
sslocspresponder.get
public static sslocspresponder get(nitro_service service, String name) throws Exception{ sslocspresponder obj = new sslocspresponder(); obj.set_name(name); sslocspresponder response = (sslocspresponder) obj.get_resource(service); return response; }
java
public static sslocspresponder get(nitro_service service, String name) throws Exception{ sslocspresponder obj = new sslocspresponder(); obj.set_name(name); sslocspresponder response = (sslocspresponder) obj.get_resource(service); return response; }
[ "public", "static", "sslocspresponder", "get", "(", "nitro_service", "service", ",", "String", "name", ")", "throws", "Exception", "{", "sslocspresponder", "obj", "=", "new", "sslocspresponder", "(", ")", ";", "obj", ".", "set_name", "(", "name", ")", ";", "sslocspresponder", "response", "=", "(", "sslocspresponder", ")", "obj", ".", "get_resource", "(", "service", ")", ";", "return", "response", ";", "}" ]
Use this API to fetch sslocspresponder resource of given name .
[ "Use", "this", "API", "to", "fetch", "sslocspresponder", "resource", "of", "given", "name", "." ]
train
https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/ssl/sslocspresponder.java#L634-L639
mangstadt/biweekly
src/main/java/biweekly/util/com/google/ical/util/TimeUtils.java
TimeUtils.timetMillisFromEpochSecs
private static long timetMillisFromEpochSecs(long epochSecs, TimeZone zone) { DateTimeValue date = timeFromSecsSinceEpoch(epochSecs); Calendar cal = new GregorianCalendar(zone); cal.clear(); cal.set(date.year(), date.month() - 1, date.day(), date.hour(), date.minute(), date.second()); return cal.getTimeInMillis(); }
java
private static long timetMillisFromEpochSecs(long epochSecs, TimeZone zone) { DateTimeValue date = timeFromSecsSinceEpoch(epochSecs); Calendar cal = new GregorianCalendar(zone); cal.clear(); cal.set(date.year(), date.month() - 1, date.day(), date.hour(), date.minute(), date.second()); return cal.getTimeInMillis(); }
[ "private", "static", "long", "timetMillisFromEpochSecs", "(", "long", "epochSecs", ",", "TimeZone", "zone", ")", "{", "DateTimeValue", "date", "=", "timeFromSecsSinceEpoch", "(", "epochSecs", ")", ";", "Calendar", "cal", "=", "new", "GregorianCalendar", "(", "zone", ")", ";", "cal", ".", "clear", "(", ")", ";", "cal", ".", "set", "(", "date", ".", "year", "(", ")", ",", "date", ".", "month", "(", ")", "-", "1", ",", "date", ".", "day", "(", ")", ",", "date", ".", "hour", "(", ")", ",", "date", ".", "minute", "(", ")", ",", "date", ".", "second", "(", ")", ")", ";", "return", "cal", ".", "getTimeInMillis", "(", ")", ";", "}" ]
Get a "time_t" in milliseconds given a number of seconds since the Dershowitz/Reingold epoch relative to a given timezone. @param epochSecs the number of seconds since the Dershowitz/Reingold epoch relative to the given timezone @param zone timezone against which epochSecs applies @return the number of milliseconds since 00:00:00 Jan 1, 1970 GMT
[ "Get", "a", "time_t", "in", "milliseconds", "given", "a", "number", "of", "seconds", "since", "the", "Dershowitz", "/", "Reingold", "epoch", "relative", "to", "a", "given", "timezone", "." ]
train
https://github.com/mangstadt/biweekly/blob/2e21350f85c13dfff52fdef98fdbebe2976fcf61/src/main/java/biweekly/util/com/google/ical/util/TimeUtils.java#L83-L89
RuedigerMoeller/kontraktor
modules/kontraktor-bare/src/main/java/org/nustaq/kontraktor/barebone/RemoteActorConnection.java
RemoteActorConnection.sendRequests
protected void sendRequests() { if ( ! requestUnderway ) { requestUnderway = true; delayed( new Runnable() { @Override public void run() { synchronized (requests) { Object req[]; if ( openFutureRequests.get() > 0 && requests.size() == 0 ) { req = new Object[] { "SP", lastSeenSeq }; } else { req = new Object[requests.size() + 1]; for (int i = 0; i < requests.size(); i++) { req[i] = requests.get(i); } req[req.length - 1] = lastSeenSeq; requests.clear(); } sendCallArray(req).then(new Callback<Integer>() { @Override public void receive(Integer result, Object error) { synchronized (requests ) { requestUnderway = false; if ( requests.size() > 0 || (result != null && result > 0 && openFutureRequests.get() > 0 ) ) { myExec.execute(new Runnable() { @Override public void run() { sendRequests(); } }); } } } }); } } }, 1); } }
java
protected void sendRequests() { if ( ! requestUnderway ) { requestUnderway = true; delayed( new Runnable() { @Override public void run() { synchronized (requests) { Object req[]; if ( openFutureRequests.get() > 0 && requests.size() == 0 ) { req = new Object[] { "SP", lastSeenSeq }; } else { req = new Object[requests.size() + 1]; for (int i = 0; i < requests.size(); i++) { req[i] = requests.get(i); } req[req.length - 1] = lastSeenSeq; requests.clear(); } sendCallArray(req).then(new Callback<Integer>() { @Override public void receive(Integer result, Object error) { synchronized (requests ) { requestUnderway = false; if ( requests.size() > 0 || (result != null && result > 0 && openFutureRequests.get() > 0 ) ) { myExec.execute(new Runnable() { @Override public void run() { sendRequests(); } }); } } } }); } } }, 1); } }
[ "protected", "void", "sendRequests", "(", ")", "{", "if", "(", "!", "requestUnderway", ")", "{", "requestUnderway", "=", "true", ";", "delayed", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "synchronized", "(", "requests", ")", "{", "Object", "req", "[", "]", ";", "if", "(", "openFutureRequests", ".", "get", "(", ")", ">", "0", "&&", "requests", ".", "size", "(", ")", "==", "0", ")", "{", "req", "=", "new", "Object", "[", "]", "{", "\"SP\"", ",", "lastSeenSeq", "}", ";", "}", "else", "{", "req", "=", "new", "Object", "[", "requests", ".", "size", "(", ")", "+", "1", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "requests", ".", "size", "(", ")", ";", "i", "++", ")", "{", "req", "[", "i", "]", "=", "requests", ".", "get", "(", "i", ")", ";", "}", "req", "[", "req", ".", "length", "-", "1", "]", "=", "lastSeenSeq", ";", "requests", ".", "clear", "(", ")", ";", "}", "sendCallArray", "(", "req", ")", ".", "then", "(", "new", "Callback", "<", "Integer", ">", "(", ")", "{", "@", "Override", "public", "void", "receive", "(", "Integer", "result", ",", "Object", "error", ")", "{", "synchronized", "(", "requests", ")", "{", "requestUnderway", "=", "false", ";", "if", "(", "requests", ".", "size", "(", ")", ">", "0", "||", "(", "result", "!=", "null", "&&", "result", ">", "0", "&&", "openFutureRequests", ".", "get", "(", ")", ">", "0", ")", ")", "{", "myExec", ".", "execute", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "sendRequests", "(", ")", ";", "}", "}", ")", ";", "}", "}", "}", "}", ")", ";", "}", "}", "}", ",", "1", ")", ";", "}", "}" ]
sends pending requests async. needs be executed inside lock (see calls of this)
[ "sends", "pending", "requests", "async", ".", "needs", "be", "executed", "inside", "lock", "(", "see", "calls", "of", "this", ")" ]
train
https://github.com/RuedigerMoeller/kontraktor/blob/d5f3817f9476f3786187b8ef00400b7a4f25a404/modules/kontraktor-bare/src/main/java/org/nustaq/kontraktor/barebone/RemoteActorConnection.java#L437-L476
morimekta/utils
diff-util/src/main/java/net/morimekta/diff/DiffBase.java
DiffBase.linesToChars
LinesToCharsResult linesToChars(String text1, String text2) { List<String> lineArray = new ArrayList<>(); Map<String, Integer> lineHash = new HashMap<>(); // e.g. linearray[4] == "Hello\n" // e.g. linehash.get("Hello\n") == 4 // "\x00" is a valid character, but various debuggers don't like it. // So we'll insert a junk entry to avoid generating a null character. lineArray.add(""); String chars1 = linesToCharsMunge(text1, lineArray, lineHash); String chars2 = linesToCharsMunge(text2, lineArray, lineHash); return new LinesToCharsResult(chars1, chars2, lineArray); }
java
LinesToCharsResult linesToChars(String text1, String text2) { List<String> lineArray = new ArrayList<>(); Map<String, Integer> lineHash = new HashMap<>(); // e.g. linearray[4] == "Hello\n" // e.g. linehash.get("Hello\n") == 4 // "\x00" is a valid character, but various debuggers don't like it. // So we'll insert a junk entry to avoid generating a null character. lineArray.add(""); String chars1 = linesToCharsMunge(text1, lineArray, lineHash); String chars2 = linesToCharsMunge(text2, lineArray, lineHash); return new LinesToCharsResult(chars1, chars2, lineArray); }
[ "LinesToCharsResult", "linesToChars", "(", "String", "text1", ",", "String", "text2", ")", "{", "List", "<", "String", ">", "lineArray", "=", "new", "ArrayList", "<>", "(", ")", ";", "Map", "<", "String", ",", "Integer", ">", "lineHash", "=", "new", "HashMap", "<>", "(", ")", ";", "// e.g. linearray[4] == \"Hello\\n\"", "// e.g. linehash.get(\"Hello\\n\") == 4", "// \"\\x00\" is a valid character, but various debuggers don't like it.", "// So we'll insert a junk entry to avoid generating a null character.", "lineArray", ".", "add", "(", "\"\"", ")", ";", "String", "chars1", "=", "linesToCharsMunge", "(", "text1", ",", "lineArray", ",", "lineHash", ")", ";", "String", "chars2", "=", "linesToCharsMunge", "(", "text2", ",", "lineArray", ",", "lineHash", ")", ";", "return", "new", "LinesToCharsResult", "(", "chars1", ",", "chars2", ",", "lineArray", ")", ";", "}" ]
Split two texts into a list of strings. Reduce the texts to a string of hashes where each Unicode character represents one line. @param text1 First string. @param text2 Second string. @return An object containing the encoded text1, the encoded text2 and the List of unique strings. The zeroth element of the List of unique strings is intentionally blank.
[ "Split", "two", "texts", "into", "a", "list", "of", "strings", ".", "Reduce", "the", "texts", "to", "a", "string", "of", "hashes", "where", "each", "Unicode", "character", "represents", "one", "line", "." ]
train
https://github.com/morimekta/utils/blob/dc987485902f1a7d58169c89c61db97425a6226d/diff-util/src/main/java/net/morimekta/diff/DiffBase.java#L657-L670
fhoeben/hsac-fitnesse-fixtures
src/main/java/nl/hsac/fitnesse/fixture/slim/ListFixture.java
ListFixture.setValueAtIn
public void setValueAtIn(Object value, int index, List aList) { Object cleanValue = cleanupValue(value); while (aList.size() <= index) { aList.add(null); } aList.set(index, cleanValue); }
java
public void setValueAtIn(Object value, int index, List aList) { Object cleanValue = cleanupValue(value); while (aList.size() <= index) { aList.add(null); } aList.set(index, cleanValue); }
[ "public", "void", "setValueAtIn", "(", "Object", "value", ",", "int", "index", ",", "List", "aList", ")", "{", "Object", "cleanValue", "=", "cleanupValue", "(", "value", ")", ";", "while", "(", "aList", ".", "size", "(", ")", "<=", "index", ")", "{", "aList", ".", "add", "(", "null", ")", ";", "}", "aList", ".", "set", "(", "index", ",", "cleanValue", ")", ";", "}" ]
Sets value of element at index (0-based). If the current list has less elements it is extended to have exactly index elements. @param value value to store. @param index 0-based index to add element. @param aList list to set element in.
[ "Sets", "value", "of", "element", "at", "index", "(", "0", "-", "based", ")", ".", "If", "the", "current", "list", "has", "less", "elements", "it", "is", "extended", "to", "have", "exactly", "index", "elements", "." ]
train
https://github.com/fhoeben/hsac-fitnesse-fixtures/blob/4e9018d7386a9aa65bfcbf07eb28ae064edd1732/src/main/java/nl/hsac/fitnesse/fixture/slim/ListFixture.java#L118-L124
sahan/ZombieLink
zombielink/src/main/java/com/lonepulse/zombielink/executor/ConfigurationService.java
ConfigurationService.getDefault
@Override public Configuration getDefault() { return new Configuration() { @Override public HttpClient httpClient() { try { SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory())); PoolingClientConnectionManager pccm = new PoolingClientConnectionManager(schemeRegistry); pccm.setMaxTotal(200); pccm.setDefaultMaxPerRoute(20); return new DefaultHttpClient(pccm); } catch(Exception e) { throw new ConfigurationFailedException(e); } } }; }
java
@Override public Configuration getDefault() { return new Configuration() { @Override public HttpClient httpClient() { try { SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory())); PoolingClientConnectionManager pccm = new PoolingClientConnectionManager(schemeRegistry); pccm.setMaxTotal(200); pccm.setDefaultMaxPerRoute(20); return new DefaultHttpClient(pccm); } catch(Exception e) { throw new ConfigurationFailedException(e); } } }; }
[ "@", "Override", "public", "Configuration", "getDefault", "(", ")", "{", "return", "new", "Configuration", "(", ")", "{", "@", "Override", "public", "HttpClient", "httpClient", "(", ")", "{", "try", "{", "SchemeRegistry", "schemeRegistry", "=", "new", "SchemeRegistry", "(", ")", ";", "schemeRegistry", ".", "register", "(", "new", "Scheme", "(", "\"http\"", ",", "80", ",", "PlainSocketFactory", ".", "getSocketFactory", "(", ")", ")", ")", ";", "schemeRegistry", ".", "register", "(", "new", "Scheme", "(", "\"https\"", ",", "443", ",", "SSLSocketFactory", ".", "getSocketFactory", "(", ")", ")", ")", ";", "PoolingClientConnectionManager", "pccm", "=", "new", "PoolingClientConnectionManager", "(", "schemeRegistry", ")", ";", "pccm", ".", "setMaxTotal", "(", "200", ")", ";", "pccm", ".", "setDefaultMaxPerRoute", "(", "20", ")", ";", "return", "new", "DefaultHttpClient", "(", "pccm", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "ConfigurationFailedException", "(", "e", ")", ";", "}", "}", "}", ";", "}" ]
<p>The <i>out-of-the-box</i> configuration for an instance of {@link HttpClient} which will be used for executing all endpoint requests. Below is a detailed description of all configured properties.</p> <br> <ul> <li> <p><b>HttpClient</b></p> <br> <p>It registers two {@link Scheme}s:</p> <br> <ol> <li><b>HTTP</b> on port <b>80</b> using sockets from {@link PlainSocketFactory#getSocketFactory}</li> <li><b>HTTPS</b> on port <b>443</b> using sockets from {@link SSLSocketFactory#getSocketFactory}</li> </ol> <p>It uses a {@link PoolingClientConnectionManager} with the maximum number of client connections per route set to <b>4</b> and the total set to <b>128</b>.</p> </li> </ul> @return the instance of {@link HttpClient} which will be used for request execution <br><br> @since 1.3.0
[ "<p", ">", "The", "<i", ">", "out", "-", "of", "-", "the", "-", "box<", "/", "i", ">", "configuration", "for", "an", "instance", "of", "{", "@link", "HttpClient", "}", "which", "will", "be", "used", "for", "executing", "all", "endpoint", "requests", ".", "Below", "is", "a", "detailed", "description", "of", "all", "configured", "properties", ".", "<", "/", "p", ">", "<br", ">", "<ul", ">", "<li", ">", "<p", ">", "<b", ">", "HttpClient<", "/", "b", ">", "<", "/", "p", ">", "<br", ">", "<p", ">", "It", "registers", "two", "{", "@link", "Scheme", "}", "s", ":", "<", "/", "p", ">", "<br", ">", "<ol", ">", "<li", ">", "<b", ">", "HTTP<", "/", "b", ">", "on", "port", "<b", ">", "80<", "/", "b", ">", "using", "sockets", "from", "{", "@link", "PlainSocketFactory#getSocketFactory", "}", "<", "/", "li", ">", "<li", ">", "<b", ">", "HTTPS<", "/", "b", ">", "on", "port", "<b", ">", "443<", "/", "b", ">", "using", "sockets", "from", "{", "@link", "SSLSocketFactory#getSocketFactory", "}", "<", "/", "li", ">", "<", "/", "ol", ">" ]
train
https://github.com/sahan/ZombieLink/blob/a9971add56d4f6919a4a5e84c78e9220011d8982/zombielink/src/main/java/com/lonepulse/zombielink/executor/ConfigurationService.java#L71-L97
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/io/dxfdwg/libs/dwg/DwgFile.java
DwgFile.addDwgObjectOffset
public void addDwgObjectOffset( int handle, int offset ) { DwgObjectOffset doo = new DwgObjectOffset(handle, offset); dwgObjectOffsets.add(doo); }
java
public void addDwgObjectOffset( int handle, int offset ) { DwgObjectOffset doo = new DwgObjectOffset(handle, offset); dwgObjectOffsets.add(doo); }
[ "public", "void", "addDwgObjectOffset", "(", "int", "handle", ",", "int", "offset", ")", "{", "DwgObjectOffset", "doo", "=", "new", "DwgObjectOffset", "(", "handle", ",", "offset", ")", ";", "dwgObjectOffsets", ".", "add", "(", "doo", ")", ";", "}" ]
Add a DWG object offset to the dwgObjectOffsets vector @param handle Object handle @param offset Offset of the object data in the DWG file
[ "Add", "a", "DWG", "object", "offset", "to", "the", "dwgObjectOffsets", "vector" ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/io/dxfdwg/libs/dwg/DwgFile.java#L1152-L1155
bootique/bootique-jersey
bootique-jersey/src/main/java/io/bootique/jersey/JerseyModuleExtender.java
JerseyModuleExtender.setProperty
public JerseyModuleExtender setProperty(String name, Object value) { contributeProperties().addBinding(name).toInstance(value); return this; }
java
public JerseyModuleExtender setProperty(String name, Object value) { contributeProperties().addBinding(name).toInstance(value); return this; }
[ "public", "JerseyModuleExtender", "setProperty", "(", "String", "name", ",", "Object", "value", ")", "{", "contributeProperties", "(", ")", ".", "addBinding", "(", "name", ")", ".", "toInstance", "(", "value", ")", ";", "return", "this", ";", "}" ]
Sets Jersey container property. This allows setting ResourceConfig properties that can not be set via JAX RS features. @param name property name @param value property value @return @see org.glassfish.jersey.server.ServerProperties @since 0.22
[ "Sets", "Jersey", "container", "property", ".", "This", "allows", "setting", "ResourceConfig", "properties", "that", "can", "not", "be", "set", "via", "JAX", "RS", "features", "." ]
train
https://github.com/bootique/bootique-jersey/blob/8def056158f0ad1914e975625eb5ed3e4712648c/bootique-jersey/src/main/java/io/bootique/jersey/JerseyModuleExtender.java#L104-L107
lucee/Lucee
core/src/main/java/lucee/runtime/ComponentImpl.java
ComponentImpl.get
protected Object get(int access, String name, Object defaultValue) { return get(access, KeyImpl.init(name), defaultValue); }
java
protected Object get(int access, String name, Object defaultValue) { return get(access, KeyImpl.init(name), defaultValue); }
[ "protected", "Object", "get", "(", "int", "access", ",", "String", "name", ",", "Object", "defaultValue", ")", "{", "return", "get", "(", "access", ",", "KeyImpl", ".", "init", "(", "name", ")", ",", "defaultValue", ")", ";", "}" ]
return element that has at least given access or null @param access @param name @return matching value
[ "return", "element", "that", "has", "at", "least", "given", "access", "or", "null" ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/ComponentImpl.java#L1879-L1881
landawn/AbacusUtil
src/com/landawn/abacus/util/JdbcUtil.java
JdbcUtil.importData
public static int importData(final DataSet dataset, final PreparedStatement stmt) throws UncheckedSQLException { return importData(dataset, dataset.columnNameList(), stmt); }
java
public static int importData(final DataSet dataset, final PreparedStatement stmt) throws UncheckedSQLException { return importData(dataset, dataset.columnNameList(), stmt); }
[ "public", "static", "int", "importData", "(", "final", "DataSet", "dataset", ",", "final", "PreparedStatement", "stmt", ")", "throws", "UncheckedSQLException", "{", "return", "importData", "(", "dataset", ",", "dataset", ".", "columnNameList", "(", ")", ",", "stmt", ")", ";", "}" ]
Imports the data from <code>DataSet</code> to database. @param dataset @param stmt the column order in the sql must be consistent with the column order in the DataSet. @return @throws UncheckedSQLException
[ "Imports", "the", "data", "from", "<code", ">", "DataSet<", "/", "code", ">", "to", "database", "." ]
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/JdbcUtil.java#L2176-L2178
Jasig/uPortal
uPortal-groups/uPortal-groups-core/src/main/java/org/apereo/portal/services/EntityLockService.java
EntityLockService.newReadLock
public IEntityLock newReadLock(Class entityType, String entityKey, String owner) throws LockingException { return lockService.newLock(entityType, entityKey, IEntityLockService.READ_LOCK, owner); }
java
public IEntityLock newReadLock(Class entityType, String entityKey, String owner) throws LockingException { return lockService.newLock(entityType, entityKey, IEntityLockService.READ_LOCK, owner); }
[ "public", "IEntityLock", "newReadLock", "(", "Class", "entityType", ",", "String", "entityKey", ",", "String", "owner", ")", "throws", "LockingException", "{", "return", "lockService", ".", "newLock", "(", "entityType", ",", "entityKey", ",", "IEntityLockService", ".", "READ_LOCK", ",", "owner", ")", ";", "}" ]
Returns a read lock for the entity type, entity key and owner. @return org.apereo.portal.concurrency.locking.IEntityLock @param entityType Class @param entityKey String @param owner String @exception LockingException
[ "Returns", "a", "read", "lock", "for", "the", "entity", "type", "entity", "key", "and", "owner", "." ]
train
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-groups/uPortal-groups-core/src/main/java/org/apereo/portal/services/EntityLockService.java#L118-L121
mygreen/xlsmapper
src/main/java/com/gh/mygreen/xlsmapper/xml/AnnotationReader.java
AnnotationReader.hasAnnotation
public <A extends Annotation> boolean hasAnnotation(final Method method, final Class<A> annClass) { return getAnnotation(method, annClass) != null; }
java
public <A extends Annotation> boolean hasAnnotation(final Method method, final Class<A> annClass) { return getAnnotation(method, annClass) != null; }
[ "public", "<", "A", "extends", "Annotation", ">", "boolean", "hasAnnotation", "(", "final", "Method", "method", ",", "final", "Class", "<", "A", ">", "annClass", ")", "{", "return", "getAnnotation", "(", "method", ",", "annClass", ")", "!=", "null", ";", "}" ]
メソッドに付与されたアノテーションを持つか判定します。 @since 2.0 @param method 判定対象のメソッド @param annClass アノテーションのタイプ @return trueの場合、アノテーションを持ちます。
[ "メソッドに付与されたアノテーションを持つか判定します。" ]
train
https://github.com/mygreen/xlsmapper/blob/a0c6b25c622e5f3a50b199ef685d2ee46ad5483c/src/main/java/com/gh/mygreen/xlsmapper/xml/AnnotationReader.java#L145-L147
phax/ph-commons
ph-xml/src/main/java/com/helger/xml/serialize/write/XMLEmitter.java
XMLEmitter.onText
public void onText (@Nullable final String sText, final boolean bEscape) { if (bEscape) _appendMasked (EXMLCharMode.TEXT, sText); else _append (sText); }
java
public void onText (@Nullable final String sText, final boolean bEscape) { if (bEscape) _appendMasked (EXMLCharMode.TEXT, sText); else _append (sText); }
[ "public", "void", "onText", "(", "@", "Nullable", "final", "String", "sText", ",", "final", "boolean", "bEscape", ")", "{", "if", "(", "bEscape", ")", "_appendMasked", "(", "EXMLCharMode", ".", "TEXT", ",", "sText", ")", ";", "else", "_append", "(", "sText", ")", ";", "}" ]
Text node. @param sText The contained text @param bEscape If <code>true</code> the text should be XML masked (the default), <code>false</code> if not. The <code>false</code> case is especially interesting for HTML inline JS and CSS code.
[ "Text", "node", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-xml/src/main/java/com/helger/xml/serialize/write/XMLEmitter.java#L478-L484
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/TimeZoneFormat.java
TimeZoneFormat.setGMTOffsetPattern
public TimeZoneFormat setGMTOffsetPattern(GMTOffsetPatternType type, String pattern) { if (isFrozen()) { throw new UnsupportedOperationException("Attempt to modify frozen object"); } if (pattern == null) { throw new NullPointerException("Null GMT offset pattern"); } Object[] parsedItems = parseOffsetPattern(pattern, type.required()); _gmtOffsetPatterns[type.ordinal()] = pattern; _gmtOffsetPatternItems[type.ordinal()] = parsedItems; checkAbuttingHoursAndMinutes(); return this; }
java
public TimeZoneFormat setGMTOffsetPattern(GMTOffsetPatternType type, String pattern) { if (isFrozen()) { throw new UnsupportedOperationException("Attempt to modify frozen object"); } if (pattern == null) { throw new NullPointerException("Null GMT offset pattern"); } Object[] parsedItems = parseOffsetPattern(pattern, type.required()); _gmtOffsetPatterns[type.ordinal()] = pattern; _gmtOffsetPatternItems[type.ordinal()] = parsedItems; checkAbuttingHoursAndMinutes(); return this; }
[ "public", "TimeZoneFormat", "setGMTOffsetPattern", "(", "GMTOffsetPatternType", "type", ",", "String", "pattern", ")", "{", "if", "(", "isFrozen", "(", ")", ")", "{", "throw", "new", "UnsupportedOperationException", "(", "\"Attempt to modify frozen object\"", ")", ";", "}", "if", "(", "pattern", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"Null GMT offset pattern\"", ")", ";", "}", "Object", "[", "]", "parsedItems", "=", "parseOffsetPattern", "(", "pattern", ",", "type", ".", "required", "(", ")", ")", ";", "_gmtOffsetPatterns", "[", "type", ".", "ordinal", "(", ")", "]", "=", "pattern", ";", "_gmtOffsetPatternItems", "[", "type", ".", "ordinal", "(", ")", "]", "=", "parsedItems", ";", "checkAbuttingHoursAndMinutes", "(", ")", ";", "return", "this", ";", "}" ]
Sets the offset pattern for the given offset type. @param type the offset pattern. @param pattern the pattern string. @return this object. @throws IllegalArgumentException when the pattern string does not have required time field letters. @throws UnsupportedOperationException when this object is frozen. @see #getGMTOffsetPattern(GMTOffsetPatternType)
[ "Sets", "the", "offset", "pattern", "for", "the", "given", "offset", "type", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/TimeZoneFormat.java#L584-L599
willowtreeapps/Hyperion-Android
hyperion-phoenix/src/main/java/com/willowtreeapps/hyperion/phoenix/ProcessPhoenix.java
ProcessPhoenix.triggerRebirth
public static void triggerRebirth(Context context, Intent... nextIntents) { Intent intent = new Intent(context, ProcessPhoenix.class); intent.addFlags(FLAG_ACTIVITY_NEW_TASK); // In case we are called with non-Activity context. intent.putParcelableArrayListExtra(KEY_RESTART_INTENTS, new ArrayList<>(Arrays.asList(nextIntents))); intent.putExtra(KEY_CLEAR_CACHE, options.shouldClearCache()); intent.putExtra(KEY_CLEAR_DATA, options.shouldClearData()); context.startActivity(intent); if (context instanceof Activity) { ((Activity) context).finish(); } Runtime.getRuntime().exit(0); // Kill kill kill! }
java
public static void triggerRebirth(Context context, Intent... nextIntents) { Intent intent = new Intent(context, ProcessPhoenix.class); intent.addFlags(FLAG_ACTIVITY_NEW_TASK); // In case we are called with non-Activity context. intent.putParcelableArrayListExtra(KEY_RESTART_INTENTS, new ArrayList<>(Arrays.asList(nextIntents))); intent.putExtra(KEY_CLEAR_CACHE, options.shouldClearCache()); intent.putExtra(KEY_CLEAR_DATA, options.shouldClearData()); context.startActivity(intent); if (context instanceof Activity) { ((Activity) context).finish(); } Runtime.getRuntime().exit(0); // Kill kill kill! }
[ "public", "static", "void", "triggerRebirth", "(", "Context", "context", ",", "Intent", "...", "nextIntents", ")", "{", "Intent", "intent", "=", "new", "Intent", "(", "context", ",", "ProcessPhoenix", ".", "class", ")", ";", "intent", ".", "addFlags", "(", "FLAG_ACTIVITY_NEW_TASK", ")", ";", "// In case we are called with non-Activity context.", "intent", ".", "putParcelableArrayListExtra", "(", "KEY_RESTART_INTENTS", ",", "new", "ArrayList", "<>", "(", "Arrays", ".", "asList", "(", "nextIntents", ")", ")", ")", ";", "intent", ".", "putExtra", "(", "KEY_CLEAR_CACHE", ",", "options", ".", "shouldClearCache", "(", ")", ")", ";", "intent", ".", "putExtra", "(", "KEY_CLEAR_DATA", ",", "options", ".", "shouldClearData", "(", ")", ")", ";", "context", ".", "startActivity", "(", "intent", ")", ";", "if", "(", "context", "instanceof", "Activity", ")", "{", "(", "(", "Activity", ")", "context", ")", ".", "finish", "(", ")", ";", "}", "Runtime", ".", "getRuntime", "(", ")", ".", "exit", "(", "0", ")", ";", "// Kill kill kill!", "}" ]
Call to restart the application process using the specified intents. <p> Behavior of the current process after invoking this method is undefined.
[ "Call", "to", "restart", "the", "application", "process", "using", "the", "specified", "intents", ".", "<p", ">", "Behavior", "of", "the", "current", "process", "after", "invoking", "this", "method", "is", "undefined", "." ]
train
https://github.com/willowtreeapps/Hyperion-Android/blob/1910f53869a53f1395ba90588a0b4db7afdec79c/hyperion-phoenix/src/main/java/com/willowtreeapps/hyperion/phoenix/ProcessPhoenix.java#L61-L72
op4j/op4j
src/main/java/org/op4j/Op.java
Op.onArray
public static <T> Level0ArrayOperator<Date[],Date> onArray(final Date[] target) { return onArrayOf(Types.DATE, target); }
java
public static <T> Level0ArrayOperator<Date[],Date> onArray(final Date[] target) { return onArrayOf(Types.DATE, target); }
[ "public", "static", "<", "T", ">", "Level0ArrayOperator", "<", "Date", "[", "]", ",", "Date", ">", "onArray", "(", "final", "Date", "[", "]", "target", ")", "{", "return", "onArrayOf", "(", "Types", ".", "DATE", ",", "target", ")", ";", "}" ]
<p> Creates an <i>operation expression</i> on the specified target object. </p> @param target the target object on which the expression will execute @return an operator, ready for chaining
[ "<p", ">", "Creates", "an", "<i", ">", "operation", "expression<", "/", "i", ">", "on", "the", "specified", "target", "object", ".", "<", "/", "p", ">" ]
train
https://github.com/op4j/op4j/blob/b577596dfe462089d3dd169666defc6de7ad289a/src/main/java/org/op4j/Op.java#L819-L821
blinkfox/zealot
src/main/java/com/blinkfox/zealot/core/ZealotKhala.java
ZealotKhala.doBetween
private ZealotKhala doBetween(String prefix, String field, Object startValue, Object endValue, boolean match) { if (match) { SqlInfoBuilder.newInstace(this.source.setPrefix(prefix)).buildBetweenSql(field, startValue, endValue); this.source.resetPrefix(); } return this; }
java
private ZealotKhala doBetween(String prefix, String field, Object startValue, Object endValue, boolean match) { if (match) { SqlInfoBuilder.newInstace(this.source.setPrefix(prefix)).buildBetweenSql(field, startValue, endValue); this.source.resetPrefix(); } return this; }
[ "private", "ZealotKhala", "doBetween", "(", "String", "prefix", ",", "String", "field", ",", "Object", "startValue", ",", "Object", "endValue", ",", "boolean", "match", ")", "{", "if", "(", "match", ")", "{", "SqlInfoBuilder", ".", "newInstace", "(", "this", ".", "source", ".", "setPrefix", "(", "prefix", ")", ")", ".", "buildBetweenSql", "(", "field", ",", "startValue", ",", "endValue", ")", ";", "this", ".", "source", ".", "resetPrefix", "(", ")", ";", "}", "return", "this", ";", "}" ]
执行生成like模糊查询SQL片段的方法. @param prefix 前缀 @param field 数据库字段 @param startValue 值 @param endValue 值 @param match 是否匹配 @return ZealotKhala实例的当前实例
[ "执行生成like模糊查询SQL片段的方法", "." ]
train
https://github.com/blinkfox/zealot/blob/21b00fa3e4ed42188eef3116d494e112e7a4194c/src/main/java/com/blinkfox/zealot/core/ZealotKhala.java#L429-L435
apache/incubator-gobblin
gobblin-runtime/src/main/java/org/apache/gobblin/runtime/AbstractJobLauncher.java
AbstractJobLauncher.cancelJob
@Override public void cancelJob(JobListener jobListener) throws JobException { synchronized (this.cancellationRequest) { if (this.cancellationRequested) { // Return immediately if a cancellation has already been requested return; } this.cancellationRequested = true; // Notify the cancellation executor that a cancellation has been requested this.cancellationRequest.notify(); } synchronized (this.cancellationExecution) { try { while (!this.cancellationExecuted) { // Wait for the cancellation to be executed this.cancellationExecution.wait(); } try { LOG.info("Current job state is: " + this.jobContext.getJobState().getState()); if (this.jobContext.getJobState().getState() != JobState.RunningState.COMMITTED && ( this.jobContext.getJobCommitPolicy() == JobCommitPolicy.COMMIT_SUCCESSFUL_TASKS || this.jobContext.getJobCommitPolicy() == JobCommitPolicy.COMMIT_ON_PARTIAL_SUCCESS)) { this.jobContext.finalizeJobStateBeforeCommit(); this.jobContext.commit(true); } this.jobContext.close(); } catch (IOException ioe) { LOG.error("Could not close job context.", ioe); } notifyListeners(this.jobContext, jobListener, TimingEvent.LauncherTimings.JOB_CANCEL, new JobListenerAction() { @Override public void apply(JobListener jobListener, JobContext jobContext) throws Exception { jobListener.onJobCancellation(jobContext); } }); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } } }
java
@Override public void cancelJob(JobListener jobListener) throws JobException { synchronized (this.cancellationRequest) { if (this.cancellationRequested) { // Return immediately if a cancellation has already been requested return; } this.cancellationRequested = true; // Notify the cancellation executor that a cancellation has been requested this.cancellationRequest.notify(); } synchronized (this.cancellationExecution) { try { while (!this.cancellationExecuted) { // Wait for the cancellation to be executed this.cancellationExecution.wait(); } try { LOG.info("Current job state is: " + this.jobContext.getJobState().getState()); if (this.jobContext.getJobState().getState() != JobState.RunningState.COMMITTED && ( this.jobContext.getJobCommitPolicy() == JobCommitPolicy.COMMIT_SUCCESSFUL_TASKS || this.jobContext.getJobCommitPolicy() == JobCommitPolicy.COMMIT_ON_PARTIAL_SUCCESS)) { this.jobContext.finalizeJobStateBeforeCommit(); this.jobContext.commit(true); } this.jobContext.close(); } catch (IOException ioe) { LOG.error("Could not close job context.", ioe); } notifyListeners(this.jobContext, jobListener, TimingEvent.LauncherTimings.JOB_CANCEL, new JobListenerAction() { @Override public void apply(JobListener jobListener, JobContext jobContext) throws Exception { jobListener.onJobCancellation(jobContext); } }); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } } }
[ "@", "Override", "public", "void", "cancelJob", "(", "JobListener", "jobListener", ")", "throws", "JobException", "{", "synchronized", "(", "this", ".", "cancellationRequest", ")", "{", "if", "(", "this", ".", "cancellationRequested", ")", "{", "// Return immediately if a cancellation has already been requested", "return", ";", "}", "this", ".", "cancellationRequested", "=", "true", ";", "// Notify the cancellation executor that a cancellation has been requested", "this", ".", "cancellationRequest", ".", "notify", "(", ")", ";", "}", "synchronized", "(", "this", ".", "cancellationExecution", ")", "{", "try", "{", "while", "(", "!", "this", ".", "cancellationExecuted", ")", "{", "// Wait for the cancellation to be executed", "this", ".", "cancellationExecution", ".", "wait", "(", ")", ";", "}", "try", "{", "LOG", ".", "info", "(", "\"Current job state is: \"", "+", "this", ".", "jobContext", ".", "getJobState", "(", ")", ".", "getState", "(", ")", ")", ";", "if", "(", "this", ".", "jobContext", ".", "getJobState", "(", ")", ".", "getState", "(", ")", "!=", "JobState", ".", "RunningState", ".", "COMMITTED", "&&", "(", "this", ".", "jobContext", ".", "getJobCommitPolicy", "(", ")", "==", "JobCommitPolicy", ".", "COMMIT_SUCCESSFUL_TASKS", "||", "this", ".", "jobContext", ".", "getJobCommitPolicy", "(", ")", "==", "JobCommitPolicy", ".", "COMMIT_ON_PARTIAL_SUCCESS", ")", ")", "{", "this", ".", "jobContext", ".", "finalizeJobStateBeforeCommit", "(", ")", ";", "this", ".", "jobContext", ".", "commit", "(", "true", ")", ";", "}", "this", ".", "jobContext", ".", "close", "(", ")", ";", "}", "catch", "(", "IOException", "ioe", ")", "{", "LOG", ".", "error", "(", "\"Could not close job context.\"", ",", "ioe", ")", ";", "}", "notifyListeners", "(", "this", ".", "jobContext", ",", "jobListener", ",", "TimingEvent", ".", "LauncherTimings", ".", "JOB_CANCEL", ",", "new", "JobListenerAction", "(", ")", "{", "@", "Override", "public", "void", "apply", "(", "JobListener", "jobListener", ",", "JobContext", "jobContext", ")", "throws", "Exception", "{", "jobListener", ".", "onJobCancellation", "(", "jobContext", ")", ";", "}", "}", ")", ";", "}", "catch", "(", "InterruptedException", "ie", ")", "{", "Thread", ".", "currentThread", "(", ")", ".", "interrupt", "(", ")", ";", "}", "}", "}" ]
A default implementation of {@link JobLauncher#cancelJob(JobListener)}. <p> This implementation relies on two conditional variables: one for the condition that a cancellation is requested, and the other for the condition that the cancellation is executed. Upon entrance, the method notifies the cancellation executor started by {@link #startCancellationExecutor()} on the first conditional variable to indicate that a cancellation has been requested so the executor is unblocked. Then it waits on the second conditional variable for the cancellation to be executed. </p> <p> The actual execution of the cancellation is handled by the cancellation executor started by the method {@link #startCancellationExecutor()} that uses the {@link #executeCancellation()} method to execute the cancellation. </p> {@inheritDoc JobLauncher#cancelJob(JobListener)}
[ "A", "default", "implementation", "of", "{", "@link", "JobLauncher#cancelJob", "(", "JobListener", ")", "}", "." ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/AbstractJobLauncher.java#L251-L295
hibernate/hibernate-ogm
core/src/main/java/org/hibernate/ogm/datastore/document/impl/EmbeddableStateFinder.java
EmbeddableStateFinder.getOuterMostNullEmbeddableIfAny
public String getOuterMostNullEmbeddableIfAny(String column) { String[] path = column.split( "\\." ); if ( !isEmbeddableColumn( path ) ) { return null; } // the cached value may be null hence the explicit key lookup if ( columnToOuterMostNullEmbeddableCache.containsKey( column ) ) { return columnToOuterMostNullEmbeddableCache.get( column ); } return determineAndCacheOuterMostNullEmbeddable( column, path ); }
java
public String getOuterMostNullEmbeddableIfAny(String column) { String[] path = column.split( "\\." ); if ( !isEmbeddableColumn( path ) ) { return null; } // the cached value may be null hence the explicit key lookup if ( columnToOuterMostNullEmbeddableCache.containsKey( column ) ) { return columnToOuterMostNullEmbeddableCache.get( column ); } return determineAndCacheOuterMostNullEmbeddable( column, path ); }
[ "public", "String", "getOuterMostNullEmbeddableIfAny", "(", "String", "column", ")", "{", "String", "[", "]", "path", "=", "column", ".", "split", "(", "\"\\\\.\"", ")", ";", "if", "(", "!", "isEmbeddableColumn", "(", "path", ")", ")", "{", "return", "null", ";", "}", "// the cached value may be null hence the explicit key lookup", "if", "(", "columnToOuterMostNullEmbeddableCache", ".", "containsKey", "(", "column", ")", ")", "{", "return", "columnToOuterMostNullEmbeddableCache", ".", "get", "(", "column", ")", ";", "}", "return", "determineAndCacheOuterMostNullEmbeddable", "(", "column", ",", "path", ")", ";", "}" ]
Should only called on a column that is being set to null. Returns the most outer embeddable containing {@code column} that is entirely null. Return null otherwise i.e. not embeddable. The implementation lazily compute the embeddable state and caches it. The idea behind the lazy computation is that only some columns will be set to null and only in some situations. The idea behind caching is that an embeddable contains several columns, no need to recompute its state.
[ "Should", "only", "called", "on", "a", "column", "that", "is", "being", "set", "to", "null", "." ]
train
https://github.com/hibernate/hibernate-ogm/blob/9ea971df7c27277029006a6f748d8272fb1d69d2/core/src/main/java/org/hibernate/ogm/datastore/document/impl/EmbeddableStateFinder.java#L48-L58
StanKocken/EfficientAdapter
efficientadapter/src/main/java/com/skocken/efficientadapter/lib/viewholder/EfficientViewHolder.java
EfficientViewHolder.setImageUri
public void setImageUri(int viewId, @Nullable Uri uri) { ViewHelper.setImageUri(mCacheView, viewId, uri); }
java
public void setImageUri(int viewId, @Nullable Uri uri) { ViewHelper.setImageUri(mCacheView, viewId, uri); }
[ "public", "void", "setImageUri", "(", "int", "viewId", ",", "@", "Nullable", "Uri", "uri", ")", "{", "ViewHelper", ".", "setImageUri", "(", "mCacheView", ",", "viewId", ",", "uri", ")", ";", "}" ]
Equivalent to calling ImageView.setImageUri @param viewId The id of the view whose image should change @param uri the Uri of an image, or {@code null} to clear the content
[ "Equivalent", "to", "calling", "ImageView", ".", "setImageUri" ]
train
https://github.com/StanKocken/EfficientAdapter/blob/0bcc3a20182cbce9d7901e1e2a9104251637167d/efficientadapter/src/main/java/com/skocken/efficientadapter/lib/viewholder/EfficientViewHolder.java#L376-L378
auth0/auth0-java
src/main/java/com/auth0/client/auth/AuthAPI.java
AuthAPI.signUp
public SignUpRequest signUp(String email, String password, String connection) { Asserts.assertNotNull(email, "email"); Asserts.assertNotNull(password, "password"); Asserts.assertNotNull(connection, "connection"); String url = baseUrl .newBuilder() .addPathSegment(PATH_DBCONNECTIONS) .addPathSegment("signup") .build() .toString(); CreateUserRequest request = new CreateUserRequest(client, url); request.addParameter(KEY_CLIENT_ID, clientId); request.addParameter(KEY_EMAIL, email); request.addParameter(KEY_PASSWORD, password); request.addParameter(KEY_CONNECTION, connection); return request; }
java
public SignUpRequest signUp(String email, String password, String connection) { Asserts.assertNotNull(email, "email"); Asserts.assertNotNull(password, "password"); Asserts.assertNotNull(connection, "connection"); String url = baseUrl .newBuilder() .addPathSegment(PATH_DBCONNECTIONS) .addPathSegment("signup") .build() .toString(); CreateUserRequest request = new CreateUserRequest(client, url); request.addParameter(KEY_CLIENT_ID, clientId); request.addParameter(KEY_EMAIL, email); request.addParameter(KEY_PASSWORD, password); request.addParameter(KEY_CONNECTION, connection); return request; }
[ "public", "SignUpRequest", "signUp", "(", "String", "email", ",", "String", "password", ",", "String", "connection", ")", "{", "Asserts", ".", "assertNotNull", "(", "email", ",", "\"email\"", ")", ";", "Asserts", ".", "assertNotNull", "(", "password", ",", "\"password\"", ")", ";", "Asserts", ".", "assertNotNull", "(", "connection", ",", "\"connection\"", ")", ";", "String", "url", "=", "baseUrl", ".", "newBuilder", "(", ")", ".", "addPathSegment", "(", "PATH_DBCONNECTIONS", ")", ".", "addPathSegment", "(", "\"signup\"", ")", ".", "build", "(", ")", ".", "toString", "(", ")", ";", "CreateUserRequest", "request", "=", "new", "CreateUserRequest", "(", "client", ",", "url", ")", ";", "request", ".", "addParameter", "(", "KEY_CLIENT_ID", ",", "clientId", ")", ";", "request", ".", "addParameter", "(", "KEY_EMAIL", ",", "email", ")", ";", "request", ".", "addParameter", "(", "KEY_PASSWORD", ",", "password", ")", ";", "request", ".", "addParameter", "(", "KEY_CONNECTION", ",", "connection", ")", ";", "return", "request", ";", "}" ]
Creates a sign up request with the given credentials and database connection. i.e.: <pre> {@code AuthAPI auth = new AuthAPI("me.auth0.com", "B3c6RYhk1v9SbIJcRIOwu62gIUGsnze", "2679NfkaBn62e6w5E8zNEzjr-yWfkaBne"); try { Map<String, String> fields = new HashMap<String, String>(); fields.put("age", "25); fields.put("city", "Buenos Aires"); auth.signUp("me@auth0.com", "topsecret", "db-connection") .setCustomFields(fields) .execute(); } catch (Auth0Exception e) { //Something happened } } </pre> @param email the desired user's email. @param password the desired user's password. @param connection the database connection where the user is going to be created. @return a Request to configure and execute.
[ "Creates", "a", "sign", "up", "request", "with", "the", "given", "credentials", "and", "database", "connection", ".", "i", ".", "e", ".", ":", "<pre", ">", "{", "@code", "AuthAPI", "auth", "=", "new", "AuthAPI", "(", "me", ".", "auth0", ".", "com", "B3c6RYhk1v9SbIJcRIOwu62gIUGsnze", "2679NfkaBn62e6w5E8zNEzjr", "-", "yWfkaBne", ")", ";", "try", "{", "Map<String", "String", ">", "fields", "=", "new", "HashMap<String", "String", ">", "()", ";", "fields", ".", "put", "(", "age", "25", ")", ";", "fields", ".", "put", "(", "city", "Buenos", "Aires", ")", ";", "auth", ".", "signUp", "(", "me@auth0", ".", "com", "topsecret", "db", "-", "connection", ")", ".", "setCustomFields", "(", "fields", ")", ".", "execute", "()", ";", "}", "catch", "(", "Auth0Exception", "e", ")", "{", "//", "Something", "happened", "}", "}", "<", "/", "pre", ">" ]
train
https://github.com/auth0/auth0-java/blob/b7bc099ee9c6cde5a87c4ecfebc6d811aeb1027c/src/main/java/com/auth0/client/auth/AuthAPI.java#L285-L302
oboehm/jfachwert
src/main/java/de/jfachwert/bank/Geldbetrag.java
Geldbetrag.validate
public static String validate(String zahl) { try { return Geldbetrag.valueOf(zahl).toString(); } catch (IllegalArgumentException ex) { throw new InvalidValueException(zahl, "money_amount", ex); } }
java
public static String validate(String zahl) { try { return Geldbetrag.valueOf(zahl).toString(); } catch (IllegalArgumentException ex) { throw new InvalidValueException(zahl, "money_amount", ex); } }
[ "public", "static", "String", "validate", "(", "String", "zahl", ")", "{", "try", "{", "return", "Geldbetrag", ".", "valueOf", "(", "zahl", ")", ".", "toString", "(", ")", ";", "}", "catch", "(", "IllegalArgumentException", "ex", ")", "{", "throw", "new", "InvalidValueException", "(", "zahl", ",", "\"money_amount\"", ",", "ex", ")", ";", "}", "}" ]
Validiert die uebergebene Zahl, ob sie sich als Geldbetrag eignet. @param zahl als String @return die Zahl zur Weitervarabeitung
[ "Validiert", "die", "uebergebene", "Zahl", "ob", "sie", "sich", "als", "Geldbetrag", "eignet", "." ]
train
https://github.com/oboehm/jfachwert/blob/67b513d29e3114c7aee65cd1ea7a5b7e540b0d1b/src/main/java/de/jfachwert/bank/Geldbetrag.java#L553-L559
netty/netty
transport-native-kqueue/src/main/java/io/netty/channel/kqueue/AbstractKQueueStreamChannel.java
AbstractKQueueStreamChannel.writeBytesMultiple
private int writeBytesMultiple(ChannelOutboundBuffer in, IovArray array) throws IOException { final long expectedWrittenBytes = array.size(); assert expectedWrittenBytes != 0; final int cnt = array.count(); assert cnt != 0; final long localWrittenBytes = socket.writevAddresses(array.memoryAddress(0), cnt); if (localWrittenBytes > 0) { adjustMaxBytesPerGatheringWrite(expectedWrittenBytes, localWrittenBytes, array.maxBytes()); in.removeBytes(localWrittenBytes); return 1; } return WRITE_STATUS_SNDBUF_FULL; }
java
private int writeBytesMultiple(ChannelOutboundBuffer in, IovArray array) throws IOException { final long expectedWrittenBytes = array.size(); assert expectedWrittenBytes != 0; final int cnt = array.count(); assert cnt != 0; final long localWrittenBytes = socket.writevAddresses(array.memoryAddress(0), cnt); if (localWrittenBytes > 0) { adjustMaxBytesPerGatheringWrite(expectedWrittenBytes, localWrittenBytes, array.maxBytes()); in.removeBytes(localWrittenBytes); return 1; } return WRITE_STATUS_SNDBUF_FULL; }
[ "private", "int", "writeBytesMultiple", "(", "ChannelOutboundBuffer", "in", ",", "IovArray", "array", ")", "throws", "IOException", "{", "final", "long", "expectedWrittenBytes", "=", "array", ".", "size", "(", ")", ";", "assert", "expectedWrittenBytes", "!=", "0", ";", "final", "int", "cnt", "=", "array", ".", "count", "(", ")", ";", "assert", "cnt", "!=", "0", ";", "final", "long", "localWrittenBytes", "=", "socket", ".", "writevAddresses", "(", "array", ".", "memoryAddress", "(", "0", ")", ",", "cnt", ")", ";", "if", "(", "localWrittenBytes", ">", "0", ")", "{", "adjustMaxBytesPerGatheringWrite", "(", "expectedWrittenBytes", ",", "localWrittenBytes", ",", "array", ".", "maxBytes", "(", ")", ")", ";", "in", ".", "removeBytes", "(", "localWrittenBytes", ")", ";", "return", "1", ";", "}", "return", "WRITE_STATUS_SNDBUF_FULL", ";", "}" ]
Write multiple bytes via {@link IovArray}. @param in the collection which contains objects to write. @param array The array which contains the content to write. @return The value that should be decremented from the write quantum which starts at {@link ChannelConfig#getWriteSpinCount()}. The typical use cases are as follows: <ul> <li>0 - if no write was attempted. This is appropriate if an empty {@link ByteBuf} (or other empty content) is encountered</li> <li>1 - if a single call to write data was made to the OS</li> <li>{@link ChannelUtils#WRITE_STATUS_SNDBUF_FULL} - if an attempt to write data was made to the OS, but no data was accepted</li> </ul> @throws IOException If an I/O exception occurs during write.
[ "Write", "multiple", "bytes", "via", "{" ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/transport-native-kqueue/src/main/java/io/netty/channel/kqueue/AbstractKQueueStreamChannel.java#L147-L160
mcxiaoke/Android-Next
ui/src/main/java/com/mcxiaoke/next/ui/widget/ArrayAdapterCompat.java
ArrayAdapterCompat.addAll
public void addAll(int index, T... items) { List<T> collection = Arrays.asList(items); synchronized (mLock) { if (mOriginalValues != null) { mOriginalValues.addAll(index, collection); } else { mObjects.addAll(index, collection); } } if (mNotifyOnChange) notifyDataSetChanged(); }
java
public void addAll(int index, T... items) { List<T> collection = Arrays.asList(items); synchronized (mLock) { if (mOriginalValues != null) { mOriginalValues.addAll(index, collection); } else { mObjects.addAll(index, collection); } } if (mNotifyOnChange) notifyDataSetChanged(); }
[ "public", "void", "addAll", "(", "int", "index", ",", "T", "...", "items", ")", "{", "List", "<", "T", ">", "collection", "=", "Arrays", ".", "asList", "(", "items", ")", ";", "synchronized", "(", "mLock", ")", "{", "if", "(", "mOriginalValues", "!=", "null", ")", "{", "mOriginalValues", ".", "addAll", "(", "index", ",", "collection", ")", ";", "}", "else", "{", "mObjects", ".", "addAll", "(", "index", ",", "collection", ")", ";", "}", "}", "if", "(", "mNotifyOnChange", ")", "notifyDataSetChanged", "(", ")", ";", "}" ]
Inserts the specified objects at the specified index in the array. @param items The objects to insert into the array. @param index The index at which the object must be inserted.
[ "Inserts", "the", "specified", "objects", "at", "the", "specified", "index", "in", "the", "array", "." ]
train
https://github.com/mcxiaoke/Android-Next/blob/1bfdf99d0b81a849aa0fa6697c53ed673151ca39/ui/src/main/java/com/mcxiaoke/next/ui/widget/ArrayAdapterCompat.java#L228-L238
Omertron/api-themoviedb
src/main/java/com/omertron/themoviedbapi/TheMovieDbApi.java
TheMovieDbApi.searchCompanies
public ResultList<Company> searchCompanies(String query, Integer page) throws MovieDbException { return tmdbSearch.searchCompanies(query, page); }
java
public ResultList<Company> searchCompanies(String query, Integer page) throws MovieDbException { return tmdbSearch.searchCompanies(query, page); }
[ "public", "ResultList", "<", "Company", ">", "searchCompanies", "(", "String", "query", ",", "Integer", "page", ")", "throws", "MovieDbException", "{", "return", "tmdbSearch", ".", "searchCompanies", "(", "query", ",", "page", ")", ";", "}" ]
Search Companies. You can use this method to search for production companies that are part of TMDb. The company IDs will map to those returned on movie calls. http://help.themoviedb.org/kb/api/search-companies @param query query @param page page @return @throws MovieDbException exception
[ "Search", "Companies", "." ]
train
https://github.com/Omertron/api-themoviedb/blob/bf132d7c7271734e13b58ba3bc92bba46f220118/src/main/java/com/omertron/themoviedbapi/TheMovieDbApi.java#L1317-L1319
google/closure-compiler
src/com/google/javascript/jscomp/ControlFlowAnalysis.java
ControlFlowAnalysis.matchLabel
private static boolean matchLabel(Node target, String label) { if (label == null) { return true; } while (target.isLabel()) { if (target.getFirstChild().getString().equals(label)) { return true; } target = target.getParent(); } return false; }
java
private static boolean matchLabel(Node target, String label) { if (label == null) { return true; } while (target.isLabel()) { if (target.getFirstChild().getString().equals(label)) { return true; } target = target.getParent(); } return false; }
[ "private", "static", "boolean", "matchLabel", "(", "Node", "target", ",", "String", "label", ")", "{", "if", "(", "label", "==", "null", ")", "{", "return", "true", ";", "}", "while", "(", "target", ".", "isLabel", "(", ")", ")", "{", "if", "(", "target", ".", "getFirstChild", "(", ")", ".", "getString", "(", ")", ".", "equals", "(", "label", ")", ")", "{", "return", "true", ";", "}", "target", "=", "target", ".", "getParent", "(", ")", ";", "}", "return", "false", ";", "}" ]
Check if label is actually referencing the target control structure. If label is null, it always returns true.
[ "Check", "if", "label", "is", "actually", "referencing", "the", "target", "control", "structure", ".", "If", "label", "is", "null", "it", "always", "returns", "true", "." ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ControlFlowAnalysis.java#L946-L957
Impetus/Kundera
src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/schemamanager/CassandraSchemaManager.java
CassandraSchemaManager.onSetReplicateOnWrite
private void onSetReplicateOnWrite(CfDef cfDef, Properties cfProperties, StringBuilder builder) { String replicateOnWrite = cfProperties.getProperty(CassandraConstants.REPLICATE_ON_WRITE); if (builder != null) { String replicateOn_Write = CQLTranslator.getKeyword(CassandraConstants.REPLICATE_ON_WRITE); builder.append(replicateOn_Write); builder.append(CQLTranslator.EQ_CLAUSE); builder.append(Boolean.parseBoolean(replicateOnWrite)); builder.append(CQLTranslator.AND_CLAUSE); } else if (cfDef != null) { cfDef.setReplicate_on_write(false); } }
java
private void onSetReplicateOnWrite(CfDef cfDef, Properties cfProperties, StringBuilder builder) { String replicateOnWrite = cfProperties.getProperty(CassandraConstants.REPLICATE_ON_WRITE); if (builder != null) { String replicateOn_Write = CQLTranslator.getKeyword(CassandraConstants.REPLICATE_ON_WRITE); builder.append(replicateOn_Write); builder.append(CQLTranslator.EQ_CLAUSE); builder.append(Boolean.parseBoolean(replicateOnWrite)); builder.append(CQLTranslator.AND_CLAUSE); } else if (cfDef != null) { cfDef.setReplicate_on_write(false); } }
[ "private", "void", "onSetReplicateOnWrite", "(", "CfDef", "cfDef", ",", "Properties", "cfProperties", ",", "StringBuilder", "builder", ")", "{", "String", "replicateOnWrite", "=", "cfProperties", ".", "getProperty", "(", "CassandraConstants", ".", "REPLICATE_ON_WRITE", ")", ";", "if", "(", "builder", "!=", "null", ")", "{", "String", "replicateOn_Write", "=", "CQLTranslator", ".", "getKeyword", "(", "CassandraConstants", ".", "REPLICATE_ON_WRITE", ")", ";", "builder", ".", "append", "(", "replicateOn_Write", ")", ";", "builder", ".", "append", "(", "CQLTranslator", ".", "EQ_CLAUSE", ")", ";", "builder", ".", "append", "(", "Boolean", ".", "parseBoolean", "(", "replicateOnWrite", ")", ")", ";", "builder", ".", "append", "(", "CQLTranslator", ".", "AND_CLAUSE", ")", ";", "}", "else", "if", "(", "cfDef", "!=", "null", ")", "{", "cfDef", ".", "setReplicate_on_write", "(", "false", ")", ";", "}", "}" ]
On set replicate on write. @param cfDef the cf def @param cfProperties the cf properties @param builder the builder
[ "On", "set", "replicate", "on", "write", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/schemamanager/CassandraSchemaManager.java#L2597-L2612
DataSketches/sketches-core
src/main/java/com/yahoo/sketches/ByteArrayUtil.java
ByteArrayUtil.putLongLE
public static void putLongLE(final byte[] array, final int offset, final long value) { array[offset ] = (byte) (value ); array[offset + 1] = (byte) (value >>> 8); array[offset + 2] = (byte) (value >>> 16); array[offset + 3] = (byte) (value >>> 24); array[offset + 4] = (byte) (value >>> 32); array[offset + 5] = (byte) (value >>> 40); array[offset + 6] = (byte) (value >>> 48); array[offset + 7] = (byte) (value >>> 56); }
java
public static void putLongLE(final byte[] array, final int offset, final long value) { array[offset ] = (byte) (value ); array[offset + 1] = (byte) (value >>> 8); array[offset + 2] = (byte) (value >>> 16); array[offset + 3] = (byte) (value >>> 24); array[offset + 4] = (byte) (value >>> 32); array[offset + 5] = (byte) (value >>> 40); array[offset + 6] = (byte) (value >>> 48); array[offset + 7] = (byte) (value >>> 56); }
[ "public", "static", "void", "putLongLE", "(", "final", "byte", "[", "]", "array", ",", "final", "int", "offset", ",", "final", "long", "value", ")", "{", "array", "[", "offset", "]", "=", "(", "byte", ")", "(", "value", ")", ";", "array", "[", "offset", "+", "1", "]", "=", "(", "byte", ")", "(", "value", ">>>", "8", ")", ";", "array", "[", "offset", "+", "2", "]", "=", "(", "byte", ")", "(", "value", ">>>", "16", ")", ";", "array", "[", "offset", "+", "3", "]", "=", "(", "byte", ")", "(", "value", ">>>", "24", ")", ";", "array", "[", "offset", "+", "4", "]", "=", "(", "byte", ")", "(", "value", ">>>", "32", ")", ";", "array", "[", "offset", "+", "5", "]", "=", "(", "byte", ")", "(", "value", ">>>", "40", ")", ";", "array", "[", "offset", "+", "6", "]", "=", "(", "byte", ")", "(", "value", ">>>", "48", ")", ";", "array", "[", "offset", "+", "7", "]", "=", "(", "byte", ")", "(", "value", ">>>", "56", ")", ";", "}" ]
Put the source <i>long</i> into the destination byte array starting at the given offset in little endian order. There is no bounds checking. @param array destination byte array @param offset destination offset @param value source <i>long</i>
[ "Put", "the", "source", "<i", ">", "long<", "/", "i", ">", "into", "the", "destination", "byte", "array", "starting", "at", "the", "given", "offset", "in", "little", "endian", "order", ".", "There", "is", "no", "bounds", "checking", "." ]
train
https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/ByteArrayUtil.java#L144-L153
Azure/azure-sdk-for-java
eventgrid/resource-manager/v2019_01_01/src/main/java/com/microsoft/azure/management/eventgrid/v2019_01_01/implementation/TopicsInner.java
TopicsInner.beginUpdate
public TopicInner beginUpdate(String resourceGroupName, String topicName, Map<String, String> tags) { return beginUpdateWithServiceResponseAsync(resourceGroupName, topicName, tags).toBlocking().single().body(); }
java
public TopicInner beginUpdate(String resourceGroupName, String topicName, Map<String, String> tags) { return beginUpdateWithServiceResponseAsync(resourceGroupName, topicName, tags).toBlocking().single().body(); }
[ "public", "TopicInner", "beginUpdate", "(", "String", "resourceGroupName", ",", "String", "topicName", ",", "Map", "<", "String", ",", "String", ">", "tags", ")", "{", "return", "beginUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "topicName", ",", "tags", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Update a topic. Asynchronously updates a topic with the specified parameters. @param resourceGroupName The name of the resource group within the user's subscription. @param topicName Name of the topic @param tags Tags of the resource @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 TopicInner object if successful.
[ "Update", "a", "topic", ".", "Asynchronously", "updates", "a", "topic", "with", "the", "specified", "parameters", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/eventgrid/resource-manager/v2019_01_01/src/main/java/com/microsoft/azure/management/eventgrid/v2019_01_01/implementation/TopicsInner.java#L803-L805
comapi/comapi-sdk-android
COMAPI/foundation/src/main/java/com/comapi/internal/network/ServiceApiWrapper.java
ServiceApiWrapper.doQueryEvents
Observable<ComapiResult<EventsQueryResponse>> doQueryEvents(@NonNull final String token, @NonNull final String conversationId, @NonNull final Long from, @NonNull final Integer limit) { return addLogging(service.queryEvents(AuthManager.addAuthPrefix(token), apiSpaceId, conversationId, from, limit).map(mapToComapiResult()), log, "Querying events in " + conversationId) .flatMap(result -> { EventsQueryResponse newResult = new EventsQueryResponse(result.getResult(), new Parser()); return wrapObservable(Observable.just(new ComapiResult<>(result, newResult))); }); }
java
Observable<ComapiResult<EventsQueryResponse>> doQueryEvents(@NonNull final String token, @NonNull final String conversationId, @NonNull final Long from, @NonNull final Integer limit) { return addLogging(service.queryEvents(AuthManager.addAuthPrefix(token), apiSpaceId, conversationId, from, limit).map(mapToComapiResult()), log, "Querying events in " + conversationId) .flatMap(result -> { EventsQueryResponse newResult = new EventsQueryResponse(result.getResult(), new Parser()); return wrapObservable(Observable.just(new ComapiResult<>(result, newResult))); }); }
[ "Observable", "<", "ComapiResult", "<", "EventsQueryResponse", ">", ">", "doQueryEvents", "(", "@", "NonNull", "final", "String", "token", ",", "@", "NonNull", "final", "String", "conversationId", ",", "@", "NonNull", "final", "Long", "from", ",", "@", "NonNull", "final", "Integer", "limit", ")", "{", "return", "addLogging", "(", "service", ".", "queryEvents", "(", "AuthManager", ".", "addAuthPrefix", "(", "token", ")", ",", "apiSpaceId", ",", "conversationId", ",", "from", ",", "limit", ")", ".", "map", "(", "mapToComapiResult", "(", ")", ")", ",", "log", ",", "\"Querying events in \"", "+", "conversationId", ")", ".", "flatMap", "(", "result", "->", "{", "EventsQueryResponse", "newResult", "=", "new", "EventsQueryResponse", "(", "result", ".", "getResult", "(", ")", ",", "new", "Parser", "(", ")", ")", ";", "return", "wrapObservable", "(", "Observable", ".", "just", "(", "new", "ComapiResult", "<>", "(", "result", ",", "newResult", ")", ")", ")", ";", "}", ")", ";", "}" ]
Query events. Use {@link #doQueryConversationEvents(String, String, Long, Integer)} for better visibility of possible events. @param token Comapi access token. @param conversationId ID of a conversation to query events in it. @param from ID of the event to start from. @param limit Limit of events to obtain in this call. @return Observable to get events in a conversation.
[ "Query", "events", ".", "Use", "{", "@link", "#doQueryConversationEvents", "(", "String", "String", "Long", "Integer", ")", "}", "for", "better", "visibility", "of", "possible", "events", "." ]
train
https://github.com/comapi/comapi-sdk-android/blob/53140a58d5a62afe196047ccc5120bfe090ef211/COMAPI/foundation/src/main/java/com/comapi/internal/network/ServiceApiWrapper.java#L273-L279
Azure/azure-sdk-for-java
streamanalytics/resource-manager/v2016_03_01/src/main/java/com/microsoft/azure/management/streamanalytics/v2016_03_01/implementation/InputsInner.java
InputsInner.createOrReplaceAsync
public Observable<InputInner> createOrReplaceAsync(String resourceGroupName, String jobName, String inputName, InputInner input, String ifMatch, String ifNoneMatch) { return createOrReplaceWithServiceResponseAsync(resourceGroupName, jobName, inputName, input, ifMatch, ifNoneMatch).map(new Func1<ServiceResponseWithHeaders<InputInner, InputsCreateOrReplaceHeaders>, InputInner>() { @Override public InputInner call(ServiceResponseWithHeaders<InputInner, InputsCreateOrReplaceHeaders> response) { return response.body(); } }); }
java
public Observable<InputInner> createOrReplaceAsync(String resourceGroupName, String jobName, String inputName, InputInner input, String ifMatch, String ifNoneMatch) { return createOrReplaceWithServiceResponseAsync(resourceGroupName, jobName, inputName, input, ifMatch, ifNoneMatch).map(new Func1<ServiceResponseWithHeaders<InputInner, InputsCreateOrReplaceHeaders>, InputInner>() { @Override public InputInner call(ServiceResponseWithHeaders<InputInner, InputsCreateOrReplaceHeaders> response) { return response.body(); } }); }
[ "public", "Observable", "<", "InputInner", ">", "createOrReplaceAsync", "(", "String", "resourceGroupName", ",", "String", "jobName", ",", "String", "inputName", ",", "InputInner", "input", ",", "String", "ifMatch", ",", "String", "ifNoneMatch", ")", "{", "return", "createOrReplaceWithServiceResponseAsync", "(", "resourceGroupName", ",", "jobName", ",", "inputName", ",", "input", ",", "ifMatch", ",", "ifNoneMatch", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponseWithHeaders", "<", "InputInner", ",", "InputsCreateOrReplaceHeaders", ">", ",", "InputInner", ">", "(", ")", "{", "@", "Override", "public", "InputInner", "call", "(", "ServiceResponseWithHeaders", "<", "InputInner", ",", "InputsCreateOrReplaceHeaders", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Creates an input or replaces an already existing input under an existing streaming job. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param jobName The name of the streaming job. @param inputName The name of the input. @param input The definition of the input that will be used to create a new input or replace the existing one under the streaming job. @param ifMatch The ETag of the input. Omit this value to always overwrite the current input. Specify the last-seen ETag value to prevent accidentally overwritting concurrent changes. @param ifNoneMatch Set to '*' to allow a new input to be created, but to prevent updating an existing input. Other values will result in a 412 Pre-condition Failed response. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the InputInner object
[ "Creates", "an", "input", "or", "replaces", "an", "already", "existing", "input", "under", "an", "existing", "streaming", "job", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/streamanalytics/resource-manager/v2016_03_01/src/main/java/com/microsoft/azure/management/streamanalytics/v2016_03_01/implementation/InputsInner.java#L247-L254
Alluxio/alluxio
core/common/src/main/java/alluxio/util/CommonUtils.java
CommonUtils.stripSuffixIfPresent
public static String stripSuffixIfPresent(final String key, final String suffix) { if (key.endsWith(suffix)) { return key.substring(0, key.length() - suffix.length()); } return key; }
java
public static String stripSuffixIfPresent(final String key, final String suffix) { if (key.endsWith(suffix)) { return key.substring(0, key.length() - suffix.length()); } return key; }
[ "public", "static", "String", "stripSuffixIfPresent", "(", "final", "String", "key", ",", "final", "String", "suffix", ")", "{", "if", "(", "key", ".", "endsWith", "(", "suffix", ")", ")", "{", "return", "key", ".", "substring", "(", "0", ",", "key", ".", "length", "(", ")", "-", "suffix", ".", "length", "(", ")", ")", ";", "}", "return", "key", ";", "}" ]
Strips the suffix if it exists. This method will leave keys without a suffix unaltered. @param key the key to strip the suffix from @param suffix suffix to remove @return the key with the suffix removed, or the key unaltered if the suffix is not present
[ "Strips", "the", "suffix", "if", "it", "exists", ".", "This", "method", "will", "leave", "keys", "without", "a", "suffix", "unaltered", "." ]
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/util/CommonUtils.java#L347-L352
apache/incubator-druid
server/src/main/java/org/apache/druid/server/coordinator/helper/NewestSegmentFirstIterator.java
NewestSegmentFirstIterator.updateQueue
private void updateQueue(String dataSourceName, DataSourceCompactionConfig config) { final CompactibleTimelineObjectHolderCursor compactibleTimelineObjectHolderCursor = timelineIterators.get( dataSourceName ); if (compactibleTimelineObjectHolderCursor == null) { log.warn("Cannot find timeline for dataSource[%s]. Skip this dataSource", dataSourceName); return; } final SegmentsToCompact segmentsToCompact = findSegmentsToCompact( compactibleTimelineObjectHolderCursor, config ); if (segmentsToCompact.getNumSegments() > 1) { queue.add(new QueueEntry(segmentsToCompact.segments)); } }
java
private void updateQueue(String dataSourceName, DataSourceCompactionConfig config) { final CompactibleTimelineObjectHolderCursor compactibleTimelineObjectHolderCursor = timelineIterators.get( dataSourceName ); if (compactibleTimelineObjectHolderCursor == null) { log.warn("Cannot find timeline for dataSource[%s]. Skip this dataSource", dataSourceName); return; } final SegmentsToCompact segmentsToCompact = findSegmentsToCompact( compactibleTimelineObjectHolderCursor, config ); if (segmentsToCompact.getNumSegments() > 1) { queue.add(new QueueEntry(segmentsToCompact.segments)); } }
[ "private", "void", "updateQueue", "(", "String", "dataSourceName", ",", "DataSourceCompactionConfig", "config", ")", "{", "final", "CompactibleTimelineObjectHolderCursor", "compactibleTimelineObjectHolderCursor", "=", "timelineIterators", ".", "get", "(", "dataSourceName", ")", ";", "if", "(", "compactibleTimelineObjectHolderCursor", "==", "null", ")", "{", "log", ".", "warn", "(", "\"Cannot find timeline for dataSource[%s]. Skip this dataSource\"", ",", "dataSourceName", ")", ";", "return", ";", "}", "final", "SegmentsToCompact", "segmentsToCompact", "=", "findSegmentsToCompact", "(", "compactibleTimelineObjectHolderCursor", ",", "config", ")", ";", "if", "(", "segmentsToCompact", ".", "getNumSegments", "(", ")", ">", "1", ")", "{", "queue", ".", "add", "(", "new", "QueueEntry", "(", "segmentsToCompact", ".", "segments", ")", ")", ";", "}", "}" ]
Find the next segments to compact for the given dataSource and add them to the queue. {@link #timelineIterators} is updated according to the found segments. That is, the found segments are removed from the timeline of the given dataSource.
[ "Find", "the", "next", "segments", "to", "compact", "for", "the", "given", "dataSource", "and", "add", "them", "to", "the", "queue", ".", "{" ]
train
https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/server/src/main/java/org/apache/druid/server/coordinator/helper/NewestSegmentFirstIterator.java#L161-L180
sarl/sarl
main/coreplugins/io.sarl.lang.ui/src/io/sarl/lang/ui/labeling/SARLLabelProvider.java
SARLLabelProvider.signatureWithoutReturnType
protected StyledString signatureWithoutReturnType(StyledString simpleName, JvmExecutable element) { return simpleName.append(this.uiStrings.styledParameters(element)); }
java
protected StyledString signatureWithoutReturnType(StyledString simpleName, JvmExecutable element) { return simpleName.append(this.uiStrings.styledParameters(element)); }
[ "protected", "StyledString", "signatureWithoutReturnType", "(", "StyledString", "simpleName", ",", "JvmExecutable", "element", ")", "{", "return", "simpleName", ".", "append", "(", "this", ".", "uiStrings", ".", "styledParameters", "(", "element", ")", ")", ";", "}" ]
Create a string representation of a signature without the return type. @param simpleName the action name. @param element the executable element. @return the signature.
[ "Create", "a", "string", "representation", "of", "a", "signature", "without", "the", "return", "type", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.lang.ui/src/io/sarl/lang/ui/labeling/SARLLabelProvider.java#L182-L184
apache/flink
flink-core/src/main/java/org/apache/flink/api/common/operators/base/CoGroupRawOperatorBase.java
CoGroupRawOperatorBase.setGroupOrder
public void setGroupOrder(int inputNum, Ordering order) { if (inputNum == 0) { this.groupOrder1 = order; } else if (inputNum == 1) { this.groupOrder2 = order; } else { throw new IndexOutOfBoundsException(); } }
java
public void setGroupOrder(int inputNum, Ordering order) { if (inputNum == 0) { this.groupOrder1 = order; } else if (inputNum == 1) { this.groupOrder2 = order; } else { throw new IndexOutOfBoundsException(); } }
[ "public", "void", "setGroupOrder", "(", "int", "inputNum", ",", "Ordering", "order", ")", "{", "if", "(", "inputNum", "==", "0", ")", "{", "this", ".", "groupOrder1", "=", "order", ";", "}", "else", "if", "(", "inputNum", "==", "1", ")", "{", "this", ".", "groupOrder2", "=", "order", ";", "}", "else", "{", "throw", "new", "IndexOutOfBoundsException", "(", ")", ";", "}", "}" ]
Sets the order of the elements within a group for the given input. @param inputNum The number of the input (here either <i>0</i> or <i>1</i>). @param order The order for the elements in a group.
[ "Sets", "the", "order", "of", "the", "elements", "within", "a", "group", "for", "the", "given", "input", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/api/common/operators/base/CoGroupRawOperatorBase.java#L89-L97
google/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/patterns/StepPattern.java
StepPattern.getMatchScore
public double getMatchScore(XPathContext xctxt, int context) throws javax.xml.transform.TransformerException { xctxt.pushCurrentNode(context); xctxt.pushCurrentExpressionNode(context); try { XObject score = execute(xctxt); return score.num(); } finally { xctxt.popCurrentNode(); xctxt.popCurrentExpressionNode(); } // return XPath.MATCH_SCORE_NONE; }
java
public double getMatchScore(XPathContext xctxt, int context) throws javax.xml.transform.TransformerException { xctxt.pushCurrentNode(context); xctxt.pushCurrentExpressionNode(context); try { XObject score = execute(xctxt); return score.num(); } finally { xctxt.popCurrentNode(); xctxt.popCurrentExpressionNode(); } // return XPath.MATCH_SCORE_NONE; }
[ "public", "double", "getMatchScore", "(", "XPathContext", "xctxt", ",", "int", "context", ")", "throws", "javax", ".", "xml", ".", "transform", ".", "TransformerException", "{", "xctxt", ".", "pushCurrentNode", "(", "context", ")", ";", "xctxt", ".", "pushCurrentExpressionNode", "(", "context", ")", ";", "try", "{", "XObject", "score", "=", "execute", "(", "xctxt", ")", ";", "return", "score", ".", "num", "(", ")", ";", "}", "finally", "{", "xctxt", ".", "popCurrentNode", "(", ")", ";", "xctxt", ".", "popCurrentExpressionNode", "(", ")", ";", "}", "// return XPath.MATCH_SCORE_NONE;", "}" ]
Get the match score of the given node. @param xctxt The XPath runtime context. @param context The node to be tested. @return {@link org.apache.xpath.patterns.NodeTest#SCORE_NODETEST}, {@link org.apache.xpath.patterns.NodeTest#SCORE_NONE}, {@link org.apache.xpath.patterns.NodeTest#SCORE_NSWILD}, {@link org.apache.xpath.patterns.NodeTest#SCORE_QNAME}, or {@link org.apache.xpath.patterns.NodeTest#SCORE_OTHER}. @throws javax.xml.transform.TransformerException
[ "Get", "the", "match", "score", "of", "the", "given", "node", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/patterns/StepPattern.java#L892-L912
joniles/mpxj
src/main/java/net/sf/mpxj/reader/UniversalProjectReader.java
UniversalProjectReader.handleByteOrderMark
private ProjectFile handleByteOrderMark(InputStream stream, int length, Charset charset) throws Exception { UniversalProjectReader reader = new UniversalProjectReader(); reader.setSkipBytes(length); reader.setCharset(charset); return reader.read(stream); }
java
private ProjectFile handleByteOrderMark(InputStream stream, int length, Charset charset) throws Exception { UniversalProjectReader reader = new UniversalProjectReader(); reader.setSkipBytes(length); reader.setCharset(charset); return reader.read(stream); }
[ "private", "ProjectFile", "handleByteOrderMark", "(", "InputStream", "stream", ",", "int", "length", ",", "Charset", "charset", ")", "throws", "Exception", "{", "UniversalProjectReader", "reader", "=", "new", "UniversalProjectReader", "(", ")", ";", "reader", ".", "setSkipBytes", "(", "length", ")", ";", "reader", ".", "setCharset", "(", "charset", ")", ";", "return", "reader", ".", "read", "(", "stream", ")", ";", "}" ]
The file we are working with has a byte order mark. Skip this and try again to read the file. @param stream schedule data @param length length of the byte order mark @param charset charset indicated by byte order mark @return ProjectFile instance
[ "The", "file", "we", "are", "working", "with", "has", "a", "byte", "order", "mark", ".", "Skip", "this", "and", "try", "again", "to", "read", "the", "file", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/reader/UniversalProjectReader.java#L674-L680
DV8FromTheWorld/JDA
src/main/java/net/dv8tion/jda/core/requests/RestAction.java
RestAction.completeAfter
public T completeAfter(long delay, TimeUnit unit) { Checks.notNull(unit, "TimeUnit"); try { unit.sleep(delay); return complete(); } catch (InterruptedException e) { throw new RuntimeException(e); } }
java
public T completeAfter(long delay, TimeUnit unit) { Checks.notNull(unit, "TimeUnit"); try { unit.sleep(delay); return complete(); } catch (InterruptedException e) { throw new RuntimeException(e); } }
[ "public", "T", "completeAfter", "(", "long", "delay", ",", "TimeUnit", "unit", ")", "{", "Checks", ".", "notNull", "(", "unit", ",", "\"TimeUnit\"", ")", ";", "try", "{", "unit", ".", "sleep", "(", "delay", ")", ";", "return", "complete", "(", ")", ";", "}", "catch", "(", "InterruptedException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "}" ]
Blocks the current Thread for the specified delay and calls {@link #complete()} when delay has been reached. <br>If the specified delay is negative this action will execute immediately. (see: {@link TimeUnit#sleep(long)}) @param delay The delay after which to execute a call to {@link #complete()} @param unit The {@link java.util.concurrent.TimeUnit TimeUnit} which should be used (this will use {@link java.util.concurrent.TimeUnit#sleep(long) unit.sleep(delay)}) @throws java.lang.IllegalArgumentException If the specified {@link java.util.concurrent.TimeUnit TimeUnit} is {@code null} @throws java.lang.RuntimeException If the sleep operation is interrupted @return The response value
[ "Blocks", "the", "current", "Thread", "for", "the", "specified", "delay", "and", "calls", "{", "@link", "#complete", "()", "}", "when", "delay", "has", "been", "reached", ".", "<br", ">", "If", "the", "specified", "delay", "is", "negative", "this", "action", "will", "execute", "immediately", ".", "(", "see", ":", "{", "@link", "TimeUnit#sleep", "(", "long", ")", "}", ")" ]
train
https://github.com/DV8FromTheWorld/JDA/blob/8ecbbe354d03f6bf448411bba573d0d4c268b560/src/main/java/net/dv8tion/jda/core/requests/RestAction.java#L528-L540
apache/incubator-gobblin
gobblin-utility/src/main/java/org/apache/gobblin/util/ExponentialBackoff.java
ExponentialBackoff.evaluateConditionUntilTrue
@Builder(builderMethodName = "awaitCondition", buildMethodName = "await") private static boolean evaluateConditionUntilTrue(Callable<Boolean> callable, Double alpha, Integer maxRetries, Long maxWait, Long maxDelay, Long initialDelay) throws ExecutionException, InterruptedException { ExponentialBackoff exponentialBackoff = new ExponentialBackoff(alpha, maxRetries, maxWait, maxDelay, initialDelay); while (true) { try { if (callable.call()) { return true; } } catch (Throwable t) { throw new ExecutionException(t); } if (!exponentialBackoff.awaitNextRetryIfAvailable()) { return false; } } }
java
@Builder(builderMethodName = "awaitCondition", buildMethodName = "await") private static boolean evaluateConditionUntilTrue(Callable<Boolean> callable, Double alpha, Integer maxRetries, Long maxWait, Long maxDelay, Long initialDelay) throws ExecutionException, InterruptedException { ExponentialBackoff exponentialBackoff = new ExponentialBackoff(alpha, maxRetries, maxWait, maxDelay, initialDelay); while (true) { try { if (callable.call()) { return true; } } catch (Throwable t) { throw new ExecutionException(t); } if (!exponentialBackoff.awaitNextRetryIfAvailable()) { return false; } } }
[ "@", "Builder", "(", "builderMethodName", "=", "\"awaitCondition\"", ",", "buildMethodName", "=", "\"await\"", ")", "private", "static", "boolean", "evaluateConditionUntilTrue", "(", "Callable", "<", "Boolean", ">", "callable", ",", "Double", "alpha", ",", "Integer", "maxRetries", ",", "Long", "maxWait", ",", "Long", "maxDelay", ",", "Long", "initialDelay", ")", "throws", "ExecutionException", ",", "InterruptedException", "{", "ExponentialBackoff", "exponentialBackoff", "=", "new", "ExponentialBackoff", "(", "alpha", ",", "maxRetries", ",", "maxWait", ",", "maxDelay", ",", "initialDelay", ")", ";", "while", "(", "true", ")", "{", "try", "{", "if", "(", "callable", ".", "call", "(", ")", ")", "{", "return", "true", ";", "}", "}", "catch", "(", "Throwable", "t", ")", "{", "throw", "new", "ExecutionException", "(", "t", ")", ";", "}", "if", "(", "!", "exponentialBackoff", ".", "awaitNextRetryIfAvailable", "(", ")", ")", "{", "return", "false", ";", "}", "}", "}" ]
Evaluate a condition until true with exponential backoff. @param callable Condition. @return true if the condition returned true. @throws ExecutionException if the condition throws an exception.
[ "Evaluate", "a", "condition", "until", "true", "with", "exponential", "backoff", "." ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/ExponentialBackoff.java#L112-L128
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-backend-impls/nd4j-cuda/src/main/java/org/nd4j/linalg/jcublas/JCublasNDArrayFactory.java
JCublasNDArrayFactory.pullRows
@Override public INDArray pullRows(INDArray source, int sourceDimension, int[] indexes, char order) { if (indexes == null || indexes.length < 1) throw new IllegalStateException("Indexes can't be null or zero-length"); long[] shape; if (source.rank() == 1) { shape = new long[]{indexes.length}; } else if (sourceDimension == 1) shape = new long[] {indexes.length, source.shape()[sourceDimension]}; else if (sourceDimension == 0) shape = new long[] {source.shape()[sourceDimension], indexes.length}; else throw new UnsupportedOperationException("2D input is expected"); return pullRows(source, Nd4j.createUninitialized(source.dataType(), shape, order), sourceDimension, indexes); }
java
@Override public INDArray pullRows(INDArray source, int sourceDimension, int[] indexes, char order) { if (indexes == null || indexes.length < 1) throw new IllegalStateException("Indexes can't be null or zero-length"); long[] shape; if (source.rank() == 1) { shape = new long[]{indexes.length}; } else if (sourceDimension == 1) shape = new long[] {indexes.length, source.shape()[sourceDimension]}; else if (sourceDimension == 0) shape = new long[] {source.shape()[sourceDimension], indexes.length}; else throw new UnsupportedOperationException("2D input is expected"); return pullRows(source, Nd4j.createUninitialized(source.dataType(), shape, order), sourceDimension, indexes); }
[ "@", "Override", "public", "INDArray", "pullRows", "(", "INDArray", "source", ",", "int", "sourceDimension", ",", "int", "[", "]", "indexes", ",", "char", "order", ")", "{", "if", "(", "indexes", "==", "null", "||", "indexes", ".", "length", "<", "1", ")", "throw", "new", "IllegalStateException", "(", "\"Indexes can't be null or zero-length\"", ")", ";", "long", "[", "]", "shape", ";", "if", "(", "source", ".", "rank", "(", ")", "==", "1", ")", "{", "shape", "=", "new", "long", "[", "]", "{", "indexes", ".", "length", "}", ";", "}", "else", "if", "(", "sourceDimension", "==", "1", ")", "shape", "=", "new", "long", "[", "]", "{", "indexes", ".", "length", ",", "source", ".", "shape", "(", ")", "[", "sourceDimension", "]", "}", ";", "else", "if", "(", "sourceDimension", "==", "0", ")", "shape", "=", "new", "long", "[", "]", "{", "source", ".", "shape", "(", ")", "[", "sourceDimension", "]", ",", "indexes", ".", "length", "}", ";", "else", "throw", "new", "UnsupportedOperationException", "(", "\"2D input is expected\"", ")", ";", "return", "pullRows", "(", "source", ",", "Nd4j", ".", "createUninitialized", "(", "source", ".", "dataType", "(", ")", ",", "shape", ",", "order", ")", ",", "sourceDimension", ",", "indexes", ")", ";", "}" ]
This method produces concatenated array, that consist from tensors, fetched from source array, against some dimension and specified indexes @param source source tensor @param sourceDimension dimension of source tensor @param indexes indexes from source array @return
[ "This", "method", "produces", "concatenated", "array", "that", "consist", "from", "tensors", "fetched", "from", "source", "array", "against", "some", "dimension", "and", "specified", "indexes" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-backend-impls/nd4j-cuda/src/main/java/org/nd4j/linalg/jcublas/JCublasNDArrayFactory.java#L635-L652
elki-project/elki
elki/src/main/java/de/lmu/ifi/dbs/elki/algorithm/projection/SNE.java
SNE.optimizeSNE
protected void optimizeSNE(AffinityMatrix pij, double[][] sol) { final int size = pij.size(); if(size * 3L * dim > 0x7FFF_FFFAL) { throw new AbortException("Memory exceeds Java array size limit."); } // Meta information on each point; joined for memory locality. // Gradient, Momentum, and learning rate // For performance, we use a flat memory layout! double[] meta = new double[size * 3 * dim]; final int dim3 = dim * 3; for(int off = 2 * dim; off < meta.length; off += dim3) { Arrays.fill(meta, off, off + dim, 1.); // Initial learning rate } // Affinity matrix in projected space double[][] qij = new double[size][size]; FiniteProgress prog = LOG.isVerbose() ? new FiniteProgress("Iterative Optimization", iterations, LOG) : null; Duration timer = LOG.isStatistics() ? LOG.newDuration(this.getClass().getName() + ".runtime.optimization").begin() : null; // Optimize for(int it = 0; it < iterations; it++) { double qij_sum = computeQij(qij, sol); computeGradient(pij, qij, 1. / qij_sum, sol, meta); updateSolution(sol, meta, it); LOG.incrementProcessed(prog); } LOG.ensureCompleted(prog); if(timer != null) { LOG.statistics(timer.end()); } }
java
protected void optimizeSNE(AffinityMatrix pij, double[][] sol) { final int size = pij.size(); if(size * 3L * dim > 0x7FFF_FFFAL) { throw new AbortException("Memory exceeds Java array size limit."); } // Meta information on each point; joined for memory locality. // Gradient, Momentum, and learning rate // For performance, we use a flat memory layout! double[] meta = new double[size * 3 * dim]; final int dim3 = dim * 3; for(int off = 2 * dim; off < meta.length; off += dim3) { Arrays.fill(meta, off, off + dim, 1.); // Initial learning rate } // Affinity matrix in projected space double[][] qij = new double[size][size]; FiniteProgress prog = LOG.isVerbose() ? new FiniteProgress("Iterative Optimization", iterations, LOG) : null; Duration timer = LOG.isStatistics() ? LOG.newDuration(this.getClass().getName() + ".runtime.optimization").begin() : null; // Optimize for(int it = 0; it < iterations; it++) { double qij_sum = computeQij(qij, sol); computeGradient(pij, qij, 1. / qij_sum, sol, meta); updateSolution(sol, meta, it); LOG.incrementProcessed(prog); } LOG.ensureCompleted(prog); if(timer != null) { LOG.statistics(timer.end()); } }
[ "protected", "void", "optimizeSNE", "(", "AffinityMatrix", "pij", ",", "double", "[", "]", "[", "]", "sol", ")", "{", "final", "int", "size", "=", "pij", ".", "size", "(", ")", ";", "if", "(", "size", "*", "3L", "*", "dim", ">", "0x7FFF_FFFA", "L", ")", "{", "throw", "new", "AbortException", "(", "\"Memory exceeds Java array size limit.\"", ")", ";", "}", "// Meta information on each point; joined for memory locality.", "// Gradient, Momentum, and learning rate", "// For performance, we use a flat memory layout!", "double", "[", "]", "meta", "=", "new", "double", "[", "size", "*", "3", "*", "dim", "]", ";", "final", "int", "dim3", "=", "dim", "*", "3", ";", "for", "(", "int", "off", "=", "2", "*", "dim", ";", "off", "<", "meta", ".", "length", ";", "off", "+=", "dim3", ")", "{", "Arrays", ".", "fill", "(", "meta", ",", "off", ",", "off", "+", "dim", ",", "1.", ")", ";", "// Initial learning rate", "}", "// Affinity matrix in projected space", "double", "[", "]", "[", "]", "qij", "=", "new", "double", "[", "size", "]", "[", "size", "]", ";", "FiniteProgress", "prog", "=", "LOG", ".", "isVerbose", "(", ")", "?", "new", "FiniteProgress", "(", "\"Iterative Optimization\"", ",", "iterations", ",", "LOG", ")", ":", "null", ";", "Duration", "timer", "=", "LOG", ".", "isStatistics", "(", ")", "?", "LOG", ".", "newDuration", "(", "this", ".", "getClass", "(", ")", ".", "getName", "(", ")", "+", "\".runtime.optimization\"", ")", ".", "begin", "(", ")", ":", "null", ";", "// Optimize", "for", "(", "int", "it", "=", "0", ";", "it", "<", "iterations", ";", "it", "++", ")", "{", "double", "qij_sum", "=", "computeQij", "(", "qij", ",", "sol", ")", ";", "computeGradient", "(", "pij", ",", "qij", ",", "1.", "/", "qij_sum", ",", "sol", ",", "meta", ")", ";", "updateSolution", "(", "sol", ",", "meta", ",", "it", ")", ";", "LOG", ".", "incrementProcessed", "(", "prog", ")", ";", "}", "LOG", ".", "ensureCompleted", "(", "prog", ")", ";", "if", "(", "timer", "!=", "null", ")", "{", "LOG", ".", "statistics", "(", "timer", ".", "end", "(", ")", ")", ";", "}", "}" ]
Perform the actual tSNE optimization. @param pij Initial affinity matrix @param sol Solution output array (preinitialized)
[ "Perform", "the", "actual", "tSNE", "optimization", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki/src/main/java/de/lmu/ifi/dbs/elki/algorithm/projection/SNE.java#L219-L248
Omertron/api-thetvdb
src/main/java/com/omertron/thetvdbapi/tools/DOMHelper.java
DOMHelper.appendChild
public static void appendChild(Document doc, Element parentElement, String elementName, String elementValue) { Element child = doc.createElement(elementName); Text text = doc.createTextNode(elementValue); child.appendChild(text); parentElement.appendChild(child); }
java
public static void appendChild(Document doc, Element parentElement, String elementName, String elementValue) { Element child = doc.createElement(elementName); Text text = doc.createTextNode(elementValue); child.appendChild(text); parentElement.appendChild(child); }
[ "public", "static", "void", "appendChild", "(", "Document", "doc", ",", "Element", "parentElement", ",", "String", "elementName", ",", "String", "elementValue", ")", "{", "Element", "child", "=", "doc", ".", "createElement", "(", "elementName", ")", ";", "Text", "text", "=", "doc", ".", "createTextNode", "(", "elementValue", ")", ";", "child", ".", "appendChild", "(", "text", ")", ";", "parentElement", ".", "appendChild", "(", "child", ")", ";", "}" ]
Add a child element to a parent element @param doc @param parentElement @param elementName @param elementValue
[ "Add", "a", "child", "element", "to", "a", "parent", "element" ]
train
https://github.com/Omertron/api-thetvdb/blob/2ff9f9580e76043f19d2fc3234d87e16a95fa485/src/main/java/com/omertron/thetvdbapi/tools/DOMHelper.java#L229-L234
dihedron/dihedron-commons
src/main/java/org/dihedron/patterns/cache/CacheHelper.java
CacheHelper.getIntoByteArray
public static byte[] getIntoByteArray(Cache cache, String resource, CacheMissHandler ... handlers) throws CacheException { if(cache == null) { logger.error("cache reference must not be null"); throw new CacheException("invalid cache"); } InputStream input = null; ByteArrayOutputStream output = null; try { input = cache.get(resource, handlers); if(input != null) { output = new ByteArrayOutputStream(); long copied = Streams.copy(input, output); logger.trace("copied {} bytes from cache", copied); return output.toByteArray(); } } catch (IOException e) { logger.error("error copying data from cache to byte array", e); throw new CacheException("error copying data from cache to byte array", e); } finally { Streams.safelyClose(input); Streams.safelyClose(output); } return null; }
java
public static byte[] getIntoByteArray(Cache cache, String resource, CacheMissHandler ... handlers) throws CacheException { if(cache == null) { logger.error("cache reference must not be null"); throw new CacheException("invalid cache"); } InputStream input = null; ByteArrayOutputStream output = null; try { input = cache.get(resource, handlers); if(input != null) { output = new ByteArrayOutputStream(); long copied = Streams.copy(input, output); logger.trace("copied {} bytes from cache", copied); return output.toByteArray(); } } catch (IOException e) { logger.error("error copying data from cache to byte array", e); throw new CacheException("error copying data from cache to byte array", e); } finally { Streams.safelyClose(input); Streams.safelyClose(output); } return null; }
[ "public", "static", "byte", "[", "]", "getIntoByteArray", "(", "Cache", "cache", ",", "String", "resource", ",", "CacheMissHandler", "...", "handlers", ")", "throws", "CacheException", "{", "if", "(", "cache", "==", "null", ")", "{", "logger", ".", "error", "(", "\"cache reference must not be null\"", ")", ";", "throw", "new", "CacheException", "(", "\"invalid cache\"", ")", ";", "}", "InputStream", "input", "=", "null", ";", "ByteArrayOutputStream", "output", "=", "null", ";", "try", "{", "input", "=", "cache", ".", "get", "(", "resource", ",", "handlers", ")", ";", "if", "(", "input", "!=", "null", ")", "{", "output", "=", "new", "ByteArrayOutputStream", "(", ")", ";", "long", "copied", "=", "Streams", ".", "copy", "(", "input", ",", "output", ")", ";", "logger", ".", "trace", "(", "\"copied {} bytes from cache\"", ",", "copied", ")", ";", "return", "output", ".", "toByteArray", "(", ")", ";", "}", "}", "catch", "(", "IOException", "e", ")", "{", "logger", ".", "error", "(", "\"error copying data from cache to byte array\"", ",", "e", ")", ";", "throw", "new", "CacheException", "(", "\"error copying data from cache to byte array\"", ",", "e", ")", ";", "}", "finally", "{", "Streams", ".", "safelyClose", "(", "input", ")", ";", "Streams", ".", "safelyClose", "(", "output", ")", ";", "}", "return", "null", ";", "}" ]
Retrieves the given resource from the cache and translate it to a byte array; if missing tries to retrieve it using the (optional) provided set of handlers. @param cache the cache that stores the resource. @param resource the name of the resource to be retrieved. @param handlers the (optional) set of handlers that will attempt to retrieve the resource if missing from the cache. @return the resource as an array of bytes, or {@code null} if it cannot be retrieved. @throws CacheException
[ "Retrieves", "the", "given", "resource", "from", "the", "cache", "and", "translate", "it", "to", "a", "byte", "array", ";", "if", "missing", "tries", "to", "retrieve", "it", "using", "the", "(", "optional", ")", "provided", "set", "of", "handlers", "." ]
train
https://github.com/dihedron/dihedron-commons/blob/a5194cdaa0d6417ef4aade6ea407a1cad6e8458e/src/main/java/org/dihedron/patterns/cache/CacheHelper.java#L45-L68
wcm-io/wcm-io-handler
richtext/src/main/java/io/wcm/handler/richtext/util/RichTextUtil.java
RichTextUtil.parseText
public static @NotNull Element parseText(@NotNull String text, boolean xhtmlEntities) throws JDOMException { // add root element String xhtmlString = (xhtmlEntities ? "<!DOCTYPE root [" + XHTML_ENTITY_DEF + "]>" : "") + "<root>" + text + "</root>"; try { SAXBuilder saxBuilder = new SAXBuilder(); if (xhtmlEntities) { saxBuilder.setEntityResolver(XHtmlEntityResolver.getInstance()); } Document doc = saxBuilder.build(new StringReader(xhtmlString)); return doc.getRootElement(); } catch (IOException ex) { throw new RuntimeException("Error parsing XHTML fragment.", ex); } }
java
public static @NotNull Element parseText(@NotNull String text, boolean xhtmlEntities) throws JDOMException { // add root element String xhtmlString = (xhtmlEntities ? "<!DOCTYPE root [" + XHTML_ENTITY_DEF + "]>" : "") + "<root>" + text + "</root>"; try { SAXBuilder saxBuilder = new SAXBuilder(); if (xhtmlEntities) { saxBuilder.setEntityResolver(XHtmlEntityResolver.getInstance()); } Document doc = saxBuilder.build(new StringReader(xhtmlString)); return doc.getRootElement(); } catch (IOException ex) { throw new RuntimeException("Error parsing XHTML fragment.", ex); } }
[ "public", "static", "@", "NotNull", "Element", "parseText", "(", "@", "NotNull", "String", "text", ",", "boolean", "xhtmlEntities", ")", "throws", "JDOMException", "{", "// add root element", "String", "xhtmlString", "=", "(", "xhtmlEntities", "?", "\"<!DOCTYPE root [\"", "+", "XHTML_ENTITY_DEF", "+", "\"]>\"", ":", "\"\"", ")", "+", "\"<root>\"", "+", "text", "+", "\"</root>\"", ";", "try", "{", "SAXBuilder", "saxBuilder", "=", "new", "SAXBuilder", "(", ")", ";", "if", "(", "xhtmlEntities", ")", "{", "saxBuilder", ".", "setEntityResolver", "(", "XHtmlEntityResolver", ".", "getInstance", "(", ")", ")", ";", "}", "Document", "doc", "=", "saxBuilder", ".", "build", "(", "new", "StringReader", "(", "xhtmlString", ")", ")", ";", "return", "doc", ".", "getRootElement", "(", ")", ";", "}", "catch", "(", "IOException", "ex", ")", "{", "throw", "new", "RuntimeException", "(", "\"Error parsing XHTML fragment.\"", ",", "ex", ")", ";", "}", "}" ]
Parses XHTML text string. Adds a wrapping "root" element before parsing and returns this root element. @param text XHTML text string (root element not needed) @param xhtmlEntities If set to true, Resolving of XHtml entities in XHtml fragment is supported. @return Root element with parsed xhtml content @throws JDOMException Is thrown if the text could not be parsed as XHTML
[ "Parses", "XHTML", "text", "string", ".", "Adds", "a", "wrapping", "root", "element", "before", "parsing", "and", "returns", "this", "root", "element", "." ]
train
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/richtext/src/main/java/io/wcm/handler/richtext/util/RichTextUtil.java#L141-L162
googleapis/google-cloud-java
google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/deprecated/DiskTypeId.java
DiskTypeId.of
public static DiskTypeId of(String project, String zone, String type) { return of(ZoneId.of(project, zone), type); }
java
public static DiskTypeId of(String project, String zone, String type) { return of(ZoneId.of(project, zone), type); }
[ "public", "static", "DiskTypeId", "of", "(", "String", "project", ",", "String", "zone", ",", "String", "type", ")", "{", "return", "of", "(", "ZoneId", ".", "of", "(", "project", ",", "zone", ")", ",", "type", ")", ";", "}" ]
Returns a disk type identity given project disk, zone and disk type names.
[ "Returns", "a", "disk", "type", "identity", "given", "project", "disk", "zone", "and", "disk", "type", "names", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/deprecated/DiskTypeId.java#L121-L123
apache/flink
flink-libraries/flink-gelly/src/main/java/org/apache/flink/graph/library/metric/undirected/EdgeMetrics.java
EdgeMetrics.run
@Override public EdgeMetrics<K, VV, EV> run(Graph<K, VV, EV> input) throws Exception { super.run(input); // s, t, (d(s), d(t)) DataSet<Edge<K, Tuple3<EV, LongValue, LongValue>>> edgeDegreePair = input .run(new EdgeDegreePair<K, VV, EV>() .setReduceOnTargetId(reduceOnTargetId) .setParallelism(parallelism)); // s, d(s), count of (u, v) where deg(u) < deg(v) or (deg(u) == deg(v) and u < v) DataSet<Tuple3<K, LongValue, LongValue>> edgeStats = edgeDegreePair .map(new EdgeStats<>()) .setParallelism(parallelism) .name("Edge stats") .groupBy(0) .reduce(new SumEdgeStats<>()) .setCombineHint(CombineHint.HASH) .setParallelism(parallelism) .name("Sum edge stats"); edgeMetricsHelper = new EdgeMetricsHelper<>(); edgeStats .output(edgeMetricsHelper) .setParallelism(parallelism) .name("Edge metrics"); return this; }
java
@Override public EdgeMetrics<K, VV, EV> run(Graph<K, VV, EV> input) throws Exception { super.run(input); // s, t, (d(s), d(t)) DataSet<Edge<K, Tuple3<EV, LongValue, LongValue>>> edgeDegreePair = input .run(new EdgeDegreePair<K, VV, EV>() .setReduceOnTargetId(reduceOnTargetId) .setParallelism(parallelism)); // s, d(s), count of (u, v) where deg(u) < deg(v) or (deg(u) == deg(v) and u < v) DataSet<Tuple3<K, LongValue, LongValue>> edgeStats = edgeDegreePair .map(new EdgeStats<>()) .setParallelism(parallelism) .name("Edge stats") .groupBy(0) .reduce(new SumEdgeStats<>()) .setCombineHint(CombineHint.HASH) .setParallelism(parallelism) .name("Sum edge stats"); edgeMetricsHelper = new EdgeMetricsHelper<>(); edgeStats .output(edgeMetricsHelper) .setParallelism(parallelism) .name("Edge metrics"); return this; }
[ "@", "Override", "public", "EdgeMetrics", "<", "K", ",", "VV", ",", "EV", ">", "run", "(", "Graph", "<", "K", ",", "VV", ",", "EV", ">", "input", ")", "throws", "Exception", "{", "super", ".", "run", "(", "input", ")", ";", "// s, t, (d(s), d(t))", "DataSet", "<", "Edge", "<", "K", ",", "Tuple3", "<", "EV", ",", "LongValue", ",", "LongValue", ">", ">", ">", "edgeDegreePair", "=", "input", ".", "run", "(", "new", "EdgeDegreePair", "<", "K", ",", "VV", ",", "EV", ">", "(", ")", ".", "setReduceOnTargetId", "(", "reduceOnTargetId", ")", ".", "setParallelism", "(", "parallelism", ")", ")", ";", "// s, d(s), count of (u, v) where deg(u) < deg(v) or (deg(u) == deg(v) and u < v)", "DataSet", "<", "Tuple3", "<", "K", ",", "LongValue", ",", "LongValue", ">", ">", "edgeStats", "=", "edgeDegreePair", ".", "map", "(", "new", "EdgeStats", "<>", "(", ")", ")", ".", "setParallelism", "(", "parallelism", ")", ".", "name", "(", "\"Edge stats\"", ")", ".", "groupBy", "(", "0", ")", ".", "reduce", "(", "new", "SumEdgeStats", "<>", "(", ")", ")", ".", "setCombineHint", "(", "CombineHint", ".", "HASH", ")", ".", "setParallelism", "(", "parallelism", ")", ".", "name", "(", "\"Sum edge stats\"", ")", ";", "edgeMetricsHelper", "=", "new", "EdgeMetricsHelper", "<>", "(", ")", ";", "edgeStats", ".", "output", "(", "edgeMetricsHelper", ")", ".", "setParallelism", "(", "parallelism", ")", ".", "name", "(", "\"Edge metrics\"", ")", ";", "return", "this", ";", "}" ]
/* Implementation notes: <p>Use aggregator to replace SumEdgeStats when aggregators are rewritten to use a hash-combineable hashed-reduce.
[ "/", "*", "Implementation", "notes", ":" ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-libraries/flink-gelly/src/main/java/org/apache/flink/graph/library/metric/undirected/EdgeMetrics.java#L93-L123
looly/hutool
hutool-core/src/main/java/cn/hutool/core/bean/BeanUtil.java
BeanUtil.fillBeanWithMapIgnoreCase
public static <T> T fillBeanWithMapIgnoreCase(Map<?, ?> map, T bean, boolean isIgnoreError) { return fillBeanWithMap(map, bean, CopyOptions.create().setIgnoreCase(true).setIgnoreError(isIgnoreError)); }
java
public static <T> T fillBeanWithMapIgnoreCase(Map<?, ?> map, T bean, boolean isIgnoreError) { return fillBeanWithMap(map, bean, CopyOptions.create().setIgnoreCase(true).setIgnoreError(isIgnoreError)); }
[ "public", "static", "<", "T", ">", "T", "fillBeanWithMapIgnoreCase", "(", "Map", "<", "?", ",", "?", ">", "map", ",", "T", "bean", ",", "boolean", "isIgnoreError", ")", "{", "return", "fillBeanWithMap", "(", "map", ",", "bean", ",", "CopyOptions", ".", "create", "(", ")", ".", "setIgnoreCase", "(", "true", ")", ".", "setIgnoreError", "(", "isIgnoreError", ")", ")", ";", "}" ]
使用Map填充Bean对象,忽略大小写 @param <T> Bean类型 @param map Map @param bean Bean @param isIgnoreError 是否忽略注入错误 @return Bean
[ "使用Map填充Bean对象,忽略大小写" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/bean/BeanUtil.java#L395-L397
mygreen/xlsmapper
src/main/java/com/gh/mygreen/xlsmapper/validation/SheetBindingErrors.java
SheetBindingErrors.createFieldError
public InternalFieldErrorBuilder createFieldError(final String field, final String[] errorCodes) { final String fieldPath = buildFieldPath(field); final Class<?> fieldType = getFieldType(field); final Object fieldValue = getFieldValue(field); String[] codes = new String[0]; for(String errorCode : errorCodes) { codes = Utils.concat(codes, generateMessageCodes(errorCode, fieldPath, fieldType)); } return new InternalFieldErrorBuilder(this, getObjectName(), fieldPath, codes) .sheetName(getSheetName()) .rejectedValue(fieldValue); }
java
public InternalFieldErrorBuilder createFieldError(final String field, final String[] errorCodes) { final String fieldPath = buildFieldPath(field); final Class<?> fieldType = getFieldType(field); final Object fieldValue = getFieldValue(field); String[] codes = new String[0]; for(String errorCode : errorCodes) { codes = Utils.concat(codes, generateMessageCodes(errorCode, fieldPath, fieldType)); } return new InternalFieldErrorBuilder(this, getObjectName(), fieldPath, codes) .sheetName(getSheetName()) .rejectedValue(fieldValue); }
[ "public", "InternalFieldErrorBuilder", "createFieldError", "(", "final", "String", "field", ",", "final", "String", "[", "]", "errorCodes", ")", "{", "final", "String", "fieldPath", "=", "buildFieldPath", "(", "field", ")", ";", "final", "Class", "<", "?", ">", "fieldType", "=", "getFieldType", "(", "field", ")", ";", "final", "Object", "fieldValue", "=", "getFieldValue", "(", "field", ")", ";", "String", "[", "]", "codes", "=", "new", "String", "[", "0", "]", ";", "for", "(", "String", "errorCode", ":", "errorCodes", ")", "{", "codes", "=", "Utils", ".", "concat", "(", "codes", ",", "generateMessageCodes", "(", "errorCode", ",", "fieldPath", ",", "fieldType", ")", ")", ";", "}", "return", "new", "InternalFieldErrorBuilder", "(", "this", ",", "getObjectName", "(", ")", ",", "fieldPath", ",", "codes", ")", ".", "sheetName", "(", "getSheetName", "(", ")", ")", ".", "rejectedValue", "(", "fieldValue", ")", ";", "}" ]
フィールドエラーのビルダーを作成します。 @param field フィールドパス。 @param errorCodes エラーコード。先頭の要素が優先されます。 @return {@link FieldError}のインスタンスを組み立てるビルダクラス。
[ "フィールドエラーのビルダーを作成します。" ]
train
https://github.com/mygreen/xlsmapper/blob/a0c6b25c622e5f3a50b199ef685d2ee46ad5483c/src/main/java/com/gh/mygreen/xlsmapper/validation/SheetBindingErrors.java#L619-L634
rubenlagus/TelegramBots
telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendDocument.java
SendDocument.setDocument
public SendDocument setDocument(File file) { Objects.requireNonNull(file, "documentName cannot be null!"); this.document = new InputFile(file, file.getName()); return this; }
java
public SendDocument setDocument(File file) { Objects.requireNonNull(file, "documentName cannot be null!"); this.document = new InputFile(file, file.getName()); return this; }
[ "public", "SendDocument", "setDocument", "(", "File", "file", ")", "{", "Objects", ".", "requireNonNull", "(", "file", ",", "\"documentName cannot be null!\"", ")", ";", "this", ".", "document", "=", "new", "InputFile", "(", "file", ",", "file", ".", "getName", "(", ")", ")", ";", "return", "this", ";", "}" ]
Use this method to set the document to a new file @param file New document file
[ "Use", "this", "method", "to", "set", "the", "document", "to", "a", "new", "file" ]
train
https://github.com/rubenlagus/TelegramBots/blob/d62354915d7664597a40fd9858f16bce67ef1478/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendDocument.java#L89-L93
Azure/azure-sdk-for-java
signalr/resource-manager/v2018_03_01_preview/src/main/java/com/microsoft/azure/management/signalr/v2018_03_01_preview/implementation/SignalRsInner.java
SignalRsInner.beginCreateOrUpdate
public SignalRResourceInner beginCreateOrUpdate(String resourceGroupName, String resourceName, SignalRCreateParameters parameters) { return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, resourceName, parameters).toBlocking().single().body(); }
java
public SignalRResourceInner beginCreateOrUpdate(String resourceGroupName, String resourceName, SignalRCreateParameters parameters) { return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, resourceName, parameters).toBlocking().single().body(); }
[ "public", "SignalRResourceInner", "beginCreateOrUpdate", "(", "String", "resourceGroupName", ",", "String", "resourceName", ",", "SignalRCreateParameters", "parameters", ")", "{", "return", "beginCreateOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "resourceName", ",", "parameters", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Create a new SignalR service and update an exiting SignalR service. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param resourceName The name of the SignalR resource. @param parameters Parameters for the create or update operation @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 SignalRResourceInner object if successful.
[ "Create", "a", "new", "SignalR", "service", "and", "update", "an", "exiting", "SignalR", "service", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/signalr/resource-manager/v2018_03_01_preview/src/main/java/com/microsoft/azure/management/signalr/v2018_03_01_preview/implementation/SignalRsInner.java#L1208-L1210
forge/core
facets/api/src/main/java/org/jboss/forge/addon/facets/constraints/FacetInspector.java
FacetInspector.getAllOptionalFacets
public static <FACETEDTYPE extends Faceted<FACETTYPE>, FACETTYPE extends Facet<FACETEDTYPE>> Set<Class<FACETTYPE>> getAllOptionalFacets( final Class<FACETTYPE> inspectedType) { Set<Class<FACETTYPE>> seen = new LinkedHashSet<Class<FACETTYPE>>(); return getAllRelatedFacets(seen, inspectedType, FacetConstraintType.OPTIONAL); }
java
public static <FACETEDTYPE extends Faceted<FACETTYPE>, FACETTYPE extends Facet<FACETEDTYPE>> Set<Class<FACETTYPE>> getAllOptionalFacets( final Class<FACETTYPE> inspectedType) { Set<Class<FACETTYPE>> seen = new LinkedHashSet<Class<FACETTYPE>>(); return getAllRelatedFacets(seen, inspectedType, FacetConstraintType.OPTIONAL); }
[ "public", "static", "<", "FACETEDTYPE", "extends", "Faceted", "<", "FACETTYPE", ">", ",", "FACETTYPE", "extends", "Facet", "<", "FACETEDTYPE", ">", ">", "Set", "<", "Class", "<", "FACETTYPE", ">", ">", "getAllOptionalFacets", "(", "final", "Class", "<", "FACETTYPE", ">", "inspectedType", ")", "{", "Set", "<", "Class", "<", "FACETTYPE", ">>", "seen", "=", "new", "LinkedHashSet", "<", "Class", "<", "FACETTYPE", ">", ">", "(", ")", ";", "return", "getAllRelatedFacets", "(", "seen", ",", "inspectedType", ",", "FacetConstraintType", ".", "OPTIONAL", ")", ";", "}" ]
Inspect the given {@link Class} for all {@link FacetConstraintType#OPTIONAL} dependency {@link Facet} types. This method inspects the entire constraint tree.
[ "Inspect", "the", "given", "{" ]
train
https://github.com/forge/core/blob/e140eb03bbe2b3409478ad70c86c3edbef6d9a0c/facets/api/src/main/java/org/jboss/forge/addon/facets/constraints/FacetInspector.java#L135-L140
Azure/azure-sdk-for-java
sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/JobExecutionsInner.java
JobExecutionsInner.beginCreateOrUpdate
public JobExecutionInner beginCreateOrUpdate(String resourceGroupName, String serverName, String jobAgentName, String jobName, UUID jobExecutionId) { return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, jobAgentName, jobName, jobExecutionId).toBlocking().single().body(); }
java
public JobExecutionInner beginCreateOrUpdate(String resourceGroupName, String serverName, String jobAgentName, String jobName, UUID jobExecutionId) { return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, jobAgentName, jobName, jobExecutionId).toBlocking().single().body(); }
[ "public", "JobExecutionInner", "beginCreateOrUpdate", "(", "String", "resourceGroupName", ",", "String", "serverName", ",", "String", "jobAgentName", ",", "String", "jobName", ",", "UUID", "jobExecutionId", ")", "{", "return", "beginCreateOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "serverName", ",", "jobAgentName", ",", "jobName", ",", "jobExecutionId", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Creates or updatess a job execution. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server. @param jobAgentName The name of the job agent. @param jobName The name of the job to get. @param jobExecutionId The job execution id to create the job execution under. @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 JobExecutionInner object if successful.
[ "Creates", "or", "updatess", "a", "job", "execution", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/JobExecutionsInner.java#L1216-L1218
app55/app55-java
src/support/java/com/googlecode/openbeans/Beans.java
Beans.instantiate
public static Object instantiate(ClassLoader loader, String name) throws IOException, ClassNotFoundException { return internalInstantiate(loader, name, null, null); }
java
public static Object instantiate(ClassLoader loader, String name) throws IOException, ClassNotFoundException { return internalInstantiate(loader, name, null, null); }
[ "public", "static", "Object", "instantiate", "(", "ClassLoader", "loader", ",", "String", "name", ")", "throws", "IOException", ",", "ClassNotFoundException", "{", "return", "internalInstantiate", "(", "loader", ",", "name", ",", "null", ",", "null", ")", ";", "}" ]
Obtains an instance of a JavaBean specified the bean name using the specified class loader. <p> If the specified class loader is null, the system class loader is used. </p> @param loader the specified class loader. It can be null. @param name the name of the JavaBean @return an isntance of the bean. @throws IOException @throws ClassNotFoundException
[ "Obtains", "an", "instance", "of", "a", "JavaBean", "specified", "the", "bean", "name", "using", "the", "specified", "class", "loader", ".", "<p", ">", "If", "the", "specified", "class", "loader", "is", "null", "the", "system", "class", "loader", "is", "used", ".", "<", "/", "p", ">" ]
train
https://github.com/app55/app55-java/blob/73e51d0f3141a859dfbd37ca9becef98477e553e/src/support/java/com/googlecode/openbeans/Beans.java#L144-L147
salesforce/Argus
ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/resources/NamespaceResources.java
NamespaceResources.updateNamespace
@PUT @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Path("/{namespaceId}") @Description("Update the namespace.") public NamespaceDto updateNamespace(@Context HttpServletRequest req, @PathParam("namespaceId") final BigInteger namespaceId, NamespaceDto newNamespace) { PrincipalUser remoteUser = getRemoteUser(req); if (namespaceId == null || namespaceId.compareTo(BigInteger.ZERO) < 1) { throw new WebApplicationException("Namespace Id cannot be null and must be a positive non-zero number.", Status.BAD_REQUEST); } if (newNamespace == null) { throw new WebApplicationException("Cannot update null namespace.", Status.BAD_REQUEST); } Namespace oldNamespace = _namespaceService.findNamespaceByPrimaryKey(namespaceId); if (oldNamespace == null) { throw new WebApplicationException("The namespace with id " + namespaceId + " does not exist", Response.Status.NOT_FOUND); } if (!oldNamespace.getQualifier().equals(newNamespace.getQualifier())) { throw new WebApplicationException("The qualifier can not be updated.", Response.Status.NOT_FOUND); } validateResourceAuthorization(req, oldNamespace.getCreatedBy(), remoteUser); Set<PrincipalUser> users = _getPrincipalUserByUserName(newNamespace.getUsernames()); if (!users.contains(oldNamespace.getOwner())) { users.add(oldNamespace.getOwner()); } oldNamespace.setUsers(users); return NamespaceDto.transformToDto(_namespaceService.updateNamespace(oldNamespace)); }
java
@PUT @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Path("/{namespaceId}") @Description("Update the namespace.") public NamespaceDto updateNamespace(@Context HttpServletRequest req, @PathParam("namespaceId") final BigInteger namespaceId, NamespaceDto newNamespace) { PrincipalUser remoteUser = getRemoteUser(req); if (namespaceId == null || namespaceId.compareTo(BigInteger.ZERO) < 1) { throw new WebApplicationException("Namespace Id cannot be null and must be a positive non-zero number.", Status.BAD_REQUEST); } if (newNamespace == null) { throw new WebApplicationException("Cannot update null namespace.", Status.BAD_REQUEST); } Namespace oldNamespace = _namespaceService.findNamespaceByPrimaryKey(namespaceId); if (oldNamespace == null) { throw new WebApplicationException("The namespace with id " + namespaceId + " does not exist", Response.Status.NOT_FOUND); } if (!oldNamespace.getQualifier().equals(newNamespace.getQualifier())) { throw new WebApplicationException("The qualifier can not be updated.", Response.Status.NOT_FOUND); } validateResourceAuthorization(req, oldNamespace.getCreatedBy(), remoteUser); Set<PrincipalUser> users = _getPrincipalUserByUserName(newNamespace.getUsernames()); if (!users.contains(oldNamespace.getOwner())) { users.add(oldNamespace.getOwner()); } oldNamespace.setUsers(users); return NamespaceDto.transformToDto(_namespaceService.updateNamespace(oldNamespace)); }
[ "@", "PUT", "@", "Produces", "(", "MediaType", ".", "APPLICATION_JSON", ")", "@", "Consumes", "(", "MediaType", ".", "APPLICATION_JSON", ")", "@", "Path", "(", "\"/{namespaceId}\"", ")", "@", "Description", "(", "\"Update the namespace.\"", ")", "public", "NamespaceDto", "updateNamespace", "(", "@", "Context", "HttpServletRequest", "req", ",", "@", "PathParam", "(", "\"namespaceId\"", ")", "final", "BigInteger", "namespaceId", ",", "NamespaceDto", "newNamespace", ")", "{", "PrincipalUser", "remoteUser", "=", "getRemoteUser", "(", "req", ")", ";", "if", "(", "namespaceId", "==", "null", "||", "namespaceId", ".", "compareTo", "(", "BigInteger", ".", "ZERO", ")", "<", "1", ")", "{", "throw", "new", "WebApplicationException", "(", "\"Namespace Id cannot be null and must be a positive non-zero number.\"", ",", "Status", ".", "BAD_REQUEST", ")", ";", "}", "if", "(", "newNamespace", "==", "null", ")", "{", "throw", "new", "WebApplicationException", "(", "\"Cannot update null namespace.\"", ",", "Status", ".", "BAD_REQUEST", ")", ";", "}", "Namespace", "oldNamespace", "=", "_namespaceService", ".", "findNamespaceByPrimaryKey", "(", "namespaceId", ")", ";", "if", "(", "oldNamespace", "==", "null", ")", "{", "throw", "new", "WebApplicationException", "(", "\"The namespace with id \"", "+", "namespaceId", "+", "\" does not exist\"", ",", "Response", ".", "Status", ".", "NOT_FOUND", ")", ";", "}", "if", "(", "!", "oldNamespace", ".", "getQualifier", "(", ")", ".", "equals", "(", "newNamespace", ".", "getQualifier", "(", ")", ")", ")", "{", "throw", "new", "WebApplicationException", "(", "\"The qualifier can not be updated.\"", ",", "Response", ".", "Status", ".", "NOT_FOUND", ")", ";", "}", "validateResourceAuthorization", "(", "req", ",", "oldNamespace", ".", "getCreatedBy", "(", ")", ",", "remoteUser", ")", ";", "Set", "<", "PrincipalUser", ">", "users", "=", "_getPrincipalUserByUserName", "(", "newNamespace", ".", "getUsernames", "(", ")", ")", ";", "if", "(", "!", "users", ".", "contains", "(", "oldNamespace", ".", "getOwner", "(", ")", ")", ")", "{", "users", ".", "add", "(", "oldNamespace", ".", "getOwner", "(", ")", ")", ";", "}", "oldNamespace", ".", "setUsers", "(", "users", ")", ";", "return", "NamespaceDto", ".", "transformToDto", "(", "_namespaceService", ".", "updateNamespace", "(", "oldNamespace", ")", ")", ";", "}" ]
Updates a namespace. @param req The HTTP request. @param namespaceId The ID of the namespace to update. @param newNamespace The updated namespace data. @return The updated namespace. @throws WebApplicationException If an error occurs.
[ "Updates", "a", "namespace", "." ]
train
https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/resources/NamespaceResources.java#L167-L200
xmlunit/xmlunit
xmlunit-placeholders/src/main/java/org/xmlunit/placeholder/PlaceholderSupport.java
PlaceholderSupport.withPlaceholderSupportChainedAfter
public static <D extends DifferenceEngineConfigurer<D>> D withPlaceholderSupportChainedAfter(D configurer, DifferenceEvaluator evaluator) { return withPlaceholderSupportUsingDelimitersChainedAfter(configurer, null, null, evaluator); }
java
public static <D extends DifferenceEngineConfigurer<D>> D withPlaceholderSupportChainedAfter(D configurer, DifferenceEvaluator evaluator) { return withPlaceholderSupportUsingDelimitersChainedAfter(configurer, null, null, evaluator); }
[ "public", "static", "<", "D", "extends", "DifferenceEngineConfigurer", "<", "D", ">", ">", "D", "withPlaceholderSupportChainedAfter", "(", "D", "configurer", ",", "DifferenceEvaluator", "evaluator", ")", "{", "return", "withPlaceholderSupportUsingDelimitersChainedAfter", "(", "configurer", ",", "null", ",", "null", ",", "evaluator", ")", ";", "}" ]
Adds placeholder support to a {@link DifferenceEngineConfigurer} considering an additional {@link DifferenceEvaluator}. @param configurer the configurer to add support to @param evaluator the additional evaluator - placeholder support is {@link DifferenceEvaluators#chain chain}ed after the given evaluator
[ "Adds", "placeholder", "support", "to", "a", "{", "@link", "DifferenceEngineConfigurer", "}", "considering", "an", "additional", "{", "@link", "DifferenceEvaluator", "}", "." ]
train
https://github.com/xmlunit/xmlunit/blob/fe3d701d43f57ee83dcba336e4c1555619d3084b/xmlunit-placeholders/src/main/java/org/xmlunit/placeholder/PlaceholderSupport.java#L72-L75
cdk/cdk
display/renderbasic/src/main/java/org/openscience/cdk/renderer/generators/standard/SelectionVisibility.java
SelectionVisibility.hasSelectedBond
static boolean hasSelectedBond(List<IBond> bonds, RendererModel model) { for (IBond bond : bonds) { if (isSelected(bond, model)) return true; } return false; }
java
static boolean hasSelectedBond(List<IBond> bonds, RendererModel model) { for (IBond bond : bonds) { if (isSelected(bond, model)) return true; } return false; }
[ "static", "boolean", "hasSelectedBond", "(", "List", "<", "IBond", ">", "bonds", ",", "RendererModel", "model", ")", "{", "for", "(", "IBond", "bond", ":", "bonds", ")", "{", "if", "(", "isSelected", "(", "bond", ",", "model", ")", ")", "return", "true", ";", "}", "return", "false", ";", "}" ]
Determines if any bond in the list is selected @param bonds list of bonds @return at least bond bond is selected
[ "Determines", "if", "any", "bond", "in", "the", "list", "is", "selected" ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/display/renderbasic/src/main/java/org/openscience/cdk/renderer/generators/standard/SelectionVisibility.java#L111-L116
GenesysPureEngage/workspace-client-java
src/main/java/com/genesys/internal/workspace/api/UcsApi.java
UcsApi.getLuceneIndexesAsync
public com.squareup.okhttp.Call getLuceneIndexesAsync(LuceneIndexesData luceneIndexesData, final ApiCallback<ConfigResponse> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = getLuceneIndexesValidateBeforeCall(luceneIndexesData, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<ConfigResponse>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; }
java
public com.squareup.okhttp.Call getLuceneIndexesAsync(LuceneIndexesData luceneIndexesData, final ApiCallback<ConfigResponse> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = getLuceneIndexesValidateBeforeCall(luceneIndexesData, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<ConfigResponse>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; }
[ "public", "com", ".", "squareup", ".", "okhttp", ".", "Call", "getLuceneIndexesAsync", "(", "LuceneIndexesData", "luceneIndexesData", ",", "final", "ApiCallback", "<", "ConfigResponse", ">", "callback", ")", "throws", "ApiException", "{", "ProgressResponseBody", ".", "ProgressListener", "progressListener", "=", "null", ";", "ProgressRequestBody", ".", "ProgressRequestListener", "progressRequestListener", "=", "null", ";", "if", "(", "callback", "!=", "null", ")", "{", "progressListener", "=", "new", "ProgressResponseBody", ".", "ProgressListener", "(", ")", "{", "@", "Override", "public", "void", "update", "(", "long", "bytesRead", ",", "long", "contentLength", ",", "boolean", "done", ")", "{", "callback", ".", "onDownloadProgress", "(", "bytesRead", ",", "contentLength", ",", "done", ")", ";", "}", "}", ";", "progressRequestListener", "=", "new", "ProgressRequestBody", ".", "ProgressRequestListener", "(", ")", "{", "@", "Override", "public", "void", "onRequestProgress", "(", "long", "bytesWritten", ",", "long", "contentLength", ",", "boolean", "done", ")", "{", "callback", ".", "onUploadProgress", "(", "bytesWritten", ",", "contentLength", ",", "done", ")", ";", "}", "}", ";", "}", "com", ".", "squareup", ".", "okhttp", ".", "Call", "call", "=", "getLuceneIndexesValidateBeforeCall", "(", "luceneIndexesData", ",", "progressListener", ",", "progressRequestListener", ")", ";", "Type", "localVarReturnType", "=", "new", "TypeToken", "<", "ConfigResponse", ">", "(", ")", "{", "}", ".", "getType", "(", ")", ";", "apiClient", ".", "executeAsync", "(", "call", ",", "localVarReturnType", ",", "callback", ")", ";", "return", "call", ";", "}" ]
Get the lucene indexes for ucs (asynchronously) This request returns all the lucene indexes for contact. @param luceneIndexesData Request parameters. (optional) @param callback The callback to be executed when the API call finishes @return The request call @throws ApiException If fail to process the API call, e.g. serializing the request body object
[ "Get", "the", "lucene", "indexes", "for", "ucs", "(", "asynchronously", ")", "This", "request", "returns", "all", "the", "lucene", "indexes", "for", "contact", "." ]
train
https://github.com/GenesysPureEngage/workspace-client-java/blob/509fdd9e89b9359d012f9a72be95037a3cef53e6/src/main/java/com/genesys/internal/workspace/api/UcsApi.java#L1305-L1330
apache/incubator-gobblin
gobblin-modules/gobblin-crypto/src/main/java/org/apache/gobblin/crypto/GPGFileEncryptor.java
GPGFileEncryptor.encryptFile
public OutputStream encryptFile(OutputStream outputStream, InputStream keyIn, long keyId, String cipher) throws IOException { try { if (Security.getProvider(PROVIDER_NAME) == null) { Security.addProvider(new BouncyCastleProvider()); } PGPEncryptedDataGenerator cPk = new PGPEncryptedDataGenerator( new JcePGPDataEncryptorBuilder(symmetricKeyAlgorithmNameToTag(cipher)) .setSecureRandom(new SecureRandom()) .setProvider(PROVIDER_NAME)); PGPPublicKey publicKey; PGPPublicKeyRingCollection keyRings = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(keyIn), new BcKeyFingerprintCalculator()); publicKey = keyRings.getPublicKey(keyId); if (publicKey == null) { throw new IllegalArgumentException("public key for encryption not found"); } cPk.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(publicKey).setProvider(PROVIDER_NAME)); OutputStream cOut = cPk.open(outputStream, new byte[BUFFER_SIZE]); PGPLiteralDataGenerator literalGen = new PGPLiteralDataGenerator(); OutputStream _literalOut = literalGen.open(cOut, PGPLiteralDataGenerator.BINARY, PAYLOAD_NAME, new Date(), new byte[BUFFER_SIZE]); return new ClosingWrapperOutputStream(_literalOut, cOut, outputStream); } catch (PGPException e) { throw new IOException(e); } }
java
public OutputStream encryptFile(OutputStream outputStream, InputStream keyIn, long keyId, String cipher) throws IOException { try { if (Security.getProvider(PROVIDER_NAME) == null) { Security.addProvider(new BouncyCastleProvider()); } PGPEncryptedDataGenerator cPk = new PGPEncryptedDataGenerator( new JcePGPDataEncryptorBuilder(symmetricKeyAlgorithmNameToTag(cipher)) .setSecureRandom(new SecureRandom()) .setProvider(PROVIDER_NAME)); PGPPublicKey publicKey; PGPPublicKeyRingCollection keyRings = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(keyIn), new BcKeyFingerprintCalculator()); publicKey = keyRings.getPublicKey(keyId); if (publicKey == null) { throw new IllegalArgumentException("public key for encryption not found"); } cPk.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(publicKey).setProvider(PROVIDER_NAME)); OutputStream cOut = cPk.open(outputStream, new byte[BUFFER_SIZE]); PGPLiteralDataGenerator literalGen = new PGPLiteralDataGenerator(); OutputStream _literalOut = literalGen.open(cOut, PGPLiteralDataGenerator.BINARY, PAYLOAD_NAME, new Date(), new byte[BUFFER_SIZE]); return new ClosingWrapperOutputStream(_literalOut, cOut, outputStream); } catch (PGPException e) { throw new IOException(e); } }
[ "public", "OutputStream", "encryptFile", "(", "OutputStream", "outputStream", ",", "InputStream", "keyIn", ",", "long", "keyId", ",", "String", "cipher", ")", "throws", "IOException", "{", "try", "{", "if", "(", "Security", ".", "getProvider", "(", "PROVIDER_NAME", ")", "==", "null", ")", "{", "Security", ".", "addProvider", "(", "new", "BouncyCastleProvider", "(", ")", ")", ";", "}", "PGPEncryptedDataGenerator", "cPk", "=", "new", "PGPEncryptedDataGenerator", "(", "new", "JcePGPDataEncryptorBuilder", "(", "symmetricKeyAlgorithmNameToTag", "(", "cipher", ")", ")", ".", "setSecureRandom", "(", "new", "SecureRandom", "(", ")", ")", ".", "setProvider", "(", "PROVIDER_NAME", ")", ")", ";", "PGPPublicKey", "publicKey", ";", "PGPPublicKeyRingCollection", "keyRings", "=", "new", "PGPPublicKeyRingCollection", "(", "PGPUtil", ".", "getDecoderStream", "(", "keyIn", ")", ",", "new", "BcKeyFingerprintCalculator", "(", ")", ")", ";", "publicKey", "=", "keyRings", ".", "getPublicKey", "(", "keyId", ")", ";", "if", "(", "publicKey", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"public key for encryption not found\"", ")", ";", "}", "cPk", ".", "addMethod", "(", "new", "JcePublicKeyKeyEncryptionMethodGenerator", "(", "publicKey", ")", ".", "setProvider", "(", "PROVIDER_NAME", ")", ")", ";", "OutputStream", "cOut", "=", "cPk", ".", "open", "(", "outputStream", ",", "new", "byte", "[", "BUFFER_SIZE", "]", ")", ";", "PGPLiteralDataGenerator", "literalGen", "=", "new", "PGPLiteralDataGenerator", "(", ")", ";", "OutputStream", "_literalOut", "=", "literalGen", ".", "open", "(", "cOut", ",", "PGPLiteralDataGenerator", ".", "BINARY", ",", "PAYLOAD_NAME", ",", "new", "Date", "(", ")", ",", "new", "byte", "[", "BUFFER_SIZE", "]", ")", ";", "return", "new", "ClosingWrapperOutputStream", "(", "_literalOut", ",", "cOut", ",", "outputStream", ")", ";", "}", "catch", "(", "PGPException", "e", ")", "{", "throw", "new", "IOException", "(", "e", ")", ";", "}", "}" ]
Taking in an input {@link OutputStream}, keyring inputstream and a passPhrase, generate an encrypted {@link OutputStream}. @param outputStream {@link OutputStream} that will receive the encrypted content @param keyIn keyring inputstream. This InputStream is owned by the caller. @param keyId key identifier @param cipher the symmetric cipher to use for encryption. If null or empty then a default cipher is used. @return an {@link OutputStream} to write content to for encryption @throws IOException
[ "Taking", "in", "an", "input", "{" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-crypto/src/main/java/org/apache/gobblin/crypto/GPGFileEncryptor.java#L103-L136
ModeShape/modeshape
index-providers/modeshape-lucene-index-provider/src/main/java/org/modeshape/jcr/index/lucene/query/CompareNameQuery.java
CompareNameQuery.createQueryForNodesWithNameEqualTo
public static Query createQueryForNodesWithNameEqualTo( Name constraintValue, String fieldName, ValueFactories factories, Function<String, String> caseOperation) { return new CompareNameQuery(fieldName, constraintValue, factories.getNameFactory(), Objects::equals, caseOperation); }
java
public static Query createQueryForNodesWithNameEqualTo( Name constraintValue, String fieldName, ValueFactories factories, Function<String, String> caseOperation) { return new CompareNameQuery(fieldName, constraintValue, factories.getNameFactory(), Objects::equals, caseOperation); }
[ "public", "static", "Query", "createQueryForNodesWithNameEqualTo", "(", "Name", "constraintValue", ",", "String", "fieldName", ",", "ValueFactories", "factories", ",", "Function", "<", "String", ",", "String", ">", "caseOperation", ")", "{", "return", "new", "CompareNameQuery", "(", "fieldName", ",", "constraintValue", ",", "factories", ".", "getNameFactory", "(", ")", ",", "Objects", "::", "equals", ",", "caseOperation", ")", ";", "}" ]
Construct a {@link Query} implementation that scores documents such that the node represented by the document has a name that is greater than the supplied constraint name. @param constraintValue the constraint value; may not be null @param fieldName the name of the document field containing the name value; may not be null @param factories the value factories that can be used during the scoring; may not be null @param caseOperation the operation that should be performed on the indexed values before the constraint value is being evaluated; may be null which indicates that no case conversion should be done @return the query; never null
[ "Construct", "a", "{", "@link", "Query", "}", "implementation", "that", "scores", "documents", "such", "that", "the", "node", "represented", "by", "the", "document", "has", "a", "name", "that", "is", "greater", "than", "the", "supplied", "constraint", "name", "." ]
train
https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/index-providers/modeshape-lucene-index-provider/src/main/java/org/modeshape/jcr/index/lucene/query/CompareNameQuery.java#L83-L89
mebigfatguy/fb-contrib
src/main/java/com/mebigfatguy/fbcontrib/detect/OrphanedDOMNode.java
OrphanedDOMNode.visitCode
@Override public void visitCode(Code obj) { stack.resetForMethodEntry(this); nodeCreations.clear(); nodeStores.clear(); super.visitCode(obj); BitSet reportedPCs = new BitSet(); for (Integer pc : nodeCreations.values()) { if (!reportedPCs.get(pc.intValue())) { bugReporter.reportBug(new BugInstance(this, BugType.ODN_ORPHANED_DOM_NODE.name(), NORMAL_PRIORITY).addClass(this).addMethod(this) .addSourceLine(this, pc.intValue())); reportedPCs.set(pc.intValue()); } } for (Integer pc : nodeStores.values()) { if (!reportedPCs.get(pc.intValue())) { bugReporter.reportBug(new BugInstance(this, BugType.ODN_ORPHANED_DOM_NODE.name(), NORMAL_PRIORITY).addClass(this).addMethod(this) .addSourceLine(this, pc.intValue())); reportedPCs.set(pc.intValue()); } } }
java
@Override public void visitCode(Code obj) { stack.resetForMethodEntry(this); nodeCreations.clear(); nodeStores.clear(); super.visitCode(obj); BitSet reportedPCs = new BitSet(); for (Integer pc : nodeCreations.values()) { if (!reportedPCs.get(pc.intValue())) { bugReporter.reportBug(new BugInstance(this, BugType.ODN_ORPHANED_DOM_NODE.name(), NORMAL_PRIORITY).addClass(this).addMethod(this) .addSourceLine(this, pc.intValue())); reportedPCs.set(pc.intValue()); } } for (Integer pc : nodeStores.values()) { if (!reportedPCs.get(pc.intValue())) { bugReporter.reportBug(new BugInstance(this, BugType.ODN_ORPHANED_DOM_NODE.name(), NORMAL_PRIORITY).addClass(this).addMethod(this) .addSourceLine(this, pc.intValue())); reportedPCs.set(pc.intValue()); } } }
[ "@", "Override", "public", "void", "visitCode", "(", "Code", "obj", ")", "{", "stack", ".", "resetForMethodEntry", "(", "this", ")", ";", "nodeCreations", ".", "clear", "(", ")", ";", "nodeStores", ".", "clear", "(", ")", ";", "super", ".", "visitCode", "(", "obj", ")", ";", "BitSet", "reportedPCs", "=", "new", "BitSet", "(", ")", ";", "for", "(", "Integer", "pc", ":", "nodeCreations", ".", "values", "(", ")", ")", "{", "if", "(", "!", "reportedPCs", ".", "get", "(", "pc", ".", "intValue", "(", ")", ")", ")", "{", "bugReporter", ".", "reportBug", "(", "new", "BugInstance", "(", "this", ",", "BugType", ".", "ODN_ORPHANED_DOM_NODE", ".", "name", "(", ")", ",", "NORMAL_PRIORITY", ")", ".", "addClass", "(", "this", ")", ".", "addMethod", "(", "this", ")", ".", "addSourceLine", "(", "this", ",", "pc", ".", "intValue", "(", ")", ")", ")", ";", "reportedPCs", ".", "set", "(", "pc", ".", "intValue", "(", ")", ")", ";", "}", "}", "for", "(", "Integer", "pc", ":", "nodeStores", ".", "values", "(", ")", ")", "{", "if", "(", "!", "reportedPCs", ".", "get", "(", "pc", ".", "intValue", "(", ")", ")", ")", "{", "bugReporter", ".", "reportBug", "(", "new", "BugInstance", "(", "this", ",", "BugType", ".", "ODN_ORPHANED_DOM_NODE", ".", "name", "(", ")", ",", "NORMAL_PRIORITY", ")", ".", "addClass", "(", "this", ")", ".", "addMethod", "(", "this", ")", ".", "addSourceLine", "(", "this", ",", "pc", ".", "intValue", "(", ")", ")", ")", ";", "reportedPCs", ".", "set", "(", "pc", ".", "intValue", "(", ")", ")", ";", "}", "}", "}" ]
implements the visitor to clear the opcode stack for the next code @param obj the context object for the currently parsed code block
[ "implements", "the", "visitor", "to", "clear", "the", "opcode", "stack", "for", "the", "next", "code" ]
train
https://github.com/mebigfatguy/fb-contrib/blob/3b5203196f627b399fbcea3c2ab2b1f4e56cc7b8/src/main/java/com/mebigfatguy/fbcontrib/detect/OrphanedDOMNode.java#L95-L117
google/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/processor/TransformerFactoryImpl.java
TransformerFactoryImpl.setErrorListener
public void setErrorListener(ErrorListener listener) throws IllegalArgumentException { if (null == listener) throw new IllegalArgumentException(XSLMessages.createMessage(XSLTErrorResources.ER_ERRORLISTENER, null)); // "ErrorListener"); m_errorListener = listener; }
java
public void setErrorListener(ErrorListener listener) throws IllegalArgumentException { if (null == listener) throw new IllegalArgumentException(XSLMessages.createMessage(XSLTErrorResources.ER_ERRORLISTENER, null)); // "ErrorListener"); m_errorListener = listener; }
[ "public", "void", "setErrorListener", "(", "ErrorListener", "listener", ")", "throws", "IllegalArgumentException", "{", "if", "(", "null", "==", "listener", ")", "throw", "new", "IllegalArgumentException", "(", "XSLMessages", ".", "createMessage", "(", "XSLTErrorResources", ".", "ER_ERRORLISTENER", ",", "null", ")", ")", ";", "// \"ErrorListener\");", "m_errorListener", "=", "listener", ";", "}" ]
Set an error listener for the TransformerFactory. @param listener Must be a non-null reference to an ErrorListener. @throws IllegalArgumentException if the listener argument is null.
[ "Set", "an", "error", "listener", "for", "the", "TransformerFactory", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/processor/TransformerFactoryImpl.java#L1027-L1036
michael-rapp/AndroidUtil
library/src/main/java/de/mrapp/android/util/ThemeUtil.java
ThemeUtil.getBoolean
public static boolean getBoolean(@NonNull final Context context, @AttrRes final int resourceId, final boolean defaultValue) { return getBoolean(context, -1, resourceId, defaultValue); }
java
public static boolean getBoolean(@NonNull final Context context, @AttrRes final int resourceId, final boolean defaultValue) { return getBoolean(context, -1, resourceId, defaultValue); }
[ "public", "static", "boolean", "getBoolean", "(", "@", "NonNull", "final", "Context", "context", ",", "@", "AttrRes", "final", "int", "resourceId", ",", "final", "boolean", "defaultValue", ")", "{", "return", "getBoolean", "(", "context", ",", "-", "1", ",", "resourceId", ",", "defaultValue", ")", ";", "}" ]
Obtains the boolean value, which corresponds to a specific resource id, from a context's theme. @param context The context, which should be used, as an instance of the class {@link Context}. The context may not be null @param resourceId The resource id of the attribute, which should be obtained, as an {@link Integer} value. The resource id must corresponds to a valid theme attribute @param defaultValue The default value, which should be returned, if the given resource id is invalid, as a {@link Boolean} value @return The boolean value, which has been obtained, as an {@link Boolean} value or false, if the given resource id is invalid
[ "Obtains", "the", "boolean", "value", "which", "corresponds", "to", "a", "specific", "resource", "id", "from", "a", "context", "s", "theme", "." ]
train
https://github.com/michael-rapp/AndroidUtil/blob/67ec0e5732344eeb4d946dd1f96d782939e449f4/library/src/main/java/de/mrapp/android/util/ThemeUtil.java#L701-L704
awslabs/jsii
packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiClient.java
JsiiClient.callMethod
public JsonNode callMethod(final JsiiObjectRef objRef, final String method, final ArrayNode args) { ObjectNode req = makeRequest("invoke", objRef); req.put("method", method); req.set("args", args); JsonNode resp = this.runtime.requestResponse(req); return resp.get("result"); }
java
public JsonNode callMethod(final JsiiObjectRef objRef, final String method, final ArrayNode args) { ObjectNode req = makeRequest("invoke", objRef); req.put("method", method); req.set("args", args); JsonNode resp = this.runtime.requestResponse(req); return resp.get("result"); }
[ "public", "JsonNode", "callMethod", "(", "final", "JsiiObjectRef", "objRef", ",", "final", "String", "method", ",", "final", "ArrayNode", "args", ")", "{", "ObjectNode", "req", "=", "makeRequest", "(", "\"invoke\"", ",", "objRef", ")", ";", "req", ".", "put", "(", "\"method\"", ",", "method", ")", ";", "req", ".", "set", "(", "\"args\"", ",", "args", ")", ";", "JsonNode", "resp", "=", "this", ".", "runtime", ".", "requestResponse", "(", "req", ")", ";", "return", "resp", ".", "get", "(", "\"result\"", ")", ";", "}" ]
Calls a method on a remote object. @param objRef The remote object reference. @param method The name of the method. @param args Method arguments. @return The return value of the method.
[ "Calls", "a", "method", "on", "a", "remote", "object", "." ]
train
https://github.com/awslabs/jsii/blob/6bbf743f5f65e98e5199ad31c93961533ffc40e5/packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiClient.java#L180-L187
baratine/baratine
framework/src/main/java/com/caucho/v5/util/QDate.java
QDate.monthToDayOfYear
private long monthToDayOfYear(long month, boolean isLeapYear) { long day = 0; for (int i = 0; i < month && i < 12; i++) { day += DAYS_IN_MONTH[i]; if (i == 1 && isLeapYear) day++; } return day; }
java
private long monthToDayOfYear(long month, boolean isLeapYear) { long day = 0; for (int i = 0; i < month && i < 12; i++) { day += DAYS_IN_MONTH[i]; if (i == 1 && isLeapYear) day++; } return day; }
[ "private", "long", "monthToDayOfYear", "(", "long", "month", ",", "boolean", "isLeapYear", ")", "{", "long", "day", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "month", "&&", "i", "<", "12", ";", "i", "++", ")", "{", "day", "+=", "DAYS_IN_MONTH", "[", "i", "]", ";", "if", "(", "i", "==", "1", "&&", "isLeapYear", ")", "day", "++", ";", "}", "return", "day", ";", "}" ]
Calculates the day of the year for the beginning of the month.
[ "Calculates", "the", "day", "of", "the", "year", "for", "the", "beginning", "of", "the", "month", "." ]
train
https://github.com/baratine/baratine/blob/db34b45c03c5a5e930d8142acc72319125569fcf/framework/src/main/java/com/caucho/v5/util/QDate.java#L1580-L1591
alkacon/opencms-core
src/org/opencms/module/CmsModuleImportExportHandler.java
CmsModuleImportExportHandler.readModuleFromManifest
public static CmsModule readModuleFromManifest(byte[] manifest) throws CmsConfigurationException { // instantiate Digester and enable XML validation Digester digester = new Digester(); digester.setUseContextClassLoader(true); digester.setValidating(false); digester.setRuleNamespaceURI(null); digester.setErrorHandler(new CmsXmlErrorHandler("manifest data")); // add this class to the Digester CmsModuleImportExportHandler handler = new CmsModuleImportExportHandler(); final String[] version = new String[] {null}; digester.push(handler); digester.addRule("*/export_version", new Rule() { @Override public void body(String namespace, String name, String text) throws Exception { version[0] = text.trim(); } }); CmsModuleXmlHandler.addXmlDigesterRules(digester); InputStream stream = new ByteArrayInputStream(manifest); try { digester.parse(stream); } catch (IOException e) { CmsMessageContainer message = Messages.get().container(Messages.ERR_IO_MODULE_IMPORT_1, "manifest data"); LOG.error(message.key(), e); throw new CmsConfigurationException(message, e); } catch (SAXException e) { CmsMessageContainer message = Messages.get().container(Messages.ERR_SAX_MODULE_IMPORT_1, "manifest data"); LOG.error(message.key(), e); throw new CmsConfigurationException(message, e); } CmsModule importedModule = handler.getModule(); // the digester must have set the module now if (importedModule == null) { throw new CmsConfigurationException( Messages.get().container(Messages.ERR_IMPORT_MOD_ALREADY_INSTALLED_1, "manifest data")); } else { importedModule.setExportVersion(version[0]); } return importedModule; }
java
public static CmsModule readModuleFromManifest(byte[] manifest) throws CmsConfigurationException { // instantiate Digester and enable XML validation Digester digester = new Digester(); digester.setUseContextClassLoader(true); digester.setValidating(false); digester.setRuleNamespaceURI(null); digester.setErrorHandler(new CmsXmlErrorHandler("manifest data")); // add this class to the Digester CmsModuleImportExportHandler handler = new CmsModuleImportExportHandler(); final String[] version = new String[] {null}; digester.push(handler); digester.addRule("*/export_version", new Rule() { @Override public void body(String namespace, String name, String text) throws Exception { version[0] = text.trim(); } }); CmsModuleXmlHandler.addXmlDigesterRules(digester); InputStream stream = new ByteArrayInputStream(manifest); try { digester.parse(stream); } catch (IOException e) { CmsMessageContainer message = Messages.get().container(Messages.ERR_IO_MODULE_IMPORT_1, "manifest data"); LOG.error(message.key(), e); throw new CmsConfigurationException(message, e); } catch (SAXException e) { CmsMessageContainer message = Messages.get().container(Messages.ERR_SAX_MODULE_IMPORT_1, "manifest data"); LOG.error(message.key(), e); throw new CmsConfigurationException(message, e); } CmsModule importedModule = handler.getModule(); // the digester must have set the module now if (importedModule == null) { throw new CmsConfigurationException( Messages.get().container(Messages.ERR_IMPORT_MOD_ALREADY_INSTALLED_1, "manifest data")); } else { importedModule.setExportVersion(version[0]); } return importedModule; }
[ "public", "static", "CmsModule", "readModuleFromManifest", "(", "byte", "[", "]", "manifest", ")", "throws", "CmsConfigurationException", "{", "// instantiate Digester and enable XML validation", "Digester", "digester", "=", "new", "Digester", "(", ")", ";", "digester", ".", "setUseContextClassLoader", "(", "true", ")", ";", "digester", ".", "setValidating", "(", "false", ")", ";", "digester", ".", "setRuleNamespaceURI", "(", "null", ")", ";", "digester", ".", "setErrorHandler", "(", "new", "CmsXmlErrorHandler", "(", "\"manifest data\"", ")", ")", ";", "// add this class to the Digester", "CmsModuleImportExportHandler", "handler", "=", "new", "CmsModuleImportExportHandler", "(", ")", ";", "final", "String", "[", "]", "version", "=", "new", "String", "[", "]", "{", "null", "}", ";", "digester", ".", "push", "(", "handler", ")", ";", "digester", ".", "addRule", "(", "\"*/export_version\"", ",", "new", "Rule", "(", ")", "{", "@", "Override", "public", "void", "body", "(", "String", "namespace", ",", "String", "name", ",", "String", "text", ")", "throws", "Exception", "{", "version", "[", "0", "]", "=", "text", ".", "trim", "(", ")", ";", "}", "}", ")", ";", "CmsModuleXmlHandler", ".", "addXmlDigesterRules", "(", "digester", ")", ";", "InputStream", "stream", "=", "new", "ByteArrayInputStream", "(", "manifest", ")", ";", "try", "{", "digester", ".", "parse", "(", "stream", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "CmsMessageContainer", "message", "=", "Messages", ".", "get", "(", ")", ".", "container", "(", "Messages", ".", "ERR_IO_MODULE_IMPORT_1", ",", "\"manifest data\"", ")", ";", "LOG", ".", "error", "(", "message", ".", "key", "(", ")", ",", "e", ")", ";", "throw", "new", "CmsConfigurationException", "(", "message", ",", "e", ")", ";", "}", "catch", "(", "SAXException", "e", ")", "{", "CmsMessageContainer", "message", "=", "Messages", ".", "get", "(", ")", ".", "container", "(", "Messages", ".", "ERR_SAX_MODULE_IMPORT_1", ",", "\"manifest data\"", ")", ";", "LOG", ".", "error", "(", "message", ".", "key", "(", ")", ",", "e", ")", ";", "throw", "new", "CmsConfigurationException", "(", "message", ",", "e", ")", ";", "}", "CmsModule", "importedModule", "=", "handler", ".", "getModule", "(", ")", ";", "// the digester must have set the module now", "if", "(", "importedModule", "==", "null", ")", "{", "throw", "new", "CmsConfigurationException", "(", "Messages", ".", "get", "(", ")", ".", "container", "(", "Messages", ".", "ERR_IMPORT_MOD_ALREADY_INSTALLED_1", ",", "\"manifest data\"", ")", ")", ";", "}", "else", "{", "importedModule", ".", "setExportVersion", "(", "version", "[", "0", "]", ")", ";", "}", "return", "importedModule", ";", "}" ]
Reads a module object from an external file source.<p> @param manifest the manifest data @return the imported module @throws CmsConfigurationException if the module could not be imported
[ "Reads", "a", "module", "object", "from", "an", "external", "file", "source", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/module/CmsModuleImportExportHandler.java#L278-L326
apache/incubator-gobblin
gobblin-utility/src/main/java/org/apache/gobblin/util/ConfigUtils.java
ConfigUtils.getConfig
public static Config getConfig(Config config, String path, Config def) { if (config.hasPath(path)) { return config.getConfig(path); } return def; }
java
public static Config getConfig(Config config, String path, Config def) { if (config.hasPath(path)) { return config.getConfig(path); } return def; }
[ "public", "static", "Config", "getConfig", "(", "Config", "config", ",", "String", "path", ",", "Config", "def", ")", "{", "if", "(", "config", ".", "hasPath", "(", "path", ")", ")", "{", "return", "config", ".", "getConfig", "(", "path", ")", ";", "}", "return", "def", ";", "}" ]
Return {@link Config} value at <code>path</code> if <code>config</code> has path. If not return <code>def</code> @param config in which the path may be present @param path key to look for in the config object @return config value at <code>path</code> if <code>config</code> has path. If not return <code>def</code>
[ "Return", "{", "@link", "Config", "}", "value", "at", "<code", ">", "path<", "/", "code", ">", "if", "<code", ">", "config<", "/", "code", ">", "has", "path", ".", "If", "not", "return", "<code", ">", "def<", "/", "code", ">" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/ConfigUtils.java#L392-L397
pac4j/pac4j
pac4j-oauth/src/main/java/org/pac4j/oauth/profile/generic/GenericOAuth20ProfileDefinition.java
GenericOAuth20ProfileDefinition.profileAttribute
public void profileAttribute(final String name, String tag, final AttributeConverter<? extends Object> converter) { profileAttributes.put(name, tag); if (converter != null) { getConverters().put(name, converter); } else { getConverters().put(name, new StringConverter()); } }
java
public void profileAttribute(final String name, String tag, final AttributeConverter<? extends Object> converter) { profileAttributes.put(name, tag); if (converter != null) { getConverters().put(name, converter); } else { getConverters().put(name, new StringConverter()); } }
[ "public", "void", "profileAttribute", "(", "final", "String", "name", ",", "String", "tag", ",", "final", "AttributeConverter", "<", "?", "extends", "Object", ">", "converter", ")", "{", "profileAttributes", ".", "put", "(", "name", ",", "tag", ")", ";", "if", "(", "converter", "!=", "null", ")", "{", "getConverters", "(", ")", ".", "put", "(", "name", ",", "converter", ")", ";", "}", "else", "{", "getConverters", "(", ")", ".", "put", "(", "name", ",", "new", "StringConverter", "(", ")", ")", ";", "}", "}" ]
Add an attribute as a primary one and its converter. @param name name of the attribute @param tag json reference @param converter converter
[ "Add", "an", "attribute", "as", "a", "primary", "one", "and", "its", "converter", "." ]
train
https://github.com/pac4j/pac4j/blob/d9cd029f8783792b31dd48bf1e32f80628f2c4a3/pac4j-oauth/src/main/java/org/pac4j/oauth/profile/generic/GenericOAuth20ProfileDefinition.java#L105-L112
qatools/properties
src/main/java/ru/qatools/properties/utils/PropsReplacer.java
PropsReplacer.replaceProps
private String replaceProps(String pattern, String path, Properties properties) { Matcher matcher = Pattern.compile(pattern).matcher(path); String replaced = path; while (matcher.find()) { replaced = replaced.replace(matcher.group(0), properties.getProperty(matcher.group(1), "")); } return replaced; }
java
private String replaceProps(String pattern, String path, Properties properties) { Matcher matcher = Pattern.compile(pattern).matcher(path); String replaced = path; while (matcher.find()) { replaced = replaced.replace(matcher.group(0), properties.getProperty(matcher.group(1), "")); } return replaced; }
[ "private", "String", "replaceProps", "(", "String", "pattern", ",", "String", "path", ",", "Properties", "properties", ")", "{", "Matcher", "matcher", "=", "Pattern", ".", "compile", "(", "pattern", ")", ".", "matcher", "(", "path", ")", ";", "String", "replaced", "=", "path", ";", "while", "(", "matcher", ".", "find", "(", ")", ")", "{", "replaced", "=", "replaced", ".", "replace", "(", "matcher", ".", "group", "(", "0", ")", ",", "properties", ".", "getProperty", "(", "matcher", ".", "group", "(", "1", ")", ",", "\"\"", ")", ")", ";", "}", "return", "replaced", ";", "}" ]
Replace properties in given path using pattern @param pattern - pattern to replace. First group should contains property name @param path - given path to replace in @param properties - list of properties using to replace @return path with replaced properties
[ "Replace", "properties", "in", "given", "path", "using", "pattern" ]
train
https://github.com/qatools/properties/blob/ae50b460a6bb4fcb21afe888b2e86a7613cd2115/src/main/java/ru/qatools/properties/utils/PropsReplacer.java#L45-L52
lessthanoptimal/BoofCV
main/boofcv-feature/src/main/java/boofcv/alg/shapes/polyline/splitmerge/PolylineSplitMerge.java
PolylineSplitMerge.computeSideError
double computeSideError(List<Point2D_I32> contour , int indexA , int indexB ) { assignLine(contour, indexA, indexB, line); // don't sample the end points because the error will be zero by definition int numSamples; double sumOfDistances = 0; int length; if( indexB >= indexA ) { length = indexB-indexA-1; numSamples = Math.min(length,maxNumberOfSideSamples); for (int i = 0; i < numSamples; i++) { int index = indexA+1+length*i/numSamples; Point2D_I32 p = contour.get(index); sumOfDistances += Distance2D_F64.distanceSq(line,p.x,p.y); } sumOfDistances /= numSamples; } else { length = contour.size()-indexA-1 + indexB; numSamples = Math.min(length,maxNumberOfSideSamples); for (int i = 0; i < numSamples; i++) { int where = length*i/numSamples; int index = (indexA+1+where)%contour.size(); Point2D_I32 p = contour.get(index); sumOfDistances += Distance2D_F64.distanceSq(line,p.x,p.y); } sumOfDistances /= numSamples; } // handle divide by zero error if( numSamples > 0 ) return sumOfDistances; else return 0; }
java
double computeSideError(List<Point2D_I32> contour , int indexA , int indexB ) { assignLine(contour, indexA, indexB, line); // don't sample the end points because the error will be zero by definition int numSamples; double sumOfDistances = 0; int length; if( indexB >= indexA ) { length = indexB-indexA-1; numSamples = Math.min(length,maxNumberOfSideSamples); for (int i = 0; i < numSamples; i++) { int index = indexA+1+length*i/numSamples; Point2D_I32 p = contour.get(index); sumOfDistances += Distance2D_F64.distanceSq(line,p.x,p.y); } sumOfDistances /= numSamples; } else { length = contour.size()-indexA-1 + indexB; numSamples = Math.min(length,maxNumberOfSideSamples); for (int i = 0; i < numSamples; i++) { int where = length*i/numSamples; int index = (indexA+1+where)%contour.size(); Point2D_I32 p = contour.get(index); sumOfDistances += Distance2D_F64.distanceSq(line,p.x,p.y); } sumOfDistances /= numSamples; } // handle divide by zero error if( numSamples > 0 ) return sumOfDistances; else return 0; }
[ "double", "computeSideError", "(", "List", "<", "Point2D_I32", ">", "contour", ",", "int", "indexA", ",", "int", "indexB", ")", "{", "assignLine", "(", "contour", ",", "indexA", ",", "indexB", ",", "line", ")", ";", "// don't sample the end points because the error will be zero by definition", "int", "numSamples", ";", "double", "sumOfDistances", "=", "0", ";", "int", "length", ";", "if", "(", "indexB", ">=", "indexA", ")", "{", "length", "=", "indexB", "-", "indexA", "-", "1", ";", "numSamples", "=", "Math", ".", "min", "(", "length", ",", "maxNumberOfSideSamples", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "numSamples", ";", "i", "++", ")", "{", "int", "index", "=", "indexA", "+", "1", "+", "length", "*", "i", "/", "numSamples", ";", "Point2D_I32", "p", "=", "contour", ".", "get", "(", "index", ")", ";", "sumOfDistances", "+=", "Distance2D_F64", ".", "distanceSq", "(", "line", ",", "p", ".", "x", ",", "p", ".", "y", ")", ";", "}", "sumOfDistances", "/=", "numSamples", ";", "}", "else", "{", "length", "=", "contour", ".", "size", "(", ")", "-", "indexA", "-", "1", "+", "indexB", ";", "numSamples", "=", "Math", ".", "min", "(", "length", ",", "maxNumberOfSideSamples", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "numSamples", ";", "i", "++", ")", "{", "int", "where", "=", "length", "*", "i", "/", "numSamples", ";", "int", "index", "=", "(", "indexA", "+", "1", "+", "where", ")", "%", "contour", ".", "size", "(", ")", ";", "Point2D_I32", "p", "=", "contour", ".", "get", "(", "index", ")", ";", "sumOfDistances", "+=", "Distance2D_F64", ".", "distanceSq", "(", "line", ",", "p", ".", "x", ",", "p", ".", "y", ")", ";", "}", "sumOfDistances", "/=", "numSamples", ";", "}", "// handle divide by zero error", "if", "(", "numSamples", ">", "0", ")", "return", "sumOfDistances", ";", "else", "return", "0", ";", "}" ]
Scores a side based on the sum of Euclidean distance squared of each point along the line. Euclidean squared is used because its fast to compute @param indexA first index. Inclusive @param indexB last index. Exclusive
[ "Scores", "a", "side", "based", "on", "the", "sum", "of", "Euclidean", "distance", "squared", "of", "each", "point", "along", "the", "line", ".", "Euclidean", "squared", "is", "used", "because", "its", "fast", "to", "compute" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/shapes/polyline/splitmerge/PolylineSplitMerge.java#L625-L658
jOOQ/jOOL
jOOL-java-8/src/main/java/org/jooq/lambda/Unchecked.java
Unchecked.toIntFunction
public static <T> ToIntFunction<T> toIntFunction(CheckedToIntFunction<T> function) { return toIntFunction(function, THROWABLE_TO_RUNTIME_EXCEPTION); }
java
public static <T> ToIntFunction<T> toIntFunction(CheckedToIntFunction<T> function) { return toIntFunction(function, THROWABLE_TO_RUNTIME_EXCEPTION); }
[ "public", "static", "<", "T", ">", "ToIntFunction", "<", "T", ">", "toIntFunction", "(", "CheckedToIntFunction", "<", "T", ">", "function", ")", "{", "return", "toIntFunction", "(", "function", ",", "THROWABLE_TO_RUNTIME_EXCEPTION", ")", ";", "}" ]
Wrap a {@link CheckedToIntFunction} in a {@link ToIntFunction}. <p> Example: <code><pre> map.computeIfAbsent("key", Unchecked.toIntFunction(k -> { if (k.length() > 10) throw new Exception("Only short strings allowed"); return 42; })); </pre></code>
[ "Wrap", "a", "{", "@link", "CheckedToIntFunction", "}", "in", "a", "{", "@link", "ToIntFunction", "}", ".", "<p", ">", "Example", ":", "<code", ">", "<pre", ">", "map", ".", "computeIfAbsent", "(", "key", "Unchecked", ".", "toIntFunction", "(", "k", "-", ">", "{", "if", "(", "k", ".", "length", "()", ">", "10", ")", "throw", "new", "Exception", "(", "Only", "short", "strings", "allowed", ")", ";" ]
train
https://github.com/jOOQ/jOOL/blob/889d87c85ca57bafd4eddd78e0f7ae2804d2ee86/jOOL-java-8/src/main/java/org/jooq/lambda/Unchecked.java#L901-L903
SonarSource/sonarqube
sonar-plugin-api/src/main/java/org/sonar/api/scan/filesystem/PathResolver.java
PathResolver.relativePath
@CheckForNull public String relativePath(Path dir, Path file) { Path baseDir = dir.normalize(); Path path = file.normalize(); if (!path.startsWith(baseDir)) { return null; } try { Path relativized = baseDir.relativize(path); return FilenameUtils.separatorsToUnix(relativized.toString()); } catch (IllegalArgumentException e) { return null; } }
java
@CheckForNull public String relativePath(Path dir, Path file) { Path baseDir = dir.normalize(); Path path = file.normalize(); if (!path.startsWith(baseDir)) { return null; } try { Path relativized = baseDir.relativize(path); return FilenameUtils.separatorsToUnix(relativized.toString()); } catch (IllegalArgumentException e) { return null; } }
[ "@", "CheckForNull", "public", "String", "relativePath", "(", "Path", "dir", ",", "Path", "file", ")", "{", "Path", "baseDir", "=", "dir", ".", "normalize", "(", ")", ";", "Path", "path", "=", "file", ".", "normalize", "(", ")", ";", "if", "(", "!", "path", ".", "startsWith", "(", "baseDir", ")", ")", "{", "return", "null", ";", "}", "try", "{", "Path", "relativized", "=", "baseDir", ".", "relativize", "(", "path", ")", ";", "return", "FilenameUtils", ".", "separatorsToUnix", "(", "relativized", ".", "toString", "(", ")", ")", ";", "}", "catch", "(", "IllegalArgumentException", "e", ")", "{", "return", "null", ";", "}", "}" ]
Similar to {@link Path#relativize(Path)} except that: <ul> <li>null is returned if file is not a child of dir <li>the resulting path is converted to use Unix separators </ul> @since 6.0
[ "Similar", "to", "{" ]
train
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/sonar-plugin-api/src/main/java/org/sonar/api/scan/filesystem/PathResolver.java#L82-L95
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/utils/coverage/CoverageUtilities.java
CoverageUtilities.buildCoverage
public static GridCoverage2D buildCoverage( String name, double[][] dataMatrix, HashMap<String, Double> envelopeParams, CoordinateReferenceSystem crs, boolean matrixIsRowCol ) { WritableRaster writableRaster = createWritableRasterFromMatrix(dataMatrix, matrixIsRowCol); return buildCoverage(name, writableRaster, envelopeParams, crs); }
java
public static GridCoverage2D buildCoverage( String name, double[][] dataMatrix, HashMap<String, Double> envelopeParams, CoordinateReferenceSystem crs, boolean matrixIsRowCol ) { WritableRaster writableRaster = createWritableRasterFromMatrix(dataMatrix, matrixIsRowCol); return buildCoverage(name, writableRaster, envelopeParams, crs); }
[ "public", "static", "GridCoverage2D", "buildCoverage", "(", "String", "name", ",", "double", "[", "]", "[", "]", "dataMatrix", ",", "HashMap", "<", "String", ",", "Double", ">", "envelopeParams", ",", "CoordinateReferenceSystem", "crs", ",", "boolean", "matrixIsRowCol", ")", "{", "WritableRaster", "writableRaster", "=", "createWritableRasterFromMatrix", "(", "dataMatrix", ",", "matrixIsRowCol", ")", ";", "return", "buildCoverage", "(", "name", ",", "writableRaster", ",", "envelopeParams", ",", "crs", ")", ";", "}" ]
Creates a {@link GridCoverage2D coverage} from a double[][] matrix and the necessary geographic Information. @param name the name of the coverage. @param dataMatrix the matrix containing the data. @param envelopeParams the map of boundary parameters. @param crs the {@link CoordinateReferenceSystem}. @param matrixIsRowCol a flag to tell if the matrix has rowCol or colRow order. @return the {@link GridCoverage2D coverage}.
[ "Creates", "a", "{", "@link", "GridCoverage2D", "coverage", "}", "from", "a", "double", "[]", "[]", "matrix", "and", "the", "necessary", "geographic", "Information", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/coverage/CoverageUtilities.java#L825-L829
lightblueseas/net-extensions
src/main/java/de/alpharogroup/net/socket/SocketExtensions.java
SocketExtensions.readObject
public static Object readObject(final String serverName, final int port) throws IOException, ClassNotFoundException { final InetAddress inetAddress = InetAddress.getByName(serverName); return readObject(new Socket(inetAddress, port)); }
java
public static Object readObject(final String serverName, final int port) throws IOException, ClassNotFoundException { final InetAddress inetAddress = InetAddress.getByName(serverName); return readObject(new Socket(inetAddress, port)); }
[ "public", "static", "Object", "readObject", "(", "final", "String", "serverName", ",", "final", "int", "port", ")", "throws", "IOException", ",", "ClassNotFoundException", "{", "final", "InetAddress", "inetAddress", "=", "InetAddress", ".", "getByName", "(", "serverName", ")", ";", "return", "readObject", "(", "new", "Socket", "(", "inetAddress", ",", "port", ")", ")", ";", "}" ]
Reads an object from the given socket InetAddress. @param serverName The Name from the address to read. @param port The port to read. @return the object @throws IOException Signals that an I/O exception has occurred. @throws ClassNotFoundException the class not found exception
[ "Reads", "an", "object", "from", "the", "given", "socket", "InetAddress", "." ]
train
https://github.com/lightblueseas/net-extensions/blob/771757a93fa9ad13ce0fe061c158e5cba43344cb/src/main/java/de/alpharogroup/net/socket/SocketExtensions.java#L332-L337
ologolo/streamline-engine
src/org/daisy/streamline/engine/TaskRunner.java
TaskRunner.runTasks
public RunnerResults runTasks(FileSet input, BaseFolder output, String manifestFileName, List<InternalTask> tasks) throws IOException, TaskSystemException { Progress progress = new Progress(); logger.info(name + " started on " + progress.getStart()); int i = 0; NumberFormat nf = NumberFormat.getPercentInstance(); TempFileWriter tempWriter =writeTempFiles ? Optional.ofNullable(tempFileWriter).orElseGet(()->new DefaultTempFileWriter.Builder().build()) : null; RunnerResults.Builder builder = new RunnerResults.Builder(); // I use this to pass the exception out of the lambda Variable<IOException> ex = new Variable<>(); Consumer<FileSet> outputConsumer = current->{ try { builder.fileSet(DefaultFileSet.copy(current, output, manifestFileName)); } catch (IOException e) { ex.setValue(e); } }; try (TaskRunnerCore2 itr = new TaskRunnerCore2(input, outputConsumer, tempWriter)) { for (InternalTask task : tasks) { builder.addResults(itr.runTask(task)); i++; ProgressEvent event = progress.updateProgress(i/(double)tasks.size()); logger.info(nf.format(event.getProgress()) + " done. ETC " + event.getETC()); progressListeners.forEach(v->v.accept(event)); } } catch (IOException | TaskSystemException | RuntimeException e) { //This is called after the resource (fj) is closed. //Since the temp file handler is closed the current state will be written to output. However, we do not want it. PathTools.deleteRecursive(output.getPath()); throw e; } if (ex.getValue()!=null) { throw ex.getValue(); } if (!keepTempFilesOnSuccess && tempWriter!=null) { // Process were successful, delete temp files tempWriter.deleteTempFiles(); } logger.info(name + " finished in " + Math.round(progress.timeSinceStart()/100d)/10d + " s"); return builder.build(); }
java
public RunnerResults runTasks(FileSet input, BaseFolder output, String manifestFileName, List<InternalTask> tasks) throws IOException, TaskSystemException { Progress progress = new Progress(); logger.info(name + " started on " + progress.getStart()); int i = 0; NumberFormat nf = NumberFormat.getPercentInstance(); TempFileWriter tempWriter =writeTempFiles ? Optional.ofNullable(tempFileWriter).orElseGet(()->new DefaultTempFileWriter.Builder().build()) : null; RunnerResults.Builder builder = new RunnerResults.Builder(); // I use this to pass the exception out of the lambda Variable<IOException> ex = new Variable<>(); Consumer<FileSet> outputConsumer = current->{ try { builder.fileSet(DefaultFileSet.copy(current, output, manifestFileName)); } catch (IOException e) { ex.setValue(e); } }; try (TaskRunnerCore2 itr = new TaskRunnerCore2(input, outputConsumer, tempWriter)) { for (InternalTask task : tasks) { builder.addResults(itr.runTask(task)); i++; ProgressEvent event = progress.updateProgress(i/(double)tasks.size()); logger.info(nf.format(event.getProgress()) + " done. ETC " + event.getETC()); progressListeners.forEach(v->v.accept(event)); } } catch (IOException | TaskSystemException | RuntimeException e) { //This is called after the resource (fj) is closed. //Since the temp file handler is closed the current state will be written to output. However, we do not want it. PathTools.deleteRecursive(output.getPath()); throw e; } if (ex.getValue()!=null) { throw ex.getValue(); } if (!keepTempFilesOnSuccess && tempWriter!=null) { // Process were successful, delete temp files tempWriter.deleteTempFiles(); } logger.info(name + " finished in " + Math.round(progress.timeSinceStart()/100d)/10d + " s"); return builder.build(); }
[ "public", "RunnerResults", "runTasks", "(", "FileSet", "input", ",", "BaseFolder", "output", ",", "String", "manifestFileName", ",", "List", "<", "InternalTask", ">", "tasks", ")", "throws", "IOException", ",", "TaskSystemException", "{", "Progress", "progress", "=", "new", "Progress", "(", ")", ";", "logger", ".", "info", "(", "name", "+", "\" started on \"", "+", "progress", ".", "getStart", "(", ")", ")", ";", "int", "i", "=", "0", ";", "NumberFormat", "nf", "=", "NumberFormat", ".", "getPercentInstance", "(", ")", ";", "TempFileWriter", "tempWriter", "=", "writeTempFiles", "?", "Optional", ".", "ofNullable", "(", "tempFileWriter", ")", ".", "orElseGet", "(", "(", ")", "->", "new", "DefaultTempFileWriter", ".", "Builder", "(", ")", ".", "build", "(", ")", ")", ":", "null", ";", "RunnerResults", ".", "Builder", "builder", "=", "new", "RunnerResults", ".", "Builder", "(", ")", ";", "// I use this to pass the exception out of the lambda", "Variable", "<", "IOException", ">", "ex", "=", "new", "Variable", "<>", "(", ")", ";", "Consumer", "<", "FileSet", ">", "outputConsumer", "=", "current", "->", "{", "try", "{", "builder", ".", "fileSet", "(", "DefaultFileSet", ".", "copy", "(", "current", ",", "output", ",", "manifestFileName", ")", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "ex", ".", "setValue", "(", "e", ")", ";", "}", "}", ";", "try", "(", "TaskRunnerCore2", "itr", "=", "new", "TaskRunnerCore2", "(", "input", ",", "outputConsumer", ",", "tempWriter", ")", ")", "{", "for", "(", "InternalTask", "task", ":", "tasks", ")", "{", "builder", ".", "addResults", "(", "itr", ".", "runTask", "(", "task", ")", ")", ";", "i", "++", ";", "ProgressEvent", "event", "=", "progress", ".", "updateProgress", "(", "i", "/", "(", "double", ")", "tasks", ".", "size", "(", ")", ")", ";", "logger", ".", "info", "(", "nf", ".", "format", "(", "event", ".", "getProgress", "(", ")", ")", "+", "\" done. ETC \"", "+", "event", ".", "getETC", "(", ")", ")", ";", "progressListeners", ".", "forEach", "(", "v", "->", "v", ".", "accept", "(", "event", ")", ")", ";", "}", "}", "catch", "(", "IOException", "|", "TaskSystemException", "|", "RuntimeException", "e", ")", "{", "//This is called after the resource (fj) is closed.", "//Since the temp file handler is closed the current state will be written to output. However, we do not want it.", "PathTools", ".", "deleteRecursive", "(", "output", ".", "getPath", "(", ")", ")", ";", "throw", "e", ";", "}", "if", "(", "ex", ".", "getValue", "(", ")", "!=", "null", ")", "{", "throw", "ex", ".", "getValue", "(", ")", ";", "}", "if", "(", "!", "keepTempFilesOnSuccess", "&&", "tempWriter", "!=", "null", ")", "{", "// Process were successful, delete temp files", "tempWriter", ".", "deleteTempFiles", "(", ")", ";", "}", "logger", ".", "info", "(", "name", "+", "\" finished in \"", "+", "Math", ".", "round", "(", "progress", ".", "timeSinceStart", "(", ")", "/", "100d", ")", "/", "10d", "+", "\" s\"", ")", ";", "return", "builder", ".", "build", "(", ")", ";", "}" ]
Runs a list of tasks starting from the input file as input to the first task, the following tasks use the preceding result as input. The final result is written to the output. @param input the input file @param output the output file @param manifestFileName the file name of the manifest file @param tasks the list of tasks @return returns a list of runner results @throws IOException if there is an I/O error @throws TaskSystemException if there is a problem with the task system
[ "Runs", "a", "list", "of", "tasks", "starting", "from", "the", "input", "file", "as", "input", "to", "the", "first", "task", "the", "following", "tasks", "use", "the", "preceding", "result", "as", "input", ".", "The", "final", "result", "is", "written", "to", "the", "output", "." ]
train
https://github.com/ologolo/streamline-engine/blob/04b7adc85d84d91dc5f0eaaa401d2738f9401b17/src/org/daisy/streamline/engine/TaskRunner.java#L204-L243
craterdog/java-security-framework
java-certificate-management-api/src/main/java/craterdog/security/CertificateManager.java
CertificateManager.saveKeyStore
public final void saveKeyStore(OutputStream output, KeyStore keyStore, char[] password) throws IOException { logger.entry(); try { keyStore.store(output, password); } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException e) { RuntimeException exception = new RuntimeException("An unexpected exception occurred while attempting to save a keystore.", e); logger.error(exception.toString()); throw exception; } logger.exit(); }
java
public final void saveKeyStore(OutputStream output, KeyStore keyStore, char[] password) throws IOException { logger.entry(); try { keyStore.store(output, password); } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException e) { RuntimeException exception = new RuntimeException("An unexpected exception occurred while attempting to save a keystore.", e); logger.error(exception.toString()); throw exception; } logger.exit(); }
[ "public", "final", "void", "saveKeyStore", "(", "OutputStream", "output", ",", "KeyStore", "keyStore", ",", "char", "[", "]", "password", ")", "throws", "IOException", "{", "logger", ".", "entry", "(", ")", ";", "try", "{", "keyStore", ".", "store", "(", "output", ",", "password", ")", ";", "}", "catch", "(", "KeyStoreException", "|", "NoSuchAlgorithmException", "|", "CertificateException", "e", ")", "{", "RuntimeException", "exception", "=", "new", "RuntimeException", "(", "\"An unexpected exception occurred while attempting to save a keystore.\"", ",", "e", ")", ";", "logger", ".", "error", "(", "exception", ".", "toString", "(", ")", ")", ";", "throw", "exception", ";", "}", "logger", ".", "exit", "(", ")", ";", "}" ]
This method saves a PKCS12 format key store out to an output stream. @param output The output stream to be written to. @param keyStore The PKCS12 format key store. @param password The password that should be used to encrypt the file. @throws java.io.IOException Unable to save the key store to the specified output stream.
[ "This", "method", "saves", "a", "PKCS12", "format", "key", "store", "out", "to", "an", "output", "stream", "." ]
train
https://github.com/craterdog/java-security-framework/blob/a5634c19812d473b608bc11060f5cbb4b4b0b5da/java-certificate-management-api/src/main/java/craterdog/security/CertificateManager.java#L44-L54
exoplatform/jcr
exo.jcr.component.webdav/src/main/java/org/exoplatform/services/jcr/webdav/command/PropPatchCommand.java
PropPatchCommand.propPatch
public Response propPatch(Session session, String path, HierarchicalProperty body, List<String> tokens, String baseURI) { try { lockHolder.checkLock(session, path, tokens); Node node = (Node)session.getItem(path); WebDavNamespaceContext nsContext = new WebDavNamespaceContext(session); URI uri = new URI(TextUtil.escape(baseURI + node.getPath(), '%', true)); List<HierarchicalProperty> setList = Collections.emptyList(); if (body.getChild(new QName("DAV:", "set")) != null) { setList = setList(body); } List<HierarchicalProperty> removeList = Collections.emptyList(); if (body.getChild(new QName("DAV:", "remove")) != null) { removeList = removeList(body); } PropPatchResponseEntity entity = new PropPatchResponseEntity(nsContext, node, uri, setList, removeList); return Response.status(HTTPStatus.MULTISTATUS).entity(entity).type(MediaType.TEXT_XML).build(); } catch (PathNotFoundException exc) { return Response.status(HTTPStatus.NOT_FOUND).entity(exc.getMessage()).build(); } catch (LockException exc) { return Response.status(HTTPStatus.LOCKED).entity(exc.getMessage()).build(); } catch (Exception exc) { log.error(exc.getMessage(), exc); return Response.serverError().entity(exc.getMessage()).build(); } }
java
public Response propPatch(Session session, String path, HierarchicalProperty body, List<String> tokens, String baseURI) { try { lockHolder.checkLock(session, path, tokens); Node node = (Node)session.getItem(path); WebDavNamespaceContext nsContext = new WebDavNamespaceContext(session); URI uri = new URI(TextUtil.escape(baseURI + node.getPath(), '%', true)); List<HierarchicalProperty> setList = Collections.emptyList(); if (body.getChild(new QName("DAV:", "set")) != null) { setList = setList(body); } List<HierarchicalProperty> removeList = Collections.emptyList(); if (body.getChild(new QName("DAV:", "remove")) != null) { removeList = removeList(body); } PropPatchResponseEntity entity = new PropPatchResponseEntity(nsContext, node, uri, setList, removeList); return Response.status(HTTPStatus.MULTISTATUS).entity(entity).type(MediaType.TEXT_XML).build(); } catch (PathNotFoundException exc) { return Response.status(HTTPStatus.NOT_FOUND).entity(exc.getMessage()).build(); } catch (LockException exc) { return Response.status(HTTPStatus.LOCKED).entity(exc.getMessage()).build(); } catch (Exception exc) { log.error(exc.getMessage(), exc); return Response.serverError().entity(exc.getMessage()).build(); } }
[ "public", "Response", "propPatch", "(", "Session", "session", ",", "String", "path", ",", "HierarchicalProperty", "body", ",", "List", "<", "String", ">", "tokens", ",", "String", "baseURI", ")", "{", "try", "{", "lockHolder", ".", "checkLock", "(", "session", ",", "path", ",", "tokens", ")", ";", "Node", "node", "=", "(", "Node", ")", "session", ".", "getItem", "(", "path", ")", ";", "WebDavNamespaceContext", "nsContext", "=", "new", "WebDavNamespaceContext", "(", "session", ")", ";", "URI", "uri", "=", "new", "URI", "(", "TextUtil", ".", "escape", "(", "baseURI", "+", "node", ".", "getPath", "(", ")", ",", "'", "'", ",", "true", ")", ")", ";", "List", "<", "HierarchicalProperty", ">", "setList", "=", "Collections", ".", "emptyList", "(", ")", ";", "if", "(", "body", ".", "getChild", "(", "new", "QName", "(", "\"DAV:\"", ",", "\"set\"", ")", ")", "!=", "null", ")", "{", "setList", "=", "setList", "(", "body", ")", ";", "}", "List", "<", "HierarchicalProperty", ">", "removeList", "=", "Collections", ".", "emptyList", "(", ")", ";", "if", "(", "body", ".", "getChild", "(", "new", "QName", "(", "\"DAV:\"", ",", "\"remove\"", ")", ")", "!=", "null", ")", "{", "removeList", "=", "removeList", "(", "body", ")", ";", "}", "PropPatchResponseEntity", "entity", "=", "new", "PropPatchResponseEntity", "(", "nsContext", ",", "node", ",", "uri", ",", "setList", ",", "removeList", ")", ";", "return", "Response", ".", "status", "(", "HTTPStatus", ".", "MULTISTATUS", ")", ".", "entity", "(", "entity", ")", ".", "type", "(", "MediaType", ".", "TEXT_XML", ")", ".", "build", "(", ")", ";", "}", "catch", "(", "PathNotFoundException", "exc", ")", "{", "return", "Response", ".", "status", "(", "HTTPStatus", ".", "NOT_FOUND", ")", ".", "entity", "(", "exc", ".", "getMessage", "(", ")", ")", ".", "build", "(", ")", ";", "}", "catch", "(", "LockException", "exc", ")", "{", "return", "Response", ".", "status", "(", "HTTPStatus", ".", "LOCKED", ")", ".", "entity", "(", "exc", ".", "getMessage", "(", ")", ")", ".", "build", "(", ")", ";", "}", "catch", "(", "Exception", "exc", ")", "{", "log", ".", "error", "(", "exc", ".", "getMessage", "(", ")", ",", "exc", ")", ";", "return", "Response", ".", "serverError", "(", ")", ".", "entity", "(", "exc", ".", "getMessage", "(", ")", ")", ".", "build", "(", ")", ";", "}", "}" ]
Webdav Proppatch method method implementation. @param session current session @param path resource path @param body request body @param tokens tokens @param baseURI base uri @return the instance of javax.ws.rs.core.Response
[ "Webdav", "Proppatch", "method", "method", "implementation", "." ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.webdav/src/main/java/org/exoplatform/services/jcr/webdav/command/PropPatchCommand.java#L82-L126
BorderTech/wcomponents
wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/WButtonExample.java
WButtonExample.addDefaultSubmitButtonExample
private void addDefaultSubmitButtonExample() { add(new WHeading(HeadingLevel.H3, "Default submit button")); add(new ExplanatoryText( "This example shows how to use an image as the only content of a WButton. " + "In addition this text field submits the entire screen using the image button to the right of the field.")); // We use WFieldLayout to lay out a label:input pair. In this case the input is a //compound control of a WTextField and a WButton. WFieldLayout imageButtonFieldLayout = new WFieldLayout(); imageButtonFieldLayout.setLabelWidth(25); add(imageButtonFieldLayout); // the text field and the button both need to be defined explicitly to be able to add them into a wrapper WTextField textFld = new WTextField(); //and finally we get to the actual button WButton button = new WButton("Flag this record for follow-up"); button.setImage("/image/flag.png"); button.getImageHolder().setCacheKey("eg-button-flag"); button.setActionObject(button); button.setAction(new ExampleButtonAction()); //we can set the image button to be the default submit button for the text field. textFld.setDefaultSubmitButton(button); //There are many way of putting multiple controls in to a WField's input. //We are using a WContainer is the one which is lowest impact in the UI. WContainer imageButtonFieldContainer = new WContainer(); imageButtonFieldContainer.add(textFld); //Use a WText to push the button off of the text field by an appropriate (user-agent determined) amount. imageButtonFieldContainer.add(new WText("\u2002")); //an en space is half an em. a none-breaking space \u00a0 could also be used but will have no effect on inter-node wrapping imageButtonFieldContainer.add(button); //Finally add the input wrapper to the WFieldLayout imageButtonFieldLayout.addField("Enter record ID", imageButtonFieldContainer); }
java
private void addDefaultSubmitButtonExample() { add(new WHeading(HeadingLevel.H3, "Default submit button")); add(new ExplanatoryText( "This example shows how to use an image as the only content of a WButton. " + "In addition this text field submits the entire screen using the image button to the right of the field.")); // We use WFieldLayout to lay out a label:input pair. In this case the input is a //compound control of a WTextField and a WButton. WFieldLayout imageButtonFieldLayout = new WFieldLayout(); imageButtonFieldLayout.setLabelWidth(25); add(imageButtonFieldLayout); // the text field and the button both need to be defined explicitly to be able to add them into a wrapper WTextField textFld = new WTextField(); //and finally we get to the actual button WButton button = new WButton("Flag this record for follow-up"); button.setImage("/image/flag.png"); button.getImageHolder().setCacheKey("eg-button-flag"); button.setActionObject(button); button.setAction(new ExampleButtonAction()); //we can set the image button to be the default submit button for the text field. textFld.setDefaultSubmitButton(button); //There are many way of putting multiple controls in to a WField's input. //We are using a WContainer is the one which is lowest impact in the UI. WContainer imageButtonFieldContainer = new WContainer(); imageButtonFieldContainer.add(textFld); //Use a WText to push the button off of the text field by an appropriate (user-agent determined) amount. imageButtonFieldContainer.add(new WText("\u2002")); //an en space is half an em. a none-breaking space \u00a0 could also be used but will have no effect on inter-node wrapping imageButtonFieldContainer.add(button); //Finally add the input wrapper to the WFieldLayout imageButtonFieldLayout.addField("Enter record ID", imageButtonFieldContainer); }
[ "private", "void", "addDefaultSubmitButtonExample", "(", ")", "{", "add", "(", "new", "WHeading", "(", "HeadingLevel", ".", "H3", ",", "\"Default submit button\"", ")", ")", ";", "add", "(", "new", "ExplanatoryText", "(", "\"This example shows how to use an image as the only content of a WButton. \"", "+", "\"In addition this text field submits the entire screen using the image button to the right of the field.\"", ")", ")", ";", "// We use WFieldLayout to lay out a label:input pair. In this case the input is a", "//compound control of a WTextField and a WButton.", "WFieldLayout", "imageButtonFieldLayout", "=", "new", "WFieldLayout", "(", ")", ";", "imageButtonFieldLayout", ".", "setLabelWidth", "(", "25", ")", ";", "add", "(", "imageButtonFieldLayout", ")", ";", "// the text field and the button both need to be defined explicitly to be able to add them into a wrapper", "WTextField", "textFld", "=", "new", "WTextField", "(", ")", ";", "//and finally we get to the actual button", "WButton", "button", "=", "new", "WButton", "(", "\"Flag this record for follow-up\"", ")", ";", "button", ".", "setImage", "(", "\"/image/flag.png\"", ")", ";", "button", ".", "getImageHolder", "(", ")", ".", "setCacheKey", "(", "\"eg-button-flag\"", ")", ";", "button", ".", "setActionObject", "(", "button", ")", ";", "button", ".", "setAction", "(", "new", "ExampleButtonAction", "(", ")", ")", ";", "//we can set the image button to be the default submit button for the text field.", "textFld", ".", "setDefaultSubmitButton", "(", "button", ")", ";", "//There are many way of putting multiple controls in to a WField's input.", "//We are using a WContainer is the one which is lowest impact in the UI.", "WContainer", "imageButtonFieldContainer", "=", "new", "WContainer", "(", ")", ";", "imageButtonFieldContainer", ".", "add", "(", "textFld", ")", ";", "//Use a WText to push the button off of the text field by an appropriate (user-agent determined) amount.", "imageButtonFieldContainer", ".", "add", "(", "new", "WText", "(", "\"\\u2002\"", ")", ")", ";", "//an en space is half an em. a none-breaking space \\u00a0 could also be used but will have no effect on inter-node wrapping", "imageButtonFieldContainer", ".", "add", "(", "button", ")", ";", "//Finally add the input wrapper to the WFieldLayout", "imageButtonFieldLayout", ".", "addField", "(", "\"Enter record ID\"", ",", "imageButtonFieldContainer", ")", ";", "}" ]
Examples showing how to set a WButton as the default submit button for an input control.
[ "Examples", "showing", "how", "to", "set", "a", "WButton", "as", "the", "default", "submit", "button", "for", "an", "input", "control", "." ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/WButtonExample.java#L280-L311
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.utils/src/com/ibm/ws/sib/utils/ras/FormattedWriter.java
FormattedWriter.taggedValue
public final void taggedValue(String tag, long value) throws IOException { startTag(tag); write(Long.toString(value)); endTag(tag); }
java
public final void taggedValue(String tag, long value) throws IOException { startTag(tag); write(Long.toString(value)); endTag(tag); }
[ "public", "final", "void", "taggedValue", "(", "String", "tag", ",", "long", "value", ")", "throws", "IOException", "{", "startTag", "(", "tag", ")", ";", "write", "(", "Long", ".", "toString", "(", "value", ")", ")", ";", "endTag", "(", "tag", ")", ";", "}" ]
Write out a one-line XML tag with a long datatype, for instance &lttag&gt123456&lt/tag&gt @param tag The name of the tag to be written @param value The data value to be written @throws IOException If an I/O error occurs while attempting to write the characters
[ "Write", "out", "a", "one", "-", "line", "XML", "tag", "with", "a", "long", "datatype", "for", "instance", "&lttag&gt123456&lt", "/", "tag&gt" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.utils/src/com/ibm/ws/sib/utils/ras/FormattedWriter.java#L212-L216
matthewhorridge/owlapi-gwt
owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLDataExactCardinalityImpl_CustomFieldSerializer.java
OWLDataExactCardinalityImpl_CustomFieldSerializer.serializeInstance
@Override public void serializeInstance(SerializationStreamWriter streamWriter, OWLDataExactCardinalityImpl instance) throws SerializationException { serialize(streamWriter, instance); }
java
@Override public void serializeInstance(SerializationStreamWriter streamWriter, OWLDataExactCardinalityImpl instance) throws SerializationException { serialize(streamWriter, instance); }
[ "@", "Override", "public", "void", "serializeInstance", "(", "SerializationStreamWriter", "streamWriter", ",", "OWLDataExactCardinalityImpl", "instance", ")", "throws", "SerializationException", "{", "serialize", "(", "streamWriter", ",", "instance", ")", ";", "}" ]
Serializes the content of the object into the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter}. @param streamWriter the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter} to write the object's content to @param instance the object instance to serialize @throws com.google.gwt.user.client.rpc.SerializationException if the serialization operation is not successful
[ "Serializes", "the", "content", "of", "the", "object", "into", "the", "{", "@link", "com", ".", "google", ".", "gwt", ".", "user", ".", "client", ".", "rpc", ".", "SerializationStreamWriter", "}", "." ]
train
https://github.com/matthewhorridge/owlapi-gwt/blob/7ab975fb6cef3c8947099983551672a3b5d4e2fd/owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLDataExactCardinalityImpl_CustomFieldSerializer.java#L73-L76
calrissian/mango
mango-core/src/main/java/org/calrissian/mango/io/Serializables.java
Serializables.deserialize
public static <T extends Serializable> T deserialize(byte[] bytes) throws IOException, ClassNotFoundException { return deserialize(bytes, false); }
java
public static <T extends Serializable> T deserialize(byte[] bytes) throws IOException, ClassNotFoundException { return deserialize(bytes, false); }
[ "public", "static", "<", "T", "extends", "Serializable", ">", "T", "deserialize", "(", "byte", "[", "]", "bytes", ")", "throws", "IOException", ",", "ClassNotFoundException", "{", "return", "deserialize", "(", "bytes", ",", "false", ")", ";", "}" ]
Utility for returning a Serializable object from a byte array.
[ "Utility", "for", "returning", "a", "Serializable", "object", "from", "a", "byte", "array", "." ]
train
https://github.com/calrissian/mango/blob/a95aa5e77af9aa0e629787228d80806560023452/mango-core/src/main/java/org/calrissian/mango/io/Serializables.java#L58-L60
google/closure-compiler
src/com/google/javascript/jscomp/MustBeReachingVariableDef.java
MustBeReachingVariableDef.getDef
Definition getDef(String name, Node useNode) { checkArgument(getCfg().hasNode(useNode)); GraphNode<Node, Branch> n = getCfg().getNode(useNode); FlowState<MustDef> state = n.getAnnotation(); return state.getIn().reachingDef.get(allVarsInFn.get(name)); }
java
Definition getDef(String name, Node useNode) { checkArgument(getCfg().hasNode(useNode)); GraphNode<Node, Branch> n = getCfg().getNode(useNode); FlowState<MustDef> state = n.getAnnotation(); return state.getIn().reachingDef.get(allVarsInFn.get(name)); }
[ "Definition", "getDef", "(", "String", "name", ",", "Node", "useNode", ")", "{", "checkArgument", "(", "getCfg", "(", ")", ".", "hasNode", "(", "useNode", ")", ")", ";", "GraphNode", "<", "Node", ",", "Branch", ">", "n", "=", "getCfg", "(", ")", ".", "getNode", "(", "useNode", ")", ";", "FlowState", "<", "MustDef", ">", "state", "=", "n", ".", "getAnnotation", "(", ")", ";", "return", "state", ".", "getIn", "(", ")", ".", "reachingDef", ".", "get", "(", "allVarsInFn", ".", "get", "(", "name", ")", ")", ";", "}" ]
Gets the must reaching definition of a given node. @param name name of the variable. It can only be names of local variable that are not function parameters, escaped variables or variables declared in catch. @param useNode the location of the use where the definition reaches.
[ "Gets", "the", "must", "reaching", "definition", "of", "a", "given", "node", "." ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/MustBeReachingVariableDef.java#L469-L474
Cornutum/tcases
tcases-openapi/src/main/java/org/cornutum/tcases/openapi/TcasesOpenApi.java
TcasesOpenApi.getResponseInputModel
public static SystemInputDef getResponseInputModel( OpenAPI api, ModelOptions options) { ResponseInputModeller inputModeller = new ResponseInputModeller( options); return inputModeller.getResponseInputModel( api); }
java
public static SystemInputDef getResponseInputModel( OpenAPI api, ModelOptions options) { ResponseInputModeller inputModeller = new ResponseInputModeller( options); return inputModeller.getResponseInputModel( api); }
[ "public", "static", "SystemInputDef", "getResponseInputModel", "(", "OpenAPI", "api", ",", "ModelOptions", "options", ")", "{", "ResponseInputModeller", "inputModeller", "=", "new", "ResponseInputModeller", "(", "options", ")", ";", "return", "inputModeller", ".", "getResponseInputModel", "(", "api", ")", ";", "}" ]
Returns a {@link SystemInputDef system input definition} for the API responses defined by the given OpenAPI specification. Returns null if the given spec defines no API responses to model.
[ "Returns", "a", "{" ]
train
https://github.com/Cornutum/tcases/blob/21e15cf107fa149620c40f4bda1829c1224fcfb1/tcases-openapi/src/main/java/org/cornutum/tcases/openapi/TcasesOpenApi.java#L60-L64
Mozu/mozu-java
mozu-java-core/src/main/java/com/mozu/api/urls/commerce/catalog/admin/FacetUrl.java
FacetUrl.getFacetCategoryListUrl
public static MozuUrl getFacetCategoryListUrl(Integer categoryId, Boolean includeAvailable, String responseFields, Boolean validate) { UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/admin/facets/category/{categoryId}?includeAvailable={includeAvailable}&validate={validate}&responseFields={responseFields}"); formatter.formatUrl("categoryId", categoryId); formatter.formatUrl("includeAvailable", includeAvailable); formatter.formatUrl("responseFields", responseFields); formatter.formatUrl("validate", validate); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
java
public static MozuUrl getFacetCategoryListUrl(Integer categoryId, Boolean includeAvailable, String responseFields, Boolean validate) { UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/admin/facets/category/{categoryId}?includeAvailable={includeAvailable}&validate={validate}&responseFields={responseFields}"); formatter.formatUrl("categoryId", categoryId); formatter.formatUrl("includeAvailable", includeAvailable); formatter.formatUrl("responseFields", responseFields); formatter.formatUrl("validate", validate); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
[ "public", "static", "MozuUrl", "getFacetCategoryListUrl", "(", "Integer", "categoryId", ",", "Boolean", "includeAvailable", ",", "String", "responseFields", ",", "Boolean", "validate", ")", "{", "UrlFormatter", "formatter", "=", "new", "UrlFormatter", "(", "\"/api/commerce/catalog/admin/facets/category/{categoryId}?includeAvailable={includeAvailable}&validate={validate}&responseFields={responseFields}\"", ")", ";", "formatter", ".", "formatUrl", "(", "\"categoryId\"", ",", "categoryId", ")", ";", "formatter", ".", "formatUrl", "(", "\"includeAvailable\"", ",", "includeAvailable", ")", ";", "formatter", ".", "formatUrl", "(", "\"responseFields\"", ",", "responseFields", ")", ";", "formatter", ".", "formatUrl", "(", "\"validate\"", ",", "validate", ")", ";", "return", "new", "MozuUrl", "(", "formatter", ".", "getResourceUrl", "(", ")", ",", "MozuUrl", ".", "UrlLocation", ".", "TENANT_POD", ")", ";", "}" ]
Get Resource Url for GetFacetCategoryList @param categoryId Unique identifier of the category to modify. @param includeAvailable If true, returns a list of the attributes and categories associated with a product type that have not been defined as a facet for the category. @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss. @param validate Validates that the product category associated with a facet is active. System-supplied and read only. @return String Resource Url
[ "Get", "Resource", "Url", "for", "GetFacetCategoryList" ]
train
https://github.com/Mozu/mozu-java/blob/5beadde73601a859f845e3e2fc1077b39c8bea83/mozu-java-core/src/main/java/com/mozu/api/urls/commerce/catalog/admin/FacetUrl.java#L40-L48
jinahya/bit-io
src/main/java/com/github/jinahya/bit/io/AbstractBitOutput.java
AbstractBitOutput.unsigned8
protected void unsigned8(final int size, int value) throws IOException { requireValidSizeUnsigned8(size); final int required = size - available; if (required > 0) { unsigned8(available, value >> required); unsigned8(required, value); return; } octet <<= size; octet |= (value & ((1 << size) - 1)); available -= size; if (available == 0) { write(octet); count++; octet = 0x00; available = Byte.SIZE; } }
java
protected void unsigned8(final int size, int value) throws IOException { requireValidSizeUnsigned8(size); final int required = size - available; if (required > 0) { unsigned8(available, value >> required); unsigned8(required, value); return; } octet <<= size; octet |= (value & ((1 << size) - 1)); available -= size; if (available == 0) { write(octet); count++; octet = 0x00; available = Byte.SIZE; } }
[ "protected", "void", "unsigned8", "(", "final", "int", "size", ",", "int", "value", ")", "throws", "IOException", "{", "requireValidSizeUnsigned8", "(", "size", ")", ";", "final", "int", "required", "=", "size", "-", "available", ";", "if", "(", "required", ">", "0", ")", "{", "unsigned8", "(", "available", ",", "value", ">>", "required", ")", ";", "unsigned8", "(", "required", ",", "value", ")", ";", "return", ";", "}", "octet", "<<=", "size", ";", "octet", "|=", "(", "value", "&", "(", "(", "1", "<<", "size", ")", "-", "1", ")", ")", ";", "available", "-=", "size", ";", "if", "(", "available", "==", "0", ")", "{", "write", "(", "octet", ")", ";", "count", "++", ";", "octet", "=", "0x00", ";", "available", "=", "Byte", ".", "SIZE", ";", "}", "}" ]
Writes an unsigned value whose size is, in maximum, {@value Byte#SIZE}. @param size the number of lower bits to write; between {@code 1} and {@value Byte#SIZE}, both inclusive. @param value the value to write @throws IOException if an I/O error occurs.
[ "Writes", "an", "unsigned", "value", "whose", "size", "is", "in", "maximum", "{", "@value", "Byte#SIZE", "}", "." ]
train
https://github.com/jinahya/bit-io/blob/f3b49bbec80047c0cc3ea2424def98eb2d08352a/src/main/java/com/github/jinahya/bit/io/AbstractBitOutput.java#L60-L77
liyiorg/weixin-popular
src/main/java/weixin/popular/api/SnsAPI.java
SnsAPI.jscode2session
public static Jscode2sessionResult jscode2session(String appid,String secret,String js_code){ HttpUriRequest httpUriRequest = RequestBuilder.get() .setUri(BASE_URI + "/sns/jscode2session") .addParameter("appid",appid) .addParameter("secret",secret) .addParameter("js_code",js_code) .addParameter("grant_type","authorization_code") .build(); return LocalHttpClient.executeJsonResult(httpUriRequest,Jscode2sessionResult.class); }
java
public static Jscode2sessionResult jscode2session(String appid,String secret,String js_code){ HttpUriRequest httpUriRequest = RequestBuilder.get() .setUri(BASE_URI + "/sns/jscode2session") .addParameter("appid",appid) .addParameter("secret",secret) .addParameter("js_code",js_code) .addParameter("grant_type","authorization_code") .build(); return LocalHttpClient.executeJsonResult(httpUriRequest,Jscode2sessionResult.class); }
[ "public", "static", "Jscode2sessionResult", "jscode2session", "(", "String", "appid", ",", "String", "secret", ",", "String", "js_code", ")", "{", "HttpUriRequest", "httpUriRequest", "=", "RequestBuilder", ".", "get", "(", ")", ".", "setUri", "(", "BASE_URI", "+", "\"/sns/jscode2session\"", ")", ".", "addParameter", "(", "\"appid\"", ",", "appid", ")", ".", "addParameter", "(", "\"secret\"", ",", "secret", ")", ".", "addParameter", "(", "\"js_code\"", ",", "js_code", ")", ".", "addParameter", "(", "\"grant_type\"", ",", "\"authorization_code\"", ")", ".", "build", "(", ")", ";", "return", "LocalHttpClient", ".", "executeJsonResult", "(", "httpUriRequest", ",", "Jscode2sessionResult", ".", "class", ")", ";", "}" ]
code 换取 session_key(微信小程序) @since 2.8.3 @param appid appid @param secret secret @param js_code js_code @return result
[ "code", "换取", "session_key(微信小程序)" ]
train
https://github.com/liyiorg/weixin-popular/blob/c64255292d41463bdb671938feaabf42a335d82c/src/main/java/weixin/popular/api/SnsAPI.java#L235-L244
looly/hutool
hutool-core/src/main/java/cn/hutool/core/util/ObjectUtil.java
ObjectUtil.defaultIfNull
public static <T> T defaultIfNull(final T object, final T defaultValue) { return (null != object) ? object : defaultValue; }
java
public static <T> T defaultIfNull(final T object, final T defaultValue) { return (null != object) ? object : defaultValue; }
[ "public", "static", "<", "T", ">", "T", "defaultIfNull", "(", "final", "T", "object", ",", "final", "T", "defaultValue", ")", "{", "return", "(", "null", "!=", "object", ")", "?", "object", ":", "defaultValue", ";", "}" ]
如果给定对象为{@code null}返回默认值 <pre> ObjectUtil.defaultIfNull(null, null) = null ObjectUtil.defaultIfNull(null, "") = "" ObjectUtil.defaultIfNull(null, "zz") = "zz" ObjectUtil.defaultIfNull("abc", *) = "abc" ObjectUtil.defaultIfNull(Boolean.TRUE, *) = Boolean.TRUE </pre> @param <T> 对象类型 @param object 被检查对象,可能为{@code null} @param defaultValue 被检查对象为{@code null}返回的默认值,可以为{@code null} @return 被检查对象为{@code null}返回默认值,否则返回原值 @since 3.0.7
[ "如果给定对象为", "{", "@code", "null", "}", "返回默认值" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/ObjectUtil.java#L274-L276
bitcoinj/bitcoinj
core/src/main/java/org/bitcoinj/script/Script.java
Script.createEmptyInputScript
public Script createEmptyInputScript(@Nullable ECKey key, @Nullable Script redeemScript) { if (ScriptPattern.isP2PKH(this)) { checkArgument(key != null, "Key required to create P2PKH input script"); return ScriptBuilder.createInputScript(null, key); } else if (ScriptPattern.isP2WPKH(this)) { return ScriptBuilder.createEmpty(); } else if (ScriptPattern.isP2PK(this)) { return ScriptBuilder.createInputScript(null); } else if (ScriptPattern.isP2SH(this)) { checkArgument(redeemScript != null, "Redeem script required to create P2SH input script"); return ScriptBuilder.createP2SHMultiSigInputScript(null, redeemScript); } else { throw new ScriptException(ScriptError.SCRIPT_ERR_UNKNOWN_ERROR, "Do not understand script type: " + this); } }
java
public Script createEmptyInputScript(@Nullable ECKey key, @Nullable Script redeemScript) { if (ScriptPattern.isP2PKH(this)) { checkArgument(key != null, "Key required to create P2PKH input script"); return ScriptBuilder.createInputScript(null, key); } else if (ScriptPattern.isP2WPKH(this)) { return ScriptBuilder.createEmpty(); } else if (ScriptPattern.isP2PK(this)) { return ScriptBuilder.createInputScript(null); } else if (ScriptPattern.isP2SH(this)) { checkArgument(redeemScript != null, "Redeem script required to create P2SH input script"); return ScriptBuilder.createP2SHMultiSigInputScript(null, redeemScript); } else { throw new ScriptException(ScriptError.SCRIPT_ERR_UNKNOWN_ERROR, "Do not understand script type: " + this); } }
[ "public", "Script", "createEmptyInputScript", "(", "@", "Nullable", "ECKey", "key", ",", "@", "Nullable", "Script", "redeemScript", ")", "{", "if", "(", "ScriptPattern", ".", "isP2PKH", "(", "this", ")", ")", "{", "checkArgument", "(", "key", "!=", "null", ",", "\"Key required to create P2PKH input script\"", ")", ";", "return", "ScriptBuilder", ".", "createInputScript", "(", "null", ",", "key", ")", ";", "}", "else", "if", "(", "ScriptPattern", ".", "isP2WPKH", "(", "this", ")", ")", "{", "return", "ScriptBuilder", ".", "createEmpty", "(", ")", ";", "}", "else", "if", "(", "ScriptPattern", ".", "isP2PK", "(", "this", ")", ")", "{", "return", "ScriptBuilder", ".", "createInputScript", "(", "null", ")", ";", "}", "else", "if", "(", "ScriptPattern", ".", "isP2SH", "(", "this", ")", ")", "{", "checkArgument", "(", "redeemScript", "!=", "null", ",", "\"Redeem script required to create P2SH input script\"", ")", ";", "return", "ScriptBuilder", ".", "createP2SHMultiSigInputScript", "(", "null", ",", "redeemScript", ")", ";", "}", "else", "{", "throw", "new", "ScriptException", "(", "ScriptError", ".", "SCRIPT_ERR_UNKNOWN_ERROR", ",", "\"Do not understand script type: \"", "+", "this", ")", ";", "}", "}" ]
Creates an incomplete scriptSig that, once filled with signatures, can redeem output containing this scriptPubKey. Instead of the signatures resulting script has OP_0. Having incomplete input script allows to pass around partially signed tx. It is expected that this program later on will be updated with proper signatures.
[ "Creates", "an", "incomplete", "scriptSig", "that", "once", "filled", "with", "signatures", "can", "redeem", "output", "containing", "this", "scriptPubKey", ".", "Instead", "of", "the", "signatures", "resulting", "script", "has", "OP_0", ".", "Having", "incomplete", "input", "script", "allows", "to", "pass", "around", "partially", "signed", "tx", ".", "It", "is", "expected", "that", "this", "program", "later", "on", "will", "be", "updated", "with", "proper", "signatures", "." ]
train
https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/script/Script.java#L388-L402
b3log/latke
latke-core/src/main/java/org/json/JSONObject.java
JSONObject.optDouble
public double optDouble(String key, double defaultValue) { Number val = this.optNumber(key); if (val == null) { return defaultValue; } final double doubleValue = val.doubleValue(); // if (Double.isNaN(doubleValue) || Double.isInfinite(doubleValue)) { // return defaultValue; // } return doubleValue; }
java
public double optDouble(String key, double defaultValue) { Number val = this.optNumber(key); if (val == null) { return defaultValue; } final double doubleValue = val.doubleValue(); // if (Double.isNaN(doubleValue) || Double.isInfinite(doubleValue)) { // return defaultValue; // } return doubleValue; }
[ "public", "double", "optDouble", "(", "String", "key", ",", "double", "defaultValue", ")", "{", "Number", "val", "=", "this", ".", "optNumber", "(", "key", ")", ";", "if", "(", "val", "==", "null", ")", "{", "return", "defaultValue", ";", "}", "final", "double", "doubleValue", "=", "val", ".", "doubleValue", "(", ")", ";", "// if (Double.isNaN(doubleValue) || Double.isInfinite(doubleValue)) {", "// return defaultValue;", "// }", "return", "doubleValue", ";", "}" ]
Get an optional double associated with a key, or the defaultValue if there is no such key or if its value is not a number. If the value is a string, an attempt will be made to evaluate it as a number. @param key A key string. @param defaultValue The default. @return An object which is the value.
[ "Get", "an", "optional", "double", "associated", "with", "a", "key", "or", "the", "defaultValue", "if", "there", "is", "no", "such", "key", "or", "if", "its", "value", "is", "not", "a", "number", ".", "If", "the", "value", "is", "a", "string", "an", "attempt", "will", "be", "made", "to", "evaluate", "it", "as", "a", "number", "." ]
train
https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/json/JSONObject.java#L1233-L1243
Azure/azure-sdk-for-java
iothub/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/iothub/v2018_04_01/implementation/IotHubResourcesInner.java
IotHubResourcesInner.getStats
public RegistryStatisticsInner getStats(String resourceGroupName, String resourceName) { return getStatsWithServiceResponseAsync(resourceGroupName, resourceName).toBlocking().single().body(); }
java
public RegistryStatisticsInner getStats(String resourceGroupName, String resourceName) { return getStatsWithServiceResponseAsync(resourceGroupName, resourceName).toBlocking().single().body(); }
[ "public", "RegistryStatisticsInner", "getStats", "(", "String", "resourceGroupName", ",", "String", "resourceName", ")", "{", "return", "getStatsWithServiceResponseAsync", "(", "resourceGroupName", ",", "resourceName", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Get the statistics from an IoT hub. Get the statistics from an IoT hub. @param resourceGroupName The name of the resource group that contains the IoT hub. @param resourceName The name of the IoT hub. @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 RegistryStatisticsInner object if successful.
[ "Get", "the", "statistics", "from", "an", "IoT", "hub", ".", "Get", "the", "statistics", "from", "an", "IoT", "hub", "." ]
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/IotHubResourcesInner.java#L1414-L1416
grpc/grpc-java
examples/src/main/java/io/grpc/examples/errorhandling/DetailErrorSample.java
DetailErrorSample.advancedAsyncCall
void advancedAsyncCall() { ClientCall<HelloRequest, HelloReply> call = channel.newCall(GreeterGrpc.getSayHelloMethod(), CallOptions.DEFAULT); final CountDownLatch latch = new CountDownLatch(1); call.start(new ClientCall.Listener<HelloReply>() { @Override public void onClose(Status status, Metadata trailers) { Verify.verify(status.getCode() == Status.Code.INTERNAL); Verify.verify(trailers.containsKey(DEBUG_INFO_TRAILER_KEY)); try { Verify.verify(trailers.get(DEBUG_INFO_TRAILER_KEY).equals(DEBUG_INFO)); } catch (IllegalArgumentException e) { throw new VerifyException(e); } latch.countDown(); } }, new Metadata()); call.sendMessage(HelloRequest.newBuilder().build()); call.halfClose(); if (!Uninterruptibles.awaitUninterruptibly(latch, 1, TimeUnit.SECONDS)) { throw new RuntimeException("timeout!"); } }
java
void advancedAsyncCall() { ClientCall<HelloRequest, HelloReply> call = channel.newCall(GreeterGrpc.getSayHelloMethod(), CallOptions.DEFAULT); final CountDownLatch latch = new CountDownLatch(1); call.start(new ClientCall.Listener<HelloReply>() { @Override public void onClose(Status status, Metadata trailers) { Verify.verify(status.getCode() == Status.Code.INTERNAL); Verify.verify(trailers.containsKey(DEBUG_INFO_TRAILER_KEY)); try { Verify.verify(trailers.get(DEBUG_INFO_TRAILER_KEY).equals(DEBUG_INFO)); } catch (IllegalArgumentException e) { throw new VerifyException(e); } latch.countDown(); } }, new Metadata()); call.sendMessage(HelloRequest.newBuilder().build()); call.halfClose(); if (!Uninterruptibles.awaitUninterruptibly(latch, 1, TimeUnit.SECONDS)) { throw new RuntimeException("timeout!"); } }
[ "void", "advancedAsyncCall", "(", ")", "{", "ClientCall", "<", "HelloRequest", ",", "HelloReply", ">", "call", "=", "channel", ".", "newCall", "(", "GreeterGrpc", ".", "getSayHelloMethod", "(", ")", ",", "CallOptions", ".", "DEFAULT", ")", ";", "final", "CountDownLatch", "latch", "=", "new", "CountDownLatch", "(", "1", ")", ";", "call", ".", "start", "(", "new", "ClientCall", ".", "Listener", "<", "HelloReply", ">", "(", ")", "{", "@", "Override", "public", "void", "onClose", "(", "Status", "status", ",", "Metadata", "trailers", ")", "{", "Verify", ".", "verify", "(", "status", ".", "getCode", "(", ")", "==", "Status", ".", "Code", ".", "INTERNAL", ")", ";", "Verify", ".", "verify", "(", "trailers", ".", "containsKey", "(", "DEBUG_INFO_TRAILER_KEY", ")", ")", ";", "try", "{", "Verify", ".", "verify", "(", "trailers", ".", "get", "(", "DEBUG_INFO_TRAILER_KEY", ")", ".", "equals", "(", "DEBUG_INFO", ")", ")", ";", "}", "catch", "(", "IllegalArgumentException", "e", ")", "{", "throw", "new", "VerifyException", "(", "e", ")", ";", "}", "latch", ".", "countDown", "(", ")", ";", "}", "}", ",", "new", "Metadata", "(", ")", ")", ";", "call", ".", "sendMessage", "(", "HelloRequest", ".", "newBuilder", "(", ")", ".", "build", "(", ")", ")", ";", "call", ".", "halfClose", "(", ")", ";", "if", "(", "!", "Uninterruptibles", ".", "awaitUninterruptibly", "(", "latch", ",", "1", ",", "TimeUnit", ".", "SECONDS", ")", ")", "{", "throw", "new", "RuntimeException", "(", "\"timeout!\"", ")", ";", "}", "}" ]
This is more advanced and does not make use of the stub. You should not normally need to do this, but here is how you would.
[ "This", "is", "more", "advanced", "and", "does", "not", "make", "use", "of", "the", "stub", ".", "You", "should", "not", "normally", "need", "to", "do", "this", "but", "here", "is", "how", "you", "would", "." ]
train
https://github.com/grpc/grpc-java/blob/973885457f9609de232d2553b82c67f6c3ff57bf/examples/src/main/java/io/grpc/examples/errorhandling/DetailErrorSample.java#L199-L227
Netflix/karyon
karyon2-governator/src/main/java/netflix/karyon/Karyon.java
Karyon.forWebSocketServer
public static KaryonServer forWebSocketServer(RxServer<? extends WebSocketFrame, ? extends WebSocketFrame> server, Module... modules) { return forWebSocketServer(server, toBootstrapModule(modules)); }
java
public static KaryonServer forWebSocketServer(RxServer<? extends WebSocketFrame, ? extends WebSocketFrame> server, Module... modules) { return forWebSocketServer(server, toBootstrapModule(modules)); }
[ "public", "static", "KaryonServer", "forWebSocketServer", "(", "RxServer", "<", "?", "extends", "WebSocketFrame", ",", "?", "extends", "WebSocketFrame", ">", "server", ",", "Module", "...", "modules", ")", "{", "return", "forWebSocketServer", "(", "server", ",", "toBootstrapModule", "(", "modules", ")", ")", ";", "}" ]
Creates a new {@link KaryonServer} which combines lifecycle of the passed WebSockets {@link RxServer} with it's own lifecycle. @param server WebSocket server @param modules Additional bootstrapModules if any. @return {@link KaryonServer} which is to be used to start the created server.
[ "Creates", "a", "new", "{", "@link", "KaryonServer", "}", "which", "combines", "lifecycle", "of", "the", "passed", "WebSockets", "{", "@link", "RxServer", "}", "with", "it", "s", "own", "lifecycle", "." ]
train
https://github.com/Netflix/karyon/blob/d50bc0ff37693ef3fbda373e90a109d1f92e0b9a/karyon2-governator/src/main/java/netflix/karyon/Karyon.java#L204-L206