repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
218
func_name
stringlengths
4
140
whole_func_string
stringlengths
153
5.32k
language
stringclasses
1 value
func_code_string
stringlengths
72
4k
func_code_tokens
listlengths
20
832
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
listlengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
102
339
google/closure-compiler
src/com/google/javascript/jscomp/Es6RewriteBlockScopedDeclaration.java
Es6RewriteBlockScopedDeclaration.createAssignNode
private Node createAssignNode(Node lhs, Node rhs) { """ Creates an ASSIGN node with type information matching its RHS. """ Node assignNode = IR.assign(lhs, rhs); if (shouldAddTypesOnNewAstNodes) { assignNode.setJSType(rhs.getJSType()); } return assignNode; }
java
private Node createAssignNode(Node lhs, Node rhs) { Node assignNode = IR.assign(lhs, rhs); if (shouldAddTypesOnNewAstNodes) { assignNode.setJSType(rhs.getJSType()); } return assignNode; }
[ "private", "Node", "createAssignNode", "(", "Node", "lhs", ",", "Node", "rhs", ")", "{", "Node", "assignNode", "=", "IR", ".", "assign", "(", "lhs", ",", "rhs", ")", ";", "if", "(", "shouldAddTypesOnNewAstNodes", ")", "{", "assignNode", ".", "setJSType", "(", "rhs", ".", "getJSType", "(", ")", ")", ";", "}", "return", "assignNode", ";", "}" ]
Creates an ASSIGN node with type information matching its RHS.
[ "Creates", "an", "ASSIGN", "node", "with", "type", "information", "matching", "its", "RHS", "." ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/Es6RewriteBlockScopedDeclaration.java#L709-L715
LearnLib/automatalib
incremental/src/main/java/net/automatalib/incremental/dfa/dag/IncrementalDFADAGBuilder.java
IncrementalDFADAGBuilder.createSuffix
private State createSuffix(Word<? extends I> suffix, Acceptance acc) { """ Creates a suffix state sequence, i.e., a linear sequence of states connected by transitions labeled by the letters of the given suffix word. @param suffix the suffix word @param acc the acceptance status of the final state @return the first state in the sequence """ StateSignature sig = new StateSignature(alphabetSize, acc); sig.updateHashCode(); State last = replaceOrRegister(sig); int len = suffix.length(); for (int i = len - 1; i >= 0; i--) { sig = new StateSignature(alphabetSize, Acceptance.DONT_KNOW); I sym = suffix.getSymbol(i); int idx = inputAlphabet.getSymbolIndex(sym); sig.successors.array[idx] = last; sig.updateHashCode(); last = replaceOrRegister(sig); } return last; }
java
private State createSuffix(Word<? extends I> suffix, Acceptance acc) { StateSignature sig = new StateSignature(alphabetSize, acc); sig.updateHashCode(); State last = replaceOrRegister(sig); int len = suffix.length(); for (int i = len - 1; i >= 0; i--) { sig = new StateSignature(alphabetSize, Acceptance.DONT_KNOW); I sym = suffix.getSymbol(i); int idx = inputAlphabet.getSymbolIndex(sym); sig.successors.array[idx] = last; sig.updateHashCode(); last = replaceOrRegister(sig); } return last; }
[ "private", "State", "createSuffix", "(", "Word", "<", "?", "extends", "I", ">", "suffix", ",", "Acceptance", "acc", ")", "{", "StateSignature", "sig", "=", "new", "StateSignature", "(", "alphabetSize", ",", "acc", ")", ";", "sig", ".", "updateHashCode", "(", ")", ";", "State", "last", "=", "replaceOrRegister", "(", "sig", ")", ";", "int", "len", "=", "suffix", ".", "length", "(", ")", ";", "for", "(", "int", "i", "=", "len", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "sig", "=", "new", "StateSignature", "(", "alphabetSize", ",", "Acceptance", ".", "DONT_KNOW", ")", ";", "I", "sym", "=", "suffix", ".", "getSymbol", "(", "i", ")", ";", "int", "idx", "=", "inputAlphabet", ".", "getSymbolIndex", "(", "sym", ")", ";", "sig", ".", "successors", ".", "array", "[", "idx", "]", "=", "last", ";", "sig", ".", "updateHashCode", "(", ")", ";", "last", "=", "replaceOrRegister", "(", "sig", ")", ";", "}", "return", "last", ";", "}" ]
Creates a suffix state sequence, i.e., a linear sequence of states connected by transitions labeled by the letters of the given suffix word. @param suffix the suffix word @param acc the acceptance status of the final state @return the first state in the sequence
[ "Creates", "a", "suffix", "state", "sequence", "i", ".", "e", ".", "a", "linear", "sequence", "of", "states", "connected", "by", "transitions", "labeled", "by", "the", "letters", "of", "the", "given", "suffix", "word", "." ]
train
https://github.com/LearnLib/automatalib/blob/8a462ec52f6eaab9f8996e344f2163a72cb8aa6e/incremental/src/main/java/net/automatalib/incremental/dfa/dag/IncrementalDFADAGBuilder.java#L204-L220
phax/ph-css
ph-css/src/main/java/com/helger/css/reader/CSSReaderDeclarationList.java
CSSReaderDeclarationList.readFromStream
@Nullable public static CSSDeclarationList readFromStream (@Nonnull @WillClose final InputStream aIS, @Nonnull final Charset aCharset, @Nonnull final ECSSVersion eVersion) { """ Read the CSS from the passed {@link InputStream}. @param aIS The input stream to use. Will be closed automatically after reading - independent of success or error. May not be <code>null</code>. @param aCharset The charset to be used. May not be <code>null</code>. @param eVersion The CSS version to use. May not be <code>null</code>. @return <code>null</code> if reading failed, the CSS declarations otherwise. @since 3.7.4 """ return readFromReader (StreamHelper.createReader (aIS, aCharset), new CSSReaderSettings ().setCSSVersion (eVersion)); }
java
@Nullable public static CSSDeclarationList readFromStream (@Nonnull @WillClose final InputStream aIS, @Nonnull final Charset aCharset, @Nonnull final ECSSVersion eVersion) { return readFromReader (StreamHelper.createReader (aIS, aCharset), new CSSReaderSettings ().setCSSVersion (eVersion)); }
[ "@", "Nullable", "public", "static", "CSSDeclarationList", "readFromStream", "(", "@", "Nonnull", "@", "WillClose", "final", "InputStream", "aIS", ",", "@", "Nonnull", "final", "Charset", "aCharset", ",", "@", "Nonnull", "final", "ECSSVersion", "eVersion", ")", "{", "return", "readFromReader", "(", "StreamHelper", ".", "createReader", "(", "aIS", ",", "aCharset", ")", ",", "new", "CSSReaderSettings", "(", ")", ".", "setCSSVersion", "(", "eVersion", ")", ")", ";", "}" ]
Read the CSS from the passed {@link InputStream}. @param aIS The input stream to use. Will be closed automatically after reading - independent of success or error. May not be <code>null</code>. @param aCharset The charset to be used. May not be <code>null</code>. @param eVersion The CSS version to use. May not be <code>null</code>. @return <code>null</code> if reading failed, the CSS declarations otherwise. @since 3.7.4
[ "Read", "the", "CSS", "from", "the", "passed", "{", "@link", "InputStream", "}", "." ]
train
https://github.com/phax/ph-css/blob/c9da5bb4decc681de6e27ce31712aad4c00adafa/ph-css/src/main/java/com/helger/css/reader/CSSReaderDeclarationList.java#L552-L559
youngmonkeys/ezyfox-sfs2x
src/main/java/com/tvd12/ezyfox/sfs2x/data/impl/SimpleTransformer.java
SimpleTransformer.initWithStringType
protected void initWithStringType() { """ Add transformer of string and transformer of array of strings to the map """ transformers.put(String.class, new Transformer() { @Override public SFSDataWrapper transform(Object value) { return new SFSDataWrapper(SFSDataType.UTF_STRING, value); } }); transformers.put(String[].class, new Transformer() { @Override public SFSDataWrapper transform(Object value) { return new SFSDataWrapper(SFSDataType.UTF_STRING_ARRAY, stringArrayToCollection((String[])value)); } }); }
java
protected void initWithStringType() { transformers.put(String.class, new Transformer() { @Override public SFSDataWrapper transform(Object value) { return new SFSDataWrapper(SFSDataType.UTF_STRING, value); } }); transformers.put(String[].class, new Transformer() { @Override public SFSDataWrapper transform(Object value) { return new SFSDataWrapper(SFSDataType.UTF_STRING_ARRAY, stringArrayToCollection((String[])value)); } }); }
[ "protected", "void", "initWithStringType", "(", ")", "{", "transformers", ".", "put", "(", "String", ".", "class", ",", "new", "Transformer", "(", ")", "{", "@", "Override", "public", "SFSDataWrapper", "transform", "(", "Object", "value", ")", "{", "return", "new", "SFSDataWrapper", "(", "SFSDataType", ".", "UTF_STRING", ",", "value", ")", ";", "}", "}", ")", ";", "transformers", ".", "put", "(", "String", "[", "]", ".", "class", ",", "new", "Transformer", "(", ")", "{", "@", "Override", "public", "SFSDataWrapper", "transform", "(", "Object", "value", ")", "{", "return", "new", "SFSDataWrapper", "(", "SFSDataType", ".", "UTF_STRING_ARRAY", ",", "stringArrayToCollection", "(", "(", "String", "[", "]", ")", "value", ")", ")", ";", "}", "}", ")", ";", "}" ]
Add transformer of string and transformer of array of strings to the map
[ "Add", "transformer", "of", "string", "and", "transformer", "of", "array", "of", "strings", "to", "the", "map" ]
train
https://github.com/youngmonkeys/ezyfox-sfs2x/blob/7e004033a3b551c3ae970a0c8f45db7b1ec144de/src/main/java/com/tvd12/ezyfox/sfs2x/data/impl/SimpleTransformer.java#L411-L425
apache/incubator-druid
processing/src/main/java/org/apache/druid/segment/BitmapOffset.java
BitmapOffset.factorizeFullness
private static String factorizeFullness(long bitmapCardinality, long numRows) { """ Processing of queries with BitmapOffsets, whose Bitmaps has different factorized fullness (bucket), reported from this method, uses different copies of the same code, so JIT compiler analyzes and compiles the code for different factorized fullness separately. The goal is to capture frequency of abstraction usage in compressed bitmap algorithms, i. e. - "Zero sequence" vs. "Literal" vs. "One sequence" in {@link org.apache.druid.extendedset.intset.ImmutableConciseSet} - {@link org.roaringbitmap.ArrayContainer} vs {@link org.roaringbitmap.BitmapContainer} in Roaring and then https://shipilev.net/blog/2015/black-magic-method-dispatch/ comes into play. The secondary goal is to capture HotSpot's thresholds, which it uses to compile conditional blocks differently inside bitmap impls. See https://bugs.openjdk.java.net/browse/JDK-6743900. The default BlockLayoutMinDiamondPercentage=20, i. e. if probability of taking some branch is less than 20%, it is moved out of the hot path (to save some icache?). On the other hand, we don't want to factor fullness into too small pieces, because - too little queries may fall into those small buckets, and they are not compiled with Hotspot's C2 compiler - if there are a lot of queries for each small factorized fullness and their copies of the code is compiled by C2, this pollutes code cache and takes time to perform too many compilations, while some of them likely produce identical code. Ideally there should be as much buckets as possible as long as Hotspot's C2 output for each bucket is different. """ if (bitmapCardinality == 0) { return "0"; } else if (bitmapCardinality == numRows) { return "1"; } else { double fullness = bitmapCardinality / (double) numRows; int index = Arrays.binarySearch(BITMAP_FULLNESS_FACTORIZATION_STOPS, fullness); if (index < 0) { index = ~index; } return FACTORIZED_FULLNESS[index]; } }
java
private static String factorizeFullness(long bitmapCardinality, long numRows) { if (bitmapCardinality == 0) { return "0"; } else if (bitmapCardinality == numRows) { return "1"; } else { double fullness = bitmapCardinality / (double) numRows; int index = Arrays.binarySearch(BITMAP_FULLNESS_FACTORIZATION_STOPS, fullness); if (index < 0) { index = ~index; } return FACTORIZED_FULLNESS[index]; } }
[ "private", "static", "String", "factorizeFullness", "(", "long", "bitmapCardinality", ",", "long", "numRows", ")", "{", "if", "(", "bitmapCardinality", "==", "0", ")", "{", "return", "\"0\"", ";", "}", "else", "if", "(", "bitmapCardinality", "==", "numRows", ")", "{", "return", "\"1\"", ";", "}", "else", "{", "double", "fullness", "=", "bitmapCardinality", "/", "(", "double", ")", "numRows", ";", "int", "index", "=", "Arrays", ".", "binarySearch", "(", "BITMAP_FULLNESS_FACTORIZATION_STOPS", ",", "fullness", ")", ";", "if", "(", "index", "<", "0", ")", "{", "index", "=", "~", "index", ";", "}", "return", "FACTORIZED_FULLNESS", "[", "index", "]", ";", "}", "}" ]
Processing of queries with BitmapOffsets, whose Bitmaps has different factorized fullness (bucket), reported from this method, uses different copies of the same code, so JIT compiler analyzes and compiles the code for different factorized fullness separately. The goal is to capture frequency of abstraction usage in compressed bitmap algorithms, i. e. - "Zero sequence" vs. "Literal" vs. "One sequence" in {@link org.apache.druid.extendedset.intset.ImmutableConciseSet} - {@link org.roaringbitmap.ArrayContainer} vs {@link org.roaringbitmap.BitmapContainer} in Roaring and then https://shipilev.net/blog/2015/black-magic-method-dispatch/ comes into play. The secondary goal is to capture HotSpot's thresholds, which it uses to compile conditional blocks differently inside bitmap impls. See https://bugs.openjdk.java.net/browse/JDK-6743900. The default BlockLayoutMinDiamondPercentage=20, i. e. if probability of taking some branch is less than 20%, it is moved out of the hot path (to save some icache?). On the other hand, we don't want to factor fullness into too small pieces, because - too little queries may fall into those small buckets, and they are not compiled with Hotspot's C2 compiler - if there are a lot of queries for each small factorized fullness and their copies of the code is compiled by C2, this pollutes code cache and takes time to perform too many compilations, while some of them likely produce identical code. Ideally there should be as much buckets as possible as long as Hotspot's C2 output for each bucket is different.
[ "Processing", "of", "queries", "with", "BitmapOffsets", "whose", "Bitmaps", "has", "different", "factorized", "fullness", "(", "bucket", ")", "reported", "from", "this", "method", "uses", "different", "copies", "of", "the", "same", "code", "so", "JIT", "compiler", "analyzes", "and", "compiles", "the", "code", "for", "different", "factorized", "fullness", "separately", ".", "The", "goal", "is", "to", "capture", "frequency", "of", "abstraction", "usage", "in", "compressed", "bitmap", "algorithms", "i", ".", "e", ".", "-", "Zero", "sequence", "vs", ".", "Literal", "vs", ".", "One", "sequence", "in", "{", "@link", "org", ".", "apache", ".", "druid", ".", "extendedset", ".", "intset", ".", "ImmutableConciseSet", "}", "-", "{", "@link", "org", ".", "roaringbitmap", ".", "ArrayContainer", "}", "vs", "{", "@link", "org", ".", "roaringbitmap", ".", "BitmapContainer", "}", "in", "Roaring", "and", "then", "https", ":", "//", "shipilev", ".", "net", "/", "blog", "/", "2015", "/", "black", "-", "magic", "-", "method", "-", "dispatch", "/", "comes", "into", "play", ".", "The", "secondary", "goal", "is", "to", "capture", "HotSpot", "s", "thresholds", "which", "it", "uses", "to", "compile", "conditional", "blocks", "differently", "inside", "bitmap", "impls", ".", "See", "https", ":", "//", "bugs", ".", "openjdk", ".", "java", ".", "net", "/", "browse", "/", "JDK", "-", "6743900", ".", "The", "default", "BlockLayoutMinDiamondPercentage", "=", "20", "i", ".", "e", ".", "if", "probability", "of", "taking", "some", "branch", "is", "less", "than", "20%", "it", "is", "moved", "out", "of", "the", "hot", "path", "(", "to", "save", "some", "icache?", ")", "." ]
train
https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/processing/src/main/java/org/apache/druid/segment/BitmapOffset.java#L110-L124
grails/grails-core
grails-core/src/main/groovy/grails/util/GrailsClassUtils.java
GrailsClassUtils.isStaticProperty
@SuppressWarnings("rawtypes") public static boolean isStaticProperty(Class clazz, String propertyName) { """ <p>Work out if the specified property is readable and static. Java introspection does not recognize this concept of static properties but Groovy does. We also consider public static fields as static properties with no getters/setters</p> @param clazz The class to check for static property @param propertyName The property name @return true if the property with name propertyName has a static getter method """ Method getter = BeanUtils.findDeclaredMethod(clazz, getGetterName(propertyName), (Class[])null); if (getter != null) { return isPublicStatic(getter); } try { Field f = clazz.getDeclaredField(propertyName); if (f != null) { return isPublicStatic(f); } } catch (NoSuchFieldException ignored) { // ignored } return false; }
java
@SuppressWarnings("rawtypes") public static boolean isStaticProperty(Class clazz, String propertyName) { Method getter = BeanUtils.findDeclaredMethod(clazz, getGetterName(propertyName), (Class[])null); if (getter != null) { return isPublicStatic(getter); } try { Field f = clazz.getDeclaredField(propertyName); if (f != null) { return isPublicStatic(f); } } catch (NoSuchFieldException ignored) { // ignored } return false; }
[ "@", "SuppressWarnings", "(", "\"rawtypes\"", ")", "public", "static", "boolean", "isStaticProperty", "(", "Class", "clazz", ",", "String", "propertyName", ")", "{", "Method", "getter", "=", "BeanUtils", ".", "findDeclaredMethod", "(", "clazz", ",", "getGetterName", "(", "propertyName", ")", ",", "(", "Class", "[", "]", ")", "null", ")", ";", "if", "(", "getter", "!=", "null", ")", "{", "return", "isPublicStatic", "(", "getter", ")", ";", "}", "try", "{", "Field", "f", "=", "clazz", ".", "getDeclaredField", "(", "propertyName", ")", ";", "if", "(", "f", "!=", "null", ")", "{", "return", "isPublicStatic", "(", "f", ")", ";", "}", "}", "catch", "(", "NoSuchFieldException", "ignored", ")", "{", "// ignored", "}", "return", "false", ";", "}" ]
<p>Work out if the specified property is readable and static. Java introspection does not recognize this concept of static properties but Groovy does. We also consider public static fields as static properties with no getters/setters</p> @param clazz The class to check for static property @param propertyName The property name @return true if the property with name propertyName has a static getter method
[ "<p", ">", "Work", "out", "if", "the", "specified", "property", "is", "readable", "and", "static", ".", "Java", "introspection", "does", "not", "recognize", "this", "concept", "of", "static", "properties", "but", "Groovy", "does", ".", "We", "also", "consider", "public", "static", "fields", "as", "static", "properties", "with", "no", "getters", "/", "setters<", "/", "p", ">" ]
train
https://github.com/grails/grails-core/blob/c0b08aa995b0297143b75d05642abba8cb7b4122/grails-core/src/main/groovy/grails/util/GrailsClassUtils.java#L524-L542
camunda/camunda-bpm-platform
engine/src/main/java/org/camunda/bpm/engine/impl/bpmn/behavior/ExternalTaskActivityBehavior.java
ExternalTaskActivityBehavior.propagateBpmnError
@Override public void propagateBpmnError(BpmnError error, ActivityExecution execution) throws Exception { """ Overrides the propagateBpmnError method to made it public. Is used to propagate the bpmn error from an external task. @param error the error which should be propagated @param execution the current activity execution @throws Exception throwsn an exception if no handler was found """ super.propagateBpmnError(error, execution); }
java
@Override public void propagateBpmnError(BpmnError error, ActivityExecution execution) throws Exception { super.propagateBpmnError(error, execution); }
[ "@", "Override", "public", "void", "propagateBpmnError", "(", "BpmnError", "error", ",", "ActivityExecution", "execution", ")", "throws", "Exception", "{", "super", ".", "propagateBpmnError", "(", "error", ",", "execution", ")", ";", "}" ]
Overrides the propagateBpmnError method to made it public. Is used to propagate the bpmn error from an external task. @param error the error which should be propagated @param execution the current activity execution @throws Exception throwsn an exception if no handler was found
[ "Overrides", "the", "propagateBpmnError", "method", "to", "made", "it", "public", ".", "Is", "used", "to", "propagate", "the", "bpmn", "error", "from", "an", "external", "task", "." ]
train
https://github.com/camunda/camunda-bpm-platform/blob/1a464fc887ef3760e53d6f91b9e5b871a0d77cc0/engine/src/main/java/org/camunda/bpm/engine/impl/bpmn/behavior/ExternalTaskActivityBehavior.java#L76-L79
stephanrauh/AngularFaces
AngularFaces_2.0/AngularFaces-core/src/main/java/de/beyondjava/angularFaces/components/puiModelSync/PuiModelSync.java
PuiModelSync.getValueToRender
public static Object getValueToRender(FacesContext context, UIComponent component) { """ This method has been copied from the PrimeFaces 5 project (and been adapted after). Algorithm works as follows; - If it's an input component, submitted value is checked first since it'd be the value to be used in case validation errors terminates jsf lifecycle - Finally the value of the component is retrieved from backing bean and if there's a converter, converted value is returned @param context FacesContext instance @param component UIComponent instance whose value will be returned @return End text """ if (component instanceof ValueHolder) { if (component instanceof EditableValueHolder) { EditableValueHolder input = (EditableValueHolder) component; Object submittedValue = input.getSubmittedValue(); if (submittedValue == null && context.isValidationFailed() && !input.isValid()) { return null; } else if (submittedValue != null) { return submittedValue; } } ValueHolder valueHolder = (ValueHolder) component; Object value = valueHolder.getValue(); return value; } // component it not a value holder return null; }
java
public static Object getValueToRender(FacesContext context, UIComponent component) { if (component instanceof ValueHolder) { if (component instanceof EditableValueHolder) { EditableValueHolder input = (EditableValueHolder) component; Object submittedValue = input.getSubmittedValue(); if (submittedValue == null && context.isValidationFailed() && !input.isValid()) { return null; } else if (submittedValue != null) { return submittedValue; } } ValueHolder valueHolder = (ValueHolder) component; Object value = valueHolder.getValue(); return value; } // component it not a value holder return null; }
[ "public", "static", "Object", "getValueToRender", "(", "FacesContext", "context", ",", "UIComponent", "component", ")", "{", "if", "(", "component", "instanceof", "ValueHolder", ")", "{", "if", "(", "component", "instanceof", "EditableValueHolder", ")", "{", "EditableValueHolder", "input", "=", "(", "EditableValueHolder", ")", "component", ";", "Object", "submittedValue", "=", "input", ".", "getSubmittedValue", "(", ")", ";", "if", "(", "submittedValue", "==", "null", "&&", "context", ".", "isValidationFailed", "(", ")", "&&", "!", "input", ".", "isValid", "(", ")", ")", "{", "return", "null", ";", "}", "else", "if", "(", "submittedValue", "!=", "null", ")", "{", "return", "submittedValue", ";", "}", "}", "ValueHolder", "valueHolder", "=", "(", "ValueHolder", ")", "component", ";", "Object", "value", "=", "valueHolder", ".", "getValue", "(", ")", ";", "return", "value", ";", "}", "// component it not a value holder", "return", "null", ";", "}" ]
This method has been copied from the PrimeFaces 5 project (and been adapted after). Algorithm works as follows; - If it's an input component, submitted value is checked first since it'd be the value to be used in case validation errors terminates jsf lifecycle - Finally the value of the component is retrieved from backing bean and if there's a converter, converted value is returned @param context FacesContext instance @param component UIComponent instance whose value will be returned @return End text
[ "This", "method", "has", "been", "copied", "from", "the", "PrimeFaces", "5", "project", "(", "and", "been", "adapted", "after", ")", "." ]
train
https://github.com/stephanrauh/AngularFaces/blob/43d915f004645b1bbbf2625214294dab0858ba01/AngularFaces_2.0/AngularFaces-core/src/main/java/de/beyondjava/angularFaces/components/puiModelSync/PuiModelSync.java#L261-L282
EdwardRaff/JSAT
JSAT/src/jsat/io/LIBSVMLoader.java
LIBSVMLoader.loadC
public static ClassificationDataSet loadC(Reader reader, double sparseRatio, int vectorLength) throws IOException { """ Loads a new classification data set from a LIBSVM file, assuming the label is a nominal target value @param reader the input stream for the file to load @param sparseRatio the fraction of non zero values to qualify a data point as sparse @param vectorLength the pre-determined length of each vector. If given a negative value, the largest non-zero index observed in the data will be used as the length. @param store the type of store to use for the data @return a classification data set @throws IOException if an error occurred reading the input stream """ return loadC(reader, sparseRatio, vectorLength, DataStore.DEFAULT_STORE); }
java
public static ClassificationDataSet loadC(Reader reader, double sparseRatio, int vectorLength) throws IOException { return loadC(reader, sparseRatio, vectorLength, DataStore.DEFAULT_STORE); }
[ "public", "static", "ClassificationDataSet", "loadC", "(", "Reader", "reader", ",", "double", "sparseRatio", ",", "int", "vectorLength", ")", "throws", "IOException", "{", "return", "loadC", "(", "reader", ",", "sparseRatio", ",", "vectorLength", ",", "DataStore", ".", "DEFAULT_STORE", ")", ";", "}" ]
Loads a new classification data set from a LIBSVM file, assuming the label is a nominal target value @param reader the input stream for the file to load @param sparseRatio the fraction of non zero values to qualify a data point as sparse @param vectorLength the pre-determined length of each vector. If given a negative value, the largest non-zero index observed in the data will be used as the length. @param store the type of store to use for the data @return a classification data set @throws IOException if an error occurred reading the input stream
[ "Loads", "a", "new", "classification", "data", "set", "from", "a", "LIBSVM", "file", "assuming", "the", "label", "is", "a", "nominal", "target", "value" ]
train
https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/io/LIBSVMLoader.java#L233-L236
wildfly/wildfly-core
controller/src/main/java/org/jboss/as/controller/AttributeDefinition.java
AttributeDefinition.removeCapabilityRequirements
@Deprecated public void removeCapabilityRequirements(OperationContext context, ModelNode attributeValue) { """ Based on the given attribute value, remove capability requirements. If this definition is for an attribute whose value is or contains a reference to the name of some capability, this method should record the removal of a requirement for the capability. <p> This is a no-op in this base class. Subclasses that support attribute types that can represent capability references should override this method. @param context the operation context @param attributeValue the value of the attribute described by this object @deprecated use {@link #removeCapabilityRequirements(OperationContext, Resource, ModelNode)} variant """ removeCapabilityRequirements(context, null, attributeValue); }
java
@Deprecated public void removeCapabilityRequirements(OperationContext context, ModelNode attributeValue) { removeCapabilityRequirements(context, null, attributeValue); }
[ "@", "Deprecated", "public", "void", "removeCapabilityRequirements", "(", "OperationContext", "context", ",", "ModelNode", "attributeValue", ")", "{", "removeCapabilityRequirements", "(", "context", ",", "null", ",", "attributeValue", ")", ";", "}" ]
Based on the given attribute value, remove capability requirements. If this definition is for an attribute whose value is or contains a reference to the name of some capability, this method should record the removal of a requirement for the capability. <p> This is a no-op in this base class. Subclasses that support attribute types that can represent capability references should override this method. @param context the operation context @param attributeValue the value of the attribute described by this object @deprecated use {@link #removeCapabilityRequirements(OperationContext, Resource, ModelNode)} variant
[ "Based", "on", "the", "given", "attribute", "value", "remove", "capability", "requirements", ".", "If", "this", "definition", "is", "for", "an", "attribute", "whose", "value", "is", "or", "contains", "a", "reference", "to", "the", "name", "of", "some", "capability", "this", "method", "should", "record", "the", "removal", "of", "a", "requirement", "for", "the", "capability", ".", "<p", ">", "This", "is", "a", "no", "-", "op", "in", "this", "base", "class", ".", "Subclasses", "that", "support", "attribute", "types", "that", "can", "represent", "capability", "references", "should", "override", "this", "method", "." ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/AttributeDefinition.java#L1083-L1086
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/util/ObjectIdentifier.java
ObjectIdentifier.pack7Oid
private static int pack7Oid(byte[] in, int ioffset, int ilength, byte[] out, int ooffset) { """ Repack from NUB 8 to a NUB 7 OID sub-identifier, remove all unnecessary 0 headings, set the first bit of all non-tail output bytes to 1 (as ITU-T Rec. X.690 8.19.2 says), and paste it into an existing byte array. @param out the existing array to be pasted into @param ooffset the starting position to paste @return the number of bytes pasted """ byte[] pack = pack(in, ioffset, ilength, 8, 7); int firstNonZero = pack.length-1; // paste at least one byte for (int i=pack.length-2; i>=0; i--) { if (pack[i] != 0) { firstNonZero = i; } pack[i] |= 0x80; } System.arraycopy(pack, firstNonZero, out, ooffset, pack.length-firstNonZero); return pack.length-firstNonZero; }
java
private static int pack7Oid(byte[] in, int ioffset, int ilength, byte[] out, int ooffset) { byte[] pack = pack(in, ioffset, ilength, 8, 7); int firstNonZero = pack.length-1; // paste at least one byte for (int i=pack.length-2; i>=0; i--) { if (pack[i] != 0) { firstNonZero = i; } pack[i] |= 0x80; } System.arraycopy(pack, firstNonZero, out, ooffset, pack.length-firstNonZero); return pack.length-firstNonZero; }
[ "private", "static", "int", "pack7Oid", "(", "byte", "[", "]", "in", ",", "int", "ioffset", ",", "int", "ilength", ",", "byte", "[", "]", "out", ",", "int", "ooffset", ")", "{", "byte", "[", "]", "pack", "=", "pack", "(", "in", ",", "ioffset", ",", "ilength", ",", "8", ",", "7", ")", ";", "int", "firstNonZero", "=", "pack", ".", "length", "-", "1", ";", "// paste at least one byte", "for", "(", "int", "i", "=", "pack", ".", "length", "-", "2", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "if", "(", "pack", "[", "i", "]", "!=", "0", ")", "{", "firstNonZero", "=", "i", ";", "}", "pack", "[", "i", "]", "|=", "0x80", ";", "}", "System", ".", "arraycopy", "(", "pack", ",", "firstNonZero", ",", "out", ",", "ooffset", ",", "pack", ".", "length", "-", "firstNonZero", ")", ";", "return", "pack", ".", "length", "-", "firstNonZero", ";", "}" ]
Repack from NUB 8 to a NUB 7 OID sub-identifier, remove all unnecessary 0 headings, set the first bit of all non-tail output bytes to 1 (as ITU-T Rec. X.690 8.19.2 says), and paste it into an existing byte array. @param out the existing array to be pasted into @param ooffset the starting position to paste @return the number of bytes pasted
[ "Repack", "from", "NUB", "8", "to", "a", "NUB", "7", "OID", "sub", "-", "identifier", "remove", "all", "unnecessary", "0", "headings", "set", "the", "first", "bit", "of", "all", "non", "-", "tail", "output", "bytes", "to", "1", "(", "as", "ITU", "-", "T", "Rec", ".", "X", ".", "690", "8", ".", "19", ".", "2", "says", ")", "and", "paste", "it", "into", "an", "existing", "byte", "array", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/util/ObjectIdentifier.java#L537-L548
QSFT/Doradus
doradus-client/src/main/java/com/dell/doradus/dory/command/Command.java
Command.matchCommand
public static JsonObject matchCommand(JsonObject commandsJson, String commandName, String storageService) { """ Finds out if a command is supported by Doradus @param commandsJson @param commandName @param storageService @return """ for (String key : commandsJson.keySet()) { if (key.equals(storageService)) { JsonObject commandCats = commandsJson.getJsonObject(key); if (commandCats.containsKey(commandName)) { return commandCats.getJsonObject(commandName); } } } return null; }
java
public static JsonObject matchCommand(JsonObject commandsJson, String commandName, String storageService) { for (String key : commandsJson.keySet()) { if (key.equals(storageService)) { JsonObject commandCats = commandsJson.getJsonObject(key); if (commandCats.containsKey(commandName)) { return commandCats.getJsonObject(commandName); } } } return null; }
[ "public", "static", "JsonObject", "matchCommand", "(", "JsonObject", "commandsJson", ",", "String", "commandName", ",", "String", "storageService", ")", "{", "for", "(", "String", "key", ":", "commandsJson", ".", "keySet", "(", ")", ")", "{", "if", "(", "key", ".", "equals", "(", "storageService", ")", ")", "{", "JsonObject", "commandCats", "=", "commandsJson", ".", "getJsonObject", "(", "key", ")", ";", "if", "(", "commandCats", ".", "containsKey", "(", "commandName", ")", ")", "{", "return", "commandCats", ".", "getJsonObject", "(", "commandName", ")", ";", "}", "}", "}", "return", "null", ";", "}" ]
Finds out if a command is supported by Doradus @param commandsJson @param commandName @param storageService @return
[ "Finds", "out", "if", "a", "command", "is", "supported", "by", "Doradus" ]
train
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-client/src/main/java/com/dell/doradus/dory/command/Command.java#L270-L280
VoltDB/voltdb
src/hsqldb19b3/org/hsqldb_voltpatches/ParserDML.java
ParserDML.compileMigrateStatement
StatementDMQL compileMigrateStatement(RangeVariable[] outerRanges) { """ Creates a MIGRATE-type statement from this parser context (i.e. MIGRATE FROM tbl WHERE ... @param outerRanges @return compiled statement """ final Expression condition; assert token.tokenType == Tokens.MIGRATE; read(); readThis(Tokens.FROM); RangeVariable[] rangeVariables = { readSimpleRangeVariable(StatementTypes.MIGRATE_WHERE) }; Table table = rangeVariables[0].getTable(); if (token.tokenType == Tokens.WHERE) { read(); condition = XreadBooleanValueExpression(); HsqlList unresolved = condition.resolveColumnReferences(outerRanges, null); unresolved = Expression.resolveColumnSet(rangeVariables, unresolved, null); ExpressionColumn.checkColumnsResolved(unresolved); condition.resolveTypes(session, null); if (condition.isParam()) { condition.dataType = Type.SQL_BOOLEAN; } if (condition.getDataType() != Type.SQL_BOOLEAN) { throw Error.error(ErrorCode.X_42568); } } else { throw Error.error(ErrorCode.X_47000); } // check WHERE condition RangeVariableResolver resolver = new RangeVariableResolver(rangeVariables, condition, compileContext); resolver.processConditions(); rangeVariables = resolver.rangeVariables; return new StatementDML(session, table, rangeVariables, compileContext); }
java
StatementDMQL compileMigrateStatement(RangeVariable[] outerRanges) { final Expression condition; assert token.tokenType == Tokens.MIGRATE; read(); readThis(Tokens.FROM); RangeVariable[] rangeVariables = { readSimpleRangeVariable(StatementTypes.MIGRATE_WHERE) }; Table table = rangeVariables[0].getTable(); if (token.tokenType == Tokens.WHERE) { read(); condition = XreadBooleanValueExpression(); HsqlList unresolved = condition.resolveColumnReferences(outerRanges, null); unresolved = Expression.resolveColumnSet(rangeVariables, unresolved, null); ExpressionColumn.checkColumnsResolved(unresolved); condition.resolveTypes(session, null); if (condition.isParam()) { condition.dataType = Type.SQL_BOOLEAN; } if (condition.getDataType() != Type.SQL_BOOLEAN) { throw Error.error(ErrorCode.X_42568); } } else { throw Error.error(ErrorCode.X_47000); } // check WHERE condition RangeVariableResolver resolver = new RangeVariableResolver(rangeVariables, condition, compileContext); resolver.processConditions(); rangeVariables = resolver.rangeVariables; return new StatementDML(session, table, rangeVariables, compileContext); }
[ "StatementDMQL", "compileMigrateStatement", "(", "RangeVariable", "[", "]", "outerRanges", ")", "{", "final", "Expression", "condition", ";", "assert", "token", ".", "tokenType", "==", "Tokens", ".", "MIGRATE", ";", "read", "(", ")", ";", "readThis", "(", "Tokens", ".", "FROM", ")", ";", "RangeVariable", "[", "]", "rangeVariables", "=", "{", "readSimpleRangeVariable", "(", "StatementTypes", ".", "MIGRATE_WHERE", ")", "}", ";", "Table", "table", "=", "rangeVariables", "[", "0", "]", ".", "getTable", "(", ")", ";", "if", "(", "token", ".", "tokenType", "==", "Tokens", ".", "WHERE", ")", "{", "read", "(", ")", ";", "condition", "=", "XreadBooleanValueExpression", "(", ")", ";", "HsqlList", "unresolved", "=", "condition", ".", "resolveColumnReferences", "(", "outerRanges", ",", "null", ")", ";", "unresolved", "=", "Expression", ".", "resolveColumnSet", "(", "rangeVariables", ",", "unresolved", ",", "null", ")", ";", "ExpressionColumn", ".", "checkColumnsResolved", "(", "unresolved", ")", ";", "condition", ".", "resolveTypes", "(", "session", ",", "null", ")", ";", "if", "(", "condition", ".", "isParam", "(", ")", ")", "{", "condition", ".", "dataType", "=", "Type", ".", "SQL_BOOLEAN", ";", "}", "if", "(", "condition", ".", "getDataType", "(", ")", "!=", "Type", ".", "SQL_BOOLEAN", ")", "{", "throw", "Error", ".", "error", "(", "ErrorCode", ".", "X_42568", ")", ";", "}", "}", "else", "{", "throw", "Error", ".", "error", "(", "ErrorCode", ".", "X_47000", ")", ";", "}", "// check WHERE condition", "RangeVariableResolver", "resolver", "=", "new", "RangeVariableResolver", "(", "rangeVariables", ",", "condition", ",", "compileContext", ")", ";", "resolver", ".", "processConditions", "(", ")", ";", "rangeVariables", "=", "resolver", ".", "rangeVariables", ";", "return", "new", "StatementDML", "(", "session", ",", "table", ",", "rangeVariables", ",", "compileContext", ")", ";", "}" ]
Creates a MIGRATE-type statement from this parser context (i.e. MIGRATE FROM tbl WHERE ... @param outerRanges @return compiled statement
[ "Creates", "a", "MIGRATE", "-", "type", "statement", "from", "this", "parser", "context", "(", "i", ".", "e", ".", "MIGRATE", "FROM", "tbl", "WHERE", "..." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/ParserDML.java#L334-L377
eclipse/xtext-lib
org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/IntegerExtensions.java
IntegerExtensions.bitwiseXor
@Pure @Inline(value="($1 ^ $2)", constantExpression=true) public static int bitwiseXor(int a, int b) { """ The bitwise exclusive <code>or</code> operation. This is the equivalent to the java <code>^</code> operator. @param a an integer. @param b an integer. @return <code>a^b</code> """ return a ^ b; }
java
@Pure @Inline(value="($1 ^ $2)", constantExpression=true) public static int bitwiseXor(int a, int b) { return a ^ b; }
[ "@", "Pure", "@", "Inline", "(", "value", "=", "\"($1 ^ $2)\"", ",", "constantExpression", "=", "true", ")", "public", "static", "int", "bitwiseXor", "(", "int", "a", ",", "int", "b", ")", "{", "return", "a", "^", "b", ";", "}" ]
The bitwise exclusive <code>or</code> operation. This is the equivalent to the java <code>^</code> operator. @param a an integer. @param b an integer. @return <code>a^b</code>
[ "The", "bitwise", "exclusive", "<code", ">", "or<", "/", "code", ">", "operation", ".", "This", "is", "the", "equivalent", "to", "the", "java", "<code", ">", "^<", "/", "code", ">", "operator", "." ]
train
https://github.com/eclipse/xtext-lib/blob/7063572e1f1bd713a3aa53bdf3a8dc60e25c169a/org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/IntegerExtensions.java#L91-L95
westnordost/osmapi
src/main/java/de/westnordost/osmapi/notes/NotesDao.java
NotesDao.getAll
public void getAll(BoundingBox bounds, Handler<Note> handler, int limit, int hideClosedNoteAfter) { """ Retrieve all notes in the given area and feed them to the given handler. @see #getAll(BoundingBox, String, Handler, int, int) """ getAll(bounds, null, handler, limit, hideClosedNoteAfter); }
java
public void getAll(BoundingBox bounds, Handler<Note> handler, int limit, int hideClosedNoteAfter) { getAll(bounds, null, handler, limit, hideClosedNoteAfter); }
[ "public", "void", "getAll", "(", "BoundingBox", "bounds", ",", "Handler", "<", "Note", ">", "handler", ",", "int", "limit", ",", "int", "hideClosedNoteAfter", ")", "{", "getAll", "(", "bounds", ",", "null", ",", "handler", ",", "limit", ",", "hideClosedNoteAfter", ")", ";", "}" ]
Retrieve all notes in the given area and feed them to the given handler. @see #getAll(BoundingBox, String, Handler, int, int)
[ "Retrieve", "all", "notes", "in", "the", "given", "area", "and", "feed", "them", "to", "the", "given", "handler", "." ]
train
https://github.com/westnordost/osmapi/blob/dda6978fd12e117d0cf17812bc22037f61e22c4b/src/main/java/de/westnordost/osmapi/notes/NotesDao.java#L172-L175
groupon/monsoon
expr/src/main/java/com/groupon/lex/metrics/timeseries/expression/SumExpression.java
SumExpression.sum_impl_
private static Number sum_impl_(Number x, Number y) { """ /* Calculate the sum of two numbers, preserving integral type if possible. """ if (x instanceof Double || y instanceof Double) return Double.valueOf(x.doubleValue() + y.doubleValue()); else return Long.valueOf(x.longValue() + y.longValue()); }
java
private static Number sum_impl_(Number x, Number y) { if (x instanceof Double || y instanceof Double) return Double.valueOf(x.doubleValue() + y.doubleValue()); else return Long.valueOf(x.longValue() + y.longValue()); }
[ "private", "static", "Number", "sum_impl_", "(", "Number", "x", ",", "Number", "y", ")", "{", "if", "(", "x", "instanceof", "Double", "||", "y", "instanceof", "Double", ")", "return", "Double", ".", "valueOf", "(", "x", ".", "doubleValue", "(", ")", "+", "y", ".", "doubleValue", "(", ")", ")", ";", "else", "return", "Long", ".", "valueOf", "(", "x", ".", "longValue", "(", ")", "+", "y", ".", "longValue", "(", ")", ")", ";", "}" ]
/* Calculate the sum of two numbers, preserving integral type if possible.
[ "/", "*", "Calculate", "the", "sum", "of", "two", "numbers", "preserving", "integral", "type", "if", "possible", "." ]
train
https://github.com/groupon/monsoon/blob/eb68d72ba4c01fe018dc981097dbee033908f5c7/expr/src/main/java/com/groupon/lex/metrics/timeseries/expression/SumExpression.java#L56-L61
goldmansachs/gs-collections
collections/src/main/java/com/gs/collections/impl/utility/MapIterate.java
MapIterate.selectMapOnEntry
public static <K, V, R extends Map<K, V>> R selectMapOnEntry( Map<K, V> map, final Predicate2<? super K, ? super V> predicate, R target) { """ For each <em>entry</em> of the source map, the Predicate2 is evaluated. If the result of the evaluation is true, the map entry is moved to a result map. The result map is returned containing all entries in the source map that evaluated to true. """ final Procedure2<K, V> mapTransferProcedure = new MapPutProcedure<K, V>(target); Procedure2<K, V> procedure = new Procedure2<K, V>() { public void value(K key, V value) { if (predicate.accept(key, value)) { mapTransferProcedure.value(key, value); } } }; MapIterate.forEachKeyValue(map, procedure); return target; }
java
public static <K, V, R extends Map<K, V>> R selectMapOnEntry( Map<K, V> map, final Predicate2<? super K, ? super V> predicate, R target) { final Procedure2<K, V> mapTransferProcedure = new MapPutProcedure<K, V>(target); Procedure2<K, V> procedure = new Procedure2<K, V>() { public void value(K key, V value) { if (predicate.accept(key, value)) { mapTransferProcedure.value(key, value); } } }; MapIterate.forEachKeyValue(map, procedure); return target; }
[ "public", "static", "<", "K", ",", "V", ",", "R", "extends", "Map", "<", "K", ",", "V", ">", ">", "R", "selectMapOnEntry", "(", "Map", "<", "K", ",", "V", ">", "map", ",", "final", "Predicate2", "<", "?", "super", "K", ",", "?", "super", "V", ">", "predicate", ",", "R", "target", ")", "{", "final", "Procedure2", "<", "K", ",", "V", ">", "mapTransferProcedure", "=", "new", "MapPutProcedure", "<", "K", ",", "V", ">", "(", "target", ")", ";", "Procedure2", "<", "K", ",", "V", ">", "procedure", "=", "new", "Procedure2", "<", "K", ",", "V", ">", "(", ")", "{", "public", "void", "value", "(", "K", "key", ",", "V", "value", ")", "{", "if", "(", "predicate", ".", "accept", "(", "key", ",", "value", ")", ")", "{", "mapTransferProcedure", ".", "value", "(", "key", ",", "value", ")", ";", "}", "}", "}", ";", "MapIterate", ".", "forEachKeyValue", "(", "map", ",", "procedure", ")", ";", "return", "target", ";", "}" ]
For each <em>entry</em> of the source map, the Predicate2 is evaluated. If the result of the evaluation is true, the map entry is moved to a result map. The result map is returned containing all entries in the source map that evaluated to true.
[ "For", "each", "<em", ">", "entry<", "/", "em", ">", "of", "the", "source", "map", "the", "Predicate2", "is", "evaluated", ".", "If", "the", "result", "of", "the", "evaluation", "is", "true", "the", "map", "entry", "is", "moved", "to", "a", "result", "map", ".", "The", "result", "map", "is", "returned", "containing", "all", "entries", "in", "the", "source", "map", "that", "evaluated", "to", "true", "." ]
train
https://github.com/goldmansachs/gs-collections/blob/fa8bf3e103689efa18bca2ab70203e71cde34b52/collections/src/main/java/com/gs/collections/impl/utility/MapIterate.java#L296-L315
ThreeTen/threetenbp
src/main/java/org/threeten/bp/ZonedDateTime.java
ZonedDateTime.ofLenient
private static ZonedDateTime ofLenient(LocalDateTime localDateTime, ZoneOffset offset, ZoneId zone) { """ Obtains an instance of {@code ZonedDateTime} leniently, for advanced use cases, allowing any combination of local date-time, offset and zone ID. <p> This creates a zoned date-time with no checks other than no nulls. This means that the resulting zoned date-time may have an offset that is in conflict with the zone ID. <p> This method is intended for advanced use cases. For example, consider the case where a zoned date-time with valid fields is created and then stored in a database or serialization-based store. At some later point, the object is then re-loaded. However, between those points in time, the government that defined the time-zone has changed the rules, such that the originally stored local date-time now does not occur. This method can be used to create the object in an "invalid" state, despite the change in rules. @param localDateTime the local date-time, not null @param offset the zone offset, not null @param zone the time-zone, not null @return the zoned date-time, not null """ Jdk8Methods.requireNonNull(localDateTime, "localDateTime"); Jdk8Methods.requireNonNull(offset, "offset"); Jdk8Methods.requireNonNull(zone, "zone"); if (zone instanceof ZoneOffset && offset.equals(zone) == false) { throw new IllegalArgumentException("ZoneId must match ZoneOffset"); } return new ZonedDateTime(localDateTime, offset, zone); }
java
private static ZonedDateTime ofLenient(LocalDateTime localDateTime, ZoneOffset offset, ZoneId zone) { Jdk8Methods.requireNonNull(localDateTime, "localDateTime"); Jdk8Methods.requireNonNull(offset, "offset"); Jdk8Methods.requireNonNull(zone, "zone"); if (zone instanceof ZoneOffset && offset.equals(zone) == false) { throw new IllegalArgumentException("ZoneId must match ZoneOffset"); } return new ZonedDateTime(localDateTime, offset, zone); }
[ "private", "static", "ZonedDateTime", "ofLenient", "(", "LocalDateTime", "localDateTime", ",", "ZoneOffset", "offset", ",", "ZoneId", "zone", ")", "{", "Jdk8Methods", ".", "requireNonNull", "(", "localDateTime", ",", "\"localDateTime\"", ")", ";", "Jdk8Methods", ".", "requireNonNull", "(", "offset", ",", "\"offset\"", ")", ";", "Jdk8Methods", ".", "requireNonNull", "(", "zone", ",", "\"zone\"", ")", ";", "if", "(", "zone", "instanceof", "ZoneOffset", "&&", "offset", ".", "equals", "(", "zone", ")", "==", "false", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"ZoneId must match ZoneOffset\"", ")", ";", "}", "return", "new", "ZonedDateTime", "(", "localDateTime", ",", "offset", ",", "zone", ")", ";", "}" ]
Obtains an instance of {@code ZonedDateTime} leniently, for advanced use cases, allowing any combination of local date-time, offset and zone ID. <p> This creates a zoned date-time with no checks other than no nulls. This means that the resulting zoned date-time may have an offset that is in conflict with the zone ID. <p> This method is intended for advanced use cases. For example, consider the case where a zoned date-time with valid fields is created and then stored in a database or serialization-based store. At some later point, the object is then re-loaded. However, between those points in time, the government that defined the time-zone has changed the rules, such that the originally stored local date-time now does not occur. This method can be used to create the object in an "invalid" state, despite the change in rules. @param localDateTime the local date-time, not null @param offset the zone offset, not null @param zone the time-zone, not null @return the zoned date-time, not null
[ "Obtains", "an", "instance", "of", "{", "@code", "ZonedDateTime", "}", "leniently", "for", "advanced", "use", "cases", "allowing", "any", "combination", "of", "local", "date", "-", "time", "offset", "and", "zone", "ID", ".", "<p", ">", "This", "creates", "a", "zoned", "date", "-", "time", "with", "no", "checks", "other", "than", "no", "nulls", ".", "This", "means", "that", "the", "resulting", "zoned", "date", "-", "time", "may", "have", "an", "offset", "that", "is", "in", "conflict", "with", "the", "zone", "ID", ".", "<p", ">", "This", "method", "is", "intended", "for", "advanced", "use", "cases", ".", "For", "example", "consider", "the", "case", "where", "a", "zoned", "date", "-", "time", "with", "valid", "fields", "is", "created", "and", "then", "stored", "in", "a", "database", "or", "serialization", "-", "based", "store", ".", "At", "some", "later", "point", "the", "object", "is", "then", "re", "-", "loaded", ".", "However", "between", "those", "points", "in", "time", "the", "government", "that", "defined", "the", "time", "-", "zone", "has", "changed", "the", "rules", "such", "that", "the", "originally", "stored", "local", "date", "-", "time", "now", "does", "not", "occur", ".", "This", "method", "can", "be", "used", "to", "create", "the", "object", "in", "an", "invalid", "state", "despite", "the", "change", "in", "rules", "." ]
train
https://github.com/ThreeTen/threetenbp/blob/5f05b649f89f205aabd96b2f83c36796ec616fe6/src/main/java/org/threeten/bp/ZonedDateTime.java#L481-L489
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/BooleanUtils.java
BooleanUtils.toIntegerObject
public static Integer toIntegerObject(final boolean bool, final Integer trueValue, final Integer falseValue) { """ <p>Converts a boolean to an Integer specifying the conversion values.</p> <pre> BooleanUtils.toIntegerObject(true, Integer.valueOf(1), Integer.valueOf(0)) = Integer.valueOf(1) BooleanUtils.toIntegerObject(false, Integer.valueOf(1), Integer.valueOf(0)) = Integer.valueOf(0) </pre> @param bool the to convert @param trueValue the value to return if {@code true}, may be {@code null} @param falseValue the value to return if {@code false}, may be {@code null} @return the appropriate value """ return bool ? trueValue : falseValue; }
java
public static Integer toIntegerObject(final boolean bool, final Integer trueValue, final Integer falseValue) { return bool ? trueValue : falseValue; }
[ "public", "static", "Integer", "toIntegerObject", "(", "final", "boolean", "bool", ",", "final", "Integer", "trueValue", ",", "final", "Integer", "falseValue", ")", "{", "return", "bool", "?", "trueValue", ":", "falseValue", ";", "}" ]
<p>Converts a boolean to an Integer specifying the conversion values.</p> <pre> BooleanUtils.toIntegerObject(true, Integer.valueOf(1), Integer.valueOf(0)) = Integer.valueOf(1) BooleanUtils.toIntegerObject(false, Integer.valueOf(1), Integer.valueOf(0)) = Integer.valueOf(0) </pre> @param bool the to convert @param trueValue the value to return if {@code true}, may be {@code null} @param falseValue the value to return if {@code false}, may be {@code null} @return the appropriate value
[ "<p", ">", "Converts", "a", "boolean", "to", "an", "Integer", "specifying", "the", "conversion", "values", ".", "<", "/", "p", ">" ]
train
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/BooleanUtils.java#L484-L486
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/zip/GZIPOutputStream.java
GZIPOutputStream.writeTrailer
private void writeTrailer(byte[] buf, int offset) throws IOException { """ /* Writes GZIP member trailer to a byte array, starting at a given offset. """ writeInt((int)crc.getValue(), buf, offset); // CRC-32 of uncompr. data writeInt(def.getTotalIn(), buf, offset + 4); // Number of uncompr. bytes }
java
private void writeTrailer(byte[] buf, int offset) throws IOException { writeInt((int)crc.getValue(), buf, offset); // CRC-32 of uncompr. data writeInt(def.getTotalIn(), buf, offset + 4); // Number of uncompr. bytes }
[ "private", "void", "writeTrailer", "(", "byte", "[", "]", "buf", ",", "int", "offset", ")", "throws", "IOException", "{", "writeInt", "(", "(", "int", ")", "crc", ".", "getValue", "(", ")", ",", "buf", ",", "offset", ")", ";", "// CRC-32 of uncompr. data", "writeInt", "(", "def", ".", "getTotalIn", "(", ")", ",", "buf", ",", "offset", "+", "4", ")", ";", "// Number of uncompr. bytes", "}" ]
/* Writes GZIP member trailer to a byte array, starting at a given offset.
[ "/", "*", "Writes", "GZIP", "member", "trailer", "to", "a", "byte", "array", "starting", "at", "a", "given", "offset", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/zip/GZIPOutputStream.java#L200-L203
Impetus/Kundera
src/jpa-engine/core/src/main/java/com/impetus/kundera/cache/ElementCollectionCacheManager.java
ElementCollectionCacheManager.getLastElementCollectionObjectCount
public int getLastElementCollectionObjectCount(Object rowKey) { """ Gets the last element collection object count. @param rowKey the row key @return the last element collection object count """ if (getElementCollectionCache().get(rowKey) == null) { log.debug("No element collection object map found in cache for Row key " + rowKey); return -1; } else { Map<Object, String> elementCollectionMap = getElementCollectionCache().get(rowKey); Collection<String> elementCollectionObjectNames = elementCollectionMap.values(); int max = 0; for (String s : elementCollectionObjectNames) { String elementCollectionCountStr = s.substring(s.indexOf(Constants.EMBEDDED_COLUMN_NAME_DELIMITER) + 1); int elementCollectionCount = 0; try { elementCollectionCount = Integer.parseInt(elementCollectionCountStr); } catch (NumberFormatException e) { log.error("Invalid element collection Object name " + s); throw new CacheException("Invalid element collection Object name " + s,e); } if (elementCollectionCount > max) { max = elementCollectionCount; } } return max; } }
java
public int getLastElementCollectionObjectCount(Object rowKey) { if (getElementCollectionCache().get(rowKey) == null) { log.debug("No element collection object map found in cache for Row key " + rowKey); return -1; } else { Map<Object, String> elementCollectionMap = getElementCollectionCache().get(rowKey); Collection<String> elementCollectionObjectNames = elementCollectionMap.values(); int max = 0; for (String s : elementCollectionObjectNames) { String elementCollectionCountStr = s.substring(s.indexOf(Constants.EMBEDDED_COLUMN_NAME_DELIMITER) + 1); int elementCollectionCount = 0; try { elementCollectionCount = Integer.parseInt(elementCollectionCountStr); } catch (NumberFormatException e) { log.error("Invalid element collection Object name " + s); throw new CacheException("Invalid element collection Object name " + s,e); } if (elementCollectionCount > max) { max = elementCollectionCount; } } return max; } }
[ "public", "int", "getLastElementCollectionObjectCount", "(", "Object", "rowKey", ")", "{", "if", "(", "getElementCollectionCache", "(", ")", ".", "get", "(", "rowKey", ")", "==", "null", ")", "{", "log", ".", "debug", "(", "\"No element collection object map found in cache for Row key \"", "+", "rowKey", ")", ";", "return", "-", "1", ";", "}", "else", "{", "Map", "<", "Object", ",", "String", ">", "elementCollectionMap", "=", "getElementCollectionCache", "(", ")", ".", "get", "(", "rowKey", ")", ";", "Collection", "<", "String", ">", "elementCollectionObjectNames", "=", "elementCollectionMap", ".", "values", "(", ")", ";", "int", "max", "=", "0", ";", "for", "(", "String", "s", ":", "elementCollectionObjectNames", ")", "{", "String", "elementCollectionCountStr", "=", "s", ".", "substring", "(", "s", ".", "indexOf", "(", "Constants", ".", "EMBEDDED_COLUMN_NAME_DELIMITER", ")", "+", "1", ")", ";", "int", "elementCollectionCount", "=", "0", ";", "try", "{", "elementCollectionCount", "=", "Integer", ".", "parseInt", "(", "elementCollectionCountStr", ")", ";", "}", "catch", "(", "NumberFormatException", "e", ")", "{", "log", ".", "error", "(", "\"Invalid element collection Object name \"", "+", "s", ")", ";", "throw", "new", "CacheException", "(", "\"Invalid element collection Object name \"", "+", "s", ",", "e", ")", ";", "}", "if", "(", "elementCollectionCount", ">", "max", ")", "{", "max", "=", "elementCollectionCount", ";", "}", "}", "return", "max", ";", "}", "}" ]
Gets the last element collection object count. @param rowKey the row key @return the last element collection object count
[ "Gets", "the", "last", "element", "collection", "object", "count", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/jpa-engine/core/src/main/java/com/impetus/kundera/cache/ElementCollectionCacheManager.java#L174-L207
Azure/azure-sdk-for-java
labservices/resource-manager/v2018_10_15/src/main/java/com/microsoft/azure/management/labservices/v2018_10_15/implementation/GlobalUsersInner.java
GlobalUsersInner.resetPasswordAsync
public Observable<Void> resetPasswordAsync(String userName, ResetPasswordPayload resetPasswordPayload) { """ Resets the user password on an environment This operation can take a while to complete. @param userName The name of the user. @param resetPasswordPayload Represents the payload for resetting passwords. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request """ return resetPasswordWithServiceResponseAsync(userName, resetPasswordPayload).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); }
java
public Observable<Void> resetPasswordAsync(String userName, ResetPasswordPayload resetPasswordPayload) { return resetPasswordWithServiceResponseAsync(userName, resetPasswordPayload).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Void", ">", "resetPasswordAsync", "(", "String", "userName", ",", "ResetPasswordPayload", "resetPasswordPayload", ")", "{", "return", "resetPasswordWithServiceResponseAsync", "(", "userName", ",", "resetPasswordPayload", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "Void", ">", ",", "Void", ">", "(", ")", "{", "@", "Override", "public", "Void", "call", "(", "ServiceResponse", "<", "Void", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Resets the user password on an environment This operation can take a while to complete. @param userName The name of the user. @param resetPasswordPayload Represents the payload for resetting passwords. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Resets", "the", "user", "password", "on", "an", "environment", "This", "operation", "can", "take", "a", "while", "to", "complete", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/labservices/resource-manager/v2018_10_15/src/main/java/com/microsoft/azure/management/labservices/v2018_10_15/implementation/GlobalUsersInner.java#L957-L964
brunocvcunha/inutils4j
src/main/java/org/brunocvcunha/inutils4j/MyStringUtils.java
MyStringUtils.getLine
public static String getLine(String content, int line) { """ Gets a specific line of a text (String) @param content text @param line line to get @return the specified line """ if (content == null) { return null; } String[] contentSplit = content.replace("\r\n", "\n").split("\n"); if (contentSplit.length < line) { return null; } return contentSplit[line - 1]; }
java
public static String getLine(String content, int line) { if (content == null) { return null; } String[] contentSplit = content.replace("\r\n", "\n").split("\n"); if (contentSplit.length < line) { return null; } return contentSplit[line - 1]; }
[ "public", "static", "String", "getLine", "(", "String", "content", ",", "int", "line", ")", "{", "if", "(", "content", "==", "null", ")", "{", "return", "null", ";", "}", "String", "[", "]", "contentSplit", "=", "content", ".", "replace", "(", "\"\\r\\n\"", ",", "\"\\n\"", ")", ".", "split", "(", "\"\\n\"", ")", ";", "if", "(", "contentSplit", ".", "length", "<", "line", ")", "{", "return", "null", ";", "}", "return", "contentSplit", "[", "line", "-", "1", "]", ";", "}" ]
Gets a specific line of a text (String) @param content text @param line line to get @return the specified line
[ "Gets", "a", "specific", "line", "of", "a", "text", "(", "String", ")" ]
train
https://github.com/brunocvcunha/inutils4j/blob/223c4443c2cee662576ce644e552588fa114aa94/src/main/java/org/brunocvcunha/inutils4j/MyStringUtils.java#L471-L482
zaproxy/zaproxy
src/org/zaproxy/zap/extension/pscan/ExtensionPassiveScan.java
ExtensionPassiveScan.setPluginPassiveScannerEnabled
void setPluginPassiveScannerEnabled(int pluginId, boolean enabled) { """ Sets whether or not the plug-in passive scanner with the given {@code pluginId} is {@code enabled}. @param pluginId the ID of the plug-in passive scanner @param enabled {@code true} if the scanner should be enabled, {@code false} otherwise """ PluginPassiveScanner scanner = getPluginPassiveScanner(pluginId); if (scanner != null) { scanner.setEnabled(enabled); scanner.save(); } }
java
void setPluginPassiveScannerEnabled(int pluginId, boolean enabled) { PluginPassiveScanner scanner = getPluginPassiveScanner(pluginId); if (scanner != null) { scanner.setEnabled(enabled); scanner.save(); } }
[ "void", "setPluginPassiveScannerEnabled", "(", "int", "pluginId", ",", "boolean", "enabled", ")", "{", "PluginPassiveScanner", "scanner", "=", "getPluginPassiveScanner", "(", "pluginId", ")", ";", "if", "(", "scanner", "!=", "null", ")", "{", "scanner", ".", "setEnabled", "(", "enabled", ")", ";", "scanner", ".", "save", "(", ")", ";", "}", "}" ]
Sets whether or not the plug-in passive scanner with the given {@code pluginId} is {@code enabled}. @param pluginId the ID of the plug-in passive scanner @param enabled {@code true} if the scanner should be enabled, {@code false} otherwise
[ "Sets", "whether", "or", "not", "the", "plug", "-", "in", "passive", "scanner", "with", "the", "given", "{", "@code", "pluginId", "}", "is", "{", "@code", "enabled", "}", "." ]
train
https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/extension/pscan/ExtensionPassiveScan.java#L342-L348
elki-project/elki
elki-docutil/src/main/java/de/lmu/ifi/dbs/elki/utilities/xml/HTMLUtil.java
HTMLUtil.writeXHTML
public static void writeXHTML(Document htmldoc, OutputStream out) throws IOException { """ Write an HTML document to an output stream. @param htmldoc Document to output @param out Stream to write to @throws IOException thrown on IO errors """ javax.xml.transform.Result result = new StreamResult(out); // Use a transformer for pretty printing Transformer xformer; try { xformer = TransformerFactory.newInstance().newTransformer(); xformer.setOutputProperty(OutputKeys.INDENT, "yes"); // TODO: ensure the "meta" tag doesn't claim a different encoding! xformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); xformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, HTML_XHTML_TRANSITIONAL_DOCTYPE_PUBLIC); xformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, HTML_XHTML_TRANSITIONAL_DOCTYPE_SYSTEM); xformer.transform(new DOMSource(htmldoc), result); } catch(TransformerException e1) { throw new IOException(e1); } out.flush(); }
java
public static void writeXHTML(Document htmldoc, OutputStream out) throws IOException { javax.xml.transform.Result result = new StreamResult(out); // Use a transformer for pretty printing Transformer xformer; try { xformer = TransformerFactory.newInstance().newTransformer(); xformer.setOutputProperty(OutputKeys.INDENT, "yes"); // TODO: ensure the "meta" tag doesn't claim a different encoding! xformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); xformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, HTML_XHTML_TRANSITIONAL_DOCTYPE_PUBLIC); xformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, HTML_XHTML_TRANSITIONAL_DOCTYPE_SYSTEM); xformer.transform(new DOMSource(htmldoc), result); } catch(TransformerException e1) { throw new IOException(e1); } out.flush(); }
[ "public", "static", "void", "writeXHTML", "(", "Document", "htmldoc", ",", "OutputStream", "out", ")", "throws", "IOException", "{", "javax", ".", "xml", ".", "transform", ".", "Result", "result", "=", "new", "StreamResult", "(", "out", ")", ";", "// Use a transformer for pretty printing", "Transformer", "xformer", ";", "try", "{", "xformer", "=", "TransformerFactory", ".", "newInstance", "(", ")", ".", "newTransformer", "(", ")", ";", "xformer", ".", "setOutputProperty", "(", "OutputKeys", ".", "INDENT", ",", "\"yes\"", ")", ";", "// TODO: ensure the \"meta\" tag doesn't claim a different encoding!", "xformer", ".", "setOutputProperty", "(", "OutputKeys", ".", "ENCODING", ",", "\"UTF-8\"", ")", ";", "xformer", ".", "setOutputProperty", "(", "OutputKeys", ".", "DOCTYPE_PUBLIC", ",", "HTML_XHTML_TRANSITIONAL_DOCTYPE_PUBLIC", ")", ";", "xformer", ".", "setOutputProperty", "(", "OutputKeys", ".", "DOCTYPE_SYSTEM", ",", "HTML_XHTML_TRANSITIONAL_DOCTYPE_SYSTEM", ")", ";", "xformer", ".", "transform", "(", "new", "DOMSource", "(", "htmldoc", ")", ",", "result", ")", ";", "}", "catch", "(", "TransformerException", "e1", ")", "{", "throw", "new", "IOException", "(", "e1", ")", ";", "}", "out", ".", "flush", "(", ")", ";", "}" ]
Write an HTML document to an output stream. @param htmldoc Document to output @param out Stream to write to @throws IOException thrown on IO errors
[ "Write", "an", "HTML", "document", "to", "an", "output", "stream", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-docutil/src/main/java/de/lmu/ifi/dbs/elki/utilities/xml/HTMLUtil.java#L267-L284
ckpoint/CheckPoint
src/main/java/hsim/checkpoint/core/store/ValidationStore.java
ValidationStore.getValidationDatas
public List<ValidationData> getValidationDatas(ParamType paramType, String key) { """ Gets validation datas. @param paramType the param type @param key the key @return the validation datas """ if (this.urlMap == null || this.validationDataRuleListMap == null) { log.info("url map is empty :: " + key ); return null; } if (key == null || paramType == null) { throw new ValidationLibException("any parameter is null", HttpStatus.INTERNAL_SERVER_ERROR); } ReqUrl reqUrl = urlMap.get(key); if (reqUrl == null) { log.info("reqUrl is null :" + key); return null; } return validationDataRuleListMap.get(paramType.getUniqueKey(reqUrl.getUniqueKey())); }
java
public List<ValidationData> getValidationDatas(ParamType paramType, String key) { if (this.urlMap == null || this.validationDataRuleListMap == null) { log.info("url map is empty :: " + key ); return null; } if (key == null || paramType == null) { throw new ValidationLibException("any parameter is null", HttpStatus.INTERNAL_SERVER_ERROR); } ReqUrl reqUrl = urlMap.get(key); if (reqUrl == null) { log.info("reqUrl is null :" + key); return null; } return validationDataRuleListMap.get(paramType.getUniqueKey(reqUrl.getUniqueKey())); }
[ "public", "List", "<", "ValidationData", ">", "getValidationDatas", "(", "ParamType", "paramType", ",", "String", "key", ")", "{", "if", "(", "this", ".", "urlMap", "==", "null", "||", "this", ".", "validationDataRuleListMap", "==", "null", ")", "{", "log", ".", "info", "(", "\"url map is empty :: \"", "+", "key", ")", ";", "return", "null", ";", "}", "if", "(", "key", "==", "null", "||", "paramType", "==", "null", ")", "{", "throw", "new", "ValidationLibException", "(", "\"any parameter is null\"", ",", "HttpStatus", ".", "INTERNAL_SERVER_ERROR", ")", ";", "}", "ReqUrl", "reqUrl", "=", "urlMap", ".", "get", "(", "key", ")", ";", "if", "(", "reqUrl", "==", "null", ")", "{", "log", ".", "info", "(", "\"reqUrl is null :\"", "+", "key", ")", ";", "return", "null", ";", "}", "return", "validationDataRuleListMap", ".", "get", "(", "paramType", ".", "getUniqueKey", "(", "reqUrl", ".", "getUniqueKey", "(", ")", ")", ")", ";", "}" ]
Gets validation datas. @param paramType the param type @param key the key @return the validation datas
[ "Gets", "validation", "datas", "." ]
train
https://github.com/ckpoint/CheckPoint/blob/2c2b1a87a88485d49ea6afa34acdf16ef4134f19/src/main/java/hsim/checkpoint/core/store/ValidationStore.java#L83-L100
VoltDB/voltdb
src/frontend/org/voltdb/compiler/VoltCompiler.java
VoltCompiler.compileFromDDL
public boolean compileFromDDL(final String jarOutputPath, final String... ddlFilePaths) { """ Compile from a set of DDL files. @param jarOutputPath The location to put the finished JAR to. @param ddlFilePaths The array of DDL files to compile (at least one is required). @return true if successful @throws VoltCompilerException """ if (ddlFilePaths.length == 0) { compilerLog.error("At least one DDL file is required."); return false; } List<VoltCompilerReader> ddlReaderList; try { ddlReaderList = DDLPathsToReaderList(ddlFilePaths); } catch (VoltCompilerException e) { compilerLog.error("Unable to open DDL file.", e); return false; } return compileInternalToFile(jarOutputPath, null, null, ddlReaderList, null); }
java
public boolean compileFromDDL(final String jarOutputPath, final String... ddlFilePaths) { if (ddlFilePaths.length == 0) { compilerLog.error("At least one DDL file is required."); return false; } List<VoltCompilerReader> ddlReaderList; try { ddlReaderList = DDLPathsToReaderList(ddlFilePaths); } catch (VoltCompilerException e) { compilerLog.error("Unable to open DDL file.", e); return false; } return compileInternalToFile(jarOutputPath, null, null, ddlReaderList, null); }
[ "public", "boolean", "compileFromDDL", "(", "final", "String", "jarOutputPath", ",", "final", "String", "...", "ddlFilePaths", ")", "{", "if", "(", "ddlFilePaths", ".", "length", "==", "0", ")", "{", "compilerLog", ".", "error", "(", "\"At least one DDL file is required.\"", ")", ";", "return", "false", ";", "}", "List", "<", "VoltCompilerReader", ">", "ddlReaderList", ";", "try", "{", "ddlReaderList", "=", "DDLPathsToReaderList", "(", "ddlFilePaths", ")", ";", "}", "catch", "(", "VoltCompilerException", "e", ")", "{", "compilerLog", ".", "error", "(", "\"Unable to open DDL file.\"", ",", "e", ")", ";", "return", "false", ";", "}", "return", "compileInternalToFile", "(", "jarOutputPath", ",", "null", ",", "null", ",", "ddlReaderList", ",", "null", ")", ";", "}" ]
Compile from a set of DDL files. @param jarOutputPath The location to put the finished JAR to. @param ddlFilePaths The array of DDL files to compile (at least one is required). @return true if successful @throws VoltCompilerException
[ "Compile", "from", "a", "set", "of", "DDL", "files", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/compiler/VoltCompiler.java#L514-L528
xwiki/xwiki-rendering
xwiki-rendering-xml/src/main/java/org/xwiki/rendering/renderer/printer/XMLWikiPrinter.java
XMLWikiPrinter.printXMLComment
public void printXMLComment(String content, boolean escape) { """ Print a XML comment. @param content the comment content @param escape indicate if comment content has to be escaped. XML content does not support -- and - (when it's the last character). Escaping is based on backslash. "- --\ -" give "- \-\-\\ \-\ ". """ try { this.xmlWriter.write(new DefaultComment(escape ? XMLUtils.escapeXMLComment(content) : content)); } catch (IOException e) { // TODO: add error log here } }
java
public void printXMLComment(String content, boolean escape) { try { this.xmlWriter.write(new DefaultComment(escape ? XMLUtils.escapeXMLComment(content) : content)); } catch (IOException e) { // TODO: add error log here } }
[ "public", "void", "printXMLComment", "(", "String", "content", ",", "boolean", "escape", ")", "{", "try", "{", "this", ".", "xmlWriter", ".", "write", "(", "new", "DefaultComment", "(", "escape", "?", "XMLUtils", ".", "escapeXMLComment", "(", "content", ")", ":", "content", ")", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "// TODO: add error log here", "}", "}" ]
Print a XML comment. @param content the comment content @param escape indicate if comment content has to be escaped. XML content does not support -- and - (when it's the last character). Escaping is based on backslash. "- --\ -" give "- \-\-\\ \-\ ".
[ "Print", "a", "XML", "comment", "." ]
train
https://github.com/xwiki/xwiki-rendering/blob/a21cdfcb64ef5b76872e3eedf78c530f26d7beb0/xwiki-rendering-xml/src/main/java/org/xwiki/rendering/renderer/printer/XMLWikiPrinter.java#L219-L226
shrinkwrap/descriptors
metadata-parser/src/main/java/org/jboss/shrinkwrap/descriptor/metadata/MetadataUtil.java
MetadataUtil.getNextParentNodeWithAttr
public static Node getNextParentNodeWithAttr(final Node parent, final String attrName) { """ Returns the next parent node which has the specific attribute name defined. @param parent the w3c node from which the search will start. @param attrName the attribute name which is searched for. @return a parent node, if the attribute is found, otherwise null. """ Node parentNode = parent; Element parendElement = (Element) parentNode; Node valueNode = parendElement.getAttributes().getNamedItem(attrName); while (valueNode == null) { parentNode = parentNode.getParentNode(); if (parentNode != null) { if (parentNode.getNodeType() == Node.ELEMENT_NODE) { parendElement = (Element) parentNode; valueNode = parendElement.getAttributes().getNamedItem(attrName); } } else { break; } } return parendElement; }
java
public static Node getNextParentNodeWithAttr(final Node parent, final String attrName) { Node parentNode = parent; Element parendElement = (Element) parentNode; Node valueNode = parendElement.getAttributes().getNamedItem(attrName); while (valueNode == null) { parentNode = parentNode.getParentNode(); if (parentNode != null) { if (parentNode.getNodeType() == Node.ELEMENT_NODE) { parendElement = (Element) parentNode; valueNode = parendElement.getAttributes().getNamedItem(attrName); } } else { break; } } return parendElement; }
[ "public", "static", "Node", "getNextParentNodeWithAttr", "(", "final", "Node", "parent", ",", "final", "String", "attrName", ")", "{", "Node", "parentNode", "=", "parent", ";", "Element", "parendElement", "=", "(", "Element", ")", "parentNode", ";", "Node", "valueNode", "=", "parendElement", ".", "getAttributes", "(", ")", ".", "getNamedItem", "(", "attrName", ")", ";", "while", "(", "valueNode", "==", "null", ")", "{", "parentNode", "=", "parentNode", ".", "getParentNode", "(", ")", ";", "if", "(", "parentNode", "!=", "null", ")", "{", "if", "(", "parentNode", ".", "getNodeType", "(", ")", "==", "Node", ".", "ELEMENT_NODE", ")", "{", "parendElement", "=", "(", "Element", ")", "parentNode", ";", "valueNode", "=", "parendElement", ".", "getAttributes", "(", ")", ".", "getNamedItem", "(", "attrName", ")", ";", "}", "}", "else", "{", "break", ";", "}", "}", "return", "parendElement", ";", "}" ]
Returns the next parent node which has the specific attribute name defined. @param parent the w3c node from which the search will start. @param attrName the attribute name which is searched for. @return a parent node, if the attribute is found, otherwise null.
[ "Returns", "the", "next", "parent", "node", "which", "has", "the", "specific", "attribute", "name", "defined", "." ]
train
https://github.com/shrinkwrap/descriptors/blob/023ba080e6396b9f4dd8275dc4e5c0ebb6b5e6ba/metadata-parser/src/main/java/org/jboss/shrinkwrap/descriptor/metadata/MetadataUtil.java#L64-L81
Stratio/deep-spark
deep-cassandra/src/main/java/com/stratio/deep/cassandra/entity/CassandraCell.java
CassandraCell.create
public static Cell create(String cellName) { """ Factory method, builds a new CassandraCell (isPartitionKey = false and isClusterKey = false) with value = null. The validator will be automatically calculated using the value object type. @param cellName the cell name @return an instance of a Cell object for the provided parameters. """ return create(cellName, (Object) null, Boolean.FALSE, Boolean.FALSE); }
java
public static Cell create(String cellName) { return create(cellName, (Object) null, Boolean.FALSE, Boolean.FALSE); }
[ "public", "static", "Cell", "create", "(", "String", "cellName", ")", "{", "return", "create", "(", "cellName", ",", "(", "Object", ")", "null", ",", "Boolean", ".", "FALSE", ",", "Boolean", ".", "FALSE", ")", ";", "}" ]
Factory method, builds a new CassandraCell (isPartitionKey = false and isClusterKey = false) with value = null. The validator will be automatically calculated using the value object type. @param cellName the cell name @return an instance of a Cell object for the provided parameters.
[ "Factory", "method", "builds", "a", "new", "CassandraCell", "(", "isPartitionKey", "=", "false", "and", "isClusterKey", "=", "false", ")", "with", "value", "=", "null", ".", "The", "validator", "will", "be", "automatically", "calculated", "using", "the", "value", "object", "type", "." ]
train
https://github.com/Stratio/deep-spark/blob/b9621c9b7a6d996f80fce1d073d696a157bed095/deep-cassandra/src/main/java/com/stratio/deep/cassandra/entity/CassandraCell.java#L83-L85
kiegroup/droolsjbpm-integration
kie-server-parent/kie-server-remote/kie-server-client/src/main/java/org/kie/server/client/KieServicesFactory.java
KieServicesFactory.newJMSConfiguration
public static KieServicesConfiguration newJMSConfiguration( ConnectionFactory connectionFactory, Queue requestQueue, Queue responseQueue) { """ Creates a new configuration object for JMS based service @param connectionFactory a JMS connection factory @param requestQueue a reference to the requests queue @param responseQueue a reference to the responses queue @return configuration instance """ return new KieServicesConfigurationImpl( connectionFactory, requestQueue, responseQueue ); }
java
public static KieServicesConfiguration newJMSConfiguration( ConnectionFactory connectionFactory, Queue requestQueue, Queue responseQueue) { return new KieServicesConfigurationImpl( connectionFactory, requestQueue, responseQueue ); }
[ "public", "static", "KieServicesConfiguration", "newJMSConfiguration", "(", "ConnectionFactory", "connectionFactory", ",", "Queue", "requestQueue", ",", "Queue", "responseQueue", ")", "{", "return", "new", "KieServicesConfigurationImpl", "(", "connectionFactory", ",", "requestQueue", ",", "responseQueue", ")", ";", "}" ]
Creates a new configuration object for JMS based service @param connectionFactory a JMS connection factory @param requestQueue a reference to the requests queue @param responseQueue a reference to the responses queue @return configuration instance
[ "Creates", "a", "new", "configuration", "object", "for", "JMS", "based", "service" ]
train
https://github.com/kiegroup/droolsjbpm-integration/blob/6c26200ab03855dbb92b56ca0c6363cdec0eaf2c/kie-server-parent/kie-server-remote/kie-server-client/src/main/java/org/kie/server/client/KieServicesFactory.java#L66-L68
DataSketches/sketches-core
src/main/java/com/yahoo/sketches/sampling/VarOptItemsSketch.java
VarOptItemsSketch.updateHeavyREq1
private void updateHeavyREq1(final T item, final double weight, final boolean mark) { """ /* The analysis of this case is similar to that of the general heavy case. The one small technical difference is that since R < 2, we must grab an M item to have a valid starting point for continue_by_growing_candidate_set () """ assert m_ == 0; assert r_ == 1; assert (r_ + h_) == k_; push(item, weight, mark); // new item into H popMinToMRegion(); // pop lightest back into M // Any set of two items is downsample-able to one item, // so the two lightest items are a valid starting point for the following final int mSlot = k_ - 1; // array is k+1, 1 in R, so slot before is M growCandidateSet(weights_.get(mSlot) + totalWtR_, 2); }
java
private void updateHeavyREq1(final T item, final double weight, final boolean mark) { assert m_ == 0; assert r_ == 1; assert (r_ + h_) == k_; push(item, weight, mark); // new item into H popMinToMRegion(); // pop lightest back into M // Any set of two items is downsample-able to one item, // so the two lightest items are a valid starting point for the following final int mSlot = k_ - 1; // array is k+1, 1 in R, so slot before is M growCandidateSet(weights_.get(mSlot) + totalWtR_, 2); }
[ "private", "void", "updateHeavyREq1", "(", "final", "T", "item", ",", "final", "double", "weight", ",", "final", "boolean", "mark", ")", "{", "assert", "m_", "==", "0", ";", "assert", "r_", "==", "1", ";", "assert", "(", "r_", "+", "h_", ")", "==", "k_", ";", "push", "(", "item", ",", "weight", ",", "mark", ")", ";", "// new item into H", "popMinToMRegion", "(", ")", ";", "// pop lightest back into M", "// Any set of two items is downsample-able to one item,", "// so the two lightest items are a valid starting point for the following", "final", "int", "mSlot", "=", "k_", "-", "1", ";", "// array is k+1, 1 in R, so slot before is M", "growCandidateSet", "(", "weights_", ".", "get", "(", "mSlot", ")", "+", "totalWtR_", ",", "2", ")", ";", "}" ]
/* The analysis of this case is similar to that of the general heavy case. The one small technical difference is that since R < 2, we must grab an M item to have a valid starting point for continue_by_growing_candidate_set ()
[ "/", "*", "The", "analysis", "of", "this", "case", "is", "similar", "to", "that", "of", "the", "general", "heavy", "case", ".", "The", "one", "small", "technical", "difference", "is", "that", "since", "R", "<", "2", "we", "must", "grab", "an", "M", "item", "to", "have", "a", "valid", "starting", "point", "for", "continue_by_growing_candidate_set", "()" ]
train
https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/sampling/VarOptItemsSketch.java#L937-L949
alkacon/opencms-core
src-gwt/org/opencms/gwt/client/util/CmsToolTipHandler.java
CmsToolTipHandler.setToolTipPosition
private void setToolTipPosition(int clientLeft, int clientTop) { """ Sets the tool-tip position.<p> @param clientLeft the mouse pointer left position relative to the client window @param clientTop the mouse pointer top position relative to the client window """ if (m_toolTip != null) { int height = m_toolTip.getOffsetHeight(); int width = m_toolTip.getOffsetWidth(); int windowHeight = Window.getClientHeight(); int windowWidth = Window.getClientWidth(); int scrollLeft = Window.getScrollLeft(); int scrollTop = Window.getScrollTop(); int left = clientLeft + scrollLeft + m_offsetLeft; if ((left + width) > (windowWidth + scrollLeft)) { left = (windowWidth + scrollLeft) - m_offsetLeft - width; } m_toolTip.getStyle().setLeft(left, Unit.PX); int top = clientTop + scrollTop + m_offsetTop; if (((top + height) > (windowHeight + scrollTop)) && ((height + m_offsetTop) < clientTop)) { top = (clientTop + scrollTop) - m_offsetTop - height; } m_toolTip.getStyle().setTop(top, Unit.PX); } }
java
private void setToolTipPosition(int clientLeft, int clientTop) { if (m_toolTip != null) { int height = m_toolTip.getOffsetHeight(); int width = m_toolTip.getOffsetWidth(); int windowHeight = Window.getClientHeight(); int windowWidth = Window.getClientWidth(); int scrollLeft = Window.getScrollLeft(); int scrollTop = Window.getScrollTop(); int left = clientLeft + scrollLeft + m_offsetLeft; if ((left + width) > (windowWidth + scrollLeft)) { left = (windowWidth + scrollLeft) - m_offsetLeft - width; } m_toolTip.getStyle().setLeft(left, Unit.PX); int top = clientTop + scrollTop + m_offsetTop; if (((top + height) > (windowHeight + scrollTop)) && ((height + m_offsetTop) < clientTop)) { top = (clientTop + scrollTop) - m_offsetTop - height; } m_toolTip.getStyle().setTop(top, Unit.PX); } }
[ "private", "void", "setToolTipPosition", "(", "int", "clientLeft", ",", "int", "clientTop", ")", "{", "if", "(", "m_toolTip", "!=", "null", ")", "{", "int", "height", "=", "m_toolTip", ".", "getOffsetHeight", "(", ")", ";", "int", "width", "=", "m_toolTip", ".", "getOffsetWidth", "(", ")", ";", "int", "windowHeight", "=", "Window", ".", "getClientHeight", "(", ")", ";", "int", "windowWidth", "=", "Window", ".", "getClientWidth", "(", ")", ";", "int", "scrollLeft", "=", "Window", ".", "getScrollLeft", "(", ")", ";", "int", "scrollTop", "=", "Window", ".", "getScrollTop", "(", ")", ";", "int", "left", "=", "clientLeft", "+", "scrollLeft", "+", "m_offsetLeft", ";", "if", "(", "(", "left", "+", "width", ")", ">", "(", "windowWidth", "+", "scrollLeft", ")", ")", "{", "left", "=", "(", "windowWidth", "+", "scrollLeft", ")", "-", "m_offsetLeft", "-", "width", ";", "}", "m_toolTip", ".", "getStyle", "(", ")", ".", "setLeft", "(", "left", ",", "Unit", ".", "PX", ")", ";", "int", "top", "=", "clientTop", "+", "scrollTop", "+", "m_offsetTop", ";", "if", "(", "(", "(", "top", "+", "height", ")", ">", "(", "windowHeight", "+", "scrollTop", ")", ")", "&&", "(", "(", "height", "+", "m_offsetTop", ")", "<", "clientTop", ")", ")", "{", "top", "=", "(", "clientTop", "+", "scrollTop", ")", "-", "m_offsetTop", "-", "height", ";", "}", "m_toolTip", ".", "getStyle", "(", ")", ".", "setTop", "(", "top", ",", "Unit", ".", "PX", ")", ";", "}", "}" ]
Sets the tool-tip position.<p> @param clientLeft the mouse pointer left position relative to the client window @param clientTop the mouse pointer top position relative to the client window
[ "Sets", "the", "tool", "-", "tip", "position", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/util/CmsToolTipHandler.java#L266-L286
jcustenborder/connect-utils
connect-utils/src/main/java/com/github/jcustenborder/kafka/connect/utils/config/ConfigUtils.java
ConfigUtils.hostAndPort
public static HostAndPort hostAndPort(AbstractConfig config, String key, Integer defaultPort) { """ Method is used to parse a string ConfigDef item to a HostAndPort @param config Config to read from @param key ConfigItem to get the host string from. @param defaultPort The default port to use if a port was not specified. Can be null. @return HostAndPort based on the ConfigItem. """ final String input = config.getString(key); return hostAndPort(input, defaultPort); }
java
public static HostAndPort hostAndPort(AbstractConfig config, String key, Integer defaultPort) { final String input = config.getString(key); return hostAndPort(input, defaultPort); }
[ "public", "static", "HostAndPort", "hostAndPort", "(", "AbstractConfig", "config", ",", "String", "key", ",", "Integer", "defaultPort", ")", "{", "final", "String", "input", "=", "config", ".", "getString", "(", "key", ")", ";", "return", "hostAndPort", "(", "input", ",", "defaultPort", ")", ";", "}" ]
Method is used to parse a string ConfigDef item to a HostAndPort @param config Config to read from @param key ConfigItem to get the host string from. @param defaultPort The default port to use if a port was not specified. Can be null. @return HostAndPort based on the ConfigItem.
[ "Method", "is", "used", "to", "parse", "a", "string", "ConfigDef", "item", "to", "a", "HostAndPort" ]
train
https://github.com/jcustenborder/connect-utils/blob/19add138921f59ffcc85282d7aad551eeb582370/connect-utils/src/main/java/com/github/jcustenborder/kafka/connect/utils/config/ConfigUtils.java#L157-L160
liferay/com-liferay-commerce
commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceOrderItemPersistenceImpl.java
CommerceOrderItemPersistenceImpl.findAll
@Override public List<CommerceOrderItem> findAll(int start, int end) { """ Returns a range of all the commerce order items. <p> Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommerceOrderItemModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. </p> @param start the lower bound of the range of commerce order items @param end the upper bound of the range of commerce order items (not inclusive) @return the range of commerce order items """ return findAll(start, end, null); }
java
@Override public List<CommerceOrderItem> findAll(int start, int end) { return findAll(start, end, null); }
[ "@", "Override", "public", "List", "<", "CommerceOrderItem", ">", "findAll", "(", "int", "start", ",", "int", "end", ")", "{", "return", "findAll", "(", "start", ",", "end", ",", "null", ")", ";", "}" ]
Returns a range of all the commerce order items. <p> Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommerceOrderItemModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. </p> @param start the lower bound of the range of commerce order items @param end the upper bound of the range of commerce order items (not inclusive) @return the range of commerce order items
[ "Returns", "a", "range", "of", "all", "the", "commerce", "order", "items", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceOrderItemPersistenceImpl.java#L3683-L3686
threerings/nenya
core/src/main/java/com/threerings/miso/client/SceneObjectTip.java
SceneObjectTip.registerTipLayout
public static void registerTipLayout (String prefix, TipLayout layout) { """ It may be desirable to layout object tips specially depending on what sort of actions they represent, so we allow different tip layout algorithms to be registered for particular object prefixes. The registration is simply a list searched from longest string to shortest string for the first match to an object's action. """ LayoutReg reg = new LayoutReg(); reg.prefix = prefix; reg.layout = layout; _layouts.insertSorted(reg); }
java
public static void registerTipLayout (String prefix, TipLayout layout) { LayoutReg reg = new LayoutReg(); reg.prefix = prefix; reg.layout = layout; _layouts.insertSorted(reg); }
[ "public", "static", "void", "registerTipLayout", "(", "String", "prefix", ",", "TipLayout", "layout", ")", "{", "LayoutReg", "reg", "=", "new", "LayoutReg", "(", ")", ";", "reg", ".", "prefix", "=", "prefix", ";", "reg", ".", "layout", "=", "layout", ";", "_layouts", ".", "insertSorted", "(", "reg", ")", ";", "}" ]
It may be desirable to layout object tips specially depending on what sort of actions they represent, so we allow different tip layout algorithms to be registered for particular object prefixes. The registration is simply a list searched from longest string to shortest string for the first match to an object's action.
[ "It", "may", "be", "desirable", "to", "layout", "object", "tips", "specially", "depending", "on", "what", "sort", "of", "actions", "they", "represent", "so", "we", "allow", "different", "tip", "layout", "algorithms", "to", "be", "registered", "for", "particular", "object", "prefixes", ".", "The", "registration", "is", "simply", "a", "list", "searched", "from", "longest", "string", "to", "shortest", "string", "for", "the", "first", "match", "to", "an", "object", "s", "action", "." ]
train
https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/miso/client/SceneObjectTip.java#L144-L150
b3dgs/lionengine
lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/collision/CollisionFunctionConfig.java
CollisionFunctionConfig.imports
public static CollisionFunction imports(Xml parent) { """ Create the collision function from node. @param parent The parent reference (must not be <code>null</code>). @return The collision function data. @throws LionEngineException If error when reading node. """ Check.notNull(parent); final Xml node = parent.getChild(FUNCTION); final String name = node.readString(TYPE); try { final CollisionFunctionType type = CollisionFunctionType.valueOf(name); switch (type) { case LINEAR: return new CollisionFunctionLinear(node.readDouble(A), node.readDouble(B)); default: throw new LionEngineException(ERROR_TYPE + name); } } catch (final IllegalArgumentException | NullPointerException exception) { throw new LionEngineException(exception, ERROR_TYPE + name); } }
java
public static CollisionFunction imports(Xml parent) { Check.notNull(parent); final Xml node = parent.getChild(FUNCTION); final String name = node.readString(TYPE); try { final CollisionFunctionType type = CollisionFunctionType.valueOf(name); switch (type) { case LINEAR: return new CollisionFunctionLinear(node.readDouble(A), node.readDouble(B)); default: throw new LionEngineException(ERROR_TYPE + name); } } catch (final IllegalArgumentException | NullPointerException exception) { throw new LionEngineException(exception, ERROR_TYPE + name); } }
[ "public", "static", "CollisionFunction", "imports", "(", "Xml", "parent", ")", "{", "Check", ".", "notNull", "(", "parent", ")", ";", "final", "Xml", "node", "=", "parent", ".", "getChild", "(", "FUNCTION", ")", ";", "final", "String", "name", "=", "node", ".", "readString", "(", "TYPE", ")", ";", "try", "{", "final", "CollisionFunctionType", "type", "=", "CollisionFunctionType", ".", "valueOf", "(", "name", ")", ";", "switch", "(", "type", ")", "{", "case", "LINEAR", ":", "return", "new", "CollisionFunctionLinear", "(", "node", ".", "readDouble", "(", "A", ")", ",", "node", ".", "readDouble", "(", "B", ")", ")", ";", "default", ":", "throw", "new", "LionEngineException", "(", "ERROR_TYPE", "+", "name", ")", ";", "}", "}", "catch", "(", "final", "IllegalArgumentException", "|", "NullPointerException", "exception", ")", "{", "throw", "new", "LionEngineException", "(", "exception", ",", "ERROR_TYPE", "+", "name", ")", ";", "}", "}" ]
Create the collision function from node. @param parent The parent reference (must not be <code>null</code>). @return The collision function data. @throws LionEngineException If error when reading node.
[ "Create", "the", "collision", "function", "from", "node", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/collision/CollisionFunctionConfig.java#L53-L74
VoltDB/voltdb
src/frontend/org/voltdb/compiler/AdHocPlannedStmtBatch.java
AdHocPlannedStmtBatch.getSQLStatements
public List<String> getSQLStatements() { """ Retrieve all the SQL statement text as a list of strings. @return list of SQL statement strings """ List<String> sqlStatements = new ArrayList<>(plannedStatements.size()); for (AdHocPlannedStatement plannedStatement : plannedStatements) { sqlStatements.add(new String(plannedStatement.sql, Constants.UTF8ENCODING)); } return sqlStatements; }
java
public List<String> getSQLStatements() { List<String> sqlStatements = new ArrayList<>(plannedStatements.size()); for (AdHocPlannedStatement plannedStatement : plannedStatements) { sqlStatements.add(new String(plannedStatement.sql, Constants.UTF8ENCODING)); } return sqlStatements; }
[ "public", "List", "<", "String", ">", "getSQLStatements", "(", ")", "{", "List", "<", "String", ">", "sqlStatements", "=", "new", "ArrayList", "<>", "(", "plannedStatements", ".", "size", "(", ")", ")", ";", "for", "(", "AdHocPlannedStatement", "plannedStatement", ":", "plannedStatements", ")", "{", "sqlStatements", ".", "add", "(", "new", "String", "(", "plannedStatement", ".", "sql", ",", "Constants", ".", "UTF8ENCODING", ")", ")", ";", "}", "return", "sqlStatements", ";", "}" ]
Retrieve all the SQL statement text as a list of strings. @return list of SQL statement strings
[ "Retrieve", "all", "the", "SQL", "statement", "text", "as", "a", "list", "of", "strings", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/compiler/AdHocPlannedStmtBatch.java#L191-L197
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/string/StringHelper.java
StringHelper.trimStartAndEnd
@Nullable @CheckReturnValue public static String trimStartAndEnd (@Nullable final String sSrc, @Nullable final String sValueToTrim) { """ Trim the passed lead and tail from the source value. If the source value does not start with the passed trimmed value, nothing happens. @param sSrc The input source string @param sValueToTrim The string to be trimmed of the beginning and the end @return The trimmed string, or the original input string, if the value to trim was not found @see #trimStart(String, String) @see #trimEnd(String, String) @see #trimStartAndEnd(String, String, String) """ return trimStartAndEnd (sSrc, sValueToTrim, sValueToTrim); }
java
@Nullable @CheckReturnValue public static String trimStartAndEnd (@Nullable final String sSrc, @Nullable final String sValueToTrim) { return trimStartAndEnd (sSrc, sValueToTrim, sValueToTrim); }
[ "@", "Nullable", "@", "CheckReturnValue", "public", "static", "String", "trimStartAndEnd", "(", "@", "Nullable", "final", "String", "sSrc", ",", "@", "Nullable", "final", "String", "sValueToTrim", ")", "{", "return", "trimStartAndEnd", "(", "sSrc", ",", "sValueToTrim", ",", "sValueToTrim", ")", ";", "}" ]
Trim the passed lead and tail from the source value. If the source value does not start with the passed trimmed value, nothing happens. @param sSrc The input source string @param sValueToTrim The string to be trimmed of the beginning and the end @return The trimmed string, or the original input string, if the value to trim was not found @see #trimStart(String, String) @see #trimEnd(String, String) @see #trimStartAndEnd(String, String, String)
[ "Trim", "the", "passed", "lead", "and", "tail", "from", "the", "source", "value", ".", "If", "the", "source", "value", "does", "not", "start", "with", "the", "passed", "trimmed", "value", "nothing", "happens", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/string/StringHelper.java#L3468-L3473
jcuda/jcusparse
JCusparseJava/src/main/java/jcuda/jcusparse/JCusparse.java
JCusparse.cusparseSbsrilu02_numericBoost
public static int cusparseSbsrilu02_numericBoost( cusparseHandle handle, bsrilu02Info info, int enable_boost, Pointer tol, Pointer boost_val) { """ <pre> Description: Compute the incomplete-LU factorization with 0 fill-in (ILU0) of the matrix A stored in block-CSR format based on the information in the opaque structure info that was obtained from the analysis phase (bsrsv2_analysis). This routine implements algorithm 2 for this problem. </pre> """ return checkResult(cusparseSbsrilu02_numericBoostNative(handle, info, enable_boost, tol, boost_val)); }
java
public static int cusparseSbsrilu02_numericBoost( cusparseHandle handle, bsrilu02Info info, int enable_boost, Pointer tol, Pointer boost_val) { return checkResult(cusparseSbsrilu02_numericBoostNative(handle, info, enable_boost, tol, boost_val)); }
[ "public", "static", "int", "cusparseSbsrilu02_numericBoost", "(", "cusparseHandle", "handle", ",", "bsrilu02Info", "info", ",", "int", "enable_boost", ",", "Pointer", "tol", ",", "Pointer", "boost_val", ")", "{", "return", "checkResult", "(", "cusparseSbsrilu02_numericBoostNative", "(", "handle", ",", "info", ",", "enable_boost", ",", "tol", ",", "boost_val", ")", ")", ";", "}" ]
<pre> Description: Compute the incomplete-LU factorization with 0 fill-in (ILU0) of the matrix A stored in block-CSR format based on the information in the opaque structure info that was obtained from the analysis phase (bsrsv2_analysis). This routine implements algorithm 2 for this problem. </pre>
[ "<pre", ">", "Description", ":", "Compute", "the", "incomplete", "-", "LU", "factorization", "with", "0", "fill", "-", "in", "(", "ILU0", ")", "of", "the", "matrix", "A", "stored", "in", "block", "-", "CSR", "format", "based", "on", "the", "information", "in", "the", "opaque", "structure", "info", "that", "was", "obtained", "from", "the", "analysis", "phase", "(", "bsrsv2_analysis", ")", ".", "This", "routine", "implements", "algorithm", "2", "for", "this", "problem", ".", "<", "/", "pre", ">" ]
train
https://github.com/jcuda/jcusparse/blob/7687a62a4ef6b76cb91cf7da93d4cf5ade96a791/JCusparseJava/src/main/java/jcuda/jcusparse/JCusparse.java#L6377-L6385
aws/aws-sdk-java
aws-java-sdk-core/src/main/java/com/amazonaws/monitoring/internal/ClientSideMonitoringRequestHandler.java
ClientSideMonitoringRequestHandler.trimValueIfExceedsMaxLength
private String trimValueIfExceedsMaxLength(String entry, String value) { """ If the entry exceeds the maximum length limit associated with the entry, its value will be trimmed to meet its limit. """ if (value == null) { return null; } String result = value; Integer maximumSize = ENTRY_TO_MAX_SIZE.get(entry); if (maximumSize != null && value.length() > maximumSize) { result = value.substring(0, maximumSize); } return result; }
java
private String trimValueIfExceedsMaxLength(String entry, String value) { if (value == null) { return null; } String result = value; Integer maximumSize = ENTRY_TO_MAX_SIZE.get(entry); if (maximumSize != null && value.length() > maximumSize) { result = value.substring(0, maximumSize); } return result; }
[ "private", "String", "trimValueIfExceedsMaxLength", "(", "String", "entry", ",", "String", "value", ")", "{", "if", "(", "value", "==", "null", ")", "{", "return", "null", ";", "}", "String", "result", "=", "value", ";", "Integer", "maximumSize", "=", "ENTRY_TO_MAX_SIZE", ".", "get", "(", "entry", ")", ";", "if", "(", "maximumSize", "!=", "null", "&&", "value", ".", "length", "(", ")", ">", "maximumSize", ")", "{", "result", "=", "value", ".", "substring", "(", "0", ",", "maximumSize", ")", ";", "}", "return", "result", ";", "}" ]
If the entry exceeds the maximum length limit associated with the entry, its value will be trimmed to meet its limit.
[ "If", "the", "entry", "exceeds", "the", "maximum", "length", "limit", "associated", "with", "the", "entry", "its", "value", "will", "be", "trimmed", "to", "meet", "its", "limit", "." ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-core/src/main/java/com/amazonaws/monitoring/internal/ClientSideMonitoringRequestHandler.java#L285-L296
atomix/catalyst
serializer/src/main/java/io/atomix/catalyst/serializer/Serializer.java
Serializer.writeById
@SuppressWarnings("unchecked") private BufferOutput writeById(int id, Object object, BufferOutput output, TypeSerializer serializer) { """ Writes an object to the buffer using the given serialization ID. """ for (Identifier identifier : Identifier.values()) { if (identifier.accept(id)) { identifier.write(id, output.writeByte(identifier.code())); serializer.write(object, output, this); return output; } } throw new SerializationException("invalid type ID: " + id); }
java
@SuppressWarnings("unchecked") private BufferOutput writeById(int id, Object object, BufferOutput output, TypeSerializer serializer) { for (Identifier identifier : Identifier.values()) { if (identifier.accept(id)) { identifier.write(id, output.writeByte(identifier.code())); serializer.write(object, output, this); return output; } } throw new SerializationException("invalid type ID: " + id); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "private", "BufferOutput", "writeById", "(", "int", "id", ",", "Object", "object", ",", "BufferOutput", "output", ",", "TypeSerializer", "serializer", ")", "{", "for", "(", "Identifier", "identifier", ":", "Identifier", ".", "values", "(", ")", ")", "{", "if", "(", "identifier", ".", "accept", "(", "id", ")", ")", "{", "identifier", ".", "write", "(", "id", ",", "output", ".", "writeByte", "(", "identifier", ".", "code", "(", ")", ")", ")", ";", "serializer", ".", "write", "(", "object", ",", "output", ",", "this", ")", ";", "return", "output", ";", "}", "}", "throw", "new", "SerializationException", "(", "\"invalid type ID: \"", "+", "id", ")", ";", "}" ]
Writes an object to the buffer using the given serialization ID.
[ "Writes", "an", "object", "to", "the", "buffer", "using", "the", "given", "serialization", "ID", "." ]
train
https://github.com/atomix/catalyst/blob/140e762cb975cd8ee1fd85119043c5b8bf917c5c/serializer/src/main/java/io/atomix/catalyst/serializer/Serializer.java#L883-L893
kubernetes-client/java
util/src/main/java/io/kubernetes/client/util/Yaml.java
Yaml.loadAs
public static <T> T loadAs(File f, Class<T> clazz) throws IOException { """ Load an API object from a YAML file. Returns a concrete typed object using the type specified. @param f The YAML file @param clazz The class of object to return. @return An instantiation of the object. @throws IOException If an error occurs while reading the YAML. """ return getSnakeYaml().loadAs(new FileReader(f), clazz); }
java
public static <T> T loadAs(File f, Class<T> clazz) throws IOException { return getSnakeYaml().loadAs(new FileReader(f), clazz); }
[ "public", "static", "<", "T", ">", "T", "loadAs", "(", "File", "f", ",", "Class", "<", "T", ">", "clazz", ")", "throws", "IOException", "{", "return", "getSnakeYaml", "(", ")", ".", "loadAs", "(", "new", "FileReader", "(", "f", ")", ",", "clazz", ")", ";", "}" ]
Load an API object from a YAML file. Returns a concrete typed object using the type specified. @param f The YAML file @param clazz The class of object to return. @return An instantiation of the object. @throws IOException If an error occurs while reading the YAML.
[ "Load", "an", "API", "object", "from", "a", "YAML", "file", ".", "Returns", "a", "concrete", "typed", "object", "using", "the", "type", "specified", "." ]
train
https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/util/Yaml.java#L208-L210
kevoree/kevoree-library
mqttServer/src/main/java/org/dna/mqtt/moquette/messaging/spi/impl/ProtocolProcessor.java
ProtocolProcessor.processUnsubscribe
void processUnsubscribe(ServerChannel session, String clientID, List<String> topics, int messageID) { """ Remove the clientID from topic subscription, if not previously subscribed, doesn't reply any error """ Log.trace("processUnsubscribe invoked, removing subscription on topics {}, for clientID <{}>", topics, clientID); for (String topic : topics) { subscriptions.removeSubscription(topic, clientID); } //ack the client UnsubAckMessage ackMessage = new UnsubAckMessage(); ackMessage.setMessageID(messageID); Log.trace("replying with UnsubAck to MSG ID {}", messageID); session.write(ackMessage); }
java
void processUnsubscribe(ServerChannel session, String clientID, List<String> topics, int messageID) { Log.trace("processUnsubscribe invoked, removing subscription on topics {}, for clientID <{}>", topics, clientID); for (String topic : topics) { subscriptions.removeSubscription(topic, clientID); } //ack the client UnsubAckMessage ackMessage = new UnsubAckMessage(); ackMessage.setMessageID(messageID); Log.trace("replying with UnsubAck to MSG ID {}", messageID); session.write(ackMessage); }
[ "void", "processUnsubscribe", "(", "ServerChannel", "session", ",", "String", "clientID", ",", "List", "<", "String", ">", "topics", ",", "int", "messageID", ")", "{", "Log", ".", "trace", "(", "\"processUnsubscribe invoked, removing subscription on topics {}, for clientID <{}>\"", ",", "topics", ",", "clientID", ")", ";", "for", "(", "String", "topic", ":", "topics", ")", "{", "subscriptions", ".", "removeSubscription", "(", "topic", ",", "clientID", ")", ";", "}", "//ack the client", "UnsubAckMessage", "ackMessage", "=", "new", "UnsubAckMessage", "(", ")", ";", "ackMessage", ".", "setMessageID", "(", "messageID", ")", ";", "Log", ".", "trace", "(", "\"replying with UnsubAck to MSG ID {}\"", ",", "messageID", ")", ";", "session", ".", "write", "(", "ackMessage", ")", ";", "}" ]
Remove the clientID from topic subscription, if not previously subscribed, doesn't reply any error
[ "Remove", "the", "clientID", "from", "topic", "subscription", "if", "not", "previously", "subscribed", "doesn", "t", "reply", "any", "error" ]
train
https://github.com/kevoree/kevoree-library/blob/617460e6c5881902ebc488a31ecdea179024d8f1/mqttServer/src/main/java/org/dna/mqtt/moquette/messaging/spi/impl/ProtocolProcessor.java#L485-L497
guardtime/ksi-java-sdk
ksi-common/src/main/java/com/guardtime/ksi/util/Util.java
Util.equalsIgnoreOrder
public static boolean equalsIgnoreOrder(Collection<?> c1, Collection<?> c2) { """ Checks if two collections are equal ignoring the order of components. It's safe to pass collections that might be null. @param c1 first collection. @param c2 second collection. @return True, if both lists are null or if they have exactly the same components. """ return (c1 == null && c2 == null) || (c1 != null && c2 != null && c1.size() == c2.size() && c1.containsAll(c2) && c2.containsAll(c1)); }
java
public static boolean equalsIgnoreOrder(Collection<?> c1, Collection<?> c2) { return (c1 == null && c2 == null) || (c1 != null && c2 != null && c1.size() == c2.size() && c1.containsAll(c2) && c2.containsAll(c1)); }
[ "public", "static", "boolean", "equalsIgnoreOrder", "(", "Collection", "<", "?", ">", "c1", ",", "Collection", "<", "?", ">", "c2", ")", "{", "return", "(", "c1", "==", "null", "&&", "c2", "==", "null", ")", "||", "(", "c1", "!=", "null", "&&", "c2", "!=", "null", "&&", "c1", ".", "size", "(", ")", "==", "c2", ".", "size", "(", ")", "&&", "c1", ".", "containsAll", "(", "c2", ")", "&&", "c2", ".", "containsAll", "(", "c1", ")", ")", ";", "}" ]
Checks if two collections are equal ignoring the order of components. It's safe to pass collections that might be null. @param c1 first collection. @param c2 second collection. @return True, if both lists are null or if they have exactly the same components.
[ "Checks", "if", "two", "collections", "are", "equal", "ignoring", "the", "order", "of", "components", ".", "It", "s", "safe", "to", "pass", "collections", "that", "might", "be", "null", "." ]
train
https://github.com/guardtime/ksi-java-sdk/blob/b2cd877050f0f392657c724452318d10a1002171/ksi-common/src/main/java/com/guardtime/ksi/util/Util.java#L728-L730
hypfvieh/java-utils
src/main/java/com/github/hypfvieh/util/TypeUtil.java
TypeUtil.isInteger
public static boolean isInteger(String _str, boolean _allowNegative) { """ Check if string is an either positive or negative integer. @param _str string to validate @param _allowNegative negative integer allowed @return true if integer, false otherwise """ if (_str == null) { return false; } String regex = "[0-9]+$"; if (_allowNegative) { regex = "^-?" + regex; } else { regex = "^" + regex; } return _str.matches(regex); }
java
public static boolean isInteger(String _str, boolean _allowNegative) { if (_str == null) { return false; } String regex = "[0-9]+$"; if (_allowNegative) { regex = "^-?" + regex; } else { regex = "^" + regex; } return _str.matches(regex); }
[ "public", "static", "boolean", "isInteger", "(", "String", "_str", ",", "boolean", "_allowNegative", ")", "{", "if", "(", "_str", "==", "null", ")", "{", "return", "false", ";", "}", "String", "regex", "=", "\"[0-9]+$\"", ";", "if", "(", "_allowNegative", ")", "{", "regex", "=", "\"^-?\"", "+", "regex", ";", "}", "else", "{", "regex", "=", "\"^\"", "+", "regex", ";", "}", "return", "_str", ".", "matches", "(", "regex", ")", ";", "}" ]
Check if string is an either positive or negative integer. @param _str string to validate @param _allowNegative negative integer allowed @return true if integer, false otherwise
[ "Check", "if", "string", "is", "an", "either", "positive", "or", "negative", "integer", "." ]
train
https://github.com/hypfvieh/java-utils/blob/407c32d6b485596d4d2b644f5f7fc7a02d0169c6/src/main/java/com/github/hypfvieh/util/TypeUtil.java#L113-L125
Stratio/stratio-cassandra
src/java/org/apache/cassandra/utils/btree/BTree.java
BTree.find
static <V> int find(Comparator<V> comparator, Object key, Object[] a, final int fromIndex, final int toIndex) { """ wrapping generic Comparator with support for Special +/- infinity sentinels """ int low = fromIndex; int high = toIndex - 1; while (low <= high) { int mid = (low + high) / 2; int cmp = comparator.compare((V) key, (V) a[mid]); if (cmp > 0) low = mid + 1; else if (cmp < 0) high = mid - 1; else return mid; // key found } return -(low + 1); // key not found. }
java
static <V> int find(Comparator<V> comparator, Object key, Object[] a, final int fromIndex, final int toIndex) { int low = fromIndex; int high = toIndex - 1; while (low <= high) { int mid = (low + high) / 2; int cmp = comparator.compare((V) key, (V) a[mid]); if (cmp > 0) low = mid + 1; else if (cmp < 0) high = mid - 1; else return mid; // key found } return -(low + 1); // key not found. }
[ "static", "<", "V", ">", "int", "find", "(", "Comparator", "<", "V", ">", "comparator", ",", "Object", "key", ",", "Object", "[", "]", "a", ",", "final", "int", "fromIndex", ",", "final", "int", "toIndex", ")", "{", "int", "low", "=", "fromIndex", ";", "int", "high", "=", "toIndex", "-", "1", ";", "while", "(", "low", "<=", "high", ")", "{", "int", "mid", "=", "(", "low", "+", "high", ")", "/", "2", ";", "int", "cmp", "=", "comparator", ".", "compare", "(", "(", "V", ")", "key", ",", "(", "V", ")", "a", "[", "mid", "]", ")", ";", "if", "(", "cmp", ">", "0", ")", "low", "=", "mid", "+", "1", ";", "else", "if", "(", "cmp", "<", "0", ")", "high", "=", "mid", "-", "1", ";", "else", "return", "mid", ";", "// key found", "}", "return", "-", "(", "low", "+", "1", ")", ";", "// key not found.", "}" ]
wrapping generic Comparator with support for Special +/- infinity sentinels
[ "wrapping", "generic", "Comparator", "with", "support", "for", "Special", "+", "/", "-", "infinity", "sentinels" ]
train
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/utils/btree/BTree.java#L269-L287
jfoenixadmin/JFoenix
jfoenix/src/main/java/com/jfoenix/svg/SVGGlyphLoader.java
SVGGlyphLoader.loadGlyphsFont
public static void loadGlyphsFont(InputStream stream, String keyPrefix) throws IOException { """ will load SVG icons from input stream @param stream input stream of svg font file @param keyPrefix will be used as a prefix when storing SVG icons in the map @throws IOException """ try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); docBuilder.setEntityResolver((publicId, systemId) -> { // disable dtd entites at runtime return new InputSource(new StringReader("")); }); Document doc = docBuilder.parse(stream); doc.getDocumentElement().normalize(); NodeList glyphsList = doc.getElementsByTagName("glyph"); for (int i = 0; i < glyphsList.getLength(); i++) { Node glyph = glyphsList.item(i); Node glyphName = glyph.getAttributes().getNamedItem("glyph-name"); if (glyphName == null) { continue; } String glyphId = glyphName.getNodeValue(); SVGGlyphBuilder glyphPane = new SVGGlyphBuilder(i, glyphId, glyph.getAttributes() .getNamedItem("d") .getNodeValue()); glyphsMap.put(keyPrefix + "." + glyphId, glyphPane); } stream.close(); } catch (ParserConfigurationException | SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
java
public static void loadGlyphsFont(InputStream stream, String keyPrefix) throws IOException { try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); docBuilder.setEntityResolver((publicId, systemId) -> { // disable dtd entites at runtime return new InputSource(new StringReader("")); }); Document doc = docBuilder.parse(stream); doc.getDocumentElement().normalize(); NodeList glyphsList = doc.getElementsByTagName("glyph"); for (int i = 0; i < glyphsList.getLength(); i++) { Node glyph = glyphsList.item(i); Node glyphName = glyph.getAttributes().getNamedItem("glyph-name"); if (glyphName == null) { continue; } String glyphId = glyphName.getNodeValue(); SVGGlyphBuilder glyphPane = new SVGGlyphBuilder(i, glyphId, glyph.getAttributes() .getNamedItem("d") .getNodeValue()); glyphsMap.put(keyPrefix + "." + glyphId, glyphPane); } stream.close(); } catch (ParserConfigurationException | SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
[ "public", "static", "void", "loadGlyphsFont", "(", "InputStream", "stream", ",", "String", "keyPrefix", ")", "throws", "IOException", "{", "try", "{", "DocumentBuilderFactory", "docFactory", "=", "DocumentBuilderFactory", ".", "newInstance", "(", ")", ";", "DocumentBuilder", "docBuilder", "=", "docFactory", ".", "newDocumentBuilder", "(", ")", ";", "docBuilder", ".", "setEntityResolver", "(", "(", "publicId", ",", "systemId", ")", "->", "{", "// disable dtd entites at runtime", "return", "new", "InputSource", "(", "new", "StringReader", "(", "\"\"", ")", ")", ";", "}", ")", ";", "Document", "doc", "=", "docBuilder", ".", "parse", "(", "stream", ")", ";", "doc", ".", "getDocumentElement", "(", ")", ".", "normalize", "(", ")", ";", "NodeList", "glyphsList", "=", "doc", ".", "getElementsByTagName", "(", "\"glyph\"", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "glyphsList", ".", "getLength", "(", ")", ";", "i", "++", ")", "{", "Node", "glyph", "=", "glyphsList", ".", "item", "(", "i", ")", ";", "Node", "glyphName", "=", "glyph", ".", "getAttributes", "(", ")", ".", "getNamedItem", "(", "\"glyph-name\"", ")", ";", "if", "(", "glyphName", "==", "null", ")", "{", "continue", ";", "}", "String", "glyphId", "=", "glyphName", ".", "getNodeValue", "(", ")", ";", "SVGGlyphBuilder", "glyphPane", "=", "new", "SVGGlyphBuilder", "(", "i", ",", "glyphId", ",", "glyph", ".", "getAttributes", "(", ")", ".", "getNamedItem", "(", "\"d\"", ")", ".", "getNodeValue", "(", ")", ")", ";", "glyphsMap", ".", "put", "(", "keyPrefix", "+", "\".\"", "+", "glyphId", ",", "glyphPane", ")", ";", "}", "stream", ".", "close", "(", ")", ";", "}", "catch", "(", "ParserConfigurationException", "|", "SAXException", "e", ")", "{", "// TODO Auto-generated catch block", "e", ".", "printStackTrace", "(", ")", ";", "}", "}" ]
will load SVG icons from input stream @param stream input stream of svg font file @param keyPrefix will be used as a prefix when storing SVG icons in the map @throws IOException
[ "will", "load", "SVG", "icons", "from", "input", "stream" ]
train
https://github.com/jfoenixadmin/JFoenix/blob/53235b5f561da4a515ef716059b8a8df5239ffa1/jfoenix/src/main/java/com/jfoenix/svg/SVGGlyphLoader.java#L133-L167
box/box-android-sdk
box-content-sdk/src/main/java/com/box/androidsdk/content/BoxApiMetadata.java
BoxApiMetadata.getUpdateFolderMetadataRequest
public BoxRequestsMetadata.UpdateItemMetadata getUpdateFolderMetadataRequest(String id, String scope, String template) { """ Gets a request that updates the metadata for a specific template on a folder @param id id of the folder to retrieve metadata for @param scope currently only global and enterprise scopes are supported @param template metadata template to use @return request to update metadata on a folder """ BoxRequestsMetadata.UpdateItemMetadata request = new BoxRequestsMetadata.UpdateItemMetadata(getFolderMetadataUrl(id, scope, template), mSession); return request; }
java
public BoxRequestsMetadata.UpdateItemMetadata getUpdateFolderMetadataRequest(String id, String scope, String template) { BoxRequestsMetadata.UpdateItemMetadata request = new BoxRequestsMetadata.UpdateItemMetadata(getFolderMetadataUrl(id, scope, template), mSession); return request; }
[ "public", "BoxRequestsMetadata", ".", "UpdateItemMetadata", "getUpdateFolderMetadataRequest", "(", "String", "id", ",", "String", "scope", ",", "String", "template", ")", "{", "BoxRequestsMetadata", ".", "UpdateItemMetadata", "request", "=", "new", "BoxRequestsMetadata", ".", "UpdateItemMetadata", "(", "getFolderMetadataUrl", "(", "id", ",", "scope", ",", "template", ")", ",", "mSession", ")", ";", "return", "request", ";", "}" ]
Gets a request that updates the metadata for a specific template on a folder @param id id of the folder to retrieve metadata for @param scope currently only global and enterprise scopes are supported @param template metadata template to use @return request to update metadata on a folder
[ "Gets", "a", "request", "that", "updates", "the", "metadata", "for", "a", "specific", "template", "on", "a", "folder" ]
train
https://github.com/box/box-android-sdk/blob/a621ad5ddebf23067fec27529130d72718fc0e88/box-content-sdk/src/main/java/com/box/androidsdk/content/BoxApiMetadata.java#L241-L244
Harium/keel
src/main/java/com/harium/keel/catalano/math/distance/Distance.java
Distance.SquaredEuclidean
public static double SquaredEuclidean(double[] x, double[] y) { """ Gets the Square Euclidean distance between two points. @param x A point in space. @param y A point in space. @return The Square Euclidean distance between x and y. """ double d = 0.0, u; for (int i = 0; i < x.length; i++) { u = x[i] - y[i]; d += u * u; } return d; }
java
public static double SquaredEuclidean(double[] x, double[] y) { double d = 0.0, u; for (int i = 0; i < x.length; i++) { u = x[i] - y[i]; d += u * u; } return d; }
[ "public", "static", "double", "SquaredEuclidean", "(", "double", "[", "]", "x", ",", "double", "[", "]", "y", ")", "{", "double", "d", "=", "0.0", ",", "u", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "x", ".", "length", ";", "i", "++", ")", "{", "u", "=", "x", "[", "i", "]", "-", "y", "[", "i", "]", ";", "d", "+=", "u", "*", "u", ";", "}", "return", "d", ";", "}" ]
Gets the Square Euclidean distance between two points. @param x A point in space. @param y A point in space. @return The Square Euclidean distance between x and y.
[ "Gets", "the", "Square", "Euclidean", "distance", "between", "two", "points", "." ]
train
https://github.com/Harium/keel/blob/0369ae674f9e664bccc5f9e161ae7e7a3b949a1e/src/main/java/com/harium/keel/catalano/math/distance/Distance.java#L801-L810
forge/core
projects/api/src/main/java/org/jboss/forge/addon/projects/stacks/StackInspector.java
StackInspector.getAllRelatedFacets
public static <FACETTYPE extends Facet<?>> Set<Class<FACETTYPE>> getAllRelatedFacets(final Class<?> inspectedType) { """ Inspect the given {@link Class} for all {@link Facet} types from all {@link FacetConstraint} declarations. This method inspects the entire constraint tree. """ Set<Class<FACETTYPE>> seen = new LinkedHashSet<Class<FACETTYPE>>(); return getAllRelatedFacets(seen, inspectedType); }
java
public static <FACETTYPE extends Facet<?>> Set<Class<FACETTYPE>> getAllRelatedFacets(final Class<?> inspectedType) { Set<Class<FACETTYPE>> seen = new LinkedHashSet<Class<FACETTYPE>>(); return getAllRelatedFacets(seen, inspectedType); }
[ "public", "static", "<", "FACETTYPE", "extends", "Facet", "<", "?", ">", ">", "Set", "<", "Class", "<", "FACETTYPE", ">", ">", "getAllRelatedFacets", "(", "final", "Class", "<", "?", ">", "inspectedType", ")", "{", "Set", "<", "Class", "<", "FACETTYPE", ">>", "seen", "=", "new", "LinkedHashSet", "<", "Class", "<", "FACETTYPE", ">", ">", "(", ")", ";", "return", "getAllRelatedFacets", "(", "seen", ",", "inspectedType", ")", ";", "}" ]
Inspect the given {@link Class} for all {@link Facet} types from all {@link FacetConstraint} declarations. This method inspects the entire constraint tree.
[ "Inspect", "the", "given", "{" ]
train
https://github.com/forge/core/blob/e140eb03bbe2b3409478ad70c86c3edbef6d9a0c/projects/api/src/main/java/org/jboss/forge/addon/projects/stacks/StackInspector.java#L107-L111
hawtio/hawtio
hawtio-ide/src/main/java/io/hawt/ide/IdeFacade.java
IdeFacade.ideaOpenAndNavigate
@Override public String ideaOpenAndNavigate(String fileName, int line, int column) throws Exception { """ Uses Intellij's XmlRPC mechanism to open and navigate to a file """ if (line < 0) line = 0; if (column < 0) column = 0; String xml = "<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\n" + "<methodCall>\n" + " <methodName>fileOpener.openAndNavigate</methodName>\n" + " <params>\n" + " <param><value><string>" + fileName + "</string></value></param>\n" + " <param><value><int>" + line + "</int></value></param>\n" + " <param><value><int>" + column + "</int></value></param>\n" + " </params>\n" + "</methodCall>\n"; return ideaXmlRpc(xml); }
java
@Override public String ideaOpenAndNavigate(String fileName, int line, int column) throws Exception { if (line < 0) line = 0; if (column < 0) column = 0; String xml = "<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\n" + "<methodCall>\n" + " <methodName>fileOpener.openAndNavigate</methodName>\n" + " <params>\n" + " <param><value><string>" + fileName + "</string></value></param>\n" + " <param><value><int>" + line + "</int></value></param>\n" + " <param><value><int>" + column + "</int></value></param>\n" + " </params>\n" + "</methodCall>\n"; return ideaXmlRpc(xml); }
[ "@", "Override", "public", "String", "ideaOpenAndNavigate", "(", "String", "fileName", ",", "int", "line", ",", "int", "column", ")", "throws", "Exception", "{", "if", "(", "line", "<", "0", ")", "line", "=", "0", ";", "if", "(", "column", "<", "0", ")", "column", "=", "0", ";", "String", "xml", "=", "\"<?xml version=\\\\\\\"1.0\\\\\\\" encoding=\\\\\\\"UTF-8\\\\\\\"?>\\n\"", "+", "\"<methodCall>\\n\"", "+", "\" <methodName>fileOpener.openAndNavigate</methodName>\\n\"", "+", "\" <params>\\n\"", "+", "\" <param><value><string>\"", "+", "fileName", "+", "\"</string></value></param>\\n\"", "+", "\" <param><value><int>\"", "+", "line", "+", "\"</int></value></param>\\n\"", "+", "\" <param><value><int>\"", "+", "column", "+", "\"</int></value></param>\\n\"", "+", "\" </params>\\n\"", "+", "\"</methodCall>\\n\"", ";", "return", "ideaXmlRpc", "(", "xml", ")", ";", "}" ]
Uses Intellij's XmlRPC mechanism to open and navigate to a file
[ "Uses", "Intellij", "s", "XmlRPC", "mechanism", "to", "open", "and", "navigate", "to", "a", "file" ]
train
https://github.com/hawtio/hawtio/blob/d8b1c8f246307c0313ba297a494106d0859f3ffd/hawtio-ide/src/main/java/io/hawt/ide/IdeFacade.java#L130-L145
logic-ng/LogicNG
src/main/java/org/logicng/solvers/maxsat/encodings/Encoder.java
Encoder.encodeCardinality
public void encodeCardinality(final MiniSatStyleSolver s, final LNGIntVector lits, int rhs) { """ Encodes a cardinality constraint in the given solver. @param s the solver @param lits the literals for the constraint @param rhs the right hand side of the constraint @throws IllegalStateException if the cardinality encoding is unknown """ switch (this.cardinalityEncoding) { case TOTALIZER: this.totalizer.build(s, lits, rhs); if (this.totalizer.hasCreatedEncoding()) this.totalizer.update(s, rhs); break; case MTOTALIZER: this.mtotalizer.encode(s, lits, rhs); break; default: throw new IllegalStateException("Unknown cardinality encoding: " + this.cardinalityEncoding); } }
java
public void encodeCardinality(final MiniSatStyleSolver s, final LNGIntVector lits, int rhs) { switch (this.cardinalityEncoding) { case TOTALIZER: this.totalizer.build(s, lits, rhs); if (this.totalizer.hasCreatedEncoding()) this.totalizer.update(s, rhs); break; case MTOTALIZER: this.mtotalizer.encode(s, lits, rhs); break; default: throw new IllegalStateException("Unknown cardinality encoding: " + this.cardinalityEncoding); } }
[ "public", "void", "encodeCardinality", "(", "final", "MiniSatStyleSolver", "s", ",", "final", "LNGIntVector", "lits", ",", "int", "rhs", ")", "{", "switch", "(", "this", ".", "cardinalityEncoding", ")", "{", "case", "TOTALIZER", ":", "this", ".", "totalizer", ".", "build", "(", "s", ",", "lits", ",", "rhs", ")", ";", "if", "(", "this", ".", "totalizer", ".", "hasCreatedEncoding", "(", ")", ")", "this", ".", "totalizer", ".", "update", "(", "s", ",", "rhs", ")", ";", "break", ";", "case", "MTOTALIZER", ":", "this", ".", "mtotalizer", ".", "encode", "(", "s", ",", "lits", ",", "rhs", ")", ";", "break", ";", "default", ":", "throw", "new", "IllegalStateException", "(", "\"Unknown cardinality encoding: \"", "+", "this", ".", "cardinalityEncoding", ")", ";", "}", "}" ]
Encodes a cardinality constraint in the given solver. @param s the solver @param lits the literals for the constraint @param rhs the right hand side of the constraint @throws IllegalStateException if the cardinality encoding is unknown
[ "Encodes", "a", "cardinality", "constraint", "in", "the", "given", "solver", "." ]
train
https://github.com/logic-ng/LogicNG/blob/bb9eb88a768be4be8e02a76cfc4a59e6c3fb7f2e/src/main/java/org/logicng/solvers/maxsat/encodings/Encoder.java#L168-L181
vincentk/joptimizer
src/main/java/com/joptimizer/util/Utils.java
Utils.calculateScaledResidual
public static double calculateScaledResidual(double[][] A, double[] x, double[] b) { """ Calculate the scaled residual <br> ||Ax-b||_oo/( ||A||_oo . ||x||_oo + ||b||_oo ), with <br> ||x||_oo = max(||x[i]||) """ DoubleMatrix2D AMatrix = DoubleFactory2D.dense.make(A); DoubleMatrix1D xVector = DoubleFactory1D.dense.make(x); DoubleMatrix1D bVector = DoubleFactory1D.dense.make(b); return calculateScaledResidual(AMatrix, xVector, bVector); }
java
public static double calculateScaledResidual(double[][] A, double[] x, double[] b){ DoubleMatrix2D AMatrix = DoubleFactory2D.dense.make(A); DoubleMatrix1D xVector = DoubleFactory1D.dense.make(x); DoubleMatrix1D bVector = DoubleFactory1D.dense.make(b); return calculateScaledResidual(AMatrix, xVector, bVector); }
[ "public", "static", "double", "calculateScaledResidual", "(", "double", "[", "]", "[", "]", "A", ",", "double", "[", "]", "x", ",", "double", "[", "]", "b", ")", "{", "DoubleMatrix2D", "AMatrix", "=", "DoubleFactory2D", ".", "dense", ".", "make", "(", "A", ")", ";", "DoubleMatrix1D", "xVector", "=", "DoubleFactory1D", ".", "dense", ".", "make", "(", "x", ")", ";", "DoubleMatrix1D", "bVector", "=", "DoubleFactory1D", ".", "dense", ".", "make", "(", "b", ")", ";", "return", "calculateScaledResidual", "(", "AMatrix", ",", "xVector", ",", "bVector", ")", ";", "}" ]
Calculate the scaled residual <br> ||Ax-b||_oo/( ||A||_oo . ||x||_oo + ||b||_oo ), with <br> ||x||_oo = max(||x[i]||)
[ "Calculate", "the", "scaled", "residual", "<br", ">", "||Ax", "-", "b||_oo", "/", "(", "||A||_oo", ".", "||x||_oo", "+", "||b||_oo", ")", "with", "<br", ">", "||x||_oo", "=", "max", "(", "||x", "[", "i", "]", "||", ")" ]
train
https://github.com/vincentk/joptimizer/blob/65064c1bb0b26c7261358021e4c93d06dd43564f/src/main/java/com/joptimizer/util/Utils.java#L167-L172
weld/core
environments/se/core/src/main/java/org/jboss/weld/environment/se/WeldContainer.java
WeldContainer.startInitialization
static WeldContainer startInitialization(String id, Deployment deployment, Bootstrap bootstrap) { """ Start the initialization. @param id @param manager @param bootstrap @return the initialized Weld container """ if (SINGLETON.isSet(id)) { throw WeldSELogger.LOG.weldContainerAlreadyRunning(id); } WeldContainer weldContainer = new WeldContainer(id, deployment, bootstrap); SINGLETON.set(id, weldContainer); RUNNING_CONTAINER_IDS.add(id); return weldContainer; }
java
static WeldContainer startInitialization(String id, Deployment deployment, Bootstrap bootstrap) { if (SINGLETON.isSet(id)) { throw WeldSELogger.LOG.weldContainerAlreadyRunning(id); } WeldContainer weldContainer = new WeldContainer(id, deployment, bootstrap); SINGLETON.set(id, weldContainer); RUNNING_CONTAINER_IDS.add(id); return weldContainer; }
[ "static", "WeldContainer", "startInitialization", "(", "String", "id", ",", "Deployment", "deployment", ",", "Bootstrap", "bootstrap", ")", "{", "if", "(", "SINGLETON", ".", "isSet", "(", "id", ")", ")", "{", "throw", "WeldSELogger", ".", "LOG", ".", "weldContainerAlreadyRunning", "(", "id", ")", ";", "}", "WeldContainer", "weldContainer", "=", "new", "WeldContainer", "(", "id", ",", "deployment", ",", "bootstrap", ")", ";", "SINGLETON", ".", "set", "(", "id", ",", "weldContainer", ")", ";", "RUNNING_CONTAINER_IDS", ".", "add", "(", "id", ")", ";", "return", "weldContainer", ";", "}" ]
Start the initialization. @param id @param manager @param bootstrap @return the initialized Weld container
[ "Start", "the", "initialization", "." ]
train
https://github.com/weld/core/blob/567a2eaf95b168597d23a56be89bf05a7834b2aa/environments/se/core/src/main/java/org/jboss/weld/environment/se/WeldContainer.java#L161-L169
prestodb/presto
presto-accumulo/src/main/java/com/facebook/presto/accumulo/conf/AccumuloTableProperties.java
AccumuloTableProperties.getSerializerClass
public static String getSerializerClass(Map<String, Object> tableProperties) { """ Gets the {@link AccumuloRowSerializer} class name to use for this table @param tableProperties The map of table properties @return The name of the AccumuloRowSerializer class """ requireNonNull(tableProperties); @SuppressWarnings("unchecked") String serializerClass = (String) tableProperties.get(SERIALIZER); return serializerClass; }
java
public static String getSerializerClass(Map<String, Object> tableProperties) { requireNonNull(tableProperties); @SuppressWarnings("unchecked") String serializerClass = (String) tableProperties.get(SERIALIZER); return serializerClass; }
[ "public", "static", "String", "getSerializerClass", "(", "Map", "<", "String", ",", "Object", ">", "tableProperties", ")", "{", "requireNonNull", "(", "tableProperties", ")", ";", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "String", "serializerClass", "=", "(", "String", ")", "tableProperties", ".", "get", "(", "SERIALIZER", ")", ";", "return", "serializerClass", ";", "}" ]
Gets the {@link AccumuloRowSerializer} class name to use for this table @param tableProperties The map of table properties @return The name of the AccumuloRowSerializer class
[ "Gets", "the", "{", "@link", "AccumuloRowSerializer", "}", "class", "name", "to", "use", "for", "this", "table" ]
train
https://github.com/prestodb/presto/blob/89de5e379d8f85e139d292b0add8c537a2a01a88/presto-accumulo/src/main/java/com/facebook/presto/accumulo/conf/AccumuloTableProperties.java#L234-L241
googleads/googleads-java-lib
examples/admanager_axis/src/main/java/admanager/axis/v201902/inventoryservice/GetAdUnitHierarchy.java
GetAdUnitHierarchy.displayInventoryTree
private static void displayInventoryTree(AdUnit root, Map<String, List<AdUnit>> treeMap) { """ Displays the ad unit tree beginning at the root ad unit. @param root the root ad unit @param treeMap the map of id to {@code List} of ad units """ displayInventoryTreeHelper(root, treeMap, 0); }
java
private static void displayInventoryTree(AdUnit root, Map<String, List<AdUnit>> treeMap) { displayInventoryTreeHelper(root, treeMap, 0); }
[ "private", "static", "void", "displayInventoryTree", "(", "AdUnit", "root", ",", "Map", "<", "String", ",", "List", "<", "AdUnit", ">", ">", "treeMap", ")", "{", "displayInventoryTreeHelper", "(", "root", ",", "treeMap", ",", "0", ")", ";", "}" ]
Displays the ad unit tree beginning at the root ad unit. @param root the root ad unit @param treeMap the map of id to {@code List} of ad units
[ "Displays", "the", "ad", "unit", "tree", "beginning", "at", "the", "root", "ad", "unit", "." ]
train
https://github.com/googleads/googleads-java-lib/blob/967957cc4f6076514e3a7926fe653e4f1f7cc9c9/examples/admanager_axis/src/main/java/admanager/axis/v201902/inventoryservice/GetAdUnitHierarchy.java#L154-L156
gallandarakhneorg/afc
core/maths/mathgeom/tobeincluded/src/d3/continuous/Path3f.java
Path3f.moveTo
public void moveTo(double x, double y, double z) { """ Adds a point to the path by moving to the specified coordinates specified in double precision. @param x the specified X coordinate @param y the specified Y coordinate @param z the specified Z coordinate """ if (this.numTypes>0 && this.types[this.numTypes-1]==PathElementType.MOVE_TO) { this.coords[this.numCoords-3] = x; this.coords[this.numCoords-2] = y; this.coords[this.numCoords-1] = z; } else { ensureSlots(false, 3); this.types[this.numTypes++] = PathElementType.MOVE_TO; this.coords[this.numCoords++] = x; this.coords[this.numCoords++] = y; this.coords[this.numCoords++] = z; } this.graphicalBounds = null; this.logicalBounds = null; }
java
public void moveTo(double x, double y, double z) { if (this.numTypes>0 && this.types[this.numTypes-1]==PathElementType.MOVE_TO) { this.coords[this.numCoords-3] = x; this.coords[this.numCoords-2] = y; this.coords[this.numCoords-1] = z; } else { ensureSlots(false, 3); this.types[this.numTypes++] = PathElementType.MOVE_TO; this.coords[this.numCoords++] = x; this.coords[this.numCoords++] = y; this.coords[this.numCoords++] = z; } this.graphicalBounds = null; this.logicalBounds = null; }
[ "public", "void", "moveTo", "(", "double", "x", ",", "double", "y", ",", "double", "z", ")", "{", "if", "(", "this", ".", "numTypes", ">", "0", "&&", "this", ".", "types", "[", "this", ".", "numTypes", "-", "1", "]", "==", "PathElementType", ".", "MOVE_TO", ")", "{", "this", ".", "coords", "[", "this", ".", "numCoords", "-", "3", "]", "=", "x", ";", "this", ".", "coords", "[", "this", ".", "numCoords", "-", "2", "]", "=", "y", ";", "this", ".", "coords", "[", "this", ".", "numCoords", "-", "1", "]", "=", "z", ";", "}", "else", "{", "ensureSlots", "(", "false", ",", "3", ")", ";", "this", ".", "types", "[", "this", ".", "numTypes", "++", "]", "=", "PathElementType", ".", "MOVE_TO", ";", "this", ".", "coords", "[", "this", ".", "numCoords", "++", "]", "=", "x", ";", "this", ".", "coords", "[", "this", ".", "numCoords", "++", "]", "=", "y", ";", "this", ".", "coords", "[", "this", ".", "numCoords", "++", "]", "=", "z", ";", "}", "this", ".", "graphicalBounds", "=", "null", ";", "this", ".", "logicalBounds", "=", "null", ";", "}" ]
Adds a point to the path by moving to the specified coordinates specified in double precision. @param x the specified X coordinate @param y the specified Y coordinate @param z the specified Z coordinate
[ "Adds", "a", "point", "to", "the", "path", "by", "moving", "to", "the", "specified", "coordinates", "specified", "in", "double", "precision", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/maths/mathgeom/tobeincluded/src/d3/continuous/Path3f.java#L1847-L1862
pressgang-ccms/PressGangCCMSBuilder
src/main/java/org/jboss/pressgang/ccms/contentspec/builder/DocBookXMLPreProcessor.java
DocBookXMLPreProcessor.createExternalLinkElement
protected String createExternalLinkElement(final DocBookVersion docBookVersion, final String title, final String url) { """ Creates a string that represents an external link. @param docBookVersion The DocBook Version the link should be created for. @param title @param url The links url. @return """ final StringBuilder linkEle = new StringBuilder(); if (docBookVersion == DocBookVersion.DOCBOOK_50) { linkEle.append("<link xmlns:xlink=\"http://www.w3.org/1999/xlink\" xlink:href=\"").append(url).append("\">"); linkEle.append(title); linkEle.append("</link>"); } else { linkEle.append("<ulink url=\"").append(url).append("\">"); linkEle.append(title); linkEle.append("</ulink>"); } return linkEle.toString(); }
java
protected String createExternalLinkElement(final DocBookVersion docBookVersion, final String title, final String url) { final StringBuilder linkEle = new StringBuilder(); if (docBookVersion == DocBookVersion.DOCBOOK_50) { linkEle.append("<link xmlns:xlink=\"http://www.w3.org/1999/xlink\" xlink:href=\"").append(url).append("\">"); linkEle.append(title); linkEle.append("</link>"); } else { linkEle.append("<ulink url=\"").append(url).append("\">"); linkEle.append(title); linkEle.append("</ulink>"); } return linkEle.toString(); }
[ "protected", "String", "createExternalLinkElement", "(", "final", "DocBookVersion", "docBookVersion", ",", "final", "String", "title", ",", "final", "String", "url", ")", "{", "final", "StringBuilder", "linkEle", "=", "new", "StringBuilder", "(", ")", ";", "if", "(", "docBookVersion", "==", "DocBookVersion", ".", "DOCBOOK_50", ")", "{", "linkEle", ".", "append", "(", "\"<link xmlns:xlink=\\\"http://www.w3.org/1999/xlink\\\" xlink:href=\\\"\"", ")", ".", "append", "(", "url", ")", ".", "append", "(", "\"\\\">\"", ")", ";", "linkEle", ".", "append", "(", "title", ")", ";", "linkEle", ".", "append", "(", "\"</link>\"", ")", ";", "}", "else", "{", "linkEle", ".", "append", "(", "\"<ulink url=\\\"\"", ")", ".", "append", "(", "url", ")", ".", "append", "(", "\"\\\">\"", ")", ";", "linkEle", ".", "append", "(", "title", ")", ";", "linkEle", ".", "append", "(", "\"</ulink>\"", ")", ";", "}", "return", "linkEle", ".", "toString", "(", ")", ";", "}" ]
Creates a string that represents an external link. @param docBookVersion The DocBook Version the link should be created for. @param title @param url The links url. @return
[ "Creates", "a", "string", "that", "represents", "an", "external", "link", "." ]
train
https://github.com/pressgang-ccms/PressGangCCMSBuilder/blob/5436d36ba1b3c5baa246b270e5fc350e6778bce8/src/main/java/org/jboss/pressgang/ccms/contentspec/builder/DocBookXMLPreProcessor.java#L268-L280
timols/java-gitlab-api
src/main/java/org/gitlab/api/GitlabAPI.java
GitlabAPI.deleteBranch
public void deleteBranch(Serializable projectId, String branchName) throws IOException { """ Delete Branch. @param projectId The id of the project @param branchName The name of the branch to delete @throws IOException on gitlab api call error """ String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabBranch.URL + '/' + sanitizePath(branchName); retrieve().method(DELETE).to(tailUrl, Void.class); }
java
public void deleteBranch(Serializable projectId, String branchName) throws IOException { String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabBranch.URL + '/' + sanitizePath(branchName); retrieve().method(DELETE).to(tailUrl, Void.class); }
[ "public", "void", "deleteBranch", "(", "Serializable", "projectId", ",", "String", "branchName", ")", "throws", "IOException", "{", "String", "tailUrl", "=", "GitlabProject", ".", "URL", "+", "\"/\"", "+", "sanitizeProjectId", "(", "projectId", ")", "+", "GitlabBranch", ".", "URL", "+", "'", "'", "+", "sanitizePath", "(", "branchName", ")", ";", "retrieve", "(", ")", ".", "method", "(", "DELETE", ")", ".", "to", "(", "tailUrl", ",", "Void", ".", "class", ")", ";", "}" ]
Delete Branch. @param projectId The id of the project @param branchName The name of the branch to delete @throws IOException on gitlab api call error
[ "Delete", "Branch", "." ]
train
https://github.com/timols/java-gitlab-api/blob/f03eedf952cfbb40306be3bf9234dcf78fab029e/src/main/java/org/gitlab/api/GitlabAPI.java#L2345-L2348
apache/flink
flink-runtime/src/main/java/org/apache/flink/runtime/zookeeper/ZooKeeperUtilityFactory.java
ZooKeeperUtilityFactory.createSharedValue
public ZooKeeperSharedValue createSharedValue(String path, byte[] seedValue) { """ Creates a {@link ZooKeeperSharedValue} to store a shared value between multiple instances. @param path to the shared value in ZooKeeper @param seedValue for the shared value @return a shared value """ return new ZooKeeperSharedValue( new SharedValue( facade, path, seedValue)); }
java
public ZooKeeperSharedValue createSharedValue(String path, byte[] seedValue) { return new ZooKeeperSharedValue( new SharedValue( facade, path, seedValue)); }
[ "public", "ZooKeeperSharedValue", "createSharedValue", "(", "String", "path", ",", "byte", "[", "]", "seedValue", ")", "{", "return", "new", "ZooKeeperSharedValue", "(", "new", "SharedValue", "(", "facade", ",", "path", ",", "seedValue", ")", ")", ";", "}" ]
Creates a {@link ZooKeeperSharedValue} to store a shared value between multiple instances. @param path to the shared value in ZooKeeper @param seedValue for the shared value @return a shared value
[ "Creates", "a", "{", "@link", "ZooKeeperSharedValue", "}", "to", "store", "a", "shared", "value", "between", "multiple", "instances", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/zookeeper/ZooKeeperUtilityFactory.java#L96-L102
google/closure-compiler
src/com/google/javascript/jscomp/MaybeReachingVariableUse.java
MaybeReachingVariableUse.removeFromUseIfLocal
private void removeFromUseIfLocal(String name, ReachingUses use) { """ Removes the variable for the given name from the node value in the upward exposed lattice. Do nothing if the variable name is one of the escaped variable. """ Var var = allVarsInFn.get(name); if (var == null) { return; } if (!escaped.contains(var)) { use.mayUseMap.removeAll(var); } }
java
private void removeFromUseIfLocal(String name, ReachingUses use) { Var var = allVarsInFn.get(name); if (var == null) { return; } if (!escaped.contains(var)) { use.mayUseMap.removeAll(var); } }
[ "private", "void", "removeFromUseIfLocal", "(", "String", "name", ",", "ReachingUses", "use", ")", "{", "Var", "var", "=", "allVarsInFn", ".", "get", "(", "name", ")", ";", "if", "(", "var", "==", "null", ")", "{", "return", ";", "}", "if", "(", "!", "escaped", ".", "contains", "(", "var", ")", ")", "{", "use", ".", "mayUseMap", ".", "removeAll", "(", "var", ")", ";", "}", "}" ]
Removes the variable for the given name from the node value in the upward exposed lattice. Do nothing if the variable name is one of the escaped variable.
[ "Removes", "the", "variable", "for", "the", "given", "name", "from", "the", "node", "value", "in", "the", "upward", "exposed", "lattice", ".", "Do", "nothing", "if", "the", "variable", "name", "is", "one", "of", "the", "escaped", "variable", "." ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/MaybeReachingVariableUse.java#L323-L331
VoltDB/voltdb
src/hsqldb19b3/org/hsqldb_voltpatches/types/DateTimeType.java
DateTimeType.convertSQLToJavaGMT
public Object convertSQLToJavaGMT(SessionInterface session, Object a) { """ /* return (Time) Type.SQL_TIME.getJavaDateObject(session, t, 0); java.sql.Timestamp value = new java.sql.Timestamp( (((TimestampData) o).getSeconds() - ((TimestampData) o) .getZone()) * 1000); """ long millis; switch (typeCode) { case Types.SQL_TIME : case Types.SQL_TIME_WITH_TIME_ZONE : millis = ((TimeData) a).getSeconds() * 1000; return new java.sql.Time(millis); case Types.SQL_DATE : millis = ((TimestampData) a).getSeconds() * 1000; return new java.sql.Date(millis); case Types.SQL_TIMESTAMP : case Types.SQL_TIMESTAMP_WITH_TIME_ZONE : millis = ((TimestampData) a).getSeconds() * 1000; java.sql.Timestamp value = new java.sql.Timestamp(millis); value.setNanos(((TimestampData) a).getNanos()); return value; default : throw Error.runtimeError(ErrorCode.U_S0500, "DateTimeType"); } }
java
public Object convertSQLToJavaGMT(SessionInterface session, Object a) { long millis; switch (typeCode) { case Types.SQL_TIME : case Types.SQL_TIME_WITH_TIME_ZONE : millis = ((TimeData) a).getSeconds() * 1000; return new java.sql.Time(millis); case Types.SQL_DATE : millis = ((TimestampData) a).getSeconds() * 1000; return new java.sql.Date(millis); case Types.SQL_TIMESTAMP : case Types.SQL_TIMESTAMP_WITH_TIME_ZONE : millis = ((TimestampData) a).getSeconds() * 1000; java.sql.Timestamp value = new java.sql.Timestamp(millis); value.setNanos(((TimestampData) a).getNanos()); return value; default : throw Error.runtimeError(ErrorCode.U_S0500, "DateTimeType"); } }
[ "public", "Object", "convertSQLToJavaGMT", "(", "SessionInterface", "session", ",", "Object", "a", ")", "{", "long", "millis", ";", "switch", "(", "typeCode", ")", "{", "case", "Types", ".", "SQL_TIME", ":", "case", "Types", ".", "SQL_TIME_WITH_TIME_ZONE", ":", "millis", "=", "(", "(", "TimeData", ")", "a", ")", ".", "getSeconds", "(", ")", "*", "1000", ";", "return", "new", "java", ".", "sql", ".", "Time", "(", "millis", ")", ";", "case", "Types", ".", "SQL_DATE", ":", "millis", "=", "(", "(", "TimestampData", ")", "a", ")", ".", "getSeconds", "(", ")", "*", "1000", ";", "return", "new", "java", ".", "sql", ".", "Date", "(", "millis", ")", ";", "case", "Types", ".", "SQL_TIMESTAMP", ":", "case", "Types", ".", "SQL_TIMESTAMP_WITH_TIME_ZONE", ":", "millis", "=", "(", "(", "TimestampData", ")", "a", ")", ".", "getSeconds", "(", ")", "*", "1000", ";", "java", ".", "sql", ".", "Timestamp", "value", "=", "new", "java", ".", "sql", ".", "Timestamp", "(", "millis", ")", ";", "value", ".", "setNanos", "(", "(", "(", "TimestampData", ")", "a", ")", ".", "getNanos", "(", ")", ")", ";", "return", "value", ";", "default", ":", "throw", "Error", ".", "runtimeError", "(", "ErrorCode", ".", "U_S0500", ",", "\"DateTimeType\"", ")", ";", "}", "}" ]
/* return (Time) Type.SQL_TIME.getJavaDateObject(session, t, 0); java.sql.Timestamp value = new java.sql.Timestamp( (((TimestampData) o).getSeconds() - ((TimestampData) o) .getZone()) * 1000);
[ "/", "*", "return", "(", "Time", ")", "Type", ".", "SQL_TIME", ".", "getJavaDateObject", "(", "session", "t", "0", ")", ";", "java", ".", "sql", ".", "Timestamp", "value", "=", "new", "java", ".", "sql", ".", "Timestamp", "(", "(((", "TimestampData", ")", "o", ")", ".", "getSeconds", "()", "-", "((", "TimestampData", ")", "o", ")", ".", "getZone", "()", ")", "*", "1000", ")", ";" ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/types/DateTimeType.java#L775-L805
pac4j/pac4j
pac4j-core/src/main/java/org/pac4j/core/context/ContextHelper.java
ContextHelper.getCookie
public static Cookie getCookie(final WebContext context, final String name) { """ Get a specific cookie by its name. @param context the current web context @param name the name of the cookie @return the cookie """ return getCookie(context.getRequestCookies(), name); }
java
public static Cookie getCookie(final WebContext context, final String name) { return getCookie(context.getRequestCookies(), name); }
[ "public", "static", "Cookie", "getCookie", "(", "final", "WebContext", "context", ",", "final", "String", "name", ")", "{", "return", "getCookie", "(", "context", ".", "getRequestCookies", "(", ")", ",", "name", ")", ";", "}" ]
Get a specific cookie by its name. @param context the current web context @param name the name of the cookie @return the cookie
[ "Get", "a", "specific", "cookie", "by", "its", "name", "." ]
train
https://github.com/pac4j/pac4j/blob/d9cd029f8783792b31dd48bf1e32f80628f2c4a3/pac4j-core/src/main/java/org/pac4j/core/context/ContextHelper.java#L40-L42
UrielCh/ovh-java-sdk
ovh-java-sdk-sms/src/main/java/net/minidev/ovh/api/ApiOvhSms.java
ApiOvhSms.serviceName_senders_POST
public String serviceName_senders_POST(String serviceName, String description, String reason, String sender) throws IOException { """ Create the sms sender given REST: POST /sms/{serviceName}/senders @param description [required] Sender description @param sender [required] The sender (alpha or phone number) @param reason [required] Message seen by the moderator @param serviceName [required] The internal name of your SMS offer """ String qPath = "/sms/{serviceName}/senders"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "description", description); addBody(o, "reason", reason); addBody(o, "sender", sender); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, String.class); }
java
public String serviceName_senders_POST(String serviceName, String description, String reason, String sender) throws IOException { String qPath = "/sms/{serviceName}/senders"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "description", description); addBody(o, "reason", reason); addBody(o, "sender", sender); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, String.class); }
[ "public", "String", "serviceName_senders_POST", "(", "String", "serviceName", ",", "String", "description", ",", "String", "reason", ",", "String", "sender", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/sms/{serviceName}/senders\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ")", ";", "HashMap", "<", "String", ",", "Object", ">", "o", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "addBody", "(", "o", ",", "\"description\"", ",", "description", ")", ";", "addBody", "(", "o", ",", "\"reason\"", ",", "reason", ")", ";", "addBody", "(", "o", ",", "\"sender\"", ",", "sender", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"POST\"", ",", "sb", ".", "toString", "(", ")", ",", "o", ")", ";", "return", "convertTo", "(", "resp", ",", "String", ".", "class", ")", ";", "}" ]
Create the sms sender given REST: POST /sms/{serviceName}/senders @param description [required] Sender description @param sender [required] The sender (alpha or phone number) @param reason [required] Message seen by the moderator @param serviceName [required] The internal name of your SMS offer
[ "Create", "the", "sms", "sender", "given" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-sms/src/main/java/net/minidev/ovh/api/ApiOvhSms.java#L164-L173
jbundle/jbundle
base/base/src/main/java/org/jbundle/base/db/PassThruTable.java
PassThruTable.addTable
public void addTable(Object objKey, BaseTable table) { """ Add this record's table to the list of tables to pass commands to. @param table The table to add. """ if (m_mapTable == null) m_mapTable = new Hashtable<Object,BaseTable>(); if (objKey == null) objKey = new Integer(m_mapTable.size()); m_mapTable.put(objKey, table); }
java
public void addTable(Object objKey, BaseTable table) { if (m_mapTable == null) m_mapTable = new Hashtable<Object,BaseTable>(); if (objKey == null) objKey = new Integer(m_mapTable.size()); m_mapTable.put(objKey, table); }
[ "public", "void", "addTable", "(", "Object", "objKey", ",", "BaseTable", "table", ")", "{", "if", "(", "m_mapTable", "==", "null", ")", "m_mapTable", "=", "new", "Hashtable", "<", "Object", ",", "BaseTable", ">", "(", ")", ";", "if", "(", "objKey", "==", "null", ")", "objKey", "=", "new", "Integer", "(", "m_mapTable", ".", "size", "(", ")", ")", ";", "m_mapTable", ".", "put", "(", "objKey", ",", "table", ")", ";", "}" ]
Add this record's table to the list of tables to pass commands to. @param table The table to add.
[ "Add", "this", "record", "s", "table", "to", "the", "list", "of", "tables", "to", "pass", "commands", "to", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/db/PassThruTable.java#L506-L513
ben-manes/caffeine
caffeine/src/main/java/com/github/benmanes/caffeine/cache/BoundedLocalCache.java
BoundedLocalCache.removeWithWriter
@Nullable V removeWithWriter(Object key) { """ Removes the mapping for a key after notifying the writer. @param key key whose mapping is to be removed @return the removed value or null if no mapping was found """ @SuppressWarnings("unchecked") K castKey = (K) key; @SuppressWarnings({"unchecked", "rawtypes"}) Node<K, V>[] node = new Node[1]; @SuppressWarnings("unchecked") V[] oldValue = (V[]) new Object[1]; RemovalCause[] cause = new RemovalCause[1]; data.computeIfPresent(nodeFactory.newLookupKey(key), (k, n) -> { synchronized (n) { oldValue[0] = n.getValue(); if (oldValue[0] == null) { cause[0] = RemovalCause.COLLECTED; } else if (hasExpired(n, expirationTicker().read())) { cause[0] = RemovalCause.EXPIRED; } else { cause[0] = RemovalCause.EXPLICIT; } writer.delete(castKey, oldValue[0], cause[0]); n.retire(); } node[0] = n; return null; }); if (cause[0] != null) { afterWrite(new RemovalTask(node[0])); if (hasRemovalListener()) { notifyRemoval(castKey, oldValue[0], cause[0]); } } return (cause[0] == RemovalCause.EXPLICIT) ? oldValue[0] : null; }
java
@Nullable V removeWithWriter(Object key) { @SuppressWarnings("unchecked") K castKey = (K) key; @SuppressWarnings({"unchecked", "rawtypes"}) Node<K, V>[] node = new Node[1]; @SuppressWarnings("unchecked") V[] oldValue = (V[]) new Object[1]; RemovalCause[] cause = new RemovalCause[1]; data.computeIfPresent(nodeFactory.newLookupKey(key), (k, n) -> { synchronized (n) { oldValue[0] = n.getValue(); if (oldValue[0] == null) { cause[0] = RemovalCause.COLLECTED; } else if (hasExpired(n, expirationTicker().read())) { cause[0] = RemovalCause.EXPIRED; } else { cause[0] = RemovalCause.EXPLICIT; } writer.delete(castKey, oldValue[0], cause[0]); n.retire(); } node[0] = n; return null; }); if (cause[0] != null) { afterWrite(new RemovalTask(node[0])); if (hasRemovalListener()) { notifyRemoval(castKey, oldValue[0], cause[0]); } } return (cause[0] == RemovalCause.EXPLICIT) ? oldValue[0] : null; }
[ "@", "Nullable", "V", "removeWithWriter", "(", "Object", "key", ")", "{", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "K", "castKey", "=", "(", "K", ")", "key", ";", "@", "SuppressWarnings", "(", "{", "\"unchecked\"", ",", "\"rawtypes\"", "}", ")", "Node", "<", "K", ",", "V", ">", "[", "]", "node", "=", "new", "Node", "[", "1", "]", ";", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "V", "[", "]", "oldValue", "=", "(", "V", "[", "]", ")", "new", "Object", "[", "1", "]", ";", "RemovalCause", "[", "]", "cause", "=", "new", "RemovalCause", "[", "1", "]", ";", "data", ".", "computeIfPresent", "(", "nodeFactory", ".", "newLookupKey", "(", "key", ")", ",", "(", "k", ",", "n", ")", "->", "{", "synchronized", "(", "n", ")", "{", "oldValue", "[", "0", "]", "=", "n", ".", "getValue", "(", ")", ";", "if", "(", "oldValue", "[", "0", "]", "==", "null", ")", "{", "cause", "[", "0", "]", "=", "RemovalCause", ".", "COLLECTED", ";", "}", "else", "if", "(", "hasExpired", "(", "n", ",", "expirationTicker", "(", ")", ".", "read", "(", ")", ")", ")", "{", "cause", "[", "0", "]", "=", "RemovalCause", ".", "EXPIRED", ";", "}", "else", "{", "cause", "[", "0", "]", "=", "RemovalCause", ".", "EXPLICIT", ";", "}", "writer", ".", "delete", "(", "castKey", ",", "oldValue", "[", "0", "]", ",", "cause", "[", "0", "]", ")", ";", "n", ".", "retire", "(", ")", ";", "}", "node", "[", "0", "]", "=", "n", ";", "return", "null", ";", "}", ")", ";", "if", "(", "cause", "[", "0", "]", "!=", "null", ")", "{", "afterWrite", "(", "new", "RemovalTask", "(", "node", "[", "0", "]", ")", ")", ";", "if", "(", "hasRemovalListener", "(", ")", ")", "{", "notifyRemoval", "(", "castKey", ",", "oldValue", "[", "0", "]", ",", "cause", "[", "0", "]", ")", ";", "}", "}", "return", "(", "cause", "[", "0", "]", "==", "RemovalCause", ".", "EXPLICIT", ")", "?", "oldValue", "[", "0", "]", ":", "null", ";", "}" ]
Removes the mapping for a key after notifying the writer. @param key key whose mapping is to be removed @return the removed value or null if no mapping was found
[ "Removes", "the", "mapping", "for", "a", "key", "after", "notifying", "the", "writer", "." ]
train
https://github.com/ben-manes/caffeine/blob/4cf6d6e6a18ea2e8088f166261e5949343b0f2eb/caffeine/src/main/java/com/github/benmanes/caffeine/cache/BoundedLocalCache.java#L2086-L2119
JadiraOrg/jadira
bindings/src/main/java/org/jadira/bindings/core/binder/BasicBinder.java
BasicBinder.convertTo
public <S, T> T convertTo(Class<T> output, Object object) { """ Convert an object to the given target class This method infers the source type for the conversion from the runtime type of object. @param output The target class to convert the object to @param object The object to be converted """ return convertTo(output, object, DefaultBinding.class); }
java
public <S, T> T convertTo(Class<T> output, Object object) { return convertTo(output, object, DefaultBinding.class); }
[ "public", "<", "S", ",", "T", ">", "T", "convertTo", "(", "Class", "<", "T", ">", "output", ",", "Object", "object", ")", "{", "return", "convertTo", "(", "output", ",", "object", ",", "DefaultBinding", ".", "class", ")", ";", "}" ]
Convert an object to the given target class This method infers the source type for the conversion from the runtime type of object. @param output The target class to convert the object to @param object The object to be converted
[ "Convert", "an", "object", "to", "the", "given", "target", "class", "This", "method", "infers", "the", "source", "type", "for", "the", "conversion", "from", "the", "runtime", "type", "of", "object", "." ]
train
https://github.com/JadiraOrg/jadira/blob/d55d0238395f0cb900531f1f08b4b2d87fa9a4f6/bindings/src/main/java/org/jadira/bindings/core/binder/BasicBinder.java#L730-L732
Kickflip/kickflip-android-sdk
sdk/src/main/java/io/kickflip/sdk/api/KickflipApiClient.java
KickflipApiClient.executeAndRetryRequest
private void executeAndRetryRequest(HttpRequest request, Class responseClass, KickflipCallback cb) throws IOException { """ Execute a HTTPRequest and retry up to {@link io.kickflip.sdk.api.KickflipApiClient#MAX_EOF_RETRIES} times if an EOFException occurs. This is an attempt to address what appears to be a bug in NetHttpTransport <p/> See <a href="https://code.google.com/p/google-api-java-client/issues/detail?id=869&can=4&colspec=Milestone%20Priority%20Component%20Type%20Summary%20ID%20Status%20Owner">This issue</a> @param request @param responseClass @param cb @throws IOException """ int numRetries = 0; while (numRetries < MAX_EOF_RETRIES + 1) { try { executeAndHandleHttpRequest(request, responseClass, cb); // If executeAndHandleHttpRequest completes without throwing EOFException // we're good return; } catch (EOFException eof) { if (VERBOSE) Log.i(TAG, "Got EOFException. Retrying.."); // An EOFException may be due to a bug in the way Connections are recycled // within the NetHttpTransport package. Ignore and retry } numRetries++; } postExceptionToCallback(cb, UNKNOWN_ERROR_CODE); }
java
private void executeAndRetryRequest(HttpRequest request, Class responseClass, KickflipCallback cb) throws IOException { int numRetries = 0; while (numRetries < MAX_EOF_RETRIES + 1) { try { executeAndHandleHttpRequest(request, responseClass, cb); // If executeAndHandleHttpRequest completes without throwing EOFException // we're good return; } catch (EOFException eof) { if (VERBOSE) Log.i(TAG, "Got EOFException. Retrying.."); // An EOFException may be due to a bug in the way Connections are recycled // within the NetHttpTransport package. Ignore and retry } numRetries++; } postExceptionToCallback(cb, UNKNOWN_ERROR_CODE); }
[ "private", "void", "executeAndRetryRequest", "(", "HttpRequest", "request", ",", "Class", "responseClass", ",", "KickflipCallback", "cb", ")", "throws", "IOException", "{", "int", "numRetries", "=", "0", ";", "while", "(", "numRetries", "<", "MAX_EOF_RETRIES", "+", "1", ")", "{", "try", "{", "executeAndHandleHttpRequest", "(", "request", ",", "responseClass", ",", "cb", ")", ";", "// If executeAndHandleHttpRequest completes without throwing EOFException", "// we're good", "return", ";", "}", "catch", "(", "EOFException", "eof", ")", "{", "if", "(", "VERBOSE", ")", "Log", ".", "i", "(", "TAG", ",", "\"Got EOFException. Retrying..\"", ")", ";", "// An EOFException may be due to a bug in the way Connections are recycled", "// within the NetHttpTransport package. Ignore and retry", "}", "numRetries", "++", ";", "}", "postExceptionToCallback", "(", "cb", ",", "UNKNOWN_ERROR_CODE", ")", ";", "}" ]
Execute a HTTPRequest and retry up to {@link io.kickflip.sdk.api.KickflipApiClient#MAX_EOF_RETRIES} times if an EOFException occurs. This is an attempt to address what appears to be a bug in NetHttpTransport <p/> See <a href="https://code.google.com/p/google-api-java-client/issues/detail?id=869&can=4&colspec=Milestone%20Priority%20Component%20Type%20Summary%20ID%20Status%20Owner">This issue</a> @param request @param responseClass @param cb @throws IOException
[ "Execute", "a", "HTTPRequest", "and", "retry", "up", "to", "{", "@link", "io", ".", "kickflip", ".", "sdk", ".", "api", ".", "KickflipApiClient#MAX_EOF_RETRIES", "}", "times", "if", "an", "EOFException", "occurs", ".", "This", "is", "an", "attempt", "to", "address", "what", "appears", "to", "be", "a", "bug", "in", "NetHttpTransport", "<p", "/", ">", "See", "<a", "href", "=", "https", ":", "//", "code", ".", "google", ".", "com", "/", "p", "/", "google", "-", "api", "-", "java", "-", "client", "/", "issues", "/", "detail?id", "=", "869&can", "=", "4&colspec", "=", "Milestone%20Priority%20Component%20Type%20Summary%20ID%20Status%20Owner", ">", "This", "issue<", "/", "a", ">" ]
train
https://github.com/Kickflip/kickflip-android-sdk/blob/af3aae5f1128d7376e67aefe11a3a1a3844be734/sdk/src/main/java/io/kickflip/sdk/api/KickflipApiClient.java#L642-L658
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/transform/OpPredicate.java
OpPredicate.opNameMatches
public static OpPredicate opNameMatches(final String regex) { """ Return true if the operation name (i.e., "add", "mul", etc - not the user specified name) matches the specified regular expression """ return new OpPredicate() { @Override public boolean matches(SameDiff sameDiff, DifferentialFunction function) { return function.getOwnName().matches(regex); } }; }
java
public static OpPredicate opNameMatches(final String regex){ return new OpPredicate() { @Override public boolean matches(SameDiff sameDiff, DifferentialFunction function) { return function.getOwnName().matches(regex); } }; }
[ "public", "static", "OpPredicate", "opNameMatches", "(", "final", "String", "regex", ")", "{", "return", "new", "OpPredicate", "(", ")", "{", "@", "Override", "public", "boolean", "matches", "(", "SameDiff", "sameDiff", ",", "DifferentialFunction", "function", ")", "{", "return", "function", ".", "getOwnName", "(", ")", ".", "matches", "(", "regex", ")", ";", "}", "}", ";", "}" ]
Return true if the operation name (i.e., "add", "mul", etc - not the user specified name) matches the specified regular expression
[ "Return", "true", "if", "the", "operation", "name", "(", "i", ".", "e", ".", "add", "mul", "etc", "-", "not", "the", "user", "specified", "name", ")", "matches", "the", "specified", "regular", "expression" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/transform/OpPredicate.java#L78-L85
alkacon/opencms-core
src/org/opencms/ade/configuration/CmsConfigurationReader.java
CmsConfigurationReader.parseFunctionReference
protected void parseFunctionReference(I_CmsXmlContentLocation node) { """ Parses a function reference node.<p> @param node the function reference node """ String name = node.getSubValue(N_NAME).asString(m_cms); CmsUUID functionId = node.getSubValue(N_FUNCTION).asId(m_cms); CmsUUID functionDefaultPageId = null; I_CmsXmlContentValueLocation defaultPageValue = node.getSubValue(N_FUNCTION_DEFAULT_PAGE); if (defaultPageValue != null) { functionDefaultPageId = defaultPageValue.asId(m_cms); } I_CmsXmlContentValueLocation orderNode = node.getSubValue(N_ORDER); int order = I_CmsConfigurationObject.DEFAULT_ORDER; if (orderNode != null) { String orderStr = orderNode.asString(m_cms); try { order = Integer.parseInt(orderStr); } catch (NumberFormatException e) { // noop } } m_functionReferences.add(new CmsFunctionReference(name, functionId, functionDefaultPageId, order)); }
java
protected void parseFunctionReference(I_CmsXmlContentLocation node) { String name = node.getSubValue(N_NAME).asString(m_cms); CmsUUID functionId = node.getSubValue(N_FUNCTION).asId(m_cms); CmsUUID functionDefaultPageId = null; I_CmsXmlContentValueLocation defaultPageValue = node.getSubValue(N_FUNCTION_DEFAULT_PAGE); if (defaultPageValue != null) { functionDefaultPageId = defaultPageValue.asId(m_cms); } I_CmsXmlContentValueLocation orderNode = node.getSubValue(N_ORDER); int order = I_CmsConfigurationObject.DEFAULT_ORDER; if (orderNode != null) { String orderStr = orderNode.asString(m_cms); try { order = Integer.parseInt(orderStr); } catch (NumberFormatException e) { // noop } } m_functionReferences.add(new CmsFunctionReference(name, functionId, functionDefaultPageId, order)); }
[ "protected", "void", "parseFunctionReference", "(", "I_CmsXmlContentLocation", "node", ")", "{", "String", "name", "=", "node", ".", "getSubValue", "(", "N_NAME", ")", ".", "asString", "(", "m_cms", ")", ";", "CmsUUID", "functionId", "=", "node", ".", "getSubValue", "(", "N_FUNCTION", ")", ".", "asId", "(", "m_cms", ")", ";", "CmsUUID", "functionDefaultPageId", "=", "null", ";", "I_CmsXmlContentValueLocation", "defaultPageValue", "=", "node", ".", "getSubValue", "(", "N_FUNCTION_DEFAULT_PAGE", ")", ";", "if", "(", "defaultPageValue", "!=", "null", ")", "{", "functionDefaultPageId", "=", "defaultPageValue", ".", "asId", "(", "m_cms", ")", ";", "}", "I_CmsXmlContentValueLocation", "orderNode", "=", "node", ".", "getSubValue", "(", "N_ORDER", ")", ";", "int", "order", "=", "I_CmsConfigurationObject", ".", "DEFAULT_ORDER", ";", "if", "(", "orderNode", "!=", "null", ")", "{", "String", "orderStr", "=", "orderNode", ".", "asString", "(", "m_cms", ")", ";", "try", "{", "order", "=", "Integer", ".", "parseInt", "(", "orderStr", ")", ";", "}", "catch", "(", "NumberFormatException", "e", ")", "{", "// noop", "}", "}", "m_functionReferences", ".", "add", "(", "new", "CmsFunctionReference", "(", "name", ",", "functionId", ",", "functionDefaultPageId", ",", "order", ")", ")", ";", "}" ]
Parses a function reference node.<p> @param node the function reference node
[ "Parses", "a", "function", "reference", "node", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/configuration/CmsConfigurationReader.java#L879-L899
apache/flink
flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/dataformat/Decimal.java
Decimal.fromUnscaledBytes
public static Decimal fromUnscaledBytes(int precision, int scale, byte[] bytes) { """ we assume the bytes were generated by us from toUnscaledBytes() """ if (precision > MAX_COMPACT_PRECISION) { BigDecimal bd = new BigDecimal(new BigInteger(bytes), scale); return new Decimal(precision, scale, -1, bd); } assert bytes.length == 8; long l = 0; for (int i = 0; i < 8; i++) { l <<= 8; l |= (bytes[i] & (0xff)); } return new Decimal(precision, scale, l, null); }
java
public static Decimal fromUnscaledBytes(int precision, int scale, byte[] bytes) { if (precision > MAX_COMPACT_PRECISION) { BigDecimal bd = new BigDecimal(new BigInteger(bytes), scale); return new Decimal(precision, scale, -1, bd); } assert bytes.length == 8; long l = 0; for (int i = 0; i < 8; i++) { l <<= 8; l |= (bytes[i] & (0xff)); } return new Decimal(precision, scale, l, null); }
[ "public", "static", "Decimal", "fromUnscaledBytes", "(", "int", "precision", ",", "int", "scale", ",", "byte", "[", "]", "bytes", ")", "{", "if", "(", "precision", ">", "MAX_COMPACT_PRECISION", ")", "{", "BigDecimal", "bd", "=", "new", "BigDecimal", "(", "new", "BigInteger", "(", "bytes", ")", ",", "scale", ")", ";", "return", "new", "Decimal", "(", "precision", ",", "scale", ",", "-", "1", ",", "bd", ")", ";", "}", "assert", "bytes", ".", "length", "==", "8", ";", "long", "l", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "8", ";", "i", "++", ")", "{", "l", "<<=", "8", ";", "l", "|=", "(", "bytes", "[", "i", "]", "&", "(", "0xff", ")", ")", ";", "}", "return", "new", "Decimal", "(", "precision", ",", "scale", ",", "l", ",", "null", ")", ";", "}" ]
we assume the bytes were generated by us from toUnscaledBytes()
[ "we", "assume", "the", "bytes", "were", "generated", "by", "us", "from", "toUnscaledBytes", "()" ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/dataformat/Decimal.java#L209-L221
apache/flink
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/operations/AliasOperationUtils.java
AliasOperationUtils.createAliasList
public static List<Expression> createAliasList(List<Expression> aliases, TableOperation child) { """ Creates a list of valid alias expressions. Resulting expression might still contain {@link UnresolvedReferenceExpression}. @param aliases aliases to validate @param child relational operation on top of which to apply the aliases @return validated list of aliases """ TableSchema childSchema = child.getTableSchema(); if (aliases.size() > childSchema.getFieldCount()) { throw new ValidationException("Aliasing more fields than we actually have."); } List<ValueLiteralExpression> fieldAliases = aliases.stream() .map(f -> f.accept(aliasLiteralValidator)) .collect(Collectors.toList()); String[] childNames = childSchema.getFieldNames(); return IntStream.range(0, childNames.length) .mapToObj(idx -> { UnresolvedReferenceExpression oldField = new UnresolvedReferenceExpression(childNames[idx]); if (idx < fieldAliases.size()) { ValueLiteralExpression alias = fieldAliases.get(idx); return new CallExpression(BuiltInFunctionDefinitions.AS, Arrays.asList(oldField, alias)); } else { return oldField; } }).collect(Collectors.toList()); }
java
public static List<Expression> createAliasList(List<Expression> aliases, TableOperation child) { TableSchema childSchema = child.getTableSchema(); if (aliases.size() > childSchema.getFieldCount()) { throw new ValidationException("Aliasing more fields than we actually have."); } List<ValueLiteralExpression> fieldAliases = aliases.stream() .map(f -> f.accept(aliasLiteralValidator)) .collect(Collectors.toList()); String[] childNames = childSchema.getFieldNames(); return IntStream.range(0, childNames.length) .mapToObj(idx -> { UnresolvedReferenceExpression oldField = new UnresolvedReferenceExpression(childNames[idx]); if (idx < fieldAliases.size()) { ValueLiteralExpression alias = fieldAliases.get(idx); return new CallExpression(BuiltInFunctionDefinitions.AS, Arrays.asList(oldField, alias)); } else { return oldField; } }).collect(Collectors.toList()); }
[ "public", "static", "List", "<", "Expression", ">", "createAliasList", "(", "List", "<", "Expression", ">", "aliases", ",", "TableOperation", "child", ")", "{", "TableSchema", "childSchema", "=", "child", ".", "getTableSchema", "(", ")", ";", "if", "(", "aliases", ".", "size", "(", ")", ">", "childSchema", ".", "getFieldCount", "(", ")", ")", "{", "throw", "new", "ValidationException", "(", "\"Aliasing more fields than we actually have.\"", ")", ";", "}", "List", "<", "ValueLiteralExpression", ">", "fieldAliases", "=", "aliases", ".", "stream", "(", ")", ".", "map", "(", "f", "->", "f", ".", "accept", "(", "aliasLiteralValidator", ")", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ";", "String", "[", "]", "childNames", "=", "childSchema", ".", "getFieldNames", "(", ")", ";", "return", "IntStream", ".", "range", "(", "0", ",", "childNames", ".", "length", ")", ".", "mapToObj", "(", "idx", "->", "{", "UnresolvedReferenceExpression", "oldField", "=", "new", "UnresolvedReferenceExpression", "(", "childNames", "[", "idx", "]", ")", ";", "if", "(", "idx", "<", "fieldAliases", ".", "size", "(", ")", ")", "{", "ValueLiteralExpression", "alias", "=", "fieldAliases", ".", "get", "(", "idx", ")", ";", "return", "new", "CallExpression", "(", "BuiltInFunctionDefinitions", ".", "AS", ",", "Arrays", ".", "asList", "(", "oldField", ",", "alias", ")", ")", ";", "}", "else", "{", "return", "oldField", ";", "}", "}", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ";", "}" ]
Creates a list of valid alias expressions. Resulting expression might still contain {@link UnresolvedReferenceExpression}. @param aliases aliases to validate @param child relational operation on top of which to apply the aliases @return validated list of aliases
[ "Creates", "a", "list", "of", "valid", "alias", "expressions", ".", "Resulting", "expression", "might", "still", "contain", "{", "@link", "UnresolvedReferenceExpression", "}", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/operations/AliasOperationUtils.java#L55-L77
GenesysPureEngage/workspace-client-java
src/main/java/com/genesys/internal/workspace/api/UcsApi.java
UcsApi.setCompleted
public ApiSuccessResponse setCompleted(String id, CompletedData completedData) throws ApiException { """ Set the interaction as being completed @param id id of the Interaction (required) @param completedData (optional) @return ApiSuccessResponse @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body """ ApiResponse<ApiSuccessResponse> resp = setCompletedWithHttpInfo(id, completedData); return resp.getData(); }
java
public ApiSuccessResponse setCompleted(String id, CompletedData completedData) throws ApiException { ApiResponse<ApiSuccessResponse> resp = setCompletedWithHttpInfo(id, completedData); return resp.getData(); }
[ "public", "ApiSuccessResponse", "setCompleted", "(", "String", "id", ",", "CompletedData", "completedData", ")", "throws", "ApiException", "{", "ApiResponse", "<", "ApiSuccessResponse", ">", "resp", "=", "setCompletedWithHttpInfo", "(", "id", ",", "completedData", ")", ";", "return", "resp", ".", "getData", "(", ")", ";", "}" ]
Set the interaction as being completed @param id id of the Interaction (required) @param completedData (optional) @return ApiSuccessResponse @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
[ "Set", "the", "interaction", "as", "being", "completed" ]
train
https://github.com/GenesysPureEngage/workspace-client-java/blob/509fdd9e89b9359d012f9a72be95037a3cef53e6/src/main/java/com/genesys/internal/workspace/api/UcsApi.java#L2044-L2047
ist-dresden/composum
sling/core/commons/src/main/java/com/composum/sling/core/util/LinkUtil.java
LinkUtil.getUrl
public static String getUrl(SlingHttpServletRequest request, String url, String extension) { """ Builds a (mapped) link to a path (resource path) without selectors and with the given extension. @param request the request context for path mapping (the result is always mapped) @param url the URL to use (complete) or the path to an addressed resource (without any extension) @param extension the extension (can be 'null'; should be 'html or '.html' by default) @return the mapped url for the referenced resource """ return getUrl(request, url, null, extension); }
java
public static String getUrl(SlingHttpServletRequest request, String url, String extension) { return getUrl(request, url, null, extension); }
[ "public", "static", "String", "getUrl", "(", "SlingHttpServletRequest", "request", ",", "String", "url", ",", "String", "extension", ")", "{", "return", "getUrl", "(", "request", ",", "url", ",", "null", ",", "extension", ")", ";", "}" ]
Builds a (mapped) link to a path (resource path) without selectors and with the given extension. @param request the request context for path mapping (the result is always mapped) @param url the URL to use (complete) or the path to an addressed resource (without any extension) @param extension the extension (can be 'null'; should be 'html or '.html' by default) @return the mapped url for the referenced resource
[ "Builds", "a", "(", "mapped", ")", "link", "to", "a", "path", "(", "resource", "path", ")", "without", "selectors", "and", "with", "the", "given", "extension", "." ]
train
https://github.com/ist-dresden/composum/blob/ebc79f559f6022c935240c19102539bdfb1bd1e2/sling/core/commons/src/main/java/com/composum/sling/core/util/LinkUtil.java#L88-L90
baidubce/bce-sdk-java
src/main/java/com/baidubce/services/bos/BosClient.java
BosClient.generatePresignedUrl
public URL generatePresignedUrl(String bucketName, String key, int expirationInSeconds, HttpMethodName method) { """ Returns a pre-signed URL for accessing a Bos resource. @param bucketName The name of the bucket containing the desired object. @param key The key in the specified bucket under which the desired object is stored. @param expirationInSeconds The expiration after which the returned pre-signed URL will expire. @param method The HTTP method verb to use for this URL @return A pre-signed URL which expires at the specified time, and can be used to allow anyone to download the specified object from Bos, without exposing the owner's Bce secret access key. """ GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, key, method); request.setExpiration(expirationInSeconds); return this.generatePresignedUrl(request); }
java
public URL generatePresignedUrl(String bucketName, String key, int expirationInSeconds, HttpMethodName method) { GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, key, method); request.setExpiration(expirationInSeconds); return this.generatePresignedUrl(request); }
[ "public", "URL", "generatePresignedUrl", "(", "String", "bucketName", ",", "String", "key", ",", "int", "expirationInSeconds", ",", "HttpMethodName", "method", ")", "{", "GeneratePresignedUrlRequest", "request", "=", "new", "GeneratePresignedUrlRequest", "(", "bucketName", ",", "key", ",", "method", ")", ";", "request", ".", "setExpiration", "(", "expirationInSeconds", ")", ";", "return", "this", ".", "generatePresignedUrl", "(", "request", ")", ";", "}" ]
Returns a pre-signed URL for accessing a Bos resource. @param bucketName The name of the bucket containing the desired object. @param key The key in the specified bucket under which the desired object is stored. @param expirationInSeconds The expiration after which the returned pre-signed URL will expire. @param method The HTTP method verb to use for this URL @return A pre-signed URL which expires at the specified time, and can be used to allow anyone to download the specified object from Bos, without exposing the owner's Bce secret access key.
[ "Returns", "a", "pre", "-", "signed", "URL", "for", "accessing", "a", "Bos", "resource", "." ]
train
https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/bos/BosClient.java#L474-L479
OpenLiberty/open-liberty
dev/com.ibm.ws.security.fat.common/src/com/ibm/ws/security/fat/common/web/WebFormUtils.java
WebFormUtils.getAndSubmitLoginForm
public Page getAndSubmitLoginForm(HtmlPage loginPage, String username, String password) throws Exception { """ Fills out the first form found in the provided login page with the specified credentials and submits the form. An exception is thrown if the provided login page does not have any forms, if the first form does not have an action of "j_security_check", or if the form is missing the appropriate username/password inputs or submit button. """ if (loginPage == null) { throw new Exception("Cannot submit login form because the provided HtmlPage object is null."); } HtmlForm form = getAndValidateLoginForm(loginPage); return fillAndSubmitCredentialForm(form, username, password); }
java
public Page getAndSubmitLoginForm(HtmlPage loginPage, String username, String password) throws Exception { if (loginPage == null) { throw new Exception("Cannot submit login form because the provided HtmlPage object is null."); } HtmlForm form = getAndValidateLoginForm(loginPage); return fillAndSubmitCredentialForm(form, username, password); }
[ "public", "Page", "getAndSubmitLoginForm", "(", "HtmlPage", "loginPage", ",", "String", "username", ",", "String", "password", ")", "throws", "Exception", "{", "if", "(", "loginPage", "==", "null", ")", "{", "throw", "new", "Exception", "(", "\"Cannot submit login form because the provided HtmlPage object is null.\"", ")", ";", "}", "HtmlForm", "form", "=", "getAndValidateLoginForm", "(", "loginPage", ")", ";", "return", "fillAndSubmitCredentialForm", "(", "form", ",", "username", ",", "password", ")", ";", "}" ]
Fills out the first form found in the provided login page with the specified credentials and submits the form. An exception is thrown if the provided login page does not have any forms, if the first form does not have an action of "j_security_check", or if the form is missing the appropriate username/password inputs or submit button.
[ "Fills", "out", "the", "first", "form", "found", "in", "the", "provided", "login", "page", "with", "the", "specified", "credentials", "and", "submits", "the", "form", ".", "An", "exception", "is", "thrown", "if", "the", "provided", "login", "page", "does", "not", "have", "any", "forms", "if", "the", "first", "form", "does", "not", "have", "an", "action", "of", "j_security_check", "or", "if", "the", "form", "is", "missing", "the", "appropriate", "username", "/", "password", "inputs", "or", "submit", "button", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.fat.common/src/com/ibm/ws/security/fat/common/web/WebFormUtils.java#L22-L28
looly/hutool
hutool-core/src/main/java/cn/hutool/core/collection/CollUtil.java
CollUtil.removeBlank
public static <T extends CharSequence> Collection<T> removeBlank(Collection<T> collection) { """ 去除{@code null}或者""或者空白字符串 元素 @param collection 集合 @return 处理后的集合 @since 3.2.2 """ return filter(collection, new Filter<T>() { @Override public boolean accept(T t) { return false == StrUtil.isBlank(t); } }); }
java
public static <T extends CharSequence> Collection<T> removeBlank(Collection<T> collection) { return filter(collection, new Filter<T>() { @Override public boolean accept(T t) { return false == StrUtil.isBlank(t); } }); }
[ "public", "static", "<", "T", "extends", "CharSequence", ">", "Collection", "<", "T", ">", "removeBlank", "(", "Collection", "<", "T", ">", "collection", ")", "{", "return", "filter", "(", "collection", ",", "new", "Filter", "<", "T", ">", "(", ")", "{", "@", "Override", "public", "boolean", "accept", "(", "T", "t", ")", "{", "return", "false", "==", "StrUtil", ".", "isBlank", "(", "t", ")", ";", "}", "}", ")", ";", "}" ]
去除{@code null}或者""或者空白字符串 元素 @param collection 集合 @return 处理后的集合 @since 3.2.2
[ "去除", "{", "@code", "null", "}", "或者", "或者空白字符串", "元素" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/collection/CollUtil.java#L1106-L1113
haraldk/TwelveMonkeys
servlet/src/main/java/com/twelvemonkeys/servlet/ServletUtil.java
ServletUtil.getRealURL
public static URL getRealURL(final ServletContext pContext, final String pPath) throws MalformedURLException { """ Returns a {@code URL} containing the real path for a given virtual path, on URL form. Note that this method will return {@code null} for all the same reasons as {@code ServletContext.getRealPath(java.lang.String)} does. @param pContext the servlet context @param pPath the virtual path @return a {@code URL} object containing the path, or {@code null}. @throws MalformedURLException if the path refers to a malformed URL @see ServletContext#getRealPath(java.lang.String) @see ServletContext#getResource(java.lang.String) """ String realPath = pContext.getRealPath(pPath); if (realPath != null) { // NOTE: First convert to URI, as of Java 6 File.toURL is deprecated return new File(realPath).toURI().toURL(); } return null; }
java
public static URL getRealURL(final ServletContext pContext, final String pPath) throws MalformedURLException { String realPath = pContext.getRealPath(pPath); if (realPath != null) { // NOTE: First convert to URI, as of Java 6 File.toURL is deprecated return new File(realPath).toURI().toURL(); } return null; }
[ "public", "static", "URL", "getRealURL", "(", "final", "ServletContext", "pContext", ",", "final", "String", "pPath", ")", "throws", "MalformedURLException", "{", "String", "realPath", "=", "pContext", ".", "getRealPath", "(", "pPath", ")", ";", "if", "(", "realPath", "!=", "null", ")", "{", "// NOTE: First convert to URI, as of Java 6 File.toURL is deprecated\r", "return", "new", "File", "(", "realPath", ")", ".", "toURI", "(", ")", ".", "toURL", "(", ")", ";", "}", "return", "null", ";", "}" ]
Returns a {@code URL} containing the real path for a given virtual path, on URL form. Note that this method will return {@code null} for all the same reasons as {@code ServletContext.getRealPath(java.lang.String)} does. @param pContext the servlet context @param pPath the virtual path @return a {@code URL} object containing the path, or {@code null}. @throws MalformedURLException if the path refers to a malformed URL @see ServletContext#getRealPath(java.lang.String) @see ServletContext#getResource(java.lang.String)
[ "Returns", "a", "{", "@code", "URL", "}", "containing", "the", "real", "path", "for", "a", "given", "virtual", "path", "on", "URL", "form", ".", "Note", "that", "this", "method", "will", "return", "{", "@code", "null", "}", "for", "all", "the", "same", "reasons", "as", "{", "@code", "ServletContext", ".", "getRealPath", "(", "java", ".", "lang", ".", "String", ")", "}", "does", "." ]
train
https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/servlet/src/main/java/com/twelvemonkeys/servlet/ServletUtil.java#L559-L568
awslabs/jsii
packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiEngine.java
JsiiEngine.findCallbackMethod
private Method findCallbackMethod(final Class<?> klass, final String signature) { """ Finds the Java method that implements a callback. @param klass The java class. @param signature Method signature @return a {@link Method}. """ for (Method method : klass.getMethods()) { if (method.toString().equals(signature)) { // found! return method; } } throw new JsiiException("Unable to find callback method with signature: " + signature); }
java
private Method findCallbackMethod(final Class<?> klass, final String signature) { for (Method method : klass.getMethods()) { if (method.toString().equals(signature)) { // found! return method; } } throw new JsiiException("Unable to find callback method with signature: " + signature); }
[ "private", "Method", "findCallbackMethod", "(", "final", "Class", "<", "?", ">", "klass", ",", "final", "String", "signature", ")", "{", "for", "(", "Method", "method", ":", "klass", ".", "getMethods", "(", ")", ")", "{", "if", "(", "method", ".", "toString", "(", ")", ".", "equals", "(", "signature", ")", ")", "{", "// found!", "return", "method", ";", "}", "}", "throw", "new", "JsiiException", "(", "\"Unable to find callback method with signature: \"", "+", "signature", ")", ";", "}" ]
Finds the Java method that implements a callback. @param klass The java class. @param signature Method signature @return a {@link Method}.
[ "Finds", "the", "Java", "method", "that", "implements", "a", "callback", "." ]
train
https://github.com/awslabs/jsii/blob/6bbf743f5f65e98e5199ad31c93961533ffc40e5/packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiEngine.java#L423-L433
jspringbot/jspringbot
src/main/java/org/jspringbot/spring/KeywordUtils.java
KeywordUtils.getKeywordInfo
public static KeywordInfo getKeywordInfo(String keyword, ApplicationContext context, Map<String, String> beanMap) { """ Retrieves the KeywordInfo of the given keyword. @param keyword keyword name @param context Spring application context @param beanMap keyword name to bean name mapping @return KeywordInfo object or null if unavailable """ Object bean = context.getBean(beanMap.get(keyword)); return AnnotationUtils.findAnnotation(bean.getClass(), KeywordInfo.class); }
java
public static KeywordInfo getKeywordInfo(String keyword, ApplicationContext context, Map<String, String> beanMap) { Object bean = context.getBean(beanMap.get(keyword)); return AnnotationUtils.findAnnotation(bean.getClass(), KeywordInfo.class); }
[ "public", "static", "KeywordInfo", "getKeywordInfo", "(", "String", "keyword", ",", "ApplicationContext", "context", ",", "Map", "<", "String", ",", "String", ">", "beanMap", ")", "{", "Object", "bean", "=", "context", ".", "getBean", "(", "beanMap", ".", "get", "(", "keyword", ")", ")", ";", "return", "AnnotationUtils", ".", "findAnnotation", "(", "bean", ".", "getClass", "(", ")", ",", "KeywordInfo", ".", "class", ")", ";", "}" ]
Retrieves the KeywordInfo of the given keyword. @param keyword keyword name @param context Spring application context @param beanMap keyword name to bean name mapping @return KeywordInfo object or null if unavailable
[ "Retrieves", "the", "KeywordInfo", "of", "the", "given", "keyword", "." ]
train
https://github.com/jspringbot/jspringbot/blob/03285a7013492fb793cb0c38a4625a5f5c5750e0/src/main/java/org/jspringbot/spring/KeywordUtils.java#L135-L138
ngageoint/geopackage-java
src/main/java/mil/nga/geopackage/extension/related/RelatedTablesExtension.java
RelatedTablesExtension.hasMapping
public boolean hasMapping(String tableName, long baseId, long relatedId) { """ Determine if the base id and related id mapping exists @param tableName mapping table name @param baseId base id @param relatedId related id @return true if mapping exists @since 3.2.0 """ UserMappingDao userMappingDao = getMappingDao(tableName); return userMappingDao.countByIds(baseId, relatedId) > 0; }
java
public boolean hasMapping(String tableName, long baseId, long relatedId) { UserMappingDao userMappingDao = getMappingDao(tableName); return userMappingDao.countByIds(baseId, relatedId) > 0; }
[ "public", "boolean", "hasMapping", "(", "String", "tableName", ",", "long", "baseId", ",", "long", "relatedId", ")", "{", "UserMappingDao", "userMappingDao", "=", "getMappingDao", "(", "tableName", ")", ";", "return", "userMappingDao", ".", "countByIds", "(", "baseId", ",", "relatedId", ")", ">", "0", ";", "}" ]
Determine if the base id and related id mapping exists @param tableName mapping table name @param baseId base id @param relatedId related id @return true if mapping exists @since 3.2.0
[ "Determine", "if", "the", "base", "id", "and", "related", "id", "mapping", "exists" ]
train
https://github.com/ngageoint/geopackage-java/blob/889bffb5d18330a3f4bd89443acf7959ebe3a376/src/main/java/mil/nga/geopackage/extension/related/RelatedTablesExtension.java#L263-L266
OpenLiberty/open-liberty
dev/com.ibm.ws.security.mp.jwt/src/com/ibm/ws/security/mp/jwt/tai/TAIRequestHelper.java
TAIRequestHelper.shouldDeferToJwtSso
private boolean shouldDeferToJwtSso(HttpServletRequest req, MicroProfileJwtConfig config, MicroProfileJwtConfig jwtssoConfig) { """ if we don't have a valid bearer header, and jwtsso is active, we should defer. """ if ((!isJwtSsoFeatureActive(config)) && (jwtssoConfig == null)) { return false; } String hdrValue = req.getHeader(Authorization_Header); if (tc.isDebugEnabled()) { Tr.debug(tc, "Authorization header=", hdrValue); } boolean haveValidBearerHeader = (hdrValue != null && hdrValue.startsWith("Bearer ")); return !haveValidBearerHeader; }
java
private boolean shouldDeferToJwtSso(HttpServletRequest req, MicroProfileJwtConfig config, MicroProfileJwtConfig jwtssoConfig) { if ((!isJwtSsoFeatureActive(config)) && (jwtssoConfig == null)) { return false; } String hdrValue = req.getHeader(Authorization_Header); if (tc.isDebugEnabled()) { Tr.debug(tc, "Authorization header=", hdrValue); } boolean haveValidBearerHeader = (hdrValue != null && hdrValue.startsWith("Bearer ")); return !haveValidBearerHeader; }
[ "private", "boolean", "shouldDeferToJwtSso", "(", "HttpServletRequest", "req", ",", "MicroProfileJwtConfig", "config", ",", "MicroProfileJwtConfig", "jwtssoConfig", ")", "{", "if", "(", "(", "!", "isJwtSsoFeatureActive", "(", "config", ")", ")", "&&", "(", "jwtssoConfig", "==", "null", ")", ")", "{", "return", "false", ";", "}", "String", "hdrValue", "=", "req", ".", "getHeader", "(", "Authorization_Header", ")", ";", "if", "(", "tc", ".", "isDebugEnabled", "(", ")", ")", "{", "Tr", ".", "debug", "(", "tc", ",", "\"Authorization header=\"", ",", "hdrValue", ")", ";", "}", "boolean", "haveValidBearerHeader", "=", "(", "hdrValue", "!=", "null", "&&", "hdrValue", ".", "startsWith", "(", "\"Bearer \"", ")", ")", ";", "return", "!", "haveValidBearerHeader", ";", "}" ]
if we don't have a valid bearer header, and jwtsso is active, we should defer.
[ "if", "we", "don", "t", "have", "a", "valid", "bearer", "header", "and", "jwtsso", "is", "active", "we", "should", "defer", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.mp.jwt/src/com/ibm/ws/security/mp/jwt/tai/TAIRequestHelper.java#L106-L118
foundation-runtime/service-directory
2.0/sd-core/src/main/java/com/cisco/oss/foundation/directory/ServiceDirectoryThread.java
ServiceDirectoryThread.getThread
public static Thread getThread(Runnable runnable, String name) { """ Get a Thread. @param runnable the runnable task. @param name the thread name. @return the Thread. """ return doThread(runnable, name, DefaultThreadDeamon); }
java
public static Thread getThread(Runnable runnable, String name){ return doThread(runnable, name, DefaultThreadDeamon); }
[ "public", "static", "Thread", "getThread", "(", "Runnable", "runnable", ",", "String", "name", ")", "{", "return", "doThread", "(", "runnable", ",", "name", ",", "DefaultThreadDeamon", ")", ";", "}" ]
Get a Thread. @param runnable the runnable task. @param name the thread name. @return the Thread.
[ "Get", "a", "Thread", "." ]
train
https://github.com/foundation-runtime/service-directory/blob/a7bdefe173dc99e75eff4a24e07e6407e62f2ed4/2.0/sd-core/src/main/java/com/cisco/oss/foundation/directory/ServiceDirectoryThread.java#L64-L66
Impetus/Kundera
src/kundera-couchbase/src/main/java/com/impetus/client/couchbase/query/CouchbaseQuery.java
CouchbaseQuery.addWhereCondition
public Statement addWhereCondition(AsPath asPath, String identifier, String colName, String val, String tableName) { """ Adds the where condition. @param asPath the as path @param identifier the identifier @param colName the col name @param val the val @param tableName the table name @return the statement """ com.couchbase.client.java.query.dsl.Expression exp; switch (identifier) { case "<": exp = x(colName).lt(x(val)); break; case "<=": exp = x(colName).lte(x(val)); break; case ">": exp = x(colName).gt(x(val)); break; case ">=": exp = x(colName).gte(x(val)); break; case "=": exp = x(colName).eq(x(val)); break; default: LOGGER.error("Operator " + identifier + " is not supported in the JPA query for Couchbase."); throw new KunderaException("Operator " + identifier + " is not supported in the JPA query for Couchbase."); } return asPath.where(exp.and(x(CouchbaseConstants.KUNDERA_ENTITY).eq(x("'" + tableName) + "'"))); }
java
public Statement addWhereCondition(AsPath asPath, String identifier, String colName, String val, String tableName) { com.couchbase.client.java.query.dsl.Expression exp; switch (identifier) { case "<": exp = x(colName).lt(x(val)); break; case "<=": exp = x(colName).lte(x(val)); break; case ">": exp = x(colName).gt(x(val)); break; case ">=": exp = x(colName).gte(x(val)); break; case "=": exp = x(colName).eq(x(val)); break; default: LOGGER.error("Operator " + identifier + " is not supported in the JPA query for Couchbase."); throw new KunderaException("Operator " + identifier + " is not supported in the JPA query for Couchbase."); } return asPath.where(exp.and(x(CouchbaseConstants.KUNDERA_ENTITY).eq(x("'" + tableName) + "'"))); }
[ "public", "Statement", "addWhereCondition", "(", "AsPath", "asPath", ",", "String", "identifier", ",", "String", "colName", ",", "String", "val", ",", "String", "tableName", ")", "{", "com", ".", "couchbase", ".", "client", ".", "java", ".", "query", ".", "dsl", ".", "Expression", "exp", ";", "switch", "(", "identifier", ")", "{", "case", "\"<\"", ":", "exp", "=", "x", "(", "colName", ")", ".", "lt", "(", "x", "(", "val", ")", ")", ";", "break", ";", "case", "\"<=\"", ":", "exp", "=", "x", "(", "colName", ")", ".", "lte", "(", "x", "(", "val", ")", ")", ";", "break", ";", "case", "\">\"", ":", "exp", "=", "x", "(", "colName", ")", ".", "gt", "(", "x", "(", "val", ")", ")", ";", "break", ";", "case", "\">=\"", ":", "exp", "=", "x", "(", "colName", ")", ".", "gte", "(", "x", "(", "val", ")", ")", ";", "break", ";", "case", "\"=\"", ":", "exp", "=", "x", "(", "colName", ")", ".", "eq", "(", "x", "(", "val", ")", ")", ";", "break", ";", "default", ":", "LOGGER", ".", "error", "(", "\"Operator \"", "+", "identifier", "+", "\" is not supported in the JPA query for Couchbase.\"", ")", ";", "throw", "new", "KunderaException", "(", "\"Operator \"", "+", "identifier", "+", "\" is not supported in the JPA query for Couchbase.\"", ")", ";", "}", "return", "asPath", ".", "where", "(", "exp", ".", "and", "(", "x", "(", "CouchbaseConstants", ".", "KUNDERA_ENTITY", ")", ".", "eq", "(", "x", "(", "\"'\"", "+", "tableName", ")", "+", "\"'\"", ")", ")", ")", ";", "}" ]
Adds the where condition. @param asPath the as path @param identifier the identifier @param colName the col name @param val the val @param tableName the table name @return the statement
[ "Adds", "the", "where", "condition", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-couchbase/src/main/java/com/impetus/client/couchbase/query/CouchbaseQuery.java#L157-L184
b3dgs/lionengine
lionengine-core-awt/src/main/java/com/b3dgs/lionengine/awt/MouseClickAwt.java
MouseClickAwt.addActionReleased
void addActionReleased(int click, EventAction action) { """ Add a released action. @param click The action click. @param action The associated action. """ final Integer key = Integer.valueOf(click); final List<EventAction> list; if (actionsReleased.get(key) == null) { list = new ArrayList<>(); actionsReleased.put(key, list); } else { list = actionsReleased.get(key); } list.add(action); }
java
void addActionReleased(int click, EventAction action) { final Integer key = Integer.valueOf(click); final List<EventAction> list; if (actionsReleased.get(key) == null) { list = new ArrayList<>(); actionsReleased.put(key, list); } else { list = actionsReleased.get(key); } list.add(action); }
[ "void", "addActionReleased", "(", "int", "click", ",", "EventAction", "action", ")", "{", "final", "Integer", "key", "=", "Integer", ".", "valueOf", "(", "click", ")", ";", "final", "List", "<", "EventAction", ">", "list", ";", "if", "(", "actionsReleased", ".", "get", "(", "key", ")", "==", "null", ")", "{", "list", "=", "new", "ArrayList", "<>", "(", ")", ";", "actionsReleased", ".", "put", "(", "key", ",", "list", ")", ";", "}", "else", "{", "list", "=", "actionsReleased", ".", "get", "(", "key", ")", ";", "}", "list", ".", "add", "(", "action", ")", ";", "}" ]
Add a released action. @param click The action click. @param action The associated action.
[ "Add", "a", "released", "action", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-core-awt/src/main/java/com/b3dgs/lionengine/awt/MouseClickAwt.java#L139-L153
Azure/azure-sdk-for-java
labservices/resource-manager/v2018_10_15/src/main/java/com/microsoft/azure/management/labservices/v2018_10_15/implementation/LabAccountsInner.java
LabAccountsInner.createLabAsync
public Observable<Void> createLabAsync(String resourceGroupName, String labAccountName, CreateLabProperties createLabProperties) { """ Create a lab in a lab account. @param resourceGroupName The name of the resource group. @param labAccountName The name of the lab Account. @param createLabProperties Properties for creating a managed lab and a default environment setting @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceResponse} object if successful. """ return createLabWithServiceResponseAsync(resourceGroupName, labAccountName, createLabProperties).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); }
java
public Observable<Void> createLabAsync(String resourceGroupName, String labAccountName, CreateLabProperties createLabProperties) { return createLabWithServiceResponseAsync(resourceGroupName, labAccountName, createLabProperties).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Void", ">", "createLabAsync", "(", "String", "resourceGroupName", ",", "String", "labAccountName", ",", "CreateLabProperties", "createLabProperties", ")", "{", "return", "createLabWithServiceResponseAsync", "(", "resourceGroupName", ",", "labAccountName", ",", "createLabProperties", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "Void", ">", ",", "Void", ">", "(", ")", "{", "@", "Override", "public", "Void", "call", "(", "ServiceResponse", "<", "Void", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Create a lab in a lab account. @param resourceGroupName The name of the resource group. @param labAccountName The name of the lab Account. @param createLabProperties Properties for creating a managed lab and a default environment setting @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceResponse} object if successful.
[ "Create", "a", "lab", "in", "a", "lab", "account", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/labservices/resource-manager/v2018_10_15/src/main/java/com/microsoft/azure/management/labservices/v2018_10_15/implementation/LabAccountsInner.java#L1145-L1152
Azure/azure-sdk-for-java
common/azure-common-mgmt/src/main/java/com/azure/common/mgmt/AzureAsyncOperationPollStrategy.java
AzureAsyncOperationPollStrategy.tryToCreate
static PollStrategy tryToCreate(RestProxy restProxy, SwaggerMethodParser methodParser, HttpRequest originalHttpRequest, HttpResponse httpResponse, long delayInMilliseconds) { """ Try to create a new AzureAsyncOperationPollStrategy object that will poll the provided operation resource URL. If the provided HttpResponse doesn't have an Azure-AsyncOperation header or if the header is empty, then null will be returned. @param restProxy The proxy object that is attempting to create a PollStrategy. @param methodParser The method parser that describes the service interface method that initiated the long running operation. @param originalHttpRequest The original HTTP request that initiated the long running operation. @param httpResponse The HTTP response that the required header values for this pollStrategy will be read from. @param delayInMilliseconds The delay (in milliseconds) that the resulting pollStrategy will use when polling. """ String urlHeader = getHeader(httpResponse); URL azureAsyncOperationUrl = null; if (urlHeader != null) { try { azureAsyncOperationUrl = new URL(urlHeader); } catch (MalformedURLException ignored) { } } urlHeader = httpResponse.headerValue("Location"); URL locationUrl = null; if (urlHeader != null) { try { locationUrl = new URL(urlHeader); } catch (MalformedURLException ignored) { } } return azureAsyncOperationUrl != null ? new AzureAsyncOperationPollStrategy( new AzureAsyncOperationPollStrategyData(restProxy, methodParser, azureAsyncOperationUrl, originalHttpRequest.url(), locationUrl, originalHttpRequest.httpMethod(), delayInMilliseconds)) : null; }
java
static PollStrategy tryToCreate(RestProxy restProxy, SwaggerMethodParser methodParser, HttpRequest originalHttpRequest, HttpResponse httpResponse, long delayInMilliseconds) { String urlHeader = getHeader(httpResponse); URL azureAsyncOperationUrl = null; if (urlHeader != null) { try { azureAsyncOperationUrl = new URL(urlHeader); } catch (MalformedURLException ignored) { } } urlHeader = httpResponse.headerValue("Location"); URL locationUrl = null; if (urlHeader != null) { try { locationUrl = new URL(urlHeader); } catch (MalformedURLException ignored) { } } return azureAsyncOperationUrl != null ? new AzureAsyncOperationPollStrategy( new AzureAsyncOperationPollStrategyData(restProxy, methodParser, azureAsyncOperationUrl, originalHttpRequest.url(), locationUrl, originalHttpRequest.httpMethod(), delayInMilliseconds)) : null; }
[ "static", "PollStrategy", "tryToCreate", "(", "RestProxy", "restProxy", ",", "SwaggerMethodParser", "methodParser", ",", "HttpRequest", "originalHttpRequest", ",", "HttpResponse", "httpResponse", ",", "long", "delayInMilliseconds", ")", "{", "String", "urlHeader", "=", "getHeader", "(", "httpResponse", ")", ";", "URL", "azureAsyncOperationUrl", "=", "null", ";", "if", "(", "urlHeader", "!=", "null", ")", "{", "try", "{", "azureAsyncOperationUrl", "=", "new", "URL", "(", "urlHeader", ")", ";", "}", "catch", "(", "MalformedURLException", "ignored", ")", "{", "}", "}", "urlHeader", "=", "httpResponse", ".", "headerValue", "(", "\"Location\"", ")", ";", "URL", "locationUrl", "=", "null", ";", "if", "(", "urlHeader", "!=", "null", ")", "{", "try", "{", "locationUrl", "=", "new", "URL", "(", "urlHeader", ")", ";", "}", "catch", "(", "MalformedURLException", "ignored", ")", "{", "}", "}", "return", "azureAsyncOperationUrl", "!=", "null", "?", "new", "AzureAsyncOperationPollStrategy", "(", "new", "AzureAsyncOperationPollStrategyData", "(", "restProxy", ",", "methodParser", ",", "azureAsyncOperationUrl", ",", "originalHttpRequest", ".", "url", "(", ")", ",", "locationUrl", ",", "originalHttpRequest", ".", "httpMethod", "(", ")", ",", "delayInMilliseconds", ")", ")", ":", "null", ";", "}" ]
Try to create a new AzureAsyncOperationPollStrategy object that will poll the provided operation resource URL. If the provided HttpResponse doesn't have an Azure-AsyncOperation header or if the header is empty, then null will be returned. @param restProxy The proxy object that is attempting to create a PollStrategy. @param methodParser The method parser that describes the service interface method that initiated the long running operation. @param originalHttpRequest The original HTTP request that initiated the long running operation. @param httpResponse The HTTP response that the required header values for this pollStrategy will be read from. @param delayInMilliseconds The delay (in milliseconds) that the resulting pollStrategy will use when polling.
[ "Try", "to", "create", "a", "new", "AzureAsyncOperationPollStrategy", "object", "that", "will", "poll", "the", "provided", "operation", "resource", "URL", ".", "If", "the", "provided", "HttpResponse", "doesn", "t", "have", "an", "Azure", "-", "AsyncOperation", "header", "or", "if", "the", "header", "is", "empty", "then", "null", "will", "be", "returned", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/common/azure-common-mgmt/src/main/java/com/azure/common/mgmt/AzureAsyncOperationPollStrategy.java#L172-L195
playn/playn
scene/src/playn/scene/LayerUtil.java
LayerUtil.layerToScreen
public static Point layerToScreen(Layer layer, XY point, Point into) { """ Converts the supplied point from coordinates relative to the specified layer to screen coordinates. The results are stored into {@code into}, which is returned for convenience. """ return layerToParent(layer, null, point, into); }
java
public static Point layerToScreen(Layer layer, XY point, Point into) { return layerToParent(layer, null, point, into); }
[ "public", "static", "Point", "layerToScreen", "(", "Layer", "layer", ",", "XY", "point", ",", "Point", "into", ")", "{", "return", "layerToParent", "(", "layer", ",", "null", ",", "point", ",", "into", ")", ";", "}" ]
Converts the supplied point from coordinates relative to the specified layer to screen coordinates. The results are stored into {@code into}, which is returned for convenience.
[ "Converts", "the", "supplied", "point", "from", "coordinates", "relative", "to", "the", "specified", "layer", "to", "screen", "coordinates", ".", "The", "results", "are", "stored", "into", "{" ]
train
https://github.com/playn/playn/blob/7e7a9d048ba6afe550dc0cdeaca3e1d5b0d01c66/scene/src/playn/scene/LayerUtil.java#L36-L38
sd4324530/fastweixin
src/main/java/com/github/sd4324530/fastweixin/api/BaseAPI.java
BaseAPI.executePost
protected BaseResponse executePost(String url, String json) { """ 通用post请求 @param url 地址,其中token用#代替 @param json 参数,json格式 @return 请求结果 """ return executePost(url, json, null); }
java
protected BaseResponse executePost(String url, String json) { return executePost(url, json, null); }
[ "protected", "BaseResponse", "executePost", "(", "String", "url", ",", "String", "json", ")", "{", "return", "executePost", "(", "url", ",", "json", ",", "null", ")", ";", "}" ]
通用post请求 @param url 地址,其中token用#代替 @param json 参数,json格式 @return 请求结果
[ "通用post请求" ]
train
https://github.com/sd4324530/fastweixin/blob/6bc0a7abfa23aad0dbad4c3123a47a7fb53f3447/src/main/java/com/github/sd4324530/fastweixin/api/BaseAPI.java#L43-L45
kumuluz/kumuluzee
tools/loader/src/main/java/com/kumuluz/ee/loader/EeClassLoader.java
EeClassLoader.findJarNativeEntry
private JarEntryInfo findJarNativeEntry(String libraryName) { """ Finds native library entry. @param libraryName Library name. For example for the library name "Native" - Windows returns entry "Native.dll" - Linux returns entry "libNative.so" - Mac returns entry "libNative.jnilib" or "libNative.dylib" (depending on Apple or Oracle JDK and/or JDK version) @return Native library entry. """ String name = System.mapLibraryName(libraryName); for (JarFileInfo jarFileInfo : jarFiles) { JarFile jarFile = jarFileInfo.getJarFile(); Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry jarEntry = entries.nextElement(); if (jarEntry.isDirectory()) { continue; } // Example: name is "Native.dll" String jarEntryName = jarEntry.getName(); // "Native.dll" or "abc/xyz/Native.dll" // name "Native.dll" could be found, for example // - in the path: abc/Native.dll/xyz/my.dll <-- do not load this one! // - in the partial name: abc/aNative.dll <-- do not load this one! String[] token = jarEntryName.split("/"); // the last token is library name if (token.length > 0 && token[token.length - 1].equals(name)) { debug(String.format("Loading native library '%s' found as '%s' in JAR %s", libraryName, jarEntryName, jarFileInfo.getSimpleName())); return new JarEntryInfo(jarFileInfo, jarEntry); } } } return null; }
java
private JarEntryInfo findJarNativeEntry(String libraryName) { String name = System.mapLibraryName(libraryName); for (JarFileInfo jarFileInfo : jarFiles) { JarFile jarFile = jarFileInfo.getJarFile(); Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry jarEntry = entries.nextElement(); if (jarEntry.isDirectory()) { continue; } // Example: name is "Native.dll" String jarEntryName = jarEntry.getName(); // "Native.dll" or "abc/xyz/Native.dll" // name "Native.dll" could be found, for example // - in the path: abc/Native.dll/xyz/my.dll <-- do not load this one! // - in the partial name: abc/aNative.dll <-- do not load this one! String[] token = jarEntryName.split("/"); // the last token is library name if (token.length > 0 && token[token.length - 1].equals(name)) { debug(String.format("Loading native library '%s' found as '%s' in JAR %s", libraryName, jarEntryName, jarFileInfo.getSimpleName())); return new JarEntryInfo(jarFileInfo, jarEntry); } } } return null; }
[ "private", "JarEntryInfo", "findJarNativeEntry", "(", "String", "libraryName", ")", "{", "String", "name", "=", "System", ".", "mapLibraryName", "(", "libraryName", ")", ";", "for", "(", "JarFileInfo", "jarFileInfo", ":", "jarFiles", ")", "{", "JarFile", "jarFile", "=", "jarFileInfo", ".", "getJarFile", "(", ")", ";", "Enumeration", "<", "JarEntry", ">", "entries", "=", "jarFile", ".", "entries", "(", ")", ";", "while", "(", "entries", ".", "hasMoreElements", "(", ")", ")", "{", "JarEntry", "jarEntry", "=", "entries", ".", "nextElement", "(", ")", ";", "if", "(", "jarEntry", ".", "isDirectory", "(", ")", ")", "{", "continue", ";", "}", "// Example: name is \"Native.dll\"", "String", "jarEntryName", "=", "jarEntry", ".", "getName", "(", ")", ";", "// \"Native.dll\" or \"abc/xyz/Native.dll\"", "// name \"Native.dll\" could be found, for example", "// - in the path: abc/Native.dll/xyz/my.dll <-- do not load this one!", "// - in the partial name: abc/aNative.dll <-- do not load this one!", "String", "[", "]", "token", "=", "jarEntryName", ".", "split", "(", "\"/\"", ")", ";", "// the last token is library name", "if", "(", "token", ".", "length", ">", "0", "&&", "token", "[", "token", ".", "length", "-", "1", "]", ".", "equals", "(", "name", ")", ")", "{", "debug", "(", "String", ".", "format", "(", "\"Loading native library '%s' found as '%s' in JAR %s\"", ",", "libraryName", ",", "jarEntryName", ",", "jarFileInfo", ".", "getSimpleName", "(", ")", ")", ")", ";", "return", "new", "JarEntryInfo", "(", "jarFileInfo", ",", "jarEntry", ")", ";", "}", "}", "}", "return", "null", ";", "}" ]
Finds native library entry. @param libraryName Library name. For example for the library name "Native" - Windows returns entry "Native.dll" - Linux returns entry "libNative.so" - Mac returns entry "libNative.jnilib" or "libNative.dylib" (depending on Apple or Oracle JDK and/or JDK version) @return Native library entry.
[ "Finds", "native", "library", "entry", "." ]
train
https://github.com/kumuluz/kumuluzee/blob/86fbce2acc04264f20d548173d5d9f28d79cb415/tools/loader/src/main/java/com/kumuluz/ee/loader/EeClassLoader.java#L353-L379
alipay/sofa-rpc
core/api/src/main/java/com/alipay/sofa/rpc/tracer/Tracers.java
Tracers.serverSend
public static void serverSend(SofaRequest request, SofaResponse response, Throwable throwable) { """ 3. 服务端返回请求或者异常 @param request 调用请求 @param response 调用响应 @param throwable 异常 """ if (openTrace) { try { tracer.serverSend(request, response, throwable); } catch (Exception e) { if (LOGGER.isWarnEnabled()) { LOGGER.warn(e.getMessage(), e); } } } }
java
public static void serverSend(SofaRequest request, SofaResponse response, Throwable throwable) { if (openTrace) { try { tracer.serverSend(request, response, throwable); } catch (Exception e) { if (LOGGER.isWarnEnabled()) { LOGGER.warn(e.getMessage(), e); } } } }
[ "public", "static", "void", "serverSend", "(", "SofaRequest", "request", ",", "SofaResponse", "response", ",", "Throwable", "throwable", ")", "{", "if", "(", "openTrace", ")", "{", "try", "{", "tracer", ".", "serverSend", "(", "request", ",", "response", ",", "throwable", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "if", "(", "LOGGER", ".", "isWarnEnabled", "(", ")", ")", "{", "LOGGER", ".", "warn", "(", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "}", "}", "}", "}" ]
3. 服务端返回请求或者异常 @param request 调用请求 @param response 调用响应 @param throwable 异常
[ "3", ".", "服务端返回请求或者异常" ]
train
https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/core/api/src/main/java/com/alipay/sofa/rpc/tracer/Tracers.java#L152-L162
mebigfatguy/fb-contrib
src/main/java/com/mebigfatguy/fbcontrib/utils/SignatureUtils.java
SignatureUtils.isWonkyEclipseSignature
private static boolean isWonkyEclipseSignature(String sig, int startIndex) { """ Eclipse makes weird class signatures. @param sig the signature in type table @param startIndex the index into the signature where the wonkyness begins @return if this signature has eclipse meta chars """ return (sig.length() > startIndex) && (ECLIPSE_WEIRD_SIG_CHARS.indexOf(sig.charAt(startIndex)) >= 0); }
java
private static boolean isWonkyEclipseSignature(String sig, int startIndex) { return (sig.length() > startIndex) && (ECLIPSE_WEIRD_SIG_CHARS.indexOf(sig.charAt(startIndex)) >= 0); }
[ "private", "static", "boolean", "isWonkyEclipseSignature", "(", "String", "sig", ",", "int", "startIndex", ")", "{", "return", "(", "sig", ".", "length", "(", ")", ">", "startIndex", ")", "&&", "(", "ECLIPSE_WEIRD_SIG_CHARS", ".", "indexOf", "(", "sig", ".", "charAt", "(", "startIndex", ")", ")", ">=", "0", ")", ";", "}" ]
Eclipse makes weird class signatures. @param sig the signature in type table @param startIndex the index into the signature where the wonkyness begins @return if this signature has eclipse meta chars
[ "Eclipse", "makes", "weird", "class", "signatures", "." ]
train
https://github.com/mebigfatguy/fb-contrib/blob/3b5203196f627b399fbcea3c2ab2b1f4e56cc7b8/src/main/java/com/mebigfatguy/fbcontrib/utils/SignatureUtils.java#L455-L457
fuinorg/event-store-commons
jpa/src/main/java/org/fuin/esc/jpa/AbstractJpaEventStore.java
AbstractJpaEventStore.setNativeSqlParameters
private final void setNativeSqlParameters(final Query query, final List<NativeSqlCondition> conditions) { """ Sets parameters in a query. @param query Query to set parameters for. @param streamId Unique stream identifier that has the parameter values. @param additionalConditions Parameters to add in addition to the ones from the stream identifier. """ for (final NativeSqlCondition condition : conditions) { query.setParameter(condition.getColumn(), condition.getValue()); } }
java
private final void setNativeSqlParameters(final Query query, final List<NativeSqlCondition> conditions) { for (final NativeSqlCondition condition : conditions) { query.setParameter(condition.getColumn(), condition.getValue()); } }
[ "private", "final", "void", "setNativeSqlParameters", "(", "final", "Query", "query", ",", "final", "List", "<", "NativeSqlCondition", ">", "conditions", ")", "{", "for", "(", "final", "NativeSqlCondition", "condition", ":", "conditions", ")", "{", "query", ".", "setParameter", "(", "condition", ".", "getColumn", "(", ")", ",", "condition", ".", "getValue", "(", ")", ")", ";", "}", "}" ]
Sets parameters in a query. @param query Query to set parameters for. @param streamId Unique stream identifier that has the parameter values. @param additionalConditions Parameters to add in addition to the ones from the stream identifier.
[ "Sets", "parameters", "in", "a", "query", "." ]
train
https://github.com/fuinorg/event-store-commons/blob/ea175582d8cda2b5a6d2fe52bbb2f1c183eee77c/jpa/src/main/java/org/fuin/esc/jpa/AbstractJpaEventStore.java#L473-L477
aws/aws-sdk-java
aws-java-sdk-medialive/src/main/java/com/amazonaws/services/medialive/model/DescribeReservationResult.java
DescribeReservationResult.withTags
public DescribeReservationResult withTags(java.util.Map<String, String> tags) { """ A collection of key-value pairs @param tags A collection of key-value pairs @return Returns a reference to this object so that method calls can be chained together. """ setTags(tags); return this; }
java
public DescribeReservationResult withTags(java.util.Map<String, String> tags) { setTags(tags); return this; }
[ "public", "DescribeReservationResult", "withTags", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "tags", ")", "{", "setTags", "(", "tags", ")", ";", "return", "this", ";", "}" ]
A collection of key-value pairs @param tags A collection of key-value pairs @return Returns a reference to this object so that method calls can be chained together.
[ "A", "collection", "of", "key", "-", "value", "pairs" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-medialive/src/main/java/com/amazonaws/services/medialive/model/DescribeReservationResult.java#L688-L691
google/closure-templates
java/src/com/google/template/soy/SoyFileSetParser.java
SoyFileSetParser.parseSoyFileHelper
private SoyFileNode parseSoyFileHelper(SoyFileSupplier soyFileSupplier, IdGenerator nodeIdGen) throws IOException { """ Private helper for {@code parseWithVersions()} to parse one Soy file. @param soyFileSupplier Supplier of the Soy file content and path. @param nodeIdGen The generator of node ids. @return The resulting parse tree for one Soy file and the version from which it was parsed. """ // See copious comments above on this test if (soyFileSupplier instanceof HasAstOrErrors) { return ((HasAstOrErrors) soyFileSupplier).getAst(nodeIdGen, errorReporter()); } else { try (Reader soyFileReader = soyFileSupplier.open()) { String filePath = soyFileSupplier.getFilePath(); int lastBangIndex = filePath.lastIndexOf('!'); if (lastBangIndex != -1) { // This is a resource in a JAR file. Only keep everything after the bang. filePath = filePath.substring(lastBangIndex + 1); } // Think carefully before adding new parameters to the parser. // Currently the only parameters are the id generator, the file, and the errorReporter. // This // ensures that the file be cached without worrying about other compiler inputs. return new SoyFileParser(nodeIdGen, soyFileReader, filePath, errorReporter()) .parseSoyFile(); } } }
java
private SoyFileNode parseSoyFileHelper(SoyFileSupplier soyFileSupplier, IdGenerator nodeIdGen) throws IOException { // See copious comments above on this test if (soyFileSupplier instanceof HasAstOrErrors) { return ((HasAstOrErrors) soyFileSupplier).getAst(nodeIdGen, errorReporter()); } else { try (Reader soyFileReader = soyFileSupplier.open()) { String filePath = soyFileSupplier.getFilePath(); int lastBangIndex = filePath.lastIndexOf('!'); if (lastBangIndex != -1) { // This is a resource in a JAR file. Only keep everything after the bang. filePath = filePath.substring(lastBangIndex + 1); } // Think carefully before adding new parameters to the parser. // Currently the only parameters are the id generator, the file, and the errorReporter. // This // ensures that the file be cached without worrying about other compiler inputs. return new SoyFileParser(nodeIdGen, soyFileReader, filePath, errorReporter()) .parseSoyFile(); } } }
[ "private", "SoyFileNode", "parseSoyFileHelper", "(", "SoyFileSupplier", "soyFileSupplier", ",", "IdGenerator", "nodeIdGen", ")", "throws", "IOException", "{", "// See copious comments above on this test", "if", "(", "soyFileSupplier", "instanceof", "HasAstOrErrors", ")", "{", "return", "(", "(", "HasAstOrErrors", ")", "soyFileSupplier", ")", ".", "getAst", "(", "nodeIdGen", ",", "errorReporter", "(", ")", ")", ";", "}", "else", "{", "try", "(", "Reader", "soyFileReader", "=", "soyFileSupplier", ".", "open", "(", ")", ")", "{", "String", "filePath", "=", "soyFileSupplier", ".", "getFilePath", "(", ")", ";", "int", "lastBangIndex", "=", "filePath", ".", "lastIndexOf", "(", "'", "'", ")", ";", "if", "(", "lastBangIndex", "!=", "-", "1", ")", "{", "// This is a resource in a JAR file. Only keep everything after the bang.", "filePath", "=", "filePath", ".", "substring", "(", "lastBangIndex", "+", "1", ")", ";", "}", "// Think carefully before adding new parameters to the parser.", "// Currently the only parameters are the id generator, the file, and the errorReporter.", "// This", "// ensures that the file be cached without worrying about other compiler inputs.", "return", "new", "SoyFileParser", "(", "nodeIdGen", ",", "soyFileReader", ",", "filePath", ",", "errorReporter", "(", ")", ")", ".", "parseSoyFile", "(", ")", ";", "}", "}", "}" ]
Private helper for {@code parseWithVersions()} to parse one Soy file. @param soyFileSupplier Supplier of the Soy file content and path. @param nodeIdGen The generator of node ids. @return The resulting parse tree for one Soy file and the version from which it was parsed.
[ "Private", "helper", "for", "{", "@code", "parseWithVersions", "()", "}", "to", "parse", "one", "Soy", "file", "." ]
train
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/SoyFileSetParser.java#L229-L250
realtime-framework/RealtimeMessaging-Android
library/src/main/java/ibt/ortc/api/Ortc.java
Ortc.saveAuthentication
public static void saveAuthentication(String url, boolean isCluster, final String authenticationToken, final boolean authenticationTokenIsPrivate, final String applicationKey, final int timeToLive, final String privateKey, final HashMap<String, LinkedList<ChannelPermissions>> permissions, final OnRestWebserviceResponse onCompleted) throws IOException, InvalidBalancerServerException, OrtcAuthenticationNotAuthorizedException { """ Saves the authentication token channels permissions in the ORTC server. <pre> HashMap&lt;String, LinkedList&lt;ChannelPermissions&gt;&gt; permissions = new HashMap&lt;String, LinkedList&lt;ChannelPermissions&gt;&gt;(); LinkedList&lt;ChannelPermissions&gt; channelPermissions = new LinkedList&lt;ChannelPermissions&gt;(); channelPermissions.add(ChannelPermissions.Write); channelPermissions.add(ChannelPermissions.Presence); permissions.put(&quot;channel&quot;, channelPermissions); if (!Ortc.saveAuthentication(&quot;http://ortc-developers.realtime.co/server/2.1/&quot;, true, &quot;SessionId&quot;, false, &quot;APPKEY&quot;, 1800, &quot;PVTKEY&quot;, permissions)) { throw new Exception(&quot;Was not possible to authenticate&quot;); } </pre> @param url Ortc Server Url @param isCluster Indicates whether the ORTC server is in a cluster. @param authenticationToken Authentication Token which is generated by the application server, for instance a unique session ID. @param authenticationTokenIsPrivate Indicates whether the authentication token is private (true) or not (false) @param applicationKey Application Key that was provided to you together with the ORTC service purchasing. @param timeToLive The authentication token time to live, in other words, the allowed activity time (in seconds). @param privateKey The private key provided to you together with the ORTC service purchasing. @param permissions HashMap&lt;String,LinkedList&lt;String,ChannelPermissions&gt; &gt; permissions The channels and their permissions (w: write/read or r: read or p: presence, case sensitive). @param onCompleted The callback that is executed after the save authentication is completed @throws ibt.ortc.api.OrtcAuthenticationNotAuthorizedException @throws InvalidBalancerServerException """ String connectionUrl = url; if (isCluster) { Balancer.getServerFromBalancerAsync(url, applicationKey, new OnRestWebserviceResponse() { @Override public void run(Exception error, String response) { if(error != null){ onCompleted.run(error, null); }else{ saveAuthenticationAsync(response, authenticationToken, authenticationTokenIsPrivate, applicationKey, timeToLive, privateKey, permissions, onCompleted); } } }); }else{ saveAuthenticationAsync(connectionUrl, authenticationToken, authenticationTokenIsPrivate, applicationKey, timeToLive, privateKey, permissions, onCompleted); } }
java
public static void saveAuthentication(String url, boolean isCluster, final String authenticationToken, final boolean authenticationTokenIsPrivate, final String applicationKey, final int timeToLive, final String privateKey, final HashMap<String, LinkedList<ChannelPermissions>> permissions, final OnRestWebserviceResponse onCompleted) throws IOException, InvalidBalancerServerException, OrtcAuthenticationNotAuthorizedException { String connectionUrl = url; if (isCluster) { Balancer.getServerFromBalancerAsync(url, applicationKey, new OnRestWebserviceResponse() { @Override public void run(Exception error, String response) { if(error != null){ onCompleted.run(error, null); }else{ saveAuthenticationAsync(response, authenticationToken, authenticationTokenIsPrivate, applicationKey, timeToLive, privateKey, permissions, onCompleted); } } }); }else{ saveAuthenticationAsync(connectionUrl, authenticationToken, authenticationTokenIsPrivate, applicationKey, timeToLive, privateKey, permissions, onCompleted); } }
[ "public", "static", "void", "saveAuthentication", "(", "String", "url", ",", "boolean", "isCluster", ",", "final", "String", "authenticationToken", ",", "final", "boolean", "authenticationTokenIsPrivate", ",", "final", "String", "applicationKey", ",", "final", "int", "timeToLive", ",", "final", "String", "privateKey", ",", "final", "HashMap", "<", "String", ",", "LinkedList", "<", "ChannelPermissions", ">", ">", "permissions", ",", "final", "OnRestWebserviceResponse", "onCompleted", ")", "throws", "IOException", ",", "InvalidBalancerServerException", ",", "OrtcAuthenticationNotAuthorizedException", "{", "String", "connectionUrl", "=", "url", ";", "if", "(", "isCluster", ")", "{", "Balancer", ".", "getServerFromBalancerAsync", "(", "url", ",", "applicationKey", ",", "new", "OnRestWebserviceResponse", "(", ")", "{", "@", "Override", "public", "void", "run", "(", "Exception", "error", ",", "String", "response", ")", "{", "if", "(", "error", "!=", "null", ")", "{", "onCompleted", ".", "run", "(", "error", ",", "null", ")", ";", "}", "else", "{", "saveAuthenticationAsync", "(", "response", ",", "authenticationToken", ",", "authenticationTokenIsPrivate", ",", "applicationKey", ",", "timeToLive", ",", "privateKey", ",", "permissions", ",", "onCompleted", ")", ";", "}", "}", "}", ")", ";", "}", "else", "{", "saveAuthenticationAsync", "(", "connectionUrl", ",", "authenticationToken", ",", "authenticationTokenIsPrivate", ",", "applicationKey", ",", "timeToLive", ",", "privateKey", ",", "permissions", ",", "onCompleted", ")", ";", "}", "}" ]
Saves the authentication token channels permissions in the ORTC server. <pre> HashMap&lt;String, LinkedList&lt;ChannelPermissions&gt;&gt; permissions = new HashMap&lt;String, LinkedList&lt;ChannelPermissions&gt;&gt;(); LinkedList&lt;ChannelPermissions&gt; channelPermissions = new LinkedList&lt;ChannelPermissions&gt;(); channelPermissions.add(ChannelPermissions.Write); channelPermissions.add(ChannelPermissions.Presence); permissions.put(&quot;channel&quot;, channelPermissions); if (!Ortc.saveAuthentication(&quot;http://ortc-developers.realtime.co/server/2.1/&quot;, true, &quot;SessionId&quot;, false, &quot;APPKEY&quot;, 1800, &quot;PVTKEY&quot;, permissions)) { throw new Exception(&quot;Was not possible to authenticate&quot;); } </pre> @param url Ortc Server Url @param isCluster Indicates whether the ORTC server is in a cluster. @param authenticationToken Authentication Token which is generated by the application server, for instance a unique session ID. @param authenticationTokenIsPrivate Indicates whether the authentication token is private (true) or not (false) @param applicationKey Application Key that was provided to you together with the ORTC service purchasing. @param timeToLive The authentication token time to live, in other words, the allowed activity time (in seconds). @param privateKey The private key provided to you together with the ORTC service purchasing. @param permissions HashMap&lt;String,LinkedList&lt;String,ChannelPermissions&gt; &gt; permissions The channels and their permissions (w: write/read or r: read or p: presence, case sensitive). @param onCompleted The callback that is executed after the save authentication is completed @throws ibt.ortc.api.OrtcAuthenticationNotAuthorizedException @throws InvalidBalancerServerException
[ "Saves", "the", "authentication", "token", "channels", "permissions", "in", "the", "ORTC", "server", "." ]
train
https://github.com/realtime-framework/RealtimeMessaging-Android/blob/f0d87b92ed7c591bcfe2b9cf45b947865570e061/library/src/main/java/ibt/ortc/api/Ortc.java#L496-L518
gallandarakhneorg/afc
advanced/attributes/src/main/java/org/arakhne/afc/attrs/attr/AttributeValueImpl.java
AttributeValueImpl.setInternalValue
protected void setInternalValue(Object value, AttributeType type) { """ Set this value with the content of the specified one. <p>The type of the attribute will be NOT detected from the type of the object. It means that it will be equal to the given type, even if the given value is incompatible. The given value must be compatible with internal representation of the attribute implementation. @param value is the raw value to put inside this attribute value. @param type is the type of the value. """ this.value = value; this.assigned = this.value != null; this.type = type; }
java
protected void setInternalValue(Object value, AttributeType type) { this.value = value; this.assigned = this.value != null; this.type = type; }
[ "protected", "void", "setInternalValue", "(", "Object", "value", ",", "AttributeType", "type", ")", "{", "this", ".", "value", "=", "value", ";", "this", ".", "assigned", "=", "this", ".", "value", "!=", "null", ";", "this", ".", "type", "=", "type", ";", "}" ]
Set this value with the content of the specified one. <p>The type of the attribute will be NOT detected from the type of the object. It means that it will be equal to the given type, even if the given value is incompatible. The given value must be compatible with internal representation of the attribute implementation. @param value is the raw value to put inside this attribute value. @param type is the type of the value.
[ "Set", "this", "value", "with", "the", "content", "of", "the", "specified", "one", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/attributes/src/main/java/org/arakhne/afc/attrs/attr/AttributeValueImpl.java#L849-L853
deeplearning4j/deeplearning4j
nd4j/nd4j-parameter-server-parent/nd4j-parameter-server-node/src/main/java/org/nd4j/parameterserver/distributed/logic/completion/Clipboard.java
Clipboard.unpin
public VoidAggregation unpin(long originatorId, long taskId) { """ This method removes given VoidAggregation from clipboard, and returns it @param taskId """ RequestDescriptor descriptor = RequestDescriptor.createDescriptor(originatorId, taskId); VoidAggregation aggregation; if ((aggregation = clipboard.get(descriptor)) != null) { clipboard.remove(descriptor); trackingCounter.decrementAndGet(); // FIXME: we don't want this here // completedQueue.clear(); return aggregation; } else return null; }
java
public VoidAggregation unpin(long originatorId, long taskId) { RequestDescriptor descriptor = RequestDescriptor.createDescriptor(originatorId, taskId); VoidAggregation aggregation; if ((aggregation = clipboard.get(descriptor)) != null) { clipboard.remove(descriptor); trackingCounter.decrementAndGet(); // FIXME: we don't want this here // completedQueue.clear(); return aggregation; } else return null; }
[ "public", "VoidAggregation", "unpin", "(", "long", "originatorId", ",", "long", "taskId", ")", "{", "RequestDescriptor", "descriptor", "=", "RequestDescriptor", ".", "createDescriptor", "(", "originatorId", ",", "taskId", ")", ";", "VoidAggregation", "aggregation", ";", "if", "(", "(", "aggregation", "=", "clipboard", ".", "get", "(", "descriptor", ")", ")", "!=", "null", ")", "{", "clipboard", ".", "remove", "(", "descriptor", ")", ";", "trackingCounter", ".", "decrementAndGet", "(", ")", ";", "// FIXME: we don't want this here", "// completedQueue.clear();", "return", "aggregation", ";", "}", "else", "return", "null", ";", "}" ]
This method removes given VoidAggregation from clipboard, and returns it @param taskId
[ "This", "method", "removes", "given", "VoidAggregation", "from", "clipboard", "and", "returns", "it" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-parameter-server-parent/nd4j-parameter-server-node/src/main/java/org/nd4j/parameterserver/distributed/logic/completion/Clipboard.java#L89-L102
blackducksoftware/blackduck-common
src/main/java/com/synopsys/integration/blackduck/service/ProjectMappingService.java
ProjectMappingService.populateApplicationId
public void populateApplicationId(ProjectView projectView, String applicationId) throws IntegrationException { """ Sets the applicationId for a project @throws IntegrationException """ List<ProjectMappingView> projectMappings = blackDuckService.getAllResponses(projectView, ProjectView.PROJECT_MAPPINGS_LINK_RESPONSE); boolean canCreate = projectMappings.isEmpty(); if (canCreate) { if (!projectView.hasLink(ProjectView.PROJECT_MAPPINGS_LINK)) { throw new BlackDuckIntegrationException(String.format("The supplied projectView does not have the link (%s) to create a project mapping.", ProjectView.PROJECT_MAPPINGS_LINK)); } String projectMappingsLink = projectView.getFirstLink(ProjectView.PROJECT_MAPPINGS_LINK).get(); ProjectMappingView projectMappingView = new ProjectMappingView(); projectMappingView.setApplicationId(applicationId); blackDuckService.post(projectMappingsLink, projectMappingView); } else { // Currently there exists only one project-mapping which is the project's Application ID. // Eventually, this method would need to take in a namespace on which we will need to filter. ProjectMappingView projectMappingView = projectMappings.get(0); projectMappingView.setApplicationId(applicationId); blackDuckService.put(projectMappingView); } }
java
public void populateApplicationId(ProjectView projectView, String applicationId) throws IntegrationException { List<ProjectMappingView> projectMappings = blackDuckService.getAllResponses(projectView, ProjectView.PROJECT_MAPPINGS_LINK_RESPONSE); boolean canCreate = projectMappings.isEmpty(); if (canCreate) { if (!projectView.hasLink(ProjectView.PROJECT_MAPPINGS_LINK)) { throw new BlackDuckIntegrationException(String.format("The supplied projectView does not have the link (%s) to create a project mapping.", ProjectView.PROJECT_MAPPINGS_LINK)); } String projectMappingsLink = projectView.getFirstLink(ProjectView.PROJECT_MAPPINGS_LINK).get(); ProjectMappingView projectMappingView = new ProjectMappingView(); projectMappingView.setApplicationId(applicationId); blackDuckService.post(projectMappingsLink, projectMappingView); } else { // Currently there exists only one project-mapping which is the project's Application ID. // Eventually, this method would need to take in a namespace on which we will need to filter. ProjectMappingView projectMappingView = projectMappings.get(0); projectMappingView.setApplicationId(applicationId); blackDuckService.put(projectMappingView); } }
[ "public", "void", "populateApplicationId", "(", "ProjectView", "projectView", ",", "String", "applicationId", ")", "throws", "IntegrationException", "{", "List", "<", "ProjectMappingView", ">", "projectMappings", "=", "blackDuckService", ".", "getAllResponses", "(", "projectView", ",", "ProjectView", ".", "PROJECT_MAPPINGS_LINK_RESPONSE", ")", ";", "boolean", "canCreate", "=", "projectMappings", ".", "isEmpty", "(", ")", ";", "if", "(", "canCreate", ")", "{", "if", "(", "!", "projectView", ".", "hasLink", "(", "ProjectView", ".", "PROJECT_MAPPINGS_LINK", ")", ")", "{", "throw", "new", "BlackDuckIntegrationException", "(", "String", ".", "format", "(", "\"The supplied projectView does not have the link (%s) to create a project mapping.\"", ",", "ProjectView", ".", "PROJECT_MAPPINGS_LINK", ")", ")", ";", "}", "String", "projectMappingsLink", "=", "projectView", ".", "getFirstLink", "(", "ProjectView", ".", "PROJECT_MAPPINGS_LINK", ")", ".", "get", "(", ")", ";", "ProjectMappingView", "projectMappingView", "=", "new", "ProjectMappingView", "(", ")", ";", "projectMappingView", ".", "setApplicationId", "(", "applicationId", ")", ";", "blackDuckService", ".", "post", "(", "projectMappingsLink", ",", "projectMappingView", ")", ";", "}", "else", "{", "// Currently there exists only one project-mapping which is the project's Application ID.", "// Eventually, this method would need to take in a namespace on which we will need to filter.", "ProjectMappingView", "projectMappingView", "=", "projectMappings", ".", "get", "(", "0", ")", ";", "projectMappingView", ".", "setApplicationId", "(", "applicationId", ")", ";", "blackDuckService", ".", "put", "(", "projectMappingView", ")", ";", "}", "}" ]
Sets the applicationId for a project @throws IntegrationException
[ "Sets", "the", "applicationId", "for", "a", "project" ]
train
https://github.com/blackducksoftware/blackduck-common/blob/4ea4e90b52b75470b71c597b65cf4e2d73887bcc/src/main/java/com/synopsys/integration/blackduck/service/ProjectMappingService.java#L42-L60