idx
int64
0
41.2k
question
stringlengths
74
4.04k
target
stringlengths
7
750
40,300
public void registerTemplateEngine ( Class < ? extends TemplateEngine > engineClass ) { if ( templateEngine != null ) { log . debug ( "Template engine already registered, ignoring '{}'" , engineClass . getName ( ) ) ; return ; } try { TemplateEngine engine = engineClass . newInstance ( ) ; setTemplateEngine ( engine ) ; } catch ( Exception e ) { throw new PippoRuntimeException ( e , "Failed to instantiate '{}'" , engineClass . getName ( ) ) ; } }
Registers a template engine if no other engine has been registered .
40,301
public static String getPippoVersion ( ) { String pippoVersionPropertyKey = "pippo.version" ; String pippoVersion ; try { Properties prop = new Properties ( ) ; URL url = ClasspathUtils . locateOnClasspath ( PippoConstants . LOCATION_OF_PIPPO_BUILTIN_PROPERTIES ) ; InputStream stream = url . openStream ( ) ; prop . load ( stream ) ; pippoVersion = prop . getProperty ( pippoVersionPropertyKey ) ; } catch ( Exception e ) { throw new PippoRuntimeException ( "Something is wrong with your build. Cannot find resource {}" , PippoConstants . LOCATION_OF_PIPPO_BUILTIN_PROPERTIES ) ; } return pippoVersion ; }
Simply reads a property resource file that contains the version of this Pippo build . Helps to identify the Pippo version currently running .
40,302
public Object layout ( Map model , String templateName , boolean inheritModel ) throws IOException , ClassNotFoundException { Map submodel = inheritModel ? forkModel ( model ) : model ; URL resource = engine . resolveTemplate ( templateName ) ; PippoGroovyTemplate template = ( PippoGroovyTemplate ) engine . createTypeCheckedModelTemplate ( resource , modelTypes ) . make ( submodel ) ; template . setup ( languages , messages , router ) ; template . writeTo ( getOut ( ) ) ; return this ; }
Imports a template and renders it using the specified model allowing fine grained composition of templates and layouting . This works similarily to a template include but allows a distinct model to be used . If the layout inherits from the parent model a new model is created with the values from the parent model eventually overriden with those provided specifically for this layout .
40,303
public static EmbeddedCacheManager create ( long idleTime ) { Configuration configuration = new ConfigurationBuilder ( ) . expiration ( ) . maxIdle ( idleTime , TimeUnit . SECONDS ) . build ( ) ; return new DefaultCacheManager ( configuration ) ; }
Create cache manager with custom idle time .
40,304
public static EmbeddedCacheManager create ( String file ) { try { return new DefaultCacheManager ( file ) ; } catch ( IOException ex ) { log . error ( "" , ex ) ; throw new PippoRuntimeException ( ex ) ; } }
Create cache manager with custom config file .
40,305
public Response bind ( String name , Object model ) { getLocals ( ) . put ( name , model ) ; return this ; }
Binds an object to the response .
40,306
public Response removeCookie ( String name ) { Cookie cookie = new Cookie ( name , "" ) ; cookie . setSecure ( true ) ; cookie . setMaxAge ( 0 ) ; addCookie ( cookie ) ; return this ; }
Removes the specified cookie by name .
40,307
public Response noCache ( ) { checkCommitted ( ) ; header ( HttpConstants . Header . CACHE_CONTROL , "no-store, no-cache, must-revalidate" ) ; header ( HttpConstants . Header . CACHE_CONTROL , "post-check=0, pre-check=0" ) ; header ( HttpConstants . Header . PRAGMA , "no-cache" ) ; httpServletResponse . setDateHeader ( "Expires" , 0 ) ; return this ; }
Sets this response as not cacheable .
40,308
public String getContentType ( ) { String contentType = getHeader ( HttpConstants . Header . CONTENT_TYPE ) ; if ( contentType == null ) { contentType = httpServletResponse . getContentType ( ) ; } return contentType ; }
Returns the content type of the response .
40,309
public Response contentType ( String contentType ) { checkCommitted ( ) ; header ( HttpConstants . Header . CONTENT_TYPE , contentType ) ; httpServletResponse . setContentType ( contentType ) ; return this ; }
Sets the content type of the response .
40,310
public static String getHashSHA256 ( String text ) { byte [ ] bytes = text . getBytes ( StandardCharsets . ISO_8859_1 ) ; return getHashSHA256 ( bytes ) ; }
Calculates the SHA256 hash of the string .
40,311
public static String getHashSHA1 ( String text ) { byte [ ] bytes = text . getBytes ( StandardCharsets . ISO_8859_1 ) ; return getHashSHA1 ( bytes ) ; }
Calculates the SHA1 hash of the string .
40,312
public static String getHashMD5 ( String text ) { byte [ ] bytes = text . getBytes ( StandardCharsets . ISO_8859_1 ) ; return getHashMD5 ( bytes ) ; }
Calculates the MD5 hash of the string .
40,313
public static String getHashMD5 ( byte [ ] bytes ) { try { MessageDigest md = MessageDigest . getInstance ( "MD5" ) ; md . update ( bytes , 0 , bytes . length ) ; byte [ ] digest = md . digest ( ) ; return toHex ( digest ) ; } catch ( NoSuchAlgorithmException t ) { throw new RuntimeException ( t ) ; } }
Calculates the MD5 hash of the byte array .
40,314
public static String generateSecretKey ( ) { return hmacDigest ( UUID . randomUUID ( ) . toString ( ) , UUID . randomUUID ( ) . toString ( ) , HMAC_SHA256 ) ; }
Generates a random secret key .
40,315
public static MongoClient create ( final PippoSettings settings ) { String host = settings . getString ( HOST , "mongodb://localhost:27017" ) ; return create ( host ) ; }
Create a MongoDB client with pippo settings .
40,316
public static MongoClient create ( String hosts ) { MongoClientURI connectionString = new MongoClientURI ( hosts ) ; return new MongoClient ( connectionString ) ; }
Create a MongoDB client with params .
40,317
protected void onPreDispatch ( Request request , Response response ) { application . getRoutePreDispatchListeners ( ) . onPreDispatch ( request , response ) ; }
Executes onPreDispatch of registered route pre - dispatch listeners .
40,318
protected void onRouteDispatch ( Request request , Response response ) { final String requestPath = request . getPath ( ) ; final String requestMethod = request . getMethod ( ) ; if ( shouldIgnorePath ( requestPath ) ) { RouteContext routeContext = routeContextFactory . createRouteContext ( application , request , response , noMatches ) ; ROUTE_CONTEXT_THREAD_LOCAL . set ( routeContext ) ; errorHandler . handle ( HttpServletResponse . SC_NOT_FOUND , routeContext ) ; ROUTE_CONTEXT_THREAD_LOCAL . remove ( ) ; log . debug ( "Returned status code {} for {} '{}' (IGNORED)" , response . getStatus ( ) , requestMethod , requestPath ) ; return ; } List < RouteMatch > routeMatches = router . findRoutes ( requestMethod , requestPath ) ; RouteContext routeContext = routeContextFactory . createRouteContext ( application , request , response , routeMatches ) ; ROUTE_CONTEXT_THREAD_LOCAL . set ( routeContext ) ; try { if ( routeMatches . isEmpty ( ) ) { if ( notFoundRouteHandler != null ) { notFoundRouteHandler . handle ( routeContext ) ; } else { errorHandler . handle ( HttpConstants . StatusCode . NOT_FOUND , routeContext ) ; } } else { processFlash ( routeContext ) ; } routeContext . next ( ) ; if ( ! response . isCommitted ( ) ) { if ( response . getStatus ( ) == 0 ) { log . debug ( "Status code not set for {} '{}'" , requestMethod , requestPath ) ; response . notFound ( ) ; } log . debug ( "Auto-committing response for {} '{}'" , requestMethod , requestPath ) ; if ( response . getStatus ( ) >= HttpServletResponse . SC_BAD_REQUEST ) { errorHandler . handle ( response . getStatus ( ) , routeContext ) ; } else { response . commit ( ) ; } } } catch ( Exception e ) { errorHandler . handle ( e , routeContext ) ; } finally { routeContext . runFinallyRoutes ( ) ; log . debug ( "Returned status code {} for {} '{}'" , response . getStatus ( ) , requestMethod , requestPath ) ; ROUTE_CONTEXT_THREAD_LOCAL . remove ( ) ; } }
onRouteDispatch is the front - line for Route processing .
40,319
protected void onPostDispatch ( Request request , Response response ) { application . getRoutePostDispatchListeners ( ) . onPostDispatch ( request , response ) ; }
Executes onPostDispatch of registered route post - dispatch listeners .
40,320
private void processFlash ( RouteContext routeContext ) { Flash flash = null ; if ( routeContext . hasSession ( ) ) { flash = routeContext . removeSession ( "flash" ) ; routeContext . setSession ( "flash" , new Flash ( ) ) ; } if ( flash == null ) { flash = new Flash ( ) ; } routeContext . setLocal ( "flash" , flash ) ; }
Removes a Flash instance from the session binds it to the RouteContext and creates a new Flash instance .
40,321
protected Map < String , Object > prepareTemplateBindings ( int statusCode , RouteContext routeContext ) { Map < String , Object > locals = new LinkedHashMap < > ( ) ; locals . put ( "applicationName" , application . getApplicationName ( ) ) ; locals . put ( "applicationVersion" , application . getApplicationVersion ( ) ) ; locals . put ( "runtimeMode" , application . getPippoSettings ( ) . getRuntimeMode ( ) . toString ( ) ) ; if ( application . getPippoSettings ( ) . isDev ( ) ) { locals . put ( "routes" , application . getRouter ( ) . getRoutes ( ) ) ; } return locals ; }
Get the template bindings for the error response .
40,322
protected Error prepareError ( int statusCode , RouteContext routeContext ) { String messageKey = "pippo.statusCode" + statusCode ; Error error = new Error ( ) ; error . setStatusCode ( statusCode ) ; error . setStatusMessage ( application . getMessages ( ) . get ( messageKey , routeContext ) ) ; error . setRequestMethod ( routeContext . getRequestMethod ( ) ) ; error . setRequestUri ( routeContext . getRequestUri ( ) ) ; error . setStacktrace ( routeContext . getLocal ( STACKTRACE ) ) ; error . setMessage ( routeContext . getLocal ( MESSAGE ) ) ; return error ; }
Prepares an Error instance for the error response .
40,323
public String getParameterName ( ) { if ( parameterName == null ) { Parameter parameter = getParameter ( ) ; if ( parameter . isNamePresent ( ) ) { parameterName = parameter . getName ( ) ; } } return parameterName ; }
Try looking for the parameter name in the compiled . class file .
40,324
private Map < String , Properties > loadRegisteredMessageResources ( ) { Map < String , Properties > internalMessages = loadRegisteredMessageResources ( "pippo/pippo-messages%s.properties" ) ; Map < String , Properties > applicationMessages = loadRegisteredMessageResources ( "conf/messages%s.properties" ) ; Map < String , Properties > allMessages = new TreeMap < > ( ) ; Set < String > merged = new HashSet < > ( ) ; for ( Map . Entry < String , Properties > entry : internalMessages . entrySet ( ) ) { String language = entry . getKey ( ) ; Properties messages = entry . getValue ( ) ; allMessages . put ( language , messages ) ; if ( applicationMessages . containsKey ( language ) ) { messages . putAll ( applicationMessages . get ( language ) ) ; } merged . add ( language ) ; } Set < String > unmerged = new HashSet < > ( applicationMessages . keySet ( ) ) ; unmerged . removeAll ( merged ) ; for ( String language : unmerged ) { allMessages . put ( language , applicationMessages . get ( language ) ) ; } return allMessages ; }
Loads Pippo internal messages & application messages and returns the merger .
40,325
private Map < String , Properties > loadRegisteredMessageResources ( String name ) { Map < String , Properties > messageResources = new TreeMap < > ( ) ; Properties defaultMessages = loadMessages ( String . format ( name , "" ) ) ; if ( defaultMessages == null ) { log . error ( "Could not locate the default messages resource '{}', please create it." , String . format ( name , "" ) ) ; } else { messageResources . put ( "" , defaultMessages ) ; } List < String > registeredLanguages = languages . getRegisteredLanguages ( ) ; for ( String language : registeredLanguages ) { Properties messages = loadMessages ( String . format ( name , "_" + language ) ) ; Properties messagesLangOnly = null ; String langComponent = languages . getLanguageComponent ( language ) ; if ( ! langComponent . equals ( language ) ) { messagesLangOnly = messageResources . get ( langComponent ) ; if ( messagesLangOnly == null ) { messagesLangOnly = loadMessages ( String . format ( name , "_" + langComponent ) ) ; } } if ( messages == null ) { log . error ( "Could not locate the '{}' messages resource '{}' specified in '{}'." , language , String . format ( name , "_" + language ) , PippoConstants . SETTING_APPLICATION_LANGUAGES ) ; } else { Properties compositeMessages = new Properties ( defaultMessages ) ; if ( messagesLangOnly != null ) { compositeMessages . putAll ( messagesLangOnly ) ; if ( ! messageResources . containsKey ( langComponent ) ) { Properties langResources = new Properties ( ) ; langResources . putAll ( compositeMessages ) ; messageResources . put ( langComponent , langResources ) ; } } compositeMessages . putAll ( messages ) ; messageResources . put ( language . toLowerCase ( ) , compositeMessages ) ; } } return Collections . unmodifiableMap ( messageResources ) ; }
Loads all registered message resources .
40,326
private Properties loadMessages ( String fileOrUrl ) { URL url = ClasspathUtils . locateOnClasspath ( fileOrUrl ) ; if ( url != null ) { try ( InputStreamReader reader = new InputStreamReader ( url . openStream ( ) , StandardCharsets . UTF_8 ) ) { Properties messages = new Properties ( ) ; messages . load ( reader ) ; return messages ; } catch ( IOException e ) { log . error ( "Failed to load {}" , fileOrUrl , e ) ; } } return null ; }
Attempts to load a message resource .
40,327
public String getSubmittedFileName ( ) { if ( submittedFileName == null ) { String header = part . getHeader ( HttpConstants . Header . CONTENT_DISPOSITION ) ; if ( header == null ) { return null ; } for ( String headerPart : header . split ( ";" ) ) { if ( headerPart . trim ( ) . startsWith ( "filename" ) ) { submittedFileName = headerPart . substring ( headerPart . indexOf ( '=' ) + 1 ) . trim ( ) . replace ( "\"" , "" ) ; break ; } } } return submittedFileName ; }
Retrieves the filename specified by the client .
40,328
public void write ( File file ) throws IOException { try ( InputStream inputStream = getInputStream ( ) ) { IoUtils . copy ( inputStream , file ) ; } }
Saves this file item to a given file on the server side .
40,329
protected Cache < String , SessionData > create ( String name , long idleTime ) { return Caching . getCachingProvider ( ) . getCacheManager ( ) . createCache ( name , new MutableConfiguration < String , SessionData > ( ) . setTypes ( String . class , SessionData . class ) . setExpiryPolicyFactory ( TouchedExpiryPolicy . factoryOf ( new Duration ( TimeUnit . SECONDS , idleTime ) ) ) ) ; }
Create a cache with name and expiry policy with idle time .
40,330
public static String getPrettyPath ( List < Puzzle > path , int size ) { StringBuffer output = new StringBuffer ( ) ; for ( int y = 0 ; y < size ; y ++ ) { String row = "" ; for ( Puzzle state : path ) { int [ ] [ ] board = state . getMatrixBoard ( ) ; row += "| " ; for ( int x = 0 ; x < size ; x ++ ) { row += board [ y ] [ x ] + " " ; } row += "| " ; } row += "\n" ; output . append ( row ) ; } return output . toString ( ) ; }
Prints a search path in a readable form .
40,331
public static Maze2D read ( File file ) throws IOException { ArrayList < String > array = new ArrayList < String > ( ) ; BufferedReader br = new BufferedReader ( new FileReader ( file ) ) ; String line ; while ( ( line = br . readLine ( ) ) != null ) { array . add ( line ) ; } br . close ( ) ; return new Maze2D ( ( String [ ] ) array . toArray ( ) ) ; }
Read a maze from a file in plain text .
40,332
public void updateLocation ( Point p , Symbol symbol ) { int row = p . y ; int column = p . x ; this . maze [ row ] [ column ] = symbol . value ( ) ; }
Replace a tile in the maze
40,333
public void updateRectangle ( Point a , Point b , Symbol symbol ) { int xfrom = ( a . x < b . x ) ? a . x : b . x ; int xto = ( a . x > b . x ) ? a . x : b . x ; int yfrom = ( a . y < b . y ) ? a . y : b . y ; int yto = ( a . y > b . y ) ? a . y : b . y ; for ( int x = xfrom ; x <= xto ; x ++ ) { for ( int y = yfrom ; y <= yto ; y ++ ) { updateLocation ( new Point ( x , y ) , symbol ) ; } } }
Replace all tiles inside the rectangle with the provided symbol .
40,334
public void putObstacleRectangle ( Point a , Point b ) { updateRectangle ( a , b , Symbol . OCCUPIED ) ; }
Fill a rectangle defined by points a and b with occupied tiles .
40,335
public void removeObstacleRectangle ( Point a , Point b ) { updateRectangle ( a , b , Symbol . EMPTY ) ; }
Fill a rectangle defined by points a and b with empty tiles .
40,336
public String getReplacedMazeString ( List < Map < Point , Character > > replacements ) { String [ ] stringMaze = toStringArray ( ) ; for ( Map < Point , Character > replacement : replacements ) { for ( Point p : replacement . keySet ( ) ) { int row = p . y ; int column = p . x ; char c = stringMaze [ row ] . charAt ( column ) ; if ( c != Symbol . START . value ( ) && c != Symbol . GOAL . value ( ) ) { stringMaze [ row ] = replaceChar ( stringMaze [ row ] , column , replacement . get ( p ) ) ; } } } String output = "" ; for ( String line : stringMaze ) { output += String . format ( "%s%n" , line ) ; } return output ; }
Generates a string representation of this maze but replacing all the indicated points with the characters provided .
40,337
public String getStringMazeFilled ( Collection < Point > points , char symbol ) { Map < Point , Character > replacements = new HashMap < Point , Character > ( ) ; for ( Point p : points ) { replacements . put ( p , symbol ) ; } return getReplacedMazeString ( Collections . singletonList ( replacements ) ) ; }
Generates a string representation of this maze with the indicated points replaced with the symbol provided .
40,338
public boolean pointInBounds ( Point loc ) { return loc . x >= 0 && loc . x < this . columns && loc . y >= 0 && loc . y < this . rows ; }
Check if the provided point is in the maze bounds or outside .
40,339
public Collection < Point > validLocationsFrom ( Point loc ) { Collection < Point > validMoves = new HashSet < Point > ( ) ; for ( int row = - 1 ; row <= 1 ; row ++ ) { for ( int column = - 1 ; column <= 1 ; column ++ ) { try { if ( isFree ( new Point ( loc . x + column , loc . y + row ) ) ) { validMoves . add ( new Point ( loc . x + column , loc . y + row ) ) ; } } catch ( ArrayIndexOutOfBoundsException ex ) { } } } validMoves . remove ( loc ) ; return validMoves ; }
Return all neighbor empty points from a specific location point .
40,340
public Set < Point > diff ( Maze2D to ) { char [ ] [ ] maze1 = this . getMazeCharArray ( ) ; char [ ] [ ] maze2 = to . getMazeCharArray ( ) ; Set < Point > differentLocations = new HashSet < Point > ( ) ; for ( int row = 0 ; row < this . rows ; row ++ ) { for ( int column = 0 ; column < this . columns ; column ++ ) { if ( maze1 [ row ] [ column ] != maze2 [ row ] [ column ] ) { differentLocations . add ( new Point ( column , row ) ) ; } } } return differentLocations ; }
Returns a set of points that are different with respect this maze . Both mazes must have same size .
40,341
public static Maze2D empty ( int size ) { char [ ] [ ] maze = new char [ size ] [ size ] ; for ( int i = 0 ; i < size ; i ++ ) { Arrays . fill ( maze [ i ] , Symbol . EMPTY . value ( ) ) ; } maze [ 0 ] [ 0 ] = Symbol . START . value ( ) ; maze [ size ] [ size ] = Symbol . GOAL . value ( ) ; return new Maze2D ( maze ) ; }
Generate an empty squared maze of the indicated size .
40,342
public Entry < T > enqueue ( T value , double priority ) { checkPriority ( priority ) ; Entry < T > result = new Entry < T > ( value , priority ) ; mMin = mergeLists ( mMin , result ) ; ++ mSize ; return result ; }
Inserts the specified element into the Fibonacci heap with the specified priority . Its priority must be a valid double so you cannot set the priority to NaN .
40,343
public static < T > FibonacciHeap < T > merge ( FibonacciHeap < T > one , FibonacciHeap < T > two ) { FibonacciHeap < T > result = new FibonacciHeap < T > ( ) ; result . mMin = mergeLists ( one . mMin , two . mMin ) ; result . mSize = one . mSize + two . mSize ; one . mSize = two . mSize = 0 ; one . mMin = null ; two . mMin = null ; return result ; }
Given two Fibonacci heaps returns a new Fibonacci heap that contains all of the elements of the two heaps . Each of the input heaps is destructively modified by having all its elements removed . You can continue to use those heaps but be aware that they will be empty after this call completes .
40,344
public Entry < T > dequeueMin ( ) { if ( isEmpty ( ) ) throw new NoSuchElementException ( "Heap is empty." ) ; -- mSize ; Entry < T > minElem = mMin ; if ( mMin . mNext == mMin ) { mMin = null ; } else { mMin . mPrev . mNext = mMin . mNext ; mMin . mNext . mPrev = mMin . mPrev ; mMin = mMin . mNext ; } if ( minElem . mChild != null ) { Entry < ? > curr = minElem . mChild ; do { curr . mParent = null ; curr = curr . mNext ; } while ( curr != minElem . mChild ) ; } mMin = mergeLists ( mMin , minElem . mChild ) ; if ( mMin == null ) return minElem ; List < Entry < T > > treeTable = new ArrayList < Entry < T > > ( ) ; List < Entry < T > > toVisit = new ArrayList < Entry < T > > ( ) ; for ( Entry < T > curr = mMin ; toVisit . isEmpty ( ) || toVisit . get ( 0 ) != curr ; curr = curr . mNext ) toVisit . add ( curr ) ; for ( Entry < T > curr : toVisit ) { while ( true ) { while ( curr . mDegree >= treeTable . size ( ) ) treeTable . add ( null ) ; if ( treeTable . get ( curr . mDegree ) == null ) { treeTable . set ( curr . mDegree , curr ) ; break ; } Entry < T > other = treeTable . get ( curr . mDegree ) ; treeTable . set ( curr . mDegree , null ) ; Entry < T > min = ( other . mPriority < curr . mPriority ) ? other : curr ; Entry < T > max = ( other . mPriority < curr . mPriority ) ? curr : other ; max . mNext . mPrev = max . mPrev ; max . mPrev . mNext = max . mNext ; max . mNext = max . mPrev = max ; min . mChild = mergeLists ( min . mChild , max ) ; max . mParent = min ; max . mIsMarked = false ; ++ min . mDegree ; curr = min ; } if ( curr . mPriority <= mMin . mPriority ) mMin = curr ; } return minElem ; }
Dequeues and returns the minimum element of the Fibonacci heap . If the heap is empty this throws a NoSuchElementException .
40,345
private void decreaseKeyUnchecked ( Entry < T > entry , double priority ) { entry . mPriority = priority ; if ( entry . mParent != null && entry . mPriority <= entry . mParent . mPriority ) cutNode ( entry ) ; if ( entry . mPriority <= mMin . mPriority ) mMin = entry ; }
Decreases the key of a node in the tree without doing any checking to ensure that the new priority is valid .
40,346
private void cutNode ( Entry < T > entry ) { entry . mIsMarked = false ; if ( entry . mParent == null ) return ; if ( entry . mNext != entry ) { entry . mNext . mPrev = entry . mPrev ; entry . mPrev . mNext = entry . mNext ; } if ( entry . mParent . mChild == entry ) { if ( entry . mNext != entry ) { entry . mParent . mChild = entry . mNext ; } else { entry . mParent . mChild = null ; } } -- entry . mParent . mDegree ; entry . mPrev = entry . mNext = entry ; mMin = mergeLists ( mMin , entry ) ; if ( entry . mParent . mIsMarked ) cutNode ( entry . mParent ) ; else entry . mParent . mIsMarked = true ; entry . mParent = null ; }
Cuts a node from its parent . If the parent was already marked recursively cuts that node from its parent as well .
40,347
public static ScalarOperation < Double > doubleMultiplicationOp ( ) { return new ScalarOperation < Double > ( new ScalarFunction < Double > ( ) { public Double scale ( Double a , double b ) { return a * b ; } } , 1d ) ; }
Builds the scaling operation for Doubles that is the multiplying operation for the factor .
40,348
public Iterable < N > expandTransitionsChanged ( N begin , Iterable < Transition < A , S > > transitions ) { Collection < N > nodes = new ArrayList < N > ( ) ; for ( Transition < A , S > transition : transitions ) { S state = transition . getState ( ) ; if ( ! state . equals ( begin . state ( ) ) ) { N node = this . visited . get ( state ) ; if ( node == null ) { node = nodeFactory . makeNode ( begin , transition ) ; visited . put ( state , node ) ; } updateInconsistent ( node , predecessorsMap ( transition . getState ( ) ) ) ; nodes . add ( node ) ; } } return nodes ; }
Generates an iterable list of nodes updated as inconsistent after applying the cost changes in the list of transitions passed as parameter .
40,349
private Map < Transition < A , S > , N > predecessorsMap ( S current ) { Map < Transition < A , S > , N > mapPredecessors = new HashMap < Transition < A , S > , N > ( ) ; for ( Transition < A , S > predecessor : predecessorFunction . transitionsFrom ( current ) ) { N predecessorNode = visited . get ( predecessor . getState ( ) ) ; if ( predecessorNode != null ) { mapPredecessors . put ( predecessor , predecessorNode ) ; } } return mapPredecessors ; }
Retrieves a map with the predecessors states and the node associated to each predecessor state .
40,350
public N makeNode ( N from , Transition < A , S > transition ) { return nodeFactory . makeNode ( from , transition ) ; }
Creates a new node from the parent and a transition calling the node factory .
40,351
public void updateKey ( N node ) { node . getKey ( ) . update ( node . getG ( ) , node . getV ( ) , heuristicFunction . estimate ( node . state ( ) ) , epsilon , add , scale ) ; }
Updating the priority of a node is required when changing the value of Epsilon .
40,352
private static Graph buildGraph ( ) { Graph g = new TinkerGraph ( ) ; Vertex v1 = g . addVertex ( "v1" ) ; Vertex v2 = g . addVertex ( "v2" ) ; Vertex v3 = g . addVertex ( "v3" ) ; Vertex v4 = g . addVertex ( "v4" ) ; Vertex v5 = g . addVertex ( "v5" ) ; Vertex v6 = g . addVertex ( "v6" ) ; Edge e1 = g . addEdge ( "e1" , v1 , v2 , "(7, 1)" ) ; e1 . setProperty ( "c1" , 7 ) ; e1 . setProperty ( "c2" , 1 ) ; Edge e2 = g . addEdge ( "e2" , v1 , v3 , "(1, 4)" ) ; e2 . setProperty ( "c1" , 1 ) ; e2 . setProperty ( "c2" , 4 ) ; Edge e3 = g . addEdge ( "e3" , v1 , v4 , "(2, 1)" ) ; e3 . setProperty ( "c1" , 2 ) ; e3 . setProperty ( "c2" , 1 ) ; Edge e4 = g . addEdge ( "e4" , v2 , v4 , "(1, 1)" ) ; e4 . setProperty ( "c1" , 1 ) ; e4 . setProperty ( "c2" , 1 ) ; Edge e5 = g . addEdge ( "e5" , v2 , v6 , "(2, 1)" ) ; e5 . setProperty ( "c1" , 2 ) ; e5 . setProperty ( "c2" , 1 ) ; Edge e6 = g . addEdge ( "e6" , v3 , v4 , "(1, 1)" ) ; e6 . setProperty ( "c1" , 1 ) ; e6 . setProperty ( "c2" , 1 ) ; Edge e7 = g . addEdge ( "e7" , v4 , v5 , "(3, 2)" ) ; e7 . setProperty ( "c1" , 3 ) ; e7 . setProperty ( "c2" , 2 ) ; Edge e8 = g . addEdge ( "e8" , v4 , v6 , "(4, 8)" ) ; e8 . setProperty ( "c1" , 4 ) ; e8 . setProperty ( "c2" , 8 ) ; Edge e9 = g . addEdge ( "e9" , v5 , v6 , "(1, 1)" ) ; e9 . setProperty ( "c1" , 1 ) ; e9 . setProperty ( "c2" , 1 ) ; return g ; }
Build an example graph to execute in this example .
40,353
public static < A , S > Transition < A , S > create ( S fromState , A action , S toState ) { return new Transition < A , S > ( fromState , action , toState ) ; }
Instantiates a transition specifying an action the origin and destination states .
40,354
public static < S > Transition < Void , S > create ( S fromState , S toState ) { return new Transition < Void , S > ( fromState , null , toState ) ; }
Offers a way to instantiate a transition without specifying an action but only the origin and destination states .
40,355
public static void printSearch ( Iterator < ? extends Node < ? , Point , ? > > it , Maze2D maze ) throws InterruptedException { Collection < Point > explored = new HashSet < Point > ( ) ; while ( it . hasNext ( ) ) { Node < ? , Point , ? > currentNode = it . next ( ) ; if ( currentNode . previousNode ( ) != null ) { explored . add ( currentNode . previousNode ( ) . state ( ) ) ; } List < Point > statePath = new ArrayList < Point > ( ) ; for ( Node < ? , Point , ? > current : currentNode . path ( ) ) { statePath . add ( current . state ( ) ) ; } System . out . println ( getMazeStringSolution ( maze , explored , statePath ) ) ; Thread . sleep ( 50 ) ; if ( currentNode . state ( ) . equals ( maze . getGoalLoc ( ) ) ) { return ; } } }
Prints the maze and the result of the current iteration until the solution is found .
40,356
public static String getMazeStringSolution ( Maze2D maze , Collection < Point > explored , Collection < Point > path ) { List < Map < Point , Character > > replacements = new ArrayList < Map < Point , Character > > ( ) ; Map < Point , Character > replacement = new HashMap < Point , Character > ( ) ; for ( Point p : explored ) { replacement . put ( p , '.' ) ; } replacements . add ( replacement ) ; replacement = new HashMap < Point , Character > ( ) ; for ( Point p : path ) { replacement . put ( p , '*' ) ; } replacements . add ( replacement ) ; return maze . getReplacedMazeString ( replacements ) ; }
Returns the maze passed as parameter but replacing some characters to print the path found in the current iteration .
40,357
public static void main ( String [ ] args ) { SearchProblem p = ProblemBuilder . create ( ) . initialState ( Arrays . asList ( 5 , 4 , 0 , 7 , 2 , 6 , 8 , 1 , 3 ) ) . defineProblemWithExplicitActions ( ) . useActionFunction ( new ActionFunction < Action , List < Integer > > ( ) { public Iterable < Action > actionsFor ( List < Integer > state ) { return validMovementsFor ( state ) ; } } ) . useTransitionFunction ( new ActionStateTransitionFunction < Action , List < Integer > > ( ) { public List < Integer > apply ( Action action , List < Integer > state ) { return applyActionToState ( action , state ) ; } } ) . useCostFunction ( new CostFunction < Action , List < Integer > , Double > ( ) { public Double evaluate ( Transition < Action , List < Integer > > transition ) { return 1d ; } } ) . build ( ) ; System . out . println ( Hipster . createDijkstra ( p ) . search ( Arrays . asList ( 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ) ) ) ; }
Possible actions of our problem
40,358
public Iterable < GraphEdge < V , E > > edges ( ) { return F . map ( vedges ( ) , new Function < Map . Entry < V , GraphEdge < V , E > > , GraphEdge < V , E > > ( ) { public GraphEdge < V , E > apply ( Map . Entry < V , GraphEdge < V , E > > entry ) { return entry . getValue ( ) ; } } ) ; }
Returns a list of the edges in the graph .
40,359
public SearchResult search ( final S goalState ) { return search ( new Predicate < N > ( ) { public boolean apply ( N n ) { if ( goalState != null ) { return n . state ( ) . equals ( goalState ) ; } return false ; } } ) ; }
Run the algorithm until the goal is found or no more states are available .
40,360
public SearchResult search ( Predicate < N > condition ) { int iteration = 0 ; Iterator < N > it = iterator ( ) ; long begin = System . currentTimeMillis ( ) ; N currentNode = null ; while ( it . hasNext ( ) ) { iteration ++ ; currentNode = it . next ( ) ; if ( condition . apply ( currentNode ) ) { break ; } } long end = System . currentTimeMillis ( ) ; return new SearchResult ( currentNode , iteration , end - begin ) ; }
Executes the search algorithm until the predicate condition is satisfied or there are no more nodes to explore .
40,361
public static < S , N extends Node < ? , S , N > > List < S > recoverStatePath ( N node ) { List < S > states = new LinkedList < S > ( ) ; for ( N n : node . path ( ) ) { states . add ( n . state ( ) ) ; } return states ; }
Returns a path with all the states of the path .
40,362
public static < A , S , C extends Comparable < C > , N extends CostNode < A , S , C , N > > BellmanFord < A , S , C , N > createBellmanFord ( SearchProblem < A , S , N > components ) { return new BellmanFord < A , S , C , N > ( components . getInitialNode ( ) , components . getExpander ( ) ) ; }
Instantiates a Bellman Ford algorithm for a problem definition .
40,363
public static < A , S , N extends Node < A , S , N > > BreadthFirstSearch < A , S , N > createBreadthFirstSearch ( SearchProblem < A , S , N > components ) { return new BreadthFirstSearch < A , S , N > ( components . getInitialNode ( ) , components . getExpander ( ) ) ; }
Instantiates Breadth First Search algorithm for a problem definition .
40,364
public static < A , S , N extends Node < A , S , N > > DepthFirstSearch < A , S , N > createDepthFirstSearch ( SearchProblem < A , S , N > components ) { return new DepthFirstSearch < A , S , N > ( components . getInitialNode ( ) , components . getExpander ( ) ) ; }
Instantiates Depth First Search algorithm for a problem definition .
40,365
public static < A , S , N extends Node < A , S , N > > DepthLimitedSearch < A , S , N > createDepthLimitedSearch ( SearchProblem < A , S , N > components , int depth ) { return new DepthLimitedSearch < A , S , N > ( components . getInitialNode ( ) , components . getFinalNode ( ) , components . getExpander ( ) , depth ) ; }
Instantiates Depth Limited Search algorithm for a problem definition .
40,366
public static < A , S , C extends Comparable < C > , N extends HeuristicNode < A , S , C , N > > HillClimbing < A , S , C , N > createHillClimbing ( SearchProblem < A , S , N > components , boolean enforced ) { return new HillClimbing < A , S , C , N > ( components . getInitialNode ( ) , components . getExpander ( ) , enforced ) ; }
Instantiates a Hill Climbing algorithm given a problem definition .
40,367
public static < A , S , N extends HeuristicNode < A , S , Double , N > > AnnealingSearch < A , S , N > createAnnealingSearch ( SearchProblem < A , S , N > components , Double alpha , Double minTemp , AcceptanceProbability acceptanceProbability , SuccessorFinder < A , S , N > successorFinder ) { return new AnnealingSearch < A , S , N > ( components . getInitialNode ( ) , components . getExpander ( ) , alpha , minTemp , acceptanceProbability , successorFinder ) ; }
Instantiates an AnnealingSearch algorithm given a problem definition .
40,368
public static < A , S , C extends Comparable < C > , N extends HeuristicNode < A , S , C , N > > MultiobjectiveLS < A , S , C , N > createMultiobjectiveLS ( SearchProblem < A , S , N > components ) { return new MultiobjectiveLS < A , S , C , N > ( components . getInitialNode ( ) , components . getExpander ( ) ) ; }
Instantiates a Multi - objective Label Setting algorithm given a problem definition .
40,369
public static HeuristicFunction < City , Double > heuristicFunction ( ) { return new HeuristicFunction < City , Double > ( ) { public Double estimate ( City state ) { return heuristics ( ) . get ( state ) ; } } ; }
Heuristic function required to define search problems to be used with Hipster .
40,370
public static < S > UnweightedNode < Void , S > newNodeWithoutAction ( UnweightedNode < Void , S > previousNode , S state ) { return new UnweightedNode < Void , S > ( previousNode , state , null ) ; }
This static method creates an unweighted node without defining an explicit action using the parent node and a state .
40,371
public static < T extends GraphNode < T > > T getFirstChild ( T node ) { return hasChildren ( node ) ? node . getChildren ( ) . get ( 0 ) : null ; }
Returns the first child node of the given node or null if node is null or does not have any children .
40,372
public static < T extends GraphNode < T > > T getLastChild ( T node ) { return hasChildren ( node ) ? node . getChildren ( ) . get ( node . getChildren ( ) . size ( ) - 1 ) : null ; }
Returns the last child node of the given node or null if node is null or does not have any children .
40,373
public static < T extends GraphNode < T > > int countAllDistinct ( T node ) { if ( node == null ) return 0 ; return collectAllNodes ( node , new HashSet < T > ( ) ) . size ( ) ; }
Counts all distinct nodes in the graph reachable from the given node . This method can properly deal with cycles in the graph .
40,374
public static < T extends GraphNode < T > , C extends Collection < T > > C collectAllNodes ( T node , C collection ) { checkArgNotNull ( collection , "collection" ) ; if ( node != null && ! collection . contains ( node ) ) { collection . add ( node ) ; for ( T child : node . getChildren ( ) ) { collectAllNodes ( child , collection ) ; } } return collection ; }
Collects all nodes from the graph reachable from the given node in the given collection . This method can properly deal with cycles in the graph .
40,375
public static < T extends GraphNode < T > > String printTree ( T node , Formatter < T > formatter ) { checkArgNotNull ( formatter , "formatter" ) ; return printTree ( node , formatter , Predicates . < T > alwaysTrue ( ) , Predicates . < T > alwaysTrue ( ) ) ; }
Creates a string representation of the graph reachable from the given node using the given formatter .
40,376
private static < T extends GraphNode < T > > StringBuilder printTree ( T node , Formatter < T > formatter , String indent , StringBuilder sb , Predicate < T > nodeFilter , Predicate < T > subTreeFilter ) { if ( nodeFilter . apply ( node ) ) { String line = formatter . format ( node ) ; if ( line != null ) { sb . append ( indent ) . append ( line ) . append ( "\n" ) ; indent += " " ; } } if ( subTreeFilter . apply ( node ) ) { for ( T sub : node . getChildren ( ) ) { printTree ( sub , formatter , indent , sb , nodeFilter , subTreeFilter ) ; } } return sb ; }
private recursion helper
40,377
public static boolean isBoxedType ( Class < ? > primitive , Class < ? > boxed ) { return ( primitive . equals ( boolean . class ) && boxed . equals ( Boolean . class ) ) || ( primitive . equals ( byte . class ) && boxed . equals ( Byte . class ) ) || ( primitive . equals ( char . class ) && boxed . equals ( Character . class ) ) || ( primitive . equals ( double . class ) && boxed . equals ( Double . class ) ) || ( primitive . equals ( float . class ) && boxed . equals ( Float . class ) ) || ( primitive . equals ( int . class ) && boxed . equals ( Integer . class ) ) || ( primitive . equals ( long . class ) && boxed . equals ( Long . class ) ) || ( primitive . equals ( short . class ) && boxed . equals ( Short . class ) ) || ( primitive . equals ( void . class ) && boxed . equals ( Void . class ) ) ; }
Determines if the primitive type is boxed as the boxed type
40,378
public static Constructor findConstructor ( Class < ? > type , Object [ ] args ) { outer : for ( Constructor constructor : type . getConstructors ( ) ) { Class < ? > [ ] paramTypes = constructor . getParameterTypes ( ) ; if ( paramTypes . length != args . length ) continue ; for ( int i = 0 ; i < args . length ; i ++ ) { Object arg = args [ i ] ; if ( arg != null && ! paramTypes [ i ] . isAssignableFrom ( arg . getClass ( ) ) && ! isBoxedType ( paramTypes [ i ] , arg . getClass ( ) ) ) continue outer ; if ( arg == null && paramTypes [ i ] . isPrimitive ( ) ) continue outer ; } return constructor ; } throw new GrammarException ( "No constructor found for %s and the given %s arguments" , type , args . length ) ; }
Finds the constructor of the given class that is compatible with the given arguments .
40,379
public static String humanize ( long value ) { if ( value < 0 ) { return '-' + humanize ( - value ) ; } else if ( value > 1000000000000000000L ) { return Double . toString ( ( value + 500000000000000L ) / 1000000000000000L * 1000000000000000L / 1000000000000000000.0 ) + 'E' ; } else if ( value > 100000000000000000L ) { return Double . toString ( ( value + 50000000000000L ) / 100000000000000L * 100000000000000L / 1000000000000000.0 ) + 'P' ; } else if ( value > 10000000000000000L ) { return Double . toString ( ( value + 5000000000000L ) / 10000000000000L * 10000000000000L / 1000000000000000.0 ) + 'P' ; } else if ( value > 1000000000000000L ) { return Double . toString ( ( value + 500000000000L ) / 1000000000000L * 1000000000000L / 1000000000000000.0 ) + 'P' ; } else if ( value > 100000000000000L ) { return Double . toString ( ( value + 50000000000L ) / 100000000000L * 100000000000L / 1000000000000.0 ) + 'T' ; } else if ( value > 10000000000000L ) { return Double . toString ( ( value + 5000000000L ) / 10000000000L * 10000000000L / 1000000000000.0 ) + 'T' ; } else if ( value > 1000000000000L ) { return Double . toString ( ( value + 500000000 ) / 1000000000 * 1000000000 / 1000000000000.0 ) + 'T' ; } else if ( value > 100000000000L ) { return Double . toString ( ( value + 50000000 ) / 100000000 * 100000000 / 1000000000.0 ) + 'G' ; } else if ( value > 10000000000L ) { return Double . toString ( ( value + 5000000 ) / 10000000 * 10000000 / 1000000000.0 ) + 'G' ; } else if ( value > 1000000000 ) { return Double . toString ( ( value + 500000 ) / 1000000 * 1000000 / 1000000000.0 ) + 'G' ; } else if ( value > 100000000 ) { return Double . toString ( ( value + 50000 ) / 100000 * 100000 / 1000000.0 ) + 'M' ; } else if ( value > 10000000 ) { return Double . toString ( ( value + 5000 ) / 10000 * 10000 / 1000000.0 ) + 'M' ; } else if ( value > 1000000 ) { return Double . toString ( ( value + 500 ) / 1000 * 1000 / 1000000.0 ) + 'M' ; } else if ( value > 100000 ) { return Double . toString ( ( value + 50 ) / 100 * 100 / 1000.0 ) + 'K' ; } else if ( value > 10000 ) { return Double . toString ( ( value + 5 ) / 10 * 10 / 1000.0 ) + 'K' ; } else if ( value > 1000 ) { return Double . toString ( value / 1000.0 ) + 'K' ; } else { return Long . toString ( value ) + ' ' ; } }
Formats the given long value into a human readable notation using the Kilo Mega Giga etc . abbreviations .
40,380
protected Rule fromStringLiteral ( String string ) { return string . endsWith ( " " ) ? Sequence ( String ( string . substring ( 0 , string . length ( ) - 1 ) ) , WhiteSpace ( ) ) : String ( string ) ; }
character or string literal
40,381
static Matcher findProperLabelMatcher ( MatcherPath path , int errorIndex ) { try { return findProperLabelMatcher0 ( path , errorIndex ) ; } catch ( RuntimeException e ) { if ( e == UnderneathTestNot ) return null ; else throw e ; } }
Finds the Matcher in the given failedMatcherPath whose label is best for presentation in expected strings of parse error messages given the provided lastMatchPath .
40,382
public static String printParseErrors ( List < ParseError > errors ) { checkArgNotNull ( errors , "errors" ) ; StringBuilder sb = new StringBuilder ( ) ; for ( ParseError error : errors ) { if ( sb . length ( ) > 0 ) sb . append ( "---\n" ) ; sb . append ( printParseError ( error ) ) ; } return sb . toString ( ) ; }
Pretty prints the given parse errors showing their location in the given input buffer .
40,383
public static String printParseError ( ParseError error , Formatter < InvalidInputError > formatter ) { checkArgNotNull ( error , "error" ) ; checkArgNotNull ( formatter , "formatter" ) ; String message = error . getErrorMessage ( ) != null ? error . getErrorMessage ( ) : error instanceof InvalidInputError ? formatter . format ( ( InvalidInputError ) error ) : error . getClass ( ) . getSimpleName ( ) ; return printErrorMessage ( "%s (line %s, pos %s):" , message , error . getStartIndex ( ) , error . getEndIndex ( ) , error . getInputBuffer ( ) ) ; }
Pretty prints the given parse error showing its location in the given input buffer .
40,384
public static String repeat ( char c , int n ) { char [ ] array = new char [ n ] ; Arrays . fill ( array , c ) ; return String . valueOf ( array ) ; }
Creates a string consisting of n times the given character .
40,385
public static boolean startsWith ( String string , String prefix ) { return string != null && ( prefix == null || string . startsWith ( prefix ) ) ; }
Test whether a string starts with a given prefix handling null values without exceptions .
40,386
private static int getLine0 ( int [ ] newlines , int index ) { int j = Arrays . binarySearch ( newlines , index ) ; return j >= 0 ? j : - ( j + 1 ) ; }
returns the zero based input line number the character with the given index is found in
40,387
public boolean enterFrame ( ) { if ( level ++ > 0 ) { if ( stack == null ) stack = new LinkedList < T > ( ) ; stack . add ( get ( ) ) ; } return set ( initialValueFactory . create ( ) ) ; }
Provides a new frame for the variable . Potentially existing previous frames are saved . Normally you do not have to call this method manually as parboiled provides for automatic Var frame management .
40,388
public static Matcher unwrap ( Matcher matcher ) { if ( matcher instanceof MemoMismatchesMatcher ) { MemoMismatchesMatcher memoMismatchesMatcher = ( MemoMismatchesMatcher ) matcher ; return unwrap ( memoMismatchesMatcher . inner ) ; } return matcher ; }
Retrieves the innermost Matcher that is not a MemoMismatchesMatcher .
40,389
public String [ ] getLabels ( Matcher matcher ) { if ( ( matcher instanceof AnyOfMatcher ) && ( ( AnyOfMatcher ) matcher ) . characters . toString ( ) . equals ( matcher . getLabel ( ) ) ) { AnyOfMatcher cMatcher = ( AnyOfMatcher ) matcher ; if ( ! cMatcher . characters . isSubtractive ( ) ) { String [ ] labels = new String [ cMatcher . characters . getChars ( ) . length ] ; for ( int i = 0 ; i < labels . length ; i ++ ) { labels [ i ] = '\'' + String . valueOf ( cMatcher . characters . getChars ( ) [ i ] ) + '\'' ; } return labels ; } } return new String [ ] { matcher . getLabel ( ) } ; }
Gets the labels corresponding to the given matcher AnyOfMatchers are treated specially in that their label is constructed as a list of their contents
40,390
public static Matcher unwrap ( Matcher matcher ) { if ( matcher instanceof VarFramingMatcher ) { VarFramingMatcher varFramingMatcher = ( VarFramingMatcher ) matcher ; return unwrap ( varFramingMatcher . inner ) ; } return matcher ; }
Retrieves the innermost Matcher that is not a VarFramingMatcher .
40,391
public static Class < ? > findLoadedClass ( String className , ClassLoader classLoader ) { checkArgNotNull ( className , "className" ) ; checkArgNotNull ( classLoader , "classLoader" ) ; try { Class < ? > classLoaderBaseClass = Class . forName ( "java.lang.ClassLoader" ) ; Method findLoadedClassMethod = classLoaderBaseClass . getDeclaredMethod ( "findLoadedClass" , String . class ) ; findLoadedClassMethod . setAccessible ( true ) ; try { return ( Class < ? > ) findLoadedClassMethod . invoke ( classLoader , className ) ; } finally { findLoadedClassMethod . setAccessible ( false ) ; } } catch ( Exception e ) { throw new RuntimeException ( "Could not determine whether class '" + className + "' has already been loaded" , e ) ; } }
Returns the class with the given name if it has already been loaded by the given class loader . Otherwise the method returns null .
40,392
public static boolean isAssignableTo ( String classInternalName , Class < ? > type ) { checkArgNotNull ( classInternalName , "classInternalName" ) ; checkArgNotNull ( type , "type" ) ; return type . isAssignableFrom ( getClassForInternalName ( classInternalName ) ) ; }
Determines whether the class with the given descriptor is assignable to the given type .
40,393
public static < T extends TreeNode < T > > T getRoot ( T node ) { if ( node == null ) return null ; if ( node . getParent ( ) != null ) return getRoot ( node . getParent ( ) ) ; return node ; }
Returns the root of the tree the given node is part of .
40,394
public static < T extends MutableTreeNode < T > > void addChild ( T parent , T child ) { checkArgNotNull ( parent , "parent" ) ; parent . addChild ( parent . getChildren ( ) . size ( ) , child ) ; }
Adds a new child node to a given MutableTreeNode parent .
40,395
public static < T extends MutableTreeNode < T > > void removeChild ( T parent , T child ) { checkArgNotNull ( parent , "parent" ) ; int index = parent . getChildren ( ) . indexOf ( child ) ; checkElementIndex ( index , parent . getChildren ( ) . size ( ) ) ; parent . removeChild ( index ) ; }
Removes the given child from the given parent node .
40,396
Rule ArrayCreatorRest ( ) { return Sequence ( LBRK , FirstOf ( Sequence ( RBRK , ZeroOrMore ( Dim ( ) ) , ArrayInitializer ( ) ) , Sequence ( Expression ( ) , RBRK , ZeroOrMore ( DimExpr ( ) ) , ZeroOrMore ( Dim ( ) ) ) ) ) ; }
BasicType must be followed by at least one DimExpr or by ArrayInitializer .
40,397
public T getAndSet ( T value ) { T t = this . value ; this . value = value ; return t ; }
Replaces this references value with the given one .
40,398
private static void verify ( char [ ] [ ] strings ) { int length = strings . length ; for ( int i = 0 ; i < length ; i ++ ) { char [ ] a = strings [ i ] ; inner : for ( int j = i + 1 ; j < length ; j ++ ) { char [ ] b = strings [ j ] ; if ( b . length < a . length ) continue ; for ( int k = 0 ; k < a . length ; k ++ ) { if ( a [ k ] != b [ k ] ) continue inner ; } String sa = '"' + String . valueOf ( a ) + '"' ; String sb = '"' + String . valueOf ( b ) + '"' ; String msg = a . length == b . length ? sa + " is specified twice in a FirstOf(String...)" : sa + " is a prefix of " + sb + " in a FirstOf(String...) and comes before " + sb + ", which prevents " + sb + " from ever matching! You should reverse the order of the two alternatives." ; throw new GrammarException ( msg ) ; } } }
but match in the fast implementation
40,399
public static < V > Node < V > findNode ( Node < V > parent , Predicate < Node < V > > predicate ) { checkArgNotNull ( predicate , "predicate" ) ; if ( parent != null ) { if ( predicate . apply ( parent ) ) return parent ; if ( hasChildren ( parent ) ) { Node < V > found = findNode ( parent . getChildren ( ) , predicate ) ; if ( found != null ) return found ; } } return null ; }
Returns the first node underneath the given parent for which the given predicate evaluates to true . If parent is null or no node is found the method returns null .