idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
11,700
public void visitCode ( ) { mv = cv . visitMethod ( ACC_PRIVATE , "<init>" , "(Z)V" , null , null ) ; mv . visitCode ( ) ; Label l0 = new Label ( ) ; mv . visitLabel ( l0 ) ; mv . visitLineNumber ( 1 , l0 ) ; mv . visitVarInsn ( ALOAD , 0 ) ; mv . visitVarInsn ( ILOAD , 1 ) ; mv . visitMethodInsn ( INVOKESPECIAL , TQ_ROOT_BEAN , "<init>" , "(Z)V" , false ) ; Label l1 = new Label ( ) ; mv . visitLabel ( l1 ) ; mv . visitLineNumber ( 2 , l1 ) ; mv . visitVarInsn ( ALOAD , 0 ) ; mv . visitVarInsn ( ALOAD , 0 ) ; mv . visitMethodInsn ( INVOKEVIRTUAL , classInfo . getClassName ( ) , "setRoot" , "(Ljava/lang/Object;)V" , false ) ; List < FieldInfo > fields = classInfo . getFields ( ) ; if ( fields != null ) { for ( FieldInfo field : fields ) { field . writeFieldInit ( mv ) ; } } Label l2 = new Label ( ) ; mv . visitLabel ( l2 ) ; mv . visitLineNumber ( 3 , l2 ) ; mv . visitInsn ( RETURN ) ; Label l12 = new Label ( ) ; mv . visitLabel ( l12 ) ; mv . visitLocalVariable ( "this" , "L" + classInfo . getClassName ( ) + ";" , null , l0 , l12 , 0 ) ; mv . visitLocalVariable ( "alias" , "Z" , null , l0 , l12 , 1 ) ; mv . visitMaxs ( 5 , 2 ) ; mv . visitEnd ( ) ; }
Write the constructor initialising all the fields eagerly .
11,701
public static String getHostName ( ) { try { return java . net . InetAddress . getLocalHost ( ) . getHostName ( ) ; } catch ( java . net . UnknownHostException _ex ) { return null ; } }
Gets the host name of the local machine .
11,702
public static String getJavaVersion ( ) { String [ ] sysPropParms = new String [ ] { "java.runtime.version" , "java.version" } ; for ( int i = 0 ; i < sysPropParms . length ; i ++ ) { String val = System . getProperty ( sysPropParms [ i ] ) ; if ( ! StringUtil . isEmpty ( val ) ) { return val ; } } return null ; }
Determines the Java version of the executing JVM .
11,703
public static String concatFilePath ( boolean _includeTrailingDelimiter , String ... _parts ) { if ( _parts == null ) { return null ; } StringBuilder allParts = new StringBuilder ( ) ; for ( int i = 0 ; i < _parts . length ; i ++ ) { if ( _parts [ i ] == null ) { continue ; } allParts . append ( _parts [ i ] ) ; if ( ! _parts [ i ] . endsWith ( File . separator ) ) { allParts . append ( File . separator ) ; } } if ( ! _includeTrailingDelimiter && allParts . length ( ) > 0 ) { return allParts . substring ( 0 , allParts . lastIndexOf ( File . separator ) ) ; } return allParts . toString ( ) ; }
Concats a path from all given parts using the path delimiter for the currently used platform .
11,704
public static String appendTrailingDelimiter ( String _filePath ) { if ( _filePath == null ) { return null ; } if ( ! _filePath . endsWith ( File . separator ) ) { _filePath += File . separator ; } return _filePath ; }
Appends the OS specific path delimiter to the end of the String if it is missing .
11,705
public static File createTempDirectory ( String _path , String _name , boolean _deleteOnExit ) { File outputDir = new File ( concatFilePath ( _path , _name ) ) ; if ( ! outputDir . exists ( ) ) { try { Files . createDirectory ( Paths . get ( outputDir . toString ( ) ) ) ; } catch ( IOException _ex ) { LOGGER . error ( "Error while creating temp directory: " , _ex ) ; } } else { return null ; } if ( _deleteOnExit ) { outputDir . deleteOnExit ( ) ; } return outputDir ; }
Creates a new temporary directory in the given path .
11,706
public static File createTempDirectory ( String _path , String _prefix , int _length , boolean _timestamp , boolean _deleteOnExit ) { SimpleDateFormat formatter = new SimpleDateFormat ( "yyyyMMdd_HHmmss-SSS" ) ; String randomStr = StringUtil . randomString ( _length ) ; StringBuilder fileName = new StringBuilder ( ) ; if ( _prefix != null ) { fileName . append ( _prefix ) ; } fileName . append ( randomStr ) ; if ( _timestamp ) { fileName . append ( "_" ) . append ( formatter . format ( new Date ( ) ) ) ; } File result = createTempDirectory ( _path , fileName . toString ( ) , _deleteOnExit ) ; while ( result == null ) { result = createTempDirectory ( _path , _prefix , _length , _timestamp , _deleteOnExit ) ; } return result ; }
Creates a temporary directory in the given path . You can specify certain files to get a random unique name .
11,707
public static boolean isDebuggingEnabled ( ) { boolean debuggingEnabled = false ; if ( ManagementFactory . getRuntimeMXBean ( ) . getInputArguments ( ) . toString ( ) . indexOf ( "-agentlib:jdwp" ) > 0 ) { debuggingEnabled = true ; } else if ( ManagementFactory . getRuntimeMXBean ( ) . getInputArguments ( ) . contains ( "-Xdebug" ) ) { debuggingEnabled = true ; } else if ( System . getProperty ( "debug" , "" ) . equals ( "true" ) ) { debuggingEnabled = true ; } return debuggingEnabled ; }
Examines some system properties to determine whether the process is likely being debugged in an IDE or remotely .
11,708
public static String formatBytesHumanReadable ( long _bytes , boolean _use1000BytesPerMb ) { int unit = _use1000BytesPerMb ? 1000 : 1024 ; if ( _bytes < unit ) { return _bytes + " B" ; } int exp = ( int ) ( Math . log ( _bytes ) / Math . log ( unit ) ) ; String pre = ( _use1000BytesPerMb ? "kMGTPE" : "KMGTPE" ) . charAt ( exp - 1 ) + ( _use1000BytesPerMb ? "" : "i" ) ; return String . format ( "%.1f %sB" , _bytes / Math . pow ( unit , exp ) , pre ) ; }
Formats a file size given in byte to something human readable .
11,709
public static String getApplicationVersionFromJar ( Class < ? > _class , String _default ) { try { Enumeration < URL > resources = _class . getClassLoader ( ) . getResources ( "META-INF/MANIFEST.MF" ) ; while ( resources . hasMoreElements ( ) ) { Manifest manifest = new Manifest ( resources . nextElement ( ) . openStream ( ) ) ; Attributes attribs = manifest . getMainAttributes ( ) ; String ver = attribs . getValue ( Attributes . Name . IMPLEMENTATION_VERSION ) ; if ( ver == null ) { return _default ; } String rev = attribs . getValue ( "Implementation-Revision" ) ; if ( rev != null ) { ver += "-r" + rev ; } return ver ; } } catch ( IOException _ex ) { } return _default ; }
Read the JARs manifest and try to get the current program version from it .
11,710
public static String normalizePath ( String _path , boolean _appendFinalSeparator ) { if ( _path == null ) { return _path ; } String path = _path . replace ( "\\" , FILE_SEPARATOR ) . replace ( "/" , FILE_SEPARATOR ) ; if ( _appendFinalSeparator && ! path . endsWith ( FILE_SEPARATOR ) ) { path += FILE_SEPARATOR ; } return path ; }
Normalize a file system path expression for the current OS . Replaces path separators by this OS s path separator . Appends a final path separator if parameter is set and if not yet present .
11,711
void init ( ) throws KnowledgeSourceBackendInitializationException { if ( this . project == null ) { Util . logger ( ) . log ( Level . FINE , "Opening Protege project {0}" , this . projectIdentifier ) ; this . project = initProject ( ) ; if ( this . project == null ) { throw new KnowledgeSourceBackendInitializationException ( "Could not load project " + this . projectIdentifier ) ; } else { this . protegeKnowledgeBase = this . project . getKnowledgeBase ( ) ; Util . logger ( ) . log ( Level . FINE , "Project {0} opened successfully" , this . projectIdentifier ) ; } } }
Opens the project .
11,712
void close ( ) { if ( this . project != null ) { Util . logger ( ) . log ( Level . FINE , "Closing Protege project {0}" , this . projectIdentifier ) ; for ( Iterator < ProjectListener > itr = this . projectListeners . iterator ( ) ; itr . hasNext ( ) ; ) { this . project . removeProjectListener ( itr . next ( ) ) ; itr . remove ( ) ; } try { this . project . dispose ( ) ; Util . logger ( ) . fine ( "Done closing connection." ) ; } catch ( IllegalStateException e ) { Util . logger ( ) . fine ( "Done closing connection." ) ; } finally { this . project = null ; } } }
Closes the project .
11,713
private < S , T > S getFromProtege ( T obj , ProtegeCommand < S , T > getter ) throws KnowledgeSourceReadException { if ( protegeKnowledgeBase != null && getter != null ) { int tries = TRIES ; Exception lastException = null ; do { try { return getter . getHelper ( obj ) ; } catch ( Exception e ) { lastException = e ; Util . logger ( ) . log ( Level . WARNING , "Exception attempting to " + getter . getWhat ( ) + " " + obj , e ) ; tries -- ; } close ( ) ; try { init ( ) ; } catch ( KnowledgeSourceBackendInitializationException e ) { throw new KnowledgeSourceReadException ( "Exception attempting to " + getter . getWhat ( ) + " " + obj , e ) ; } } while ( tries > 0 ) ; throw new KnowledgeSourceReadException ( "Failed to " + getter . getWhat ( ) + " " + obj + " after " + TRIES + " tries" , lastException ) ; } return null ; }
Executes a command upon the Protege knowledge base retrying if needed .
11,714
Instance createInstance ( String name , Cls cls ) throws KnowledgeSourceReadException { return getFromProtege ( new InstanceSpec ( name , cls ) , INSTANCE_CREATOR ) ; }
Creates a new instance in the knowledge base .
11,715
public static Integer strToInt ( String _str , Integer _default ) { if ( _str == null ) { return _default ; } if ( TypeUtil . isInteger ( _str , true ) ) { return Integer . valueOf ( _str ) ; } else { return _default ; } }
Convert given String to Integer returns _default if String is not an integer .
11,716
public static Properties toProperties ( Map < ? , ? > _map ) { Properties props = new Properties ( ) ; props . putAll ( _map ) ; return props ; }
Convertes a map to a Properties object .
11,717
public < T > Serializer < T > nullable ( Serializer < T > serializer ) { return new NullSerializer < T > ( serializer ) ; }
Build a serializer that is capable of serializing null values .
11,718
public static Properties readProperties ( File _file ) { if ( _file . exists ( ) ) { try { return readProperties ( new FileInputStream ( _file ) ) ; } catch ( FileNotFoundException _ex ) { LOGGER . info ( "Could not load properties file: " + _file , _ex ) ; } } return null ; }
Trys to read a properties file . Returns null if properties file could not be loaded
11,719
public static Properties readProperties ( InputStream _stream ) { Properties props = new Properties ( ) ; if ( _stream == null ) { return null ; } try { props . load ( _stream ) ; return props ; } catch ( IOException | NumberFormatException _ex ) { LOGGER . warn ( "Could not properties: " , _ex ) ; } return null ; }
Tries to read a properties file from an inputstream .
11,720
public static boolean writeProperties ( File _file , Properties _props ) { LOGGER . debug ( "Trying to write Properties to file: " + _file ) ; try ( FileOutputStream out = new FileOutputStream ( _file ) ) { _props . store ( out , _file . getName ( ) ) ; LOGGER . debug ( "Successfully wrote properties to file: " + _file ) ; } catch ( IOException _ex ) { LOGGER . warn ( "Could not save File: " + _file , _ex ) ; return false ; } return true ; }
Writes a properties Object to file . Returns true on success false otherwise .
11,721
public static boolean readPropertiesBoolean ( Properties _props , String _property ) { if ( _props . containsKey ( _property ) ) { if ( _props . getProperty ( _property ) . matches ( "(?i)(1|yes|true|enabled|on|y)" ) ) { return true ; } } return false ; }
Reads a property as boolean from an properties object . Returns true if read property matches 1 yes true enabled on y
11,722
public static String readFileToString ( String _file ) { List < String > localText = getTextfileFromUrl ( _file ) ; if ( localText == null ) { return null ; } return StringUtil . join ( guessLineTerminatorOfFile ( _file ) , localText ) ; }
Reads a file and returns it s content as string .
11,723
public static String readFileFromClassPath ( String _fileName ) { StringBuilder sb = new StringBuilder ( ) ; for ( String string : readFileFromClassPathAsList ( _fileName ) ) { sb . append ( string ) . append ( "\n" ) ; } return sb . length ( ) == 0 ? null : sb . toString ( ) ; }
Reads a file from classpath to String .
11,724
public static List < String > readFileFromClassPathAsList ( String _fileName ) { List < String > result = readFileFromClassPathAsList ( _fileName , Charset . defaultCharset ( ) , false ) ; return result == null ? new ArrayList < String > ( ) : result ; }
Reads a file from classpath to a list of String using default charset and log any exception .
11,725
public static List < String > readFileFromClassPathAsList ( String _fileName , Charset _charset , boolean _silent ) { List < String > contents = new ArrayList < > ( ) ; if ( StringUtil . isBlank ( _fileName ) ) { return contents ; } InputStream inputStream = FileIoUtil . class . getClassLoader ( ) . getResourceAsStream ( _fileName ) ; if ( inputStream != null ) { try ( BufferedReader dis = new BufferedReader ( new InputStreamReader ( inputStream , _charset ) ) ) { String s ; while ( ( s = dis . readLine ( ) ) != null ) { contents . add ( s ) ; } return contents ; } catch ( IOException _ex ) { if ( ! _silent ) { LOGGER . error ( "Error while reading resource to string: " , _ex ) ; } return null ; } } else { if ( _silent ) { return null ; } } return contents ; }
Reads a file from classpath to a list of String with the given charset . Will optionally suppress any exception logging .
11,726
public static boolean writeTextFile ( String _fileName , String _fileContent , Charset _charset , boolean _append ) { if ( StringUtil . isBlank ( _fileName ) ) { return false ; } String allText = "" ; if ( _append ) { File file = new File ( _fileName ) ; if ( file . exists ( ) ) { allText = readFileToString ( file ) + guessLineTerminatorOfFile ( _fileName ) ; } } allText += _fileContent ; OutputStreamWriter writer = null ; try { writer = new OutputStreamWriter ( new FileOutputStream ( _fileName ) , _charset ) ; writer . write ( allText ) ; } catch ( IOException _ex ) { LOGGER . error ( "Could not write file to '" + _fileName + "'" , _ex ) ; return false ; } finally { try { if ( writer != null ) { writer . close ( ) ; } } catch ( IOException _ex ) { LOGGER . error ( "Error while closing file '" + _fileName + "'" , _ex ) ; return false ; } } return true ; }
Write String to file with the given charset . Optionally appends the data to the file .
11,727
public static List < String > readFileFrom ( String _fileName , Charset _charset , SearchOrder ... _searchOrder ) { InputStream stream = openInputStreamForFile ( _fileName , _searchOrder ) ; if ( stream != null ) { return readTextFileFromStream ( stream , _charset , true ) ; } return null ; }
Read a file from different sources depending on _searchOrder . Will return the first successfully read file which can be loaded either from custom path classpath or system path .
11,728
protected Project initProject ( ) { return RemoteProjectManager . getInstance ( ) . getProject ( host , username , password , getProjectIdentifier ( ) , false ) ; }
Connects to the project specified in the constructor . Throws an undocumented runtime exception from within Protege if something bad happens .
11,729
public static Logger getLogger ( final Class < ? > clazz ) { if ( ! clazz . getPackage ( ) . getName ( ) . startsWith ( LOGGER . getName ( ) ) ) { throw new IllegalArgumentException ( String . format ( "Class %s is not a child of the package %s" , clazz . getName ( ) , LOGGER . getName ( ) ) ) ; } LOGGER . fine ( ( ) -> String . format ( "Locating logger for class %s" , clazz ) ) ; return Logger . getLogger ( clazz . getName ( ) ) ; }
Simple wrapper that forces initialization of the package - level LOGGER instance .
11,730
public static void setStandaloneLogging ( Level level ) { LOGGER . setUseParentHandlers ( false ) ; for ( Handler h : LOGGER . getHandlers ( ) ) { LOGGER . removeHandler ( h ) ; } StdoutHandler handler = new StdoutHandler ( ) ; handler . setFormatter ( new InlineFormatter ( ) ) ; LOGGER . addHandler ( handler ) ; final UncaughtExceptionHandler ueh = Thread . getDefaultUncaughtExceptionHandler ( ) ; Thread . setDefaultUncaughtExceptionHandler ( ( t , e ) -> { LOGGER . log ( Level . SEVERE , "Uncaught Exception in thread " + t . getName ( ) , e ) ; if ( ueh != null ) { ueh . uncaughtException ( t , e ) ; } } ) ; setLogLevel ( level ) ; }
Enable regular logging for all UBench code at the specified level .
11,731
public static void setLogLevel ( Level level ) { LOGGER . finer ( "Changing logging from " + LOGGER . getLevel ( ) ) ; LOGGER . setLevel ( level ) ; if ( ! LOGGER . getUseParentHandlers ( ) ) { LOGGER . setLevel ( level ) ; Stream . of ( LOGGER . getHandlers ( ) ) . forEach ( h -> h . setLevel ( level ) ) ; } LOGGER . finer ( "Changed logging to " + LOGGER . getLevel ( ) ) ; }
Enable the specified debug level messages to be output . Note that both this Logger and whatever Handler you use have to be set to enable the required log level for the handler to output the messages . If this UBench code is logging stand alone then this method will also change the output level of the log handlers .
11,732
public static String readResource ( String path ) { final long start = System . nanoTime ( ) ; try ( InputStream is = UScale . class . getClassLoader ( ) . getResourceAsStream ( path ) ; ) { int len = 0 ; byte [ ] buffer = new byte [ 2048 ] ; ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; while ( ( len = is . read ( buffer ) ) >= 0 ) { baos . write ( buffer , 0 , len ) ; } return new String ( baos . toByteArray ( ) , StandardCharsets . UTF_8 ) ; } catch ( IOException e ) { LOGGER . log ( Level . WARNING , e , ( ) -> "IOException loading resource " + path ) ; throw new IllegalStateException ( "Unable to read class loaded stream " + path , e ) ; } catch ( RuntimeException re ) { LOGGER . log ( Level . WARNING , re , ( ) -> "Unexpected exception loading resource " + path ) ; throw re ; } finally { LOGGER . fine ( ( ) -> String . format ( "Loaded resource %s in %.3fms" , path , ( System . nanoTime ( ) - start ) / 1000000.0 ) ) ; } }
Load a resource stored in the classpath as a String .
11,733
public static void add ( ClassVisitor cw , ClassInfo classInfo , boolean typeQueryRootBean ) { List < FieldInfo > fields = classInfo . getFields ( ) ; if ( fields != null ) { for ( FieldInfo field : fields ) { field . writeMethod ( cw , typeQueryRootBean ) ; } } }
Add the generated property access methods .
11,734
public static String getHostName ( String _ipAddress ) { try { InetAddress addr = InetAddress . getByName ( _ipAddress ) ; return addr . getHostName ( ) ; } catch ( Exception _ex ) { return _ipAddress ; } }
Get the host name of a local address if available .
11,735
public static boolean isIPv4orIPv6Address ( String _ipAddress ) { return IPV4_PATTERN . matcher ( _ipAddress ) . matches ( ) || IPV6_PATTERN . matcher ( _ipAddress ) . matches ( ) ; }
Checks if given String is either a valid IPv4 or IPv6 address .
11,736
public ValueComparator compare ( Value o ) { if ( o == null ) { return ValueComparator . NOT_EQUAL_TO ; } switch ( o . getType ( ) ) { case ORDINALVALUE : OrdinalValue other = ( OrdinalValue ) o ; if ( val == null || other . val == null ) { return ValueComparator . UNKNOWN ; } int c = this . index - other . index ; if ( c == 0 ) { return ValueComparator . EQUAL_TO ; } else if ( c > 0 ) { return ValueComparator . GREATER_THAN ; } else { return ValueComparator . LESS_THAN ; } case VALUELIST : ValueList < ? > vl = ( ValueList < ? > ) o ; return equals ( vl ) ? ValueComparator . EQUAL_TO : ValueComparator . NOT_EQUAL_TO ; default : return ValueComparator . NOT_EQUAL_TO ; } }
Compares this value and another according to the defined order or checks this number value for membership in a value list .
11,737
public static Class < ? > getGenericTypeArgument ( Field field ) { Type genericType = field . getGenericType ( ) ; if ( genericType instanceof ParameterizedType ) { ParameterizedType parameterizedType = ( ParameterizedType ) genericType ; Type [ ] actualTypeArguments = parameterizedType . getActualTypeArguments ( ) ; if ( actualTypeArguments . length == 1 ) { Type type = actualTypeArguments [ 0 ] ; if ( type instanceof Class < ? > ) { Class < ? > realClass = ( Class < ? > ) type ; return realClass ; } else { throw new IllegalArgumentException ( "only direct class types are allowed for generic parameter on field " + field . getName ( ) + " of type " + genericType . getClass ( ) . getName ( ) + "<T>, but " + type + " was given!" ) ; } } else { throw new IllegalArgumentException ( "only one type parameter expected for field " + field . getName ( ) + " but " + actualTypeArguments . length + " where found!" ) ; } } else { throw new IllegalArgumentException ( "The field '" + field . getName ( ) + "' is not a ParameterizedType but this is required for type inferrence!" ) ; } }
Takes a field and returns the type argument for this
11,738
public DataValidationEvent [ ] validateDataSourceBackendData ( ) throws DataSourceFailedDataValidationException , DataSourceValidationIncompleteException { KnowledgeSource knowledgeSource = getKnowledgeSource ( ) ; List < DataValidationEvent > validationEvents = new ArrayList < > ( ) ; try { for ( DataSourceBackend backend : getDataSource ( ) . getBackends ( ) ) { CollectionUtils . addAll ( validationEvents , backend . validateData ( knowledgeSource ) ) ; } } catch ( DataSourceBackendFailedDataValidationException ex ) { throw new DataSourceFailedDataValidationException ( "Data source failed validation" , ex , validationEvents . toArray ( new DataValidationEvent [ validationEvents . size ( ) ] ) ) ; } catch ( KnowledgeSourceReadException ex ) { throw new DataSourceValidationIncompleteException ( "An error occurred during validation" , ex ) ; } return validationEvents . toArray ( new DataValidationEvent [ validationEvents . size ( ) ] ) ; }
Runs each data source backend s data validation routine .
11,739
public void clear ( ) { this . abstractionFinder . getAlgorithmSource ( ) . clear ( ) ; this . abstractionFinder . getDataSource ( ) . clear ( ) ; this . abstractionFinder . getKnowledgeSource ( ) . clear ( ) ; LOGGER . fine ( "Protempa cleared" ) ; }
Clears resources created by this object and the data source knowledge source and algorithm source .
11,740
public void merge ( PropositionDefinitionCache otherCache ) { if ( otherCache != null ) { for ( Map . Entry < String , PropositionDefinition > me : otherCache . cache . entrySet ( ) ) { this . cache . putIfAbsent ( me . getKey ( ) , me . getValue ( ) ) ; } } }
Merges the given cache into this one . Any proposition definitions that are not in this cache will be added .
11,741
public void setInterval ( Interval interval ) { if ( interval == null ) { interval = INTERVAL_FACTORY . getInstance ( ) ; } this . interval = interval ; }
Sets the valid interval .
11,742
public final String getStartFormattedLong ( ) { Granularity startGran = this . interval . getStartGranularity ( ) ; return formatStart ( startGran != null ? startGran . getLongFormat ( ) : null ) ; }
Returns the earliest valid time of this proposition as a long string .
11,743
public final String getFinishFormattedLong ( ) { Granularity finishGran = this . interval . getFinishGranularity ( ) ; return formatFinish ( finishGran != null ? finishGran . getLongFormat ( ) : null ) ; }
Returns the latest valid time of this proposition as a long string .
11,744
protected void readTemporalProposition ( ObjectInputStream s ) throws IOException , ClassNotFoundException { int mode = s . readChar ( ) ; try { switch ( mode ) { case 0 : setInterval ( INTERVAL_FACTORY . getInstance ( s . readLong ( ) , ( Granularity ) s . readObject ( ) ) ) ; break ; case 1 : setInterval ( INTERVAL_FACTORY . getInstance ( s . readLong ( ) , ( Granularity ) s . readObject ( ) , s . readLong ( ) , ( Granularity ) s . readObject ( ) ) ) ; break ; case 2 : setInterval ( INTERVAL_FACTORY . getInstance ( ( Long ) s . readObject ( ) , ( Long ) s . readObject ( ) , ( Granularity ) s . readObject ( ) , ( Long ) s . readObject ( ) , ( Long ) s . readObject ( ) , ( Granularity ) s . readObject ( ) ) ) ; break ; default : throw new InvalidObjectException ( "Can't restore. Invalid mode: " + mode ) ; } } catch ( IllegalArgumentException iae ) { throw new InvalidObjectException ( "Can't restore: " + iae . getMessage ( ) ) ; } }
Called while deserializing a temporal proposition .
11,745
public static < R > R beatAroundTheBush ( Callable < R > callable ) { try { return callable . call ( ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }
If exception happens during callable automatically wrap it in RuntimeException .
11,746
private void initInflightMessageStore ( ) { BTreeIndexFactory < String , StoredPublishEvent > indexFactory = new BTreeIndexFactory < String , StoredPublishEvent > ( ) ; indexFactory . setKeyCodec ( StringCodec . INSTANCE ) ; m_inflightStore = ( SortedIndex < String , StoredPublishEvent > ) m_multiIndexFactory . openOrCreate ( "inflight" , indexFactory ) ; }
Initialize the message store used to handle the temporary storage of QoS 1 2 messages in flight .
11,747
public void visit ( LowLevelAbstractionDefinition def ) throws ProtempaException { LOGGER . log ( Level . FINER , "Creating rule for {0}" , def ) ; try { if ( ! def . getValueDefinitions ( ) . isEmpty ( ) ) { Rule rule = new Rule ( def . getId ( ) ) ; Pattern sourceP = new Pattern ( 2 , 1 , PRIM_PARAM_OT , "" ) ; Set < String > abstractedFrom = def . getAbstractedFrom ( ) ; String [ ] abstractedFromArr = abstractedFrom . toArray ( new String [ abstractedFrom . size ( ) ] ) ; Set < String > subtrees = this . cache . collectPropIdDescendantsUsingInverseIsA ( abstractedFromArr ) ; sourceP . addConstraint ( new PredicateConstraint ( new PropositionPredicateExpression ( subtrees ) ) ) ; Pattern resultP = new Pattern ( 1 , 1 , ARRAY_LIST_OT , "result" ) ; resultP . setSource ( new Collect ( sourceP , new Pattern ( 1 , 1 , ARRAY_LIST_OT , "result" ) ) ) ; resultP . addConstraint ( new PredicateConstraint ( new CollectionSizeExpression ( 1 ) ) ) ; rule . addPattern ( resultP ) ; String contextId = def . getContextId ( ) ; if ( contextId != null ) { Pattern sourceP2 = new Pattern ( 4 , 1 , CONTEXT_OT , "context" ) ; sourceP2 . addConstraint ( new PredicateConstraint ( new PropositionPredicateExpression ( contextId ) ) ) ; Pattern resultP2 = new Pattern ( 3 , 1 , ARRAY_LIST_OT , "result2" ) ; resultP2 . setSource ( new Collect ( sourceP2 , new Pattern ( 3 , 1 , ARRAY_LIST_OT , "result" ) ) ) ; resultP2 . addConstraint ( new PredicateConstraint ( new CollectionSizeExpression ( 1 ) ) ) ; rule . addPattern ( resultP2 ) ; } Algorithm algo = this . algorithms . get ( def ) ; rule . setConsequence ( new LowLevelAbstractionConsequence ( def , algo , this . derivationsBuilder ) ) ; rule . setSalience ( TWO_SALIENCE ) ; this . ruleToAbstractionDefinition . put ( rule , def ) ; rules . add ( rule ) ; } } catch ( InvalidRuleException e ) { throw new AssertionError ( e . getClass ( ) . getName ( ) + ": " + e . getMessage ( ) ) ; } }
Translates a low - level abstraction definition into rules .
11,748
public void visit ( HighLevelAbstractionDefinition def ) throws ProtempaException { LOGGER . log ( Level . FINER , "Creating rule for {0}" , def ) ; try { Set < ExtendedPropositionDefinition > epdsC = def . getExtendedPropositionDefinitions ( ) ; if ( ! epdsC . isEmpty ( ) ) { Rule rule = new Rule ( def . getId ( ) ) ; rule . setSalience ( TWO_SALIENCE ) ; ExtendedPropositionDefinition [ ] epds = epdsC . toArray ( new ExtendedPropositionDefinition [ epdsC . size ( ) ] ) ; for ( int i = 0 ; i < epds . length ; i ++ ) { Pattern p = new Pattern ( i , PROP_OT ) ; GetMatchesPredicateExpression matchesPredicateExpression = new GetMatchesPredicateExpression ( epds [ i ] , this . cache ) ; Constraint c = new PredicateConstraint ( matchesPredicateExpression ) ; p . addConstraint ( c ) ; rule . addPattern ( p ) ; } rule . addPattern ( new EvalCondition ( new HighLevelAbstractionCondition ( def , epds ) , null ) ) ; rule . setConsequence ( new HighLevelAbstractionConsequence ( def , epds , this . derivationsBuilder ) ) ; this . ruleToAbstractionDefinition . put ( rule , def ) ; rules . add ( rule ) ; ABSTRACTION_COMBINER . toRules ( def , rules , this . derivationsBuilder ) ; } } catch ( InvalidRuleException e ) { throw new AssertionError ( e . getClass ( ) . getName ( ) + ": " + e . getMessage ( ) ) ; } }
Translates a high - level abstraction definition into rules .
11,749
public void visit ( SliceDefinition def ) throws ProtempaException { LOGGER . log ( Level . FINER , "Creating rule for {0}" , def ) ; try { Set < TemporalExtendedPropositionDefinition > epdsC = def . getTemporalExtendedPropositionDefinitions ( ) ; if ( ! epdsC . isEmpty ( ) ) { TemporalExtendedPropositionDefinition [ ] epds = epdsC . toArray ( new TemporalExtendedPropositionDefinition [ epdsC . size ( ) ] ) ; Rule rule = new Rule ( "SLICE_" + def . getId ( ) ) ; Pattern sourceP = new Pattern ( 2 , 1 , TEMP_PROP_OT , "" ) ; for ( int i = 0 ; i < epds . length ; i ++ ) { GetMatchesPredicateExpression matchesPredicateExpression = new GetMatchesPredicateExpression ( epds [ i ] , this . cache ) ; Constraint c = new PredicateConstraint ( matchesPredicateExpression ) ; sourceP . addConstraint ( c ) ; } Pattern resultP = new Pattern ( 1 , 1 , ARRAY_LIST_OT , "result" ) ; resultP . setSource ( new Collect ( sourceP , new Pattern ( 1 , 1 , ARRAY_LIST_OT , "result" ) ) ) ; int len ; int minInd = def . getMinIndex ( ) ; int maxInd = def . getMaxIndex ( ) ; if ( maxInd < 0 ) { len = Math . abs ( minInd ) ; } else { len = maxInd ; } resultP . addConstraint ( new PredicateConstraint ( new CollectionSizeExpression ( len ) ) ) ; rule . addPattern ( resultP ) ; rule . setConsequence ( new SliceConsequence ( def , this . derivationsBuilder ) ) ; rule . setSalience ( MINUS_TWO_SALIENCE ) ; this . ruleToAbstractionDefinition . put ( rule , def ) ; rules . add ( rule ) ; } } catch ( InvalidRuleException e ) { throw new AssertionError ( e . getClass ( ) . getName ( ) + ": " + e . getMessage ( ) ) ; } }
Translates a slice definition into rules .
11,750
public void visit ( SequentialTemporalPatternDefinition def ) throws ProtempaException { LOGGER . log ( Level . FINER , "Creating rule for {0}" , def ) ; try { TemporalExtendedPropositionDefinition lhs = def . getFirstTemporalExtendedPropositionDefinition ( ) ; if ( lhs != null ) { Rule rule = new Rule ( "SEQ_TP_" + def . getId ( ) ) ; Pattern sourceP = new Pattern ( 2 , TEMP_PROP_OT ) ; GetMatchesPredicateExpression matchesPredicateExpression = new GetMatchesPredicateExpression ( lhs , this . cache ) ; sourceP . addConstraint ( new PredicateConstraint ( matchesPredicateExpression ) ) ; SubsequentTemporalExtendedPropositionDefinition [ ] relatedTemporalExtendedPropositionDefinitions = def . getSubsequentTemporalExtendedPropositionDefinitions ( ) ; for ( int i = 0 ; i < relatedTemporalExtendedPropositionDefinitions . length ; i ++ ) { SubsequentTemporalExtendedPropositionDefinition rtepd = relatedTemporalExtendedPropositionDefinitions [ i ] ; GetMatchesPredicateExpression matchesPredicateExpression1 = new GetMatchesPredicateExpression ( rtepd . getRelatedTemporalExtendedPropositionDefinition ( ) , this . cache ) ; Constraint c = new PredicateConstraint ( matchesPredicateExpression1 ) ; sourceP . addConstraint ( c ) ; } Pattern resultP = new Pattern ( 1 , 1 , ARRAY_LIST_OT , "result" ) ; resultP . setSource ( new Collect ( sourceP , new Pattern ( 1 , 1 , ARRAY_LIST_OT , "result" ) ) ) ; resultP . addConstraint ( new PredicateConstraint ( new CollectionSizeExpression ( 1 ) ) ) ; rule . addPattern ( resultP ) ; rule . setConsequence ( new SequentialTemporalPatternConsequence ( def , this . derivationsBuilder ) ) ; rule . setSalience ( MINUS_TWO_SALIENCE ) ; this . ruleToAbstractionDefinition . put ( rule , def ) ; rules . add ( rule ) ; ABSTRACTION_COMBINER . toRules ( def , rules , this . derivationsBuilder ) ; } } catch ( InvalidRuleException e ) { throw new AssertionError ( e . getClass ( ) . getName ( ) + ": " + e . getMessage ( ) ) ; } }
Translates a sequential temporal pattern definition into rules .
11,751
List < Rule > getRules ( ) { List < Rule > rulesToReturn = new ArrayList < > ( this . rules ) ; new DeletedProposition ( ) . toRules ( rulesToReturn ) ; return rulesToReturn ; }
Returns a newly - created an array of rules that were generated .
11,752
public < T > UBench addTask ( String name , Supplier < T > task ) { return addTask ( name , task , null ) ; }
Include a named task in to the benchmark .
11,753
public UBench addIntTask ( String name , IntSupplier task ) { return addIntTask ( name , task , null ) ; }
Include an int - specialized named task in to the benchmark .
11,754
public UBench addLongTask ( String name , LongSupplier task ) { return addLongTask ( name , task , null ) ; }
Include a long - specialized named task in to the benchmark .
11,755
public UBench addDoubleTask ( String name , DoubleSupplier task ) { return addDoubleTask ( name , task , null ) ; }
Include a double - specialized named task in to the benchmark .
11,756
public UBench addTask ( String name , Runnable task ) { return putTask ( name , ( ) -> { long start = System . nanoTime ( ) ; task . run ( ) ; return System . nanoTime ( ) - start ; } ) ; }
Include a named task that has no output value in to the benchmark .
11,757
public UReport press ( UMode mode , final long timeLimit , final TimeUnit timeUnit ) { return press ( mode , 0 , 0 , 0.0 , timeLimit , timeUnit ) ; }
Benchmark all added tasks until they exceed the set time limit
11,758
public static boolean isDouble ( String _str , boolean _allowNegative ) { return isDouble ( _str , DecimalFormatSymbols . getInstance ( ) . getDecimalSeparator ( ) , _allowNegative ) ; }
Checks if the given string is a valid double . The used separator is based on the used system locale
11,759
public static boolean isDouble ( String _str , char _separator , boolean _allowNegative ) { String pattern = "\\d+XXX\\d+$" ; if ( _separator == '.' ) { pattern = pattern . replace ( "XXX" , "\\.?" ) ; } else { pattern = pattern . replace ( "XXX" , _separator + "?" ) ; } if ( _allowNegative ) { pattern = "^-?" + pattern ; } else { pattern = "^" + pattern ; } if ( _str != null ) { return _str . matches ( pattern ) || isInteger ( _str , _allowNegative ) ; } return false ; }
Checks if the given string is a valid double .
11,760
public static boolean isInteger ( String _str , boolean _allowNegative ) { if ( _str == null ) { return false ; } String regex = "[0-9]+$" ; if ( _allowNegative ) { regex = "^-?" + regex ; } else { regex = "^" + regex ; } return _str . matches ( regex ) ; }
Check if string is an either positive or negative integer .
11,761
public static Pattern createRegExPatternIfValid ( String _regExStr ) { if ( StringUtil . isBlank ( _regExStr ) ) { return null ; } Pattern pattern ; try { pattern = Pattern . compile ( _regExStr ) ; } catch ( PatternSyntaxException _ex ) { return null ; } return pattern ; }
Creates a RegEx Pattern object if given String is a valid regular expression .
11,762
public static < T > List < T > createList ( T ... _entries ) { List < T > l = new ArrayList < > ( ) ; if ( _entries != null ) { l . addAll ( Arrays . asList ( _entries ) ) ; } return l ; }
Creates a list from a varargs parameter array . The generic list is created with the same type as the parameters .
11,763
public static < T > Map < T , T > createMap ( T ... _args ) { Map < T , T > map = new HashMap < > ( ) ; if ( _args != null ) { if ( _args . length % 2 != 0 ) { throw new IllegalArgumentException ( "Even number of parameters required to create map: " + Arrays . toString ( _args ) ) ; } for ( int i = 0 ; i < _args . length ; ) { map . put ( _args [ i ] , _args [ i + 1 ] ) ; i += 2 ; } } return map ; }
Creates a map from the even - sized parameter array .
11,764
public static < T > List < List < T > > splitList ( List < T > _list , int _elements ) { List < List < T > > partitions = new ArrayList < > ( ) ; for ( int i = 0 ; i < _list . size ( ) ; i += _elements ) { partitions . add ( _list . subList ( i , Math . min ( i + _elements , _list . size ( ) ) ) ) ; } return partitions ; }
Split a List into equal parts . Last list could be shorter than _elements .
11,765
public static int defaultIfNotInteger ( String _possibleInt , int _default ) { if ( isInteger ( _possibleInt ) ) { return Integer . parseInt ( _possibleInt ) ; } return _default ; }
Returns integer converted from string or default if string could not be converted to int .
11,766
public long getTime ( ) throws NotAvailableException { synchronized ( timeSync ) { try { if ( ! isRunning ( ) ) { throw new InvalidStateException ( "Stopwatch was never started!" ) ; } if ( endTime == - 1 ) { return System . currentTimeMillis ( ) - startTime ; } return endTime - startTime ; } catch ( CouldNotPerformException ex ) { throw new NotAvailableException ( ContextType . INSTANCE , "time" , ex ) ; } } }
This method returns the time interval between the start - and end timestamps . In case the the Stopwatch is still running the elapsed time since Stopwatch start will be returned .
11,767
public long stop ( ) throws CouldNotPerformException { synchronized ( timeSync ) { if ( ! isRunning ( ) ) { throw new InvalidStateException ( "Stopwatch was never started!" ) ; } synchronized ( stopWaiter ) { endTime = System . currentTimeMillis ( ) ; stopWaiter . notifyAll ( ) ; } return getTime ( ) ; } }
This method stops the Stopwatch and returns the time result .
11,768
void parse ( File file ) throws ParseException { if ( file == null ) { Log . warn ( "parsing NULL file, so fallback on default configuration!" ) ; return ; } if ( ! file . exists ( ) ) { Log . warn ( String . format ( "parsing not existing file %s, so fallback on default configuration!" , file . getAbsolutePath ( ) ) ) ; return ; } try { FileReader reader = new FileReader ( file ) ; parse ( reader ) ; } catch ( FileNotFoundException fex ) { Log . warn ( String . format ( "parsing not existing file %s, so fallback on default configuration!" , file . getAbsolutePath ( ) ) , fex ) ; return ; } }
Parse the configuration from file .
11,769
void parse ( Reader reader ) throws ParseException { if ( reader == null ) { Log . warn ( "parsing NULL reader, so fallback on default configuration!" ) ; return ; } BufferedReader br = new BufferedReader ( reader ) ; String line ; try { while ( ( line = br . readLine ( ) ) != null ) { int commentMarker = line . indexOf ( '#' ) ; if ( commentMarker != - 1 ) { if ( commentMarker == 0 ) { continue ; } else { throw new ParseException ( line , commentMarker ) ; } } else { if ( line . isEmpty ( ) || line . matches ( "^\\s*$" ) ) { continue ; } int deilimiterIdx = line . indexOf ( ' ' ) ; String key = line . substring ( 0 , deilimiterIdx ) . trim ( ) ; String value = line . substring ( deilimiterIdx ) . trim ( ) ; m_properties . put ( key , value ) ; } } } catch ( IOException ex ) { throw new ParseException ( "Failed to read" , 1 ) ; } }
Parse the configuration
11,770
public static DataSourceBackendId getInstance ( String id ) { DataSourceBackendId result = cache . get ( id ) ; if ( result == null ) { id = id . intern ( ) ; result = new DataSourceBackendId ( id ) ; cache . put ( id , result ) ; } return result ; }
Creates a data source backend id .
11,771
public void init ( String param , Date time , String language ) { if ( param == null ) param = JCalendarPopup . DATE_PARAM ; timeParam = param ; targetTime = time ; languageString = language ; this . setName ( "JTimeButton" ) ; }
Creates new TimeButton .
11,772
public void actionPerformed ( ActionEvent e ) { if ( e . getSource ( ) == this ) { Date dateTarget = this . getTargetDate ( ) ; JTimePopup popup = JTimePopup . createTimePopup ( this . getTimeParam ( ) , dateTarget , this , languageString ) ; popup . addPropertyChangeListener ( this ) ; } }
The user pressed the button display the JTimePopup .
11,773
public final void setStartEndPoints ( final Point3D start , final Point3D end ) { final Point3D direction = start . subtract ( end ) ; final Point3D position = start . midpoint ( end ) ; setLength ( direction . magnitude ( ) ) ; final Point3D axis = UP . crossProduct ( direction . normalize ( ) ) ; super . setVisible ( true ) ; super . setTranslateX ( position . getX ( ) ) ; super . setTranslateY ( position . getY ( ) ) ; super . setTranslateZ ( position . getZ ( ) ) ; super . setRotationAxis ( axis ) ; super . setRotate ( UP . angle ( direction . normalize ( ) ) ) ; }
Sets the start and end point of the line .
11,774
public void setMaterial ( final Material material ) { switch ( type ) { case BOX : box . setMaterial ( material ) ; break ; case CYLINDER : cylinder . setMaterial ( material ) ; break ; default : break ; } }
Sets the Material of the line which can be used to display different colors .
11,775
public void setWidth ( double width ) { switch ( type ) { case BOX : box . setWidth ( width ) ; box . setDepth ( width ) ; break ; case CYLINDER : cylinder . setRadius ( width * 0.5 ) ; break ; default : break ; } }
Sets the width of the line .
11,776
private void setLength ( double length ) { switch ( type ) { case BOX : box . setHeight ( length ) ; break ; case CYLINDER : cylinder . setHeight ( length ) ; break ; default : break ; } }
Sets the length of the line . This is only used internally to shape the line correctly .
11,777
public final void initialize ( BackendInstanceSpec config ) throws BackendInitializationException { super . initialize ( config ) ; try { IOUtil . readPropertiesFromResource ( algorithmClasses , getClass ( ) , getAlgorithmsPropertiesResourceName ( ) ) ; } catch ( IOException e ) { throw new AlgorithmSourceBackendInitializationException ( "Could not initialize " + getClass ( ) , e ) ; } }
Reads the properties file containing the list of algorithm classes .
11,778
public K removeValue ( V _val ) { checkParms ( _val ) ; K removedKey = inverseMap . remove ( _val ) ; if ( removedKey != null ) { map . remove ( removedKey ) ; } return removedKey ; }
Removes the mapping for a value from this map if it is present .
11,779
public SQLException attempt ( ) { try { Connection con = this . connectionSpec . getOrCreate ( ) ; con . setReadOnly ( true ) ; try { Statement stmt = con . createStatement ( ResultSet . TYPE_FORWARD_ONLY , ResultSet . CONCUR_READ_ONLY ) ; stmt . setFetchSize ( AbstractSQLGenerator . FETCH_SIZE ) ; if ( this . queryTimeout != null ) { stmt . setQueryTimeout ( this . queryTimeout ) ; } try { SQLExecutor . executeSQL ( con , stmt , this . query , this . resultProcessor ) ; stmt . close ( ) ; stmt = null ; } finally { if ( stmt != null ) { try { stmt . close ( ) ; } catch ( SQLException e ) { } } } con . close ( ) ; con = null ; } finally { if ( con != null ) { try { con . close ( ) ; } catch ( SQLException e ) { } } } return null ; } catch ( SQLException ex ) { return ex ; } }
Attempts executing the query specified in the constructor .
11,780
@ SuppressWarnings ( "unchecked" ) public Iterator < String > getKeys ( ) { final Iterator tempKeysIter = super . getKeys ( ) ; final List < String > keys = sortKeys ( tempKeysIter ) ; return keys . iterator ( ) ; }
each call to this method method will first sort the keys and then return the iterator .
11,781
public static Resource getGenericResource ( String resource ) { log . trace ( "retrieving resource -> " + resource ) ; try { final File file = normFile ( resource ) ; if ( file . exists ( ) ) { return new ResourceImpl ( file . toURI ( ) . toURL ( ) ) ; } if ( resource . startsWith ( "/" ) ) { throw new IllegalArgumentException ( "Classpath resource cannot start with '/': " + resource ) ; } if ( resource . indexOf ( '\\' ) != - 1 ) { throw new IllegalArgumentException ( "Classpath resource cannot contain '\\': " + resource ) ; } URL url = getLoader ( ) . getResource ( resource ) ; if ( url == null ) { return null ; } return new ResourceImpl ( url ) ; } catch ( Exception e ) { log . error ( "Could not retrieve resource: " + e . getMessage ( ) , e ) ; return null ; } }
Gets a generic resource searching first from the file system then in the classpath if not found .
11,782
public ValueComparator compare ( Value o ) { if ( o == null ) { return ValueComparator . NOT_EQUAL_TO ; } switch ( o . getType ( ) ) { case NUMBERVALUE : NumberValue other = ( NumberValue ) o ; int comp = compareTo ( other ) ; return comp > 0 ? ValueComparator . GREATER_THAN : ( comp < 0 ? ValueComparator . LESS_THAN : ValueComparator . EQUAL_TO ) ; case INEQUALITYNUMBERVALUE : InequalityNumberValue other2 = ( InequalityNumberValue ) o ; int comp2 = num . compareTo ( ( BigDecimal ) other2 . getNumber ( ) ) ; switch ( other2 . getComparator ( ) ) { case EQUAL_TO : return comp2 > 0 ? ValueComparator . GREATER_THAN : ( comp2 < 0 ? ValueComparator . LESS_THAN : ValueComparator . EQUAL_TO ) ; case GREATER_THAN : return comp2 <= 0 ? ValueComparator . LESS_THAN : ValueComparator . UNKNOWN ; default : return comp2 >= 0 ? ValueComparator . GREATER_THAN : ValueComparator . UNKNOWN ; } case VALUELIST : ValueList < ? > vl = ( ValueList < ? > ) o ; return equals ( vl ) ? ValueComparator . EQUAL_TO : ValueComparator . NOT_EQUAL_TO ; default : return ValueComparator . NOT_EQUAL_TO ; } }
Compares this value and another numerically or checks this number value for membership in a value list .
11,783
public static boolean hasNegativeCycle ( Object sourceOrDest , DirectedGraph g , Mode mode ) { return calcShortestDistances ( sourceOrDest , g , mode ) == null ; }
Determines if there are any negative cycles found .
11,784
private final void checkInvariants ( ) throws Error { if ( _lineBreak == null ) { throw new Error ( "_lineBreak == null" ) ; } else if ( _lineBreak == LineBreak . NONE && _indentation . length ( ) > 0 ) { throw new Error ( "_lineBreak == LineBreak.NONE && _indentation = \"" + _indentation + "\"." ) ; } else if ( _elementStack == null ) { throw new Error ( "_elementStack (" + _elementStack + " == null" ) ; } else if ( _elementStackSize < 0 ) { throw new Error ( "_elementStackSize (" + _elementStackSize + ") < 0" ) ; } }
Checks all invariants . This check should be performed at the end of every method that changes the internal state of this object .
11,785
private final void writeIndentation ( ) throws IOException { if ( _indentation . length ( ) > 0 ) { int count = _elementStackSize - 1 ; for ( int i = 0 ; i < count ; i ++ ) { _out . write ( _indentation ) ; } } }
Writes the indentation to the output stream .
11,786
public final void setElementStackCapacity ( int newCapacity ) throws IllegalArgumentException , OutOfMemoryError { if ( newCapacity < _elementStack . length ) { throw new IllegalArgumentException ( "newCapacity < getElementStackSize()" ) ; } int currentCapacity = _elementStack . length ; if ( currentCapacity == newCapacity ) { return ; } String [ ] newStack = new String [ newCapacity ] ; System . arraycopy ( _elementStack , 0 , newStack , 0 , _elementStackSize ) ; _elementStack = newStack ; checkInvariants ( ) ; }
Sets the capacity for the stack of open elements . The new capacity must at least allow the stack to contain the current open elements .
11,787
public final void startTag ( String type ) throws IllegalStateException , IllegalArgumentException , IOException { if ( _state != XMLEventListenerStates . BEFORE_XML_DECLARATION && _state != XMLEventListenerStates . BEFORE_DTD_DECLARATION && _state != XMLEventListenerStates . BEFORE_ROOT_ELEMENT && _state != XMLEventListenerStates . START_TAG_OPEN && _state != XMLEventListenerStates . WITHIN_ELEMENT ) { throw new IllegalStateException ( "getState() == " + _state ) ; } else if ( type == null ) { throw new IllegalArgumentException ( "type == null" ) ; } XMLEventListenerState oldState = _state ; _state = XMLEventListenerStates . ERROR_STATE ; if ( _elementStackSize == _elementStack . length ) { String [ ] newStack ; try { newStack = new String [ ( _elementStackSize + 1 ) * 2 ] ; } catch ( OutOfMemoryError error ) { newStack = new String [ _elementStackSize + 1 ] ; } System . arraycopy ( _elementStack , 0 , newStack , 0 , _elementStackSize ) ; _elementStack = newStack ; } _elementStack [ _elementStackSize ] = type ; _elementStackSize ++ ; if ( oldState == XMLEventListenerStates . START_TAG_OPEN ) { _out . write ( '>' ) ; } if ( oldState != XMLEventListenerStates . BEFORE_XML_DECLARATION ) { _out . write ( _lineBreakChars ) ; writeIndentation ( ) ; } _out . write ( '<' ) ; _out . write ( type ) ; _state = XMLEventListenerStates . START_TAG_OPEN ; checkInvariants ( ) ; }
Writes an element start tag . The element type name will be stored in the internal element stack . If necessary the capacity of this stack will be extended .
11,788
public final void pcdata ( char [ ] ch , int start , int length ) throws IllegalStateException , IllegalArgumentException , IndexOutOfBoundsException , InvalidXMLException , IOException { if ( _state != XMLEventListenerStates . START_TAG_OPEN && _state != XMLEventListenerStates . WITHIN_ELEMENT ) { throw new IllegalStateException ( "getState() == " + _state ) ; } else if ( ch == null ) { throw new IllegalArgumentException ( "ch == null" ) ; } else if ( start < 0 ) { throw new IllegalArgumentException ( "start (" + start + ") < 0" ) ; } else if ( start >= ch . length ) { throw new IllegalArgumentException ( "start (" + start + ") >= ch.length (" + ch . length + ')' ) ; } else if ( length < 0 ) { throw new IllegalArgumentException ( "length < 0" ) ; } XMLEventListenerState oldState = _state ; _state = XMLEventListenerStates . ERROR_STATE ; if ( oldState == XMLEventListenerStates . START_TAG_OPEN ) { closeStartTag ( ) ; } _encoder . text ( _out , ch , start , length , _escapeAmpersands ) ; _state = XMLEventListenerStates . WITHIN_ELEMENT ; checkInvariants ( ) ; }
Writes the specified character array as PCDATA .
11,789
public void setEditorSearchPackages ( String [ ] packages ) { SecurityManager sm = System . getSecurityManager ( ) ; if ( sm != null ) { sm . checkPropertiesAccess ( ) ; } this . packages = packages . clone ( ) ; }
Sets packages in which editors should be looked up .
11,790
private static double [ ] newtonSolve ( Function < double [ ] , double [ ] > function , double [ ] initial , double tolerance ) { RealVector dx = new ArrayRealVector ( initial . length ) ; dx . set ( tolerance + 1 ) ; int iterations = 0 ; int d = initial . length ; double [ ] values = Arrays . copyOf ( initial , initial . length ) ; while ( dx . getNorm ( ) > tolerance ) { double [ ] fx = function . apply ( values ) ; Array2DRowRealMatrix df = new Array2DRowRealMatrix ( fx . length , d ) ; ArrayRealVector fxVector = new ArrayRealVector ( fx ) ; for ( int i = 0 ; i < d ; i ++ ) { double originalValue = values [ i ] ; values [ i ] += H ; double [ ] fxi = function . apply ( values ) ; values [ i ] = originalValue ; ArrayRealVector fxiVector = new ArrayRealVector ( fxi ) ; RealVector result = fxiVector . subtract ( fxVector ) ; result = result . mapDivide ( H ) ; df . setColumn ( i , result . toArray ( ) ) ; } dx = new RRQRDecomposition ( df ) . getSolver ( ) . solve ( fxVector . mapMultiply ( - 1 ) ) ; for ( int i = 0 ; i < values . length ; i ++ ) { values [ i ] += dx . getEntry ( i ) ; } iterations ++ ; if ( iterations % 100 == 0 ) { tolerance *= 10 ; } } return values ; }
Finding the best fit using least - squares method for an equation system
11,791
public static MathEquation detect ( UScale scale ) { return Arrays . stream ( rank ( scale ) ) . filter ( eq -> eq . isValid ( ) ) . findFirst ( ) . orElse ( fit ( scale , Models . CONSTANT ) ) ; }
From the results of a UScale run calculate the best - fit scaling equation
11,792
public static MathEquation [ ] rank ( UScale scale ) { double [ ] x = extractX ( scale ) ; double [ ] y = extractY ( scale ) ; return rank ( x , y ) ; }
From the scaling results calculate a number of scaling equations and return their equations in descending order of relevance
11,793
public static void initialize ( ) { PrivilegedAction action = new PrivilegedAction ( ) { public Object run ( ) { String defaultFormat = System . getProperty ( "org.jboss.common.beans.property.DateEditor.format" , "MMM d, yyyy" ) ; String defaultLocale = System . getProperty ( "org.jboss.common.beans.property.DateEditor.locale" ) ; DateFormat defaultDateFormat ; if ( defaultLocale == null || defaultLocale . length ( ) == 0 ) { defaultDateFormat = new SimpleDateFormat ( defaultFormat ) ; } else { LocaleEditor localeEditor = new LocaleEditor ( ) ; localeEditor . setAsText ( defaultLocale ) ; Locale locale = ( Locale ) localeEditor . getValue ( ) ; defaultDateFormat = new SimpleDateFormat ( defaultFormat , locale ) ; } formats = new DateFormat [ ] { defaultDateFormat , new SimpleDateFormat ( "EEE MMM d HH:mm:ss z yyyy" ) , new SimpleDateFormat ( "EEE, d MMM yyyy HH:mm:ss Z" ) } ; return null ; } } ; AccessController . doPrivileged ( action ) ; }
Setup the parsing formats . Offered as a separate static method to allow testing of locale changes since SimpleDateFormat will use the default locale upon construction . Should not be normally used!
11,794
public void setValue ( Object value ) { if ( value instanceof Date || value == null ) { this . text = null ; super . setValue ( value ) ; } else { throw new IllegalArgumentException ( "setValue() expected java.util.Date value, got " + value . getClass ( ) . getName ( ) ) ; } }
Sets directly the java . util . Date value
11,795
public void setAsText ( String text ) { if ( BeanUtils . isNull ( text ) ) { setValue ( null ) ; return ; } setValue ( getAsDocument ( text ) . getDocumentElement ( ) ) ; }
Sets as an Document created from a String .
11,796
public void useBackupDnsServer ( int index ) { this . selectedDnsServer = backupDnsServers . get ( index ) ; try { this . simpleResolver = new SimpleResolver ( this . selectedDnsServer ) ; } catch ( UnknownHostException ignore ) { } this . validatingResolver = new ValidatingResolver ( this . simpleResolver ) ; }
Use Backup DNS Server identified by index
11,797
public Value callMethod ( ExecutionContext context , Map < String , Value > params ) { validateParameters ( params ) ; fillDefaultValues ( params ) ; return internalCallMethod ( context , params ) ; }
Executes the method call .
11,798
protected void validateParameters ( Map < String , Value > callParameters ) { for ( String name : callParameters . keySet ( ) ) { if ( ! parameters . containsKey ( name ) ) throw new IllegalParametersException ( "Parameter not supported: " + name ) ; } for ( Map . Entry < String , MethodParameter > entry : parameters . entrySet ( ) ) { if ( entry . getValue ( ) . isOptional ( ) ) continue ; if ( ! callParameters . containsKey ( entry . getKey ( ) ) ) { throw new IllegalParametersException ( "Parameter not supplied: " + entry . getKey ( ) ) ; } } }
Validates the parameters .
11,799
protected void fillDefaultValues ( Map < String , Value > params ) { for ( MethodParameter parameter : parameters . values ( ) ) { if ( ! parameter . isOptional ( ) || parameter . getDefaultValue ( ) == null || params . get ( parameter . getName ( ) ) != null ) continue ; params . put ( parameter . getName ( ) , parameter . getDefaultValue ( ) ) ; } }
Fills in the default values .