idx int64 0 41.2k | question stringlengths 74 4.04k | target stringlengths 7 750 |
|---|---|---|
27,800 | void findErrorEvaluator ( GrowQueue_I8 syndromes , GrowQueue_I8 errorLocator , GrowQueue_I8 evaluator ) { math . polyMult_flipA ( syndromes , errorLocator , evaluator ) ; int N = errorLocator . size - 1 ; int offset = evaluator . size - N ; for ( int i = 0 ; i < N ; i ++ ) { evaluator . data [ i ] = evaluator . data [ i + offset ] ; } evaluator . data [ N ] = 0 ; evaluator . size = errorLocator . size ; for ( int i = 0 ; i < evaluator . size / 2 ; i ++ ) { int j = evaluator . size - i - 1 ; int tmp = evaluator . data [ i ] ; evaluator . data [ i ] = evaluator . data [ j ] ; evaluator . data [ j ] = ( byte ) tmp ; } } | Compute the error evaluator polynomial Omega . |
27,801 | public static < O extends ImageGray < O > > O [ ] declareOutput ( ImagePyramid < ? > pyramid , Class < O > outputType ) { O [ ] ret = ( O [ ] ) Array . newInstance ( outputType , pyramid . getNumLayers ( ) ) ; for ( int i = 0 ; i < ret . length ; i ++ ) { int w = pyramid . getWidth ( i ) ; int h = pyramid . getHeight ( i ) ; ret [ i ] = GeneralizedImageOps . createSingleBand ( outputType , w , h ) ; } return ret ; } | Creates an array of single band images for each layer in the provided pyramid . Each image will be the same size as the corresponding layer in the pyramid . |
27,802 | public static < O extends ImageGray < O > > void reshapeOutput ( ImagePyramid < ? > pyramid , O [ ] output ) { for ( int i = 0 ; i < output . length ; i ++ ) { int w = pyramid . getWidth ( i ) ; int h = pyramid . getHeight ( i ) ; output [ i ] . reshape ( w , h ) ; } } | Reshapes each image in the array to match the layers in the pyramid |
27,803 | public static void histogram ( GrayU8 image , int maxPixelValue , TupleDesc_F64 histogram ) { int numBins = histogram . size ( ) ; int divisor = maxPixelValue + 1 ; histogram . fill ( 0 ) ; for ( int y = 0 ; y < image . height ; y ++ ) { int index = image . startIndex + y * image . stride ; for ( int x = 0 ; x < image . width ; x ++ , index ++ ) { int value = image . data [ index ] & 0xFF ; int bin = numBins * value / divisor ; histogram . value [ bin ] ++ ; } } } | Computes a single - band normalized histogram from an integer image .. |
27,804 | public static < T > T convertGenericToSpecificType ( Class < ? > type ) { if ( type == GrayI8 . class ) return ( T ) GrayU8 . class ; if ( type == GrayI16 . class ) return ( T ) GrayS16 . class ; if ( type == InterleavedI8 . class ) return ( T ) InterleavedU8 . class ; if ( type == InterleavedI16 . class ) return ( T ) InterleavedS16 . class ; return ( T ) type ; } | If an image is to be created then the generic type can t be used a specific one needs to be . An arbitrary specific image type is returned here . |
27,805 | public static List < LineParametric2D_F32 > pruneSimilarLines ( List < LineParametric2D_F32 > lines , float intensity [ ] , float toleranceAngle , float toleranceDist , int imgWidth , int imgHeight ) { int indexSort [ ] = new int [ intensity . length ] ; QuickSort_F32 sort = new QuickSort_F32 ( ) ; sort . sort ( intensity , 0 , lines . size ( ) , indexSort ) ; float theta [ ] = new float [ lines . size ( ) ] ; List < LineSegment2D_F32 > segments = new ArrayList < > ( lines . size ( ) ) ; for ( int i = 0 ; i < lines . size ( ) ; i ++ ) { LineParametric2D_F32 l = lines . get ( i ) ; theta [ i ] = UtilAngle . atanSafe ( l . getSlopeY ( ) , l . getSlopeX ( ) ) ; segments . add ( convert ( l , imgWidth , imgHeight ) ) ; } for ( int i = segments . size ( ) - 1 ; i >= 0 ; i -- ) { LineSegment2D_F32 a = segments . get ( indexSort [ i ] ) ; if ( a == null ) continue ; for ( int j = i - 1 ; j >= 0 ; j -- ) { LineSegment2D_F32 b = segments . get ( indexSort [ j ] ) ; if ( b == null ) continue ; if ( UtilAngle . distHalf ( theta [ indexSort [ i ] ] , theta [ indexSort [ j ] ] ) > toleranceAngle ) continue ; Point2D_F32 p = Intersection2D_F32 . intersection ( a , b , null ) ; if ( p != null && p . x >= 0 && p . y >= 0 && p . x < imgWidth && p . y < imgHeight ) { segments . set ( indexSort [ j ] , null ) ; } else { float distA = Distance2D_F32 . distance ( a , b . a ) ; float distB = Distance2D_F32 . distance ( a , b . b ) ; if ( distA <= toleranceDist || distB < toleranceDist ) { segments . set ( indexSort [ j ] , null ) ; } } } } List < LineParametric2D_F32 > ret = new ArrayList < > ( ) ; for ( int i = 0 ; i < segments . size ( ) ; i ++ ) { if ( segments . get ( i ) != null ) { ret . add ( lines . get ( i ) ) ; } } return ret ; } | Prunes similar looking lines but keeps the lines with the most intensity . |
27,806 | public static LineSegment2D_F32 convert ( LineParametric2D_F32 l , int width , int height ) { double t0 = ( 0 - l . p . x ) / l . getSlopeX ( ) ; double t1 = ( 0 - l . p . y ) / l . getSlopeY ( ) ; double t2 = ( width - l . p . x ) / l . getSlopeX ( ) ; double t3 = ( height - l . p . y ) / l . getSlopeY ( ) ; Point2D_F32 a = computePoint ( l , t0 ) ; Point2D_F32 b = computePoint ( l , t1 ) ; Point2D_F32 c = computePoint ( l , t2 ) ; Point2D_F32 d = computePoint ( l , t3 ) ; List < Point2D_F32 > inside = new ArrayList < > ( ) ; checkAddInside ( width , height , a , inside ) ; checkAddInside ( width , height , b , inside ) ; checkAddInside ( width , height , c , inside ) ; checkAddInside ( width , height , d , inside ) ; if ( inside . size ( ) != 2 ) { return null ; } return new LineSegment2D_F32 ( inside . get ( 0 ) , inside . get ( 1 ) ) ; } | Find the point in which the line intersects the image border and create a line segment at those points |
27,807 | public static void applyMask ( GrayF32 disparity , GrayU8 mask , int radius ) { if ( disparity . isSubimage ( ) || mask . isSubimage ( ) ) throw new RuntimeException ( "Input is subimage. Currently not support but no reason why it can't be. Ask for it" ) ; int N = disparity . width * disparity . height ; for ( int i = 0 ; i < N ; i ++ ) { if ( mask . data [ i ] == 0 ) { disparity . data [ i ] = 255 ; } } if ( radius > 0 ) { int r = radius ; for ( int y = r ; y < mask . height - r - 1 ; y ++ ) { int indexMsk = y * mask . stride + r ; for ( int x = r ; x < mask . width - r - 1 ; x ++ , indexMsk ++ ) { int deltaX = mask . data [ indexMsk ] - mask . data [ indexMsk + 1 ] ; int deltaY = mask . data [ indexMsk ] - mask . data [ indexMsk + mask . stride ] ; if ( deltaX != 0 || deltaY != 0 ) { if ( deltaX < 0 ) deltaX = 0 ; if ( deltaY < 0 ) deltaY = 0 ; for ( int i = - r ; i <= r ; i ++ ) { for ( int j = - r ; j <= r ; j ++ ) { disparity . set ( deltaX + x + j , deltaY + y + i , 255 ) ; } } } } } } } | Applies a mask which indicates which pixels had mappings to the unrectified image . Pixels which were outside of the original image will be set to 255 . The border is extended because the sharp edge in the rectified image can cause in incorrect match between image features . |
27,808 | public boolean fitAnchored ( int anchor0 , int anchor1 , GrowQueue_I32 corners , GrowQueue_I32 output ) { this . anchor0 = anchor0 ; this . anchor1 = anchor1 ; int numLines = anchor0 == anchor1 ? corners . size ( ) : CircularIndex . distanceP ( anchor0 , anchor1 , corners . size ) ; if ( numLines < 2 ) { throw new RuntimeException ( "The one line is anchored and can't be optimized" ) ; } lines . resize ( numLines ) ; if ( verbose ) System . out . println ( "ENTER FitLinesToContour" ) ; workCorners . setTo ( corners ) ; for ( int iteration = 0 ; iteration < maxIterations ; iteration ++ ) { if ( ! fitLinesUsingCorners ( numLines , workCorners ) ) { return false ; } if ( ! linesIntoCorners ( numLines , workCorners ) ) { return false ; } if ( ! sanityCheckCornerOrder ( numLines , workCorners ) ) { return false ; } } if ( verbose ) System . out . println ( "EXIT FitLinesToContour. " + corners . size ( ) + " " + workCorners . size ( ) ) ; output . setTo ( workCorners ) ; return true ; } | Fits line segments along the contour with the first and last corner fixed at the original corners . The output will be a new set of corner indexes . Since the corner list is circular it is assumed that anchor1 comes after anchor0 . The same index can be specified for an anchor it will just go around the entire circle |
27,809 | boolean sanityCheckCornerOrder ( int numLines , GrowQueue_I32 corners ) { int contourAnchor0 = corners . get ( anchor0 ) ; int previous = 0 ; for ( int i = 1 ; i < numLines ; i ++ ) { int contourIndex = corners . get ( CircularIndex . addOffset ( anchor0 , i , corners . size ( ) ) ) ; int pixelsFromAnchor0 = CircularIndex . distanceP ( contourAnchor0 , contourIndex , contour . size ( ) ) ; if ( pixelsFromAnchor0 < previous ) { return false ; } else { previous = pixelsFromAnchor0 ; } } return true ; } | All the corners should be in increasing order from the first anchor . |
27,810 | boolean fitLinesUsingCorners ( int numLines , GrowQueue_I32 cornerIndexes ) { for ( int i = 1 ; i <= numLines ; i ++ ) { int index0 = cornerIndexes . get ( CircularIndex . addOffset ( anchor0 , i - 1 , cornerIndexes . size ) ) ; int index1 = cornerIndexes . get ( CircularIndex . addOffset ( anchor0 , i , cornerIndexes . size ) ) ; if ( index0 == index1 ) return false ; if ( ! fitLine ( index0 , index1 , lines . get ( i - 1 ) ) ) { return false ; } LineGeneral2D_F64 l = lines . get ( i - 1 ) ; if ( Double . isNaN ( l . A ) || Double . isNaN ( l . B ) || Double . isNaN ( l . C ) ) { throw new RuntimeException ( "This should be impossible" ) ; } } return true ; } | Fits lines across the sequence of corners |
27,811 | boolean fitLine ( int contourIndex0 , int contourIndex1 , LineGeneral2D_F64 line ) { int numPixels = CircularIndex . distanceP ( contourIndex0 , contourIndex1 , contour . size ( ) ) ; if ( numPixels < minimumLineLength ) return false ; Point2D_I32 c0 = contour . get ( contourIndex0 ) ; Point2D_I32 c1 = contour . get ( contourIndex1 ) ; double scale = c0 . distance ( c1 ) ; double centerX = ( c1 . x + c0 . x ) / 2.0 ; double centerY = ( c1 . y + c0 . y ) / 2.0 ; int numSamples = Math . min ( maxSamples , numPixels ) ; pointsFit . reset ( ) ; for ( int i = 0 ; i < numSamples ; i ++ ) { int index = i * ( numPixels - 1 ) / ( numSamples - 1 ) ; Point2D_I32 c = contour . get ( CircularIndex . addOffset ( contourIndex0 , index , contour . size ( ) ) ) ; Point2D_F64 p = pointsFit . grow ( ) ; p . x = ( c . x - centerX ) / scale ; p . y = ( c . y - centerY ) / scale ; } if ( null == FitLine_F64 . polar ( pointsFit . toList ( ) , linePolar ) ) { return false ; } UtilLine2D_F64 . convert ( linePolar , line ) ; line . C = scale * line . C - centerX * line . A - centerY * line . B ; return true ; } | Given a sequence of points on the contour find the best fit line . |
27,812 | int closestPoint ( Point2D_F64 target ) { double bestDistance = Double . MAX_VALUE ; int bestIndex = - 1 ; for ( int i = 0 ; i < contour . size ( ) ; i ++ ) { Point2D_I32 c = contour . get ( i ) ; double d = UtilPoint2D_F64 . distanceSq ( target . x , target . y , c . x , c . y ) ; if ( d < bestDistance ) { bestDistance = d ; bestIndex = i ; } } return bestIndex ; } | Returns the closest point on the contour to the provided point in space |
27,813 | public void setTransformFromLinesSquare ( QrCode qr ) { storagePairs2D . reset ( ) ; storagePairs3D . reset ( ) ; set ( 0 , 7 , qr . ppCorner , 1 ) ; set ( 7 , 7 , qr . ppCorner , 2 ) ; set ( 7 , 0 , qr . ppCorner , 3 ) ; setLine ( 0 , 7 , 0 , 14 , qr . ppCorner , 1 , qr . ppRight , 0 ) ; setLine ( 7 , 7 , 7 , 14 , qr . ppCorner , 2 , qr . ppRight , 3 ) ; setLine ( 7 , 7 , 14 , 7 , qr . ppCorner , 2 , qr . ppDown , 1 ) ; setLine ( 7 , 0 , 14 , 0 , qr . ppCorner , 3 , qr . ppDown , 0 ) ; DMatrixRMaj HH = new DMatrixRMaj ( 3 , 3 ) ; dlt . process ( storagePairs2D . toList ( ) , storagePairs3D . toList ( ) , null , HH ) ; H . set ( HH ) ; H . invert ( Hinv ) ; ConvertFloatType . convert ( Hinv , Hinv32 ) ; ConvertFloatType . convert ( H , H32 ) ; } | Used to estimate the image to grid coordinate system before the version is known . The top left square is used to fix the coordinate system . Then 4 lines between corners going to other QR codes is used to make it less suspectable to errors in the first 4 corners |
27,814 | public void removeOutsideCornerFeatures ( ) { if ( pairs2D . size ( ) != storagePairs2D . size ) throw new RuntimeException ( "This can only be called when all the features have been added" ) ; pairs2D . remove ( 11 ) ; pairs2D . remove ( 5 ) ; pairs2D . remove ( 0 ) ; } | Outside corners on position patterns are more likely to be damaged so remove them |
27,815 | public static < T extends ImageGray < T > > SearchLocalPeak < T > meanShiftUniform ( int maxIterations , float convergenceTol , Class < T > imageType ) { WeightPixel_F32 weights = new WeightPixelUniform_F32 ( ) ; MeanShiftPeak < T > alg = new MeanShiftPeak < > ( maxIterations , convergenceTol , weights , imageType ) ; return new MeanShiftPeak_to_SearchLocalPeak < > ( alg ) ; } | Mean - shift based search with a uniform kernel |
27,816 | public static < T extends ImageGray < T > > SearchLocalPeak < T > meanShiftGaussian ( int maxIterations , float convergenceTol , Class < T > imageType ) { WeightPixel_F32 weights = new WeightPixelGaussian_F32 ( ) ; MeanShiftPeak < T > alg = new MeanShiftPeak < > ( maxIterations , convergenceTol , weights , imageType ) ; return new MeanShiftPeak_to_SearchLocalPeak < > ( alg ) ; } | Mean - shift based search with a Gaussian kernel |
27,817 | public static void loopBlocks ( int start , int endExclusive , int minBlock , IntRangeConsumer consumer ) { final ForkJoinPool pool = BoofConcurrency . pool ; int numThreads = pool . getParallelism ( ) ; int range = endExclusive - start ; if ( range == 0 ) return ; if ( range < 0 ) throw new IllegalArgumentException ( "end must be more than start. " + start + " -> " + endExclusive ) ; int block = selectBlockSize ( range , minBlock , numThreads ) ; try { pool . submit ( new IntRangeTask ( start , endExclusive , block , consumer ) ) . get ( ) ; } catch ( InterruptedException | ExecutionException e ) { e . printStackTrace ( ) ; } } | Automatically breaks the problem up into blocks based on the number of threads available . It is assumed that there is some cost associated with processing a block and the number of blocks is minimized . |
27,818 | public static void loopBlocks ( int start , int endExclusive , IntRangeConsumer consumer ) { final ForkJoinPool pool = BoofConcurrency . pool ; int numThreads = pool . getParallelism ( ) ; int range = endExclusive - start ; if ( range == 0 ) return ; if ( range < 0 ) throw new IllegalArgumentException ( "end must be more than start. " + start + " -> " + endExclusive ) ; int blockSize = Math . max ( 1 , range / numThreads ) ; try { pool . submit ( new IntRangeTask ( start , endExclusive , blockSize , consumer ) ) . get ( ) ; } catch ( InterruptedException | ExecutionException e ) { throw new RuntimeException ( e ) ; } } | Splits the range of values up into blocks . It s assumed the cost to process a block is small so more can be created . |
27,819 | public static Number sum ( int start , int endExclusive , Class type , IntProducerNumber producer ) { try { return pool . submit ( new IntOperatorTask . Sum ( start , endExclusive , type , producer ) ) . get ( ) ; } catch ( InterruptedException | ExecutionException e ) { throw new RuntimeException ( e ) ; } } | Computes sums up the results using the specified primitive type |
27,820 | public synchronized T pop ( ) { if ( list . isEmpty ( ) ) { return factory . newInstance ( ) ; } else { return list . remove ( list . size ( ) - 1 ) ; } } | Returns an instance . If there are instances queued up internally one of those is returned . Otherwise a new instance is created . |
27,821 | private void printGrid ( PDPageContentStream pcs , float offsetX , float offsetY , int numRows , int numCols , float sizeBox ) throws IOException { float pageWidth = ( float ) paper . convertWidth ( units ) * UNIT_TO_POINTS ; float pageHeight = ( float ) paper . convertHeight ( units ) * UNIT_TO_POINTS ; pcs . setStrokingColor ( 0.75 ) ; for ( int i = 0 ; i <= numCols ; i ++ ) { float x = offsetX + i * sizeBox ; pcs . moveTo ( x , 0 ) ; pcs . lineTo ( x , pageHeight ) ; } for ( int i = 0 ; i <= numRows ; i ++ ) { float y = offsetY + i * sizeBox ; pcs . moveTo ( 0 , y ) ; pcs . lineTo ( pageWidth , y ) ; } pcs . closeAndStroke ( ) ; } | Draws the grid in light grey on the document |
27,822 | public void setInput ( I input ) { this . inputImage = input ; if ( stale != null ) { for ( int i = 0 ; i < stale . length ; i ++ ) { boolean a [ ] = stale [ i ] ; for ( int j = 0 ; j < a . length ; j ++ ) { a [ j ] = true ; } } } } | Sets the new input image from which the image derivatives are computed from . |
27,823 | public void configure ( double descriptorRegionScale , double periodX , double periodY ) { this . radius = descriptorRegionScale * scaleToRadius ; this . periodX = ( int ) ( periodX + 0.5 ) ; this . periodY = ( int ) ( periodY + 0.5 ) ; this . featureWidth = ( int ) ( alg . getCanonicalWidth ( ) * descriptorRegionScale + 0.5 ) ; descriptions = new FastQueue < Desc > ( alg . getDescriptionType ( ) , true ) { protected Desc createInstance ( ) { return alg . createDescription ( ) ; } } ; } | Configures size of the descriptor and the frequency at which it s computed |
27,824 | public void setPoint ( int which , double x , double y , double z ) { points [ which ] . set ( x , y , z ) ; } | Specifies the location of a point in 3D space |
27,825 | public void connectPointToView ( int pointIndex , int viewIndex ) { SceneStructureMetric . Point p = points [ pointIndex ] ; for ( int i = 0 ; i < p . views . size ; i ++ ) { if ( p . views . data [ i ] == viewIndex ) throw new IllegalArgumentException ( "Tried to add the same view twice. viewIndex=" + viewIndex ) ; } p . views . add ( viewIndex ) ; } | Specifies that the point was observed in this view . |
27,826 | public void removePoints ( GrowQueue_I32 which ) { SceneStructureMetric . Point results [ ] = new SceneStructureMetric . Point [ points . length - which . size ] ; int indexWhich = 0 ; for ( int i = 0 ; i < points . length ; i ++ ) { if ( indexWhich < which . size && which . data [ indexWhich ] == i ) { indexWhich ++ ; } else { results [ i - indexWhich ] = points [ i ] ; } } points = results ; } | Removes the points specified in which from the list of points . which must be ordered from lowest to highest index . |
27,827 | public void select ( List < Se3_F64 > candidatesAtoB , List < AssociatedPair > observations , Se3_F64 model ) { Se3_F64 bestModel = null ; int bestCount = - 1 ; for ( int i = 0 ; i < candidatesAtoB . size ( ) ; i ++ ) { Se3_F64 s = candidatesAtoB . get ( i ) ; int count = 0 ; for ( AssociatedPair p : observations ) { if ( depthCheck . checkConstraint ( p . p1 , p . p2 , s ) ) { count ++ ; } } if ( count > bestCount ) { bestCount = count ; bestModel = s ; } } if ( bestModel == null ) throw new RuntimeException ( "BUG" ) ; model . set ( bestModel ) ; } | Selects the transform which describes a view where observations appear in front of the camera the most |
27,828 | public float get ( int x , int y ) { if ( ! isInBounds ( x , y ) ) throw new ImageAccessException ( "Requested pixel is out of bounds: ( " + x + " , " + y + " )" ) ; return unsafe_get ( x , y ) ; } | Returns the value of the specified pixel . |
27,829 | public void apply ( GrayU8 binary , int maxLoops ) { this . binary = binary ; inputBorder . setImage ( binary ) ; ones0 . reset ( ) ; zerosOut . reset ( ) ; findOnePixels ( ones0 ) ; for ( int loop = 0 ; ( loop < maxLoops || maxLoops == - 1 ) && ones0 . size > 0 ; loop ++ ) { boolean changed = false ; for ( int i = 0 ; i < masks . length ; i ++ ) { zerosOut . reset ( ) ; ones1 . reset ( ) ; masks [ i ] . apply ( ones0 , ones1 , zerosOut ) ; changed |= ones0 . size != ones1 . size ; for ( int j = 0 ; j < zerosOut . size ( ) ; j ++ ) { binary . data [ zerosOut . get ( j ) ] = 0 ; } GrowQueue_I32 tmp = ones0 ; ones0 = ones1 ; ones1 = tmp ; } if ( ! changed ) break ; } } | Applies the thinning algorithm . Runs for the specified number of loops or until no change is detected . |
27,830 | protected void findOnePixels ( GrowQueue_I32 ones ) { for ( int y = 0 ; y < binary . height ; y ++ ) { int index = binary . startIndex + y * binary . stride ; for ( int x = 0 ; x < binary . width ; x ++ , index ++ ) { if ( binary . data [ index ] != 0 ) { ones . add ( index ) ; } } } } | Scans through the image and record the array index of all marked pixels |
27,831 | public void pruneObservationsBehindCamera ( ) { Point3D_F64 X = new Point3D_F64 ( ) ; for ( int viewIndex = 0 ; viewIndex < observations . views . length ; viewIndex ++ ) { SceneObservations . View v = observations . views [ viewIndex ] ; SceneStructureMetric . View view = structure . views [ viewIndex ] ; for ( int pointIndex = 0 ; pointIndex < v . point . size ; pointIndex ++ ) { SceneStructureMetric . Point f = structure . points [ v . getPointId ( pointIndex ) ] ; f . get ( X ) ; if ( ! f . views . contains ( viewIndex ) ) throw new RuntimeException ( "BUG!" ) ; view . worldToView . transform ( X , X ) ; if ( X . z <= 0 ) { v . set ( pointIndex , Float . NaN , Float . NaN ) ; } } } removeMarkedObservations ( ) ; } | Check to see if a point is behind the camera which is viewing it . If it is remove that observation since it can t possibly be observed . |
27,832 | public void prunePoints ( int neighbors , double distance ) { Point3D_F64 worldX = new Point3D_F64 ( ) ; List < Point3D_F64 > cloud = new ArrayList < > ( ) ; for ( int i = 0 ; i < structure . points . length ; i ++ ) { SceneStructureMetric . Point structureP = structure . points [ i ] ; structureP . get ( worldX ) ; cloud . add ( worldX . copy ( ) ) ; } NearestNeighbor < Point3D_F64 > nn = FactoryNearestNeighbor . kdtree ( new KdTreePoint3D_F64 ( ) ) ; NearestNeighbor . Search < Point3D_F64 > search = nn . createSearch ( ) ; nn . setPoints ( cloud , false ) ; FastQueue < NnData < Point3D_F64 > > resultsNN = new FastQueue ( NnData . class , true ) ; int oldToNew [ ] = new int [ structure . points . length ] ; Arrays . fill ( oldToNew , - 1 ) ; GrowQueue_I32 prunePointID = new GrowQueue_I32 ( ) ; for ( int pointId = 0 ; pointId < structure . points . length ; pointId ++ ) { SceneStructureMetric . Point structureP = structure . points [ pointId ] ; structureP . get ( worldX ) ; search . findNearest ( cloud . get ( pointId ) , distance * distance , neighbors + 1 , resultsNN ) ; if ( resultsNN . size ( ) > neighbors ) { oldToNew [ pointId ] = pointId - prunePointID . size ; continue ; } prunePointID . add ( pointId ) ; for ( int viewIdx = 0 ; viewIdx < structureP . views . size ; viewIdx ++ ) { SceneObservations . View v = observations . getView ( structureP . views . data [ viewIdx ] ) ; int pointIdx = v . point . indexOf ( pointId ) ; if ( pointIdx < 0 ) throw new RuntimeException ( "Bad structure. Point not found in view's observation " + "which was in its structure" ) ; v . remove ( pointIdx ) ; } } pruneUpdatePointID ( oldToNew , prunePointID ) ; } | Prune a feature it has fewer than X neighbors within Y distance . Observations associated with this feature are also pruned . |
27,833 | public void pruneViews ( int count ) { List < SceneStructureMetric . View > remainingS = new ArrayList < > ( ) ; List < SceneObservations . View > remainingO = new ArrayList < > ( ) ; for ( int viewId = 0 ; viewId < structure . views . length ; viewId ++ ) { SceneObservations . View view = observations . views [ viewId ] ; if ( view . size ( ) > count ) { remainingS . add ( structure . views [ viewId ] ) ; remainingO . add ( view ) ; continue ; } for ( int pointIdx = 0 ; pointIdx < view . point . size ; pointIdx ++ ) { int pointId = view . getPointId ( pointIdx ) ; int viewIdx = structure . points [ pointId ] . views . indexOf ( viewId ) ; if ( viewIdx < 0 ) throw new RuntimeException ( "Bug in structure. view has point but point doesn't have view" ) ; structure . points [ pointId ] . views . remove ( viewIdx ) ; } } structure . views = new SceneStructureMetric . View [ remainingS . size ( ) ] ; observations . views = new SceneObservations . View [ remainingO . size ( ) ] ; for ( int i = 0 ; i < structure . views . length ; i ++ ) { structure . views [ i ] = remainingS . get ( i ) ; observations . views [ i ] = remainingO . get ( i ) ; } } | Removes views with less than count features visible . Observations of features in removed views are also removed . |
27,834 | public void pruneUnusedCameras ( ) { int histogram [ ] = new int [ structure . cameras . length ] ; for ( int i = 0 ; i < structure . views . length ; i ++ ) { histogram [ structure . views [ i ] . camera ] ++ ; } int oldToNew [ ] = new int [ structure . cameras . length ] ; List < SceneStructureMetric . Camera > remaining = new ArrayList < > ( ) ; for ( int i = 0 ; i < structure . cameras . length ; i ++ ) { if ( histogram [ i ] > 0 ) { oldToNew [ i ] = remaining . size ( ) ; remaining . add ( structure . cameras [ i ] ) ; } } structure . cameras = new SceneStructureMetric . Camera [ remaining . size ( ) ] ; for ( int i = 0 ; i < remaining . size ( ) ; i ++ ) { structure . cameras [ i ] = remaining . get ( i ) ; } for ( int i = 0 ; i < structure . views . length ; i ++ ) { SceneStructureMetric . View v = structure . views [ i ] ; v . camera = oldToNew [ v . camera ] ; } } | Prunes cameras that are not referenced by any views . |
27,835 | public void setIntrinsic ( CameraPinholeBrown intrinsic ) { planeProjection . setIntrinsic ( intrinsic ) ; normToPixel = LensDistortionFactory . narrow ( intrinsic ) . distort_F64 ( false , true ) ; pixelToNorm = LensDistortionFactory . narrow ( intrinsic ) . undistort_F64 ( true , false ) ; thresholdFarAngleError = Math . atan2 ( thresholdPixelError , intrinsic . fx ) ; } | Camera the camera s intrinsic parameters . Can be called at any time . |
27,836 | public void setExtrinsic ( Se3_F64 planeToCamera ) { this . planeToCamera = planeToCamera ; planeToCamera . invert ( cameraToPlane ) ; planeProjection . setPlaneToCamera ( planeToCamera , true ) ; } | Camera the camera s extrinsic parameters . Can be called at any time . |
27,837 | public void reset ( ) { tick = 0 ; first = true ; tracker . reset ( ) ; keyToWorld . reset ( ) ; currToKey . reset ( ) ; currToWorld . reset ( ) ; worldToCurrCam3D . reset ( ) ; } | Resets the algorithm into its initial state |
27,838 | private void addNewTracks ( ) { tracker . spawnTracks ( ) ; List < PointTrack > spawned = tracker . getNewTracks ( null ) ; for ( PointTrack t : spawned ) { VoTrack p = t . getCookie ( ) ; if ( p == null ) { t . cookie = p = new VoTrack ( ) ; } pixelToNorm . compute ( t . x , t . y , n ) ; if ( planeProjection . normalToPlane ( n . x , n . y , p . ground ) ) { p . onPlane = true ; } else { pointing . set ( n . x , n . y , 1 ) ; GeometryMath_F64 . mult ( cameraToPlane . getR ( ) , pointing , pointing ) ; pointing . normalize ( ) ; double normXZ = Math . sqrt ( pointing . x * pointing . x + pointing . z * pointing . z ) ; p . pointingY = pointing . y / normXZ ; p . ground . x = pointing . z ; p . ground . y = - pointing . x ; p . ground . x /= normXZ ; p . ground . y /= normXZ ; p . onPlane = false ; } p . lastInlier = tick ; } } | Requests that new tracks are spawned determines if they are on the plane or not and computes other required data structures . |
27,839 | private void sortTracksForEstimation ( ) { planeSamples . reset ( ) ; farAngles . reset ( ) ; tracksOnPlane . clear ( ) ; tracksFar . clear ( ) ; List < PointTrack > active = tracker . getActiveTracks ( null ) ; for ( PointTrack t : active ) { VoTrack p = t . getCookie ( ) ; pixelToNorm . compute ( t . x , t . y , n ) ; pointing . set ( n . x , n . y , 1 ) ; GeometryMath_F64 . mult ( cameraToPlane . getR ( ) , pointing , pointing ) ; pointing . normalize ( ) ; if ( p . onPlane ) { if ( pointing . y > 0 ) { PlanePtPixel ppp = planeSamples . grow ( ) ; ppp . normalizedCurr . set ( n ) ; ppp . planeKey . set ( p . ground ) ; tracksOnPlane . add ( t ) ; } } else { boolean allGood = pointing . y < 0 ; if ( strictFar ) { allGood = isRotationFromAxisY ( t , pointing ) ; } if ( allGood ) { computeAngleOfRotation ( t , pointing ) ; tracksFar . add ( t ) ; } } } } | Splits the set of active tracks into on plane and infinity sets . For each set also perform specific sanity checks to make sure basic constraints are still being meet . If not then the track will not be considered for motion estimation . |
27,840 | protected boolean isRotationFromAxisY ( PointTrack t , Vector3D_F64 pointing ) { VoTrack p = t . getCookie ( ) ; double normXZ = Math . sqrt ( pointing . x * pointing . x + pointing . z * pointing . z ) ; pointingAdj . set ( pointing . x / normXZ , p . pointingY , pointing . z / normXZ ) ; GeometryMath_F64 . multTran ( cameraToPlane . getR ( ) , pointingAdj , pointingAdj ) ; n . x = pointingAdj . x / pointingAdj . z ; n . y = pointingAdj . y / pointingAdj . z ; normToPixel . compute ( n . x , n . y , pixel ) ; double error = pixel . distance2 ( t ) ; return error < thresholdPixelError * thresholdPixelError ; } | Checks for motion which can t be caused by rotations along the y - axis alone . This is done by adjusting the pointing vector in the plane reference frame such that it has the same y component as when the track was spawned and that the x - z components are normalized to one to ensure consistent units . That pointing vector is then projected back into the image and a pixel difference computed . |
27,841 | private void computeAngleOfRotation ( PointTrack t , Vector3D_F64 pointingPlane ) { VoTrack p = t . getCookie ( ) ; groundCurr . x = pointingPlane . z ; groundCurr . y = - pointingPlane . x ; double norm = groundCurr . norm ( ) ; groundCurr . x /= norm ; groundCurr . y /= norm ; double dot = groundCurr . x * p . ground . x + groundCurr . y * p . ground . y ; if ( dot > 1.0 ) dot = 1.0 ; double angle = Math . acos ( dot ) ; if ( groundCurr . x * p . ground . y - groundCurr . y * p . ground . x > 0 ) angle = - angle ; farAngles . add ( angle ) ; } | Computes the angle of rotation between two pointing vectors on the ground plane and adds it to a list . |
27,842 | private void estimateFar ( ) { farInlierCount = 0 ; if ( farAngles . size == 0 ) return ; farAnglesCopy . reset ( ) ; farAnglesCopy . addAll ( farAngles ) ; farAngle = maximizeCountInSpread ( farAnglesCopy . data , farAngles . size , 2 * thresholdFarAngleError ) ; for ( int i = 0 ; i < tracksFar . size ( ) ; i ++ ) { PointTrack t = tracksFar . get ( i ) ; VoTrack p = t . getCookie ( ) ; if ( UtilAngle . dist ( farAngles . get ( i ) , farAngle ) <= thresholdFarAngleError ) { p . lastInlier = tick ; farInlierCount ++ ; } } } | Estimates only rotation using points at infinity . A robust estimation algorithm is used which finds an angle which maximizes the inlier set like RANSAC does . Unlike RANSAC this will produce an optimal result . |
27,843 | private void fuseEstimates ( ) { double x = closeMotionKeyToCurr . c * closeInlierCount + Math . cos ( farAngle ) * farInlierCount ; double y = closeMotionKeyToCurr . s * closeInlierCount + Math . sin ( farAngle ) * farInlierCount ; closeMotionKeyToCurr . setYaw ( Math . atan2 ( y , x ) ) ; closeMotionKeyToCurr . invert ( currToKey ) ; } | Fuse the estimates for yaw from both sets of points using a weighted vector average and save the results into currToKey |
27,844 | public Se3_F64 getWorldToCurr3D ( ) { Se2_F64 currToWorld = getCurrToWorld2D ( ) ; currPlaneToWorld3D . getT ( ) . set ( - currToWorld . T . y , 0 , currToWorld . T . x ) ; DMatrixRMaj R = currPlaneToWorld3D . getR ( ) ; R . unsafe_set ( 0 , 0 , currToWorld . c ) ; R . unsafe_set ( 0 , 2 , - currToWorld . s ) ; R . unsafe_set ( 1 , 1 , 1 ) ; R . unsafe_set ( 2 , 0 , currToWorld . s ) ; R . unsafe_set ( 2 , 2 , currToWorld . c ) ; currPlaneToWorld3D . invert ( worldToCurrPlane3D ) ; worldToCurrPlane3D . concat ( planeToCamera , worldToCurrCam3D ) ; return worldToCurrCam3D ; } | Converts 2D motion estimate into a 3D motion estimate |
27,845 | public static double maximizeCountInSpread ( double [ ] data , int size , double maxSpread ) { if ( size <= 0 ) return 0 ; Arrays . sort ( data , 0 , size ) ; int length = 0 ; for ( ; length < size ; length ++ ) { double s = UtilAngle . dist ( data [ 0 ] , data [ length ] ) ; if ( s > maxSpread ) { break ; } } int bestStart = 0 ; int bestLength = length ; int start ; for ( start = 1 ; start < size && length < size ; start ++ ) { length -- ; while ( length < size ) { double s = UtilAngle . dist ( data [ start ] , data [ ( start + length ) % size ] ) ; if ( s > maxSpread ) { break ; } else { length ++ ; } } if ( length > bestLength ) { bestLength = length ; bestStart = start ; } } return data [ ( bestStart + bestLength / 2 ) % size ] ; } | Finds the value which has the largest number of points above and below it within the specified spread |
27,846 | public boolean computeNextOctave ( ) { currentOctave += 1 ; if ( currentOctave > lastOctave ) { return false ; } if ( octaveImages [ numScales ] . width <= 5 || octaveImages [ numScales ] . height <= 5 ) return false ; PyramidOps . scaleDown2 ( octaveImages [ numScales ] , tempImage0 ) ; computeOctaveScales ( ) ; return true ; } | Computes the next octave . If the last octave has already been computed false is returned . |
27,847 | private void computeOctaveScales ( ) { octaveImages [ 0 ] = tempImage0 ; for ( int i = 1 ; i < numScales + 3 ; i ++ ) { octaveImages [ i ] . reshape ( tempImage0 . width , tempImage0 . height ) ; applyGaussian ( octaveImages [ i - 1 ] , octaveImages [ i ] , kernelSigmaToK [ i - 1 ] ) ; } for ( int i = 1 ; i < numScales + 3 ; i ++ ) { differenceOfGaussian [ i - 1 ] . reshape ( tempImage0 . width , tempImage0 . height ) ; PixelMath . subtract ( octaveImages [ i ] , octaveImages [ i - 1 ] , differenceOfGaussian [ i - 1 ] ) ; } } | Computes all the scale images in an octave . This includes DoG images . |
27,848 | void applyGaussian ( GrayF32 input , GrayF32 output , Kernel1D kernel ) { tempBlur . reshape ( input . width , input . height ) ; GConvolveImageOps . horizontalNormalized ( kernel , input , tempBlur ) ; GConvolveImageOps . verticalNormalized ( kernel , tempBlur , output ) ; } | Applies the separable kernel to the input image and stores the results in the output image . |
27,849 | public double computeOverlap ( ImageRectangle a , ImageRectangle b ) { if ( ! a . intersection ( b , work ) ) return 0 ; int areaI = work . area ( ) ; int bottom = a . area ( ) + b . area ( ) - areaI ; return areaI / ( double ) bottom ; } | Computes the fractional area of intersection between the two regions . |
27,850 | public Point2D_F64 getCenter ( ) { Rectangle r = getVisibleRect ( ) ; double x = ( r . x + r . width / 2 ) / scale ; double y = ( r . y + r . height / 2 ) / scale ; return new Point2D_F64 ( x , y ) ; } | The center pixel in the current view at a scale of 1 |
27,851 | public static boolean isValidVersion ( final String version ) { return StringUtils . isNotBlank ( version ) && ( ALTERNATE_PATTERN . matcher ( version ) . matches ( ) || STANDARD_PATTERN . matcher ( version ) . matches ( ) ) ; } | Validates version . |
27,852 | public String featureVersion ( final String featureName ) { String version = toString ( ) ; if ( featureName != null ) { version = getReleaseVersionString ( ) + "-" + featureName + ( isSnapshot ( ) ? "-" + Artifact . SNAPSHOT_VERSION : "" ) ; } return version ; } | Gets version with appended feature name . |
27,853 | private void initExecutables ( ) { if ( StringUtils . isBlank ( cmdMvn . getExecutable ( ) ) ) { if ( StringUtils . isBlank ( mvnExecutable ) ) { mvnExecutable = "mvn" ; } cmdMvn . setExecutable ( mvnExecutable ) ; } if ( StringUtils . isBlank ( cmdGit . getExecutable ( ) ) ) { if ( StringUtils . isBlank ( gitExecutable ) ) { gitExecutable = "git" ; } cmdGit . setExecutable ( gitExecutable ) ; } } | Initializes command line executables . |
27,854 | protected void validateConfiguration ( String ... params ) throws MojoFailureException { if ( StringUtils . isNotBlank ( argLine ) && MAVEN_DISALLOWED_PATTERN . matcher ( argLine ) . find ( ) ) { throw new MojoFailureException ( "The argLine doesn't match allowed pattern." ) ; } if ( params != null && params . length > 0 ) { for ( String p : params ) { if ( StringUtils . isNotBlank ( p ) && MAVEN_DISALLOWED_PATTERN . matcher ( p ) . find ( ) ) { throw new MojoFailureException ( "The '" + p + "' value doesn't match allowed pattern." ) ; } } } } | Validates plugin configuration . Throws exception if configuration is not valid . |
27,855 | protected String getCurrentProjectVersion ( ) throws MojoFailureException { final Model model = readModel ( mavenSession . getCurrentProject ( ) ) ; if ( model . getVersion ( ) == null ) { throw new MojoFailureException ( "Cannot get current project version. This plugin should be executed from the parent project." ) ; } return model . getVersion ( ) ; } | Gets current project version from pom . xml file . |
27,856 | private Model readModel ( MavenProject project ) throws MojoFailureException { try { Model model ; FileReader fileReader = new FileReader ( project . getFile ( ) . getAbsoluteFile ( ) ) ; MavenXpp3Reader mavenReader = new MavenXpp3Reader ( ) ; try { model = mavenReader . read ( fileReader ) ; } finally { if ( fileReader != null ) { fileReader . close ( ) ; } } return model ; } catch ( Exception e ) { throw new MojoFailureException ( "" , e ) ; } } | Reads model from Maven project pom . xml . |
27,857 | protected boolean validBranchName ( final String branchName ) throws MojoFailureException , CommandLineException { CommandResult r = executeGitCommandExitCode ( "check-ref-format" , "--allow-onelevel" , branchName ) ; return r . getExitCode ( ) == SUCCESS_EXIT_CODE ; } | Checks if branch name is acceptable . |
27,858 | private boolean executeGitHasUncommitted ( ) throws MojoFailureException , CommandLineException { boolean uncommited = false ; final CommandResult diffCommandResult = executeGitCommandExitCode ( "diff" , "--no-ext-diff" , "--ignore-submodules" , "--quiet" , "--exit-code" ) ; String error = null ; if ( diffCommandResult . getExitCode ( ) == SUCCESS_EXIT_CODE ) { final CommandResult diffIndexCommandResult = executeGitCommandExitCode ( "diff-index" , "--cached" , "--quiet" , "--ignore-submodules" , "HEAD" , "--" ) ; if ( diffIndexCommandResult . getExitCode ( ) != SUCCESS_EXIT_CODE ) { error = diffIndexCommandResult . getError ( ) ; uncommited = true ; } } else { error = diffCommandResult . getError ( ) ; uncommited = true ; } if ( StringUtils . isNotBlank ( error ) ) { throw new MojoFailureException ( error ) ; } return uncommited ; } | Executes git commands to check for uncommitted changes . |
27,859 | protected void initGitFlowConfig ( ) throws MojoFailureException , CommandLineException { gitSetConfig ( "gitflow.branch.master" , gitFlowConfig . getProductionBranch ( ) ) ; gitSetConfig ( "gitflow.branch.develop" , gitFlowConfig . getDevelopmentBranch ( ) ) ; gitSetConfig ( "gitflow.prefix.feature" , gitFlowConfig . getFeatureBranchPrefix ( ) ) ; gitSetConfig ( "gitflow.prefix.release" , gitFlowConfig . getReleaseBranchPrefix ( ) ) ; gitSetConfig ( "gitflow.prefix.hotfix" , gitFlowConfig . getHotfixBranchPrefix ( ) ) ; gitSetConfig ( "gitflow.prefix.support" , gitFlowConfig . getSupportBranchPrefix ( ) ) ; gitSetConfig ( "gitflow.prefix.versiontag" , gitFlowConfig . getVersionTagPrefix ( ) ) ; gitSetConfig ( "gitflow.origin" , gitFlowConfig . getOrigin ( ) ) ; } | Executes git config commands to set Git Flow configuration . |
27,860 | private void gitSetConfig ( final String name , String value ) throws MojoFailureException , CommandLineException { if ( value == null || value . isEmpty ( ) ) { value = "\"\"" ; } executeGitCommandExitCode ( "config" , name , value ) ; } | Executes git config command . |
27,861 | protected String gitFindTags ( ) throws MojoFailureException , CommandLineException { String tags = executeGitCommandReturn ( "for-each-ref" , "--sort=*authordate" , "--format=\"%(refname:short)\"" , "refs/tags/" ) ; tags = removeQuotes ( tags ) ; return tags ; } | Executes git for - each - ref to get all tags . |
27,862 | protected String gitFindLastTag ( ) throws MojoFailureException , CommandLineException { String tag = executeGitCommandReturn ( "for-each-ref" , "--sort=-*authordate" , "--count=1" , "--format=\"%(refname:short)\"" , "refs/tags/" ) ; tag = removeQuotes ( tag ) ; tag = tag . replaceAll ( "\\r?\\n" , "" ) ; return tag ; } | Executes git for - each - ref to get the last tag . |
27,863 | private String removeQuotes ( String str ) { if ( str != null && ! str . isEmpty ( ) ) { str = str . replaceAll ( "\"" , "" ) ; } return str ; } | Removes double quotes from the string . |
27,864 | protected boolean gitCheckBranchExists ( final String branchName ) throws MojoFailureException , CommandLineException { CommandResult commandResult = executeGitCommandExitCode ( "show-ref" , "--verify" , "--quiet" , "refs/heads/" + branchName ) ; return commandResult . getExitCode ( ) == SUCCESS_EXIT_CODE ; } | Checks if local branch with given name exists . |
27,865 | protected boolean gitCheckTagExists ( final String tagName ) throws MojoFailureException , CommandLineException { CommandResult commandResult = executeGitCommandExitCode ( "show-ref" , "--verify" , "--quiet" , "refs/tags/" + tagName ) ; return commandResult . getExitCode ( ) == SUCCESS_EXIT_CODE ; } | Checks if local tag with given name exists . |
27,866 | protected void gitCheckout ( final String branchName ) throws MojoFailureException , CommandLineException { getLog ( ) . info ( "Checking out '" + branchName + "' branch." ) ; executeGitCommand ( "checkout" , branchName ) ; } | Executes git checkout . |
27,867 | protected void gitCreateAndCheckout ( final String newBranchName , final String fromBranchName ) throws MojoFailureException , CommandLineException { getLog ( ) . info ( "Creating a new branch '" + newBranchName + "' from '" + fromBranchName + "' and checking it out." ) ; executeGitCommand ( "checkout" , "-b" , newBranchName , fromBranchName ) ; } | Executes git checkout - b . |
27,868 | private String replaceProperties ( String message , Map < String , String > map ) { if ( map != null ) { for ( Entry < String , String > entr : map . entrySet ( ) ) { message = StringUtils . replace ( message , "@{" + entr . getKey ( ) + "}" , entr . getValue ( ) ) ; } } return message ; } | Replaces properties in message . |
27,869 | protected void gitBranchDelete ( final String branchName ) throws MojoFailureException , CommandLineException { getLog ( ) . info ( "Deleting '" + branchName + "' branch." ) ; executeGitCommand ( "branch" , "-d" , branchName ) ; } | Executes git branch - d . |
27,870 | protected void gitBranchDeleteForce ( final String branchName ) throws MojoFailureException , CommandLineException { getLog ( ) . info ( "Deleting (-D) '" + branchName + "' branch." ) ; executeGitCommand ( "branch" , "-D" , branchName ) ; } | Executes git branch - D . |
27,871 | protected void gitFetchRemoteAndCreate ( final String branchName ) throws MojoFailureException , CommandLineException { if ( ! gitCheckBranchExists ( branchName ) ) { getLog ( ) . info ( "Local branch '" + branchName + "' doesn't exist. Trying to fetch and check it out from '" + gitFlowConfig . getOrigin ( ) + "'." ) ; gitFetchRemote ( branchName ) ; gitCreateAndCheckout ( branchName , gitFlowConfig . getOrigin ( ) + "/" + branchName ) ; } } | Fetches and checkouts from remote if local branch doesn t exist . |
27,872 | protected void gitFetchRemoteAndCompare ( final String branchName ) throws MojoFailureException , CommandLineException { if ( gitFetchRemote ( branchName ) ) { getLog ( ) . info ( "Comparing local branch '" + branchName + "' with remote '" + gitFlowConfig . getOrigin ( ) + "/" + branchName + "'." ) ; String revlistout = executeGitCommandReturn ( "rev-list" , "--left-right" , "--count" , branchName + "..." + gitFlowConfig . getOrigin ( ) + "/" + branchName ) ; String [ ] counts = org . apache . commons . lang3 . StringUtils . split ( revlistout , '\t' ) ; if ( counts != null && counts . length > 1 ) { if ( ! "0" . equals ( org . apache . commons . lang3 . StringUtils . deleteWhitespace ( counts [ 1 ] ) ) ) { throw new MojoFailureException ( "Remote branch '" + gitFlowConfig . getOrigin ( ) + "/" + branchName + "' is ahead of the local branch '" + branchName + "'. Execute git pull." ) ; } } } } | Executes git fetch and compares local branch with the remote . |
27,873 | private boolean gitFetchRemote ( final String branchName ) throws MojoFailureException , CommandLineException { getLog ( ) . info ( "Fetching remote branch '" + gitFlowConfig . getOrigin ( ) + " " + branchName + "'." ) ; CommandResult result = executeGitCommandExitCode ( "fetch" , "--quiet" , gitFlowConfig . getOrigin ( ) , branchName ) ; boolean success = result . getExitCode ( ) == SUCCESS_EXIT_CODE ; if ( ! success ) { getLog ( ) . warn ( "There were some problems fetching remote branch '" + gitFlowConfig . getOrigin ( ) + " " + branchName + "'. You can turn off remote branch fetching by setting the 'fetchRemote' parameter to false." ) ; } return success ; } | Executes git fetch . |
27,874 | protected void mvnSetVersions ( final String version ) throws MojoFailureException , CommandLineException { getLog ( ) . info ( "Updating version(s) to '" + version + "'." ) ; String newVersion = "-DnewVersion=" + version ; String g = "" ; String a = "" ; if ( versionsForceUpdate ) { g = "-DgroupId=" ; a = "-DartifactId=" ; } if ( tychoBuild ) { String prop = "" ; if ( StringUtils . isNotBlank ( versionProperty ) ) { prop = "-Dproperties=" + versionProperty ; getLog ( ) . info ( "Updating property '" + versionProperty + "' to '" + version + "'." ) ; } executeMvnCommand ( TYCHO_VERSIONS_PLUGIN_SET_GOAL , prop , newVersion , "-Dtycho.mode=maven" ) ; } else { if ( ! skipUpdateVersion ) { executeMvnCommand ( VERSIONS_MAVEN_PLUGIN_SET_GOAL , g , a , newVersion , "-DgenerateBackupPoms=false" ) ; } if ( StringUtils . isNotBlank ( versionProperty ) ) { getLog ( ) . info ( "Updating property '" + versionProperty + "' to '" + version + "'." ) ; executeMvnCommand ( VERSIONS_MAVEN_PLUGIN_SET_PROPERTY_GOAL , newVersion , "-Dproperty=" + versionProperty , "-DgenerateBackupPoms=false" ) ; } } } | Executes set goal of versions - maven - plugin or set - version of tycho - versions - plugin in case it is tycho build . |
27,875 | protected void mvnRun ( final String goals ) throws Exception { getLog ( ) . info ( "Running Maven goals: " + goals ) ; executeMvnCommand ( CommandLineUtils . translateCommandline ( goals ) ) ; } | Executes Maven goals . |
27,876 | private String executeGitCommandReturn ( final String ... args ) throws CommandLineException , MojoFailureException { return executeCommand ( cmdGit , true , null , args ) . getOut ( ) ; } | Executes Git command and returns output . |
27,877 | private CommandResult executeGitCommandExitCode ( final String ... args ) throws CommandLineException , MojoFailureException { return executeCommand ( cmdGit , false , null , args ) ; } | Executes Git command without failing on non successful exit code . |
27,878 | private void executeGitCommand ( final String ... args ) throws CommandLineException , MojoFailureException { executeCommand ( cmdGit , true , null , args ) ; } | Executes Git command . |
27,879 | private void executeMvnCommand ( final String ... args ) throws CommandLineException , MojoFailureException { executeCommand ( cmdMvn , true , argLine , args ) ; } | Executes Maven command . |
27,880 | private CommandResult executeCommand ( final Commandline cmd , final boolean failOnError , final String argStr , final String ... args ) throws CommandLineException , MojoFailureException { initExecutables ( ) ; if ( getLog ( ) . isDebugEnabled ( ) ) { getLog ( ) . debug ( cmd . getExecutable ( ) + " " + StringUtils . join ( args , " " ) + ( argStr == null ? "" : " " + argStr ) ) ; } cmd . clearArgs ( ) ; cmd . addArguments ( args ) ; if ( StringUtils . isNotBlank ( argStr ) ) { cmd . createArg ( ) . setLine ( argStr ) ; } final StringBufferStreamConsumer out = new StringBufferStreamConsumer ( verbose ) ; final CommandLineUtils . StringStreamConsumer err = new CommandLineUtils . StringStreamConsumer ( ) ; final int exitCode = CommandLineUtils . executeCommandLine ( cmd , out , err ) ; String errorStr = err . getOutput ( ) ; String outStr = out . getOutput ( ) ; if ( failOnError && exitCode != SUCCESS_EXIT_CODE ) { if ( StringUtils . isBlank ( errorStr ) && StringUtils . isNotBlank ( outStr ) ) { errorStr = outStr ; } throw new MojoFailureException ( errorStr ) ; } return new CommandResult ( exitCode , outStr , errorStr ) ; } | Executes command line . |
27,881 | public static ESVersion fromString ( String version ) { String lVersion = version ; final boolean snapshot = lVersion . endsWith ( "-SNAPSHOT" ) ; if ( snapshot ) { lVersion = lVersion . substring ( 0 , lVersion . length ( ) - 9 ) ; } String [ ] parts = lVersion . split ( "[.-]" ) ; if ( parts . length < 3 || parts . length > 4 ) { throw new IllegalArgumentException ( "the lVersion needs to contain major, minor, and revision, and optionally the build: " + lVersion ) ; } try { final int rawMajor = Integer . parseInt ( parts [ 0 ] ) ; if ( rawMajor >= 5 && snapshot ) { throw new IllegalArgumentException ( "illegal lVersion format - snapshots are only supported until lVersion 2.x" ) ; } final int betaOffset = rawMajor < 5 ? 0 : 25 ; final int major = rawMajor * 1000000 ; final int minor = Integer . parseInt ( parts [ 1 ] ) * 10000 ; final int revision = Integer . parseInt ( parts [ 2 ] ) * 100 ; int build = 99 ; if ( parts . length == 4 ) { String buildStr = parts [ 3 ] ; if ( buildStr . startsWith ( "alpha" ) ) { assert rawMajor >= 5 : "major must be >= 5 but was " + major ; build = Integer . parseInt ( buildStr . substring ( 5 ) ) ; assert build < 25 : "expected a beta build but " + build + " >= 25" ; } else if ( buildStr . startsWith ( "Beta" ) || buildStr . startsWith ( "beta" ) ) { build = betaOffset + Integer . parseInt ( buildStr . substring ( 4 ) ) ; assert build < 50 : "expected a beta build but " + build + " >= 50" ; } else if ( buildStr . startsWith ( "RC" ) || buildStr . startsWith ( "rc" ) ) { build = Integer . parseInt ( buildStr . substring ( 2 ) ) + 50 ; } else { throw new IllegalArgumentException ( "unable to parse lVersion " + lVersion ) ; } } return new ESVersion ( major + minor + revision + build ) ; } catch ( NumberFormatException e ) { throw new IllegalArgumentException ( "unable to parse lVersion " + lVersion , e ) ; } } | Returns the version given its string representation current version if the argument is null or empty |
27,882 | public < V > V getValue ( ) { if ( values == null || values . isEmpty ( ) ) { return null ; } return ( V ) values . get ( 0 ) ; } | The first value of the hit . |
27,883 | private void updateFsJob ( String jobName , LocalDateTime scanDate ) throws Exception { scanDate = scanDate . minus ( 2 , ChronoUnit . SECONDS ) ; FsJob fsJob = FsJob . builder ( ) . setName ( jobName ) . setLastrun ( scanDate ) . setIndexed ( stats . getNbDocScan ( ) ) . setDeleted ( stats . getNbDocDeleted ( ) ) . build ( ) ; fsJobFileHandler . write ( jobName , fsJob ) ; } | Update the job metadata |
27,884 | private void indexDirectory ( String path ) throws Exception { fr . pilato . elasticsearch . crawler . fs . beans . Path pathObject = new fr . pilato . elasticsearch . crawler . fs . beans . Path ( ) ; pathObject . setReal ( path ) ; String rootdir = path . substring ( 0 , path . lastIndexOf ( File . separator ) ) ; pathObject . setRoot ( SignTool . sign ( rootdir ) ) ; pathObject . setVirtual ( computeVirtualPathName ( stats . getRootPath ( ) , path ) ) ; indexDirectory ( SignTool . sign ( path ) , pathObject ) ; } | Index a directory |
27,885 | private void removeEsDirectoryRecursively ( final String path ) throws Exception { logger . debug ( "Delete folder [{}]" , path ) ; Collection < String > listFile = getFileDirectory ( path ) ; for ( String esfile : listFile ) { esDelete ( fsSettings . getElasticsearch ( ) . getIndex ( ) , SignTool . sign ( path . concat ( File . separator ) . concat ( esfile ) ) ) ; } Collection < String > listFolder = getFolderDirectory ( path ) ; for ( String esfolder : listFolder ) { removeEsDirectoryRecursively ( esfolder ) ; } esDelete ( fsSettings . getElasticsearch ( ) . getIndexFolder ( ) , SignTool . sign ( path ) ) ; } | Remove a full directory and sub dirs recursively |
27,886 | private void esIndex ( String index , String id , String json , String pipeline ) { logger . debug ( "Indexing {}/{}?pipeline={}" , index , id , pipeline ) ; logger . trace ( "JSon indexed : {}" , json ) ; if ( ! closed ) { esClient . index ( index , id , json , pipeline ) ; } else { logger . warn ( "trying to add new file while closing crawler. Document [{}]/[{}] has been ignored" , index , id ) ; } } | Add to bulk an IndexRequest in JSon format |
27,887 | private void esDelete ( String index , String id ) { logger . debug ( "Deleting {}/{}" , index , id ) ; if ( ! closed ) { esClient . delete ( index , id ) ; } else { logger . warn ( "trying to remove a file while closing crawler. Document [{}]/[{}] has been ignored" , index , id ) ; } } | Add to bulk a DeleteRequest |
27,888 | public void checkVersion ( ) throws IOException { ESVersion esVersion = getVersion ( ) ; if ( esVersion . major != compatibleVersion ( ) ) { throw new RuntimeException ( "The Elasticsearch client version [" + compatibleVersion ( ) + "] is not compatible with the Elasticsearch cluster version [" + esVersion . toString ( ) + "]." ) ; } if ( esVersion . minor < 4 ) { throw new RuntimeException ( "This version of FSCrawler is not compatible with " + "Elasticsearch version [" + esVersion . toString ( ) + "]. Please upgrade Elasticsearch to at least a 6.4.x version." ) ; } } | For Elasticsearch 6 we need to make sure we are running at least Elasticsearch 6 . 4 |
27,889 | public static void start ( FsSettings settings , ElasticsearchClient esClient ) { if ( httpServer == null ) { final ResourceConfig rc = new ResourceConfig ( ) . registerInstances ( new ServerStatusApi ( esClient , settings ) , new UploadApi ( settings , esClient ) ) . register ( MultiPartFeature . class ) . register ( RestJsonProvider . class ) . register ( JacksonFeature . class ) . register ( new CORSFilter ( settings . getRest ( ) ) ) . packages ( "fr.pilato.elasticsearch.crawler.fs.rest" ) ; httpServer = GrizzlyHttpServerFactory . createHttpServer ( URI . create ( settings . getRest ( ) . getUrl ( ) ) , rc ) ; logger . info ( "FS crawler Rest service started on [{}]" , settings . getRest ( ) . getUrl ( ) ) ; } } | Starts Grizzly HTTP server exposing JAX - RS resources defined in this application . |
27,890 | @ SuppressWarnings ( "deprecation" ) public boolean upgrade ( ) throws Exception { try { esClient . start ( ) ; } catch ( Exception t ) { logger . fatal ( "We can not start Elasticsearch Client. Exiting." , t ) ; return false ; } String index = settings . getElasticsearch ( ) . getIndex ( ) ; if ( esClient . isExistingIndex ( index ) ) { String indexFolder = settings . getElasticsearch ( ) . getIndexFolder ( ) ; boolean indexExists = esClient . isExistingIndex ( indexFolder ) ; long numberOfDocs = 0 ; if ( indexExists ) { ESSearchResponse responseFolder = esClient . search ( new ESSearchRequest ( ) . withIndex ( indexFolder ) ) ; numberOfDocs = responseFolder . getTotalHits ( ) ; } if ( numberOfDocs > 0 ) { logger . warn ( "[{}] already exists and is not empty. No upgrade needed." , indexFolder ) ; } else { logger . debug ( "[{}] can be upgraded." , index ) ; if ( ! indexExists ) { esClient . createIndices ( ) ; logger . info ( "[{}] has been created." , indexFolder ) ; } logger . info ( "Starting reindex folders..." ) ; int folders = esClient . reindex ( index , INDEX_TYPE_FOLDER , indexFolder ) ; logger . info ( "Done reindexing [{}] folders..." , folders ) ; logger . info ( "Starting removing folders from [{}]..." , index ) ; esClient . deleteByQuery ( index , INDEX_TYPE_FOLDER ) ; logger . info ( "Done removing folders from [{}]" , index ) ; logger . info ( "You can now upgrade your elasticsearch cluster to >=6.0.0!" ) ; return true ; } } else { logger . info ( "[{}] does not exist. No upgrade needed." , index ) ; } return false ; } | Upgrade FSCrawler indices |
27,891 | public static String getOwnerName ( final File file ) { try { final Path path = Paths . get ( file . getAbsolutePath ( ) ) ; final FileOwnerAttributeView ownerAttributeView = Files . getFileAttributeView ( path , FileOwnerAttributeView . class ) ; return ownerAttributeView != null ? ownerAttributeView . getOwner ( ) . getName ( ) : null ; } catch ( Exception e ) { logger . warn ( "Failed to determine 'owner' of {}: {}" , file , e . getMessage ( ) ) ; return null ; } } | Determines the owner of the file . |
27,892 | public static void copyDefaultResources ( Path configPath ) throws IOException { Path targetResourceDir = configPath . resolve ( "_default" ) ; for ( String filename : MAPPING_RESOURCES ) { Path target = targetResourceDir . resolve ( filename ) ; if ( Files . exists ( target ) ) { logger . debug ( "Mapping [{}] already exists" , filename ) ; } else { logger . debug ( "Copying [{}]..." , filename ) ; copyResourceFile ( CLASSPATH_RESOURCES_ROOT + filename , target ) ; } } } | Copy default resources files which are available as project resources under fr . pilato . elasticsearch . crawler . fs . _default package to a given configuration path under a _default sub directory . |
27,893 | public static void copyResourceFile ( String source , Path target ) throws IOException { InputStream resource = FsCrawlerUtil . class . getResourceAsStream ( source ) ; FileUtils . copyInputStreamToFile ( resource , target . toFile ( ) ) ; } | Copy a single resource file from the classpath or from a JAR . |
27,894 | public static Properties readPropertiesFromClassLoader ( String resource ) { Properties properties = new Properties ( ) ; try { properties . load ( FsCrawlerUtil . class . getClassLoader ( ) . getResourceAsStream ( resource ) ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } return properties ; } | Read a property file from the class loader |
27,895 | public static void copyDirs ( Path source , Path target , CopyOption ... options ) throws IOException { if ( Files . notExists ( target ) ) { Files . createDirectory ( target ) ; } logger . debug ( " , source ) ; if ( Files . notExists ( source ) ) { throw new RuntimeException ( source + " doesn't seem to exist." ) ; } Files . walkFileTree ( source , EnumSet . of ( FileVisitOption . FOLLOW_LINKS ) , Integer . MAX_VALUE , new InternalFileVisitor ( source , target , options ) ) ; logger . debug ( " , target ) ; } | Copy files from a source to a target under a _default sub directory . |
27,896 | public static void unzip ( String jarFile , Path destination ) throws IOException { Map < String , String > zipProperties = new HashMap < > ( ) ; zipProperties . put ( "create" , "false" ) ; zipProperties . put ( "encoding" , "UTF-8" ) ; URI zipFile = URI . create ( "jar:" + jarFile ) ; try ( FileSystem zipfs = FileSystems . newFileSystem ( zipFile , zipProperties ) ) { Path rootPath = zipfs . getPath ( "/" ) ; Files . walkFileTree ( rootPath , new SimpleFileVisitor < Path > ( ) { public FileVisitResult preVisitDirectory ( Path dir , BasicFileAttributes attrs ) throws IOException { Path targetPath = destination . resolve ( rootPath . relativize ( dir ) . toString ( ) ) ; if ( ! Files . exists ( targetPath ) ) { Files . createDirectory ( targetPath ) ; } return FileVisitResult . CONTINUE ; } public FileVisitResult visitFile ( Path file , BasicFileAttributes attrs ) throws IOException { Files . copy ( file , destination . resolve ( rootPath . relativize ( file ) . toString ( ) ) , StandardCopyOption . COPY_ATTRIBUTES , StandardCopyOption . REPLACE_EXISTING ) ; return FileVisitResult . CONTINUE ; } } ) ; } } | Unzip a jar file |
27,897 | public static boolean isFileSizeUnderLimit ( ByteSizeValue limit , long fileSizeAsBytes ) { boolean result = true ; if ( limit != null ) { ByteSizeValue fileSize = new ByteSizeValue ( fileSizeAsBytes ) ; int compare = fileSize . compareTo ( limit ) ; result = compare <= 0 ; logger . debug ( "Comparing file size [{}] with current limit [{}] -> {}" , fileSize , limit , result ? "under limit" : "above limit" ) ; } return result ; } | Compare if a file size is strictly under a given limit |
27,898 | private static Class < ElasticsearchClient > findClass ( int version ) throws ClassNotFoundException { String className = "fr.pilato.elasticsearch.crawler.fs.client.v" + version + ".ElasticsearchClientV" + version ; logger . trace ( "Trying to find a class named [{}]" , className ) ; Class < ? > aClass = Class . forName ( className ) ; boolean isImplementingInterface = ElasticsearchClient . class . isAssignableFrom ( aClass ) ; if ( ! isImplementingInterface ) { throw new IllegalArgumentException ( "Class " + className + " does not implement " + ElasticsearchClient . class . getName ( ) + " interface" ) ; } return ( Class < ElasticsearchClient > ) aClass ; } | Try to load an ElasticsearchClient class |
27,899 | public void setClassTag ( String tag , Class type ) { if ( tag == null ) throw new IllegalArgumentException ( "tag cannot be null." ) ; if ( type == null ) throw new IllegalArgumentException ( "type cannot be null." ) ; classNameToTag . put ( type . getName ( ) , tag ) ; tagToClass . put ( tag , type ) ; } | Allows the specified tag to be used in YAML instead of the full class name . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.