signature stringlengths 43 39.1k | implementation stringlengths 0 450k |
|---|---|
public class SignalProperties { /** * Returns the signal properties as a Map . */
public Map < String , Collection < String > > toMap ( ) { } } | Map < String , Collection < String > > params = new HashMap < String , Collection < String > > ( ) ; if ( null != type ) { ArrayList < String > valueList = new ArrayList < String > ( ) ; valueList . add ( type ) ; params . put ( "type" , valueList ) ; } if ( null != data ) { ArrayList < String > valueList = new ArrayList < String > ( ) ; valueList . add ( data ) ; params . put ( "data" , valueList ) ; } return params ; |
public class PasswordStrengthView { /** * Checks that all the requirements are meet .
* @ param password the current password to validate
* @ return whether the given password complies with this password policy or not . */
public boolean isValid ( String password ) { } } | if ( password == null ) { return false ; } boolean length = hasMinimumLength ( password , getMinimumLength ( ) ) ; boolean other = true ; switch ( complexity . getPasswordPolicy ( ) ) { case PasswordStrength . EXCELLENT : boolean atLeast = atLeastThree ( hasLowercaseCharacters ( password ) , hasUppercaseCharacters ( password ) , hasNumericCharacters ( password ) , hasSpecialCharacters ( password ) ) ; other = hasIdenticalCharacters ( password ) && atLeast ; break ; case PasswordStrength . GOOD : other = atLeastThree ( hasLowercaseCharacters ( password ) , hasUppercaseCharacters ( password ) , hasNumericCharacters ( password ) , hasSpecialCharacters ( password ) ) ; break ; case PasswordStrength . FAIR : other = allThree ( hasLowercaseCharacters ( password ) , hasUppercaseCharacters ( password ) , hasNumericCharacters ( password ) ) ; break ; case PasswordStrength . LOW : case PasswordStrength . NONE : } return length && other ; |
public class Quaternionf { /** * / * ( non - Javadoc )
* @ see org . joml . Quaternionfc # transform ( org . joml . Vector4fc , org . joml . Vector4f ) */
public Vector4f transform ( Vector4fc vec , Vector4f dest ) { } } | return transform ( vec . x ( ) , vec . y ( ) , vec . z ( ) , dest ) ; |
public class FilterInvoker { /** * Buildmkey string .
* @ param methodName the method name
* @ param key the key
* @ return the string */
private String buildMethodKey ( String methodName , String key ) { } } | return RpcConstants . HIDE_KEY_PREFIX + methodName + RpcConstants . HIDE_KEY_PREFIX + key ; |
public class ReidSolomonCodes { /** * Given the input message compute the error correction code for it
* @ param input Input message . Modified internally then returned to its initial state
* @ param output error correction code */
public void computeECC ( GrowQueue_I8 input , GrowQueue_I8 output ) { } } | int N = generator . size - 1 ; input . extend ( input . size + N ) ; Arrays . fill ( input . data , input . size - N , input . size , ( byte ) 0 ) ; math . polyDivide ( input , generator , tmp0 , output ) ; input . size -= N ; |
public class ObjectFactory { /** * Create an instance of { @ link JAXBElement } { @ code < } { @ link ApplyType } { @ code > } } */
@ XmlElementDecl ( namespace = "http://www.w3.org/1998/Math/MathML" , name = "apply" ) public JAXBElement < ApplyType > createApply ( ApplyType value ) { } } | return new JAXBElement < ApplyType > ( _Apply_QNAME , ApplyType . class , null , value ) ; |
public class RemoteFieldTable { /** * Get the Handle to the last modified or added record .
* This uses some very inefficient ( and incorrect ) code . . . override if possible .
* NOTE : There is a huge concurrency problem with this logic if another person adds
* a record after you , you get the their ( wrong ) record , which is why you need to
* provide a solid implementation when you override this method .
* @ param iHandleType The handle type .
* @ return The bookmark . */
public Object getLastModified ( int iHandleType ) throws DBException { } } | if ( m_objLastModBookmark != null ) return m_objLastModBookmark ; // Override this to supply last modified .
else { try { return m_tableRemote . getLastModified ( iHandleType ) ; } catch ( RemoteException ex ) { ex . printStackTrace ( ) ; throw new DBException ( ex . getMessage ( ) ) ; } } |
public class AlertPolicy { /** * Sets the channels for the policy .
* @ param channelIds The channels for the policy */
public void setChannelIds ( List < Long > channelIds ) { } } | setChannels ( AlertPolicyChannel . builder ( ) . channelIds ( channelIds ) . build ( ) ) ; |
public class appqoepolicy { /** * Use this API to fetch all the appqoepolicy resources that are configured on netscaler . */
public static appqoepolicy [ ] get ( nitro_service service ) throws Exception { } } | appqoepolicy obj = new appqoepolicy ( ) ; appqoepolicy [ ] response = ( appqoepolicy [ ] ) obj . get_resources ( service ) ; return response ; |
public class AbstractMarkerLanguageParser { /** * Read the given input content and transform it in order to have a raw text .
* @ param content the content to parse .
* @ param inputFile the name of the input file for locating included features and formatting error messages .
* @ return the raw file content . */
public final String transform ( CharSequence content , File inputFile ) { } } | return transform ( content , inputFile , true ) ; |
public class ApiKeyRealm { /** * Test for whether an API key has a specific permission using its ID . */
public boolean hasPermissionById ( String id , String permission ) { } } | Permission resolvedPermission = getPermissionResolver ( ) . resolvePermission ( permission ) ; return hasPermissionById ( id , resolvedPermission ) ; |
public class Maven { /** * convenience method */
public void deploy ( RemoteRepository target , Artifact ... artifacts ) throws DeploymentException { } } | deploy ( target , null , Arrays . asList ( artifacts ) ) ; |
public class SnorocketOWLReasoner { /** * Gets the set of named data properties that are the strict ( potentially
* direct ) subproperties of the specified data property expression with
* respect to the imports closure of the root ontology . Note that the
* properties are returned as a
* { @ link NodeSet } .
* @ param pe
* The data property whose strict ( direct ) subproperties are to
* be retrieved .
* @ param direct
* Specifies if the direct subproperties should be retrived (
* < code > true < / code > ) or if the all subproperties ( descendants )
* should be retrieved ( < code > false < / code > ) .
* @ return If direct is < code > true < / code > , a < code > NodeSet < / code > such that
* for each property < code > P < / code > in the < code > NodeSet < / code > the
* set of reasoner axioms entails
* < code > DirectSubDataPropertyOf ( P , pe ) < / code > . < / p > If direct is
* < code > false < / code > , a < code > NodeSet < / code > such that for each
* property < code > P < / code > in the < code > NodeSet < / code > the set of
* reasoner axioms entails
* < code > StrictSubDataPropertyOf ( P , pe ) < / code > . < / p > If
* < code > pe < / code > is equivalent to
* < code > owl : bottomDataProperty < / code > then the empty
* < code > NodeSet < / code > will be returned .
* @ throws InconsistentOntologyException
* if the imports closure of the root ontology is inconsistent
* @ throws FreshEntitiesException
* if the signature of the data property is not contained within
* the signature of the imports closure of the root ontology and
* the undeclared entity policy of this reasoner is set to
* { @ link FreshEntityPolicy # DISALLOW } .
* @ throws ReasonerInterruptedException
* if the reasoning process was interrupted for any particular
* reason ( for example if reasoning was cancelled by a client
* process )
* @ throws TimeOutException
* if the reasoner timed out during a basic reasoning operation .
* See { @ link # getTimeOut ( ) } . */
@ Override public NodeSet < OWLDataProperty > getSubDataProperties ( OWLDataProperty pe , boolean direct ) throws InconsistentOntologyException , FreshEntitiesException , ReasonerInterruptedException , TimeOutException { } } | throw new ReasonerInternalException ( "getSubDataProperties not implemented" ) ; |
public class ProcessorConfigurationUtils { /** * Wraps an implementation of { @ link IProcessingInstructionProcessor } into an object that adds some information
* required internally ( like e . g . the dialect this processor was registered for ) .
* This method is meant for < strong > internal < / strong > use only .
* @ param processor the processor to be wrapped .
* @ param dialect the dialect this processor was configured for .
* @ return the wrapped processor . */
public static IProcessingInstructionProcessor wrap ( final IProcessingInstructionProcessor processor , final IProcessorDialect dialect ) { } } | Validate . notNull ( dialect , "Dialect cannot be null" ) ; if ( processor == null ) { return null ; } return new ProcessingInstructionProcessorWrapper ( processor , dialect ) ; |
public class MethodMarshaller { /** * Marshall the given parameter object . */
public void marshall ( Method method , ProtocolMarshaller protocolMarshaller ) { } } | if ( method == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( method . getHttpMethod ( ) , HTTPMETHOD_BINDING ) ; protocolMarshaller . marshall ( method . getAuthorizationType ( ) , AUTHORIZATIONTYPE_BINDING ) ; protocolMarshaller . marshall ( method . getAuthorizerId ( ) , AUTHORIZERID_BINDING ) ; protocolMarshaller . marshall ( method . getApiKeyRequired ( ) , APIKEYREQUIRED_BINDING ) ; protocolMarshaller . marshall ( method . getRequestValidatorId ( ) , REQUESTVALIDATORID_BINDING ) ; protocolMarshaller . marshall ( method . getOperationName ( ) , OPERATIONNAME_BINDING ) ; protocolMarshaller . marshall ( method . getRequestParameters ( ) , REQUESTPARAMETERS_BINDING ) ; protocolMarshaller . marshall ( method . getRequestModels ( ) , REQUESTMODELS_BINDING ) ; protocolMarshaller . marshall ( method . getMethodResponses ( ) , METHODRESPONSES_BINDING ) ; protocolMarshaller . marshall ( method . getMethodIntegration ( ) , METHODINTEGRATION_BINDING ) ; protocolMarshaller . marshall ( method . getAuthorizationScopes ( ) , AUTHORIZATIONSCOPES_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class ApiResource { /** * Invalidate null typed parameters .
* @ param url request url associated with the given parameters .
* @ param params typed parameters to check for null value . */
public static void checkNullTypedParams ( String url , ApiRequestParams params ) { } } | if ( params == null ) { throw new IllegalArgumentException ( String . format ( "Found null params for %s. " + "Please pass empty params using param builder via `builder().build()` instead." , url ) ) ; } |
public class Swift { /** * If path references a folder , this is a lengthly operation because all sub - objects must be deleted one by one . ( as
* of 2014-02 , hubic swift does not seem to support bulk deletes :
* http : / / docs . openstack . org / developer / swift / middleware . html # module - swift . common . middleware . bulk )
* @ param path The file path */
public boolean delete ( CPath path ) throws CStorageException { } } | // Request sub - objects w / o delimiter : all sub - objects are returned
// In case c _ path is a blob , we ' ll get an empty list
JSONArray array = listObjectsWithinFolder ( path , null ) ; LOGGER . debug ( "List objects with folder {} = {}" , path , array ) ; // Now delete all objects ; we start with the deepest ones so that
// in case we are interrupted , directory markers are still present
// Note : swift may guarantee that list is ordered , but could not confirm information . . .
List < String > pathnames = new ArrayList < String > ( array . length ( ) + 1 ) ; JSONObject obj ; for ( int i = 0 ; i < array . length ( ) ; i ++ ) { obj = array . getJSONObject ( i ) ; pathnames . add ( "/" + obj . getString ( "name" ) ) ; } Collections . sort ( pathnames ) ; Collections . reverse ( pathnames ) ; // Now we also add that top - level folder ( or blob ) to delete :
pathnames . add ( path . getPathName ( ) ) ; boolean atLeastOneDeleted = false ; for ( String pathname : pathnames ) { LOGGER . debug ( "deleting object at path : {}" , pathname ) ; String url = getObjectUrl ( new CPath ( pathname ) ) ; CResponse response = null ; try { RequestInvoker < CResponse > ri = getApiRequestInvoker ( new HttpDelete ( url ) , path ) ; response = retryStrategy . invokeRetry ( ri ) ; atLeastOneDeleted = true ; } catch ( CFileNotFoundException ex ) { // continue
} finally { PcsUtils . closeQuietly ( response ) ; } } return atLeastOneDeleted ; |
public class StringUtil { /** * @ param source
* @ param token
* @ return */
public static List < Long > parseStringToLongList ( String source , String token ) { } } | if ( StringUtils . isBlank ( source ) || StringUtils . isEmpty ( token ) ) { return null ; } List < Long > result = new ArrayList < Long > ( ) ; String [ ] units = source . split ( token ) ; for ( String unit : units ) { result . add ( Long . valueOf ( unit ) ) ; } return result ; |
public class ArrayHelper { /** * Get the component type of the array ( the type of which the array is made
* up )
* @ param < ELEMENTTYPE >
* The component type of the array
* @ param aArray
* The array to get the type from . May not be < code > null < / code > .
* @ return The class that determines a single element of the array . */
@ Nonnull public static < ELEMENTTYPE > Class < ? extends ELEMENTTYPE > getComponentType ( @ Nonnull final ELEMENTTYPE [ ] aArray ) { } } | ValueEnforcer . notNull ( aArray , "Array" ) ; final Class < ? > aComponentType = aArray . getClass ( ) . getComponentType ( ) ; return GenericReflection . uncheckedCast ( aComponentType ) ; |
public class KeyStoreServiceImpl { /** * { @ inheritDoc } */
@ Override public String getKeyStoreLocation ( String keyStoreName ) throws KeyStoreException { } } | WSKeyStore ks = ksMgr . getKeyStore ( keyStoreName ) ; if ( ks != null ) { return ks . getLocation ( ) ; } else { throw new KeyStoreException ( "The keystore [" + keyStoreName + "] is not present in the configuration" ) ; } |
public class FileChooserView { /** * Command to open the file chooser . */
protected void openFileChooser ( ) { } } | if ( m_model . getShowDialog ( ) ) { if ( m_fileChooser . showOpenDialog ( m_parent ) == JFileChooser . APPROVE_OPTION ) { m_model . setFile ( m_fileChooser . getSelectedFile ( ) ) ; } m_model . setShowDialog ( false ) ; } |
public class ByteArrayWrapper { /** * Copies the contents of src byte array from offset srcoff to the
* target of tgt byte array at the offset tgtoff .
* @ param src source byte array to copy from
* @ param srcoff start offset of src to copy from
* @ param tgt target byte array to copy to
* @ param tgtoff start offset of tgt to copy to
* @ param length size of contents to copy */
private static final void copyBytes ( byte [ ] src , int srcoff , byte [ ] tgt , int tgtoff , int length ) { } } | if ( length < 64 ) { for ( int i = srcoff , n = tgtoff ; -- length >= 0 ; ++ i , ++ n ) { tgt [ n ] = src [ i ] ; } } else { System . arraycopy ( src , srcoff , tgt , tgtoff , length ) ; } |
public class CmsSiteManagerImpl { /** * Initializes the workplace matchers . < p > */
private void initWorkplaceMatchers ( ) { } } | List < CmsSiteMatcher > matchers = new ArrayList < CmsSiteMatcher > ( ) ; if ( ! m_workplaceServers . isEmpty ( ) ) { Map < String , CmsSiteMatcher > matchersByUrl = Maps . newHashMap ( ) ; for ( String server : m_workplaceServers . keySet ( ) ) { CmsSSLMode mode = m_workplaceServers . get ( server ) ; CmsSiteMatcher matcher = new CmsSiteMatcher ( server ) ; if ( ( mode == CmsSSLMode . LETS_ENCRYPT ) || ( mode == CmsSSLMode . MANUAL_EP_TERMINATION ) ) { CmsSiteMatcher httpMatcher = matcher . forDifferentScheme ( "http" ) ; CmsSiteMatcher httpsMatcher = matcher . forDifferentScheme ( "https" ) ; for ( CmsSiteMatcher current : new CmsSiteMatcher [ ] { httpMatcher , httpsMatcher } ) { matchersByUrl . put ( current . getUrl ( ) , current ) ; if ( CmsLog . INIT . isInfoEnabled ( ) ) { CmsLog . INIT . info ( Messages . get ( ) . getBundle ( ) . key ( Messages . INIT_WORKPLACE_SITE_1 , matcher ) ) ; } } } else { matchersByUrl . put ( matcher . getUrl ( ) , matcher ) ; if ( CmsLog . INIT . isInfoEnabled ( ) ) { CmsLog . INIT . info ( Messages . get ( ) . getBundle ( ) . key ( Messages . INIT_WORKPLACE_SITE_1 , matcher ) ) ; } } } matchers = Lists . newArrayList ( matchersByUrl . values ( ) ) ; } else if ( CmsLog . INIT . isInfoEnabled ( ) ) { CmsLog . INIT . info ( Messages . get ( ) . getBundle ( ) . key ( Messages . INIT_WORKPLACE_SITE_0 ) ) ; } m_workplaceMatchers = matchers ; |
public class TimePoint { /** * / * [ deutsch ]
* < p > Ermittelt die ( meist normalisierte ) Zeitspanne zwischen dieser
* Bezugszeit und dem Endzeitpunkt in der angegebenen Metrik . < / p >
* @ param < P > generic type of time span result
* @ param end end time point
* @ param metric temporal distance metric
* @ return difference between this and given end time point
* expressed as time span
* @ throws ArithmeticException in case of numerical overflow */
public < P > P until ( T end , TimeMetric < ? extends U , P > metric ) { } } | return metric . between ( this . getContext ( ) , end ) ; |
public class MwsConnection { /** * Call an operation and return the response data .
* @ param requestData
* The request data .
* @ return The response data . */
@ SuppressWarnings ( "unchecked" ) public < T extends MwsObject > T call ( MwsRequestType type , MwsObject requestData ) { } } | MwsReader responseReader = null ; try { String servicePath = type . getServicePath ( ) ; String operationName = type . getOperationName ( ) ; MwsCall mc = newCall ( servicePath , operationName ) ; requestData . writeFragmentTo ( mc ) ; responseReader = mc . invoke ( ) ; MwsResponseHeaderMetadata rhmd = mc . getResponseHeaderMetadata ( ) ; MwsObject response = MwsUtl . newInstance ( type . getResponseClass ( ) ) ; type . setRHMD ( response , rhmd ) ; response . readFragmentFrom ( responseReader ) ; return ( T ) response ; } catch ( Exception e ) { throw type . wrapException ( e ) ; } finally { MwsUtl . close ( responseReader ) ; } |
public class ConnectionProxy { /** * Creates new SQL Connection Proxy instance
* @ param conn SQL Connection
* @ return Proxy SQL Connection */
public static Connection newInstance ( Connection conn ) { } } | return ( Connection ) java . lang . reflect . Proxy . newProxyInstance ( Connection . class . getClassLoader ( ) , new Class [ ] { Connection . class } , new ConnectionProxy ( conn ) ) ; /* return ( Connection ) java . lang . reflect . Proxy . newProxyInstance ( conn . getClass ( ) . getClassLoader ( ) , conn . getClass ( ) . getInterfaces ( ) ,
new ConnectionProxy ( conn ) ) ; */ |
public class NettySctpManagementImpl { /** * ( non - Javadoc )
* @ see org . mobicents . protocols . api . Management # addServerAssociation ( java . lang . String , int , java . lang . String ,
* java . lang . String , org . mobicents . protocols . api . IpChannelType ) */
@ Override public Association addServerAssociation ( String peerAddress , int peerPort , String serverName , String assocName , IpChannelType ipChannelType ) throws Exception { } } | if ( ! this . started ) { throw new Exception ( String . format ( "Management=%s not started" , this . name ) ) ; } if ( peerAddress == null ) { throw new Exception ( "Peer address cannot be null" ) ; } if ( peerPort < 0 ) { throw new Exception ( "Peer port cannot be less than 0" ) ; } if ( serverName == null ) { throw new Exception ( "Server name cannot be null" ) ; } if ( assocName == null ) { throw new Exception ( "Association name cannot be null" ) ; } synchronized ( this ) { if ( this . associations . get ( assocName ) != null ) { throw new Exception ( String . format ( "Already has association=%s" , assocName ) ) ; } Server server = null ; for ( FastList . Node < Server > n = this . servers . head ( ) , end = this . servers . tail ( ) ; ( n = n . getNext ( ) ) != end ; ) { Server serverTemp = n . getValue ( ) ; if ( serverTemp . getName ( ) . equals ( serverName ) ) { server = serverTemp ; } } if ( server == null ) { throw new Exception ( String . format ( "No Server found for name=%s" , serverName ) ) ; } for ( FastMap . Entry < String , Association > n = this . associations . head ( ) , end = this . associations . tail ( ) ; ( n = n . getNext ( ) ) != end ; ) { Association associationTemp = n . getValue ( ) ; if ( associationTemp . getServerName ( ) . equals ( server . getName ( ) ) && peerAddress . equals ( associationTemp . getPeerAddress ( ) ) && associationTemp . getPeerPort ( ) == peerPort ) { throw new Exception ( String . format ( "Already has association=%s with same peer address=%s and port=%d" , associationTemp . getName ( ) , peerAddress , peerPort ) ) ; } } if ( server . getIpChannelType ( ) != ipChannelType ) throw new Exception ( String . format ( "Server and Accociation has different IP channel type" ) ) ; NettyAssociationImpl association = new NettyAssociationImpl ( peerAddress , peerPort , serverName , assocName , ipChannelType ) ; association . setManagement ( this ) ; NettyAssociationMap < String , Association > newAssociations = new NettyAssociationMap < String , Association > ( ) ; newAssociations . putAll ( this . associations ) ; newAssociations . put ( assocName , association ) ; this . associations = newAssociations ; // this . associations . put ( assocName , association ) ;
FastList < String > newAssociations2 = new FastList < String > ( ) ; newAssociations2 . addAll ( ( ( NettyServerImpl ) server ) . associations ) ; newAssociations2 . add ( assocName ) ; ( ( NettyServerImpl ) server ) . associations = newAssociations2 ; // ( ( ServerImpl ) server ) . associations . add ( assocName ) ;
this . store ( ) ; for ( ManagementEventListener lstr : managementEventListeners ) { try { lstr . onAssociationAdded ( association ) ; } catch ( Throwable ee ) { logger . error ( "Exception while invoking onAssociationAdded" , ee ) ; } } if ( logger . isInfoEnabled ( ) ) { logger . info ( String . format ( "Added Associoation=%s of type=%s" , association . getName ( ) , association . getAssociationType ( ) ) ) ; } return association ; } |
public class RunbookDraftsInner { /** * Publish runbook draft .
* @ param resourceGroupName Name of an Azure Resource group .
* @ param automationAccountName The name of the automation account .
* @ param runbookName The parameters supplied to the publish runbook operation .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the observable for the request */
public Observable < ServiceResponseWithHeaders < Void , RunbookDraftPublishHeaders > > publishWithServiceResponseAsync ( String resourceGroupName , String automationAccountName , String runbookName ) { } } | if ( this . client . subscriptionId ( ) == null ) { throw new IllegalArgumentException ( "Parameter this.client.subscriptionId() is required and cannot be null." ) ; } if ( resourceGroupName == null ) { throw new IllegalArgumentException ( "Parameter resourceGroupName is required and cannot be null." ) ; } if ( automationAccountName == null ) { throw new IllegalArgumentException ( "Parameter automationAccountName is required and cannot be null." ) ; } if ( runbookName == null ) { throw new IllegalArgumentException ( "Parameter runbookName is required and cannot be null." ) ; } final String apiVersion = "2015-10-31" ; Observable < Response < ResponseBody > > observable = service . publish ( this . client . subscriptionId ( ) , resourceGroupName , automationAccountName , runbookName , apiVersion , this . client . acceptLanguage ( ) , this . client . userAgent ( ) ) ; return client . getAzureClient ( ) . getPostOrDeleteResultWithHeadersAsync ( observable , new TypeToken < Void > ( ) { } . getType ( ) , RunbookDraftPublishHeaders . class ) ; |
public class Chronic { /** * DIFF : We return Span instead of Date */
protected static Span guess ( Span span ) { } } | if ( span == null ) { return null ; } long guessValue ; if ( span . getWidth ( ) > 1 ) { guessValue = span . getBegin ( ) + ( span . getWidth ( ) / 2 ) ; } else { guessValue = span . getBegin ( ) ; } Span guess = new Span ( guessValue , guessValue ) ; return guess ; |
public class DatabaseMapping { /** * Returns the name of the Identifier property
* @ param tableRef the < code > TableRef < / code > for the table
* @ return the name of the identifier property , or null if the table specified by the < code > tableRef < / code >
* parameter is not mapped
* @ throws IllegalStateException if the map ( ) method has not been invoked first . */
public String getIdProperty ( TableRef tableRef ) { } } | TableMapping tableMapping = mappedClasses . get ( tableRef ) ; if ( tableMapping == null ) { return null ; } ColumnMetaData identifierColumn = tableMapping . getIdentifierColumn ( ) ; return tableMapping . getColumnMapping ( identifierColumn ) . getPropertyName ( ) ; |
public class SystemUtil { /** * Returns server IP address ( v4 or v6 ) bound to local NIC . If multiple NICs are present , choose ' eth0 ' or ' en0 ' or
* any one with name ending with 0 . If non found , take first on the list that is not localhost . If no NIC
* present ( relevant only for desktop deployments ) , return loopback address . */
public static String getServerIPv4 ( ) { } } | String candidateAddress = null ; try { Enumeration < NetworkInterface > nics = NetworkInterface . getNetworkInterfaces ( ) ; while ( nics . hasMoreElements ( ) ) { NetworkInterface nic = nics . nextElement ( ) ; Enumeration < InetAddress > inetAddresses = nic . getInetAddresses ( ) ; while ( inetAddresses . hasMoreElements ( ) ) { String address = inetAddresses . nextElement ( ) . getHostAddress ( ) ; String nicName = nic . getName ( ) ; if ( nicName . startsWith ( "eth0" ) || nicName . startsWith ( "en0" ) ) { return address ; } if ( nicName . endsWith ( "0" ) || candidateAddress == null ) { candidateAddress = address ; } } } } catch ( SocketException e ) { throw new RuntimeException ( "Cannot resolve local network address" , e ) ; } return candidateAddress == null ? "127.0.0.1" : candidateAddress ; |
public class TiledMap { /** * Get the global ID of a tile at specified location in the map
* @ param x
* The x location of the tile
* @ param y
* The y location of the tile
* @ param layerIndex
* The index of the layer to retireve the tile from
* @ return The global ID of the tile */
public int getTileId ( int x , int y , int layerIndex ) { } } | Layer layer = ( Layer ) layers . get ( layerIndex ) ; return layer . getTileID ( x , y ) ; |
public class ProfilerTimerFilter { /** * Profile a SessionIdle event . This method will gather the following
* informations :
* - the method duration
* - the shortest execution time
* - the slowest execution time
* - the average execution time
* - the global number of calls
* @ param nextFilter The filter to call next
* @ param session The associated session
* @ param status The session ' s status */
@ Override public void sessionIdle ( NextFilter nextFilter , IoSession session , IdleStatus status ) throws Exception { } } | if ( profileSessionIdle ) { long start = timeNow ( ) ; nextFilter . sessionIdle ( session , status ) ; long end = timeNow ( ) ; sessionIdleTimerWorker . addNewDuration ( end - start ) ; } else { nextFilter . sessionIdle ( session , status ) ; } |
public class TimeService { /** * get server time in ms
* @ return the server time in ms */
@ GET @ Produces ( { } } | MediaType . TEXT_PLAIN } ) public String getTime ( ) { return String . valueOf ( System . currentTimeMillis ( ) ) ; |
public class CommandParser { /** * Reads an argument of type " number " from the request . */
public long number ( ImapRequestLineReader request ) throws ProtocolException { } } | String digits = consumeWord ( request , new DigitCharValidator ( ) ) ; return Long . parseLong ( digits ) ; |
public class AuthInterface { /** * Get the OAuth request token - this is step one of authorization .
* @ param callbackUrl
* optional callback URL - required for web auth flow , will be set to " oob " if not specified .
* @ return the { @ link OAuth1RequestToken } , store this for when the user returns from the Flickr website . */
public OAuth1RequestToken getRequestToken ( String callbackUrl ) { } } | String callback = ( callbackUrl != null ) ? callbackUrl : OUT_OF_BOUND_AUTH_METHOD ; OAuth10aService service = new ServiceBuilder ( apiKey ) . apiSecret ( sharedSecret ) . callback ( callback ) . build ( FlickrApi . instance ( ) ) ; try { return service . getRequestToken ( ) ; } catch ( IOException | InterruptedException | ExecutionException e ) { throw new FlickrRuntimeException ( e ) ; } |
public class ConnectionManager { /** * Stop offering shared dbserver sessions . */
public synchronized void stop ( ) { } } | if ( isRunning ( ) ) { running . set ( false ) ; DeviceFinder . getInstance ( ) . removeDeviceAnnouncementListener ( announcementListener ) ; dbServerPorts . clear ( ) ; for ( Client client : openClients . values ( ) ) { try { client . close ( ) ; } catch ( Exception e ) { logger . warn ( "Problem closing " + client + " when stopping" , e ) ; } } openClients . clear ( ) ; useCounts . clear ( ) ; deliverLifecycleAnnouncement ( logger , false ) ; } |
public class MavenWorkingSessionImpl { /** * utility methods */
private static boolean isIdIncluded ( Collection < RemoteRepository > repositories , RemoteRepository candidate ) { } } | for ( RemoteRepository r : repositories ) { if ( r . getId ( ) . equals ( candidate . getId ( ) ) ) { return true ; } } return false ; |
public class HttpStatusSetter { /** * Sets the status code .
* @ param httpStatus the http status code
* @ param translet the Translet instance */
public static void setStatus ( HttpStatus httpStatus , Translet translet ) { } } | translet . getResponseAdapter ( ) . setStatus ( httpStatus . value ( ) ) ; |
public class DescribeSpotInstanceRequestsRequest { /** * This method is intended for internal use only . Returns the marshaled request configured with additional
* parameters to enable operation dry - run . */
@ Override public Request < DescribeSpotInstanceRequestsRequest > getDryRunRequest ( ) { } } | Request < DescribeSpotInstanceRequestsRequest > request = new DescribeSpotInstanceRequestsRequestMarshaller ( ) . marshall ( this ) ; request . addParameter ( "DryRun" , Boolean . toString ( true ) ) ; return request ; |
public class Timer { /** * Returns the scheduled executor service used by all timed tasks in Jenkins .
* @ return the single { @ link ScheduledExecutorService } . */
@ Nonnull public static synchronized ScheduledExecutorService get ( ) { } } | if ( executorService == null ) { // corePoolSize is set to 10 , but will only be created if needed .
// ScheduledThreadPoolExecutor " acts as a fixed - sized pool using corePoolSize threads "
// TODO consider also wrapping in ContextResettingExecutorService
executorService = new ImpersonatingScheduledExecutorService ( new ErrorLoggingScheduledThreadPoolExecutor ( 10 , new NamingThreadFactory ( new ClassLoaderSanityThreadFactory ( new DaemonThreadFactory ( ) ) , "jenkins.util.Timer" ) ) , ACL . SYSTEM ) ; } return executorService ; |
public class UBench { /** * Include a long - specialized named task in to the benchmark .
* @ param name
* The name of the task . Only one task with any one name is
* allowed .
* @ param task
* The task to perform
* @ return The same object , for chaining calls . */
public UBench addLongTask ( String name , LongSupplier task ) { } } | return addLongTask ( name , task , null ) ; |
public class JbcSrcRuntime { /** * Casts the given type to SoyString or throws a ClassCastException . */
public static SoyString checkSoyString ( Object o ) { } } | // if it isn ' t a sanitized content we don ' t want to warn and if it isn ' t a soystring we should
// always fail .
if ( o instanceof SoyString && o instanceof SanitizedContent && ( ( SanitizedContent ) o ) . getContentKind ( ) != ContentKind . TEXT && logger . isLoggable ( Level . WARNING ) ) { logger . log ( Level . WARNING , String . format ( "Passing in sanitized content into a template that accepts only string is forbidden. " + " Please modify the template to take in %s." , ( ( SanitizedContent ) o ) . getContentKind ( ) ) , new Exception ( ) ) ; } return ( SoyString ) o ; |
public class TransportFactory { /** * Inject the given resources plus all available transport acceptors and connectors into every available acceptor
* and connector .
* @ param resources Resources that should be injected ( in addition to available transport acceptors and connectors )
* @ return A map containing the given input resources plus entries for the acceptor and connector of each available
* transport . This can be used to inject resources into other objects which require acceptors or connectors to be injected . */
public Map < String , Object > injectResources ( Map < String , Object > resources ) { } } | Map < String , Object > allResources = new HashMap < > ( resources ) ; for ( Entry < String , Transport > entry : transportsByName . entrySet ( ) ) { allResources . put ( entry . getKey ( ) + ".acceptor" , entry . getValue ( ) . getAcceptor ( ) ) ; allResources . put ( entry . getKey ( ) + ".connector" , entry . getValue ( ) . getConnector ( ) ) ; } for ( Transport transport : transportsByName . values ( ) ) { BridgeAcceptor acceptor = transport . getAcceptor ( ) ; if ( acceptor != null ) { injectResources ( acceptor , allResources ) ; } BridgeConnector connector = transport . getConnector ( ) ; if ( connector != null ) { injectResources ( transport . getConnector ( ) , allResources ) ; } for ( Object extension : transport . getExtensions ( ) ) { injectResources ( extension , allResources ) ; } } return allResources ; |
public class RxComapi { /** * Build SDK client . Can be called only once in onCreate callback on Application class . */
public static Observable < RxComapiClient > initialise ( @ NonNull Application app , @ NonNull ComapiConfig config ) { } } | String error = checkIfCanInitialise ( app , config , false ) ; if ( ! TextUtils . isEmpty ( error ) ) { return Observable . error ( new Exception ( error ) ) ; } RxComapiClient client = new RxComapiClient ( config ) ; return client . initialise ( app , config . getCallbackAdapter ( ) != null ? config . getCallbackAdapter ( ) : new CallbackAdapter ( ) , client ) ; |
public class ISO9660Config { /** * Set Interchange Level < br > 1 : Filenames 8 + 3 , directories 8 characters < br > 2 : Filenames 30 , directories 31
* characters < br > 3 : multiple File Sections ( files > 2 GB )
* @ param level 1 , 2 or 3
* @ throws com . github . stephenc . javaisotools . iso9660 . ConfigException Invalid or unsupported Interchange Level */
public void setInterchangeLevel ( int level ) throws ConfigException { } } | if ( level < 1 || level > 3 ) { throw new ConfigException ( this , "Invalid ISO9660 Interchange Level: " + level ) ; } if ( level == 3 ) { throw new ConfigException ( this , "Interchange Level 3 (multiple File Sections per file) is not (yet) supported by this implementation." ) ; } ISO9660NamingConventions . INTERCHANGE_LEVEL = level ; |
public class JsApiHdrsImpl { /** * Set the contents of the encoding field in the message payload part .
* d395685
* @ param value the Object value of the Encoding ( for MQ ) be set into the encoding field */
final void setEncoding ( Object value ) { } } | if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . entry ( this , tc , "setEncoding" , value ) ; // If the value is null or unsuitable , then clear the field
if ( ( value == null ) || ! ( value instanceof Integer ) ) { jmo . getPayloadPart ( ) . setField ( JsPayloadAccess . ENCODING , JsPayloadAccess . IS_ENCODING_EMPTY ) ; } // If it does exist and is an Integer , then we just store it
else { jmo . getPayloadPart ( ) . setField ( JsPayloadAccess . ENCODING_DATA , value ) ; } if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . exit ( this , tc , "setEncoding" ) ; |
public class CampaignLimitsMarshaller { /** * Marshall the given parameter object . */
public void marshall ( CampaignLimits campaignLimits , ProtocolMarshaller protocolMarshaller ) { } } | if ( campaignLimits == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( campaignLimits . getDaily ( ) , DAILY_BINDING ) ; protocolMarshaller . marshall ( campaignLimits . getMaximumDuration ( ) , MAXIMUMDURATION_BINDING ) ; protocolMarshaller . marshall ( campaignLimits . getMessagesPerSecond ( ) , MESSAGESPERSECOND_BINDING ) ; protocolMarshaller . marshall ( campaignLimits . getTotal ( ) , TOTAL_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class AvatarShellCommand { /** * For commands that directly obtain information from zk */
void noZeroOrOneOrAddress ( String command ) { } } | if ( isZeroCommand || isOneCommand ) { throwException ( CMD + command + " (zero|one) should not be specified" ) ; } if ( isAddressCommand ) { throwException ( CMD + command + " address should not be specified" ) ; } |
public class WebFragmentTypeImpl { /** * If not already created , a new < code > listener < / code > element will be created and returned .
* Otherwise , the first existing < code > listener < / code > element will be returned .
* @ return the instance defined for the element < code > listener < / code > */
public ListenerType < WebFragmentType < T > > getOrCreateListener ( ) { } } | List < Node > nodeList = childNode . get ( "listener" ) ; if ( nodeList != null && nodeList . size ( ) > 0 ) { return new ListenerTypeImpl < WebFragmentType < T > > ( this , "listener" , childNode , nodeList . get ( 0 ) ) ; } return createListener ( ) ; |
public class KeywordFilterMarshaller { /** * Marshall the given parameter object . */
public void marshall ( KeywordFilter keywordFilter , ProtocolMarshaller protocolMarshaller ) { } } | if ( keywordFilter == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( keywordFilter . getValue ( ) , VALUE_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class XidManager { /** * Called at server startup to rebuild our list of indoubt
* transactions from the datastore .
* @ param PM The PersistentMessageStore to use to access our datastore .
* @ exception TransactionException
* Thrown if any unexpected exceptions occur .
* @ throws SevereMessageStoreException */
public void restart ( PersistentMessageStore PM ) throws TransactionException , SevereMessageStoreException { } } | if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . entry ( this , tc , "restart" , "PersistenceManager=" + PM ) ; if ( PM != null ) { // We need to store the PM so that we can call
// it during transaction completion .
if ( PM instanceof PersistenceManager ) { _persistence = ( PersistenceManager ) PM ; } else { // We don ' t have a valid PersistenceManager so we
// are up the spout . Need to fall over in a big heap .
if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEventEnabled ( ) ) SibTr . event ( this , tc , "No PersistenceManager provided at startup. MessageStore cannot continue!" ) ; if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . exit ( this , tc , "restart" ) ; throw new SevereMessageStoreException ( "UNRECOVERABLE_ERROR_SIMS1499" , new Object [ ] { } ) ; } // We need to read our indoubt xid list in preperation
// for a call from the transaction manager at recovery
// time .
try { List list = PM . readIndoubtXIDs ( ) ; Iterator iterator = list . iterator ( ) ; while ( iterator . hasNext ( ) ) { PersistentTranId ptid = ( PersistentTranId ) iterator . next ( ) ; _indoubtXids . add ( ptid ) ; synchronized ( _associationLock ) { _unassociatedTrans . put ( ptid , new XidParticipant ( _ms , ptid , _persistence , 0 , TransactionState . STATE_PREPARED ) ) ; } if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isDebugEnabled ( ) ) SibTr . debug ( this , tc , "Indoubt Transaction Re-instated from database: " + ptid ) ; } } catch ( PersistenceException pe ) { com . ibm . ws . ffdc . FFDCFilter . processException ( pe , "com.ibm.ws.sib.msgstore.transactions.XidManager.restart" , "1:516:1.62" ) ; if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEventEnabled ( ) ) SibTr . event ( this , tc , "Persistence exception caught reading indoubt transactions from database!" , pe ) ; if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . exit ( this , tc , "restart" ) ; throw new TransactionException ( "UNEXPECTED_EXCEPTION_SIMS1099" , new Object [ ] { pe } , pe ) ; } } else { // We don ' t have a valid PersistenceManager so we
// are up the spout . Need to fall over in a big heap .
if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEventEnabled ( ) ) SibTr . event ( this , tc , "PersistenceManager is null. MessageStore cannot continue!" ) ; if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . exit ( this , tc , "restart" ) ; throw new SevereMessageStoreException ( "UNRECOVERABLE_ERROR_SIMS1499" , new Object [ ] { } ) ; } if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . exit ( this , tc , "restart" ) ; |
public class TypeRegistry { /** * To avoid leaking permgen we want to periodically discard the child classloader and recreate a new one . We will
* need to then redefine types again over time as they are used ( the most recent variants of them ) .
* @ param currentlyDefining the reloadable type currently being defined reloaded */
public void checkChildClassLoader ( ReloadableType currentlyDefining ) { } } | ChildClassLoader ccl = childClassLoader == null ? null : childClassLoader . get ( ) ; int definedCount = ( ccl == null ? 0 : ccl . getDefinedCount ( ) ) ; long time = System . currentTimeMillis ( ) ; // Don ' t do this more than every 5 seconds - that allows for situations where a lot of types are being redefined all in one go
if ( definedCount > maxClassDefinitions && ( ( time - lastTidyup ) > 5000 ) ) { lastTidyup = time ; if ( GlobalConfiguration . isRuntimeLogging && log . isLoggable ( Level . INFO ) ) { log . info ( "Recreating the typeregistry managed classloader, limit(#" + GlobalConfiguration . maxClassDefinitions + ") reached" ) ; } ccl = new ChildClassLoader ( classLoader . get ( ) ) ; this . childClassLoader = new WeakReference < ChildClassLoader > ( ccl ) ; // Need to tidy up all the links to this classloader !
for ( int i = 0 ; i < reloadableTypesSize ; i ++ ) { ReloadableType rtype = reloadableTypes [ i ] ; if ( rtype != null && rtype != currentlyDefining ) { rtype . clearClassloaderLinks ( ) ; // TODO [ performance ] could avoid doing this now - that would mean we would have to do it
// ' on demand ' and that would add an extra check to every operation
rtype . reloadMostRecentDispatcherAndExecutor ( ) ; } } for ( int i = 0 ; i < reloadableTypesSize ; i ++ ) { ReloadableType rtype = reloadableTypes [ i ] ; if ( rtype != null && rtype != currentlyDefining && rtype . hasBeenReloaded ( ) ) { if ( rtype . getLiveVersion ( ) . staticInitializedNeedsRerunningOnDefine ) { rtype . runStaticInitializer ( ) ; } } } // Up the limit if it is too low , or too much time will be spent constantly over the limit ( and so reloading )
int count = ccl . getDefinedCount ( ) + 3 ; if ( count > maxClassDefinitions ) { maxClassDefinitions = count ; } } |
public class GeoPackageValidate { /** * Validate the extension file as a GeoPackage
* @ param file
* GeoPackage file */
public static void validateGeoPackageExtension ( File file ) { } } | if ( ! hasGeoPackageExtension ( file ) ) { throw new GeoPackageException ( "GeoPackage database file '" + file + "' does not have a valid extension of '" + GeoPackageConstants . GEOPACKAGE_EXTENSION + "' or '" + GeoPackageConstants . GEOPACKAGE_EXTENDED_EXTENSION + "'" ) ; } |
public class BaseStreamWriter { /** * Method that essentially copies event that the specified reader has
* just read .
* @ param sr Stream reader to use for accessing event to copy
* @ param preserveEventData If true , writer is not allowed to change
* the state of the reader ( so that all the data associated with the
* current event has to be preserved ) ; if false , writer is allowed
* to use methods that may cause some data to be discarded . Setting
* this to false may improve the performance , since it may allow
* full no - copy streaming of data , especially textual contents . */
@ Override public void copyEventFromReader ( XMLStreamReader2 sr , boolean preserveEventData ) throws XMLStreamException { } } | try { switch ( sr . getEventType ( ) ) { case START_DOCUMENT : { String version = sr . getVersion ( ) ; // No real declaration ? If so , we don ' t want to output anything , to replicate
// as closely as possible the source document
if ( version == null || version . length ( ) == 0 ) { ; // no output if no real input
} else { if ( sr . standaloneSet ( ) ) { writeStartDocument ( sr . getVersion ( ) , sr . getCharacterEncodingScheme ( ) , sr . isStandalone ( ) ) ; } else { writeStartDocument ( sr . getCharacterEncodingScheme ( ) , sr . getVersion ( ) ) ; } } } return ; case END_DOCUMENT : writeEndDocument ( ) ; return ; // Element start / end events :
case START_ELEMENT : if ( sr instanceof StreamReaderImpl ) { StreamReaderImpl impl = ( StreamReaderImpl ) sr ; copyStartElement ( impl . getInputElementStack ( ) , impl . getAttributeCollector ( ) ) ; } else { // otherwise impl from Stax ref . impl ( Stax2WriterImpl ) has to do :
super . copyStartElement ( sr ) ; } return ; case END_ELEMENT : writeEndElement ( ) ; return ; case SPACE : { mAnyOutput = true ; // Need to finish an open start element ?
if ( mStartElementOpen ) { closeStartElement ( mEmptyElement ) ; } // No need to write as chars , should be pure space ( caller should
// have verified ) ; also , no escaping necessary .
// 28 - Mar - 2017 , tatu : Various optimization do not work well when validation so :
if ( mValidator != null ) { writeSpace ( sr . getText ( ) ) ; } else { sr . getText ( wrapAsRawWriter ( ) , preserveEventData ) ; } } return ; case CDATA : // First ; is this to be changed to ' normal ' text output ?
// 28 - Mar - 2017 , tatu : Various optimization do not work well when validation so :
if ( mValidator != null ) { writeCData ( sr . getText ( ) ) ; return ; } if ( ! mCfgCDataAsText ) { mAnyOutput = true ; // Need to finish an open start element ?
if ( mStartElementOpen ) { closeStartElement ( mEmptyElement ) ; } // Not legal outside main element tree :
if ( mCheckStructure ) { if ( inPrologOrEpilog ( ) ) { reportNwfStructure ( ErrorConsts . WERR_PROLOG_CDATA ) ; } } // Note : no need to check content , since reader is assumed
// to have verified it to be valid XML .
mWriter . writeCDataStart ( ) ; sr . getText ( wrapAsRawWriter ( ) , preserveEventData ) ; mWriter . writeCDataEnd ( ) ; return ; } // fall down if it is to be converted . . .
case CHARACTERS : // 28 - Mar - 2017 , tatu : Various optimization do not work well when validation so :
if ( mValidator != null ) { writeCharacters ( sr . getText ( ) ) ; } else { // Let ' s just assume content is fine . . . not 100 % reliably
// true , but usually is ( not true if input had a root
// element surrounding text , but omitted for output )
mAnyOutput = true ; // Need to finish an open start element ?
if ( mStartElementOpen ) { closeStartElement ( mEmptyElement ) ; } sr . getText ( wrapAsTextWriter ( ) , preserveEventData ) ; } return ; case COMMENT : { mAnyOutput = true ; if ( mStartElementOpen ) { closeStartElement ( mEmptyElement ) ; } // No need to check for content ( embedded ' - - ' ) ; reader
// is assumed to have verified it ' s ok ( otherwise should
// have thrown an exception for non - well - formed XML )
mWriter . writeCommentStart ( ) ; sr . getText ( wrapAsRawWriter ( ) , preserveEventData ) ; mWriter . writeCommentEnd ( ) ; } return ; case PROCESSING_INSTRUCTION : { mWriter . writePIStart ( sr . getPITarget ( ) , true ) ; sr . getText ( wrapAsRawWriter ( ) , preserveEventData ) ; mWriter . writePIEnd ( ) ; } return ; case DTD : { DTDInfo info = sr . getDTDInfo ( ) ; if ( info == null ) { // Hmmmh . It is legal for this to happen , for non - DTD - aware
// readers . But what is the right thing to do here ?
throwOutputError ( "Current state DOCTYPE, but not DTDInfo Object returned -- reader doesn't support DTDs?" ) ; } // Could optimize this a bit ( stream the int . subset possible ) ,
// but it ' s never going to occur more than once per document ,
// so it ' s probably not much of a bottleneck , ever
writeDTD ( info ) ; } return ; case ENTITY_REFERENCE : writeEntityRef ( sr . getLocalName ( ) ) ; return ; case ATTRIBUTE : case NAMESPACE : case ENTITY_DECLARATION : case NOTATION_DECLARATION : // Let ' s just fall back to throw the exception
} } catch ( IOException ioe ) { throw new WstxIOException ( ioe ) ; } throw new XMLStreamException ( "Unrecognized event type (" + sr . getEventType ( ) + "); not sure how to copy" ) ; |
public class XHTMLManager { /** * Returns an Iterator for the XHTML bodies in the message . Returns null if
* the message does not contain an XHTML extension .
* @ param message an XHTML message
* @ return an Iterator for the bodies in the message or null if none . */
public static List < CharSequence > getBodies ( Message message ) { } } | XHTMLExtension xhtmlExtension = XHTMLExtension . from ( message ) ; if ( xhtmlExtension != null ) return xhtmlExtension . getBodies ( ) ; else return null ; |
public class processNAF { /** * return :
* 1 if input mention " m " was added as a new mention
* 0 if a previously accepted mention with the same span of input mention m was enriched
* < 0 in case of problems ( e . g . due to a conflict with previously accepted mention ) ; input mention m was not added */
private static Integer addOrMergeAMention ( Record m , processNAFVariables vars ) { } } | String charS = m . getUnique ( NIF . BEGIN_INDEX , Integer . class ) + "," + m . getUnique ( NIF . END_INDEX , Integer . class ) ; if ( vars . mentionListHash . containsKey ( charS ) ) { /* there is a previously accepted mention with the same span : try to enrich it */
boolean chk = checkClassCompatibility ( vars . mentionListHash . get ( charS ) , m ) ; if ( ! chk ) { /* there is conflict between the input mention and the previously accepted mention with the same span :
check if the new mention can replace the old one , otherwise report the error */
if ( checkMentionReplaceability ( vars . mentionListHash . get ( charS ) , m ) ) { // replace the old mention with the new one
vars . mentionListHash . put ( charS , m ) ; logDebug ( "Replacement with Mention: " + m . getID ( ) + ", class(" + getTypeasString ( m . get ( RDF . TYPE ) ) + ")" , vars ) ; return 0 ; } String types = getTypeasString ( m . get ( RDF . TYPE ) ) ; if ( types . contains ( NWR . PARTICIPATION . stringValue ( ) ) ) { logDebug ( "Participation collision error, mentionID(" + m . getID ( ) + ") class1(" + getTypeasString ( m . get ( RDF . TYPE ) ) + "), class-pre-xtracted(" + getTypeasString ( vars . mentionListHash . get ( charS ) . get ( RDF . TYPE ) ) + ")" , vars ) ; } else { logDebug ( "Generic collision error, mentionID(" + m . getID ( ) + ") class1(" + getTypeasString ( m . get ( RDF . TYPE ) ) + "), class-pre-xtracted(" + getTypeasString ( vars . mentionListHash . get ( charS ) . get ( RDF . TYPE ) ) + ")" , vars ) ; } return - 1 ; } else { /* there is compatibility between the input mention and the previously accepted mention with the same span :
enrich old mention with properties from the new one ( except participation mentions ) */
String types = getTypeasString ( m . get ( RDF . TYPE ) ) ; if ( types . contains ( NWR . PARTICIPATION . stringValue ( ) ) ) { // Rule : no enrichment for participation
logDebug ( "Refused enrichment with participation mention, mentionID(" + m . getID ( ) + ")" , vars ) ; return - 1 ; } // enrich mention
ListIterator < URI > mit = m . getProperties ( ) . listIterator ( ) ; while ( mit . hasNext ( ) ) { URI mittmp = mit . next ( ) ; for ( Object pit : m . get ( mittmp ) ) { vars . mentionListHash . get ( charS ) . add ( mittmp , pit ) ; } } logDebug ( "Mention enrichment: " + m . getID ( ) + ", class(" + getTypeasString ( m . get ( RDF . TYPE ) ) + ")" , vars ) ; return 0 ; } } else { /* the mention is new ( there is no previously accepted mention with the same span ) */
vars . mentionListHash . put ( charS , m ) ; logDebug ( "Created Mention: " + m . getID ( ) , vars ) ; return 1 ; } |
public class SimpleRadioButton { /** * Creates a SimpleRadioButton widget that wraps an existing & lt ; input
* type = ' radio ' & gt ; element .
* This element must already be attached to the document . If the element is
* removed from the document , you must call
* { @ link RootPanel # detachNow ( Widget ) } .
* @ param element
* the element to be wrapped */
public static SimpleRadioButton wrap ( Element element ) { } } | // Assert that the element is attached .
assert Document . get ( ) . getBody ( ) . isOrHasChild ( element ) ; SimpleRadioButton radioButton = new SimpleRadioButton ( InputElement . as ( element ) ) ; // Mark it attached and remember it for cleanup .
radioButton . onAttach ( ) ; RootPanel . detachOnWindowClose ( radioButton ) ; return radioButton ; |
public class DefaultUrlMode { /** * Gets site root level path of a site .
* @ param path Path of page within the site
* @ param rootLevel Level of root page
* @ param resourceResolver Resource resolver
* @ return Site root path for the site . The path is not checked for validness . */
private String getRootPath ( String path , int rootLevel , ResourceResolver resourceResolver ) { } } | String rootPath = Path . getAbsoluteParent ( path , rootLevel , resourceResolver ) ; // strip off everything after first " . " - root path may be passed with selectors / extension which is not relevant
if ( StringUtils . contains ( rootPath , "." ) ) { rootPath = StringUtils . substringBefore ( rootPath , "." ) ; } return rootPath ; |
public class MicroOrm { /** * Fills the field in the provided object with data from the current row in
* { @ link Cursor } .
* @ param < T > the type of the provided object
* @ param c an open { @ link Cursor } with position set to valid row
* @ param object the instance to be filled with data
* @ return the same object for easy chaining */
@ SuppressWarnings ( "unchecked" ) public < T > T fromCursor ( Cursor c , T object ) { } } | return ( ( DaoAdapter < T > ) getAdapter ( object . getClass ( ) ) ) . fromCursor ( c , object ) ; |
public class API { /** * 获取ticket
* @ param key
* key
* @ param type
* 类型 jsapi , wx _ card
* @ return ticket */
public static String ticket ( String key , String type ) { } } | if ( isKeyParam ( key ) ) { String [ ] keys = key . split ( KEY_JOIN ) ; if ( keys . length == 2 ) { return apiHandler . ticket ( keys [ 0 ] , keys [ 1 ] , type ) ; } else if ( keys . length == 1 ) { return apiHandler . ticket ( keys [ 0 ] , type ) ; } } return key ; |
public class SharedInformerFactory { /** * Constructs and returns a shared index informer w / resync period specified . And the informer
* cache will be overwritten .
* @ param < ApiType > the type parameter
* @ param < ApiListType > the type parameter
* @ param callGenerator the call generator
* @ param apiTypeClass the api type class
* @ param apiListTypeClass the api list type class
* @ param resyncPeriodInMillis the resync period in millis
* @ return the shared index informer */
public synchronized < ApiType , ApiListType > SharedIndexInformer < ApiType > sharedIndexInformerFor ( Function < CallGeneratorParams , Call > callGenerator , Class < ApiType > apiTypeClass , Class < ApiListType > apiListTypeClass , long resyncPeriodInMillis ) { } } | ListerWatcher < ApiType , ApiListType > listerWatcher = listerWatcherFor ( callGenerator , apiTypeClass , apiListTypeClass ) ; SharedIndexInformer < ApiType > informer = new DefaultSharedIndexInformer < ApiType , ApiListType > ( apiTypeClass , listerWatcher , resyncPeriodInMillis ) ; this . informers . put ( TypeToken . get ( apiTypeClass ) . getType ( ) , informer ) ; return informer ; |
public class ResourceReaderImpl { /** * Searches for a property of " key " with all overrides , using the
* specified prefixes
* @ param key
* @ param prefixes
* @ return the value , or null if nothing was found */
private Tuple < String , String > getEntry ( final String key , final Collection < String > prefixes ) { } } | if ( CollectionUtils . isEmpty ( prefixes ) ) { return getEntry ( key ) ; } for ( String prefix : prefixes ) { String prefixedKey = prefix + "." + key ; Tuple < String , String > override = getOverrideEntry ( prefixedKey ) ; if ( override != null ) { return override ; } // Above we were checking overrides of the override . Here ,
// just check for the first override . If that doesn ' t work ,
// then we need to just pass it on and ignore the specified override .
String value = getPropertyValue ( prefixedKey ) ; if ( value != null ) { return new Tuple < String , String > ( prefixedKey , value ) ; } } // No prefixed overrides were found , so drop back to using
// the standard , non - prefixed version
return getEntry ( key ) ; |
public class MapperBuilder { /** * add a new mapping to the specified property with a key property definition and an undefined type .
* The index is incremented for each non indexed property mapping .
* @ param column the property name
* @ return the current builder */
public final B addKey ( String column ) { } } | return addMapping ( column , calculatedIndex ++ , FieldMapperColumnDefinition . < K > key ( ) ) ; |
public class MethodConfig { /** * Sets parameters .
* @ param parameters the parameters */
public MethodConfig setParameters ( Map < String , String > parameters ) { } } | if ( this . parameters == null ) { this . parameters = new ConcurrentHashMap < String , String > ( ) ; this . parameters . putAll ( parameters ) ; } return this ; |
public class FieldUtils { /** * This method determines whether a fragment of a bean path is a valid bean property identifier
* or bean property expression . */
private static boolean validateBeanPath ( final CharSequence path ) { } } | final int pathLen = path . length ( ) ; boolean inKey = false ; for ( int charPos = 0 ; charPos < pathLen ; charPos ++ ) { final char c = path . charAt ( charPos ) ; if ( ! inKey && c == PropertyAccessor . PROPERTY_KEY_PREFIX_CHAR ) { inKey = true ; } else if ( inKey && c == PropertyAccessor . PROPERTY_KEY_SUFFIX_CHAR ) { inKey = false ; } else if ( ! inKey && ! Character . isJavaIdentifierPart ( c ) && c != '.' ) { return false ; } } return true ; |
public class ActionContext { /** * Add an object into cache by key . The key will be used in conjunction with session id if
* there is a session instance
* @ param key
* the key to index the object within the cache
* @ param obj
* the object to be cached */
public void cache ( String key , Object obj ) { } } | H . Session sess = session ( ) ; if ( null != sess ) { sess . cache ( key , obj ) ; } else { app ( ) . cache ( ) . put ( key , obj ) ; } |
public class OrderedItemProcessor { /** * Callback that is invoked when an item has completed execution .
* @ param exception ( Optional ) An exception from the execution . If set , it indicates the item has not been
* processed successfully . */
@ VisibleForTesting protected void executionComplete ( Throwable exception ) { } } | Collection < QueueItem > toFail = null ; Throwable failEx = null ; synchronized ( this . stateLock ) { // Release the spot occupied by this item ' s execution .
this . activeCount -- ; if ( exception != null && ! this . closed ) { // Need to fail all future items and close to prevent new items from being processed .
failEx = new ProcessingException ( "A previous item failed to commit. Cannot process new items." , exception ) ; toFail = new ArrayList < > ( this . pendingItems ) ; this . pendingItems . clear ( ) ; this . closed = true ; } if ( this . emptyNotifier != null && this . activeCount == 0 && this . pendingItems . isEmpty ( ) ) { // We were asked to notify when we were empty .
this . emptyNotifier . release ( ) ; this . emptyNotifier = null ; } } if ( toFail != null ) { for ( QueueItem q : toFail ) { q . result . completeExceptionally ( failEx ) ; } return ; } // We need to ensure the items are still executed in order . Once out of the main sync block , it is possible that
// this callback may be invoked concurrently after various completions . As such , we need a special handler for
// these , using its own synchronization , different from the main one , so that we don ' t hold that stateLock for too long .
synchronized ( this . processingLock ) { while ( true ) { QueueItem toProcess ; synchronized ( this . stateLock ) { if ( hasCapacity ( ) && ! this . pendingItems . isEmpty ( ) ) { // We have spare capacity and we have something to process . Dequeue it and reserve the spot .
toProcess = this . pendingItems . pollFirst ( ) ; this . activeCount ++ ; } else { // No capacity left or no more pending items .
break ; } } Futures . completeAfter ( ( ) -> processInternal ( toProcess . data ) , toProcess . result ) ; } } |
public class PathPoint { /** * Constructs and returns a PathPoint object that describes a cubic B � zier curve to the
* given xy location with the control points at c0 and c1. */
public static PathPoint curveTo ( float c0X , float c0Y , float c1X , float c1Y , float x , float y ) { } } | return new PathPoint ( c0X , c0Y , c1X , c1Y , x , y ) ; |
public class InheritanceUnsafeGetResource { /** * Adjust the priority of a warning about to be reported .
* @ param priority
* initial priority
* @ return adjusted priority */
private int adjustPriority ( int priority ) { } } | try { Subtypes2 subtypes2 = AnalysisContext . currentAnalysisContext ( ) . getSubtypes2 ( ) ; if ( ! subtypes2 . hasSubtypes ( getClassDescriptor ( ) ) ) { priority ++ ; } else { Set < ClassDescriptor > mySubtypes = subtypes2 . getSubtypes ( getClassDescriptor ( ) ) ; String myPackagename = getThisClass ( ) . getPackageName ( ) ; for ( ClassDescriptor c : mySubtypes ) { if ( c . equals ( getClassDescriptor ( ) ) ) { continue ; } if ( ! c . getPackageName ( ) . equals ( myPackagename ) ) { priority -- ; break ; } } } } catch ( ClassNotFoundException e ) { bugReporter . reportMissingClass ( e ) ; } return priority ; |
public class BigtableTableAdminClientWrapper { /** * { @ inheritDoc } */
@ Override public Table modifyFamilies ( ModifyColumnFamiliesRequest request ) { } } | com . google . bigtable . admin . v2 . ModifyColumnFamiliesRequest modifyColumnRequestProto = request . toProto ( instanceName . getProjectId ( ) , instanceName . getInstanceId ( ) ) ; return Table . fromProto ( delegate . modifyColumnFamily ( modifyColumnRequestProto ) ) ; |
public class Style { /** * Default material yellow transparent style for SuperToasts .
* @ return A new Style */
public static Style yellow ( ) { } } | final Style style = new Style ( ) ; style . color = PaletteUtils . getSolidColor ( PaletteUtils . MATERIAL_YELLOW ) ; style . messageTextColor = PaletteUtils . getSolidColor ( PaletteUtils . DARK_GREY ) ; style . buttonDividerColor = PaletteUtils . getSolidColor ( PaletteUtils . DARK_GREY ) ; style . buttonTextColor = PaletteUtils . getSolidColor ( PaletteUtils . DARK_GREY ) ; return style ; |
public class DefaultApplicationRouter { /** * This method is checking if the application that initiated the request is currently configured to be called for this
* method . Apps that initiate request may not be in the list . */
private DefaultSipApplicationRouterInfo getFirstRequestApplicationEntry ( List < ? extends SipApplicationRouterInfo > defaultSipApplicationRouterInfoList , SipServletRequest initialRequest ) { } } | SipSession sipSession = initialRequest . getSession ( false ) ; if ( sipSession != null ) { String appName = sipSession . getApplicationSession ( ) . getApplicationName ( ) ; Iterator < ? extends SipApplicationRouterInfo > iterator = defaultSipApplicationRouterInfoList . iterator ( ) ; while ( iterator . hasNext ( ) ) { DefaultSipApplicationRouterInfo next = ( DefaultSipApplicationRouterInfo ) iterator . next ( ) ; if ( next . getApplicationName ( ) . equals ( appName ) ) return next ; } } return null ; |
public class ResourceAssignment { /** * Set an enterprise number value .
* @ param index number index ( 1-40)
* @ param value number value */
public void setEnterpriseNumber ( int index , Number value ) { } } | set ( selectField ( AssignmentFieldLists . ENTERPRISE_NUMBER , index ) , value ) ; |
public class SdkUpdater { /** * Configure and create a new Updater instance .
* @ param gcloudPath path to gcloud in the Cloud SDK
* @ return a new configured Cloud SDK updater */
public static SdkUpdater newUpdater ( OsInfo . Name osName , Path gcloudPath ) { } } | switch ( osName ) { case WINDOWS : return new SdkUpdater ( gcloudPath , CommandRunner . newRunner ( ) , new WindowsBundledPythonCopier ( gcloudPath , CommandCaller . newCaller ( ) ) ) ; default : return new SdkUpdater ( gcloudPath , CommandRunner . newRunner ( ) , null ) ; } |
public class CmsSchedulerList { /** * This method should handle every defined list multi action ,
* by comparing < code > { @ link # getParamListAction ( ) } < / code > with the id
* of the action to execute . < p >
* @ throws CmsRuntimeException to signal that an action is not supported */
@ Override public void executeListMultiActions ( ) throws CmsRuntimeException { } } | if ( getParamListAction ( ) . equals ( LIST_MACTION_DELETE ) ) { // execute the delete multiaction
List < String > removedItems = new ArrayList < String > ( ) ; Iterator < CmsListItem > itItems = getSelectedItems ( ) . iterator ( ) ; while ( itItems . hasNext ( ) ) { CmsListItem listItem = itItems . next ( ) ; try { OpenCms . getScheduleManager ( ) . unscheduleJob ( getCms ( ) , listItem . getId ( ) ) ; removedItems . add ( listItem . getId ( ) ) ; } catch ( CmsException e ) { throw new CmsRuntimeException ( Messages . get ( ) . container ( Messages . ERR_UNSCHEDULE_JOB_1 , listItem . getId ( ) ) , e ) ; } } // update the XML configuration
writeConfiguration ( false ) ; } else if ( getParamListAction ( ) . equals ( LIST_MACTION_ACTIVATE ) || getParamListAction ( ) . equals ( LIST_MACTION_DEACTIVATE ) ) { // execute the activate or deactivate multiaction
Iterator < CmsListItem > itItems = getSelectedItems ( ) . iterator ( ) ; boolean activate = getParamListAction ( ) . equals ( LIST_MACTION_ACTIVATE ) ; while ( itItems . hasNext ( ) ) { // toggle the active state of the selected item ( s )
CmsListItem listItem = itItems . next ( ) ; try { CmsScheduledJobInfo job = ( CmsScheduledJobInfo ) OpenCms . getScheduleManager ( ) . getJob ( listItem . getId ( ) ) . clone ( ) ; job . setActive ( activate ) ; OpenCms . getScheduleManager ( ) . scheduleJob ( getCms ( ) , job ) ; } catch ( CmsException e ) { throw new CmsRuntimeException ( Messages . get ( ) . container ( Messages . ERR_SCHEDULE_JOB_1 , listItem . getId ( ) ) , e ) ; } } // update the XML configuration
writeConfiguration ( true ) ; } else { throwListUnsupportedActionException ( ) ; } listSave ( ) ; |
public class UsersApi { /** * Search for users .
* Search for users with the specified filters .
* @ param searchTerm The text to search . ( optional )
* @ param groupId The ID of the group where the user belongs . ( optional )
* @ param sort The sort order , either & # x60 ; asc & # x60 ; ( ascending ) or & # x60 ; desc & # x60 ; ( descending ) . The default is & # x60 ; asc & # x60 ; . ( optional )
* @ param sortBy The sort order by criteria , either comma - separated list of criteria . Possible ccriteria & # 39 ; firstName & # 39 ; , & # 39 ; lastName & # 39 ; , & # 39 ; userName & # 39 ; . The default is & # x60 ; firstName , lastName & # x60 ; . ( optional )
* @ param limit Number of results to return . The default value is 100 . ( optional )
* @ param offset The offset to start from in the results . The default value is 0 . ( optional )
* @ param channels List of restricted channel , either comma - separated list of channels . If channels is not defined all available channels are returned . ( optional )
* @ return ApiSuccessResponse
* @ throws ApiException If fail to call the API , e . g . server error or cannot deserialize the response body */
public ApiSuccessResponse getUsers ( String searchTerm , BigDecimal groupId , String sort , String sortBy , BigDecimal limit , BigDecimal offset , String channels ) throws ApiException { } } | ApiResponse < ApiSuccessResponse > resp = getUsersWithHttpInfo ( searchTerm , groupId , sort , sortBy , limit , offset , channels ) ; return resp . getData ( ) ; |
public class AbstractValidate { /** * Method without varargs to increase performance */
public < T > T notNull ( final T object , final String message ) { } } | if ( object == null ) { failNull ( message ) ; } return object ; |
public class PartitionLevelWatermarker { /** * Adds watermark workunits to < code > workunits < / code > . A watermark workunit is a dummy workunit that is skipped by extractor / converter / writer .
* It stores a map of watermarks . The map has one entry per partition with partition watermark as value .
* < ul >
* < li > Add one NoOp watermark workunit for each { @ link Table }
* < li > The workunit has an identifier property { @ link # IS _ WATERMARK _ WORKUNIT _ KEY } set to true .
* < li > Watermarks for all { @ link Partition } s that belong to this { @ link Table } are added as { @ link Map }
* < li > A maximum of { @ link # maxPartitionsPerDataset } are persisted . Watermarks are ordered by most recently modified { @ link Partition } s
* < / ul >
* { @ inheritDoc }
* @ see org . apache . gobblin . data . management . conversion . hive . watermarker . HiveSourceWatermarker # onGetWorkunitsEnd ( java . util . List ) */
@ Override public void onGetWorkunitsEnd ( List < WorkUnit > workunits ) { } } | try ( AutoReturnableObject < IMetaStoreClient > client = this . pool . getClient ( ) ) { for ( Map . Entry < String , Map < String , Long > > tableWatermark : this . expectedHighWatermarks . entrySet ( ) ) { String tableKey = tableWatermark . getKey ( ) ; Map < String , Long > partitionWatermarks = tableWatermark . getValue ( ) ; // Watermark workunits are required only for Partitioned tables
// tableKey is table complete name in the format db @ table
if ( ! HiveUtils . isPartitioned ( new org . apache . hadoop . hive . ql . metadata . Table ( client . get ( ) . getTable ( tableKey . split ( "@" ) [ 0 ] , tableKey . split ( "@" ) [ 1 ] ) ) ) ) { continue ; } // We only keep watermarks for partitions that were updated after leastWatermarkToPersistInState
Map < String , Long > expectedPartitionWatermarks = ImmutableMap . copyOf ( Maps . filterEntries ( partitionWatermarks , new Predicate < Map . Entry < String , Long > > ( ) { @ Override public boolean apply ( @ Nonnull Map . Entry < String , Long > input ) { return Long . compare ( input . getValue ( ) , PartitionLevelWatermarker . this . leastWatermarkToPersistInState ) >= 0 ; } } ) ) ; // Create dummy workunit to track all the partition watermarks for this table
WorkUnit watermarkWorkunit = WorkUnit . createEmpty ( ) ; watermarkWorkunit . setProp ( IS_WATERMARK_WORKUNIT_KEY , true ) ; watermarkWorkunit . setProp ( ConfigurationKeys . DATASET_URN_KEY , tableKey ) ; watermarkWorkunit . setWatermarkInterval ( new WatermarkInterval ( new MultiKeyValueLongWatermark ( this . previousWatermarks . get ( tableKey ) ) , new MultiKeyValueLongWatermark ( expectedPartitionWatermarks ) ) ) ; workunits . add ( watermarkWorkunit ) ; } } catch ( IOException | TException e ) { Throwables . propagate ( e ) ; } |
public class IgnoredNonAffectedServerGroupsUtil { /** * For the DC to check whether an operation should be ignored on the slave , if the slave is set up to ignore config not relevant to it
* @ param domainResource the domain root resource
* @ param serverConfigs the server configs the slave is known to have
* @ param pathAddress the address of the operation to check if should be ignored or not */
public boolean ignoreOperation ( final Resource domainResource , final Collection < ServerConfigInfo > serverConfigs , final PathAddress pathAddress ) { } } | if ( pathAddress . size ( ) == 0 ) { return false ; } boolean ignore = ignoreResourceInternal ( domainResource , serverConfigs , pathAddress ) ; return ignore ; |
public class AbstractUncertainObject { /** * Compute the bounding box for some samples .
* @ param samples Samples
* @ return Bounding box . */
protected static HyperBoundingBox computeBounds ( NumberVector [ ] samples ) { } } | assert ( samples . length > 0 ) : "Cannot compute bounding box of empty set." ; // Compute bounds :
final int dimensions = samples [ 0 ] . getDimensionality ( ) ; final double [ ] min = new double [ dimensions ] ; final double [ ] max = new double [ dimensions ] ; NumberVector first = samples [ 0 ] ; for ( int d = 0 ; d < dimensions ; d ++ ) { min [ d ] = max [ d ] = first . doubleValue ( d ) ; } for ( int i = 1 ; i < samples . length ; i ++ ) { NumberVector v = samples [ i ] ; for ( int d = 0 ; d < dimensions ; d ++ ) { final double c = v . doubleValue ( d ) ; min [ d ] = c < min [ d ] ? c : min [ d ] ; max [ d ] = c > max [ d ] ? c : max [ d ] ; } } return new HyperBoundingBox ( min , max ) ; |
public class TvdbParser { /** * Get all the episodes from the URL
* @ param urlString
* @ param season
* @ return
* @ throws com . omertron . thetvdbapi . TvDbException */
public static List < Episode > getAllEpisodes ( String urlString , int season ) throws TvDbException { } } | List < Episode > episodeList = new ArrayList < > ( ) ; Episode episode ; NodeList nlEpisode ; Node nEpisode ; Element eEpisode ; Document doc = DOMHelper . getEventDocFromUrl ( urlString ) ; nlEpisode = doc . getElementsByTagName ( EPISODE ) ; for ( int loop = 0 ; loop < nlEpisode . getLength ( ) ; loop ++ ) { nEpisode = nlEpisode . item ( loop ) ; if ( nEpisode . getNodeType ( ) == Node . ELEMENT_NODE ) { eEpisode = ( Element ) nEpisode ; episode = parseNextEpisode ( eEpisode ) ; if ( ( episode != null ) && ( season == - 1 || episode . getSeasonNumber ( ) == season ) ) { // Add the episode only if the season is - 1 ( all seasons ) or matches the season
episodeList . add ( episode ) ; } } } return episodeList ; |
public class ZooKeeper { /** * The Asynchronous version of getChildren . The request doesn ' t actually
* until the asynchronous callback is called .
* @ see # getChildren ( String , Watcher ) */
public void getChildren ( final String path , Watcher watcher , ChildrenCallback cb , Object ctx ) { } } | verbotenThreadCheck ( ) ; final String clientPath = path ; PathUtils . validatePath ( clientPath ) ; // the watch contains the un - chroot path
WatchRegistration wcb = null ; if ( watcher != null ) { wcb = new ChildWatchRegistration ( watcher , clientPath ) ; } final String serverPath = prependChroot ( clientPath ) ; RequestHeader h = new RequestHeader ( ) ; h . setType ( ZooDefs . OpCode . getChildren ) ; GetChildrenRequest request = new GetChildrenRequest ( ) ; request . setPath ( serverPath ) ; request . setWatch ( watcher != null ) ; GetChildrenResponse response = new GetChildrenResponse ( ) ; cnxn . queuePacket ( h , new ReplyHeader ( ) , request , response , cb , clientPath , serverPath , ctx , wcb ) ; |
public class MessageUtil { /** * Removes the tainting character added to a string by { @ link # taint } . If the provided string
* is not tainted , this silently returns the originally provided string . */
public static String untaint ( String text ) { } } | return isTainted ( text ) ? text . substring ( TAINT_CHAR . length ( ) ) : text ; |
public class Delimiters { /** * get the escape for a character
* @ param ch
* @ return */
public String getEscape ( char ch ) { } } | if ( ch == escapeCharacter ) return escapeCharacter + "E" + escapeCharacter ; else if ( ch == fieldDelimiter ) return escapeCharacter + "F" + escapeCharacter ; else if ( ch == componentDelimiter ) return escapeCharacter + "S" + escapeCharacter ; else if ( ch == subComponentDelimiter ) return escapeCharacter + "T" + escapeCharacter ; else if ( ch == repetitionDelimiter ) return escapeCharacter + "R" + escapeCharacter ; else return null ; |
public class StructureInterface { /** * Calculates the number of non - Hydrogen atoms in the given group
* @ param g
* @ return */
private static int getSizeNoH ( Group g ) { } } | int size = 0 ; for ( Atom a : g . getAtoms ( ) ) { if ( a . getElement ( ) != Element . H ) size ++ ; } return size ; |
public class DescribeComputeEnvironmentsRequest { /** * A list of up to 100 compute environment names or full Amazon Resource Name ( ARN ) entries .
* < b > NOTE : < / b > This method appends the values to the existing list ( if any ) . Use
* { @ link # setComputeEnvironments ( java . util . Collection ) } or { @ link # withComputeEnvironments ( java . util . Collection ) }
* if you want to override the existing values .
* @ param computeEnvironments
* A list of up to 100 compute environment names or full Amazon Resource Name ( ARN ) entries .
* @ return Returns a reference to this object so that method calls can be chained together . */
public DescribeComputeEnvironmentsRequest withComputeEnvironments ( String ... computeEnvironments ) { } } | if ( this . computeEnvironments == null ) { setComputeEnvironments ( new java . util . ArrayList < String > ( computeEnvironments . length ) ) ; } for ( String ele : computeEnvironments ) { this . computeEnvironments . add ( ele ) ; } return this ; |
public class BuilderImpl { /** * ( non - Javadoc )
* @ see com . ibm . ws . security . jwt . internal . Builder # subject ( java . lang . String ) */
@ Override public Builder subject ( String username ) throws InvalidClaimException { } } | if ( username != null && ! username . isEmpty ( ) ) { claims . put ( Claims . SUBJECT , username ) ; } else { String err = Tr . formatMessage ( tc , "JWT_INVALID_CLAIM_VALUE_ERR" , new Object [ ] { Claims . SUBJECT , username } ) ; throw new InvalidClaimException ( err ) ; } return this ; |
public class ConfigTemplate { /** * Create the xml configuration descriptor .
* @ param stagingDirectory The parent directory where the configuration descriptor is to be
* created .
* @ throws MojoExecutionException Unspecified exception . */
protected void createFile ( File stagingDirectory ) throws MojoExecutionException { } } | File targetDirectory = newSubdirectory ( stagingDirectory , "META-INF" ) ; File newEntry = new File ( targetDirectory , filename ) ; try ( FileOutputStream out = new FileOutputStream ( newEntry ) ; PrintStream ps = new PrintStream ( out ) ; ) { Iterator < ConfigEntry > iter = entries . values ( ) . iterator ( ) ; ConfigEntry entry = null ; for ( int i = 0 ; i < buffer . size ( ) ; i ++ ) { if ( entry == null && iter . hasNext ( ) ) { entry = iter . next ( ) ; } if ( entry != null && entry . placeholder == i ) { for ( String line : entry . buffer ) { ps . println ( line ) ; } entry = null ; continue ; } ps . println ( buffer . get ( i ) ) ; } } catch ( Exception e ) { throw new MojoExecutionException ( "Unexpected error while creating configuration file." , e ) ; } |
public class GetProductsForProductTemplate { /** * Runs the example .
* @ param adManagerServices the services factory .
* @ param session the session .
* @ param productTemplateId the ID of the product template .
* @ throws ApiException if the API request failed with one or more service errors .
* @ throws RemoteException if the API request failed due to other errors . */
public static void runExample ( AdManagerServices adManagerServices , AdManagerSession session , long productTemplateId ) throws RemoteException { } } | ProductServiceInterface productService = adManagerServices . get ( session , ProductServiceInterface . class ) ; // Create a statement to select products .
StatementBuilder statementBuilder = new StatementBuilder ( ) . where ( "productTemplateId = :productTemplateId" ) . orderBy ( "id ASC" ) . limit ( StatementBuilder . SUGGESTED_PAGE_LIMIT ) . withBindVariableValue ( "productTemplateId" , productTemplateId ) ; // Retrieve a small amount of products at a time , paging through
// until all products have been retrieved .
int totalResultSetSize = 0 ; do { ProductPage page = productService . getProductsByStatement ( statementBuilder . toStatement ( ) ) ; if ( page . getResults ( ) != null ) { // Print out some information for each product .
totalResultSetSize = page . getTotalResultSetSize ( ) ; int i = page . getStartIndex ( ) ; for ( Product product : page . getResults ( ) ) { System . out . printf ( "%d) Product with ID %d and name '%s' was found.%n" , i ++ , product . getId ( ) , product . getName ( ) ) ; } } statementBuilder . increaseOffsetBy ( StatementBuilder . SUGGESTED_PAGE_LIMIT ) ; } while ( statementBuilder . getOffset ( ) < totalResultSetSize ) ; System . out . printf ( "Number of results found: %d%n" , totalResultSetSize ) ; |
public class SimulatorEngine { /** * The main loop of the simulation . First call init ( ) to get objects ready ,
* then go into the main loop , where { @ link SimulatorEvent } s are handled removed from
* the { @ link SimulatorEventQueue } , and new { @ link SimulatorEvent } s are created and inserted
* into the { @ link SimulatorEventQueue } .
* @ throws IOException
* @ throws InterruptedException */
void run ( ) throws IOException , InterruptedException { } } | init ( ) ; for ( SimulatorEvent next = queue . get ( ) ; next != null && next . getTimeStamp ( ) < terminateTime && ! shutdown ; next = queue . get ( ) ) { currentTime = next . getTimeStamp ( ) ; assert ( currentTime == queue . getCurrentTime ( ) ) ; SimulatorEventListener listener = next . getListener ( ) ; List < SimulatorEvent > response = listener . accept ( next ) ; queue . addAll ( response ) ; } summary ( System . out ) ; |
public class LatLongUtils { /** * Calculate the spherical distance between two LatLongs in meters using the Haversine
* formula .
* This calculation is done using the assumption , that the earth is a sphere , it is not
* though . If you need a higher precision and can afford a longer execution time you might
* want to use vincentyDistance .
* @ param latLong1 first LatLong
* @ param latLong2 second LatLong
* @ return distance in meters as a double */
public static double sphericalDistance ( LatLong latLong1 , LatLong latLong2 ) { } } | double dLat = Math . toRadians ( latLong2 . latitude - latLong1 . latitude ) ; double dLon = Math . toRadians ( latLong2 . longitude - latLong1 . longitude ) ; double a = Math . sin ( dLat / 2 ) * Math . sin ( dLat / 2 ) + Math . cos ( Math . toRadians ( latLong1 . latitude ) ) * Math . cos ( Math . toRadians ( latLong2 . latitude ) ) * Math . sin ( dLon / 2 ) * Math . sin ( dLon / 2 ) ; double c = 2 * Math . atan2 ( Math . sqrt ( a ) , Math . sqrt ( 1 - a ) ) ; return c * LatLongUtils . EQUATORIAL_RADIUS ; |
public class HtmlDocletWriter { /** * Get link to the module summary page for the module passed .
* @ param mdle Module to which link will be generated
* @ return a content tree for the link */
protected Content getNavLinkModule ( ModuleElement mdle ) { } } | Content linkContent = getModuleLink ( mdle , contents . moduleLabel ) ; Content li = HtmlTree . LI ( linkContent ) ; return li ; |
public class TechSet { /** * Tells whether or not any of the given technologies is included .
* @ param techs the technologies that will be checked .
* @ return { @ code true } if any of the technologies is included , { @ code false } otherwise .
* @ since TODO add version
* @ see # includes ( Tech ) */
public boolean includesAny ( Tech ... techs ) { } } | if ( techs == null || techs . length == 0 ) { return false ; } for ( Tech tech : techs ) { if ( includes ( tech ) ) { return true ; } } return false ; |
public class CompressionUtils { /** * Checks to see if fName is a valid name for a " * . zip " file
* @ param fName The name of the file in question
* @ return True if fName is properly named for a . zip file , false otherwise */
public static boolean isZip ( String fName ) { } } | if ( Strings . isNullOrEmpty ( fName ) ) { return false ; } return fName . endsWith ( ZIP_SUFFIX ) ; // Technically a file named ` . zip ` would be fine |
public class CPTaxCategoryServiceBaseImpl { /** * Sets the cp rule local service .
* @ param cpRuleLocalService the cp rule local service */
public void setCPRuleLocalService ( com . liferay . commerce . product . service . CPRuleLocalService cpRuleLocalService ) { } } | this . cpRuleLocalService = cpRuleLocalService ; |
public class ProcessEngines { /** * retries to initialize a process engine that previously failed . */
public static ProcessEngineInfo retry ( String resourceUrl ) { } } | log . debug ( "retying initializing of resource {}" , resourceUrl ) ; try { return initProcessEngineFromResource ( new URL ( resourceUrl ) ) ; } catch ( MalformedURLException e ) { throw new ActivitiIllegalArgumentException ( "invalid url: " + resourceUrl , e ) ; } |
public class ClientSpanNameProvider { /** * Using regexes derived from the Elasticsearch 5.6 HTTP API , this method removes additional
* parameters in the request and replaces numerical IDs with ' ? ' to reduce granularity .
* @ param uri The uri of the HttpRequest that is calling out to Elasticsearch
* @ return A standardized version of the uri that reduces granularity . */
private static String standardizeUri ( String uri ) { } } | return ( uri == null ) ? null : regexIDPattern . matcher ( regexTaskIDPattern . matcher ( regexParameterPattern . matcher ( uri ) . replaceFirst ( "" ) ) . replaceAll ( "task_id:\\?" ) ) . replaceAll ( "/\\?$1" ) ; |
public class NodeStack { /** * Start the stack with the root of the tree . */
private void stackStart ( GBSNode node ) { } } | _idx = 0 ; _cidx = 0 ; _state [ _cidx ] = 0 ; _node [ _cidx ] = node ; _bpidx = _cidx + 1 ; _maxIdx = _cidx ; |
public class ImageHandlerBuilder { /** * Saves the file on the server in the folder given
* @ param uploadFolder
* @ return The server path to the saved file .
* @ throws ControllerException If anything goes wrong during write to disk . */
public String save ( String uploadFolder ) throws ControllerException { } } | String realPath = info . getRealPath ( uploadFolder ) ; fn . sanitise ( ) ; String imagename = uniqueImagename ( realPath , fn . fullPath ( ) ) ; try { ImageIO . write ( image , fn . extension ( ) , new File ( realPath , imagename ) ) ; image . flush ( ) ; } catch ( IOException e ) { throw new ControllerException ( e ) ; } return uploadFolder + File . separatorChar + imagename ; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.