repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
partition
stringclasses
1 value
deephacks/confit
api-model/src/main/java/org/deephacks/confit/model/Bean.java
Bean.getFirstReference
public BeanId getFirstReference(final String propertyName) { List<BeanId> refrences = getReference(propertyName); if (refrences == null || refrences.size() < 1) { return null; } return refrences.get(0); }
java
public BeanId getFirstReference(final String propertyName) { List<BeanId> refrences = getReference(propertyName); if (refrences == null || refrences.size() < 1) { return null; } return refrences.get(0); }
[ "public", "BeanId", "getFirstReference", "(", "final", "String", "propertyName", ")", "{", "List", "<", "BeanId", ">", "refrences", "=", "getReference", "(", "propertyName", ")", ";", "if", "(", "refrences", "==", "null", "||", "refrences", ".", "size", "(", ")", "<", "1", ")", "{", "return", "null", ";", "}", "return", "refrences", ".", "get", "(", "0", ")", ";", "}" ]
A helper method for getting the value of single referenced property. Returns null if the refrences does not exist. @param propertyName name of the property as defined by the bean's schema. @return the value.
[ "A", "helper", "method", "for", "getting", "the", "value", "of", "single", "referenced", "property", ".", "Returns", "null", "if", "the", "refrences", "does", "not", "exist", "." ]
4e6d4ee5fed32cbc5104433e61de1bcf1b360832
https://github.com/deephacks/confit/blob/4e6d4ee5fed32cbc5104433e61de1bcf1b360832/api-model/src/main/java/org/deephacks/confit/model/Bean.java#L409-L415
train
deephacks/confit
api-provider/src/main/java/org/deephacks/confit/spi/CacheManager.java
CacheManager.lookup
public static Optional<CacheManager> lookup() { CacheManager manager = lookup.lookup(CacheManager.class); if (manager != null) { return Optional.of(manager); } else { return Optional.absent(); } }
java
public static Optional<CacheManager> lookup() { CacheManager manager = lookup.lookup(CacheManager.class); if (manager != null) { return Optional.of(manager); } else { return Optional.absent(); } }
[ "public", "static", "Optional", "<", "CacheManager", ">", "lookup", "(", ")", "{", "CacheManager", "manager", "=", "lookup", ".", "lookup", "(", "CacheManager", ".", "class", ")", ";", "if", "(", "manager", "!=", "null", ")", "{", "return", "Optional", ".", "of", "(", "manager", ")", ";", "}", "else", "{", "return", "Optional", ".", "absent", "(", ")", ";", "}", "}" ]
Lookup the most suitable CacheManager available. @return CacheManager.
[ "Lookup", "the", "most", "suitable", "CacheManager", "available", "." ]
4e6d4ee5fed32cbc5104433e61de1bcf1b360832
https://github.com/deephacks/confit/blob/4e6d4ee5fed32cbc5104433e61de1bcf1b360832/api-provider/src/main/java/org/deephacks/confit/spi/CacheManager.java#L43-L50
train
nightcode/yaranga
core/src/org/nightcode/common/net/http/AuthUtils.java
AuthUtils.percentEncode
public static String percentEncode(String source) throws AuthException { try { return URLEncoder.encode(source, "UTF-8") .replace("+", "%20") .replace("*", "%2A") .replace("%7E", "~"); } catch (UnsupportedEncodingException ex) { throw new AuthException("cannot encode value '" + source + "'", ex); } }
java
public static String percentEncode(String source) throws AuthException { try { return URLEncoder.encode(source, "UTF-8") .replace("+", "%20") .replace("*", "%2A") .replace("%7E", "~"); } catch (UnsupportedEncodingException ex) { throw new AuthException("cannot encode value '" + source + "'", ex); } }
[ "public", "static", "String", "percentEncode", "(", "String", "source", ")", "throws", "AuthException", "{", "try", "{", "return", "URLEncoder", ".", "encode", "(", "source", ",", "\"UTF-8\"", ")", ".", "replace", "(", "\"+\"", ",", "\"%20\"", ")", ".", "replace", "(", "\"*\"", ",", "\"%2A\"", ")", ".", "replace", "(", "\"%7E\"", ",", "\"~\"", ")", ";", "}", "catch", "(", "UnsupportedEncodingException", "ex", ")", "{", "throw", "new", "AuthException", "(", "\"cannot encode value '\"", "+", "source", "+", "\"'\"", ",", "ex", ")", ";", "}", "}" ]
Returns an encoded string. @see <a href="http://tools.ietf.org/html/rfc5849#section-3.6">3.6. Percent Encoding</a> @param source source string for encoding @return encoded string @throws AuthException if the named encoding is not supported
[ "Returns", "an", "encoded", "string", "." ]
f02cf8d8bcd365b6b1d55638938631a00e9ee808
https://github.com/nightcode/yaranga/blob/f02cf8d8bcd365b6b1d55638938631a00e9ee808/core/src/org/nightcode/common/net/http/AuthUtils.java#L35-L44
train
nightcode/yaranga
core/src/org/nightcode/common/net/http/AuthUtils.java
AuthUtils.percentDecode
public static String percentDecode(String source) throws AuthException { try { return URLDecoder.decode(source, "UTF-8"); } catch (java.io.UnsupportedEncodingException ex) { throw new AuthException("cannot decode value '" + source + "'", ex); } }
java
public static String percentDecode(String source) throws AuthException { try { return URLDecoder.decode(source, "UTF-8"); } catch (java.io.UnsupportedEncodingException ex) { throw new AuthException("cannot decode value '" + source + "'", ex); } }
[ "public", "static", "String", "percentDecode", "(", "String", "source", ")", "throws", "AuthException", "{", "try", "{", "return", "URLDecoder", ".", "decode", "(", "source", ",", "\"UTF-8\"", ")", ";", "}", "catch", "(", "java", ".", "io", ".", "UnsupportedEncodingException", "ex", ")", "{", "throw", "new", "AuthException", "(", "\"cannot decode value '\"", "+", "source", "+", "\"'\"", ",", "ex", ")", ";", "}", "}" ]
Returns a decoded string. @param source source string for decoding @return decoded string @throws AuthException if character encoding needs to be consulted, but named character encoding is not supported
[ "Returns", "a", "decoded", "string", "." ]
f02cf8d8bcd365b6b1d55638938631a00e9ee808
https://github.com/nightcode/yaranga/blob/f02cf8d8bcd365b6b1d55638938631a00e9ee808/core/src/org/nightcode/common/net/http/AuthUtils.java#L54-L60
train
aoindustries/ao-servlet-filter
src/main/java/com/aoindustries/servlet/filter/TempFileContext.java
TempFileContext.wrapTempFileList
public static <T> T wrapTempFileList(T original, com.aoindustries.io.TempFileList tempFileList, Wrapper<T> wrapper) { if(tempFileList != null) { return wrapper.call(original, tempFileList); } else { // Warn once synchronized(tempFileWarningLock) { if(!tempFileWarned) { if(logger.isLoggable(Level.WARNING)) { logger.log( Level.WARNING, "TempFileContext not initialized: refusing to automatically create temp files for large buffers. " + "Additional heap space may be used for large requests. " + "Please add the " + TempFileContext.class.getName() + " filter to your web.xml file.", new Throwable("Stack Trace") ); } tempFileWarned = true; } } return original; } }
java
public static <T> T wrapTempFileList(T original, com.aoindustries.io.TempFileList tempFileList, Wrapper<T> wrapper) { if(tempFileList != null) { return wrapper.call(original, tempFileList); } else { // Warn once synchronized(tempFileWarningLock) { if(!tempFileWarned) { if(logger.isLoggable(Level.WARNING)) { logger.log( Level.WARNING, "TempFileContext not initialized: refusing to automatically create temp files for large buffers. " + "Additional heap space may be used for large requests. " + "Please add the " + TempFileContext.class.getName() + " filter to your web.xml file.", new Throwable("Stack Trace") ); } tempFileWarned = true; } } return original; } }
[ "public", "static", "<", "T", ">", "T", "wrapTempFileList", "(", "T", "original", ",", "com", ".", "aoindustries", ".", "io", ".", "TempFileList", "tempFileList", ",", "Wrapper", "<", "T", ">", "wrapper", ")", "{", "if", "(", "tempFileList", "!=", "null", ")", "{", "return", "wrapper", ".", "call", "(", "original", ",", "tempFileList", ")", ";", "}", "else", "{", "// Warn once", "synchronized", "(", "tempFileWarningLock", ")", "{", "if", "(", "!", "tempFileWarned", ")", "{", "if", "(", "logger", ".", "isLoggable", "(", "Level", ".", "WARNING", ")", ")", "{", "logger", ".", "log", "(", "Level", ".", "WARNING", ",", "\"TempFileContext not initialized: refusing to automatically create temp files for large buffers. \"", "+", "\"Additional heap space may be used for large requests. \"", "+", "\"Please add the \"", "+", "TempFileContext", ".", "class", ".", "getName", "(", ")", "+", "\" filter to your web.xml file.\"", ",", "new", "Throwable", "(", "\"Stack Trace\"", ")", ")", ";", "}", "tempFileWarned", "=", "true", ";", "}", "}", "return", "original", ";", "}", "}" ]
If the TempFileContext is enabled, wraps the original object. When the context is inactive, the original object is returned unaltered. This is logged as a warning the first time not wrapped.
[ "If", "the", "TempFileContext", "is", "enabled", "wraps", "the", "original", "object", ".", "When", "the", "context", "is", "inactive", "the", "original", "object", "is", "returned", "unaltered", ".", "This", "is", "logged", "as", "a", "warning", "the", "first", "time", "not", "wrapped", "." ]
ee1fb95e36b0620949e9cb8ee863ac37fb9e4f2b
https://github.com/aoindustries/ao-servlet-filter/blob/ee1fb95e36b0620949e9cb8ee863ac37fb9e4f2b/src/main/java/com/aoindustries/servlet/filter/TempFileContext.java#L91-L112
train
crowmagnumb/s6-util
src/main/java/net/crowmagnumb/util/reflect/MethodLister.java
MethodLister.listMethods
public List<Method> listMethods( final Class<?> classObj, final String methodName ) { // // Get the array of methods for my classname. // Method[] methods = classObj.getMethods(); List<Method> methodSignatures = new ArrayList<Method>(); // // Loop round all the methods and print them out. // for ( int ii = 0; ii < methods.length; ++ii ) { if ( methods[ii].getName().equals( methodName ) ) { methodSignatures.add( methods[ii] ); } } return methodSignatures; }
java
public List<Method> listMethods( final Class<?> classObj, final String methodName ) { // // Get the array of methods for my classname. // Method[] methods = classObj.getMethods(); List<Method> methodSignatures = new ArrayList<Method>(); // // Loop round all the methods and print them out. // for ( int ii = 0; ii < methods.length; ++ii ) { if ( methods[ii].getName().equals( methodName ) ) { methodSignatures.add( methods[ii] ); } } return methodSignatures; }
[ "public", "List", "<", "Method", ">", "listMethods", "(", "final", "Class", "<", "?", ">", "classObj", ",", "final", "String", "methodName", ")", "{", "//", "// Get the array of methods for my classname.", "//", "Method", "[", "]", "methods", "=", "classObj", ".", "getMethods", "(", ")", ";", "List", "<", "Method", ">", "methodSignatures", "=", "new", "ArrayList", "<", "Method", ">", "(", ")", ";", "//", "// Loop round all the methods and print them out.", "//", "for", "(", "int", "ii", "=", "0", ";", "ii", "<", "methods", ".", "length", ";", "++", "ii", ")", "{", "if", "(", "methods", "[", "ii", "]", ".", "getName", "(", ")", ".", "equals", "(", "methodName", ")", ")", "{", "methodSignatures", ".", "add", "(", "methods", "[", "ii", "]", ")", ";", "}", "}", "return", "methodSignatures", ";", "}" ]
Given an object and a method name, list the methods that match the method name on the class..
[ "Given", "an", "object", "and", "a", "method", "name", "list", "the", "methods", "that", "match", "the", "method", "name", "on", "the", "class", ".." ]
0f9969bc0809e8a617501fa57c135e9b3984fae0
https://github.com/crowmagnumb/s6-util/blob/0f9969bc0809e8a617501fa57c135e9b3984fae0/src/main/java/net/crowmagnumb/util/reflect/MethodLister.java#L24-L46
train
maochen/NLP
CoreNLP-NLP/src/main/java/org/maochen/nlp/ml/classifier/perceptron/PerceptronClassifier.java
PerceptronClassifier.predict
private Map<Integer, Double> predict(final double[] x) { Map<Integer, Double> result = new HashMap<>(); for (int i = 0; i < model.weights.length; i++) { double y = VectorUtils.dotProduct(x, model.weights[i]); y += model.bias[i]; result.put(i, y); } return result; }
java
private Map<Integer, Double> predict(final double[] x) { Map<Integer, Double> result = new HashMap<>(); for (int i = 0; i < model.weights.length; i++) { double y = VectorUtils.dotProduct(x, model.weights[i]); y += model.bias[i]; result.put(i, y); } return result; }
[ "private", "Map", "<", "Integer", ",", "Double", ">", "predict", "(", "final", "double", "[", "]", "x", ")", "{", "Map", "<", "Integer", ",", "Double", ">", "result", "=", "new", "HashMap", "<>", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "model", ".", "weights", ".", "length", ";", "i", "++", ")", "{", "double", "y", "=", "VectorUtils", ".", "dotProduct", "(", "x", ",", "model", ".", "weights", "[", "i", "]", ")", ";", "y", "+=", "model", ".", "bias", "[", "i", "]", ";", "result", ".", "put", "(", "i", ",", "y", ")", ";", "}", "return", "result", ";", "}" ]
Key is LabelIndex.
[ "Key", "is", "LabelIndex", "." ]
38ae7b384d5295334d9efa9dc4cd901b19d9c27e
https://github.com/maochen/NLP/blob/38ae7b384d5295334d9efa9dc4cd901b19d9c27e/CoreNLP-NLP/src/main/java/org/maochen/nlp/ml/classifier/perceptron/PerceptronClassifier.java#L37-L46
train
maochen/NLP
CoreNLP-NLP/src/main/java/org/maochen/nlp/ml/classifier/perceptron/PerceptronClassifier.java
PerceptronClassifier.onlineTrain
public void onlineTrain(final double[] x, final int labelIndex) { Map<Integer, Double> result = predict(x); Map.Entry<Integer, Double> maxResult = result.entrySet().stream().max((e1, e2) -> e1.getValue().compareTo(e2.getValue())).orElse(null); if (maxResult.getKey() != labelIndex) { double e_correction_d = 1; model.weights[labelIndex] = reweight(x, model.weights[labelIndex], e_correction_d); model.bias[labelIndex] = e_correction_d; double w_correction_d = -1; model.weights[maxResult.getKey()] = reweight(x, model.weights[maxResult.getKey()], w_correction_d); model.bias[maxResult.getKey()] = w_correction_d; } if (LOG.isDebugEnabled()) { LOG.debug("New bias: " + Arrays.toString(model.bias)); LOG.debug("New weight: " + Arrays.stream(model.weights).map(Arrays::toString).reduce((wi, wii) -> wi + ", " + wii).get()); } }
java
public void onlineTrain(final double[] x, final int labelIndex) { Map<Integer, Double> result = predict(x); Map.Entry<Integer, Double> maxResult = result.entrySet().stream().max((e1, e2) -> e1.getValue().compareTo(e2.getValue())).orElse(null); if (maxResult.getKey() != labelIndex) { double e_correction_d = 1; model.weights[labelIndex] = reweight(x, model.weights[labelIndex], e_correction_d); model.bias[labelIndex] = e_correction_d; double w_correction_d = -1; model.weights[maxResult.getKey()] = reweight(x, model.weights[maxResult.getKey()], w_correction_d); model.bias[maxResult.getKey()] = w_correction_d; } if (LOG.isDebugEnabled()) { LOG.debug("New bias: " + Arrays.toString(model.bias)); LOG.debug("New weight: " + Arrays.stream(model.weights).map(Arrays::toString).reduce((wi, wii) -> wi + ", " + wii).get()); } }
[ "public", "void", "onlineTrain", "(", "final", "double", "[", "]", "x", ",", "final", "int", "labelIndex", ")", "{", "Map", "<", "Integer", ",", "Double", ">", "result", "=", "predict", "(", "x", ")", ";", "Map", ".", "Entry", "<", "Integer", ",", "Double", ">", "maxResult", "=", "result", ".", "entrySet", "(", ")", ".", "stream", "(", ")", ".", "max", "(", "(", "e1", ",", "e2", ")", "->", "e1", ".", "getValue", "(", ")", ".", "compareTo", "(", "e2", ".", "getValue", "(", ")", ")", ")", ".", "orElse", "(", "null", ")", ";", "if", "(", "maxResult", ".", "getKey", "(", ")", "!=", "labelIndex", ")", "{", "double", "e_correction_d", "=", "1", ";", "model", ".", "weights", "[", "labelIndex", "]", "=", "reweight", "(", "x", ",", "model", ".", "weights", "[", "labelIndex", "]", ",", "e_correction_d", ")", ";", "model", ".", "bias", "[", "labelIndex", "]", "=", "e_correction_d", ";", "double", "w_correction_d", "=", "-", "1", ";", "model", ".", "weights", "[", "maxResult", ".", "getKey", "(", ")", "]", "=", "reweight", "(", "x", ",", "model", ".", "weights", "[", "maxResult", ".", "getKey", "(", ")", "]", ",", "w_correction_d", ")", ";", "model", ".", "bias", "[", "maxResult", ".", "getKey", "(", ")", "]", "=", "w_correction_d", ";", "}", "if", "(", "LOG", ".", "isDebugEnabled", "(", ")", ")", "{", "LOG", ".", "debug", "(", "\"New bias: \"", "+", "Arrays", ".", "toString", "(", "model", ".", "bias", ")", ")", ";", "LOG", ".", "debug", "(", "\"New weight: \"", "+", "Arrays", ".", "stream", "(", "model", ".", "weights", ")", ".", "map", "(", "Arrays", "::", "toString", ")", ".", "reduce", "(", "(", "wi", ",", "wii", ")", "->", "wi", "+", "\", \"", "+", "wii", ")", ".", "get", "(", ")", ")", ";", "}", "}" ]
public use for doing one training sample. @param x Feature Vector @param labelIndex label's index, from PerceptronModel.LabelIndexer
[ "public", "use", "for", "doing", "one", "training", "sample", "." ]
38ae7b384d5295334d9efa9dc4cd901b19d9c27e
https://github.com/maochen/NLP/blob/38ae7b384d5295334d9efa9dc4cd901b19d9c27e/CoreNLP-NLP/src/main/java/org/maochen/nlp/ml/classifier/perceptron/PerceptronClassifier.java#L65-L83
train
maochen/NLP
CoreNLP-NLP/src/main/java/org/maochen/nlp/ml/classifier/perceptron/PerceptronClassifier.java
PerceptronClassifier.predict
@Override public Map<String, Double> predict(Tuple predict) { Map<Integer, Double> indexResult = predict(predict.vector.getVector()); return indexResult.entrySet().stream() .map(e -> new ImmutablePair<>(model.labelIndexer.getLabel(e.getKey()), VectorUtils.sigmoid.apply(e.getValue()))) // Only do sigmoid here! .collect(Collectors.toMap(ImmutablePair::getLeft, ImmutablePair::getRight)); }
java
@Override public Map<String, Double> predict(Tuple predict) { Map<Integer, Double> indexResult = predict(predict.vector.getVector()); return indexResult.entrySet().stream() .map(e -> new ImmutablePair<>(model.labelIndexer.getLabel(e.getKey()), VectorUtils.sigmoid.apply(e.getValue()))) // Only do sigmoid here! .collect(Collectors.toMap(ImmutablePair::getLeft, ImmutablePair::getRight)); }
[ "@", "Override", "public", "Map", "<", "String", ",", "Double", ">", "predict", "(", "Tuple", "predict", ")", "{", "Map", "<", "Integer", ",", "Double", ">", "indexResult", "=", "predict", "(", "predict", ".", "vector", ".", "getVector", "(", ")", ")", ";", "return", "indexResult", ".", "entrySet", "(", ")", ".", "stream", "(", ")", ".", "map", "(", "e", "->", "new", "ImmutablePair", "<>", "(", "model", ".", "labelIndexer", ".", "getLabel", "(", "e", ".", "getKey", "(", ")", ")", ",", "VectorUtils", ".", "sigmoid", ".", "apply", "(", "e", ".", "getValue", "(", ")", ")", ")", ")", "// Only do sigmoid here!", ".", "collect", "(", "Collectors", ".", "toMap", "(", "ImmutablePair", "::", "getLeft", ",", "ImmutablePair", "::", "getRight", ")", ")", ";", "}" ]
Do a prediction. @param predict predict tuple. @return Map's key is the actual label, Value is probability, the probability is random depends on the order of training sample.
[ "Do", "a", "prediction", "." ]
38ae7b384d5295334d9efa9dc4cd901b19d9c27e
https://github.com/maochen/NLP/blob/38ae7b384d5295334d9efa9dc4cd901b19d9c27e/CoreNLP-NLP/src/main/java/org/maochen/nlp/ml/classifier/perceptron/PerceptronClassifier.java#L115-L121
train
aoindustries/ao-servlet-filter
src/main/java/com/aoindustries/servlet/filter/TrimFilterWriter.java
TrimFilterWriter.isTrimEnabled
private boolean isTrimEnabled() { String contentType = response.getContentType(); // If the contentType is the same string (by identity), return the previously determined value. // This assumes the same string instance is returned by the response when content type not changed between calls. if(contentType!=isTrimEnabledCacheContentType) { isTrimEnabledCacheResult = contentType==null || contentType.equals("application/xhtml+xml") || contentType.startsWith("application/xhtml+xml;") || contentType.equals("text/html") || contentType.startsWith("text/html;") || contentType.equals("application/xml") || contentType.startsWith("application/xml;") || contentType.equals("text/xml") || contentType.startsWith("text/xml;") ; isTrimEnabledCacheContentType = contentType; } return isTrimEnabledCacheResult; }
java
private boolean isTrimEnabled() { String contentType = response.getContentType(); // If the contentType is the same string (by identity), return the previously determined value. // This assumes the same string instance is returned by the response when content type not changed between calls. if(contentType!=isTrimEnabledCacheContentType) { isTrimEnabledCacheResult = contentType==null || contentType.equals("application/xhtml+xml") || contentType.startsWith("application/xhtml+xml;") || contentType.equals("text/html") || contentType.startsWith("text/html;") || contentType.equals("application/xml") || contentType.startsWith("application/xml;") || contentType.equals("text/xml") || contentType.startsWith("text/xml;") ; isTrimEnabledCacheContentType = contentType; } return isTrimEnabledCacheResult; }
[ "private", "boolean", "isTrimEnabled", "(", ")", "{", "String", "contentType", "=", "response", ".", "getContentType", "(", ")", ";", "// If the contentType is the same string (by identity), return the previously determined value.", "// This assumes the same string instance is returned by the response when content type not changed between calls.", "if", "(", "contentType", "!=", "isTrimEnabledCacheContentType", ")", "{", "isTrimEnabledCacheResult", "=", "contentType", "==", "null", "||", "contentType", ".", "equals", "(", "\"application/xhtml+xml\"", ")", "||", "contentType", ".", "startsWith", "(", "\"application/xhtml+xml;\"", ")", "||", "contentType", ".", "equals", "(", "\"text/html\"", ")", "||", "contentType", ".", "startsWith", "(", "\"text/html;\"", ")", "||", "contentType", ".", "equals", "(", "\"application/xml\"", ")", "||", "contentType", ".", "startsWith", "(", "\"application/xml;\"", ")", "||", "contentType", ".", "equals", "(", "\"text/xml\"", ")", "||", "contentType", ".", "startsWith", "(", "\"text/xml;\"", ")", ";", "isTrimEnabledCacheContentType", "=", "contentType", ";", "}", "return", "isTrimEnabledCacheResult", ";", "}" ]
Determines if trimming is enabled based on the output content type. @see TrimFilterOutputStream#isTrimEnabled() for same method implemented
[ "Determines", "if", "trimming", "is", "enabled", "based", "on", "the", "output", "content", "type", "." ]
ee1fb95e36b0620949e9cb8ee863ac37fb9e4f2b
https://github.com/aoindustries/ao-servlet-filter/blob/ee1fb95e36b0620949e9cb8ee863ac37fb9e4f2b/src/main/java/com/aoindustries/servlet/filter/TrimFilterWriter.java#L69-L88
train
aoindustries/ao-servlet-filter
src/main/java/com/aoindustries/servlet/filter/TrimFilterOutputStream.java
TrimFilterOutputStream.processChar
private boolean processChar(char c) { if(inTextArea) { if( c==TrimFilterWriter.textarea_close[readCharMatchCount] || c==TrimFilterWriter.TEXTAREA_CLOSE[readCharMatchCount] ) { readCharMatchCount++; if(readCharMatchCount>=TrimFilterWriter.textarea_close.length) { inTextArea=false; readCharMatchCount=0; } } else { readCharMatchCount=0; } return true; } else if(inPre) { if( c==TrimFilterWriter.pre_close[preReadCharMatchCount] || c==TrimFilterWriter.PRE_CLOSE[preReadCharMatchCount] ) { preReadCharMatchCount++; if(preReadCharMatchCount>=TrimFilterWriter.pre_close.length) { inPre=false; preReadCharMatchCount=0; } } else { preReadCharMatchCount=0; } return true; } else { if(c=='\r') { readCharMatchCount = 0; preReadCharMatchCount = 0; // Carriage return only output when no longer at the beginning of the line return !atLineStart; } else if(c=='\n') { readCharMatchCount = 0; preReadCharMatchCount = 0; // Newline only output when no longer at the beginning of the line if(!atLineStart) { atLineStart = true; return true; } else { return false; } } else if(c==' ' || c=='\t') { readCharMatchCount = 0; preReadCharMatchCount = 0; // Space and tab only output when no longer at the beginning of the line return !atLineStart; } else { atLineStart = false; if( c==TrimFilterWriter.textarea[readCharMatchCount] || c==TrimFilterWriter.TEXTAREA[readCharMatchCount] ) { readCharMatchCount++; if(readCharMatchCount>=TrimFilterWriter.textarea.length) { inTextArea=true; readCharMatchCount=0; } } else { readCharMatchCount=0; } if( c==TrimFilterWriter.pre[preReadCharMatchCount] || c==TrimFilterWriter.PRE[preReadCharMatchCount] ) { preReadCharMatchCount++; if(preReadCharMatchCount>=TrimFilterWriter.pre.length) { inPre=true; preReadCharMatchCount=0; } } else { preReadCharMatchCount=0; } return true; } } }
java
private boolean processChar(char c) { if(inTextArea) { if( c==TrimFilterWriter.textarea_close[readCharMatchCount] || c==TrimFilterWriter.TEXTAREA_CLOSE[readCharMatchCount] ) { readCharMatchCount++; if(readCharMatchCount>=TrimFilterWriter.textarea_close.length) { inTextArea=false; readCharMatchCount=0; } } else { readCharMatchCount=0; } return true; } else if(inPre) { if( c==TrimFilterWriter.pre_close[preReadCharMatchCount] || c==TrimFilterWriter.PRE_CLOSE[preReadCharMatchCount] ) { preReadCharMatchCount++; if(preReadCharMatchCount>=TrimFilterWriter.pre_close.length) { inPre=false; preReadCharMatchCount=0; } } else { preReadCharMatchCount=0; } return true; } else { if(c=='\r') { readCharMatchCount = 0; preReadCharMatchCount = 0; // Carriage return only output when no longer at the beginning of the line return !atLineStart; } else if(c=='\n') { readCharMatchCount = 0; preReadCharMatchCount = 0; // Newline only output when no longer at the beginning of the line if(!atLineStart) { atLineStart = true; return true; } else { return false; } } else if(c==' ' || c=='\t') { readCharMatchCount = 0; preReadCharMatchCount = 0; // Space and tab only output when no longer at the beginning of the line return !atLineStart; } else { atLineStart = false; if( c==TrimFilterWriter.textarea[readCharMatchCount] || c==TrimFilterWriter.TEXTAREA[readCharMatchCount] ) { readCharMatchCount++; if(readCharMatchCount>=TrimFilterWriter.textarea.length) { inTextArea=true; readCharMatchCount=0; } } else { readCharMatchCount=0; } if( c==TrimFilterWriter.pre[preReadCharMatchCount] || c==TrimFilterWriter.PRE[preReadCharMatchCount] ) { preReadCharMatchCount++; if(preReadCharMatchCount>=TrimFilterWriter.pre.length) { inPre=true; preReadCharMatchCount=0; } } else { preReadCharMatchCount=0; } return true; } } }
[ "private", "boolean", "processChar", "(", "char", "c", ")", "{", "if", "(", "inTextArea", ")", "{", "if", "(", "c", "==", "TrimFilterWriter", ".", "textarea_close", "[", "readCharMatchCount", "]", "||", "c", "==", "TrimFilterWriter", ".", "TEXTAREA_CLOSE", "[", "readCharMatchCount", "]", ")", "{", "readCharMatchCount", "++", ";", "if", "(", "readCharMatchCount", ">=", "TrimFilterWriter", ".", "textarea_close", ".", "length", ")", "{", "inTextArea", "=", "false", ";", "readCharMatchCount", "=", "0", ";", "}", "}", "else", "{", "readCharMatchCount", "=", "0", ";", "}", "return", "true", ";", "}", "else", "if", "(", "inPre", ")", "{", "if", "(", "c", "==", "TrimFilterWriter", ".", "pre_close", "[", "preReadCharMatchCount", "]", "||", "c", "==", "TrimFilterWriter", ".", "PRE_CLOSE", "[", "preReadCharMatchCount", "]", ")", "{", "preReadCharMatchCount", "++", ";", "if", "(", "preReadCharMatchCount", ">=", "TrimFilterWriter", ".", "pre_close", ".", "length", ")", "{", "inPre", "=", "false", ";", "preReadCharMatchCount", "=", "0", ";", "}", "}", "else", "{", "preReadCharMatchCount", "=", "0", ";", "}", "return", "true", ";", "}", "else", "{", "if", "(", "c", "==", "'", "'", ")", "{", "readCharMatchCount", "=", "0", ";", "preReadCharMatchCount", "=", "0", ";", "// Carriage return only output when no longer at the beginning of the line", "return", "!", "atLineStart", ";", "}", "else", "if", "(", "c", "==", "'", "'", ")", "{", "readCharMatchCount", "=", "0", ";", "preReadCharMatchCount", "=", "0", ";", "// Newline only output when no longer at the beginning of the line", "if", "(", "!", "atLineStart", ")", "{", "atLineStart", "=", "true", ";", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}", "else", "if", "(", "c", "==", "'", "'", "||", "c", "==", "'", "'", ")", "{", "readCharMatchCount", "=", "0", ";", "preReadCharMatchCount", "=", "0", ";", "// Space and tab only output when no longer at the beginning of the line", "return", "!", "atLineStart", ";", "}", "else", "{", "atLineStart", "=", "false", ";", "if", "(", "c", "==", "TrimFilterWriter", ".", "textarea", "[", "readCharMatchCount", "]", "||", "c", "==", "TrimFilterWriter", ".", "TEXTAREA", "[", "readCharMatchCount", "]", ")", "{", "readCharMatchCount", "++", ";", "if", "(", "readCharMatchCount", ">=", "TrimFilterWriter", ".", "textarea", ".", "length", ")", "{", "inTextArea", "=", "true", ";", "readCharMatchCount", "=", "0", ";", "}", "}", "else", "{", "readCharMatchCount", "=", "0", ";", "}", "if", "(", "c", "==", "TrimFilterWriter", ".", "pre", "[", "preReadCharMatchCount", "]", "||", "c", "==", "TrimFilterWriter", ".", "PRE", "[", "preReadCharMatchCount", "]", ")", "{", "preReadCharMatchCount", "++", ";", "if", "(", "preReadCharMatchCount", ">=", "TrimFilterWriter", ".", "pre", ".", "length", ")", "{", "inPre", "=", "true", ";", "preReadCharMatchCount", "=", "0", ";", "}", "}", "else", "{", "preReadCharMatchCount", "=", "0", ";", "}", "return", "true", ";", "}", "}", "}" ]
Processes one character and returns true if the character should be outputted.
[ "Processes", "one", "character", "and", "returns", "true", "if", "the", "character", "should", "be", "outputted", "." ]
ee1fb95e36b0620949e9cb8ee863ac37fb9e4f2b
https://github.com/aoindustries/ao-servlet-filter/blob/ee1fb95e36b0620949e9cb8ee863ac37fb9e4f2b/src/main/java/com/aoindustries/servlet/filter/TrimFilterOutputStream.java#L116-L195
train
crowmagnumb/s6-util
src/main/java/net/crowmagnumb/util/bits/AtomicBitflags.java
AtomicBitflags.set
public int set( final int flags ) { for (;;) { int current = _flags.get(); int newValue = current | flags; if ( _flags.compareAndSet( current, newValue ) ) { return current; } } }
java
public int set( final int flags ) { for (;;) { int current = _flags.get(); int newValue = current | flags; if ( _flags.compareAndSet( current, newValue ) ) { return current; } } }
[ "public", "int", "set", "(", "final", "int", "flags", ")", "{", "for", "(", ";", ";", ")", "{", "int", "current", "=", "_flags", ".", "get", "(", ")", ";", "int", "newValue", "=", "current", "|", "flags", ";", "if", "(", "_flags", ".", "compareAndSet", "(", "current", ",", "newValue", ")", ")", "{", "return", "current", ";", "}", "}", "}" ]
Atomically add the given flags to the current set @param flags to add @return the previous value
[ "Atomically", "add", "the", "given", "flags", "to", "the", "current", "set" ]
0f9969bc0809e8a617501fa57c135e9b3984fae0
https://github.com/crowmagnumb/s6-util/blob/0f9969bc0809e8a617501fa57c135e9b3984fae0/src/main/java/net/crowmagnumb/util/bits/AtomicBitflags.java#L21-L33
train
crowmagnumb/s6-util
src/main/java/net/crowmagnumb/util/bits/AtomicBitflags.java
AtomicBitflags.unset
public int unset( final int flags ) { for (;;) { int current = _flags.get(); int newValue = current & ~flags; if ( _flags.compareAndSet( current, newValue ) ) { return current; } } }
java
public int unset( final int flags ) { for (;;) { int current = _flags.get(); int newValue = current & ~flags; if ( _flags.compareAndSet( current, newValue ) ) { return current; } } }
[ "public", "int", "unset", "(", "final", "int", "flags", ")", "{", "for", "(", ";", ";", ")", "{", "int", "current", "=", "_flags", ".", "get", "(", ")", ";", "int", "newValue", "=", "current", "&", "~", "flags", ";", "if", "(", "_flags", ".", "compareAndSet", "(", "current", ",", "newValue", ")", ")", "{", "return", "current", ";", "}", "}", "}" ]
Atomically remove the given flags from the current set @param flags to unset @return the previous value
[ "Atomically", "remove", "the", "given", "flags", "from", "the", "current", "set" ]
0f9969bc0809e8a617501fa57c135e9b3984fae0
https://github.com/crowmagnumb/s6-util/blob/0f9969bc0809e8a617501fa57c135e9b3984fae0/src/main/java/net/crowmagnumb/util/bits/AtomicBitflags.java#L42-L54
train
crowmagnumb/s6-util
src/main/java/net/crowmagnumb/util/bits/AtomicBitflags.java
AtomicBitflags.change
public int change( final int add, final int remove ) { for (;;) { int current = _flags.get(); int newValue = ( current | add ) & ~remove; if ( _flags.compareAndSet( current, newValue ) ) { return current; } } }
java
public int change( final int add, final int remove ) { for (;;) { int current = _flags.get(); int newValue = ( current | add ) & ~remove; if ( _flags.compareAndSet( current, newValue ) ) { return current; } } }
[ "public", "int", "change", "(", "final", "int", "add", ",", "final", "int", "remove", ")", "{", "for", "(", ";", ";", ")", "{", "int", "current", "=", "_flags", ".", "get", "(", ")", ";", "int", "newValue", "=", "(", "current", "|", "add", ")", "&", "~", "remove", ";", "if", "(", "_flags", ".", "compareAndSet", "(", "current", ",", "newValue", ")", ")", "{", "return", "current", ";", "}", "}", "}" ]
Atomically add and remove the given flags from the current set @param add the flags to add @param remove the flags to remove @return the previous value
[ "Atomically", "add", "and", "remove", "the", "given", "flags", "from", "the", "current", "set" ]
0f9969bc0809e8a617501fa57c135e9b3984fae0
https://github.com/crowmagnumb/s6-util/blob/0f9969bc0809e8a617501fa57c135e9b3984fae0/src/main/java/net/crowmagnumb/util/bits/AtomicBitflags.java#L64-L77
train
liuyukuai/commons
commons-core/src/main/java/com/itxiaoer/commons/core/page/Response.java
Response.message
public static <E> String message(Response<E> response) { return Optional.ofNullable(response).map(Response::getMessage).orElse(StringUtils.EMPTY); }
java
public static <E> String message(Response<E> response) { return Optional.ofNullable(response).map(Response::getMessage).orElse(StringUtils.EMPTY); }
[ "public", "static", "<", "E", ">", "String", "message", "(", "Response", "<", "E", ">", "response", ")", "{", "return", "Optional", ".", "ofNullable", "(", "response", ")", ".", "map", "(", "Response", "::", "getMessage", ")", ".", "orElse", "(", "StringUtils", ".", "EMPTY", ")", ";", "}" ]
get response message @param response response @param <E> e @return message
[ "get", "response", "message" ]
ba67eddb542446b12f419f1866dbaa82e47fbf35
https://github.com/liuyukuai/commons/blob/ba67eddb542446b12f419f1866dbaa82e47fbf35/commons-core/src/main/java/com/itxiaoer/commons/core/page/Response.java#L138-L140
train
maochen/NLP
CoreNLP-NLP/src/main/java/org/maochen/nlp/parser/stanford/util/StanfordParserUtils.java
StanfordParserUtils.convertTreeBankToCoNLLX
public static DTree convertTreeBankToCoNLLX(final String constituentTree) { Tree tree = Tree.valueOf(constituentTree); SemanticHeadFinder headFinder = new SemanticHeadFinder(false); // keep copula verbs as head Collection<TypedDependency> dependencies = new EnglishGrammaticalStructure(tree, string -> true, headFinder).typedDependencies(); List<CoreLabel> tokens = tree.taggedLabeledYield(); StanfordParser.tagLemma(tokens); return StanfordTreeBuilder.generate(tokens, dependencies, null); }
java
public static DTree convertTreeBankToCoNLLX(final String constituentTree) { Tree tree = Tree.valueOf(constituentTree); SemanticHeadFinder headFinder = new SemanticHeadFinder(false); // keep copula verbs as head Collection<TypedDependency> dependencies = new EnglishGrammaticalStructure(tree, string -> true, headFinder).typedDependencies(); List<CoreLabel> tokens = tree.taggedLabeledYield(); StanfordParser.tagLemma(tokens); return StanfordTreeBuilder.generate(tokens, dependencies, null); }
[ "public", "static", "DTree", "convertTreeBankToCoNLLX", "(", "final", "String", "constituentTree", ")", "{", "Tree", "tree", "=", "Tree", ".", "valueOf", "(", "constituentTree", ")", ";", "SemanticHeadFinder", "headFinder", "=", "new", "SemanticHeadFinder", "(", "false", ")", ";", "// keep copula verbs as head", "Collection", "<", "TypedDependency", ">", "dependencies", "=", "new", "EnglishGrammaticalStructure", "(", "tree", ",", "string", "->", "true", ",", "headFinder", ")", ".", "typedDependencies", "(", ")", ";", "List", "<", "CoreLabel", ">", "tokens", "=", "tree", ".", "taggedLabeledYield", "(", ")", ";", "StanfordParser", ".", "tagLemma", "(", "tokens", ")", ";", "return", "StanfordTreeBuilder", ".", "generate", "(", "tokens", ",", "dependencies", ",", "null", ")", ";", "}" ]
Parser for tag Lemma
[ "Parser", "for", "tag", "Lemma" ]
38ae7b384d5295334d9efa9dc4cd901b19d9c27e
https://github.com/maochen/NLP/blob/38ae7b384d5295334d9efa9dc4cd901b19d9c27e/CoreNLP-NLP/src/main/java/org/maochen/nlp/parser/stanford/util/StanfordParserUtils.java#L163-L172
train
aoindustries/ao-servlet-filter
src/main/java/com/aoindustries/servlet/filter/LocaleFilter.java
LocaleFilter.addLocale
private String addLocale(Locale locale, String url, String encodedParamName, String encoding) { // Split the anchor int poundPos = url.lastIndexOf('#'); String beforeAnchor; String anchor; if(poundPos==-1) { beforeAnchor = url; anchor = null; } else { anchor = url.substring(poundPos); beforeAnchor = url.substring(0, poundPos); } // Only add for non-excluded file types if(isLocalizedPath(beforeAnchor)) { int questionPos = beforeAnchor.lastIndexOf('?'); // Only rewrite a URL that does not already contain a paramName parameter. if( questionPos == -1 || ( !beforeAnchor.startsWith("?"+encodedParamName+"=", questionPos) && beforeAnchor.indexOf("&"+encodedParamName+"=", questionPos + 1) == -1 ) ) { try { beforeAnchor += (questionPos == -1 ? '?' : '&') + encodedParamName + '=' + URLEncoder.encode(toLocaleString(locale), encoding); } catch(UnsupportedEncodingException e) { // Should never happen with standard supported encoding throw new WrappedException(e); } } return (anchor != null) ? (beforeAnchor + anchor) : beforeAnchor ; } else { // Unmodified return url; } }
java
private String addLocale(Locale locale, String url, String encodedParamName, String encoding) { // Split the anchor int poundPos = url.lastIndexOf('#'); String beforeAnchor; String anchor; if(poundPos==-1) { beforeAnchor = url; anchor = null; } else { anchor = url.substring(poundPos); beforeAnchor = url.substring(0, poundPos); } // Only add for non-excluded file types if(isLocalizedPath(beforeAnchor)) { int questionPos = beforeAnchor.lastIndexOf('?'); // Only rewrite a URL that does not already contain a paramName parameter. if( questionPos == -1 || ( !beforeAnchor.startsWith("?"+encodedParamName+"=", questionPos) && beforeAnchor.indexOf("&"+encodedParamName+"=", questionPos + 1) == -1 ) ) { try { beforeAnchor += (questionPos == -1 ? '?' : '&') + encodedParamName + '=' + URLEncoder.encode(toLocaleString(locale), encoding); } catch(UnsupportedEncodingException e) { // Should never happen with standard supported encoding throw new WrappedException(e); } } return (anchor != null) ? (beforeAnchor + anchor) : beforeAnchor ; } else { // Unmodified return url; } }
[ "private", "String", "addLocale", "(", "Locale", "locale", ",", "String", "url", ",", "String", "encodedParamName", ",", "String", "encoding", ")", "{", "// Split the anchor", "int", "poundPos", "=", "url", ".", "lastIndexOf", "(", "'", "'", ")", ";", "String", "beforeAnchor", ";", "String", "anchor", ";", "if", "(", "poundPos", "==", "-", "1", ")", "{", "beforeAnchor", "=", "url", ";", "anchor", "=", "null", ";", "}", "else", "{", "anchor", "=", "url", ".", "substring", "(", "poundPos", ")", ";", "beforeAnchor", "=", "url", ".", "substring", "(", "0", ",", "poundPos", ")", ";", "}", "// Only add for non-excluded file types", "if", "(", "isLocalizedPath", "(", "beforeAnchor", ")", ")", "{", "int", "questionPos", "=", "beforeAnchor", ".", "lastIndexOf", "(", "'", "'", ")", ";", "// Only rewrite a URL that does not already contain a paramName parameter.", "if", "(", "questionPos", "==", "-", "1", "||", "(", "!", "beforeAnchor", ".", "startsWith", "(", "\"?\"", "+", "encodedParamName", "+", "\"=\"", ",", "questionPos", ")", "&&", "beforeAnchor", ".", "indexOf", "(", "\"&\"", "+", "encodedParamName", "+", "\"=\"", ",", "questionPos", "+", "1", ")", "==", "-", "1", ")", ")", "{", "try", "{", "beforeAnchor", "+=", "(", "questionPos", "==", "-", "1", "?", "'", "'", ":", "'", "'", ")", "+", "encodedParamName", "+", "'", "'", "+", "URLEncoder", ".", "encode", "(", "toLocaleString", "(", "locale", ")", ",", "encoding", ")", ";", "}", "catch", "(", "UnsupportedEncodingException", "e", ")", "{", "// Should never happen with standard supported encoding", "throw", "new", "WrappedException", "(", "e", ")", ";", "}", "}", "return", "(", "anchor", "!=", "null", ")", "?", "(", "beforeAnchor", "+", "anchor", ")", ":", "beforeAnchor", ";", "}", "else", "{", "// Unmodified", "return", "url", ";", "}", "}" ]
Adds the current locale as a parameter to the URL.
[ "Adds", "the", "current", "locale", "as", "a", "parameter", "to", "the", "URL", "." ]
ee1fb95e36b0620949e9cb8ee863ac37fb9e4f2b
https://github.com/aoindustries/ao-servlet-filter/blob/ee1fb95e36b0620949e9cb8ee863ac37fb9e4f2b/src/main/java/com/aoindustries/servlet/filter/LocaleFilter.java#L99-L138
train
aoindustries/ao-servlet-filter
src/main/java/com/aoindustries/servlet/filter/LocaleFilter.java
LocaleFilter.getEnabledLocales
public static Map<String,Locale> getEnabledLocales(ServletRequest request) { @SuppressWarnings("unchecked") Map<String,Locale> enabledLocales = (Map<String,Locale>)request.getAttribute(ENABLED_LOCALES_REQUEST_ATTRIBUTE_KEY); if(enabledLocales==null) throw new IllegalStateException("Not in request filtered by LocaleFilter, unable to get enabled locales."); return enabledLocales; }
java
public static Map<String,Locale> getEnabledLocales(ServletRequest request) { @SuppressWarnings("unchecked") Map<String,Locale> enabledLocales = (Map<String,Locale>)request.getAttribute(ENABLED_LOCALES_REQUEST_ATTRIBUTE_KEY); if(enabledLocales==null) throw new IllegalStateException("Not in request filtered by LocaleFilter, unable to get enabled locales."); return enabledLocales; }
[ "public", "static", "Map", "<", "String", ",", "Locale", ">", "getEnabledLocales", "(", "ServletRequest", "request", ")", "{", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "Map", "<", "String", ",", "Locale", ">", "enabledLocales", "=", "(", "Map", "<", "String", ",", "Locale", ">", ")", "request", ".", "getAttribute", "(", "ENABLED_LOCALES_REQUEST_ATTRIBUTE_KEY", ")", ";", "if", "(", "enabledLocales", "==", "null", ")", "throw", "new", "IllegalStateException", "(", "\"Not in request filtered by LocaleFilter, unable to get enabled locales.\"", ")", ";", "return", "enabledLocales", ";", "}" ]
Gets the set of enabled locales for the provided request. This must be called from a request that has already been filtered through LocaleFilter. When container's default locale is used, will return an empty map. @return The mapping from localeString to locale
[ "Gets", "the", "set", "of", "enabled", "locales", "for", "the", "provided", "request", ".", "This", "must", "be", "called", "from", "a", "request", "that", "has", "already", "been", "filtered", "through", "LocaleFilter", ".", "When", "container", "s", "default", "locale", "is", "used", "will", "return", "an", "empty", "map", "." ]
ee1fb95e36b0620949e9cb8ee863ac37fb9e4f2b
https://github.com/aoindustries/ao-servlet-filter/blob/ee1fb95e36b0620949e9cb8ee863ac37fb9e4f2b/src/main/java/com/aoindustries/servlet/filter/LocaleFilter.java#L154-L159
train
aoindustries/ao-servlet-filter
src/main/java/com/aoindustries/servlet/filter/LocaleFilter.java
LocaleFilter.isLocalizedPath
protected boolean isLocalizedPath(String url) { int questionPos = url.lastIndexOf('?'); String lowerPath = (questionPos==-1 ? url : url.substring(0, questionPos)).toLowerCase(Locale.ROOT); return // Matches SessionResponseWrapper // Matches NoSessionFilter !lowerPath.endsWith(".bmp") && !lowerPath.endsWith(".css") && !lowerPath.endsWith(".exe") && !lowerPath.endsWith(".gif") && !lowerPath.endsWith(".ico") && !lowerPath.endsWith(".jpeg") && !lowerPath.endsWith(".jpg") && !lowerPath.endsWith(".js") && !lowerPath.endsWith(".png") && !lowerPath.endsWith(".svg") && !lowerPath.endsWith(".txt") && !lowerPath.endsWith(".zip") ; }
java
protected boolean isLocalizedPath(String url) { int questionPos = url.lastIndexOf('?'); String lowerPath = (questionPos==-1 ? url : url.substring(0, questionPos)).toLowerCase(Locale.ROOT); return // Matches SessionResponseWrapper // Matches NoSessionFilter !lowerPath.endsWith(".bmp") && !lowerPath.endsWith(".css") && !lowerPath.endsWith(".exe") && !lowerPath.endsWith(".gif") && !lowerPath.endsWith(".ico") && !lowerPath.endsWith(".jpeg") && !lowerPath.endsWith(".jpg") && !lowerPath.endsWith(".js") && !lowerPath.endsWith(".png") && !lowerPath.endsWith(".svg") && !lowerPath.endsWith(".txt") && !lowerPath.endsWith(".zip") ; }
[ "protected", "boolean", "isLocalizedPath", "(", "String", "url", ")", "{", "int", "questionPos", "=", "url", ".", "lastIndexOf", "(", "'", "'", ")", ";", "String", "lowerPath", "=", "(", "questionPos", "==", "-", "1", "?", "url", ":", "url", ".", "substring", "(", "0", ",", "questionPos", ")", ")", ".", "toLowerCase", "(", "Locale", ".", "ROOT", ")", ";", "return", "// Matches SessionResponseWrapper", "// Matches NoSessionFilter", "!", "lowerPath", ".", "endsWith", "(", "\".bmp\"", ")", "&&", "!", "lowerPath", ".", "endsWith", "(", "\".css\"", ")", "&&", "!", "lowerPath", ".", "endsWith", "(", "\".exe\"", ")", "&&", "!", "lowerPath", ".", "endsWith", "(", "\".gif\"", ")", "&&", "!", "lowerPath", ".", "endsWith", "(", "\".ico\"", ")", "&&", "!", "lowerPath", ".", "endsWith", "(", "\".jpeg\"", ")", "&&", "!", "lowerPath", ".", "endsWith", "(", "\".jpg\"", ")", "&&", "!", "lowerPath", ".", "endsWith", "(", "\".js\"", ")", "&&", "!", "lowerPath", ".", "endsWith", "(", "\".png\"", ")", "&&", "!", "lowerPath", ".", "endsWith", "(", "\".svg\"", ")", "&&", "!", "lowerPath", ".", "endsWith", "(", "\".txt\"", ")", "&&", "!", "lowerPath", ".", "endsWith", "(", "\".zip\"", ")", ";", "}" ]
Checks if the locale parameter should be added to the given URL. This default implementation will cause the parameter to be added to any URL that is not one of the following (case-insensitive): <ul> <li>*.css[?params]</li> <li>*.exe[?params]</li> <li>*.gif[?params]</li> <li>*.ico[?params]</li> <li>*.jpeg[?params]</li> <li>*.jpg[?params]</li> <li>*.js[?params]</li> <li>*.png[?params]</li> <li>*.txt[?params]</li> <li>*.zip[?params]</li> </ul>
[ "Checks", "if", "the", "locale", "parameter", "should", "be", "added", "to", "the", "given", "URL", "." ]
ee1fb95e36b0620949e9cb8ee863ac37fb9e4f2b
https://github.com/aoindustries/ao-servlet-filter/blob/ee1fb95e36b0620949e9cb8ee863ac37fb9e4f2b/src/main/java/com/aoindustries/servlet/filter/LocaleFilter.java#L468-L487
train
aoindustries/ao-servlet-filter
src/main/java/com/aoindustries/servlet/filter/LocaleFilter.java
LocaleFilter.toLocaleString
protected String toLocaleString(Locale locale) { String language = locale.getLanguage(); if(language.isEmpty()) return ""; String country = locale.getCountry(); if(country.isEmpty()) return language; String variant = locale.getVariant(); if(variant.isEmpty()) { return language + '-' + country; } else { return language + '-' + country + '-' + variant; } }
java
protected String toLocaleString(Locale locale) { String language = locale.getLanguage(); if(language.isEmpty()) return ""; String country = locale.getCountry(); if(country.isEmpty()) return language; String variant = locale.getVariant(); if(variant.isEmpty()) { return language + '-' + country; } else { return language + '-' + country + '-' + variant; } }
[ "protected", "String", "toLocaleString", "(", "Locale", "locale", ")", "{", "String", "language", "=", "locale", ".", "getLanguage", "(", ")", ";", "if", "(", "language", ".", "isEmpty", "(", ")", ")", "return", "\"\"", ";", "String", "country", "=", "locale", ".", "getCountry", "(", ")", ";", "if", "(", "country", ".", "isEmpty", "(", ")", ")", "return", "language", ";", "String", "variant", "=", "locale", ".", "getVariant", "(", ")", ";", "if", "(", "variant", ".", "isEmpty", "(", ")", ")", "{", "return", "language", "+", "'", "'", "+", "country", ";", "}", "else", "{", "return", "language", "+", "'", "'", "+", "country", "+", "'", "'", "+", "variant", ";", "}", "}" ]
Gets a string representation of the given locale. This default implementation only supports language, country, and variant. Country will only be added when language present. Variant will only be added when both language and country are present.
[ "Gets", "a", "string", "representation", "of", "the", "given", "locale", ".", "This", "default", "implementation", "only", "supports", "language", "country", "and", "variant", ".", "Country", "will", "only", "be", "added", "when", "language", "present", ".", "Variant", "will", "only", "be", "added", "when", "both", "language", "and", "country", "are", "present", "." ]
ee1fb95e36b0620949e9cb8ee863ac37fb9e4f2b
https://github.com/aoindustries/ao-servlet-filter/blob/ee1fb95e36b0620949e9cb8ee863ac37fb9e4f2b/src/main/java/com/aoindustries/servlet/filter/LocaleFilter.java#L495-L508
train
maochen/NLP
CoreNLP-NLP/src/main/java/org/maochen/nlp/ml/classifier/libsvm/LibSVMClassifier.java
LibSVMClassifier.loadModel
@Override public void loadModel(InputStream modelIs) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { IOUtils.copy(modelIs, baos); } catch (IOException e) { LOG.error("Load model err.", e); } InputStream isForSVMLoad = new ByteArrayInputStream(baos.toByteArray()); try (ZipInputStream zipInputStream = new ZipInputStream(isForSVMLoad)) { ZipEntry entry; while ((entry = zipInputStream.getNextEntry()) != null) { if (entry.getName().endsWith(".model")) { BufferedReader br = new BufferedReader(new InputStreamReader(zipInputStream, Charset.defaultCharset())); this.model = svm.svm_load_model(br); } } } catch (IOException e) { // Do Nothing. } modelIs = new ByteArrayInputStream(baos.toByteArray()); try (ZipInputStream zipInputStream = new ZipInputStream(modelIs)) { ZipEntry entry; while ((entry = zipInputStream.getNextEntry()) != null) { if (entry.getName().endsWith(".lbindexer")) { String lbIndexer = IOUtils.toString(zipInputStream, Charset.defaultCharset()); this.labelIndexer = new LabelIndexer(new ArrayList<>()); this.labelIndexer.readFromSerializedString(lbIndexer); } } } catch (IOException e) { LOG.error("Err in load LabelIndexer", e); } }
java
@Override public void loadModel(InputStream modelIs) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { IOUtils.copy(modelIs, baos); } catch (IOException e) { LOG.error("Load model err.", e); } InputStream isForSVMLoad = new ByteArrayInputStream(baos.toByteArray()); try (ZipInputStream zipInputStream = new ZipInputStream(isForSVMLoad)) { ZipEntry entry; while ((entry = zipInputStream.getNextEntry()) != null) { if (entry.getName().endsWith(".model")) { BufferedReader br = new BufferedReader(new InputStreamReader(zipInputStream, Charset.defaultCharset())); this.model = svm.svm_load_model(br); } } } catch (IOException e) { // Do Nothing. } modelIs = new ByteArrayInputStream(baos.toByteArray()); try (ZipInputStream zipInputStream = new ZipInputStream(modelIs)) { ZipEntry entry; while ((entry = zipInputStream.getNextEntry()) != null) { if (entry.getName().endsWith(".lbindexer")) { String lbIndexer = IOUtils.toString(zipInputStream, Charset.defaultCharset()); this.labelIndexer = new LabelIndexer(new ArrayList<>()); this.labelIndexer.readFromSerializedString(lbIndexer); } } } catch (IOException e) { LOG.error("Err in load LabelIndexer", e); } }
[ "@", "Override", "public", "void", "loadModel", "(", "InputStream", "modelIs", ")", "{", "ByteArrayOutputStream", "baos", "=", "new", "ByteArrayOutputStream", "(", ")", ";", "try", "{", "IOUtils", ".", "copy", "(", "modelIs", ",", "baos", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "LOG", ".", "error", "(", "\"Load model err.\"", ",", "e", ")", ";", "}", "InputStream", "isForSVMLoad", "=", "new", "ByteArrayInputStream", "(", "baos", ".", "toByteArray", "(", ")", ")", ";", "try", "(", "ZipInputStream", "zipInputStream", "=", "new", "ZipInputStream", "(", "isForSVMLoad", ")", ")", "{", "ZipEntry", "entry", ";", "while", "(", "(", "entry", "=", "zipInputStream", ".", "getNextEntry", "(", ")", ")", "!=", "null", ")", "{", "if", "(", "entry", ".", "getName", "(", ")", ".", "endsWith", "(", "\".model\"", ")", ")", "{", "BufferedReader", "br", "=", "new", "BufferedReader", "(", "new", "InputStreamReader", "(", "zipInputStream", ",", "Charset", ".", "defaultCharset", "(", ")", ")", ")", ";", "this", ".", "model", "=", "svm", ".", "svm_load_model", "(", "br", ")", ";", "}", "}", "}", "catch", "(", "IOException", "e", ")", "{", "// Do Nothing.", "}", "modelIs", "=", "new", "ByteArrayInputStream", "(", "baos", ".", "toByteArray", "(", ")", ")", ";", "try", "(", "ZipInputStream", "zipInputStream", "=", "new", "ZipInputStream", "(", "modelIs", ")", ")", "{", "ZipEntry", "entry", ";", "while", "(", "(", "entry", "=", "zipInputStream", ".", "getNextEntry", "(", ")", ")", "!=", "null", ")", "{", "if", "(", "entry", ".", "getName", "(", ")", ".", "endsWith", "(", "\".lbindexer\"", ")", ")", "{", "String", "lbIndexer", "=", "IOUtils", ".", "toString", "(", "zipInputStream", ",", "Charset", ".", "defaultCharset", "(", ")", ")", ";", "this", ".", "labelIndexer", "=", "new", "LabelIndexer", "(", "new", "ArrayList", "<>", "(", ")", ")", ";", "this", ".", "labelIndexer", ".", "readFromSerializedString", "(", "lbIndexer", ")", ";", "}", "}", "}", "catch", "(", "IOException", "e", ")", "{", "LOG", ".", "error", "(", "\"Err in load LabelIndexer\"", ",", "e", ")", ";", "}", "}" ]
We load twice because svm.svm_load_model will close the stream after load. so the next guy will have Steam closed exception.
[ "We", "load", "twice", "because", "svm", ".", "svm_load_model", "will", "close", "the", "stream", "after", "load", ".", "so", "the", "next", "guy", "will", "have", "Steam", "closed", "exception", "." ]
38ae7b384d5295334d9efa9dc4cd901b19d9c27e
https://github.com/maochen/NLP/blob/38ae7b384d5295334d9efa9dc4cd901b19d9c27e/CoreNLP-NLP/src/main/java/org/maochen/nlp/ml/classifier/libsvm/LibSVMClassifier.java#L152-L191
train
aoindustries/ao-encoding
src/main/java/com/aoindustries/encoding/NewEncodingUtils.java
NewEncodingUtils.getJavaScriptUnicodeEscapeString
static String getJavaScriptUnicodeEscapeString(char ch) { int chInt = (int)ch; if(chInt>=ENCODE_RANGE_1_START && chInt<ENCODE_RANGE_1_END) { return javaScriptUnicodeEscapeStrings1[chInt - ENCODE_RANGE_1_START]; } if(chInt>=ENCODE_RANGE_2_START && chInt<ENCODE_RANGE_2_END) { return javaScriptUnicodeEscapeStrings2[chInt - ENCODE_RANGE_2_START]; } if(chInt>=ENCODE_RANGE_3_START && chInt<ENCODE_RANGE_3_END) { return javaScriptUnicodeEscapeStrings3[chInt - ENCODE_RANGE_3_START]; } // No encoding needed return null; }
java
static String getJavaScriptUnicodeEscapeString(char ch) { int chInt = (int)ch; if(chInt>=ENCODE_RANGE_1_START && chInt<ENCODE_RANGE_1_END) { return javaScriptUnicodeEscapeStrings1[chInt - ENCODE_RANGE_1_START]; } if(chInt>=ENCODE_RANGE_2_START && chInt<ENCODE_RANGE_2_END) { return javaScriptUnicodeEscapeStrings2[chInt - ENCODE_RANGE_2_START]; } if(chInt>=ENCODE_RANGE_3_START && chInt<ENCODE_RANGE_3_END) { return javaScriptUnicodeEscapeStrings3[chInt - ENCODE_RANGE_3_START]; } // No encoding needed return null; }
[ "static", "String", "getJavaScriptUnicodeEscapeString", "(", "char", "ch", ")", "{", "int", "chInt", "=", "(", "int", ")", "ch", ";", "if", "(", "chInt", ">=", "ENCODE_RANGE_1_START", "&&", "chInt", "<", "ENCODE_RANGE_1_END", ")", "{", "return", "javaScriptUnicodeEscapeStrings1", "[", "chInt", "-", "ENCODE_RANGE_1_START", "]", ";", "}", "if", "(", "chInt", ">=", "ENCODE_RANGE_2_START", "&&", "chInt", "<", "ENCODE_RANGE_2_END", ")", "{", "return", "javaScriptUnicodeEscapeStrings2", "[", "chInt", "-", "ENCODE_RANGE_2_START", "]", ";", "}", "if", "(", "chInt", ">=", "ENCODE_RANGE_3_START", "&&", "chInt", "<", "ENCODE_RANGE_3_END", ")", "{", "return", "javaScriptUnicodeEscapeStrings3", "[", "chInt", "-", "ENCODE_RANGE_3_START", "]", ";", "}", "// No encoding needed", "return", "null", ";", "}" ]
Gets the unicode escape for a JavaScript character or null if may be passed-through without escape. @param ch @return
[ "Gets", "the", "unicode", "escape", "for", "a", "JavaScript", "character", "or", "null", "if", "may", "be", "passed", "-", "through", "without", "escape", "." ]
54eeb8ff58ab7b44bb02549bbe2572625b449e4e
https://github.com/aoindustries/ao-encoding/blob/54eeb8ff58ab7b44bb02549bbe2572625b449e4e/src/main/java/com/aoindustries/encoding/NewEncodingUtils.java#L84-L97
train
maochen/NLP
CoreNLP-NLP/src/main/java/org/maochen/nlp/ml/classifier/naivebayes/NaiveBayesClassifier.java
NaiveBayesClassifier.predict
@Override public Map<String, Double> predict(Tuple predict) { Map<Integer, Double> labelProb = new HashMap<>(); for (Integer labelIndex : model.labelIndexer.getIndexSet()) { double likelihood = 1.0D; for (int i = 0; i < predict.vector.getVector().length; i++) { double fi = predict.vector.getVector()[i]; likelihood = likelihood * VectorUtils.gaussianPDF(model.meanVectors[labelIndex][i], model.varianceVectors[labelIndex][i], fi); } double posterior = model.labelPrior.get(labelIndex) * likelihood; // prior*likelihood, This is numerator of posterior labelProb.put(labelIndex, posterior); } double evidence = labelProb.values().stream().reduce((e1, e2) -> e1 + e2).orElse(-1D); if (evidence == -1) { LOG.error("Evidence is Empty!"); return new HashMap<>(); } labelProb.entrySet().forEach(entry -> { double prob = entry.getValue() / evidence; labelProb.put(entry.getKey(), prob); }); // This is denominator of posterior Map<String, Double> result = model.labelIndexer.convertMapKey(labelProb); if (predict.label == null || predict.label.isEmpty()) { // Just for write to predict tuple. predict.label = result.entrySet().stream().max((e1, e2) -> e1.getValue().compareTo(e2.getValue())).map(Entry::getKey).orElse(StringUtils.EMPTY); } return result; }
java
@Override public Map<String, Double> predict(Tuple predict) { Map<Integer, Double> labelProb = new HashMap<>(); for (Integer labelIndex : model.labelIndexer.getIndexSet()) { double likelihood = 1.0D; for (int i = 0; i < predict.vector.getVector().length; i++) { double fi = predict.vector.getVector()[i]; likelihood = likelihood * VectorUtils.gaussianPDF(model.meanVectors[labelIndex][i], model.varianceVectors[labelIndex][i], fi); } double posterior = model.labelPrior.get(labelIndex) * likelihood; // prior*likelihood, This is numerator of posterior labelProb.put(labelIndex, posterior); } double evidence = labelProb.values().stream().reduce((e1, e2) -> e1 + e2).orElse(-1D); if (evidence == -1) { LOG.error("Evidence is Empty!"); return new HashMap<>(); } labelProb.entrySet().forEach(entry -> { double prob = entry.getValue() / evidence; labelProb.put(entry.getKey(), prob); }); // This is denominator of posterior Map<String, Double> result = model.labelIndexer.convertMapKey(labelProb); if (predict.label == null || predict.label.isEmpty()) { // Just for write to predict tuple. predict.label = result.entrySet().stream().max((e1, e2) -> e1.getValue().compareTo(e2.getValue())).map(Entry::getKey).orElse(StringUtils.EMPTY); } return result; }
[ "@", "Override", "public", "Map", "<", "String", ",", "Double", ">", "predict", "(", "Tuple", "predict", ")", "{", "Map", "<", "Integer", ",", "Double", ">", "labelProb", "=", "new", "HashMap", "<>", "(", ")", ";", "for", "(", "Integer", "labelIndex", ":", "model", ".", "labelIndexer", ".", "getIndexSet", "(", ")", ")", "{", "double", "likelihood", "=", "1.0D", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "predict", ".", "vector", ".", "getVector", "(", ")", ".", "length", ";", "i", "++", ")", "{", "double", "fi", "=", "predict", ".", "vector", ".", "getVector", "(", ")", "[", "i", "]", ";", "likelihood", "=", "likelihood", "*", "VectorUtils", ".", "gaussianPDF", "(", "model", ".", "meanVectors", "[", "labelIndex", "]", "[", "i", "]", ",", "model", ".", "varianceVectors", "[", "labelIndex", "]", "[", "i", "]", ",", "fi", ")", ";", "}", "double", "posterior", "=", "model", ".", "labelPrior", ".", "get", "(", "labelIndex", ")", "*", "likelihood", ";", "// prior*likelihood, This is numerator of posterior", "labelProb", ".", "put", "(", "labelIndex", ",", "posterior", ")", ";", "}", "double", "evidence", "=", "labelProb", ".", "values", "(", ")", ".", "stream", "(", ")", ".", "reduce", "(", "(", "e1", ",", "e2", ")", "->", "e1", "+", "e2", ")", ".", "orElse", "(", "-", "1D", ")", ";", "if", "(", "evidence", "==", "-", "1", ")", "{", "LOG", ".", "error", "(", "\"Evidence is Empty!\"", ")", ";", "return", "new", "HashMap", "<>", "(", ")", ";", "}", "labelProb", ".", "entrySet", "(", ")", ".", "forEach", "(", "entry", "->", "{", "double", "prob", "=", "entry", ".", "getValue", "(", ")", "/", "evidence", ";", "labelProb", ".", "put", "(", "entry", ".", "getKey", "(", ")", ",", "prob", ")", ";", "}", ")", ";", "// This is denominator of posterior", "Map", "<", "String", ",", "Double", ">", "result", "=", "model", ".", "labelIndexer", ".", "convertMapKey", "(", "labelProb", ")", ";", "if", "(", "predict", ".", "label", "==", "null", "||", "predict", ".", "label", ".", "isEmpty", "(", ")", ")", "{", "// Just for write to predict tuple.", "predict", ".", "label", "=", "result", ".", "entrySet", "(", ")", ".", "stream", "(", ")", ".", "max", "(", "(", "e1", ",", "e2", ")", "->", "e1", ".", "getValue", "(", ")", ".", "compareTo", "(", "e2", ".", "getValue", "(", ")", ")", ")", ".", "map", "(", "Entry", "::", "getKey", ")", ".", "orElse", "(", "StringUtils", ".", "EMPTY", ")", ";", "}", "return", "result", ";", "}" ]
Integer is label's Index from labelIndexer
[ "Integer", "is", "label", "s", "Index", "from", "labelIndexer" ]
38ae7b384d5295334d9efa9dc4cd901b19d9c27e
https://github.com/maochen/NLP/blob/38ae7b384d5295334d9efa9dc4cd901b19d9c27e/CoreNLP-NLP/src/main/java/org/maochen/nlp/ml/classifier/naivebayes/NaiveBayesClassifier.java#L52-L84
train
maochen/NLP
CoreNLP-NLP/src/main/java/org/maochen/nlp/ml/classifier/naivebayes/NaiveBayesClassifier.java
NaiveBayesClassifier.splitData
public static void splitData(final String originalTrainingDataFile) { List<Tuple> trainingData = NaiveBayesClassifier.readTrainingData(originalTrainingDataFile, "\\s"); List<Tuple> wrongData = new ArrayList<>(); int lastTrainingDataSize; int iterCount = 0; do { System.out.println("Iteration:\t" + (++iterCount)); lastTrainingDataSize = trainingData.size(); NaiveBayesClassifier nbc = new NaiveBayesClassifier(); nbc.train(trainingData); Iterator<Tuple> trainingDataIter = trainingData.iterator(); while (trainingDataIter.hasNext()) { Tuple t = trainingDataIter.next(); String actual = nbc.predictLabel(t); if (!t.label.equals(actual) && !t.label.equals("1")) { // preserve 1 since too few. wrongData.add(t); trainingDataIter.remove(); } } Iterator<Tuple> wrongDataIter = wrongData.iterator(); while (wrongDataIter.hasNext()) { Tuple t = wrongDataIter.next(); String actual = nbc.predictLabel(t); if (t.label.equals(actual)) { trainingData.add(t); wrongDataIter.remove(); } } } while (trainingData.size() != lastTrainingDataSize); writeToFile(trainingData, originalTrainingDataFile + ".aligned"); writeToFile(wrongData, originalTrainingDataFile + ".wrong"); }
java
public static void splitData(final String originalTrainingDataFile) { List<Tuple> trainingData = NaiveBayesClassifier.readTrainingData(originalTrainingDataFile, "\\s"); List<Tuple> wrongData = new ArrayList<>(); int lastTrainingDataSize; int iterCount = 0; do { System.out.println("Iteration:\t" + (++iterCount)); lastTrainingDataSize = trainingData.size(); NaiveBayesClassifier nbc = new NaiveBayesClassifier(); nbc.train(trainingData); Iterator<Tuple> trainingDataIter = trainingData.iterator(); while (trainingDataIter.hasNext()) { Tuple t = trainingDataIter.next(); String actual = nbc.predictLabel(t); if (!t.label.equals(actual) && !t.label.equals("1")) { // preserve 1 since too few. wrongData.add(t); trainingDataIter.remove(); } } Iterator<Tuple> wrongDataIter = wrongData.iterator(); while (wrongDataIter.hasNext()) { Tuple t = wrongDataIter.next(); String actual = nbc.predictLabel(t); if (t.label.equals(actual)) { trainingData.add(t); wrongDataIter.remove(); } } } while (trainingData.size() != lastTrainingDataSize); writeToFile(trainingData, originalTrainingDataFile + ".aligned"); writeToFile(wrongData, originalTrainingDataFile + ".wrong"); }
[ "public", "static", "void", "splitData", "(", "final", "String", "originalTrainingDataFile", ")", "{", "List", "<", "Tuple", ">", "trainingData", "=", "NaiveBayesClassifier", ".", "readTrainingData", "(", "originalTrainingDataFile", ",", "\"\\\\s\"", ")", ";", "List", "<", "Tuple", ">", "wrongData", "=", "new", "ArrayList", "<>", "(", ")", ";", "int", "lastTrainingDataSize", ";", "int", "iterCount", "=", "0", ";", "do", "{", "System", ".", "out", ".", "println", "(", "\"Iteration:\\t\"", "+", "(", "++", "iterCount", ")", ")", ";", "lastTrainingDataSize", "=", "trainingData", ".", "size", "(", ")", ";", "NaiveBayesClassifier", "nbc", "=", "new", "NaiveBayesClassifier", "(", ")", ";", "nbc", ".", "train", "(", "trainingData", ")", ";", "Iterator", "<", "Tuple", ">", "trainingDataIter", "=", "trainingData", ".", "iterator", "(", ")", ";", "while", "(", "trainingDataIter", ".", "hasNext", "(", ")", ")", "{", "Tuple", "t", "=", "trainingDataIter", ".", "next", "(", ")", ";", "String", "actual", "=", "nbc", ".", "predictLabel", "(", "t", ")", ";", "if", "(", "!", "t", ".", "label", ".", "equals", "(", "actual", ")", "&&", "!", "t", ".", "label", ".", "equals", "(", "\"1\"", ")", ")", "{", "// preserve 1 since too few.", "wrongData", ".", "add", "(", "t", ")", ";", "trainingDataIter", ".", "remove", "(", ")", ";", "}", "}", "Iterator", "<", "Tuple", ">", "wrongDataIter", "=", "wrongData", ".", "iterator", "(", ")", ";", "while", "(", "wrongDataIter", ".", "hasNext", "(", ")", ")", "{", "Tuple", "t", "=", "wrongDataIter", ".", "next", "(", ")", ";", "String", "actual", "=", "nbc", ".", "predictLabel", "(", "t", ")", ";", "if", "(", "t", ".", "label", ".", "equals", "(", "actual", ")", ")", "{", "trainingData", ".", "add", "(", "t", ")", ";", "wrongDataIter", ".", "remove", "(", ")", ";", "}", "}", "}", "while", "(", "trainingData", ".", "size", "(", ")", "!=", "lastTrainingDataSize", ")", ";", "writeToFile", "(", "trainingData", ",", "originalTrainingDataFile", "+", "\".aligned\"", ")", ";", "writeToFile", "(", "wrongData", ",", "originalTrainingDataFile", "+", "\".wrong\"", ")", ";", "}" ]
Split the data between trainable and wrong.
[ "Split", "the", "data", "between", "trainable", "and", "wrong", "." ]
38ae7b384d5295334d9efa9dc4cd901b19d9c27e
https://github.com/maochen/NLP/blob/38ae7b384d5295334d9efa9dc4cd901b19d9c27e/CoreNLP-NLP/src/main/java/org/maochen/nlp/ml/classifier/naivebayes/NaiveBayesClassifier.java#L153-L189
train
crowmagnumb/s6-util
src/main/java/net/crowmagnumb/util/net/AbstractMultipartUtility.java
AbstractMultipartUtility.addFilePart
public void addFilePart(final String fieldName, final InputStream stream, final String contentType) throws IOException { addFilePart(fieldName, stream, null, contentType); }
java
public void addFilePart(final String fieldName, final InputStream stream, final String contentType) throws IOException { addFilePart(fieldName, stream, null, contentType); }
[ "public", "void", "addFilePart", "(", "final", "String", "fieldName", ",", "final", "InputStream", "stream", ",", "final", "String", "contentType", ")", "throws", "IOException", "{", "addFilePart", "(", "fieldName", ",", "stream", ",", "null", ",", "contentType", ")", ";", "}" ]
Adds a upload file section to the request by stream @param fieldName name attribute in &lt;input type="file" name="..." /&gt; @param stream input stream of data to upload @param contentType content type of data @throws IOException if problems
[ "Adds", "a", "upload", "file", "section", "to", "the", "request", "by", "stream" ]
0f9969bc0809e8a617501fa57c135e9b3984fae0
https://github.com/crowmagnumb/s6-util/blob/0f9969bc0809e8a617501fa57c135e9b3984fae0/src/main/java/net/crowmagnumb/util/net/AbstractMultipartUtility.java#L71-L75
train
crowmagnumb/s6-util
src/main/java/net/crowmagnumb/util/net/AbstractMultipartUtility.java
AbstractMultipartUtility.addFilePart
public void addFilePart(final String fieldName, final URL urlToUploadFile) throws IOException { // // Maybe try and extract a filename from the last part of the url? // Or have the user pass it in? // Or just leave it blank as I have already done? // addFilePart(fieldName, urlToUploadFile.openStream(), null, URLConnection.guessContentTypeFromName(urlToUploadFile.toString())); }
java
public void addFilePart(final String fieldName, final URL urlToUploadFile) throws IOException { // // Maybe try and extract a filename from the last part of the url? // Or have the user pass it in? // Or just leave it blank as I have already done? // addFilePart(fieldName, urlToUploadFile.openStream(), null, URLConnection.guessContentTypeFromName(urlToUploadFile.toString())); }
[ "public", "void", "addFilePart", "(", "final", "String", "fieldName", ",", "final", "URL", "urlToUploadFile", ")", "throws", "IOException", "{", "//", "// Maybe try and extract a filename from the last part of the url?", "// Or have the user pass it in?", "// Or just leave it blank as I have already done?", "//", "addFilePart", "(", "fieldName", ",", "urlToUploadFile", ".", "openStream", "(", ")", ",", "null", ",", "URLConnection", ".", "guessContentTypeFromName", "(", "urlToUploadFile", ".", "toString", "(", ")", ")", ")", ";", "}" ]
Adds a upload file section to the request by url stream @param fieldName name attribute in &lt;input type="file" name="..." /&gt; @param urlToUploadFile url to add as a stream @throws IOException if problems
[ "Adds", "a", "upload", "file", "section", "to", "the", "request", "by", "url", "stream" ]
0f9969bc0809e8a617501fa57c135e9b3984fae0
https://github.com/crowmagnumb/s6-util/blob/0f9969bc0809e8a617501fa57c135e9b3984fae0/src/main/java/net/crowmagnumb/util/net/AbstractMultipartUtility.java#L83-L95
train
crowmagnumb/s6-util
src/main/java/net/crowmagnumb/util/net/AbstractMultipartUtility.java
AbstractMultipartUtility.addHeaderField
public void addHeaderField(final String name, final String value) { writer.append(name + ": " + value).append(LINE_FEED); writer.flush(); }
java
public void addHeaderField(final String name, final String value) { writer.append(name + ": " + value).append(LINE_FEED); writer.flush(); }
[ "public", "void", "addHeaderField", "(", "final", "String", "name", ",", "final", "String", "value", ")", "{", "writer", ".", "append", "(", "name", "+", "\": \"", "+", "value", ")", ".", "append", "(", "LINE_FEED", ")", ";", "writer", ".", "flush", "(", ")", ";", "}" ]
Adds a header field to the request. @param name - name of the header field @param value - value of the header field
[ "Adds", "a", "header", "field", "to", "the", "request", "." ]
0f9969bc0809e8a617501fa57c135e9b3984fae0
https://github.com/crowmagnumb/s6-util/blob/0f9969bc0809e8a617501fa57c135e9b3984fae0/src/main/java/net/crowmagnumb/util/net/AbstractMultipartUtility.java#L134-L138
train
crowmagnumb/s6-util
src/main/java/net/crowmagnumb/util/net/AbstractMultipartUtility.java
AbstractMultipartUtility.finish
public HttpResponse finish() throws IOException { writer.append("--" + boundary + "--").append(LINE_FEED); writer.flush(); try { return doFinish(); } finally { writer.close(); } }
java
public HttpResponse finish() throws IOException { writer.append("--" + boundary + "--").append(LINE_FEED); writer.flush(); try { return doFinish(); } finally { writer.close(); } }
[ "public", "HttpResponse", "finish", "(", ")", "throws", "IOException", "{", "writer", ".", "append", "(", "\"--\"", "+", "boundary", "+", "\"--\"", ")", ".", "append", "(", "LINE_FEED", ")", ";", "writer", ".", "flush", "(", ")", ";", "try", "{", "return", "doFinish", "(", ")", ";", "}", "finally", "{", "writer", ".", "close", "(", ")", ";", "}", "}" ]
Completes the request and receives response from the server. @return a list of Strings as response in case the server returned status OK, otherwise an exception is thrown. @throws IOException if problems
[ "Completes", "the", "request", "and", "receives", "response", "from", "the", "server", "." ]
0f9969bc0809e8a617501fa57c135e9b3984fae0
https://github.com/crowmagnumb/s6-util/blob/0f9969bc0809e8a617501fa57c135e9b3984fae0/src/main/java/net/crowmagnumb/util/net/AbstractMultipartUtility.java#L146-L156
train
nightcode/yaranga
core/src/org/nightcode/common/util/monitoring/Speedometer.java
Speedometer.update
public double update(final double units) { final double speed; lock.lock(); try { final long currentTime = System.nanoTime(); final long timeDifference = (currentTime - lastUpdateTime) / C1; // nanoseconds to micros if (timeDifference >= averagingPeriod) { speed = units / averagingPeriod; cachedSpeed = speed; lastUpdateTime = currentTime; elapsedTime = ZERO_TIME; quantity = ZERO_UNITS; } else { if (timeDifference > ZERO_TIME) { lastUpdateTime = currentTime; elapsedTime += timeDifference; } if (units != ZERO_UNITS) { quantity += units; } if (elapsedTime >= averagingPeriod) { speed = quantity / elapsedTime; cachedSpeed = speed; elapsedTime = ZERO_TIME; quantity = ZERO_UNITS; } else { speed = (cachedSpeed * (averagingPeriod - elapsedTime) + quantity) / averagingPeriod; } } } finally { lock.unlock(); } return speed * C0; // units per micro to units per second }
java
public double update(final double units) { final double speed; lock.lock(); try { final long currentTime = System.nanoTime(); final long timeDifference = (currentTime - lastUpdateTime) / C1; // nanoseconds to micros if (timeDifference >= averagingPeriod) { speed = units / averagingPeriod; cachedSpeed = speed; lastUpdateTime = currentTime; elapsedTime = ZERO_TIME; quantity = ZERO_UNITS; } else { if (timeDifference > ZERO_TIME) { lastUpdateTime = currentTime; elapsedTime += timeDifference; } if (units != ZERO_UNITS) { quantity += units; } if (elapsedTime >= averagingPeriod) { speed = quantity / elapsedTime; cachedSpeed = speed; elapsedTime = ZERO_TIME; quantity = ZERO_UNITS; } else { speed = (cachedSpeed * (averagingPeriod - elapsedTime) + quantity) / averagingPeriod; } } } finally { lock.unlock(); } return speed * C0; // units per micro to units per second }
[ "public", "double", "update", "(", "final", "double", "units", ")", "{", "final", "double", "speed", ";", "lock", ".", "lock", "(", ")", ";", "try", "{", "final", "long", "currentTime", "=", "System", ".", "nanoTime", "(", ")", ";", "final", "long", "timeDifference", "=", "(", "currentTime", "-", "lastUpdateTime", ")", "/", "C1", ";", "// nanoseconds to micros", "if", "(", "timeDifference", ">=", "averagingPeriod", ")", "{", "speed", "=", "units", "/", "averagingPeriod", ";", "cachedSpeed", "=", "speed", ";", "lastUpdateTime", "=", "currentTime", ";", "elapsedTime", "=", "ZERO_TIME", ";", "quantity", "=", "ZERO_UNITS", ";", "}", "else", "{", "if", "(", "timeDifference", ">", "ZERO_TIME", ")", "{", "lastUpdateTime", "=", "currentTime", ";", "elapsedTime", "+=", "timeDifference", ";", "}", "if", "(", "units", "!=", "ZERO_UNITS", ")", "{", "quantity", "+=", "units", ";", "}", "if", "(", "elapsedTime", ">=", "averagingPeriod", ")", "{", "speed", "=", "quantity", "/", "elapsedTime", ";", "cachedSpeed", "=", "speed", ";", "elapsedTime", "=", "ZERO_TIME", ";", "quantity", "=", "ZERO_UNITS", ";", "}", "else", "{", "speed", "=", "(", "cachedSpeed", "*", "(", "averagingPeriod", "-", "elapsedTime", ")", "+", "quantity", ")", "/", "averagingPeriod", ";", "}", "}", "}", "finally", "{", "lock", ".", "unlock", "(", ")", ";", "}", "return", "speed", "*", "C0", ";", "// units per micro to units per second", "}" ]
Updates speed value. @param units units @return the current speed value (units per second)
[ "Updates", "speed", "value", "." ]
f02cf8d8bcd365b6b1d55638938631a00e9ee808
https://github.com/nightcode/yaranga/blob/f02cf8d8bcd365b6b1d55638938631a00e9ee808/core/src/org/nightcode/common/util/monitoring/Speedometer.java#L79-L112
train
liuyukuai/commons
commons-core/src/main/java/com/itxiaoer/commons/core/json/JsonUtil.java
JsonUtil.toBean
public static <T> Optional<T> toBean(String json, Class<T> clazz) { if (StringUtils.isBlank(json)) { log.warn("json is blank. "); return Optional.empty(); } try { OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); return Optional.of(OBJECT_MAPPER.readValue(json, clazz)); } catch (Exception e) { log.error(e.getMessage(), e); return Optional.empty(); } }
java
public static <T> Optional<T> toBean(String json, Class<T> clazz) { if (StringUtils.isBlank(json)) { log.warn("json is blank. "); return Optional.empty(); } try { OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); return Optional.of(OBJECT_MAPPER.readValue(json, clazz)); } catch (Exception e) { log.error(e.getMessage(), e); return Optional.empty(); } }
[ "public", "static", "<", "T", ">", "Optional", "<", "T", ">", "toBean", "(", "String", "json", ",", "Class", "<", "T", ">", "clazz", ")", "{", "if", "(", "StringUtils", ".", "isBlank", "(", "json", ")", ")", "{", "log", ".", "warn", "(", "\"json is blank. \"", ")", ";", "return", "Optional", ".", "empty", "(", ")", ";", "}", "try", "{", "OBJECT_MAPPER", ".", "configure", "(", "DeserializationFeature", ".", "FAIL_ON_UNKNOWN_PROPERTIES", ",", "false", ")", ";", "return", "Optional", ".", "of", "(", "OBJECT_MAPPER", ".", "readValue", "(", "json", ",", "clazz", ")", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "log", ".", "error", "(", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "return", "Optional", ".", "empty", "(", ")", ";", "}", "}" ]
json to object @param json json @param clazz clazz @param <T> T @return Optional
[ "json", "to", "object" ]
ba67eddb542446b12f419f1866dbaa82e47fbf35
https://github.com/liuyukuai/commons/blob/ba67eddb542446b12f419f1866dbaa82e47fbf35/commons-core/src/main/java/com/itxiaoer/commons/core/json/JsonUtil.java#L28-L40
train
liuyukuai/commons
commons-core/src/main/java/com/itxiaoer/commons/core/json/JsonUtil.java
JsonUtil.toJson
public static <T> String toJson(T t) { if (Objects.isNull(t)) { log.warn("t is blank. "); return ""; } try { return OBJECT_MAPPER.writeValueAsString(t); } catch (Exception e) { log.error(e.getMessage(), e); return ""; } }
java
public static <T> String toJson(T t) { if (Objects.isNull(t)) { log.warn("t is blank. "); return ""; } try { return OBJECT_MAPPER.writeValueAsString(t); } catch (Exception e) { log.error(e.getMessage(), e); return ""; } }
[ "public", "static", "<", "T", ">", "String", "toJson", "(", "T", "t", ")", "{", "if", "(", "Objects", ".", "isNull", "(", "t", ")", ")", "{", "log", ".", "warn", "(", "\"t is blank. \"", ")", ";", "return", "\"\"", ";", "}", "try", "{", "return", "OBJECT_MAPPER", ".", "writeValueAsString", "(", "t", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "log", ".", "error", "(", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "return", "\"\"", ";", "}", "}" ]
object to json @param <T> T t @param t 参数类型 @return string
[ "object", "to", "json" ]
ba67eddb542446b12f419f1866dbaa82e47fbf35
https://github.com/liuyukuai/commons/blob/ba67eddb542446b12f419f1866dbaa82e47fbf35/commons-core/src/main/java/com/itxiaoer/commons/core/json/JsonUtil.java#L50-L61
train
maochen/NLP
CoreNLP-WEB/src/main/java/org/maochen/nlp/web/ws/RESTWebService.java
RESTWebService.parse
@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE, value = "/parse", method = RequestMethod.GET) public String parse(@RequestParam("sentence") String sentence, HttpServletRequest request) { if (sentence == null || sentence.trim().isEmpty()) { return StringUtils.EMPTY; } sentence = sentence.trim(); LOGGER.info("Parse [" + sentence + "]"); DTree tree = PARSER.parse(sentence); DTreeEntity parseTreeEntity = new DTreeEntity(tree, "SAMPLE_AUTHOR"); dNodeEntityRepository.save(parseTreeEntity.dNodeEntities); dTreeEntityRepository.save(parseTreeEntity); return "[" + toJSON(tree.get(0)) + "]"; }
java
@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE, value = "/parse", method = RequestMethod.GET) public String parse(@RequestParam("sentence") String sentence, HttpServletRequest request) { if (sentence == null || sentence.trim().isEmpty()) { return StringUtils.EMPTY; } sentence = sentence.trim(); LOGGER.info("Parse [" + sentence + "]"); DTree tree = PARSER.parse(sentence); DTreeEntity parseTreeEntity = new DTreeEntity(tree, "SAMPLE_AUTHOR"); dNodeEntityRepository.save(parseTreeEntity.dNodeEntities); dTreeEntityRepository.save(parseTreeEntity); return "[" + toJSON(tree.get(0)) + "]"; }
[ "@", "RequestMapping", "(", "produces", "=", "MediaType", ".", "APPLICATION_JSON_VALUE", ",", "value", "=", "\"/parse\"", ",", "method", "=", "RequestMethod", ".", "GET", ")", "public", "String", "parse", "(", "@", "RequestParam", "(", "\"sentence\"", ")", "String", "sentence", ",", "HttpServletRequest", "request", ")", "{", "if", "(", "sentence", "==", "null", "||", "sentence", ".", "trim", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "return", "StringUtils", ".", "EMPTY", ";", "}", "sentence", "=", "sentence", ".", "trim", "(", ")", ";", "LOGGER", ".", "info", "(", "\"Parse [\"", "+", "sentence", "+", "\"]\"", ")", ";", "DTree", "tree", "=", "PARSER", ".", "parse", "(", "sentence", ")", ";", "DTreeEntity", "parseTreeEntity", "=", "new", "DTreeEntity", "(", "tree", ",", "\"SAMPLE_AUTHOR\"", ")", ";", "dNodeEntityRepository", ".", "save", "(", "parseTreeEntity", ".", "dNodeEntities", ")", ";", "dTreeEntityRepository", ".", "save", "(", "parseTreeEntity", ")", ";", "return", "\"[\"", "+", "toJSON", "(", "tree", ".", "get", "(", "0", ")", ")", "+", "\"]\"", ";", "}" ]
Parse sentence. @param sentence sentence. @param request http servlet request. @return parse tree JSON.
[ "Parse", "sentence", "." ]
38ae7b384d5295334d9efa9dc4cd901b19d9c27e
https://github.com/maochen/NLP/blob/38ae7b384d5295334d9efa9dc4cd901b19d9c27e/CoreNLP-WEB/src/main/java/org/maochen/nlp/web/ws/RESTWebService.java#L83-L98
train
aoindustries/ao-taglib
src/main/java/com/aoindustries/taglib/AttributeUtils.java
AttributeUtils.resolveValue
public static <T> T resolveValue(ValueExpression expression, Class<T> type, ELContext elContext) { if(expression == null) { return null; } else { return type.cast(expression.getValue(elContext)); } }
java
public static <T> T resolveValue(ValueExpression expression, Class<T> type, ELContext elContext) { if(expression == null) { return null; } else { return type.cast(expression.getValue(elContext)); } }
[ "public", "static", "<", "T", ">", "T", "resolveValue", "(", "ValueExpression", "expression", ",", "Class", "<", "T", ">", "type", ",", "ELContext", "elContext", ")", "{", "if", "(", "expression", "==", "null", ")", "{", "return", "null", ";", "}", "else", "{", "return", "type", ".", "cast", "(", "expression", ".", "getValue", "(", "elContext", ")", ")", ";", "}", "}" ]
Evaluates an expression then casts to the provided type.
[ "Evaluates", "an", "expression", "then", "casts", "to", "the", "provided", "type", "." ]
5670eba8485196bd42d31d3ff09a42deacb025f8
https://github.com/aoindustries/ao-taglib/blob/5670eba8485196bd42d31d3ff09a42deacb025f8/src/main/java/com/aoindustries/taglib/AttributeUtils.java#L50-L56
train
aoindustries/ao-taglib
src/main/java/com/aoindustries/taglib/AttributeUtils.java
AttributeUtils.resolveValue
public static <T> T resolveValue(Object value, Class<T> type, ELContext elContext) { if(value == null) { return null; } else if(value instanceof ValueExpression) { return resolveValue((ValueExpression)value, type, elContext); } else { return type.cast(value); } }
java
public static <T> T resolveValue(Object value, Class<T> type, ELContext elContext) { if(value == null) { return null; } else if(value instanceof ValueExpression) { return resolveValue((ValueExpression)value, type, elContext); } else { return type.cast(value); } }
[ "public", "static", "<", "T", ">", "T", "resolveValue", "(", "Object", "value", ",", "Class", "<", "T", ">", "type", ",", "ELContext", "elContext", ")", "{", "if", "(", "value", "==", "null", ")", "{", "return", "null", ";", "}", "else", "if", "(", "value", "instanceof", "ValueExpression", ")", "{", "return", "resolveValue", "(", "(", "ValueExpression", ")", "value", ",", "type", ",", "elContext", ")", ";", "}", "else", "{", "return", "type", ".", "cast", "(", "value", ")", ";", "}", "}" ]
Casts or evaluates an expression then casts to the provided type.
[ "Casts", "or", "evaluates", "an", "expression", "then", "casts", "to", "the", "provided", "type", "." ]
5670eba8485196bd42d31d3ff09a42deacb025f8
https://github.com/aoindustries/ao-taglib/blob/5670eba8485196bd42d31d3ff09a42deacb025f8/src/main/java/com/aoindustries/taglib/AttributeUtils.java#L61-L69
train
aoindustries/ao-encoding
src/main/java/com/aoindustries/encoding/MediaValidator.java
MediaValidator.getMediaValidator
public static MediaValidator getMediaValidator(MediaType contentType, Writer out) throws MediaException { // If the existing out is already validating for this type, use it. // This occurs when one validation validates to a set of characters that are a subset of the requested validator. // For example, a URL is always valid TEXT. if(out instanceof MediaValidator) { MediaValidator inputValidator = (MediaValidator)out; if(inputValidator.isValidatingMediaInputType(contentType)) return inputValidator; } // Add filter if needed for the given type switch(contentType) { case JAVASCRIPT: case JSON: case LD_JSON: return new JavaScriptValidator(out, contentType); case SH: return new ShValidator(out); case MYSQL: return new MysqlValidator(out); case PSQL: return new PsqlValidator(out); case TEXT: return new TextValidator(out); case URL: return new UrlValidator(out); case XHTML: return new XhtmlValidator(out); case XHTML_ATTRIBUTE: return new XhtmlAttributeValidator(out); default: throw new MediaException(ApplicationResources.accessor.getMessage("MediaValidator.unableToFindValidator", contentType.getContentType())); } }
java
public static MediaValidator getMediaValidator(MediaType contentType, Writer out) throws MediaException { // If the existing out is already validating for this type, use it. // This occurs when one validation validates to a set of characters that are a subset of the requested validator. // For example, a URL is always valid TEXT. if(out instanceof MediaValidator) { MediaValidator inputValidator = (MediaValidator)out; if(inputValidator.isValidatingMediaInputType(contentType)) return inputValidator; } // Add filter if needed for the given type switch(contentType) { case JAVASCRIPT: case JSON: case LD_JSON: return new JavaScriptValidator(out, contentType); case SH: return new ShValidator(out); case MYSQL: return new MysqlValidator(out); case PSQL: return new PsqlValidator(out); case TEXT: return new TextValidator(out); case URL: return new UrlValidator(out); case XHTML: return new XhtmlValidator(out); case XHTML_ATTRIBUTE: return new XhtmlAttributeValidator(out); default: throw new MediaException(ApplicationResources.accessor.getMessage("MediaValidator.unableToFindValidator", contentType.getContentType())); } }
[ "public", "static", "MediaValidator", "getMediaValidator", "(", "MediaType", "contentType", ",", "Writer", "out", ")", "throws", "MediaException", "{", "// If the existing out is already validating for this type, use it.", "// This occurs when one validation validates to a set of characters that are a subset of the requested validator.", "// For example, a URL is always valid TEXT.", "if", "(", "out", "instanceof", "MediaValidator", ")", "{", "MediaValidator", "inputValidator", "=", "(", "MediaValidator", ")", "out", ";", "if", "(", "inputValidator", ".", "isValidatingMediaInputType", "(", "contentType", ")", ")", "return", "inputValidator", ";", "}", "// Add filter if needed for the given type", "switch", "(", "contentType", ")", "{", "case", "JAVASCRIPT", ":", "case", "JSON", ":", "case", "LD_JSON", ":", "return", "new", "JavaScriptValidator", "(", "out", ",", "contentType", ")", ";", "case", "SH", ":", "return", "new", "ShValidator", "(", "out", ")", ";", "case", "MYSQL", ":", "return", "new", "MysqlValidator", "(", "out", ")", ";", "case", "PSQL", ":", "return", "new", "PsqlValidator", "(", "out", ")", ";", "case", "TEXT", ":", "return", "new", "TextValidator", "(", "out", ")", ";", "case", "URL", ":", "return", "new", "UrlValidator", "(", "out", ")", ";", "case", "XHTML", ":", "return", "new", "XhtmlValidator", "(", "out", ")", ";", "case", "XHTML_ATTRIBUTE", ":", "return", "new", "XhtmlAttributeValidator", "(", "out", ")", ";", "default", ":", "throw", "new", "MediaException", "(", "ApplicationResources", ".", "accessor", ".", "getMessage", "(", "\"MediaValidator.unableToFindValidator\"", ",", "contentType", ".", "getContentType", "(", ")", ")", ")", ";", "}", "}" ]
Gets the media validator for the given type. If the given writer is already validator for the requested type, will return the provided writer. @exception MediaException when unable to find an appropriate validator.
[ "Gets", "the", "media", "validator", "for", "the", "given", "type", ".", "If", "the", "given", "writer", "is", "already", "validator", "for", "the", "requested", "type", "will", "return", "the", "provided", "writer", "." ]
54eeb8ff58ab7b44bb02549bbe2572625b449e4e
https://github.com/aoindustries/ao-encoding/blob/54eeb8ff58ab7b44bb02549bbe2572625b449e4e/src/main/java/com/aoindustries/encoding/MediaValidator.java#L42-L73
train
aoindustries/semanticcms-autogit-view
src/main/java/com/semanticcms/autogit/view/AutoGitView.java
AutoGitView.getAllowRobots
@Override public boolean getAllowRobots(ServletContext servletContext, HttpServletRequest request, HttpServletResponse response, Page page) { return false; }
java
@Override public boolean getAllowRobots(ServletContext servletContext, HttpServletRequest request, HttpServletResponse response, Page page) { return false; }
[ "@", "Override", "public", "boolean", "getAllowRobots", "(", "ServletContext", "servletContext", ",", "HttpServletRequest", "request", ",", "HttpServletResponse", "response", ",", "Page", "page", ")", "{", "return", "false", ";", "}" ]
No robots for transient Git status.
[ "No", "robots", "for", "transient", "Git", "status", "." ]
d66383cd2c9ca2852608c386929260d969edc876
https://github.com/aoindustries/semanticcms-autogit-view/blob/d66383cd2c9ca2852608c386929260d969edc876/src/main/java/com/semanticcms/autogit/view/AutoGitView.java#L122-L125
train
maochen/NLP
CoreNLP-NLP/src/main/java/org/maochen/nlp/ml/classifier/LabelIndexer.java
LabelIndexer.convertMapKey
public Map<String, Double> convertMapKey(Map<Integer, Double> probs) { Map<String, Double> stringKeyProb = new HashMap<>(); probs.entrySet().forEach(e -> stringKeyProb.put(getLabel(e.getKey()), e.getValue())); return stringKeyProb; }
java
public Map<String, Double> convertMapKey(Map<Integer, Double> probs) { Map<String, Double> stringKeyProb = new HashMap<>(); probs.entrySet().forEach(e -> stringKeyProb.put(getLabel(e.getKey()), e.getValue())); return stringKeyProb; }
[ "public", "Map", "<", "String", ",", "Double", ">", "convertMapKey", "(", "Map", "<", "Integer", ",", "Double", ">", "probs", ")", "{", "Map", "<", "String", ",", "Double", ">", "stringKeyProb", "=", "new", "HashMap", "<>", "(", ")", ";", "probs", ".", "entrySet", "(", ")", ".", "forEach", "(", "e", "->", "stringKeyProb", ".", "put", "(", "getLabel", "(", "e", ".", "getKey", "(", ")", ")", ",", "e", ".", "getValue", "(", ")", ")", ")", ";", "return", "stringKeyProb", ";", "}" ]
Convert Index to actual string.
[ "Convert", "Index", "to", "actual", "string", "." ]
38ae7b384d5295334d9efa9dc4cd901b19d9c27e
https://github.com/maochen/NLP/blob/38ae7b384d5295334d9efa9dc4cd901b19d9c27e/CoreNLP-NLP/src/main/java/org/maochen/nlp/ml/classifier/LabelIndexer.java#L50-L54
train
aoindustries/ao-taglib
src/main/java/com/aoindustries/taglib/TeiUtils.java
TeiUtils.validateMediaType
public static List<ValidationMessage> validateMediaType(TagData data, List<ValidationMessage> messages) { Object o = data.getAttribute("type"); if( o != null && o != TagData.REQUEST_TIME_VALUE && !(o instanceof MediaType) ) { String type = Coercion.toString(o); try { // First allow shortcuts (matching enum names) MediaType mediaType = MediaType.getMediaTypeByName(type); if(mediaType == null) { mediaType = MediaType.getMediaTypeForContentType(type); } // Value is OK } catch(MediaException err) { messages = MinimalList.add( messages, new ValidationMessage( data.getId(), err.getMessage() ) ); } } return messages; }
java
public static List<ValidationMessage> validateMediaType(TagData data, List<ValidationMessage> messages) { Object o = data.getAttribute("type"); if( o != null && o != TagData.REQUEST_TIME_VALUE && !(o instanceof MediaType) ) { String type = Coercion.toString(o); try { // First allow shortcuts (matching enum names) MediaType mediaType = MediaType.getMediaTypeByName(type); if(mediaType == null) { mediaType = MediaType.getMediaTypeForContentType(type); } // Value is OK } catch(MediaException err) { messages = MinimalList.add( messages, new ValidationMessage( data.getId(), err.getMessage() ) ); } } return messages; }
[ "public", "static", "List", "<", "ValidationMessage", ">", "validateMediaType", "(", "TagData", "data", ",", "List", "<", "ValidationMessage", ">", "messages", ")", "{", "Object", "o", "=", "data", ".", "getAttribute", "(", "\"type\"", ")", ";", "if", "(", "o", "!=", "null", "&&", "o", "!=", "TagData", ".", "REQUEST_TIME_VALUE", "&&", "!", "(", "o", "instanceof", "MediaType", ")", ")", "{", "String", "type", "=", "Coercion", ".", "toString", "(", "o", ")", ";", "try", "{", "// First allow shortcuts (matching enum names)", "MediaType", "mediaType", "=", "MediaType", ".", "getMediaTypeByName", "(", "type", ")", ";", "if", "(", "mediaType", "==", "null", ")", "{", "mediaType", "=", "MediaType", ".", "getMediaTypeForContentType", "(", "type", ")", ";", "}", "// Value is OK", "}", "catch", "(", "MediaException", "err", ")", "{", "messages", "=", "MinimalList", ".", "add", "(", "messages", ",", "new", "ValidationMessage", "(", "data", ".", "getId", "(", ")", ",", "err", ".", "getMessage", "(", ")", ")", ")", ";", "}", "}", "return", "messages", ";", "}" ]
Checks that a type is a valid MediaType. @param message the list of messages to add to, maybe <code>null</code> @return the list of messages. A new list will have been created if the <code>message</code> parameter was <code>null</code> @see MediaType#getMediaType(java.lang.String)
[ "Checks", "that", "a", "type", "is", "a", "valid", "MediaType", "." ]
5670eba8485196bd42d31d3ff09a42deacb025f8
https://github.com/aoindustries/ao-taglib/blob/5670eba8485196bd42d31d3ff09a42deacb025f8/src/main/java/com/aoindustries/taglib/TeiUtils.java#L52-L78
train
aoindustries/ao-taglib
src/main/java/com/aoindustries/taglib/TeiUtils.java
TeiUtils.validateScope
public static List<ValidationMessage> validateScope(TagData data, List<ValidationMessage> messages) { Object o = data.getAttribute("scope"); if( o != null && o != TagData.REQUEST_TIME_VALUE ) { String scope = Coercion.toString(o); try { Scope.getScopeId(scope); // Value is OK } catch(JspTagException err) { messages = MinimalList.add( messages, new ValidationMessage( data.getId(), err.getMessage() ) ); } } return messages; }
java
public static List<ValidationMessage> validateScope(TagData data, List<ValidationMessage> messages) { Object o = data.getAttribute("scope"); if( o != null && o != TagData.REQUEST_TIME_VALUE ) { String scope = Coercion.toString(o); try { Scope.getScopeId(scope); // Value is OK } catch(JspTagException err) { messages = MinimalList.add( messages, new ValidationMessage( data.getId(), err.getMessage() ) ); } } return messages; }
[ "public", "static", "List", "<", "ValidationMessage", ">", "validateScope", "(", "TagData", "data", ",", "List", "<", "ValidationMessage", ">", "messages", ")", "{", "Object", "o", "=", "data", ".", "getAttribute", "(", "\"scope\"", ")", ";", "if", "(", "o", "!=", "null", "&&", "o", "!=", "TagData", ".", "REQUEST_TIME_VALUE", ")", "{", "String", "scope", "=", "Coercion", ".", "toString", "(", "o", ")", ";", "try", "{", "Scope", ".", "getScopeId", "(", "scope", ")", ";", "// Value is OK", "}", "catch", "(", "JspTagException", "err", ")", "{", "messages", "=", "MinimalList", ".", "add", "(", "messages", ",", "new", "ValidationMessage", "(", "data", ".", "getId", "(", ")", ",", "err", ".", "getMessage", "(", ")", ")", ")", ";", "}", "}", "return", "messages", ";", "}" ]
Checks that a scope is a valid. @see Scope for supported values. @param message the list of messages to add to, maybe <code>null</code> @return the list of messages. A new list will have been created if the <code>message</code> parameter was <code>null</code> @see PropertyUtils#getScope(java.lang.String)
[ "Checks", "that", "a", "scope", "is", "a", "valid", "." ]
5670eba8485196bd42d31d3ff09a42deacb025f8
https://github.com/aoindustries/ao-taglib/blob/5670eba8485196bd42d31d3ff09a42deacb025f8/src/main/java/com/aoindustries/taglib/TeiUtils.java#L91-L112
train
venkatramanm/common
src/main/java/com/venky/geo/GeoDistance.java
GeoDistance.distanceKms
public static double distanceKms(BigDecimal lat1, BigDecimal lng1, BigDecimal lat2, BigDecimal lng2 ){ return new GeoCoordinate(lat1, lng1).distanceTo(new GeoCoordinate(lat2, lng2)); }
java
public static double distanceKms(BigDecimal lat1, BigDecimal lng1, BigDecimal lat2, BigDecimal lng2 ){ return new GeoCoordinate(lat1, lng1).distanceTo(new GeoCoordinate(lat2, lng2)); }
[ "public", "static", "double", "distanceKms", "(", "BigDecimal", "lat1", ",", "BigDecimal", "lng1", ",", "BigDecimal", "lat2", ",", "BigDecimal", "lng2", ")", "{", "return", "new", "GeoCoordinate", "(", "lat1", ",", "lng1", ")", ".", "distanceTo", "(", "new", "GeoCoordinate", "(", "lat2", ",", "lng2", ")", ")", ";", "}" ]
Equitorial Radius of Earth.
[ "Equitorial", "Radius", "of", "Earth", "." ]
b89583efd674f73cf4c04927300a9ea6e49a3e9f
https://github.com/venkatramanm/common/blob/b89583efd674f73cf4c04927300a9ea6e49a3e9f/src/main/java/com/venky/geo/GeoDistance.java#L15-L17
train
mbizhani/Adroit
src/main/java/org/devocative/adroit/obuilder/ObjectBuilder.java
ObjectBuilder.map
public static <K, V> MapBuilder<K, V> map(Map<K, V> instance) { return new MapBuilder<>(instance); }
java
public static <K, V> MapBuilder<K, V> map(Map<K, V> instance) { return new MapBuilder<>(instance); }
[ "public", "static", "<", "K", ",", "V", ">", "MapBuilder", "<", "K", ",", "V", ">", "map", "(", "Map", "<", "K", ",", "V", ">", "instance", ")", "{", "return", "new", "MapBuilder", "<>", "(", "instance", ")", ";", "}" ]
Creates a MapBuilder around the passed instance @param instance @param <K> the key type @param <V> the value type @return a MapBuilder object for method chaining
[ "Creates", "a", "MapBuilder", "around", "the", "passed", "instance" ]
0d76dbd549dde23c009192919e6c256acffb1e41
https://github.com/mbizhani/Adroit/blob/0d76dbd549dde23c009192919e6c256acffb1e41/src/main/java/org/devocative/adroit/obuilder/ObjectBuilder.java#L29-L31
train
maochen/NLP
CoreNLP-NLP/src/main/java/org/maochen/nlp/ml/util/CrossValidation.java
CrossValidation.run
public void run(final List<Tuple> data) { List<Tuple> dataCopy = new ArrayList<>(data); this.labels = data.parallelStream().map(x -> x.label).collect(Collectors.toSet()); if (shuffleData) { Collections.shuffle(dataCopy); } int chunkSize = data.size() / nfold; int reminder = data.size() % chunkSize; for (int i = data.size() - 1; i > data.size() - 1 - reminder; i--) { LOG.info("Dropping the tail id: " + data.get(i).id); } for (int i = 0; i < nfold; i++) { System.err.println("Cross validation round " + (i + 1) + "/" + nfold); List<Tuple> testing = new ArrayList<>(data.subList(i, i + chunkSize)); List<Tuple> training = new ArrayList<>(data.subList(0, i)); training.addAll(data.subList(i + chunkSize, data.size())); eval(training, testing, i); } }
java
public void run(final List<Tuple> data) { List<Tuple> dataCopy = new ArrayList<>(data); this.labels = data.parallelStream().map(x -> x.label).collect(Collectors.toSet()); if (shuffleData) { Collections.shuffle(dataCopy); } int chunkSize = data.size() / nfold; int reminder = data.size() % chunkSize; for (int i = data.size() - 1; i > data.size() - 1 - reminder; i--) { LOG.info("Dropping the tail id: " + data.get(i).id); } for (int i = 0; i < nfold; i++) { System.err.println("Cross validation round " + (i + 1) + "/" + nfold); List<Tuple> testing = new ArrayList<>(data.subList(i, i + chunkSize)); List<Tuple> training = new ArrayList<>(data.subList(0, i)); training.addAll(data.subList(i + chunkSize, data.size())); eval(training, testing, i); } }
[ "public", "void", "run", "(", "final", "List", "<", "Tuple", ">", "data", ")", "{", "List", "<", "Tuple", ">", "dataCopy", "=", "new", "ArrayList", "<>", "(", "data", ")", ";", "this", ".", "labels", "=", "data", ".", "parallelStream", "(", ")", ".", "map", "(", "x", "->", "x", ".", "label", ")", ".", "collect", "(", "Collectors", ".", "toSet", "(", ")", ")", ";", "if", "(", "shuffleData", ")", "{", "Collections", ".", "shuffle", "(", "dataCopy", ")", ";", "}", "int", "chunkSize", "=", "data", ".", "size", "(", ")", "/", "nfold", ";", "int", "reminder", "=", "data", ".", "size", "(", ")", "%", "chunkSize", ";", "for", "(", "int", "i", "=", "data", ".", "size", "(", ")", "-", "1", ";", "i", ">", "data", ".", "size", "(", ")", "-", "1", "-", "reminder", ";", "i", "--", ")", "{", "LOG", ".", "info", "(", "\"Dropping the tail id: \"", "+", "data", ".", "get", "(", "i", ")", ".", "id", ")", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "nfold", ";", "i", "++", ")", "{", "System", ".", "err", ".", "println", "(", "\"Cross validation round \"", "+", "(", "i", "+", "1", ")", "+", "\"/\"", "+", "nfold", ")", ";", "List", "<", "Tuple", ">", "testing", "=", "new", "ArrayList", "<>", "(", "data", ".", "subList", "(", "i", ",", "i", "+", "chunkSize", ")", ")", ";", "List", "<", "Tuple", ">", "training", "=", "new", "ArrayList", "<>", "(", "data", ".", "subList", "(", "0", ",", "i", ")", ")", ";", "training", ".", "addAll", "(", "data", ".", "subList", "(", "i", "+", "chunkSize", ",", "data", ".", "size", "(", ")", ")", ")", ";", "eval", "(", "training", ",", "testing", ",", "i", ")", ";", "}", "}" ]
Cross validation. @param data whole testing data collection
[ "Cross", "validation", "." ]
38ae7b384d5295334d9efa9dc4cd901b19d9c27e
https://github.com/maochen/NLP/blob/38ae7b384d5295334d9efa9dc4cd901b19d9c27e/CoreNLP-NLP/src/main/java/org/maochen/nlp/ml/util/CrossValidation.java#L80-L103
train
maochen/NLP
CoreNLP-NLP/src/main/java/org/maochen/nlp/ml/util/CrossValidation.java
CrossValidation.eval
private void eval(List<Tuple> training, List<Tuple> testing, int nfold) { classifier.train(training); for (Tuple tuple : testing) { String actual = classifier.predict(tuple).entrySet().stream() .max((e1, e2) -> e1.getValue().compareTo(e2.getValue())) .map(Map.Entry::getKey).orElse(StringUtils.EMPTY); updateScore(tuple, actual, nfold); } }
java
private void eval(List<Tuple> training, List<Tuple> testing, int nfold) { classifier.train(training); for (Tuple tuple : testing) { String actual = classifier.predict(tuple).entrySet().stream() .max((e1, e2) -> e1.getValue().compareTo(e2.getValue())) .map(Map.Entry::getKey).orElse(StringUtils.EMPTY); updateScore(tuple, actual, nfold); } }
[ "private", "void", "eval", "(", "List", "<", "Tuple", ">", "training", ",", "List", "<", "Tuple", ">", "testing", ",", "int", "nfold", ")", "{", "classifier", ".", "train", "(", "training", ")", ";", "for", "(", "Tuple", "tuple", ":", "testing", ")", "{", "String", "actual", "=", "classifier", ".", "predict", "(", "tuple", ")", ".", "entrySet", "(", ")", ".", "stream", "(", ")", ".", "max", "(", "(", "e1", ",", "e2", ")", "->", "e1", ".", "getValue", "(", ")", ".", "compareTo", "(", "e2", ".", "getValue", "(", ")", ")", ")", ".", "map", "(", "Map", ".", "Entry", "::", "getKey", ")", ".", "orElse", "(", "StringUtils", ".", "EMPTY", ")", ";", "updateScore", "(", "tuple", ",", "actual", ",", "nfold", ")", ";", "}", "}" ]
This is for one fold.
[ "This", "is", "for", "one", "fold", "." ]
38ae7b384d5295334d9efa9dc4cd901b19d9c27e
https://github.com/maochen/NLP/blob/38ae7b384d5295334d9efa9dc4cd901b19d9c27e/CoreNLP-NLP/src/main/java/org/maochen/nlp/ml/util/CrossValidation.java#L106-L115
train
aoindustries/ao-servlet-filter
src/main/java/com/aoindustries/servlet/filter/StripInvalidXmlCharactersFilter.java
StripInvalidXmlCharactersFilter.filter
private static String filter(String s) { int len = s.length(); StringBuilder filtered = new StringBuilder(len); int pos = 0; while(pos < len) { char ch1 = s.charAt(pos++); if(Character.isHighSurrogate(ch1)) { // Handle surrogates if(pos < len) { char ch2 = s.charAt(pos++); if(Character.isLowSurrogate(ch2)) { if(isValidCharacter(Character.toCodePoint(ch1, ch2))) { filtered.append(ch1).append(ch2); } } else { // High surrogate not followed by low surrogate, invalid } } else { // High surrogate at end of string, invalid } } else { // Not surrogates if(isValidCharacter(ch1)) { filtered.append(ch1); } } } assert filtered.length() <= len; return filtered.length() != len ? filtered.toString() : s; }
java
private static String filter(String s) { int len = s.length(); StringBuilder filtered = new StringBuilder(len); int pos = 0; while(pos < len) { char ch1 = s.charAt(pos++); if(Character.isHighSurrogate(ch1)) { // Handle surrogates if(pos < len) { char ch2 = s.charAt(pos++); if(Character.isLowSurrogate(ch2)) { if(isValidCharacter(Character.toCodePoint(ch1, ch2))) { filtered.append(ch1).append(ch2); } } else { // High surrogate not followed by low surrogate, invalid } } else { // High surrogate at end of string, invalid } } else { // Not surrogates if(isValidCharacter(ch1)) { filtered.append(ch1); } } } assert filtered.length() <= len; return filtered.length() != len ? filtered.toString() : s; }
[ "private", "static", "String", "filter", "(", "String", "s", ")", "{", "int", "len", "=", "s", ".", "length", "(", ")", ";", "StringBuilder", "filtered", "=", "new", "StringBuilder", "(", "len", ")", ";", "int", "pos", "=", "0", ";", "while", "(", "pos", "<", "len", ")", "{", "char", "ch1", "=", "s", ".", "charAt", "(", "pos", "++", ")", ";", "if", "(", "Character", ".", "isHighSurrogate", "(", "ch1", ")", ")", "{", "// Handle surrogates", "if", "(", "pos", "<", "len", ")", "{", "char", "ch2", "=", "s", ".", "charAt", "(", "pos", "++", ")", ";", "if", "(", "Character", ".", "isLowSurrogate", "(", "ch2", ")", ")", "{", "if", "(", "isValidCharacter", "(", "Character", ".", "toCodePoint", "(", "ch1", ",", "ch2", ")", ")", ")", "{", "filtered", ".", "append", "(", "ch1", ")", ".", "append", "(", "ch2", ")", ";", "}", "}", "else", "{", "// High surrogate not followed by low surrogate, invalid", "}", "}", "else", "{", "// High surrogate at end of string, invalid", "}", "}", "else", "{", "// Not surrogates", "if", "(", "isValidCharacter", "(", "ch1", ")", ")", "{", "filtered", ".", "append", "(", "ch1", ")", ";", "}", "}", "}", "assert", "filtered", ".", "length", "(", ")", "<=", "len", ";", "return", "filtered", ".", "length", "(", ")", "!=", "len", "?", "filtered", ".", "toString", "(", ")", ":", "s", ";", "}" ]
Filters invalid XML characters.
[ "Filters", "invalid", "XML", "characters", "." ]
ee1fb95e36b0620949e9cb8ee863ac37fb9e4f2b
https://github.com/aoindustries/ao-servlet-filter/blob/ee1fb95e36b0620949e9cb8ee863ac37fb9e4f2b/src/main/java/com/aoindustries/servlet/filter/StripInvalidXmlCharactersFilter.java#L114-L143
train
aoindustries/ao-taglib
src/main/java/com/aoindustries/taglib/AutoEncodingFilteredTag.java
AutoEncodingFilteredTag.doTag
protected void doTag(Writer out) throws JspException, IOException { JspFragment body = getJspBody(); if(body!=null) { // Check for JspWriter to avoid a JspWriter wrapping a JspWriter body.invoke( (out instanceof JspWriter) ? null : out ); } }
java
protected void doTag(Writer out) throws JspException, IOException { JspFragment body = getJspBody(); if(body!=null) { // Check for JspWriter to avoid a JspWriter wrapping a JspWriter body.invoke( (out instanceof JspWriter) ? null : out ); } }
[ "protected", "void", "doTag", "(", "Writer", "out", ")", "throws", "JspException", ",", "IOException", "{", "JspFragment", "body", "=", "getJspBody", "(", ")", ";", "if", "(", "body", "!=", "null", ")", "{", "// Check for JspWriter to avoid a JspWriter wrapping a JspWriter", "body", ".", "invoke", "(", "(", "out", "instanceof", "JspWriter", ")", "?", "null", ":", "out", ")", ";", "}", "}" ]
Once the out JspWriter has been replaced to output the proper content type, this version of invoke is called. @param out the output. If passed-through, this will be a <code>JspWriter</code> @implSpec This default implementation invokes the jsp body, if present. @throws javax.servlet.jsp.JspTagException
[ "Once", "the", "out", "JspWriter", "has", "been", "replaced", "to", "output", "the", "proper", "content", "type", "this", "version", "of", "invoke", "is", "called", "." ]
5670eba8485196bd42d31d3ff09a42deacb025f8
https://github.com/aoindustries/ao-taglib/blob/5670eba8485196bd42d31d3ff09a42deacb025f8/src/main/java/com/aoindustries/taglib/AutoEncodingFilteredTag.java#L185-L195
train
maochen/NLP
CoreNLP-NLP/src/main/java/org/maochen/nlp/app/relationextract/QuestionRelationExtractor.java
QuestionRelationExtractor.extractPolar
private static BinRelation extractPolar(DTree tree) { // TODO: HERE. DNode rootVerb = tree.getRoots().get(0); // rootVerb.getChildren(). BinRelation binRelation = new BinRelation(); return binRelation; }
java
private static BinRelation extractPolar(DTree tree) { // TODO: HERE. DNode rootVerb = tree.getRoots().get(0); // rootVerb.getChildren(). BinRelation binRelation = new BinRelation(); return binRelation; }
[ "private", "static", "BinRelation", "extractPolar", "(", "DTree", "tree", ")", "{", "// TODO: HERE.", "DNode", "rootVerb", "=", "tree", ".", "getRoots", "(", ")", ".", "get", "(", "0", ")", ";", "// rootVerb.getChildren().", "BinRelation", "binRelation", "=", "new", "BinRelation", "(", ")", ";", "return", "binRelation", ";", "}" ]
POLAR doesnt have wildcard.
[ "POLAR", "doesnt", "have", "wildcard", "." ]
38ae7b384d5295334d9efa9dc4cd901b19d9c27e
https://github.com/maochen/NLP/blob/38ae7b384d5295334d9efa9dc4cd901b19d9c27e/CoreNLP-NLP/src/main/java/org/maochen/nlp/app/relationextract/QuestionRelationExtractor.java#L80-L86
train
maochen/NLP
CoreNLP-NLP/src/main/java/org/maochen/nlp/ml/classifier/maxent/eventstream/StringEventStream.java
StringEventStream.createEvent
private Event createEvent(String obs) { int lastSpace = obs.lastIndexOf(StringUtils.SPACE); Event event = null; if (lastSpace != -1) { String label = obs.substring(lastSpace + 1); String[] contexts = obs.substring(0, lastSpace).split("\\s+"); // Split name and value float[] values = RealValueFileEventStream.parseContexts(contexts); // Label, feature name, feature value event = new Event(label, contexts, values); } return event; }
java
private Event createEvent(String obs) { int lastSpace = obs.lastIndexOf(StringUtils.SPACE); Event event = null; if (lastSpace != -1) { String label = obs.substring(lastSpace + 1); String[] contexts = obs.substring(0, lastSpace).split("\\s+"); // Split name and value float[] values = RealValueFileEventStream.parseContexts(contexts); // Label, feature name, feature value event = new Event(label, contexts, values); } return event; }
[ "private", "Event", "createEvent", "(", "String", "obs", ")", "{", "int", "lastSpace", "=", "obs", ".", "lastIndexOf", "(", "StringUtils", ".", "SPACE", ")", ";", "Event", "event", "=", "null", ";", "if", "(", "lastSpace", "!=", "-", "1", ")", "{", "String", "label", "=", "obs", ".", "substring", "(", "lastSpace", "+", "1", ")", ";", "String", "[", "]", "contexts", "=", "obs", ".", "substring", "(", "0", ",", "lastSpace", ")", ".", "split", "(", "\"\\\\s+\"", ")", ";", "// Split name and value", "float", "[", "]", "values", "=", "RealValueFileEventStream", ".", "parseContexts", "(", "contexts", ")", ";", "// Label, feature name, feature value", "event", "=", "new", "Event", "(", "label", ",", "contexts", ",", "values", ")", ";", "}", "return", "event", ";", "}" ]
away pdiff=9.6875 ptwins=0.5 lose
[ "away", "pdiff", "=", "9", ".", "6875", "ptwins", "=", "0", ".", "5", "lose" ]
38ae7b384d5295334d9efa9dc4cd901b19d9c27e
https://github.com/maochen/NLP/blob/38ae7b384d5295334d9efa9dc4cd901b19d9c27e/CoreNLP-NLP/src/main/java/org/maochen/nlp/ml/classifier/maxent/eventstream/StringEventStream.java#L19-L33
train
maochen/NLP
CoreNLP-NLP/src/main/java/org/maochen/nlp/parser/stanford/StanfordParser.java
StanfordParser.stanfordTokenize
public static List<CoreLabel> stanfordTokenize(String str) { TokenizerFactory<? extends HasWord> tf = PTBTokenizer.coreLabelFactory(); // ptb3Escaping=false -> '(' not converted as '-LRB-', Dont use it, it will cause Dependency resolution err. Tokenizer<? extends HasWord> originalWordTokenizer = tf.getTokenizer(new StringReader(str), "ptb3Escaping=false"); Tokenizer<? extends HasWord> tokenizer = tf.getTokenizer(new StringReader(str)); List<? extends HasWord> originalTokens = originalWordTokenizer.tokenize(); List<? extends HasWord> tokens = tokenizer.tokenize(); // Curse you Stanford! List<CoreLabel> coreLabels = new ArrayList<>(tokens.size()); for (int i = 0; i < tokens.size(); i++) { CoreLabel coreLabel = new CoreLabel(); coreLabel.setWord(tokens.get(i).word()); coreLabel.setOriginalText(originalTokens.get(i).word()); coreLabel.setValue(tokens.get(i).word()); coreLabel.setBeginPosition(((CoreLabel) tokens.get(i)).beginPosition()); coreLabel.setEndPosition(((CoreLabel) tokens.get(i)).endPosition()); coreLabels.add(coreLabel); } return coreLabels; }
java
public static List<CoreLabel> stanfordTokenize(String str) { TokenizerFactory<? extends HasWord> tf = PTBTokenizer.coreLabelFactory(); // ptb3Escaping=false -> '(' not converted as '-LRB-', Dont use it, it will cause Dependency resolution err. Tokenizer<? extends HasWord> originalWordTokenizer = tf.getTokenizer(new StringReader(str), "ptb3Escaping=false"); Tokenizer<? extends HasWord> tokenizer = tf.getTokenizer(new StringReader(str)); List<? extends HasWord> originalTokens = originalWordTokenizer.tokenize(); List<? extends HasWord> tokens = tokenizer.tokenize(); // Curse you Stanford! List<CoreLabel> coreLabels = new ArrayList<>(tokens.size()); for (int i = 0; i < tokens.size(); i++) { CoreLabel coreLabel = new CoreLabel(); coreLabel.setWord(tokens.get(i).word()); coreLabel.setOriginalText(originalTokens.get(i).word()); coreLabel.setValue(tokens.get(i).word()); coreLabel.setBeginPosition(((CoreLabel) tokens.get(i)).beginPosition()); coreLabel.setEndPosition(((CoreLabel) tokens.get(i)).endPosition()); coreLabels.add(coreLabel); } return coreLabels; }
[ "public", "static", "List", "<", "CoreLabel", ">", "stanfordTokenize", "(", "String", "str", ")", "{", "TokenizerFactory", "<", "?", "extends", "HasWord", ">", "tf", "=", "PTBTokenizer", ".", "coreLabelFactory", "(", ")", ";", "// ptb3Escaping=false -> '(' not converted as '-LRB-', Dont use it, it will cause Dependency resolution err.", "Tokenizer", "<", "?", "extends", "HasWord", ">", "originalWordTokenizer", "=", "tf", ".", "getTokenizer", "(", "new", "StringReader", "(", "str", ")", ",", "\"ptb3Escaping=false\"", ")", ";", "Tokenizer", "<", "?", "extends", "HasWord", ">", "tokenizer", "=", "tf", ".", "getTokenizer", "(", "new", "StringReader", "(", "str", ")", ")", ";", "List", "<", "?", "extends", "HasWord", ">", "originalTokens", "=", "originalWordTokenizer", ".", "tokenize", "(", ")", ";", "List", "<", "?", "extends", "HasWord", ">", "tokens", "=", "tokenizer", ".", "tokenize", "(", ")", ";", "// Curse you Stanford!", "List", "<", "CoreLabel", ">", "coreLabels", "=", "new", "ArrayList", "<>", "(", "tokens", ".", "size", "(", ")", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "tokens", ".", "size", "(", ")", ";", "i", "++", ")", "{", "CoreLabel", "coreLabel", "=", "new", "CoreLabel", "(", ")", ";", "coreLabel", ".", "setWord", "(", "tokens", ".", "get", "(", "i", ")", ".", "word", "(", ")", ")", ";", "coreLabel", ".", "setOriginalText", "(", "originalTokens", ".", "get", "(", "i", ")", ".", "word", "(", ")", ")", ";", "coreLabel", ".", "setValue", "(", "tokens", ".", "get", "(", "i", ")", ".", "word", "(", ")", ")", ";", "coreLabel", ".", "setBeginPosition", "(", "(", "(", "CoreLabel", ")", "tokens", ".", "get", "(", "i", ")", ")", ".", "beginPosition", "(", ")", ")", ";", "coreLabel", ".", "setEndPosition", "(", "(", "(", "CoreLabel", ")", "tokens", ".", "get", "(", "i", ")", ")", ".", "endPosition", "(", ")", ")", ";", "coreLabels", ".", "add", "(", "coreLabel", ")", ";", "}", "return", "coreLabels", ";", "}" ]
1. Tokenize
[ "1", ".", "Tokenize" ]
38ae7b384d5295334d9efa9dc4cd901b19d9c27e
https://github.com/maochen/NLP/blob/38ae7b384d5295334d9efa9dc4cd901b19d9c27e/CoreNLP-NLP/src/main/java/org/maochen/nlp/parser/stanford/StanfordParser.java#L51-L74
train
maochen/NLP
CoreNLP-NLP/src/main/java/org/maochen/nlp/parser/stanford/StanfordParser.java
StanfordParser.tagPOS
public void tagPOS(List<CoreLabel> tokens) { if (posTagger == null) { if (POS_TAGGER_MODEL_PATH == null) { LOG.warn("Default POS Tagger model"); POS_TAGGER_MODEL_PATH = StanfordConst.STANFORD_DEFAULT_POS_EN_MODEL; } posTagger = new MaxentTagger(POS_TAGGER_MODEL_PATH); } List<TaggedWord> posList = posTagger.tagSentence(tokens); for (int i = 0; i < tokens.size(); i++) { String pos = posList.get(i).tag(); tokens.get(i).setTag(pos); } }
java
public void tagPOS(List<CoreLabel> tokens) { if (posTagger == null) { if (POS_TAGGER_MODEL_PATH == null) { LOG.warn("Default POS Tagger model"); POS_TAGGER_MODEL_PATH = StanfordConst.STANFORD_DEFAULT_POS_EN_MODEL; } posTagger = new MaxentTagger(POS_TAGGER_MODEL_PATH); } List<TaggedWord> posList = posTagger.tagSentence(tokens); for (int i = 0; i < tokens.size(); i++) { String pos = posList.get(i).tag(); tokens.get(i).setTag(pos); } }
[ "public", "void", "tagPOS", "(", "List", "<", "CoreLabel", ">", "tokens", ")", "{", "if", "(", "posTagger", "==", "null", ")", "{", "if", "(", "POS_TAGGER_MODEL_PATH", "==", "null", ")", "{", "LOG", ".", "warn", "(", "\"Default POS Tagger model\"", ")", ";", "POS_TAGGER_MODEL_PATH", "=", "StanfordConst", ".", "STANFORD_DEFAULT_POS_EN_MODEL", ";", "}", "posTagger", "=", "new", "MaxentTagger", "(", "POS_TAGGER_MODEL_PATH", ")", ";", "}", "List", "<", "TaggedWord", ">", "posList", "=", "posTagger", ".", "tagSentence", "(", "tokens", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "tokens", ".", "size", "(", ")", ";", "i", "++", ")", "{", "String", "pos", "=", "posList", ".", "get", "(", "i", ")", ".", "tag", "(", ")", ";", "tokens", ".", "get", "(", "i", ")", ".", "setTag", "(", "pos", ")", ";", "}", "}" ]
2. POS Tagger
[ "2", ".", "POS", "Tagger" ]
38ae7b384d5295334d9efa9dc4cd901b19d9c27e
https://github.com/maochen/NLP/blob/38ae7b384d5295334d9efa9dc4cd901b19d9c27e/CoreNLP-NLP/src/main/java/org/maochen/nlp/parser/stanford/StanfordParser.java#L77-L90
train
maochen/NLP
CoreNLP-NLP/src/main/java/org/maochen/nlp/parser/stanford/StanfordParser.java
StanfordParser.tagLemma
public static void tagLemma(List<CoreLabel> tokens) { // Not sure if this can be static. Morphology morpha = new Morphology(); for (CoreLabel token : tokens) { String lemma; String pos = token.tag(); if (pos.equals(LangLib.POS_NNPS)) { pos = LangLib.POS_NNS; } if (pos.length() > 0) { String phrasalVerb = phrasalVerb(morpha, token.word(), pos); if (phrasalVerb == null) { lemma = morpha.lemma(token.word(), pos); } else { lemma = phrasalVerb; } } else { lemma = morpha.stem(token.word()); } // LGLibEn.convertUnI only accept cap I. if (lemma.equals("i")) { lemma = "I"; } token.setLemma(lemma); } }
java
public static void tagLemma(List<CoreLabel> tokens) { // Not sure if this can be static. Morphology morpha = new Morphology(); for (CoreLabel token : tokens) { String lemma; String pos = token.tag(); if (pos.equals(LangLib.POS_NNPS)) { pos = LangLib.POS_NNS; } if (pos.length() > 0) { String phrasalVerb = phrasalVerb(morpha, token.word(), pos); if (phrasalVerb == null) { lemma = morpha.lemma(token.word(), pos); } else { lemma = phrasalVerb; } } else { lemma = morpha.stem(token.word()); } // LGLibEn.convertUnI only accept cap I. if (lemma.equals("i")) { lemma = "I"; } token.setLemma(lemma); } }
[ "public", "static", "void", "tagLemma", "(", "List", "<", "CoreLabel", ">", "tokens", ")", "{", "// Not sure if this can be static.", "Morphology", "morpha", "=", "new", "Morphology", "(", ")", ";", "for", "(", "CoreLabel", "token", ":", "tokens", ")", "{", "String", "lemma", ";", "String", "pos", "=", "token", ".", "tag", "(", ")", ";", "if", "(", "pos", ".", "equals", "(", "LangLib", ".", "POS_NNPS", ")", ")", "{", "pos", "=", "LangLib", ".", "POS_NNS", ";", "}", "if", "(", "pos", ".", "length", "(", ")", ">", "0", ")", "{", "String", "phrasalVerb", "=", "phrasalVerb", "(", "morpha", ",", "token", ".", "word", "(", ")", ",", "pos", ")", ";", "if", "(", "phrasalVerb", "==", "null", ")", "{", "lemma", "=", "morpha", ".", "lemma", "(", "token", ".", "word", "(", ")", ",", "pos", ")", ";", "}", "else", "{", "lemma", "=", "phrasalVerb", ";", "}", "}", "else", "{", "lemma", "=", "morpha", ".", "stem", "(", "token", ".", "word", "(", ")", ")", ";", "}", "// LGLibEn.convertUnI only accept cap I.", "if", "(", "lemma", ".", "equals", "(", "\"i\"", ")", ")", "{", "lemma", "=", "\"I\"", ";", "}", "token", ".", "setLemma", "(", "lemma", ")", ";", "}", "}" ]
3. Lemma Tagger
[ "3", ".", "Lemma", "Tagger" ]
38ae7b384d5295334d9efa9dc4cd901b19d9c27e
https://github.com/maochen/NLP/blob/38ae7b384d5295334d9efa9dc4cd901b19d9c27e/CoreNLP-NLP/src/main/java/org/maochen/nlp/parser/stanford/StanfordParser.java#L118-L146
train
maochen/NLP
CoreNLP-NLP/src/main/java/org/maochen/nlp/parser/stanford/StanfordParser.java
StanfordParser.tagNamedEntity
public synchronized void tagNamedEntity(List<CoreLabel> tokens) { boolean isPOSTagged = tokens.parallelStream().filter(x -> x.tag() == null).count() == 0; if (!isPOSTagged) { throw new RuntimeException("Please Run POS Tagger before Named Entity tagger."); } if (ners != null) { try { ners.stream().forEach(ner -> ner.classify(tokens)); } catch (Exception e) { /* edu.stanford.nlp.util.RuntimeInterruptedException: java.lang.InterruptedException at edu.stanford.nlp.util.HashIndex.addToIndex(HashIndex.java:173) ~[stanford-corenlp-3.5.2.jar:3.5.2] at edu.stanford.nlp.ling.tokensregex.SequenceMatcher$BranchStates.newBid(SequenceMatcher.java:902) ~[stanford-corenlp-3.5.2.jar:3.5.2] at edu.stanford.nlp.ling.tokensregex.SequenceMatcher$MatchedStates.<init>(SequenceMatcher.java:1288) ~[stanford-corenlp-3.5.2.jar:3.5.2] at edu.stanford.nlp.ling.tokensregex.SequenceMatcher.getStartStates(SequenceMatcher.java:709) ~[stanford-corenlp-3.5.2.jar:3.5.2] at edu.stanford.nlp.ling.tokensregex.SequenceMatcher.findMatchStartBacktracking(SequenceMatcher.java:488) ~[stanford-corenlp-3.5.2.jar:3.5.2] at edu.stanford.nlp.ling.tokensregex.SequenceMatcher.findMatchStart(SequenceMatcher.java:449) ~[stanford-corenlp-3.5.2.jar:3.5.2] at edu.stanford.nlp.ling.tokensregex.SequenceMatcher.find(SequenceMatcher.java:341) ~[stanford-corenlp-3.5.2.jar:3.5.2] at edu.stanford.nlp.ling.tokensregex.SequenceMatcher.findNextNonOverlapping(SequenceMatcher.java:365) ~[stanford-corenlp-3.5.2.jar:3.5.2] at edu.stanford.nlp.ling.tokensregex.SequenceMatcher.find(SequenceMatcher.java:437) ~[stanford-corenlp-3.5.2.jar:3.5.2] at edu.stanford.nlp.ie.NumberNormalizer.findNumbers(NumberNormalizer.java:452) ~[stanford-corenlp-3.5.2.jar:3.5.2] at edu.stanford.nlp.ie.NumberNormalizer.findAndMergeNumbers(NumberNormalizer.java:721) ~[stanford-corenlp-3.5.2.jar:3.5.2] at edu.stanford.nlp.time.TimeExpressionExtractorImpl.extractTimeExpressions(TimeExpressionExtractorImpl.java:184) ~[stanford-corenlp-3.5.2.jar:3.5.2] at edu.stanford.nlp.time.TimeExpressionExtractorImpl.extractTimeExpressions(TimeExpressionExtractorImpl.java:178) ~[stanford-corenlp-3.5.2.jar:3.5.2] at edu.stanford.nlp.time.TimeExpressionExtractorImpl.extractTimeExpressionCoreMaps(TimeExpressionExtractorImpl.java:116) ~[stanford-corenlp-3.5.2.jar:3.5.2] at edu.stanford.nlp.time.TimeExpressionExtractorImpl.extractTimeExpressionCoreMaps(TimeExpressionExtractorImpl.java:104) ~[stanford-corenlp-3.5.2.jar:3.5.2] at edu.stanford.nlp.ie.regexp.NumberSequenceClassifier.runSUTime(NumberSequenceClassifier.java:340) ~[stanford-corenlp-3.5.2.jar:3.5.2] at edu.stanford.nlp.ie.regexp.NumberSequenceClassifier.classifyWithSUTime(NumberSequenceClassifier.java:138) ~[stanford-corenlp-3.5.2.jar:3.5.2] at edu.stanford.nlp.ie.regexp.NumberSequenceClassifier.classifyWithGlobalInformation(NumberSequenceClassifier.java:101) ~[stanford-corenlp-3.5.2.jar:3.5.2] at edu.stanford.nlp.ie.NERClassifierCombiner.recognizeNumberSequences(NERClassifierCombiner.java:267) ~[stanford-corenlp-3.5.2.jar:3.5.2] at edu.stanford.nlp.ie.NERClassifierCombiner.classifyWithGlobalInformation(NERClassifierCombiner.java:231) ~[stanford-corenlp-3.5.2.jar:3.5.2] at edu.stanford.nlp.ie.NERClassifierCombiner.classify(NERClassifierCombiner.java:218) ~[stanford-corenlp-3.5.2.jar:3.5.2] */ LOG.warn("NER Classifier err for: " + tokens.stream().map(CoreLabel::word).collect(Collectors.joining(StringUtils.SPACE))); } } }
java
public synchronized void tagNamedEntity(List<CoreLabel> tokens) { boolean isPOSTagged = tokens.parallelStream().filter(x -> x.tag() == null).count() == 0; if (!isPOSTagged) { throw new RuntimeException("Please Run POS Tagger before Named Entity tagger."); } if (ners != null) { try { ners.stream().forEach(ner -> ner.classify(tokens)); } catch (Exception e) { /* edu.stanford.nlp.util.RuntimeInterruptedException: java.lang.InterruptedException at edu.stanford.nlp.util.HashIndex.addToIndex(HashIndex.java:173) ~[stanford-corenlp-3.5.2.jar:3.5.2] at edu.stanford.nlp.ling.tokensregex.SequenceMatcher$BranchStates.newBid(SequenceMatcher.java:902) ~[stanford-corenlp-3.5.2.jar:3.5.2] at edu.stanford.nlp.ling.tokensregex.SequenceMatcher$MatchedStates.<init>(SequenceMatcher.java:1288) ~[stanford-corenlp-3.5.2.jar:3.5.2] at edu.stanford.nlp.ling.tokensregex.SequenceMatcher.getStartStates(SequenceMatcher.java:709) ~[stanford-corenlp-3.5.2.jar:3.5.2] at edu.stanford.nlp.ling.tokensregex.SequenceMatcher.findMatchStartBacktracking(SequenceMatcher.java:488) ~[stanford-corenlp-3.5.2.jar:3.5.2] at edu.stanford.nlp.ling.tokensregex.SequenceMatcher.findMatchStart(SequenceMatcher.java:449) ~[stanford-corenlp-3.5.2.jar:3.5.2] at edu.stanford.nlp.ling.tokensregex.SequenceMatcher.find(SequenceMatcher.java:341) ~[stanford-corenlp-3.5.2.jar:3.5.2] at edu.stanford.nlp.ling.tokensregex.SequenceMatcher.findNextNonOverlapping(SequenceMatcher.java:365) ~[stanford-corenlp-3.5.2.jar:3.5.2] at edu.stanford.nlp.ling.tokensregex.SequenceMatcher.find(SequenceMatcher.java:437) ~[stanford-corenlp-3.5.2.jar:3.5.2] at edu.stanford.nlp.ie.NumberNormalizer.findNumbers(NumberNormalizer.java:452) ~[stanford-corenlp-3.5.2.jar:3.5.2] at edu.stanford.nlp.ie.NumberNormalizer.findAndMergeNumbers(NumberNormalizer.java:721) ~[stanford-corenlp-3.5.2.jar:3.5.2] at edu.stanford.nlp.time.TimeExpressionExtractorImpl.extractTimeExpressions(TimeExpressionExtractorImpl.java:184) ~[stanford-corenlp-3.5.2.jar:3.5.2] at edu.stanford.nlp.time.TimeExpressionExtractorImpl.extractTimeExpressions(TimeExpressionExtractorImpl.java:178) ~[stanford-corenlp-3.5.2.jar:3.5.2] at edu.stanford.nlp.time.TimeExpressionExtractorImpl.extractTimeExpressionCoreMaps(TimeExpressionExtractorImpl.java:116) ~[stanford-corenlp-3.5.2.jar:3.5.2] at edu.stanford.nlp.time.TimeExpressionExtractorImpl.extractTimeExpressionCoreMaps(TimeExpressionExtractorImpl.java:104) ~[stanford-corenlp-3.5.2.jar:3.5.2] at edu.stanford.nlp.ie.regexp.NumberSequenceClassifier.runSUTime(NumberSequenceClassifier.java:340) ~[stanford-corenlp-3.5.2.jar:3.5.2] at edu.stanford.nlp.ie.regexp.NumberSequenceClassifier.classifyWithSUTime(NumberSequenceClassifier.java:138) ~[stanford-corenlp-3.5.2.jar:3.5.2] at edu.stanford.nlp.ie.regexp.NumberSequenceClassifier.classifyWithGlobalInformation(NumberSequenceClassifier.java:101) ~[stanford-corenlp-3.5.2.jar:3.5.2] at edu.stanford.nlp.ie.NERClassifierCombiner.recognizeNumberSequences(NERClassifierCombiner.java:267) ~[stanford-corenlp-3.5.2.jar:3.5.2] at edu.stanford.nlp.ie.NERClassifierCombiner.classifyWithGlobalInformation(NERClassifierCombiner.java:231) ~[stanford-corenlp-3.5.2.jar:3.5.2] at edu.stanford.nlp.ie.NERClassifierCombiner.classify(NERClassifierCombiner.java:218) ~[stanford-corenlp-3.5.2.jar:3.5.2] */ LOG.warn("NER Classifier err for: " + tokens.stream().map(CoreLabel::word).collect(Collectors.joining(StringUtils.SPACE))); } } }
[ "public", "synchronized", "void", "tagNamedEntity", "(", "List", "<", "CoreLabel", ">", "tokens", ")", "{", "boolean", "isPOSTagged", "=", "tokens", ".", "parallelStream", "(", ")", ".", "filter", "(", "x", "->", "x", ".", "tag", "(", ")", "==", "null", ")", ".", "count", "(", ")", "==", "0", ";", "if", "(", "!", "isPOSTagged", ")", "{", "throw", "new", "RuntimeException", "(", "\"Please Run POS Tagger before Named Entity tagger.\"", ")", ";", "}", "if", "(", "ners", "!=", "null", ")", "{", "try", "{", "ners", ".", "stream", "(", ")", ".", "forEach", "(", "ner", "->", "ner", ".", "classify", "(", "tokens", ")", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "/* edu.stanford.nlp.util.RuntimeInterruptedException: java.lang.InterruptedException\n at edu.stanford.nlp.util.HashIndex.addToIndex(HashIndex.java:173) ~[stanford-corenlp-3.5.2.jar:3.5.2]\n at edu.stanford.nlp.ling.tokensregex.SequenceMatcher$BranchStates.newBid(SequenceMatcher.java:902) ~[stanford-corenlp-3.5.2.jar:3.5.2]\n at edu.stanford.nlp.ling.tokensregex.SequenceMatcher$MatchedStates.<init>(SequenceMatcher.java:1288) ~[stanford-corenlp-3.5.2.jar:3.5.2]\n at edu.stanford.nlp.ling.tokensregex.SequenceMatcher.getStartStates(SequenceMatcher.java:709) ~[stanford-corenlp-3.5.2.jar:3.5.2]\n at edu.stanford.nlp.ling.tokensregex.SequenceMatcher.findMatchStartBacktracking(SequenceMatcher.java:488) ~[stanford-corenlp-3.5.2.jar:3.5.2]\n at edu.stanford.nlp.ling.tokensregex.SequenceMatcher.findMatchStart(SequenceMatcher.java:449) ~[stanford-corenlp-3.5.2.jar:3.5.2]\n at edu.stanford.nlp.ling.tokensregex.SequenceMatcher.find(SequenceMatcher.java:341) ~[stanford-corenlp-3.5.2.jar:3.5.2]\n at edu.stanford.nlp.ling.tokensregex.SequenceMatcher.findNextNonOverlapping(SequenceMatcher.java:365) ~[stanford-corenlp-3.5.2.jar:3.5.2]\n at edu.stanford.nlp.ling.tokensregex.SequenceMatcher.find(SequenceMatcher.java:437) ~[stanford-corenlp-3.5.2.jar:3.5.2]\n at edu.stanford.nlp.ie.NumberNormalizer.findNumbers(NumberNormalizer.java:452) ~[stanford-corenlp-3.5.2.jar:3.5.2]\n at edu.stanford.nlp.ie.NumberNormalizer.findAndMergeNumbers(NumberNormalizer.java:721) ~[stanford-corenlp-3.5.2.jar:3.5.2]\n at edu.stanford.nlp.time.TimeExpressionExtractorImpl.extractTimeExpressions(TimeExpressionExtractorImpl.java:184) ~[stanford-corenlp-3.5.2.jar:3.5.2]\n at edu.stanford.nlp.time.TimeExpressionExtractorImpl.extractTimeExpressions(TimeExpressionExtractorImpl.java:178) ~[stanford-corenlp-3.5.2.jar:3.5.2]\n at edu.stanford.nlp.time.TimeExpressionExtractorImpl.extractTimeExpressionCoreMaps(TimeExpressionExtractorImpl.java:116) ~[stanford-corenlp-3.5.2.jar:3.5.2]\n at edu.stanford.nlp.time.TimeExpressionExtractorImpl.extractTimeExpressionCoreMaps(TimeExpressionExtractorImpl.java:104) ~[stanford-corenlp-3.5.2.jar:3.5.2]\n at edu.stanford.nlp.ie.regexp.NumberSequenceClassifier.runSUTime(NumberSequenceClassifier.java:340) ~[stanford-corenlp-3.5.2.jar:3.5.2]\n at edu.stanford.nlp.ie.regexp.NumberSequenceClassifier.classifyWithSUTime(NumberSequenceClassifier.java:138) ~[stanford-corenlp-3.5.2.jar:3.5.2]\n at edu.stanford.nlp.ie.regexp.NumberSequenceClassifier.classifyWithGlobalInformation(NumberSequenceClassifier.java:101) ~[stanford-corenlp-3.5.2.jar:3.5.2]\n at edu.stanford.nlp.ie.NERClassifierCombiner.recognizeNumberSequences(NERClassifierCombiner.java:267) ~[stanford-corenlp-3.5.2.jar:3.5.2]\n at edu.stanford.nlp.ie.NERClassifierCombiner.classifyWithGlobalInformation(NERClassifierCombiner.java:231) ~[stanford-corenlp-3.5.2.jar:3.5.2]\n at edu.stanford.nlp.ie.NERClassifierCombiner.classify(NERClassifierCombiner.java:218) ~[stanford-corenlp-3.5.2.jar:3.5.2]\n */", "LOG", ".", "warn", "(", "\"NER Classifier err for: \"", "+", "tokens", ".", "stream", "(", ")", ".", "map", "(", "CoreLabel", "::", "word", ")", ".", "collect", "(", "Collectors", ".", "joining", "(", "StringUtils", ".", "SPACE", ")", ")", ")", ";", "}", "}", "}" ]
NER not thread safe ...
[ "NER", "not", "thread", "safe", "..." ]
38ae7b384d5295334d9efa9dc4cd901b19d9c27e
https://github.com/maochen/NLP/blob/38ae7b384d5295334d9efa9dc4cd901b19d9c27e/CoreNLP-NLP/src/main/java/org/maochen/nlp/parser/stanford/StanfordParser.java#L150-L185
train
crowmagnumb/s6-util
src/main/java/net/crowmagnumb/util/io/ResourceReaderImpl.java
ResourceReaderImpl.getOverrideEntry
private Tuple<String,String> getOverrideEntry( final String key ) { for ( String prefix : _overrides ) { String override = prefix + "." + key; String value = getPropertyValue( override ); if ( value != null ) { return new Tuple<String,String>( override, value ); } } return null; }
java
private Tuple<String,String> getOverrideEntry( final String key ) { for ( String prefix : _overrides ) { String override = prefix + "." + key; String value = getPropertyValue( override ); if ( value != null ) { return new Tuple<String,String>( override, value ); } } return null; }
[ "private", "Tuple", "<", "String", ",", "String", ">", "getOverrideEntry", "(", "final", "String", "key", ")", "{", "for", "(", "String", "prefix", ":", "_overrides", ")", "{", "String", "override", "=", "prefix", "+", "\".\"", "+", "key", ";", "String", "value", "=", "getPropertyValue", "(", "override", ")", ";", "if", "(", "value", "!=", "null", ")", "{", "return", "new", "Tuple", "<", "String", ",", "String", ">", "(", "override", ",", "value", ")", ";", "}", "}", "return", "null", ";", "}" ]
Looks for each instance of "key" in all of the overrides, in order. Does not look for a non-overridden version. @param key @return the first override found, or null if no overrides existed
[ "Looks", "for", "each", "instance", "of", "key", "in", "all", "of", "the", "overrides", "in", "order", ".", "Does", "not", "look", "for", "a", "non", "-", "overridden", "version", "." ]
0f9969bc0809e8a617501fa57c135e9b3984fae0
https://github.com/crowmagnumb/s6-util/blob/0f9969bc0809e8a617501fa57c135e9b3984fae0/src/main/java/net/crowmagnumb/util/io/ResourceReaderImpl.java#L143-L157
train
crowmagnumb/s6-util
src/main/java/net/crowmagnumb/util/io/ResourceReaderImpl.java
ResourceReaderImpl.getEntry
private Tuple<String,String> getEntry( final String key ) { Tuple<String,String> override = getOverrideEntry( key ); if ( override == null ) { String value = getPropertyValue( key ); if ( value != null ) { return new Tuple<String,String>( key, value ); } } return override; }
java
private Tuple<String,String> getEntry( final String key ) { Tuple<String,String> override = getOverrideEntry( key ); if ( override == null ) { String value = getPropertyValue( key ); if ( value != null ) { return new Tuple<String,String>( key, value ); } } return override; }
[ "private", "Tuple", "<", "String", ",", "String", ">", "getEntry", "(", "final", "String", "key", ")", "{", "Tuple", "<", "String", ",", "String", ">", "override", "=", "getOverrideEntry", "(", "key", ")", ";", "if", "(", "override", "==", "null", ")", "{", "String", "value", "=", "getPropertyValue", "(", "key", ")", ";", "if", "(", "value", "!=", "null", ")", "{", "return", "new", "Tuple", "<", "String", ",", "String", ">", "(", "key", ",", "value", ")", ";", "}", "}", "return", "override", ";", "}" ]
Searches for a property of "key" using all overrides @param key @return the value, or null if nothing was found
[ "Searches", "for", "a", "property", "of", "key", "using", "all", "overrides" ]
0f9969bc0809e8a617501fa57c135e9b3984fae0
https://github.com/crowmagnumb/s6-util/blob/0f9969bc0809e8a617501fa57c135e9b3984fae0/src/main/java/net/crowmagnumb/util/io/ResourceReaderImpl.java#L166-L181
train
crowmagnumb/s6-util
src/main/java/net/crowmagnumb/util/io/ResourceReaderImpl.java
ResourceReaderImpl.getEntry
private Tuple<String,String> getEntry( final String key, final Collection<String> prefixes ) { if ( CollectionUtils.isEmpty( prefixes ) ) { return getEntry( key ); } for( String prefix : prefixes ) { String prefixedKey = prefix + "." + key; Tuple<String,String> override = getOverrideEntry( prefixedKey ); if ( override != null ) { return override; } // // Above we were checking overrides of the override. Here, // just check for the first override. If that doesn't work, // then we need to just pass it on and ignore the specified override. // String value = getPropertyValue( prefixedKey ); if ( value != null ) { return new Tuple<String,String>( prefixedKey, value ); } } // // No prefixed overrides were found, so drop back to using // the standard, non-prefixed version // return getEntry( key ); }
java
private Tuple<String,String> getEntry( final String key, final Collection<String> prefixes ) { if ( CollectionUtils.isEmpty( prefixes ) ) { return getEntry( key ); } for( String prefix : prefixes ) { String prefixedKey = prefix + "." + key; Tuple<String,String> override = getOverrideEntry( prefixedKey ); if ( override != null ) { return override; } // // Above we were checking overrides of the override. Here, // just check for the first override. If that doesn't work, // then we need to just pass it on and ignore the specified override. // String value = getPropertyValue( prefixedKey ); if ( value != null ) { return new Tuple<String,String>( prefixedKey, value ); } } // // No prefixed overrides were found, so drop back to using // the standard, non-prefixed version // return getEntry( key ); }
[ "private", "Tuple", "<", "String", ",", "String", ">", "getEntry", "(", "final", "String", "key", ",", "final", "Collection", "<", "String", ">", "prefixes", ")", "{", "if", "(", "CollectionUtils", ".", "isEmpty", "(", "prefixes", ")", ")", "{", "return", "getEntry", "(", "key", ")", ";", "}", "for", "(", "String", "prefix", ":", "prefixes", ")", "{", "String", "prefixedKey", "=", "prefix", "+", "\".\"", "+", "key", ";", "Tuple", "<", "String", ",", "String", ">", "override", "=", "getOverrideEntry", "(", "prefixedKey", ")", ";", "if", "(", "override", "!=", "null", ")", "{", "return", "override", ";", "}", "//", "// Above we were checking overrides of the override. Here,", "// just check for the first override. If that doesn't work,", "// then we need to just pass it on and ignore the specified override.", "//", "String", "value", "=", "getPropertyValue", "(", "prefixedKey", ")", ";", "if", "(", "value", "!=", "null", ")", "{", "return", "new", "Tuple", "<", "String", ",", "String", ">", "(", "prefixedKey", ",", "value", ")", ";", "}", "}", "//", "// No prefixed overrides were found, so drop back to using", "// the standard, non-prefixed version", "//", "return", "getEntry", "(", "key", ")", ";", "}" ]
Searches for a property of "key" with all overrides, using the specified prefixes @param key @param prefixes @return the value, or null if nothing was found
[ "Searches", "for", "a", "property", "of", "key", "with", "all", "overrides", "using", "the", "specified", "prefixes" ]
0f9969bc0809e8a617501fa57c135e9b3984fae0
https://github.com/crowmagnumb/s6-util/blob/0f9969bc0809e8a617501fa57c135e9b3984fae0/src/main/java/net/crowmagnumb/util/io/ResourceReaderImpl.java#L192-L228
train
maochen/NLP
CoreNLP-WEB/src/main/java/org/maochen/nlp/web/db/H2DbConfig.java
H2DbConfig.entityManagerFactory
@Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter(); jpaVendorAdapter.setDatabase(Database.H2); jpaVendorAdapter.setGenerateDdl(true); LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean(); entityManagerFactory.setPackagesToScan(this.getClass().getPackage().getName()); entityManagerFactory.setJpaVendorAdapter(jpaVendorAdapter); entityManagerFactory.setDataSource(dataSource()); return entityManagerFactory; }
java
@Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter(); jpaVendorAdapter.setDatabase(Database.H2); jpaVendorAdapter.setGenerateDdl(true); LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean(); entityManagerFactory.setPackagesToScan(this.getClass().getPackage().getName()); entityManagerFactory.setJpaVendorAdapter(jpaVendorAdapter); entityManagerFactory.setDataSource(dataSource()); return entityManagerFactory; }
[ "@", "Bean", "public", "LocalContainerEntityManagerFactoryBean", "entityManagerFactory", "(", ")", "{", "HibernateJpaVendorAdapter", "jpaVendorAdapter", "=", "new", "HibernateJpaVendorAdapter", "(", ")", ";", "jpaVendorAdapter", ".", "setDatabase", "(", "Database", ".", "H2", ")", ";", "jpaVendorAdapter", ".", "setGenerateDdl", "(", "true", ")", ";", "LocalContainerEntityManagerFactoryBean", "entityManagerFactory", "=", "new", "LocalContainerEntityManagerFactoryBean", "(", ")", ";", "entityManagerFactory", ".", "setPackagesToScan", "(", "this", ".", "getClass", "(", ")", ".", "getPackage", "(", ")", ".", "getName", "(", ")", ")", ";", "entityManagerFactory", ".", "setJpaVendorAdapter", "(", "jpaVendorAdapter", ")", ";", "entityManagerFactory", ".", "setDataSource", "(", "dataSource", "(", ")", ")", ";", "return", "entityManagerFactory", ";", "}" ]
Entity manager factory. @return local container entity manager factory bean.
[ "Entity", "manager", "factory", "." ]
38ae7b384d5295334d9efa9dc4cd901b19d9c27e
https://github.com/maochen/NLP/blob/38ae7b384d5295334d9efa9dc4cd901b19d9c27e/CoreNLP-WEB/src/main/java/org/maochen/nlp/web/db/H2DbConfig.java#L60-L71
train
maochen/NLP
CoreNLP-WEB/src/main/java/org/maochen/nlp/web/db/H2DbConfig.java
H2DbConfig.h2servletRegistration
@Bean public ServletRegistrationBean h2servletRegistration() { ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new WebServlet()); servletRegistrationBean.addUrlMappings("/h2/*"); return servletRegistrationBean; }
java
@Bean public ServletRegistrationBean h2servletRegistration() { ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new WebServlet()); servletRegistrationBean.addUrlMappings("/h2/*"); return servletRegistrationBean; }
[ "@", "Bean", "public", "ServletRegistrationBean", "h2servletRegistration", "(", ")", "{", "ServletRegistrationBean", "servletRegistrationBean", "=", "new", "ServletRegistrationBean", "(", "new", "WebServlet", "(", ")", ")", ";", "servletRegistrationBean", ".", "addUrlMappings", "(", "\"/h2/*\"", ")", ";", "return", "servletRegistrationBean", ";", "}" ]
H2 console. @return /console/*
[ "H2", "console", "." ]
38ae7b384d5295334d9efa9dc4cd901b19d9c27e
https://github.com/maochen/NLP/blob/38ae7b384d5295334d9efa9dc4cd901b19d9c27e/CoreNLP-WEB/src/main/java/org/maochen/nlp/web/db/H2DbConfig.java#L89-L94
train
aoindustries/ao-taglib
src/main/java/com/aoindustries/taglib/PropertyUtils.java
PropertyUtils.setAttribute
public static void setAttribute(PageContext pageContext, String scope, String name, Object value) throws JspTagException { pageContext.setAttribute(name, value, Scope.getScopeId(scope)); }
java
public static void setAttribute(PageContext pageContext, String scope, String name, Object value) throws JspTagException { pageContext.setAttribute(name, value, Scope.getScopeId(scope)); }
[ "public", "static", "void", "setAttribute", "(", "PageContext", "pageContext", ",", "String", "scope", ",", "String", "name", ",", "Object", "value", ")", "throws", "JspTagException", "{", "pageContext", ".", "setAttribute", "(", "name", ",", "value", ",", "Scope", ".", "getScopeId", "(", "scope", ")", ")", ";", "}" ]
Sets an attribute in the provided textual scope.
[ "Sets", "an", "attribute", "in", "the", "provided", "textual", "scope", "." ]
5670eba8485196bd42d31d3ff09a42deacb025f8
https://github.com/aoindustries/ao-taglib/blob/5670eba8485196bd42d31d3ff09a42deacb025f8/src/main/java/com/aoindustries/taglib/PropertyUtils.java#L43-L45
train
aoindustries/ao-taglib
src/main/java/com/aoindustries/taglib/PropertyUtils.java
PropertyUtils.findObject
public static Object findObject(PageContext pageContext, String scope, String name, String property, boolean beanRequired, boolean valueRequired) throws JspTagException { try { // Check the name if(name==null) throw new AttributeRequiredException("name"); // Find the bean Object bean; if(scope==null) bean = pageContext.findAttribute(name); else bean = pageContext.getAttribute(name, Scope.getScopeId(scope)); // Check required if(bean==null) { if(beanRequired) { // null and required if(scope==null) throw new LocalizedJspTagException(ApplicationResources.accessor, "PropertyUtils.bean.required.nullScope", name); else throw new LocalizedJspTagException(ApplicationResources.accessor, "PropertyUtils.bean.required.scope", name, scope); } else { // null and not required return null; } } else { if(property==null) { // No property lookup, use the bean directly return bean; } else { // Find the property Object value = org.apache.commons.beanutils.PropertyUtils.getProperty(bean, property); if(valueRequired && value==null) { // null and required if(scope==null) throw new LocalizedJspTagException(ApplicationResources.accessor, "PropertyUtils.value.required.nullScope", property, name); else throw new LocalizedJspTagException(ApplicationResources.accessor, "PropertyUtils.value.required.scope", property, name, scope); } return value; } } } catch(IllegalAccessException | InvocationTargetException | NoSuchMethodException err) { throw new JspTagException(err); } }
java
public static Object findObject(PageContext pageContext, String scope, String name, String property, boolean beanRequired, boolean valueRequired) throws JspTagException { try { // Check the name if(name==null) throw new AttributeRequiredException("name"); // Find the bean Object bean; if(scope==null) bean = pageContext.findAttribute(name); else bean = pageContext.getAttribute(name, Scope.getScopeId(scope)); // Check required if(bean==null) { if(beanRequired) { // null and required if(scope==null) throw new LocalizedJspTagException(ApplicationResources.accessor, "PropertyUtils.bean.required.nullScope", name); else throw new LocalizedJspTagException(ApplicationResources.accessor, "PropertyUtils.bean.required.scope", name, scope); } else { // null and not required return null; } } else { if(property==null) { // No property lookup, use the bean directly return bean; } else { // Find the property Object value = org.apache.commons.beanutils.PropertyUtils.getProperty(bean, property); if(valueRequired && value==null) { // null and required if(scope==null) throw new LocalizedJspTagException(ApplicationResources.accessor, "PropertyUtils.value.required.nullScope", property, name); else throw new LocalizedJspTagException(ApplicationResources.accessor, "PropertyUtils.value.required.scope", property, name, scope); } return value; } } } catch(IllegalAccessException | InvocationTargetException | NoSuchMethodException err) { throw new JspTagException(err); } }
[ "public", "static", "Object", "findObject", "(", "PageContext", "pageContext", ",", "String", "scope", ",", "String", "name", ",", "String", "property", ",", "boolean", "beanRequired", ",", "boolean", "valueRequired", ")", "throws", "JspTagException", "{", "try", "{", "// Check the name", "if", "(", "name", "==", "null", ")", "throw", "new", "AttributeRequiredException", "(", "\"name\"", ")", ";", "// Find the bean", "Object", "bean", ";", "if", "(", "scope", "==", "null", ")", "bean", "=", "pageContext", ".", "findAttribute", "(", "name", ")", ";", "else", "bean", "=", "pageContext", ".", "getAttribute", "(", "name", ",", "Scope", ".", "getScopeId", "(", "scope", ")", ")", ";", "// Check required", "if", "(", "bean", "==", "null", ")", "{", "if", "(", "beanRequired", ")", "{", "// null and required", "if", "(", "scope", "==", "null", ")", "throw", "new", "LocalizedJspTagException", "(", "ApplicationResources", ".", "accessor", ",", "\"PropertyUtils.bean.required.nullScope\"", ",", "name", ")", ";", "else", "throw", "new", "LocalizedJspTagException", "(", "ApplicationResources", ".", "accessor", ",", "\"PropertyUtils.bean.required.scope\"", ",", "name", ",", "scope", ")", ";", "}", "else", "{", "// null and not required", "return", "null", ";", "}", "}", "else", "{", "if", "(", "property", "==", "null", ")", "{", "// No property lookup, use the bean directly", "return", "bean", ";", "}", "else", "{", "// Find the property", "Object", "value", "=", "org", ".", "apache", ".", "commons", ".", "beanutils", ".", "PropertyUtils", ".", "getProperty", "(", "bean", ",", "property", ")", ";", "if", "(", "valueRequired", "&&", "value", "==", "null", ")", "{", "// null and required", "if", "(", "scope", "==", "null", ")", "throw", "new", "LocalizedJspTagException", "(", "ApplicationResources", ".", "accessor", ",", "\"PropertyUtils.value.required.nullScope\"", ",", "property", ",", "name", ")", ";", "else", "throw", "new", "LocalizedJspTagException", "(", "ApplicationResources", ".", "accessor", ",", "\"PropertyUtils.value.required.scope\"", ",", "property", ",", "name", ",", "scope", ")", ";", "}", "return", "value", ";", "}", "}", "}", "catch", "(", "IllegalAccessException", "|", "InvocationTargetException", "|", "NoSuchMethodException", "err", ")", "{", "throw", "new", "JspTagException", "(", "err", ")", ";", "}", "}" ]
Gets the object given its scope, name, and optional property. @param scope scope should be one of these acceptable values: <ul> <li><code>null</code></li> <li><code>"page"</code></li> <li><code>"request"</code></li> <li><code>"session"</code></li> <li><code>"application"</code></li> </ul> @param beanRequired when <code>true</code>, this method will not return <code>null</code>, instead it will throw a <code>JspTagException</code> with an appropriate localized message. @param valueRequired when <code>true</code>, this method will not return <code>null</code>, instead it will throw a <code>JspTagException</code> with an appropriate localized message. @return the resolved <code>Object</code> or <code>null</code> if not found.
[ "Gets", "the", "object", "given", "its", "scope", "name", "and", "optional", "property", "." ]
5670eba8485196bd42d31d3ff09a42deacb025f8
https://github.com/aoindustries/ao-taglib/blob/5670eba8485196bd42d31d3ff09a42deacb025f8/src/main/java/com/aoindustries/taglib/PropertyUtils.java#L65-L103
train
aoindustries/ao-taglib
src/main/java/com/aoindustries/taglib/Scope.java
Scope.getScopeId
public static int getScopeId(String scope) throws JspTagException { if(scope==null || PAGE.equals(scope)) return PageContext.PAGE_SCOPE; else if(REQUEST.equals(scope)) return PageContext.REQUEST_SCOPE; else if(SESSION.equals(scope)) return PageContext.SESSION_SCOPE; else if(APPLICATION.equals(scope)) return PageContext.APPLICATION_SCOPE; else throw new LocalizedJspTagException(ApplicationResources.accessor, "Scope.scope.invalid", scope); }
java
public static int getScopeId(String scope) throws JspTagException { if(scope==null || PAGE.equals(scope)) return PageContext.PAGE_SCOPE; else if(REQUEST.equals(scope)) return PageContext.REQUEST_SCOPE; else if(SESSION.equals(scope)) return PageContext.SESSION_SCOPE; else if(APPLICATION.equals(scope)) return PageContext.APPLICATION_SCOPE; else throw new LocalizedJspTagException(ApplicationResources.accessor, "Scope.scope.invalid", scope); }
[ "public", "static", "int", "getScopeId", "(", "String", "scope", ")", "throws", "JspTagException", "{", "if", "(", "scope", "==", "null", "||", "PAGE", ".", "equals", "(", "scope", ")", ")", "return", "PageContext", ".", "PAGE_SCOPE", ";", "else", "if", "(", "REQUEST", ".", "equals", "(", "scope", ")", ")", "return", "PageContext", ".", "REQUEST_SCOPE", ";", "else", "if", "(", "SESSION", ".", "equals", "(", "scope", ")", ")", "return", "PageContext", ".", "SESSION_SCOPE", ";", "else", "if", "(", "APPLICATION", ".", "equals", "(", "scope", ")", ")", "return", "PageContext", ".", "APPLICATION_SCOPE", ";", "else", "throw", "new", "LocalizedJspTagException", "(", "ApplicationResources", ".", "accessor", ",", "\"Scope.scope.invalid\"", ",", "scope", ")", ";", "}" ]
Gets the PageContext scope value for the textual scope name. @exception JspTagException if invalid scope
[ "Gets", "the", "PageContext", "scope", "value", "for", "the", "textual", "scope", "name", "." ]
5670eba8485196bd42d31d3ff09a42deacb025f8
https://github.com/aoindustries/ao-taglib/blob/5670eba8485196bd42d31d3ff09a42deacb025f8/src/main/java/com/aoindustries/taglib/Scope.java#L51-L57
train
crowmagnumb/s6-util
src/main/java/net/crowmagnumb/util/ResourceBundleUtils.java
ResourceBundleUtils.bundleToStringMap
public static Map<String,String> bundleToStringMap( final ResourceBundle bundle, final String suffix ) { if ( bundle == null ) { return Collections.<String,String>emptyMap(); } String theSuffix; if ( StringUtils.isEmpty( suffix ) ) { theSuffix = ""; } else { theSuffix = suffix + "."; } Map<String,String> map = new LinkedHashMap<String,String>(); Enumeration<String> keys = bundle.getKeys(); while( keys.hasMoreElements() ) { String key = keys.nextElement(); Object value = bundle.getObject( key ); String strValue = ( value != null ) ? value.toString() : null; map.put( theSuffix + key, strValue ); } return map; }
java
public static Map<String,String> bundleToStringMap( final ResourceBundle bundle, final String suffix ) { if ( bundle == null ) { return Collections.<String,String>emptyMap(); } String theSuffix; if ( StringUtils.isEmpty( suffix ) ) { theSuffix = ""; } else { theSuffix = suffix + "."; } Map<String,String> map = new LinkedHashMap<String,String>(); Enumeration<String> keys = bundle.getKeys(); while( keys.hasMoreElements() ) { String key = keys.nextElement(); Object value = bundle.getObject( key ); String strValue = ( value != null ) ? value.toString() : null; map.put( theSuffix + key, strValue ); } return map; }
[ "public", "static", "Map", "<", "String", ",", "String", ">", "bundleToStringMap", "(", "final", "ResourceBundle", "bundle", ",", "final", "String", "suffix", ")", "{", "if", "(", "bundle", "==", "null", ")", "{", "return", "Collections", ".", "<", "String", ",", "String", ">", "emptyMap", "(", ")", ";", "}", "String", "theSuffix", ";", "if", "(", "StringUtils", ".", "isEmpty", "(", "suffix", ")", ")", "{", "theSuffix", "=", "\"\"", ";", "}", "else", "{", "theSuffix", "=", "suffix", "+", "\".\"", ";", "}", "Map", "<", "String", ",", "String", ">", "map", "=", "new", "LinkedHashMap", "<", "String", ",", "String", ">", "(", ")", ";", "Enumeration", "<", "String", ">", "keys", "=", "bundle", ".", "getKeys", "(", ")", ";", "while", "(", "keys", ".", "hasMoreElements", "(", ")", ")", "{", "String", "key", "=", "keys", ".", "nextElement", "(", ")", ";", "Object", "value", "=", "bundle", ".", "getObject", "(", "key", ")", ";", "String", "strValue", "=", "(", "value", "!=", "null", ")", "?", "value", ".", "toString", "(", ")", ":", "null", ";", "map", ".", "put", "(", "theSuffix", "+", "key", ",", "strValue", ")", ";", "}", "return", "map", ";", "}" ]
Converts a resource bundle to a map after prepending suffix + "." to each property Things that aren't strings in the map (if there are any) are converted via .toString() @param bundle bundle to convert @param suffix suffix to add to each key in bundle @return a key,value map of string,string
[ "Converts", "a", "resource", "bundle", "to", "a", "map", "after", "prepending", "suffix", "+", ".", "to", "each", "property" ]
0f9969bc0809e8a617501fa57c135e9b3984fae0
https://github.com/crowmagnumb/s6-util/blob/0f9969bc0809e8a617501fa57c135e9b3984fae0/src/main/java/net/crowmagnumb/util/ResourceBundleUtils.java#L30-L62
train
maochen/NLP
CoreNLP-Experiment/src/main/java/org/maochen/nlp/ml/classifier/knn/KNNClassifier.java
KNNClassifier.predict
@Override public Map<String, Double> predict(Tuple predict) { KNNEngine engine = new KNNEngine(predict, trainingData, k); if (mode == 1) { engine.getDistance(engine.chebyshevDistance); } else if (mode == 2) { engine.getDistance(engine.manhattanDistance); } else { engine.getDistance(engine.euclideanDistance); } predict.label = engine.getResult(); Map<String, Double> outputMap = new ConcurrentHashMap<>(); trainingData.parallelStream().forEach(x -> outputMap.put(String.valueOf(x.id), (Double) x.getExtra().get(DISTANCE))); return outputMap; }
java
@Override public Map<String, Double> predict(Tuple predict) { KNNEngine engine = new KNNEngine(predict, trainingData, k); if (mode == 1) { engine.getDistance(engine.chebyshevDistance); } else if (mode == 2) { engine.getDistance(engine.manhattanDistance); } else { engine.getDistance(engine.euclideanDistance); } predict.label = engine.getResult(); Map<String, Double> outputMap = new ConcurrentHashMap<>(); trainingData.parallelStream().forEach(x -> outputMap.put(String.valueOf(x.id), (Double) x.getExtra().get(DISTANCE))); return outputMap; }
[ "@", "Override", "public", "Map", "<", "String", ",", "Double", ">", "predict", "(", "Tuple", "predict", ")", "{", "KNNEngine", "engine", "=", "new", "KNNEngine", "(", "predict", ",", "trainingData", ",", "k", ")", ";", "if", "(", "mode", "==", "1", ")", "{", "engine", ".", "getDistance", "(", "engine", ".", "chebyshevDistance", ")", ";", "}", "else", "if", "(", "mode", "==", "2", ")", "{", "engine", ".", "getDistance", "(", "engine", ".", "manhattanDistance", ")", ";", "}", "else", "{", "engine", ".", "getDistance", "(", "engine", ".", "euclideanDistance", ")", ";", "}", "predict", ".", "label", "=", "engine", ".", "getResult", "(", ")", ";", "Map", "<", "String", ",", "Double", ">", "outputMap", "=", "new", "ConcurrentHashMap", "<>", "(", ")", ";", "trainingData", ".", "parallelStream", "(", ")", ".", "forEach", "(", "x", "->", "outputMap", ".", "put", "(", "String", ".", "valueOf", "(", "x", ".", "id", ")", ",", "(", "Double", ")", "x", ".", "getExtra", "(", ")", ".", "get", "(", "DISTANCE", ")", ")", ")", ";", "return", "outputMap", ";", "}" ]
Return the predict to every other train vector's distance. @return return by Id which is ordered by input sequential.
[ "Return", "the", "predict", "to", "every", "other", "train", "vector", "s", "distance", "." ]
38ae7b384d5295334d9efa9dc4cd901b19d9c27e
https://github.com/maochen/NLP/blob/38ae7b384d5295334d9efa9dc4cd901b19d9c27e/CoreNLP-Experiment/src/main/java/org/maochen/nlp/ml/classifier/knn/KNNClassifier.java#L67-L85
train
crowmagnumb/s6-util
src/main/java/net/crowmagnumb/util/weak/WeakHashSet.java
WeakHashSet.purge
public void purge() { WeakElement<?> element; while( ( element = (WeakElement<?>) _queue.poll() ) != null ) { _set.remove( element ); } }
java
public void purge() { WeakElement<?> element; while( ( element = (WeakElement<?>) _queue.poll() ) != null ) { _set.remove( element ); } }
[ "public", "void", "purge", "(", ")", "{", "WeakElement", "<", "?", ">", "element", ";", "while", "(", "(", "element", "=", "(", "WeakElement", "<", "?", ">", ")", "_queue", ".", "poll", "(", ")", ")", "!=", "null", ")", "{", "_set", ".", "remove", "(", "element", ")", ";", "}", "}" ]
Removes all garbage-collected elements from this set
[ "Removes", "all", "garbage", "-", "collected", "elements", "from", "this", "set" ]
0f9969bc0809e8a617501fa57c135e9b3984fae0
https://github.com/crowmagnumb/s6-util/blob/0f9969bc0809e8a617501fa57c135e9b3984fae0/src/main/java/net/crowmagnumb/util/weak/WeakHashSet.java#L108-L116
train
maochen/NLP
CoreNLP-NLP/src/main/java/org/maochen/nlp/ml/classifier/crfsuite/CRFClassifier.java
CRFClassifier.train
@Override public ISeqClassifier train(List<SequenceTuple> trainingData) { if (trainingData == null || trainingData.size() == 0) { LOG.warn("Training data is empty."); return this; } if (modelPath == null) { try { modelPath = Files.createTempDirectory("crfsuite").toAbsolutePath().toString(); } catch (IOException e) { LOG.error("Create temp directory failed.", e); e.printStackTrace(); } } Pair<List<ItemSequence>, List<StringList>> crfCompatibleTrainingData = loadTrainingData(trainingData); Trainer trainer = new Trainer(); String algorithm = (String) props.getOrDefault("algorithm", DEFAULT_ALGORITHM); props.remove("algorithm"); String graphicalModelType = (String) props.getOrDefault("graphicalModelType", DEFAULT_GRAPHICAL_MODEL_TYPE); props.remove("graphicalModelType"); trainer.select(algorithm, graphicalModelType); // Set parameters props.entrySet().forEach(pair -> trainer.set((String) pair.getKey(), (String) pair.getValue())); // Add training data into the trainer for (int i = 0; i < trainingData.size(); i++) { // Use group id = 0 but the API doesn't say what it is used for :( trainer.append(crfCompatibleTrainingData.getLeft().get(i), crfCompatibleTrainingData.getRight().get(i), 0); } // Start training without hold-outs. trainer.message() // will be called to report the training process trainer.train(modelPath, -1); return this; }
java
@Override public ISeqClassifier train(List<SequenceTuple> trainingData) { if (trainingData == null || trainingData.size() == 0) { LOG.warn("Training data is empty."); return this; } if (modelPath == null) { try { modelPath = Files.createTempDirectory("crfsuite").toAbsolutePath().toString(); } catch (IOException e) { LOG.error("Create temp directory failed.", e); e.printStackTrace(); } } Pair<List<ItemSequence>, List<StringList>> crfCompatibleTrainingData = loadTrainingData(trainingData); Trainer trainer = new Trainer(); String algorithm = (String) props.getOrDefault("algorithm", DEFAULT_ALGORITHM); props.remove("algorithm"); String graphicalModelType = (String) props.getOrDefault("graphicalModelType", DEFAULT_GRAPHICAL_MODEL_TYPE); props.remove("graphicalModelType"); trainer.select(algorithm, graphicalModelType); // Set parameters props.entrySet().forEach(pair -> trainer.set((String) pair.getKey(), (String) pair.getValue())); // Add training data into the trainer for (int i = 0; i < trainingData.size(); i++) { // Use group id = 0 but the API doesn't say what it is used for :( trainer.append(crfCompatibleTrainingData.getLeft().get(i), crfCompatibleTrainingData.getRight().get(i), 0); } // Start training without hold-outs. trainer.message() // will be called to report the training process trainer.train(modelPath, -1); return this; }
[ "@", "Override", "public", "ISeqClassifier", "train", "(", "List", "<", "SequenceTuple", ">", "trainingData", ")", "{", "if", "(", "trainingData", "==", "null", "||", "trainingData", ".", "size", "(", ")", "==", "0", ")", "{", "LOG", ".", "warn", "(", "\"Training data is empty.\"", ")", ";", "return", "this", ";", "}", "if", "(", "modelPath", "==", "null", ")", "{", "try", "{", "modelPath", "=", "Files", ".", "createTempDirectory", "(", "\"crfsuite\"", ")", ".", "toAbsolutePath", "(", ")", ".", "toString", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "LOG", ".", "error", "(", "\"Create temp directory failed.\"", ",", "e", ")", ";", "e", ".", "printStackTrace", "(", ")", ";", "}", "}", "Pair", "<", "List", "<", "ItemSequence", ">", ",", "List", "<", "StringList", ">", ">", "crfCompatibleTrainingData", "=", "loadTrainingData", "(", "trainingData", ")", ";", "Trainer", "trainer", "=", "new", "Trainer", "(", ")", ";", "String", "algorithm", "=", "(", "String", ")", "props", ".", "getOrDefault", "(", "\"algorithm\"", ",", "DEFAULT_ALGORITHM", ")", ";", "props", ".", "remove", "(", "\"algorithm\"", ")", ";", "String", "graphicalModelType", "=", "(", "String", ")", "props", ".", "getOrDefault", "(", "\"graphicalModelType\"", ",", "DEFAULT_GRAPHICAL_MODEL_TYPE", ")", ";", "props", ".", "remove", "(", "\"graphicalModelType\"", ")", ";", "trainer", ".", "select", "(", "algorithm", ",", "graphicalModelType", ")", ";", "// Set parameters", "props", ".", "entrySet", "(", ")", ".", "forEach", "(", "pair", "->", "trainer", ".", "set", "(", "(", "String", ")", "pair", ".", "getKey", "(", ")", ",", "(", "String", ")", "pair", ".", "getValue", "(", ")", ")", ")", ";", "// Add training data into the trainer", "for", "(", "int", "i", "=", "0", ";", "i", "<", "trainingData", ".", "size", "(", ")", ";", "i", "++", ")", "{", "// Use group id = 0 but the API doesn't say what it is used for :(", "trainer", ".", "append", "(", "crfCompatibleTrainingData", ".", "getLeft", "(", ")", ".", "get", "(", "i", ")", ",", "crfCompatibleTrainingData", ".", "getRight", "(", ")", ".", "get", "(", "i", ")", ",", "0", ")", ";", "}", "// Start training without hold-outs. trainer.message()", "// will be called to report the training process", "trainer", ".", "train", "(", "modelPath", ",", "-", "1", ")", ";", "return", "this", ";", "}" ]
Train CRF Suite with annotated item sequences.
[ "Train", "CRF", "Suite", "with", "annotated", "item", "sequences", "." ]
38ae7b384d5295334d9efa9dc4cd901b19d9c27e
https://github.com/maochen/NLP/blob/38ae7b384d5295334d9efa9dc4cd901b19d9c27e/CoreNLP-NLP/src/main/java/org/maochen/nlp/ml/classifier/crfsuite/CRFClassifier.java#L87-L126
train
nightcode/yaranga
core/src/org/nightcode/common/net/http/OAuthUtils.java
OAuthUtils.getSignatureBaseString
public static String getSignatureBaseString(String requestMethod, String requestUrl, Map<String, String> protocolParameters) throws AuthException { StringBuilder sb = new StringBuilder(); sb.append(requestMethod.toUpperCase()).append("&") .append(AuthUtils.percentEncode(normalizeUrl(requestUrl))).append("&") .append(AuthUtils.percentEncode(normalizeParameters(requestUrl, protocolParameters))); return sb.toString(); }
java
public static String getSignatureBaseString(String requestMethod, String requestUrl, Map<String, String> protocolParameters) throws AuthException { StringBuilder sb = new StringBuilder(); sb.append(requestMethod.toUpperCase()).append("&") .append(AuthUtils.percentEncode(normalizeUrl(requestUrl))).append("&") .append(AuthUtils.percentEncode(normalizeParameters(requestUrl, protocolParameters))); return sb.toString(); }
[ "public", "static", "String", "getSignatureBaseString", "(", "String", "requestMethod", ",", "String", "requestUrl", ",", "Map", "<", "String", ",", "String", ">", "protocolParameters", ")", "throws", "AuthException", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "requestMethod", ".", "toUpperCase", "(", ")", ")", ".", "append", "(", "\"&\"", ")", ".", "append", "(", "AuthUtils", ".", "percentEncode", "(", "normalizeUrl", "(", "requestUrl", ")", ")", ")", ".", "append", "(", "\"&\"", ")", ".", "append", "(", "AuthUtils", ".", "percentEncode", "(", "normalizeParameters", "(", "requestUrl", ",", "protocolParameters", ")", ")", ")", ";", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
Returns a signature base string. The signature base string is a consistent, reproducible concatenation of several of the HTTP request elements into a single string. The signature base string includes the following components of the HTTP request: <ul> <li>the HTTP request method (e.g., "GET", "POST", etc.)</li> <li>the authority as declared by the HTTP "Host" request header field</li> <li>the path and query components of the request resource URI</li> <li>the protocol parameters excluding the "oauth_signature"</li> <li>parameters included in the request entity-body if they comply with the strict restrictions defined in Section 3.4.1.3</li> </ul> NOTE 1: only 4 first parameter sources are used for now. NOTE 2: no percent encoding for custom HTTP methods for now. @see <a href="http://tools.ietf.org/html/rfc5849#section-3.4.1">3.4.1. Signature Base String</a> @param requestMethod request method @param requestUrl request url @param protocolParameters protocol parameters @return signature base string @throws AuthException if some of parameters has unacceptable value
[ "Returns", "a", "signature", "base", "string", ".", "The", "signature", "base", "string", "is", "a", "consistent", "reproducible", "concatenation", "of", "several", "of", "the", "HTTP", "request", "elements", "into", "a", "single", "string", "." ]
f02cf8d8bcd365b6b1d55638938631a00e9ee808
https://github.com/nightcode/yaranga/blob/f02cf8d8bcd365b6b1d55638938631a00e9ee808/core/src/org/nightcode/common/net/http/OAuthUtils.java#L124-L131
train
maochen/NLP
CoreNLP-NLP/src/main/java/org/maochen/nlp/ml/util/TrainingDataUtils.java
TrainingDataUtils.createBalancedTrainingData
public static List<Tuple> createBalancedTrainingData(final List<Tuple> trainingData) { Map<String, Long> tagCount = trainingData.parallelStream() .map(x -> new AbstractMap.SimpleImmutableEntry<>(x.label, 1)) .collect(Collectors.groupingBy(Map.Entry::getKey, Collectors.counting())); Map.Entry<String, Long> minCountEntry = tagCount.entrySet().stream() .min(Comparator.comparing(Map.Entry::getValue)) .orElse(null); tagCount.clear(); List<Tuple> newData = new ArrayList<>(); for (Tuple t : trainingData) { String label = t.label; if (!tagCount.containsKey(label)) { tagCount.put(t.label, 0L); } if (tagCount.get(label) < minCountEntry.getValue()) { tagCount.put(label, tagCount.get(label) + 1); newData.add(t); } } return newData; }
java
public static List<Tuple> createBalancedTrainingData(final List<Tuple> trainingData) { Map<String, Long> tagCount = trainingData.parallelStream() .map(x -> new AbstractMap.SimpleImmutableEntry<>(x.label, 1)) .collect(Collectors.groupingBy(Map.Entry::getKey, Collectors.counting())); Map.Entry<String, Long> minCountEntry = tagCount.entrySet().stream() .min(Comparator.comparing(Map.Entry::getValue)) .orElse(null); tagCount.clear(); List<Tuple> newData = new ArrayList<>(); for (Tuple t : trainingData) { String label = t.label; if (!tagCount.containsKey(label)) { tagCount.put(t.label, 0L); } if (tagCount.get(label) < minCountEntry.getValue()) { tagCount.put(label, tagCount.get(label) + 1); newData.add(t); } } return newData; }
[ "public", "static", "List", "<", "Tuple", ">", "createBalancedTrainingData", "(", "final", "List", "<", "Tuple", ">", "trainingData", ")", "{", "Map", "<", "String", ",", "Long", ">", "tagCount", "=", "trainingData", ".", "parallelStream", "(", ")", ".", "map", "(", "x", "->", "new", "AbstractMap", ".", "SimpleImmutableEntry", "<>", "(", "x", ".", "label", ",", "1", ")", ")", ".", "collect", "(", "Collectors", ".", "groupingBy", "(", "Map", ".", "Entry", "::", "getKey", ",", "Collectors", ".", "counting", "(", ")", ")", ")", ";", "Map", ".", "Entry", "<", "String", ",", "Long", ">", "minCountEntry", "=", "tagCount", ".", "entrySet", "(", ")", ".", "stream", "(", ")", ".", "min", "(", "Comparator", ".", "comparing", "(", "Map", ".", "Entry", "::", "getValue", ")", ")", ".", "orElse", "(", "null", ")", ";", "tagCount", ".", "clear", "(", ")", ";", "List", "<", "Tuple", ">", "newData", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "Tuple", "t", ":", "trainingData", ")", "{", "String", "label", "=", "t", ".", "label", ";", "if", "(", "!", "tagCount", ".", "containsKey", "(", "label", ")", ")", "{", "tagCount", ".", "put", "(", "t", ".", "label", ",", "0L", ")", ";", "}", "if", "(", "tagCount", ".", "get", "(", "label", ")", "<", "minCountEntry", ".", "getValue", "(", ")", ")", "{", "tagCount", ".", "put", "(", "label", ",", "tagCount", ".", "get", "(", "label", ")", "+", "1", ")", ";", "newData", ".", "add", "(", "t", ")", ";", "}", "}", "return", "newData", ";", "}" ]
Regardless of the label, just consider isPosExample and !isPosExample @param trainingData input training data. @return List of balanced tuples.
[ "Regardless", "of", "the", "label", "just", "consider", "isPosExample", "and", "!isPosExample" ]
38ae7b384d5295334d9efa9dc4cd901b19d9c27e
https://github.com/maochen/NLP/blob/38ae7b384d5295334d9efa9dc4cd901b19d9c27e/CoreNLP-NLP/src/main/java/org/maochen/nlp/ml/util/TrainingDataUtils.java#L31-L56
train
maochen/NLP
CoreNLP-NLP/src/main/java/org/maochen/nlp/ml/util/TrainingDataUtils.java
TrainingDataUtils.splitData
public static Pair<List<Tuple>, List<Tuple>> splitData(final List<Tuple> trainingData, double proportion) { if (proportion < 0 || proportion > 1) { throw new RuntimeException("Proportion should between 0.0 - 1.0"); } if (proportion > 0.5) { proportion = 1 - proportion; } List<Tuple> smallList = new ArrayList<>(); List<Tuple> largeList = new ArrayList<>(); int smallListSize = (int) Math.floor(proportion * trainingData.size()); int ct = 0; Set<Integer> indices = new HashSet<>(); while (ct < smallListSize && trainingData.size() > indices.size()) { int index = (int) (Math.random() * (trainingData.size() - 1)); while (indices.contains(index)) { index = (int) (Math.random() * (trainingData.size() - 1)); } indices.add(index); ct++; } smallList.addAll(indices.stream().map(trainingData::get).collect(Collectors.toList())); IntStream.range(0, trainingData.size()) .filter(x -> !indices.contains(x)) .forEach(i -> largeList.add(trainingData.get(i))); return new ImmutablePair<>(smallList, largeList); }
java
public static Pair<List<Tuple>, List<Tuple>> splitData(final List<Tuple> trainingData, double proportion) { if (proportion < 0 || proportion > 1) { throw new RuntimeException("Proportion should between 0.0 - 1.0"); } if (proportion > 0.5) { proportion = 1 - proportion; } List<Tuple> smallList = new ArrayList<>(); List<Tuple> largeList = new ArrayList<>(); int smallListSize = (int) Math.floor(proportion * trainingData.size()); int ct = 0; Set<Integer> indices = new HashSet<>(); while (ct < smallListSize && trainingData.size() > indices.size()) { int index = (int) (Math.random() * (trainingData.size() - 1)); while (indices.contains(index)) { index = (int) (Math.random() * (trainingData.size() - 1)); } indices.add(index); ct++; } smallList.addAll(indices.stream().map(trainingData::get).collect(Collectors.toList())); IntStream.range(0, trainingData.size()) .filter(x -> !indices.contains(x)) .forEach(i -> largeList.add(trainingData.get(i))); return new ImmutablePair<>(smallList, largeList); }
[ "public", "static", "Pair", "<", "List", "<", "Tuple", ">", ",", "List", "<", "Tuple", ">", ">", "splitData", "(", "final", "List", "<", "Tuple", ">", "trainingData", ",", "double", "proportion", ")", "{", "if", "(", "proportion", "<", "0", "||", "proportion", ">", "1", ")", "{", "throw", "new", "RuntimeException", "(", "\"Proportion should between 0.0 - 1.0\"", ")", ";", "}", "if", "(", "proportion", ">", "0.5", ")", "{", "proportion", "=", "1", "-", "proportion", ";", "}", "List", "<", "Tuple", ">", "smallList", "=", "new", "ArrayList", "<>", "(", ")", ";", "List", "<", "Tuple", ">", "largeList", "=", "new", "ArrayList", "<>", "(", ")", ";", "int", "smallListSize", "=", "(", "int", ")", "Math", ".", "floor", "(", "proportion", "*", "trainingData", ".", "size", "(", ")", ")", ";", "int", "ct", "=", "0", ";", "Set", "<", "Integer", ">", "indices", "=", "new", "HashSet", "<>", "(", ")", ";", "while", "(", "ct", "<", "smallListSize", "&&", "trainingData", ".", "size", "(", ")", ">", "indices", ".", "size", "(", ")", ")", "{", "int", "index", "=", "(", "int", ")", "(", "Math", ".", "random", "(", ")", "*", "(", "trainingData", ".", "size", "(", ")", "-", "1", ")", ")", ";", "while", "(", "indices", ".", "contains", "(", "index", ")", ")", "{", "index", "=", "(", "int", ")", "(", "Math", ".", "random", "(", ")", "*", "(", "trainingData", ".", "size", "(", ")", "-", "1", ")", ")", ";", "}", "indices", ".", "add", "(", "index", ")", ";", "ct", "++", ";", "}", "smallList", ".", "addAll", "(", "indices", ".", "stream", "(", ")", ".", "map", "(", "trainingData", "::", "get", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ")", ";", "IntStream", ".", "range", "(", "0", ",", "trainingData", ".", "size", "(", ")", ")", ".", "filter", "(", "x", "->", "!", "indices", ".", "contains", "(", "x", ")", ")", ".", "forEach", "(", "i", "->", "largeList", ".", "add", "(", "trainingData", ".", "get", "(", "i", ")", ")", ")", ";", "return", "new", "ImmutablePair", "<>", "(", "smallList", ",", "largeList", ")", ";", "}" ]
Shuffle the data and split by proportion @param trainingData whole data collection. @param proportion scale from 0.1 - 1.0. @return Left- small chunk. Right - large chunk.
[ "Shuffle", "the", "data", "and", "split", "by", "proportion" ]
38ae7b384d5295334d9efa9dc4cd901b19d9c27e
https://github.com/maochen/NLP/blob/38ae7b384d5295334d9efa9dc4cd901b19d9c27e/CoreNLP-NLP/src/main/java/org/maochen/nlp/ml/util/TrainingDataUtils.java#L167-L199
train
maochen/NLP
CoreNLP-NLP/src/main/java/org/maochen/nlp/ml/classifier/naivebayes/NBTrainingEngine.java
NBTrainingEngine.calculateLabelPrior
public void calculateLabelPrior() { double prior = 1D / model.labelIndexer.getLabelSize(); model.labelIndexer.getIndexSet().forEach(labelIndex -> model.labelPrior.put(labelIndex, prior)); }
java
public void calculateLabelPrior() { double prior = 1D / model.labelIndexer.getLabelSize(); model.labelIndexer.getIndexSet().forEach(labelIndex -> model.labelPrior.put(labelIndex, prior)); }
[ "public", "void", "calculateLabelPrior", "(", ")", "{", "double", "prior", "=", "1D", "/", "model", ".", "labelIndexer", ".", "getLabelSize", "(", ")", ";", "model", ".", "labelIndexer", ".", "getIndexSet", "(", ")", ".", "forEach", "(", "labelIndex", "->", "model", ".", "labelPrior", ".", "put", "(", "labelIndex", ",", "prior", ")", ")", ";", "}" ]
Assume labels have equal probability. Not depends on the training data size.
[ "Assume", "labels", "have", "equal", "probability", ".", "Not", "depends", "on", "the", "training", "data", "size", "." ]
38ae7b384d5295334d9efa9dc4cd901b19d9c27e
https://github.com/maochen/NLP/blob/38ae7b384d5295334d9efa9dc4cd901b19d9c27e/CoreNLP-NLP/src/main/java/org/maochen/nlp/ml/classifier/naivebayes/NBTrainingEngine.java#L86-L89
train
aoindustries/ao-taglib
src/main/java/com/aoindustries/taglib/MarkupUtils.java
MarkupUtils.writeWithMarkup
public static void writeWithMarkup(Object value, MarkupType markupType, MediaEncoder encoder, Writer out) throws IOException { if(encoder==null) { writeWithMarkup(value, markupType, out); } else { if(value!=null) { if( value instanceof Writable && !((Writable)value).isFastToString() ) { // Avoid intermediate String from Writable Coercion.write(value, encoder, out); } else { String str = Coercion.toString(value); BundleLookupMarkup lookupMarkup; BundleLookupThreadContext threadContext = BundleLookupThreadContext.getThreadContext(false); if(threadContext!=null) { lookupMarkup = threadContext.getLookupMarkup(str); } else { lookupMarkup = null; } if(lookupMarkup!=null) lookupMarkup.appendPrefixTo(markupType, encoder, out); encoder.write(str, out); if(lookupMarkup!=null) lookupMarkup.appendSuffixTo(markupType, encoder, out); } } } }
java
public static void writeWithMarkup(Object value, MarkupType markupType, MediaEncoder encoder, Writer out) throws IOException { if(encoder==null) { writeWithMarkup(value, markupType, out); } else { if(value!=null) { if( value instanceof Writable && !((Writable)value).isFastToString() ) { // Avoid intermediate String from Writable Coercion.write(value, encoder, out); } else { String str = Coercion.toString(value); BundleLookupMarkup lookupMarkup; BundleLookupThreadContext threadContext = BundleLookupThreadContext.getThreadContext(false); if(threadContext!=null) { lookupMarkup = threadContext.getLookupMarkup(str); } else { lookupMarkup = null; } if(lookupMarkup!=null) lookupMarkup.appendPrefixTo(markupType, encoder, out); encoder.write(str, out); if(lookupMarkup!=null) lookupMarkup.appendSuffixTo(markupType, encoder, out); } } } }
[ "public", "static", "void", "writeWithMarkup", "(", "Object", "value", ",", "MarkupType", "markupType", ",", "MediaEncoder", "encoder", ",", "Writer", "out", ")", "throws", "IOException", "{", "if", "(", "encoder", "==", "null", ")", "{", "writeWithMarkup", "(", "value", ",", "markupType", ",", "out", ")", ";", "}", "else", "{", "if", "(", "value", "!=", "null", ")", "{", "if", "(", "value", "instanceof", "Writable", "&&", "!", "(", "(", "Writable", ")", "value", ")", ".", "isFastToString", "(", ")", ")", "{", "// Avoid intermediate String from Writable", "Coercion", ".", "write", "(", "value", ",", "encoder", ",", "out", ")", ";", "}", "else", "{", "String", "str", "=", "Coercion", ".", "toString", "(", "value", ")", ";", "BundleLookupMarkup", "lookupMarkup", ";", "BundleLookupThreadContext", "threadContext", "=", "BundleLookupThreadContext", ".", "getThreadContext", "(", "false", ")", ";", "if", "(", "threadContext", "!=", "null", ")", "{", "lookupMarkup", "=", "threadContext", ".", "getLookupMarkup", "(", "str", ")", ";", "}", "else", "{", "lookupMarkup", "=", "null", ";", "}", "if", "(", "lookupMarkup", "!=", "null", ")", "lookupMarkup", ".", "appendPrefixTo", "(", "markupType", ",", "encoder", ",", "out", ")", ";", "encoder", ".", "write", "(", "str", ",", "out", ")", ";", "if", "(", "lookupMarkup", "!=", "null", ")", "lookupMarkup", ".", "appendSuffixTo", "(", "markupType", ",", "encoder", ",", "out", ")", ";", "}", "}", "}", "}" ]
Writes a value with markup enabled using the provided encoder. @param encoder no encoding performed when null @see MarkupType
[ "Writes", "a", "value", "with", "markup", "enabled", "using", "the", "provided", "encoder", "." ]
5670eba8485196bd42d31d3ff09a42deacb025f8
https://github.com/aoindustries/ao-taglib/blob/5670eba8485196bd42d31d3ff09a42deacb025f8/src/main/java/com/aoindustries/taglib/MarkupUtils.java#L78-L104
train
maochen/NLP
CoreNLP-Experiment/src/main/java/org/maochen/nlp/wordcorrection/SingleWordCorrection.java
SingleWordCorrection.buildModel
public void buildModel(String wordFileName) throws IOException { BufferedReader br = new BufferedReader(new FileReader(new File(wordFileName))); String str; while ((str = br.readLine()) != null) { List<String> tokens = StanfordParser.stanfordTokenize(str).stream().map(CoreLabel::originalText).collect(Collectors.toList()); for (String word : tokens) { double count = model.wordProbability.containsKey(word) ? model.wordProbability.get(word) : 0; count++; model.wordProbability.put(word, count); } } br.close(); // Remove Empty prob. model.wordProbability.remove(StringUtils.EMPTY); model.normalizeWordProbability(); }
java
public void buildModel(String wordFileName) throws IOException { BufferedReader br = new BufferedReader(new FileReader(new File(wordFileName))); String str; while ((str = br.readLine()) != null) { List<String> tokens = StanfordParser.stanfordTokenize(str).stream().map(CoreLabel::originalText).collect(Collectors.toList()); for (String word : tokens) { double count = model.wordProbability.containsKey(word) ? model.wordProbability.get(word) : 0; count++; model.wordProbability.put(word, count); } } br.close(); // Remove Empty prob. model.wordProbability.remove(StringUtils.EMPTY); model.normalizeWordProbability(); }
[ "public", "void", "buildModel", "(", "String", "wordFileName", ")", "throws", "IOException", "{", "BufferedReader", "br", "=", "new", "BufferedReader", "(", "new", "FileReader", "(", "new", "File", "(", "wordFileName", ")", ")", ")", ";", "String", "str", ";", "while", "(", "(", "str", "=", "br", ".", "readLine", "(", ")", ")", "!=", "null", ")", "{", "List", "<", "String", ">", "tokens", "=", "StanfordParser", ".", "stanfordTokenize", "(", "str", ")", ".", "stream", "(", ")", ".", "map", "(", "CoreLabel", "::", "originalText", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ";", "for", "(", "String", "word", ":", "tokens", ")", "{", "double", "count", "=", "model", ".", "wordProbability", ".", "containsKey", "(", "word", ")", "?", "model", ".", "wordProbability", ".", "get", "(", "word", ")", ":", "0", ";", "count", "++", ";", "model", ".", "wordProbability", ".", "put", "(", "word", ",", "count", ")", ";", "}", "}", "br", ".", "close", "(", ")", ";", "// Remove Empty prob.", "model", ".", "wordProbability", ".", "remove", "(", "StringUtils", ".", "EMPTY", ")", ";", "model", ".", "normalizeWordProbability", "(", ")", ";", "}" ]
Parser here is just for tokenize.
[ "Parser", "here", "is", "just", "for", "tokenize", "." ]
38ae7b384d5295334d9efa9dc4cd901b19d9c27e
https://github.com/maochen/NLP/blob/38ae7b384d5295334d9efa9dc4cd901b19d9c27e/CoreNLP-Experiment/src/main/java/org/maochen/nlp/wordcorrection/SingleWordCorrection.java#L152-L169
train
crowmagnumb/s6-util
src/main/java/net/crowmagnumb/util/net/NetUtils.java
NetUtils.ipv4ToInt
public static int ipv4ToInt( final Inet4Address addr ) { int value = 0; for( byte chunk : addr.getAddress() ) { value <<= 8; value |= chunk & 0xff; } return value; }
java
public static int ipv4ToInt( final Inet4Address addr ) { int value = 0; for( byte chunk : addr.getAddress() ) { value <<= 8; value |= chunk & 0xff; } return value; }
[ "public", "static", "int", "ipv4ToInt", "(", "final", "Inet4Address", "addr", ")", "{", "int", "value", "=", "0", ";", "for", "(", "byte", "chunk", ":", "addr", ".", "getAddress", "(", ")", ")", "{", "value", "<<=", "8", ";", "value", "|=", "chunk", "&", "0xff", ";", "}", "return", "value", ";", "}" ]
Turns an Inet4Address into a 32-bit integer representation @param addr address @return integer representation
[ "Turns", "an", "Inet4Address", "into", "a", "32", "-", "bit", "integer", "representation" ]
0f9969bc0809e8a617501fa57c135e9b3984fae0
https://github.com/crowmagnumb/s6-util/blob/0f9969bc0809e8a617501fa57c135e9b3984fae0/src/main/java/net/crowmagnumb/util/net/NetUtils.java#L18-L29
train
liuyukuai/commons
commons-core/src/main/java/com/itxiaoer/commons/core/util/Lists.java
Lists.empty
public static <E> List<E> empty(List<E> list) { return Optional.ofNullable(list).orElse(newArrayList()); }
java
public static <E> List<E> empty(List<E> list) { return Optional.ofNullable(list).orElse(newArrayList()); }
[ "public", "static", "<", "E", ">", "List", "<", "E", ">", "empty", "(", "List", "<", "E", ">", "list", ")", "{", "return", "Optional", ".", "ofNullable", "(", "list", ")", ".", "orElse", "(", "newArrayList", "(", ")", ")", ";", "}" ]
null to empty list @param list list @param <E> element type @return list
[ "null", "to", "empty", "list" ]
ba67eddb542446b12f419f1866dbaa82e47fbf35
https://github.com/liuyukuai/commons/blob/ba67eddb542446b12f419f1866dbaa82e47fbf35/commons-core/src/main/java/com/itxiaoer/commons/core/util/Lists.java#L57-L59
train
liuyukuai/commons
commons-core/src/main/java/com/itxiaoer/commons/core/util/Lists.java
Lists.clean
public static <E> List<E> clean(List<E> list) { if (iterable(list)) { return list.stream().filter(e -> { if (Objects.isNull(e)) { return false; } if (e instanceof Nullable) { return !((Nullable) e).isNull(); } return true; }).collect(Collectors.toList()); } return list; }
java
public static <E> List<E> clean(List<E> list) { if (iterable(list)) { return list.stream().filter(e -> { if (Objects.isNull(e)) { return false; } if (e instanceof Nullable) { return !((Nullable) e).isNull(); } return true; }).collect(Collectors.toList()); } return list; }
[ "public", "static", "<", "E", ">", "List", "<", "E", ">", "clean", "(", "List", "<", "E", ">", "list", ")", "{", "if", "(", "iterable", "(", "list", ")", ")", "{", "return", "list", ".", "stream", "(", ")", ".", "filter", "(", "e", "->", "{", "if", "(", "Objects", ".", "isNull", "(", "e", ")", ")", "{", "return", "false", ";", "}", "if", "(", "e", "instanceof", "Nullable", ")", "{", "return", "!", "(", "(", "Nullable", ")", "e", ")", ".", "isNull", "(", ")", ";", "}", "return", "true", ";", "}", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ";", "}", "return", "list", ";", "}" ]
clean null element @param list list @param <E> element type @return list
[ "clean", "null", "element" ]
ba67eddb542446b12f419f1866dbaa82e47fbf35
https://github.com/liuyukuai/commons/blob/ba67eddb542446b12f419f1866dbaa82e47fbf35/commons-core/src/main/java/com/itxiaoer/commons/core/util/Lists.java#L68-L81
train
aoindustries/ao-encoding
src/main/java/com/aoindustries/encoding/ChainWriter.java
ChainWriter.encodeJavaScriptStringInXmlAttribute
public ChainWriter encodeJavaScriptStringInXmlAttribute(Object value) throws IOException { // Two stage encoding: // 1) Text -> JavaScript (with quotes added) // 2) JavaScript -> XML Attribute if( value instanceof Writable && !((Writable)value).isFastToString() ) { // Avoid unnecessary toString calls textInJavaScriptEncoder.writePrefixTo(javaScriptInXhtmlAttributeWriter); Coercion.write(value, textInJavaScriptEncoder, javaScriptInXhtmlAttributeWriter); textInJavaScriptEncoder.writeSuffixTo(javaScriptInXhtmlAttributeWriter); } else { String str = Coercion.toString(value); BundleLookupMarkup lookupMarkup; BundleLookupThreadContext threadContext = BundleLookupThreadContext.getThreadContext(false); if(threadContext!=null) { lookupMarkup = threadContext.getLookupMarkup(str); } else { lookupMarkup = null; } if(lookupMarkup!=null) lookupMarkup.appendPrefixTo(MarkupType.JAVASCRIPT, javaScriptInXhtmlAttributeWriter); textInJavaScriptEncoder.writePrefixTo(javaScriptInXhtmlAttributeWriter); textInJavaScriptEncoder.write(str, javaScriptInXhtmlAttributeWriter); textInJavaScriptEncoder.writeSuffixTo(javaScriptInXhtmlAttributeWriter); if(lookupMarkup!=null) lookupMarkup.appendSuffixTo(MarkupType.JAVASCRIPT, javaScriptInXhtmlAttributeWriter); } return this; }
java
public ChainWriter encodeJavaScriptStringInXmlAttribute(Object value) throws IOException { // Two stage encoding: // 1) Text -> JavaScript (with quotes added) // 2) JavaScript -> XML Attribute if( value instanceof Writable && !((Writable)value).isFastToString() ) { // Avoid unnecessary toString calls textInJavaScriptEncoder.writePrefixTo(javaScriptInXhtmlAttributeWriter); Coercion.write(value, textInJavaScriptEncoder, javaScriptInXhtmlAttributeWriter); textInJavaScriptEncoder.writeSuffixTo(javaScriptInXhtmlAttributeWriter); } else { String str = Coercion.toString(value); BundleLookupMarkup lookupMarkup; BundleLookupThreadContext threadContext = BundleLookupThreadContext.getThreadContext(false); if(threadContext!=null) { lookupMarkup = threadContext.getLookupMarkup(str); } else { lookupMarkup = null; } if(lookupMarkup!=null) lookupMarkup.appendPrefixTo(MarkupType.JAVASCRIPT, javaScriptInXhtmlAttributeWriter); textInJavaScriptEncoder.writePrefixTo(javaScriptInXhtmlAttributeWriter); textInJavaScriptEncoder.write(str, javaScriptInXhtmlAttributeWriter); textInJavaScriptEncoder.writeSuffixTo(javaScriptInXhtmlAttributeWriter); if(lookupMarkup!=null) lookupMarkup.appendSuffixTo(MarkupType.JAVASCRIPT, javaScriptInXhtmlAttributeWriter); } return this; }
[ "public", "ChainWriter", "encodeJavaScriptStringInXmlAttribute", "(", "Object", "value", ")", "throws", "IOException", "{", "// Two stage encoding:", "// 1) Text -> JavaScript (with quotes added)", "// 2) JavaScript -> XML Attribute", "if", "(", "value", "instanceof", "Writable", "&&", "!", "(", "(", "Writable", ")", "value", ")", ".", "isFastToString", "(", ")", ")", "{", "// Avoid unnecessary toString calls", "textInJavaScriptEncoder", ".", "writePrefixTo", "(", "javaScriptInXhtmlAttributeWriter", ")", ";", "Coercion", ".", "write", "(", "value", ",", "textInJavaScriptEncoder", ",", "javaScriptInXhtmlAttributeWriter", ")", ";", "textInJavaScriptEncoder", ".", "writeSuffixTo", "(", "javaScriptInXhtmlAttributeWriter", ")", ";", "}", "else", "{", "String", "str", "=", "Coercion", ".", "toString", "(", "value", ")", ";", "BundleLookupMarkup", "lookupMarkup", ";", "BundleLookupThreadContext", "threadContext", "=", "BundleLookupThreadContext", ".", "getThreadContext", "(", "false", ")", ";", "if", "(", "threadContext", "!=", "null", ")", "{", "lookupMarkup", "=", "threadContext", ".", "getLookupMarkup", "(", "str", ")", ";", "}", "else", "{", "lookupMarkup", "=", "null", ";", "}", "if", "(", "lookupMarkup", "!=", "null", ")", "lookupMarkup", ".", "appendPrefixTo", "(", "MarkupType", ".", "JAVASCRIPT", ",", "javaScriptInXhtmlAttributeWriter", ")", ";", "textInJavaScriptEncoder", ".", "writePrefixTo", "(", "javaScriptInXhtmlAttributeWriter", ")", ";", "textInJavaScriptEncoder", ".", "write", "(", "str", ",", "javaScriptInXhtmlAttributeWriter", ")", ";", "textInJavaScriptEncoder", ".", "writeSuffixTo", "(", "javaScriptInXhtmlAttributeWriter", ")", ";", "if", "(", "lookupMarkup", "!=", "null", ")", "lookupMarkup", ".", "appendSuffixTo", "(", "MarkupType", ".", "JAVASCRIPT", ",", "javaScriptInXhtmlAttributeWriter", ")", ";", "}", "return", "this", ";", "}" ]
Encodes a javascript string for use in an XML attribute context. Quotes are added around the string. Also, if the string is translated, comments will be added giving the translation lookup id to aid in translation of server-translated values in JavaScript. @see Coercion#toString(java.lang.Object, com.aoindustries.util.i18n.BundleLookup.MarkupType)
[ "Encodes", "a", "javascript", "string", "for", "use", "in", "an", "XML", "attribute", "context", ".", "Quotes", "are", "added", "around", "the", "string", ".", "Also", "if", "the", "string", "is", "translated", "comments", "will", "be", "added", "giving", "the", "translation", "lookup", "id", "to", "aid", "in", "translation", "of", "server", "-", "translated", "values", "in", "JavaScript", "." ]
54eeb8ff58ab7b44bb02549bbe2572625b449e4e
https://github.com/aoindustries/ao-encoding/blob/54eeb8ff58ab7b44bb02549bbe2572625b449e4e/src/main/java/com/aoindustries/encoding/ChainWriter.java#L549-L577
train
aoindustries/ao-encoding
src/main/java/com/aoindustries/encoding/ChainWriter.java
ChainWriter.printEU
@Deprecated public ChainWriter printEU(String value) { int len = value.length(); for (int c = 0; c < len; c++) { char ch = value.charAt(c); if (ch == ' ') out.print('+'); else { if ((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) out.print(ch); else { out.print('%'); out.print(getHex(ch >>> 4)); out.print(getHex(ch)); } } } return this; }
java
@Deprecated public ChainWriter printEU(String value) { int len = value.length(); for (int c = 0; c < len; c++) { char ch = value.charAt(c); if (ch == ' ') out.print('+'); else { if ((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) out.print(ch); else { out.print('%'); out.print(getHex(ch >>> 4)); out.print(getHex(ch)); } } } return this; }
[ "@", "Deprecated", "public", "ChainWriter", "printEU", "(", "String", "value", ")", "{", "int", "len", "=", "value", ".", "length", "(", ")", ";", "for", "(", "int", "c", "=", "0", ";", "c", "<", "len", ";", "c", "++", ")", "{", "char", "ch", "=", "value", ".", "charAt", "(", "c", ")", ";", "if", "(", "ch", "==", "'", "'", ")", "out", ".", "print", "(", "'", "'", ")", ";", "else", "{", "if", "(", "(", "ch", ">=", "'", "'", "&&", "ch", "<=", "'", "'", ")", "||", "(", "ch", ">=", "'", "'", "&&", "ch", "<=", "'", "'", ")", "||", "(", "ch", ">=", "'", "'", "&&", "ch", "<=", "'", "'", ")", ")", "out", ".", "print", "(", "ch", ")", ";", "else", "{", "out", ".", "print", "(", "'", "'", ")", ";", "out", ".", "print", "(", "getHex", "(", "ch", ">>>", "4", ")", ")", ";", "out", ".", "print", "(", "getHex", "(", "ch", ")", ")", ";", "}", "}", "}", "return", "this", ";", "}" ]
Prints a value that may be placed in a URL. @deprecated Use URLEncoder instead. @see URLEncoder
[ "Prints", "a", "value", "that", "may", "be", "placed", "in", "a", "URL", "." ]
54eeb8ff58ab7b44bb02549bbe2572625b449e4e
https://github.com/aoindustries/ao-encoding/blob/54eeb8ff58ab7b44bb02549bbe2572625b449e4e/src/main/java/com/aoindustries/encoding/ChainWriter.java#L623-L639
train
aoindustries/ao-encoding
src/main/java/com/aoindustries/encoding/ChainWriter.java
ChainWriter.writeHtmlImagePreloadJavaScript
public static void writeHtmlImagePreloadJavaScript(String url, Appendable out) throws IOException { out.append("<script type='text/javascript'>\n" + " var img=new Image();\n" + " img.src=\""); // Escape for javascript StringBuilder javascript = new StringBuilder(url.length()); encodeTextInJavaScript(url, javascript); // Encode for XML attribute encodeJavaScriptInXhtmlAttribute(javascript, out); out.append("\";\n" + "</script>"); }
java
public static void writeHtmlImagePreloadJavaScript(String url, Appendable out) throws IOException { out.append("<script type='text/javascript'>\n" + " var img=new Image();\n" + " img.src=\""); // Escape for javascript StringBuilder javascript = new StringBuilder(url.length()); encodeTextInJavaScript(url, javascript); // Encode for XML attribute encodeJavaScriptInXhtmlAttribute(javascript, out); out.append("\";\n" + "</script>"); }
[ "public", "static", "void", "writeHtmlImagePreloadJavaScript", "(", "String", "url", ",", "Appendable", "out", ")", "throws", "IOException", "{", "out", ".", "append", "(", "\"<script type='text/javascript'>\\n\"", "+", "\" var img=new Image();\\n\"", "+", "\" img.src=\\\"\"", ")", ";", "// Escape for javascript", "StringBuilder", "javascript", "=", "new", "StringBuilder", "(", "url", ".", "length", "(", ")", ")", ";", "encodeTextInJavaScript", "(", "url", ",", "javascript", ")", ";", "// Encode for XML attribute", "encodeJavaScriptInXhtmlAttribute", "(", "javascript", ",", "out", ")", ";", "out", ".", "append", "(", "\"\\\";\\n\"", "+", "\"</script>\"", ")", ";", "}" ]
Prints a JavaScript script that will preload the image at the provided URL. @param url This should be the URL-encoded URL, but with only a standalone ampersand (&amp;) as parameter separator (not &amp;amp;)
[ "Prints", "a", "JavaScript", "script", "that", "will", "preload", "the", "image", "at", "the", "provided", "URL", "." ]
54eeb8ff58ab7b44bb02549bbe2572625b449e4e
https://github.com/aoindustries/ao-encoding/blob/54eeb8ff58ab7b44bb02549bbe2572625b449e4e/src/main/java/com/aoindustries/encoding/ChainWriter.java#L718-L729
train
nightcode/yaranga
core/src/org/nightcode/common/base/Splitter.java
Splitter.split
public Map<String, String> split(final CharSequence source) { java.util.Objects.requireNonNull(source, "source"); Map<String, String> parameters = new HashMap<>(); Iterator<String> i = new StringIterator(source, pairSeparator); while (i.hasNext()) { String keyValue = i.next(); int keyValueSeparatorPosition = keyValueSeparatorStart(keyValue); if (keyValueSeparatorPosition == 0 || keyValue.length() == 0) { continue; } if (keyValueSeparatorPosition < 0) { parameters.put(keyValue, null); continue; } int keyStart = 0; int keyEnd = keyValueSeparatorPosition; while (keyStart < keyEnd && keyTrimMatcher.matches(keyValue.charAt(keyStart))) { keyStart++; } while (keyStart < keyEnd && keyTrimMatcher.matches(keyValue.charAt(keyEnd - 1))) { keyEnd--; } int valueStart = keyValueSeparatorPosition + keyValueSeparator.length(); int valueEnd = keyValue.length(); while (valueStart < valueEnd && valueTrimMatcher.matches(keyValue.charAt(valueStart))) { valueStart++; } while (valueStart < valueEnd && valueTrimMatcher.matches(keyValue.charAt(valueEnd - 1))) { valueEnd--; } String key = keyValue.substring(keyStart, keyEnd); String value = keyValue.substring(valueStart, valueEnd); parameters.put(key, value); } return parameters; }
java
public Map<String, String> split(final CharSequence source) { java.util.Objects.requireNonNull(source, "source"); Map<String, String> parameters = new HashMap<>(); Iterator<String> i = new StringIterator(source, pairSeparator); while (i.hasNext()) { String keyValue = i.next(); int keyValueSeparatorPosition = keyValueSeparatorStart(keyValue); if (keyValueSeparatorPosition == 0 || keyValue.length() == 0) { continue; } if (keyValueSeparatorPosition < 0) { parameters.put(keyValue, null); continue; } int keyStart = 0; int keyEnd = keyValueSeparatorPosition; while (keyStart < keyEnd && keyTrimMatcher.matches(keyValue.charAt(keyStart))) { keyStart++; } while (keyStart < keyEnd && keyTrimMatcher.matches(keyValue.charAt(keyEnd - 1))) { keyEnd--; } int valueStart = keyValueSeparatorPosition + keyValueSeparator.length(); int valueEnd = keyValue.length(); while (valueStart < valueEnd && valueTrimMatcher.matches(keyValue.charAt(valueStart))) { valueStart++; } while (valueStart < valueEnd && valueTrimMatcher.matches(keyValue.charAt(valueEnd - 1))) { valueEnd--; } String key = keyValue.substring(keyStart, keyEnd); String value = keyValue.substring(valueStart, valueEnd); parameters.put(key, value); } return parameters; }
[ "public", "Map", "<", "String", ",", "String", ">", "split", "(", "final", "CharSequence", "source", ")", "{", "java", ".", "util", ".", "Objects", ".", "requireNonNull", "(", "source", ",", "\"source\"", ")", ";", "Map", "<", "String", ",", "String", ">", "parameters", "=", "new", "HashMap", "<>", "(", ")", ";", "Iterator", "<", "String", ">", "i", "=", "new", "StringIterator", "(", "source", ",", "pairSeparator", ")", ";", "while", "(", "i", ".", "hasNext", "(", ")", ")", "{", "String", "keyValue", "=", "i", ".", "next", "(", ")", ";", "int", "keyValueSeparatorPosition", "=", "keyValueSeparatorStart", "(", "keyValue", ")", ";", "if", "(", "keyValueSeparatorPosition", "==", "0", "||", "keyValue", ".", "length", "(", ")", "==", "0", ")", "{", "continue", ";", "}", "if", "(", "keyValueSeparatorPosition", "<", "0", ")", "{", "parameters", ".", "put", "(", "keyValue", ",", "null", ")", ";", "continue", ";", "}", "int", "keyStart", "=", "0", ";", "int", "keyEnd", "=", "keyValueSeparatorPosition", ";", "while", "(", "keyStart", "<", "keyEnd", "&&", "keyTrimMatcher", ".", "matches", "(", "keyValue", ".", "charAt", "(", "keyStart", ")", ")", ")", "{", "keyStart", "++", ";", "}", "while", "(", "keyStart", "<", "keyEnd", "&&", "keyTrimMatcher", ".", "matches", "(", "keyValue", ".", "charAt", "(", "keyEnd", "-", "1", ")", ")", ")", "{", "keyEnd", "--", ";", "}", "int", "valueStart", "=", "keyValueSeparatorPosition", "+", "keyValueSeparator", ".", "length", "(", ")", ";", "int", "valueEnd", "=", "keyValue", ".", "length", "(", ")", ";", "while", "(", "valueStart", "<", "valueEnd", "&&", "valueTrimMatcher", ".", "matches", "(", "keyValue", ".", "charAt", "(", "valueStart", ")", ")", ")", "{", "valueStart", "++", ";", "}", "while", "(", "valueStart", "<", "valueEnd", "&&", "valueTrimMatcher", ".", "matches", "(", "keyValue", ".", "charAt", "(", "valueEnd", "-", "1", ")", ")", ")", "{", "valueEnd", "--", ";", "}", "String", "key", "=", "keyValue", ".", "substring", "(", "keyStart", ",", "keyEnd", ")", ";", "String", "value", "=", "keyValue", ".", "substring", "(", "valueStart", ",", "valueEnd", ")", ";", "parameters", ".", "put", "(", "key", ",", "value", ")", ";", "}", "return", "parameters", ";", "}" ]
Splits the CharSequence passed in parameter. @param source the sequence of characters to split @return a map of key/value pairs
[ "Splits", "the", "CharSequence", "passed", "in", "parameter", "." ]
f02cf8d8bcd365b6b1d55638938631a00e9ee808
https://github.com/nightcode/yaranga/blob/f02cf8d8bcd365b6b1d55638938631a00e9ee808/core/src/org/nightcode/common/base/Splitter.java#L91-L131
train
nightcode/yaranga
core/src/org/nightcode/common/base/Splitter.java
Splitter.trim
public Splitter trim(char c) { Matcher matcher = new CharMatcher(c); return new Splitter(pairSeparator, keyValueSeparator, matcher, matcher); }
java
public Splitter trim(char c) { Matcher matcher = new CharMatcher(c); return new Splitter(pairSeparator, keyValueSeparator, matcher, matcher); }
[ "public", "Splitter", "trim", "(", "char", "c", ")", "{", "Matcher", "matcher", "=", "new", "CharMatcher", "(", "c", ")", ";", "return", "new", "Splitter", "(", "pairSeparator", ",", "keyValueSeparator", ",", "matcher", ",", "matcher", ")", ";", "}" ]
Returns a splitter that removes all leading or trailing characters matching the given character from each returned key and value. @param c character @return a splitter with the desired configuration
[ "Returns", "a", "splitter", "that", "removes", "all", "leading", "or", "trailing", "characters", "matching", "the", "given", "character", "from", "each", "returned", "key", "and", "value", "." ]
f02cf8d8bcd365b6b1d55638938631a00e9ee808
https://github.com/nightcode/yaranga/blob/f02cf8d8bcd365b6b1d55638938631a00e9ee808/core/src/org/nightcode/common/base/Splitter.java#L140-L143
train
nightcode/yaranga
core/src/org/nightcode/common/base/Splitter.java
Splitter.trim
public Splitter trim(char[] chars) { Matcher matcher = new CharsMatcher(chars); return new Splitter(pairSeparator, keyValueSeparator, matcher, matcher); }
java
public Splitter trim(char[] chars) { Matcher matcher = new CharsMatcher(chars); return new Splitter(pairSeparator, keyValueSeparator, matcher, matcher); }
[ "public", "Splitter", "trim", "(", "char", "[", "]", "chars", ")", "{", "Matcher", "matcher", "=", "new", "CharsMatcher", "(", "chars", ")", ";", "return", "new", "Splitter", "(", "pairSeparator", ",", "keyValueSeparator", ",", "matcher", ",", "matcher", ")", ";", "}" ]
Returns a splitter that removes all leading or trailing characters matching the given characters from each returned key and value. @param chars characters @return a splitter with the desired configuration
[ "Returns", "a", "splitter", "that", "removes", "all", "leading", "or", "trailing", "characters", "matching", "the", "given", "characters", "from", "each", "returned", "key", "and", "value", "." ]
f02cf8d8bcd365b6b1d55638938631a00e9ee808
https://github.com/nightcode/yaranga/blob/f02cf8d8bcd365b6b1d55638938631a00e9ee808/core/src/org/nightcode/common/base/Splitter.java#L152-L155
train
venkatramanm/common
src/main/java/com/venky/cache/PersistentCache.java
PersistentCache.close
public void close() { super.clear(); if (indexMap != null){ indexMap.clear(); indexMap = null; } if (this.indexStore != null){ getIndexStore().close(); this.indexStore = null ; } if (this.cacheStore != null){ getCacheStore().close(); this.cacheStore = null ; } }
java
public void close() { super.clear(); if (indexMap != null){ indexMap.clear(); indexMap = null; } if (this.indexStore != null){ getIndexStore().close(); this.indexStore = null ; } if (this.cacheStore != null){ getCacheStore().close(); this.cacheStore = null ; } }
[ "public", "void", "close", "(", ")", "{", "super", ".", "clear", "(", ")", ";", "if", "(", "indexMap", "!=", "null", ")", "{", "indexMap", ".", "clear", "(", ")", ";", "indexMap", "=", "null", ";", "}", "if", "(", "this", ".", "indexStore", "!=", "null", ")", "{", "getIndexStore", "(", ")", ".", "close", "(", ")", ";", "this", ".", "indexStore", "=", "null", ";", "}", "if", "(", "this", ".", "cacheStore", "!=", "null", ")", "{", "getCacheStore", "(", ")", ".", "close", "(", ")", ";", "this", ".", "cacheStore", "=", "null", ";", "}", "}" ]
Ensure closing without opening should notbe an issue.
[ "Ensure", "closing", "without", "opening", "should", "notbe", "an", "issue", "." ]
b89583efd674f73cf4c04927300a9ea6e49a3e9f
https://github.com/venkatramanm/common/blob/b89583efd674f73cf4c04927300a9ea6e49a3e9f/src/main/java/com/venky/cache/PersistentCache.java#L374-L388
train
maochen/NLP
CoreNLP-NLP/src/main/java/org/maochen/nlp/ml/classifier/maxent/GISTrainer.java
GISTrainer.gaussianUpdate
private double gaussianUpdate(int predicate, int oid, double correctionConstant) { double param = params[predicate].getParameters()[oid]; double x0 = 0.0; double modelValue = modelExpects[0][predicate].getParameters()[oid]; double observedValue = observedExpects[predicate].getParameters()[oid]; for (int i = 0; i < 50; i++) { double tmp = modelValue * Math.exp(correctionConstant * x0); double f = tmp + (param + x0) / sigma - observedValue; double fp = tmp * correctionConstant + 1 / sigma; if (fp == 0) { break; } double x = x0 - f / fp; if (Math.abs(x - x0) < 0.000001) { x0 = x; break; } x0 = x; } return x0; }
java
private double gaussianUpdate(int predicate, int oid, double correctionConstant) { double param = params[predicate].getParameters()[oid]; double x0 = 0.0; double modelValue = modelExpects[0][predicate].getParameters()[oid]; double observedValue = observedExpects[predicate].getParameters()[oid]; for (int i = 0; i < 50; i++) { double tmp = modelValue * Math.exp(correctionConstant * x0); double f = tmp + (param + x0) / sigma - observedValue; double fp = tmp * correctionConstant + 1 / sigma; if (fp == 0) { break; } double x = x0 - f / fp; if (Math.abs(x - x0) < 0.000001) { x0 = x; break; } x0 = x; } return x0; }
[ "private", "double", "gaussianUpdate", "(", "int", "predicate", ",", "int", "oid", ",", "double", "correctionConstant", ")", "{", "double", "param", "=", "params", "[", "predicate", "]", ".", "getParameters", "(", ")", "[", "oid", "]", ";", "double", "x0", "=", "0.0", ";", "double", "modelValue", "=", "modelExpects", "[", "0", "]", "[", "predicate", "]", ".", "getParameters", "(", ")", "[", "oid", "]", ";", "double", "observedValue", "=", "observedExpects", "[", "predicate", "]", ".", "getParameters", "(", ")", "[", "oid", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "50", ";", "i", "++", ")", "{", "double", "tmp", "=", "modelValue", "*", "Math", ".", "exp", "(", "correctionConstant", "*", "x0", ")", ";", "double", "f", "=", "tmp", "+", "(", "param", "+", "x0", ")", "/", "sigma", "-", "observedValue", ";", "double", "fp", "=", "tmp", "*", "correctionConstant", "+", "1", "/", "sigma", ";", "if", "(", "fp", "==", "0", ")", "{", "break", ";", "}", "double", "x", "=", "x0", "-", "f", "/", "fp", ";", "if", "(", "Math", ".", "abs", "(", "x", "-", "x0", ")", "<", "0.000001", ")", "{", "x0", "=", "x", ";", "break", ";", "}", "x0", "=", "x", ";", "}", "return", "x0", ";", "}" ]
modeled on implementation in Zhang Le's maxent kit
[ "modeled", "on", "implementation", "in", "Zhang", "Le", "s", "maxent", "kit" ]
38ae7b384d5295334d9efa9dc4cd901b19d9c27e
https://github.com/maochen/NLP/blob/38ae7b384d5295334d9efa9dc4cd901b19d9c27e/CoreNLP-NLP/src/main/java/org/maochen/nlp/ml/classifier/maxent/GISTrainer.java#L360-L380
train
aoindustries/ao-encoding
src/main/java/com/aoindustries/encoding/BufferedEncoder.java
BufferedEncoder.writeSuffixTo
@Override final public void writeSuffixTo(Appendable out) throws IOException { writeSuffix(buffer, out); buffer.setLength(0); }
java
@Override final public void writeSuffixTo(Appendable out) throws IOException { writeSuffix(buffer, out); buffer.setLength(0); }
[ "@", "Override", "final", "public", "void", "writeSuffixTo", "(", "Appendable", "out", ")", "throws", "IOException", "{", "writeSuffix", "(", "buffer", ",", "out", ")", ";", "buffer", ".", "setLength", "(", "0", ")", ";", "}" ]
Writes the suffix and clears the buffer for reuse.
[ "Writes", "the", "suffix", "and", "clears", "the", "buffer", "for", "reuse", "." ]
54eeb8ff58ab7b44bb02549bbe2572625b449e4e
https://github.com/aoindustries/ao-encoding/blob/54eeb8ff58ab7b44bb02549bbe2572625b449e4e/src/main/java/com/aoindustries/encoding/BufferedEncoder.java#L92-L96
train
aoindustries/ao-encoding
src/main/java/com/aoindustries/encoding/Coercion.java
Coercion.nullIfEmpty
public static <T> T nullIfEmpty(T value) throws IOException { return isEmpty(value) ? null : value; }
java
public static <T> T nullIfEmpty(T value) throws IOException { return isEmpty(value) ? null : value; }
[ "public", "static", "<", "T", ">", "T", "nullIfEmpty", "(", "T", "value", ")", "throws", "IOException", "{", "return", "isEmpty", "(", "value", ")", "?", "null", ":", "value", ";", "}" ]
Returns the provided value or null if the value is empty. @see #isEmpty(java.lang.Object)
[ "Returns", "the", "provided", "value", "or", "null", "if", "the", "value", "is", "empty", "." ]
54eeb8ff58ab7b44bb02549bbe2572625b449e4e
https://github.com/aoindustries/ao-encoding/blob/54eeb8ff58ab7b44bb02549bbe2572625b449e4e/src/main/java/com/aoindustries/encoding/Coercion.java#L278-L280
train
crowmagnumb/s6-util
src/main/java/net/crowmagnumb/util/string/StringUtilities.java
StringUtilities.toCapCase
public static String toCapCase( final String string ) { if ( string == null ) { return null; } if( string.length() == 1 ) { return string.toUpperCase(); } return Character.toUpperCase( string.charAt( 0 ) ) + string.substring( 1 ).toLowerCase(); }
java
public static String toCapCase( final String string ) { if ( string == null ) { return null; } if( string.length() == 1 ) { return string.toUpperCase(); } return Character.toUpperCase( string.charAt( 0 ) ) + string.substring( 1 ).toLowerCase(); }
[ "public", "static", "String", "toCapCase", "(", "final", "String", "string", ")", "{", "if", "(", "string", "==", "null", ")", "{", "return", "null", ";", "}", "if", "(", "string", ".", "length", "(", ")", "==", "1", ")", "{", "return", "string", ".", "toUpperCase", "(", ")", ";", "}", "return", "Character", ".", "toUpperCase", "(", "string", ".", "charAt", "(", "0", ")", ")", "+", "string", ".", "substring", "(", "1", ")", ".", "toLowerCase", "(", ")", ";", "}" ]
Takes the first letter and capitalizes it. @param string String we are capitalizing @return Capitalized string
[ "Takes", "the", "first", "letter", "and", "capitalizes", "it", "." ]
0f9969bc0809e8a617501fa57c135e9b3984fae0
https://github.com/crowmagnumb/s6-util/blob/0f9969bc0809e8a617501fa57c135e9b3984fae0/src/main/java/net/crowmagnumb/util/string/StringUtilities.java#L468-L481
train
crowmagnumb/s6-util
src/main/java/net/crowmagnumb/util/string/StringUtilities.java
StringUtilities.appendToBuffer
public static void appendToBuffer( final StringBuffer buffer, final String string, final String delimiter ) { if ( string == null ) { return; } // // Only append the delimiter in front if the buffer isn't empty. // if ( buffer.length() == 0 || delimiter == null ) { buffer.append( string ); } else { buffer.append( delimiter ).append( string ); } }
java
public static void appendToBuffer( final StringBuffer buffer, final String string, final String delimiter ) { if ( string == null ) { return; } // // Only append the delimiter in front if the buffer isn't empty. // if ( buffer.length() == 0 || delimiter == null ) { buffer.append( string ); } else { buffer.append( delimiter ).append( string ); } }
[ "public", "static", "void", "appendToBuffer", "(", "final", "StringBuffer", "buffer", ",", "final", "String", "string", ",", "final", "String", "delimiter", ")", "{", "if", "(", "string", "==", "null", ")", "{", "return", ";", "}", "//", "// Only append the delimiter in front if the buffer isn't empty.", "//", "if", "(", "buffer", ".", "length", "(", ")", "==", "0", "||", "delimiter", "==", "null", ")", "{", "buffer", ".", "append", "(", "string", ")", ";", "}", "else", "{", "buffer", ".", "append", "(", "delimiter", ")", ".", "append", "(", "string", ")", ";", "}", "}" ]
Appends a string to a buffer, prepending with a delimiter string. For instance, this may be used to create a string of comma-delimited values. This does not ignore empty strings. @param buffer Our initial buffer string. @param string String we are adding to the buffer @param delimiter Delimiter that gets appended to the buffer before the string to be appended
[ "Appends", "a", "string", "to", "a", "buffer", "prepending", "with", "a", "delimiter", "string", ".", "For", "instance", "this", "may", "be", "used", "to", "create", "a", "string", "of", "comma", "-", "delimited", "values", ".", "This", "does", "not", "ignore", "empty", "strings", "." ]
0f9969bc0809e8a617501fa57c135e9b3984fae0
https://github.com/crowmagnumb/s6-util/blob/0f9969bc0809e8a617501fa57c135e9b3984fae0/src/main/java/net/crowmagnumb/util/string/StringUtilities.java#L497-L517
train
crowmagnumb/s6-util
src/main/java/net/crowmagnumb/util/string/StringUtilities.java
StringUtilities.coalesce
@SafeVarargs public static <T> T coalesce( final T ... things ) { if( things == null || things.length == 0 ) { return null; } for( T thing : things ) { if( thing != null ) { return thing; } } return null; }
java
@SafeVarargs public static <T> T coalesce( final T ... things ) { if( things == null || things.length == 0 ) { return null; } for( T thing : things ) { if( thing != null ) { return thing; } } return null; }
[ "@", "SafeVarargs", "public", "static", "<", "T", ">", "T", "coalesce", "(", "final", "T", "...", "things", ")", "{", "if", "(", "things", "==", "null", "||", "things", ".", "length", "==", "0", ")", "{", "return", "null", ";", "}", "for", "(", "T", "thing", ":", "things", ")", "{", "if", "(", "thing", "!=", "null", ")", "{", "return", "thing", ";", "}", "}", "return", "null", ";", "}" ]
Similar to SQL coalesce, returns the first non-null argument @param things to check for non nullness @param <T> type of thing @return first non-null thing
[ "Similar", "to", "SQL", "coalesce", "returns", "the", "first", "non", "-", "null", "argument" ]
0f9969bc0809e8a617501fa57c135e9b3984fae0
https://github.com/crowmagnumb/s6-util/blob/0f9969bc0809e8a617501fa57c135e9b3984fae0/src/main/java/net/crowmagnumb/util/string/StringUtilities.java#L2183-L2200
train
crowmagnumb/s6-util
src/main/java/net/crowmagnumb/util/string/StringUtilities.java
StringUtilities.coalesceNonEmpty
@SafeVarargs public static <T> T coalesceNonEmpty( final T ... things ) { if( things == null || things.length == 0 ) { return null; } for( T thing : things ) { if( thing instanceof CharSequence ) { if( ! StringUtils.isBlank( (CharSequence) thing ) ) { return thing; } } else if( thing != null ) { return thing; } } return null; }
java
@SafeVarargs public static <T> T coalesceNonEmpty( final T ... things ) { if( things == null || things.length == 0 ) { return null; } for( T thing : things ) { if( thing instanceof CharSequence ) { if( ! StringUtils.isBlank( (CharSequence) thing ) ) { return thing; } } else if( thing != null ) { return thing; } } return null; }
[ "@", "SafeVarargs", "public", "static", "<", "T", ">", "T", "coalesceNonEmpty", "(", "final", "T", "...", "things", ")", "{", "if", "(", "things", "==", "null", "||", "things", ".", "length", "==", "0", ")", "{", "return", "null", ";", "}", "for", "(", "T", "thing", ":", "things", ")", "{", "if", "(", "thing", "instanceof", "CharSequence", ")", "{", "if", "(", "!", "StringUtils", ".", "isBlank", "(", "(", "CharSequence", ")", "thing", ")", ")", "{", "return", "thing", ";", "}", "}", "else", "if", "(", "thing", "!=", "null", ")", "{", "return", "thing", ";", "}", "}", "return", "null", ";", "}" ]
Similar to SQL coalesce, returns the first non-EMPTY argument @param things to check for non emptiness @param <T> type of thing @return first non-empty thing
[ "Similar", "to", "SQL", "coalesce", "returns", "the", "first", "non", "-", "EMPTY", "argument" ]
0f9969bc0809e8a617501fa57c135e9b3984fae0
https://github.com/crowmagnumb/s6-util/blob/0f9969bc0809e8a617501fa57c135e9b3984fae0/src/main/java/net/crowmagnumb/util/string/StringUtilities.java#L2210-L2234
train
aoindustries/ao-taglib
src/main/java/com/aoindustries/taglib/InputTagBeanInfo.java
InputTagBeanInfo.getAdditionalBeanInfo
@Override public BeanInfo[] getAdditionalBeanInfo() { try { return new BeanInfo[] { Introspector.getBeanInfo(InputTag.class.getSuperclass()) }; } catch(IntrospectionException err) { throw new AssertionError(err); } }
java
@Override public BeanInfo[] getAdditionalBeanInfo() { try { return new BeanInfo[] { Introspector.getBeanInfo(InputTag.class.getSuperclass()) }; } catch(IntrospectionException err) { throw new AssertionError(err); } }
[ "@", "Override", "public", "BeanInfo", "[", "]", "getAdditionalBeanInfo", "(", ")", "{", "try", "{", "return", "new", "BeanInfo", "[", "]", "{", "Introspector", ".", "getBeanInfo", "(", "InputTag", ".", "class", ".", "getSuperclass", "(", ")", ")", "}", ";", "}", "catch", "(", "IntrospectionException", "err", ")", "{", "throw", "new", "AssertionError", "(", "err", ")", ";", "}", "}" ]
Include base class.
[ "Include", "base", "class", "." ]
5670eba8485196bd42d31d3ff09a42deacb025f8
https://github.com/aoindustries/ao-taglib/blob/5670eba8485196bd42d31d3ff09a42deacb025f8/src/main/java/com/aoindustries/taglib/InputTagBeanInfo.java#L76-L85
train
crowmagnumb/s6-util
src/main/java/net/crowmagnumb/util/OsUtils.java
OsUtils.fileNameFromString
public static String fileNameFromString( final String text ) { String value = text.replace( ' ', '_' ); if ( value.length() < 48 ) { return value; } return value.substring( 0, 47 ); }
java
public static String fileNameFromString( final String text ) { String value = text.replace( ' ', '_' ); if ( value.length() < 48 ) { return value; } return value.substring( 0, 47 ); }
[ "public", "static", "String", "fileNameFromString", "(", "final", "String", "text", ")", "{", "String", "value", "=", "text", ".", "replace", "(", "'", "'", ",", "'", "'", ")", ";", "if", "(", "value", ".", "length", "(", ")", "<", "48", ")", "{", "return", "value", ";", "}", "return", "value", ".", "substring", "(", "0", ",", "47", ")", ";", "}" ]
This method takes a string and converts it into a filename by replacing any spaces with underscores and then also truncating it if it is over a certain length. At the time of the writing of this comment that was 48 characters which was chosen by pulling a number out of my brain. @param text Text to convert to usable filename @return usable filename
[ "This", "method", "takes", "a", "string", "and", "converts", "it", "into", "a", "filename", "by", "replacing", "any", "spaces", "with", "underscores", "and", "then", "also", "truncating", "it", "if", "it", "is", "over", "a", "certain", "length", ".", "At", "the", "time", "of", "the", "writing", "of", "this", "comment", "that", "was", "48", "characters", "which", "was", "chosen", "by", "pulling", "a", "number", "out", "of", "my", "brain", "." ]
0f9969bc0809e8a617501fa57c135e9b3984fae0
https://github.com/crowmagnumb/s6-util/blob/0f9969bc0809e8a617501fa57c135e9b3984fae0/src/main/java/net/crowmagnumb/util/OsUtils.java#L374-L384
train
crowmagnumb/s6-util
src/main/java/net/crowmagnumb/util/OsUtils.java
OsUtils.executeToFile
public static int executeToFile( final String[] command, final File file ) throws IOException, InterruptedException { return executeToFile( command, file, System.err ); }
java
public static int executeToFile( final String[] command, final File file ) throws IOException, InterruptedException { return executeToFile( command, file, System.err ); }
[ "public", "static", "int", "executeToFile", "(", "final", "String", "[", "]", "command", ",", "final", "File", "file", ")", "throws", "IOException", ",", "InterruptedException", "{", "return", "executeToFile", "(", "command", ",", "file", ",", "System", ".", "err", ")", ";", "}" ]
Executes the given command, redirecting stdout to the given file and stderr to actual stderr @param command array of commands to run @param file to write stdout @return error code from system @throws java.io.IOException if problems @throws java.lang.InterruptedException if interrupted
[ "Executes", "the", "given", "command", "redirecting", "stdout", "to", "the", "given", "file", "and", "stderr", "to", "actual", "stderr" ]
0f9969bc0809e8a617501fa57c135e9b3984fae0
https://github.com/crowmagnumb/s6-util/blob/0f9969bc0809e8a617501fa57c135e9b3984fae0/src/main/java/net/crowmagnumb/util/OsUtils.java#L397-L404
train
crowmagnumb/s6-util
src/main/java/net/crowmagnumb/util/OsUtils.java
OsUtils.executeToFile
public static int executeToFile( final String[] command, final File file, final OutputStream stderr ) throws IOException, InterruptedException { return executeToStreams( command, new FileOutputStream( file ), stderr ); }
java
public static int executeToFile( final String[] command, final File file, final OutputStream stderr ) throws IOException, InterruptedException { return executeToStreams( command, new FileOutputStream( file ), stderr ); }
[ "public", "static", "int", "executeToFile", "(", "final", "String", "[", "]", "command", ",", "final", "File", "file", ",", "final", "OutputStream", "stderr", ")", "throws", "IOException", ",", "InterruptedException", "{", "return", "executeToStreams", "(", "command", ",", "new", "FileOutputStream", "(", "file", ")", ",", "stderr", ")", ";", "}" ]
Executes the given command, redirecting stdout to the given file and stderr to the given stream @param command array of commands to run @param file file to write stdout @param stderr output stream for stderr @return error code from system @throws java.io.IOException if problems @throws java.lang.InterruptedException if interrupted
[ "Executes", "the", "given", "command", "redirecting", "stdout", "to", "the", "given", "file", "and", "stderr", "to", "the", "given", "stream" ]
0f9969bc0809e8a617501fa57c135e9b3984fae0
https://github.com/crowmagnumb/s6-util/blob/0f9969bc0809e8a617501fa57c135e9b3984fae0/src/main/java/net/crowmagnumb/util/OsUtils.java#L441-L449
train
crowmagnumb/s6-util
src/main/java/net/crowmagnumb/util/OsUtils.java
OsUtils.makeSecurityCheck
public static void makeSecurityCheck( final File file, final File base ) { if( ! file.getAbsolutePath().startsWith( base.getAbsolutePath() ) ) { throw new IllegalArgumentException( "Illegal file path [" + file + "]" ); } }
java
public static void makeSecurityCheck( final File file, final File base ) { if( ! file.getAbsolutePath().startsWith( base.getAbsolutePath() ) ) { throw new IllegalArgumentException( "Illegal file path [" + file + "]" ); } }
[ "public", "static", "void", "makeSecurityCheck", "(", "final", "File", "file", ",", "final", "File", "base", ")", "{", "if", "(", "!", "file", ".", "getAbsolutePath", "(", ")", ".", "startsWith", "(", "base", ".", "getAbsolutePath", "(", ")", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Illegal file path [\"", "+", "file", "+", "\"]\"", ")", ";", "}", "}" ]
Check to make sure the user has not put .. anywhere in the path to allow overwriting of system files. Throws IllegalArgumentException if it fails the check. @param file file to check @param base base directory to compare it to.
[ "Check", "to", "make", "sure", "the", "user", "has", "not", "put", "..", "anywhere", "in", "the", "path", "to", "allow", "overwriting", "of", "system", "files", ".", "Throws", "IllegalArgumentException", "if", "it", "fails", "the", "check", "." ]
0f9969bc0809e8a617501fa57c135e9b3984fae0
https://github.com/crowmagnumb/s6-util/blob/0f9969bc0809e8a617501fa57c135e9b3984fae0/src/main/java/net/crowmagnumb/util/OsUtils.java#L1080-L1087
train
aoindustries/ao-taglib
src/main/java/com/aoindustries/taglib/LinkTag.java
LinkTag.setLink
public void setLink(Link link) { setHref(link.getHref()); setHrefAbsolute(link.getHrefAbsolute()); HttpParameters linkParams = link.getParams(); if(linkParams != null) { for(Map.Entry<String,List<String>> entry : linkParams.getParameterMap().entrySet()) { String paramName = entry.getKey(); for(String paramValue : entry.getValue()) { addParam(paramName, paramValue); } } } this.addLastModified = link.getAddLastModified(); setHreflang(link.getHreflang()); setRel(link.getRel()); setType(link.getType()); setMedia(link.getMedia()); setTitle(link.getTitle()); }
java
public void setLink(Link link) { setHref(link.getHref()); setHrefAbsolute(link.getHrefAbsolute()); HttpParameters linkParams = link.getParams(); if(linkParams != null) { for(Map.Entry<String,List<String>> entry : linkParams.getParameterMap().entrySet()) { String paramName = entry.getKey(); for(String paramValue : entry.getValue()) { addParam(paramName, paramValue); } } } this.addLastModified = link.getAddLastModified(); setHreflang(link.getHreflang()); setRel(link.getRel()); setType(link.getType()); setMedia(link.getMedia()); setTitle(link.getTitle()); }
[ "public", "void", "setLink", "(", "Link", "link", ")", "{", "setHref", "(", "link", ".", "getHref", "(", ")", ")", ";", "setHrefAbsolute", "(", "link", ".", "getHrefAbsolute", "(", ")", ")", ";", "HttpParameters", "linkParams", "=", "link", ".", "getParams", "(", ")", ";", "if", "(", "linkParams", "!=", "null", ")", "{", "for", "(", "Map", ".", "Entry", "<", "String", ",", "List", "<", "String", ">", ">", "entry", ":", "linkParams", ".", "getParameterMap", "(", ")", ".", "entrySet", "(", ")", ")", "{", "String", "paramName", "=", "entry", ".", "getKey", "(", ")", ";", "for", "(", "String", "paramValue", ":", "entry", ".", "getValue", "(", ")", ")", "{", "addParam", "(", "paramName", ",", "paramValue", ")", ";", "}", "}", "}", "this", ".", "addLastModified", "=", "link", ".", "getAddLastModified", "(", ")", ";", "setHreflang", "(", "link", ".", "getHreflang", "(", ")", ")", ";", "setRel", "(", "link", ".", "getRel", "(", ")", ")", ";", "setType", "(", "link", ".", "getType", "(", ")", ")", ";", "setMedia", "(", "link", ".", "getMedia", "(", ")", ")", ";", "setTitle", "(", "link", ".", "getTitle", "(", ")", ")", ";", "}" ]
Copies all values from the provided link.
[ "Copies", "all", "values", "from", "the", "provided", "link", "." ]
5670eba8485196bd42d31d3ff09a42deacb025f8
https://github.com/aoindustries/ao-taglib/blob/5670eba8485196bd42d31d3ff09a42deacb025f8/src/main/java/com/aoindustries/taglib/LinkTag.java#L76-L94
train
maochen/NLP
CoreNLP-NLP/src/main/java/org/maochen/nlp/ml/classifier/maxent/OnePassRealValueDataIndexer.java
OnePassRealValueDataIndexer.update
protected static void update(String[] ec, Set<String> predicateSet, Map<String, Integer> counter, int cutoff) { for (String s : ec) { Integer val = counter.get(s); val = val == null ? 1 : val + 1; counter.put(s, val); if (!predicateSet.contains(s) && counter.get(s) >= cutoff) { predicateSet.add(s); } } }
java
protected static void update(String[] ec, Set<String> predicateSet, Map<String, Integer> counter, int cutoff) { for (String s : ec) { Integer val = counter.get(s); val = val == null ? 1 : val + 1; counter.put(s, val); if (!predicateSet.contains(s) && counter.get(s) >= cutoff) { predicateSet.add(s); } } }
[ "protected", "static", "void", "update", "(", "String", "[", "]", "ec", ",", "Set", "<", "String", ">", "predicateSet", ",", "Map", "<", "String", ",", "Integer", ">", "counter", ",", "int", "cutoff", ")", "{", "for", "(", "String", "s", ":", "ec", ")", "{", "Integer", "val", "=", "counter", ".", "get", "(", "s", ")", ";", "val", "=", "val", "==", "null", "?", "1", ":", "val", "+", "1", ";", "counter", ".", "put", "(", "s", ",", "val", ")", ";", "if", "(", "!", "predicateSet", ".", "contains", "(", "s", ")", "&&", "counter", ".", "get", "(", "s", ")", ">=", "cutoff", ")", "{", "predicateSet", ".", "add", "(", "s", ")", ";", "}", "}", "}" ]
Updates the set of predicated and counter with the specified event contexts and cutoff. @param ec The contexts/features which occur in a event. @param predicateSet The set of predicates which will be used for model building. @param counter The predicate counters. @param cutoff The cutoff which determines whether a predicate is included.
[ "Updates", "the", "set", "of", "predicated", "and", "counter", "with", "the", "specified", "event", "contexts", "and", "cutoff", "." ]
38ae7b384d5295334d9efa9dc4cd901b19d9c27e
https://github.com/maochen/NLP/blob/38ae7b384d5295334d9efa9dc4cd901b19d9c27e/CoreNLP-NLP/src/main/java/org/maochen/nlp/ml/classifier/maxent/OnePassRealValueDataIndexer.java#L130-L140
train
maochen/NLP
CoreNLP-NLP/src/main/java/org/maochen/nlp/parser/stanford/nn/StanfordNNDepParser.java
StanfordNNDepParser.tagDependencies
private GrammaticalStructure tagDependencies(List<? extends HasWord> taggedWords) { GrammaticalStructure gs = nndepParser.predict(taggedWords); return gs; }
java
private GrammaticalStructure tagDependencies(List<? extends HasWord> taggedWords) { GrammaticalStructure gs = nndepParser.predict(taggedWords); return gs; }
[ "private", "GrammaticalStructure", "tagDependencies", "(", "List", "<", "?", "extends", "HasWord", ">", "taggedWords", ")", "{", "GrammaticalStructure", "gs", "=", "nndepParser", ".", "predict", "(", "taggedWords", ")", ";", "return", "gs", ";", "}" ]
4. Dependency Label
[ "4", ".", "Dependency", "Label" ]
38ae7b384d5295334d9efa9dc4cd901b19d9c27e
https://github.com/maochen/NLP/blob/38ae7b384d5295334d9efa9dc4cd901b19d9c27e/CoreNLP-NLP/src/main/java/org/maochen/nlp/parser/stanford/nn/StanfordNNDepParser.java#L21-L24
train
maochen/NLP
CoreNLP-NLP/src/main/java/org/maochen/nlp/ml/classifier/FeatureIndexer.java
FeatureIndexer.getFeatNames
public String[] getFeatNames() { String[] namesArray = new String[nameIndexMap.size()]; for (Map.Entry<String, Integer> entry : nameIndexMap.entrySet()) { namesArray[entry.getValue()] = entry.getKey(); } return namesArray; }
java
public String[] getFeatNames() { String[] namesArray = new String[nameIndexMap.size()]; for (Map.Entry<String, Integer> entry : nameIndexMap.entrySet()) { namesArray[entry.getValue()] = entry.getKey(); } return namesArray; }
[ "public", "String", "[", "]", "getFeatNames", "(", ")", "{", "String", "[", "]", "namesArray", "=", "new", "String", "[", "nameIndexMap", ".", "size", "(", ")", "]", ";", "for", "(", "Map", ".", "Entry", "<", "String", ",", "Integer", ">", "entry", ":", "nameIndexMap", ".", "entrySet", "(", ")", ")", "{", "namesArray", "[", "entry", ".", "getValue", "(", ")", "]", "=", "entry", ".", "getKey", "(", ")", ";", "}", "return", "namesArray", ";", "}" ]
This method should only be used for print or debug purpose. @return Array of feat names. Index corresponding to feat vector's Index.
[ "This", "method", "should", "only", "be", "used", "for", "print", "or", "debug", "purpose", "." ]
38ae7b384d5295334d9efa9dc4cd901b19d9c27e
https://github.com/maochen/NLP/blob/38ae7b384d5295334d9efa9dc4cd901b19d9c27e/CoreNLP-NLP/src/main/java/org/maochen/nlp/ml/classifier/FeatureIndexer.java#L64-L72
train
maochen/NLP
CoreNLP-NLP/src/main/java/org/maochen/nlp/parser/stanford/pcfg/StanfordPCFGParser.java
StanfordPCFGParser.tagPOS
public void tagPOS(List<CoreLabel> tokens, Tree tree) { try { List<TaggedWord> posList = tree.getChild(0).taggedYield(); for (int i = 0; i < tokens.size(); i++) { String pos = posList.get(i).tag(); tokens.get(i).setTag(pos); } } catch (Exception e) { tagPOS(tokens); // At least gives you something. LOG.warn("POS Failed:\n" + tree.pennString()); } }
java
public void tagPOS(List<CoreLabel> tokens, Tree tree) { try { List<TaggedWord> posList = tree.getChild(0).taggedYield(); for (int i = 0; i < tokens.size(); i++) { String pos = posList.get(i).tag(); tokens.get(i).setTag(pos); } } catch (Exception e) { tagPOS(tokens); // At least gives you something. LOG.warn("POS Failed:\n" + tree.pennString()); } }
[ "public", "void", "tagPOS", "(", "List", "<", "CoreLabel", ">", "tokens", ",", "Tree", "tree", ")", "{", "try", "{", "List", "<", "TaggedWord", ">", "posList", "=", "tree", ".", "getChild", "(", "0", ")", ".", "taggedYield", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "tokens", ".", "size", "(", ")", ";", "i", "++", ")", "{", "String", "pos", "=", "posList", ".", "get", "(", "i", ")", ".", "tag", "(", ")", ";", "tokens", ".", "get", "(", "i", ")", ".", "setTag", "(", "pos", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "tagPOS", "(", "tokens", ")", ";", "// At least gives you something.", "LOG", ".", "warn", "(", "\"POS Failed:\\n\"", "+", "tree", ".", "pennString", "(", ")", ")", ";", "}", "}" ]
This is for the backward compatibility
[ "This", "is", "for", "the", "backward", "compatibility" ]
38ae7b384d5295334d9efa9dc4cd901b19d9c27e
https://github.com/maochen/NLP/blob/38ae7b384d5295334d9efa9dc4cd901b19d9c27e/CoreNLP-NLP/src/main/java/org/maochen/nlp/parser/stanford/pcfg/StanfordPCFGParser.java#L38-L49
train
maochen/NLP
CoreNLP-NLP/src/main/java/org/maochen/nlp/parser/stanford/pcfg/StanfordPCFGParser.java
StanfordPCFGParser.parseForCoref
public Pair<CoreMap, GrammaticalStructure> parseForCoref(String sentence) { List<CoreLabel> tokens = stanfordTokenize(sentence); Tree tree = parser.parse(tokens); GrammaticalStructure gs = tagDependencies(tree, true); tagPOS(tokens); tagLemma(tokens); tagNamedEntity(tokens); CoreMap result = new ArrayCoreMap(); result.set(CoreAnnotations.TokensAnnotation.class, tokens); result.set(TreeCoreAnnotations.TreeAnnotation.class, tree); GrammaticalStructure.Extras extras = GrammaticalStructure.Extras.NONE; SemanticGraph deps = SemanticGraphFactory.generateCollapsedDependencies(gs, extras); SemanticGraph uncollapsedDeps = SemanticGraphFactory.generateUncollapsedDependencies(gs, extras); SemanticGraph ccDeps = SemanticGraphFactory.generateCCProcessedDependencies(gs, extras); result.set(SemanticGraphCoreAnnotations.CollapsedDependenciesAnnotation.class, deps); result.set(SemanticGraphCoreAnnotations.BasicDependenciesAnnotation.class, uncollapsedDeps); result.set(SemanticGraphCoreAnnotations.CollapsedCCProcessedDependenciesAnnotation.class, ccDeps); return new ImmutablePair<>(result, gs); }
java
public Pair<CoreMap, GrammaticalStructure> parseForCoref(String sentence) { List<CoreLabel> tokens = stanfordTokenize(sentence); Tree tree = parser.parse(tokens); GrammaticalStructure gs = tagDependencies(tree, true); tagPOS(tokens); tagLemma(tokens); tagNamedEntity(tokens); CoreMap result = new ArrayCoreMap(); result.set(CoreAnnotations.TokensAnnotation.class, tokens); result.set(TreeCoreAnnotations.TreeAnnotation.class, tree); GrammaticalStructure.Extras extras = GrammaticalStructure.Extras.NONE; SemanticGraph deps = SemanticGraphFactory.generateCollapsedDependencies(gs, extras); SemanticGraph uncollapsedDeps = SemanticGraphFactory.generateUncollapsedDependencies(gs, extras); SemanticGraph ccDeps = SemanticGraphFactory.generateCCProcessedDependencies(gs, extras); result.set(SemanticGraphCoreAnnotations.CollapsedDependenciesAnnotation.class, deps); result.set(SemanticGraphCoreAnnotations.BasicDependenciesAnnotation.class, uncollapsedDeps); result.set(SemanticGraphCoreAnnotations.CollapsedCCProcessedDependenciesAnnotation.class, ccDeps); return new ImmutablePair<>(result, gs); }
[ "public", "Pair", "<", "CoreMap", ",", "GrammaticalStructure", ">", "parseForCoref", "(", "String", "sentence", ")", "{", "List", "<", "CoreLabel", ">", "tokens", "=", "stanfordTokenize", "(", "sentence", ")", ";", "Tree", "tree", "=", "parser", ".", "parse", "(", "tokens", ")", ";", "GrammaticalStructure", "gs", "=", "tagDependencies", "(", "tree", ",", "true", ")", ";", "tagPOS", "(", "tokens", ")", ";", "tagLemma", "(", "tokens", ")", ";", "tagNamedEntity", "(", "tokens", ")", ";", "CoreMap", "result", "=", "new", "ArrayCoreMap", "(", ")", ";", "result", ".", "set", "(", "CoreAnnotations", ".", "TokensAnnotation", ".", "class", ",", "tokens", ")", ";", "result", ".", "set", "(", "TreeCoreAnnotations", ".", "TreeAnnotation", ".", "class", ",", "tree", ")", ";", "GrammaticalStructure", ".", "Extras", "extras", "=", "GrammaticalStructure", ".", "Extras", ".", "NONE", ";", "SemanticGraph", "deps", "=", "SemanticGraphFactory", ".", "generateCollapsedDependencies", "(", "gs", ",", "extras", ")", ";", "SemanticGraph", "uncollapsedDeps", "=", "SemanticGraphFactory", ".", "generateUncollapsedDependencies", "(", "gs", ",", "extras", ")", ";", "SemanticGraph", "ccDeps", "=", "SemanticGraphFactory", ".", "generateCCProcessedDependencies", "(", "gs", ",", "extras", ")", ";", "result", ".", "set", "(", "SemanticGraphCoreAnnotations", ".", "CollapsedDependenciesAnnotation", ".", "class", ",", "deps", ")", ";", "result", ".", "set", "(", "SemanticGraphCoreAnnotations", ".", "BasicDependenciesAnnotation", ".", "class", ",", "uncollapsedDeps", ")", ";", "result", ".", "set", "(", "SemanticGraphCoreAnnotations", ".", "CollapsedCCProcessedDependenciesAnnotation", ".", "class", ",", "ccDeps", ")", ";", "return", "new", "ImmutablePair", "<>", "(", "result", ",", "gs", ")", ";", "}" ]
This is for coref using.
[ "This", "is", "for", "coref", "using", "." ]
38ae7b384d5295334d9efa9dc4cd901b19d9c27e
https://github.com/maochen/NLP/blob/38ae7b384d5295334d9efa9dc4cd901b19d9c27e/CoreNLP-NLP/src/main/java/org/maochen/nlp/parser/stanford/pcfg/StanfordPCFGParser.java#L52-L73
train
crowmagnumb/s6-util
src/main/java/net/crowmagnumb/util/ExceptionUtils.java
ExceptionUtils.causedBy
public static boolean causedBy( final Throwable ex, final Class<? extends Throwable> exceptionClass ) { Throwable cause = ex; while( cause != null && ! exceptionClass.isInstance( cause ) ) { cause = cause.getCause(); } return ( cause == null ) ? false : true; }
java
public static boolean causedBy( final Throwable ex, final Class<? extends Throwable> exceptionClass ) { Throwable cause = ex; while( cause != null && ! exceptionClass.isInstance( cause ) ) { cause = cause.getCause(); } return ( cause == null ) ? false : true; }
[ "public", "static", "boolean", "causedBy", "(", "final", "Throwable", "ex", ",", "final", "Class", "<", "?", "extends", "Throwable", ">", "exceptionClass", ")", "{", "Throwable", "cause", "=", "ex", ";", "while", "(", "cause", "!=", "null", "&&", "!", "exceptionClass", ".", "isInstance", "(", "cause", ")", ")", "{", "cause", "=", "cause", ".", "getCause", "(", ")", ";", "}", "return", "(", "cause", "==", "null", ")", "?", "false", ":", "true", ";", "}" ]
Checks to see if this exception or any of its causes is an instance of the given throwable class @param ex exception to check @param exceptionClass class of the exception @return true if it is
[ "Checks", "to", "see", "if", "this", "exception", "or", "any", "of", "its", "causes", "is", "an", "instance", "of", "the", "given", "throwable", "class" ]
0f9969bc0809e8a617501fa57c135e9b3984fae0
https://github.com/crowmagnumb/s6-util/blob/0f9969bc0809e8a617501fa57c135e9b3984fae0/src/main/java/net/crowmagnumb/util/ExceptionUtils.java#L39-L50
train
crowmagnumb/s6-util
src/main/java/net/crowmagnumb/util/ExceptionUtils.java
ExceptionUtils.getCause
public static <T extends Throwable> T getCause( final Throwable ex, final Class<T> exceptionClass ) { Throwable cause = ex; while( cause != null && ! exceptionClass.isInstance( cause ) ) { cause = cause.getCause(); } return ( cause == null ) ? null : exceptionClass.cast( cause ); }
java
public static <T extends Throwable> T getCause( final Throwable ex, final Class<T> exceptionClass ) { Throwable cause = ex; while( cause != null && ! exceptionClass.isInstance( cause ) ) { cause = cause.getCause(); } return ( cause == null ) ? null : exceptionClass.cast( cause ); }
[ "public", "static", "<", "T", "extends", "Throwable", ">", "T", "getCause", "(", "final", "Throwable", "ex", ",", "final", "Class", "<", "T", ">", "exceptionClass", ")", "{", "Throwable", "cause", "=", "ex", ";", "while", "(", "cause", "!=", "null", "&&", "!", "exceptionClass", ".", "isInstance", "(", "cause", ")", ")", "{", "cause", "=", "cause", ".", "getCause", "(", ")", ";", "}", "return", "(", "cause", "==", "null", ")", "?", "null", ":", "exceptionClass", ".", "cast", "(", "cause", ")", ";", "}" ]
Checks to see if an exception or any of its causes are of a certain type. Returns the first type in the chain if it exists, or null if no causes are of this type. @param ex exception to check @param exceptionClass class of the exception to find @param <T> type of class @return null or an exception
[ "Checks", "to", "see", "if", "an", "exception", "or", "any", "of", "its", "causes", "are", "of", "a", "certain", "type", ".", "Returns", "the", "first", "type", "in", "the", "chain", "if", "it", "exists", "or", "null", "if", "no", "causes", "are", "of", "this", "type", "." ]
0f9969bc0809e8a617501fa57c135e9b3984fae0
https://github.com/crowmagnumb/s6-util/blob/0f9969bc0809e8a617501fa57c135e9b3984fae0/src/main/java/net/crowmagnumb/util/ExceptionUtils.java#L61-L72
train
crowmagnumb/s6-util
src/main/java/net/crowmagnumb/util/ExceptionUtils.java
ExceptionUtils.getMessage
public static String getMessage( final Throwable ex ) { String message = ex.getMessage(); // // It *appears* as though the SQLException hasn't been // converted to nest? It seems like it has it's own // method of nesting, not sure why. I don't know // why Sun wouldn't have converted it. Maybe they // did, but just left these getNextException methods // on for compatibility? In my java source code, they // aren't deprecated, though. // if ( ex instanceof SQLException ) { String sqlMessage = getSqlExceptionMessage( (SQLException) ex ); if ( ! StringUtils.isBlank( sqlMessage ) ) { if ( ! StringUtils.isBlank( message ) ) { message += "\n" + sqlMessage; } else { message = sqlMessage; } } } Throwable cause = ex.getCause(); if ( ex instanceof SamSixException && ((SamSixException) ex).isShowThisCauseOnly() ) { return message; } if ( cause != null ) { String causeMessage = ExceptionUtils.getMessage( cause ); if ( ! StringUtils.isBlank( causeMessage ) ) { if ( ! StringUtils.isBlank( message ) ) { // // ALWAYS use "broadest first" when showing error messages. // Otherwise, error messages end up with some non-human readable thing at the top, // confusing users with deeply technical details. This is especially important for user errors. // // broadest/non-broadest should be used for stack traces only. // message = message + "\n" + causeMessage; } else { message = causeMessage; } } } if ( ! StringUtils.isBlank( message ) ) { return message; } return ex.getClass().getName() + ": An error has been detected."; }
java
public static String getMessage( final Throwable ex ) { String message = ex.getMessage(); // // It *appears* as though the SQLException hasn't been // converted to nest? It seems like it has it's own // method of nesting, not sure why. I don't know // why Sun wouldn't have converted it. Maybe they // did, but just left these getNextException methods // on for compatibility? In my java source code, they // aren't deprecated, though. // if ( ex instanceof SQLException ) { String sqlMessage = getSqlExceptionMessage( (SQLException) ex ); if ( ! StringUtils.isBlank( sqlMessage ) ) { if ( ! StringUtils.isBlank( message ) ) { message += "\n" + sqlMessage; } else { message = sqlMessage; } } } Throwable cause = ex.getCause(); if ( ex instanceof SamSixException && ((SamSixException) ex).isShowThisCauseOnly() ) { return message; } if ( cause != null ) { String causeMessage = ExceptionUtils.getMessage( cause ); if ( ! StringUtils.isBlank( causeMessage ) ) { if ( ! StringUtils.isBlank( message ) ) { // // ALWAYS use "broadest first" when showing error messages. // Otherwise, error messages end up with some non-human readable thing at the top, // confusing users with deeply technical details. This is especially important for user errors. // // broadest/non-broadest should be used for stack traces only. // message = message + "\n" + causeMessage; } else { message = causeMessage; } } } if ( ! StringUtils.isBlank( message ) ) { return message; } return ex.getClass().getName() + ": An error has been detected."; }
[ "public", "static", "String", "getMessage", "(", "final", "Throwable", "ex", ")", "{", "String", "message", "=", "ex", ".", "getMessage", "(", ")", ";", "//", "// It *appears* as though the SQLException hasn't been", "// converted to nest? It seems like it has it's own", "// method of nesting, not sure why. I don't know", "// why Sun wouldn't have converted it. Maybe they", "// did, but just left these getNextException methods", "// on for compatibility? In my java source code, they", "// aren't deprecated, though.", "//", "if", "(", "ex", "instanceof", "SQLException", ")", "{", "String", "sqlMessage", "=", "getSqlExceptionMessage", "(", "(", "SQLException", ")", "ex", ")", ";", "if", "(", "!", "StringUtils", ".", "isBlank", "(", "sqlMessage", ")", ")", "{", "if", "(", "!", "StringUtils", ".", "isBlank", "(", "message", ")", ")", "{", "message", "+=", "\"\\n\"", "+", "sqlMessage", ";", "}", "else", "{", "message", "=", "sqlMessage", ";", "}", "}", "}", "Throwable", "cause", "=", "ex", ".", "getCause", "(", ")", ";", "if", "(", "ex", "instanceof", "SamSixException", "&&", "(", "(", "SamSixException", ")", "ex", ")", ".", "isShowThisCauseOnly", "(", ")", ")", "{", "return", "message", ";", "}", "if", "(", "cause", "!=", "null", ")", "{", "String", "causeMessage", "=", "ExceptionUtils", ".", "getMessage", "(", "cause", ")", ";", "if", "(", "!", "StringUtils", ".", "isBlank", "(", "causeMessage", ")", ")", "{", "if", "(", "!", "StringUtils", ".", "isBlank", "(", "message", ")", ")", "{", "//", "// ALWAYS use \"broadest first\" when showing error messages.", "// Otherwise, error messages end up with some non-human readable thing at the top,", "// confusing users with deeply technical details. This is especially important for user errors.", "//", "// broadest/non-broadest should be used for stack traces only.", "//", "message", "=", "message", "+", "\"\\n\"", "+", "causeMessage", ";", "}", "else", "{", "message", "=", "causeMessage", ";", "}", "}", "}", "if", "(", "!", "StringUtils", ".", "isBlank", "(", "message", ")", ")", "{", "return", "message", ";", "}", "return", "ex", ".", "getClass", "(", ")", ".", "getName", "(", ")", "+", "\": An error has been detected.\"", ";", "}" ]
Static method to recursively get the message text from the entire stack. Messages are concatenated with the linefeed character. This allows for a more informational message to be displayed to the user. @param ex exception @return total message
[ "Static", "method", "to", "recursively", "get", "the", "message", "text", "from", "the", "entire", "stack", ".", "Messages", "are", "concatenated", "with", "the", "linefeed", "character", ".", "This", "allows", "for", "a", "more", "informational", "message", "to", "be", "displayed", "to", "the", "user", "." ]
0f9969bc0809e8a617501fa57c135e9b3984fae0
https://github.com/crowmagnumb/s6-util/blob/0f9969bc0809e8a617501fa57c135e9b3984fae0/src/main/java/net/crowmagnumb/util/ExceptionUtils.java#L215-L285
train