idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
9,900
public static Class < ? > getType ( String className ) { ClassLoader classLoader = ReflectionHelper . getThreadContextClassLoader ( ) ; Class < ? > type = null ; try { type = classLoader . loadClass ( className ) ; } catch ( ClassNotFoundException exception ) { throw new FaxException ( "Unable to load class: " + classN...
This function returns the class based on the class name .
9,901
public static Object invokeMethod ( Class < ? > type , Object instance , String methodName , Class < ? > [ ] inputTypes , Object [ ] input ) { Method method = null ; try { method = type . getDeclaredMethod ( methodName , inputTypes ) ; } catch ( Exception exception ) { throw new FaxException ( "Unable to extract method...
This function invokes the requested method .
9,902
public static Field getField ( Class < ? > type , String fieldName ) { Field field = null ; try { field = type . getDeclaredField ( fieldName ) ; } catch ( Exception exception ) { throw new FaxException ( "Unable to extract field: " + fieldName + " from type: " + type , exception ) ; } field . setAccessible ( true ) ; ...
This function returns the field wrapper for the requested field
9,903
protected ProcessOutputValidator createProcessOutputValidator ( ) { String className = this . getConfigurationValue ( FaxClientSpiConfigurationConstants . PROCESS_OUTPUT_VALIDATOR_PRE_FORMAT_PROPERTY_KEY ) ; ProcessOutputValidator validator = null ; if ( className == null ) { className = ExitCodeProcessOutputValidator ...
This function creates and returns the process output validator .
9,904
protected ProcessOutputHandler createProcessOutputHandler ( ) { String className = this . getConfigurationValue ( FaxClientSpiConfigurationConstants . PROCESS_OUTPUT_HANDLER_PRE_FORMAT_PROPERTY_KEY ) ; ProcessOutputHandler handler = null ; if ( className != null ) { handler = ( ProcessOutputHandler ) ReflectionHelper ....
This function creates and returns the process output handler .
9,905
protected ProcessOutput executeProcess ( FaxJob faxJob , String command , FaxActionType faxActionType ) { if ( command == null ) { this . throwUnsupportedException ( ) ; } String updatedCommand = command ; if ( this . useWindowsCommandPrefix ) { StringBuilder buffer = new StringBuilder ( updatedCommand . length ( ) + t...
Executes the process and returns the output .
9,906
public String getFilePath ( ) { File fileInstance = this . getFile ( ) ; String filePath = null ; if ( fileInstance != null ) { filePath = fileInstance . getPath ( ) ; } return filePath ; }
This function returns the path to the file to fax .
9,907
public void setFilePath ( String filePath ) { File fileInstance = null ; if ( filePath != null ) { fileInstance = new File ( filePath ) ; } this . setFile ( fileInstance ) ; }
This function sets the path to the file to fax .
9,908
protected StringBuilder addToStringAttributes ( String faxJobType ) { StringBuilder buffer = new StringBuilder ( 500 ) ; buffer . append ( faxJobType ) ; buffer . append ( ":" ) ; buffer . append ( Logger . SYSTEM_EOL ) ; buffer . append ( "ID: " ) ; buffer . append ( this . getID ( ) ) ; buffer . append ( Logger . SYS...
This function adds the common attributes for the toString printing .
9,909
protected final CommPortConnectionFactory createCommPortConnectionFactory ( ) { CommPortConnectionFactory factory = ( CommPortConnectionFactory ) ReflectionHelper . createInstance ( this . commConnectionFactoryClassName ) ; factory . initialize ( this ) ; return factory ; }
Creates and returns the COMM port connection factory .
9,910
protected final FaxModemAdapter createFaxModemAdapter ( ) { FaxModemAdapter adapter = ( FaxModemAdapter ) ReflectionHelper . createInstance ( this . faxModemClassName ) ; adapter . initialize ( this ) ; return adapter ; }
Creates and returns the fax modem adapter .
9,911
protected void releaseCommPortConnection ( ) { Connection < CommPortAdapter > connection = this . commConnection ; this . commConnection = null ; if ( connection != null ) { Logger logger = this . getLogger ( ) ; try { logger . logInfo ( new Object [ ] { "Closing COMM port connection." } , null ) ; connection . close (...
Releases the COMM port connection if open .
9,912
protected Connection < CommPortAdapter > getCommPortConnection ( ) { Connection < CommPortAdapter > connection = null ; synchronized ( this ) { boolean connectionValid = true ; if ( this . commConnection == null ) { connectionValid = false ; } else { CommPortAdapter adapter = this . commConnection . getResource ( ) ; i...
Returns the COMM port connection to be used .
9,913
public void stop ( ) { logger . info ( "Stop..." ) ; lifecycleLock . writeLock ( ) . lock ( ) ; try { if ( ! State . STARTED . equals ( state ) ) { logger . debug ( "Ignore stop() command for " + state + " instance" ) ; return ; } logger . info ( "Unregister shutdown hook" ) ; this . shutdownHook . unregisterFromRuntim...
Stop scheduled executors and collect - and - export metrics one last time .
9,914
private SortedMap < String , List < QueryResult > > splitQueryResultsByTime ( Iterable < QueryResult > results ) { SortedMap < String , List < QueryResult > > resultsByTime = new TreeMap < String , List < QueryResult > > ( ) ; for ( QueryResult result : results ) { String epoch = String . valueOf ( result . getEpoch ( ...
Often query results for a given query come in batches so we need to split them up by time
9,915
List < Object > alignResults ( List < QueryResult > results , String epoch ) { Object [ ] alignedResults = new Object [ results . size ( ) + 1 ] ; List < String > headerList = Arrays . asList ( header ) ; alignedResults [ 0 ] = epoch ; for ( QueryResult result : results ) { alignedResults [ headerList . indexOf ( resul...
We have no guarantee that the results will always be in the same order so we make sure to align them according to the header on each query .
9,916
private void appendEscapedNonAlphaNumericChars ( String str , boolean escapeDot , StringBuilder result ) { char [ ] chars = str . toCharArray ( ) ; for ( int i = 0 ; i < chars . length ; i ++ ) { char ch = chars [ i ] ; if ( Character . isLetter ( ch ) || Character . isDigit ( ch ) || ch == '-' ) { result . append ( ch...
Escape all non a - z A - Z 0 - 9 and - with a _ .
9,917
private long computeConfigurationLastModified ( List < Resource > configurations ) { long result = 0 ; for ( Resource configuration : configurations ) { try { long currentConfigurationLastModified = configuration . lastModified ( ) ; if ( currentConfigurationLastModified > result ) { result = currentConfigurationLastMo...
Computes the last modified date of all configuration files .
9,918
private List < Resource > getConfigurations ( ) { List < Resource > result = new ArrayList < Resource > ( ) ; for ( String delimitedConfigurationUrl : configurationUrls ) { String [ ] tokens = StringUtils . commaDelimitedListToStringArray ( delimitedConfigurationUrl ) ; tokens = StringUtils . trimArrayElements ( tokens...
Returns the list of all configuration spring resources .
9,919
private void sendGenericNack ( Pdu packet ) { GenericNack genericNack = new GenericNack ( ) ; genericNack . setSequenceNumber ( packet . getSequenceNumber ( ) ) ; genericNack . setCommandStatus ( SmppConstants . STATUS_INVCMDID ) ; ChannelBuffer buffer = null ; try { buffer = transcoder . encode ( genericNack ) ; } cat...
Send generic_nack to client if unable to convert request from client
9,920
public KeyValue getKeyValue ( String KeyURI ) throws EmbeddedJmxTransException { String etcdURI = KeyURI . substring ( 0 , KeyURI . indexOf ( "/" , 7 ) ) ; String key = KeyURI . substring ( KeyURI . indexOf ( "/" , 7 ) ) ; try { return getFromEtcd ( makeEtcdBaseUris ( etcdURI ) , key ) ; } catch ( Throwable t ) { throw...
Get a key value from etcd . Returns the key value and the etcd modification index as version
9,921
public static void closeClient ( TServiceClient client ) { if ( client == null ) { return ; } try { TProtocol proto = client . getInputProtocol ( ) ; if ( proto != null ) { proto . getTransport ( ) . close ( ) ; } } catch ( Throwable e ) { logger . warn ( "close input transport fail" , e ) ; } try { TProtocol proto = c...
close internal transport
9,922
public void start ( ) { try { url = new URL ( getStringSetting ( SETTING_URL , DEFAULT_STACKDRIVER_API_URL ) ) ; } catch ( MalformedURLException e ) { throw new EmbeddedJmxTransException ( e ) ; } apiKey = getStringSetting ( SETTING_TOKEN ) ; if ( getStringSetting ( SETTING_PROXY_HOST , null ) != null && ! getStringSet...
Initial setup for the writer class . Loads in settings and initializes one - time setup variables like instanceId .
9,923
public void write ( Iterable < QueryResult > results ) { logger . debug ( "Export to '{}', proxy {} metrics {}" , url , proxy , results ) ; HttpURLConnection urlConnection = null ; try { if ( proxy == null ) { urlConnection = ( HttpURLConnection ) url . openConnection ( ) ; } else { urlConnection = ( HttpURLConnection ...
Send given metrics to the Stackdriver server using HTTP
9,924
private String getLocalAwsInstanceId ( ) { String detectedInstanceId = null ; try { final URL metadataUrl = new URL ( "http://169.254.169.254/latest/meta-data/instance-id" ) ; URLConnection metadataConnection = metadataUrl . openConnection ( ) ; BufferedReader in = new BufferedReader ( new InputStreamReader ( metadataC...
Use the EC2 Metadata URL to determine the instance ID that this code is running on . Useful if you don t want to configure the instance ID manually . Pass detectInstance = AWS to have this run in your configuration .
9,925
public void start ( ) { try { this . regularBootstrap . bind ( new InetSocketAddress ( regularConfiguration . getHost ( ) , regularConfiguration . getPort ( ) ) ) ; if ( logger . isInfoEnabled ( ) ) { logger . info ( regularConfiguration . getName ( ) + " started at " + regularConfiguration . getHost ( ) + " : " + regu...
Start load balancer server
9,926
public void stop ( ) { if ( this . channels . size ( ) > 0 ) { logger . info ( regularConfiguration . getName ( ) + " currently has [" + this . channels . size ( ) + "] open child channel(s) that will be closed as part of stop()" ) ; } this . channelFactory . shutdown ( ) ; this . channels . close ( ) . awaitUninterrup...
Stop load balancer server
9,927
protected String getStringSetting ( String name , String defaultValue ) { if ( settings . containsKey ( name ) ) { return settings . get ( name ) . toString ( ) ; } else { return defaultValue ; } }
Return the value of the given property .
9,928
public void setServices ( List < ServiceInfo > services ) { if ( services == null || services . size ( ) == 0 ) { throw new IllegalArgumentException ( "services is empty!" ) ; } this . services = services ; serviceReset = true ; }
set new services for this pool
9,929
private ServiceInfo getRandomService ( List < ServiceInfo > serviceList ) { if ( serviceList == null || serviceList . size ( ) == 0 ) { return null ; } return serviceList . get ( RandomUtils . nextInt ( 0 , serviceList . size ( ) ) ) ; }
get a random service
9,930
public ThriftClient < T > getClient ( ) throws ThriftException { try { return pool . borrowObject ( ) ; } catch ( Exception e ) { if ( e instanceof ThriftException ) { throw ( ThriftException ) e ; } throw new ThriftException ( "Get client from pool failed." , e ) ; } }
get a client from pool
9,931
private Node checkRouteHeaderForSipNode ( SipURI routeSipUri ) { Node node = null ; String hostNode = routeSipUri . getParameter ( ROUTE_PARAM_NODE_HOST ) ; String hostPort = routeSipUri . getParameter ( ROUTE_PARAM_NODE_PORT ) ; String hostVersion = routeSipUri . getParameter ( ROUTE_PARAM_NODE_VERSION ) ; if ( hostNo...
This will check if in the route header there is information on which node from the cluster send the request . If the request is not received from the cluster this information will not be present .
9,932
protected Boolean comesFromInternalNode ( Response externalResponse , InvocationContext ctx , String host , Integer port , String transport , Boolean isIpV6 ) { boolean found = false ; if ( host != null && port != null ) { if ( ctx . sipNodeMap ( isIpV6 ) . containsKey ( new KeySip ( host , port , isIpV6 ) ) ) found = ...
need to verify that comes from external in case of single leg
9,933
public void initialise ( ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "now initialising conf" ) ; } initDecodeUsing ( decodeUsing ) ; boolean rulesOk = true ; for ( int i = 0 ; i < rules . size ( ) ; i ++ ) { final Rule rule = ( Rule ) rules . get ( i ) ; if ( ! rule . initialise ( context ) ) { rulesOk = false ...
Initialise the conf file . This will run initialise on each rule and condition in the conf file .
9,934
public void destroy ( ) { for ( int i = 0 ; i < rules . size ( ) ; i ++ ) { final Rule rule = ( Rule ) rules . get ( i ) ; rule . destroy ( ) ; } }
Destory the conf gracefully .
9,935
private void ensure_dashboards ( ) { HttpURLConnection urlConnection = null ; OutputStreamWriter wr = null ; URL myurl = null ; try { myurl = new URL ( url_str + "/dashboards.json" ) ; urlConnection = ( HttpURLConnection ) myurl . openConnection ( ) ; urlConnection . setRequestMethod ( "GET" ) ; urlConnection . setDoIn...
If dashboard doesn t exist create it If it does exist update it .
9,936
public static double [ ] normalizeL2 ( double [ ] vector ) { double norm2 = 0 ; for ( int i = 0 ; i < vector . length ; i ++ ) { norm2 += vector [ i ] * vector [ i ] ; } norm2 = ( double ) Math . sqrt ( norm2 ) ; if ( norm2 == 0 ) { Arrays . fill ( vector , 1 ) ; } else { for ( int i = 0 ; i < vector . length ; i ++ ) ...
This method applies L2 normalization on a given array of doubles . The passed vector is modified by the method .
9,937
public static double [ ] normalizeL1 ( double [ ] vector ) { double norm1 = 0 ; for ( int i = 0 ; i < vector . length ; i ++ ) { norm1 += Math . abs ( vector [ i ] ) ; } if ( norm1 == 0 ) { Arrays . fill ( vector , 1.0 / vector . length ) ; } else { for ( int i = 0 ; i < vector . length ; i ++ ) { vector [ i ] = vector...
This method applies L1 normalization on a given array of doubles . The passed vector is modified by the method .
9,938
public static double [ ] normalizePower ( double [ ] vector , double aParameter ) { for ( int i = 0 ; i < vector . length ; i ++ ) { vector [ i ] = Math . signum ( vector [ i ] ) * Math . pow ( Math . abs ( vector [ i ] ) , aParameter ) ; } return vector ; }
This method applies power normalization on a given array of doubles . The passed vector is modified by the method .
9,939
protected double [ ] aggregateInternal ( ArrayList < double [ ] > descriptors ) { double [ ] vlad = new double [ numCentroids * descriptorLength ] ; if ( descriptors . size ( ) == 0 ) { return vlad ; } for ( double [ ] descriptor : descriptors ) { int nnIndex = computeNearestCentroid ( descriptor ) ; for ( int i = 0 ; ...
Takes as input an ArrayList of double arrays which contains the set of local descriptors for an image . Returns the VLAD vector representation of the image using the codebook supplied in the constructor .
9,940
public CSLDate parse ( String str ) { Map < String , Object > res ; try { Map < String , Object > m = runner . callMethod ( parser , "parseDateToArray" , Map . class , str ) ; res = m ; } catch ( ScriptRunnerException e ) { throw new IllegalArgumentException ( "Could not update items" , e ) ; } CSLDate r = CSLDate . fr...
Parses a string to a date
9,941
public static void main ( String [ ] args ) throws Exception { String indexLocation = args [ 0 ] ; int numTrainVectors = Integer . parseInt ( args [ 1 ] ) ; int vectorLength = Integer . parseInt ( args [ 2 ] ) ; int numPrincipalComponents = Integer . parseInt ( args [ 3 ] ) ; boolean whitening = true ; boolean compact ...
This method can be used to learn a PCA projection matrix .
9,942
private static CSLName [ ] toAuthors ( List < Map < String , Object > > authors ) { CSLName [ ] result = new CSLName [ authors . size ( ) ] ; int i = 0 ; for ( Map < String , Object > a : authors ) { CSLNameBuilder builder = new CSLNameBuilder ( ) ; if ( a . containsKey ( FIELD_FIRSTNAME ) ) { builder . given ( strOrNu...
Converts a list of authors
9,943
private static CSLType toType ( String type ) { if ( type . equalsIgnoreCase ( TYPE_BILL ) ) { return CSLType . BILL ; } else if ( type . equalsIgnoreCase ( TYPE_BOOK ) ) { return CSLType . BOOK ; } else if ( type . equalsIgnoreCase ( TYPE_BOOK_SECTION ) ) { return CSLType . CHAPTER ; } else if ( type . equalsIgnoreCas...
Converts a Mendeley type to a CSL type
9,944
public final Operation getOperation ( String name ) { GetOperationRequest request = GetOperationRequest . newBuilder ( ) . setName ( name ) . build ( ) ; return getOperation ( request ) ; }
Gets the latest state of a long - running operation . Clients can use this method to poll the operation result at intervals as recommended by the API service .
9,945
public final ListOperationsPagedResponse listOperations ( String name , String filter ) { ListOperationsRequest request = ListOperationsRequest . newBuilder ( ) . setName ( name ) . setFilter ( filter ) . build ( ) ; return listOperations ( request ) ; }
Lists operations that match the specified filter in the request . If the server doesn t support this method it returns UNIMPLEMENTED .
9,946
public final void deleteOperation ( String name ) { DeleteOperationRequest request = DeleteOperationRequest . newBuilder ( ) . setName ( name ) . build ( ) ; deleteOperation ( request ) ; }
Deletes a long - running operation . This method indicates that the client is no longer interested in the operation result . It does not cancel the operation . If the server doesn t support this method it returns google . rpc . Code . UNIMPLEMENTED .
9,947
@ CommandDescList ( { @ CommandDesc ( longName = "load" , description = "load an input bibliography from a file" , command = ShellLoadCommand . class ) , @ CommandDesc ( longName = "get" , description = "get values of shell variables" , command = ShellGetCommand . class ) , @ CommandDesc ( longName = "set" , descriptio...
Configures all additional shell commands
9,948
private void vibrateIfEnabled ( ) { final boolean enabled = styledAttributes . getBoolean ( R . styleable . PinLock_vibrateOnClick , false ) ; if ( enabled ) { Vibrator v = ( Vibrator ) context . getSystemService ( Context . VIBRATOR_SERVICE ) ; final int duration = styledAttributes . getInt ( R . styleable . PinLock_v...
Vibrate device on each key press if the feature is enabled
9,949
private void setStyle ( Button view ) { final int textSize = styledAttributes . getInt ( R . styleable . PinLock_keypadTextSize , 12 ) ; view . setTextSize ( TypedValue . COMPLEX_UNIT_SP , textSize ) ; final int color = styledAttributes . getColor ( R . styleable . PinLock_keypadTextColor , Color . BLACK ) ; view . set...
Setting Button background styles such as background size and shape
9,950
private void setValues ( int position , Button view ) { if ( position == 10 ) { view . setText ( "0" ) ; } else if ( position == 9 ) { view . setVisibility ( View . INVISIBLE ) ; } else { view . setText ( String . valueOf ( ( position + 1 ) % 10 ) ) ; } }
Setting Button text
9,951
public static void writeBinary ( String featuresFileName , double [ ] [ ] features ) throws Exception { DataOutputStream out = new DataOutputStream ( new BufferedOutputStream ( new FileOutputStream ( featuresFileName ) ) ) ; for ( int i = 0 ; i < features . length ; i ++ ) { for ( int j = 0 ; j < features [ i ] . lengt...
Takes a two - dimensional double array with features and writes them in a binary file .
9,952
public static void writeText ( String featuresFileName , double [ ] [ ] features ) throws Exception { BufferedWriter out = new BufferedWriter ( new FileWriter ( featuresFileName ) ) ; for ( double [ ] feature : features ) { for ( int j = 0 ; j < feature . length - 1 ; j ++ ) { out . write ( feature [ j ] + "," ) ; } ou...
Takes a two - dimensional double array with features and writes them in a comma separated text file .
9,953
public static void textToBinary ( String featuresFolder , final String featureType , int featureLength ) throws Exception { File dir = new File ( featuresFolder ) ; FilenameFilter filter = new FilenameFilter ( ) { public boolean accept ( File dir , String name ) { if ( name . endsWith ( "." + featureType ) ) return tru...
Takes a folder with feature files in text format and converts them to binary .
9,954
public static void binaryToText ( String featuresFolder , final String featureType , int featureLength ) throws Exception { File dir = new File ( featuresFolder ) ; FilenameFilter filter = new FilenameFilter ( ) { public boolean accept ( File dir , String name ) { if ( name . endsWith ( "." + featureType + "b" ) ) retu...
Takes a folder with feature files in binary format and converts them to text .
9,955
private void setupButtons ( ) { cancelButton = ( TextView ) findViewById ( R . id . cancelButton ) ; cancelButton . setOnClickListener ( new View . OnClickListener ( ) { public void onClick ( View v ) { setResult ( CANCELLED ) ; finish ( ) ; } } ) ; forgetButton = ( TextView ) findViewById ( R . id . forgotPin ) ; forg...
Setting up cancel and forgot buttons and adding onClickListeners to them
9,956
@ OptionDesc ( longName = "output" , shortName = "o" , description = "write output to FILE instead of stdout" , argumentName = "FILE" , argumentType = ArgumentType . STRING ) public void setOutputFile ( String outputFile ) { this . outputFile = outputFile ; }
Sets the name of the output file
9,957
@ CommandDescList ( { @ CommandDesc ( longName = "bibliography" , description = "generate a bibliography" , command = BibliographyCommand . class ) , @ CommandDesc ( longName = "citation" , description = "generate citations" , command = CitationCommand . class ) , @ CommandDesc ( longName = "list" , description = "disp...
Sets the command to execute
9,958
private boolean enableRed ( ) throws IOException { boolean oldwriting = writing ; if ( ! writing ) { writing = true ; byte [ ] en = "\u001B[31m" . getBytes ( ) ; super . write ( en , 0 , en . length ) ; } return oldwriting ; }
Enables colored output
9,959
private void disableRed ( ) throws IOException { byte [ ] dis = "\u001B[0m" . getBytes ( ) ; super . write ( dis , 0 , dis . length ) ; writing = false ; }
Disabled colored output
9,960
public ItemDataProvider readBibliographyFile ( File bibfile ) throws FileNotFoundException , IOException { if ( ! bibfile . exists ( ) ) { throw new FileNotFoundException ( "Bibliography file `" + bibfile . getName ( ) + "' does not exist" ) ; } try ( BufferedInputStream bis = new BufferedInputStream ( new FileInputStr...
Reads all items from an input bibliography file and returns a provider serving these items
9,961
public FileFormat determineFileFormat ( File bibfile ) throws FileNotFoundException , IOException { if ( ! bibfile . exists ( ) ) { throw new FileNotFoundException ( "Bibliography file `" + bibfile . getName ( ) + "' does not exist" ) ; } try ( BufferedInputStream bis = new BufferedInputStream ( new FileInputStream ( b...
Reads the first 100 KB of the given bibliography file and tries to determine the file format
9,962
private Token requestCredentials ( URL url , Method method , Token token , Map < String , String > additionalAuthParams ) throws IOException { Response r = requestInternal ( url , method , token , additionalAuthParams , null ) ; InputStream is = r . getInputStream ( ) ; String response = CSLUtils . readStreamToString (...
Sends a request to the server and returns a token
9,963
protected Token responseToToken ( Map < String , String > response ) { return new Token ( response . get ( OAUTH_TOKEN ) , response . get ( OAUTH_TOKEN_SECRET ) ) ; }
Parses a service response and creates a token
9,964
private Response requestInternal ( URL url , Method method , Token token , Map < String , String > additionalAuthParams , Map < String , String > additionalHeaders ) throws IOException { HttpURLConnection conn = ( HttpURLConnection ) url . openConnection ( ) ; conn . setInstanceFollowRedirects ( true ) ; conn . setRequ...
Sends a request to the server and returns an input stream from which the response can be read . The caller is responsible for consuming the input stream s content and for closing the stream .
9,965
private static void appendAuthParam ( StringBuilder sb , String key , String value ) { if ( sb . length ( ) > 0 ) { sb . append ( "," ) ; } sb . append ( key ) ; sb . append ( "=\"" ) ; sb . append ( value ) ; sb . append ( "\"" ) ; }
Appends an authorization parameter to the given string builder
9,966
private String makeNonce ( String timestamp ) { byte [ ] bytes = new byte [ 10 ] ; random . nextBytes ( bytes ) ; StringBuilder sb = new StringBuilder ( timestamp ) ; sb . append ( "-" ) ; for ( int i = 0 ; i < bytes . length ; ++ i ) { String b = Integer . toHexString ( bytes [ i ] & 0xff ) ; if ( b . length ( ) < 2 )...
Generates a nonce for a request using a secure random number generator
9,967
private static String makeBaseUri ( URL url ) { String r = url . getProtocol ( ) . toLowerCase ( ) + "://" + url . getHost ( ) . toLowerCase ( ) ; if ( ( url . getProtocol ( ) . equalsIgnoreCase ( "http" ) && url . getPort ( ) != - 1 && url . getPort ( ) != 80 ) || ( url . getProtocol ( ) . equalsIgnoreCase ( "https" )...
Generates a base URI from a given URL . The base URI consists of the protocol the host and also the port if its not the default port for the given protocol .
9,968
private static List < String > splitAndEncodeParams ( URL url ) { if ( url . getQuery ( ) == null ) { return new ArrayList < > ( ) ; } String [ ] params = url . getQuery ( ) . split ( "&" ) ; List < String > result = new ArrayList < > ( params . length ) ; for ( String p : params ) { String [ ] kv = p . split ( "=" ) ;...
Splits the query parameters of the given URL encodes their keys and values and puts each key - value pair in a list
9,969
private String makeSignature ( String method , URL url , Map < String , String > authParams , Token token ) { StringBuilder sb = new StringBuilder ( method + "&" + PercentEncoding . encode ( makeBaseUri ( url ) + url . getPath ( ) ) ) ; List < String > params = splitAndEncodeParams ( url ) ; for ( Map . Entry < String ...
Generates a OAuth signature from the HTTP method the URL and the authorization parameters
9,970
private String mainLoop ( ConsoleReader reader , PrintWriter cout ) throws IOException { InputReader lr = new ConsoleInputReader ( reader ) ; String line ; while ( ( line = reader . readLine ( ) ) != null ) { if ( line . isEmpty ( ) ) { continue ; } String [ ] args = ShellCommandParser . split ( line ) ; Result pr ; tr...
Runs the shell s main loop
9,971
private String [ ] augmentCommand ( String [ ] args , Class < ? extends Command > cmd , boolean acceptsInputFile ) { OptionGroup < ID > options ; try { if ( acceptsInputFile ) { options = OptionIntrospector . introspect ( cmd , InputFileCommand . class ) ; } else { options = OptionIntrospector . introspect ( cmd ) ; } ...
Augments the given command line with context variables
9,972
private void addDots ( int length ) { removeAllViews ( ) ; final int pinLength = styledAttributes . getInt ( R . styleable . PinLock_pinLength , 4 ) ; for ( int i = 0 ; i < pinLength ; i ++ ) { Dot dot = new Dot ( context , styledAttributes , i < length ) ; addView ( dot ) ; } }
Adding Dot objects to layout
9,973
private void setBackground ( boolean filled ) { if ( filled ) { final int background = styledAttributes . getResourceId ( R . styleable . PinLock_statusFilledBackground , R . drawable . dot_filled ) ; setBackgroundResource ( background ) ; } else { final int background = styledAttributes . getResourceId ( R . styleable...
Setting up background for the view . Should pass shapes for both filled and empty dots . Otherwise will use the default backgrounds
9,974
public Type readNextToken ( ) throws IOException { int c ; if ( currentCharacter >= 0 && ! Character . isWhitespace ( currentCharacter ) ) { c = currentCharacter ; currentCharacter = - 1 ; } else { c = skipWhitespace ( ) ; } if ( c < 0 ) { return null ; } if ( c == '{' ) { currentTokenType = Type . START_OBJECT ; } els...
Reads the next token from the stream
9,975
private int skipWhitespace ( ) throws IOException { int c = 0 ; do { c = r . read ( ) ; if ( c < 0 ) { return - 1 ; } } while ( Character . isWhitespace ( c ) ) ; return c ; }
Reads characters from the stream until a non - whitespace character has been found . Reads at least one character .
9,976
public String readString ( ) throws IOException { StringBuilder result = new StringBuilder ( ) ; while ( true ) { int c = r . read ( ) ; if ( c < 0 ) { throw new IllegalStateException ( "Premature end of stream" ) ; } else if ( c == '"' ) { break ; } else if ( c == '\\' ) { int c2 = r . read ( ) ; if ( c2 == '"' || c2 ...
Reads a string from the stream
9,977
private static void checkHexDigit ( int c ) { if ( ! Character . isDigit ( c ) && ! ( c >= 'a' && c <= 'f' ) && ! ( c >= 'A' && c <= 'F' ) ) { throw new IllegalStateException ( "Not a hexadecimal digit: " + c ) ; } }
Checks if the given character is a hexadecimal character
9,978
public Number readNumber ( ) throws IOException { if ( currentCharacter < 0 ) { throw new IllegalStateException ( "Missed first digit" ) ; } boolean negative = false ; if ( currentCharacter == '-' ) { negative = true ; currentCharacter = r . read ( ) ; } long result = 0 ; while ( currentCharacter >= 0 ) { if ( currentC...
Reads a number from the stream
9,979
private Number readReal ( long prev , boolean negative ) throws IOException { StringBuilder b = new StringBuilder ( prev + "." ) ; boolean exponent = false ; boolean expsign = false ; do { currentCharacter = r . read ( ) ; if ( currentCharacter >= '0' && currentCharacter <= '9' ) { b . append ( ( char ) currentCharacte...
Reads a real number from the stream
9,980
public static String decode ( String str ) { try { return URLDecoder . decode ( str , "UTF-8" ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } }
Decodes a string
9,981
private boolean authorize ( RemoteConnector mc , InputReader in ) { String authUrl ; try { authUrl = mc . getAuthorizationURL ( ) ; } catch ( IOException e ) { error ( "could not get authorization URL from remote server." ) ; return false ; } System . out . println ( "This tool requires authorization. Please point your...
Request authorization for the tool from remote server
9,982
public double [ ] permute ( double [ ] vector ) { double [ ] permuted = new double [ vector . length ] ; for ( int i = 0 ; i < vector . length ; i ++ ) { permuted [ i ] = vector [ randomlyPermutatedIndices [ i ] ] ; } return permuted ; }
Randomly permutes a vector using the random permutation of the indices that was created in the constructor .
9,983
private boolean checkStyle ( String style ) throws IOException { if ( CSL . supportsStyle ( style ) ) { return true ; } String message = "Could not find style in classpath: " + style ; Set < String > availableStyles = CSL . getSupportedStyles ( ) ; if ( ! availableStyles . isEmpty ( ) ) { String dyms = ToolUtils . getD...
Checks if the given style exists and output possible alternatives if it does not
9,984
public void loadProductQuantizer ( String filename ) throws Exception { productQuantizer = new double [ numSubVectors ] [ numProductCentroids ] [ subVectorLength ] ; BufferedReader in = new BufferedReader ( new FileReader ( new File ( filename ) ) ) ; for ( int i = 0 ; i < numSubVectors ; i ++ ) { for ( int j = 0 ; j <...
Load the product quantizer from the given file .
9,985
public void loadCoarseQuantizer ( String filename ) throws IOException { coarseQuantizer = new double [ numCoarseCentroids ] [ vectorLength ] ; coarseQuantizer = AbstractFeatureAggregator . readQuantizer ( filename , numCoarseCentroids , vectorLength ) ; }
Load the coarse quantizer from the given file .
9,986
private BoundedPriorityQueue < Result > computeKnnIVFADC ( int k , double [ ] qVector ) throws Exception { BoundedPriorityQueue < Result > nn = new BoundedPriorityQueue < Result > ( new Result ( ) , k ) ; int [ ] nearestCoarseCentroidIndices = computeNearestCoarseIndices ( qVector , w ) ; for ( int i = 0 ; i < w ; i ++...
Computes and returns the k nearest neighbors of the query vector using the IVFADC approach .
9,987
private int computeNearestCoarseIndex ( double [ ] vector ) { int centroidIndex = - 1 ; double minDistance = Double . MAX_VALUE ; for ( int i = 0 ; i < numCoarseCentroids ; i ++ ) { double distance = 0 ; for ( int j = 0 ; j < vectorLength ; j ++ ) { distance += ( coarseQuantizer [ i ] [ j ] - vector [ j ] ) * ( coarseQ...
Returns the index of the coarse centroid which is closer to the given vector .
9,988
protected int [ ] computeNearestCoarseIndices ( double [ ] vector , int k ) { BoundedPriorityQueue < Result > bpq = new BoundedPriorityQueue < Result > ( new Result ( ) , k ) ; double lowest = Double . MAX_VALUE ; for ( int i = 0 ; i < numCoarseCentroids ; i ++ ) { boolean skip = false ; double l2distance = 0 ; for ( i...
Returns the indices of the k coarse centroids which are closer to the given vector .
9,989
private int computeNearestProductIndex ( double [ ] subvector , int subQuantizerIndex ) { int centroidIndex = - 1 ; double minDistance = Double . MAX_VALUE ; for ( int i = 0 ; i < numProductCentroids ; i ++ ) { double distance = 0 ; for ( int j = 0 ; j < subVectorLength ; j ++ ) { distance += ( productQuantizer [ subQu...
Finds and returns the index of the centroid of the subquantizer with the given index which is closer to the given subvector .
9,990
private double [ ] computeResidualVector ( double [ ] vector , int centroidIndex ) { double [ ] residualVector = new double [ vectorLength ] ; for ( int i = 0 ; i < vectorLength ; i ++ ) { residualVector [ i ] = coarseQuantizer [ centroidIndex ] [ i ] - vector [ i ] ; } return residualVector ; }
Computes the residual vector .
9,991
public void outputItemsPerList ( ) { int max = 0 ; int min = Integer . MAX_VALUE ; double sum = 0 ; for ( int i = 0 ; i < numCoarseCentroids ; i ++ ) { if ( invertedLists [ i ] . size ( ) > max ) { max = invertedLists [ i ] . size ( ) ; } if ( invertedLists [ i ] . size ( ) < min ) { min = invertedLists [ i ] . size ( ...
Utility method that calculates and prints the min max and avg number of items per inverted list of the index .
9,992
public byte [ ] getPQCodeByte ( String id ) throws Exception { int iid = getInternalId ( id ) ; if ( iid == - 1 ) { throw new Exception ( "Id does not exist!" ) ; } if ( numProductCentroids > 256 ) { throw new Exception ( "Call the short variant of the method!" ) ; } DatabaseEntry key = new DatabaseEntry ( ) ; IntegerB...
Returns the pq code of the image with the given id .
9,993
public int getInvertedListId ( String id ) throws Exception { int iid = getInternalId ( id ) ; if ( iid == - 1 ) { throw new Exception ( "Id does not exist!" ) ; } DatabaseEntry key = new DatabaseEntry ( ) ; IntegerBinding . intToEntry ( iid , key ) ; DatabaseEntry data = new DatabaseEntry ( ) ; if ( ( iidToIvfpqDB . g...
Returns the inverted list of the image with the given id .
9,994
public static PageRange parse ( String pages ) { ANTLRInputStream is = new ANTLRInputStream ( pages ) ; InternalPageLexer lexer = new InternalPageLexer ( is ) ; lexer . removeErrorListeners ( ) ; CommonTokenStream tokens = new CommonTokenStream ( lexer ) ; InternalPageParser parser = new InternalPageParser ( tokens ) ;...
Parses a given page or range of pages . If the given string cannot be parsed the method will return a page range with a literal string .
9,995
public static void main ( String args [ ] ) throws Exception { String urlStr = "http://upload.wikimedia.org/wikipedia/commons/5/58/Sunset_2007-1.jpg" ; String id = "Sunset_2007-1" ; String downloadFolder = "images/" ; boolean saveThumb = true ; boolean saveOriginal = true ; boolean followRedirects = false ; ImageDownlo...
Example of a single image download using this class .
9,996
private static CSLDate merge ( CSLDate d1 , CSLDate d2 ) { if ( d1 == null ) { return d2 ; } else if ( d2 == null ) { return d1 ; } CSLDateBuilder builder = new CSLDateBuilder ( ) ; builder . dateParts ( d1 . getDateParts ( ) [ 0 ] , d2 . getDateParts ( ) [ d2 . getDateParts ( ) . length - 1 ] ) ; if ( d1 . getCirca ( ...
Merges two dates
9,997
public static int toMonth ( String month ) { int m = - 1 ; if ( month != null && ! month . isEmpty ( ) ) { if ( StringUtils . isNumeric ( month ) ) { m = Integer . parseInt ( month ) ; if ( m < 1 || m > 12 ) { m = - 1 ; } } else { m = tryParseMonth ( month , Locale . ENGLISH ) ; if ( m <= 0 ) { m = tryParseMonth ( mont...
Parses the given month string
9,998
private static Map < String , Integer > getMonthNames ( Locale locale ) { Map < String , Integer > r = MONTH_NAMES_CACHE . get ( locale ) ; if ( r == null ) { DateFormatSymbols symbols = DateFormatSymbols . getInstance ( locale ) ; r = new HashMap < > ( 24 ) ; String [ ] months = symbols . getMonths ( ) ; for ( int i =...
Retrieves and caches a list of month names for a given locale
9,999
private static int tryParseMonth ( String month , Locale locale ) { Map < String , Integer > names = getMonthNames ( locale ) ; Integer r = names . get ( month . toUpperCase ( ) ) ; if ( r != null ) { return r ; } return - 1 ; }
Tries to parse the given month string using the month names of the given locale