idx
int64
0
41.2k
question
stringlengths
74
4.04k
target
stringlengths
7
750
40,600
public SettingsPack connectionsLimit ( int value ) { sp . set_int ( settings_pack . int_types . connections_limit . swigValue ( ) , value ) ; return this ; }
Sets a global limit on the number of connections opened . The number of connections is set to a hard minimum of at least two per torrent so if you set a too low connections limit and open too many torrents the limit will not be met .
40,601
public SettingsPack maxPeerlistSize ( int value ) { sp . set_int ( settings_pack . int_types . max_peerlist_size . swigValue ( ) , value ) ; return this ; }
Sets the maximum number of peers in the list of known peers . These peers are not necessarily connected so this number should be much greater than the maximum number of connected peers . Peers are evicted from the cache when the list grows passed 90% of this limit and once the size hits the limit peers are no longer added to the list . If this limit is set to 0 there is no limit on how many peers we ll keep in the peer list .
40,602
public SettingsPack inactivityTimeout ( int value ) { sp . set_int ( settings_pack . int_types . inactivity_timeout . swigValue ( ) , value ) ; return this ; }
if a peer is uninteresting and uninterested for longer than this number of seconds it will be disconnected . default is 10 minutes
40,603
public SettingsPack enableDht ( boolean value ) { sp . set_bool ( settings_pack . bool_types . enable_dht . swigValue ( ) , value ) ; return this ; }
Starts the dht node and makes the trackerless service available to torrents .
40,604
public SettingsPack upnpIgnoreNonRouters ( boolean value ) { sp . set_bool ( settings_pack . bool_types . upnp_ignore_nonrouters . swigValue ( ) , value ) ; return this ; }
Indicates whether or not the UPnP implementation should ignore any broadcast response from a device whose address is not the configured router for this machine . i . e . it s a way to not talk to other people s routers by mistake .
40,605
public TorrentBuilder addNode ( Pair < String , Integer > value ) { if ( value != null ) { this . nodes . add ( value ) ; } return this ; }
This adds a DHT node to the torrent . This especially useful if you re creating a tracker less torrent . It can be used by clients to bootstrap their DHT node from . The node is a hostname and a port number where there is a DHT node running . You can have any number of DHT nodes in a torrent .
40,606
public Result generate ( ) throws IOException { if ( path == null ) { throw new IOException ( "path can't be null" ) ; } File absPath = path . getAbsoluteFile ( ) ; file_storage fs = new file_storage ( ) ; add_files_listener l1 = new add_files_listener ( ) { public boolean pred ( String p ) { return listener != null ? listener . accept ( p ) : true ; } } ; add_files_ex ( fs , absPath . getPath ( ) , l1 , flags ) ; if ( fs . total_size ( ) == 0 ) { throw new IOException ( "content total size can't be 0" ) ; } create_torrent t = new create_torrent ( fs , pieceSize , padFileLimit , flags , alignment ) ; final int numPieces = t . num_pieces ( ) ; set_piece_hashes_listener l2 = new set_piece_hashes_listener ( ) { public void progress ( int i ) { if ( listener != null ) { listener . progress ( i , numPieces ) ; } } } ; File parent = absPath . getParentFile ( ) ; if ( parent == null ) { throw new IOException ( "path's parent can't be null" ) ; } error_code ec = new error_code ( ) ; set_piece_hashes_ex ( t , parent . getAbsolutePath ( ) , l2 , ec ) ; if ( ec . value ( ) != 0 ) { throw new IOException ( ec . message ( ) ) ; } if ( comment != null ) { t . set_comment ( comment ) ; } if ( creator != null ) { t . set_creator ( creator ) ; } for ( String s : urlSeeds ) { t . add_url_seed ( s ) ; } for ( String s : httpSeeds ) { t . add_http_seed ( s ) ; } for ( Pair < String , Integer > n : nodes ) { t . add_node ( n . to_string_int_pair ( ) ) ; } for ( Pair < String , Integer > tr : trackers ) { t . add_tracker ( tr . first , tr . second ) ; } if ( priv ) { t . set_priv ( priv ) ; } if ( ! similarTorrents . isEmpty ( ) ) { for ( Sha1Hash h : similarTorrents ) { t . add_similar_torrent ( h . swig ( ) ) ; } } if ( ! collections . isEmpty ( ) ) { for ( String s : collections ) { t . add_collection ( s ) ; } } return new Result ( t ) ; }
This function will generate a result withe the . torrent file as a bencode tree .
40,607
public static byte [ ] bytes ( File file ) throws IOException { InputStream in = null ; try { in = openInputStream ( file ) ; return toByteArray ( in , file . length ( ) ) ; } finally { closeQuietly ( in ) ; } }
Reads the contents of a file into a byte array . The file is always closed .
40,608
public Priority [ ] filePriorities ( ) { int_vector v = th . get_file_priorities2 ( ) ; int size = ( int ) v . size ( ) ; Priority [ ] arr = new Priority [ size ] ; for ( int i = 0 ; i < size ; i ++ ) { arr [ i ] = Priority . fromSwig ( v . get ( i ) ) ; } return arr ; }
Returns a vector with the priorities of all files .
40,609
public String name ( ) { torrent_status ts = th . status ( torrent_handle . query_name ) ; return ts . getName ( ) ; }
The name of the torrent . Typically this is derived from the . torrent file . In case the torrent was started without metadata and hasn t completely received it yet it returns the name given to it when added to the session .
40,610
public static < T , S extends T > Optional < T > of ( S value ) { if ( value == null ) { throw new IllegalArgumentException ( "Optional does not support NULL, use Optional.empty() instead." ) ; } return new Optional < T > ( value ) ; }
Create a new Optional containing value .
40,611
public ErrorResponse parseError ( Response response ) { if ( response . isSuccessful ( ) ) { throw new IllegalArgumentException ( "Response must be unsuccessful." ) ; } Converter < ResponseBody , ErrorResponse > responseBodyObjectConverter = retrofit . responseBodyConverter ( ErrorResponse . class , new Annotation [ 0 ] ) ; try { return responseBodyObjectConverter . convert ( response . errorBody ( ) ) ; } catch ( IOException ex ) { throw new RuntimeException ( "Could not parse error response" , ex ) ; } }
A helper to assist with decoding unsuccessful responses .
40,612
public static void notEmpty ( Collection collection , String name ) { notNull ( collection , name ) ; if ( collection . isEmpty ( ) ) { throw new IllegalArgumentException ( name + " must not be empty" ) ; } }
Checks that a given collection is not null and not empty .
40,613
public static void notEmpty ( Object [ ] arr , String name ) { notNull ( arr , name ) ; if ( arr . length == 0 ) { throw new IllegalArgumentException ( name + "must not be empty" ) ; } }
Checks that a given array is not null and not empty .
40,614
public static void notEmpty ( Map map , String name ) { notNull ( map , name ) ; if ( map . isEmpty ( ) ) { throw new IllegalArgumentException ( name + " must not be empty" ) ; } }
Checks that a given map is not null and not empty .
40,615
public static void isBetween ( Integer value , int min , int max , String name ) { notNull ( value , name ) ; if ( value < min || value > max ) { throw new IllegalArgumentException ( name + "(" + value + ") out of range: " + min + " <= " + name + " <= " + max ) ; } }
Checks that i is not null and is in the range min &lt ; = i &lt ; = max .
40,616
public static void isPositive ( Integer value , String name ) { notNull ( value , name ) ; if ( value < 0 ) { throw new IllegalArgumentException ( name + "must be a positive number." ) ; } }
Checks that i is not null and is a positive number
40,617
public static Map < String , String > arrayToMap ( String [ ] args ) { if ( args . length % 2 != 0 ) { throw new IllegalArgumentException ( "Must pass in an even number of args, one key per value." ) ; } Map < String , String > ret = new HashMap < > ( ) ; for ( int i = 0 ; i < args . length ; i += 2 ) { ret . put ( args [ i ] , args [ i + 1 ] ) ; } return ret ; }
Helper to convert an alternating key1 value1 key2 value2 ... array into a map .
40,618
private static < T > int binarySearch0 ( Sortable < T > a , int fromIndex , int toIndex , T key , Comparator < ? super T > c ) { if ( c == null ) { throw new NullPointerException ( ) ; } int low = fromIndex ; int high = toIndex - 1 ; while ( low <= high ) { int mid = ( low + high ) >>> 1 ; T midVal = a . at ( mid ) ; int cmp = c . compare ( midVal , key ) ; if ( cmp < 0 ) low = mid + 1 ; else if ( cmp > 0 ) high = mid - 1 ; else return mid ; } return - ( low + 1 ) ; }
Like public version but without range checks .
40,619
public void addState ( ) { DiffHistoryDataState nextState = new DiffHistoryDataState ( stateEngine , typeDiffInstructions ) ; if ( currentDataState != null ) newHistoricalState ( currentDataState , nextState ) ; currentDataState = nextState ; }
Call this method after new data has been loaded by the FastBlobStateEngine . This will add a historical record of the differences between the previous state and this new state .
40,620
public String generateDiff ( String objectType , Object from , Object to ) { GenericObject fromGenericObject = from == null ? null : genericObjectFramework . serialize ( from , objectType ) ; GenericObject toGenericObject = to == null ? null : genericObjectFramework . serialize ( to , objectType ) ; return generateDiff ( fromGenericObject , toGenericObject ) ; }
Generate the HTML difference between two objects .
40,621
public String generateDiff ( GenericObject from , GenericObject to ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( "<table class=\"nomargin diff\">" ) ; builder . append ( "<thead>" ) ; builder . append ( "<tr>" ) ; builder . append ( "<th/>" ) ; builder . append ( "<th class=\"texttitle\">From</th>" ) ; builder . append ( "<th/>" ) ; builder . append ( "<th class=\"texttitle\">To</th>" ) ; builder . append ( "</tr>" ) ; builder . append ( "</thead>" ) ; builder . append ( "<tbody>" ) ; writeDiff ( builder , from , to ) ; builder . append ( "</tbody>" ) ; builder . append ( "</table>" ) ; return builder . toString ( ) ; }
Generate the HTML difference between two GenericObjects .
40,622
public DiffReport performDiff ( FastBlobStateEngine fromState , FastBlobStateEngine toState ) throws DiffReportGenerationException { return performDiff ( null , fromState , toState ) ; }
Perform a diff between two data states .
40,623
public void runCycle ( int ... valuesForMap ) { HeapFriendlyMapArrayRecycler . get ( ) . swapCycleObjectArrays ( ) ; try { makeDataAvailableToApplication ( valuesForMap ) ; } finally { HeapFriendlyMapArrayRecycler . get ( ) . clearNextCycleObjectArrays ( ) ; } }
For each cycle we need to perform some administrative tasks .
40,624
public void serializePrimitive ( S rec , String fieldName , long value ) { serializePrimitive ( rec , fieldName , Long . valueOf ( value ) ) ; }
Can be overridden to avoid boxing a long where appropriate
40,625
public void serializePrimitive ( S rec , String fieldName , float value ) { serializePrimitive ( rec , fieldName , Float . valueOf ( value ) ) ; }
Can be overridden to avoid boxing a float where appropriate
40,626
public void serializePrimitive ( S rec , String fieldName , double value ) { serializePrimitive ( rec , fieldName , Double . valueOf ( value ) ) ; }
Can be overridden to avoid boxing a double where appropriate
40,627
public < K , V > void serializeSortedMap ( S rec , String fieldName , String keyTypeName , String valueTypeName , SortedMap < K , V > obj ) { serializeMap ( rec , fieldName , keyTypeName , valueTypeName , obj ) ; }
Serialize sorted map
40,628
private < K , V > List < Map . Entry < K , V > > sortedEntryList ( Map < K , V > obj ) { List < Map . Entry < K , V > > entryList = new ArrayList < Map . Entry < K , V > > ( obj . entrySet ( ) ) ; Collections . sort ( entryList , new Comparator < Map . Entry < K , V > > ( ) { @ SuppressWarnings ( { "unchecked" , "rawtypes" } ) public int compare ( Entry < K , V > o1 , Entry < K , V > o2 ) { K k1 = o1 . getKey ( ) ; K k2 = o2 . getKey ( ) ; if ( k1 instanceof Comparable ) { return ( ( Comparable ) k1 ) . compareTo ( k2 ) ; } return k1 . hashCode ( ) - k2 . hashCode ( ) ; } } ) ; return entryList ; }
diffs to match up better .
40,629
public List < Object > getList ( DiffPropertyPath path ) { Integer listIndex = fieldValuesLists . get ( path ) ; if ( listIndex == null ) return null ; return getList ( listIndex . intValue ( ) ) ; }
Get the list of values associated with the supplied DiffPropertyPath
40,630
private void reset ( ) { int count = 0 ; for ( int i = 0 ; i < tableLength ; i ++ ) { long t = tableAt ( i ) ; count += Long . bitCount ( t & ONE_MASK ) ; tableAt ( i , ( t >>> 1 ) & RESET_MASK ) ; } size = ( size >>> 1 ) - ( count >>> 2 ) ; }
Reduces every counter by half of its original value .
40,631
public long average ( ) { double sum = 0 ; int count = 0 ; for ( float d = 0 ; d <= 1.0d ; d += 0.02d ) { sum += inverseCumProb ( d ) ; count += 1 ; } return ( long ) ( sum / count ) ; }
approximation of the average ; slightly costly to calculate so should not be invoked frequently
40,632
void add ( long hashEntryAdr , long expireAt ) { int slotNum = slot ( expireAt ) ; slots [ slotNum ] . add ( hashEntryAdr , expireAt ) ; }
Add a cache entry .
40,633
void remove ( long hashEntryAdr , long expireAt ) { int slot = slot ( expireAt ) ; slots [ slot ] . remove ( hashEntryAdr ) ; }
Remote a cache entry .
40,634
int removeExpired ( TimeoutHandler expireHandler ) { long t = ticker . currentTimeMillis ( ) ; int expired = 0 ; for ( int i = 0 ; i < slotCount ; i ++ ) { expired += slots [ i ] . removeExpired ( t , expireHandler ) ; } return expired ; }
Remove expired entries .
40,635
private void assertValidDateFieldType ( Optional < Field > field ) { field . ifPresent ( it -> { if ( SUPPORTED_DATE_TYPES . contains ( it . getType ( ) . getName ( ) ) ) { return ; } Class < ? > type = it . getType ( ) ; if ( Jsr310Converters . supports ( type ) || ThreeTenBackPortConverters . supports ( type ) ) { return ; } throw new IllegalStateException ( String . format ( "Found created/modified date field with type %s but only %s as well as java.time types are supported!" , type , SUPPORTED_DATE_TYPES ) ) ; } ) ; }
Checks whether the given field has a type that is a supported date type .
40,636
protected < X > long calculateTotal ( Pageable pager , List < X > result ) { if ( pager . hasPrevious ( ) ) { if ( CollectionUtils . isEmpty ( result ) ) { return - 1 ; } if ( result . size ( ) == pager . getPageSize ( ) ) { return - 1 ; } return ( pager . getPageNumber ( ) - 1 ) * pager . getPageSize ( ) + result . size ( ) ; } if ( result . size ( ) < pager . getPageSize ( ) ) { return result . size ( ) ; } return - 1 ; }
Calculate total mount .
40,637
protected final int bindLimitParameters ( RowSelection selection , PreparedStatement statement , int index ) throws SQLException { if ( ! supportsVariableLimit ( ) || ! LimitHelper . hasMaxRows ( selection ) ) { return 0 ; } final int firstRow = convertToFirstRowValue ( LimitHelper . getFirstRow ( selection ) ) ; final int lastRow = getMaxOrLimit ( selection ) ; final boolean hasFirstRow = supportsLimitOffset ( ) && ( firstRow > 0 || forceLimitUsage ( ) ) ; final boolean reverse = bindLimitParametersInReverseOrder ( ) ; if ( hasFirstRow ) { statement . setInt ( index + ( reverse ? 1 : 0 ) , firstRow ) ; } statement . setInt ( index + ( reverse || ! hasFirstRow ? 0 : 1 ) , lastRow ) ; return hasFirstRow ? 2 : 1 ; }
Default implementation of binding parameter values needed by the LIMIT clause .
40,638
public < T > T markCreated ( T source ) { Assert . notNull ( source , "Entity must not be null!" ) ; return touch ( source , true ) ; }
Marks the given object as created .
40,639
public < T > T markModified ( T source ) { Assert . notNull ( source , "Entity must not be null!" ) ; return touch ( source , false ) ; }
Marks the given object as modified .
40,640
protected final boolean isAuditable ( Object source ) { Assert . notNull ( source , "Source must not be null!" ) ; return factory . getBeanWrapperFor ( source ) . isPresent ( ) ; }
Returns whether the given source is considered to be auditable in the first place
40,641
private Optional < Object > touchAuditor ( AuditableBeanWrapper < ? > wrapper , boolean isNew ) { Assert . notNull ( wrapper , "AuditableBeanWrapper must not be null!" ) ; return auditorAware . map ( it -> { Optional < ? > auditor = it . getCurrentAuditor ( ) ; Assert . notNull ( auditor , ( ) -> String . format ( "Auditor must not be null! Returned by: %s!" , AopUtils . getTargetClass ( it ) ) ) ; auditor . filter ( __ -> isNew ) . ifPresent ( foo -> wrapper . setCreatedBy ( foo ) ) ; auditor . filter ( __ -> ! isNew || modifyOnCreation ) . ifPresent ( foo -> wrapper . setLastModifiedBy ( foo ) ) ; return auditor ; } ) ; }
Sets modifying and creating auditor . Creating auditor is only set on new auditables .
40,642
private Optional < TemporalAccessor > touchDate ( AuditableBeanWrapper < ? > wrapper , boolean isNew ) { Assert . notNull ( wrapper , "AuditableBeanWrapper must not be null!" ) ; Optional < TemporalAccessor > now = dateTimeProvider . getNow ( ) ; Assert . notNull ( now , ( ) -> String . format ( "Now must not be null! Returned by: %s!" , dateTimeProvider . getClass ( ) ) ) ; now . filter ( __ -> isNew ) . ifPresent ( it -> wrapper . setCreatedDate ( it ) ) ; now . filter ( __ -> ! isNew || modifyOnCreation ) . ifPresent ( it -> wrapper . setLastModifiedDate ( it ) ) ; return now ; }
Touches the auditable regarding modification and creation date . Creation date is only set on new auditables .
40,643
protected SqlSource buildSqlSourceFromStrings ( String [ ] strings , Class < ? > parameterTypeClass ) { final StringBuilder sql = new StringBuilder ( ) ; for ( String fragment : strings ) { sql . append ( fragment ) ; sql . append ( " " ) ; } LanguageDriver languageDriver = getLanguageDriver ( ) ; return languageDriver . createSqlSource ( configuration , sql . toString ( ) . trim ( ) , parameterTypeClass ) ; }
build sql source for mybatis from string concat by array .
40,644
public static boolean hasMaxRows ( RowSelection selection ) { return selection != null && selection . getMaxRows ( ) != null && selection . getMaxRows ( ) > 0 ; }
Is a max row limit indicated?
40,645
public static int getFirstRow ( RowSelection selection ) { return ( selection == null || selection . getFirstRow ( ) == null ) ? 0 : selection . getFirstRow ( ) ; }
Retrieve the indicated first row for pagination
40,646
public static List < Event > parse ( String requestBody , String signatureHeader , String webhookEndpointSecret ) { if ( isValidSignature ( requestBody , signatureHeader , webhookEndpointSecret ) ) { return WebhookParser . parse ( requestBody ) ; } else { throw new InvalidSignatureException ( ) ; } }
Validates that a webhook was genuinely sent by GoCardless using isValidSignature and then parses it into an array of com . gocardless . resources . Event objects representing each event included in the webhook .
40,647
public static boolean isValidSignature ( String requestBody , String signatureHeader , String webhookEndpointSecret ) { String computedSignature = new HmacUtils ( HmacAlgorithms . HMAC_SHA_256 , webhookEndpointSecret ) . hmacHex ( requestBody ) ; return MessageDigest . isEqual ( signatureHeader . getBytes ( ) , computedSignature . getBytes ( ) ) ; }
Validates that a webhook was genuinely sent by GoCardless by computing its signature using the body and your webhook endpoint secret and comparing that with the signature included in the Webhook - Signature header .
40,648
public static GoCardlessApiException toException ( ApiErrorResponse error ) { switch ( error . getType ( ) ) { case GOCARDLESS : return new GoCardlessInternalException ( error ) ; case INVALID_API_USAGE : return new InvalidApiUsageException ( error ) ; case INVALID_STATE : return new InvalidStateException ( error ) ; case VALIDATION_FAILED : return new ValidationFailedException ( error ) ; } throw new IllegalStateException ( "Unknown error type: " + error . getType ( ) ) ; }
Maps an error response to an exception .
40,649
public Map < String , String > getLinks ( ) { if ( links == null ) { return ImmutableMap . of ( ) ; } return ImmutableMap . copyOf ( links ) ; }
Returns the IDs of related objects .
40,650
private void buildRecorderFromObject ( int opcode , String owner , String name , String signature , boolean itf ) { super . visitMethodInsn ( opcode , owner , name , signature , itf ) ; super . visitInsn ( Opcodes . DUP ) ; super . visitInsn ( Opcodes . DUP ) ; super . visitMethodInsn ( Opcodes . INVOKEVIRTUAL , "java/lang/Object" , "getClass" , "()Ljava/lang/Class;" , false ) ; super . visitInsn ( Opcodes . SWAP ) ; super . visitMethodInsn ( Opcodes . INVOKESTATIC , recorderClass , recorderMethod , CLASS_RECORDER_SIG , false ) ; }
object then we get the class and invoke the recorder .
40,651
public void visitMaxs ( int maxStack , int maxLocals ) { if ( localScopes != null ) { for ( VariableScope scope : localScopes ) { super . visitLocalVariable ( "xxxxx$" + scope . index , scope . desc , null , scope . start , scope . end , scope . index ) ; } } super . visitMaxs ( maxStack , maxLocals ) ; }
Called by the ASM framework once the class is done being visited to compute stack & local variable count maximums .
40,652
private int newLocal ( Type type , String typeDesc , Label begin , Label end ) { int newVar = lvs . newLocal ( type ) ; getLocalScopes ( ) . add ( new VariableScope ( newVar , begin , end , typeDesc ) ) ; return newVar ; }
Helper method to allocate a new local variable and account for its scope .
40,653
public void visitMultiANewArrayInsn ( String typeName , int dimCount ) { super . visitMultiANewArrayInsn ( typeName , dimCount ) ; calculateArrayLengthAndDispatch ( typeName , dimCount ) ; }
multianewarray gets its very own visit method in the ASM framework so we hook it here . This bytecode is different from most in that it consumes a variable number of stack elements during execution . The number of stack elements consumed is specified by the dimCount operand .
40,654
public static void instrumentClass ( Class < ? > c , ConstructorCallback < ? > sampler ) throws UnmodifiableClassException { synchronized ( samplerPutAtomicityLock ) { List < ConstructorCallback < ? > > list = samplerMap . get ( c ) ; if ( list == null ) { CopyOnWriteArrayList < ConstructorCallback < ? > > samplerList = new CopyOnWriteArrayList < ConstructorCallback < ? > > ( ) ; samplerList . add ( sampler ) ; samplerMap . put ( c , samplerList ) ; Instrumentation inst = AllocationRecorder . getInstrumentation ( ) ; Class < ? > [ ] cs = new Class < ? > [ 1 ] ; cs [ 0 ] = c ; inst . retransformClasses ( c ) ; } else { list . add ( sampler ) ; } } }
Ensures that the given sampler will be invoked every time a constructor for class c is invoked .
40,655
public static byte [ ] instrument ( byte [ ] originalBytes , Class < ? > classBeingRedefined ) { try { ClassReader cr = new ClassReader ( originalBytes ) ; ClassWriter cw = new ClassWriter ( cr , ClassWriter . COMPUTE_MAXS ) ; VerifyingClassAdapter vcw = new VerifyingClassAdapter ( cw , originalBytes , cr . getClassName ( ) ) ; ClassVisitor adapter = new ConstructorClassAdapter ( vcw , classBeingRedefined ) ; cr . accept ( adapter , ClassReader . SKIP_FRAMES ) ; return vcw . toByteArray ( ) ; } catch ( RuntimeException e ) { logger . log ( Level . WARNING , "Failed to instrument class." , e ) ; throw e ; } catch ( Error e ) { logger . log ( Level . WARNING , "Failed to instrument class." , e ) ; throw e ; } }
Given the bytes representing a class add invocations of the ConstructorCallback method to the constructor .
40,656
@ SuppressWarnings ( "unchecked" ) public static void invokeSamplers ( Object o ) { Class < ? > currentClass = o . getClass ( ) ; while ( currentClass != null ) { List < ConstructorCallback < ? > > samplers = samplerMap . get ( currentClass ) ; if ( samplers != null ) { for ( @ SuppressWarnings ( "rawtypes" ) ConstructorCallback sampler : samplers ) { sampler . sample ( o ) ; } return ; } else { if ( ! subclassesAlso ) { return ; } currentClass = currentClass . getSuperclass ( ) ; } } }
Bytecode is rewritten to invoke this method ; it calls the sampler for the given class . Note that unless the javaagent command line argument subclassesAlso is specified it won t do anything if o is a subclass of the class that was supposed to be tracked .
40,657
public byte [ ] toByteArray ( ) { if ( state != State . PASS ) { logger . log ( Level . WARNING , "Failed to instrument class " + className + " because " + message ) ; return original ; } return cw . toByteArray ( ) ; }
Returns the byte array that contains the byte code for this class .
40,658
private static long getObjectSize ( Object obj , boolean isArray , Instrumentation instr ) { if ( isArray ) { return instr . getObjectSize ( obj ) ; } Class < ? > clazz = obj . getClass ( ) ; Long classSize = classSizesMap . get ( clazz ) ; if ( classSize == null ) { classSize = instr . getObjectSize ( obj ) ; classSizesMap . put ( clazz , classSize ) ; } return classSize ; }
Returns the size of the given object . If the object is not an array we check the cache first and update it as necessary .
40,659
public static void recordAllocation ( int count , String desc , Object newObj ) { if ( Objects . equals ( recordingAllocation . get ( ) , Boolean . TRUE ) ) { return ; } recordingAllocation . set ( Boolean . TRUE ) ; if ( count >= 0 ) { desc = desc . replace ( '.' , '/' ) ; } Instrumentation instr = instrumentation ; if ( instr != null ) { long objectSize = - 1 ; Sampler [ ] samplers = additionalSamplers ; if ( samplers != null ) { if ( objectSize < 0 ) { objectSize = getObjectSize ( newObj , ( count >= 0 ) , instr ) ; } for ( Sampler sampler : samplers ) { sampler . sampleAllocation ( count , desc , newObj , objectSize ) ; } } } recordingAllocation . set ( Boolean . FALSE ) ; }
Records the allocation . This method is invoked on every allocation performed by the system .
40,660
public void onNewTraces ( List < Trace > traces ) { int tracesRemoved = updateTraceBuffer ( traces ) ; List < Trace > tracesToNotify = getCurrentTraces ( ) ; view . showTraces ( tracesToNotify , tracesRemoved ) ; }
Given a list of Trace objects to show updates the buffer of traces and refresh the view .
40,661
public void updateFilter ( String filter ) { if ( isInitialized ) { LynxConfig lynxConfig = lynx . getConfig ( ) ; lynxConfig . setFilter ( filter ) ; lynx . setConfig ( lynxConfig ) ; clearView ( ) ; restartLynx ( ) ; } }
Updates the filter used to know which Trace objects we have to show in the UI .
40,662
public void onShareButtonClicked ( ) { List < Trace > tracesToShare = new LinkedList < Trace > ( traceBuffer . getTraces ( ) ) ; String plainTraces = generatePlainTracesToShare ( tracesToShare ) ; if ( ! view . shareTraces ( plainTraces ) ) { view . notifyShareTracesFailed ( ) ; } }
Generates a plain representation of all the Trace objects this presenter has stored and share them to other applications .
40,663
public void run ( ) { super . run ( ) ; try { process = Runtime . getRuntime ( ) . exec ( "logcat -v time" ) ; } catch ( IOException e ) { Log . e ( LOGTAG , "IOException executing logcat command." , e ) ; } readLogcat ( ) ; }
Starts reading traces from the application logcat and notifying listeners if needed .
40,664
private void generateFiveRandomTracesPerSecond ( ) { logGeneratorThread = new Thread ( new Runnable ( ) { public void run ( ) { while ( continueReading ) { int traceLevel = traceCounter % 6 ; switch ( traceLevel ) { case 0 : Log . d ( "Lynx" , traceCounter + " - Debug trace generated automatically" ) ; break ; case 1 : Log . w ( "Lynx" , traceCounter + " - Warning trace generated automatically" ) ; break ; case 2 : Log . e ( "Lynx" , traceCounter + " - Error trace generated automatically" ) ; break ; case 3 : Log . wtf ( "Lynx" , traceCounter + " - WTF trace generated automatically" ) ; break ; case 4 : Log . i ( "Lynx" , traceCounter + " - Info trace generated automatically" ) ; default : Log . v ( "Lynx" , traceCounter + " - Verbose trace generated automatically" ) ; } traceCounter ++ ; try { Thread . sleep ( 200 ) ; } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } } } } ) ; logGeneratorThread . start ( ) ; }
Random traces generator used just for this demo application .
40,665
protected void onVisibilityChanged ( View changedView , int visibility ) { super . onVisibilityChanged ( changedView , visibility ) ; if ( changedView != this ) { return ; } if ( visibility == View . VISIBLE ) { resumePresenter ( ) ; } else { pausePresenter ( ) ; } }
Initializes or stops LynxPresenter based on visibility changes . Doing this Lynx is not going to read your application Logcat if LynxView is not visible or attached .
40,666
public void setLynxConfig ( LynxConfig lynxConfig ) { validateLynxConfig ( lynxConfig ) ; boolean hasChangedLynxConfig = ! this . lynxConfig . equals ( lynxConfig ) ; if ( hasChangedLynxConfig ) { this . lynxConfig = ( LynxConfig ) lynxConfig . clone ( ) ; updateFilterText ( ) ; updateAdapter ( ) ; updateSpinner ( ) ; presenter . setLynxConfig ( lynxConfig ) ; } }
Given a valid LynxConfig object update all the dependencies to apply this new configuration .
40,667
public boolean shareTraces ( String fullTraces ) { try { shareTracesInternal ( fullTraces ) ; return true ; } catch ( RuntimeException exception1 ) { try { int fullTracesLength = fullTraces . length ( ) ; String truncatedTraces = fullTraces . substring ( Math . max ( 0 , fullTracesLength - 100000 ) , fullTracesLength ) ; shareTracesInternal ( truncatedTraces ) ; return true ; } catch ( RuntimeException exception2 ) { return false ; } } }
Uses an intent to share content and given one String with all the information related to the List of traces shares this information with other applications .
40,668
private void configureCursorColor ( ) { try { Field f = TextView . class . getDeclaredField ( "mCursorDrawableRes" ) ; f . setAccessible ( true ) ; f . set ( et_filter , R . drawable . edit_text_cursor_color ) ; } catch ( Exception e ) { Log . e ( LOGTAG , "Error trying to change cursor color text cursor drawable to null." ) ; } }
Hack to change EditText cursor color even if the API level is lower than 12 . Please don t do this at home .
40,669
public static Intent getIntent ( Context context , LynxConfig lynxConfig ) { if ( lynxConfig == null ) { lynxConfig = new LynxConfig ( ) ; } Intent intent = new Intent ( context , LynxActivity . class ) ; intent . putExtra ( LYNX_CONFIG_EXTRA , lynxConfig ) ; return intent ; }
Generates an Intent to start LynxActivity with a LynxConfig configuration passed as parameter .
40,670
public void startReading ( ) { logcat . setListener ( new Logcat . Listener ( ) { public void onTraceRead ( String logcatTrace ) { try { addTraceToTheBuffer ( logcatTrace ) ; } catch ( IllegalTraceException e ) { return ; } notifyNewTraces ( ) ; } } ) ; boolean logcatWasNotStarted = Thread . State . NEW . equals ( logcat . getState ( ) ) ; if ( logcatWasNotStarted ) { logcat . start ( ) ; } }
Configures a Logcat . Listener and initialize Logcat dependency to read traces from the OS log .
40,671
public synchronized void restart ( ) { Logcat . Listener previousListener = logcat . getListener ( ) ; logcat . stopReading ( ) ; logcat . interrupt ( ) ; logcat = ( Logcat ) logcat . clone ( ) ; logcat . setListener ( previousListener ) ; lastNotificationTime = 0 ; tracesToNotify . clear ( ) ; logcat . start ( ) ; }
Stops the configured Logcat dependency and creates a clone to restart using Logcat and LogcatListener configured previously .
40,672
public void init ( final LynxConfig lynxConfig ) { ShakeDetector shakeDetector = new ShakeDetector ( new ShakeDetector . Listener ( ) { public void hearShake ( ) { if ( isEnabled ) { openLynxActivity ( lynxConfig ) ; } } } ) ; SensorManager sensorManager = ( SensorManager ) context . getSystemService ( Context . SENSOR_SERVICE ) ; shakeDetector . start ( sensorManager ) ; }
Starts listening shakes to open LynxActivity if a shake is detected and if the ShakeDetector is enabled .
40,673
public List < String > list ( URL url , String path ) throws IOException { InputStream is = null ; try { List < String > resources = new ArrayList < String > ( ) ; URL jarUrl = findJarForResource ( url ) ; if ( jarUrl != null ) { is = jarUrl . openStream ( ) ; return listResources ( new JarInputStream ( is ) , path ) ; } List < String > children = new ArrayList < String > ( ) ; children = this . getResourceUrls ( url , path , is , children ) ; String prefix = url . toExternalForm ( ) ; if ( ! prefix . endsWith ( PATH_SP ) ) { prefix = prefix + PATH_SP ; } for ( String child : children ) { String resourcePath = path + PATH_SP + child ; resources . add ( resourcePath ) ; URL childUrl = new URL ( prefix + child ) ; resources . addAll ( list ( childUrl , resourcePath ) ) ; } return resources ; } finally { IoHelper . closeQuietly ( is ) ; } }
Recursively list the full resource path of all the resources that are children of the resource identified by a URL .
40,674
public void doBackgroundOp ( final Runnable run , final boolean showWaitCursor ) { final Component [ ] key = new Component [ 1 ] ; ExecutorService jobRunner = getJobRunner ( ) ; if ( jobRunner != null ) { jobRunner . submit ( ( ) -> performBackgroundOp ( run , key , showWaitCursor ) ) ; } else { run . run ( ) ; } }
Runs a job in a background thread using the ExecutorService and optionally sets the cursor to the wait cursor and blocks input .
40,675
public static int getArrayLength ( Object obj ) { if ( obj == null ) { return 0 ; } IType type = TypeLoaderAccess . instance ( ) . getIntrinsicTypeFromObject ( obj ) ; if ( type . isArray ( ) ) { return type . getArrayLength ( obj ) ; } if ( obj instanceof CharSequence ) { return ( ( CharSequence ) obj ) . length ( ) ; } if ( obj instanceof Collection ) { return ( ( Collection ) obj ) . size ( ) ; } if ( obj instanceof Iterable ) { int iCount = 0 ; for ( Object o : ( Iterable ) obj ) { iCount ++ ; } return iCount ; } return 0 ; }
Return the length of the specified Array or Collection .
40,676
private boolean canAccessPrivateMembers ( IType ownersClass , IType whosAskin ) { return getOwnersType ( ) == whosAskin || getTopLevelTypeName ( whosAskin ) . equals ( getTopLevelTypeName ( ownersClass ) ) ; }
A private feature is accessible from its declaring class and any inner class defined in its declaring class .
40,677
public static < T > T findAncestor ( Component start , Class < T > aClass ) { if ( start == null ) { return null ; } return findAtOrAbove ( start . getParent ( ) , aClass ) ; }
Finds the first widget above the passed in widget of the given class
40,678
public static < T > T findAtOrAbove ( Component start , Class < T > aClass ) { Component comp = start ; while ( comp != null ) { if ( aClass . isInstance ( comp ) ) { return ( T ) comp ; } else { comp = comp . getParent ( ) ; } } return null ; }
Finds the first widget at or above the passed in widget of the given class
40,679
public SimpleXmlNode shallowCopy ( ) { SimpleXmlNode copy = new SimpleXmlNode ( _name ) ; copy . setText ( _text ) ; copy . getAttributes ( ) . putAll ( _attributes ) ; return copy ; }
Makes a shallow copy of this node including its name text and attributes . The returned node will have no children and no parent .
40,680
public SimpleXmlNode deepCopy ( ) { SimpleXmlNode rootCopy = shallowCopy ( ) ; for ( SimpleXmlNode child : _children ) { rootCopy . getChildren ( ) . add ( child . deepCopy ( ) ) ; } return rootCopy ; }
Makes a deep copy of this node including copies of all contained children . The returned node will have the same name text and attributes as this node and its list of children will contain deep copies of each child of this node .
40,681
private void removeUseless ( ) { Set < Map . Entry < String , PropertyNode > > entries = _children . entrySet ( ) ; for ( Iterator < Map . Entry < String , PropertyNode > > it = entries . iterator ( ) ; it . hasNext ( ) ; ) { Map . Entry < String , PropertyNode > entry = it . next ( ) ; PropertyNode child = entry . getValue ( ) ; child . removeUseless ( ) ; if ( child . isUseless ( ) ) { it . remove ( ) ; } } }
removes all useless nodes in the tree represented by this node as a root
40,682
public void setReadMethod ( Method getter ) throws IntrospectionException { super . setReadMethod ( getter ) ; if ( _propertyClass == null ) { _propertyClass = super . getPropertyType ( ) ; } }
this class maintains its own copy of propertyType .
40,683
private void compileJavaInteropBridgeConstructor ( DynamicFunctionSymbol dfs ) { DynamicFunctionSymbol copy = new DynamicFunctionSymbol ( dfs ) ; copy . setValue ( null ) ; copy . setInitializer ( null ) ; ConstructorStatement fs = new ConstructorStatement ( true ) ; fs . setDynamicFunctionSymbol ( copy ) ; fs . setSynthetic ( true ) ; MethodCallExpression expr = new MethodCallExpression ( ) ; expr . setType ( JavaTypes . pVOID ( ) ) ; List < ISymbol > args = dfs . getArgs ( ) ; Expression [ ] exprArgs = new Expression [ args . size ( ) ] ; for ( int i = 0 ; i < args . size ( ) ; i ++ ) { ISymbol arg = args . get ( i ) ; Identifier id = new Identifier ( ) ; id . setSymbol ( arg , dfs . getSymbolTable ( ) ) ; id . setType ( arg . getType ( ) ) ; exprArgs [ i ] = id ; } expr . setArgs ( exprArgs ) ; expr . setFunctionSymbol ( new ThisConstructorFunctionSymbol ( dfs , true ) ) ; MethodCallStatement stmt = new MethodCallStatement ( ) ; stmt . setMethodCall ( expr ) ; stmt . setSynthetic ( true ) ; copy . setValue ( stmt ) ; copy . setDeclFunctionStmt ( fs ) ; int iModifiers = getModifiers ( copy ) ; List < IRSymbol > parameters = new ArrayList < > ( ) ; maybeGetEnumSuperConstructorSymbols ( parameters ) ; for ( ISymbol param : copy . getArgs ( ) ) { parameters . add ( makeParamSymbol ( copy , param ) ) ; } setUpFunctionContext ( copy , true , parameters ) ; FunctionStatementTransformer funcStmtCompiler = new FunctionStatementTransformer ( copy , _context ) ; IRStatement methodBody = funcStmtCompiler . compile ( ) ; IExpression annotationDefault = copy . getAnnotationDefault ( ) ; Object [ ] annotationDefaultValue = null ; if ( annotationDefault != null ) { annotationDefaultValue = new Object [ ] { CompileTimeExpressionParser . convertValueToInfoFriendlyValue ( annotationDefault . evaluate ( ) , getGosuClass ( ) . getTypeInfo ( ) ) } ; } IRMethodStatement methodStatement = new IRMethodStatement ( methodBody , "<init>" , iModifiers , copy . isInternal ( ) , IRTypeConstants . pVOID ( ) , copy . getReturnType ( ) , parameters , copy . getArgTypes ( ) , copy . getType ( ) , annotationDefaultValue ) ; methodStatement . setAnnotations ( getIRAnnotations ( makeAnnotationInfos ( copy . getModifierInfo ( ) . getAnnotations ( ) , getGosuClass ( ) . getTypeInfo ( ) ) ) ) ; _irClass . addMethod ( methodStatement ) ; }
Add constructor so Java can use the Gosu generic class without explicitly passing in type arguments .
40,684
public Object evaluate ( ) { if ( ! isCompileTimeConstant ( ) ) { return super . evaluate ( ) ; } Object value = getLHS ( ) . evaluate ( ) ; IType argType = getType ( ) ; if ( value instanceof IType && argType instanceof IJavaType && JavaTypes . CLASS ( ) == TypeLord . getPureGenericType ( argType ) ) { return value ; } if ( argType == GosuParserTypes . NUMBER_TYPE ( ) ) { return CommonServices . getCoercionManager ( ) . makeDoubleFrom ( value ) ; } else if ( argType == GosuParserTypes . STRING_TYPE ( ) ) { return CommonServices . getCoercionManager ( ) . makeStringFrom ( value ) ; } else if ( argType == GosuParserTypes . DATETIME_TYPE ( ) ) { Date date = CommonServices . getCoercionManager ( ) . makeDateFrom ( value ) ; if ( date != null ) { return date ; } } if ( _coercer != null && ( value != null || _coercer . handlesNull ( ) ) ) { return _coercer . coerceValue ( argType , value ) ; } return value ; }
Perform a type cast .
40,685
public static ProgressFeedback runWithProgress ( final String strNotice , final IRunnableWithProgress task ) { return runWithProgress ( strNotice , task , false , false ) ; }
A helper method that executes a task in a worker thread and displays feedback in a progress windows .
40,686
public Object parse ( ) { Object val = null ; if ( T . isValueType ( ) ) { val = parseValue ( ) ; } else { addError ( ) ; } return val ; }
jsonText = value .
40,687
public Object parseValue ( ) { Object val ; switch ( T . getType ( ) ) { case LCURLY : val = parseObject ( ) ; break ; case LSQUARE : val = parseArray ( ) ; break ; case INTEGER : if ( useBig ) { val = new BigInteger ( T . getString ( ) ) ; } else { try { val = Integer . parseInt ( T . getString ( ) ) ; } catch ( NumberFormatException e0 ) { try { val = Long . parseLong ( T . getString ( ) ) ; } catch ( NumberFormatException e1 ) { val = 0 ; } } } advance ( ) ; break ; case DOUBLE : if ( useBig ) { val = new BigDecimal ( T . getString ( ) ) ; } else { val = Double . parseDouble ( T . getString ( ) ) ; } advance ( ) ; break ; case STRING : val = T . getString ( ) ; advance ( ) ; break ; case TRUE : val = true ; advance ( ) ; break ; case FALSE : val = false ; advance ( ) ; break ; case NULL : val = null ; advance ( ) ; break ; default : val = null ; addError ( ) ; } return val ; }
value = object | array | number | string | true | false | null .
40,688
private TypeVarToTypeMap mapTypes ( TypeVarToTypeMap actualParamByVarName , IType ... types ) { for ( int i = 0 ; i < types . length ; i ++ ) { IType type = types [ i ] ; if ( type instanceof ITypeVariableType ) { actualParamByVarName . put ( ( ITypeVariableType ) types [ i ] , types [ i ] ) ; } if ( type instanceof ITypeVariableArrayType ) { mapTypes ( actualParamByVarName , type . getComponentType ( ) ) ; } if ( type . isParameterizedType ( ) ) { IType [ ] parameters = type . getTypeParameters ( ) ; mapTypes ( actualParamByVarName , parameters ) ; } if ( type instanceof IFunctionType ) { IFunctionType funType = ( IFunctionType ) type ; mapTypes ( actualParamByVarName , funType . getReturnType ( ) ) ; IType [ ] paramTypes = funType . getParameterTypes ( ) ; for ( IType paramType : paramTypes ) { mapTypes ( actualParamByVarName , paramType ) ; } } } return actualParamByVarName ; }
Move Intrinsic type helper up here
40,689
public ProcessRunner withEnvironmentVariable ( String name , String value ) { _env . put ( name , value ) ; return this ; }
Adds a name - value pair into this process environment . This can be called multiple times in a chain to set multiple environment variables .
40,690
public V put ( K key , V value ) { return _cacheImpl . put ( key , value ) ; }
This will put a specific entry in the cache
40,691
public V get ( K key ) { V value = _cacheImpl . get ( key ) ; _requests . incrementAndGet ( ) ; if ( value == null ) { value = _missHandler . load ( key ) ; _cacheImpl . put ( key , value ) ; _misses . incrementAndGet ( ) ; } else { _hits . incrementAndGet ( ) ; } return value ; }
This will get a specific entry it will call the missHandler if it is not found .
40,692
public synchronized Cache < K , V > logEveryNSeconds ( int seconds , final ILogger logger ) { if ( _loggingTask == null ) { ScheduledExecutorService service = Executors . newScheduledThreadPool ( 1 ) ; _loggingTask = service . scheduleAtFixedRate ( new Runnable ( ) { public void run ( ) { logger . info ( Cache . this ) ; } } , seconds , seconds , TimeUnit . SECONDS ) ; } else { throw new IllegalStateException ( "Logging for " + this + " is already enabled" ) ; } return this ; }
Sets up a recurring task every n seconds to report on the status of this cache . This can be useful if you are doing exploratory caching and wish to monitor the performance of this cache with minimal fuss . Consider
40,693
public void setUndoableEditListener ( UndoableEditListener uel ) { if ( _uel != null ) { getEditor ( ) . getDocument ( ) . removeUndoableEditListener ( _uel ) ; } _uel = uel ; if ( _uel != null ) { getEditor ( ) . getDocument ( ) . addUndoableEditListener ( _uel ) ; } }
Sets the one and only undoable edit listener for this editor section . The primary use case for this method is to establish an undo manager connection .
40,694
private IType getCompilingClass ( ) { if ( isIncludeAll ( ) ) { return _gsClass ; } IType type = GosuClassCompilingStack . getCurrentCompilingType ( ) ; if ( type != null ) { return type ; } ISymbolTable symTableCtx = CompiledGosuClassSymbolTable . getSymTableCtx ( ) ; ISymbol thisSymbol = symTableCtx . getThisSymbolFromStackOrMap ( ) ; if ( thisSymbol != null ) { IType thisSymbolType = thisSymbol . getType ( ) ; if ( thisSymbolType instanceof IGosuClassInternal ) { return thisSymbolType ; } } return ! _gsClass . isDeclarationsCompiled ( ) ? _gsClass : null ; }
We expose type info in a context sensitive manner . For instance we only expose private features from within the containing class . We can determine the context class from the current compiling class . The compiling class is obtained from either 1 ) the actual CompiledGosuClass stack the Gosu Class TypeLoader manages or 2 ) from the class itself if it s not compiled yet . Note the latter case happens only on the UI side when a class is being edited .
40,695
public Object evaluate ( ) { if ( ! isCompileTimeConstant ( ) ) { return super . evaluate ( ) ; } return ( Boolean ) getLHS ( ) . evaluate ( ) || ( Boolean ) getRHS ( ) . evaluate ( ) ; }
Performs a logical OR operation . Note this operation is naturally short - circuited by using || in conjunction with postponing RHS evaluation .
40,696
public static int getModifiersFrom ( IAttributedFeatureInfo afi ) { int iModifiers = 0 ; iModifiers = Modifier . setBit ( iModifiers , afi . isPublic ( ) , PUBLIC ) ; iModifiers = Modifier . setBit ( iModifiers , afi . isPrivate ( ) , PRIVATE ) ; iModifiers = Modifier . setBit ( iModifiers , afi . isProtected ( ) , PROTECTED ) ; iModifiers = Modifier . setBit ( iModifiers , afi . isInternal ( ) , INTERNAL ) ; iModifiers = Modifier . setBit ( iModifiers , afi . isStatic ( ) , STATIC ) ; iModifiers = Modifier . setBit ( iModifiers , afi . isFinal ( ) , FINAL ) ; iModifiers = Modifier . setBit ( iModifiers , afi . isReified ( ) , REIFIED ) ; return iModifiers ; }
Match the Java value for the annotation modifier
40,697
public static boolean isAM ( Date date ) { return dateToCalendar ( date ) . get ( Calendar . AM_PM ) == Calendar . AM ; }
Is the time AM?
40,698
public static boolean isPM ( Date date ) { return dateToCalendar ( date ) . get ( Calendar . AM_PM ) == Calendar . PM ; }
Is the time PM?
40,699
public Color getForeground ( int code ) { Style s = _tokenStyles . get ( new Integer ( code ) ) ; if ( s == null ) { s = getStyle ( DEFAULT_STYLE ) ; } return getForeground ( s ) ; }
Fetch the foreground color to use for a lexical token with the given value .