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: " + className , exception ) ; } return type ; }
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: " + methodName + " from type: " + type , exception ) ; } method . setAccessible ( true ) ; Object output = null ; try { output = method . invoke ( instance , input ) ; } catch ( Exception exception ) { throw new FaxException ( "Unable to invoke method: " + methodName + " of type: " + type , exception ) ; } return output ; }
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 ) ; return field ; }
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 . class . getName ( ) ; } validator = ( ProcessOutputValidator ) ReflectionHelper . createInstance ( className ) ; return validator ; }
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 . createInstance ( className ) ; } return handler ; }
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 ( ) + this . windowsCommandPrefix . length ( ) + 1 ) ; buffer . append ( this . windowsCommandPrefix ) ; buffer . append ( " " ) ; buffer . append ( updatedCommand ) ; updatedCommand = buffer . toString ( ) ; } ProcessOutput processOutput = ProcessExecutorHelper . executeProcess ( this , updatedCommand ) ; this . validateProcessOutput ( processOutput , faxActionType ) ; this . updateFaxJob ( faxJob , processOutput , faxActionType ) ; return processOutput ; }
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 . SYSTEM_EOL ) ; buffer . append ( "File: " ) ; buffer . append ( this . getFilePath ( ) ) ; buffer . append ( Logger . SYSTEM_EOL ) ; buffer . append ( "Priority: " ) ; buffer . append ( this . getPriority ( ) ) ; buffer . append ( Logger . SYSTEM_EOL ) ; buffer . append ( "Target Address: " ) ; buffer . append ( this . getTargetAddress ( ) ) ; buffer . append ( Logger . SYSTEM_EOL ) ; buffer . append ( "Target Name: " ) ; buffer . append ( this . getTargetName ( ) ) ; buffer . append ( Logger . SYSTEM_EOL ) ; buffer . append ( "Sender Name: " ) ; buffer . append ( this . getSenderName ( ) ) ; buffer . append ( Logger . SYSTEM_EOL ) ; buffer . append ( "Sender Fax Number: " ) ; buffer . append ( this . getSenderFaxNumber ( ) ) ; buffer . append ( Logger . SYSTEM_EOL ) ; buffer . append ( "Sender Email: " ) ; buffer . append ( this . getSenderEmail ( ) ) ; return buffer ; }
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 ( ) ; } catch ( Exception exception ) { logger . logError ( new Object [ ] { "Error while closing COMM port connection." } , exception ) ; } } }
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 ( ) ; if ( ! adapter . isOpen ( ) ) { connectionValid = false ; } } if ( ! connectionValid ) { this . releaseCommPortConnection ( ) ; this . commConnection = this . createCommPortConnection ( ) ; } } connection = this . commConnection ; return connection ; }
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 . unregisterFromRuntime ( ) ; logger . info ( "Shutdown collectScheduledExecutor and exportScheduledExecutor..." ) ; collectScheduledExecutor . shutdownNow ( ) ; exportScheduledExecutor . shutdownNow ( ) ; try { logger . info ( "Collect metrics..." ) ; collectMetrics ( ) ; logger . info ( "Export metrics..." ) ; exportCollectedMetrics ( ) ; } catch ( RuntimeException e ) { logger . warn ( "Ignore failure collecting and exporting metrics during stop" , e ) ; } logger . info ( "Stop queries..." ) ; for ( Query query : queries ) { try { query . stop ( ) ; } catch ( Exception e ) { logger . warn ( "Ignore exception stopping query {}" , query , e ) ; } } logger . info ( "Stop output writers..." ) ; for ( OutputWriter outputWriter : outputWriters ) { try { outputWriter . stop ( ) ; } catch ( Exception e ) { logger . warn ( "Ignore exception stopping outputWriters" , e ) ; } } state = State . STOPPED ; logger . info ( "Set state to {}" , state ) ; } catch ( RuntimeException e ) { state = State . ERROR ; if ( logger . isDebugEnabled ( ) ) { logger . warn ( "Exception stopping EmbeddedJmxTrans" , e ) ; } throw e ; } finally { lifecycleLock . writeLock ( ) . unlock ( ) ; } logger . info ( "Stopped" ) ; }
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 ( TimeUnit . SECONDS ) ) ; if ( resultsByTime . containsKey ( epoch ) ) { List < QueryResult > current = resultsByTime . get ( epoch ) ; current . add ( result ) ; resultsByTime . put ( epoch , current ) ; } else { ArrayList < QueryResult > newQueryList = new ArrayList < QueryResult > ( ) ; newQueryList . add ( result ) ; resultsByTime . put ( epoch , newQueryList ) ; } } return resultsByTime ; }
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 ( result . getName ( ) ) ] = result . getValue ( ) ; } return Arrays . asList ( alignedResults ) ; }
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 ) ; } else if ( ch == '.' ) { result . append ( escapeDot ? '_' : ch ) ; } else if ( ch == '"' && ( ( i == 0 ) || ( i == chars . length - 1 ) ) ) { } else { result . append ( '_' ) ; } } }
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 = currentConfigurationLastModified ; } } catch ( IOException ioex ) { logger . warn ( "Error while reading last configuration modification date." , ioex ) ; } } return result ; }
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 ) ; for ( String configurationUrl : tokens ) { configurationUrl = configurationUrl . trim ( ) ; Resource configuration = resourceLoader . getResource ( configurationUrl ) ; if ( configuration != null && configuration . exists ( ) ) { result . add ( configuration ) ; } else if ( ignoreConfigurationNotFound ) { logger . debug ( "Ignore missing configuration file {}" , configuration ) ; } else { throw new EmbeddedJmxTransException ( "Configuration file " + configuration + " not found" ) ; } } } return result ; }
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 ) ; } catch ( UnrecoverablePduException e ) { logger . error ( "Encode error: " , e ) ; } catch ( RecoverablePduException e ) { logger . error ( "Encode error: " , e ) ; } if ( logger . isDebugEnabled ( ) ) logger . debug ( "LB sent generic_nack response for packet (" + packet + ") to " + channel . getRemoteAddress ( ) . toString ( ) + ". session ID : " + sessionId ) ; channel . write ( buffer ) ; }
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 new EmbeddedJmxTransException ( "Exception reading etcd key '" + KeyURI + "': " + t . getMessage ( ) , t ) ; } }
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 = client . getOutputProtocol ( ) ; if ( proto != null ) { proto . getTransport ( ) . close ( ) ; } } catch ( Throwable e ) { logger . warn ( "close output transport fail" , e ) ; } }
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 && ! getStringSetting ( SETTING_PROXY_HOST ) . isEmpty ( ) ) { proxy = new Proxy ( Proxy . Type . HTTP , new InetSocketAddress ( getStringSetting ( SETTING_PROXY_HOST ) , getIntSetting ( SETTING_PROXY_PORT ) ) ) ; } logger . info ( "Starting Stackdriver writer connected to '{}', proxy {} ..." , url , proxy ) ; stackdriverApiTimeoutInMillis = getIntSetting ( SETTING_STACKDRIVER_API_TIMEOUT_IN_MILLIS , DEFAULT_STACKDRIVER_API_TIMEOUT_IN_MILLIS ) ; if ( getStringSetting ( SETTING_SOURCE_INSTANCE , null ) != null && ! getStringSetting ( SETTING_SOURCE_INSTANCE ) . isEmpty ( ) ) { instanceId = getStringSetting ( SETTING_SOURCE_INSTANCE ) ; logger . info ( "Using instance ID {} from setting {}" , instanceId , SETTING_SOURCE_INSTANCE ) ; } else if ( getStringSetting ( SETTING_DETECT_INSTANCE , null ) != null && "AWS" . equalsIgnoreCase ( getStringSetting ( SETTING_DETECT_INSTANCE ) ) ) { logger . info ( "Detect instance set to AWS, trying to determine AWS instance ID" ) ; instanceId = getLocalAwsInstanceId ( ) ; if ( instanceId != null ) { logger . info ( "Detected instance ID as {}" , instanceId ) ; } else { logger . info ( "Unable to detect AWS instance ID for this machine, sending metrics without an instance ID" ) ; } } else { instanceId = null ; logger . info ( "No source instance ID passed, and not set to detect, sending metrics without and instance ID" ) ; } }
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 ) url . openConnection ( proxy ) ; } urlConnection . setRequestMethod ( "POST" ) ; urlConnection . setDoInput ( true ) ; urlConnection . setDoOutput ( true ) ; urlConnection . setReadTimeout ( stackdriverApiTimeoutInMillis ) ; urlConnection . setRequestProperty ( "content-type" , "application/json; charset=utf-8" ) ; urlConnection . setRequestProperty ( "x-stackdriver-apikey" , apiKey ) ; serialize ( results , urlConnection . getOutputStream ( ) ) ; int responseCode = urlConnection . getResponseCode ( ) ; if ( responseCode != 200 && responseCode != 201 ) { exceptionCounter . incrementAndGet ( ) ; logger . warn ( "Failure {}:'{}' to send result to Stackdriver server '{}' with proxy {}" , responseCode , urlConnection . getResponseMessage ( ) , url , proxy ) ; } if ( logger . isTraceEnabled ( ) ) { IoUtils2 . copy ( urlConnection . getInputStream ( ) , System . out ) ; } } catch ( Exception e ) { exceptionCounter . incrementAndGet ( ) ; logger . warn ( "Failure to send result to Stackdriver server '{}' with proxy {}" , url , proxy , e ) ; } finally { if ( urlConnection != null ) { try { InputStream in = urlConnection . getInputStream ( ) ; IoUtils2 . copy ( in , IoUtils2 . nullOutputStream ( ) ) ; IoUtils2 . closeQuietly ( in ) ; InputStream err = urlConnection . getErrorStream ( ) ; if ( err != null ) { IoUtils2 . copy ( err , IoUtils2 . nullOutputStream ( ) ) ; IoUtils2 . closeQuietly ( err ) ; } urlConnection . disconnect ( ) ; } catch ( IOException e ) { logger . warn ( "Error flushing http connection for one result, continuing" ) ; logger . debug ( "Stack trace for the http connection, usually a network timeout" , e ) ; } } } }
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 ( metadataConnection . getInputStream ( ) , "UTF-8" ) ) ; String inputLine ; while ( ( inputLine = in . readLine ( ) ) != null ) { detectedInstanceId = inputLine ; } in . close ( ) ; } catch ( Exception e ) { logger . warn ( "unable to determine AWS instance ID" , e ) ; } return detectedInstanceId ; }
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 ( ) + " : " + regularConfiguration . getPort ( ) ) ; } if ( this . securedConfiguration != null ) { this . securedBootstrap . bind ( new InetSocketAddress ( securedConfiguration . getHost ( ) , securedConfiguration . getPort ( ) ) ) ; if ( logger . isInfoEnabled ( ) ) { logger . info ( securedConfiguration . getName ( ) + " uses port : " + securedConfiguration . getPort ( ) + " for TLS clients." ) ; } } } catch ( ChannelException e ) { logger . error ( "Smpp Channel Exception:" , e ) ; } }
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 ( ) . awaitUninterruptibly ( ) ; this . regularBootstrap . shutdown ( ) ; if ( this . securedBootstrap != null ) this . securedBootstrap . shutdown ( ) ; logger . info ( regularConfiguration . getName ( ) + " stopped at " + regularConfiguration . getHost ( ) ) ; }
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 ( hostNode != null && hostPort != null ) { int port = Integer . parseInt ( hostPort ) ; String transport = routeSipUri . getTransportParam ( ) ; if ( transport == null ) transport = ListeningPoint . UDP ; node = register . getNode ( hostNode , port , transport , hostVersion ) ; } return node ; }
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 = true ; } return 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 ; } } for ( int i = 0 ; i < outboundRules . size ( ) ; i ++ ) { final OutboundRule outboundRule = ( OutboundRule ) outboundRules . get ( i ) ; if ( ! outboundRule . initialise ( context ) ) { rulesOk = false ; } } for ( int i = 0 ; i < catchElems . size ( ) ; i ++ ) { final CatchElem catchElem = ( CatchElem ) catchElems . get ( i ) ; if ( ! catchElem . initialise ( context ) ) { rulesOk = false ; } } if ( rulesOk ) { ok = true ; } if ( log . isDebugEnabled ( ) ) { log . debug ( "conf status " + ok ) ; } }
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 . setDoInput ( true ) ; urlConnection . setDoOutput ( true ) ; urlConnection . setReadTimeout ( coppereggApiTimeoutInMillis ) ; urlConnection . setRequestProperty ( "content-type" , "application/json; charset=utf-8" ) ; urlConnection . setRequestProperty ( "Authorization" , "Basic " + basicAuthentication ) ; int responseCode = urlConnection . getResponseCode ( ) ; if ( responseCode != 200 ) { logger . warn ( "Bad responsecode " + String . valueOf ( responseCode ) + " from Dahsboards Index: " + myurl ) ; } } catch ( Exception e ) { exceptionCounter . incrementAndGet ( ) ; logger . warn ( "Exception on dashboards index request " + myurl + " " + e ) ; } finally { if ( urlConnection != null ) { try { InputStream in = urlConnection . getInputStream ( ) ; String theString = convertStreamToString ( in ) ; for ( Map . Entry < String , String > entry : dashMap . entrySet ( ) ) { String checkName = entry . getKey ( ) ; try { String Rslt = groupFind ( checkName , theString , 1 ) ; if ( Rslt != null ) { Rslt = Send_Commmand ( "/dashboards/" + Rslt + ".json" , "PUT" , entry . getValue ( ) , 1 ) ; } else { Rslt = Send_Commmand ( "/dashboards.json" , "POST" , entry . getValue ( ) , 1 ) ; } } catch ( Exception e ) { exceptionCounter . incrementAndGet ( ) ; logger . warn ( "Exception in dashboard update or create: " + myurl + " " + e ) ; } } } catch ( IOException e ) { exceptionCounter . incrementAndGet ( ) ; logger . warn ( "Exception flushing http connection" + e ) ; } } } }
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 ++ ) { vector [ i ] = vector [ i ] / norm2 ; } } return vector ; }
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 [ i ] / norm1 ; } } return 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 ; i < descriptorLength ; i ++ ) { vlad [ nnIndex * descriptorLength + i ] += descriptor [ i ] - codebook [ nnIndex ] [ i ] ; } } return vlad ; }
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 . fromJson ( res ) ; if ( r . getDateParts ( ) . length == 2 && Arrays . equals ( r . getDateParts ( ) [ 0 ] , r . getDateParts ( ) [ 1 ] ) ) { r = new CSLDateBuilder ( r ) . dateParts ( r . getDateParts ( ) [ 0 ] ) . build ( ) ; } return r ; }
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 = false ; PCA pca = new PCA ( numPrincipalComponents , numTrainVectors , vectorLength , whitening ) ; pca . setCompact ( compact ) ; Linear vladArray = new Linear ( vectorLength , numTrainVectors , true , indexLocation , false , true , 0 ) ; for ( int i = 0 ; i < numTrainVectors ; i ++ ) { pca . addSample ( vladArray . getVector ( i ) ) ; } System . out . println ( "PCA computation started!" ) ; long start = System . currentTimeMillis ( ) ; pca . computeBasis ( ) ; long end = System . currentTimeMillis ( ) ; System . out . println ( "PCA computation completed in " + ( end - start ) + " ms" ) ; String PCAfile = indexLocation + "pca_" + numTrainVectors + "_" + numPrincipalComponents + "_" + ( end - start ) + "ms.txt" ; pca . savePCAToFile ( PCAfile ) ; }
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 ( strOrNull ( a . get ( FIELD_FIRSTNAME ) ) ) ; } if ( a . containsKey ( FIELD_LASTNAME ) ) { builder . family ( strOrNull ( a . get ( FIELD_LASTNAME ) ) ) ; } builder . parseNames ( true ) ; result [ i ] = builder . build ( ) ; ++ i ; } return result ; }
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 . equalsIgnoreCase ( TYPE_CASE ) ) { return CSLType . ARTICLE ; } else if ( type . equalsIgnoreCase ( TYPE_COMPUTER_PROGRAM ) ) { return CSLType . ARTICLE ; } else if ( type . equalsIgnoreCase ( TYPE_CONFERENCE_PROCEEDINGS ) ) { return CSLType . PAPER_CONFERENCE ; } else if ( type . equalsIgnoreCase ( TYPE_ENCYCLOPEDIA_ARTICLE ) ) { return CSLType . ENTRY_ENCYCLOPEDIA ; } else if ( type . equalsIgnoreCase ( TYPE_FILM ) ) { return CSLType . MOTION_PICTURE ; } else if ( type . equalsIgnoreCase ( TYPE_GENERIC ) ) { return CSLType . ARTICLE ; } else if ( type . equalsIgnoreCase ( TYPE_HEARING ) ) { return CSLType . SPEECH ; } else if ( type . equalsIgnoreCase ( TYPE_JOURNAL ) ) { return CSLType . ARTICLE_JOURNAL ; } else if ( type . equalsIgnoreCase ( TYPE_MAGAZINE_ARTICLE ) ) { return CSLType . ARTICLE_MAGAZINE ; } else if ( type . equalsIgnoreCase ( TYPE_NEWSPAPER_ARTICLE ) ) { return CSLType . ARTICLE_NEWSPAPER ; } else if ( type . equalsIgnoreCase ( TYPE_PATENT ) ) { return CSLType . PATENT ; } else if ( type . equalsIgnoreCase ( TYPE_REPORT ) ) { return CSLType . REPORT ; } else if ( type . equalsIgnoreCase ( TYPE_STATUTE ) ) { return CSLType . LEGISLATION ; } else if ( type . equalsIgnoreCase ( TYPE_TELEVISION_BROADCAST ) ) { return CSLType . BROADCAST ; } else if ( type . equalsIgnoreCase ( TYPE_THESIS ) ) { return CSLType . THESIS ; } else if ( type . equalsIgnoreCase ( TYPE_WEB_PAGE ) ) { return CSLType . WEBPAGE ; } else if ( type . equalsIgnoreCase ( TYPE_WORKING_PAPER ) ) { return CSLType . ARTICLE ; } return CSLType . ARTICLE ; }
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" , description = "assign values to shell variables" , command = ShellSetCommand . class ) , @ CommandDesc ( longName = "help" , description = "display help for a given command" , command = ShellHelpCommand . class ) , @ CommandDesc ( longName = "exit" , description = "exit the interactive shell" , command = ShellExitCommand . class ) , @ CommandDesc ( longName = "quit" , description = "exit the interactive shell" , command = ShellQuitCommand . class ) , } ) public void setCommand ( AbstractCSLToolCommand command ) { }
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_vibrateDuration , 20 ) ; v . vibrate ( duration ) ; } }
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 . setTextColor ( color ) ; final int background = styledAttributes . getResourceId ( R . styleable . PinLock_keypadButtonShape , R . drawable . rectangle ) ; view . setBackgroundResource ( background ) ; }
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 ] . length ; j ++ ) { out . writeDouble ( features [ i ] [ j ] ) ; } } out . close ( ) ; }
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 ] + "," ) ; } out . write ( feature [ feature . length - 1 ] + "\n" ) ; } out . close ( ) ; }
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 true ; else return false ; } } ; String [ ] files = dir . list ( filter ) ; for ( int i = 0 ; i < files . length ; i ++ ) { if ( i % 100 == 0 ) { System . out . println ( "Converting file " + i ) ; } BufferedReader in = new BufferedReader ( new FileReader ( new File ( featuresFolder + files [ i ] ) ) ) ; DataOutputStream out = new DataOutputStream ( new BufferedOutputStream ( new FileOutputStream ( featuresFolder + files [ i ] + "b" ) ) ) ; String line ; while ( ( line = in . readLine ( ) ) != null ) { String [ ] nums = line . split ( "," ) ; for ( int j = 0 ; j < featureLength ; j ++ ) { out . writeDouble ( Double . parseDouble ( nums [ j ] ) ) ; } } in . close ( ) ; out . close ( ) ; } }
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" ) ) return true ; else return false ; } } ; String [ ] files = dir . list ( filter ) ; for ( int i = 0 ; i < files . length ; i ++ ) { if ( i % 100 == 0 ) { System . out . println ( "Converting file " + i ) ; } DataInputStream in = new DataInputStream ( new BufferedInputStream ( new FileInputStream ( featuresFolder + files [ i ] ) ) ) ; BufferedWriter out = new BufferedWriter ( new FileWriter ( new File ( featuresFolder + files [ i ] . replace ( "b" , "" ) ) ) ) ; long counter = 0 ; while ( true ) { try { double val = in . readDouble ( ) ; out . write ( String . valueOf ( val ) ) ; } catch ( EOFException e ) { break ; } counter ++ ; if ( counter % featureLength == 0 ) { out . write ( "\n" ) ; } else { out . write ( "," ) ; } } in . close ( ) ; out . close ( ) ; } }
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 ) ; forgetButton . setOnClickListener ( new View . OnClickListener ( ) { public void onClick ( View v ) { onForgotPin ( ) ; setResult ( FORGOT ) ; finish ( ) ; } } ) ; }
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 = "display sorted list of available citation IDs" , command = ListCommand . class ) , @ CommandDesc ( longName = "lint" , description = "validate citation items" , command = LintCommand . class ) , @ CommandDesc ( longName = "json" , description = "convert input bibliography to JSON" , command = JsonCommand . class ) , @ CommandDesc ( longName = "mendeley" , description = "connect to Mendeley Web" , command = MendeleyCommand . class ) , @ CommandDesc ( longName = "zotero" , description = "connect to Zotero" , command = ZoteroCommand . class ) , @ CommandDesc ( longName = "shell" , description = "run citeproc-java in interactive mode" , command = ShellCommand . class ) , @ CommandDesc ( longName = "help" , description = "display help for a given command" , command = HelpCommand . class ) } ) public void setCommand ( AbstractCSLToolCommand command ) { if ( command instanceof ProviderCommand ) { this . command = new InputFileCommand ( ( ProviderCommand ) command ) ; } else { this . command = command ; } }
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 FileInputStream ( bibfile ) ) ) { return readBibliographyFile ( bis , bibfile . getName ( ) ) ; } }
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 ( bibfile ) ) ) { return determineFileFormat ( bis , bibfile . getName ( ) ) ; } }
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 ( is , UTF8 ) ; Map < String , String > sr = splitResponse ( response ) ; return responseToToken ( sr ) ; }
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 . setRequestMethod ( method . toString ( ) ) ; conn . setRequestProperty ( HEADER_HOST , makeBaseUri ( url ) ) ; String timestamp = makeTimestamp ( ) ; String nonce = makeNonce ( timestamp ) ; Map < String , String > authParams = new HashMap < > ( ) ; if ( additionalAuthParams != null ) { authParams . putAll ( additionalAuthParams ) ; } if ( token != null ) { authParams . put ( OAUTH_TOKEN , token . getToken ( ) ) ; } authParams . put ( OAUTH_CONSUMER_KEY , consumerKey ) ; authParams . put ( OAUTH_SIGNATURE_METHOD , HMAC_SHA1_METHOD ) ; authParams . put ( OAUTH_TIMESTAMP , timestamp ) ; authParams . put ( OAUTH_NONCE , nonce ) ; authParams . put ( OAUTH_VERSION , OAUTH_IMPL_VERSION ) ; String signature = makeSignature ( method . toString ( ) , url , authParams , token ) ; StringBuilder sb = new StringBuilder ( ) ; for ( Map . Entry < String , String > e : authParams . entrySet ( ) ) { appendAuthParam ( sb , e . getKey ( ) , e . getValue ( ) ) ; } appendAuthParam ( sb , OAUTH_SIGNATURE , signature ) ; conn . setRequestProperty ( HEADER_AUTHORIZATION , "OAuth " + sb . toString ( ) ) ; if ( additionalHeaders != null ) { for ( Map . Entry < String , String > e : additionalHeaders . entrySet ( ) ) { conn . setRequestProperty ( e . getKey ( ) , e . getValue ( ) ) ; } } conn . connect ( ) ; if ( conn . getResponseCode ( ) == 401 ) { throw new UnauthorizedException ( "Not authorized" ) ; } else if ( conn . getResponseCode ( ) != 200 ) { throw new RequestException ( "HTTP request failed with error code: " + conn . getResponseCode ( ) ) ; } return new Response ( conn ) ; }
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 ) { sb . append ( "0" ) ; } sb . append ( b ) ; } return sb . toString ( ) ; }
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" ) && url . getPort ( ) != - 1 && url . getPort ( ) != 443 ) ) { r += ":" + url . getPort ( ) ; } return r ; }
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 ( "=" ) ; kv [ 0 ] = PercentEncoding . decode ( kv [ 0 ] ) ; kv [ 1 ] = PercentEncoding . decode ( kv [ 1 ] ) ; kv [ 0 ] = PercentEncoding . encode ( kv [ 0 ] ) ; kv [ 1 ] = PercentEncoding . encode ( kv [ 1 ] ) ; String np = kv [ 0 ] + "=" + kv [ 1 ] ; result . add ( np ) ; } return result ; }
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 , String > p : authParams . entrySet ( ) ) { params . add ( PercentEncoding . encode ( p . getKey ( ) ) + "=" + PercentEncoding . encode ( p . getValue ( ) ) ) ; } Collections . sort ( params ) ; StringBuilder pb = new StringBuilder ( ) ; for ( String p : params ) { if ( pb . length ( ) > 0 ) { pb . append ( "&" ) ; } pb . append ( p ) ; } sb . append ( "&" ) ; sb . append ( PercentEncoding . encode ( pb . toString ( ) ) ) ; String baseString = sb . toString ( ) ; String tokenSecret = token != null ? token . getSecret ( ) : "" ; String key = PercentEncoding . encode ( consumerSecret ) + "&" + PercentEncoding . encode ( tokenSecret ) ; try { SecretKeySpec secretKey = new SecretKeySpec ( key . getBytes ( UTF8 ) , HMAC_SHA1_ALGORITHM ) ; Mac mac = Mac . getInstance ( HMAC_SHA1_ALGORITHM ) ; mac . init ( secretKey ) ; byte [ ] bytes = mac . doFinal ( baseString . getBytes ( UTF8 ) ) ; return PercentEncoding . encode ( DatatypeConverter . printBase64Binary ( bytes ) ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } catch ( NoSuchAlgorithmException e ) { throw new RuntimeException ( e ) ; } catch ( InvalidKeyException e ) { throw new RuntimeException ( e ) ; } }
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 ; try { pr = ShellCommandParser . parse ( args , EXCLUDED_COMMANDS ) ; } catch ( OptionParserException e ) { error ( e . getMessage ( ) ) ; continue ; } catch ( IntrospectionException e ) { throw new RuntimeException ( e ) ; } Class < ? extends Command > cmdClass = pr . getFirstCommand ( ) ; if ( cmdClass == ShellExitCommand . class || cmdClass == ShellQuitCommand . class ) { break ; } else if ( cmdClass == null ) { error ( "unknown command `" + args [ 0 ] + "'" ) ; continue ; } Command cmd ; try { cmd = cmdClass . newInstance ( ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } boolean acceptsInputFile = false ; if ( cmd instanceof ProviderCommand ) { cmd = new InputFileCommand ( ( ProviderCommand ) cmd ) ; acceptsInputFile = true ; } args = ArrayUtils . subarray ( args , 1 , args . length ) ; args = augmentCommand ( args , pr . getLastCommand ( ) , acceptsInputFile ) ; try { cmd . run ( args , lr , cout ) ; } catch ( OptionParserException e ) { error ( e . getMessage ( ) ) ; } } return line ; }
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 ) ; } } catch ( IntrospectionException e ) { throw new RuntimeException ( e ) ; } ShellContext sc = ShellContext . current ( ) ; for ( Option < ID > o : options . getOptions ( ) ) { if ( o . getLongName ( ) . equals ( "style" ) ) { args = ArrayUtils . add ( args , "--style" ) ; args = ArrayUtils . add ( args , sc . getStyle ( ) ) ; } else if ( o . getLongName ( ) . equals ( "locale" ) ) { args = ArrayUtils . add ( args , "--locale" ) ; args = ArrayUtils . add ( args , sc . getLocale ( ) ) ; } else if ( o . getLongName ( ) . equals ( "format" ) ) { args = ArrayUtils . add ( args , "--format" ) ; args = ArrayUtils . add ( args , sc . getFormat ( ) ) ; } else if ( o . getLongName ( ) . equals ( "input" ) && sc . getInputFile ( ) != null && ! sc . getInputFile ( ) . isEmpty ( ) ) { args = ArrayUtils . add ( args , "--input" ) ; args = ArrayUtils . add ( args , sc . getInputFile ( ) ) ; } } return args ; }
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 . PinLock_statusEmptyBackground , R . drawable . dot_empty ) ; setBackgroundResource ( background ) ; } }
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 ; } else if ( c == '}' ) { currentTokenType = Type . END_OBJECT ; } else if ( c == '[' ) { currentTokenType = Type . START_ARRAY ; } else if ( c == ']' ) { currentTokenType = Type . END_ARRAY ; } else if ( c == ':' ) { currentTokenType = Type . COLON ; } else if ( c == ',' ) { currentTokenType = Type . COMMA ; } else if ( c == '"' ) { currentTokenType = Type . STRING ; } else if ( c == '-' || ( c >= '0' && c <= '9' ) ) { currentTokenType = Type . NUMBER ; currentCharacter = c ; } else if ( c == 't' ) { int c2 = r . read ( ) ; int c3 = r . read ( ) ; int c4 = r . read ( ) ; if ( c2 == 'r' && c3 == 'u' & c4 == 'e' ) { currentTokenType = Type . TRUE ; } else { currentTokenType = null ; } } else if ( c == 'f' ) { int c2 = r . read ( ) ; int c3 = r . read ( ) ; int c4 = r . read ( ) ; int c5 = r . read ( ) ; if ( c2 == 'a' && c3 == 'l' & c4 == 's' && c5 == 'e' ) { currentTokenType = Type . FALSE ; } else { currentTokenType = null ; } } else if ( c == 'n' ) { int c2 = r . read ( ) ; int c3 = r . read ( ) ; int c4 = r . read ( ) ; if ( c2 == 'u' && c3 == 'l' & c4 == 'l' ) { currentTokenType = Type . NULL ; } else { currentTokenType = null ; } } else { currentTokenType = null ; } if ( currentTokenType == null ) { throw new IllegalStateException ( "Unrecognized token: " + ( char ) c ) ; } return currentTokenType ; }
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 == '\\' || c2 == '/' ) { result . append ( ( char ) c2 ) ; } else if ( c2 == 'b' ) { result . append ( "\b" ) ; } else if ( c2 == 'f' ) { result . append ( "\f" ) ; } else if ( c2 == 'n' ) { result . append ( "\n" ) ; } else if ( c2 == 'r' ) { result . append ( "\r" ) ; } else if ( c2 == 't' ) { result . append ( "\t" ) ; } else if ( c2 == 'u' ) { int d1 = r . read ( ) ; int d2 = r . read ( ) ; int d3 = r . read ( ) ; int d4 = r . read ( ) ; checkHexDigit ( d1 ) ; checkHexDigit ( d2 ) ; checkHexDigit ( d3 ) ; checkHexDigit ( d4 ) ; int e = Character . digit ( d1 , 16 ) ; e = ( e << 4 ) + Character . digit ( d2 , 16 ) ; e = ( e << 4 ) + Character . digit ( d3 , 16 ) ; e = ( e << 4 ) + Character . digit ( d4 , 16 ) ; result . append ( ( char ) e ) ; } } else { result . append ( ( char ) c ) ; } } return result . toString ( ) ; }
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 ( currentCharacter >= '0' && currentCharacter <= '9' ) { result = result * 10 + currentCharacter - '0' ; } else if ( currentCharacter == '.' ) { return readReal ( result , negative ) ; } else { break ; } currentCharacter = r . read ( ) ; } return negative ? - result : result ; }
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 ) currentCharacter ) ; } else if ( currentCharacter == 'e' || currentCharacter == 'E' ) { if ( exponent ) { break ; } b . append ( ( char ) currentCharacter ) ; exponent = true ; } else if ( currentCharacter == '-' || currentCharacter == '+' ) { if ( expsign ) { break ; } b . append ( ( char ) currentCharacter ) ; expsign = true ; } else { break ; } } while ( currentCharacter >= 0 ) ; double result = Double . parseDouble ( b . toString ( ) ) ; return negative ? - result : result ; }
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 " + "web browser to the\nfollowing URL and follow the instructions:\n" ) ; System . out . println ( authUrl ) ; System . out . println ( ) ; if ( Desktop . isDesktopSupported ( ) ) { Desktop d = Desktop . getDesktop ( ) ; if ( d . isSupported ( Desktop . Action . BROWSE ) ) { try { d . browse ( new URI ( authUrl ) ) ; } catch ( Exception e ) { } } } String verificationCode ; try { verificationCode = in . readLine ( "Enter verification code: " ) ; } catch ( IOException e ) { throw new RuntimeException ( "Could not read from console." ) ; } if ( verificationCode == null || verificationCode . isEmpty ( ) ) { return false ; } try { System . out . println ( "Connecting ..." ) ; mc . authorize ( verificationCode ) ; } catch ( IOException e ) { error ( "remote server refused authorization." ) ; return false ; } return true ; }
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 . getDidYouMeanString ( availableStyles , style ) ; if ( dyms != null && ! dyms . isEmpty ( ) ) { message += "\n\n" + dyms ; } } error ( message ) ; return false ; }
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 < numProductCentroids ; j ++ ) { String line = in . readLine ( ) ; String [ ] centroidString = line . split ( "," ) ; for ( int k = 0 ; k < subVectorLength ; k ++ ) { productQuantizer [ i ] [ j ] [ k ] = Double . parseDouble ( centroidString [ k ] ) ; } } } in . close ( ) ; }
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 ++ ) { int nearestCoarseIndex = nearestCoarseCentroidIndices [ i ] ; double [ ] residualVectorQuery = computeResidualVector ( qVector , nearestCoarseIndex ) ; if ( transformation == TransformationType . RandomRotation ) { residualVectorQuery = rr . rotate ( residualVectorQuery ) ; } else if ( transformation == TransformationType . RandomPermutation ) { residualVectorQuery = rp . permute ( residualVectorQuery ) ; } double [ ] [ ] lookUpTable = computeLookupADC ( residualVectorQuery ) ; for ( int j = 0 ; j < invertedLists [ nearestCoarseIndex ] . size ( ) ; j ++ ) { int iid = invertedLists [ nearestCoarseIndex ] . getQuick ( j ) ; double l2distance = 0 ; int codeStart = j * numSubVectors ; if ( numProductCentroids <= 256 ) { byte [ ] pqCode = pqByteCodes [ nearestCoarseIndex ] . toArray ( codeStart , numSubVectors ) ; for ( int m = 0 ; m < pqCode . length ; m ++ ) { l2distance += lookUpTable [ m ] [ pqCode [ m ] + 128 ] ; } } else { short [ ] pqCode = pqShortCodes [ nearestCoarseIndex ] . toArray ( codeStart , numSubVectors ) ; for ( int m = 0 ; m < pqCode . length ; m ++ ) { l2distance += lookUpTable [ m ] [ pqCode [ m ] ] ; } } nn . offer ( new Result ( iid , l2distance ) ) ; } } return nn ; }
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 ] ) * ( coarseQuantizer [ i ] [ j ] - vector [ j ] ) ; if ( distance >= minDistance ) { break ; } } if ( distance < minDistance ) { minDistance = distance ; centroidIndex = i ; } } return centroidIndex ; }
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 ( int j = 0 ; j < vectorLength ; j ++ ) { l2distance += ( coarseQuantizer [ i ] [ j ] - vector [ j ] ) * ( coarseQuantizer [ i ] [ j ] - vector [ j ] ) ; if ( l2distance > lowest ) { skip = true ; break ; } } if ( ! skip ) { bpq . offer ( new Result ( i , l2distance ) ) ; if ( i >= k ) { lowest = bpq . last ( ) . getDistance ( ) ; } } } int [ ] nn = new int [ k ] ; for ( int i = 0 ; i < k ; i ++ ) { nn [ i ] = bpq . poll ( ) . getId ( ) ; } return nn ; }
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 [ subQuantizerIndex ] [ i ] [ j ] - subvector [ j ] ) * ( productQuantizer [ subQuantizerIndex ] [ i ] [ j ] - subvector [ j ] ) ; if ( distance >= minDistance ) { break ; } } if ( distance < minDistance ) { minDistance = distance ; centroidIndex = i ; } } return centroidIndex ; }
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 ( ) ; } sum += invertedLists [ i ] . size ( ) ; } System . out . println ( "Maximum number of vectors: " + max ) ; System . out . println ( "Minimum number of vectors: " + min ) ; System . out . println ( "Average number of vectors: " + ( sum / numCoarseCentroids ) ) ; }
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 ( ) ; IntegerBinding . intToEntry ( iid , key ) ; DatabaseEntry data = new DatabaseEntry ( ) ; if ( ( iidToIvfpqDB . get ( null , key , data , null ) == OperationStatus . SUCCESS ) ) { TupleInput input = TupleBinding . entryToInput ( data ) ; input . readInt ( ) ; byte [ ] code = new byte [ numSubVectors ] ; for ( int i = 0 ; i < numSubVectors ; i ++ ) { code [ i ] = input . readByte ( ) ; } return code ; } else { throw new Exception ( "Id does not exist!" ) ; } }
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 . get ( null , key , data , null ) == OperationStatus . SUCCESS ) ) { TupleInput input = TupleBinding . entryToInput ( data ) ; int listId = input . readInt ( ) ; return listId ; } else { throw new Exception ( "Id does not exist!" ) ; } }
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 ) ; parser . removeErrorListeners ( ) ; PagesContext ctx = parser . pages ( ) ; return new PageRange ( ctx . literal != null ? ctx . literal : pages , ctx . pageFrom , ctx . numberOfPages ) ; }
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 ; ImageDownload imdown = new ImageDownload ( urlStr , id , downloadFolder , saveThumb , saveOriginal , followRedirects ) ; imdown . setDebug ( true ) ; ImageDownloadResult imdr = imdown . call ( ) ; System . out . println ( "Getting the BufferedImage object of the downloaded image." ) ; imdr . getImage ( ) ; System . out . println ( "Reading the downloaded image thumbnail into a BufferedImage object." ) ; ImageIO . read ( new File ( downloadFolder + id + "-thumb.jpg" ) ) ; System . out . println ( "Success!" ) ; }
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 ( ) != null ) { builder . circa ( d1 . getCirca ( ) ) ; } if ( d2 . getCirca ( ) != null && ( d1 . getCirca ( ) == null || d2 . getCirca ( ) . booleanValue ( ) ) ) { builder . circa ( d2 . getCirca ( ) ) ; } if ( d1 . getLiteral ( ) != null ) { builder . literal ( d1 . getLiteral ( ) ) ; } if ( d2 . getLiteral ( ) != null ) { if ( d1 . getLiteral ( ) != null ) { builder . literal ( d1 . getLiteral ( ) + "-" + d2 . getLiteral ( ) ) ; } else { builder . literal ( d2 . getLiteral ( ) ) ; } } if ( d1 . getSeason ( ) != null ) { builder . season ( d1 . getSeason ( ) ) ; } if ( d2 . getSeason ( ) != null ) { if ( d1 . getSeason ( ) != null ) { builder . season ( d1 . getSeason ( ) + "-" + d2 . getSeason ( ) ) ; } else { builder . season ( d2 . getSeason ( ) ) ; } } if ( d1 . getRaw ( ) != null ) { builder . raw ( d1 . getRaw ( ) ) ; } if ( d2 . getRaw ( ) != null ) { if ( d1 . getRaw ( ) != null ) { builder . raw ( d1 . getRaw ( ) + "-" + d2 . getRaw ( ) ) ; } else { builder . raw ( d2 . getRaw ( ) ) ; } } return builder . build ( ) ; }
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 ( month , Locale . getDefault ( ) ) ; if ( m <= 0 ) { for ( Locale l : Locale . getAvailableLocales ( ) ) { m = tryParseMonth ( month , l ) ; if ( m > 0 ) { break ; } } } } } } return m ; }
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 = 0 ; i < months . length ; ++ i ) { String m = months [ i ] ; if ( ! m . isEmpty ( ) ) { r . put ( m . toUpperCase ( ) , i + 1 ) ; } } String [ ] shortMonths = symbols . getShortMonths ( ) ; for ( int i = 0 ; i < shortMonths . length ; ++ i ) { String m = shortMonths [ i ] ; if ( ! m . isEmpty ( ) ) { r . put ( m . toUpperCase ( ) , i + 1 ) ; } } MONTH_NAMES_CACHE . put ( locale , r ) ; } return r ; }
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