idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
29,600 | public boolean setSecondaryHostFail ( ) { if ( secondaryHostFail . compareAndSet ( false , true ) ) { secondaryHostFailNanos = System . nanoTime ( ) ; currentConnectionAttempts . set ( 0 ) ; return true ; } return false ; } | Set slave connection lost variables . | 56 | 6 |
29,601 | public void remove ( ) { for ( int i = 0 ; i < buf . length ; i ++ ) { buf [ i ] = null ; // force null for easier garbage } buf = null ; } | Clear trace array for easy garbage . | 42 | 7 |
29,602 | public PooledConnection getPooledConnection ( String user , String password ) throws SQLException { return new MariaDbPooledConnection ( ( MariaDbConnection ) getConnection ( user , password ) ) ; } | Attempts to establish a physical database connection that can be used as a pooled connection . | 44 | 16 |
29,603 | @ Override public void initializeConnection ( ) throws SQLException { super . initializeConnection ( ) ; this . currentProtocol = null ; //launching initial loop reconnectFailedConnection ( new SearchFilter ( true , false ) ) ; resetMasterFailoverData ( ) ; } | Connect to database . | 59 | 4 |
29,604 | public void preExecute ( ) throws SQLException { lastQueryNanos = System . nanoTime ( ) ; //if connection is closed or failed on slave if ( this . currentProtocol != null && this . currentProtocol . isClosed ( ) ) { preAutoReconnect ( ) ; } } | Before executing query reconnect if connection is closed and autoReconnect option is set . | 67 | 17 |
29,605 | @ Override public void reconnectFailedConnection ( SearchFilter searchFilter ) throws SQLException { proxy . lock . lock ( ) ; try { if ( ! searchFilter . isInitialConnection ( ) && ( isExplicitClosed ( ) || ! isMasterHostFail ( ) ) ) { return ; } currentConnectionAttempts . incrementAndGet ( ) ; resetOldsBlackListHosts ( ) ; List < HostAddress > loopAddress = new LinkedList <> ( urlParser . getHostAddresses ( ) ) ; if ( HaMode . FAILOVER . equals ( mode ) ) { //put the list in the following order // - random order not connected host // - random order blacklist host // - random order connected host loopAddress . removeAll ( getBlacklistKeys ( ) ) ; Collections . shuffle ( loopAddress ) ; List < HostAddress > blacklistShuffle = new LinkedList <> ( getBlacklistKeys ( ) ) ; blacklistShuffle . retainAll ( urlParser . getHostAddresses ( ) ) ; Collections . shuffle ( blacklistShuffle ) ; loopAddress . addAll ( blacklistShuffle ) ; } else { //order in sequence loopAddress . removeAll ( getBlacklistKeys ( ) ) ; loopAddress . addAll ( getBlacklistKeys ( ) ) ; loopAddress . retainAll ( urlParser . getHostAddresses ( ) ) ; } //put connected at end if ( currentProtocol != null && ! isMasterHostFail ( ) ) { loopAddress . remove ( currentProtocol . getHostAddress ( ) ) ; //loopAddress.add(currentProtocol.getHostAddress()); } MasterProtocol . loop ( this , globalInfo , loopAddress , searchFilter ) ; //close loop if all connection are retrieved if ( ! isMasterHostFail ( ) ) { FailoverLoop . removeListener ( this ) ; } //if no error, reset failover variables resetMasterFailoverData ( ) ; } finally { proxy . lock . unlock ( ) ; } } | Loop to connect failed hosts . | 421 | 6 |
29,606 | public void switchReadOnlyConnection ( Boolean mustBeReadOnly ) throws SQLException { if ( urlParser . getOptions ( ) . assureReadOnly && currentReadOnlyAsked != mustBeReadOnly ) { proxy . lock . lock ( ) ; try { // verify not updated now that hold lock, double check safe due to volatile if ( currentReadOnlyAsked != mustBeReadOnly ) { currentReadOnlyAsked = mustBeReadOnly ; setSessionReadOnly ( mustBeReadOnly , currentProtocol ) ; } } finally { proxy . lock . unlock ( ) ; } } } | Force session to read - only according to options . | 122 | 10 |
29,607 | @ Override public void foundActiveMaster ( Protocol protocol ) throws SQLException { if ( isExplicitClosed ( ) ) { proxy . lock . lock ( ) ; try { protocol . close ( ) ; } finally { proxy . lock . unlock ( ) ; } return ; } syncConnection ( this . currentProtocol , protocol ) ; proxy . lock . lock ( ) ; try { if ( currentProtocol != null && ! currentProtocol . isClosed ( ) ) { currentProtocol . close ( ) ; } currentProtocol = protocol ; } finally { proxy . lock . unlock ( ) ; } resetMasterFailoverData ( ) ; FailoverLoop . removeListener ( this ) ; } | method called when a new Master connection is found after a fallback . | 148 | 14 |
29,608 | public void reconnect ( ) throws SQLException { boolean inTransaction = currentProtocol != null && currentProtocol . inTransaction ( ) ; reconnectFailedConnection ( new SearchFilter ( true , false ) ) ; handleFailLoop ( ) ; if ( inTransaction ) { throw new ReconnectDuringTransactionException ( "Connection reconnect automatically during an active transaction" , 1401 , "25S03" ) ; } } | Try to reconnect connection . | 87 | 5 |
29,609 | public void authenticate ( final PacketOutputStream out , final PacketInputStream in , final AtomicInteger sequence , final String servicePrincipalName , String mechanisms ) throws SQLException , IOException { if ( "" . equals ( servicePrincipalName ) ) { throw new SQLException ( "No principal name defined on server. " + "Please set server variable \"gssapi-principal-name\" or set option \"servicePrincipalName\"" , "28000" ) ; } if ( System . getProperty ( "java.security.auth.login.config" ) == null ) { final File jaasConfFile ; try { jaasConfFile = File . createTempFile ( "jaas.conf" , null ) ; try ( PrintStream bos = new PrintStream ( new FileOutputStream ( jaasConfFile ) ) ) { bos . print ( "Krb5ConnectorContext {\n" + "com.sun.security.auth.module.Krb5LoginModule required " + "useTicketCache=true " + "debug=true " + "renewTGT=true " + "doNotPrompt=true; };" ) ; } jaasConfFile . deleteOnExit ( ) ; } catch ( final IOException ex ) { throw new UncheckedIOException ( ex ) ; } System . setProperty ( "java.security.auth.login.config" , jaasConfFile . getCanonicalPath ( ) ) ; } try { LoginContext loginContext = new LoginContext ( "Krb5ConnectorContext" ) ; // attempt authentication loginContext . login ( ) ; final Subject mySubject = loginContext . getSubject ( ) ; if ( ! mySubject . getPrincipals ( ) . isEmpty ( ) ) { try { PrivilegedExceptionAction < Void > action = ( ) -> { try { Oid krb5Mechanism = new Oid ( "1.2.840.113554.1.2.2" ) ; GSSManager manager = GSSManager . getInstance ( ) ; GSSName peerName = manager . createName ( servicePrincipalName , GSSName . NT_USER_NAME ) ; GSSContext context = manager . createContext ( peerName , krb5Mechanism , null , GSSContext . DEFAULT_LIFETIME ) ; context . requestMutualAuth ( true ) ; byte [ ] inToken = new byte [ 0 ] ; byte [ ] outToken ; while ( ! context . isEstablished ( ) ) { outToken = context . initSecContext ( inToken , 0 , inToken . length ) ; // Send a token to the peer if one was generated by acceptSecContext if ( outToken != null ) { out . startPacket ( sequence . incrementAndGet ( ) ) ; out . write ( outToken ) ; out . flush ( ) ; } if ( ! context . isEstablished ( ) ) { Buffer buffer = in . getPacket ( true ) ; sequence . set ( in . getLastPacketSeq ( ) ) ; inToken = buffer . readRawBytes ( buffer . remaining ( ) ) ; } } } catch ( GSSException le ) { throw new SQLException ( "GSS-API authentication exception" , "28000" , 1045 , le ) ; } return null ; } ; Subject . doAs ( mySubject , action ) ; } catch ( PrivilegedActionException exception ) { throw new SQLException ( "GSS-API authentication exception" , "28000" , 1045 , exception ) ; } } else { throw new SQLException ( "GSS-API authentication exception : no credential cache not found." , "28000" , 1045 ) ; } } catch ( LoginException le ) { throw new SQLException ( "GSS-API authentication exception" , "28000" , 1045 , le ) ; } } | Process default GSS plugin authentication . | 835 | 7 |
29,610 | public static void send ( final PacketOutputStream pos , final String username , final String password , final HostAddress currentHost , final String database , final long clientCapabilities , final long serverCapabilities , final byte serverLanguage , final byte packetSeq , final Options options , final ReadInitialHandShakePacket greetingPacket ) throws IOException { pos . startPacket ( packetSeq ) ; final byte [ ] authData ; switch ( greetingPacket . getPluginName ( ) ) { case "" : //CONJ-274 : permit connection mysql 5.1 db case DefaultAuthenticationProvider . MYSQL_NATIVE_PASSWORD : pos . permitTrace ( false ) ; try { authData = Utils . encryptPassword ( password , greetingPacket . getSeed ( ) , options . passwordCharacterEncoding ) ; break ; } catch ( NoSuchAlgorithmException e ) { //cannot occur : throw new IOException ( "Unknown algorithm SHA-1. Cannot encrypt password" , e ) ; } case DefaultAuthenticationProvider . MYSQL_CLEAR_PASSWORD : pos . permitTrace ( false ) ; if ( options . passwordCharacterEncoding != null && ! options . passwordCharacterEncoding . isEmpty ( ) ) { authData = password . getBytes ( options . passwordCharacterEncoding ) ; } else { authData = password . getBytes ( ) ; } break ; default : authData = new byte [ 0 ] ; } pos . writeInt ( ( int ) clientCapabilities ) ; pos . writeInt ( 1024 * 1024 * 1024 ) ; pos . write ( serverLanguage ) ; //1 pos . writeBytes ( ( byte ) 0 , 19 ) ; //19 pos . writeInt ( ( int ) ( clientCapabilities >> 32 ) ) ; //Maria extended flag if ( username == null || username . isEmpty ( ) ) { pos . write ( System . getProperty ( "user.name" ) . getBytes ( ) ) ; //to permit SSO } else { pos . write ( username . getBytes ( ) ) ; //strlen username } pos . write ( ( byte ) 0 ) ; //1 if ( ( serverCapabilities & MariaDbServerCapabilities . PLUGIN_AUTH_LENENC_CLIENT_DATA ) != 0 ) { pos . writeFieldLength ( authData . length ) ; pos . write ( authData ) ; } else if ( ( serverCapabilities & MariaDbServerCapabilities . SECURE_CONNECTION ) != 0 ) { pos . write ( ( byte ) authData . length ) ; pos . write ( authData ) ; } else { pos . write ( authData ) ; pos . write ( ( byte ) 0 ) ; } if ( ( serverCapabilities & MariaDbServerCapabilities . CONNECT_WITH_DB ) != 0 ) { pos . write ( database ) ; pos . write ( ( byte ) 0 ) ; } if ( ( serverCapabilities & MariaDbServerCapabilities . PLUGIN_AUTH ) != 0 ) { pos . write ( greetingPacket . getPluginName ( ) ) ; pos . write ( ( byte ) 0 ) ; } if ( ( serverCapabilities & MariaDbServerCapabilities . CONNECT_ATTRS ) != 0 ) { writeConnectAttributes ( pos , options . connectionAttributes , currentHost ) ; } pos . flush ( ) ; pos . permitTrace ( true ) ; } | Send handshake response packet . | 726 | 5 |
29,611 | public static List < HostAddress > parse ( String spec , HaMode haMode ) { if ( spec == null ) { throw new IllegalArgumentException ( "Invalid connection URL, host address must not be empty " ) ; } if ( "" . equals ( spec ) ) { return new ArrayList <> ( 0 ) ; } String [ ] tokens = spec . trim ( ) . split ( "," ) ; int size = tokens . length ; List < HostAddress > arr = new ArrayList <> ( size ) ; // Aurora using cluster end point mustn't have any other host if ( haMode == HaMode . AURORA ) { Pattern clusterPattern = Pattern . compile ( "(.+)\\.cluster-([a-z0-9]+\\.[a-z0-9\\-]+\\.rds\\.amazonaws\\.com)" , Pattern . CASE_INSENSITIVE ) ; Matcher matcher = clusterPattern . matcher ( spec ) ; if ( ! matcher . find ( ) ) { logger . warn ( "Aurora recommended connection URL must only use cluster end-point like " + "\"jdbc:mariadb:aurora://xx.cluster-yy.zz.rds.amazonaws.com\". " + "Using end-point permit auto-discovery of new replicas" ) ; } } for ( String token : tokens ) { if ( token . startsWith ( "address=" ) ) { arr . add ( parseParameterHostAddress ( token ) ) ; } else { arr . add ( parseSimpleHostAddress ( token ) ) ; } } if ( haMode == HaMode . REPLICATION ) { for ( int i = 0 ; i < size ; i ++ ) { if ( i == 0 && arr . get ( i ) . type == null ) { arr . get ( i ) . type = ParameterConstant . TYPE_MASTER ; } else if ( i != 0 && arr . get ( i ) . type == null ) { arr . get ( i ) . type = ParameterConstant . TYPE_SLAVE ; } } } return arr ; } | parse - parse server addresses from the URL fragment . | 456 | 10 |
29,612 | public void writeTo ( final PacketOutputStream os ) throws IOException { os . write ( QUOTE ) ; os . write ( dateByteFormat ( ) ) ; os . write ( QUOTE ) ; } | Write to server OutputStream in text protocol . | 44 | 9 |
29,613 | public ServerPrepareResult read ( PacketInputStream reader , boolean eofDeprecated ) throws IOException , SQLException { Buffer buffer = reader . getPacket ( true ) ; byte firstByte = buffer . getByteAt ( buffer . position ) ; if ( firstByte == ERROR ) { throw buildErrorException ( buffer ) ; } if ( firstByte == OK ) { /* Prepared Statement OK */ buffer . readByte ( ) ; /* skip field count */ final int statementId = buffer . readInt ( ) ; final int numColumns = buffer . readShort ( ) & 0xffff ; final int numParams = buffer . readShort ( ) & 0xffff ; ColumnInformation [ ] params = new ColumnInformation [ numParams ] ; ColumnInformation [ ] columns = new ColumnInformation [ numColumns ] ; if ( numParams > 0 ) { for ( int i = 0 ; i < numParams ; i ++ ) { params [ i ] = new ColumnInformation ( reader . getPacket ( false ) ) ; } if ( numColumns > 0 ) { if ( ! eofDeprecated ) { protocol . skipEofPacket ( ) ; } for ( int i = 0 ; i < numColumns ; i ++ ) { columns [ i ] = new ColumnInformation ( reader . getPacket ( false ) ) ; } } if ( ! eofDeprecated ) { protocol . readEofPacket ( ) ; } } else { if ( numColumns > 0 ) { for ( int i = 0 ; i < numColumns ; i ++ ) { columns [ i ] = new ColumnInformation ( reader . getPacket ( false ) ) ; } if ( ! eofDeprecated ) { protocol . readEofPacket ( ) ; } } else { //read warning only if no param / columns, because will be overwritten by EOF warning data buffer . readByte ( ) ; // reserved protocol . setHasWarnings ( buffer . readShort ( ) > 0 ) ; } } ServerPrepareResult serverPrepareResult = new ServerPrepareResult ( sql , statementId , columns , params , protocol ) ; if ( protocol . getOptions ( ) . cachePrepStmts && protocol . getOptions ( ) . useServerPrepStmts && sql != null && sql . length ( ) < protocol . getOptions ( ) . prepStmtCacheSqlLimit ) { String key = protocol . getDatabase ( ) + "-" + sql ; ServerPrepareResult cachedServerPrepareResult = protocol . addPrepareInCache ( key , serverPrepareResult ) ; return cachedServerPrepareResult != null ? cachedServerPrepareResult : serverPrepareResult ; } return serverPrepareResult ; } else { throw new SQLException ( "Unexpected packet returned by server, first byte " + firstByte ) ; } } | Read COM_PREPARE_RESULT . | 606 | 10 |
29,614 | private static void resetHostList ( MastersSlavesListener listener , Deque < HostAddress > loopAddresses ) { //if all servers have been connected without result //add back all servers List < HostAddress > servers = new ArrayList <> ( ) ; servers . addAll ( listener . getUrlParser ( ) . getHostAddresses ( ) ) ; Collections . shuffle ( servers ) ; //remove current connected hosts to avoid reconnect them servers . removeAll ( listener . connectedHosts ( ) ) ; loopAddresses . clear ( ) ; loopAddresses . addAll ( servers ) ; } | Reinitialize loopAddresses with all servers in randomize order . | 123 | 14 |
29,615 | public void fireStatementClosed ( Statement st ) { if ( st instanceof PreparedStatement ) { StatementEvent event = new StatementEvent ( this , ( PreparedStatement ) st ) ; for ( StatementEventListener listener : statementEventListeners ) { listener . statementClosed ( event ) ; } } } | Fire statement close event to listeners . | 64 | 7 |
29,616 | public void fireStatementErrorOccured ( Statement st , SQLException ex ) { if ( st instanceof PreparedStatement ) { StatementEvent event = new StatementEvent ( this , ( PreparedStatement ) st , ex ) ; for ( StatementEventListener listener : statementEventListeners ) { listener . statementErrorOccurred ( event ) ; } } } | Fire statement error to listeners . | 74 | 6 |
29,617 | public void fireConnectionClosed ( ) { ConnectionEvent event = new ConnectionEvent ( this ) ; for ( ConnectionEventListener listener : connectionEventListeners ) { listener . connectionClosed ( event ) ; } } | Fire Connection close to listening listeners . | 44 | 7 |
29,618 | public void fireConnectionErrorOccured ( SQLException ex ) { ConnectionEvent event = new ConnectionEvent ( this , ex ) ; for ( ConnectionEventListener listener : connectionEventListeners ) { listener . connectionErrorOccurred ( event ) ; } } | Fire connection error to listening listeners . | 53 | 7 |
29,619 | protected void setTimerTask ( boolean isBatch ) { assert ( timerTaskFuture == null ) ; timerTaskFuture = timeoutScheduler . schedule ( ( ) -> { try { isTimedout = true ; if ( ! isBatch ) { protocol . cancelCurrentQuery ( ) ; } protocol . interrupt ( ) ; } catch ( Throwable e ) { //eat } } , queryTimeout , TimeUnit . SECONDS ) ; } | Part of query prolog - setup timeout timer | 93 | 9 |
29,620 | protected SQLException executeExceptionEpilogue ( SQLException sqle ) { //if has a failover, closing the statement if ( sqle . getSQLState ( ) != null && sqle . getSQLState ( ) . startsWith ( "08" ) ) { try { close ( ) ; } catch ( SQLException sqlee ) { //eat exception } } if ( isTimedout ) { return new SQLTimeoutException ( "(conn:" + getServerThreadId ( ) + ") Query timed out" , "JZ0002" , 1317 , sqle ) ; } SQLException sqlException = ExceptionMapper . getException ( sqle , connection , this , queryTimeout != 0 ) ; logger . error ( "error executing query" , sqlException ) ; return sqlException ; } | Reset timeout after query re - throw SQL exception . | 174 | 11 |
29,621 | @ Override public long executeLargeUpdate ( String sql ) throws SQLException { if ( executeInternal ( sql , fetchSize , Statement . NO_GENERATED_KEYS ) ) { return 0 ; } return getLargeUpdateCount ( ) ; } | Executes the given SQL statement which may be an INSERT UPDATE or DELETE statement or an SQL statement that returns nothing such as an SQL DDL statement . This method should be used when the returned row count may exceed Integer . MAX_VALUE . | 54 | 51 |
29,622 | public int getUpdateCount ( ) { if ( results != null && results . getCmdInformation ( ) != null && ! results . isBatch ( ) ) { return results . getCmdInformation ( ) . getUpdateCount ( ) ; } return - 1 ; } | Retrieves the current result as an update count ; if the result is a ResultSet object or there are no more results - 1 is returned . This method should be called only once per result . | 55 | 40 |
29,623 | @ Override public long getLargeUpdateCount ( ) { if ( results != null && results . getCmdInformation ( ) != null && ! results . isBatch ( ) ) { return results . getCmdInformation ( ) . getLargeUpdateCount ( ) ; } return - 1 ; } | Retrieves the current result as an update count ; if the result is a ResultSet object or there are no more results - 1 is returned . | 60 | 30 |
29,624 | private void internalBatchExecution ( int size ) throws SQLException { executeQueryPrologue ( true ) ; results = new Results ( this , 0 , true , size , false , resultSetScrollType , resultSetConcurrency , Statement . RETURN_GENERATED_KEYS , protocol . getAutoIncrementIncrement ( ) ) ; protocol . executeBatchStmt ( protocol . isMasterConnection ( ) , results , batchQueries ) ; results . commandEnd ( ) ; } | Internal batch execution . | 106 | 4 |
29,625 | public void checkCloseOnCompletion ( ResultSet resultSet ) throws SQLException { if ( mustCloseOnCompletion && ! closed && results != null && resultSet . equals ( results . getResultSet ( ) ) ) { close ( ) ; } } | Check that close on completion is asked and close if so . | 55 | 12 |
29,626 | public void initFunctionData ( int parametersCount ) { params = new CallParameter [ parametersCount ] ; for ( int i = 0 ; i < parametersCount ; i ++ ) { params [ i ] = new CallParameter ( ) ; if ( i > 0 ) { params [ i ] . setInput ( true ) ; } } // the query was in the form {?=call function()}, so the first parameter is always output params [ 0 ] . setOutput ( true ) ; } | Data initialisation when parameterCount is defined . | 101 | 9 |
29,627 | private void executeQueryPrologue ( ServerPrepareResult serverPrepareResult ) throws SQLException { executing = true ; if ( closed ) { throw new SQLException ( "execute() is called on closed statement" ) ; } protocol . prologProxy ( serverPrepareResult , maxRows , protocol . getProxy ( ) != null , connection , this ) ; } | must have lock locked before invoking | 81 | 6 |
29,628 | public static void printButtons ( int buttonNumber ) { boolean buttonPressed = false ; System . out . print ( "Button Pressed: " ) ; for ( int i = 0 ; i < 7 ; i ++ ) { if ( ( buttonNumber & ( 1 << i ) ) != 0 ) { System . out . println ( i + " " ) ; buttonPressed = true ; } } if ( ! buttonPressed ) { System . out . println ( "None " ) ; } } | This function prints out the button numbers from 0 through 6 | 105 | 11 |
29,629 | public static void transaction ( Runnable action , boolean readOnly ) { Ctx ctx = Ctxs . get ( ) ; boolean newContext = ctx == null ; if ( newContext ) { ctx = Ctxs . open ( "transaction" ) ; } try { EntityManager em = ctx . persister ( ) ; JPA . with ( em ) . transactional ( action , readOnly ) ; } finally { if ( newContext ) { Ctxs . close ( ) ; } } } | FIXME replace Runnable with Executable | 110 | 9 |
29,630 | public static synchronized void run ( String [ ] args , String ... extraArgs ) { AppStarter . startUp ( args , extraArgs ) ; // no implicit classpath scanning here boot ( ) ; // finish initialization and start the application onAppReady ( ) ; boot ( ) ; } | Initializes the app in non - atomic way . Then starts serving requests immediately when routes are configured . | 59 | 20 |
29,631 | public static synchronized void bootstrap ( String [ ] args , String ... extraArgs ) { AppStarter . startUp ( args , extraArgs ) ; boot ( ) ; App . scan ( ) ; // scan classpath for beans // finish initialization and start the application onAppReady ( ) ; boot ( ) ; } | Initializes the app in non - atomic way . Then scans the classpath for beans . Then starts serving requests immediately when routes are configured . | 65 | 28 |
29,632 | private V setValueInsideWriteLock ( V newValue ) { CachedValue < V > cached = cachedValue ; // read the cached value V oldValue = cached != null ? cached . value : null ; if ( newValue != null ) { long expiresAt = ttlInMs > 0 ? U . time ( ) + ttlInMs : Long . MAX_VALUE ; cachedValue = new CachedValue <> ( newValue , expiresAt ) ; } else { cachedValue = null ; } return oldValue ; } | Sets new cached value executes inside already acquired write lock . | 110 | 12 |
29,633 | public static Factory newInstance ( ) { ScheduledExecutorService scheduler = newSingleThreadScheduledExecutor ( new ThreadFactory ( ) { public Thread newThread ( Runnable r ) { Thread result = new Thread ( r ) ; result . setDaemon ( true ) ; return result ; } } ) ; Properties props = new Properties ( ) ; return new DefaultFactory ( scheduler , props ) ; } | Returns a new instance of a config Factory object . | 87 | 10 |
29,634 | @ SuppressWarnings ( "unchecked" ) public static < T extends Config > T remove ( Object key ) { return ( T ) CACHE . remove ( key ) ; } | Removes the cached instance for the given key if it is present . | 40 | 14 |
29,635 | public void parse ( Class clazz , PrintWriter output , String headerName , String projectName ) throws Exception { long startTime = System . currentTimeMillis ( ) ; Group [ ] groups = parseMethods ( clazz ) ; long finishTime = System . currentTimeMillis ( ) ; lastExecutionTime = finishTime - startTime ; String result = toPropertiesString ( groups , headerName , projectName ) ; writeProperties ( output , result ) ; } | Method to parse the class and write file in the choosen output . | 99 | 14 |
29,636 | private Group [ ] parseMethods ( Class clazz ) { List < Group > groups = new ArrayList ( ) ; Group unknownGroup = new Group ( ) ; groups . add ( unknownGroup ) ; String [ ] groupsOrder = new String [ 0 ] ; for ( Method method : clazz . getMethods ( ) ) { Property prop = new Property ( ) ; prop . deprecated = method . isAnnotationPresent ( Deprecated . class ) ; if ( method . isAnnotationPresent ( Key . class ) ) { Key val = method . getAnnotation ( Key . class ) ; prop . name = val . value ( ) ; } else { prop . name = method . getName ( ) ; } if ( method . isAnnotationPresent ( DefaultValue . class ) ) { DefaultValue val = method . getAnnotation ( DefaultValue . class ) ; prop . defaultValue = val . value ( ) ; } unknownGroup . properties . add ( prop ) ; } return orderGroup ( groups , groupsOrder ) ; } | Method to get group array with subgroups and properties . | 212 | 11 |
29,637 | private Group [ ] orderGroup ( List < Group > groups , String [ ] groupsOrder ) { LinkedList < Group > groupsOrdered = new LinkedList ( ) ; List < Group > remained = new ArrayList ( groups ) ; for ( String order : groupsOrder ) { for ( Group remain : remained ) { if ( remain . title . equals ( order ) ) { groupsOrdered . add ( remain ) ; remained . remove ( remain ) ; break ; } } } groupsOrdered . addAll ( remained ) ; return groupsOrdered . toArray ( new Group [ groupsOrdered . size ( ) ] ) ; } | Order groups based on passed order . | 132 | 7 |
29,638 | private String toPropertiesString ( Group [ ] groups , String headerName , String projectName ) { StringBuilder result = new StringBuilder ( ) ; result . append ( format ( header , headerName , projectName ) ) ; for ( Group group : groups ) { result . append ( group . toString ( ) ) ; } result . append ( generateFileFooter ( ) ) ; return result . toString ( ) ; } | Convert groups list into string . | 89 | 7 |
29,639 | public BigInteger getBytes ( ) { return value . multiply ( unit . getFactor ( ) ) . setScale ( 0 , RoundingMode . CEILING ) . toBigIntegerExact ( ) ; } | Returns the number of bytes that this byte size represents after multiplying the unit factor with the value . | 44 | 19 |
29,640 | String replace ( String source ) { if ( source == null ) return null ; Matcher m = PATTERN . matcher ( source ) ; StringBuffer sb = new StringBuffer ( ) ; while ( m . find ( ) ) { String var = m . group ( 1 ) ; String value = values . getProperty ( var ) ; String replacement = ( value != null ) ? replace ( value ) : "" ; m . appendReplacement ( sb , Matcher . quoteReplacement ( replacement ) ) ; } m . appendTail ( sb ) ; return sb . toString ( ) ; } | Replaces all the occurrences of variables with their matching values from the resolver using the given source string as a template . | 127 | 24 |
29,641 | public List < JApiClass > compare ( JApiCmpArchive oldArchive , JApiCmpArchive newArchive ) { return compare ( Collections . singletonList ( oldArchive ) , Collections . singletonList ( newArchive ) ) ; } | Compares the two given archives . | 57 | 7 |
29,642 | public List < JApiClass > compare ( List < JApiCmpArchive > oldArchives , List < JApiCmpArchive > newArchives ) { return createAndCompareClassLists ( toFileList ( oldArchives ) , toFileList ( newArchives ) ) ; } | Compares the two given lists of archives . | 64 | 9 |
29,643 | List < JApiClass > compareClassLists ( JarArchiveComparatorOptions options , List < CtClass > oldClasses , List < CtClass > newClasses ) { List < CtClass > oldClassesFiltered = applyFilter ( options , oldClasses ) ; List < CtClass > newClassesFiltered = applyFilter ( options , newClasses ) ; ClassesComparator classesComparator = new ClassesComparator ( this , options ) ; classesComparator . compare ( oldClassesFiltered , newClassesFiltered ) ; List < JApiClass > classList = classesComparator . getClasses ( ) ; if ( LOGGER . isLoggable ( Level . FINE ) ) { for ( JApiClass jApiClass : classList ) { LOGGER . fine ( jApiClass . toString ( ) ) ; } } checkBinaryCompatibility ( classList ) ; checkJavaObjectSerializationCompatibility ( classList ) ; OutputFilter . sortClassesAndMethods ( classList ) ; return classList ; } | Compares the two lists with CtClass objects using the provided options instance . | 224 | 15 |
29,644 | public Optional < CtClass > loadClass ( ArchiveType archiveType , String name ) { Optional < CtClass > loadedClass = Optional . absent ( ) ; if ( this . options . getClassPathMode ( ) == JarArchiveComparatorOptions . ClassPathMode . ONE_COMMON_CLASSPATH ) { try { loadedClass = Optional . of ( commonClassPool . get ( name ) ) ; } catch ( NotFoundException e ) { if ( ! options . getIgnoreMissingClasses ( ) . ignoreClass ( e . getMessage ( ) ) ) { throw JApiCmpException . forClassLoading ( e , name , this ) ; } } } else if ( this . options . getClassPathMode ( ) == JarArchiveComparatorOptions . ClassPathMode . TWO_SEPARATE_CLASSPATHS ) { if ( archiveType == ArchiveType . OLD ) { try { loadedClass = Optional . of ( oldClassPool . get ( name ) ) ; } catch ( NotFoundException e ) { if ( ! options . getIgnoreMissingClasses ( ) . ignoreClass ( e . getMessage ( ) ) ) { throw JApiCmpException . forClassLoading ( e , name , this ) ; } } } else if ( archiveType == ArchiveType . NEW ) { try { loadedClass = Optional . of ( newClassPool . get ( name ) ) ; } catch ( NotFoundException e ) { if ( ! options . getIgnoreMissingClasses ( ) . ignoreClass ( e . getMessage ( ) ) ) { throw JApiCmpException . forClassLoading ( e , name , this ) ; } } } else { throw new JApiCmpException ( Reason . IllegalState , "Unknown archive type: " + archiveType ) ; } } else { throw new JApiCmpException ( Reason . IllegalState , "Unknown classpath mode: " + this . options . getClassPathMode ( ) ) ; } return loadedClass ; } | Loads a class either from the old new or common classpath . | 423 | 14 |
29,645 | private boolean isImplemented ( JApiMethod jApiMethod ) { JApiClass aClass = jApiMethod . getjApiClass ( ) ; while ( aClass != null ) { for ( JApiMethod method : aClass . getMethods ( ) ) { if ( jApiMethod . getName ( ) . equals ( method . getName ( ) ) && jApiMethod . hasSameParameter ( method ) && ! isAbstract ( method ) && method . getChangeStatus ( ) != JApiChangeStatus . REMOVED && isNotPrivate ( method ) ) { return true ; } } if ( aClass . getSuperclass ( ) != null && aClass . getSuperclass ( ) . getJApiClass ( ) . isPresent ( ) ) { aClass = aClass . getSuperclass ( ) . getJApiClass ( ) . get ( ) ; } else { aClass = null ; } } return false ; } | Is a method implemented in a super class | 202 | 8 |
29,646 | private void emitLoop ( ) { for ( ; ; ) { AppendOnlyLinkedArrayList < T > q ; synchronized ( this ) { q = queue ; if ( q == null ) { emitting = false ; return ; } queue = null ; } q . accept ( actual ) ; } } | Loops until all notifications in the queue has been processed . | 62 | 12 |
29,647 | public int geneCount ( ) { int count = 0 ; for ( int i = 0 , n = _chromosomes . length ( ) ; i < n ; ++ i ) { count += _chromosomes . get ( i ) . length ( ) ; } return count ; } | Return the number of genes this genotype consists of . This is the sum of the number of genes of the genotype chromosomes . | 59 | 26 |
29,648 | @ Override public void accept ( final C object ) { _min = min ( _comparator , _min , object ) ; _max = max ( _comparator , _max , object ) ; ++ _count ; } | Accept the element for min - max calculation . | 49 | 9 |
29,649 | public int [ ] toArray ( final int [ ] array ) { final int [ ] a = array . length >= length ( ) ? array : new int [ length ( ) ] ; for ( int i = length ( ) ; -- i >= 0 ; ) { a [ i ] = intValue ( i ) ; } return a ; } | Returns an int array containing all of the elements in this chromosome in proper sequence . If the chromosome fits in the specified array it is returned therein . Otherwise a new array is allocated with the length of this chromosome . | 70 | 42 |
29,650 | public DoubleAdder add ( final double [ ] values ) { for ( int i = values . length ; -- i >= 0 ; ) { add ( values [ i ] ) ; } return this ; } | Add the given values to this adder . | 42 | 9 |
29,651 | public void draw ( final Graphics2D g , final int width , final int height ) { g . setColor ( new Color ( _data [ 0 ] , _data [ 1 ] , _data [ 2 ] , _data [ 3 ] ) ) ; final GeneralPath path = new GeneralPath ( ) ; path . moveTo ( _data [ 4 ] * width , _data [ 5 ] * height ) ; for ( int j = 1 ; j < _length ; ++ j ) { path . lineTo ( _data [ 4 + j * 2 ] * width , _data [ 5 + j * 2 ] * height ) ; } path . closePath ( ) ; g . fill ( path ) ; } | Draw the Polygon to the buffer of the given size . | 148 | 12 |
29,652 | public static Polygon newRandom ( final int length , final Random random ) { require . positive ( length ) ; final Polygon p = new Polygon ( length ) ; p . _data [ 0 ] = random . nextFloat ( ) ; // r p . _data [ 1 ] = random . nextFloat ( ) ; // g p . _data [ 2 ] = random . nextFloat ( ) ; // b p . _data [ 3 ] = max ( 0.2F , random . nextFloat ( ) * random . nextFloat ( ) ) ; // a float px = 0.5F ; float py = 0.5F ; for ( int k = 0 ; k < length ; k ++ ) { p . _data [ 4 + 2 * k ] = px = clamp ( px + random . nextFloat ( ) - 0.5F ) ; p . _data [ 5 + 2 * k ] = py = clamp ( py + random . nextFloat ( ) - 0.5F ) ; } return p ; } | Creates a new random Polygon of the given length . | 219 | 12 |
29,653 | public void create ( final Path data , final Path output ) throws IOException { _parameters . put ( DATA_NAME , data . toString ( ) ) ; _parameters . put ( OUTPUT_NAME , output . toString ( ) ) ; final String params = _parameters . entrySet ( ) . stream ( ) . map ( Gnuplot :: toParamString ) . collect ( Collectors . joining ( "; " ) ) ; String script = new String ( Files . readAllBytes ( _template ) ) ; for ( Map . Entry < String , String > entry : _environment . entrySet ( ) ) { final String key = format ( "${%s}" , entry . getKey ( ) ) ; script = script . replace ( key , entry . getValue ( ) ) ; } final Path scriptPath = tempPath ( ) ; try { IO . write ( script , scriptPath ) ; final List < String > command = Arrays . asList ( "gnuplot" , "-e" , params , scriptPath . toString ( ) ) ; final Process process = new ProcessBuilder ( ) . command ( command ) . start ( ) ; System . out . println ( IO . toText ( process . getErrorStream ( ) ) ) ; try { process . waitFor ( ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; } } finally { deleteIfExists ( scriptPath ) ; } } | Generate the Gnuplot graph . | 308 | 8 |
29,654 | public static Timer of ( final Clock clock ) { requireNonNull ( clock ) ; return clock instanceof NanoClock ? new Timer ( System :: nanoTime ) : new Timer ( ( ) -> nanos ( clock ) ) ; } | Return an new timer object which uses the given clock for measuring the execution time . | 50 | 16 |
29,655 | private void adjustMarkerHeights ( ) { double mm = _n [ 1 ] - 1.0 ; double mp = _n [ 1 ] + 1.0 ; if ( _nn [ 0 ] >= mp && _n [ 2 ] > mp ) { _q [ 1 ] = qPlus ( mp , _n [ 0 ] , _n [ 1 ] , _n [ 2 ] , _q [ 0 ] , _q [ 1 ] , _q [ 2 ] ) ; _n [ 1 ] = mp ; } else if ( _nn [ 0 ] <= mm && _n [ 0 ] < mm ) { _q [ 1 ] = qMinus ( mm , _n [ 0 ] , _n [ 1 ] , _n [ 2 ] , _q [ 0 ] , _q [ 1 ] , _q [ 2 ] ) ; _n [ 1 ] = mm ; } mm = _n [ 2 ] - 1.0 ; mp = _n [ 2 ] + 1.0 ; if ( _nn [ 1 ] >= mp && _n [ 3 ] > mp ) { _q [ 2 ] = qPlus ( mp , _n [ 1 ] , _n [ 2 ] , _n [ 3 ] , _q [ 1 ] , _q [ 2 ] , _q [ 3 ] ) ; _n [ 2 ] = mp ; } else if ( _nn [ 1 ] <= mm && _n [ 1 ] < mm ) { _q [ 2 ] = qMinus ( mm , _n [ 1 ] , _n [ 2 ] , _n [ 3 ] , _q [ 1 ] , _q [ 2 ] , _q [ 3 ] ) ; _n [ 2 ] = mm ; } mm = _n [ 3 ] - 1.0 ; mp = _n [ 3 ] + 1.0 ; if ( _nn [ 2 ] >= mp && _n [ 4 ] > mp ) { _q [ 3 ] = qPlus ( mp , _n [ 2 ] , _n [ 3 ] , _n [ 4 ] , _q [ 2 ] , _q [ 3 ] , _q [ 4 ] ) ; _n [ 3 ] = mp ; } else if ( _nn [ 2 ] <= mm && _n [ 2 ] < mm ) { _q [ 3 ] = qMinus ( mm , _n [ 2 ] , _n [ 3 ] , _n [ 4 ] , _q [ 2 ] , _q [ 3 ] , _q [ 4 ] ) ; _n [ 3 ] = mm ; } } | Adjust heights of markers 0 to 2 if necessary | 547 | 9 |
29,656 | private static < G extends Gene < ? , G > , C extends Comparable < ? super C > > ISeq < C > batchEval ( final Seq < Genotype < G > > genotypes , final Function < ? super Genotype < G > , ? extends C > function ) { return genotypes . < C > map ( function ) . asISeq ( ) ; } | Not really batch eval . Just for testing . | 81 | 9 |
29,657 | @ SafeVarargs public static < G extends Gene < ? , G > , C extends Comparable < ? super C > > ConcatEngine < G , C > of ( final EvolutionStreamable < G , C > ... engines ) { return new ConcatEngine <> ( Arrays . asList ( engines ) ) ; } | Create a new concatenating evolution engine with the given array of engines . | 68 | 15 |
29,658 | public static TravelingSalesman of ( int stops , double radius ) { final MSeq < double [ ] > points = MSeq . ofLength ( stops ) ; final double delta = 2.0 * PI / stops ; for ( int i = 0 ; i < stops ; ++ i ) { final double alpha = delta * i ; final double x = cos ( alpha ) * radius + radius ; final double y = sin ( alpha ) * radius + radius ; points . set ( i , new double [ ] { x , y } ) ; } // Shuffling of the created points. final Random random = RandomRegistry . getRandom ( ) ; for ( int j = points . length ( ) - 1 ; j > 0 ; -- j ) { final int i = random . nextInt ( j + 1 ) ; final double [ ] tmp = points . get ( i ) ; points . set ( i , points . get ( j ) ) ; points . set ( j , tmp ) ; } return new TravelingSalesman ( points . toISeq ( ) ) ; } | of stops . All stops lie on a circle with the given radius . | 226 | 14 |
29,659 | public Optional < String > arg ( final String name ) { int index = _args . indexOf ( "--" + name ) ; if ( index == - 1 ) index = _args . indexOf ( "-" + name ) ; return index >= 0 && index < _args . length ( ) - 1 ? Optional . of ( _args . get ( index + 1 ) ) : Optional . empty ( ) ; } | Return the parameter with the given name . | 87 | 8 |
29,660 | public Optional < Integer > intArg ( final String name ) { return arg ( name ) . flatMap ( s -> parse ( s , Integer :: valueOf ) ) ; } | Return the int - argument with the given name . | 36 | 10 |
29,661 | public Optional < Long > longArg ( final String name ) { return arg ( name ) . flatMap ( s -> parse ( s , Long :: valueOf ) ) ; } | Return the long - argument with the given name . | 36 | 10 |
29,662 | public Optional < Double > doubleArg ( final String name ) { return arg ( name ) . flatMap ( s -> parse ( s , Double :: valueOf ) ) ; } | Return the double - argument with the given name . | 36 | 10 |
29,663 | public static double min ( final double [ ] values ) { double min = NaN ; if ( values . length > 0 ) { min = values [ 0 ] ; for ( int i = 0 ; i < values . length ; ++ i ) { if ( values [ i ] < min ) { min = values [ i ] ; } } } return min ; } | Return the minimum value of the given double array . | 75 | 10 |
29,664 | public static < A , G extends Gene < A , G > , C extends Chromosome < G > > List < io . jenetics . Genotype < G > > read ( final InputStream in , final Reader < ? extends C > chromosomeReader ) throws XMLStreamException { return Genotypes . read ( in , chromosomeReader ) ; } | Reads the genotypes by using the given chromosome reader . | 72 | 12 |
29,665 | public char [ ] toArray ( final char [ ] array ) { final char [ ] a = array . length >= length ( ) ? array : new char [ length ( ) ] ; for ( int i = length ( ) ; -- i >= 0 ; ) { a [ i ] = charAt ( i ) ; } return a ; } | Returns an char array containing all of the elements in this chromosome in proper sequence . If the chromosome fits in the specified array it is returned therein . Otherwise a new array is allocated with the length of this chromosome . | 70 | 42 |
29,666 | public static < G extends Gene < ? , G > , C extends Comparable < ? super C > > AdaptiveEngine < G , C > of ( final Function < ? super EvolutionResult < G , C > , ? extends EvolutionStreamable < G , C > > engine ) { return new AdaptiveEngine <> ( engine ) ; } | Return a new adaptive evolution engine with the given engine generation function . | 71 | 13 |
29,667 | public static PermutationChromosome < Integer > ofInteger ( final int start , final int end ) { if ( end <= start ) { throw new IllegalArgumentException ( format ( "end <= start: %d <= %d" , end , start ) ) ; } return ofInteger ( IntRange . of ( start , end ) , end - start ) ; } | Create an integer permutation chromosome with the given range . | 79 | 11 |
29,668 | public static PermutationChromosome < Integer > ofInteger ( final IntRange range , final int length ) { return of ( range . stream ( ) . boxed ( ) . collect ( ISeq . toISeq ( ) ) , length ) ; } | Create an integer permutation chromosome with the given range and length | 54 | 12 |
29,669 | private static ISeq < WayPoint > districtCapitals ( ) throws IOException { final String capitals = "/io/jenetics/example/DistrictCapitals.gpx" ; try ( InputStream in = TravelingSalesman . class . getResourceAsStream ( capitals ) ) { return ISeq . of ( GPX . read ( in ) . getWayPoints ( ) ) ; } } | Return the district capitals we want to visit . | 82 | 9 |
29,670 | public static < A > EnumGene < A > of ( final ISeq < ? extends A > validAlleles ) { return new EnumGene <> ( RandomRegistry . getRandom ( ) . nextInt ( validAlleles . length ( ) ) , validAlleles ) ; } | Return a new enum gene with an allele randomly chosen from the given valid alleles . | 64 | 17 |
29,671 | @ SafeVarargs public static < A > EnumGene < A > of ( final int alleleIndex , final A ... validAlleles ) { return new EnumGene <> ( alleleIndex , ISeq . of ( validAlleles ) ) ; } | Create a new enum gene from the given valid genes and the chosen allele index . | 55 | 16 |
29,672 | public double [ ] toArray ( final double [ ] array ) { final double [ ] a = array . length >= length ( ) ? array : new double [ length ( ) ] ; for ( int i = length ( ) ; -- i >= 0 ; ) { a [ i ] = doubleValue ( i ) ; } return a ; } | Returns an double array containing all of the elements in this chromosome in proper sequence . If the chromosome fits in the specified array it is returned therein . Otherwise a new array is allocated with the length of this chromosome . | 70 | 42 |
29,673 | public static < C extends Comparable < ? super C > > Collector < C , ? , ParetoFront < C > > toParetoFront ( ) { return toParetoFront ( Comparator . naturalOrder ( ) ) ; } | Return a pareto - front collector . The natural order of the elements is used as pareto - dominance order . | 52 | 25 |
29,674 | public static < C extends Comparable < ? super C > > Predicate < EvolutionResult < ? , C > > byFitnessThreshold ( final C threshold ) { return new FitnessThresholdLimit <> ( threshold ) ; } | Return a predicate which will truncated the evolution stream if the best fitness of the current population becomes less than the specified threshold and the objective is set to minimize the fitness . This predicate also stops the evolution if the best fitness in the current population becomes greater than the user - specified fitness threshold when the objective is to maximize the fitness . | 48 | 66 |
29,675 | public static < N extends Number & Comparable < ? super N > > Predicate < EvolutionResult < ? , N > > byFitnessConvergence ( final int shortFilterSize , final int longFilterSize , final BiPredicate < DoubleMoments , DoubleMoments > proceed ) { return new FitnessConvergenceLimit <> ( shortFilterSize , longFilterSize , proceed ) ; } | Return a predicate which will truncate the evolution stream if the fitness is converging . Two filters of different lengths are used to smooth the best fitness across the generations . | 83 | 33 |
29,676 | public static < N extends Number & Comparable < ? super N > > Predicate < EvolutionResult < ? , N > > byFitnessConvergence ( final int shortFilterSize , final int longFilterSize , final double epsilon ) { if ( epsilon < 0.0 || epsilon > 1.0 ) { throw new IllegalArgumentException ( format ( "The given epsilon is not in the range [0, 1]: %f" , epsilon ) ) ; } return new FitnessConvergenceLimit <> ( shortFilterSize , longFilterSize , ( s , l ) -> eps ( s . getMean ( ) , l . getMean ( ) ) >= epsilon ) ; } | Return a predicate which will truncate the evolution stream if the fitness is converging . Two filters of different lengths are used to smooth the best fitness across the generations . When the smoothed best fitness from the long filter is less than a user - specified percentage away from the smoothed best fitness from the short filter the fitness is deemed as converged and the evolution terminates . | 157 | 75 |
29,677 | private static double eps ( final double s , final double l ) { final double div = max ( abs ( s ) , abs ( l ) ) ; return abs ( s - l ) / ( div <= 10E-20 ? 1.0 : div ) ; } | Calculate the relative mean difference between short and long filter . | 56 | 13 |
29,678 | public static < N extends Number & Comparable < ? super N > > Predicate < EvolutionResult < ? , N > > byPopulationConvergence ( final double epsilon ) { if ( epsilon < 0.0 || epsilon > 1.0 ) { throw new IllegalArgumentException ( format ( "The given epsilon is not in the range [0, 1]: %f" , epsilon ) ) ; } return new PopulationConvergenceLimit <> ( ( best , moments ) -> eps ( best , moments . getMean ( ) ) >= epsilon ) ; } | A termination method that stops the evolution when the population is deemed as converged . The population is deemed as converged when the average fitness across the current population is less than a user - specified percentage away from the best fitness of the current population . | 130 | 49 |
29,679 | @ SafeVarargs static < G extends Gene < ? , G > , C extends Comparable < ? super C > > CompositeAlterer < G , C > of ( final Alterer < G , C > ... alterers ) { return new CompositeAlterer <> ( ISeq . of ( alterers ) ) ; } | Combine the given alterers . | 67 | 7 |
29,680 | static < T extends Gene < ? , T > , C extends Comparable < ? super C > > CompositeAlterer < T , C > join ( final Alterer < T , C > a1 , final Alterer < T , C > a2 ) { return CompositeAlterer . of ( a1 , a2 ) ; } | Joins the given alterer and returns a new CompositeAlterer object . If one of the given alterers is a CompositeAlterer the sub alterers of it are unpacked and appended to the newly created CompositeAlterer . | 69 | 47 |
29,681 | @ Deprecated public Phenotype < G , C > newInstance ( final long generation , final Function < ? super Genotype < G > , ? extends C > function , final Function < ? super C , ? extends C > scaler ) { return of ( _genotype , generation , function , scaler ) ; } | Return a new phenotype with the the genotype of this and with new fitness function fitness scaler and generation . | 66 | 22 |
29,682 | @ Deprecated public Phenotype < G , C > newInstance ( final long generation , final Function < ? super Genotype < G > , ? extends C > function ) { return of ( _genotype , generation , function , a -> a ) ; } | Return a new phenotype with the the genotype of this and with new fitness function and generation . | 53 | 19 |
29,683 | public static < G extends Gene < ? , G > , C extends Comparable < ? super C > > Phenotype < G , C > of ( final Genotype < G > genotype , final long generation , final Function < ? super Genotype < G > , ? extends C > function , final Function < ? super C , ? extends C > scaler ) { return new Phenotype <> ( genotype , generation , function , scaler , null ) ; } | Create a new phenotype from the given arguments . | 97 | 9 |
29,684 | public static TreePattern compile ( final String pattern ) { return new TreePattern ( TreeNode . parse ( pattern , Decl :: of ) ) ; } | Compiles the given tree pattern string . | 30 | 8 |
29,685 | public void sort ( final int from , final int until , final Comparator < ? super T > comparator ) { _store . sort ( from + _start , until + _start , comparator ) ; } | Sort the store . | 44 | 4 |
29,686 | public static < T > TrialMeter < T > of ( final String name , final String description , final Params < T > params , final String ... dataSetNames ) { return new TrialMeter < T > ( name , description , Env . of ( ) , params , DataSet . of ( params . size ( ) , dataSetNames ) ) ; } | Return a new trial measure environment . | 77 | 7 |
29,687 | private static Integer count ( final Genotype < BitGene > gt ) { return gt . getChromosome ( ) . as ( BitChromosome . class ) . bitCount ( ) ; } | This method calculates the fitness for a given genotype . | 45 | 11 |
29,688 | private void accept ( final EvolutionDurations durations ) { final double selection = toSeconds ( durations . getOffspringSelectionDuration ( ) ) + toSeconds ( durations . getSurvivorsSelectionDuration ( ) ) ; final double alter = toSeconds ( durations . getOffspringAlterDuration ( ) ) + toSeconds ( durations . getOffspringFilterDuration ( ) ) ; _selectionDuration . accept ( selection ) ; _alterDuration . accept ( alter ) ; _evaluationDuration . accept ( toSeconds ( durations . getEvaluationDuration ( ) ) ) ; _evolveDuration . accept ( toSeconds ( durations . getEvolveDuration ( ) ) ) ; } | Calculate duration statistics | 154 | 5 |
29,689 | private EvolutionResult < BitGene , Double > run ( final EvolutionResult < BitGene , Double > last , final AtomicBoolean proceed ) { System . out . println ( "Starting evolution with existing result." ) ; return ( last != null ? ENGINE . stream ( last ) : ENGINE . stream ( ) ) . limit ( r -> proceed . get ( ) ) . collect ( EvolutionResult . toBestEvolutionResult ( ) ) ; } | Run the evolution . | 92 | 4 |
29,690 | @ Override public void accept ( final double value ) { super . accept ( value ) ; _min = Math . min ( _min , value ) ; _max = Math . max ( _max , value ) ; _sum . add ( value ) ; } | Records a new value into the moments information | 54 | 9 |
29,691 | public BitSet toBitSet ( ) { final BitSet set = new BitSet ( length ( ) ) ; for ( int i = 0 , n = length ( ) ; i < n ; ++ i ) { set . set ( i , getGene ( i ) . getBit ( ) ) ; } return set ; } | Return the corresponding BitSet of this BitChromosome . | 67 | 13 |
29,692 | public BitChromosome invert ( ) { final byte [ ] data = _genes . clone ( ) ; bit . invert ( data ) ; return new BitChromosome ( data , _length , 1.0 - _p ) ; } | Invert the ones and zeros of this bit chromosome . | 55 | 12 |
29,693 | public static BitChromosome of ( final int length , final double p ) { return new BitChromosome ( bit . newArray ( length , p ) , length , p ) ; } | Construct a new BitChromosome with the given _length . | 42 | 14 |
29,694 | public void forEach ( final IntConsumer action ) { requireNonNull ( action ) ; final int size = _size ; for ( int i = 0 ; i < size ; ++ i ) { action . accept ( _data [ i ] ) ; } } | Performs the given action for each element of the list . | 53 | 12 |
29,695 | public boolean addAll ( final int [ ] elements ) { final int count = elements . length ; ensureSize ( _size + count ) ; arraycopy ( elements , 0 , _data , _size , count ) ; _size += count ; return count != 0 ; } | Appends all of the elements in the specified array to the end of this list . | 56 | 17 |
29,696 | public boolean addAll ( final int index , final int [ ] elements ) { addRangeCheck ( index ) ; final int count = elements . length ; ensureSize ( _size + count ) ; final int moved = _size - index ; if ( moved > 0 ) { arraycopy ( _data , index , _data , index + count , moved ) ; } arraycopy ( elements , 0 , _data , index , count ) ; _size += count ; return count != 0 ; } | Inserts all of the elements in the specified array into this list starting at the specified position . | 101 | 19 |
29,697 | @ Override public G getChild ( final int index ) { checkTreeState ( ) ; if ( index < 0 || index >= childCount ( ) ) { throw new IndexOutOfBoundsException ( format ( "Child index out of bounds: %s" , index ) ) ; } assert _genes != null ; return _genes . get ( _childOffset + index ) ; } | Return the child gene with the given index . | 82 | 9 |
29,698 | @ SuppressWarnings ( "deprecation" ) protected MutatorResult < Phenotype < G , C > > mutate ( final Phenotype < G , C > phenotype , final long generation , final double p , final Random random ) { return mutate ( phenotype . getGenotype ( ) , p , random ) . map ( gt -> phenotype . newInstance ( gt , generation ) ) ; } | Mutates the given phenotype . | 87 | 6 |
29,699 | protected MutatorResult < Genotype < G > > mutate ( final Genotype < G > genotype , final double p , final Random random ) { final int P = probability . toInt ( p ) ; final ISeq < MutatorResult < Chromosome < G > > > result = genotype . toSeq ( ) . map ( gt -> random . nextInt ( ) < P ? mutate ( gt , p , random ) : MutatorResult . of ( gt ) ) ; return MutatorResult . of ( Genotype . of ( result . map ( MutatorResult :: getResult ) ) , result . stream ( ) . mapToInt ( MutatorResult :: getMutations ) . sum ( ) ) ; } | Mutates the given genotype . | 157 | 7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.