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
21,100
graphhopper/graphhopper
core/src/main/java/com/graphhopper/GraphHopper.java
GraphHopper.createTurnWeighting
public Weighting createTurnWeighting(Graph graph, Weighting weighting, TraversalMode tMode) { FlagEncoder encoder = weighting.getFlagEncoder(); if (encoder.supports(TurnWeighting.class) && !tMode.equals(TraversalMode.NODE_BASED)) return new TurnWeighting(weighting, (TurnCostExtension) graph.getExtension()); return weighting; }
java
public Weighting createTurnWeighting(Graph graph, Weighting weighting, TraversalMode tMode) { FlagEncoder encoder = weighting.getFlagEncoder(); if (encoder.supports(TurnWeighting.class) && !tMode.equals(TraversalMode.NODE_BASED)) return new TurnWeighting(weighting, (TurnCostExtension) graph.getExtension()); return weighting; }
[ "public", "Weighting", "createTurnWeighting", "(", "Graph", "graph", ",", "Weighting", "weighting", ",", "TraversalMode", "tMode", ")", "{", "FlagEncoder", "encoder", "=", "weighting", ".", "getFlagEncoder", "(", ")", ";", "if", "(", "encoder", ".", "supports", "(", "TurnWeighting", ".", "class", ")", "&&", "!", "tMode", ".", "equals", "(", "TraversalMode", ".", "NODE_BASED", ")", ")", "return", "new", "TurnWeighting", "(", "weighting", ",", "(", "TurnCostExtension", ")", "graph", ".", "getExtension", "(", ")", ")", ";", "return", "weighting", ";", "}" ]
Potentially wraps the specified weighting into a TurnWeighting instance.
[ "Potentially", "wraps", "the", "specified", "weighting", "into", "a", "TurnWeighting", "instance", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/GraphHopper.java#L912-L917
21,101
graphhopper/graphhopper
core/src/main/java/com/graphhopper/GraphHopper.java
GraphHopper.cleanUp
protected void cleanUp() { int prevNodeCount = ghStorage.getNodes(); PrepareRoutingSubnetworks preparation = new PrepareRoutingSubnetworks(ghStorage, encodingManager.fetchEdgeEncoders()); preparation.setMinNetworkSize(minNetworkSize); preparation.setMinOneWayNetworkSize(minOneWayNetworkSize); preparation.doWork(); int currNodeCount = ghStorage.getNodes(); logger.info("edges: " + Helper.nf(ghStorage.getAllEdges().length()) + ", nodes " + Helper.nf(currNodeCount) + ", there were " + Helper.nf(preparation.getMaxSubnetworks()) + " subnetworks. removed them => " + Helper.nf(prevNodeCount - currNodeCount) + " less nodes"); }
java
protected void cleanUp() { int prevNodeCount = ghStorage.getNodes(); PrepareRoutingSubnetworks preparation = new PrepareRoutingSubnetworks(ghStorage, encodingManager.fetchEdgeEncoders()); preparation.setMinNetworkSize(minNetworkSize); preparation.setMinOneWayNetworkSize(minOneWayNetworkSize); preparation.doWork(); int currNodeCount = ghStorage.getNodes(); logger.info("edges: " + Helper.nf(ghStorage.getAllEdges().length()) + ", nodes " + Helper.nf(currNodeCount) + ", there were " + Helper.nf(preparation.getMaxSubnetworks()) + " subnetworks. removed them => " + Helper.nf(prevNodeCount - currNodeCount) + " less nodes"); }
[ "protected", "void", "cleanUp", "(", ")", "{", "int", "prevNodeCount", "=", "ghStorage", ".", "getNodes", "(", ")", ";", "PrepareRoutingSubnetworks", "preparation", "=", "new", "PrepareRoutingSubnetworks", "(", "ghStorage", ",", "encodingManager", ".", "fetchEdgeEncoders", "(", ")", ")", ";", "preparation", ".", "setMinNetworkSize", "(", "minNetworkSize", ")", ";", "preparation", ".", "setMinOneWayNetworkSize", "(", "minOneWayNetworkSize", ")", ";", "preparation", ".", "doWork", "(", ")", ";", "int", "currNodeCount", "=", "ghStorage", ".", "getNodes", "(", ")", ";", "logger", ".", "info", "(", "\"edges: \"", "+", "Helper", ".", "nf", "(", "ghStorage", ".", "getAllEdges", "(", ")", ".", "length", "(", ")", ")", "+", "\", nodes \"", "+", "Helper", ".", "nf", "(", "currNodeCount", ")", "+", "\", there were \"", "+", "Helper", ".", "nf", "(", "preparation", ".", "getMaxSubnetworks", "(", ")", ")", "+", "\" subnetworks. removed them => \"", "+", "Helper", ".", "nf", "(", "prevNodeCount", "-", "currNodeCount", ")", "+", "\" less nodes\"", ")", ";", "}" ]
Internal method to clean up the graph.
[ "Internal", "method", "to", "clean", "up", "the", "graph", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/GraphHopper.java#L1181-L1192
21,102
graphhopper/graphhopper
core/src/main/java/com/graphhopper/GraphHopper.java
GraphHopper.clean
public void clean() { if (getGraphHopperLocation().isEmpty()) throw new IllegalStateException("Cannot clean GraphHopper without specified graphHopperLocation"); File folder = new File(getGraphHopperLocation()); removeDir(folder); }
java
public void clean() { if (getGraphHopperLocation().isEmpty()) throw new IllegalStateException("Cannot clean GraphHopper without specified graphHopperLocation"); File folder = new File(getGraphHopperLocation()); removeDir(folder); }
[ "public", "void", "clean", "(", ")", "{", "if", "(", "getGraphHopperLocation", "(", ")", ".", "isEmpty", "(", ")", ")", "throw", "new", "IllegalStateException", "(", "\"Cannot clean GraphHopper without specified graphHopperLocation\"", ")", ";", "File", "folder", "=", "new", "File", "(", "getGraphHopperLocation", "(", ")", ")", ";", "removeDir", "(", "folder", ")", ";", "}" ]
Removes the on-disc routing files. Call only after calling close or before importOrLoad or load
[ "Removes", "the", "on", "-", "disc", "routing", "files", ".", "Call", "only", "after", "calling", "close", "or", "before", "importOrLoad", "or", "load" ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/GraphHopper.java#L1224-L1230
21,103
graphhopper/graphhopper
core/src/main/java/com/graphhopper/routing/lm/LandmarkStorage.java
LandmarkStorage.setLandmarkSuggestions
public LandmarkStorage setLandmarkSuggestions(List<LandmarkSuggestion> landmarkSuggestions) { if (landmarkSuggestions == null) throw new IllegalArgumentException("landmark suggestions cannot be null"); this.landmarkSuggestions = landmarkSuggestions; return this; }
java
public LandmarkStorage setLandmarkSuggestions(List<LandmarkSuggestion> landmarkSuggestions) { if (landmarkSuggestions == null) throw new IllegalArgumentException("landmark suggestions cannot be null"); this.landmarkSuggestions = landmarkSuggestions; return this; }
[ "public", "LandmarkStorage", "setLandmarkSuggestions", "(", "List", "<", "LandmarkSuggestion", ">", "landmarkSuggestions", ")", "{", "if", "(", "landmarkSuggestions", "==", "null", ")", "throw", "new", "IllegalArgumentException", "(", "\"landmark suggestions cannot be null\"", ")", ";", "this", ".", "landmarkSuggestions", "=", "landmarkSuggestions", ";", "return", "this", ";", "}" ]
This method forces the landmark preparation to skip the landmark search and uses the specified landmark list instead. Useful for manual tuning of larger areas to safe import time or improve quality.
[ "This", "method", "forces", "the", "landmark", "preparation", "to", "skip", "the", "landmark", "search", "and", "uses", "the", "specified", "landmark", "list", "instead", ".", "Useful", "for", "manual", "tuning", "of", "larger", "areas", "to", "safe", "import", "time", "or", "improve", "quality", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/lm/LandmarkStorage.java#L152-L158
21,104
graphhopper/graphhopper
core/src/main/java/com/graphhopper/routing/lm/LandmarkStorage.java
LandmarkStorage.findBorderEdgeIds
protected IntHashSet findBorderEdgeIds(SpatialRuleLookup ruleLookup) { AllEdgesIterator allEdgesIterator = graph.getAllEdges(); NodeAccess nodeAccess = graph.getNodeAccess(); IntHashSet inaccessible = new IntHashSet(); while (allEdgesIterator.next()) { int adjNode = allEdgesIterator.getAdjNode(); SpatialRule ruleAdj = ruleLookup.lookupRule(nodeAccess.getLatitude(adjNode), nodeAccess.getLongitude(adjNode)); int baseNode = allEdgesIterator.getBaseNode(); SpatialRule ruleBase = ruleLookup.lookupRule(nodeAccess.getLatitude(baseNode), nodeAccess.getLongitude(baseNode)); if (ruleAdj != ruleBase) { inaccessible.add(allEdgesIterator.getEdge()); } } return inaccessible; }
java
protected IntHashSet findBorderEdgeIds(SpatialRuleLookup ruleLookup) { AllEdgesIterator allEdgesIterator = graph.getAllEdges(); NodeAccess nodeAccess = graph.getNodeAccess(); IntHashSet inaccessible = new IntHashSet(); while (allEdgesIterator.next()) { int adjNode = allEdgesIterator.getAdjNode(); SpatialRule ruleAdj = ruleLookup.lookupRule(nodeAccess.getLatitude(adjNode), nodeAccess.getLongitude(adjNode)); int baseNode = allEdgesIterator.getBaseNode(); SpatialRule ruleBase = ruleLookup.lookupRule(nodeAccess.getLatitude(baseNode), nodeAccess.getLongitude(baseNode)); if (ruleAdj != ruleBase) { inaccessible.add(allEdgesIterator.getEdge()); } } return inaccessible; }
[ "protected", "IntHashSet", "findBorderEdgeIds", "(", "SpatialRuleLookup", "ruleLookup", ")", "{", "AllEdgesIterator", "allEdgesIterator", "=", "graph", ".", "getAllEdges", "(", ")", ";", "NodeAccess", "nodeAccess", "=", "graph", ".", "getNodeAccess", "(", ")", ";", "IntHashSet", "inaccessible", "=", "new", "IntHashSet", "(", ")", ";", "while", "(", "allEdgesIterator", ".", "next", "(", ")", ")", "{", "int", "adjNode", "=", "allEdgesIterator", ".", "getAdjNode", "(", ")", ";", "SpatialRule", "ruleAdj", "=", "ruleLookup", ".", "lookupRule", "(", "nodeAccess", ".", "getLatitude", "(", "adjNode", ")", ",", "nodeAccess", ".", "getLongitude", "(", "adjNode", ")", ")", ";", "int", "baseNode", "=", "allEdgesIterator", ".", "getBaseNode", "(", ")", ";", "SpatialRule", "ruleBase", "=", "ruleLookup", ".", "lookupRule", "(", "nodeAccess", ".", "getLatitude", "(", "baseNode", ")", ",", "nodeAccess", ".", "getLongitude", "(", "baseNode", ")", ")", ";", "if", "(", "ruleAdj", "!=", "ruleBase", ")", "{", "inaccessible", ".", "add", "(", "allEdgesIterator", ".", "getEdge", "(", ")", ")", ";", "}", "}", "return", "inaccessible", ";", "}" ]
This method makes edges crossing the specified border inaccessible to split a bigger area into smaller subnetworks. This is important for the world wide use case to limit the maximum distance and also to detect unreasonable routes faster.
[ "This", "method", "makes", "edges", "crossing", "the", "specified", "border", "inaccessible", "to", "split", "a", "bigger", "area", "into", "smaller", "subnetworks", ".", "This", "is", "important", "for", "the", "world", "wide", "use", "case", "to", "limit", "the", "maximum", "distance", "and", "also", "to", "detect", "unreasonable", "routes", "faster", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/lm/LandmarkStorage.java#L453-L468
21,105
graphhopper/graphhopper
core/src/main/java/com/graphhopper/routing/lm/LandmarkStorage.java
LandmarkStorage.initActiveLandmarks
boolean initActiveLandmarks(int fromNode, int toNode, int[] activeLandmarkIndices, int[] activeFroms, int[] activeTos, boolean reverse) { if (fromNode < 0 || toNode < 0) throw new IllegalStateException("from " + fromNode + " and to " + toNode + " nodes have to be 0 or positive to init landmarks"); int subnetworkFrom = subnetworkStorage.getSubnetwork(fromNode); int subnetworkTo = subnetworkStorage.getSubnetwork(toNode); if (subnetworkFrom <= UNCLEAR_SUBNETWORK || subnetworkTo <= UNCLEAR_SUBNETWORK) return false; if (subnetworkFrom != subnetworkTo) { throw new ConnectionNotFoundException("Connection between locations not found. Different subnetworks " + subnetworkFrom + " vs. " + subnetworkTo, new HashMap<String, Object>()); } int[] tmpIDs = landmarkIDs.get(subnetworkFrom); // kind of code duplication to approximate List<Map.Entry<Integer, Integer>> list = new ArrayList<>(tmpIDs.length); for (int lmIndex = 0; lmIndex < tmpIDs.length; lmIndex++) { int fromWeight = getFromWeight(lmIndex, toNode) - getFromWeight(lmIndex, fromNode); int toWeight = getToWeight(lmIndex, fromNode) - getToWeight(lmIndex, toNode); list.add(new MapEntry<>(reverse ? Math.max(-fromWeight, -toWeight) : Math.max(fromWeight, toWeight), lmIndex)); } Collections.sort(list, SORT_BY_WEIGHT); if (activeLandmarkIndices[0] >= 0) { IntHashSet set = new IntHashSet(activeLandmarkIndices.length); set.addAll(activeLandmarkIndices); int existingLandmarkCounter = 0; final int COUNT = Math.min(activeLandmarkIndices.length - 2, 2); for (int i = 0; i < activeLandmarkIndices.length; i++) { if (i >= activeLandmarkIndices.length - COUNT + existingLandmarkCounter) { // keep at least two of the previous landmarks (pick the best) break; } else { activeLandmarkIndices[i] = list.get(i).getValue(); if (set.contains(activeLandmarkIndices[i])) existingLandmarkCounter++; } } } else { for (int i = 0; i < activeLandmarkIndices.length; i++) { activeLandmarkIndices[i] = list.get(i).getValue(); } } // store weight values of active landmarks in 'cache' arrays for (int i = 0; i < activeLandmarkIndices.length; i++) { int lmIndex = activeLandmarkIndices[i]; activeFroms[i] = getFromWeight(lmIndex, toNode); activeTos[i] = getToWeight(lmIndex, toNode); } return true; }
java
boolean initActiveLandmarks(int fromNode, int toNode, int[] activeLandmarkIndices, int[] activeFroms, int[] activeTos, boolean reverse) { if (fromNode < 0 || toNode < 0) throw new IllegalStateException("from " + fromNode + " and to " + toNode + " nodes have to be 0 or positive to init landmarks"); int subnetworkFrom = subnetworkStorage.getSubnetwork(fromNode); int subnetworkTo = subnetworkStorage.getSubnetwork(toNode); if (subnetworkFrom <= UNCLEAR_SUBNETWORK || subnetworkTo <= UNCLEAR_SUBNETWORK) return false; if (subnetworkFrom != subnetworkTo) { throw new ConnectionNotFoundException("Connection between locations not found. Different subnetworks " + subnetworkFrom + " vs. " + subnetworkTo, new HashMap<String, Object>()); } int[] tmpIDs = landmarkIDs.get(subnetworkFrom); // kind of code duplication to approximate List<Map.Entry<Integer, Integer>> list = new ArrayList<>(tmpIDs.length); for (int lmIndex = 0; lmIndex < tmpIDs.length; lmIndex++) { int fromWeight = getFromWeight(lmIndex, toNode) - getFromWeight(lmIndex, fromNode); int toWeight = getToWeight(lmIndex, fromNode) - getToWeight(lmIndex, toNode); list.add(new MapEntry<>(reverse ? Math.max(-fromWeight, -toWeight) : Math.max(fromWeight, toWeight), lmIndex)); } Collections.sort(list, SORT_BY_WEIGHT); if (activeLandmarkIndices[0] >= 0) { IntHashSet set = new IntHashSet(activeLandmarkIndices.length); set.addAll(activeLandmarkIndices); int existingLandmarkCounter = 0; final int COUNT = Math.min(activeLandmarkIndices.length - 2, 2); for (int i = 0; i < activeLandmarkIndices.length; i++) { if (i >= activeLandmarkIndices.length - COUNT + existingLandmarkCounter) { // keep at least two of the previous landmarks (pick the best) break; } else { activeLandmarkIndices[i] = list.get(i).getValue(); if (set.contains(activeLandmarkIndices[i])) existingLandmarkCounter++; } } } else { for (int i = 0; i < activeLandmarkIndices.length; i++) { activeLandmarkIndices[i] = list.get(i).getValue(); } } // store weight values of active landmarks in 'cache' arrays for (int i = 0; i < activeLandmarkIndices.length; i++) { int lmIndex = activeLandmarkIndices[i]; activeFroms[i] = getFromWeight(lmIndex, toNode); activeTos[i] = getToWeight(lmIndex, toNode); } return true; }
[ "boolean", "initActiveLandmarks", "(", "int", "fromNode", ",", "int", "toNode", ",", "int", "[", "]", "activeLandmarkIndices", ",", "int", "[", "]", "activeFroms", ",", "int", "[", "]", "activeTos", ",", "boolean", "reverse", ")", "{", "if", "(", "fromNode", "<", "0", "||", "toNode", "<", "0", ")", "throw", "new", "IllegalStateException", "(", "\"from \"", "+", "fromNode", "+", "\" and to \"", "+", "toNode", "+", "\" nodes have to be 0 or positive to init landmarks\"", ")", ";", "int", "subnetworkFrom", "=", "subnetworkStorage", ".", "getSubnetwork", "(", "fromNode", ")", ";", "int", "subnetworkTo", "=", "subnetworkStorage", ".", "getSubnetwork", "(", "toNode", ")", ";", "if", "(", "subnetworkFrom", "<=", "UNCLEAR_SUBNETWORK", "||", "subnetworkTo", "<=", "UNCLEAR_SUBNETWORK", ")", "return", "false", ";", "if", "(", "subnetworkFrom", "!=", "subnetworkTo", ")", "{", "throw", "new", "ConnectionNotFoundException", "(", "\"Connection between locations not found. Different subnetworks \"", "+", "subnetworkFrom", "+", "\" vs. \"", "+", "subnetworkTo", ",", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ")", ";", "}", "int", "[", "]", "tmpIDs", "=", "landmarkIDs", ".", "get", "(", "subnetworkFrom", ")", ";", "// kind of code duplication to approximate", "List", "<", "Map", ".", "Entry", "<", "Integer", ",", "Integer", ">", ">", "list", "=", "new", "ArrayList", "<>", "(", "tmpIDs", ".", "length", ")", ";", "for", "(", "int", "lmIndex", "=", "0", ";", "lmIndex", "<", "tmpIDs", ".", "length", ";", "lmIndex", "++", ")", "{", "int", "fromWeight", "=", "getFromWeight", "(", "lmIndex", ",", "toNode", ")", "-", "getFromWeight", "(", "lmIndex", ",", "fromNode", ")", ";", "int", "toWeight", "=", "getToWeight", "(", "lmIndex", ",", "fromNode", ")", "-", "getToWeight", "(", "lmIndex", ",", "toNode", ")", ";", "list", ".", "add", "(", "new", "MapEntry", "<>", "(", "reverse", "?", "Math", ".", "max", "(", "-", "fromWeight", ",", "-", "toWeight", ")", ":", "Math", ".", "max", "(", "fromWeight", ",", "toWeight", ")", ",", "lmIndex", ")", ")", ";", "}", "Collections", ".", "sort", "(", "list", ",", "SORT_BY_WEIGHT", ")", ";", "if", "(", "activeLandmarkIndices", "[", "0", "]", ">=", "0", ")", "{", "IntHashSet", "set", "=", "new", "IntHashSet", "(", "activeLandmarkIndices", ".", "length", ")", ";", "set", ".", "addAll", "(", "activeLandmarkIndices", ")", ";", "int", "existingLandmarkCounter", "=", "0", ";", "final", "int", "COUNT", "=", "Math", ".", "min", "(", "activeLandmarkIndices", ".", "length", "-", "2", ",", "2", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "activeLandmarkIndices", ".", "length", ";", "i", "++", ")", "{", "if", "(", "i", ">=", "activeLandmarkIndices", ".", "length", "-", "COUNT", "+", "existingLandmarkCounter", ")", "{", "// keep at least two of the previous landmarks (pick the best)", "break", ";", "}", "else", "{", "activeLandmarkIndices", "[", "i", "]", "=", "list", ".", "get", "(", "i", ")", ".", "getValue", "(", ")", ";", "if", "(", "set", ".", "contains", "(", "activeLandmarkIndices", "[", "i", "]", ")", ")", "existingLandmarkCounter", "++", ";", "}", "}", "}", "else", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "activeLandmarkIndices", ".", "length", ";", "i", "++", ")", "{", "activeLandmarkIndices", "[", "i", "]", "=", "list", ".", "get", "(", "i", ")", ".", "getValue", "(", ")", ";", "}", "}", "// store weight values of active landmarks in 'cache' arrays", "for", "(", "int", "i", "=", "0", ";", "i", "<", "activeLandmarkIndices", ".", "length", ";", "i", "++", ")", "{", "int", "lmIndex", "=", "activeLandmarkIndices", "[", "i", "]", ";", "activeFroms", "[", "i", "]", "=", "getFromWeight", "(", "lmIndex", ",", "toNode", ")", ";", "activeTos", "[", "i", "]", "=", "getToWeight", "(", "lmIndex", ",", "toNode", ")", ";", "}", "return", "true", ";", "}" ]
From all available landmarks pick just a few active ones
[ "From", "all", "available", "landmarks", "pick", "just", "a", "few", "active", "ones" ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/lm/LandmarkStorage.java#L585-L643
21,106
graphhopper/graphhopper
core/src/main/java/com/graphhopper/util/DistanceCalc2D.java
DistanceCalc2D.calcNormalizedDist
@Override public double calcNormalizedDist(double fromY, double fromX, double toY, double toX) { double dX = fromX - toX; double dY = fromY - toY; return dX * dX + dY * dY; }
java
@Override public double calcNormalizedDist(double fromY, double fromX, double toY, double toX) { double dX = fromX - toX; double dY = fromY - toY; return dX * dX + dY * dY; }
[ "@", "Override", "public", "double", "calcNormalizedDist", "(", "double", "fromY", ",", "double", "fromX", ",", "double", "toY", ",", "double", "toX", ")", "{", "double", "dX", "=", "fromX", "-", "toX", ";", "double", "dY", "=", "fromY", "-", "toY", ";", "return", "dX", "*", "dX", "+", "dY", "*", "dY", ";", "}" ]
Calculates in normalized meter
[ "Calculates", "in", "normalized", "meter" ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/util/DistanceCalc2D.java#L57-L62
21,107
graphhopper/graphhopper
core/src/main/java/com/graphhopper/routing/ch/CHAlgoFactoryDecorator.java
CHAlgoFactoryDecorator.setPreparationThreads
public void setPreparationThreads(int preparationThreads) { this.preparationThreads = preparationThreads; this.threadPool = java.util.concurrent.Executors.newFixedThreadPool(preparationThreads); }
java
public void setPreparationThreads(int preparationThreads) { this.preparationThreads = preparationThreads; this.threadPool = java.util.concurrent.Executors.newFixedThreadPool(preparationThreads); }
[ "public", "void", "setPreparationThreads", "(", "int", "preparationThreads", ")", "{", "this", ".", "preparationThreads", "=", "preparationThreads", ";", "this", ".", "threadPool", "=", "java", ".", "util", ".", "concurrent", ".", "Executors", ".", "newFixedThreadPool", "(", "preparationThreads", ")", ";", "}" ]
This method changes the number of threads used for preparation on import. Default is 1. Make sure that you have enough memory when increasing this number!
[ "This", "method", "changes", "the", "number", "of", "threads", "used", "for", "preparation", "on", "import", ".", "Default", "is", "1", ".", "Make", "sure", "that", "you", "have", "enough", "memory", "when", "increasing", "this", "number!" ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/ch/CHAlgoFactoryDecorator.java#L277-L280
21,108
graphhopper/graphhopper
core/src/main/java/com/graphhopper/storage/AbstractDataAccess.java
AbstractDataAccess.writeHeader
protected void writeHeader(RandomAccessFile file, long length, int segmentSize) throws IOException { file.seek(0); file.writeUTF("GH"); file.writeLong(length); file.writeInt(segmentSize); for (int i = 0; i < header.length; i++) { file.writeInt(header[i]); } }
java
protected void writeHeader(RandomAccessFile file, long length, int segmentSize) throws IOException { file.seek(0); file.writeUTF("GH"); file.writeLong(length); file.writeInt(segmentSize); for (int i = 0; i < header.length; i++) { file.writeInt(header[i]); } }
[ "protected", "void", "writeHeader", "(", "RandomAccessFile", "file", ",", "long", "length", ",", "int", "segmentSize", ")", "throws", "IOException", "{", "file", ".", "seek", "(", "0", ")", ";", "file", ".", "writeUTF", "(", "\"GH\"", ")", ";", "file", ".", "writeLong", "(", "length", ")", ";", "file", ".", "writeInt", "(", "segmentSize", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "header", ".", "length", ";", "i", "++", ")", "{", "file", ".", "writeInt", "(", "header", "[", "i", "]", ")", ";", "}", "}" ]
Writes some internal data into the beginning of the specified file.
[ "Writes", "some", "internal", "data", "into", "the", "beginning", "of", "the", "specified", "file", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/storage/AbstractDataAccess.java#L91-L99
21,109
graphhopper/graphhopper
core/src/main/java/com/graphhopper/routing/AlgorithmOptions.java
AlgorithmOptions.start
public static Builder start(AlgorithmOptions opts) { Builder b = new Builder(); if (opts.algorithm != null) b.algorithm(opts.getAlgorithm()); if (opts.traversalMode != null) b.traversalMode(opts.getTraversalMode()); if (opts.weighting != null) b.weighting(opts.getWeighting()); if (opts.maxVisitedNodes >= 0) b.maxVisitedNodes(opts.maxVisitedNodes); if (!opts.hints.isEmpty()) b.hints(opts.hints); return b; }
java
public static Builder start(AlgorithmOptions opts) { Builder b = new Builder(); if (opts.algorithm != null) b.algorithm(opts.getAlgorithm()); if (opts.traversalMode != null) b.traversalMode(opts.getTraversalMode()); if (opts.weighting != null) b.weighting(opts.getWeighting()); if (opts.maxVisitedNodes >= 0) b.maxVisitedNodes(opts.maxVisitedNodes); if (!opts.hints.isEmpty()) b.hints(opts.hints); return b; }
[ "public", "static", "Builder", "start", "(", "AlgorithmOptions", "opts", ")", "{", "Builder", "b", "=", "new", "Builder", "(", ")", ";", "if", "(", "opts", ".", "algorithm", "!=", "null", ")", "b", ".", "algorithm", "(", "opts", ".", "getAlgorithm", "(", ")", ")", ";", "if", "(", "opts", ".", "traversalMode", "!=", "null", ")", "b", ".", "traversalMode", "(", "opts", ".", "getTraversalMode", "(", ")", ")", ";", "if", "(", "opts", ".", "weighting", "!=", "null", ")", "b", ".", "weighting", "(", "opts", ".", "getWeighting", "(", ")", ")", ";", "if", "(", "opts", ".", "maxVisitedNodes", ">=", "0", ")", "b", ".", "maxVisitedNodes", "(", "opts", ".", "maxVisitedNodes", ")", ";", "if", "(", "!", "opts", ".", "hints", ".", "isEmpty", "(", ")", ")", "b", ".", "hints", "(", "opts", ".", "hints", ")", ";", "return", "b", ";", "}" ]
This method clones the specified AlgorithmOption object with the possibility for further changes.
[ "This", "method", "clones", "the", "specified", "AlgorithmOption", "object", "with", "the", "possibility", "for", "further", "changes", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/AlgorithmOptions.java#L72-L86
21,110
graphhopper/graphhopper
core/src/main/java/com/graphhopper/storage/StorableProperties.java
StorableProperties.put
public synchronized StorableProperties put(String key, Object val) { if (!key.equals(toLowerCase(key))) throw new IllegalArgumentException("Do not use upper case keys (" + key + ") for StorableProperties since 0.7"); map.put(key, val.toString()); return this; }
java
public synchronized StorableProperties put(String key, Object val) { if (!key.equals(toLowerCase(key))) throw new IllegalArgumentException("Do not use upper case keys (" + key + ") for StorableProperties since 0.7"); map.put(key, val.toString()); return this; }
[ "public", "synchronized", "StorableProperties", "put", "(", "String", "key", ",", "Object", "val", ")", "{", "if", "(", "!", "key", ".", "equals", "(", "toLowerCase", "(", "key", ")", ")", ")", "throw", "new", "IllegalArgumentException", "(", "\"Do not use upper case keys (\"", "+", "key", "+", "\") for StorableProperties since 0.7\"", ")", ";", "map", ".", "put", "(", "key", ",", "val", ".", "toString", "(", ")", ")", ";", "return", "this", ";", "}" ]
Before it saves this value it creates a string out of it.
[ "Before", "it", "saves", "this", "value", "it", "creates", "a", "string", "out", "of", "it", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/storage/StorableProperties.java#L97-L103
21,111
graphhopper/graphhopper
reader-gtfs/src/main/java/com/conveyal/gtfs/model/Service.java
Service.activeOn
public boolean activeOn (LocalDate date) { // first check for exceptions CalendarDate exception = calendar_dates.get(date); if (exception != null) return exception.exception_type == 1; else if (calendar == null) return false; else { int gtfsDate = date.getYear() * 10000 + date.getMonthValue() * 100 + date.getDayOfMonth(); boolean withinValidityRange = calendar.end_date >= gtfsDate && calendar.start_date <= gtfsDate; if (!withinValidityRange) return false; switch (date.getDayOfWeek()) { case MONDAY: return calendar.monday == 1; case TUESDAY: return calendar.tuesday == 1; case WEDNESDAY: return calendar.wednesday == 1; case THURSDAY: return calendar.thursday == 1; case FRIDAY: return calendar.friday == 1; case SATURDAY: return calendar.saturday == 1; case SUNDAY: return calendar.sunday == 1; default: throw new IllegalArgumentException("unknown day of week constant!"); } } }
java
public boolean activeOn (LocalDate date) { // first check for exceptions CalendarDate exception = calendar_dates.get(date); if (exception != null) return exception.exception_type == 1; else if (calendar == null) return false; else { int gtfsDate = date.getYear() * 10000 + date.getMonthValue() * 100 + date.getDayOfMonth(); boolean withinValidityRange = calendar.end_date >= gtfsDate && calendar.start_date <= gtfsDate; if (!withinValidityRange) return false; switch (date.getDayOfWeek()) { case MONDAY: return calendar.monday == 1; case TUESDAY: return calendar.tuesday == 1; case WEDNESDAY: return calendar.wednesday == 1; case THURSDAY: return calendar.thursday == 1; case FRIDAY: return calendar.friday == 1; case SATURDAY: return calendar.saturday == 1; case SUNDAY: return calendar.sunday == 1; default: throw new IllegalArgumentException("unknown day of week constant!"); } } }
[ "public", "boolean", "activeOn", "(", "LocalDate", "date", ")", "{", "// first check for exceptions", "CalendarDate", "exception", "=", "calendar_dates", ".", "get", "(", "date", ")", ";", "if", "(", "exception", "!=", "null", ")", "return", "exception", ".", "exception_type", "==", "1", ";", "else", "if", "(", "calendar", "==", "null", ")", "return", "false", ";", "else", "{", "int", "gtfsDate", "=", "date", ".", "getYear", "(", ")", "*", "10000", "+", "date", ".", "getMonthValue", "(", ")", "*", "100", "+", "date", ".", "getDayOfMonth", "(", ")", ";", "boolean", "withinValidityRange", "=", "calendar", ".", "end_date", ">=", "gtfsDate", "&&", "calendar", ".", "start_date", "<=", "gtfsDate", ";", "if", "(", "!", "withinValidityRange", ")", "return", "false", ";", "switch", "(", "date", ".", "getDayOfWeek", "(", ")", ")", "{", "case", "MONDAY", ":", "return", "calendar", ".", "monday", "==", "1", ";", "case", "TUESDAY", ":", "return", "calendar", ".", "tuesday", "==", "1", ";", "case", "WEDNESDAY", ":", "return", "calendar", ".", "wednesday", "==", "1", ";", "case", "THURSDAY", ":", "return", "calendar", ".", "thursday", "==", "1", ";", "case", "FRIDAY", ":", "return", "calendar", ".", "friday", "==", "1", ";", "case", "SATURDAY", ":", "return", "calendar", ".", "saturday", "==", "1", ";", "case", "SUNDAY", ":", "return", "calendar", ".", "sunday", "==", "1", ";", "default", ":", "throw", "new", "IllegalArgumentException", "(", "\"unknown day of week constant!\"", ")", ";", "}", "}", "}" ]
Is this service active on the specified date?
[ "Is", "this", "service", "active", "on", "the", "specified", "date?" ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/reader-gtfs/src/main/java/com/conveyal/gtfs/model/Service.java#L114-L149
21,112
graphhopper/graphhopper
reader-gtfs/src/main/java/com/conveyal/gtfs/model/Service.java
Service.checkOverlap
public static boolean checkOverlap (Service s1, Service s2) { if (s1.calendar == null || s2.calendar == null) { return false; } // overlap exists if at least one day of week is shared by two calendars boolean overlappingDays = s1.calendar.monday == 1 && s2.calendar.monday == 1 || s1.calendar.tuesday == 1 && s2.calendar.tuesday == 1 || s1.calendar.wednesday == 1 && s2.calendar.wednesday == 1 || s1.calendar.thursday == 1 && s2.calendar.thursday == 1 || s1.calendar.friday == 1 && s2.calendar.friday == 1 || s1.calendar.saturday == 1 && s2.calendar.saturday == 1 || s1.calendar.sunday == 1 && s2.calendar.sunday == 1; return overlappingDays; }
java
public static boolean checkOverlap (Service s1, Service s2) { if (s1.calendar == null || s2.calendar == null) { return false; } // overlap exists if at least one day of week is shared by two calendars boolean overlappingDays = s1.calendar.monday == 1 && s2.calendar.monday == 1 || s1.calendar.tuesday == 1 && s2.calendar.tuesday == 1 || s1.calendar.wednesday == 1 && s2.calendar.wednesday == 1 || s1.calendar.thursday == 1 && s2.calendar.thursday == 1 || s1.calendar.friday == 1 && s2.calendar.friday == 1 || s1.calendar.saturday == 1 && s2.calendar.saturday == 1 || s1.calendar.sunday == 1 && s2.calendar.sunday == 1; return overlappingDays; }
[ "public", "static", "boolean", "checkOverlap", "(", "Service", "s1", ",", "Service", "s2", ")", "{", "if", "(", "s1", ".", "calendar", "==", "null", "||", "s2", ".", "calendar", "==", "null", ")", "{", "return", "false", ";", "}", "// overlap exists if at least one day of week is shared by two calendars", "boolean", "overlappingDays", "=", "s1", ".", "calendar", ".", "monday", "==", "1", "&&", "s2", ".", "calendar", ".", "monday", "==", "1", "||", "s1", ".", "calendar", ".", "tuesday", "==", "1", "&&", "s2", ".", "calendar", ".", "tuesday", "==", "1", "||", "s1", ".", "calendar", ".", "wednesday", "==", "1", "&&", "s2", ".", "calendar", ".", "wednesday", "==", "1", "||", "s1", ".", "calendar", ".", "thursday", "==", "1", "&&", "s2", ".", "calendar", ".", "thursday", "==", "1", "||", "s1", ".", "calendar", ".", "friday", "==", "1", "&&", "s2", ".", "calendar", ".", "friday", "==", "1", "||", "s1", ".", "calendar", ".", "saturday", "==", "1", "&&", "s2", ".", "calendar", ".", "saturday", "==", "1", "||", "s1", ".", "calendar", ".", "sunday", "==", "1", "&&", "s2", ".", "calendar", ".", "sunday", "==", "1", ";", "return", "overlappingDays", ";", "}" ]
Checks for overlapping days of week between two service calendars @param s1 @param s2 @return true if both calendars simultaneously operate on at least one day of the week
[ "Checks", "for", "overlapping", "days", "of", "week", "between", "two", "service", "calendars" ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/reader-gtfs/src/main/java/com/conveyal/gtfs/model/Service.java#L157-L170
21,113
graphhopper/graphhopper
api/src/main/java/com/graphhopper/util/PointList.java
PointList.copy
public PointList copy(int from, int end) { if (from > end) throw new IllegalArgumentException("from must be smaller or equal to end"); if (from < 0 || end > getSize()) throw new IllegalArgumentException("Illegal interval: " + from + ", " + end + ", size:" + getSize()); PointList thisPL = this; if (this instanceof ShallowImmutablePointList) { ShallowImmutablePointList spl = (ShallowImmutablePointList) this; thisPL = spl.wrappedPointList; from = spl.fromOffset + from; end = spl.fromOffset + end; } int len = end - from; PointList copyPL = new PointList(len, is3D()); copyPL.size = len; copyPL.isImmutable = isImmutable(); System.arraycopy(thisPL.latitudes, from, copyPL.latitudes, 0, len); System.arraycopy(thisPL.longitudes, from, copyPL.longitudes, 0, len); if (is3D()) System.arraycopy(thisPL.elevations, from, copyPL.elevations, 0, len); return copyPL; }
java
public PointList copy(int from, int end) { if (from > end) throw new IllegalArgumentException("from must be smaller or equal to end"); if (from < 0 || end > getSize()) throw new IllegalArgumentException("Illegal interval: " + from + ", " + end + ", size:" + getSize()); PointList thisPL = this; if (this instanceof ShallowImmutablePointList) { ShallowImmutablePointList spl = (ShallowImmutablePointList) this; thisPL = spl.wrappedPointList; from = spl.fromOffset + from; end = spl.fromOffset + end; } int len = end - from; PointList copyPL = new PointList(len, is3D()); copyPL.size = len; copyPL.isImmutable = isImmutable(); System.arraycopy(thisPL.latitudes, from, copyPL.latitudes, 0, len); System.arraycopy(thisPL.longitudes, from, copyPL.longitudes, 0, len); if (is3D()) System.arraycopy(thisPL.elevations, from, copyPL.elevations, 0, len); return copyPL; }
[ "public", "PointList", "copy", "(", "int", "from", ",", "int", "end", ")", "{", "if", "(", "from", ">", "end", ")", "throw", "new", "IllegalArgumentException", "(", "\"from must be smaller or equal to end\"", ")", ";", "if", "(", "from", "<", "0", "||", "end", ">", "getSize", "(", ")", ")", "throw", "new", "IllegalArgumentException", "(", "\"Illegal interval: \"", "+", "from", "+", "\", \"", "+", "end", "+", "\", size:\"", "+", "getSize", "(", ")", ")", ";", "PointList", "thisPL", "=", "this", ";", "if", "(", "this", "instanceof", "ShallowImmutablePointList", ")", "{", "ShallowImmutablePointList", "spl", "=", "(", "ShallowImmutablePointList", ")", "this", ";", "thisPL", "=", "spl", ".", "wrappedPointList", ";", "from", "=", "spl", ".", "fromOffset", "+", "from", ";", "end", "=", "spl", ".", "fromOffset", "+", "end", ";", "}", "int", "len", "=", "end", "-", "from", ";", "PointList", "copyPL", "=", "new", "PointList", "(", "len", ",", "is3D", "(", ")", ")", ";", "copyPL", ".", "size", "=", "len", ";", "copyPL", ".", "isImmutable", "=", "isImmutable", "(", ")", ";", "System", ".", "arraycopy", "(", "thisPL", ".", "latitudes", ",", "from", ",", "copyPL", ".", "latitudes", ",", "0", ",", "len", ")", ";", "System", ".", "arraycopy", "(", "thisPL", ".", "longitudes", ",", "from", ",", "copyPL", ".", "longitudes", ",", "0", ",", "len", ")", ";", "if", "(", "is3D", "(", ")", ")", "System", ".", "arraycopy", "(", "thisPL", ".", "elevations", ",", "from", ",", "copyPL", ".", "elevations", ",", "0", ",", "len", ")", ";", "return", "copyPL", ";", "}" ]
This method does a deep copy of this object for the specified range. @param from the copying of the old PointList starts at this index @param end the copying of the old PointList ends at the index before (i.e. end is exclusive)
[ "This", "method", "does", "a", "deep", "copy", "of", "this", "object", "for", "the", "specified", "range", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/api/src/main/java/com/graphhopper/util/PointList.java#L489-L513
21,114
graphhopper/graphhopper
api/src/main/java/com/graphhopper/util/PointList.java
PointList.shallowCopy
public PointList shallowCopy(final int from, final int end, boolean makeImmutable) { if (makeImmutable) this.makeImmutable(); return new ShallowImmutablePointList(from, end, this); }
java
public PointList shallowCopy(final int from, final int end, boolean makeImmutable) { if (makeImmutable) this.makeImmutable(); return new ShallowImmutablePointList(from, end, this); }
[ "public", "PointList", "shallowCopy", "(", "final", "int", "from", ",", "final", "int", "end", ",", "boolean", "makeImmutable", ")", "{", "if", "(", "makeImmutable", ")", "this", ".", "makeImmutable", "(", ")", ";", "return", "new", "ShallowImmutablePointList", "(", "from", ",", "end", ",", "this", ")", ";", "}" ]
Create a shallow copy of this Pointlist from from to end, excluding end. @param makeImmutable makes this PointList immutable. If you don't ensure the consistency it might happen that due to changes of this object, the shallow copy might contain incorrect or corrupt data.
[ "Create", "a", "shallow", "copy", "of", "this", "Pointlist", "from", "from", "to", "end", "excluding", "end", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/api/src/main/java/com/graphhopper/util/PointList.java#L521-L525
21,115
graphhopper/graphhopper
core/src/main/java/com/graphhopper/storage/IntsRef.java
IntsRef.compareTo
@Override public int compareTo(IntsRef other) { if (this == other) return 0; final int[] aInts = this.ints; int aUpto = this.offset; final int[] bInts = other.ints; int bUpto = other.offset; final int aStop = aUpto + Math.min(this.length, other.length); while (aUpto < aStop) { int aInt = aInts[aUpto++]; int bInt = bInts[bUpto++]; if (aInt > bInt) { return 1; } else if (aInt < bInt) { return -1; } } // One is a prefix of the other, or, they are equal: return this.length - other.length; }
java
@Override public int compareTo(IntsRef other) { if (this == other) return 0; final int[] aInts = this.ints; int aUpto = this.offset; final int[] bInts = other.ints; int bUpto = other.offset; final int aStop = aUpto + Math.min(this.length, other.length); while (aUpto < aStop) { int aInt = aInts[aUpto++]; int bInt = bInts[bUpto++]; if (aInt > bInt) { return 1; } else if (aInt < bInt) { return -1; } } // One is a prefix of the other, or, they are equal: return this.length - other.length; }
[ "@", "Override", "public", "int", "compareTo", "(", "IntsRef", "other", ")", "{", "if", "(", "this", "==", "other", ")", "return", "0", ";", "final", "int", "[", "]", "aInts", "=", "this", ".", "ints", ";", "int", "aUpto", "=", "this", ".", "offset", ";", "final", "int", "[", "]", "bInts", "=", "other", ".", "ints", ";", "int", "bUpto", "=", "other", ".", "offset", ";", "final", "int", "aStop", "=", "aUpto", "+", "Math", ".", "min", "(", "this", ".", "length", ",", "other", ".", "length", ")", ";", "while", "(", "aUpto", "<", "aStop", ")", "{", "int", "aInt", "=", "aInts", "[", "aUpto", "++", "]", ";", "int", "bInt", "=", "bInts", "[", "bUpto", "++", "]", ";", "if", "(", "aInt", ">", "bInt", ")", "{", "return", "1", ";", "}", "else", "if", "(", "aInt", "<", "bInt", ")", "{", "return", "-", "1", ";", "}", "}", "// One is a prefix of the other, or, they are equal:", "return", "this", ".", "length", "-", "other", ".", "length", ";", "}" ]
Signed int order comparison
[ "Signed", "int", "order", "comparison" ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/storage/IntsRef.java#L110-L129
21,116
graphhopper/graphhopper
core/src/main/java/com/graphhopper/routing/weighting/AvoidEdgesWeighting.java
AvoidEdgesWeighting.addEdges
public void addEdges(Collection<EdgeIteratorState> edges) { for (EdgeIteratorState edge : edges) { visitedEdges.add(edge.getEdge()); } }
java
public void addEdges(Collection<EdgeIteratorState> edges) { for (EdgeIteratorState edge : edges) { visitedEdges.add(edge.getEdge()); } }
[ "public", "void", "addEdges", "(", "Collection", "<", "EdgeIteratorState", ">", "edges", ")", "{", "for", "(", "EdgeIteratorState", "edge", ":", "edges", ")", "{", "visitedEdges", ".", "add", "(", "edge", ".", "getEdge", "(", ")", ")", ";", "}", "}" ]
This method adds the specified path to this weighting which should be penalized in the calcWeight method.
[ "This", "method", "adds", "the", "specified", "path", "to", "this", "weighting", "which", "should", "be", "penalized", "in", "the", "calcWeight", "method", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/weighting/AvoidEdgesWeighting.java#L50-L54
21,117
graphhopper/graphhopper
core/src/main/java/com/graphhopper/routing/Path.java
Path.extract
public Path extract() { if (isFound()) throw new IllegalStateException("Extract can only be called once"); extractSW.start(); SPTEntry currEdge = sptEntry; setEndNode(currEdge.adjNode); boolean nextEdgeValid = EdgeIterator.Edge.isValid(currEdge.edge); int nextEdge; while (nextEdgeValid) { // the reverse search needs the next edge nextEdgeValid = EdgeIterator.Edge.isValid(currEdge.parent.edge); nextEdge = nextEdgeValid ? currEdge.parent.edge : EdgeIterator.NO_EDGE; processEdge(currEdge.edge, currEdge.adjNode, nextEdge); currEdge = currEdge.parent; } setFromNode(currEdge.adjNode); reverseOrder(); extractSW.stop(); return setFound(true); }
java
public Path extract() { if (isFound()) throw new IllegalStateException("Extract can only be called once"); extractSW.start(); SPTEntry currEdge = sptEntry; setEndNode(currEdge.adjNode); boolean nextEdgeValid = EdgeIterator.Edge.isValid(currEdge.edge); int nextEdge; while (nextEdgeValid) { // the reverse search needs the next edge nextEdgeValid = EdgeIterator.Edge.isValid(currEdge.parent.edge); nextEdge = nextEdgeValid ? currEdge.parent.edge : EdgeIterator.NO_EDGE; processEdge(currEdge.edge, currEdge.adjNode, nextEdge); currEdge = currEdge.parent; } setFromNode(currEdge.adjNode); reverseOrder(); extractSW.stop(); return setFound(true); }
[ "public", "Path", "extract", "(", ")", "{", "if", "(", "isFound", "(", ")", ")", "throw", "new", "IllegalStateException", "(", "\"Extract can only be called once\"", ")", ";", "extractSW", ".", "start", "(", ")", ";", "SPTEntry", "currEdge", "=", "sptEntry", ";", "setEndNode", "(", "currEdge", ".", "adjNode", ")", ";", "boolean", "nextEdgeValid", "=", "EdgeIterator", ".", "Edge", ".", "isValid", "(", "currEdge", ".", "edge", ")", ";", "int", "nextEdge", ";", "while", "(", "nextEdgeValid", ")", "{", "// the reverse search needs the next edge", "nextEdgeValid", "=", "EdgeIterator", ".", "Edge", ".", "isValid", "(", "currEdge", ".", "parent", ".", "edge", ")", ";", "nextEdge", "=", "nextEdgeValid", "?", "currEdge", ".", "parent", ".", "edge", ":", "EdgeIterator", ".", "NO_EDGE", ";", "processEdge", "(", "currEdge", ".", "edge", ",", "currEdge", ".", "adjNode", ",", "nextEdge", ")", ";", "currEdge", "=", "currEdge", ".", "parent", ";", "}", "setFromNode", "(", "currEdge", ".", "adjNode", ")", ";", "reverseOrder", "(", ")", ";", "extractSW", ".", "stop", "(", ")", ";", "return", "setFound", "(", "true", ")", ";", "}" ]
Extracts the Path from the shortest-path-tree determined by sptEntry.
[ "Extracts", "the", "Path", "from", "the", "shortest", "-", "path", "-", "tree", "determined", "by", "sptEntry", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/Path.java#L193-L214
21,118
graphhopper/graphhopper
core/src/main/java/com/graphhopper/routing/Path.java
Path.processEdge
protected void processEdge(int edgeId, int adjNode, int prevEdgeId) { EdgeIteratorState iter = graph.getEdgeIteratorState(edgeId, adjNode); distance += iter.getDistance(); time += weighting.calcMillis(iter, false, prevEdgeId); addEdge(edgeId); }
java
protected void processEdge(int edgeId, int adjNode, int prevEdgeId) { EdgeIteratorState iter = graph.getEdgeIteratorState(edgeId, adjNode); distance += iter.getDistance(); time += weighting.calcMillis(iter, false, prevEdgeId); addEdge(edgeId); }
[ "protected", "void", "processEdge", "(", "int", "edgeId", ",", "int", "adjNode", ",", "int", "prevEdgeId", ")", "{", "EdgeIteratorState", "iter", "=", "graph", ".", "getEdgeIteratorState", "(", "edgeId", ",", "adjNode", ")", ";", "distance", "+=", "iter", ".", "getDistance", "(", ")", ";", "time", "+=", "weighting", ".", "calcMillis", "(", "iter", ",", "false", ",", "prevEdgeId", ")", ";", "addEdge", "(", "edgeId", ")", ";", "}" ]
Calculates the distance and time of the specified edgeId. Also it adds the edgeId to the path list. @param prevEdgeId here the edge that comes before edgeId is necessary. I.e. for the reverse search we need the next edge.
[ "Calculates", "the", "distance", "and", "time", "of", "the", "specified", "edgeId", ".", "Also", "it", "adds", "the", "edgeId", "to", "the", "path", "list", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/Path.java#L240-L245
21,119
graphhopper/graphhopper
core/src/main/java/com/graphhopper/routing/Path.java
Path.calcEdges
public List<EdgeIteratorState> calcEdges() { final List<EdgeIteratorState> edges = new ArrayList<>(edgeIds.size()); if (edgeIds.isEmpty()) return edges; forEveryEdge(new EdgeVisitor() { @Override public void next(EdgeIteratorState eb, int index, int prevEdgeId) { edges.add(eb); } @Override public void finish() { } }); return edges; }
java
public List<EdgeIteratorState> calcEdges() { final List<EdgeIteratorState> edges = new ArrayList<>(edgeIds.size()); if (edgeIds.isEmpty()) return edges; forEveryEdge(new EdgeVisitor() { @Override public void next(EdgeIteratorState eb, int index, int prevEdgeId) { edges.add(eb); } @Override public void finish() { } }); return edges; }
[ "public", "List", "<", "EdgeIteratorState", ">", "calcEdges", "(", ")", "{", "final", "List", "<", "EdgeIteratorState", ">", "edges", "=", "new", "ArrayList", "<>", "(", "edgeIds", ".", "size", "(", ")", ")", ";", "if", "(", "edgeIds", ".", "isEmpty", "(", ")", ")", "return", "edges", ";", "forEveryEdge", "(", "new", "EdgeVisitor", "(", ")", "{", "@", "Override", "public", "void", "next", "(", "EdgeIteratorState", "eb", ",", "int", "index", ",", "int", "prevEdgeId", ")", "{", "edges", ".", "add", "(", "eb", ")", ";", "}", "@", "Override", "public", "void", "finish", "(", ")", "{", "}", "}", ")", ";", "return", "edges", ";", "}" ]
Returns the list of all edges.
[ "Returns", "the", "list", "of", "all", "edges", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/Path.java#L278-L295
21,120
graphhopper/graphhopper
core/src/main/java/com/graphhopper/routing/Path.java
Path.calcDetails
public Map<String, List<PathDetail>> calcDetails(List<String> requestedPathDetails, PathDetailsBuilderFactory pathBuilderFactory, int previousIndex) { if (!isFound() || requestedPathDetails.isEmpty()) return Collections.emptyMap(); List<PathDetailsBuilder> pathBuilders = pathBuilderFactory.createPathDetailsBuilders(requestedPathDetails, encoder, weighting); if (pathBuilders.isEmpty()) return Collections.emptyMap(); forEveryEdge(new PathDetailsFromEdges(pathBuilders, previousIndex)); Map<String, List<PathDetail>> pathDetails = new HashMap<>(pathBuilders.size()); for (PathDetailsBuilder builder : pathBuilders) { Map.Entry<String, List<PathDetail>> entry = builder.build(); List<PathDetail> existing = pathDetails.put(entry.getKey(), entry.getValue()); if (existing != null) throw new IllegalStateException("Some PathDetailsBuilders use duplicate key: " + entry.getKey()); } return pathDetails; }
java
public Map<String, List<PathDetail>> calcDetails(List<String> requestedPathDetails, PathDetailsBuilderFactory pathBuilderFactory, int previousIndex) { if (!isFound() || requestedPathDetails.isEmpty()) return Collections.emptyMap(); List<PathDetailsBuilder> pathBuilders = pathBuilderFactory.createPathDetailsBuilders(requestedPathDetails, encoder, weighting); if (pathBuilders.isEmpty()) return Collections.emptyMap(); forEveryEdge(new PathDetailsFromEdges(pathBuilders, previousIndex)); Map<String, List<PathDetail>> pathDetails = new HashMap<>(pathBuilders.size()); for (PathDetailsBuilder builder : pathBuilders) { Map.Entry<String, List<PathDetail>> entry = builder.build(); List<PathDetail> existing = pathDetails.put(entry.getKey(), entry.getValue()); if (existing != null) throw new IllegalStateException("Some PathDetailsBuilders use duplicate key: " + entry.getKey()); } return pathDetails; }
[ "public", "Map", "<", "String", ",", "List", "<", "PathDetail", ">", ">", "calcDetails", "(", "List", "<", "String", ">", "requestedPathDetails", ",", "PathDetailsBuilderFactory", "pathBuilderFactory", ",", "int", "previousIndex", ")", "{", "if", "(", "!", "isFound", "(", ")", "||", "requestedPathDetails", ".", "isEmpty", "(", ")", ")", "return", "Collections", ".", "emptyMap", "(", ")", ";", "List", "<", "PathDetailsBuilder", ">", "pathBuilders", "=", "pathBuilderFactory", ".", "createPathDetailsBuilders", "(", "requestedPathDetails", ",", "encoder", ",", "weighting", ")", ";", "if", "(", "pathBuilders", ".", "isEmpty", "(", ")", ")", "return", "Collections", ".", "emptyMap", "(", ")", ";", "forEveryEdge", "(", "new", "PathDetailsFromEdges", "(", "pathBuilders", ",", "previousIndex", ")", ")", ";", "Map", "<", "String", ",", "List", "<", "PathDetail", ">", ">", "pathDetails", "=", "new", "HashMap", "<>", "(", "pathBuilders", ".", "size", "(", ")", ")", ";", "for", "(", "PathDetailsBuilder", "builder", ":", "pathBuilders", ")", "{", "Map", ".", "Entry", "<", "String", ",", "List", "<", "PathDetail", ">", ">", "entry", "=", "builder", ".", "build", "(", ")", ";", "List", "<", "PathDetail", ">", "existing", "=", "pathDetails", ".", "put", "(", "entry", ".", "getKey", "(", ")", ",", "entry", ".", "getValue", "(", ")", ")", ";", "if", "(", "existing", "!=", "null", ")", "throw", "new", "IllegalStateException", "(", "\"Some PathDetailsBuilders use duplicate key: \"", "+", "entry", ".", "getKey", "(", ")", ")", ";", "}", "return", "pathDetails", ";", "}" ]
Calculates the PathDetails for this Path. This method will return fast, if there are no calculators. @param pathBuilderFactory Generates the relevant PathBuilders @return List of PathDetails for this Path
[ "Calculates", "the", "PathDetails", "for", "this", "Path", ".", "This", "method", "will", "return", "fast", "if", "there", "are", "no", "calculators", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/Path.java#L380-L398
21,121
graphhopper/graphhopper
core/src/main/java/com/graphhopper/reader/ReaderElement.java
ReaderElement.hasTag
public boolean hasTag(String key, String... values) { Object value = properties.get(key); if (value == null) return false; // tag present, no values given: success if (values.length == 0) return true; for (String val : values) { if (val.equals(value)) return true; } return false; }
java
public boolean hasTag(String key, String... values) { Object value = properties.get(key); if (value == null) return false; // tag present, no values given: success if (values.length == 0) return true; for (String val : values) { if (val.equals(value)) return true; } return false; }
[ "public", "boolean", "hasTag", "(", "String", "key", ",", "String", "...", "values", ")", "{", "Object", "value", "=", "properties", ".", "get", "(", "key", ")", ";", "if", "(", "value", "==", "null", ")", "return", "false", ";", "// tag present, no values given: success", "if", "(", "values", ".", "length", "==", "0", ")", "return", "true", ";", "for", "(", "String", "val", ":", "values", ")", "{", "if", "(", "val", ".", "equals", "(", "value", ")", ")", "return", "true", ";", "}", "return", "false", ";", "}" ]
Check that a given tag has one of the specified values. If no values are given, just checks for presence of the tag
[ "Check", "that", "a", "given", "tag", "has", "one", "of", "the", "specified", "values", ".", "If", "no", "values", "are", "given", "just", "checks", "for", "presence", "of", "the", "tag" ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/reader/ReaderElement.java#L113-L127
21,122
graphhopper/graphhopper
core/src/main/java/com/graphhopper/reader/ReaderElement.java
ReaderElement.hasTag
public final boolean hasTag(String key, Set<String> values) { return values.contains(getTag(key, "")); }
java
public final boolean hasTag(String key, Set<String> values) { return values.contains(getTag(key, "")); }
[ "public", "final", "boolean", "hasTag", "(", "String", "key", ",", "Set", "<", "String", ">", "values", ")", "{", "return", "values", ".", "contains", "(", "getTag", "(", "key", ",", "\"\"", ")", ")", ";", "}" ]
Check that a given tag has one of the specified values.
[ "Check", "that", "a", "given", "tag", "has", "one", "of", "the", "specified", "values", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/reader/ReaderElement.java#L132-L134
21,123
graphhopper/graphhopper
core/src/main/java/com/graphhopper/reader/ReaderElement.java
ReaderElement.hasTag
public boolean hasTag(List<String> keyList, Set<String> values) { for (String key : keyList) { if (values.contains(getTag(key, ""))) return true; } return false; }
java
public boolean hasTag(List<String> keyList, Set<String> values) { for (String key : keyList) { if (values.contains(getTag(key, ""))) return true; } return false; }
[ "public", "boolean", "hasTag", "(", "List", "<", "String", ">", "keyList", ",", "Set", "<", "String", ">", "values", ")", "{", "for", "(", "String", "key", ":", "keyList", ")", "{", "if", "(", "values", ".", "contains", "(", "getTag", "(", "key", ",", "\"\"", ")", ")", ")", "return", "true", ";", "}", "return", "false", ";", "}" ]
Check a number of tags in the given order for the any of the given values. Used to parse hierarchical access restrictions
[ "Check", "a", "number", "of", "tags", "in", "the", "given", "order", "for", "the", "any", "of", "the", "given", "values", ".", "Used", "to", "parse", "hierarchical", "access", "restrictions" ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/reader/ReaderElement.java#L140-L146
21,124
graphhopper/graphhopper
core/src/main/java/com/graphhopper/reader/ReaderElement.java
ReaderElement.getFirstPriorityTag
public String getFirstPriorityTag(List<String> restrictions) { for (String str : restrictions) { if (hasTag(str)) return getTag(str); } return ""; }
java
public String getFirstPriorityTag(List<String> restrictions) { for (String str : restrictions) { if (hasTag(str)) return getTag(str); } return ""; }
[ "public", "String", "getFirstPriorityTag", "(", "List", "<", "String", ">", "restrictions", ")", "{", "for", "(", "String", "str", ":", "restrictions", ")", "{", "if", "(", "hasTag", "(", "str", ")", ")", "return", "getTag", "(", "str", ")", ";", "}", "return", "\"\"", ";", "}" ]
Returns the first existing tag of the specified list where the order is important.
[ "Returns", "the", "first", "existing", "tag", "of", "the", "specified", "list", "where", "the", "order", "is", "important", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/reader/ReaderElement.java#L151-L157
21,125
graphhopper/graphhopper
core/src/main/java/com/graphhopper/routing/util/AbstractFlagEncoder.java
AbstractFlagEncoder.createEncodedValues
public void createEncodedValues(List<EncodedValue> registerNewEncodedValue, String prefix, int index) { // define the first 2 speedBits in flags for routing registerNewEncodedValue.add(accessEnc = new SimpleBooleanEncodedValue(prefix + "access", true)); roundaboutEnc = getBooleanEncodedValue(EncodingManager.ROUNDABOUT); encoderBit = 1L << index; }
java
public void createEncodedValues(List<EncodedValue> registerNewEncodedValue, String prefix, int index) { // define the first 2 speedBits in flags for routing registerNewEncodedValue.add(accessEnc = new SimpleBooleanEncodedValue(prefix + "access", true)); roundaboutEnc = getBooleanEncodedValue(EncodingManager.ROUNDABOUT); encoderBit = 1L << index; }
[ "public", "void", "createEncodedValues", "(", "List", "<", "EncodedValue", ">", "registerNewEncodedValue", ",", "String", "prefix", ",", "int", "index", ")", "{", "// define the first 2 speedBits in flags for routing", "registerNewEncodedValue", ".", "add", "(", "accessEnc", "=", "new", "SimpleBooleanEncodedValue", "(", "prefix", "+", "\"access\"", ",", "true", ")", ")", ";", "roundaboutEnc", "=", "getBooleanEncodedValue", "(", "EncodingManager", ".", "ROUNDABOUT", ")", ";", "encoderBit", "=", "1L", "<<", "index", ";", "}" ]
Defines bits used for edge flags used for access, speed etc. @return incremented shift value pointing behind the last used bit
[ "Defines", "bits", "used", "for", "edge", "flags", "used", "for", "access", "speed", "etc", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/util/AbstractFlagEncoder.java#L168-L173
21,126
graphhopper/graphhopper
core/src/main/java/com/graphhopper/routing/util/AbstractFlagEncoder.java
AbstractFlagEncoder.flagsDefault
protected void flagsDefault(IntsRef edgeFlags, boolean forward, boolean backward) { if (forward) speedEncoder.setDecimal(false, edgeFlags, speedDefault); if (backward) speedEncoder.setDecimal(true, edgeFlags, speedDefault); accessEnc.setBool(false, edgeFlags, forward); accessEnc.setBool(true, edgeFlags, backward); }
java
protected void flagsDefault(IntsRef edgeFlags, boolean forward, boolean backward) { if (forward) speedEncoder.setDecimal(false, edgeFlags, speedDefault); if (backward) speedEncoder.setDecimal(true, edgeFlags, speedDefault); accessEnc.setBool(false, edgeFlags, forward); accessEnc.setBool(true, edgeFlags, backward); }
[ "protected", "void", "flagsDefault", "(", "IntsRef", "edgeFlags", ",", "boolean", "forward", ",", "boolean", "backward", ")", "{", "if", "(", "forward", ")", "speedEncoder", ".", "setDecimal", "(", "false", ",", "edgeFlags", ",", "speedDefault", ")", ";", "if", "(", "backward", ")", "speedEncoder", ".", "setDecimal", "(", "true", ",", "edgeFlags", ",", "speedDefault", ")", ";", "accessEnc", ".", "setBool", "(", "false", ",", "edgeFlags", ",", "forward", ")", ";", "accessEnc", ".", "setBool", "(", "true", ",", "edgeFlags", ",", "backward", ")", ";", "}" ]
Sets default flags with specified access.
[ "Sets", "default", "flags", "with", "specified", "access", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/util/AbstractFlagEncoder.java#L253-L260
21,127
graphhopper/graphhopper
core/src/main/java/com/graphhopper/routing/util/AbstractFlagEncoder.java
AbstractFlagEncoder.getFerrySpeed
protected double getFerrySpeed(ReaderWay way) { long duration = 0; try { // During the reader process we have converted the duration value into a artificial tag called "duration:seconds". duration = Long.parseLong(way.getTag("duration:seconds")); } catch (Exception ex) { } // seconds to hours double durationInHours = duration / 60d / 60d; // Check if our graphhopper specific artificially created estimated_distance way tag is present Number estimatedLength = way.getTag("estimated_distance", null); if (durationInHours > 0) try { if (estimatedLength != null) { double estimatedLengthInKm = estimatedLength.doubleValue() / 1000; // If duration AND distance is available we can calculate the speed more precisely // and set both speed to the same value. Factor 1.4 slower because of waiting time! double calculatedTripSpeed = estimatedLengthInKm / durationInHours / 1.4; // Plausibility check especially for the case of wrongly used PxM format with the intention to // specify the duration in minutes, but actually using months if (calculatedTripSpeed > 0.01d) { if (calculatedTripSpeed > getMaxSpeed()) { return getMaxSpeed(); } // If the speed is lower than the speed we can store, we have to set it to the minSpeed, but > 0 if (Math.round(calculatedTripSpeed) < speedFactor / 2) { return speedFactor / 2; } return Math.round(calculatedTripSpeed); } else { long lastId = way.getNodes().isEmpty() ? -1 : way.getNodes().get(way.getNodes().size() - 1); long firstId = way.getNodes().isEmpty() ? -1 : way.getNodes().get(0); if (firstId != lastId) logger.warn("Unrealistic long duration ignored in way with way ID=" + way.getId() + " : Duration tag value=" + way.getTag("duration") + " (=" + Math.round(duration / 60d) + " minutes)"); durationInHours = 0; } } } catch (Exception ex) { } if (durationInHours == 0) { if (estimatedLength != null && estimatedLength.doubleValue() <= 300) return speedFactor / 2; // unknown speed -> put penalty on ferry transport return UNKNOWN_DURATION_FERRY_SPEED; } else if (durationInHours > 1) { // lengthy ferries should be faster than short trip ferry return LONG_TRIP_FERRY_SPEED; } else { return SHORT_TRIP_FERRY_SPEED; } }
java
protected double getFerrySpeed(ReaderWay way) { long duration = 0; try { // During the reader process we have converted the duration value into a artificial tag called "duration:seconds". duration = Long.parseLong(way.getTag("duration:seconds")); } catch (Exception ex) { } // seconds to hours double durationInHours = duration / 60d / 60d; // Check if our graphhopper specific artificially created estimated_distance way tag is present Number estimatedLength = way.getTag("estimated_distance", null); if (durationInHours > 0) try { if (estimatedLength != null) { double estimatedLengthInKm = estimatedLength.doubleValue() / 1000; // If duration AND distance is available we can calculate the speed more precisely // and set both speed to the same value. Factor 1.4 slower because of waiting time! double calculatedTripSpeed = estimatedLengthInKm / durationInHours / 1.4; // Plausibility check especially for the case of wrongly used PxM format with the intention to // specify the duration in minutes, but actually using months if (calculatedTripSpeed > 0.01d) { if (calculatedTripSpeed > getMaxSpeed()) { return getMaxSpeed(); } // If the speed is lower than the speed we can store, we have to set it to the minSpeed, but > 0 if (Math.round(calculatedTripSpeed) < speedFactor / 2) { return speedFactor / 2; } return Math.round(calculatedTripSpeed); } else { long lastId = way.getNodes().isEmpty() ? -1 : way.getNodes().get(way.getNodes().size() - 1); long firstId = way.getNodes().isEmpty() ? -1 : way.getNodes().get(0); if (firstId != lastId) logger.warn("Unrealistic long duration ignored in way with way ID=" + way.getId() + " : Duration tag value=" + way.getTag("duration") + " (=" + Math.round(duration / 60d) + " minutes)"); durationInHours = 0; } } } catch (Exception ex) { } if (durationInHours == 0) { if (estimatedLength != null && estimatedLength.doubleValue() <= 300) return speedFactor / 2; // unknown speed -> put penalty on ferry transport return UNKNOWN_DURATION_FERRY_SPEED; } else if (durationInHours > 1) { // lengthy ferries should be faster than short trip ferry return LONG_TRIP_FERRY_SPEED; } else { return SHORT_TRIP_FERRY_SPEED; } }
[ "protected", "double", "getFerrySpeed", "(", "ReaderWay", "way", ")", "{", "long", "duration", "=", "0", ";", "try", "{", "// During the reader process we have converted the duration value into a artificial tag called \"duration:seconds\".", "duration", "=", "Long", ".", "parseLong", "(", "way", ".", "getTag", "(", "\"duration:seconds\"", ")", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "}", "// seconds to hours", "double", "durationInHours", "=", "duration", "/", "60d", "/", "60d", ";", "// Check if our graphhopper specific artificially created estimated_distance way tag is present", "Number", "estimatedLength", "=", "way", ".", "getTag", "(", "\"estimated_distance\"", ",", "null", ")", ";", "if", "(", "durationInHours", ">", "0", ")", "try", "{", "if", "(", "estimatedLength", "!=", "null", ")", "{", "double", "estimatedLengthInKm", "=", "estimatedLength", ".", "doubleValue", "(", ")", "/", "1000", ";", "// If duration AND distance is available we can calculate the speed more precisely", "// and set both speed to the same value. Factor 1.4 slower because of waiting time!", "double", "calculatedTripSpeed", "=", "estimatedLengthInKm", "/", "durationInHours", "/", "1.4", ";", "// Plausibility check especially for the case of wrongly used PxM format with the intention to", "// specify the duration in minutes, but actually using months", "if", "(", "calculatedTripSpeed", ">", "0.01d", ")", "{", "if", "(", "calculatedTripSpeed", ">", "getMaxSpeed", "(", ")", ")", "{", "return", "getMaxSpeed", "(", ")", ";", "}", "// If the speed is lower than the speed we can store, we have to set it to the minSpeed, but > 0", "if", "(", "Math", ".", "round", "(", "calculatedTripSpeed", ")", "<", "speedFactor", "/", "2", ")", "{", "return", "speedFactor", "/", "2", ";", "}", "return", "Math", ".", "round", "(", "calculatedTripSpeed", ")", ";", "}", "else", "{", "long", "lastId", "=", "way", ".", "getNodes", "(", ")", ".", "isEmpty", "(", ")", "?", "-", "1", ":", "way", ".", "getNodes", "(", ")", ".", "get", "(", "way", ".", "getNodes", "(", ")", ".", "size", "(", ")", "-", "1", ")", ";", "long", "firstId", "=", "way", ".", "getNodes", "(", ")", ".", "isEmpty", "(", ")", "?", "-", "1", ":", "way", ".", "getNodes", "(", ")", ".", "get", "(", "0", ")", ";", "if", "(", "firstId", "!=", "lastId", ")", "logger", ".", "warn", "(", "\"Unrealistic long duration ignored in way with way ID=\"", "+", "way", ".", "getId", "(", ")", "+", "\" : Duration tag value=\"", "+", "way", ".", "getTag", "(", "\"duration\"", ")", "+", "\" (=\"", "+", "Math", ".", "round", "(", "duration", "/", "60d", ")", "+", "\" minutes)\"", ")", ";", "durationInHours", "=", "0", ";", "}", "}", "}", "catch", "(", "Exception", "ex", ")", "{", "}", "if", "(", "durationInHours", "==", "0", ")", "{", "if", "(", "estimatedLength", "!=", "null", "&&", "estimatedLength", ".", "doubleValue", "(", ")", "<=", "300", ")", "return", "speedFactor", "/", "2", ";", "// unknown speed -> put penalty on ferry transport", "return", "UNKNOWN_DURATION_FERRY_SPEED", ";", "}", "else", "if", "(", "durationInHours", ">", "1", ")", "{", "// lengthy ferries should be faster than short trip ferry", "return", "LONG_TRIP_FERRY_SPEED", ";", "}", "else", "{", "return", "SHORT_TRIP_FERRY_SPEED", ";", "}", "}" ]
Special handling for ferry ways.
[ "Special", "handling", "for", "ferry", "ways", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/util/AbstractFlagEncoder.java#L365-L419
21,128
graphhopper/graphhopper
core/src/main/java/com/graphhopper/routing/util/AbstractFlagEncoder.java
AbstractFlagEncoder.setSpeed
protected void setSpeed(boolean reverse, IntsRef edgeFlags, double speed) { if (speed < 0 || Double.isNaN(speed)) throw new IllegalArgumentException("Speed cannot be negative or NaN: " + speed + ", flags:" + BitUtil.LITTLE.toBitString(edgeFlags)); if (speed < speedFactor / 2) { speedEncoder.setDecimal(reverse, edgeFlags, 0); accessEnc.setBool(reverse, edgeFlags, false); return; } if (speed > getMaxSpeed()) speed = getMaxSpeed(); speedEncoder.setDecimal(reverse, edgeFlags, speed); }
java
protected void setSpeed(boolean reverse, IntsRef edgeFlags, double speed) { if (speed < 0 || Double.isNaN(speed)) throw new IllegalArgumentException("Speed cannot be negative or NaN: " + speed + ", flags:" + BitUtil.LITTLE.toBitString(edgeFlags)); if (speed < speedFactor / 2) { speedEncoder.setDecimal(reverse, edgeFlags, 0); accessEnc.setBool(reverse, edgeFlags, false); return; } if (speed > getMaxSpeed()) speed = getMaxSpeed(); speedEncoder.setDecimal(reverse, edgeFlags, speed); }
[ "protected", "void", "setSpeed", "(", "boolean", "reverse", ",", "IntsRef", "edgeFlags", ",", "double", "speed", ")", "{", "if", "(", "speed", "<", "0", "||", "Double", ".", "isNaN", "(", "speed", ")", ")", "throw", "new", "IllegalArgumentException", "(", "\"Speed cannot be negative or NaN: \"", "+", "speed", "+", "\", flags:\"", "+", "BitUtil", ".", "LITTLE", ".", "toBitString", "(", "edgeFlags", ")", ")", ";", "if", "(", "speed", "<", "speedFactor", "/", "2", ")", "{", "speedEncoder", ".", "setDecimal", "(", "reverse", ",", "edgeFlags", ",", "0", ")", ";", "accessEnc", ".", "setBool", "(", "reverse", ",", "edgeFlags", ",", "false", ")", ";", "return", ";", "}", "if", "(", "speed", ">", "getMaxSpeed", "(", ")", ")", "speed", "=", "getMaxSpeed", "(", ")", ";", "speedEncoder", ".", "setDecimal", "(", "reverse", ",", "edgeFlags", ",", "speed", ")", ";", "}" ]
Most use cases do not require this method. Will still keep it accessible so that one can disable it until the averageSpeedEncodedValue is moved out of the FlagEncoder. @Deprecated
[ "Most", "use", "cases", "do", "not", "require", "this", "method", ".", "Will", "still", "keep", "it", "accessible", "so", "that", "one", "can", "disable", "it", "until", "the", "averageSpeedEncodedValue", "is", "moved", "out", "of", "the", "FlagEncoder", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/util/AbstractFlagEncoder.java#L540-L554
21,129
graphhopper/graphhopper
core/src/main/java/com/graphhopper/routing/lm/LMAlgoFactoryDecorator.java
LMAlgoFactoryDecorator.setWeightingsAsStrings
public LMAlgoFactoryDecorator setWeightingsAsStrings(List<String> weightingList) { if (weightingList.isEmpty()) throw new IllegalArgumentException("It is not allowed to pass an emtpy weightingList"); weightingsAsStrings.clear(); for (String strWeighting : weightingList) { strWeighting = toLowerCase(strWeighting); strWeighting = strWeighting.trim(); addWeighting(strWeighting); } return this; }
java
public LMAlgoFactoryDecorator setWeightingsAsStrings(List<String> weightingList) { if (weightingList.isEmpty()) throw new IllegalArgumentException("It is not allowed to pass an emtpy weightingList"); weightingsAsStrings.clear(); for (String strWeighting : weightingList) { strWeighting = toLowerCase(strWeighting); strWeighting = strWeighting.trim(); addWeighting(strWeighting); } return this; }
[ "public", "LMAlgoFactoryDecorator", "setWeightingsAsStrings", "(", "List", "<", "String", ">", "weightingList", ")", "{", "if", "(", "weightingList", ".", "isEmpty", "(", ")", ")", "throw", "new", "IllegalArgumentException", "(", "\"It is not allowed to pass an emtpy weightingList\"", ")", ";", "weightingsAsStrings", ".", "clear", "(", ")", ";", "for", "(", "String", "strWeighting", ":", "weightingList", ")", "{", "strWeighting", "=", "toLowerCase", "(", "strWeighting", ")", ";", "strWeighting", "=", "strWeighting", ".", "trim", "(", ")", ";", "addWeighting", "(", "strWeighting", ")", ";", "}", "return", "this", ";", "}" ]
Enables the use of contraction hierarchies to reduce query times. Enabled by default. @param weightingList A list containing multiple weightings like: "fastest", "shortest" or your own weight-calculation type.
[ "Enables", "the", "use", "of", "contraction", "hierarchies", "to", "reduce", "query", "times", ".", "Enabled", "by", "default", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/lm/LMAlgoFactoryDecorator.java#L147-L158
21,130
graphhopper/graphhopper
core/src/main/java/com/graphhopper/routing/lm/LMAlgoFactoryDecorator.java
LMAlgoFactoryDecorator.createPreparations
public void createPreparations(GraphHopperStorage ghStorage, LocationIndex locationIndex) { if (!isEnabled() || !preparations.isEmpty()) return; if (weightings.isEmpty()) throw new IllegalStateException("No landmark weightings found"); List<LandmarkSuggestion> lmSuggestions = new ArrayList<>(lmSuggestionsLocations.size()); if (!lmSuggestionsLocations.isEmpty()) { try { for (String loc : lmSuggestionsLocations) { lmSuggestions.add(LandmarkSuggestion.readLandmarks(loc, locationIndex)); } } catch (IOException ex) { throw new RuntimeException(ex); } } for (Weighting weighting : getWeightings()) { Double maximumWeight = maximumWeights.get(weighting.getName()); if (maximumWeight == null) throw new IllegalStateException("maximumWeight cannot be null. Default should be just negative. " + "Couldn't find " + weighting.getName() + " in " + maximumWeights); PrepareLandmarks tmpPrepareLM = new PrepareLandmarks(ghStorage.getDirectory(), ghStorage, weighting, landmarkCount, activeLandmarkCount). setLandmarkSuggestions(lmSuggestions). setMaximumWeight(maximumWeight). setLogDetails(logDetails); if (minNodes > 1) tmpPrepareLM.setMinimumNodes(minNodes); addPreparation(tmpPrepareLM); } }
java
public void createPreparations(GraphHopperStorage ghStorage, LocationIndex locationIndex) { if (!isEnabled() || !preparations.isEmpty()) return; if (weightings.isEmpty()) throw new IllegalStateException("No landmark weightings found"); List<LandmarkSuggestion> lmSuggestions = new ArrayList<>(lmSuggestionsLocations.size()); if (!lmSuggestionsLocations.isEmpty()) { try { for (String loc : lmSuggestionsLocations) { lmSuggestions.add(LandmarkSuggestion.readLandmarks(loc, locationIndex)); } } catch (IOException ex) { throw new RuntimeException(ex); } } for (Weighting weighting : getWeightings()) { Double maximumWeight = maximumWeights.get(weighting.getName()); if (maximumWeight == null) throw new IllegalStateException("maximumWeight cannot be null. Default should be just negative. " + "Couldn't find " + weighting.getName() + " in " + maximumWeights); PrepareLandmarks tmpPrepareLM = new PrepareLandmarks(ghStorage.getDirectory(), ghStorage, weighting, landmarkCount, activeLandmarkCount). setLandmarkSuggestions(lmSuggestions). setMaximumWeight(maximumWeight). setLogDetails(logDetails); if (minNodes > 1) tmpPrepareLM.setMinimumNodes(minNodes); addPreparation(tmpPrepareLM); } }
[ "public", "void", "createPreparations", "(", "GraphHopperStorage", "ghStorage", ",", "LocationIndex", "locationIndex", ")", "{", "if", "(", "!", "isEnabled", "(", ")", "||", "!", "preparations", ".", "isEmpty", "(", ")", ")", "return", ";", "if", "(", "weightings", ".", "isEmpty", "(", ")", ")", "throw", "new", "IllegalStateException", "(", "\"No landmark weightings found\"", ")", ";", "List", "<", "LandmarkSuggestion", ">", "lmSuggestions", "=", "new", "ArrayList", "<>", "(", "lmSuggestionsLocations", ".", "size", "(", ")", ")", ";", "if", "(", "!", "lmSuggestionsLocations", ".", "isEmpty", "(", ")", ")", "{", "try", "{", "for", "(", "String", "loc", ":", "lmSuggestionsLocations", ")", "{", "lmSuggestions", ".", "add", "(", "LandmarkSuggestion", ".", "readLandmarks", "(", "loc", ",", "locationIndex", ")", ")", ";", "}", "}", "catch", "(", "IOException", "ex", ")", "{", "throw", "new", "RuntimeException", "(", "ex", ")", ";", "}", "}", "for", "(", "Weighting", "weighting", ":", "getWeightings", "(", ")", ")", "{", "Double", "maximumWeight", "=", "maximumWeights", ".", "get", "(", "weighting", ".", "getName", "(", ")", ")", ";", "if", "(", "maximumWeight", "==", "null", ")", "throw", "new", "IllegalStateException", "(", "\"maximumWeight cannot be null. Default should be just negative. \"", "+", "\"Couldn't find \"", "+", "weighting", ".", "getName", "(", ")", "+", "\" in \"", "+", "maximumWeights", ")", ";", "PrepareLandmarks", "tmpPrepareLM", "=", "new", "PrepareLandmarks", "(", "ghStorage", ".", "getDirectory", "(", ")", ",", "ghStorage", ",", "weighting", ",", "landmarkCount", ",", "activeLandmarkCount", ")", ".", "setLandmarkSuggestions", "(", "lmSuggestions", ")", ".", "setMaximumWeight", "(", "maximumWeight", ")", ".", "setLogDetails", "(", "logDetails", ")", ";", "if", "(", "minNodes", ">", "1", ")", "tmpPrepareLM", ".", "setMinimumNodes", "(", "minNodes", ")", ";", "addPreparation", "(", "tmpPrepareLM", ")", ";", "}", "}" ]
This method creates the landmark storages ready for landmark creation.
[ "This", "method", "creates", "the", "landmark", "storages", "ready", "for", "landmark", "creation", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/lm/LMAlgoFactoryDecorator.java#L312-L344
21,131
graphhopper/graphhopper
core/src/main/java/com/graphhopper/storage/GraphBuilder.java
GraphBuilder.chGraphCreate
public CHGraph chGraphCreate(Weighting singleCHWeighting) { return setCHGraph(singleCHWeighting).create().getGraph(CHGraph.class, singleCHWeighting); }
java
public CHGraph chGraphCreate(Weighting singleCHWeighting) { return setCHGraph(singleCHWeighting).create().getGraph(CHGraph.class, singleCHWeighting); }
[ "public", "CHGraph", "chGraphCreate", "(", "Weighting", "singleCHWeighting", ")", "{", "return", "setCHGraph", "(", "singleCHWeighting", ")", ".", "create", "(", ")", ".", "getGraph", "(", "CHGraph", ".", "class", ",", "singleCHWeighting", ")", ";", "}" ]
Creates a CHGraph
[ "Creates", "a", "CHGraph" ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/storage/GraphBuilder.java#L91-L93
21,132
graphhopper/graphhopper
isochrone/src/main/java/com/graphhopper/isochrone/algorithm/Isochrone.java
Isochrone.setTimeLimit
public void setTimeLimit(double limit) { exploreType = TIME; this.limit = limit * 1000; // we explore until all spt-entries are '>timeLimitInSeconds' // and add some more into this bucket for car we need a bit more as // we otherwise get artifacts for motorway endings this.finishLimit = this.limit + Math.max(this.limit * 0.14, 200_000); }
java
public void setTimeLimit(double limit) { exploreType = TIME; this.limit = limit * 1000; // we explore until all spt-entries are '>timeLimitInSeconds' // and add some more into this bucket for car we need a bit more as // we otherwise get artifacts for motorway endings this.finishLimit = this.limit + Math.max(this.limit * 0.14, 200_000); }
[ "public", "void", "setTimeLimit", "(", "double", "limit", ")", "{", "exploreType", "=", "TIME", ";", "this", ".", "limit", "=", "limit", "*", "1000", ";", "// we explore until all spt-entries are '>timeLimitInSeconds' ", "// and add some more into this bucket for car we need a bit more as ", "// we otherwise get artifacts for motorway endings", "this", ".", "finishLimit", "=", "this", ".", "limit", "+", "Math", ".", "max", "(", "this", ".", "limit", "*", "0.14", ",", "200_000", ")", ";", "}" ]
Time limit in seconds
[ "Time", "limit", "in", "seconds" ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/isochrone/src/main/java/com/graphhopper/isochrone/algorithm/Isochrone.java#L88-L95
21,133
graphhopper/graphhopper
isochrone/src/main/java/com/graphhopper/isochrone/algorithm/Isochrone.java
Isochrone.setDistanceLimit
public void setDistanceLimit(double limit) { exploreType = DISTANCE; this.limit = limit; this.finishLimit = limit + Math.max(limit * 0.14, 2_000); }
java
public void setDistanceLimit(double limit) { exploreType = DISTANCE; this.limit = limit; this.finishLimit = limit + Math.max(limit * 0.14, 2_000); }
[ "public", "void", "setDistanceLimit", "(", "double", "limit", ")", "{", "exploreType", "=", "DISTANCE", ";", "this", ".", "limit", "=", "limit", ";", "this", ".", "finishLimit", "=", "limit", "+", "Math", ".", "max", "(", "limit", "*", "0.14", ",", "2_000", ")", ";", "}" ]
Distance limit in meter
[ "Distance", "limit", "in", "meter" ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/isochrone/src/main/java/com/graphhopper/isochrone/algorithm/Isochrone.java#L100-L104
21,134
graphhopper/graphhopper
core/src/main/java/com/graphhopper/storage/index/BresenhamLine.java
BresenhamLine.calcPoints
public static void calcPoints(final double lat1, final double lon1, final double lat2, final double lon2, final PointEmitter emitter, final double offsetLat, final double offsetLon, final double deltaLat, final double deltaLon) { // round to make results of bresenham closer to correct solution int y1 = (int) ((lat1 - offsetLat) / deltaLat); int x1 = (int) ((lon1 - offsetLon) / deltaLon); int y2 = (int) ((lat2 - offsetLat) / deltaLat); int x2 = (int) ((lon2 - offsetLon) / deltaLon); bresenham(y1, x1, y2, x2, new PointEmitter() { @Override public void set(double lat, double lon) { // +.1 to move more near the center of the tile emitter.set((lat + .1) * deltaLat + offsetLat, (lon + .1) * deltaLon + offsetLon); } }); }
java
public static void calcPoints(final double lat1, final double lon1, final double lat2, final double lon2, final PointEmitter emitter, final double offsetLat, final double offsetLon, final double deltaLat, final double deltaLon) { // round to make results of bresenham closer to correct solution int y1 = (int) ((lat1 - offsetLat) / deltaLat); int x1 = (int) ((lon1 - offsetLon) / deltaLon); int y2 = (int) ((lat2 - offsetLat) / deltaLat); int x2 = (int) ((lon2 - offsetLon) / deltaLon); bresenham(y1, x1, y2, x2, new PointEmitter() { @Override public void set(double lat, double lon) { // +.1 to move more near the center of the tile emitter.set((lat + .1) * deltaLat + offsetLat, (lon + .1) * deltaLon + offsetLon); } }); }
[ "public", "static", "void", "calcPoints", "(", "final", "double", "lat1", ",", "final", "double", "lon1", ",", "final", "double", "lat2", ",", "final", "double", "lon2", ",", "final", "PointEmitter", "emitter", ",", "final", "double", "offsetLat", ",", "final", "double", "offsetLon", ",", "final", "double", "deltaLat", ",", "final", "double", "deltaLon", ")", "{", "// round to make results of bresenham closer to correct solution", "int", "y1", "=", "(", "int", ")", "(", "(", "lat1", "-", "offsetLat", ")", "/", "deltaLat", ")", ";", "int", "x1", "=", "(", "int", ")", "(", "(", "lon1", "-", "offsetLon", ")", "/", "deltaLon", ")", ";", "int", "y2", "=", "(", "int", ")", "(", "(", "lat2", "-", "offsetLat", ")", "/", "deltaLat", ")", ";", "int", "x2", "=", "(", "int", ")", "(", "(", "lon2", "-", "offsetLon", ")", "/", "deltaLon", ")", ";", "bresenham", "(", "y1", ",", "x1", ",", "y2", ",", "x2", ",", "new", "PointEmitter", "(", ")", "{", "@", "Override", "public", "void", "set", "(", "double", "lat", ",", "double", "lon", ")", "{", "// +.1 to move more near the center of the tile", "emitter", ".", "set", "(", "(", "lat", "+", ".1", ")", "*", "deltaLat", "+", "offsetLat", ",", "(", "lon", "+", ".1", ")", "*", "deltaLon", "+", "offsetLon", ")", ";", "}", "}", ")", ";", "}" ]
Calls the Bresenham algorithm but make it working for double values
[ "Calls", "the", "Bresenham", "algorithm", "but", "make", "it", "working", "for", "double", "values" ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/storage/index/BresenhamLine.java#L65-L82
21,135
graphhopper/graphhopper
core/src/main/java/com/graphhopper/routing/ch/EdgeBasedNodeContractor.java
EdgeBasedNodeContractor.loopShortcutNecessary
private boolean loopShortcutNecessary(int node, int firstOrigEdge, int lastOrigEdge, double loopWeight) { EdgeIterator inIter = loopAvoidanceInEdgeExplorer.setBaseNode(node); while (inIter.next()) { EdgeIterator outIter = loopAvoidanceOutEdgeExplorer.setBaseNode(node); double inTurnCost = getTurnCost(inIter.getEdge(), node, firstOrigEdge); while (outIter.next()) { double totalLoopCost = inTurnCost + loopWeight + getTurnCost(lastOrigEdge, node, outIter.getEdge()); double directTurnCost = getTurnCost(inIter.getEdge(), node, outIter.getEdge()); if (totalLoopCost < directTurnCost) { return true; } } } LOGGER.trace("Loop avoidance -> no shortcut"); return false; }
java
private boolean loopShortcutNecessary(int node, int firstOrigEdge, int lastOrigEdge, double loopWeight) { EdgeIterator inIter = loopAvoidanceInEdgeExplorer.setBaseNode(node); while (inIter.next()) { EdgeIterator outIter = loopAvoidanceOutEdgeExplorer.setBaseNode(node); double inTurnCost = getTurnCost(inIter.getEdge(), node, firstOrigEdge); while (outIter.next()) { double totalLoopCost = inTurnCost + loopWeight + getTurnCost(lastOrigEdge, node, outIter.getEdge()); double directTurnCost = getTurnCost(inIter.getEdge(), node, outIter.getEdge()); if (totalLoopCost < directTurnCost) { return true; } } } LOGGER.trace("Loop avoidance -> no shortcut"); return false; }
[ "private", "boolean", "loopShortcutNecessary", "(", "int", "node", ",", "int", "firstOrigEdge", ",", "int", "lastOrigEdge", ",", "double", "loopWeight", ")", "{", "EdgeIterator", "inIter", "=", "loopAvoidanceInEdgeExplorer", ".", "setBaseNode", "(", "node", ")", ";", "while", "(", "inIter", ".", "next", "(", ")", ")", "{", "EdgeIterator", "outIter", "=", "loopAvoidanceOutEdgeExplorer", ".", "setBaseNode", "(", "node", ")", ";", "double", "inTurnCost", "=", "getTurnCost", "(", "inIter", ".", "getEdge", "(", ")", ",", "node", ",", "firstOrigEdge", ")", ";", "while", "(", "outIter", ".", "next", "(", ")", ")", "{", "double", "totalLoopCost", "=", "inTurnCost", "+", "loopWeight", "+", "getTurnCost", "(", "lastOrigEdge", ",", "node", ",", "outIter", ".", "getEdge", "(", ")", ")", ";", "double", "directTurnCost", "=", "getTurnCost", "(", "inIter", ".", "getEdge", "(", ")", ",", "node", ",", "outIter", ".", "getEdge", "(", ")", ")", ";", "if", "(", "totalLoopCost", "<", "directTurnCost", ")", "{", "return", "true", ";", "}", "}", "}", "LOGGER", ".", "trace", "(", "\"Loop avoidance -> no shortcut\"", ")", ";", "return", "false", ";", "}" ]
A given potential loop shortcut is only necessary if there is at least one pair of original in- & out-edges for which taking the loop is cheaper than doing the direct turn. However this is almost always the case, because doing a u-turn at any of the incoming edges is forbidden, i.e. he costs of the direct turn will be infinite.
[ "A", "given", "potential", "loop", "shortcut", "is", "only", "necessary", "if", "there", "is", "at", "least", "one", "pair", "of", "original", "in", "-", "&", "out", "-", "edges", "for", "which", "taking", "the", "loop", "is", "cheaper", "than", "doing", "the", "direct", "turn", ".", "However", "this", "is", "almost", "always", "the", "case", "because", "doing", "a", "u", "-", "turn", "at", "any", "of", "the", "incoming", "edges", "is", "forbidden", "i", ".", "e", ".", "he", "costs", "of", "the", "direct", "turn", "will", "be", "infinite", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/ch/EdgeBasedNodeContractor.java#L244-L260
21,136
graphhopper/graphhopper
core/src/main/java/com/graphhopper/routing/ch/WitnessPathSearcher.java
WitnessPathSearcher.initSearch
public int initSearch(int centerNode, int sourceNode, int sourceEdge) { reset(); this.sourceEdge = sourceEdge; this.sourceNode = sourceNode; this.centerNode = centerNode; setInitialEntries(sourceNode, sourceEdge, centerNode); // if there is no entry that reaches the center node we won't need to search for any witnesses if (numPathsToCenter < 1) { reset(); return 0; } currentBatchStats.numSearches++; currentBatchStats.maxNumSettledEdges += maxSettledEdges; totalStats.numSearches++; totalStats.maxNumSettledEdges += maxSettledEdges; return dijkstraHeap.getSize(); }
java
public int initSearch(int centerNode, int sourceNode, int sourceEdge) { reset(); this.sourceEdge = sourceEdge; this.sourceNode = sourceNode; this.centerNode = centerNode; setInitialEntries(sourceNode, sourceEdge, centerNode); // if there is no entry that reaches the center node we won't need to search for any witnesses if (numPathsToCenter < 1) { reset(); return 0; } currentBatchStats.numSearches++; currentBatchStats.maxNumSettledEdges += maxSettledEdges; totalStats.numSearches++; totalStats.maxNumSettledEdges += maxSettledEdges; return dijkstraHeap.getSize(); }
[ "public", "int", "initSearch", "(", "int", "centerNode", ",", "int", "sourceNode", ",", "int", "sourceEdge", ")", "{", "reset", "(", ")", ";", "this", ".", "sourceEdge", "=", "sourceEdge", ";", "this", ".", "sourceNode", "=", "sourceNode", ";", "this", ".", "centerNode", "=", "centerNode", ";", "setInitialEntries", "(", "sourceNode", ",", "sourceEdge", ",", "centerNode", ")", ";", "// if there is no entry that reaches the center node we won't need to search for any witnesses", "if", "(", "numPathsToCenter", "<", "1", ")", "{", "reset", "(", ")", ";", "return", "0", ";", "}", "currentBatchStats", ".", "numSearches", "++", ";", "currentBatchStats", ".", "maxNumSettledEdges", "+=", "maxSettledEdges", ";", "totalStats", ".", "numSearches", "++", ";", "totalStats", ".", "maxNumSettledEdges", "+=", "maxSettledEdges", ";", "return", "dijkstraHeap", ".", "getSize", "(", ")", ";", "}" ]
Deletes the shortest path tree that has been found so far and initializes a new witness path search for a given node to be contracted and search edge. @param centerNode the node to be contracted (x) @param sourceNode the neighbor node from which the search starts (s) @param sourceEdge the original edge incoming to s from which the search starts @return the number of initial entries and always 0 if we can not directly reach the center node from the given source edge, e.g. when turn costs at s do not allow this.
[ "Deletes", "the", "shortest", "path", "tree", "that", "has", "been", "found", "so", "far", "and", "initializes", "a", "new", "witness", "path", "search", "for", "a", "given", "node", "to", "be", "contracted", "and", "search", "edge", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/ch/WitnessPathSearcher.java#L143-L159
21,137
graphhopper/graphhopper
core/src/main/java/com/graphhopper/util/GHUtility.java
GHUtility.getProblems
public static List<String> getProblems(Graph g) { List<String> problems = new ArrayList<>(); int nodes = g.getNodes(); int nodeIndex = 0; NodeAccess na = g.getNodeAccess(); try { EdgeExplorer explorer = g.createEdgeExplorer(); for (; nodeIndex < nodes; nodeIndex++) { double lat = na.getLatitude(nodeIndex); if (lat > 90 || lat < -90) problems.add("latitude is not within its bounds " + lat); double lon = na.getLongitude(nodeIndex); if (lon > 180 || lon < -180) problems.add("longitude is not within its bounds " + lon); EdgeIterator iter = explorer.setBaseNode(nodeIndex); while (iter.next()) { if (iter.getAdjNode() >= nodes) { problems.add("edge of " + nodeIndex + " has a node " + iter.getAdjNode() + " greater or equal to getNodes"); } if (iter.getAdjNode() < 0) { problems.add("edge of " + nodeIndex + " has a negative node " + iter.getAdjNode()); } } } } catch (Exception ex) { throw new RuntimeException("problem with node " + nodeIndex, ex); } // for (int i = 0; i < nodes; i++) { // new BreadthFirstSearch().start(g, i); // } return problems; }
java
public static List<String> getProblems(Graph g) { List<String> problems = new ArrayList<>(); int nodes = g.getNodes(); int nodeIndex = 0; NodeAccess na = g.getNodeAccess(); try { EdgeExplorer explorer = g.createEdgeExplorer(); for (; nodeIndex < nodes; nodeIndex++) { double lat = na.getLatitude(nodeIndex); if (lat > 90 || lat < -90) problems.add("latitude is not within its bounds " + lat); double lon = na.getLongitude(nodeIndex); if (lon > 180 || lon < -180) problems.add("longitude is not within its bounds " + lon); EdgeIterator iter = explorer.setBaseNode(nodeIndex); while (iter.next()) { if (iter.getAdjNode() >= nodes) { problems.add("edge of " + nodeIndex + " has a node " + iter.getAdjNode() + " greater or equal to getNodes"); } if (iter.getAdjNode() < 0) { problems.add("edge of " + nodeIndex + " has a negative node " + iter.getAdjNode()); } } } } catch (Exception ex) { throw new RuntimeException("problem with node " + nodeIndex, ex); } // for (int i = 0; i < nodes; i++) { // new BreadthFirstSearch().start(g, i); // } return problems; }
[ "public", "static", "List", "<", "String", ">", "getProblems", "(", "Graph", "g", ")", "{", "List", "<", "String", ">", "problems", "=", "new", "ArrayList", "<>", "(", ")", ";", "int", "nodes", "=", "g", ".", "getNodes", "(", ")", ";", "int", "nodeIndex", "=", "0", ";", "NodeAccess", "na", "=", "g", ".", "getNodeAccess", "(", ")", ";", "try", "{", "EdgeExplorer", "explorer", "=", "g", ".", "createEdgeExplorer", "(", ")", ";", "for", "(", ";", "nodeIndex", "<", "nodes", ";", "nodeIndex", "++", ")", "{", "double", "lat", "=", "na", ".", "getLatitude", "(", "nodeIndex", ")", ";", "if", "(", "lat", ">", "90", "||", "lat", "<", "-", "90", ")", "problems", ".", "add", "(", "\"latitude is not within its bounds \"", "+", "lat", ")", ";", "double", "lon", "=", "na", ".", "getLongitude", "(", "nodeIndex", ")", ";", "if", "(", "lon", ">", "180", "||", "lon", "<", "-", "180", ")", "problems", ".", "add", "(", "\"longitude is not within its bounds \"", "+", "lon", ")", ";", "EdgeIterator", "iter", "=", "explorer", ".", "setBaseNode", "(", "nodeIndex", ")", ";", "while", "(", "iter", ".", "next", "(", ")", ")", "{", "if", "(", "iter", ".", "getAdjNode", "(", ")", ">=", "nodes", ")", "{", "problems", ".", "add", "(", "\"edge of \"", "+", "nodeIndex", "+", "\" has a node \"", "+", "iter", ".", "getAdjNode", "(", ")", "+", "\" greater or equal to getNodes\"", ")", ";", "}", "if", "(", "iter", ".", "getAdjNode", "(", ")", "<", "0", ")", "{", "problems", ".", "add", "(", "\"edge of \"", "+", "nodeIndex", "+", "\" has a negative node \"", "+", "iter", ".", "getAdjNode", "(", ")", ")", ";", "}", "}", "}", "}", "catch", "(", "Exception", "ex", ")", "{", "throw", "new", "RuntimeException", "(", "\"problem with node \"", "+", "nodeIndex", ",", "ex", ")", ";", "}", "// for (int i = 0; i < nodes; i++) {", "// new BreadthFirstSearch().start(g, i);", "// }", "return", "problems", ";", "}" ]
This method could throw an exception if problems like index out of bounds etc
[ "This", "method", "could", "throw", "an", "exception", "if", "problems", "like", "index", "out", "of", "bounds", "etc" ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/util/GHUtility.java#L49-L83
21,138
graphhopper/graphhopper
core/src/main/java/com/graphhopper/util/GHUtility.java
GHUtility.newStorage
public static GraphHopperStorage newStorage(GraphHopperStorage store) { Directory outdir = guessDirectory(store); boolean is3D = store.getNodeAccess().is3D(); return new GraphHopperStorage(store.getNodeBasedCHWeightings(), store.getEdgeBasedCHWeightings(), outdir, store.getEncodingManager(), is3D, store.getExtension()). create(store.getNodes()); }
java
public static GraphHopperStorage newStorage(GraphHopperStorage store) { Directory outdir = guessDirectory(store); boolean is3D = store.getNodeAccess().is3D(); return new GraphHopperStorage(store.getNodeBasedCHWeightings(), store.getEdgeBasedCHWeightings(), outdir, store.getEncodingManager(), is3D, store.getExtension()). create(store.getNodes()); }
[ "public", "static", "GraphHopperStorage", "newStorage", "(", "GraphHopperStorage", "store", ")", "{", "Directory", "outdir", "=", "guessDirectory", "(", "store", ")", ";", "boolean", "is3D", "=", "store", ".", "getNodeAccess", "(", ")", ".", "is3D", "(", ")", ";", "return", "new", "GraphHopperStorage", "(", "store", ".", "getNodeBasedCHWeightings", "(", ")", ",", "store", ".", "getEdgeBasedCHWeightings", "(", ")", ",", "outdir", ",", "store", ".", "getEncodingManager", "(", ")", ",", "is3D", ",", "store", ".", "getExtension", "(", ")", ")", ".", "create", "(", "store", ".", "getNodes", "(", ")", ")", ";", "}" ]
Create a new storage from the specified one without copying the data.
[ "Create", "a", "new", "storage", "from", "the", "specified", "one", "without", "copying", "the", "data", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/util/GHUtility.java#L397-L404
21,139
graphhopper/graphhopper
core/src/main/java/com/graphhopper/util/GHUtility.java
GHUtility.createEdgeKey
public static int createEdgeKey(int nodeA, int nodeB, int edgeId, boolean reverse) { edgeId = edgeId << 1; if (reverse) return (nodeA > nodeB) ? edgeId : edgeId + 1; return (nodeA > nodeB) ? edgeId + 1 : edgeId; }
java
public static int createEdgeKey(int nodeA, int nodeB, int edgeId, boolean reverse) { edgeId = edgeId << 1; if (reverse) return (nodeA > nodeB) ? edgeId : edgeId + 1; return (nodeA > nodeB) ? edgeId + 1 : edgeId; }
[ "public", "static", "int", "createEdgeKey", "(", "int", "nodeA", ",", "int", "nodeB", ",", "int", "edgeId", ",", "boolean", "reverse", ")", "{", "edgeId", "=", "edgeId", "<<", "1", ";", "if", "(", "reverse", ")", "return", "(", "nodeA", ">", "nodeB", ")", "?", "edgeId", ":", "edgeId", "+", "1", ";", "return", "(", "nodeA", ">", "nodeB", ")", "?", "edgeId", "+", "1", ":", "edgeId", ";", "}" ]
Creates unique positive number for specified edgeId taking into account the direction defined by nodeA, nodeB and reverse.
[ "Creates", "unique", "positive", "number", "for", "specified", "edgeId", "taking", "into", "account", "the", "direction", "defined", "by", "nodeA", "nodeB", "and", "reverse", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/util/GHUtility.java#L465-L470
21,140
graphhopper/graphhopper
core/src/main/java/com/graphhopper/util/GHUtility.java
GHUtility.getEdgeKey
public static int getEdgeKey(Graph graph, int edgeId, int node, boolean reverse) { EdgeIteratorState edgeIteratorState = graph.getEdgeIteratorState(edgeId, node); return GHUtility.createEdgeKey(edgeIteratorState.getBaseNode(), edgeIteratorState.getAdjNode(), edgeId, reverse); }
java
public static int getEdgeKey(Graph graph, int edgeId, int node, boolean reverse) { EdgeIteratorState edgeIteratorState = graph.getEdgeIteratorState(edgeId, node); return GHUtility.createEdgeKey(edgeIteratorState.getBaseNode(), edgeIteratorState.getAdjNode(), edgeId, reverse); }
[ "public", "static", "int", "getEdgeKey", "(", "Graph", "graph", ",", "int", "edgeId", ",", "int", "node", ",", "boolean", "reverse", ")", "{", "EdgeIteratorState", "edgeIteratorState", "=", "graph", ".", "getEdgeIteratorState", "(", "edgeId", ",", "node", ")", ";", "return", "GHUtility", ".", "createEdgeKey", "(", "edgeIteratorState", ".", "getBaseNode", "(", ")", ",", "edgeIteratorState", ".", "getAdjNode", "(", ")", ",", "edgeId", ",", "reverse", ")", ";", "}" ]
Returns the edge key for a given edge id and adjacent node. This is needed in a few places where the base node is not known.
[ "Returns", "the", "edge", "key", "for", "a", "given", "edge", "id", "and", "adjacent", "node", ".", "This", "is", "needed", "in", "a", "few", "places", "where", "the", "base", "node", "is", "not", "known", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/util/GHUtility.java#L498-L501
21,141
graphhopper/graphhopper
core/src/main/java/com/graphhopper/routing/util/spatialrules/countries/GermanySpatialRule.java
GermanySpatialRule.getMaxSpeed
@Override public double getMaxSpeed(String highwayTag, double _default) { // As defined in: https://wiki.openstreetmap.org/wiki/OSM_tags_for_routing/Maxspeed#Motorcar switch (highwayTag) { case "motorway": return Integer.MAX_VALUE; case "trunk": return Integer.MAX_VALUE; case "residential": return 100; case "living_street": return 4; default: return super.getMaxSpeed(highwayTag, _default); } }
java
@Override public double getMaxSpeed(String highwayTag, double _default) { // As defined in: https://wiki.openstreetmap.org/wiki/OSM_tags_for_routing/Maxspeed#Motorcar switch (highwayTag) { case "motorway": return Integer.MAX_VALUE; case "trunk": return Integer.MAX_VALUE; case "residential": return 100; case "living_street": return 4; default: return super.getMaxSpeed(highwayTag, _default); } }
[ "@", "Override", "public", "double", "getMaxSpeed", "(", "String", "highwayTag", ",", "double", "_default", ")", "{", "// As defined in: https://wiki.openstreetmap.org/wiki/OSM_tags_for_routing/Maxspeed#Motorcar", "switch", "(", "highwayTag", ")", "{", "case", "\"motorway\"", ":", "return", "Integer", ".", "MAX_VALUE", ";", "case", "\"trunk\"", ":", "return", "Integer", ".", "MAX_VALUE", ";", "case", "\"residential\"", ":", "return", "100", ";", "case", "\"living_street\"", ":", "return", "4", ";", "default", ":", "return", "super", ".", "getMaxSpeed", "(", "highwayTag", ",", "_default", ")", ";", "}", "}" ]
Germany contains roads with no speed limit. For these roads, this method will return Integer.MAX_VALUE. Your implementation should be able to handle these cases.
[ "Germany", "contains", "roads", "with", "no", "speed", "limit", ".", "For", "these", "roads", "this", "method", "will", "return", "Integer", ".", "MAX_VALUE", ".", "Your", "implementation", "should", "be", "able", "to", "handle", "these", "cases", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/util/spatialrules/countries/GermanySpatialRule.java#L34-L49
21,142
graphhopper/graphhopper
core/src/main/java/com/graphhopper/util/PathMerger.java
PathMerger.updateInstructionsWithContext
private InstructionList updateInstructionsWithContext(InstructionList instructions) { Instruction instruction; Instruction nextInstruction; for (int i = 0; i < instructions.size() - 1; i++) { instruction = instructions.get(i); if (i == 0 && !Double.isNaN(favoredHeading) && instruction.extraInfo.containsKey("heading")) { double heading = (double) instruction.extraInfo.get("heading"); double diff = Math.abs(heading - favoredHeading) % 360; if (diff > 170 && diff < 190) { // The requested heading points into the opposite direction of the calculated heading // therefore we change the continue instruction to a u-turn instruction.setSign(Instruction.U_TURN_UNKNOWN); } } if (instruction.getSign() == Instruction.REACHED_VIA) { nextInstruction = instructions.get(i + 1); if (nextInstruction.getSign() != Instruction.CONTINUE_ON_STREET || !instruction.extraInfo.containsKey("last_heading") || !nextInstruction.extraInfo.containsKey("heading")) { // TODO throw exception? continue; } double lastHeading = (double) instruction.extraInfo.get("last_heading"); double heading = (double) nextInstruction.extraInfo.get("heading"); // Since it's supposed to go back the same edge, we can be very strict with the diff double diff = Math.abs(lastHeading - heading) % 360; if (diff > 179 && diff < 181) { nextInstruction.setSign(Instruction.U_TURN_UNKNOWN); } } } return instructions; }
java
private InstructionList updateInstructionsWithContext(InstructionList instructions) { Instruction instruction; Instruction nextInstruction; for (int i = 0; i < instructions.size() - 1; i++) { instruction = instructions.get(i); if (i == 0 && !Double.isNaN(favoredHeading) && instruction.extraInfo.containsKey("heading")) { double heading = (double) instruction.extraInfo.get("heading"); double diff = Math.abs(heading - favoredHeading) % 360; if (diff > 170 && diff < 190) { // The requested heading points into the opposite direction of the calculated heading // therefore we change the continue instruction to a u-turn instruction.setSign(Instruction.U_TURN_UNKNOWN); } } if (instruction.getSign() == Instruction.REACHED_VIA) { nextInstruction = instructions.get(i + 1); if (nextInstruction.getSign() != Instruction.CONTINUE_ON_STREET || !instruction.extraInfo.containsKey("last_heading") || !nextInstruction.extraInfo.containsKey("heading")) { // TODO throw exception? continue; } double lastHeading = (double) instruction.extraInfo.get("last_heading"); double heading = (double) nextInstruction.extraInfo.get("heading"); // Since it's supposed to go back the same edge, we can be very strict with the diff double diff = Math.abs(lastHeading - heading) % 360; if (diff > 179 && diff < 181) { nextInstruction.setSign(Instruction.U_TURN_UNKNOWN); } } } return instructions; }
[ "private", "InstructionList", "updateInstructionsWithContext", "(", "InstructionList", "instructions", ")", "{", "Instruction", "instruction", ";", "Instruction", "nextInstruction", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "instructions", ".", "size", "(", ")", "-", "1", ";", "i", "++", ")", "{", "instruction", "=", "instructions", ".", "get", "(", "i", ")", ";", "if", "(", "i", "==", "0", "&&", "!", "Double", ".", "isNaN", "(", "favoredHeading", ")", "&&", "instruction", ".", "extraInfo", ".", "containsKey", "(", "\"heading\"", ")", ")", "{", "double", "heading", "=", "(", "double", ")", "instruction", ".", "extraInfo", ".", "get", "(", "\"heading\"", ")", ";", "double", "diff", "=", "Math", ".", "abs", "(", "heading", "-", "favoredHeading", ")", "%", "360", ";", "if", "(", "diff", ">", "170", "&&", "diff", "<", "190", ")", "{", "// The requested heading points into the opposite direction of the calculated heading", "// therefore we change the continue instruction to a u-turn", "instruction", ".", "setSign", "(", "Instruction", ".", "U_TURN_UNKNOWN", ")", ";", "}", "}", "if", "(", "instruction", ".", "getSign", "(", ")", "==", "Instruction", ".", "REACHED_VIA", ")", "{", "nextInstruction", "=", "instructions", ".", "get", "(", "i", "+", "1", ")", ";", "if", "(", "nextInstruction", ".", "getSign", "(", ")", "!=", "Instruction", ".", "CONTINUE_ON_STREET", "||", "!", "instruction", ".", "extraInfo", ".", "containsKey", "(", "\"last_heading\"", ")", "||", "!", "nextInstruction", ".", "extraInfo", ".", "containsKey", "(", "\"heading\"", ")", ")", "{", "// TODO throw exception?", "continue", ";", "}", "double", "lastHeading", "=", "(", "double", ")", "instruction", ".", "extraInfo", ".", "get", "(", "\"last_heading\"", ")", ";", "double", "heading", "=", "(", "double", ")", "nextInstruction", ".", "extraInfo", ".", "get", "(", "\"heading\"", ")", ";", "// Since it's supposed to go back the same edge, we can be very strict with the diff", "double", "diff", "=", "Math", ".", "abs", "(", "lastHeading", "-", "heading", ")", "%", "360", ";", "if", "(", "diff", ">", "179", "&&", "diff", "<", "181", ")", "{", "nextInstruction", ".", "setSign", "(", "Instruction", ".", "U_TURN_UNKNOWN", ")", ";", "}", "}", "}", "return", "instructions", ";", "}" ]
This method iterates over all instructions and uses the available context to improve the instructions. If the requests contains a heading, this method can transform the first continue to a u-turn if the heading points into the opposite direction of the route. At a waypoint it can transform the continue to a u-turn if the route involves turning.
[ "This", "method", "iterates", "over", "all", "instructions", "and", "uses", "the", "available", "context", "to", "improve", "the", "instructions", ".", "If", "the", "requests", "contains", "a", "heading", "this", "method", "can", "transform", "the", "first", "continue", "to", "a", "u", "-", "turn", "if", "the", "heading", "points", "into", "the", "opposite", "direction", "of", "the", "route", ".", "At", "a", "waypoint", "it", "can", "transform", "the", "continue", "to", "a", "u", "-", "turn", "if", "the", "route", "involves", "turning", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/util/PathMerger.java#L168-L205
21,143
graphhopper/graphhopper
core/src/main/java/com/graphhopper/util/DouglasPeucker.java
DouglasPeucker.subSimplify
int subSimplify(PointList points, int fromIndex, int lastIndex) { if (lastIndex - fromIndex < 2) { return 0; } int indexWithMaxDist = -1; double maxDist = -1; double firstLat = points.getLatitude(fromIndex); double firstLon = points.getLongitude(fromIndex); double lastLat = points.getLatitude(lastIndex); double lastLon = points.getLongitude(lastIndex); for (int i = fromIndex + 1; i < lastIndex; i++) { double lat = points.getLatitude(i); if (Double.isNaN(lat)) { continue; } double lon = points.getLongitude(i); double dist = calc.calcNormalizedEdgeDistance(lat, lon, firstLat, firstLon, lastLat, lastLon); if (maxDist < dist) { indexWithMaxDist = i; maxDist = dist; } } if (indexWithMaxDist < 0) { throw new IllegalStateException("maximum not found in [" + fromIndex + "," + lastIndex + "]"); } int counter = 0; if (maxDist < normedMaxDist) { for (int i = fromIndex + 1; i < lastIndex; i++) { points.set(i, Double.NaN, Double.NaN, Double.NaN); counter++; } } else { counter = subSimplify(points, fromIndex, indexWithMaxDist); counter += subSimplify(points, indexWithMaxDist, lastIndex); } return counter; }
java
int subSimplify(PointList points, int fromIndex, int lastIndex) { if (lastIndex - fromIndex < 2) { return 0; } int indexWithMaxDist = -1; double maxDist = -1; double firstLat = points.getLatitude(fromIndex); double firstLon = points.getLongitude(fromIndex); double lastLat = points.getLatitude(lastIndex); double lastLon = points.getLongitude(lastIndex); for (int i = fromIndex + 1; i < lastIndex; i++) { double lat = points.getLatitude(i); if (Double.isNaN(lat)) { continue; } double lon = points.getLongitude(i); double dist = calc.calcNormalizedEdgeDistance(lat, lon, firstLat, firstLon, lastLat, lastLon); if (maxDist < dist) { indexWithMaxDist = i; maxDist = dist; } } if (indexWithMaxDist < 0) { throw new IllegalStateException("maximum not found in [" + fromIndex + "," + lastIndex + "]"); } int counter = 0; if (maxDist < normedMaxDist) { for (int i = fromIndex + 1; i < lastIndex; i++) { points.set(i, Double.NaN, Double.NaN, Double.NaN); counter++; } } else { counter = subSimplify(points, fromIndex, indexWithMaxDist); counter += subSimplify(points, indexWithMaxDist, lastIndex); } return counter; }
[ "int", "subSimplify", "(", "PointList", "points", ",", "int", "fromIndex", ",", "int", "lastIndex", ")", "{", "if", "(", "lastIndex", "-", "fromIndex", "<", "2", ")", "{", "return", "0", ";", "}", "int", "indexWithMaxDist", "=", "-", "1", ";", "double", "maxDist", "=", "-", "1", ";", "double", "firstLat", "=", "points", ".", "getLatitude", "(", "fromIndex", ")", ";", "double", "firstLon", "=", "points", ".", "getLongitude", "(", "fromIndex", ")", ";", "double", "lastLat", "=", "points", ".", "getLatitude", "(", "lastIndex", ")", ";", "double", "lastLon", "=", "points", ".", "getLongitude", "(", "lastIndex", ")", ";", "for", "(", "int", "i", "=", "fromIndex", "+", "1", ";", "i", "<", "lastIndex", ";", "i", "++", ")", "{", "double", "lat", "=", "points", ".", "getLatitude", "(", "i", ")", ";", "if", "(", "Double", ".", "isNaN", "(", "lat", ")", ")", "{", "continue", ";", "}", "double", "lon", "=", "points", ".", "getLongitude", "(", "i", ")", ";", "double", "dist", "=", "calc", ".", "calcNormalizedEdgeDistance", "(", "lat", ",", "lon", ",", "firstLat", ",", "firstLon", ",", "lastLat", ",", "lastLon", ")", ";", "if", "(", "maxDist", "<", "dist", ")", "{", "indexWithMaxDist", "=", "i", ";", "maxDist", "=", "dist", ";", "}", "}", "if", "(", "indexWithMaxDist", "<", "0", ")", "{", "throw", "new", "IllegalStateException", "(", "\"maximum not found in [\"", "+", "fromIndex", "+", "\",\"", "+", "lastIndex", "+", "\"]\"", ")", ";", "}", "int", "counter", "=", "0", ";", "if", "(", "maxDist", "<", "normedMaxDist", ")", "{", "for", "(", "int", "i", "=", "fromIndex", "+", "1", ";", "i", "<", "lastIndex", ";", "i", "++", ")", "{", "points", ".", "set", "(", "i", ",", "Double", ".", "NaN", ",", "Double", ".", "NaN", ",", "Double", ".", "NaN", ")", ";", "counter", "++", ";", "}", "}", "else", "{", "counter", "=", "subSimplify", "(", "points", ",", "fromIndex", ",", "indexWithMaxDist", ")", ";", "counter", "+=", "subSimplify", "(", "points", ",", "indexWithMaxDist", ",", "lastIndex", ")", ";", "}", "return", "counter", ";", "}" ]
keep the points of fromIndex and lastIndex
[ "keep", "the", "points", "of", "fromIndex", "and", "lastIndex" ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/util/DouglasPeucker.java#L130-L168
21,144
graphhopper/graphhopper
core/src/main/java/com/graphhopper/routing/subnetwork/PrepareRoutingSubnetworks.java
PrepareRoutingSubnetworks.findSubnetworks
List<IntArrayList> findSubnetworks(PrepEdgeFilter filter) { final BooleanEncodedValue accessEnc = filter.getAccessEnc(); final EdgeExplorer explorer = ghStorage.createEdgeExplorer(filter); int locs = ghStorage.getNodes(); List<IntArrayList> list = new ArrayList<>(100); final GHBitSet bs = new GHBitSetImpl(locs); for (int start = 0; start < locs; start++) { if (bs.contains(start)) continue; final IntArrayList intList = new IntArrayList(20); list.add(intList); new BreadthFirstSearch() { int tmpCounter = 0; @Override protected GHBitSet createBitSet() { return bs; } @Override protected final boolean goFurther(int nodeId) { if (tmpCounter > maxEdgesPerNode.get()) maxEdgesPerNode.set(tmpCounter); tmpCounter = 0; intList.add(nodeId); return true; } @Override protected final boolean checkAdjacent(EdgeIteratorState edge) { if (edge.get(accessEnc) || edge.getReverse(accessEnc)) { tmpCounter++; return true; } return false; } }.start(explorer, start); intList.trimToSize(); } return list; }
java
List<IntArrayList> findSubnetworks(PrepEdgeFilter filter) { final BooleanEncodedValue accessEnc = filter.getAccessEnc(); final EdgeExplorer explorer = ghStorage.createEdgeExplorer(filter); int locs = ghStorage.getNodes(); List<IntArrayList> list = new ArrayList<>(100); final GHBitSet bs = new GHBitSetImpl(locs); for (int start = 0; start < locs; start++) { if (bs.contains(start)) continue; final IntArrayList intList = new IntArrayList(20); list.add(intList); new BreadthFirstSearch() { int tmpCounter = 0; @Override protected GHBitSet createBitSet() { return bs; } @Override protected final boolean goFurther(int nodeId) { if (tmpCounter > maxEdgesPerNode.get()) maxEdgesPerNode.set(tmpCounter); tmpCounter = 0; intList.add(nodeId); return true; } @Override protected final boolean checkAdjacent(EdgeIteratorState edge) { if (edge.get(accessEnc) || edge.getReverse(accessEnc)) { tmpCounter++; return true; } return false; } }.start(explorer, start); intList.trimToSize(); } return list; }
[ "List", "<", "IntArrayList", ">", "findSubnetworks", "(", "PrepEdgeFilter", "filter", ")", "{", "final", "BooleanEncodedValue", "accessEnc", "=", "filter", ".", "getAccessEnc", "(", ")", ";", "final", "EdgeExplorer", "explorer", "=", "ghStorage", ".", "createEdgeExplorer", "(", "filter", ")", ";", "int", "locs", "=", "ghStorage", ".", "getNodes", "(", ")", ";", "List", "<", "IntArrayList", ">", "list", "=", "new", "ArrayList", "<>", "(", "100", ")", ";", "final", "GHBitSet", "bs", "=", "new", "GHBitSetImpl", "(", "locs", ")", ";", "for", "(", "int", "start", "=", "0", ";", "start", "<", "locs", ";", "start", "++", ")", "{", "if", "(", "bs", ".", "contains", "(", "start", ")", ")", "continue", ";", "final", "IntArrayList", "intList", "=", "new", "IntArrayList", "(", "20", ")", ";", "list", ".", "add", "(", "intList", ")", ";", "new", "BreadthFirstSearch", "(", ")", "{", "int", "tmpCounter", "=", "0", ";", "@", "Override", "protected", "GHBitSet", "createBitSet", "(", ")", "{", "return", "bs", ";", "}", "@", "Override", "protected", "final", "boolean", "goFurther", "(", "int", "nodeId", ")", "{", "if", "(", "tmpCounter", ">", "maxEdgesPerNode", ".", "get", "(", ")", ")", "maxEdgesPerNode", ".", "set", "(", "tmpCounter", ")", ";", "tmpCounter", "=", "0", ";", "intList", ".", "add", "(", "nodeId", ")", ";", "return", "true", ";", "}", "@", "Override", "protected", "final", "boolean", "checkAdjacent", "(", "EdgeIteratorState", "edge", ")", "{", "if", "(", "edge", ".", "get", "(", "accessEnc", ")", "||", "edge", ".", "getReverse", "(", "accessEnc", ")", ")", "{", "tmpCounter", "++", ";", "return", "true", ";", "}", "return", "false", ";", "}", "}", ".", "start", "(", "explorer", ",", "start", ")", ";", "intList", ".", "trimToSize", "(", ")", ";", "}", "return", "list", ";", "}" ]
This method finds the double linked components according to the specified filter.
[ "This", "method", "finds", "the", "double", "linked", "components", "according", "to", "the", "specified", "filter", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/subnetwork/PrepareRoutingSubnetworks.java#L107-L150
21,145
graphhopper/graphhopper
core/src/main/java/com/graphhopper/routing/subnetwork/PrepareRoutingSubnetworks.java
PrepareRoutingSubnetworks.keepLargeNetworks
int keepLargeNetworks(PrepEdgeFilter filter, List<IntArrayList> components) { if (components.size() <= 1) return 0; int maxCount = -1; IntIndexedContainer oldComponent = null; int allRemoved = 0; BooleanEncodedValue accessEnc = filter.getAccessEnc(); EdgeExplorer explorer = ghStorage.createEdgeExplorer(filter); for (IntArrayList component : components) { if (maxCount < 0) { maxCount = component.size(); oldComponent = component; continue; } int removedEdges; if (maxCount < component.size()) { // new biggest area found. remove old removedEdges = removeEdges(explorer, accessEnc, oldComponent, minNetworkSize); maxCount = component.size(); oldComponent = component; } else { removedEdges = removeEdges(explorer, accessEnc, component, minNetworkSize); } allRemoved += removedEdges; } if (allRemoved > ghStorage.getAllEdges().length() / 2) throw new IllegalStateException("Too many total edges were removed: " + allRemoved + ", all edges:" + ghStorage.getAllEdges().length()); return allRemoved; }
java
int keepLargeNetworks(PrepEdgeFilter filter, List<IntArrayList> components) { if (components.size() <= 1) return 0; int maxCount = -1; IntIndexedContainer oldComponent = null; int allRemoved = 0; BooleanEncodedValue accessEnc = filter.getAccessEnc(); EdgeExplorer explorer = ghStorage.createEdgeExplorer(filter); for (IntArrayList component : components) { if (maxCount < 0) { maxCount = component.size(); oldComponent = component; continue; } int removedEdges; if (maxCount < component.size()) { // new biggest area found. remove old removedEdges = removeEdges(explorer, accessEnc, oldComponent, minNetworkSize); maxCount = component.size(); oldComponent = component; } else { removedEdges = removeEdges(explorer, accessEnc, component, minNetworkSize); } allRemoved += removedEdges; } if (allRemoved > ghStorage.getAllEdges().length() / 2) throw new IllegalStateException("Too many total edges were removed: " + allRemoved + ", all edges:" + ghStorage.getAllEdges().length()); return allRemoved; }
[ "int", "keepLargeNetworks", "(", "PrepEdgeFilter", "filter", ",", "List", "<", "IntArrayList", ">", "components", ")", "{", "if", "(", "components", ".", "size", "(", ")", "<=", "1", ")", "return", "0", ";", "int", "maxCount", "=", "-", "1", ";", "IntIndexedContainer", "oldComponent", "=", "null", ";", "int", "allRemoved", "=", "0", ";", "BooleanEncodedValue", "accessEnc", "=", "filter", ".", "getAccessEnc", "(", ")", ";", "EdgeExplorer", "explorer", "=", "ghStorage", ".", "createEdgeExplorer", "(", "filter", ")", ";", "for", "(", "IntArrayList", "component", ":", "components", ")", "{", "if", "(", "maxCount", "<", "0", ")", "{", "maxCount", "=", "component", ".", "size", "(", ")", ";", "oldComponent", "=", "component", ";", "continue", ";", "}", "int", "removedEdges", ";", "if", "(", "maxCount", "<", "component", ".", "size", "(", ")", ")", "{", "// new biggest area found. remove old", "removedEdges", "=", "removeEdges", "(", "explorer", ",", "accessEnc", ",", "oldComponent", ",", "minNetworkSize", ")", ";", "maxCount", "=", "component", ".", "size", "(", ")", ";", "oldComponent", "=", "component", ";", "}", "else", "{", "removedEdges", "=", "removeEdges", "(", "explorer", ",", "accessEnc", ",", "component", ",", "minNetworkSize", ")", ";", "}", "allRemoved", "+=", "removedEdges", ";", "}", "if", "(", "allRemoved", ">", "ghStorage", ".", "getAllEdges", "(", ")", ".", "length", "(", ")", "/", "2", ")", "throw", "new", "IllegalStateException", "(", "\"Too many total edges were removed: \"", "+", "allRemoved", "+", "\", all edges:\"", "+", "ghStorage", ".", "getAllEdges", "(", ")", ".", "length", "(", ")", ")", ";", "return", "allRemoved", ";", "}" ]
Deletes all but the largest subnetworks.
[ "Deletes", "all", "but", "the", "largest", "subnetworks", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/subnetwork/PrepareRoutingSubnetworks.java#L155-L188
21,146
graphhopper/graphhopper
core/src/main/java/com/graphhopper/routing/subnetwork/PrepareRoutingSubnetworks.java
PrepareRoutingSubnetworks.removeEdges
int removeEdges(final PrepEdgeFilter bothFilter, List<IntArrayList> components, int min) { // remove edges determined from nodes but only if less than minimum size EdgeExplorer explorer = ghStorage.createEdgeExplorer(bothFilter); int removedEdges = 0; for (IntArrayList component : components) { removedEdges += removeEdges(explorer, bothFilter.getAccessEnc(), component, min); } return removedEdges; }
java
int removeEdges(final PrepEdgeFilter bothFilter, List<IntArrayList> components, int min) { // remove edges determined from nodes but only if less than minimum size EdgeExplorer explorer = ghStorage.createEdgeExplorer(bothFilter); int removedEdges = 0; for (IntArrayList component : components) { removedEdges += removeEdges(explorer, bothFilter.getAccessEnc(), component, min); } return removedEdges; }
[ "int", "removeEdges", "(", "final", "PrepEdgeFilter", "bothFilter", ",", "List", "<", "IntArrayList", ">", "components", ",", "int", "min", ")", "{", "// remove edges determined from nodes but only if less than minimum size", "EdgeExplorer", "explorer", "=", "ghStorage", ".", "createEdgeExplorer", "(", "bothFilter", ")", ";", "int", "removedEdges", "=", "0", ";", "for", "(", "IntArrayList", "component", ":", "components", ")", "{", "removedEdges", "+=", "removeEdges", "(", "explorer", ",", "bothFilter", ".", "getAccessEnc", "(", ")", ",", "component", ",", "min", ")", ";", "}", "return", "removedEdges", ";", "}" ]
This method removes the access to edges available from the nodes contained in the components. But only if a components' size is smaller then the specified min value. @return number of removed edges
[ "This", "method", "removes", "the", "access", "to", "edges", "available", "from", "the", "nodes", "contained", "in", "the", "components", ".", "But", "only", "if", "a", "components", "size", "is", "smaller", "then", "the", "specified", "min", "value", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/subnetwork/PrepareRoutingSubnetworks.java#L216-L224
21,147
graphhopper/graphhopper
core/src/main/java/com/graphhopper/routing/subnetwork/PrepareRoutingSubnetworks.java
PrepareRoutingSubnetworks.markNodesRemovedIfUnreachable
void markNodesRemovedIfUnreachable() { EdgeExplorer edgeExplorer = ghStorage.createEdgeExplorer(); for (int nodeIndex = 0; nodeIndex < ghStorage.getNodes(); nodeIndex++) { if (detectNodeRemovedForAllEncoders(edgeExplorer, nodeIndex)) ghStorage.markNodeRemoved(nodeIndex); } }
java
void markNodesRemovedIfUnreachable() { EdgeExplorer edgeExplorer = ghStorage.createEdgeExplorer(); for (int nodeIndex = 0; nodeIndex < ghStorage.getNodes(); nodeIndex++) { if (detectNodeRemovedForAllEncoders(edgeExplorer, nodeIndex)) ghStorage.markNodeRemoved(nodeIndex); } }
[ "void", "markNodesRemovedIfUnreachable", "(", ")", "{", "EdgeExplorer", "edgeExplorer", "=", "ghStorage", ".", "createEdgeExplorer", "(", ")", ";", "for", "(", "int", "nodeIndex", "=", "0", ";", "nodeIndex", "<", "ghStorage", ".", "getNodes", "(", ")", ";", "nodeIndex", "++", ")", "{", "if", "(", "detectNodeRemovedForAllEncoders", "(", "edgeExplorer", ",", "nodeIndex", ")", ")", "ghStorage", ".", "markNodeRemoved", "(", "nodeIndex", ")", ";", "}", "}" ]
Removes nodes if all edges are not accessible. I.e. removes zero degree nodes.
[ "Removes", "nodes", "if", "all", "edges", "are", "not", "accessible", ".", "I", ".", "e", ".", "removes", "zero", "degree", "nodes", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/subnetwork/PrepareRoutingSubnetworks.java#L244-L250
21,148
graphhopper/graphhopper
core/src/main/java/com/graphhopper/routing/subnetwork/PrepareRoutingSubnetworks.java
PrepareRoutingSubnetworks.detectNodeRemovedForAllEncoders
boolean detectNodeRemovedForAllEncoders(EdgeExplorer edgeExplorerAllEdges, int nodeIndex) { // we could implement a 'fast check' for several previously marked removed nodes via GHBitSet // removedNodesPerVehicle. The problem is that we would need long-indices but BitSet only supports int (due to nodeIndex*numberOfEncoders) // if no edges are reachable return true EdgeIterator iter = edgeExplorerAllEdges.setBaseNode(nodeIndex); while (iter.next()) { // if at least on encoder allows one direction return false for (BooleanEncodedValue accessEnc : accessEncList) { if (iter.get(accessEnc) || iter.getReverse(accessEnc)) return false; } } return true; }
java
boolean detectNodeRemovedForAllEncoders(EdgeExplorer edgeExplorerAllEdges, int nodeIndex) { // we could implement a 'fast check' for several previously marked removed nodes via GHBitSet // removedNodesPerVehicle. The problem is that we would need long-indices but BitSet only supports int (due to nodeIndex*numberOfEncoders) // if no edges are reachable return true EdgeIterator iter = edgeExplorerAllEdges.setBaseNode(nodeIndex); while (iter.next()) { // if at least on encoder allows one direction return false for (BooleanEncodedValue accessEnc : accessEncList) { if (iter.get(accessEnc) || iter.getReverse(accessEnc)) return false; } } return true; }
[ "boolean", "detectNodeRemovedForAllEncoders", "(", "EdgeExplorer", "edgeExplorerAllEdges", ",", "int", "nodeIndex", ")", "{", "// we could implement a 'fast check' for several previously marked removed nodes via GHBitSet ", "// removedNodesPerVehicle. The problem is that we would need long-indices but BitSet only supports int (due to nodeIndex*numberOfEncoders)", "// if no edges are reachable return true", "EdgeIterator", "iter", "=", "edgeExplorerAllEdges", ".", "setBaseNode", "(", "nodeIndex", ")", ";", "while", "(", "iter", ".", "next", "(", ")", ")", "{", "// if at least on encoder allows one direction return false", "for", "(", "BooleanEncodedValue", "accessEnc", ":", "accessEncList", ")", "{", "if", "(", "iter", ".", "get", "(", "accessEnc", ")", "||", "iter", ".", "getReverse", "(", "accessEnc", ")", ")", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
This method checks if the node is removed or inaccessible for ALL encoders. @return true if no edges are reachable from the specified nodeIndex for any flag encoder.
[ "This", "method", "checks", "if", "the", "node", "is", "removed", "or", "inaccessible", "for", "ALL", "encoders", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/subnetwork/PrepareRoutingSubnetworks.java#L257-L272
21,149
graphhopper/graphhopper
core/src/main/java/com/graphhopper/coll/CompressedArray.java
CompressedArray.decompress
public static byte[] decompress(byte[] value) throws DataFormatException { // Create an expandable byte array to hold the decompressed data ByteArrayOutputStream bos = new ByteArrayOutputStream(value.length); Inflater decompressor = new Inflater(); try { decompressor.setInput(value); final byte[] buf = new byte[1024]; while (!decompressor.finished()) { int count = decompressor.inflate(buf); bos.write(buf, 0, count); } } finally { decompressor.end(); } return bos.toByteArray(); }
java
public static byte[] decompress(byte[] value) throws DataFormatException { // Create an expandable byte array to hold the decompressed data ByteArrayOutputStream bos = new ByteArrayOutputStream(value.length); Inflater decompressor = new Inflater(); try { decompressor.setInput(value); final byte[] buf = new byte[1024]; while (!decompressor.finished()) { int count = decompressor.inflate(buf); bos.write(buf, 0, count); } } finally { decompressor.end(); } return bos.toByteArray(); }
[ "public", "static", "byte", "[", "]", "decompress", "(", "byte", "[", "]", "value", ")", "throws", "DataFormatException", "{", "// Create an expandable byte array to hold the decompressed data", "ByteArrayOutputStream", "bos", "=", "new", "ByteArrayOutputStream", "(", "value", ".", "length", ")", ";", "Inflater", "decompressor", "=", "new", "Inflater", "(", ")", ";", "try", "{", "decompressor", ".", "setInput", "(", "value", ")", ";", "final", "byte", "[", "]", "buf", "=", "new", "byte", "[", "1024", "]", ";", "while", "(", "!", "decompressor", ".", "finished", "(", ")", ")", "{", "int", "count", "=", "decompressor", ".", "inflate", "(", "buf", ")", ";", "bos", ".", "write", "(", "buf", ",", "0", ",", "count", ")", ";", "}", "}", "finally", "{", "decompressor", ".", "end", "(", ")", ";", "}", "return", "bos", ".", "toByteArray", "(", ")", ";", "}" ]
Decompress the byte array previously returned by compress
[ "Decompress", "the", "byte", "array", "previously", "returned", "by", "compress" ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/coll/CompressedArray.java#L96-L112
21,150
graphhopper/graphhopper
core/src/main/java/com/graphhopper/storage/TurnCostExtension.java
TurnCostExtension.addTurnInfo
public void addTurnInfo(int fromEdge, int viaNode, int toEdge, long turnFlags) { // no need to store turn information if (turnFlags == EMPTY_FLAGS) return; mergeOrOverwriteTurnInfo(fromEdge, viaNode, toEdge, turnFlags, true); }
java
public void addTurnInfo(int fromEdge, int viaNode, int toEdge, long turnFlags) { // no need to store turn information if (turnFlags == EMPTY_FLAGS) return; mergeOrOverwriteTurnInfo(fromEdge, viaNode, toEdge, turnFlags, true); }
[ "public", "void", "addTurnInfo", "(", "int", "fromEdge", ",", "int", "viaNode", ",", "int", "toEdge", ",", "long", "turnFlags", ")", "{", "// no need to store turn information", "if", "(", "turnFlags", "==", "EMPTY_FLAGS", ")", "return", ";", "mergeOrOverwriteTurnInfo", "(", "fromEdge", ",", "viaNode", ",", "toEdge", ",", "turnFlags", ",", "true", ")", ";", "}" ]
Add an entry which is a turn restriction or cost information via the turnFlags. Overwrite existing information if it is the same edges and node.
[ "Add", "an", "entry", "which", "is", "a", "turn", "restriction", "or", "cost", "information", "via", "the", "turnFlags", ".", "Overwrite", "existing", "information", "if", "it", "is", "the", "same", "edges", "and", "node", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/storage/TurnCostExtension.java#L113-L119
21,151
graphhopper/graphhopper
core/src/main/java/com/graphhopper/storage/TurnCostExtension.java
TurnCostExtension.mergeOrOverwriteTurnInfo
public void mergeOrOverwriteTurnInfo(int fromEdge, int viaNode, int toEdge, long turnFlags, boolean merge) { int newEntryIndex = turnCostsCount; ensureTurnCostIndex(newEntryIndex); boolean oldEntryFound = false; long newFlags = turnFlags; int next = NO_TURN_ENTRY; // determine if we already have a cost entry for this node int previousEntryIndex = nodeAccess.getAdditionalNodeField(viaNode); if (previousEntryIndex == NO_TURN_ENTRY) { // set cost-pointer to this new cost entry nodeAccess.setAdditionalNodeField(viaNode, newEntryIndex); } else { int i = 0; next = turnCosts.getInt((long) previousEntryIndex * turnCostsEntryBytes + TC_NEXT); long existingFlags = 0; while (true) { long costsIdx = (long) previousEntryIndex * turnCostsEntryBytes; if (fromEdge == turnCosts.getInt(costsIdx + TC_FROM) && toEdge == turnCosts.getInt(costsIdx + TC_TO)) { // there is already an entry for this turn oldEntryFound = true; existingFlags = turnCosts.getInt(costsIdx + TC_FLAGS); break; } else if (next == NO_TURN_ENTRY) { break; } previousEntryIndex = next; // search for the last added cost entry if (i++ > 1000) { throw new IllegalStateException("Something unexpected happened. A node probably will not have 1000+ relations."); } // get index of next turn cost entry next = turnCosts.getInt((long) next * turnCostsEntryBytes + TC_NEXT); } if (!oldEntryFound) { // set next-pointer to this new cost entry turnCosts.setInt((long) previousEntryIndex * turnCostsEntryBytes + TC_NEXT, newEntryIndex); } else if (merge) { newFlags = existingFlags | newFlags; } else { // overwrite! } } long costsBase; // where to (over)write if (!oldEntryFound) { costsBase = (long) newEntryIndex * turnCostsEntryBytes; turnCostsCount++; } else { costsBase = (long) previousEntryIndex * turnCostsEntryBytes; } turnCosts.setInt(costsBase + TC_FROM, fromEdge); turnCosts.setInt(costsBase + TC_TO, toEdge); turnCosts.setInt(costsBase + TC_FLAGS, (int) newFlags); turnCosts.setInt(costsBase + TC_NEXT, next); }
java
public void mergeOrOverwriteTurnInfo(int fromEdge, int viaNode, int toEdge, long turnFlags, boolean merge) { int newEntryIndex = turnCostsCount; ensureTurnCostIndex(newEntryIndex); boolean oldEntryFound = false; long newFlags = turnFlags; int next = NO_TURN_ENTRY; // determine if we already have a cost entry for this node int previousEntryIndex = nodeAccess.getAdditionalNodeField(viaNode); if (previousEntryIndex == NO_TURN_ENTRY) { // set cost-pointer to this new cost entry nodeAccess.setAdditionalNodeField(viaNode, newEntryIndex); } else { int i = 0; next = turnCosts.getInt((long) previousEntryIndex * turnCostsEntryBytes + TC_NEXT); long existingFlags = 0; while (true) { long costsIdx = (long) previousEntryIndex * turnCostsEntryBytes; if (fromEdge == turnCosts.getInt(costsIdx + TC_FROM) && toEdge == turnCosts.getInt(costsIdx + TC_TO)) { // there is already an entry for this turn oldEntryFound = true; existingFlags = turnCosts.getInt(costsIdx + TC_FLAGS); break; } else if (next == NO_TURN_ENTRY) { break; } previousEntryIndex = next; // search for the last added cost entry if (i++ > 1000) { throw new IllegalStateException("Something unexpected happened. A node probably will not have 1000+ relations."); } // get index of next turn cost entry next = turnCosts.getInt((long) next * turnCostsEntryBytes + TC_NEXT); } if (!oldEntryFound) { // set next-pointer to this new cost entry turnCosts.setInt((long) previousEntryIndex * turnCostsEntryBytes + TC_NEXT, newEntryIndex); } else if (merge) { newFlags = existingFlags | newFlags; } else { // overwrite! } } long costsBase; // where to (over)write if (!oldEntryFound) { costsBase = (long) newEntryIndex * turnCostsEntryBytes; turnCostsCount++; } else { costsBase = (long) previousEntryIndex * turnCostsEntryBytes; } turnCosts.setInt(costsBase + TC_FROM, fromEdge); turnCosts.setInt(costsBase + TC_TO, toEdge); turnCosts.setInt(costsBase + TC_FLAGS, (int) newFlags); turnCosts.setInt(costsBase + TC_NEXT, next); }
[ "public", "void", "mergeOrOverwriteTurnInfo", "(", "int", "fromEdge", ",", "int", "viaNode", ",", "int", "toEdge", ",", "long", "turnFlags", ",", "boolean", "merge", ")", "{", "int", "newEntryIndex", "=", "turnCostsCount", ";", "ensureTurnCostIndex", "(", "newEntryIndex", ")", ";", "boolean", "oldEntryFound", "=", "false", ";", "long", "newFlags", "=", "turnFlags", ";", "int", "next", "=", "NO_TURN_ENTRY", ";", "// determine if we already have a cost entry for this node", "int", "previousEntryIndex", "=", "nodeAccess", ".", "getAdditionalNodeField", "(", "viaNode", ")", ";", "if", "(", "previousEntryIndex", "==", "NO_TURN_ENTRY", ")", "{", "// set cost-pointer to this new cost entry", "nodeAccess", ".", "setAdditionalNodeField", "(", "viaNode", ",", "newEntryIndex", ")", ";", "}", "else", "{", "int", "i", "=", "0", ";", "next", "=", "turnCosts", ".", "getInt", "(", "(", "long", ")", "previousEntryIndex", "*", "turnCostsEntryBytes", "+", "TC_NEXT", ")", ";", "long", "existingFlags", "=", "0", ";", "while", "(", "true", ")", "{", "long", "costsIdx", "=", "(", "long", ")", "previousEntryIndex", "*", "turnCostsEntryBytes", ";", "if", "(", "fromEdge", "==", "turnCosts", ".", "getInt", "(", "costsIdx", "+", "TC_FROM", ")", "&&", "toEdge", "==", "turnCosts", ".", "getInt", "(", "costsIdx", "+", "TC_TO", ")", ")", "{", "// there is already an entry for this turn", "oldEntryFound", "=", "true", ";", "existingFlags", "=", "turnCosts", ".", "getInt", "(", "costsIdx", "+", "TC_FLAGS", ")", ";", "break", ";", "}", "else", "if", "(", "next", "==", "NO_TURN_ENTRY", ")", "{", "break", ";", "}", "previousEntryIndex", "=", "next", ";", "// search for the last added cost entry", "if", "(", "i", "++", ">", "1000", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Something unexpected happened. A node probably will not have 1000+ relations.\"", ")", ";", "}", "// get index of next turn cost entry", "next", "=", "turnCosts", ".", "getInt", "(", "(", "long", ")", "next", "*", "turnCostsEntryBytes", "+", "TC_NEXT", ")", ";", "}", "if", "(", "!", "oldEntryFound", ")", "{", "// set next-pointer to this new cost entry", "turnCosts", ".", "setInt", "(", "(", "long", ")", "previousEntryIndex", "*", "turnCostsEntryBytes", "+", "TC_NEXT", ",", "newEntryIndex", ")", ";", "}", "else", "if", "(", "merge", ")", "{", "newFlags", "=", "existingFlags", "|", "newFlags", ";", "}", "else", "{", "// overwrite!", "}", "}", "long", "costsBase", ";", "// where to (over)write", "if", "(", "!", "oldEntryFound", ")", "{", "costsBase", "=", "(", "long", ")", "newEntryIndex", "*", "turnCostsEntryBytes", ";", "turnCostsCount", "++", ";", "}", "else", "{", "costsBase", "=", "(", "long", ")", "previousEntryIndex", "*", "turnCostsEntryBytes", ";", "}", "turnCosts", ".", "setInt", "(", "costsBase", "+", "TC_FROM", ",", "fromEdge", ")", ";", "turnCosts", ".", "setInt", "(", "costsBase", "+", "TC_TO", ",", "toEdge", ")", ";", "turnCosts", ".", "setInt", "(", "costsBase", "+", "TC_FLAGS", ",", "(", "int", ")", "newFlags", ")", ";", "turnCosts", ".", "setInt", "(", "costsBase", "+", "TC_NEXT", ",", "next", ")", ";", "}" ]
Add a new turn cost entry or clear an existing. See tests for usage examples. @param fromEdge edge ID @param viaNode node ID @param toEdge edge ID @param turnFlags flags to be written @param merge If true don't overwrite existing entries with the new flag but do a bitwise OR of the old and new flags and write this merged flag.
[ "Add", "a", "new", "turn", "cost", "entry", "or", "clear", "an", "existing", ".", "See", "tests", "for", "usage", "examples", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/storage/TurnCostExtension.java#L131-L186
21,152
graphhopper/graphhopper
api/src/main/java/com/graphhopper/PathWrapper.java
PathWrapper.calcBBox2D
public BBox calcBBox2D() { check("calcRouteBBox"); BBox bounds = BBox.createInverse(false); for (int i = 0; i < pointList.getSize(); i++) { bounds.update(pointList.getLatitude(i), pointList.getLongitude(i)); } return bounds; }
java
public BBox calcBBox2D() { check("calcRouteBBox"); BBox bounds = BBox.createInverse(false); for (int i = 0; i < pointList.getSize(); i++) { bounds.update(pointList.getLatitude(i), pointList.getLongitude(i)); } return bounds; }
[ "public", "BBox", "calcBBox2D", "(", ")", "{", "check", "(", "\"calcRouteBBox\"", ")", ";", "BBox", "bounds", "=", "BBox", ".", "createInverse", "(", "false", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "pointList", ".", "getSize", "(", ")", ";", "i", "++", ")", "{", "bounds", ".", "update", "(", "pointList", ".", "getLatitude", "(", "i", ")", ",", "pointList", ".", "getLongitude", "(", "i", ")", ")", ";", "}", "return", "bounds", ";", "}" ]
Calculates the 2D bounding box of this route
[ "Calculates", "the", "2D", "bounding", "box", "of", "this", "route" ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/api/src/main/java/com/graphhopper/PathWrapper.java#L202-L209
21,153
graphhopper/graphhopper
core/src/main/java/com/graphhopper/util/details/AbstractPathDetailsBuilder.java
AbstractPathDetailsBuilder.endInterval
public void endInterval(int lastIndex) { if (isOpen) { currentDetail.setLast(lastIndex); pathDetails.add(currentDetail); } isOpen = false; }
java
public void endInterval(int lastIndex) { if (isOpen) { currentDetail.setLast(lastIndex); pathDetails.add(currentDetail); } isOpen = false; }
[ "public", "void", "endInterval", "(", "int", "lastIndex", ")", "{", "if", "(", "isOpen", ")", "{", "currentDetail", ".", "setLast", "(", "lastIndex", ")", ";", "pathDetails", ".", "add", "(", "currentDetail", ")", ";", "}", "isOpen", "=", "false", ";", "}" ]
Ending intervals multiple times is safe, we only write the interval if it was open and not empty. Writes the interval to the pathDetails @param lastIndex the index the PathDetail ends
[ "Ending", "intervals", "multiple", "times", "is", "safe", "we", "only", "write", "the", "interval", "if", "it", "was", "open", "and", "not", "empty", ".", "Writes", "the", "interval", "to", "the", "pathDetails" ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/util/details/AbstractPathDetailsBuilder.java#L71-L77
21,154
graphhopper/graphhopper
core/src/main/java/com/graphhopper/util/DepthFirstSearch.java
DepthFirstSearch.start
@Override public void start(EdgeExplorer explorer, int startNode) { IntArrayDeque stack = new IntArrayDeque(); GHBitSet explored = createBitSet(); stack.addLast(startNode); int current; while (stack.size() > 0) { current = stack.removeLast(); if (!explored.contains(current) && goFurther(current)) { EdgeIterator iter = explorer.setBaseNode(current); while (iter.next()) { int connectedId = iter.getAdjNode(); if (checkAdjacent(iter)) { stack.addLast(connectedId); } } explored.add(current); } } }
java
@Override public void start(EdgeExplorer explorer, int startNode) { IntArrayDeque stack = new IntArrayDeque(); GHBitSet explored = createBitSet(); stack.addLast(startNode); int current; while (stack.size() > 0) { current = stack.removeLast(); if (!explored.contains(current) && goFurther(current)) { EdgeIterator iter = explorer.setBaseNode(current); while (iter.next()) { int connectedId = iter.getAdjNode(); if (checkAdjacent(iter)) { stack.addLast(connectedId); } } explored.add(current); } } }
[ "@", "Override", "public", "void", "start", "(", "EdgeExplorer", "explorer", ",", "int", "startNode", ")", "{", "IntArrayDeque", "stack", "=", "new", "IntArrayDeque", "(", ")", ";", "GHBitSet", "explored", "=", "createBitSet", "(", ")", ";", "stack", ".", "addLast", "(", "startNode", ")", ";", "int", "current", ";", "while", "(", "stack", ".", "size", "(", ")", ">", "0", ")", "{", "current", "=", "stack", ".", "removeLast", "(", ")", ";", "if", "(", "!", "explored", ".", "contains", "(", "current", ")", "&&", "goFurther", "(", "current", ")", ")", "{", "EdgeIterator", "iter", "=", "explorer", ".", "setBaseNode", "(", "current", ")", ";", "while", "(", "iter", ".", "next", "(", ")", ")", "{", "int", "connectedId", "=", "iter", ".", "getAdjNode", "(", ")", ";", "if", "(", "checkAdjacent", "(", "iter", ")", ")", "{", "stack", ".", "addLast", "(", "connectedId", ")", ";", "}", "}", "explored", ".", "add", "(", "current", ")", ";", "}", "}", "}" ]
beginning with startNode add all following nodes to LIFO queue. If node has been already explored before, skip reexploration.
[ "beginning", "with", "startNode", "add", "all", "following", "nodes", "to", "LIFO", "queue", ".", "If", "node", "has", "been", "already", "explored", "before", "skip", "reexploration", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/util/DepthFirstSearch.java#L35-L55
21,155
graphhopper/graphhopper
reader-osm/src/main/java/com/graphhopper/reader/osm/OSMReader.java
OSMReader.preProcess
void preProcess(File osmFile) { try (OSMInput in = openOsmInputFile(osmFile)) { long tmpWayCounter = 1; long tmpRelationCounter = 1; ReaderElement item; while ((item = in.getNext()) != null) { if (item.isType(ReaderElement.WAY)) { final ReaderWay way = (ReaderWay) item; boolean valid = filterWay(way); if (valid) { LongIndexedContainer wayNodes = way.getNodes(); int s = wayNodes.size(); for (int index = 0; index < s; index++) { prepareHighwayNode(wayNodes.get(index)); } if (++tmpWayCounter % 10_000_000 == 0) { LOGGER.info(nf(tmpWayCounter) + " (preprocess), osmIdMap:" + nf(getNodeMap().getSize()) + " (" + getNodeMap().getMemoryUsage() + "MB) " + Helper.getMemInfo()); } } } else if (item.isType(ReaderElement.RELATION)) { final ReaderRelation relation = (ReaderRelation) item; if (!relation.isMetaRelation() && relation.hasTag("type", "route")) prepareWaysWithRelationInfo(relation); if (relation.hasTag("type", "restriction")) prepareRestrictionRelation(relation); if (++tmpRelationCounter % 100_000 == 0) { LOGGER.info(nf(tmpRelationCounter) + " (preprocess), osmWayMap:" + nf(getRelFlagsMap().size()) + " " + Helper.getMemInfo()); } } else if (item.isType(ReaderElement.FILEHEADER)) { final OSMFileHeader fileHeader = (OSMFileHeader) item; osmDataDate = Helper.createFormatter().parse(fileHeader.getTag("timestamp")); } } } catch (Exception ex) { throw new RuntimeException("Problem while parsing file", ex); } }
java
void preProcess(File osmFile) { try (OSMInput in = openOsmInputFile(osmFile)) { long tmpWayCounter = 1; long tmpRelationCounter = 1; ReaderElement item; while ((item = in.getNext()) != null) { if (item.isType(ReaderElement.WAY)) { final ReaderWay way = (ReaderWay) item; boolean valid = filterWay(way); if (valid) { LongIndexedContainer wayNodes = way.getNodes(); int s = wayNodes.size(); for (int index = 0; index < s; index++) { prepareHighwayNode(wayNodes.get(index)); } if (++tmpWayCounter % 10_000_000 == 0) { LOGGER.info(nf(tmpWayCounter) + " (preprocess), osmIdMap:" + nf(getNodeMap().getSize()) + " (" + getNodeMap().getMemoryUsage() + "MB) " + Helper.getMemInfo()); } } } else if (item.isType(ReaderElement.RELATION)) { final ReaderRelation relation = (ReaderRelation) item; if (!relation.isMetaRelation() && relation.hasTag("type", "route")) prepareWaysWithRelationInfo(relation); if (relation.hasTag("type", "restriction")) prepareRestrictionRelation(relation); if (++tmpRelationCounter % 100_000 == 0) { LOGGER.info(nf(tmpRelationCounter) + " (preprocess), osmWayMap:" + nf(getRelFlagsMap().size()) + " " + Helper.getMemInfo()); } } else if (item.isType(ReaderElement.FILEHEADER)) { final OSMFileHeader fileHeader = (OSMFileHeader) item; osmDataDate = Helper.createFormatter().parse(fileHeader.getTag("timestamp")); } } } catch (Exception ex) { throw new RuntimeException("Problem while parsing file", ex); } }
[ "void", "preProcess", "(", "File", "osmFile", ")", "{", "try", "(", "OSMInput", "in", "=", "openOsmInputFile", "(", "osmFile", ")", ")", "{", "long", "tmpWayCounter", "=", "1", ";", "long", "tmpRelationCounter", "=", "1", ";", "ReaderElement", "item", ";", "while", "(", "(", "item", "=", "in", ".", "getNext", "(", ")", ")", "!=", "null", ")", "{", "if", "(", "item", ".", "isType", "(", "ReaderElement", ".", "WAY", ")", ")", "{", "final", "ReaderWay", "way", "=", "(", "ReaderWay", ")", "item", ";", "boolean", "valid", "=", "filterWay", "(", "way", ")", ";", "if", "(", "valid", ")", "{", "LongIndexedContainer", "wayNodes", "=", "way", ".", "getNodes", "(", ")", ";", "int", "s", "=", "wayNodes", ".", "size", "(", ")", ";", "for", "(", "int", "index", "=", "0", ";", "index", "<", "s", ";", "index", "++", ")", "{", "prepareHighwayNode", "(", "wayNodes", ".", "get", "(", "index", ")", ")", ";", "}", "if", "(", "++", "tmpWayCounter", "%", "10_000_000", "==", "0", ")", "{", "LOGGER", ".", "info", "(", "nf", "(", "tmpWayCounter", ")", "+", "\" (preprocess), osmIdMap:\"", "+", "nf", "(", "getNodeMap", "(", ")", ".", "getSize", "(", ")", ")", "+", "\" (\"", "+", "getNodeMap", "(", ")", ".", "getMemoryUsage", "(", ")", "+", "\"MB) \"", "+", "Helper", ".", "getMemInfo", "(", ")", ")", ";", "}", "}", "}", "else", "if", "(", "item", ".", "isType", "(", "ReaderElement", ".", "RELATION", ")", ")", "{", "final", "ReaderRelation", "relation", "=", "(", "ReaderRelation", ")", "item", ";", "if", "(", "!", "relation", ".", "isMetaRelation", "(", ")", "&&", "relation", ".", "hasTag", "(", "\"type\"", ",", "\"route\"", ")", ")", "prepareWaysWithRelationInfo", "(", "relation", ")", ";", "if", "(", "relation", ".", "hasTag", "(", "\"type\"", ",", "\"restriction\"", ")", ")", "prepareRestrictionRelation", "(", "relation", ")", ";", "if", "(", "++", "tmpRelationCounter", "%", "100_000", "==", "0", ")", "{", "LOGGER", ".", "info", "(", "nf", "(", "tmpRelationCounter", ")", "+", "\" (preprocess), osmWayMap:\"", "+", "nf", "(", "getRelFlagsMap", "(", ")", ".", "size", "(", ")", ")", "+", "\" \"", "+", "Helper", ".", "getMemInfo", "(", ")", ")", ";", "}", "}", "else", "if", "(", "item", ".", "isType", "(", "ReaderElement", ".", "FILEHEADER", ")", ")", "{", "final", "OSMFileHeader", "fileHeader", "=", "(", "OSMFileHeader", ")", "item", ";", "osmDataDate", "=", "Helper", ".", "createFormatter", "(", ")", ".", "parse", "(", "fileHeader", ".", "getTag", "(", "\"timestamp\"", ")", ")", ";", "}", "}", "}", "catch", "(", "Exception", "ex", ")", "{", "throw", "new", "RuntimeException", "(", "\"Problem while parsing file\"", ",", "ex", ")", ";", "}", "}" ]
Preprocessing of OSM file to select nodes which are used for highways. This allows a more compact graph data structure.
[ "Preprocessing", "of", "OSM", "file", "to", "select", "nodes", "which", "are", "used", "for", "highways", ".", "This", "allows", "a", "more", "compact", "graph", "data", "structure", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/reader-osm/src/main/java/com/graphhopper/reader/osm/OSMReader.java#L158-L200
21,156
graphhopper/graphhopper
reader-osm/src/main/java/com/graphhopper/reader/osm/OSMReader.java
OSMReader.filterWay
boolean filterWay(ReaderWay item) { // ignore broken geometry if (item.getNodes().size() < 2) return false; // ignore multipolygon geometry if (!item.hasTags()) return false; return encodingManager.acceptWay(item, new EncodingManager.AcceptWay()); }
java
boolean filterWay(ReaderWay item) { // ignore broken geometry if (item.getNodes().size() < 2) return false; // ignore multipolygon geometry if (!item.hasTags()) return false; return encodingManager.acceptWay(item, new EncodingManager.AcceptWay()); }
[ "boolean", "filterWay", "(", "ReaderWay", "item", ")", "{", "// ignore broken geometry", "if", "(", "item", ".", "getNodes", "(", ")", ".", "size", "(", ")", "<", "2", ")", "return", "false", ";", "// ignore multipolygon geometry", "if", "(", "!", "item", ".", "hasTags", "(", ")", ")", "return", "false", ";", "return", "encodingManager", ".", "acceptWay", "(", "item", ",", "new", "EncodingManager", ".", "AcceptWay", "(", ")", ")", ";", "}" ]
Filter ways but do not analyze properties wayNodes will be filled with participating node ids. @return true the current xml entry is a way entry and has nodes
[ "Filter", "ways", "but", "do", "not", "analyze", "properties", "wayNodes", "will", "be", "filled", "with", "participating", "node", "ids", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/reader-osm/src/main/java/com/graphhopper/reader/osm/OSMReader.java#L229-L239
21,157
graphhopper/graphhopper
reader-osm/src/main/java/com/graphhopper/reader/osm/OSMReader.java
OSMReader.writeOsm2Graph
private void writeOsm2Graph(File osmFile) { int tmp = (int) Math.max(getNodeMap().getSize() / 50, 100); LOGGER.info("creating graph. Found nodes (pillar+tower):" + nf(getNodeMap().getSize()) + ", " + Helper.getMemInfo()); if (createStorage) ghStorage.create(tmp); long wayStart = -1; long relationStart = -1; long counter = 1; try (OSMInput in = openOsmInputFile(osmFile)) { LongIntMap nodeFilter = getNodeMap(); ReaderElement item; while ((item = in.getNext()) != null) { switch (item.getType()) { case ReaderElement.NODE: if (nodeFilter.get(item.getId()) != EMPTY_NODE) { processNode((ReaderNode) item); } break; case ReaderElement.WAY: if (wayStart < 0) { LOGGER.info(nf(counter) + ", now parsing ways"); wayStart = counter; } processWay((ReaderWay) item); break; case ReaderElement.RELATION: if (relationStart < 0) { LOGGER.info(nf(counter) + ", now parsing relations"); relationStart = counter; } processRelation((ReaderRelation) item); break; case ReaderElement.FILEHEADER: break; default: throw new IllegalStateException("Unknown type " + item.getType()); } if (++counter % 200_000_000 == 0) { LOGGER.info(nf(counter) + ", locs:" + nf(locations) + " (" + skippedLocations + ") " + Helper.getMemInfo()); } } if (in.getUnprocessedElements() > 0) throw new IllegalStateException("Still unprocessed elements in reader queue " + in.getUnprocessedElements()); // logger.info("storage nodes:" + storage.nodes() + " vs. graph nodes:" + storage.getGraph().nodes()); } catch (Exception ex) { throw new RuntimeException("Couldn't process file " + osmFile + ", error: " + ex.getMessage(), ex); } finishedReading(); if (graph.getNodes() == 0) throw new RuntimeException("Graph after reading OSM must not be empty. Read " + counter + " items and " + locations + " locations"); }
java
private void writeOsm2Graph(File osmFile) { int tmp = (int) Math.max(getNodeMap().getSize() / 50, 100); LOGGER.info("creating graph. Found nodes (pillar+tower):" + nf(getNodeMap().getSize()) + ", " + Helper.getMemInfo()); if (createStorage) ghStorage.create(tmp); long wayStart = -1; long relationStart = -1; long counter = 1; try (OSMInput in = openOsmInputFile(osmFile)) { LongIntMap nodeFilter = getNodeMap(); ReaderElement item; while ((item = in.getNext()) != null) { switch (item.getType()) { case ReaderElement.NODE: if (nodeFilter.get(item.getId()) != EMPTY_NODE) { processNode((ReaderNode) item); } break; case ReaderElement.WAY: if (wayStart < 0) { LOGGER.info(nf(counter) + ", now parsing ways"); wayStart = counter; } processWay((ReaderWay) item); break; case ReaderElement.RELATION: if (relationStart < 0) { LOGGER.info(nf(counter) + ", now parsing relations"); relationStart = counter; } processRelation((ReaderRelation) item); break; case ReaderElement.FILEHEADER: break; default: throw new IllegalStateException("Unknown type " + item.getType()); } if (++counter % 200_000_000 == 0) { LOGGER.info(nf(counter) + ", locs:" + nf(locations) + " (" + skippedLocations + ") " + Helper.getMemInfo()); } } if (in.getUnprocessedElements() > 0) throw new IllegalStateException("Still unprocessed elements in reader queue " + in.getUnprocessedElements()); // logger.info("storage nodes:" + storage.nodes() + " vs. graph nodes:" + storage.getGraph().nodes()); } catch (Exception ex) { throw new RuntimeException("Couldn't process file " + osmFile + ", error: " + ex.getMessage(), ex); } finishedReading(); if (graph.getNodes() == 0) throw new RuntimeException("Graph after reading OSM must not be empty. Read " + counter + " items and " + locations + " locations"); }
[ "private", "void", "writeOsm2Graph", "(", "File", "osmFile", ")", "{", "int", "tmp", "=", "(", "int", ")", "Math", ".", "max", "(", "getNodeMap", "(", ")", ".", "getSize", "(", ")", "/", "50", ",", "100", ")", ";", "LOGGER", ".", "info", "(", "\"creating graph. Found nodes (pillar+tower):\"", "+", "nf", "(", "getNodeMap", "(", ")", ".", "getSize", "(", ")", ")", "+", "\", \"", "+", "Helper", ".", "getMemInfo", "(", ")", ")", ";", "if", "(", "createStorage", ")", "ghStorage", ".", "create", "(", "tmp", ")", ";", "long", "wayStart", "=", "-", "1", ";", "long", "relationStart", "=", "-", "1", ";", "long", "counter", "=", "1", ";", "try", "(", "OSMInput", "in", "=", "openOsmInputFile", "(", "osmFile", ")", ")", "{", "LongIntMap", "nodeFilter", "=", "getNodeMap", "(", ")", ";", "ReaderElement", "item", ";", "while", "(", "(", "item", "=", "in", ".", "getNext", "(", ")", ")", "!=", "null", ")", "{", "switch", "(", "item", ".", "getType", "(", ")", ")", "{", "case", "ReaderElement", ".", "NODE", ":", "if", "(", "nodeFilter", ".", "get", "(", "item", ".", "getId", "(", ")", ")", "!=", "EMPTY_NODE", ")", "{", "processNode", "(", "(", "ReaderNode", ")", "item", ")", ";", "}", "break", ";", "case", "ReaderElement", ".", "WAY", ":", "if", "(", "wayStart", "<", "0", ")", "{", "LOGGER", ".", "info", "(", "nf", "(", "counter", ")", "+", "\", now parsing ways\"", ")", ";", "wayStart", "=", "counter", ";", "}", "processWay", "(", "(", "ReaderWay", ")", "item", ")", ";", "break", ";", "case", "ReaderElement", ".", "RELATION", ":", "if", "(", "relationStart", "<", "0", ")", "{", "LOGGER", ".", "info", "(", "nf", "(", "counter", ")", "+", "\", now parsing relations\"", ")", ";", "relationStart", "=", "counter", ";", "}", "processRelation", "(", "(", "ReaderRelation", ")", "item", ")", ";", "break", ";", "case", "ReaderElement", ".", "FILEHEADER", ":", "break", ";", "default", ":", "throw", "new", "IllegalStateException", "(", "\"Unknown type \"", "+", "item", ".", "getType", "(", ")", ")", ";", "}", "if", "(", "++", "counter", "%", "200_000_000", "==", "0", ")", "{", "LOGGER", ".", "info", "(", "nf", "(", "counter", ")", "+", "\", locs:\"", "+", "nf", "(", "locations", ")", "+", "\" (\"", "+", "skippedLocations", "+", "\") \"", "+", "Helper", ".", "getMemInfo", "(", ")", ")", ";", "}", "}", "if", "(", "in", ".", "getUnprocessedElements", "(", ")", ">", "0", ")", "throw", "new", "IllegalStateException", "(", "\"Still unprocessed elements in reader queue \"", "+", "in", ".", "getUnprocessedElements", "(", ")", ")", ";", "// logger.info(\"storage nodes:\" + storage.nodes() + \" vs. graph nodes:\" + storage.getGraph().nodes());", "}", "catch", "(", "Exception", "ex", ")", "{", "throw", "new", "RuntimeException", "(", "\"Couldn't process file \"", "+", "osmFile", "+", "\", error: \"", "+", "ex", ".", "getMessage", "(", ")", ",", "ex", ")", ";", "}", "finishedReading", "(", ")", ";", "if", "(", "graph", ".", "getNodes", "(", ")", "==", "0", ")", "throw", "new", "RuntimeException", "(", "\"Graph after reading OSM must not be empty. Read \"", "+", "counter", "+", "\" items and \"", "+", "locations", "+", "\" locations\"", ")", ";", "}" ]
Creates the graph with edges and nodes from the specified osm file.
[ "Creates", "the", "graph", "with", "edges", "and", "nodes", "from", "the", "specified", "osm", "file", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/reader-osm/src/main/java/com/graphhopper/reader/osm/OSMReader.java#L244-L300
21,158
graphhopper/graphhopper
reader-osm/src/main/java/com/graphhopper/reader/osm/OSMReader.java
OSMReader.isOnePassable
private static boolean isOnePassable(List<BooleanEncodedValue> checkEncoders, IntsRef edgeFlags) { for (BooleanEncodedValue accessEnc : checkEncoders) { if (accessEnc.getBool(false, edgeFlags) || accessEnc.getBool(true, edgeFlags)) return true; } return false; }
java
private static boolean isOnePassable(List<BooleanEncodedValue> checkEncoders, IntsRef edgeFlags) { for (BooleanEncodedValue accessEnc : checkEncoders) { if (accessEnc.getBool(false, edgeFlags) || accessEnc.getBool(true, edgeFlags)) return true; } return false; }
[ "private", "static", "boolean", "isOnePassable", "(", "List", "<", "BooleanEncodedValue", ">", "checkEncoders", ",", "IntsRef", "edgeFlags", ")", "{", "for", "(", "BooleanEncodedValue", "accessEnc", ":", "checkEncoders", ")", "{", "if", "(", "accessEnc", ".", "getBool", "(", "false", ",", "edgeFlags", ")", "||", "accessEnc", ".", "getBool", "(", "true", ",", "edgeFlags", ")", ")", "return", "true", ";", "}", "return", "false", ";", "}" ]
The nodeFlags store the encoders to check for accessibility in edgeFlags. E.g. if nodeFlags==3, then the accessibility of the first two encoders will be check in edgeFlags
[ "The", "nodeFlags", "store", "the", "encoders", "to", "check", "for", "accessibility", "in", "edgeFlags", ".", "E", ".", "g", ".", "if", "nodeFlags", "==", "3", "then", "the", "accessibility", "of", "the", "first", "two", "encoders", "will", "be", "check", "in", "edgeFlags" ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/reader-osm/src/main/java/com/graphhopper/reader/osm/OSMReader.java#L553-L559
21,159
graphhopper/graphhopper
reader-osm/src/main/java/com/graphhopper/reader/osm/OSMReader.java
OSMReader.storeOsmWayID
protected void storeOsmWayID(int edgeId, long osmWayId) { if (getOsmWayIdSet().contains(osmWayId)) { getEdgeIdToOsmWayIdMap().put(edgeId, osmWayId); } }
java
protected void storeOsmWayID(int edgeId, long osmWayId) { if (getOsmWayIdSet().contains(osmWayId)) { getEdgeIdToOsmWayIdMap().put(edgeId, osmWayId); } }
[ "protected", "void", "storeOsmWayID", "(", "int", "edgeId", ",", "long", "osmWayId", ")", "{", "if", "(", "getOsmWayIdSet", "(", ")", ".", "contains", "(", "osmWayId", ")", ")", "{", "getEdgeIdToOsmWayIdMap", "(", ")", ".", "put", "(", "edgeId", ",", "osmWayId", ")", ";", "}", "}" ]
Stores only osmWayIds which are required for relations
[ "Stores", "only", "osmWayIds", "which", "are", "required", "for", "relations" ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/reader-osm/src/main/java/com/graphhopper/reader/osm/OSMReader.java#L775-L779
21,160
graphhopper/graphhopper
reader-osm/src/main/java/com/graphhopper/reader/osm/OSMReader.java
OSMReader.addBarrierNode
long addBarrierNode(long nodeId) { ReaderNode newNode; int graphIndex = getNodeMap().get(nodeId); if (graphIndex < TOWER_NODE) { graphIndex = -graphIndex - 3; newNode = new ReaderNode(createNewNodeId(), nodeAccess, graphIndex); } else { graphIndex = graphIndex - 3; newNode = new ReaderNode(createNewNodeId(), pillarInfo, graphIndex); } final long id = newNode.getId(); prepareHighwayNode(id); addNode(newNode); return id; }
java
long addBarrierNode(long nodeId) { ReaderNode newNode; int graphIndex = getNodeMap().get(nodeId); if (graphIndex < TOWER_NODE) { graphIndex = -graphIndex - 3; newNode = new ReaderNode(createNewNodeId(), nodeAccess, graphIndex); } else { graphIndex = graphIndex - 3; newNode = new ReaderNode(createNewNodeId(), pillarInfo, graphIndex); } final long id = newNode.getId(); prepareHighwayNode(id); addNode(newNode); return id; }
[ "long", "addBarrierNode", "(", "long", "nodeId", ")", "{", "ReaderNode", "newNode", ";", "int", "graphIndex", "=", "getNodeMap", "(", ")", ".", "get", "(", "nodeId", ")", ";", "if", "(", "graphIndex", "<", "TOWER_NODE", ")", "{", "graphIndex", "=", "-", "graphIndex", "-", "3", ";", "newNode", "=", "new", "ReaderNode", "(", "createNewNodeId", "(", ")", ",", "nodeAccess", ",", "graphIndex", ")", ";", "}", "else", "{", "graphIndex", "=", "graphIndex", "-", "3", ";", "newNode", "=", "new", "ReaderNode", "(", "createNewNodeId", "(", ")", ",", "pillarInfo", ",", "graphIndex", ")", ";", "}", "final", "long", "id", "=", "newNode", ".", "getId", "(", ")", ";", "prepareHighwayNode", "(", "id", ")", ";", "addNode", "(", "newNode", ")", ";", "return", "id", ";", "}" ]
Create a copy of the barrier node
[ "Create", "a", "copy", "of", "the", "barrier", "node" ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/reader-osm/src/main/java/com/graphhopper/reader/osm/OSMReader.java#L819-L834
21,161
graphhopper/graphhopper
reader-osm/src/main/java/com/graphhopper/reader/osm/OSMReader.java
OSMReader.addBarrierEdge
Collection<EdgeIteratorState> addBarrierEdge(long fromId, long toId, IntsRef inEdgeFlags, long nodeFlags, long wayOsmId) { IntsRef edgeFlags = IntsRef.deepCopyOf(inEdgeFlags); // clear blocked directions from flags for (BooleanEncodedValue accessEnc : encodingManager.getAccessEncFromNodeFlags(nodeFlags)) { accessEnc.setBool(false, edgeFlags, false); accessEnc.setBool(true, edgeFlags, false); } // add edge barrierNodeIds.clear(); barrierNodeIds.add(fromId); barrierNodeIds.add(toId); return addOSMWay(barrierNodeIds, edgeFlags, wayOsmId); }
java
Collection<EdgeIteratorState> addBarrierEdge(long fromId, long toId, IntsRef inEdgeFlags, long nodeFlags, long wayOsmId) { IntsRef edgeFlags = IntsRef.deepCopyOf(inEdgeFlags); // clear blocked directions from flags for (BooleanEncodedValue accessEnc : encodingManager.getAccessEncFromNodeFlags(nodeFlags)) { accessEnc.setBool(false, edgeFlags, false); accessEnc.setBool(true, edgeFlags, false); } // add edge barrierNodeIds.clear(); barrierNodeIds.add(fromId); barrierNodeIds.add(toId); return addOSMWay(barrierNodeIds, edgeFlags, wayOsmId); }
[ "Collection", "<", "EdgeIteratorState", ">", "addBarrierEdge", "(", "long", "fromId", ",", "long", "toId", ",", "IntsRef", "inEdgeFlags", ",", "long", "nodeFlags", ",", "long", "wayOsmId", ")", "{", "IntsRef", "edgeFlags", "=", "IntsRef", ".", "deepCopyOf", "(", "inEdgeFlags", ")", ";", "// clear blocked directions from flags", "for", "(", "BooleanEncodedValue", "accessEnc", ":", "encodingManager", ".", "getAccessEncFromNodeFlags", "(", "nodeFlags", ")", ")", "{", "accessEnc", ".", "setBool", "(", "false", ",", "edgeFlags", ",", "false", ")", ";", "accessEnc", ".", "setBool", "(", "true", ",", "edgeFlags", ",", "false", ")", ";", "}", "// add edge", "barrierNodeIds", ".", "clear", "(", ")", ";", "barrierNodeIds", ".", "add", "(", "fromId", ")", ";", "barrierNodeIds", ".", "add", "(", "toId", ")", ";", "return", "addOSMWay", "(", "barrierNodeIds", ",", "edgeFlags", ",", "wayOsmId", ")", ";", "}" ]
Add a zero length edge with reduced routing options to the graph.
[ "Add", "a", "zero", "length", "edge", "with", "reduced", "routing", "options", "to", "the", "graph", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/reader-osm/src/main/java/com/graphhopper/reader/osm/OSMReader.java#L843-L855
21,162
graphhopper/graphhopper
core/src/main/java/com/graphhopper/routing/subnetwork/SubnetworkStorage.java
SubnetworkStorage.setSubnetwork
public void setSubnetwork(int nodeId, int subnetwork) { if (subnetwork > 127) throw new IllegalArgumentException("Number of subnetworks is currently limited to 127 but requested " + subnetwork); byte[] bytes = new byte[1]; bytes[0] = (byte) subnetwork; da.setBytes(nodeId, bytes, bytes.length); }
java
public void setSubnetwork(int nodeId, int subnetwork) { if (subnetwork > 127) throw new IllegalArgumentException("Number of subnetworks is currently limited to 127 but requested " + subnetwork); byte[] bytes = new byte[1]; bytes[0] = (byte) subnetwork; da.setBytes(nodeId, bytes, bytes.length); }
[ "public", "void", "setSubnetwork", "(", "int", "nodeId", ",", "int", "subnetwork", ")", "{", "if", "(", "subnetwork", ">", "127", ")", "throw", "new", "IllegalArgumentException", "(", "\"Number of subnetworks is currently limited to 127 but requested \"", "+", "subnetwork", ")", ";", "byte", "[", "]", "bytes", "=", "new", "byte", "[", "1", "]", ";", "bytes", "[", "0", "]", "=", "(", "byte", ")", "subnetwork", ";", "da", ".", "setBytes", "(", "nodeId", ",", "bytes", ",", "bytes", ".", "length", ")", ";", "}" ]
This method sets the subnetwork if of the specified nodeId. Default is 0 and means subnetwork was too small to be useful to be stored.
[ "This", "method", "sets", "the", "subnetwork", "if", "of", "the", "specified", "nodeId", ".", "Default", "is", "0", "and", "means", "subnetwork", "was", "too", "small", "to", "be", "useful", "to", "be", "stored", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/subnetwork/SubnetworkStorage.java#L54-L61
21,163
graphhopper/graphhopper
core/src/main/java/com/graphhopper/storage/BaseGraph.java
BaseGraph.initNodeRefs
void initNodeRefs(long oldCapacity, long newCapacity) { for (long pointer = oldCapacity + N_EDGE_REF; pointer < newCapacity; pointer += nodeEntryBytes) { nodes.setInt(pointer, EdgeIterator.NO_EDGE); } if (extStorage.isRequireNodeField()) { for (long pointer = oldCapacity + N_ADDITIONAL; pointer < newCapacity; pointer += nodeEntryBytes) { nodes.setInt(pointer, extStorage.getDefaultNodeFieldValue()); } } }
java
void initNodeRefs(long oldCapacity, long newCapacity) { for (long pointer = oldCapacity + N_EDGE_REF; pointer < newCapacity; pointer += nodeEntryBytes) { nodes.setInt(pointer, EdgeIterator.NO_EDGE); } if (extStorage.isRequireNodeField()) { for (long pointer = oldCapacity + N_ADDITIONAL; pointer < newCapacity; pointer += nodeEntryBytes) { nodes.setInt(pointer, extStorage.getDefaultNodeFieldValue()); } } }
[ "void", "initNodeRefs", "(", "long", "oldCapacity", ",", "long", "newCapacity", ")", "{", "for", "(", "long", "pointer", "=", "oldCapacity", "+", "N_EDGE_REF", ";", "pointer", "<", "newCapacity", ";", "pointer", "+=", "nodeEntryBytes", ")", "{", "nodes", ".", "setInt", "(", "pointer", ",", "EdgeIterator", ".", "NO_EDGE", ")", ";", "}", "if", "(", "extStorage", ".", "isRequireNodeField", "(", ")", ")", "{", "for", "(", "long", "pointer", "=", "oldCapacity", "+", "N_ADDITIONAL", ";", "pointer", "<", "newCapacity", ";", "pointer", "+=", "nodeEntryBytes", ")", "{", "nodes", ".", "setInt", "(", "pointer", ",", "extStorage", ".", "getDefaultNodeFieldValue", "(", ")", ")", ";", "}", "}", "}" ]
Initializes the node area with the empty edge value and default additional value.
[ "Initializes", "the", "node", "area", "with", "the", "empty", "edge", "value", "and", "default", "additional", "value", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/storage/BaseGraph.java#L258-L267
21,164
graphhopper/graphhopper
core/src/main/java/com/graphhopper/storage/BaseGraph.java
BaseGraph.ensureNodeIndex
final void ensureNodeIndex(int nodeIndex) { if (!initialized) throw new AssertionError("The graph has not yet been initialized."); if (nodeIndex < nodeCount) return; long oldNodes = nodeCount; nodeCount = nodeIndex + 1; boolean capacityIncreased = nodes.ensureCapacity((long) nodeCount * nodeEntryBytes); if (capacityIncreased) { long newBytesCapacity = nodes.getCapacity(); initNodeRefs(oldNodes * nodeEntryBytes, newBytesCapacity); } }
java
final void ensureNodeIndex(int nodeIndex) { if (!initialized) throw new AssertionError("The graph has not yet been initialized."); if (nodeIndex < nodeCount) return; long oldNodes = nodeCount; nodeCount = nodeIndex + 1; boolean capacityIncreased = nodes.ensureCapacity((long) nodeCount * nodeEntryBytes); if (capacityIncreased) { long newBytesCapacity = nodes.getCapacity(); initNodeRefs(oldNodes * nodeEntryBytes, newBytesCapacity); } }
[ "final", "void", "ensureNodeIndex", "(", "int", "nodeIndex", ")", "{", "if", "(", "!", "initialized", ")", "throw", "new", "AssertionError", "(", "\"The graph has not yet been initialized.\"", ")", ";", "if", "(", "nodeIndex", "<", "nodeCount", ")", "return", ";", "long", "oldNodes", "=", "nodeCount", ";", "nodeCount", "=", "nodeIndex", "+", "1", ";", "boolean", "capacityIncreased", "=", "nodes", ".", "ensureCapacity", "(", "(", "long", ")", "nodeCount", "*", "nodeEntryBytes", ")", ";", "if", "(", "capacityIncreased", ")", "{", "long", "newBytesCapacity", "=", "nodes", ".", "getCapacity", "(", ")", ";", "initNodeRefs", "(", "oldNodes", "*", "nodeEntryBytes", ",", "newBytesCapacity", ")", ";", "}", "}" ]
Check if byte capacity of DataAcess nodes object is sufficient to include node index, else extend byte capacity
[ "Check", "if", "byte", "capacity", "of", "DataAcess", "nodes", "object", "is", "sufficient", "to", "include", "node", "index", "else", "extend", "byte", "capacity" ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/storage/BaseGraph.java#L290-L304
21,165
graphhopper/graphhopper
core/src/main/java/com/graphhopper/storage/BaseGraph.java
BaseGraph.edge
@Override public EdgeIteratorState edge(int nodeA, int nodeB) { if (isFrozen()) throw new IllegalStateException("Cannot create edge if graph is already frozen"); ensureNodeIndex(Math.max(nodeA, nodeB)); int edgeId = edgeAccess.internalEdgeAdd(nextEdgeId(), nodeA, nodeB); EdgeIterable iter = new EdgeIterable(this, edgeAccess, EdgeFilter.ALL_EDGES); boolean ret = iter.init(edgeId, nodeB); assert ret; if (extStorage.isRequireEdgeField()) iter.setAdditionalField(extStorage.getDefaultEdgeFieldValue()); return iter; }
java
@Override public EdgeIteratorState edge(int nodeA, int nodeB) { if (isFrozen()) throw new IllegalStateException("Cannot create edge if graph is already frozen"); ensureNodeIndex(Math.max(nodeA, nodeB)); int edgeId = edgeAccess.internalEdgeAdd(nextEdgeId(), nodeA, nodeB); EdgeIterable iter = new EdgeIterable(this, edgeAccess, EdgeFilter.ALL_EDGES); boolean ret = iter.init(edgeId, nodeB); assert ret; if (extStorage.isRequireEdgeField()) iter.setAdditionalField(extStorage.getDefaultEdgeFieldValue()); return iter; }
[ "@", "Override", "public", "EdgeIteratorState", "edge", "(", "int", "nodeA", ",", "int", "nodeB", ")", "{", "if", "(", "isFrozen", "(", ")", ")", "throw", "new", "IllegalStateException", "(", "\"Cannot create edge if graph is already frozen\"", ")", ";", "ensureNodeIndex", "(", "Math", ".", "max", "(", "nodeA", ",", "nodeB", ")", ")", ";", "int", "edgeId", "=", "edgeAccess", ".", "internalEdgeAdd", "(", "nextEdgeId", "(", ")", ",", "nodeA", ",", "nodeB", ")", ";", "EdgeIterable", "iter", "=", "new", "EdgeIterable", "(", "this", ",", "edgeAccess", ",", "EdgeFilter", ".", "ALL_EDGES", ")", ";", "boolean", "ret", "=", "iter", ".", "init", "(", "edgeId", ",", "nodeB", ")", ";", "assert", "ret", ";", "if", "(", "extStorage", ".", "isRequireEdgeField", "(", ")", ")", "iter", ".", "setAdditionalField", "(", "extStorage", ".", "getDefaultEdgeFieldValue", "(", ")", ")", ";", "return", "iter", ";", "}" ]
Create edge between nodes a and b @return EdgeIteratorState of newly created edge
[ "Create", "edge", "between", "nodes", "a", "and", "b" ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/storage/BaseGraph.java#L503-L517
21,166
graphhopper/graphhopper
core/src/main/java/com/graphhopper/storage/BaseGraph.java
BaseGraph.nextEdgeId
protected int nextEdgeId() { int nextEdge = edgeCount; edgeCount++; if (edgeCount < 0) throw new IllegalStateException("too many edges. new edge id would be negative. " + toString()); edges.ensureCapacity(((long) edgeCount + 1) * edgeEntryBytes); return nextEdge; }
java
protected int nextEdgeId() { int nextEdge = edgeCount; edgeCount++; if (edgeCount < 0) throw new IllegalStateException("too many edges. new edge id would be negative. " + toString()); edges.ensureCapacity(((long) edgeCount + 1) * edgeEntryBytes); return nextEdge; }
[ "protected", "int", "nextEdgeId", "(", ")", "{", "int", "nextEdge", "=", "edgeCount", ";", "edgeCount", "++", ";", "if", "(", "edgeCount", "<", "0", ")", "throw", "new", "IllegalStateException", "(", "\"too many edges. new edge id would be negative. \"", "+", "toString", "(", ")", ")", ";", "edges", ".", "ensureCapacity", "(", "(", "(", "long", ")", "edgeCount", "+", "1", ")", "*", "edgeEntryBytes", ")", ";", "return", "nextEdge", ";", "}" ]
Determine next free edgeId and ensure byte capacity to store edge @return next free edgeId
[ "Determine", "next", "free", "edgeId", "and", "ensure", "byte", "capacity", "to", "store", "edge" ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/storage/BaseGraph.java#L529-L537
21,167
graphhopper/graphhopper
core/src/main/java/com/graphhopper/reader/dem/SRTMProvider.java
SRTMProvider.init
private SRTMProvider init() { try { String strs[] = {"Africa", "Australia", "Eurasia", "Islands", "North_America", "South_America"}; for (String str : strs) { InputStream is = getClass().getResourceAsStream(str + "_names.txt"); for (String line : Helper.readFile(new InputStreamReader(is, Helper.UTF_CS))) { int lat = Integer.parseInt(line.substring(1, 3)); if (line.substring(0, 1).charAt(0) == 'S') lat = -lat; int lon = Integer.parseInt(line.substring(4, 7)); if (line.substring(3, 4).charAt(0) == 'W') lon = -lon; int intKey = calcIntKey(lat, lon); String key = areas.put(intKey, str); if (key != null) throw new IllegalStateException("do not overwrite existing! key " + intKey + " " + key + " vs. " + str); } } return this; } catch (Exception ex) { throw new IllegalStateException("Cannot load area names from classpath", ex); } }
java
private SRTMProvider init() { try { String strs[] = {"Africa", "Australia", "Eurasia", "Islands", "North_America", "South_America"}; for (String str : strs) { InputStream is = getClass().getResourceAsStream(str + "_names.txt"); for (String line : Helper.readFile(new InputStreamReader(is, Helper.UTF_CS))) { int lat = Integer.parseInt(line.substring(1, 3)); if (line.substring(0, 1).charAt(0) == 'S') lat = -lat; int lon = Integer.parseInt(line.substring(4, 7)); if (line.substring(3, 4).charAt(0) == 'W') lon = -lon; int intKey = calcIntKey(lat, lon); String key = areas.put(intKey, str); if (key != null) throw new IllegalStateException("do not overwrite existing! key " + intKey + " " + key + " vs. " + str); } } return this; } catch (Exception ex) { throw new IllegalStateException("Cannot load area names from classpath", ex); } }
[ "private", "SRTMProvider", "init", "(", ")", "{", "try", "{", "String", "strs", "[", "]", "=", "{", "\"Africa\"", ",", "\"Australia\"", ",", "\"Eurasia\"", ",", "\"Islands\"", ",", "\"North_America\"", ",", "\"South_America\"", "}", ";", "for", "(", "String", "str", ":", "strs", ")", "{", "InputStream", "is", "=", "getClass", "(", ")", ".", "getResourceAsStream", "(", "str", "+", "\"_names.txt\"", ")", ";", "for", "(", "String", "line", ":", "Helper", ".", "readFile", "(", "new", "InputStreamReader", "(", "is", ",", "Helper", ".", "UTF_CS", ")", ")", ")", "{", "int", "lat", "=", "Integer", ".", "parseInt", "(", "line", ".", "substring", "(", "1", ",", "3", ")", ")", ";", "if", "(", "line", ".", "substring", "(", "0", ",", "1", ")", ".", "charAt", "(", "0", ")", "==", "'", "'", ")", "lat", "=", "-", "lat", ";", "int", "lon", "=", "Integer", ".", "parseInt", "(", "line", ".", "substring", "(", "4", ",", "7", ")", ")", ";", "if", "(", "line", ".", "substring", "(", "3", ",", "4", ")", ".", "charAt", "(", "0", ")", "==", "'", "'", ")", "lon", "=", "-", "lon", ";", "int", "intKey", "=", "calcIntKey", "(", "lat", ",", "lon", ")", ";", "String", "key", "=", "areas", ".", "put", "(", "intKey", ",", "str", ")", ";", "if", "(", "key", "!=", "null", ")", "throw", "new", "IllegalStateException", "(", "\"do not overwrite existing! key \"", "+", "intKey", "+", "\" \"", "+", "key", "+", "\" vs. \"", "+", "str", ")", ";", "}", "}", "return", "this", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Cannot load area names from classpath\"", ",", "ex", ")", ";", "}", "}" ]
The URLs are a bit ugly and so we need to find out which area name a certain lat,lon coordinate has.
[ "The", "URLs", "are", "a", "bit", "ugly", "and", "so", "we", "need", "to", "find", "out", "which", "area", "name", "a", "certain", "lat", "lon", "coordinate", "has", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/reader/dem/SRTMProvider.java#L86-L110
21,168
graphhopper/graphhopper
reader-osm/src/main/java/com/graphhopper/reader/osm/OSMFileHeader.java
OSMFileHeader.create
public static OSMFileHeader create(long id, XMLStreamReader parser) throws XMLStreamException { OSMFileHeader header = new OSMFileHeader(); parser.nextTag(); return header; }
java
public static OSMFileHeader create(long id, XMLStreamReader parser) throws XMLStreamException { OSMFileHeader header = new OSMFileHeader(); parser.nextTag(); return header; }
[ "public", "static", "OSMFileHeader", "create", "(", "long", "id", ",", "XMLStreamReader", "parser", ")", "throws", "XMLStreamException", "{", "OSMFileHeader", "header", "=", "new", "OSMFileHeader", "(", ")", ";", "parser", ".", "nextTag", "(", ")", ";", "return", "header", ";", "}" ]
Constructor for XML Parser
[ "Constructor", "for", "XML", "Parser" ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/reader-osm/src/main/java/com/graphhopper/reader/osm/OSMFileHeader.java#L40-L44
21,169
graphhopper/graphhopper
core/src/main/java/com/graphhopper/routing/util/DataFlagEncoder.java
DataFlagEncoder.getHighwayAsString
public String getHighwayAsString(EdgeIteratorState edge) { int val = getHighway(edge); for (Entry<String, Integer> e : highwayMap.entrySet()) { if (e.getValue() == val) return e.getKey(); } return null; }
java
public String getHighwayAsString(EdgeIteratorState edge) { int val = getHighway(edge); for (Entry<String, Integer> e : highwayMap.entrySet()) { if (e.getValue() == val) return e.getKey(); } return null; }
[ "public", "String", "getHighwayAsString", "(", "EdgeIteratorState", "edge", ")", "{", "int", "val", "=", "getHighway", "(", "edge", ")", ";", "for", "(", "Entry", "<", "String", ",", "Integer", ">", "e", ":", "highwayMap", ".", "entrySet", "(", ")", ")", "{", "if", "(", "e", ".", "getValue", "(", ")", "==", "val", ")", "return", "e", ".", "getKey", "(", ")", ";", "}", "return", "null", ";", "}" ]
Do not use within weighting as this is suboptimal from performance point of view.
[ "Do", "not", "use", "within", "weighting", "as", "this", "is", "suboptimal", "from", "performance", "point", "of", "view", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/util/DataFlagEncoder.java#L534-L541
21,170
graphhopper/graphhopper
core/src/main/java/com/graphhopper/routing/util/DataFlagEncoder.java
DataFlagEncoder.createWeightingConfig
public WeightingConfig createWeightingConfig(PMap pMap) { HashMap<String, Double> map = new HashMap<>(DEFAULT_SPEEDS.size()); for (Entry<String, Double> e : DEFAULT_SPEEDS.entrySet()) { map.put(e.getKey(), pMap.getDouble(e.getKey(), e.getValue())); } return new WeightingConfig(getHighwaySpeedMap(map)); }
java
public WeightingConfig createWeightingConfig(PMap pMap) { HashMap<String, Double> map = new HashMap<>(DEFAULT_SPEEDS.size()); for (Entry<String, Double> e : DEFAULT_SPEEDS.entrySet()) { map.put(e.getKey(), pMap.getDouble(e.getKey(), e.getValue())); } return new WeightingConfig(getHighwaySpeedMap(map)); }
[ "public", "WeightingConfig", "createWeightingConfig", "(", "PMap", "pMap", ")", "{", "HashMap", "<", "String", ",", "Double", ">", "map", "=", "new", "HashMap", "<>", "(", "DEFAULT_SPEEDS", ".", "size", "(", ")", ")", ";", "for", "(", "Entry", "<", "String", ",", "Double", ">", "e", ":", "DEFAULT_SPEEDS", ".", "entrySet", "(", ")", ")", "{", "map", ".", "put", "(", "e", ".", "getKey", "(", ")", ",", "pMap", ".", "getDouble", "(", "e", ".", "getKey", "(", ")", ",", "e", ".", "getValue", "(", ")", ")", ")", ";", "}", "return", "new", "WeightingConfig", "(", "getHighwaySpeedMap", "(", "map", ")", ")", ";", "}" ]
This method creates a Config map out of the PMap. Later on this conversion should not be necessary when we read JSON.
[ "This", "method", "creates", "a", "Config", "map", "out", "of", "the", "PMap", ".", "Later", "on", "this", "conversion", "should", "not", "be", "necessary", "when", "we", "read", "JSON", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/util/DataFlagEncoder.java#L743-L750
21,171
graphhopper/graphhopper
core/src/main/java/com/graphhopper/routing/util/BikeCommonFlagEncoder.java
BikeCommonFlagEncoder.handleBikeRelated
void handleBikeRelated(IntsRef edgeFlags, ReaderWay way, boolean partOfCycleRelation) { String surfaceTag = way.getTag("surface"); String highway = way.getTag("highway"); String trackType = way.getTag("tracktype"); // Populate unpavedBit if ("track".equals(highway) && (trackType == null || !"grade1".equals(trackType)) || "path".equals(highway) && surfaceTag == null || unpavedSurfaceTags.contains(surfaceTag)) { unpavedEncoder.setBool(false, edgeFlags, true); } WayType wayType; if (roadValues.contains(highway)) wayType = WayType.ROAD; else wayType = WayType.OTHER_SMALL_WAY; boolean isPushingSection = isPushingSection(way); if (isPushingSection && !partOfCycleRelation || "steps".equals(highway)) wayType = WayType.PUSHING_SECTION; if (way.hasTag("bicycle", intendedValues)) { if (isPushingSection && !way.hasTag("bicycle", "designated")) wayType = WayType.OTHER_SMALL_WAY; else if (wayType == WayType.OTHER_SMALL_WAY || wayType == WayType.PUSHING_SECTION) wayType = WayType.CYCLEWAY; } else if ("cycleway".equals(highway)) wayType = WayType.CYCLEWAY; wayTypeEncoder.setInt(false, edgeFlags, wayType.getValue()); }
java
void handleBikeRelated(IntsRef edgeFlags, ReaderWay way, boolean partOfCycleRelation) { String surfaceTag = way.getTag("surface"); String highway = way.getTag("highway"); String trackType = way.getTag("tracktype"); // Populate unpavedBit if ("track".equals(highway) && (trackType == null || !"grade1".equals(trackType)) || "path".equals(highway) && surfaceTag == null || unpavedSurfaceTags.contains(surfaceTag)) { unpavedEncoder.setBool(false, edgeFlags, true); } WayType wayType; if (roadValues.contains(highway)) wayType = WayType.ROAD; else wayType = WayType.OTHER_SMALL_WAY; boolean isPushingSection = isPushingSection(way); if (isPushingSection && !partOfCycleRelation || "steps".equals(highway)) wayType = WayType.PUSHING_SECTION; if (way.hasTag("bicycle", intendedValues)) { if (isPushingSection && !way.hasTag("bicycle", "designated")) wayType = WayType.OTHER_SMALL_WAY; else if (wayType == WayType.OTHER_SMALL_WAY || wayType == WayType.PUSHING_SECTION) wayType = WayType.CYCLEWAY; } else if ("cycleway".equals(highway)) wayType = WayType.CYCLEWAY; wayTypeEncoder.setInt(false, edgeFlags, wayType.getValue()); }
[ "void", "handleBikeRelated", "(", "IntsRef", "edgeFlags", ",", "ReaderWay", "way", ",", "boolean", "partOfCycleRelation", ")", "{", "String", "surfaceTag", "=", "way", ".", "getTag", "(", "\"surface\"", ")", ";", "String", "highway", "=", "way", ".", "getTag", "(", "\"highway\"", ")", ";", "String", "trackType", "=", "way", ".", "getTag", "(", "\"tracktype\"", ")", ";", "// Populate unpavedBit", "if", "(", "\"track\"", ".", "equals", "(", "highway", ")", "&&", "(", "trackType", "==", "null", "||", "!", "\"grade1\"", ".", "equals", "(", "trackType", ")", ")", "||", "\"path\"", ".", "equals", "(", "highway", ")", "&&", "surfaceTag", "==", "null", "||", "unpavedSurfaceTags", ".", "contains", "(", "surfaceTag", ")", ")", "{", "unpavedEncoder", ".", "setBool", "(", "false", ",", "edgeFlags", ",", "true", ")", ";", "}", "WayType", "wayType", ";", "if", "(", "roadValues", ".", "contains", "(", "highway", ")", ")", "wayType", "=", "WayType", ".", "ROAD", ";", "else", "wayType", "=", "WayType", ".", "OTHER_SMALL_WAY", ";", "boolean", "isPushingSection", "=", "isPushingSection", "(", "way", ")", ";", "if", "(", "isPushingSection", "&&", "!", "partOfCycleRelation", "||", "\"steps\"", ".", "equals", "(", "highway", ")", ")", "wayType", "=", "WayType", ".", "PUSHING_SECTION", ";", "if", "(", "way", ".", "hasTag", "(", "\"bicycle\"", ",", "intendedValues", ")", ")", "{", "if", "(", "isPushingSection", "&&", "!", "way", ".", "hasTag", "(", "\"bicycle\"", ",", "\"designated\"", ")", ")", "wayType", "=", "WayType", ".", "OTHER_SMALL_WAY", ";", "else", "if", "(", "wayType", "==", "WayType", ".", "OTHER_SMALL_WAY", "||", "wayType", "==", "WayType", ".", "PUSHING_SECTION", ")", "wayType", "=", "WayType", ".", "CYCLEWAY", ";", "}", "else", "if", "(", "\"cycleway\"", ".", "equals", "(", "highway", ")", ")", "wayType", "=", "WayType", ".", "CYCLEWAY", ";", "wayTypeEncoder", ".", "setInt", "(", "false", ",", "edgeFlags", ",", "wayType", ".", "getValue", "(", ")", ")", ";", "}" ]
Handle surface and wayType encoding
[ "Handle", "surface", "and", "wayType", "encoding" ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/util/BikeCommonFlagEncoder.java#L591-L622
21,172
graphhopper/graphhopper
core/src/main/java/com/graphhopper/storage/index/LocationIndexTree.java
LocationIndexTree.createReverseKey
final long createReverseKey(double lat, double lon) { return BitUtil.BIG.reverse(keyAlgo.encode(lat, lon), keyAlgo.getBits()); }
java
final long createReverseKey(double lat, double lon) { return BitUtil.BIG.reverse(keyAlgo.encode(lat, lon), keyAlgo.getBits()); }
[ "final", "long", "createReverseKey", "(", "double", "lat", ",", "double", "lon", ")", "{", "return", "BitUtil", ".", "BIG", ".", "reverse", "(", "keyAlgo", ".", "encode", "(", "lat", ",", "lon", ")", ",", "keyAlgo", ".", "getBits", "(", ")", ")", ";", "}" ]
this method returns the spatial key in reverse order for easier right-shifting
[ "this", "method", "returns", "the", "spatial", "key", "in", "reverse", "order", "for", "easier", "right", "-", "shifting" ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/storage/index/LocationIndexTree.java#L377-L379
21,173
graphhopper/graphhopper
api/src/main/java/com/graphhopper/util/shapes/Polygon.java
Polygon.create
public static Polygon create(org.locationtech.jts.geom.Polygon polygon) { double[] lats = new double[polygon.getNumPoints()]; double[] lons = new double[polygon.getNumPoints()]; for (int i = 0; i < polygon.getNumPoints(); i++) { lats[i] = polygon.getCoordinates()[i].y; lons[i] = polygon.getCoordinates()[i].x; } return new Polygon(lats, lons); }
java
public static Polygon create(org.locationtech.jts.geom.Polygon polygon) { double[] lats = new double[polygon.getNumPoints()]; double[] lons = new double[polygon.getNumPoints()]; for (int i = 0; i < polygon.getNumPoints(); i++) { lats[i] = polygon.getCoordinates()[i].y; lons[i] = polygon.getCoordinates()[i].x; } return new Polygon(lats, lons); }
[ "public", "static", "Polygon", "create", "(", "org", ".", "locationtech", ".", "jts", ".", "geom", ".", "Polygon", "polygon", ")", "{", "double", "[", "]", "lats", "=", "new", "double", "[", "polygon", ".", "getNumPoints", "(", ")", "]", ";", "double", "[", "]", "lons", "=", "new", "double", "[", "polygon", ".", "getNumPoints", "(", ")", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "polygon", ".", "getNumPoints", "(", ")", ";", "i", "++", ")", "{", "lats", "[", "i", "]", "=", "polygon", ".", "getCoordinates", "(", ")", "[", "i", "]", ".", "y", ";", "lons", "[", "i", "]", "=", "polygon", ".", "getCoordinates", "(", ")", "[", "i", "]", ".", "x", ";", "}", "return", "new", "Polygon", "(", "lats", ",", "lons", ")", ";", "}" ]
Lossy conversion to a GraphHopper Polygon.
[ "Lossy", "conversion", "to", "a", "GraphHopper", "Polygon", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/api/src/main/java/com/graphhopper/util/shapes/Polygon.java#L85-L93
21,174
graphhopper/graphhopper
core/src/main/java/com/graphhopper/util/Downloader.java
Downloader.fetch
public InputStream fetch(HttpURLConnection connection, boolean readErrorStreamNoException) throws IOException { // create connection but before reading get the correct inputstream based on the compression and if error connection.connect(); InputStream is; if (readErrorStreamNoException && connection.getResponseCode() >= 400 && connection.getErrorStream() != null) is = connection.getErrorStream(); else is = connection.getInputStream(); if (is == null) throw new IOException("Stream is null. Message:" + connection.getResponseMessage()); // wrap try { String encoding = connection.getContentEncoding(); if (encoding != null && encoding.equalsIgnoreCase("gzip")) is = new GZIPInputStream(is); else if (encoding != null && encoding.equalsIgnoreCase("deflate")) is = new InflaterInputStream(is, new Inflater(true)); } catch (IOException ex) { } return is; }
java
public InputStream fetch(HttpURLConnection connection, boolean readErrorStreamNoException) throws IOException { // create connection but before reading get the correct inputstream based on the compression and if error connection.connect(); InputStream is; if (readErrorStreamNoException && connection.getResponseCode() >= 400 && connection.getErrorStream() != null) is = connection.getErrorStream(); else is = connection.getInputStream(); if (is == null) throw new IOException("Stream is null. Message:" + connection.getResponseMessage()); // wrap try { String encoding = connection.getContentEncoding(); if (encoding != null && encoding.equalsIgnoreCase("gzip")) is = new GZIPInputStream(is); else if (encoding != null && encoding.equalsIgnoreCase("deflate")) is = new InflaterInputStream(is, new Inflater(true)); } catch (IOException ex) { } return is; }
[ "public", "InputStream", "fetch", "(", "HttpURLConnection", "connection", ",", "boolean", "readErrorStreamNoException", ")", "throws", "IOException", "{", "// create connection but before reading get the correct inputstream based on the compression and if error", "connection", ".", "connect", "(", ")", ";", "InputStream", "is", ";", "if", "(", "readErrorStreamNoException", "&&", "connection", ".", "getResponseCode", "(", ")", ">=", "400", "&&", "connection", ".", "getErrorStream", "(", ")", "!=", "null", ")", "is", "=", "connection", ".", "getErrorStream", "(", ")", ";", "else", "is", "=", "connection", ".", "getInputStream", "(", ")", ";", "if", "(", "is", "==", "null", ")", "throw", "new", "IOException", "(", "\"Stream is null. Message:\"", "+", "connection", ".", "getResponseMessage", "(", ")", ")", ";", "// wrap", "try", "{", "String", "encoding", "=", "connection", ".", "getContentEncoding", "(", ")", ";", "if", "(", "encoding", "!=", "null", "&&", "encoding", ".", "equalsIgnoreCase", "(", "\"gzip\"", ")", ")", "is", "=", "new", "GZIPInputStream", "(", "is", ")", ";", "else", "if", "(", "encoding", "!=", "null", "&&", "encoding", ".", "equalsIgnoreCase", "(", "\"deflate\"", ")", ")", "is", "=", "new", "InflaterInputStream", "(", "is", ",", "new", "Inflater", "(", "true", ")", ")", ";", "}", "catch", "(", "IOException", "ex", ")", "{", "}", "return", "is", ";", "}" ]
This method initiates a connect call of the provided connection and returns the response stream. It only returns the error stream if it is available and readErrorStreamNoException is true otherwise it throws an IOException if an error happens. Furthermore it wraps the stream to decompress it if the connection content encoding is specified.
[ "This", "method", "initiates", "a", "connect", "call", "of", "the", "provided", "connection", "and", "returns", "the", "response", "stream", ".", "It", "only", "returns", "the", "error", "stream", "if", "it", "is", "available", "and", "readErrorStreamNoException", "is", "true", "otherwise", "it", "throws", "an", "IOException", "if", "an", "error", "happens", ".", "Furthermore", "it", "wraps", "the", "stream", "to", "decompress", "it", "if", "the", "connection", "content", "encoding", "is", "specified", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/util/Downloader.java#L66-L90
21,175
graphhopper/graphhopper
core/src/main/java/com/graphhopper/storage/GraphHopperStorage.java
GraphHopperStorage.getGraph
public <T extends Graph> T getGraph(Class<T> clazz, Weighting weighting) { if (clazz.equals(Graph.class)) return (T) baseGraph; Collection<CHGraphImpl> chGraphs = getAllCHGraphs(); if (chGraphs.isEmpty()) throw new IllegalStateException("Cannot find graph implementation for " + clazz); if (weighting == null) throw new IllegalStateException("Cannot find CHGraph with null weighting"); List<Weighting> existing = new ArrayList<>(); for (CHGraphImpl cg : chGraphs) { if (cg.getWeighting() == weighting) return (T) cg; existing.add(cg.getWeighting()); } throw new IllegalStateException("Cannot find CHGraph for specified weighting: " + weighting + ", existing:" + existing); }
java
public <T extends Graph> T getGraph(Class<T> clazz, Weighting weighting) { if (clazz.equals(Graph.class)) return (T) baseGraph; Collection<CHGraphImpl> chGraphs = getAllCHGraphs(); if (chGraphs.isEmpty()) throw new IllegalStateException("Cannot find graph implementation for " + clazz); if (weighting == null) throw new IllegalStateException("Cannot find CHGraph with null weighting"); List<Weighting> existing = new ArrayList<>(); for (CHGraphImpl cg : chGraphs) { if (cg.getWeighting() == weighting) return (T) cg; existing.add(cg.getWeighting()); } throw new IllegalStateException("Cannot find CHGraph for specified weighting: " + weighting + ", existing:" + existing); }
[ "public", "<", "T", "extends", "Graph", ">", "T", "getGraph", "(", "Class", "<", "T", ">", "clazz", ",", "Weighting", "weighting", ")", "{", "if", "(", "clazz", ".", "equals", "(", "Graph", ".", "class", ")", ")", "return", "(", "T", ")", "baseGraph", ";", "Collection", "<", "CHGraphImpl", ">", "chGraphs", "=", "getAllCHGraphs", "(", ")", ";", "if", "(", "chGraphs", ".", "isEmpty", "(", ")", ")", "throw", "new", "IllegalStateException", "(", "\"Cannot find graph implementation for \"", "+", "clazz", ")", ";", "if", "(", "weighting", "==", "null", ")", "throw", "new", "IllegalStateException", "(", "\"Cannot find CHGraph with null weighting\"", ")", ";", "List", "<", "Weighting", ">", "existing", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "CHGraphImpl", "cg", ":", "chGraphs", ")", "{", "if", "(", "cg", ".", "getWeighting", "(", ")", "==", "weighting", ")", "return", "(", "T", ")", "cg", ";", "existing", ".", "add", "(", "cg", ".", "getWeighting", "(", ")", ")", ";", "}", "throw", "new", "IllegalStateException", "(", "\"Cannot find CHGraph for specified weighting: \"", "+", "weighting", "+", "\", existing:\"", "+", "existing", ")", ";", "}" ]
This method returns the routing graph for the specified weighting, could be potentially filled with shortcuts.
[ "This", "method", "returns", "the", "routing", "graph", "for", "the", "specified", "weighting", "could", "be", "potentially", "filled", "with", "shortcuts", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/storage/GraphHopperStorage.java#L102-L122
21,176
graphhopper/graphhopper
core/src/main/java/com/graphhopper/storage/GraphHopperStorage.java
GraphHopperStorage.create
@Override public GraphHopperStorage create(long byteCount) { baseGraph.checkInit(); if (encodingManager == null) throw new IllegalStateException("EncodingManager can only be null if you call loadExisting"); dir.create(); long initSize = Math.max(byteCount, 100); properties.create(100); properties.put("graph.bytes_for_flags", encodingManager.getBytesForFlags()); properties.put("graph.flag_encoders", encodingManager.toDetailsString()); properties.put("graph.byte_order", dir.getByteOrder()); properties.put("graph.dimension", baseGraph.nodeAccess.getDimension()); properties.putCurrentVersions(); baseGraph.create(initSize); for (CHGraphImpl cg : getAllCHGraphs()) { cg.create(byteCount); } properties.put("graph.ch.weightings", getNodeBasedCHWeightings().toString()); properties.put("graph.ch.edge.weightings", getEdgeBasedCHWeightings().toString()); return this; }
java
@Override public GraphHopperStorage create(long byteCount) { baseGraph.checkInit(); if (encodingManager == null) throw new IllegalStateException("EncodingManager can only be null if you call loadExisting"); dir.create(); long initSize = Math.max(byteCount, 100); properties.create(100); properties.put("graph.bytes_for_flags", encodingManager.getBytesForFlags()); properties.put("graph.flag_encoders", encodingManager.toDetailsString()); properties.put("graph.byte_order", dir.getByteOrder()); properties.put("graph.dimension", baseGraph.nodeAccess.getDimension()); properties.putCurrentVersions(); baseGraph.create(initSize); for (CHGraphImpl cg : getAllCHGraphs()) { cg.create(byteCount); } properties.put("graph.ch.weightings", getNodeBasedCHWeightings().toString()); properties.put("graph.ch.edge.weightings", getEdgeBasedCHWeightings().toString()); return this; }
[ "@", "Override", "public", "GraphHopperStorage", "create", "(", "long", "byteCount", ")", "{", "baseGraph", ".", "checkInit", "(", ")", ";", "if", "(", "encodingManager", "==", "null", ")", "throw", "new", "IllegalStateException", "(", "\"EncodingManager can only be null if you call loadExisting\"", ")", ";", "dir", ".", "create", "(", ")", ";", "long", "initSize", "=", "Math", ".", "max", "(", "byteCount", ",", "100", ")", ";", "properties", ".", "create", "(", "100", ")", ";", "properties", ".", "put", "(", "\"graph.bytes_for_flags\"", ",", "encodingManager", ".", "getBytesForFlags", "(", ")", ")", ";", "properties", ".", "put", "(", "\"graph.flag_encoders\"", ",", "encodingManager", ".", "toDetailsString", "(", ")", ")", ";", "properties", ".", "put", "(", "\"graph.byte_order\"", ",", "dir", ".", "getByteOrder", "(", ")", ")", ";", "properties", ".", "put", "(", "\"graph.dimension\"", ",", "baseGraph", ".", "nodeAccess", ".", "getDimension", "(", ")", ")", ";", "properties", ".", "putCurrentVersions", "(", ")", ";", "baseGraph", ".", "create", "(", "initSize", ")", ";", "for", "(", "CHGraphImpl", "cg", ":", "getAllCHGraphs", "(", ")", ")", "{", "cg", ".", "create", "(", "byteCount", ")", ";", "}", "properties", ".", "put", "(", "\"graph.ch.weightings\"", ",", "getNodeBasedCHWeightings", "(", ")", ".", "toString", "(", ")", ")", ";", "properties", ".", "put", "(", "\"graph.ch.edge.weightings\"", ",", "getEdgeBasedCHWeightings", "(", ")", ".", "toString", "(", ")", ")", ";", "return", "this", ";", "}" ]
After configuring this storage you need to create it explicitly.
[ "After", "configuring", "this", "storage", "you", "need", "to", "create", "it", "explicitly", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/storage/GraphHopperStorage.java#L176-L202
21,177
graphhopper/graphhopper
core/src/main/java/com/graphhopper/apache/commons/collections/IntDoubleBinaryHeap.java
IntDoubleBinaryHeap.percolateDownMinHeap
final void percolateDownMinHeap(final int index) { final int element = elements[index]; final float key = keys[index]; int hole = index; while (hole * 2 <= size) { int child = hole * 2; // if we have a right child and that child can not be percolated // up then move onto other child if (child != size && keys[child + 1] < keys[child]) { child++; } // if we found resting place of bubble then terminate search if (keys[child] >= key) { break; } elements[hole] = elements[child]; keys[hole] = keys[child]; hole = child; } elements[hole] = element; keys[hole] = key; }
java
final void percolateDownMinHeap(final int index) { final int element = elements[index]; final float key = keys[index]; int hole = index; while (hole * 2 <= size) { int child = hole * 2; // if we have a right child and that child can not be percolated // up then move onto other child if (child != size && keys[child + 1] < keys[child]) { child++; } // if we found resting place of bubble then terminate search if (keys[child] >= key) { break; } elements[hole] = elements[child]; keys[hole] = keys[child]; hole = child; } elements[hole] = element; keys[hole] = key; }
[ "final", "void", "percolateDownMinHeap", "(", "final", "int", "index", ")", "{", "final", "int", "element", "=", "elements", "[", "index", "]", ";", "final", "float", "key", "=", "keys", "[", "index", "]", ";", "int", "hole", "=", "index", ";", "while", "(", "hole", "*", "2", "<=", "size", ")", "{", "int", "child", "=", "hole", "*", "2", ";", "// if we have a right child and that child can not be percolated", "// up then move onto other child", "if", "(", "child", "!=", "size", "&&", "keys", "[", "child", "+", "1", "]", "<", "keys", "[", "child", "]", ")", "{", "child", "++", ";", "}", "// if we found resting place of bubble then terminate search", "if", "(", "keys", "[", "child", "]", ">=", "key", ")", "{", "break", ";", "}", "elements", "[", "hole", "]", "=", "elements", "[", "child", "]", ";", "keys", "[", "hole", "]", "=", "keys", "[", "child", "]", ";", "hole", "=", "child", ";", "}", "elements", "[", "hole", "]", "=", "element", ";", "keys", "[", "hole", "]", "=", "key", ";", "}" ]
Percolates element down heap from the array position given by the index.
[ "Percolates", "element", "down", "heap", "from", "the", "array", "position", "given", "by", "the", "index", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/apache/commons/collections/IntDoubleBinaryHeap.java#L139-L165
21,178
graphhopper/graphhopper
reader-gtfs/src/main/java/com/conveyal/gtfs/error/GTFSError.java
GTFSError.compareTo
public int compareTo (GTFSError o) { if (this.file == null && o.file != null) return -1; else if (this.file != null && o.file == null) return 1; int file = this.file == null && o.file == null ? 0 : String.CASE_INSENSITIVE_ORDER.compare(this.file, o.file); if (file != 0) return file; int errorType = String.CASE_INSENSITIVE_ORDER.compare(this.errorType, o.errorType); if (errorType != 0) return errorType; int affectedEntityId = this.affectedEntityId == null && o.affectedEntityId == null ? 0 : String.CASE_INSENSITIVE_ORDER.compare(this.affectedEntityId, o.affectedEntityId); if (affectedEntityId != 0) return affectedEntityId; else return Long.compare(this.line, o.line); }
java
public int compareTo (GTFSError o) { if (this.file == null && o.file != null) return -1; else if (this.file != null && o.file == null) return 1; int file = this.file == null && o.file == null ? 0 : String.CASE_INSENSITIVE_ORDER.compare(this.file, o.file); if (file != 0) return file; int errorType = String.CASE_INSENSITIVE_ORDER.compare(this.errorType, o.errorType); if (errorType != 0) return errorType; int affectedEntityId = this.affectedEntityId == null && o.affectedEntityId == null ? 0 : String.CASE_INSENSITIVE_ORDER.compare(this.affectedEntityId, o.affectedEntityId); if (affectedEntityId != 0) return affectedEntityId; else return Long.compare(this.line, o.line); }
[ "public", "int", "compareTo", "(", "GTFSError", "o", ")", "{", "if", "(", "this", ".", "file", "==", "null", "&&", "o", ".", "file", "!=", "null", ")", "return", "-", "1", ";", "else", "if", "(", "this", ".", "file", "!=", "null", "&&", "o", ".", "file", "==", "null", ")", "return", "1", ";", "int", "file", "=", "this", ".", "file", "==", "null", "&&", "o", ".", "file", "==", "null", "?", "0", ":", "String", ".", "CASE_INSENSITIVE_ORDER", ".", "compare", "(", "this", ".", "file", ",", "o", ".", "file", ")", ";", "if", "(", "file", "!=", "0", ")", "return", "file", ";", "int", "errorType", "=", "String", ".", "CASE_INSENSITIVE_ORDER", ".", "compare", "(", "this", ".", "errorType", ",", "o", ".", "errorType", ")", ";", "if", "(", "errorType", "!=", "0", ")", "return", "errorType", ";", "int", "affectedEntityId", "=", "this", ".", "affectedEntityId", "==", "null", "&&", "o", ".", "affectedEntityId", "==", "null", "?", "0", ":", "String", ".", "CASE_INSENSITIVE_ORDER", ".", "compare", "(", "this", ".", "affectedEntityId", ",", "o", ".", "affectedEntityId", ")", ";", "if", "(", "affectedEntityId", "!=", "0", ")", "return", "affectedEntityId", ";", "else", "return", "Long", ".", "compare", "(", "this", ".", "line", ",", "o", ".", "line", ")", ";", "}" ]
must be comparable to put into mapdb
[ "must", "be", "comparable", "to", "put", "into", "mapdb" ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/reader-gtfs/src/main/java/com/conveyal/gtfs/error/GTFSError.java#L79-L90
21,179
graphhopper/graphhopper
reader-gtfs/src/main/java/com/graphhopper/reader/gtfs/Transfers.java
Transfers.getTransfersToStop
List<Transfer> getTransfersToStop(String toStopId, String toRouteId) { final List<Transfer> allInboundTransfers = transfersToStop.getOrDefault(toStopId, Collections.emptyList()); final Map<String, List<Transfer>> byFromStop = allInboundTransfers.stream() .filter(t -> t.transfer_type == 0 || t.transfer_type == 2) .filter(t -> t.to_route_id == null || toRouteId.equals(t.to_route_id)) .collect(Collectors.groupingBy(t -> t.from_stop_id)); final List<Transfer> result = new ArrayList<>(); byFromStop.forEach((fromStop, transfers) -> { routesByStop.getOrDefault(fromStop, Collections.emptySet()).forEach(fromRoute -> { final Transfer mostSpecificRule = findMostSpecificRule(transfers, fromRoute, toRouteId); final Transfer myRule = new Transfer(); myRule.to_route_id = toRouteId; myRule.from_route_id = fromRoute; myRule.to_stop_id = mostSpecificRule.to_stop_id; myRule.from_stop_id = mostSpecificRule.from_stop_id; myRule.transfer_type = mostSpecificRule.transfer_type; myRule.min_transfer_time = mostSpecificRule.min_transfer_time; myRule.from_trip_id = mostSpecificRule.from_trip_id; myRule.to_trip_id = mostSpecificRule.to_trip_id; result.add(myRule); }); }); return result; }
java
List<Transfer> getTransfersToStop(String toStopId, String toRouteId) { final List<Transfer> allInboundTransfers = transfersToStop.getOrDefault(toStopId, Collections.emptyList()); final Map<String, List<Transfer>> byFromStop = allInboundTransfers.stream() .filter(t -> t.transfer_type == 0 || t.transfer_type == 2) .filter(t -> t.to_route_id == null || toRouteId.equals(t.to_route_id)) .collect(Collectors.groupingBy(t -> t.from_stop_id)); final List<Transfer> result = new ArrayList<>(); byFromStop.forEach((fromStop, transfers) -> { routesByStop.getOrDefault(fromStop, Collections.emptySet()).forEach(fromRoute -> { final Transfer mostSpecificRule = findMostSpecificRule(transfers, fromRoute, toRouteId); final Transfer myRule = new Transfer(); myRule.to_route_id = toRouteId; myRule.from_route_id = fromRoute; myRule.to_stop_id = mostSpecificRule.to_stop_id; myRule.from_stop_id = mostSpecificRule.from_stop_id; myRule.transfer_type = mostSpecificRule.transfer_type; myRule.min_transfer_time = mostSpecificRule.min_transfer_time; myRule.from_trip_id = mostSpecificRule.from_trip_id; myRule.to_trip_id = mostSpecificRule.to_trip_id; result.add(myRule); }); }); return result; }
[ "List", "<", "Transfer", ">", "getTransfersToStop", "(", "String", "toStopId", ",", "String", "toRouteId", ")", "{", "final", "List", "<", "Transfer", ">", "allInboundTransfers", "=", "transfersToStop", ".", "getOrDefault", "(", "toStopId", ",", "Collections", ".", "emptyList", "(", ")", ")", ";", "final", "Map", "<", "String", ",", "List", "<", "Transfer", ">", ">", "byFromStop", "=", "allInboundTransfers", ".", "stream", "(", ")", ".", "filter", "(", "t", "->", "t", ".", "transfer_type", "==", "0", "||", "t", ".", "transfer_type", "==", "2", ")", ".", "filter", "(", "t", "->", "t", ".", "to_route_id", "==", "null", "||", "toRouteId", ".", "equals", "(", "t", ".", "to_route_id", ")", ")", ".", "collect", "(", "Collectors", ".", "groupingBy", "(", "t", "->", "t", ".", "from_stop_id", ")", ")", ";", "final", "List", "<", "Transfer", ">", "result", "=", "new", "ArrayList", "<>", "(", ")", ";", "byFromStop", ".", "forEach", "(", "(", "fromStop", ",", "transfers", ")", "->", "{", "routesByStop", ".", "getOrDefault", "(", "fromStop", ",", "Collections", ".", "emptySet", "(", ")", ")", ".", "forEach", "(", "fromRoute", "->", "{", "final", "Transfer", "mostSpecificRule", "=", "findMostSpecificRule", "(", "transfers", ",", "fromRoute", ",", "toRouteId", ")", ";", "final", "Transfer", "myRule", "=", "new", "Transfer", "(", ")", ";", "myRule", ".", "to_route_id", "=", "toRouteId", ";", "myRule", ".", "from_route_id", "=", "fromRoute", ";", "myRule", ".", "to_stop_id", "=", "mostSpecificRule", ".", "to_stop_id", ";", "myRule", ".", "from_stop_id", "=", "mostSpecificRule", ".", "from_stop_id", ";", "myRule", ".", "transfer_type", "=", "mostSpecificRule", ".", "transfer_type", ";", "myRule", ".", "min_transfer_time", "=", "mostSpecificRule", ".", "min_transfer_time", ";", "myRule", ".", "from_trip_id", "=", "mostSpecificRule", ".", "from_trip_id", ";", "myRule", ".", "to_trip_id", "=", "mostSpecificRule", ".", "to_trip_id", ";", "result", ".", "add", "(", "myRule", ")", ";", "}", ")", ";", "}", ")", ";", "return", "result", ";", "}" ]
So far, only the route is supported.
[ "So", "far", "only", "the", "route", "is", "supported", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/reader-gtfs/src/main/java/com/graphhopper/reader/gtfs/Transfers.java#L43-L66
21,180
graphhopper/graphhopper
core/src/main/java/com/graphhopper/reader/dem/AbstractTiffElevationProvider.java
AbstractTiffElevationProvider.downloadFile
private void downloadFile(File downloadFile, String url) throws IOException { if (!downloadFile.exists()) { int max = 3; for (int trial = 0; trial < max; trial++) { try { downloader.downloadFile(url, downloadFile.getAbsolutePath()); return; } catch (SocketTimeoutException ex) { if (trial >= max - 1) throw new RuntimeException(ex); try { Thread.sleep(sleep); } catch (InterruptedException ignored) { } } } } }
java
private void downloadFile(File downloadFile, String url) throws IOException { if (!downloadFile.exists()) { int max = 3; for (int trial = 0; trial < max; trial++) { try { downloader.downloadFile(url, downloadFile.getAbsolutePath()); return; } catch (SocketTimeoutException ex) { if (trial >= max - 1) throw new RuntimeException(ex); try { Thread.sleep(sleep); } catch (InterruptedException ignored) { } } } } }
[ "private", "void", "downloadFile", "(", "File", "downloadFile", ",", "String", "url", ")", "throws", "IOException", "{", "if", "(", "!", "downloadFile", ".", "exists", "(", ")", ")", "{", "int", "max", "=", "3", ";", "for", "(", "int", "trial", "=", "0", ";", "trial", "<", "max", ";", "trial", "++", ")", "{", "try", "{", "downloader", ".", "downloadFile", "(", "url", ",", "downloadFile", ".", "getAbsolutePath", "(", ")", ")", ";", "return", ";", "}", "catch", "(", "SocketTimeoutException", "ex", ")", "{", "if", "(", "trial", ">=", "max", "-", "1", ")", "throw", "new", "RuntimeException", "(", "ex", ")", ";", "try", "{", "Thread", ".", "sleep", "(", "sleep", ")", ";", "}", "catch", "(", "InterruptedException", "ignored", ")", "{", "}", "}", "}", "}", "}" ]
Download a file at the provided url and save it as the given downloadFile if the downloadFile does not exist.
[ "Download", "a", "file", "at", "the", "provided", "url", "and", "save", "it", "as", "the", "given", "downloadFile", "if", "the", "downloadFile", "does", "not", "exist", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/reader/dem/AbstractTiffElevationProvider.java#L150-L167
21,181
graphhopper/graphhopper
core/src/main/java/com/graphhopper/routing/subnetwork/TarjansSCCAlgorithm.java
TarjansSCCAlgorithm.findComponents
public List<IntArrayList> findComponents() { int nodes = graph.getNodes(); for (int start = 0; start < nodes; start++) { if (nodeIndex[start] == 0 && !ignoreSet.contains(start) && !graph.isNodeRemoved(start)) strongConnect(start); } return components; }
java
public List<IntArrayList> findComponents() { int nodes = graph.getNodes(); for (int start = 0; start < nodes; start++) { if (nodeIndex[start] == 0 && !ignoreSet.contains(start) && !graph.isNodeRemoved(start)) strongConnect(start); } return components; }
[ "public", "List", "<", "IntArrayList", ">", "findComponents", "(", ")", "{", "int", "nodes", "=", "graph", ".", "getNodes", "(", ")", ";", "for", "(", "int", "start", "=", "0", ";", "start", "<", "nodes", ";", "start", "++", ")", "{", "if", "(", "nodeIndex", "[", "start", "]", "==", "0", "&&", "!", "ignoreSet", ".", "contains", "(", "start", ")", "&&", "!", "graph", ".", "isNodeRemoved", "(", "start", ")", ")", "strongConnect", "(", "start", ")", ";", "}", "return", "components", ";", "}" ]
Find and return list of all strongly connected components in g.
[ "Find", "and", "return", "list", "of", "all", "strongly", "connected", "components", "in", "g", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/subnetwork/TarjansSCCAlgorithm.java#L87-L97
21,182
graphhopper/graphhopper
core/src/main/java/com/graphhopper/reader/dem/MultiSourceElevationProvider.java
MultiSourceElevationProvider.setBaseURL
@Override public ElevationProvider setBaseURL(String baseURL) { String[] urls = baseURL.split(";"); if (urls.length != 2) { throw new IllegalArgumentException("The base url must consist of two urls separated by a ';'. The first for cgiar, the second for gmted"); } srtmProvider.setBaseURL(urls[0]); globalProvider.setBaseURL(urls[1]); return this; }
java
@Override public ElevationProvider setBaseURL(String baseURL) { String[] urls = baseURL.split(";"); if (urls.length != 2) { throw new IllegalArgumentException("The base url must consist of two urls separated by a ';'. The first for cgiar, the second for gmted"); } srtmProvider.setBaseURL(urls[0]); globalProvider.setBaseURL(urls[1]); return this; }
[ "@", "Override", "public", "ElevationProvider", "setBaseURL", "(", "String", "baseURL", ")", "{", "String", "[", "]", "urls", "=", "baseURL", ".", "split", "(", "\";\"", ")", ";", "if", "(", "urls", ".", "length", "!=", "2", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"The base url must consist of two urls separated by a ';'. The first for cgiar, the second for gmted\"", ")", ";", "}", "srtmProvider", ".", "setBaseURL", "(", "urls", "[", "0", "]", ")", ";", "globalProvider", ".", "setBaseURL", "(", "urls", "[", "1", "]", ")", ";", "return", "this", ";", "}" ]
For the MultiSourceElevationProvider you have to specify the base URL separated by a ';'. The first for cgiar, the second for gmted.
[ "For", "the", "MultiSourceElevationProvider", "you", "have", "to", "specify", "the", "base", "URL", "separated", "by", "a", ";", ".", "The", "first", "for", "cgiar", "the", "second", "for", "gmted", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/reader/dem/MultiSourceElevationProvider.java#L61-L70
21,183
graphhopper/graphhopper
core/src/main/java/com/graphhopper/routing/weighting/TurnWeighting.java
TurnWeighting.calcTurnWeight
public double calcTurnWeight(int edgeFrom, int nodeVia, int edgeTo) { long turnFlags = turnCostExt.getTurnCostFlags(edgeFrom, nodeVia, edgeTo); if (turnCostEncoder.isTurnRestricted(turnFlags)) return Double.POSITIVE_INFINITY; return turnCostEncoder.getTurnCost(turnFlags); }
java
public double calcTurnWeight(int edgeFrom, int nodeVia, int edgeTo) { long turnFlags = turnCostExt.getTurnCostFlags(edgeFrom, nodeVia, edgeTo); if (turnCostEncoder.isTurnRestricted(turnFlags)) return Double.POSITIVE_INFINITY; return turnCostEncoder.getTurnCost(turnFlags); }
[ "public", "double", "calcTurnWeight", "(", "int", "edgeFrom", ",", "int", "nodeVia", ",", "int", "edgeTo", ")", "{", "long", "turnFlags", "=", "turnCostExt", ".", "getTurnCostFlags", "(", "edgeFrom", ",", "nodeVia", ",", "edgeTo", ")", ";", "if", "(", "turnCostEncoder", ".", "isTurnRestricted", "(", "turnFlags", ")", ")", "return", "Double", ".", "POSITIVE_INFINITY", ";", "return", "turnCostEncoder", ".", "getTurnCost", "(", "turnFlags", ")", ";", "}" ]
This method calculates the turn weight separately.
[ "This", "method", "calculates", "the", "turn", "weight", "separately", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/weighting/TurnWeighting.java#L105-L111
21,184
graphhopper/graphhopper
core/src/main/java/com/graphhopper/routing/InstructionsOutgoingEdges.java
InstructionsOutgoingEdges.outgoingEdgesAreSlowerByFactor
public boolean outgoingEdgesAreSlowerByFactor(double factor) { double tmpSpeed = getSpeed(currentEdge); double pathSpeed = getSpeed(prevEdge); // Speed-Change on the path indicates, that we change road types, show instruction if (pathSpeed != tmpSpeed || pathSpeed < 1) { return false; } double maxSurroundingSpeed = -1; for (EdgeIteratorState edge : allOutgoingEdges) { tmpSpeed = getSpeed(edge); if (tmpSpeed < 1) { // This might happen for the DataFlagEncoder, might create unnecessary turn instructions return false; } if (tmpSpeed > maxSurroundingSpeed) { maxSurroundingSpeed = tmpSpeed; } } // Surrounding streets need to be slower by a factor return maxSurroundingSpeed * factor < pathSpeed; }
java
public boolean outgoingEdgesAreSlowerByFactor(double factor) { double tmpSpeed = getSpeed(currentEdge); double pathSpeed = getSpeed(prevEdge); // Speed-Change on the path indicates, that we change road types, show instruction if (pathSpeed != tmpSpeed || pathSpeed < 1) { return false; } double maxSurroundingSpeed = -1; for (EdgeIteratorState edge : allOutgoingEdges) { tmpSpeed = getSpeed(edge); if (tmpSpeed < 1) { // This might happen for the DataFlagEncoder, might create unnecessary turn instructions return false; } if (tmpSpeed > maxSurroundingSpeed) { maxSurroundingSpeed = tmpSpeed; } } // Surrounding streets need to be slower by a factor return maxSurroundingSpeed * factor < pathSpeed; }
[ "public", "boolean", "outgoingEdgesAreSlowerByFactor", "(", "double", "factor", ")", "{", "double", "tmpSpeed", "=", "getSpeed", "(", "currentEdge", ")", ";", "double", "pathSpeed", "=", "getSpeed", "(", "prevEdge", ")", ";", "// Speed-Change on the path indicates, that we change road types, show instruction", "if", "(", "pathSpeed", "!=", "tmpSpeed", "||", "pathSpeed", "<", "1", ")", "{", "return", "false", ";", "}", "double", "maxSurroundingSpeed", "=", "-", "1", ";", "for", "(", "EdgeIteratorState", "edge", ":", "allOutgoingEdges", ")", "{", "tmpSpeed", "=", "getSpeed", "(", "edge", ")", ";", "if", "(", "tmpSpeed", "<", "1", ")", "{", "// This might happen for the DataFlagEncoder, might create unnecessary turn instructions", "return", "false", ";", "}", "if", "(", "tmpSpeed", ">", "maxSurroundingSpeed", ")", "{", "maxSurroundingSpeed", "=", "tmpSpeed", ";", "}", "}", "// Surrounding streets need to be slower by a factor", "return", "maxSurroundingSpeed", "*", "factor", "<", "pathSpeed", ";", "}" ]
Checks if the outgoing edges are slower by the provided factor. If they are, this indicates, that we are staying on the prominent street that one would follow anyway.
[ "Checks", "if", "the", "outgoing", "edges", "are", "slower", "by", "the", "provided", "factor", ".", "If", "they", "are", "this", "indicates", "that", "we", "are", "staying", "on", "the", "prominent", "street", "that", "one", "would", "follow", "anyway", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/InstructionsOutgoingEdges.java#L125-L149
21,185
graphhopper/graphhopper
core/src/main/java/com/graphhopper/routing/InstructionsOutgoingEdges.java
InstructionsOutgoingEdges.getOtherContinue
public EdgeIteratorState getOtherContinue(double prevLat, double prevLon, double prevOrientation) { int tmpSign; for (EdgeIteratorState edge : allowedOutgoingEdges) { GHPoint point = InstructionsHelper.getPointForOrientationCalculation(edge, nodeAccess); tmpSign = InstructionsHelper.calculateSign(prevLat, prevLon, point.getLat(), point.getLon(), prevOrientation); if (Math.abs(tmpSign) <= 1) { return edge; } } return null; }
java
public EdgeIteratorState getOtherContinue(double prevLat, double prevLon, double prevOrientation) { int tmpSign; for (EdgeIteratorState edge : allowedOutgoingEdges) { GHPoint point = InstructionsHelper.getPointForOrientationCalculation(edge, nodeAccess); tmpSign = InstructionsHelper.calculateSign(prevLat, prevLon, point.getLat(), point.getLon(), prevOrientation); if (Math.abs(tmpSign) <= 1) { return edge; } } return null; }
[ "public", "EdgeIteratorState", "getOtherContinue", "(", "double", "prevLat", ",", "double", "prevLon", ",", "double", "prevOrientation", ")", "{", "int", "tmpSign", ";", "for", "(", "EdgeIteratorState", "edge", ":", "allowedOutgoingEdges", ")", "{", "GHPoint", "point", "=", "InstructionsHelper", ".", "getPointForOrientationCalculation", "(", "edge", ",", "nodeAccess", ")", ";", "tmpSign", "=", "InstructionsHelper", ".", "calculateSign", "(", "prevLat", ",", "prevLon", ",", "point", ".", "getLat", "(", ")", ",", "point", ".", "getLon", "(", ")", ",", "prevOrientation", ")", ";", "if", "(", "Math", ".", "abs", "(", "tmpSign", ")", "<=", "1", ")", "{", "return", "edge", ";", "}", "}", "return", "null", ";", "}" ]
Returns an edge that has more or less in the same orientation as the prevEdge, but is not the currentEdge. If there is one, this indicates that we might need an instruction to help finding the correct edge out of the different choices. If there is none, return null.
[ "Returns", "an", "edge", "that", "has", "more", "or", "less", "in", "the", "same", "orientation", "as", "the", "prevEdge", "but", "is", "not", "the", "currentEdge", ".", "If", "there", "is", "one", "this", "indicates", "that", "we", "might", "need", "an", "instruction", "to", "help", "finding", "the", "correct", "edge", "out", "of", "the", "different", "choices", ".", "If", "there", "is", "none", "return", "null", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/InstructionsOutgoingEdges.java#L164-L174
21,186
graphhopper/graphhopper
core/src/main/java/com/graphhopper/routing/InstructionsOutgoingEdges.java
InstructionsOutgoingEdges.isLeavingCurrentStreet
public boolean isLeavingCurrentStreet(String prevName, String name) { if (InstructionsHelper.isNameSimilar(name, prevName)) { return false; } // If flags are changing, there might be a chance we find these flags on a different edge boolean checkFlag = currentEdge.getFlags() != prevEdge.getFlags(); for (EdgeIteratorState edge : allowedOutgoingEdges) { String edgeName = edge.getName(); IntsRef edgeFlag = edge.getFlags(); // leave the current street || enter a different street if (isTheSameStreet(prevName, prevEdge.getFlags(), edgeName, edgeFlag, checkFlag) || isTheSameStreet(name, currentEdge.getFlags(), edgeName, edgeFlag, checkFlag)) { return true; } } return false; }
java
public boolean isLeavingCurrentStreet(String prevName, String name) { if (InstructionsHelper.isNameSimilar(name, prevName)) { return false; } // If flags are changing, there might be a chance we find these flags on a different edge boolean checkFlag = currentEdge.getFlags() != prevEdge.getFlags(); for (EdgeIteratorState edge : allowedOutgoingEdges) { String edgeName = edge.getName(); IntsRef edgeFlag = edge.getFlags(); // leave the current street || enter a different street if (isTheSameStreet(prevName, prevEdge.getFlags(), edgeName, edgeFlag, checkFlag) || isTheSameStreet(name, currentEdge.getFlags(), edgeName, edgeFlag, checkFlag)) { return true; } } return false; }
[ "public", "boolean", "isLeavingCurrentStreet", "(", "String", "prevName", ",", "String", "name", ")", "{", "if", "(", "InstructionsHelper", ".", "isNameSimilar", "(", "name", ",", "prevName", ")", ")", "{", "return", "false", ";", "}", "// If flags are changing, there might be a chance we find these flags on a different edge", "boolean", "checkFlag", "=", "currentEdge", ".", "getFlags", "(", ")", "!=", "prevEdge", ".", "getFlags", "(", ")", ";", "for", "(", "EdgeIteratorState", "edge", ":", "allowedOutgoingEdges", ")", "{", "String", "edgeName", "=", "edge", ".", "getName", "(", ")", ";", "IntsRef", "edgeFlag", "=", "edge", ".", "getFlags", "(", ")", ";", "// leave the current street || enter a different street", "if", "(", "isTheSameStreet", "(", "prevName", ",", "prevEdge", ".", "getFlags", "(", ")", ",", "edgeName", ",", "edgeFlag", ",", "checkFlag", ")", "||", "isTheSameStreet", "(", "name", ",", "currentEdge", ".", "getFlags", "(", ")", ",", "edgeName", ",", "edgeFlag", ",", "checkFlag", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
If the name and prevName changes this method checks if either the current street is continued on a different edge or if the edge we are turning onto is continued on a different edge. If either of these properties is true, we can be quite certain that a turn instruction should be provided.
[ "If", "the", "name", "and", "prevName", "changes", "this", "method", "checks", "if", "either", "the", "current", "street", "is", "continued", "on", "a", "different", "edge", "or", "if", "the", "edge", "we", "are", "turning", "onto", "is", "continued", "on", "a", "different", "edge", ".", "If", "either", "of", "these", "properties", "is", "true", "we", "can", "be", "quite", "certain", "that", "a", "turn", "instruction", "should", "be", "provided", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/InstructionsOutgoingEdges.java#L181-L198
21,187
graphhopper/graphhopper
client-hc/src/main/java/com/graphhopper/api/GHMRequest.java
GHMRequest.addPoint
@Override public GHMRequest addPoint(GHPoint point) { fromPoints.add(point); toPoints.add(point); return this; }
java
@Override public GHMRequest addPoint(GHPoint point) { fromPoints.add(point); toPoints.add(point); return this; }
[ "@", "Override", "public", "GHMRequest", "addPoint", "(", "GHPoint", "point", ")", "{", "fromPoints", ".", "add", "(", "point", ")", ";", "toPoints", ".", "add", "(", "point", ")", ";", "return", "this", ";", "}" ]
This methods adds the coordinate as 'from' and 'to' to the request.
[ "This", "methods", "adds", "the", "coordinate", "as", "from", "and", "to", "to", "the", "request", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/client-hc/src/main/java/com/graphhopper/api/GHMRequest.java#L72-L77
21,188
graphhopper/graphhopper
core/src/main/java/com/graphhopper/routing/ch/PrepareContractionHierarchies.java
PrepareContractionHierarchies.useFixedNodeOrdering
public PrepareContractionHierarchies useFixedNodeOrdering(NodeOrderingProvider nodeOrderingProvider) { if (nodeOrderingProvider.getNumNodes() != prepareGraph.getNodes()) { throw new IllegalArgumentException( "contraction order size (" + nodeOrderingProvider.getNumNodes() + ")" + " must be equal to number of nodes in graph (" + prepareGraph.getNodes() + ")."); } this.nodeOrderingProvider = nodeOrderingProvider; return this; }
java
public PrepareContractionHierarchies useFixedNodeOrdering(NodeOrderingProvider nodeOrderingProvider) { if (nodeOrderingProvider.getNumNodes() != prepareGraph.getNodes()) { throw new IllegalArgumentException( "contraction order size (" + nodeOrderingProvider.getNumNodes() + ")" + " must be equal to number of nodes in graph (" + prepareGraph.getNodes() + ")."); } this.nodeOrderingProvider = nodeOrderingProvider; return this; }
[ "public", "PrepareContractionHierarchies", "useFixedNodeOrdering", "(", "NodeOrderingProvider", "nodeOrderingProvider", ")", "{", "if", "(", "nodeOrderingProvider", ".", "getNumNodes", "(", ")", "!=", "prepareGraph", ".", "getNodes", "(", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"contraction order size (\"", "+", "nodeOrderingProvider", ".", "getNumNodes", "(", ")", "+", "\")\"", "+", "\" must be equal to number of nodes in graph (\"", "+", "prepareGraph", ".", "getNodes", "(", ")", "+", "\").\"", ")", ";", "}", "this", ".", "nodeOrderingProvider", "=", "nodeOrderingProvider", ";", "return", "this", ";", "}" ]
Instead of heuristically determining a node ordering for the graph contraction it is also possible to use a fixed ordering. For example this allows re-using a previously calculated node ordering. This will speed up CH preparation, but might lead to slower queries.
[ "Instead", "of", "heuristically", "determining", "a", "node", "ordering", "for", "the", "graph", "contraction", "it", "is", "also", "possible", "to", "use", "a", "fixed", "ordering", ".", "For", "example", "this", "allows", "re", "-", "using", "a", "previously", "calculated", "node", "ordering", ".", "This", "will", "speed", "up", "CH", "preparation", "but", "might", "lead", "to", "slower", "queries", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/ch/PrepareContractionHierarchies.java#L104-L112
21,189
graphhopper/graphhopper
core/src/main/java/com/graphhopper/storage/GraphEdgeIdFinder.java
GraphEdgeIdFinder.findEdgesInShape
public void findEdgesInShape(final GHIntHashSet edgeIds, final Shape shape, EdgeFilter filter) { GHPoint center = shape.getCenter(); QueryResult qr = locationIndex.findClosest(center.getLat(), center.getLon(), filter); // TODO: if there is no street close to the center it'll fail although there are roads covered. Maybe we should check edge points or some random points in the Shape instead? if (!qr.isValid()) throw new IllegalArgumentException("Shape " + shape + " does not cover graph"); if (shape.contains(qr.getSnappedPoint().lat, qr.getSnappedPoint().lon)) edgeIds.add(qr.getClosestEdge().getEdge()); final boolean isPolygon = shape instanceof Polygon; BreadthFirstSearch bfs = new BreadthFirstSearch() { final NodeAccess na = graph.getNodeAccess(); final Shape localShape = shape; @Override protected boolean goFurther(int nodeId) { if (isPolygon) return isInsideBBox(nodeId); return localShape.contains(na.getLatitude(nodeId), na.getLongitude(nodeId)); } @Override protected boolean checkAdjacent(EdgeIteratorState edge) { int adjNodeId = edge.getAdjNode(); if (localShape.contains(na.getLatitude(adjNodeId), na.getLongitude(adjNodeId))) { edgeIds.add(edge.getEdge()); return true; } return isPolygon && isInsideBBox(adjNodeId); } private boolean isInsideBBox(int nodeId) { BBox bbox = localShape.getBounds(); double lat = na.getLatitude(nodeId); double lon = na.getLongitude(nodeId); return lat <= bbox.maxLat && lat >= bbox.minLat && lon <= bbox.maxLon && lon >= bbox.minLon; } }; bfs.start(graph.createEdgeExplorer(filter), qr.getClosestNode()); }
java
public void findEdgesInShape(final GHIntHashSet edgeIds, final Shape shape, EdgeFilter filter) { GHPoint center = shape.getCenter(); QueryResult qr = locationIndex.findClosest(center.getLat(), center.getLon(), filter); // TODO: if there is no street close to the center it'll fail although there are roads covered. Maybe we should check edge points or some random points in the Shape instead? if (!qr.isValid()) throw new IllegalArgumentException("Shape " + shape + " does not cover graph"); if (shape.contains(qr.getSnappedPoint().lat, qr.getSnappedPoint().lon)) edgeIds.add(qr.getClosestEdge().getEdge()); final boolean isPolygon = shape instanceof Polygon; BreadthFirstSearch bfs = new BreadthFirstSearch() { final NodeAccess na = graph.getNodeAccess(); final Shape localShape = shape; @Override protected boolean goFurther(int nodeId) { if (isPolygon) return isInsideBBox(nodeId); return localShape.contains(na.getLatitude(nodeId), na.getLongitude(nodeId)); } @Override protected boolean checkAdjacent(EdgeIteratorState edge) { int adjNodeId = edge.getAdjNode(); if (localShape.contains(na.getLatitude(adjNodeId), na.getLongitude(adjNodeId))) { edgeIds.add(edge.getEdge()); return true; } return isPolygon && isInsideBBox(adjNodeId); } private boolean isInsideBBox(int nodeId) { BBox bbox = localShape.getBounds(); double lat = na.getLatitude(nodeId); double lon = na.getLongitude(nodeId); return lat <= bbox.maxLat && lat >= bbox.minLat && lon <= bbox.maxLon && lon >= bbox.minLon; } }; bfs.start(graph.createEdgeExplorer(filter), qr.getClosestNode()); }
[ "public", "void", "findEdgesInShape", "(", "final", "GHIntHashSet", "edgeIds", ",", "final", "Shape", "shape", ",", "EdgeFilter", "filter", ")", "{", "GHPoint", "center", "=", "shape", ".", "getCenter", "(", ")", ";", "QueryResult", "qr", "=", "locationIndex", ".", "findClosest", "(", "center", ".", "getLat", "(", ")", ",", "center", ".", "getLon", "(", ")", ",", "filter", ")", ";", "// TODO: if there is no street close to the center it'll fail although there are roads covered. Maybe we should check edge points or some random points in the Shape instead?", "if", "(", "!", "qr", ".", "isValid", "(", ")", ")", "throw", "new", "IllegalArgumentException", "(", "\"Shape \"", "+", "shape", "+", "\" does not cover graph\"", ")", ";", "if", "(", "shape", ".", "contains", "(", "qr", ".", "getSnappedPoint", "(", ")", ".", "lat", ",", "qr", ".", "getSnappedPoint", "(", ")", ".", "lon", ")", ")", "edgeIds", ".", "add", "(", "qr", ".", "getClosestEdge", "(", ")", ".", "getEdge", "(", ")", ")", ";", "final", "boolean", "isPolygon", "=", "shape", "instanceof", "Polygon", ";", "BreadthFirstSearch", "bfs", "=", "new", "BreadthFirstSearch", "(", ")", "{", "final", "NodeAccess", "na", "=", "graph", ".", "getNodeAccess", "(", ")", ";", "final", "Shape", "localShape", "=", "shape", ";", "@", "Override", "protected", "boolean", "goFurther", "(", "int", "nodeId", ")", "{", "if", "(", "isPolygon", ")", "return", "isInsideBBox", "(", "nodeId", ")", ";", "return", "localShape", ".", "contains", "(", "na", ".", "getLatitude", "(", "nodeId", ")", ",", "na", ".", "getLongitude", "(", "nodeId", ")", ")", ";", "}", "@", "Override", "protected", "boolean", "checkAdjacent", "(", "EdgeIteratorState", "edge", ")", "{", "int", "adjNodeId", "=", "edge", ".", "getAdjNode", "(", ")", ";", "if", "(", "localShape", ".", "contains", "(", "na", ".", "getLatitude", "(", "adjNodeId", ")", ",", "na", ".", "getLongitude", "(", "adjNodeId", ")", ")", ")", "{", "edgeIds", ".", "add", "(", "edge", ".", "getEdge", "(", ")", ")", ";", "return", "true", ";", "}", "return", "isPolygon", "&&", "isInsideBBox", "(", "adjNodeId", ")", ";", "}", "private", "boolean", "isInsideBBox", "(", "int", "nodeId", ")", "{", "BBox", "bbox", "=", "localShape", ".", "getBounds", "(", ")", ";", "double", "lat", "=", "na", ".", "getLatitude", "(", "nodeId", ")", ";", "double", "lon", "=", "na", ".", "getLongitude", "(", "nodeId", ")", ";", "return", "lat", "<=", "bbox", ".", "maxLat", "&&", "lat", ">=", "bbox", ".", "minLat", "&&", "lon", "<=", "bbox", ".", "maxLon", "&&", "lon", ">=", "bbox", ".", "minLon", ";", "}", "}", ";", "bfs", ".", "start", "(", "graph", ".", "createEdgeExplorer", "(", "filter", ")", ",", "qr", ".", "getClosestNode", "(", ")", ")", ";", "}" ]
This method fills the edgeIds hash with edgeIds found inside the specified shape
[ "This", "method", "fills", "the", "edgeIds", "hash", "with", "edgeIds", "found", "inside", "the", "specified", "shape" ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/storage/GraphEdgeIdFinder.java#L71-L113
21,190
graphhopper/graphhopper
core/src/main/java/com/graphhopper/storage/GraphEdgeIdFinder.java
GraphEdgeIdFinder.fillEdgeIDs
public void fillEdgeIDs(GHIntHashSet edgeIds, Geometry geometry, EdgeFilter filter) { if (geometry instanceof Point) { GHPoint point = GHPoint.create((Point) geometry); findClosestEdgeToPoint(edgeIds, point, filter); } else if (geometry instanceof LineString) { PointList pl = PointList.fromLineString((LineString) geometry); // TODO do map matching or routing int lastIdx = pl.size() - 1; if (pl.size() >= 2) { double meanLat = (pl.getLatitude(0) + pl.getLatitude(lastIdx)) / 2; double meanLon = (pl.getLongitude(0) + pl.getLongitude(lastIdx)) / 2; findClosestEdge(edgeIds, meanLat, meanLon, filter); } } else if (geometry instanceof MultiPoint) { for (Coordinate coordinate : geometry.getCoordinates()) { findClosestEdge(edgeIds, coordinate.y, coordinate.x, filter); } } }
java
public void fillEdgeIDs(GHIntHashSet edgeIds, Geometry geometry, EdgeFilter filter) { if (geometry instanceof Point) { GHPoint point = GHPoint.create((Point) geometry); findClosestEdgeToPoint(edgeIds, point, filter); } else if (geometry instanceof LineString) { PointList pl = PointList.fromLineString((LineString) geometry); // TODO do map matching or routing int lastIdx = pl.size() - 1; if (pl.size() >= 2) { double meanLat = (pl.getLatitude(0) + pl.getLatitude(lastIdx)) / 2; double meanLon = (pl.getLongitude(0) + pl.getLongitude(lastIdx)) / 2; findClosestEdge(edgeIds, meanLat, meanLon, filter); } } else if (geometry instanceof MultiPoint) { for (Coordinate coordinate : geometry.getCoordinates()) { findClosestEdge(edgeIds, coordinate.y, coordinate.x, filter); } } }
[ "public", "void", "fillEdgeIDs", "(", "GHIntHashSet", "edgeIds", ",", "Geometry", "geometry", ",", "EdgeFilter", "filter", ")", "{", "if", "(", "geometry", "instanceof", "Point", ")", "{", "GHPoint", "point", "=", "GHPoint", ".", "create", "(", "(", "Point", ")", "geometry", ")", ";", "findClosestEdgeToPoint", "(", "edgeIds", ",", "point", ",", "filter", ")", ";", "}", "else", "if", "(", "geometry", "instanceof", "LineString", ")", "{", "PointList", "pl", "=", "PointList", ".", "fromLineString", "(", "(", "LineString", ")", "geometry", ")", ";", "// TODO do map matching or routing", "int", "lastIdx", "=", "pl", ".", "size", "(", ")", "-", "1", ";", "if", "(", "pl", ".", "size", "(", ")", ">=", "2", ")", "{", "double", "meanLat", "=", "(", "pl", ".", "getLatitude", "(", "0", ")", "+", "pl", ".", "getLatitude", "(", "lastIdx", ")", ")", "/", "2", ";", "double", "meanLon", "=", "(", "pl", ".", "getLongitude", "(", "0", ")", "+", "pl", ".", "getLongitude", "(", "lastIdx", ")", ")", "/", "2", ";", "findClosestEdge", "(", "edgeIds", ",", "meanLat", ",", "meanLon", ",", "filter", ")", ";", "}", "}", "else", "if", "(", "geometry", "instanceof", "MultiPoint", ")", "{", "for", "(", "Coordinate", "coordinate", ":", "geometry", ".", "getCoordinates", "(", ")", ")", "{", "findClosestEdge", "(", "edgeIds", ",", "coordinate", ".", "y", ",", "coordinate", ".", "x", ",", "filter", ")", ";", "}", "}", "}" ]
This method fills the edgeIds hash with edgeIds found inside the specified geometry
[ "This", "method", "fills", "the", "edgeIds", "hash", "with", "edgeIds", "found", "inside", "the", "specified", "geometry" ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/storage/GraphEdgeIdFinder.java#L118-L136
21,191
graphhopper/graphhopper
core/src/main/java/com/graphhopper/storage/GraphEdgeIdFinder.java
GraphEdgeIdFinder.parseBlockArea
public BlockArea parseBlockArea(String blockAreaString, EdgeFilter filter, double useEdgeIdsUntilAreaSize) { final String objectSeparator = ";"; final String innerObjSep = ","; BlockArea blockArea = new BlockArea(graph); // Add blocked circular areas or points if (!blockAreaString.isEmpty()) { String[] blockedCircularAreasArr = blockAreaString.split(objectSeparator); for (int i = 0; i < blockedCircularAreasArr.length; i++) { String objectAsString = blockedCircularAreasArr[i]; String[] splittedObject = objectAsString.split(innerObjSep); if (splittedObject.length > 4) { final Polygon polygon = Polygon.parsePoints(objectAsString, 0.003); findEdgesInShape(blockArea.blockedEdges, polygon, filter); } else if (splittedObject.length == 4) { final BBox bbox = BBox.parseTwoPoints(objectAsString); if (bbox.calculateArea() > useEdgeIdsUntilAreaSize) blockArea.add(bbox); else findEdgesInShape(blockArea.blockedEdges, bbox, filter); } else if (splittedObject.length == 3) { double lat = Double.parseDouble(splittedObject[0]); double lon = Double.parseDouble(splittedObject[1]); int radius = Integer.parseInt(splittedObject[2]); Circle circle = new Circle(lat, lon, radius); if (circle.calculateArea() > useEdgeIdsUntilAreaSize) { blockArea.add(circle); } else { findEdgesInShape(blockArea.blockedEdges, circle, filter); } } else if (splittedObject.length == 2) { double lat = Double.parseDouble(splittedObject[0]); double lon = Double.parseDouble(splittedObject[1]); findClosestEdge(blockArea.blockedEdges, lat, lon, filter); } else { throw new IllegalArgumentException(objectAsString + " at index " + i + " need to be defined as lat,lon " + "or as a circle lat,lon,radius or rectangular lat1,lon1,lat2,lon2"); } } } return blockArea; }
java
public BlockArea parseBlockArea(String blockAreaString, EdgeFilter filter, double useEdgeIdsUntilAreaSize) { final String objectSeparator = ";"; final String innerObjSep = ","; BlockArea blockArea = new BlockArea(graph); // Add blocked circular areas or points if (!blockAreaString.isEmpty()) { String[] blockedCircularAreasArr = blockAreaString.split(objectSeparator); for (int i = 0; i < blockedCircularAreasArr.length; i++) { String objectAsString = blockedCircularAreasArr[i]; String[] splittedObject = objectAsString.split(innerObjSep); if (splittedObject.length > 4) { final Polygon polygon = Polygon.parsePoints(objectAsString, 0.003); findEdgesInShape(blockArea.blockedEdges, polygon, filter); } else if (splittedObject.length == 4) { final BBox bbox = BBox.parseTwoPoints(objectAsString); if (bbox.calculateArea() > useEdgeIdsUntilAreaSize) blockArea.add(bbox); else findEdgesInShape(blockArea.blockedEdges, bbox, filter); } else if (splittedObject.length == 3) { double lat = Double.parseDouble(splittedObject[0]); double lon = Double.parseDouble(splittedObject[1]); int radius = Integer.parseInt(splittedObject[2]); Circle circle = new Circle(lat, lon, radius); if (circle.calculateArea() > useEdgeIdsUntilAreaSize) { blockArea.add(circle); } else { findEdgesInShape(blockArea.blockedEdges, circle, filter); } } else if (splittedObject.length == 2) { double lat = Double.parseDouble(splittedObject[0]); double lon = Double.parseDouble(splittedObject[1]); findClosestEdge(blockArea.blockedEdges, lat, lon, filter); } else { throw new IllegalArgumentException(objectAsString + " at index " + i + " need to be defined as lat,lon " + "or as a circle lat,lon,radius or rectangular lat1,lon1,lat2,lon2"); } } } return blockArea; }
[ "public", "BlockArea", "parseBlockArea", "(", "String", "blockAreaString", ",", "EdgeFilter", "filter", ",", "double", "useEdgeIdsUntilAreaSize", ")", "{", "final", "String", "objectSeparator", "=", "\";\"", ";", "final", "String", "innerObjSep", "=", "\",\"", ";", "BlockArea", "blockArea", "=", "new", "BlockArea", "(", "graph", ")", ";", "// Add blocked circular areas or points", "if", "(", "!", "blockAreaString", ".", "isEmpty", "(", ")", ")", "{", "String", "[", "]", "blockedCircularAreasArr", "=", "blockAreaString", ".", "split", "(", "objectSeparator", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "blockedCircularAreasArr", ".", "length", ";", "i", "++", ")", "{", "String", "objectAsString", "=", "blockedCircularAreasArr", "[", "i", "]", ";", "String", "[", "]", "splittedObject", "=", "objectAsString", ".", "split", "(", "innerObjSep", ")", ";", "if", "(", "splittedObject", ".", "length", ">", "4", ")", "{", "final", "Polygon", "polygon", "=", "Polygon", ".", "parsePoints", "(", "objectAsString", ",", "0.003", ")", ";", "findEdgesInShape", "(", "blockArea", ".", "blockedEdges", ",", "polygon", ",", "filter", ")", ";", "}", "else", "if", "(", "splittedObject", ".", "length", "==", "4", ")", "{", "final", "BBox", "bbox", "=", "BBox", ".", "parseTwoPoints", "(", "objectAsString", ")", ";", "if", "(", "bbox", ".", "calculateArea", "(", ")", ">", "useEdgeIdsUntilAreaSize", ")", "blockArea", ".", "add", "(", "bbox", ")", ";", "else", "findEdgesInShape", "(", "blockArea", ".", "blockedEdges", ",", "bbox", ",", "filter", ")", ";", "}", "else", "if", "(", "splittedObject", ".", "length", "==", "3", ")", "{", "double", "lat", "=", "Double", ".", "parseDouble", "(", "splittedObject", "[", "0", "]", ")", ";", "double", "lon", "=", "Double", ".", "parseDouble", "(", "splittedObject", "[", "1", "]", ")", ";", "int", "radius", "=", "Integer", ".", "parseInt", "(", "splittedObject", "[", "2", "]", ")", ";", "Circle", "circle", "=", "new", "Circle", "(", "lat", ",", "lon", ",", "radius", ")", ";", "if", "(", "circle", ".", "calculateArea", "(", ")", ">", "useEdgeIdsUntilAreaSize", ")", "{", "blockArea", ".", "add", "(", "circle", ")", ";", "}", "else", "{", "findEdgesInShape", "(", "blockArea", ".", "blockedEdges", ",", "circle", ",", "filter", ")", ";", "}", "}", "else", "if", "(", "splittedObject", ".", "length", "==", "2", ")", "{", "double", "lat", "=", "Double", ".", "parseDouble", "(", "splittedObject", "[", "0", "]", ")", ";", "double", "lon", "=", "Double", ".", "parseDouble", "(", "splittedObject", "[", "1", "]", ")", ";", "findClosestEdge", "(", "blockArea", ".", "blockedEdges", ",", "lat", ",", "lon", ",", "filter", ")", ";", "}", "else", "{", "throw", "new", "IllegalArgumentException", "(", "objectAsString", "+", "\" at index \"", "+", "i", "+", "\" need to be defined as lat,lon \"", "+", "\"or as a circle lat,lon,radius or rectangular lat1,lon1,lat2,lon2\"", ")", ";", "}", "}", "}", "return", "blockArea", ";", "}" ]
This method reads the blockAreaString and creates a Collection of Shapes or a set of found edges if area is small enough. @param useEdgeIdsUntilAreaSize until the specified area (specified in m²) use the findEdgesInShape method
[ "This", "method", "reads", "the", "blockAreaString", "and", "creates", "a", "Collection", "of", "Shapes", "or", "a", "set", "of", "found", "edges", "if", "area", "is", "small", "enough", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/storage/GraphEdgeIdFinder.java#L142-L183
21,192
graphhopper/graphhopper
core/src/main/java/com/graphhopper/routing/util/spatialrules/SpatialRuleLookupArray.java
SpatialRuleLookupArray.isBorderTile
private boolean isBorderTile(int xIndex, int yIndex, int ruleIndex) { for (int i = -1; i < 2; i++) { for (int j = -1; j < 2; j++) { if (i != xIndex && j != yIndex) if (ruleIndex != getRuleContainerIndex(i, j)) return true; } } return false; }
java
private boolean isBorderTile(int xIndex, int yIndex, int ruleIndex) { for (int i = -1; i < 2; i++) { for (int j = -1; j < 2; j++) { if (i != xIndex && j != yIndex) if (ruleIndex != getRuleContainerIndex(i, j)) return true; } } return false; }
[ "private", "boolean", "isBorderTile", "(", "int", "xIndex", ",", "int", "yIndex", ",", "int", "ruleIndex", ")", "{", "for", "(", "int", "i", "=", "-", "1", ";", "i", "<", "2", ";", "i", "++", ")", "{", "for", "(", "int", "j", "=", "-", "1", ";", "j", "<", "2", ";", "j", "++", ")", "{", "if", "(", "i", "!=", "xIndex", "&&", "j", "!=", "yIndex", ")", "if", "(", "ruleIndex", "!=", "getRuleContainerIndex", "(", "i", ",", "j", ")", ")", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Might fail for small holes that do not occur in the array
[ "Might", "fail", "for", "small", "holes", "that", "do", "not", "occur", "in", "the", "array" ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/util/spatialrules/SpatialRuleLookupArray.java#L139-L148
21,193
graphhopper/graphhopper
core/src/main/java/com/graphhopper/routing/util/spatialrules/SpatialRuleLookupArray.java
SpatialRuleLookupArray.addRuleContainer
private int addRuleContainer(SpatialRuleContainer container) { int newIndex = this.ruleContainers.indexOf(container); if (newIndex >= 0) return newIndex; newIndex = ruleContainers.size(); if (newIndex >= 255) throw new IllegalStateException("No more spatial rule container fit into this lookup as 255 combination of ruleContainers reached"); this.ruleContainers.add(container); return newIndex; }
java
private int addRuleContainer(SpatialRuleContainer container) { int newIndex = this.ruleContainers.indexOf(container); if (newIndex >= 0) return newIndex; newIndex = ruleContainers.size(); if (newIndex >= 255) throw new IllegalStateException("No more spatial rule container fit into this lookup as 255 combination of ruleContainers reached"); this.ruleContainers.add(container); return newIndex; }
[ "private", "int", "addRuleContainer", "(", "SpatialRuleContainer", "container", ")", "{", "int", "newIndex", "=", "this", ".", "ruleContainers", ".", "indexOf", "(", "container", ")", ";", "if", "(", "newIndex", ">=", "0", ")", "return", "newIndex", ";", "newIndex", "=", "ruleContainers", ".", "size", "(", ")", ";", "if", "(", "newIndex", ">=", "255", ")", "throw", "new", "IllegalStateException", "(", "\"No more spatial rule container fit into this lookup as 255 combination of ruleContainers reached\"", ")", ";", "this", ".", "ruleContainers", ".", "add", "(", "container", ")", ";", "return", "newIndex", ";", "}" ]
This method adds the container if no such rule container exists in this lookup and returns the index otherwise.
[ "This", "method", "adds", "the", "container", "if", "no", "such", "rule", "container", "exists", "in", "this", "lookup", "and", "returns", "the", "index", "otherwise", "." ]
c235e306e6e823043cadcc41ead0e685bdebf737
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/util/spatialrules/SpatialRuleLookupArray.java#L228-L239
21,194
rubenlagus/TelegramBots
telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/db/MapDBContext.java
MapDBContext.onlineInstance
public static DBContext onlineInstance(String name) { DB db = DBMaker .fileDB(name) .fileMmapEnableIfSupported() .closeOnJvmShutdown() .transactionEnable() .make(); return new MapDBContext(db); }
java
public static DBContext onlineInstance(String name) { DB db = DBMaker .fileDB(name) .fileMmapEnableIfSupported() .closeOnJvmShutdown() .transactionEnable() .make(); return new MapDBContext(db); }
[ "public", "static", "DBContext", "onlineInstance", "(", "String", "name", ")", "{", "DB", "db", "=", "DBMaker", ".", "fileDB", "(", "name", ")", ".", "fileMmapEnableIfSupported", "(", ")", ".", "closeOnJvmShutdown", "(", ")", ".", "transactionEnable", "(", ")", ".", "make", "(", ")", ";", "return", "new", "MapDBContext", "(", "db", ")", ";", "}" ]
This DB returned by this method does not trigger deletion on JVM shutdown. @param name name of the DB file @return an online instance of {@link MapDBContext}
[ "This", "DB", "returned", "by", "this", "method", "does", "not", "trigger", "deletion", "on", "JVM", "shutdown", "." ]
d62354915d7664597a40fd9858f16bce67ef1478
https://github.com/rubenlagus/TelegramBots/blob/d62354915d7664597a40fd9858f16bce67ef1478/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/db/MapDBContext.java#L52-L61
21,195
rubenlagus/TelegramBots
telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/db/MapDBContext.java
MapDBContext.offlineInstance
public static DBContext offlineInstance(String name) { DB db = DBMaker .fileDB(name) .fileMmapEnableIfSupported() .closeOnJvmShutdown() .cleanerHackEnable() .transactionEnable() .fileDeleteAfterClose() .make(); return new MapDBContext(db); }
java
public static DBContext offlineInstance(String name) { DB db = DBMaker .fileDB(name) .fileMmapEnableIfSupported() .closeOnJvmShutdown() .cleanerHackEnable() .transactionEnable() .fileDeleteAfterClose() .make(); return new MapDBContext(db); }
[ "public", "static", "DBContext", "offlineInstance", "(", "String", "name", ")", "{", "DB", "db", "=", "DBMaker", ".", "fileDB", "(", "name", ")", ".", "fileMmapEnableIfSupported", "(", ")", ".", "closeOnJvmShutdown", "(", ")", ".", "cleanerHackEnable", "(", ")", ".", "transactionEnable", "(", ")", ".", "fileDeleteAfterClose", "(", ")", ".", "make", "(", ")", ";", "return", "new", "MapDBContext", "(", "db", ")", ";", "}" ]
This DB returned by this method gets deleted on JVM shutdown. @param name name of the DB file @return an offline instance of {@link MapDBContext}
[ "This", "DB", "returned", "by", "this", "method", "gets", "deleted", "on", "JVM", "shutdown", "." ]
d62354915d7664597a40fd9858f16bce67ef1478
https://github.com/rubenlagus/TelegramBots/blob/d62354915d7664597a40fd9858f16bce67ef1478/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/db/MapDBContext.java#L69-L80
21,196
rubenlagus/TelegramBots
telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/TelegramBotsApi.java
TelegramBotsApi.registerBot
public BotSession registerBot(LongPollingBot bot) throws TelegramApiRequestException { bot.clearWebhook(); BotSession session = ApiContext.getInstance(BotSession.class); session.setToken(bot.getBotToken()); session.setOptions(bot.getOptions()); session.setCallback(bot); session.start(); return session; }
java
public BotSession registerBot(LongPollingBot bot) throws TelegramApiRequestException { bot.clearWebhook(); BotSession session = ApiContext.getInstance(BotSession.class); session.setToken(bot.getBotToken()); session.setOptions(bot.getOptions()); session.setCallback(bot); session.start(); return session; }
[ "public", "BotSession", "registerBot", "(", "LongPollingBot", "bot", ")", "throws", "TelegramApiRequestException", "{", "bot", ".", "clearWebhook", "(", ")", ";", "BotSession", "session", "=", "ApiContext", ".", "getInstance", "(", "BotSession", ".", "class", ")", ";", "session", ".", "setToken", "(", "bot", ".", "getBotToken", "(", ")", ")", ";", "session", ".", "setOptions", "(", "bot", ".", "getOptions", "(", ")", ")", ";", "session", ".", "setCallback", "(", "bot", ")", ";", "session", ".", "start", "(", ")", ";", "return", "session", ";", "}" ]
Register a bot. The Bot Session is started immediately, and may be disconnected by calling close. @param bot the bot to register
[ "Register", "a", "bot", ".", "The", "Bot", "Session", "is", "started", "immediately", "and", "may", "be", "disconnected", "by", "calling", "close", "." ]
d62354915d7664597a40fd9858f16bce67ef1478
https://github.com/rubenlagus/TelegramBots/blob/d62354915d7664597a40fd9858f16bce67ef1478/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/TelegramBotsApi.java#L119-L127
21,197
rubenlagus/TelegramBots
telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/TelegramBotsApi.java
TelegramBotsApi.registerBot
public void registerBot(WebhookBot bot) throws TelegramApiRequestException { if (useWebhook) { webhook.registerWebhook(bot); bot.setWebhook(externalUrl + bot.getBotPath(), pathToCertificate); } }
java
public void registerBot(WebhookBot bot) throws TelegramApiRequestException { if (useWebhook) { webhook.registerWebhook(bot); bot.setWebhook(externalUrl + bot.getBotPath(), pathToCertificate); } }
[ "public", "void", "registerBot", "(", "WebhookBot", "bot", ")", "throws", "TelegramApiRequestException", "{", "if", "(", "useWebhook", ")", "{", "webhook", ".", "registerWebhook", "(", "bot", ")", ";", "bot", ".", "setWebhook", "(", "externalUrl", "+", "bot", ".", "getBotPath", "(", ")", ",", "pathToCertificate", ")", ";", "}", "}" ]
Register a bot in the api that will receive updates using webhook method @param bot Bot to register
[ "Register", "a", "bot", "in", "the", "api", "that", "will", "receive", "updates", "using", "webhook", "method" ]
d62354915d7664597a40fd9858f16bce67ef1478
https://github.com/rubenlagus/TelegramBots/blob/d62354915d7664597a40fd9858f16bce67ef1478/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/TelegramBotsApi.java#L133-L138
21,198
rubenlagus/TelegramBots
telegrambots-extensions/src/main/java/org/telegram/telegrambots/extensions/bots/commandbot/commands/CommandRegistry.java
CommandRegistry.executeCommand
public final boolean executeCommand(AbsSender absSender, Message message) { if (message.hasText()) { String text = message.getText(); if (text.startsWith(BotCommand.COMMAND_INIT_CHARACTER)) { String commandMessage = text.substring(1); String[] commandSplit = commandMessage.split(BotCommand.COMMAND_PARAMETER_SEPARATOR_REGEXP); String command = removeUsernameFromCommandIfNeeded(commandSplit[0]); if (commandRegistryMap.containsKey(command)) { String[] parameters = Arrays.copyOfRange(commandSplit, 1, commandSplit.length); commandRegistryMap.get(command).processMessage(absSender, message, parameters); return true; } else if (defaultConsumer != null) { defaultConsumer.accept(absSender, message); return true; } } } return false; }
java
public final boolean executeCommand(AbsSender absSender, Message message) { if (message.hasText()) { String text = message.getText(); if (text.startsWith(BotCommand.COMMAND_INIT_CHARACTER)) { String commandMessage = text.substring(1); String[] commandSplit = commandMessage.split(BotCommand.COMMAND_PARAMETER_SEPARATOR_REGEXP); String command = removeUsernameFromCommandIfNeeded(commandSplit[0]); if (commandRegistryMap.containsKey(command)) { String[] parameters = Arrays.copyOfRange(commandSplit, 1, commandSplit.length); commandRegistryMap.get(command).processMessage(absSender, message, parameters); return true; } else if (defaultConsumer != null) { defaultConsumer.accept(absSender, message); return true; } } } return false; }
[ "public", "final", "boolean", "executeCommand", "(", "AbsSender", "absSender", ",", "Message", "message", ")", "{", "if", "(", "message", ".", "hasText", "(", ")", ")", "{", "String", "text", "=", "message", ".", "getText", "(", ")", ";", "if", "(", "text", ".", "startsWith", "(", "BotCommand", ".", "COMMAND_INIT_CHARACTER", ")", ")", "{", "String", "commandMessage", "=", "text", ".", "substring", "(", "1", ")", ";", "String", "[", "]", "commandSplit", "=", "commandMessage", ".", "split", "(", "BotCommand", ".", "COMMAND_PARAMETER_SEPARATOR_REGEXP", ")", ";", "String", "command", "=", "removeUsernameFromCommandIfNeeded", "(", "commandSplit", "[", "0", "]", ")", ";", "if", "(", "commandRegistryMap", ".", "containsKey", "(", "command", ")", ")", "{", "String", "[", "]", "parameters", "=", "Arrays", ".", "copyOfRange", "(", "commandSplit", ",", "1", ",", "commandSplit", ".", "length", ")", ";", "commandRegistryMap", ".", "get", "(", "command", ")", ".", "processMessage", "(", "absSender", ",", "message", ",", "parameters", ")", ";", "return", "true", ";", "}", "else", "if", "(", "defaultConsumer", "!=", "null", ")", "{", "defaultConsumer", ".", "accept", "(", "absSender", ",", "message", ")", ";", "return", "true", ";", "}", "}", "}", "return", "false", ";", "}" ]
Executes a command action if the command is registered. @note If the command is not registered and there is a default consumer, that action will be performed @param absSender absSender @param message input message @return True if a command or default action is executed, false otherwise
[ "Executes", "a", "command", "action", "if", "the", "command", "is", "registered", "." ]
d62354915d7664597a40fd9858f16bce67ef1478
https://github.com/rubenlagus/TelegramBots/blob/d62354915d7664597a40fd9858f16bce67ef1478/telegrambots-extensions/src/main/java/org/telegram/telegrambots/extensions/bots/commandbot/commands/CommandRegistry.java#L95-L115
21,199
rubenlagus/TelegramBots
telegrambots-extensions/src/main/java/org/telegram/telegrambots/extensions/bots/commandbot/commands/DefaultBotCommand.java
DefaultBotCommand.processMessage
@Override public void processMessage(AbsSender absSender, Message message, String[] arguments) { execute(absSender, message.getFrom(), message.getChat(), message.getMessageId(), arguments); }
java
@Override public void processMessage(AbsSender absSender, Message message, String[] arguments) { execute(absSender, message.getFrom(), message.getChat(), message.getMessageId(), arguments); }
[ "@", "Override", "public", "void", "processMessage", "(", "AbsSender", "absSender", ",", "Message", "message", ",", "String", "[", "]", "arguments", ")", "{", "execute", "(", "absSender", ",", "message", ".", "getFrom", "(", ")", ",", "message", ".", "getChat", "(", ")", ",", "message", ".", "getMessageId", "(", ")", ",", "arguments", ")", ";", "}" ]
Process the message and execute the command @param absSender absSender to send messages over @param message the message to process @param arguments passed arguments
[ "Process", "the", "message", "and", "execute", "the", "command" ]
d62354915d7664597a40fd9858f16bce67ef1478
https://github.com/rubenlagus/TelegramBots/blob/d62354915d7664597a40fd9858f16bce67ef1478/telegrambots-extensions/src/main/java/org/telegram/telegrambots/extensions/bots/commandbot/commands/DefaultBotCommand.java#L33-L36