idx int64 0 41.2k | question stringlengths 74 4.21k | target stringlengths 5 888 |
|---|---|---|
7,800 | public Builder addProcessors ( Processor ... processors ) { this . processors . add ( new ArrayList < > ( Arrays . asList ( processors ) ) ) ; return self ( ) ; } | Adds processors for populating a series of exchanges with an outgoing message - all processors in a single call apply ONLY to a single message add consecutive calls to addProcessors in order to handle further messages |
7,801 | public Builder addPredicates ( Predicate ... predicates ) { this . predicates . add ( new ArrayList < > ( Arrays . asList ( predicates ) ) ) ; return self ( ) ; } | Add a set of predicates to validate an incoming exchange - all predicates in a single call apply ONLY to a single message add consecutive calls to addPredicates in order to handle further messages |
7,802 | public Builder predicateMultiplier ( int count , Predicate ... predicates ) { for ( int i = 0 ; i < count ; i ++ ) { addPredicates ( predicates ) ; } return self ( ) ; } | Expect a repeat of the same predicates multiple times |
7,803 | public static String closestKey ( String propertyPrefix , Language language , String ... propertyComponents ) { return findKey ( propertyPrefix , language , propertyComponents ) ; } | Finds the closest key to the given components |
7,804 | public static Val get ( Class < ? > clazz , String ... propertyComponents ) { return get ( clazz . getName ( ) , propertyComponents ) ; } | Gets the value of a property for a given class |
7,805 | public static void loadConfig ( Resource resource ) { if ( resource == null || ! resource . exists ( ) ) { return ; } if ( resource . path ( ) != null && getInstance ( ) . loaded . contains ( resource . path ( ) ) ) { return ; } new ConfigParser ( resource ) . parse ( ) ; if ( resource . path ( ) != null ) { getInstance ( ) . loaded . add ( resource . path ( ) ) ; } } | Loads a config file |
7,806 | public static void setAllCommandLine ( String [ ] args ) { if ( args != null ) { CommandLineParser parser = new CommandLineParser ( ) ; parser . parse ( args ) ; setAllCommandLine ( parser ) ; } } | Sets all properties from the given array of arguments |
7,807 | public static void setAllCommandLine ( CommandLineParser parser ) { if ( parser != null ) { parser . getSetEntries ( ) . forEach ( entry -> getInstance ( ) . setterFunction . setProperty ( entry . getKey ( ) , entry . getValue ( ) , "CommandLine" ) ) ; } } | Sets all properties from the given command line parser . |
7,808 | protected static boolean loadDefaultConf ( String packageName ) throws ParseException { if ( packageName . endsWith ( ".conf" ) ) { return false ; } packageName = packageName . replaceAll ( "\\$[0-9]+$" , "" ) ; Resource defaultConf = new ClasspathResource ( ( packageName . replaceAll ( "\\." , "/" ) + "/" + DEFAULT_CONFIG_FILE_NAME ) . trim ( ) , Config . getDefaultClassLoader ( ) ) ; while ( ! defaultConf . exists ( ) ) { int idx = packageName . lastIndexOf ( '.' ) ; if ( idx == - 1 ) { defaultConf = new ClasspathResource ( packageName + "/" + DEFAULT_CONFIG_FILE_NAME , Config . getDefaultClassLoader ( ) ) ; break ; } packageName = packageName . substring ( 0 , idx ) ; defaultConf = new ClasspathResource ( packageName . replaceAll ( "\\." , "/" ) + "/" + DEFAULT_CONFIG_FILE_NAME , Config . getDefaultClassLoader ( ) ) ; } if ( defaultConf . exists ( ) ) { loadConfig ( defaultConf ) ; return true ; } return false ; } | Load default conf . |
7,809 | static String resolveVariables ( String string ) { if ( string == null ) { return null ; } String rval = string ; Matcher m = STRING_SUBSTITUTION . matcher ( string ) ; while ( m . find ( ) ) { if ( getInstance ( ) . properties . containsKey ( m . group ( 1 ) ) ) { rval = rval . replaceAll ( Pattern . quote ( m . group ( 0 ) ) , get ( m . group ( 1 ) ) . asString ( ) ) ; } else if ( System . getProperties ( ) . contains ( m . group ( 1 ) ) ) { rval = rval . replaceAll ( Pattern . quote ( m . group ( 0 ) ) , System . getProperties ( ) . get ( m . group ( 1 ) ) . toString ( ) ) ; } else if ( System . getenv ( ) . containsKey ( m . group ( 1 ) ) ) { rval = rval . replaceAll ( Pattern . quote ( m . group ( 0 ) ) , System . getenv ( ) . get ( m . group ( 1 ) ) ) ; } } return rval ; } | Resolve variables string . |
7,810 | public static boolean valueIsScript ( String propertyName ) { return ( getInstance ( ) . properties . containsKey ( propertyName ) && getInstance ( ) . properties . get ( propertyName ) . startsWith ( SCRIPT_PROPERTY ) ) ; } | Determines if the value of the given property is a script or not |
7,811 | public void situateScenario ( Scenario scenario , Double2D position , Double2D alpha , Double2D beta , Double2D gamma ) throws ShanksException { Scenario2DPortrayal portrayal ; try { portrayal = ( Scenario2DPortrayal ) scenario . createScenarioPortrayal ( ) ; ContinuousPortrayal2D devicesPortrayal = ( ContinuousPortrayal2D ) portrayal . getPortrayals ( ) . get ( Scenario2DPortrayal . MAIN_DISPLAY_ID ) . get ( ScenarioPortrayal . DEVICES_PORTRAYAL ) ; Continuous2D devicesSpace = ( Continuous2D ) devicesPortrayal . getField ( ) ; Bag allElements = devicesSpace . getAllObjects ( ) ; Object [ ] all = allElements . objs ; for ( int i = 0 ; i < all . length ; i ++ ) { Device device = ( Device ) all [ i ] ; if ( device != null ) { Double2D devicePosition = devicesSpace . getObjectLocation ( device ) ; Double2D rotated = ShanksMath . rotate ( devicePosition , alpha , beta , gamma ) ; Double2D finalPosition = ShanksMath . add ( rotated , position ) ; this . situateDevice ( device , finalPosition . x , finalPosition . y ) ; } } HashMap < String , NetworkElement > elements = scenario . getCurrentElements ( ) ; for ( Entry < String , NetworkElement > entry : elements . entrySet ( ) ) { if ( entry . getValue ( ) instanceof Link ) { this . drawLink ( ( Link ) entry . getValue ( ) ) ; } } if ( scenario instanceof ComplexScenario ) { this . drawScenarioLinksLinks ( ( ComplexScenario ) scenario ) ; } } catch ( DuplicatedPortrayalIDException e ) { throw e ; } } | Situate the scenario in the complex scenario main display |
7,812 | public void awaitTermination ( ) throws InterruptedException { lock . lock ( ) ; try { while ( ! isDone ) { done . await ( ) ; } } finally { isDone = false ; lock . unlock ( ) ; } } | Awaits termination of the threads |
7,813 | protected boolean add ( GraphicalModel m , boolean recordOnDisk ) { boolean success = super . add ( m ) ; if ( ! success ) return false ; if ( recordOnDisk ) { try { if ( writeWithFactors ) { writeExample ( m ) ; } else { Set < GraphicalModel . Factor > cachedFactors = m . factors ; m . factors = new HashSet < > ( ) ; writeExample ( m ) ; m . factors = cachedFactors ; } } catch ( IOException e ) { e . printStackTrace ( ) ; } } return true ; } | Adds an element to the list and if recordOnDisk is true appends it to the backing store . |
7,814 | public static OAuthClientRequest getAuthorizationRequest ( String clientId , String redirectUri ) throws OAuthSystemException { return OAuthClientRequest . authorizationLocation ( OAUTH2_AUTHORIZATION_URL ) . setScope ( "public read write" ) . setResponseType ( ResponseType . CODE . toString ( ) ) . setClientId ( clientId ) . setRedirectURI ( redirectUri ) . buildQueryMessage ( ) ; } | Build an OAuth authorization request . |
7,815 | public static OAuthClientRequest getAccessTokenRequest ( String clientId , String clientSecret , String redirectUri , String authCode ) throws OAuthSystemException { return OAuthClientRequest . tokenLocation ( OAUTH2_ACCESS_TOKEN_URL ) . setGrantType ( GrantType . AUTHORIZATION_CODE ) . setClientId ( clientId ) . setClientSecret ( clientSecret ) . setRedirectURI ( redirectUri ) . setCode ( authCode ) . buildQueryMessage ( ) ; } | Build an OAuth access token request . |
7,816 | public final boolean hasAnnotation ( final String name ) { if ( name == null ) { throw new IllegalArgumentException ( "The argument 'name' cannot be NULL!" ) ; } for ( int i = 0 ; i < annotations . size ( ) ; i ++ ) { final SgAnnotation annotation = annotations . get ( i ) ; if ( annotation . getName ( ) . equals ( name ) ) { return true ; } } return false ; } | Checks if a given annotation is in the list . |
7,817 | public boolean accept ( ClassInfo classInfo , ClassHierarchyResolver hierarchyResolver ) { return pattern . matcher ( classInfo . getClassName ( ) ) . find ( ) ; } | Determine whether a class name is to be accepted or not based on the regular expression specified to the constructor . |
7,818 | public PropertyManager < T > getPropertyManager ( T property ) { PropertyManager < T > propertyManager = propertyManagerCache . get ( property ) ; if ( propertyManager == null ) { PropertyManager < T > newPropertyManager = new PropertyManager < T > ( property , this ) ; propertyManager = propertyManagerCache . putIfAbsent ( property , newPropertyManager ) ; if ( propertyManager == null ) { propertyManager = newPropertyManager ; } } return propertyManager ; } | Get an object that will encapsulate the functionality of this manager specific to a single property . This makes it easier to watch modify and generally interact with a single property . |
7,819 | public int getIntegerPropertyFallback ( T property ) throws NumberFormatException { try { return getIntegerProperty ( property ) ; } catch ( NumberFormatException e ) { return Integer . parseInt ( getDefaultProperty ( property ) ) ; } } | Retrieve the value of the given property as an integer . If the current value of the specified property cannot be converted to an integer the default value will be retrieved . |
7,820 | public long getLongPropertyFallback ( T property ) throws NumberFormatException { try { return getLongProperty ( property ) ; } catch ( NumberFormatException e ) { return Long . parseLong ( getDefaultProperty ( property ) ) ; } } | Retrieve the value of the given property as a long . If the current value of the specified property cannot be converted to a long the default value will be retrieved . |
7,821 | public float getFloatPropertyFallback ( T property ) throws NumberFormatException { try { return getFloatProperty ( property ) ; } catch ( NumberFormatException e ) { return Float . parseFloat ( getDefaultProperty ( property ) ) ; } } | Retrieve the value of the given property as a float . If the current value of the specified property cannot be converted to a float the default value will be retrieved . |
7,822 | public double getDoublePropertyFallback ( T property ) throws NumberFormatException { try { return Double . parseDouble ( getProperty ( property ) ) ; } catch ( NumberFormatException e ) { return Double . parseDouble ( getDefaultProperty ( property ) ) ; } } | Retrieve the value of the given property as a double . If the current value of the specified property cannot be converted to a double the default value will be retrieved . |
7,823 | public boolean isReferencing ( T property1 , T property2 ) { return getEvaluator ( ) . isReferencing ( getRawProperty ( property1 ) , getTranslator ( ) . getPropertyName ( property2 ) , getRetriever ( ) ) ; } | Determine whether or not one property holds references to another property . |
7,824 | public void setProperty ( T property , Object value ) throws IllegalArgumentException { if ( value == null ) { throw new IllegalArgumentException ( "Cannot set a null value, use reset instead" ) ; } setProperty ( property , value . toString ( ) ) ; } | Set the given property using an object s string representation . This will not write the new value to the file system . |
7,825 | public void setProperty ( T property , String value ) throws IllegalArgumentException { if ( value == null ) { throw new IllegalArgumentException ( "Cannot set a null value, use reset instead" ) ; } String propertyName = getTranslator ( ) . getPropertyName ( property ) ; if ( properties . setProperty ( propertyName , value ) ) { firePropertyChanged ( property ) ; } } | Set the given property using a string . This will not write the new value to the file system . |
7,826 | public void resetProperty ( T property ) { String propertyName = getTranslator ( ) . getPropertyName ( property ) ; if ( properties . resetToDefault ( propertyName ) ) { firePropertyReset ( property ) ; } } | Reset the given property to its default value . This will not write the new value to the file system . |
7,827 | private void firePropertyLoaded ( T property ) { PropertyEvent < T > event = null ; for ( PropertyListener < T > l : listeners ) { if ( event == null ) { event = new PropertyEvent < T > ( this , property ) ; } l . loaded ( event ) ; } } | Notify all listeners that a property has been loaded . |
7,828 | private void firePropertySaved ( T property ) { PropertyEvent < T > event = null ; for ( PropertyListener < T > l : listeners ) { if ( event == null ) { event = new PropertyEvent < T > ( this , property ) ; } l . saved ( event ) ; } } | Notify all listeners that a property has been saved . |
7,829 | private void firePropertyChanged ( T property ) { PropertyEvent < T > event = null ; for ( PropertyListener < T > l : listeners ) { if ( event == null ) { event = new PropertyEvent < T > ( this , property ) ; } l . changed ( event ) ; } } | Notify all listeners that a property has changed . |
7,830 | private void firePropertyReset ( T property ) { PropertyEvent < T > event = null ; for ( PropertyListener < T > l : listeners ) { if ( event == null ) { event = new PropertyEvent < T > ( this , property ) ; } l . reset ( event ) ; } } | Notify all listeners that a property has been reset . |
7,831 | public synchronized Map < String , String > getVariableMetaDataByReference ( int variableIndex ) { while ( variableIndex >= variableMetaData . size ( ) ) { variableMetaData . add ( new HashMap < > ( ) ) ; } return variableMetaData . get ( variableIndex ) ; } | Gets the metadata for a variable . Creates blank metadata if does not exists then returns that . Pass by reference . |
7,832 | public StaticFactor addStaticFactor ( int [ ] neighborIndices , int [ ] neighborDimensions , Function < int [ ] , Double > assignmentFeaturizer ) { NDArrayDoubles doubleArray = new NDArrayDoubles ( neighborDimensions ) ; for ( int [ ] assignment : doubleArray ) { doubleArray . setAssignmentValue ( assignment , assignmentFeaturizer . apply ( assignment ) ) ; } return addStaticFactor ( doubleArray , neighborIndices ) ; } | This adds a static factor to the model which will always produce the same value regardless of the assignment of weights during inference . |
7,833 | public Factor addBinaryFactor ( int a , int b , BiFunction < Integer , Integer , ConcatVector > featurizer ) { int [ ] variableDims = getVariableSizes ( ) ; assert a < variableDims . length ; assert b < variableDims . length ; return addFactor ( new int [ ] { a , b } , new int [ ] { variableDims [ a ] , variableDims [ b ] } , assignment -> featurizer . apply ( assignment [ 0 ] , assignment [ 1 ] ) ) ; } | A simple helper function for defining a binary factor . That is a factor between two variables in the graphical model . |
7,834 | public Factor addBinaryFactor ( int a , int cardA , int b , int cardB , BiFunction < Integer , Integer , ConcatVector > featurizer ) { return addFactor ( new int [ ] { a , b } , new int [ ] { cardA , cardB } , assignment -> featurizer . apply ( assignment [ 0 ] , assignment [ 1 ] ) ) ; } | Add a binary factor with known dimensions for the variables |
7,835 | public void setTrainingLabel ( int variable , int value ) { getVariableMetaDataByReference ( variable ) . put ( LogLikelihoodDifferentiableFunction . VARIABLE_TRAINING_VALUE , Integer . toString ( value ) ) ; } | Set a training value for this variable in the graphical model . |
7,836 | public void observe ( int variable , int value ) { getVariableMetaDataByReference ( variable ) . put ( CliqueTree . VARIABLE_OBSERVED_VALUE , Integer . toString ( value ) ) ; } | Observe a given variable setting it to a given value . |
7,837 | public int numVariables ( ) { int maxVar = 0 ; for ( Factor f : factors ) { for ( int n : f . neigborIndices ) { if ( n > maxVar ) maxVar = n ; } } return maxVar + 1 ; } | The number of variables in this graphical model . |
7,838 | public static GraphicalModel readFromStream ( InputStream stream ) throws IOException { return readFromProto ( GraphicalModelProto . GraphicalModel . parseDelimitedFrom ( stream ) ) ; } | Static function to deserialize a graphical model from an input stream . |
7,839 | public static GraphicalModel readFromProto ( GraphicalModelProto . GraphicalModel proto ) { if ( proto == null ) return null ; GraphicalModel model = new GraphicalModel ( ) ; model . modelMetaData = readMetaDataFromProto ( proto . getMetaData ( ) ) ; model . variableMetaData = new ArrayList < > ( ) ; for ( int i = 0 ; i < proto . getVariableMetaDataCount ( ) ; i ++ ) { model . variableMetaData . add ( readMetaDataFromProto ( proto . getVariableMetaData ( i ) ) ) ; } for ( int i = 0 ; i < proto . getFactorCount ( ) ; i ++ ) { model . factors . add ( Factor . readFromProto ( proto . getFactor ( i ) ) ) ; } return model ; } | Recreates an in - memory GraphicalModel from a proto serialization recursively creating all the ConcatVectorTable s and ConcatVector s in memory as well . |
7,840 | public boolean valueEquals ( GraphicalModel other , double tolerance ) { if ( ! modelMetaData . equals ( other . modelMetaData ) ) { return false ; } if ( ! variableMetaData . equals ( other . variableMetaData ) ) { return false ; } Set < Factor > remaining = new HashSet < > ( ) ; remaining . addAll ( factors ) ; for ( Factor otherFactor : other . factors ) { Factor match = null ; for ( Factor factor : remaining ) { if ( factor . valueEquals ( otherFactor , tolerance ) ) { match = factor ; break ; } } if ( match == null ) return false ; else remaining . remove ( match ) ; } return remaining . size ( ) <= 0 ; } | Check that two models are deeply value - equivalent down to the concat vectors inside the factor tables within some tolerance . Mostly useful for testing . |
7,841 | public GraphicalModel cloneModel ( ) { GraphicalModel clone = new GraphicalModel ( ) ; clone . modelMetaData . putAll ( modelMetaData ) ; for ( int i = 0 ; i < variableMetaData . size ( ) ; i ++ ) { if ( variableMetaData . get ( i ) != null ) { clone . getVariableMetaDataByReference ( i ) . putAll ( variableMetaData . get ( i ) ) ; } } for ( Factor f : factors ) { clone . factors . add ( f . cloneFactor ( ) ) ; } return clone ; } | The point here is to allow us to save a copy of the model with a current set of factors and metadata mappings which can come in super handy with gameplaying applications . The cloned model doesn t instantiate the feature thunks inside factors those are just taken over individually . |
7,842 | public void close ( ) { sessionsByKeyspace . entrySet ( ) . forEach ( session -> session . getValue ( ) . close ( ) ) ; cluster . close ( ) ; } | Initiate close cluster and session operations |
7,843 | public static MockClassLoader getInstance ( ) { if ( MockClassLoader . instance == null ) { MockClassLoader . instance = new MockClassLoader ( ) ; } return MockClassLoader . instance ; } | Access an instance of our class loader . |
7,844 | public boolean shutdownService ( Object service , BundleContext context ) { if ( this . service != null ) ( ( HttpServiceTracker ) this . service ) . close ( ) ; return true ; } | Shutdown this service . Override this to do all the startup . |
7,845 | public HttpServiceTracker createServiceTracker ( BundleContext context , HttpContext httpContext , Dictionary < String , String > dictionary ) { if ( httpContext == null ) httpContext = getHttpContext ( ) ; return new HttpServiceTracker ( context , httpContext , dictionary ) ; } | Create the service tracker . |
7,846 | public String getWebAlias ( ) { String contextPath = context . getProperty ( BaseWebappServlet . ALIAS ) ; if ( contextPath == null ) contextPath = context . getProperty ( BaseWebappServlet . ALIAS . substring ( BaseWebappServlet . PROPERTY_PREFIX . length ( ) ) ) ; if ( contextPath == null ) contextPath = this . getProperty ( BaseWebappServlet . ALIAS ) ; if ( contextPath == null ) contextPath = this . getProperty ( BaseWebappServlet . ALIAS . substring ( BaseWebappServlet . PROPERTY_PREFIX . length ( ) ) ) ; if ( contextPath == null ) { contextPath = this . getServicePid ( ) ; if ( contextPath . lastIndexOf ( '.' ) != - 1 ) contextPath = contextPath . substring ( contextPath . lastIndexOf ( '.' ) + 1 ) ; } if ( ! contextPath . startsWith ( "/" ) ) contextPath = "/" + contextPath ; return contextPath ; } | Get the web alias for this servlet . |
7,847 | public static HttpServiceTracker getServiceTracker ( BundleContext context , String key , String value ) { String filter = "(" + key + "=" + value + ")" ; try { ServiceReference [ ] references = context . getServiceReferences ( ServiceTracker . class . getName ( ) , filter ) ; if ( ( references == null ) || ( references . length == 0 ) ) references = context . getServiceReferences ( ServiceTracker . class . getName ( ) , null ) ; if ( references != null ) { for ( ServiceReference reference : references ) { Object service = context . getService ( reference ) ; if ( service instanceof HttpServiceTracker ) if ( value . equals ( ( ( HttpServiceTracker ) service ) . getProperty ( key ) ) ) return ( HttpServiceTracker ) service ; } } } catch ( InvalidSyntaxException e ) { e . printStackTrace ( ) ; } return null ; } | Get this service tracker . |
7,848 | private CtClass createCtClass ( final SgClass modelClass ) throws NotFoundException , CannotCompileException { final CtClass clasz = pool . makeClass ( modelClass . getName ( ) ) ; clasz . setModifiers ( SgUtils . toModifiers ( modelClass . getModifiers ( ) ) ) ; if ( modelClass . getSuperClass ( ) != null ) { clasz . setSuperclass ( pool . get ( modelClass . getSuperClass ( ) . getName ( ) ) ) ; } addInterfaces ( modelClass , clasz ) ; addFields ( modelClass , clasz ) ; addConstructors ( modelClass , clasz ) ; addMethods ( modelClass , clasz ) ; return clasz ; } | Creates a Javassist class from a given model class . |
7,849 | public static ByteCodeGenerator createWithCurrentThreadContextClassLoader ( ) { final ClassPool pool = ClassPool . getDefault ( ) ; final ClassLoader classLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; pool . appendClassPath ( new LoaderClassPath ( classLoader ) ) ; return new ByteCodeGenerator ( pool , classLoader ) ; } | Creates a generator initialized with default class pool and the context class loader of the current thread . |
7,850 | public static CacheEngine get ( String name ) { if ( ! engines . containsKey ( name ) ) { throw new IllegalArgumentException ( name + " is not a valid cache engine name." ) ; } return engines . get ( name ) ; } | Gets the cache engine associated with the given name |
7,851 | public void changeAlpha ( int alpha ) { alpha = alpha > 255 ? 255 : alpha < 0 ? 0 : alpha ; Color foreground = getForeground ( ) ; int red = foreground . getRed ( ) ; int green = foreground . getGreen ( ) ; int blue = foreground . getBlue ( ) ; Color withAlpha = new Color ( red , green , blue , alpha ) ; super . setForeground ( withAlpha ) ; } | Convenience method to applyChanges the alpha value of the current foreground Color to the specifice value . |
7,852 | private void checkForPrompt ( ) { if ( document . getLength ( ) > 0 ) { setVisible ( false ) ; return ; } if ( showPromptOnce && focusLost > 0 ) { setVisible ( false ) ; return ; } if ( component . hasFocus ( ) ) { if ( show == Show . ALWAYS || show == Show . FOCUS_GAINED ) setVisible ( true ) ; else setVisible ( false ) ; } else { if ( show == Show . ALWAYS || show == Show . FOCUS_LOST ) setVisible ( true ) ; else setVisible ( false ) ; } } | Check whether the prompt should be visible or not . The visibility will applyChanges on updates to the Document and on focus changes . |
7,853 | public Trie < V > trimToSize ( ) { Queue < TrieNode < V > > queue = new LinkedList < > ( ) ; queue . add ( root ) ; while ( ! queue . isEmpty ( ) ) { TrieNode < V > node = queue . remove ( ) ; node . children . trimToSize ( ) ; queue . addAll ( node . children ) ; } return this ; } | Compresses the memory of the individual trie nodes . |
7,854 | protected Thread createThread ( final Runnable runnable , final String name ) { return new Thread ( runnable , Thread . currentThread ( ) . getName ( ) + "-exec" ) ; } | Factory method to create a thread waiting for the result of an asynchronous execution . |
7,855 | public void forEach ( Consumer < ? super List < String > > consumer ) { try ( Stream < List < String > > stream = stream ( ) ) { stream . forEach ( consumer ) ; } } | Convenience method for consuming all rows in the CSV file |
7,856 | public List < String > getHeader ( ) { if ( header == null ) { return Collections . emptyList ( ) ; } return Collections . unmodifiableList ( header ) ; } | Gets the header read in from the csv file or specified via the CSV specification . |
7,857 | public List < String > nextRow ( ) throws IOException { row = new ArrayList < > ( ) ; STATE = START ; int c ; int readCount = 0 ; gobbleWhiteSpace ( ) ; while ( ( c = read ( ) ) != - 1 ) { if ( c == '\r' ) { if ( bufferPeek ( ) == '\n' ) { continue ; } else { c = '\n' ; } } readCount ++ ; switch ( STATE ) { case START : STATE = beginOfLine ( c ) ; break ; case IN_QUOTE : wasQuoted = true ; STATE = inField ( c , true ) ; break ; case IN_FIELD : STATE = inField ( c , false ) ; break ; case OUT_QUOTE : STATE = outQuote ( c ) ; break ; default : throw new IOException ( "State [" + STATE + "]" ) ; } if ( STATE == END_OF_ROW ) { break ; } } if ( readCount > 0 ) { addCell ( wasQuoted ) ; } if ( row . isEmpty ( ) ) { return null ; } return new ArrayList < > ( row ) ; } | Reads the next row from the CSV file retuning null if there are not anymore |
7,858 | public Stream < List < String > > stream ( ) { return Streams . asStream ( new RowIterator ( ) ) . onClose ( Unchecked . runnable ( this :: close ) ) ; } | Creates a new stream over the rows in the file that will close underlying reader on stream close . |
7,859 | public static RealMatrix readMatrix ( Reader reader ) throws IOException { List < double [ ] > retval = new ArrayList < > ( ) ; Iterable < CSVRecord > records = CSVFormat . EXCEL . parse ( reader ) ; for ( CSVRecord record : records ) { double [ ] row = new double [ record . size ( ) ] ; for ( int i = 0 ; i < record . size ( ) ; i ++ ) { row [ i ] = Double . parseDouble ( record . get ( i ) ) ; } retval . add ( row ) ; } double [ ] [ ] retvalArray = new double [ retval . size ( ) ] [ ] ; retval . toArray ( retvalArray ) ; return MatrixUtils . createRealMatrix ( retvalArray ) ; } | Reads a matrix of double values from the reader provided . |
7,860 | protected static KLU_symbolic klu_alloc_symbolic ( int n , int [ ] Ap , int [ ] Ai , KLU_common Common ) { KLU_symbolic Symbolic ; int [ ] P , Q , R ; double [ ] Lnz ; int nz , i , j , p , pend ; if ( Common == null ) { return ( null ) ; } Common . status = KLU_OK ; if ( n <= 0 || Ap == null || Ai == null ) { Common . status = KLU_INVALID ; return ( null ) ; } nz = Ap [ n ] ; if ( Ap [ 0 ] != 0 || nz < 0 ) { Common . status = KLU_INVALID ; return ( null ) ; } for ( j = 0 ; j < n ; j ++ ) { if ( Ap [ j ] > Ap [ j + 1 ] ) { Common . status = KLU_INVALID ; return ( null ) ; } } P = klu_malloc_int ( n , Common ) ; if ( Common . status < KLU_OK ) { Common . status = KLU_OUT_OF_MEMORY ; return ( null ) ; } for ( i = 0 ; i < n ; i ++ ) { P [ i ] = EMPTY ; } for ( j = 0 ; j < n ; j ++ ) { pend = Ap [ j + 1 ] ; for ( p = Ap [ j ] ; p < pend ; p ++ ) { i = Ai [ p ] ; if ( i < 0 || i >= n || P [ i ] == j ) { P = null ; Common . status = KLU_INVALID ; return ( null ) ; } P [ i ] = j ; } } try { Symbolic = new KLU_symbolic ( ) ; } catch ( OutOfMemoryError e ) { P = null ; Common . status = KLU_OUT_OF_MEMORY ; return ( null ) ; } Q = klu_malloc_int ( n , Common ) ; R = klu_malloc_int ( n + 1 , Common ) ; Lnz = klu_malloc_dbl ( n , Common ) ; Symbolic . n = n ; Symbolic . nz = nz ; Symbolic . P = P ; Symbolic . Q = Q ; Symbolic . R = R ; Symbolic . Lnz = Lnz ; if ( Common . status < KLU_OK ) { Symbolic = null ; Common . status = KLU_OUT_OF_MEMORY ; return ( null ) ; } return ( Symbolic ) ; } | Allocate Symbolic object and check input matrix . Not user callable . |
7,861 | public void connectToLink ( Link link ) throws ShanksException { if ( ! this . linksList . contains ( link ) ) { this . linksList . add ( link ) ; logger . finer ( "Device " + this . getID ( ) + " is now connected to Link " + link . getID ( ) ) ; link . connectDevice ( this ) ; } } | Connect the device to a link |
7,862 | public void disconnectFromLink ( Link link ) { boolean disconnected = this . linksList . remove ( link ) ; if ( disconnected ) { link . disconnectDevice ( this ) ; logger . fine ( "Device " + this . getID ( ) + " is now disconnected from Link " + link . getID ( ) ) ; } else { logger . warning ( "Device " + this . getID ( ) + " could not be disconnected from Link " + link . getID ( ) + ", because it was not connected." ) ; } } | Disconnect the device From a link |
7,863 | public void connectToDeviceWithLink ( Device device , Link link ) throws ShanksException { this . connectToLink ( link ) ; try { device . connectToLink ( link ) ; } catch ( ShanksException e ) { this . disconnectFromLink ( link ) ; throw e ; } } | Connect the device to other device with a link |
7,864 | public static List < Resource > getClasspathResources ( ) { synchronized ( classpathResources ) { if ( classpathResources . isEmpty ( ) ) { for ( String jar : SystemInfo . JAVA_CLASS_PATH . split ( SystemInfo . PATH_SEPARATOR ) ) { File file = new File ( jar ) ; if ( file . isDirectory ( ) ) { classpathResources . addAll ( new FileResource ( file ) . getChildren ( true ) ) ; } else { classpathResources . addAll ( getJarContents ( Resources . fromFile ( jar ) , v -> true ) ) ; } } } return Collections . unmodifiableList ( classpathResources ) ; } } | Gets classpath resources . |
7,865 | private void initializeApplicationContext ( JobExecutionContext jobExecutionContext ) throws JobExecutionException { try { this . applicationContext = ( ApplicationContext ) jobExecutionContext . getScheduler ( ) . getContext ( ) . get ( "applicationContext" ) ; if ( this . applicationContext == null ) { throw new JobExecutionException ( "No application context available in scheduler context for key \"applicationContext\"" ) ; } } catch ( SchedulerException e ) { getLogger ( ) . error ( "Error extracting Spring application context from SchedulerContext" , e ) ; throw new JobExecutionException ( "Error fetching application context available in scheduler context for key \"applicationContext\"" ) ; } } | Initialize Spring Application Context from Quartz SchedulerContext . |
7,866 | public static < A , B , C , D > Tuple4 < A , B , C , D > of ( A a , B b , C c , D d ) { return new Tuple4 < > ( a , b , c , d ) ; } | Of tuple 4 . |
7,867 | static void registerDiscoveryClient ( UUID injectorId , ReadOnlyDiscoveryClient discoveryClient , DiscoveryJmsConfig config ) { DISCO_CLIENTS . put ( injectorId , discoveryClient ) ; CONFIGS . put ( injectorId , config ) ; LOG . info ( "Registered discovery client %s as %s" , injectorId , discoveryClient ) ; } | Register a discoveryClient under a unique id . This works around the TransportFactory s inherent staticness so that we may use the correct discovery client even in the presence of multiple injectors in the same JVM . |
7,868 | @ SuppressWarnings ( "PMD.PreserveStackTrace" ) private Map < String , String > findParameters ( URI location ) throws MalformedURLException { final Map < String , String > params ; try { params = URISupport . parseParameters ( location ) ; } catch ( final URISyntaxException e ) { throw new MalformedURLException ( e . getMessage ( ) ) ; } return params ; } | Extract the query string from a connection URI into a Map |
7,869 | private UUID getDiscoveryId ( final Map < String , String > params ) throws IOException { final String discoveryId = params . get ( "discoveryId" ) ; if ( discoveryId == null ) { throw new IOException ( "srvc transport did not get a discoveryId parameter. Refusing to create." ) ; } return UUID . fromString ( discoveryId ) ; } | Find and validate the discoveryId given in a connection string |
7,870 | private ReadOnlyDiscoveryClient getDiscoveryClient ( Map < String , String > params ) throws IOException { final UUID discoveryId = getDiscoveryId ( params ) ; final ReadOnlyDiscoveryClient discoveryClient = DISCO_CLIENTS . get ( discoveryId ) ; if ( discoveryClient == null ) { throw new IOException ( "No discovery client registered for id " + discoveryId ) ; } return discoveryClient ; } | Locate the appropriate DiscoveryClient for a given discoveryId |
7,871 | private List < ServiceInformation > getServiceInformations ( URI location , final Map < String , String > params ) throws IOException { final ReadOnlyDiscoveryClient discoveryClient = getDiscoveryClient ( params ) ; final String serviceType = params . get ( "serviceType" ) ; final List < ServiceInformation > services ; if ( serviceType != null ) { services = discoveryClient . findAllServiceInformation ( location . getHost ( ) , serviceType ) ; } else { services = discoveryClient . findAllServiceInformation ( location . getHost ( ) ) ; } return services ; } | Find and return applicable services for a given connection |
7,872 | private Transport buildTransport ( Map < String , String > params , final List < ServiceInformation > services ) throws IOException { final String configPostfix = getConfig ( params ) . getServiceConfigurationPostfix ( ) ; final StringBuilder uriBuilder = new StringBuilder ( ) ; uriBuilder . append ( "failover:(" ) ; uriBuilder . append ( Joiner . on ( ',' ) . join ( Collections2 . transform ( services , SERVICE_TO_URI ) ) ) ; uriBuilder . append ( ')' ) ; if ( ! StringUtils . isBlank ( configPostfix ) ) { uriBuilder . append ( '?' ) ; uriBuilder . append ( configPostfix ) ; } try { final URI uri = URI . create ( uriBuilder . toString ( ) ) ; LOG . debug ( "Service discovery transport discovered %s" , uri ) ; return interceptPropertySetters ( TransportFactory . compositeConnect ( uri ) ) ; } catch ( final Exception e ) { Throwables . propagateIfPossible ( e , IOException . class ) ; throw new IOException ( "Could not create failover transport" , e ) ; } } | From a list of ServiceInformation build a failover transport that balances between the brokers . |
7,873 | private Transport interceptPropertySetters ( Transport transport ) { final Enhancer e = new Enhancer ( ) ; e . setInterfaces ( new Class < ? > [ ] { Transport . class , ServiceTransportBeanSetters . class } ) ; final TransportDelegationFilter filter = new TransportDelegationFilter ( transport , ServiceTransportBeanSetters . class ) ; e . setCallbackFilter ( filter ) ; e . setCallbacks ( filter . getCallbacks ( ) ) ; return ( Transport ) e . create ( ) ; } | ActiveMQ expects to reflectively call setX for every property x specified in the connection string . Since we are actually constructing a failover transport these properties are obviously not expected and ActiveMQ complains that we are specifying invalid parameters . So create a CGLIB proxy that intercepts and ignores appropriate setter calls . |
7,874 | public String beginArray ( ) throws IOException { String name = null ; if ( currentValue . getKey ( ) == NAME ) { name = currentValue . getValue ( ) . asString ( ) ; consume ( ) ; } if ( currentValue . getKey ( ) == BEGIN_ARRAY ) { consume ( ) ; } else if ( readStack . peek ( ) != BEGIN_ARRAY ) { throw new IOException ( "Expecting BEGIN_ARRAY, but found " + jsonTokenToStructuredElement ( null ) ) ; } return name ; } | Begins an Array |
7,875 | public JsonReader beginArray ( String expectedName ) throws IOException { String name = beginArray ( ) ; if ( ! StringUtils . isNullOrBlank ( expectedName ) && ( name == null || ! name . equals ( expectedName ) ) ) { throw new IOException ( "Expected " + expectedName ) ; } return this ; } | Begins an array with an expected name . |
7,876 | public JsonReader beginObject ( String expectedName ) throws IOException { String name = beginObject ( ) ; if ( ! StringUtils . isNullOrBlank ( expectedName ) && ! name . equals ( expectedName ) ) { throw new IOException ( "Expected " + expectedName ) ; } return this ; } | Begins an object with an expected name . |
7,877 | public JsonReader endArray ( ) throws IOException { if ( currentValue . getKey ( ) != END_ARRAY ) { throw new IOException ( "Expecting END_ARRAY, but found " + jsonTokenToStructuredElement ( null ) ) ; } consume ( ) ; return this ; } | Ends an Array |
7,878 | public JsonReader endObject ( ) throws IOException { if ( currentValue . getKey ( ) != END_OBJECT ) { throw new IOException ( "Expecting END_OBJECT, but found " + jsonTokenToStructuredElement ( null ) ) ; } consume ( ) ; return this ; } | Ends the document |
7,879 | public Tuple2 < String , Val > nextKeyValue ( ) throws IOException { if ( currentValue . getKey ( ) != NAME ) { throw new IOException ( "Expecting NAME, but found " + jsonTokenToStructuredElement ( null ) ) ; } String name = currentValue . getValue ( ) . asString ( ) ; consume ( ) ; return Tuple2 . of ( name , nextValue ( ) ) ; } | Reads the next key - value pair |
7,880 | public Val nextKeyValue ( String expectedKey ) throws IOException { Tuple2 < String , Val > Tuple2 = nextKeyValue ( ) ; if ( expectedKey != null && ( Tuple2 == null || ! Tuple2 . getKey ( ) . equals ( expectedKey ) ) ) { throw new IOException ( "Expected a Key-Value Tuple2 with named " + expectedKey ) ; } return Tuple2 . getV2 ( ) ; } | Reads in a key value with an expected key . |
7,881 | public < T > Tuple2 < String , T > nextKeyValue ( Class < T > clazz ) throws IOException { if ( currentValue . getKey ( ) != NAME ) { throw new IOException ( "Expecting NAME, but found " + jsonTokenToStructuredElement ( null ) ) ; } String name = currentValue . getValue ( ) . asString ( ) ; consume ( ) ; return Tuple2 . of ( name , nextValue ( clazz ) ) ; } | Reads the next key - value pair with the value being of the given type |
7,882 | public Map < String , Val > nextMap ( String expectedName ) throws IOException { boolean ignoreObject = peek ( ) != JsonTokenType . BEGIN_OBJECT && StringUtils . isNullOrBlank ( expectedName ) ; if ( ! ignoreObject ) beginObject ( expectedName ) ; Map < String , Val > map = new HashMap < > ( ) ; while ( peek ( ) != JsonTokenType . END_OBJECT && peek ( ) != JsonTokenType . END_DOCUMENT ) { Tuple2 < String , Val > kv = nextKeyValue ( ) ; map . put ( kv . getKey ( ) , kv . getValue ( ) ) ; } if ( ! ignoreObject ) endObject ( ) ; return map ; } | Reads in the next object as a map with an expected name |
7,883 | protected Val nextSimpleValue ( ) throws IOException { switch ( currentValue . getKey ( ) ) { case NULL : case STRING : case BOOLEAN : case NUMBER : Val object = currentValue . v2 ; consume ( ) ; return object ; default : throw new IOException ( "Expecting VALUE, but found " + jsonTokenToStructuredElement ( null ) ) ; } } | Next simple value val . |
7,884 | public Val nextValue ( ) throws IOException { switch ( peek ( ) ) { case BEGIN_ARRAY : return Val . of ( nextCollection ( ArrayList :: new ) ) ; case BEGIN_OBJECT : return Val . of ( nextMap ( ) ) ; case NAME : return nextKeyValue ( ) . getV2 ( ) ; default : return nextSimpleValue ( ) ; } } | Reads the next value |
7,885 | protected < T > T readReadable ( Class < T > clazz ) throws IOException { try { T object = Reflect . onClass ( clazz ) . allowPrivilegedAccess ( ) . create ( ) . get ( ) ; JsonSerializable readable = Cast . as ( object ) ; boolean isArray = JsonArraySerializable . class . isAssignableFrom ( clazz ) ; if ( isArray && peek ( ) == JsonTokenType . BEGIN_ARRAY ) { beginArray ( ) ; } else if ( peek ( ) == JsonTokenType . BEGIN_OBJECT ) { beginObject ( ) ; } readable . fromJson ( this ) ; if ( isArray && peek ( ) == JsonTokenType . END_ARRAY ) { endArray ( ) ; } else if ( peek ( ) == JsonTokenType . END_OBJECT ) { endObject ( ) ; } return object ; } catch ( ReflectionException e ) { throw new IOException ( e ) ; } } | Reads a class implementing readable |
7,886 | public JsonTokenType skip ( ) throws IOException { try { JsonTokenType element = jsonTokenToStructuredElement ( reader . peek ( ) ) ; JsonToken token = currentValue . getKey ( ) ; if ( token == NAME && ( element == JsonTokenType . BEGIN_OBJECT || element == JsonTokenType . BEGIN_ARRAY ) ) { reader . skipValue ( ) ; } consume ( ) ; return element ; } catch ( IOException e ) { throw new IOException ( e ) ; } } | Skips the next element in the stream |
7,887 | public JarScanner addJar ( Collection < URL > jars ) { this . jars . addAll ( jars . stream ( ) . map ( JarScanner :: toUri ) . collect ( Collectors . toList ( ) ) ) ; return this ; } | Adds a jar file to be scanned |
7,888 | private static URI toUri ( final URL u ) { try { return u . toURI ( ) ; } catch ( URISyntaxException e ) { throw new IllegalArgumentException ( "Could not convert URL " + u + " to uri" , e ) ; } } | Converts a url to uri without throwing a checked exception . In case an URI syntax exception occurs an IllegalArgumentException is thrown . |
7,889 | private Collection < String > scanJar ( Predicate < Path > pathFilter ) { return jars . parallelStream ( ) . map ( JarScanner :: createJarUri ) . flatMap ( u -> scanJar ( u , pathFilter ) . stream ( ) ) . distinct ( ) . collect ( Collectors . toList ( ) ) ; } | Scans the jars of the JarScanner finding all items matching the path filter |
7,890 | private Collection < String > scanJar ( URI u , Predicate < Path > pathPredicate ) { try ( FileSystem fs = FileSystems . newFileSystem ( u , READY_ONLY_ENV ) ) { return Files . walk ( fs . getPath ( "/" ) ) . filter ( pathPredicate ) . map ( f -> toFQName ( f . toAbsolutePath ( ) ) ) . distinct ( ) . collect ( Collectors . toList ( ) ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } | Scans the jar and filters all elements |
7,891 | private boolean isIgnored ( Path p ) { final String path = toFQName ( p ) ; return this . ignoredFolders . stream ( ) . anyMatch ( path :: startsWith ) ; } | Checks if the specified path is on the ignore list |
7,892 | protected OutputStream createOutputStream ( ) throws IOException { if ( asFile ( ) . isPresent ( ) ) { return new FileOutputStream ( asFile ( ) . orElse ( null ) ) ; } return null ; } | Create output stream output stream . |
7,893 | protected InputStream createInputStream ( ) throws IOException { if ( asFile ( ) . isPresent ( ) ) { return new FileInputStream ( asFile ( ) . orElse ( null ) ) ; } return null ; } | Create input stream input stream . |
7,894 | public static String uppercaseToUnderscore ( final String str ) { if ( str == null ) { return null ; } final StringBuffer sb = new StringBuffer ( ) ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { final char ch = str . charAt ( i ) ; if ( Character . isUpperCase ( ch ) ) { if ( i > 0 ) { sb . append ( "_" ) ; } sb . append ( Character . toLowerCase ( ch ) ) ; } else { sb . append ( ch ) ; } } return sb . toString ( ) ; } | Inserts an underscore before every upper case character and returns an all lower case string . If the first character is upper case an underscore will not be inserted . |
7,895 | public static String concatPackages ( final String package1 , final String package2 ) { if ( ( package1 == null ) || ( package1 . length ( ) == 0 ) ) { if ( ( package2 == null ) || ( package2 . length ( ) == 0 ) ) { return "" ; } else { return package2 ; } } else { if ( ( package2 == null ) || ( package2 . length ( ) == 0 ) ) { return package1 ; } else { return package1 + "." + package2 ; } } } | Merge two packages into one . If any package is null or empty no . will be added . If both packages are null an empty string will be returned . |
7,896 | public static String modifierMatrixToHtml ( ) { final StringBuffer sb = new StringBuffer ( ) ; sb . append ( "<table border=\"1\">\n" ) ; sb . append ( "<tr>" ) ; sb . append ( "<th> </th>" ) ; for ( int type = FIELD ; type <= INNER_INTERFACE ; type ++ ) { sb . append ( "<th>" ) ; sb . append ( TYPE_NAMES [ type ] ) ; sb . append ( "</th>" ) ; } sb . append ( "</tr>\n" ) ; for ( int modifier = ABSTRACT ; modifier <= STRICTFP ; modifier ++ ) { sb . append ( "<tr>" ) ; sb . append ( "<td>" ) ; sb . append ( MODIFIER_NAMES [ modifier ] ) ; sb . append ( "</td>" ) ; for ( int type = FIELD ; type <= INNER_INTERFACE ; type ++ ) { sb . append ( "<td>" ) ; sb . append ( MODIFIERS_MATRIX [ modifier ] [ type ] ) ; sb . append ( "</td>" ) ; } sb . append ( "</tr>\n" ) ; } sb . append ( "</table>\n" ) ; return sb . toString ( ) ; } | Create a simple HTML table for the modifier matrix . This is helpful to check if the matrix is valid . |
7,897 | public static int toModifiers ( final String modifiers ) { if ( modifiers == null ) { return 0 ; } final String trimmedModifiers = modifiers . trim ( ) ; int modifier = 0 ; final StringTokenizer tok = new StringTokenizer ( trimmedModifiers , " " ) ; while ( tok . hasMoreTokens ( ) ) { final String mod = tok . nextToken ( ) ; modifier = modifier | modifierValueForName ( mod ) ; } return modifier ; } | Returns a Java Modifier value for a list of modifier names . |
7,898 | public static List < SgAnnotation > createAnnotations ( final Annotation [ ] ann ) { final List < SgAnnotation > list = new ArrayList < SgAnnotation > ( ) ; if ( ( ann != null ) && ( ann . length > 0 ) ) { for ( int i = 0 ; i < ann . length ; i ++ ) { final SgAnnotation annotation = new SgAnnotation ( ann [ i ] . annotationType ( ) . getPackage ( ) . getName ( ) , ann [ i ] . annotationType ( ) . getSimpleName ( ) ) ; list . add ( annotation ) ; } } return list ; } | Create a list of annotations . |
7,899 | public void open ( ) { try { if ( this . isOpened ( ) == false ) { System . out . println ( formatVersionInfo ( ) + " Opening ..." ) ; this . traceLogfile = FileSystems . getDefault ( ) . getPath ( this . logDirPath . toString ( ) , super . getName ( ) + ".log" ) . toFile ( ) ; this . fileOutputStream = new FileOutputStream ( this . traceLogfile ) ; this . setBufferedOutputStream ( new BufferedOutputStream ( this . fileOutputStream , this . getBufferSize ( ) ) ) ; this . setTracePrintStream ( new TracePrintStream ( this . getBufferedOutputStream ( ) , this . getThreadMap ( ) ) ) ; this . getTracePrintStream ( ) . printf ( " ) ; this . getTracePrintStream ( ) . printf ( " Time : %tc%n" , new Date ( ) ) ; this . getTracePrintStream ( ) . printf ( " Bufsize : %d%n" , this . getBufferSize ( ) ) ; this . getTracePrintStream ( ) . printf ( " Autoflush: %b%n%n" , this . isAutoflush ( ) ) ; this . setOpened ( true ) ; } else { System . err . println ( "WARNING: Tracelog is opened already." ) ; } } catch ( FileNotFoundException ex ) { ex . printStackTrace ( System . err ) ; } } | Creates the underlying trace file and opens the associated trace streams . The file name will be assembled by the path to log directory and the name of the tracer . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.