signature stringlengths 43 39.1k | implementation stringlengths 0 450k |
|---|---|
public class RectifyFundamental { /** * Apply a rotation such that the epipole is equal to [ f , 0,1] */
static SimpleMatrix rotateEpipole ( Point3D_F64 epipole , int x0 , int y0 ) { } } | // compute rotation which will set
// x * sin ( theta ) + y * cos ( theta ) = 0
double x = epipole . x / epipole . z - x0 ; double y = epipole . y / epipole . z - y0 ; double theta = Math . atan2 ( - y , x ) ; double c = Math . cos ( theta ) ; double s = Math . sin ( theta ) ; SimpleMatrix R = new SimpleMatrix ( 3 , 3 ) ; R . setRow ( 0 , 0 , c , - s ) ; R . setRow ( 1 , 0 , s , c ) ; R . set ( 2 , 2 , 1 ) ; return R ; |
public class Transform1D { /** * Replies the path used by this transformation .
* @ return the path . */
@ Pure public List < S > getPath ( ) { } } | if ( this . path == null ) { return Collections . emptyList ( ) ; } return Collections . unmodifiableList ( this . path ) ; |
public class DirectoryRosterStore { /** * Opens a roster store .
* @ param baseDir
* The directory containing the roster store .
* @ return A { @ link DirectoryRosterStore } instance if successful ,
* < code > null < / code > else . */
public static DirectoryRosterStore open ( final File baseDir ) { } } | DirectoryRosterStore store = new DirectoryRosterStore ( baseDir ) ; String s = FileUtils . readFile ( store . getVersionFile ( ) ) ; if ( s != null && s . startsWith ( STORE_ID + "\n" ) ) { return store ; } else { return null ; } |
public class SimpleStringTargetProviderImpl { /** * Set the permission targets for this provider .
* @ param targets collection of targets */
public void setTargets ( Collection < IPermissionTarget > targets ) { } } | // clear out any existing targets
targetMap . clear ( ) ; // add each target to the internal map and index it by the target key
for ( IPermissionTarget target : targets ) { targetMap . put ( target . getKey ( ) , target ) ; } |
public class StringHelper { /** * Count the number of occurrences of sSearch within sText ignoring case .
* @ param sText
* The text to search in . May be < code > null < / code > .
* @ param sSearch
* The text to search for . May be < code > null < / code > .
* @ param aSortLocale
* The locale to be used for case unifying .
* @ return A non - negative number of occurrences . */
@ Nonnegative public static int getOccurrenceCountIgnoreCase ( @ Nullable final String sText , @ Nullable final String sSearch , @ Nonnull final Locale aSortLocale ) { } } | return sText != null && sSearch != null ? getOccurrenceCount ( sText . toLowerCase ( aSortLocale ) , sSearch . toLowerCase ( aSortLocale ) ) : 0 ; |
public class GitController { /** * Issue information in a project */
@ RequestMapping ( value = "{projectId}/issue-info/{issue}" , method = RequestMethod . GET ) public Resource < OntrackGitIssueInfo > issueProjectInfo ( @ PathVariable ID projectId , @ PathVariable String issue ) { } } | return Resource . of ( gitService . getIssueProjectInfo ( projectId , issue ) , uri ( on ( getClass ( ) ) . issueProjectInfo ( projectId , issue ) ) ) . withView ( Build . class ) ; |
public class SlackApi { /** * See https : / / api . slack . com / docs / oauth . */
public HttpUrl authorizeUrl ( String scopes , HttpUrl redirectUrl , ByteString state , String team ) { } } | HttpUrl . Builder builder = baseUrl . newBuilder ( "/oauth/authorize" ) . addQueryParameter ( "client_id" , clientId ) . addQueryParameter ( "scope" , scopes ) . addQueryParameter ( "redirect_uri" , redirectUrl . toString ( ) ) . addQueryParameter ( "state" , state . base64 ( ) ) ; if ( team != null ) { builder . addQueryParameter ( "team" , team ) ; } return builder . build ( ) ; |
public class NetworkMessageEntity { /** * Add an action .
* @ param element The action type .
* @ param value The action value . */
public void addAction ( M element , byte value ) { } } | actions . put ( element , Byte . valueOf ( value ) ) ; |
public class ClassLoaderUtils { /** * Locates the resource with the specified name . For Java 2 callers , the
* current thread ' s context class loader is preferred , falling back on the
* class loader of the caller when the current thread ' s context is not set ,
* or the caller is pre Java 2 . If the callerClassLoader is null , then
* fall back on the system class loader .
* @ param name the name of the resource
* @ param callerClassLoader the calling class loader context
* @ return the resulting < code > URL < / code > object */
public static URL getResource ( String name , ClassLoader callerClassLoader ) { } } | _checkResourceName ( name ) ; URL url = null ; ClassLoader loader = getContextClassLoader ( ) ; if ( loader != null ) { url = loader . getResource ( name ) ; } if ( url == null ) { if ( callerClassLoader != null ) { url = callerClassLoader . getResource ( name ) ; } else { url = ClassLoader . getSystemResource ( name ) ; } } return url ; |
public class GetInventoryRequest { /** * Returns counts of inventory types based on one or more expressions . For example , if you aggregate by using an
* expression that uses the < code > AWS : InstanceInformation . PlatformType < / code > type , you can see a count of how many
* Windows and Linux instances exist in your inventoried fleet .
* < b > NOTE : < / b > This method appends the values to the existing list ( if any ) . Use
* { @ link # setAggregators ( java . util . Collection ) } or { @ link # withAggregators ( java . util . Collection ) } if you want to
* override the existing values .
* @ param aggregators
* Returns counts of inventory types based on one or more expressions . For example , if you aggregate by using
* an expression that uses the < code > AWS : InstanceInformation . PlatformType < / code > type , you can see a count of
* how many Windows and Linux instances exist in your inventoried fleet .
* @ return Returns a reference to this object so that method calls can be chained together . */
public GetInventoryRequest withAggregators ( InventoryAggregator ... aggregators ) { } } | if ( this . aggregators == null ) { setAggregators ( new com . amazonaws . internal . SdkInternalList < InventoryAggregator > ( aggregators . length ) ) ; } for ( InventoryAggregator ele : aggregators ) { this . aggregators . add ( ele ) ; } return this ; |
public class FileUtil { /** * 创建文件夹 , 如果目标存在则删除 */
public static File createDir ( String path , boolean isHidden ) throws IOException { } } | File file = new File ( path ) ; deleteIfExists ( file ) ; File newFile = new File ( path ) ; newFile . mkdir ( ) ; if ( OsUtil . isWindows ( ) ) { Files . setAttribute ( newFile . toPath ( ) , "dos:hidden" , isHidden ) ; } return file ; |
public class VarInt { /** * Encodes an integer in a variable - length encoding , 7 bits per byte , and writes it to the given
* OutputStream .
* @ param v the value to encode
* @ param outputStream the OutputStream to write to */
public static void putVarInt ( int v , OutputStream outputStream ) throws IOException { } } | byte [ ] bytes = new byte [ varIntSize ( v ) ] ; putVarInt ( v , bytes , 0 ) ; outputStream . write ( bytes ) ; |
public class RSS090Generator { /** * Populates the given channel with parsed data from the ROME element that holds the channel
* data .
* @ param channel the channel into which parsed data will be added .
* @ param eChannel the XML element that holds the data for the channel . */
protected void populateChannel ( final Channel channel , final Element eChannel ) { } } | final String title = channel . getTitle ( ) ; if ( title != null ) { eChannel . addContent ( generateSimpleElement ( "title" , title ) ) ; } final String link = channel . getLink ( ) ; if ( link != null ) { eChannel . addContent ( generateSimpleElement ( "link" , link ) ) ; } final String description = channel . getDescription ( ) ; if ( description != null ) { eChannel . addContent ( generateSimpleElement ( "description" , description ) ) ; } |
public class Caster { /** * cast a Object to a UUID
* @ param o Object to cast
* @ return casted Query Object
* @ throws PageException */
public static Object toUUId ( Object o ) throws PageException { } } | String str = toString ( o ) ; if ( ! Decision . isUUId ( str ) ) throw new ExpressionException ( "can't cast [" + str + "] to uuid value" ) ; return str ; |
public class AetherFactories { /** * system prop takes precedence over env var */
private static String fromSystemPropOrEnv ( String prop ) { } } | String resolvedProp = System . getProperty ( prop ) ; if ( StringUtils . hasText ( resolvedProp ) ) { return resolvedProp ; } return System . getenv ( prop ) ; |
public class MultiPathImpl { /** * Reviewed vs . Native Jan 11 , 2011 */
protected void _initPathStartPoint ( ) { } } | _touch ( ) ; if ( m_moveToPoint == null ) m_moveToPoint = new Point ( m_description ) ; else m_moveToPoint . assignVertexDescription ( m_description ) ; |
public class GenericsResolutionUtils { /** * Analyze class hierarchy and resolve actual generic values for all composing types . Root type
* generics must be specified directly .
* If generics are known for some middle type , then they would be used " as is " instead of generics tracked
* from root . Also , known generics will be used for lower hierarchy resolution .
* @ param type class to analyze
* @ param rootGenerics resolved root type generics ( including owner type generics ) ; must not be null !
* @ param knownGenerics type generics known before analysis ( some middle class generics are known ) and
* could contain possible outer generics ( types for sure not included in resolving type
* hierarchy ) ; must not be null , but could be empty map
* @ param ignoreClasses classes to ignore during analysis
* @ return resolved generics for all types in class hierarchy */
public static Map < Class < ? > , LinkedHashMap < String , Type > > resolve ( final Class < ? > type , final LinkedHashMap < String , Type > rootGenerics , final Map < Class < ? > , LinkedHashMap < String , Type > > knownGenerics , final List < Class < ? > > ignoreClasses ) { } } | final Map < Class < ? > , LinkedHashMap < String , Type > > generics = new HashMap < Class < ? > , LinkedHashMap < String , Type > > ( ) ; generics . put ( type , rootGenerics ) ; try { analyzeType ( generics , type , knownGenerics , ignoreClasses ) ; } catch ( Exception ex ) { throw new GenericsResolutionException ( type , rootGenerics , knownGenerics , ex ) ; } return generics ; |
public class StreamTransformation { /** * Sets the parallelism of this { @ code StreamTransformation } .
* @ param parallelism The new parallelism to set on this { @ code StreamTransformation } . */
public void setParallelism ( int parallelism ) { } } | Preconditions . checkArgument ( parallelism > 0 || parallelism == ExecutionConfig . PARALLELISM_DEFAULT , "The parallelism must be at least one, or ExecutionConfig.PARALLELISM_DEFAULT (use system default)." ) ; this . parallelism = parallelism ; |
public class AndroidEventBuilderHelper { /** * Check whether the application has internet access at a point in time .
* @ param ctx Android application context
* @ return true if the application has internet access */
protected static boolean isConnected ( Context ctx ) { } } | ConnectivityManager connectivityManager = ( ConnectivityManager ) ctx . getSystemService ( Context . CONNECTIVITY_SERVICE ) ; NetworkInfo activeNetworkInfo = connectivityManager . getActiveNetworkInfo ( ) ; return activeNetworkInfo != null && activeNetworkInfo . isConnected ( ) ; |
public class TextUtils { /** * Removes empty spans from the < code > spans < / code > array .
* When parsing a Spanned using { @ link Spanned # nextSpanTransition ( int , int , Class ) } , empty spans
* will ( correctly ) create span transitions , and calling getSpans on a slice of text bounded by
* one of these transitions will ( correctly ) include the empty overlapping span .
* However , these empty spans should not be taken into account when layouting or rendering the
* string and this method provides a way to filter getSpans ' results accordingly .
* @ param spans A list of spans retrieved using { @ link Spanned # getSpans ( int , int , Class ) } from
* the < code > spanned < / code >
* @ param spanned The Spanned from which spans were extracted
* @ return A subset of spans where empty spans ( { @ link Spanned # getSpanStart ( Object ) } = =
* { @ link Spanned # getSpanEnd ( Object ) } have been removed . The initial order is preserved
* @ hide */
@ SuppressWarnings ( "unchecked" ) public static < T > T [ ] removeEmptySpans ( T [ ] spans , Spanned spanned , Class < T > klass ) { } } | T [ ] copy = null ; int count = 0 ; for ( int i = 0 ; i < spans . length ; i ++ ) { final T span = spans [ i ] ; final int start = spanned . getSpanStart ( span ) ; final int end = spanned . getSpanEnd ( span ) ; if ( start == end ) { if ( copy == null ) { copy = ( T [ ] ) Array . newInstance ( klass , spans . length - 1 ) ; System . arraycopy ( spans , 0 , copy , 0 , i ) ; count = i ; } } else { if ( copy != null ) { copy [ count ] = span ; count ++ ; } } } if ( copy != null ) { T [ ] result = ( T [ ] ) Array . newInstance ( klass , count ) ; System . arraycopy ( copy , 0 , result , 0 , count ) ; return result ; } else { return spans ; } |
public class GraphCsvReader { /** * Creates a Graph from CSV input with vertex values and edge values .
* The vertex values are specified through a vertices input file or a user - defined map function .
* @ param vertexKey the type of the vertex IDs
* @ param vertexValue the type of the vertex values
* @ param edgeValue the type of the edge values
* @ return a Graph with vertex and edge values . */
@ SuppressWarnings ( "unchecked" ) public < K , VV , EV > Graph < K , VV , EV > types ( Class < K > vertexKey , Class < VV > vertexValue , Class < EV > edgeValue ) { } } | if ( edgeReader == null ) { throw new RuntimeException ( "The edge input file cannot be null!" ) ; } DataSet < Tuple3 < K , K , EV > > edges = edgeReader . types ( vertexKey , vertexKey , edgeValue ) ; // the vertex value can be provided by an input file or a user - defined mapper
if ( vertexReader != null ) { DataSet < Tuple2 < K , VV > > vertices = vertexReader . types ( vertexKey , vertexValue ) . name ( GraphCsvReader . class . getName ( ) ) ; return Graph . fromTupleDataSet ( vertices , edges , executionContext ) ; } else if ( mapper != null ) { return Graph . fromTupleDataSet ( edges , ( MapFunction < K , VV > ) mapper , executionContext ) ; } else { throw new RuntimeException ( "Vertex values have to be specified through a vertices input file" + "or a user-defined map function." ) ; } |
public class KeyManager { /** * Generates a secret key .
* @ return a SecretKey
* @ throws NoSuchAlgorithmException if the algorithm cannot be found
* @ since 1.0.0 */
public SecretKey generateSecretKey ( ) throws NoSuchAlgorithmException { } } | final KeyGenerator keyGen = KeyGenerator . getInstance ( "AES" ) ; final SecureRandom random = SecureRandom . getInstance ( "SHA1PRNG" ) ; keyGen . init ( 256 , random ) ; return this . secretKey = keyGen . generateKey ( ) ; |
public class ProductInfo { /** * Returns the product info printout .
* @ return The product info printout */
public static String getProductInfoPrintout ( ) { } } | // read properties
Properties properties = LibraryConfigurationLoader . readInternalConfiguration ( ) ; // get values
String name = properties . getProperty ( "org.fax4j.product.name" ) ; String version = properties . getProperty ( "org.fax4j.product.version" ) ; // init buffer
StringBuilder buffer = new StringBuilder ( ) ; buffer . append ( name ) ; buffer . append ( " library." ) ; buffer . append ( Logger . SYSTEM_EOL ) ; buffer . append ( "Version: " ) ; buffer . append ( version ) ; // get text
String text = buffer . toString ( ) ; return text ; |
public class CrossChunkCodeMotion { /** * Is the expression of the form { @ code x instanceof Ref } ?
* @ param expression
* @ param reference Ref node must be equivalent to this node */
private boolean isInstanceofFor ( Node expression , Node reference ) { } } | return expression . isInstanceOf ( ) && expression . getLastChild ( ) . isEquivalentTo ( reference ) ; |
public class ProcessConsolePageParticipant { /** * ( non - Javadoc )
* @ see org . eclipse . ui . console . IConsolePageParticipant # activated ( ) */
public void activated ( ) { } } | // add EOF submissions
IPageSite site = fPage . getSite ( ) ; if ( fActivatedContext == null && fActivatedHandler == null ) { IHandlerService handlerService = ( IHandlerService ) site . getService ( IHandlerService . class ) ; IContextService contextService = ( IContextService ) site . getService ( IContextService . class ) ; fActivatedContext = contextService . activateContext ( fContextId ) ; fActivatedHandler = handlerService . activateHandler ( "org.eclipse.debug.ui.commands.eof" , fEOFHandler ) ; // $ NON - NLS - 1 $
} |
public class PositionManager { /** * Return true if the passed in node or any downstream ( higher index ) siblings < strong > relative
* to its destination location < / strong > have moveAllowed = " false " . */
private static boolean isNotReparentable ( NodeInfo ni , Element compViewParent , Element positionSet ) { } } | // This one is easy - - can ' t re - parent a node with dlm : moveAllowed = false
if ( ni . getNode ( ) . getAttribute ( Constants . ATT_MOVE_ALLOWED ) . equals ( "false" ) ) { return true ; } try { /* * Annoying to do in Java , but we need to find our own placeholder
* element in the positionSet */
final XPathFactory xpathFactory = XPathFactory . newInstance ( ) ; final XPath xpath = xpathFactory . newXPath ( ) ; final String findPlaceholderXpath = ".//*[local-name()='position' and @name='" + ni . getId ( ) + "']" ; final XPathExpression findPlaceholder = xpath . compile ( findPlaceholderXpath ) ; final NodeList findPlaceholderList = ( NodeList ) findPlaceholder . evaluate ( positionSet , XPathConstants . NODESET ) ; switch ( findPlaceholderList . getLength ( ) ) { case 0 : LOG . warn ( "Node not found for XPathExpression=\"" + findPlaceholderXpath + "\" in positionSet=" + XmlUtilitiesImpl . toString ( positionSet ) ) ; return true ; case 1 : // This is healthy
break ; default : LOG . warn ( "More than one node found for XPathExpression=\"" + findPlaceholderXpath + "\" in positionSet=" + XmlUtilitiesImpl . toString ( positionSet ) ) ; return true ; } final Element placeholder = ( Element ) findPlaceholderList . item ( 0 ) ; // At last
for ( Element nextPlaceholder = ( Element ) placeholder . getNextSibling ( ) ; // Start with the next dlm : position
// element after placeholder
nextPlaceholder != null ; // As long as we have a placeholder to look at
nextPlaceholder = ( Element ) nextPlaceholder . getNextSibling ( ) ) { // Advance to the next placeholder
if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Considering whether node ''" + ni . getId ( ) + "' is Reparentable; subsequent sibling is: " + nextPlaceholder . getAttribute ( "name" ) ) ; } /* * Next task : we have to find the non - placeholder representation of
* the nextSiblingPlaceholder within the compViewParent */
final String unmaskPlaceholderXpath = ".//*[@ID='" + nextPlaceholder . getAttribute ( "name" ) + "']" ; final XPathExpression unmaskPlaceholder = xpath . compile ( unmaskPlaceholderXpath ) ; final NodeList unmaskPlaceholderList = ( NodeList ) unmaskPlaceholder . evaluate ( compViewParent , XPathConstants . NODESET ) ; switch ( unmaskPlaceholderList . getLength ( ) ) { case 0 : // Not a problem ; the nextSiblingPlaceholder also refers
// to a node that has been moved to this context ( afaik )
continue ; case 1 : final Element nextSibling = ( Element ) unmaskPlaceholderList . item ( 0 ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Considering whether node ''" + ni . getId ( ) + "' is Reparentable; subsequent sibling '" + nextSibling . getAttribute ( "ID" ) + "' has dlm:moveAllowed=" + ! nextSibling . getAttribute ( Constants . ATT_MOVE_ALLOWED ) . equals ( "false" ) ) ; } // Need to perform some checks . . .
if ( nextSibling . getAttribute ( Constants . ATT_MOVE_ALLOWED ) . equals ( "false" ) ) { /* * The following check is a bit strange ; it seems to verify
* that the current NodeInfo and the nextSibling come from the
* same fragment . If they don ' t , the re - parenting is allowable .
* I believe this check could only be unsatisfied in the case
* of tabs . */
Precedence p = Precedence . newInstance ( nextSibling . getAttribute ( Constants . ATT_FRAGMENT ) ) ; if ( ni . getPrecedence ( ) . isEqualTo ( p ) ) { return true ; } } break ; default : LOG . warn ( "More than one node found for XPathExpression=\"" + unmaskPlaceholderXpath + "\" in compViewParent" ) ; return true ; } } } catch ( XPathExpressionException xpe ) { throw new RuntimeException ( "Failed to evaluate XPATH" , xpe ) ; } return false ; // Re - parenting is " not disallowed " ( double - negative less readable ) |
public class AfplibPackageImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
public EEnum getIOBObjType ( ) { } } | if ( iobObjTypeEEnum == null ) { iobObjTypeEEnum = ( EEnum ) EPackage . Registry . INSTANCE . getEPackage ( AfplibPackage . eNS_URI ) . getEClassifiers ( ) . get ( 38 ) ; } return iobObjTypeEEnum ; |
public class Queue { /** * Gets the Queues default Output . Will ask the parent Queue
* to get its default Output if this Queue doesn ' t have one . */
Output getDefaultOutput ( ) { } } | if ( default_output != null ) return default_output ; if ( parent_queue != null ) return parent_queue . getDefaultOutput ( ) ; return null ; |
public class DriverLoader { /** * Loads the specified class using the supplied class loader and registers
* the driver with the driver manager .
* @ param className the fully qualified name of the desired class
* @ param loader the class loader to use when loading the driver
* @ return the loaded Driver
* @ throws DriverLoadException thrown if the driver cannot be loaded */
private static Driver load ( String className , ClassLoader loader ) throws DriverLoadException { } } | try { final Class < ? > c = Class . forName ( className , true , loader ) ; // final Class c = loader . loadClass ( className ) ;
final Driver driver = ( Driver ) c . getDeclaredConstructor ( ) . newInstance ( ) ; // TODO add usage count so we don ' t de - register a driver that is in use .
final Driver shim = new DriverShim ( driver ) ; // using the DriverShim to get around the fact that the DriverManager won ' t register a driver not in the base class path
DriverManager . registerDriver ( shim ) ; return shim ; } catch ( ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException | NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException ex ) { final String msg = String . format ( "Unable to load database driver '%s'" , className ) ; LOGGER . debug ( msg , ex ) ; throw new DriverLoadException ( msg , ex ) ; } |
public class CommonHelper { /** * Verify that a String is not blank otherwise throw a { @ link TechnicalException } .
* @ param name name if the string
* @ param value value of the string
* @ param msg an expanatory message */
public static void assertNotBlank ( final String name , final String value , final String msg ) { } } | assertTrue ( ! isBlank ( value ) , name + " cannot be blank" + ( msg != null ? ": " + msg : "" ) ) ; |
public class AnnotationTypeRequiredMemberWriterImpl { /** * { @ inheritDoc } */
public Content getMemberSummaryHeader ( TypeElement typeElement , Content memberSummaryTree ) { } } | memberSummaryTree . addContent ( HtmlConstants . START_OF_ANNOTATION_TYPE_REQUIRED_MEMBER_SUMMARY ) ; Content memberTree = writer . getMemberTreeHeader ( ) ; writer . addSummaryHeader ( this , typeElement , memberTree ) ; return memberTree ; |
public class AWSBackupClient { /** * Returns detailed information about recovery points of the type specified by a resource Amazon Resource Name
* ( ARN ) .
* @ param listRecoveryPointsByResourceRequest
* @ return Result of the ListRecoveryPointsByResource operation returned by the service .
* @ throws ResourceNotFoundException
* A resource that is required for the action doesn ' t exist .
* @ throws InvalidParameterValueException
* Indicates that something is wrong with a parameter ' s value . For example , the value is out of range .
* @ throws MissingParameterValueException
* Indicates that a required parameter is missing .
* @ throws ServiceUnavailableException
* The request failed due to a temporary failure of the server .
* @ sample AWSBackup . ListRecoveryPointsByResource
* @ see < a href = " http : / / docs . aws . amazon . com / goto / WebAPI / backup - 2018-11-15 / ListRecoveryPointsByResource "
* target = " _ top " > AWS API Documentation < / a > */
@ Override public ListRecoveryPointsByResourceResult listRecoveryPointsByResource ( ListRecoveryPointsByResourceRequest request ) { } } | request = beforeClientExecution ( request ) ; return executeListRecoveryPointsByResource ( request ) ; |
public class DependencyInfoFactory { /** * / * - - - Public methods - - - */
public DependencyInfo createDependencyInfo ( File basedir , String filename ) { } } | DependencyInfo dependency ; try { File dependencyFile = new File ( basedir , filename ) ; String sha1 = ChecksumUtils . calculateSHA1 ( dependencyFile ) ; dependency = new DependencyInfo ( sha1 ) ; dependency . setArtifactId ( dependencyFile . getName ( ) ) ; dependency . setFilename ( dependencyFile . getName ( ) ) ; // system path
try { dependency . setSystemPath ( dependencyFile . getCanonicalPath ( ) ) ; } catch ( IOException e ) { dependency . setSystemPath ( dependencyFile . getAbsolutePath ( ) ) ; } // populate hints
if ( calculateHints ) { DependencyHintsInfo hints = HintUtils . getHints ( dependencyFile . getPath ( ) ) ; dependency . setHints ( hints ) ; } // additional sha1s
// MD5
if ( calculateMd5 ) { String md5 = ChecksumUtils . calculateHash ( dependencyFile , HashAlgorithm . MD5 ) ; dependency . addChecksum ( ChecksumType . MD5 , md5 ) ; } // handle JavaScript files
if ( filename . toLowerCase ( ) . matches ( JAVA_SCRIPT_REGEX ) ) { Map < ChecksumType , String > javaScriptChecksums ; try { javaScriptChecksums = new HashCalculator ( ) . calculateJavaScriptHashes ( dependencyFile ) ; if ( javaScriptChecksums == null || javaScriptChecksums . isEmpty ( ) ) { logger . debug ( "Failed to calculate javaScript hash: {}" , dependencyFile . getPath ( ) ) ; } for ( Map . Entry < ChecksumType , String > entry : javaScriptChecksums . entrySet ( ) ) { dependency . addChecksum ( entry . getKey ( ) , entry . getValue ( ) ) ; } } catch ( Exception e ) { logger . warn ( "Failed to calculate javaScript hash for file: {}, error: {}" , dependencyFile . getPath ( ) , e . getMessage ( ) ) ; logger . debug ( "Failed to calculate javaScript hash for file: {}, error: {}" , dependencyFile . getPath ( ) , e . getStackTrace ( ) ) ; } } // other platform SHA1
ChecksumUtils . calculateOtherPlatformSha1 ( dependency , dependencyFile ) ; // super hash
ChecksumUtils . calculateSuperHash ( dependency , dependencyFile ) ; } catch ( IOException e ) { logger . warn ( "Failed to create dependency " + filename + " to dependency list: {}" , e . getMessage ( ) ) ; dependency = null ; } return dependency ; |
public class ImageDeformPointMLS_F32 { /** * Computes the average P given the weights at this cached point */
void computeAverageP ( Cache cache ) { } } | float [ ] weights = cache . weights . data ; cache . aveP . set ( 0 , 0 ) ; for ( int i = 0 ; i < controls . size ( ) ; i ++ ) { Control c = controls . get ( i ) ; float w = weights [ i ] ; cache . aveP . x += c . p . x * w ; cache . aveP . y += c . p . y * w ; } cache . aveP . x /= cache . totalWeight ; cache . aveP . y /= cache . totalWeight ; |
public class AmazonPinpointClient { /** * Returns information about your export jobs .
* @ param getExportJobsRequest
* @ return Result of the GetExportJobs operation returned by the service .
* @ throws BadRequestException
* 400 response
* @ throws InternalServerErrorException
* 500 response
* @ throws ForbiddenException
* 403 response
* @ throws NotFoundException
* 404 response
* @ throws MethodNotAllowedException
* 405 response
* @ throws TooManyRequestsException
* 429 response
* @ sample AmazonPinpoint . GetExportJobs
* @ see < a href = " http : / / docs . aws . amazon . com / goto / WebAPI / pinpoint - 2016-12-01 / GetExportJobs " target = " _ top " > AWS API
* Documentation < / a > */
@ Override public GetExportJobsResult getExportJobs ( GetExportJobsRequest request ) { } } | request = beforeClientExecution ( request ) ; return executeGetExportJobs ( request ) ; |
public class ObjectNameBuilder { /** * Use introspection to obtain the objectName from the { @ link MBean # objectName ( ) } annotation attribute .
* @ param mBeanClass a type annotated with { @ link MBean }
* @ return an ObjectNameBuilder
* @ throws MalformedObjectNameException */
public ObjectNameBuilder withObjectName ( Class < ? > mBeanClass ) throws MalformedObjectNameException { } } | MBean annotation = mBeanClass . getAnnotation ( MBean . class ) ; Preconditions . notNull ( annotation , mBeanClass + " is not annotated with " + MBean . class ) ; return withObjectName ( annotation ) ; |
public class BundleUtils { /** * Returns a optional long array value . In other words , returns the value mapped by key if it exists and is a long array .
* The bundle argument is allowed to be { @ code null } . If the bundle is null , this method returns null .
* @ param bundle a bundle . If the bundle is null , this method will return null .
* @ param key a key for the value .
* @ param fallback fallback value .
* @ return a long array value if exists , null otherwise .
* @ see android . os . Bundle # getInt ( String , int ) */
@ Nullable public static long [ ] optLongArray ( @ Nullable Bundle bundle , @ Nullable String key , @ Nullable long [ ] fallback ) { } } | if ( bundle == null ) { return fallback ; } return bundle . getLongArray ( key ) ; |
public class ReceiveMessageBuilder { /** * Creates new variable extractor and adds it to test action . */
private XpathPayloadVariableExtractor getXpathVariableExtractor ( ) { } } | if ( xpathExtractor == null ) { xpathExtractor = new XpathPayloadVariableExtractor ( ) ; getAction ( ) . getVariableExtractors ( ) . add ( xpathExtractor ) ; } return xpathExtractor ; |
public class HadoopUtils { /** * Renames a src { @ link Path } on fs { @ link FileSystem } to a dst { @ link Path } . If fs is a { @ link LocalFileSystem } and
* src is a directory then { @ link File # renameTo } is called directly to avoid a directory rename race condition where
* { @ link org . apache . hadoop . fs . RawLocalFileSystem # rename } copies the conflicting src directory into dst resulting in
* an extra nested level , such as / root / a / b / c / e / e where e is repeated .
* @ param fs the { @ link FileSystem } where the src { @ link Path } exists
* @ param src the source { @ link Path } which will be renamed
* @ param dst the { @ link Path } to rename to
* @ return true if rename succeeded , false if rename failed .
* @ throws IOException if rename failed for reasons other than target exists . */
public static boolean renamePathHandleLocalFSRace ( FileSystem fs , Path src , Path dst ) throws IOException { } } | if ( DecoratorUtils . resolveUnderlyingObject ( fs ) instanceof LocalFileSystem && fs . isDirectory ( src ) ) { LocalFileSystem localFs = ( LocalFileSystem ) DecoratorUtils . resolveUnderlyingObject ( fs ) ; File srcFile = localFs . pathToFile ( src ) ; File dstFile = localFs . pathToFile ( dst ) ; return srcFile . renameTo ( dstFile ) ; } else { return fs . rename ( src , dst ) ; } |
public class JvmDoubleAnnotationValueImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
public EList < Double > getValues ( ) { } } | if ( values == null ) { values = new EDataTypeEList < Double > ( Double . class , this , TypesPackage . JVM_DOUBLE_ANNOTATION_VALUE__VALUES ) ; } return values ; |
public class GCMMessage { /** * Default message substitutions . Can be overridden by individual address substitutions .
* @ param substitutions
* Default message substitutions . Can be overridden by individual address substitutions . */
public void setSubstitutions ( java . util . Map < String , java . util . List < String > > substitutions ) { } } | this . substitutions = substitutions ; |
public class DetectorFactory { /** * Get the short name of the Detector . This is the name of the detector
* class without the package qualification . */
public String getShortName ( ) { } } | int endOfPkg = className . lastIndexOf ( '.' ) ; if ( endOfPkg >= 0 ) { return className . substring ( endOfPkg + 1 ) ; } return className ; |
public class Trie { /** * Matches the strings in the trie against a specified text . Matching is doing using a greedy longest match wins way .
* The give CharPredicate is used to determine if matches are accepted , e . g . only accept a match followed by a
* whitespace character .
* @ param text the text to find the trie elements in
* @ param delimiter the predicate that specifies acceptable delimiters
* @ return the list of matched elements */
public List < TrieMatch < V > > find ( String text , CharMatcher delimiter ) { } } | if ( StringUtils . isNullOrBlank ( text ) ) { return Collections . emptyList ( ) ; } if ( delimiter == null ) { delimiter = CharMatcher . ANY ; } int len = text . length ( ) ; StringBuilder key = new StringBuilder ( ) ; int start = 0 ; int lastMatch = - 1 ; List < TrieMatch < V > > results = new ArrayList < > ( ) ; for ( int i = 0 ; i < len ; i ++ ) { key . append ( text . charAt ( i ) ) ; // We have a key match
if ( containsKey ( key . toString ( ) ) ) { int nextI = lastMatch = i + 1 ; // There is something longer !
if ( nextI < len && prefix ( key . toString ( ) + text . charAt ( i + 1 ) ) . size ( ) > 0 ) { continue ; } lastMatch = - 1 ; // check if we accept
if ( nextI >= len || delimiter . matches ( text . charAt ( nextI ) ) ) { V value = get ( key . toString ( ) ) ; results . add ( new TrieMatch < > ( start , nextI , value ) ) ; start = nextI ; } } else if ( prefix ( key . toString ( ) ) . isEmpty ( ) ) { // We cannot possibly match anything
if ( lastMatch != - 1 ) { // We have a good match , so lets use it
int nextI = lastMatch ; if ( nextI >= 1 && delimiter . matches ( text . charAt ( nextI ) ) ) { key = new StringBuilder ( text . substring ( start , nextI ) ) ; V value = get ( key . toString ( ) ) ; results . add ( new TrieMatch < > ( start , nextI , value ) ) ; i = nextI ; lastMatch = - 1 ; start = nextI ; } else { start = i ; } } else { start = i ; } if ( start < len ) { key . setLength ( 1 ) ; key . setCharAt ( 0 , text . charAt ( start ) ) ; } else { key . setLength ( 0 ) ; } } } return results ; |
public class Actionable { /** * Gets all actions , transient or persistent .
* { @ link # getActions } is supplemented with anything contributed by { @ link TransientActionFactory } .
* @ return an unmodifiable , possible empty list
* @ since 1.548 */
@ Exported ( name = "actions" ) @ Nonnull public final List < ? extends Action > getAllActions ( ) { } } | List < Action > _actions = getActions ( ) ; boolean adding = false ; for ( TransientActionFactory < ? > taf : TransientActionFactory . factoriesFor ( getClass ( ) , Action . class ) ) { Collection < ? extends Action > additions = createFor ( taf ) ; if ( ! additions . isEmpty ( ) ) { if ( ! adding ) { // need to make a copy
adding = true ; _actions = new ArrayList < > ( _actions ) ; } _actions . addAll ( additions ) ; } } return Collections . unmodifiableList ( _actions ) ; |
public class Repeater { /** * Internal utility method .
* This is called in places where the repeater needs to move to the next
* non - null item in the data set to render . This occurs when the
* current data item is null and the < code > ignoreNulls < / code >
* flag has been set to skip rendering null items in the data set .
* This method side - effects to advance the iterator to the next
* non - null item or the end if there are zero remaining non - null
* items .
* At the end , the < code > currentItem < / code > may be null , and the
* < code > currentIndex < / code > will reference either the integer
* location in the data structure of the non - null data item , or
* it will reference the end of the data structure . */
private final void advanceToNonNullItem ( ) { } } | assert _iterator != null ; assert _currentItem == null ; while ( _iterator . hasNext ( ) && _currentItem == null ) { _currentItem = _iterator . next ( ) ; _currentIndex ++ ; } |
public class EllipsesIntoClusters { /** * Removes stray connections that are highly likely to be noise . If a node has one connection it then removed .
* Then it ' s only connection is considered for removal . */
static void removeSingleConnections ( List < Node > cluster ) { } } | List < Node > open = new ArrayList < > ( ) ; List < Node > future = new ArrayList < > ( ) ; open . addAll ( cluster ) ; while ( ! open . isEmpty ( ) ) { for ( int i = open . size ( ) - 1 ; i >= 0 ; i -- ) { Node n = open . get ( i ) ; if ( n . connections . size == 1 ) { // clear it ' s connections and remove it from the cluster
int index = findNode ( n . which , cluster ) ; cluster . remove ( index ) ; // Remove the reference to this node from its one connection
int parent = findNode ( n . connections . get ( 0 ) , cluster ) ; n . connections . reset ( ) ; if ( parent == - 1 ) throw new RuntimeException ( "BUG!" ) ; Node p = cluster . get ( parent ) ; int edge = p . connections . indexOf ( n . which ) ; if ( edge == - 1 ) throw new RuntimeException ( "BUG!" ) ; p . connections . remove ( edge ) ; // if the parent now only has one connection
if ( p . connections . size == 1 ) { future . add ( p ) ; } } } open . clear ( ) ; List < Node > tmp = open ; open = future ; future = tmp ; } |
public class PreferenceActivity { /** * Obtains the elevation of the toolbar , which is used to show the bread crumb of the currently
* selected preference fragment , when using the split screen layout . */
private void obtainBreadcrumbElevation ( ) { } } | int elevation ; try { elevation = ThemeUtil . getDimensionPixelSize ( this , R . attr . breadCrumbElevation ) ; } catch ( NotFoundException e ) { elevation = getResources ( ) . getDimensionPixelSize ( R . dimen . bread_crumb_toolbar_elevation ) ; } setBreadCrumbElevation ( pixelsToDp ( this , elevation ) ) ; |
public class JDK8TriggerBuilder { /** * Set the identity of the Job which should be fired by the produced Trigger -
* a < code > JobKey < / code > will be produced with the given name and group .
* @ param jobName
* the name of the job to fire .
* @ param jobGroup
* the group of the job to fire .
* @ return the updated JDK8TriggerBuilder
* @ see ITrigger # getJobKey ( ) */
@ Nonnull public JDK8TriggerBuilder < T > forJob ( final String jobName , final String jobGroup ) { } } | m_aJobKey = new JobKey ( jobName , jobGroup ) ; return this ; |
public class URLUtil { /** * 编码字符为 application / x - www - form - urlencoded < br >
* 将需要转换的内容 ( ASCII码形式之外的内容 ) , 用十六进制表示法转换出来 , 并在之前加上 % 开头 。 < br >
* 此方法用于URL自动编码 , 类似于浏览器中键入地址自动编码 , 对于像类似于 “ / ” 的字符不再编码
* @ param url 被编码内容
* @ param charset 编码
* @ return 编码后的字符
* @ since 4.4.1 */
public static String encode ( String url , Charset charset ) { } } | if ( StrUtil . isEmpty ( url ) ) { return url ; } if ( null == charset ) { charset = CharsetUtil . defaultCharset ( ) ; } return URLEncoder . DEFAULT . encode ( url , charset ) ; |
public class ModelsImpl { /** * Adds a list of prebuilt entity extractors to the application .
* @ param appId The application ID .
* @ param versionId The version ID .
* @ param prebuiltExtractorNames An array of prebuilt entity extractor names .
* @ param serviceCallback the async ServiceCallback to handle successful and failed responses .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the { @ link ServiceFuture } object */
public ServiceFuture < List < PrebuiltEntityExtractor > > addPrebuiltAsync ( UUID appId , String versionId , List < String > prebuiltExtractorNames , final ServiceCallback < List < PrebuiltEntityExtractor > > serviceCallback ) { } } | return ServiceFuture . fromResponse ( addPrebuiltWithServiceResponseAsync ( appId , versionId , prebuiltExtractorNames ) , serviceCallback ) ; |
public class BackedSession { /** * removeValueGuts - To remove the values */
synchronized Object removeValueGuts ( String pName ) { } } | // create local variable - JIT performance improvement
final boolean isTraceOn = com . ibm . websphere . ras . TraceComponent . isAnyTracingEnabled ( ) ; if ( isTraceOn && LoggingUtil . SESSION_LOGGER_WAS . isLoggable ( Level . FINER ) ) { LoggingUtil . SESSION_LOGGER_WAS . entering ( methodClassName , methodNames [ REMOVE_VALUE_GUTS ] , "session " + getId ( ) + " prop id " + pName ) ; } Object tmp = getValueGuts ( pName , false ) ; // if object does not acutally exist , just return
if ( tmp == null ) { if ( isTraceOn && LoggingUtil . SESSION_LOGGER_WAS . isLoggable ( Level . FINER ) ) { LoggingUtil . SESSION_LOGGER_WAS . exiting ( methodClassName , methodNames [ REMOVE_VALUE_GUTS ] , "prop id " + pName + " not in " + getId ( ) ) ; } return null ; } if ( appDataRemovals == null ) { if ( isTraceOn && LoggingUtil . SESSION_LOGGER_WAS . isLoggable ( Level . FINE ) ) { LoggingUtil . SESSION_LOGGER_WAS . logp ( Level . FINE , methodClassName , methodNames [ REMOVE_VALUE_GUTS ] , "init appDataRemovals " + getId ( ) ) ; } appDataRemovals = new Hashtable ( ) ; } if ( appDataTablesPerThread ) { if ( isTraceOn && LoggingUtil . SESSION_LOGGER_WAS . isLoggable ( Level . FINE ) ) { LoggingUtil . SESSION_LOGGER_WAS . logp ( Level . FINE , methodClassName , methodNames [ REMOVE_VALUE_GUTS ] , "appDataTablesPerThread" ) ; } Thread t = Thread . currentThread ( ) ; Hashtable sht = ( Hashtable ) appDataRemovals . get ( t ) ; if ( sht == null ) { sht = new Hashtable ( ) ; appDataRemovals . put ( t , sht ) ; } if ( isTraceOn && LoggingUtil . SESSION_LOGGER_WAS . isLoggable ( Level . FINE ) ) { LoggingUtil . SESSION_LOGGER_WAS . logp ( Level . FINE , methodClassName , methodNames [ REMOVE_VALUE_GUTS ] , "remove value for " + getId ( ) + " and prop " + pName + " via thread " + t ) ; } sht . put ( pName , pName ) ; } else { // appDataTablesPerSession
if ( isTraceOn && LoggingUtil . SESSION_LOGGER_WAS . isLoggable ( Level . FINE ) ) { LoggingUtil . SESSION_LOGGER_WAS . logp ( Level . FINE , methodClassName , methodNames [ REMOVE_VALUE_GUTS ] , "appDataTablesPerSession" ) ; } appDataRemovals . put ( pName , pName ) ; } Object ret = ( mNonswappableData == null ) ? null : mNonswappableData . remove ( pName ) ; if ( ret == null ) ret = getSwappableData ( ) . remove ( pName ) ; if ( isTraceOn && LoggingUtil . SESSION_LOGGER_WAS . isLoggable ( Level . FINE ) ) { LoggingUtil . SESSION_LOGGER_WAS . exiting ( methodClassName , methodNames [ REMOVE_VALUE_GUTS ] ) ; } return ret ; |
public class TryCatchFinallyStatementTransformer { /** * Handle case where a catch clause declares a non - bytecode exception type e . g . , soap exception type .
* In such a case the catch clause and all subsequent catch clauses must be handled in a single
* catch - clause for Throwable . If none of the subsequent catch clauses handle Throwable explicitly
* and none of the clauses field the exception , it is rethrown . Note if a ' default ' catch clause
* is declard ( i . e . a JavaScript - style catch clause with no exception type declared ) , it is treated
* as handling Throwable explicitly ; in other words no code is generated to rethrow the exception .
* For example , the following try - catch statement declares a soap exception , which is not really
* a valid Java exception type . It ' s a simple case with no finally clause and no default catch , but
* it illustrates the essence of the problem .
* < pre >
* try {
* doSomething ( )
* catch ( re : RuntimeException ) {
* print ( " RuntimeException " )
* catch ( fake : DoesntActuallyExtendThrowable ) {
* print ( " DoesntActuallyExtendThrowable " )
* catch ( e : RealException ) {
* print ( " RealException " )
* < / pre >
* We must treat this statement as the following ( simplified ) code :
* < pre >
* try {
* doSomething ( )
* catch ( re : RuntimeException ) {
* print ( " RuntimeException " )
* catch ( t : Throwable ) {
* var rtt = TypeSystem . getFromObject ( t )
* if ( DoesntActuallyExtendThrowable . Type . isAssignableFrom ( rtt ) ) {
* print ( " DoesntActuallyExtendThrowable " )
* if ( RealException . Type . isAssignableFrom ( rtt ) ) {
* print ( " RealException " )
* else {
* throw t
* < / pre > */
private void compileOtherCatchStatements ( final TopLevelTransformationContext cc , List < CatchClause > otherCatches , List < IRCatchClause > resultingClauses ) { } } | cc . pushScope ( false ) ; try { // Create a temp symbol to represent the exception variable for the synthetic clause
IRSymbol exceptionSymbol = new IRSymbol ( "exception$$temp$$var" , getDescriptor ( Throwable . class ) , true ) ; cc . putSymbol ( exceptionSymbol ) ; List < IRStatement > catchBody = new ArrayList < IRStatement > ( ) ; // Store the exception type in a temporary variable
IRSymbol exceptionTypeSymbol = new IRSymbol ( "exceptiontype$$temp$$var" , IRTypeConstants . ITYPE ( ) , true ) ; cc . putSymbol ( exceptionTypeSymbol ) ; catchBody . add ( buildAssignment ( exceptionTypeSymbol , callStaticMethod ( TypeSystem . class , "getFromObject" , new Class [ ] { Object . class } , exprList ( identifier ( exceptionSymbol ) ) ) ) ) ; // Build up a nested if - statement
IRIfStatement lastStatement = null ; for ( CatchClause clause : otherCatches ) { cc . pushScope ( false ) ; // scope for the exception param
try { Symbol symbol = clause . getSymbol ( ) ; IType type = clause . getCatchType ( ) ; if ( type == null ) { type = JavaTypes . THROWABLE ( ) ; } if ( symbol != null ) { if ( type != JavaTypes . THROWABLE ( ) ) { // Test for assignability
IRExpression test = callMethod ( IType . class , "isAssignableFrom" , new Class [ ] { IType . class } , pushType ( type ) , exprList ( identifier ( exceptionTypeSymbol ) ) ) ; // Assign the generic variable to an appropriately typed and boxed symbol , then compile the catch body
List < IRStatement > body = new ArrayList < IRStatement > ( ) ; body . add ( assignCatchClauseSymbol ( exceptionSymbol , symbol . getName ( ) , type , symbol . isValueBoxed ( ) ) ) ; body . add ( cc . compile ( clause . getCatchStmt ( ) ) ) ; IRIfStatement nestedCatchStatement = new IRIfStatement ( test , new IRStatementList ( false , body ) , null ) ; // Add it to the list we ' re building up ; if it ' s the first statement then set up the variable and add it to
// the list , otherwise chain it to the previous if statement
if ( lastStatement == null ) { catchBody . add ( nestedCatchStatement ) ; } else { // It ' s possible that some clause follows the last if / else clause ; if so , the else statement
// will already be non - null , so in that case we can just drop these statements on the floor
// since they ' ll never be executed
if ( lastStatement . getElseStatement ( ) == null ) { lastStatement . setElseStatement ( nestedCatchStatement ) ; } } lastStatement = nestedCatchStatement ; } else { // No point in testing for assignability , so we know it ' s a throwable .
List < IRStatement > body = new ArrayList < IRStatement > ( ) ; body . add ( assignCatchClauseSymbol ( exceptionSymbol , symbol . getName ( ) , clause . getCatchType ( ) , symbol . isValueBoxed ( ) ) ) ; body . add ( cc . compile ( clause . getCatchStmt ( ) ) ) ; if ( lastStatement != null ) { lastStatement . setElseStatement ( new IRStatementList ( false , body ) ) ; } else { catchBody . addAll ( body ) ; } // Once we ' ve hit a catch around Throwable , exit the loop immediately
break ; } } else { // Uncaught , so rethrow
lastStatement . setElseStatement ( new IRThrowStatement ( identifier ( exceptionSymbol ) ) ) ; } } finally { cc . popScope ( ) ; } } resultingClauses . add ( new IRCatchClause ( exceptionSymbol , new IRStatementList ( false , catchBody ) ) ) ; } finally { cc . popScope ( ) ; } |
public class BingImagesImpl { /** * The Image Detail Search API lets you search on Bing and get back insights about an image , such as webpages that include the image . This section provides technical details about the query parameters and headers that you use to request insights of images and the JSON response objects that contain them . For examples that show how to make requests , see [ Searching the Web for Images ] ( https : / / docs . microsoft . com / azure / cognitive - services / bing - image - search / search - the - web ) .
* @ param query The user ' s search query term . The term cannot be empty . The term may contain [ Bing Advanced Operators ] ( http : / / msdn . microsoft . com / library / ff795620 . aspx ) . For example , to limit images to a specific domain , use the [ site : ] ( http : / / msdn . microsoft . com / library / ff795613 . aspx ) operator . To help improve relevance of an insights query ( see [ insightsToken ] ( https : / / docs . microsoft . com / en - us / rest / api / cognitiveservices / bing - images - api - v7 - reference # insightstoken ) ) , you should always include the user ' s query term . Use this parameter only with the Image Search API . Do not specify this parameter when calling the Trending Images API .
* @ param detailsOptionalParameter the object representing the optional parameters to be set before calling this API
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the observable to the ImageInsights object */
public Observable < ServiceResponse < ImageInsights > > detailsWithServiceResponseAsync ( String query , DetailsOptionalParameter detailsOptionalParameter ) { } } | if ( query == null ) { throw new IllegalArgumentException ( "Parameter query is required and cannot be null." ) ; } final String acceptLanguage = detailsOptionalParameter != null ? detailsOptionalParameter . acceptLanguage ( ) : null ; final String contentType = detailsOptionalParameter != null ? detailsOptionalParameter . contentType ( ) : null ; final String userAgent = detailsOptionalParameter != null ? detailsOptionalParameter . userAgent ( ) : this . client . userAgent ( ) ; final String clientId = detailsOptionalParameter != null ? detailsOptionalParameter . clientId ( ) : null ; final String clientIp = detailsOptionalParameter != null ? detailsOptionalParameter . clientIp ( ) : null ; final String location = detailsOptionalParameter != null ? detailsOptionalParameter . location ( ) : null ; final Double cropBottom = detailsOptionalParameter != null ? detailsOptionalParameter . cropBottom ( ) : null ; final Double cropLeft = detailsOptionalParameter != null ? detailsOptionalParameter . cropLeft ( ) : null ; final Double cropRight = detailsOptionalParameter != null ? detailsOptionalParameter . cropRight ( ) : null ; final Double cropTop = detailsOptionalParameter != null ? detailsOptionalParameter . cropTop ( ) : null ; final ImageCropType cropType = detailsOptionalParameter != null ? detailsOptionalParameter . cropType ( ) : null ; final String countryCode = detailsOptionalParameter != null ? detailsOptionalParameter . countryCode ( ) : null ; final String id = detailsOptionalParameter != null ? detailsOptionalParameter . id ( ) : null ; final String imageUrl = detailsOptionalParameter != null ? detailsOptionalParameter . imageUrl ( ) : null ; final String insightsToken = detailsOptionalParameter != null ? detailsOptionalParameter . insightsToken ( ) : null ; final List < ImageInsightModule > modules = detailsOptionalParameter != null ? detailsOptionalParameter . modules ( ) : null ; final String market = detailsOptionalParameter != null ? detailsOptionalParameter . market ( ) : null ; final SafeSearch safeSearch = detailsOptionalParameter != null ? detailsOptionalParameter . safeSearch ( ) : null ; final String setLang = detailsOptionalParameter != null ? detailsOptionalParameter . setLang ( ) : null ; return detailsWithServiceResponseAsync ( query , acceptLanguage , contentType , userAgent , clientId , clientIp , location , cropBottom , cropLeft , cropRight , cropTop , cropType , countryCode , id , imageUrl , insightsToken , modules , market , safeSearch , setLang ) ; |
public class AbstractCodeCreator { /** * Find the integer value of a property or a default if it is not set
* @ param name the property name
* @ param defVal the default value
* @ return the properties integer value or the default */
public int findPropertyValueAsIntWithDefault ( String name , int defVal ) { } } | return properties ( ) . stream ( ) . filter ( p -> name . equals ( p . getName ( ) ) ) . map ( CreatorProperty :: getLatestValueAsInt ) . findFirst ( ) . orElse ( defVal ) ; |
public class DogmaApi { /** * Get dynamic item information ( asynchronously ) Returns info about a
* dynamic item resulting from mutation with a mutaplasmid . - - - This route
* expires daily at 11:05
* @ param itemId
* item _ id integer ( required )
* @ param typeId
* type _ id integer ( required )
* @ param datasource
* The server name you would like data from ( optional , default to
* tranquility )
* @ param ifNoneMatch
* ETag from a previous request . A 304 will be returned if this
* matches the current ETag ( optional )
* @ param callback
* The callback to be executed when the API call finishes
* @ return The request call
* @ throws ApiException
* If fail to process the API call , e . g . serializing the request
* body object */
public com . squareup . okhttp . Call getDogmaDynamicItemsTypeIdItemIdAsync ( Long itemId , Integer typeId , String datasource , String ifNoneMatch , final ApiCallback < DogmaDynamicItemsResponse > callback ) throws ApiException { } } | com . squareup . okhttp . Call call = getDogmaDynamicItemsTypeIdItemIdValidateBeforeCall ( itemId , typeId , datasource , ifNoneMatch , callback ) ; Type localVarReturnType = new TypeToken < DogmaDynamicItemsResponse > ( ) { } . getType ( ) ; apiClient . executeAsync ( call , localVarReturnType , callback ) ; return call ; |
public class RedmineManagerFactory { /** * Creates a non - authenticating redmine manager .
* @ param uri redmine manager URI .
* @ param httpClient you can provide your own pre - configured HttpClient if you want
* to control connection pooling , manage connections eviction , closing , etc . */
public static RedmineManager createUnauthenticated ( String uri , HttpClient httpClient ) { } } | return createWithUserAuth ( uri , null , null , httpClient ) ; |
public class KTypeArrayList { /** * { @ inheritDoc } */
@ Override public KType set ( int index , KType e1 ) { } } | assert ( index >= 0 && index < size ( ) ) : "Index " + index + " out of bounds [" + 0 + ", " + size ( ) + ")." ; final KType v = Intrinsics . < KType > cast ( buffer [ index ] ) ; buffer [ index ] = e1 ; return v ; |
public class CountrySpinnerAdapter { /** * Drop down selected view
* @ param position position of selected item
* @ param convertView View of selected item
* @ param parent parent of selected view
* @ return convertView */
@ Override public View getView ( int position , View convertView , ViewGroup parent ) { } } | Country country = getItem ( position ) ; if ( convertView == null ) { convertView = new ImageView ( getContext ( ) ) ; } ( ( ImageView ) convertView ) . setImageResource ( getFlagResource ( country ) ) ; return convertView ; |
public class ActivityTypeInfoMarshaller { /** * Marshall the given parameter object . */
public void marshall ( ActivityTypeInfo activityTypeInfo , ProtocolMarshaller protocolMarshaller ) { } } | if ( activityTypeInfo == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( activityTypeInfo . getActivityType ( ) , ACTIVITYTYPE_BINDING ) ; protocolMarshaller . marshall ( activityTypeInfo . getStatus ( ) , STATUS_BINDING ) ; protocolMarshaller . marshall ( activityTypeInfo . getDescription ( ) , DESCRIPTION_BINDING ) ; protocolMarshaller . marshall ( activityTypeInfo . getCreationDate ( ) , CREATIONDATE_BINDING ) ; protocolMarshaller . marshall ( activityTypeInfo . getDeprecationDate ( ) , DEPRECATIONDATE_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class ThumbnailsMarshaller { /** * Marshall the given parameter object . */
public void marshall ( Thumbnails thumbnails , ProtocolMarshaller protocolMarshaller ) { } } | if ( thumbnails == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( thumbnails . getFormat ( ) , FORMAT_BINDING ) ; protocolMarshaller . marshall ( thumbnails . getInterval ( ) , INTERVAL_BINDING ) ; protocolMarshaller . marshall ( thumbnails . getResolution ( ) , RESOLUTION_BINDING ) ; protocolMarshaller . marshall ( thumbnails . getAspectRatio ( ) , ASPECTRATIO_BINDING ) ; protocolMarshaller . marshall ( thumbnails . getMaxWidth ( ) , MAXWIDTH_BINDING ) ; protocolMarshaller . marshall ( thumbnails . getMaxHeight ( ) , MAXHEIGHT_BINDING ) ; protocolMarshaller . marshall ( thumbnails . getSizingPolicy ( ) , SIZINGPOLICY_BINDING ) ; protocolMarshaller . marshall ( thumbnails . getPaddingPolicy ( ) , PADDINGPOLICY_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class AvatarNode { /** * Return the configuration that should be used by this instance of AvatarNode
* Copy fsimages from the remote shared device . */
static Configuration setupAvatarNodeStorage ( Configuration conf , StartupInfo startInfo , NamenodeProtocol primaryNamenode ) throws IOException { } } | // shared loations for image and edits
URI img0 = NNStorageConfiguration . getURIKey ( conf , "dfs.name.dir.shared0" ) ; URI img1 = NNStorageConfiguration . getURIKey ( conf , "dfs.name.dir.shared1" ) ; URI edit0 = NNStorageConfiguration . getURIKey ( conf , "dfs.name.edits.dir.shared0" ) ; URI edit1 = NNStorageConfiguration . getURIKey ( conf , "dfs.name.edits.dir.shared1" ) ; // local locations for image and edits
Collection < URI > namedirs = NNStorageConfiguration . getNamespaceDirs ( conf , null ) ; Collection < URI > editsdir = NNStorageConfiguration . getNamespaceEditsDirs ( conf , null ) ; // validate correctness of the configuration
AvatarStorageSetup . validate ( conf , namedirs , editsdir , img0 , img1 , edit0 , edit1 ) ; FileSystem localFs = FileSystem . getLocal ( conf ) . getRaw ( ) ; URI ownSharedImage = null ; URI ownSharedEdits = null ; // if we are instance one then copy from primary to secondary
// otherwise copy from secondary to primary .
if ( startInfo . instance == InstanceId . NODEONE ) { ownSharedImage = img1 ; ownSharedEdits = edit1 ; } else if ( startInfo . instance == InstanceId . NODEZERO ) { ownSharedImage = img0 ; ownSharedEdits = edit0 ; } // allocate a new configuration and update fs . name . dir approprately
// The shared device should be the first in the list .
Configuration newconf = new Configuration ( conf ) ; AvatarStorageSetup . updateConf ( startInfo , newconf , namedirs , img0 , img1 , "dfs.name.dir" ) ; // update fs . name . edits . dir approprately in the new configuration
// The shared device should be the first in the list .
AvatarStorageSetup . updateConf ( startInfo , newconf , editsdir , edit0 , edit1 , "dfs.name.edits.dir" ) ; // copy fsimage directory if needed
if ( startInfo . isStandby ) { // do not open edit log at startup
newconf . setBoolean ( "dfs.namenode.openlog" , false ) ; // connect to primary
String fsName = getRemoteNamenodeHttpName ( conf , startInfo . instance ) ; FSImage tempImage = new FSImage ( newconf , NNStorageConfiguration . getNamespaceDirs ( newconf ) , NNStorageConfiguration . getNamespaceEditsDirs ( newconf ) , null ) ; // will block until Primary has left the safemode
CheckpointSignature cs = getCheckpointSignature ( primaryNamenode ) ; long lastCheckpointTxId = cs . mostRecentCheckpointTxId ; if ( cs . layoutVersion != FSConstants . LAYOUT_VERSION ) { throw new IOException ( "Upgrade for standby is not supported" ) ; } if ( isFile ( ownSharedImage ) ) { File destFile = new File ( ownSharedImage . getPath ( ) ) ; NNStorageDirectoryRetentionManager . backupFiles ( localFs , destFile , conf ) ; } if ( isFile ( ownSharedEdits ) ) { File destFile = new File ( ownSharedEdits . getPath ( ) ) ; NNStorageDirectoryRetentionManager . backupFiles ( localFs , destFile , newconf ) ; } // setup storage
NNStorage tempStorage = tempImage . storage ; tempStorage . format ( ) ; tempStorage . setStorageInfo ( cs ) ; tempStorage . writeAll ( ) ; tempImage . editLog . transitionNonFileJournals ( tempStorage , false , Transition . FORMAT , null ) ; tempImage . transitionNonFileImages ( tempStorage , false , Transition . FORMAT ) ; // we need to become the active writer to upload image successfully to
// non - file images storage
tempImage . editLog . recoverUnclosedStreams ( ) ; // Download the image to all storage directories
FLOG . info ( "Downloading image to all storage directories." ) ; MD5Hash digest = downloadImageToStorage ( fsName , lastCheckpointTxId , tempImage ) ; List < StorageDirectory > badSds = new ArrayList < StorageDirectory > ( ) ; tempStorage . checkpointUploadDone ( lastCheckpointTxId , digest ) ; FLOG . info ( "Downloading image to all storage directories. DONE" ) ; tempImage . saveDigestAndRenameCheckpointImage ( lastCheckpointTxId , digest ) ; tempStorage . reportErrorsOnDirectories ( badSds , tempImage ) ; tempStorage . close ( ) ; tempImage . close ( ) ; } return newconf ; |
public class XDMClientParentSbb { /** * ( non - Javadoc )
* @ see
* XDMClientParent # subscriptionTerminated
* ( XDMClientChildSbbLocalObject ,
* java . net . URI , org . mobicents . slee . enabler . sip . TerminationReason ) */
@ Override public void subscriptionTerminated ( XDMClientChildSbbLocalObject child , String notifier , TerminationReason reason ) { } } | tracer . info ( "subscription terminated, reason = " + reason ) ; getXDMClientChildSbbChildRelation ( ) . get ( ChildRelationExt . DEFAULT_CHILD_NAME ) . remove ( ) ; |
public class NumberItemCollector { /** * Extract collecting stats map map .
* @ param dataList the data list
* @ return the map */
public Map < String , StatsMap > extractCollectingStatsMap ( List < Number > dataList ) { } } | return JMMap . newChangedValueMap ( this , this :: buildStatsMap ) ; |
public class DescribeAffectedEntitiesResult { /** * The entities that match the filter criteria .
* @ param entities
* The entities that match the filter criteria . */
public void setEntities ( java . util . Collection < AffectedEntity > entities ) { } } | if ( entities == null ) { this . entities = null ; return ; } this . entities = new java . util . ArrayList < AffectedEntity > ( entities ) ; |
public class StringUtils { /** * Bytes to hex .
* @ param bytes the bytes
* @ param size the size
* @ return the string */
public static String bytesToHex ( byte [ ] bytes , int size ) { } } | size = Math . min ( bytes . length , size ) ; char [ ] hexChars = new char [ size * 2 ] ; for ( int j = 0 ; j < size ; j ++ ) { int v = bytes [ j ] & 0xFF ; hexChars [ j * 2 ] = hexArray [ v >>> 4 ] ; hexChars [ j * 2 + 1 ] = hexArray [ v & 0x0F ] ; } return new String ( hexChars ) ; |
public class GlobalManager { /** * Performs the given action for each const vars until all have been processed or the action throws an exception .
* @ param action
* @ since 2.5.0 */
public void forEachConst ( BiConsumer < String , Object > action ) { } } | Objects . requireNonNull ( action ) ; this . constVars . forEach ( action ) ; |
public class DashboardMenu { /** * Returns the dashboard view type by a given view name .
* @ param viewName
* the name of the view to retrieve
* @ return the dashboard view for a given viewname or { @ code null } if view
* with given viewname does not exists */
public DashboardMenuItem getByViewName ( final String viewName ) { } } | final Optional < DashboardMenuItem > findFirst = dashboardVaadinViews . stream ( ) . filter ( view -> view . getViewName ( ) . equals ( viewName ) ) . findAny ( ) ; if ( ! findFirst . isPresent ( ) ) { return null ; } return findFirst . get ( ) ; |
public class CreateCloudFormationChangeSetRequest { /** * A list of parameter values for the parameters of the application .
* @ param parameterOverrides
* A list of parameter values for the parameters of the application . */
public void setParameterOverrides ( java . util . Collection < ParameterValue > parameterOverrides ) { } } | if ( parameterOverrides == null ) { this . parameterOverrides = null ; return ; } this . parameterOverrides = new java . util . ArrayList < ParameterValue > ( parameterOverrides ) ; |
public class JSONArray { /** * Encode a list into JSON text and write it to out . If this list is also a
* JSONStreamAware or a JSONAware , JSONStreamAware and JSONAware specific
* behaviours will be ignored at this top level .
* @ see JSONValue # writeJSONString ( Object , Appendable )
* @ param list
* @ param out */
public static void writeJSONString ( Iterable < ? extends Object > list , Appendable out , JSONStyle compression ) throws IOException { } } | if ( list == null ) { out . append ( "null" ) ; return ; } JsonWriter . JSONIterableWriter . writeJSONString ( list , out , compression ) ; |
public class Utils { /** * Splits columns names and values as required by Datastax java driver to generate an Insert query .
* @ param tuple an object containing the key Cell ( s ) as the first element and all the other columns as the second element .
* @ return an object containing an array of column names as the first element and an array of column values as the second element . */
public static Tuple2 < String [ ] , Object [ ] > prepareTuple4CqlDriver ( Tuple2 < Cells , Cells > tuple ) { } } | Cells keys = tuple . _1 ( ) ; Cells columns = tuple . _2 ( ) ; String [ ] names = new String [ keys . size ( ) + columns . size ( ) ] ; Object [ ] values = new Object [ keys . size ( ) + columns . size ( ) ] ; for ( int k = 0 ; k < keys . size ( ) ; k ++ ) { Cell cell = keys . getCellByIdx ( k ) ; names [ k ] = quote ( cell . getCellName ( ) ) ; values [ k ] = cell . getCellValue ( ) ; } for ( int v = keys . size ( ) ; v < ( keys . size ( ) + columns . size ( ) ) ; v ++ ) { Cell cell = columns . getCellByIdx ( v - keys . size ( ) ) ; names [ v ] = quote ( cell . getCellName ( ) ) ; values [ v ] = cell . getCellValue ( ) ; } return new Tuple2 < > ( names , values ) ; |
public class AbstractLoginModule { /** * / * ( non - Javadoc )
* @ see javax . security . auth . spi . LoginModule # initialize ( javax . security . auth . Subject , javax . security . auth . callback . CallbackHandler , java . util . Map , java . util . Map ) */
public void initialize ( Subject subject , CallbackHandler callbackHandler , Map < String , ? > sharedState , Map < String , ? > options ) { } } | this . subject = subject ; this . callbackHandler = callbackHandler ; this . principals . clear ( ) ; this . publicCredentials . clear ( ) ; this . privateCredentials . clear ( ) ; this . initialize ( sharedState , options ) ; |
public class JKTypeMapping { /** * This method is used to avoid reconigure the mapping in the otherside again . */
private static void processOtherMappings ( ) { } } | codeToJavaMapping . clear ( ) ; codeToJKTypeMapping . clear ( ) ; shortListOfJKTypes . clear ( ) ; Set < Class < ? > > keySet = javaToCodeMapping . keySet ( ) ; for ( Class < ? > clas : keySet ) { List < Integer > codes = javaToCodeMapping . get ( clas ) ; for ( Integer code : codes ) { codeToJavaMapping . put ( code , clas ) ; logger . debug ( " Code ({}) class ({}) name ({})" , code , clas . getSimpleName ( ) , namesMapping . get ( code ) ) ; codeToJKTypeMapping . put ( code , new JKType ( code , clas , namesMapping . get ( code ) ) ) ; } shortListOfJKTypes . add ( new JKType ( codes . get ( 0 ) , clas , namesMapping . get ( codes . get ( 0 ) ) ) ) ; } |
public class AbstractRasClassAdapter { /** * Visit the information about an inner class . We use this to determine
* whether or not the we ' re visiting an inner class . This callback is
* also used to ensure that appropriate class level annotations exist . */
@ Override public void visitInnerClass ( String name , String outerName , String innerName , int access ) { } } | // Make sure the class is annotated .
ensureAnnotated ( ) ; if ( name . equals ( getClassInternalName ( ) ) ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( outerName ) ; sb . append ( "$" ) ; sb . append ( innerName ) ; isInnerClass = name . equals ( sb . toString ( ) ) ; } super . visitInnerClass ( name , outerName , innerName , access ) ; |
public class HashBiMap { /** * { @ inheritDoc } */
public V put ( K key , V value ) { } } | reverseMap . put ( value , key ) ; return originalMap . put ( key , value ) ; |
public class ComputationGraph { /** * Set the computationGraphUpdater for the network */
public void setUpdater ( ComputationGraphUpdater updater ) { } } | if ( solver == null ) { solver = new Solver . Builder ( ) . configure ( conf ( ) ) . listeners ( getListeners ( ) ) . model ( this ) . build ( ) ; } solver . getOptimizer ( ) . setUpdaterComputationGraph ( updater ) ; |
public class ExtendedProperties { /** * Sets the property with the specified key .
* @ param key
* The key ( may not be { @ code null } )
* @ param value
* The value ( may not be { @ code null } )
* @ return The previous value of the property , or { @ code null } if it did not have one */
@ Override public String put ( final String key , final String value ) { } } | return propsMap . put ( key , value ) ; |
public class UnsortedWriterReportVisitor { /** * / * ( non - Javadoc )
* @ see de . is24 . util . monitoring . ReportVisitor # reportVersion ( de . is24 . util . monitoring . Version ) */
public void reportVersion ( Version aVersion ) { } } | LOGGER . debug ( "+++ enter UnsortedWriterReportVisitor.reportVersion+++" ) ; String result = aVersion . getName ( ) + " version : " + aVersion . getValue ( ) ; writeStringToWriter ( result ) ; |
public class DropDown { /** * ( non - Javadoc )
* @ see qc . automation . framework . widget . IDropDown # getSelectedOption ( ) */
@ Override public String getSelectedOption ( ) throws WidgetException { } } | try { Select select = new Select ( getByLocator ( ) ) ; List < String > selectedOptions = select . getSelectedOptions ( ) ; if ( selectedOptions != null && selectedOptions . size ( ) > 0 ) { return selectedOptions . get ( 0 ) ; } else { return "" ; } } catch ( Exception e ) { throw new WidgetException ( "Error while fetching selected options" , getByLocator ( ) , e ) ; } |
public class ProjectApi { /** * Get a list of projects starred by the authenticated user in the specified page range .
* < pre > < code > GET / projects ? starred = true < / code > < / pre >
* @ param page the page to get
* @ param perPage the number of projects per page
* @ return a list of projects starred by the authenticated user
* @ throws GitLabApiException if any exception occurs */
public List < Project > getStarredProjects ( int page , int perPage ) throws GitLabApiException { } } | Form formData = new GitLabApiForm ( ) . withParam ( "starred" , true ) . withParam ( PAGE_PARAM , page ) . withParam ( PER_PAGE_PARAM , perPage ) ; Response response = get ( Response . Status . OK , formData . asMap ( ) , "projects" ) ; return ( response . readEntity ( new GenericType < List < Project > > ( ) { } ) ) ; |
public class InformationRequestMessageImpl { /** * ( non - Javadoc )
* @ see org . restcomm . protocols . ss7 . isup . ISUPMessageImpl # decodeOptionalBody ( byte [ ] , byte ) */
protected void decodeOptionalBody ( ISUPParameterFactory parameterFactory , byte [ ] parameterBody , byte parameterCode ) throws ParameterException { } } | switch ( parameterCode & 0xFF ) { case CallReference . _PARAMETER_CODE : CallReference RS = parameterFactory . createCallReference ( ) ; ( ( AbstractISUPParameter ) RS ) . decode ( parameterBody ) ; this . setCallReference ( RS ) ; break ; case ParameterCompatibilityInformation . _PARAMETER_CODE : ParameterCompatibilityInformation pri = parameterFactory . createParameterCompatibilityInformation ( ) ; ( ( AbstractISUPParameter ) pri ) . decode ( parameterBody ) ; this . setParameterCompatibilityInformation ( pri ) ; break ; case NetworkSpecificFacility . _PARAMETER_CODE : NetworkSpecificFacility nsf = parameterFactory . createNetworkSpecificFacility ( ) ; ( ( AbstractISUPParameter ) nsf ) . decode ( parameterBody ) ; this . setNetworkSpecificFacility ( nsf ) ; break ; default : throw new ParameterException ( "Unrecognized parameter code for optional part: " + parameterCode ) ; } |
public class BaseUnitConverter { /** * Breaks down the unit value into a sequence of units , using the given divisors and
* allowed units . */
public List < UnitValue > sequence ( UnitValue value , UnitFactorSet factorSet ) { } } | value = convert ( value , factorSet . base ( ) ) ; boolean negative = false ; BigDecimal n = value . amount ( ) ; // Use absolute value for all comparisons .
if ( n . signum ( ) == - 1 ) { negative = true ; n = n . abs ( ) ; } List < UnitValue > result = new ArrayList < > ( ) ; List < UnitValue > factors = factorSet . factors ( ) ; int size = factors . size ( ) ; int last = size - 1 ; for ( int i = 0 ; i < size ; i ++ ) { UnitValue factor = factors . get ( i ) ; BigDecimal divisor = factor . amount ( ) ; if ( divisor == null ) { continue ; } if ( i == last && ( n . compareTo ( BigDecimal . ZERO ) != 0 || result . isEmpty ( ) ) ) { // Include decimals on the last unit .
int scale = n . precision ( ) + divisor . precision ( ) ; BigDecimal res = n . divide ( divisor , scale , RoundingMode . HALF_EVEN ) ; if ( negative && result . isEmpty ( ) ) { res = res . negate ( ) ; } result . add ( new UnitValue ( res . stripTrailingZeros ( ) , factor . unit ( ) ) ) ; } else if ( divisor . compareTo ( n ) <= 0 ) { BigDecimal [ ] res = n . divideAndRemainder ( divisor ) ; if ( negative && result . isEmpty ( ) ) { res [ 0 ] = res [ 0 ] . negate ( ) ; } result . add ( new UnitValue ( res [ 0 ] . stripTrailingZeros ( ) , factor . unit ( ) ) ) ; n = res [ 1 ] ; } } return result ; |
public class FadableImageSprite { /** * Sets the alpha value of this sprite . */
public void setAlpha ( float alpha ) { } } | if ( alpha < 0.0f ) { alpha = 0.0f ; } else if ( alpha > 1.0f ) { alpha = 1.0f ; } if ( alpha != _alphaComposite . getAlpha ( ) ) { _alphaComposite = AlphaComposite . getInstance ( AlphaComposite . SRC_OVER , alpha ) ; if ( _mgr != null ) { _mgr . getRegionManager ( ) . invalidateRegion ( _bounds ) ; } } |
public class JavacFileManager { /** * container is a directory , a zip file , or a non - existent path . */
private boolean isValidFile ( String s , Set < JavaFileObject . Kind > fileKinds ) { } } | JavaFileObject . Kind kind = getKind ( s ) ; return fileKinds . contains ( kind ) ; |
public class SpaceModifyingSnapshotTaskRunner { /** * Returns snapshot from the snapshot properties file if it exists
* @ param spaceId
* @ return snapshot from the snapshot properties file if it exists , otherwise null */
protected String getSnapshotIdFromProperties ( String spaceId ) { } } | Properties props = new Properties ( ) ; try ( InputStream is = this . snapshotProvider . getContent ( spaceId , Constants . SNAPSHOT_PROPS_FILENAME ) . getContentStream ( ) ) { props . load ( is ) ; return props . getProperty ( Constants . SNAPSHOT_ID_PROP ) ; } catch ( NotFoundException ex ) { return null ; } catch ( Exception e ) { throw new TaskException ( MessageFormat . format ( "Call to create snapshot failed, unable to determine existence of " + "snapshot properties file in {0}. Error: {1}" , spaceId , e . getMessage ( ) ) ) ; } |
public class FromXml { /** * Populate either the object o via setters or the Collection col by adding
* elements of type cl
* @ param o the object
* @ param subroot of XML data
* @ param col a collection
* @ param cl the class
* @ throws Throwable on error */
private void populate ( final Element subroot , final Object o , final Collection < Object > col , final Class cl ) throws Throwable { } } | if ( cb . skipElement ( subroot ) ) { return ; } Method meth = null ; Class elClass = cb . forElement ( subroot ) ; if ( col == null ) { /* We must have a setter */
meth = findSetter ( o , subroot ) ; if ( meth == null ) { error ( "No setter for " + subroot ) ; return ; } /* We require a single parameter */
final Class [ ] parClasses = meth . getParameterTypes ( ) ; if ( parClasses . length != 1 ) { error ( "Invalid setter method " + subroot ) ; throw new SAXException ( "Invalid setter method " + subroot ) ; } elClass = parClasses [ 0 ] ; } else if ( cl != null ) { elClass = cl ; } if ( elClass == null ) { error ( "No class for element " + subroot ) ; return ; } if ( ! XmlUtil . hasChildren ( subroot ) ) { /* A primitive value for which we should have a setter */
final Object val = simpleValue ( elClass , subroot ) ; if ( val == null ) { error ( "Unsupported par class " + elClass + " for field " + subroot ) ; throw new SAXException ( "Unsupported par class " + elClass + " for field " + subroot ) ; } assign ( val , subroot , col , o , meth ) ; return ; } /* There are children to this element . It either represents a complex type
* or a collection . */
if ( Collection . class . isAssignableFrom ( elClass ) ) { final Collection < Object > colVal ; if ( elClass . getName ( ) . equals ( "java.util.Set" ) ) { colVal = new TreeSet < > ( ) ; } else if ( elClass . getName ( ) . equals ( "java.util.List" ) ) { colVal = new ArrayList < > ( ) ; } else if ( elClass . getName ( ) . equals ( "java.util.Collection" ) ) { colVal = new ArrayList < > ( ) ; } else { error ( "Unsupported element class " + elClass + " for field " + subroot ) ; return ; } assign ( colVal , subroot , col , o , meth ) ; // Figure out the class of the elements
/* I thought I might be able to extract it from the generic info -
* Doesn ' t appear to be the case . */
final Type [ ] gpts = meth . getGenericParameterTypes ( ) ; /* Should only be one parameter */
if ( gpts . length != 1 ) { error ( "Unsupported type " + elClass + " with name " + subroot ) ; return ; } final Type gpt = gpts [ 0 ] ; if ( ! ( gpt instanceof ParameterizedType ) ) { error ( "Unsupported type " + elClass + " with name " + subroot ) ; return ; } final ParameterizedType aType = ( ParameterizedType ) gpt ; final Type [ ] parameterArgTypes = aType . getActualTypeArguments ( ) ; /* Should only be one arg */
if ( parameterArgTypes . length != 1 ) { error ( "Unsupported type " + elClass + " with name " + subroot ) ; return ; } final Type parameterArgType = parameterArgTypes [ 0 ] ; final Class colElType = ( Class ) parameterArgType ; /* ConfInfo ci = meth . getAnnotation ( ConfInfo . class ) ;
String colElTypeName ;
if ( ci = = null ) {
colElTypeName = " java . lang . String " ;
} else {
colElTypeName = ci . elementType ( ) ; */
for ( final Element el : XmlUtil . getElementsArray ( subroot ) ) { populate ( el , o , colVal , /* Class . forName ( colElTypeName ) */
colElType ) ; } return ; } /* Asssume a complex type */
final Object val = fromClass ( elClass ) ; assign ( val , subroot , col , o , meth ) ; for ( final Element el : XmlUtil . getElementsArray ( subroot ) ) { populate ( el , val , null , null ) ; } |
public class GraphHopper { /** * Removes the on - disc routing files . Call only after calling close or before importOrLoad or
* load */
public void clean ( ) { } } | if ( getGraphHopperLocation ( ) . isEmpty ( ) ) throw new IllegalStateException ( "Cannot clean GraphHopper without specified graphHopperLocation" ) ; File folder = new File ( getGraphHopperLocation ( ) ) ; removeDir ( folder ) ; |
public class OptionalRandomizer { /** * Create a new { @ link OptionalRandomizer } .
* @ param delegate the delegate randomizer to use
* @ param optionalPercent the optional percent threshold
* @ param < T > the type generated by this randomizer
* @ return a new { @ link OptionalRandomizer } */
public static < T > Randomizer < T > aNewOptionalRandomizer ( final Randomizer < T > delegate , final int optionalPercent ) { } } | return new OptionalRandomizer < > ( delegate , optionalPercent ) ; |
public class LocaleUtils { /** * Converts the given < code > baseName < / code > and < code > locale < / code > to the
* bundle name . This method is called from the default implementation of the
* { @ link # newBundle ( String , Locale , String , ClassLoader , boolean )
* newBundle } and
* { @ link # needsReload ( String , Locale , String , ClassLoader , ResourceBundle , long )
* needsReload } methods .
* This implementation returns the following value :
* < pre >
* baseName + & quot ; _ & quot ; + language + & quot ; _ & quot ; + country + & quot ; _ & quot ; + variant
* < / pre >
* where < code > language < / code > , < code > country < / code > and
* < code > variant < / code > are the language , country and variant values of
* < code > locale < / code > , respectively . Final component values that are empty
* Strings are omitted along with the preceding ' _ ' . If all of the values
* are empty strings , then < code > baseName < / code > is returned .
* For example , if < code > baseName < / code > is < code > " baseName " < / code > and
* < code > locale < / code > is < code > Locale ( " ja " , & nbsp ; " " , & nbsp ; " XX " ) < / code > ,
* then < code > " baseName _ ja _ & thinsp ; _ XX " < / code > is returned . If the given
* locale is < code > Locale ( " en " ) < / code > , then < code > " baseName _ en " < / code > is
* returned .
* Overriding this method allows applications to use different conventions
* in the organization and packaging of localized resources .
* @ param bundleBaseName
* the base name of the resource bundle , a fully qualified class
* name
* @ param locale
* the locale for which a resource bundle should be loaded
* @ return the bundle name for the resource bundle
* @ exception NullPointerException
* if < code > baseName < / code > or < code > locale < / code > is
* < code > null < / code > */
public static String toBundleName ( String bundleBaseName , Locale locale ) { } } | String baseName = bundleBaseName . replace ( '.' , '/' ) ; if ( locale == null ) { return baseName ; } String language = locale . getLanguage ( ) ; String country = locale . getCountry ( ) ; String variant = locale . getVariant ( ) ; if ( StringUtils . isEmpty ( language ) && StringUtils . isEmpty ( country ) && StringUtils . isEmpty ( variant ) ) { return baseName ; } StringBuilder sb = new StringBuilder ( baseName ) ; sb . append ( '_' ) ; if ( StringUtils . isNotEmpty ( variant ) ) { sb . append ( language ) . append ( '_' ) . append ( country ) . append ( '_' ) . append ( variant ) ; } else if ( StringUtils . isNotEmpty ( country ) ) { sb . append ( language ) . append ( '_' ) . append ( country ) ; } else { sb . append ( language ) ; } return sb . toString ( ) ; |
public class SuffixParser { /** * Extract the value of a named suffix part from this request ' s suffix
* @ param key key of the suffix part
* @ param defaultValue the default value to return if suffix part not set .
* Only String , Boolean , Integer , Long are supported .
* @ param < T > Parameter type .
* @ return the value of that named parameter ( or the default value if not used ) */
@ SuppressWarnings ( "unchecked" ) public < T > @ Nullable T get ( @ NotNull String key , @ Nullable T defaultValue ) { } } | if ( defaultValue instanceof String || defaultValue == null ) { return ( T ) getString ( key , ( String ) defaultValue ) ; } if ( defaultValue instanceof Boolean ) { return ( T ) ( Boolean ) getBoolean ( key , ( Boolean ) defaultValue ) ; } if ( defaultValue instanceof Integer ) { return ( T ) ( Integer ) getInt ( key , ( Integer ) defaultValue ) ; } if ( defaultValue instanceof Long ) { return ( T ) ( Long ) getLong ( key , ( Long ) defaultValue ) ; } throw new IllegalArgumentException ( "Unsupported type: " + defaultValue . getClass ( ) . getName ( ) ) ; |
public class AstFactory { /** * Creates a NAME node having the type of " this " appropriate for the given function node . */
Node createThisAliasReferenceForFunction ( String aliasName , Node functionNode ) { } } | final Node result = IR . name ( aliasName ) ; if ( isAddingTypes ( ) ) { result . setJSType ( getTypeOfThisForFunctionNode ( functionNode ) ) ; } return result ; |
public class HttpRequest { /** * 初始化网络连接 */
private void initConnecton ( ) { } } | this . httpConnection = HttpConnection . create ( URLUtil . toUrlForHttp ( this . url , this . urlHandler ) , this . proxy ) . setMethod ( this . method ) . setHttpsInfo ( this . hostnameVerifier , this . ssf ) . setConnectTimeout ( this . connectionTimeout ) . setReadTimeout ( this . readTimeout ) // 自定义Cookie
. setCookie ( this . cookie ) // 定义转发
. setInstanceFollowRedirects ( this . maxRedirectCount > 0 ? true : false ) // 覆盖默认Header
. header ( this . headers , true ) ; // 是否禁用缓存
if ( this . isDisableCache ) { this . httpConnection . disableCache ( ) ; } |
public class X509CertInfo { /** * Set the public key in the certificate .
* @ params val the Object class value for the PublicKey
* @ exception CertificateException on invalid data . */
private void setKey ( Object val ) throws CertificateException { } } | if ( ! ( val instanceof CertificateX509Key ) ) { throw new CertificateException ( "Key class type invalid." ) ; } pubKey = ( CertificateX509Key ) val ; |
public class GoogleMapShapeConverter { /** * Transform the bounding box in WGS84 to the feature projection
* @ param boundingBox bounding box in WGS84
* @ return bounding box in the feature projection */
public BoundingBox boundingBoxFromWgs84 ( BoundingBox boundingBox ) { } } | if ( projection == null ) { throw new GeoPackageException ( "Shape Converter projection is null" ) ; } return boundingBox . transform ( fromWgs84 ) ; |
public class Record { /** * Accessor method used to retrieve an Date instance representing the
* contents of an individual field . If the field does not exist in the
* record , null is returned .
* @ param field the index number of the field to be retrieved
* @ return the value of the required field
* @ throws MPXJException normally thrown when parsing fails */
public Date getTime ( int field ) throws MPXJException { } } | try { Date result ; if ( ( field < m_fields . length ) && ( m_fields [ field ] . length ( ) != 0 ) ) { result = m_formats . getTimeFormat ( ) . parse ( m_fields [ field ] ) ; } else { result = null ; } return ( result ) ; } catch ( ParseException ex ) { throw new MPXJException ( "Failed to parse time" , ex ) ; } |
public class ScreenRecordingUploadOptions { /** * Sets the credentials for remote ftp / http authentication ( if needed ) .
* This option only has an effect if remotePath is provided .
* @ param user The name of the user for the remote authentication .
* @ param pass The password for the remote authentication .
* @ return self instance for chaining . */
public ScreenRecordingUploadOptions withAuthCredentials ( String user , String pass ) { } } | this . user = checkNotNull ( user ) ; this . pass = checkNotNull ( pass ) ; return this ; |
public class Linker { /** * Returns the binding if it exists immediately . Otherwise this returns
* null . If the returned binding didn ' t exist or was unlinked , it will be
* enqueued to be linked .
* @ param mustHaveInjections true if the the referenced key requires either an
* { @ code @ Inject } annotation is produced by a { @ code @ Provides } method .
* This isn ' t necessary for Module . injects types because frameworks need
* to inject arbitrary classes like JUnit test cases and Android
* activities . It also isn ' t necessary for supertypes . */
public Binding < ? > requestBinding ( String key , Object requiredBy , ClassLoader classLoader , boolean mustHaveInjections , boolean library ) { } } | assertLockHeld ( ) ; Binding < ? > binding = null ; for ( Linker linker = this ; linker != null ; linker = linker . base ) { binding = linker . bindings . get ( key ) ; if ( binding != null ) { if ( linker != this && ! binding . isLinked ( ) ) throw new AssertionError ( ) ; break ; } } if ( binding == null ) { // We can ' t satisfy this binding . Make sure it ' ll work next time !
Binding < ? > deferredBinding = new DeferredBinding ( key , classLoader , requiredBy , mustHaveInjections ) ; deferredBinding . setLibrary ( library ) ; deferredBinding . setDependedOn ( true ) ; toLink . add ( deferredBinding ) ; attachSuccess = false ; return null ; } if ( ! binding . isLinked ( ) ) { toLink . add ( binding ) ; // This binding was never linked ; link it now !
} binding . setLibrary ( library ) ; binding . setDependedOn ( true ) ; return binding ; |
public class PropsReplacer { /** * Replace properties in given path using pattern
* @ param pattern - pattern to replace . First group should contains property name
* @ param path - given path to replace in
* @ param properties - list of properties using to replace
* @ return path with replaced properties */
private String replaceProps ( String pattern , String path , Properties properties ) { } } | Matcher matcher = Pattern . compile ( pattern ) . matcher ( path ) ; String replaced = path ; while ( matcher . find ( ) ) { replaced = replaced . replace ( matcher . group ( 0 ) , properties . getProperty ( matcher . group ( 1 ) , "" ) ) ; } return replaced ; |
public class AmazonEC2Client { /** * Registers an AMI . When you ' re creating an AMI , this is the final step you must complete before you can launch an
* instance from the AMI . For more information about creating AMIs , see < a
* href = " https : / / docs . aws . amazon . com / AWSEC2 / latest / UserGuide / creating - an - ami . html " > Creating Your Own AMIs < / a > in the
* < i > Amazon Elastic Compute Cloud User Guide < / i > .
* < note >
* For Amazon EBS - backed instances , < a > CreateImage < / a > creates and registers the AMI in a single request , so you
* don ' t have to register the AMI yourself .
* < / note >
* You can also use < code > RegisterImage < / code > to create an Amazon EBS - backed Linux AMI from a snapshot of a root
* device volume . You specify the snapshot using the block device mapping . For more information , see < a
* href = " https : / / docs . aws . amazon . com / AWSEC2 / latest / UserGuide / instance - launch - snapshot . html " > Launching a Linux
* Instance from a Backup < / a > in the < i > Amazon Elastic Compute Cloud User Guide < / i > .
* You can ' t register an image where a secondary ( non - root ) snapshot has AWS Marketplace product codes .
* Some Linux distributions , such as Red Hat Enterprise Linux ( RHEL ) and SUSE Linux Enterprise Server ( SLES ) , use
* the EC2 billing product code associated with an AMI to verify the subscription status for package updates .
* Creating an AMI from an EBS snapshot does not maintain this billing code , and instances launched from such an AMI
* are not able to connect to package update infrastructure . If you purchase a Reserved Instance offering for one of
* these Linux distributions and launch instances using an AMI that does not contain the required billing code , your
* Reserved Instance is not applied to these instances .
* To create an AMI for operating systems that require a billing code , see < a > CreateImage < / a > .
* If needed , you can deregister an AMI at any time . Any modifications you make to an AMI backed by an instance
* store volume invalidates its registration . If you make changes to an image , deregister the previous image and
* register the new image .
* @ param registerImageRequest
* Contains the parameters for RegisterImage .
* @ return Result of the RegisterImage operation returned by the service .
* @ sample AmazonEC2 . RegisterImage
* @ see < a href = " http : / / docs . aws . amazon . com / goto / WebAPI / ec2-2016-11-15 / RegisterImage " target = " _ top " > AWS API
* Documentation < / a > */
@ Override public RegisterImageResult registerImage ( RegisterImageRequest request ) { } } | request = beforeClientExecution ( request ) ; return executeRegisterImage ( request ) ; |
public class CmsProjectsTable { /** * Returns the available menu entries . < p >
* @ return the menu entries */
List < I_CmsSimpleContextMenuEntry < Set < CmsUUID > > > getMenuEntries ( ) { } } | if ( m_menuEntries == null ) { m_menuEntries = new ArrayList < I_CmsSimpleContextMenuEntry < Set < CmsUUID > > > ( ) ; m_menuEntries . add ( new ShowFilesEntry ( ) ) ; m_menuEntries . add ( new UnlockEntry ( ) ) ; m_menuEntries . add ( new PublishEntry ( ) ) ; m_menuEntries . add ( new EditEntry ( ) ) ; m_menuEntries . add ( new DeleteEntry ( ) ) ; } return m_menuEntries ; |
public class HebrewCalendar { /** * Return JD of start of given month / year . */
protected int handleComputeMonthStart ( int eyear , int month , boolean useMonth ) { } } | // Resolve out - of - range months . This is necessary in order to
// obtain the correct year . We correct to
// a 12 - or 13 - month year ( add / subtract 12 or 13 , depending
// on the year ) but since we _ always _ number from 0 . . 12 , and
// the leap year determines whether or not month 5 ( Adar 1)
// is present , we allow 0 . . 12 in any given year .
while ( month < 0 ) { month += monthsInYear ( -- eyear ) ; } // Careful : allow 0 . . 12 in all years
while ( month > 12 ) { month -= monthsInYear ( eyear ++ ) ; } long day = startOfYear ( eyear ) ; if ( month != 0 ) { if ( isLeapYear ( eyear ) ) { day += LEAP_MONTH_START [ month ] [ yearType ( eyear ) ] ; } else { day += MONTH_START [ month ] [ yearType ( eyear ) ] ; } } return ( int ) ( day + 347997 ) ; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.