id
int32
0
165k
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
137,700
TheHortonMachine/hortonmachine
gears/src/main/java/oms3/ComponentAccess.java
ComponentAccess.adjustOutputPath
public static boolean adjustOutputPath(File outputDir, Object comp, Logger log) { boolean adjusted = false; ComponentAccess cp = new ComponentAccess(comp); for (Access in : cp.inputs()) { String fieldName = in.getField().getName(); Class fieldType = in.getField().getType(); if (fieldType == File.class) { Role role = in.getField().getAnnotation(Role.class); if (role != null && Annotations.plays(role, Role.OUTPUT)) { try { File f = (File) in.getField().get(comp); if (f != null && !f.isAbsolute()) { f = new File(outputDir, f.getName()); in.setFieldValue(f); adjusted = true; if (log.isLoggable(Level.CONFIG)) { log.config("Adjusting output for '" + fieldName + "' to " + f); } } } catch (Exception ex) { throw new ComponentException("Failed adjusting output path for '" + fieldName); } } } } return adjusted; }
java
public static boolean adjustOutputPath(File outputDir, Object comp, Logger log) { boolean adjusted = false; ComponentAccess cp = new ComponentAccess(comp); for (Access in : cp.inputs()) { String fieldName = in.getField().getName(); Class fieldType = in.getField().getType(); if (fieldType == File.class) { Role role = in.getField().getAnnotation(Role.class); if (role != null && Annotations.plays(role, Role.OUTPUT)) { try { File f = (File) in.getField().get(comp); if (f != null && !f.isAbsolute()) { f = new File(outputDir, f.getName()); in.setFieldValue(f); adjusted = true; if (log.isLoggable(Level.CONFIG)) { log.config("Adjusting output for '" + fieldName + "' to " + f); } } } catch (Exception ex) { throw new ComponentException("Failed adjusting output path for '" + fieldName); } } } } return adjusted; }
[ "public", "static", "boolean", "adjustOutputPath", "(", "File", "outputDir", ",", "Object", "comp", ",", "Logger", "log", ")", "{", "boolean", "adjusted", "=", "false", ";", "ComponentAccess", "cp", "=", "new", "ComponentAccess", "(", "comp", ")", ";", "for", "(", "Access", "in", ":", "cp", ".", "inputs", "(", ")", ")", "{", "String", "fieldName", "=", "in", ".", "getField", "(", ")", ".", "getName", "(", ")", ";", "Class", "fieldType", "=", "in", ".", "getField", "(", ")", ".", "getType", "(", ")", ";", "if", "(", "fieldType", "==", "File", ".", "class", ")", "{", "Role", "role", "=", "in", ".", "getField", "(", ")", ".", "getAnnotation", "(", "Role", ".", "class", ")", ";", "if", "(", "role", "!=", "null", "&&", "Annotations", ".", "plays", "(", "role", ",", "Role", ".", "OUTPUT", ")", ")", "{", "try", "{", "File", "f", "=", "(", "File", ")", "in", ".", "getField", "(", ")", ".", "get", "(", "comp", ")", ";", "if", "(", "f", "!=", "null", "&&", "!", "f", ".", "isAbsolute", "(", ")", ")", "{", "f", "=", "new", "File", "(", "outputDir", ",", "f", ".", "getName", "(", ")", ")", ";", "in", ".", "setFieldValue", "(", "f", ")", ";", "adjusted", "=", "true", ";", "if", "(", "log", ".", "isLoggable", "(", "Level", ".", "CONFIG", ")", ")", "{", "log", ".", "config", "(", "\"Adjusting output for '\"", "+", "fieldName", "+", "\"' to \"", "+", "f", ")", ";", "}", "}", "}", "catch", "(", "Exception", "ex", ")", "{", "throw", "new", "ComponentException", "(", "\"Failed adjusting output path for '\"", "+", "fieldName", ")", ";", "}", "}", "}", "}", "return", "adjusted", ";", "}" ]
Adjust the output path. @param outputDir @param comp @param log @return true is adjusted, false otherwise.
[ "Adjust", "the", "output", "path", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/oms3/ComponentAccess.java#L293-L319
137,701
TheHortonMachine/hortonmachine
gears/src/main/java/oms3/ComponentAccess.java
ComponentAccess.createDefault
public static Properties createDefault(Object comp) { Properties p = new Properties(); ComponentAccess ca = new ComponentAccess(comp); // over all input slots. for (Access in : ca.inputs()) { try { String name = in.getField().getName(); Object o = in.getField().get(comp); if (o != null) { String value = o.toString(); p.put(name, value); } } catch (Exception ex) { throw new ComponentException("Failed access to field: " + in.getField().getName()); } } return p; }
java
public static Properties createDefault(Object comp) { Properties p = new Properties(); ComponentAccess ca = new ComponentAccess(comp); // over all input slots. for (Access in : ca.inputs()) { try { String name = in.getField().getName(); Object o = in.getField().get(comp); if (o != null) { String value = o.toString(); p.put(name, value); } } catch (Exception ex) { throw new ComponentException("Failed access to field: " + in.getField().getName()); } } return p; }
[ "public", "static", "Properties", "createDefault", "(", "Object", "comp", ")", "{", "Properties", "p", "=", "new", "Properties", "(", ")", ";", "ComponentAccess", "ca", "=", "new", "ComponentAccess", "(", "comp", ")", ";", "// over all input slots.", "for", "(", "Access", "in", ":", "ca", ".", "inputs", "(", ")", ")", "{", "try", "{", "String", "name", "=", "in", ".", "getField", "(", ")", ".", "getName", "(", ")", ";", "Object", "o", "=", "in", ".", "getField", "(", ")", ".", "get", "(", "comp", ")", ";", "if", "(", "o", "!=", "null", ")", "{", "String", "value", "=", "o", ".", "toString", "(", ")", ";", "p", ".", "put", "(", "name", ",", "value", ")", ";", "}", "}", "catch", "(", "Exception", "ex", ")", "{", "throw", "new", "ComponentException", "(", "\"Failed access to field: \"", "+", "in", ".", "getField", "(", ")", ".", "getName", "(", ")", ")", ";", "}", "}", "return", "p", ";", "}" ]
Create a default parameter set @param comp @return the default properties
[ "Create", "a", "default", "parameter", "set" ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/oms3/ComponentAccess.java#L326-L343
137,702
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/modules/r/cutout/OmsCutOut.java
OmsCutOut.cut
public static GridCoverage2D cut( GridCoverage2D raster, GridCoverage2D mask ) throws Exception { OmsCutOut cutDrain = new OmsCutOut(); cutDrain.inRaster = raster; cutDrain.inMask = mask; cutDrain.process(); return cutDrain.outRaster; }
java
public static GridCoverage2D cut( GridCoverage2D raster, GridCoverage2D mask ) throws Exception { OmsCutOut cutDrain = new OmsCutOut(); cutDrain.inRaster = raster; cutDrain.inMask = mask; cutDrain.process(); return cutDrain.outRaster; }
[ "public", "static", "GridCoverage2D", "cut", "(", "GridCoverage2D", "raster", ",", "GridCoverage2D", "mask", ")", "throws", "Exception", "{", "OmsCutOut", "cutDrain", "=", "new", "OmsCutOut", "(", ")", ";", "cutDrain", ".", "inRaster", "=", "raster", ";", "cutDrain", ".", "inMask", "=", "mask", ";", "cutDrain", ".", "process", "(", ")", ";", "return", "cutDrain", ".", "outRaster", ";", "}" ]
Cut a raster on a mask using the default parameters. @param raster the raster to cut. @param mask the mask to apply. @return the cut map. @throws Exception
[ "Cut", "a", "raster", "on", "a", "mask", "using", "the", "default", "parameters", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/modules/r/cutout/OmsCutOut.java#L186-L192
137,703
enasequence/sequencetools
src/main/java/uk/ac/ebi/embl/api/validation/ValidationResult.java
ValidationResult.addMessage
private void addMessage(ValidationMessage<Origin> message) { if (message == null) { return; } if( null != defaultOrigin ) { message.addOrigin( defaultOrigin ); } this.messages.add(message); }
java
private void addMessage(ValidationMessage<Origin> message) { if (message == null) { return; } if( null != defaultOrigin ) { message.addOrigin( defaultOrigin ); } this.messages.add(message); }
[ "private", "void", "addMessage", "(", "ValidationMessage", "<", "Origin", ">", "message", ")", "{", "if", "(", "message", "==", "null", ")", "{", "return", ";", "}", "if", "(", "null", "!=", "defaultOrigin", ")", "{", "message", ".", "addOrigin", "(", "defaultOrigin", ")", ";", "}", "this", ".", "messages", ".", "add", "(", "message", ")", ";", "}" ]
Adds a validation message to the result. @param message a validation message to be added
[ "Adds", "a", "validation", "message", "to", "the", "result", "." ]
4127f5e1a17540239f5810136153fbd6737fa262
https://github.com/enasequence/sequencetools/blob/4127f5e1a17540239f5810136153fbd6737fa262/src/main/java/uk/ac/ebi/embl/api/validation/ValidationResult.java#L131-L141
137,704
enasequence/sequencetools
src/main/java/uk/ac/ebi/embl/api/validation/ValidationResult.java
ValidationResult.count
public int count(Severity severity) { int result = 0; if (severity == null) { return result; } for (ValidationMessage<Origin> message : messages) { if (severity.equals(message.getSeverity())) { result++; } } return result; }
java
public int count(Severity severity) { int result = 0; if (severity == null) { return result; } for (ValidationMessage<Origin> message : messages) { if (severity.equals(message.getSeverity())) { result++; } } return result; }
[ "public", "int", "count", "(", "Severity", "severity", ")", "{", "int", "result", "=", "0", ";", "if", "(", "severity", "==", "null", ")", "{", "return", "result", ";", "}", "for", "(", "ValidationMessage", "<", "Origin", ">", "message", ":", "messages", ")", "{", "if", "(", "severity", ".", "equals", "(", "message", ".", "getSeverity", "(", ")", ")", ")", "{", "result", "++", ";", "}", "}", "return", "result", ";", "}" ]
Counts validation messages by its severity. @param severity a severity of the message which should be counted @return a number of validation messages with provided severity
[ "Counts", "validation", "messages", "by", "its", "severity", "." ]
4127f5e1a17540239f5810136153fbd6737fa262
https://github.com/enasequence/sequencetools/blob/4127f5e1a17540239f5810136153fbd6737fa262/src/main/java/uk/ac/ebi/embl/api/validation/ValidationResult.java#L215-L226
137,705
enasequence/sequencetools
src/main/java/uk/ac/ebi/embl/api/validation/ValidationResult.java
ValidationResult.removeMessage
public void removeMessage(String messageId) { Collection<ValidationMessage<Origin>> toRemove = new ArrayList<ValidationMessage<Origin>>(); for (ValidationMessage<Origin> message : messages) { if (messageId.equals(message.getMessageKey())) { toRemove.add(message); } } messages.removeAll(toRemove); }
java
public void removeMessage(String messageId) { Collection<ValidationMessage<Origin>> toRemove = new ArrayList<ValidationMessage<Origin>>(); for (ValidationMessage<Origin> message : messages) { if (messageId.equals(message.getMessageKey())) { toRemove.add(message); } } messages.removeAll(toRemove); }
[ "public", "void", "removeMessage", "(", "String", "messageId", ")", "{", "Collection", "<", "ValidationMessage", "<", "Origin", ">>", "toRemove", "=", "new", "ArrayList", "<", "ValidationMessage", "<", "Origin", ">", ">", "(", ")", ";", "for", "(", "ValidationMessage", "<", "Origin", ">", "message", ":", "messages", ")", "{", "if", "(", "messageId", ".", "equals", "(", "message", ".", "getMessageKey", "(", ")", ")", ")", "{", "toRemove", ".", "add", "(", "message", ")", ";", "}", "}", "messages", ".", "removeAll", "(", "toRemove", ")", ";", "}" ]
removes all messages with a specified message id @param messageId
[ "removes", "all", "messages", "with", "a", "specified", "message", "id" ]
4127f5e1a17540239f5810136153fbd6737fa262
https://github.com/enasequence/sequencetools/blob/4127f5e1a17540239f5810136153fbd6737fa262/src/main/java/uk/ac/ebi/embl/api/validation/ValidationResult.java#L302-L311
137,706
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/io/las/index/strtree/BoundablePair.java
BoundablePair.compareTo
public int compareTo( Object o ) { BoundablePair nd = (BoundablePair) o; if (distance < nd.distance) return -1; if (distance > nd.distance) return 1; return 0; }
java
public int compareTo( Object o ) { BoundablePair nd = (BoundablePair) o; if (distance < nd.distance) return -1; if (distance > nd.distance) return 1; return 0; }
[ "public", "int", "compareTo", "(", "Object", "o", ")", "{", "BoundablePair", "nd", "=", "(", "BoundablePair", ")", "o", ";", "if", "(", "distance", "<", "nd", ".", "distance", ")", "return", "-", "1", ";", "if", "(", "distance", ">", "nd", ".", "distance", ")", "return", "1", ";", "return", "0", ";", "}" ]
Compares two pairs based on their minimum distances
[ "Compares", "two", "pairs", "based", "on", "their", "minimum", "distances" ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/io/las/index/strtree/BoundablePair.java#L134-L141
137,707
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/utils/math/interpolation/splines/Bspline.java
Bspline.b
double b( int i, double t ) { switch( i ) { case -2: return (((-t + 3) * t - 3) * t + 1) / 6; case -1: return (((3 * t - 6) * t) * t + 4) / 6; case 0: return (((-3 * t + 3) * t + 3) * t + 1) / 6; case 1: return (t * t * t) / 6; } return 0; // we only get here if an invalid i is specified }
java
double b( int i, double t ) { switch( i ) { case -2: return (((-t + 3) * t - 3) * t + 1) / 6; case -1: return (((3 * t - 6) * t) * t + 4) / 6; case 0: return (((-3 * t + 3) * t + 3) * t + 1) / 6; case 1: return (t * t * t) / 6; } return 0; // we only get here if an invalid i is specified }
[ "double", "b", "(", "int", "i", ",", "double", "t", ")", "{", "switch", "(", "i", ")", "{", "case", "-", "2", ":", "return", "(", "(", "(", "-", "t", "+", "3", ")", "*", "t", "-", "3", ")", "*", "t", "+", "1", ")", "/", "6", ";", "case", "-", "1", ":", "return", "(", "(", "(", "3", "*", "t", "-", "6", ")", "*", "t", ")", "*", "t", "+", "4", ")", "/", "6", ";", "case", "0", ":", "return", "(", "(", "(", "-", "3", "*", "t", "+", "3", ")", "*", "t", "+", "3", ")", "*", "t", "+", "1", ")", "/", "6", ";", "case", "1", ":", "return", "(", "t", "*", "t", "*", "t", ")", "/", "6", ";", "}", "return", "0", ";", "// we only get here if an invalid i is specified", "}" ]
the basis function for a cubic B spline
[ "the", "basis", "function", "for", "a", "cubic", "B", "spline" ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/math/interpolation/splines/Bspline.java#L35-L47
137,708
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/utils/math/interpolation/splines/Bspline.java
Bspline.p
private Coordinate p( int i, double t ) { double px = 0; double py = 0; for( int j = -2; j <= 1; j++ ) { Coordinate coordinate = pts.get(i + j); px += b(j, t) * coordinate.x; py += b(j, t) * coordinate.y; } return new Coordinate(px, py); }
java
private Coordinate p( int i, double t ) { double px = 0; double py = 0; for( int j = -2; j <= 1; j++ ) { Coordinate coordinate = pts.get(i + j); px += b(j, t) * coordinate.x; py += b(j, t) * coordinate.y; } return new Coordinate(px, py); }
[ "private", "Coordinate", "p", "(", "int", "i", ",", "double", "t", ")", "{", "double", "px", "=", "0", ";", "double", "py", "=", "0", ";", "for", "(", "int", "j", "=", "-", "2", ";", "j", "<=", "1", ";", "j", "++", ")", "{", "Coordinate", "coordinate", "=", "pts", ".", "get", "(", "i", "+", "j", ")", ";", "px", "+=", "b", "(", "j", ",", "t", ")", "*", "coordinate", ".", "x", ";", "py", "+=", "b", "(", "j", ",", "t", ")", "*", "coordinate", ".", "y", ";", "}", "return", "new", "Coordinate", "(", "px", ",", "py", ")", ";", "}" ]
evaluate a point on the B spline
[ "evaluate", "a", "point", "on", "the", "B", "spline" ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/math/interpolation/splines/Bspline.java#L50-L59
137,709
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/utils/sorting/OddEvenSortAlgorithm.java
OddEvenSortAlgorithm.oddEvenSort
public static void oddEvenSort( List<Double> listToBeSorted, List<Double> listThatFollowsTheSort ) { for( int i = 0; i < listToBeSorted.size() / 2; i++ ) { for( int j = 0; j + 1 < listToBeSorted.size(); j += 2 ) if (listToBeSorted.get(j) > listToBeSorted.get(j + 1)) { double tmpa = listToBeSorted.get(j); listToBeSorted.set(j, listToBeSorted.get(j + 1)); listToBeSorted.set(j + 1, tmpa); if (listThatFollowsTheSort != null) { double tmpb = listThatFollowsTheSort.get(j); listThatFollowsTheSort.set(j, listThatFollowsTheSort.get(j + 1)); listThatFollowsTheSort.set(j + 1, tmpb); } } for( int j = 1; j + 1 < listToBeSorted.size(); j += 2 ) if (listToBeSorted.get(j) > listToBeSorted.get(j + 1)) { double tmpa = listToBeSorted.get(j); listToBeSorted.set(j, listToBeSorted.get(j + 1)); listToBeSorted.set(j + 1, tmpa); if (listThatFollowsTheSort != null) { double tmpb = listThatFollowsTheSort.get(j); listThatFollowsTheSort.set(j, listThatFollowsTheSort.get(j + 1)); listThatFollowsTheSort.set(j + 1, tmpb); } } } }
java
public static void oddEvenSort( List<Double> listToBeSorted, List<Double> listThatFollowsTheSort ) { for( int i = 0; i < listToBeSorted.size() / 2; i++ ) { for( int j = 0; j + 1 < listToBeSorted.size(); j += 2 ) if (listToBeSorted.get(j) > listToBeSorted.get(j + 1)) { double tmpa = listToBeSorted.get(j); listToBeSorted.set(j, listToBeSorted.get(j + 1)); listToBeSorted.set(j + 1, tmpa); if (listThatFollowsTheSort != null) { double tmpb = listThatFollowsTheSort.get(j); listThatFollowsTheSort.set(j, listThatFollowsTheSort.get(j + 1)); listThatFollowsTheSort.set(j + 1, tmpb); } } for( int j = 1; j + 1 < listToBeSorted.size(); j += 2 ) if (listToBeSorted.get(j) > listToBeSorted.get(j + 1)) { double tmpa = listToBeSorted.get(j); listToBeSorted.set(j, listToBeSorted.get(j + 1)); listToBeSorted.set(j + 1, tmpa); if (listThatFollowsTheSort != null) { double tmpb = listThatFollowsTheSort.get(j); listThatFollowsTheSort.set(j, listThatFollowsTheSort.get(j + 1)); listThatFollowsTheSort.set(j + 1, tmpb); } } } }
[ "public", "static", "void", "oddEvenSort", "(", "List", "<", "Double", ">", "listToBeSorted", ",", "List", "<", "Double", ">", "listThatFollowsTheSort", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "listToBeSorted", ".", "size", "(", ")", "/", "2", ";", "i", "++", ")", "{", "for", "(", "int", "j", "=", "0", ";", "j", "+", "1", "<", "listToBeSorted", ".", "size", "(", ")", ";", "j", "+=", "2", ")", "if", "(", "listToBeSorted", ".", "get", "(", "j", ")", ">", "listToBeSorted", ".", "get", "(", "j", "+", "1", ")", ")", "{", "double", "tmpa", "=", "listToBeSorted", ".", "get", "(", "j", ")", ";", "listToBeSorted", ".", "set", "(", "j", ",", "listToBeSorted", ".", "get", "(", "j", "+", "1", ")", ")", ";", "listToBeSorted", ".", "set", "(", "j", "+", "1", ",", "tmpa", ")", ";", "if", "(", "listThatFollowsTheSort", "!=", "null", ")", "{", "double", "tmpb", "=", "listThatFollowsTheSort", ".", "get", "(", "j", ")", ";", "listThatFollowsTheSort", ".", "set", "(", "j", ",", "listThatFollowsTheSort", ".", "get", "(", "j", "+", "1", ")", ")", ";", "listThatFollowsTheSort", ".", "set", "(", "j", "+", "1", ",", "tmpb", ")", ";", "}", "}", "for", "(", "int", "j", "=", "1", ";", "j", "+", "1", "<", "listToBeSorted", ".", "size", "(", ")", ";", "j", "+=", "2", ")", "if", "(", "listToBeSorted", ".", "get", "(", "j", ")", ">", "listToBeSorted", ".", "get", "(", "j", "+", "1", ")", ")", "{", "double", "tmpa", "=", "listToBeSorted", ".", "get", "(", "j", ")", ";", "listToBeSorted", ".", "set", "(", "j", ",", "listToBeSorted", ".", "get", "(", "j", "+", "1", ")", ")", ";", "listToBeSorted", ".", "set", "(", "j", "+", "1", ",", "tmpa", ")", ";", "if", "(", "listThatFollowsTheSort", "!=", "null", ")", "{", "double", "tmpb", "=", "listThatFollowsTheSort", ".", "get", "(", "j", ")", ";", "listThatFollowsTheSort", ".", "set", "(", "j", ",", "listThatFollowsTheSort", ".", "get", "(", "j", "+", "1", ")", ")", ";", "listThatFollowsTheSort", ".", "set", "(", "j", "+", "1", ",", "tmpb", ")", ";", "}", "}", "}", "}" ]
Sorts two lists regarding to the sort of the first @param listToBeSorted the array on wich the sort is performed @param listThatFollowsTheSort the array that is sorted following the others list sort. Can be null, in which case it acts like a normal sorting algorithm
[ "Sorts", "two", "lists", "regarding", "to", "the", "sort", "of", "the", "first" ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/sorting/OddEvenSortAlgorithm.java#L67-L92
137,710
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/utils/math/integration/SimpsonIntegral.java
SimpsonIntegral.simpson
protected double simpson() { double s = 0f; double st = 0f; double ost = 0f; double os = 0f; for( int i = 1; i < maxsteps; i++ ) { st = trapezoid(i); s = (4f * st - ost) / 3f; if (i > 5) { if (Math.abs(s - os) < accuracy * Math.abs(os) || (s == 0f && os == 0f)) { return s; } } os = s; ost = st; } return 0d; }
java
protected double simpson() { double s = 0f; double st = 0f; double ost = 0f; double os = 0f; for( int i = 1; i < maxsteps; i++ ) { st = trapezoid(i); s = (4f * st - ost) / 3f; if (i > 5) { if (Math.abs(s - os) < accuracy * Math.abs(os) || (s == 0f && os == 0f)) { return s; } } os = s; ost = st; } return 0d; }
[ "protected", "double", "simpson", "(", ")", "{", "double", "s", "=", "0f", ";", "double", "st", "=", "0f", ";", "double", "ost", "=", "0f", ";", "double", "os", "=", "0f", ";", "for", "(", "int", "i", "=", "1", ";", "i", "<", "maxsteps", ";", "i", "++", ")", "{", "st", "=", "trapezoid", "(", "i", ")", ";", "s", "=", "(", "4f", "*", "st", "-", "ost", ")", "/", "3f", ";", "if", "(", "i", ">", "5", ")", "{", "if", "(", "Math", ".", "abs", "(", "s", "-", "os", ")", "<", "accuracy", "*", "Math", ".", "abs", "(", "os", ")", "||", "(", "s", "==", "0f", "&&", "os", "==", "0f", ")", ")", "{", "return", "s", ";", "}", "}", "os", "=", "s", ";", "ost", "=", "st", ";", "}", "return", "0d", ";", "}" ]
Calculate the integral with the simpson method of the equation implemented in the method equation @return @throws Exception
[ "Calculate", "the", "integral", "with", "the", "simpson", "method", "of", "the", "equation", "implemented", "in", "the", "method", "equation" ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/math/integration/SimpsonIntegral.java#L46-L67
137,711
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/utils/math/integration/SimpsonIntegral.java
SimpsonIntegral.trapezoid
protected double trapezoid( int n ) { double x = 0; double tnm = 0; double sum = 0; double del = 0; int it = 0; int j = 0; if (n == 1) { strapezoid = 0.5f * (upperlimit - lowerlimit) * (equation(lowerlimit) + equation(upperlimit)); } else { /* * for (it = 1, j = 1; j < n - 1; j++) { it <<= 1; } */ it = (int) Math.pow(2.0, n - 1); tnm = (double) it; del = (upperlimit - lowerlimit) / tnm; x = lowerlimit + 0.5f * del; for( sum = 0f, j = 1; j <= it; j++, x += del ) { if (x >= upperlimit) { System.out.println("hoi"); } sum += equation(x); } strapezoid = (double) (0.5f * (strapezoid + (upperlimit - lowerlimit) * sum / tnm)); } return strapezoid; }
java
protected double trapezoid( int n ) { double x = 0; double tnm = 0; double sum = 0; double del = 0; int it = 0; int j = 0; if (n == 1) { strapezoid = 0.5f * (upperlimit - lowerlimit) * (equation(lowerlimit) + equation(upperlimit)); } else { /* * for (it = 1, j = 1; j < n - 1; j++) { it <<= 1; } */ it = (int) Math.pow(2.0, n - 1); tnm = (double) it; del = (upperlimit - lowerlimit) / tnm; x = lowerlimit + 0.5f * del; for( sum = 0f, j = 1; j <= it; j++, x += del ) { if (x >= upperlimit) { System.out.println("hoi"); } sum += equation(x); } strapezoid = (double) (0.5f * (strapezoid + (upperlimit - lowerlimit) * sum / tnm)); } return strapezoid; }
[ "protected", "double", "trapezoid", "(", "int", "n", ")", "{", "double", "x", "=", "0", ";", "double", "tnm", "=", "0", ";", "double", "sum", "=", "0", ";", "double", "del", "=", "0", ";", "int", "it", "=", "0", ";", "int", "j", "=", "0", ";", "if", "(", "n", "==", "1", ")", "{", "strapezoid", "=", "0.5f", "*", "(", "upperlimit", "-", "lowerlimit", ")", "*", "(", "equation", "(", "lowerlimit", ")", "+", "equation", "(", "upperlimit", ")", ")", ";", "}", "else", "{", "/*\n * for (it = 1, j = 1; j < n - 1; j++) { it <<= 1; }\n */", "it", "=", "(", "int", ")", "Math", ".", "pow", "(", "2.0", ",", "n", "-", "1", ")", ";", "tnm", "=", "(", "double", ")", "it", ";", "del", "=", "(", "upperlimit", "-", "lowerlimit", ")", "/", "tnm", ";", "x", "=", "lowerlimit", "+", "0.5f", "*", "del", ";", "for", "(", "sum", "=", "0f", ",", "j", "=", "1", ";", "j", "<=", "it", ";", "j", "++", ",", "x", "+=", "del", ")", "{", "if", "(", "x", ">=", "upperlimit", ")", "{", "System", ".", "out", ".", "println", "(", "\"hoi\"", ")", ";", "}", "sum", "+=", "equation", "(", "x", ")", ";", "}", "strapezoid", "=", "(", "double", ")", "(", "0.5f", "*", "(", "strapezoid", "+", "(", "upperlimit", "-", "lowerlimit", ")", "*", "sum", "/", "tnm", ")", ")", ";", "}", "return", "strapezoid", ";", "}" ]
Calculate the integral with the trapezoidal algorithm of the equation implemented in the method equation @param n - number of steps to perform @return
[ "Calculate", "the", "integral", "with", "the", "trapezoidal", "algorithm", "of", "the", "equation", "implemented", "in", "the", "method", "equation" ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/math/integration/SimpsonIntegral.java#L76-L106
137,712
TheHortonMachine/hortonmachine
dbs/src/main/java/org/hortonmachine/dbs/utils/MercatorUtils.java
MercatorUtils.tileLatLonBounds
public static double[] tileLatLonBounds( int tx, int ty, int zoom, int tileSize ) { double[] bounds = tileBounds3857(tx, ty, zoom, tileSize); double[] mins = metersToLatLon(bounds[0], bounds[1]); double[] maxs = metersToLatLon(bounds[2], bounds[3]); return new double[]{mins[1], maxs[0], maxs[1], mins[0]}; }
java
public static double[] tileLatLonBounds( int tx, int ty, int zoom, int tileSize ) { double[] bounds = tileBounds3857(tx, ty, zoom, tileSize); double[] mins = metersToLatLon(bounds[0], bounds[1]); double[] maxs = metersToLatLon(bounds[2], bounds[3]); return new double[]{mins[1], maxs[0], maxs[1], mins[0]}; }
[ "public", "static", "double", "[", "]", "tileLatLonBounds", "(", "int", "tx", ",", "int", "ty", ",", "int", "zoom", ",", "int", "tileSize", ")", "{", "double", "[", "]", "bounds", "=", "tileBounds3857", "(", "tx", ",", "ty", ",", "zoom", ",", "tileSize", ")", ";", "double", "[", "]", "mins", "=", "metersToLatLon", "(", "bounds", "[", "0", "]", ",", "bounds", "[", "1", "]", ")", ";", "double", "[", "]", "maxs", "=", "metersToLatLon", "(", "bounds", "[", "2", "]", ",", "bounds", "[", "3", "]", ")", ";", "return", "new", "double", "[", "]", "{", "mins", "[", "1", "]", ",", "maxs", "[", "0", "]", ",", "maxs", "[", "1", "]", ",", "mins", "[", "0", "]", "}", ";", "}" ]
Get lat-long bounds from tile index. @param tx tile x. @param ty tile y. @param zoom zoomlevel. @param tileSize tile size. @return [minx, miny, maxx, maxy]
[ "Get", "lat", "-", "long", "bounds", "from", "tile", "index", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/dbs/src/main/java/org/hortonmachine/dbs/utils/MercatorUtils.java#L74-L79
137,713
TheHortonMachine/hortonmachine
dbs/src/main/java/org/hortonmachine/dbs/utils/MercatorUtils.java
MercatorUtils.metersYToLatitude
public static double metersYToLatitude( double y ) { return Math.toDegrees(Math.atan(Math.sinh(y / EQUATORIALRADIUS))); }
java
public static double metersYToLatitude( double y ) { return Math.toDegrees(Math.atan(Math.sinh(y / EQUATORIALRADIUS))); }
[ "public", "static", "double", "metersYToLatitude", "(", "double", "y", ")", "{", "return", "Math", ".", "toDegrees", "(", "Math", ".", "atan", "(", "Math", ".", "sinh", "(", "y", "/", "EQUATORIALRADIUS", ")", ")", ")", ";", "}" ]
Convert a meter measure to a latitude @param y in meters @return latitude in degrees in spherical mercator projection
[ "Convert", "a", "meter", "measure", "to", "a", "latitude" ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/dbs/src/main/java/org/hortonmachine/dbs/utils/MercatorUtils.java#L172-L174
137,714
TheHortonMachine/hortonmachine
dbs/src/main/java/org/hortonmachine/dbs/postgis/PostgisDb.java
PostgisDb.addGeometryXYColumnAndIndex
public void addGeometryXYColumnAndIndex( String tableName, String geomColName, String geomType, String epsg, boolean avoidIndex ) throws Exception { String epsgStr = "4326"; if (epsg != null) { epsgStr = epsg; } String geomTypeStr = "LINESTRING"; if (geomType != null) { geomTypeStr = geomType; } if (geomColName == null) { geomColName = ASpatialDb.DEFAULT_GEOM_FIELD_NAME; } String _geomColName = geomColName; String _epsgStr = epsgStr; String _geomTypeStr = geomTypeStr; pgDb.execOnConnection(connection -> { try (IHMStatement stmt = connection.createStatement()) { String sql = sqlTemplates.addGeometryColumn(tableName, _geomColName, _epsgStr, _geomTypeStr, "2"); stmt.execute(sql); if (!avoidIndex) { sql = sqlTemplates.createSpatialIndex(tableName, _geomColName); stmt.execute(sql); } } return null; }); }
java
public void addGeometryXYColumnAndIndex( String tableName, String geomColName, String geomType, String epsg, boolean avoidIndex ) throws Exception { String epsgStr = "4326"; if (epsg != null) { epsgStr = epsg; } String geomTypeStr = "LINESTRING"; if (geomType != null) { geomTypeStr = geomType; } if (geomColName == null) { geomColName = ASpatialDb.DEFAULT_GEOM_FIELD_NAME; } String _geomColName = geomColName; String _epsgStr = epsgStr; String _geomTypeStr = geomTypeStr; pgDb.execOnConnection(connection -> { try (IHMStatement stmt = connection.createStatement()) { String sql = sqlTemplates.addGeometryColumn(tableName, _geomColName, _epsgStr, _geomTypeStr, "2"); stmt.execute(sql); if (!avoidIndex) { sql = sqlTemplates.createSpatialIndex(tableName, _geomColName); stmt.execute(sql); } } return null; }); }
[ "public", "void", "addGeometryXYColumnAndIndex", "(", "String", "tableName", ",", "String", "geomColName", ",", "String", "geomType", ",", "String", "epsg", ",", "boolean", "avoidIndex", ")", "throws", "Exception", "{", "String", "epsgStr", "=", "\"4326\"", ";", "if", "(", "epsg", "!=", "null", ")", "{", "epsgStr", "=", "epsg", ";", "}", "String", "geomTypeStr", "=", "\"LINESTRING\"", ";", "if", "(", "geomType", "!=", "null", ")", "{", "geomTypeStr", "=", "geomType", ";", "}", "if", "(", "geomColName", "==", "null", ")", "{", "geomColName", "=", "ASpatialDb", ".", "DEFAULT_GEOM_FIELD_NAME", ";", "}", "String", "_geomColName", "=", "geomColName", ";", "String", "_epsgStr", "=", "epsgStr", ";", "String", "_geomTypeStr", "=", "geomTypeStr", ";", "pgDb", ".", "execOnConnection", "(", "connection", "->", "{", "try", "(", "IHMStatement", "stmt", "=", "connection", ".", "createStatement", "(", ")", ")", "{", "String", "sql", "=", "sqlTemplates", ".", "addGeometryColumn", "(", "tableName", ",", "_geomColName", ",", "_epsgStr", ",", "_geomTypeStr", ",", "\"2\"", ")", ";", "stmt", ".", "execute", "(", "sql", ")", ";", "if", "(", "!", "avoidIndex", ")", "{", "sql", "=", "sqlTemplates", ".", "createSpatialIndex", "(", "tableName", ",", "_geomColName", ")", ";", "stmt", ".", "execute", "(", "sql", ")", ";", "}", "}", "return", "null", ";", "}", ")", ";", "}" ]
Adds a geometry column to a table. @param tableName the table name. @param geomColName the geometry column name. @param geomType the geometry type (ex. LINESTRING); @param epsg the optional epsg code (default is 4326); @param avoidIndex if <code>true</code>, the index is not created. @throws Exception
[ "Adds", "a", "geometry", "column", "to", "a", "table", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/dbs/src/main/java/org/hortonmachine/dbs/postgis/PostgisDb.java#L279-L310
137,715
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/modules/r/tmsgenerator/MBTilesHelper.java
MBTilesHelper.getTile
public BufferedImage getTile( int x, int y, int z ) throws Exception { try (PreparedStatement statement = connection.prepareStatement(SELECTQUERY)) { statement.setInt(1, z); statement.setInt(2, x); statement.setInt(3, y); ResultSet resultSet = statement.executeQuery(); if (resultSet.next()) { byte[] imageBytes = resultSet.getBytes(1); boolean orig = ImageIO.getUseCache(); ImageIO.setUseCache(false); InputStream in = new ByteArrayInputStream(imageBytes); BufferedImage bufferedImage = ImageIO.read(in); ImageIO.setUseCache(orig); return bufferedImage; } } return null; }
java
public BufferedImage getTile( int x, int y, int z ) throws Exception { try (PreparedStatement statement = connection.prepareStatement(SELECTQUERY)) { statement.setInt(1, z); statement.setInt(2, x); statement.setInt(3, y); ResultSet resultSet = statement.executeQuery(); if (resultSet.next()) { byte[] imageBytes = resultSet.getBytes(1); boolean orig = ImageIO.getUseCache(); ImageIO.setUseCache(false); InputStream in = new ByteArrayInputStream(imageBytes); BufferedImage bufferedImage = ImageIO.read(in); ImageIO.setUseCache(orig); return bufferedImage; } } return null; }
[ "public", "BufferedImage", "getTile", "(", "int", "x", ",", "int", "y", ",", "int", "z", ")", "throws", "Exception", "{", "try", "(", "PreparedStatement", "statement", "=", "connection", ".", "prepareStatement", "(", "SELECTQUERY", ")", ")", "{", "statement", ".", "setInt", "(", "1", ",", "z", ")", ";", "statement", ".", "setInt", "(", "2", ",", "x", ")", ";", "statement", ".", "setInt", "(", "3", ",", "y", ")", ";", "ResultSet", "resultSet", "=", "statement", ".", "executeQuery", "(", ")", ";", "if", "(", "resultSet", ".", "next", "(", ")", ")", "{", "byte", "[", "]", "imageBytes", "=", "resultSet", ".", "getBytes", "(", "1", ")", ";", "boolean", "orig", "=", "ImageIO", ".", "getUseCache", "(", ")", ";", "ImageIO", ".", "setUseCache", "(", "false", ")", ";", "InputStream", "in", "=", "new", "ByteArrayInputStream", "(", "imageBytes", ")", ";", "BufferedImage", "bufferedImage", "=", "ImageIO", ".", "read", "(", "in", ")", ";", "ImageIO", ".", "setUseCache", "(", "orig", ")", ";", "return", "bufferedImage", ";", "}", "}", "return", "null", ";", "}" ]
Get a Tile image from the database. @param x @param y @param z @return @throws Exception
[ "Get", "a", "Tile", "image", "from", "the", "database", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/modules/r/tmsgenerator/MBTilesHelper.java#L275-L292
137,716
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/modules/r/tmsgenerator/MBTilesHelper.java
MBTilesHelper.readGridcoverageImageForTile
public static BufferedImage readGridcoverageImageForTile( AbstractGridCoverage2DReader reader, int x, int y, int zoom, CoordinateReferenceSystem resampleCrs ) throws IOException { double north = tile2lat(y, zoom); double south = tile2lat(y + 1, zoom); double west = tile2lon(x, zoom); double east = tile2lon(x + 1, zoom); Coordinate ll = new Coordinate(west, south); Coordinate ur = new Coordinate(east, north); try { CoordinateReferenceSystem sourceCRS = DefaultGeographicCRS.WGS84; MathTransform transform = CRS.findMathTransform(sourceCRS, resampleCrs); ll = JTS.transform(ll, null, transform); ur = JTS.transform(ur, null, transform); } catch (Exception e) { e.printStackTrace(); } BufferedImage image = ImageUtilities.imageFromReader(reader, TILESIZE, TILESIZE, ll.x, ur.x, ll.y, ur.y, resampleCrs); return image; }
java
public static BufferedImage readGridcoverageImageForTile( AbstractGridCoverage2DReader reader, int x, int y, int zoom, CoordinateReferenceSystem resampleCrs ) throws IOException { double north = tile2lat(y, zoom); double south = tile2lat(y + 1, zoom); double west = tile2lon(x, zoom); double east = tile2lon(x + 1, zoom); Coordinate ll = new Coordinate(west, south); Coordinate ur = new Coordinate(east, north); try { CoordinateReferenceSystem sourceCRS = DefaultGeographicCRS.WGS84; MathTransform transform = CRS.findMathTransform(sourceCRS, resampleCrs); ll = JTS.transform(ll, null, transform); ur = JTS.transform(ur, null, transform); } catch (Exception e) { e.printStackTrace(); } BufferedImage image = ImageUtilities.imageFromReader(reader, TILESIZE, TILESIZE, ll.x, ur.x, ll.y, ur.y, resampleCrs); return image; }
[ "public", "static", "BufferedImage", "readGridcoverageImageForTile", "(", "AbstractGridCoverage2DReader", "reader", ",", "int", "x", ",", "int", "y", ",", "int", "zoom", ",", "CoordinateReferenceSystem", "resampleCrs", ")", "throws", "IOException", "{", "double", "north", "=", "tile2lat", "(", "y", ",", "zoom", ")", ";", "double", "south", "=", "tile2lat", "(", "y", "+", "1", ",", "zoom", ")", ";", "double", "west", "=", "tile2lon", "(", "x", ",", "zoom", ")", ";", "double", "east", "=", "tile2lon", "(", "x", "+", "1", ",", "zoom", ")", ";", "Coordinate", "ll", "=", "new", "Coordinate", "(", "west", ",", "south", ")", ";", "Coordinate", "ur", "=", "new", "Coordinate", "(", "east", ",", "north", ")", ";", "try", "{", "CoordinateReferenceSystem", "sourceCRS", "=", "DefaultGeographicCRS", ".", "WGS84", ";", "MathTransform", "transform", "=", "CRS", ".", "findMathTransform", "(", "sourceCRS", ",", "resampleCrs", ")", ";", "ll", "=", "JTS", ".", "transform", "(", "ll", ",", "null", ",", "transform", ")", ";", "ur", "=", "JTS", ".", "transform", "(", "ur", ",", "null", ",", "transform", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "BufferedImage", "image", "=", "ImageUtilities", ".", "imageFromReader", "(", "reader", ",", "TILESIZE", ",", "TILESIZE", ",", "ll", ".", "x", ",", "ur", ".", "x", ",", "ll", ".", "y", ",", "ur", ".", "y", ",", "resampleCrs", ")", ";", "return", "image", ";", "}" ]
Read the image of a tile from a generic geotools coverage reader. @param reader the reader, expected to be in CRS 3857. @param x the tile x. @param y the tile y. @param zoom the zoomlevel. @return the image. @throws IOException
[ "Read", "the", "image", "of", "a", "tile", "from", "a", "generic", "geotools", "coverage", "reader", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/modules/r/tmsgenerator/MBTilesHelper.java#L341-L363
137,717
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/modules/utils/BinaryFast.java
BinaryFast.convertToArray
public int[] convertToArray() { int[] p = new int[size]; for( int j = 0; j < height; ++j ) { for( int i = 0; i < width; ++i ) { p[(j * width) + i] = pixels[i][j]; } } return p; }
java
public int[] convertToArray() { int[] p = new int[size]; for( int j = 0; j < height; ++j ) { for( int i = 0; i < width; ++i ) { p[(j * width) + i] = pixels[i][j]; } } return p; }
[ "public", "int", "[", "]", "convertToArray", "(", ")", "{", "int", "[", "]", "p", "=", "new", "int", "[", "size", "]", ";", "for", "(", "int", "j", "=", "0", ";", "j", "<", "height", ";", "++", "j", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "width", ";", "++", "i", ")", "{", "p", "[", "(", "j", "*", "width", ")", "+", "i", "]", "=", "pixels", "[", "i", "]", "[", "j", "]", ";", "}", "}", "return", "p", ";", "}" ]
Converts the 2D array into a 1D array of pixel values. @return The 1D array of pixel values.
[ "Converts", "the", "2D", "array", "into", "a", "1D", "array", "of", "pixel", "values", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/modules/utils/BinaryFast.java#L138-L146
137,718
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/modules/utils/BinaryFast.java
BinaryFast.generatePixels
public void generatePixels( HashSet<Point> pix ) { // Reset all pixels to background for( int j = 0; j < height; ++j ) { for( int i = 0; i < width; ++i ) { pixels[i][j] = BACKGROUND; } } convertToPixels(pix); }
java
public void generatePixels( HashSet<Point> pix ) { // Reset all pixels to background for( int j = 0; j < height; ++j ) { for( int i = 0; i < width; ++i ) { pixels[i][j] = BACKGROUND; } } convertToPixels(pix); }
[ "public", "void", "generatePixels", "(", "HashSet", "<", "Point", ">", "pix", ")", "{", "// Reset all pixels to background", "for", "(", "int", "j", "=", "0", ";", "j", "<", "height", ";", "++", "j", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "width", ";", "++", "i", ")", "{", "pixels", "[", "i", "]", "[", "j", "]", "=", "BACKGROUND", ";", "}", "}", "convertToPixels", "(", "pix", ")", ";", "}" ]
Generates a new 2D array of pixels from a hash set of foreground pixels. @param pix The hash set of foreground pixels.
[ "Generates", "a", "new", "2D", "array", "of", "pixels", "from", "a", "hash", "set", "of", "foreground", "pixels", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/modules/utils/BinaryFast.java#L154-L162
137,719
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/modules/utils/BinaryFast.java
BinaryFast.convertToPixels
public void convertToPixels( HashSet<Point> pix ) { Iterator<Point> it = pix.iterator(); while( it.hasNext() ) { Point p = it.next(); pixels[p.x][p.y] = FOREGROUND; } }
java
public void convertToPixels( HashSet<Point> pix ) { Iterator<Point> it = pix.iterator(); while( it.hasNext() ) { Point p = it.next(); pixels[p.x][p.y] = FOREGROUND; } }
[ "public", "void", "convertToPixels", "(", "HashSet", "<", "Point", ">", "pix", ")", "{", "Iterator", "<", "Point", ">", "it", "=", "pix", ".", "iterator", "(", ")", ";", "while", "(", "it", ".", "hasNext", "(", ")", ")", "{", "Point", "p", "=", "it", ".", "next", "(", ")", ";", "pixels", "[", "p", ".", "x", "]", "[", "p", ".", "y", "]", "=", "FOREGROUND", ";", "}", "}" ]
Adds the pixels from a hash set to the 2D array of pixels. @param pix The hash set of foreground pixels to be added.
[ "Adds", "the", "pixels", "from", "a", "hash", "set", "to", "the", "2D", "array", "of", "pixels", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/modules/utils/BinaryFast.java#L169-L175
137,720
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/modules/utils/BinaryFast.java
BinaryFast.generateForegroundEdge
public void generateForegroundEdge() { foregroundEdgePixels.clear(); Point p; for( int n = 0; n < height; ++n ) { for( int m = 0; m < width; ++m ) { if (pixels[m][n] == FOREGROUND) { p = new Point(m, n); for( int j = -1; j < 2; ++j ) { for( int i = -1; i < 2; ++i ) { if ((p.x + i >= 0) && (p.x + i < width) && (p.y + j >= 0) && (p.y + j < height)) { if ((pixels[p.x + i][p.y + j] == BACKGROUND) && (!foregroundEdgePixels.contains(p))) { foregroundEdgePixels.add(p); } } } } } } } }
java
public void generateForegroundEdge() { foregroundEdgePixels.clear(); Point p; for( int n = 0; n < height; ++n ) { for( int m = 0; m < width; ++m ) { if (pixels[m][n] == FOREGROUND) { p = new Point(m, n); for( int j = -1; j < 2; ++j ) { for( int i = -1; i < 2; ++i ) { if ((p.x + i >= 0) && (p.x + i < width) && (p.y + j >= 0) && (p.y + j < height)) { if ((pixels[p.x + i][p.y + j] == BACKGROUND) && (!foregroundEdgePixels.contains(p))) { foregroundEdgePixels.add(p); } } } } } } } }
[ "public", "void", "generateForegroundEdge", "(", ")", "{", "foregroundEdgePixels", ".", "clear", "(", ")", ";", "Point", "p", ";", "for", "(", "int", "n", "=", "0", ";", "n", "<", "height", ";", "++", "n", ")", "{", "for", "(", "int", "m", "=", "0", ";", "m", "<", "width", ";", "++", "m", ")", "{", "if", "(", "pixels", "[", "m", "]", "[", "n", "]", "==", "FOREGROUND", ")", "{", "p", "=", "new", "Point", "(", "m", ",", "n", ")", ";", "for", "(", "int", "j", "=", "-", "1", ";", "j", "<", "2", ";", "++", "j", ")", "{", "for", "(", "int", "i", "=", "-", "1", ";", "i", "<", "2", ";", "++", "i", ")", "{", "if", "(", "(", "p", ".", "x", "+", "i", ">=", "0", ")", "&&", "(", "p", ".", "x", "+", "i", "<", "width", ")", "&&", "(", "p", ".", "y", "+", "j", ">=", "0", ")", "&&", "(", "p", ".", "y", "+", "j", "<", "height", ")", ")", "{", "if", "(", "(", "pixels", "[", "p", ".", "x", "+", "i", "]", "[", "p", ".", "y", "+", "j", "]", "==", "BACKGROUND", ")", "&&", "(", "!", "foregroundEdgePixels", ".", "contains", "(", "p", ")", ")", ")", "{", "foregroundEdgePixels", ".", "add", "(", "p", ")", ";", "}", "}", "}", "}", "}", "}", "}", "}" ]
Generates the foreground edge hash set from the 2D array of pixels.
[ "Generates", "the", "foreground", "edge", "hash", "set", "from", "the", "2D", "array", "of", "pixels", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/modules/utils/BinaryFast.java#L180-L201
137,721
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/modules/utils/BinaryFast.java
BinaryFast.generateBackgroundEdgeFromForegroundEdge
public void generateBackgroundEdgeFromForegroundEdge() { backgroundEdgePixels.clear(); Point p, p2; Iterator<Point> it = foregroundEdgePixels.iterator(); while( it.hasNext() ) { p = new Point(it.next()); for( int j = -1; j < 2; ++j ) { for( int i = -1; i < 2; ++i ) { if ((p.x + i >= 0) && (p.x + i < width) && (p.y + j >= 0) && (p.y + j < height)) { p2 = new Point(p.x + i, p.y + j); if (pixels[p2.x][p2.y] == BACKGROUND) { backgroundEdgePixels.add(p2); } } } } } }
java
public void generateBackgroundEdgeFromForegroundEdge() { backgroundEdgePixels.clear(); Point p, p2; Iterator<Point> it = foregroundEdgePixels.iterator(); while( it.hasNext() ) { p = new Point(it.next()); for( int j = -1; j < 2; ++j ) { for( int i = -1; i < 2; ++i ) { if ((p.x + i >= 0) && (p.x + i < width) && (p.y + j >= 0) && (p.y + j < height)) { p2 = new Point(p.x + i, p.y + j); if (pixels[p2.x][p2.y] == BACKGROUND) { backgroundEdgePixels.add(p2); } } } } } }
[ "public", "void", "generateBackgroundEdgeFromForegroundEdge", "(", ")", "{", "backgroundEdgePixels", ".", "clear", "(", ")", ";", "Point", "p", ",", "p2", ";", "Iterator", "<", "Point", ">", "it", "=", "foregroundEdgePixels", ".", "iterator", "(", ")", ";", "while", "(", "it", ".", "hasNext", "(", ")", ")", "{", "p", "=", "new", "Point", "(", "it", ".", "next", "(", ")", ")", ";", "for", "(", "int", "j", "=", "-", "1", ";", "j", "<", "2", ";", "++", "j", ")", "{", "for", "(", "int", "i", "=", "-", "1", ";", "i", "<", "2", ";", "++", "i", ")", "{", "if", "(", "(", "p", ".", "x", "+", "i", ">=", "0", ")", "&&", "(", "p", ".", "x", "+", "i", "<", "width", ")", "&&", "(", "p", ".", "y", "+", "j", ">=", "0", ")", "&&", "(", "p", ".", "y", "+", "j", "<", "height", ")", ")", "{", "p2", "=", "new", "Point", "(", "p", ".", "x", "+", "i", ",", "p", ".", "y", "+", "j", ")", ";", "if", "(", "pixels", "[", "p2", ".", "x", "]", "[", "p2", ".", "y", "]", "==", "BACKGROUND", ")", "{", "backgroundEdgePixels", ".", "add", "(", "p2", ")", ";", "}", "}", "}", "}", "}", "}" ]
Generates the background edge hash set from the foreground edge hash set and the 2D array of pixels.
[ "Generates", "the", "background", "edge", "hash", "set", "from", "the", "foreground", "edge", "hash", "set", "and", "the", "2D", "array", "of", "pixels", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/modules/utils/BinaryFast.java#L207-L224
137,722
TheHortonMachine/hortonmachine
gears/src/main/java/oms3/io/CSVParser.java
CSVParser.nextValue
public String nextValue() throws IOException { Token tkn = nextToken(); String ret = null; switch (tkn.type) { case TT_TOKEN: case TT_EORECORD: ret = tkn.content.toString(); break; case TT_EOF: ret = null; break; case TT_INVALID: default: // error no token available (or error) throw new IOException( "(line " + getLineNumber() + ") invalid parse sequence"); /// unreachable: break; } return ret; }
java
public String nextValue() throws IOException { Token tkn = nextToken(); String ret = null; switch (tkn.type) { case TT_TOKEN: case TT_EORECORD: ret = tkn.content.toString(); break; case TT_EOF: ret = null; break; case TT_INVALID: default: // error no token available (or error) throw new IOException( "(line " + getLineNumber() + ") invalid parse sequence"); /// unreachable: break; } return ret; }
[ "public", "String", "nextValue", "(", ")", "throws", "IOException", "{", "Token", "tkn", "=", "nextToken", "(", ")", ";", "String", "ret", "=", "null", ";", "switch", "(", "tkn", ".", "type", ")", "{", "case", "TT_TOKEN", ":", "case", "TT_EORECORD", ":", "ret", "=", "tkn", ".", "content", ".", "toString", "(", ")", ";", "break", ";", "case", "TT_EOF", ":", "ret", "=", "null", ";", "break", ";", "case", "TT_INVALID", ":", "default", ":", "// error no token available (or error)", "throw", "new", "IOException", "(", "\"(line \"", "+", "getLineNumber", "(", ")", "+", "\") invalid parse sequence\"", ")", ";", "/// unreachable: break;", "}", "return", "ret", ";", "}" ]
Parses the CSV according to the given strategy and returns the next csv-value as string. @return next value in the input stream ('null' when end of file) @throws IOException on parse error or input read-failure
[ "Parses", "the", "CSV", "according", "to", "the", "given", "strategy", "and", "returns", "the", "next", "csv", "-", "value", "as", "string", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/oms3/io/CSVParser.java#L237-L256
137,723
TheHortonMachine/hortonmachine
gears/src/main/java/oms3/io/CSVParser.java
CSVParser.getLine
public String[] getLine() throws IOException { String[] ret = EMPTY_STRING_ARRAY; record.clear(); while (true) { reusableToken.reset(); nextToken(reusableToken); switch (reusableToken.type) { case TT_TOKEN: record.add(reusableToken.content.toString()); break; case TT_EORECORD: record.add(reusableToken.content.toString()); break; case TT_EOF: if (reusableToken.isReady) { record.add(reusableToken.content.toString()); } else { ret = null; } break; case TT_INVALID: default: // error: throw IOException throw new IOException("(line " + getLineNumber() + ") invalid parse sequence"); // unreachable: break; } if (reusableToken.type != TT_TOKEN) { break; } } if (!record.isEmpty()) { ret = (String[]) record.toArray(new String[record.size()]); } return ret; }
java
public String[] getLine() throws IOException { String[] ret = EMPTY_STRING_ARRAY; record.clear(); while (true) { reusableToken.reset(); nextToken(reusableToken); switch (reusableToken.type) { case TT_TOKEN: record.add(reusableToken.content.toString()); break; case TT_EORECORD: record.add(reusableToken.content.toString()); break; case TT_EOF: if (reusableToken.isReady) { record.add(reusableToken.content.toString()); } else { ret = null; } break; case TT_INVALID: default: // error: throw IOException throw new IOException("(line " + getLineNumber() + ") invalid parse sequence"); // unreachable: break; } if (reusableToken.type != TT_TOKEN) { break; } } if (!record.isEmpty()) { ret = (String[]) record.toArray(new String[record.size()]); } return ret; }
[ "public", "String", "[", "]", "getLine", "(", ")", "throws", "IOException", "{", "String", "[", "]", "ret", "=", "EMPTY_STRING_ARRAY", ";", "record", ".", "clear", "(", ")", ";", "while", "(", "true", ")", "{", "reusableToken", ".", "reset", "(", ")", ";", "nextToken", "(", "reusableToken", ")", ";", "switch", "(", "reusableToken", ".", "type", ")", "{", "case", "TT_TOKEN", ":", "record", ".", "add", "(", "reusableToken", ".", "content", ".", "toString", "(", ")", ")", ";", "break", ";", "case", "TT_EORECORD", ":", "record", ".", "add", "(", "reusableToken", ".", "content", ".", "toString", "(", ")", ")", ";", "break", ";", "case", "TT_EOF", ":", "if", "(", "reusableToken", ".", "isReady", ")", "{", "record", ".", "add", "(", "reusableToken", ".", "content", ".", "toString", "(", ")", ")", ";", "}", "else", "{", "ret", "=", "null", ";", "}", "break", ";", "case", "TT_INVALID", ":", "default", ":", "// error: throw IOException", "throw", "new", "IOException", "(", "\"(line \"", "+", "getLineNumber", "(", ")", "+", "\") invalid parse sequence\"", ")", ";", "// unreachable: break;", "}", "if", "(", "reusableToken", ".", "type", "!=", "TT_TOKEN", ")", "{", "break", ";", "}", "}", "if", "(", "!", "record", ".", "isEmpty", "(", ")", ")", "{", "ret", "=", "(", "String", "[", "]", ")", "record", ".", "toArray", "(", "new", "String", "[", "record", ".", "size", "(", ")", "]", ")", ";", "}", "return", "ret", ";", "}" ]
Parses from the current point in the stream til the end of the current line. @return array of values til end of line ('null' when end of file has been reached) @throws IOException on parse error or input read-failure
[ "Parses", "from", "the", "current", "point", "in", "the", "stream", "til", "the", "end", "of", "the", "current", "line", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/oms3/io/CSVParser.java#L266-L300
137,724
TheHortonMachine/hortonmachine
gears/src/main/java/oms3/io/CSVParser.java
CSVParser.nextToken
Token nextToken(Token tkn) throws IOException { wsBuf.clear(); // resuse // get the last read char (required for empty line detection) int lastChar = in.readAgain(); // read the next char and set eol /* note: unfourtunately isEndOfLine may consumes a character silently. * this has no effect outside of the method. so a simple workaround * is to call 'readAgain' on the stream... * uh: might using objects instead of base-types (jdk1.5 autoboxing!) */ int c = in.read(); boolean eol = isEndOfLine(c); c = in.readAgain(); // empty line detection: eol AND (last char was EOL or beginning) while (strategy.getIgnoreEmptyLines() && eol && (lastChar == '\n' || lastChar == ExtendedBufferedReader.UNDEFINED) && !isEndOfFile(lastChar)) { // go on char ahead ... lastChar = c; c = in.read(); eol = isEndOfLine(c); c = in.readAgain(); // reached end of file without any content (empty line at the end) if (isEndOfFile(c)) { tkn.type = TT_EOF; return tkn; } } // did we reached eof during the last iteration already ? TT_EOF if (isEndOfFile(lastChar) || (lastChar != strategy.getDelimiter() && isEndOfFile(c))) { tkn.type = TT_EOF; return tkn; } // important: make sure a new char gets consumed in each iteration while (!tkn.isReady) { // ignore whitespaces at beginning of a token while (isWhitespace(c) && !eol) { wsBuf.append((char) c); c = in.read(); eol = isEndOfLine(c); } // ok, start of token reached: comment, encapsulated, or token if (c == strategy.getCommentStart()) { // ignore everything till end of line and continue (incr linecount) in.readLine(); tkn = nextToken(tkn.reset()); } else if (c == strategy.getDelimiter()) { // empty token return TT_TOKEN("") tkn.type = TT_TOKEN; tkn.isReady = true; } else if (eol) { // empty token return TT_EORECORD("") //noop: tkn.content.append(""); tkn.type = TT_EORECORD; tkn.isReady = true; } else if (c == strategy.getEncapsulator()) { // consume encapsulated token encapsulatedTokenLexer(tkn, c); } else if (isEndOfFile(c)) { // end of file return TT_EOF() //noop: tkn.content.append(""); tkn.type = TT_EOF; tkn.isReady = true; } else { // next token must be a simple token // add removed blanks when not ignoring whitespace chars... if (!strategy.getIgnoreLeadingWhitespaces()) { tkn.content.append(wsBuf); } simpleTokenLexer(tkn, c); } } return tkn; }
java
Token nextToken(Token tkn) throws IOException { wsBuf.clear(); // resuse // get the last read char (required for empty line detection) int lastChar = in.readAgain(); // read the next char and set eol /* note: unfourtunately isEndOfLine may consumes a character silently. * this has no effect outside of the method. so a simple workaround * is to call 'readAgain' on the stream... * uh: might using objects instead of base-types (jdk1.5 autoboxing!) */ int c = in.read(); boolean eol = isEndOfLine(c); c = in.readAgain(); // empty line detection: eol AND (last char was EOL or beginning) while (strategy.getIgnoreEmptyLines() && eol && (lastChar == '\n' || lastChar == ExtendedBufferedReader.UNDEFINED) && !isEndOfFile(lastChar)) { // go on char ahead ... lastChar = c; c = in.read(); eol = isEndOfLine(c); c = in.readAgain(); // reached end of file without any content (empty line at the end) if (isEndOfFile(c)) { tkn.type = TT_EOF; return tkn; } } // did we reached eof during the last iteration already ? TT_EOF if (isEndOfFile(lastChar) || (lastChar != strategy.getDelimiter() && isEndOfFile(c))) { tkn.type = TT_EOF; return tkn; } // important: make sure a new char gets consumed in each iteration while (!tkn.isReady) { // ignore whitespaces at beginning of a token while (isWhitespace(c) && !eol) { wsBuf.append((char) c); c = in.read(); eol = isEndOfLine(c); } // ok, start of token reached: comment, encapsulated, or token if (c == strategy.getCommentStart()) { // ignore everything till end of line and continue (incr linecount) in.readLine(); tkn = nextToken(tkn.reset()); } else if (c == strategy.getDelimiter()) { // empty token return TT_TOKEN("") tkn.type = TT_TOKEN; tkn.isReady = true; } else if (eol) { // empty token return TT_EORECORD("") //noop: tkn.content.append(""); tkn.type = TT_EORECORD; tkn.isReady = true; } else if (c == strategy.getEncapsulator()) { // consume encapsulated token encapsulatedTokenLexer(tkn, c); } else if (isEndOfFile(c)) { // end of file return TT_EOF() //noop: tkn.content.append(""); tkn.type = TT_EOF; tkn.isReady = true; } else { // next token must be a simple token // add removed blanks when not ignoring whitespace chars... if (!strategy.getIgnoreLeadingWhitespaces()) { tkn.content.append(wsBuf); } simpleTokenLexer(tkn, c); } } return tkn; }
[ "Token", "nextToken", "(", "Token", "tkn", ")", "throws", "IOException", "{", "wsBuf", ".", "clear", "(", ")", ";", "// resuse", "// get the last read char (required for empty line detection)", "int", "lastChar", "=", "in", ".", "readAgain", "(", ")", ";", "// read the next char and set eol", "/* note: unfourtunately isEndOfLine may consumes a character silently.\n * this has no effect outside of the method. so a simple workaround\n * is to call 'readAgain' on the stream...\n * uh: might using objects instead of base-types (jdk1.5 autoboxing!)\n */", "int", "c", "=", "in", ".", "read", "(", ")", ";", "boolean", "eol", "=", "isEndOfLine", "(", "c", ")", ";", "c", "=", "in", ".", "readAgain", "(", ")", ";", "// empty line detection: eol AND (last char was EOL or beginning)", "while", "(", "strategy", ".", "getIgnoreEmptyLines", "(", ")", "&&", "eol", "&&", "(", "lastChar", "==", "'", "'", "||", "lastChar", "==", "ExtendedBufferedReader", ".", "UNDEFINED", ")", "&&", "!", "isEndOfFile", "(", "lastChar", ")", ")", "{", "// go on char ahead ...", "lastChar", "=", "c", ";", "c", "=", "in", ".", "read", "(", ")", ";", "eol", "=", "isEndOfLine", "(", "c", ")", ";", "c", "=", "in", ".", "readAgain", "(", ")", ";", "// reached end of file without any content (empty line at the end)", "if", "(", "isEndOfFile", "(", "c", ")", ")", "{", "tkn", ".", "type", "=", "TT_EOF", ";", "return", "tkn", ";", "}", "}", "// did we reached eof during the last iteration already ? TT_EOF", "if", "(", "isEndOfFile", "(", "lastChar", ")", "||", "(", "lastChar", "!=", "strategy", ".", "getDelimiter", "(", ")", "&&", "isEndOfFile", "(", "c", ")", ")", ")", "{", "tkn", ".", "type", "=", "TT_EOF", ";", "return", "tkn", ";", "}", "// important: make sure a new char gets consumed in each iteration", "while", "(", "!", "tkn", ".", "isReady", ")", "{", "// ignore whitespaces at beginning of a token", "while", "(", "isWhitespace", "(", "c", ")", "&&", "!", "eol", ")", "{", "wsBuf", ".", "append", "(", "(", "char", ")", "c", ")", ";", "c", "=", "in", ".", "read", "(", ")", ";", "eol", "=", "isEndOfLine", "(", "c", ")", ";", "}", "// ok, start of token reached: comment, encapsulated, or token", "if", "(", "c", "==", "strategy", ".", "getCommentStart", "(", ")", ")", "{", "// ignore everything till end of line and continue (incr linecount)", "in", ".", "readLine", "(", ")", ";", "tkn", "=", "nextToken", "(", "tkn", ".", "reset", "(", ")", ")", ";", "}", "else", "if", "(", "c", "==", "strategy", ".", "getDelimiter", "(", ")", ")", "{", "// empty token return TT_TOKEN(\"\")", "tkn", ".", "type", "=", "TT_TOKEN", ";", "tkn", ".", "isReady", "=", "true", ";", "}", "else", "if", "(", "eol", ")", "{", "// empty token return TT_EORECORD(\"\")", "//noop: tkn.content.append(\"\");", "tkn", ".", "type", "=", "TT_EORECORD", ";", "tkn", ".", "isReady", "=", "true", ";", "}", "else", "if", "(", "c", "==", "strategy", ".", "getEncapsulator", "(", ")", ")", "{", "// consume encapsulated token", "encapsulatedTokenLexer", "(", "tkn", ",", "c", ")", ";", "}", "else", "if", "(", "isEndOfFile", "(", "c", ")", ")", "{", "// end of file return TT_EOF()", "//noop: tkn.content.append(\"\");", "tkn", ".", "type", "=", "TT_EOF", ";", "tkn", ".", "isReady", "=", "true", ";", "}", "else", "{", "// next token must be a simple token", "// add removed blanks when not ignoring whitespace chars...", "if", "(", "!", "strategy", ".", "getIgnoreLeadingWhitespaces", "(", ")", ")", "{", "tkn", ".", "content", ".", "append", "(", "wsBuf", ")", ";", "}", "simpleTokenLexer", "(", "tkn", ",", "c", ")", ";", "}", "}", "return", "tkn", ";", "}" ]
Returns the next token. A token corresponds to a term, a record change or an end-of-file indicator. @param tkn an existing Token object to reuse. The caller is responsible to initialize the Token. @return the next token found @throws IOException on stream access error
[ "Returns", "the", "next", "token", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/oms3/io/CSVParser.java#L335-L411
137,725
TheHortonMachine/hortonmachine
gears/src/main/java/oms3/io/CSVParser.java
CSVParser.simpleTokenLexer
private Token simpleTokenLexer(Token tkn, int c) throws IOException { for (;;) { if (isEndOfLine(c)) { // end of record tkn.type = TT_EORECORD; tkn.isReady = true; break; } else if (isEndOfFile(c)) { // end of file tkn.type = TT_EOF; tkn.isReady = true; break; } else if (c == strategy.getDelimiter()) { // end of token tkn.type = TT_TOKEN; tkn.isReady = true; break; } else if (c == '\\' && strategy.getUnicodeEscapeInterpretation() && in.lookAhead() == 'u') { // interpret unicode escaped chars (like \u0070 -> p) tkn.content.append((char) unicodeEscapeLexer(c)); } else if (c == strategy.getEscape()) { tkn.content.append((char) readEscape(c)); } else { tkn.content.append((char) c); } c = in.read(); } if (strategy.getIgnoreTrailingWhitespaces()) { tkn.content.trimTrailingWhitespace(); } return tkn; }
java
private Token simpleTokenLexer(Token tkn, int c) throws IOException { for (;;) { if (isEndOfLine(c)) { // end of record tkn.type = TT_EORECORD; tkn.isReady = true; break; } else if (isEndOfFile(c)) { // end of file tkn.type = TT_EOF; tkn.isReady = true; break; } else if (c == strategy.getDelimiter()) { // end of token tkn.type = TT_TOKEN; tkn.isReady = true; break; } else if (c == '\\' && strategy.getUnicodeEscapeInterpretation() && in.lookAhead() == 'u') { // interpret unicode escaped chars (like \u0070 -> p) tkn.content.append((char) unicodeEscapeLexer(c)); } else if (c == strategy.getEscape()) { tkn.content.append((char) readEscape(c)); } else { tkn.content.append((char) c); } c = in.read(); } if (strategy.getIgnoreTrailingWhitespaces()) { tkn.content.trimTrailingWhitespace(); } return tkn; }
[ "private", "Token", "simpleTokenLexer", "(", "Token", "tkn", ",", "int", "c", ")", "throws", "IOException", "{", "for", "(", ";", ";", ")", "{", "if", "(", "isEndOfLine", "(", "c", ")", ")", "{", "// end of record", "tkn", ".", "type", "=", "TT_EORECORD", ";", "tkn", ".", "isReady", "=", "true", ";", "break", ";", "}", "else", "if", "(", "isEndOfFile", "(", "c", ")", ")", "{", "// end of file", "tkn", ".", "type", "=", "TT_EOF", ";", "tkn", ".", "isReady", "=", "true", ";", "break", ";", "}", "else", "if", "(", "c", "==", "strategy", ".", "getDelimiter", "(", ")", ")", "{", "// end of token", "tkn", ".", "type", "=", "TT_TOKEN", ";", "tkn", ".", "isReady", "=", "true", ";", "break", ";", "}", "else", "if", "(", "c", "==", "'", "'", "&&", "strategy", ".", "getUnicodeEscapeInterpretation", "(", ")", "&&", "in", ".", "lookAhead", "(", ")", "==", "'", "'", ")", "{", "// interpret unicode escaped chars (like \\u0070 -> p)", "tkn", ".", "content", ".", "append", "(", "(", "char", ")", "unicodeEscapeLexer", "(", "c", ")", ")", ";", "}", "else", "if", "(", "c", "==", "strategy", ".", "getEscape", "(", ")", ")", "{", "tkn", ".", "content", ".", "append", "(", "(", "char", ")", "readEscape", "(", "c", ")", ")", ";", "}", "else", "{", "tkn", ".", "content", ".", "append", "(", "(", "char", ")", "c", ")", ";", "}", "c", "=", "in", ".", "read", "(", ")", ";", "}", "if", "(", "strategy", ".", "getIgnoreTrailingWhitespaces", "(", ")", ")", "{", "tkn", ".", "content", ".", "trimTrailingWhitespace", "(", ")", ";", "}", "return", "tkn", ";", "}" ]
A simple token lexer Simple token are tokens which are not surrounded by encapsulators. A simple token might contain escaped delimiters (as \, or \;). The token is finished when one of the following conditions become true: <ul> <li>end of line has been reached (TT_EORECORD)</li> <li>end of stream has been reached (TT_EOF)</li> <li>an unescaped delimiter has been reached (TT_TOKEN)</li> </ul> @param tkn the current token @param c the current character @return the filled token @throws IOException on stream access error
[ "A", "simple", "token", "lexer" ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/oms3/io/CSVParser.java#L431-L465
137,726
TheHortonMachine/hortonmachine
gears/src/main/java/oms3/io/CSVParser.java
CSVParser.encapsulatedTokenLexer
private Token encapsulatedTokenLexer(Token tkn, int c) throws IOException { // save current line int startLineNumber = getLineNumber(); // ignore the given delimiter // assert c == delimiter; for (;;) { c = in.read(); if (c == '\\' && strategy.getUnicodeEscapeInterpretation() && in.lookAhead() == 'u') { tkn.content.append((char) unicodeEscapeLexer(c)); } else if (c == strategy.getEscape()) { tkn.content.append((char) readEscape(c)); } else if (c == strategy.getEncapsulator()) { if (in.lookAhead() == strategy.getEncapsulator()) { // double or escaped encapsulator -> add single encapsulator to token c = in.read(); tkn.content.append((char) c); } else { // token finish mark (encapsulator) reached: ignore whitespace till delimiter for (;;) { c = in.read(); if (c == strategy.getDelimiter()) { tkn.type = TT_TOKEN; tkn.isReady = true; return tkn; } else if (isEndOfFile(c)) { tkn.type = TT_EOF; tkn.isReady = true; return tkn; } else if (isEndOfLine(c)) { // ok eo token reached tkn.type = TT_EORECORD; tkn.isReady = true; return tkn; } else if (!isWhitespace(c)) { // error invalid char between token and next delimiter throw new IOException( "(line " + getLineNumber() + ") invalid char between encapsulated token end delimiter"); } } } } else if (isEndOfFile(c)) { // error condition (end of file before end of token) throw new IOException( "(startline " + startLineNumber + ")" + "eof reached before encapsulated token finished"); } else { // consume character tkn.content.append((char) c); } } }
java
private Token encapsulatedTokenLexer(Token tkn, int c) throws IOException { // save current line int startLineNumber = getLineNumber(); // ignore the given delimiter // assert c == delimiter; for (;;) { c = in.read(); if (c == '\\' && strategy.getUnicodeEscapeInterpretation() && in.lookAhead() == 'u') { tkn.content.append((char) unicodeEscapeLexer(c)); } else if (c == strategy.getEscape()) { tkn.content.append((char) readEscape(c)); } else if (c == strategy.getEncapsulator()) { if (in.lookAhead() == strategy.getEncapsulator()) { // double or escaped encapsulator -> add single encapsulator to token c = in.read(); tkn.content.append((char) c); } else { // token finish mark (encapsulator) reached: ignore whitespace till delimiter for (;;) { c = in.read(); if (c == strategy.getDelimiter()) { tkn.type = TT_TOKEN; tkn.isReady = true; return tkn; } else if (isEndOfFile(c)) { tkn.type = TT_EOF; tkn.isReady = true; return tkn; } else if (isEndOfLine(c)) { // ok eo token reached tkn.type = TT_EORECORD; tkn.isReady = true; return tkn; } else if (!isWhitespace(c)) { // error invalid char between token and next delimiter throw new IOException( "(line " + getLineNumber() + ") invalid char between encapsulated token end delimiter"); } } } } else if (isEndOfFile(c)) { // error condition (end of file before end of token) throw new IOException( "(startline " + startLineNumber + ")" + "eof reached before encapsulated token finished"); } else { // consume character tkn.content.append((char) c); } } }
[ "private", "Token", "encapsulatedTokenLexer", "(", "Token", "tkn", ",", "int", "c", ")", "throws", "IOException", "{", "// save current line", "int", "startLineNumber", "=", "getLineNumber", "(", ")", ";", "// ignore the given delimiter", "// assert c == delimiter;", "for", "(", ";", ";", ")", "{", "c", "=", "in", ".", "read", "(", ")", ";", "if", "(", "c", "==", "'", "'", "&&", "strategy", ".", "getUnicodeEscapeInterpretation", "(", ")", "&&", "in", ".", "lookAhead", "(", ")", "==", "'", "'", ")", "{", "tkn", ".", "content", ".", "append", "(", "(", "char", ")", "unicodeEscapeLexer", "(", "c", ")", ")", ";", "}", "else", "if", "(", "c", "==", "strategy", ".", "getEscape", "(", ")", ")", "{", "tkn", ".", "content", ".", "append", "(", "(", "char", ")", "readEscape", "(", "c", ")", ")", ";", "}", "else", "if", "(", "c", "==", "strategy", ".", "getEncapsulator", "(", ")", ")", "{", "if", "(", "in", ".", "lookAhead", "(", ")", "==", "strategy", ".", "getEncapsulator", "(", ")", ")", "{", "// double or escaped encapsulator -> add single encapsulator to token", "c", "=", "in", ".", "read", "(", ")", ";", "tkn", ".", "content", ".", "append", "(", "(", "char", ")", "c", ")", ";", "}", "else", "{", "// token finish mark (encapsulator) reached: ignore whitespace till delimiter", "for", "(", ";", ";", ")", "{", "c", "=", "in", ".", "read", "(", ")", ";", "if", "(", "c", "==", "strategy", ".", "getDelimiter", "(", ")", ")", "{", "tkn", ".", "type", "=", "TT_TOKEN", ";", "tkn", ".", "isReady", "=", "true", ";", "return", "tkn", ";", "}", "else", "if", "(", "isEndOfFile", "(", "c", ")", ")", "{", "tkn", ".", "type", "=", "TT_EOF", ";", "tkn", ".", "isReady", "=", "true", ";", "return", "tkn", ";", "}", "else", "if", "(", "isEndOfLine", "(", "c", ")", ")", "{", "// ok eo token reached", "tkn", ".", "type", "=", "TT_EORECORD", ";", "tkn", ".", "isReady", "=", "true", ";", "return", "tkn", ";", "}", "else", "if", "(", "!", "isWhitespace", "(", "c", ")", ")", "{", "// error invalid char between token and next delimiter", "throw", "new", "IOException", "(", "\"(line \"", "+", "getLineNumber", "(", ")", "+", "\") invalid char between encapsulated token end delimiter\"", ")", ";", "}", "}", "}", "}", "else", "if", "(", "isEndOfFile", "(", "c", ")", ")", "{", "// error condition (end of file before end of token)", "throw", "new", "IOException", "(", "\"(startline \"", "+", "startLineNumber", "+", "\")\"", "+", "\"eof reached before encapsulated token finished\"", ")", ";", "}", "else", "{", "// consume character", "tkn", ".", "content", ".", "append", "(", "(", "char", ")", "c", ")", ";", "}", "}", "}" ]
An encapsulated token lexer Encapsulated tokens are surrounded by the given encapsulating-string. The encapsulator itself might be included in the token using a doubling syntax (as "", '') or using escaping (as in \", \'). Whitespaces before and after an encapsulated token are ignored. @param tkn the current token @param c the current character @return a valid token object @throws IOException on invalid state
[ "An", "encapsulated", "token", "lexer" ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/oms3/io/CSVParser.java#L480-L530
137,727
TheHortonMachine/hortonmachine
gears/src/main/java/oms3/io/CSVParser.java
CSVParser.unicodeEscapeLexer
protected int unicodeEscapeLexer(int c) throws IOException { int ret = 0; // ignore 'u' (assume c==\ now) and read 4 hex digits c = in.read(); code.clear(); try { for (int i = 0; i < 4; i++) { c = in.read(); if (isEndOfFile(c) || isEndOfLine(c)) { throw new NumberFormatException("number too short"); } code.append((char) c); } ret = Integer.parseInt(code.toString(), 16); } catch (NumberFormatException e) { throw new IOException( "(line " + getLineNumber() + ") Wrong unicode escape sequence found '" + code.toString() + "'" + e.toString()); } return ret; }
java
protected int unicodeEscapeLexer(int c) throws IOException { int ret = 0; // ignore 'u' (assume c==\ now) and read 4 hex digits c = in.read(); code.clear(); try { for (int i = 0; i < 4; i++) { c = in.read(); if (isEndOfFile(c) || isEndOfLine(c)) { throw new NumberFormatException("number too short"); } code.append((char) c); } ret = Integer.parseInt(code.toString(), 16); } catch (NumberFormatException e) { throw new IOException( "(line " + getLineNumber() + ") Wrong unicode escape sequence found '" + code.toString() + "'" + e.toString()); } return ret; }
[ "protected", "int", "unicodeEscapeLexer", "(", "int", "c", ")", "throws", "IOException", "{", "int", "ret", "=", "0", ";", "// ignore 'u' (assume c==\\ now) and read 4 hex digits", "c", "=", "in", ".", "read", "(", ")", ";", "code", ".", "clear", "(", ")", ";", "try", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "4", ";", "i", "++", ")", "{", "c", "=", "in", ".", "read", "(", ")", ";", "if", "(", "isEndOfFile", "(", "c", ")", "||", "isEndOfLine", "(", "c", ")", ")", "{", "throw", "new", "NumberFormatException", "(", "\"number too short\"", ")", ";", "}", "code", ".", "append", "(", "(", "char", ")", "c", ")", ";", "}", "ret", "=", "Integer", ".", "parseInt", "(", "code", ".", "toString", "(", ")", ",", "16", ")", ";", "}", "catch", "(", "NumberFormatException", "e", ")", "{", "throw", "new", "IOException", "(", "\"(line \"", "+", "getLineNumber", "(", ")", "+", "\") Wrong unicode escape sequence found '\"", "+", "code", ".", "toString", "(", ")", "+", "\"'\"", "+", "e", ".", "toString", "(", ")", ")", ";", "}", "return", "ret", ";", "}" ]
Decodes Unicode escapes. Interpretation of "\\uXXXX" escape sequences where XXXX is a hex-number. @param c current char which is discarded because it's the "\\" of "\\uXXXX" @return the decoded character @throws IOException on wrong unicode escape sequence or read error
[ "Decodes", "Unicode", "escapes", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/oms3/io/CSVParser.java#L541-L560
137,728
TheHortonMachine/hortonmachine
gears/src/main/java/oms3/io/CSVParser.java
CSVParser.isEndOfLine
private boolean isEndOfLine(int c) throws IOException { // check if we have \r\n... if (c == '\r') { if (in.lookAhead() == '\n') { // note: does not change c outside of this method !! c = in.read(); } } return (c == '\n'); }
java
private boolean isEndOfLine(int c) throws IOException { // check if we have \r\n... if (c == '\r') { if (in.lookAhead() == '\n') { // note: does not change c outside of this method !! c = in.read(); } } return (c == '\n'); }
[ "private", "boolean", "isEndOfLine", "(", "int", "c", ")", "throws", "IOException", "{", "// check if we have \\r\\n...", "if", "(", "c", "==", "'", "'", ")", "{", "if", "(", "in", ".", "lookAhead", "(", ")", "==", "'", "'", ")", "{", "// note: does not change c outside of this method !!", "c", "=", "in", ".", "read", "(", ")", ";", "}", "}", "return", "(", "c", "==", "'", "'", ")", ";", "}" ]
Greedy - accepts \n and \r\n This checker consumes silently the second control-character... @return true if the given character is a line-terminator
[ "Greedy", "-", "accepts", "\\", "n", "and", "\\", "r", "\\", "n", "This", "checker", "consumes", "silently", "the", "second", "control", "-", "character", "..." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/oms3/io/CSVParser.java#L616-L625
137,729
TheHortonMachine/hortonmachine
hmachine/src/main/java/org/hortonmachine/hmachine/modules/hydrogeomorphology/skyview/OmsSkyview.java
OmsSkyview.skyviewfactor
private WritableRaster skyviewfactor( WritableRaster pitWR, double res ) { /* * evalutating the normal vector (in the center of the square compound * of 4 pixel. */ normalVectorWR = normalVector(pitWR, res); WritableRaster skyviewFactorWR = CoverageUtilities.createWritableRaster(cols, rows, null, pitWR.getSampleModel(), 0.0); pm.beginTask(msg.message("skyview.calculating"), 35); for( int i = 0; i < 360 - 10; i = i + 10 ) { azimuth = Math.toRadians(i * 1.0); WritableRaster skyViewWR = CoverageUtilities.createWritableRaster(cols, rows, null, pitWR.getSampleModel(), Math.toRadians(maxSlope)); for( int j = (int) maxSlope; j >= 0; j-- ) { elevation = Math.toRadians(j * 1.0); double[] sunVector = calcSunVector(); double[] inverseSunVector = calcInverseSunVector(sunVector); double[] normalSunVector = calcNormalSunVector(sunVector); calculateFactor(rows, cols, sunVector, inverseSunVector, normalSunVector, pitWR, skyViewWR, res); } for( int t = normalVectorWR.getMinY(); t < normalVectorWR.getMinY() + normalVectorWR.getHeight(); t++ ) { for( int k = normalVectorWR.getMinX(); k < normalVectorWR.getMinX() + normalVectorWR.getWidth(); k++ ) { double tmp = skyViewWR.getSampleDouble(k, t, 0); skyViewWR.setSample(k, t, 0, Math.cos(tmp) * Math.cos(tmp) * 10.0 / 360.0); } } for( int q = 0; q < skyviewFactorWR.getWidth(); q++ ) { for( int k = 0; k < skyviewFactorWR.getHeight(); k++ ) { double tmp = skyviewFactorWR.getSampleDouble(q, k, 0); skyviewFactorWR.setSample(q, k, 0, tmp + skyViewWR.getSampleDouble(q, k, 0)); } } pm.worked(1); } pm.done(); return skyviewFactorWR; }
java
private WritableRaster skyviewfactor( WritableRaster pitWR, double res ) { /* * evalutating the normal vector (in the center of the square compound * of 4 pixel. */ normalVectorWR = normalVector(pitWR, res); WritableRaster skyviewFactorWR = CoverageUtilities.createWritableRaster(cols, rows, null, pitWR.getSampleModel(), 0.0); pm.beginTask(msg.message("skyview.calculating"), 35); for( int i = 0; i < 360 - 10; i = i + 10 ) { azimuth = Math.toRadians(i * 1.0); WritableRaster skyViewWR = CoverageUtilities.createWritableRaster(cols, rows, null, pitWR.getSampleModel(), Math.toRadians(maxSlope)); for( int j = (int) maxSlope; j >= 0; j-- ) { elevation = Math.toRadians(j * 1.0); double[] sunVector = calcSunVector(); double[] inverseSunVector = calcInverseSunVector(sunVector); double[] normalSunVector = calcNormalSunVector(sunVector); calculateFactor(rows, cols, sunVector, inverseSunVector, normalSunVector, pitWR, skyViewWR, res); } for( int t = normalVectorWR.getMinY(); t < normalVectorWR.getMinY() + normalVectorWR.getHeight(); t++ ) { for( int k = normalVectorWR.getMinX(); k < normalVectorWR.getMinX() + normalVectorWR.getWidth(); k++ ) { double tmp = skyViewWR.getSampleDouble(k, t, 0); skyViewWR.setSample(k, t, 0, Math.cos(tmp) * Math.cos(tmp) * 10.0 / 360.0); } } for( int q = 0; q < skyviewFactorWR.getWidth(); q++ ) { for( int k = 0; k < skyviewFactorWR.getHeight(); k++ ) { double tmp = skyviewFactorWR.getSampleDouble(q, k, 0); skyviewFactorWR.setSample(q, k, 0, tmp + skyViewWR.getSampleDouble(q, k, 0)); } } pm.worked(1); } pm.done(); return skyviewFactorWR; }
[ "private", "WritableRaster", "skyviewfactor", "(", "WritableRaster", "pitWR", ",", "double", "res", ")", "{", "/*\n * evalutating the normal vector (in the center of the square compound\n * of 4 pixel.\n */", "normalVectorWR", "=", "normalVector", "(", "pitWR", ",", "res", ")", ";", "WritableRaster", "skyviewFactorWR", "=", "CoverageUtilities", ".", "createWritableRaster", "(", "cols", ",", "rows", ",", "null", ",", "pitWR", ".", "getSampleModel", "(", ")", ",", "0.0", ")", ";", "pm", ".", "beginTask", "(", "msg", ".", "message", "(", "\"skyview.calculating\"", ")", ",", "35", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "360", "-", "10", ";", "i", "=", "i", "+", "10", ")", "{", "azimuth", "=", "Math", ".", "toRadians", "(", "i", "*", "1.0", ")", ";", "WritableRaster", "skyViewWR", "=", "CoverageUtilities", ".", "createWritableRaster", "(", "cols", ",", "rows", ",", "null", ",", "pitWR", ".", "getSampleModel", "(", ")", ",", "Math", ".", "toRadians", "(", "maxSlope", ")", ")", ";", "for", "(", "int", "j", "=", "(", "int", ")", "maxSlope", ";", "j", ">=", "0", ";", "j", "--", ")", "{", "elevation", "=", "Math", ".", "toRadians", "(", "j", "*", "1.0", ")", ";", "double", "[", "]", "sunVector", "=", "calcSunVector", "(", ")", ";", "double", "[", "]", "inverseSunVector", "=", "calcInverseSunVector", "(", "sunVector", ")", ";", "double", "[", "]", "normalSunVector", "=", "calcNormalSunVector", "(", "sunVector", ")", ";", "calculateFactor", "(", "rows", ",", "cols", ",", "sunVector", ",", "inverseSunVector", ",", "normalSunVector", ",", "pitWR", ",", "skyViewWR", ",", "res", ")", ";", "}", "for", "(", "int", "t", "=", "normalVectorWR", ".", "getMinY", "(", ")", ";", "t", "<", "normalVectorWR", ".", "getMinY", "(", ")", "+", "normalVectorWR", ".", "getHeight", "(", ")", ";", "t", "++", ")", "{", "for", "(", "int", "k", "=", "normalVectorWR", ".", "getMinX", "(", ")", ";", "k", "<", "normalVectorWR", ".", "getMinX", "(", ")", "+", "normalVectorWR", ".", "getWidth", "(", ")", ";", "k", "++", ")", "{", "double", "tmp", "=", "skyViewWR", ".", "getSampleDouble", "(", "k", ",", "t", ",", "0", ")", ";", "skyViewWR", ".", "setSample", "(", "k", ",", "t", ",", "0", ",", "Math", ".", "cos", "(", "tmp", ")", "*", "Math", ".", "cos", "(", "tmp", ")", "*", "10.0", "/", "360.0", ")", ";", "}", "}", "for", "(", "int", "q", "=", "0", ";", "q", "<", "skyviewFactorWR", ".", "getWidth", "(", ")", ";", "q", "++", ")", "{", "for", "(", "int", "k", "=", "0", ";", "k", "<", "skyviewFactorWR", ".", "getHeight", "(", ")", ";", "k", "++", ")", "{", "double", "tmp", "=", "skyviewFactorWR", ".", "getSampleDouble", "(", "q", ",", "k", ",", "0", ")", ";", "skyviewFactorWR", ".", "setSample", "(", "q", ",", "k", ",", "0", ",", "tmp", "+", "skyViewWR", ".", "getSampleDouble", "(", "q", ",", "k", ",", "0", ")", ")", ";", "}", "}", "pm", ".", "worked", "(", "1", ")", ";", "}", "pm", ".", "done", "(", ")", ";", "return", "skyviewFactorWR", ";", "}" ]
Calculate the skyview factor. @param pitWR the dem ( the map of elevation). @param res the resolution of the map. @return the map of sky view factor.
[ "Calculate", "the", "skyview", "factor", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/hmachine/src/main/java/org/hortonmachine/hmachine/modules/hydrogeomorphology/skyview/OmsSkyview.java#L228-L270
137,730
TheHortonMachine/hortonmachine
hmachine/src/main/java/org/hortonmachine/hmachine/modules/hydrogeomorphology/skyview/OmsSkyview.java
OmsSkyview.shadow
protected WritableRaster shadow( int x, int y, WritableRaster tmpWR, WritableRaster pitWR, double res, double[] normalSunVector, double[] inverseSunVector, double[] sunVector ) { int n = 0; double zcompare = -Double.MAX_VALUE; double dx = (inverseSunVector[0] * n); double dy = (inverseSunVector[1] * n); int nCols = tmpWR.getWidth(); int nRows = tmpWR.getHeight(); int idx = (int) (x + dx); int jdy = (int) (y + dy); double vectorToOrigin[] = new double[3]; while( idx >= 0 && idx <= nCols - 1 && jdy >= 0 && jdy <= nRows - 1 ) { vectorToOrigin[0] = dx * res; vectorToOrigin[1] = dy * res; vectorToOrigin[2] = pitWR.getSampleDouble(idx, jdy, 0); double zprojection = scalarProduct(vectorToOrigin, normalSunVector); double nGrad[] = normalVectorWR.getPixel(idx, jdy, new double[3]); double cosinc = scalarProduct(sunVector, nGrad); double elevRad = elevation; if ((cosinc >= 0) && (zprojection > zcompare)) { tmpWR.setSample(idx, jdy, 0, elevRad); zcompare = zprojection; } n = n + 1; dy = (inverseSunVector[1] * n); dx = (inverseSunVector[0] * n); idx = (int) Math.round(x + dx); jdy = (int) Math.round(y + dy); } return tmpWR; }
java
protected WritableRaster shadow( int x, int y, WritableRaster tmpWR, WritableRaster pitWR, double res, double[] normalSunVector, double[] inverseSunVector, double[] sunVector ) { int n = 0; double zcompare = -Double.MAX_VALUE; double dx = (inverseSunVector[0] * n); double dy = (inverseSunVector[1] * n); int nCols = tmpWR.getWidth(); int nRows = tmpWR.getHeight(); int idx = (int) (x + dx); int jdy = (int) (y + dy); double vectorToOrigin[] = new double[3]; while( idx >= 0 && idx <= nCols - 1 && jdy >= 0 && jdy <= nRows - 1 ) { vectorToOrigin[0] = dx * res; vectorToOrigin[1] = dy * res; vectorToOrigin[2] = pitWR.getSampleDouble(idx, jdy, 0); double zprojection = scalarProduct(vectorToOrigin, normalSunVector); double nGrad[] = normalVectorWR.getPixel(idx, jdy, new double[3]); double cosinc = scalarProduct(sunVector, nGrad); double elevRad = elevation; if ((cosinc >= 0) && (zprojection > zcompare)) { tmpWR.setSample(idx, jdy, 0, elevRad); zcompare = zprojection; } n = n + 1; dy = (inverseSunVector[1] * n); dx = (inverseSunVector[0] * n); idx = (int) Math.round(x + dx); jdy = (int) Math.round(y + dy); } return tmpWR; }
[ "protected", "WritableRaster", "shadow", "(", "int", "x", ",", "int", "y", ",", "WritableRaster", "tmpWR", ",", "WritableRaster", "pitWR", ",", "double", "res", ",", "double", "[", "]", "normalSunVector", ",", "double", "[", "]", "inverseSunVector", ",", "double", "[", "]", "sunVector", ")", "{", "int", "n", "=", "0", ";", "double", "zcompare", "=", "-", "Double", ".", "MAX_VALUE", ";", "double", "dx", "=", "(", "inverseSunVector", "[", "0", "]", "*", "n", ")", ";", "double", "dy", "=", "(", "inverseSunVector", "[", "1", "]", "*", "n", ")", ";", "int", "nCols", "=", "tmpWR", ".", "getWidth", "(", ")", ";", "int", "nRows", "=", "tmpWR", ".", "getHeight", "(", ")", ";", "int", "idx", "=", "(", "int", ")", "(", "x", "+", "dx", ")", ";", "int", "jdy", "=", "(", "int", ")", "(", "y", "+", "dy", ")", ";", "double", "vectorToOrigin", "[", "]", "=", "new", "double", "[", "3", "]", ";", "while", "(", "idx", ">=", "0", "&&", "idx", "<=", "nCols", "-", "1", "&&", "jdy", ">=", "0", "&&", "jdy", "<=", "nRows", "-", "1", ")", "{", "vectorToOrigin", "[", "0", "]", "=", "dx", "*", "res", ";", "vectorToOrigin", "[", "1", "]", "=", "dy", "*", "res", ";", "vectorToOrigin", "[", "2", "]", "=", "pitWR", ".", "getSampleDouble", "(", "idx", ",", "jdy", ",", "0", ")", ";", "double", "zprojection", "=", "scalarProduct", "(", "vectorToOrigin", ",", "normalSunVector", ")", ";", "double", "nGrad", "[", "]", "=", "normalVectorWR", ".", "getPixel", "(", "idx", ",", "jdy", ",", "new", "double", "[", "3", "]", ")", ";", "double", "cosinc", "=", "scalarProduct", "(", "sunVector", ",", "nGrad", ")", ";", "double", "elevRad", "=", "elevation", ";", "if", "(", "(", "cosinc", ">=", "0", ")", "&&", "(", "zprojection", ">", "zcompare", ")", ")", "{", "tmpWR", ".", "setSample", "(", "idx", ",", "jdy", ",", "0", ",", "elevRad", ")", ";", "zcompare", "=", "zprojection", ";", "}", "n", "=", "n", "+", "1", ";", "dy", "=", "(", "inverseSunVector", "[", "1", "]", "*", "n", ")", ";", "dx", "=", "(", "inverseSunVector", "[", "0", "]", "*", "n", ")", ";", "idx", "=", "(", "int", ")", "Math", ".", "round", "(", "x", "+", "dx", ")", ";", "jdy", "=", "(", "int", ")", "Math", ".", "round", "(", "y", "+", "dy", ")", ";", "}", "return", "tmpWR", ";", "}" ]
Calculate the angle. @param x the x index. @param y the y index. @param tmpWR the sky map. @param pitWR the elevation map. @param res the resolution of the map. @param normalSunVector @param inverseSunVector @param sunVector
[ "Calculate", "the", "angle", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/hmachine/src/main/java/org/hortonmachine/hmachine/modules/hydrogeomorphology/skyview/OmsSkyview.java#L284-L315
137,731
TheHortonMachine/hortonmachine
hmachine/src/main/java/org/hortonmachine/hmachine/modules/hydrogeomorphology/adige/core/MonitoringPoint.java
MonitoringPoint.connectIfPossible
public boolean connectIfPossible( MonitoringPoint monitoringPoint ) { // check if the other point has this as related id if (ID == monitoringPoint.getRelatedID()) { pfafRelatedMonitoringPointsTable.put(monitoringPoint.getPfatstetterNumber().toString(), monitoringPoint); return true; } return false; }
java
public boolean connectIfPossible( MonitoringPoint monitoringPoint ) { // check if the other point has this as related id if (ID == monitoringPoint.getRelatedID()) { pfafRelatedMonitoringPointsTable.put(monitoringPoint.getPfatstetterNumber().toString(), monitoringPoint); return true; } return false; }
[ "public", "boolean", "connectIfPossible", "(", "MonitoringPoint", "monitoringPoint", ")", "{", "// check if the other point has this as related id", "if", "(", "ID", "==", "monitoringPoint", ".", "getRelatedID", "(", ")", ")", "{", "pfafRelatedMonitoringPointsTable", ".", "put", "(", "monitoringPoint", ".", "getPfatstetterNumber", "(", ")", ".", "toString", "(", ")", ",", "monitoringPoint", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Tries to connect another monitoringpoint if that one has a related id equal to that of this object. That way it would be possible to add more than one point as related. @param monitoringPoint the point to connect @return true if the connection was successfull
[ "Tries", "to", "connect", "another", "monitoringpoint", "if", "that", "one", "has", "a", "related", "id", "equal", "to", "that", "of", "this", "object", ".", "That", "way", "it", "would", "be", "possible", "to", "add", "more", "than", "one", "point", "as", "related", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/hmachine/src/main/java/org/hortonmachine/hmachine/modules/hydrogeomorphology/adige/core/MonitoringPoint.java#L102-L111
137,732
TheHortonMachine/hortonmachine
hmachine/src/main/java/org/hortonmachine/hmachine/modules/hydrogeomorphology/adige/core/MonitoringPoint.java
MonitoringPoint.getRelatedMonitoringPoint
public MonitoringPoint getRelatedMonitoringPoint( String pfafStetter ) { if (pfafStetter != null) { return pfafRelatedMonitoringPointsTable.get(pfafStetter); } else { Set<String> keySet = pfafRelatedMonitoringPointsTable.keySet(); for( String key : keySet ) { return pfafRelatedMonitoringPointsTable.get(key); } return null; } }
java
public MonitoringPoint getRelatedMonitoringPoint( String pfafStetter ) { if (pfafStetter != null) { return pfafRelatedMonitoringPointsTable.get(pfafStetter); } else { Set<String> keySet = pfafRelatedMonitoringPointsTable.keySet(); for( String key : keySet ) { return pfafRelatedMonitoringPointsTable.get(key); } return null; } }
[ "public", "MonitoringPoint", "getRelatedMonitoringPoint", "(", "String", "pfafStetter", ")", "{", "if", "(", "pfafStetter", "!=", "null", ")", "{", "return", "pfafRelatedMonitoringPointsTable", ".", "get", "(", "pfafStetter", ")", ";", "}", "else", "{", "Set", "<", "String", ">", "keySet", "=", "pfafRelatedMonitoringPointsTable", ".", "keySet", "(", ")", ";", "for", "(", "String", "key", ":", "keySet", ")", "{", "return", "pfafRelatedMonitoringPointsTable", ".", "get", "(", "key", ")", ";", "}", "return", "null", ";", "}", "}" ]
Get the related monitoringpoint. If there are more than one, the pfafstetter number is used to chose. @param pfafStetter used to chose in the points table. Can be null, in which case the first found is taken (should be used only if there is only one point in the table) @return the related point
[ "Get", "the", "related", "monitoringpoint", ".", "If", "there", "are", "more", "than", "one", "the", "pfafstetter", "number", "is", "used", "to", "chose", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/hmachine/src/main/java/org/hortonmachine/hmachine/modules/hydrogeomorphology/adige/core/MonitoringPoint.java#L121-L131
137,733
TheHortonMachine/hortonmachine
hmachine/src/main/java/org/hortonmachine/hmachine/modules/hydrogeomorphology/adige/core/MonitoringPoint.java
MonitoringPoint.toFeatureCollection
public SimpleFeatureCollection toFeatureCollection( List<MonitoringPoint> monitoringPointsList ) { // create the feature type SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder(); // set the name b.setName("monitoringpoints"); // add a geometry property b.add("the_geom", Point.class); // add some properties b.add("id", Integer.class); b.add("relatedid", Integer.class); b.add("pfaf", String.class); // build the type SimpleFeatureType type = b.buildFeatureType(); // create the feature SimpleFeatureBuilder builder = new SimpleFeatureBuilder(type); GeometryFactory gF = new GeometryFactory(); /* * insert them in inverse order to get them out of the collection in the same order as the * list */ DefaultFeatureCollection newCollection = new DefaultFeatureCollection(); for( int i = 0; i < monitoringPointsList.size(); i++ ) { MonitoringPoint mp = monitoringPointsList.get(monitoringPointsList.size() - i - 1); Object[] values = new Object[]{gF.createPoint(mp.getPosition()), mp.getID(), mp.getRelatedID(), mp.getPfatstetterNumber().toString()}; // add the values builder.addAll(values); // build the feature with provided ID SimpleFeature feature = builder.buildFeature(type.getTypeName() + "." + i); newCollection.add(feature); } return newCollection; }
java
public SimpleFeatureCollection toFeatureCollection( List<MonitoringPoint> monitoringPointsList ) { // create the feature type SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder(); // set the name b.setName("monitoringpoints"); // add a geometry property b.add("the_geom", Point.class); // add some properties b.add("id", Integer.class); b.add("relatedid", Integer.class); b.add("pfaf", String.class); // build the type SimpleFeatureType type = b.buildFeatureType(); // create the feature SimpleFeatureBuilder builder = new SimpleFeatureBuilder(type); GeometryFactory gF = new GeometryFactory(); /* * insert them in inverse order to get them out of the collection in the same order as the * list */ DefaultFeatureCollection newCollection = new DefaultFeatureCollection(); for( int i = 0; i < monitoringPointsList.size(); i++ ) { MonitoringPoint mp = monitoringPointsList.get(monitoringPointsList.size() - i - 1); Object[] values = new Object[]{gF.createPoint(mp.getPosition()), mp.getID(), mp.getRelatedID(), mp.getPfatstetterNumber().toString()}; // add the values builder.addAll(values); // build the feature with provided ID SimpleFeature feature = builder.buildFeature(type.getTypeName() + "." + i); newCollection.add(feature); } return newCollection; }
[ "public", "SimpleFeatureCollection", "toFeatureCollection", "(", "List", "<", "MonitoringPoint", ">", "monitoringPointsList", ")", "{", "// create the feature type", "SimpleFeatureTypeBuilder", "b", "=", "new", "SimpleFeatureTypeBuilder", "(", ")", ";", "// set the name", "b", ".", "setName", "(", "\"monitoringpoints\"", ")", ";", "// add a geometry property", "b", ".", "add", "(", "\"the_geom\"", ",", "Point", ".", "class", ")", ";", "// add some properties", "b", ".", "add", "(", "\"id\"", ",", "Integer", ".", "class", ")", ";", "b", ".", "add", "(", "\"relatedid\"", ",", "Integer", ".", "class", ")", ";", "b", ".", "add", "(", "\"pfaf\"", ",", "String", ".", "class", ")", ";", "// build the type", "SimpleFeatureType", "type", "=", "b", ".", "buildFeatureType", "(", ")", ";", "// create the feature", "SimpleFeatureBuilder", "builder", "=", "new", "SimpleFeatureBuilder", "(", "type", ")", ";", "GeometryFactory", "gF", "=", "new", "GeometryFactory", "(", ")", ";", "/*\n * insert them in inverse order to get them out of the collection in the same order as the\n * list\n */", "DefaultFeatureCollection", "newCollection", "=", "new", "DefaultFeatureCollection", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "monitoringPointsList", ".", "size", "(", ")", ";", "i", "++", ")", "{", "MonitoringPoint", "mp", "=", "monitoringPointsList", ".", "get", "(", "monitoringPointsList", ".", "size", "(", ")", "-", "i", "-", "1", ")", ";", "Object", "[", "]", "values", "=", "new", "Object", "[", "]", "{", "gF", ".", "createPoint", "(", "mp", ".", "getPosition", "(", ")", ")", ",", "mp", ".", "getID", "(", ")", ",", "mp", ".", "getRelatedID", "(", ")", ",", "mp", ".", "getPfatstetterNumber", "(", ")", ".", "toString", "(", ")", "}", ";", "// add the values", "builder", ".", "addAll", "(", "values", ")", ";", "// build the feature with provided ID", "SimpleFeature", "feature", "=", "builder", ".", "buildFeature", "(", "type", ".", "getTypeName", "(", ")", "+", "\".\"", "+", "i", ")", ";", "newCollection", ".", "add", "(", "feature", ")", ";", "}", "return", "newCollection", ";", "}" ]
Create a featurecollection from a list of monitoringpoints. Based on the position of the points and some of their attributes. @param monitoringPointsList @return the featurecollection
[ "Create", "a", "featurecollection", "from", "a", "list", "of", "monitoringpoints", ".", "Based", "on", "the", "position", "of", "the", "points", "and", "some", "of", "their", "attributes", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/hmachine/src/main/java/org/hortonmachine/hmachine/modules/hydrogeomorphology/adige/core/MonitoringPoint.java#L241-L278
137,734
TheHortonMachine/hortonmachine
dbs/src/main/java/jsqlite/Blob.java
BlobR.skip
public long skip(long n) throws IOException { long ret = pos + n; if (ret < 0) { ret = 0; pos = 0; } else if (ret > blob.size) { ret = blob.size; pos = blob.size; } else { pos = (int) ret; } return ret; }
java
public long skip(long n) throws IOException { long ret = pos + n; if (ret < 0) { ret = 0; pos = 0; } else if (ret > blob.size) { ret = blob.size; pos = blob.size; } else { pos = (int) ret; } return ret; }
[ "public", "long", "skip", "(", "long", "n", ")", "throws", "IOException", "{", "long", "ret", "=", "pos", "+", "n", ";", "if", "(", "ret", "<", "0", ")", "{", "ret", "=", "0", ";", "pos", "=", "0", ";", "}", "else", "if", "(", "ret", ">", "blob", ".", "size", ")", "{", "ret", "=", "blob", ".", "size", ";", "pos", "=", "blob", ".", "size", ";", "}", "else", "{", "pos", "=", "(", "int", ")", "ret", ";", "}", "return", "ret", ";", "}" ]
Skip over blob data.
[ "Skip", "over", "blob", "data", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/dbs/src/main/java/jsqlite/Blob.java#L82-L94
137,735
TheHortonMachine/hortonmachine
dbs/src/main/java/jsqlite/Blob.java
BlobR.read
public int read() throws IOException { byte b[] = new byte[1]; int n = blob.read(b, 0, pos, b.length); if (n > 0) { pos += n; return b[0]; } return -1; }
java
public int read() throws IOException { byte b[] = new byte[1]; int n = blob.read(b, 0, pos, b.length); if (n > 0) { pos += n; return b[0]; } return -1; }
[ "public", "int", "read", "(", ")", "throws", "IOException", "{", "byte", "b", "[", "]", "=", "new", "byte", "[", "1", "]", ";", "int", "n", "=", "blob", ".", "read", "(", "b", ",", "0", ",", "pos", ",", "b", ".", "length", ")", ";", "if", "(", "n", ">", "0", ")", "{", "pos", "+=", "n", ";", "return", "b", "[", "0", "]", ";", "}", "return", "-", "1", ";", "}" ]
Read single byte from blob. @return byte read
[ "Read", "single", "byte", "from", "blob", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/dbs/src/main/java/jsqlite/Blob.java#L101-L109
137,736
TheHortonMachine/hortonmachine
dbs/src/main/java/jsqlite/Blob.java
BlobR.read
public int read(byte b[], int off, int len) throws IOException { if (off + len > b.length) { len = b.length - off; } if (len < 0) { return -1; } if (len == 0) { return 0; } int n = blob.read(b, off, pos, len); if (n > 0) { pos += n; return n; } return -1; }
java
public int read(byte b[], int off, int len) throws IOException { if (off + len > b.length) { len = b.length - off; } if (len < 0) { return -1; } if (len == 0) { return 0; } int n = blob.read(b, off, pos, len); if (n > 0) { pos += n; return n; } return -1; }
[ "public", "int", "read", "(", "byte", "b", "[", "]", ",", "int", "off", ",", "int", "len", ")", "throws", "IOException", "{", "if", "(", "off", "+", "len", ">", "b", ".", "length", ")", "{", "len", "=", "b", ".", "length", "-", "off", ";", "}", "if", "(", "len", "<", "0", ")", "{", "return", "-", "1", ";", "}", "if", "(", "len", "==", "0", ")", "{", "return", "0", ";", "}", "int", "n", "=", "blob", ".", "read", "(", "b", ",", "off", ",", "pos", ",", "len", ")", ";", "if", "(", "n", ">", "0", ")", "{", "pos", "+=", "n", ";", "return", "n", ";", "}", "return", "-", "1", ";", "}" ]
Read slice of byte array from blob. @param b byte array to be filled @param off offset into byte array @param len length to be read @return number of bytes read
[ "Read", "slice", "of", "byte", "array", "from", "blob", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/dbs/src/main/java/jsqlite/Blob.java#L134-L150
137,737
TheHortonMachine/hortonmachine
dbs/src/main/java/org/hortonmachine/dbs/rasterlite/Rasterlite2Db.java
Rasterlite2Db.getRasterCoverages
public List<Rasterlite2Coverage> getRasterCoverages( boolean doOrder ) throws Exception { List<Rasterlite2Coverage> rasterCoverages = new ArrayList<Rasterlite2Coverage>(); String orderBy = " ORDER BY " + Rasterlite2Coverage.COVERAGE_NAME; if (!doOrder) { orderBy = ""; } String sql = "SELECT " + Rasterlite2Coverage.COVERAGE_NAME + ", " + Rasterlite2Coverage.TITLE + ", " + Rasterlite2Coverage.SRID + ", " + Rasterlite2Coverage.COMPRESSION + ", " + Rasterlite2Coverage.EXTENT_MINX + ", " + Rasterlite2Coverage.EXTENT_MINY + ", " + Rasterlite2Coverage.EXTENT_MAXX + ", " + Rasterlite2Coverage.EXTENT_MAXY + " FROM " + Rasterlite2Coverage.TABLENAME + orderBy; return database.execOnConnection(connection -> { try (IHMStatement stmt = connection.createStatement(); IHMResultSet rs = stmt.executeQuery(sql)) { while( rs.next() ) { int i = 1; String coverageName = rs.getString(i++); String title = rs.getString(i++); int srid = rs.getInt(i++); String compression = rs.getString(i++); double minX = rs.getDouble(i++); double minY = rs.getDouble(i++); double maxX = rs.getDouble(i++); double maxY = rs.getDouble(i++); Rasterlite2Coverage rc = new Rasterlite2Coverage(database, coverageName, title, srid, compression, minX, minY, maxX, maxY); rasterCoverages.add(rc); } return rasterCoverages; } }); }
java
public List<Rasterlite2Coverage> getRasterCoverages( boolean doOrder ) throws Exception { List<Rasterlite2Coverage> rasterCoverages = new ArrayList<Rasterlite2Coverage>(); String orderBy = " ORDER BY " + Rasterlite2Coverage.COVERAGE_NAME; if (!doOrder) { orderBy = ""; } String sql = "SELECT " + Rasterlite2Coverage.COVERAGE_NAME + ", " + Rasterlite2Coverage.TITLE + ", " + Rasterlite2Coverage.SRID + ", " + Rasterlite2Coverage.COMPRESSION + ", " + Rasterlite2Coverage.EXTENT_MINX + ", " + Rasterlite2Coverage.EXTENT_MINY + ", " + Rasterlite2Coverage.EXTENT_MAXX + ", " + Rasterlite2Coverage.EXTENT_MAXY + " FROM " + Rasterlite2Coverage.TABLENAME + orderBy; return database.execOnConnection(connection -> { try (IHMStatement stmt = connection.createStatement(); IHMResultSet rs = stmt.executeQuery(sql)) { while( rs.next() ) { int i = 1; String coverageName = rs.getString(i++); String title = rs.getString(i++); int srid = rs.getInt(i++); String compression = rs.getString(i++); double minX = rs.getDouble(i++); double minY = rs.getDouble(i++); double maxX = rs.getDouble(i++); double maxY = rs.getDouble(i++); Rasterlite2Coverage rc = new Rasterlite2Coverage(database, coverageName, title, srid, compression, minX, minY, maxX, maxY); rasterCoverages.add(rc); } return rasterCoverages; } }); }
[ "public", "List", "<", "Rasterlite2Coverage", ">", "getRasterCoverages", "(", "boolean", "doOrder", ")", "throws", "Exception", "{", "List", "<", "Rasterlite2Coverage", ">", "rasterCoverages", "=", "new", "ArrayList", "<", "Rasterlite2Coverage", ">", "(", ")", ";", "String", "orderBy", "=", "\" ORDER BY \"", "+", "Rasterlite2Coverage", ".", "COVERAGE_NAME", ";", "if", "(", "!", "doOrder", ")", "{", "orderBy", "=", "\"\"", ";", "}", "String", "sql", "=", "\"SELECT \"", "+", "Rasterlite2Coverage", ".", "COVERAGE_NAME", "+", "\", \"", "+", "Rasterlite2Coverage", ".", "TITLE", "+", "\", \"", "+", "Rasterlite2Coverage", ".", "SRID", "+", "\", \"", "+", "Rasterlite2Coverage", ".", "COMPRESSION", "+", "\", \"", "+", "Rasterlite2Coverage", ".", "EXTENT_MINX", "+", "\", \"", "+", "Rasterlite2Coverage", ".", "EXTENT_MINY", "+", "\", \"", "+", "Rasterlite2Coverage", ".", "EXTENT_MAXX", "+", "\", \"", "+", "Rasterlite2Coverage", ".", "EXTENT_MAXY", "+", "\" FROM \"", "+", "Rasterlite2Coverage", ".", "TABLENAME", "+", "orderBy", ";", "return", "database", ".", "execOnConnection", "(", "connection", "->", "{", "try", "(", "IHMStatement", "stmt", "=", "connection", ".", "createStatement", "(", ")", ";", "IHMResultSet", "rs", "=", "stmt", ".", "executeQuery", "(", "sql", ")", ")", "{", "while", "(", "rs", ".", "next", "(", ")", ")", "{", "int", "i", "=", "1", ";", "String", "coverageName", "=", "rs", ".", "getString", "(", "i", "++", ")", ";", "String", "title", "=", "rs", ".", "getString", "(", "i", "++", ")", ";", "int", "srid", "=", "rs", ".", "getInt", "(", "i", "++", ")", ";", "String", "compression", "=", "rs", ".", "getString", "(", "i", "++", ")", ";", "double", "minX", "=", "rs", ".", "getDouble", "(", "i", "++", ")", ";", "double", "minY", "=", "rs", ".", "getDouble", "(", "i", "++", ")", ";", "double", "maxX", "=", "rs", ".", "getDouble", "(", "i", "++", ")", ";", "double", "maxY", "=", "rs", ".", "getDouble", "(", "i", "++", ")", ";", "Rasterlite2Coverage", "rc", "=", "new", "Rasterlite2Coverage", "(", "database", ",", "coverageName", ",", "title", ",", "srid", ",", "compression", ",", "minX", ",", "minY", ",", "maxX", ",", "maxY", ")", ";", "rasterCoverages", ".", "add", "(", "rc", ")", ";", "}", "return", "rasterCoverages", ";", "}", "}", ")", ";", "}" ]
Get the list of available raster coverages. @param doOrder if <code>true</code>, the names are ordered. @return the list of raster coverages. @throws Exception
[ "Get", "the", "list", "of", "available", "raster", "coverages", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/dbs/src/main/java/org/hortonmachine/dbs/rasterlite/Rasterlite2Db.java#L61-L94
137,738
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/io/dxfdwg/libs/dwg/objects/DwgEndblk.java
DwgEndblk.readDwgEndblkV15
public void readDwgEndblkV15(int[] data, int offset) throws Exception { int bitPos = offset; bitPos = readObjectHeaderV15(data, bitPos); bitPos = readObjectTailV15(data, bitPos); }
java
public void readDwgEndblkV15(int[] data, int offset) throws Exception { int bitPos = offset; bitPos = readObjectHeaderV15(data, bitPos); bitPos = readObjectTailV15(data, bitPos); }
[ "public", "void", "readDwgEndblkV15", "(", "int", "[", "]", "data", ",", "int", "offset", ")", "throws", "Exception", "{", "int", "bitPos", "=", "offset", ";", "bitPos", "=", "readObjectHeaderV15", "(", "data", ",", "bitPos", ")", ";", "bitPos", "=", "readObjectTailV15", "(", "data", ",", "bitPos", ")", ";", "}" ]
Read a Endblk in the DWG format Version 15 @param data Array of unsigned bytes obtained from the DWG binary file @param offset The current bit offset where the value begins @throws Exception If an unexpected bit value is found in the DWG file. Occurs when we are looking for LwPolylines.
[ "Read", "a", "Endblk", "in", "the", "DWG", "format", "Version", "15" ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/io/dxfdwg/libs/dwg/objects/DwgEndblk.java#L38-L42
137,739
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/utils/features/FilterUtilities.java
FilterUtilities.getBboxFilter
public static Filter getBboxFilter( String attribute, BoundingBox bbox ) throws CQLException { double w = bbox.getMinX(); double e = bbox.getMaxX(); double s = bbox.getMinY(); double n = bbox.getMaxY(); return getBboxFilter(attribute, w, e, s, n); }
java
public static Filter getBboxFilter( String attribute, BoundingBox bbox ) throws CQLException { double w = bbox.getMinX(); double e = bbox.getMaxX(); double s = bbox.getMinY(); double n = bbox.getMaxY(); return getBboxFilter(attribute, w, e, s, n); }
[ "public", "static", "Filter", "getBboxFilter", "(", "String", "attribute", ",", "BoundingBox", "bbox", ")", "throws", "CQLException", "{", "double", "w", "=", "bbox", ".", "getMinX", "(", ")", ";", "double", "e", "=", "bbox", ".", "getMaxX", "(", ")", ";", "double", "s", "=", "bbox", ".", "getMinY", "(", ")", ";", "double", "n", "=", "bbox", ".", "getMaxY", "(", ")", ";", "return", "getBboxFilter", "(", "attribute", ",", "w", ",", "e", ",", "s", ",", "n", ")", ";", "}" ]
Create a bounding box filter from a bounding box. @param attribute the geometry attribute or null in the case of default "the_geom". @param bbox the {@link BoundingBox}. @return the filter. @throws CQLException
[ "Create", "a", "bounding", "box", "filter", "from", "a", "bounding", "box", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/features/FilterUtilities.java#L44-L51
137,740
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/utils/features/FilterUtilities.java
FilterUtilities.getBboxFilter
public static Filter getBboxFilter( String attribute, double west, double east, double south, double north ) throws CQLException { if (attribute == null) { attribute = "the_geom"; } StringBuilder sB = new StringBuilder(); sB.append("BBOX("); sB.append(attribute); sB.append(","); sB.append(west); sB.append(","); sB.append(south); sB.append(","); sB.append(east); sB.append(","); sB.append(north); sB.append(")"); Filter bboxFilter = CQL.toFilter(sB.toString()); return bboxFilter; }
java
public static Filter getBboxFilter( String attribute, double west, double east, double south, double north ) throws CQLException { if (attribute == null) { attribute = "the_geom"; } StringBuilder sB = new StringBuilder(); sB.append("BBOX("); sB.append(attribute); sB.append(","); sB.append(west); sB.append(","); sB.append(south); sB.append(","); sB.append(east); sB.append(","); sB.append(north); sB.append(")"); Filter bboxFilter = CQL.toFilter(sB.toString()); return bboxFilter; }
[ "public", "static", "Filter", "getBboxFilter", "(", "String", "attribute", ",", "double", "west", ",", "double", "east", ",", "double", "south", ",", "double", "north", ")", "throws", "CQLException", "{", "if", "(", "attribute", "==", "null", ")", "{", "attribute", "=", "\"the_geom\"", ";", "}", "StringBuilder", "sB", "=", "new", "StringBuilder", "(", ")", ";", "sB", ".", "append", "(", "\"BBOX(\"", ")", ";", "sB", ".", "append", "(", "attribute", ")", ";", "sB", ".", "append", "(", "\",\"", ")", ";", "sB", ".", "append", "(", "west", ")", ";", "sB", ".", "append", "(", "\",\"", ")", ";", "sB", ".", "append", "(", "south", ")", ";", "sB", ".", "append", "(", "\",\"", ")", ";", "sB", ".", "append", "(", "east", ")", ";", "sB", ".", "append", "(", "\",\"", ")", ";", "sB", ".", "append", "(", "north", ")", ";", "sB", ".", "append", "(", "\")\"", ")", ";", "Filter", "bboxFilter", "=", "CQL", ".", "toFilter", "(", "sB", ".", "toString", "(", ")", ")", ";", "return", "bboxFilter", ";", "}" ]
Create a bounding box filter from the bounds coordinates. @param attribute the geometry attribute or null in the case of default "the_geom". @param west western bound coordinate. @param east eastern bound coordinate. @param south southern bound coordinate. @param north northern bound coordinate. @return the filter. @throws CQLException
[ "Create", "a", "bounding", "box", "filter", "from", "the", "bounds", "coordinates", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/features/FilterUtilities.java#L64-L87
137,741
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/utils/features/FilterUtilities.java
FilterUtilities.getIntersectsGeometryFilter
public static Filter getIntersectsGeometryFilter( String geomName, Geometry geometry ) throws CQLException { Filter result = CQL.toFilter("INTERSECTS(" + geomName + ", " + geometry.toText() + " )"); return result; }
java
public static Filter getIntersectsGeometryFilter( String geomName, Geometry geometry ) throws CQLException { Filter result = CQL.toFilter("INTERSECTS(" + geomName + ", " + geometry.toText() + " )"); return result; }
[ "public", "static", "Filter", "getIntersectsGeometryFilter", "(", "String", "geomName", ",", "Geometry", "geometry", ")", "throws", "CQLException", "{", "Filter", "result", "=", "CQL", ".", "toFilter", "(", "\"INTERSECTS(\"", "+", "geomName", "+", "\", \"", "+", "geometry", ".", "toText", "(", ")", "+", "\" )\"", ")", ";", "return", "result", ";", "}" ]
Creates an intersect filter. @param geomName the name of the geom field to filter. @param geometry the geometry to use as filtering geom. @return the filter. @throws CQLException
[ "Creates", "an", "intersect", "filter", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/features/FilterUtilities.java#L102-L105
137,742
TheHortonMachine/hortonmachine
gears/src/main/java/oms3/ngmf/util/cosu/DDS.java
DDS.neigh_value
private double neigh_value(double x_cur, double x_min, double x_max, double r) { double ranval, zvalue, new_value; double work3, work2 = 0, work1 = 0; double x_range = x_max - x_min; // ------------ generate a standard normal random variate (zvalue) ------------------- // perturb current value with normal random variable // CALL DRNNOA(1,zvalue) // generates a standard normal random deviate // ISML Stat Library 2 routine - Acceptance/rejection // Below returns a standard Gaussian random number based upon Numerical recipes gasdev and // Marsagalia-Bray Algorithm work3 = 2.0; while (work3 >= 1.0 || work3 == 0.0) { ranval = rand.nextDouble(); work1 = 2.0 * ranval - 1.0; ranval = rand.nextDouble(); work2 = 2.0 * ranval - 1.0; work3 = work1 * work1 + work2 * work2; } // was dlog() !!! work3 = Math.pow((-2.0 * Math.log(work3)) / work3, 0.5); // natural log // pick one of two deviates at random (don't worry about trying to use both): ranval = rand.nextDouble(); if (ranval < 0.5) { zvalue = work1 * work3; } else { zvalue = work2 * work3; } // ------------ done standard normal random variate generation ----------------- // calculate new decision variable value: new_value = x_cur + zvalue * r * x_range; // check new value is within DV bounds. If not, bounds are reflecting. if (new_value < x_min) { new_value = x_min + (x_min - new_value); if (new_value > x_max) { // if reflection goes past x_max { value should be x_min since // without reflection the approach goes way past lower bound. // This keeps x close to lower bound when x_cur is close to lower bound // Practically speaking, this should never happen with r values <0.3 new_value = x_min; } } else if (new_value > x_max) { new_value = x_max - (new_value - x_max); if (new_value < x_min) { // if reflection goes past x_min { value should be x_max for same reasons as above new_value = x_max; } } return new_value; }
java
private double neigh_value(double x_cur, double x_min, double x_max, double r) { double ranval, zvalue, new_value; double work3, work2 = 0, work1 = 0; double x_range = x_max - x_min; // ------------ generate a standard normal random variate (zvalue) ------------------- // perturb current value with normal random variable // CALL DRNNOA(1,zvalue) // generates a standard normal random deviate // ISML Stat Library 2 routine - Acceptance/rejection // Below returns a standard Gaussian random number based upon Numerical recipes gasdev and // Marsagalia-Bray Algorithm work3 = 2.0; while (work3 >= 1.0 || work3 == 0.0) { ranval = rand.nextDouble(); work1 = 2.0 * ranval - 1.0; ranval = rand.nextDouble(); work2 = 2.0 * ranval - 1.0; work3 = work1 * work1 + work2 * work2; } // was dlog() !!! work3 = Math.pow((-2.0 * Math.log(work3)) / work3, 0.5); // natural log // pick one of two deviates at random (don't worry about trying to use both): ranval = rand.nextDouble(); if (ranval < 0.5) { zvalue = work1 * work3; } else { zvalue = work2 * work3; } // ------------ done standard normal random variate generation ----------------- // calculate new decision variable value: new_value = x_cur + zvalue * r * x_range; // check new value is within DV bounds. If not, bounds are reflecting. if (new_value < x_min) { new_value = x_min + (x_min - new_value); if (new_value > x_max) { // if reflection goes past x_max { value should be x_min since // without reflection the approach goes way past lower bound. // This keeps x close to lower bound when x_cur is close to lower bound // Practically speaking, this should never happen with r values <0.3 new_value = x_min; } } else if (new_value > x_max) { new_value = x_max - (new_value - x_max); if (new_value < x_min) { // if reflection goes past x_min { value should be x_max for same reasons as above new_value = x_max; } } return new_value; }
[ "private", "double", "neigh_value", "(", "double", "x_cur", ",", "double", "x_min", ",", "double", "x_max", ",", "double", "r", ")", "{", "double", "ranval", ",", "zvalue", ",", "new_value", ";", "double", "work3", ",", "work2", "=", "0", ",", "work1", "=", "0", ";", "double", "x_range", "=", "x_max", "-", "x_min", ";", "// ------------ generate a standard normal random variate (zvalue) -------------------", "// perturb current value with normal random variable", "//\tCALL DRNNOA(1,zvalue) // generates a standard normal random deviate", "// ISML Stat Library 2 routine - Acceptance/rejection", "//\tBelow returns a standard Gaussian random number based upon Numerical recipes gasdev and", "//\tMarsagalia-Bray Algorithm", "work3", "=", "2.0", ";", "while", "(", "work3", ">=", "1.0", "||", "work3", "==", "0.0", ")", "{", "ranval", "=", "rand", ".", "nextDouble", "(", ")", ";", "work1", "=", "2.0", "*", "ranval", "-", "1.0", ";", "ranval", "=", "rand", ".", "nextDouble", "(", ")", ";", "work2", "=", "2.0", "*", "ranval", "-", "1.0", ";", "work3", "=", "work1", "*", "work1", "+", "work2", "*", "work2", ";", "}", "// was dlog() !!!", "work3", "=", "Math", ".", "pow", "(", "(", "-", "2.0", "*", "Math", ".", "log", "(", "work3", ")", ")", "/", "work3", ",", "0.5", ")", ";", "// natural log", "// pick one of two deviates at random (don't worry about trying to use both):", "ranval", "=", "rand", ".", "nextDouble", "(", ")", ";", "if", "(", "ranval", "<", "0.5", ")", "{", "zvalue", "=", "work1", "*", "work3", ";", "}", "else", "{", "zvalue", "=", "work2", "*", "work3", ";", "}", "// ------------ done standard normal random variate generation -----------------", "// calculate new decision variable value:", "new_value", "=", "x_cur", "+", "zvalue", "*", "r", "*", "x_range", ";", "// check new value is within DV bounds. If not, bounds are reflecting.", "if", "(", "new_value", "<", "x_min", ")", "{", "new_value", "=", "x_min", "+", "(", "x_min", "-", "new_value", ")", ";", "if", "(", "new_value", ">", "x_max", ")", "{", "// if reflection goes past x_max { value should be x_min since", "// without reflection the approach goes way past lower bound.", "// This keeps x close to lower bound when x_cur is close to lower bound", "// Practically speaking, this should never happen with r values <0.3", "new_value", "=", "x_min", ";", "}", "}", "else", "if", "(", "new_value", ">", "x_max", ")", "{", "new_value", "=", "x_max", "-", "(", "new_value", "-", "x_max", ")", ";", "if", "(", "new_value", "<", "x_min", ")", "{", "// if reflection goes past x_min { value should be x_max for same reasons as above", "new_value", "=", "x_max", ";", "}", "}", "return", "new_value", ";", "}" ]
Purpose is to generate a neighboring decision variable value for a single decision variable value being perturbed by the DDS optimization algorithm. New DV value respects the upper and lower DV bounds. Coded by Bryan Tolson, Nov 2005. I/O variable definitions: x_cur - current decision variable (DV) value x_min - min DV value x_max - max DV value r - the neighborhood perturbation factor new_value - new DV variable value (within specified min and max)
[ "Purpose", "is", "to", "generate", "a", "neighboring", "decision", "variable", "value", "for", "a", "single", "decision", "variable", "value", "being", "perturbed", "by", "the", "DDS", "optimization", "algorithm", ".", "New", "DV", "value", "respects", "the", "upper", "and", "lower", "DV", "bounds", ".", "Coded", "by", "Bryan", "Tolson", "Nov", "2005", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/oms3/ngmf/util/cosu/DDS.java#L144-L201
137,743
TheHortonMachine/hortonmachine
hmachine/src/main/java/org/hortonmachine/hmachine/modules/hydrogeomorphology/hillshade/OmsHillshade.java
OmsHillshade.calchillshade
private void calchillshade( WritableRaster pitWR, WritableRaster hillshadeWR, WritableRaster gradientWR, double dx ) { pAzimuth = Math.toRadians(pAzimuth); pElev = Math.toRadians(pElev); double[] sunVector = calcSunVector(); double[] normalSunVector = calcNormalSunVector(sunVector); double[] inverseSunVector = calcInverseSunVector(sunVector); int rows = pitWR.getHeight(); int cols = pitWR.getWidth(); WritableRaster sOmbraWR = calculateFactor(rows, cols, sunVector, inverseSunVector, normalSunVector, pitWR, dx); pm.beginTask(msg.message("hillshade.calculating"), rows * cols); for( int j = 1; j < rows - 1; j++ ) { for( int i = 1; i < cols - 1; i++ ) { double[] ng = gradientWR.getPixel(i, j, new double[3]); double cosinc = scalarProduct(sunVector, ng); if (cosinc < 0) { sOmbraWR.setSample(i, j, 0, 0); } hillshadeWR.setSample(i, j, 0, (int) (212.5 * (cosinc * sOmbraWR.getSample(i, j, 0) + pMinDiffuse))); pm.worked(1); } } pm.done(); }
java
private void calchillshade( WritableRaster pitWR, WritableRaster hillshadeWR, WritableRaster gradientWR, double dx ) { pAzimuth = Math.toRadians(pAzimuth); pElev = Math.toRadians(pElev); double[] sunVector = calcSunVector(); double[] normalSunVector = calcNormalSunVector(sunVector); double[] inverseSunVector = calcInverseSunVector(sunVector); int rows = pitWR.getHeight(); int cols = pitWR.getWidth(); WritableRaster sOmbraWR = calculateFactor(rows, cols, sunVector, inverseSunVector, normalSunVector, pitWR, dx); pm.beginTask(msg.message("hillshade.calculating"), rows * cols); for( int j = 1; j < rows - 1; j++ ) { for( int i = 1; i < cols - 1; i++ ) { double[] ng = gradientWR.getPixel(i, j, new double[3]); double cosinc = scalarProduct(sunVector, ng); if (cosinc < 0) { sOmbraWR.setSample(i, j, 0, 0); } hillshadeWR.setSample(i, j, 0, (int) (212.5 * (cosinc * sOmbraWR.getSample(i, j, 0) + pMinDiffuse))); pm.worked(1); } } pm.done(); }
[ "private", "void", "calchillshade", "(", "WritableRaster", "pitWR", ",", "WritableRaster", "hillshadeWR", ",", "WritableRaster", "gradientWR", ",", "double", "dx", ")", "{", "pAzimuth", "=", "Math", ".", "toRadians", "(", "pAzimuth", ")", ";", "pElev", "=", "Math", ".", "toRadians", "(", "pElev", ")", ";", "double", "[", "]", "sunVector", "=", "calcSunVector", "(", ")", ";", "double", "[", "]", "normalSunVector", "=", "calcNormalSunVector", "(", "sunVector", ")", ";", "double", "[", "]", "inverseSunVector", "=", "calcInverseSunVector", "(", "sunVector", ")", ";", "int", "rows", "=", "pitWR", ".", "getHeight", "(", ")", ";", "int", "cols", "=", "pitWR", ".", "getWidth", "(", ")", ";", "WritableRaster", "sOmbraWR", "=", "calculateFactor", "(", "rows", ",", "cols", ",", "sunVector", ",", "inverseSunVector", ",", "normalSunVector", ",", "pitWR", ",", "dx", ")", ";", "pm", ".", "beginTask", "(", "msg", ".", "message", "(", "\"hillshade.calculating\"", ")", ",", "rows", "*", "cols", ")", ";", "for", "(", "int", "j", "=", "1", ";", "j", "<", "rows", "-", "1", ";", "j", "++", ")", "{", "for", "(", "int", "i", "=", "1", ";", "i", "<", "cols", "-", "1", ";", "i", "++", ")", "{", "double", "[", "]", "ng", "=", "gradientWR", ".", "getPixel", "(", "i", ",", "j", ",", "new", "double", "[", "3", "]", ")", ";", "double", "cosinc", "=", "scalarProduct", "(", "sunVector", ",", "ng", ")", ";", "if", "(", "cosinc", "<", "0", ")", "{", "sOmbraWR", ".", "setSample", "(", "i", ",", "j", ",", "0", ",", "0", ")", ";", "}", "hillshadeWR", ".", "setSample", "(", "i", ",", "j", ",", "0", ",", "(", "int", ")", "(", "212.5", "*", "(", "cosinc", "*", "sOmbraWR", ".", "getSample", "(", "i", ",", "j", ",", "0", ")", "+", "pMinDiffuse", ")", ")", ")", ";", "pm", ".", "worked", "(", "1", ")", ";", "}", "}", "pm", ".", "done", "(", ")", ";", "}" ]
Evaluate the hillshade. @param pitWR the raster of elevation. @param hillshadeWR the WR where store the result. @param gradientWR the raster of the gradient value of the dem. @param dx the resolution of the dem. .
[ "Evaluate", "the", "hillshade", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/hmachine/src/main/java/org/hortonmachine/hmachine/modules/hydrogeomorphology/hillshade/OmsHillshade.java#L169-L194
137,744
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/utils/coverage/ProfilePoint.java
ProfilePoint.getMeanSlope
public static double getMeanSlope( List<ProfilePoint> points ) { double meanSlope = 0; int num = 0; for( int i = 0; i < points.size() - 1; i++ ) { ProfilePoint p1 = points.get(i); ProfilePoint p2 = points.get(i + 1); double dx = p2.progressive - p1.progressive; double dy = p2.elevation - p1.elevation; double tmpSlope = dy / dx; meanSlope = meanSlope + tmpSlope; num++; } meanSlope = meanSlope / num; return meanSlope; }
java
public static double getMeanSlope( List<ProfilePoint> points ) { double meanSlope = 0; int num = 0; for( int i = 0; i < points.size() - 1; i++ ) { ProfilePoint p1 = points.get(i); ProfilePoint p2 = points.get(i + 1); double dx = p2.progressive - p1.progressive; double dy = p2.elevation - p1.elevation; double tmpSlope = dy / dx; meanSlope = meanSlope + tmpSlope; num++; } meanSlope = meanSlope / num; return meanSlope; }
[ "public", "static", "double", "getMeanSlope", "(", "List", "<", "ProfilePoint", ">", "points", ")", "{", "double", "meanSlope", "=", "0", ";", "int", "num", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "points", ".", "size", "(", ")", "-", "1", ";", "i", "++", ")", "{", "ProfilePoint", "p1", "=", "points", ".", "get", "(", "i", ")", ";", "ProfilePoint", "p2", "=", "points", ".", "get", "(", "i", "+", "1", ")", ";", "double", "dx", "=", "p2", ".", "progressive", "-", "p1", ".", "progressive", ";", "double", "dy", "=", "p2", ".", "elevation", "-", "p1", ".", "elevation", ";", "double", "tmpSlope", "=", "dy", "/", "dx", ";", "meanSlope", "=", "meanSlope", "+", "tmpSlope", ";", "num", "++", ";", "}", "meanSlope", "=", "meanSlope", "/", "num", ";", "return", "meanSlope", ";", "}" ]
Calculates the mean slope of a given set of profilepoints. @param points the points of the profile. @return the mean slope.
[ "Calculates", "the", "mean", "slope", "of", "a", "given", "set", "of", "profilepoints", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/coverage/ProfilePoint.java#L82-L98
137,745
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/utils/coverage/ProfilePoint.java
ProfilePoint.getLastVisiblePointData
public static double[] getLastVisiblePointData( List<ProfilePoint> profile ) { if (profile.size() < 2) { throw new IllegalArgumentException("A profile needs to have at least 2 points."); } ProfilePoint first = profile.get(0); double baseElev = first.getElevation(); Coordinate baseCoord = new Coordinate(0, 0); double minAzimuthAngle = Double.POSITIVE_INFINITY; double maxAzimuthAngle = Double.NEGATIVE_INFINITY; ProfilePoint minAzimuthPoint = null; ProfilePoint maxAzimuthPoint = null; for( int i = 1; i < profile.size(); i++ ) { ProfilePoint currentPoint = profile.get(i); double currentElev = currentPoint.getElevation(); if (HMConstants.isNovalue(currentElev)) { continue; } currentElev = currentElev - baseElev; double currentProg = currentPoint.getProgressive(); Coordinate currentCoord = new Coordinate(currentProg, currentElev); double azimuth = GeometryUtilities.azimuth(baseCoord, currentCoord); if (azimuth <= minAzimuthAngle) { minAzimuthAngle = azimuth; minAzimuthPoint = currentPoint; } if (azimuth >= maxAzimuthAngle) { maxAzimuthAngle = azimuth; maxAzimuthPoint = currentPoint; } } if (minAzimuthPoint == null || maxAzimuthPoint == null) { return null; } return new double[]{// /* */minAzimuthPoint.elevation, // minAzimuthPoint.position.x, // minAzimuthPoint.position.y, // minAzimuthPoint.progressive, // minAzimuthAngle, // maxAzimuthPoint.elevation, // maxAzimuthPoint.position.x, // maxAzimuthPoint.position.y, // maxAzimuthPoint.progressive, // maxAzimuthAngle, // }; }
java
public static double[] getLastVisiblePointData( List<ProfilePoint> profile ) { if (profile.size() < 2) { throw new IllegalArgumentException("A profile needs to have at least 2 points."); } ProfilePoint first = profile.get(0); double baseElev = first.getElevation(); Coordinate baseCoord = new Coordinate(0, 0); double minAzimuthAngle = Double.POSITIVE_INFINITY; double maxAzimuthAngle = Double.NEGATIVE_INFINITY; ProfilePoint minAzimuthPoint = null; ProfilePoint maxAzimuthPoint = null; for( int i = 1; i < profile.size(); i++ ) { ProfilePoint currentPoint = profile.get(i); double currentElev = currentPoint.getElevation(); if (HMConstants.isNovalue(currentElev)) { continue; } currentElev = currentElev - baseElev; double currentProg = currentPoint.getProgressive(); Coordinate currentCoord = new Coordinate(currentProg, currentElev); double azimuth = GeometryUtilities.azimuth(baseCoord, currentCoord); if (azimuth <= minAzimuthAngle) { minAzimuthAngle = azimuth; minAzimuthPoint = currentPoint; } if (azimuth >= maxAzimuthAngle) { maxAzimuthAngle = azimuth; maxAzimuthPoint = currentPoint; } } if (minAzimuthPoint == null || maxAzimuthPoint == null) { return null; } return new double[]{// /* */minAzimuthPoint.elevation, // minAzimuthPoint.position.x, // minAzimuthPoint.position.y, // minAzimuthPoint.progressive, // minAzimuthAngle, // maxAzimuthPoint.elevation, // maxAzimuthPoint.position.x, // maxAzimuthPoint.position.y, // maxAzimuthPoint.progressive, // maxAzimuthAngle, // }; }
[ "public", "static", "double", "[", "]", "getLastVisiblePointData", "(", "List", "<", "ProfilePoint", ">", "profile", ")", "{", "if", "(", "profile", ".", "size", "(", ")", "<", "2", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"A profile needs to have at least 2 points.\"", ")", ";", "}", "ProfilePoint", "first", "=", "profile", ".", "get", "(", "0", ")", ";", "double", "baseElev", "=", "first", ".", "getElevation", "(", ")", ";", "Coordinate", "baseCoord", "=", "new", "Coordinate", "(", "0", ",", "0", ")", ";", "double", "minAzimuthAngle", "=", "Double", ".", "POSITIVE_INFINITY", ";", "double", "maxAzimuthAngle", "=", "Double", ".", "NEGATIVE_INFINITY", ";", "ProfilePoint", "minAzimuthPoint", "=", "null", ";", "ProfilePoint", "maxAzimuthPoint", "=", "null", ";", "for", "(", "int", "i", "=", "1", ";", "i", "<", "profile", ".", "size", "(", ")", ";", "i", "++", ")", "{", "ProfilePoint", "currentPoint", "=", "profile", ".", "get", "(", "i", ")", ";", "double", "currentElev", "=", "currentPoint", ".", "getElevation", "(", ")", ";", "if", "(", "HMConstants", ".", "isNovalue", "(", "currentElev", ")", ")", "{", "continue", ";", "}", "currentElev", "=", "currentElev", "-", "baseElev", ";", "double", "currentProg", "=", "currentPoint", ".", "getProgressive", "(", ")", ";", "Coordinate", "currentCoord", "=", "new", "Coordinate", "(", "currentProg", ",", "currentElev", ")", ";", "double", "azimuth", "=", "GeometryUtilities", ".", "azimuth", "(", "baseCoord", ",", "currentCoord", ")", ";", "if", "(", "azimuth", "<=", "minAzimuthAngle", ")", "{", "minAzimuthAngle", "=", "azimuth", ";", "minAzimuthPoint", "=", "currentPoint", ";", "}", "if", "(", "azimuth", ">=", "maxAzimuthAngle", ")", "{", "maxAzimuthAngle", "=", "azimuth", ";", "maxAzimuthPoint", "=", "currentPoint", ";", "}", "}", "if", "(", "minAzimuthPoint", "==", "null", "||", "maxAzimuthPoint", "==", "null", ")", "{", "return", "null", ";", "}", "return", "new", "double", "[", "]", "{", "//", "/* */", "minAzimuthPoint", ".", "elevation", ",", "//", "minAzimuthPoint", ".", "position", ".", "x", ",", "//", "minAzimuthPoint", ".", "position", ".", "y", ",", "//", "minAzimuthPoint", ".", "progressive", ",", "//", "minAzimuthAngle", ",", "//", "maxAzimuthPoint", ".", "elevation", ",", "//", "maxAzimuthPoint", ".", "position", ".", "x", ",", "//", "maxAzimuthPoint", ".", "position", ".", "y", ",", "//", "maxAzimuthPoint", ".", "progressive", ",", "//", "maxAzimuthAngle", ",", "//", "}", ";", "}" ]
Return last visible point data for a profile points list. <p>For the profile the min and max angles of "sight" are calculated. The min azimuth angle represents the "upper" line of sight, as thoght from the zenith. <p>The max azimuth angle represents the "below the earth" line of sight (think of a viewer looking in direction nadir). <p>The return values are in an array of doubles containing: <ul> <li>[0] min point elev, </li> <li>[1] min point x, </li> <li>[2] min point y, </li> <li>[3] min point progressive, </li> <li>[4] min point azimuth, </li> <li>[5] max point elev, </li> <li>[6] max point x, </li> <li>[7] max point y, </li> <li>[8] max point progressive, </li> <li>[9] max point azimuth </li> </ul> @param profile the profile to analize. @return the last visible point parameters.
[ "Return", "last", "visible", "point", "data", "for", "a", "profile", "points", "list", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/coverage/ProfilePoint.java#L125-L175
137,746
enasequence/sequencetools
src/main/java/uk/ac/ebi/embl/api/validation/check/sourcefeature/SourceFeatureQualifierCheck.java
SourceFeatureQualifierCheck.checkMetagenomeSource
private void checkMetagenomeSource(Origin origin, SourceFeature source) { List<Qualifier> metagenomeSourceQual = source.getQualifiers(Qualifier.METAGENOME_SOURCE_QUALIFIER_NAME); if(metagenomeSourceQual != null && !metagenomeSourceQual.isEmpty()) { Qualifier envSample = source.getSingleQualifier(Qualifier.ENVIRONMENTAL_SAMPLE_QUALIFIER_NAME); if(envSample == null) { reportError(origin, ENV_SAMPLE_REQUIRED); } if(metagenomeSourceQual.size() > 1) { reportError(origin, MORE_THAN_ONE_METAGENOME_SOURCE); } String metegenomeSource = metagenomeSourceQual.get(0).getValue(); if(metegenomeSource == null || (!metegenomeSource.contains("metagenome") && metegenomeSource.contains("Metagenome"))) { reportError(origin, INVALID_METAGENOME_SOURCE, metegenomeSource); } List<Taxon> taxon = getEmblEntryValidationPlanProperty().taxonHelper.get().getTaxonsByScientificName(metegenomeSource); if(taxon == null || taxon.isEmpty() || taxon.get(0).getTaxId() == 408169L || !getEmblEntryValidationPlanProperty().taxonHelper.get().isOrganismMetagenome(metegenomeSource)) { reportError(origin, INVALID_METAGENOME_SOURCE, metegenomeSource); } } }
java
private void checkMetagenomeSource(Origin origin, SourceFeature source) { List<Qualifier> metagenomeSourceQual = source.getQualifiers(Qualifier.METAGENOME_SOURCE_QUALIFIER_NAME); if(metagenomeSourceQual != null && !metagenomeSourceQual.isEmpty()) { Qualifier envSample = source.getSingleQualifier(Qualifier.ENVIRONMENTAL_SAMPLE_QUALIFIER_NAME); if(envSample == null) { reportError(origin, ENV_SAMPLE_REQUIRED); } if(metagenomeSourceQual.size() > 1) { reportError(origin, MORE_THAN_ONE_METAGENOME_SOURCE); } String metegenomeSource = metagenomeSourceQual.get(0).getValue(); if(metegenomeSource == null || (!metegenomeSource.contains("metagenome") && metegenomeSource.contains("Metagenome"))) { reportError(origin, INVALID_METAGENOME_SOURCE, metegenomeSource); } List<Taxon> taxon = getEmblEntryValidationPlanProperty().taxonHelper.get().getTaxonsByScientificName(metegenomeSource); if(taxon == null || taxon.isEmpty() || taxon.get(0).getTaxId() == 408169L || !getEmblEntryValidationPlanProperty().taxonHelper.get().isOrganismMetagenome(metegenomeSource)) { reportError(origin, INVALID_METAGENOME_SOURCE, metegenomeSource); } } }
[ "private", "void", "checkMetagenomeSource", "(", "Origin", "origin", ",", "SourceFeature", "source", ")", "{", "List", "<", "Qualifier", ">", "metagenomeSourceQual", "=", "source", ".", "getQualifiers", "(", "Qualifier", ".", "METAGENOME_SOURCE_QUALIFIER_NAME", ")", ";", "if", "(", "metagenomeSourceQual", "!=", "null", "&&", "!", "metagenomeSourceQual", ".", "isEmpty", "(", ")", ")", "{", "Qualifier", "envSample", "=", "source", ".", "getSingleQualifier", "(", "Qualifier", ".", "ENVIRONMENTAL_SAMPLE_QUALIFIER_NAME", ")", ";", "if", "(", "envSample", "==", "null", ")", "{", "reportError", "(", "origin", ",", "ENV_SAMPLE_REQUIRED", ")", ";", "}", "if", "(", "metagenomeSourceQual", ".", "size", "(", ")", ">", "1", ")", "{", "reportError", "(", "origin", ",", "MORE_THAN_ONE_METAGENOME_SOURCE", ")", ";", "}", "String", "metegenomeSource", "=", "metagenomeSourceQual", ".", "get", "(", "0", ")", ".", "getValue", "(", ")", ";", "if", "(", "metegenomeSource", "==", "null", "||", "(", "!", "metegenomeSource", ".", "contains", "(", "\"metagenome\"", ")", "&&", "metegenomeSource", ".", "contains", "(", "\"Metagenome\"", ")", ")", ")", "{", "reportError", "(", "origin", ",", "INVALID_METAGENOME_SOURCE", ",", "metegenomeSource", ")", ";", "}", "List", "<", "Taxon", ">", "taxon", "=", "getEmblEntryValidationPlanProperty", "(", ")", ".", "taxonHelper", ".", "get", "(", ")", ".", "getTaxonsByScientificName", "(", "metegenomeSource", ")", ";", "if", "(", "taxon", "==", "null", "||", "taxon", ".", "isEmpty", "(", ")", "||", "taxon", ".", "get", "(", "0", ")", ".", "getTaxId", "(", ")", "==", "408169L", "||", "!", "getEmblEntryValidationPlanProperty", "(", ")", ".", "taxonHelper", ".", "get", "(", ")", ".", "isOrganismMetagenome", "(", "metegenomeSource", ")", ")", "{", "reportError", "(", "origin", ",", "INVALID_METAGENOME_SOURCE", ",", "metegenomeSource", ")", ";", "}", "}", "}" ]
ENA-2825
[ "ENA", "-", "2825" ]
4127f5e1a17540239f5810136153fbd6737fa262
https://github.com/enasequence/sequencetools/blob/4127f5e1a17540239f5810136153fbd6737fa262/src/main/java/uk/ac/ebi/embl/api/validation/check/sourcefeature/SourceFeatureQualifierCheck.java#L146-L169
137,747
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/utils/images/ImageGenerator.java
ImageGenerator.addFeaturePath
public void addFeaturePath( String featurePath, String filter ) { if (!featurePaths.contains(featurePath)) { featurePaths.add(featurePath); if (filter == null) { filter = ""; } featureFilter.add(filter); } }
java
public void addFeaturePath( String featurePath, String filter ) { if (!featurePaths.contains(featurePath)) { featurePaths.add(featurePath); if (filter == null) { filter = ""; } featureFilter.add(filter); } }
[ "public", "void", "addFeaturePath", "(", "String", "featurePath", ",", "String", "filter", ")", "{", "if", "(", "!", "featurePaths", ".", "contains", "(", "featurePath", ")", ")", "{", "featurePaths", ".", "add", "(", "featurePath", ")", ";", "if", "(", "filter", "==", "null", ")", "{", "filter", "=", "\"\"", ";", "}", "featureFilter", ".", "add", "(", "filter", ")", ";", "}", "}" ]
Add a new feature file path. <p>The order will be considered. First paths are drawn first.</p> @param featurePath the path to add.
[ "Add", "a", "new", "feature", "file", "path", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/images/ImageGenerator.java#L184-L192
137,748
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/utils/images/ImageGenerator.java
ImageGenerator.drawImageWithNewMapContent
public BufferedImage drawImageWithNewMapContent( ReferencedEnvelope ref, int imageWidth, int imageHeight, double buffer ) { MapContent content = new MapContent(); content.setTitle("dump"); if (forceCrs != null) { content.getViewport().setCoordinateReferenceSystem(forceCrs); content.getViewport().setBounds(ref); } synchronized (synchronizedLayers) { for( Layer layer : synchronizedLayers ) { content.addLayer(layer); } } StreamingRenderer renderer = new StreamingRenderer(); renderer.setMapContent(content); if (buffer > 0.0) { ref = new ReferencedEnvelope(ref); ref.expandBy(buffer, buffer); } double envW = ref.getWidth(); double envH = ref.getHeight(); if (envW < envH) { double newEnvW = envH * (double) imageWidth / (double) imageHeight; double delta = newEnvW - envW; ref.expandBy(delta / 2, 0); } else { double newEnvH = envW * (double) imageHeight / (double) imageWidth; double delta = newEnvH - envH; ref.expandBy(0, delta / 2.0); } Rectangle imageBounds = new Rectangle(0, 0, imageWidth, imageHeight); BufferedImage dumpImage = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = dumpImage.createGraphics(); g2d.fillRect(0, 0, imageWidth, imageHeight); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); renderer.paint(g2d, imageBounds, ref); return dumpImage; }
java
public BufferedImage drawImageWithNewMapContent( ReferencedEnvelope ref, int imageWidth, int imageHeight, double buffer ) { MapContent content = new MapContent(); content.setTitle("dump"); if (forceCrs != null) { content.getViewport().setCoordinateReferenceSystem(forceCrs); content.getViewport().setBounds(ref); } synchronized (synchronizedLayers) { for( Layer layer : synchronizedLayers ) { content.addLayer(layer); } } StreamingRenderer renderer = new StreamingRenderer(); renderer.setMapContent(content); if (buffer > 0.0) { ref = new ReferencedEnvelope(ref); ref.expandBy(buffer, buffer); } double envW = ref.getWidth(); double envH = ref.getHeight(); if (envW < envH) { double newEnvW = envH * (double) imageWidth / (double) imageHeight; double delta = newEnvW - envW; ref.expandBy(delta / 2, 0); } else { double newEnvH = envW * (double) imageHeight / (double) imageWidth; double delta = newEnvH - envH; ref.expandBy(0, delta / 2.0); } Rectangle imageBounds = new Rectangle(0, 0, imageWidth, imageHeight); BufferedImage dumpImage = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = dumpImage.createGraphics(); g2d.fillRect(0, 0, imageWidth, imageHeight); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); renderer.paint(g2d, imageBounds, ref); return dumpImage; }
[ "public", "BufferedImage", "drawImageWithNewMapContent", "(", "ReferencedEnvelope", "ref", ",", "int", "imageWidth", ",", "int", "imageHeight", ",", "double", "buffer", ")", "{", "MapContent", "content", "=", "new", "MapContent", "(", ")", ";", "content", ".", "setTitle", "(", "\"dump\"", ")", ";", "if", "(", "forceCrs", "!=", "null", ")", "{", "content", ".", "getViewport", "(", ")", ".", "setCoordinateReferenceSystem", "(", "forceCrs", ")", ";", "content", ".", "getViewport", "(", ")", ".", "setBounds", "(", "ref", ")", ";", "}", "synchronized", "(", "synchronizedLayers", ")", "{", "for", "(", "Layer", "layer", ":", "synchronizedLayers", ")", "{", "content", ".", "addLayer", "(", "layer", ")", ";", "}", "}", "StreamingRenderer", "renderer", "=", "new", "StreamingRenderer", "(", ")", ";", "renderer", ".", "setMapContent", "(", "content", ")", ";", "if", "(", "buffer", ">", "0.0", ")", "{", "ref", "=", "new", "ReferencedEnvelope", "(", "ref", ")", ";", "ref", ".", "expandBy", "(", "buffer", ",", "buffer", ")", ";", "}", "double", "envW", "=", "ref", ".", "getWidth", "(", ")", ";", "double", "envH", "=", "ref", ".", "getHeight", "(", ")", ";", "if", "(", "envW", "<", "envH", ")", "{", "double", "newEnvW", "=", "envH", "*", "(", "double", ")", "imageWidth", "/", "(", "double", ")", "imageHeight", ";", "double", "delta", "=", "newEnvW", "-", "envW", ";", "ref", ".", "expandBy", "(", "delta", "/", "2", ",", "0", ")", ";", "}", "else", "{", "double", "newEnvH", "=", "envW", "*", "(", "double", ")", "imageHeight", "/", "(", "double", ")", "imageWidth", ";", "double", "delta", "=", "newEnvH", "-", "envH", ";", "ref", ".", "expandBy", "(", "0", ",", "delta", "/", "2.0", ")", ";", "}", "Rectangle", "imageBounds", "=", "new", "Rectangle", "(", "0", ",", "0", ",", "imageWidth", ",", "imageHeight", ")", ";", "BufferedImage", "dumpImage", "=", "new", "BufferedImage", "(", "imageWidth", ",", "imageHeight", ",", "BufferedImage", ".", "TYPE_INT_RGB", ")", ";", "Graphics2D", "g2d", "=", "dumpImage", ".", "createGraphics", "(", ")", ";", "g2d", ".", "fillRect", "(", "0", ",", "0", ",", "imageWidth", ",", "imageHeight", ")", ";", "g2d", ".", "setRenderingHint", "(", "RenderingHints", ".", "KEY_ANTIALIASING", ",", "RenderingHints", ".", "VALUE_ANTIALIAS_ON", ")", ";", "renderer", ".", "paint", "(", "g2d", ",", "imageBounds", ",", "ref", ")", ";", "return", "dumpImage", ";", "}" ]
Draw the map on an image creating a new MapContent. @param bounds the area of interest. @param imageWidth the width of the image to produce. @param imageHeight the height of the image to produce. @param buffer the buffer to add around the map bounds in map units. @return the image.
[ "Draw", "the", "map", "on", "an", "image", "creating", "a", "new", "MapContent", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/images/ImageGenerator.java#L512-L557
137,749
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/utils/images/ImageGenerator.java
ImageGenerator.dumpPngImage
public void dumpPngImage( String imagePath, ReferencedEnvelope bounds, int imageWidth, int imageHeight, double buffer, int[] rgbCheck ) throws IOException { BufferedImage dumpImage = drawImageWithNewMapContent(bounds, imageWidth, imageHeight, buffer); boolean dumpIt = true; if (rgbCheck != null) dumpIt = !isAllOfCheckColor(rgbCheck, dumpImage); if (dumpIt) ImageIO.write(dumpImage, "png", new File(imagePath)); //$NON-NLS-1$ }
java
public void dumpPngImage( String imagePath, ReferencedEnvelope bounds, int imageWidth, int imageHeight, double buffer, int[] rgbCheck ) throws IOException { BufferedImage dumpImage = drawImageWithNewMapContent(bounds, imageWidth, imageHeight, buffer); boolean dumpIt = true; if (rgbCheck != null) dumpIt = !isAllOfCheckColor(rgbCheck, dumpImage); if (dumpIt) ImageIO.write(dumpImage, "png", new File(imagePath)); //$NON-NLS-1$ }
[ "public", "void", "dumpPngImage", "(", "String", "imagePath", ",", "ReferencedEnvelope", "bounds", ",", "int", "imageWidth", ",", "int", "imageHeight", ",", "double", "buffer", ",", "int", "[", "]", "rgbCheck", ")", "throws", "IOException", "{", "BufferedImage", "dumpImage", "=", "drawImageWithNewMapContent", "(", "bounds", ",", "imageWidth", ",", "imageHeight", ",", "buffer", ")", ";", "boolean", "dumpIt", "=", "true", ";", "if", "(", "rgbCheck", "!=", "null", ")", "dumpIt", "=", "!", "isAllOfCheckColor", "(", "rgbCheck", ",", "dumpImage", ")", ";", "if", "(", "dumpIt", ")", "ImageIO", ".", "write", "(", "dumpImage", ",", "\"png\"", ",", "new", "File", "(", "imagePath", ")", ")", ";", "//$NON-NLS-1$", "}" ]
Writes an image of maps drawn to a png file. @param imagePath the path to which to write the image. @param bounds the area of interest. @param imageWidth the width of the image to produce. @param imageHeight the height of the image to produce. @param buffer the buffer to add around the map bounds in map units. @param rgbCheck an rgb tripled. If not <code>null</code> and the image generated is composed only of that color, then the tile is not generated. This can be useful to avoid generation of empty tiles. @throws IOException
[ "Writes", "an", "image", "of", "maps", "drawn", "to", "a", "png", "file", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/images/ImageGenerator.java#L577-L585
137,750
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/utils/images/ImageGenerator.java
ImageGenerator.dumpPngImageForScaleAndPaper
public void dumpPngImageForScaleAndPaper( String imagePath, ReferencedEnvelope bounds, double scale, EPaperFormat paperFormat, Double dpi, BufferedImage legend, int legendX, int legendY, String scalePrefix, float scaleSize, int scaleX, int scaleY ) throws Exception { if (dpi == null) { dpi = 72.0; } // we use the bounds top find the center Coordinate centre = bounds.centre(); double boundsXExtension = paperFormat.width() / 1000.0 * scale; double boundsYExtension = paperFormat.height() / 1000.0 * scale; Coordinate ll = new Coordinate(centre.x - boundsXExtension / 2.0, centre.y - boundsYExtension / 2.0); Coordinate ur = new Coordinate(centre.x + boundsXExtension / 2.0, centre.y + boundsYExtension / 2.0); Envelope tmpEnv = new Envelope(ll, ur); bounds = new ReferencedEnvelope(tmpEnv, bounds.getCoordinateReferenceSystem()); int imageWidth = (int) (paperFormat.width() / 25.4 * dpi); int imageHeight = (int) (paperFormat.height() / 25.4 * dpi); BufferedImage dumpImage = drawImage(bounds, imageWidth, imageHeight, 0); Graphics2D graphics = (Graphics2D) dumpImage.getGraphics(); graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); if (shapesFile != null && shapesFile.exists()) { applyShapes(graphics); } if (legend != null) { graphics.drawImage(legend, null, legendX, legendY); } if (scalePrefix != null) { Font scaleFont = graphics.getFont().deriveFont(scaleSize); graphics.setFont(scaleFont); FontMetrics fontMetrics = graphics.getFontMetrics(scaleFont); String scaleString = scalePrefix + "1:" + (int) scale; Rectangle2D stringBounds = fontMetrics.getStringBounds(scaleString, graphics); double width = stringBounds.getWidth(); double height = stringBounds.getHeight(); graphics.setColor(Color.white); double border = 5; graphics.fillRect((int) scaleX, (int) (scaleY - height + 2 * border), (int) (width + 3 * border), (int) (height + 2 * border)); graphics.setColor(Color.black); graphics.drawString(scaleString, (int) scaleX + 5, (int) scaleY); } ImageIO.write(dumpImage, "png", new File(imagePath)); }
java
public void dumpPngImageForScaleAndPaper( String imagePath, ReferencedEnvelope bounds, double scale, EPaperFormat paperFormat, Double dpi, BufferedImage legend, int legendX, int legendY, String scalePrefix, float scaleSize, int scaleX, int scaleY ) throws Exception { if (dpi == null) { dpi = 72.0; } // we use the bounds top find the center Coordinate centre = bounds.centre(); double boundsXExtension = paperFormat.width() / 1000.0 * scale; double boundsYExtension = paperFormat.height() / 1000.0 * scale; Coordinate ll = new Coordinate(centre.x - boundsXExtension / 2.0, centre.y - boundsYExtension / 2.0); Coordinate ur = new Coordinate(centre.x + boundsXExtension / 2.0, centre.y + boundsYExtension / 2.0); Envelope tmpEnv = new Envelope(ll, ur); bounds = new ReferencedEnvelope(tmpEnv, bounds.getCoordinateReferenceSystem()); int imageWidth = (int) (paperFormat.width() / 25.4 * dpi); int imageHeight = (int) (paperFormat.height() / 25.4 * dpi); BufferedImage dumpImage = drawImage(bounds, imageWidth, imageHeight, 0); Graphics2D graphics = (Graphics2D) dumpImage.getGraphics(); graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); if (shapesFile != null && shapesFile.exists()) { applyShapes(graphics); } if (legend != null) { graphics.drawImage(legend, null, legendX, legendY); } if (scalePrefix != null) { Font scaleFont = graphics.getFont().deriveFont(scaleSize); graphics.setFont(scaleFont); FontMetrics fontMetrics = graphics.getFontMetrics(scaleFont); String scaleString = scalePrefix + "1:" + (int) scale; Rectangle2D stringBounds = fontMetrics.getStringBounds(scaleString, graphics); double width = stringBounds.getWidth(); double height = stringBounds.getHeight(); graphics.setColor(Color.white); double border = 5; graphics.fillRect((int) scaleX, (int) (scaleY - height + 2 * border), (int) (width + 3 * border), (int) (height + 2 * border)); graphics.setColor(Color.black); graphics.drawString(scaleString, (int) scaleX + 5, (int) scaleY); } ImageIO.write(dumpImage, "png", new File(imagePath)); }
[ "public", "void", "dumpPngImageForScaleAndPaper", "(", "String", "imagePath", ",", "ReferencedEnvelope", "bounds", ",", "double", "scale", ",", "EPaperFormat", "paperFormat", ",", "Double", "dpi", ",", "BufferedImage", "legend", ",", "int", "legendX", ",", "int", "legendY", ",", "String", "scalePrefix", ",", "float", "scaleSize", ",", "int", "scaleX", ",", "int", "scaleY", ")", "throws", "Exception", "{", "if", "(", "dpi", "==", "null", ")", "{", "dpi", "=", "72.0", ";", "}", "// we use the bounds top find the center", "Coordinate", "centre", "=", "bounds", ".", "centre", "(", ")", ";", "double", "boundsXExtension", "=", "paperFormat", ".", "width", "(", ")", "/", "1000.0", "*", "scale", ";", "double", "boundsYExtension", "=", "paperFormat", ".", "height", "(", ")", "/", "1000.0", "*", "scale", ";", "Coordinate", "ll", "=", "new", "Coordinate", "(", "centre", ".", "x", "-", "boundsXExtension", "/", "2.0", ",", "centre", ".", "y", "-", "boundsYExtension", "/", "2.0", ")", ";", "Coordinate", "ur", "=", "new", "Coordinate", "(", "centre", ".", "x", "+", "boundsXExtension", "/", "2.0", ",", "centre", ".", "y", "+", "boundsYExtension", "/", "2.0", ")", ";", "Envelope", "tmpEnv", "=", "new", "Envelope", "(", "ll", ",", "ur", ")", ";", "bounds", "=", "new", "ReferencedEnvelope", "(", "tmpEnv", ",", "bounds", ".", "getCoordinateReferenceSystem", "(", ")", ")", ";", "int", "imageWidth", "=", "(", "int", ")", "(", "paperFormat", ".", "width", "(", ")", "/", "25.4", "*", "dpi", ")", ";", "int", "imageHeight", "=", "(", "int", ")", "(", "paperFormat", ".", "height", "(", ")", "/", "25.4", "*", "dpi", ")", ";", "BufferedImage", "dumpImage", "=", "drawImage", "(", "bounds", ",", "imageWidth", ",", "imageHeight", ",", "0", ")", ";", "Graphics2D", "graphics", "=", "(", "Graphics2D", ")", "dumpImage", ".", "getGraphics", "(", ")", ";", "graphics", ".", "setRenderingHint", "(", "RenderingHints", ".", "KEY_ANTIALIASING", ",", "RenderingHints", ".", "VALUE_ANTIALIAS_ON", ")", ";", "if", "(", "shapesFile", "!=", "null", "&&", "shapesFile", ".", "exists", "(", ")", ")", "{", "applyShapes", "(", "graphics", ")", ";", "}", "if", "(", "legend", "!=", "null", ")", "{", "graphics", ".", "drawImage", "(", "legend", ",", "null", ",", "legendX", ",", "legendY", ")", ";", "}", "if", "(", "scalePrefix", "!=", "null", ")", "{", "Font", "scaleFont", "=", "graphics", ".", "getFont", "(", ")", ".", "deriveFont", "(", "scaleSize", ")", ";", "graphics", ".", "setFont", "(", "scaleFont", ")", ";", "FontMetrics", "fontMetrics", "=", "graphics", ".", "getFontMetrics", "(", "scaleFont", ")", ";", "String", "scaleString", "=", "scalePrefix", "+", "\"1:\"", "+", "(", "int", ")", "scale", ";", "Rectangle2D", "stringBounds", "=", "fontMetrics", ".", "getStringBounds", "(", "scaleString", ",", "graphics", ")", ";", "double", "width", "=", "stringBounds", ".", "getWidth", "(", ")", ";", "double", "height", "=", "stringBounds", ".", "getHeight", "(", ")", ";", "graphics", ".", "setColor", "(", "Color", ".", "white", ")", ";", "double", "border", "=", "5", ";", "graphics", ".", "fillRect", "(", "(", "int", ")", "scaleX", ",", "(", "int", ")", "(", "scaleY", "-", "height", "+", "2", "*", "border", ")", ",", "(", "int", ")", "(", "width", "+", "3", "*", "border", ")", ",", "(", "int", ")", "(", "height", "+", "2", "*", "border", ")", ")", ";", "graphics", ".", "setColor", "(", "Color", ".", "black", ")", ";", "graphics", ".", "drawString", "(", "scaleString", ",", "(", "int", ")", "scaleX", "+", "5", ",", "(", "int", ")", "scaleY", ")", ";", "}", "ImageIO", ".", "write", "(", "dumpImage", ",", "\"png\"", ",", "new", "File", "(", "imagePath", ")", ")", ";", "}" ]
Create an image for a given paper size and scale. @param imagePath the path to which to write the image. @param bounds the area of interest. In this case only the center is considered. The bounds are recalculated based in paper size and scale. @param scale the scale wanted for the map. @param paperFormat the paper format to use. @param dpi the wanted dpi. If <code>null</code>, 72dpi is used as default. @param legend an optional legend {@link BufferedImage image}. @param legendX the X position of the legend in the final image. @param legendY the Y position of the legend in the final image. @param scalePrefix if not <code>null</code>, this string will be added before the scale definition. If <code>null</code>, no scale definition will be added. @param scaleSize a size for the scale. @param scaleX the X position of the scale in the final image. @param scaleY the X position of the scale in the final image. @throws Exception @since 0.7.6
[ "Create", "an", "image", "for", "a", "given", "paper", "size", "and", "scale", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/images/ImageGenerator.java#L668-L721
137,751
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/utils/clustering/GvmSpace.java
GvmSpace.distance
public double distance(Object pt1, Object pt2) { Object p = newCopy(pt1); subtract(p, pt2); return magnitude(p); }
java
public double distance(Object pt1, Object pt2) { Object p = newCopy(pt1); subtract(p, pt2); return magnitude(p); }
[ "public", "double", "distance", "(", "Object", "pt1", ",", "Object", "pt2", ")", "{", "Object", "p", "=", "newCopy", "(", "pt1", ")", ";", "subtract", "(", "p", ",", "pt2", ")", ";", "return", "magnitude", "(", "p", ")", ";", "}" ]
not used directly in algorithm, but useful - override for good performance
[ "not", "used", "directly", "in", "algorithm", "but", "useful", "-", "override", "for", "good", "performance" ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/clustering/GvmSpace.java#L24-L28
137,752
TheHortonMachine/hortonmachine
hmachine/src/main/java/org/hortonmachine/hmachine/modules/demmanipulation/pitfiller/OmsDePitter.java
OmsDePitter.makeCellsFlowReady
private void makeCellsFlowReady( int iteration, GridNode pitfillExitNode, List<GridNode> cellsToMakeFlowReady, BitMatrix allPitsPositions, WritableRandomIter pitIter, float delta ) { iteration++; double exitElevation = pitfillExitNode.elevation; List<GridNode> connected = new ArrayList<>(); for( GridNode checkNode : cellsToMakeFlowReady ) { List<GridNode> validSurroundingNodes = checkNode.getValidSurroundingNodes(); for( GridNode gridNode : validSurroundingNodes ) { if (!pitfillExitNode.equals(gridNode) && allPitsPositions.isMarked(gridNode.col, gridNode.row) && gridNode.elevation == exitElevation) { if (!connected.contains(gridNode)) connected.add(gridNode); } } } if (connected.size() == 0) { return; } for( GridNode gridNode : connected ) { double newElev = (double) (gridNode.elevation + delta * (double) iteration); gridNode.setValueInMap(pitIter, newElev); } List<GridNode> updatedConnected = new ArrayList<>(); for( GridNode gridNode : connected ) { GridNode updatedNode = new GridNode(pitIter, gridNode.cols, gridNode.rows, gridNode.xRes, gridNode.yRes, gridNode.col, gridNode.row); updatedConnected.add(updatedNode); } makeCellsFlowReady(iteration, pitfillExitNode, updatedConnected, allPitsPositions, pitIter, delta); }
java
private void makeCellsFlowReady( int iteration, GridNode pitfillExitNode, List<GridNode> cellsToMakeFlowReady, BitMatrix allPitsPositions, WritableRandomIter pitIter, float delta ) { iteration++; double exitElevation = pitfillExitNode.elevation; List<GridNode> connected = new ArrayList<>(); for( GridNode checkNode : cellsToMakeFlowReady ) { List<GridNode> validSurroundingNodes = checkNode.getValidSurroundingNodes(); for( GridNode gridNode : validSurroundingNodes ) { if (!pitfillExitNode.equals(gridNode) && allPitsPositions.isMarked(gridNode.col, gridNode.row) && gridNode.elevation == exitElevation) { if (!connected.contains(gridNode)) connected.add(gridNode); } } } if (connected.size() == 0) { return; } for( GridNode gridNode : connected ) { double newElev = (double) (gridNode.elevation + delta * (double) iteration); gridNode.setValueInMap(pitIter, newElev); } List<GridNode> updatedConnected = new ArrayList<>(); for( GridNode gridNode : connected ) { GridNode updatedNode = new GridNode(pitIter, gridNode.cols, gridNode.rows, gridNode.xRes, gridNode.yRes, gridNode.col, gridNode.row); updatedConnected.add(updatedNode); } makeCellsFlowReady(iteration, pitfillExitNode, updatedConnected, allPitsPositions, pitIter, delta); }
[ "private", "void", "makeCellsFlowReady", "(", "int", "iteration", ",", "GridNode", "pitfillExitNode", ",", "List", "<", "GridNode", ">", "cellsToMakeFlowReady", ",", "BitMatrix", "allPitsPositions", ",", "WritableRandomIter", "pitIter", ",", "float", "delta", ")", "{", "iteration", "++", ";", "double", "exitElevation", "=", "pitfillExitNode", ".", "elevation", ";", "List", "<", "GridNode", ">", "connected", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "GridNode", "checkNode", ":", "cellsToMakeFlowReady", ")", "{", "List", "<", "GridNode", ">", "validSurroundingNodes", "=", "checkNode", ".", "getValidSurroundingNodes", "(", ")", ";", "for", "(", "GridNode", "gridNode", ":", "validSurroundingNodes", ")", "{", "if", "(", "!", "pitfillExitNode", ".", "equals", "(", "gridNode", ")", "&&", "allPitsPositions", ".", "isMarked", "(", "gridNode", ".", "col", ",", "gridNode", ".", "row", ")", "&&", "gridNode", ".", "elevation", "==", "exitElevation", ")", "{", "if", "(", "!", "connected", ".", "contains", "(", "gridNode", ")", ")", "connected", ".", "add", "(", "gridNode", ")", ";", "}", "}", "}", "if", "(", "connected", ".", "size", "(", ")", "==", "0", ")", "{", "return", ";", "}", "for", "(", "GridNode", "gridNode", ":", "connected", ")", "{", "double", "newElev", "=", "(", "double", ")", "(", "gridNode", ".", "elevation", "+", "delta", "*", "(", "double", ")", "iteration", ")", ";", "gridNode", ".", "setValueInMap", "(", "pitIter", ",", "newElev", ")", ";", "}", "List", "<", "GridNode", ">", "updatedConnected", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "GridNode", "gridNode", ":", "connected", ")", "{", "GridNode", "updatedNode", "=", "new", "GridNode", "(", "pitIter", ",", "gridNode", ".", "cols", ",", "gridNode", ".", "rows", ",", "gridNode", ".", "xRes", ",", "gridNode", ".", "yRes", ",", "gridNode", ".", "col", ",", "gridNode", ".", "row", ")", ";", "updatedConnected", ".", "add", "(", "updatedNode", ")", ";", "}", "makeCellsFlowReady", "(", "iteration", ",", "pitfillExitNode", ",", "updatedConnected", ",", "allPitsPositions", ",", "pitIter", ",", "delta", ")", ";", "}" ]
Make cells flow ready by creating a slope starting from the output cell. @param iteration the iteration. @param pitfillExitNode the exit node. @param cellsToMakeFlowReady the cells to check and change at each iteration. @param allPitsPositions the marked positions of all existing pits. Necessary to pick only those that really are part of the pit pool. @param pitIter elevation data. @param delta the elevation delta to add to the cells to create the slope.
[ "Make", "cells", "flow", "ready", "by", "creating", "a", "slope", "starting", "from", "the", "output", "cell", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/hmachine/src/main/java/org/hortonmachine/hmachine/modules/demmanipulation/pitfiller/OmsDePitter.java#L568-L599
137,753
TheHortonMachine/hortonmachine
lesto/src/main/java/org/hortonmachine/lesto/modules/raster/adaptivetinfilter/TinHandler.java
TinHandler.setStartCoordinates
public void setStartCoordinates( List<Coordinate> coordinateList ) { generateTin(coordinateList); for( int i = 0; i < tinGeometries.length; i++ ) { Coordinate[] coordinates = tinGeometries[i].getCoordinates(); if (!tinCoordinateList.contains(coordinates[0])) { tinCoordinateList.add(coordinates[0]); } if (!tinCoordinateList.contains(coordinates[1])) { tinCoordinateList.add(coordinates[1]); } if (!tinCoordinateList.contains(coordinates[2])) { tinCoordinateList.add(coordinates[2]); } } didInitialize = true; }
java
public void setStartCoordinates( List<Coordinate> coordinateList ) { generateTin(coordinateList); for( int i = 0; i < tinGeometries.length; i++ ) { Coordinate[] coordinates = tinGeometries[i].getCoordinates(); if (!tinCoordinateList.contains(coordinates[0])) { tinCoordinateList.add(coordinates[0]); } if (!tinCoordinateList.contains(coordinates[1])) { tinCoordinateList.add(coordinates[1]); } if (!tinCoordinateList.contains(coordinates[2])) { tinCoordinateList.add(coordinates[2]); } } didInitialize = true; }
[ "public", "void", "setStartCoordinates", "(", "List", "<", "Coordinate", ">", "coordinateList", ")", "{", "generateTin", "(", "coordinateList", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "tinGeometries", ".", "length", ";", "i", "++", ")", "{", "Coordinate", "[", "]", "coordinates", "=", "tinGeometries", "[", "i", "]", ".", "getCoordinates", "(", ")", ";", "if", "(", "!", "tinCoordinateList", ".", "contains", "(", "coordinates", "[", "0", "]", ")", ")", "{", "tinCoordinateList", ".", "add", "(", "coordinates", "[", "0", "]", ")", ";", "}", "if", "(", "!", "tinCoordinateList", ".", "contains", "(", "coordinates", "[", "1", "]", ")", ")", "{", "tinCoordinateList", ".", "add", "(", "coordinates", "[", "1", "]", ")", ";", "}", "if", "(", "!", "tinCoordinateList", ".", "contains", "(", "coordinates", "[", "2", "]", ")", ")", "{", "tinCoordinateList", ".", "add", "(", "coordinates", "[", "2", "]", ")", ";", "}", "}", "didInitialize", "=", "true", ";", "}" ]
Sets the initial coordinates to start with. <p>Generates the tin on the first set of coordinates and adds the coordinates to the {@link #tinCoordinateList} for future use.</p> <p><b>Note that it is mandatory to call this method to initialize.</b></p> @param coordinateList the initial list of coordinates.
[ "Sets", "the", "initial", "coordinates", "to", "start", "with", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/lesto/src/main/java/org/hortonmachine/lesto/modules/raster/adaptivetinfilter/TinHandler.java#L135-L150
137,754
TheHortonMachine/hortonmachine
lesto/src/main/java/org/hortonmachine/lesto/modules/raster/adaptivetinfilter/TinHandler.java
TinHandler.filterOnAllData
public void filterOnAllData( final ALasDataManager lasHandler ) throws Exception { final ConcurrentSkipListSet<Double> angleSet = new ConcurrentSkipListSet<Double>(); final ConcurrentSkipListSet<Double> distanceSet = new ConcurrentSkipListSet<Double>(); if (isFirstStatsCalculation) { pm.beginTask("Calculating initial statistics...", tinGeometries.length); } else { pm.beginTask("Filtering all data on seeds tin...", tinGeometries.length); } try { final List<Coordinate> newTotalLeftOverCoordinateList = new ArrayList<Coordinate>(); if (threadsNum > 1) { // multithreaded ThreadedRunnable tRun = new ThreadedRunnable(threadsNum, null); for( final Geometry tinGeom : tinGeometries ) { tRun.executeRunnable(new Runnable(){ public void run() { List<Coordinate> leftOverList = runFilterOnAllData(lasHandler, angleSet, distanceSet, tinGeom); synchronized (newTotalLeftOverCoordinateList) { newTotalLeftOverCoordinateList.addAll(leftOverList); } } }); } tRun.waitAndClose(); } else { for( final Geometry tinGeom : tinGeometries ) { List<Coordinate> leftOverList = runFilterOnAllData(lasHandler, angleSet, distanceSet, tinGeom); newTotalLeftOverCoordinateList.addAll(leftOverList); } } pm.done(); leftOverCoordinateList.clear(); leftOverCoordinateList.addAll(newTotalLeftOverCoordinateList); /* * now recalculate the thresholds */ if (angleSet.size() > 1) { calculatedAngleThreshold = getMedianFromSet(angleSet); pm.message("Calculated angle threshold: " + calculatedAngleThreshold + " (range: " + angleSet.first() + " to " + angleSet.last() + ")"); } else if (angleSet.size() == 0) { return; } else { calculatedAngleThreshold = angleSet.first(); pm.message("Single angle left: " + calculatedAngleThreshold); } if (distanceSet.size() > 1) { calculatedDistanceThreshold = getMedianFromSet(distanceSet); pm.message("Calculated distance threshold: " + calculatedDistanceThreshold + " (range: " + distanceSet.first() + " to " + distanceSet.last() + ")"); } else if (distanceSet.size() == 0) { return; } else { calculatedDistanceThreshold = distanceSet.first(); pm.message("Single distance left: " + calculatedDistanceThreshold); } if (isFirstStatsCalculation) { isFirstStatsCalculation = false; } } catch (Exception e) { e.printStackTrace(); } }
java
public void filterOnAllData( final ALasDataManager lasHandler ) throws Exception { final ConcurrentSkipListSet<Double> angleSet = new ConcurrentSkipListSet<Double>(); final ConcurrentSkipListSet<Double> distanceSet = new ConcurrentSkipListSet<Double>(); if (isFirstStatsCalculation) { pm.beginTask("Calculating initial statistics...", tinGeometries.length); } else { pm.beginTask("Filtering all data on seeds tin...", tinGeometries.length); } try { final List<Coordinate> newTotalLeftOverCoordinateList = new ArrayList<Coordinate>(); if (threadsNum > 1) { // multithreaded ThreadedRunnable tRun = new ThreadedRunnable(threadsNum, null); for( final Geometry tinGeom : tinGeometries ) { tRun.executeRunnable(new Runnable(){ public void run() { List<Coordinate> leftOverList = runFilterOnAllData(lasHandler, angleSet, distanceSet, tinGeom); synchronized (newTotalLeftOverCoordinateList) { newTotalLeftOverCoordinateList.addAll(leftOverList); } } }); } tRun.waitAndClose(); } else { for( final Geometry tinGeom : tinGeometries ) { List<Coordinate> leftOverList = runFilterOnAllData(lasHandler, angleSet, distanceSet, tinGeom); newTotalLeftOverCoordinateList.addAll(leftOverList); } } pm.done(); leftOverCoordinateList.clear(); leftOverCoordinateList.addAll(newTotalLeftOverCoordinateList); /* * now recalculate the thresholds */ if (angleSet.size() > 1) { calculatedAngleThreshold = getMedianFromSet(angleSet); pm.message("Calculated angle threshold: " + calculatedAngleThreshold + " (range: " + angleSet.first() + " to " + angleSet.last() + ")"); } else if (angleSet.size() == 0) { return; } else { calculatedAngleThreshold = angleSet.first(); pm.message("Single angle left: " + calculatedAngleThreshold); } if (distanceSet.size() > 1) { calculatedDistanceThreshold = getMedianFromSet(distanceSet); pm.message("Calculated distance threshold: " + calculatedDistanceThreshold + " (range: " + distanceSet.first() + " to " + distanceSet.last() + ")"); } else if (distanceSet.size() == 0) { return; } else { calculatedDistanceThreshold = distanceSet.first(); pm.message("Single distance left: " + calculatedDistanceThreshold); } if (isFirstStatsCalculation) { isFirstStatsCalculation = false; } } catch (Exception e) { e.printStackTrace(); } }
[ "public", "void", "filterOnAllData", "(", "final", "ALasDataManager", "lasHandler", ")", "throws", "Exception", "{", "final", "ConcurrentSkipListSet", "<", "Double", ">", "angleSet", "=", "new", "ConcurrentSkipListSet", "<", "Double", ">", "(", ")", ";", "final", "ConcurrentSkipListSet", "<", "Double", ">", "distanceSet", "=", "new", "ConcurrentSkipListSet", "<", "Double", ">", "(", ")", ";", "if", "(", "isFirstStatsCalculation", ")", "{", "pm", ".", "beginTask", "(", "\"Calculating initial statistics...\"", ",", "tinGeometries", ".", "length", ")", ";", "}", "else", "{", "pm", ".", "beginTask", "(", "\"Filtering all data on seeds tin...\"", ",", "tinGeometries", ".", "length", ")", ";", "}", "try", "{", "final", "List", "<", "Coordinate", ">", "newTotalLeftOverCoordinateList", "=", "new", "ArrayList", "<", "Coordinate", ">", "(", ")", ";", "if", "(", "threadsNum", ">", "1", ")", "{", "// multithreaded", "ThreadedRunnable", "tRun", "=", "new", "ThreadedRunnable", "(", "threadsNum", ",", "null", ")", ";", "for", "(", "final", "Geometry", "tinGeom", ":", "tinGeometries", ")", "{", "tRun", ".", "executeRunnable", "(", "new", "Runnable", "(", ")", "{", "public", "void", "run", "(", ")", "{", "List", "<", "Coordinate", ">", "leftOverList", "=", "runFilterOnAllData", "(", "lasHandler", ",", "angleSet", ",", "distanceSet", ",", "tinGeom", ")", ";", "synchronized", "(", "newTotalLeftOverCoordinateList", ")", "{", "newTotalLeftOverCoordinateList", ".", "addAll", "(", "leftOverList", ")", ";", "}", "}", "}", ")", ";", "}", "tRun", ".", "waitAndClose", "(", ")", ";", "}", "else", "{", "for", "(", "final", "Geometry", "tinGeom", ":", "tinGeometries", ")", "{", "List", "<", "Coordinate", ">", "leftOverList", "=", "runFilterOnAllData", "(", "lasHandler", ",", "angleSet", ",", "distanceSet", ",", "tinGeom", ")", ";", "newTotalLeftOverCoordinateList", ".", "addAll", "(", "leftOverList", ")", ";", "}", "}", "pm", ".", "done", "(", ")", ";", "leftOverCoordinateList", ".", "clear", "(", ")", ";", "leftOverCoordinateList", ".", "addAll", "(", "newTotalLeftOverCoordinateList", ")", ";", "/*\n * now recalculate the thresholds\n */", "if", "(", "angleSet", ".", "size", "(", ")", ">", "1", ")", "{", "calculatedAngleThreshold", "=", "getMedianFromSet", "(", "angleSet", ")", ";", "pm", ".", "message", "(", "\"Calculated angle threshold: \"", "+", "calculatedAngleThreshold", "+", "\" (range: \"", "+", "angleSet", ".", "first", "(", ")", "+", "\" to \"", "+", "angleSet", ".", "last", "(", ")", "+", "\")\"", ")", ";", "}", "else", "if", "(", "angleSet", ".", "size", "(", ")", "==", "0", ")", "{", "return", ";", "}", "else", "{", "calculatedAngleThreshold", "=", "angleSet", ".", "first", "(", ")", ";", "pm", ".", "message", "(", "\"Single angle left: \"", "+", "calculatedAngleThreshold", ")", ";", "}", "if", "(", "distanceSet", ".", "size", "(", ")", ">", "1", ")", "{", "calculatedDistanceThreshold", "=", "getMedianFromSet", "(", "distanceSet", ")", ";", "pm", ".", "message", "(", "\"Calculated distance threshold: \"", "+", "calculatedDistanceThreshold", "+", "\" (range: \"", "+", "distanceSet", ".", "first", "(", ")", "+", "\" to \"", "+", "distanceSet", ".", "last", "(", ")", "+", "\")\"", ")", ";", "}", "else", "if", "(", "distanceSet", ".", "size", "(", ")", "==", "0", ")", "{", "return", ";", "}", "else", "{", "calculatedDistanceThreshold", "=", "distanceSet", ".", "first", "(", ")", ";", "pm", ".", "message", "(", "\"Single distance left: \"", "+", "calculatedDistanceThreshold", ")", ";", "}", "if", "(", "isFirstStatsCalculation", ")", "{", "isFirstStatsCalculation", "=", "false", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "}" ]
Filter data on thresholds of all available data on the tin. <p><b>Note: At the first run of this method, only thresholds are calculated.</b></p> @param lasHandler the las data handler of all data. @throws Exception
[ "Filter", "data", "on", "thresholds", "of", "all", "available", "data", "on", "the", "tin", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/lesto/src/main/java/org/hortonmachine/lesto/modules/raster/adaptivetinfilter/TinHandler.java#L190-L256
137,755
TheHortonMachine/hortonmachine
lesto/src/main/java/org/hortonmachine/lesto/modules/raster/adaptivetinfilter/TinHandler.java
TinHandler.generateTin
private void generateTin( List<Coordinate> coordinateList ) { pm.beginTask("Generate tin...", -1); DelaunayTriangulationBuilder b = new DelaunayTriangulationBuilder(); b.setSites(coordinateList); Geometry tinTriangles = b.getTriangles(gf); tinGeometries = new Geometry[tinTriangles.getNumGeometries()]; for( int i = 0; i < tinTriangles.getNumGeometries(); i++ ) { tinGeometries[i] = tinTriangles.getGeometryN(i); } pm.done(); }
java
private void generateTin( List<Coordinate> coordinateList ) { pm.beginTask("Generate tin...", -1); DelaunayTriangulationBuilder b = new DelaunayTriangulationBuilder(); b.setSites(coordinateList); Geometry tinTriangles = b.getTriangles(gf); tinGeometries = new Geometry[tinTriangles.getNumGeometries()]; for( int i = 0; i < tinTriangles.getNumGeometries(); i++ ) { tinGeometries[i] = tinTriangles.getGeometryN(i); } pm.done(); }
[ "private", "void", "generateTin", "(", "List", "<", "Coordinate", ">", "coordinateList", ")", "{", "pm", ".", "beginTask", "(", "\"Generate tin...\"", ",", "-", "1", ")", ";", "DelaunayTriangulationBuilder", "b", "=", "new", "DelaunayTriangulationBuilder", "(", ")", ";", "b", ".", "setSites", "(", "coordinateList", ")", ";", "Geometry", "tinTriangles", "=", "b", ".", "getTriangles", "(", "gf", ")", ";", "tinGeometries", "=", "new", "Geometry", "[", "tinTriangles", ".", "getNumGeometries", "(", ")", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "tinTriangles", ".", "getNumGeometries", "(", ")", ";", "i", "++", ")", "{", "tinGeometries", "[", "i", "]", "=", "tinTriangles", ".", "getGeometryN", "(", "i", ")", ";", "}", "pm", ".", "done", "(", ")", ";", "}" ]
Generate a tin from a given coords list. The internal tin geoms array is set from the result. @param coordinateList the coords to use for the tin generation.
[ "Generate", "a", "tin", "from", "a", "given", "coords", "list", ".", "The", "internal", "tin", "geoms", "array", "is", "set", "from", "the", "result", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/lesto/src/main/java/org/hortonmachine/lesto/modules/raster/adaptivetinfilter/TinHandler.java#L588-L598
137,756
TheHortonMachine/hortonmachine
lesto/src/main/java/org/hortonmachine/lesto/modules/raster/adaptivetinfilter/TinHandler.java
TinHandler.generateTinIndex
public STRtree generateTinIndex( Double maxEdgeLength ) { double maxEdge = maxEdgeLength != null ? maxEdgeLength : 0.0; pm.beginTask("Creating tin indexes...", tinGeometries.length); final STRtree tinTree = new STRtree(tinGeometries.length); for( Geometry geometry : tinGeometries ) { if (maxEdgeLength != null) { Coordinate[] coordinates = geometry.getCoordinates(); double maxLength = distance3d(coordinates[0], coordinates[1], null); double tmpLength = distance3d(coordinates[1], coordinates[2], null); if (tmpLength > maxLength) { maxLength = tmpLength; } tmpLength = distance3d(coordinates[2], coordinates[0], null); if (tmpLength > maxLength) { maxLength = tmpLength; } // triangles below a certain edge length are not adapted if (maxLength < maxEdge) { continue; } } tinTree.insert(geometry.getEnvelopeInternal(), geometry); } pm.done(); return tinTree; }
java
public STRtree generateTinIndex( Double maxEdgeLength ) { double maxEdge = maxEdgeLength != null ? maxEdgeLength : 0.0; pm.beginTask("Creating tin indexes...", tinGeometries.length); final STRtree tinTree = new STRtree(tinGeometries.length); for( Geometry geometry : tinGeometries ) { if (maxEdgeLength != null) { Coordinate[] coordinates = geometry.getCoordinates(); double maxLength = distance3d(coordinates[0], coordinates[1], null); double tmpLength = distance3d(coordinates[1], coordinates[2], null); if (tmpLength > maxLength) { maxLength = tmpLength; } tmpLength = distance3d(coordinates[2], coordinates[0], null); if (tmpLength > maxLength) { maxLength = tmpLength; } // triangles below a certain edge length are not adapted if (maxLength < maxEdge) { continue; } } tinTree.insert(geometry.getEnvelopeInternal(), geometry); } pm.done(); return tinTree; }
[ "public", "STRtree", "generateTinIndex", "(", "Double", "maxEdgeLength", ")", "{", "double", "maxEdge", "=", "maxEdgeLength", "!=", "null", "?", "maxEdgeLength", ":", "0.0", ";", "pm", ".", "beginTask", "(", "\"Creating tin indexes...\"", ",", "tinGeometries", ".", "length", ")", ";", "final", "STRtree", "tinTree", "=", "new", "STRtree", "(", "tinGeometries", ".", "length", ")", ";", "for", "(", "Geometry", "geometry", ":", "tinGeometries", ")", "{", "if", "(", "maxEdgeLength", "!=", "null", ")", "{", "Coordinate", "[", "]", "coordinates", "=", "geometry", ".", "getCoordinates", "(", ")", ";", "double", "maxLength", "=", "distance3d", "(", "coordinates", "[", "0", "]", ",", "coordinates", "[", "1", "]", ",", "null", ")", ";", "double", "tmpLength", "=", "distance3d", "(", "coordinates", "[", "1", "]", ",", "coordinates", "[", "2", "]", ",", "null", ")", ";", "if", "(", "tmpLength", ">", "maxLength", ")", "{", "maxLength", "=", "tmpLength", ";", "}", "tmpLength", "=", "distance3d", "(", "coordinates", "[", "2", "]", ",", "coordinates", "[", "0", "]", ",", "null", ")", ";", "if", "(", "tmpLength", ">", "maxLength", ")", "{", "maxLength", "=", "tmpLength", ";", "}", "// triangles below a certain edge length are not adapted", "if", "(", "maxLength", "<", "maxEdge", ")", "{", "continue", ";", "}", "}", "tinTree", ".", "insert", "(", "geometry", ".", "getEnvelopeInternal", "(", ")", ",", "geometry", ")", ";", "}", "pm", ".", "done", "(", ")", ";", "return", "tinTree", ";", "}" ]
Generate a spatial index on the tin geometries.
[ "Generate", "a", "spatial", "index", "on", "the", "tin", "geometries", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/lesto/src/main/java/org/hortonmachine/lesto/modules/raster/adaptivetinfilter/TinHandler.java#L603-L628
137,757
TheHortonMachine/hortonmachine
lesto/src/main/java/org/hortonmachine/lesto/modules/raster/adaptivetinfilter/TinHandler.java
TinHandler.getOrderedNodes
private Coordinate[] getOrderedNodes( Coordinate c, Coordinate coordinate1, Coordinate coordinate2, Coordinate coordinate3 ) { double d = distance3d(c, coordinate1, null); Coordinate nearest = coordinate1; Coordinate c2 = coordinate2; Coordinate c3 = coordinate3; double d2 = distance3d(c, coordinate2, null); if (d2 < d) { nearest = coordinate2; d = d2; c2 = coordinate1; c3 = coordinate3; } double d3 = distance3d(c, coordinate3, null); if (d3 < d) { nearest = coordinate3; c2 = coordinate1; c3 = coordinate2; } return new Coordinate[]{nearest, c2, c3}; }
java
private Coordinate[] getOrderedNodes( Coordinate c, Coordinate coordinate1, Coordinate coordinate2, Coordinate coordinate3 ) { double d = distance3d(c, coordinate1, null); Coordinate nearest = coordinate1; Coordinate c2 = coordinate2; Coordinate c3 = coordinate3; double d2 = distance3d(c, coordinate2, null); if (d2 < d) { nearest = coordinate2; d = d2; c2 = coordinate1; c3 = coordinate3; } double d3 = distance3d(c, coordinate3, null); if (d3 < d) { nearest = coordinate3; c2 = coordinate1; c3 = coordinate2; } return new Coordinate[]{nearest, c2, c3}; }
[ "private", "Coordinate", "[", "]", "getOrderedNodes", "(", "Coordinate", "c", ",", "Coordinate", "coordinate1", ",", "Coordinate", "coordinate2", ",", "Coordinate", "coordinate3", ")", "{", "double", "d", "=", "distance3d", "(", "c", ",", "coordinate1", ",", "null", ")", ";", "Coordinate", "nearest", "=", "coordinate1", ";", "Coordinate", "c2", "=", "coordinate2", ";", "Coordinate", "c3", "=", "coordinate3", ";", "double", "d2", "=", "distance3d", "(", "c", ",", "coordinate2", ",", "null", ")", ";", "if", "(", "d2", "<", "d", ")", "{", "nearest", "=", "coordinate2", ";", "d", "=", "d2", ";", "c2", "=", "coordinate1", ";", "c3", "=", "coordinate3", ";", "}", "double", "d3", "=", "distance3d", "(", "c", ",", "coordinate3", ",", "null", ")", ";", "if", "(", "d3", "<", "d", ")", "{", "nearest", "=", "coordinate3", ";", "c2", "=", "coordinate1", ";", "c3", "=", "coordinate2", ";", "}", "return", "new", "Coordinate", "[", "]", "{", "nearest", ",", "c2", ",", "c3", "}", ";", "}" ]
Order coordinates to have the first coordinate in the array as the nearest to a given coordinate 'c'. The second and third are not ordered, but randomly added. @param c @param coordinate1 @param coordinate2 @param coordinate3 @return
[ "Order", "coordinates", "to", "have", "the", "first", "coordinate", "in", "the", "array", "as", "the", "nearest", "to", "a", "given", "coordinate", "c", ".", "The", "second", "and", "third", "are", "not", "ordered", "but", "randomly", "added", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/lesto/src/main/java/org/hortonmachine/lesto/modules/raster/adaptivetinfilter/TinHandler.java#L652-L672
137,758
enasequence/sequencetools
src/main/java/uk/ac/ebi/embl/flatfile/reader/BufferedFileLineReader.java
BufferedFileLineReader.seek
public void seek(long pos) throws IOException { int n = (int) (real_pos - pos); if (n >= 0 && n <= buf_end) { buf_pos = buf_end - n; } else { raf.seek(pos); buf_end = 0; buf_pos = 0; real_pos = raf.getFilePointer(); } }
java
public void seek(long pos) throws IOException { int n = (int) (real_pos - pos); if (n >= 0 && n <= buf_end) { buf_pos = buf_end - n; } else { raf.seek(pos); buf_end = 0; buf_pos = 0; real_pos = raf.getFilePointer(); } }
[ "public", "void", "seek", "(", "long", "pos", ")", "throws", "IOException", "{", "int", "n", "=", "(", "int", ")", "(", "real_pos", "-", "pos", ")", ";", "if", "(", "n", ">=", "0", "&&", "n", "<=", "buf_end", ")", "{", "buf_pos", "=", "buf_end", "-", "n", ";", "}", "else", "{", "raf", ".", "seek", "(", "pos", ")", ";", "buf_end", "=", "0", ";", "buf_pos", "=", "0", ";", "real_pos", "=", "raf", ".", "getFilePointer", "(", ")", ";", "}", "}" ]
If the sought position is within the buffer - simply sets the current buffer position so the next read will be from the buffer. Otherwise seeks in the RAF and reset the buffer end and current positions. @param pos @throws IOException
[ "If", "the", "sought", "position", "is", "within", "the", "buffer", "-", "simply", "sets", "the", "current", "buffer", "position", "so", "the", "next", "read", "will", "be", "from", "the", "buffer", ".", "Otherwise", "seeks", "in", "the", "RAF", "and", "reset", "the", "buffer", "end", "and", "current", "positions", "." ]
4127f5e1a17540239f5810136153fbd6737fa262
https://github.com/enasequence/sequencetools/blob/4127f5e1a17540239f5810136153fbd6737fa262/src/main/java/uk/ac/ebi/embl/flatfile/reader/BufferedFileLineReader.java#L108-L124
137,759
enasequence/sequencetools
src/main/java/uk/ac/ebi/embl/flatfile/reader/BufferedFileLineReader.java
BufferedFileLineReader.readLine
@Override public final String readLine() throws IOException { String str = null; if (buf_end - buf_pos <= 0) { if (fillBuffer() < 0) { // return null if we are at the end and there is nothing to read return null; } } int lineend = -1; for (int i = buf_pos; i < buf_end; i++) { if (buffer[i] == '\n') { lineend = i; break; } } if (lineend < 0) { StringBuffer input = new StringBuffer(256); int c; while (((c = read()) != -1) && (c != '\n')) { input.append((char) c); } if ((c == -1) && (input.length() == 0)) { return null; } return input.toString(); } if (lineend > 0 && buffer[lineend - 1] == '\r') { str = new String(buffer, 0, buf_pos, lineend - buf_pos - 1); } else { str = new String(buffer, 0, buf_pos, lineend - buf_pos); } buf_pos = lineend + 1; return str; }
java
@Override public final String readLine() throws IOException { String str = null; if (buf_end - buf_pos <= 0) { if (fillBuffer() < 0) { // return null if we are at the end and there is nothing to read return null; } } int lineend = -1; for (int i = buf_pos; i < buf_end; i++) { if (buffer[i] == '\n') { lineend = i; break; } } if (lineend < 0) { StringBuffer input = new StringBuffer(256); int c; while (((c = read()) != -1) && (c != '\n')) { input.append((char) c); } if ((c == -1) && (input.length() == 0)) { return null; } return input.toString(); } if (lineend > 0 && buffer[lineend - 1] == '\r') { str = new String(buffer, 0, buf_pos, lineend - buf_pos - 1); } else { str = new String(buffer, 0, buf_pos, lineend - buf_pos); } buf_pos = lineend + 1; return str; }
[ "@", "Override", "public", "final", "String", "readLine", "(", ")", "throws", "IOException", "{", "String", "str", "=", "null", ";", "if", "(", "buf_end", "-", "buf_pos", "<=", "0", ")", "{", "if", "(", "fillBuffer", "(", ")", "<", "0", ")", "{", "// return null if we are at the end and there is nothing to read", "return", "null", ";", "}", "}", "int", "lineend", "=", "-", "1", ";", "for", "(", "int", "i", "=", "buf_pos", ";", "i", "<", "buf_end", ";", "i", "++", ")", "{", "if", "(", "buffer", "[", "i", "]", "==", "'", "'", ")", "{", "lineend", "=", "i", ";", "break", ";", "}", "}", "if", "(", "lineend", "<", "0", ")", "{", "StringBuffer", "input", "=", "new", "StringBuffer", "(", "256", ")", ";", "int", "c", ";", "while", "(", "(", "(", "c", "=", "read", "(", ")", ")", "!=", "-", "1", ")", "&&", "(", "c", "!=", "'", "'", ")", ")", "{", "input", ".", "append", "(", "(", "char", ")", "c", ")", ";", "}", "if", "(", "(", "c", "==", "-", "1", ")", "&&", "(", "input", ".", "length", "(", ")", "==", "0", ")", ")", "{", "return", "null", ";", "}", "return", "input", ".", "toString", "(", ")", ";", "}", "if", "(", "lineend", ">", "0", "&&", "buffer", "[", "lineend", "-", "1", "]", "==", "'", "'", ")", "{", "str", "=", "new", "String", "(", "buffer", ",", "0", ",", "buf_pos", ",", "lineend", "-", "buf_pos", "-", "1", ")", ";", "}", "else", "{", "str", "=", "new", "String", "(", "buffer", ",", "0", ",", "buf_pos", ",", "lineend", "-", "buf_pos", ")", ";", "}", "buf_pos", "=", "lineend", "+", "1", ";", "return", "str", ";", "}" ]
This method first decides if the buffer still contains unread contents. If it doesn't, the buffer needs to be filled up. If the new line delimiter can be found in the buffer, then a new line is read from the buffer and converted into String. Otherwise, it will simply call the read method to read byte by byte. Although the code of the latter portion is similar to the original readLine, performance is better here because the read method is buffered in the new class. @see uk.ac.ebi.embl.flatfile.reader.ILineReader#readline()
[ "This", "method", "first", "decides", "if", "the", "buffer", "still", "contains", "unread", "contents", ".", "If", "it", "doesn", "t", "the", "buffer", "needs", "to", "be", "filled", "up", ".", "If", "the", "new", "line", "delimiter", "can", "be", "found", "in", "the", "buffer", "then", "a", "new", "line", "is", "read", "from", "the", "buffer", "and", "converted", "into", "String", ".", "Otherwise", "it", "will", "simply", "call", "the", "read", "method", "to", "read", "byte", "by", "byte", ".", "Although", "the", "code", "of", "the", "latter", "portion", "is", "similar", "to", "the", "original", "readLine", "performance", "is", "better", "here", "because", "the", "read", "method", "is", "buffered", "in", "the", "new", "class", "." ]
4127f5e1a17540239f5810136153fbd6737fa262
https://github.com/enasequence/sequencetools/blob/4127f5e1a17540239f5810136153fbd6737fa262/src/main/java/uk/ac/ebi/embl/flatfile/reader/BufferedFileLineReader.java#L155-L197
137,760
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/utils/StringUtilities.java
StringUtilities.checkSameName
public static String checkSameName( List<String> strings, String string ) { int index = 1; for( int i = 0; i < strings.size(); i++ ) { if (index == 10000) { // something odd is going on throw new RuntimeException(); } String existingString = strings.get(i); existingString = existingString.trim(); if (existingString.trim().equals(string.trim())) { // name exists, change the name of the entering if (string.endsWith(")")) { string = string.trim().replaceFirst("\\([0-9]+\\)$", "(" + (index++) + ")"); } else { string = string + " (" + (index++) + ")"; } // start again i = 0; } } return string; }
java
public static String checkSameName( List<String> strings, String string ) { int index = 1; for( int i = 0; i < strings.size(); i++ ) { if (index == 10000) { // something odd is going on throw new RuntimeException(); } String existingString = strings.get(i); existingString = existingString.trim(); if (existingString.trim().equals(string.trim())) { // name exists, change the name of the entering if (string.endsWith(")")) { string = string.trim().replaceFirst("\\([0-9]+\\)$", "(" + (index++) + ")"); } else { string = string + " (" + (index++) + ")"; } // start again i = 0; } } return string; }
[ "public", "static", "String", "checkSameName", "(", "List", "<", "String", ">", "strings", ",", "String", "string", ")", "{", "int", "index", "=", "1", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "strings", ".", "size", "(", ")", ";", "i", "++", ")", "{", "if", "(", "index", "==", "10000", ")", "{", "// something odd is going on", "throw", "new", "RuntimeException", "(", ")", ";", "}", "String", "existingString", "=", "strings", ".", "get", "(", "i", ")", ";", "existingString", "=", "existingString", ".", "trim", "(", ")", ";", "if", "(", "existingString", ".", "trim", "(", ")", ".", "equals", "(", "string", ".", "trim", "(", ")", ")", ")", "{", "// name exists, change the name of the entering", "if", "(", "string", ".", "endsWith", "(", "\")\"", ")", ")", "{", "string", "=", "string", ".", "trim", "(", ")", ".", "replaceFirst", "(", "\"\\\\([0-9]+\\\\)$\"", ",", "\"(\"", "+", "(", "index", "++", ")", "+", "\")\"", ")", ";", "}", "else", "{", "string", "=", "string", "+", "\" (\"", "+", "(", "index", "++", ")", "+", "\")\"", ";", "}", "// start again", "i", "=", "0", ";", "}", "}", "return", "string", ";", "}" ]
Checks if the list of strings supplied contains the supplied string. <p>If the string is contained it changes the name by adding a number. <p>The spaces are trimmed away before performing name equality. @param strings the list of existing strings. @param string the proposed new string, to be changed if colliding. @return the new non-colliding name for the string.
[ "Checks", "if", "the", "list", "of", "strings", "supplied", "contains", "the", "supplied", "string", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/StringUtilities.java#L47-L68
137,761
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/utils/StringUtilities.java
StringUtilities.splitString
public static List<String> splitString( String string, int limit ) { List<String> list = new ArrayList<String>(); char[] chars = string.toCharArray(); boolean endOfString = false; int start = 0; int end = start; while( start < chars.length - 1 ) { int charCount = 0; int lastSpace = 0; while( charCount < limit ) { if (chars[charCount + start] == ' ') { lastSpace = charCount; } charCount++; if (charCount + start == string.length()) { endOfString = true; break; } } end = endOfString ? string.length() : (lastSpace > 0) ? lastSpace + start : charCount + start; list.add(string.substring(start, end)); start = end + 1; } return list; }
java
public static List<String> splitString( String string, int limit ) { List<String> list = new ArrayList<String>(); char[] chars = string.toCharArray(); boolean endOfString = false; int start = 0; int end = start; while( start < chars.length - 1 ) { int charCount = 0; int lastSpace = 0; while( charCount < limit ) { if (chars[charCount + start] == ' ') { lastSpace = charCount; } charCount++; if (charCount + start == string.length()) { endOfString = true; break; } } end = endOfString ? string.length() : (lastSpace > 0) ? lastSpace + start : charCount + start; list.add(string.substring(start, end)); start = end + 1; } return list; }
[ "public", "static", "List", "<", "String", ">", "splitString", "(", "String", "string", ",", "int", "limit", ")", "{", "List", "<", "String", ">", "list", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "char", "[", "]", "chars", "=", "string", ".", "toCharArray", "(", ")", ";", "boolean", "endOfString", "=", "false", ";", "int", "start", "=", "0", ";", "int", "end", "=", "start", ";", "while", "(", "start", "<", "chars", ".", "length", "-", "1", ")", "{", "int", "charCount", "=", "0", ";", "int", "lastSpace", "=", "0", ";", "while", "(", "charCount", "<", "limit", ")", "{", "if", "(", "chars", "[", "charCount", "+", "start", "]", "==", "'", "'", ")", "{", "lastSpace", "=", "charCount", ";", "}", "charCount", "++", ";", "if", "(", "charCount", "+", "start", "==", "string", ".", "length", "(", ")", ")", "{", "endOfString", "=", "true", ";", "break", ";", "}", "}", "end", "=", "endOfString", "?", "string", ".", "length", "(", ")", ":", "(", "lastSpace", ">", "0", ")", "?", "lastSpace", "+", "start", ":", "charCount", "+", "start", ";", "list", ".", "add", "(", "string", ".", "substring", "(", "start", ",", "end", ")", ")", ";", "start", "=", "end", "+", "1", ";", "}", "return", "list", ";", "}" ]
Splits a string by char limit, not breaking works. @param string the string to split. @param limit the char limit. @return the list of split words.
[ "Splits", "a", "string", "by", "char", "limit", "not", "breaking", "works", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/StringUtilities.java#L98-L123
137,762
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/utils/StringUtilities.java
StringUtilities.streamToScanner
@SuppressWarnings("resource") public static Scanner streamToScanner( InputStream stream, String delimiter ) { java.util.Scanner s = new java.util.Scanner(stream).useDelimiter(delimiter); return s; }
java
@SuppressWarnings("resource") public static Scanner streamToScanner( InputStream stream, String delimiter ) { java.util.Scanner s = new java.util.Scanner(stream).useDelimiter(delimiter); return s; }
[ "@", "SuppressWarnings", "(", "\"resource\"", ")", "public", "static", "Scanner", "streamToScanner", "(", "InputStream", "stream", ",", "String", "delimiter", ")", "{", "java", ".", "util", ".", "Scanner", "s", "=", "new", "java", ".", "util", ".", "Scanner", "(", "stream", ")", ".", "useDelimiter", "(", "delimiter", ")", ";", "return", "s", ";", "}" ]
Get scanner from input stream. <b>Note: the scanner needs to be closed after use.</b> @param stream the stream to read. @param delimiter the delimiter to use. @return the scanner.
[ "Get", "scanner", "from", "input", "stream", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/StringUtilities.java#L141-L145
137,763
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/utils/StringUtilities.java
StringUtilities.stringToDoubleArray
public static double[] stringToDoubleArray( String string, String separator ) { if (separator == null) { separator = ","; } String[] stringSplit = string.trim().split(separator); double[] array = new double[stringSplit.length]; for( int i = 0; i < array.length; i++ ) { array[i] = Double.parseDouble(stringSplit[i].trim()); } return array; }
java
public static double[] stringToDoubleArray( String string, String separator ) { if (separator == null) { separator = ","; } String[] stringSplit = string.trim().split(separator); double[] array = new double[stringSplit.length]; for( int i = 0; i < array.length; i++ ) { array[i] = Double.parseDouble(stringSplit[i].trim()); } return array; }
[ "public", "static", "double", "[", "]", "stringToDoubleArray", "(", "String", "string", ",", "String", "separator", ")", "{", "if", "(", "separator", "==", "null", ")", "{", "separator", "=", "\",\"", ";", "}", "String", "[", "]", "stringSplit", "=", "string", ".", "trim", "(", ")", ".", "split", "(", "separator", ")", ";", "double", "[", "]", "array", "=", "new", "double", "[", "stringSplit", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "array", ".", "length", ";", "i", "++", ")", "{", "array", "[", "i", "]", "=", "Double", ".", "parseDouble", "(", "stringSplit", "[", "i", "]", ".", "trim", "(", ")", ")", ";", "}", "return", "array", ";", "}" ]
Convert a string containing a list of numbers into its array. @param string the string containing numbers. @param separator the number separator. @return the array of values.
[ "Convert", "a", "string", "containing", "a", "list", "of", "numbers", "into", "its", "array", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/StringUtilities.java#L154-L164
137,764
enasequence/sequencetools
src/main/java/uk/ac/ebi/embl/api/entry/feature/Feature.java
Feature.getTextDescription
public String getTextDescription() { StringBuilder builder = new StringBuilder(name); builder.append(" "); List<Location> locationList = new ArrayList<Location>(locations.getLocations()); Collections.sort(locationList, new LocationComparator(LocationComparator.START_LOCATION)); for(Location location : locationList) { builder.append(" "); builder.append(location.getBeginPosition()); builder.append("-"); builder.append(location.getEndPosition()); } return builder.toString(); }
java
public String getTextDescription() { StringBuilder builder = new StringBuilder(name); builder.append(" "); List<Location> locationList = new ArrayList<Location>(locations.getLocations()); Collections.sort(locationList, new LocationComparator(LocationComparator.START_LOCATION)); for(Location location : locationList) { builder.append(" "); builder.append(location.getBeginPosition()); builder.append("-"); builder.append(location.getEndPosition()); } return builder.toString(); }
[ "public", "String", "getTextDescription", "(", ")", "{", "StringBuilder", "builder", "=", "new", "StringBuilder", "(", "name", ")", ";", "builder", ".", "append", "(", "\" \"", ")", ";", "List", "<", "Location", ">", "locationList", "=", "new", "ArrayList", "<", "Location", ">", "(", "locations", ".", "getLocations", "(", ")", ")", ";", "Collections", ".", "sort", "(", "locationList", ",", "new", "LocationComparator", "(", "LocationComparator", ".", "START_LOCATION", ")", ")", ";", "for", "(", "Location", "location", ":", "locationList", ")", "{", "builder", ".", "append", "(", "\" \"", ")", ";", "builder", ".", "append", "(", "location", ".", "getBeginPosition", "(", ")", ")", ";", "builder", ".", "append", "(", "\"-\"", ")", ";", "builder", ".", "append", "(", "location", ".", "getEndPosition", "(", ")", ")", ";", "}", "return", "builder", ".", "toString", "(", ")", ";", "}" ]
The feature name and location as a string - handy for text summary @return
[ "The", "feature", "name", "and", "location", "as", "a", "string", "-", "handy", "for", "text", "summary" ]
4127f5e1a17540239f5810136153fbd6737fa262
https://github.com/enasequence/sequencetools/blob/4127f5e1a17540239f5810136153fbd6737fa262/src/main/java/uk/ac/ebi/embl/api/entry/feature/Feature.java#L369-L382
137,765
codahale/xsalsa20poly1305
src/main/java/com/codahale/xsalsa20poly1305/SimpleBox.java
SimpleBox.seal
public byte[] seal(byte[] plaintext) { final byte[] nonce = box.nonce(plaintext); final byte[] ciphertext = box.seal(nonce, plaintext); final byte[] combined = new byte[nonce.length + ciphertext.length]; System.arraycopy(nonce, 0, combined, 0, nonce.length); System.arraycopy(ciphertext, 0, combined, nonce.length, ciphertext.length); return combined; }
java
public byte[] seal(byte[] plaintext) { final byte[] nonce = box.nonce(plaintext); final byte[] ciphertext = box.seal(nonce, plaintext); final byte[] combined = new byte[nonce.length + ciphertext.length]; System.arraycopy(nonce, 0, combined, 0, nonce.length); System.arraycopy(ciphertext, 0, combined, nonce.length, ciphertext.length); return combined; }
[ "public", "byte", "[", "]", "seal", "(", "byte", "[", "]", "plaintext", ")", "{", "final", "byte", "[", "]", "nonce", "=", "box", ".", "nonce", "(", "plaintext", ")", ";", "final", "byte", "[", "]", "ciphertext", "=", "box", ".", "seal", "(", "nonce", ",", "plaintext", ")", ";", "final", "byte", "[", "]", "combined", "=", "new", "byte", "[", "nonce", ".", "length", "+", "ciphertext", ".", "length", "]", ";", "System", ".", "arraycopy", "(", "nonce", ",", "0", ",", "combined", ",", "0", ",", "nonce", ".", "length", ")", ";", "System", ".", "arraycopy", "(", "ciphertext", ",", "0", ",", "combined", ",", "nonce", ".", "length", ",", "ciphertext", ".", "length", ")", ";", "return", "combined", ";", "}" ]
Encrypt the plaintext with the given key. @param plaintext any arbitrary bytes @return the ciphertext
[ "Encrypt", "the", "plaintext", "with", "the", "given", "key", "." ]
f3c1ab2f05b17df137ed8fbb66da2b417066729a
https://github.com/codahale/xsalsa20poly1305/blob/f3c1ab2f05b17df137ed8fbb66da2b417066729a/src/main/java/com/codahale/xsalsa20poly1305/SimpleBox.java#L56-L63
137,766
codahale/xsalsa20poly1305
src/main/java/com/codahale/xsalsa20poly1305/SimpleBox.java
SimpleBox.open
public Optional<byte[]> open(byte[] ciphertext) { if (ciphertext.length < SecretBox.NONCE_SIZE) { return Optional.empty(); } final byte[] nonce = Arrays.copyOfRange(ciphertext, 0, SecretBox.NONCE_SIZE); final byte[] x = Arrays.copyOfRange(ciphertext, SecretBox.NONCE_SIZE, ciphertext.length); return box.open(nonce, x); }
java
public Optional<byte[]> open(byte[] ciphertext) { if (ciphertext.length < SecretBox.NONCE_SIZE) { return Optional.empty(); } final byte[] nonce = Arrays.copyOfRange(ciphertext, 0, SecretBox.NONCE_SIZE); final byte[] x = Arrays.copyOfRange(ciphertext, SecretBox.NONCE_SIZE, ciphertext.length); return box.open(nonce, x); }
[ "public", "Optional", "<", "byte", "[", "]", ">", "open", "(", "byte", "[", "]", "ciphertext", ")", "{", "if", "(", "ciphertext", ".", "length", "<", "SecretBox", ".", "NONCE_SIZE", ")", "{", "return", "Optional", ".", "empty", "(", ")", ";", "}", "final", "byte", "[", "]", "nonce", "=", "Arrays", ".", "copyOfRange", "(", "ciphertext", ",", "0", ",", "SecretBox", ".", "NONCE_SIZE", ")", ";", "final", "byte", "[", "]", "x", "=", "Arrays", ".", "copyOfRange", "(", "ciphertext", ",", "SecretBox", ".", "NONCE_SIZE", ",", "ciphertext", ".", "length", ")", ";", "return", "box", ".", "open", "(", "nonce", ",", "x", ")", ";", "}" ]
Decrypt the ciphertext with the given key. @param ciphertext an encrypted message @return an {@link Optional} of the original plaintext, or if either the key, nonce, or ciphertext was modified, an empty {@link Optional}
[ "Decrypt", "the", "ciphertext", "with", "the", "given", "key", "." ]
f3c1ab2f05b17df137ed8fbb66da2b417066729a
https://github.com/codahale/xsalsa20poly1305/blob/f3c1ab2f05b17df137ed8fbb66da2b417066729a/src/main/java/com/codahale/xsalsa20poly1305/SimpleBox.java#L72-L79
137,767
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/io/dxfdwg/libs/dwg/objects/DwgVertex3D.java
DwgVertex3D.readDwgVertex3DV15
public void readDwgVertex3DV15(int[] data, int offset) throws Exception { int bitPos = offset; bitPos = readObjectHeaderV15(data, bitPos); Vector v = DwgUtil.getRawChar(data, bitPos); bitPos = ((Integer)v.get(0)).intValue(); int flags = ((Integer)v.get(1)).intValue(); this.flags = flags; v = DwgUtil.getBitDouble(data, bitPos); bitPos = ((Integer)v.get(0)).intValue(); double x = ((Double)v.get(1)).doubleValue(); v = DwgUtil.getBitDouble(data, bitPos); bitPos = ((Integer)v.get(0)).intValue(); double y = ((Double)v.get(1)).doubleValue(); v = DwgUtil.getBitDouble(data, bitPos); bitPos = ((Integer)v.get(0)).intValue(); double z = ((Double)v.get(1)).doubleValue(); double[] coord = new double[]{x, y, z}; point = new double[]{x, y, z}; bitPos = readObjectTailV15(data, bitPos); }
java
public void readDwgVertex3DV15(int[] data, int offset) throws Exception { int bitPos = offset; bitPos = readObjectHeaderV15(data, bitPos); Vector v = DwgUtil.getRawChar(data, bitPos); bitPos = ((Integer)v.get(0)).intValue(); int flags = ((Integer)v.get(1)).intValue(); this.flags = flags; v = DwgUtil.getBitDouble(data, bitPos); bitPos = ((Integer)v.get(0)).intValue(); double x = ((Double)v.get(1)).doubleValue(); v = DwgUtil.getBitDouble(data, bitPos); bitPos = ((Integer)v.get(0)).intValue(); double y = ((Double)v.get(1)).doubleValue(); v = DwgUtil.getBitDouble(data, bitPos); bitPos = ((Integer)v.get(0)).intValue(); double z = ((Double)v.get(1)).doubleValue(); double[] coord = new double[]{x, y, z}; point = new double[]{x, y, z}; bitPos = readObjectTailV15(data, bitPos); }
[ "public", "void", "readDwgVertex3DV15", "(", "int", "[", "]", "data", ",", "int", "offset", ")", "throws", "Exception", "{", "int", "bitPos", "=", "offset", ";", "bitPos", "=", "readObjectHeaderV15", "(", "data", ",", "bitPos", ")", ";", "Vector", "v", "=", "DwgUtil", ".", "getRawChar", "(", "data", ",", "bitPos", ")", ";", "bitPos", "=", "(", "(", "Integer", ")", "v", ".", "get", "(", "0", ")", ")", ".", "intValue", "(", ")", ";", "int", "flags", "=", "(", "(", "Integer", ")", "v", ".", "get", "(", "1", ")", ")", ".", "intValue", "(", ")", ";", "this", ".", "flags", "=", "flags", ";", "v", "=", "DwgUtil", ".", "getBitDouble", "(", "data", ",", "bitPos", ")", ";", "bitPos", "=", "(", "(", "Integer", ")", "v", ".", "get", "(", "0", ")", ")", ".", "intValue", "(", ")", ";", "double", "x", "=", "(", "(", "Double", ")", "v", ".", "get", "(", "1", ")", ")", ".", "doubleValue", "(", ")", ";", "v", "=", "DwgUtil", ".", "getBitDouble", "(", "data", ",", "bitPos", ")", ";", "bitPos", "=", "(", "(", "Integer", ")", "v", ".", "get", "(", "0", ")", ")", ".", "intValue", "(", ")", ";", "double", "y", "=", "(", "(", "Double", ")", "v", ".", "get", "(", "1", ")", ")", ".", "doubleValue", "(", ")", ";", "v", "=", "DwgUtil", ".", "getBitDouble", "(", "data", ",", "bitPos", ")", ";", "bitPos", "=", "(", "(", "Integer", ")", "v", ".", "get", "(", "0", ")", ")", ".", "intValue", "(", ")", ";", "double", "z", "=", "(", "(", "Double", ")", "v", ".", "get", "(", "1", ")", ")", ".", "doubleValue", "(", ")", ";", "double", "[", "]", "coord", "=", "new", "double", "[", "]", "{", "x", ",", "y", ",", "z", "}", ";", "point", "=", "new", "double", "[", "]", "{", "x", ",", "y", ",", "z", "}", ";", "bitPos", "=", "readObjectTailV15", "(", "data", ",", "bitPos", ")", ";", "}" ]
Read a Vertex3D in the DWG format Version 15 @param data Array of unsigned bytes obtained from the DWG binary file @param offset The current bit offset where the value begins @throws Exception If an unexpected bit value is found in the DWG file. Occurs when we are looking for LwPolylines.
[ "Read", "a", "Vertex3D", "in", "the", "DWG", "format", "Version", "15" ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/io/dxfdwg/libs/dwg/objects/DwgVertex3D.java#L43-L62
137,768
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/modules/utils/fileiterator/OmsFileIterator.java
OmsFileIterator.addPrj
public static void addPrj( String folder, String epsg ) throws Exception { OmsFileIterator fiter = new OmsFileIterator(); fiter.inFolder = folder; fiter.pCode = epsg; fiter.process(); }
java
public static void addPrj( String folder, String epsg ) throws Exception { OmsFileIterator fiter = new OmsFileIterator(); fiter.inFolder = folder; fiter.pCode = epsg; fiter.process(); }
[ "public", "static", "void", "addPrj", "(", "String", "folder", ",", "String", "epsg", ")", "throws", "Exception", "{", "OmsFileIterator", "fiter", "=", "new", "OmsFileIterator", "(", ")", ";", "fiter", ".", "inFolder", "=", "folder", ";", "fiter", ".", "pCode", "=", "epsg", ";", "fiter", ".", "process", "(", ")", ";", "}" ]
Utility to add to all found files in a given folder the prj file following the supplied epsg. @param folder the folder to browse. @param epsg the epsg from which to take the prj. @throws Exception
[ "Utility", "to", "add", "to", "all", "found", "files", "in", "a", "given", "folder", "the", "prj", "file", "following", "the", "supplied", "epsg", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/modules/utils/fileiterator/OmsFileIterator.java#L181-L186
137,769
TheHortonMachine/hortonmachine
hmachine/src/main/java/org/hortonmachine/hmachine/modules/geomorphology/draindir/OmsDrainDir.java
OmsDrainDir.process
@Execute public void process() throws Exception { if (!concatOr(outFlow == null, doReset)) { return; } checkNull(inFlow, inPit); RegionMap regionMap = CoverageUtilities.getRegionParamsFromGridCoverage(inPit); cols = regionMap.getCols(); rows = regionMap.getRows(); xRes = regionMap.getXres(); yRes = regionMap.getYres(); dxySqrt = Math.sqrt(xRes * xRes + yRes * yRes); RenderedImage pitfillerRI = inPit.getRenderedImage(); WritableRaster pitfillerWR = CoverageUtilities.renderedImage2DoubleWritableRaster(pitfillerRI, true); RenderedImage flowRI = inFlow.getRenderedImage(); WritableRaster flowWR = CoverageUtilities.renderedImage2ShortWritableRaster(flowRI, true); RandomIter pitRandomIter = RandomIterFactory.create(pitfillerWR, null); // create new matrix double[] orderedelev = new double[cols * rows]; int[] indexes = new int[cols * rows]; int nelev = 0; for( int r = 0; r < rows; r++ ) { if (pm.isCanceled()) { return; } for( int c = 0; c < cols; c++ ) { double pitValue = pitRandomIter.getSampleDouble(c, r, 0); int pos = (r * cols) + c; orderedelev[pos] = pitValue; indexes[pos] = pos + 1; if (!isNovalue(pitValue)) { nelev = nelev + 1; } } } QuickSortAlgorithm t = new QuickSortAlgorithm(pm); t.sort(orderedelev, indexes); pm.message(msg.message("draindir.initializematrix")); // Initialize new RasterData and set value WritableRaster tcaWR = CoverageUtilities.createWritableRaster(cols, rows, Integer.class, null, HMConstants.intNovalue); WritableRaster dirWR = CoverageUtilities.createWritableRaster(cols, rows, Short.class, null, HMConstants.shortNovalue); // it contains the analyzed cells WritableRaster deviationsWR = CoverageUtilities.createWritableRaster(cols, rows, Double.class, null, null); BitMatrix analizedMatrix = new BitMatrix(cols, rows); if (doLad) { orlandiniD8LAD(indexes, deviationsWR, analizedMatrix, pitfillerWR, flowWR, tcaWR, dirWR, nelev); } else { orlandiniD8LTD(indexes, deviationsWR, analizedMatrix, pitfillerWR, flowWR, tcaWR, dirWR, nelev); if (pm.isCanceled()) { return; } // only if required executes this method if (inFlownet != null) { newDirections(pitfillerWR, dirWR); } } if (pm.isCanceled()) { return; } outFlow = CoverageUtilities.buildCoverage("draindir", dirWR, regionMap, inPit.getCoordinateReferenceSystem()); outTca = CoverageUtilities.buildCoverage("tca", tcaWR, regionMap, inPit.getCoordinateReferenceSystem()); }
java
@Execute public void process() throws Exception { if (!concatOr(outFlow == null, doReset)) { return; } checkNull(inFlow, inPit); RegionMap regionMap = CoverageUtilities.getRegionParamsFromGridCoverage(inPit); cols = regionMap.getCols(); rows = regionMap.getRows(); xRes = regionMap.getXres(); yRes = regionMap.getYres(); dxySqrt = Math.sqrt(xRes * xRes + yRes * yRes); RenderedImage pitfillerRI = inPit.getRenderedImage(); WritableRaster pitfillerWR = CoverageUtilities.renderedImage2DoubleWritableRaster(pitfillerRI, true); RenderedImage flowRI = inFlow.getRenderedImage(); WritableRaster flowWR = CoverageUtilities.renderedImage2ShortWritableRaster(flowRI, true); RandomIter pitRandomIter = RandomIterFactory.create(pitfillerWR, null); // create new matrix double[] orderedelev = new double[cols * rows]; int[] indexes = new int[cols * rows]; int nelev = 0; for( int r = 0; r < rows; r++ ) { if (pm.isCanceled()) { return; } for( int c = 0; c < cols; c++ ) { double pitValue = pitRandomIter.getSampleDouble(c, r, 0); int pos = (r * cols) + c; orderedelev[pos] = pitValue; indexes[pos] = pos + 1; if (!isNovalue(pitValue)) { nelev = nelev + 1; } } } QuickSortAlgorithm t = new QuickSortAlgorithm(pm); t.sort(orderedelev, indexes); pm.message(msg.message("draindir.initializematrix")); // Initialize new RasterData and set value WritableRaster tcaWR = CoverageUtilities.createWritableRaster(cols, rows, Integer.class, null, HMConstants.intNovalue); WritableRaster dirWR = CoverageUtilities.createWritableRaster(cols, rows, Short.class, null, HMConstants.shortNovalue); // it contains the analyzed cells WritableRaster deviationsWR = CoverageUtilities.createWritableRaster(cols, rows, Double.class, null, null); BitMatrix analizedMatrix = new BitMatrix(cols, rows); if (doLad) { orlandiniD8LAD(indexes, deviationsWR, analizedMatrix, pitfillerWR, flowWR, tcaWR, dirWR, nelev); } else { orlandiniD8LTD(indexes, deviationsWR, analizedMatrix, pitfillerWR, flowWR, tcaWR, dirWR, nelev); if (pm.isCanceled()) { return; } // only if required executes this method if (inFlownet != null) { newDirections(pitfillerWR, dirWR); } } if (pm.isCanceled()) { return; } outFlow = CoverageUtilities.buildCoverage("draindir", dirWR, regionMap, inPit.getCoordinateReferenceSystem()); outTca = CoverageUtilities.buildCoverage("tca", tcaWR, regionMap, inPit.getCoordinateReferenceSystem()); }
[ "@", "Execute", "public", "void", "process", "(", ")", "throws", "Exception", "{", "if", "(", "!", "concatOr", "(", "outFlow", "==", "null", ",", "doReset", ")", ")", "{", "return", ";", "}", "checkNull", "(", "inFlow", ",", "inPit", ")", ";", "RegionMap", "regionMap", "=", "CoverageUtilities", ".", "getRegionParamsFromGridCoverage", "(", "inPit", ")", ";", "cols", "=", "regionMap", ".", "getCols", "(", ")", ";", "rows", "=", "regionMap", ".", "getRows", "(", ")", ";", "xRes", "=", "regionMap", ".", "getXres", "(", ")", ";", "yRes", "=", "regionMap", ".", "getYres", "(", ")", ";", "dxySqrt", "=", "Math", ".", "sqrt", "(", "xRes", "*", "xRes", "+", "yRes", "*", "yRes", ")", ";", "RenderedImage", "pitfillerRI", "=", "inPit", ".", "getRenderedImage", "(", ")", ";", "WritableRaster", "pitfillerWR", "=", "CoverageUtilities", ".", "renderedImage2DoubleWritableRaster", "(", "pitfillerRI", ",", "true", ")", ";", "RenderedImage", "flowRI", "=", "inFlow", ".", "getRenderedImage", "(", ")", ";", "WritableRaster", "flowWR", "=", "CoverageUtilities", ".", "renderedImage2ShortWritableRaster", "(", "flowRI", ",", "true", ")", ";", "RandomIter", "pitRandomIter", "=", "RandomIterFactory", ".", "create", "(", "pitfillerWR", ",", "null", ")", ";", "// create new matrix", "double", "[", "]", "orderedelev", "=", "new", "double", "[", "cols", "*", "rows", "]", ";", "int", "[", "]", "indexes", "=", "new", "int", "[", "cols", "*", "rows", "]", ";", "int", "nelev", "=", "0", ";", "for", "(", "int", "r", "=", "0", ";", "r", "<", "rows", ";", "r", "++", ")", "{", "if", "(", "pm", ".", "isCanceled", "(", ")", ")", "{", "return", ";", "}", "for", "(", "int", "c", "=", "0", ";", "c", "<", "cols", ";", "c", "++", ")", "{", "double", "pitValue", "=", "pitRandomIter", ".", "getSampleDouble", "(", "c", ",", "r", ",", "0", ")", ";", "int", "pos", "=", "(", "r", "*", "cols", ")", "+", "c", ";", "orderedelev", "[", "pos", "]", "=", "pitValue", ";", "indexes", "[", "pos", "]", "=", "pos", "+", "1", ";", "if", "(", "!", "isNovalue", "(", "pitValue", ")", ")", "{", "nelev", "=", "nelev", "+", "1", ";", "}", "}", "}", "QuickSortAlgorithm", "t", "=", "new", "QuickSortAlgorithm", "(", "pm", ")", ";", "t", ".", "sort", "(", "orderedelev", ",", "indexes", ")", ";", "pm", ".", "message", "(", "msg", ".", "message", "(", "\"draindir.initializematrix\"", ")", ")", ";", "// Initialize new RasterData and set value", "WritableRaster", "tcaWR", "=", "CoverageUtilities", ".", "createWritableRaster", "(", "cols", ",", "rows", ",", "Integer", ".", "class", ",", "null", ",", "HMConstants", ".", "intNovalue", ")", ";", "WritableRaster", "dirWR", "=", "CoverageUtilities", ".", "createWritableRaster", "(", "cols", ",", "rows", ",", "Short", ".", "class", ",", "null", ",", "HMConstants", ".", "shortNovalue", ")", ";", "// it contains the analyzed cells", "WritableRaster", "deviationsWR", "=", "CoverageUtilities", ".", "createWritableRaster", "(", "cols", ",", "rows", ",", "Double", ".", "class", ",", "null", ",", "null", ")", ";", "BitMatrix", "analizedMatrix", "=", "new", "BitMatrix", "(", "cols", ",", "rows", ")", ";", "if", "(", "doLad", ")", "{", "orlandiniD8LAD", "(", "indexes", ",", "deviationsWR", ",", "analizedMatrix", ",", "pitfillerWR", ",", "flowWR", ",", "tcaWR", ",", "dirWR", ",", "nelev", ")", ";", "}", "else", "{", "orlandiniD8LTD", "(", "indexes", ",", "deviationsWR", ",", "analizedMatrix", ",", "pitfillerWR", ",", "flowWR", ",", "tcaWR", ",", "dirWR", ",", "nelev", ")", ";", "if", "(", "pm", ".", "isCanceled", "(", ")", ")", "{", "return", ";", "}", "// only if required executes this method", "if", "(", "inFlownet", "!=", "null", ")", "{", "newDirections", "(", "pitfillerWR", ",", "dirWR", ")", ";", "}", "}", "if", "(", "pm", ".", "isCanceled", "(", ")", ")", "{", "return", ";", "}", "outFlow", "=", "CoverageUtilities", ".", "buildCoverage", "(", "\"draindir\"", ",", "dirWR", ",", "regionMap", ",", "inPit", ".", "getCoordinateReferenceSystem", "(", ")", ")", ";", "outTca", "=", "CoverageUtilities", ".", "buildCoverage", "(", "\"tca\"", ",", "tcaWR", ",", "regionMap", ",", "inPit", ".", "getCoordinateReferenceSystem", "(", ")", ")", ";", "}" ]
Calculates new drainage directions @throws Exception
[ "Calculates", "new", "drainage", "directions" ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/hmachine/src/main/java/org/hortonmachine/hmachine/modules/geomorphology/draindir/OmsDrainDir.java#L144-L215
137,770
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/io/geopaparazzi/geopap4/DaoMetadata.java
DaoMetadata.fillProjectMetadata
public static void fillProjectMetadata(Connection connection, String name, String description, String notes, String creationUser) throws Exception { Date creationDate = new Date(); if (name == null) { name = "project-" + ETimeUtilities.INSTANCE.TIME_FORMATTER_LOCAL.format(creationDate); } if (description == null) { description = EMPTY_VALUE; } if (notes == null) { notes = EMPTY_VALUE; } if (creationUser == null) { creationUser = "dummy user"; } insertPair(connection, MetadataTableFields.KEY_NAME.getFieldName(), name); insertPair(connection, MetadataTableFields.KEY_DESCRIPTION.getFieldName(), description); insertPair(connection, MetadataTableFields.KEY_NOTES.getFieldName(), notes); insertPair(connection, MetadataTableFields.KEY_CREATIONTS.getFieldName(), String.valueOf(creationDate.getTime())); insertPair(connection, MetadataTableFields.KEY_LASTTS.getFieldName(), EMPTY_VALUE); insertPair(connection, MetadataTableFields.KEY_CREATIONUSER.getFieldName(), creationUser); insertPair(connection, MetadataTableFields.KEY_LASTUSER.getFieldName(), EMPTY_VALUE); }
java
public static void fillProjectMetadata(Connection connection, String name, String description, String notes, String creationUser) throws Exception { Date creationDate = new Date(); if (name == null) { name = "project-" + ETimeUtilities.INSTANCE.TIME_FORMATTER_LOCAL.format(creationDate); } if (description == null) { description = EMPTY_VALUE; } if (notes == null) { notes = EMPTY_VALUE; } if (creationUser == null) { creationUser = "dummy user"; } insertPair(connection, MetadataTableFields.KEY_NAME.getFieldName(), name); insertPair(connection, MetadataTableFields.KEY_DESCRIPTION.getFieldName(), description); insertPair(connection, MetadataTableFields.KEY_NOTES.getFieldName(), notes); insertPair(connection, MetadataTableFields.KEY_CREATIONTS.getFieldName(), String.valueOf(creationDate.getTime())); insertPair(connection, MetadataTableFields.KEY_LASTTS.getFieldName(), EMPTY_VALUE); insertPair(connection, MetadataTableFields.KEY_CREATIONUSER.getFieldName(), creationUser); insertPair(connection, MetadataTableFields.KEY_LASTUSER.getFieldName(), EMPTY_VALUE); }
[ "public", "static", "void", "fillProjectMetadata", "(", "Connection", "connection", ",", "String", "name", ",", "String", "description", ",", "String", "notes", ",", "String", "creationUser", ")", "throws", "Exception", "{", "Date", "creationDate", "=", "new", "Date", "(", ")", ";", "if", "(", "name", "==", "null", ")", "{", "name", "=", "\"project-\"", "+", "ETimeUtilities", ".", "INSTANCE", ".", "TIME_FORMATTER_LOCAL", ".", "format", "(", "creationDate", ")", ";", "}", "if", "(", "description", "==", "null", ")", "{", "description", "=", "EMPTY_VALUE", ";", "}", "if", "(", "notes", "==", "null", ")", "{", "notes", "=", "EMPTY_VALUE", ";", "}", "if", "(", "creationUser", "==", "null", ")", "{", "creationUser", "=", "\"dummy user\"", ";", "}", "insertPair", "(", "connection", ",", "MetadataTableFields", ".", "KEY_NAME", ".", "getFieldName", "(", ")", ",", "name", ")", ";", "insertPair", "(", "connection", ",", "MetadataTableFields", ".", "KEY_DESCRIPTION", ".", "getFieldName", "(", ")", ",", "description", ")", ";", "insertPair", "(", "connection", ",", "MetadataTableFields", ".", "KEY_NOTES", ".", "getFieldName", "(", ")", ",", "notes", ")", ";", "insertPair", "(", "connection", ",", "MetadataTableFields", ".", "KEY_CREATIONTS", ".", "getFieldName", "(", ")", ",", "String", ".", "valueOf", "(", "creationDate", ".", "getTime", "(", ")", ")", ")", ";", "insertPair", "(", "connection", ",", "MetadataTableFields", ".", "KEY_LASTTS", ".", "getFieldName", "(", ")", ",", "EMPTY_VALUE", ")", ";", "insertPair", "(", "connection", ",", "MetadataTableFields", ".", "KEY_CREATIONUSER", ".", "getFieldName", "(", ")", ",", "creationUser", ")", ";", "insertPair", "(", "connection", ",", "MetadataTableFields", ".", "KEY_LASTUSER", ".", "getFieldName", "(", ")", ",", "EMPTY_VALUE", ")", ";", "}" ]
Populate the project metadata table. @param name the project name @param description an optional description. @param notes optional notes. @param creationUser the user creating the project. @throws java.io.IOException if something goes wrong.
[ "Populate", "the", "project", "metadata", "table", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/io/geopaparazzi/geopap4/DaoMetadata.java#L74-L97
137,771
TheHortonMachine/hortonmachine
gears/src/main/java/oms3/compiler/MemoryOutputJavaFileManager.java
MemoryOutputJavaFileManager.listClassesFromUrl
protected List<JavaFileObject> listClassesFromUrl(URL base, String packageName) throws IOException { //TODO this will only work with file:// not jar:// if (base == null) { throw new NullPointerException("base == null"); } List<JavaFileObject> list = new ArrayList<JavaFileObject>(); URLConnection connection = base.openConnection(); connection.connect(); String encoding = connection.getContentEncoding(); if (encoding == null) { encoding = "UTF-8"; } BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), encoding)); try { String curLine; do { curLine = reader.readLine(); if (curLine != null && curLine.endsWith(".class")) { try { String curSimpleName = curLine.substring(0, curLine.length() - ".class".length()); String binaryName; if (packageName == null) { binaryName = curSimpleName; } else { binaryName = packageName + "." + curSimpleName; } list.add(new UrlJavaFileObject(curLine, new URL(base, curLine), Kind.CLASS, binaryName)); } catch (URISyntaxException e) { throw new IOException("Error parsing URL " + curLine + ".", e); } } } while (curLine != null); } finally { reader.close(); } return list; }
java
protected List<JavaFileObject> listClassesFromUrl(URL base, String packageName) throws IOException { //TODO this will only work with file:// not jar:// if (base == null) { throw new NullPointerException("base == null"); } List<JavaFileObject> list = new ArrayList<JavaFileObject>(); URLConnection connection = base.openConnection(); connection.connect(); String encoding = connection.getContentEncoding(); if (encoding == null) { encoding = "UTF-8"; } BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), encoding)); try { String curLine; do { curLine = reader.readLine(); if (curLine != null && curLine.endsWith(".class")) { try { String curSimpleName = curLine.substring(0, curLine.length() - ".class".length()); String binaryName; if (packageName == null) { binaryName = curSimpleName; } else { binaryName = packageName + "." + curSimpleName; } list.add(new UrlJavaFileObject(curLine, new URL(base, curLine), Kind.CLASS, binaryName)); } catch (URISyntaxException e) { throw new IOException("Error parsing URL " + curLine + ".", e); } } } while (curLine != null); } finally { reader.close(); } return list; }
[ "protected", "List", "<", "JavaFileObject", ">", "listClassesFromUrl", "(", "URL", "base", ",", "String", "packageName", ")", "throws", "IOException", "{", "//TODO this will only work with file:// not jar://", "if", "(", "base", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"base == null\"", ")", ";", "}", "List", "<", "JavaFileObject", ">", "list", "=", "new", "ArrayList", "<", "JavaFileObject", ">", "(", ")", ";", "URLConnection", "connection", "=", "base", ".", "openConnection", "(", ")", ";", "connection", ".", "connect", "(", ")", ";", "String", "encoding", "=", "connection", ".", "getContentEncoding", "(", ")", ";", "if", "(", "encoding", "==", "null", ")", "{", "encoding", "=", "\"UTF-8\"", ";", "}", "BufferedReader", "reader", "=", "new", "BufferedReader", "(", "new", "InputStreamReader", "(", "connection", ".", "getInputStream", "(", ")", ",", "encoding", ")", ")", ";", "try", "{", "String", "curLine", ";", "do", "{", "curLine", "=", "reader", ".", "readLine", "(", ")", ";", "if", "(", "curLine", "!=", "null", "&&", "curLine", ".", "endsWith", "(", "\".class\"", ")", ")", "{", "try", "{", "String", "curSimpleName", "=", "curLine", ".", "substring", "(", "0", ",", "curLine", ".", "length", "(", ")", "-", "\".class\"", ".", "length", "(", ")", ")", ";", "String", "binaryName", ";", "if", "(", "packageName", "==", "null", ")", "{", "binaryName", "=", "curSimpleName", ";", "}", "else", "{", "binaryName", "=", "packageName", "+", "\".\"", "+", "curSimpleName", ";", "}", "list", ".", "add", "(", "new", "UrlJavaFileObject", "(", "curLine", ",", "new", "URL", "(", "base", ",", "curLine", ")", ",", "Kind", ".", "CLASS", ",", "binaryName", ")", ")", ";", "}", "catch", "(", "URISyntaxException", "e", ")", "{", "throw", "new", "IOException", "(", "\"Error parsing URL \"", "+", "curLine", "+", "\".\"", ",", "e", ")", ";", "}", "}", "}", "while", "(", "curLine", "!=", "null", ")", ";", "}", "finally", "{", "reader", ".", "close", "(", ")", ";", "}", "return", "list", ";", "}" ]
Lists all files at a specified URL. @param base the URL. @param packageName the package name of classes to list. @return a list of class files. @throws IOException if an I/O error occurs.
[ "Lists", "all", "files", "at", "a", "specified", "URL", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/oms3/compiler/MemoryOutputJavaFileManager.java#L175-L214
137,772
TheHortonMachine/hortonmachine
gears/src/main/java/oms3/io/DataIO.java
DataIO.sliceByTime
public static int[] sliceByTime(CSTable table, int timeCol, Date start, Date end) { if (end.before(start)) { throw new IllegalArgumentException("end<start"); } if (timeCol < 0) { throw new IllegalArgumentException("timeCol :" + timeCol); } int s = -1; int e = -1; int i = -1; for (String[] col : table.rows()) { i++; Date d = Conversions.convert(col[timeCol], Date.class); if (s == -1 && (start.before(d) || start.equals(d))) { s = i; } if (e == -1 && (end.before(d) || end.equals(d))) { e = i; break; } } return new int[]{s, e}; }
java
public static int[] sliceByTime(CSTable table, int timeCol, Date start, Date end) { if (end.before(start)) { throw new IllegalArgumentException("end<start"); } if (timeCol < 0) { throw new IllegalArgumentException("timeCol :" + timeCol); } int s = -1; int e = -1; int i = -1; for (String[] col : table.rows()) { i++; Date d = Conversions.convert(col[timeCol], Date.class); if (s == -1 && (start.before(d) || start.equals(d))) { s = i; } if (e == -1 && (end.before(d) || end.equals(d))) { e = i; break; } } return new int[]{s, e}; }
[ "public", "static", "int", "[", "]", "sliceByTime", "(", "CSTable", "table", ",", "int", "timeCol", ",", "Date", "start", ",", "Date", "end", ")", "{", "if", "(", "end", ".", "before", "(", "start", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"end<start\"", ")", ";", "}", "if", "(", "timeCol", "<", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"timeCol :\"", "+", "timeCol", ")", ";", "}", "int", "s", "=", "-", "1", ";", "int", "e", "=", "-", "1", ";", "int", "i", "=", "-", "1", ";", "for", "(", "String", "[", "]", "col", ":", "table", ".", "rows", "(", ")", ")", "{", "i", "++", ";", "Date", "d", "=", "Conversions", ".", "convert", "(", "col", "[", "timeCol", "]", ",", "Date", ".", "class", ")", ";", "if", "(", "s", "==", "-", "1", "&&", "(", "start", ".", "before", "(", "d", ")", "||", "start", ".", "equals", "(", "d", ")", ")", ")", "{", "s", "=", "i", ";", "}", "if", "(", "e", "==", "-", "1", "&&", "(", "end", ".", "before", "(", "d", ")", "||", "end", ".", "equals", "(", "d", ")", ")", ")", "{", "e", "=", "i", ";", "break", ";", "}", "}", "return", "new", "int", "[", "]", "{", "s", ",", "e", "}", ";", "}" ]
Get a slice of rows out of the table matching the time window @param table @param timeCol @param start @param end @return the first and last row that matches the time window start->end
[ "Get", "a", "slice", "of", "rows", "out", "of", "the", "table", "matching", "the", "time", "window" ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/oms3/io/DataIO.java#L468-L490
137,773
TheHortonMachine/hortonmachine
gears/src/main/java/oms3/io/DataIO.java
DataIO.getProperties
public static AbstractTableModel getProperties(final CSProperties p) { return new AbstractTableModel() { @Override public int getRowCount() { return p.keySet().size(); } @Override public int getColumnCount() { return 2; } @Override public Object getValueAt(int rowIndex, int columnIndex) { if (columnIndex == 0) { return " " + p.keySet().toArray()[rowIndex]; } else { return p.values().toArray()[rowIndex]; } } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return columnIndex == 1; } @Override public void setValueAt(Object aValue, int rowIndex, int columnIndex) { if (columnIndex == 1) { String[] keys = p.keySet().toArray(new String[0]); p.put(keys[rowIndex], aValue.toString()); } } @Override public String getColumnName(int column) { return column == 0 ? "Name" : "Value"; } @Override public Class<?> getColumnClass(int columnIndex) { return String.class; } }; }
java
public static AbstractTableModel getProperties(final CSProperties p) { return new AbstractTableModel() { @Override public int getRowCount() { return p.keySet().size(); } @Override public int getColumnCount() { return 2; } @Override public Object getValueAt(int rowIndex, int columnIndex) { if (columnIndex == 0) { return " " + p.keySet().toArray()[rowIndex]; } else { return p.values().toArray()[rowIndex]; } } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return columnIndex == 1; } @Override public void setValueAt(Object aValue, int rowIndex, int columnIndex) { if (columnIndex == 1) { String[] keys = p.keySet().toArray(new String[0]); p.put(keys[rowIndex], aValue.toString()); } } @Override public String getColumnName(int column) { return column == 0 ? "Name" : "Value"; } @Override public Class<?> getColumnClass(int columnIndex) { return String.class; } }; }
[ "public", "static", "AbstractTableModel", "getProperties", "(", "final", "CSProperties", "p", ")", "{", "return", "new", "AbstractTableModel", "(", ")", "{", "@", "Override", "public", "int", "getRowCount", "(", ")", "{", "return", "p", ".", "keySet", "(", ")", ".", "size", "(", ")", ";", "}", "@", "Override", "public", "int", "getColumnCount", "(", ")", "{", "return", "2", ";", "}", "@", "Override", "public", "Object", "getValueAt", "(", "int", "rowIndex", ",", "int", "columnIndex", ")", "{", "if", "(", "columnIndex", "==", "0", ")", "{", "return", "\" \"", "+", "p", ".", "keySet", "(", ")", ".", "toArray", "(", ")", "[", "rowIndex", "]", ";", "}", "else", "{", "return", "p", ".", "values", "(", ")", ".", "toArray", "(", ")", "[", "rowIndex", "]", ";", "}", "}", "@", "Override", "public", "boolean", "isCellEditable", "(", "int", "rowIndex", ",", "int", "columnIndex", ")", "{", "return", "columnIndex", "==", "1", ";", "}", "@", "Override", "public", "void", "setValueAt", "(", "Object", "aValue", ",", "int", "rowIndex", ",", "int", "columnIndex", ")", "{", "if", "(", "columnIndex", "==", "1", ")", "{", "String", "[", "]", "keys", "=", "p", ".", "keySet", "(", ")", ".", "toArray", "(", "new", "String", "[", "0", "]", ")", ";", "p", ".", "put", "(", "keys", "[", "rowIndex", "]", ",", "aValue", ".", "toString", "(", ")", ")", ";", "}", "}", "@", "Override", "public", "String", "getColumnName", "(", "int", "column", ")", "{", "return", "column", "==", "0", "?", "\"Name\"", ":", "\"Value\"", ";", "}", "@", "Override", "public", "Class", "<", "?", ">", "getColumnClass", "(", "int", "columnIndex", ")", "{", "return", "String", ".", "class", ";", "}", "}", ";", "}" ]
Get the KVP as table. @param p @return an AbstractTableModel for properties (KVP)
[ "Get", "the", "KVP", "as", "table", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/oms3/io/DataIO.java#L555-L601
137,774
TheHortonMachine/hortonmachine
gears/src/main/java/oms3/io/DataIO.java
DataIO.toArrayString
public static String toArrayString(String[] arr) { StringBuilder b = new StringBuilder(); b.append('{'); for (int i = 0; i < arr.length; i++) { b.append(arr[i]); if (i < arr.length - 1) { b.append(','); } } b.append('}'); return b.toString(); }
java
public static String toArrayString(String[] arr) { StringBuilder b = new StringBuilder(); b.append('{'); for (int i = 0; i < arr.length; i++) { b.append(arr[i]); if (i < arr.length - 1) { b.append(','); } } b.append('}'); return b.toString(); }
[ "public", "static", "String", "toArrayString", "(", "String", "[", "]", "arr", ")", "{", "StringBuilder", "b", "=", "new", "StringBuilder", "(", ")", ";", "b", ".", "append", "(", "'", "'", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "arr", ".", "length", ";", "i", "++", ")", "{", "b", ".", "append", "(", "arr", "[", "i", "]", ")", ";", "if", "(", "i", "<", "arr", ".", "length", "-", "1", ")", "{", "b", ".", "append", "(", "'", "'", ")", ";", "}", "}", "b", ".", "append", "(", "'", "'", ")", ";", "return", "b", ".", "toString", "(", ")", ";", "}" ]
Create array string. @param arr @return an array String.
[ "Create", "array", "string", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/oms3/io/DataIO.java#L789-L800
137,775
TheHortonMachine/hortonmachine
gears/src/main/java/oms3/io/DataIO.java
DataIO.getColumnDoubleValues
public static Double[] getColumnDoubleValues(CSTable t, String columnName) { int col = columnIndex(t, columnName); if (col == -1) { throw new IllegalArgumentException("No such column: " + columnName); } List<Double> l = new ArrayList<Double>(); for (String[] s : t.rows()) { l.add(new Double(s[col])); } return l.toArray(new Double[0]); }
java
public static Double[] getColumnDoubleValues(CSTable t, String columnName) { int col = columnIndex(t, columnName); if (col == -1) { throw new IllegalArgumentException("No such column: " + columnName); } List<Double> l = new ArrayList<Double>(); for (String[] s : t.rows()) { l.add(new Double(s[col])); } return l.toArray(new Double[0]); }
[ "public", "static", "Double", "[", "]", "getColumnDoubleValues", "(", "CSTable", "t", ",", "String", "columnName", ")", "{", "int", "col", "=", "columnIndex", "(", "t", ",", "columnName", ")", ";", "if", "(", "col", "==", "-", "1", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"No such column: \"", "+", "columnName", ")", ";", "}", "List", "<", "Double", ">", "l", "=", "new", "ArrayList", "<", "Double", ">", "(", ")", ";", "for", "(", "String", "[", "]", "s", ":", "t", ".", "rows", "(", ")", ")", "{", "l", ".", "add", "(", "new", "Double", "(", "s", "[", "col", "]", ")", ")", ";", "}", "return", "l", ".", "toArray", "(", "new", "Double", "[", "0", "]", ")", ";", "}" ]
Get a column as an int array. @param t @param columnName @return the column data as doubles.
[ "Get", "a", "column", "as", "an", "int", "array", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/oms3/io/DataIO.java#L941-L951
137,776
TheHortonMachine/hortonmachine
gears/src/main/java/oms3/io/DataIO.java
DataIO.getDate
public static Date getDate(CSProperties p, String key) throws ParseException { String val = p.get(key).toString(); if (val == null) { throw new IllegalArgumentException(key); } String f = p.getInfo(key).get(KEY_FORMAT); DateFormat fmt = new SimpleDateFormat(f == null ? ISO8601 : f); return fmt.parse(val); }
java
public static Date getDate(CSProperties p, String key) throws ParseException { String val = p.get(key).toString(); if (val == null) { throw new IllegalArgumentException(key); } String f = p.getInfo(key).get(KEY_FORMAT); DateFormat fmt = new SimpleDateFormat(f == null ? ISO8601 : f); return fmt.parse(val); }
[ "public", "static", "Date", "getDate", "(", "CSProperties", "p", ",", "String", "key", ")", "throws", "ParseException", "{", "String", "val", "=", "p", ".", "get", "(", "key", ")", ".", "toString", "(", ")", ";", "if", "(", "val", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "key", ")", ";", "}", "String", "f", "=", "p", ".", "getInfo", "(", "key", ")", ".", "get", "(", "KEY_FORMAT", ")", ";", "DateFormat", "fmt", "=", "new", "SimpleDateFormat", "(", "f", "==", "null", "?", "ISO8601", ":", "f", ")", ";", "return", "fmt", ".", "parse", "(", "val", ")", ";", "}" ]
Get a value as date. @param p @param key @return a property as Date @throws java.text.ParseException
[ "Get", "a", "value", "as", "date", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/oms3/io/DataIO.java#L961-L969
137,777
TheHortonMachine/hortonmachine
gears/src/main/java/oms3/io/DataIO.java
DataIO.getInt
public static int getInt(CSProperties p, String key) throws ParseException { String val = p.get(key).toString(); if (val == null) { throw new IllegalArgumentException(key); } return Integer.parseInt(val); }
java
public static int getInt(CSProperties p, String key) throws ParseException { String val = p.get(key).toString(); if (val == null) { throw new IllegalArgumentException(key); } return Integer.parseInt(val); }
[ "public", "static", "int", "getInt", "(", "CSProperties", "p", ",", "String", "key", ")", "throws", "ParseException", "{", "String", "val", "=", "p", ".", "get", "(", "key", ")", ".", "toString", "(", ")", ";", "if", "(", "val", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "key", ")", ";", "}", "return", "Integer", ".", "parseInt", "(", "val", ")", ";", "}" ]
Get a value as integer. @param p @param key @return a property value as integer. @throws java.text.ParseException
[ "Get", "a", "value", "as", "integer", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/oms3/io/DataIO.java#L978-L984
137,778
TheHortonMachine/hortonmachine
gears/src/main/java/oms3/io/DataIO.java
DataIO.print
public static void print(CSProperties props, PrintWriter out) { out.println(PROPERTIES + "," + CSVParser.printLine(props.getName())); for (String key : props.getInfo().keySet()) { out.println(" " + CSVParser.printLine(key, props.getInfo().get(key))); } out.println(); for (String key : props.keySet()) { out.println(PROPERTY + "," + CSVParser.printLine(key, props.get(key).toString())); for (String key1 : props.getInfo(key).keySet()) { out.println(" " + CSVParser.printLine(key1, props.getInfo(key).get(key1))); } out.println(); } out.println(); out.flush(); }
java
public static void print(CSProperties props, PrintWriter out) { out.println(PROPERTIES + "," + CSVParser.printLine(props.getName())); for (String key : props.getInfo().keySet()) { out.println(" " + CSVParser.printLine(key, props.getInfo().get(key))); } out.println(); for (String key : props.keySet()) { out.println(PROPERTY + "," + CSVParser.printLine(key, props.get(key).toString())); for (String key1 : props.getInfo(key).keySet()) { out.println(" " + CSVParser.printLine(key1, props.getInfo(key).get(key1))); } out.println(); } out.println(); out.flush(); }
[ "public", "static", "void", "print", "(", "CSProperties", "props", ",", "PrintWriter", "out", ")", "{", "out", ".", "println", "(", "PROPERTIES", "+", "\",\"", "+", "CSVParser", ".", "printLine", "(", "props", ".", "getName", "(", ")", ")", ")", ";", "for", "(", "String", "key", ":", "props", ".", "getInfo", "(", ")", ".", "keySet", "(", ")", ")", "{", "out", ".", "println", "(", "\" \"", "+", "CSVParser", ".", "printLine", "(", "key", ",", "props", ".", "getInfo", "(", ")", ".", "get", "(", "key", ")", ")", ")", ";", "}", "out", ".", "println", "(", ")", ";", "for", "(", "String", "key", ":", "props", ".", "keySet", "(", ")", ")", "{", "out", ".", "println", "(", "PROPERTY", "+", "\",\"", "+", "CSVParser", ".", "printLine", "(", "key", ",", "props", ".", "get", "(", "key", ")", ".", "toString", "(", ")", ")", ")", ";", "for", "(", "String", "key1", ":", "props", ".", "getInfo", "(", "key", ")", ".", "keySet", "(", ")", ")", "{", "out", ".", "println", "(", "\" \"", "+", "CSVParser", ".", "printLine", "(", "key1", ",", "props", ".", "getInfo", "(", "key", ")", ".", "get", "(", "key1", ")", ")", ")", ";", "}", "out", ".", "println", "(", ")", ";", "}", "out", ".", "println", "(", ")", ";", "out", ".", "flush", "(", ")", ";", "}" ]
Print CSProperties. @param props the Properties to print @param out the output writer to print to.
[ "Print", "CSProperties", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/oms3/io/DataIO.java#L1010-L1025
137,779
TheHortonMachine/hortonmachine
gears/src/main/java/oms3/io/DataIO.java
DataIO.print
public static void print(CSTable table, PrintWriter out) { out.println(TABLE + "," + CSVParser.printLine(table.getName())); for (String key : table.getInfo().keySet()) { out.println(CSVParser.printLine(key, table.getInfo().get(key))); } if (table.getColumnCount() < 1) { out.flush(); return; } out.print(HEADER); for (int i = 1; i <= table.getColumnCount(); i++) { out.print("," + table.getColumnName(i)); } out.println(); Map<String, String> m = table.getColumnInfo(1); for (String key : m.keySet()) { out.print(key); for (int i = 1; i <= table.getColumnCount(); i++) { out.print("," + table.getColumnInfo(i).get(key)); } out.println(); } for (String[] row : table.rows()) { for (int i = 1; i < row.length; i++) { out.print("," + row[i]); } out.println(); } out.println(); out.flush(); }
java
public static void print(CSTable table, PrintWriter out) { out.println(TABLE + "," + CSVParser.printLine(table.getName())); for (String key : table.getInfo().keySet()) { out.println(CSVParser.printLine(key, table.getInfo().get(key))); } if (table.getColumnCount() < 1) { out.flush(); return; } out.print(HEADER); for (int i = 1; i <= table.getColumnCount(); i++) { out.print("," + table.getColumnName(i)); } out.println(); Map<String, String> m = table.getColumnInfo(1); for (String key : m.keySet()) { out.print(key); for (int i = 1; i <= table.getColumnCount(); i++) { out.print("," + table.getColumnInfo(i).get(key)); } out.println(); } for (String[] row : table.rows()) { for (int i = 1; i < row.length; i++) { out.print("," + row[i]); } out.println(); } out.println(); out.flush(); }
[ "public", "static", "void", "print", "(", "CSTable", "table", ",", "PrintWriter", "out", ")", "{", "out", ".", "println", "(", "TABLE", "+", "\",\"", "+", "CSVParser", ".", "printLine", "(", "table", ".", "getName", "(", ")", ")", ")", ";", "for", "(", "String", "key", ":", "table", ".", "getInfo", "(", ")", ".", "keySet", "(", ")", ")", "{", "out", ".", "println", "(", "CSVParser", ".", "printLine", "(", "key", ",", "table", ".", "getInfo", "(", ")", ".", "get", "(", "key", ")", ")", ")", ";", "}", "if", "(", "table", ".", "getColumnCount", "(", ")", "<", "1", ")", "{", "out", ".", "flush", "(", ")", ";", "return", ";", "}", "out", ".", "print", "(", "HEADER", ")", ";", "for", "(", "int", "i", "=", "1", ";", "i", "<=", "table", ".", "getColumnCount", "(", ")", ";", "i", "++", ")", "{", "out", ".", "print", "(", "\",\"", "+", "table", ".", "getColumnName", "(", "i", ")", ")", ";", "}", "out", ".", "println", "(", ")", ";", "Map", "<", "String", ",", "String", ">", "m", "=", "table", ".", "getColumnInfo", "(", "1", ")", ";", "for", "(", "String", "key", ":", "m", ".", "keySet", "(", ")", ")", "{", "out", ".", "print", "(", "key", ")", ";", "for", "(", "int", "i", "=", "1", ";", "i", "<=", "table", ".", "getColumnCount", "(", ")", ";", "i", "++", ")", "{", "out", ".", "print", "(", "\",\"", "+", "table", ".", "getColumnInfo", "(", "i", ")", ".", "get", "(", "key", ")", ")", ";", "}", "out", ".", "println", "(", ")", ";", "}", "for", "(", "String", "[", "]", "row", ":", "table", ".", "rows", "(", ")", ")", "{", "for", "(", "int", "i", "=", "1", ";", "i", "<", "row", ".", "length", ";", "i", "++", ")", "{", "out", ".", "print", "(", "\",\"", "+", "row", "[", "i", "]", ")", ";", "}", "out", ".", "println", "(", ")", ";", "}", "out", ".", "println", "(", ")", ";", "out", ".", "flush", "(", ")", ";", "}" ]
Print a CSTable to a PrintWriter @param table the table to print @param out the writer to write to
[ "Print", "a", "CSTable", "to", "a", "PrintWriter" ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/oms3/io/DataIO.java#L1043-L1073
137,780
TheHortonMachine/hortonmachine
gears/src/main/java/oms3/io/DataIO.java
DataIO.save
public static void save(CSTable table, File file) throws IOException { PrintWriter w = new PrintWriter(file); print(table, w); w.close(); }
java
public static void save(CSTable table, File file) throws IOException { PrintWriter w = new PrintWriter(file); print(table, w); w.close(); }
[ "public", "static", "void", "save", "(", "CSTable", "table", ",", "File", "file", ")", "throws", "IOException", "{", "PrintWriter", "w", "=", "new", "PrintWriter", "(", "file", ")", ";", "print", "(", "table", ",", "w", ")", ";", "w", ".", "close", "(", ")", ";", "}" ]
Saves a table to a file. @param table the table to save @param file the file to store it in (overwritten, if exists) @throws IOException
[ "Saves", "a", "table", "to", "a", "file", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/oms3/io/DataIO.java#L1081-L1085
137,781
TheHortonMachine/hortonmachine
gears/src/main/java/oms3/io/DataIO.java
DataIO.properties
public static CSProperties properties(Reader r, String name) throws IOException { return new CSVProperties(r, name); }
java
public static CSProperties properties(Reader r, String name) throws IOException { return new CSVProperties(r, name); }
[ "public", "static", "CSProperties", "properties", "(", "Reader", "r", ",", "String", "name", ")", "throws", "IOException", "{", "return", "new", "CSVProperties", "(", "r", ",", "name", ")", ";", "}" ]
Parse properties from a reader @param r the Reader @param name the name of the properties @return properties from a file. @throws java.io.IOException
[ "Parse", "properties", "from", "a", "reader" ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/oms3/io/DataIO.java#L1095-L1097
137,782
TheHortonMachine/hortonmachine
gears/src/main/java/oms3/io/DataIO.java
DataIO.properties
public static CSProperties properties(Reader[] r, String name) throws IOException { CSVProperties p = new CSVProperties(r[0], name); for (int i = 1; i < r.length; i++) { CSVParser csv = new CSVParser(r[i], CSVStrategy.DEFAULT_STRATEGY); locate(csv, name, PROPERTIES, PROPERTIES1); p.readProps(csv); r[i].close(); } return p; }
java
public static CSProperties properties(Reader[] r, String name) throws IOException { CSVProperties p = new CSVProperties(r[0], name); for (int i = 1; i < r.length; i++) { CSVParser csv = new CSVParser(r[i], CSVStrategy.DEFAULT_STRATEGY); locate(csv, name, PROPERTIES, PROPERTIES1); p.readProps(csv); r[i].close(); } return p; }
[ "public", "static", "CSProperties", "properties", "(", "Reader", "[", "]", "r", ",", "String", "name", ")", "throws", "IOException", "{", "CSVProperties", "p", "=", "new", "CSVProperties", "(", "r", "[", "0", "]", ",", "name", ")", ";", "for", "(", "int", "i", "=", "1", ";", "i", "<", "r", ".", "length", ";", "i", "++", ")", "{", "CSVParser", "csv", "=", "new", "CSVParser", "(", "r", "[", "i", "]", ",", "CSVStrategy", ".", "DEFAULT_STRATEGY", ")", ";", "locate", "(", "csv", ",", "name", ",", "PROPERTIES", ",", "PROPERTIES1", ")", ";", "p", ".", "readProps", "(", "csv", ")", ";", "r", "[", "i", "]", ".", "close", "(", ")", ";", "}", "return", "p", ";", "}" ]
Create a CSProperty from an array of reader. @param r @param name @return merged properties. @throws java.io.IOException
[ "Create", "a", "CSProperty", "from", "an", "array", "of", "reader", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/oms3/io/DataIO.java#L1106-L1115
137,783
TheHortonMachine/hortonmachine
gears/src/main/java/oms3/io/DataIO.java
DataIO.merge
public static void merge(CSProperties base, CSProperties overlay) { for (String key : overlay.keySet()) { if (base.getInfo(key).containsKey("public")) { base.put(key, overlay.get(key)); } else { throw new IllegalArgumentException("Not public: " + key); } } }
java
public static void merge(CSProperties base, CSProperties overlay) { for (String key : overlay.keySet()) { if (base.getInfo(key).containsKey("public")) { base.put(key, overlay.get(key)); } else { throw new IllegalArgumentException("Not public: " + key); } } }
[ "public", "static", "void", "merge", "(", "CSProperties", "base", ",", "CSProperties", "overlay", ")", "{", "for", "(", "String", "key", ":", "overlay", ".", "keySet", "(", ")", ")", "{", "if", "(", "base", ".", "getInfo", "(", "key", ")", ".", "containsKey", "(", "\"public\"", ")", ")", "{", "base", ".", "put", "(", "key", ",", "overlay", ".", "get", "(", "key", ")", ")", ";", "}", "else", "{", "throw", "new", "IllegalArgumentException", "(", "\"Not public: \"", "+", "key", ")", ";", "}", "}", "}" ]
Merges two Properties, respects permissions @param base @param overlay
[ "Merges", "two", "Properties", "respects", "permissions" ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/oms3/io/DataIO.java#L1123-L1131
137,784
TheHortonMachine/hortonmachine
gears/src/main/java/oms3/io/DataIO.java
DataIO.properties
public static Properties properties(CSProperties p) { Properties pr = new Properties(); pr.putAll(p); return pr; }
java
public static Properties properties(CSProperties p) { Properties pr = new Properties(); pr.putAll(p); return pr; }
[ "public", "static", "Properties", "properties", "(", "CSProperties", "p", ")", "{", "Properties", "pr", "=", "new", "Properties", "(", ")", ";", "pr", ".", "putAll", "(", "p", ")", ";", "return", "pr", ";", "}" ]
Convert CSProperties into Properties @param p @return the Properties.
[ "Convert", "CSProperties", "into", "Properties" ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/oms3/io/DataIO.java#L1138-L1142
137,785
TheHortonMachine/hortonmachine
gears/src/main/java/oms3/io/DataIO.java
DataIO.table
public static CSTable table(File file, String name) throws IOException { return new FileTable(file, name); }
java
public static CSTable table(File file, String name) throws IOException { return new FileTable(file, name); }
[ "public", "static", "CSTable", "table", "(", "File", "file", ",", "String", "name", ")", "throws", "IOException", "{", "return", "new", "FileTable", "(", "file", ",", "name", ")", ";", "}" ]
Parse a table from a given File. @param file @param name @return a CSTable. @throws java.io.IOException
[ "Parse", "a", "table", "from", "a", "given", "File", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/oms3/io/DataIO.java#L1185-L1187
137,786
TheHortonMachine/hortonmachine
gears/src/main/java/oms3/io/DataIO.java
DataIO.table
public static CSTable table(String s, String name) throws IOException { return new StringTable(s, name); }
java
public static CSTable table(String s, String name) throws IOException { return new StringTable(s, name); }
[ "public", "static", "CSTable", "table", "(", "String", "s", ",", "String", "name", ")", "throws", "IOException", "{", "return", "new", "StringTable", "(", "s", ",", "name", ")", ";", "}" ]
Parse a table from a Reader. @param s the Reader to read from @param name the name of the table @return the CSTable @throws IOException
[ "Parse", "a", "table", "from", "a", "Reader", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/oms3/io/DataIO.java#L1206-L1208
137,787
TheHortonMachine/hortonmachine
gears/src/main/java/oms3/io/DataIO.java
DataIO.table
public static CSTable table(URL url, String name) throws IOException { return new URLTable(url, name); }
java
public static CSTable table(URL url, String name) throws IOException { return new URLTable(url, name); }
[ "public", "static", "CSTable", "table", "(", "URL", "url", ",", "String", "name", ")", "throws", "IOException", "{", "return", "new", "URLTable", "(", "url", ",", "name", ")", ";", "}" ]
Create a CSTable from a URL source. @param url the table URL @param name the name of the table @return a new CSTable @throws IOException
[ "Create", "a", "CSTable", "from", "a", "URL", "source", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/oms3/io/DataIO.java#L1227-L1229
137,788
TheHortonMachine/hortonmachine
gears/src/main/java/oms3/io/DataIO.java
DataIO.columnExist
public static boolean columnExist(CSTable table, String name) { for (int i = 1; i <= table.getColumnCount(); i++) { if (table.getColumnName(i).startsWith(name)) { return true; } } return false; }
java
public static boolean columnExist(CSTable table, String name) { for (int i = 1; i <= table.getColumnCount(); i++) { if (table.getColumnName(i).startsWith(name)) { return true; } } return false; }
[ "public", "static", "boolean", "columnExist", "(", "CSTable", "table", ",", "String", "name", ")", "{", "for", "(", "int", "i", "=", "1", ";", "i", "<=", "table", ".", "getColumnCount", "(", ")", ";", "i", "++", ")", "{", "if", "(", "table", ".", "getColumnName", "(", "i", ")", ".", "startsWith", "(", "name", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Check if a column exist in table. @param table the table to check @param name the name of the column @return
[ "Check", "if", "a", "column", "exist", "in", "table", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/oms3/io/DataIO.java#L1237-L1244
137,789
TheHortonMachine/hortonmachine
gears/src/main/java/oms3/io/DataIO.java
DataIO.columnIndex
public static int columnIndex(CSTable table, String name) { for (int i = 1; i <= table.getColumnCount(); i++) { if (table.getColumnName(i).equals(name)) { return i; } } return -1; }
java
public static int columnIndex(CSTable table, String name) { for (int i = 1; i <= table.getColumnCount(); i++) { if (table.getColumnName(i).equals(name)) { return i; } } return -1; }
[ "public", "static", "int", "columnIndex", "(", "CSTable", "table", ",", "String", "name", ")", "{", "for", "(", "int", "i", "=", "1", ";", "i", "<=", "table", ".", "getColumnCount", "(", ")", ";", "i", "++", ")", "{", "if", "(", "table", ".", "getColumnName", "(", "i", ")", ".", "equals", "(", "name", ")", ")", "{", "return", "i", ";", "}", "}", "return", "-", "1", ";", "}" ]
Gets a column index by name @param table The table to check @param name the column name @return the index of the column
[ "Gets", "a", "column", "index", "by", "name" ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/oms3/io/DataIO.java#L1252-L1259
137,790
TheHortonMachine/hortonmachine
gears/src/main/java/oms3/io/DataIO.java
DataIO.extractColumns
public static CSTable extractColumns(CSTable table, String... colNames) { int[] idx = {}; for (String name : colNames) { idx = add(idx, columnIndexes(table, name)); } if (idx.length == 0) { throw new IllegalArgumentException("No such column names: " + Arrays.toString(colNames)); } List<String> cols = new ArrayList<String>(); for (String name : colNames) { cols.addAll(columnNames(table, name)); } MemoryTable t = new MemoryTable(); t.setName(table.getName()); t.getInfo().putAll(table.getInfo()); // header t.setColumns(cols.toArray(new String[0])); for (int i = 0; i < idx.length; i++) { t.getColumnInfo(i + 1).putAll(table.getColumnInfo(idx[i])); } String[] r = new String[idx.length]; for (String[] row : table.rows()) { rowStringValues(row, idx, r); t.addRow((Object[]) r); } return t; }
java
public static CSTable extractColumns(CSTable table, String... colNames) { int[] idx = {}; for (String name : colNames) { idx = add(idx, columnIndexes(table, name)); } if (idx.length == 0) { throw new IllegalArgumentException("No such column names: " + Arrays.toString(colNames)); } List<String> cols = new ArrayList<String>(); for (String name : colNames) { cols.addAll(columnNames(table, name)); } MemoryTable t = new MemoryTable(); t.setName(table.getName()); t.getInfo().putAll(table.getInfo()); // header t.setColumns(cols.toArray(new String[0])); for (int i = 0; i < idx.length; i++) { t.getColumnInfo(i + 1).putAll(table.getColumnInfo(idx[i])); } String[] r = new String[idx.length]; for (String[] row : table.rows()) { rowStringValues(row, idx, r); t.addRow((Object[]) r); } return t; }
[ "public", "static", "CSTable", "extractColumns", "(", "CSTable", "table", ",", "String", "...", "colNames", ")", "{", "int", "[", "]", "idx", "=", "{", "}", ";", "for", "(", "String", "name", ":", "colNames", ")", "{", "idx", "=", "add", "(", "idx", ",", "columnIndexes", "(", "table", ",", "name", ")", ")", ";", "}", "if", "(", "idx", ".", "length", "==", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"No such column names: \"", "+", "Arrays", ".", "toString", "(", "colNames", ")", ")", ";", "}", "List", "<", "String", ">", "cols", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "for", "(", "String", "name", ":", "colNames", ")", "{", "cols", ".", "addAll", "(", "columnNames", "(", "table", ",", "name", ")", ")", ";", "}", "MemoryTable", "t", "=", "new", "MemoryTable", "(", ")", ";", "t", ".", "setName", "(", "table", ".", "getName", "(", ")", ")", ";", "t", ".", "getInfo", "(", ")", ".", "putAll", "(", "table", ".", "getInfo", "(", ")", ")", ";", "// header", "t", ".", "setColumns", "(", "cols", ".", "toArray", "(", "new", "String", "[", "0", "]", ")", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "idx", ".", "length", ";", "i", "++", ")", "{", "t", ".", "getColumnInfo", "(", "i", "+", "1", ")", ".", "putAll", "(", "table", ".", "getColumnInfo", "(", "idx", "[", "i", "]", ")", ")", ";", "}", "String", "[", "]", "r", "=", "new", "String", "[", "idx", ".", "length", "]", ";", "for", "(", "String", "[", "]", "row", ":", "table", ".", "rows", "(", ")", ")", "{", "rowStringValues", "(", "row", ",", "idx", ",", "r", ")", ";", "t", ".", "addRow", "(", "(", "Object", "[", "]", ")", "r", ")", ";", "}", "return", "t", ";", "}" ]
Extract the columns and create another table. @param table the table @param colName the names of the columns to extract. @return A new Table with the Columns.
[ "Extract", "the", "columns", "and", "create", "another", "table", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/oms3/io/DataIO.java#L1323-L1356
137,791
TheHortonMachine/hortonmachine
gears/src/main/java/oms3/util/Threads.java
Threads.par_ief
private static void par_ief(CompList<?> t, int numproc) throws Exception { if (numproc < 1) { throw new IllegalArgumentException("numproc"); } final CountDownLatch latch = new CountDownLatch(t.list().size()); // final ExecutorService e = Executors.newFixedThreadPool(numproc); for (final Compound c : t) { e.submit(new Runnable() { @Override public void run() { try { ComponentAccess.callAnnotated(c, Initialize.class, true); c.execute(); ComponentAccess.callAnnotated(c, Finalize.class, true); } catch (Throwable E) { e.shutdownNow(); } latch.countDown(); } }); } latch.await(); // e.shutdown(); }
java
private static void par_ief(CompList<?> t, int numproc) throws Exception { if (numproc < 1) { throw new IllegalArgumentException("numproc"); } final CountDownLatch latch = new CountDownLatch(t.list().size()); // final ExecutorService e = Executors.newFixedThreadPool(numproc); for (final Compound c : t) { e.submit(new Runnable() { @Override public void run() { try { ComponentAccess.callAnnotated(c, Initialize.class, true); c.execute(); ComponentAccess.callAnnotated(c, Finalize.class, true); } catch (Throwable E) { e.shutdownNow(); } latch.countDown(); } }); } latch.await(); // e.shutdown(); }
[ "private", "static", "void", "par_ief", "(", "CompList", "<", "?", ">", "t", ",", "int", "numproc", ")", "throws", "Exception", "{", "if", "(", "numproc", "<", "1", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"numproc\"", ")", ";", "}", "final", "CountDownLatch", "latch", "=", "new", "CountDownLatch", "(", "t", ".", "list", "(", ")", ".", "size", "(", ")", ")", ";", "// final ExecutorService e = Executors.newFixedThreadPool(numproc);", "for", "(", "final", "Compound", "c", ":", "t", ")", "{", "e", ".", "submit", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "try", "{", "ComponentAccess", ".", "callAnnotated", "(", "c", ",", "Initialize", ".", "class", ",", "true", ")", ";", "c", ".", "execute", "(", ")", ";", "ComponentAccess", ".", "callAnnotated", "(", "c", ",", "Finalize", ".", "class", ",", "true", ")", ";", "}", "catch", "(", "Throwable", "E", ")", "{", "e", ".", "shutdownNow", "(", ")", ";", "}", "latch", ".", "countDown", "(", ")", ";", "}", "}", ")", ";", "}", "latch", ".", "await", "(", ")", ";", "// e.shutdown();", "}" ]
Runs a set of Compounds in parallel. there are always numproc + 1 threads active. @param comp @param numproc @throws java.lang.Exception
[ "Runs", "a", "set", "of", "Compounds", "in", "parallel", ".", "there", "are", "always", "numproc", "+", "1", "threads", "active", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/oms3/util/Threads.java#L98-L122
137,792
TheHortonMachine/hortonmachine
gui/src/main/java/org/hortonmachine/gui/spatialtoolbox/core/ModuleDescription.java
ModuleDescription.addInput
public void addInput( String fieldName, String type, String description, String defaultValue, String uiHint ) { if (fieldName == null) { throw new IllegalArgumentException("field name is mandatory"); } if (type == null) { throw new IllegalArgumentException("field type is mandatory"); } if (description == null) { description = "No description available"; } FieldData fieldData = new FieldData(); fieldData.isIn = true; fieldData.fieldName = fieldName; fieldData.fieldType = type; fieldData.fieldDescription = description; fieldData.fieldValue = defaultValue; fieldData.guiHints = uiHint; if (!inputsList.contains(fieldData)) { inputsList.add(fieldData); } else { throw new IllegalArgumentException("Duplicated field: " + fieldName); } }
java
public void addInput( String fieldName, String type, String description, String defaultValue, String uiHint ) { if (fieldName == null) { throw new IllegalArgumentException("field name is mandatory"); } if (type == null) { throw new IllegalArgumentException("field type is mandatory"); } if (description == null) { description = "No description available"; } FieldData fieldData = new FieldData(); fieldData.isIn = true; fieldData.fieldName = fieldName; fieldData.fieldType = type; fieldData.fieldDescription = description; fieldData.fieldValue = defaultValue; fieldData.guiHints = uiHint; if (!inputsList.contains(fieldData)) { inputsList.add(fieldData); } else { throw new IllegalArgumentException("Duplicated field: " + fieldName); } }
[ "public", "void", "addInput", "(", "String", "fieldName", ",", "String", "type", ",", "String", "description", ",", "String", "defaultValue", ",", "String", "uiHint", ")", "{", "if", "(", "fieldName", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"field name is mandatory\"", ")", ";", "}", "if", "(", "type", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"field type is mandatory\"", ")", ";", "}", "if", "(", "description", "==", "null", ")", "{", "description", "=", "\"No description available\"", ";", "}", "FieldData", "fieldData", "=", "new", "FieldData", "(", ")", ";", "fieldData", ".", "isIn", "=", "true", ";", "fieldData", ".", "fieldName", "=", "fieldName", ";", "fieldData", ".", "fieldType", "=", "type", ";", "fieldData", ".", "fieldDescription", "=", "description", ";", "fieldData", ".", "fieldValue", "=", "defaultValue", ";", "fieldData", ".", "guiHints", "=", "uiHint", ";", "if", "(", "!", "inputsList", ".", "contains", "(", "fieldData", ")", ")", "{", "inputsList", ".", "add", "(", "fieldData", ")", ";", "}", "else", "{", "throw", "new", "IllegalArgumentException", "(", "\"Duplicated field: \"", "+", "fieldName", ")", ";", "}", "}" ]
Adds an input field to the module. @param fieldName the name of the field (accessed through reflection). @param type the chanonical name of the class of the field. @param description a description of the field. @param defaultValue a default value or <code>null</code>. @param uiHint
[ "Adds", "an", "input", "field", "to", "the", "module", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gui/src/main/java/org/hortonmachine/gui/spatialtoolbox/core/ModuleDescription.java#L118-L142
137,793
TheHortonMachine/hortonmachine
gui/src/main/java/org/hortonmachine/gui/spatialtoolbox/core/ModuleDescription.java
ModuleDescription.addOutput
public void addOutput( String fieldName, String type, String description, String defaultValue, String uiHint ) { if (fieldName == null) { throw new IllegalArgumentException("field name is mandatory"); } if (type == null) { throw new IllegalArgumentException("field type is mandatory"); } if (description == null) { description = "No description available"; } FieldData fieldData = new FieldData(); fieldData.isIn = false; fieldData.fieldName = fieldName; fieldData.fieldType = type; fieldData.fieldDescription = description; fieldData.fieldValue = defaultValue; fieldData.guiHints = uiHint; if (!outputsList.contains(fieldData)) { outputsList.add(fieldData); } else { throw new IllegalArgumentException("Duplicated field: " + fieldName); } }
java
public void addOutput( String fieldName, String type, String description, String defaultValue, String uiHint ) { if (fieldName == null) { throw new IllegalArgumentException("field name is mandatory"); } if (type == null) { throw new IllegalArgumentException("field type is mandatory"); } if (description == null) { description = "No description available"; } FieldData fieldData = new FieldData(); fieldData.isIn = false; fieldData.fieldName = fieldName; fieldData.fieldType = type; fieldData.fieldDescription = description; fieldData.fieldValue = defaultValue; fieldData.guiHints = uiHint; if (!outputsList.contains(fieldData)) { outputsList.add(fieldData); } else { throw new IllegalArgumentException("Duplicated field: " + fieldName); } }
[ "public", "void", "addOutput", "(", "String", "fieldName", ",", "String", "type", ",", "String", "description", ",", "String", "defaultValue", ",", "String", "uiHint", ")", "{", "if", "(", "fieldName", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"field name is mandatory\"", ")", ";", "}", "if", "(", "type", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"field type is mandatory\"", ")", ";", "}", "if", "(", "description", "==", "null", ")", "{", "description", "=", "\"No description available\"", ";", "}", "FieldData", "fieldData", "=", "new", "FieldData", "(", ")", ";", "fieldData", ".", "isIn", "=", "false", ";", "fieldData", ".", "fieldName", "=", "fieldName", ";", "fieldData", ".", "fieldType", "=", "type", ";", "fieldData", ".", "fieldDescription", "=", "description", ";", "fieldData", ".", "fieldValue", "=", "defaultValue", ";", "fieldData", ".", "guiHints", "=", "uiHint", ";", "if", "(", "!", "outputsList", ".", "contains", "(", "fieldData", ")", ")", "{", "outputsList", ".", "add", "(", "fieldData", ")", ";", "}", "else", "{", "throw", "new", "IllegalArgumentException", "(", "\"Duplicated field: \"", "+", "fieldName", ")", ";", "}", "}" ]
Adds an output field to the module. @param fieldName the name of the field (accessed through reflection). @param type the chanonical name of the class of the field. @param description a description of the field. @param defaultValue a default value or <code>null</code>. @param uiHint
[ "Adds", "an", "output", "field", "to", "the", "module", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gui/src/main/java/org/hortonmachine/gui/spatialtoolbox/core/ModuleDescription.java#L153-L177
137,794
TheHortonMachine/hortonmachine
dbs/src/main/java/org/hortonmachine/ssh/SshUtilities.java
SshUtilities.getPreference
public static String getPreference( String preferenceKey, String defaultValue ) { Preferences preferences = Preferences.userRoot().node(PREFS_NODE_NAME); String preference = preferences.get(preferenceKey, defaultValue); return preference; }
java
public static String getPreference( String preferenceKey, String defaultValue ) { Preferences preferences = Preferences.userRoot().node(PREFS_NODE_NAME); String preference = preferences.get(preferenceKey, defaultValue); return preference; }
[ "public", "static", "String", "getPreference", "(", "String", "preferenceKey", ",", "String", "defaultValue", ")", "{", "Preferences", "preferences", "=", "Preferences", ".", "userRoot", "(", ")", ".", "node", "(", "PREFS_NODE_NAME", ")", ";", "String", "preference", "=", "preferences", ".", "get", "(", "preferenceKey", ",", "defaultValue", ")", ";", "return", "preference", ";", "}" ]
Get from preference. @param preferenceKey the preference key. @param defaultValue the default value in case of <code>null</code>. @return the string preference asked.
[ "Get", "from", "preference", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/dbs/src/main/java/org/hortonmachine/ssh/SshUtilities.java#L56-L60
137,795
TheHortonMachine/hortonmachine
dbs/src/main/java/org/hortonmachine/ssh/SshUtilities.java
SshUtilities.getProcessPid
public static String getProcessPid( Session session, String userName, String grep1, String grep2 ) throws JSchException, IOException { String command = "ps aux | grep \"" + grep1 + "\" | grep -v grep"; String remoteResponseStr = launchACommand(session, command); if (remoteResponseStr.length() == 0) { return null; } List<String> pidsList = new ArrayList<>(); String[] linesSplit = remoteResponseStr.split("\n"); for( String line : linesSplit ) { if (!line.contains(grep2)) { continue; } String[] psSplit = line.split("\\s+"); if (psSplit.length < 3) { throw new JSchException("Could not retrieve process data. Result was: " + line); } String user = psSplit[0]; if (userName != null && !user.equals(userName)) { continue; } String pid = psSplit[1]; try { Integer.parseInt(pid); } catch (Exception e) { throw new JSchException("The pid is invalid: " + pid); } pidsList.add(pid); } if (pidsList.size() > 1) { throw new JSchException("More than one process was identified with the given filters. Check your filters."); } else if (pidsList.size() == 0) { return null; } return pidsList.get(0); }
java
public static String getProcessPid( Session session, String userName, String grep1, String grep2 ) throws JSchException, IOException { String command = "ps aux | grep \"" + grep1 + "\" | grep -v grep"; String remoteResponseStr = launchACommand(session, command); if (remoteResponseStr.length() == 0) { return null; } List<String> pidsList = new ArrayList<>(); String[] linesSplit = remoteResponseStr.split("\n"); for( String line : linesSplit ) { if (!line.contains(grep2)) { continue; } String[] psSplit = line.split("\\s+"); if (psSplit.length < 3) { throw new JSchException("Could not retrieve process data. Result was: " + line); } String user = psSplit[0]; if (userName != null && !user.equals(userName)) { continue; } String pid = psSplit[1]; try { Integer.parseInt(pid); } catch (Exception e) { throw new JSchException("The pid is invalid: " + pid); } pidsList.add(pid); } if (pidsList.size() > 1) { throw new JSchException("More than one process was identified with the given filters. Check your filters."); } else if (pidsList.size() == 0) { return null; } return pidsList.get(0); }
[ "public", "static", "String", "getProcessPid", "(", "Session", "session", ",", "String", "userName", ",", "String", "grep1", ",", "String", "grep2", ")", "throws", "JSchException", ",", "IOException", "{", "String", "command", "=", "\"ps aux | grep \\\"\"", "+", "grep1", "+", "\"\\\" | grep -v grep\"", ";", "String", "remoteResponseStr", "=", "launchACommand", "(", "session", ",", "command", ")", ";", "if", "(", "remoteResponseStr", ".", "length", "(", ")", "==", "0", ")", "{", "return", "null", ";", "}", "List", "<", "String", ">", "pidsList", "=", "new", "ArrayList", "<>", "(", ")", ";", "String", "[", "]", "linesSplit", "=", "remoteResponseStr", ".", "split", "(", "\"\\n\"", ")", ";", "for", "(", "String", "line", ":", "linesSplit", ")", "{", "if", "(", "!", "line", ".", "contains", "(", "grep2", ")", ")", "{", "continue", ";", "}", "String", "[", "]", "psSplit", "=", "line", ".", "split", "(", "\"\\\\s+\"", ")", ";", "if", "(", "psSplit", ".", "length", "<", "3", ")", "{", "throw", "new", "JSchException", "(", "\"Could not retrieve process data. Result was: \"", "+", "line", ")", ";", "}", "String", "user", "=", "psSplit", "[", "0", "]", ";", "if", "(", "userName", "!=", "null", "&&", "!", "user", ".", "equals", "(", "userName", ")", ")", "{", "continue", ";", "}", "String", "pid", "=", "psSplit", "[", "1", "]", ";", "try", "{", "Integer", ".", "parseInt", "(", "pid", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "JSchException", "(", "\"The pid is invalid: \"", "+", "pid", ")", ";", "}", "pidsList", ".", "add", "(", "pid", ")", ";", "}", "if", "(", "pidsList", ".", "size", "(", ")", ">", "1", ")", "{", "throw", "new", "JSchException", "(", "\"More than one process was identified with the given filters. Check your filters.\"", ")", ";", "}", "else", "if", "(", "pidsList", ".", "size", "(", ")", "==", "0", ")", "{", "return", "null", ";", "}", "return", "pidsList", ".", "get", "(", "0", ")", ";", "}" ]
Get the pid of a process identified by a consequent grepping on a ps aux command. <P><b>THIS WORKS ONLY ON LINUX HOSTS</b></p> @param session the jsch sesssion to use. @param userName an optional username to check the process on. @param grep1 the first grep filter. @param grep2 the second grep filter, done in the java code. @return the process pid or <code>null</code> if no process was found. @throws JSchException @throws IOException
[ "Get", "the", "pid", "of", "a", "process", "identified", "by", "a", "consequent", "grepping", "on", "a", "ps", "aux", "command", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/dbs/src/main/java/org/hortonmachine/ssh/SshUtilities.java#L92-L131
137,796
TheHortonMachine/hortonmachine
dbs/src/main/java/org/hortonmachine/ssh/SshUtilities.java
SshUtilities.killProcessByPid
public static void killProcessByPid( Session session, int pid ) throws Exception { String command = "kill -9 " + pid; String remoteResponseStr = launchACommand(session, command); if (remoteResponseStr.length() == 0) { return; } else { new Exception(remoteResponseStr); } }
java
public static void killProcessByPid( Session session, int pid ) throws Exception { String command = "kill -9 " + pid; String remoteResponseStr = launchACommand(session, command); if (remoteResponseStr.length() == 0) { return; } else { new Exception(remoteResponseStr); } }
[ "public", "static", "void", "killProcessByPid", "(", "Session", "session", ",", "int", "pid", ")", "throws", "Exception", "{", "String", "command", "=", "\"kill -9 \"", "+", "pid", ";", "String", "remoteResponseStr", "=", "launchACommand", "(", "session", ",", "command", ")", ";", "if", "(", "remoteResponseStr", ".", "length", "(", ")", "==", "0", ")", "{", "return", ";", "}", "else", "{", "new", "Exception", "(", "remoteResponseStr", ")", ";", "}", "}" ]
Kills a process using its pid. <P><b>THIS WORKS ONLY ON LINUX HOSTS</b></p> @param session the session to use. @param pid the pid to use. @throws Exception
[ "Kills", "a", "process", "using", "its", "pid", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/dbs/src/main/java/org/hortonmachine/ssh/SshUtilities.java#L142-L151
137,797
TheHortonMachine/hortonmachine
dbs/src/main/java/org/hortonmachine/ssh/SshUtilities.java
SshUtilities.getRunningDockerContainerId
public static String getRunningDockerContainerId( Session session, String containerName ) throws JSchException, IOException { String command = "docker ps | grep " + containerName; String remoteResponseStr = launchACommand(session, command); if (remoteResponseStr.length() == 0) { return null; } List<String> containerIdsList = new ArrayList<>(); String[] linesSplit = remoteResponseStr.split("\n"); for( String line : linesSplit ) { String[] psSplit = line.split("\\s+"); if (psSplit.length < 3) { throw new JSchException("Could not retrieve container data. Result was: " + line); } String cid = psSplit[0]; containerIdsList.add(cid); } if (containerIdsList.size() > 1) { throw new JSchException("More than one container was identified with the given filters. Check your filters."); } else if (containerIdsList.size() == 0) { return null; } return containerIdsList.get(0); }
java
public static String getRunningDockerContainerId( Session session, String containerName ) throws JSchException, IOException { String command = "docker ps | grep " + containerName; String remoteResponseStr = launchACommand(session, command); if (remoteResponseStr.length() == 0) { return null; } List<String> containerIdsList = new ArrayList<>(); String[] linesSplit = remoteResponseStr.split("\n"); for( String line : linesSplit ) { String[] psSplit = line.split("\\s+"); if (psSplit.length < 3) { throw new JSchException("Could not retrieve container data. Result was: " + line); } String cid = psSplit[0]; containerIdsList.add(cid); } if (containerIdsList.size() > 1) { throw new JSchException("More than one container was identified with the given filters. Check your filters."); } else if (containerIdsList.size() == 0) { return null; } return containerIdsList.get(0); }
[ "public", "static", "String", "getRunningDockerContainerId", "(", "Session", "session", ",", "String", "containerName", ")", "throws", "JSchException", ",", "IOException", "{", "String", "command", "=", "\"docker ps | grep \"", "+", "containerName", ";", "String", "remoteResponseStr", "=", "launchACommand", "(", "session", ",", "command", ")", ";", "if", "(", "remoteResponseStr", ".", "length", "(", ")", "==", "0", ")", "{", "return", "null", ";", "}", "List", "<", "String", ">", "containerIdsList", "=", "new", "ArrayList", "<>", "(", ")", ";", "String", "[", "]", "linesSplit", "=", "remoteResponseStr", ".", "split", "(", "\"\\n\"", ")", ";", "for", "(", "String", "line", ":", "linesSplit", ")", "{", "String", "[", "]", "psSplit", "=", "line", ".", "split", "(", "\"\\\\s+\"", ")", ";", "if", "(", "psSplit", ".", "length", "<", "3", ")", "{", "throw", "new", "JSchException", "(", "\"Could not retrieve container data. Result was: \"", "+", "line", ")", ";", "}", "String", "cid", "=", "psSplit", "[", "0", "]", ";", "containerIdsList", ".", "add", "(", "cid", ")", ";", "}", "if", "(", "containerIdsList", ".", "size", "(", ")", ">", "1", ")", "{", "throw", "new", "JSchException", "(", "\"More than one container was identified with the given filters. Check your filters.\"", ")", ";", "}", "else", "if", "(", "containerIdsList", ".", "size", "(", ")", "==", "0", ")", "{", "return", "null", ";", "}", "return", "containerIdsList", ".", "get", "(", "0", ")", ";", "}" ]
Get the container id of a running docker container. @param session the session to use. @param containerName the name of the container, used in a grep filter. @return the id of the container or null. @throws JSchException @throws IOException
[ "Get", "the", "container", "id", "of", "a", "running", "docker", "container", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/dbs/src/main/java/org/hortonmachine/ssh/SshUtilities.java#L162-L185
137,798
TheHortonMachine/hortonmachine
dbs/src/main/java/org/hortonmachine/ssh/SshUtilities.java
SshUtilities.launchACommand
private static String launchACommand( Session session, String command ) throws JSchException, IOException { Channel channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand(command); channel.setInputStream(null); ((ChannelExec) channel).setErrStream(System.err); InputStream in = channel.getInputStream(); channel.connect(); StringBuilder sb = new StringBuilder(); byte[] tmp = new byte[1024]; while( true ) { while( in.available() > 0 ) { int i = in.read(tmp, 0, 1024); if (i < 0) break; sb.append(new String(tmp, 0, i)); } if (channel.isClosed()) { if (in.available() > 0) continue; System.out.println("exitstatus: " + channel.getExitStatus()); break; } try { Thread.sleep(1000); } catch (Exception ee) { } } channel.disconnect(); String remoteResponseStr = sb.toString().trim(); return remoteResponseStr; }
java
private static String launchACommand( Session session, String command ) throws JSchException, IOException { Channel channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand(command); channel.setInputStream(null); ((ChannelExec) channel).setErrStream(System.err); InputStream in = channel.getInputStream(); channel.connect(); StringBuilder sb = new StringBuilder(); byte[] tmp = new byte[1024]; while( true ) { while( in.available() > 0 ) { int i = in.read(tmp, 0, 1024); if (i < 0) break; sb.append(new String(tmp, 0, i)); } if (channel.isClosed()) { if (in.available() > 0) continue; System.out.println("exitstatus: " + channel.getExitStatus()); break; } try { Thread.sleep(1000); } catch (Exception ee) { } } channel.disconnect(); String remoteResponseStr = sb.toString().trim(); return remoteResponseStr; }
[ "private", "static", "String", "launchACommand", "(", "Session", "session", ",", "String", "command", ")", "throws", "JSchException", ",", "IOException", "{", "Channel", "channel", "=", "session", ".", "openChannel", "(", "\"exec\"", ")", ";", "(", "(", "ChannelExec", ")", "channel", ")", ".", "setCommand", "(", "command", ")", ";", "channel", ".", "setInputStream", "(", "null", ")", ";", "(", "(", "ChannelExec", ")", "channel", ")", ".", "setErrStream", "(", "System", ".", "err", ")", ";", "InputStream", "in", "=", "channel", ".", "getInputStream", "(", ")", ";", "channel", ".", "connect", "(", ")", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "byte", "[", "]", "tmp", "=", "new", "byte", "[", "1024", "]", ";", "while", "(", "true", ")", "{", "while", "(", "in", ".", "available", "(", ")", ">", "0", ")", "{", "int", "i", "=", "in", ".", "read", "(", "tmp", ",", "0", ",", "1024", ")", ";", "if", "(", "i", "<", "0", ")", "break", ";", "sb", ".", "append", "(", "new", "String", "(", "tmp", ",", "0", ",", "i", ")", ")", ";", "}", "if", "(", "channel", ".", "isClosed", "(", ")", ")", "{", "if", "(", "in", ".", "available", "(", ")", ">", "0", ")", "continue", ";", "System", ".", "out", ".", "println", "(", "\"exitstatus: \"", "+", "channel", ".", "getExitStatus", "(", ")", ")", ";", "break", ";", "}", "try", "{", "Thread", ".", "sleep", "(", "1000", ")", ";", "}", "catch", "(", "Exception", "ee", ")", "{", "}", "}", "channel", ".", "disconnect", "(", ")", ";", "String", "remoteResponseStr", "=", "sb", ".", "toString", "(", ")", ".", "trim", "(", ")", ";", "return", "remoteResponseStr", ";", "}" ]
Launch a command on the remote host and exit once the command is done. @param session the session to use. @param command the command to launch. @return the output of the command. @throws JSchException @throws IOException
[ "Launch", "a", "command", "on", "the", "remote", "host", "and", "exit", "once", "the", "command", "is", "done", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/dbs/src/main/java/org/hortonmachine/ssh/SshUtilities.java#L196-L226
137,799
TheHortonMachine/hortonmachine
dbs/src/main/java/org/hortonmachine/ssh/SshUtilities.java
SshUtilities.runShellCommand
public static String runShellCommand( Session session, String command ) throws JSchException, IOException { String remoteResponseStr = launchACommand(session, command); return remoteResponseStr; }
java
public static String runShellCommand( Session session, String command ) throws JSchException, IOException { String remoteResponseStr = launchACommand(session, command); return remoteResponseStr; }
[ "public", "static", "String", "runShellCommand", "(", "Session", "session", ",", "String", "command", ")", "throws", "JSchException", ",", "IOException", "{", "String", "remoteResponseStr", "=", "launchACommand", "(", "session", ",", "command", ")", ";", "return", "remoteResponseStr", ";", "}" ]
Launch a shell command. @param session the session to use. @param command the command to launch. @return the output of the command. @throws JSchException @throws IOException
[ "Launch", "a", "shell", "command", "." ]
d2b436bbdf951dc1fda56096a42dbc0eae4d35a5
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/dbs/src/main/java/org/hortonmachine/ssh/SshUtilities.java#L280-L283