repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
218
func_name
stringlengths
4
140
whole_func_string
stringlengths
153
5.32k
language
stringclasses
1 value
func_code_string
stringlengths
72
4k
func_code_tokens
listlengths
20
832
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
listlengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
102
339
sporniket/core
sporniket-core-ml/src/main/java/com/sporniket/libre/lang/xml/XmlStringTools.java
XmlStringTools.doAppendClosingTag
private static StringBuffer doAppendClosingTag(StringBuffer buffer, String tag) { """ Add a closing tag to a StringBuffer. If the buffer is null, a new one is created. @param buffer StringBuffer to fill @param tag the tag to close @return the buffer """ buffer.append(SEQUENCE__TAG__BEGIN_CLOSING_TAG).append(tag).append(SEQUENCE__TAG__END_OF_TAG); return buffer; }
java
private static StringBuffer doAppendClosingTag(StringBuffer buffer, String tag) { buffer.append(SEQUENCE__TAG__BEGIN_CLOSING_TAG).append(tag).append(SEQUENCE__TAG__END_OF_TAG); return buffer; }
[ "private", "static", "StringBuffer", "doAppendClosingTag", "(", "StringBuffer", "buffer", ",", "String", "tag", ")", "{", "buffer", ".", "append", "(", "SEQUENCE__TAG__BEGIN_CLOSING_TAG", ")", ".", "append", "(", "tag", ")", ".", "append", "(", "SEQUENCE__TAG__END_OF_TAG", ")", ";", "return", "buffer", ";", "}" ]
Add a closing tag to a StringBuffer. If the buffer is null, a new one is created. @param buffer StringBuffer to fill @param tag the tag to close @return the buffer
[ "Add", "a", "closing", "tag", "to", "a", "StringBuffer", "." ]
train
https://github.com/sporniket/core/blob/3480ebd72a07422fcc09971be2607ee25efb2c26/sporniket-core-ml/src/main/java/com/sporniket/libre/lang/xml/XmlStringTools.java#L453-L457
samskivert/pythagoras
src/main/java/pythagoras/f/Matrix4.java
Matrix4.setToRotation
public Matrix4 setToRotation (IVector3 from, IVector3 to) { """ Sets this to a rotation matrix that rotates one vector onto another. @return a reference to this matrix, for chaining. """ float angle = from.angle(to); if (angle < MathUtil.EPSILON) { return setToIdentity(); } if (angle <= FloatMath.PI - MathUtil.EPSILON) { return setToRotation(angle, from.cross(to).normalizeLocal()); } // it's a 180 degree rotation; any axis orthogonal to the from vector will do Vector3 axis = new Vector3(0f, from.z(), -from.y()); float length = axis.length(); return setToRotation(FloatMath.PI, length < MathUtil.EPSILON ? axis.set(-from.z(), 0f, from.x()).normalizeLocal() : axis.multLocal(1f / length)); }
java
public Matrix4 setToRotation (IVector3 from, IVector3 to) { float angle = from.angle(to); if (angle < MathUtil.EPSILON) { return setToIdentity(); } if (angle <= FloatMath.PI - MathUtil.EPSILON) { return setToRotation(angle, from.cross(to).normalizeLocal()); } // it's a 180 degree rotation; any axis orthogonal to the from vector will do Vector3 axis = new Vector3(0f, from.z(), -from.y()); float length = axis.length(); return setToRotation(FloatMath.PI, length < MathUtil.EPSILON ? axis.set(-from.z(), 0f, from.x()).normalizeLocal() : axis.multLocal(1f / length)); }
[ "public", "Matrix4", "setToRotation", "(", "IVector3", "from", ",", "IVector3", "to", ")", "{", "float", "angle", "=", "from", ".", "angle", "(", "to", ")", ";", "if", "(", "angle", "<", "MathUtil", ".", "EPSILON", ")", "{", "return", "setToIdentity", "(", ")", ";", "}", "if", "(", "angle", "<=", "FloatMath", ".", "PI", "-", "MathUtil", ".", "EPSILON", ")", "{", "return", "setToRotation", "(", "angle", ",", "from", ".", "cross", "(", "to", ")", ".", "normalizeLocal", "(", ")", ")", ";", "}", "// it's a 180 degree rotation; any axis orthogonal to the from vector will do", "Vector3", "axis", "=", "new", "Vector3", "(", "0f", ",", "from", ".", "z", "(", ")", ",", "-", "from", ".", "y", "(", ")", ")", ";", "float", "length", "=", "axis", ".", "length", "(", ")", ";", "return", "setToRotation", "(", "FloatMath", ".", "PI", ",", "length", "<", "MathUtil", ".", "EPSILON", "?", "axis", ".", "set", "(", "-", "from", ".", "z", "(", ")", ",", "0f", ",", "from", ".", "x", "(", ")", ")", ".", "normalizeLocal", "(", ")", ":", "axis", ".", "multLocal", "(", "1f", "/", "length", ")", ")", ";", "}" ]
Sets this to a rotation matrix that rotates one vector onto another. @return a reference to this matrix, for chaining.
[ "Sets", "this", "to", "a", "rotation", "matrix", "that", "rotates", "one", "vector", "onto", "another", "." ]
train
https://github.com/samskivert/pythagoras/blob/b8fea743ee8a7d742ad9c06ee4f11f50571fbd32/src/main/java/pythagoras/f/Matrix4.java#L181-L195
jayantk/jklol
src/com/jayantkrish/jklol/ccg/lambda2/TypeReplacement.java
TypeReplacement.add
public void add(int var, Type t) { """ Compose (var -> t) with this replacement. Any occurrences of var in this replacement are substituted with t. @param var @param t """ Set<Integer> tVars = t.getTypeVariables(); Set<Integer> intersection = Sets.intersection(tVars, bindings.keySet()); Preconditions.checkArgument(intersection.size() == 0, "Tried to replace %s with %s, but already have bindings for %s", var, t, intersection); Preconditions.checkArgument(!tVars.contains(var), "Recursive replacement: tried to replace %s with %s", var, t); Map<Integer, Type> newBinding = Maps.newHashMap(); newBinding.put(var, t); for (int boundVar : bindings.keySet()) { bindings.put(boundVar, bindings.get(boundVar).substitute(newBinding)); } bindings.put(var, t); }
java
public void add(int var, Type t) { Set<Integer> tVars = t.getTypeVariables(); Set<Integer> intersection = Sets.intersection(tVars, bindings.keySet()); Preconditions.checkArgument(intersection.size() == 0, "Tried to replace %s with %s, but already have bindings for %s", var, t, intersection); Preconditions.checkArgument(!tVars.contains(var), "Recursive replacement: tried to replace %s with %s", var, t); Map<Integer, Type> newBinding = Maps.newHashMap(); newBinding.put(var, t); for (int boundVar : bindings.keySet()) { bindings.put(boundVar, bindings.get(boundVar).substitute(newBinding)); } bindings.put(var, t); }
[ "public", "void", "add", "(", "int", "var", ",", "Type", "t", ")", "{", "Set", "<", "Integer", ">", "tVars", "=", "t", ".", "getTypeVariables", "(", ")", ";", "Set", "<", "Integer", ">", "intersection", "=", "Sets", ".", "intersection", "(", "tVars", ",", "bindings", ".", "keySet", "(", ")", ")", ";", "Preconditions", ".", "checkArgument", "(", "intersection", ".", "size", "(", ")", "==", "0", ",", "\"Tried to replace %s with %s, but already have bindings for %s\"", ",", "var", ",", "t", ",", "intersection", ")", ";", "Preconditions", ".", "checkArgument", "(", "!", "tVars", ".", "contains", "(", "var", ")", ",", "\"Recursive replacement: tried to replace %s with %s\"", ",", "var", ",", "t", ")", ";", "Map", "<", "Integer", ",", "Type", ">", "newBinding", "=", "Maps", ".", "newHashMap", "(", ")", ";", "newBinding", ".", "put", "(", "var", ",", "t", ")", ";", "for", "(", "int", "boundVar", ":", "bindings", ".", "keySet", "(", ")", ")", "{", "bindings", ".", "put", "(", "boundVar", ",", "bindings", ".", "get", "(", "boundVar", ")", ".", "substitute", "(", "newBinding", ")", ")", ";", "}", "bindings", ".", "put", "(", "var", ",", "t", ")", ";", "}" ]
Compose (var -> t) with this replacement. Any occurrences of var in this replacement are substituted with t. @param var @param t
[ "Compose", "(", "var", "-", ">", "t", ")", "with", "this", "replacement", ".", "Any", "occurrences", "of", "var", "in", "this", "replacement", "are", "substituted", "with", "t", "." ]
train
https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/ccg/lambda2/TypeReplacement.java#L36-L50
opendatatrentino/s-match
src/main/java/it/unitn/disi/smatch/oracles/wordnet/InMemoryWordNetBinaryArray.java
InMemoryWordNetBinaryArray.createWordNetCaches
public static void createWordNetCaches(String componentKey, Properties properties) throws SMatchException { """ Create caches of WordNet to speed up matching. @param componentKey a key to the component in the configuration @param properties configuration @throws SMatchException SMatchException """ properties = getComponentProperties(makeComponentPrefix(componentKey, InMemoryWordNetBinaryArray.class.getSimpleName()), properties); if (properties.containsKey(JWNL_PROPERTIES_PATH_KEY)) { // initialize JWNL (this must be done before JWNL library can be used) try { final String configPath = properties.getProperty(JWNL_PROPERTIES_PATH_KEY); log.info("Initializing JWNL from " + configPath); JWNL.initialize(new FileInputStream(configPath)); } catch (JWNLException e) { final String errMessage = e.getClass().getSimpleName() + ": " + e.getMessage(); log.error(errMessage, e); throw new SMatchException(errMessage, e); } catch (FileNotFoundException e) { final String errMessage = e.getClass().getSimpleName() + ": " + e.getMessage(); log.error(errMessage, e); throw new SMatchException(errMessage, e); } } else { final String errMessage = "Cannot find configuration key " + JWNL_PROPERTIES_PATH_KEY; log.error(errMessage); throw new SMatchException(errMessage); } log.info("Creating WordNet caches..."); writeNominalizations(properties); writeSynonymsAdj(properties); writeOppAdverbs(properties); writeOppAdjectives(properties); writeOppNouns(properties); writeNounMG(properties); writeVerbMG(properties); log.info("Done"); }
java
public static void createWordNetCaches(String componentKey, Properties properties) throws SMatchException { properties = getComponentProperties(makeComponentPrefix(componentKey, InMemoryWordNetBinaryArray.class.getSimpleName()), properties); if (properties.containsKey(JWNL_PROPERTIES_PATH_KEY)) { // initialize JWNL (this must be done before JWNL library can be used) try { final String configPath = properties.getProperty(JWNL_PROPERTIES_PATH_KEY); log.info("Initializing JWNL from " + configPath); JWNL.initialize(new FileInputStream(configPath)); } catch (JWNLException e) { final String errMessage = e.getClass().getSimpleName() + ": " + e.getMessage(); log.error(errMessage, e); throw new SMatchException(errMessage, e); } catch (FileNotFoundException e) { final String errMessage = e.getClass().getSimpleName() + ": " + e.getMessage(); log.error(errMessage, e); throw new SMatchException(errMessage, e); } } else { final String errMessage = "Cannot find configuration key " + JWNL_PROPERTIES_PATH_KEY; log.error(errMessage); throw new SMatchException(errMessage); } log.info("Creating WordNet caches..."); writeNominalizations(properties); writeSynonymsAdj(properties); writeOppAdverbs(properties); writeOppAdjectives(properties); writeOppNouns(properties); writeNounMG(properties); writeVerbMG(properties); log.info("Done"); }
[ "public", "static", "void", "createWordNetCaches", "(", "String", "componentKey", ",", "Properties", "properties", ")", "throws", "SMatchException", "{", "properties", "=", "getComponentProperties", "(", "makeComponentPrefix", "(", "componentKey", ",", "InMemoryWordNetBinaryArray", ".", "class", ".", "getSimpleName", "(", ")", ")", ",", "properties", ")", ";", "if", "(", "properties", ".", "containsKey", "(", "JWNL_PROPERTIES_PATH_KEY", ")", ")", "{", "// initialize JWNL (this must be done before JWNL library can be used)\r", "try", "{", "final", "String", "configPath", "=", "properties", ".", "getProperty", "(", "JWNL_PROPERTIES_PATH_KEY", ")", ";", "log", ".", "info", "(", "\"Initializing JWNL from \"", "+", "configPath", ")", ";", "JWNL", ".", "initialize", "(", "new", "FileInputStream", "(", "configPath", ")", ")", ";", "}", "catch", "(", "JWNLException", "e", ")", "{", "final", "String", "errMessage", "=", "e", ".", "getClass", "(", ")", ".", "getSimpleName", "(", ")", "+", "\": \"", "+", "e", ".", "getMessage", "(", ")", ";", "log", ".", "error", "(", "errMessage", ",", "e", ")", ";", "throw", "new", "SMatchException", "(", "errMessage", ",", "e", ")", ";", "}", "catch", "(", "FileNotFoundException", "e", ")", "{", "final", "String", "errMessage", "=", "e", ".", "getClass", "(", ")", ".", "getSimpleName", "(", ")", "+", "\": \"", "+", "e", ".", "getMessage", "(", ")", ";", "log", ".", "error", "(", "errMessage", ",", "e", ")", ";", "throw", "new", "SMatchException", "(", "errMessage", ",", "e", ")", ";", "}", "}", "else", "{", "final", "String", "errMessage", "=", "\"Cannot find configuration key \"", "+", "JWNL_PROPERTIES_PATH_KEY", ";", "log", ".", "error", "(", "errMessage", ")", ";", "throw", "new", "SMatchException", "(", "errMessage", ")", ";", "}", "log", ".", "info", "(", "\"Creating WordNet caches...\"", ")", ";", "writeNominalizations", "(", "properties", ")", ";", "writeSynonymsAdj", "(", "properties", ")", ";", "writeOppAdverbs", "(", "properties", ")", ";", "writeOppAdjectives", "(", "properties", ")", ";", "writeOppNouns", "(", "properties", ")", ";", "writeNounMG", "(", "properties", ")", ";", "writeVerbMG", "(", "properties", ")", ";", "log", ".", "info", "(", "\"Done\"", ")", ";", "}" ]
Create caches of WordNet to speed up matching. @param componentKey a key to the component in the configuration @param properties configuration @throws SMatchException SMatchException
[ "Create", "caches", "of", "WordNet", "to", "speed", "up", "matching", "." ]
train
https://github.com/opendatatrentino/s-match/blob/ba5982ef406b7010c2f92592e43887a485935aa1/src/main/java/it/unitn/disi/smatch/oracles/wordnet/InMemoryWordNetBinaryArray.java#L261-L293
jmeetsma/Iglu-Util
src/main/java/org/ijsberg/iglu/util/misc/StringSupport.java
StringSupport.replaceAll
public static void replaceAll(StringBuffer haystack, String needle, String newNeedle, int interval) { """ default is 0, which means that all found characters must be replaced """ if (needle == null) { throw new IllegalArgumentException("string to replace can not be empty"); } int idx = haystack.indexOf(needle); int nextIdx = -1; int processedChunkSize = idx; int needleLength = needle.length(); int newNeedleLength = newNeedle.length(); while (idx != -1/* && idx < haystack.length()*/) { if (processedChunkSize >= interval) { haystack.replace(idx, idx + needleLength, newNeedle); nextIdx = haystack.indexOf(needle, idx + newNeedleLength); processedChunkSize = nextIdx - idx;//length of replacement is not included idx = nextIdx; } else { nextIdx = haystack.indexOf(needle, idx + newNeedleLength); processedChunkSize += nextIdx - idx; idx = nextIdx; if (newNeedleLength == 0) { return; } } } }
java
public static void replaceAll(StringBuffer haystack, String needle, String newNeedle, int interval) { if (needle == null) { throw new IllegalArgumentException("string to replace can not be empty"); } int idx = haystack.indexOf(needle); int nextIdx = -1; int processedChunkSize = idx; int needleLength = needle.length(); int newNeedleLength = newNeedle.length(); while (idx != -1/* && idx < haystack.length()*/) { if (processedChunkSize >= interval) { haystack.replace(idx, idx + needleLength, newNeedle); nextIdx = haystack.indexOf(needle, idx + newNeedleLength); processedChunkSize = nextIdx - idx;//length of replacement is not included idx = nextIdx; } else { nextIdx = haystack.indexOf(needle, idx + newNeedleLength); processedChunkSize += nextIdx - idx; idx = nextIdx; if (newNeedleLength == 0) { return; } } } }
[ "public", "static", "void", "replaceAll", "(", "StringBuffer", "haystack", ",", "String", "needle", ",", "String", "newNeedle", ",", "int", "interval", ")", "{", "if", "(", "needle", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"string to replace can not be empty\"", ")", ";", "}", "int", "idx", "=", "haystack", ".", "indexOf", "(", "needle", ")", ";", "int", "nextIdx", "=", "-", "1", ";", "int", "processedChunkSize", "=", "idx", ";", "int", "needleLength", "=", "needle", ".", "length", "(", ")", ";", "int", "newNeedleLength", "=", "newNeedle", ".", "length", "(", ")", ";", "while", "(", "idx", "!=", "-", "1", "/* && idx < haystack.length()*/", ")", "{", "if", "(", "processedChunkSize", ">=", "interval", ")", "{", "haystack", ".", "replace", "(", "idx", ",", "idx", "+", "needleLength", ",", "newNeedle", ")", ";", "nextIdx", "=", "haystack", ".", "indexOf", "(", "needle", ",", "idx", "+", "newNeedleLength", ")", ";", "processedChunkSize", "=", "nextIdx", "-", "idx", ";", "//length of replacement is not included", "idx", "=", "nextIdx", ";", "}", "else", "{", "nextIdx", "=", "haystack", ".", "indexOf", "(", "needle", ",", "idx", "+", "newNeedleLength", ")", ";", "processedChunkSize", "+=", "nextIdx", "-", "idx", ";", "idx", "=", "nextIdx", ";", "if", "(", "newNeedleLength", "==", "0", ")", "{", "return", ";", "}", "}", "}", "}" ]
default is 0, which means that all found characters must be replaced
[ "default", "is", "0", "which", "means", "that", "all", "found", "characters", "must", "be", "replaced" ]
train
https://github.com/jmeetsma/Iglu-Util/blob/971eb022115247b1e34dc26dd02e7e621e29e910/src/main/java/org/ijsberg/iglu/util/misc/StringSupport.java#L159-L184
Netflix/eureka
eureka-client/src/main/java/com/netflix/discovery/util/DeserializerStringCache.java
DeserializerStringCache.init
public static ObjectReader init(ObjectReader reader) { """ adds a new DeserializerStringCache to the passed-in ObjectReader @param reader @return a wrapped ObjectReader with the string cache attribute """ return reader.withAttribute(ATTR_STRING_CACHE, new DeserializerStringCache( new HashMap<CharBuffer, String>(2048), new LinkedHashMap<CharBuffer, String>(4096, 0.75f, true) { @Override protected boolean removeEldestEntry(Entry<CharBuffer, String> eldest) { return size() > LRU_LIMIT; } })); }
java
public static ObjectReader init(ObjectReader reader) { return reader.withAttribute(ATTR_STRING_CACHE, new DeserializerStringCache( new HashMap<CharBuffer, String>(2048), new LinkedHashMap<CharBuffer, String>(4096, 0.75f, true) { @Override protected boolean removeEldestEntry(Entry<CharBuffer, String> eldest) { return size() > LRU_LIMIT; } })); }
[ "public", "static", "ObjectReader", "init", "(", "ObjectReader", "reader", ")", "{", "return", "reader", ".", "withAttribute", "(", "ATTR_STRING_CACHE", ",", "new", "DeserializerStringCache", "(", "new", "HashMap", "<", "CharBuffer", ",", "String", ">", "(", "2048", ")", ",", "new", "LinkedHashMap", "<", "CharBuffer", ",", "String", ">", "(", "4096", ",", "0.75f", ",", "true", ")", "{", "@", "Override", "protected", "boolean", "removeEldestEntry", "(", "Entry", "<", "CharBuffer", ",", "String", ">", "eldest", ")", "{", "return", "size", "(", ")", ">", "LRU_LIMIT", ";", "}", "}", ")", ")", ";", "}" ]
adds a new DeserializerStringCache to the passed-in ObjectReader @param reader @return a wrapped ObjectReader with the string cache attribute
[ "adds", "a", "new", "DeserializerStringCache", "to", "the", "passed", "-", "in", "ObjectReader" ]
train
https://github.com/Netflix/eureka/blob/48446d956be09df6650a3c00b7ebd7e2d1e1544f/eureka-client/src/main/java/com/netflix/discovery/util/DeserializerStringCache.java#L54-L63
comapi/comapi-chat-sdk-android
COMAPI/chat/src/main/java/com/comapi/chat/ChatController.java
ChatController.handleNoLocalConversation
Observable<ChatResult> handleNoLocalConversation(String conversationId) { """ When SDK detects missing conversation it makes query in services and saves in the saves locally. @param conversationId Unique identifier of an conversation. @return Observable to handle missing local conversation data. """ return checkState().flatMap(client -> client.service().messaging().getConversation(conversationId) .flatMap(result -> { if (result.isSuccessful() && result.getResult() != null) { return persistenceController.upsertConversation(ChatConversation.builder().populate(result.getResult(), result.getETag()).build()) .map(success -> new ChatResult(success, success ? null : new ChatResult.Error(0, "External store reported failure.", "Error when inserting conversation "+conversationId))); } else { return Observable.fromCallable(() -> adapter.adaptResult(result)); } })); }
java
Observable<ChatResult> handleNoLocalConversation(String conversationId) { return checkState().flatMap(client -> client.service().messaging().getConversation(conversationId) .flatMap(result -> { if (result.isSuccessful() && result.getResult() != null) { return persistenceController.upsertConversation(ChatConversation.builder().populate(result.getResult(), result.getETag()).build()) .map(success -> new ChatResult(success, success ? null : new ChatResult.Error(0, "External store reported failure.", "Error when inserting conversation "+conversationId))); } else { return Observable.fromCallable(() -> adapter.adaptResult(result)); } })); }
[ "Observable", "<", "ChatResult", ">", "handleNoLocalConversation", "(", "String", "conversationId", ")", "{", "return", "checkState", "(", ")", ".", "flatMap", "(", "client", "->", "client", ".", "service", "(", ")", ".", "messaging", "(", ")", ".", "getConversation", "(", "conversationId", ")", ".", "flatMap", "(", "result", "->", "{", "if", "(", "result", ".", "isSuccessful", "(", ")", "&&", "result", ".", "getResult", "(", ")", "!=", "null", ")", "{", "return", "persistenceController", ".", "upsertConversation", "(", "ChatConversation", ".", "builder", "(", ")", ".", "populate", "(", "result", ".", "getResult", "(", ")", ",", "result", ".", "getETag", "(", ")", ")", ".", "build", "(", ")", ")", ".", "map", "(", "success", "->", "new", "ChatResult", "(", "success", ",", "success", "?", "null", ":", "new", "ChatResult", ".", "Error", "(", "0", ",", "\"External store reported failure.\"", ",", "\"Error when inserting conversation \"", "+", "conversationId", ")", ")", ")", ";", "}", "else", "{", "return", "Observable", ".", "fromCallable", "(", "(", ")", "->", "adapter", ".", "adaptResult", "(", "result", ")", ")", ";", "}", "}", ")", ")", ";", "}" ]
When SDK detects missing conversation it makes query in services and saves in the saves locally. @param conversationId Unique identifier of an conversation. @return Observable to handle missing local conversation data.
[ "When", "SDK", "detects", "missing", "conversation", "it", "makes", "query", "in", "services", "and", "saves", "in", "the", "saves", "locally", "." ]
train
https://github.com/comapi/comapi-chat-sdk-android/blob/388f37bfacb7793ce30c92ab70e5f32848bbe460/COMAPI/chat/src/main/java/com/comapi/chat/ChatController.java#L245-L256
lessthanoptimal/BoofCV
main/boofcv-sfm/src/main/java/boofcv/alg/sfm/structure2/ProjectiveInitializeAllCommon.java
ProjectiveInitializeAllCommon.createObservationsForBundleAdjustment
private SceneObservations createObservationsForBundleAdjustment(LookupSimilarImages db, View seed, GrowQueue_I32 motions) { """ Convert observations into a format which bundle adjustment will understand @param seed The first view which all other views are connected to @param motions Which edges in seed @return observations for SBA """ // seed view + the motions SceneObservations observations = new SceneObservations(motions.size+1); // Observations for the seed view are a special case SceneObservations.View obsView = observations.getView(0); for (int i = 0; i < inlierToSeed.size; i++) { int id = inlierToSeed.data[i]; Point2D_F64 o = featsA.get(id); // featsA is never modified after initially loaded id = seedToStructure.data[id]; obsView.add(id,(float)o.x,(float)o.y); } // Now add observations for edges connected to the seed for (int i = 0; i < motions.size(); i++) { obsView = observations.getView(i+1); Motion m = seed.connections.get(motions.get(i)); View v = m.other(seed); boolean seedIsSrc = m.src == seed; db.lookupPixelFeats(v.id,featsB); for (int j = 0; j < m.inliers.size; j++) { AssociatedIndex a = m.inliers.get(j); int id = seedToStructure.data[seedIsSrc?a.src:a.dst]; if( id < 0 ) continue; Point2D_F64 o = featsB.get(seedIsSrc?a.dst:a.src); obsView.add(id,(float)o.x,(float)o.y); } } return observations; }
java
private SceneObservations createObservationsForBundleAdjustment(LookupSimilarImages db, View seed, GrowQueue_I32 motions) { // seed view + the motions SceneObservations observations = new SceneObservations(motions.size+1); // Observations for the seed view are a special case SceneObservations.View obsView = observations.getView(0); for (int i = 0; i < inlierToSeed.size; i++) { int id = inlierToSeed.data[i]; Point2D_F64 o = featsA.get(id); // featsA is never modified after initially loaded id = seedToStructure.data[id]; obsView.add(id,(float)o.x,(float)o.y); } // Now add observations for edges connected to the seed for (int i = 0; i < motions.size(); i++) { obsView = observations.getView(i+1); Motion m = seed.connections.get(motions.get(i)); View v = m.other(seed); boolean seedIsSrc = m.src == seed; db.lookupPixelFeats(v.id,featsB); for (int j = 0; j < m.inliers.size; j++) { AssociatedIndex a = m.inliers.get(j); int id = seedToStructure.data[seedIsSrc?a.src:a.dst]; if( id < 0 ) continue; Point2D_F64 o = featsB.get(seedIsSrc?a.dst:a.src); obsView.add(id,(float)o.x,(float)o.y); } } return observations; }
[ "private", "SceneObservations", "createObservationsForBundleAdjustment", "(", "LookupSimilarImages", "db", ",", "View", "seed", ",", "GrowQueue_I32", "motions", ")", "{", "// seed view + the motions", "SceneObservations", "observations", "=", "new", "SceneObservations", "(", "motions", ".", "size", "+", "1", ")", ";", "// Observations for the seed view are a special case", "SceneObservations", ".", "View", "obsView", "=", "observations", ".", "getView", "(", "0", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "inlierToSeed", ".", "size", ";", "i", "++", ")", "{", "int", "id", "=", "inlierToSeed", ".", "data", "[", "i", "]", ";", "Point2D_F64", "o", "=", "featsA", ".", "get", "(", "id", ")", ";", "// featsA is never modified after initially loaded", "id", "=", "seedToStructure", ".", "data", "[", "id", "]", ";", "obsView", ".", "add", "(", "id", ",", "(", "float", ")", "o", ".", "x", ",", "(", "float", ")", "o", ".", "y", ")", ";", "}", "// Now add observations for edges connected to the seed", "for", "(", "int", "i", "=", "0", ";", "i", "<", "motions", ".", "size", "(", ")", ";", "i", "++", ")", "{", "obsView", "=", "observations", ".", "getView", "(", "i", "+", "1", ")", ";", "Motion", "m", "=", "seed", ".", "connections", ".", "get", "(", "motions", ".", "get", "(", "i", ")", ")", ";", "View", "v", "=", "m", ".", "other", "(", "seed", ")", ";", "boolean", "seedIsSrc", "=", "m", ".", "src", "==", "seed", ";", "db", ".", "lookupPixelFeats", "(", "v", ".", "id", ",", "featsB", ")", ";", "for", "(", "int", "j", "=", "0", ";", "j", "<", "m", ".", "inliers", ".", "size", ";", "j", "++", ")", "{", "AssociatedIndex", "a", "=", "m", ".", "inliers", ".", "get", "(", "j", ")", ";", "int", "id", "=", "seedToStructure", ".", "data", "[", "seedIsSrc", "?", "a", ".", "src", ":", "a", ".", "dst", "]", ";", "if", "(", "id", "<", "0", ")", "continue", ";", "Point2D_F64", "o", "=", "featsB", ".", "get", "(", "seedIsSrc", "?", "a", ".", "dst", ":", "a", ".", "src", ")", ";", "obsView", ".", "add", "(", "id", ",", "(", "float", ")", "o", ".", "x", ",", "(", "float", ")", "o", ".", "y", ")", ";", "}", "}", "return", "observations", ";", "}" ]
Convert observations into a format which bundle adjustment will understand @param seed The first view which all other views are connected to @param motions Which edges in seed @return observations for SBA
[ "Convert", "observations", "into", "a", "format", "which", "bundle", "adjustment", "will", "understand" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-sfm/src/main/java/boofcv/alg/sfm/structure2/ProjectiveInitializeAllCommon.java#L464-L495
briandilley/jsonrpc4j
src/main/java/com/googlecode/jsonrpc4j/JsonRpcBasicServer.java
JsonRpcBasicServer.handleRequest
public int handleRequest(final InputStream input, final OutputStream output) throws IOException { """ Handles a single request from the given {@link InputStream}, that is to say that a single {@link JsonNode} is read from the stream and treated as a JSON-RPC request. All responses are written to the given {@link OutputStream}. @param input the {@link InputStream} @param output the {@link OutputStream} @return the error code, or {@code 0} if none @throws IOException on error """ final ReadContext readContext = ReadContext.getReadContext(input, mapper); try { readContext.assertReadable(); final JsonNode jsonNode = readContext.nextValue(); for (JsonRpcInterceptor interceptor : interceptorList) { interceptor.preHandleJson(jsonNode); } return handleJsonNodeRequest(jsonNode, output).code; } catch (JsonParseException | JsonMappingException e) { return writeAndFlushValueError(output, createResponseError(VERSION, NULL, JsonError.PARSE_ERROR)).code; } }
java
public int handleRequest(final InputStream input, final OutputStream output) throws IOException { final ReadContext readContext = ReadContext.getReadContext(input, mapper); try { readContext.assertReadable(); final JsonNode jsonNode = readContext.nextValue(); for (JsonRpcInterceptor interceptor : interceptorList) { interceptor.preHandleJson(jsonNode); } return handleJsonNodeRequest(jsonNode, output).code; } catch (JsonParseException | JsonMappingException e) { return writeAndFlushValueError(output, createResponseError(VERSION, NULL, JsonError.PARSE_ERROR)).code; } }
[ "public", "int", "handleRequest", "(", "final", "InputStream", "input", ",", "final", "OutputStream", "output", ")", "throws", "IOException", "{", "final", "ReadContext", "readContext", "=", "ReadContext", ".", "getReadContext", "(", "input", ",", "mapper", ")", ";", "try", "{", "readContext", ".", "assertReadable", "(", ")", ";", "final", "JsonNode", "jsonNode", "=", "readContext", ".", "nextValue", "(", ")", ";", "for", "(", "JsonRpcInterceptor", "interceptor", ":", "interceptorList", ")", "{", "interceptor", ".", "preHandleJson", "(", "jsonNode", ")", ";", "}", "return", "handleJsonNodeRequest", "(", "jsonNode", ",", "output", ")", ".", "code", ";", "}", "catch", "(", "JsonParseException", "|", "JsonMappingException", "e", ")", "{", "return", "writeAndFlushValueError", "(", "output", ",", "createResponseError", "(", "VERSION", ",", "NULL", ",", "JsonError", ".", "PARSE_ERROR", ")", ")", ".", "code", ";", "}", "}" ]
Handles a single request from the given {@link InputStream}, that is to say that a single {@link JsonNode} is read from the stream and treated as a JSON-RPC request. All responses are written to the given {@link OutputStream}. @param input the {@link InputStream} @param output the {@link OutputStream} @return the error code, or {@code 0} if none @throws IOException on error
[ "Handles", "a", "single", "request", "from", "the", "given", "{", "@link", "InputStream", "}", "that", "is", "to", "say", "that", "a", "single", "{", "@link", "JsonNode", "}", "is", "read", "from", "the", "stream", "and", "treated", "as", "a", "JSON", "-", "RPC", "request", ".", "All", "responses", "are", "written", "to", "the", "given", "{", "@link", "OutputStream", "}", "." ]
train
https://github.com/briandilley/jsonrpc4j/blob/d749762c9295b92d893677a8c7be2a14dd43b3bb/src/main/java/com/googlecode/jsonrpc4j/JsonRpcBasicServer.java#L235-L247
Carbonado/Carbonado
src/main/java/com/amazon/carbonado/repo/jdbc/JDBCStorableGenerator.java
JDBCStorableGenerator.yieldConnection
private void yieldConnection(CodeBuilder b, LocalVariable capVar, LocalVariable conVar) { """ Generates code which emulates this: // May throw FetchException JDBCConnectionCapability.yieldConnection(con); @param capVar required reference to JDBCConnectionCapability @param conVar optional connection to yield """ if (conVar != null) { b.loadLocal(capVar); b.loadLocal(conVar); b.invokeInterface(TypeDesc.forClass(JDBCConnectionCapability.class), "yieldConnection", null, new TypeDesc[] {TypeDesc.forClass(Connection.class)}); } }
java
private void yieldConnection(CodeBuilder b, LocalVariable capVar, LocalVariable conVar) { if (conVar != null) { b.loadLocal(capVar); b.loadLocal(conVar); b.invokeInterface(TypeDesc.forClass(JDBCConnectionCapability.class), "yieldConnection", null, new TypeDesc[] {TypeDesc.forClass(Connection.class)}); } }
[ "private", "void", "yieldConnection", "(", "CodeBuilder", "b", ",", "LocalVariable", "capVar", ",", "LocalVariable", "conVar", ")", "{", "if", "(", "conVar", "!=", "null", ")", "{", "b", ".", "loadLocal", "(", "capVar", ")", ";", "b", ".", "loadLocal", "(", "conVar", ")", ";", "b", ".", "invokeInterface", "(", "TypeDesc", ".", "forClass", "(", "JDBCConnectionCapability", ".", "class", ")", ",", "\"yieldConnection\"", ",", "null", ",", "new", "TypeDesc", "[", "]", "{", "TypeDesc", ".", "forClass", "(", "Connection", ".", "class", ")", "}", ")", ";", "}", "}" ]
Generates code which emulates this: // May throw FetchException JDBCConnectionCapability.yieldConnection(con); @param capVar required reference to JDBCConnectionCapability @param conVar optional connection to yield
[ "Generates", "code", "which", "emulates", "this", ":" ]
train
https://github.com/Carbonado/Carbonado/blob/eee29b365a61c8f03e1a1dc6bed0692e6b04b1db/src/main/java/com/amazon/carbonado/repo/jdbc/JDBCStorableGenerator.java#L1381-L1389
alibaba/jstorm
example/sequence-split-merge/src/main/java/org/apache/storm/starter/tools/RankableObjectWithFields.java
RankableObjectWithFields.from
public static RankableObjectWithFields from(Tuple tuple) { """ Construct a new instance based on the provided {@link Tuple}. <p/> This method expects the object to be ranked in the first field (index 0) of the provided tuple, and the number of occurrences of the object (its count) in the second field (index 1). Any further fields in the tuple will be extracted and tracked, too. These fields can be accessed via {@link RankableObjectWithFields#getFields()}. @param tuple @return new instance based on the provided tuple """ List<Object> otherFields = Lists.newArrayList(tuple.getValues()); Object obj = otherFields.remove(0); Long count = (Long) otherFields.remove(0); return new RankableObjectWithFields(obj, count, otherFields.toArray()); }
java
public static RankableObjectWithFields from(Tuple tuple) { List<Object> otherFields = Lists.newArrayList(tuple.getValues()); Object obj = otherFields.remove(0); Long count = (Long) otherFields.remove(0); return new RankableObjectWithFields(obj, count, otherFields.toArray()); }
[ "public", "static", "RankableObjectWithFields", "from", "(", "Tuple", "tuple", ")", "{", "List", "<", "Object", ">", "otherFields", "=", "Lists", ".", "newArrayList", "(", "tuple", ".", "getValues", "(", ")", ")", ";", "Object", "obj", "=", "otherFields", ".", "remove", "(", "0", ")", ";", "Long", "count", "=", "(", "Long", ")", "otherFields", ".", "remove", "(", "0", ")", ";", "return", "new", "RankableObjectWithFields", "(", "obj", ",", "count", ",", "otherFields", ".", "toArray", "(", ")", ")", ";", "}" ]
Construct a new instance based on the provided {@link Tuple}. <p/> This method expects the object to be ranked in the first field (index 0) of the provided tuple, and the number of occurrences of the object (its count) in the second field (index 1). Any further fields in the tuple will be extracted and tracked, too. These fields can be accessed via {@link RankableObjectWithFields#getFields()}. @param tuple @return new instance based on the provided tuple
[ "Construct", "a", "new", "instance", "based", "on", "the", "provided", "{", "@link", "Tuple", "}", ".", "<p", "/", ">", "This", "method", "expects", "the", "object", "to", "be", "ranked", "in", "the", "first", "field", "(", "index", "0", ")", "of", "the", "provided", "tuple", "and", "the", "number", "of", "occurrences", "of", "the", "object", "(", "its", "count", ")", "in", "the", "second", "field", "(", "index", "1", ")", ".", "Any", "further", "fields", "in", "the", "tuple", "will", "be", "extracted", "and", "tracked", "too", ".", "These", "fields", "can", "be", "accessed", "via", "{", "@link", "RankableObjectWithFields#getFields", "()", "}", "." ]
train
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/example/sequence-split-merge/src/main/java/org/apache/storm/starter/tools/RankableObjectWithFields.java#L69-L74
ben-manes/caffeine
simulator/src/main/java/com/github/benmanes/caffeine/cache/simulator/policy/sketch/segment/RandomWindowTinyLfuPolicy.java
RandomWindowTinyLfuPolicy.removeFromTable
private void removeFromTable(Node[] table, Node node) { """ Removes the node from the table and adds the index to the free list. """ int last = table.length - 1; table[node.index] = table[last]; table[node.index].index = node.index; table[last] = null; }
java
private void removeFromTable(Node[] table, Node node) { int last = table.length - 1; table[node.index] = table[last]; table[node.index].index = node.index; table[last] = null; }
[ "private", "void", "removeFromTable", "(", "Node", "[", "]", "table", ",", "Node", "node", ")", "{", "int", "last", "=", "table", ".", "length", "-", "1", ";", "table", "[", "node", ".", "index", "]", "=", "table", "[", "last", "]", ";", "table", "[", "node", ".", "index", "]", ".", "index", "=", "node", ".", "index", ";", "table", "[", "last", "]", "=", "null", ";", "}" ]
Removes the node from the table and adds the index to the free list.
[ "Removes", "the", "node", "from", "the", "table", "and", "adds", "the", "index", "to", "the", "free", "list", "." ]
train
https://github.com/ben-manes/caffeine/blob/4cf6d6e6a18ea2e8088f166261e5949343b0f2eb/simulator/src/main/java/com/github/benmanes/caffeine/cache/simulator/policy/sketch/segment/RandomWindowTinyLfuPolicy.java#L123-L128
sniffy/sniffy
sniffy-core/src/main/java/io/sniffy/LegacySpy.java
LegacySpy.verifyBetween
@Deprecated public C verifyBetween(int minAllowedStatements, int maxAllowedStatements) throws WrongNumberOfQueriesError { """ Alias for {@link #verifyBetween(int, int, Threads)} with arguments {@code minAllowedStatements}, {@link Threads#CURRENT}, {@link Query#ANY} @since 2.0 """ return verify(SqlQueries.queriesBetween(minAllowedStatements, maxAllowedStatements)); }
java
@Deprecated public C verifyBetween(int minAllowedStatements, int maxAllowedStatements) throws WrongNumberOfQueriesError { return verify(SqlQueries.queriesBetween(minAllowedStatements, maxAllowedStatements)); }
[ "@", "Deprecated", "public", "C", "verifyBetween", "(", "int", "minAllowedStatements", ",", "int", "maxAllowedStatements", ")", "throws", "WrongNumberOfQueriesError", "{", "return", "verify", "(", "SqlQueries", ".", "queriesBetween", "(", "minAllowedStatements", ",", "maxAllowedStatements", ")", ")", ";", "}" ]
Alias for {@link #verifyBetween(int, int, Threads)} with arguments {@code minAllowedStatements}, {@link Threads#CURRENT}, {@link Query#ANY} @since 2.0
[ "Alias", "for", "{" ]
train
https://github.com/sniffy/sniffy/blob/7bdddb9593e6b6e9fe5c7c87519f864acbc3a5c0/sniffy-core/src/main/java/io/sniffy/LegacySpy.java#L639-L642
avianey/facebook-api-android-maven
facebook/src/main/java/com/facebook/AccessToken.java
AccessToken.createFromNativeLinkingIntent
public static AccessToken createFromNativeLinkingIntent(Intent intent) { """ Creates a new AccessToken using the information contained in an Intent populated by the Facebook application in order to launch a native link. For more information on native linking, please see https://developers.facebook.com/docs/mobile/android/deep_linking/. @param intent the Intent that was used to start an Activity; must not be null @return a new AccessToken, or null if the Intent did not contain enough data to create one """ Validate.notNull(intent, "intent"); if (intent.getExtras() == null) { return null; } return createFromBundle(null, intent.getExtras(), AccessTokenSource.FACEBOOK_APPLICATION_WEB, new Date()); }
java
public static AccessToken createFromNativeLinkingIntent(Intent intent) { Validate.notNull(intent, "intent"); if (intent.getExtras() == null) { return null; } return createFromBundle(null, intent.getExtras(), AccessTokenSource.FACEBOOK_APPLICATION_WEB, new Date()); }
[ "public", "static", "AccessToken", "createFromNativeLinkingIntent", "(", "Intent", "intent", ")", "{", "Validate", ".", "notNull", "(", "intent", ",", "\"intent\"", ")", ";", "if", "(", "intent", ".", "getExtras", "(", ")", "==", "null", ")", "{", "return", "null", ";", "}", "return", "createFromBundle", "(", "null", ",", "intent", ".", "getExtras", "(", ")", ",", "AccessTokenSource", ".", "FACEBOOK_APPLICATION_WEB", ",", "new", "Date", "(", ")", ")", ";", "}" ]
Creates a new AccessToken using the information contained in an Intent populated by the Facebook application in order to launch a native link. For more information on native linking, please see https://developers.facebook.com/docs/mobile/android/deep_linking/. @param intent the Intent that was used to start an Activity; must not be null @return a new AccessToken, or null if the Intent did not contain enough data to create one
[ "Creates", "a", "new", "AccessToken", "using", "the", "information", "contained", "in", "an", "Intent", "populated", "by", "the", "Facebook", "application", "in", "order", "to", "launch", "a", "native", "link", ".", "For", "more", "information", "on", "native", "linking", "please", "see", "https", ":", "//", "developers", ".", "facebook", ".", "com", "/", "docs", "/", "mobile", "/", "android", "/", "deep_linking", "/", "." ]
train
https://github.com/avianey/facebook-api-android-maven/blob/ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede/facebook/src/main/java/com/facebook/AccessToken.java#L177-L185
orbisgis/h2gis
h2gis-functions/src/main/java/org/h2gis/functions/spatial/convert/ST_OSMMapLink.java
ST_OSMMapLink.generateLink
public static String generateLink(Geometry geom, boolean withMarker) { """ Create the OSM map link based on the bounding box of the geometry. @param geom the input geometry. @param withMarker true to place a marker on the center of the BBox. @return """ if (geom == null) { return null; } Envelope env = geom.getEnvelopeInternal(); StringBuilder sb = new StringBuilder("http://www.openstreetmap.org/?"); sb.append("minlon=").append(env.getMinX()); sb.append("&minlat=").append(env.getMinY()); sb.append("&maxlon=").append(env.getMaxX()); sb.append("&maxlat=").append(env.getMaxY()); if (withMarker) { Coordinate centre = env.centre(); sb.append("&mlat=").append(centre.y); sb.append("&mlon=").append(centre.x); } return sb.toString(); }
java
public static String generateLink(Geometry geom, boolean withMarker) { if (geom == null) { return null; } Envelope env = geom.getEnvelopeInternal(); StringBuilder sb = new StringBuilder("http://www.openstreetmap.org/?"); sb.append("minlon=").append(env.getMinX()); sb.append("&minlat=").append(env.getMinY()); sb.append("&maxlon=").append(env.getMaxX()); sb.append("&maxlat=").append(env.getMaxY()); if (withMarker) { Coordinate centre = env.centre(); sb.append("&mlat=").append(centre.y); sb.append("&mlon=").append(centre.x); } return sb.toString(); }
[ "public", "static", "String", "generateLink", "(", "Geometry", "geom", ",", "boolean", "withMarker", ")", "{", "if", "(", "geom", "==", "null", ")", "{", "return", "null", ";", "}", "Envelope", "env", "=", "geom", ".", "getEnvelopeInternal", "(", ")", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", "\"http://www.openstreetmap.org/?\"", ")", ";", "sb", ".", "append", "(", "\"minlon=\"", ")", ".", "append", "(", "env", ".", "getMinX", "(", ")", ")", ";", "sb", ".", "append", "(", "\"&minlat=\"", ")", ".", "append", "(", "env", ".", "getMinY", "(", ")", ")", ";", "sb", ".", "append", "(", "\"&maxlon=\"", ")", ".", "append", "(", "env", ".", "getMaxX", "(", ")", ")", ";", "sb", ".", "append", "(", "\"&maxlat=\"", ")", ".", "append", "(", "env", ".", "getMaxY", "(", ")", ")", ";", "if", "(", "withMarker", ")", "{", "Coordinate", "centre", "=", "env", ".", "centre", "(", ")", ";", "sb", ".", "append", "(", "\"&mlat=\"", ")", ".", "append", "(", "centre", ".", "y", ")", ";", "sb", ".", "append", "(", "\"&mlon=\"", ")", ".", "append", "(", "centre", ".", "x", ")", ";", "}", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
Create the OSM map link based on the bounding box of the geometry. @param geom the input geometry. @param withMarker true to place a marker on the center of the BBox. @return
[ "Create", "the", "OSM", "map", "link", "based", "on", "the", "bounding", "box", "of", "the", "geometry", "." ]
train
https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/spatial/convert/ST_OSMMapLink.java#L63-L79
elki-project/elki
elki-core/src/main/java/de/lmu/ifi/dbs/elki/evaluation/scores/DCGEvaluation.java
DCGEvaluation.sumInvLog1p
public static double sumInvLog1p(int s, int e) { """ Compute <code>\sum_{i=s}^e 1/log(1+i)</code> @param s Start value @param e End value (inclusive!) @return Sum """ double sum = 0.; // Iterate e + 1 .. s + 1, descending for better precision for(int i = e + 1; i > s; i--) { sum += 1. / FastMath.log(i); } return sum; }
java
public static double sumInvLog1p(int s, int e) { double sum = 0.; // Iterate e + 1 .. s + 1, descending for better precision for(int i = e + 1; i > s; i--) { sum += 1. / FastMath.log(i); } return sum; }
[ "public", "static", "double", "sumInvLog1p", "(", "int", "s", ",", "int", "e", ")", "{", "double", "sum", "=", "0.", ";", "// Iterate e + 1 .. s + 1, descending for better precision", "for", "(", "int", "i", "=", "e", "+", "1", ";", "i", ">", "s", ";", "i", "--", ")", "{", "sum", "+=", "1.", "/", "FastMath", ".", "log", "(", "i", ")", ";", "}", "return", "sum", ";", "}" ]
Compute <code>\sum_{i=s}^e 1/log(1+i)</code> @param s Start value @param e End value (inclusive!) @return Sum
[ "Compute", "<code", ">", "\\", "sum_", "{", "i", "=", "s", "}", "^e", "1", "/", "log", "(", "1", "+", "i", ")", "<", "/", "code", ">" ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core/src/main/java/de/lmu/ifi/dbs/elki/evaluation/scores/DCGEvaluation.java#L78-L85
threerings/nenya
core/src/main/java/com/threerings/util/KeyTranslatorImpl.java
KeyTranslatorImpl.addPressCommand
public void addPressCommand (int keyCode, String command, int rate) { """ Adds a mapping from a key press to an action command string that will auto-repeat at the specified repeat rate. Overwrites any existing mapping and repeat rate that may have already been registered. @param rate the number of times each second that the key press should be repeated while the key is down, or <code>0</code> to disable auto-repeat for the key. """ addPressCommand(keyCode, command, rate, DEFAULT_REPEAT_DELAY); }
java
public void addPressCommand (int keyCode, String command, int rate) { addPressCommand(keyCode, command, rate, DEFAULT_REPEAT_DELAY); }
[ "public", "void", "addPressCommand", "(", "int", "keyCode", ",", "String", "command", ",", "int", "rate", ")", "{", "addPressCommand", "(", "keyCode", ",", "command", ",", "rate", ",", "DEFAULT_REPEAT_DELAY", ")", ";", "}" ]
Adds a mapping from a key press to an action command string that will auto-repeat at the specified repeat rate. Overwrites any existing mapping and repeat rate that may have already been registered. @param rate the number of times each second that the key press should be repeated while the key is down, or <code>0</code> to disable auto-repeat for the key.
[ "Adds", "a", "mapping", "from", "a", "key", "press", "to", "an", "action", "command", "string", "that", "will", "auto", "-", "repeat", "at", "the", "specified", "repeat", "rate", ".", "Overwrites", "any", "existing", "mapping", "and", "repeat", "rate", "that", "may", "have", "already", "been", "registered", "." ]
train
https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/util/KeyTranslatorImpl.java#L55-L58
Azure/azure-sdk-for-java
hdinsight/resource-manager/v2018_06_01_preview/src/main/java/com/microsoft/azure/management/hdinsight/v2018_06_01_preview/implementation/ClustersInner.java
ClustersInner.updateGatewaySettings
public void updateGatewaySettings(String resourceGroupName, String clusterName, UpdateGatewaySettingsParameters parameters) { """ Configures the gateway settings on the specified cluster. @param resourceGroupName The name of the resource group. @param clusterName The name of the cluster. @param parameters The cluster configurations. @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorResponseException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent """ updateGatewaySettingsWithServiceResponseAsync(resourceGroupName, clusterName, parameters).toBlocking().last().body(); }
java
public void updateGatewaySettings(String resourceGroupName, String clusterName, UpdateGatewaySettingsParameters parameters) { updateGatewaySettingsWithServiceResponseAsync(resourceGroupName, clusterName, parameters).toBlocking().last().body(); }
[ "public", "void", "updateGatewaySettings", "(", "String", "resourceGroupName", ",", "String", "clusterName", ",", "UpdateGatewaySettingsParameters", "parameters", ")", "{", "updateGatewaySettingsWithServiceResponseAsync", "(", "resourceGroupName", ",", "clusterName", ",", "parameters", ")", ".", "toBlocking", "(", ")", ".", "last", "(", ")", ".", "body", "(", ")", ";", "}" ]
Configures the gateway settings on the specified cluster. @param resourceGroupName The name of the resource group. @param clusterName The name of the cluster. @param parameters The cluster configurations. @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorResponseException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
[ "Configures", "the", "gateway", "settings", "on", "the", "specified", "cluster", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/hdinsight/resource-manager/v2018_06_01_preview/src/main/java/com/microsoft/azure/management/hdinsight/v2018_06_01_preview/implementation/ClustersInner.java#L1549-L1551
baidubce/bce-sdk-java
src/main/java/com/baidubce/services/doc/DocClient.java
DocClient.bosUploadDocument
private void bosUploadDocument(String bucketName, String objectName, File file, String endpoint) { """ publish a Document. @param bucketName The bucket name response from register. @param objectName The object name response from register. @param file The Document file need to be uploaded. @param endpoint The bos endpoint response from register. @return A PublishDocumentResponse object containing the information returned by Document. """ BosClientConfiguration config = new BosClientConfiguration(this.config); config.setEndpoint(endpoint); BosClient bosClient = new BosClient(config); PutObjectResponse response = bosClient.putObject(bucketName, objectName, file); }
java
private void bosUploadDocument(String bucketName, String objectName, File file, String endpoint) { BosClientConfiguration config = new BosClientConfiguration(this.config); config.setEndpoint(endpoint); BosClient bosClient = new BosClient(config); PutObjectResponse response = bosClient.putObject(bucketName, objectName, file); }
[ "private", "void", "bosUploadDocument", "(", "String", "bucketName", ",", "String", "objectName", ",", "File", "file", ",", "String", "endpoint", ")", "{", "BosClientConfiguration", "config", "=", "new", "BosClientConfiguration", "(", "this", ".", "config", ")", ";", "config", ".", "setEndpoint", "(", "endpoint", ")", ";", "BosClient", "bosClient", "=", "new", "BosClient", "(", "config", ")", ";", "PutObjectResponse", "response", "=", "bosClient", ".", "putObject", "(", "bucketName", ",", "objectName", ",", "file", ")", ";", "}" ]
publish a Document. @param bucketName The bucket name response from register. @param objectName The object name response from register. @param file The Document file need to be uploaded. @param endpoint The bos endpoint response from register. @return A PublishDocumentResponse object containing the information returned by Document.
[ "publish", "a", "Document", "." ]
train
https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/doc/DocClient.java#L434-L440
redkale/redkale
src/org/redkale/net/http/HttpRequest.java
HttpRequest.getRequstURIPath
public long getRequstURIPath(String prefix, long defvalue) { """ 获取请求URL分段中含prefix段的long值 <br> 例如请求URL /pipes/record/query/time:1453104341363/id:40 <br> 获取time参数: long time = request.getRequstURIPath("time:", 0L); @param prefix prefix段前缀 @param defvalue 默认long值 @return long值 """ String val = getRequstURIPath(prefix, null); try { return val == null ? defvalue : Long.parseLong(val); } catch (NumberFormatException e) { return defvalue; } }
java
public long getRequstURIPath(String prefix, long defvalue) { String val = getRequstURIPath(prefix, null); try { return val == null ? defvalue : Long.parseLong(val); } catch (NumberFormatException e) { return defvalue; } }
[ "public", "long", "getRequstURIPath", "(", "String", "prefix", ",", "long", "defvalue", ")", "{", "String", "val", "=", "getRequstURIPath", "(", "prefix", ",", "null", ")", ";", "try", "{", "return", "val", "==", "null", "?", "defvalue", ":", "Long", ".", "parseLong", "(", "val", ")", ";", "}", "catch", "(", "NumberFormatException", "e", ")", "{", "return", "defvalue", ";", "}", "}" ]
获取请求URL分段中含prefix段的long值 <br> 例如请求URL /pipes/record/query/time:1453104341363/id:40 <br> 获取time参数: long time = request.getRequstURIPath("time:", 0L); @param prefix prefix段前缀 @param defvalue 默认long值 @return long值
[ "获取请求URL分段中含prefix段的long值", "<br", ">", "例如请求URL", "/", "pipes", "/", "record", "/", "query", "/", "time", ":", "1453104341363", "/", "id", ":", "40", "<br", ">", "获取time参数", ":", "long", "time", "=", "request", ".", "getRequstURIPath", "(", "time", ":", "0L", ")", ";" ]
train
https://github.com/redkale/redkale/blob/ea5169b5c5ea7412fd762331c0c497165832e901/src/org/redkale/net/http/HttpRequest.java#L916-L923
UrielCh/ovh-java-sdk
ovh-java-sdk-hostingprivateDatabase/src/main/java/net/minidev/ovh/api/ApiOvhHostingprivateDatabase.java
ApiOvhHostingprivateDatabase.serviceName_user_userName_grant_databaseName_update_POST
public OvhTask serviceName_user_userName_grant_databaseName_update_POST(String serviceName, String userName, String databaseName, OvhGrantEnum grant) throws IOException { """ Update user grant REST: POST /hosting/privateDatabase/{serviceName}/user/{userName}/grant/{databaseName}/update @param grant [required] Grant you want set on the database for this user @param serviceName [required] The internal name of your private database @param userName [required] User name used to connect to your databases @param databaseName [required] Database name where grant is set """ String qPath = "/hosting/privateDatabase/{serviceName}/user/{userName}/grant/{databaseName}/update"; StringBuilder sb = path(qPath, serviceName, userName, databaseName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "grant", grant); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhTask.class); }
java
public OvhTask serviceName_user_userName_grant_databaseName_update_POST(String serviceName, String userName, String databaseName, OvhGrantEnum grant) throws IOException { String qPath = "/hosting/privateDatabase/{serviceName}/user/{userName}/grant/{databaseName}/update"; StringBuilder sb = path(qPath, serviceName, userName, databaseName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "grant", grant); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhTask.class); }
[ "public", "OvhTask", "serviceName_user_userName_grant_databaseName_update_POST", "(", "String", "serviceName", ",", "String", "userName", ",", "String", "databaseName", ",", "OvhGrantEnum", "grant", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/hosting/privateDatabase/{serviceName}/user/{userName}/grant/{databaseName}/update\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ",", "userName", ",", "databaseName", ")", ";", "HashMap", "<", "String", ",", "Object", ">", "o", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "addBody", "(", "o", ",", "\"grant\"", ",", "grant", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"POST\"", ",", "sb", ".", "toString", "(", ")", ",", "o", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhTask", ".", "class", ")", ";", "}" ]
Update user grant REST: POST /hosting/privateDatabase/{serviceName}/user/{userName}/grant/{databaseName}/update @param grant [required] Grant you want set on the database for this user @param serviceName [required] The internal name of your private database @param userName [required] User name used to connect to your databases @param databaseName [required] Database name where grant is set
[ "Update", "user", "grant" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-hostingprivateDatabase/src/main/java/net/minidev/ovh/api/ApiOvhHostingprivateDatabase.java#L277-L284
querydsl/querydsl
querydsl-core/src/main/java/com/querydsl/core/types/dsl/Expressions.java
Expressions.asEnum
public static <T extends Enum<T>> EnumExpression<T> asEnum(Expression<T> expr) { """ Create a new EnumExpression @param expr Expression of type Enum @return new EnumExpression """ Expression<T> underlyingMixin = ExpressionUtils.extract(expr); if (underlyingMixin instanceof PathImpl) { return new EnumPath<T>((PathImpl<T>) underlyingMixin); } else if (underlyingMixin instanceof OperationImpl) { return new EnumOperation<T>((OperationImpl<T>) underlyingMixin); } else if (underlyingMixin instanceof TemplateExpressionImpl) { return new EnumTemplate<T>((TemplateExpressionImpl<T>) underlyingMixin); } else { return new EnumExpression<T>(underlyingMixin) { private static final long serialVersionUID = 949681836002045152L; @Override public <R, C> R accept(Visitor<R, C> v, C context) { return this.mixin.accept(v, context); } }; } }
java
public static <T extends Enum<T>> EnumExpression<T> asEnum(Expression<T> expr) { Expression<T> underlyingMixin = ExpressionUtils.extract(expr); if (underlyingMixin instanceof PathImpl) { return new EnumPath<T>((PathImpl<T>) underlyingMixin); } else if (underlyingMixin instanceof OperationImpl) { return new EnumOperation<T>((OperationImpl<T>) underlyingMixin); } else if (underlyingMixin instanceof TemplateExpressionImpl) { return new EnumTemplate<T>((TemplateExpressionImpl<T>) underlyingMixin); } else { return new EnumExpression<T>(underlyingMixin) { private static final long serialVersionUID = 949681836002045152L; @Override public <R, C> R accept(Visitor<R, C> v, C context) { return this.mixin.accept(v, context); } }; } }
[ "public", "static", "<", "T", "extends", "Enum", "<", "T", ">", ">", "EnumExpression", "<", "T", ">", "asEnum", "(", "Expression", "<", "T", ">", "expr", ")", "{", "Expression", "<", "T", ">", "underlyingMixin", "=", "ExpressionUtils", ".", "extract", "(", "expr", ")", ";", "if", "(", "underlyingMixin", "instanceof", "PathImpl", ")", "{", "return", "new", "EnumPath", "<", "T", ">", "(", "(", "PathImpl", "<", "T", ">", ")", "underlyingMixin", ")", ";", "}", "else", "if", "(", "underlyingMixin", "instanceof", "OperationImpl", ")", "{", "return", "new", "EnumOperation", "<", "T", ">", "(", "(", "OperationImpl", "<", "T", ">", ")", "underlyingMixin", ")", ";", "}", "else", "if", "(", "underlyingMixin", "instanceof", "TemplateExpressionImpl", ")", "{", "return", "new", "EnumTemplate", "<", "T", ">", "(", "(", "TemplateExpressionImpl", "<", "T", ">", ")", "underlyingMixin", ")", ";", "}", "else", "{", "return", "new", "EnumExpression", "<", "T", ">", "(", "underlyingMixin", ")", "{", "private", "static", "final", "long", "serialVersionUID", "=", "949681836002045152L", ";", "@", "Override", "public", "<", "R", ",", "C", ">", "R", "accept", "(", "Visitor", "<", "R", ",", "C", ">", "v", ",", "C", "context", ")", "{", "return", "this", ".", "mixin", ".", "accept", "(", "v", ",", "context", ")", ";", "}", "}", ";", "}", "}" ]
Create a new EnumExpression @param expr Expression of type Enum @return new EnumExpression
[ "Create", "a", "new", "EnumExpression" ]
train
https://github.com/querydsl/querydsl/blob/2bf234caf78549813a1e0f44d9c30ecc5ef734e3/querydsl-core/src/main/java/com/querydsl/core/types/dsl/Expressions.java#L2054-L2075
zaproxy/zaproxy
src/org/zaproxy/zap/utils/PausableScheduledThreadPoolExecutor.java
PausableScheduledThreadPoolExecutor.setDefaultDelay
public void setDefaultDelay(long delay, TimeUnit unit) { """ Sets the default required delay when executing/submitting tasks. <p> Default value is zero, no required delay. @param delay the value delay @param unit the time unit of delay @throws IllegalArgumentException if {@code defaultDelayInMs} is negative. @see #execute(Runnable) @see #submit(Callable) @see #submit(Runnable) @see #submit(Runnable, Object) @see #setIncrementalDefaultDelay(boolean) """ if (delay < 0) { throw new IllegalArgumentException("Parameter delay must be greater or equal to zero."); } if (unit == null) { throw new IllegalArgumentException("Parameter unit must not be null."); } this.defaultDelayInMs = unit.toMillis(delay); }
java
public void setDefaultDelay(long delay, TimeUnit unit) { if (delay < 0) { throw new IllegalArgumentException("Parameter delay must be greater or equal to zero."); } if (unit == null) { throw new IllegalArgumentException("Parameter unit must not be null."); } this.defaultDelayInMs = unit.toMillis(delay); }
[ "public", "void", "setDefaultDelay", "(", "long", "delay", ",", "TimeUnit", "unit", ")", "{", "if", "(", "delay", "<", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Parameter delay must be greater or equal to zero.\"", ")", ";", "}", "if", "(", "unit", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Parameter unit must not be null.\"", ")", ";", "}", "this", ".", "defaultDelayInMs", "=", "unit", ".", "toMillis", "(", "delay", ")", ";", "}" ]
Sets the default required delay when executing/submitting tasks. <p> Default value is zero, no required delay. @param delay the value delay @param unit the time unit of delay @throws IllegalArgumentException if {@code defaultDelayInMs} is negative. @see #execute(Runnable) @see #submit(Callable) @see #submit(Runnable) @see #submit(Runnable, Object) @see #setIncrementalDefaultDelay(boolean)
[ "Sets", "the", "default", "required", "delay", "when", "executing", "/", "submitting", "tasks", ".", "<p", ">", "Default", "value", "is", "zero", "no", "required", "delay", "." ]
train
https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/utils/PausableScheduledThreadPoolExecutor.java#L127-L135
micrometer-metrics/micrometer
micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jvm/ExecutorServiceMetrics.java
ExecutorServiceMetrics.monitor
public static ExecutorService monitor(MeterRegistry registry, ExecutorService executor, String executorServiceName, Iterable<Tag> tags) { """ Record metrics on the use of an {@link ExecutorService}. @param registry The registry to bind metrics to. @param executor The executor to instrument. @param executorServiceName Will be used to tag metrics with "name". @param tags Tags to apply to all recorded metrics. @return The instrumented executor, proxied. """ new ExecutorServiceMetrics(executor, executorServiceName, tags).bindTo(registry); return new TimedExecutorService(registry, executor, executorServiceName, tags); }
java
public static ExecutorService monitor(MeterRegistry registry, ExecutorService executor, String executorServiceName, Iterable<Tag> tags) { new ExecutorServiceMetrics(executor, executorServiceName, tags).bindTo(registry); return new TimedExecutorService(registry, executor, executorServiceName, tags); }
[ "public", "static", "ExecutorService", "monitor", "(", "MeterRegistry", "registry", ",", "ExecutorService", "executor", ",", "String", "executorServiceName", ",", "Iterable", "<", "Tag", ">", "tags", ")", "{", "new", "ExecutorServiceMetrics", "(", "executor", ",", "executorServiceName", ",", "tags", ")", ".", "bindTo", "(", "registry", ")", ";", "return", "new", "TimedExecutorService", "(", "registry", ",", "executor", ",", "executorServiceName", ",", "tags", ")", ";", "}" ]
Record metrics on the use of an {@link ExecutorService}. @param registry The registry to bind metrics to. @param executor The executor to instrument. @param executorServiceName Will be used to tag metrics with "name". @param tags Tags to apply to all recorded metrics. @return The instrumented executor, proxied.
[ "Record", "metrics", "on", "the", "use", "of", "an", "{", "@link", "ExecutorService", "}", "." ]
train
https://github.com/micrometer-metrics/micrometer/blob/127fa3265325cc894f368312ed8890b76a055d88/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jvm/ExecutorServiceMetrics.java#L91-L94
adyliu/jafka
src/main/java/io/jafka/utils/Utils.java
Utils.putUnsignedInt
public static void putUnsignedInt(ByteBuffer buffer, int index, long value) { """ Write the given long value as a 4 byte unsigned integer. Overflow is ignored. @param buffer The buffer to write to @param index The position in the buffer at which to begin writing @param value The value to write """ buffer.putInt(index, (int) (value & 0xffffffffL)); }
java
public static void putUnsignedInt(ByteBuffer buffer, int index, long value) { buffer.putInt(index, (int) (value & 0xffffffffL)); }
[ "public", "static", "void", "putUnsignedInt", "(", "ByteBuffer", "buffer", ",", "int", "index", ",", "long", "value", ")", "{", "buffer", ".", "putInt", "(", "index", ",", "(", "int", ")", "(", "value", "&", "0xffffffff", "L", ")", ")", ";", "}" ]
Write the given long value as a 4 byte unsigned integer. Overflow is ignored. @param buffer The buffer to write to @param index The position in the buffer at which to begin writing @param value The value to write
[ "Write", "the", "given", "long", "value", "as", "a", "4", "byte", "unsigned", "integer", ".", "Overflow", "is", "ignored", "." ]
train
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/utils/Utils.java#L285-L287
jmeetsma/Iglu-Common
src/main/java/org/ijsberg/iglu/caching/module/StandardCache.java
StandardCache.storeCachedObject
private Object storeCachedObject(K key, CachedObject<V> co) { """ Places an empty wrapper in the cache to indicate that some thread should be busy retrieving the object, after which it should be cached after all. @param co @return """ //data is only locked if cleanup removes cached objects synchronized (data) { data.put(key, co); } //mirror is also locked if cleanup is busy collecting cached objects synchronized (mirror) { mirror.put(key, co); } System.out.println(new LogEntry("object with key " + key + " stored in cache")); return co; }
java
private Object storeCachedObject(K key, CachedObject<V> co) { //data is only locked if cleanup removes cached objects synchronized (data) { data.put(key, co); } //mirror is also locked if cleanup is busy collecting cached objects synchronized (mirror) { mirror.put(key, co); } System.out.println(new LogEntry("object with key " + key + " stored in cache")); return co; }
[ "private", "Object", "storeCachedObject", "(", "K", "key", ",", "CachedObject", "<", "V", ">", "co", ")", "{", "//data is only locked if cleanup removes cached objects", "synchronized", "(", "data", ")", "{", "data", ".", "put", "(", "key", ",", "co", ")", ";", "}", "//mirror is also locked if cleanup is busy collecting cached objects", "synchronized", "(", "mirror", ")", "{", "mirror", ".", "put", "(", "key", ",", "co", ")", ";", "}", "System", ".", "out", ".", "println", "(", "new", "LogEntry", "(", "\"object with key \"", "+", "key", "+", "\" stored in cache\"", ")", ")", ";", "return", "co", ";", "}" ]
Places an empty wrapper in the cache to indicate that some thread should be busy retrieving the object, after which it should be cached after all. @param co @return
[ "Places", "an", "empty", "wrapper", "in", "the", "cache", "to", "indicate", "that", "some", "thread", "should", "be", "busy", "retrieving", "the", "object", "after", "which", "it", "should", "be", "cached", "after", "all", "." ]
train
https://github.com/jmeetsma/Iglu-Common/blob/0fb0885775b576209ff1b5a0f67e3c25a99a6420/src/main/java/org/ijsberg/iglu/caching/module/StandardCache.java#L237-L248
js-lib-com/dom
src/main/java/js/dom/w3c/DocumentImpl.java
DocumentImpl.buildAttrXPath
String buildAttrXPath(String name, String... value) { """ Build XPath expression for elements with attribute name and optional value. @param name attribute name, @param value optional attribute value. @return XPath expression. """ StringBuilder sb = new StringBuilder(); sb.append("//*[@"); sb.append(name); if (value.length == 1) { sb.append("='"); sb.append(value[0]); sb.append("'"); } sb.append("]"); return sb.toString(); }
java
String buildAttrXPath(String name, String... value) { StringBuilder sb = new StringBuilder(); sb.append("//*[@"); sb.append(name); if (value.length == 1) { sb.append("='"); sb.append(value[0]); sb.append("'"); } sb.append("]"); return sb.toString(); }
[ "String", "buildAttrXPath", "(", "String", "name", ",", "String", "...", "value", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"//*[@\"", ")", ";", "sb", ".", "append", "(", "name", ")", ";", "if", "(", "value", ".", "length", "==", "1", ")", "{", "sb", ".", "append", "(", "\"='\"", ")", ";", "sb", ".", "append", "(", "value", "[", "0", "]", ")", ";", "sb", ".", "append", "(", "\"'\"", ")", ";", "}", "sb", ".", "append", "(", "\"]\"", ")", ";", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
Build XPath expression for elements with attribute name and optional value. @param name attribute name, @param value optional attribute value. @return XPath expression.
[ "Build", "XPath", "expression", "for", "elements", "with", "attribute", "name", "and", "optional", "value", "." ]
train
https://github.com/js-lib-com/dom/blob/8c7cd7c802977f210674dec7c2a8f61e8de05b63/src/main/java/js/dom/w3c/DocumentImpl.java#L382-L393
liferay/com-liferay-commerce
commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPAttachmentFileEntryPersistenceImpl.java
CPAttachmentFileEntryPersistenceImpl.removeByC_C
@Override public void removeByC_C(long classNameId, long classPK) { """ Removes all the cp attachment file entries where classNameId = &#63; and classPK = &#63; from the database. @param classNameId the class name ID @param classPK the class pk """ for (CPAttachmentFileEntry cpAttachmentFileEntry : findByC_C( classNameId, classPK, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) { remove(cpAttachmentFileEntry); } }
java
@Override public void removeByC_C(long classNameId, long classPK) { for (CPAttachmentFileEntry cpAttachmentFileEntry : findByC_C( classNameId, classPK, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) { remove(cpAttachmentFileEntry); } }
[ "@", "Override", "public", "void", "removeByC_C", "(", "long", "classNameId", ",", "long", "classPK", ")", "{", "for", "(", "CPAttachmentFileEntry", "cpAttachmentFileEntry", ":", "findByC_C", "(", "classNameId", ",", "classPK", ",", "QueryUtil", ".", "ALL_POS", ",", "QueryUtil", ".", "ALL_POS", ",", "null", ")", ")", "{", "remove", "(", "cpAttachmentFileEntry", ")", ";", "}", "}" ]
Removes all the cp attachment file entries where classNameId = &#63; and classPK = &#63; from the database. @param classNameId the class name ID @param classPK the class pk
[ "Removes", "all", "the", "cp", "attachment", "file", "entries", "where", "classNameId", "=", "&#63", ";", "and", "classPK", "=", "&#63", ";", "from", "the", "database", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPAttachmentFileEntryPersistenceImpl.java#L1981-L1987
Samsung/GearVRf
GVRf/Extensions/script/src/main/java/org/gearvrf/script/GVRScriptManager.java
GVRScriptManager.bindScriptBundleToScene
public void bindScriptBundleToScene(GVRScriptBundle scriptBundle, GVRScene scene) throws IOException, GVRScriptException { """ Binds a script bundle to a scene. @param scriptBundle The {@code GVRScriptBundle} object containing script binding information. @param scene The scene to bind to. @throws IOException if script bundle file cannot be read. @throws GVRScriptException if script processing error occurs. """ for (GVRSceneObject sceneObject : scene.getSceneObjects()) { bindBundleToSceneObject(scriptBundle, sceneObject); } }
java
public void bindScriptBundleToScene(GVRScriptBundle scriptBundle, GVRScene scene) throws IOException, GVRScriptException { for (GVRSceneObject sceneObject : scene.getSceneObjects()) { bindBundleToSceneObject(scriptBundle, sceneObject); } }
[ "public", "void", "bindScriptBundleToScene", "(", "GVRScriptBundle", "scriptBundle", ",", "GVRScene", "scene", ")", "throws", "IOException", ",", "GVRScriptException", "{", "for", "(", "GVRSceneObject", "sceneObject", ":", "scene", ".", "getSceneObjects", "(", ")", ")", "{", "bindBundleToSceneObject", "(", "scriptBundle", ",", "sceneObject", ")", ";", "}", "}" ]
Binds a script bundle to a scene. @param scriptBundle The {@code GVRScriptBundle} object containing script binding information. @param scene The scene to bind to. @throws IOException if script bundle file cannot be read. @throws GVRScriptException if script processing error occurs.
[ "Binds", "a", "script", "bundle", "to", "a", "scene", "." ]
train
https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Extensions/script/src/main/java/org/gearvrf/script/GVRScriptManager.java#L313-L317
pressgang-ccms/PressGangCCMSCommonUtilities
src/main/java/org/jboss/pressgang/ccms/utils/common/DocBookUtilities.java
DocBookUtilities.getConditionNodes
private static void getConditionNodes(final Node node, final Map<Node, List<String>> conditionalNodes) { """ Collects any nodes that have the "condition" attribute in the passed node or any of it's children nodes. @param node The node to collect condition elements from. @param conditionalNodes A mapping of nodes to their conditions """ final NamedNodeMap attributes = node.getAttributes(); if (attributes != null) { final Node attr = attributes.getNamedItem("condition"); if (attr != null) { final String conditionStatement = attr.getNodeValue(); final String[] conditions = conditionStatement.split("\\s*(;|,)\\s*"); conditionalNodes.put(node, Arrays.asList(conditions)); } } // Check the child nodes for condition attributes final NodeList elements = node.getChildNodes(); for (int i = 0; i < elements.getLength(); ++i) { getConditionNodes(elements.item(i), conditionalNodes); } }
java
private static void getConditionNodes(final Node node, final Map<Node, List<String>> conditionalNodes) { final NamedNodeMap attributes = node.getAttributes(); if (attributes != null) { final Node attr = attributes.getNamedItem("condition"); if (attr != null) { final String conditionStatement = attr.getNodeValue(); final String[] conditions = conditionStatement.split("\\s*(;|,)\\s*"); conditionalNodes.put(node, Arrays.asList(conditions)); } } // Check the child nodes for condition attributes final NodeList elements = node.getChildNodes(); for (int i = 0; i < elements.getLength(); ++i) { getConditionNodes(elements.item(i), conditionalNodes); } }
[ "private", "static", "void", "getConditionNodes", "(", "final", "Node", "node", ",", "final", "Map", "<", "Node", ",", "List", "<", "String", ">", ">", "conditionalNodes", ")", "{", "final", "NamedNodeMap", "attributes", "=", "node", ".", "getAttributes", "(", ")", ";", "if", "(", "attributes", "!=", "null", ")", "{", "final", "Node", "attr", "=", "attributes", ".", "getNamedItem", "(", "\"condition\"", ")", ";", "if", "(", "attr", "!=", "null", ")", "{", "final", "String", "conditionStatement", "=", "attr", ".", "getNodeValue", "(", ")", ";", "final", "String", "[", "]", "conditions", "=", "conditionStatement", ".", "split", "(", "\"\\\\s*(;|,)\\\\s*\"", ")", ";", "conditionalNodes", ".", "put", "(", "node", ",", "Arrays", ".", "asList", "(", "conditions", ")", ")", ";", "}", "}", "// Check the child nodes for condition attributes", "final", "NodeList", "elements", "=", "node", ".", "getChildNodes", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "elements", ".", "getLength", "(", ")", ";", "++", "i", ")", "{", "getConditionNodes", "(", "elements", ".", "item", "(", "i", ")", ",", "conditionalNodes", ")", ";", "}", "}" ]
Collects any nodes that have the "condition" attribute in the passed node or any of it's children nodes. @param node The node to collect condition elements from. @param conditionalNodes A mapping of nodes to their conditions
[ "Collects", "any", "nodes", "that", "have", "the", "condition", "attribute", "in", "the", "passed", "node", "or", "any", "of", "it", "s", "children", "nodes", "." ]
train
https://github.com/pressgang-ccms/PressGangCCMSCommonUtilities/blob/5ebf5ed30a94c34c33f4708caa04a8da99cbb15c/src/main/java/org/jboss/pressgang/ccms/utils/common/DocBookUtilities.java#L3263-L3282
arnaudroger/SimpleFlatMapper
sfm-map/src/main/java/org/simpleflatmapper/map/mapper/MapperBuilder.java
MapperBuilder.addMapping
public final B addMapping(final String column, final ColumnDefinition<K, ?> columnDefinition) { """ add a new mapping to the specified property with the specified columnDefinition and an undefined type. The index is incremented for each non indexed property mapping. @param column the property name @param columnDefinition the definition @return the current builder """ return addMapping(column, calculatedIndex++, columnDefinition); }
java
public final B addMapping(final String column, final ColumnDefinition<K, ?> columnDefinition) { return addMapping(column, calculatedIndex++, columnDefinition); }
[ "public", "final", "B", "addMapping", "(", "final", "String", "column", ",", "final", "ColumnDefinition", "<", "K", ",", "?", ">", "columnDefinition", ")", "{", "return", "addMapping", "(", "column", ",", "calculatedIndex", "++", ",", "columnDefinition", ")", ";", "}" ]
add a new mapping to the specified property with the specified columnDefinition and an undefined type. The index is incremented for each non indexed property mapping. @param column the property name @param columnDefinition the definition @return the current builder
[ "add", "a", "new", "mapping", "to", "the", "specified", "property", "with", "the", "specified", "columnDefinition", "and", "an", "undefined", "type", ".", "The", "index", "is", "incremented", "for", "each", "non", "indexed", "property", "mapping", "." ]
train
https://github.com/arnaudroger/SimpleFlatMapper/blob/93435438c18f26c87963d5e0f3ebf0f264dcd8c2/sfm-map/src/main/java/org/simpleflatmapper/map/mapper/MapperBuilder.java#L77-L79
Azure/azure-sdk-for-java
mysql/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/mysql/v2017_12_01/implementation/ConfigurationsInner.java
ConfigurationsInner.createOrUpdate
public ConfigurationInner createOrUpdate(String resourceGroupName, String serverName, String configurationName, ConfigurationInner parameters) { """ Updates a configuration of a server. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server. @param configurationName The name of the server configuration. @param parameters The required parameters for updating a server configuration. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the ConfigurationInner object if successful. """ return createOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, configurationName, parameters).toBlocking().last().body(); }
java
public ConfigurationInner createOrUpdate(String resourceGroupName, String serverName, String configurationName, ConfigurationInner parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, configurationName, parameters).toBlocking().last().body(); }
[ "public", "ConfigurationInner", "createOrUpdate", "(", "String", "resourceGroupName", ",", "String", "serverName", ",", "String", "configurationName", ",", "ConfigurationInner", "parameters", ")", "{", "return", "createOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "serverName", ",", "configurationName", ",", "parameters", ")", ".", "toBlocking", "(", ")", ".", "last", "(", ")", ".", "body", "(", ")", ";", "}" ]
Updates a configuration of a server. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server. @param configurationName The name of the server configuration. @param parameters The required parameters for updating a server configuration. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the ConfigurationInner object if successful.
[ "Updates", "a", "configuration", "of", "a", "server", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/mysql/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/mysql/v2017_12_01/implementation/ConfigurationsInner.java#L88-L90
unic/neba
core/src/main/java/io/neba/core/util/ReflectionUtil.java
ReflectionUtil.findField
public static Field findField(Class<?> type, String name) { """ Rerturns the {@link Class#getDeclaredFields() declared field} with the given name. @param type must not be <code>null</code>. @param name must not be <code>null</code>. @return the field, or <code>null</code> """ if (type == null) { throw new IllegalArgumentException("Method argument type must not be null"); } if (name == null) { throw new IllegalArgumentException("Method argument name must not be null"); } Class<?> c = type; do { for (Field f : c.getDeclaredFields()) { if (name.equals(f.getName())) { return f; } } c = c.getSuperclass(); } while (c != null); return null; }
java
public static Field findField(Class<?> type, String name) { if (type == null) { throw new IllegalArgumentException("Method argument type must not be null"); } if (name == null) { throw new IllegalArgumentException("Method argument name must not be null"); } Class<?> c = type; do { for (Field f : c.getDeclaredFields()) { if (name.equals(f.getName())) { return f; } } c = c.getSuperclass(); } while (c != null); return null; }
[ "public", "static", "Field", "findField", "(", "Class", "<", "?", ">", "type", ",", "String", "name", ")", "{", "if", "(", "type", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Method argument type must not be null\"", ")", ";", "}", "if", "(", "name", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Method argument name must not be null\"", ")", ";", "}", "Class", "<", "?", ">", "c", "=", "type", ";", "do", "{", "for", "(", "Field", "f", ":", "c", ".", "getDeclaredFields", "(", ")", ")", "{", "if", "(", "name", ".", "equals", "(", "f", ".", "getName", "(", ")", ")", ")", "{", "return", "f", ";", "}", "}", "c", "=", "c", ".", "getSuperclass", "(", ")", ";", "}", "while", "(", "c", "!=", "null", ")", ";", "return", "null", ";", "}" ]
Rerturns the {@link Class#getDeclaredFields() declared field} with the given name. @param type must not be <code>null</code>. @param name must not be <code>null</code>. @return the field, or <code>null</code>
[ "Rerturns", "the", "{", "@link", "Class#getDeclaredFields", "()", "declared", "field", "}", "with", "the", "given", "name", "." ]
train
https://github.com/unic/neba/blob/4d762e60112a1fcb850926a56a9843d5aa424c4b/core/src/main/java/io/neba/core/util/ReflectionUtil.java#L196-L216
Erudika/para
para-client/src/main/java/com/erudika/para/client/ParaClient.java
ParaClient.findTerms
public <P extends ParaObject> List<P> findTerms(String type, Map<String, ?> terms, boolean matchAll, Pager... pager) { """ Searches for objects that have properties matching some given values. A terms query. @param <P> type of the object @param type the type of object to search for. See {@link com.erudika.para.core.ParaObject#getType()} @param terms a map of fields (property names) to terms (property values) @param matchAll match all terms. If true - AND search, if false - OR search @param pager a {@link com.erudika.para.utils.Pager} @return a list of objects found """ if (terms == null) { return Collections.emptyList(); } MultivaluedMap<String, String> params = new MultivaluedHashMap<>(); params.putSingle("matchall", Boolean.toString(matchAll)); LinkedList<String> list = new LinkedList<>(); for (Map.Entry<String, ? extends Object> term : terms.entrySet()) { String key = term.getKey(); Object value = term.getValue(); if (value != null) { list.add(key.concat(Config.SEPARATOR).concat(value.toString())); } } if (!terms.isEmpty()) { params.put("terms", list); } params.putSingle(Config._TYPE, type); params.putAll(pagerToParams(pager)); return getItems(find("terms", params), pager); }
java
public <P extends ParaObject> List<P> findTerms(String type, Map<String, ?> terms, boolean matchAll, Pager... pager) { if (terms == null) { return Collections.emptyList(); } MultivaluedMap<String, String> params = new MultivaluedHashMap<>(); params.putSingle("matchall", Boolean.toString(matchAll)); LinkedList<String> list = new LinkedList<>(); for (Map.Entry<String, ? extends Object> term : terms.entrySet()) { String key = term.getKey(); Object value = term.getValue(); if (value != null) { list.add(key.concat(Config.SEPARATOR).concat(value.toString())); } } if (!terms.isEmpty()) { params.put("terms", list); } params.putSingle(Config._TYPE, type); params.putAll(pagerToParams(pager)); return getItems(find("terms", params), pager); }
[ "public", "<", "P", "extends", "ParaObject", ">", "List", "<", "P", ">", "findTerms", "(", "String", "type", ",", "Map", "<", "String", ",", "?", ">", "terms", ",", "boolean", "matchAll", ",", "Pager", "...", "pager", ")", "{", "if", "(", "terms", "==", "null", ")", "{", "return", "Collections", ".", "emptyList", "(", ")", ";", "}", "MultivaluedMap", "<", "String", ",", "String", ">", "params", "=", "new", "MultivaluedHashMap", "<>", "(", ")", ";", "params", ".", "putSingle", "(", "\"matchall\"", ",", "Boolean", ".", "toString", "(", "matchAll", ")", ")", ";", "LinkedList", "<", "String", ">", "list", "=", "new", "LinkedList", "<>", "(", ")", ";", "for", "(", "Map", ".", "Entry", "<", "String", ",", "?", "extends", "Object", ">", "term", ":", "terms", ".", "entrySet", "(", ")", ")", "{", "String", "key", "=", "term", ".", "getKey", "(", ")", ";", "Object", "value", "=", "term", ".", "getValue", "(", ")", ";", "if", "(", "value", "!=", "null", ")", "{", "list", ".", "add", "(", "key", ".", "concat", "(", "Config", ".", "SEPARATOR", ")", ".", "concat", "(", "value", ".", "toString", "(", ")", ")", ")", ";", "}", "}", "if", "(", "!", "terms", ".", "isEmpty", "(", ")", ")", "{", "params", ".", "put", "(", "\"terms\"", ",", "list", ")", ";", "}", "params", ".", "putSingle", "(", "Config", ".", "_TYPE", ",", "type", ")", ";", "params", ".", "putAll", "(", "pagerToParams", "(", "pager", ")", ")", ";", "return", "getItems", "(", "find", "(", "\"terms\"", ",", "params", ")", ",", "pager", ")", ";", "}" ]
Searches for objects that have properties matching some given values. A terms query. @param <P> type of the object @param type the type of object to search for. See {@link com.erudika.para.core.ParaObject#getType()} @param terms a map of fields (property names) to terms (property values) @param matchAll match all terms. If true - AND search, if false - OR search @param pager a {@link com.erudika.para.utils.Pager} @return a list of objects found
[ "Searches", "for", "objects", "that", "have", "properties", "matching", "some", "given", "values", ".", "A", "terms", "query", "." ]
train
https://github.com/Erudika/para/blob/5ba096c477042ea7b18e9a0e8b5b1ee0f5bd6ce9/para-client/src/main/java/com/erudika/para/client/ParaClient.java#L828-L849
eduarddrenth/ConfigurableReports
src/main/java/com/vectorprint/report/itext/DefaultElementProducer.java
DefaultElementProducer.createChunk
public Chunk createChunk(Object data, Collection<? extends BaseStyler> stylers) throws VectorPrintException { """ Create a piece of text (part of a Phrase), style it and ad the data. @param data @param stylers @return @throws VectorPrintException """ Chunk c = styleHelper.style(new Chunk(), data, stylers); if (data != null) { c.append(formatValue(data)); } if (notDelayedStyle(c, ADV + (++advancedTag), stylers) && debug) { c.setGenericTag(String.valueOf(++genericTag)); } return c; }
java
public Chunk createChunk(Object data, Collection<? extends BaseStyler> stylers) throws VectorPrintException { Chunk c = styleHelper.style(new Chunk(), data, stylers); if (data != null) { c.append(formatValue(data)); } if (notDelayedStyle(c, ADV + (++advancedTag), stylers) && debug) { c.setGenericTag(String.valueOf(++genericTag)); } return c; }
[ "public", "Chunk", "createChunk", "(", "Object", "data", ",", "Collection", "<", "?", "extends", "BaseStyler", ">", "stylers", ")", "throws", "VectorPrintException", "{", "Chunk", "c", "=", "styleHelper", ".", "style", "(", "new", "Chunk", "(", ")", ",", "data", ",", "stylers", ")", ";", "if", "(", "data", "!=", "null", ")", "{", "c", ".", "append", "(", "formatValue", "(", "data", ")", ")", ";", "}", "if", "(", "notDelayedStyle", "(", "c", ",", "ADV", "+", "(", "++", "advancedTag", ")", ",", "stylers", ")", "&&", "debug", ")", "{", "c", ".", "setGenericTag", "(", "String", ".", "valueOf", "(", "++", "genericTag", ")", ")", ";", "}", "return", "c", ";", "}" ]
Create a piece of text (part of a Phrase), style it and ad the data. @param data @param stylers @return @throws VectorPrintException
[ "Create", "a", "piece", "of", "text", "(", "part", "of", "a", "Phrase", ")", "style", "it", "and", "ad", "the", "data", "." ]
train
https://github.com/eduarddrenth/ConfigurableReports/blob/b5fb7a89e16d9b35f557f3bf620594f821fa1552/src/main/java/com/vectorprint/report/itext/DefaultElementProducer.java#L191-L203
mgm-tp/jfunk
jfunk-data/src/main/java/com/mgmtp/jfunk/data/source/BaseDataSource.java
BaseDataSource.resetFixedValue
@Override public void resetFixedValue(final String dataSetKey, final String entryKey) { """ Resets (= removes) a specific fixed value from the specified {@link DataSet}. @param dataSetKey The {@link DataSet} key. @param entryKey The entry key. """ Map<String, String> map = fixedValues.get(dataSetKey); if (map != null) { if (map.remove(entryKey) == null) { log.warn("Entry " + dataSetKey + "." + entryKey + " could not be found in map of fixed values"); } if (map.isEmpty()) { fixedValues.remove(dataSetKey); } } DataSet dataSet = getCurrentDataSets().get(dataSetKey); if (dataSet != null) { dataSet.resetFixedValue(entryKey); } }
java
@Override public void resetFixedValue(final String dataSetKey, final String entryKey) { Map<String, String> map = fixedValues.get(dataSetKey); if (map != null) { if (map.remove(entryKey) == null) { log.warn("Entry " + dataSetKey + "." + entryKey + " could not be found in map of fixed values"); } if (map.isEmpty()) { fixedValues.remove(dataSetKey); } } DataSet dataSet = getCurrentDataSets().get(dataSetKey); if (dataSet != null) { dataSet.resetFixedValue(entryKey); } }
[ "@", "Override", "public", "void", "resetFixedValue", "(", "final", "String", "dataSetKey", ",", "final", "String", "entryKey", ")", "{", "Map", "<", "String", ",", "String", ">", "map", "=", "fixedValues", ".", "get", "(", "dataSetKey", ")", ";", "if", "(", "map", "!=", "null", ")", "{", "if", "(", "map", ".", "remove", "(", "entryKey", ")", "==", "null", ")", "{", "log", ".", "warn", "(", "\"Entry \"", "+", "dataSetKey", "+", "\".\"", "+", "entryKey", "+", "\" could not be found in map of fixed values\"", ")", ";", "}", "if", "(", "map", ".", "isEmpty", "(", ")", ")", "{", "fixedValues", ".", "remove", "(", "dataSetKey", ")", ";", "}", "}", "DataSet", "dataSet", "=", "getCurrentDataSets", "(", ")", ".", "get", "(", "dataSetKey", ")", ";", "if", "(", "dataSet", "!=", "null", ")", "{", "dataSet", ".", "resetFixedValue", "(", "entryKey", ")", ";", "}", "}" ]
Resets (= removes) a specific fixed value from the specified {@link DataSet}. @param dataSetKey The {@link DataSet} key. @param entryKey The entry key.
[ "Resets", "(", "=", "removes", ")", "a", "specific", "fixed", "value", "from", "the", "specified", "{", "@link", "DataSet", "}", "." ]
train
https://github.com/mgm-tp/jfunk/blob/5b9fecac5778b988bb458085ded39ea9a4c7c2ae/jfunk-data/src/main/java/com/mgmtp/jfunk/data/source/BaseDataSource.java#L151-L166
phax/ph-oton
ph-oton-app/src/main/java/com/helger/photon/app/url/LinkHelper.java
LinkHelper.getURLWithServerAndContext
@Nonnull public static SimpleURL getURLWithServerAndContext (@Nonnull final IRequestWebScopeWithoutResponse aRequestScope, @Nonnull final String sHRef) { """ Prefix the passed href with the absolute server + context path in case the passed href has no protocol yet. @param aRequestScope The request web scope to be used. Required for cookie-less handling. May not be <code>null</code>. @param sHRef The href to be extended. @return Either the original href if already absolute or <code>http://servername:8123/webapp-context/<i>href</i></code> otherwise. """ return new SimpleURL (getURIWithServerAndContext (aRequestScope, sHRef)); }
java
@Nonnull public static SimpleURL getURLWithServerAndContext (@Nonnull final IRequestWebScopeWithoutResponse aRequestScope, @Nonnull final String sHRef) { return new SimpleURL (getURIWithServerAndContext (aRequestScope, sHRef)); }
[ "@", "Nonnull", "public", "static", "SimpleURL", "getURLWithServerAndContext", "(", "@", "Nonnull", "final", "IRequestWebScopeWithoutResponse", "aRequestScope", ",", "@", "Nonnull", "final", "String", "sHRef", ")", "{", "return", "new", "SimpleURL", "(", "getURIWithServerAndContext", "(", "aRequestScope", ",", "sHRef", ")", ")", ";", "}" ]
Prefix the passed href with the absolute server + context path in case the passed href has no protocol yet. @param aRequestScope The request web scope to be used. Required for cookie-less handling. May not be <code>null</code>. @param sHRef The href to be extended. @return Either the original href if already absolute or <code>http://servername:8123/webapp-context/<i>href</i></code> otherwise.
[ "Prefix", "the", "passed", "href", "with", "the", "absolute", "server", "+", "context", "path", "in", "case", "the", "passed", "href", "has", "no", "protocol", "yet", "." ]
train
https://github.com/phax/ph-oton/blob/f3aaacbbc02a9f3e4f32fe8db8e4adf7b9c1d3ef/ph-oton-app/src/main/java/com/helger/photon/app/url/LinkHelper.java#L305-L310
Azure/azure-sdk-for-java
cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/FacesImpl.java
FacesImpl.verifyFaceToPerson
public VerifyResult verifyFaceToPerson(UUID faceId, String personGroupId, UUID personId) { """ Verify whether two faces belong to a same person. Compares a face Id with a Person Id. @param faceId FaceId the face, comes from Face - Detect @param personGroupId Using existing personGroupId and personId for fast loading a specified person. personGroupId is created in Person Groups.Create. @param personId Specify a certain person in a person group. personId is created in Persons.Create. @throws IllegalArgumentException thrown if parameters fail the validation @throws APIErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the VerifyResult object if successful. """ return verifyFaceToPersonWithServiceResponseAsync(faceId, personGroupId, personId).toBlocking().single().body(); }
java
public VerifyResult verifyFaceToPerson(UUID faceId, String personGroupId, UUID personId) { return verifyFaceToPersonWithServiceResponseAsync(faceId, personGroupId, personId).toBlocking().single().body(); }
[ "public", "VerifyResult", "verifyFaceToPerson", "(", "UUID", "faceId", ",", "String", "personGroupId", ",", "UUID", "personId", ")", "{", "return", "verifyFaceToPersonWithServiceResponseAsync", "(", "faceId", ",", "personGroupId", ",", "personId", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Verify whether two faces belong to a same person. Compares a face Id with a Person Id. @param faceId FaceId the face, comes from Face - Detect @param personGroupId Using existing personGroupId and personId for fast loading a specified person. personGroupId is created in Person Groups.Create. @param personId Specify a certain person in a person group. personId is created in Persons.Create. @throws IllegalArgumentException thrown if parameters fail the validation @throws APIErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the VerifyResult object if successful.
[ "Verify", "whether", "two", "faces", "belong", "to", "a", "same", "person", ".", "Compares", "a", "face", "Id", "with", "a", "Person", "Id", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/FacesImpl.java#L830-L832
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/text/movingwindow/WindowConverter.java
WindowConverter.asExampleMatrix
public static INDArray asExampleMatrix(Window window, Word2Vec vec) { """ Converts a window (each word in the window) in to a vector. Keep in mind each window is a multi word context. From there, each word uses the passed in model as a lookup table to get what vectors are relevant to the passed in windows @param window the window to take in. @param vec the model to use as a lookup table @return a concatneated 1 row array containing all of the numbers for each word in the window """ INDArray[] data = new INDArray[window.getWords().size()]; for (int i = 0; i < data.length; i++) { data[i] = vec.getWordVectorMatrix(window.getWord(i)); // if there's null elements if (data[i] == null) data[i] = Nd4j.zeros(1, vec.getLayerSize()); } return Nd4j.hstack(data); }
java
public static INDArray asExampleMatrix(Window window, Word2Vec vec) { INDArray[] data = new INDArray[window.getWords().size()]; for (int i = 0; i < data.length; i++) { data[i] = vec.getWordVectorMatrix(window.getWord(i)); // if there's null elements if (data[i] == null) data[i] = Nd4j.zeros(1, vec.getLayerSize()); } return Nd4j.hstack(data); }
[ "public", "static", "INDArray", "asExampleMatrix", "(", "Window", "window", ",", "Word2Vec", "vec", ")", "{", "INDArray", "[", "]", "data", "=", "new", "INDArray", "[", "window", ".", "getWords", "(", ")", ".", "size", "(", ")", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "data", ".", "length", ";", "i", "++", ")", "{", "data", "[", "i", "]", "=", "vec", ".", "getWordVectorMatrix", "(", "window", ".", "getWord", "(", "i", ")", ")", ";", "// if there's null elements", "if", "(", "data", "[", "i", "]", "==", "null", ")", "data", "[", "i", "]", "=", "Nd4j", ".", "zeros", "(", "1", ",", "vec", ".", "getLayerSize", "(", ")", ")", ";", "}", "return", "Nd4j", ".", "hstack", "(", "data", ")", ";", "}" ]
Converts a window (each word in the window) in to a vector. Keep in mind each window is a multi word context. From there, each word uses the passed in model as a lookup table to get what vectors are relevant to the passed in windows @param window the window to take in. @param vec the model to use as a lookup table @return a concatneated 1 row array containing all of the numbers for each word in the window
[ "Converts", "a", "window", "(", "each", "word", "in", "the", "window", ")" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/text/movingwindow/WindowConverter.java#L93-L103
Azure/azure-sdk-for-java
streamanalytics/resource-manager/v2016_03_01/src/main/java/com/microsoft/azure/management/streamanalytics/v2016_03_01/implementation/TransformationsInner.java
TransformationsInner.createOrReplaceAsync
public Observable<TransformationInner> createOrReplaceAsync(String resourceGroupName, String jobName, String transformationName, TransformationInner transformation, String ifMatch, String ifNoneMatch) { """ Creates a transformation or replaces an already existing transformation under an existing streaming job. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param jobName The name of the streaming job. @param transformationName The name of the transformation. @param transformation The definition of the transformation that will be used to create a new transformation or replace the existing one under the streaming job. @param ifMatch The ETag of the transformation. Omit this value to always overwrite the current transformation. Specify the last-seen ETag value to prevent accidentally overwritting concurrent changes. @param ifNoneMatch Set to '*' to allow a new transformation to be created, but to prevent updating an existing transformation. Other values will result in a 412 Pre-condition Failed response. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the TransformationInner object """ return createOrReplaceWithServiceResponseAsync(resourceGroupName, jobName, transformationName, transformation, ifMatch, ifNoneMatch).map(new Func1<ServiceResponseWithHeaders<TransformationInner, TransformationsCreateOrReplaceHeaders>, TransformationInner>() { @Override public TransformationInner call(ServiceResponseWithHeaders<TransformationInner, TransformationsCreateOrReplaceHeaders> response) { return response.body(); } }); }
java
public Observable<TransformationInner> createOrReplaceAsync(String resourceGroupName, String jobName, String transformationName, TransformationInner transformation, String ifMatch, String ifNoneMatch) { return createOrReplaceWithServiceResponseAsync(resourceGroupName, jobName, transformationName, transformation, ifMatch, ifNoneMatch).map(new Func1<ServiceResponseWithHeaders<TransformationInner, TransformationsCreateOrReplaceHeaders>, TransformationInner>() { @Override public TransformationInner call(ServiceResponseWithHeaders<TransformationInner, TransformationsCreateOrReplaceHeaders> response) { return response.body(); } }); }
[ "public", "Observable", "<", "TransformationInner", ">", "createOrReplaceAsync", "(", "String", "resourceGroupName", ",", "String", "jobName", ",", "String", "transformationName", ",", "TransformationInner", "transformation", ",", "String", "ifMatch", ",", "String", "ifNoneMatch", ")", "{", "return", "createOrReplaceWithServiceResponseAsync", "(", "resourceGroupName", ",", "jobName", ",", "transformationName", ",", "transformation", ",", "ifMatch", ",", "ifNoneMatch", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponseWithHeaders", "<", "TransformationInner", ",", "TransformationsCreateOrReplaceHeaders", ">", ",", "TransformationInner", ">", "(", ")", "{", "@", "Override", "public", "TransformationInner", "call", "(", "ServiceResponseWithHeaders", "<", "TransformationInner", ",", "TransformationsCreateOrReplaceHeaders", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Creates a transformation or replaces an already existing transformation under an existing streaming job. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param jobName The name of the streaming job. @param transformationName The name of the transformation. @param transformation The definition of the transformation that will be used to create a new transformation or replace the existing one under the streaming job. @param ifMatch The ETag of the transformation. Omit this value to always overwrite the current transformation. Specify the last-seen ETag value to prevent accidentally overwritting concurrent changes. @param ifNoneMatch Set to '*' to allow a new transformation to be created, but to prevent updating an existing transformation. Other values will result in a 412 Pre-condition Failed response. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the TransformationInner object
[ "Creates", "a", "transformation", "or", "replaces", "an", "already", "existing", "transformation", "under", "an", "existing", "streaming", "job", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/streamanalytics/resource-manager/v2016_03_01/src/main/java/com/microsoft/azure/management/streamanalytics/v2016_03_01/implementation/TransformationsInner.java#L218-L225
Azure/azure-sdk-for-java
datamigration/resource-manager/v2018_07_15_preview/src/main/java/com/microsoft/azure/management/datamigration/v2018_07_15_preview/implementation/FilesInner.java
FilesInner.listAsync
public Observable<Page<ProjectFileInner>> listAsync(final String groupName, final String serviceName, final String projectName) { """ Get files in a project. The project resource is a nested resource representing a stored migration project. This method returns a list of files owned by a project resource. @param groupName Name of the resource group @param serviceName Name of the service @param projectName Name of the project @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;ProjectFileInner&gt; object """ return listWithServiceResponseAsync(groupName, serviceName, projectName) .map(new Func1<ServiceResponse<Page<ProjectFileInner>>, Page<ProjectFileInner>>() { @Override public Page<ProjectFileInner> call(ServiceResponse<Page<ProjectFileInner>> response) { return response.body(); } }); }
java
public Observable<Page<ProjectFileInner>> listAsync(final String groupName, final String serviceName, final String projectName) { return listWithServiceResponseAsync(groupName, serviceName, projectName) .map(new Func1<ServiceResponse<Page<ProjectFileInner>>, Page<ProjectFileInner>>() { @Override public Page<ProjectFileInner> call(ServiceResponse<Page<ProjectFileInner>> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Page", "<", "ProjectFileInner", ">", ">", "listAsync", "(", "final", "String", "groupName", ",", "final", "String", "serviceName", ",", "final", "String", "projectName", ")", "{", "return", "listWithServiceResponseAsync", "(", "groupName", ",", "serviceName", ",", "projectName", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "Page", "<", "ProjectFileInner", ">", ">", ",", "Page", "<", "ProjectFileInner", ">", ">", "(", ")", "{", "@", "Override", "public", "Page", "<", "ProjectFileInner", ">", "call", "(", "ServiceResponse", "<", "Page", "<", "ProjectFileInner", ">", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Get files in a project. The project resource is a nested resource representing a stored migration project. This method returns a list of files owned by a project resource. @param groupName Name of the resource group @param serviceName Name of the service @param projectName Name of the project @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;ProjectFileInner&gt; object
[ "Get", "files", "in", "a", "project", ".", "The", "project", "resource", "is", "a", "nested", "resource", "representing", "a", "stored", "migration", "project", ".", "This", "method", "returns", "a", "list", "of", "files", "owned", "by", "a", "project", "resource", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/datamigration/resource-manager/v2018_07_15_preview/src/main/java/com/microsoft/azure/management/datamigration/v2018_07_15_preview/implementation/FilesInner.java#L155-L163
linkedin/PalDB
paldb/src/main/java/com/linkedin/paldb/impl/StorageWriter.java
StorageWriter.getDataStream
private DataOutputStream getDataStream(int keyLength) throws IOException { """ Get the data stream for the specified keyLength, create it if needed """ // Resize array if necessary if (dataStreams.length <= keyLength) { dataStreams = Arrays.copyOf(dataStreams, keyLength + 1); dataFiles = Arrays.copyOf(dataFiles, keyLength + 1); } DataOutputStream dos = dataStreams[keyLength]; if (dos == null) { File file = new File(tempFolder, "data" + keyLength + ".dat"); file.deleteOnExit(); dataFiles[keyLength] = file; dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file))); dataStreams[keyLength] = dos; // Write one byte so the zero offset is reserved dos.writeByte(0); } return dos; }
java
private DataOutputStream getDataStream(int keyLength) throws IOException { // Resize array if necessary if (dataStreams.length <= keyLength) { dataStreams = Arrays.copyOf(dataStreams, keyLength + 1); dataFiles = Arrays.copyOf(dataFiles, keyLength + 1); } DataOutputStream dos = dataStreams[keyLength]; if (dos == null) { File file = new File(tempFolder, "data" + keyLength + ".dat"); file.deleteOnExit(); dataFiles[keyLength] = file; dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file))); dataStreams[keyLength] = dos; // Write one byte so the zero offset is reserved dos.writeByte(0); } return dos; }
[ "private", "DataOutputStream", "getDataStream", "(", "int", "keyLength", ")", "throws", "IOException", "{", "// Resize array if necessary", "if", "(", "dataStreams", ".", "length", "<=", "keyLength", ")", "{", "dataStreams", "=", "Arrays", ".", "copyOf", "(", "dataStreams", ",", "keyLength", "+", "1", ")", ";", "dataFiles", "=", "Arrays", ".", "copyOf", "(", "dataFiles", ",", "keyLength", "+", "1", ")", ";", "}", "DataOutputStream", "dos", "=", "dataStreams", "[", "keyLength", "]", ";", "if", "(", "dos", "==", "null", ")", "{", "File", "file", "=", "new", "File", "(", "tempFolder", ",", "\"data\"", "+", "keyLength", "+", "\".dat\"", ")", ";", "file", ".", "deleteOnExit", "(", ")", ";", "dataFiles", "[", "keyLength", "]", "=", "file", ";", "dos", "=", "new", "DataOutputStream", "(", "new", "BufferedOutputStream", "(", "new", "FileOutputStream", "(", "file", ")", ")", ")", ";", "dataStreams", "[", "keyLength", "]", "=", "dos", ";", "// Write one byte so the zero offset is reserved", "dos", ".", "writeByte", "(", "0", ")", ";", "}", "return", "dos", ";", "}" ]
Get the data stream for the specified keyLength, create it if needed
[ "Get", "the", "data", "stream", "for", "the", "specified", "keyLength", "create", "it", "if", "needed" ]
train
https://github.com/linkedin/PalDB/blob/d05ccdd3f67855eb2675dbd82599f19aa7a9f650/paldb/src/main/java/com/linkedin/paldb/impl/StorageWriter.java#L429-L450
OpenTSDB/opentsdb
src/tsd/QueryRpc.java
QueryRpc.handleExpressionQuery
private void handleExpressionQuery(final TSDB tsdb, final HttpQuery query) { """ Handles an expression query @param tsdb The TSDB to which we belong @param query The HTTP query to parse/respond @since 2.3 """ final net.opentsdb.query.pojo.Query v2_query = JSON.parseToObject(query.getContent(), net.opentsdb.query.pojo.Query.class); v2_query.validate(); checkAuthorization(tsdb, query.channel(), v2_query); final QueryExecutor executor = new QueryExecutor(tsdb, v2_query); executor.execute(query); }
java
private void handleExpressionQuery(final TSDB tsdb, final HttpQuery query) { final net.opentsdb.query.pojo.Query v2_query = JSON.parseToObject(query.getContent(), net.opentsdb.query.pojo.Query.class); v2_query.validate(); checkAuthorization(tsdb, query.channel(), v2_query); final QueryExecutor executor = new QueryExecutor(tsdb, v2_query); executor.execute(query); }
[ "private", "void", "handleExpressionQuery", "(", "final", "TSDB", "tsdb", ",", "final", "HttpQuery", "query", ")", "{", "final", "net", ".", "opentsdb", ".", "query", ".", "pojo", ".", "Query", "v2_query", "=", "JSON", ".", "parseToObject", "(", "query", ".", "getContent", "(", ")", ",", "net", ".", "opentsdb", ".", "query", ".", "pojo", ".", "Query", ".", "class", ")", ";", "v2_query", ".", "validate", "(", ")", ";", "checkAuthorization", "(", "tsdb", ",", "query", ".", "channel", "(", ")", ",", "v2_query", ")", ";", "final", "QueryExecutor", "executor", "=", "new", "QueryExecutor", "(", "tsdb", ",", "v2_query", ")", ";", "executor", ".", "execute", "(", "query", ")", ";", "}" ]
Handles an expression query @param tsdb The TSDB to which we belong @param query The HTTP query to parse/respond @since 2.3
[ "Handles", "an", "expression", "query" ]
train
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/tsd/QueryRpc.java#L330-L339
OpenLiberty/open-liberty
dev/com.ibm.ws.transport.http/src/com/ibm/ws/http/channel/internal/HttpChannelConfig.java
HttpChannelConfig.parseAccessLog
private void parseAccessLog(Map<Object, Object> props) { """ Parse the NCSA access log information from the property map. @param props """ String id = (String) props.get(HttpConfigConstants.PROPNAME_ACCESSLOG_ID); if (id != null) { AtomicReference<AccessLog> aLog = HttpEndpointImpl.getAccessLogger(id); if (aLog != null) { this.accessLogger = aLog; } if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Config: using logging service", accessLogger); } } }
java
private void parseAccessLog(Map<Object, Object> props) { String id = (String) props.get(HttpConfigConstants.PROPNAME_ACCESSLOG_ID); if (id != null) { AtomicReference<AccessLog> aLog = HttpEndpointImpl.getAccessLogger(id); if (aLog != null) { this.accessLogger = aLog; } if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Config: using logging service", accessLogger); } } }
[ "private", "void", "parseAccessLog", "(", "Map", "<", "Object", ",", "Object", ">", "props", ")", "{", "String", "id", "=", "(", "String", ")", "props", ".", "get", "(", "HttpConfigConstants", ".", "PROPNAME_ACCESSLOG_ID", ")", ";", "if", "(", "id", "!=", "null", ")", "{", "AtomicReference", "<", "AccessLog", ">", "aLog", "=", "HttpEndpointImpl", ".", "getAccessLogger", "(", "id", ")", ";", "if", "(", "aLog", "!=", "null", ")", "{", "this", ".", "accessLogger", "=", "aLog", ";", "}", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isDebugEnabled", "(", ")", ")", "{", "Tr", ".", "debug", "(", "tc", ",", "\"Config: using logging service\"", ",", "accessLogger", ")", ";", "}", "}", "}" ]
Parse the NCSA access log information from the property map. @param props
[ "Parse", "the", "NCSA", "access", "log", "information", "from", "the", "property", "map", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.transport.http/src/com/ibm/ws/http/channel/internal/HttpChannelConfig.java#L918-L931
Azure/azure-sdk-for-java
appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServiceEnvironmentsInner.java
AppServiceEnvironmentsInner.listVipsAsync
public Observable<AddressResponseInner> listVipsAsync(String resourceGroupName, String name) { """ Get IP addresses assigned to an App Service Environment. Get IP addresses assigned to an App Service Environment. @param resourceGroupName Name of the resource group to which the resource belongs. @param name Name of the App Service Environment. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the AddressResponseInner object """ return listVipsWithServiceResponseAsync(resourceGroupName, name).map(new Func1<ServiceResponse<AddressResponseInner>, AddressResponseInner>() { @Override public AddressResponseInner call(ServiceResponse<AddressResponseInner> response) { return response.body(); } }); }
java
public Observable<AddressResponseInner> listVipsAsync(String resourceGroupName, String name) { return listVipsWithServiceResponseAsync(resourceGroupName, name).map(new Func1<ServiceResponse<AddressResponseInner>, AddressResponseInner>() { @Override public AddressResponseInner call(ServiceResponse<AddressResponseInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "AddressResponseInner", ">", "listVipsAsync", "(", "String", "resourceGroupName", ",", "String", "name", ")", "{", "return", "listVipsWithServiceResponseAsync", "(", "resourceGroupName", ",", "name", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "AddressResponseInner", ">", ",", "AddressResponseInner", ">", "(", ")", "{", "@", "Override", "public", "AddressResponseInner", "call", "(", "ServiceResponse", "<", "AddressResponseInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Get IP addresses assigned to an App Service Environment. Get IP addresses assigned to an App Service Environment. @param resourceGroupName Name of the resource group to which the resource belongs. @param name Name of the App Service Environment. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the AddressResponseInner object
[ "Get", "IP", "addresses", "assigned", "to", "an", "App", "Service", "Environment", ".", "Get", "IP", "addresses", "assigned", "to", "an", "App", "Service", "Environment", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServiceEnvironmentsInner.java#L1453-L1460
looly/hutool
hutool-core/src/main/java/cn/hutool/core/util/NumberUtil.java
NumberUtil.div
public static BigDecimal div(String v1, String v2, int scale, RoundingMode roundingMode) { """ 提供(相对)精确的除法运算,当发生除不尽的情况时,由scale指定精确度 @param v1 被除数 @param v2 除数 @param scale 精确度,如果为负值,取绝对值 @param roundingMode 保留小数的模式 {@link RoundingMode} @return 两个参数的商 """ return div(new BigDecimal(v1), new BigDecimal(v2), scale, roundingMode); }
java
public static BigDecimal div(String v1, String v2, int scale, RoundingMode roundingMode) { return div(new BigDecimal(v1), new BigDecimal(v2), scale, roundingMode); }
[ "public", "static", "BigDecimal", "div", "(", "String", "v1", ",", "String", "v2", ",", "int", "scale", ",", "RoundingMode", "roundingMode", ")", "{", "return", "div", "(", "new", "BigDecimal", "(", "v1", ")", ",", "new", "BigDecimal", "(", "v2", ")", ",", "scale", ",", "roundingMode", ")", ";", "}" ]
提供(相对)精确的除法运算,当发生除不尽的情况时,由scale指定精确度 @param v1 被除数 @param v2 除数 @param scale 精确度,如果为负值,取绝对值 @param roundingMode 保留小数的模式 {@link RoundingMode} @return 两个参数的商
[ "提供", "(", "相对", ")", "精确的除法运算", "当发生除不尽的情况时", "由scale指定精确度" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/NumberUtil.java#L727-L729
mebigfatguy/fb-contrib
src/main/java/com/mebigfatguy/fbcontrib/detect/ExceptionSoftening.java
ExceptionSoftening.findMethod
@Nullable private static Method findMethod(JavaClass cls, String methodName, String methodSig) { """ finds a method that matches the name and signature in the given class @param cls the class to look in @param methodName the name to look for @param methodSig the signature to look for @return the method or null """ Method[] methods = cls.getMethods(); for (Method method : methods) { if (method.getName().equals(methodName) && method.getSignature().equals(methodSig)) { return method; } } return null; }
java
@Nullable private static Method findMethod(JavaClass cls, String methodName, String methodSig) { Method[] methods = cls.getMethods(); for (Method method : methods) { if (method.getName().equals(methodName) && method.getSignature().equals(methodSig)) { return method; } } return null; }
[ "@", "Nullable", "private", "static", "Method", "findMethod", "(", "JavaClass", "cls", ",", "String", "methodName", ",", "String", "methodSig", ")", "{", "Method", "[", "]", "methods", "=", "cls", ".", "getMethods", "(", ")", ";", "for", "(", "Method", "method", ":", "methods", ")", "{", "if", "(", "method", ".", "getName", "(", ")", ".", "equals", "(", "methodName", ")", "&&", "method", ".", "getSignature", "(", ")", ".", "equals", "(", "methodSig", ")", ")", "{", "return", "method", ";", "}", "}", "return", "null", ";", "}" ]
finds a method that matches the name and signature in the given class @param cls the class to look in @param methodName the name to look for @param methodSig the signature to look for @return the method or null
[ "finds", "a", "method", "that", "matches", "the", "name", "and", "signature", "in", "the", "given", "class" ]
train
https://github.com/mebigfatguy/fb-contrib/blob/3b5203196f627b399fbcea3c2ab2b1f4e56cc7b8/src/main/java/com/mebigfatguy/fbcontrib/detect/ExceptionSoftening.java#L430-L439
Axway/Grapes
utils/src/main/java/org/axway/grapes/utils/client/GrapesClient.java
GrapesClient.getArtifactVersions
public List<String> getArtifactVersions(final String gavc) throws GrapesCommunicationException { """ Returns the artifact available versions @param gavc String @return List<String> """ final Client client = getClient(); final WebResource resource = client.resource(serverURL).path(RequestUtils.getArtifactVersions(gavc)); final ClientResponse response = resource .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); client.destroy(); if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){ final String message = FAILED_TO_GET_CORPORATE_FILTERS; if(LOG.isErrorEnabled()) { LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus())); } throw new GrapesCommunicationException(message, response.getStatus()); } return response.getEntity(new GenericType<List<String>>(){}); }
java
public List<String> getArtifactVersions(final String gavc) throws GrapesCommunicationException { final Client client = getClient(); final WebResource resource = client.resource(serverURL).path(RequestUtils.getArtifactVersions(gavc)); final ClientResponse response = resource .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); client.destroy(); if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){ final String message = FAILED_TO_GET_CORPORATE_FILTERS; if(LOG.isErrorEnabled()) { LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus())); } throw new GrapesCommunicationException(message, response.getStatus()); } return response.getEntity(new GenericType<List<String>>(){}); }
[ "public", "List", "<", "String", ">", "getArtifactVersions", "(", "final", "String", "gavc", ")", "throws", "GrapesCommunicationException", "{", "final", "Client", "client", "=", "getClient", "(", ")", ";", "final", "WebResource", "resource", "=", "client", ".", "resource", "(", "serverURL", ")", ".", "path", "(", "RequestUtils", ".", "getArtifactVersions", "(", "gavc", ")", ")", ";", "final", "ClientResponse", "response", "=", "resource", ".", "accept", "(", "MediaType", ".", "APPLICATION_JSON", ")", ".", "get", "(", "ClientResponse", ".", "class", ")", ";", "client", ".", "destroy", "(", ")", ";", "if", "(", "ClientResponse", ".", "Status", ".", "OK", ".", "getStatusCode", "(", ")", "!=", "response", ".", "getStatus", "(", ")", ")", "{", "final", "String", "message", "=", "FAILED_TO_GET_CORPORATE_FILTERS", ";", "if", "(", "LOG", ".", "isErrorEnabled", "(", ")", ")", "{", "LOG", ".", "error", "(", "String", ".", "format", "(", "HTTP_STATUS_TEMPLATE_MSG", ",", "message", ",", "response", ".", "getStatus", "(", ")", ")", ")", ";", "}", "throw", "new", "GrapesCommunicationException", "(", "message", ",", "response", ".", "getStatus", "(", ")", ")", ";", "}", "return", "response", ".", "getEntity", "(", "new", "GenericType", "<", "List", "<", "String", ">", ">", "(", ")", "{", "}", ")", ";", "}" ]
Returns the artifact available versions @param gavc String @return List<String>
[ "Returns", "the", "artifact", "available", "versions" ]
train
https://github.com/Axway/Grapes/blob/ce9cc73d85f83eaa5fbc991abb593915a8c8374e/utils/src/main/java/org/axway/grapes/utils/client/GrapesClient.java#L561-L578
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/earlystopping/trainer/BaseEarlyStoppingTrainer.java
BaseEarlyStoppingTrainer.triggerEpochListeners
protected void triggerEpochListeners(boolean epochStart, Model model, int epochNum) { """ Trigger epoch listener methods manually - these won't be triggered due to not calling fit(DataSetIterator) etc """ Collection<TrainingListener> listeners; if(model instanceof MultiLayerNetwork){ MultiLayerNetwork n = ((MultiLayerNetwork) model); listeners = n.getListeners(); n.setEpochCount(epochNum); } else if(model instanceof ComputationGraph){ ComputationGraph cg = ((ComputationGraph) model); listeners = cg.getListeners(); cg.getConfiguration().setEpochCount(epochNum); } else { return; } if(listeners != null && !listeners.isEmpty()){ for (TrainingListener l : listeners) { if (epochStart) { l.onEpochStart(model); } else { l.onEpochEnd(model); } } } }
java
protected void triggerEpochListeners(boolean epochStart, Model model, int epochNum){ Collection<TrainingListener> listeners; if(model instanceof MultiLayerNetwork){ MultiLayerNetwork n = ((MultiLayerNetwork) model); listeners = n.getListeners(); n.setEpochCount(epochNum); } else if(model instanceof ComputationGraph){ ComputationGraph cg = ((ComputationGraph) model); listeners = cg.getListeners(); cg.getConfiguration().setEpochCount(epochNum); } else { return; } if(listeners != null && !listeners.isEmpty()){ for (TrainingListener l : listeners) { if (epochStart) { l.onEpochStart(model); } else { l.onEpochEnd(model); } } } }
[ "protected", "void", "triggerEpochListeners", "(", "boolean", "epochStart", ",", "Model", "model", ",", "int", "epochNum", ")", "{", "Collection", "<", "TrainingListener", ">", "listeners", ";", "if", "(", "model", "instanceof", "MultiLayerNetwork", ")", "{", "MultiLayerNetwork", "n", "=", "(", "(", "MultiLayerNetwork", ")", "model", ")", ";", "listeners", "=", "n", ".", "getListeners", "(", ")", ";", "n", ".", "setEpochCount", "(", "epochNum", ")", ";", "}", "else", "if", "(", "model", "instanceof", "ComputationGraph", ")", "{", "ComputationGraph", "cg", "=", "(", "(", "ComputationGraph", ")", "model", ")", ";", "listeners", "=", "cg", ".", "getListeners", "(", ")", ";", "cg", ".", "getConfiguration", "(", ")", ".", "setEpochCount", "(", "epochNum", ")", ";", "}", "else", "{", "return", ";", "}", "if", "(", "listeners", "!=", "null", "&&", "!", "listeners", ".", "isEmpty", "(", ")", ")", "{", "for", "(", "TrainingListener", "l", ":", "listeners", ")", "{", "if", "(", "epochStart", ")", "{", "l", ".", "onEpochStart", "(", "model", ")", ";", "}", "else", "{", "l", ".", "onEpochEnd", "(", "model", ")", ";", "}", "}", "}", "}" ]
Trigger epoch listener methods manually - these won't be triggered due to not calling fit(DataSetIterator) etc
[ "Trigger", "epoch", "listener", "methods", "manually", "-", "these", "won", "t", "be", "triggered", "due", "to", "not", "calling", "fit", "(", "DataSetIterator", ")", "etc" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/earlystopping/trainer/BaseEarlyStoppingTrainer.java#L342-L365
Waikato/jclasslocator
src/main/java/nz/ac/waikato/cms/locator/ClassCompare.java
ClassCompare.fillUp
protected String fillUp(String s, int len) { """ appends blanks to the string if its shorter than <code>len</code>. @param s the string to pad @param len the minimum length for the string to have @return the padded string """ while (s.length() < len) s += " "; return s; }
java
protected String fillUp(String s, int len) { while (s.length() < len) s += " "; return s; }
[ "protected", "String", "fillUp", "(", "String", "s", ",", "int", "len", ")", "{", "while", "(", "s", ".", "length", "(", ")", "<", "len", ")", "s", "+=", "\" \"", ";", "return", "s", ";", "}" ]
appends blanks to the string if its shorter than <code>len</code>. @param s the string to pad @param len the minimum length for the string to have @return the padded string
[ "appends", "blanks", "to", "the", "string", "if", "its", "shorter", "than", "<code", ">", "len<", "/", "code", ">", "." ]
train
https://github.com/Waikato/jclasslocator/blob/c899072fff607a56ee7f8c2d01fbeb15157ad144/src/main/java/nz/ac/waikato/cms/locator/ClassCompare.java#L60-L64
DigitalPebble/TextClassification
src/main/java/com/digitalpebble/classification/TextClassifier.java
TextClassifier.getClassifier
public static TextClassifier getClassifier(File resourceDirectoryFile) throws Exception { """ Returns a specific instance of a Text Classifier given a resource Directory @throws Exception """ // check whether we need to unzip the resources first if (resourceDirectoryFile.toString().endsWith(".zip") && resourceDirectoryFile.isFile()) { resourceDirectoryFile = UnZip.unzip(resourceDirectoryFile); } // check the existence of the path if (resourceDirectoryFile.exists() == false) throw new IOException("Directory " + resourceDirectoryFile.getAbsolutePath() + " does not exist"); // check that the lexicon files exists (e.g. its name should be simply // 'lexicon') File lexiconFile = new File(resourceDirectoryFile, Parameters.lexiconName); if (lexiconFile.exists() == false) throw new IOException("Lexicon " + lexiconFile + " does not exist"); // and that there is a model file File modelFile = new File(resourceDirectoryFile, Parameters.modelName); if (modelFile.exists() == false) throw new IOException("Model " + modelFile + " does not exist"); Lexicon lexicon = new Lexicon(lexiconFile.toString()); // ask the Lexicon for the classifier to use String classifier = lexicon.getClassifierType(); TextClassifier instance = (TextClassifier) Class.forName(classifier) .newInstance(); // set the last modification info instance.lastmodifiedLexicon = lexiconFile.lastModified(); // set the pathResourceDirectory instance.pathResourceDirectory = resourceDirectoryFile .getAbsolutePath(); // set the model instance.lexicon = lexicon; instance.loadModel(); return instance; }
java
public static TextClassifier getClassifier(File resourceDirectoryFile) throws Exception { // check whether we need to unzip the resources first if (resourceDirectoryFile.toString().endsWith(".zip") && resourceDirectoryFile.isFile()) { resourceDirectoryFile = UnZip.unzip(resourceDirectoryFile); } // check the existence of the path if (resourceDirectoryFile.exists() == false) throw new IOException("Directory " + resourceDirectoryFile.getAbsolutePath() + " does not exist"); // check that the lexicon files exists (e.g. its name should be simply // 'lexicon') File lexiconFile = new File(resourceDirectoryFile, Parameters.lexiconName); if (lexiconFile.exists() == false) throw new IOException("Lexicon " + lexiconFile + " does not exist"); // and that there is a model file File modelFile = new File(resourceDirectoryFile, Parameters.modelName); if (modelFile.exists() == false) throw new IOException("Model " + modelFile + " does not exist"); Lexicon lexicon = new Lexicon(lexiconFile.toString()); // ask the Lexicon for the classifier to use String classifier = lexicon.getClassifierType(); TextClassifier instance = (TextClassifier) Class.forName(classifier) .newInstance(); // set the last modification info instance.lastmodifiedLexicon = lexiconFile.lastModified(); // set the pathResourceDirectory instance.pathResourceDirectory = resourceDirectoryFile .getAbsolutePath(); // set the model instance.lexicon = lexicon; instance.loadModel(); return instance; }
[ "public", "static", "TextClassifier", "getClassifier", "(", "File", "resourceDirectoryFile", ")", "throws", "Exception", "{", "// check whether we need to unzip the resources first\r", "if", "(", "resourceDirectoryFile", ".", "toString", "(", ")", ".", "endsWith", "(", "\".zip\"", ")", "&&", "resourceDirectoryFile", ".", "isFile", "(", ")", ")", "{", "resourceDirectoryFile", "=", "UnZip", ".", "unzip", "(", "resourceDirectoryFile", ")", ";", "}", "// check the existence of the path\r", "if", "(", "resourceDirectoryFile", ".", "exists", "(", ")", "==", "false", ")", "throw", "new", "IOException", "(", "\"Directory \"", "+", "resourceDirectoryFile", ".", "getAbsolutePath", "(", ")", "+", "\" does not exist\"", ")", ";", "// check that the lexicon files exists (e.g. its name should be simply\r", "// 'lexicon')\r", "File", "lexiconFile", "=", "new", "File", "(", "resourceDirectoryFile", ",", "Parameters", ".", "lexiconName", ")", ";", "if", "(", "lexiconFile", ".", "exists", "(", ")", "==", "false", ")", "throw", "new", "IOException", "(", "\"Lexicon \"", "+", "lexiconFile", "+", "\" does not exist\"", ")", ";", "// and that there is a model file\r", "File", "modelFile", "=", "new", "File", "(", "resourceDirectoryFile", ",", "Parameters", ".", "modelName", ")", ";", "if", "(", "modelFile", ".", "exists", "(", ")", "==", "false", ")", "throw", "new", "IOException", "(", "\"Model \"", "+", "modelFile", "+", "\" does not exist\"", ")", ";", "Lexicon", "lexicon", "=", "new", "Lexicon", "(", "lexiconFile", ".", "toString", "(", ")", ")", ";", "// ask the Lexicon for the classifier to use\r", "String", "classifier", "=", "lexicon", ".", "getClassifierType", "(", ")", ";", "TextClassifier", "instance", "=", "(", "TextClassifier", ")", "Class", ".", "forName", "(", "classifier", ")", ".", "newInstance", "(", ")", ";", "// set the last modification info\r", "instance", ".", "lastmodifiedLexicon", "=", "lexiconFile", ".", "lastModified", "(", ")", ";", "// set the pathResourceDirectory\r", "instance", ".", "pathResourceDirectory", "=", "resourceDirectoryFile", ".", "getAbsolutePath", "(", ")", ";", "// set the model\r", "instance", ".", "lexicon", "=", "lexicon", ";", "instance", ".", "loadModel", "(", ")", ";", "return", "instance", ";", "}" ]
Returns a specific instance of a Text Classifier given a resource Directory @throws Exception
[ "Returns", "a", "specific", "instance", "of", "a", "Text", "Classifier", "given", "a", "resource", "Directory" ]
train
https://github.com/DigitalPebble/TextClassification/blob/c510719c31633841af2bf393a20707d4624f865d/src/main/java/com/digitalpebble/classification/TextClassifier.java#L46-L82
jenkinsci/email-ext-plugin
src/main/java/hudson/plugins/emailext/plugins/content/ScriptContent.java
ScriptContent.executeScript
private String executeScript(Run<?, ?> build, FilePath workspace, TaskListener listener, InputStream scriptStream) throws IOException { """ Executes a script and returns the last value as a String @param build the build to act on @param scriptStream the script input stream @return a String containing the toString of the last item in the script @throws IOException """ String result = ""; Map binding = new HashMap<>(); ExtendedEmailPublisherDescriptor descriptor = Jenkins.getActiveInstance().getDescriptorByType(ExtendedEmailPublisherDescriptor.class); Item parent = build.getParent(); binding.put("build", build); binding.put("it", new ScriptContentBuildWrapper(build)); binding.put("project", parent); binding.put("rooturl", descriptor.getHudsonUrl()); binding.put("workspace", workspace); PrintStream logger = listener.getLogger(); binding.put("logger", logger); String scriptContent = IOUtils.toString(scriptStream, descriptor.getCharset()); if (scriptStream instanceof UserProvidedContentInputStream) { ScriptApproval.get().configuring(scriptContent, GroovyLanguage.get(), ApprovalContext.create().withItem(parent)); } if (scriptStream instanceof UserProvidedContentInputStream && !AbstractEvalContent.isApprovedScript(scriptContent, GroovyLanguage.get())) { //Unapproved script, run it in the sandbox GroovyShell shell = createEngine(descriptor, binding, true); Object res = GroovySandbox.run(shell, scriptContent, new ProxyWhitelist( Whitelist.all(), new PrintStreamInstanceWhitelist(logger), new EmailExtScriptTokenMacroWhitelist() )); if (res != null) { result = res.toString(); } } else { if (scriptStream instanceof UserProvidedContentInputStream) { ScriptApproval.get().using(scriptContent, GroovyLanguage.get()); } //Pre approved script, so run as is GroovyShell shell = createEngine(descriptor, binding, false); Script script = shell.parse(scriptContent); Object res = script.run(); if (res != null) { result = res.toString(); } } return result; }
java
private String executeScript(Run<?, ?> build, FilePath workspace, TaskListener listener, InputStream scriptStream) throws IOException { String result = ""; Map binding = new HashMap<>(); ExtendedEmailPublisherDescriptor descriptor = Jenkins.getActiveInstance().getDescriptorByType(ExtendedEmailPublisherDescriptor.class); Item parent = build.getParent(); binding.put("build", build); binding.put("it", new ScriptContentBuildWrapper(build)); binding.put("project", parent); binding.put("rooturl", descriptor.getHudsonUrl()); binding.put("workspace", workspace); PrintStream logger = listener.getLogger(); binding.put("logger", logger); String scriptContent = IOUtils.toString(scriptStream, descriptor.getCharset()); if (scriptStream instanceof UserProvidedContentInputStream) { ScriptApproval.get().configuring(scriptContent, GroovyLanguage.get(), ApprovalContext.create().withItem(parent)); } if (scriptStream instanceof UserProvidedContentInputStream && !AbstractEvalContent.isApprovedScript(scriptContent, GroovyLanguage.get())) { //Unapproved script, run it in the sandbox GroovyShell shell = createEngine(descriptor, binding, true); Object res = GroovySandbox.run(shell, scriptContent, new ProxyWhitelist( Whitelist.all(), new PrintStreamInstanceWhitelist(logger), new EmailExtScriptTokenMacroWhitelist() )); if (res != null) { result = res.toString(); } } else { if (scriptStream instanceof UserProvidedContentInputStream) { ScriptApproval.get().using(scriptContent, GroovyLanguage.get()); } //Pre approved script, so run as is GroovyShell shell = createEngine(descriptor, binding, false); Script script = shell.parse(scriptContent); Object res = script.run(); if (res != null) { result = res.toString(); } } return result; }
[ "private", "String", "executeScript", "(", "Run", "<", "?", ",", "?", ">", "build", ",", "FilePath", "workspace", ",", "TaskListener", "listener", ",", "InputStream", "scriptStream", ")", "throws", "IOException", "{", "String", "result", "=", "\"\"", ";", "Map", "binding", "=", "new", "HashMap", "<>", "(", ")", ";", "ExtendedEmailPublisherDescriptor", "descriptor", "=", "Jenkins", ".", "getActiveInstance", "(", ")", ".", "getDescriptorByType", "(", "ExtendedEmailPublisherDescriptor", ".", "class", ")", ";", "Item", "parent", "=", "build", ".", "getParent", "(", ")", ";", "binding", ".", "put", "(", "\"build\"", ",", "build", ")", ";", "binding", ".", "put", "(", "\"it\"", ",", "new", "ScriptContentBuildWrapper", "(", "build", ")", ")", ";", "binding", ".", "put", "(", "\"project\"", ",", "parent", ")", ";", "binding", ".", "put", "(", "\"rooturl\"", ",", "descriptor", ".", "getHudsonUrl", "(", ")", ")", ";", "binding", ".", "put", "(", "\"workspace\"", ",", "workspace", ")", ";", "PrintStream", "logger", "=", "listener", ".", "getLogger", "(", ")", ";", "binding", ".", "put", "(", "\"logger\"", ",", "logger", ")", ";", "String", "scriptContent", "=", "IOUtils", ".", "toString", "(", "scriptStream", ",", "descriptor", ".", "getCharset", "(", ")", ")", ";", "if", "(", "scriptStream", "instanceof", "UserProvidedContentInputStream", ")", "{", "ScriptApproval", ".", "get", "(", ")", ".", "configuring", "(", "scriptContent", ",", "GroovyLanguage", ".", "get", "(", ")", ",", "ApprovalContext", ".", "create", "(", ")", ".", "withItem", "(", "parent", ")", ")", ";", "}", "if", "(", "scriptStream", "instanceof", "UserProvidedContentInputStream", "&&", "!", "AbstractEvalContent", ".", "isApprovedScript", "(", "scriptContent", ",", "GroovyLanguage", ".", "get", "(", ")", ")", ")", "{", "//Unapproved script, run it in the sandbox", "GroovyShell", "shell", "=", "createEngine", "(", "descriptor", ",", "binding", ",", "true", ")", ";", "Object", "res", "=", "GroovySandbox", ".", "run", "(", "shell", ",", "scriptContent", ",", "new", "ProxyWhitelist", "(", "Whitelist", ".", "all", "(", ")", ",", "new", "PrintStreamInstanceWhitelist", "(", "logger", ")", ",", "new", "EmailExtScriptTokenMacroWhitelist", "(", ")", ")", ")", ";", "if", "(", "res", "!=", "null", ")", "{", "result", "=", "res", ".", "toString", "(", ")", ";", "}", "}", "else", "{", "if", "(", "scriptStream", "instanceof", "UserProvidedContentInputStream", ")", "{", "ScriptApproval", ".", "get", "(", ")", ".", "using", "(", "scriptContent", ",", "GroovyLanguage", ".", "get", "(", ")", ")", ";", "}", "//Pre approved script, so run as is", "GroovyShell", "shell", "=", "createEngine", "(", "descriptor", ",", "binding", ",", "false", ")", ";", "Script", "script", "=", "shell", ".", "parse", "(", "scriptContent", ")", ";", "Object", "res", "=", "script", ".", "run", "(", ")", ";", "if", "(", "res", "!=", "null", ")", "{", "result", "=", "res", ".", "toString", "(", ")", ";", "}", "}", "return", "result", ";", "}" ]
Executes a script and returns the last value as a String @param build the build to act on @param scriptStream the script input stream @return a String containing the toString of the last item in the script @throws IOException
[ "Executes", "a", "script", "and", "returns", "the", "last", "value", "as", "a", "String" ]
train
https://github.com/jenkinsci/email-ext-plugin/blob/21fbd402665848a18205b26751424149e51e86e4/src/main/java/hudson/plugins/emailext/plugins/content/ScriptContent.java#L186-L233
alkacon/opencms-core
src/org/opencms/db/CmsDriverManager.java
CmsDriverManager.getLock
public CmsLock getLock(CmsDbContext dbc, CmsResource resource) throws CmsException { """ Returns the lock state of a resource.<p> @param dbc the current database context @param resource the resource to return the lock state for @return the lock state of the resource @throws CmsException if something goes wrong """ return m_lockManager.getLock(dbc, resource); }
java
public CmsLock getLock(CmsDbContext dbc, CmsResource resource) throws CmsException { return m_lockManager.getLock(dbc, resource); }
[ "public", "CmsLock", "getLock", "(", "CmsDbContext", "dbc", ",", "CmsResource", "resource", ")", "throws", "CmsException", "{", "return", "m_lockManager", ".", "getLock", "(", "dbc", ",", "resource", ")", ";", "}" ]
Returns the lock state of a resource.<p> @param dbc the current database context @param resource the resource to return the lock state for @return the lock state of the resource @throws CmsException if something goes wrong
[ "Returns", "the", "lock", "state", "of", "a", "resource", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsDriverManager.java#L4083-L4086
kiegroup/drools
drools-compiler/src/main/java/org/drools/compiler/compiler/BuilderResultUtils.java
BuilderResultUtils.getProblemMessage
public static String getProblemMessage(Object object, String summary, String separator) { """ Appends compilation problems to summary message if object is an array of {@link CompilationProblem} with custom separator @param object object with compilation results @param summary summary message @param separator custom messages separator @return summary message with changes """ if (object instanceof CompilationProblem[]) { return fillSummary( (CompilationProblem[]) object, summary, separator ); } return summary; }
java
public static String getProblemMessage(Object object, String summary, String separator) { if (object instanceof CompilationProblem[]) { return fillSummary( (CompilationProblem[]) object, summary, separator ); } return summary; }
[ "public", "static", "String", "getProblemMessage", "(", "Object", "object", ",", "String", "summary", ",", "String", "separator", ")", "{", "if", "(", "object", "instanceof", "CompilationProblem", "[", "]", ")", "{", "return", "fillSummary", "(", "(", "CompilationProblem", "[", "]", ")", "object", ",", "summary", ",", "separator", ")", ";", "}", "return", "summary", ";", "}" ]
Appends compilation problems to summary message if object is an array of {@link CompilationProblem} with custom separator @param object object with compilation results @param summary summary message @param separator custom messages separator @return summary message with changes
[ "Appends", "compilation", "problems", "to", "summary", "message", "if", "object", "is", "an", "array", "of", "{", "@link", "CompilationProblem", "}", "with", "custom", "separator" ]
train
https://github.com/kiegroup/drools/blob/22b0275d6dbe93070b8090948502cf46eda543c4/drools-compiler/src/main/java/org/drools/compiler/compiler/BuilderResultUtils.java#L36-L41
LAW-Unimi/BUbiNG
src/it/unimi/di/law/warc/records/WarcHeader.java
WarcHeader.parseDate
public static Date parseDate(final String date) throws WarcFormatException { """ Parses the date found in a {@link WarcHeader.Name#WARC_DATE} header. @param date the date. @return the parsed date. """ try { synchronized (W3C_ISO8601_DATE_PARSE) { return W3C_ISO8601_DATE_PARSE.parse(date); } } catch (ParseException e) { throw new WarcFormatException("Error parsing date " + date, e); } }
java
public static Date parseDate(final String date) throws WarcFormatException { try { synchronized (W3C_ISO8601_DATE_PARSE) { return W3C_ISO8601_DATE_PARSE.parse(date); } } catch (ParseException e) { throw new WarcFormatException("Error parsing date " + date, e); } }
[ "public", "static", "Date", "parseDate", "(", "final", "String", "date", ")", "throws", "WarcFormatException", "{", "try", "{", "synchronized", "(", "W3C_ISO8601_DATE_PARSE", ")", "{", "return", "W3C_ISO8601_DATE_PARSE", ".", "parse", "(", "date", ")", ";", "}", "}", "catch", "(", "ParseException", "e", ")", "{", "throw", "new", "WarcFormatException", "(", "\"Error parsing date \"", "+", "date", ",", "e", ")", ";", "}", "}" ]
Parses the date found in a {@link WarcHeader.Name#WARC_DATE} header. @param date the date. @return the parsed date.
[ "Parses", "the", "date", "found", "in", "a", "{", "@link", "WarcHeader", ".", "Name#WARC_DATE", "}", "header", "." ]
train
https://github.com/LAW-Unimi/BUbiNG/blob/e148acc90031a4f3967422705a9fb07ddaf155e4/src/it/unimi/di/law/warc/records/WarcHeader.java#L133-L141
OpenLiberty/open-liberty
dev/com.ibm.ws.security.fat.common/src/com/ibm/ws/security/fat/common/utils/FatStringUtils.java
FatStringUtils.extractRegexGroup
public static String extractRegexGroup(String fromContent, Pattern regex, int groupNumber) throws Exception { """ Extracts the specified matching group in the provided content. An exception is thrown if the group number is invalid (negative or greater than the number of groups found in the content), or if a matching group cannot be found in the content. """ if (fromContent == null) { throw new Exception("Cannot extract regex group because the provided content string is null."); } if (regex == null) { throw new Exception("Cannot extract regex group because the provided regular expression is null."); } if (groupNumber < 0) { throw new Exception("Group number to extract must be non-negative. Provided group number was " + groupNumber); } Matcher matcher = regex.matcher(fromContent); if (!matcher.find()) { throw new Exception("Did not find any matches for regex [" + regex + "] in the provided content: [" + fromContent + "]."); } if (matcher.groupCount() < groupNumber) { throw new Exception("Found " + matcher.groupCount() + " matching groups in the content, but expected at least " + groupNumber + ". Regex was [" + regex + "] and content was [" + fromContent + "]."); } return matcher.group(groupNumber); }
java
public static String extractRegexGroup(String fromContent, Pattern regex, int groupNumber) throws Exception { if (fromContent == null) { throw new Exception("Cannot extract regex group because the provided content string is null."); } if (regex == null) { throw new Exception("Cannot extract regex group because the provided regular expression is null."); } if (groupNumber < 0) { throw new Exception("Group number to extract must be non-negative. Provided group number was " + groupNumber); } Matcher matcher = regex.matcher(fromContent); if (!matcher.find()) { throw new Exception("Did not find any matches for regex [" + regex + "] in the provided content: [" + fromContent + "]."); } if (matcher.groupCount() < groupNumber) { throw new Exception("Found " + matcher.groupCount() + " matching groups in the content, but expected at least " + groupNumber + ". Regex was [" + regex + "] and content was [" + fromContent + "]."); } return matcher.group(groupNumber); }
[ "public", "static", "String", "extractRegexGroup", "(", "String", "fromContent", ",", "Pattern", "regex", ",", "int", "groupNumber", ")", "throws", "Exception", "{", "if", "(", "fromContent", "==", "null", ")", "{", "throw", "new", "Exception", "(", "\"Cannot extract regex group because the provided content string is null.\"", ")", ";", "}", "if", "(", "regex", "==", "null", ")", "{", "throw", "new", "Exception", "(", "\"Cannot extract regex group because the provided regular expression is null.\"", ")", ";", "}", "if", "(", "groupNumber", "<", "0", ")", "{", "throw", "new", "Exception", "(", "\"Group number to extract must be non-negative. Provided group number was \"", "+", "groupNumber", ")", ";", "}", "Matcher", "matcher", "=", "regex", ".", "matcher", "(", "fromContent", ")", ";", "if", "(", "!", "matcher", ".", "find", "(", ")", ")", "{", "throw", "new", "Exception", "(", "\"Did not find any matches for regex [\"", "+", "regex", "+", "\"] in the provided content: [\"", "+", "fromContent", "+", "\"].\"", ")", ";", "}", "if", "(", "matcher", ".", "groupCount", "(", ")", "<", "groupNumber", ")", "{", "throw", "new", "Exception", "(", "\"Found \"", "+", "matcher", ".", "groupCount", "(", ")", "+", "\" matching groups in the content, but expected at least \"", "+", "groupNumber", "+", "\". Regex was [\"", "+", "regex", "+", "\"] and content was [\"", "+", "fromContent", "+", "\"].\"", ")", ";", "}", "return", "matcher", ".", "group", "(", "groupNumber", ")", ";", "}" ]
Extracts the specified matching group in the provided content. An exception is thrown if the group number is invalid (negative or greater than the number of groups found in the content), or if a matching group cannot be found in the content.
[ "Extracts", "the", "specified", "matching", "group", "in", "the", "provided", "content", ".", "An", "exception", "is", "thrown", "if", "the", "group", "number", "is", "invalid", "(", "negative", "or", "greater", "than", "the", "number", "of", "groups", "found", "in", "the", "content", ")", "or", "if", "a", "matching", "group", "cannot", "be", "found", "in", "the", "content", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.fat.common/src/com/ibm/ws/security/fat/common/utils/FatStringUtils.java#L52-L70
GenesysPureEngage/workspace-client-java
src/main/java/com/genesys/internal/workspace/api/UsersApi.java
UsersApi.supervisorRemoteOperation
public ApiSuccessResponse supervisorRemoteOperation(String operationName, String dbid) throws ApiException { """ Logout user remotely for supervisors @param operationName Name of state to change to (required) @param dbid The dbid of the agent. (required) @return ApiSuccessResponse @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body """ ApiResponse<ApiSuccessResponse> resp = supervisorRemoteOperationWithHttpInfo(operationName, dbid); return resp.getData(); }
java
public ApiSuccessResponse supervisorRemoteOperation(String operationName, String dbid) throws ApiException { ApiResponse<ApiSuccessResponse> resp = supervisorRemoteOperationWithHttpInfo(operationName, dbid); return resp.getData(); }
[ "public", "ApiSuccessResponse", "supervisorRemoteOperation", "(", "String", "operationName", ",", "String", "dbid", ")", "throws", "ApiException", "{", "ApiResponse", "<", "ApiSuccessResponse", ">", "resp", "=", "supervisorRemoteOperationWithHttpInfo", "(", "operationName", ",", "dbid", ")", ";", "return", "resp", ".", "getData", "(", ")", ";", "}" ]
Logout user remotely for supervisors @param operationName Name of state to change to (required) @param dbid The dbid of the agent. (required) @return ApiSuccessResponse @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
[ "Logout", "user", "remotely", "for", "supervisors" ]
train
https://github.com/GenesysPureEngage/workspace-client-java/blob/509fdd9e89b9359d012f9a72be95037a3cef53e6/src/main/java/com/genesys/internal/workspace/api/UsersApi.java#L442-L445
sarl/sarl
main/coreplugins/io.sarl.lang.ui/src/io/sarl/lang/ui/quickfix/SARLQuickfixProvider.java
SARLQuickfixProvider.fixClassExpected
@Fix(IssueCodes.CLASS_EXPECTED) public void fixClassExpected(final Issue issue, IssueResolutionAcceptor acceptor) { """ Quick fix for "Class expected". @param issue the issue. @param acceptor the quick fix acceptor. """ ExtendedTypeRemoveModification.accept(this, issue, acceptor); }
java
@Fix(IssueCodes.CLASS_EXPECTED) public void fixClassExpected(final Issue issue, IssueResolutionAcceptor acceptor) { ExtendedTypeRemoveModification.accept(this, issue, acceptor); }
[ "@", "Fix", "(", "IssueCodes", ".", "CLASS_EXPECTED", ")", "public", "void", "fixClassExpected", "(", "final", "Issue", "issue", ",", "IssueResolutionAcceptor", "acceptor", ")", "{", "ExtendedTypeRemoveModification", ".", "accept", "(", "this", ",", "issue", ",", "acceptor", ")", ";", "}" ]
Quick fix for "Class expected". @param issue the issue. @param acceptor the quick fix acceptor.
[ "Quick", "fix", "for", "Class", "expected", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.lang.ui/src/io/sarl/lang/ui/quickfix/SARLQuickfixProvider.java#L845-L848
jayantk/jklol
src/com/jayantkrish/jklol/models/TableFactorBuilder.java
TableFactorBuilder.setWeight
public void setWeight(Assignment a, double weight) { """ Sets the weight of {@code a} to {@code weight} in the table factor returned by {@link #build()}. If {@code a} has already been associated with a weight in {@code this} builder, this call overwrites the old weight. If {@code weight} is 0.0, {@code a} is deleted from this builder. """ Preconditions.checkArgument(a.containsAll(vars.getVariableNumsArray())); weightBuilder.put(vars.assignmentToIntArray(a), weight); }
java
public void setWeight(Assignment a, double weight) { Preconditions.checkArgument(a.containsAll(vars.getVariableNumsArray())); weightBuilder.put(vars.assignmentToIntArray(a), weight); }
[ "public", "void", "setWeight", "(", "Assignment", "a", ",", "double", "weight", ")", "{", "Preconditions", ".", "checkArgument", "(", "a", ".", "containsAll", "(", "vars", ".", "getVariableNumsArray", "(", ")", ")", ")", ";", "weightBuilder", ".", "put", "(", "vars", ".", "assignmentToIntArray", "(", "a", ")", ",", "weight", ")", ";", "}" ]
Sets the weight of {@code a} to {@code weight} in the table factor returned by {@link #build()}. If {@code a} has already been associated with a weight in {@code this} builder, this call overwrites the old weight. If {@code weight} is 0.0, {@code a} is deleted from this builder.
[ "Sets", "the", "weight", "of", "{" ]
train
https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/models/TableFactorBuilder.java#L162-L165
lessthanoptimal/BoofCV
main/boofcv-feature/src/main/java/boofcv/alg/segmentation/fh04/SegmentFelzenszwalbHuttenlocher04.java
SegmentFelzenszwalbHuttenlocher04.process
public void process( T input , GrayS32 output ) { """ Segments the image. Each region in the output image is given a unique ID. To find out what the ID of each region is call {@link #getRegionId()}. To get a list of number of pixels in each region call {@link #getRegionSizes()}. @param input Input image. Not modified. @param output Output segmented image. Modified. """ if( output.isSubimage() ) throw new IllegalArgumentException("Output can't be a sub-image"); InputSanityCheck.checkSameShape(input, output); initialize(input,output); // compute edges weights // long time0 = System.currentTimeMillis(); computeWeights.process(input, edges); // long time1 = System.currentTimeMillis(); // System.out.println("Edge weights time " + (time1 - time0)); // Merge regions together mergeRegions(); // Get rid of small ones mergeSmallRegions(); // compute the final output computeOutput(); }
java
public void process( T input , GrayS32 output ) { if( output.isSubimage() ) throw new IllegalArgumentException("Output can't be a sub-image"); InputSanityCheck.checkSameShape(input, output); initialize(input,output); // compute edges weights // long time0 = System.currentTimeMillis(); computeWeights.process(input, edges); // long time1 = System.currentTimeMillis(); // System.out.println("Edge weights time " + (time1 - time0)); // Merge regions together mergeRegions(); // Get rid of small ones mergeSmallRegions(); // compute the final output computeOutput(); }
[ "public", "void", "process", "(", "T", "input", ",", "GrayS32", "output", ")", "{", "if", "(", "output", ".", "isSubimage", "(", ")", ")", "throw", "new", "IllegalArgumentException", "(", "\"Output can't be a sub-image\"", ")", ";", "InputSanityCheck", ".", "checkSameShape", "(", "input", ",", "output", ")", ";", "initialize", "(", "input", ",", "output", ")", ";", "// compute edges weights", "//\t\tlong time0 = System.currentTimeMillis();", "computeWeights", ".", "process", "(", "input", ",", "edges", ")", ";", "//\t\tlong time1 = System.currentTimeMillis();", "//\t\tSystem.out.println(\"Edge weights time \" + (time1 - time0));", "// Merge regions together", "mergeRegions", "(", ")", ";", "// Get rid of small ones", "mergeSmallRegions", "(", ")", ";", "// compute the final output", "computeOutput", "(", ")", ";", "}" ]
Segments the image. Each region in the output image is given a unique ID. To find out what the ID of each region is call {@link #getRegionId()}. To get a list of number of pixels in each region call {@link #getRegionSizes()}. @param input Input image. Not modified. @param output Output segmented image. Modified.
[ "Segments", "the", "image", ".", "Each", "region", "in", "the", "output", "image", "is", "given", "a", "unique", "ID", ".", "To", "find", "out", "what", "the", "ID", "of", "each", "region", "is", "call", "{", "@link", "#getRegionId", "()", "}", ".", "To", "get", "a", "list", "of", "number", "of", "pixels", "in", "each", "region", "call", "{", "@link", "#getRegionSizes", "()", "}", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/segmentation/fh04/SegmentFelzenszwalbHuttenlocher04.java#L143-L165
Azure/azure-sdk-for-java
sql/resource-manager/v2017_10_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_10_01_preview/implementation/ManagedInstanceKeysInner.java
ManagedInstanceKeysInner.beginCreateOrUpdateAsync
public Observable<ManagedInstanceKeyInner> beginCreateOrUpdateAsync(String resourceGroupName, String managedInstanceName, String keyName, ManagedInstanceKeyInner parameters) { """ Creates or updates a managed instance key. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param managedInstanceName The name of the managed instance. @param keyName The name of the managed instance key to be operated on (updated or created). @param parameters The requested managed instance key resource state. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the ManagedInstanceKeyInner object """ return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, managedInstanceName, keyName, parameters).map(new Func1<ServiceResponse<ManagedInstanceKeyInner>, ManagedInstanceKeyInner>() { @Override public ManagedInstanceKeyInner call(ServiceResponse<ManagedInstanceKeyInner> response) { return response.body(); } }); }
java
public Observable<ManagedInstanceKeyInner> beginCreateOrUpdateAsync(String resourceGroupName, String managedInstanceName, String keyName, ManagedInstanceKeyInner parameters) { return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, managedInstanceName, keyName, parameters).map(new Func1<ServiceResponse<ManagedInstanceKeyInner>, ManagedInstanceKeyInner>() { @Override public ManagedInstanceKeyInner call(ServiceResponse<ManagedInstanceKeyInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "ManagedInstanceKeyInner", ">", "beginCreateOrUpdateAsync", "(", "String", "resourceGroupName", ",", "String", "managedInstanceName", ",", "String", "keyName", ",", "ManagedInstanceKeyInner", "parameters", ")", "{", "return", "beginCreateOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "managedInstanceName", ",", "keyName", ",", "parameters", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "ManagedInstanceKeyInner", ">", ",", "ManagedInstanceKeyInner", ">", "(", ")", "{", "@", "Override", "public", "ManagedInstanceKeyInner", "call", "(", "ServiceResponse", "<", "ManagedInstanceKeyInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Creates or updates a managed instance key. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param managedInstanceName The name of the managed instance. @param keyName The name of the managed instance key to be operated on (updated or created). @param parameters The requested managed instance key resource state. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the ManagedInstanceKeyInner object
[ "Creates", "or", "updates", "a", "managed", "instance", "key", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2017_10_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_10_01_preview/implementation/ManagedInstanceKeysInner.java#L557-L564
mapsforge/mapsforge
mapsforge-map/src/main/java/org/mapsforge/map/layer/Layers.java
Layers.addAll
public synchronized void addAll(Collection<Layer> layers, boolean redraw) { """ Adds multiple new layers on top. @param layers The new layers to add @param redraw Whether the map should be redrawn after adding the layers @see List#addAll(Collection) """ checkIsNull(layers); for (Layer layer : layers) { layer.setDisplayModel(this.displayModel); } this.layersList.addAll(layers); for (Layer layer : layers) { layer.assign(this.redrawer); } if (redraw) { this.redrawer.redrawLayers(); } }
java
public synchronized void addAll(Collection<Layer> layers, boolean redraw) { checkIsNull(layers); for (Layer layer : layers) { layer.setDisplayModel(this.displayModel); } this.layersList.addAll(layers); for (Layer layer : layers) { layer.assign(this.redrawer); } if (redraw) { this.redrawer.redrawLayers(); } }
[ "public", "synchronized", "void", "addAll", "(", "Collection", "<", "Layer", ">", "layers", ",", "boolean", "redraw", ")", "{", "checkIsNull", "(", "layers", ")", ";", "for", "(", "Layer", "layer", ":", "layers", ")", "{", "layer", ".", "setDisplayModel", "(", "this", ".", "displayModel", ")", ";", "}", "this", ".", "layersList", ".", "addAll", "(", "layers", ")", ";", "for", "(", "Layer", "layer", ":", "layers", ")", "{", "layer", ".", "assign", "(", "this", ".", "redrawer", ")", ";", "}", "if", "(", "redraw", ")", "{", "this", ".", "redrawer", ".", "redrawLayers", "(", ")", ";", "}", "}" ]
Adds multiple new layers on top. @param layers The new layers to add @param redraw Whether the map should be redrawn after adding the layers @see List#addAll(Collection)
[ "Adds", "multiple", "new", "layers", "on", "top", "." ]
train
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-map/src/main/java/org/mapsforge/map/layer/Layers.java#L142-L154
rwl/CSparseJ
src/main/java/edu/emory/mathcs/csparsej/tdouble/Dcs_sqr.java
Dcs_sqr.cs_sqr
public static Dcss cs_sqr(int order, Dcs A, boolean qr) { """ Symbolic QR or LU ordering and analysis. @param order ordering method to use (0 to 3) @param A column-compressed matrix @param qr analyze for QR if true or LU if false @return symbolic analysis for QR or LU, null on error """ int n, k, post[]; Dcss S; boolean ok = true; if (!Dcs_util.CS_CSC(A)) return (null); /* check inputs */ n = A.n; S = new Dcss(); /* allocate result S */ S.q = Dcs_amd.cs_amd(order, A); /* fill-reducing ordering */ if (order > 0 && S.q == null) return (null); if (qr) /* QR symbolic analysis */ { Dcs C = order > 0 ? Dcs_permute.cs_permute(A, null, S.q, false) : A; S.parent = Dcs_etree.cs_etree(C, true); /* etree of C'*C, where C=A(:,q) */ post = Dcs_post.cs_post(S.parent, n); S.cp = Dcs_counts.cs_counts(C, S.parent, post, true); /* col counts chol(C'*C) */ ok = C != null && S.parent != null && S.cp != null && cs_vcount(C, S); if (ok) for (S.unz = 0, k = 0; k < n; k++) S.unz += S.cp[k]; ok = ok && S.lnz >= 0 && S.unz >= 0; /* int overflow guard */ } else { S.unz = 4 * (A.p[n]) + n; /* for LU factorization only, */ S.lnz = S.unz; /* guess nnz(L) and nnz(U) */ } return (ok ? S : null); /* return result S */ }
java
public static Dcss cs_sqr(int order, Dcs A, boolean qr) { int n, k, post[]; Dcss S; boolean ok = true; if (!Dcs_util.CS_CSC(A)) return (null); /* check inputs */ n = A.n; S = new Dcss(); /* allocate result S */ S.q = Dcs_amd.cs_amd(order, A); /* fill-reducing ordering */ if (order > 0 && S.q == null) return (null); if (qr) /* QR symbolic analysis */ { Dcs C = order > 0 ? Dcs_permute.cs_permute(A, null, S.q, false) : A; S.parent = Dcs_etree.cs_etree(C, true); /* etree of C'*C, where C=A(:,q) */ post = Dcs_post.cs_post(S.parent, n); S.cp = Dcs_counts.cs_counts(C, S.parent, post, true); /* col counts chol(C'*C) */ ok = C != null && S.parent != null && S.cp != null && cs_vcount(C, S); if (ok) for (S.unz = 0, k = 0; k < n; k++) S.unz += S.cp[k]; ok = ok && S.lnz >= 0 && S.unz >= 0; /* int overflow guard */ } else { S.unz = 4 * (A.p[n]) + n; /* for LU factorization only, */ S.lnz = S.unz; /* guess nnz(L) and nnz(U) */ } return (ok ? S : null); /* return result S */ }
[ "public", "static", "Dcss", "cs_sqr", "(", "int", "order", ",", "Dcs", "A", ",", "boolean", "qr", ")", "{", "int", "n", ",", "k", ",", "post", "[", "]", ";", "Dcss", "S", ";", "boolean", "ok", "=", "true", ";", "if", "(", "!", "Dcs_util", ".", "CS_CSC", "(", "A", ")", ")", "return", "(", "null", ")", ";", "/* check inputs */", "n", "=", "A", ".", "n", ";", "S", "=", "new", "Dcss", "(", ")", ";", "/* allocate result S */", "S", ".", "q", "=", "Dcs_amd", ".", "cs_amd", "(", "order", ",", "A", ")", ";", "/* fill-reducing ordering */", "if", "(", "order", ">", "0", "&&", "S", ".", "q", "==", "null", ")", "return", "(", "null", ")", ";", "if", "(", "qr", ")", "/* QR symbolic analysis */", "{", "Dcs", "C", "=", "order", ">", "0", "?", "Dcs_permute", ".", "cs_permute", "(", "A", ",", "null", ",", "S", ".", "q", ",", "false", ")", ":", "A", ";", "S", ".", "parent", "=", "Dcs_etree", ".", "cs_etree", "(", "C", ",", "true", ")", ";", "/* etree of C'*C, where C=A(:,q) */", "post", "=", "Dcs_post", ".", "cs_post", "(", "S", ".", "parent", ",", "n", ")", ";", "S", ".", "cp", "=", "Dcs_counts", ".", "cs_counts", "(", "C", ",", "S", ".", "parent", ",", "post", ",", "true", ")", ";", "/* col counts chol(C'*C) */", "ok", "=", "C", "!=", "null", "&&", "S", ".", "parent", "!=", "null", "&&", "S", ".", "cp", "!=", "null", "&&", "cs_vcount", "(", "C", ",", "S", ")", ";", "if", "(", "ok", ")", "for", "(", "S", ".", "unz", "=", "0", ",", "k", "=", "0", ";", "k", "<", "n", ";", "k", "++", ")", "S", ".", "unz", "+=", "S", ".", "cp", "[", "k", "]", ";", "ok", "=", "ok", "&&", "S", ".", "lnz", ">=", "0", "&&", "S", ".", "unz", ">=", "0", ";", "/* int overflow guard */", "}", "else", "{", "S", ".", "unz", "=", "4", "*", "(", "A", ".", "p", "[", "n", "]", ")", "+", "n", ";", "/* for LU factorization only, */", "S", ".", "lnz", "=", "S", ".", "unz", ";", "/* guess nnz(L) and nnz(U) */", "}", "return", "(", "ok", "?", "S", ":", "null", ")", ";", "/* return result S */", "}" ]
Symbolic QR or LU ordering and analysis. @param order ordering method to use (0 to 3) @param A column-compressed matrix @param qr analyze for QR if true or LU if false @return symbolic analysis for QR or LU, null on error
[ "Symbolic", "QR", "or", "LU", "ordering", "and", "analysis", "." ]
train
https://github.com/rwl/CSparseJ/blob/6a6f66bccce1558156a961494358952603b0ac84/src/main/java/edu/emory/mathcs/csparsej/tdouble/Dcs_sqr.java#L113-L140
eurekaclinical/javautil
src/main/java/org/arp/javautil/stat/UpdatingCovarCalc.java
UpdatingCovarCalc.addPoint
public void addPoint(double x, double y) { """ Update the covariance with another point. @param x x value @param y y value """ numItems++; double xMinusMeanX = x - meanx; double yMinusMeanY = y - meany; sumsq += xMinusMeanX * yMinusMeanY * (numItems - 1) / numItems; meanx += xMinusMeanX / numItems; meany += yMinusMeanY / numItems; }
java
public void addPoint(double x, double y) { numItems++; double xMinusMeanX = x - meanx; double yMinusMeanY = y - meany; sumsq += xMinusMeanX * yMinusMeanY * (numItems - 1) / numItems; meanx += xMinusMeanX / numItems; meany += yMinusMeanY / numItems; }
[ "public", "void", "addPoint", "(", "double", "x", ",", "double", "y", ")", "{", "numItems", "++", ";", "double", "xMinusMeanX", "=", "x", "-", "meanx", ";", "double", "yMinusMeanY", "=", "y", "-", "meany", ";", "sumsq", "+=", "xMinusMeanX", "*", "yMinusMeanY", "*", "(", "numItems", "-", "1", ")", "/", "numItems", ";", "meanx", "+=", "xMinusMeanX", "/", "numItems", ";", "meany", "+=", "yMinusMeanY", "/", "numItems", ";", "}" ]
Update the covariance with another point. @param x x value @param y y value
[ "Update", "the", "covariance", "with", "another", "point", "." ]
train
https://github.com/eurekaclinical/javautil/blob/779bbc5bf096c75f8eed4f99ca45b99c1d44df43/src/main/java/org/arp/javautil/stat/UpdatingCovarCalc.java#L59-L66
gocardless/gocardless-pro-java
src/main/java/com/gocardless/Webhook.java
Webhook.isValidSignature
public static boolean isValidSignature(String requestBody, String signatureHeader, String webhookEndpointSecret) { """ Validates that a webhook was genuinely sent by GoCardless by computing its signature using the body and your webhook endpoint secret, and comparing that with the signature included in the `Webhook-Signature` header. @param requestBody the request body @param signatureHeader the signature included in the request, found in the `Webhook-Signature` header @param webhookEndpointSecret the webhook endpoint secret for your webhook endpoint, as configured in your GoCardless Dashboard @return whether the webhook's signature is valid """ String computedSignature = new HmacUtils(HmacAlgorithms.HMAC_SHA_256, webhookEndpointSecret) .hmacHex(requestBody); return MessageDigest.isEqual(signatureHeader.getBytes(), computedSignature.getBytes()); }
java
public static boolean isValidSignature(String requestBody, String signatureHeader, String webhookEndpointSecret) { String computedSignature = new HmacUtils(HmacAlgorithms.HMAC_SHA_256, webhookEndpointSecret) .hmacHex(requestBody); return MessageDigest.isEqual(signatureHeader.getBytes(), computedSignature.getBytes()); }
[ "public", "static", "boolean", "isValidSignature", "(", "String", "requestBody", ",", "String", "signatureHeader", ",", "String", "webhookEndpointSecret", ")", "{", "String", "computedSignature", "=", "new", "HmacUtils", "(", "HmacAlgorithms", ".", "HMAC_SHA_256", ",", "webhookEndpointSecret", ")", ".", "hmacHex", "(", "requestBody", ")", ";", "return", "MessageDigest", ".", "isEqual", "(", "signatureHeader", ".", "getBytes", "(", ")", ",", "computedSignature", ".", "getBytes", "(", ")", ")", ";", "}" ]
Validates that a webhook was genuinely sent by GoCardless by computing its signature using the body and your webhook endpoint secret, and comparing that with the signature included in the `Webhook-Signature` header. @param requestBody the request body @param signatureHeader the signature included in the request, found in the `Webhook-Signature` header @param webhookEndpointSecret the webhook endpoint secret for your webhook endpoint, as configured in your GoCardless Dashboard @return whether the webhook's signature is valid
[ "Validates", "that", "a", "webhook", "was", "genuinely", "sent", "by", "GoCardless", "by", "computing", "its", "signature", "using", "the", "body", "and", "your", "webhook", "endpoint", "secret", "and", "comparing", "that", "with", "the", "signature", "included", "in", "the", "Webhook", "-", "Signature", "header", "." ]
train
https://github.com/gocardless/gocardless-pro-java/blob/e121320c9bdfdfc7ca0996b431e5a45c91d0c1c1/src/main/java/com/gocardless/Webhook.java#L55-L61
aspectran/aspectran
core/src/main/java/com/aspectran/core/component/bean/proxy/CglibDynamicBeanProxy.java
CglibDynamicBeanProxy.newInstance
public static Object newInstance(ActivityContext context, BeanRule beanRule, Object[] args, Class<?>[] argTypes) { """ Creates a proxy class of bean and returns an instance of that class. @param context the activity context @param beanRule the bean rule @param args the arguments passed to a constructor @param argTypes the parameter types for a constructor @return a new proxy bean object """ Enhancer enhancer = new Enhancer(); enhancer.setClassLoader(context.getEnvironment().getClassLoader()); enhancer.setSuperclass(beanRule.getBeanClass()); enhancer.setCallback(new CglibDynamicBeanProxy(context, beanRule)); return enhancer.create(argTypes, args); }
java
public static Object newInstance(ActivityContext context, BeanRule beanRule, Object[] args, Class<?>[] argTypes) { Enhancer enhancer = new Enhancer(); enhancer.setClassLoader(context.getEnvironment().getClassLoader()); enhancer.setSuperclass(beanRule.getBeanClass()); enhancer.setCallback(new CglibDynamicBeanProxy(context, beanRule)); return enhancer.create(argTypes, args); }
[ "public", "static", "Object", "newInstance", "(", "ActivityContext", "context", ",", "BeanRule", "beanRule", ",", "Object", "[", "]", "args", ",", "Class", "<", "?", ">", "[", "]", "argTypes", ")", "{", "Enhancer", "enhancer", "=", "new", "Enhancer", "(", ")", ";", "enhancer", ".", "setClassLoader", "(", "context", ".", "getEnvironment", "(", ")", ".", "getClassLoader", "(", ")", ")", ";", "enhancer", ".", "setSuperclass", "(", "beanRule", ".", "getBeanClass", "(", ")", ")", ";", "enhancer", ".", "setCallback", "(", "new", "CglibDynamicBeanProxy", "(", "context", ",", "beanRule", ")", ")", ";", "return", "enhancer", ".", "create", "(", "argTypes", ",", "args", ")", ";", "}" ]
Creates a proxy class of bean and returns an instance of that class. @param context the activity context @param beanRule the bean rule @param args the arguments passed to a constructor @param argTypes the parameter types for a constructor @return a new proxy bean object
[ "Creates", "a", "proxy", "class", "of", "bean", "and", "returns", "an", "instance", "of", "that", "class", "." ]
train
https://github.com/aspectran/aspectran/blob/2d758a2a28b71ee85b42823c12dc44674d7f2c70/core/src/main/java/com/aspectran/core/component/bean/proxy/CglibDynamicBeanProxy.java#L125-L131
phax/ph-commons
ph-json/src/main/java/com/helger/json/serialize/JsonReader.java
JsonReader.readFromStream
@Nullable public static IJson readFromStream (@Nonnull final InputStream aIS, @Nonnull final Charset aFallbackCharset) { """ Read the Json from the passed {@link InputStream}. @param aIS The input stream to use. May not be <code>null</code>. @param aFallbackCharset The charset to be used if no BOM is present. May not be <code>null</code>. @return <code>null</code> if reading failed, the Json declarations otherwise. """ return readFromStream (aIS, aFallbackCharset, null); }
java
@Nullable public static IJson readFromStream (@Nonnull final InputStream aIS, @Nonnull final Charset aFallbackCharset) { return readFromStream (aIS, aFallbackCharset, null); }
[ "@", "Nullable", "public", "static", "IJson", "readFromStream", "(", "@", "Nonnull", "final", "InputStream", "aIS", ",", "@", "Nonnull", "final", "Charset", "aFallbackCharset", ")", "{", "return", "readFromStream", "(", "aIS", ",", "aFallbackCharset", ",", "null", ")", ";", "}" ]
Read the Json from the passed {@link InputStream}. @param aIS The input stream to use. May not be <code>null</code>. @param aFallbackCharset The charset to be used if no BOM is present. May not be <code>null</code>. @return <code>null</code> if reading failed, the Json declarations otherwise.
[ "Read", "the", "Json", "from", "the", "passed", "{", "@link", "InputStream", "}", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-json/src/main/java/com/helger/json/serialize/JsonReader.java#L656-L660
CenturyLinkCloud/mdw
mdw-services/src/com/centurylink/mdw/services/cache/CacheRegistration.java
CacheRegistration.refreshCache
public void refreshCache(String cacheName, List<String> excludedFormats) { """ Refreshes a particular cache by name. @param cacheName the cache to refresh """ CacheService cache = allCaches.get(cacheName); if (cache != null) { if (excludedFormats != null && cache instanceof ExcludableCache && excludedFormats.contains(((ExcludableCache)cache).getFormat())) { logger.debug(" - omitting cache " + cacheName); } else { logger.info(" - refresh cache " + cacheName); try { cache.refreshCache(); } catch (Exception e) { logger.severeException("failed to refresh cache", e); } } } }
java
public void refreshCache(String cacheName, List<String> excludedFormats) { CacheService cache = allCaches.get(cacheName); if (cache != null) { if (excludedFormats != null && cache instanceof ExcludableCache && excludedFormats.contains(((ExcludableCache)cache).getFormat())) { logger.debug(" - omitting cache " + cacheName); } else { logger.info(" - refresh cache " + cacheName); try { cache.refreshCache(); } catch (Exception e) { logger.severeException("failed to refresh cache", e); } } } }
[ "public", "void", "refreshCache", "(", "String", "cacheName", ",", "List", "<", "String", ">", "excludedFormats", ")", "{", "CacheService", "cache", "=", "allCaches", ".", "get", "(", "cacheName", ")", ";", "if", "(", "cache", "!=", "null", ")", "{", "if", "(", "excludedFormats", "!=", "null", "&&", "cache", "instanceof", "ExcludableCache", "&&", "excludedFormats", ".", "contains", "(", "(", "(", "ExcludableCache", ")", "cache", ")", ".", "getFormat", "(", ")", ")", ")", "{", "logger", ".", "debug", "(", "\" - omitting cache \"", "+", "cacheName", ")", ";", "}", "else", "{", "logger", ".", "info", "(", "\" - refresh cache \"", "+", "cacheName", ")", ";", "try", "{", "cache", ".", "refreshCache", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "logger", ".", "severeException", "(", "\"failed to refresh cache\"", ",", "e", ")", ";", "}", "}", "}", "}" ]
Refreshes a particular cache by name. @param cacheName the cache to refresh
[ "Refreshes", "a", "particular", "cache", "by", "name", "." ]
train
https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-services/src/com/centurylink/mdw/services/cache/CacheRegistration.java#L239-L254
Azure/azure-sdk-for-java
keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java
KeyVaultClientBaseImpl.setSasDefinitionAsync
public ServiceFuture<SasDefinitionBundle> setSasDefinitionAsync(String vaultBaseUrl, String storageAccountName, String sasDefinitionName, String templateUri, SasTokenType sasType, String validityPeriod, SasDefinitionAttributes sasDefinitionAttributes, Map<String, String> tags, final ServiceCallback<SasDefinitionBundle> serviceCallback) { """ Creates or updates a new SAS definition for the specified storage account. This operation requires the storage/setsas permission. @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. @param storageAccountName The name of the storage account. @param sasDefinitionName The name of the SAS definition. @param templateUri The SAS definition token template signed with an arbitrary key. Tokens created according to the SAS definition will have the same properties as the template. @param sasType The type of SAS token the SAS definition will create. Possible values include: 'account', 'service' @param validityPeriod The validity period of SAS tokens created according to the SAS definition. @param sasDefinitionAttributes The attributes of the SAS definition. @param tags Application specific metadata in the form of key-value pairs. @param serviceCallback the async ServiceCallback to handle successful and failed responses. @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceFuture} object """ return ServiceFuture.fromResponse(setSasDefinitionWithServiceResponseAsync(vaultBaseUrl, storageAccountName, sasDefinitionName, templateUri, sasType, validityPeriod, sasDefinitionAttributes, tags), serviceCallback); }
java
public ServiceFuture<SasDefinitionBundle> setSasDefinitionAsync(String vaultBaseUrl, String storageAccountName, String sasDefinitionName, String templateUri, SasTokenType sasType, String validityPeriod, SasDefinitionAttributes sasDefinitionAttributes, Map<String, String> tags, final ServiceCallback<SasDefinitionBundle> serviceCallback) { return ServiceFuture.fromResponse(setSasDefinitionWithServiceResponseAsync(vaultBaseUrl, storageAccountName, sasDefinitionName, templateUri, sasType, validityPeriod, sasDefinitionAttributes, tags), serviceCallback); }
[ "public", "ServiceFuture", "<", "SasDefinitionBundle", ">", "setSasDefinitionAsync", "(", "String", "vaultBaseUrl", ",", "String", "storageAccountName", ",", "String", "sasDefinitionName", ",", "String", "templateUri", ",", "SasTokenType", "sasType", ",", "String", "validityPeriod", ",", "SasDefinitionAttributes", "sasDefinitionAttributes", ",", "Map", "<", "String", ",", "String", ">", "tags", ",", "final", "ServiceCallback", "<", "SasDefinitionBundle", ">", "serviceCallback", ")", "{", "return", "ServiceFuture", ".", "fromResponse", "(", "setSasDefinitionWithServiceResponseAsync", "(", "vaultBaseUrl", ",", "storageAccountName", ",", "sasDefinitionName", ",", "templateUri", ",", "sasType", ",", "validityPeriod", ",", "sasDefinitionAttributes", ",", "tags", ")", ",", "serviceCallback", ")", ";", "}" ]
Creates or updates a new SAS definition for the specified storage account. This operation requires the storage/setsas permission. @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. @param storageAccountName The name of the storage account. @param sasDefinitionName The name of the SAS definition. @param templateUri The SAS definition token template signed with an arbitrary key. Tokens created according to the SAS definition will have the same properties as the template. @param sasType The type of SAS token the SAS definition will create. Possible values include: 'account', 'service' @param validityPeriod The validity period of SAS tokens created according to the SAS definition. @param sasDefinitionAttributes The attributes of the SAS definition. @param tags Application specific metadata in the form of key-value pairs. @param serviceCallback the async ServiceCallback to handle successful and failed responses. @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceFuture} object
[ "Creates", "or", "updates", "a", "new", "SAS", "definition", "for", "the", "specified", "storage", "account", ".", "This", "operation", "requires", "the", "storage", "/", "setsas", "permission", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java#L11388-L11390
jbundle/jbundle
base/screen/model/src/main/java/org/jbundle/base/screen/model/BasePanel.java
BasePanel.addURLParam
public String addURLParam(String strOldURL, String strParam, String strData) { """ Get the command string that will restore this screen. Override in Screen, GridScreen, MenuScreen. @param strOldURL The URL to add this param to. @param strParam The new param. @param strData The new data for this param. @return The new URL. @see Utility.addURLParam. """ return Utility.addURLParam(strOldURL, strParam, strData); }
java
public String addURLParam(String strOldURL, String strParam, String strData) { return Utility.addURLParam(strOldURL, strParam, strData); }
[ "public", "String", "addURLParam", "(", "String", "strOldURL", ",", "String", "strParam", ",", "String", "strData", ")", "{", "return", "Utility", ".", "addURLParam", "(", "strOldURL", ",", "strParam", ",", "strData", ")", ";", "}" ]
Get the command string that will restore this screen. Override in Screen, GridScreen, MenuScreen. @param strOldURL The URL to add this param to. @param strParam The new param. @param strData The new data for this param. @return The new URL. @see Utility.addURLParam.
[ "Get", "the", "command", "string", "that", "will", "restore", "this", "screen", ".", "Override", "in", "Screen", "GridScreen", "MenuScreen", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/screen/model/src/main/java/org/jbundle/base/screen/model/BasePanel.java#L960-L963
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/rest/RESTServlet.java
RESTServlet.getApplication
private ApplicationDefinition getApplication(String uri, Tenant tenant) { """ Get the definition of the referenced application or null if there is none. """ if (uri.length() < 2 || uri.startsWith("/_")) { return null; // Non-application request } String[] pathNodes = uri.substring(1).split("/"); String appName = Utils.urlDecode(pathNodes[0]); ApplicationDefinition appDef = SchemaService.instance().getApplication(tenant, appName); if (appDef == null) { throw new NotFoundException("Unknown application: " + appName); } return appDef; }
java
private ApplicationDefinition getApplication(String uri, Tenant tenant) { if (uri.length() < 2 || uri.startsWith("/_")) { return null; // Non-application request } String[] pathNodes = uri.substring(1).split("/"); String appName = Utils.urlDecode(pathNodes[0]); ApplicationDefinition appDef = SchemaService.instance().getApplication(tenant, appName); if (appDef == null) { throw new NotFoundException("Unknown application: " + appName); } return appDef; }
[ "private", "ApplicationDefinition", "getApplication", "(", "String", "uri", ",", "Tenant", "tenant", ")", "{", "if", "(", "uri", ".", "length", "(", ")", "<", "2", "||", "uri", ".", "startsWith", "(", "\"/_\"", ")", ")", "{", "return", "null", ";", "// Non-application request\r", "}", "String", "[", "]", "pathNodes", "=", "uri", ".", "substring", "(", "1", ")", ".", "split", "(", "\"/\"", ")", ";", "String", "appName", "=", "Utils", ".", "urlDecode", "(", "pathNodes", "[", "0", "]", ")", ";", "ApplicationDefinition", "appDef", "=", "SchemaService", ".", "instance", "(", ")", ".", "getApplication", "(", "tenant", ",", "appName", ")", ";", "if", "(", "appDef", "==", "null", ")", "{", "throw", "new", "NotFoundException", "(", "\"Unknown application: \"", "+", "appName", ")", ";", "}", "return", "appDef", ";", "}" ]
Get the definition of the referenced application or null if there is none.
[ "Get", "the", "definition", "of", "the", "referenced", "application", "or", "null", "if", "there", "is", "none", "." ]
train
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/rest/RESTServlet.java#L200-L211
GoogleCloudPlatform/bigdata-interop
bigquery/src/main/java/com/google/cloud/hadoop/io/bigquery/output/ForwardingBigQueryFileOutputFormat.java
ForwardingBigQueryFileOutputFormat.checkOutputSpecs
@Override public void checkOutputSpecs(JobContext job) throws FileAlreadyExistsException, IOException { """ Checks to make sure the configuration is valid, the output path doesn't already exist, and that a connection to BigQuery can be established. """ Configuration conf = job.getConfiguration(); // Validate the output configuration. BigQueryOutputConfiguration.validateConfiguration(conf); // Get the output path. Path outputPath = BigQueryOutputConfiguration.getGcsOutputPath(conf); logger.atInfo().log("Using output path '%s'.", outputPath); // Error if the output path already exists. FileSystem outputFileSystem = outputPath.getFileSystem(conf); if (outputFileSystem.exists(outputPath)) { throw new IOException("The output path '" + outputPath + "' already exists."); } // Error if compression is set as there's mixed support in BigQuery. if (FileOutputFormat.getCompressOutput(job)) { throw new IOException("Compression isn't supported for this OutputFormat."); } // Error if unable to create a BigQuery helper. try { new BigQueryFactory().getBigQueryHelper(conf); } catch (GeneralSecurityException gse) { throw new IOException("Failed to create BigQuery client", gse); } // Let delegate process its checks. getDelegate(conf).checkOutputSpecs(job); }
java
@Override public void checkOutputSpecs(JobContext job) throws FileAlreadyExistsException, IOException { Configuration conf = job.getConfiguration(); // Validate the output configuration. BigQueryOutputConfiguration.validateConfiguration(conf); // Get the output path. Path outputPath = BigQueryOutputConfiguration.getGcsOutputPath(conf); logger.atInfo().log("Using output path '%s'.", outputPath); // Error if the output path already exists. FileSystem outputFileSystem = outputPath.getFileSystem(conf); if (outputFileSystem.exists(outputPath)) { throw new IOException("The output path '" + outputPath + "' already exists."); } // Error if compression is set as there's mixed support in BigQuery. if (FileOutputFormat.getCompressOutput(job)) { throw new IOException("Compression isn't supported for this OutputFormat."); } // Error if unable to create a BigQuery helper. try { new BigQueryFactory().getBigQueryHelper(conf); } catch (GeneralSecurityException gse) { throw new IOException("Failed to create BigQuery client", gse); } // Let delegate process its checks. getDelegate(conf).checkOutputSpecs(job); }
[ "@", "Override", "public", "void", "checkOutputSpecs", "(", "JobContext", "job", ")", "throws", "FileAlreadyExistsException", ",", "IOException", "{", "Configuration", "conf", "=", "job", ".", "getConfiguration", "(", ")", ";", "// Validate the output configuration.", "BigQueryOutputConfiguration", ".", "validateConfiguration", "(", "conf", ")", ";", "// Get the output path.", "Path", "outputPath", "=", "BigQueryOutputConfiguration", ".", "getGcsOutputPath", "(", "conf", ")", ";", "logger", ".", "atInfo", "(", ")", ".", "log", "(", "\"Using output path '%s'.\"", ",", "outputPath", ")", ";", "// Error if the output path already exists.", "FileSystem", "outputFileSystem", "=", "outputPath", ".", "getFileSystem", "(", "conf", ")", ";", "if", "(", "outputFileSystem", ".", "exists", "(", "outputPath", ")", ")", "{", "throw", "new", "IOException", "(", "\"The output path '\"", "+", "outputPath", "+", "\"' already exists.\"", ")", ";", "}", "// Error if compression is set as there's mixed support in BigQuery.", "if", "(", "FileOutputFormat", ".", "getCompressOutput", "(", "job", ")", ")", "{", "throw", "new", "IOException", "(", "\"Compression isn't supported for this OutputFormat.\"", ")", ";", "}", "// Error if unable to create a BigQuery helper.", "try", "{", "new", "BigQueryFactory", "(", ")", ".", "getBigQueryHelper", "(", "conf", ")", ";", "}", "catch", "(", "GeneralSecurityException", "gse", ")", "{", "throw", "new", "IOException", "(", "\"Failed to create BigQuery client\"", ",", "gse", ")", ";", "}", "// Let delegate process its checks.", "getDelegate", "(", "conf", ")", ".", "checkOutputSpecs", "(", "job", ")", ";", "}" ]
Checks to make sure the configuration is valid, the output path doesn't already exist, and that a connection to BigQuery can be established.
[ "Checks", "to", "make", "sure", "the", "configuration", "is", "valid", "the", "output", "path", "doesn", "t", "already", "exist", "and", "that", "a", "connection", "to", "BigQuery", "can", "be", "established", "." ]
train
https://github.com/GoogleCloudPlatform/bigdata-interop/blob/918d91c80a63e36046edb28972a5c65d3326a858/bigquery/src/main/java/com/google/cloud/hadoop/io/bigquery/output/ForwardingBigQueryFileOutputFormat.java#L58-L89
OpenNTF/JavascriptAggregator
jaggr-core/src/main/java/com/ibm/jaggr/core/impl/transport/DojoHttpTransport.java
DojoHttpTransport.beginModules
protected String beginModules(HttpServletRequest request, Object arg) { """ Handles the {@link com.ibm.jaggr.core.transport.IHttpTransport.LayerContributionType#BEGIN_MODULES} layer listener event. <p> When doing server expanded layers, the loader extension JavaScript needs to be in control of determining when explicitly requested modules are defined so that it can ensure the modules are defined in request order. This prevents the loader from issuing unnecessary, additional, requests for unresolved modules when responses arrive out-of-order. <p> The markup emitted by this method, together with the {@link #endModules(HttpServletRequest, Object)} method, wraps the module definitions within the <code>require.combo.defineModules</code> function call as follows: <pre> require.combo.defineModules(['mid1', 'mid2', ...], function() { define([...], function(...) { ... }); define([...], function(...) { ... }); ... }); </pre> @param request the http request object @param arg the set of module names. The iteration order of the set is guaranteed to be the same as the order of the subsequent {@link com.ibm.jaggr.core.transport.IHttpTransport.LayerContributionType#BEFORE_FIRST_MODULE}, {@link com.ibm.jaggr.core.transport.IHttpTransport.LayerContributionType#BEFORE_SUBSEQUENT_MODULE}, and {@link com.ibm.jaggr.core.transport.IHttpTransport.LayerContributionType#AFTER_MODULE} events. @return the layer contribution """ StringBuffer sb = new StringBuffer(); if (RequestUtil.isServerExpandedLayers(request) && request.getParameter(REQUESTEDMODULESCOUNT_REQPARAM) != null) { // it's a loader generated request @SuppressWarnings("unchecked") Set<String> modules = (Set<String>)arg; sb.append("require.combo.defineModules(["); //$NON-NLS-1$ int i = 0; for (String module : modules) { sb.append(i++ > 0 ? "," : "").append("'").append(module).append("'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } sb.append("], function(){\r\n"); //$NON-NLS-1$ } return sb.toString(); }
java
protected String beginModules(HttpServletRequest request, Object arg) { StringBuffer sb = new StringBuffer(); if (RequestUtil.isServerExpandedLayers(request) && request.getParameter(REQUESTEDMODULESCOUNT_REQPARAM) != null) { // it's a loader generated request @SuppressWarnings("unchecked") Set<String> modules = (Set<String>)arg; sb.append("require.combo.defineModules(["); //$NON-NLS-1$ int i = 0; for (String module : modules) { sb.append(i++ > 0 ? "," : "").append("'").append(module).append("'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } sb.append("], function(){\r\n"); //$NON-NLS-1$ } return sb.toString(); }
[ "protected", "String", "beginModules", "(", "HttpServletRequest", "request", ",", "Object", "arg", ")", "{", "StringBuffer", "sb", "=", "new", "StringBuffer", "(", ")", ";", "if", "(", "RequestUtil", ".", "isServerExpandedLayers", "(", "request", ")", "&&", "request", ".", "getParameter", "(", "REQUESTEDMODULESCOUNT_REQPARAM", ")", "!=", "null", ")", "{", "// it's a loader generated request\r", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "Set", "<", "String", ">", "modules", "=", "(", "Set", "<", "String", ">", ")", "arg", ";", "sb", ".", "append", "(", "\"require.combo.defineModules([\"", ")", ";", "//$NON-NLS-1$\r", "int", "i", "=", "0", ";", "for", "(", "String", "module", ":", "modules", ")", "{", "sb", ".", "append", "(", "i", "++", ">", "0", "?", "\",\"", ":", "\"\"", ")", ".", "append", "(", "\"'\"", ")", ".", "append", "(", "module", ")", ".", "append", "(", "\"'\"", ")", ";", "//$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$\r", "}", "sb", ".", "append", "(", "\"], function(){\\r\\n\"", ")", ";", "//$NON-NLS-1$\r", "}", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
Handles the {@link com.ibm.jaggr.core.transport.IHttpTransport.LayerContributionType#BEGIN_MODULES} layer listener event. <p> When doing server expanded layers, the loader extension JavaScript needs to be in control of determining when explicitly requested modules are defined so that it can ensure the modules are defined in request order. This prevents the loader from issuing unnecessary, additional, requests for unresolved modules when responses arrive out-of-order. <p> The markup emitted by this method, together with the {@link #endModules(HttpServletRequest, Object)} method, wraps the module definitions within the <code>require.combo.defineModules</code> function call as follows: <pre> require.combo.defineModules(['mid1', 'mid2', ...], function() { define([...], function(...) { ... }); define([...], function(...) { ... }); ... }); </pre> @param request the http request object @param arg the set of module names. The iteration order of the set is guaranteed to be the same as the order of the subsequent {@link com.ibm.jaggr.core.transport.IHttpTransport.LayerContributionType#BEFORE_FIRST_MODULE}, {@link com.ibm.jaggr.core.transport.IHttpTransport.LayerContributionType#BEFORE_SUBSEQUENT_MODULE}, and {@link com.ibm.jaggr.core.transport.IHttpTransport.LayerContributionType#AFTER_MODULE} events. @return the layer contribution
[ "Handles", "the", "{", "@link", "com", ".", "ibm", ".", "jaggr", ".", "core", ".", "transport", ".", "IHttpTransport", ".", "LayerContributionType#BEGIN_MODULES", "}", "layer", "listener", "event", ".", "<p", ">", "When", "doing", "server", "expanded", "layers", "the", "loader", "extension", "JavaScript", "needs", "to", "be", "in", "control", "of", "determining", "when", "explicitly", "requested", "modules", "are", "defined", "so", "that", "it", "can", "ensure", "the", "modules", "are", "defined", "in", "request", "order", ".", "This", "prevents", "the", "loader", "from", "issuing", "unnecessary", "additional", "requests", "for", "unresolved", "modules", "when", "responses", "arrive", "out", "-", "of", "-", "order", ".", "<p", ">", "The", "markup", "emitted", "by", "this", "method", "together", "with", "the", "{", "@link", "#endModules", "(", "HttpServletRequest", "Object", ")", "}", "method", "wraps", "the", "module", "definitions", "within", "the", "<code", ">", "require", ".", "combo", ".", "defineModules<", "/", "code", ">", "function", "call", "as", "follows", ":", "<pre", ">", "require", ".", "combo", ".", "defineModules", "(", "[", "mid1", "mid2", "...", "]", "function", "()", "{", "define", "(", "[", "...", "]", "function", "(", "...", ")", "{", "...", "}", ")", ";", "define", "(", "[", "...", "]", "function", "(", "...", ")", "{", "...", "}", ")", ";", "...", "}", ")", ";", "<", "/", "pre", ">" ]
train
https://github.com/OpenNTF/JavascriptAggregator/blob/9f47a96d778251638b1df9a368462176216d5b29/jaggr-core/src/main/java/com/ibm/jaggr/core/impl/transport/DojoHttpTransport.java#L355-L369
albfernandez/itext2
src/main/java/com/lowagie/text/pdf/PdfContentByte.java
PdfContentByte.beginMarkedContentSequence
public void beginMarkedContentSequence(PdfName tag, PdfDictionary property, boolean inline) { """ Begins a marked content sequence. If property is <CODE>null</CODE> the mark will be of the type <CODE>BMC</CODE> otherwise it will be <CODE>BDC</CODE>. @param tag the tag @param property the property @param inline <CODE>true</CODE> to include the property in the content or <CODE>false</CODE> to include the property in the resource dictionary with the possibility of reusing """ if (property == null) { content.append(tag.getBytes()).append(" BMC").append_i(separator); return; } content.append(tag.getBytes()).append(' '); if (inline) try { property.toPdf(writer, content); } catch (Exception e) { throw new ExceptionConverter(e); } else { PdfObject[] objs; if (writer.propertyExists(property)) objs = writer.addSimpleProperty(property, null); else objs = writer.addSimpleProperty(property, writer.getPdfIndirectReference()); PdfName name = (PdfName)objs[0]; PageResources prs = getPageResources(); name = prs.addProperty(name, (PdfIndirectReference)objs[1]); content.append(name.getBytes()); } content.append(" BDC").append_i(separator); ++mcDepth; }
java
public void beginMarkedContentSequence(PdfName tag, PdfDictionary property, boolean inline) { if (property == null) { content.append(tag.getBytes()).append(" BMC").append_i(separator); return; } content.append(tag.getBytes()).append(' '); if (inline) try { property.toPdf(writer, content); } catch (Exception e) { throw new ExceptionConverter(e); } else { PdfObject[] objs; if (writer.propertyExists(property)) objs = writer.addSimpleProperty(property, null); else objs = writer.addSimpleProperty(property, writer.getPdfIndirectReference()); PdfName name = (PdfName)objs[0]; PageResources prs = getPageResources(); name = prs.addProperty(name, (PdfIndirectReference)objs[1]); content.append(name.getBytes()); } content.append(" BDC").append_i(separator); ++mcDepth; }
[ "public", "void", "beginMarkedContentSequence", "(", "PdfName", "tag", ",", "PdfDictionary", "property", ",", "boolean", "inline", ")", "{", "if", "(", "property", "==", "null", ")", "{", "content", ".", "append", "(", "tag", ".", "getBytes", "(", ")", ")", ".", "append", "(", "\" BMC\"", ")", ".", "append_i", "(", "separator", ")", ";", "return", ";", "}", "content", ".", "append", "(", "tag", ".", "getBytes", "(", ")", ")", ".", "append", "(", "'", "'", ")", ";", "if", "(", "inline", ")", "try", "{", "property", ".", "toPdf", "(", "writer", ",", "content", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "ExceptionConverter", "(", "e", ")", ";", "}", "else", "{", "PdfObject", "[", "]", "objs", ";", "if", "(", "writer", ".", "propertyExists", "(", "property", ")", ")", "objs", "=", "writer", ".", "addSimpleProperty", "(", "property", ",", "null", ")", ";", "else", "objs", "=", "writer", ".", "addSimpleProperty", "(", "property", ",", "writer", ".", "getPdfIndirectReference", "(", ")", ")", ";", "PdfName", "name", "=", "(", "PdfName", ")", "objs", "[", "0", "]", ";", "PageResources", "prs", "=", "getPageResources", "(", ")", ";", "name", "=", "prs", ".", "addProperty", "(", "name", ",", "(", "PdfIndirectReference", ")", "objs", "[", "1", "]", ")", ";", "content", ".", "append", "(", "name", ".", "getBytes", "(", ")", ")", ";", "}", "content", ".", "append", "(", "\" BDC\"", ")", ".", "append_i", "(", "separator", ")", ";", "++", "mcDepth", ";", "}" ]
Begins a marked content sequence. If property is <CODE>null</CODE> the mark will be of the type <CODE>BMC</CODE> otherwise it will be <CODE>BDC</CODE>. @param tag the tag @param property the property @param inline <CODE>true</CODE> to include the property in the content or <CODE>false</CODE> to include the property in the resource dictionary with the possibility of reusing
[ "Begins", "a", "marked", "content", "sequence", ".", "If", "property", "is", "<CODE", ">", "null<", "/", "CODE", ">", "the", "mark", "will", "be", "of", "the", "type", "<CODE", ">", "BMC<", "/", "CODE", ">", "otherwise", "it", "will", "be", "<CODE", ">", "BDC<", "/", "CODE", ">", "." ]
train
https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/PdfContentByte.java#L3089-L3115
alkacon/opencms-core
src/org/opencms/ade/sitemap/CmsVfsSitemapService.java
CmsVfsSitemapService.shouldChangeDefaultFileTitle
private boolean shouldChangeDefaultFileTitle(Map<String, CmsProperty> properties, CmsProperty folderNavtext) { """ Determines if the title property of the default file should be changed.<p> @param properties the current default file properties @param folderNavtext the 'NavText' property of the folder @return <code>true</code> if the title property should be changed """ return (properties == null) || (properties.get(CmsPropertyDefinition.PROPERTY_TITLE) == null) || (properties.get(CmsPropertyDefinition.PROPERTY_TITLE).getValue() == null) || ((folderNavtext != null) && properties.get(CmsPropertyDefinition.PROPERTY_TITLE).getValue().equals(folderNavtext.getValue())); }
java
private boolean shouldChangeDefaultFileTitle(Map<String, CmsProperty> properties, CmsProperty folderNavtext) { return (properties == null) || (properties.get(CmsPropertyDefinition.PROPERTY_TITLE) == null) || (properties.get(CmsPropertyDefinition.PROPERTY_TITLE).getValue() == null) || ((folderNavtext != null) && properties.get(CmsPropertyDefinition.PROPERTY_TITLE).getValue().equals(folderNavtext.getValue())); }
[ "private", "boolean", "shouldChangeDefaultFileTitle", "(", "Map", "<", "String", ",", "CmsProperty", ">", "properties", ",", "CmsProperty", "folderNavtext", ")", "{", "return", "(", "properties", "==", "null", ")", "||", "(", "properties", ".", "get", "(", "CmsPropertyDefinition", ".", "PROPERTY_TITLE", ")", "==", "null", ")", "||", "(", "properties", ".", "get", "(", "CmsPropertyDefinition", ".", "PROPERTY_TITLE", ")", ".", "getValue", "(", ")", "==", "null", ")", "||", "(", "(", "folderNavtext", "!=", "null", ")", "&&", "properties", ".", "get", "(", "CmsPropertyDefinition", ".", "PROPERTY_TITLE", ")", ".", "getValue", "(", ")", ".", "equals", "(", "folderNavtext", ".", "getValue", "(", ")", ")", ")", ";", "}" ]
Determines if the title property of the default file should be changed.<p> @param properties the current default file properties @param folderNavtext the 'NavText' property of the folder @return <code>true</code> if the title property should be changed
[ "Determines", "if", "the", "title", "property", "of", "the", "default", "file", "should", "be", "changed", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/sitemap/CmsVfsSitemapService.java#L3072-L3079
killbilling/recurly-java-library
src/main/java/com/ning/billing/recurly/RecurlyJs.java
RecurlyJs.generateRecurlyHMAC
private static String generateRecurlyHMAC(String privateJsKey, String protectedParams) { """ HMAC-SHA1 Hash Generator - Helper method <p> Returns a signature key for use with recurly.js BuildSubscriptionForm. @param privateJsKey recurly.js private key @param protectedParams protected parameter string in the format: &lt;secure_hash&gt;|&lt;protected_string&gt; @return subscription object on success, null otherwise """ try { SecretKey sk = new SecretKeySpec(privateJsKey.getBytes(), "HmacSHA1"); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(sk); byte[] result = mac.doFinal(protectedParams.getBytes("UTF-8")); return BaseEncoding.base16().encode(result).toLowerCase(); } catch (Exception e) { log.error("Error while trying to generate Recurly HMAC signature", e); return null; } }
java
private static String generateRecurlyHMAC(String privateJsKey, String protectedParams) { try { SecretKey sk = new SecretKeySpec(privateJsKey.getBytes(), "HmacSHA1"); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(sk); byte[] result = mac.doFinal(protectedParams.getBytes("UTF-8")); return BaseEncoding.base16().encode(result).toLowerCase(); } catch (Exception e) { log.error("Error while trying to generate Recurly HMAC signature", e); return null; } }
[ "private", "static", "String", "generateRecurlyHMAC", "(", "String", "privateJsKey", ",", "String", "protectedParams", ")", "{", "try", "{", "SecretKey", "sk", "=", "new", "SecretKeySpec", "(", "privateJsKey", ".", "getBytes", "(", ")", ",", "\"HmacSHA1\"", ")", ";", "Mac", "mac", "=", "Mac", ".", "getInstance", "(", "\"HmacSHA1\"", ")", ";", "mac", ".", "init", "(", "sk", ")", ";", "byte", "[", "]", "result", "=", "mac", ".", "doFinal", "(", "protectedParams", ".", "getBytes", "(", "\"UTF-8\"", ")", ")", ";", "return", "BaseEncoding", ".", "base16", "(", ")", ".", "encode", "(", "result", ")", ".", "toLowerCase", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "log", ".", "error", "(", "\"Error while trying to generate Recurly HMAC signature\"", ",", "e", ")", ";", "return", "null", ";", "}", "}" ]
HMAC-SHA1 Hash Generator - Helper method <p> Returns a signature key for use with recurly.js BuildSubscriptionForm. @param privateJsKey recurly.js private key @param protectedParams protected parameter string in the format: &lt;secure_hash&gt;|&lt;protected_string&gt; @return subscription object on success, null otherwise
[ "HMAC", "-", "SHA1", "Hash", "Generator", "-", "Helper", "method", "<p", ">", "Returns", "a", "signature", "key", "for", "use", "with", "recurly", ".", "js", "BuildSubscriptionForm", "." ]
train
https://github.com/killbilling/recurly-java-library/blob/5e05eedd91885a51e1aa8293bd41139d082cf7f4/src/main/java/com/ning/billing/recurly/RecurlyJs.java#L102-L113
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/taskmanager/TaskManagerService.java
TaskManagerService.waitForTaskStatus
private TaskRecord waitForTaskStatus(Tenant tenant, Task task, Predicate<TaskStatus> pred) { """ latest status record. If it has never run, a never-run task record is stored. """ TaskRecord taskRecord = null; while (true) { Iterator<DColumn> colIter = DBService.instance(tenant).getAllColumns(TaskManagerService.TASKS_STORE_NAME, task.getTaskID()).iterator(); if (!colIter.hasNext()) { taskRecord = storeTaskRecord(tenant, task); } else { taskRecord = buildTaskRecord(task.getTaskID(), colIter); } if (pred.test(taskRecord.getStatus())) { break; } try { Thread.sleep(TASK_CHECK_MILLIS); } catch (InterruptedException e) { } }; return taskRecord; }
java
private TaskRecord waitForTaskStatus(Tenant tenant, Task task, Predicate<TaskStatus> pred) { TaskRecord taskRecord = null; while (true) { Iterator<DColumn> colIter = DBService.instance(tenant).getAllColumns(TaskManagerService.TASKS_STORE_NAME, task.getTaskID()).iterator(); if (!colIter.hasNext()) { taskRecord = storeTaskRecord(tenant, task); } else { taskRecord = buildTaskRecord(task.getTaskID(), colIter); } if (pred.test(taskRecord.getStatus())) { break; } try { Thread.sleep(TASK_CHECK_MILLIS); } catch (InterruptedException e) { } }; return taskRecord; }
[ "private", "TaskRecord", "waitForTaskStatus", "(", "Tenant", "tenant", ",", "Task", "task", ",", "Predicate", "<", "TaskStatus", ">", "pred", ")", "{", "TaskRecord", "taskRecord", "=", "null", ";", "while", "(", "true", ")", "{", "Iterator", "<", "DColumn", ">", "colIter", "=", "DBService", ".", "instance", "(", "tenant", ")", ".", "getAllColumns", "(", "TaskManagerService", ".", "TASKS_STORE_NAME", ",", "task", ".", "getTaskID", "(", ")", ")", ".", "iterator", "(", ")", ";", "if", "(", "!", "colIter", ".", "hasNext", "(", ")", ")", "{", "taskRecord", "=", "storeTaskRecord", "(", "tenant", ",", "task", ")", ";", "}", "else", "{", "taskRecord", "=", "buildTaskRecord", "(", "task", ".", "getTaskID", "(", ")", ",", "colIter", ")", ";", "}", "if", "(", "pred", ".", "test", "(", "taskRecord", ".", "getStatus", "(", ")", ")", ")", "{", "break", ";", "}", "try", "{", "Thread", ".", "sleep", "(", "TASK_CHECK_MILLIS", ")", ";", "}", "catch", "(", "InterruptedException", "e", ")", "{", "}", "}", ";", "return", "taskRecord", ";", "}" ]
latest status record. If it has never run, a never-run task record is stored.
[ "latest", "status", "record", ".", "If", "it", "has", "never", "run", "a", "never", "-", "run", "task", "record", "is", "stored", "." ]
train
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/taskmanager/TaskManagerService.java#L285-L301
landawn/AbacusUtil
src/com/landawn/abacus/util/Multimap.java
Multimap.replaceIf
public <X extends Exception> boolean replaceIf(Try.Predicate<? super K, X> predicate, Object oldValue, E newValue) throws X { """ Replace the specified value (one occurrence) from the value set associated with keys which satisfy the specified <code>predicate</code>. @param predicate @param oldValue @param newValue @return <code>true</code> if this Multimap is modified by this operation, otherwise <code>false</code>. """ boolean modified = false; for (Map.Entry<K, V> entry : this.valueMap.entrySet()) { if (predicate.test(entry.getKey())) { modified = modified | replace(entry.getValue(), oldValue, newValue); } } return modified; }
java
public <X extends Exception> boolean replaceIf(Try.Predicate<? super K, X> predicate, Object oldValue, E newValue) throws X { boolean modified = false; for (Map.Entry<K, V> entry : this.valueMap.entrySet()) { if (predicate.test(entry.getKey())) { modified = modified | replace(entry.getValue(), oldValue, newValue); } } return modified; }
[ "public", "<", "X", "extends", "Exception", ">", "boolean", "replaceIf", "(", "Try", ".", "Predicate", "<", "?", "super", "K", ",", "X", ">", "predicate", ",", "Object", "oldValue", ",", "E", "newValue", ")", "throws", "X", "{", "boolean", "modified", "=", "false", ";", "for", "(", "Map", ".", "Entry", "<", "K", ",", "V", ">", "entry", ":", "this", ".", "valueMap", ".", "entrySet", "(", ")", ")", "{", "if", "(", "predicate", ".", "test", "(", "entry", ".", "getKey", "(", ")", ")", ")", "{", "modified", "=", "modified", "|", "replace", "(", "entry", ".", "getValue", "(", ")", ",", "oldValue", ",", "newValue", ")", ";", "}", "}", "return", "modified", ";", "}" ]
Replace the specified value (one occurrence) from the value set associated with keys which satisfy the specified <code>predicate</code>. @param predicate @param oldValue @param newValue @return <code>true</code> if this Multimap is modified by this operation, otherwise <code>false</code>.
[ "Replace", "the", "specified", "value", "(", "one", "occurrence", ")", "from", "the", "value", "set", "associated", "with", "keys", "which", "satisfy", "the", "specified", "<code", ">", "predicate<", "/", "code", ">", ".", "@param", "predicate", "@param", "oldValue", "@param", "newValue" ]
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/Multimap.java#L845-L855
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/map/impl/MapKeyLoader.java
MapKeyLoader.sendKeyLoadCompleted
private void sendKeyLoadCompleted(int clusterSize, Throwable exception) throws Exception { """ Notifies the record stores of the {@link MapKeyLoader.Role#SENDER}, {@link MapKeyLoader.Role#SENDER_BACKUP} and all other partition record stores that the key loading has finished and the keys have been dispatched to the partition owners for value loading. @param clusterSize the size of the cluster @param exception the exception that occurred during key loading or {@code null} if there was no exception @throws Exception if there was an exception when notifying the record stores that the key loading has finished @see com.hazelcast.map.impl.recordstore.RecordStore#updateLoadStatus(boolean, Throwable) """ // Notify SENDER first - reason why this is so important: // Someone may do map.get(other_nodes_key) and when it finishes do map.loadAll // The problem is that map.get may finish earlier than then overall loading on the SENDER due to the fact // that the LoadStatusOperation may first reach the node that did map.get and not the SENDER. // The SENDER will be then in the LOADING status, thus the loadAll call will be ignored. // it happens only if all LoadAllOperation finish before the sendKeyLoadCompleted is started (test case, little data) // Fixes https://github.com/hazelcast/hazelcast/issues/5453 List<Future> futures = new ArrayList<>(); Operation senderStatus = new KeyLoadStatusOperation(mapName, exception); Future senderFuture = opService.createInvocationBuilder(SERVICE_NAME, senderStatus, mapNamePartition) .setReplicaIndex(0).invoke(); futures.add(senderFuture); // notify SENDER_BACKUP if (hasBackup && clusterSize > 1) { Operation senderBackupStatus = new KeyLoadStatusOperation(mapName, exception); Future senderBackupFuture = opService.createInvocationBuilder(SERVICE_NAME, senderBackupStatus, mapNamePartition) .setReplicaIndex(1).invoke(); futures.add(senderBackupFuture); } // Blocks until finished on SENDER & SENDER_BACKUP PARTITIONS // We need to wait for these operation to finished before the map-key-loader returns from the call // otherwise the loading won't be finished on SENDER and SENDER_BACKUP but the user may be able to call loadAll which // will be ignored since the SENDER and SENDER_BACKUP are still loading. FutureUtil.waitForever(futures); // INVOKES AND BLOCKS UNTIL FINISHED on ALL PARTITIONS (SENDER AND SENDER BACKUP WILL BE REPEATED) // notify all partitions about loading status: finished or exception encountered opService.invokeOnAllPartitions(SERVICE_NAME, new KeyLoadStatusOperationFactory(mapName, exception)); }
java
private void sendKeyLoadCompleted(int clusterSize, Throwable exception) throws Exception { // Notify SENDER first - reason why this is so important: // Someone may do map.get(other_nodes_key) and when it finishes do map.loadAll // The problem is that map.get may finish earlier than then overall loading on the SENDER due to the fact // that the LoadStatusOperation may first reach the node that did map.get and not the SENDER. // The SENDER will be then in the LOADING status, thus the loadAll call will be ignored. // it happens only if all LoadAllOperation finish before the sendKeyLoadCompleted is started (test case, little data) // Fixes https://github.com/hazelcast/hazelcast/issues/5453 List<Future> futures = new ArrayList<>(); Operation senderStatus = new KeyLoadStatusOperation(mapName, exception); Future senderFuture = opService.createInvocationBuilder(SERVICE_NAME, senderStatus, mapNamePartition) .setReplicaIndex(0).invoke(); futures.add(senderFuture); // notify SENDER_BACKUP if (hasBackup && clusterSize > 1) { Operation senderBackupStatus = new KeyLoadStatusOperation(mapName, exception); Future senderBackupFuture = opService.createInvocationBuilder(SERVICE_NAME, senderBackupStatus, mapNamePartition) .setReplicaIndex(1).invoke(); futures.add(senderBackupFuture); } // Blocks until finished on SENDER & SENDER_BACKUP PARTITIONS // We need to wait for these operation to finished before the map-key-loader returns from the call // otherwise the loading won't be finished on SENDER and SENDER_BACKUP but the user may be able to call loadAll which // will be ignored since the SENDER and SENDER_BACKUP are still loading. FutureUtil.waitForever(futures); // INVOKES AND BLOCKS UNTIL FINISHED on ALL PARTITIONS (SENDER AND SENDER BACKUP WILL BE REPEATED) // notify all partitions about loading status: finished or exception encountered opService.invokeOnAllPartitions(SERVICE_NAME, new KeyLoadStatusOperationFactory(mapName, exception)); }
[ "private", "void", "sendKeyLoadCompleted", "(", "int", "clusterSize", ",", "Throwable", "exception", ")", "throws", "Exception", "{", "// Notify SENDER first - reason why this is so important:", "// Someone may do map.get(other_nodes_key) and when it finishes do map.loadAll", "// The problem is that map.get may finish earlier than then overall loading on the SENDER due to the fact", "// that the LoadStatusOperation may first reach the node that did map.get and not the SENDER.", "// The SENDER will be then in the LOADING status, thus the loadAll call will be ignored.", "// it happens only if all LoadAllOperation finish before the sendKeyLoadCompleted is started (test case, little data)", "// Fixes https://github.com/hazelcast/hazelcast/issues/5453", "List", "<", "Future", ">", "futures", "=", "new", "ArrayList", "<>", "(", ")", ";", "Operation", "senderStatus", "=", "new", "KeyLoadStatusOperation", "(", "mapName", ",", "exception", ")", ";", "Future", "senderFuture", "=", "opService", ".", "createInvocationBuilder", "(", "SERVICE_NAME", ",", "senderStatus", ",", "mapNamePartition", ")", ".", "setReplicaIndex", "(", "0", ")", ".", "invoke", "(", ")", ";", "futures", ".", "add", "(", "senderFuture", ")", ";", "// notify SENDER_BACKUP", "if", "(", "hasBackup", "&&", "clusterSize", ">", "1", ")", "{", "Operation", "senderBackupStatus", "=", "new", "KeyLoadStatusOperation", "(", "mapName", ",", "exception", ")", ";", "Future", "senderBackupFuture", "=", "opService", ".", "createInvocationBuilder", "(", "SERVICE_NAME", ",", "senderBackupStatus", ",", "mapNamePartition", ")", ".", "setReplicaIndex", "(", "1", ")", ".", "invoke", "(", ")", ";", "futures", ".", "add", "(", "senderBackupFuture", ")", ";", "}", "// Blocks until finished on SENDER & SENDER_BACKUP PARTITIONS", "// We need to wait for these operation to finished before the map-key-loader returns from the call", "// otherwise the loading won't be finished on SENDER and SENDER_BACKUP but the user may be able to call loadAll which", "// will be ignored since the SENDER and SENDER_BACKUP are still loading.", "FutureUtil", ".", "waitForever", "(", "futures", ")", ";", "// INVOKES AND BLOCKS UNTIL FINISHED on ALL PARTITIONS (SENDER AND SENDER BACKUP WILL BE REPEATED)", "// notify all partitions about loading status: finished or exception encountered", "opService", ".", "invokeOnAllPartitions", "(", "SERVICE_NAME", ",", "new", "KeyLoadStatusOperationFactory", "(", "mapName", ",", "exception", ")", ")", ";", "}" ]
Notifies the record stores of the {@link MapKeyLoader.Role#SENDER}, {@link MapKeyLoader.Role#SENDER_BACKUP} and all other partition record stores that the key loading has finished and the keys have been dispatched to the partition owners for value loading. @param clusterSize the size of the cluster @param exception the exception that occurred during key loading or {@code null} if there was no exception @throws Exception if there was an exception when notifying the record stores that the key loading has finished @see com.hazelcast.map.impl.recordstore.RecordStore#updateLoadStatus(boolean, Throwable)
[ "Notifies", "the", "record", "stores", "of", "the", "{", "@link", "MapKeyLoader", ".", "Role#SENDER", "}", "{", "@link", "MapKeyLoader", ".", "Role#SENDER_BACKUP", "}", "and", "all", "other", "partition", "record", "stores", "that", "the", "key", "loading", "has", "finished", "and", "the", "keys", "have", "been", "dispatched", "to", "the", "partition", "owners", "for", "value", "loading", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/map/impl/MapKeyLoader.java#L499-L530
lessthanoptimal/BoofCV
main/boofcv-feature/src/main/java/boofcv/alg/flow/HornSchunck.java
HornSchunck.borderAverageFlow
protected static void borderAverageFlow( ImageFlow flow , ImageFlow averageFlow) { """ Computes average flow using an 8-connect neighborhood for the image border """ for( int y = 0; y < flow.height; y++ ) { computeBorder(flow,averageFlow, 0, y); computeBorder(flow,averageFlow, flow.width-1, y); } for( int x = 1; x < flow.width-1; x++ ) { computeBorder(flow,averageFlow, x, 0); computeBorder(flow,averageFlow, x, flow.height-1); } }
java
protected static void borderAverageFlow( ImageFlow flow , ImageFlow averageFlow) { for( int y = 0; y < flow.height; y++ ) { computeBorder(flow,averageFlow, 0, y); computeBorder(flow,averageFlow, flow.width-1, y); } for( int x = 1; x < flow.width-1; x++ ) { computeBorder(flow,averageFlow, x, 0); computeBorder(flow,averageFlow, x, flow.height-1); } }
[ "protected", "static", "void", "borderAverageFlow", "(", "ImageFlow", "flow", ",", "ImageFlow", "averageFlow", ")", "{", "for", "(", "int", "y", "=", "0", ";", "y", "<", "flow", ".", "height", ";", "y", "++", ")", "{", "computeBorder", "(", "flow", ",", "averageFlow", ",", "0", ",", "y", ")", ";", "computeBorder", "(", "flow", ",", "averageFlow", ",", "flow", ".", "width", "-", "1", ",", "y", ")", ";", "}", "for", "(", "int", "x", "=", "1", ";", "x", "<", "flow", ".", "width", "-", "1", ";", "x", "++", ")", "{", "computeBorder", "(", "flow", ",", "averageFlow", ",", "x", ",", "0", ")", ";", "computeBorder", "(", "flow", ",", "averageFlow", ",", "x", ",", "flow", ".", "height", "-", "1", ")", ";", "}", "}" ]
Computes average flow using an 8-connect neighborhood for the image border
[ "Computes", "average", "flow", "using", "an", "8", "-", "connect", "neighborhood", "for", "the", "image", "border" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/flow/HornSchunck.java#L154-L165
andriusvelykis/reflow-maven-skin
reflow-velocity-tools/src/main/java/lt/velykis/maven/skins/reflow/HtmlTool.java
HtmlTool.addClass
public String addClass(String content, String selector, String className) { """ Adds given class to the elements in HTML. @param content HTML content to modify @param selector CSS selector for elements to add the class to @param className Name of class to add to the selected elements @return HTML content with modified elements. If no elements are found, the original content is returned. @since 1.0 """ return addClass(content, selector, Collections.singletonList(className)); }
java
public String addClass(String content, String selector, String className) { return addClass(content, selector, Collections.singletonList(className)); }
[ "public", "String", "addClass", "(", "String", "content", ",", "String", "selector", ",", "String", "className", ")", "{", "return", "addClass", "(", "content", ",", "selector", ",", "Collections", ".", "singletonList", "(", "className", ")", ")", ";", "}" ]
Adds given class to the elements in HTML. @param content HTML content to modify @param selector CSS selector for elements to add the class to @param className Name of class to add to the selected elements @return HTML content with modified elements. If no elements are found, the original content is returned. @since 1.0
[ "Adds", "given", "class", "to", "the", "elements", "in", "HTML", "." ]
train
https://github.com/andriusvelykis/reflow-maven-skin/blob/01170ae1426a1adfe7cc9c199e77aaa2ecb37ef2/reflow-velocity-tools/src/main/java/lt/velykis/maven/skins/reflow/HtmlTool.java#L713-L715
apache/groovy
src/main/java/org/codehaus/groovy/classgen/asm/BytecodeHelper.java
BytecodeHelper.convertPrimitiveToBoolean
public static void convertPrimitiveToBoolean(MethodVisitor mv, ClassNode type) { """ Converts a primitive type to boolean. @param mv method visitor @param type primitive type to convert """ if (type == boolean_TYPE) { return; } // Special handling is done for floating point types in order to // handle checking for 0 or NaN values. if (type == double_TYPE) { convertDoubleToBoolean(mv); return; } else if (type == float_TYPE) { convertFloatToBoolean(mv); return; } Label trueLabel = new Label(); Label falseLabel = new Label(); // Convert long to int for IFEQ comparison using LCMP if (type== long_TYPE) { mv.visitInsn(LCONST_0); mv.visitInsn(LCMP); } // This handles byte, short, char and int mv.visitJumpInsn(IFEQ, falseLabel); mv.visitInsn(ICONST_1); mv.visitJumpInsn(GOTO, trueLabel); mv.visitLabel(falseLabel); mv.visitInsn(ICONST_0); mv.visitLabel(trueLabel); }
java
public static void convertPrimitiveToBoolean(MethodVisitor mv, ClassNode type) { if (type == boolean_TYPE) { return; } // Special handling is done for floating point types in order to // handle checking for 0 or NaN values. if (type == double_TYPE) { convertDoubleToBoolean(mv); return; } else if (type == float_TYPE) { convertFloatToBoolean(mv); return; } Label trueLabel = new Label(); Label falseLabel = new Label(); // Convert long to int for IFEQ comparison using LCMP if (type== long_TYPE) { mv.visitInsn(LCONST_0); mv.visitInsn(LCMP); } // This handles byte, short, char and int mv.visitJumpInsn(IFEQ, falseLabel); mv.visitInsn(ICONST_1); mv.visitJumpInsn(GOTO, trueLabel); mv.visitLabel(falseLabel); mv.visitInsn(ICONST_0); mv.visitLabel(trueLabel); }
[ "public", "static", "void", "convertPrimitiveToBoolean", "(", "MethodVisitor", "mv", ",", "ClassNode", "type", ")", "{", "if", "(", "type", "==", "boolean_TYPE", ")", "{", "return", ";", "}", "// Special handling is done for floating point types in order to", "// handle checking for 0 or NaN values.", "if", "(", "type", "==", "double_TYPE", ")", "{", "convertDoubleToBoolean", "(", "mv", ")", ";", "return", ";", "}", "else", "if", "(", "type", "==", "float_TYPE", ")", "{", "convertFloatToBoolean", "(", "mv", ")", ";", "return", ";", "}", "Label", "trueLabel", "=", "new", "Label", "(", ")", ";", "Label", "falseLabel", "=", "new", "Label", "(", ")", ";", "// Convert long to int for IFEQ comparison using LCMP", "if", "(", "type", "==", "long_TYPE", ")", "{", "mv", ".", "visitInsn", "(", "LCONST_0", ")", ";", "mv", ".", "visitInsn", "(", "LCMP", ")", ";", "}", "// This handles byte, short, char and int", "mv", ".", "visitJumpInsn", "(", "IFEQ", ",", "falseLabel", ")", ";", "mv", ".", "visitInsn", "(", "ICONST_1", ")", ";", "mv", ".", "visitJumpInsn", "(", "GOTO", ",", "trueLabel", ")", ";", "mv", ".", "visitLabel", "(", "falseLabel", ")", ";", "mv", ".", "visitInsn", "(", "ICONST_0", ")", ";", "mv", ".", "visitLabel", "(", "trueLabel", ")", ";", "}" ]
Converts a primitive type to boolean. @param mv method visitor @param type primitive type to convert
[ "Converts", "a", "primitive", "type", "to", "boolean", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/classgen/asm/BytecodeHelper.java#L592-L619
alkacon/opencms-core
src/org/opencms/file/CmsLinkRewriter.java
CmsLinkRewriter.rewriteOtherRelations
protected void rewriteOtherRelations(CmsResource res, Collection<CmsRelation> relations) throws CmsException { """ Rewrites relations which are not derived from links in the content itself.<p> @param res the resource for which to rewrite the relations @param relations the original relations @throws CmsException if something goes wrong """ LOG.info("Rewriting non-content links for " + res.getRootPath()); for (CmsRelation rel : relations) { CmsUUID targetId = rel.getTargetId(); CmsResource newTargetResource = m_translationsById.get(targetId); CmsRelationType relType = rel.getType(); if (!relType.isDefinedInContent()) { if (newTargetResource != null) { m_cms.deleteRelationsFromResource( rel.getSourcePath(), CmsRelationFilter.TARGETS.filterStructureId(rel.getTargetId()).filterType(relType)); m_cms.addRelationToResource( rel.getSourcePath(), newTargetResource.getRootPath(), relType.getName()); } } } }
java
protected void rewriteOtherRelations(CmsResource res, Collection<CmsRelation> relations) throws CmsException { LOG.info("Rewriting non-content links for " + res.getRootPath()); for (CmsRelation rel : relations) { CmsUUID targetId = rel.getTargetId(); CmsResource newTargetResource = m_translationsById.get(targetId); CmsRelationType relType = rel.getType(); if (!relType.isDefinedInContent()) { if (newTargetResource != null) { m_cms.deleteRelationsFromResource( rel.getSourcePath(), CmsRelationFilter.TARGETS.filterStructureId(rel.getTargetId()).filterType(relType)); m_cms.addRelationToResource( rel.getSourcePath(), newTargetResource.getRootPath(), relType.getName()); } } } }
[ "protected", "void", "rewriteOtherRelations", "(", "CmsResource", "res", ",", "Collection", "<", "CmsRelation", ">", "relations", ")", "throws", "CmsException", "{", "LOG", ".", "info", "(", "\"Rewriting non-content links for \"", "+", "res", ".", "getRootPath", "(", ")", ")", ";", "for", "(", "CmsRelation", "rel", ":", "relations", ")", "{", "CmsUUID", "targetId", "=", "rel", ".", "getTargetId", "(", ")", ";", "CmsResource", "newTargetResource", "=", "m_translationsById", ".", "get", "(", "targetId", ")", ";", "CmsRelationType", "relType", "=", "rel", ".", "getType", "(", ")", ";", "if", "(", "!", "relType", ".", "isDefinedInContent", "(", ")", ")", "{", "if", "(", "newTargetResource", "!=", "null", ")", "{", "m_cms", ".", "deleteRelationsFromResource", "(", "rel", ".", "getSourcePath", "(", ")", ",", "CmsRelationFilter", ".", "TARGETS", ".", "filterStructureId", "(", "rel", ".", "getTargetId", "(", ")", ")", ".", "filterType", "(", "relType", ")", ")", ";", "m_cms", ".", "addRelationToResource", "(", "rel", ".", "getSourcePath", "(", ")", ",", "newTargetResource", ".", "getRootPath", "(", ")", ",", "relType", ".", "getName", "(", ")", ")", ";", "}", "}", "}", "}" ]
Rewrites relations which are not derived from links in the content itself.<p> @param res the resource for which to rewrite the relations @param relations the original relations @throws CmsException if something goes wrong
[ "Rewrites", "relations", "which", "are", "not", "derived", "from", "links", "in", "the", "content", "itself", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/file/CmsLinkRewriter.java#L722-L741
3redronin/mu-server
src/main/java/io/muserver/MuServerBuilder.java
MuServerBuilder.withGzip
public MuServerBuilder withGzip(long minimumGzipSize, Set<String> mimeTypesToGzip) { """ Enables gzip for files of at least the specified size that match the given mime-types. By default, gzip is enabled for text-based mime types over 1400 bytes. It is recommended to keep the defaults and only use this method if you have very specific requirements around GZIP. @param minimumGzipSize The size in bytes before gzip is used. The default is 1400. @param mimeTypesToGzip The mime-types that should be gzipped. In general, only text files should be gzipped. @return The current Mu-Server Builder """ this.gzipEnabled = true; this.mimeTypesToGzip = mimeTypesToGzip; this.minimumGzipSize = minimumGzipSize; return this; }
java
public MuServerBuilder withGzip(long minimumGzipSize, Set<String> mimeTypesToGzip) { this.gzipEnabled = true; this.mimeTypesToGzip = mimeTypesToGzip; this.minimumGzipSize = minimumGzipSize; return this; }
[ "public", "MuServerBuilder", "withGzip", "(", "long", "minimumGzipSize", ",", "Set", "<", "String", ">", "mimeTypesToGzip", ")", "{", "this", ".", "gzipEnabled", "=", "true", ";", "this", ".", "mimeTypesToGzip", "=", "mimeTypesToGzip", ";", "this", ".", "minimumGzipSize", "=", "minimumGzipSize", ";", "return", "this", ";", "}" ]
Enables gzip for files of at least the specified size that match the given mime-types. By default, gzip is enabled for text-based mime types over 1400 bytes. It is recommended to keep the defaults and only use this method if you have very specific requirements around GZIP. @param minimumGzipSize The size in bytes before gzip is used. The default is 1400. @param mimeTypesToGzip The mime-types that should be gzipped. In general, only text files should be gzipped. @return The current Mu-Server Builder
[ "Enables", "gzip", "for", "files", "of", "at", "least", "the", "specified", "size", "that", "match", "the", "given", "mime", "-", "types", ".", "By", "default", "gzip", "is", "enabled", "for", "text", "-", "based", "mime", "types", "over", "1400", "bytes", ".", "It", "is", "recommended", "to", "keep", "the", "defaults", "and", "only", "use", "this", "method", "if", "you", "have", "very", "specific", "requirements", "around", "GZIP", "." ]
train
https://github.com/3redronin/mu-server/blob/51598606a3082a121fbd785348ee9770b40308e6/src/main/java/io/muserver/MuServerBuilder.java#L121-L126
Jasig/uPortal
uPortal-groups/uPortal-groups-core/src/main/java/org/apereo/portal/services/EntityLockService.java
EntityLockService.newWriteLock
public IEntityLock newWriteLock(Class entityType, String entityKey, String owner) throws LockingException { """ Returns a write lock for the entity type, entity key and owner. @return org.apereo.portal.concurrency.locking.IEntityLock @param entityType Class @param entityKey String @param owner String @exception LockingException """ return lockService.newLock(entityType, entityKey, IEntityLockService.WRITE_LOCK, owner); }
java
public IEntityLock newWriteLock(Class entityType, String entityKey, String owner) throws LockingException { return lockService.newLock(entityType, entityKey, IEntityLockService.WRITE_LOCK, owner); }
[ "public", "IEntityLock", "newWriteLock", "(", "Class", "entityType", ",", "String", "entityKey", ",", "String", "owner", ")", "throws", "LockingException", "{", "return", "lockService", ".", "newLock", "(", "entityType", ",", "entityKey", ",", "IEntityLockService", ".", "WRITE_LOCK", ",", "owner", ")", ";", "}" ]
Returns a write lock for the entity type, entity key and owner. @return org.apereo.portal.concurrency.locking.IEntityLock @param entityType Class @param entityKey String @param owner String @exception LockingException
[ "Returns", "a", "write", "lock", "for", "the", "entity", "type", "entity", "key", "and", "owner", "." ]
train
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-groups/uPortal-groups-core/src/main/java/org/apereo/portal/services/EntityLockService.java#L177-L180
cesarferreira/AndroidQuickUtils
library/src/main/java/quickutils/core/cache/GsonCache.java
GsonCache.read
public static <T> T read(String key, Class<T> classOfT) throws Exception { """ Get an object from Reservoir with the given key. This a blocking IO operation. @param key the key string. @param classOfT the Class type of the expected return object. @return the object of the given type if it exists. """ String json = cache.getString(key).getString(); T value = new Gson().fromJson(json, classOfT); if (value == null) { throw new NullPointerException(); } return value; }
java
public static <T> T read(String key, Class<T> classOfT) throws Exception { String json = cache.getString(key).getString(); T value = new Gson().fromJson(json, classOfT); if (value == null) { throw new NullPointerException(); } return value; }
[ "public", "static", "<", "T", ">", "T", "read", "(", "String", "key", ",", "Class", "<", "T", ">", "classOfT", ")", "throws", "Exception", "{", "String", "json", "=", "cache", ".", "getString", "(", "key", ")", ".", "getString", "(", ")", ";", "T", "value", "=", "new", "Gson", "(", ")", ".", "fromJson", "(", "json", ",", "classOfT", ")", ";", "if", "(", "value", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", ")", ";", "}", "return", "value", ";", "}" ]
Get an object from Reservoir with the given key. This a blocking IO operation. @param key the key string. @param classOfT the Class type of the expected return object. @return the object of the given type if it exists.
[ "Get", "an", "object", "from", "Reservoir", "with", "the", "given", "key", ".", "This", "a", "blocking", "IO", "operation", "." ]
train
https://github.com/cesarferreira/AndroidQuickUtils/blob/73a91daedbb9f7be7986ea786fbc441c9e5a881c/library/src/main/java/quickutils/core/cache/GsonCache.java#L80-L88
OpenLiberty/open-liberty
dev/com.ibm.ws.jaxrs.2.0.common/src/org/apache/cxf/jaxrs/utils/ThreadLocalProxyCopyOnWriteArrayList.java
ThreadLocalProxyCopyOnWriteArrayList.removeRange
private void removeRange(int fromIndex, int toIndex) { """ Removes from this list all of the elements whose index is between <tt>fromIndex</tt>, inclusive, and <tt>toIndex</tt>, exclusive. Shifts any succeeding elements to the left (reduces their index). This call shortens the list by <tt>(toIndex - fromIndex)</tt> elements. (If <tt>toIndex==fromIndex</tt>, this operation has no effect.) @param fromIndex index of first element to be removed @param toIndex index after last element to be removed @throws IndexOutOfBoundsException if fromIndex or toIndex out of range ({@code{fromIndex < 0 || toIndex > size() || toIndex < fromIndex}) """ final ReentrantLock lock = this.lock; lock.lock(); try { Object[] elements = getArray(); int len = elements.length; if (fromIndex < 0 || toIndex > len || toIndex < fromIndex) throw new IndexOutOfBoundsException(); int newlen = len - (toIndex - fromIndex); int numMoved = len - toIndex; if (numMoved == 0) setArray(Arrays.copyOf(elements, newlen)); else { Object[] newElements = new Object[newlen]; System.arraycopy(elements, 0, newElements, 0, fromIndex); System.arraycopy(elements, toIndex, newElements, fromIndex, numMoved); setArray(newElements); } } finally { lock.unlock(); } }
java
private void removeRange(int fromIndex, int toIndex) { final ReentrantLock lock = this.lock; lock.lock(); try { Object[] elements = getArray(); int len = elements.length; if (fromIndex < 0 || toIndex > len || toIndex < fromIndex) throw new IndexOutOfBoundsException(); int newlen = len - (toIndex - fromIndex); int numMoved = len - toIndex; if (numMoved == 0) setArray(Arrays.copyOf(elements, newlen)); else { Object[] newElements = new Object[newlen]; System.arraycopy(elements, 0, newElements, 0, fromIndex); System.arraycopy(elements, toIndex, newElements, fromIndex, numMoved); setArray(newElements); } } finally { lock.unlock(); } }
[ "private", "void", "removeRange", "(", "int", "fromIndex", ",", "int", "toIndex", ")", "{", "final", "ReentrantLock", "lock", "=", "this", ".", "lock", ";", "lock", ".", "lock", "(", ")", ";", "try", "{", "Object", "[", "]", "elements", "=", "getArray", "(", ")", ";", "int", "len", "=", "elements", ".", "length", ";", "if", "(", "fromIndex", "<", "0", "||", "toIndex", ">", "len", "||", "toIndex", "<", "fromIndex", ")", "throw", "new", "IndexOutOfBoundsException", "(", ")", ";", "int", "newlen", "=", "len", "-", "(", "toIndex", "-", "fromIndex", ")", ";", "int", "numMoved", "=", "len", "-", "toIndex", ";", "if", "(", "numMoved", "==", "0", ")", "setArray", "(", "Arrays", ".", "copyOf", "(", "elements", ",", "newlen", ")", ")", ";", "else", "{", "Object", "[", "]", "newElements", "=", "new", "Object", "[", "newlen", "]", ";", "System", ".", "arraycopy", "(", "elements", ",", "0", ",", "newElements", ",", "0", ",", "fromIndex", ")", ";", "System", ".", "arraycopy", "(", "elements", ",", "toIndex", ",", "newElements", ",", "fromIndex", ",", "numMoved", ")", ";", "setArray", "(", "newElements", ")", ";", "}", "}", "finally", "{", "lock", ".", "unlock", "(", ")", ";", "}", "}" ]
Removes from this list all of the elements whose index is between <tt>fromIndex</tt>, inclusive, and <tt>toIndex</tt>, exclusive. Shifts any succeeding elements to the left (reduces their index). This call shortens the list by <tt>(toIndex - fromIndex)</tt> elements. (If <tt>toIndex==fromIndex</tt>, this operation has no effect.) @param fromIndex index of first element to be removed @param toIndex index after last element to be removed @throws IndexOutOfBoundsException if fromIndex or toIndex out of range ({@code{fromIndex < 0 || toIndex > size() || toIndex < fromIndex})
[ "Removes", "from", "this", "list", "all", "of", "the", "elements", "whose", "index", "is", "between", "<tt", ">", "fromIndex<", "/", "tt", ">", "inclusive", "and", "<tt", ">", "toIndex<", "/", "tt", ">", "exclusive", ".", "Shifts", "any", "succeeding", "elements", "to", "the", "left", "(", "reduces", "their", "index", ")", ".", "This", "call", "shortens", "the", "list", "by", "<tt", ">", "(", "toIndex", "-", "fromIndex", ")", "<", "/", "tt", ">", "elements", ".", "(", "If", "<tt", ">", "toIndex", "==", "fromIndex<", "/", "tt", ">", "this", "operation", "has", "no", "effect", ".", ")" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jaxrs.2.0.common/src/org/apache/cxf/jaxrs/utils/ThreadLocalProxyCopyOnWriteArrayList.java#L496-L519
Azure/autorest-clientruntime-for-java
azure-arm-client-runtime/src/main/java/com/microsoft/azure/arm/utils/ResourceNamer.java
ResourceNamer.randomName
public String randomName(String prefix, int maxLen) { """ Gets a random name. @param prefix the prefix to be used if possible @param maxLen the max length for the random generated name @return the random name """ prefix = prefix.toLowerCase(); int minRandomnessLength = 5; if (maxLen <= minRandomnessLength) { return randomString(maxLen); } if (maxLen < prefix.length() + minRandomnessLength) { return randomString(maxLen); } String minRandomString = String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); if (maxLen <= prefix.length() + randName.length() + minRandomnessLength) { String str = prefix + minRandomString; return str + randomString((maxLen - str.length()) / 2); } String str = prefix + randName + minRandomString; return str + randomString((maxLen - str.length()) / 2); }
java
public String randomName(String prefix, int maxLen) { prefix = prefix.toLowerCase(); int minRandomnessLength = 5; if (maxLen <= minRandomnessLength) { return randomString(maxLen); } if (maxLen < prefix.length() + minRandomnessLength) { return randomString(maxLen); } String minRandomString = String.format("%05d", Math.abs(RANDOM.nextInt() % 100000)); if (maxLen <= prefix.length() + randName.length() + minRandomnessLength) { String str = prefix + minRandomString; return str + randomString((maxLen - str.length()) / 2); } String str = prefix + randName + minRandomString; return str + randomString((maxLen - str.length()) / 2); }
[ "public", "String", "randomName", "(", "String", "prefix", ",", "int", "maxLen", ")", "{", "prefix", "=", "prefix", ".", "toLowerCase", "(", ")", ";", "int", "minRandomnessLength", "=", "5", ";", "if", "(", "maxLen", "<=", "minRandomnessLength", ")", "{", "return", "randomString", "(", "maxLen", ")", ";", "}", "if", "(", "maxLen", "<", "prefix", ".", "length", "(", ")", "+", "minRandomnessLength", ")", "{", "return", "randomString", "(", "maxLen", ")", ";", "}", "String", "minRandomString", "=", "String", ".", "format", "(", "\"%05d\"", ",", "Math", ".", "abs", "(", "RANDOM", ".", "nextInt", "(", ")", "%", "100000", ")", ")", ";", "if", "(", "maxLen", "<=", "prefix", ".", "length", "(", ")", "+", "randName", ".", "length", "(", ")", "+", "minRandomnessLength", ")", "{", "String", "str", "=", "prefix", "+", "minRandomString", ";", "return", "str", "+", "randomString", "(", "(", "maxLen", "-", "str", ".", "length", "(", ")", ")", "/", "2", ")", ";", "}", "String", "str", "=", "prefix", "+", "randName", "+", "minRandomString", ";", "return", "str", "+", "randomString", "(", "(", "maxLen", "-", "str", ".", "length", "(", ")", ")", "/", "2", ")", ";", "}" ]
Gets a random name. @param prefix the prefix to be used if possible @param maxLen the max length for the random generated name @return the random name
[ "Gets", "a", "random", "name", "." ]
train
https://github.com/Azure/autorest-clientruntime-for-java/blob/04621e07dbb0456dd5459dd641f06a9fd4f3abad/azure-arm-client-runtime/src/main/java/com/microsoft/azure/arm/utils/ResourceNamer.java#L35-L55
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/classification/Evaluation.java
Evaluation.getPredictions
public List<Prediction> getPredictions(int actualClass, int predictedClass) { """ Get a list of predictions in the specified confusion matrix entry (i.e., for the given actua/predicted class pair) @param actualClass Actual class @param predictedClass Predicted class @return List of predictions that match the specified actual/predicted classes, or null if the "evaluate with metadata" method was not used """ if (confusionMatrixMetaData == null) return null; List<Prediction> out = new ArrayList<>(); List<Object> list = confusionMatrixMetaData.get(new Pair<>(actualClass, predictedClass)); if (list == null) return out; for (Object meta : list) { out.add(new Prediction(actualClass, predictedClass, meta)); } return out; }
java
public List<Prediction> getPredictions(int actualClass, int predictedClass) { if (confusionMatrixMetaData == null) return null; List<Prediction> out = new ArrayList<>(); List<Object> list = confusionMatrixMetaData.get(new Pair<>(actualClass, predictedClass)); if (list == null) return out; for (Object meta : list) { out.add(new Prediction(actualClass, predictedClass, meta)); } return out; }
[ "public", "List", "<", "Prediction", ">", "getPredictions", "(", "int", "actualClass", ",", "int", "predictedClass", ")", "{", "if", "(", "confusionMatrixMetaData", "==", "null", ")", "return", "null", ";", "List", "<", "Prediction", ">", "out", "=", "new", "ArrayList", "<>", "(", ")", ";", "List", "<", "Object", ">", "list", "=", "confusionMatrixMetaData", ".", "get", "(", "new", "Pair", "<>", "(", "actualClass", ",", "predictedClass", ")", ")", ";", "if", "(", "list", "==", "null", ")", "return", "out", ";", "for", "(", "Object", "meta", ":", "list", ")", "{", "out", ".", "add", "(", "new", "Prediction", "(", "actualClass", ",", "predictedClass", ",", "meta", ")", ")", ";", "}", "return", "out", ";", "}" ]
Get a list of predictions in the specified confusion matrix entry (i.e., for the given actua/predicted class pair) @param actualClass Actual class @param predictedClass Predicted class @return List of predictions that match the specified actual/predicted classes, or null if the "evaluate with metadata" method was not used
[ "Get", "a", "list", "of", "predictions", "in", "the", "specified", "confusion", "matrix", "entry", "(", "i", ".", "e", ".", "for", "the", "given", "actua", "/", "predicted", "class", "pair", ")" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/classification/Evaluation.java#L1824-L1837
BorderTech/wcomponents
wcomponents-core/src/main/java/com/github/bordertech/wcomponents/util/TreeUtil.java
TreeUtil.getClosestContextForId
public static UIContext getClosestContextForId(final WComponent root, final String id) { """ Retrieves the closest context for the component with the given Id. <p> Searches visible and not visible components. </p> @param root the root component to search from. @param id the id to search for. @return the closest context for the component with the given id, or null if not found. """ return getClosestContextForId(root, id, false); }
java
public static UIContext getClosestContextForId(final WComponent root, final String id) { return getClosestContextForId(root, id, false); }
[ "public", "static", "UIContext", "getClosestContextForId", "(", "final", "WComponent", "root", ",", "final", "String", "id", ")", "{", "return", "getClosestContextForId", "(", "root", ",", "id", ",", "false", ")", ";", "}" ]
Retrieves the closest context for the component with the given Id. <p> Searches visible and not visible components. </p> @param root the root component to search from. @param id the id to search for. @return the closest context for the component with the given id, or null if not found.
[ "Retrieves", "the", "closest", "context", "for", "the", "component", "with", "the", "given", "Id", ".", "<p", ">", "Searches", "visible", "and", "not", "visible", "components", ".", "<", "/", "p", ">" ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/util/TreeUtil.java#L214-L216
Azure/azure-sdk-for-java
mysql/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/mysql/v2017_12_01/implementation/ServersInner.java
ServersInner.beginUpdateAsync
public Observable<ServerInner> beginUpdateAsync(String resourceGroupName, String serverName, ServerUpdateParameters parameters) { """ Updates an existing server. The request body can contain one to many of the properties present in the normal server definition. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server. @param parameters The required parameters for updating a server. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the ServerInner object """ return beginUpdateWithServiceResponseAsync(resourceGroupName, serverName, parameters).map(new Func1<ServiceResponse<ServerInner>, ServerInner>() { @Override public ServerInner call(ServiceResponse<ServerInner> response) { return response.body(); } }); }
java
public Observable<ServerInner> beginUpdateAsync(String resourceGroupName, String serverName, ServerUpdateParameters parameters) { return beginUpdateWithServiceResponseAsync(resourceGroupName, serverName, parameters).map(new Func1<ServiceResponse<ServerInner>, ServerInner>() { @Override public ServerInner call(ServiceResponse<ServerInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "ServerInner", ">", "beginUpdateAsync", "(", "String", "resourceGroupName", ",", "String", "serverName", ",", "ServerUpdateParameters", "parameters", ")", "{", "return", "beginUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "serverName", ",", "parameters", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "ServerInner", ">", ",", "ServerInner", ">", "(", ")", "{", "@", "Override", "public", "ServerInner", "call", "(", "ServiceResponse", "<", "ServerInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Updates an existing server. The request body can contain one to many of the properties present in the normal server definition. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server. @param parameters The required parameters for updating a server. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the ServerInner object
[ "Updates", "an", "existing", "server", ".", "The", "request", "body", "can", "contain", "one", "to", "many", "of", "the", "properties", "present", "in", "the", "normal", "server", "definition", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/mysql/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/mysql/v2017_12_01/implementation/ServersInner.java#L393-L400
ggrandes/packer
src/main/java/org/javastack/packer/Packer.java
Packer.getStringF
public String getStringF() { """ Get String stored in UTF-8 format (encoded as: Int32-Length + bytes) @return @see #putString(String) """ int len = getInt(); byte[] utf = new byte[len]; System.arraycopy(buf, bufPosition, utf, 0, utf.length); bufPosition += utf.length; return new String(utf, 0, len, charsetUTF8); }
java
public String getStringF() { int len = getInt(); byte[] utf = new byte[len]; System.arraycopy(buf, bufPosition, utf, 0, utf.length); bufPosition += utf.length; return new String(utf, 0, len, charsetUTF8); }
[ "public", "String", "getStringF", "(", ")", "{", "int", "len", "=", "getInt", "(", ")", ";", "byte", "[", "]", "utf", "=", "new", "byte", "[", "len", "]", ";", "System", ".", "arraycopy", "(", "buf", ",", "bufPosition", ",", "utf", ",", "0", ",", "utf", ".", "length", ")", ";", "bufPosition", "+=", "utf", ".", "length", ";", "return", "new", "String", "(", "utf", ",", "0", ",", "len", ",", "charsetUTF8", ")", ";", "}" ]
Get String stored in UTF-8 format (encoded as: Int32-Length + bytes) @return @see #putString(String)
[ "Get", "String", "stored", "in", "UTF", "-", "8", "format", "(", "encoded", "as", ":", "Int32", "-", "Length", "+", "bytes", ")" ]
train
https://github.com/ggrandes/packer/blob/0b37b286a3d0555050eb2e65419dd74f8d8d3e78/src/main/java/org/javastack/packer/Packer.java#L1107-L1113
carewebframework/carewebframework-core
org.carewebframework.shell/src/main/java/org/carewebframework/shell/layout/LayoutParser.java
LayoutParser.copyAttributes
private void copyAttributes(ElementBase src, LayoutElement dest) { """ Copy attributes from a UI element to layout element. @param src UI element. @param dest Layout element. """ for (PropertyInfo propInfo : src.getDefinition().getProperties()) { Object value = propInfo.isSerializable() ? propInfo.getPropertyValue(src) : null; String val = value == null ? null : propInfo.getPropertyType().getSerializer().serialize(value); if (!ObjectUtils.equals(value, propInfo.getDefault())) { dest.getAttributes().put(propInfo.getId(), val); } } }
java
private void copyAttributes(ElementBase src, LayoutElement dest) { for (PropertyInfo propInfo : src.getDefinition().getProperties()) { Object value = propInfo.isSerializable() ? propInfo.getPropertyValue(src) : null; String val = value == null ? null : propInfo.getPropertyType().getSerializer().serialize(value); if (!ObjectUtils.equals(value, propInfo.getDefault())) { dest.getAttributes().put(propInfo.getId(), val); } } }
[ "private", "void", "copyAttributes", "(", "ElementBase", "src", ",", "LayoutElement", "dest", ")", "{", "for", "(", "PropertyInfo", "propInfo", ":", "src", ".", "getDefinition", "(", ")", ".", "getProperties", "(", ")", ")", "{", "Object", "value", "=", "propInfo", ".", "isSerializable", "(", ")", "?", "propInfo", ".", "getPropertyValue", "(", "src", ")", ":", "null", ";", "String", "val", "=", "value", "==", "null", "?", "null", ":", "propInfo", ".", "getPropertyType", "(", ")", ".", "getSerializer", "(", ")", ".", "serialize", "(", "value", ")", ";", "if", "(", "!", "ObjectUtils", ".", "equals", "(", "value", ",", "propInfo", ".", "getDefault", "(", ")", ")", ")", "{", "dest", ".", "getAttributes", "(", ")", ".", "put", "(", "propInfo", ".", "getId", "(", ")", ",", "val", ")", ";", "}", "}", "}" ]
Copy attributes from a UI element to layout element. @param src UI element. @param dest Layout element.
[ "Copy", "attributes", "from", "a", "UI", "element", "to", "layout", "element", "." ]
train
https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.shell/src/main/java/org/carewebframework/shell/layout/LayoutParser.java#L407-L416
DDTH/ddth-dao
ddth-dao-core/src/main/java/com/github/ddth/dao/BaseDao.java
BaseDao.putToCache
protected void putToCache(String cacheName, String key, Object value, long ttlSeconds) { """ Puts an entry to cache, with specific TTL. @param cacheName @param key @param value @param ttlSeconds """ if (cacheItemsExpireAfterWrite) { putToCache(cacheName, key, value, ttlSeconds, 0); } else { putToCache(cacheName, key, value, 0, ttlSeconds); } }
java
protected void putToCache(String cacheName, String key, Object value, long ttlSeconds) { if (cacheItemsExpireAfterWrite) { putToCache(cacheName, key, value, ttlSeconds, 0); } else { putToCache(cacheName, key, value, 0, ttlSeconds); } }
[ "protected", "void", "putToCache", "(", "String", "cacheName", ",", "String", "key", ",", "Object", "value", ",", "long", "ttlSeconds", ")", "{", "if", "(", "cacheItemsExpireAfterWrite", ")", "{", "putToCache", "(", "cacheName", ",", "key", ",", "value", ",", "ttlSeconds", ",", "0", ")", ";", "}", "else", "{", "putToCache", "(", "cacheName", ",", "key", ",", "value", ",", "0", ",", "ttlSeconds", ")", ";", "}", "}" ]
Puts an entry to cache, with specific TTL. @param cacheName @param key @param value @param ttlSeconds
[ "Puts", "an", "entry", "to", "cache", "with", "specific", "TTL", "." ]
train
https://github.com/DDTH/ddth-dao/blob/8d059ddf641a1629aa53851f9d1b41abf175a180/ddth-dao-core/src/main/java/com/github/ddth/dao/BaseDao.java#L174-L180
alkacon/opencms-core
src/org/opencms/module/CmsModule.java
CmsModule.getParameter
public String getParameter(String key, String defaultValue) { """ Returns a parameter value from the module parameters, or a given default value in case the parameter is not set.<p> @param key the parameter to return the value for @param defaultValue the default value in case there is no value stored for this key @return the parameter value from the module parameters """ String value = m_parameters.get(key); return (value != null) ? value : defaultValue; }
java
public String getParameter(String key, String defaultValue) { String value = m_parameters.get(key); return (value != null) ? value : defaultValue; }
[ "public", "String", "getParameter", "(", "String", "key", ",", "String", "defaultValue", ")", "{", "String", "value", "=", "m_parameters", ".", "get", "(", "key", ")", ";", "return", "(", "value", "!=", "null", ")", "?", "value", ":", "defaultValue", ";", "}" ]
Returns a parameter value from the module parameters, or a given default value in case the parameter is not set.<p> @param key the parameter to return the value for @param defaultValue the default value in case there is no value stored for this key @return the parameter value from the module parameters
[ "Returns", "a", "parameter", "value", "from", "the", "module", "parameters", "or", "a", "given", "default", "value", "in", "case", "the", "parameter", "is", "not", "set", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/module/CmsModule.java#L934-L938
codeprimate-software/cp-elements
src/main/java/org/cp/elements/lang/reflect/MethodInvocation.java
MethodInvocation.newMethodInvocation
public static MethodInvocation newMethodInvocation(Method method, Object... args) { """ Factory method used to construct a new instance of {@link MethodInvocation} initialized with the given {@link Method} and array of {@link Object arguments} passed to the {@link Method} during invocation. The {@link Method} is expected to be a {@link java.lang.reflect.Modifier#STATIC}, {@link Class} member {@link Method}. @param method {@link Method} to invoke. @param args array of {@link Object arguments} to pass to the {@link Method} during invocation. @return an instance of {@link MethodInvocation} encapsulating all the necessary details to invoke the {@link java.lang.reflect.Modifier#STATIC} {@link Method}. @see #newMethodInvocation(Object, Method, Object...) @see java.lang.reflect.Method """ return newMethodInvocation(null, method, args); }
java
public static MethodInvocation newMethodInvocation(Method method, Object... args) { return newMethodInvocation(null, method, args); }
[ "public", "static", "MethodInvocation", "newMethodInvocation", "(", "Method", "method", ",", "Object", "...", "args", ")", "{", "return", "newMethodInvocation", "(", "null", ",", "method", ",", "args", ")", ";", "}" ]
Factory method used to construct a new instance of {@link MethodInvocation} initialized with the given {@link Method} and array of {@link Object arguments} passed to the {@link Method} during invocation. The {@link Method} is expected to be a {@link java.lang.reflect.Modifier#STATIC}, {@link Class} member {@link Method}. @param method {@link Method} to invoke. @param args array of {@link Object arguments} to pass to the {@link Method} during invocation. @return an instance of {@link MethodInvocation} encapsulating all the necessary details to invoke the {@link java.lang.reflect.Modifier#STATIC} {@link Method}. @see #newMethodInvocation(Object, Method, Object...) @see java.lang.reflect.Method
[ "Factory", "method", "used", "to", "construct", "a", "new", "instance", "of", "{", "@link", "MethodInvocation", "}", "initialized", "with", "the", "given", "{", "@link", "Method", "}", "and", "array", "of", "{", "@link", "Object", "arguments", "}", "passed", "to", "the", "{", "@link", "Method", "}", "during", "invocation", "." ]
train
https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/lang/reflect/MethodInvocation.java#L57-L59
krummas/DrizzleJDBC
src/main/java/org/drizzle/jdbc/DrizzleResultSet.java
DrizzleResultSet.getObject
public Object getObject(final String columnLabel, final Map<String, Class<?>> map) throws SQLException { """ According to the JDBC4 spec, this is only required for UDT's, and since drizzle does not support UDTs, this method ignores the map parameter <p/> Retrieves the value of the designated column in the current row of this <code>ResultSet</code> object as an <code>Object</code> in the Java programming language. If the value is an SQL <code>NULL</code>, the driver returns a Java <code>null</code>. This method uses the specified <code>Map</code> object for custom mapping if appropriate. @param columnLabel the label for the column specified with the SQL AS clause. If the SQL AS clause was not specified, then the label is the name of the column @param map a <code>java.util.Map</code> object that contains the mapping from SQL type names to classes in the Java programming language @return an <code>Object</code> representing the SQL value in the specified column @throws java.sql.SQLException if the columnLabel is not valid; if a database access error occurs or this method is called on a closed result set @throws java.sql.SQLFeatureNotSupportedException if the JDBC driver does not support this method @since 1.2 """ //TODO: implement this throw SQLExceptionMapper.getFeatureNotSupportedException("Type map getting is not supported"); }
java
public Object getObject(final String columnLabel, final Map<String, Class<?>> map) throws SQLException { //TODO: implement this throw SQLExceptionMapper.getFeatureNotSupportedException("Type map getting is not supported"); }
[ "public", "Object", "getObject", "(", "final", "String", "columnLabel", ",", "final", "Map", "<", "String", ",", "Class", "<", "?", ">", ">", "map", ")", "throws", "SQLException", "{", "//TODO: implement this", "throw", "SQLExceptionMapper", ".", "getFeatureNotSupportedException", "(", "\"Type map getting is not supported\"", ")", ";", "}" ]
According to the JDBC4 spec, this is only required for UDT's, and since drizzle does not support UDTs, this method ignores the map parameter <p/> Retrieves the value of the designated column in the current row of this <code>ResultSet</code> object as an <code>Object</code> in the Java programming language. If the value is an SQL <code>NULL</code>, the driver returns a Java <code>null</code>. This method uses the specified <code>Map</code> object for custom mapping if appropriate. @param columnLabel the label for the column specified with the SQL AS clause. If the SQL AS clause was not specified, then the label is the name of the column @param map a <code>java.util.Map</code> object that contains the mapping from SQL type names to classes in the Java programming language @return an <code>Object</code> representing the SQL value in the specified column @throws java.sql.SQLException if the columnLabel is not valid; if a database access error occurs or this method is called on a closed result set @throws java.sql.SQLFeatureNotSupportedException if the JDBC driver does not support this method @since 1.2
[ "According", "to", "the", "JDBC4", "spec", "this", "is", "only", "required", "for", "UDT", "s", "and", "since", "drizzle", "does", "not", "support", "UDTs", "this", "method", "ignores", "the", "map", "parameter", "<p", "/", ">", "Retrieves", "the", "value", "of", "the", "designated", "column", "in", "the", "current", "row", "of", "this", "<code", ">", "ResultSet<", "/", "code", ">", "object", "as", "an", "<code", ">", "Object<", "/", "code", ">", "in", "the", "Java", "programming", "language", ".", "If", "the", "value", "is", "an", "SQL", "<code", ">", "NULL<", "/", "code", ">", "the", "driver", "returns", "a", "Java", "<code", ">", "null<", "/", "code", ">", ".", "This", "method", "uses", "the", "specified", "<code", ">", "Map<", "/", "code", ">", "object", "for", "custom", "mapping", "if", "appropriate", "." ]
train
https://github.com/krummas/DrizzleJDBC/blob/716f31fd71f3cc289edf69844d8117deb86d98d6/src/main/java/org/drizzle/jdbc/DrizzleResultSet.java#L1990-L1993
kmi/iserve
iserve-semantic-discovery/src/main/java/uk/ac/open/kmi/iserve/discovery/disco/Util.java
Util.getStringValueFromRow
private static String getStringValueFromRow(QuerySolution resultRow, String variableName) { """ Given a query result from a SPARQL query, obtain the given variable value as a String @param resultRow the result from a SPARQL query @param variableName the name of the variable to obtain @return the value or null if it could not be found """ // Check the input and exit immediately if null if (resultRow == null) { return null; } String result = null; Resource res = resultRow.getResource(variableName); if (res != null && res.isLiteral()) { result = res.asLiteral().getString(); } return result; }
java
private static String getStringValueFromRow(QuerySolution resultRow, String variableName) { // Check the input and exit immediately if null if (resultRow == null) { return null; } String result = null; Resource res = resultRow.getResource(variableName); if (res != null && res.isLiteral()) { result = res.asLiteral().getString(); } return result; }
[ "private", "static", "String", "getStringValueFromRow", "(", "QuerySolution", "resultRow", ",", "String", "variableName", ")", "{", "// Check the input and exit immediately if null", "if", "(", "resultRow", "==", "null", ")", "{", "return", "null", ";", "}", "String", "result", "=", "null", ";", "Resource", "res", "=", "resultRow", ".", "getResource", "(", "variableName", ")", ";", "if", "(", "res", "!=", "null", "&&", "res", ".", "isLiteral", "(", ")", ")", "{", "result", "=", "res", ".", "asLiteral", "(", ")", ".", "getString", "(", ")", ";", "}", "return", "result", ";", "}" ]
Given a query result from a SPARQL query, obtain the given variable value as a String @param resultRow the result from a SPARQL query @param variableName the name of the variable to obtain @return the value or null if it could not be found
[ "Given", "a", "query", "result", "from", "a", "SPARQL", "query", "obtain", "the", "given", "variable", "value", "as", "a", "String" ]
train
https://github.com/kmi/iserve/blob/13e7016e64c1d5a539b838c6debf1a5cc4aefcb7/iserve-semantic-discovery/src/main/java/uk/ac/open/kmi/iserve/discovery/disco/Util.java#L85-L99
davetcc/tcMenu
tcMenuGenerator/src/main/java/com/thecoderscorner/menu/editorui/uimodel/UIMenuItem.java
UIMenuItem.safeStringFromProperty
protected String safeStringFromProperty(StringProperty stringProperty, String field, List<FieldError> errorsBuilder, int maxLen, StringFieldType fieldType) { """ Gets the string value from a text field and validates it is correct in terms of length and content. @param stringProperty the string property to get the string from @param field the field name to report errors against @param errorsBuilder the list of errors reported so far @param maxLen the maximum allowable length @param fieldType the type of field which changes the method of evaluation. @return the string once checked """ String s = stringProperty.get(); if(fieldType == StringFieldType.OPTIONAL && s.length() > maxLen) { errorsBuilder.add(new FieldError("field must be less than " + maxLen + " characters", field)); } else if(fieldType != StringFieldType.OPTIONAL && (s.length() > maxLen || s.isEmpty())) { errorsBuilder.add(new FieldError("field must not be blank and less than " + maxLen + " characters", field)); } if(fieldType == StringFieldType.VARIABLE && !s.matches("^[\\p{L}_$][\\p{L}\\p{N}_]*$")) { errorsBuilder.add(new FieldError("Function fields must use only letters, digits, and '_'", field)); } else if(!s.matches("^[\\p{L}\\p{N}\\s\\-_*%()]*$")) { errorsBuilder.add(new FieldError("Text can only contain letters, numbers, spaces and '-_()*%'", field)); } return s; }
java
protected String safeStringFromProperty(StringProperty stringProperty, String field, List<FieldError> errorsBuilder, int maxLen, StringFieldType fieldType) { String s = stringProperty.get(); if(fieldType == StringFieldType.OPTIONAL && s.length() > maxLen) { errorsBuilder.add(new FieldError("field must be less than " + maxLen + " characters", field)); } else if(fieldType != StringFieldType.OPTIONAL && (s.length() > maxLen || s.isEmpty())) { errorsBuilder.add(new FieldError("field must not be blank and less than " + maxLen + " characters", field)); } if(fieldType == StringFieldType.VARIABLE && !s.matches("^[\\p{L}_$][\\p{L}\\p{N}_]*$")) { errorsBuilder.add(new FieldError("Function fields must use only letters, digits, and '_'", field)); } else if(!s.matches("^[\\p{L}\\p{N}\\s\\-_*%()]*$")) { errorsBuilder.add(new FieldError("Text can only contain letters, numbers, spaces and '-_()*%'", field)); } return s; }
[ "protected", "String", "safeStringFromProperty", "(", "StringProperty", "stringProperty", ",", "String", "field", ",", "List", "<", "FieldError", ">", "errorsBuilder", ",", "int", "maxLen", ",", "StringFieldType", "fieldType", ")", "{", "String", "s", "=", "stringProperty", ".", "get", "(", ")", ";", "if", "(", "fieldType", "==", "StringFieldType", ".", "OPTIONAL", "&&", "s", ".", "length", "(", ")", ">", "maxLen", ")", "{", "errorsBuilder", ".", "add", "(", "new", "FieldError", "(", "\"field must be less than \"", "+", "maxLen", "+", "\" characters\"", ",", "field", ")", ")", ";", "}", "else", "if", "(", "fieldType", "!=", "StringFieldType", ".", "OPTIONAL", "&&", "(", "s", ".", "length", "(", ")", ">", "maxLen", "||", "s", ".", "isEmpty", "(", ")", ")", ")", "{", "errorsBuilder", ".", "add", "(", "new", "FieldError", "(", "\"field must not be blank and less than \"", "+", "maxLen", "+", "\" characters\"", ",", "field", ")", ")", ";", "}", "if", "(", "fieldType", "==", "StringFieldType", ".", "VARIABLE", "&&", "!", "s", ".", "matches", "(", "\"^[\\\\p{L}_$][\\\\p{L}\\\\p{N}_]*$\"", ")", ")", "{", "errorsBuilder", ".", "add", "(", "new", "FieldError", "(", "\"Function fields must use only letters, digits, and '_'\"", ",", "field", ")", ")", ";", "}", "else", "if", "(", "!", "s", ".", "matches", "(", "\"^[\\\\p{L}\\\\p{N}\\\\s\\\\-_*%()]*$\"", ")", ")", "{", "errorsBuilder", ".", "add", "(", "new", "FieldError", "(", "\"Text can only contain letters, numbers, spaces and '-_()*%'\"", ",", "field", ")", ")", ";", "}", "return", "s", ";", "}" ]
Gets the string value from a text field and validates it is correct in terms of length and content. @param stringProperty the string property to get the string from @param field the field name to report errors against @param errorsBuilder the list of errors reported so far @param maxLen the maximum allowable length @param fieldType the type of field which changes the method of evaluation. @return the string once checked
[ "Gets", "the", "string", "value", "from", "a", "text", "field", "and", "validates", "it", "is", "correct", "in", "terms", "of", "length", "and", "content", "." ]
train
https://github.com/davetcc/tcMenu/blob/61546e4b982b25ceaff384073fe9ec1fff55e64a/tcMenuGenerator/src/main/java/com/thecoderscorner/menu/editorui/uimodel/UIMenuItem.java#L195-L212
lucee/Lucee
core/src/main/java/lucee/runtime/type/sql/ClobImpl.java
ClobImpl.getSubString
@Override public String getSubString(long pos, int length) throws SQLException { """ Returns a copy of the portion of the <code>CLOB</code> value represented by this <code>CLOB</code> object that starts at position <i>position </i> and has ip to <i>length </i> consecutive characters. @param pos the position where to get the substring from @param length the length of the substring @return the substring @exception SQLException if there is an error accessing the <code>CLOB</code> """ if (length > stringData.length()) throw new SQLException("Clob contains only " + stringData.length() + " characters (asking for " + length + ")."); return stringData.substring((int) pos - 1, length); }
java
@Override public String getSubString(long pos, int length) throws SQLException { if (length > stringData.length()) throw new SQLException("Clob contains only " + stringData.length() + " characters (asking for " + length + ")."); return stringData.substring((int) pos - 1, length); }
[ "@", "Override", "public", "String", "getSubString", "(", "long", "pos", ",", "int", "length", ")", "throws", "SQLException", "{", "if", "(", "length", ">", "stringData", ".", "length", "(", ")", ")", "throw", "new", "SQLException", "(", "\"Clob contains only \"", "+", "stringData", ".", "length", "(", ")", "+", "\" characters (asking for \"", "+", "length", "+", "\").\"", ")", ";", "return", "stringData", ".", "substring", "(", "(", "int", ")", "pos", "-", "1", ",", "length", ")", ";", "}" ]
Returns a copy of the portion of the <code>CLOB</code> value represented by this <code>CLOB</code> object that starts at position <i>position </i> and has ip to <i>length </i> consecutive characters. @param pos the position where to get the substring from @param length the length of the substring @return the substring @exception SQLException if there is an error accessing the <code>CLOB</code>
[ "Returns", "a", "copy", "of", "the", "portion", "of", "the", "<code", ">", "CLOB<", "/", "code", ">", "value", "represented", "by", "this", "<code", ">", "CLOB<", "/", "code", ">", "object", "that", "starts", "at", "position", "<i", ">", "position", "<", "/", "i", ">", "and", "has", "ip", "to", "<i", ">", "length", "<", "/", "i", ">", "consecutive", "characters", "." ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/type/sql/ClobImpl.java#L148-L152