signature stringlengths 43 39.1k | implementation stringlengths 0 450k |
|---|---|
public class Ifc4PackageImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
@ Override public EClass getIfcPipeFittingType ( ) { } } | if ( ifcPipeFittingTypeEClass == null ) { ifcPipeFittingTypeEClass = ( EClass ) EPackage . Registry . INSTANCE . getEPackage ( Ifc4Package . eNS_URI ) . getEClassifiers ( ) . get ( 420 ) ; } return ifcPipeFittingTypeEClass ; |
public class CoreNaviRpcProcessor { /** * 验证appId和token是否有权限访问方法
* @ param desc
* 方法描述
* @ param appId
* appId
* @ param token
* token
* @ return 是否有权限访问 */
private boolean isAuthoriedAccess ( MethodDescriptor < String > desc , String appId , String token ) { } } | if ( CollectionUtil . isNotEmpty ( desc . getAppIdTokens ( ) ) ) { for ( AppIdToken appIdToken : desc . getAppIdTokens ( ) ) { if ( AppIdToken . isValid ( appIdToken , appId , token ) ) { return true ; } } return false ; } return true ; |
public class NaiveBayesModel { /** * Note : For small probabilities , product may end up zero due to underflow error . Can circumvent by taking logs . */
@ Override protected double [ ] score0 ( double [ ] data , double [ ] preds ) { } } | double [ ] nums = new double [ _output . _levels . length ] ; // log ( p ( x , y ) ) for all levels of y
assert preds . length >= ( _output . _levels . length + 1 ) ; // Note : First column of preds is predicted response class
// Compute joint probability of predictors for every response class
for ( int rlevel = 0 ; rlevel < _output . _levels . length ; rlevel ++ ) { // Take logs to avoid overflow : p ( x , y ) = p ( x | y ) * p ( y ) - > log ( p ( x , y ) ) = log ( p ( x | y ) ) + log ( p ( y ) )
nums [ rlevel ] = Math . log ( _output . _apriori_raw [ rlevel ] ) ; for ( int col = 0 ; col < _output . _ncats ; col ++ ) { if ( Double . isNaN ( data [ col ] ) ) continue ; // Skip predictor in joint x _ 1 , . . . , x _ m if NA
int plevel = ( int ) data [ col ] ; double prob = plevel < _output . _pcond_raw [ col ] [ rlevel ] . length ? _output . _pcond_raw [ col ] [ rlevel ] [ plevel ] : _parms . _laplace / ( ( double ) _output . _rescnt [ rlevel ] + _parms . _laplace * _output . _domains [ col ] . length ) ; // Laplace smoothing if predictor level unobserved in training set
nums [ rlevel ] += Math . log ( prob <= _parms . _eps_prob ? _parms . _min_prob : prob ) ; // log ( p ( x | y ) ) = \ sum _ { j = 1 } ^ m p ( x _ j | y )
} // For numeric predictors , assume Gaussian distribution with sample mean and variance from model
for ( int col = _output . _ncats ; col < data . length ; col ++ ) { if ( Double . isNaN ( data [ col ] ) ) continue ; // Skip predictor in joint x _ 1 , . . . , x _ m if NA
double x = data [ col ] ; double mean = Double . isNaN ( _output . _pcond_raw [ col ] [ rlevel ] [ 0 ] ) ? 0 : _output . _pcond_raw [ col ] [ rlevel ] [ 0 ] ; double stddev = Double . isNaN ( _output . _pcond_raw [ col ] [ rlevel ] [ 1 ] ) ? 1.0 : ( _output . _pcond_raw [ col ] [ rlevel ] [ 1 ] <= _parms . _eps_sdev ? _parms . _min_sdev : _output . _pcond_raw [ col ] [ rlevel ] [ 1 ] ) ; // double prob = Math . exp ( new NormalDistribution ( mean , stddev ) . density ( data [ col ] ) ) ; / / slower
double prob = Math . exp ( - ( ( x - mean ) * ( x - mean ) ) / ( 2. * stddev * stddev ) ) / ( stddev * Math . sqrt ( 2. * Math . PI ) ) ; // faster
nums [ rlevel ] += Math . log ( prob <= _parms . _eps_prob ? _parms . _min_prob : prob ) ; } } // Numerically unstable :
// p ( x , y ) = exp ( log ( p ( x , y ) ) ) , p ( x ) = \ Sum _ { r = levels of y } exp ( log ( p ( x , y = r ) ) ) - > p ( y | x ) = p ( x , y ) / p ( x )
// Instead , we rewrite using a more stable form :
// p ( y | x ) = p ( x , y ) / p ( x ) = exp ( log ( p ( x , y ) ) ) / ( \ Sum _ { r = levels of y } exp ( log ( p ( x , y = r ) ) )
// = 1 / ( exp ( - log ( p ( x , y ) ) ) * \ Sum _ { r = levels of y } exp ( log ( p ( x , y = r ) ) ) )
// = 1 / ( \ Sum _ { r = levels of y } exp ( log ( p ( x , y = r ) ) - log ( p ( x , y ) ) ) )
for ( int i = 0 ; i < nums . length ; i ++ ) { double sum = 0 ; for ( int j = 0 ; j < nums . length ; j ++ ) sum += Math . exp ( nums [ j ] - nums [ i ] ) ; preds [ i + 1 ] = 1 / sum ; } // Select class with highest conditional probability
preds [ 0 ] = GenModel . getPrediction ( preds , _output . _priorClassDist , data , defaultThreshold ( ) ) ; return preds ; |
public class AbstractContainerHelper { /** * Call this method to simulate what would happen if the UIContext was serialized due to clustering of servers . */
protected void cycleUIContext ( ) { } } | boolean cycleIt = ConfigurationProperties . getDeveloperClusterEmulation ( ) ; if ( cycleIt ) { UIContext uic = getUIContext ( ) ; if ( uic instanceof UIContextWrap ) { LOG . info ( "Cycling the UIContext to simulate clustering" ) ; ( ( UIContextWrap ) uic ) . cycle ( ) ; } } |
public class CmsUserSelectionList { /** * Gets the sort key to use . < p >
* @ param column the list column id
* @ return the sort key */
protected SortKey getSortKey ( String column ) { } } | if ( column == null ) { return null ; } if ( column . equals ( LIST_COLUMN_FULLNAME ) ) { return SortKey . fullName ; } else if ( column . equals ( LIST_COLUMN_LOGIN ) ) { return SortKey . loginName ; } return null ; |
public class AbstractCommandBuilder { /** * Adds the arguments to the collection of arguments that will be passed to the server ignoring any { @ code null }
* arguments .
* @ param args the arguments to add
* @ return the builder */
public T addServerArguments ( final String ... args ) { } } | if ( args != null ) { for ( String arg : args ) { addServerArgument ( arg ) ; } } return getThis ( ) ; |
public class CloseGuard { /** * If CloseGuard is enabled , { @ code open } initializes the instance
* with a warning that the caller should have explicitly called the
* { @ code closer } method instead of relying on finalization .
* @ param closer non - null name of explicit termination method
* @ throws NullPointerException if closer is null , regardless of
* whether or not CloseGuard is enabled */
public void open ( String closer ) { } } | // always perform the check for valid API usage . . .
if ( closer == null ) { throw new NullPointerException ( "closer == null" ) ; } // . . . but avoid allocating an allocationSite if disabled
if ( this == NOOP || ! ENABLED ) { return ; } String message = "Explicit termination method '" + closer + "' not called" ; allocationSite = new Throwable ( message ) ; |
public class SolrIndexer { /** * To put events to subscriber queue
* @ param oid
* Object id
* @ param eventType
* type of events happened
* @ param context
* where the event happened
* @ param jsonFile
* Configuration file */
private void sendToIndex ( String message ) { } } | try { getMessaging ( ) . queueMessage ( SolrWrapperQueueConsumer . QUEUE_ID , message ) ; } catch ( MessagingException ex ) { log . error ( "Unable to send message: " , ex ) ; } |
public class CmsObjectWrapper { /** * Locks a resource temporarily . < p >
* @ param resourceName the name of the resource to lock
* @ throws CmsException if something goes wrong */
public void lockResourceTemporary ( String resourceName ) throws CmsException { } } | boolean exec = false ; // iterate through all wrappers and call " lockResource " till one does not return false
List < I_CmsResourceWrapper > wrappers = getWrappers ( ) ; for ( I_CmsResourceWrapper wrapper : wrappers ) { exec = wrapper . lockResource ( m_cms , resourceName , true ) ; if ( exec ) { break ; } } // delegate the call to the CmsObject
if ( ! exec ) { m_cms . lockResourceTemporary ( resourceName ) ; } |
public class MetaKeywords { /** * Get the current class for a meta tag keyword , as the first
* and only element of an array list . */
protected List < String > getClassKeyword ( TypeElement typeElement ) { } } | ArrayList < String > metakeywords = new ArrayList < > ( 1 ) ; String cltypelower = config . utils . isInterface ( typeElement ) ? "interface" : "class" ; metakeywords . add ( config . utils . getFullyQualifiedName ( typeElement ) + " " + cltypelower ) ; return metakeywords ; |
public class MinioClient { /** * Executes put object . If size of object data is < = 5MiB , single put object is used
* else multipart put object is used .
* @ param bucketName
* Bucket name .
* @ param objectName
* Object name in the bucket .
* @ param size
* Size of object data .
* @ param data
* Object data . */
private void putObject ( String bucketName , String objectName , Long size , Object data , Map < String , String > headerMap , ServerSideEncryption sse ) throws InvalidBucketNameException , NoSuchAlgorithmException , IOException , InvalidKeyException , NoResponseException , XmlPullParserException , ErrorResponseException , InternalException , InvalidArgumentException , InsufficientDataException { } } | boolean unknownSize = false ; // Add content type if not already set
if ( headerMap . get ( "Content-Type" ) == null ) { headerMap . put ( "Content-Type" , "application/octet-stream" ) ; } if ( size == null ) { unknownSize = true ; size = MAX_OBJECT_SIZE ; } if ( size <= MIN_MULTIPART_SIZE ) { // Single put object .
if ( sse != null ) { sse . marshal ( headerMap ) ; } putObject ( bucketName , objectName , size . intValue ( ) , data , null , 0 , headerMap ) ; return ; } /* Multipart upload */
int [ ] rv = calculateMultipartSize ( size ) ; int partSize = rv [ 0 ] ; int partCount = rv [ 1 ] ; int lastPartSize = rv [ 2 ] ; Part [ ] totalParts = new Part [ partCount ] ; // if sse is requested set the necessary headers before we begin the multipart session .
if ( sse != null ) { sse . marshal ( headerMap ) ; } // initiate new multipart upload .
String uploadId = initMultipartUpload ( bucketName , objectName , headerMap ) ; try { int expectedReadSize = partSize ; for ( int partNumber = 1 ; partNumber <= partCount ; partNumber ++ ) { if ( partNumber == partCount ) { expectedReadSize = lastPartSize ; } // For unknown sized stream , check available size .
int availableSize = 0 ; if ( unknownSize ) { // Check whether data is available one byte more than expectedReadSize .
availableSize = getAvailableSize ( data , expectedReadSize + 1 ) ; // If availableSize is less or equal to expectedReadSize , then we reached last part .
if ( availableSize <= expectedReadSize ) { // If it is first part , do single put object .
if ( partNumber == 1 ) { putObject ( bucketName , objectName , availableSize , data , null , 0 , headerMap ) ; return ; } expectedReadSize = availableSize ; partCount = partNumber ; } } // In multi - part uploads , Set encryption headers in the case of SSE - C .
Map < String , String > encryptionHeaders = new HashMap < > ( ) ; if ( sse != null && sse . getType ( ) == ServerSideEncryption . Type . SSE_C ) { sse . marshal ( encryptionHeaders ) ; } String etag = putObject ( bucketName , objectName , expectedReadSize , data , uploadId , partNumber , encryptionHeaders ) ; totalParts [ partNumber - 1 ] = new Part ( partNumber , etag ) ; } // All parts have been uploaded , complete the multipart upload .
completeMultipart ( bucketName , objectName , uploadId , totalParts ) ; } catch ( RuntimeException e ) { throw e ; } catch ( Exception e ) { abortMultipartUpload ( bucketName , objectName , uploadId ) ; throw e ; } |
public class Selector { /** * Helper method to transform the given arguments , consisting of the receiver
* and the actual arguments in an Object [ ] , into a new Object [ ] consisting
* of the receiver and the arguments directly . Before the size of args was
* always 2 , the returned Object [ ] will have a size of 1 + n , where n is the
* number arguments . */
private static Object [ ] spread ( Object [ ] args , boolean spreadCall ) { } } | if ( ! spreadCall ) return args ; Object [ ] normalArguments = ( Object [ ] ) args [ 1 ] ; Object [ ] ret = new Object [ normalArguments . length + 1 ] ; ret [ 0 ] = args [ 0 ] ; System . arraycopy ( normalArguments , 0 , ret , 1 , ret . length - 1 ) ; return ret ; |
public class VaultNotificationConfig { /** * A list of one or more events for which Amazon Glacier will send a notification to the specified Amazon SNS topic .
* @ param events
* A list of one or more events for which Amazon Glacier will send a notification to the specified Amazon SNS
* topic . */
public void setEvents ( java . util . Collection < String > events ) { } } | if ( events == null ) { this . events = null ; return ; } this . events = new java . util . ArrayList < String > ( events ) ; |
public class KeyVaultClientBaseImpl { /** * Deletes the certificate contacts for a specified key vault .
* Deletes the certificate contacts for a specified key vault certificate . This operation requires the certificates / managecontacts permission .
* @ param vaultBaseUrl The vault name , for example https : / / myvault . vault . azure . net .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the observable to the Contacts object */
public Observable < ServiceResponse < Contacts > > deleteCertificateContactsWithServiceResponseAsync ( String vaultBaseUrl ) { } } | if ( vaultBaseUrl == null ) { throw new IllegalArgumentException ( "Parameter vaultBaseUrl is required and cannot be null." ) ; } if ( this . apiVersion ( ) == null ) { throw new IllegalArgumentException ( "Parameter this.apiVersion() is required and cannot be null." ) ; } String parameterizedHost = Joiner . on ( ", " ) . join ( "{vaultBaseUrl}" , vaultBaseUrl ) ; return service . deleteCertificateContacts ( this . apiVersion ( ) , this . acceptLanguage ( ) , parameterizedHost , this . userAgent ( ) ) . flatMap ( new Func1 < Response < ResponseBody > , Observable < ServiceResponse < Contacts > > > ( ) { @ Override public Observable < ServiceResponse < Contacts > > call ( Response < ResponseBody > response ) { try { ServiceResponse < Contacts > clientResponse = deleteCertificateContactsDelegate ( response ) ; return Observable . just ( clientResponse ) ; } catch ( Throwable t ) { return Observable . error ( t ) ; } } } ) ; |
public class UEL { /** * Join expressions using the trigger character , if any ( { @ link # DEFAULT _ TRIGGER } if absent ) , of the first .
* @ param expressions
* @ return String */
public static String join ( final String ... expressions ) { } } | Validate . notEmpty ( expressions ) ; final char trigger = isDelimited ( expressions [ 0 ] ) ? getTrigger ( expressions [ 0 ] ) : DEFAULT_TRIGGER ; return join ( trigger , expressions ) ; |
public class DetectorsExtensionHelper { /** * key is the plugin id , value is the plugin library path */
public static synchronized SortedMap < String , String > getContributedDetectors ( ) { } } | if ( contributedDetectors != null ) { return new TreeMap < > ( contributedDetectors ) ; } TreeMap < String , String > set = new TreeMap < > ( ) ; IExtensionRegistry registry = Platform . getExtensionRegistry ( ) ; for ( IConfigurationElement configElt : registry . getConfigurationElementsFor ( EXTENSION_POINT_ID ) ) { addContribution ( set , configElt ) ; } contributedDetectors = set ; return new TreeMap < > ( contributedDetectors ) ; |
public class Configuration { /** * Get the value of the < code > name < / code > property as a < code > Pattern < / code > .
* If no such property is specified , or if the specified value is not a valid
* < code > Pattern < / code > , then an exception is thrown .
* @ param name property name
* @ throws NullPointerException if the configuration property does not exist
* @ throws java . util . regex . PatternSyntaxException if the configured value is not a valid { @ code Pattern }
* @ return property value as a compiled Pattern */
public Pattern getPattern ( String name ) { } } | String valString = get ( name ) ; Preconditions . checkNotNull ( valString ) ; return Pattern . compile ( valString ) ; |
public class Duration { /** * Add the supplied duration to this duration , and return the result .
* @ param duration the duration to add to this object
* @ param unit the unit of the duration being added ; may not be null
* @ return the total duration */
public Duration add ( long duration , TimeUnit unit ) { } } | long durationInNanos = TimeUnit . NANOSECONDS . convert ( duration , unit ) ; return new Duration ( this . durationInNanos + durationInNanos ) ; |
public class Elements { /** * Get the elements in the array that are at the indexes .
* @ since 1.4.0 */
public static < T > T [ ] slice ( T [ ] array , int ... indexes ) { } } | int length = indexes . length ; T [ ] slice = ObjectArrays . newArray ( array , length ) ; for ( int i = 0 ; i < length ; i ++ ) { slice [ i ] = array [ indexes [ i ] ] ; } return slice ; |
public class CommerceCurrencyPersistenceImpl { /** * Removes all the commerce currencies where groupId = & # 63 ; and primary = & # 63 ; from the database .
* @ param groupId the group ID
* @ param primary the primary */
@ Override public void removeByG_P ( long groupId , boolean primary ) { } } | for ( CommerceCurrency commerceCurrency : findByG_P ( groupId , primary , QueryUtil . ALL_POS , QueryUtil . ALL_POS , null ) ) { remove ( commerceCurrency ) ; } |
public class LBiObjLongFunctionBuilder { /** * One of ways of creating builder . This is possibly the least verbose way where compiler should be able to guess the generic parameters . */
@ Nonnull public static < T1 , T2 , R > LBiObjLongFunction < T1 , T2 , R > biObjLongFunctionFrom ( Consumer < LBiObjLongFunctionBuilder < T1 , T2 , R > > buildingFunction ) { } } | LBiObjLongFunctionBuilder builder = new LBiObjLongFunctionBuilder ( ) ; buildingFunction . accept ( builder ) ; return builder . build ( ) ; |
public class RequestProgressManager { /** * Disable request listeners notifications for a specific request . < br / >
* All listeners associated to this request won ' t be called when request
* will finish . < br / >
* @ param request
* Request on which you want to disable listeners
* @ param listRequestListener
* the collection of listeners associated to request not to be
* notified */
public void dontNotifyRequestListenersForRequest ( final CachedSpiceRequest < ? > request , final Collection < RequestListener < ? > > listRequestListener ) { } } | final Set < RequestListener < ? > > setRequestListener = mapRequestToRequestListener . get ( request ) ; requestListenerNotifier . clearNotificationsForRequest ( request , setRequestListener ) ; if ( setRequestListener != null && listRequestListener != null ) { Ln . d ( "Removing listeners of request : " + request . toString ( ) + " : " + setRequestListener . size ( ) ) ; setRequestListener . removeAll ( listRequestListener ) ; } |
public class TypeScriptCompilerMojo { /** * Process all typescripts file from the given directory . Output files are generated in the given destination .
* @ param input the input directory
* @ param destination the output directory
* @ throws WatchingException if the compilation failed */
protected void processDirectory ( File input , File destination ) throws WatchingException { } } | if ( ! input . isDirectory ( ) ) { return ; } if ( ! destination . isDirectory ( ) ) { destination . mkdirs ( ) ; } // Now execute the compiler
// We compute the set of argument according to the Mojo ' s configuration .
try { Collection < File > files = FileUtils . listFiles ( input , new String [ ] { "ts" } , true ) ; if ( files . isEmpty ( ) ) { return ; } List < String > arguments = typescript . createTypeScriptCompilerArgumentList ( input , destination , files ) ; getLog ( ) . info ( "Invoking the TypeScript compiler with " + arguments ) ; npm . registerOutputStream ( true ) ; int exit = npm . execute ( TYPE_SCRIPT_COMMAND , arguments . toArray ( new String [ arguments . size ( ) ] ) ) ; getLog ( ) . debug ( "TypeScript Compiler execution exiting with status: " + exit ) ; } catch ( MojoExecutionException e ) { // If the NPM execution has caught an error stream , try to create the associated watching exception .
if ( ! Strings . isNullOrEmpty ( npm . getLastOutputStream ( ) ) ) { throw build ( npm . getLastOutputStream ( ) ) ; } else { throw new WatchingException ( ERROR_TITLE , "Error while compiling " + input . getAbsolutePath ( ) , input , e ) ; } } |
public class Replication { /** * Set OAuth 1 authentication credentials for the replication target
* @ param consumerSecret client secret
* @ param consumerKey client identifier
* @ param tokenSecret OAuth server token secret
* @ param token OAuth server issued token
* @ return this Replication instance to set more options or trigger the replication */
public Replication targetOauth ( String consumerSecret , String consumerKey , String tokenSecret , String token ) { } } | this . replication = replication . targetOauth ( consumerSecret , consumerKey , tokenSecret , token ) ; return this ; |
public class ConcurrentServiceReferenceMap { /** * Iterate over all services in the map in no specific order . The iterator
* will return the service associated with each ServiceReference as it progresses .
* Creation of the iterator does not eagerly resolve services : resolution
* is done only once per service reference , and only when " next " would
* retrieve that service . */
public Iterator < V > getServices ( ) { } } | final List < V > empty = Collections . emptyList ( ) ; if ( context == null ) { return empty . iterator ( ) ; } return new ValueIterator ( elementMap . values ( ) . iterator ( ) ) ; |
public class PackagedProgram { /** * Takes all JAR files that are contained in this program ' s JAR file and extracts them
* to the system ' s temp directory .
* @ return The file names of the extracted temporary files .
* @ throws ProgramInvocationException Thrown , if the extraction process failed . */
public static List < File > extractContainedLibraries ( URL jarFile ) throws ProgramInvocationException { } } | Random rnd = new Random ( ) ; JarFile jar = null ; try { jar = new JarFile ( new File ( jarFile . toURI ( ) ) ) ; final List < JarEntry > containedJarFileEntries = new ArrayList < JarEntry > ( ) ; Enumeration < JarEntry > entries = jar . entries ( ) ; while ( entries . hasMoreElements ( ) ) { JarEntry entry = entries . nextElement ( ) ; String name = entry . getName ( ) ; if ( name . length ( ) > 8 && name . startsWith ( "lib/" ) && name . endsWith ( ".jar" ) ) { containedJarFileEntries . add ( entry ) ; } } if ( containedJarFileEntries . isEmpty ( ) ) { return Collections . emptyList ( ) ; } else { // go over all contained jar files
final List < File > extractedTempLibraries = new ArrayList < File > ( containedJarFileEntries . size ( ) ) ; final byte [ ] buffer = new byte [ 4096 ] ; boolean incomplete = true ; try { for ( int i = 0 ; i < containedJarFileEntries . size ( ) ; i ++ ) { final JarEntry entry = containedJarFileEntries . get ( i ) ; String name = entry . getName ( ) ; // ' / ' as in case of zip , jar
// java . util . zip . ZipEntry # isDirectory always looks only for ' / ' not for File . separator
name = name . replace ( '/' , '_' ) ; File tempFile ; try { tempFile = File . createTempFile ( rnd . nextInt ( Integer . MAX_VALUE ) + "_" , name ) ; tempFile . deleteOnExit ( ) ; } catch ( IOException e ) { throw new ProgramInvocationException ( "An I/O error occurred while creating temporary file to extract nested library '" + entry . getName ( ) + "'." , e ) ; } extractedTempLibraries . add ( tempFile ) ; // copy the temp file contents to a temporary File
OutputStream out = null ; InputStream in = null ; try { out = new FileOutputStream ( tempFile ) ; in = new BufferedInputStream ( jar . getInputStream ( entry ) ) ; int numRead = 0 ; while ( ( numRead = in . read ( buffer ) ) != - 1 ) { out . write ( buffer , 0 , numRead ) ; } } catch ( IOException e ) { throw new ProgramInvocationException ( "An I/O error occurred while extracting nested library '" + entry . getName ( ) + "' to temporary file '" + tempFile . getAbsolutePath ( ) + "'." ) ; } finally { if ( out != null ) { out . close ( ) ; } if ( in != null ) { in . close ( ) ; } } } incomplete = false ; } finally { if ( incomplete ) { deleteExtractedLibraries ( extractedTempLibraries ) ; } } return extractedTempLibraries ; } } catch ( Throwable t ) { throw new ProgramInvocationException ( "Unknown I/O error while extracting contained jar files." , t ) ; } finally { if ( jar != null ) { try { jar . close ( ) ; } catch ( Throwable t ) { } } } |
public class BELDataHeaderParser { /** * Parse the BEL Data header { @ link File } to a { @ link Map } of block name
* to block properties held in a { @ link Properties } object .
* @ param belDataFile { @ link File } , the BEL data document file to parse
* @ return { @ link Map } of { @ link String } to { @ link Properties } the
* properties indexed in a block name
* @ throws IOException , if there was an error reading from { @ code belDataFile } */
public Map < String , Properties > parse ( File belDataFile ) throws IOException { } } | RandomAccessFile raf = null ; try { raf = new RandomAccessFile ( belDataFile , "r" ) ; Map < String , Properties > blockProperties = new LinkedHashMap < String , Properties > ( ) ; String line ; String currentBlock = null ; boolean aborted = false ; while ( ! aborted && ( line = raf . readLine ( ) ) != null ) { line = line . trim ( ) ; if ( line . startsWith ( "#" ) || line . equals ( "" ) ) { // skip commented or blank lines .
continue ; } else if ( line . charAt ( 0 ) == '[' && line . charAt ( line . length ( ) - 1 ) == ']' ) { currentBlock = line . substring ( 1 , line . length ( ) - 1 ) . trim ( ) ; // if we have reached the VALUE _ BLOCK then we ' re done
// parsing the header .
if ( VALUES_BLOCK . equals ( currentBlock ) ) { nextCharacterOffset = raf . getFilePointer ( ) ; aborted = true ; continue ; } blockProperties . put ( currentBlock , new Properties ( ) ) ; } else { Matcher propertyLineMatcher = PROPERTY_LINE_REGEX . matcher ( line ) ; if ( propertyLineMatcher . matches ( ) ) { blockProperties . get ( currentBlock ) . put ( propertyLineMatcher . group ( 1 ) . trim ( ) , propertyLineMatcher . group ( 2 ) . trim ( ) ) ; } } } return blockProperties ; } finally { if ( raf != null ) { raf . close ( ) ; } } |
public class BasicDao { /** * Updates entry / entries of table by provided values & amp ; conditions
* @ param tableName table name to update values of
* @ param entry entry to update by
* @ param entryMapper a mapper between the the value object to the map key
* @ param idMapper a mapper between the condition column to update by to the value ( . . where column = value )
* @ param < T > entry generic
* @ return number of updated entries */
@ Override public < T > ComposableFuture < Long > update ( final String tableName , final T entry , final EntityMapper < T > entryMapper , final EntityMapper < T > idMapper ) { } } | return execute ( createUpdateCommand ( tableName , entry , entryMapper , idMapper ) ) ; |
public class ConfigurationInfo { /** * Used to query items of all configuration types . May be useful to build configuration tree ( e . g . to search
* all items configured by bundle or by classpath scan ) . Some common filters are
* predefined in { @ link Filters } . Use { @ link Predicate # and ( Predicate ) } , { @ link Predicate # or ( Predicate ) }
* and { @ link Predicate # negate ( ) } to reuse default filters .
* Pay attention that disabled ( or disabled and never registered ) items are also returned .
* @ param filter predicate to filter definitions
* @ return registered item classes in registration order , filtered with provided filter or empty list */
@ SuppressWarnings ( "unchecked" ) public List < Class < Object > > getItems ( final Predicate < ItemInfo > filter ) { } } | final List < Class < Object > > items = ( List ) Lists . newArrayList ( itemsHolder . values ( ) ) ; return filter ( items , filter ) ; |
public class CmsDefaultXmlContentHandler { /** * Initializes the layout for this content handler . < p >
* Unless otherwise instructed , the editor uses one specific GUI widget for each
* XML value schema type . For example , for a { @ link org . opencms . xml . types . CmsXmlStringValue }
* the default widget is the { @ link org . opencms . widgets . CmsInputWidget } .
* However , certain values can also use more then one widget , for example you may
* also use a { @ link org . opencms . widgets . CmsCheckboxWidget } for a String value ,
* and as a result the Strings possible values would be either < code > " false " < / code > or < code > " true " < / code > ,
* but nevertheless be a String . < p >
* The widget to use can further be controlled using the < code > widget < / code > attribute .
* You can specify either a valid widget alias such as < code > StringWidget < / code > ,
* or the name of a Java class that implements < code > { @ link I _ CmsWidget } < / code > . < p >
* Configuration options to the widget can be passed using the < code > configuration < / code >
* attribute . You can specify any String as configuration . This String is then passed
* to the widget during initialization . It ' s up to the individual widget implementation
* to interpret this configuration String . < p >
* @ param root the " layouts " element from the appinfo node of the XML content definition
* @ param contentDefinition the content definition the layout belongs to
* @ throws CmsXmlException if something goes wrong */
protected void initLayouts ( Element root , CmsXmlContentDefinition contentDefinition ) throws CmsXmlException { } } | m_useAcacia = safeParseBoolean ( root . attributeValue ( ATTR_USE_ACACIA ) , true ) ; Iterator < Element > i = CmsXmlGenericWrapper . elementIterator ( root , APPINFO_LAYOUT ) ; while ( i . hasNext ( ) ) { // iterate all " layout " elements in the " layouts " node
Element element = i . next ( ) ; String elementName = element . attributeValue ( APPINFO_ATTR_ELEMENT ) ; String widgetClassOrAlias = element . attributeValue ( APPINFO_ATTR_WIDGET ) ; String configuration = element . attributeValue ( APPINFO_ATTR_CONFIGURATION ) ; String displayStr = element . attributeValue ( APPINFO_ATTR_DISPLAY ) ; if ( CmsStringUtil . isNotEmptyOrWhitespaceOnly ( displayStr ) && ( elementName != null ) ) { addDisplayType ( contentDefinition , elementName , DisplayType . valueOf ( displayStr ) ) ; } if ( ( elementName != null ) && CmsStringUtil . isNotEmptyOrWhitespaceOnly ( widgetClassOrAlias ) ) { // add a widget mapping for the element
addWidget ( contentDefinition , elementName , widgetClassOrAlias ) ; if ( configuration != null ) { addConfiguration ( contentDefinition , elementName , configuration ) ; } } } |
public class C4BlobStore { /** * Opens a blob for reading , as a random - access byte stream . */
public C4BlobReadStream openReadStream ( C4BlobKey blobKey ) throws LiteCoreException { } } | return new C4BlobReadStream ( openReadStream ( handle , blobKey . getHandle ( ) ) ) ; |
public class NFVORequestor { /** * Returns a UserAgent with which requests regarding Users can be sent to the NFVO .
* @ return a UserAgent */
public synchronized UserAgent getUserAgent ( ) { } } | if ( this . userAgent == null ) { if ( isService ) { this . userAgent = new UserAgent ( this . serviceName , this . projectId , this . sslEnabled , this . nfvoIp , this . nfvoPort , this . version , this . serviceKey ) ; } else { this . userAgent = new UserAgent ( this . username , this . password , this . projectId , this . sslEnabled , this . nfvoIp , this . nfvoPort , this . version ) ; } } return this . userAgent ; |
public class JaxRxResource { /** * This method will be called when a HTTP client sends a POST request to an
* existing resource with ' application / query + xml ' as Content - Type .
* @ param system
* The implementation system .
* @ param input
* The input stream .
* @ param headers
* HTTP header attributes .
* @ return The { @ link Response } which can be empty when no response is
* expected . Otherwise it holds the response XML file . */
@ Path ( JaxRxConstants . JAXRXPATH ) @ POST @ Consumes ( APPLICATION_QUERY_XML ) public Response postQuery ( @ PathParam ( JaxRxConstants . SYSTEM ) final String system , final InputStream input , @ Context final HttpHeaders headers ) { } } | return postQuery ( system , input , "" , headers ) ; |
public class FlyWeightFlatXmlProducer { /** * merges the existing columns with the potentially new ones .
* @ param columnsToMerge List of extra columns found , which need to be merge back into the metadata .
* @ return ITableMetaData The merged metadata object containing the new columns
* @ throws DataSetException */
private ITableMetaData mergeTableMetaData ( List < Column > columnsToMerge , ITableMetaData originalMetaData ) throws DataSetException { } } | Column [ ] columns = new Column [ originalMetaData . getColumns ( ) . length + columnsToMerge . size ( ) ] ; System . arraycopy ( originalMetaData . getColumns ( ) , 0 , columns , 0 , originalMetaData . getColumns ( ) . length ) ; for ( int i = 0 ; i < columnsToMerge . size ( ) ; i ++ ) { Column column = columnsToMerge . get ( i ) ; columns [ columns . length - columnsToMerge . size ( ) + i ] = column ; } return new DefaultTableMetaData ( originalMetaData . getTableName ( ) , columns ) ; |
public class StorageUtil { /** * reads a XML Element Attribute ans cast it to a DateTime Object
* @ param config
* @ param el XML Element to read Attribute from it
* @ param attributeName Name of the Attribute to read
* @ return Attribute Value */
public DateTime toDateTime ( Config config , Element el , String attributeName ) { } } | String str = el . getAttribute ( attributeName ) ; if ( str == null ) return null ; return DateCaster . toDateAdvanced ( str , ThreadLocalPageContext . getTimeZone ( config ) , null ) ; |
public class Cob2JaxbConverter { /** * Convert host data to a JAXB instance .
* @ param hostData the buffer of host data
* @ param start where to start in the buffer of host data
* @ param length How many bytes of hostData contains actual data to process
* @ return a result object containing the JAXB instance created as well as
* the total number of host bytes used to generate that JAXB
* instance */
public FromHostResult < J > convert ( byte [ ] hostData , int start , int length ) { } } | Cob2JaxbVisitor visitor = new Cob2JaxbVisitor ( getCobolContext ( ) , hostData , start , length , jaxbWrapperFactory ) ; visitor . visit ( getCobolComplexType ( ) ) ; JaxbWrapper < ? > jaxbWrapper = visitor . getLastObject ( JaxbWrapper . class ) ; return new FromHostResult < J > ( visitor . getLastPos ( ) , jaxbClass . cast ( jaxbWrapper . getJaxb ( ) ) ) ; |
public class KnowledgeOperations { /** * Gets an input - output map .
* @ param message the message
* @ param operation the operation
* @ param runtime the runtime engine
* @ return the input - output map */
public static Map < String , Object > getInputOutputMap ( Message message , KnowledgeOperation operation , KnowledgeRuntimeEngine runtime ) { } } | Map < String , Object > map = new LinkedHashMap < String , Object > ( ) ; Map < String , ExpressionMapping > inputs = operation . getInputOutputExpressionMappings ( ) ; for ( Entry < String , ExpressionMapping > entry : inputs . entrySet ( ) ) { List < Object > list = getList ( message , Collections . singletonList ( entry . getValue ( ) ) ) ; final Object output ; switch ( list . size ( ) ) { case 0 : output = null ; break ; case 1 : output = list . get ( 0 ) ; break ; default : output = list ; } map . put ( entry . getKey ( ) , output ) ; } return map ; |
public class SingleLockedMessageEnumerationImpl { /** * / * ( non - Javadoc )
* @ see com . ibm . wsspi . sib . core . LockedMessageEnumeration # getConsumerSession ( ) */
public ConsumerSession getConsumerSession ( ) throws SISessionUnavailableException , SISessionDroppedException , SIIncorrectCallException { } } | if ( TraceComponent . isAnyTracingEnabled ( ) && CoreSPILockedMessageEnumeration . tc . isEntryEnabled ( ) ) SibTr . entry ( CoreSPILockedMessageEnumeration . tc , "getConsumerSession" , this ) ; checkValidState ( "getConsumerSession" ) ; _localConsumerPoint . checkNotClosed ( ) ; if ( TraceComponent . isAnyTracingEnabled ( ) && CoreSPILockedMessageEnumeration . tc . isEntryEnabled ( ) ) SibTr . exit ( CoreSPILockedMessageEnumeration . tc , "getConsumerSession" , _localConsumerPoint . getConsumerSession ( ) ) ; return _localConsumerPoint . getConsumerSession ( ) ; |
public class LoadBalancerContext { /** * Derive the host and port from virtual address if virtual address is indeed contains the actual host
* and port of the server . This is the final resort to compute the final URI in { @ link # getServerFromLoadBalancer ( java . net . URI , Object ) }
* if there is no load balancer available and the request URI is incomplete . Sub classes can override this method
* to be more accurate or throws ClientException if it does not want to support virtual address to be the
* same as physical server address .
* The virtual address is used by certain load balancers to filter the servers of the same function
* to form the server pool . */
protected Pair < String , Integer > deriveHostAndPortFromVipAddress ( String vipAddress ) throws URISyntaxException , ClientException { } } | Pair < String , Integer > hostAndPort = new Pair < String , Integer > ( null , - 1 ) ; URI uri = new URI ( vipAddress ) ; String scheme = uri . getScheme ( ) ; if ( scheme == null ) { uri = new URI ( "http://" + vipAddress ) ; } String host = uri . getHost ( ) ; if ( host == null ) { throw new ClientException ( "Unable to derive host/port from vip address " + vipAddress ) ; } int port = uri . getPort ( ) ; if ( port < 0 ) { port = getDefaultPortFromScheme ( scheme ) ; } if ( port < 0 ) { throw new ClientException ( "Unable to derive host/port from vip address " + vipAddress ) ; } hostAndPort . setFirst ( host ) ; hostAndPort . setSecond ( port ) ; return hostAndPort ; |
public class CmsMessageBundleEditorModel { /** * Creates all propertyvfsbundle files for the currently loaded translations .
* The method is used to convert xmlvfsbundle files into propertyvfsbundle files .
* @ throws CmsIllegalArgumentException thrown if resource creation fails .
* @ throws CmsLoaderException thrown if the propertyvfsbundle type can ' t be read from the resource manager .
* @ throws CmsException thrown if creation , type retrieval or locking fails . */
private void createPropertyVfsBundleFiles ( ) throws CmsIllegalArgumentException , CmsLoaderException , CmsException { } } | String bundleFileBasePath = m_sitepath + m_basename + "_" ; for ( Locale l : m_localizations . keySet ( ) ) { CmsResource res = m_cms . createResource ( bundleFileBasePath + l . toString ( ) , OpenCms . getResourceManager ( ) . getResourceType ( CmsMessageBundleEditorTypes . BundleType . PROPERTY . toString ( ) ) ) ; m_bundleFiles . put ( l , res ) ; LockedFile file = LockedFile . lockResource ( m_cms , res ) ; file . setCreated ( true ) ; m_lockedBundleFiles . put ( l , file ) ; m_changedTranslations . add ( l ) ; } |
public class HeapAlphaSketch { /** * Computes whether there have been 0 , 1 , or 2 or more actual insertions into the cache in a
* numerically safe way .
* @ param theta < a href = " { @ docRoot } / resources / dictionary . html # theta " > See Theta < / a > .
* @ param alpha internal computed value alpha .
* @ param p < a href = " { @ docRoot } / resources / dictionary . html # p " > See Sampling Probability , < i > p < / i > < / a > .
* @ return R . */
private static final int getR ( final double theta , final double alpha , final double p ) { } } | final double split1 = ( p * ( alpha + 1.0 ) ) / 2.0 ; if ( theta > split1 ) { return 0 ; } if ( theta > ( alpha * split1 ) ) { return 1 ; } return 2 ; |
public class Graph { /** * Print readable circular graph
* @ throws CircularDependenciesException */
private void throwCircularDependenciesException ( ) throws CircularDependenciesException { } } | String msg = "Circular dependencies found. Check the circular graph below:\n" ; boolean firstNode = true ; String tab = " " ; for ( String visit : visitedInjectNodes ) { if ( ! firstNode ) { msg += tab + "->" ; tab += tab ; } msg += visit + "\n" ; firstNode = false ; } msg += tab . substring ( 2 ) + "->" + revisitedNode + "\n" ; throw new CircularDependenciesException ( msg ) ; |
public class AliasSensitiveX509KeyManager { /** * / * ( non - Javadoc )
* @ see javax . net . ssl . X509KeyManager # chooseClientAlias ( java . lang . String [ ] , java . security . Principal [ ] , java . net . Socket ) */
public String chooseClientAlias ( String [ ] keyType , Principal [ ] issuers , Socket socket ) { } } | // If not security domain is available , or the preferred alias is NULL ,
// then default to the nested key manager ' s process for selecting the keystore
if ( null == domain || domain . getPreferredKeyAlias ( ) == null ) { if ( LOGGER . isInfoEnabled ( ) ) { LOGGER . info ( "No preferred key alias defined. Defaulting to JSSE certificate selection." ) ; } return parent . chooseClientAlias ( keyType , issuers , socket ) ; } String preferredAlias = domain . getPreferredKeyAlias ( ) ; String alias = null ; if ( keyType != null && keyType . length > 0 ) { for ( int i = 0 ; i < keyType . length ; i ++ ) { alias = chooseClientAliasForKey ( preferredAlias , keyType [ i ] , issuers , socket ) ; if ( alias != null && ! "" . equals ( alias ) ) { if ( LOGGER . isInfoEnabled ( ) ) { LOGGER . info ( "Found valid keystore alias: " + alias ) ; } return alias ; } } } LOGGER . warn ( "The requested key alias " + preferredAlias + " was not found in the keystore. No certificate selected. The transaction will probably fail." ) ; return null ; |
public class FromCobolVisitor { /** * Visit a primitive type performing the actual conversion to a java object .
* If there is an extra offset left over by a previous item , adjust the
* position accordingly .
* @ param type the primitive type
* @ param callback a function that is invoked after the primitive type has
* been visited
* @ throws FromCobolException */
public void visitCobolPrimitiveType ( CobolPrimitiveType < ? > type , PrimitiveTypeHandler callback ) throws FromCobolException { } } | if ( extraOffset > 0 ) { lastPos += extraOffset ; extraOffset = 0 ; } if ( lastPos >= length ) { if ( isDebugEnabled ) { log . debug ( getCurFieldFullCobolName ( ) + " past maximum length" ) ; } return ; } cobolNamesStack . push ( type . getCobolName ( ) ) ; callback . preVisit ( type ) ; FromHostPrimitiveResult < ? > result = type . fromHost ( cobolContext , hostData , lastPos ) ; if ( result . isSuccess ( ) ) { lastPos += type . getBytesLen ( ) ; } else { throw new FromCobolException ( result . getErrorMessage ( ) , getCurFieldFullCobolName ( ) , type ) ; } // Keep those values that might be needed later
if ( type . isOdoObject ( ) || isCustomVariable ( type , curFieldName ) ) { putVariable ( curFieldName , result . getValue ( ) ) ; } if ( isDebugEnabled ) { log . debug ( getCurFieldFullCobolName ( ) + "=" + result . getValue ( ) ) ; } callback . postVisit ( type , result . getValue ( ) ) ; cobolNamesStack . pop ( ) ; |
public class ResponseBuilder { /** * Adds a Dialog { @ link ElicitSlotDirective } to the response .
* @ param slotName name of slot to elicit
* @ param updatedIntent updated intent
* @ return response builder */
public ResponseBuilder addElicitSlotDirective ( String slotName , Intent updatedIntent ) { } } | ElicitSlotDirective elicitSlotDirective = ElicitSlotDirective . builder ( ) . withUpdatedIntent ( updatedIntent ) . withSlotToElicit ( slotName ) . build ( ) ; return addDirective ( elicitSlotDirective ) ; |
public class AsyncMutateInBuilder { /** * Insert a fragment , replacing the old value if the path exists .
* @ param path the path where to insert ( or replace ) a dictionary value .
* @ param fragment the new dictionary value to be applied . */
public < T > AsyncMutateInBuilder upsert ( String path , T fragment ) { } } | if ( StringUtil . isNullOrEmpty ( path ) ) { throw new IllegalArgumentException ( "Path must not be empty for upsert" ) ; } this . mutationSpecs . add ( new MutationSpec ( Mutation . DICT_UPSERT , path , fragment ) ) ; return this ; |
public class SipSession { /** * This basic method sends out a request message as part of a transaction . A test program should
* use this method when a response to a request is expected . A Request object is constructed from
* the string passed in .
* This method returns when the request message has been sent out . The calling program must
* subsequently call the waitResponse ( ) method to wait for the result ( response , timeout , etc . ) .
* @ param reqMessage A request message in the form of a String with everything from the request
* line and headers to the body . It must be in the proper format per RFC - 3261.
* @ param viaProxy If true , send the message to the proxy . In this case the request URI is
* modified by this method . Else send it to the user specified in the given request URI . In
* this case , for an INVITE request , a route header must be present for the request routing
* to complete . This method does NOT add a route header .
* @ param dialog If not null , send the request via the given dialog . Else send it outside of any
* dialog .
* @ return A SipTransaction object if the message was built and sent successfully , null otherwise .
* The calling program doesn ' t need to do anything with the returned SipTransaction other
* than pass it in to a subsequent call to waitResponse ( ) .
* @ throws ParseException if an error is encountered while parsing the string . */
public SipTransaction sendRequestWithTransaction ( String reqMessage , boolean viaProxy , Dialog dialog ) throws ParseException { } } | Request request = parent . getMessageFactory ( ) . createRequest ( reqMessage ) ; return sendRequestWithTransaction ( request , viaProxy , dialog ) ; |
public class IteratedGatheringModelProcessable { /** * Creates , from the iterated object ( e . g . right part of a th : each expression ) , the iterator that will be used . */
private static Iterator < ? > computeIteratedObjectIterator ( final Object iteratedObject ) { } } | if ( iteratedObject == null ) { return Collections . EMPTY_LIST . iterator ( ) ; } if ( iteratedObject instanceof Collection < ? > ) { return ( ( Collection < ? > ) iteratedObject ) . iterator ( ) ; } if ( iteratedObject instanceof Map < ? , ? > ) { return ( ( Map < ? , ? > ) iteratedObject ) . entrySet ( ) . iterator ( ) ; } if ( iteratedObject . getClass ( ) . isArray ( ) ) { return new Iterator < Object > ( ) { protected final Object array = iteratedObject ; protected final int length = Array . getLength ( this . array ) ; private int i = 0 ; public boolean hasNext ( ) { return this . i < this . length ; } public Object next ( ) { return Array . get ( this . array , i ++ ) ; } public void remove ( ) { throw new UnsupportedOperationException ( "Cannot remove from an array iterator" ) ; } } ; } if ( iteratedObject instanceof Iterable < ? > ) { return ( ( Iterable < ? > ) iteratedObject ) . iterator ( ) ; } if ( iteratedObject instanceof Iterator < ? > ) { return ( Iterator < ? > ) iteratedObject ; } if ( iteratedObject instanceof Enumeration < ? > ) { return new Iterator < Object > ( ) { protected final Enumeration < ? > enumeration = ( Enumeration < ? > ) iteratedObject ; public boolean hasNext ( ) { return this . enumeration . hasMoreElements ( ) ; } public Object next ( ) { return this . enumeration . nextElement ( ) ; } public void remove ( ) { throw new UnsupportedOperationException ( "Cannot remove from an Enumeration iterator" ) ; } } ; } return Collections . singletonList ( iteratedObject ) . iterator ( ) ; |
public class FreeTextSearch { /** * Search in the specified index for nodes matching the the given value .
* Any indexed property is searched .
* @ param index The name of the index to search in .
* @ param query The query specifying what to search for .
* @ param maxNumberOfresults maximum number of results to be retruned . Defaults to 100 . If - 1 , returns all the results .
* @ return a stream of all matching nodes . */
@ Procedure ( mode = Mode . READ ) @ Description ( "apoc.index.search('name', 'query', [maxNumberOfResults]) YIELD node, weight - search for nodes in the free text index matching the given query" ) public Stream < WeightedNodeResult > search ( @ Name ( "index" ) String index , @ Name ( "query" ) String query , @ Name ( value = "numberOfResults" , defaultValue = "100" ) long maxNumberOfresults ) throws Exception { } } | if ( ! db . index ( ) . existsForNodes ( index ) ) { return Stream . empty ( ) ; } QueryContext queryParam = new QueryContext ( parseFreeTextQuery ( query ) ) . sort ( Sort . RELEVANCE ) ; if ( maxNumberOfresults != - 1 ) { queryParam = queryParam . top ( ( int ) maxNumberOfresults ) ; } return toWeightedNodeResult ( db . index ( ) . forNodes ( index ) . query ( queryParam ) ) ; |
public class DownloadChemCompProvider { /** * Get this provider ' s cache path
* @ return */
public static File getPath ( ) { } } | if ( path == null ) { UserConfiguration config = new UserConfiguration ( ) ; path = new File ( config . getCacheFilePath ( ) ) ; } return path ; |
public class ListUtil { /** * finds a value inside a list , ignore case , ignore empty items
* @ param list list to search
* @ param value value to find
* @ param delimiter delimiter of the list
* @ return position in list or 0 */
public static int listFindNoCaseIgnoreEmpty ( String list , String value , char delimiter ) { } } | if ( list == null ) return - 1 ; int len = list . length ( ) ; if ( len == 0 ) return - 1 ; int last = 0 ; int count = 0 ; for ( int i = 0 ; i < len ; i ++ ) { if ( list . charAt ( i ) == delimiter ) { if ( last < i ) { if ( list . substring ( last , i ) . equalsIgnoreCase ( value ) ) return count ; count ++ ; } last = i + 1 ; } } if ( last < len ) { if ( list . substring ( last ) . equalsIgnoreCase ( value ) ) return count ; } return - 1 ; |
public class SparseWeightedDirectedTypedEdgeSet { /** * { @ inheritDoc } */
public boolean connects ( int vertex , T type ) { } } | if ( inEdges . containsKey ( vertex ) ) { for ( WeightedDirectedTypedEdge < T > e : inEdges . get ( vertex ) ) { if ( e . edgeType ( ) . equals ( type ) ) return true ; } } else if ( outEdges . containsKey ( vertex ) ) { for ( WeightedDirectedTypedEdge < T > e : outEdges . get ( vertex ) ) { if ( e . edgeType ( ) . equals ( type ) ) return true ; } } return false ; |
public class Watch { /** * Applies the mutations in changeMap to the document tree . Modified ' documentSet ' in - place and
* returns the changed documents .
* @ param readTime The time at which this snapshot was obtained . */
private List < DocumentChange > computeSnapshot ( Timestamp readTime ) { } } | List < DocumentChange > appliedChanges = new ArrayList < > ( ) ; ChangeSet changeSet = extractChanges ( readTime ) ; // Process the sorted changes in the order that is expected by our clients ( removals , additions ,
// and then modifications ) . We also need to sort the individual changes to assure that
// oldIndex / newIndex keep incrementing .
Collections . sort ( changeSet . deletes , comparator ) ; for ( QueryDocumentSnapshot delete : changeSet . deletes ) { appliedChanges . add ( deleteDoc ( delete ) ) ; } Collections . sort ( changeSet . adds , comparator ) ; for ( QueryDocumentSnapshot add : changeSet . adds ) { appliedChanges . add ( addDoc ( add ) ) ; } Collections . sort ( changeSet . updates , comparator ) ; for ( QueryDocumentSnapshot update : changeSet . updates ) { DocumentChange change = modifyDoc ( update ) ; if ( change != null ) { appliedChanges . add ( change ) ; } } return appliedChanges ; |
public class BenchmarkMatrixMultAccessors { /** * Only sets and gets that are by row and column are used . */
public static long access2d ( DMatrixRMaj a , DMatrixRMaj b , DMatrixRMaj c ) { } } | long timeBefore = System . currentTimeMillis ( ) ; for ( int i = 0 ; i < a . numRows ; i ++ ) { for ( int j = 0 ; j < b . numCols ; j ++ ) { c . set ( i , j , a . get ( i , 0 ) * b . get ( 0 , j ) ) ; } for ( int k = 1 ; k < b . numRows ; k ++ ) { for ( int j = 0 ; j < b . numCols ; j ++ ) { // c . set ( i , j , c . get ( i , j ) + a . get ( i , k ) * b . get ( k , j ) ) ;
c . data [ i * b . numCols + j ] += a . get ( i , k ) * b . get ( k , j ) ; } } } return System . currentTimeMillis ( ) - timeBefore ; |
public class CmsObject { /** * Writes a resource to the OpenCms VFS , including it ' s content . < p >
* Applies only to resources of type < code > { @ link CmsFile } < / code >
* i . e . resources that have a binary content attached . < p >
* Certain resource types might apply content validation or transformation rules
* before the resource is actually written to the VFS . The returned result
* might therefore be a modified version from the provided original . < p >
* @ param resource the resource to write
* @ return the written resource ( may have been modified )
* @ throws CmsException if something goes wrong */
public CmsFile writeFile ( CmsFile resource ) throws CmsException { } } | return getResourceType ( resource ) . writeFile ( this , m_securityManager , resource ) ; |
public class ISUPMessageFactoryImpl { /** * ( non - Javadoc )
* @ see org . restcomm . protocols . ss7 . isup . ISUPMessageFactory # createACM ( int ) */
@ Override public AddressCompleteMessage createACM ( int cic ) { } } | AddressCompleteMessage acm = createACM ( ) ; CircuitIdentificationCode code = this . parameterFactory . createCircuitIdentificationCode ( ) ; code . setCIC ( cic ) ; acm . setCircuitIdentificationCode ( code ) ; return acm ; |
public class AbstractParamDialog { /** * This method initializes jSplitPane
* @ return javax . swing . JSplitPane */
private AbstractParamContainerPanel getJSplitPane ( ) { } } | if ( jSplitPane == null ) { jSplitPane = new AbstractParamContainerPanel ( ) ; jSplitPane . setVisible ( true ) ; if ( this . rootName != null ) { jSplitPane . getRootNode ( ) . setUserObject ( rootName ) ; } } return jSplitPane ; |
public class DataSet { /** * Groups a { @ link DataSet } using a { @ link KeySelector } function .
* The KeySelector function is called for each element of the DataSet and extracts a single
* key value on which the DataSet is grouped . < / br >
* This method returns an { @ link UnsortedGrouping } on which one of the following grouping transformation
* can be applied .
* < ul >
* < li > { @ link UnsortedGrouping # sortGroup ( int , eu . stratosphere . api . common . operators . Order ) } to get a { @ link SortedGrouping } .
* < li > { @ link Grouping # aggregate ( Aggregations , int ) } to apply an Aggregate transformation .
* < li > { @ link Grouping # reduce ( ReduceFunction ) } to apply a Reduce transformation .
* < li > { @ link Grouping # reduceGroup ( GroupReduceFunction ) } to apply a GroupReduce transformation .
* < / ul >
* @ param keyExtractor The KeySelector function which extracts the key values from the DataSet on which it is grouped .
* @ return An UnsortedGrouping on which a transformation needs to be applied to obtain a transformed DataSet .
* @ see KeySelector
* @ see Grouping
* @ see UnsortedGrouping
* @ see SortedGrouping
* @ see AggregateOperator
* @ see ReduceOperator
* @ see GroupReduceOperator
* @ see DataSet */
public < K extends Comparable < K > > UnsortedGrouping < T > groupBy ( KeySelector < T , K > keyExtractor ) { } } | return new UnsortedGrouping < T > ( this , new Keys . SelectorFunctionKeys < T , K > ( keyExtractor , getType ( ) ) ) ; |
public class VariableTranslator { /** * If pkg is null then will use any available bundle to provide the translator . */
public static boolean isDocumentReferenceVariable ( Package pkg , String type ) { } } | com . centurylink . mdw . variable . VariableTranslator trans = getTranslator ( pkg , type ) ; return ( trans instanceof DocumentReferenceTranslator ) ; |
public class ByteSequence { /** * Compares this byte sequence to another .
* @ param obs byte sequence to compare
* @ return comparison result
* @ see # compareBytes ( ByteSequence , ByteSequence ) */
public int compareTo ( ByteSequence obs ) { } } | if ( isBackedByArray ( ) && obs . isBackedByArray ( ) ) { return WritableComparator . compareBytes ( getBackingArray ( ) , offset ( ) , length ( ) , obs . getBackingArray ( ) , obs . offset ( ) , obs . length ( ) ) ; } return compareBytes ( this , obs ) ; |
public class ClassWriterImpl { /** * { @ inheritDoc } */
@ Override public void addClassSignature ( String modifiers , Content classInfoTree ) { } } | classInfoTree . addContent ( new HtmlTree ( HtmlTag . BR ) ) ; Content pre = new HtmlTree ( HtmlTag . PRE ) ; addAnnotationInfo ( typeElement , pre ) ; pre . addContent ( modifiers ) ; LinkInfoImpl linkInfo = new LinkInfoImpl ( configuration , LinkInfoImpl . Kind . CLASS_SIGNATURE , typeElement ) ; // Let ' s not link to ourselves in the signature .
linkInfo . linkToSelf = false ; Content className = new StringContent ( utils . getSimpleName ( typeElement ) ) ; Content parameterLinks = getTypeParameterLinks ( linkInfo ) ; if ( configuration . linksource ) { addSrcLink ( typeElement , className , pre ) ; pre . addContent ( parameterLinks ) ; } else { Content span = HtmlTree . SPAN ( HtmlStyle . typeNameLabel , className ) ; span . addContent ( parameterLinks ) ; pre . addContent ( span ) ; } if ( ! utils . isInterface ( typeElement ) ) { TypeMirror superclass = utils . getFirstVisibleSuperClass ( typeElement ) ; if ( superclass != null ) { pre . addContent ( DocletConstants . NL ) ; pre . addContent ( "extends " ) ; Content link = getLink ( new LinkInfoImpl ( configuration , LinkInfoImpl . Kind . CLASS_SIGNATURE_PARENT_NAME , superclass ) ) ; pre . addContent ( link ) ; } } List < ? extends TypeMirror > interfaces = typeElement . getInterfaces ( ) ; if ( ! interfaces . isEmpty ( ) ) { boolean isFirst = true ; for ( TypeMirror type : interfaces ) { TypeElement tDoc = utils . asTypeElement ( type ) ; if ( ! ( utils . isPublic ( tDoc ) || utils . isLinkable ( tDoc ) ) ) { continue ; } if ( isFirst ) { pre . addContent ( DocletConstants . NL ) ; pre . addContent ( utils . isInterface ( typeElement ) ? "extends " : "implements " ) ; isFirst = false ; } else { pre . addContent ( ", " ) ; } Content link = getLink ( new LinkInfoImpl ( configuration , LinkInfoImpl . Kind . CLASS_SIGNATURE_PARENT_NAME , type ) ) ; pre . addContent ( link ) ; } } classInfoTree . addContent ( pre ) ; |
public class DeleteCodeRepositoryRequestMarshaller { /** * Marshall the given parameter object . */
public void marshall ( DeleteCodeRepositoryRequest deleteCodeRepositoryRequest , ProtocolMarshaller protocolMarshaller ) { } } | if ( deleteCodeRepositoryRequest == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( deleteCodeRepositoryRequest . getCodeRepositoryName ( ) , CODEREPOSITORYNAME_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class CSSNumberHelper { /** * Try to find the unit that is used in the specified values . This check is
* done using " endsWith " so you have to make sure , that no trailing spaces are
* contained in the passed value . This check includes a check for percentage
* values ( e . g . < code > 10 % < / code > )
* @ param sCSSValue
* The value to check . May not be < code > null < / code > .
* @ return < code > null < / code > if no matching unit from { @ link ECSSUnit } was
* found .
* @ see # getMatchingUnitExclPercentage ( String ) */
@ Nullable public static ECSSUnit getMatchingUnitInclPercentage ( @ Nonnull final String sCSSValue ) { } } | ValueEnforcer . notNull ( sCSSValue , "CSSValue" ) ; // Search units , the ones with the longest names come first
return s_aNameToUnitMap . findFirstValue ( aEntry -> sCSSValue . endsWith ( aEntry . getKey ( ) ) ) ; |
public class Provider { /** * Remove a service previously added using
* { @ link # putService putService ( ) } . The specified service is removed from
* this provider . It will no longer be returned by
* { @ link # getService getService ( ) } and its information will be removed
* from this provider ' s Hashtable .
* < p > Also , if there is a security manager , its
* < code > checkSecurityAccess < / code > method is called with the string
* < code > " removeProviderProperty . " + name < / code > , where < code > name < / code > is
* the provider name , to see if it ' s ok to remove this provider ' s
* properties . If the default implementation of
* < code > checkSecurityAccess < / code > is used ( that is , that method is not
* overriden ) , then this results in a call to the security manager ' s
* < code > checkPermission < / code > method with a
* < code > SecurityPermission ( " removeProviderProperty . " + name ) < / code >
* permission .
* @ param s the Service to be removed
* @ throws SecurityException
* if a security manager exists and its < code > { @ link
* java . lang . SecurityManager # checkSecurityAccess } < / code > method denies
* access to remove this provider ' s properties .
* @ throws NullPointerException if s is null
* @ since 1.5 */
protected synchronized void removeService ( Service s ) { } } | check ( "removeProviderProperty." + name ) ; // if ( debug ! = null ) {
// debug . println ( name + " . removeService ( ) : " + s ) ;
if ( s == null ) { throw new NullPointerException ( ) ; } implRemoveService ( s ) ; |
public class SchemaBuilder { /** * Shortcut for { @ link # createMaterializedView ( CqlIdentifier )
* createMaterializedView ( CqlIdentifier . fromCql ( viewName ) } */
@ NonNull public static CreateMaterializedViewStart createMaterializedView ( @ NonNull String viewName ) { } } | return createMaterializedView ( CqlIdentifier . fromCql ( viewName ) ) ; |
public class SeaGlassLookAndFeel { /** * Initialize the progress bar settings .
* @ param d the UI defaults map . */
private void defineProgressBars ( UIDefaults d ) { } } | // Copied from nimbus
// Initialize ProgressBar
d . put ( "ProgressBar.contentMargins" , new InsetsUIResource ( 0 , 0 , 0 , 0 ) ) ; d . put ( "ProgressBar.States" , "Enabled,Disabled,Indeterminate,Finished" ) ; d . put ( "ProgressBar.tileWhenIndeterminate" , Boolean . TRUE ) ; d . put ( "ProgressBar.paintOutsideClip" , Boolean . TRUE ) ; d . put ( "ProgressBar.rotateText" , Boolean . TRUE ) ; d . put ( "ProgressBar.vertictalSize" , new DimensionUIResource ( 19 , 150 ) ) ; d . put ( "ProgressBar.horizontalSize" , new DimensionUIResource ( 150 , 19 ) ) ; addColor ( d , "ProgressBar[Disabled].textForeground" , "seaGlassDisabledText" , 0.0f , 0.0f , 0.0f , 0 ) ; d . put ( "ProgressBar[Disabled+Indeterminate].progressPadding" , new Integer ( 3 ) ) ; // Seaglass starts below .
d . put ( "progressBarTrackInterior" , Color . WHITE ) ; d . put ( "progressBarTrackBase" , new Color ( 0x4076bf ) ) ; d . put ( "ProgressBar.Indeterminate" , new ProgressBarIndeterminateState ( ) ) ; d . put ( "ProgressBar.Finished" , new ProgressBarFinishedState ( ) ) ; String p = "ProgressBar" ; String c = PAINTER_PREFIX + "ProgressBarPainter" ; d . put ( p + ".cycleTime" , 500 ) ; d . put ( p + ".progressPadding" , new Integer ( 3 ) ) ; d . put ( p + ".trackThickness" , new Integer ( 19 ) ) ; d . put ( p + ".tileWidth" , new Integer ( 24 ) ) ; d . put ( p + ".backgroundFillColor" , Color . WHITE ) ; d . put ( p + ".font" , new DerivedFont ( "defaultFont" , 0.769f , null , null ) ) ; d . put ( p + "[Enabled].backgroundPainter" , new LazyPainter ( c , ProgressBarPainter . Which . BACKGROUND_ENABLED ) ) ; d . put ( p + "[Disabled].backgroundPainter" , new LazyPainter ( c , ProgressBarPainter . Which . BACKGROUND_DISABLED ) ) ; d . put ( p + "[Enabled].foregroundPainter" , new LazyPainter ( c , ProgressBarPainter . Which . FOREGROUND_ENABLED ) ) ; d . put ( p + "[Enabled+Finished].foregroundPainter" , new LazyPainter ( c , ProgressBarPainter . Which . FOREGROUND_ENABLED_FINISHED ) ) ; d . put ( p + "[Enabled+Indeterminate].foregroundPainter" , new LazyPainter ( c , ProgressBarPainter . Which . FOREGROUND_ENABLED_INDETERMINATE ) ) ; d . put ( p + "[Disabled].foregroundPainter" , new LazyPainter ( c , ProgressBarPainter . Which . FOREGROUND_DISABLED ) ) ; d . put ( p + "[Disabled+Finished].foregroundPainter" , new LazyPainter ( c , ProgressBarPainter . Which . FOREGROUND_DISABLED_FINISHED ) ) ; d . put ( p + "[Disabled+Indeterminate].foregroundPainter" , new LazyPainter ( c , ProgressBarPainter . Which . FOREGROUND_DISABLED_INDETERMINATE ) ) ; |
public class Flow { /** * Returns the Flow instance for the { @ link Activity } that owns the given context .
* Note that it is not safe to call this method before the first call to that
* Activity ' s { @ link Activity # onResume ( ) } method in the current Android task . In practice
* this boils down to two rules :
* < ol >
* < li > In views , do not access Flow before { @ link View # onAttachedToWindow ( ) } is called .
* < li > In activities , do not access flow before { @ link Activity # onResume ( ) } is called .
* < / ol > */
@ NonNull public static Flow get ( @ NonNull Context context ) { } } | Flow flow = InternalContextWrapper . getFlow ( context ) ; if ( null == flow ) { throw new IllegalStateException ( "Context was not wrapped with flow. " + "Make sure attachBaseContext was overridden in your main activity" ) ; } return flow ; |
public class ByteArrayBuffer { /** * Ensures that the capacity is at least equal to the specified minimum .
* If the current capacity is less than the argument , then a new internal
* array is allocated with greater capacity . If the { @ code required }
* argument is non - positive , this method takes no action .
* @ param required the minimum required capacity .
* @ since 4.1 */
public void ensureCapacity ( final int required ) { } } | if ( required <= 0 ) { return ; } final int available = this . array . length - this . len ; if ( required > available ) { expand ( this . len + required ) ; } |
public class FileSystem { /** * The src file is under FS , and the dst is on the local disk .
* Copy it from FS control to the local dst name .
* Remove the source afterwards */
public void moveToLocalFile ( Path src , Path dst ) throws IOException { } } | copyToLocalFile ( true , false , src , dst ) ; |
public class TimingInfo { /** * Returns a { @ link TimingInfoFullSupport } based on the given
* start time since epoch in millisecond ,
* and the given start and end time in nanosecond .
* @ param startEpochTimeMilli start time since epoch in millisecond
* @ param startTimeNano start time in nanosecond
* @ param endTimeNano end time in nanosecond */
public static TimingInfo newTimingInfoFullSupport ( long startEpochTimeMilli , long startTimeNano , long endTimeNano ) { } } | return new TimingInfoFullSupport ( Long . valueOf ( startEpochTimeMilli ) , startTimeNano , Long . valueOf ( endTimeNano ) ) ; |
public class NDArrayFragmentHandler { /** * Callback for handling
* fragments of data being read from a log .
* @ param buffer containing the data .
* @ param offset at which the data begins .
* @ param length of the data in bytes .
* @ param header representing the meta data for the data . */
@ Override public void onFragment ( DirectBuffer buffer , int offset , int length , Header header ) { } } | ByteBuffer byteBuffer = buffer . byteBuffer ( ) ; boolean byteArrayInput = false ; if ( byteBuffer == null ) { byteArrayInput = true ; byte [ ] destination = new byte [ length ] ; ByteBuffer wrap = ByteBuffer . wrap ( buffer . byteArray ( ) ) ; wrap . get ( destination , offset , length ) ; byteBuffer = ByteBuffer . wrap ( destination ) . order ( ByteOrder . nativeOrder ( ) ) ; } // only applicable for direct buffers where we don ' t wrap the array
if ( ! byteArrayInput ) { byteBuffer . position ( offset ) ; byteBuffer . order ( ByteOrder . nativeOrder ( ) ) ; } int messageTypeIndex = byteBuffer . getInt ( ) ; if ( messageTypeIndex >= NDArrayMessage . MessageType . values ( ) . length ) throw new IllegalStateException ( "Illegal index on message opType. Likely corrupt message. Please check the serialization of the bytebuffer. Input was bytebuffer: " + byteArrayInput ) ; NDArrayMessage . MessageType messageType = NDArrayMessage . MessageType . values ( ) [ messageTypeIndex ] ; if ( messageType == NDArrayMessage . MessageType . CHUNKED ) { NDArrayMessageChunk chunk = NDArrayMessageChunk . fromBuffer ( byteBuffer , messageType ) ; if ( chunk . getNumChunks ( ) < 1 ) throw new IllegalStateException ( "Found invalid number of chunks " + chunk . getNumChunks ( ) + " on chunk index " + chunk . getChunkIndex ( ) ) ; chunkAccumulator . accumulateChunk ( chunk ) ; log . info ( "Number of chunks " + chunk . getNumChunks ( ) + " and number of chunks " + chunk . getNumChunks ( ) + " for id " + chunk . getId ( ) + " is " + chunkAccumulator . numChunksSoFar ( chunk . getId ( ) ) ) ; if ( chunkAccumulator . allPresent ( chunk . getId ( ) ) ) { NDArrayMessage message = chunkAccumulator . reassemble ( chunk . getId ( ) ) ; ndArrayCallback . onNDArrayMessage ( message ) ; } } else { NDArrayMessage message = NDArrayMessage . fromBuffer ( buffer , offset ) ; ndArrayCallback . onNDArrayMessage ( message ) ; } |
public class CodecInfo { /** * Gets the next doc .
* @ param field
* the field
* @ param previousDocId
* the previous doc id
* @ return the next doc */
public IndexDoc getNextDoc ( String field , int previousDocId ) { } } | if ( fieldReferences . containsKey ( field ) ) { FieldReferences fr = fieldReferences . get ( field ) ; try { if ( previousDocId < 0 ) { return new IndexDoc ( fr . refIndexDoc ) ; } else { int nextDocId = previousDocId + 1 ; IndexInput inIndexDocId = indexInputList . get ( "indexDocId" ) ; ArrayList < MtasTreeHit < ? > > list = CodecSearchTree . advanceMtasTree ( nextDocId , inIndexDocId , fr . refIndexDocId , fr . refIndexDoc ) ; if ( list . size ( ) == 1 ) { IndexInput inDoc = indexInputList . get ( "doc" ) ; inDoc . seek ( list . get ( 0 ) . ref ) ; return new IndexDoc ( inDoc . getFilePointer ( ) ) ; } } } catch ( IOException e ) { log . debug ( e ) ; return null ; } } return null ; |
public class FileService { /** * returns the list of files found in a folder . Does not return hidden files
* , unreadable , folder ' . git '
* @ param sourceFolder
* the source folder to search content
* @ param baseFile
* sub directory from source folder
* @ return file set */
private static Set < String > findFiles ( File sourceFolder , File baseFile ) { } } | Set < String > retval = new HashSet < String > ( ) ; if ( ! sourceFolder . exists ( ) || sourceFolder . isHidden ( ) || ! sourceFolder . isDirectory ( ) || ! sourceFolder . canRead ( ) || isGitMetaDataFolder ( sourceFolder ) ) { return retval ; } for ( File file : sourceFolder . listFiles ( ) ) { if ( file . isDirectory ( ) ) { retval . addAll ( findFiles ( file , sourceFolder ) ) ; } else { retval . add ( file . getAbsolutePath ( ) ) ; } } return retval ; |
public class JdbcRepositories { /** * Initializes the repository definitions .
* @ throws JSONException JSONException */
private static void initRepositoryDefinitions ( ) throws JSONException { } } | final JSONObject jsonObject = Repositories . getRepositoriesDescription ( ) ; if ( null == jsonObject ) { LOGGER . warn ( "Loads repository description [repository.json] failed" ) ; return ; } repositoryDefinitions = new ArrayList < > ( ) ; final JSONArray repositoritArray = jsonObject . getJSONArray ( REPOSITORIES ) ; JSONObject repositoryObject ; JSONObject keyObject ; for ( int i = 0 ; i < repositoritArray . length ( ) ; i ++ ) { repositoryObject = repositoritArray . getJSONObject ( i ) ; final RepositoryDefinition repositoryDefinition = new RepositoryDefinition ( ) ; repositoryDefinitions . add ( repositoryDefinition ) ; repositoryDefinition . setName ( repositoryObject . getString ( NAME ) ) ; repositoryDefinition . setDescription ( repositoryObject . optString ( DESCRIPTION ) ) ; final List < FieldDefinition > keys = new ArrayList < > ( ) ; repositoryDefinition . setKeys ( keys ) ; final JSONArray keysJsonArray = repositoryObject . getJSONArray ( KEYS ) ; FieldDefinition definition ; for ( int j = 0 ; j < keysJsonArray . length ( ) ; j ++ ) { keyObject = keysJsonArray . getJSONObject ( j ) ; definition = fillFieldDefinitionData ( keyObject ) ; keys . add ( definition ) ; } repositoryDefinition . setCharset ( repositoryObject . optString ( CHARSET ) ) ; repositoryDefinition . setCollate ( repositoryObject . optString ( COLLATE ) ) ; } |
public class Mixin { /** * Creates a method lookup that is capable of accessing private members of declaring classes this Mixin factory has
* usually no access to .
* @ param declaringClass
* @ return
* @ throws NoSuchMethodException
* @ throws IllegalAccessException
* @ throws InvocationTargetException
* @ throws InstantiationException */
private static MethodHandles . Lookup lookupIn ( final Class < ? > declaringClass ) { } } | try { final Constructor < MethodHandles . Lookup > constructor = MethodHandles . Lookup . class . getDeclaredConstructor ( Class . class , int . class ) ; constructor . setAccessible ( true ) ; return constructor . newInstance ( declaringClass , MethodHandles . Lookup . PRIVATE ) ; } catch ( NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException e ) { throw new RuntimeException ( e ) ; } |
public class IncludeTag { /** * This is the method called when the JSP interpreter first hits the tag
* associated with this class . This method will firstly determine whether
* the page referenced by the { @ code page } attribute exists . If the
* page doesn ' t exist , this method will throw a { @ code JspException } .
* If the page does exist , this method will hand control over to that JSP
* page .
* @ exception JspException */
public int doStartTag ( ) throws JspException { } } | oldParameters = new HashMap < String , Object > ( ) ; parameterNames = new ArrayList < String > ( ) ; return EVAL_BODY_INCLUDE ; |
public class CompactionJobConfigurator { /** * Converts a top level input path to a group of sub - paths according to user defined granularity .
* This may be required because if upstream application generates many sub - paths but the map - reduce
* job only keeps track of the top level path , after the job is done , we won ' t be able to tell if
* those new arriving sub - paths is processed by previous map - reduce job or not . Hence a better way
* is to pre - define those sub - paths as input paths before we start to run MR . The implementation of
* this method should depend on the data generation granularity controlled by upstream . Here we just
* list the deepest level of containing folder as the smallest granularity .
* @ param path top level directory needs compaction
* @ return A collection of input paths which will participate in map - reduce job */
protected Collection < Path > getGranularInputPaths ( Path path ) throws IOException { } } | boolean appendDelta = this . state . getPropAsBoolean ( MRCompactor . COMPACTION_RENAME_SOURCE_DIR_ENABLED , MRCompactor . DEFAULT_COMPACTION_RENAME_SOURCE_DIR_ENABLED ) ; Set < Path > uncompacted = Sets . newHashSet ( ) ; Set < Path > total = Sets . newHashSet ( ) ; for ( FileStatus fileStatus : FileListUtils . listFilesRecursively ( fs , path ) ) { if ( appendDelta ) { // use source dir suffix to identify the delta input paths
if ( ! fileStatus . getPath ( ) . getParent ( ) . toString ( ) . endsWith ( MRCompactor . COMPACTION_RENAME_SOURCE_DIR_SUFFIX ) ) { uncompacted . add ( fileStatus . getPath ( ) . getParent ( ) ) ; } total . add ( fileStatus . getPath ( ) . getParent ( ) ) ; } else { uncompacted . add ( fileStatus . getPath ( ) . getParent ( ) ) ; } } if ( appendDelta ) { // When the output record count from mr counter doesn ' t match
// the record count from input file names , we prefer file names because
// it will be used to calculate the difference of count in next run .
this . fileNameRecordCount = new InputRecordCountHelper ( this . state ) . calculateRecordCount ( total ) ; log . info ( "{} has total input record count (based on file name) {}" , path , this . fileNameRecordCount ) ; } return uncompacted ; |
public class StatementManager { /** * return a generic Statement for the given ClassDescriptor .
* Never use this method for UPDATE / INSERT / DELETE if you want to use the batch mode . */
public Statement getGenericStatement ( ClassDescriptor cds , boolean scrollable ) throws PersistenceBrokerException { } } | try { return cds . getStatementsForClass ( m_conMan ) . getGenericStmt ( m_conMan . getConnection ( ) , scrollable ) ; } catch ( LookupException e ) { throw new PersistenceBrokerException ( "Used ConnectionManager instance could not obtain a connection" , e ) ; } |
public class DatatypeConverter { /** * Print a date time value .
* @ param value date time value
* @ return string representation */
public static final String printDateTime ( Date value ) { } } | return ( value == null ? null : DATE_FORMAT . get ( ) . format ( value ) ) ; |
public class DefaultAliasedCumulatives { /** * Get the generated constraints .
* @ return a list of constraint that may be empty . */
@ Override public boolean beforeSolve ( ReconfigurationProblem r ) { } } | super . beforeSolve ( r ) ; for ( int i = 0 ; i < aliases . size ( ) ; i ++ ) { int capa = capacities . get ( i ) ; int [ ] alias = aliases . get ( i ) ; int [ ] cUse = cUsages . get ( i ) ; int [ ] dUses = new int [ dUsages . get ( i ) . length ] ; for ( IntVar dUseDim : dUsages . get ( i ) ) { dUses [ i ++ ] = dUseDim . getLB ( ) ; } r . getModel ( ) . post ( new AliasedCumulatives ( alias , new int [ ] { capa } , cHosts , new int [ ] [ ] { cUse } , cEnds , dHosts , new int [ ] [ ] { dUses } , dStarts , associations ) ) ; } return true ; |
public class CmsUserDataDialog { /** * Submits the dialog . < p > */
void submit ( ) { } } | try { // Special user info attributes may have been set since the time the dialog was instantiated ,
// and we don ' t want to overwrite them , so we read the user again .
m_user = m_context . getCms ( ) . readUser ( m_user . getId ( ) ) ; m_form . submit ( m_user , m_context . getCms ( ) , new Runnable ( ) { public void run ( ) { try { m_context . getCms ( ) . writeUser ( m_user ) ; m_context . finish ( Collections . < CmsUUID > emptyList ( ) ) ; m_context . updateUserInfo ( ) ; } catch ( CmsException e ) { } } } ) ; } catch ( CmsException e ) { LOG . error ( "Unable to read user" , e ) ; } |
public class UserPreferences { /** * Enable or disable all known Detectors .
* @ param enable
* true if all detectors should be enabled , false if they should
* all be disabled */
public void enableAllDetectors ( boolean enable ) { } } | detectorEnablementMap . clear ( ) ; Collection < Plugin > allPlugins = Plugin . getAllPlugins ( ) ; for ( Plugin plugin : allPlugins ) { for ( DetectorFactory factory : plugin . getDetectorFactories ( ) ) { detectorEnablementMap . put ( factory . getShortName ( ) , enable ) ; } } |
public class AWSCognitoIdentityProviderClient { /** * Gets the user attributes and metadata for a user .
* @ param getUserRequest
* Represents the request to get information about the user .
* @ return Result of the GetUser operation returned by the service .
* @ throws ResourceNotFoundException
* This exception is thrown when the Amazon Cognito service cannot find the requested resource .
* @ throws InvalidParameterException
* This exception is thrown when the Amazon Cognito service encounters an invalid parameter .
* @ throws NotAuthorizedException
* This exception is thrown when a user is not authorized .
* @ throws TooManyRequestsException
* This exception is thrown when the user has made too many requests for a given operation .
* @ throws PasswordResetRequiredException
* This exception is thrown when a password reset is required .
* @ throws UserNotFoundException
* This exception is thrown when a user is not found .
* @ throws UserNotConfirmedException
* This exception is thrown when a user is not confirmed successfully .
* @ throws InternalErrorException
* This exception is thrown when Amazon Cognito encounters an internal error .
* @ sample AWSCognitoIdentityProvider . GetUser
* @ see < a href = " http : / / docs . aws . amazon . com / goto / WebAPI / cognito - idp - 2016-04-18 / GetUser " target = " _ top " > AWS API
* Documentation < / a > */
@ Override public GetUserResult getUser ( GetUserRequest request ) { } } | request = beforeClientExecution ( request ) ; return executeGetUser ( request ) ; |
public class AbstractUnitConverter { /** * Returns the components screen resolution or the default screen resolution if the component is
* null or has no toolkit assigned yet .
* @ param c the component to ask for a toolkit
* @ return the component ' s screen resolution */
protected int getScreenResolution ( Component c ) { } } | if ( c == null ) { return getDefaultScreenResolution ( ) ; } Toolkit toolkit = c . getToolkit ( ) ; return toolkit != null ? toolkit . getScreenResolution ( ) : getDefaultScreenResolution ( ) ; |
public class BitMatrix { /** * < p > Sets a square region of the bit matrix to true . < / p >
* @ param left The horizontal position to begin at ( inclusive )
* @ param top The vertical position to begin at ( inclusive )
* @ param width The width of the region
* @ param height The height of the region */
public void setRegion ( int left , int top , int width , int height ) { } } | if ( top < 0 || left < 0 ) { throw new IllegalArgumentException ( "Left and top must be nonnegative" ) ; } if ( height < 1 || width < 1 ) { throw new IllegalArgumentException ( "Height and width must be at least 1" ) ; } int right = left + width ; int bottom = top + height ; if ( bottom > this . height || right > this . width ) { throw new IllegalArgumentException ( "The region must fit inside the matrix" ) ; } for ( int y = top ; y < bottom ; y ++ ) { int offset = y * rowSize ; for ( int x = left ; x < right ; x ++ ) { bits [ offset + ( x / 32 ) ] |= 1 << ( x & 0x1f ) ; } } |
public class AssetsFeature { /** * < p > lookupAsset . < / p >
* @ param name a { @ link java . lang . String } object .
* @ param file a { @ link java . lang . String } object .
* @ return a { @ link java . net . URL } object . */
public static URL lookupAsset ( String name , String file ) { } } | URL url = null ; if ( name . startsWith ( "/" ) ) { name = name . substring ( 1 ) ; } if ( name . endsWith ( "/" ) ) { name = name . substring ( 0 , name . lastIndexOf ( "/" ) ) ; } if ( name . equals ( "" ) ) { name = ROOT_MAPPING_PATH ; } if ( file . startsWith ( "/" ) ) { file = file . substring ( 1 ) ; } String [ ] dirs = assetsMap . get ( name ) ; if ( dirs != null ) { for ( String dir : dirs ) { File f = FileUtils . getFile ( dir , file ) ; if ( f . exists ( ) && f . isFile ( ) ) { try { url = f . getAbsoluteFile ( ) . toURI ( ) . toURL ( ) ; } catch ( MalformedURLException e ) { } } if ( url == null ) { url = IOUtils . getResource ( dir + file ) ; } if ( url != null ) { break ; } } } return url ; |
public class ConcurrentNodeMemories { /** * Checks if a memory does not exists for the given node and
* creates it . */
private Memory createNodeMemory ( MemoryFactory node , InternalWorkingMemory wm ) { } } | try { this . lock . lock ( ) ; // need to try again in a synchronized code block to make sure
// it was not created yet
Memory memory = this . memories . get ( node . getMemoryId ( ) ) ; if ( memory == null ) { memory = node . createMemory ( this . kBase . getConfiguration ( ) , wm ) ; if ( ! this . memories . compareAndSet ( node . getMemoryId ( ) , null , memory ) ) { memory = this . memories . get ( node . getMemoryId ( ) ) ; } } return memory ; } finally { this . lock . unlock ( ) ; } |
public class Store { /** * { @ inheritDoc } */
@ Override protected void setLinkProperty ( final UUID _linkTypeUUID , final long _toId , final UUID _toTypeUUID , final String _toName ) throws EFapsException { } } | if ( _linkTypeUUID . equals ( CIDB . Store2Resource . uuid ) ) { this . resource = _toName ; loadResourceProperties ( _toId ) ; } super . setLinkProperty ( _linkTypeUUID , _toId , _toTypeUUID , _toName ) ; |
public class CmsPrincipal { /** * Utility function to read a principal by its id from the OpenCms database using the
* provided OpenCms user context . < p >
* @ param cms the OpenCms user context to use when reading the principal
* @ param name the name of the principal to read
* @ return the principal read from the OpenCms database
* @ throws CmsException in case the principal could not be read */
public static I_CmsPrincipal readPrincipal ( CmsObject cms , String name ) throws CmsException { } } | try { // first try to read the principal as a user
return cms . readUser ( name ) ; } catch ( CmsException exc ) { // assume user does not exist
} try { // now try to read the principal as a group
return cms . readGroup ( name ) ; } catch ( CmsException exc ) { // assume group does not exist
} // invalid principal name was given
throw new CmsDbEntryNotFoundException ( Messages . get ( ) . container ( Messages . ERR_INVALID_PRINCIPAL_1 , name ) ) ; |
public class SuggestionsAdapter { /** * Gets the activity or application icon for an activity .
* @ param component Name of an activity .
* @ return A drawable , or { @ code null } if neither the acitivy or the application
* have an icon set . */
private Drawable getActivityIcon ( ComponentName component ) { } } | PackageManager pm = mContext . getPackageManager ( ) ; final ActivityInfo activityInfo ; try { activityInfo = pm . getActivityInfo ( component , PackageManager . GET_META_DATA ) ; } catch ( NameNotFoundException ex ) { Log . w ( LOG_TAG , ex . toString ( ) ) ; return null ; } int iconId = activityInfo . getIconResource ( ) ; if ( iconId == 0 ) return null ; String pkg = component . getPackageName ( ) ; Drawable drawable = pm . getDrawable ( pkg , iconId , activityInfo . applicationInfo ) ; if ( drawable == null ) { Log . w ( LOG_TAG , "Invalid icon resource " + iconId + " for " + component . flattenToShortString ( ) ) ; return null ; } return drawable ; |
public class InboundCookiesHandler { /** * Retrieves the value of a cookie with a given name from a HttpServerExchange
* @ param exchange The exchange containing the cookie
* @ param cookieName The name of the cookie
* @ return The value of the cookie or null if none found */
private String getCookieValue ( HttpServerExchange exchange , String cookieName ) { } } | String value = null ; Map < String , Cookie > requestCookies = exchange . getRequestCookies ( ) ; if ( requestCookies != null ) { Cookie cookie = exchange . getRequestCookies ( ) . get ( cookieName ) ; if ( cookie != null ) { value = cookie . getValue ( ) ; } } return value ; |
public class LaJobRunner { protected long showRunning ( LaJobRuntime runtime ) { } } | JobNoticeLog . log ( runtime . getNoticeLogLevel ( ) , ( ) -> buildRunningJobLogMessage ( runtime ) ) ; if ( noticeLogHook != null ) { noticeLogHook . hookRunning ( runtime , buildRunningJobLogMessage ( runtime ) ) ; } return System . currentTimeMillis ( ) ; |
public class CSVParserBuilder { /** * Construct parser using current setting
* @ return CSV Parser */
public CSVParser < T > build ( ) { } } | return subsetView == null ? new QuickCSVParser < T , K > ( bufferSize , metadata , recordMapper , charset ) : new QuickCSVParser < T , K > ( bufferSize , metadata , recordWithHeaderMapper , subsetView , charset ) ; |
public class ST_Expand { /** * Expands a geometry ' s envelope by the given delta X and delta Y . Both
* positive and negative distances are supported .
* @ param geometry the input geometry
* @ param deltaX the distance to expand the envelope along the X axis
* @ param deltaY the distance to expand the envelope along the Y axis
* @ return the expanded geometry */
public static Geometry expand ( Geometry geometry , double deltaX , double deltaY ) { } } | if ( geometry == null ) { return null ; } Envelope env = geometry . getEnvelopeInternal ( ) ; // As the time of writing Envelope . expand is buggy with negative parameters
double minX = env . getMinX ( ) - deltaX ; double maxX = env . getMaxX ( ) + deltaX ; double minY = env . getMinY ( ) - deltaY ; double maxY = env . getMaxY ( ) + deltaY ; Envelope expandedEnvelope = new Envelope ( minX < maxX ? minX : ( env . getMaxX ( ) - env . getMinX ( ) ) / 2 + env . getMinX ( ) , minX < maxX ? maxX : ( env . getMaxX ( ) - env . getMinX ( ) ) / 2 + env . getMinX ( ) , minY < maxY ? minY : ( env . getMaxY ( ) - env . getMinY ( ) ) / 2 + env . getMinY ( ) , minY < maxY ? maxY : ( env . getMaxY ( ) - env . getMinY ( ) ) / 2 + env . getMinY ( ) ) ; return geometry . getFactory ( ) . toGeometry ( expandedEnvelope ) ; |
public class HttpContextManager { /** * Initialize the Http Context . This will set up current context for
* request , response , session ( resolved from cookie ) and flash ( resolved
* from cookie )
* @ param request the http request
* @ param response the http response */
public static void init ( H . Request request , H . Response response ) { } } | H . Request . current ( request ) ; H . Response . current ( response ) ; resolveSession ( request ) ; resolveFlash ( request ) ; |
public class PacketCapturesInner { /** * Query the status of a running packet capture session .
* @ param resourceGroupName The name of the resource group .
* @ param networkWatcherName The name of the Network Watcher resource .
* @ param packetCaptureName The name given to the packet capture session .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the observable for the request */
public Observable < PacketCaptureQueryStatusResultInner > getStatusAsync ( String resourceGroupName , String networkWatcherName , String packetCaptureName ) { } } | return getStatusWithServiceResponseAsync ( resourceGroupName , networkWatcherName , packetCaptureName ) . map ( new Func1 < ServiceResponse < PacketCaptureQueryStatusResultInner > , PacketCaptureQueryStatusResultInner > ( ) { @ Override public PacketCaptureQueryStatusResultInner call ( ServiceResponse < PacketCaptureQueryStatusResultInner > response ) { return response . body ( ) ; } } ) ; |
public class StringUtil { /** * Converts the specified byte array into a hexadecimal value . */
public static String toHexString ( byte [ ] src , int offset , int length ) { } } | return toHexString ( new StringBuilder ( length << 1 ) , src , offset , length ) . toString ( ) ; |
public class BeanHelperCache { /** * Creates a BeanHelper and writes an interface containing its instance . Also , recursively creates
* any BeanHelpers on its constrained properties . ( Public for testing . )
* @ param clazz class type
* @ param logger tree logger to use
* @ param context generator context
* @ return bean helper instance
* @ throws UnableToCompleteException if generation can not be done */
public BeanHelper createHelper ( final Class < ? > clazz , final TreeLogger logger , final GeneratorContext context ) throws UnableToCompleteException { } } | final JClassType beanType = context . getTypeOracle ( ) . findType ( clazz . getCanonicalName ( ) ) ; return doCreateHelper ( clazz , beanType , logger , context ) ; |
public class Base64VLQ { /** * Writes a VLQ encoded value to the provide appendable .
* @ throws IOException */
public static void encode ( Appendable out , int value ) throws IOException { } } | value = toVLQSigned ( value ) ; do { int digit = value & VLQ_BASE_MASK ; value >>>= VLQ_BASE_SHIFT ; if ( value > 0 ) { digit |= VLQ_CONTINUATION_BIT ; } out . append ( Base64 . toBase64 ( digit ) ) ; } while ( value > 0 ) ; |
public class Stream { /** * Creates a concatenated stream whose elements are all the elements of the first stream followed by all the elements of the second stream .
* @ param a first stream
* @ param b second stream
* @ param < T > type of elements
* @ return a stream concatenating first and second */
@ SuppressWarnings ( "unchecked" ) public static < T > Stream < T > concat ( Stream < ? extends T > a , Stream < ? extends T > b ) { } } | return new Stream ( Iterators . concat ( a . iterator , b . iterator ) ) ; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.