idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
27,800
@ ObjectiveCName ( "registerApplePushWithApnsId:withToken:" ) public void registerApplePush ( int apnsId , String token ) { modules . getPushesModule ( ) . registerApplePush ( apnsId , token ) ; }
Register apple push
27,801
@ ObjectiveCName ( "registerApplePushKitWithApnsId:withToken:" ) public void registerApplePushKit ( int apnsId , String token ) { modules . getPushesModule ( ) . registerApplePushKit ( apnsId , token ) ; }
Register apple push kit tokens
27,802
@ ObjectiveCName ( "addTrustedKey:" ) public ConfigurationBuilder addTrustedKey ( String trustedKey ) { trustedKeys . add ( new TrustedKey ( trustedKey ) ) ; return this ; }
Adding Trusted key for protocol encryption securing
27,803
@ ObjectiveCName ( "addPreferredLanguage:" ) public ConfigurationBuilder addPreferredLanguage ( String language ) { if ( ! preferredLanguages . contains ( language ) ) { preferredLanguages . add ( language ) ; } return this ; }
Adding preferred language
27,804
public synchronized void onDialogsChanged ( boolean isEmpty ) { if ( isDialogsEmpty . get ( ) != isEmpty ) { context . getPreferences ( ) . putBool ( "app.dialogs.empty" , isEmpty ) ; isDialogsEmpty . change ( isEmpty ) ; } if ( ! isEmpty ) { if ( isAppEmpty . get ( ) ) { context . getPreferences ( ) . putBool ( "app.empty" , false ) ; isAppEmpty . change ( false ) ; } } }
Notify from Modules about dialogs state changed
27,805
public synchronized void onContactsChanged ( boolean isEmpty ) { if ( isContactsEmpty . get ( ) != isEmpty ) { context . getPreferences ( ) . putBool ( "app.contacts.empty" , isEmpty ) ; isContactsEmpty . change ( isEmpty ) ; } if ( ! isEmpty ) { if ( isAppEmpty . get ( ) ) { context . getPreferences ( ) . putBool ( "app.empty" , false ) ; isAppEmpty . change ( false ) ; } } }
Notify from Modules about contacts state changed
27,806
public void onNewMessage ( Peer peer , int sender , long date , ContentDescription description , boolean hasCurrentUserMention , int messagesCount , int dialogsCount ) { if ( date <= getLastReadDate ( peer ) ) { return ; } boolean isEnabled = isNotificationsEnabled ( peer , hasCurrentUserMention ) ; if ( isEnabled ) { List < PendingNotification > pendingNotifications = getNotifications ( ) ; PendingNotification pendingNotification = new PendingNotification ( peer , sender , date , description ) ; pendingNotifications . add ( pendingNotification ) ; pendingStorage . setMessagesCount ( messagesCount ) ; pendingStorage . setDialogsCount ( dialogsCount ) ; allPendingNotifications . add ( pendingNotification ) ; saveStorage ( ) ; } if ( isNotificationsPaused ) { if ( ! notificationsDuringPause . containsKey ( peer ) ) { notificationsDuringPause . put ( peer , hasCurrentUserMention ) ; } else { if ( hasCurrentUserMention && ! notificationsDuringPause . get ( peer ) ) { notificationsDuringPause . put ( peer , true ) ; } } return ; } if ( isAppVisible ) { if ( visiblePeer != null && visiblePeer . equals ( peer ) ) { if ( isMobilePlatform ) { playEffectIfEnabled ( ) ; } else { } } else { if ( isMobilePlatform ) { } else { if ( isEnabled ) { playEffectIfEnabled ( ) ; } } } } else { if ( isEnabled ) { showNotification ( ) ; } } }
Handling event about incoming notification
27,807
public void onMessagesRead ( Peer peer , long fromDate ) { if ( fromDate < getLastReadDate ( peer ) ) { return ; } getNotifications ( ) . clear ( ) ; pendingStorage . setMessagesCount ( 0 ) ; pendingStorage . setDialogsCount ( 0 ) ; allPendingNotifications . clear ( ) ; saveStorage ( ) ; updateNotification ( ) ; setLastReadDate ( peer , fromDate ) ; }
Processing event about messages read
27,808
public void onConversationHidden ( Peer peer ) { if ( visiblePeer != null && visiblePeer . equals ( peer ) ) { this . visiblePeer = null ; } }
Processing Conversation hidden event
27,809
private boolean isNotificationsEnabled ( Peer peer , boolean hasMention ) { if ( ! context ( ) . getSettingsModule ( ) . isNotificationsEnabled ( ) ) { return false ; } if ( peer . getPeerType ( ) == PeerType . GROUP ) { if ( getGroup ( peer . getPeerId ( ) ) . isHidden ( ) ) { return false ; } if ( context ( ) . getSettingsModule ( ) . isGroupNotificationsEnabled ( ) ) { if ( hasMention ) { return true ; } if ( context ( ) . getSettingsModule ( ) . isNotificationsEnabled ( peer ) ) { if ( context ( ) . getSettingsModule ( ) . isGroupNotificationsOnlyMentionsEnabled ( ) ) { return false ; } else { return true ; } } else { return false ; } } else { return false ; } } else if ( peer . getPeerType ( ) == PeerType . PRIVATE ) { return context ( ) . getSettingsModule ( ) . isNotificationsEnabled ( peer ) ; } else { throw new RuntimeException ( "Unknown peer type" ) ; } }
Testing if notifications enabled for message
27,810
private long getLastReadDate ( Peer peer ) { if ( readStates . containsKey ( peer ) ) { return readStates . get ( peer ) ; } byte [ ] data = storage . get ( peer . getUnuqueId ( ) ) ; if ( data != null ) { try { return ReadState . fromBytes ( data ) . getSortDate ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } return 0 ; }
Getting last read sort key for peer
27,811
private void setLastReadDate ( Peer peer , long date ) { storage . put ( peer . getUnuqueId ( ) , new ReadState ( date ) . toByteArray ( ) ) ; readStates . put ( peer , date ) ; }
Setting last read date for peer
27,812
public void onBusEvent ( Event event ) { if ( event instanceof AppVisibleChanged ) { AppVisibleChanged visibleChanged = ( AppVisibleChanged ) event ; if ( visibleChanged . isVisible ( ) ) { onAppVisible ( ) ; } else { onAppHidden ( ) ; } } else if ( event instanceof PeerChatOpened ) { onConversationVisible ( ( ( PeerChatOpened ) event ) . getPeer ( ) ) ; } else if ( event instanceof PeerChatClosed ) { onConversationHidden ( ( ( PeerChatClosed ) event ) . getPeer ( ) ) ; } }
Receiving bus events
27,813
public void encryptBlock ( byte [ ] data , int offset , byte [ ] dest , int destOffset ) { Kuz128 x = new Kuz128 ( ) ; x . setQ ( 0 , ByteStrings . bytesToLong ( data , offset ) ) ; x . setQ ( 1 , ByteStrings . bytesToLong ( data , offset + 8 ) ) ; for ( int i = 0 ; i < 9 ; i ++ ) { x . setQ ( 0 , x . getQ ( 0 ) ^ key . getK ( ) [ i ] . getQ ( 0 ) ) ; x . setQ ( 1 , x . getQ ( 1 ) ^ key . getK ( ) [ i ] . getQ ( 1 ) ) ; for ( int j = 0 ; j < 16 ; j ++ ) { x . getB ( ) [ j ] = KuznechikTables . kuz_pi [ ( x . getB ( ) [ j ] & 0xFF ) ] ; } KuznechikMath . kuz_l ( x ) ; } ByteStrings . write ( dest , destOffset , ByteStrings . longToBytes ( x . getQ ( 0 ) ^ key . getK ( ) [ 9 ] . getQ ( 0 ) ) , 0 , 8 ) ; ByteStrings . write ( dest , destOffset + 8 , ByteStrings . longToBytes ( x . getQ ( 1 ) ^ key . getK ( ) [ 9 ] . getQ ( 1 ) ) , 0 , 8 ) ; }
Encrypting Block with KuznechikImpl encryption
27,814
public void decryptBlock ( byte [ ] data , int offset , byte [ ] dest , int destOffset ) { Kuz128 x = new Kuz128 ( ) ; x . setQ ( 0 , ByteStrings . bytesToLong ( data , offset ) ^ key . getK ( ) [ 9 ] . getQ ( 0 ) ) ; x . setQ ( 1 , ByteStrings . bytesToLong ( data , offset + 8 ) ^ key . getK ( ) [ 9 ] . getQ ( 1 ) ) ; for ( int i = 8 ; i >= 0 ; i -- ) { KuznechikMath . kuz_l_inv ( x ) ; for ( int j = 0 ; j < 16 ; j ++ ) { x . getB ( ) [ j ] = KuznechikTables . kuz_pi_inv [ x . getB ( ) [ j ] & 0xFF ] ; } x . setQ ( 0 , x . getQ ( 0 ) ^ key . getK ( ) [ i ] . getQ ( 0 ) ) ; x . setQ ( 1 , x . getQ ( 1 ) ^ key . getK ( ) [ i ] . getQ ( 1 ) ) ; } ByteStrings . write ( dest , destOffset , ByteStrings . longToBytes ( x . getQ ( 0 ) ) , 0 , 8 ) ; ByteStrings . write ( dest , destOffset + 8 , ByteStrings . longToBytes ( x . getQ ( 1 ) ) , 0 , 8 ) ; }
Decrypting block with Kuznechik encryption
27,815
static KuzIntKey convertKey ( byte [ ] key ) { if ( key . length != 32 ) { throw new RuntimeException ( "Key might be 32 bytes length" ) ; } KuzIntKey kuz = new KuzIntKey ( ) ; Kuz128 c = new Kuz128 ( ) , x = new Kuz128 ( ) , y = new Kuz128 ( ) , z = new Kuz128 ( ) ; for ( int i = 0 ; i < 16 ; i ++ ) { x . getB ( ) [ i ] = key [ i ] ; y . getB ( ) [ i ] = key [ i + 16 ] ; } kuz . getK ( ) [ 0 ] . set ( x ) ; kuz . getK ( ) [ 1 ] . set ( y ) ; for ( int i = 1 ; i <= 32 ; i ++ ) { c . setQ ( 0 , 0 ) ; c . setQ ( 1 , 0 ) ; c . getB ( ) [ 15 ] = ( byte ) i ; KuznechikMath . kuz_l ( c ) ; z . setQ ( 0 , x . getQ ( 0 ) ^ c . getQ ( 0 ) ) ; z . setQ ( 1 , x . getQ ( 1 ) ^ c . getQ ( 1 ) ) ; for ( int j = 0 ; j < 16 ; j ++ ) { z . getB ( ) [ j ] = KuznechikTables . kuz_pi [ ( z . getB ( ) [ j ] & 0xFF ) ] ; } KuznechikMath . kuz_l ( z ) ; z . setQ ( 0 , z . getQ ( 0 ) ^ y . getQ ( 0 ) ) ; z . setQ ( 1 , z . getQ ( 1 ) ^ y . getQ ( 1 ) ) ; y . set ( x ) ; x . set ( z ) ; if ( ( i & 7 ) == 0 ) { kuz . getK ( ) [ ( i >> 2 ) ] . set ( x ) ; kuz . getK ( ) [ ( i >> 2 ) + 1 ] . set ( y ) ; } } return kuz ; }
Converting binary representation of a key to internal format
27,816
public void waitForReady ( ) { if ( ! isLoaded ) { synchronized ( LOAD_LOCK ) { if ( ! isLoaded ) { try { long start = Runtime . getActorTime ( ) ; LOAD_LOCK . wait ( ) ; Log . d ( TAG , "Waited for startup in " + ( Runtime . getActorTime ( ) - start ) + " ms" ) ; } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } } } } }
Waiting for Messenger Ready
27,817
public < T > T getDelegatedFragment ( ActorIntent delegatedIntent , android . support . v4 . app . Fragment baseFragment , Class < T > type ) { if ( delegatedIntent != null && delegatedIntent instanceof ActorIntentFragmentActivity && ( ( ActorIntentFragmentActivity ) delegatedIntent ) . getFragment ( ) != null && type . isInstance ( ( ( ActorIntentFragmentActivity ) delegatedIntent ) . getFragment ( ) ) ) { return ( T ) ( ( ActorIntentFragmentActivity ) delegatedIntent ) . getFragment ( ) ; } else { return ( T ) baseFragment ; } }
Method is used internally for getting delegated fragment
27,818
@ ObjectiveCName ( "tupleWithT1:withT2:" ) public static < T1 , T2 > Promise < Tuple2 < T1 , T2 > > tuple ( Promise < T1 > t1 , Promise < T2 > t2 ) { return PromisesArray . ofPromises ( ( Promise < Object > ) t1 , ( Promise < Object > ) t2 ) . zip ( ) . map ( src -> new Tuple2 < > ( ( T1 ) src . get ( 0 ) , ( T2 ) src . get ( 1 ) ) ) ; }
Combines two promises to one with different data types
27,819
@ ObjectiveCName ( "tupleWithT1:withT2:withT3:" ) public static < T1 , T2 , T3 > Promise < Tuple3 < T1 , T2 , T3 > > tuple ( Promise < T1 > t1 , Promise < T2 > t2 , Promise < T3 > t3 ) { return PromisesArray . ofPromises ( ( Promise < Object > ) t1 , ( Promise < Object > ) t2 , ( Promise < Object > ) t3 ) . zip ( ) . map ( src -> new Tuple3 < > ( ( T1 ) src . get ( 0 ) , ( T2 ) src . get ( 1 ) , ( T3 ) src . get ( 3 ) ) ) ; }
Combines tree promises to one with different data types
27,820
public static < T > Promise traverse ( List < Supplier < Promise < T > > > queue ) { if ( queue . size ( ) == 0 ) { return Promise . success ( null ) ; } return queue . remove ( 0 ) . get ( ) . flatMap ( v -> traverse ( queue ) ) ; }
Execute promises step by step
27,821
public static final String concatGroups ( MatcherCompat matcher ) { StringBuilder b = new StringBuilder ( ) ; final int numGroups = matcher . groupCount ( ) ; for ( int i = 1 ; i <= numGroups ; i ++ ) { String s = matcher . group ( i ) ; if ( s != null ) { b . append ( s ) ; } } return b . toString ( ) ; }
Convenience method to take all of the non - null matching groups in a regex Matcher and return them as a concatenated string .
27,822
public static final String digitsAndPlusOnly ( MatcherCompat matcher ) { StringBuilder buffer = new StringBuilder ( ) ; String matchingRegion = matcher . group ( ) ; for ( int i = 0 , size = matchingRegion . length ( ) ; i < size ; i ++ ) { char character = matchingRegion . charAt ( i ) ; if ( character == '+' || Character . isDigit ( character ) ) { buffer . append ( character ) ; } } return buffer . toString ( ) ; }
Convenience method to return only the digits and plus signs in the matching string .
27,823
private static byte [ ] writeInt ( int value ) throws IOException { byte [ ] b = new byte [ 4 ] ; b [ 0 ] = ( byte ) ( value & 0x000000FF ) ; b [ 1 ] = ( byte ) ( ( value & 0x0000FF00 ) >> 8 ) ; b [ 2 ] = ( byte ) ( ( value & 0x00FF0000 ) >> 16 ) ; b [ 3 ] = ( byte ) ( ( value & 0xFF000000 ) >> 24 ) ; return b ; }
Write integer to little - endian
27,824
public void reply ( Object message ) { if ( context . sender ( ) != null ) { context . sender ( ) . send ( message , self ( ) ) ; } }
Reply message to sender of last message
27,825
public void drop ( Object message ) { if ( system ( ) . getTraceInterface ( ) != null ) { system ( ) . getTraceInterface ( ) . onDrop ( sender ( ) , message , this ) ; } reply ( new DeadLetter ( message ) ) ; }
Dropping of message
27,826
public synchronized long exponentialWait ( ) { long maxDelayRet = minDelay + ( ( maxDelay - minDelay ) / maxFailureCount ) * currentFailureCount ; return ( long ) ( random . nextFloat ( ) * maxDelayRet ) ; }
Calculating wait duration after failure attempt
27,827
@ ObjectiveCName ( "then:" ) public synchronized Promise < T > then ( final Consumer < T > then ) { if ( isFinished ) { if ( exception == null ) { dispatcher . dispatch ( ( ) -> then . apply ( result ) ) ; } } else { callbacks . add ( new PromiseCallback < T > ( ) { public void onResult ( T t ) { then . apply ( t ) ; } public void onError ( Exception e ) { } } ) ; } return this ; }
Handling successful result
27,828
@ ObjectiveCName ( "map:" ) public < R > Promise < R > map ( final Function < T , R > res ) { final Promise < T > self = this ; return new Promise < > ( ( PromiseFunc < R > ) resolver -> { self . then ( t -> { R r ; try { r = res . apply ( t ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; resolver . tryError ( e ) ; return ; } resolver . tryResult ( r ) ; } ) ; self . failure ( e -> resolver . error ( e ) ) ; } ) ; }
Mapping result value of promise to another value
27,829
@ ObjectiveCName ( "flatMap:" ) public < R > Promise < R > flatMap ( final Function < T , Promise < R > > res ) { final Promise < T > self = this ; return new Promise < > ( ( PromiseFunc < R > ) resolver -> { self . then ( t -> { Promise < R > promise ; try { promise = res . apply ( t ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; resolver . tryError ( e ) ; return ; } promise . then ( t2 -> resolver . result ( t2 ) ) ; promise . failure ( e -> resolver . error ( e ) ) ; } ) ; self . failure ( e -> resolver . error ( e ) ) ; } ) ; }
Map result of promise to promise of value
27,830
public < R > Promise < T > chain ( final Function < T , Promise < R > > res ) { final Promise < T > self = this ; return new Promise < > ( resolver -> { self . then ( t -> { Promise < R > chained = res . apply ( t ) ; chained . then ( t2 -> resolver . result ( t ) ) ; chained . failure ( e -> resolver . error ( e ) ) ; } ) ; self . failure ( e -> resolver . error ( e ) ) ; } ) ; }
Chaining result to next promise and returning current value as result promise
27,831
public Promise < T > after ( final ConsumerDouble < T , Exception > afterHandler ) { then ( t -> afterHandler . apply ( t , null ) ) ; failure ( e -> afterHandler . apply ( null , e ) ) ; return this ; }
Called after success or failure
27,832
@ ObjectiveCName ( "pipeTo:" ) public Promise < T > pipeTo ( PromiseResolver < T > resolver ) { then ( t -> resolver . result ( t ) ) ; failure ( e -> resolver . error ( e ) ) ; return this ; }
Pipe result to resolver
27,833
public static String hex ( byte [ ] bytes ) { char [ ] hexChars = new char [ bytes . length * 2 ] ; for ( int j = 0 ; j < bytes . length ; j ++ ) { int v = bytes [ j ] & 0xFF ; hexChars [ j * 2 ] = HEXES_SMALL [ v >>> 4 ] ; hexChars [ j * 2 + 1 ] = HEXES_SMALL [ v & 0x0F ] ; } return new String ( hexChars ) ; }
Calculating lowcase hex string
27,834
protected void onMeasure ( int widthMeasureSpec , int heightMeasureSpec ) { int topOffset = 0 ; View messageView = findMessageView ( ) ; int padding = Screen . dp ( 8 ) ; if ( showAvatar ) { padding += Screen . dp ( 48 ) ; } measureChildWithMargins ( messageView , widthMeasureSpec , padding , heightMeasureSpec , 0 ) ; if ( showDateDiv ) { measureChild ( dateDiv , widthMeasureSpec , heightMeasureSpec ) ; topOffset += Screen . dp ( 16 ) + dateDiv . getMeasuredHeight ( ) ; } if ( showUnreadDiv ) { measureChild ( unreadDiv , widthMeasureSpec , heightMeasureSpec ) ; topOffset += Screen . dp ( 16 ) + unreadDiv . getMeasuredHeight ( ) ; } if ( showAvatar ) { measureChild ( avatarView , widthMeasureSpec , heightMeasureSpec ) ; } setMeasuredDimension ( MeasureSpec . getSize ( widthMeasureSpec ) , messageView . getMeasuredHeight ( ) + topOffset ) ; }
Small hack for avoiding listview selection
27,835
public synchronized < T extends Response > long request ( Request < T > request , RpcCallback < T > callback , long timeout ) { if ( request == null ) { throw new RuntimeException ( "Request can't be null" ) ; } long rid = NEXT_RPC_ID . incrementAndGet ( ) ; this . apiBroker . send ( new ApiBroker . PerformRequest ( rid , request , callback , timeout ) ) ; return rid ; }
Performing API request
27,836
public static byte [ ] openBox ( byte [ ] header , byte [ ] cipherText , ActorBoxKey key ) throws IntegrityException { CBCHmacBox aesCipher = new CBCHmacBox ( Crypto . createAES128 ( key . getKeyAES ( ) ) , Crypto . createSHA256 ( ) , key . getMacAES ( ) ) ; CBCHmacBox kuzCipher = new CBCHmacBox ( new KuznechikFastEngine ( key . getKeyKuz ( ) ) , new Streebog256 ( ) , key . getMacKuz ( ) ) ; byte [ ] kuzPackage = aesCipher . decryptPackage ( header , ByteStrings . substring ( cipherText , 0 , 16 ) , ByteStrings . substring ( cipherText , 16 , cipherText . length - 16 ) ) ; byte [ ] plainText = kuzCipher . decryptPackage ( header , ByteStrings . substring ( kuzPackage , 0 , 16 ) , ByteStrings . substring ( kuzPackage , 16 , kuzPackage . length - 16 ) ) ; int paddingSize = plainText [ plainText . length - 1 ] & 0xFF ; if ( paddingSize < 0 || paddingSize >= 16 ) { throw new IntegrityException ( "Incorrect padding!" ) ; } PKCS7Padding padding = new PKCS7Padding ( ) ; if ( ! padding . validate ( plainText , plainText . length - 1 - paddingSize , paddingSize ) ) { throw new IntegrityException ( "Padding does not isMatch!" ) ; } return ByteStrings . substring ( plainText , 0 , plainText . length - 1 - paddingSize ) ; }
Opening Encrypted box
27,837
public static byte [ ] closeBox ( byte [ ] header , byte [ ] plainText , byte [ ] random32 , ActorBoxKey key ) throws IntegrityException { CBCHmacBox aesCipher = new CBCHmacBox ( Crypto . createAES128 ( key . getKeyAES ( ) ) , Crypto . createSHA256 ( ) , key . getMacAES ( ) ) ; CBCHmacBox kuzCipher = new CBCHmacBox ( new KuznechikFastEngine ( key . getKeyKuz ( ) ) , new Streebog256 ( ) , key . getMacKuz ( ) ) ; int paddingSize = ( plainText . length + 1 ) % 16 ; byte [ ] paddedPlainText = new byte [ plainText . length + 1 + paddingSize ] ; ByteStrings . write ( paddedPlainText , 0 , plainText , 0 , plainText . length ) ; paddedPlainText [ paddedPlainText . length - 1 ] = ( byte ) paddingSize ; PKCS7Padding padding = new PKCS7Padding ( ) ; padding . padding ( paddedPlainText , plainText . length , paddingSize ) ; byte [ ] kuzIv = ByteStrings . substring ( random32 , 0 , 16 ) ; byte [ ] aesIv = ByteStrings . substring ( random32 , 16 , 16 ) ; byte [ ] kuzPackage = ByteStrings . merge ( kuzIv , kuzCipher . encryptPackage ( header , kuzIv , paddedPlainText ) ) ; return ByteStrings . merge ( aesIv , aesCipher . encryptPackage ( header , aesIv , kuzPackage ) ) ; }
Closing encrypted box
27,838
public static boolean contains ( String [ ] vals , String value ) { for ( int i = 0 ; i < vals . length ; i ++ ) { if ( vals [ i ] . equals ( value ) ) { return true ; } } return false ; }
Checking if string array contains value
27,839
public static < T > boolean equalsE ( T a , T b ) { if ( a == null && b == null ) { return true ; } if ( a != null && b == null ) { return false ; } if ( a == null ) { return false ; } return a . equals ( b ) ; }
Equals with null checking
27,840
public static < T > List < T > last ( List < T > elements , int limit ) { ArrayList < T > res = new ArrayList < T > ( ) ; for ( int i = 0 ; i < elements . size ( ) ; i ++ ) { if ( res . size ( ) >= limit ) { break ; } res . add ( elements . get ( elements . size ( ) - 1 - i ) ) ; } return res ; }
Getting last elements of list in reverse order
27,841
public static long [ ] unbox ( List < Long > list ) { long [ ] res = new long [ list . size ( ) ] ; for ( int i = 0 ; i < res . length ; i ++ ) { res [ i ] = list . get ( i ) ; } return res ; }
Unboxing long list
27,842
public synchronized void onGlobalCounterChanged ( int value ) { globalCounter . change ( value ) ; if ( ! isAppVisible . get ( ) ) { globalTempCounter . change ( value ) ; } }
Notify from Modules about global counters changed
27,843
public void addOrUpdateItem ( T item ) { synchronized ( LOCK ) { cache . onObjectUpdated ( item . getEngineId ( ) , item ) ; List < T > items = new ArrayList < T > ( ) ; items . add ( item ) ; asyncStorageInt . addOrUpdateItems ( items ) ; for ( ListEngineDisplayListener < T > l : listeners ) { l . addOrUpdate ( item ) ; } } }
Main List Engine
27,844
private Promise < OwnIdentity > fetchOwnIdentity ( ) { return Promise . success ( new OwnIdentity ( ownKeys . getKeyGroupId ( ) , ownKeys . getIdentityKey ( ) ) ) ; }
Fetching Own Identity key and group id
27,845
private Promise < PrivateKey > fetchPreKey ( byte [ ] publicKey ) { try { return Promise . success ( ManagedList . of ( ownKeys . getPreKeys ( ) ) . filter ( PrivateKey . PRE_KEY_EQUALS ( publicKey ) ) . first ( ) ) ; } catch ( Exception e ) { Log . d ( TAG , "Unable to find own pre key " + Crypto . keyHash ( publicKey ) ) ; for ( PrivateKey p : ownKeys . getPreKeys ( ) ) { Log . d ( TAG , "Have: " + Crypto . keyHash ( p . getPublicKey ( ) ) ) ; } throw e ; } }
Fetching own private pre key by public key
27,846
private Promise < PrivateKey > fetchPreKey ( long keyId ) { try { return Promise . success ( ManagedList . of ( ownKeys . getPreKeys ( ) ) . filter ( PrivateKey . PRE_KEY_EQUALS_ID ( keyId ) ) . first ( ) ) ; } catch ( Exception e ) { Log . d ( TAG , "Unable to find own pre key #" + keyId ) ; throw e ; } }
Fetching own pre key by id
27,847
private Promise < UserKeys > fetchUserGroups ( final int uid ) { User user = users ( ) . getValue ( uid ) ; if ( user == null ) { throw new RuntimeException ( "Unable to find user #" + uid ) ; } final UserKeys userKeys = getCachedUserKeys ( uid ) ; if ( userKeys != null ) { return Promise . success ( userKeys ) ; } return api ( new RequestLoadPublicKeyGroups ( new ApiUserOutPeer ( uid , user . getAccessHash ( ) ) ) ) . map ( new Function < ResponsePublicKeyGroups , ArrayList < UserKeysGroup > > ( ) { public ArrayList < UserKeysGroup > apply ( ResponsePublicKeyGroups response ) { ArrayList < UserKeysGroup > keysGroups = new ArrayList < > ( ) ; for ( ApiEncryptionKeyGroup keyGroup : response . getPublicKeyGroups ( ) ) { UserKeysGroup validatedKeysGroup = validateUserKeysGroup ( uid , keyGroup ) ; if ( validatedKeysGroup != null ) { keysGroups . add ( validatedKeysGroup ) ; } } return keysGroups ; } } ) . map ( new Function < ArrayList < UserKeysGroup > , UserKeys > ( ) { public UserKeys apply ( ArrayList < UserKeysGroup > userKeysGroups ) { UserKeys userKeys = new UserKeys ( uid , userKeysGroups . toArray ( new UserKeysGroup [ userKeysGroups . size ( ) ] ) ) ; cacheUserKeys ( userKeys ) ; return userKeys ; } } ) ; }
Fetching all user s key groups
27,848
private Promise < PublicKey > fetchUserPreKey ( final int uid , final int keyGroupId , final long keyId ) { User user = users ( ) . getValue ( uid ) ; if ( user == null ) { throw new RuntimeException ( "Unable to find user #" + uid ) ; } return pickUserGroup ( uid , keyGroupId ) . flatMap ( new Function < Tuple2 < UserKeysGroup , UserKeys > , Promise < PublicKey > > ( ) { public Promise < PublicKey > apply ( final Tuple2 < UserKeysGroup , UserKeys > keysGroup ) { for ( PublicKey p : keysGroup . getT1 ( ) . getEphemeralKeys ( ) ) { if ( p . getKeyId ( ) == keyId ) { return Promise . success ( p ) ; } } ArrayList < Long > ids = new ArrayList < Long > ( ) ; ids . add ( keyId ) ; final UserKeysGroup finalKeysGroup = keysGroup . getT1 ( ) ; return api ( new RequestLoadPublicKey ( new ApiUserOutPeer ( uid , getUser ( uid ) . getAccessHash ( ) ) , keyGroupId , ids ) ) . map ( new Function < ResponsePublicKeys , PublicKey > ( ) { public PublicKey apply ( ResponsePublicKeys responsePublicKeys ) { if ( responsePublicKeys . getPublicKey ( ) . size ( ) == 0 ) { throw new RuntimeException ( "Unable to find public key on server" ) ; } ApiEncryptionKeySignature sig = null ; for ( ApiEncryptionKeySignature s : responsePublicKeys . getSignatures ( ) ) { if ( s . getKeyId ( ) == keyId && "Ed25519" . equals ( s . getSignatureAlg ( ) ) ) { sig = s ; break ; } } if ( sig == null ) { throw new RuntimeException ( "Unable to find public key on server" ) ; } ApiEncryptionKey key = responsePublicKeys . getPublicKey ( ) . get ( 0 ) ; byte [ ] keyHash = RatchetKeySignature . hashForSignature ( key . getKeyId ( ) , key . getKeyAlg ( ) , key . getKeyMaterial ( ) ) ; if ( ! Curve25519 . verifySignature ( keysGroup . getT1 ( ) . getIdentityKey ( ) . getPublicKey ( ) , keyHash , sig . getSignature ( ) ) ) { throw new RuntimeException ( "Key signature does not isMatch" ) ; } PublicKey pkey = new PublicKey ( keyId , key . getKeyAlg ( ) , key . getKeyMaterial ( ) ) ; UserKeysGroup userKeysGroup = finalKeysGroup . addPublicKey ( pkey ) ; cacheUserKeys ( keysGroup . getT2 ( ) . removeUserKeyGroup ( userKeysGroup . getKeyGroupId ( ) ) . addUserKeyGroup ( userKeysGroup ) ) ; return pkey ; } } ) ; } } ) ; }
Fetching user s pre key by key id
27,849
private Promise < PublicKey > fetchUserPreKey ( final int uid , final int keyGroupId ) { return pickUserGroup ( uid , keyGroupId ) . flatMap ( new Function < Tuple2 < UserKeysGroup , UserKeys > , Promise < PublicKey > > ( ) { public Promise < PublicKey > apply ( final Tuple2 < UserKeysGroup , UserKeys > keyGroups ) { return api ( new RequestLoadPrePublicKeys ( new ApiUserOutPeer ( uid , getUser ( uid ) . getAccessHash ( ) ) , keyGroupId ) ) . map ( new Function < ResponsePublicKeys , PublicKey > ( ) { public PublicKey apply ( ResponsePublicKeys response ) { if ( response . getPublicKey ( ) . size ( ) == 0 ) { throw new RuntimeException ( "User doesn't have pre keys" ) ; } ApiEncryptionKey key = response . getPublicKey ( ) . get ( 0 ) ; ApiEncryptionKeySignature sig = null ; for ( ApiEncryptionKeySignature s : response . getSignatures ( ) ) { if ( s . getKeyId ( ) == key . getKeyId ( ) && "Ed25519" . equals ( s . getSignatureAlg ( ) ) ) { sig = s ; break ; } } if ( sig == null ) { throw new RuntimeException ( "Unable to find public key on server" ) ; } byte [ ] keyHash = RatchetKeySignature . hashForSignature ( key . getKeyId ( ) , key . getKeyAlg ( ) , key . getKeyMaterial ( ) ) ; if ( ! Curve25519 . verifySignature ( keyGroups . getT1 ( ) . getIdentityKey ( ) . getPublicKey ( ) , keyHash , sig . getSignature ( ) ) ) { throw new RuntimeException ( "Key signature does not isMatch" ) ; } return new PublicKey ( key . getKeyId ( ) , key . getKeyAlg ( ) , key . getKeyMaterial ( ) ) ; } } ) ; } } ) ; }
Fetching user s random pre key
27,850
private void onPublicKeysGroupAdded ( int uid , ApiEncryptionKeyGroup keyGroup ) { UserKeys userKeys = getCachedUserKeys ( uid ) ; if ( userKeys == null ) { return ; } UserKeysGroup validatedKeysGroup = validateUserKeysGroup ( uid , keyGroup ) ; if ( validatedKeysGroup != null ) { UserKeys updatedUserKeys = userKeys . addUserKeyGroup ( validatedKeysGroup ) ; cacheUserKeys ( updatedUserKeys ) ; context ( ) . getEncryption ( ) . getEncryptedChatManager ( uid ) . send ( new EncryptedPeerActor . KeyGroupUpdated ( userKeys ) ) ; } }
Handler for adding new key group
27,851
private void onPublicKeysGroupRemoved ( int uid , int keyGroupId ) { UserKeys userKeys = getCachedUserKeys ( uid ) ; if ( userKeys == null ) { return ; } UserKeys updatedUserKeys = userKeys . removeUserKeyGroup ( keyGroupId ) ; cacheUserKeys ( updatedUserKeys ) ; context ( ) . getEncryption ( ) . getEncryptedChatManager ( uid ) . send ( new EncryptedPeerActor . KeyGroupUpdated ( userKeys ) ) ; }
Handler for removing key group
27,852
public void clearPref ( ) { try { ( ( ClcJavaPreferenceStorage ) modules . getPreferences ( ) ) . getPref ( ) . clear ( ) ; } catch ( BackingStoreException e ) { logger . error ( "Cannot clear preferences" , e ) ; } }
clear java preferences
27,853
public static Bitmap loadBitmap ( Uri uri , Context context ) throws ImageLoadException { return loadBitmap ( new UriSource ( uri , context ) ) ; }
Loading bitmap without any modifications
27,854
public static Bitmap loadBitmapOptimized ( Uri uri , Context context ) throws ImageLoadException { return loadBitmapOptimized ( uri , context , MAX_PIXELS ) ; }
Loading bitmap with optimized loaded size less than 1 . 4 MPX
27,855
public static byte [ ] save ( Bitmap src ) throws ImageSaveException { return save ( src , Bitmap . CompressFormat . JPEG , JPEG_QUALITY ) ; }
Saving image in jpeg to byte array with quality 80
27,856
public static byte [ ] saveHq ( Bitmap src ) throws ImageSaveException { return save ( src , Bitmap . CompressFormat . JPEG , JPEG_QUALITY_HQ ) ; }
Saving image in jpeg to byte array with better quality 90
27,857
public static void save ( Bitmap src , String fileName ) throws ImageSaveException { saveJpeg ( src , fileName , JPEG_QUALITY ) ; }
Saving image in jpeg to file with quality 80
27,858
public static void saveLq ( Bitmap src , String fileName ) throws ImageSaveException { saveJpeg ( src , fileName , JPEG_QUALITY_LOW ) ; }
Saving image in jpeg to file with quality 55
27,859
public static void savePng ( Bitmap src , String fileName ) throws ImageSaveException { save ( src , fileName , Bitmap . CompressFormat . PNG , 100 ) ; }
Saving image in png to file
27,860
public static void saveBmp ( Bitmap src , String fileName ) throws ImageSaveException { try { BitmapUtil . save ( src , fileName ) ; } catch ( IOException e ) { throw new ImageSaveException ( e ) ; } }
Saving image in bmp to file
27,861
public static int bitmapSize ( Bitmap bitmap ) { if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . KITKAT ) { return bitmap . getByteCount ( ) ; } else { return bitmap . getRowBytes ( ) * bitmap . getHeight ( ) ; } }
Calculating allocated memory for bitmap
27,862
private static ReuseResult loadBitmapReuseExact ( ImageSource source , Bitmap dest ) throws ImageLoadException { ImageMetadata metadata = source . getImageMetadata ( ) ; boolean tryReuse = false ; if ( dest . isMutable ( ) && dest . getWidth ( ) == metadata . getW ( ) && dest . getHeight ( ) == metadata . getH ( ) ) { if ( Build . VERSION . SDK_INT >= 19 ) { tryReuse = true ; } else if ( Build . VERSION . SDK_INT >= 11 ) { if ( metadata . getFormat ( ) == ImageFormat . JPEG || metadata . getFormat ( ) == ImageFormat . PNG ) { tryReuse = true ; } } } if ( tryReuse ) { return source . loadBitmap ( dest ) ; } else { return new ReuseResult ( loadBitmap ( source ) , false ) ; } }
Loading image with reuse bitmap of same size as source
27,863
private static void save ( Bitmap src , String fileName , Bitmap . CompressFormat format , int quality ) throws ImageSaveException { FileOutputStream outputStream = null ; try { outputStream = new FileOutputStream ( fileName ) ; src . compress ( format , quality , outputStream ) ; outputStream . close ( ) ; } catch ( IOException e ) { throw new ImageSaveException ( e ) ; } finally { if ( outputStream != null ) { try { outputStream . close ( ) ; } catch ( IOException e1 ) { e1 . printStackTrace ( ) ; } } } }
Saving image to file
27,864
private static ILigand [ ] getLigands ( IAtom atom , IAtomContainer container , IAtom exclude ) { List < IAtom > neighbors = container . getConnectedAtomsList ( atom ) ; ILigand [ ] ligands = new ILigand [ neighbors . size ( ) - 1 ] ; int i = 0 ; for ( IAtom neighbor : neighbors ) { if ( ! neighbor . equals ( exclude ) ) ligands [ i ++ ] = new Ligand ( container , new VisitedAtoms ( ) , atom , neighbor ) ; } return ligands ; }
Obtain the ligands connected to the atom excluding exclude . This is mainly meant as a utility for double - bond labelling .
27,865
public static ILigand [ ] getLigandLigands ( ILigand ligand ) { if ( ligand instanceof TerminalLigand ) return new ILigand [ 0 ] ; IAtomContainer container = ligand . getAtomContainer ( ) ; IAtom ligandAtom = ligand . getLigandAtom ( ) ; IAtom centralAtom = ligand . getCentralAtom ( ) ; VisitedAtoms visitedAtoms = ligand . getVisitedAtoms ( ) ; List < IBond > bonds = container . getConnectedBondsList ( ligandAtom ) ; List < ILigand > ligands = new ArrayList < ILigand > ( ) ; for ( IBond bond : bonds ) { if ( bond . contains ( centralAtom ) ) { if ( Order . SINGLE == bond . getOrder ( ) ) continue ; int duplication = getDuplication ( bond . getOrder ( ) ) - 1 ; if ( duplication > 0 ) { for ( int i = 1 ; i <= duplication ; i ++ ) { ligands . add ( new TerminalLigand ( container , visitedAtoms , ligandAtom , centralAtom ) ) ; } } } else { int duplication = getDuplication ( bond . getOrder ( ) ) ; IAtom connectedAtom = bond . getOther ( ligandAtom ) ; if ( visitedAtoms . isVisited ( connectedAtom ) ) { ligands . add ( new TerminalLigand ( container , visitedAtoms , ligandAtom , connectedAtom ) ) ; } else { ligands . add ( new Ligand ( container , visitedAtoms , ligandAtom , connectedAtom ) ) ; } for ( int i = 2 ; i <= duplication ; i ++ ) { ligands . add ( new TerminalLigand ( container , visitedAtoms , ligandAtom , connectedAtom ) ) ; } } } return ligands . toArray ( new ILigand [ 0 ] ) ; }
Returns a CIP - expanded array of side chains of a ligand . If the ligand atom is only connected to the chiral atom the method will return an empty list . The expansion involves the CIP rules so that a double bonded oxygen will be represented twice in the list .
27,866
private void readCoordinates ( IChemModel model ) throws CDKException , IOException { IAtomContainer container = model . getBuilder ( ) . newInstance ( IAtomContainer . class ) ; String line = input . readLine ( ) ; line = input . readLine ( ) ; line = input . readLine ( ) ; line = input . readLine ( ) ; while ( input . ready ( ) ) { line = input . readLine ( ) ; if ( ( line == null ) || ( line . indexOf ( "-----" ) >= 0 ) ) { break ; } int atomicNumber = 0 ; StringReader sr = new StringReader ( line ) ; StreamTokenizer token = new StreamTokenizer ( sr ) ; token . nextToken ( ) ; if ( token . nextToken ( ) == StreamTokenizer . TT_NUMBER ) { atomicNumber = ( int ) token . nval ; if ( atomicNumber == 0 ) { continue ; } } else { throw new IOException ( "Error reading coordinates" ) ; } token . nextToken ( ) ; double x = 0.0 ; double y = 0.0 ; double z = 0.0 ; if ( token . nextToken ( ) == StreamTokenizer . TT_NUMBER ) { x = token . nval ; } else { throw new IOException ( "Error reading coordinates" ) ; } if ( token . nextToken ( ) == StreamTokenizer . TT_NUMBER ) { y = token . nval ; } else { throw new IOException ( "Error reading coordinates" ) ; } if ( token . nextToken ( ) == StreamTokenizer . TT_NUMBER ) { z = token . nval ; } else { throw new IOException ( "Error reading coordinates" ) ; } String symbol = "Du" ; symbol = PeriodicTable . getSymbol ( atomicNumber ) ; IAtom atom = model . getBuilder ( ) . newInstance ( IAtom . class , symbol ) ; atom . setPoint3d ( new Point3d ( x , y , z ) ) ; container . addAtom ( atom ) ; } IAtomContainerSet moleculeSet = model . getBuilder ( ) . newInstance ( IAtomContainerSet . class ) ; moleculeSet . addAtomContainer ( model . getBuilder ( ) . newInstance ( IAtomContainer . class , container ) ) ; model . setMoleculeSet ( moleculeSet ) ; }
Reads a set of coordinates into ChemModel .
27,867
private void readPartialCharges ( IChemModel model ) throws CDKException , IOException { logger . info ( "Reading partial atomic charges" ) ; IAtomContainerSet moleculeSet = model . getMoleculeSet ( ) ; IAtomContainer molecule = moleculeSet . getAtomContainer ( 0 ) ; String line = input . readLine ( ) ; while ( input . ready ( ) ) { line = input . readLine ( ) ; logger . debug ( "Read charge block line: " + line ) ; if ( ( line == null ) || ( line . indexOf ( "Sum of Mulliken charges" ) >= 0 ) ) { logger . debug ( "End of charge block found" ) ; break ; } StringReader sr = new StringReader ( line ) ; StreamTokenizer tokenizer = new StreamTokenizer ( sr ) ; if ( tokenizer . nextToken ( ) == StreamTokenizer . TT_NUMBER ) { int atomCounter = ( int ) tokenizer . nval ; tokenizer . nextToken ( ) ; double charge = 0.0 ; if ( tokenizer . nextToken ( ) == StreamTokenizer . TT_NUMBER ) { charge = ( double ) tokenizer . nval ; logger . debug ( "Found charge for atom " + atomCounter + ": " + charge ) ; } else { throw new CDKException ( "Error while reading charge: expected double." ) ; } IAtom atom = molecule . getAtom ( atomCounter - 1 ) ; atom . setCharge ( charge ) ; } } }
Reads partial atomic charges and add the to the given ChemModel .
27,868
public DescriptorValue calculate ( IAtom atom , IAtomContainer container ) { int period ; String symbol = atom . getSymbol ( ) ; period = periodicTable . get ( symbol ) ; return new DescriptorValue ( getSpecification ( ) , getParameterNames ( ) , getParameters ( ) , new IntegerResult ( period ) , NAMES ) ; }
This method calculates the period of an atom .
27,869
private int skipDigits ( ) { char ch ; int i = 0 ; while ( index < format . length ( ) ) { if ( Character . isDigit ( ch = format . charAt ( index ) ) ) { index ++ ; i = i * 10 + Character . digit ( ch , 10 ) ; } else { break ; } } return i ; }
Skip digits and return the number they form .
27,870
public Partition getAutomorphismPartition ( ) { final int n = group . getSize ( ) ; final DisjointSetForest forest = new DisjointSetForest ( n ) ; group . apply ( new PermutationGroup . Backtracker ( ) { boolean [ ] inOrbit = new boolean [ n ] ; private int inOrbitCount = 0 ; private boolean isFinished ; public boolean isFinished ( ) { return isFinished ; } public void applyTo ( Permutation p ) { for ( int elementX = 0 ; elementX < n ; elementX ++ ) { if ( inOrbit [ elementX ] ) { continue ; } else { int elementY = p . get ( elementX ) ; while ( elementY != elementX ) { if ( ! inOrbit [ elementY ] ) { inOrbitCount ++ ; inOrbit [ elementY ] = true ; forest . makeUnion ( elementX , elementY ) ; } elementY = p . get ( elementY ) ; } } } if ( inOrbitCount == n ) { isFinished = true ; } } } ) ; Partition partition = new Partition ( ) ; for ( int [ ] set : forest . getSets ( ) ) { partition . addCell ( set ) ; } partition . order ( ) ; return partition ; }
The automorphism partition is a partition of the elements of the group .
27,871
private String getHalfMatrixString ( Permutation permutation ) { StringBuilder builder = new StringBuilder ( permutation . size ( ) ) ; int size = permutation . size ( ) ; for ( int indexI = 0 ; indexI < size - 1 ; indexI ++ ) { for ( int indexJ = indexI + 1 ; indexJ < size ; indexJ ++ ) { builder . append ( getConnectivity ( permutation . get ( indexI ) , permutation . get ( indexJ ) ) ) ; } } return builder . toString ( ) ; }
Get the upper - half of the adjacency matrix under the permutation .
27,872
private void refine ( PermutationGroup group , Partition coarser ) { int vertexCount = getVertexCount ( ) ; Partition finer = equitableRefiner . refine ( coarser ) ; int firstNonDiscreteCell = finer . getIndexOfFirstNonDiscreteCell ( ) ; if ( firstNonDiscreteCell == - 1 ) { firstNonDiscreteCell = vertexCount ; } Permutation pi1 = new Permutation ( firstNonDiscreteCell ) ; Result result = Result . BETTER ; if ( bestExist ) { pi1 = finer . setAsPermutation ( firstNonDiscreteCell ) ; result = compareRowwise ( pi1 ) ; } if ( finer . size ( ) == vertexCount ) { if ( ! bestExist ) { best = finer . toPermutation ( ) ; first = finer . toPermutation ( ) ; bestExist = true ; } else { if ( result == Result . BETTER ) { best = new Permutation ( pi1 ) ; } else if ( result == Result . EQUAL ) { group . enter ( pi1 . multiply ( best . invert ( ) ) ) ; } } } else { if ( result != Result . WORSE ) { Set < Integer > blockCopy = finer . copyBlock ( firstNonDiscreteCell ) ; for ( int vertexInBlock = 0 ; vertexInBlock < vertexCount ; vertexInBlock ++ ) { if ( blockCopy . contains ( vertexInBlock ) ) { Partition nextPartition = finer . splitBefore ( firstNonDiscreteCell , vertexInBlock ) ; this . refine ( group , nextPartition ) ; int [ ] permF = new int [ vertexCount ] ; int [ ] invF = new int [ vertexCount ] ; for ( int i = 0 ; i < vertexCount ; i ++ ) { permF [ i ] = i ; invF [ i ] = i ; } for ( int j = 0 ; j <= firstNonDiscreteCell ; j ++ ) { int x = nextPartition . getFirstInCell ( j ) ; int i = invF [ x ] ; int h = permF [ j ] ; permF [ j ] = x ; permF [ i ] = h ; invF [ h ] = i ; invF [ x ] = j ; } Permutation pPermF = new Permutation ( permF ) ; group . changeBase ( pPermF ) ; for ( int j = 0 ; j < vertexCount ; j ++ ) { Permutation g = group . get ( firstNonDiscreteCell , j ) ; if ( g != null ) { blockCopy . remove ( g . get ( vertexInBlock ) ) ; } } } } } } }
Does the work of the class that refines a coarse partition into a finer one using the supplied automorphism group to prune the search .
27,873
private Result compareRowwise ( Permutation perm ) { int m = perm . size ( ) ; for ( int i = 0 ; i < m - 1 ; i ++ ) { for ( int j = i + 1 ; j < m ; j ++ ) { int x = getConnectivity ( best . get ( i ) , best . get ( j ) ) ; int y = getConnectivity ( perm . get ( i ) , perm . get ( j ) ) ; if ( x > y ) return Result . WORSE ; if ( x < y ) return Result . BETTER ; } } return Result . EQUAL ; }
Check a permutation to see if it is better equal or worse than the current best .
27,874
public long order ( ) { long total = 1 ; for ( int i = 0 ; i < size ; i ++ ) { int sum = 0 ; for ( int j = 0 ; j < size ; j ++ ) { if ( this . permutations [ i ] [ j ] != null ) { sum ++ ; } } total *= sum ; } return total ; }
Calculates the size of the group .
27,875
public List < Permutation > transversal ( final PermutationGroup subgroup ) { final long m = this . order ( ) / subgroup . order ( ) ; final List < Permutation > results = new ArrayList < Permutation > ( ) ; Backtracker transversalBacktracker = new Backtracker ( ) { private boolean finished = false ; public void applyTo ( Permutation p ) { for ( Permutation f : results ) { Permutation h = f . invert ( ) . multiply ( p ) ; if ( subgroup . test ( h ) == size ) { return ; } } results . add ( p ) ; if ( results . size ( ) >= m ) { this . finished = true ; } } public boolean isFinished ( ) { return finished ; } } ; this . apply ( transversalBacktracker ) ; return results ; }
Generate a transversal of a subgroup in this group .
27,876
public List < Permutation > all ( ) { final List < Permutation > permutations = new ArrayList < Permutation > ( ) ; Backtracker counter = new Backtracker ( ) { public void applyTo ( Permutation p ) { permutations . add ( p ) ; } public boolean isFinished ( ) { return false ; } } ; this . apply ( counter ) ; return permutations ; }
Generate the whole group from the compact list of permutations .
27,877
public void enter ( Permutation g ) { int deg = size ; int i = test ( g ) ; if ( i == deg ) { return ; } else { permutations [ i ] [ g . get ( base . get ( i ) ) ] = new Permutation ( g ) ; } for ( int j = 0 ; j <= i ; j ++ ) { for ( int a = 0 ; a < deg ; a ++ ) { Permutation h = permutations [ j ] [ a ] ; if ( h != null ) { Permutation f = g . multiply ( h ) ; enter ( f ) ; } } } }
Enter the permutation g into this group .
27,878
public void readDictionary ( Reader reader , String name ) { name = name . toLowerCase ( ) ; logger . debug ( "Reading dictionary: " , name ) ; if ( ! dictionaries . containsKey ( name ) ) { try { Dictionary dictionary = Dictionary . unmarshal ( reader ) ; dictionaries . put ( name , dictionary ) ; logger . debug ( " ... loaded and stored" ) ; } catch ( Exception exception ) { logger . error ( "Could not read dictionary: " , name ) ; logger . debug ( exception ) ; } } else { logger . error ( "Dictionary already loaded: " , name ) ; } }
Reads a custom dictionary into the database .
27,879
public boolean hasEntry ( String dictName , String entryID ) { if ( hasDictionary ( dictName ) ) { Dictionary dictionary = ( Dictionary ) dictionaries . get ( dictName ) ; return dictionary . hasEntry ( entryID . toLowerCase ( ) ) ; } else { return false ; } }
Returns true if the given dictionary contains the given entry .
27,880
public void removeMonomer ( String name ) { if ( monomers . containsKey ( name ) ) { Monomer monomer = ( Monomer ) monomers . get ( name ) ; this . remove ( monomer ) ; monomers . remove ( name ) ; } }
Removes a particular monomer specified by its name .
27,881
public DescriptorValue calculate ( IAtom atom , IAtomContainer atomContainer ) { IAtomContainer clonedAtomContainer ; try { clonedAtomContainer = ( IAtomContainer ) atomContainer . clone ( ) ; } catch ( CloneNotSupportedException e ) { return new DescriptorValue ( getSpecification ( ) , getParameterNames ( ) , getParameters ( ) , new BooleanResult ( false ) , NAMES , e ) ; } IAtom clonedAtom = clonedAtomContainer . getAtom ( atomContainer . indexOf ( atom ) ) ; boolean isProtonInPiSystem = false ; IAtomContainer mol = clonedAtom . getBuilder ( ) . newInstance ( IAtomContainer . class , clonedAtomContainer ) ; if ( checkAromaticity ) { try { AtomContainerManipulator . percieveAtomTypesAndConfigureAtoms ( mol ) ; Aromaticity . cdkLegacy ( ) . apply ( mol ) ; } catch ( CDKException e ) { return new DescriptorValue ( getSpecification ( ) , getParameterNames ( ) , getParameters ( ) , new BooleanResult ( false ) , NAMES , e ) ; } } if ( atom . getSymbol ( ) . equals ( "H" ) ) { if ( acold != clonedAtomContainer ) { acold = clonedAtomContainer ; acSet = ConjugatedPiSystemsDetector . detect ( mol ) ; } Iterator < IAtomContainer > detected = acSet . atomContainers ( ) . iterator ( ) ; List < IAtom > neighboors = mol . getConnectedAtomsList ( clonedAtom ) ; for ( IAtom neighboor : neighboors ) { while ( detected . hasNext ( ) ) { IAtomContainer detectedAC = detected . next ( ) ; if ( ( detectedAC != null ) && ( detectedAC . contains ( neighboor ) ) ) { isProtonInPiSystem = true ; break ; } } } } return new DescriptorValue ( getSpecification ( ) , getParameterNames ( ) , getParameters ( ) , new BooleanResult ( isProtonInPiSystem ) , NAMES ) ; }
The method is a proton descriptor that evaluates if a proton is joined to a conjugated system .
27,882
public boolean matches ( IAtomContainer atomContainer , boolean initializeTarget ) throws CDKException { if ( ! GeometryUtil . has3DCoordinates ( atomContainer ) ) throw new CDKException ( "Molecule must have 3D coordinates" ) ; if ( pharmacophoreQuery == null ) throw new CDKException ( "Must set the query pharmacophore before matching" ) ; if ( ! checkQuery ( pharmacophoreQuery ) ) throw new CDKException ( "A problem in the query. Make sure all pharmacophore groups of the same symbol have the same same SMARTS" ) ; String title = ( String ) atomContainer . getTitle ( ) ; if ( initializeTarget ) pharmacophoreMolecule = getPharmacophoreMolecule ( atomContainer ) ; else { for ( IAtom iAtom : pharmacophoreMolecule . atoms ( ) ) { PharmacophoreAtom patom = PharmacophoreAtom . get ( iAtom ) ; List < Integer > tmpList = new ArrayList < Integer > ( ) ; for ( int idx : patom . getMatchingAtoms ( ) ) tmpList . add ( idx ) ; Point3d coords = getEffectiveCoordinates ( atomContainer , tmpList ) ; patom . setPoint3d ( coords ) ; } } if ( pharmacophoreMolecule . getAtomCount ( ) < pharmacophoreQuery . getAtomCount ( ) ) { logger . debug ( "Target [" + title + "] did not match the query SMARTS. Skipping constraints" ) ; return false ; } mappings = Pattern . findSubstructure ( pharmacophoreQuery ) . matchAll ( pharmacophoreMolecule ) ; return mappings . atLeast ( 1 ) ; }
Performs the pharmacophore matching .
27,883
public List < List < IBond > > getMatchingPharmacophoreBonds ( ) { if ( mappings == null ) return null ; List < List < IBond > > bonds = new ArrayList < > ( ) ; for ( Map < IBond , IBond > map : mappings . toBondMap ( ) ) { bonds . add ( new ArrayList < > ( map . values ( ) ) ) ; } return bonds ; }
Get the matching pharmacophore constraints .
27,884
public List < HashMap < IBond , IBond > > getTargetQueryBondMappings ( ) { if ( mappings == null ) return null ; List < HashMap < IBond , IBond > > bondMap = new ArrayList < > ( ) ; for ( Map < IBond , IBond > map : mappings . toBondMap ( ) ) { bondMap . add ( new HashMap < > ( HashBiMap . create ( map ) . inverse ( ) ) ) ; } return bondMap ; }
Return a list of HashMap s that allows one to get the query constraint for a given pharmacophore bond .
27,885
public List < List < PharmacophoreAtom > > getMatchingPharmacophoreAtoms ( ) { if ( pharmacophoreMolecule == null || mappings == null ) return null ; return getPCoreAtoms ( mappings ) ; }
Get the matching pharmacophore groups .
27,886
public List < List < PharmacophoreAtom > > getUniqueMatchingPharmacophoreAtoms ( ) { if ( pharmacophoreMolecule == null || mappings == null ) return null ; return getPCoreAtoms ( mappings . uniqueAtoms ( ) ) ; }
Get the uniue matching pharmacophore groups .
27,887
public static boolean deAromatize ( IRing ring ) { boolean allaromatic = true ; for ( int i = 0 ; i < ring . getBondCount ( ) ; i ++ ) { if ( ! ring . getBond ( i ) . getFlag ( CDKConstants . ISAROMATIC ) ) allaromatic = false ; } if ( ! allaromatic ) return false ; for ( int i = 0 ; i < ring . getBondCount ( ) ; i ++ ) { if ( ring . getBond ( i ) . getFlag ( CDKConstants . ISAROMATIC ) ) ring . getBond ( i ) . setOrder ( IBond . Order . SINGLE ) ; } boolean result = false ; IMolecularFormula formula = MolecularFormulaManipulator . getMolecularFormula ( ring ) ; if ( ring . getRingSize ( ) == 6 ) { if ( MolecularFormulaManipulator . getElementCount ( formula , new Element ( "C" ) ) == 6 ) { result = DeAromatizationTool . deAromatizeBenzene ( ring ) ; } else if ( MolecularFormulaManipulator . getElementCount ( formula , new Element ( "C" ) ) == 5 && MolecularFormulaManipulator . getElementCount ( formula , new Element ( "N" ) ) == 1 ) { result = DeAromatizationTool . deAromatizePyridine ( ring ) ; } } if ( ring . getRingSize ( ) == 5 ) { if ( MolecularFormulaManipulator . getElementCount ( formula , new Element ( "C" ) ) == 4 && MolecularFormulaManipulator . getElementCount ( formula , new Element ( "N" ) ) == 1 ) { result = deAromatizePyrolle ( ring ) ; } } return result ; }
Methods that takes a ring of which all bonds are aromatic and assigns single and double bonds . It does this in a non - general way by looking at the ring size and take everything as a special case .
27,888
private double calculateAngleBetweenTwoLines ( Vector3d a , Vector3d b , Vector3d c , Vector3d d ) { Vector3d firstLine = new Vector3d ( ) ; firstLine . sub ( a , b ) ; Vector3d secondLine = new Vector3d ( ) ; secondLine . sub ( c , d ) ; Vector3d firstVec = new Vector3d ( firstLine ) ; Vector3d secondVec = new Vector3d ( secondLine ) ; return firstVec . angle ( secondVec ) ; }
this method calculates the angle between two bonds given coordinates of their atoms
27,889
private double calculateDistanceBetweenTwoAtoms ( IAtom atom1 , IAtom atom2 ) { double distance ; Point3d firstPoint = atom1 . getPoint3d ( ) ; Point3d secondPoint = atom2 . getPoint3d ( ) ; distance = firstPoint . distance ( secondPoint ) ; return distance ; }
generic method for calculation of distance btw 2 atoms
27,890
private double [ ] calculateDistanceBetweenAtomAndBond ( IAtom proton , IBond theBond ) { Point3d middlePoint = theBond . get3DCenter ( ) ; Point3d protonPoint = proton . getPoint3d ( ) ; double [ ] values = new double [ 4 ] ; values [ 0 ] = middlePoint . distance ( protonPoint ) ; values [ 1 ] = middlePoint . x ; values [ 2 ] = middlePoint . y ; values [ 3 ] = middlePoint . z ; return values ; }
and returns distance and coordinates of middle point
27,891
public Object getParameterType ( String name ) { if ( name . equals ( "checkAromaticity" ) ) return Boolean . TRUE ; return null ; }
Gets the parameterType attribute of the RDFProtonDescriptor object
27,892
public void add ( IMolecularFormulaSet formulaSet ) { for ( IMolecularFormula mf : formulaSet . molecularFormulas ( ) ) { addMolecularFormula ( mf ) ; } }
Adds all molecularFormulas in the AdductFormula to this chemObject .
27,893
public boolean contains ( IIsotope isotope ) { for ( Iterator < IIsotope > it = isotopes ( ) . iterator ( ) ; it . hasNext ( ) ; ) { IIsotope thisIsotope = it . next ( ) ; if ( isTheSame ( thisIsotope , isotope ) ) { return true ; } } return false ; }
True if the AdductFormula contains the given IIsotope object and not the instance . The method looks for other isotopes which has the same symbol natural abundance and exact mass .
27,894
public Integer getCharge ( ) { Integer charge = 0 ; Iterator < IMolecularFormula > componentIterator = components . iterator ( ) ; while ( componentIterator . hasNext ( ) ) { charge += componentIterator . next ( ) . getCharge ( ) ; } return charge ; }
Returns the partial charge of this Adduct . If the charge has not been set the return value is Double . NaN .
27,895
public int getIsotopeCount ( IIsotope isotope ) { int count = 0 ; Iterator < IMolecularFormula > componentIterator = components . iterator ( ) ; while ( componentIterator . hasNext ( ) ) { count += componentIterator . next ( ) . getIsotopeCount ( isotope ) ; } return count ; }
Checks a set of Nodes for the occurrence of the isotope in the adduct formula from a particular isotope . It returns 0 if the does not exist .
27,896
public Iterable < IIsotope > isotopes ( ) { return new Iterable < IIsotope > ( ) { public Iterator < IIsotope > iterator ( ) { return isotopesList ( ) . iterator ( ) ; } } ; }
Returns an Iterator for looping over all isotopes in this adduct formula .
27,897
private List < IIsotope > isotopesList ( ) { List < IIsotope > isotopes = new ArrayList < IIsotope > ( ) ; Iterator < IMolecularFormula > componentIterator = components . iterator ( ) ; while ( componentIterator . hasNext ( ) ) { Iterator < IIsotope > compIsotopes = componentIterator . next ( ) . isotopes ( ) . iterator ( ) ; while ( compIsotopes . hasNext ( ) ) { IIsotope isotope = compIsotopes . next ( ) ; if ( ! isotopes . contains ( isotope ) ) { isotopes . add ( isotope ) ; } } } return isotopes ; }
Returns a List for looping over all isotopes in this adduct formula .
27,898
public void setParameters ( Object [ ] params ) throws CDKException { if ( params . length != 1 ) throw new CDKException ( "ChargeRule expects only one parameter" ) ; if ( ! ( params [ 0 ] instanceof Double ) ) throw new CDKException ( "The parameter must be of type Double" ) ; charge = ( Double ) params [ 0 ] ; }
Sets the parameters attribute of the ChargeRule object .
27,899
public double validate ( IMolecularFormula formula ) throws CDKException { logger . info ( "Start validation of " , formula ) ; if ( formula . getCharge ( ) == null ) { return 0.0 ; } else if ( formula . getCharge ( ) == charge ) { return 1.0 ; } else { return 0.0 ; } }
Validate the charge of this IMolecularFormula .