idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
7,600
public static double ComplementedIncomplete ( double a , double x ) { final double big = 4.503599627370496e15 ; final double biginv = 2.22044604925031308085e-16 ; double ans , ax , c , yc , r , t , y , z ; double pk , pkm1 , pkm2 , qk , qkm1 , qkm2 ; if ( x <= 0 || a <= 0 ) return 1.0 ; if ( x < 1.0 || x < a ) return 1.0 - Incomplete ( a , x ) ; ax = a * Math . log ( x ) - x - Log ( a ) ; if ( ax < - Constants . LogMax ) return 0.0 ; ax = Math . exp ( ax ) ; y = 1.0 - a ; z = x + y + 1.0 ; c = 0.0 ; pkm2 = 1.0 ; qkm2 = x ; pkm1 = x + 1.0 ; qkm1 = z * x ; ans = pkm1 / qkm1 ; do { c += 1.0 ; y += 1.0 ; z += 2.0 ; yc = y * c ; pk = pkm1 * z - pkm2 * yc ; qk = qkm1 * z - qkm2 * yc ; if ( qk != 0 ) { r = pk / qk ; t = Math . abs ( ( ans - r ) / r ) ; ans = r ; } else t = 1.0 ; pkm2 = pkm1 ; pkm1 = pk ; qkm2 = qkm1 ; qkm1 = qk ; if ( Math . abs ( pk ) > big ) { pkm2 *= biginv ; pkm1 *= biginv ; qkm2 *= biginv ; qkm1 *= biginv ; } } while ( t > Constants . DoubleEpsilon ) ; return ans * ax ; }
Complemented incomplete gamma function .
7,601
public static double Incomplete ( double a , double x ) { double ans , ax , c , r ; if ( x <= 0 || a <= 0 ) return 0.0 ; if ( x > 1.0 && x > a ) return 1.0 - ComplementedIncomplete ( a , x ) ; ax = a * Math . log ( x ) - x - Log ( a ) ; if ( ax < - Constants . LogMax ) return ( 0.0 ) ; ax = Math . exp ( ax ) ; r = a ; c = 1.0 ; ans = 1.0 ; do { r += 1.0 ; c *= x / r ; ans += c ; } while ( c / ans > Constants . DoubleEpsilon ) ; return ( ans * ax / a ) ; }
Incomplete gamma function .
7,602
public static double Log ( double x ) { double p , q , w , z ; double [ ] A = { 8.11614167470508450300E-4 , - 5.95061904284301438324E-4 , 7.93650340457716943945E-4 , - 2.77777777730099687205E-3 , 8.33333333333331927722E-2 } ; double [ ] B = { - 1.37825152569120859100E3 , - 3.88016315134637840924E4 , - 3.31612992738871184744E5 , - 1.16237097492762307383E6 , - 1.72173700820839662146E6 , - 8.53555664245765465627E5 } ; double [ ] C = { - 3.51815701436523470549E2 , - 1.70642106651881159223E4 , - 2.20528590553854454839E5 , - 1.13933444367982507207E6 , - 2.53252307177582951285E6 , - 2.01889141433532773231E6 } ; if ( x < - 34.0 ) { q = - x ; w = Log ( q ) ; p = Math . floor ( q ) ; if ( p == q ) { try { throw new ArithmeticException ( "Overflow." ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } z = q - p ; if ( z > 0.5 ) { p += 1.0 ; z = p - q ; } z = q * Math . sin ( Math . PI * z ) ; if ( z == 0.0 ) { try { throw new ArithmeticException ( "Overflow." ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } z = Constants . LogPI - Math . log ( z ) - w ; return z ; } if ( x < 13.0 ) { z = 1.0 ; while ( x >= 3.0 ) { x -= 1.0 ; z *= x ; } while ( x < 2.0 ) { if ( x == 0.0 ) { try { throw new ArithmeticException ( "Overflow." ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } z /= x ; x += 1.0 ; } if ( z < 0.0 ) z = - z ; if ( x == 2.0 ) return Math . log ( z ) ; x -= 2.0 ; p = x * Special . Polevl ( x , B , 5 ) / Special . P1evl ( x , C , 6 ) ; return ( Math . log ( z ) + p ) ; } if ( x > 2.556348e305 ) { try { throw new ArithmeticException ( "Overflow." ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } q = ( x - 0.5 ) * Math . log ( x ) - x + 0.91893853320467274178 ; if ( x > 1.0e8 ) return ( q ) ; p = 1.0 / ( x * x ) ; if ( x >= 1000.0 ) { q += ( ( 7.9365079365079365079365e-4 * p - 2.7777777777777777777778e-3 ) * p + 0.0833333333333333333333 ) / x ; } else { q += Special . Polevl ( p , A , 4 ) / x ; } return q ; }
Natural logarithm of gamma function .
7,603
public void Forward ( ImageSource fastBitmap ) { this . width = fastBitmap . getWidth ( ) ; this . height = fastBitmap . getHeight ( ) ; if ( ! isTransformed ) { if ( fastBitmap . isGrayscale ( ) ) { if ( Tools . isPowerOf2 ( width ) && Tools . isPowerOf2 ( height ) ) { data = new double [ height ] [ width ] ; for ( int i = 0 ; i < height ; i ++ ) { for ( int j = 0 ; j < width ; j ++ ) { data [ i ] [ j ] = Tools . Scale ( 0 , 255 , 0 , 1 , fastBitmap . getRGB ( i , j ) ) ; } } DiscreteCosineTransform . Forward ( data ) ; isTransformed = true ; } else { try { throw new IllegalArgumentException ( "Image width and height should be power of 2." ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } } else { try { throw new IllegalArgumentException ( "Only grayscale images are supported." ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } } }
Applies forward Cosine transformation to an image .
7,604
public ImageSource toFastBitmap ( ) { OneBandSource l = new OneBandSource ( width , height ) ; PowerSpectrum ( ) ; double max = Math . log ( PowerMax + 1.0 ) ; double scale = 1.0 ; if ( scaleValue > 0 ) scale = scaleValue / max ; for ( int i = 0 ; i < height ; i ++ ) { for ( int j = 0 ; j < width ; j ++ ) { double p = Power [ i ] [ j ] ; double plog = Math . log ( p + 1.0 ) ; l . setRGB ( i , j , ( int ) ( plog * scale * 255 ) ) ; } } return l ; }
Convert image s data to FastBitmap .
7,605
private void PowerSpectrum ( ) { Power = new double [ data . length ] [ data [ 0 ] . length ] ; PowerMax = 0 ; for ( int i = 0 ; i < data . length ; i ++ ) { for ( int j = 0 ; j < data [ 0 ] . length ; j ++ ) { double p = data [ i ] [ j ] ; if ( p < 0 ) p = - p ; Power [ i ] [ j ] = p ; if ( p > PowerMax ) PowerMax = p ; } } }
compute the Power Spectrum ;
7,606
public ImageSource apply ( ImageSource input ) { int w = input . getWidth ( ) ; int h = input . getHeight ( ) ; MatrixSource output = new MatrixSource ( w , h ) ; Vector3 s = new Vector3 ( 1 , 0 , 0 ) ; Vector3 t = new Vector3 ( 0 , 1 , 0 ) ; for ( int y = 0 ; y < h ; y ++ ) { for ( int x = 0 ; x < w ; x ++ ) { if ( x < border || x == w - border || y < border || y == h - border ) { output . setRGB ( x , y , VectorHelper . Z_NORMAL ) ; continue ; } float dh = input . getR ( x + 1 , y ) - input . getR ( x - 1 , y ) ; float dv = input . getR ( x , y + 1 ) - input . getR ( x , y - 1 ) ; s . set ( scale , 0 , dh ) ; t . set ( 0 , scale , dv ) ; Vector3 cross = s . crs ( t ) . nor ( ) ; int rgb = VectorHelper . vectorToColor ( cross ) ; output . setRGB ( x , y , rgb ) ; } } return new MatrixSource ( output ) ; }
Simple method to generate bump map from a height map
7,607
public Vector3 findClosePoint ( Vector3 pointToDelete ) { Triangle triangle = find ( pointToDelete ) ; Vector3 p1 = triangle . p1 ( ) ; Vector3 p2 = triangle . p2 ( ) ; double d1 = distanceXY ( p1 , pointToDelete ) ; double d2 = distanceXY ( p2 , pointToDelete ) ; if ( triangle . isHalfplane ( ) ) { if ( d1 <= d2 ) { return p1 ; } else { return p2 ; } } else { Vector3 p3 = triangle . p3 ( ) ; double d3 = distanceXY ( p3 , pointToDelete ) ; if ( d1 <= d2 && d1 <= d3 ) { return p1 ; } else if ( d2 <= d1 && d2 <= d3 ) { return p2 ; } else { return p3 ; } } }
return a point from the trangulation that is close to pointToDelete
7,608
public List < Triangle > findTriangleNeighborhood ( Triangle firstTriangle , Vector3 point ) { List < Triangle > triangles = new ArrayList < Triangle > ( 30 ) ; triangles . add ( firstTriangle ) ; Triangle prevTriangle = null ; Triangle currentTriangle = firstTriangle ; Triangle nextTriangle = currentTriangle . nextNeighbor ( point , prevTriangle ) ; while ( ! nextTriangle . equals ( firstTriangle ) ) { if ( nextTriangle . isHalfplane ( ) ) { return null ; } triangles . add ( nextTriangle ) ; prevTriangle = currentTriangle ; currentTriangle = nextTriangle ; nextTriangle = currentTriangle . nextNeighbor ( point , prevTriangle ) ; } return triangles ; }
changed to public by Udi
7,609
private Iterator < Vector3 > getConvexHullVerticesIterator ( ) { List < Vector3 > ans = new ArrayList < Vector3 > ( ) ; Triangle curr = this . startTriangleHull ; boolean cont = true ; double x0 = bbMin . x , x1 = bbMax . x ; double y0 = bbMin . y , y1 = bbMax . y ; boolean sx , sy ; while ( cont ) { sx = curr . p1 ( ) . x == x0 || curr . p1 ( ) . x == x1 ; sy = curr . p1 ( ) . y == y0 || curr . p1 ( ) . y == y1 ; if ( ( sx && sy ) || ( ! sx && ! sy ) ) { ans . add ( curr . p1 ( ) ) ; } if ( curr . bcnext != null && curr . bcnext . halfplane ) curr = curr . bcnext ; if ( curr == this . startTriangleHull ) cont = false ; } return ans . iterator ( ) ; }
returns an iterator to the set of all the points on the XY - convex hull
7,610
public RotateOperation angle ( double angle ) { this . angle = angle ; double angleRad = - angle * Math . PI / 180 ; angleCos = Math . cos ( angleRad ) ; angleSin = Math . sin ( angleRad ) ; return this ; }
Set Angle .
7,611
public RotateOperation fillColor ( int red , int green , int blue ) { this . fillRed = red ; this . fillGreen = green ; this . fillBlue = blue ; return this ; }
Set Fill color .
7,612
public int [ ] makeLut ( ) { int numKnots = x . length ; float [ ] nx = new float [ numKnots + 2 ] ; float [ ] ny = new float [ numKnots + 2 ] ; System . arraycopy ( x , 0 , nx , 1 , numKnots ) ; System . arraycopy ( y , 0 , ny , 1 , numKnots ) ; nx [ 0 ] = nx [ 1 ] ; ny [ 0 ] = ny [ 1 ] ; nx [ numKnots + 1 ] = nx [ numKnots ] ; ny [ numKnots + 1 ] = ny [ numKnots ] ; int [ ] table = new int [ 256 ] ; for ( int i = 0 ; i < 1024 ; i ++ ) { float f = i / 1024.0f ; int x = ( int ) ( 255 * Curve . Spline ( f , nx . length , nx ) + 0.5f ) ; int y = ( int ) ( 255 * Curve . Spline ( f , nx . length , ny ) + 0.5f ) ; x = x > 255 ? 255 : x ; x = x < 0 ? 0 : x ; y = y > 255 ? 255 : y ; y = y < 0 ? 0 : y ; table [ x ] = y ; } return table ; }
Create LUT .
7,613
public static float Spline ( float x , int numKnots , float [ ] knots ) { int span ; int numSpans = numKnots - 3 ; float k0 , k1 , k2 , k3 ; float c0 , c1 , c2 , c3 ; if ( numSpans < 1 ) throw new IllegalArgumentException ( "Too few knots in spline" ) ; x = x > 1 ? 1 : x ; x = x < 0 ? 0 : x ; x *= numSpans ; span = ( int ) x ; if ( span > numKnots - 4 ) span = numKnots - 4 ; x -= span ; k0 = knots [ span ] ; k1 = knots [ span + 1 ] ; k2 = knots [ span + 2 ] ; k3 = knots [ span + 3 ] ; c3 = - 0.5f * k0 + 1.5f * k1 + - 1.5f * k2 + 0.5f * k3 ; c2 = 1f * k0 + - 2.5f * k1 + 2f * k2 + - 0.5f * k3 ; c1 = - 0.5f * k0 + 0f * k1 + 0.5f * k2 + 0f * k3 ; c0 = 0f * k0 + 1f * k1 + 0f * k2 + 0f * k3 ; return ( ( c3 * x + c2 ) * x + c1 ) * x + c0 ; }
compute a Catmull - Rom spline .
7,614
public static float Spline ( float x , int numKnots , int [ ] xknots , int [ ] yknots ) { int span ; int numSpans = numKnots - 3 ; float k0 , k1 , k2 , k3 ; float c0 , c1 , c2 , c3 ; if ( numSpans < 1 ) throw new IllegalArgumentException ( "Too few knots in spline" ) ; for ( span = 0 ; span < numSpans ; span ++ ) if ( xknots [ span + 1 ] > x ) break ; if ( span > numKnots - 3 ) span = numKnots - 3 ; float t = ( float ) ( x - xknots [ span ] ) / ( xknots [ span + 1 ] - xknots [ span ] ) ; span -- ; if ( span < 0 ) { span = 0 ; t = 0 ; } k0 = yknots [ span ] ; k1 = yknots [ span + 1 ] ; k2 = yknots [ span + 2 ] ; k3 = yknots [ span + 3 ] ; c3 = - 0.5f * k0 + 1.5f * k1 + - 1.5f * k2 + 0.5f * k3 ; c2 = 1f * k0 + - 2.5f * k1 + 2f * k2 + - 0.5f * k3 ; c1 = - 0.5f * k0 + 0f * k1 + 0.5f * k2 + 0f * k3 ; c0 = 0f * k0 + 1f * k1 + 0f * k2 + 0f * k3 ; return ( ( c3 * t + c2 ) * t + c1 ) * t + c0 ; }
compute a Catmull - Rom spline but with variable knot spacing .
7,615
public static Predicate < Event < ? , ? > > withListenerClass ( Class < ? extends Listener > cls ) { if ( cls == null ) { throw new IllegalArgumentException ( "cls is null" ) ; } return event -> event . getListenerClass ( ) == cls ; }
Creates a predicate that matches events for the given listener class .
7,616
public static float fieldOfView ( float focalLength , float sensorWidth ) { double fov = 2 * Math . atan ( .5 * sensorWidth / focalLength ) ; return ( float ) Math . toDegrees ( fov ) ; }
Calculate the FOV of camera using focalLength and sensorWidth
7,617
private static int [ ] gammaLUT ( double gammaValue ) { int [ ] gammaLUT = new int [ 256 ] ; for ( int i = 0 ; i < gammaLUT . length ; i ++ ) { gammaLUT [ i ] = ( int ) ( 255 * ( Math . pow ( ( double ) i / ( double ) 255 , gammaValue ) ) ) ; } return gammaLUT ; }
Create the gamma correction lookup table
7,618
public static double Log ( double a , double b ) { return Gamma . Log ( a ) + Gamma . Log ( b ) - Gamma . Log ( a + b ) ; }
Natural logarithm of the Beta function .
7,619
public static void DFT ( ComplexNumber [ ] data , Direction direction ) { int n = data . length ; ComplexNumber [ ] c = new ComplexNumber [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { c [ i ] = new ComplexNumber ( 0 , 0 ) ; double sumRe = 0 ; double sumIm = 0 ; double phim = 2 * Math . PI * i / n ; for ( int j = 0 ; j < n ; j ++ ) { double gRe = data [ j ] . real ; double gIm = data [ j ] . imaginary ; double cosw = Math . cos ( phim * j ) ; double sinw = Math . sin ( phim * j ) ; if ( direction == Direction . Backward ) sinw = - sinw ; sumRe += ( gRe * cosw + data [ j ] . imaginary * sinw ) ; sumIm += ( gIm * cosw - data [ j ] . real * sinw ) ; } c [ i ] = new ComplexNumber ( sumRe , sumIm ) ; } if ( direction == Direction . Backward ) { for ( int i = 0 ; i < c . length ; i ++ ) { data [ i ] . real = c [ i ] . real / n ; data [ i ] . imaginary = c [ i ] . imaginary / n ; } } else { for ( int i = 0 ; i < c . length ; i ++ ) { data [ i ] . real = c [ i ] . real ; data [ i ] . imaginary = c [ i ] . imaginary ; } } }
1 - D Discrete Fourier Transform .
7,620
public static void DFT2 ( ComplexNumber [ ] [ ] data , Direction direction ) { int n = data . length ; int m = data [ 0 ] . length ; ComplexNumber [ ] row = new ComplexNumber [ Math . max ( m , n ) ] ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) row [ j ] = data [ i ] [ j ] ; FourierTransform . DFT ( row , direction ) ; for ( int j = 0 ; j < n ; j ++ ) data [ i ] [ j ] = row [ j ] ; } ComplexNumber [ ] col = new ComplexNumber [ n ] ; for ( int j = 0 ; j < n ; j ++ ) { for ( int i = 0 ; i < n ; i ++ ) col [ i ] = data [ i ] [ j ] ; FourierTransform . DFT ( col , direction ) ; for ( int i = 0 ; i < n ; i ++ ) data [ i ] [ j ] = col [ i ] ; } }
2 - D Discrete Fourier Transform .
7,621
public static void FFT ( ComplexNumber [ ] data , Direction direction ) { double [ ] real = ComplexNumber . getReal ( data ) ; double [ ] img = ComplexNumber . getImaginary ( data ) ; if ( direction == Direction . Forward ) FFT ( real , img ) ; else FFT ( img , real ) ; if ( direction == Direction . Forward ) { for ( int i = 0 ; i < real . length ; i ++ ) { data [ i ] = new ComplexNumber ( real [ i ] , img [ i ] ) ; } } else { int n = real . length ; for ( int i = 0 ; i < n ; i ++ ) { data [ i ] = new ComplexNumber ( real [ i ] / n , img [ i ] / n ) ; } } }
1 - D Fast Fourier Transform .
7,622
public static void FFT2 ( ComplexNumber [ ] [ ] data , Direction direction ) { int n = data . length ; int m = data [ 0 ] . length ; for ( int i = 0 ; i < n ; i ++ ) { ComplexNumber [ ] row = data [ i ] ; FourierTransform . FFT ( row , direction ) ; for ( int j = 0 ; j < m ; j ++ ) data [ i ] [ j ] = row [ j ] ; } ComplexNumber [ ] col = new ComplexNumber [ n ] ; for ( int j = 0 ; j < m ; j ++ ) { for ( int i = 0 ; i < n ; i ++ ) col [ i ] = data [ i ] [ j ] ; FourierTransform . FFT ( col , direction ) ; for ( int i = 0 ; i < n ; i ++ ) data [ i ] [ j ] = col [ i ] ; } }
2 - D Fast Fourier Transform .
7,623
public ImageSource BFS ( int startI , int startJ , ImageSource originalImage ) { LinkedList < Vector2i > queue = new LinkedList < > ( ) ; int gapX = 30 ; int gapY = 30 ; MatrixSource letter = new MatrixSource ( letterWidth , letterHeight ) ; int alpha = originalImage . getA ( startI , startJ ) ; int white = ColorHelper . getARGB ( 255 , 255 , 255 , alpha ) ; int black = ColorHelper . getARGB ( 0 , 0 , 0 , alpha ) ; for ( int j = 0 ; j < letterHeight ; j ++ ) { for ( int i = 0 ; i < letterWidth ; i ++ ) { letter . setRGB ( i , j , white ) ; } } int count = 0 ; Vector2i positions = new Vector2i ( startI , startJ ) ; visited [ startI ] [ startJ ] = true ; queue . addLast ( positions ) ; while ( ! queue . isEmpty ( ) ) { Vector2i pos = queue . removeFirst ( ) ; int x = pos . getX ( ) ; int y = pos . getY ( ) ; visited [ x ] [ y ] = true ; int posX = startI - x + gapX ; int posY = startJ - y + gapY ; count ++ ; if ( posX >= originalImage . getWidth ( ) || posY >= originalImage . getHeight ( ) ) { continue ; } else { letter . setRGB ( posX , posY , black ) ; } for ( int i = x - 1 ; i <= x + 1 ; i ++ ) { for ( int j = y - 1 ; j <= y + 1 ; j ++ ) { if ( i >= 0 && j >= 0 && i < originalImage . getWidth ( ) && j < originalImage . getHeight ( ) ) { if ( ! visited [ i ] [ j ] ) { int color = originalImage . getGray ( i , j ) ; if ( color < 10 ) { visited [ i ] [ j ] = true ; Vector2i tmpPos = new Vector2i ( i , j ) ; queue . addLast ( tmpPos ) ; } } } } } } System . out . println ( "count = " + count ) ; if ( count < 3 ) { return letter ; } return letter ; }
Breadth first search
7,624
public FloatPoint Subtract ( FloatPoint point1 , FloatPoint point2 ) { FloatPoint result = new FloatPoint ( point1 ) ; result . Subtract ( point2 ) ; return result ; }
Subtracts values of two points .
7,625
public FloatPoint Divide ( FloatPoint point1 , FloatPoint point2 ) { FloatPoint result = new FloatPoint ( point1 ) ; result . Divide ( point2 ) ; return result ; }
Divide values of two points .
7,626
public void setCurve ( Curve curveRed , Curve curveGreen , Curve curveBlue ) { this . curveRed = curveRed ; this . curveGreen = curveGreen ; this . curveBlue = curveBlue ; }
Set curves .
7,627
private void writeStringNoTag ( String value ) throws IOException { writeIntegerNoTag ( value . length ( ) ) ; for ( int i = 0 , n = value . length ( ) ; i < n ; i ++ ) { char c = value . charAt ( i ) ; if ( c <= 0x007f ) { out . write ( ( byte ) c ) ; } else if ( c > 0x07ff ) { out . write ( ( byte ) ( 0xe0 | c >> 12 & 0x0f ) ) ; out . write ( ( byte ) ( 0x80 | c >> 6 & 0x3f ) ) ; out . write ( ( byte ) ( 0x80 | c >> 0 & 0x3f ) ) ; } else { out . write ( ( byte ) ( 0xc0 | c >> 6 & 0x1f ) ) ; out . write ( ( byte ) ( 0x80 | c >> 0 & 0x3f ) ) ; } } }
Write a string to the output without tagging that its actually a string .
7,628
public static int indexOf ( final String input , final char delim , final int fromIndex ) { if ( input == null ) return - 1 ; int index = input . indexOf ( delim , fromIndex ) ; if ( index != 0 ) { while ( index != - 1 && index != ( input . length ( ) - 1 ) ) { if ( input . charAt ( index - 1 ) != '\\' ) break ; index = input . indexOf ( delim , index + 1 ) ; } } return index ; }
Gets the first index of a character after fromIndex . Ignoring characters that have been escaped
7,629
public static int lastIndexOf ( final String input , final char delim ) { return input == null ? - 1 : lastIndexOf ( input , delim , input . length ( ) ) ; }
Gets the last index of a character ignoring characters that have been escaped
7,630
public static int lastIndexOf ( final String input , final char delim , final int fromIndex ) { if ( input == null ) return - 1 ; int index = input . lastIndexOf ( delim , fromIndex ) ; while ( index != - 1 && index != 0 ) { if ( input . charAt ( index - 1 ) != '\\' ) break ; index = input . lastIndexOf ( delim , index - 1 ) ; } return index ; }
Gets the last index of a character starting at fromIndex . Ignoring characters that have been escaped
7,631
public static boolean isAlphanumeric ( final String input ) { for ( int i = 0 ; i < input . length ( ) ; i ++ ) { if ( ! Character . isLetterOrDigit ( input . charAt ( i ) ) ) return false ; } return true ; }
Checks to see if a string entered is alpha numeric
7,632
public static String convertToRegexString ( final String input ) { return input . replaceAll ( "\\\\" , "\\\\" ) . replaceAll ( "\\*" , "\\*" ) . replaceAll ( "\\+" , "\\+" ) . replaceAll ( "\\]" , "\\]" ) . replaceAll ( "\\[" , "\\[" ) . replaceAll ( "\\(" , "\\(" ) . replaceAll ( "\\)" , "\\)" ) . replaceAll ( "\\?" , "\\?" ) . replaceAll ( "\\$" , "\\$" ) . replaceAll ( "\\|" , "\\|" ) . replaceAll ( "\\^" , "\\^" ) . replaceAll ( "\\." , "\\." ) ; }
Converts a string so that it can be used in a regular expression .
7,633
public static double similarLevenshtein ( String s1 , String s2 ) { if ( s1 . equals ( s2 ) ) { return 1.0 ; } if ( s1 . length ( ) < s2 . length ( ) ) { String swap = s1 ; s1 = s2 ; s2 = swap ; } int bigLength = s1 . length ( ) ; return ( bigLength - StringUtils . getLevenshteinDistance ( s2 , s1 ) ) / ( double ) bigLength ; }
Checks to see how similar two strings are using the Levenshtein distance algorithm .
7,634
public static double similarDamerauLevenshtein ( String s1 , String s2 ) { if ( s1 . equals ( s2 ) ) { return 1.0 ; } if ( s1 . length ( ) < s2 . length ( ) ) { String swap = s1 ; s1 = s2 ; s2 = swap ; } int bigLength = s1 . length ( ) ; return ( bigLength - getDamerauLevenshteinDistance ( s2 , s1 ) ) / ( double ) bigLength ; }
Checks to see how similar two strings are using the Damerau - Levenshtein distance algorithm .
7,635
public static boolean isStringNullOrEmpty ( final String input ) { if ( input == null || input . trim ( ) . isEmpty ( ) ) { return true ; } return false ; }
Test to see if a String is null or contains only whitespace .
7,636
public Service getService ( String name ) { Service service = store . get ( name ) ; if ( service == null ) { throw HttpException . notFound ( "Service not found for name '" + name + "'" ) ; } return service ; }
returns a copy of all the services including the disabled ones
7,637
private < T > void preFlightCheckMethods ( final T target , final List < Method > methods ) { methods . forEach ( m -> { m . setAccessible ( true ) ; try { m . invoke ( target ) ; } catch ( IllegalAccessException | InvocationTargetException e ) { throw new RuntimeException ( e ) ; } } ) ; }
Invokes all methods in the list on the target .
7,638
private void injectParameters ( Object target , Map < String , Option > options ) { ClassStreams . selfAndSupertypes ( target . getClass ( ) ) . forEach ( type -> { for ( Field f : type . getDeclaredFields ( ) ) { Optional . ofNullable ( f . getAnnotation ( CliOption . class ) ) . ifPresent ( opt -> populate ( f , target , getEffectiveValue ( options , opt ) ) ) ; Optional . ofNullable ( f . getAnnotation ( CliOptionGroup . class ) ) . ifPresent ( opt -> populate ( f , target , options ) ) ; } } ) ; }
Inject parameter values from the map of options .
7,639
private String getEffectiveValue ( Map < String , Option > options , CliOption opt ) { final String shortOpt = opt . value ( ) ; if ( opt . hasArg ( ) ) { if ( options . containsKey ( shortOpt ) ) { return options . get ( shortOpt ) . getValue ( ) ; } return opt . defaultValue ( ) ; } return Boolean . toString ( options . containsKey ( opt . value ( ) ) ) ; }
Returns the effective value for the specified option .
7,640
private Map < String , Option > toMap ( CommandLine cl ) { final Map < String , Option > opts = new HashMap < > ( ) ; for ( Option opt : cl . getOptions ( ) ) { opts . put ( opt . getOpt ( ) , opt ) ; } return opts ; }
Creates a map of option short - names to the corresponding option instance .
7,641
public static Collection < byte [ ] > getKeyBytes ( Collection < String > keys ) { Collection < byte [ ] > rv = new ArrayList < byte [ ] > ( keys . size ( ) ) ; for ( String s : keys ) { rv . add ( getKeyBytes ( s ) ) ; } return rv ; }
Get the keys in byte form for all of the string keys .
7,642
public static Map < String , Object > resolve ( Map < String , Object > root ) { Map < String , Object > newRoot = new HashMap < String , Object > ( ) ; resolve ( newRoot , root , "" ) ; return newRoot ; }
Resolve the specified map and return the resolved map .
7,643
public static Map < String , Object > resolveTo ( Map < String , Object > root , Map < String , Object > target ) { resolve ( target , root , "" ) ; return target ; }
Resolve the specified map and store it in the specified target .
7,644
public final void debugf ( Throwable cause , String message , Object ... args ) { logf ( Level . DEBUG , cause , message , args ) ; }
Logs a formatted message and stack trace if DEBUG logging is enabled .
7,645
public final void debugf ( String message , Object ... args ) { logf ( Level . DEBUG , null , message , args ) ; }
Logs a formatted message if DEBUG logging is enabled .
7,646
public final void infof ( Throwable cause , String message , Object ... args ) { logf ( Level . INFO , cause , message , args ) ; }
Logs a formatted message and stack trace if INFO logging is enabled .
7,647
public final void infof ( String message , Object ... args ) { logf ( Level . INFO , null , message , args ) ; }
Logs a formatted message if INFO logging is enabled .
7,648
public final void warnf ( Throwable cause , String message , Object ... args ) { logf ( Level . WARN , cause , message , args ) ; }
Logs a formatted message and stack trace if WARN logging is enabled .
7,649
public final void warnf ( String message , Object ... args ) { logf ( Level . WARN , null , message , args ) ; }
Logs a formatted message if WARN logging is enabled .
7,650
public final void errorf ( Throwable cause , String message , Object ... args ) { logf ( Level . ERROR , cause , message , args ) ; }
Logs a formatted message and stack trace if ERROR logging is enabled .
7,651
public final void errorf ( String message , Object ... args ) { logf ( Level . ERROR , null , message , args ) ; }
Logs a formatted message if ERROR logging is enabled .
7,652
public final void infoDebugf ( final Throwable cause , final String message , final Object ... args ) { logDebugf ( Level . INFO , cause , message , args ) ; }
Logs a formatted message and stack trace if DEBUG logging is enabled or a formatted message and exception description if INFO logging is enabled .
7,653
public final void infoDebug ( final Throwable cause , final String message ) { logDebug ( Level . INFO , cause , message ) ; }
Logs a message and stack trace if DEBUG logging is enabled or a formatted message and exception description if INFO logging is enabled .
7,654
public final void warnDebugf ( final Throwable cause , final String message , final Object ... args ) { logDebugf ( Level . WARN , cause , message , args ) ; }
Logs a formatted message and stack trace if DEBUG logging is enabled or a formatted message and exception description if WARN logging is enabled .
7,655
public final void warnDebug ( final Throwable cause , final String message ) { logDebug ( Level . WARN , cause , message ) ; }
Logs a message and stack trace if DEBUG logging is enabled or a formatted message and exception description if WARN logging is enabled .
7,656
public final void errorDebugf ( final Throwable cause , final String message , final Object ... args ) { logDebugf ( Level . ERROR , cause , message , args ) ; }
Logs a formatted message and stack trace if DEBUG logging is enabled or a formatted message and exception description if ERROR logging is enabled .
7,657
public final void errorDebug ( final Throwable cause , final String message ) { logDebug ( Level . ERROR , cause , message ) ; }
Logs a message and stack trace if DEBUG logging is enabled or a formatted message and exception description if ERROR logging is enabled .
7,658
public static Method bestMatchingMethod ( Collection < Method > methods , String methodName , Class [ ] types ) { if ( methods == null || StringUtils . isNullOrBlank ( methodName ) || types == null ) { return null ; } for ( Method method : methods ) { if ( method . getName ( ) . equals ( methodName ) && typesMatch ( method . getParameterTypes ( ) , types ) ) { return method ; } } return null ; }
Finds the best Method match for a given method name and types against a collection of methods .
7,659
public static Class [ ] getTypes ( Object ... args ) { if ( args . length == 0 ) { return new Class [ 0 ] ; } Class [ ] types = new Class [ args . length ] ; for ( int i = 0 ; i < args . length ; i ++ ) { types [ i ] = args [ i ] == null ? Object . class : args [ i ] . getClass ( ) ; } return types ; }
Gets the types for an array of objects
7,660
@ SuppressWarnings ( "unchecked" ) public static boolean typesMatch ( Class < ? > [ ] c1 , Class [ ] c2 ) { if ( c1 . length != c2 . length ) { return false ; } for ( int i = 0 ; i < c1 . length ; i ++ ) { if ( ! inSameHierarchy ( c1 [ i ] , c2 [ i ] ) && ! isConvertible ( c1 [ i ] , c2 [ i ] ) ) { return false ; } } return true ; }
Determines if the two given arrays of class are compatible with one another .
7,661
private HttpResponse execute ( HttpClient client , HttpUriRequest request ) throws IOException { if ( localContext != null ) { return client . execute ( request , localContext ) ; } else { return client . execute ( request ) ; } }
executes a request with the localContext if set
7,662
public static < K , V > LRUMap < K , V > create ( int maxSize ) { Preconditions . checkArgument ( maxSize > 0 , "Max size must be greater than zero." ) ; return new LRUMap < > ( maxSize ) ; }
Creates a new LRU Map .
7,663
public static Tailer create ( final File file , final TailerListener listener ) { return Tailer . create ( file , listener , Tailer . DEFAULT_DELAY_MILLIS , false ) ; }
Creates and starts a Tailer for the given file starting at the beginning of the file with the default delay of 1 . 0s
7,664
public static Tailer create ( final File file , final TailerListener listener , final long delayMillis , final boolean end ) { return Tailer . create ( file , listener , delayMillis , end , Tailer . DEFAULT_BUFSIZE ) ; }
Creates and starts a Tailer for the given file with default buffer size .
7,665
public void run ( ) { final ScheduledFuture < ? > future = this . executor . scheduleWithFixedDelay ( this . scheduled , 0 , this . delayMillis , TimeUnit . MILLISECONDS ) ; try { this . runTrigger . await ( ) ; } catch ( final InterruptedException e ) { this . listener . handle ( e ) ; } finally { future . cancel ( true ) ; this . scheduled . cleanup ( ) ; this . executor . shutdownNow ( ) ; this . listener . destroy ( ) ; } }
Follows changes in the file calling the TailerListener s handle method for each new line .
7,666
public static Set < String > references ( final String value ) { final HashSet < String > names = new HashSet < String > ( ) ; if ( ( value == null ) || ( value . length ( ) == 0 ) ) { return names ; } int end = - 1 ; int from = 0 ; int start = - 1 ; while ( ( start = value . indexOf ( "${" , from ) ) > - 1 ) { end = value . indexOf ( '}' , start + 1 ) ; if ( end == - 1 ) { from = value . length ( ) ; } else { names . add ( value . substring ( start + 2 , end ) ) ; from = end + 1 ; } } return names ; }
Returns a set of references variables .
7,667
public static void get ( String url , HttpConsumer < HttpExchange > endpoint , MediaTypes ... mediaTypes ) { addResource ( Methods . GET , url , endpoint , mediaTypes ) ; }
Define a REST endpoint mapped to HTTP GET
7,668
public static void post ( String url , HttpConsumer < HttpExchange > endpoint , MediaTypes ... mediaTypes ) { addResource ( Methods . POST , url , endpoint , mediaTypes ) ; }
Define a REST endpoint mapped to HTTP POST
7,669
public static void put ( String url , HttpConsumer < HttpExchange > endpoint , MediaTypes ... mediaTypes ) { addResource ( Methods . PUT , url , endpoint , mediaTypes ) ; }
Define a REST endpoint mapped to HTTP PUT
7,670
public static void delete ( String url , HttpConsumer < HttpExchange > endpoint , MediaTypes ... mediaTypes ) { addResource ( Methods . DELETE , url , endpoint , mediaTypes ) ; }
Define a REST endpoint mapped to HTTP DELETE
7,671
public static void options ( String url , HttpConsumer < HttpExchange > endpoint , MediaTypes ... mediaTypes ) { addResource ( Methods . OPTIONS , url , endpoint , mediaTypes ) ; }
Define a REST endpoint mapped to HTTP OPTIONS
7,672
public static synchronized void websocket ( String url , AbstractReceiveListener endpoint ) { checkStarted ( ) ; instance ( ) . endpoints . add ( HandlerUtil . websocket ( url , endpoint ) ) ; }
Define a Websocket endpoint . Supports path variables
7,673
public static synchronized void websocket ( String url , BiConsumer < WebSocketChannel , BufferedTextMessage > onMessage ) { checkStarted ( ) ; instance ( ) . endpoints . add ( HandlerUtil . websocket ( url , new WebsocketEndpoint ( ) { public void onConnect ( WebSocketHttpExchange exchange , WebSocketChannel channel ) { } protected void onFullTextMessage ( WebSocketChannel channel , BufferedTextMessage message ) throws IOException { onMessage . accept ( channel , message ) ; } } ) ) ; }
A simplified Websocket endpoint . Supports path variables
7,674
public static synchronized void staticFiles ( String url , String docPath ) { checkStarted ( ) ; instance ( ) . endpoints . add ( HandlerUtil . staticFiles ( url , docPath ) ) ; }
Serve static files from a given url . Path variables are not supported .
7,675
private void exportDefaultProperties ( ) { AppProperties . set ( PropertyKey . HTTP_PORT , String . valueOf ( this . port ) ) ; AppProperties . set ( PropertyKey . ADMIN_HTTP_PORT , String . valueOf ( this . adminManager . getPort ( ) ) ) ; }
sets the properties that are may be useful outside the application
7,676
public void open ( ) { Futures . transform ( lcm , new Subscribe ( subscriber ) ) ; publishTask = Futures . transform ( lcm , publisher ) ; }
Starts the publish and subscribe tasks
7,677
public void close ( ) { Futures . transform ( lcm , new Unsubscribe ( subscriber ) ) ; subscriber . clear ( ) ; publishTask . cancel ( true ) ; }
Stops the publish and subscribe tasks
7,678
public NDArrayDoubles deepCopy ( ) { int [ ] dimensions = new int [ this . dimensions . length ] ; System . arraycopy ( this . dimensions , 0 , dimensions , 0 , this . dimensions . length ) ; double [ ] values = new double [ this . values . length ] ; System . arraycopy ( this . values , 0 , values , 0 , this . values . length ) ; return new NDArrayDoubles ( dimensions , values ) ; }
Copy this array .
7,679
public void setAssignmentValue ( int [ ] assignment , double value ) { assert ! Double . isNaN ( value ) ; values [ getTableAccessOffset ( assignment ) ] = value ; }
Set a single value in the factor table .
7,680
public boolean valueEquals ( NDArrayDoubles other , double tolerance ) { if ( ! Arrays . equals ( dimensions , other . dimensions ) ) return false ; if ( dimensions . length != other . dimensions . length ) return false ; for ( int i = 0 ; i < dimensions . length ; i ++ ) { if ( Math . abs ( dimensions [ i ] - other . dimensions [ i ] ) > tolerance ) return false ; } return true ; }
Does a deep comparison using equality with tolerance checks against the vector table of values .
7,681
private static String stringMessageDigest ( String source , String algorithm ) { return getMessageDigest ( source . getBytes ( ) , algorithm ) ; }
Get the sha1 value of a string
7,682
protected void launch ( String [ ] args , String mainClass , ClassLoader classLoader ) throws Exception { Runnable runner = createMainMethodRunner ( mainClass , args , classLoader ) ; Thread . currentThread ( ) . setContextClassLoader ( classLoader ) ; runner . run ( ) ; }
Launch the application given the archive file and a fully configured classloader .
7,683
public void logException ( LogLevel logLevel , Throwable throwable , Class clazz , String methodName ) { this . tracer . logException ( logLevel , throwable , clazz , methodName ) ; }
Delegates to the corresponding method of the wrapped tracer .
7,684
public TraceMethod wayout ( ) { TraceMethod traceMethod = this . tracer . wayout ( ) ; if ( getThreadMap ( ) . getCurrentStackSize ( ) == 0 ) { clearCurrentTracingContext ( ) ; if ( ! TracerFactory . getInstance ( ) . offerTracer ( this ) ) System . err . printf ( "WARNING: Offer failed. Possible queue corruption.%n" ) ; } return traceMethod ; }
Delegates to the corresponding method of the wrapped tracer . Besides it checks if the stack size of the current tracing context has decreased to zero . If so then the current tracing context will be cleared .
7,685
public final boolean overrideAllowed ( final File file ) { if ( isOverride ( ) ) { if ( overrideExclude == null ) { return true ; } else { return ! getOverrideExcludeFilter ( ) . accept ( file ) ; } } else { if ( overrideInclude == null ) { return false ; } else { return getOverrideIncludeFilter ( ) . accept ( file ) ; } } }
Checks if a file can be overridden .
7,686
public final boolean cleanAllowed ( final File file ) { if ( cleanExclude == null ) { return true ; } if ( cleanExcludeFilter == null ) { cleanExcludeFilter = new RegexFileFilter ( cleanExclude ) ; } return ! cleanExcludeFilter . accept ( file ) ; }
Checks if a file should be excluded from cleaning .
7,687
public final File getCanonicalDir ( ) { final String dir = getDirectory ( ) ; if ( dir == null ) { return null ; } try { return new File ( dir ) . getCanonicalFile ( ) ; } catch ( final IOException ex ) { throw new RuntimeException ( "Couldn't determine canonical file: " + dir , ex ) ; } }
Returns the full path from project and folder .
7,688
private File downloadSdk ( final String path ) throws MojoExecutionException { File dotCeylon = new File ( path ) ; if ( ! dotCeylon . exists ( ) ) { dotCeylon . mkdirs ( ) ; } String [ ] segments = this . fromURL . split ( "/" ) ; String file = segments [ segments . length - 1 ] ; String repoUrl = this . fromURL . substring ( 0 , this . fromURL . length ( ) - file . length ( ) ) ; String version = FileUtils . basename ( file ) ; File home = new File ( dotCeylon , version ) ; if ( home . exists ( ) ) { getLog ( ) . info ( "Skipping download: Folder " + version + " corresponding to SDK already exists " + " in " + dotCeylon . getAbsolutePath ( ) ) ; return new File ( home , "repo" ) ; } File outputFile = new File ( dotCeylon , file ) ; if ( outputFile . exists ( ) ) { throw new MojoExecutionException ( "Downloaded file " + outputFile . getAbsolutePath ( ) + " exists. Please remove it and try again" ) ; } try { doGet ( outputFile , repoUrl ) ; } catch ( Exception e ) { throw new MojoExecutionException ( "Error downloading SDK" + e . getLocalizedMessage ( ) , e ) ; } CeylonUtil . extract ( outputFile , dotCeylon ) ; outputFile . delete ( ) ; return new File ( home , "repo" ) ; }
Download the Ceylon SDK .
7,689
private void doGet ( final File outputFile , final String repoUrl ) throws Exception { int readTimeOut = 5 * 60 * 1000 ; Repository repository = new Repository ( repoUrl , repoUrl ) ; wagon . setReadTimeout ( readTimeOut ) ; getLog ( ) . info ( "Read Timeout is set to " + readTimeOut + " milliseconds" ) ; wagon . connect ( repository ) ; wagon . get ( outputFile . getName ( ) , outputFile ) ; wagon . disconnect ( ) ; }
Does the actual retrieval .
7,690
public void execute ( ) throws MojoExecutionException , MojoFailureException { try { removeFromResources ( blocksDir ) ; removeFromResources ( resourcesDir ) ; File targetDir = new File ( outputDir ) ; boolean jar = "jar" . equalsIgnoreCase ( mavenProject . getPackaging ( ) ) ; if ( jar ) { JarBuilder builder = new JarBuilder ( blocksDir , resourcesDir , targetDir , mavenProject , mavenSession , getLog ( ) ) ; builder . generate ( ) ; } else { WarBuilder builder = new WarBuilder ( blocksDir , resourcesDir , targetDir , mavenProject , mavenSession , getLog ( ) ) ; builder . generate ( ) ; } } catch ( Exception e ) { throw new MojoFailureException ( "Source generator error" , e ) ; } }
protected MojoExecutor . ExecutionEnvironment _pluginEnv ;
7,691
public static < T > T getStateAsObject ( HalResource halResource , Class < T > type ) { return halResource . adaptTo ( type ) ; }
Converts the JSON model to an object of the given type .
7,692
public static byte [ ] getURLData ( final String url ) { final int readBytes = 1000 ; URL u ; InputStream is = null ; final ByteArrayOutputStream buffer = new ByteArrayOutputStream ( ) ; final TrustManager [ ] trustAllCerts = new TrustManager [ ] { new X509TrustManager ( ) { public java . security . cert . X509Certificate [ ] getAcceptedIssuers ( ) { return null ; } public void checkClientTrusted ( java . security . cert . X509Certificate [ ] certs , String authType ) { } public void checkServerTrusted ( java . security . cert . X509Certificate [ ] certs , String authType ) { } } } ; try { final SSLContext sc = SSLContext . getInstance ( "SSL" ) ; sc . init ( null , trustAllCerts , new java . security . SecureRandom ( ) ) ; HttpsURLConnection . setDefaultSSLSocketFactory ( sc . getSocketFactory ( ) ) ; } catch ( final Exception ex ) { LOG . error ( "Unable to install the all-trust SSL Manager" , ex ) ; } try { u = new URL ( url ) ; is = u . openStream ( ) ; int nRead ; byte [ ] data = new byte [ readBytes ] ; while ( ( nRead = is . read ( data , 0 , readBytes ) ) != - 1 ) { buffer . write ( data , 0 , nRead ) ; } } catch ( final Exception ex ) { LOG . error ( "Unable to read data from URL" , ex ) ; } finally { try { buffer . flush ( ) ; if ( is != null ) is . close ( ) ; } catch ( final Exception ex ) { LOG . error ( "Unable to flush and close URL Input Stream" , ex ) ; } } return buffer . toByteArray ( ) ; }
Downloads a file as a byte array
7,693
public void putImage ( String path , int x , int y , int w , int h , Graphics2D graphics ) { ImageIcon i = new ImageIcon ( path ) ; Image image = i . getImage ( ) ; ImageObserver io = new ImageObserver ( ) { public boolean imageUpdate ( Image img , int infoflags , int x , int y , int width , int height ) { return false ; } } ; graphics . drawImage ( image , x , y , w * 3 , h * 3 , io ) ; }
The portrayal of the current device can draw a geometric figure or print a predefine image . This method is called when the device has been linked to be draw as an image .
7,694
public JsonWriter beginArray ( String arrayName ) throws IOException { writeName ( arrayName ) ; writer . beginArray ( ) ; writeStack . add ( JsonTokenType . BEGIN_ARRAY ) ; return this ; }
Begins a new array with given name
7,695
public JsonWriter beginObject ( String objectName ) throws IOException { writeName ( objectName ) ; writer . beginObject ( ) ; writeStack . add ( JsonTokenType . BEGIN_OBJECT ) ; return this ; }
Begins a new object with a given name
7,696
public JsonWriter endArray ( ) throws IOException { checkAndPop ( JsonTokenType . BEGIN_ARRAY ) ; popIf ( JsonTokenType . NAME ) ; writer . endArray ( ) ; return this ; }
Ends the current array
7,697
public JsonWriter endObject ( ) throws IOException { checkAndPop ( JsonTokenType . BEGIN_OBJECT ) ; popIf ( JsonTokenType . NAME ) ; writer . endObject ( ) ; return this ; }
Ends the current object
7,698
public boolean inArray ( ) { return writeStack . peek ( ) == JsonTokenType . BEGIN_ARRAY || ( writeStack . peek ( ) == JsonTokenType . BEGIN_DOCUMENT && isArray ) ; }
Determines if the writer is currently in an array
7,699
public boolean inObject ( ) { return writeStack . peek ( ) == JsonTokenType . BEGIN_OBJECT || ( writeStack . peek ( ) == JsonTokenType . BEGIN_DOCUMENT && ! isArray ) ; }
Determines if the writer is currently in an object