idx int64 0 41.2k | question stringlengths 83 4.15k | target stringlengths 5 715 |
|---|---|---|
9,600 | public char [ ] ts2string ( double [ ] ts , int paaSize , double [ ] cuts , double nThreshold ) throws SAXException { if ( paaSize == ts . length ) { return tsProcessor . ts2String ( tsProcessor . znorm ( ts , nThreshold ) , cuts ) ; } else { double [ ] paa = tsProcessor . paa ( tsProcessor . znorm ( ts , nThreshold ) , paaSize ) ; return tsProcessor . ts2String ( paa , cuts ) ; } } | Convert the timeseries into SAX string representation . |
9,601 | public SAXRecords ts2saxByChunking ( double [ ] ts , int paaSize , double [ ] cuts , double nThreshold ) throws SAXException { SAXRecords saxFrequencyData = new SAXRecords ( ) ; double [ ] normalizedTS = tsProcessor . znorm ( ts , nThreshold ) ; double [ ] paa = tsProcessor . paa ( normalizedTS , paaSize ) ; char [ ] currentString = tsProcessor . ts2String ( paa , cuts ) ; for ( int i = 0 ; i < currentString . length ; i ++ ) { char c = currentString [ i ] ; int pos = ( int ) Math . floor ( i * ts . length / currentString . length ) ; saxFrequencyData . add ( String . valueOf ( c ) . toCharArray ( ) , pos ) ; } return saxFrequencyData ; } | Converts the input time series into a SAX data structure via chunking and Z normalization . |
9,602 | public int charDistance ( char a , char b ) { return Math . abs ( Character . getNumericValue ( a ) - Character . getNumericValue ( b ) ) ; } | Compute the distance between the two chars based on the ASCII symbol codes . |
9,603 | public int strDistance ( char [ ] a , char [ ] b ) throws SAXException { if ( a . length == b . length ) { int distance = 0 ; for ( int i = 0 ; i < a . length ; i ++ ) { int tDist = Math . abs ( Character . getNumericValue ( a [ i ] ) - Character . getNumericValue ( b [ i ] ) ) ; distance += tDist ; } return distance ; } else { throw new SAXException ( "Unable to compute SAX distance, string lengths are not equal" ) ; } } | Compute the distance between the two strings this function use the numbers associated with ASCII codes i . e . distance between a and b would be 1 . |
9,604 | public double saxMinDist ( char [ ] a , char [ ] b , double [ ] [ ] distanceMatrix , int n , int w ) throws SAXException { if ( a . length == b . length ) { double dist = 0.0D ; for ( int i = 0 ; i < a . length ; i ++ ) { if ( Character . isLetter ( a [ i ] ) && Character . isLetter ( b [ i ] ) ) { int numA = Character . getNumericValue ( a [ i ] ) - 10 ; int numB = Character . getNumericValue ( b [ i ] ) - 10 ; int maxIdx = distanceMatrix [ 0 ] . length ; if ( numA > ( maxIdx - 1 ) || numA < 0 || numB > ( maxIdx - 1 ) || numB < 0 ) { throw new SAXException ( "The character index greater than " + maxIdx + " or less than 0!" ) ; } double localDist = distanceMatrix [ numA ] [ numB ] ; dist = dist + localDist * localDist ; } else { throw new SAXException ( "Non-literal character found!" ) ; } } return Math . sqrt ( ( double ) n / ( double ) w ) * Math . sqrt ( dist ) ; } else { throw new SAXException ( "Data arrays lengths are not equal!" ) ; } } | This function implements SAX MINDIST function which uses alphabet based distance matrix . |
9,605 | public boolean checkMinDistIsZero ( char [ ] a , char [ ] b ) { for ( int i = 0 ; i < a . length ; i ++ ) { if ( charDistance ( a [ i ] , b [ i ] ) > 1 ) { return false ; } } return true ; } | Check for trivial mindist case . |
9,606 | public Map < String , Integer > ts2Shingles ( double [ ] series , int windowSize , int paaSize , int alphabetSize , NumerosityReductionStrategy strategy , double nrThreshold , int shingleSize ) throws SAXException { String [ ] alphabet = new String [ alphabetSize ] ; for ( int i = 0 ; i < alphabetSize ; i ++ ) { alphabet [ i ] = String . valueOf ( TSProcessor . ALPHABET [ i ] ) ; } String [ ] allShingles = getAllPermutations ( alphabet , shingleSize ) ; HashMap < String , Integer > res = new HashMap < String , Integer > ( allShingles . length ) ; for ( String s : allShingles ) { res . put ( s , 0 ) ; } SAXRecords saxData = ts2saxViaWindow ( series , windowSize , paaSize , na . getCuts ( alphabetSize ) , strategy , nrThreshold ) ; for ( SAXRecord sr : saxData ) { String word = String . valueOf ( sr . getPayload ( ) ) ; int frequency = sr . getIndexes ( ) . size ( ) ; for ( int i = 0 ; i <= word . length ( ) - shingleSize ; i ++ ) { String shingle = word . substring ( i , i + shingleSize ) ; res . put ( shingle , res . get ( shingle ) + frequency ) ; } } return res ; } | Converts a single time - series into map of shingle frequencies . |
9,607 | public static String [ ] getAllPermutations ( String [ ] alphabet , int wordLength ) { String [ ] allLists = new String [ ( int ) Math . pow ( alphabet . length , wordLength ) ] ; if ( wordLength == 1 ) return alphabet ; else { String [ ] allSublists = getAllPermutations ( alphabet , wordLength - 1 ) ; int arrayIndex = 0 ; for ( int i = 0 ; i < alphabet . length ; i ++ ) { for ( int j = 0 ; j < allSublists . length ; j ++ ) { allLists [ arrayIndex ] = alphabet [ i ] + allSublists [ j ] ; arrayIndex ++ ; } } return allLists ; } } | Get all permutations of the given alphabet of given length . |
9,608 | public static String timeToString ( long start , long finish ) { Duration duration = new Duration ( finish - start ) ; PeriodFormatter formatter = new PeriodFormatterBuilder ( ) . appendDays ( ) . appendSuffix ( "d" ) . appendHours ( ) . appendSuffix ( "h" ) . appendMinutes ( ) . appendSuffix ( "m" ) . appendSeconds ( ) . appendSuffix ( "s" ) . appendMillis ( ) . appendSuffix ( "ms" ) . toFormatter ( ) ; return formatter . print ( duration . toPeriod ( ) ) ; } | Generic method to convert the milliseconds into the elapsed time string . |
9,609 | public static DiscordRecords series2DiscordsDeprecated ( double [ ] series , int discordsNumToReport , int windowSize , int paaSize , int alphabetSize , SlidingWindowMarkerAlgorithm markerAlgorithm , NumerosityReductionStrategy strategy , double nThreshold ) throws Exception { Date start = new Date ( ) ; NormalAlphabet normalA = new NormalAlphabet ( ) ; SAXRecords sax = sp . ts2saxViaWindow ( series , windowSize , alphabetSize , normalA . getCuts ( alphabetSize ) , strategy , nThreshold ) ; Date saxEnd = new Date ( ) ; LOGGER . debug ( "discretized in {}, words: {}, indexes: {}" , SAXProcessor . timeToString ( start . getTime ( ) , saxEnd . getTime ( ) ) , sax . getRecords ( ) . size ( ) , sax . getIndexes ( ) . size ( ) ) ; HashMap < String , ArrayList < Integer > > hash = new HashMap < String , ArrayList < Integer > > ( ) ; for ( SAXRecord sr : sax . getRecords ( ) ) { for ( Integer pos : sr . getIndexes ( ) ) { String word = String . valueOf ( sr . getPayload ( ) ) ; if ( ! ( hash . containsKey ( word ) ) ) { hash . put ( word , new ArrayList < Integer > ( ) ) ; } hash . get ( String . valueOf ( word ) ) . add ( pos ) ; } } Date hashEnd = new Date ( ) ; LOGGER . debug ( "Hash filled in : {}" , SAXProcessor . timeToString ( saxEnd . getTime ( ) , hashEnd . getTime ( ) ) ) ; DiscordRecords discords = getDiscordsWithHash ( series , windowSize , hash , discordsNumToReport , markerAlgorithm , nThreshold ) ; Date end = new Date ( ) ; LOGGER . info ( "{} discords found in {}" , discords . getSize ( ) , SAXProcessor . timeToString ( start . getTime ( ) , end . getTime ( ) ) ) ; return discords ; } | Old implementation . Nearest neighbot for a candidate subsequence is searched among all other time - series subsequences regardless of their exclusion by EXACT or MINDIST . This also accepts a marker implementation which is responsible for marking a segment as visited . |
9,610 | private static ArrayList < FrequencyTableEntry > hashToFreqEntries ( HashMap < String , ArrayList < Integer > > hash ) { ArrayList < FrequencyTableEntry > res = new ArrayList < FrequencyTableEntry > ( ) ; for ( Entry < String , ArrayList < Integer > > e : hash . entrySet ( ) ) { char [ ] payload = e . getKey ( ) . toCharArray ( ) ; int frequency = e . getValue ( ) . size ( ) ; for ( Integer i : e . getValue ( ) ) { res . add ( new FrequencyTableEntry ( i , payload . clone ( ) , frequency ) ) ; } } return res ; } | Translates the hash table into sortable array of substrings . |
9,611 | private static double distance ( double [ ] subseries , double [ ] series , int from , int to , double nThreshold ) throws Exception { double [ ] subsequence = tp . znorm ( tp . subseriesByCopy ( series , from , to ) , nThreshold ) ; Double sum = 0D ; for ( int i = 0 ; i < subseries . length ; i ++ ) { double tmp = subseries [ i ] - subsequence [ i ] ; sum = sum + tmp * tmp ; } return Math . sqrt ( sum ) ; } | Calculates the Euclidean distance between two points . Don t use this unless you need that . |
9,612 | public void addShingledSeries ( String key , Map < String , Integer > shingledSeries ) { int [ ] counts = new int [ this . indexTable . size ( ) ] ; for ( String str : shingledSeries . keySet ( ) ) { Integer idx = this . indexTable . get ( str ) ; if ( null == idx ) { throw new IndexOutOfBoundsException ( "the requested shingle " + str + " doesn't exist!" ) ; } counts [ idx ] = shingledSeries . get ( str ) ; } shingles . put ( key , counts ) ; } | Adds a shingled series assuring the proper index . |
9,613 | public static void main ( String [ ] args ) throws Exception { NormalAlphabet na = new NormalAlphabet ( ) ; SAXProcessor sp = new SAXProcessor ( ) ; String dataFileName = args [ 0 ] ; System . out . println ( "data file: " + dataFileName ) ; double [ ] ts = TSProcessor . readFileColumn ( dataFileName , 0 , 0 ) ; System . out . println ( "data size: " + ts . length ) ; System . out . println ( "SAX parameters:\n sliding window sizes: " + Arrays . toString ( WINDOWS ) + "\n PAA sizes: " + Arrays . toString ( PAAS ) + "\n alphabet sizes: " + Arrays . toString ( ALPHABETS ) + "\n NR strategis: " + Arrays . toString ( NRS ) ) ; System . out . println ( "Performing " + NRUNS + " SAX conversion runs for each algorithm implementation ... " ) ; long tstamp1 = System . currentTimeMillis ( ) ; for ( int slidingWindowSize : WINDOWS ) { for ( int paaSize : PAAS ) { for ( int alphabetSize : ALPHABETS ) { for ( String nrStrategy : NRS ) { for ( int i = 0 ; i < NRUNS ; i ++ ) { @ SuppressWarnings ( "unused" ) SAXRecords sequentialRes = sp . ts2saxViaWindow ( ts , slidingWindowSize , paaSize , na . getCuts ( alphabetSize ) , NumerosityReductionStrategy . fromString ( nrStrategy ) , N_THRESHOLD ) ; } } } } } long tstamp2 = System . currentTimeMillis ( ) ; System . out . println ( "single thread conversion: " + String . valueOf ( tstamp2 - tstamp1 ) + ", " + SAXProcessor . timeToString ( tstamp1 , tstamp2 ) ) ; for ( int threadsNum = MIN_CPUS ; threadsNum < MAX_CPUS ; threadsNum ++ ) { tstamp1 = System . currentTimeMillis ( ) ; for ( int slidingWindowSize : WINDOWS ) { for ( int paaSize : PAAS ) { for ( int alphabetSize : ALPHABETS ) { for ( String nrStrategy : NRS ) { for ( int i = 0 ; i < NRUNS ; i ++ ) { ParallelSAXImplementation ps = new ParallelSAXImplementation ( ) ; @ SuppressWarnings ( "unused" ) SAXRecords parallelRes = ps . process ( ts , threadsNum , slidingWindowSize , paaSize , alphabetSize , NumerosityReductionStrategy . fromString ( nrStrategy ) , N_THRESHOLD ) ; } } } } } tstamp2 = System . currentTimeMillis ( ) ; System . out . println ( "parallel conversion using " + threadsNum + " threads: " + String . valueOf ( tstamp2 - tstamp1 ) + ", " + SAXProcessor . timeToString ( tstamp1 , tstamp2 ) ) ; } } | Runs the evaluation . |
9,614 | public void markVisited ( int loc ) { if ( checkBounds ( loc ) ) { if ( ZERO == this . registry [ loc ] ) { this . unvisitedCount -- ; } this . registry [ loc ] = ONE ; } else { throw new RuntimeException ( "The location " + loc + " out of bounds [0," + ( this . registry . length - 1 ) + "]" ) ; } } | Marks location visited . If it was unvisited counter decremented . |
9,615 | public void markVisited ( int from , int upTo ) { if ( checkBounds ( from ) && checkBounds ( upTo - 1 ) ) { for ( int i = from ; i < upTo ; i ++ ) { this . markVisited ( i ) ; } } else { throw new RuntimeException ( "The location " + from + "," + upTo + " out of bounds [0," + ( this . registry . length - 1 ) + "]" ) ; } } | Marks as visited a range of locations . |
9,616 | public int getNextRandomUnvisitedPosition ( ) { if ( 0 == this . unvisitedCount ) { return - 1 ; } int i = this . randomizer . nextInt ( this . registry . length ) ; while ( ONE == registry [ i ] ) { i = this . randomizer . nextInt ( this . registry . length ) ; } return i ; } | Get the next random unvisited position . |
9,617 | public boolean isNotVisited ( int loc ) { if ( checkBounds ( loc ) ) { return ( ZERO == this . registry [ loc ] ) ; } else { throw new RuntimeException ( "The location " + loc + " out of bounds [0," + ( this . registry . length - 1 ) + "]" ) ; } } | Check if position is not visited . |
9,618 | public boolean isVisited ( int from , int upTo ) { if ( checkBounds ( from ) && checkBounds ( upTo - 1 ) ) { for ( int i = from ; i < upTo ; i ++ ) { if ( ONE == this . registry [ i ] ) { return true ; } } return false ; } else { throw new RuntimeException ( "The location " + from + "," + upTo + " out of bounds [0," + ( this . registry . length - 1 ) + "]" ) ; } } | Check if the interval and its boundaries were visited . |
9,619 | public boolean isVisited ( int loc ) { if ( checkBounds ( loc ) ) { return ( ONE == this . registry [ loc ] ) ; } else { throw new RuntimeException ( "The location " + loc + " out of bounds [0," + ( this . registry . length - 1 ) + "]" ) ; } } | Check if the location specified is visited . |
9,620 | public ArrayList < Integer > getUnvisited ( ) { if ( 0 == this . unvisitedCount ) { return new ArrayList < Integer > ( ) ; } ArrayList < Integer > res = new ArrayList < Integer > ( this . unvisitedCount ) ; for ( int i = 0 ; i < this . registry . length ; i ++ ) { if ( ZERO == this . registry [ i ] ) { res . add ( i ) ; } } return res ; } | Get the list of unvisited positions . |
9,621 | public ArrayList < Integer > getVisited ( ) { if ( 0 == ( this . registry . length - this . unvisitedCount ) ) { return new ArrayList < Integer > ( ) ; } ArrayList < Integer > res = new ArrayList < Integer > ( this . registry . length - this . unvisitedCount ) ; for ( int i = 0 ; i < this . registry . length ; i ++ ) { if ( ONE == this . registry [ i ] ) { res . add ( i ) ; } } return res ; } | Get the list of visited positions . Returns NULL if none are visited . |
9,622 | public static Map < String , List < double [ ] > > readUCRData ( String fileName ) throws IOException , NumberFormatException { Map < String , List < double [ ] > > res = new HashMap < String , List < double [ ] > > ( ) ; BufferedReader br = new BufferedReader ( new FileReader ( new File ( fileName ) ) ) ; String line = "" ; while ( ( line = br . readLine ( ) ) != null ) { if ( line . trim ( ) . length ( ) == 0 ) { continue ; } String [ ] split = line . trim ( ) . split ( "[\\,\\s]+" ) ; String label = split [ 0 ] ; Double num = parseValue ( label ) ; String seriesType = label ; if ( ! ( Double . isNaN ( num ) ) ) { seriesType = String . valueOf ( num . intValue ( ) ) ; } double [ ] series = new double [ split . length - 1 ] ; for ( int i = 1 ; i < split . length ; i ++ ) { series [ i - 1 ] = Double . valueOf ( split [ i ] . trim ( ) ) . doubleValue ( ) ; } if ( ! res . containsKey ( seriesType ) ) { res . put ( seriesType , new ArrayList < double [ ] > ( ) ) ; } res . get ( seriesType ) . add ( series ) ; } br . close ( ) ; return res ; } | Reads bunch of series from file . First column treats as a class label . Rest as a real - valued series . |
9,623 | public static String datasetStats ( Map < String , List < double [ ] > > data , String name ) { int globalMinLength = Integer . MAX_VALUE ; int globalMaxLength = Integer . MIN_VALUE ; double globalMinValue = Double . MAX_VALUE ; double globalMaxValue = Double . MIN_VALUE ; for ( Entry < String , List < double [ ] > > e : data . entrySet ( ) ) { for ( double [ ] dataEntry : e . getValue ( ) ) { globalMaxLength = ( dataEntry . length > globalMaxLength ) ? dataEntry . length : globalMaxLength ; globalMinLength = ( dataEntry . length < globalMinLength ) ? dataEntry . length : globalMinLength ; for ( double value : dataEntry ) { globalMaxValue = ( value > globalMaxValue ) ? value : globalMaxValue ; globalMinValue = ( value < globalMinValue ) ? value : globalMinValue ; } } } StringBuffer sb = new StringBuffer ( ) ; sb . append ( name ) . append ( "classes: " ) . append ( data . size ( ) ) ; sb . append ( ", series length min: " ) . append ( globalMinLength ) ; sb . append ( ", max: " ) . append ( globalMaxLength ) ; sb . append ( ", min value: " ) . append ( globalMinValue ) ; sb . append ( ", max value: " ) . append ( globalMaxValue ) . append ( ";" ) ; for ( Entry < String , List < double [ ] > > e : data . entrySet ( ) ) { sb . append ( name ) . append ( " class: " ) . append ( e . getKey ( ) ) ; sb . append ( " series: " ) . append ( e . getValue ( ) . size ( ) ) . append ( ";" ) ; } return sb . delete ( sb . length ( ) - 1 , sb . length ( ) ) . toString ( ) ; } | Prints the dataset statistics . |
9,624 | public static void saveData ( Map < String , List < double [ ] > > data , File file ) throws IOException { BufferedWriter bw = new BufferedWriter ( new FileWriter ( file ) ) ; for ( Entry < String , List < double [ ] > > classEntry : data . entrySet ( ) ) { String classLabel = classEntry . getKey ( ) ; for ( double [ ] arr : classEntry . getValue ( ) ) { String arrStr = Arrays . toString ( arr ) . replaceAll ( "[\\]\\[\\s]+" , "" ) ; bw . write ( classLabel + "," + arrStr + CR ) ; } } bw . close ( ) ; } | Saves the dataset . |
9,625 | public double [ ] readTS ( String dataFileName , int loadLimit ) throws SAXException , IOException { Path path = Paths . get ( dataFileName ) ; if ( ! ( Files . exists ( path ) ) ) { throw new SAXException ( "unable to load data - data source not found." ) ; } BufferedReader reader = Files . newBufferedReader ( path , DEFAULT_CHARSET ) ; return readTS ( reader , 0 , loadLimit ) ; } | Read at least N elements from the one - column file . |
9,626 | public double max ( double [ ] series ) { double max = Double . MIN_VALUE ; for ( int i = 0 ; i < series . length ; i ++ ) { if ( max < series [ i ] ) { max = series [ i ] ; } } return max ; } | Finds the maximal value in timeseries . |
9,627 | public double min ( double [ ] series ) { double min = Double . MAX_VALUE ; for ( int i = 0 ; i < series . length ; i ++ ) { if ( min > series [ i ] ) { min = series [ i ] ; } } return min ; } | Finds the minimal value in timeseries . |
9,628 | public double mean ( double [ ] series ) { double res = 0D ; int count = 0 ; for ( double tp : series ) { res += tp ; count += 1 ; } if ( count > 0 ) { return res / ( ( Integer ) count ) . doubleValue ( ) ; } return Double . NaN ; } | Computes the mean value of timeseries . |
9,629 | public double median ( double [ ] series ) { double [ ] clonedSeries = series . clone ( ) ; Arrays . sort ( clonedSeries ) ; double median ; if ( clonedSeries . length % 2 == 0 ) { median = ( clonedSeries [ clonedSeries . length / 2 ] + ( double ) clonedSeries [ clonedSeries . length / 2 - 1 ] ) / 2 ; } else { median = clonedSeries [ clonedSeries . length / 2 ] ; } return median ; } | Computes the median value of timeseries . |
9,630 | public double stDev ( double [ ] series ) { double num0 = 0D ; double sum = 0D ; int count = 0 ; for ( double tp : series ) { num0 = num0 + tp * tp ; sum = sum + tp ; count += 1 ; } double len = ( ( Integer ) count ) . doubleValue ( ) ; return Math . sqrt ( ( len * num0 - sum * sum ) / ( len * ( len - 1 ) ) ) ; } | Speed - optimized implementation . |
9,631 | public double [ ] znorm ( double [ ] series , double normalizationThreshold ) { double [ ] res = new double [ series . length ] ; double sd = stDev ( series ) ; if ( sd < normalizationThreshold ) { return res ; } double mean = mean ( series ) ; for ( int i = 0 ; i < res . length ; i ++ ) { res [ i ] = ( series [ i ] - mean ) / sd ; } return res ; } | Z - Normalize routine . |
9,632 | public char [ ] ts2String ( double [ ] vals , double [ ] cuts ) { char [ ] res = new char [ vals . length ] ; for ( int i = 0 ; i < vals . length ; i ++ ) { res [ i ] = num2char ( vals [ i ] , cuts ) ; } return res ; } | Converts the timeseries into string using given cuts intervals . Useful for not - normal distribution cuts . |
9,633 | public int [ ] ts2Index ( double [ ] series , double [ ] cuts ) throws Exception { int [ ] res = new int [ series . length ] ; for ( int i = 0 ; i < series . length ; i ++ ) { res [ i ] = num2index ( series [ i ] , cuts ) ; } return res ; } | Convert the timeseries into the index using SAX cuts . |
9,634 | public char num2char ( double value , double [ ] cuts ) { int idx = 0 ; if ( value >= 0 ) { idx = cuts . length ; while ( ( idx > 0 ) && ( cuts [ idx - 1 ] > value ) ) { idx -- ; } } else { while ( ( idx < cuts . length ) && ( cuts [ idx ] <= value ) ) { idx ++ ; } } return ALPHABET [ idx ] ; } | Get mapping of a number to char . |
9,635 | public int num2index ( double value , double [ ] cuts ) { int count = 0 ; while ( ( count < cuts . length ) && ( cuts [ count ] <= value ) ) { count ++ ; } return count ; } | Get mapping of number to cut index . |
9,636 | public double [ ] subseriesByCopy ( double [ ] series , int start , int end ) throws IndexOutOfBoundsException { if ( ( start > end ) || ( start < 0 ) || ( end > series . length ) ) { throw new IndexOutOfBoundsException ( "Unable to extract subseries, series length: " + series . length + ", start: " + start + ", end: " + String . valueOf ( end - start ) ) ; } return Arrays . copyOfRange ( series , start , end ) ; } | Extract subseries out of series . |
9,637 | public String seriesToString ( double [ ] series , NumberFormat df ) { StringBuffer sb = new StringBuffer ( ) ; sb . append ( '[' ) ; for ( double d : series ) { sb . append ( df . format ( d ) ) . append ( ',' ) ; } sb . delete ( sb . length ( ) - 2 , sb . length ( ) - 1 ) . append ( "]" ) ; return sb . toString ( ) ; } | Prettyfies the timeseries for screen output . |
9,638 | public double [ ] normOne ( double [ ] data ) { double [ ] res = new double [ data . length ] ; double max = max ( data ) ; for ( int i = 0 ; i < data . length ; i ++ ) { res [ i ] = data [ i ] / max ; } return res ; } | Normalizes data in interval 0 - 1 . |
9,639 | public List < DiscordRecord > getTopHits ( Integer num ) { if ( num >= this . discords . size ( ) ) { return this . discords ; } List < DiscordRecord > res = this . discords . subList ( this . discords . size ( ) - num , this . discords . size ( ) ) ; return res ; } | Returns the number of the top hits . |
9,640 | public void setZValues ( double [ ] [ ] zValues , double low , double high ) { this . zValues = zValues ; this . lowValue = low ; this . highValue = high ; } | Replaces the z - values array . The number of elements should match the number of y - values with each element containing a double array with an equal number of elements that matches the number of x - values . Use this method where the minimum and maximum values possible are not contained within the dataset . |
9,641 | public void setBackgroundColour ( Color backgroundColour ) { if ( backgroundColour == null ) { backgroundColour = Color . WHITE ; } this . backgroundColour = backgroundColour ; } | Sets the colour to be used on the background of the chart . A transparent background can be set by setting a background colour with an alpha value . The transparency will only be effective when the image is saved as a png or gif . |
9,642 | public static double max ( double [ ] [ ] values ) { double max = 0 ; for ( int i = 0 ; i < values . length ; i ++ ) { for ( int j = 0 ; j < values [ i ] . length ; j ++ ) { max = ( values [ i ] [ j ] > max ) ? values [ i ] [ j ] : max ; } } return max ; } | Finds and returns the maximum value in a 2 - dimensional array of doubles . |
9,643 | public static double min ( double [ ] [ ] values ) { double min = Double . MAX_VALUE ; for ( int i = 0 ; i < values . length ; i ++ ) { for ( int j = 0 ; j < values [ i ] . length ; j ++ ) { min = ( values [ i ] [ j ] < min ) ? values [ i ] [ j ] : min ; } } return min ; } | Finds and returns the minimum value in a 2 - dimensional array of doubles . |
9,644 | public int compareTo ( DiscordRecord other ) { if ( null == other ) { throw new NullPointerException ( "Unable compare to null!" ) ; } return Double . compare ( other . getNNDistance ( ) , this . nnDistance ) ; } | The simple comparator based on the distance . Note that discord is better if the NN distance is greater . |
9,645 | public static double gaussian ( ) { double r , x , y ; do { x = uniform ( - 1.0 , 1.0 ) ; y = uniform ( - 1.0 , 1.0 ) ; r = x * x + y * y ; } while ( r >= 1 || r == 0 ) ; return x * Math . sqrt ( - 2 * Math . log ( r ) / r ) ; } | Returns a real number with a standard Gaussian distribution . |
9,646 | public static void shuffle ( double [ ] a ) { int N = a . length ; for ( int i = 0 ; i < N ; i ++ ) { int r = i + uniform ( N - i ) ; double temp = a [ i ] ; a [ i ] = a [ r ] ; a [ r ] = temp ; } } | Rearrange the elements of a double array in random order . |
9,647 | public void dropByIndex ( int idx ) { SAXRecord entry = realTSindex . get ( idx ) ; if ( null != entry ) { realTSindex . remove ( idx ) ; entry . removeIndex ( idx ) ; if ( entry . getIndexes ( ) . isEmpty ( ) ) { records . remove ( String . valueOf ( entry . getPayload ( ) ) ) ; } } } | Drops a single entry . |
9,648 | public void add ( char [ ] str , int idx ) { SAXRecord rr = records . get ( String . valueOf ( str ) ) ; if ( null == rr ) { rr = new SAXRecord ( str , idx ) ; this . records . put ( String . valueOf ( str ) , rr ) ; } else { rr . addIndex ( idx ) ; } this . realTSindex . put ( idx , rr ) ; } | Adds a single string and index entry by creating a SAXRecord . |
9,649 | public void addAll ( SAXRecords records ) { for ( SAXRecord record : records ) { char [ ] payload = record . getPayload ( ) ; for ( Integer i : record . getIndexes ( ) ) { this . add ( payload , i ) ; } } } | Adds all entries from the collection . |
9,650 | public void addAll ( HashMap < Integer , char [ ] > records ) { for ( Entry < Integer , char [ ] > e : records . entrySet ( ) ) { this . add ( e . getValue ( ) , e . getKey ( ) ) ; } } | This adds all to the internal store . Used by the parallel SAX conversion engine . |
9,651 | public String getSAXString ( String separatorToken ) { StringBuffer sb = new StringBuffer ( ) ; ArrayList < Integer > index = new ArrayList < Integer > ( ) ; index . addAll ( this . realTSindex . keySet ( ) ) ; Collections . sort ( index , new Comparator < Integer > ( ) { public int compare ( Integer int1 , Integer int2 ) { return int1 . compareTo ( int2 ) ; } } ) ; for ( int i : index ) { sb . append ( this . realTSindex . get ( i ) . getPayload ( ) ) . append ( separatorToken ) ; } return sb . toString ( ) ; } | Get the SAX string of this whole collection . |
9,652 | public ArrayList < Integer > getAllIndices ( ) { ArrayList < Integer > res = new ArrayList < Integer > ( this . realTSindex . size ( ) ) ; res . addAll ( this . realTSindex . keySet ( ) ) ; Collections . sort ( res ) ; return res ; } | Get all indexes sorted . |
9,653 | public void buildIndex ( ) { this . stringPosToRealPos = new HashMap < Integer , Integer > ( ) ; int counter = 0 ; for ( Integer idx : getAllIndices ( ) ) { this . stringPosToRealPos . put ( counter , idx ) ; counter ++ ; } } | This builds an index that aids in mapping of a SAX word to the real timeseries index . |
9,654 | public void excludePositions ( ArrayList < Integer > positions ) { for ( Integer p : positions ) { if ( realTSindex . containsKey ( p ) ) { SAXRecord rec = realTSindex . get ( p ) ; rec . removeIndex ( p ) ; if ( rec . getIndexes ( ) . isEmpty ( ) ) { this . records . remove ( String . valueOf ( rec . getPayload ( ) ) ) ; } realTSindex . remove ( p ) ; } } } | Removes saxRecord occurrences that correspond to these positions . |
9,655 | public ArrayList < SAXRecord > getSimpleMotifs ( int num ) { ArrayList < SAXRecord > res = new ArrayList < SAXRecord > ( num ) ; DoublyLinkedSortedList < Entry < String , SAXRecord > > list = new DoublyLinkedSortedList < Entry < String , SAXRecord > > ( num , new Comparator < Entry < String , SAXRecord > > ( ) { public int compare ( Entry < String , SAXRecord > o1 , Entry < String , SAXRecord > o2 ) { int f1 = o1 . getValue ( ) . getIndexes ( ) . size ( ) ; int f2 = o2 . getValue ( ) . getIndexes ( ) . size ( ) ; return Integer . compare ( f1 , f2 ) ; } } ) ; for ( Entry < String , SAXRecord > e : this . records . entrySet ( ) ) { list . addElement ( e ) ; } Iterator < Entry < String , SAXRecord > > i = list . iterator ( ) ; while ( i . hasNext ( ) ) { res . add ( i . next ( ) . getValue ( ) ) ; } return res ; } | Get motifs . |
9,656 | public void cancel ( ) { try { executorService . shutdown ( ) ; if ( ! executorService . awaitTermination ( 30 , TimeUnit . MINUTES ) ) { executorService . shutdownNow ( ) ; if ( ! executorService . awaitTermination ( 30 , TimeUnit . MINUTES ) ) { LOGGER . error ( "Pool did not terminate... FATAL ERROR" ) ; throw new RuntimeException ( "Parallel SAX pool did not terminate... FATAL ERROR" ) ; } } else { LOGGER . error ( "Parallel SAX was interrupted by a request" ) ; } } catch ( InterruptedException ie ) { LOGGER . error ( "Error while waiting interrupting." , ie ) ; executorService . shutdownNow ( ) ; Thread . currentThread ( ) . interrupt ( ) ; } } | Cancels the execution . |
9,657 | public static void main ( String [ ] args ) throws Exception { SAXProcessor sp = new SAXProcessor ( ) ; double [ ] dat = TSProcessor . readFileColumn ( DAT_FNAME , 1 , 0 ) ; LOGGER . info ( "read {} points from {}" , dat . length , DAT_FNAME ) ; String str = "win_width: " + cPoint + "; SAX: W " + SAX_WINDOW_SIZE + ", P " + SAX_PAA_SIZE + ", A " + SAX_ALPHABET_SIZE + ", STR " + SAX_NR_STRATEGY . toString ( ) ; int frameCounter = 0 ; int startOffset = cPoint ; while ( cPoint < dat . length - startOffset - 1 ) { if ( 0 == cPoint % 2 ) { BufferedImage tsChart = getChart ( dat , cPoint ) ; double [ ] win1 = Arrays . copyOfRange ( dat , cPoint - startOffset , cPoint ) ; Map < String , Integer > shingledData1 = sp . ts2Shingles ( win1 , SAX_WINDOW_SIZE , SAX_PAA_SIZE , SAX_ALPHABET_SIZE , SAX_NR_STRATEGY , SAX_NORM_THRESHOLD , SHINGLE_SIZE ) ; BufferedImage pam1 = getHeatMap ( shingledData1 , "pre-window" ) ; double [ ] win2 = Arrays . copyOfRange ( dat , cPoint , cPoint + startOffset ) ; Map < String , Integer > shingledData2 = sp . ts2Shingles ( win2 , SAX_WINDOW_SIZE , SAX_PAA_SIZE , SAX_ALPHABET_SIZE , SAX_NR_STRATEGY , SAX_NORM_THRESHOLD , SHINGLE_SIZE ) ; BufferedImage pam2 = getHeatMap ( shingledData2 , "post-window" ) ; BufferedImage target = new BufferedImage ( 800 , 530 , BufferedImage . TYPE_INT_ARGB ) ; Graphics targetGraphics = target . getGraphics ( ) ; targetGraphics . setColor ( Color . WHITE ) ; targetGraphics . fillRect ( 0 , 0 , 799 , 529 ) ; targetGraphics . drawImage ( tsChart , 0 , 0 , null ) ; targetGraphics . drawImage ( pam1 , 10 , 410 , null ) ; targetGraphics . drawImage ( pam2 , 120 , 410 , null ) ; targetGraphics . setColor ( Color . RED ) ; targetGraphics . setFont ( new Font ( "monospaced" , Font . PLAIN , 16 ) ) ; targetGraphics . drawString ( str , 300 , 420 ) ; targetGraphics . setColor ( Color . BLUE ) ; targetGraphics . setFont ( new Font ( "monospaced" , Font . PLAIN , 24 ) ) ; double dist = ed . distance ( toVector ( shingledData1 ) , toVector ( shingledData2 ) ) ; targetGraphics . drawString ( "ED=" + df . format ( dist ) , 300 , 480 ) ; File outputfile = new File ( "dframe" + String . format ( "%04d" , frameCounter ) + ".png" ) ; ImageIO . write ( target , "png" , outputfile ) ; frameCounter ++ ; } cPoint ++ ; } } | - pix_fmt yuv420p daimler_man . mp4 |
9,658 | private static double [ ] toDoubleAray ( Integer [ ] intArray , HashSet < Integer > skipIndex ) { double [ ] res = new double [ intArray . length - skipIndex . size ( ) ] ; int skip = 0 ; for ( int i = 0 ; i < intArray . length ; i ++ ) { if ( skipIndex . contains ( i ) ) { skip ++ ; continue ; } res [ i - skip ] = intArray [ i ] . doubleValue ( ) ; } return res ; } | Converts an array into array of doubles skipping specified indeces . |
9,659 | public VirtualFile getFile ( VirtualFile mountPoint , VirtualFile target ) { final String path = target . getPathNameRelativeTo ( mountPoint ) ; return rootNode . getFile ( new Path ( path ) , mountPoint ) ; } | Get the VirtualFile from the assembly . This will traverse VirtualFiles in assembly to find children if needed . |
9,660 | public List < String > getChildNames ( VirtualFile mountPoint , VirtualFile target ) { List < String > names = new LinkedList < String > ( ) ; AssemblyNode targetNode = null ; if ( mountPoint . equals ( target ) ) { targetNode = rootNode ; } else { targetNode = rootNode . find ( target . getPathNameRelativeTo ( mountPoint ) ) ; } if ( targetNode != null ) { for ( AssemblyNode childNode : targetNode . children . values ( ) ) { names . add ( childNode . realName ) ; } } return names ; } | Returns a list of all the names of the children in the assembly . |
9,661 | public File createFile ( String relativePath , InputStream sourceData ) throws IOException { final File tempFile = getFile ( relativePath ) ; boolean ok = false ; try { final FileOutputStream fos = new FileOutputStream ( tempFile ) ; try { VFSUtils . copyStream ( sourceData , fos ) ; fos . close ( ) ; sourceData . close ( ) ; ok = true ; return tempFile ; } finally { VFSUtils . safeClose ( fos ) ; } } finally { VFSUtils . safeClose ( sourceData ) ; if ( ! ok ) { tempFile . delete ( ) ; } } } | Create a file within this temporary directory prepopulating the file from the given input stream . |
9,662 | private static void init ( ) { String pkgs = System . getProperty ( "java.protocol.handler.pkgs" ) ; if ( pkgs == null || pkgs . trim ( ) . length ( ) == 0 ) { pkgs = "org.jboss.net.protocol|org.jboss.vfs.protocol" ; System . setProperty ( "java.protocol.handler.pkgs" , pkgs ) ; } else if ( pkgs . contains ( "org.jboss.vfs.protocol" ) == false ) { if ( pkgs . contains ( "org.jboss.net.protocol" ) == false ) { pkgs += "|org.jboss.net.protocol" ; } pkgs += "|org.jboss.vfs.protocol" ; System . setProperty ( "java.protocol.handler.pkgs" , pkgs ) ; } } | Initialize VFS protocol handlers package property . |
9,663 | public static Closeable mount ( VirtualFile mountPoint , FileSystem fileSystem ) throws IOException { final VirtualFile parent = mountPoint . getParent ( ) ; if ( parent == null ) { throw VFSMessages . MESSAGES . rootFileSystemAlreadyMounted ( ) ; } final String name = mountPoint . getName ( ) ; final Mount mount = new Mount ( fileSystem , mountPoint ) ; final ConcurrentMap < VirtualFile , Map < String , Mount > > mounts = VFS . mounts ; for ( ; ; ) { Map < String , Mount > childMountMap = mounts . get ( parent ) ; Map < String , Mount > newMap ; if ( childMountMap == null ) { childMountMap = mounts . putIfAbsent ( parent , Collections . singletonMap ( name , mount ) ) ; if ( childMountMap == null ) { return mount ; } } newMap = new HashMap < String , Mount > ( childMountMap ) ; if ( newMap . put ( name , mount ) != null ) { throw VFSMessages . MESSAGES . fileSystemAlreadyMountedAtMountPoint ( mountPoint ) ; } if ( mounts . replace ( parent , childMountMap , newMap ) ) { VFSLogger . ROOT_LOGGER . tracef ( "Mounted filesystem %s on mount point %s" , fileSystem , mountPoint ) ; return mount ; } } } | Mount a filesystem on a mount point in the VFS . The mount point is any valid file name existent or non - existent . If a relative path is given it will be treated as relative to the VFS root . |
9,664 | protected static void visit ( VirtualFile file , VirtualFileVisitor visitor ) throws IOException { if ( file == null ) { throw VFSMessages . MESSAGES . nullArgument ( "file" ) ; } visitor . visit ( file ) ; } | Visit the virtual file system |
9,665 | static Set < String > getSubmounts ( VirtualFile virtualFile ) { final ConcurrentMap < VirtualFile , Map < String , Mount > > mounts = VFS . mounts ; final Map < String , Mount > mountMap = mounts . get ( virtualFile ) ; if ( mountMap == null ) { return emptyRemovableSet ( ) ; } return new HashSet < String > ( mountMap . keySet ( ) ) ; } | Get all immediate submounts for a path . |
9,666 | public static Closeable mountReal ( File realRoot , VirtualFile mountPoint ) throws IOException { return doMount ( new RealFileSystem ( realRoot ) , mountPoint ) ; } | Create and mount a real file system returning a single handle which will unmount and close the filesystem when closed . |
9,667 | public static Closeable mountTemp ( VirtualFile mountPoint , TempFileProvider tempFileProvider ) throws IOException { boolean ok = false ; final TempDir tempDir = tempFileProvider . createTempDir ( "tmpfs" ) ; try { final MountHandle handle = doMount ( new RealFileSystem ( tempDir . getRoot ( ) ) , mountPoint , tempDir ) ; ok = true ; return handle ; } finally { if ( ! ok ) { VFSUtils . safeClose ( tempDir ) ; } } } | Create and mount a temporary file system returning a single handle which will unmount and close the filesystem when closed . |
9,668 | public static Closeable mountZipExpanded ( File zipFile , VirtualFile mountPoint , TempFileProvider tempFileProvider ) throws IOException { boolean ok = false ; final TempDir tempDir = tempFileProvider . createTempDir ( zipFile . getName ( ) ) ; try { final File rootFile = tempDir . getRoot ( ) ; VFSUtils . unzip ( zipFile , rootFile ) ; final MountHandle handle = doMount ( new RealFileSystem ( rootFile ) , mountPoint , tempDir ) ; ok = true ; return handle ; } finally { if ( ! ok ) { VFSUtils . safeClose ( tempDir ) ; } } } | Create and mount an expanded zip file in a temporary file system returning a single handle which will unmount and close the filesystem when closed . |
9,669 | public static Closeable mountZipExpanded ( InputStream zipData , String zipName , VirtualFile mountPoint , TempFileProvider tempFileProvider ) throws IOException { try { boolean ok = false ; final TempDir tempDir = tempFileProvider . createTempDir ( zipName ) ; try { final File zipFile = File . createTempFile ( zipName + "-" , ".tmp" , tempDir . getRoot ( ) ) ; try { final FileOutputStream os = new FileOutputStream ( zipFile ) ; try { VFSUtils . copyStream ( zipData , os ) ; zipData . close ( ) ; os . close ( ) ; } finally { VFSUtils . safeClose ( zipData ) ; VFSUtils . safeClose ( os ) ; } final File rootFile = tempDir . getRoot ( ) ; VFSUtils . unzip ( zipFile , rootFile ) ; final MountHandle handle = doMount ( new RealFileSystem ( rootFile ) , mountPoint , tempDir ) ; ok = true ; return handle ; } finally { zipFile . delete ( ) ; } } finally { if ( ! ok ) { VFSUtils . safeClose ( tempDir ) ; } } } finally { VFSUtils . safeClose ( zipData ) ; } } | Create and mount an expanded zip file in a temporary file system returning a single handle which will unmount and close the filesystem when closed . The given zip data stream is closed . |
9,670 | public static Closeable mountAssembly ( VirtualFileAssembly assembly , VirtualFile mountPoint ) throws IOException { return doMount ( new AssemblyFileSystem ( assembly ) , mountPoint ) ; } | Create and mount an assembly file system returning a single handle which will unmount and close the filesystem when closed . |
9,671 | private void closeCurrent ( ) throws IOException { virtualJarInputStream . closeEntry ( ) ; currentEntry . crc = crc . getValue ( ) ; crc . reset ( ) ; } | Close the current entry and calculate the crc value . |
9,672 | private boolean bufferLocalFileHeader ( ) throws IOException { buffer . reset ( ) ; JarEntry jarEntry = virtualJarInputStream . getNextJarEntry ( ) ; if ( jarEntry == null ) { return false ; } currentEntry = new ProcessedEntry ( jarEntry , totalRead ) ; processedEntries . add ( currentEntry ) ; bufferInt ( ZipEntry . LOCSIG ) ; bufferShort ( 10 ) ; bufferShort ( 0 ) ; bufferShort ( ZipEntry . STORED ) ; bufferInt ( jarEntry . getTime ( ) ) ; bufferInt ( 0 ) ; bufferInt ( 0 ) ; bufferInt ( 0 ) ; byte [ ] nameBytes = jarEntry . getName ( ) . getBytes ( "UTF8" ) ; bufferShort ( nameBytes . length ) ; bufferShort ( 0 ) ; buffer ( nameBytes ) ; return true ; } | Buffer the content of the local file header for a single entry . |
9,673 | private boolean bufferNextCentralFileHeader ( ) throws IOException { buffer . reset ( ) ; if ( currentCentralEntryIdx == processedEntries . size ( ) ) { return false ; } ProcessedEntry entry = processedEntries . get ( currentCentralEntryIdx ++ ) ; JarEntry jarEntry = entry . jarEntry ; bufferInt ( ZipEntry . CENSIG ) ; bufferShort ( 10 ) ; bufferShort ( 10 ) ; bufferShort ( 0 ) ; bufferShort ( ZipEntry . STORED ) ; bufferInt ( jarEntry . getTime ( ) ) ; bufferInt ( entry . crc ) ; bufferInt ( jarEntry . getSize ( ) ) ; bufferInt ( jarEntry . getSize ( ) ) ; byte [ ] nameBytes = jarEntry . getName ( ) . getBytes ( "UTF8" ) ; bufferShort ( nameBytes . length ) ; bufferShort ( 0 ) ; bufferShort ( 0 ) ; bufferShort ( 0 ) ; bufferShort ( 0 ) ; bufferInt ( 0 ) ; bufferInt ( entry . offset ) ; buffer ( nameBytes ) ; return true ; } | Buffer the central file header record for a single entry . |
9,674 | private void bufferCentralDirectoryEnd ( ) throws IOException { buffer . reset ( ) ; long lengthOfCentral = totalRead - centralOffset ; int count = processedEntries . size ( ) ; bufferInt ( JarEntry . ENDSIG ) ; bufferShort ( 0 ) ; bufferShort ( 0 ) ; bufferShort ( count ) ; bufferShort ( count ) ; bufferInt ( lengthOfCentral ) ; bufferInt ( centralOffset ) ; bufferShort ( 0 ) ; } | Write the central file header records . This is repeated until all entries have been added to the central file header . |
9,675 | private void bufferInt ( long i ) { buffer ( ( byte ) ( i & 0xff ) ) ; buffer ( ( byte ) ( ( i >>> 8 ) & 0xff ) ) ; buffer ( ( byte ) ( ( i >>> 16 ) & 0xff ) ) ; buffer ( ( byte ) ( ( i >>> 24 ) & 0xff ) ) ; } | Buffer a 32 - bit integer in little - endian |
9,676 | private void buffer ( byte b ) { if ( buffer . hasCapacity ( ) ) { buffer . put ( b ) ; } else { throw VFSMessages . MESSAGES . bufferDoesntHaveEnoughCapacity ( ) ; } } | Buffer a single byte |
9,677 | String getPathName ( boolean url ) { if ( pathName == null || pathName . isEmpty ( ) ) { VirtualFile [ ] path = getParentFiles ( ) ; final StringBuilder builder = new StringBuilder ( path . length * 30 + 50 ) ; for ( int i = path . length - 1 ; i > - 1 ; i -- ) { final VirtualFile parent = path [ i ] . parent ; if ( parent == null ) { builder . append ( path [ i ] . name ) ; } else { if ( parent . parent != null ) { builder . append ( '/' ) ; } builder . append ( path [ i ] . name ) ; } } pathName = builder . toString ( ) ; } return ( url && isDirectory ( ) ) ? pathName . concat ( "/" ) : pathName ; } | Get the absolute VFS full path name . If this is a URL then directory entries will have a trailing slash . |
9,678 | public long getLastModified ( ) { final SecurityManager sm = System . getSecurityManager ( ) ; if ( sm != null ) { sm . checkPermission ( new VirtualFilePermission ( getPathName ( ) , "read" ) ) ; } final VFS . Mount mount = VFS . getMount ( this ) ; if ( sm != null ) { return AccessController . doPrivileged ( ( PrivilegedAction < Long > ) ( ) -> mount . getFileSystem ( ) . getLastModified ( mount . getMountPoint ( ) , this ) ) ; } return mount . getFileSystem ( ) . getLastModified ( mount . getMountPoint ( ) , this ) ; } | When the file was last modified |
9,679 | public InputStream openStream ( ) throws IOException { final SecurityManager sm = System . getSecurityManager ( ) ; if ( sm != null ) { sm . checkPermission ( new VirtualFilePermission ( getPathName ( ) , "read" ) ) ; } if ( isDirectory ( ) ) { return new VirtualJarInputStream ( this ) ; } final VFS . Mount mount = VFS . getMount ( this ) ; if ( sm != null ) { return doIoPrivileged ( ( ) -> mount . getFileSystem ( ) . openInputStream ( mount . getMountPoint ( ) , this ) ) ; } return mount . getFileSystem ( ) . openInputStream ( mount . getMountPoint ( ) , this ) ; } | Access the file contents . |
9,680 | public File getPhysicalFile ( ) throws IOException { final SecurityManager sm = System . getSecurityManager ( ) ; if ( sm != null ) { sm . checkPermission ( new VirtualFilePermission ( getPathName ( ) , "getfile" ) ) ; } final VFS . Mount mount = VFS . getMount ( this ) ; if ( sm != null ) { return doIoPrivileged ( ( ) -> mount . getFileSystem ( ) . getFile ( mount . getMountPoint ( ) , this ) ) ; } return mount . getFileSystem ( ) . getFile ( mount . getMountPoint ( ) , this ) ; } | Get a physical file for this virtual file . Depending on the underlying file system type this may simply return an already - existing file ; it may create a copy of a file ; or it may reuse a preexisting copy of the file . Furthermore the returned file may or may not have any relationship to other files from the same or any other virtual directory . |
9,681 | public List < VirtualFile > getChildren ( ) { if ( ! isDirectory ( ) ) { return Collections . emptyList ( ) ; } final VFS . Mount mount = VFS . getMount ( this ) ; final Set < String > submounts = VFS . getSubmounts ( this ) ; final List < String > names = mount . getFileSystem ( ) . getDirectoryEntries ( mount . getMountPoint ( ) , this ) ; final List < VirtualFile > virtualFiles = new ArrayList < VirtualFile > ( names . size ( ) + submounts . size ( ) ) ; for ( String name : names ) { final VirtualFile child = new VirtualFile ( name , this ) ; virtualFiles . add ( child ) ; submounts . remove ( name ) ; } for ( String name : submounts ) { final VirtualFile child = new VirtualFile ( name , this ) ; virtualFiles . add ( child ) ; } return virtualFiles ; } | Get the children . This is the combined list of real children within this directory as well as virtual children created by submounts . |
9,682 | public List < VirtualFile > getChildren ( VirtualFileFilter filter ) throws IOException { if ( ! isDirectory ( ) ) { return Collections . emptyList ( ) ; } if ( filter == null ) { filter = MatchAllVirtualFileFilter . INSTANCE ; } FilterVirtualFileVisitor visitor = new FilterVirtualFileVisitor ( filter , null ) ; visit ( visitor ) ; return visitor . getMatched ( ) ; } | Get the children |
9,683 | public VirtualFile getChild ( String path ) { if ( path == null ) { throw VFSMessages . MESSAGES . nullArgument ( "path" ) ; } final List < String > pathParts = PathTokenizer . getTokens ( path ) ; VirtualFile current = this ; for ( String part : pathParts ) { if ( PathTokenizer . isReverseToken ( part ) ) { final VirtualFile parent = current . parent ; current = parent == null ? current : parent ; } else if ( PathTokenizer . isCurrentToken ( part ) == false ) { current = new VirtualFile ( part , current ) ; } } return current ; } | Get a child virtual file . The child may or may not exist in the virtual filesystem . |
9,684 | public static List < String > getTokens ( String path ) { if ( path == null ) { throw MESSAGES . nullArgument ( "path" ) ; } List < String > list = new ArrayList < String > ( ) ; getTokens ( list , path ) ; return list ; } | Get the tokens that comprise this path . |
9,685 | public static void getTokens ( List < String > list , String path ) { int start = - 1 , length = path . length ( ) , state = STATE_INITIAL ; char ch ; for ( int index = 0 ; index < length ; index ++ ) { ch = path . charAt ( index ) ; switch ( ch ) { case '/' : case '\\' : { switch ( state ) { case STATE_INITIAL : { continue ; } case STATE_MAYBE_CURRENT_PATH : { list . add ( CURRENT_PATH ) ; state = STATE_INITIAL ; continue ; } case STATE_MAYBE_REVERSE_PATH : { list . add ( REVERSE_PATH ) ; state = STATE_INITIAL ; continue ; } case STATE_NORMAL : { list . add ( path . substring ( start , index ) ) ; state = STATE_INITIAL ; continue ; } } continue ; } case '.' : { switch ( state ) { case STATE_INITIAL : { state = STATE_MAYBE_CURRENT_PATH ; start = index ; continue ; } case STATE_MAYBE_CURRENT_PATH : { state = STATE_MAYBE_REVERSE_PATH ; continue ; } case STATE_MAYBE_REVERSE_PATH : { state = STATE_NORMAL ; continue ; } } continue ; } default : { switch ( state ) { case STATE_INITIAL : { state = STATE_NORMAL ; start = index ; continue ; } case STATE_MAYBE_CURRENT_PATH : case STATE_MAYBE_REVERSE_PATH : { state = STATE_NORMAL ; } } } } } switch ( state ) { case STATE_INITIAL : { break ; } case STATE_MAYBE_CURRENT_PATH : { list . add ( CURRENT_PATH ) ; break ; } case STATE_MAYBE_REVERSE_PATH : { list . add ( REVERSE_PATH ) ; break ; } case STATE_NORMAL : { list . add ( path . substring ( start ) ) ; break ; } } return ; } | Get the tokens that comprise this path and append them to the list . |
9,686 | public static String applySpecialPaths ( String path ) throws IllegalArgumentException { List < String > tokens = getTokens ( path ) ; if ( tokens == null ) { return null ; } int i = 0 ; for ( int j = 0 ; j < tokens . size ( ) ; j ++ ) { String token = tokens . get ( j ) ; if ( isCurrentToken ( token ) ) { continue ; } else if ( isReverseToken ( token ) ) { i -- ; } else { tokens . set ( i ++ , token ) ; } if ( i < 0 ) { throw VFSMessages . MESSAGES . onRootPath ( ) ; } } return getRemainingPath ( tokens , 0 , i ) ; } | Apply any . or .. paths in the path param . |
9,687 | public static List < String > applySpecialPaths ( List < String > pathTokens ) throws IllegalArgumentException { final ArrayList < String > newTokens = new ArrayList < String > ( ) ; for ( String pathToken : pathTokens ) { if ( isCurrentToken ( pathToken ) ) { continue ; } else if ( isReverseToken ( pathToken ) ) { final int size = newTokens . size ( ) ; if ( size == 0 ) { throw VFSMessages . MESSAGES . onRootPath ( ) ; } newTokens . remove ( size - 1 ) ; } else { newTokens . add ( pathToken ) ; } } return newTokens ; } | Apply any . or .. paths in the pathTokens parameter returning the minimal token list . |
9,688 | public static String getPathsString ( Collection < VirtualFile > paths ) { if ( paths == null ) { throw MESSAGES . nullArgument ( "paths" ) ; } StringBuilder buffer = new StringBuilder ( ) ; boolean first = true ; for ( VirtualFile path : paths ) { if ( path == null ) { throw new IllegalArgumentException ( "Null path in " + paths ) ; } if ( first == false ) { buffer . append ( ':' ) ; } else { first = false ; } buffer . append ( path . getPathName ( ) ) ; } if ( first == true ) { buffer . append ( "<empty>" ) ; } return buffer . toString ( ) ; } | Get the paths string for a collection of virtual files |
9,689 | public static void addManifestLocations ( VirtualFile file , List < VirtualFile > paths ) throws IOException { if ( file == null ) { throw MESSAGES . nullArgument ( "file" ) ; } if ( paths == null ) { throw MESSAGES . nullArgument ( "paths" ) ; } boolean trace = VFSLogger . ROOT_LOGGER . isTraceEnabled ( ) ; Manifest manifest = getManifest ( file ) ; if ( manifest == null ) { return ; } Attributes mainAttributes = manifest . getMainAttributes ( ) ; String classPath = mainAttributes . getValue ( Attributes . Name . CLASS_PATH ) ; if ( classPath == null ) { if ( trace ) { VFSLogger . ROOT_LOGGER . tracef ( "Manifest has no Class-Path for %s" , file . getPathName ( ) ) ; } return ; } VirtualFile parent = file . getParent ( ) ; if ( parent == null ) { VFSLogger . ROOT_LOGGER . debugf ( "%s has no parent." , file ) ; return ; } if ( trace ) { VFSLogger . ROOT_LOGGER . tracef ( "Parsing Class-Path: %s for %s parent=%s" , classPath , file . getName ( ) , parent . getName ( ) ) ; } StringTokenizer tokenizer = new StringTokenizer ( classPath ) ; while ( tokenizer . hasMoreTokens ( ) ) { String path = tokenizer . nextToken ( ) ; try { VirtualFile vf = parent . getChild ( path ) ; if ( vf . exists ( ) ) { if ( paths . contains ( vf ) == false ) { paths . add ( vf ) ; Automounter . mount ( file , vf ) ; addManifestLocations ( vf , paths ) ; } else if ( trace ) { VFSLogger . ROOT_LOGGER . tracef ( "%s from manifest is already in the classpath %s" , vf . getName ( ) , paths ) ; } } else if ( trace ) { VFSLogger . ROOT_LOGGER . trace ( "Unable to find " + path + " from " + parent . getName ( ) ) ; } } catch ( IOException e ) { VFSLogger . ROOT_LOGGER . debugf ( "Manifest Class-Path entry %s ignored for %s reason= %s" , path , file . getPathName ( ) , e ) ; } } } | Add manifest paths |
9,690 | public static Manifest getManifest ( VirtualFile archive ) throws IOException { if ( archive == null ) { throw MESSAGES . nullArgument ( "archive" ) ; } VirtualFile manifest = archive . getChild ( JarFile . MANIFEST_NAME ) ; if ( manifest == null || ! manifest . exists ( ) ) { if ( VFSLogger . ROOT_LOGGER . isTraceEnabled ( ) ) { VFSLogger . ROOT_LOGGER . tracef ( "Can't find manifest for %s" , archive . getPathName ( ) ) ; } return null ; } return readManifest ( manifest ) ; } | Get a manifest from a virtual file assuming the virtual file is the root of an archive |
9,691 | public static Manifest readManifest ( VirtualFile manifest ) throws IOException { if ( manifest == null ) { throw MESSAGES . nullArgument ( "manifest file" ) ; } InputStream stream = new PaddedManifestStream ( manifest . openStream ( ) ) ; try { return new Manifest ( stream ) ; } finally { safeClose ( stream ) ; } } | Read the manifest from given manifest VirtualFile . |
9,692 | public static String decode ( String path , String encoding ) { try { return URLDecoder . decode ( path , encoding ) ; } catch ( UnsupportedEncodingException e ) { throw MESSAGES . cannotDecode ( path , encoding , e ) ; } } | Decode the path . |
9,693 | public static String getName ( URI uri ) { if ( uri == null ) { throw MESSAGES . nullArgument ( "uri" ) ; } String name = uri . getPath ( ) ; if ( name != null ) { int lastSlash = name . lastIndexOf ( '/' ) ; if ( lastSlash > 0 ) { name = name . substring ( lastSlash + 1 ) ; } } return name ; } | Get the name . |
9,694 | public static URI toURI ( URL url ) throws URISyntaxException { if ( url == null ) { throw MESSAGES . nullArgument ( "url" ) ; } try { return url . toURI ( ) ; } catch ( URISyntaxException e ) { String urispec = url . toExternalForm ( ) ; urispec = urispec . replaceAll ( "%" , "%25" ) ; urispec = urispec . replaceAll ( " " , "%20" ) ; return new URI ( urispec ) ; } } | Deal with urls that may include spaces . |
9,695 | public static void safeClose ( final Iterable < ? extends Closeable > ci ) { if ( ci != null ) { for ( Closeable closeable : ci ) { safeClose ( closeable ) ; } } } | Safely close some resources without throwing an exception . Any exception will be logged at TRACE level . |
9,696 | public static boolean exists ( File file ) { try { boolean fileExists = file . exists ( ) ; if ( ! forceCaseSensitive || ! fileExists ) { return fileExists ; } String absPath = canonicalize ( file . getAbsolutePath ( ) ) ; String canPath = canonicalize ( file . getCanonicalPath ( ) ) ; return fileExists && absPath . equals ( canPath ) ; } catch ( IOException io ) { return false ; } } | In case the file system is not case sensitive we compare the canonical path with the absolute path of the file after normalized . |
9,697 | public static boolean recursiveDelete ( VirtualFile root ) { boolean ok = true ; if ( root . isDirectory ( ) ) { final List < VirtualFile > files = root . getChildren ( ) ; for ( VirtualFile file : files ) { ok &= recursiveDelete ( file ) ; } return ok && ( root . delete ( ) || ! root . exists ( ) ) ; } else { ok &= root . delete ( ) || ! root . exists ( ) ; } return ok ; } | Attempt to recursively delete a virtual file . |
9,698 | public static void recursiveCopy ( File original , File destDir ) throws IOException { final String name = original . getName ( ) ; final File destFile = new File ( destDir , name ) ; if ( original . isDirectory ( ) ) { destFile . mkdir ( ) ; for ( File file : original . listFiles ( ) ) { recursiveCopy ( file , destFile ) ; } } else { final OutputStream os = new FileOutputStream ( destFile ) ; try { final InputStream is = new FileInputStream ( original ) ; copyStreamAndClose ( is , os ) ; } finally { safeClose ( os ) ; } } } | Recursively copy a file or directory from one location to another . |
9,699 | public static void unzip ( File zipFile , File destDir ) throws IOException { final ZipFile zip = new ZipFile ( zipFile ) ; try { final Set < File > createdDirs = new HashSet < File > ( ) ; final Enumeration < ? extends ZipEntry > entries = zip . entries ( ) ; FILES_LOOP : while ( entries . hasMoreElements ( ) ) { final ZipEntry zipEntry = entries . nextElement ( ) ; final String name = zipEntry . getName ( ) ; final List < String > tokens = PathTokenizer . getTokens ( name ) ; final Iterator < String > it = tokens . iterator ( ) ; File current = destDir ; while ( it . hasNext ( ) ) { String token = it . next ( ) ; if ( PathTokenizer . isCurrentToken ( token ) || PathTokenizer . isReverseToken ( token ) ) { continue FILES_LOOP ; } current = new File ( current , token ) ; if ( ( it . hasNext ( ) || zipEntry . isDirectory ( ) ) && createdDirs . add ( current ) ) { current . mkdir ( ) ; } } if ( ! zipEntry . isDirectory ( ) ) { final InputStream is = zip . getInputStream ( zipEntry ) ; try { final FileOutputStream os = new FileOutputStream ( current ) ; try { VFSUtils . copyStream ( is , os ) ; is . close ( ) ; os . close ( ) ; } finally { VFSUtils . safeClose ( os ) ; } } finally { VFSUtils . safeClose ( is ) ; } if ( ! current . getName ( ) . endsWith ( ".jsp" ) ) current . setLastModified ( zipEntry . getTime ( ) ) ; } } } finally { VFSUtils . safeClose ( zip ) ; } } | Expand a zip file to a destination directory . The directory must exist . If an error occurs the destination directory may contain a partially - extracted archive so cleanup is up to the caller . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.