signature
stringlengths
43
39.1k
implementation
stringlengths
0
450k
public class MiniJPEContentHandler { /** * { @ inheritDoc } */ public Object addYToPoint ( double y , Object point ) { } }
( ( Point ) point ) . setY ( y ) ; return point ;
public class CompressedArray { /** * Compresses the specified byte range using the specified compressionLevel ( constants are * defined in java . util . zip . Deflater ) . */ public static byte [ ] compress ( byte [ ] value , int offset , int length , int compressionLevel ) { } }
/* Create an expandable byte array to hold the compressed data . * You cannot use an array that ' s the same size as the orginal because * there is no guarantee that the compressed data will be smaller than * the uncompressed data . */ ByteArrayOutputStream bos = new ByteArrayOutputStream ( length ) ; Deflater compressor = new Deflater ( ) ; try { compressor . setLevel ( compressionLevel ) ; compressor . setInput ( value , offset , length ) ; compressor . finish ( ) ; final byte [ ] buf = new byte [ 1024 ] ; while ( ! compressor . finished ( ) ) { int count = compressor . deflate ( buf ) ; bos . write ( buf , 0 , count ) ; } } finally { compressor . end ( ) ; } return bos . toByteArray ( ) ;
public class DocEnv { /** * Create a MethodDoc for this MethodSymbol . * Should be called only on symbols representing methods . */ protected void makeMethodDoc ( MethodSymbol meth , TreePath treePath ) { } }
MethodDocImpl result = ( MethodDocImpl ) methodMap . get ( meth ) ; if ( result != null ) { if ( treePath != null ) result . setTreePath ( treePath ) ; } else { result = new MethodDocImpl ( this , meth , treePath ) ; methodMap . put ( meth , result ) ; }
public class PublicIPAddressesInner { /** * Creates or updates a static or dynamic public IP address . * @ param resourceGroupName The name of the resource group . * @ param publicIpAddressName The name of the public IP address . * @ param parameters Parameters supplied to the create or update public IP address operation . * @ throws IllegalArgumentException thrown if parameters fail the validation * @ return the observable to the PublicIPAddressInner object */ public Observable < PublicIPAddressInner > beginCreateOrUpdateAsync ( String resourceGroupName , String publicIpAddressName , PublicIPAddressInner parameters ) { } }
return beginCreateOrUpdateWithServiceResponseAsync ( resourceGroupName , publicIpAddressName , parameters ) . map ( new Func1 < ServiceResponse < PublicIPAddressInner > , PublicIPAddressInner > ( ) { @ Override public PublicIPAddressInner call ( ServiceResponse < PublicIPAddressInner > response ) { return response . body ( ) ; } } ) ;
public class ArtifactArchiver { /** * Backwards compatibility for older builds */ @ SuppressFBWarnings ( value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE" , justification = "Null checks in readResolve are valid since we deserialize and upgrade objects" ) protected Object readResolve ( ) { } }
if ( allowEmptyArchive == null ) { this . allowEmptyArchive = SystemProperties . getBoolean ( ArtifactArchiver . class . getName ( ) + ".warnOnEmpty" ) ; } if ( defaultExcludes == null ) { defaultExcludes = true ; } if ( caseSensitive == null ) { caseSensitive = true ; } return this ;
public class TimeZoneNamesImpl { /** * Load all strings used by the specified time zone . * This is called from the initializer to load default zone ' s * strings . * @ param tzCanonicalID the canonical time zone ID */ private synchronized void loadStrings ( String tzCanonicalID ) { } }
if ( tzCanonicalID == null || tzCanonicalID . length ( ) == 0 ) { return ; } loadTimeZoneNames ( tzCanonicalID ) ; Set < String > mzIDs = getAvailableMetaZoneIDs ( tzCanonicalID ) ; for ( String mzID : mzIDs ) { loadMetaZoneNames ( mzID ) ; }
public class MainActivity { /** * Button onClick listener . * @ param v */ public void buttonClick ( View v ) { } }
switch ( v . getId ( ) ) { case R . id . show : showAppMsg ( ) ; break ; case R . id . cancel_all : AppMsg . cancelAll ( this ) ; break ; default : return ; }
public class SnapshotStore { /** * Loads all available snapshots from disk . * @ return A list of available snapshots . */ private Collection < Snapshot > loadSnapshots ( ) { } }
// Ensure log directories are created . storage . directory ( ) . mkdirs ( ) ; List < Snapshot > snapshots = new ArrayList < > ( ) ; // Iterate through all files in the log directory . for ( File file : storage . directory ( ) . listFiles ( File :: isFile ) ) { // If the file looks like a segment file , attempt to load the segment . if ( SnapshotFile . isSnapshotFile ( file ) ) { SnapshotFile snapshotFile = new SnapshotFile ( file ) ; SnapshotDescriptor descriptor = new SnapshotDescriptor ( FileBuffer . allocate ( file , SnapshotDescriptor . BYTES ) ) ; // Valid segments will have been locked . Segments that resulting from failures during log cleaning will be // unlocked and should ultimately be deleted from disk . if ( descriptor . isLocked ( ) ) { log . debug ( "Loaded disk snapshot: {} ({})" , descriptor . index ( ) , snapshotFile . file ( ) . getName ( ) ) ; snapshots . add ( new FileSnapshot ( snapshotFile , descriptor , this ) ) ; descriptor . close ( ) ; } // If the segment descriptor wasn ' t locked , close and delete the descriptor . else { log . debug ( "Deleting partial snapshot: {} ({})" , descriptor . index ( ) , snapshotFile . file ( ) . getName ( ) ) ; descriptor . close ( ) ; descriptor . delete ( ) ; } } } return snapshots ;
public class FessMessages { /** * Add the created action message for the key ' success . upload _ elevate _ word ' with parameters . * < pre > * message : Uploaded Additional Word file . * < / pre > * @ param property The property name for the message . ( NotNull ) * @ return this . ( NotNull ) */ public FessMessages addSuccessUploadElevateWord ( String property ) { } }
assertPropertyNotNull ( property ) ; add ( property , new UserMessage ( SUCCESS_upload_elevate_word ) ) ; return this ;
public class ElementMatchers { /** * Creates a matcher that matches none of the given methods as { @ link FieldDescription } s * by the { @ link java . lang . Object # equals ( Object ) } method . None of the values must be { @ code null } . * @ param value The input values to be compared against . * @ param < T > The type of the matched object . * @ return A matcher that checks for the equality with none of the given objects . */ public static < T extends FieldDescription > ElementMatcher . Junction < T > noneOf ( Field ... value ) { } }
return definedField ( noneOf ( new FieldList . ForLoadedFields ( value ) ) ) ;
public class ParosTableSessionUrl { /** * / * ( non - Javadoc ) * @ see org . parosproxy . paros . db . paros . TableSessionUrl # deleteAllUrlsForType ( int ) */ @ Override public synchronized void deleteAllUrlsForType ( int type ) throws DatabaseException { } }
try { psDeleteAllUrlsForType . setInt ( 1 , type ) ; psDeleteAllUrlsForType . executeUpdate ( ) ; } catch ( SQLException e ) { throw new DatabaseException ( e ) ; }
public class StringUtility { /** * Method that attempts to break a string up into lines no longer than the * specified line length . * < p > The string is assumed to a large chunk of undifferentiated text such * as base 64 encoded binary data . * @ param str * The input string to be split into lines . * @ param indent * The number of spaces to insert at the start of each line . * @ param numChars * The maximum length of each line ( not counting the indent spaces ) . * @ return A string split into multiple indented lines whose length is less * than the specified length + indent amount . */ @ Deprecated public static String splitAndIndent ( String str , int indent , int numChars ) { } }
final int inputLength = str . length ( ) ; // to prevent resizing , we can predict the size of the indented string // the formatting addition is the indent spaces plus a newline // this length is added once for each line boolean perfectFit = ( inputLength % numChars == 0 ) ; int fullLines = ( inputLength / numChars ) ; int formatLength = perfectFit ? ( indent + 1 ) * fullLines : ( indent + 1 ) * ( fullLines + 1 ) ; int outputLength = inputLength + formatLength ; StringBuilder sb = new StringBuilder ( outputLength ) ; for ( int offset = 0 ; offset < inputLength ; offset += numChars ) { SpaceCharacters . indent ( indent , sb ) ; sb . append ( str , offset , Math . min ( offset + numChars , inputLength ) ) ; sb . append ( '\n' ) ; } return sb . toString ( ) ;
public class SHPRead { /** * Copy data from Shape File into a new table in specified connection . * @ param connection Active connection * @ param tableReference [ [ catalog . ] schema . ] table reference * @ param fileName File path of the SHP file or URI * @ throws java . io . IOException * @ throws java . sql . SQLException */ public static void readShape ( Connection connection , String fileName , String tableReference ) throws IOException , SQLException { } }
readShape ( connection , fileName , tableReference , null ) ;
public class BaseDatasourceFactory { /** * Set the params for this datasource . * @ param database * @ param dataSource */ public void setDatasourceParams ( JdbcDatabase database , ComboPooledDataSource dataSource ) { } }
if ( dataSource != null ) { // Try pooled connection first String strURL = database . getProperty ( SQLParams . JDBC_URL_PARAM ) ; if ( ( strURL == null ) || ( strURL . length ( ) == 0 ) ) strURL = database . getProperty ( SQLParams . DEFAULT_JDBC_URL_PARAM ) ; // Default String strServer = database . getProperty ( SQLParams . DB_SERVER_PARAM ) ; if ( ( strServer == null ) || ( strServer . length ( ) == 0 ) ) strServer = database . getProperty ( SQLParams . DEFAULT_DB_SERVER_PARAM ) ; // Default if ( ( strServer == null ) || ( strServer . length ( ) == 0 ) ) strServer = "localhost" ; // this . getProperty ( DBParams . SERVER ) ; / / ? ? String strDatabaseName = database . getDatabaseName ( true ) ; if ( strURL != null ) { if ( strServer != null ) strURL = Utility . replace ( strURL , "{dbserver}" , strServer ) ; strURL = Utility . replace ( strURL , "{dbname}" , strDatabaseName ) ; } String strUsername = database . getProperty ( SQLParams . USERNAME_PARAM ) ; if ( ( strUsername == null ) || ( strUsername . length ( ) == 0 ) ) strUsername = database . getProperty ( SQLParams . DEFAULT_USERNAME_PARAM ) ; // Default String strPassword = database . getProperty ( SQLParams . PASSWORD_PARAM ) ; if ( ( strPassword == null ) || ( strPassword . length ( ) == 0 ) ) strPassword = database . getProperty ( SQLParams . DEFAULT_PASSWORD_PARAM ) ; // Default String strDriver = database . getProperty ( SQLParams . JDBC_DRIVER_PARAM ) ; try { dataSource . setDriverClass ( strDriver ) ; // loads the jdbc driver } catch ( PropertyVetoException e ) { e . printStackTrace ( ) ; } // dataSource . setDatabaseName ( strDatabaseName ) ; // if ( strServer ! = null ) // dataSource . setServerName ( strServer ) ; // else dataSource . setJdbcUrl ( strURL ) ; dataSource . setUser ( strUsername ) ; dataSource . setPassword ( strPassword ) ; // the settings below are optional - - c3p0 can work with defaults // ? dataSource . setMinPoolSize ( 5 ) ; // ? dataSource . setAcquireIncrement ( 5 ) ; // ? dataSource . setMaxPoolSize ( 20 ) ; // xMiniConnectionPoolManager poolMgr = new MiniConnectionPoolManager ( poolDataSource , MAX _ POOLED _ CONNECTIONS , POOL _ TIMEOUT ) ; }
public class NaiveBayesClassifier { /** * Naive Bayes Text Classification with Add - 1 Smoothing * @ param text Input text * @ return the best { @ link Category } */ public Category classify ( String text ) { } }
StringTokenizer itr = new StringTokenizer ( text ) ; Map < Category , Double > scorePerCategory = new HashMap < Category , Double > ( ) ; double bestScore = Double . NEGATIVE_INFINITY ; Category bestCategory = null ; while ( itr . hasMoreTokens ( ) ) { String token = NaiveBayesGenerate . normalizeWord ( itr . nextToken ( ) ) ; for ( Category category : Category . values ( ) ) { int count = MapUtils . getInteger ( wordCountPerCategory . get ( category ) , token , 0 ) + 1 ; double wordScore = Math . log ( count / ( double ) ( tokensPerCategory . get ( category ) + V ) ) ; double totalScore = MapUtils . getDouble ( scorePerCategory , category , 0. ) + wordScore ; if ( totalScore > bestScore ) { bestScore = totalScore ; bestCategory = category ; } scorePerCategory . put ( category , totalScore ) ; } } return bestCategory ;
public class CookieExpiresData { /** * @ see * com . ibm . ws . http . channel . internal . values . CookieData # set ( com . ibm . websphere * . http . HttpCookie , byte [ ] ) */ @ Override public boolean set ( HttpCookie cookie , byte [ ] attribValue ) { } }
if ( null == cookie || null == attribValue || 0 == attribValue . length ) { return false ; } // Start parsing the byte array here to set the expiry date // For example : 24 - Jun - 03 16:01:45 GMT is a valid attrib value // Using the HttpDateFormat class try { Date expiryDate = HttpDispatcher . getDateFormatter ( ) . parseTime ( attribValue ) ; long remainingTime = expiryDate . getTime ( ) - HttpDispatcher . getApproxTime ( ) ; if ( - 1 < remainingTime ) { cookie . setMaxAge ( ( int ) ( remainingTime / 1000L ) ) ; } else { // PK62826 - old date will translate to a 0 max - age ( immediate // expiration ) cookie . setMaxAge ( 0 ) ; } if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isDebugEnabled ( ) ) { Tr . debug ( tc , "Expires/max-age set to " + cookie . getMaxAge ( ) ) ; } return true ; } catch ( ParseException e ) { // No FFDC required if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isDebugEnabled ( ) ) { Tr . debug ( tc , "Error parsing expires date: " + GenericUtils . getEnglishString ( attribValue ) ) ; } } return false ;
public class ArrayList { /** * Inserts all of the elements in the specified collection into this * list , starting at the specified position . Shifts the element * currently at that position ( if any ) and any subsequent elements to * the right ( increases their indices ) . The new elements will appear * in the list in the order that they are returned by the * specified collection ' s iterator . * @ param index index at which to insert the first element from the * specified collection * @ param c collection containing elements to be added to this list * @ return < tt > true < / tt > if this list changed as a result of the call * @ throws IndexOutOfBoundsException { @ inheritDoc } * @ throws NullPointerException if the specified collection is null */ public boolean addAll ( int index , Collection < ? extends E > c ) { } }
if ( index > size || index < 0 ) throw new IndexOutOfBoundsException ( outOfBoundsMsg ( index ) ) ; Object [ ] a = c . toArray ( ) ; int numNew = a . length ; ensureCapacityInternal ( size + numNew ) ; // Increments modCount int numMoved = size - index ; if ( numMoved > 0 ) System . arraycopy ( elementData , index , elementData , index + numNew , numMoved ) ; System . arraycopy ( a , 0 , elementData , index , numNew ) ; size += numNew ; return numNew != 0 ;
public class JQMList { /** * Find the list item with the given tag . This method will search all the items and return * the first item found with the given tag . * @ return the list item with the given tag ( if found , or null otherwise ) . */ public JQMListItem findItemByTag ( Object tag ) { } }
if ( tag == null ) return null ; List < JQMListItem > lst = getItems ( ) ; for ( JQMListItem i : lst ) { if ( i == null ) continue ; if ( tag . equals ( i . getTag ( ) ) ) return i ; } return null ;
public class DeserializeJSON { /** * { " ROWCOUNT " : 2 , " COLUMNS " : [ " AAA " , " BBB " ] , " DATA " : { " aaa " : [ " a " , " c " ] , " bbb " : [ " b " , " d " ] } } */ private static Object toQuery ( Object obj ) throws PageException { } }
if ( obj instanceof Struct ) { Struct sct = ( Struct ) obj ; Key [ ] keys = CollectionUtil . keys ( sct ) ; // Columns Key [ ] columns = null ; if ( contains ( keys , KeyConstants . _COLUMNS ) ) columns = toColumns ( sct . get ( KeyConstants . _COLUMNS , null ) ) ; else if ( contains ( keys , KeyConstants . _COLUMNLIST ) ) columns = toColumnlist ( sct . get ( KeyConstants . _COLUMNLIST , null ) ) ; // rowcount int rowcount = - 1 ; if ( contains ( keys , ROWCOUNT ) ) rowcount = toRowCount ( sct . get ( ROWCOUNT , null ) ) ; else if ( contains ( keys , KeyConstants . _RECORDCOUNT ) ) rowcount = toRowCount ( sct . get ( KeyConstants . _RECORDCOUNT , null ) ) ; if ( columns != null ) { if ( keys . length == 2 && contains ( keys , KeyConstants . _DATA ) ) { Array [ ] data = toData ( sct . get ( KeyConstants . _DATA , null ) , columns ) ; if ( data != null ) { return new QueryImpl ( columns , data , "query" ) ; } } else if ( keys . length == 3 && rowcount != - 1 && contains ( keys , KeyConstants . _DATA ) ) { Array [ ] data = toData ( sct . get ( KeyConstants . _DATA , null ) , columns , rowcount ) ; if ( data != null ) { return new QueryImpl ( columns , data , "query" ) ; } } } return toQuery ( sct , keys ) ; } /* * else if ( obj instanceof Query ) { return toQuery ( ( Query ) obj ) ; } */ else if ( obj instanceof Collection ) { Collection coll = ( Collection ) obj ; return toQuery ( coll , CollectionUtil . keys ( coll ) ) ; } return obj ;
public class IpChecker { /** * Check whether a given IP Adress falls within a subnet or is equal to * @ param pExpected either a simple IP adress ( without " / " ) or a net specification * including a netmask ( e . g " / 24 " or " / 255.255.255.0 " ) * @ param pToCheck the ip address to check * @ return true if either the address to check is the same as the address expected * of falls within the subnet if a netmask is given */ public static boolean matches ( String pExpected , String pToCheck ) { } }
String [ ] parts = pExpected . split ( "/" , 2 ) ; if ( parts . length == 1 ) { // No Net part given , check for equality . . . // Check for valid ips convertToIntTuple ( pExpected ) ; convertToIntTuple ( pToCheck ) ; return pExpected . equals ( pToCheck ) ; } else if ( parts . length == 2 ) { int ipToCheck [ ] = convertToIntTuple ( pToCheck ) ; int ipPattern [ ] = convertToIntTuple ( parts [ 0 ] ) ; int netmask [ ] ; if ( parts [ 1 ] . length ( ) <= 2 ) { netmask = transformCidrToNetmask ( parts [ 1 ] ) ; } else { netmask = convertToIntTuple ( parts [ 1 ] ) ; } for ( int i = 0 ; i < ipToCheck . length ; i ++ ) { if ( ( ipPattern [ i ] & netmask [ i ] ) != ( ipToCheck [ i ] & netmask [ i ] ) ) { return false ; } } return true ; } else { throw new IllegalArgumentException ( "Invalid IP adress specification " + pExpected ) ; }
public class BaseRdbParser { /** * 1 . | 11xxxxx | xxxxx | remaining 6bit is 0 , then an 8 bit integer follows * 2 . | 11xxxxx | xxxxx | xxxxx | remaining 6bit is 1 , then an 16 bit integer follows * 3 . | 11xxxxx | xxxxx | xxxxx | xxxxx | xxxxx | remaining 6bit is 2 , then an 32 bit integer follows * 4 . | 11xxxxx | remaining 6bit is 3 , then lzf compressed string follows * @ param flags RDB _ LOAD _ ENC : encoded string . RDB _ LOAD _ PLAIN | RDB _ LOAD _ NONE : raw bytes * @ return ByteArray rdb byte array object * @ throws IOException when read timeout * @ see # rdbLoadIntegerObject * @ see # rdbLoadLzfStringObject */ public ByteArray rdbGenericLoadStringObject ( int flags ) throws IOException { } }
boolean plain = ( flags & RDB_LOAD_PLAIN ) != 0 ; boolean encode = ( flags & RDB_LOAD_ENC ) != 0 ; Len lenObj = rdbLoadLen ( ) ; long len = ( int ) lenObj . len ; boolean isencoded = lenObj . encoded ; if ( isencoded ) { switch ( ( int ) len ) { case RDB_ENC_INT8 : case RDB_ENC_INT16 : case RDB_ENC_INT32 : return rdbLoadIntegerObject ( ( int ) len , flags ) ; case RDB_ENC_LZF : return rdbLoadLzfStringObject ( flags ) ; default : throw new AssertionError ( "unknown RdbParser encoding type:" + len ) ; } } if ( plain ) { return in . readBytes ( len ) ; } else if ( encode ) { // createStringObject ( NULL , len ) return in . readBytes ( len ) ; } else { // createRawStringObject ( NULL , len ) ; return in . readBytes ( len ) ; }
public class MutableDateTime { /** * Set the milliseconds of the datetime . * All changes to the millisecond field occurs via this method . * @ param instant the milliseconds since 1970-01-01T00:00:00Z to set the * datetime to */ public void setMillis ( long instant ) { } }
switch ( iRoundingMode ) { case ROUND_NONE : break ; case ROUND_FLOOR : instant = iRoundingField . roundFloor ( instant ) ; break ; case ROUND_CEILING : instant = iRoundingField . roundCeiling ( instant ) ; break ; case ROUND_HALF_FLOOR : instant = iRoundingField . roundHalfFloor ( instant ) ; break ; case ROUND_HALF_CEILING : instant = iRoundingField . roundHalfCeiling ( instant ) ; break ; case ROUND_HALF_EVEN : instant = iRoundingField . roundHalfEven ( instant ) ; break ; } super . setMillis ( instant ) ;
public class Swift2ThriftGenerator { /** * and does a topological sort of thriftTypes in dependency order */ private boolean verifyTypes ( ) { } }
SuccessAndResult < ThriftType > output = topologicalSort ( thriftTypes , new Predicate < ThriftType > ( ) { @ Override public boolean apply ( @ Nullable ThriftType t ) { ThriftProtocolType proto = checkNotNull ( t ) . getProtocolType ( ) ; if ( proto == ThriftProtocolType . ENUM || proto == ThriftProtocolType . STRUCT ) { return verifyStruct ( t , true ) ; } else { Preconditions . checkState ( false , "Top-level non-enum and non-struct?" ) ; return false ; // silence compiler } } } ) ; if ( output . success ) { thriftTypes = output . result ; return true ; } else { for ( ThriftType t : output . result ) { // we know it ' s gonna fail , we just want the precise error message verifyStruct ( t , false ) ; } return false ; }
public class RecurlyClient { /** * Lookup an account ' s transactions history given query params * Returns the account ' s transaction history * @ param accountCode recurly account id * @ param state { @ link TransactionState } * @ param type { @ link TransactionType } * @ param params { @ link QueryParams } * @ return the transaction history associated with this account on success , null otherwise */ public Transactions getAccountTransactions ( final String accountCode , final TransactionState state , final TransactionType type , final QueryParams params ) { } }
if ( state != null ) params . put ( "state" , state . getType ( ) ) ; if ( type != null ) params . put ( "type" , type . getType ( ) ) ; return doGET ( Accounts . ACCOUNTS_RESOURCE + "/" + accountCode + Transactions . TRANSACTIONS_RESOURCE , Transactions . class , params ) ;
public class MetricAlarm { /** * The actions to execute when this alarm transitions to the < code > OK < / code > state from any other state . Each action * is specified as an Amazon Resource Name ( ARN ) . * @ param oKActions * The actions to execute when this alarm transitions to the < code > OK < / code > state from any other state . Each * action is specified as an Amazon Resource Name ( ARN ) . */ public void setOKActions ( java . util . Collection < String > oKActions ) { } }
if ( oKActions == null ) { this . oKActions = null ; return ; } this . oKActions = new com . amazonaws . internal . SdkInternalList < String > ( oKActions ) ;
public class Searcher { /** * Prepares an int for printing with leading zeros for the given size . * @ param i the int to prepare * @ param size max value for i * @ return printable string for i with leading zeros */ private static String getLeadingZeros ( int i , int size ) { } }
assert i <= size ; int w1 = ( int ) Math . floor ( Math . log10 ( size ) ) ; int w2 = ( int ) Math . floor ( Math . log10 ( i ) ) ; String s = "" ; for ( int j = w2 ; j < w1 ; j ++ ) { s += "0" ; } return s ;
public class JRubyProcessor { /** * Parses the given raw asciidoctor content , parses it and appends it as children to the given parent block . * < p > The following example will add two paragraphs with the role { @ code newcontent } to all top * level sections of a document : * < pre > * < verbatim > * Asciidoctor asciidoctor = . . . * asciidoctor . javaExtensionRegistry ( ) . treeprocessor ( new Treeprocessor ( ) { * DocumentRuby process ( DocumentRuby document ) { * for ( AbstractBlock block : document . getBlocks ( ) ) { * if ( block instanceof Section ) { * parseContent ( block , Arrays . asList ( new String [ ] { * " [ newcontent ] " , * " This is new content " * " [ newcontent ] " , * " This is also new content " } ) ) ; * < / verbatim > * < / pre > * @ param parent The block to which the parsed content should be added as children . * @ param lines Raw asciidoctor content */ @ Override public void parseContent ( StructuralNode parent , List < String > lines ) { } }
Ruby runtime = JRubyRuntimeContext . get ( parent ) ; Parser parser = new Parser ( runtime , parent , ReaderImpl . createReader ( runtime , lines ) ) ; StructuralNode nextBlock = parser . nextBlock ( ) ; while ( nextBlock != null ) { parent . append ( nextBlock ) ; nextBlock = parser . nextBlock ( ) ; }
public class ProxiedFileSystemUtils { /** * Create a { @ link FileSystem } that can perform any operations allowed the by the specified userNameToProxyAs . The * method first proxies as userNameToProxyAs , and then adds the specified { @ link Token } to the given * { @ link UserGroupInformation } object . It then uses the { @ link UserGroupInformation # doAs ( PrivilegedExceptionAction ) } * method to create a { @ link FileSystem } . * @ param userNameToProxyAs The name of the user the super user should proxy as * @ param userNameToken The { @ link Token } to add to the proxied user ' s { @ link UserGroupInformation } . * @ param fsURI The { @ link URI } for the { @ link FileSystem } that should be created * @ param conf The { @ link Configuration } for the { @ link FileSystem } that should be created * @ return a { @ link FileSystem } that can execute commands on behalf of the specified userNameToProxyAs */ static FileSystem createProxiedFileSystemUsingToken ( @ NonNull String userNameToProxyAs , @ NonNull Token < ? > userNameToken , URI fsURI , Configuration conf ) throws IOException , InterruptedException { } }
UserGroupInformation ugi = UserGroupInformation . createProxyUser ( userNameToProxyAs , UserGroupInformation . getLoginUser ( ) ) ; ugi . addToken ( userNameToken ) ; return ugi . doAs ( new ProxiedFileSystem ( fsURI , conf ) ) ;
public class VisualizationUtils { /** * Plots the mean MSD curve over all trajectories in t . * @ param t List of trajectories * @ param lagMin Minimum timelag ( e . g . 1,2,3 . . ) lagMin * timelag = elapsed time in seconds * @ param lagMax Maximum timelag ( e . g . 1,2,3 . . ) lagMax * timelag = elapsed time in seconds * @ param msdeval Evaluates the mean squared displacment */ public static Chart getMSDLineChart ( ArrayList < ? extends Trajectory > t , int lagMin , int lagMax , AbstractMeanSquaredDisplacmentEvaluator msdeval ) { } }
double [ ] xData = new double [ lagMax - lagMin + 1 ] ; double [ ] yData = new double [ lagMax - lagMin + 1 ] ; for ( int j = lagMin ; j < lagMax + 1 ; j ++ ) { double msd = 0 ; int N = 0 ; for ( int i = 0 ; i < t . size ( ) ; i ++ ) { if ( t . get ( i ) . size ( ) > lagMax ) { msdeval . setTrajectory ( t . get ( i ) ) ; msdeval . setTimelag ( j ) ; msd += msdeval . evaluate ( ) [ 0 ] ; N ++ ; } } msd = 1.0 / N * msd ; xData [ j - lagMin ] = j ; yData [ j - lagMin ] = msd ; } // Create Chart Chart chart = QuickChart . getChart ( "MSD Line" , "LAG" , "MSD" , "MSD" , xData , yData ) ; // Show it // new SwingWrapper ( chart ) . displayChart ( ) ; return chart ;
public class RuleMatchAsXmlSerializer { /** * Get the string to begin the XML . After this , use { @ link # ruleMatchesToXmlSnippet } and then { @ link # getXmlEnd ( ) } * or better , simply use { @ link # ruleMatchesToXml } . */ public String getXmlStart ( Language lang , Language motherTongue ) { } }
StringBuilder xml = new StringBuilder ( CAPACITY ) ; xml . append ( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" ) . append ( "<!-- THIS OUTPUT IS DEPRECATED, PLEASE SEE http://wiki.languagetool.org/http-server FOR A BETTER APPROACH -->\n" ) . append ( "<matches software=\"LanguageTool\" version=\"" + JLanguageTool . VERSION + "\"" + " buildDate=\"" ) . append ( JLanguageTool . BUILD_DATE ) . append ( "\">\n" ) ; if ( lang != null || motherTongue != null ) { String languageXml = "<language " ; String warning = "" ; if ( lang != null ) { languageXml += "shortname=\"" + lang . getShortCodeWithCountryAndVariant ( ) + "\" name=\"" + lang . getName ( ) + "\"" ; String longCode = lang . getShortCodeWithCountryAndVariant ( ) ; if ( "en" . equals ( longCode ) || "de" . equals ( longCode ) ) { xml . append ( "<!-- NOTE: The language code you selected ('" ) . append ( longCode ) . append ( "') doesn't support spell checking. Consider using a code with a variant like 'en-US'. -->\n" ) ; } } if ( motherTongue != null && ( lang == null || ! motherTongue . getShortCode ( ) . equals ( lang . getShortCodeWithCountryAndVariant ( ) ) ) ) { languageXml += " mothertongueshortname=\"" + motherTongue . getShortCode ( ) + "\" mothertonguename=\"" + motherTongue . getName ( ) + "\"" ; } languageXml += "/>\n" ; xml . append ( languageXml ) ; xml . append ( warning ) ; } return xml . toString ( ) ;
public class InMemoryLinkedDataStore { /** * ( non - Javadoc ) * @ see net . timewalker . ffmq4 . utils . store . LinkedStore # delete ( int ) */ @ Override public int delete ( int handle ) throws DataStoreException { } }
if ( SAFE_MODE ) checkHandle ( handle ) ; int previousHandle = previousEntry [ handle ] ; int nextHandle = nextEntry [ handle ] ; // Reconnect list if ( previousHandle != - 1 ) nextEntry [ previousHandle ] = nextHandle ; if ( nextHandle != - 1 ) previousEntry [ nextHandle ] = previousHandle ; // Clear data previousEntry [ handle ] = - 1 ; nextEntry [ handle ] = - 1 ; data [ handle ] = null ; locks . clear ( handle ) ; if ( firstEntry == handle ) firstEntry = nextHandle ; size -- ; return previousHandle ;
public class VarianceOfVolume { /** * Compute volumes * @ param knnq KNN query * @ param dim Data dimensionality * @ param ids IDs to process * @ param vols Volume storage */ private void computeVolumes ( KNNQuery < O > knnq , int dim , DBIDs ids , WritableDoubleDataStore vols ) { } }
FiniteProgress prog = LOG . isVerbose ( ) ? new FiniteProgress ( "Volume" , ids . size ( ) , LOG ) : null ; double scaleconst = MathUtil . SQRTPI * FastMath . pow ( GammaDistribution . gamma ( 1 + dim * .5 ) , - 1. / dim ) ; boolean warned = false ; double sum = 0. ; for ( DBIDIter iter = ids . iter ( ) ; iter . valid ( ) ; iter . advance ( ) ) { double dk = knnq . getKNNForDBID ( iter , k ) . getKNNDistance ( ) ; double vol = dk > 0 ? MathUtil . powi ( dk * scaleconst , dim ) : 0. ; if ( vol == Double . POSITIVE_INFINITY && ! warned ) { LOG . warning ( "Variance of Volumes has hit double precision limits, results are not reliable." ) ; warned = true ; } vols . putDouble ( iter , vol ) ; sum += vol ; LOG . incrementProcessed ( prog ) ; } double scaling = ids . size ( ) / sum ; for ( DBIDIter iter = ids . iter ( ) ; iter . valid ( ) ; iter . advance ( ) ) { vols . putDouble ( iter , vols . doubleValue ( iter ) * scaling ) ; } LOG . ensureCompleted ( prog ) ;
public class HttpResponseDecoder { /** * Asynchronously decodes a { @ link HttpResponse } . * @ param response the publisher that emits response to be decoded * @ param decodeData the necessary data required to decode the response emitted by { @ code response } * @ return a publisher that emits decoded HttpResponse upon subscription */ public Mono < HttpDecodedResponse > decode ( Mono < HttpResponse > response , HttpResponseDecodeData decodeData ) { } }
return response . map ( r -> new HttpDecodedResponse ( r , this . serializer , decodeData ) ) ;
public class InternalRequest { /** * Returns a content - type header value * @ return content - type header value in { @ link Optional } object */ public MediaType getContentType ( ) { } }
if ( isNull ( this . contentType ) ) { contentType = getHeader ( HeaderName . CONTENT_TYPE ) . map ( MediaType :: of ) . orElse ( WILDCARD ) ; } return contentType ;
public class Anima { /** * Create anima with url and db info * @ param url jdbc url * @ param user database username * @ param pass database password * @ return Anima */ public static Anima open ( String url , String user , String pass ) { } }
return open ( url , user , pass , QuirksDetector . forURL ( url ) ) ;
public class CommerceWishListUtil { /** * Returns a range of all the commerce wish lists where userId = & # 63 ; . * Useful when paginating results . Returns a maximum of < code > end - start < / code > instances . < code > start < / code > and < code > end < / code > are not primary keys , they are indexes in the result set . Thus , < code > 0 < / code > refers to the first result in the set . Setting both < code > start < / code > and < code > end < / code > to { @ link QueryUtil # ALL _ POS } will return the full result set . If < code > orderByComparator < / code > is specified , then the query will include the given ORDER BY logic . If < code > orderByComparator < / code > is absent and pagination is required ( < code > start < / code > and < code > end < / code > are not { @ link QueryUtil # ALL _ POS } ) , then the query will include the default ORDER BY logic from { @ link CommerceWishListModelImpl } . If both < code > orderByComparator < / code > and pagination are absent , for performance reasons , the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order . * @ param userId the user ID * @ param start the lower bound of the range of commerce wish lists * @ param end the upper bound of the range of commerce wish lists ( not inclusive ) * @ return the range of matching commerce wish lists */ public static List < CommerceWishList > findByUserId ( long userId , int start , int end ) { } }
return getPersistence ( ) . findByUserId ( userId , start , end ) ;
public class IssuesTemplate { /** * TODO , pagination */ @ Override public List < Issue > listOrganizationIssues ( String organization ) { } }
Map < String , Object > uriVariables = new HashMap < > ( ) ; uriVariables . put ( "organization" , organization ) ; return getRestOperations ( ) . exchange ( buildUri ( "/orgs/{organization}/issues?per_page=25" , uriVariables ) , HttpMethod . GET , null , issueListTypeRef ) . getBody ( ) ;
public class ClientProxyImpl { /** * Updates the current state if Client method is invoked , otherwise * does the remote invocation or returns a new proxy if subresource * method is invoked . Can throw an expected exception if ResponseExceptionMapper * is registered */ @ Trivial @ Override public Object invoke ( Object o , Method m , Object [ ] params ) throws Throwable { } }
Class < ? > declaringClass = m . getDeclaringClass ( ) ; if ( Client . class == declaringClass || InvocationHandlerAware . class == declaringClass || Object . class == declaringClass ) { return m . invoke ( this , params ) ; } resetResponse ( ) ; OperationResourceInfo ori = cri . getMethodDispatcher ( ) . getOperationResourceInfo ( m ) ; if ( ori == null ) { reportInvalidResourceMethod ( m , "INVALID_RESOURCE_METHOD" ) ; } MultivaluedMap < ParameterType , Parameter > types = getParametersInfo ( m , params , ori ) ; List < Parameter > beanParamsList = getParameters ( types , ParameterType . BEAN ) ; int bodyIndex = getBodyIndex ( types , ori ) ; List < Object > pathParams = getPathParamValues ( m , params , types , beanParamsList , ori , bodyIndex ) ; UriBuilder builder = getCurrentBuilder ( ) . clone ( ) ; if ( isRoot ) { addNonEmptyPath ( builder , ori . getClassResourceInfo ( ) . getURITemplate ( ) . getValue ( ) ) ; } addNonEmptyPath ( builder , ori . getURITemplate ( ) . getValue ( ) ) ; handleMatrixes ( m , params , types , beanParamsList , builder ) ; handleQueries ( m , params , types , beanParamsList , builder ) ; URI uri = builder . buildFromEncoded ( pathParams . toArray ( ) ) . normalize ( ) ; MultivaluedMap < String , String > headers = getHeaders ( ) ; MultivaluedMap < String , String > paramHeaders = new MetadataMap < String , String > ( ) ; handleHeaders ( m , params , paramHeaders , beanParamsList , types ) ; handleCookies ( m , params , paramHeaders , beanParamsList , types ) ; if ( ori . isSubResourceLocator ( ) ) { ClassResourceInfo subCri = cri . getSubResource ( m . getReturnType ( ) , m . getReturnType ( ) ) ; if ( subCri == null ) { reportInvalidResourceMethod ( m , "INVALID_SUBRESOURCE" ) ; } MultivaluedMap < String , String > subHeaders = paramHeaders ; if ( inheritHeaders ) { subHeaders . putAll ( headers ) ; } ClientState newState = getState ( ) . newState ( uri , subHeaders , getTemplateParametersMap ( ori . getURITemplate ( ) , pathParams ) ) ; ClientProxyImpl proxyImpl = new ClientProxyImpl ( newState , proxyLoader , subCri , false , inheritHeaders ) ; proxyImpl . setConfiguration ( getConfiguration ( ) ) ; return JAXRSClientFactory . createProxy ( m . getReturnType ( ) , proxyLoader , proxyImpl ) ; } headers . putAll ( paramHeaders ) ; getState ( ) . setTemplates ( getTemplateParametersMap ( ori . getURITemplate ( ) , pathParams ) ) ; Object body = null ; if ( bodyIndex != - 1 ) { body = params [ bodyIndex ] ; if ( body == null ) { bodyIndex = - 1 ; } } else if ( types . containsKey ( ParameterType . FORM ) ) { body = handleForm ( m , params , types , beanParamsList ) ; } else if ( types . containsKey ( ParameterType . REQUEST_BODY ) ) { body = handleMultipart ( types , ori , params ) ; } setRequestHeaders ( headers , ori , types . containsKey ( ParameterType . FORM ) , body == null ? null : body . getClass ( ) , m . getReturnType ( ) ) ; try { return doChainedInvocation ( uri , headers , ori , params , body , bodyIndex , null , null ) ; } finally { resetResponseStateImmediatelyIfNeeded ( ) ; }
public class HttpClientResponseBuilder { /** * Adds action which returns provided XML in UTF - 8 and status 200 . Additionally it sets " Content - type " header to " application / xml " . * @ param response JSON to return * @ return response builder */ public HttpClientResponseBuilder doReturnXML ( String response , Charset charset ) { } }
return doReturn ( response , charset ) . withHeader ( "Content-type" , APPLICATION_XML . toString ( ) ) ;
public class ArgumentParser { /** * Handler - D argument */ private Map < String , Object > handleArgDefine ( final String arg , final Deque < String > args ) { } }
/* * Interestingly enough , we get to here when a user uses - Dname = value . * However , in some cases , the OS goes ahead and parses this out to args * { " - Dname " , " value " } so instead of parsing on " = " , we just make the * " - D " characters go away and skip one argument forward . * I don ' t know how to predict when the JDK is going to help or not , so * we simply look for the equals sign . */ final Map . Entry < String , String > entry = parse ( arg . substring ( 2 ) , args ) ; if ( entry . getValue ( ) == null ) { throw new BuildException ( "Missing value for property " + entry . getKey ( ) ) ; } if ( RESERVED_PROPERTIES . containsKey ( entry . getKey ( ) ) ) { throw new BuildException ( "Property " + entry . getKey ( ) + " cannot be set with -D, use " + RESERVED_PROPERTIES . get ( entry . getKey ( ) ) + " instead" ) ; } return ImmutableMap . of ( entry . getKey ( ) , entry . getValue ( ) ) ;
public class MimeMessageHelper { /** * Fills the { @ link Message } instance with the attachments from the { @ link Email } . * @ param email The message in which the attachments are defined . * @ param multipartRoot The branch in the email structure in which we ' ll stuff the attachments . * @ throws MessagingException See { @ link MimeMultipart # addBodyPart ( BodyPart ) } and { @ link # getBodyPartFromDatasource ( AttachmentResource , String ) } */ static void setAttachments ( final Email email , final MimeMultipart multipartRoot ) throws MessagingException { } }
for ( final AttachmentResource resource : email . getAttachments ( ) ) { multipartRoot . addBodyPart ( getBodyPartFromDatasource ( resource , Part . ATTACHMENT ) ) ; }
public class WFieldSetRenderer { /** * Paints the given WFieldSet . * @ param component the WFieldSet to paint . * @ param renderContext the RenderContext to paint to . */ @ Override public void doRender ( final WComponent component , final WebXmlRenderContext renderContext ) { } }
WFieldSet fieldSet = ( WFieldSet ) component ; XmlStringBuilder xml = renderContext . getWriter ( ) ; xml . appendTagOpen ( "ui:fieldset" ) ; xml . appendAttribute ( "id" , component . getId ( ) ) ; xml . appendOptionalAttribute ( "class" , component . getHtmlClass ( ) ) ; xml . appendOptionalAttribute ( "track" , component . isTracking ( ) , "true" ) ; xml . appendOptionalAttribute ( "hidden" , fieldSet . isHidden ( ) , "true" ) ; switch ( fieldSet . getFrameType ( ) ) { case NO_BORDER : xml . appendOptionalAttribute ( "frame" , "noborder" ) ; break ; case NO_TEXT : xml . appendOptionalAttribute ( "frame" , "notext" ) ; break ; case NONE : xml . appendOptionalAttribute ( "frame" , "none" ) ; break ; case NORMAL : default : break ; } xml . appendOptionalAttribute ( "required" , fieldSet . isMandatory ( ) , "true" ) ; xml . appendClose ( ) ; // Render margin MarginRendererUtil . renderMargin ( fieldSet , renderContext ) ; // Label WDecoratedLabel label = fieldSet . getTitle ( ) ; label . paint ( renderContext ) ; // Children xml . appendTag ( "ui:content" ) ; int size = fieldSet . getChildCount ( ) ; for ( int i = 0 ; i < size ; i ++ ) { WComponent child = fieldSet . getChildAt ( i ) ; // Skip label , as it has already been painted if ( child != label ) { child . paint ( renderContext ) ; } } xml . appendEndTag ( "ui:content" ) ; DiagnosticRenderUtil . renderDiagnostics ( fieldSet , renderContext ) ; xml . appendEndTag ( "ui:fieldset" ) ;
public class NodeInterval { /** * Return the first node satisfying the date and match callback . * @ param callback custom logic to decide if a given node is a match * @ return the found node or null if there is nothing . */ public NodeInterval findNode ( final SearchCallback callback ) { } }
Preconditions . checkNotNull ( callback ) ; if ( callback . isMatch ( this ) ) { return this ; } NodeInterval curChild = leftChild ; while ( curChild != null ) { final NodeInterval result = curChild . findNode ( callback ) ; if ( result != null ) { return result ; } curChild = curChild . getRightSibling ( ) ; } return null ;
public class ReflectionUtils { /** * Returns a { @ link LinkedHashSet } of { @ link Class } objects containing all * classes of a specified package ( including subpackages ) which extend the * given class . * Example : * < pre > * String pack = & quot ; de . uni . freiburg . iig . telematik . sepia & quot ; ; * Class & lt ; ? & gt ; superclass = AbstractPlace . class ; * LinkedHashSet & lt ; Class & lt ; ? & gt ; & gt ; classes = ReflectionUtils . getSubclasses ( superclass , pack ) ; * for ( Class & lt ; ? & gt ; c : classes ) { * System . out . println ( c ) ; * / / class de . uni . freiburg . iig . telematik . sepia . petrinet . cpn . abstr . AbstractCPNPlace * / / class de . uni . freiburg . iig . telematik . sepia . petrinet . cpn . CPNPlace * / / class de . uni . freiburg . iig . telematik . sepia . petrinet . ifnet . abstr . AbstractIFNetPlace * / / class de . uni . freiburg . iig . telematik . sepia . petrinet . ifnet . IFNetPlace * / / class de . uni . freiburg . iig . telematik . sepia . petrinet . pt . abstr . AbstractPTPlace * / / class de . uni . freiburg . iig . telematik . sepia . petrinet . pt . PTPlace * < / pre > * @ param clazz Class which should be extended . * @ param packageName Package to search for subclasses . * @ param recursive < code > true < / code > if subpackages should be considered , * too . * @ return { @ link LinkedHashSet } of { @ link Class } objects extending the * given class in the specified package . * @ throws ReflectionException */ public static LinkedHashSet < Class < ? > > getSubclassesInPackage ( Class < ? > clazz , String packageName , boolean recursive ) throws ReflectionException { } }
Validate . notNull ( clazz ) ; if ( clazz . isInterface ( ) || clazz . isEnum ( ) ) { throw new ParameterException ( "Parameter is not a class" ) ; } LinkedHashSet < Class < ? > > classesInPackage = getClassesInPackage ( packageName , recursive ) ; try { LinkedHashSet < Class < ? > > subClassesInPackage = new LinkedHashSet < > ( ) ; for ( Class < ? > classInPackage : classesInPackage ) { if ( getSuperclasses ( classInPackage ) . contains ( clazz ) && clazz != classInPackage ) { subClassesInPackage . add ( classInPackage ) ; } } return subClassesInPackage ; } catch ( Exception e ) { throw new ReflectionException ( e ) ; }
public class DefaultExecutor { /** * Factory method to create a thread waiting for the result of an * asynchronous execution . * @ param runnable the runnable passed to the thread * @ param name the name of the thread * @ return the thread */ @ Override protected Thread createThread ( final Runnable runnable , final String name ) { } }
return new Thread ( runnable , Thread . currentThread ( ) . getName ( ) + "-exec" ) ;
public class QueryWithResultMessage { /** * / * XXX : Issues with async / future that are chained */ @ Override public boolean isFuture ( ) { } }
ResultChain < T > result = _result ; return result . isFuture ( ) && method ( ) . isDirect ( ) ;
public class DescribeSpotPriceHistoryRequest { /** * Filters the results by the specified basic product descriptions . * @ return Filters the results by the specified basic product descriptions . */ public java . util . List < String > getProductDescriptions ( ) { } }
if ( productDescriptions == null ) { productDescriptions = new com . amazonaws . internal . SdkInternalList < String > ( ) ; } return productDescriptions ;
public class SymmetricQrAlgorithm_DDRM { /** * First looks for zeros and then performs the implicit single step in the QR Algorithm . */ public void performStep ( ) { } }
// check for zeros for ( int i = helper . x2 - 1 ; i >= helper . x1 ; i -- ) { if ( helper . isZero ( i ) ) { helper . splits [ helper . numSplits ++ ] = i ; helper . x1 = i + 1 ; return ; } } double lambda ; if ( followingScript ) { if ( helper . steps > 10 ) { followingScript = false ; return ; } else { // Using the true eigenvalues will in general lead to the fastest convergence // typically takes 1 or 2 steps lambda = eigenvalues [ helper . x2 ] ; } } else { // the current eigenvalue isn ' t working so try something else lambda = helper . computeShift ( ) ; } // similar transforms helper . performImplicitSingleStep ( lambda , false ) ;
public class AndroidUtils { /** * Execute an { @ link AsyncTask } on a thread pool . * @ param task Task to add . * @ param args Optional arguments to pass to { @ link AsyncTask # execute ( Object [ ] ) } . * @ param < T > Task argument type . */ @ SuppressWarnings ( "unchecked" ) @ TargetApi ( VERSION_CODES . HONEYCOMB ) public static < T > void execute ( AsyncTask < T , ? , ? > task , T ... args ) { } }
if ( Build . VERSION . SDK_INT < VERSION_CODES . HONEYCOMB ) { task . execute ( args ) ; } else { task . executeOnExecutor ( AsyncTask . THREAD_POOL_EXECUTOR , args ) ; }
public class OpenLDAPModifyPasswordRequest { /** * Get the BER encoded value for this operation . * @ return a bytearray containing the BER sequence . */ public byte [ ] getEncodedValue ( ) { } }
final String characterEncoding = this . chaiConfiguration . getSetting ( ChaiSetting . LDAP_CHARACTER_ENCODING ) ; final byte [ ] password = modifyPassword . getBytes ( Charset . forName ( characterEncoding ) ) ; final byte [ ] dn = modifyDn . getBytes ( Charset . forName ( characterEncoding ) ) ; // Sequence tag ( 1 ) + sequence length ( 1 ) + dn tag ( 1 ) + // dn length ( 1 ) + dn ( variable ) + password tag ( 1 ) + // password length ( 1 ) + password ( variable ) final int encodedLength = 6 + dn . length + password . length ; final byte [ ] encoded = new byte [ encodedLength ] ; int valueI = 0 ; // sequence start encoded [ valueI ++ ] = ( byte ) 0x30 ; // length of body encoded [ valueI ++ ] = ( byte ) ( 4 + dn . length + password . length ) ; encoded [ valueI ++ ] = LDAP_TAG_EXOP_X_MODIFY_PASSWD_ID ; encoded [ valueI ++ ] = ( byte ) dn . length ; System . arraycopy ( dn , 0 , encoded , valueI , dn . length ) ; valueI += dn . length ; encoded [ valueI ++ ] = LDAP_TAG_EXOP_X_MODIFY_PASSWD_NEW ; encoded [ valueI ++ ] = ( byte ) password . length ; System . arraycopy ( password , 0 , encoded , valueI , password . length ) ; valueI += password . length ; return encoded ;
public class BasicEventStream { /** * Returns the next Event object held in this EventStream . Each call to nextEvent advances the EventStream . * @ return the Event object which is next in this EventStream */ public Event nextEvent ( ) { } }
while ( _next == null && _ds . hasNext ( ) ) _next = createEvent ( ( String ) _ds . nextToken ( ) ) ; Event current = _next ; if ( _ds . hasNext ( ) ) { _next = createEvent ( ( String ) _ds . nextToken ( ) ) ; } else { _next = null ; } return current ;
public class JobListPreparationAndReleaseTaskStatusNextOptions { /** * Set the time the request was issued . Client libraries typically set this to the current system clock time ; set it explicitly if you are calling the REST API directly . * @ param ocpDate the ocpDate value to set * @ return the JobListPreparationAndReleaseTaskStatusNextOptions object itself . */ public JobListPreparationAndReleaseTaskStatusNextOptions withOcpDate ( DateTime ocpDate ) { } }
if ( ocpDate == null ) { this . ocpDate = null ; } else { this . ocpDate = new DateTimeRfc1123 ( ocpDate ) ; } return this ;
public class Matchers { /** * Match a method declaration with a specific enclosing class and method name . * @ param className The fully - qualified name of the enclosing class , e . g . * " com . google . common . base . Preconditions " * @ param methodName The name of the method to match , e . g . , " checkNotNull " */ public static Matcher < MethodTree > methodWithClassAndName ( final String className , final String methodName ) { } }
return new Matcher < MethodTree > ( ) { @ Override public boolean matches ( MethodTree methodTree , VisitorState state ) { return ASTHelpers . getSymbol ( methodTree ) . getEnclosingElement ( ) . getQualifiedName ( ) . contentEquals ( className ) && methodTree . getName ( ) . contentEquals ( methodName ) ; } } ;
public class ReflectionUtilImpl { /** * This method gets the singleton instance of this { @ link ReflectionUtil } . < br > * < b > ATTENTION : < / b > < br > * Please prefer dependency - injection instead of using this method . * @ return the singleton instance . */ public static ReflectionUtil getInstance ( ) { } }
if ( instance == null ) { ReflectionUtilImpl impl = null ; synchronized ( ReflectionUtilImpl . class ) { if ( instance == null ) { impl = new ReflectionUtilImpl ( ) ; instance = impl ; } } if ( impl != null ) { // static access is generally discouraged , cyclic dependency forces this ugly initialization to // prevent deadlock . impl . initialize ( ) ; } } return instance ;
public class SameAsServiceImpl { /** * { @ inheritDoc } */ public EquivalenceList getDuplicates ( String keyword ) throws SameAsServiceException { } }
return invokeURL ( format ( SERVICE_KEYWORD , keyword ) , EquivalenceList . class ) ;
public class GrailsDomainBinder { /** * Override the default naming strategy for the default datasource given a Class or a full class name . * @ param strategy the class or name * @ throws ClassNotFoundException When the class was not found for specified strategy * @ throws InstantiationException When an error occurred instantiating the strategy * @ throws IllegalAccessException When an error occurred instantiating the strategy */ public static void configureNamingStrategy ( final Object strategy ) throws ClassNotFoundException , InstantiationException , IllegalAccessException { } }
configureNamingStrategy ( ConnectionSource . DEFAULT , strategy ) ;
public class BytecodeUtils { /** * Returns an expression that does a numeric conversion cast from the given expression to the * given type . * @ throws IllegalArgumentException if either the expression or the target type is not a numeric * primitive */ public static Expression numericConversion ( final Expression expr , final Type to ) { } }
if ( to . equals ( expr . resultType ( ) ) ) { return expr ; } if ( ! isNumericPrimitive ( to ) || ! isNumericPrimitive ( expr . resultType ( ) ) ) { throw new IllegalArgumentException ( "Cannot convert from " + expr . resultType ( ) + " to " + to ) ; } return new Expression ( to , expr . features ( ) ) { @ Override protected void doGen ( CodeBuilder adapter ) { expr . gen ( adapter ) ; adapter . cast ( expr . resultType ( ) , to ) ; } } ;
public class HttpServletResponseWrapper { /** * The default behaviour of this method is to call * { @ link HttpServletResponse # setTrailerFields } on the wrapped response * object . * @ param supplier of trailer headers * @ since Servlet 4.0 */ @ Override public void setTrailerFields ( Supplier < Map < String , String > > supplier ) { } }
_getHttpServletResponse ( ) . setTrailerFields ( supplier ) ;
public class ByteCodeParser { /** * Parses a method ref constant pool entry . */ private MethodRefConstant parseMethodRefConstant ( int index ) throws IOException { } }
int classIndex = readShort ( ) ; int nameAndTypeIndex = readShort ( ) ; return new MethodRefConstant ( _class . getConstantPool ( ) , index , classIndex , nameAndTypeIndex ) ;
public class AnimatorSet { /** * { @ inheritDoc } * < p > Starting this < code > AnimatorSet < / code > will , in turn , start the animations for which * it is responsible . The details of when exactly those animations are started depends on * the dependency relationships that have been set up between the animations . */ @ Override public void start ( ) { } }
mTerminated = false ; mStarted = true ; // First , sort the nodes ( if necessary ) . This will ensure that sortedNodes // contains the animation nodes in the correct order . sortNodes ( ) ; int numSortedNodes = mSortedNodes . size ( ) ; for ( int i = 0 ; i < numSortedNodes ; ++ i ) { Node node = mSortedNodes . get ( i ) ; // First , clear out the old listeners ArrayList < AnimatorListener > oldListeners = node . animation . getListeners ( ) ; if ( oldListeners != null && oldListeners . size ( ) > 0 ) { final ArrayList < AnimatorListener > clonedListeners = new ArrayList < AnimatorListener > ( oldListeners ) ; for ( AnimatorListener listener : clonedListeners ) { if ( listener instanceof DependencyListener || listener instanceof AnimatorSetListener ) { node . animation . removeListener ( listener ) ; } } } } // nodesToStart holds the list of nodes to be started immediately . We don ' t want to // start the animations in the loop directly because we first need to set up // dependencies on all of the nodes . For example , we don ' t want to start an animation // when some other animation also wants to start when the first animation begins . final ArrayList < Node > nodesToStart = new ArrayList < Node > ( ) ; for ( int i = 0 ; i < numSortedNodes ; ++ i ) { Node node = mSortedNodes . get ( i ) ; if ( mSetListener == null ) { mSetListener = new AnimatorSetListener ( this ) ; } if ( node . dependencies == null || node . dependencies . size ( ) == 0 ) { nodesToStart . add ( node ) ; } else { int numDependencies = node . dependencies . size ( ) ; for ( int j = 0 ; j < numDependencies ; ++ j ) { Dependency dependency = node . dependencies . get ( j ) ; dependency . node . animation . addListener ( new DependencyListener ( this , node , dependency . rule ) ) ; } node . tmpDependencies = ( ArrayList < Dependency > ) node . dependencies . clone ( ) ; } node . animation . addListener ( mSetListener ) ; } // Now that all dependencies are set up , start the animations that should be started . if ( mStartDelay <= 0 ) { for ( Node node : nodesToStart ) { node . animation . start ( ) ; mPlayingSet . add ( node . animation ) ; } } else { mDelayAnim = ValueAnimator . ofFloat ( 0f , 1f ) ; mDelayAnim . setDuration ( mStartDelay ) ; mDelayAnim . addListener ( new AnimatorListenerAdapter ( ) { boolean canceled = false ; public void onAnimationCancel ( Animator anim ) { canceled = true ; } public void onAnimationEnd ( Animator anim ) { if ( ! canceled ) { int numNodes = nodesToStart . size ( ) ; for ( int i = 0 ; i < numNodes ; ++ i ) { Node node = nodesToStart . get ( i ) ; node . animation . start ( ) ; mPlayingSet . add ( node . animation ) ; } } } } ) ; mDelayAnim . start ( ) ; } if ( mListeners != null ) { ArrayList < AnimatorListener > tmpListeners = ( ArrayList < AnimatorListener > ) mListeners . clone ( ) ; int numListeners = tmpListeners . size ( ) ; for ( int i = 0 ; i < numListeners ; ++ i ) { tmpListeners . get ( i ) . onAnimationStart ( this ) ; } } if ( mNodes . size ( ) == 0 && mStartDelay == 0 ) { // Handle unusual case where empty AnimatorSet is started - should send out // end event immediately since the event will not be sent out at all otherwise mStarted = false ; if ( mListeners != null ) { ArrayList < AnimatorListener > tmpListeners = ( ArrayList < AnimatorListener > ) mListeners . clone ( ) ; int numListeners = tmpListeners . size ( ) ; for ( int i = 0 ; i < numListeners ; ++ i ) { tmpListeners . get ( i ) . onAnimationEnd ( this ) ; } } }
public class CleverTapAPI { /** * InApp */ @ Override public void notificationReady ( final CTInAppNotification inAppNotification ) { } }
if ( Looper . myLooper ( ) != Looper . getMainLooper ( ) ) { getHandlerUsingMainLooper ( ) . post ( new Runnable ( ) { @ Override public void run ( ) { notificationReady ( inAppNotification ) ; } } ) ; return ; } if ( inAppNotification . getError ( ) != null ) { getConfigLogger ( ) . debug ( getAccountId ( ) , "Unable to process inapp notification " + inAppNotification . getError ( ) ) ; return ; } getConfigLogger ( ) . debug ( getAccountId ( ) , "Notification ready: " + inAppNotification . getJsonDescription ( ) ) ; displayNotification ( inAppNotification ) ;
public class UpdateScriptRequestMarshaller { /** * Marshall the given parameter object . */ public void marshall ( UpdateScriptRequest updateScriptRequest , ProtocolMarshaller protocolMarshaller ) { } }
if ( updateScriptRequest == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( updateScriptRequest . getScriptId ( ) , SCRIPTID_BINDING ) ; protocolMarshaller . marshall ( updateScriptRequest . getName ( ) , NAME_BINDING ) ; protocolMarshaller . marshall ( updateScriptRequest . getVersion ( ) , VERSION_BINDING ) ; protocolMarshaller . marshall ( updateScriptRequest . getStorageLocation ( ) , STORAGELOCATION_BINDING ) ; protocolMarshaller . marshall ( updateScriptRequest . getZipFile ( ) , ZIPFILE_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; }
public class SessionBeanTypeImpl { /** * If not already created , a new < code > concurrent - method < / code > element will be created and returned . * Otherwise , the first existing < code > concurrent - method < / code > element will be returned . * @ return the instance defined for the element < code > concurrent - method < / code > */ public ConcurrentMethodType < SessionBeanType < T > > getOrCreateConcurrentMethod ( ) { } }
List < Node > nodeList = childNode . get ( "concurrent-method" ) ; if ( nodeList != null && nodeList . size ( ) > 0 ) { return new ConcurrentMethodTypeImpl < SessionBeanType < T > > ( this , "concurrent-method" , childNode , nodeList . get ( 0 ) ) ; } return createConcurrentMethod ( ) ;
public class ImageIconCache { /** * Retourne une imageIcon à partir du cache , redimensionnée . * @ param fileName String * @ param targetWidth int * @ param targetHeight int * @ return ImageIcon */ public static ImageIcon getScaledImageIcon ( String fileName , int targetWidth , int targetHeight ) { } }
return MSwingUtilities . getScaledInstance ( getImageIcon ( fileName ) , targetWidth , targetHeight ) ;
public class LazyTreeReader { /** * Adjust all streams to the beginning of the row index entry specified , backwards means that * a previous value is being read and forces the index entry to be restarted , otherwise , has * no effect if we ' re already in the current index entry * @ param rowIndexEntry * @ param backwards * @ throws IOException */ protected void seek ( int rowIndexEntry , boolean backwards ) throws IOException { } }
if ( backwards || rowIndexEntry != computeRowIndexEntry ( previousRow ) ) { // initialize the previousPositionProvider previousRowIndexEntry = rowIndexEntry ; // if the present stream exists and we are seeking backwards or to a new row Index entry // the present stream needs to seek if ( present != null && ( backwards || rowIndexEntry != computeRowIndexEntry ( previousPresentRow ) ) ) { present . seek ( rowIndexEntry ) ; // Update previousPresentRow because the state is now as if that were the case previousPresentRow = rowBaseInStripe + rowIndexEntry * rowIndexStride - 1 ; } seek ( rowIndexEntry ) ; // Update previousRow because the state is now as if that were the case previousRow = rowBaseInStripe + rowIndexEntry * rowIndexStride - 1 ; }
public class TimeAndDimsPointer { /** * Compares time column value and dimension column values , but not metric column values . */ @ Override public int compareTo ( @ Nonnull TimeAndDimsPointer rhs ) { } }
long timestamp = getTimestamp ( ) ; long rhsTimestamp = rhs . getTimestamp ( ) ; int timestampDiff = Long . compare ( timestamp , rhsTimestamp ) ; if ( timestampDiff != 0 ) { return timestampDiff ; } for ( int dimIndex = 0 ; dimIndex < dimensionSelectors . length ; dimIndex ++ ) { int dimDiff = dimensionSelectorComparators [ dimIndex ] . compare ( dimensionSelectors [ dimIndex ] , rhs . dimensionSelectors [ dimIndex ] ) ; if ( dimDiff != 0 ) { return dimDiff ; } } return 0 ;
public class LongRangeValidator { /** * VALIDATE */ public void validate ( FacesContext facesContext , UIComponent uiComponent , Object value ) throws ValidatorException { } }
if ( facesContext == null ) { throw new NullPointerException ( "facesContext" ) ; } if ( uiComponent == null ) { throw new NullPointerException ( "uiComponent" ) ; } if ( value == null ) { return ; } double dvalue = parseLongValue ( facesContext , uiComponent , value ) ; if ( _minimum != null && _maximum != null ) { if ( dvalue < _minimum . longValue ( ) || dvalue > _maximum . longValue ( ) ) { Object [ ] args = { _minimum , _maximum , _MessageUtils . getLabel ( facesContext , uiComponent ) } ; throw new ValidatorException ( _MessageUtils . getErrorMessage ( facesContext , NOT_IN_RANGE_MESSAGE_ID , args ) ) ; } } else if ( _minimum != null ) { if ( dvalue < _minimum . longValue ( ) ) { Object [ ] args = { _minimum , _MessageUtils . getLabel ( facesContext , uiComponent ) } ; throw new ValidatorException ( _MessageUtils . getErrorMessage ( facesContext , MINIMUM_MESSAGE_ID , args ) ) ; } } else if ( _maximum != null ) { if ( dvalue > _maximum . longValue ( ) ) { Object [ ] args = { _maximum , _MessageUtils . getLabel ( facesContext , uiComponent ) } ; throw new ValidatorException ( _MessageUtils . getErrorMessage ( facesContext , MAXIMUM_MESSAGE_ID , args ) ) ; } }
public class CommerceTierPriceEntryPersistenceImpl { /** * Removes the commerce tier price entry where companyId = & # 63 ; and externalReferenceCode = & # 63 ; from the database . * @ param companyId the company ID * @ param externalReferenceCode the external reference code * @ return the commerce tier price entry that was removed */ @ Override public CommerceTierPriceEntry removeByC_ERC ( long companyId , String externalReferenceCode ) throws NoSuchTierPriceEntryException { } }
CommerceTierPriceEntry commerceTierPriceEntry = findByC_ERC ( companyId , externalReferenceCode ) ; return remove ( commerceTierPriceEntry ) ;
public class AbstractCollection { /** * Read all fields related to this collection object . * @ throws CacheReloadException on error */ private void readFromDB4Fields ( ) throws CacheReloadException { } }
try { final QueryBuilder queryBldr = new QueryBuilder ( CIAdminUserInterface . Field ) ; queryBldr . addWhereAttrEqValue ( CIAdminUserInterface . Field . Collection , getId ( ) ) ; final MultiPrintQuery multi = queryBldr . getPrint ( ) ; multi . addAttribute ( CIAdminUserInterface . Field . Type , CIAdminUserInterface . Field . Name ) ; multi . executeWithoutAccessCheck ( ) ; while ( multi . next ( ) ) { final long id = multi . getCurrentInstance ( ) . getId ( ) ; final String name = multi . < String > getAttribute ( CIAdminUserInterface . Field . Name ) ; final Type type = multi . < Type > getAttribute ( CIAdminUserInterface . Field . Type ) ; final Field field ; if ( type . equals ( CIAdminUserInterface . FieldCommand . getType ( ) ) ) { field = new FieldCommand ( id , null , name ) ; } else if ( type . equals ( CIAdminUserInterface . FieldHeading . getType ( ) ) ) { field = new FieldHeading ( id , null , name ) ; } else if ( type . equals ( CIAdminUserInterface . FieldTable . getType ( ) ) ) { field = new FieldTable ( id , null , name ) ; } else if ( type . equals ( CIAdminUserInterface . FieldGroup . getType ( ) ) ) { field = new FieldGroup ( id , null , name ) ; } else if ( type . equals ( CIAdminUserInterface . FieldSet . getType ( ) ) ) { field = new FieldSet ( id , null , name ) ; } else if ( type . equals ( CIAdminUserInterface . FieldClassification . getType ( ) ) ) { field = new FieldClassification ( id , null , name ) ; } else if ( type . equals ( CIAdminUserInterface . FieldPicker . getType ( ) ) ) { field = new FieldPicker ( id , null , name ) ; } else { field = new Field ( id , null , name ) ; } field . readFromDB ( ) ; add ( field ) ; } } catch ( final EFapsException e ) { throw new CacheReloadException ( "could not read fields for '" + getName ( ) + "'" , e ) ; }
public class Radar { /** * Updates the position of the given poi by it ' s name ( BLIP _ NAME ) on * the radar screen . This could be useful to visualize moving points . * Keep in mind that only the poi ' s are visible as blips that are * in the range of the radar . * @ param BLIP _ NAME * @ param LOCATION */ public void updatePoi ( final String BLIP_NAME , final Point2D LOCATION ) { } }
if ( pois . keySet ( ) . contains ( BLIP_NAME ) ) { pois . get ( BLIP_NAME ) . setLocation ( LOCATION ) ; checkForBlips ( ) ; }
public class User { /** * Validates a token sent via email for password reset . * @ param token a token * @ return true if valid */ public final boolean isValidPasswordResetToken ( String token ) { } }
Sysprop s = CoreUtils . getInstance ( ) . getDao ( ) . read ( getAppid ( ) , identifier ) ; return isValidToken ( s , Config . _RESET_TOKEN , token ) ;
public class IamCredentialsClient { /** * Signs a JWT using a service account ' s system - managed private key . * < p > Sample code : * < pre > < code > * try ( IamCredentialsClient iamCredentialsClient = IamCredentialsClient . create ( ) ) { * ServiceAccountName name = ServiceAccountName . of ( " [ PROJECT ] " , " [ SERVICE _ ACCOUNT ] " ) ; * List & lt ; String & gt ; delegates = new ArrayList & lt ; & gt ; ( ) ; * String payload = " " ; * SignJwtResponse response = iamCredentialsClient . signJwt ( name , delegates , payload ) ; * < / code > < / pre > * @ param name The resource name of the service account for which the credentials are requested , * in the following format : ` projects / - / serviceAccounts / { ACCOUNT _ EMAIL _ OR _ UNIQUEID } ` . * @ param delegates The sequence of service accounts in a delegation chain . Each service account * must be granted the ` roles / iam . serviceAccountTokenCreator ` role on its next service account * in the chain . The last service account in the chain must be granted the * ` roles / iam . serviceAccountTokenCreator ` role on the service account that is specified in the * ` name ` field of the request . * < p > The delegates must have the following format : * ` projects / - / serviceAccounts / { ACCOUNT _ EMAIL _ OR _ UNIQUEID } ` * @ param payload The JWT payload to sign : a JSON object that contains a JWT Claims Set . * @ throws com . google . api . gax . rpc . ApiException if the remote call fails */ public final SignJwtResponse signJwt ( ServiceAccountName name , List < String > delegates , String payload ) { } }
SignJwtRequest request = SignJwtRequest . newBuilder ( ) . setName ( name == null ? null : name . toString ( ) ) . addAllDelegates ( delegates ) . setPayload ( payload ) . build ( ) ; return signJwt ( request ) ;
public class EntityPropertyDescFactory { /** * 識別子を生成する方法を検証します 。 * @ param generationType 識別子を生成する方法 */ protected void validateGenerationType ( GenerationType generationType ) { } }
if ( generationType == null ) { return ; } if ( generationType == GenerationType . IDENTITY ) { if ( ! dialect . supportsIdentity ( ) ) { throw new GenException ( Message . DOMAGEN0003 , dialect . getName ( ) ) ; } } else if ( generationType == GenerationType . SEQUENCE ) { if ( ! dialect . supportsSequence ( ) ) { throw new GenException ( Message . DOMAGEN0004 , dialect . getName ( ) ) ; } }
public class TableSawQuandlSession { /** * Create a Quandl session with detailed SessionOptions . No attempt will be made to read the java property < em > quandl . auth . token < / em > even * if available . Note creating this object does not make any actual API requests , the token is used in subsequent requests . * @ param sessionOptions a user created SessionOptions instance , not null * @ return an instance of the Quandl session , not null */ public static TableSawQuandlSession create ( final SessionOptions sessionOptions ) { } }
ArgumentChecker . notNull ( sessionOptions , "sessionOptions" ) ; return new TableSawQuandlSession ( sessionOptions , new JSONTableSawRESTDataProvider ( ) , new ClassicMetaDataPackager ( ) ) ;
public class ServiceUtil { /** * Build an object out of a given class and a map for field names to values . * @ param clazz The class to be created . * @ param params A map of the parameters . * @ return An instantiated object . * @ throws Exception when constructor fails . */ public static Object constructByNamedParams ( Class clazz , Map params ) throws Exception { } }
Object obj = clazz . getConstructor ( ) . newInstance ( ) ; Method [ ] allMethods = clazz . getMethods ( ) ; for ( Method method : allMethods ) { if ( method . getName ( ) . startsWith ( "set" ) ) { Object [ ] o = new Object [ 1 ] ; String propertyName = Introspector . decapitalize ( method . getName ( ) . substring ( 3 ) ) ; if ( params . containsKey ( propertyName ) ) { o [ 0 ] = params . get ( propertyName ) ; method . invoke ( obj , o ) ; } } } return obj ;
public class SchemaHelper { /** * Maps simple types supported by RAML into primitives and other simple Java * types * @ param param * The Type to map * @ param format * Number format specified * @ param rawType * RAML type * @ return The Java Class which maps to this Simple RAML ParamType or string * if one is not found */ public static Class < ? > mapSimpleType ( RamlParamType param , String format , String rawType ) { } }
switch ( param ) { case BOOLEAN : return Boolean . class ; case DATE : return mapDateFormat ( rawType ) ; case INTEGER : { Class < ? > fromFormat = mapNumberFromFormat ( format ) ; if ( fromFormat == Double . class ) { throw new IllegalStateException ( ) ; } if ( fromFormat == null ) { return Long . class ; // retained for backward compatibility } else { return fromFormat ; } } case NUMBER : { Class < ? > fromFormat = mapNumberFromFormat ( format ) ; if ( fromFormat == null ) { return BigDecimal . class ; // retained for backward // compatibility } else { return fromFormat ; } } case FILE : return MultipartFile . class ; default : return String . class ; }
public class Replace_First { /** * replace _ first ( input , string , replacement = ' ' ) * Replace the first occurrences of a string with another */ @ Override public Object apply ( Object value , Object ... params ) { } }
String original = super . asString ( value ) ; Object needle = super . get ( 0 , params ) ; String replacement = "" ; if ( needle == null ) { throw new RuntimeException ( "invalid pattern: " + needle ) ; } if ( params . length >= 2 ) { Object obj = super . get ( 1 , params ) ; if ( obj == null ) { throw new RuntimeException ( "invalid replacement: " + needle ) ; } replacement = super . asString ( super . get ( 1 , params ) ) ; } return original . replaceFirst ( Pattern . quote ( String . valueOf ( needle ) ) , Matcher . quoteReplacement ( replacement ) ) ;
public class Resolve { /** * Try to instantiate the type of a method so that it fits * given type arguments and argument types . If successful , return * the method ' s instantiated type , else return null . * The instantiation will take into account an additional leading * formal parameter if the method is an instance method seen as a member * of an under determined site . In this case , we treat site as an additional * parameter and the parameters of the class containing the method as * additional type variables that get instantiated . * @ param env The current environment * @ param site The type of which the method is a member . * @ param m The method symbol . * @ param argtypes The invocation ' s given value arguments . * @ param typeargtypes The invocation ' s given type arguments . * @ param allowBoxing Allow boxing conversions of arguments . * @ param useVarargs Box trailing arguments into an array for varargs . */ Type rawInstantiate ( Env < AttrContext > env , Type site , Symbol m , ResultInfo resultInfo , List < Type > argtypes , List < Type > typeargtypes , boolean allowBoxing , boolean useVarargs , Warner warn ) throws Infer . InferenceException { } }
Type mt = types . memberType ( site , m ) ; // tvars is the list of formal type variables for which type arguments // need to inferred . List < Type > tvars = List . nil ( ) ; if ( typeargtypes == null ) typeargtypes = List . nil ( ) ; if ( ! mt . hasTag ( FORALL ) && typeargtypes . nonEmpty ( ) ) { // This is not a polymorphic method , but typeargs are supplied // which is fine , see JLS 15.12.2.1 } else if ( mt . hasTag ( FORALL ) && typeargtypes . nonEmpty ( ) ) { ForAll pmt = ( ForAll ) mt ; if ( typeargtypes . length ( ) != pmt . tvars . length ( ) ) throw inapplicableMethodException . setMessage ( "arg.length.mismatch" ) ; // not enough args // Check type arguments are within bounds List < Type > formals = pmt . tvars ; List < Type > actuals = typeargtypes ; while ( formals . nonEmpty ( ) && actuals . nonEmpty ( ) ) { List < Type > bounds = types . subst ( types . getBounds ( ( TypeVar ) formals . head ) , pmt . tvars , typeargtypes ) ; for ( ; bounds . nonEmpty ( ) ; bounds = bounds . tail ) if ( ! types . isSubtypeUnchecked ( actuals . head , bounds . head , warn ) ) throw inapplicableMethodException . setMessage ( "explicit.param.do.not.conform.to.bounds" , actuals . head , bounds ) ; formals = formals . tail ; actuals = actuals . tail ; } mt = types . subst ( pmt . qtype , pmt . tvars , typeargtypes ) ; } else if ( mt . hasTag ( FORALL ) ) { ForAll pmt = ( ForAll ) mt ; List < Type > tvars1 = types . newInstances ( pmt . tvars ) ; tvars = tvars . appendList ( tvars1 ) ; mt = types . subst ( pmt . qtype , pmt . tvars , tvars1 ) ; } // find out whether we need to go the slow route via infer boolean instNeeded = tvars . tail != null ; /* inlined : tvars . nonEmpty ( ) */ for ( List < Type > l = argtypes ; l . tail != null /* inlined : l . nonEmpty ( ) */ && ! instNeeded ; l = l . tail ) { if ( l . head . hasTag ( FORALL ) ) instNeeded = true ; } if ( instNeeded ) return infer . instantiateMethod ( env , tvars , ( MethodType ) mt , resultInfo , ( MethodSymbol ) m , argtypes , allowBoxing , useVarargs , currentResolutionContext , warn ) ; DeferredAttr . DeferredAttrContext dc = currentResolutionContext . deferredAttrContext ( m , infer . emptyContext , resultInfo , warn ) ; currentResolutionContext . methodCheck . argumentsAcceptable ( env , dc , argtypes , mt . getParameterTypes ( ) , warn ) ; dc . complete ( ) ; return mt ;
public class HmlUtils { /** * Convert the specified HML Sequence element into a DNA symbol list . * @ param sequence HML Sequence element , must not be null * @ return the specified HML Sequence element converted into a DNA symbol list * @ throws IllegalSymbolException if an illegal symbol is found */ public static SymbolList toDnaSymbolList ( final Sequence sequence ) throws IllegalSymbolException { } }
checkNotNull ( sequence ) ; return DNATools . createDNA ( sequence . getValue ( ) . replaceAll ( "\\s+" , "" ) ) ;
public class SuspensionRecord { /** * Sets the detailed infraction history . * @ param history The detailed infraction history . Cannot be null or empty . */ public void setInfractionHistory ( List < Long > history ) { } }
SystemAssert . requireArgument ( history != null && ! history . isEmpty ( ) , "Infraction History cannot be set to null or empty." ) ; this . infractionHistory = history ;
public class CPDefinitionOptionValueRelUtil { /** * Returns the cp definition option value rels before and after the current cp definition option value rel in the ordered set where CPDefinitionOptionRelId = & # 63 ; . * @ param CPDefinitionOptionValueRelId the primary key of the current cp definition option value rel * @ param CPDefinitionOptionRelId the cp definition option rel ID * @ param orderByComparator the comparator to order the set by ( optionally < code > null < / code > ) * @ return the previous , current , and next cp definition option value rel * @ throws NoSuchCPDefinitionOptionValueRelException if a cp definition option value rel with the primary key could not be found */ public static CPDefinitionOptionValueRel [ ] findByCPDefinitionOptionRelId_PrevAndNext ( long CPDefinitionOptionValueRelId , long CPDefinitionOptionRelId , OrderByComparator < CPDefinitionOptionValueRel > orderByComparator ) throws com . liferay . commerce . product . exception . NoSuchCPDefinitionOptionValueRelException { } }
return getPersistence ( ) . findByCPDefinitionOptionRelId_PrevAndNext ( CPDefinitionOptionValueRelId , CPDefinitionOptionRelId , orderByComparator ) ;
public class ConvertedObjectPool { /** * get the converted object corresponding to sourceObject as converted to * destination type by converter * @ param converter * @ param sourceObject * @ param destinationType * @ return */ public Object get ( IConverter converter , Object sourceObject , TypeReference < ? > destinationType ) { } }
return convertedObjects . get ( new ConvertedObjectsKey ( converter , sourceObject , destinationType ) ) ;
public class JSpinnerEditorValueProvider { /** * Retrieves the text currently in the text component of the spinner , if any . * Note that if editor of the spinner has been customized , this method may need to be adapted in a sub - class . * @ return Spinner text or null if not found . */ protected String getText ( ) { } }
String text = null ; // Try to find a text component in the spinner JTextComponent textEditorComponent ; if ( spinner . getEditor ( ) instanceof JTextComponent ) { textEditorComponent = ( JTextComponent ) spinner . getEditor ( ) ; } else if ( spinner . getEditor ( ) instanceof JSpinner . DefaultEditor ) { textEditorComponent = ( ( JSpinner . DefaultEditor ) spinner . getEditor ( ) ) . getTextField ( ) ; } else { LOGGER . error ( "No text component can be found in the spinner to get the text: " + spinner ) ; textEditorComponent = null ; } // Read text from text component if ( textEditorComponent != null ) { text = textEditorComponent . getText ( ) ; } return text ;
public class CPDefinitionInventoryLocalServiceWrapper { /** * Returns the cp definition inventory matching the UUID and group . * @ param uuid the cp definition inventory ' s UUID * @ param groupId the primary key of the group * @ return the matching cp definition inventory * @ throws PortalException if a matching cp definition inventory could not be found */ @ Override public com . liferay . commerce . model . CPDefinitionInventory getCPDefinitionInventoryByUuidAndGroupId ( String uuid , long groupId ) throws com . liferay . portal . kernel . exception . PortalException { } }
return _cpDefinitionInventoryLocalService . getCPDefinitionInventoryByUuidAndGroupId ( uuid , groupId ) ;
public class ZipUtil { /** * 对流中的数据加入到压缩文件 , 使用默认UTF - 8编码 * @ param zipFile 生成的Zip文件 , 包括文件名 。 注意 : zipPath不能是srcPath路径下的子文件夹 * @ param path 流数据在压缩文件中的路径或文件名 * @ param data 要压缩的数据 * @ return 压缩文件 * @ throws UtilException IO异常 * @ since 3.0.6 */ public static File zip ( File zipFile , String path , String data ) throws UtilException { } }
return zip ( zipFile , path , data , DEFAULT_CHARSET ) ;
public class MapUtil { /** * 根据等号左边的类型 , 构造类型正确的HashMap . * 同时初始化元素 . */ public static < K , V > HashMap < K , V > newHashMap ( @ NotNull final List < K > keys , @ NotNull final List < V > values ) { } }
Validate . isTrue ( keys . size ( ) == values . size ( ) , "keys.length is %s but values.length is %s" , keys . size ( ) , values . size ( ) ) ; HashMap < K , V > map = new HashMap < K , V > ( keys . size ( ) * 2 ) ; Iterator < K > keyIt = keys . iterator ( ) ; Iterator < V > valueIt = values . iterator ( ) ; while ( keyIt . hasNext ( ) ) { map . put ( keyIt . next ( ) , valueIt . next ( ) ) ; } return map ;
public class FileSystem { /** * Add the extension of to specified filename . * If the filename has already the given extension , the filename is not changed . * If the filename has no extension or an other extension , the specified one is added . * @ param filename is the filename to parse . * @ param extension is the extension to remove if it is existing . * @ return the filename with the extension . * @ since 6.0 */ @ Pure public static File addExtension ( File filename , String extension ) { } }
if ( filename != null && ! hasExtension ( filename , extension ) ) { String extent = extension ; if ( ! "" . equals ( extent ) && ! extent . startsWith ( EXTENSION_SEPARATOR ) ) { // $ NON - NLS - 1 $ extent = EXTENSION_SEPARATOR + extent ; } return new File ( filename . getParentFile ( ) , filename . getName ( ) + extent ) ; } return filename ;
public class DescribeFleetResult { /** * A list of robots . * < b > NOTE : < / b > This method appends the values to the existing list ( if any ) . Use * { @ link # setRobots ( java . util . Collection ) } or { @ link # withRobots ( java . util . Collection ) } if you want to override the * existing values . * @ param robots * A list of robots . * @ return Returns a reference to this object so that method calls can be chained together . */ public DescribeFleetResult withRobots ( Robot ... robots ) { } }
if ( this . robots == null ) { setRobots ( new java . util . ArrayList < Robot > ( robots . length ) ) ; } for ( Robot ele : robots ) { this . robots . add ( ele ) ; } return this ;
public class AbstractPlainDatagramSocketImpl { /** * Connects a datagram socket to a remote destination . This associates the remote * address with the local socket so that datagrams may only be sent to this destination * and received from this destination . * @ param address the remote InetAddress to connect to * @ param port the remote port number */ protected void connect ( InetAddress address , int port ) throws SocketException { } }
BlockGuard . getThreadPolicy ( ) . onNetwork ( ) ; connect0 ( address , port ) ; connectedAddress = address ; connectedPort = port ; connected = true ;
public class KarafDistributionOption { /** * This option allows to configure each configuration file based on the karaf . home location . The * value is " put " . Which means it is either replaced or added . * If you like to extend an option ( e . g . make a = b to a = b , c ) please make use of the * { @ link KarafDistributionConfigurationFileExtendOption } . * @ param configurationFilePath * configuration file path * @ param key * property key * @ param value * property value * @ return option */ public static Option editConfigurationFilePut ( String configurationFilePath , String key , Object value ) { } }
return new KarafDistributionConfigurationFilePutOption ( configurationFilePath , key , value ) ;
public class VdWRadiusDescriptor { /** * This method calculate the Van der Waals radius of an atom . * @ param container The { @ link IAtomContainer } for which the descriptor is to be calculated * @ return The Van der Waals radius of the atom */ @ Override public DescriptorValue calculate ( IAtom atom , IAtomContainer container ) { } }
String symbol = atom . getSymbol ( ) ; double vdwradius = PeriodicTable . getVdwRadius ( symbol ) ; return new DescriptorValue ( getSpecification ( ) , getParameterNames ( ) , getParameters ( ) , new DoubleResult ( vdwradius ) , NAMES ) ;
public class DockPaneModel { /** * { @ inheritDoc } */ @ Override protected void initModel ( ) { } }
final WaveChecker waveChecker = wave -> ObjectUtility . equalsOrBothNull ( wave . get ( DOCK_KEY ) , object ( ) . id ( ) ) ; listen ( waveChecker , ADD ) ; listen ( waveChecker , REMOVE ) ; if ( ObjectUtility . nullOrEmpty ( object ( ) . id ( ) ) ) { object ( ) . id ( DockPaneModel . class . getSimpleName ( ) + DOCK_COUNTER ++ ) ; } for ( final PartConfig < ? , ? > pc : object ( ) . panes ( ) ) { callCommand ( AddDockCommand . class , DockWaveBean . create ( ) . dockConfig ( object ( ) ) . parts ( pc ) ) ; }
public class FSDirectory { /** * Get the file info for a specific file . * @ param src The string representation of the path to the file * @ return object containing information regarding the file * or null if file not found */ FileStatus getFileInfo ( String src , INode targetNode ) { } }
String srcs = normalizePath ( src ) ; readLock ( ) ; try { if ( targetNode == null ) { return null ; } else { return createFileStatus ( srcs , targetNode ) ; } } finally { readUnlock ( ) ; }
public class JaxWsHttpServletRequestAdapter { /** * ( non - Javadoc ) * @ see javax . servlet . ServletRequest # getRemoteHost ( ) */ @ Override public String getRemoteHost ( ) { } }
try { collaborator . preInvoke ( componentMetaData ) ; return request . getRemoteHost ( ) ; } finally { collaborator . postInvoke ( ) ; }
public class AttachmentServlet { /** * Also audit logs create and delete . */ private void authorize ( HttpSession session , Action action , Entity entity , String location ) throws AuthorizationException , DataAccessException { } }
AuthenticatedUser user = ( AuthenticatedUser ) session . getAttribute ( "authenticatedUser" ) ; if ( user == null && ApplicationContext . getServiceUser ( ) != null ) { String cuid = ApplicationContext . getServiceUser ( ) ; user = new AuthenticatedUser ( UserGroupCache . getUser ( cuid ) ) ; } if ( user == null ) throw new AuthorizationException ( AuthorizationException . NOT_AUTHORIZED , "Authentication failure" ) ; if ( action == Action . Create || action == Action . Delete ) { if ( ! user . hasRole ( Role . PROCESS_EXECUTION ) ) { throw new AuthorizationException ( AuthorizationException . FORBIDDEN , "User " + user . getCuid ( ) + " not authorized for " + action + " on " + location ) ; } logger . info ( "Asset mod request received from user: " + user . getCuid ( ) + " for: " + location ) ; UserAction userAction = new UserAction ( user . getCuid ( ) , action , entity , 0L , location ) ; userAction . setSource ( getClass ( ) . getSimpleName ( ) ) ; ServiceLocator . getUserServices ( ) . auditLog ( userAction ) ; }
public class SoftwareModuleSpecification { /** * { @ link Specification } for retrieving { @ link SoftwareModule } s by " like * name or like version " . * @ param type * to be filtered on * @ return the { @ link SoftwareModule } { @ link Specification } */ public static Specification < JpaSoftwareModule > equalType ( final Long type ) { } }
return ( targetRoot , query , cb ) -> cb . equal ( targetRoot . < JpaSoftwareModuleType > get ( JpaSoftwareModule_ . type ) . get ( JpaSoftwareModuleType_ . id ) , type ) ;
public class DatalogProgram2QueryConverterImpl { /** * TODO : explain */ private static Optional < ImmutableQueryModifiers > convertModifiers ( MutableQueryModifiers queryModifiers ) { } }
if ( queryModifiers . hasModifiers ( ) ) { ImmutableQueryModifiers immutableQueryModifiers = new ImmutableQueryModifiersImpl ( queryModifiers ) ; return Optional . of ( immutableQueryModifiers ) ; } else { return Optional . empty ( ) ; }
public class UpdateResourceRequestMarshaller { /** * Marshall the given parameter object . */ public void marshall ( UpdateResourceRequest updateResourceRequest , ProtocolMarshaller protocolMarshaller ) { } }
if ( updateResourceRequest == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( updateResourceRequest . getOrganizationId ( ) , ORGANIZATIONID_BINDING ) ; protocolMarshaller . marshall ( updateResourceRequest . getResourceId ( ) , RESOURCEID_BINDING ) ; protocolMarshaller . marshall ( updateResourceRequest . getName ( ) , NAME_BINDING ) ; protocolMarshaller . marshall ( updateResourceRequest . getBookingOptions ( ) , BOOKINGOPTIONS_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; }
public class ClassLister { /** * Adds / appends a class hierarchy . * @ param superclassthe superclass * @ param packagesthe packages */ public void addHierarchy ( String superclass , String [ ] packages ) { } }
List < String > names ; List < Class > classes ; String [ ] patterns ; int i ; Pattern p ; ClassLocator locator ; locator = getClassLocator ( ) ; names = locator . findNames ( superclass , packages ) ; classes = locator . findClasses ( superclass , packages ) ; // remove blacklisted classes if ( m_Blacklist . containsKey ( superclass ) ) { try { patterns = m_Blacklist . getProperty ( superclass ) . replaceAll ( " " , "" ) . split ( "," ) ; for ( String pattern : patterns ) { p = Pattern . compile ( pattern ) ; // names i = 0 ; while ( i < names . size ( ) ) { if ( p . matcher ( names . get ( i ) ) . matches ( ) ) names . remove ( i ) ; else i ++ ; } // classes i = 0 ; while ( i < classes . size ( ) ) { if ( p . matcher ( classes . get ( i ) . getName ( ) ) . matches ( ) ) classes . remove ( i ) ; else i ++ ; } } } catch ( Exception ex ) { getLogger ( ) . log ( Level . SEVERE , "Failed to blacklist classes for superclass '" + superclass + "':" , ex ) ; } } // create class list updateClassnames ( m_CacheNames , superclass , new HashSet < > ( names ) ) ; updateClassnames ( m_ListNames , superclass , new ArrayList < > ( names ) ) ; updateClasses ( m_CacheClasses , superclass , new HashSet < > ( classes ) ) ; updateClasses ( m_ListClasses , superclass , new ArrayList < > ( classes ) ) ;
public class SARLPreferences { /** * Replies the preference store for the given project . * @ param project the project . * @ return the preference store or < code > null < / code > . */ public static IPreferenceStore getSARLPreferencesFor ( IProject project ) { } }
if ( project != null ) { final Injector injector = LangActivator . getInstance ( ) . getInjector ( LangActivator . IO_SARL_LANG_SARL ) ; final IPreferenceStoreAccess preferenceStoreAccess = injector . getInstance ( IPreferenceStoreAccess . class ) ; return preferenceStoreAccess . getWritablePreferenceStore ( project ) ; } return null ;