idx
int64 0
41.2k
| question
stringlengths 73
5.81k
| target
stringlengths 5
918
|
|---|---|---|
2,900
|
static String toPattern ( String pos1 , String rel , String pos2 ) { return pos1 + ":" + rel + ":" + pos2 ; }
|
Returns the pattern string for the provided parts of speech and relation .
|
2,901
|
private int computePk1Measure ( double [ ] objectiveScores , double pk1Threshold ) { LOGGER . fine ( "Computing the PK1 measure" ) ; double average = 0 ; for ( int k = 0 ; k < objectiveScores . length ; ++ k ) average += objectiveScores [ k ] ; average /= objectiveScores . length ; double stdev = 0 ; for ( int k = 0 ; k < objectiveScores . length ; ++ k ) stdev += Math . pow ( objectiveScores [ k ] , 2 ) ; stdev /= objectiveScores . length ; stdev = Math . sqrt ( stdev ) ; for ( int k = 0 ; k < objectiveScores . length ; ++ k ) { objectiveScores [ k ] = ( objectiveScores [ k ] - average ) / stdev ; if ( objectiveScores [ k ] > pk1Threshold ) return k ; } return 0 ; }
|
Compute the smallest k that satisfies the Pk1 method .
|
2,902
|
private int computePk2Measure ( double [ ] objectiveScores ) { LOGGER . fine ( "Computing the PK2 measure" ) ; double average = 0 ; for ( int k = objectiveScores . length - 1 ; k > 0 ; -- k ) { objectiveScores [ k ] /= objectiveScores [ k - 1 ] ; average += objectiveScores [ k ] ; } average /= ( objectiveScores . length - 1 ) ; double stdev = 0 ; for ( int k = 1 ; k < objectiveScores . length ; ++ k ) stdev += Math . pow ( objectiveScores [ k ] - average , 2 ) ; stdev /= ( objectiveScores . length - 2 ) ; stdev = Math . sqrt ( stdev ) ; double referencePoint = 1 + stdev ; int bestIndex = 0 ; double bestScore = Double . MAX_VALUE ; for ( int k = 1 ; k < objectiveScores . length ; ++ k ) { if ( objectiveScores [ k ] < bestScore && objectiveScores [ k ] >= referencePoint ) { bestIndex = k ; bestScore = objectiveScores [ k ] ; } } return bestIndex ; }
|
Compute the smallest k that satisfies the Pk3 method .
|
2,903
|
private double extractScore ( String clutoOutput ) throws IOException { double score = 0 ; BufferedReader reader = new BufferedReader ( new StringReader ( clutoOutput ) ) ; String line = null ; while ( ( line = reader . readLine ( ) ) != null ) { if ( line . contains ( "[I2=" ) ) { String [ ] split = line . split ( "=" ) ; int endOfIndex = split [ 1 ] . indexOf ( "]" ) ; return Double . parseDouble ( split [ 1 ] . substring ( 0 , endOfIndex ) ) ; } } return 0 ; }
|
Extracts the score of the objective function for a given set of clustering assignments . This requires scraping the output from Cluto to find the line specifiying the score .
|
2,904
|
protected ArgOptions setupOptions ( ) { ArgOptions options = new ArgOptions ( ) ; options . addOption ( 'c' , "corpusDir" , "the directory of the corpus" , true , "DIR" , "Required" ) ; options . addOption ( 'a' , "analogyFile" , "the file containing list of word pairs" , true , "FILE" , "Required" ) ; options . addOption ( 't' , "testAnalogies" , "the file containing list of analogies" , true , "FILE" , "Required" ) ; options . addOption ( 'o' , "outputFile" , "the file containing the cosine similarity output " + "for the analogies from testAnalogies" , true , "FILE" , "Required" ) ; options . addOption ( 'i' , "indexDir" , "a Directory for storing or loading " + "the Lucene index" , true , "DIR" , "Required" ) ; options . addOption ( 'n' , "dimensions" , "the number of dimensions in the semantic space" , true , "INT" ) ; options . addOption ( 'r' , "readMatrixFile" , "file containing projection matrix" , true , "FILE" ) ; options . addOption ( 's' , "skipIndex" , "turn indexing off. Must specify index directory" , false , null ) ; options . addOption ( 'v' , "verbose" , "prints verbose output" , false , null , "Program Options" ) ; options . addOption ( 'w' , "writeMatrixFile" , "file to write projection matrix to" , true , "FILE" ) ; return options ; }
|
Adds the default options for running semantic space algorithms from the command line . Subclasses should override this method and return a different instance if the default options need to be different .
|
2,905
|
public static synchronized DependencyExtractor getExtractor ( String name ) { DependencyExtractor e = nameToExtractor . get ( name ) ; if ( e == null ) throw new IllegalArgumentException ( "No extactor with name " + name ) ; return e ; }
|
Returns the extractor with the specified name . The name typically refers to the parser that generated the output files that the extractor can read .
|
2,906
|
public double count ( T obj ) { double count = counts . get ( obj ) ; count ++ ; counts . put ( obj , count ) ; sum ++ ; return count ; }
|
Counts the object increasing its total count by 1 .
|
2,907
|
public Iterator < Map . Entry < T , Double > > iterator ( ) { return Collections . unmodifiableSet ( TDecorators . wrap ( counts ) . entrySet ( ) ) . iterator ( ) ; }
|
Returns an interator over the elements that have been counted thusfar and their respective counts .
|
2,908
|
private static double distanceSum ( double [ ] distances ) { double sum = 0 ; for ( double distance : distances ) sum += Math . pow ( distance , 2 ) ; return sum ; }
|
Returns the sum of distances squared .
|
2,909
|
private boolean advance ( int tokens ) { while ( buffer . size ( ) < tokens && tokenizer . hasNext ( ) ) buffer . add ( tokenizer . next ( ) ) ; return buffer . size ( ) >= tokens ; }
|
Advances the specified number of tokens in the stream and places them in the buffer .
|
2,910
|
public static void initializeIndex ( String indexDir , String dataDir ) { File indexDir_f = new File ( indexDir ) ; File dataDir_f = new File ( dataDir ) ; long start = new Date ( ) . getTime ( ) ; try { int numIndexed = index ( indexDir_f , dataDir_f ) ; long end = new Date ( ) . getTime ( ) ; System . err . println ( "Indexing " + numIndexed + " files took " + ( end - start ) + " milliseconds" ) ; } catch ( IOException e ) { System . err . println ( "Unable to index " + indexDir_f + ": " + e . getMessage ( ) ) ; } }
|
Initializes an index given the index directory and data directory .
|
2,911
|
private static int index ( File indexDir , File dataDir ) throws IOException { if ( ! dataDir . exists ( ) || ! dataDir . isDirectory ( ) ) { throw new IOException ( dataDir + " does not exist or is not a directory" ) ; } IndexWriter writer = new IndexWriter ( indexDir , new StandardAnalyzer ( ) , true , IndexWriter . MaxFieldLength . UNLIMITED ) ; writer . setUseCompoundFile ( false ) ; indexDirectory ( writer , dataDir ) ; int numIndexed = writer . numDocs ( ) ; writer . optimize ( ) ; writer . close ( ) ; return numIndexed ; }
|
creates the index files
|
2,912
|
private static HashSet < String > searchDirectoryForPattern ( File dir , String A , String B ) throws Exception { File [ ] files = dir . listFiles ( ) ; HashSet < String > pattern_set = new HashSet < String > ( ) ; for ( int i = 0 ; i < files . length ; i ++ ) { File f = files [ i ] ; if ( f . isDirectory ( ) ) { pattern_set . addAll ( searchDirectoryForPattern ( f , A , B ) ) ; } else if ( f . getName ( ) . endsWith ( ".txt" ) ) { Scanner sc = new Scanner ( f ) ; while ( sc . hasNext ( ) ) { if ( A . equals ( sc . next ( ) ) ) { String pattern = "" ; int count = 0 ; while ( count <= MAX_INTER && sc . hasNext ( ) ) { String curr = sc . next ( ) ; if ( count >= MIN_INTER && B . equals ( curr ) ) { pattern_set . add ( pattern ) ; break ; } else { if ( count > 0 ) { pattern += " " ; } pattern += curr ; count ++ ; } } } } } } return pattern_set ; }
|
recursive method that finds interleving patterns between A and B in all files within a given directory
|
2,913
|
private static void indexDirectory ( IndexWriter writer , File dir ) throws IOException { File [ ] files = dir . listFiles ( ) ; for ( int i = 0 ; i < files . length ; i ++ ) { File f = files [ i ] ; if ( f . isDirectory ( ) ) { indexDirectory ( writer , f ) ; } else if ( f . getName ( ) . endsWith ( ".txt" ) ) { indexFile ( writer , f ) ; } } }
|
recursive method that calls itself when it finds a directory or indexes if it is at a file ending in . txt
|
2,914
|
private static void indexFile ( IndexWriter writer , File f ) throws IOException { if ( f . isHidden ( ) || ! f . exists ( ) || ! f . canRead ( ) ) { System . err . println ( "Could not write " + f . getName ( ) ) ; return ; } System . err . println ( "Indexing " + f . getCanonicalPath ( ) ) ; Document doc = new Document ( ) ; doc . add ( new Field ( "path" , f . getCanonicalPath ( ) , Field . Store . YES , Field . Index . NOT_ANALYZED ) ) ; doc . add ( new Field ( "modified" , DateTools . timeToString ( f . lastModified ( ) , DateTools . Resolution . MINUTE ) , Field . Store . YES , Field . Index . NOT_ANALYZED ) ) ; doc . add ( new Field ( "contents" , new FileReader ( f ) ) ) ; writer . addDocument ( doc ) ; }
|
method to actually index a file using Lucene adds a document onto the index writer
|
2,915
|
public static float countPhraseFrequencies ( String indexDir , String A , String B ) { File indexDir_f = new File ( indexDir ) ; if ( ! indexDir_f . exists ( ) || ! indexDir_f . isDirectory ( ) ) { System . err . println ( "Search failed: index directory does not exist" ) ; } else { try { return searchPhrase ( indexDir_f , A , B ) ; } catch ( Exception e ) { System . err . println ( "Unable to search " + indexDir ) ; return 0 ; } } return 0 ; }
|
Searches an index given the index directory and counts up the frequncy of the two words used in a phrase .
|
2,916
|
private static float searchPhrase ( File indexDir , String A , String B ) throws Exception { Directory fsDir = FSDirectory . getDirectory ( indexDir ) ; IndexSearcher searcher = new IndexSearcher ( fsDir ) ; long start = new Date ( ) . getTime ( ) ; QueryParser parser = new QueryParser ( "contents" , new StandardAnalyzer ( ) ) ; parser . setPhraseSlop ( MAX_PHRASE ) ; String my_phrase = "\"" + A + " " + B + "\"" ; Query query = parser . parse ( my_phrase ) ; searcher . setSimilarity ( new Similarity ( ) { public static final long serialVersionUID = 1L ; public float coord ( int overlap , int maxOverlap ) { return 1 ; } public float queryNorm ( float sumOfSquaredWeights ) { return 1 ; } public float tf ( float freq ) { return freq ; } public float idf ( int docFreq , int numDocs ) { return 1 ; } public float lengthNorm ( String fieldName , int numTokens ) { return 1 ; } public float sloppyFreq ( int distance ) { return 1 ; } } ) ; TopDocs results = searcher . search ( query , 10 ) ; ScoreDoc [ ] hits = results . scoreDocs ; float total_score = 0 ; for ( ScoreDoc hit : hits ) { Document doc = searcher . doc ( hit . doc ) ; total_score += hit . score ; } long end = new Date ( ) . getTime ( ) ; searcher . close ( ) ; return total_score ; }
|
method that actually does the searching
|
2,917
|
private static String combinatorialPatternMaker ( String [ ] str , int str_size , int c ) { String comb_pattern = "" ; int curr_comb = 1 ; for ( int i = 0 ; i < str_size ; i ++ ) { if ( ( c & curr_comb ) != 0 ) { comb_pattern += str [ i ] + "\\s" ; } else { comb_pattern += "[\\w]+\\s" ; } curr_comb = curr_comb << 1 ; } return comb_pattern ; }
|
Makes patterns by replacing words in str with wildcards based on the binary value of c .
|
2,918
|
private static int countWildcardPhraseFrequencies ( File dir , String pattern ) throws Exception { File [ ] files = dir . listFiles ( ) ; int total = 0 ; for ( int i = 0 ; i < files . length ; i ++ ) { File f = files [ i ] ; if ( f . isDirectory ( ) ) { total += countWildcardPhraseFrequencies ( f , pattern ) ; } else if ( f . getName ( ) . endsWith ( ".txt" ) ) { Scanner sc = new Scanner ( f ) ; while ( sc . hasNext ( ) ) { String line = sc . nextLine ( ) ; if ( line . matches ( pattern ) ) { total ++ ; } } } } return total ; }
|
Searches through all the . txt files in a directory and returns the total number of occurrences of a pattern .
|
2,919
|
private static int getIndexOfPair ( String value , Map < Integer , String > row_data ) { for ( Integer i : row_data . keySet ( ) ) { if ( row_data . get ( i ) . equals ( value ) ) { return i . intValue ( ) ; } } return - 1 ; }
|
returns the index of the String in the HashMap or - 1 if value was not found .
|
2,920
|
public Matrix computeSVD ( Matrix sparse_matrix , int dimensions ) { try { File rawTermDocMatrix = File . createTempFile ( "lra-term-document-matrix" , ".dat" ) ; MatrixIO . writeMatrix ( sparse_matrix , rawTermDocMatrix , MatrixIO . Format . SVDLIBC_SPARSE_TEXT ) ; MatrixFile mFile = new MatrixFile ( rawTermDocMatrix , MatrixIO . Format . SVDLIBC_SPARSE_TEXT ) ; reducer . factorize ( mFile , dimensions ) ; return reducer . dataClasses ( ) ; } catch ( IOException ioe ) { throw new IOError ( ioe ) ; } }
|
Does the Singular Value Decomposition using the generated sparse matrix . The dimensions used cannot exceed the number of columns in the original matrix .
|
2,921
|
public void evaluateAnalogies ( Matrix projection , String inputFileName , String outputFileName ) { try { Scanner sc = new Scanner ( new File ( inputFileName ) ) ; PrintStream out = new PrintStream ( new FileOutputStream ( outputFileName ) ) ; while ( sc . hasNext ( ) ) { String analogy = sc . next ( ) ; if ( ! isAnalogyFormat ( analogy , true ) ) { System . err . println ( "\"" + analogy + "\" not in proper format." ) ; continue ; } double cosineVal = computeCosineSimilarity ( analogy , projection ) ; out . println ( analogy + " = " + cosineVal ) ; } sc . close ( ) ; out . close ( ) ; } catch ( Exception e ) { System . err . println ( "Could not read file." ) ; } }
|
Reads analogies from file and outputs their cosine similarities to another file .
|
2,922
|
public void evaluateAnalogies ( Matrix projection ) { try { Scanner sc = new Scanner ( System . in ) ; while ( sc . hasNext ( ) ) { String analogy = sc . next ( ) ; if ( ! isAnalogyFormat ( analogy , true ) ) { System . err . println ( "\"" + analogy + "\" not in proper format." ) ; continue ; } double cosineVal = computeCosineSimilarity ( analogy , projection ) ; System . out . println ( analogy + " = " + cosineVal ) ; } sc . close ( ) ; } catch ( Exception e ) { System . err . println ( "Could not read file." ) ; } }
|
Reads analogies from Standard In and outputs their cosine similarities to Standard Out .
|
2,923
|
private void loadOffsetsFromFormat ( File file , SSpaceFormat format ) throws IOException { this . format = format ; spaceName = file . getName ( ) ; termToOffset = new LinkedHashMap < String , Long > ( ) ; long start = System . currentTimeMillis ( ) ; int dims = - 1 ; RandomAccessFile raf = null ; RandomAccessBufferedReader lnr = null ; switch ( format ) { case TEXT : lnr = new RandomAccessBufferedReader ( file ) ; dims = loadTextOffsets ( lnr ) ; break ; case BINARY : raf = new RandomAccessFile ( file , "r" ) ; dims = loadBinaryOffsets ( raf ) ; break ; case SPARSE_TEXT : lnr = new RandomAccessBufferedReader ( file ) ; dims = loadSparseTextOffsets ( lnr ) ; break ; case SPARSE_BINARY : raf = new RandomAccessFile ( file , "r" ) ; dims = loadSparseBinaryOffsets ( raf ) ; break ; default : assert false : format ; } if ( LOGGER . isLoggable ( Level . FINE ) ) { LOGGER . fine ( "loaded " + format + " .sspace file in " + ( System . currentTimeMillis ( ) - start ) + "ms" ) ; } this . dimensions = dims ; this . binarySSpace = raf ; this . textSSpace = lnr ; }
|
Loads the words and offets for each word s vector in the semantic space file using the format as a guide to how the semantic space data is stored in the file .
|
2,924
|
private < E extends WeightedEdge > SparseDoubleVector getVertexWeightVector ( WeightedGraph < E > g , int vertex ) { if ( keepWeightVectors ) { SparseDoubleVector weightVec = vertexToWeightVector . get ( vertex ) ; if ( weightVec == null ) { synchronized ( this ) { weightVec = vertexToWeightVector . get ( vertex ) ; if ( weightVec == null ) { weightVec = computeWeightVector ( g , vertex ) ; vertexToWeightVector . put ( vertex , weightVec ) ; } } } return weightVec ; } else return computeWeightVector ( g , vertex ) ; }
|
Returns the normalized weight vector for the specified row to be used in edge comparisons . The weight vector is normalized by the number of edges from the row with positive weights and includes a weight for the row to itself which reflects the similarity of the keystone nod .
|
2,925
|
private void process ( Iterator < String > tokens ) { long numTokens = 0 ; while ( tokens . hasNext ( ) ) { String token = tokens . next ( ) ; if ( doLowerCasing ) token = token . toLowerCase ( ) ; if ( token . matches ( "[0-9]+" ) ) token = "<NUM>" ; if ( token . matches ( "[^\\w\\s;:\\(\\)\\[\\]'!/&?\",\\.<>]" ) ) continue ; Integer count = tokenToCount . get ( token ) ; tokenToCount . put ( token , ( count == null ) ? 1 : 1 + count ) ; numTokens ++ ; if ( numTokens % UPDATE_INTERVAL == 0 && LOGGER . isLoggable ( Level . FINE ) ) LOGGER . fine ( "Processed " + numTokens + " tokens. Currently " + tokenToCount . size ( ) + " unique tokens" ) ; } }
|
Counts all of the tokens in the iterator
|
2,926
|
public void setCurrent ( String value ) { current . replace ( 0 , current . length ( ) , value ) ; cursor = 0 ; limit = current . length ( ) ; limit_backward = 0 ; bra = cursor ; ket = limit ; }
|
Set the current string .
|
2,927
|
private TernaryVector getTermIndexVector ( String term ) { TernaryVector iv = termToIndexVector . get ( term ) ; if ( iv == null ) { synchronized ( this ) { iv = termToIndexVector . get ( term ) ; if ( iv == null ) { termToIndex . put ( term , termIndexCounter ++ ) ; termToReflectiveSemantics . put ( term , createVector ( ) ) ; iv = indexVectorGenerator . generate ( ) ; termToIndexVector . put ( term , iv ) ; } } } return iv ; }
|
Returns the index vector for the term or if creates one if the term to index vector mapping does not yet exist .
|
2,928
|
private void processSpace ( ) throws IOException { LOGGER . info ( "generating reflective vectors" ) ; compressedDocumentsWriter . close ( ) ; int numDocuments = documentCounter . get ( ) ; termToIndexVector . clear ( ) ; indexToTerm = new String [ termToIndex . size ( ) ] ; for ( Map . Entry < String , Integer > e : termToIndex . entrySet ( ) ) indexToTerm [ e . getValue ( ) ] = e . getKey ( ) ; DataInputStream corpusReader = new DataInputStream ( new BufferedInputStream ( new FileInputStream ( compressedDocuments ) ) ) ; final BlockingQueue < Runnable > workQueue = new LinkedBlockingQueue < Runnable > ( ) ; for ( int i = 0 ; i < Runtime . getRuntime ( ) . availableProcessors ( ) ; ++ i ) { Thread t = new WorkerThread ( workQueue ) ; t . start ( ) ; } final Semaphore documentsRerocessed = new Semaphore ( 0 ) ; for ( int d = 0 ; d < numDocuments ; ++ d ) { final int docId = d ; int tokensInDoc = corpusReader . readInt ( ) ; final int [ ] doc = new int [ tokensInDoc ] ; for ( int i = 0 ; i < tokensInDoc ; ++ i ) doc [ i ] = corpusReader . readInt ( ) ; workQueue . offer ( new Runnable ( ) { public void run ( ) { LOGGER . fine ( "reprocessing doc #" + docId ) ; processIntDocument ( docToVector . get ( docId ) , doc ) ; documentsRerocessed . release ( ) ; } } ) ; } corpusReader . close ( ) ; try { documentsRerocessed . acquire ( numDocuments ) ; } catch ( InterruptedException ie ) { throw new Error ( "interrupted while waiting for documents to " + "finish reprocessing" , ie ) ; } LOGGER . fine ( "finished reprocessing all documents" ) ; }
|
Computes the reflective semantic vectors for word meanings
|
2,929
|
private void processIntDocument ( IntegerVector docVector , int [ ] document ) { for ( int termIndex : document ) { IntegerVector reflectiveVector = termToReflectiveSemantics . get ( indexToTerm [ termIndex ] ) ; synchronized ( reflectiveVector ) { VectorMath . add ( reflectiveVector , docVector ) ; } } }
|
Processes the compressed version of a document where each integer indicates that token s index adding the document s vector to the reflective semantic vector each time a term occurs in the document .
|
2,930
|
public static Iterator < MatrixEntry > getMatrixFileIterator ( File matrixFile , Format fileFormat ) throws IOException { switch ( fileFormat ) { case DENSE_TEXT : return new DenseTextFileIterator ( matrixFile ) ; case SVDLIBC_SPARSE_BINARY : return new SvdlibcSparseBinaryFileIterator ( matrixFile ) ; case SVDLIBC_SPARSE_TEXT : return new SvdlibcSparseTextFileIterator ( matrixFile ) ; case SVDLIBC_DENSE_BINARY : return new SvdlibcDenseBinaryFileIterator ( matrixFile ) ; case CLUTO_SPARSE : return new ClutoSparseFileIterator ( matrixFile ) ; case CLUTO_DENSE : case SVDLIBC_DENSE_TEXT : return new SvdlibcDenseTextFileIterator ( matrixFile ) ; case MATLAB_SPARSE : return new MatlabSparseFileIterator ( matrixFile ) ; } throw new Error ( "Iterating over matrices of " + fileFormat + " format is not " + "currently supported. Email " + "s-space-research-dev@googlegroups.com to request its" + "inclusion and it will be quickly added" ) ; }
|
Returns an iterator over the matrix entries in the data file . For sparse formats that specify only non - zero no zero valued entries will be returened . Conversely for dense matrix formats all of the entries including zero entries will be returned .
|
2,931
|
private int getDimension ( PathSignature path ) { Integer index = pathToIndex . get ( path ) ; if ( index == null && ! readOnly ) { synchronized ( this ) { index = pathToIndex . get ( path ) ; if ( index == null ) { int i = pathToIndex . size ( ) ; pathToIndex . put ( path , i ) ; return i ; } } } return index ; }
|
Returns the dimension represention the occurrence of the provided path . If the path was not previously assigned an index this method adds one for it and returns that index .
|
2,932
|
public BufferedReader open ( String fileName ) throws IOException { Path filePath = new Path ( fileName ) ; if ( ! hadoopFs . exists ( filePath ) ) { throw new IOException ( fileName + " does not exist in HDFS" ) ; } BufferedReader br = new BufferedReader ( new InputStreamReader ( hadoopFs . open ( filePath ) ) ) ; return br ; }
|
Finds the file with the specified name and returns a reader for that files contents .
|
2,933
|
static Matrix [ ] svdlibc ( File matrix , int dimensions , Format format ) { try { String formatString = "" ; switch ( format ) { case SVDLIBC_DENSE_BINARY : formatString = " -r db " ; break ; case SVDLIBC_DENSE_TEXT : formatString = " -r dt " ; break ; case SVDLIBC_SPARSE_BINARY : formatString = " -r sb " ; break ; case SVDLIBC_SPARSE_TEXT : break ; default : throw new UnsupportedOperationException ( "Format type is not accepted" ) ; } File outputMatrixFile = File . createTempFile ( "svdlibc" , ".dat" ) ; outputMatrixFile . deleteOnExit ( ) ; String outputMatrixPrefix = outputMatrixFile . getAbsolutePath ( ) ; SVD_LOGGER . fine ( "creating SVDLIBC factor matrices at: " + outputMatrixPrefix ) ; String commandLine = "svd -o " + outputMatrixPrefix + formatString + " -w dt " + " -d " + dimensions + " " + matrix . getAbsolutePath ( ) ; SVD_LOGGER . fine ( commandLine ) ; Process svdlibc = Runtime . getRuntime ( ) . exec ( commandLine ) ; BufferedReader stdout = new BufferedReader ( new InputStreamReader ( svdlibc . getInputStream ( ) ) ) ; BufferedReader stderr = new BufferedReader ( new InputStreamReader ( svdlibc . getErrorStream ( ) ) ) ; StringBuilder output = new StringBuilder ( "SVDLIBC output:\n" ) ; for ( String line = null ; ( line = stderr . readLine ( ) ) != null ; ) { output . append ( line ) . append ( "\n" ) ; } SVD_LOGGER . fine ( output . toString ( ) ) ; int exitStatus = svdlibc . waitFor ( ) ; SVD_LOGGER . fine ( "svdlibc exit status: " + exitStatus ) ; if ( exitStatus == 0 ) { File Ut = new File ( outputMatrixPrefix + "-Ut" ) ; File S = new File ( outputMatrixPrefix + "-S" ) ; File Vt = new File ( outputMatrixPrefix + "-Vt" ) ; return new Matrix [ ] { MatrixIO . readMatrix ( Ut , Format . SVDLIBC_DENSE_TEXT , Type . DENSE_IN_MEMORY , true ) , readSVDLIBCsingularVector ( S ) , MatrixIO . readMatrix ( Vt , Format . SVDLIBC_DENSE_TEXT , Type . DENSE_ON_DISK ) } ; } else { StringBuilder sb = new StringBuilder ( ) ; for ( String line = null ; ( line = stderr . readLine ( ) ) != null ; ) { sb . append ( line ) . append ( "\n" ) ; } SVD_LOGGER . warning ( "svdlibc exited with error status. " + "stderr:\n" + sb . toString ( ) ) ; } } catch ( IOException ioe ) { SVD_LOGGER . log ( Level . SEVERE , "SVDLIBC" , ioe ) ; } catch ( InterruptedException ie ) { SVD_LOGGER . log ( Level . SEVERE , "SVDLIBC" , ie ) ; } throw new UnsupportedOperationException ( "SVDLIBC is not correctly installed on this system" ) ; }
|
Computes the SVD using SVDLIBC .
|
2,934
|
static Matrix [ ] matlabSVDS ( File matrix , int dimensions ) { try { File uOutput = File . createTempFile ( "matlab-svds-U" , ".dat" ) ; File sOutput = File . createTempFile ( "matlab-svds-S" , ".dat" ) ; File vOutput = File . createTempFile ( "matlab-svds-V" , ".dat" ) ; if ( SVD_LOGGER . isLoggable ( Level . FINE ) ) { SVD_LOGGER . fine ( "writing Matlab output to files:\n" + " " + uOutput + "\n" + " " + sOutput + "\n" + " " + vOutput + "\n" ) ; } uOutput . deleteOnExit ( ) ; sOutput . deleteOnExit ( ) ; vOutput . deleteOnExit ( ) ; String commandLine = "matlab -nodisplay -nosplash -nojvm" ; SVD_LOGGER . fine ( commandLine ) ; Process matlab = Runtime . getRuntime ( ) . exec ( commandLine ) ; BufferedReader br = new BufferedReader ( new InputStreamReader ( matlab . getInputStream ( ) ) ) ; PrintWriter pw = new PrintWriter ( matlab . getOutputStream ( ) ) ; pw . println ( "Z = load('" + matrix . getAbsolutePath ( ) + "','-ascii');\n" + "A = spconvert(Z);\n" + "% Remove the raw data file to save space\n" + "clear Z;\n" + "[U, S, V] = svds(A, " + dimensions + " );\n" + "save " + uOutput . getAbsolutePath ( ) + " U -ASCII\n" + "save " + sOutput . getAbsolutePath ( ) + " S -ASCII\n" + "save " + vOutput . getAbsolutePath ( ) + " V -ASCII\n" + "fprintf('Matlab Finished\\n');" ) ; pw . close ( ) ; StringBuilder output = new StringBuilder ( "Matlab svds output:\n" ) ; for ( String line = null ; ( line = br . readLine ( ) ) != null ; ) { output . append ( line ) . append ( "\n" ) ; if ( line . equals ( "Matlab Finished" ) ) { matlab . destroy ( ) ; } } SVD_LOGGER . fine ( output . toString ( ) ) ; int exitStatus = matlab . waitFor ( ) ; SVD_LOGGER . fine ( "Matlab svds exit status: " + exitStatus ) ; if ( exitStatus == 0 ) { return new Matrix [ ] { MatrixIO . readMatrix ( uOutput , Format . DENSE_TEXT , Type . DENSE_IN_MEMORY ) , MatrixIO . readMatrix ( sOutput , Format . DENSE_TEXT , Type . SPARSE_ON_DISK ) , MatrixIO . readMatrix ( vOutput , Format . DENSE_TEXT , Type . DENSE_ON_DISK , true ) } ; } } catch ( IOException ioe ) { SVD_LOGGER . log ( Level . SEVERE , "Matlab svds" , ioe ) ; } catch ( InterruptedException ie ) { SVD_LOGGER . log ( Level . SEVERE , "Matlab svds" , ie ) ; } throw new UnsupportedOperationException ( "Matlab svds is not correctly installed on this system" ) ; }
|
Computes the SVD using Matlab .
|
2,935
|
private static Set < Language > getApplicableLanguages ( PMDConfiguration configuration , RuleSets ruleSets ) { Set < Language > languages = new HashSet < > ( ) ; LanguageVersionDiscoverer discoverer = configuration . getLanguageVersionDiscoverer ( ) ; for ( Rule rule : ruleSets . getAllRules ( ) ) { Language language = rule . getLanguage ( ) ; if ( languages . contains ( language ) ) continue ; LanguageVersion version = discoverer . getDefaultLanguageVersion ( language ) ; if ( RuleSet . applies ( rule , version ) ) { languages . add ( language ) ; log . debug ( "Using {} version: {}" , language . getShortName ( ) , version . getShortName ( ) ) ; } } return languages ; }
|
Paste from PMD
|
2,936
|
public ReviewResult parseResults ( ) throws IOException { ReviewResult result = new ReviewResult ( ) ; ObjectMapper mapper = new ObjectMapper ( ) ; JsonNode rootNode = mapper . readTree ( new FileReader ( resultFile ) ) ; JsonNode issues = rootNode . path ( "issues" ) ; Iterator < JsonNode > issuesIterator = issues . iterator ( ) ; Map < String , Component > components = getComponents ( rootNode . path ( "components" ) ) ; while ( issuesIterator . hasNext ( ) ) { JsonNode issue = issuesIterator . next ( ) ; boolean isNew = issue . path ( "isNew" ) . asBoolean ( ) ; if ( ! isNew ) { log . debug ( "Skipping already indexed issue: {}" , issue . toString ( ) ) ; continue ; } JsonNode lineNode = issue . path ( "line" ) ; if ( lineNode . isMissingNode ( ) ) { log . debug ( "Skipping an issue with no line information: {}" , issue . toString ( ) ) ; continue ; } int line = lineNode . asInt ( ) ; String message = issue . path ( "message" ) . asText ( ) ; String file = getIssueFilePath ( issue . path ( "component" ) . asText ( ) , components ) ; String severity = issue . path ( "severity" ) . asText ( ) ; String rule = issue . path ( "rule" ) . asText ( ) ; result . add ( new Violation ( file , line , String . format ( "%s (Rule: %s)" , message , rule ) , getSeverity ( severity ) ) ) ; } return result ; }
|
Parses the file and returns all the issues as a ReviewResult .
|
2,937
|
static Severity getSeverity ( String severityName ) { switch ( severityName ) { case "BLOCKER" : case "CRITICAL" : case "MAJOR" : return Severity . ERROR ; case "MINOR" : return Severity . WARNING ; case "INFO" : return Severity . INFO ; default : log . warn ( "Unknown severity: " + severityName ) ; } return Severity . WARNING ; }
|
Converts a Sonar severity to a Sputnik severity .
|
2,938
|
private Map < String , Component > getComponents ( JsonNode componentsNode ) { Iterator < JsonNode > it = componentsNode . iterator ( ) ; Map < String , Component > components = Maps . newHashMap ( ) ; while ( it . hasNext ( ) ) { JsonNode componentNode = it . next ( ) ; JsonNode pathNode = componentNode . path ( "path" ) ; JsonNode moduleNode = componentNode . path ( "moduleKey" ) ; components . put ( componentNode . path ( "key" ) . asText ( ) , new Component ( pathNode . asText ( ) , moduleNode . isMissingNode ( ) ? null : moduleNode . asText ( ) ) ) ; } return components ; }
|
Extracts all the components from the json data .
|
2,939
|
private String getIssueFilePath ( String issueComponent , Map < String , Component > components ) { Component comp = components . get ( issueComponent ) ; String file = comp . path ; if ( ! Strings . isNullOrEmpty ( comp . moduleKey ) ) { String theKey = comp . moduleKey ; while ( ! theKey . isEmpty ( ) ) { Component theChildComp = components . get ( theKey ) ; int p = theKey . lastIndexOf ( ":" ) ; if ( p > 0 ) { theKey = theKey . substring ( 0 , p ) ; } else { theKey = "" ; } if ( theChildComp != null && ! Strings . isNullOrEmpty ( theChildComp . path ) ) { file = theChildComp . path + '/' + file ; } } } return file ; }
|
Returns the path of the file linked to an issue created by Sonar . The path is relative to the folder where Sonar has been run .
|
2,940
|
public String reviewFile ( String filePath ) { log . info ( "Reviewing file: " + filePath ) ; String [ ] args = new String [ ] { NODE_JS , tsScript , TS_LINT_OUTPUT_KEY , TS_LINT_OUTPUT_VALUE , TS_LINT_CONFIG_PARAM , configFile , filePath } ; return new ExternalProcess ( ) . executeCommand ( args ) ; }
|
Executes TSLint to look for violations .
|
2,941
|
public File run ( ) throws IOException { Map < String , String > props = loadBaseProperties ( ) ; setAdditionalProperties ( props ) ; sonarEmbeddedScanner . addGlobalProperties ( props ) ; log . info ( "Sonar configuration: {}" , props . toString ( ) ) ; sonarEmbeddedScanner . start ( ) ; sonarEmbeddedScanner . execute ( new HashMap < String , String > ( ) ) ; return new File ( OUTPUT_DIR , OUTPUT_FILE ) ; }
|
Runs Sonar .
|
2,942
|
public Collection < BitfinexWallet > getWallets ( ) throws BitfinexClientException { throwExceptionIfUnauthenticated ( ) ; synchronized ( walletTable ) { return Collections . unmodifiableCollection ( walletTable . values ( ) ) ; } }
|
Get all wallets
|
2,943
|
public boolean removeOrderbookCallback ( final BitfinexOrderBookSymbol symbol , final BiConsumer < BitfinexOrderBookSymbol , BitfinexOrderBookEntry > callback ) throws BitfinexClientException { return channelCallbacks . removeCallback ( symbol , callback ) ; }
|
Remove the a trading orderbook callback
|
2,944
|
private boolean checkTickerFreshness ( ) { final QuoteManager quoteManager = bitfinexApiBroker . getQuoteManager ( ) ; final Map < BitfinexStreamSymbol , Long > heartbeatValues = quoteManager . getLastTickerActivity ( ) ; return checkTickerFreshness ( heartbeatValues ) ; }
|
Are all tickers up - to - date
|
2,945
|
private void sendHeartbeatIfNeeded ( ) { final long nextHeartbeat = lastHeartbeatSupplier . get ( ) + HEARTBEAT ; if ( nextHeartbeat < System . currentTimeMillis ( ) ) { logger . debug ( "Send heartbeat" ) ; bitfinexApiBroker . sendCommand ( new PingCommand ( ) ) ; } }
|
Send a heartbeat package on the connection
|
2,946
|
private void executeReconnect ( ) throws InterruptedException { websocketEndpoint . close ( ) ; logger . info ( "Wait for next reconnect timeslot" ) ; eventsInTimeslotManager . recordNewEvent ( ) ; eventsInTimeslotManager . waitForNewTimeslot ( ) ; logger . info ( "Wait for next reconnect timeslot DONE" ) ; bitfinexApiBroker . reconnect ( ) ; }
|
Execute the reconnect
|
2,947
|
public void recordNewEvent ( ) { final double thresholdTime = System . currentTimeMillis ( ) - ( timeslotInMilliseconds * 2.0 ) ; events . removeIf ( e -> e < thresholdTime ) ; events . add ( System . currentTimeMillis ( ) ) ; }
|
Record a new event
|
2,948
|
public boolean waitForNewTimeslot ( ) throws InterruptedException { boolean hasWaited = false ; while ( true ) { final long numberOfEventsInTimeSlot = getNumberOfEventsInTimeslot ( ) ; if ( numberOfEventsInTimeSlot > numberOfEvents ) { hasWaited = true ; Thread . sleep ( timeslotInMilliseconds / 10 ) ; } else { return hasWaited ; } } }
|
Wait for a new timeslot
|
2,949
|
public long getNumberOfEventsInTimeslot ( ) { final double thresholdTime = System . currentTimeMillis ( ) - ( timeslotInMilliseconds ) ; return events . stream ( ) . filter ( e -> e >= thresholdTime ) . count ( ) ; }
|
Get the number of events in the timeslot
|
2,950
|
public static BitfinexCandlestickSymbol fromBitfinexString ( final String symbol ) { if ( ! symbol . startsWith ( "trade:" ) ) { throw new IllegalArgumentException ( "Unable to parse: " + symbol ) ; } final String [ ] splitString = symbol . split ( ":" ) ; if ( splitString . length != 3 ) { throw new IllegalArgumentException ( "Unable to parse: " + symbol ) ; } final String timeframeString = splitString [ 1 ] ; final String symbolString = splitString [ 2 ] ; return BitfinexSymbols . candlesticks ( BitfinexCurrencyPair . fromSymbolString ( symbolString ) , BitfinexCandleTimeFrame . fromSymbolString ( timeframeString ) ) ; }
|
Construct from Bitfinex string
|
2,951
|
public Closeable onConnectionStateChange ( final Consumer < BitfinexConnectionStateEnum > listener ) { connectionStateConsumers . offer ( listener ) ; return ( ) -> connectionStateConsumers . remove ( listener ) ; }
|
registers listener for notifications on connection state
|
2,952
|
public Closeable onSubscribeChannelEvent ( final Consumer < BitfinexStreamSymbol > listener ) { subscribeChannelConsumers . offer ( listener ) ; return ( ) -> subscribeChannelConsumers . remove ( listener ) ; }
|
registers listener for subscribe events
|
2,953
|
public Closeable onUnsubscribeChannelEvent ( final Consumer < BitfinexStreamSymbol > listener ) { unsubscribeChannelConsumers . offer ( listener ) ; return ( ) -> unsubscribeChannelConsumers . remove ( listener ) ; }
|
registers listener for unsubscribe events
|
2,954
|
public Closeable onMyOrderNotification ( final BiConsumer < BitfinexAccountSymbol , BitfinexSubmittedOrder > listener ) { newOrderConsumers . offer ( listener ) ; return ( ) -> newOrderConsumers . remove ( listener ) ; }
|
registers listener for my order notifications
|
2,955
|
public Closeable onMySubmittedOrderEvent ( final BiConsumer < BitfinexAccountSymbol , Collection < BitfinexSubmittedOrder > > listener ) { submittedOrderConsumers . offer ( listener ) ; return ( ) -> submittedOrderConsumers . remove ( listener ) ; }
|
registers listener for user account related events - submitted order events
|
2,956
|
public Closeable onMyPositionEvent ( final BiConsumer < BitfinexAccountSymbol , Collection < BitfinexPosition > > listener ) { positionConsumers . offer ( listener ) ; return ( ) -> positionConsumers . remove ( listener ) ; }
|
registers listener for user account related events - position events
|
2,957
|
public Closeable onMyWalletEvent ( final BiConsumer < BitfinexAccountSymbol , Collection < BitfinexWallet > > listener ) { walletConsumers . offer ( listener ) ; return ( ) -> walletConsumers . remove ( listener ) ; }
|
registers listener for user account related events - wallet change events
|
2,958
|
public Closeable onCandlesticksEvent ( final BiConsumer < BitfinexCandlestickSymbol , Collection < BitfinexCandle > > listener ) { candlesConsumers . offer ( listener ) ; return ( ) -> candlesConsumers . remove ( listener ) ; }
|
registers listener for candlesticks info updates
|
2,959
|
public Closeable onOrderbookEvent ( final BiConsumer < BitfinexOrderBookSymbol , Collection < BitfinexOrderBookEntry > > listener ) { orderbookEntryConsumers . offer ( listener ) ; return ( ) -> orderbookEntryConsumers . remove ( listener ) ; }
|
registers listener for orderbook events
|
2,960
|
public Closeable onRawOrderbookEvent ( final BiConsumer < BitfinexOrderBookSymbol , Collection < BitfinexOrderBookEntry > > listener ) { rawOrderbookEntryConsumers . offer ( listener ) ; return ( ) -> rawOrderbookEntryConsumers . remove ( listener ) ; }
|
registers listener for raw orderbook events
|
2,961
|
public Closeable onTickEvent ( final BiConsumer < BitfinexTickerSymbol , BitfinexTick > listener ) { tickConsumers . offer ( listener ) ; return ( ) -> tickConsumers . remove ( listener ) ; }
|
registers listener for tick events
|
2,962
|
public Closeable onAuthenticationSuccessEvent ( final Consumer < BitfinexAccountSymbol > listener ) { authSuccessConsumers . offer ( listener ) ; return ( ) -> authSuccessConsumers . remove ( listener ) ; }
|
registers listener for event of successful authentication with api - key
|
2,963
|
public Closeable onAuthenticationFailedEvent ( final Consumer < BitfinexAccountSymbol > listener ) { authFailedConsumers . offer ( listener ) ; return ( ) -> authFailedConsumers . remove ( listener ) ; }
|
registers listener for event of failed authentication with api - key
|
2,964
|
public static BitfinexWebsocketClient newPooledClient ( final BitfinexWebsocketConfiguration config , final int channelsPerConnection ) { if ( channelsPerConnection < 10 || channelsPerConnection > 250 ) { throw new IllegalArgumentException ( "channelsPerConnection must be in range (10, 250)" ) ; } final BitfinexApiCallbackRegistry callbacks = new BitfinexApiCallbackRegistry ( ) ; final SequenceNumberAuditor sequenceNumberAuditor = new SequenceNumberAuditor ( ) ; sequenceNumberAuditor . setErrorPolicy ( config . getErrorPolicy ( ) ) ; return new PooledBitfinexApiBroker ( config , callbacks , sequenceNumberAuditor , channelsPerConnection ) ; }
|
bitfinex client with subscribed channel managed . spreads amount of subscribed channels across multiple websocket physical connections .
|
2,965
|
public void setOrderFlags ( final int flags ) { orderFlags = Arrays . stream ( BitfinexOrderFlag . values ( ) ) . filter ( f -> ( ( f . getFlag ( ) & flags ) == f . getFlag ( ) ) ) . collect ( Collectors . toSet ( ) ) ; }
|
Convert a flag field into enums
|
2,966
|
public int getCombinedFlags ( ) { return orderFlags . stream ( ) . map ( BitfinexOrderFlag :: getFlag ) . reduce ( ( f1 , f2 ) -> f1 | f2 ) . orElse ( 0 ) ; }
|
Convert flag enums to flag field
|
2,967
|
public static BitfinexOrderBookSymbol rawOrderBook ( final BitfinexCurrencyPair currencyPair ) { return new BitfinexOrderBookSymbol ( currencyPair , BitfinexOrderBookSymbol . Precision . R0 , null , null ) ; }
|
returns symbol for raw order book channel
|
2,968
|
public static BitfinexOrderBookSymbol rawOrderBook ( final String currency , final String profitCurrency ) { final String currencyNonNull = Objects . requireNonNull ( currency ) . toUpperCase ( ) ; final String profitCurrencyNonNull = Objects . requireNonNull ( profitCurrency ) . toUpperCase ( ) ; return rawOrderBook ( BitfinexCurrencyPair . of ( currencyNonNull , profitCurrencyNonNull ) ) ; }
|
Returns symbol for raw order book channel
|
2,969
|
public static BitfinexOrderBookSymbol orderBook ( final BitfinexCurrencyPair currencyPair , final BitfinexOrderBookSymbol . Precision precision , final BitfinexOrderBookSymbol . Frequency frequency , final int pricePoints ) { if ( precision == BitfinexOrderBookSymbol . Precision . R0 ) { throw new IllegalArgumentException ( "Use BitfinexSymbols#rawOrderBook() factory method instead" ) ; } return new BitfinexOrderBookSymbol ( currencyPair , precision , frequency , pricePoints ) ; }
|
returns symbol for order book channel
|
2,970
|
public static BitfinexTickerSymbol ticker ( final String currency , final String profitCurrency ) { final String currencyNonNull = Objects . requireNonNull ( currency ) . toUpperCase ( ) ; final String profitCurrencyNonNull = Objects . requireNonNull ( profitCurrency ) . toUpperCase ( ) ; return ticker ( BitfinexCurrencyPair . of ( currencyNonNull , profitCurrencyNonNull ) ) ; }
|
returns symbol for ticker channel
|
2,971
|
public static BitfinexFundingSymbol funding ( final String bitfinexCurrency ) { final String currencyNonNull = Objects . requireNonNull ( bitfinexCurrency ) . toUpperCase ( ) ; final BitfinexFundingCurrency currency = new BitfinexFundingCurrency ( currencyNonNull ) ; return funding ( currency ) ; }
|
returns symbol for funding
|
2,972
|
private void setupCommandCallbacks ( ) { commandCallbacks = new HashMap < > ( ) ; commandCallbacks . put ( "info" , new DoNothingCommandCallback ( ) ) ; final ConnectionHeartbeatCallback pong = new ConnectionHeartbeatCallback ( ) ; pong . onHeartbeatEvent ( l -> this . updateConnectionHeartbeat ( ) ) ; commandCallbacks . put ( "pong" , pong ) ; final SubscribedCallback subscribed = new SubscribedCallback ( ) ; subscribed . onSubscribedEvent ( ( channelId , symbol ) -> { synchronized ( channelIdToHandlerMap ) { final ChannelCallbackHandler channelCallbackHandler = createChannelCallbackHandler ( channelId , symbol ) ; channelIdToHandlerMap . put ( channelId , channelCallbackHandler ) ; channelIdToHandlerMap . notifyAll ( ) ; } logger . debug ( "subscribed: {}" , symbol ) ; callbackRegistry . acceptSubscribeChannelEvent ( symbol ) ; } ) ; commandCallbacks . put ( "subscribed" , subscribed ) ; final UnsubscribedCallback unsubscribed = new UnsubscribedCallback ( ) ; unsubscribed . onUnsubscribedChannelEvent ( channelId -> { ChannelCallbackHandler removed ; synchronized ( channelIdToHandlerMap ) { removed = channelIdToHandlerMap . remove ( channelId ) ; channelIdToHandlerMap . notifyAll ( ) ; } if ( removed != null ) { callbackRegistry . acceptUnsubscribeChannelEvent ( removed . getSymbol ( ) ) ; logger . debug ( "unsubscribed: {}" , removed . getSymbol ( ) ) ; } } ) ; commandCallbacks . put ( "unsubscribed" , unsubscribed ) ; final AuthCallback auth = new AuthCallback ( ) ; auth . onAuthenticationSuccessEvent ( permissions -> { logger . info ( "authentication succeeded for key {}" , configuration . getApiKey ( ) ) ; final BitfinexAccountSymbol symbol = BitfinexSymbols . account ( permissions , configuration . getApiKey ( ) ) ; final AccountInfoHandler handler = new AccountInfoHandler ( ACCCOUNT_INFO_CHANNEL , symbol ) ; handler . onHeartbeatEvent ( timestamp -> this . updateConnectionHeartbeat ( ) ) ; handler . onPositionsEvent ( callbackRegistry :: acceptMyPositionEvent ) ; handler . onWalletsEvent ( callbackRegistry :: acceptMyWalletEvent ) ; handler . onSubmittedOrderEvent ( callbackRegistry :: acceptMySubmittedOrderEvent ) ; handler . onTradeEvent ( callbackRegistry :: acceptMyTradeEvent ) ; handler . onOrderNotification ( callbackRegistry :: acceptMyOrderNotification ) ; channelIdToHandlerMap . put ( 0 , handler ) ; callbackRegistry . acceptAuthenticationSuccessEvent ( symbol ) ; callbackRegistry . acceptConnectionStateChange ( BitfinexConnectionStateEnum . AUTHENTICATION_SUCCESS ) ; } ) ; auth . onAuthenticationFailedEvent ( permissions -> { logger . info ( "authentication failed for key {}" , configuration . getApiKey ( ) ) ; final BitfinexAccountSymbol symbol = BitfinexSymbols . account ( permissions , configuration . getApiKey ( ) ) ; callbackRegistry . acceptAuthenticationFailedEvent ( symbol ) ; callbackRegistry . acceptConnectionStateChange ( BitfinexConnectionStateEnum . AUTHENTICATION_FAILED ) ; } ) ; commandCallbacks . put ( "auth" , auth ) ; final ConfCallback conf = new ConfCallback ( ) ; conf . onConnectionFeatureEvent ( connectionFeatureManager :: setActiveConnectionFeatures ) ; commandCallbacks . put ( "conf" , conf ) ; commandCallbacks . put ( "error" , new ErrorCallback ( ) ) ; }
|
Setup the command callbacks
|
2,973
|
public void connect ( ) throws BitfinexClientException { logger . debug ( "connect() called" ) ; connectionStateChange ( BitfinexConnectionStateEnum . CONNECTION_INIT ) ; try { sequenceNumberAuditor . reset ( ) ; final CountDownLatch connectionReadyLatch = new CountDownLatch ( 4 ) ; final Closeable authSuccessEventCallback = callbackRegistry . onAuthenticationSuccessEvent ( c -> { permissions = c . getPermissions ( ) ; authenticated = true ; connectionReadyLatch . countDown ( ) ; } ) ; final Closeable authFailedCallback = callbackRegistry . onAuthenticationFailedEvent ( c -> { permissions = c . getPermissions ( ) ; authenticated = false ; while ( connectionReadyLatch . getCount ( ) != 0 ) { connectionReadyLatch . countDown ( ) ; } } ) ; final Closeable positionInitCallback = callbackRegistry . onMyPositionEvent ( ( a , p ) -> connectionReadyLatch . countDown ( ) ) ; final Closeable walletsInitCallback = callbackRegistry . onMyWalletEvent ( ( a , w ) -> connectionReadyLatch . countDown ( ) ) ; final Closeable orderInitCallback = callbackRegistry . onMySubmittedOrderEvent ( ( a , o ) -> connectionReadyLatch . countDown ( ) ) ; setupDefaultAccountInfoHandler ( ) ; websocketEndpoint = new WebsocketClientEndpoint ( new URI ( BITFINEX_URI ) , this :: websocketCallback , r -> callbackRegistry . acceptConnectionStateChange ( BitfinexConnectionStateEnum . DISCONNECTION_BY_REMOTE ) , t -> callbackRegistry . acceptConnectionStateChange ( BitfinexConnectionStateEnum . DISCONNECTION_BY_REMOTE ) ) ; websocketEndpoint . connect ( ) ; updateConnectionHeartbeat ( ) ; connectionFeatureManager . applyConnectionFeatures ( ) ; if ( configuration . isAuthenticationEnabled ( ) ) { authenticateAndWait ( connectionReadyLatch ) ; } authSuccessEventCallback . close ( ) ; authFailedCallback . close ( ) ; positionInitCallback . close ( ) ; walletsInitCallback . close ( ) ; orderInitCallback . close ( ) ; if ( configuration . isHeartbeatThreadActive ( ) ) { heartbeatThread = new Thread ( new HeartbeatThread ( this , websocketEndpoint , lastHeartbeat :: get ) ) ; heartbeatThread . start ( ) ; } connectionStateChange ( BitfinexConnectionStateEnum . CONNECTION_SUCCESS ) ; } catch ( final Exception e ) { connectionStateChange ( BitfinexConnectionStateEnum . CONNECTION_FAILED ) ; throw new BitfinexClientException ( e ) ; } }
|
Open the connection
|
2,974
|
private void setupDefaultAccountInfoHandler ( ) { final BitfinexAccountSymbol accountSymbol = BitfinexSymbols . account ( BitfinexApiKeyPermissions . NO_PERMISSIONS ) ; final AccountInfoHandler accountInfoHandler = new AccountInfoHandler ( ACCCOUNT_INFO_CHANNEL , accountSymbol ) ; accountInfoHandler . onHeartbeatEvent ( timestamp -> this . updateConnectionHeartbeat ( ) ) ; channelIdToHandlerMap . put ( ACCCOUNT_INFO_CHANNEL , accountInfoHandler ) ; }
|
Setup the default info handler - can be replaced in onAuthenticationSuccessEvent
|
2,975
|
public void close ( ) { try { callbackRegistry . acceptConnectionStateChange ( BitfinexConnectionStateEnum . DISCONNECTION_INIT ) ; logger . debug ( "close() called" ) ; if ( heartbeatThread != null ) { heartbeatThread . interrupt ( ) ; heartbeatThread = null ; } if ( websocketEndpoint != null ) { websocketEndpoint . close ( ) ; websocketEndpoint = null ; } connectionStateChange ( BitfinexConnectionStateEnum . DISCONNECTION_SUCCESS ) ; } catch ( final Exception e ) { connectionStateChange ( BitfinexConnectionStateEnum . DISCONNECTION_FAILED ) ; throw new BitfinexClientException ( e ) ; } }
|
Disconnect the websocket
|
2,976
|
public void sendCommand ( final BitfinexCommand command ) { try { if ( command instanceof BitfinexStreamSymbolToChannelIdResolverAware ) { final BitfinexStreamSymbolToChannelIdResolverAware aware = ( BitfinexStreamSymbolToChannelIdResolverAware ) command ; aware . setResolver ( symbol -> { final Integer channelId = getChannelForSymbol ( symbol ) ; if ( channelId == null ) { throw new IllegalArgumentException ( "Unknown symbol: " + symbol ) ; } return channelId ; } ) ; } final String json = command . getCommand ( this ) ; logger . debug ( "Sent: {}" , command ) ; websocketEndpoint . sendMessage ( json ) ; } catch ( final BitfinexCommandException e ) { logger . error ( "Got Exception while sending command" , e ) ; } }
|
Send a new API command
|
2,977
|
public synchronized boolean reconnect ( ) { logger . debug ( "reconnect() called" ) ; try { callbackRegistry . acceptConnectionStateChange ( BitfinexConnectionStateEnum . RECONNECTION_INIT ) ; websocketEndpoint . close ( ) ; permissions = BitfinexApiKeyPermissions . NO_PERMISSIONS ; authenticated = false ; sequenceNumberAuditor . reset ( ) ; connectionFeatureManager . setActiveConnectionFeatures ( 0 ) ; quoteManager . invalidateTickerHeartbeat ( ) ; orderManager . clear ( ) ; positionManager . clear ( ) ; final CountDownLatch connectionReadyLatch = new CountDownLatch ( 4 ) ; final Closeable authSuccessEventCallback = callbackRegistry . onAuthenticationSuccessEvent ( c -> { permissions = c . getPermissions ( ) ; authenticated = true ; connectionReadyLatch . countDown ( ) ; } ) ; final Closeable authFailedCallback = callbackRegistry . onAuthenticationFailedEvent ( c -> { permissions = c . getPermissions ( ) ; authenticated = false ; while ( connectionReadyLatch . getCount ( ) != 0 ) { connectionReadyLatch . countDown ( ) ; } } ) ; final Closeable positionInitCallback = callbackRegistry . onMyPositionEvent ( ( a , p ) -> connectionReadyLatch . countDown ( ) ) ; final Closeable walletsInitCallback = callbackRegistry . onMyWalletEvent ( ( a , w ) -> connectionReadyLatch . countDown ( ) ) ; final Closeable orderInitCallback = callbackRegistry . onMySubmittedOrderEvent ( ( a , o ) -> connectionReadyLatch . countDown ( ) ) ; setupDefaultAccountInfoHandler ( ) ; websocketEndpoint . connect ( ) ; connectionFeatureManager . applyConnectionFeatures ( ) ; if ( configuration . isAuthenticationEnabled ( ) ) { authenticateAndWait ( connectionReadyLatch ) ; } authSuccessEventCallback . close ( ) ; authFailedCallback . close ( ) ; positionInitCallback . close ( ) ; walletsInitCallback . close ( ) ; orderInitCallback . close ( ) ; resubscribeChannels ( ) ; updateConnectionHeartbeat ( ) ; callbackRegistry . acceptConnectionStateChange ( BitfinexConnectionStateEnum . RECONNECTION_SUCCESS ) ; return true ; } catch ( final Exception e ) { logger . error ( "Got exception while reconnect" , e ) ; websocketEndpoint . close ( ) ; callbackRegistry . acceptConnectionStateChange ( BitfinexConnectionStateEnum . RECONNECTION_FAILED ) ; return false ; } }
|
Perform a reconnect
|
2,978
|
private void authenticateAndWait ( final CountDownLatch latch ) throws InterruptedException , BitfinexClientException { if ( authenticated ) { return ; } sendCommand ( new AuthCommand ( configuration . getAuthNonceProducer ( ) ) ) ; logger . debug ( "Waiting for connection ready events" ) ; latch . await ( 10 , TimeUnit . SECONDS ) ; if ( ! authenticated ) { throw new BitfinexClientException ( "Unable to perform authentication, permissions are: " + permissions ) ; } }
|
Execute the authentication and wait until the socket is ready
|
2,979
|
private void websocketCallback ( final String message ) { logger . debug ( "Recv: {}" , message ) ; if ( message . startsWith ( "{" ) ) { handleCommandCallback ( message ) ; } else if ( message . startsWith ( "[" ) ) { handleChannelCallback ( message ) ; } else { logger . error ( "Got unknown callback: {}" , message ) ; } }
|
We received a websocket callback
|
2,980
|
private void handleCommandCallback ( final String message ) { final JSONObject jsonObject = new JSONObject ( message ) ; final String eventType = jsonObject . getString ( "event" ) ; final CommandCallbackHandler commandCallbackHandler = commandCallbacks . get ( eventType ) ; if ( commandCallbackHandler == null ) { logger . error ( "Unknown event: {}" , message ) ; return ; } try { commandCallbackHandler . handleChannelData ( jsonObject ) ; } catch ( final BitfinexClientException e ) { logger . error ( "Got an exception while handling callback" ) ; } }
|
Handle a command callback
|
2,981
|
private void handleChannelCallback ( final String message ) { updateConnectionHeartbeat ( ) ; final JSONArray jsonArray = new JSONArray ( new JSONTokener ( message ) ) ; if ( connectionFeatureManager . isConnectionFeatureActive ( BitfinexConnectionFeature . SEQ_ALL ) ) { sequenceNumberAuditor . auditPackage ( jsonArray ) ; } final int channel = jsonArray . getInt ( 0 ) ; final ChannelCallbackHandler channelCallbackHandler = channelIdToHandlerMap . get ( channel ) ; if ( channelCallbackHandler == null ) { logger . error ( "Unable to determine symbol for channel {} / data is {} " , channel , jsonArray ) ; reconnect ( ) ; return ; } String action = null ; final JSONArray payload ; if ( jsonArray . get ( 1 ) instanceof String ) { action = jsonArray . getString ( 1 ) ; payload = jsonArray . optJSONArray ( 2 ) ; } else { payload = jsonArray . optJSONArray ( 1 ) ; } if ( Objects . equals ( action , "hb" ) ) { quoteManager . updateChannelHeartbeat ( channelCallbackHandler . getSymbol ( ) ) ; } try { if ( payload == null ) { return ; } channelCallbackHandler . handleChannelData ( action , payload ) ; } catch ( final BitfinexClientException e ) { logger . error ( "Got exception while handling callback" , e ) ; } }
|
Handle a channel callback
|
2,982
|
private Integer getChannelForSymbol ( final BitfinexStreamSymbol symbol ) { synchronized ( channelIdToHandlerMap ) { return channelIdToHandlerMap . values ( ) . stream ( ) . filter ( v -> Objects . equals ( v . getSymbol ( ) , symbol ) ) . map ( ChannelCallbackHandler :: getChannelId ) . findFirst ( ) . orElse ( null ) ; } }
|
Find the channel for the given symbol
|
2,983
|
private void resubscribeChannels ( ) throws InterruptedException , BitfinexClientException { final Map < Integer , ChannelCallbackHandler > oldChannelIdSymbolMap = new HashMap < > ( ) ; synchronized ( channelIdToHandlerMap ) { oldChannelIdSymbolMap . putAll ( channelIdToHandlerMap ) ; channelIdToHandlerMap . clear ( ) ; channelIdToHandlerMap . notifyAll ( ) ; channelIdToHandlerMap . put ( ACCCOUNT_INFO_CHANNEL , oldChannelIdSymbolMap . get ( ACCCOUNT_INFO_CHANNEL ) ) ; } for ( final ChannelCallbackHandler handler : oldChannelIdSymbolMap . values ( ) ) { final BitfinexStreamSymbol symbol = handler . getSymbol ( ) ; if ( symbol instanceof BitfinexTickerSymbol ) { sendCommand ( new SubscribeTickerCommand ( ( BitfinexTickerSymbol ) symbol ) ) ; } else if ( symbol instanceof BitfinexExecutedTradeSymbol ) { sendCommand ( new SubscribeTradesCommand ( ( BitfinexExecutedTradeSymbol ) symbol ) ) ; } else if ( symbol instanceof BitfinexCandlestickSymbol ) { sendCommand ( new SubscribeCandlesCommand ( ( BitfinexCandlestickSymbol ) symbol ) ) ; } else if ( symbol instanceof BitfinexOrderBookSymbol ) { sendCommand ( new SubscribeOrderbookCommand ( ( BitfinexOrderBookSymbol ) symbol ) ) ; } else if ( symbol instanceof BitfinexAccountSymbol ) { } else { logger . error ( "Unknown stream symbol: {}" , symbol ) ; } } waitForChannelResubscription ( oldChannelIdSymbolMap ) ; }
|
Re - subscribe the old ticker
|
2,984
|
private void waitForChannelResubscription ( final Map < Integer , ChannelCallbackHandler > oldChannelIdSymbolMap ) throws BitfinexClientException , InterruptedException { final Stopwatch stopwatch = Stopwatch . createStarted ( ) ; final long MAX_WAIT_TIME_IN_MS = TimeUnit . MINUTES . toMillis ( 3 ) ; logger . info ( "Waiting for streams to resubscribe (max wait time {} msec)" , MAX_WAIT_TIME_IN_MS ) ; synchronized ( channelIdToHandlerMap ) { while ( channelIdToHandlerMap . size ( ) != oldChannelIdSymbolMap . size ( ) ) { if ( stopwatch . elapsed ( TimeUnit . MILLISECONDS ) > MAX_WAIT_TIME_IN_MS ) { handleResubscribeFailed ( oldChannelIdSymbolMap ) ; } channelIdToHandlerMap . wait ( 500 ) ; } } }
|
Wait for the successful channel re - subscription
|
2,985
|
private void handleResubscribeFailed ( final Map < Integer , ChannelCallbackHandler > oldChannelIdSymbolMap ) throws BitfinexClientException , InterruptedException { final int requiredSymbols = oldChannelIdSymbolMap . size ( ) ; final int subscribedSymbols = channelIdToHandlerMap . size ( ) ; unsubscribeAllChannels ( ) ; synchronized ( channelIdToHandlerMap ) { channelIdToHandlerMap . clear ( ) ; channelIdToHandlerMap . putAll ( oldChannelIdSymbolMap ) ; } throw new BitfinexClientException ( "Subscription of ticker failed: got only " + subscribedSymbols + " of " + requiredSymbols + " symbols subscribed" ) ; }
|
Handle channel re - subscribe failed
|
2,986
|
public void handleEvent ( final BitfinexStreamSymbol symbol ) { final List < FutureOperation > futuresToFinish = pendingFutures . stream ( ) . filter ( f -> f . getSymbol ( ) . equals ( symbol ) ) . collect ( Collectors . toList ( ) ) ; pendingFutures . removeAll ( futuresToFinish ) ; futuresToFinish . forEach ( f -> f . setToDone ( ) ) ; }
|
Handle a subscribe or unsubscribe event
|
2,987
|
public void registerTickCallback ( final BitfinexTickerSymbol symbol , final BiConsumer < BitfinexTickerSymbol , BitfinexTick > callback ) throws BitfinexClientException { tickerCallbacks . registerCallback ( symbol , callback ) ; }
|
Register a new tick callback
|
2,988
|
public boolean removeTickCallback ( final BitfinexTickerSymbol symbol , final BiConsumer < BitfinexTickerSymbol , BitfinexTick > callback ) throws BitfinexClientException { return tickerCallbacks . removeCallback ( symbol , callback ) ; }
|
Remove the a tick callback
|
2,989
|
public void handleCandleCollection ( final BitfinexTickerSymbol symbol , final List < BitfinexTick > candles ) { updateChannelHeartbeat ( symbol ) ; tickerCallbacks . handleEventsCollection ( symbol , candles ) ; }
|
Process a list with candles
|
2,990
|
public void handleNewTick ( final BitfinexTickerSymbol currencyPair , final BitfinexTick tick ) { updateChannelHeartbeat ( currencyPair ) ; tickerCallbacks . handleEvent ( currencyPair , tick ) ; }
|
Handle a new candle
|
2,991
|
public FutureOperation subscribeTicker ( final BitfinexTickerSymbol tickerSymbol ) throws BitfinexClientException { final FutureOperation future = new FutureOperation ( tickerSymbol ) ; pendingSubscribes . registerFuture ( future ) ; final SubscribeTickerCommand command = new SubscribeTickerCommand ( tickerSymbol ) ; client . sendCommand ( command ) ; return future ; }
|
Subscribe a ticker
|
2,992
|
public FutureOperation unsubscribeTicker ( final BitfinexTickerSymbol tickerSymbol ) { final FutureOperation future = new FutureOperation ( tickerSymbol ) ; pendingUnsubscribes . registerFuture ( future ) ; lastTickerActivity . remove ( tickerSymbol ) ; final UnsubscribeChannelCommand command = new UnsubscribeChannelCommand ( tickerSymbol ) ; client . sendCommand ( command ) ; return future ; }
|
Unsubscribe a ticker
|
2,993
|
public void registerCandlestickCallback ( final BitfinexCandlestickSymbol symbol , final BiConsumer < BitfinexCandlestickSymbol , BitfinexCandle > callback ) throws BitfinexClientException { candleCallbacks . registerCallback ( symbol , callback ) ; }
|
Register a new candlestick callback
|
2,994
|
public boolean removeCandlestickCallback ( final BitfinexCandlestickSymbol symbol , final BiConsumer < BitfinexCandlestickSymbol , BitfinexCandle > callback ) throws BitfinexClientException { return candleCallbacks . removeCallback ( symbol , callback ) ; }
|
Remove the a candlestick callback
|
2,995
|
public void handleCandlestickCollection ( final BitfinexCandlestickSymbol symbol , final Collection < BitfinexCandle > ticksBuffer ) { candleCallbacks . handleEventsCollection ( symbol , ticksBuffer ) ; }
|
Process a list with candlesticks
|
2,996
|
public void handleNewCandlestick ( final BitfinexCandlestickSymbol currencyPair , final BitfinexCandle tick ) { updateChannelHeartbeat ( currencyPair ) ; candleCallbacks . handleEvent ( currencyPair , tick ) ; }
|
Handle a new candlestick
|
2,997
|
public FutureOperation subscribeCandles ( final BitfinexCandlestickSymbol symbol ) throws BitfinexClientException { final FutureOperation future = new FutureOperation ( symbol ) ; pendingSubscribes . registerFuture ( future ) ; final SubscribeCandlesCommand command = new SubscribeCandlesCommand ( symbol ) ; client . sendCommand ( command ) ; return future ; }
|
Subscribe candles for a symbol
|
2,998
|
public FutureOperation unsubscribeCandles ( final BitfinexCandlestickSymbol symbol ) { lastTickerActivity . remove ( symbol ) ; final FutureOperation future = new FutureOperation ( symbol ) ; pendingUnsubscribes . registerFuture ( future ) ; final UnsubscribeChannelCommand command = new UnsubscribeChannelCommand ( symbol ) ; client . sendCommand ( command ) ; return future ; }
|
Unsubscribe the candles
|
2,999
|
public void registerExecutedTradeCallback ( final BitfinexExecutedTradeSymbol orderbookConfiguration , final BiConsumer < BitfinexExecutedTradeSymbol , BitfinexExecutedTrade > callback ) throws BitfinexClientException { tradesCallbacks . registerCallback ( orderbookConfiguration , callback ) ; }
|
Register a new executed trade callback
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.