repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
218
func_name
stringlengths
4
140
whole_func_string
stringlengths
153
5.32k
language
stringclasses
1 value
func_code_string
stringlengths
72
4k
func_code_tokens
sequencelengths
20
832
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
sequencelengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
102
339
radkovo/jStyleParser
src/main/java/cz/vutbr/web/csskit/antlr4/CSSErrorStrategy.java
CSSErrorStrategy.consumeUntil
public void consumeUntil(Parser recognizer, IntervalSet follow, CSSLexerState.RecoveryMode mode, CSSLexerState ls) { """ Consumes token until lexer state is function-balanced and token from follow is matched. """ CSSToken t; boolean finish; TokenStream input = recognizer.getInputStream(); do { Token next = input.LT(1); if (next instanceof CSSToken) { t = (CSSToken) input.LT(1); if (t.getType() == Token.EOF) { logger.trace("token eof "); break; } } else break; /* not a CSSToken, probably EOF */ // consume token if does not match finish = (t.getLexerState().isBalanced(mode, ls, t) && follow.contains(t.getType())); if (!finish) { logger.trace("Skipped: {}", t); input.consume(); } } while (!finish); }
java
public void consumeUntil(Parser recognizer, IntervalSet follow, CSSLexerState.RecoveryMode mode, CSSLexerState ls) { CSSToken t; boolean finish; TokenStream input = recognizer.getInputStream(); do { Token next = input.LT(1); if (next instanceof CSSToken) { t = (CSSToken) input.LT(1); if (t.getType() == Token.EOF) { logger.trace("token eof "); break; } } else break; /* not a CSSToken, probably EOF */ // consume token if does not match finish = (t.getLexerState().isBalanced(mode, ls, t) && follow.contains(t.getType())); if (!finish) { logger.trace("Skipped: {}", t); input.consume(); } } while (!finish); }
[ "public", "void", "consumeUntil", "(", "Parser", "recognizer", ",", "IntervalSet", "follow", ",", "CSSLexerState", ".", "RecoveryMode", "mode", ",", "CSSLexerState", "ls", ")", "{", "CSSToken", "t", ";", "boolean", "finish", ";", "TokenStream", "input", "=", "recognizer", ".", "getInputStream", "(", ")", ";", "do", "{", "Token", "next", "=", "input", ".", "LT", "(", "1", ")", ";", "if", "(", "next", "instanceof", "CSSToken", ")", "{", "t", "=", "(", "CSSToken", ")", "input", ".", "LT", "(", "1", ")", ";", "if", "(", "t", ".", "getType", "(", ")", "==", "Token", ".", "EOF", ")", "{", "logger", ".", "trace", "(", "\"token eof \"", ")", ";", "break", ";", "}", "}", "else", "break", ";", "/* not a CSSToken, probably EOF */", "// consume token if does not match", "finish", "=", "(", "t", ".", "getLexerState", "(", ")", ".", "isBalanced", "(", "mode", ",", "ls", ",", "t", ")", "&&", "follow", ".", "contains", "(", "t", ".", "getType", "(", ")", ")", ")", ";", "if", "(", "!", "finish", ")", "{", "logger", ".", "trace", "(", "\"Skipped: {}\"", ",", "t", ")", ";", "input", ".", "consume", "(", ")", ";", "}", "}", "while", "(", "!", "finish", ")", ";", "}" ]
Consumes token until lexer state is function-balanced and token from follow is matched.
[ "Consumes", "token", "until", "lexer", "state", "is", "function", "-", "balanced", "and", "token", "from", "follow", "is", "matched", "." ]
train
https://github.com/radkovo/jStyleParser/blob/8ab049ac6866aa52c4d7deee25c9e294e7191957/src/main/java/cz/vutbr/web/csskit/antlr4/CSSErrorStrategy.java#L104-L125
infinispan/infinispan
query/src/main/java/org/infinispan/query/Search.java
Search.getQueryFactory
public static QueryFactory getQueryFactory(Cache<?, ?> cache) { """ Obtain the query factory for building DSL based Ickle queries. """ if (cache == null || cache.getAdvancedCache() == null) { throw new IllegalArgumentException("cache parameter shall not be null"); } AdvancedCache<?, ?> advancedCache = cache.getAdvancedCache(); ensureAccessPermissions(advancedCache); EmbeddedQueryEngine queryEngine = SecurityActions.getCacheComponentRegistry(advancedCache).getComponent(EmbeddedQueryEngine.class); if (queryEngine == null) { throw log.queryModuleNotInitialised(); } return new EmbeddedQueryFactory(queryEngine); }
java
public static QueryFactory getQueryFactory(Cache<?, ?> cache) { if (cache == null || cache.getAdvancedCache() == null) { throw new IllegalArgumentException("cache parameter shall not be null"); } AdvancedCache<?, ?> advancedCache = cache.getAdvancedCache(); ensureAccessPermissions(advancedCache); EmbeddedQueryEngine queryEngine = SecurityActions.getCacheComponentRegistry(advancedCache).getComponent(EmbeddedQueryEngine.class); if (queryEngine == null) { throw log.queryModuleNotInitialised(); } return new EmbeddedQueryFactory(queryEngine); }
[ "public", "static", "QueryFactory", "getQueryFactory", "(", "Cache", "<", "?", ",", "?", ">", "cache", ")", "{", "if", "(", "cache", "==", "null", "||", "cache", ".", "getAdvancedCache", "(", ")", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"cache parameter shall not be null\"", ")", ";", "}", "AdvancedCache", "<", "?", ",", "?", ">", "advancedCache", "=", "cache", ".", "getAdvancedCache", "(", ")", ";", "ensureAccessPermissions", "(", "advancedCache", ")", ";", "EmbeddedQueryEngine", "queryEngine", "=", "SecurityActions", ".", "getCacheComponentRegistry", "(", "advancedCache", ")", ".", "getComponent", "(", "EmbeddedQueryEngine", ".", "class", ")", ";", "if", "(", "queryEngine", "==", "null", ")", "{", "throw", "log", ".", "queryModuleNotInitialised", "(", ")", ";", "}", "return", "new", "EmbeddedQueryFactory", "(", "queryEngine", ")", ";", "}" ]
Obtain the query factory for building DSL based Ickle queries.
[ "Obtain", "the", "query", "factory", "for", "building", "DSL", "based", "Ickle", "queries", "." ]
train
https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/query/src/main/java/org/infinispan/query/Search.java#L66-L77
wisdom-framework/wisdom
extensions/wisdom-raml/wisdom-source-watcher/src/main/java/org/wisdom/source/ast/visitor/ClassSourceVisitor.java
ClassSourceVisitor.containsAnnotation
private boolean containsAnnotation(List<AnnotationExpr> annos, String annotationName) { """ Check if the list of annotation contains the annotation of given name. @param annos, the annotation list @param annotationName, the annotation name @return <code>true</code> if the annotation list contains the given annotation. """ for (AnnotationExpr anno : annos) { if (anno.getName().getName().equals(annotationName)) { return true; } } return false; }
java
private boolean containsAnnotation(List<AnnotationExpr> annos, String annotationName) { for (AnnotationExpr anno : annos) { if (anno.getName().getName().equals(annotationName)) { return true; } } return false; }
[ "private", "boolean", "containsAnnotation", "(", "List", "<", "AnnotationExpr", ">", "annos", ",", "String", "annotationName", ")", "{", "for", "(", "AnnotationExpr", "anno", ":", "annos", ")", "{", "if", "(", "anno", ".", "getName", "(", ")", ".", "getName", "(", ")", ".", "equals", "(", "annotationName", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Check if the list of annotation contains the annotation of given name. @param annos, the annotation list @param annotationName, the annotation name @return <code>true</code> if the annotation list contains the given annotation.
[ "Check", "if", "the", "list", "of", "annotation", "contains", "the", "annotation", "of", "given", "name", "." ]
train
https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/extensions/wisdom-raml/wisdom-source-watcher/src/main/java/org/wisdom/source/ast/visitor/ClassSourceVisitor.java#L112-L119
kiegroup/drools
drools-core/src/main/java/org/drools/core/reteoo/ObjectTypeNode.java
ObjectTypeNode.createMemory
public ObjectTypeNodeMemory createMemory(final RuleBaseConfiguration config, InternalWorkingMemory wm) { """ Creates memory for the node using PrimitiveLongMap as its optimised for storage and reteivals of Longs. However PrimitiveLongMap is not ideal for spase data. So it should be monitored incase its more optimal to switch back to a standard HashMap. """ Class<?> classType = ((ClassObjectType) getObjectType()).getClassType(); if (InitialFact.class.isAssignableFrom(classType)) { return new InitialFactObjectTypeNodeMemory(classType); } return new ObjectTypeNodeMemory(classType, wm); }
java
public ObjectTypeNodeMemory createMemory(final RuleBaseConfiguration config, InternalWorkingMemory wm) { Class<?> classType = ((ClassObjectType) getObjectType()).getClassType(); if (InitialFact.class.isAssignableFrom(classType)) { return new InitialFactObjectTypeNodeMemory(classType); } return new ObjectTypeNodeMemory(classType, wm); }
[ "public", "ObjectTypeNodeMemory", "createMemory", "(", "final", "RuleBaseConfiguration", "config", ",", "InternalWorkingMemory", "wm", ")", "{", "Class", "<", "?", ">", "classType", "=", "(", "(", "ClassObjectType", ")", "getObjectType", "(", ")", ")", ".", "getClassType", "(", ")", ";", "if", "(", "InitialFact", ".", "class", ".", "isAssignableFrom", "(", "classType", ")", ")", "{", "return", "new", "InitialFactObjectTypeNodeMemory", "(", "classType", ")", ";", "}", "return", "new", "ObjectTypeNodeMemory", "(", "classType", ",", "wm", ")", ";", "}" ]
Creates memory for the node using PrimitiveLongMap as its optimised for storage and reteivals of Longs. However PrimitiveLongMap is not ideal for spase data. So it should be monitored incase its more optimal to switch back to a standard HashMap.
[ "Creates", "memory", "for", "the", "node", "using", "PrimitiveLongMap", "as", "its", "optimised", "for", "storage", "and", "reteivals", "of", "Longs", ".", "However", "PrimitiveLongMap", "is", "not", "ideal", "for", "spase", "data", ".", "So", "it", "should", "be", "monitored", "incase", "its", "more", "optimal", "to", "switch", "back", "to", "a", "standard", "HashMap", "." ]
train
https://github.com/kiegroup/drools/blob/22b0275d6dbe93070b8090948502cf46eda543c4/drools-core/src/main/java/org/drools/core/reteoo/ObjectTypeNode.java#L524-L530
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.comms.client/src/com/ibm/ws/sib/comms/client/proxyqueue/queue/ReadAheadQueue.java
ReadAheadQueue.putToFront
public void putToFront(QueueData queueData, short msgBatch) { """ Places a message on to the front of the proxy queue so that the next get operation will consume it. @param queueData @param msgBatch """ if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "putToFront", new Object[]{queueData, msgBatch}); _put(queueData, msgBatch, false); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "putToFront"); }
java
public void putToFront(QueueData queueData, short msgBatch) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "putToFront", new Object[]{queueData, msgBatch}); _put(queueData, msgBatch, false); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "putToFront"); }
[ "public", "void", "putToFront", "(", "QueueData", "queueData", ",", "short", "msgBatch", ")", "{", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEntryEnabled", "(", ")", ")", "SibTr", ".", "entry", "(", "this", ",", "tc", ",", "\"putToFront\"", ",", "new", "Object", "[", "]", "{", "queueData", ",", "msgBatch", "}", ")", ";", "_put", "(", "queueData", ",", "msgBatch", ",", "false", ")", ";", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEntryEnabled", "(", ")", ")", "SibTr", ".", "exit", "(", "this", ",", "tc", ",", "\"putToFront\"", ")", ";", "}" ]
Places a message on to the front of the proxy queue so that the next get operation will consume it. @param queueData @param msgBatch
[ "Places", "a", "message", "on", "to", "the", "front", "of", "the", "proxy", "queue", "so", "that", "the", "next", "get", "operation", "will", "consume", "it", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.comms.client/src/com/ibm/ws/sib/comms/client/proxyqueue/queue/ReadAheadQueue.java#L267-L275
telly/MrVector
library/src/main/java/com/telly/mrvector/MrVector.java
MrVector.inflateCompatOnly
public static Drawable inflateCompatOnly(Resources resources, @DrawableRes int resId) { """ Inflates a <vector> drawable, using {@link com.telly.mrvector.VectorDrawable} implementation always. @param resources Resources to use for inflation @param resId <vector> drawable resource @return <p>Inflated instance of {@link com.telly.mrvector.VectorDrawable}.</p> @see #inflate(android.content.res.Resources, int) """ return VectorDrawable.create(resources, resId); }
java
public static Drawable inflateCompatOnly(Resources resources, @DrawableRes int resId) { return VectorDrawable.create(resources, resId); }
[ "public", "static", "Drawable", "inflateCompatOnly", "(", "Resources", "resources", ",", "@", "DrawableRes", "int", "resId", ")", "{", "return", "VectorDrawable", ".", "create", "(", "resources", ",", "resId", ")", ";", "}" ]
Inflates a <vector> drawable, using {@link com.telly.mrvector.VectorDrawable} implementation always. @param resources Resources to use for inflation @param resId <vector> drawable resource @return <p>Inflated instance of {@link com.telly.mrvector.VectorDrawable}.</p> @see #inflate(android.content.res.Resources, int)
[ "Inflates", "a", "<vector", ">", "drawable", "using", "{", "@link", "com", ".", "telly", ".", "mrvector", ".", "VectorDrawable", "}", "implementation", "always", ".", "@param", "resources", "Resources", "to", "use", "for", "inflation", "@param", "resId", "<vector", ">", "drawable", "resource", "@return", "<p", ">", "Inflated", "instance", "of", "{", "@link", "com", ".", "telly", ".", "mrvector", ".", "VectorDrawable", "}", ".", "<", "/", "p", ">" ]
train
https://github.com/telly/MrVector/blob/846cd05ab6e57dcdc1cae28e796ac84b1d6365d5/library/src/main/java/com/telly/mrvector/MrVector.java#L64-L66
apache/groovy
src/main/java/org/codehaus/groovy/reflection/CachedField.java
CachedField.setProperty
public void setProperty(final Object object, Object newValue) { """ Sets the property on the given object to the new value @param object on which to set the property @param newValue the new value of the property @throws RuntimeException if the property could not be set """ AccessPermissionChecker.checkAccessPermission(field); final Object goalValue = DefaultTypeTransformation.castToType(newValue, field.getType()); if (isFinal()) { throw new GroovyRuntimeException("Cannot set the property '" + name + "' because the backing field is final."); } try { field.set(object, goalValue); } catch (IllegalAccessException ex) { throw new GroovyRuntimeException("Cannot set the property '" + name + "'.", ex); } }
java
public void setProperty(final Object object, Object newValue) { AccessPermissionChecker.checkAccessPermission(field); final Object goalValue = DefaultTypeTransformation.castToType(newValue, field.getType()); if (isFinal()) { throw new GroovyRuntimeException("Cannot set the property '" + name + "' because the backing field is final."); } try { field.set(object, goalValue); } catch (IllegalAccessException ex) { throw new GroovyRuntimeException("Cannot set the property '" + name + "'.", ex); } }
[ "public", "void", "setProperty", "(", "final", "Object", "object", ",", "Object", "newValue", ")", "{", "AccessPermissionChecker", ".", "checkAccessPermission", "(", "field", ")", ";", "final", "Object", "goalValue", "=", "DefaultTypeTransformation", ".", "castToType", "(", "newValue", ",", "field", ".", "getType", "(", ")", ")", ";", "if", "(", "isFinal", "(", ")", ")", "{", "throw", "new", "GroovyRuntimeException", "(", "\"Cannot set the property '\"", "+", "name", "+", "\"' because the backing field is final.\"", ")", ";", "}", "try", "{", "field", ".", "set", "(", "object", ",", "goalValue", ")", ";", "}", "catch", "(", "IllegalAccessException", "ex", ")", "{", "throw", "new", "GroovyRuntimeException", "(", "\"Cannot set the property '\"", "+", "name", "+", "\"'.\"", ",", "ex", ")", ";", "}", "}" ]
Sets the property on the given object to the new value @param object on which to set the property @param newValue the new value of the property @throws RuntimeException if the property could not be set
[ "Sets", "the", "property", "on", "the", "given", "object", "to", "the", "new", "value" ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/reflection/CachedField.java#L68-L80
jmapper-framework/jmapper-core
JMapper Framework/src/main/java/com/googlecode/jmapper/xml/XML.java
XML.fillMappedField
public XML fillMappedField(Class<?> configuredClass, MappedField configuredField) { """ Enrich configuredField with get and set define in xml configuration. @param configuredClass class of field @param configuredField configured field @return this """ Attribute attribute = getGlobalAttribute(configuredField, configuredClass); if(isNull(attribute)) attribute = getAttribute(configuredField, configuredClass); if(!isNull(attribute)){ if(isEmpty(configuredField.getMethod())) configuredField.getMethod(attribute.getGet()); if(isEmpty(configuredField.setMethod())) configuredField.setMethod(attribute.getSet()); } return this; }
java
public XML fillMappedField(Class<?> configuredClass, MappedField configuredField) { Attribute attribute = getGlobalAttribute(configuredField, configuredClass); if(isNull(attribute)) attribute = getAttribute(configuredField, configuredClass); if(!isNull(attribute)){ if(isEmpty(configuredField.getMethod())) configuredField.getMethod(attribute.getGet()); if(isEmpty(configuredField.setMethod())) configuredField.setMethod(attribute.getSet()); } return this; }
[ "public", "XML", "fillMappedField", "(", "Class", "<", "?", ">", "configuredClass", ",", "MappedField", "configuredField", ")", "{", "Attribute", "attribute", "=", "getGlobalAttribute", "(", "configuredField", ",", "configuredClass", ")", ";", "if", "(", "isNull", "(", "attribute", ")", ")", "attribute", "=", "getAttribute", "(", "configuredField", ",", "configuredClass", ")", ";", "if", "(", "!", "isNull", "(", "attribute", ")", ")", "{", "if", "(", "isEmpty", "(", "configuredField", ".", "getMethod", "(", ")", ")", ")", "configuredField", ".", "getMethod", "(", "attribute", ".", "getGet", "(", ")", ")", ";", "if", "(", "isEmpty", "(", "configuredField", ".", "setMethod", "(", ")", ")", ")", "configuredField", ".", "setMethod", "(", "attribute", ".", "getSet", "(", ")", ")", ";", "}", "return", "this", ";", "}" ]
Enrich configuredField with get and set define in xml configuration. @param configuredClass class of field @param configuredField configured field @return this
[ "Enrich", "configuredField", "with", "get", "and", "set", "define", "in", "xml", "configuration", "." ]
train
https://github.com/jmapper-framework/jmapper-core/blob/b48fd3527f35055b8b4a30f53a51136f183acc90/JMapper Framework/src/main/java/com/googlecode/jmapper/xml/XML.java#L557-L571
HeidelTime/heideltime
src/de/unihd/dbs/uima/annotator/heideltime/utilities/Toolbox.java
Toolbox.findMatches
public static Iterable<MatchResult> findMatches(Pattern pattern, CharSequence s) { """ Find all the matches of a pattern in a charSequence and return the results as list. @param pattern Pattern to be matched @param s String to be matched against @return Iterable List of MatchResults """ List<MatchResult> results = new ArrayList<MatchResult>(); for (Matcher m = pattern.matcher(s); m.find();) results.add(m.toMatchResult()); return results; } /** * Sorts a given HashMap using a custom function * @param m Map of items to sort * @return sorted List of items */ public static List<Pattern> sortByValue(final HashMap<Pattern,String> m) { List<Pattern> keys = new ArrayList<Pattern>(); keys.addAll(m.keySet()); Collections.sort(keys, new Comparator<Object>() { @SuppressWarnings({ "unchecked", "rawtypes" }) public int compare(Object o1, Object o2) { Object v1 = m.get(o1); Object v2 = m.get(o2); if (v1 == null) { return (v2 == null) ? 0 : 1; } else if (v1 instanceof Comparable) { return ((Comparable) v1).compareTo(v2); } else { return 0; } } }); return keys; } }
java
public static Iterable<MatchResult> findMatches(Pattern pattern, CharSequence s) { List<MatchResult> results = new ArrayList<MatchResult>(); for (Matcher m = pattern.matcher(s); m.find();) results.add(m.toMatchResult()); return results; } /** * Sorts a given HashMap using a custom function * @param m Map of items to sort * @return sorted List of items */ public static List<Pattern> sortByValue(final HashMap<Pattern,String> m) { List<Pattern> keys = new ArrayList<Pattern>(); keys.addAll(m.keySet()); Collections.sort(keys, new Comparator<Object>() { @SuppressWarnings({ "unchecked", "rawtypes" }) public int compare(Object o1, Object o2) { Object v1 = m.get(o1); Object v2 = m.get(o2); if (v1 == null) { return (v2 == null) ? 0 : 1; } else if (v1 instanceof Comparable) { return ((Comparable) v1).compareTo(v2); } else { return 0; } } }); return keys; } }
[ "public", "static", "Iterable", "<", "MatchResult", ">", "findMatches", "(", "Pattern", "pattern", ",", "CharSequence", "s", ")", "{", "List", "<", "MatchResult", ">", "results", "=", "new", "ArrayList", "<", "MatchResult", ">", "(", ")", ";", "for", "(", "Matcher", "m", "=", "pattern", ".", "matcher", "(", "s", ")", ";", "m", ".", "find", "(", ")", ";", ")", "results", ".", "(", "m", ".", "toMatchResult", "(", ")", ")", ";", "return", "results", ";", "}", "/**\n\t * Sorts a given HashMap using a custom function\n\t * @param m Map of items to sort\n\t * @return sorted List of items\n\t */", "public", "static", "List", "<", "Pattern", ">", "sortByValue", "(", "final", "HashMap", "<", "Pattern", ",", "String", ">", "m", ")", "{", "List", "<", "Pattern", ">", "keys", "=", "new", "ArrayList", "<", "Pattern", ">", "(", ")", ";", "keys", ".", "addAll", "(", "m", ".", "keySet", "(", ")", ")", ";", "Collections", ".", "sort", "(", "keys", ",", "new", "Comparator", "<", "Object", ">", "(", ")", "{", "@", "SuppressWarnings", "(", "{", "\"unchecked\"", ",", "\"rawtypes\"", "}", ")", "public", "int", "compare", "(", "Object", "o1", ",", "Object", "o2", ")", "{", "Object", "v1", "=", "m", ".", "get", "(", "o1", ")", ";", "Object", "v2", "=", "m", ".", "get", "(", "o2", ")", ";", "if", "(", "v1", "==", "null", ")", "{", "return", "(", "v2", "==", "null", ")", "?", "0", ":", "1", ";", "}", "else", "if", "(", "v1", "instanceof", "Comparable", ")", "{", "return", "(", "(", "Comparable", ")", "v1", ")", ".", "compareTo", "(", "v2", ")", ";", "}", "else", "{", "return", "0", ";", "}", "}", "}", ")", ";", "return", "keys", ";", "}", "}" ]
Find all the matches of a pattern in a charSequence and return the results as list. @param pattern Pattern to be matched @param s String to be matched against @return Iterable List of MatchResults
[ "Find", "all", "the", "matches", "of", "a", "pattern", "in", "a", "charSequence", "and", "return", "the", "results", "as", "list", "." ]
train
https://github.com/HeidelTime/heideltime/blob/4ef5002eb5ecfeb818086ff7e394e792ee360335/src/de/unihd/dbs/uima/annotator/heideltime/utilities/Toolbox.java#L28-L61
agmip/ace-lookup
src/main/java/org/agmip/ace/util/AcePathfinderUtil.java
AcePathfinderUtil.insertValue
public static void insertValue(HashMap m, String var, String val, String path) { """ Inserts the variable in the appropriate place in a {@link HashMap}, according to the AcePathfinder. @param m the HashMap to add the variable to. @param var the variable to lookup in the AcePathfinder @param val the value to insert into the HashMap @param path use a custom path vs. a lookup path, useful if dealing with custom variables """ insertValue(m, var, val, path, false); }
java
public static void insertValue(HashMap m, String var, String val, String path) { insertValue(m, var, val, path, false); }
[ "public", "static", "void", "insertValue", "(", "HashMap", "m", ",", "String", "var", ",", "String", "val", ",", "String", "path", ")", "{", "insertValue", "(", "m", ",", "var", ",", "val", ",", "path", ",", "false", ")", ";", "}" ]
Inserts the variable in the appropriate place in a {@link HashMap}, according to the AcePathfinder. @param m the HashMap to add the variable to. @param var the variable to lookup in the AcePathfinder @param val the value to insert into the HashMap @param path use a custom path vs. a lookup path, useful if dealing with custom variables
[ "Inserts", "the", "variable", "in", "the", "appropriate", "place", "in", "a", "{", "@link", "HashMap", "}", "according", "to", "the", "AcePathfinder", "." ]
train
https://github.com/agmip/ace-lookup/blob/d8224a231cb8c01729e63010916a2a85517ce4c1/src/main/java/org/agmip/ace/util/AcePathfinderUtil.java#L116-L118
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/sun/net/www/ParseUtil.java
ParseUtil.unescape
private static byte unescape(String s, int i) { """ Un-escape and return the character at position i in string s. """ return (byte) Integer.parseInt(s.substring(i+1,i+3),16); }
java
private static byte unescape(String s, int i) { return (byte) Integer.parseInt(s.substring(i+1,i+3),16); }
[ "private", "static", "byte", "unescape", "(", "String", "s", ",", "int", "i", ")", "{", "return", "(", "byte", ")", "Integer", ".", "parseInt", "(", "s", ".", "substring", "(", "i", "+", "1", ",", "i", "+", "3", ")", ",", "16", ")", ";", "}" ]
Un-escape and return the character at position i in string s.
[ "Un", "-", "escape", "and", "return", "the", "character", "at", "position", "i", "in", "string", "s", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/net/www/ParseUtil.java#L163-L165
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/mapreduce/aggregation/Aggregations.java
Aggregations.longMax
public static <Key, Value> Aggregation<Key, Long, Long> longMax() { """ Returns an aggregation to find the long maximum of all supplied values.<br/> This aggregation is similar to: <pre>SELECT MAX(value) FROM x</pre> @param <Key> the input key type @param <Value> the supplied value type @return the maximum value over all supplied values """ return new AggregationAdapter(new LongMaxAggregation<Key, Value>()); }
java
public static <Key, Value> Aggregation<Key, Long, Long> longMax() { return new AggregationAdapter(new LongMaxAggregation<Key, Value>()); }
[ "public", "static", "<", "Key", ",", "Value", ">", "Aggregation", "<", "Key", ",", "Long", ",", "Long", ">", "longMax", "(", ")", "{", "return", "new", "AggregationAdapter", "(", "new", "LongMaxAggregation", "<", "Key", ",", "Value", ">", "(", ")", ")", ";", "}" ]
Returns an aggregation to find the long maximum of all supplied values.<br/> This aggregation is similar to: <pre>SELECT MAX(value) FROM x</pre> @param <Key> the input key type @param <Value> the supplied value type @return the maximum value over all supplied values
[ "Returns", "an", "aggregation", "to", "find", "the", "long", "maximum", "of", "all", "supplied", "values", ".", "<br", "/", ">", "This", "aggregation", "is", "similar", "to", ":", "<pre", ">", "SELECT", "MAX", "(", "value", ")", "FROM", "x<", "/", "pre", ">" ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/mapreduce/aggregation/Aggregations.java#L186-L188
h2oai/h2o-3
h2o-core/src/main/java/water/KeySnapshot.java
KeySnapshot.localSnapshot
public static KeySnapshot localSnapshot(boolean homeOnly) { """ Get the user keys from this node only. @param homeOnly - exclude the non-local (cached) keys if set @return KeySnapshot containing keys from the local K/V. """ Object [] kvs = H2O.STORE.raw_array(); ArrayList<KeyInfo> res = new ArrayList<>(); for(int i = 2; i < kvs.length; i+= 2){ Object ok = kvs[i]; if( !(ok instanceof Key ) ) continue; // Ignore tombstones and Primes and null's Key key = (Key )ok; if(!key.user_allowed())continue; if(homeOnly && !key.home())continue; // Raw array can contain regular and also wrapped values into Prime marker class: // - if we see Value object, create instance of KeyInfo // - if we do not see Value object directly (it can be wrapped in Prime marker class), // try to unwrap it via calling STORE.get (~H2O.get) and then // look at wrapped value again. Value val = Value.STORE_get(key); if( val == null ) continue; res.add(new KeyInfo(key,val)); } final KeyInfo [] arr = res.toArray(new KeyInfo[res.size()]); Arrays.sort(arr); return new KeySnapshot(arr); }
java
public static KeySnapshot localSnapshot(boolean homeOnly){ Object [] kvs = H2O.STORE.raw_array(); ArrayList<KeyInfo> res = new ArrayList<>(); for(int i = 2; i < kvs.length; i+= 2){ Object ok = kvs[i]; if( !(ok instanceof Key ) ) continue; // Ignore tombstones and Primes and null's Key key = (Key )ok; if(!key.user_allowed())continue; if(homeOnly && !key.home())continue; // Raw array can contain regular and also wrapped values into Prime marker class: // - if we see Value object, create instance of KeyInfo // - if we do not see Value object directly (it can be wrapped in Prime marker class), // try to unwrap it via calling STORE.get (~H2O.get) and then // look at wrapped value again. Value val = Value.STORE_get(key); if( val == null ) continue; res.add(new KeyInfo(key,val)); } final KeyInfo [] arr = res.toArray(new KeyInfo[res.size()]); Arrays.sort(arr); return new KeySnapshot(arr); }
[ "public", "static", "KeySnapshot", "localSnapshot", "(", "boolean", "homeOnly", ")", "{", "Object", "[", "]", "kvs", "=", "H2O", ".", "STORE", ".", "raw_array", "(", ")", ";", "ArrayList", "<", "KeyInfo", ">", "res", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "int", "i", "=", "2", ";", "i", "<", "kvs", ".", "length", ";", "i", "+=", "2", ")", "{", "Object", "ok", "=", "kvs", "[", "i", "]", ";", "if", "(", "!", "(", "ok", "instanceof", "Key", ")", ")", "continue", ";", "// Ignore tombstones and Primes and null's", "Key", "key", "=", "(", "Key", ")", "ok", ";", "if", "(", "!", "key", ".", "user_allowed", "(", ")", ")", "continue", ";", "if", "(", "homeOnly", "&&", "!", "key", ".", "home", "(", ")", ")", "continue", ";", "// Raw array can contain regular and also wrapped values into Prime marker class:", "// - if we see Value object, create instance of KeyInfo", "// - if we do not see Value object directly (it can be wrapped in Prime marker class),", "// try to unwrap it via calling STORE.get (~H2O.get) and then", "// look at wrapped value again.", "Value", "val", "=", "Value", ".", "STORE_get", "(", "key", ")", ";", "if", "(", "val", "==", "null", ")", "continue", ";", "res", ".", "add", "(", "new", "KeyInfo", "(", "key", ",", "val", ")", ")", ";", "}", "final", "KeyInfo", "[", "]", "arr", "=", "res", ".", "toArray", "(", "new", "KeyInfo", "[", "res", ".", "size", "(", ")", "]", ")", ";", "Arrays", ".", "sort", "(", "arr", ")", ";", "return", "new", "KeySnapshot", "(", "arr", ")", ";", "}" ]
Get the user keys from this node only. @param homeOnly - exclude the non-local (cached) keys if set @return KeySnapshot containing keys from the local K/V.
[ "Get", "the", "user", "keys", "from", "this", "node", "only", "." ]
train
https://github.com/h2oai/h2o-3/blob/845eb49dfeaadf638b6e2f779d82fac996391fad/h2o-core/src/main/java/water/KeySnapshot.java#L140-L161
wildfly/wildfly-core
controller/src/main/java/org/jboss/as/controller/remote/ResponseAttachmentInputStreamSupport.java
ResponseAttachmentInputStreamSupport.gc
void gc() { """ Close and remove expired streams. Package protected to allow unit tests to invoke it. """ if (stopped) { return; } long expirationTime = System.currentTimeMillis() - timeout; for (Iterator<Map.Entry<InputStreamKey, TimedStreamEntry>> iter = streamMap.entrySet().iterator(); iter.hasNext();) { if (stopped) { return; } Map.Entry<InputStreamKey, TimedStreamEntry> entry = iter.next(); TimedStreamEntry timedStreamEntry = entry.getValue(); if (timedStreamEntry.timestamp.get() <= expirationTime) { iter.remove(); InputStreamKey key = entry.getKey(); //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (timedStreamEntry) { // ensure there's no race with a request that got a ref before we removed it closeStreamEntry(timedStreamEntry, key.requestId, key.index); } } } }
java
void gc() { if (stopped) { return; } long expirationTime = System.currentTimeMillis() - timeout; for (Iterator<Map.Entry<InputStreamKey, TimedStreamEntry>> iter = streamMap.entrySet().iterator(); iter.hasNext();) { if (stopped) { return; } Map.Entry<InputStreamKey, TimedStreamEntry> entry = iter.next(); TimedStreamEntry timedStreamEntry = entry.getValue(); if (timedStreamEntry.timestamp.get() <= expirationTime) { iter.remove(); InputStreamKey key = entry.getKey(); //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (timedStreamEntry) { // ensure there's no race with a request that got a ref before we removed it closeStreamEntry(timedStreamEntry, key.requestId, key.index); } } } }
[ "void", "gc", "(", ")", "{", "if", "(", "stopped", ")", "{", "return", ";", "}", "long", "expirationTime", "=", "System", ".", "currentTimeMillis", "(", ")", "-", "timeout", ";", "for", "(", "Iterator", "<", "Map", ".", "Entry", "<", "InputStreamKey", ",", "TimedStreamEntry", ">", ">", "iter", "=", "streamMap", ".", "entrySet", "(", ")", ".", "iterator", "(", ")", ";", "iter", ".", "hasNext", "(", ")", ";", ")", "{", "if", "(", "stopped", ")", "{", "return", ";", "}", "Map", ".", "Entry", "<", "InputStreamKey", ",", "TimedStreamEntry", ">", "entry", "=", "iter", ".", "next", "(", ")", ";", "TimedStreamEntry", "timedStreamEntry", "=", "entry", ".", "getValue", "(", ")", ";", "if", "(", "timedStreamEntry", ".", "timestamp", ".", "get", "(", ")", "<=", "expirationTime", ")", "{", "iter", ".", "remove", "(", ")", ";", "InputStreamKey", "key", "=", "entry", ".", "getKey", "(", ")", ";", "//noinspection SynchronizationOnLocalVariableOrMethodParameter", "synchronized", "(", "timedStreamEntry", ")", "{", "// ensure there's no race with a request that got a ref before we removed it", "closeStreamEntry", "(", "timedStreamEntry", ",", "key", ".", "requestId", ",", "key", ".", "index", ")", ";", "}", "}", "}", "}" ]
Close and remove expired streams. Package protected to allow unit tests to invoke it.
[ "Close", "and", "remove", "expired", "streams", ".", "Package", "protected", "to", "allow", "unit", "tests", "to", "invoke", "it", "." ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/remote/ResponseAttachmentInputStreamSupport.java#L203-L223
nyla-solutions/nyla
nyla.solutions.core/src/main/java/nyla/solutions/core/util/Organizer.java
Organizer.copyToArray
public static void copyToArray(Collection<Object> collection, Object[] objects) { """ Copy collection objects to a given array @param collection the collection source @param objects array destination """ System.arraycopy(collection.toArray(), 0, objects, 0, objects.length); }
java
public static void copyToArray(Collection<Object> collection, Object[] objects) { System.arraycopy(collection.toArray(), 0, objects, 0, objects.length); }
[ "public", "static", "void", "copyToArray", "(", "Collection", "<", "Object", ">", "collection", ",", "Object", "[", "]", "objects", ")", "{", "System", ".", "arraycopy", "(", "collection", ".", "toArray", "(", ")", ",", "0", ",", "objects", ",", "0", ",", "objects", ".", "length", ")", ";", "}" ]
Copy collection objects to a given array @param collection the collection source @param objects array destination
[ "Copy", "collection", "objects", "to", "a", "given", "array" ]
train
https://github.com/nyla-solutions/nyla/blob/38d5b843c76eae9762bbca20453ed0f0ad8412a9/nyla.solutions.core/src/main/java/nyla/solutions/core/util/Organizer.java#L608-L611
lucee/Lucee
core/src/main/java/lucee/runtime/reflection/Invoker.java
Invoker.callGetter
public static Object callGetter(Object o, String prop) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { """ to invoke a getter Method of a Object @param o Object to invoke method from @param prop Name of the Method without get @return return Value of the getter Method @throws SecurityException @throws NoSuchMethodException @throws IllegalArgumentException @throws IllegalAccessException @throws InvocationTargetException """ prop = "get" + prop; Class c = o.getClass(); Method m = getMethodParameterPairIgnoreCase(c, prop, null).getMethod(); // Method m=getMethodIgnoreCase(c,prop,null); if (m.getReturnType().getName().equals("void")) throw new NoSuchMethodException("invalid return Type, method [" + m.getName() + "] can't have return type void"); return m.invoke(o, null); }
java
public static Object callGetter(Object o, String prop) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { prop = "get" + prop; Class c = o.getClass(); Method m = getMethodParameterPairIgnoreCase(c, prop, null).getMethod(); // Method m=getMethodIgnoreCase(c,prop,null); if (m.getReturnType().getName().equals("void")) throw new NoSuchMethodException("invalid return Type, method [" + m.getName() + "] can't have return type void"); return m.invoke(o, null); }
[ "public", "static", "Object", "callGetter", "(", "Object", "o", ",", "String", "prop", ")", "throws", "SecurityException", ",", "NoSuchMethodException", ",", "IllegalArgumentException", ",", "IllegalAccessException", ",", "InvocationTargetException", "{", "prop", "=", "\"get\"", "+", "prop", ";", "Class", "c", "=", "o", ".", "getClass", "(", ")", ";", "Method", "m", "=", "getMethodParameterPairIgnoreCase", "(", "c", ",", "prop", ",", "null", ")", ".", "getMethod", "(", ")", ";", "// Method m=getMethodIgnoreCase(c,prop,null);", "if", "(", "m", ".", "getReturnType", "(", ")", ".", "getName", "(", ")", ".", "equals", "(", "\"void\"", ")", ")", "throw", "new", "NoSuchMethodException", "(", "\"invalid return Type, method [\"", "+", "m", ".", "getName", "(", ")", "+", "\"] can't have return type void\"", ")", ";", "return", "m", ".", "invoke", "(", "o", ",", "null", ")", ";", "}" ]
to invoke a getter Method of a Object @param o Object to invoke method from @param prop Name of the Method without get @return return Value of the getter Method @throws SecurityException @throws NoSuchMethodException @throws IllegalArgumentException @throws IllegalAccessException @throws InvocationTargetException
[ "to", "invoke", "a", "getter", "Method", "of", "a", "Object" ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/reflection/Invoker.java#L315-L324
apache/incubator-gobblin
gobblin-modules/gobblin-sql/src/main/java/org/apache/gobblin/source/jdbc/JdbcExtractor.java
JdbcExtractor.updateDeltaFieldConfig
private void updateDeltaFieldConfig(String srcColumnName, String tgtColumnName) { """ Update water mark column property if there is an alias defined in query @param srcColumnName source column name @param tgtColumnName target column name """ if (this.workUnitState.contains(ConfigurationKeys.EXTRACT_DELTA_FIELDS_KEY)) { String watermarkCol = this.workUnitState.getProp(ConfigurationKeys.EXTRACT_DELTA_FIELDS_KEY); this.workUnitState.setProp(ConfigurationKeys.EXTRACT_DELTA_FIELDS_KEY, watermarkCol.replaceAll(srcColumnName, tgtColumnName)); } }
java
private void updateDeltaFieldConfig(String srcColumnName, String tgtColumnName) { if (this.workUnitState.contains(ConfigurationKeys.EXTRACT_DELTA_FIELDS_KEY)) { String watermarkCol = this.workUnitState.getProp(ConfigurationKeys.EXTRACT_DELTA_FIELDS_KEY); this.workUnitState.setProp(ConfigurationKeys.EXTRACT_DELTA_FIELDS_KEY, watermarkCol.replaceAll(srcColumnName, tgtColumnName)); } }
[ "private", "void", "updateDeltaFieldConfig", "(", "String", "srcColumnName", ",", "String", "tgtColumnName", ")", "{", "if", "(", "this", ".", "workUnitState", ".", "contains", "(", "ConfigurationKeys", ".", "EXTRACT_DELTA_FIELDS_KEY", ")", ")", "{", "String", "watermarkCol", "=", "this", ".", "workUnitState", ".", "getProp", "(", "ConfigurationKeys", ".", "EXTRACT_DELTA_FIELDS_KEY", ")", ";", "this", ".", "workUnitState", ".", "setProp", "(", "ConfigurationKeys", ".", "EXTRACT_DELTA_FIELDS_KEY", ",", "watermarkCol", ".", "replaceAll", "(", "srcColumnName", ",", "tgtColumnName", ")", ")", ";", "}", "}" ]
Update water mark column property if there is an alias defined in query @param srcColumnName source column name @param tgtColumnName target column name
[ "Update", "water", "mark", "column", "property", "if", "there", "is", "an", "alias", "defined", "in", "query" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-sql/src/main/java/org/apache/gobblin/source/jdbc/JdbcExtractor.java#L509-L515
Alluxio/alluxio
underfs/hdfs/src/main/java/alluxio/underfs/hdfs/HdfsUnderFileSystem.java
HdfsUnderFileSystem.createInstance
public static HdfsUnderFileSystem createInstance(AlluxioURI ufsUri, UnderFileSystemConfiguration conf, AlluxioConfiguration alluxioConf) { """ Factory method to constructs a new HDFS {@link UnderFileSystem} instance. @param ufsUri the {@link AlluxioURI} for this UFS @param conf the configuration for Hadoop @param alluxioConf Alluxio configuration @return a new HDFS {@link UnderFileSystem} instance """ Configuration hdfsConf = createConfiguration(conf); return new HdfsUnderFileSystem(ufsUri, conf, hdfsConf, alluxioConf); }
java
public static HdfsUnderFileSystem createInstance(AlluxioURI ufsUri, UnderFileSystemConfiguration conf, AlluxioConfiguration alluxioConf) { Configuration hdfsConf = createConfiguration(conf); return new HdfsUnderFileSystem(ufsUri, conf, hdfsConf, alluxioConf); }
[ "public", "static", "HdfsUnderFileSystem", "createInstance", "(", "AlluxioURI", "ufsUri", ",", "UnderFileSystemConfiguration", "conf", ",", "AlluxioConfiguration", "alluxioConf", ")", "{", "Configuration", "hdfsConf", "=", "createConfiguration", "(", "conf", ")", ";", "return", "new", "HdfsUnderFileSystem", "(", "ufsUri", ",", "conf", ",", "hdfsConf", ",", "alluxioConf", ")", ";", "}" ]
Factory method to constructs a new HDFS {@link UnderFileSystem} instance. @param ufsUri the {@link AlluxioURI} for this UFS @param conf the configuration for Hadoop @param alluxioConf Alluxio configuration @return a new HDFS {@link UnderFileSystem} instance
[ "Factory", "method", "to", "constructs", "a", "new", "HDFS", "{", "@link", "UnderFileSystem", "}", "instance", "." ]
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/underfs/hdfs/src/main/java/alluxio/underfs/hdfs/HdfsUnderFileSystem.java#L106-L110
ggrandes/kvstore
src/main/java/org/javastack/kvstore/io/FileStreamStore.java
FileStreamStore.readFromEnd
public synchronized long readFromEnd(final long datalen, final ByteBuffer buf) { """ Read desired block of datalen from end of file @param datalen expected @param ByteBuffer @return new offset (offset+headerlen+datalen+footer) """ if (!validState) { throw new InvalidStateException(); } final long size = size(); final long offset = (size - HEADER_LEN - datalen - FOOTER_LEN); return read(offset, buf); }
java
public synchronized long readFromEnd(final long datalen, final ByteBuffer buf) { if (!validState) { throw new InvalidStateException(); } final long size = size(); final long offset = (size - HEADER_LEN - datalen - FOOTER_LEN); return read(offset, buf); }
[ "public", "synchronized", "long", "readFromEnd", "(", "final", "long", "datalen", ",", "final", "ByteBuffer", "buf", ")", "{", "if", "(", "!", "validState", ")", "{", "throw", "new", "InvalidStateException", "(", ")", ";", "}", "final", "long", "size", "=", "size", "(", ")", ";", "final", "long", "offset", "=", "(", "size", "-", "HEADER_LEN", "-", "datalen", "-", "FOOTER_LEN", ")", ";", "return", "read", "(", "offset", ",", "buf", ")", ";", "}" ]
Read desired block of datalen from end of file @param datalen expected @param ByteBuffer @return new offset (offset+headerlen+datalen+footer)
[ "Read", "desired", "block", "of", "datalen", "from", "end", "of", "file" ]
train
https://github.com/ggrandes/kvstore/blob/c79277f79f4604e0fec8349a98519838e3de38f0/src/main/java/org/javastack/kvstore/io/FileStreamStore.java#L368-L375
roboconf/roboconf-platform
core/roboconf-target-iaas-openstack/src/main/java/net/roboconf/target/openstack/internal/OpenstackIaasHandler.java
OpenstackIaasHandler.novaApi
static NovaApi novaApi( Map<String,String> targetProperties ) throws TargetException { """ Creates a JCloud context for Nova. @param targetProperties the target properties @return a non-null object @throws TargetException if the target properties are invalid """ validate( targetProperties ); return ContextBuilder .newBuilder( PROVIDER_NOVA ) .endpoint( targetProperties.get( API_URL )) .credentials( identity( targetProperties ), targetProperties.get( PASSWORD )) .buildApi( NovaApi.class ); }
java
static NovaApi novaApi( Map<String,String> targetProperties ) throws TargetException { validate( targetProperties ); return ContextBuilder .newBuilder( PROVIDER_NOVA ) .endpoint( targetProperties.get( API_URL )) .credentials( identity( targetProperties ), targetProperties.get( PASSWORD )) .buildApi( NovaApi.class ); }
[ "static", "NovaApi", "novaApi", "(", "Map", "<", "String", ",", "String", ">", "targetProperties", ")", "throws", "TargetException", "{", "validate", "(", "targetProperties", ")", ";", "return", "ContextBuilder", ".", "newBuilder", "(", "PROVIDER_NOVA", ")", ".", "endpoint", "(", "targetProperties", ".", "get", "(", "API_URL", ")", ")", ".", "credentials", "(", "identity", "(", "targetProperties", ")", ",", "targetProperties", ".", "get", "(", "PASSWORD", ")", ")", ".", "buildApi", "(", "NovaApi", ".", "class", ")", ";", "}" ]
Creates a JCloud context for Nova. @param targetProperties the target properties @return a non-null object @throws TargetException if the target properties are invalid
[ "Creates", "a", "JCloud", "context", "for", "Nova", "." ]
train
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-target-iaas-openstack/src/main/java/net/roboconf/target/openstack/internal/OpenstackIaasHandler.java#L357-L365
Azure/azure-sdk-for-java
common/azure-common/src/main/java/com/azure/common/implementation/util/FluxUtil.java
FluxUtil.byteBufStreamFromFile
public static Flux<ByteBuf> byteBufStreamFromFile(AsynchronousFileChannel fileChannel, long offset, long length) { """ Creates a {@link Flux} from an {@link AsynchronousFileChannel} which reads part of a file. @param fileChannel The file channel. @param offset The offset in the file to begin reading. @param length The number of bytes to read from the file. @return the Flowable. """ return byteBufStreamFromFile(fileChannel, DEFAULT_CHUNK_SIZE, offset, length); }
java
public static Flux<ByteBuf> byteBufStreamFromFile(AsynchronousFileChannel fileChannel, long offset, long length) { return byteBufStreamFromFile(fileChannel, DEFAULT_CHUNK_SIZE, offset, length); }
[ "public", "static", "Flux", "<", "ByteBuf", ">", "byteBufStreamFromFile", "(", "AsynchronousFileChannel", "fileChannel", ",", "long", "offset", ",", "long", "length", ")", "{", "return", "byteBufStreamFromFile", "(", "fileChannel", ",", "DEFAULT_CHUNK_SIZE", ",", "offset", ",", "length", ")", ";", "}" ]
Creates a {@link Flux} from an {@link AsynchronousFileChannel} which reads part of a file. @param fileChannel The file channel. @param offset The offset in the file to begin reading. @param length The number of bytes to read from the file. @return the Flowable.
[ "Creates", "a", "{", "@link", "Flux", "}", "from", "an", "{", "@link", "AsynchronousFileChannel", "}", "which", "reads", "part", "of", "a", "file", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/common/azure-common/src/main/java/com/azure/common/implementation/util/FluxUtil.java#L177-L179
overturetool/overture
core/codegen/platform/src/main/java/org/overture/codegen/ir/CodeGenBase.java
CodeGenBase.genIrStatus
protected void genIrStatus(List<IRStatus<PIR>> statuses, INode node) throws AnalysisException { """ This method translates a VDM node into an IR status. @param statuses A list of previously generated IR statuses. The generated IR status will be added to this list. @param node The VDM node from which we generate an IR status @throws AnalysisException If something goes wrong during the construction of the IR status. """ IRStatus<PIR> status = generator.generateFrom(node); if (status != null) { statuses.add(status); } }
java
protected void genIrStatus(List<IRStatus<PIR>> statuses, INode node) throws AnalysisException { IRStatus<PIR> status = generator.generateFrom(node); if (status != null) { statuses.add(status); } }
[ "protected", "void", "genIrStatus", "(", "List", "<", "IRStatus", "<", "PIR", ">", ">", "statuses", ",", "INode", "node", ")", "throws", "AnalysisException", "{", "IRStatus", "<", "PIR", ">", "status", "=", "generator", ".", "generateFrom", "(", "node", ")", ";", "if", "(", "status", "!=", "null", ")", "{", "statuses", ".", "add", "(", "status", ")", ";", "}", "}" ]
This method translates a VDM node into an IR status. @param statuses A list of previously generated IR statuses. The generated IR status will be added to this list. @param node The VDM node from which we generate an IR status @throws AnalysisException If something goes wrong during the construction of the IR status.
[ "This", "method", "translates", "a", "VDM", "node", "into", "an", "IR", "status", "." ]
train
https://github.com/overturetool/overture/blob/83175dc6c24fa171cde4fcf61ecb648eba3bdbc1/core/codegen/platform/src/main/java/org/overture/codegen/ir/CodeGenBase.java#L138-L147
apptentive/apptentive-android
apptentive/src/main/java/com/apptentive/android/sdk/Apptentive.java
Apptentive.setPushNotificationIntegration
public static void setPushNotificationIntegration(final int pushProvider, final String token) { """ Sends push provider information to our server to allow us to send pushes to this device when you reply to your customers. Only one push provider is allowed to be active at a time, so you should only call this method once. Please see our <a href="http://www.apptentive.com/docs/android/integration/#push-notifications">integration guide</a> for instructions. @param pushProvider One of the following: <ul> <li>{@link #PUSH_PROVIDER_APPTENTIVE}</li> <li>{@link #PUSH_PROVIDER_PARSE}</li> <li>{@link #PUSH_PROVIDER_URBAN_AIRSHIP}</li> <li>{@link #PUSH_PROVIDER_AMAZON_AWS_SNS}</li> </ul> @param token The push provider token you receive from your push provider. The format is push provider specific. <dl> <dt>Apptentive</dt> <dd>If you are using Apptentive to send pushes directly to GCM or FCM, pass in the GCM/FCM Registration ID, which you can <a href="https://github.com/googlesamples/google-services/blob/73f8a4fcfc93da08a40b96df3537bb9b6ef1b0fa/android/gcm/app/src/main/java/gcm/play/android/samples/com/gcmquickstart/RegistrationIntentService.java#L51">access like this</a>. </dd> <dt>Parse</dt> <dd>The Parse <a href="https://parse.com/docs/android/guide#push-notifications">deviceToken</a></dd> <dt>Urban Airship</dt> <dd>The Urban Airship Channel ID, which you can <a href="https://github.com/urbanairship/android-samples/blob/8ad77e5e81a1b0507c6a2c45a5c30a1e2da851e9/PushSample/src/com/urbanairship/push/sample/IntentReceiver.java#L43">access like this</a>. </dd> <dt>Amazon AWS SNS</dt> <dd>The GCM Registration ID, which you can <a href="http://docs.aws.amazon.com/sns/latest/dg/mobile-push-gcm.html#registration-id-gcm">access like this</a>.</dd> </dl> """ dispatchConversationTask(new ConversationDispatchTask() { @Override protected boolean execute(Conversation conversation) { // Store the push stuff globally SharedPreferences prefs = ApptentiveInternal.getInstance().getGlobalSharedPrefs(); prefs.edit().putInt(Constants.PREF_KEY_PUSH_PROVIDER, pushProvider) .putString(Constants.PREF_KEY_PUSH_TOKEN, token) .apply(); // Also set it on the active Conversation, if there is one. conversation.setPushIntegration(pushProvider, token); return true; } }, "set push notification integration"); }
java
public static void setPushNotificationIntegration(final int pushProvider, final String token) { dispatchConversationTask(new ConversationDispatchTask() { @Override protected boolean execute(Conversation conversation) { // Store the push stuff globally SharedPreferences prefs = ApptentiveInternal.getInstance().getGlobalSharedPrefs(); prefs.edit().putInt(Constants.PREF_KEY_PUSH_PROVIDER, pushProvider) .putString(Constants.PREF_KEY_PUSH_TOKEN, token) .apply(); // Also set it on the active Conversation, if there is one. conversation.setPushIntegration(pushProvider, token); return true; } }, "set push notification integration"); }
[ "public", "static", "void", "setPushNotificationIntegration", "(", "final", "int", "pushProvider", ",", "final", "String", "token", ")", "{", "dispatchConversationTask", "(", "new", "ConversationDispatchTask", "(", ")", "{", "@", "Override", "protected", "boolean", "execute", "(", "Conversation", "conversation", ")", "{", "// Store the push stuff globally", "SharedPreferences", "prefs", "=", "ApptentiveInternal", ".", "getInstance", "(", ")", ".", "getGlobalSharedPrefs", "(", ")", ";", "prefs", ".", "edit", "(", ")", ".", "putInt", "(", "Constants", ".", "PREF_KEY_PUSH_PROVIDER", ",", "pushProvider", ")", ".", "putString", "(", "Constants", ".", "PREF_KEY_PUSH_TOKEN", ",", "token", ")", ".", "apply", "(", ")", ";", "// Also set it on the active Conversation, if there is one.", "conversation", ".", "setPushIntegration", "(", "pushProvider", ",", "token", ")", ";", "return", "true", ";", "}", "}", ",", "\"set push notification integration\"", ")", ";", "}" ]
Sends push provider information to our server to allow us to send pushes to this device when you reply to your customers. Only one push provider is allowed to be active at a time, so you should only call this method once. Please see our <a href="http://www.apptentive.com/docs/android/integration/#push-notifications">integration guide</a> for instructions. @param pushProvider One of the following: <ul> <li>{@link #PUSH_PROVIDER_APPTENTIVE}</li> <li>{@link #PUSH_PROVIDER_PARSE}</li> <li>{@link #PUSH_PROVIDER_URBAN_AIRSHIP}</li> <li>{@link #PUSH_PROVIDER_AMAZON_AWS_SNS}</li> </ul> @param token The push provider token you receive from your push provider. The format is push provider specific. <dl> <dt>Apptentive</dt> <dd>If you are using Apptentive to send pushes directly to GCM or FCM, pass in the GCM/FCM Registration ID, which you can <a href="https://github.com/googlesamples/google-services/blob/73f8a4fcfc93da08a40b96df3537bb9b6ef1b0fa/android/gcm/app/src/main/java/gcm/play/android/samples/com/gcmquickstart/RegistrationIntentService.java#L51">access like this</a>. </dd> <dt>Parse</dt> <dd>The Parse <a href="https://parse.com/docs/android/guide#push-notifications">deviceToken</a></dd> <dt>Urban Airship</dt> <dd>The Urban Airship Channel ID, which you can <a href="https://github.com/urbanairship/android-samples/blob/8ad77e5e81a1b0507c6a2c45a5c30a1e2da851e9/PushSample/src/com/urbanairship/push/sample/IntentReceiver.java#L43">access like this</a>. </dd> <dt>Amazon AWS SNS</dt> <dd>The GCM Registration ID, which you can <a href="http://docs.aws.amazon.com/sns/latest/dg/mobile-push-gcm.html#registration-id-gcm">access like this</a>.</dd> </dl>
[ "Sends", "push", "provider", "information", "to", "our", "server", "to", "allow", "us", "to", "send", "pushes", "to", "this", "device", "when", "you", "reply", "to", "your", "customers", ".", "Only", "one", "push", "provider", "is", "allowed", "to", "be", "active", "at", "a", "time", "so", "you", "should", "only", "call", "this", "method", "once", ".", "Please", "see", "our", "<a", "href", "=", "http", ":", "//", "www", ".", "apptentive", ".", "com", "/", "docs", "/", "android", "/", "integration", "/", "#push", "-", "notifications", ">", "integration", "guide<", "/", "a", ">", "for", "instructions", "." ]
train
https://github.com/apptentive/apptentive-android/blob/887c08d7bd5ae6488a90366dfb58f58938861a93/apptentive/src/main/java/com/apptentive/android/sdk/Apptentive.java#L469-L484
mgm-tp/jfunk
jfunk-core/src/main/java/com/mgmtp/jfunk/core/mail/MailAccountManager.java
MailAccountManager.reserveMailAccount
public MailAccount reserveMailAccount(final String accountReservationKey, final String pool) { """ Reserves an available mail account from the specified pool under the specified reservation key. The method blocks until an account is available. @param pool the mail address pool to reserve an account from @param accountReservationKey the key under which to reserve the account @return the reserved mail account """ if (pool == null && emailAddressPools.keySet().size() > 1) { throw new IllegalStateException("No pool specified but multiple pools available."); } String poolKey = pool == null ? defaultPool : pool; List<MailAccount> addressPool = newArrayList(emailAddressPools.get(poolKey)); Collections.shuffle(addressPool, random.getRandom()); return reserveAvailableMailAccount(accountReservationKey, addressPool); }
java
public MailAccount reserveMailAccount(final String accountReservationKey, final String pool) { if (pool == null && emailAddressPools.keySet().size() > 1) { throw new IllegalStateException("No pool specified but multiple pools available."); } String poolKey = pool == null ? defaultPool : pool; List<MailAccount> addressPool = newArrayList(emailAddressPools.get(poolKey)); Collections.shuffle(addressPool, random.getRandom()); return reserveAvailableMailAccount(accountReservationKey, addressPool); }
[ "public", "MailAccount", "reserveMailAccount", "(", "final", "String", "accountReservationKey", ",", "final", "String", "pool", ")", "{", "if", "(", "pool", "==", "null", "&&", "emailAddressPools", ".", "keySet", "(", ")", ".", "size", "(", ")", ">", "1", ")", "{", "throw", "new", "IllegalStateException", "(", "\"No pool specified but multiple pools available.\"", ")", ";", "}", "String", "poolKey", "=", "pool", "==", "null", "?", "defaultPool", ":", "pool", ";", "List", "<", "MailAccount", ">", "addressPool", "=", "newArrayList", "(", "emailAddressPools", ".", "get", "(", "poolKey", ")", ")", ";", "Collections", ".", "shuffle", "(", "addressPool", ",", "random", ".", "getRandom", "(", ")", ")", ";", "return", "reserveAvailableMailAccount", "(", "accountReservationKey", ",", "addressPool", ")", ";", "}" ]
Reserves an available mail account from the specified pool under the specified reservation key. The method blocks until an account is available. @param pool the mail address pool to reserve an account from @param accountReservationKey the key under which to reserve the account @return the reserved mail account
[ "Reserves", "an", "available", "mail", "account", "from", "the", "specified", "pool", "under", "the", "specified", "reservation", "key", ".", "The", "method", "blocks", "until", "an", "account", "is", "available", "." ]
train
https://github.com/mgm-tp/jfunk/blob/5b9fecac5778b988bb458085ded39ea9a4c7c2ae/jfunk-core/src/main/java/com/mgmtp/jfunk/core/mail/MailAccountManager.java#L177-L187
ReactiveX/RxJavaAsyncUtil
src/main/java/rx/util/async/Async.java
Async.toAsync
public static <T1, T2, T3> Func3<T1, T2, T3, Observable<Void>> toAsync(Action3<? super T1, ? super T2, ? super T3> action) { """ Convert a synchronous action call into an asynchronous function call through an Observable. <p> <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/toAsync.an.png" alt=""> @param <T1> the first parameter type @param <T2> the second parameter type @param <T3> the third parameter type @param action the action to convert @return a function that returns an Observable that executes the {@code action} and emits {@code null} @see <a href="https://github.com/ReactiveX/RxJava/wiki/Async-Operators#wiki-toasync-or-asyncaction-or-asyncfunc">RxJava Wiki: toAsync()</a> @see <a href="http://msdn.microsoft.com/en-us/library/hh229336.aspx">MSDN: Observable.ToAsync</a> """ return toAsync(action, Schedulers.computation()); }
java
public static <T1, T2, T3> Func3<T1, T2, T3, Observable<Void>> toAsync(Action3<? super T1, ? super T2, ? super T3> action) { return toAsync(action, Schedulers.computation()); }
[ "public", "static", "<", "T1", ",", "T2", ",", "T3", ">", "Func3", "<", "T1", ",", "T2", ",", "T3", ",", "Observable", "<", "Void", ">", ">", "toAsync", "(", "Action3", "<", "?", "super", "T1", ",", "?", "super", "T2", ",", "?", "super", "T3", ">", "action", ")", "{", "return", "toAsync", "(", "action", ",", "Schedulers", ".", "computation", "(", ")", ")", ";", "}" ]
Convert a synchronous action call into an asynchronous function call through an Observable. <p> <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/toAsync.an.png" alt=""> @param <T1> the first parameter type @param <T2> the second parameter type @param <T3> the third parameter type @param action the action to convert @return a function that returns an Observable that executes the {@code action} and emits {@code null} @see <a href="https://github.com/ReactiveX/RxJava/wiki/Async-Operators#wiki-toasync-or-asyncaction-or-asyncfunc">RxJava Wiki: toAsync()</a> @see <a href="http://msdn.microsoft.com/en-us/library/hh229336.aspx">MSDN: Observable.ToAsync</a>
[ "Convert", "a", "synchronous", "action", "call", "into", "an", "asynchronous", "function", "call", "through", "an", "Observable", ".", "<p", ">", "<img", "width", "=", "640", "src", "=", "https", ":", "//", "raw", ".", "github", ".", "com", "/", "wiki", "/", "ReactiveX", "/", "RxJava", "/", "images", "/", "rx", "-", "operators", "/", "toAsync", ".", "an", ".", "png", "alt", "=", ">" ]
train
https://github.com/ReactiveX/RxJavaAsyncUtil/blob/6294e1da30e639df79f76399906229314c14e74d/src/main/java/rx/util/async/Async.java#L290-L292
jboss-integration/fuse-bxms-integ
switchyard/switchyard-component-common-knowledge/src/main/java/org/switchyard/component/common/knowledge/exchange/KnowledgeExchangeHandler.java
KnowledgeExchangeHandler.isBoolean
protected boolean isBoolean(Exchange exchange, Message message, String name) { """ Gets a primitive boolean context property. @param exchange the exchange @param message the message @param name the name @return the property """ Boolean b = getBoolean(exchange, message, name); return b != null && b.booleanValue(); }
java
protected boolean isBoolean(Exchange exchange, Message message, String name) { Boolean b = getBoolean(exchange, message, name); return b != null && b.booleanValue(); }
[ "protected", "boolean", "isBoolean", "(", "Exchange", "exchange", ",", "Message", "message", ",", "String", "name", ")", "{", "Boolean", "b", "=", "getBoolean", "(", "exchange", ",", "message", ",", "name", ")", ";", "return", "b", "!=", "null", "&&", "b", ".", "booleanValue", "(", ")", ";", "}" ]
Gets a primitive boolean context property. @param exchange the exchange @param message the message @param name the name @return the property
[ "Gets", "a", "primitive", "boolean", "context", "property", "." ]
train
https://github.com/jboss-integration/fuse-bxms-integ/blob/ca5c012bf867ea15d1250f0991af3cd7e708aaaf/switchyard/switchyard-component-common-knowledge/src/main/java/org/switchyard/component/common/knowledge/exchange/KnowledgeExchangeHandler.java#L175-L178
nohana/Amalgam
amalgam/src/main/java/com/amalgam/os/BundleUtils.java
BundleUtils.optString
@Nullable public static String optString(@Nullable Bundle bundle, @Nullable String key) { """ Returns a optional {@link java.lang.String} value. In other words, returns the value mapped by key if it exists and is a {@link java.lang.String}. The bundle argument is allowed to be {@code null}. If the bundle is null, this method returns null. @param bundle a bundle. If the bundle is null, this method will return null. @param key a key for the value. @return a {@link java.lang.String} value if exists, null otherwise. @see android.os.Bundle#getString(String) """ return optString(bundle, key, null); }
java
@Nullable public static String optString(@Nullable Bundle bundle, @Nullable String key) { return optString(bundle, key, null); }
[ "@", "Nullable", "public", "static", "String", "optString", "(", "@", "Nullable", "Bundle", "bundle", ",", "@", "Nullable", "String", "key", ")", "{", "return", "optString", "(", "bundle", ",", "key", ",", "null", ")", ";", "}" ]
Returns a optional {@link java.lang.String} value. In other words, returns the value mapped by key if it exists and is a {@link java.lang.String}. The bundle argument is allowed to be {@code null}. If the bundle is null, this method returns null. @param bundle a bundle. If the bundle is null, this method will return null. @param key a key for the value. @return a {@link java.lang.String} value if exists, null otherwise. @see android.os.Bundle#getString(String)
[ "Returns", "a", "optional", "{" ]
train
https://github.com/nohana/Amalgam/blob/57809ddbfe7897e979cf507982ce0b3aa5e0ed8a/amalgam/src/main/java/com/amalgam/os/BundleUtils.java#L965-L968
Stratio/bdt
src/main/java/com/stratio/qa/specs/DcosSpec.java
DcosSpec.checkServicesDistributionMultiDataCenterPram
@Given("^services '(.+?)' are splitted correctly in datacenters '(.+?)'$") public void checkServicesDistributionMultiDataCenterPram(String serviceList, String dataCentersIps) throws Exception { """ Check if all task of a service are correctly distributed in all datacenters of the cluster @param serviceList all task deployed in the cluster separated by a semicolumn. @param dataCentersIps all ips of the datacenters to be checked Example: ip_1_dc1, ip_2_dc1;ip_3_dc2,ip_4_dc2 @throws Exception """ checkDataCentersDistribution(serviceList.split(","), dataCentersIps.split(";")); }
java
@Given("^services '(.+?)' are splitted correctly in datacenters '(.+?)'$") public void checkServicesDistributionMultiDataCenterPram(String serviceList, String dataCentersIps) throws Exception { checkDataCentersDistribution(serviceList.split(","), dataCentersIps.split(";")); }
[ "@", "Given", "(", "\"^services '(.+?)' are splitted correctly in datacenters '(.+?)'$\"", ")", "public", "void", "checkServicesDistributionMultiDataCenterPram", "(", "String", "serviceList", ",", "String", "dataCentersIps", ")", "throws", "Exception", "{", "checkDataCentersDistribution", "(", "serviceList", ".", "split", "(", "\",\"", ")", ",", "dataCentersIps", ".", "split", "(", "\";\"", ")", ")", ";", "}" ]
Check if all task of a service are correctly distributed in all datacenters of the cluster @param serviceList all task deployed in the cluster separated by a semicolumn. @param dataCentersIps all ips of the datacenters to be checked Example: ip_1_dc1, ip_2_dc1;ip_3_dc2,ip_4_dc2 @throws Exception
[ "Check", "if", "all", "task", "of", "a", "service", "are", "correctly", "distributed", "in", "all", "datacenters", "of", "the", "cluster" ]
train
https://github.com/Stratio/bdt/blob/55324d19e7497764ad3dd7139923e13eb9841d75/src/main/java/com/stratio/qa/specs/DcosSpec.java#L170-L173
googleapis/google-cloud-java
google-cloud-clients/google-cloud-storage/src/main/java/com/google/cloud/storage/BlobInfo.java
BlobInfo.newBuilder
public static Builder newBuilder(String bucket, String name) { """ Returns a {@code BlobInfo} builder where blob identity is set using the provided values. """ return newBuilder(BlobId.of(bucket, name)); }
java
public static Builder newBuilder(String bucket, String name) { return newBuilder(BlobId.of(bucket, name)); }
[ "public", "static", "Builder", "newBuilder", "(", "String", "bucket", ",", "String", "name", ")", "{", "return", "newBuilder", "(", "BlobId", ".", "of", "(", "bucket", ",", "name", ")", ")", ";", "}" ]
Returns a {@code BlobInfo} builder where blob identity is set using the provided values.
[ "Returns", "a", "{" ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-storage/src/main/java/com/google/cloud/storage/BlobInfo.java#L1009-L1011
ZuInnoTe/hadoopoffice
fileformat/src/main/java/org/zuinnote/hadoop/office/format/common/util/msexcel/MSExcelUtil.java
MSExcelUtil.getCellAddressA1Format
public static String getCellAddressA1Format(int rowNum, int columnNum) { """ Generate a cell address in A1 format from a row and column number @param rowNum row number @param columnNum column number @return Address in A1 format """ CellAddress cellAddr = new CellAddress(rowNum, columnNum); return cellAddr.formatAsString(); }
java
public static String getCellAddressA1Format(int rowNum, int columnNum) { CellAddress cellAddr = new CellAddress(rowNum, columnNum); return cellAddr.formatAsString(); }
[ "public", "static", "String", "getCellAddressA1Format", "(", "int", "rowNum", ",", "int", "columnNum", ")", "{", "CellAddress", "cellAddr", "=", "new", "CellAddress", "(", "rowNum", ",", "columnNum", ")", ";", "return", "cellAddr", ".", "formatAsString", "(", ")", ";", "}" ]
Generate a cell address in A1 format from a row and column number @param rowNum row number @param columnNum column number @return Address in A1 format
[ "Generate", "a", "cell", "address", "in", "A1", "format", "from", "a", "row", "and", "column", "number" ]
train
https://github.com/ZuInnoTe/hadoopoffice/blob/58fc9223ee290bcb14847aaaff3fadf39c465e46/fileformat/src/main/java/org/zuinnote/hadoop/office/format/common/util/msexcel/MSExcelUtil.java#L36-L39
oehf/ipf-oht-atna
context/src/main/java/org/openhealthtools/ihe/atna/context/AbstractModuleConfig.java
AbstractModuleConfig.setOption
public synchronized void setOption(String key, String value) { """ Set a value to the backed properties in this module config. @param key The key of the property to set @param value The value of the property to set """ if (key == null || value == null) { return; } config.put(key, value); }
java
public synchronized void setOption(String key, String value) { if (key == null || value == null) { return; } config.put(key, value); }
[ "public", "synchronized", "void", "setOption", "(", "String", "key", ",", "String", "value", ")", "{", "if", "(", "key", "==", "null", "||", "value", "==", "null", ")", "{", "return", ";", "}", "config", ".", "put", "(", "key", ",", "value", ")", ";", "}" ]
Set a value to the backed properties in this module config. @param key The key of the property to set @param value The value of the property to set
[ "Set", "a", "value", "to", "the", "backed", "properties", "in", "this", "module", "config", "." ]
train
https://github.com/oehf/ipf-oht-atna/blob/25ed1e926825169c94923a2c89a4618f60478ae8/context/src/main/java/org/openhealthtools/ihe/atna/context/AbstractModuleConfig.java#L73-L79
kuali/ojb-1.0.4
src/java/org/apache/ojb/broker/accesslayer/StatementManager.java
StatementManager.bindValues
public int bindValues(PreparedStatement stmt, ValueContainer[] values, int index) throws SQLException { """ binds the given array of values (if not null) starting from the given parameter index @return the next parameter index """ if (values != null) { for (int i = 0; i < values.length; i++) { setObjectForStatement(stmt, index, values[i].getValue(), values[i].getJdbcType().getType()); index++; } } return index; }
java
public int bindValues(PreparedStatement stmt, ValueContainer[] values, int index) throws SQLException { if (values != null) { for (int i = 0; i < values.length; i++) { setObjectForStatement(stmt, index, values[i].getValue(), values[i].getJdbcType().getType()); index++; } } return index; }
[ "public", "int", "bindValues", "(", "PreparedStatement", "stmt", ",", "ValueContainer", "[", "]", "values", ",", "int", "index", ")", "throws", "SQLException", "{", "if", "(", "values", "!=", "null", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "values", ".", "length", ";", "i", "++", ")", "{", "setObjectForStatement", "(", "stmt", ",", "index", ",", "values", "[", "i", "]", ".", "getValue", "(", ")", ",", "values", "[", "i", "]", ".", "getJdbcType", "(", ")", ".", "getType", "(", ")", ")", ";", "index", "++", ";", "}", "}", "return", "index", ";", "}" ]
binds the given array of values (if not null) starting from the given parameter index @return the next parameter index
[ "binds", "the", "given", "array", "of", "values", "(", "if", "not", "null", ")", "starting", "from", "the", "given", "parameter", "index" ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/accesslayer/StatementManager.java#L533-L544
voldemort/voldemort
src/java/voldemort/store/StoreUtils.java
StoreUtils.assertValidNode
public static void assertValidNode(MetadataStore metadataStore, Integer nodeId) { """ Check if the the nodeId is present in the cluster managed by the metadata store or throw an exception. @param nodeId The nodeId to check existence of """ if(!metadataStore.getCluster().hasNodeWithId(nodeId)) { throw new InvalidMetadataException("NodeId " + nodeId + " is not or no longer in this cluster"); } }
java
public static void assertValidNode(MetadataStore metadataStore, Integer nodeId) { if(!metadataStore.getCluster().hasNodeWithId(nodeId)) { throw new InvalidMetadataException("NodeId " + nodeId + " is not or no longer in this cluster"); } }
[ "public", "static", "void", "assertValidNode", "(", "MetadataStore", "metadataStore", ",", "Integer", "nodeId", ")", "{", "if", "(", "!", "metadataStore", ".", "getCluster", "(", ")", ".", "hasNodeWithId", "(", "nodeId", ")", ")", "{", "throw", "new", "InvalidMetadataException", "(", "\"NodeId \"", "+", "nodeId", "+", "\" is not or no longer in this cluster\"", ")", ";", "}", "}" ]
Check if the the nodeId is present in the cluster managed by the metadata store or throw an exception. @param nodeId The nodeId to check existence of
[ "Check", "if", "the", "the", "nodeId", "is", "present", "in", "the", "cluster", "managed", "by", "the", "metadata", "store", "or", "throw", "an", "exception", "." ]
train
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/StoreUtils.java#L154-L158
jeremybrooks/jinx
src/main/java/net/jeremybrooks/jinx/api/PhotosApi.java
PhotosApi.setSafetyLevel
public Response setSafetyLevel(String photoId, JinxConstants.SafetyLevel safetyLevel, boolean hidden) throws JinxException { """ Set the safety level of a photo. <br> This method requires authentication with 'write' permission. @param photoId Required. The id of the photo to set the adultness of. @param safetyLevel Optional. Safely level of the photo. @param hidden Whether or not to additionally hide the photo from public searches. @return object with the result of the requested operation. @throws JinxException if required parameters are null or empty, or if there are errors. @see <a href="https://www.flickr.com/services/api/flickr.photos.setSafetyLevel.html">flickr.photos.setSafetyLevel</a> """ JinxUtils.validateParams(photoId); Map<String, String> params = new TreeMap<>(); params.put("method", "flickr.photos.setSafetyLevel"); params.put("photo_id", photoId); if (safetyLevel != null) { params.put("safety_level", Integer.toString(JinxUtils.safetyLevelToFlickrSafteyLevelId(safetyLevel))); } params.put("hidden", hidden ? "1" : "0"); return jinx.flickrPost(params, Response.class); }
java
public Response setSafetyLevel(String photoId, JinxConstants.SafetyLevel safetyLevel, boolean hidden) throws JinxException { JinxUtils.validateParams(photoId); Map<String, String> params = new TreeMap<>(); params.put("method", "flickr.photos.setSafetyLevel"); params.put("photo_id", photoId); if (safetyLevel != null) { params.put("safety_level", Integer.toString(JinxUtils.safetyLevelToFlickrSafteyLevelId(safetyLevel))); } params.put("hidden", hidden ? "1" : "0"); return jinx.flickrPost(params, Response.class); }
[ "public", "Response", "setSafetyLevel", "(", "String", "photoId", ",", "JinxConstants", ".", "SafetyLevel", "safetyLevel", ",", "boolean", "hidden", ")", "throws", "JinxException", "{", "JinxUtils", ".", "validateParams", "(", "photoId", ")", ";", "Map", "<", "String", ",", "String", ">", "params", "=", "new", "TreeMap", "<>", "(", ")", ";", "params", ".", "put", "(", "\"method\"", ",", "\"flickr.photos.setSafetyLevel\"", ")", ";", "params", ".", "put", "(", "\"photo_id\"", ",", "photoId", ")", ";", "if", "(", "safetyLevel", "!=", "null", ")", "{", "params", ".", "put", "(", "\"safety_level\"", ",", "Integer", ".", "toString", "(", "JinxUtils", ".", "safetyLevelToFlickrSafteyLevelId", "(", "safetyLevel", ")", ")", ")", ";", "}", "params", ".", "put", "(", "\"hidden\"", ",", "hidden", "?", "\"1\"", ":", "\"0\"", ")", ";", "return", "jinx", ".", "flickrPost", "(", "params", ",", "Response", ".", "class", ")", ";", "}" ]
Set the safety level of a photo. <br> This method requires authentication with 'write' permission. @param photoId Required. The id of the photo to set the adultness of. @param safetyLevel Optional. Safely level of the photo. @param hidden Whether or not to additionally hide the photo from public searches. @return object with the result of the requested operation. @throws JinxException if required parameters are null or empty, or if there are errors. @see <a href="https://www.flickr.com/services/api/flickr.photos.setSafetyLevel.html">flickr.photos.setSafetyLevel</a>
[ "Set", "the", "safety", "level", "of", "a", "photo", ".", "<br", ">", "This", "method", "requires", "authentication", "with", "write", "permission", "." ]
train
https://github.com/jeremybrooks/jinx/blob/ab7a4b7462d08bcbfd9b98bd3f5029771c20f6c6/src/main/java/net/jeremybrooks/jinx/api/PhotosApi.java#L1000-L1010
dlemmermann/CalendarFX
CalendarFXView/src/main/java/com/calendarfx/model/Entry.java
Entry.changeEndDate
public final void changeEndDate(LocalDate date, boolean keepDuration) { """ Changes the end date of the entry interval. @param date the new end date @param keepDuration if true then this method will also change the start date and time in such a way that the total duration of the entry will not change. If false then this method will ensure that the entry's interval stays valid, which means that the start time will be before the end time and that the duration of the entry will be at least the duration defined by the {@link #minimumDurationProperty()}. """ requireNonNull(date); Interval interval = getInterval(); LocalDateTime newEndDateTime = getEndAsLocalDateTime().with(date); LocalDateTime startDateTime = getStartAsLocalDateTime(); if (keepDuration) { startDateTime = newEndDateTime.minus(getDuration()); setInterval(startDateTime, newEndDateTime, getZoneId()); } else { /* * We might have a problem if the new end time is BEFORE the current start time. */ if (newEndDateTime.isBefore(startDateTime)) { interval = interval.withStartDateTime(newEndDateTime.minus(interval.getDuration())); } setInterval(interval.withEndDate(date)); } }
java
public final void changeEndDate(LocalDate date, boolean keepDuration) { requireNonNull(date); Interval interval = getInterval(); LocalDateTime newEndDateTime = getEndAsLocalDateTime().with(date); LocalDateTime startDateTime = getStartAsLocalDateTime(); if (keepDuration) { startDateTime = newEndDateTime.minus(getDuration()); setInterval(startDateTime, newEndDateTime, getZoneId()); } else { /* * We might have a problem if the new end time is BEFORE the current start time. */ if (newEndDateTime.isBefore(startDateTime)) { interval = interval.withStartDateTime(newEndDateTime.minus(interval.getDuration())); } setInterval(interval.withEndDate(date)); } }
[ "public", "final", "void", "changeEndDate", "(", "LocalDate", "date", ",", "boolean", "keepDuration", ")", "{", "requireNonNull", "(", "date", ")", ";", "Interval", "interval", "=", "getInterval", "(", ")", ";", "LocalDateTime", "newEndDateTime", "=", "getEndAsLocalDateTime", "(", ")", ".", "with", "(", "date", ")", ";", "LocalDateTime", "startDateTime", "=", "getStartAsLocalDateTime", "(", ")", ";", "if", "(", "keepDuration", ")", "{", "startDateTime", "=", "newEndDateTime", ".", "minus", "(", "getDuration", "(", ")", ")", ";", "setInterval", "(", "startDateTime", ",", "newEndDateTime", ",", "getZoneId", "(", ")", ")", ";", "}", "else", "{", "/*\n * We might have a problem if the new end time is BEFORE the current start time.\n */", "if", "(", "newEndDateTime", ".", "isBefore", "(", "startDateTime", ")", ")", "{", "interval", "=", "interval", ".", "withStartDateTime", "(", "newEndDateTime", ".", "minus", "(", "interval", ".", "getDuration", "(", ")", ")", ")", ";", "}", "setInterval", "(", "interval", ".", "withEndDate", "(", "date", ")", ")", ";", "}", "}" ]
Changes the end date of the entry interval. @param date the new end date @param keepDuration if true then this method will also change the start date and time in such a way that the total duration of the entry will not change. If false then this method will ensure that the entry's interval stays valid, which means that the start time will be before the end time and that the duration of the entry will be at least the duration defined by the {@link #minimumDurationProperty()}.
[ "Changes", "the", "end", "date", "of", "the", "entry", "interval", "." ]
train
https://github.com/dlemmermann/CalendarFX/blob/f2b91c2622c3f29d004485b6426b23b86c331f96/CalendarFXView/src/main/java/com/calendarfx/model/Entry.java#L484-L505
OpenLiberty/open-liberty
dev/com.ibm.ws.channel.ssl/src/com/ibm/ws/channel/ssl/internal/SSLChannelProvider.java
SSLChannelProvider.setSslSupport
protected void setSslSupport(SSLSupport service, Map<String, Object> props) { """ Required service: this is not dynamic, and so is called before activate @param ref reference to the service """ if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(tc, "setSslSupport", service); } sslSupport = service; defaultId = (String) props.get(SSL_CFG_REF); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.exit(tc, "setSslSupport", "defaultConfigId=" + defaultId); } }
java
protected void setSslSupport(SSLSupport service, Map<String, Object> props) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(tc, "setSslSupport", service); } sslSupport = service; defaultId = (String) props.get(SSL_CFG_REF); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.exit(tc, "setSslSupport", "defaultConfigId=" + defaultId); } }
[ "protected", "void", "setSslSupport", "(", "SSLSupport", "service", ",", "Map", "<", "String", ",", "Object", ">", "props", ")", "{", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEntryEnabled", "(", ")", ")", "{", "Tr", ".", "entry", "(", "tc", ",", "\"setSslSupport\"", ",", "service", ")", ";", "}", "sslSupport", "=", "service", ";", "defaultId", "=", "(", "String", ")", "props", ".", "get", "(", "SSL_CFG_REF", ")", ";", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEntryEnabled", "(", ")", ")", "{", "Tr", ".", "exit", "(", "tc", ",", "\"setSslSupport\"", ",", "\"defaultConfigId=\"", "+", "defaultId", ")", ";", "}", "}" ]
Required service: this is not dynamic, and so is called before activate @param ref reference to the service
[ "Required", "service", ":", "this", "is", "not", "dynamic", "and", "so", "is", "called", "before", "activate" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.channel.ssl/src/com/ibm/ws/channel/ssl/internal/SSLChannelProvider.java#L198-L209
kuali/ojb-1.0.4
src/java/org/apache/ojb/broker/core/PersistenceBrokerImpl.java
PersistenceBrokerImpl.getReportQueryIteratorByQuery
public Iterator getReportQueryIteratorByQuery(Query query) throws PersistenceBrokerException { """ Get an Iterator based on the ReportQuery @param query @return Iterator """ ClassDescriptor cld = getClassDescriptor(query.getSearchClass()); return getReportQueryIteratorFromQuery(query, cld); }
java
public Iterator getReportQueryIteratorByQuery(Query query) throws PersistenceBrokerException { ClassDescriptor cld = getClassDescriptor(query.getSearchClass()); return getReportQueryIteratorFromQuery(query, cld); }
[ "public", "Iterator", "getReportQueryIteratorByQuery", "(", "Query", "query", ")", "throws", "PersistenceBrokerException", "{", "ClassDescriptor", "cld", "=", "getClassDescriptor", "(", "query", ".", "getSearchClass", "(", ")", ")", ";", "return", "getReportQueryIteratorFromQuery", "(", "query", ",", "cld", ")", ";", "}" ]
Get an Iterator based on the ReportQuery @param query @return Iterator
[ "Get", "an", "Iterator", "based", "on", "the", "ReportQuery" ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/core/PersistenceBrokerImpl.java#L2084-L2088
cdk/cdk
legacy/src/main/java/org/openscience/cdk/ringsearch/FiguerasSSSRFinder.java
FiguerasSSSRFinder.prepareRing
private IRing prepareRing(List vec, IAtomContainer mol) { """ Returns the ring that is formed by the atoms in the given vector. @param vec The vector that contains the atoms of the ring @param mol The molecule this ring is a substructure of @return The ring formed by the given atoms """ // add the atoms in vec to the new ring int atomCount = vec.size(); IRing ring = mol.getBuilder().newInstance(IRing.class, atomCount); IAtom[] atoms = new IAtom[atomCount]; vec.toArray(atoms); ring.setAtoms(atoms); // add the bonds in mol to the new ring try { IBond b; for (int i = 0; i < atomCount - 1; i++) { b = mol.getBond(atoms[i], atoms[i + 1]); if (b != null) { ring.addBond(b); } else { logger.error("This should not happen."); } } b = mol.getBond(atoms[0], atoms[atomCount - 1]); if (b != null) { ring.addBond(b); } else { logger.error("This should not happen either."); } } catch (Exception exc) { logger.debug(exc); } logger.debug("found Ring ", ring); return ring; }
java
private IRing prepareRing(List vec, IAtomContainer mol) { // add the atoms in vec to the new ring int atomCount = vec.size(); IRing ring = mol.getBuilder().newInstance(IRing.class, atomCount); IAtom[] atoms = new IAtom[atomCount]; vec.toArray(atoms); ring.setAtoms(atoms); // add the bonds in mol to the new ring try { IBond b; for (int i = 0; i < atomCount - 1; i++) { b = mol.getBond(atoms[i], atoms[i + 1]); if (b != null) { ring.addBond(b); } else { logger.error("This should not happen."); } } b = mol.getBond(atoms[0], atoms[atomCount - 1]); if (b != null) { ring.addBond(b); } else { logger.error("This should not happen either."); } } catch (Exception exc) { logger.debug(exc); } logger.debug("found Ring ", ring); return ring; }
[ "private", "IRing", "prepareRing", "(", "List", "vec", ",", "IAtomContainer", "mol", ")", "{", "// add the atoms in vec to the new ring", "int", "atomCount", "=", "vec", ".", "size", "(", ")", ";", "IRing", "ring", "=", "mol", ".", "getBuilder", "(", ")", ".", "newInstance", "(", "IRing", ".", "class", ",", "atomCount", ")", ";", "IAtom", "[", "]", "atoms", "=", "new", "IAtom", "[", "atomCount", "]", ";", "vec", ".", "toArray", "(", "atoms", ")", ";", "ring", ".", "setAtoms", "(", "atoms", ")", ";", "// add the bonds in mol to the new ring", "try", "{", "IBond", "b", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "atomCount", "-", "1", ";", "i", "++", ")", "{", "b", "=", "mol", ".", "getBond", "(", "atoms", "[", "i", "]", ",", "atoms", "[", "i", "+", "1", "]", ")", ";", "if", "(", "b", "!=", "null", ")", "{", "ring", ".", "addBond", "(", "b", ")", ";", "}", "else", "{", "logger", ".", "error", "(", "\"This should not happen.\"", ")", ";", "}", "}", "b", "=", "mol", ".", "getBond", "(", "atoms", "[", "0", "]", ",", "atoms", "[", "atomCount", "-", "1", "]", ")", ";", "if", "(", "b", "!=", "null", ")", "{", "ring", ".", "addBond", "(", "b", ")", ";", "}", "else", "{", "logger", ".", "error", "(", "\"This should not happen either.\"", ")", ";", "}", "}", "catch", "(", "Exception", "exc", ")", "{", "logger", ".", "debug", "(", "exc", ")", ";", "}", "logger", ".", "debug", "(", "\"found Ring \"", ",", "ring", ")", ";", "return", "ring", ";", "}" ]
Returns the ring that is formed by the atoms in the given vector. @param vec The vector that contains the atoms of the ring @param mol The molecule this ring is a substructure of @return The ring formed by the given atoms
[ "Returns", "the", "ring", "that", "is", "formed", "by", "the", "atoms", "in", "the", "given", "vector", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/legacy/src/main/java/org/openscience/cdk/ringsearch/FiguerasSSSRFinder.java#L258-L287
BBN-E/bue-common-open
common-core-open/src/main/java/com/bbn/bue/common/CodepointMatcher.java
CodepointMatcher.collapseFrom
public final String collapseFrom(String s, char replacementCharacter) { """ Returns a copy of the input string with all groups of 1 or more successive matching characters are replaced with {@code replacementCharacter}. """ final StringBuilder sb = new StringBuilder(); boolean follows = false; for (int offset = 0; offset < s.length(); ) { final int codePoint = s.codePointAt(offset); if (matches(codePoint)) { if (!follows) { sb.append(replacementCharacter); } follows = true; } else { sb.appendCodePoint(codePoint); follows = false; } offset += Character.charCount(codePoint); } return sb.toString(); }
java
public final String collapseFrom(String s, char replacementCharacter) { final StringBuilder sb = new StringBuilder(); boolean follows = false; for (int offset = 0; offset < s.length(); ) { final int codePoint = s.codePointAt(offset); if (matches(codePoint)) { if (!follows) { sb.append(replacementCharacter); } follows = true; } else { sb.appendCodePoint(codePoint); follows = false; } offset += Character.charCount(codePoint); } return sb.toString(); }
[ "public", "final", "String", "collapseFrom", "(", "String", "s", ",", "char", "replacementCharacter", ")", "{", "final", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "boolean", "follows", "=", "false", ";", "for", "(", "int", "offset", "=", "0", ";", "offset", "<", "s", ".", "length", "(", ")", ";", ")", "{", "final", "int", "codePoint", "=", "s", ".", "codePointAt", "(", "offset", ")", ";", "if", "(", "matches", "(", "codePoint", ")", ")", "{", "if", "(", "!", "follows", ")", "{", "sb", ".", "append", "(", "replacementCharacter", ")", ";", "}", "follows", "=", "true", ";", "}", "else", "{", "sb", ".", "appendCodePoint", "(", "codePoint", ")", ";", "follows", "=", "false", ";", "}", "offset", "+=", "Character", ".", "charCount", "(", "codePoint", ")", ";", "}", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
Returns a copy of the input string with all groups of 1 or more successive matching characters are replaced with {@code replacementCharacter}.
[ "Returns", "a", "copy", "of", "the", "input", "string", "with", "all", "groups", "of", "1", "or", "more", "successive", "matching", "characters", "are", "replaced", "with", "{" ]
train
https://github.com/BBN-E/bue-common-open/blob/d618652674d647867306e2e4b987a21b7c29c015/common-core-open/src/main/java/com/bbn/bue/common/CodepointMatcher.java#L345-L364
OpenLiberty/open-liberty
dev/com.ibm.ws.security.wim.core/src/com/ibm/ws/security/wim/adapter/urbridge/utils/URBridgeEntityFactory.java
URBridgeEntityFactory.createObject
public URBridgeEntity createObject(Entity entity, URBridge urBridge, Map<String, String> attrMap, String baseEntryName, Map<String, String> entityConfigMap) throws WIMException { """ Create a URBridgeEntity from input parameters. With inheritance this allows Users and Groups to be treated identically. @param entity The entity to be wrapped by the URBridgeEntity. This entity's type determines which type of OSEntityObject is created. @param urBridge The UserRegisty associated with the adapter. @param attrMap An attribute map containing the configuration information on how underlying UR attributes map to WIM attributes. @param baseEntryName The name of the baseEntry @return a URBridgeEntity that can be used to get and set properties of the entity. @throws WIMException The entity type passed in of not of type 'Person' or of type 'Group'. """ String entityType = entity.getTypeName(); URBridgeEntity obj = null; if (Service.DO_GROUP.equals(entityType) || Entity.getSubEntityTypes(Service.DO_GROUP).contains(entityType)) { obj = new URBridgeGroup(entity, urBridge, attrMap, baseEntryName, entityConfigMap); } else if (Service.DO_LOGIN_ACCOUNT.equals(entityType) || Entity.getSubEntityTypes(Service.DO_LOGIN_ACCOUNT).contains(entityType)) { obj = new URBridgePerson(entity, urBridge, attrMap, baseEntryName, entityConfigMap); } else { throw new WIMApplicationException(WIMMessageKey.ENTITY_TYPE_NOT_SUPPORTED, Tr.formatMessage(tc, WIMMessageKey.ENTITY_TYPE_NOT_SUPPORTED, WIMMessageHelper.generateMsgParms(entityType))); } return obj; }
java
public URBridgeEntity createObject(Entity entity, URBridge urBridge, Map<String, String> attrMap, String baseEntryName, Map<String, String> entityConfigMap) throws WIMException { String entityType = entity.getTypeName(); URBridgeEntity obj = null; if (Service.DO_GROUP.equals(entityType) || Entity.getSubEntityTypes(Service.DO_GROUP).contains(entityType)) { obj = new URBridgeGroup(entity, urBridge, attrMap, baseEntryName, entityConfigMap); } else if (Service.DO_LOGIN_ACCOUNT.equals(entityType) || Entity.getSubEntityTypes(Service.DO_LOGIN_ACCOUNT).contains(entityType)) { obj = new URBridgePerson(entity, urBridge, attrMap, baseEntryName, entityConfigMap); } else { throw new WIMApplicationException(WIMMessageKey.ENTITY_TYPE_NOT_SUPPORTED, Tr.formatMessage(tc, WIMMessageKey.ENTITY_TYPE_NOT_SUPPORTED, WIMMessageHelper.generateMsgParms(entityType))); } return obj; }
[ "public", "URBridgeEntity", "createObject", "(", "Entity", "entity", ",", "URBridge", "urBridge", ",", "Map", "<", "String", ",", "String", ">", "attrMap", ",", "String", "baseEntryName", ",", "Map", "<", "String", ",", "String", ">", "entityConfigMap", ")", "throws", "WIMException", "{", "String", "entityType", "=", "entity", ".", "getTypeName", "(", ")", ";", "URBridgeEntity", "obj", "=", "null", ";", "if", "(", "Service", ".", "DO_GROUP", ".", "equals", "(", "entityType", ")", "||", "Entity", ".", "getSubEntityTypes", "(", "Service", ".", "DO_GROUP", ")", ".", "contains", "(", "entityType", ")", ")", "{", "obj", "=", "new", "URBridgeGroup", "(", "entity", ",", "urBridge", ",", "attrMap", ",", "baseEntryName", ",", "entityConfigMap", ")", ";", "}", "else", "if", "(", "Service", ".", "DO_LOGIN_ACCOUNT", ".", "equals", "(", "entityType", ")", "||", "Entity", ".", "getSubEntityTypes", "(", "Service", ".", "DO_LOGIN_ACCOUNT", ")", ".", "contains", "(", "entityType", ")", ")", "{", "obj", "=", "new", "URBridgePerson", "(", "entity", ",", "urBridge", ",", "attrMap", ",", "baseEntryName", ",", "entityConfigMap", ")", ";", "}", "else", "{", "throw", "new", "WIMApplicationException", "(", "WIMMessageKey", ".", "ENTITY_TYPE_NOT_SUPPORTED", ",", "Tr", ".", "formatMessage", "(", "tc", ",", "WIMMessageKey", ".", "ENTITY_TYPE_NOT_SUPPORTED", ",", "WIMMessageHelper", ".", "generateMsgParms", "(", "entityType", ")", ")", ")", ";", "}", "return", "obj", ";", "}" ]
Create a URBridgeEntity from input parameters. With inheritance this allows Users and Groups to be treated identically. @param entity The entity to be wrapped by the URBridgeEntity. This entity's type determines which type of OSEntityObject is created. @param urBridge The UserRegisty associated with the adapter. @param attrMap An attribute map containing the configuration information on how underlying UR attributes map to WIM attributes. @param baseEntryName The name of the baseEntry @return a URBridgeEntity that can be used to get and set properties of the entity. @throws WIMException The entity type passed in of not of type 'Person' or of type 'Group'.
[ "Create", "a", "URBridgeEntity", "from", "input", "parameters", ".", "With", "inheritance", "this", "allows", "Users", "and", "Groups", "to", "be", "treated", "identically", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.wim.core/src/com/ibm/ws/security/wim/adapter/urbridge/utils/URBridgeEntityFactory.java#L56-L72
softindex/datakernel
core-bytebuf/src/main/java/io/datakernel/bytebuf/ByteBufQueue.java
ByteBufQueue.drainTo
public int drainTo(@NotNull ByteBufQueue dest, int maxSize) { """ Adds to ByteBufQueue {@code dest} {@code maxSize} bytes from this queue. If this queue doesn't contain enough bytes, adds all bytes from this queue. @param dest {@code ByteBufQueue} for draining @param maxSize number of bytes for adding @return number of added elements """ int s = maxSize; while (s != 0 && hasRemaining()) { ByteBuf buf = takeAtMost(s); dest.add(buf); s -= buf.readRemaining(); } return maxSize - s; }
java
public int drainTo(@NotNull ByteBufQueue dest, int maxSize) { int s = maxSize; while (s != 0 && hasRemaining()) { ByteBuf buf = takeAtMost(s); dest.add(buf); s -= buf.readRemaining(); } return maxSize - s; }
[ "public", "int", "drainTo", "(", "@", "NotNull", "ByteBufQueue", "dest", ",", "int", "maxSize", ")", "{", "int", "s", "=", "maxSize", ";", "while", "(", "s", "!=", "0", "&&", "hasRemaining", "(", ")", ")", "{", "ByteBuf", "buf", "=", "takeAtMost", "(", "s", ")", ";", "dest", ".", "add", "(", "buf", ")", ";", "s", "-=", "buf", ".", "readRemaining", "(", ")", ";", "}", "return", "maxSize", "-", "s", ";", "}" ]
Adds to ByteBufQueue {@code dest} {@code maxSize} bytes from this queue. If this queue doesn't contain enough bytes, adds all bytes from this queue. @param dest {@code ByteBufQueue} for draining @param maxSize number of bytes for adding @return number of added elements
[ "Adds", "to", "ByteBufQueue", "{", "@code", "dest", "}", "{", "@code", "maxSize", "}", "bytes", "from", "this", "queue", ".", "If", "this", "queue", "doesn", "t", "contain", "enough", "bytes", "adds", "all", "bytes", "from", "this", "queue", "." ]
train
https://github.com/softindex/datakernel/blob/090ca1116416c14d463d49d275cb1daaafa69c56/core-bytebuf/src/main/java/io/datakernel/bytebuf/ByteBufQueue.java#L623-L631
fhoeben/hsac-fitnesse-fixtures
src/main/java/nl/hsac/fitnesse/fixture/util/FirstNonNullHelper.java
FirstNonNullHelper.firstNonNull
public static <T, R> R firstNonNull(Function<T, R> function, Collection<T> values) { """ Gets first result of function which is not null. @param <T> type of values. @param <R> element to return. @param function function to apply to each value. @param values all possible values to apply function to. @return first result which was not null, OR <code>null</code> if either result for all values was <code>null</code> or values was <code>null</code>. """ return values == null ? null : firstNonNull(function, values.stream()); }
java
public static <T, R> R firstNonNull(Function<T, R> function, Collection<T> values) { return values == null ? null : firstNonNull(function, values.stream()); }
[ "public", "static", "<", "T", ",", "R", ">", "R", "firstNonNull", "(", "Function", "<", "T", ",", "R", ">", "function", ",", "Collection", "<", "T", ">", "values", ")", "{", "return", "values", "==", "null", "?", "null", ":", "firstNonNull", "(", "function", ",", "values", ".", "stream", "(", ")", ")", ";", "}" ]
Gets first result of function which is not null. @param <T> type of values. @param <R> element to return. @param function function to apply to each value. @param values all possible values to apply function to. @return first result which was not null, OR <code>null</code> if either result for all values was <code>null</code> or values was <code>null</code>.
[ "Gets", "first", "result", "of", "function", "which", "is", "not", "null", "." ]
train
https://github.com/fhoeben/hsac-fitnesse-fixtures/blob/4e9018d7386a9aa65bfcbf07eb28ae064edd1732/src/main/java/nl/hsac/fitnesse/fixture/util/FirstNonNullHelper.java#L50-L52
wmdietl/jsr308-langtools
src/share/classes/javax/lang/model/util/SimpleTypeVisitor8.java
SimpleTypeVisitor8.visitIntersection
@Override public R visitIntersection(IntersectionType t, P p) { """ This implementation visits an {@code IntersectionType} by calling {@code defaultAction}. @param t {@inheritDoc} @param p {@inheritDoc} @return the result of {@code defaultAction} """ return defaultAction(t, p); }
java
@Override public R visitIntersection(IntersectionType t, P p){ return defaultAction(t, p); }
[ "@", "Override", "public", "R", "visitIntersection", "(", "IntersectionType", "t", ",", "P", "p", ")", "{", "return", "defaultAction", "(", "t", ",", "p", ")", ";", "}" ]
This implementation visits an {@code IntersectionType} by calling {@code defaultAction}. @param t {@inheritDoc} @param p {@inheritDoc} @return the result of {@code defaultAction}
[ "This", "implementation", "visits", "an", "{", "@code", "IntersectionType", "}", "by", "calling", "{", "@code", "defaultAction", "}", "." ]
train
https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/javax/lang/model/util/SimpleTypeVisitor8.java#L111-L114
albfernandez/itext2
src/main/java/com/lowagie/text/pdf/PdfPatternPainter.java
PdfPatternPainter.setPatternMatrix
public void setPatternMatrix(float a, float b, float c, float d, float e, float f) { """ Sets the transformation matrix for the pattern. @param a @param b @param c @param d @param e @param f """ setMatrix(a, b, c, d, e, f); }
java
public void setPatternMatrix(float a, float b, float c, float d, float e, float f) { setMatrix(a, b, c, d, e, f); }
[ "public", "void", "setPatternMatrix", "(", "float", "a", ",", "float", "b", ",", "float", "c", ",", "float", "d", ",", "float", "e", ",", "float", "f", ")", "{", "setMatrix", "(", "a", ",", "b", ",", "c", ",", "d", ",", "e", ",", "f", ")", ";", "}" ]
Sets the transformation matrix for the pattern. @param a @param b @param c @param d @param e @param f
[ "Sets", "the", "transformation", "matrix", "for", "the", "pattern", "." ]
train
https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/PdfPatternPainter.java#L147-L149
sarl/sarl
main/coreplugins/io.sarl.lang/src/io/sarl/lang/jvmmodel/SARLJvmModelInferrer.java
SARLJvmModelInferrer.addAnnotationSafe
private JvmAnnotationReference addAnnotationSafe(JvmAnnotationTarget target, Class<?> annotationType, String... values) { """ Add annotation safely. <p>This function creates an annotation reference. If the type for the annotation is not found; no annotation is added. @param target the receiver of the annotation. @param annotationType the type of the annotation. @param values the annotations values. @return the annotation reference or <code>null</code> if the annotation cannot be added. """ assert target != null; assert annotationType != null; try { final JvmAnnotationReference annotationRef = this._annotationTypesBuilder.annotationRef(annotationType, values); if (annotationRef != null) { if (target.getAnnotations().add(annotationRef)) { return annotationRef; } } } catch (IllegalArgumentException exception) { // Ignore } return null; }
java
private JvmAnnotationReference addAnnotationSafe(JvmAnnotationTarget target, Class<?> annotationType, String... values) { assert target != null; assert annotationType != null; try { final JvmAnnotationReference annotationRef = this._annotationTypesBuilder.annotationRef(annotationType, values); if (annotationRef != null) { if (target.getAnnotations().add(annotationRef)) { return annotationRef; } } } catch (IllegalArgumentException exception) { // Ignore } return null; }
[ "private", "JvmAnnotationReference", "addAnnotationSafe", "(", "JvmAnnotationTarget", "target", ",", "Class", "<", "?", ">", "annotationType", ",", "String", "...", "values", ")", "{", "assert", "target", "!=", "null", ";", "assert", "annotationType", "!=", "null", ";", "try", "{", "final", "JvmAnnotationReference", "annotationRef", "=", "this", ".", "_annotationTypesBuilder", ".", "annotationRef", "(", "annotationType", ",", "values", ")", ";", "if", "(", "annotationRef", "!=", "null", ")", "{", "if", "(", "target", ".", "getAnnotations", "(", ")", ".", "add", "(", "annotationRef", ")", ")", "{", "return", "annotationRef", ";", "}", "}", "}", "catch", "(", "IllegalArgumentException", "exception", ")", "{", "// Ignore", "}", "return", "null", ";", "}" ]
Add annotation safely. <p>This function creates an annotation reference. If the type for the annotation is not found; no annotation is added. @param target the receiver of the annotation. @param annotationType the type of the annotation. @param values the annotations values. @return the annotation reference or <code>null</code> if the annotation cannot be added.
[ "Add", "annotation", "safely", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.lang/src/io/sarl/lang/jvmmodel/SARLJvmModelInferrer.java#L377-L391
Drivemode/TypefaceHelper
TypefaceHelper/src/main/java/com/drivemode/android/typeface/TypefaceHelper.java
TypefaceHelper.supportSetTypeface
public <F extends android.support.v4.app.Fragment> void supportSetTypeface(F fragment, @StringRes int strResId, int style) { """ Set the typeface to the all text views belong to the fragment. Make sure to call this method after fragment view creation. And this is a support package fragments only. @param fragment the fragment. @param strResId string resource containing typeface name. @param style the typeface style. """ supportSetTypeface(fragment, mApplication.getString(strResId), style); }
java
public <F extends android.support.v4.app.Fragment> void supportSetTypeface(F fragment, @StringRes int strResId, int style) { supportSetTypeface(fragment, mApplication.getString(strResId), style); }
[ "public", "<", "F", "extends", "android", ".", "support", ".", "v4", ".", "app", ".", "Fragment", ">", "void", "supportSetTypeface", "(", "F", "fragment", ",", "@", "StringRes", "int", "strResId", ",", "int", "style", ")", "{", "supportSetTypeface", "(", "fragment", ",", "mApplication", ".", "getString", "(", "strResId", ")", ",", "style", ")", ";", "}" ]
Set the typeface to the all text views belong to the fragment. Make sure to call this method after fragment view creation. And this is a support package fragments only. @param fragment the fragment. @param strResId string resource containing typeface name. @param style the typeface style.
[ "Set", "the", "typeface", "to", "the", "all", "text", "views", "belong", "to", "the", "fragment", ".", "Make", "sure", "to", "call", "this", "method", "after", "fragment", "view", "creation", ".", "And", "this", "is", "a", "support", "package", "fragments", "only", "." ]
train
https://github.com/Drivemode/TypefaceHelper/blob/86bef9ce16b9626b7076559e846db1b9f043c008/TypefaceHelper/src/main/java/com/drivemode/android/typeface/TypefaceHelper.java#L457-L459
pressgang-ccms/PressGangCCMSBuilder
src/main/java/org/jboss/pressgang/ccms/contentspec/builder/structures/BuildDatabase.java
BuildDatabase.getIdAttributes
public Set<String> getIdAttributes(final BuildData buildData) { """ Get a list of all the ID Attributes of all the topics and levels held in the database. @param buildData @return A List of IDs that exist for levels and topics in the database. """ final Set<String> ids = new HashSet<String>(); // Add all the level id attributes for (final Level level : levels) { ids.add(level.getUniqueLinkId(buildData.isUseFixedUrls())); } // Add all the topic id attributes for (final Entry<Integer, List<ITopicNode>> topicEntry : topics.entrySet()) { final List<ITopicNode> topics = topicEntry.getValue(); for (final ITopicNode topic : topics) { if (topic instanceof SpecTopic) { final SpecTopic specTopic = (SpecTopic) topic; ids.add(specTopic.getUniqueLinkId(buildData.isUseFixedUrls())); } } } return ids; }
java
public Set<String> getIdAttributes(final BuildData buildData) { final Set<String> ids = new HashSet<String>(); // Add all the level id attributes for (final Level level : levels) { ids.add(level.getUniqueLinkId(buildData.isUseFixedUrls())); } // Add all the topic id attributes for (final Entry<Integer, List<ITopicNode>> topicEntry : topics.entrySet()) { final List<ITopicNode> topics = topicEntry.getValue(); for (final ITopicNode topic : topics) { if (topic instanceof SpecTopic) { final SpecTopic specTopic = (SpecTopic) topic; ids.add(specTopic.getUniqueLinkId(buildData.isUseFixedUrls())); } } } return ids; }
[ "public", "Set", "<", "String", ">", "getIdAttributes", "(", "final", "BuildData", "buildData", ")", "{", "final", "Set", "<", "String", ">", "ids", "=", "new", "HashSet", "<", "String", ">", "(", ")", ";", "// Add all the level id attributes", "for", "(", "final", "Level", "level", ":", "levels", ")", "{", "ids", ".", "add", "(", "level", ".", "getUniqueLinkId", "(", "buildData", ".", "isUseFixedUrls", "(", ")", ")", ")", ";", "}", "// Add all the topic id attributes", "for", "(", "final", "Entry", "<", "Integer", ",", "List", "<", "ITopicNode", ">", ">", "topicEntry", ":", "topics", ".", "entrySet", "(", ")", ")", "{", "final", "List", "<", "ITopicNode", ">", "topics", "=", "topicEntry", ".", "getValue", "(", ")", ";", "for", "(", "final", "ITopicNode", "topic", ":", "topics", ")", "{", "if", "(", "topic", "instanceof", "SpecTopic", ")", "{", "final", "SpecTopic", "specTopic", "=", "(", "SpecTopic", ")", "topic", ";", "ids", ".", "add", "(", "specTopic", ".", "getUniqueLinkId", "(", "buildData", ".", "isUseFixedUrls", "(", ")", ")", ")", ";", "}", "}", "}", "return", "ids", ";", "}" ]
Get a list of all the ID Attributes of all the topics and levels held in the database. @param buildData @return A List of IDs that exist for levels and topics in the database.
[ "Get", "a", "list", "of", "all", "the", "ID", "Attributes", "of", "all", "the", "topics", "and", "levels", "held", "in", "the", "database", "." ]
train
https://github.com/pressgang-ccms/PressGangCCMSBuilder/blob/5436d36ba1b3c5baa246b270e5fc350e6778bce8/src/main/java/org/jboss/pressgang/ccms/contentspec/builder/structures/BuildDatabase.java#L210-L230
grpc/grpc-java
netty/src/main/java/io/grpc/netty/GrpcSslContexts.java
GrpcSslContexts.forServer
public static SslContextBuilder forServer(InputStream keyCertChain, InputStream key) { """ Creates a SslContextBuilder with ciphers and APN appropriate for gRPC. @see SslContextBuilder#forServer(InputStream, InputStream) @see #configure(SslContextBuilder) """ return configure(SslContextBuilder.forServer(keyCertChain, key)); }
java
public static SslContextBuilder forServer(InputStream keyCertChain, InputStream key) { return configure(SslContextBuilder.forServer(keyCertChain, key)); }
[ "public", "static", "SslContextBuilder", "forServer", "(", "InputStream", "keyCertChain", ",", "InputStream", "key", ")", "{", "return", "configure", "(", "SslContextBuilder", ".", "forServer", "(", "keyCertChain", ",", "key", ")", ")", ";", "}" ]
Creates a SslContextBuilder with ciphers and APN appropriate for gRPC. @see SslContextBuilder#forServer(InputStream, InputStream) @see #configure(SslContextBuilder)
[ "Creates", "a", "SslContextBuilder", "with", "ciphers", "and", "APN", "appropriate", "for", "gRPC", "." ]
train
https://github.com/grpc/grpc-java/blob/973885457f9609de232d2553b82c67f6c3ff57bf/netty/src/main/java/io/grpc/netty/GrpcSslContexts.java#L150-L152
groovy/groovy-core
src/main/org/codehaus/groovy/ast/ASTNode.java
ASTNode.putNodeMetaData
public Object putNodeMetaData(Object key, Object value) { """ Sets the node meta data but allows overwriting values. @param key - the meta data key @param value - the meta data value @return the old node meta data value for this key @throws GroovyBugError if key is null """ if (key == null) throw new GroovyBugError("Tried to set meta data with null key on " + this + "."); if (metaDataMap == null) { metaDataMap = new ListHashMap(); } return metaDataMap.put(key, value); }
java
public Object putNodeMetaData(Object key, Object value) { if (key == null) throw new GroovyBugError("Tried to set meta data with null key on " + this + "."); if (metaDataMap == null) { metaDataMap = new ListHashMap(); } return metaDataMap.put(key, value); }
[ "public", "Object", "putNodeMetaData", "(", "Object", "key", ",", "Object", "value", ")", "{", "if", "(", "key", "==", "null", ")", "throw", "new", "GroovyBugError", "(", "\"Tried to set meta data with null key on \"", "+", "this", "+", "\".\"", ")", ";", "if", "(", "metaDataMap", "==", "null", ")", "{", "metaDataMap", "=", "new", "ListHashMap", "(", ")", ";", "}", "return", "metaDataMap", ".", "put", "(", "key", ",", "value", ")", ";", "}" ]
Sets the node meta data but allows overwriting values. @param key - the meta data key @param value - the meta data value @return the old node meta data value for this key @throws GroovyBugError if key is null
[ "Sets", "the", "node", "meta", "data", "but", "allows", "overwriting", "values", "." ]
train
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/ast/ASTNode.java#L165-L171
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/lang/CharSequences.java
CharSequences.indexOf
@Deprecated public static int indexOf(CharSequence s, int codePoint) { """ Find code point in string. @deprecated This API is ICU internal only. @hide draft / provisional / internal are hidden on Android """ int cp; for (int i = 0; i < s.length(); i += Character.charCount(cp)) { cp = Character.codePointAt(s, i); if (cp == codePoint) { return i; } } return -1; }
java
@Deprecated public static int indexOf(CharSequence s, int codePoint) { int cp; for (int i = 0; i < s.length(); i += Character.charCount(cp)) { cp = Character.codePointAt(s, i); if (cp == codePoint) { return i; } } return -1; }
[ "@", "Deprecated", "public", "static", "int", "indexOf", "(", "CharSequence", "s", ",", "int", "codePoint", ")", "{", "int", "cp", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "s", ".", "length", "(", ")", ";", "i", "+=", "Character", ".", "charCount", "(", "cp", ")", ")", "{", "cp", "=", "Character", ".", "codePointAt", "(", "s", ",", "i", ")", ";", "if", "(", "cp", "==", "codePoint", ")", "{", "return", "i", ";", "}", "}", "return", "-", "1", ";", "}" ]
Find code point in string. @deprecated This API is ICU internal only. @hide draft / provisional / internal are hidden on Android
[ "Find", "code", "point", "in", "string", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/lang/CharSequences.java#L265-L275
SUSE/salt-netapi-client
src/main/java/com/suse/salt/netapi/event/WebSocketEventStream.java
WebSocketEventStream.onOpen
@OnOpen public void onOpen(Session session, EndpointConfig config) throws IOException { """ On handshake completed, get the WebSocket Session and send a message to ServerEndpoint that WebSocket is ready. http://docs.saltstack.com/en/latest/ref/netapi/all/salt.netapi.rest_cherrypy.html#ws @param session The just started WebSocket {@link Session}. @param config The {@link EndpointConfig} containing the handshake informations. @throws IOException if something goes wrong sending message to the remote peer """ this.session = session; session.getBasicRemote().sendText("websocket client ready"); }
java
@OnOpen public void onOpen(Session session, EndpointConfig config) throws IOException { this.session = session; session.getBasicRemote().sendText("websocket client ready"); }
[ "@", "OnOpen", "public", "void", "onOpen", "(", "Session", "session", ",", "EndpointConfig", "config", ")", "throws", "IOException", "{", "this", ".", "session", "=", "session", ";", "session", ".", "getBasicRemote", "(", ")", ".", "sendText", "(", "\"websocket client ready\"", ")", ";", "}" ]
On handshake completed, get the WebSocket Session and send a message to ServerEndpoint that WebSocket is ready. http://docs.saltstack.com/en/latest/ref/netapi/all/salt.netapi.rest_cherrypy.html#ws @param session The just started WebSocket {@link Session}. @param config The {@link EndpointConfig} containing the handshake informations. @throws IOException if something goes wrong sending message to the remote peer
[ "On", "handshake", "completed", "get", "the", "WebSocket", "Session", "and", "send", "a", "message", "to", "ServerEndpoint", "that", "WebSocket", "is", "ready", ".", "http", ":", "//", "docs", ".", "saltstack", ".", "com", "/", "en", "/", "latest", "/", "ref", "/", "netapi", "/", "all", "/", "salt", ".", "netapi", ".", "rest_cherrypy", ".", "html#ws" ]
train
https://github.com/SUSE/salt-netapi-client/blob/a0bdf643c8e34fa4def4b915366594c1491fdad5/src/main/java/com/suse/salt/netapi/event/WebSocketEventStream.java#L144-L148
google/error-prone-javac
src/jdk.compiler/share/classes/com/sun/tools/javac/comp/LambdaToMethod.java
LambdaToMethod.makeSyntheticVar
private VarSymbol makeSyntheticVar(long flags, String name, Type type, Symbol owner) { """ Create new synthetic variable with given flags, name, type, owner """ return makeSyntheticVar(flags, names.fromString(name), type, owner); }
java
private VarSymbol makeSyntheticVar(long flags, String name, Type type, Symbol owner) { return makeSyntheticVar(flags, names.fromString(name), type, owner); }
[ "private", "VarSymbol", "makeSyntheticVar", "(", "long", "flags", ",", "String", "name", ",", "Type", "type", ",", "Symbol", "owner", ")", "{", "return", "makeSyntheticVar", "(", "flags", ",", "names", ".", "fromString", "(", "name", ")", ",", "type", ",", "owner", ")", ";", "}" ]
Create new synthetic variable with given flags, name, type, owner
[ "Create", "new", "synthetic", "variable", "with", "given", "flags", "name", "type", "owner" ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/LambdaToMethod.java#L775-L777
westnordost/osmapi
src/main/java/de/westnordost/osmapi/traces/GpsTracesDao.java
GpsTracesDao.update
public void update( long id, GpsTraceDetails.Visibility visibility, String description, List<String> tags) { """ Change the visibility, description and tags of a GPS trace. description and tags may be null if there should be none. @throws OsmNotFoundException if the trace with the given id does not exist @throws OsmAuthorizationException if this application is not authorized to write traces (Permission.WRITE_GPS_TRACES) OR if the trace in question is not the user's own trace @throws IllegalArgumentException if the length of the description or any one single tag is more than 256 characters """ checkFieldLength("Description", description); checkTagsLength(tags); GpsTraceWriter writer = new GpsTraceWriter(id, visibility, description, tags); osm.makeAuthenticatedRequest(GPX + "/" + id, "PUT", writer); }
java
public void update( long id, GpsTraceDetails.Visibility visibility, String description, List<String> tags) { checkFieldLength("Description", description); checkTagsLength(tags); GpsTraceWriter writer = new GpsTraceWriter(id, visibility, description, tags); osm.makeAuthenticatedRequest(GPX + "/" + id, "PUT", writer); }
[ "public", "void", "update", "(", "long", "id", ",", "GpsTraceDetails", ".", "Visibility", "visibility", ",", "String", "description", ",", "List", "<", "String", ">", "tags", ")", "{", "checkFieldLength", "(", "\"Description\"", ",", "description", ")", ";", "checkTagsLength", "(", "tags", ")", ";", "GpsTraceWriter", "writer", "=", "new", "GpsTraceWriter", "(", "id", ",", "visibility", ",", "description", ",", "tags", ")", ";", "osm", ".", "makeAuthenticatedRequest", "(", "GPX", "+", "\"/\"", "+", "id", ",", "\"PUT\"", ",", "writer", ")", ";", "}" ]
Change the visibility, description and tags of a GPS trace. description and tags may be null if there should be none. @throws OsmNotFoundException if the trace with the given id does not exist @throws OsmAuthorizationException if this application is not authorized to write traces (Permission.WRITE_GPS_TRACES) OR if the trace in question is not the user's own trace @throws IllegalArgumentException if the length of the description or any one single tag is more than 256 characters
[ "Change", "the", "visibility", "description", "and", "tags", "of", "a", "GPS", "trace", ".", "description", "and", "tags", "may", "be", "null", "if", "there", "should", "be", "none", "." ]
train
https://github.com/westnordost/osmapi/blob/dda6978fd12e117d0cf17812bc22037f61e22c4b/src/main/java/de/westnordost/osmapi/traces/GpsTracesDao.java#L131-L140
undertow-io/undertow
core/src/main/java/io/undertow/util/FileUtils.java
FileUtils.readFile
public static String readFile(InputStream file) { """ Reads the {@link InputStream file} and converting it to {@link String} using UTF-8 encoding. """ try (BufferedInputStream stream = new BufferedInputStream(file)) { byte[] buff = new byte[1024]; StringBuilder builder = new StringBuilder(); int read; while ((read = stream.read(buff)) != -1) { builder.append(new String(buff, 0, read, StandardCharsets.UTF_8)); } return builder.toString(); } catch (IOException e) { throw new RuntimeException(e); } }
java
public static String readFile(InputStream file) { try (BufferedInputStream stream = new BufferedInputStream(file)) { byte[] buff = new byte[1024]; StringBuilder builder = new StringBuilder(); int read; while ((read = stream.read(buff)) != -1) { builder.append(new String(buff, 0, read, StandardCharsets.UTF_8)); } return builder.toString(); } catch (IOException e) { throw new RuntimeException(e); } }
[ "public", "static", "String", "readFile", "(", "InputStream", "file", ")", "{", "try", "(", "BufferedInputStream", "stream", "=", "new", "BufferedInputStream", "(", "file", ")", ")", "{", "byte", "[", "]", "buff", "=", "new", "byte", "[", "1024", "]", ";", "StringBuilder", "builder", "=", "new", "StringBuilder", "(", ")", ";", "int", "read", ";", "while", "(", "(", "read", "=", "stream", ".", "read", "(", "buff", ")", ")", "!=", "-", "1", ")", "{", "builder", ".", "append", "(", "new", "String", "(", "buff", ",", "0", ",", "read", ",", "StandardCharsets", ".", "UTF_8", ")", ")", ";", "}", "return", "builder", ".", "toString", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "}" ]
Reads the {@link InputStream file} and converting it to {@link String} using UTF-8 encoding.
[ "Reads", "the", "{" ]
train
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/util/FileUtils.java#L57-L69
b3dgs/lionengine
lionengine-core/src/main/java/com/b3dgs/lionengine/graphic/drawable/ImageHeaderReaderAbstract.java
ImageHeaderReaderAbstract.readInt
protected static int readInt(InputStream input, int bytesNumber, boolean bigEndian) throws IOException { """ Read integer in image data. @param input The stream. @param bytesNumber The number of bytes to read. @param bigEndian The big endian flag. @return The integer read. @throws IOException if error on reading. """ final int oneByte = 8; int ret = 0; int sv; if (bigEndian) { sv = (bytesNumber - 1) * oneByte; } else { sv = 0; } final int cnt; if (bigEndian) { cnt = -oneByte; } else { cnt = oneByte; } for (int i = 0; i < bytesNumber; i++) { ret |= input.read() << sv; sv += cnt; } return ret; }
java
protected static int readInt(InputStream input, int bytesNumber, boolean bigEndian) throws IOException { final int oneByte = 8; int ret = 0; int sv; if (bigEndian) { sv = (bytesNumber - 1) * oneByte; } else { sv = 0; } final int cnt; if (bigEndian) { cnt = -oneByte; } else { cnt = oneByte; } for (int i = 0; i < bytesNumber; i++) { ret |= input.read() << sv; sv += cnt; } return ret; }
[ "protected", "static", "int", "readInt", "(", "InputStream", "input", ",", "int", "bytesNumber", ",", "boolean", "bigEndian", ")", "throws", "IOException", "{", "final", "int", "oneByte", "=", "8", ";", "int", "ret", "=", "0", ";", "int", "sv", ";", "if", "(", "bigEndian", ")", "{", "sv", "=", "(", "bytesNumber", "-", "1", ")", "*", "oneByte", ";", "}", "else", "{", "sv", "=", "0", ";", "}", "final", "int", "cnt", ";", "if", "(", "bigEndian", ")", "{", "cnt", "=", "-", "oneByte", ";", "}", "else", "{", "cnt", "=", "oneByte", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "bytesNumber", ";", "i", "++", ")", "{", "ret", "|=", "input", ".", "read", "(", ")", "<<", "sv", ";", "sv", "+=", "cnt", ";", "}", "return", "ret", ";", "}" ]
Read integer in image data. @param input The stream. @param bytesNumber The number of bytes to read. @param bigEndian The big endian flag. @return The integer read. @throws IOException if error on reading.
[ "Read", "integer", "in", "image", "data", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-core/src/main/java/com/b3dgs/lionengine/graphic/drawable/ImageHeaderReaderAbstract.java#L51-L79
sshtools/j2ssh-maverick
j2ssh-maverick/src/main/java/com/sshtools/util/ByteArrayWriter.java
ByteArrayWriter.writeBinaryString
public void writeBinaryString(byte[] data) throws IOException { """ Write a binary string to the array. @param data @throws IOException """ if (data == null) writeInt(0); else writeBinaryString(data, 0, data.length); }
java
public void writeBinaryString(byte[] data) throws IOException { if (data == null) writeInt(0); else writeBinaryString(data, 0, data.length); }
[ "public", "void", "writeBinaryString", "(", "byte", "[", "]", "data", ")", "throws", "IOException", "{", "if", "(", "data", "==", "null", ")", "writeInt", "(", "0", ")", ";", "else", "writeBinaryString", "(", "data", ",", "0", ",", "data", ".", "length", ")", ";", "}" ]
Write a binary string to the array. @param data @throws IOException
[ "Write", "a", "binary", "string", "to", "the", "array", "." ]
train
https://github.com/sshtools/j2ssh-maverick/blob/ce11ceaf0aa0b129b54327a6891973e1e34689f7/j2ssh-maverick/src/main/java/com/sshtools/util/ByteArrayWriter.java#L100-L105
OpenLiberty/open-liberty
dev/com.ibm.ws.security/src/com/ibm/ws/security/internal/SecurityServiceImpl.java
SecurityServiceImpl.setAndValidateProperties
private void setAndValidateProperties(String systemDomain, String defaultAppDomain) { """ Sets and validates the configuration properties. If the {@link #CFG_KEY_DEFAULT_APP_DOMAIN} property is not set, then it will use the value of {@link #CFG_KEY_SYSTEM_DOMAIN}. Note this method will be a no-op if there is no configuration data from the file. @param systemDomain @param defaultAppDomain @throws IllegalArgumentException if {link #CFG_KEY_SYSTEM_DOMAIN} is not set. """ if (isConfigurationDefinedInFile()) { if ((systemDomain == null) || systemDomain.isEmpty()) { Tr.error(tc, "SECURITY_SERVICE_ERROR_MISSING_ATTRIBUTE", CFG_KEY_SYSTEM_DOMAIN); throw new IllegalArgumentException(Tr.formatMessage(tc, "SECURITY_SERVICE_ERROR_MISSING_ATTRIBUTE", CFG_KEY_SYSTEM_DOMAIN)); } this.cfgSystemDomain = systemDomain; if ((defaultAppDomain == null) || defaultAppDomain.isEmpty()) { this.cfgDefaultAppDomain = systemDomain; } else { this.cfgDefaultAppDomain = defaultAppDomain; } } }
java
private void setAndValidateProperties(String systemDomain, String defaultAppDomain) { if (isConfigurationDefinedInFile()) { if ((systemDomain == null) || systemDomain.isEmpty()) { Tr.error(tc, "SECURITY_SERVICE_ERROR_MISSING_ATTRIBUTE", CFG_KEY_SYSTEM_DOMAIN); throw new IllegalArgumentException(Tr.formatMessage(tc, "SECURITY_SERVICE_ERROR_MISSING_ATTRIBUTE", CFG_KEY_SYSTEM_DOMAIN)); } this.cfgSystemDomain = systemDomain; if ((defaultAppDomain == null) || defaultAppDomain.isEmpty()) { this.cfgDefaultAppDomain = systemDomain; } else { this.cfgDefaultAppDomain = defaultAppDomain; } } }
[ "private", "void", "setAndValidateProperties", "(", "String", "systemDomain", ",", "String", "defaultAppDomain", ")", "{", "if", "(", "isConfigurationDefinedInFile", "(", ")", ")", "{", "if", "(", "(", "systemDomain", "==", "null", ")", "||", "systemDomain", ".", "isEmpty", "(", ")", ")", "{", "Tr", ".", "error", "(", "tc", ",", "\"SECURITY_SERVICE_ERROR_MISSING_ATTRIBUTE\"", ",", "CFG_KEY_SYSTEM_DOMAIN", ")", ";", "throw", "new", "IllegalArgumentException", "(", "Tr", ".", "formatMessage", "(", "tc", ",", "\"SECURITY_SERVICE_ERROR_MISSING_ATTRIBUTE\"", ",", "CFG_KEY_SYSTEM_DOMAIN", ")", ")", ";", "}", "this", ".", "cfgSystemDomain", "=", "systemDomain", ";", "if", "(", "(", "defaultAppDomain", "==", "null", ")", "||", "defaultAppDomain", ".", "isEmpty", "(", ")", ")", "{", "this", ".", "cfgDefaultAppDomain", "=", "systemDomain", ";", "}", "else", "{", "this", ".", "cfgDefaultAppDomain", "=", "defaultAppDomain", ";", "}", "}", "}" ]
Sets and validates the configuration properties. If the {@link #CFG_KEY_DEFAULT_APP_DOMAIN} property is not set, then it will use the value of {@link #CFG_KEY_SYSTEM_DOMAIN}. Note this method will be a no-op if there is no configuration data from the file. @param systemDomain @param defaultAppDomain @throws IllegalArgumentException if {link #CFG_KEY_SYSTEM_DOMAIN} is not set.
[ "Sets", "and", "validates", "the", "configuration", "properties", ".", "If", "the", "{", "@link", "#CFG_KEY_DEFAULT_APP_DOMAIN", "}", "property", "is", "not", "set", "then", "it", "will", "use", "the", "value", "of", "{", "@link", "#CFG_KEY_SYSTEM_DOMAIN", "}", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security/src/com/ibm/ws/security/internal/SecurityServiceImpl.java#L352-L365
BorderTech/wcomponents
wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/picker/MenuPanel.java
MenuPanel.addRecentExample
private void addRecentExample(final String text, final ExampleData data, final boolean select) { """ Adds an example to the recent subMenu. @param text the text to display. @param data the example data instance @param select should the menuItem be selected """ WMenuItem item = new WMenuItem(text, new SelectExampleAction()); item.setCancel(true); menu.add(item); item.setActionObject(data); if (select) { menu.setSelectedMenuItem(item); } }
java
private void addRecentExample(final String text, final ExampleData data, final boolean select) { WMenuItem item = new WMenuItem(text, new SelectExampleAction()); item.setCancel(true); menu.add(item); item.setActionObject(data); if (select) { menu.setSelectedMenuItem(item); } }
[ "private", "void", "addRecentExample", "(", "final", "String", "text", ",", "final", "ExampleData", "data", ",", "final", "boolean", "select", ")", "{", "WMenuItem", "item", "=", "new", "WMenuItem", "(", "text", ",", "new", "SelectExampleAction", "(", ")", ")", ";", "item", ".", "setCancel", "(", "true", ")", ";", "menu", ".", "add", "(", "item", ")", ";", "item", ".", "setActionObject", "(", "data", ")", ";", "if", "(", "select", ")", "{", "menu", ".", "setSelectedMenuItem", "(", "item", ")", ";", "}", "}" ]
Adds an example to the recent subMenu. @param text the text to display. @param data the example data instance @param select should the menuItem be selected
[ "Adds", "an", "example", "to", "the", "recent", "subMenu", "." ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/picker/MenuPanel.java#L119-L127
fozziethebeat/S-Space
src/main/java/edu/ucla/sspace/common/Similarity.java
Similarity.klDivergence
public static double klDivergence(double[] a, double[] b) { """ Computes the K-L Divergence of two probability distributions {@code A} and {@code B} where the vectors {@code a} and {@code b} correspond to {@code n} samples from each respective distribution. The divergence between two samples is non-symmetric and is frequently used as a distance metric between vectors from a semantic space. This metric is described in more detail in the following paper: <li style="font-family:Garamond, Georgia, serif">S. Kullback and R. A. Leibler, "On Information and Sufficiency", <i>The Annals of Mathematical Statistics</i> 1951. </li> @throws IllegalArgumentException when the length of the two vectors are not the same. """ check(a, b); double divergence = 0; // Iterate over all values and ignore any that are zero. for (int i = 0; i < a.length; ++i) { // Ignore values from a that are zero, since they would cause a // divide by zero error. if (b[i] == 0d) throw new IllegalArgumentException( "The KL-divergence is not defined when a[i] > 0 and " + "b[i] == 0."); else if (a[i] != 0d) divergence += a[i] * Math.log(a[i]/ b[i]); } return divergence; }
java
public static double klDivergence(double[] a, double[] b) { check(a, b); double divergence = 0; // Iterate over all values and ignore any that are zero. for (int i = 0; i < a.length; ++i) { // Ignore values from a that are zero, since they would cause a // divide by zero error. if (b[i] == 0d) throw new IllegalArgumentException( "The KL-divergence is not defined when a[i] > 0 and " + "b[i] == 0."); else if (a[i] != 0d) divergence += a[i] * Math.log(a[i]/ b[i]); } return divergence; }
[ "public", "static", "double", "klDivergence", "(", "double", "[", "]", "a", ",", "double", "[", "]", "b", ")", "{", "check", "(", "a", ",", "b", ")", ";", "double", "divergence", "=", "0", ";", "// Iterate over all values and ignore any that are zero.", "for", "(", "int", "i", "=", "0", ";", "i", "<", "a", ".", "length", ";", "++", "i", ")", "{", "// Ignore values from a that are zero, since they would cause a", "// divide by zero error.", "if", "(", "b", "[", "i", "]", "==", "0d", ")", "throw", "new", "IllegalArgumentException", "(", "\"The KL-divergence is not defined when a[i] > 0 and \"", "+", "\"b[i] == 0.\"", ")", ";", "else", "if", "(", "a", "[", "i", "]", "!=", "0d", ")", "divergence", "+=", "a", "[", "i", "]", "*", "Math", ".", "log", "(", "a", "[", "i", "]", "/", "b", "[", "i", "]", ")", ";", "}", "return", "divergence", ";", "}" ]
Computes the K-L Divergence of two probability distributions {@code A} and {@code B} where the vectors {@code a} and {@code b} correspond to {@code n} samples from each respective distribution. The divergence between two samples is non-symmetric and is frequently used as a distance metric between vectors from a semantic space. This metric is described in more detail in the following paper: <li style="font-family:Garamond, Georgia, serif">S. Kullback and R. A. Leibler, "On Information and Sufficiency", <i>The Annals of Mathematical Statistics</i> 1951. </li> @throws IllegalArgumentException when the length of the two vectors are not the same.
[ "Computes", "the", "K", "-", "L", "Divergence", "of", "two", "probability", "distributions", "{", "@code", "A", "}", "and", "{", "@code", "B", "}", "where", "the", "vectors", "{", "@code", "a", "}", "and", "{", "@code", "b", "}", "correspond", "to", "{", "@code", "n", "}", "samples", "from", "each", "respective", "distribution", ".", "The", "divergence", "between", "two", "samples", "is", "non", "-", "symmetric", "and", "is", "frequently", "used", "as", "a", "distance", "metric", "between", "vectors", "from", "a", "semantic", "space", ".", "This", "metric", "is", "described", "in", "more", "detail", "in", "the", "following", "paper", ":" ]
train
https://github.com/fozziethebeat/S-Space/blob/a608102737dfd3d59038a9ead33fe60356bc6029/src/main/java/edu/ucla/sspace/common/Similarity.java#L1967-L1985
algolia/instantsearch-android
core/src/main/java/com/algolia/instantsearch/core/helpers/Highlighter.java
Highlighter.setInput
@SuppressWarnings( { """ Sets the input to highlight. @param result a {@link JSONObject} describing a hit. @param attribute the attribute to highlight. @param inverted if {@code true}, the highlighting will be inverted. @return a {@link Styler} to specify the style before rendering. """"WeakerAccess", "unused"}) // For library users public Styler setInput(@NonNull JSONObject result, @NonNull String attribute, boolean inverted) { final String highlightedAttribute = getHighlightedAttribute(result, attribute, inverted, false); return setInput(highlightedAttribute); }
java
@SuppressWarnings({"WeakerAccess", "unused"}) // For library users public Styler setInput(@NonNull JSONObject result, @NonNull String attribute, boolean inverted) { final String highlightedAttribute = getHighlightedAttribute(result, attribute, inverted, false); return setInput(highlightedAttribute); }
[ "@", "SuppressWarnings", "(", "{", "\"WeakerAccess\"", ",", "\"unused\"", "}", ")", "// For library users", "public", "Styler", "setInput", "(", "@", "NonNull", "JSONObject", "result", ",", "@", "NonNull", "String", "attribute", ",", "boolean", "inverted", ")", "{", "final", "String", "highlightedAttribute", "=", "getHighlightedAttribute", "(", "result", ",", "attribute", ",", "inverted", ",", "false", ")", ";", "return", "setInput", "(", "highlightedAttribute", ")", ";", "}" ]
Sets the input to highlight. @param result a {@link JSONObject} describing a hit. @param attribute the attribute to highlight. @param inverted if {@code true}, the highlighting will be inverted. @return a {@link Styler} to specify the style before rendering.
[ "Sets", "the", "input", "to", "highlight", "." ]
train
https://github.com/algolia/instantsearch-android/blob/12092ec30140df9ffc2bf916339b433372034616/core/src/main/java/com/algolia/instantsearch/core/helpers/Highlighter.java#L153-L157
apache/flink
flink-runtime/src/main/java/org/apache/flink/runtime/zookeeper/ZooKeeperStateHandleStore.java
ZooKeeperStateHandleStore.addAndLock
public RetrievableStateHandle<T> addAndLock( String pathInZooKeeper, T state) throws Exception { """ Creates a state handle, stores it in ZooKeeper and locks it. A locked node cannot be removed by another {@link ZooKeeperStateHandleStore} instance as long as this instance remains connected to ZooKeeper. <p><strong>Important</strong>: This will <em>not</em> store the actual state in ZooKeeper, but create a state handle and store it in ZooKeeper. This level of indirection makes sure that data in ZooKeeper is small. <p>The operation will fail if there is already an node under the given path @param pathInZooKeeper Destination path in ZooKeeper (expected to *not* exist yet) @param state State to be added @return The Created {@link RetrievableStateHandle}. @throws Exception If a ZooKeeper or state handle operation fails """ checkNotNull(pathInZooKeeper, "Path in ZooKeeper"); checkNotNull(state, "State"); final String path = normalizePath(pathInZooKeeper); RetrievableStateHandle<T> storeHandle = storage.store(state); boolean success = false; try { // Serialize the state handle. This writes the state to the backend. byte[] serializedStoreHandle = InstantiationUtil.serializeObject(storeHandle); // Write state handle (not the actual state) to ZooKeeper. This is expected to be // smaller than the state itself. This level of indirection makes sure that data in // ZooKeeper is small, because ZooKeeper is designed for data in the KB range, but // the state can be larger. // Create the lock node in a transaction with the actual state node. That way we can prevent // race conditions with a concurrent delete operation. client.inTransaction().create().withMode(CreateMode.PERSISTENT).forPath(path, serializedStoreHandle) .and().create().withMode(CreateMode.EPHEMERAL).forPath(getLockPath(path)) .and().commit(); success = true; return storeHandle; } catch (KeeperException.NodeExistsException e) { throw new ConcurrentModificationException("ZooKeeper unexpectedly modified", e); } finally { if (!success) { // Cleanup the state handle if it was not written to ZooKeeper. if (storeHandle != null) { storeHandle.discardState(); } } } }
java
public RetrievableStateHandle<T> addAndLock( String pathInZooKeeper, T state) throws Exception { checkNotNull(pathInZooKeeper, "Path in ZooKeeper"); checkNotNull(state, "State"); final String path = normalizePath(pathInZooKeeper); RetrievableStateHandle<T> storeHandle = storage.store(state); boolean success = false; try { // Serialize the state handle. This writes the state to the backend. byte[] serializedStoreHandle = InstantiationUtil.serializeObject(storeHandle); // Write state handle (not the actual state) to ZooKeeper. This is expected to be // smaller than the state itself. This level of indirection makes sure that data in // ZooKeeper is small, because ZooKeeper is designed for data in the KB range, but // the state can be larger. // Create the lock node in a transaction with the actual state node. That way we can prevent // race conditions with a concurrent delete operation. client.inTransaction().create().withMode(CreateMode.PERSISTENT).forPath(path, serializedStoreHandle) .and().create().withMode(CreateMode.EPHEMERAL).forPath(getLockPath(path)) .and().commit(); success = true; return storeHandle; } catch (KeeperException.NodeExistsException e) { throw new ConcurrentModificationException("ZooKeeper unexpectedly modified", e); } finally { if (!success) { // Cleanup the state handle if it was not written to ZooKeeper. if (storeHandle != null) { storeHandle.discardState(); } } } }
[ "public", "RetrievableStateHandle", "<", "T", ">", "addAndLock", "(", "String", "pathInZooKeeper", ",", "T", "state", ")", "throws", "Exception", "{", "checkNotNull", "(", "pathInZooKeeper", ",", "\"Path in ZooKeeper\"", ")", ";", "checkNotNull", "(", "state", ",", "\"State\"", ")", ";", "final", "String", "path", "=", "normalizePath", "(", "pathInZooKeeper", ")", ";", "RetrievableStateHandle", "<", "T", ">", "storeHandle", "=", "storage", ".", "store", "(", "state", ")", ";", "boolean", "success", "=", "false", ";", "try", "{", "// Serialize the state handle. This writes the state to the backend.", "byte", "[", "]", "serializedStoreHandle", "=", "InstantiationUtil", ".", "serializeObject", "(", "storeHandle", ")", ";", "// Write state handle (not the actual state) to ZooKeeper. This is expected to be", "// smaller than the state itself. This level of indirection makes sure that data in", "// ZooKeeper is small, because ZooKeeper is designed for data in the KB range, but", "// the state can be larger.", "// Create the lock node in a transaction with the actual state node. That way we can prevent", "// race conditions with a concurrent delete operation.", "client", ".", "inTransaction", "(", ")", ".", "create", "(", ")", ".", "withMode", "(", "CreateMode", ".", "PERSISTENT", ")", ".", "forPath", "(", "path", ",", "serializedStoreHandle", ")", ".", "and", "(", ")", ".", "create", "(", ")", ".", "withMode", "(", "CreateMode", ".", "EPHEMERAL", ")", ".", "forPath", "(", "getLockPath", "(", "path", ")", ")", ".", "and", "(", ")", ".", "commit", "(", ")", ";", "success", "=", "true", ";", "return", "storeHandle", ";", "}", "catch", "(", "KeeperException", ".", "NodeExistsException", "e", ")", "{", "throw", "new", "ConcurrentModificationException", "(", "\"ZooKeeper unexpectedly modified\"", ",", "e", ")", ";", "}", "finally", "{", "if", "(", "!", "success", ")", "{", "// Cleanup the state handle if it was not written to ZooKeeper.", "if", "(", "storeHandle", "!=", "null", ")", "{", "storeHandle", ".", "discardState", "(", ")", ";", "}", "}", "}", "}" ]
Creates a state handle, stores it in ZooKeeper and locks it. A locked node cannot be removed by another {@link ZooKeeperStateHandleStore} instance as long as this instance remains connected to ZooKeeper. <p><strong>Important</strong>: This will <em>not</em> store the actual state in ZooKeeper, but create a state handle and store it in ZooKeeper. This level of indirection makes sure that data in ZooKeeper is small. <p>The operation will fail if there is already an node under the given path @param pathInZooKeeper Destination path in ZooKeeper (expected to *not* exist yet) @param state State to be added @return The Created {@link RetrievableStateHandle}. @throws Exception If a ZooKeeper or state handle operation fails
[ "Creates", "a", "state", "handle", "stores", "it", "in", "ZooKeeper", "and", "locks", "it", ".", "A", "locked", "node", "cannot", "be", "removed", "by", "another", "{", "@link", "ZooKeeperStateHandleStore", "}", "instance", "as", "long", "as", "this", "instance", "remains", "connected", "to", "ZooKeeper", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/zookeeper/ZooKeeperStateHandleStore.java#L129-L169
OpenLiberty/open-liberty
dev/com.ibm.ws.logging.core/src/com/ibm/ws/logging/internal/BundleManifest.java
BundleManifest.parseHeader
void parseHeader(String header, Set<String> packages) { """ This algorithm is nuts. Bnd has a nice on in OSGIHeader. @param header @param packages """ if (header != null && header.length() > 0) { List<String> splitPackages = new ArrayList<String>(); // We can't just split() on commas, because there may be things in quotes, like uses clauses int lastIndex = 0; boolean inQuotedSection = false; int i = 0; for (i = 0; i < header.length(); i++) { if ((header.charAt(i) == ',') && !(inQuotedSection)) { String packagePlusAttributesAndDirectives = header.substring(lastIndex, i); lastIndex = i + 1; splitPackages.add(packagePlusAttributesAndDirectives); } else if (header.charAt(i) == '"') { inQuotedSection = !inQuotedSection; } } // Add the last string splitPackages.add(header.substring(lastIndex, i)); // Now go through and handle the attributes for (String packagePlusAttributesAndDirectives : splitPackages) { String[] bits = packagePlusAttributesAndDirectives.split(";"); // We could also process ibm-api-type and other declarations here to get better information if we need it packages.add(bits[0]); } } }
java
void parseHeader(String header, Set<String> packages) { if (header != null && header.length() > 0) { List<String> splitPackages = new ArrayList<String>(); // We can't just split() on commas, because there may be things in quotes, like uses clauses int lastIndex = 0; boolean inQuotedSection = false; int i = 0; for (i = 0; i < header.length(); i++) { if ((header.charAt(i) == ',') && !(inQuotedSection)) { String packagePlusAttributesAndDirectives = header.substring(lastIndex, i); lastIndex = i + 1; splitPackages.add(packagePlusAttributesAndDirectives); } else if (header.charAt(i) == '"') { inQuotedSection = !inQuotedSection; } } // Add the last string splitPackages.add(header.substring(lastIndex, i)); // Now go through and handle the attributes for (String packagePlusAttributesAndDirectives : splitPackages) { String[] bits = packagePlusAttributesAndDirectives.split(";"); // We could also process ibm-api-type and other declarations here to get better information if we need it packages.add(bits[0]); } } }
[ "void", "parseHeader", "(", "String", "header", ",", "Set", "<", "String", ">", "packages", ")", "{", "if", "(", "header", "!=", "null", "&&", "header", ".", "length", "(", ")", ">", "0", ")", "{", "List", "<", "String", ">", "splitPackages", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "// We can't just split() on commas, because there may be things in quotes, like uses clauses", "int", "lastIndex", "=", "0", ";", "boolean", "inQuotedSection", "=", "false", ";", "int", "i", "=", "0", ";", "for", "(", "i", "=", "0", ";", "i", "<", "header", ".", "length", "(", ")", ";", "i", "++", ")", "{", "if", "(", "(", "header", ".", "charAt", "(", "i", ")", "==", "'", "'", ")", "&&", "!", "(", "inQuotedSection", ")", ")", "{", "String", "packagePlusAttributesAndDirectives", "=", "header", ".", "substring", "(", "lastIndex", ",", "i", ")", ";", "lastIndex", "=", "i", "+", "1", ";", "splitPackages", ".", "add", "(", "packagePlusAttributesAndDirectives", ")", ";", "}", "else", "if", "(", "header", ".", "charAt", "(", "i", ")", "==", "'", "'", ")", "{", "inQuotedSection", "=", "!", "inQuotedSection", ";", "}", "}", "// Add the last string", "splitPackages", ".", "add", "(", "header", ".", "substring", "(", "lastIndex", ",", "i", ")", ")", ";", "// Now go through and handle the attributes", "for", "(", "String", "packagePlusAttributesAndDirectives", ":", "splitPackages", ")", "{", "String", "[", "]", "bits", "=", "packagePlusAttributesAndDirectives", ".", "split", "(", "\";\"", ")", ";", "// We could also process ibm-api-type and other declarations here to get better information if we need it", "packages", ".", "add", "(", "bits", "[", "0", "]", ")", ";", "}", "}", "}" ]
This algorithm is nuts. Bnd has a nice on in OSGIHeader. @param header @param packages
[ "This", "algorithm", "is", "nuts", ".", "Bnd", "has", "a", "nice", "on", "in", "OSGIHeader", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.logging.core/src/com/ibm/ws/logging/internal/BundleManifest.java#L61-L89
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/security/cert/X509CertSelector.java
X509CertSelector.addSubjectAlternativeNameInternal
private void addSubjectAlternativeNameInternal(int type, Object name) throws IOException { """ A private method that adds a name (String or byte array) to the subjectAlternativeNames criterion. The {@code X509Certificate} must contain the specified subjectAlternativeName. @param type the name type (0-8, as specified in RFC 3280, section 4.2.1.7) @param name the name in string or byte array form @throws IOException if a parsing error occurs """ // First, ensure that the name parses GeneralNameInterface tempName = makeGeneralNameInterface(type, name); if (subjectAlternativeNames == null) { subjectAlternativeNames = new HashSet<List<?>>(); } if (subjectAlternativeGeneralNames == null) { subjectAlternativeGeneralNames = new HashSet<GeneralNameInterface>(); } List<Object> list = new ArrayList<Object>(2); list.add(Integer.valueOf(type)); list.add(name); subjectAlternativeNames.add(list); subjectAlternativeGeneralNames.add(tempName); }
java
private void addSubjectAlternativeNameInternal(int type, Object name) throws IOException { // First, ensure that the name parses GeneralNameInterface tempName = makeGeneralNameInterface(type, name); if (subjectAlternativeNames == null) { subjectAlternativeNames = new HashSet<List<?>>(); } if (subjectAlternativeGeneralNames == null) { subjectAlternativeGeneralNames = new HashSet<GeneralNameInterface>(); } List<Object> list = new ArrayList<Object>(2); list.add(Integer.valueOf(type)); list.add(name); subjectAlternativeNames.add(list); subjectAlternativeGeneralNames.add(tempName); }
[ "private", "void", "addSubjectAlternativeNameInternal", "(", "int", "type", ",", "Object", "name", ")", "throws", "IOException", "{", "// First, ensure that the name parses", "GeneralNameInterface", "tempName", "=", "makeGeneralNameInterface", "(", "type", ",", "name", ")", ";", "if", "(", "subjectAlternativeNames", "==", "null", ")", "{", "subjectAlternativeNames", "=", "new", "HashSet", "<", "List", "<", "?", ">", ">", "(", ")", ";", "}", "if", "(", "subjectAlternativeGeneralNames", "==", "null", ")", "{", "subjectAlternativeGeneralNames", "=", "new", "HashSet", "<", "GeneralNameInterface", ">", "(", ")", ";", "}", "List", "<", "Object", ">", "list", "=", "new", "ArrayList", "<", "Object", ">", "(", "2", ")", ";", "list", ".", "add", "(", "Integer", ".", "valueOf", "(", "type", ")", ")", ";", "list", ".", "add", "(", "name", ")", ";", "subjectAlternativeNames", ".", "add", "(", "list", ")", ";", "subjectAlternativeGeneralNames", ".", "add", "(", "tempName", ")", ";", "}" ]
A private method that adds a name (String or byte array) to the subjectAlternativeNames criterion. The {@code X509Certificate} must contain the specified subjectAlternativeName. @param type the name type (0-8, as specified in RFC 3280, section 4.2.1.7) @param name the name in string or byte array form @throws IOException if a parsing error occurs
[ "A", "private", "method", "that", "adds", "a", "name", "(", "String", "or", "byte", "array", ")", "to", "the", "subjectAlternativeNames", "criterion", ".", "The", "{", "@code", "X509Certificate", "}", "must", "contain", "the", "specified", "subjectAlternativeName", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/security/cert/X509CertSelector.java#L814-L829
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/TimeZoneNames.java
TimeZoneNames.getDisplayName
public final String getDisplayName(String tzID, NameType type, long date) { """ Returns the display name of the time zone at the given date. <p> <b>Note:</b> This method calls the subclass's {@link #getTimeZoneDisplayName(String, NameType)} first. When the result is null, this method calls {@link #getMetaZoneID(String, long)} to get the meta zone ID mapped from the time zone, then calls {@link #getMetaZoneDisplayName(String, NameType)}. @param tzID The canonical time zone ID. @param type The display name type. See {@link TimeZoneNames.NameType}. @param date The date @return The display name for the time zone at the given date. When this object does not have a localized display name for the time zone with the specified type and date, null is returned. """ String name = getTimeZoneDisplayName(tzID, type); if (name == null) { String mzID = getMetaZoneID(tzID, date); name = getMetaZoneDisplayName(mzID, type); } return name; }
java
public final String getDisplayName(String tzID, NameType type, long date) { String name = getTimeZoneDisplayName(tzID, type); if (name == null) { String mzID = getMetaZoneID(tzID, date); name = getMetaZoneDisplayName(mzID, type); } return name; }
[ "public", "final", "String", "getDisplayName", "(", "String", "tzID", ",", "NameType", "type", ",", "long", "date", ")", "{", "String", "name", "=", "getTimeZoneDisplayName", "(", "tzID", ",", "type", ")", ";", "if", "(", "name", "==", "null", ")", "{", "String", "mzID", "=", "getMetaZoneID", "(", "tzID", ",", "date", ")", ";", "name", "=", "getMetaZoneDisplayName", "(", "mzID", ",", "type", ")", ";", "}", "return", "name", ";", "}" ]
Returns the display name of the time zone at the given date. <p> <b>Note:</b> This method calls the subclass's {@link #getTimeZoneDisplayName(String, NameType)} first. When the result is null, this method calls {@link #getMetaZoneID(String, long)} to get the meta zone ID mapped from the time zone, then calls {@link #getMetaZoneDisplayName(String, NameType)}. @param tzID The canonical time zone ID. @param type The display name type. See {@link TimeZoneNames.NameType}. @param date The date @return The display name for the time zone at the given date. When this object does not have a localized display name for the time zone with the specified type and date, null is returned.
[ "Returns", "the", "display", "name", "of", "the", "time", "zone", "at", "the", "given", "date", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/TimeZoneNames.java#L262-L269
OpenLiberty/open-liberty
dev/com.ibm.ws.logging/src/com/ibm/ws/logging/internal/impl/LoggingConfigUtils.java
LoggingConfigUtils.getLogDirectory
static File getLogDirectory(Object newValue, File defaultDirectory) { """ Find, create, and validate the log directory. @param newValue New parameter value to parse/evaluate @param defaultValue Starting/Previous log directory-- this value might *also* be null. @return defaultValue if the newValue is null or is was badly formatted, or the converted new value """ File newDirectory = defaultDirectory; // If a value was specified, try creating a file with it if (newValue != null && newValue instanceof String) { newDirectory = new File((String) newValue); } if (newDirectory == null) { String value = "."; try { value = AccessController.doPrivileged(new java.security.PrivilegedExceptionAction<String>() { @Override public String run() throws Exception { return System.getProperty("user.dir"); } }); } catch (Exception ex) { // do nothing } newDirectory = new File(value); } return LoggingFileUtils.validateDirectory(newDirectory); }
java
static File getLogDirectory(Object newValue, File defaultDirectory) { File newDirectory = defaultDirectory; // If a value was specified, try creating a file with it if (newValue != null && newValue instanceof String) { newDirectory = new File((String) newValue); } if (newDirectory == null) { String value = "."; try { value = AccessController.doPrivileged(new java.security.PrivilegedExceptionAction<String>() { @Override public String run() throws Exception { return System.getProperty("user.dir"); } }); } catch (Exception ex) { // do nothing } newDirectory = new File(value); } return LoggingFileUtils.validateDirectory(newDirectory); }
[ "static", "File", "getLogDirectory", "(", "Object", "newValue", ",", "File", "defaultDirectory", ")", "{", "File", "newDirectory", "=", "defaultDirectory", ";", "// If a value was specified, try creating a file with it", "if", "(", "newValue", "!=", "null", "&&", "newValue", "instanceof", "String", ")", "{", "newDirectory", "=", "new", "File", "(", "(", "String", ")", "newValue", ")", ";", "}", "if", "(", "newDirectory", "==", "null", ")", "{", "String", "value", "=", "\".\"", ";", "try", "{", "value", "=", "AccessController", ".", "doPrivileged", "(", "new", "java", ".", "security", ".", "PrivilegedExceptionAction", "<", "String", ">", "(", ")", "{", "@", "Override", "public", "String", "run", "(", ")", "throws", "Exception", "{", "return", "System", ".", "getProperty", "(", "\"user.dir\"", ")", ";", "}", "}", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "// do nothing", "}", "newDirectory", "=", "new", "File", "(", "value", ")", ";", "}", "return", "LoggingFileUtils", ".", "validateDirectory", "(", "newDirectory", ")", ";", "}" ]
Find, create, and validate the log directory. @param newValue New parameter value to parse/evaluate @param defaultValue Starting/Previous log directory-- this value might *also* be null. @return defaultValue if the newValue is null or is was badly formatted, or the converted new value
[ "Find", "create", "and", "validate", "the", "log", "directory", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.logging/src/com/ibm/ws/logging/internal/impl/LoggingConfigUtils.java#L40-L65
crowmagnumb/s6-util
src/main/java/net/crowmagnumb/util/OsUtils.java
OsUtils.executeToFile
public static int executeToFile( final String[] command, final File file ) throws IOException, InterruptedException { """ Executes the given command, redirecting stdout to the given file and stderr to actual stderr @param command array of commands to run @param file to write stdout @return error code from system @throws java.io.IOException if problems @throws java.lang.InterruptedException if interrupted """ return executeToFile( command, file, System.err ); }
java
public static int executeToFile( final String[] command, final File file ) throws IOException, InterruptedException { return executeToFile( command, file, System.err ); }
[ "public", "static", "int", "executeToFile", "(", "final", "String", "[", "]", "command", ",", "final", "File", "file", ")", "throws", "IOException", ",", "InterruptedException", "{", "return", "executeToFile", "(", "command", ",", "file", ",", "System", ".", "err", ")", ";", "}" ]
Executes the given command, redirecting stdout to the given file and stderr to actual stderr @param command array of commands to run @param file to write stdout @return error code from system @throws java.io.IOException if problems @throws java.lang.InterruptedException if interrupted
[ "Executes", "the", "given", "command", "redirecting", "stdout", "to", "the", "given", "file", "and", "stderr", "to", "actual", "stderr" ]
train
https://github.com/crowmagnumb/s6-util/blob/0f9969bc0809e8a617501fa57c135e9b3984fae0/src/main/java/net/crowmagnumb/util/OsUtils.java#L397-L404
lambdazen/bitsy
src/main/java/com/lambdazen/bitsy/store/FileBackedMemoryGraphStore.java
FileBackedMemoryGraphStore.flushTxLog
public void flushTxLog() { """ This method flushes the transaction log to the V/E text files """ synchronized (flushCompleteSignal) { BufferName enqueueBuffer; synchronized (txLogToVEBuf.getPot()) { // Enqueue the backup task enqueueBuffer = txLogToVEBuf.getEnqueueBuffer(); FlushNowJob flushJob = new FlushNowJob(); txLogToVEBuf.addAndExecuteWork(flushJob); } try { do { log.debug("Waiting for flush to complete in buffer {}", enqueueBuffer); flushCompleteSignal.wait(); log.debug("Flush complete in buffer {}", lastFlushedBuffer); } while (lastFlushedBuffer != enqueueBuffer); } catch (InterruptedException e) { BitsyException toThrow = new BitsyException(BitsyErrorCodes.FLUSH_INTERRUPTED, "Exception while waiting for a transaction-log flush to be performed", e); log.error("Error while flushing the transaction log", toThrow); throw toThrow; } } }
java
public void flushTxLog() { synchronized (flushCompleteSignal) { BufferName enqueueBuffer; synchronized (txLogToVEBuf.getPot()) { // Enqueue the backup task enqueueBuffer = txLogToVEBuf.getEnqueueBuffer(); FlushNowJob flushJob = new FlushNowJob(); txLogToVEBuf.addAndExecuteWork(flushJob); } try { do { log.debug("Waiting for flush to complete in buffer {}", enqueueBuffer); flushCompleteSignal.wait(); log.debug("Flush complete in buffer {}", lastFlushedBuffer); } while (lastFlushedBuffer != enqueueBuffer); } catch (InterruptedException e) { BitsyException toThrow = new BitsyException(BitsyErrorCodes.FLUSH_INTERRUPTED, "Exception while waiting for a transaction-log flush to be performed", e); log.error("Error while flushing the transaction log", toThrow); throw toThrow; } } }
[ "public", "void", "flushTxLog", "(", ")", "{", "synchronized", "(", "flushCompleteSignal", ")", "{", "BufferName", "enqueueBuffer", ";", "synchronized", "(", "txLogToVEBuf", ".", "getPot", "(", ")", ")", "{", "// Enqueue the backup task", "enqueueBuffer", "=", "txLogToVEBuf", ".", "getEnqueueBuffer", "(", ")", ";", "FlushNowJob", "flushJob", "=", "new", "FlushNowJob", "(", ")", ";", "txLogToVEBuf", ".", "addAndExecuteWork", "(", "flushJob", ")", ";", "}", "try", "{", "do", "{", "log", ".", "debug", "(", "\"Waiting for flush to complete in buffer {}\"", ",", "enqueueBuffer", ")", ";", "flushCompleteSignal", ".", "wait", "(", ")", ";", "log", ".", "debug", "(", "\"Flush complete in buffer {}\"", ",", "lastFlushedBuffer", ")", ";", "}", "while", "(", "lastFlushedBuffer", "!=", "enqueueBuffer", ")", ";", "}", "catch", "(", "InterruptedException", "e", ")", "{", "BitsyException", "toThrow", "=", "new", "BitsyException", "(", "BitsyErrorCodes", ".", "FLUSH_INTERRUPTED", ",", "\"Exception while waiting for a transaction-log flush to be performed\"", ",", "e", ")", ";", "log", ".", "error", "(", "\"Error while flushing the transaction log\"", ",", "toThrow", ")", ";", "throw", "toThrow", ";", "}", "}", "}" ]
This method flushes the transaction log to the V/E text files
[ "This", "method", "flushes", "the", "transaction", "log", "to", "the", "V", "/", "E", "text", "files" ]
train
https://github.com/lambdazen/bitsy/blob/c0dd4b6c9d6dc9987d0168c91417eb04d80bf712/src/main/java/com/lambdazen/bitsy/store/FileBackedMemoryGraphStore.java#L540-L564
gosu-lang/gosu-lang
gosu-core-api/src/main/java/gw/util/GosuStringUtil.java
GosuStringUtil.getChomp
public static String getChomp(String str, String sep) { """ <p>Remove everything and return the last value of a supplied String, and everything after it from a String.</p> @param str the String to chomp from, must not be null @param sep the String to chomp, must not be null @return String chomped @throws NullPointerException if str or sep is <code>null</code> @deprecated Use {@link #substringAfterLast(String, String)} instead (although this doesn't include the separator) Method will be removed in Commons Lang 3.0. """ int idx = str.lastIndexOf(sep); if (idx == str.length() - sep.length()) { return sep; } else if (idx != -1) { return str.substring(idx); } else { return EMPTY; } }
java
public static String getChomp(String str, String sep) { int idx = str.lastIndexOf(sep); if (idx == str.length() - sep.length()) { return sep; } else if (idx != -1) { return str.substring(idx); } else { return EMPTY; } }
[ "public", "static", "String", "getChomp", "(", "String", "str", ",", "String", "sep", ")", "{", "int", "idx", "=", "str", ".", "lastIndexOf", "(", "sep", ")", ";", "if", "(", "idx", "==", "str", ".", "length", "(", ")", "-", "sep", ".", "length", "(", ")", ")", "{", "return", "sep", ";", "}", "else", "if", "(", "idx", "!=", "-", "1", ")", "{", "return", "str", ".", "substring", "(", "idx", ")", ";", "}", "else", "{", "return", "EMPTY", ";", "}", "}" ]
<p>Remove everything and return the last value of a supplied String, and everything after it from a String.</p> @param str the String to chomp from, must not be null @param sep the String to chomp, must not be null @return String chomped @throws NullPointerException if str or sep is <code>null</code> @deprecated Use {@link #substringAfterLast(String, String)} instead (although this doesn't include the separator) Method will be removed in Commons Lang 3.0.
[ "<p", ">", "Remove", "everything", "and", "return", "the", "last", "value", "of", "a", "supplied", "String", "and", "everything", "after", "it", "from", "a", "String", ".", "<", "/", "p", ">" ]
train
https://github.com/gosu-lang/gosu-lang/blob/d6e9261b137ce66fef3726cabe7826d4a1f946b7/gosu-core-api/src/main/java/gw/util/GosuStringUtil.java#L4048-L4057
simlife/simlife
simlife-framework/src/main/java/io/github/simlife/service/QueryService.java
QueryService.buildStringSpecification
protected Specification<ENTITY> buildStringSpecification(StringFilter filter, SingularAttribute<? super ENTITY, String> field) { """ Helper function to return a specification for filtering on a {@link String} field, where equality, containment, and null/non-null conditions are supported. @param filter the individual attribute filter coming from the frontend. @param field the JPA static metamodel representing the field. @return a Specification """ if (filter.getEquals() != null) { return equalsSpecification(field, filter.getEquals()); } else if (filter.getIn() != null) { return valueIn(field, filter.getIn()); } else if (filter.getContains() != null) { return likeUpperSpecification(field, filter.getContains()); } else if (filter.getSpecified() != null) { return byFieldSpecified(field, filter.getSpecified()); } return null; }
java
protected Specification<ENTITY> buildStringSpecification(StringFilter filter, SingularAttribute<? super ENTITY, String> field) { if (filter.getEquals() != null) { return equalsSpecification(field, filter.getEquals()); } else if (filter.getIn() != null) { return valueIn(field, filter.getIn()); } else if (filter.getContains() != null) { return likeUpperSpecification(field, filter.getContains()); } else if (filter.getSpecified() != null) { return byFieldSpecified(field, filter.getSpecified()); } return null; }
[ "protected", "Specification", "<", "ENTITY", ">", "buildStringSpecification", "(", "StringFilter", "filter", ",", "SingularAttribute", "<", "?", "super", "ENTITY", ",", "String", ">", "field", ")", "{", "if", "(", "filter", ".", "getEquals", "(", ")", "!=", "null", ")", "{", "return", "equalsSpecification", "(", "field", ",", "filter", ".", "getEquals", "(", ")", ")", ";", "}", "else", "if", "(", "filter", ".", "getIn", "(", ")", "!=", "null", ")", "{", "return", "valueIn", "(", "field", ",", "filter", ".", "getIn", "(", ")", ")", ";", "}", "else", "if", "(", "filter", ".", "getContains", "(", ")", "!=", "null", ")", "{", "return", "likeUpperSpecification", "(", "field", ",", "filter", ".", "getContains", "(", ")", ")", ";", "}", "else", "if", "(", "filter", ".", "getSpecified", "(", ")", "!=", "null", ")", "{", "return", "byFieldSpecified", "(", "field", ",", "filter", ".", "getSpecified", "(", ")", ")", ";", "}", "return", "null", ";", "}" ]
Helper function to return a specification for filtering on a {@link String} field, where equality, containment, and null/non-null conditions are supported. @param filter the individual attribute filter coming from the frontend. @param field the JPA static metamodel representing the field. @return a Specification
[ "Helper", "function", "to", "return", "a", "specification", "for", "filtering", "on", "a", "{", "@link", "String", "}", "field", "where", "equality", "containment", "and", "null", "/", "non", "-", "null", "conditions", "are", "supported", "." ]
train
https://github.com/simlife/simlife/blob/357bb8f3fb39e085239b89bc7f9a19248ff3d0bb/simlife-framework/src/main/java/io/github/simlife/service/QueryService.java#L71-L83
moparisthebest/beehive
beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/DefaultIteratorResultSetMapper.java
DefaultIteratorResultSetMapper.mapToResultType
public Iterator mapToResultType(ControlBeanContext context, Method m, ResultSet resultSet, Calendar cal) { """ Map a ResultSet to an object type Type of object to interate over is defined in the SQL annotation for the method. @param context A ControlBeanContext instance, see Beehive controls javadoc for additional information @param m Method assoicated with this call. @param resultSet Result set to map. @param cal A Calendar instance for time/date value resolution. @return The Iterator object instance resulting from the ResultSet """ return new ResultSetIterator(context, m, resultSet, cal); }
java
public Iterator mapToResultType(ControlBeanContext context, Method m, ResultSet resultSet, Calendar cal) { return new ResultSetIterator(context, m, resultSet, cal); }
[ "public", "Iterator", "mapToResultType", "(", "ControlBeanContext", "context", ",", "Method", "m", ",", "ResultSet", "resultSet", ",", "Calendar", "cal", ")", "{", "return", "new", "ResultSetIterator", "(", "context", ",", "m", ",", "resultSet", ",", "cal", ")", ";", "}" ]
Map a ResultSet to an object type Type of object to interate over is defined in the SQL annotation for the method. @param context A ControlBeanContext instance, see Beehive controls javadoc for additional information @param m Method assoicated with this call. @param resultSet Result set to map. @param cal A Calendar instance for time/date value resolution. @return The Iterator object instance resulting from the ResultSet
[ "Map", "a", "ResultSet", "to", "an", "object", "type", "Type", "of", "object", "to", "interate", "over", "is", "defined", "in", "the", "SQL", "annotation", "for", "the", "method", "." ]
train
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/DefaultIteratorResultSetMapper.java#L44-L46
hibernate/hibernate-ogm
core/src/main/java/org/hibernate/ogm/persister/impl/OgmEntityPersister.java
OgmEntityPersister.isReadRequired
private boolean isReadRequired(ValueGeneration valueGeneration, GenerationTiming matchTiming) { """ Whether the given value generation strategy requires to read the value from the database or not. """ return valueGeneration != null && valueGeneration.getValueGenerator() == null && timingsMatch( valueGeneration.getGenerationTiming(), matchTiming ); }
java
private boolean isReadRequired(ValueGeneration valueGeneration, GenerationTiming matchTiming) { return valueGeneration != null && valueGeneration.getValueGenerator() == null && timingsMatch( valueGeneration.getGenerationTiming(), matchTiming ); }
[ "private", "boolean", "isReadRequired", "(", "ValueGeneration", "valueGeneration", ",", "GenerationTiming", "matchTiming", ")", "{", "return", "valueGeneration", "!=", "null", "&&", "valueGeneration", ".", "getValueGenerator", "(", ")", "==", "null", "&&", "timingsMatch", "(", "valueGeneration", ".", "getGenerationTiming", "(", ")", ",", "matchTiming", ")", ";", "}" ]
Whether the given value generation strategy requires to read the value from the database or not.
[ "Whether", "the", "given", "value", "generation", "strategy", "requires", "to", "read", "the", "value", "from", "the", "database", "or", "not", "." ]
train
https://github.com/hibernate/hibernate-ogm/blob/9ea971df7c27277029006a6f748d8272fb1d69d2/core/src/main/java/org/hibernate/ogm/persister/impl/OgmEntityPersister.java#L1902-L1905
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/lang/Math.java
Math.copySign
public static float copySign(float magnitude, float sign) { """ Returns the first floating-point argument with the sign of the second floating-point argument. Note that unlike the {@link StrictMath#copySign(float, float) StrictMath.copySign} method, this method does not require NaN {@code sign} arguments to be treated as positive values; implementations are permitted to treat some NaN arguments as positive and other NaN arguments as negative to allow greater performance. @param magnitude the parameter providing the magnitude of the result @param sign the parameter providing the sign of the result @return a value with the magnitude of {@code magnitude} and the sign of {@code sign}. @since 1.6 """ return Float.intBitsToFloat((Float.floatToRawIntBits(sign) & (FloatConsts.SIGN_BIT_MASK)) | (Float.floatToRawIntBits(magnitude) & (FloatConsts.EXP_BIT_MASK | FloatConsts.SIGNIF_BIT_MASK))); }
java
public static float copySign(float magnitude, float sign) { return Float.intBitsToFloat((Float.floatToRawIntBits(sign) & (FloatConsts.SIGN_BIT_MASK)) | (Float.floatToRawIntBits(magnitude) & (FloatConsts.EXP_BIT_MASK | FloatConsts.SIGNIF_BIT_MASK))); }
[ "public", "static", "float", "copySign", "(", "float", "magnitude", ",", "float", "sign", ")", "{", "return", "Float", ".", "intBitsToFloat", "(", "(", "Float", ".", "floatToRawIntBits", "(", "sign", ")", "&", "(", "FloatConsts", ".", "SIGN_BIT_MASK", ")", ")", "|", "(", "Float", ".", "floatToRawIntBits", "(", "magnitude", ")", "&", "(", "FloatConsts", ".", "EXP_BIT_MASK", "|", "FloatConsts", ".", "SIGNIF_BIT_MASK", ")", ")", ")", ";", "}" ]
Returns the first floating-point argument with the sign of the second floating-point argument. Note that unlike the {@link StrictMath#copySign(float, float) StrictMath.copySign} method, this method does not require NaN {@code sign} arguments to be treated as positive values; implementations are permitted to treat some NaN arguments as positive and other NaN arguments as negative to allow greater performance. @param magnitude the parameter providing the magnitude of the result @param sign the parameter providing the sign of the result @return a value with the magnitude of {@code magnitude} and the sign of {@code sign}. @since 1.6
[ "Returns", "the", "first", "floating", "-", "point", "argument", "with", "the", "sign", "of", "the", "second", "floating", "-", "point", "argument", ".", "Note", "that", "unlike", "the", "{", "@link", "StrictMath#copySign", "(", "float", "float", ")", "StrictMath", ".", "copySign", "}", "method", "this", "method", "does", "not", "require", "NaN", "{", "@code", "sign", "}", "arguments", "to", "be", "treated", "as", "positive", "values", ";", "implementations", "are", "permitted", "to", "treat", "some", "NaN", "arguments", "as", "positive", "and", "other", "NaN", "arguments", "as", "negative", "to", "allow", "greater", "performance", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/lang/Math.java#L1793-L1799
jbundle/jbundle
base/base/src/main/java/org/jbundle/base/field/StringField.java
StringField.setString
public int setString(String strString, boolean bDisplayOption, int iMoveMode) // init this field override for other value { """ Convert and move string to this field. Data is already in string format, so just move it! @param bState the state to set the data to. @param bDisplayOption Display the data on the screen if true. @param iMoveMode INIT, SCREEN, or READ move mode. @return The error code. """ int iMaxLength = this.getMaxLength(); if (strString != null) if (strString.length() > iMaxLength) strString = strString.substring(0, iMaxLength); if (strString == null) strString = Constants.BLANK; // To set a null internally, you must call setData directly return this.setData(strString, bDisplayOption, iMoveMode); }
java
public int setString(String strString, boolean bDisplayOption, int iMoveMode) // init this field override for other value { int iMaxLength = this.getMaxLength(); if (strString != null) if (strString.length() > iMaxLength) strString = strString.substring(0, iMaxLength); if (strString == null) strString = Constants.BLANK; // To set a null internally, you must call setData directly return this.setData(strString, bDisplayOption, iMoveMode); }
[ "public", "int", "setString", "(", "String", "strString", ",", "boolean", "bDisplayOption", ",", "int", "iMoveMode", ")", "// init this field override for other value", "{", "int", "iMaxLength", "=", "this", ".", "getMaxLength", "(", ")", ";", "if", "(", "strString", "!=", "null", ")", "if", "(", "strString", ".", "length", "(", ")", ">", "iMaxLength", ")", "strString", "=", "strString", ".", "substring", "(", "0", ",", "iMaxLength", ")", ";", "if", "(", "strString", "==", "null", ")", "strString", "=", "Constants", ".", "BLANK", ";", "// To set a null internally, you must call setData directly", "return", "this", ".", "setData", "(", "strString", ",", "bDisplayOption", ",", "iMoveMode", ")", ";", "}" ]
Convert and move string to this field. Data is already in string format, so just move it! @param bState the state to set the data to. @param bDisplayOption Display the data on the screen if true. @param iMoveMode INIT, SCREEN, or READ move mode. @return The error code.
[ "Convert", "and", "move", "string", "to", "this", "field", ".", "Data", "is", "already", "in", "string", "format", "so", "just", "move", "it!" ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/field/StringField.java#L153-L161
sdl/Testy
src/main/java/com/sdl/selenium/web/WebLocatorAbstractBuilder.java
WebLocatorAbstractBuilder.setTemplate
@SuppressWarnings("unchecked") public <T extends WebLocatorAbstractBuilder> T setTemplate(final String key, final String value) { """ For customize template please see here: See http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#dpos @param key name template @param value template @param <T> the element which calls this method @return this element """ pathBuilder.setTemplate(key, value); return (T) this; }
java
@SuppressWarnings("unchecked") public <T extends WebLocatorAbstractBuilder> T setTemplate(final String key, final String value) { pathBuilder.setTemplate(key, value); return (T) this; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "<", "T", "extends", "WebLocatorAbstractBuilder", ">", "T", "setTemplate", "(", "final", "String", "key", ",", "final", "String", "value", ")", "{", "pathBuilder", ".", "setTemplate", "(", "key", ",", "value", ")", ";", "return", "(", "T", ")", "this", ";", "}" ]
For customize template please see here: See http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#dpos @param key name template @param value template @param <T> the element which calls this method @return this element
[ "For", "customize", "template", "please", "see", "here", ":", "See", "http", ":", "//", "docs", ".", "oracle", ".", "com", "/", "javase", "/", "7", "/", "docs", "/", "api", "/", "java", "/", "util", "/", "Formatter", ".", "html#dpos" ]
train
https://github.com/sdl/Testy/blob/b3ae061554016f926f04694a39ff00dab7576609/src/main/java/com/sdl/selenium/web/WebLocatorAbstractBuilder.java#L324-L328
deeplearning4j/deeplearning4j
datavec/datavec-data/datavec-data-audio/src/main/java/org/datavec/audio/dsp/FastFourierTransform.java
FastFourierTransform.getMagnitudes
public double[] getMagnitudes(double[] amplitudes, boolean complex) { """ Get the frequency intensities @param amplitudes amplitudes of the signal. Format depends on value of complex @param complex if true, amplitudes is assumed to be complex interlaced (re = even, im = odd), if false amplitudes are assumed to be real valued. @return intensities of each frequency unit: mag[frequency_unit]=intensity """ final int sampleSize = amplitudes.length; final int nrofFrequencyBins = sampleSize / 2; // call the fft and transform the complex numbers if (complex) { DoubleFFT_1D fft = new DoubleFFT_1D(nrofFrequencyBins); fft.complexForward(amplitudes); } else { DoubleFFT_1D fft = new DoubleFFT_1D(sampleSize); fft.realForward(amplitudes); // amplitudes[1] contains re[sampleSize/2] or im[(sampleSize-1) / 2] (depending on whether sampleSize is odd or even) // Discard it as it is useless without the other part // im part dc bin is always 0 for real input amplitudes[1] = 0; } // end call the fft and transform the complex numbers // even indexes (0,2,4,6,...) are real parts // odd indexes (1,3,5,7,...) are img parts double[] mag = new double[nrofFrequencyBins]; for (int i = 0; i < nrofFrequencyBins; i++) { final int f = 2 * i; mag[i] = Math.sqrt(amplitudes[f] * amplitudes[f] + amplitudes[f + 1] * amplitudes[f + 1]); } return mag; }
java
public double[] getMagnitudes(double[] amplitudes, boolean complex) { final int sampleSize = amplitudes.length; final int nrofFrequencyBins = sampleSize / 2; // call the fft and transform the complex numbers if (complex) { DoubleFFT_1D fft = new DoubleFFT_1D(nrofFrequencyBins); fft.complexForward(amplitudes); } else { DoubleFFT_1D fft = new DoubleFFT_1D(sampleSize); fft.realForward(amplitudes); // amplitudes[1] contains re[sampleSize/2] or im[(sampleSize-1) / 2] (depending on whether sampleSize is odd or even) // Discard it as it is useless without the other part // im part dc bin is always 0 for real input amplitudes[1] = 0; } // end call the fft and transform the complex numbers // even indexes (0,2,4,6,...) are real parts // odd indexes (1,3,5,7,...) are img parts double[] mag = new double[nrofFrequencyBins]; for (int i = 0; i < nrofFrequencyBins; i++) { final int f = 2 * i; mag[i] = Math.sqrt(amplitudes[f] * amplitudes[f] + amplitudes[f + 1] * amplitudes[f + 1]); } return mag; }
[ "public", "double", "[", "]", "getMagnitudes", "(", "double", "[", "]", "amplitudes", ",", "boolean", "complex", ")", "{", "final", "int", "sampleSize", "=", "amplitudes", ".", "length", ";", "final", "int", "nrofFrequencyBins", "=", "sampleSize", "/", "2", ";", "// call the fft and transform the complex numbers", "if", "(", "complex", ")", "{", "DoubleFFT_1D", "fft", "=", "new", "DoubleFFT_1D", "(", "nrofFrequencyBins", ")", ";", "fft", ".", "complexForward", "(", "amplitudes", ")", ";", "}", "else", "{", "DoubleFFT_1D", "fft", "=", "new", "DoubleFFT_1D", "(", "sampleSize", ")", ";", "fft", ".", "realForward", "(", "amplitudes", ")", ";", "// amplitudes[1] contains re[sampleSize/2] or im[(sampleSize-1) / 2] (depending on whether sampleSize is odd or even)", "// Discard it as it is useless without the other part", "// im part dc bin is always 0 for real input", "amplitudes", "[", "1", "]", "=", "0", ";", "}", "// end call the fft and transform the complex numbers", "// even indexes (0,2,4,6,...) are real parts", "// odd indexes (1,3,5,7,...) are img parts", "double", "[", "]", "mag", "=", "new", "double", "[", "nrofFrequencyBins", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "nrofFrequencyBins", ";", "i", "++", ")", "{", "final", "int", "f", "=", "2", "*", "i", ";", "mag", "[", "i", "]", "=", "Math", ".", "sqrt", "(", "amplitudes", "[", "f", "]", "*", "amplitudes", "[", "f", "]", "+", "amplitudes", "[", "f", "+", "1", "]", "*", "amplitudes", "[", "f", "+", "1", "]", ")", ";", "}", "return", "mag", ";", "}" ]
Get the frequency intensities @param amplitudes amplitudes of the signal. Format depends on value of complex @param complex if true, amplitudes is assumed to be complex interlaced (re = even, im = odd), if false amplitudes are assumed to be real valued. @return intensities of each frequency unit: mag[frequency_unit]=intensity
[ "Get", "the", "frequency", "intensities" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/datavec/datavec-data/datavec-data-audio/src/main/java/org/datavec/audio/dsp/FastFourierTransform.java#L36-L65
aol/cyclops
cyclops/src/main/java/cyclops/companion/Streams.java
Streams.scheduleFixedRate
public static <T> Connectable<T> scheduleFixedRate(final Stream<T> stream, final long rate, final ScheduledExecutorService ex) { """ Execute this Stream on a schedule <pre> {@code //run every 60 seconds Streams.scheduleFixedRate(Stream.generate(()->"next job:"+formatDate(new Date())) .map(this::processJob), 60_000,Executors.newScheduledThreadPool(1))); } </pre> Connect to the Scheduled Stream <pre> {@code Connectable<Data> dataStream = Streams.scheduleFixedRate(Stream.generate(()->"next job:"+formatDate(new Date())) .map(this::processJob) ,60_000,Executors.newScheduledThreadPool(1))); data.connect().forEach(this::logToDB); } </pre> @param stream the stream to schedule element processing on @param rate Time in millis between job runs @param ex ScheduledExecutorService @return Connectable Connectable of emitted from scheduled Stream """ return new NonPausableConnectable<>( stream).scheduleFixedRate(rate, ex); }
java
public static <T> Connectable<T> scheduleFixedRate(final Stream<T> stream, final long rate, final ScheduledExecutorService ex) { return new NonPausableConnectable<>( stream).scheduleFixedRate(rate, ex); }
[ "public", "static", "<", "T", ">", "Connectable", "<", "T", ">", "scheduleFixedRate", "(", "final", "Stream", "<", "T", ">", "stream", ",", "final", "long", "rate", ",", "final", "ScheduledExecutorService", "ex", ")", "{", "return", "new", "NonPausableConnectable", "<>", "(", "stream", ")", ".", "scheduleFixedRate", "(", "rate", ",", "ex", ")", ";", "}" ]
Execute this Stream on a schedule <pre> {@code //run every 60 seconds Streams.scheduleFixedRate(Stream.generate(()->"next job:"+formatDate(new Date())) .map(this::processJob), 60_000,Executors.newScheduledThreadPool(1))); } </pre> Connect to the Scheduled Stream <pre> {@code Connectable<Data> dataStream = Streams.scheduleFixedRate(Stream.generate(()->"next job:"+formatDate(new Date())) .map(this::processJob) ,60_000,Executors.newScheduledThreadPool(1))); data.connect().forEach(this::logToDB); } </pre> @param stream the stream to schedule element processing on @param rate Time in millis between job runs @param ex ScheduledExecutorService @return Connectable Connectable of emitted from scheduled Stream
[ "Execute", "this", "Stream", "on", "a", "schedule" ]
train
https://github.com/aol/cyclops/blob/59a9fde30190a4d1faeb9f6d9851d209d82b81dd/cyclops/src/main/java/cyclops/companion/Streams.java#L811-L814
molgenis/molgenis
molgenis-jobs/src/main/java/org/molgenis/jobs/schedule/JobScheduler.java
JobScheduler.runNow
public synchronized void runNow(String scheduledJobId) { """ Executes a {@link ScheduledJob} immediately. @param scheduledJobId ID of the {@link ScheduledJob} to run """ ScheduledJob scheduledJob = getJob(scheduledJobId); try { JobKey jobKey = new JobKey(scheduledJobId, SCHEDULED_JOB_GROUP); if (quartzScheduler.checkExists(jobKey)) { // Run job now quartzScheduler.triggerJob(jobKey); } else { // Schedule with 'now' trigger Trigger trigger = newTrigger().withIdentity(scheduledJobId, SCHEDULED_JOB_GROUP).startNow().build(); schedule(scheduledJob, trigger); } } catch (SchedulerException e) { LOG.error("Error runNow ScheduledJob", e); throw new MolgenisDataException("Error job runNow", e); } }
java
public synchronized void runNow(String scheduledJobId) { ScheduledJob scheduledJob = getJob(scheduledJobId); try { JobKey jobKey = new JobKey(scheduledJobId, SCHEDULED_JOB_GROUP); if (quartzScheduler.checkExists(jobKey)) { // Run job now quartzScheduler.triggerJob(jobKey); } else { // Schedule with 'now' trigger Trigger trigger = newTrigger().withIdentity(scheduledJobId, SCHEDULED_JOB_GROUP).startNow().build(); schedule(scheduledJob, trigger); } } catch (SchedulerException e) { LOG.error("Error runNow ScheduledJob", e); throw new MolgenisDataException("Error job runNow", e); } }
[ "public", "synchronized", "void", "runNow", "(", "String", "scheduledJobId", ")", "{", "ScheduledJob", "scheduledJob", "=", "getJob", "(", "scheduledJobId", ")", ";", "try", "{", "JobKey", "jobKey", "=", "new", "JobKey", "(", "scheduledJobId", ",", "SCHEDULED_JOB_GROUP", ")", ";", "if", "(", "quartzScheduler", ".", "checkExists", "(", "jobKey", ")", ")", "{", "// Run job now", "quartzScheduler", ".", "triggerJob", "(", "jobKey", ")", ";", "}", "else", "{", "// Schedule with 'now' trigger", "Trigger", "trigger", "=", "newTrigger", "(", ")", ".", "withIdentity", "(", "scheduledJobId", ",", "SCHEDULED_JOB_GROUP", ")", ".", "startNow", "(", ")", ".", "build", "(", ")", ";", "schedule", "(", "scheduledJob", ",", "trigger", ")", ";", "}", "}", "catch", "(", "SchedulerException", "e", ")", "{", "LOG", ".", "error", "(", "\"Error runNow ScheduledJob\"", ",", "e", ")", ";", "throw", "new", "MolgenisDataException", "(", "\"Error job runNow\"", ",", "e", ")", ";", "}", "}" ]
Executes a {@link ScheduledJob} immediately. @param scheduledJobId ID of the {@link ScheduledJob} to run
[ "Executes", "a", "{", "@link", "ScheduledJob", "}", "immediately", "." ]
train
https://github.com/molgenis/molgenis/blob/b4d0d6b27e6f6c8d7505a3863dc03b589601f987/molgenis-jobs/src/main/java/org/molgenis/jobs/schedule/JobScheduler.java#L52-L70
matthewhorridge/owlapi-gwt
owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLSubObjectPropertyOfAxiomImpl_CustomFieldSerializer.java
OWLSubObjectPropertyOfAxiomImpl_CustomFieldSerializer.serializeInstance
@Override public void serializeInstance(SerializationStreamWriter streamWriter, OWLSubObjectPropertyOfAxiomImpl instance) throws SerializationException { """ Serializes the content of the object into the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter}. @param streamWriter the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter} to write the object's content to @param instance the object instance to serialize @throws com.google.gwt.user.client.rpc.SerializationException if the serialization operation is not successful """ serialize(streamWriter, instance); }
java
@Override public void serializeInstance(SerializationStreamWriter streamWriter, OWLSubObjectPropertyOfAxiomImpl instance) throws SerializationException { serialize(streamWriter, instance); }
[ "@", "Override", "public", "void", "serializeInstance", "(", "SerializationStreamWriter", "streamWriter", ",", "OWLSubObjectPropertyOfAxiomImpl", "instance", ")", "throws", "SerializationException", "{", "serialize", "(", "streamWriter", ",", "instance", ")", ";", "}" ]
Serializes the content of the object into the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter}. @param streamWriter the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter} to write the object's content to @param instance the object instance to serialize @throws com.google.gwt.user.client.rpc.SerializationException if the serialization operation is not successful
[ "Serializes", "the", "content", "of", "the", "object", "into", "the", "{", "@link", "com", ".", "google", ".", "gwt", ".", "user", ".", "client", ".", "rpc", ".", "SerializationStreamWriter", "}", "." ]
train
https://github.com/matthewhorridge/owlapi-gwt/blob/7ab975fb6cef3c8947099983551672a3b5d4e2fd/owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLSubObjectPropertyOfAxiomImpl_CustomFieldSerializer.java#L75-L78
geomajas/geomajas-project-client-gwt2
server-extension/src/main/java/org/geomajas/gwt2/client/GeomajasServerExtension.java
GeomajasServerExtension.initializeMap
public void initializeMap(final MapPresenter mapPresenter, String applicationId, String id, final DefaultMapWidget... mapWidgets) { """ Initialize the map by fetching a configuration on the server. @param mapPresenter The map to initialize. @param applicationId The application ID in the backend configuration. @param id The map ID in the backend configuration. @param mapWidgets A set of widgets that should be added to the map by default. """ GwtCommand commandRequest = new GwtCommand(GetMapConfigurationRequest.COMMAND); commandRequest.setCommandRequest(new GetMapConfigurationRequest(id, applicationId)); commandService.execute(commandRequest, new AbstractCommandCallback<GetMapConfigurationResponse>() { public void execute(GetMapConfigurationResponse response) { // Initialize the MapModel and ViewPort: ClientMapInfo mapInfo = response.getMapInfo(); // Create the map configuration MapConfiguration configuration = createMapConfiguration(mapInfo, mapPresenter); // We must initialize the map first (without firing the event), as layer constructors may depend on it : ((MapPresenterImpl) mapPresenter).initialize(configuration, false, mapWidgets); // Add all layers: for (ClientLayerInfo layerInfo : mapInfo.getLayers()) { ServerLayer<?> layer = createLayer(configuration, layerInfo, mapPresenter.getViewPort(), mapPresenter.getEventBus()); mapPresenter.getLayersModel().addLayer(layer); } // All layers animated LayersModelRenderer modelRenderer = mapPresenter.getLayersModelRenderer(); for (int i = 0; i < mapPresenter.getLayersModel().getLayerCount(); i++) { modelRenderer.setAnimated(mapPresenter.getLayersModel().getLayer(i), true); } // Also add a renderer for feature selection: FeatureSelectionRenderer renderer = new FeatureSelectionRenderer(mapPresenter); renderer.initialize(mapInfo); mapPresenter.getEventBus().addFeatureSelectionHandler(renderer); mapPresenter.getEventBus().addLayerVisibilityHandler(renderer); // now we can fire the initialization event mapPresenter.getEventBus().fireEvent(new MapInitializationEvent(mapPresenter)); } }); }
java
public void initializeMap(final MapPresenter mapPresenter, String applicationId, String id, final DefaultMapWidget... mapWidgets) { GwtCommand commandRequest = new GwtCommand(GetMapConfigurationRequest.COMMAND); commandRequest.setCommandRequest(new GetMapConfigurationRequest(id, applicationId)); commandService.execute(commandRequest, new AbstractCommandCallback<GetMapConfigurationResponse>() { public void execute(GetMapConfigurationResponse response) { // Initialize the MapModel and ViewPort: ClientMapInfo mapInfo = response.getMapInfo(); // Create the map configuration MapConfiguration configuration = createMapConfiguration(mapInfo, mapPresenter); // We must initialize the map first (without firing the event), as layer constructors may depend on it : ((MapPresenterImpl) mapPresenter).initialize(configuration, false, mapWidgets); // Add all layers: for (ClientLayerInfo layerInfo : mapInfo.getLayers()) { ServerLayer<?> layer = createLayer(configuration, layerInfo, mapPresenter.getViewPort(), mapPresenter.getEventBus()); mapPresenter.getLayersModel().addLayer(layer); } // All layers animated LayersModelRenderer modelRenderer = mapPresenter.getLayersModelRenderer(); for (int i = 0; i < mapPresenter.getLayersModel().getLayerCount(); i++) { modelRenderer.setAnimated(mapPresenter.getLayersModel().getLayer(i), true); } // Also add a renderer for feature selection: FeatureSelectionRenderer renderer = new FeatureSelectionRenderer(mapPresenter); renderer.initialize(mapInfo); mapPresenter.getEventBus().addFeatureSelectionHandler(renderer); mapPresenter.getEventBus().addLayerVisibilityHandler(renderer); // now we can fire the initialization event mapPresenter.getEventBus().fireEvent(new MapInitializationEvent(mapPresenter)); } }); }
[ "public", "void", "initializeMap", "(", "final", "MapPresenter", "mapPresenter", ",", "String", "applicationId", ",", "String", "id", ",", "final", "DefaultMapWidget", "...", "mapWidgets", ")", "{", "GwtCommand", "commandRequest", "=", "new", "GwtCommand", "(", "GetMapConfigurationRequest", ".", "COMMAND", ")", ";", "commandRequest", ".", "setCommandRequest", "(", "new", "GetMapConfigurationRequest", "(", "id", ",", "applicationId", ")", ")", ";", "commandService", ".", "execute", "(", "commandRequest", ",", "new", "AbstractCommandCallback", "<", "GetMapConfigurationResponse", ">", "(", ")", "{", "public", "void", "execute", "(", "GetMapConfigurationResponse", "response", ")", "{", "// Initialize the MapModel and ViewPort:", "ClientMapInfo", "mapInfo", "=", "response", ".", "getMapInfo", "(", ")", ";", "// Create the map configuration", "MapConfiguration", "configuration", "=", "createMapConfiguration", "(", "mapInfo", ",", "mapPresenter", ")", ";", "// We must initialize the map first (without firing the event), as layer constructors may depend on it :", "(", "(", "MapPresenterImpl", ")", "mapPresenter", ")", ".", "initialize", "(", "configuration", ",", "false", ",", "mapWidgets", ")", ";", "// Add all layers:", "for", "(", "ClientLayerInfo", "layerInfo", ":", "mapInfo", ".", "getLayers", "(", ")", ")", "{", "ServerLayer", "<", "?", ">", "layer", "=", "createLayer", "(", "configuration", ",", "layerInfo", ",", "mapPresenter", ".", "getViewPort", "(", ")", ",", "mapPresenter", ".", "getEventBus", "(", ")", ")", ";", "mapPresenter", ".", "getLayersModel", "(", ")", ".", "addLayer", "(", "layer", ")", ";", "}", "// All layers animated", "LayersModelRenderer", "modelRenderer", "=", "mapPresenter", ".", "getLayersModelRenderer", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "mapPresenter", ".", "getLayersModel", "(", ")", ".", "getLayerCount", "(", ")", ";", "i", "++", ")", "{", "modelRenderer", ".", "setAnimated", "(", "mapPresenter", ".", "getLayersModel", "(", ")", ".", "getLayer", "(", "i", ")", ",", "true", ")", ";", "}", "// Also add a renderer for feature selection:", "FeatureSelectionRenderer", "renderer", "=", "new", "FeatureSelectionRenderer", "(", "mapPresenter", ")", ";", "renderer", ".", "initialize", "(", "mapInfo", ")", ";", "mapPresenter", ".", "getEventBus", "(", ")", ".", "addFeatureSelectionHandler", "(", "renderer", ")", ";", "mapPresenter", ".", "getEventBus", "(", ")", ".", "addLayerVisibilityHandler", "(", "renderer", ")", ";", "// now we can fire the initialization event", "mapPresenter", ".", "getEventBus", "(", ")", ".", "fireEvent", "(", "new", "MapInitializationEvent", "(", "mapPresenter", ")", ")", ";", "}", "}", ")", ";", "}" ]
Initialize the map by fetching a configuration on the server. @param mapPresenter The map to initialize. @param applicationId The application ID in the backend configuration. @param id The map ID in the backend configuration. @param mapWidgets A set of widgets that should be added to the map by default.
[ "Initialize", "the", "map", "by", "fetching", "a", "configuration", "on", "the", "server", "." ]
train
https://github.com/geomajas/geomajas-project-client-gwt2/blob/bd8d7904e861fa80522eed7b83c4ea99844180c7/server-extension/src/main/java/org/geomajas/gwt2/client/GeomajasServerExtension.java#L159-L197
Stratio/stratio-cassandra
src/java/org/apache/cassandra/cql3/ErrorCollector.java
ErrorCollector.highlightToken
private static String highlightToken(String line, Token token) { """ Puts the specified token within square brackets. @param line the line containing the token @param token the token to put within square brackets """ String newLine = insertChar(line, getLastCharPositionInLine(token), ']'); return insertChar(newLine, token.getCharPositionInLine(), '['); }
java
private static String highlightToken(String line, Token token) { String newLine = insertChar(line, getLastCharPositionInLine(token), ']'); return insertChar(newLine, token.getCharPositionInLine(), '['); }
[ "private", "static", "String", "highlightToken", "(", "String", "line", ",", "Token", "token", ")", "{", "String", "newLine", "=", "insertChar", "(", "line", ",", "getLastCharPositionInLine", "(", "token", ")", ",", "'", "'", ")", ";", "return", "insertChar", "(", "newLine", ",", "token", ".", "getCharPositionInLine", "(", ")", ",", "'", "'", ")", ";", "}" ]
Puts the specified token within square brackets. @param line the line containing the token @param token the token to put within square brackets
[ "Puts", "the", "specified", "token", "within", "square", "brackets", "." ]
train
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/cql3/ErrorCollector.java#L210-L214
ops4j/org.ops4j.pax.logging
pax-logging-api/src/main/java/org/jboss/logging/Logger.java
Logger.debugf
public void debugf(String format, Object param1) { """ Issue a formatted log message with a level of DEBUG. @param format the format string as per {@link String#format(String, Object...)} or resource bundle key therefor @param param1 the sole parameter """ if (isEnabled(Level.DEBUG)) { doLogf(Level.DEBUG, FQCN, format, new Object[] { param1 }, null); } }
java
public void debugf(String format, Object param1) { if (isEnabled(Level.DEBUG)) { doLogf(Level.DEBUG, FQCN, format, new Object[] { param1 }, null); } }
[ "public", "void", "debugf", "(", "String", "format", ",", "Object", "param1", ")", "{", "if", "(", "isEnabled", "(", "Level", ".", "DEBUG", ")", ")", "{", "doLogf", "(", "Level", ".", "DEBUG", ",", "FQCN", ",", "format", ",", "new", "Object", "[", "]", "{", "param1", "}", ",", "null", ")", ";", "}", "}" ]
Issue a formatted log message with a level of DEBUG. @param format the format string as per {@link String#format(String, Object...)} or resource bundle key therefor @param param1 the sole parameter
[ "Issue", "a", "formatted", "log", "message", "with", "a", "level", "of", "DEBUG", "." ]
train
https://github.com/ops4j/org.ops4j.pax.logging/blob/493de4e1db4fe9f981f3dd78b8e40e5bf2b2e59d/pax-logging-api/src/main/java/org/jboss/logging/Logger.java#L710-L714
mapsforge/mapsforge
mapsforge-map/src/main/java/org/mapsforge/map/layer/renderer/CanvasRasterer.java
CanvasRasterer.fillOutsideAreas
void fillOutsideAreas(int color, Rectangle insideArea) { """ Fills the area outside the specificed rectangle with color. This method is used to blank out areas that fall outside the map area. @param color the fill color for the outside area @param insideArea the inside area on which not to draw """ this.canvas.setClipDifference((int) insideArea.left, (int) insideArea.top, (int) insideArea.getWidth(), (int) insideArea.getHeight()); this.canvas.fillColor(color); this.canvas.resetClip(); }
java
void fillOutsideAreas(int color, Rectangle insideArea) { this.canvas.setClipDifference((int) insideArea.left, (int) insideArea.top, (int) insideArea.getWidth(), (int) insideArea.getHeight()); this.canvas.fillColor(color); this.canvas.resetClip(); }
[ "void", "fillOutsideAreas", "(", "int", "color", ",", "Rectangle", "insideArea", ")", "{", "this", ".", "canvas", ".", "setClipDifference", "(", "(", "int", ")", "insideArea", ".", "left", ",", "(", "int", ")", "insideArea", ".", "top", ",", "(", "int", ")", "insideArea", ".", "getWidth", "(", ")", ",", "(", "int", ")", "insideArea", ".", "getHeight", "(", ")", ")", ";", "this", ".", "canvas", ".", "fillColor", "(", "color", ")", ";", "this", ".", "canvas", ".", "resetClip", "(", ")", ";", "}" ]
Fills the area outside the specificed rectangle with color. This method is used to blank out areas that fall outside the map area. @param color the fill color for the outside area @param insideArea the inside area on which not to draw
[ "Fills", "the", "area", "outside", "the", "specificed", "rectangle", "with", "color", ".", "This", "method", "is", "used", "to", "blank", "out", "areas", "that", "fall", "outside", "the", "map", "area", "." ]
train
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-map/src/main/java/org/mapsforge/map/layer/renderer/CanvasRasterer.java#L112-L116
finmath/finmath-lib
src/main/java6/net/finmath/montecarlo/assetderivativevaluation/products/AsianOption.java
AsianOption.getValue
@Override public RandomVariableInterface getValue(double evaluationTime, AssetModelMonteCarloSimulationInterface model) throws CalculationException { """ This method returns the value random variable of the product within the specified model, evaluated at a given evalutationTime. Note: For a lattice this is often the value conditional to evalutationTime, for a Monte-Carlo simulation this is the (sum of) value discounted to evaluation time. Cashflows prior evaluationTime are not considered. @param evaluationTime The time on which this products value should be observed. @param model The model used to price the product. @return The random variable representing the value of the product discounted to evaluation time @throws net.finmath.exception.CalculationException Thrown if the valuation fails, specific cause may be available via the <code>cause()</code> method. """ // Calculate average RandomVariableInterface average = model.getRandomVariableForConstant(0.0); for(double time : timesForAveraging) { RandomVariableInterface underlying = model.getAssetValue(time, underlyingIndex); average = average.add(underlying); } average = average.div(timesForAveraging.getNumberOfTimes()); // The payoff: values = max(underlying - strike, 0) RandomVariableInterface values = average.sub(strike).floor(0.0); // Discounting... RandomVariableInterface numeraireAtMaturity = model.getNumeraire(maturity); RandomVariableInterface monteCarloWeights = model.getMonteCarloWeights(maturity); values = values.div(numeraireAtMaturity).mult(monteCarloWeights); // ...to evaluation time. RandomVariableInterface numeraireAtEvalTime = model.getNumeraire(evaluationTime); RandomVariableInterface monteCarloProbabilitiesAtEvalTime = model.getMonteCarloWeights(evaluationTime); values = values.mult(numeraireAtEvalTime).div(monteCarloProbabilitiesAtEvalTime); return values; }
java
@Override public RandomVariableInterface getValue(double evaluationTime, AssetModelMonteCarloSimulationInterface model) throws CalculationException { // Calculate average RandomVariableInterface average = model.getRandomVariableForConstant(0.0); for(double time : timesForAveraging) { RandomVariableInterface underlying = model.getAssetValue(time, underlyingIndex); average = average.add(underlying); } average = average.div(timesForAveraging.getNumberOfTimes()); // The payoff: values = max(underlying - strike, 0) RandomVariableInterface values = average.sub(strike).floor(0.0); // Discounting... RandomVariableInterface numeraireAtMaturity = model.getNumeraire(maturity); RandomVariableInterface monteCarloWeights = model.getMonteCarloWeights(maturity); values = values.div(numeraireAtMaturity).mult(monteCarloWeights); // ...to evaluation time. RandomVariableInterface numeraireAtEvalTime = model.getNumeraire(evaluationTime); RandomVariableInterface monteCarloProbabilitiesAtEvalTime = model.getMonteCarloWeights(evaluationTime); values = values.mult(numeraireAtEvalTime).div(monteCarloProbabilitiesAtEvalTime); return values; }
[ "@", "Override", "public", "RandomVariableInterface", "getValue", "(", "double", "evaluationTime", ",", "AssetModelMonteCarloSimulationInterface", "model", ")", "throws", "CalculationException", "{", "// Calculate average", "RandomVariableInterface", "average", "=", "model", ".", "getRandomVariableForConstant", "(", "0.0", ")", ";", "for", "(", "double", "time", ":", "timesForAveraging", ")", "{", "RandomVariableInterface", "underlying", "=", "model", ".", "getAssetValue", "(", "time", ",", "underlyingIndex", ")", ";", "average", "=", "average", ".", "add", "(", "underlying", ")", ";", "}", "average", "=", "average", ".", "div", "(", "timesForAveraging", ".", "getNumberOfTimes", "(", ")", ")", ";", "// The payoff: values = max(underlying - strike, 0)", "RandomVariableInterface", "values", "=", "average", ".", "sub", "(", "strike", ")", ".", "floor", "(", "0.0", ")", ";", "// Discounting...", "RandomVariableInterface", "numeraireAtMaturity", "=", "model", ".", "getNumeraire", "(", "maturity", ")", ";", "RandomVariableInterface", "monteCarloWeights", "=", "model", ".", "getMonteCarloWeights", "(", "maturity", ")", ";", "values", "=", "values", ".", "div", "(", "numeraireAtMaturity", ")", ".", "mult", "(", "monteCarloWeights", ")", ";", "// ...to evaluation time.", "RandomVariableInterface", "numeraireAtEvalTime", "=", "model", ".", "getNumeraire", "(", "evaluationTime", ")", ";", "RandomVariableInterface", "monteCarloProbabilitiesAtEvalTime", "=", "model", ".", "getMonteCarloWeights", "(", "evaluationTime", ")", ";", "values", "=", "values", ".", "mult", "(", "numeraireAtEvalTime", ")", ".", "div", "(", "monteCarloProbabilitiesAtEvalTime", ")", ";", "return", "values", ";", "}" ]
This method returns the value random variable of the product within the specified model, evaluated at a given evalutationTime. Note: For a lattice this is often the value conditional to evalutationTime, for a Monte-Carlo simulation this is the (sum of) value discounted to evaluation time. Cashflows prior evaluationTime are not considered. @param evaluationTime The time on which this products value should be observed. @param model The model used to price the product. @return The random variable representing the value of the product discounted to evaluation time @throws net.finmath.exception.CalculationException Thrown if the valuation fails, specific cause may be available via the <code>cause()</code> method.
[ "This", "method", "returns", "the", "value", "random", "variable", "of", "the", "product", "within", "the", "specified", "model", "evaluated", "at", "a", "given", "evalutationTime", ".", "Note", ":", "For", "a", "lattice", "this", "is", "often", "the", "value", "conditional", "to", "evalutationTime", "for", "a", "Monte", "-", "Carlo", "simulation", "this", "is", "the", "(", "sum", "of", ")", "value", "discounted", "to", "evaluation", "time", ".", "Cashflows", "prior", "evaluationTime", "are", "not", "considered", "." ]
train
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/montecarlo/assetderivativevaluation/products/AsianOption.java#L76-L100
kiegroup/drools
kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/decisiontables/DecisionTableImpl.java
DecisionTableImpl.satisfies
private boolean satisfies(EvaluationContext ctx, Object param, UnaryTest test ) { """ Checks that a given parameter matches a single cell test @param ctx @param param @param test @return """ return test.apply( ctx, param ); }
java
private boolean satisfies(EvaluationContext ctx, Object param, UnaryTest test ) { return test.apply( ctx, param ); }
[ "private", "boolean", "satisfies", "(", "EvaluationContext", "ctx", ",", "Object", "param", ",", "UnaryTest", "test", ")", "{", "return", "test", ".", "apply", "(", "ctx", ",", "param", ")", ";", "}" ]
Checks that a given parameter matches a single cell test @param ctx @param param @param test @return
[ "Checks", "that", "a", "given", "parameter", "matches", "a", "single", "cell", "test" ]
train
https://github.com/kiegroup/drools/blob/22b0275d6dbe93070b8090948502cf46eda543c4/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/decisiontables/DecisionTableImpl.java#L289-L291
datumbox/datumbox-framework
datumbox-framework-core/src/main/java/com/datumbox/framework/core/common/utilities/PHPMethods.java
PHPMethods.arrangeByIndex
public static <T> void arrangeByIndex(T[] array, Integer[] indexes) { """ Rearranges the array based on the order of the provided indexes. @param <T> @param array @param indexes """ if(array.length != indexes.length) { throw new IllegalArgumentException("The length of the two arrays must match."); } //sort the array based on the indexes for(int i=0;i<array.length;i++) { int index = indexes[i]; //swap T tmp = array[i]; array[i] = array[index]; array[index] = tmp; } }
java
public static <T> void arrangeByIndex(T[] array, Integer[] indexes) { if(array.length != indexes.length) { throw new IllegalArgumentException("The length of the two arrays must match."); } //sort the array based on the indexes for(int i=0;i<array.length;i++) { int index = indexes[i]; //swap T tmp = array[i]; array[i] = array[index]; array[index] = tmp; } }
[ "public", "static", "<", "T", ">", "void", "arrangeByIndex", "(", "T", "[", "]", "array", ",", "Integer", "[", "]", "indexes", ")", "{", "if", "(", "array", ".", "length", "!=", "indexes", ".", "length", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"The length of the two arrays must match.\"", ")", ";", "}", "//sort the array based on the indexes", "for", "(", "int", "i", "=", "0", ";", "i", "<", "array", ".", "length", ";", "i", "++", ")", "{", "int", "index", "=", "indexes", "[", "i", "]", ";", "//swap", "T", "tmp", "=", "array", "[", "i", "]", ";", "array", "[", "i", "]", "=", "array", "[", "index", "]", ";", "array", "[", "index", "]", "=", "tmp", ";", "}", "}" ]
Rearranges the array based on the order of the provided indexes. @param <T> @param array @param indexes
[ "Rearranges", "the", "array", "based", "on", "the", "order", "of", "the", "provided", "indexes", "." ]
train
https://github.com/datumbox/datumbox-framework/blob/909dff0476e80834f05ecdde0624dd2390e9b0ca/datumbox-framework-core/src/main/java/com/datumbox/framework/core/common/utilities/PHPMethods.java#L310-L324
outbrain/ob1k
ob1k-cache/src/main/java/com/outbrain/ob1k/cache/memcache/folsom/MemcachedClientBuilder.java
MemcachedClientBuilder.newMessagePackClient
public static <T> MemcachedClientBuilder<T> newMessagePackClient(final MessagePack messagePack, final Class<T> valueType) { """ Create a client builder for MessagePack values. @return The builder """ if (!ClassUtils.isPrimitiveOrWrapper(valueType)) { messagePack.register(valueType); } return newClient(new MessagePackTranscoder<>(messagePack, valueType)); }
java
public static <T> MemcachedClientBuilder<T> newMessagePackClient(final MessagePack messagePack, final Class<T> valueType) { if (!ClassUtils.isPrimitiveOrWrapper(valueType)) { messagePack.register(valueType); } return newClient(new MessagePackTranscoder<>(messagePack, valueType)); }
[ "public", "static", "<", "T", ">", "MemcachedClientBuilder", "<", "T", ">", "newMessagePackClient", "(", "final", "MessagePack", "messagePack", ",", "final", "Class", "<", "T", ">", "valueType", ")", "{", "if", "(", "!", "ClassUtils", ".", "isPrimitiveOrWrapper", "(", "valueType", ")", ")", "{", "messagePack", ".", "register", "(", "valueType", ")", ";", "}", "return", "newClient", "(", "new", "MessagePackTranscoder", "<>", "(", "messagePack", ",", "valueType", ")", ")", ";", "}" ]
Create a client builder for MessagePack values. @return The builder
[ "Create", "a", "client", "builder", "for", "MessagePack", "values", "." ]
train
https://github.com/outbrain/ob1k/blob/9e43ab39230c5787065053da0f766d822d0fe4e7/ob1k-cache/src/main/java/com/outbrain/ob1k/cache/memcache/folsom/MemcachedClientBuilder.java#L61-L66
Activiti/Activiti
activiti-engine/src/main/java/org/activiti/engine/impl/persistence/entity/VariableScopeImpl.java
VariableScopeImpl.getVariable
public Object getVariable(String variableName, boolean fetchAllVariables) { """ The same operation as {@link VariableScopeImpl#getVariable(String)}, but with an extra parameter to indicate whether or not all variables need to be fetched. Note that the default Activiti way (because of backwards compatibility) is to fetch all the variables when doing a get/set of variables. So this means 'true' is the default value for this method, and in fact it will simply delegate to {@link #getVariable(String)}. This can also be the most performant, if you're doing a lot of variable gets in the same transaction (eg in service tasks). In case 'false' is used, only the specific variable will be fetched. """ Object value = null; VariableInstance variable = getVariableInstance(variableName, fetchAllVariables); if (variable != null) { value = variable.getValue(); } return value; }
java
public Object getVariable(String variableName, boolean fetchAllVariables) { Object value = null; VariableInstance variable = getVariableInstance(variableName, fetchAllVariables); if (variable != null) { value = variable.getValue(); } return value; }
[ "public", "Object", "getVariable", "(", "String", "variableName", ",", "boolean", "fetchAllVariables", ")", "{", "Object", "value", "=", "null", ";", "VariableInstance", "variable", "=", "getVariableInstance", "(", "variableName", ",", "fetchAllVariables", ")", ";", "if", "(", "variable", "!=", "null", ")", "{", "value", "=", "variable", ".", "getValue", "(", ")", ";", "}", "return", "value", ";", "}" ]
The same operation as {@link VariableScopeImpl#getVariable(String)}, but with an extra parameter to indicate whether or not all variables need to be fetched. Note that the default Activiti way (because of backwards compatibility) is to fetch all the variables when doing a get/set of variables. So this means 'true' is the default value for this method, and in fact it will simply delegate to {@link #getVariable(String)}. This can also be the most performant, if you're doing a lot of variable gets in the same transaction (eg in service tasks). In case 'false' is used, only the specific variable will be fetched.
[ "The", "same", "operation", "as", "{", "@link", "VariableScopeImpl#getVariable", "(", "String", ")", "}", "but", "with", "an", "extra", "parameter", "to", "indicate", "whether", "or", "not", "all", "variables", "need", "to", "be", "fetched", "." ]
train
https://github.com/Activiti/Activiti/blob/82e2b2cd2083b2f734ca0efc7815389c0f2517d9/activiti-engine/src/main/java/org/activiti/engine/impl/persistence/entity/VariableScopeImpl.java#L250-L257
javalite/activejdbc
javalite-common/src/main/java/org/javalite/http/Request.java
Request.responseMessage
public String responseMessage() { """ Returns response message from server, such as "OK", or "Created", etc. @return response message from server, such as "OK", or "Created", etc. """ try { connect(); return connection.getResponseMessage(); } catch (Exception e) { throw new HttpException("Failed URL: " + url, e); } }
java
public String responseMessage() { try { connect(); return connection.getResponseMessage(); } catch (Exception e) { throw new HttpException("Failed URL: " + url, e); } }
[ "public", "String", "responseMessage", "(", ")", "{", "try", "{", "connect", "(", ")", ";", "return", "connection", ".", "getResponseMessage", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "HttpException", "(", "\"Failed URL: \"", "+", "url", ",", "e", ")", ";", "}", "}" ]
Returns response message from server, such as "OK", or "Created", etc. @return response message from server, such as "OK", or "Created", etc.
[ "Returns", "response", "message", "from", "server", "such", "as", "OK", "or", "Created", "etc", "." ]
train
https://github.com/javalite/activejdbc/blob/ffcf5457cace19622a8f71e856cbbbe9e7dd5fcc/javalite-common/src/main/java/org/javalite/http/Request.java#L122-L129
OpenLiberty/open-liberty
dev/com.ibm.ws.webcontainer.security/src/com/ibm/ws/webcontainer/security/internal/FormLoginExtensionProcessor.java
FormLoginExtensionProcessor.getStoredReq
@Sensitive private String getStoredReq(HttpServletRequest req, ReferrerURLCookieHandler referrerURLHandler) { """ Always be redirecting to a stored req with the web app... strip any initial slash @param req @param referrerURLHandler @return storedReq """ String storedReq = referrerURLHandler.getReferrerURLFromCookies(req, ReferrerURLCookieHandler.REFERRER_URL_COOKIENAME); if (storedReq != null) { if (storedReq.equals("/")) storedReq = ""; else if (storedReq.startsWith("/")) storedReq = storedReq.substring(1); } else { storedReq = ""; } return storedReq; }
java
@Sensitive private String getStoredReq(HttpServletRequest req, ReferrerURLCookieHandler referrerURLHandler) { String storedReq = referrerURLHandler.getReferrerURLFromCookies(req, ReferrerURLCookieHandler.REFERRER_URL_COOKIENAME); if (storedReq != null) { if (storedReq.equals("/")) storedReq = ""; else if (storedReq.startsWith("/")) storedReq = storedReq.substring(1); } else { storedReq = ""; } return storedReq; }
[ "@", "Sensitive", "private", "String", "getStoredReq", "(", "HttpServletRequest", "req", ",", "ReferrerURLCookieHandler", "referrerURLHandler", ")", "{", "String", "storedReq", "=", "referrerURLHandler", ".", "getReferrerURLFromCookies", "(", "req", ",", "ReferrerURLCookieHandler", ".", "REFERRER_URL_COOKIENAME", ")", ";", "if", "(", "storedReq", "!=", "null", ")", "{", "if", "(", "storedReq", ".", "equals", "(", "\"/\"", ")", ")", "storedReq", "=", "\"\"", ";", "else", "if", "(", "storedReq", ".", "startsWith", "(", "\"/\"", ")", ")", "storedReq", "=", "storedReq", ".", "substring", "(", "1", ")", ";", "}", "else", "{", "storedReq", "=", "\"\"", ";", "}", "return", "storedReq", ";", "}" ]
Always be redirecting to a stored req with the web app... strip any initial slash @param req @param referrerURLHandler @return storedReq
[ "Always", "be", "redirecting", "to", "a", "stored", "req", "with", "the", "web", "app", "...", "strip", "any", "initial", "slash" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.webcontainer.security/src/com/ibm/ws/webcontainer/security/internal/FormLoginExtensionProcessor.java#L241-L253
auth0/Lock.Android
lib/src/main/java/com/auth0/android/lock/views/ViewUtils.java
ViewUtils.getRoundedOutlineBackground
static ShapeDrawable getRoundedOutlineBackground(Resources resources, @ColorInt int color) { """ Generates a rounded outline drawable with the given background color. @param resources the context's current resources. @param color the color to use as background. @return the rounded drawable. """ int r = resources.getDimensionPixelSize(R.dimen.com_auth0_lock_widget_corner_radius); int t = resources.getDimensionPixelSize(R.dimen.com_auth0_lock_input_field_stroke_width); RoundRectShape rr = new RoundRectShape(new float[]{r, r, r, r, r, r, r, r}, new RectF(t, t, t, t), new float[]{r, r, r, r, r, r, r, r}); ShapeDrawable drawable = new ShapeDrawable(rr); drawable.getPaint().setColor(color); return drawable; }
java
static ShapeDrawable getRoundedOutlineBackground(Resources resources, @ColorInt int color) { int r = resources.getDimensionPixelSize(R.dimen.com_auth0_lock_widget_corner_radius); int t = resources.getDimensionPixelSize(R.dimen.com_auth0_lock_input_field_stroke_width); RoundRectShape rr = new RoundRectShape(new float[]{r, r, r, r, r, r, r, r}, new RectF(t, t, t, t), new float[]{r, r, r, r, r, r, r, r}); ShapeDrawable drawable = new ShapeDrawable(rr); drawable.getPaint().setColor(color); return drawable; }
[ "static", "ShapeDrawable", "getRoundedOutlineBackground", "(", "Resources", "resources", ",", "@", "ColorInt", "int", "color", ")", "{", "int", "r", "=", "resources", ".", "getDimensionPixelSize", "(", "R", ".", "dimen", ".", "com_auth0_lock_widget_corner_radius", ")", ";", "int", "t", "=", "resources", ".", "getDimensionPixelSize", "(", "R", ".", "dimen", ".", "com_auth0_lock_input_field_stroke_width", ")", ";", "RoundRectShape", "rr", "=", "new", "RoundRectShape", "(", "new", "float", "[", "]", "{", "r", ",", "r", ",", "r", ",", "r", ",", "r", ",", "r", ",", "r", ",", "r", "}", ",", "new", "RectF", "(", "t", ",", "t", ",", "t", ",", "t", ")", ",", "new", "float", "[", "]", "{", "r", ",", "r", ",", "r", ",", "r", ",", "r", ",", "r", ",", "r", ",", "r", "}", ")", ";", "ShapeDrawable", "drawable", "=", "new", "ShapeDrawable", "(", "rr", ")", ";", "drawable", ".", "getPaint", "(", ")", ".", "setColor", "(", "color", ")", ";", "return", "drawable", ";", "}" ]
Generates a rounded outline drawable with the given background color. @param resources the context's current resources. @param color the color to use as background. @return the rounded drawable.
[ "Generates", "a", "rounded", "outline", "drawable", "with", "the", "given", "background", "color", "." ]
train
https://github.com/auth0/Lock.Android/blob/8eb2a979048d2eb6cf0ec631e82e6c3fe6e7d220/lib/src/main/java/com/auth0/android/lock/views/ViewUtils.java#L122-L129
wildfly-extras/wildfly-camel
common/src/main/java/org/wildfly/camel/utils/IllegalStateAssertion.java
IllegalStateAssertion.assertSame
public static <T> T assertSame(T exp, T was, String message) { """ Throws an IllegalStateException when the given values are not equal. """ assertNotNull(exp, message); assertNotNull(was, message); assertTrue(exp == was, message); return was; }
java
public static <T> T assertSame(T exp, T was, String message) { assertNotNull(exp, message); assertNotNull(was, message); assertTrue(exp == was, message); return was; }
[ "public", "static", "<", "T", ">", "T", "assertSame", "(", "T", "exp", ",", "T", "was", ",", "String", "message", ")", "{", "assertNotNull", "(", "exp", ",", "message", ")", ";", "assertNotNull", "(", "was", ",", "message", ")", ";", "assertTrue", "(", "exp", "==", "was", ",", "message", ")", ";", "return", "was", ";", "}" ]
Throws an IllegalStateException when the given values are not equal.
[ "Throws", "an", "IllegalStateException", "when", "the", "given", "values", "are", "not", "equal", "." ]
train
https://github.com/wildfly-extras/wildfly-camel/blob/9ebd7e28574f277a6d5b583e8a4c357e1538c370/common/src/main/java/org/wildfly/camel/utils/IllegalStateAssertion.java#L86-L91
oehf/ipf-oht-atna
auditor/src/main/java/org/openhealthtools/ihe/atna/auditor/events/ihe/GenericIHEAuditEventMessage.java
GenericIHEAuditEventMessage.addDestinationActiveParticipant
public void addDestinationActiveParticipant(String userId, String altUserId, String userName, String networkId, boolean isRequestor) { """ Adds an Active Participant block representing the destination participant @param userId The Active Participant's User ID @param altUserId The Active Participant's Alternate UserID @param userName The Active Participant's UserName @param networkId The Active Participant's Network Access Point ID @param isRequestor Whether the participant represents the requestor """ addActiveParticipant( userId, altUserId, userName, isRequestor, Collections.singletonList(new DICOMActiveParticipantRoleIdCodes.Destination()), networkId); }
java
public void addDestinationActiveParticipant(String userId, String altUserId, String userName, String networkId, boolean isRequestor) { addActiveParticipant( userId, altUserId, userName, isRequestor, Collections.singletonList(new DICOMActiveParticipantRoleIdCodes.Destination()), networkId); }
[ "public", "void", "addDestinationActiveParticipant", "(", "String", "userId", ",", "String", "altUserId", ",", "String", "userName", ",", "String", "networkId", ",", "boolean", "isRequestor", ")", "{", "addActiveParticipant", "(", "userId", ",", "altUserId", ",", "userName", ",", "isRequestor", ",", "Collections", ".", "singletonList", "(", "new", "DICOMActiveParticipantRoleIdCodes", ".", "Destination", "(", ")", ")", ",", "networkId", ")", ";", "}" ]
Adds an Active Participant block representing the destination participant @param userId The Active Participant's User ID @param altUserId The Active Participant's Alternate UserID @param userName The Active Participant's UserName @param networkId The Active Participant's Network Access Point ID @param isRequestor Whether the participant represents the requestor
[ "Adds", "an", "Active", "Participant", "block", "representing", "the", "destination", "participant" ]
train
https://github.com/oehf/ipf-oht-atna/blob/25ed1e926825169c94923a2c89a4618f60478ae8/auditor/src/main/java/org/openhealthtools/ihe/atna/auditor/events/ihe/GenericIHEAuditEventMessage.java#L115-L124
groovy/groovy-core
src/main/org/codehaus/groovy/runtime/typehandling/ShortTypeHandling.java
ShortTypeHandling.castToEnum
public static Enum castToEnum(Object object, Class<? extends Enum> type) { """ this class requires that the supplied enum is not fitting a Collection case for casting """ if (object==null) return null; if (type.isInstance(object)) return (Enum) object; if (object instanceof String || object instanceof GString) { return Enum.valueOf(type, object.toString()); } throw new GroovyCastException(object, type); }
java
public static Enum castToEnum(Object object, Class<? extends Enum> type) { if (object==null) return null; if (type.isInstance(object)) return (Enum) object; if (object instanceof String || object instanceof GString) { return Enum.valueOf(type, object.toString()); } throw new GroovyCastException(object, type); }
[ "public", "static", "Enum", "castToEnum", "(", "Object", "object", ",", "Class", "<", "?", "extends", "Enum", ">", "type", ")", "{", "if", "(", "object", "==", "null", ")", "return", "null", ";", "if", "(", "type", ".", "isInstance", "(", "object", ")", ")", "return", "(", "Enum", ")", "object", ";", "if", "(", "object", "instanceof", "String", "||", "object", "instanceof", "GString", ")", "{", "return", "Enum", ".", "valueOf", "(", "type", ",", "object", ".", "toString", "(", ")", ")", ";", "}", "throw", "new", "GroovyCastException", "(", "object", ",", "type", ")", ";", "}" ]
this class requires that the supplied enum is not fitting a Collection case for casting
[ "this", "class", "requires", "that", "the", "supplied", "enum", "is", "not", "fitting", "a", "Collection", "case", "for", "casting" ]
train
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/runtime/typehandling/ShortTypeHandling.java#L52-L59
logic-ng/LogicNG
src/main/java/org/logicng/solvers/sat/MiniSatStyleSolver.java
MiniSatStyleSolver.varBumpActivity
protected void varBumpActivity(int v, double inc) { """ Bumps the activity of the variable at a given index by a given value. @param v the variable index @param inc the increment value """ final MSVariable var = this.vars.get(v); var.incrementActivity(inc); if (var.activity() > 1e100) { for (final MSVariable variable : this.vars) variable.rescaleActivity(); this.varInc *= 1e-100; } if (this.orderHeap.inHeap(v)) this.orderHeap.decrease(v); }
java
protected void varBumpActivity(int v, double inc) { final MSVariable var = this.vars.get(v); var.incrementActivity(inc); if (var.activity() > 1e100) { for (final MSVariable variable : this.vars) variable.rescaleActivity(); this.varInc *= 1e-100; } if (this.orderHeap.inHeap(v)) this.orderHeap.decrease(v); }
[ "protected", "void", "varBumpActivity", "(", "int", "v", ",", "double", "inc", ")", "{", "final", "MSVariable", "var", "=", "this", ".", "vars", ".", "get", "(", "v", ")", ";", "var", ".", "incrementActivity", "(", "inc", ")", ";", "if", "(", "var", ".", "activity", "(", ")", ">", "1e100", ")", "{", "for", "(", "final", "MSVariable", "variable", ":", "this", ".", "vars", ")", "variable", ".", "rescaleActivity", "(", ")", ";", "this", ".", "varInc", "*=", "1e-100", ";", "}", "if", "(", "this", ".", "orderHeap", ".", "inHeap", "(", "v", ")", ")", "this", ".", "orderHeap", ".", "decrease", "(", "v", ")", ";", "}" ]
Bumps the activity of the variable at a given index by a given value. @param v the variable index @param inc the increment value
[ "Bumps", "the", "activity", "of", "the", "variable", "at", "a", "given", "index", "by", "a", "given", "value", "." ]
train
https://github.com/logic-ng/LogicNG/blob/bb9eb88a768be4be8e02a76cfc4a59e6c3fb7f2e/src/main/java/org/logicng/solvers/sat/MiniSatStyleSolver.java#L482-L492
netscaler/sdx_nitro
src/main/java/com/citrix/sdx/nitro/resource/config/ns/ns_conf_revision_history.java
ns_conf_revision_history.get_nitro_bulk_response
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { """ <pre> Converts API response of bulk operation into object and returns the object array in case of get request. </pre> """ ns_conf_revision_history_responses result = (ns_conf_revision_history_responses) service.get_payload_formatter().string_to_resource(ns_conf_revision_history_responses.class, response); if(result.errorcode != 0) { if (result.errorcode == SESSION_NOT_EXISTS) service.clear_session(); throw new nitro_exception(result.message, result.errorcode, (base_response [])result.ns_conf_revision_history_response_array); } ns_conf_revision_history[] result_ns_conf_revision_history = new ns_conf_revision_history[result.ns_conf_revision_history_response_array.length]; for(int i = 0; i < result.ns_conf_revision_history_response_array.length; i++) { result_ns_conf_revision_history[i] = result.ns_conf_revision_history_response_array[i].ns_conf_revision_history[0]; } return result_ns_conf_revision_history; }
java
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { ns_conf_revision_history_responses result = (ns_conf_revision_history_responses) service.get_payload_formatter().string_to_resource(ns_conf_revision_history_responses.class, response); if(result.errorcode != 0) { if (result.errorcode == SESSION_NOT_EXISTS) service.clear_session(); throw new nitro_exception(result.message, result.errorcode, (base_response [])result.ns_conf_revision_history_response_array); } ns_conf_revision_history[] result_ns_conf_revision_history = new ns_conf_revision_history[result.ns_conf_revision_history_response_array.length]; for(int i = 0; i < result.ns_conf_revision_history_response_array.length; i++) { result_ns_conf_revision_history[i] = result.ns_conf_revision_history_response_array[i].ns_conf_revision_history[0]; } return result_ns_conf_revision_history; }
[ "protected", "base_resource", "[", "]", "get_nitro_bulk_response", "(", "nitro_service", "service", ",", "String", "response", ")", "throws", "Exception", "{", "ns_conf_revision_history_responses", "result", "=", "(", "ns_conf_revision_history_responses", ")", "service", ".", "get_payload_formatter", "(", ")", ".", "string_to_resource", "(", "ns_conf_revision_history_responses", ".", "class", ",", "response", ")", ";", "if", "(", "result", ".", "errorcode", "!=", "0", ")", "{", "if", "(", "result", ".", "errorcode", "==", "SESSION_NOT_EXISTS", ")", "service", ".", "clear_session", "(", ")", ";", "throw", "new", "nitro_exception", "(", "result", ".", "message", ",", "result", ".", "errorcode", ",", "(", "base_response", "[", "]", ")", "result", ".", "ns_conf_revision_history_response_array", ")", ";", "}", "ns_conf_revision_history", "[", "]", "result_ns_conf_revision_history", "=", "new", "ns_conf_revision_history", "[", "result", ".", "ns_conf_revision_history_response_array", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "result", ".", "ns_conf_revision_history_response_array", ".", "length", ";", "i", "++", ")", "{", "result_ns_conf_revision_history", "[", "i", "]", "=", "result", ".", "ns_conf_revision_history_response_array", "[", "i", "]", ".", "ns_conf_revision_history", "[", "0", "]", ";", "}", "return", "result_ns_conf_revision_history", ";", "}" ]
<pre> Converts API response of bulk operation into object and returns the object array in case of get request. </pre>
[ "<pre", ">", "Converts", "API", "response", "of", "bulk", "operation", "into", "object", "and", "returns", "the", "object", "array", "in", "case", "of", "get", "request", ".", "<", "/", "pre", ">" ]
train
https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/config/ns/ns_conf_revision_history.java#L221-L238
BorderTech/wcomponents
wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/WShufflerRenderer.java
WShufflerRenderer.doRender
@Override public void doRender(final WComponent component, final WebXmlRenderContext renderContext) { """ Paints the given WShuffler. @param component the WShuffler to paint. @param renderContext the RenderContext to paint to. """ WShuffler shuffler = (WShuffler) component; XmlStringBuilder xml = renderContext.getWriter(); boolean readOnly = shuffler.isReadOnly(); // Start tag xml.appendTagOpen("ui:shuffler"); xml.appendAttribute("id", component.getId()); xml.appendOptionalAttribute("class", component.getHtmlClass()); xml.appendOptionalAttribute("track", component.isTracking(), "true"); xml.appendOptionalAttribute("hidden", shuffler.isHidden(), "true"); if (readOnly) { xml.appendAttribute("readOnly", "true"); } else { xml.appendOptionalAttribute("disabled", shuffler.isDisabled(), "true"); xml.appendOptionalAttribute("toolTip", shuffler.getToolTip()); xml.appendOptionalAttribute("accessibleText", shuffler.getAccessibleText()); int rows = shuffler.getRows(); xml.appendOptionalAttribute("rows", rows > 0, rows); } xml.appendClose(); // Options List<?> options = shuffler.getOptions(); if (options != null && !options.isEmpty()) { for (int i = 0; i < options.size(); i++) { String stringOption = String.valueOf(options.get(i)); xml.appendTagOpen("ui:option"); xml.appendAttribute("value", stringOption); xml.appendClose(); xml.appendEscaped(stringOption); xml.appendEndTag("ui:option"); } } if (!readOnly) { DiagnosticRenderUtil.renderDiagnostics(shuffler, renderContext); } // End tag xml.appendEndTag("ui:shuffler"); }
java
@Override public void doRender(final WComponent component, final WebXmlRenderContext renderContext) { WShuffler shuffler = (WShuffler) component; XmlStringBuilder xml = renderContext.getWriter(); boolean readOnly = shuffler.isReadOnly(); // Start tag xml.appendTagOpen("ui:shuffler"); xml.appendAttribute("id", component.getId()); xml.appendOptionalAttribute("class", component.getHtmlClass()); xml.appendOptionalAttribute("track", component.isTracking(), "true"); xml.appendOptionalAttribute("hidden", shuffler.isHidden(), "true"); if (readOnly) { xml.appendAttribute("readOnly", "true"); } else { xml.appendOptionalAttribute("disabled", shuffler.isDisabled(), "true"); xml.appendOptionalAttribute("toolTip", shuffler.getToolTip()); xml.appendOptionalAttribute("accessibleText", shuffler.getAccessibleText()); int rows = shuffler.getRows(); xml.appendOptionalAttribute("rows", rows > 0, rows); } xml.appendClose(); // Options List<?> options = shuffler.getOptions(); if (options != null && !options.isEmpty()) { for (int i = 0; i < options.size(); i++) { String stringOption = String.valueOf(options.get(i)); xml.appendTagOpen("ui:option"); xml.appendAttribute("value", stringOption); xml.appendClose(); xml.appendEscaped(stringOption); xml.appendEndTag("ui:option"); } } if (!readOnly) { DiagnosticRenderUtil.renderDiagnostics(shuffler, renderContext); } // End tag xml.appendEndTag("ui:shuffler"); }
[ "@", "Override", "public", "void", "doRender", "(", "final", "WComponent", "component", ",", "final", "WebXmlRenderContext", "renderContext", ")", "{", "WShuffler", "shuffler", "=", "(", "WShuffler", ")", "component", ";", "XmlStringBuilder", "xml", "=", "renderContext", ".", "getWriter", "(", ")", ";", "boolean", "readOnly", "=", "shuffler", ".", "isReadOnly", "(", ")", ";", "// Start tag", "xml", ".", "appendTagOpen", "(", "\"ui:shuffler\"", ")", ";", "xml", ".", "appendAttribute", "(", "\"id\"", ",", "component", ".", "getId", "(", ")", ")", ";", "xml", ".", "appendOptionalAttribute", "(", "\"class\"", ",", "component", ".", "getHtmlClass", "(", ")", ")", ";", "xml", ".", "appendOptionalAttribute", "(", "\"track\"", ",", "component", ".", "isTracking", "(", ")", ",", "\"true\"", ")", ";", "xml", ".", "appendOptionalAttribute", "(", "\"hidden\"", ",", "shuffler", ".", "isHidden", "(", ")", ",", "\"true\"", ")", ";", "if", "(", "readOnly", ")", "{", "xml", ".", "appendAttribute", "(", "\"readOnly\"", ",", "\"true\"", ")", ";", "}", "else", "{", "xml", ".", "appendOptionalAttribute", "(", "\"disabled\"", ",", "shuffler", ".", "isDisabled", "(", ")", ",", "\"true\"", ")", ";", "xml", ".", "appendOptionalAttribute", "(", "\"toolTip\"", ",", "shuffler", ".", "getToolTip", "(", ")", ")", ";", "xml", ".", "appendOptionalAttribute", "(", "\"accessibleText\"", ",", "shuffler", ".", "getAccessibleText", "(", ")", ")", ";", "int", "rows", "=", "shuffler", ".", "getRows", "(", ")", ";", "xml", ".", "appendOptionalAttribute", "(", "\"rows\"", ",", "rows", ">", "0", ",", "rows", ")", ";", "}", "xml", ".", "appendClose", "(", ")", ";", "// Options", "List", "<", "?", ">", "options", "=", "shuffler", ".", "getOptions", "(", ")", ";", "if", "(", "options", "!=", "null", "&&", "!", "options", ".", "isEmpty", "(", ")", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "options", ".", "size", "(", ")", ";", "i", "++", ")", "{", "String", "stringOption", "=", "String", ".", "valueOf", "(", "options", ".", "get", "(", "i", ")", ")", ";", "xml", ".", "appendTagOpen", "(", "\"ui:option\"", ")", ";", "xml", ".", "appendAttribute", "(", "\"value\"", ",", "stringOption", ")", ";", "xml", ".", "appendClose", "(", ")", ";", "xml", ".", "appendEscaped", "(", "stringOption", ")", ";", "xml", ".", "appendEndTag", "(", "\"ui:option\"", ")", ";", "}", "}", "if", "(", "!", "readOnly", ")", "{", "DiagnosticRenderUtil", ".", "renderDiagnostics", "(", "shuffler", ",", "renderContext", ")", ";", "}", "// End tag", "xml", ".", "appendEndTag", "(", "\"ui:shuffler\"", ")", ";", "}" ]
Paints the given WShuffler. @param component the WShuffler to paint. @param renderContext the RenderContext to paint to.
[ "Paints", "the", "given", "WShuffler", "." ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/WShufflerRenderer.java#L24-L66
relayrides/pushy
pushy/src/main/java/com/turo/pushy/apns/util/ApnsPayloadBuilder.java
ApnsPayloadBuilder.setSound
public ApnsPayloadBuilder setSound(final String soundFileName, final boolean isCriticalAlert, final double soundVolume) { """ <p>Sets the name of the sound file to play when the push notification is received along with its volume and whether it should be presented as a critical alert. According to Apple's documentation, the sound filename should be:</p> <blockquote>The name of a sound file in your app’s main bundle or in the {@code Library/Sounds} folder of your app’s container directory.</blockquote> <p>By default, no sound is included in the push notification.</p> <p>To explicitly specify that no sound should be played as part of this notification, use {@link #setSound(String)} with a {@code null} sound filename.</p> @param soundFileName the name of the sound file to play; must not be {@code null} @param isCriticalAlert specifies whether this sound should be played as a "critical alert" @param soundVolume the volume at which to play the sound; must be between 0.0 (silent) and 1.0 (loudest) @return a reference to this payload builder @see ApnsPayloadBuilder#DEFAULT_SOUND_FILENAME @since 0.13.3 """ Objects.requireNonNull(soundFileName, "Sound file name must not be null."); if (soundVolume < 0 || soundVolume > 1) { throw new IllegalArgumentException("Sound volume must be between 0.0 and 1.0 (inclusive)."); } this.soundFileName = null; this.soundForCriticalAlert = new SoundForCriticalAlert(soundFileName, isCriticalAlert, soundVolume); return this; }
java
public ApnsPayloadBuilder setSound(final String soundFileName, final boolean isCriticalAlert, final double soundVolume) { Objects.requireNonNull(soundFileName, "Sound file name must not be null."); if (soundVolume < 0 || soundVolume > 1) { throw new IllegalArgumentException("Sound volume must be between 0.0 and 1.0 (inclusive)."); } this.soundFileName = null; this.soundForCriticalAlert = new SoundForCriticalAlert(soundFileName, isCriticalAlert, soundVolume); return this; }
[ "public", "ApnsPayloadBuilder", "setSound", "(", "final", "String", "soundFileName", ",", "final", "boolean", "isCriticalAlert", ",", "final", "double", "soundVolume", ")", "{", "Objects", ".", "requireNonNull", "(", "soundFileName", ",", "\"Sound file name must not be null.\"", ")", ";", "if", "(", "soundVolume", "<", "0", "||", "soundVolume", ">", "1", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Sound volume must be between 0.0 and 1.0 (inclusive).\"", ")", ";", "}", "this", ".", "soundFileName", "=", "null", ";", "this", ".", "soundForCriticalAlert", "=", "new", "SoundForCriticalAlert", "(", "soundFileName", ",", "isCriticalAlert", ",", "soundVolume", ")", ";", "return", "this", ";", "}" ]
<p>Sets the name of the sound file to play when the push notification is received along with its volume and whether it should be presented as a critical alert. According to Apple's documentation, the sound filename should be:</p> <blockquote>The name of a sound file in your app’s main bundle or in the {@code Library/Sounds} folder of your app’s container directory.</blockquote> <p>By default, no sound is included in the push notification.</p> <p>To explicitly specify that no sound should be played as part of this notification, use {@link #setSound(String)} with a {@code null} sound filename.</p> @param soundFileName the name of the sound file to play; must not be {@code null} @param isCriticalAlert specifies whether this sound should be played as a "critical alert" @param soundVolume the volume at which to play the sound; must be between 0.0 (silent) and 1.0 (loudest) @return a reference to this payload builder @see ApnsPayloadBuilder#DEFAULT_SOUND_FILENAME @since 0.13.3
[ "<p", ">", "Sets", "the", "name", "of", "the", "sound", "file", "to", "play", "when", "the", "push", "notification", "is", "received", "along", "with", "its", "volume", "and", "whether", "it", "should", "be", "presented", "as", "a", "critical", "alert", ".", "According", "to", "Apple", "s", "documentation", "the", "sound", "filename", "should", "be", ":", "<", "/", "p", ">" ]
train
https://github.com/relayrides/pushy/blob/1f6f9a0e07d785c815d74c2320a8d87c80231d36/pushy/src/main/java/com/turo/pushy/apns/util/ApnsPayloadBuilder.java#L469-L480
alkacon/opencms-core
src-gwt/org/opencms/gwt/client/ui/input/CmsCategoryField.java
CmsCategoryField.hasSelectedChildren
private boolean hasSelectedChildren(List<CmsCategoryTreeEntry> children, Collection<String> selectedCategories) { """ Checks if it has selected children.<p> @param children the children to check @param selectedCategories list of all selected categories @return true if it has selected children """ boolean result = false; if (children == null) { return false; } for (CmsCategoryTreeEntry child : children) { result = selectedCategories.contains(child.getSitePath()); if (result || hasSelectedChildren(child.getChildren(), selectedCategories)) { return true; } } return result; }
java
private boolean hasSelectedChildren(List<CmsCategoryTreeEntry> children, Collection<String> selectedCategories) { boolean result = false; if (children == null) { return false; } for (CmsCategoryTreeEntry child : children) { result = selectedCategories.contains(child.getSitePath()); if (result || hasSelectedChildren(child.getChildren(), selectedCategories)) { return true; } } return result; }
[ "private", "boolean", "hasSelectedChildren", "(", "List", "<", "CmsCategoryTreeEntry", ">", "children", ",", "Collection", "<", "String", ">", "selectedCategories", ")", "{", "boolean", "result", "=", "false", ";", "if", "(", "children", "==", "null", ")", "{", "return", "false", ";", "}", "for", "(", "CmsCategoryTreeEntry", "child", ":", "children", ")", "{", "result", "=", "selectedCategories", ".", "contains", "(", "child", ".", "getSitePath", "(", ")", ")", ";", "if", "(", "result", "||", "hasSelectedChildren", "(", "child", ".", "getChildren", "(", ")", ",", "selectedCategories", ")", ")", "{", "return", "true", ";", "}", "}", "return", "result", ";", "}" ]
Checks if it has selected children.<p> @param children the children to check @param selectedCategories list of all selected categories @return true if it has selected children
[ "Checks", "if", "it", "has", "selected", "children", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/ui/input/CmsCategoryField.java#L519-L533
lessthanoptimal/BoofCV
main/boofcv-geo/src/main/java/boofcv/alg/geo/pose/PoseFromPairLinear6.java
PoseFromPairLinear6.process
public boolean process( List<AssociatedPair> observations , List<Point3D_F64> locations ) { """ Computes the transformation between two camera frames using a linear equation. Both the observed feature locations in each camera image and the depth (z-coordinate) of each feature must be known. Feature locations are in calibrated image coordinates. @param observations List of observations on the image plane in calibrated coordinates. @param locations List of object locations. One for each observation pair. """ if( observations.size() != locations.size() ) throw new IllegalArgumentException("Number of observations and locations must match."); if( observations.size() < 6 ) throw new IllegalArgumentException("At least (if not more than) six points are required."); setupA(observations,locations); if( !solveNullspace.process(A,1,P)) return false; P.numRows = 3; P.numCols = 4; return true; }
java
public boolean process( List<AssociatedPair> observations , List<Point3D_F64> locations ) { if( observations.size() != locations.size() ) throw new IllegalArgumentException("Number of observations and locations must match."); if( observations.size() < 6 ) throw new IllegalArgumentException("At least (if not more than) six points are required."); setupA(observations,locations); if( !solveNullspace.process(A,1,P)) return false; P.numRows = 3; P.numCols = 4; return true; }
[ "public", "boolean", "process", "(", "List", "<", "AssociatedPair", ">", "observations", ",", "List", "<", "Point3D_F64", ">", "locations", ")", "{", "if", "(", "observations", ".", "size", "(", ")", "!=", "locations", ".", "size", "(", ")", ")", "throw", "new", "IllegalArgumentException", "(", "\"Number of observations and locations must match.\"", ")", ";", "if", "(", "observations", ".", "size", "(", ")", "<", "6", ")", "throw", "new", "IllegalArgumentException", "(", "\"At least (if not more than) six points are required.\"", ")", ";", "setupA", "(", "observations", ",", "locations", ")", ";", "if", "(", "!", "solveNullspace", ".", "process", "(", "A", ",", "1", ",", "P", ")", ")", "return", "false", ";", "P", ".", "numRows", "=", "3", ";", "P", ".", "numCols", "=", "4", ";", "return", "true", ";", "}" ]
Computes the transformation between two camera frames using a linear equation. Both the observed feature locations in each camera image and the depth (z-coordinate) of each feature must be known. Feature locations are in calibrated image coordinates. @param observations List of observations on the image plane in calibrated coordinates. @param locations List of object locations. One for each observation pair.
[ "Computes", "the", "transformation", "between", "two", "camera", "frames", "using", "a", "linear", "equation", ".", "Both", "the", "observed", "feature", "locations", "in", "each", "camera", "image", "and", "the", "depth", "(", "z", "-", "coordinate", ")", "of", "each", "feature", "must", "be", "known", ".", "Feature", "locations", "are", "in", "calibrated", "image", "coordinates", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/pose/PoseFromPairLinear6.java#L79-L95
Stratio/deep-spark
deep-cassandra/src/main/java/com/stratio/deep/cassandra/extractor/CassandraExtractor.java
CassandraExtractor.getPartitions
@Override public Partition[] getPartitions(S config) { """ Returns the partitions on which this RDD depends on. <p/> Uses the underlying CqlPagingInputFormat in order to retrieve the splits. <p/> The number of splits, and hence the number of partitions equals to the number of tokens configured in cassandra.yaml + 1. """ cassandraJobConfig = initConfig(config, cassandraJobConfig); List<DeepTokenRange> underlyingInputSplits = null; if(isFilterdByKey(cassandraJobConfig.getFilters(), cassandraJobConfig.fetchTableMetadata().getPartitionKey() .get(0).getName())) { underlyingInputSplits = new ArrayList<>(); underlyingInputSplits.add(new DeepTokenRange(Long.MIN_VALUE, Long.MAX_VALUE, cassandraJobConfig.getHostList())); }else{ if (cassandraJobConfig.isBisectModeSet()) { underlyingInputSplits = RangeUtils.getSplits(cassandraJobConfig); } else { underlyingInputSplits = ThriftRangeUtils.build(cassandraJobConfig).getSplits(); } } Partition[] partitions = new DeepPartition[underlyingInputSplits.size()]; int i = 0; for (DeepTokenRange split : underlyingInputSplits) { partitions[i] = new DeepPartition(cassandraJobConfig.getRddId(), i, split); // log().debug("Detected partition: " + partitions[i]); ++i; } return partitions; }
java
@Override public Partition[] getPartitions(S config) { cassandraJobConfig = initConfig(config, cassandraJobConfig); List<DeepTokenRange> underlyingInputSplits = null; if(isFilterdByKey(cassandraJobConfig.getFilters(), cassandraJobConfig.fetchTableMetadata().getPartitionKey() .get(0).getName())) { underlyingInputSplits = new ArrayList<>(); underlyingInputSplits.add(new DeepTokenRange(Long.MIN_VALUE, Long.MAX_VALUE, cassandraJobConfig.getHostList())); }else{ if (cassandraJobConfig.isBisectModeSet()) { underlyingInputSplits = RangeUtils.getSplits(cassandraJobConfig); } else { underlyingInputSplits = ThriftRangeUtils.build(cassandraJobConfig).getSplits(); } } Partition[] partitions = new DeepPartition[underlyingInputSplits.size()]; int i = 0; for (DeepTokenRange split : underlyingInputSplits) { partitions[i] = new DeepPartition(cassandraJobConfig.getRddId(), i, split); // log().debug("Detected partition: " + partitions[i]); ++i; } return partitions; }
[ "@", "Override", "public", "Partition", "[", "]", "getPartitions", "(", "S", "config", ")", "{", "cassandraJobConfig", "=", "initConfig", "(", "config", ",", "cassandraJobConfig", ")", ";", "List", "<", "DeepTokenRange", ">", "underlyingInputSplits", "=", "null", ";", "if", "(", "isFilterdByKey", "(", "cassandraJobConfig", ".", "getFilters", "(", ")", ",", "cassandraJobConfig", ".", "fetchTableMetadata", "(", ")", ".", "getPartitionKey", "(", ")", ".", "get", "(", "0", ")", ".", "getName", "(", ")", ")", ")", "{", "underlyingInputSplits", "=", "new", "ArrayList", "<>", "(", ")", ";", "underlyingInputSplits", ".", "add", "(", "new", "DeepTokenRange", "(", "Long", ".", "MIN_VALUE", ",", "Long", ".", "MAX_VALUE", ",", "cassandraJobConfig", ".", "getHostList", "(", ")", ")", ")", ";", "}", "else", "{", "if", "(", "cassandraJobConfig", ".", "isBisectModeSet", "(", ")", ")", "{", "underlyingInputSplits", "=", "RangeUtils", ".", "getSplits", "(", "cassandraJobConfig", ")", ";", "}", "else", "{", "underlyingInputSplits", "=", "ThriftRangeUtils", ".", "build", "(", "cassandraJobConfig", ")", ".", "getSplits", "(", ")", ";", "}", "}", "Partition", "[", "]", "partitions", "=", "new", "DeepPartition", "[", "underlyingInputSplits", ".", "size", "(", ")", "]", ";", "int", "i", "=", "0", ";", "for", "(", "DeepTokenRange", "split", ":", "underlyingInputSplits", ")", "{", "partitions", "[", "i", "]", "=", "new", "DeepPartition", "(", "cassandraJobConfig", ".", "getRddId", "(", ")", ",", "i", ",", "split", ")", ";", "// log().debug(\"Detected partition: \" + partitions[i]);", "++", "i", ";", "}", "return", "partitions", ";", "}" ]
Returns the partitions on which this RDD depends on. <p/> Uses the underlying CqlPagingInputFormat in order to retrieve the splits. <p/> The number of splits, and hence the number of partitions equals to the number of tokens configured in cassandra.yaml + 1.
[ "Returns", "the", "partitions", "on", "which", "this", "RDD", "depends", "on", ".", "<p", "/", ">", "Uses", "the", "underlying", "CqlPagingInputFormat", "in", "order", "to", "retrieve", "the", "splits", ".", "<p", "/", ">", "The", "number", "of", "splits", "and", "hence", "the", "number", "of", "partitions", "equals", "to", "the", "number", "of", "tokens", "configured", "in", "cassandra", ".", "yaml", "+", "1", "." ]
train
https://github.com/Stratio/deep-spark/blob/b9621c9b7a6d996f80fce1d073d696a157bed095/deep-cassandra/src/main/java/com/stratio/deep/cassandra/extractor/CassandraExtractor.java#L111-L142