signature stringlengths 43 39.1k | implementation stringlengths 0 450k |
|---|---|
public class ImageSelectorAndSaver { /** * Creates a template of the fiducial and this is then used to determine how blurred the image is */
public void setTemplate ( GrayF32 image , List < Point2D_F64 > sides ) { } } | if ( sides . size ( ) != 4 ) throw new IllegalArgumentException ( "Expected 4 sidesCollision" ) ; removePerspective . apply ( image , sides . get ( 0 ) , sides . get ( 1 ) , sides . get ( 2 ) , sides . get ( 3 ) ) ; templateOriginal . setTo ( removePerspective . getOutput ( ) ) ; // blur the image a bit so it doesn ' t have to be a perfect match
GrayF32 blurred = new GrayF32 ( LENGTH , LENGTH ) ; BlurImageOps . gaussian ( templateOriginal , blurred , - 1 , 2 , null ) ; // place greater importance on pixels which are around edges
GrayF32 derivX = new GrayF32 ( LENGTH , LENGTH ) ; GrayF32 derivY = new GrayF32 ( LENGTH , LENGTH ) ; GImageDerivativeOps . gradient ( DerivativeType . SOBEL , blurred , derivX , derivY , BorderType . EXTENDED ) ; GGradientToEdgeFeatures . intensityE ( derivX , derivY , weights ) ; float max = ImageStatistics . max ( weights ) ; PixelMath . divide ( weights , max , weights ) ; totalWeight = ImageStatistics . sum ( weights ) ; // compute a normalized template for later use . Divide by the mean to add some lighting invariance
template . setTo ( removePerspective . getOutput ( ) ) ; float mean = ( float ) ImageStatistics . mean ( template ) ; PixelMath . divide ( template , mean , template ) ; |
public class HBaseClientFactory { /** * ( non - Javadoc )
* @ see
* com . impetus . kundera . loader . GenericClientFactory # instantiateClient ( java
* . lang . String ) */
@ Override protected Client instantiateClient ( String persistenceUnit ) { } } | return new HBaseClient ( indexManager , conf , connection , reader , persistenceUnit , externalProperties , clientMetadata , kunderaMetadata ) ; |
public class DescribeCertificateAuthorityAuditReportRequestMarshaller { /** * Marshall the given parameter object . */
public void marshall ( DescribeCertificateAuthorityAuditReportRequest describeCertificateAuthorityAuditReportRequest , ProtocolMarshaller protocolMarshaller ) { } } | if ( describeCertificateAuthorityAuditReportRequest == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( describeCertificateAuthorityAuditReportRequest . getCertificateAuthorityArn ( ) , CERTIFICATEAUTHORITYARN_BINDING ) ; protocolMarshaller . marshall ( describeCertificateAuthorityAuditReportRequest . getAuditReportId ( ) , AUDITREPORTID_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class JsonInput { private char readNext ( ) throws IOException { } } | if ( cachedNext != null ) { char next = cachedNext . charValue ( ) ; cachedNext = null ; return next ; } int next = input . read ( ) ; if ( next == - 1 ) { throw new IllegalArgumentException ( "Invalid JSON data: End of file" ) ; } return ( char ) next ; |
public class Levenshtein { /** * Searches the given collection of strings and returns the string that
* has the lowest Levenshtein distance to a given second string < code > t < / code > .
* If the collection contains multiple strings with the same distance to
* < code > t < / code > only the first one will be returned .
* @ param < T > the type of the strings in the given collection
* @ param ss the collection to search
* @ param t the second string
* @ return the string with the lowest Levenshtein distance */
public static < T extends CharSequence > T findMinimum ( Collection < T > ss , CharSequence t ) { } } | int min = Integer . MAX_VALUE ; T result = null ; for ( T s : ss ) { int d = StringUtils . getLevenshteinDistance ( s , t ) ; if ( d < min ) { min = d ; result = s ; } } return result ; |
public class TldRegionTracker { /** * Spawn KLT tracks at evenly spaced points inside a grid */
protected void spawnGrid ( Rectangle2D_F64 prevRect ) { } } | // Shrink the rectangle to ensure that all features are entirely contained inside
spawnRect . p0 . x = prevRect . p0 . x + featureRadius ; spawnRect . p0 . y = prevRect . p0 . y + featureRadius ; spawnRect . p1 . x = prevRect . p1 . x - featureRadius ; spawnRect . p1 . y = prevRect . p1 . y - featureRadius ; double spawnWidth = spawnRect . getWidth ( ) ; double spawnHeight = spawnRect . getHeight ( ) ; // try spawning features at evenly spaced points inside the grid
tracker . setImage ( previousImage , previousDerivX , previousDerivY ) ; for ( int i = 0 ; i < gridWidth ; i ++ ) { float y = ( float ) ( spawnRect . p0 . y + i * spawnHeight / ( gridWidth - 1 ) ) ; for ( int j = 0 ; j < gridWidth ; j ++ ) { float x = ( float ) ( spawnRect . p0 . x + j * spawnWidth / ( gridWidth - 1 ) ) ; Track t = tracks [ i * gridWidth + j ] ; t . klt . x = x ; t . klt . y = y ; if ( tracker . setDescription ( t . klt ) ) { t . active = true ; } else { t . active = false ; } } } |
public class StreamMetrics { /** * Reports the number of segment splits and merges related to a particular scale operation on a Stream . Both global
* and Stream - specific counters are updated .
* @ param scope Scope .
* @ param streamName Name of the Stream .
* @ param splits Number of segment splits in the scale operation .
* @ param merges Number of segment merges in the scale operation . */
public static void reportSegmentSplitsAndMerges ( String scope , String streamName , long splits , long merges ) { } } | DYNAMIC_LOGGER . updateCounterValue ( globalMetricName ( SEGMENTS_SPLITS ) , splits ) ; DYNAMIC_LOGGER . updateCounterValue ( SEGMENTS_SPLITS , splits , streamTags ( scope , streamName ) ) ; DYNAMIC_LOGGER . updateCounterValue ( globalMetricName ( SEGMENTS_MERGES ) , merges ) ; DYNAMIC_LOGGER . updateCounterValue ( SEGMENTS_MERGES , merges , streamTags ( scope , streamName ) ) ; |
public class ClusterMetricsContext { /** * get topology metrics , note that only topology & component & worker
* metrics are returned */
public TopologyMetric getTopologyMetric ( String topologyId ) { } } | long start = System . nanoTime ( ) ; try { TopologyMetric ret = new TopologyMetric ( ) ; List < MetricInfo > topologyMetrics = metricCache . getMetricData ( topologyId , MetaType . TOPOLOGY ) ; List < MetricInfo > componentMetrics = metricCache . getMetricData ( topologyId , MetaType . COMPONENT ) ; List < MetricInfo > workerMetrics = metricCache . getMetricData ( topologyId , MetaType . WORKER ) ; MetricInfo dummy = MetricUtils . mkMetricInfo ( ) ; if ( topologyMetrics . size ( ) > 0 ) { // get the last min topology metric
ret . set_topologyMetric ( topologyMetrics . get ( topologyMetrics . size ( ) - 1 ) ) ; } else { ret . set_topologyMetric ( dummy ) ; } if ( componentMetrics . size ( ) > 0 ) { ret . set_componentMetric ( componentMetrics . get ( 0 ) ) ; } else { ret . set_componentMetric ( dummy ) ; } if ( workerMetrics . size ( ) > 0 ) { ret . set_workerMetric ( workerMetrics . get ( 0 ) ) ; } else { ret . set_workerMetric ( dummy ) ; } ret . set_taskMetric ( dummy ) ; ret . set_streamMetric ( dummy ) ; ret . set_nettyMetric ( dummy ) ; return ret ; } finally { long end = System . nanoTime ( ) ; SimpleJStormMetric . updateNimbusHistogram ( "getTopologyMetric" , ( end - start ) / TimeUtils . NS_PER_US ) ; } |
public class InputDeserializer { /** * Deserializes an input message .
* @ param message The message to deserialize .
* @ return The message value . */
public Object deserialize ( JsonObject message ) { } } | String type = message . getString ( "type" ) ; if ( type == null ) { return message . getValue ( "value" ) ; } else { switch ( type ) { case "buffer" : return new Buffer ( message . getBinary ( "value" ) ) ; case "bytes" : return message . getBinary ( "value" ) ; case "serialized" : byte [ ] bytes = message . getBinary ( "value" ) ; ObjectInputStream stream = null ; try { stream = new ThreadObjectInputStream ( new ByteArrayInputStream ( bytes ) ) ; return stream . readObject ( ) ; } catch ( ClassNotFoundException | IOException e ) { throw new SerializationException ( e . getMessage ( ) ) ; } finally { if ( stream != null ) { try { stream . close ( ) ; } catch ( IOException e ) { } } } default : return message . getValue ( "value" ) ; } } |
public class TagAPI { /** * Removes a single tag from an object .
* @ param reference
* The object the tag should be removed from
* @ param tag
* The tag to remove */
public void removeTag ( Reference reference , String tag ) { } } | getResourceFactory ( ) . getApiResource ( "/tag/" + reference . toURLFragment ( ) ) . queryParam ( "text" , tag ) . delete ( ) ; |
public class MembershipTypeHandlerImpl { /** * { @ inheritDoc } */
public MembershipType findMembershipType ( String name ) throws Exception { } } | MembershipType mt = getFromCache ( name ) ; if ( mt != null ) { return mt ; } Session session = service . getStorageSession ( ) ; try { return findMembershipType ( session , name ) ; } finally { session . logout ( ) ; } |
public class CreateDirectoryRequestMarshaller { /** * Marshall the given parameter object . */
public void marshall ( CreateDirectoryRequest createDirectoryRequest , ProtocolMarshaller protocolMarshaller ) { } } | if ( createDirectoryRequest == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( createDirectoryRequest . getName ( ) , NAME_BINDING ) ; protocolMarshaller . marshall ( createDirectoryRequest . getShortName ( ) , SHORTNAME_BINDING ) ; protocolMarshaller . marshall ( createDirectoryRequest . getPassword ( ) , PASSWORD_BINDING ) ; protocolMarshaller . marshall ( createDirectoryRequest . getDescription ( ) , DESCRIPTION_BINDING ) ; protocolMarshaller . marshall ( createDirectoryRequest . getSize ( ) , SIZE_BINDING ) ; protocolMarshaller . marshall ( createDirectoryRequest . getVpcSettings ( ) , VPCSETTINGS_BINDING ) ; protocolMarshaller . marshall ( createDirectoryRequest . getTags ( ) , TAGS_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class cmppolicy_stats { /** * Use this API to fetch the statistics of all cmppolicy _ stats resources that are configured on netscaler . */
public static cmppolicy_stats [ ] get ( nitro_service service ) throws Exception { } } | cmppolicy_stats obj = new cmppolicy_stats ( ) ; cmppolicy_stats [ ] response = ( cmppolicy_stats [ ] ) obj . stat_resources ( service ) ; return response ; |
public class Call { /** * < p > execute . < / p >
* @ param args a { @ link java . lang . String } object .
* @ return a { @ link java . lang . Object } object .
* @ throws java . lang . Exception if any . */
public Object execute ( String ... args ) throws Exception { } } | result = new Result ( expectation ) ; try { result . setActual ( message . send ( mergeInputsWith ( args ) ) ) ; } catch ( SystemUnderDevelopmentException e ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Error while executing specifications" , e . getCause ( ) ) ; } result . exceptionOccured ( e . getCause ( ) ) ; } dispatchForHandling ( result ) ; return result . getActual ( ) ; |
public class AbstractObjectTable { /** * Initialize our internal values . */
protected void init ( ) { } } | // Get all our messages
objectSingularName = getApplicationConfig ( ) . messageResolver ( ) . getMessage ( modelId + ".objectName.singular" ) ; objectPluralName = getApplicationConfig ( ) . messageResolver ( ) . getMessage ( modelId + ".objectName.plural" ) ; |
public class Reporters { /** * Same as { @ link # fileLauncher } but doesn ' t do the swing interaction after it opens the file . This is mostly used to reuse the logic
* of file launching without adding the burden for prompting the user after that .
* @ return a reporter that launches the file */
public static Reporter fileLauncherWithoutInteraction ( ) { } } | final String cmd = new CrossPlatformCommand < String > ( ) { @ Override protected String onWindows ( ) { return "cmd /C start" ; } @ Override protected String onMac ( ) { return "open" ; } @ Override protected String onUnix ( ) { return "xdg-open" ; } } . execute ( ) ; return new ExecutableDifferenceReporter ( cmd , cmd , null ) { @ Override protected String [ ] buildApproveNewCommand ( File approvalDestination , File fileForVerification ) { return new String [ ] { getApprovalCommand ( ) , approvalDestination . getAbsolutePath ( ) } ; } @ Override protected String [ ] buildNotTheSameCommand ( File fileForVerification , File fileForApproval ) { return new String [ ] { getDiffCommand ( ) , fileForApproval . getAbsolutePath ( ) } ; } } ; |
public class ThreadPoolTaskScheduler { /** * Initialize executor .
* @ param threadFactory the thread factory
* @ param rejectedExecutionHandler the rejected execution handler
* @ return the executor service */
protected ExecutorService initializeExecutor ( ThreadFactory threadFactory , RejectedExecutionHandler rejectedExecutionHandler ) { } } | this . scheduledExecutor = createExecutor ( this . poolSize , threadFactory , rejectedExecutionHandler ) ; if ( this . removeOnCancelPolicy ) { if ( setRemoveOnCancelPolicyAvailable && this . scheduledExecutor instanceof ScheduledThreadPoolExecutor ) { ( ( ScheduledThreadPoolExecutor ) this . scheduledExecutor ) . setRemoveOnCancelPolicy ( true ) ; } else { // logger . info ( " Could not apply remove - on - cancel policy - not a Java 7 + ScheduledThreadPoolExecutor " ) ;
} } return this . scheduledExecutor ; |
public class XMLOutputter { /** * Adds an attribute to the current element , with a < code > String < / code > value . There must
* currently be an open element .
* The attribute value is surrounded by the quotation mark character ( see
* { @ link # getQuotationMark ( ) } ) .
* @ param name the name of the attribute , not < code > null < / code > .
* @ param value the value of the attribute , not < code > null < / code > .
* @ throws IllegalStateException if < code > getState ( ) ! = { @ link # START _ TAG _ OPEN } < / code > .
* @ throws IllegalArgumentException if < code > name = = null | | value = = null < / code > .
* @ throws IOException if an I / O error occurs ; this will set the state to { @ link # ERROR _ STATE } . */
@ Override public final void attribute ( String name , String value ) throws IllegalStateException , IllegalArgumentException , IOException { } } | // Check state
if ( _state != XMLEventListenerStates . START_TAG_OPEN ) { throw new IllegalStateException ( "getState() == " + _state ) ; // Check arguments
} else if ( name == null || value == null ) { if ( name == null && value == null ) { throw new IllegalArgumentException ( "name == null && value == null" ) ; } else if ( name == null ) { throw new IllegalArgumentException ( "name == null" ) ; } else { throw new IllegalArgumentException ( "value == null" ) ; } } // Temporarily set the state to ERROR _ STATE . Unless an exception is
// thrown in the write methods , it will be reset to a valid state .
_state = XMLEventListenerStates . ERROR_STATE ; // Write output
_encoder . attribute ( _out , name , value , _quotationMark , _escapeAmpersands ) ; // Reset the state
_state = XMLEventListenerStates . START_TAG_OPEN ; // State has changed , check
checkInvariants ( ) ; |
public class RecordSetsInner { /** * Lists all record sets in a DNS zone .
* @ param resourceGroupName The name of the resource group .
* @ param zoneName The name of the DNS zone ( without a terminating dot ) .
* @ param top The maximum number of record sets to return . If not specified , returns up to 100 record sets .
* @ param recordSetNameSuffix The suffix label of the record set name that has to be used to filter the record set enumerations . If this parameter is specified , Enumeration will return only records that end with . & lt ; recordSetNameSuffix & gt ;
* @ 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 < RecordSetInner > > listAllByDnsZoneAsync ( final String resourceGroupName , final String zoneName , final Integer top , final String recordSetNameSuffix , final ListOperationCallback < RecordSetInner > serviceCallback ) { } } | return AzureServiceFuture . fromPageResponse ( listAllByDnsZoneSinglePageAsync ( resourceGroupName , zoneName , top , recordSetNameSuffix ) , new Func1 < String , Observable < ServiceResponse < Page < RecordSetInner > > > > ( ) { @ Override public Observable < ServiceResponse < Page < RecordSetInner > > > call ( String nextPageLink ) { return listAllByDnsZoneNextSinglePageAsync ( nextPageLink ) ; } } , serviceCallback ) ; |
public class SuperClassInvocationBenchmark { /** * Performs a benchmark of a super method invocation using Byte Buddy . This benchmark uses an annotation - based
* approach which is more difficult to optimize by the JIT compiler .
* @ param blackHole A black hole for avoiding JIT erasure . */
@ Benchmark @ OperationsPerInvocation ( 20 ) public void benchmarkByteBuddyWithProxy ( Blackhole blackHole ) { } } | blackHole . consume ( byteBuddyWithProxyInstance . method ( booleanValue ) ) ; blackHole . consume ( byteBuddyWithProxyInstance . method ( byteValue ) ) ; blackHole . consume ( byteBuddyWithProxyInstance . method ( shortValue ) ) ; blackHole . consume ( byteBuddyWithProxyInstance . method ( intValue ) ) ; blackHole . consume ( byteBuddyWithProxyInstance . method ( charValue ) ) ; blackHole . consume ( byteBuddyWithProxyInstance . method ( intValue ) ) ; blackHole . consume ( byteBuddyWithProxyInstance . method ( longValue ) ) ; blackHole . consume ( byteBuddyWithProxyInstance . method ( floatValue ) ) ; blackHole . consume ( byteBuddyWithProxyInstance . method ( doubleValue ) ) ; blackHole . consume ( byteBuddyWithProxyInstance . method ( stringValue ) ) ; blackHole . consume ( byteBuddyWithProxyInstance . method ( booleanValue , booleanValue , booleanValue ) ) ; blackHole . consume ( byteBuddyWithProxyInstance . method ( byteValue , byteValue , byteValue ) ) ; blackHole . consume ( byteBuddyWithProxyInstance . method ( shortValue , shortValue , shortValue ) ) ; blackHole . consume ( byteBuddyWithProxyInstance . method ( intValue , intValue , intValue ) ) ; blackHole . consume ( byteBuddyWithProxyInstance . method ( charValue , charValue , charValue ) ) ; blackHole . consume ( byteBuddyWithProxyInstance . method ( intValue , intValue , intValue ) ) ; blackHole . consume ( byteBuddyWithProxyInstance . method ( longValue , longValue , longValue ) ) ; blackHole . consume ( byteBuddyWithProxyInstance . method ( floatValue , floatValue , floatValue ) ) ; blackHole . consume ( byteBuddyWithProxyInstance . method ( doubleValue , doubleValue , doubleValue ) ) ; blackHole . consume ( byteBuddyWithProxyInstance . method ( stringValue , stringValue , stringValue ) ) ; |
public class CmsUrlNameMappingFilter { /** * Creates a new filter from the current filter which also has to match a given name pattern . < p >
* @ param namePattern the name pattern which should be matched
* @ return a new filter */
public CmsUrlNameMappingFilter filterNamePattern ( String namePattern ) { } } | if ( namePattern == null ) { throw new IllegalArgumentException ( ) ; } CmsUrlNameMappingFilter result = new CmsUrlNameMappingFilter ( this ) ; result . m_namePattern = namePattern ; return result ; |
public class QuartzSchedulerThread { /** * Signals the main processing loop to pause at the next possible point . */
void halt ( final boolean wait ) { } } | synchronized ( m_aSigLock ) { m_aHalted . set ( true ) ; if ( m_bPaused ) { m_aSigLock . notifyAll ( ) ; } else { signalSchedulingChange ( 0 ) ; } } if ( wait ) { boolean interrupted = false ; try { while ( true ) { try { join ( ) ; break ; } catch ( final InterruptedException ex ) { interrupted = true ; } } } finally { if ( interrupted ) { Thread . currentThread ( ) . interrupt ( ) ; } } } |
public class CollectionData { /** * Precondition : The specified key string is the path to a long . Gets the long at the specified
* key string .
* @ param keyStr One or more map keys and / or list indices ( separated by ' . ' if multiple parts ) .
* Indicates the path to the location within this data tree .
* @ return The long at the specified key string .
* @ throws IllegalArgumentException If no data is stored at the specified key . */
public long getLong ( String keyStr ) { } } | SoyData valueData = get ( keyStr ) ; if ( valueData == null ) { throw new IllegalArgumentException ( "Missing key: " + keyStr ) ; } return valueData . longValue ( ) ; |
public class CmsDataViewPanel { /** * Gets the list of selected data items . < p >
* If this widget is not in multi - select mode , a list with a single result will be returned . < p >
* @ return the selected results */
public List < I_CmsDataViewItem > getSelection ( ) { } } | List < I_CmsDataViewItem > result = Lists . newArrayList ( ) ; Object val = m_table . get ( ) . getValue ( ) ; if ( val == null ) { return result ; } if ( val instanceof Collection ) { Collection < ? > results = ( Collection < ? > ) val ; for ( Object obj : results ) { result . add ( m_dataView . getItemById ( ( String ) obj ) ) ; } } else { result . add ( m_dataView . getItemById ( ( String ) val ) ) ; } return result ; |
public class Monetary { /** * Query all currencies matching the given query .
* @ param query The { @ link javax . money . CurrencyQuery } , not null .
* @ return the list of known currencies , never null . */
public static Collection < CurrencyUnit > getCurrencies ( CurrencyQuery query ) { } } | return Optional . ofNullable ( MONETARY_CURRENCIES_SINGLETON_SPI ( ) ) . orElseThrow ( ( ) -> new MonetaryException ( "No MonetaryCurrenciesSingletonSpi loaded, check your system setup." ) ) . getCurrencies ( query ) ; |
public class AdminObjectService { /** * { @ inheritDoc } */
@ Override public Object createResource ( ResourceInfo refInfo ) throws Exception { } } | final boolean trace = TraceComponent . isAnyTracingEnabled ( ) ; if ( trace && tc . isEntryEnabled ( ) ) Tr . entry ( this , tc , "createResource" , refInfo ) ; try { BootstrapContextImpl bootstrapContext = bootstrapContextRef . getServiceWithException ( ) ; if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isDebugEnabled ( ) ) Tr . debug ( this , tc , "loading" , adminObjectImplClassName ) ; Class < ? > adminObjectClass = bootstrapContext . loadClass ( adminObjectImplClassName ) ; ComponentMetaData cData = ComponentMetaDataAccessorImpl . getComponentMetaDataAccessor ( ) . getComponentMetaData ( ) ; String currentApp = null ; ResourceAdapterMetaData metadata = bootstrapContext . getResourceAdapterMetaData ( ) ; // cData is null when its not in an application thread
if ( cData != null && cData != metadata ) { currentApp = cData . getJ2EEName ( ) . getApplication ( ) ; applications . add ( cData . getJ2EEName ( ) . getApplication ( ) ) ; } String adapterName = bootstrapContext . getResourceAdapterName ( ) ; if ( metadata != null && metadata . isEmbedded ( ) && cData != metadata ) { // Metadata is null for SIB / WMQ . No check needed if called from activationSpec
String embeddedApp = metadata . getJ2EEName ( ) . getApplication ( ) ; Utils . checkAccessibility ( name , adapterName , embeddedApp , currentApp , false ) ; } Object adminObject = adminObjectClass . getConstructor ( ) . newInstance ( ) ; bootstrapContext . configure ( adminObject , name , properties , null , null , null ) ; return adminObject ; } catch ( Exception x ) { throw x ; } catch ( Error x ) { throw x ; } finally { if ( trace && tc . isEntryEnabled ( ) ) Tr . exit ( this , tc , "createResource" ) ; } |
public class WarsApi { /** * Get war information Return details about a war - - - This route is cached
* for up to 3600 seconds
* @ param warId
* ID for a war ( 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 )
* @ return WarResponse
* @ throws ApiException
* If fail to call the API , e . g . server error or cannot
* deserialize the response body */
public WarResponse getWarsWarId ( Integer warId , String datasource , String ifNoneMatch ) throws ApiException { } } | ApiResponse < WarResponse > resp = getWarsWarIdWithHttpInfo ( warId , datasource , ifNoneMatch ) ; return resp . getData ( ) ; |
public class AbstractGitFlowMojo { /** * Validates plugin configuration . Throws exception if configuration is not
* valid .
* @ param params
* Configuration parameters to validate .
* @ throws MojoFailureException
* If configuration is not valid . */
protected void validateConfiguration ( String ... params ) throws MojoFailureException { } } | if ( StringUtils . isNotBlank ( argLine ) && MAVEN_DISALLOWED_PATTERN . matcher ( argLine ) . find ( ) ) { throw new MojoFailureException ( "The argLine doesn't match allowed pattern." ) ; } if ( params != null && params . length > 0 ) { for ( String p : params ) { if ( StringUtils . isNotBlank ( p ) && MAVEN_DISALLOWED_PATTERN . matcher ( p ) . find ( ) ) { throw new MojoFailureException ( "The '" + p + "' value doesn't match allowed pattern." ) ; } } } |
public class LayoutPrint { /** * PrintIt Method . */
public void printIt ( Record recLayout , PrintWriter out , int iIndents , String strEnd ) { } } | // Print out the current record
String strName = recLayout . getField ( Layout . NAME ) . toString ( ) ; String strType = recLayout . getField ( Layout . TYPE ) . toString ( ) ; String strValue = recLayout . getField ( Layout . FIELD_VALUE ) . toString ( ) ; String strReturns = recLayout . getField ( Layout . RETURNS_VALUE ) . toString ( ) ; String strMax = recLayout . getField ( Layout . MAXIMUM ) . toString ( ) ; String strDescription = recLayout . getField ( Layout . COMMENT ) . toString ( ) ; boolean bLoop = false ; if ( ( strType . equalsIgnoreCase ( "module" ) ) || ( strType . equalsIgnoreCase ( "enum" ) ) || ( strType . equalsIgnoreCase ( "struct" ) ) || ( strType . equalsIgnoreCase ( "interface" ) ) ) bLoop = true ; if ( bLoop ) { this . println ( out , strType + " " + strName , strDescription , iIndents , "" ) ; String strEndLoop = ";" ; if ( strType . equalsIgnoreCase ( "enum" ) ) strEndLoop = null ; this . println ( out , "{" , null , iIndents , "" ) ; Layout recLayoutLoop = new Layout ( recLayout . findRecordOwner ( ) ) ; recLayoutLoop . setKeyArea ( Layout . PARENT_FOLDER_ID_KEY ) ; recLayoutLoop . addListener ( new SubFileFilter ( recLayout ) ) ; try { boolean bFirstLoop = true ; while ( recLayoutLoop . hasNext ( ) ) { if ( strEndLoop == null ) if ( ! bFirstLoop ) this . println ( out , "," , null , 0 , "" ) ; recLayoutLoop . next ( ) ; this . printIt ( recLayoutLoop , out , iIndents + 1 , strEndLoop ) ; bFirstLoop = false ; } if ( strEndLoop == null ) if ( ! bFirstLoop ) this . println ( out , "" , null , 0 , "" ) ; // Carriage return
recLayoutLoop . free ( ) ; recLayoutLoop = null ; } catch ( DBException ex ) { ex . printStackTrace ( ) ; } this . println ( out , "}" , null , iIndents , strEnd ) ; } else { if ( strType . equalsIgnoreCase ( "collection" ) ) strType = "typedef sequence<" + strValue + ">" ; else if ( strType . equalsIgnoreCase ( "method" ) ) { strType = strReturns + " " ; strName += "(" + strValue + ")" ; } else if ( strType . equalsIgnoreCase ( "comment" ) ) strType = "//\t" + strType ; else if ( strValue . length ( ) > 0 ) strName += " = " + strValue ; this . println ( out , strType + " " + strName , strDescription , iIndents , strEnd ) ; } |
public class CalendarPanel { /** * labelMonthIndicatorMousePressed , This event is called any time that the user clicks on the
* month display label in the calendar . This opens a menu that the user can use to select a new
* month in the same year . */
private void labelMonthIndicatorMousePressed ( MouseEvent e ) { } } | // Skip this function if the settings have not been applied .
if ( settings == null ) { return ; } // If the month menu is disabled , then return .
if ( settings . getEnableMonthMenu ( ) == false ) { return ; } // Create and show the month popup menu .
JPopupMenu monthPopupMenu = new JPopupMenu ( ) ; String [ ] allLocalMonths = settings . getTranslationArrayStandaloneLongMonthNames ( ) ; for ( int i = 0 ; i < allLocalMonths . length ; ++ i ) { final String localMonth = allLocalMonths [ i ] ; final int localMonthZeroBasedIndexTemp = i ; if ( ! localMonth . isEmpty ( ) ) { monthPopupMenu . add ( new JMenuItem ( new AbstractAction ( localMonth ) { int localMonthZeroBasedIndex = localMonthZeroBasedIndexTemp ; @ Override public void actionPerformed ( ActionEvent e ) { drawCalendar ( displayedYearMonth . getYear ( ) , Month . of ( localMonthZeroBasedIndex + 1 ) ) ; } } ) ) ; } } Point menuLocation = getMonthOrYearMenuLocation ( labelMonth , monthPopupMenu ) ; monthPopupMenu . show ( monthAndYearInnerPanel , menuLocation . x , menuLocation . y ) ; |
public class BaseDetectFiducialSquare { /** * Computes the fraction of pixels inside the image border which are black
* @ param pixelThreshold Pixel ' s less than this value are considered black
* @ return fraction of border that ' s black */
protected double computeFractionBoundary ( float pixelThreshold ) { } } | // TODO ignore outer pixels from this computation . Will require 8 regions ( 4 corners + top / bottom + left / right )
final int w = square . width ; int radius = ( int ) ( w * borderWidthFraction ) ; int innerWidth = w - 2 * radius ; int total = w * w - innerWidth * innerWidth ; int count = 0 ; for ( int y = 0 ; y < radius ; y ++ ) { int indexTop = y * w ; int indexBottom = ( w - radius + y ) * w ; for ( int x = 0 ; x < w ; x ++ ) { if ( square . data [ indexTop ++ ] < pixelThreshold ) count ++ ; if ( square . data [ indexBottom ++ ] < pixelThreshold ) count ++ ; } } for ( int y = radius ; y < w - radius ; y ++ ) { int indexLeft = y * w ; int indexRight = y * w + w - radius ; for ( int x = 0 ; x < radius ; x ++ ) { if ( square . data [ indexLeft ++ ] < pixelThreshold ) count ++ ; if ( square . data [ indexRight ++ ] < pixelThreshold ) count ++ ; } } return count / ( double ) total ; |
public class IbanUtil { /** * get bank number of iban .
* @ param pstring string with iban
* @ return bank number */
public static String getBankNumberOfIban ( final String pstring ) { } } | final String compressedIban = ibanCompress ( pstring ) ; final String country = StringUtils . substring ( compressedIban , 0 , 2 ) ; final IbanLengthDefinition length = IBAN_LENGTH_MAP . ibanLengths ( ) . get ( country ) ; return length == null ? null : StringUtils . substring ( compressedIban , length . getBankNumberStart ( ) , length . getBankNumberEnd ( ) ) ; |
public class A_CmsImport { /** * Checks if the resources is in the list of immutalbe resources . < p >
* @ param translatedName the name of the resource
* @ param immutableResources the list of the immutable resources
* @ return true or false */
protected boolean checkImmutable ( String translatedName , List < String > immutableResources ) { } } | boolean resourceNotImmutable = true ; if ( immutableResources . contains ( translatedName ) ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( Messages . get ( ) . getBundle ( ) . key ( Messages . LOG_IMPORTEXPORT_RESOURCENAME_IMMUTABLE_1 , translatedName ) ) ; } // this resource must not be modified by an import if it already exists
String storedSiteRoot = m_cms . getRequestContext ( ) . getSiteRoot ( ) ; try { m_cms . getRequestContext ( ) . setSiteRoot ( "/" ) ; m_cms . readResource ( translatedName ) ; resourceNotImmutable = false ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( Messages . get ( ) . getBundle ( ) . key ( Messages . LOG_IMPORTEXPORT_IMMUTABLE_FLAG_SET_1 , translatedName ) ) ; } } catch ( CmsException e ) { // resourceNotImmutable will be true
if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( Messages . get ( ) . getBundle ( ) . key ( Messages . LOG_IMPORTEXPORT_ERROR_ON_TEST_IMMUTABLE_1 , translatedName ) , e ) ; } } finally { m_cms . getRequestContext ( ) . setSiteRoot ( storedSiteRoot ) ; } } return resourceNotImmutable ; |
public class FileSystem { /** * Listing a directory
* The returned results include its block location if it is a file
* The results are filtered by the given path filter
* @ param f a path
* @ param filter a path filter
* @ return an iterator that traverses statuses of the files / directories
* in the given path
* @ throws FileNotFoundException if < code > f < / code > does not exist
* @ throws IOException if any I / O error occurred */
@ Deprecated public RemoteIterator < LocatedFileStatus > listLocatedStatus ( final Path f , final PathFilter filter ) throws FileNotFoundException , IOException { } } | return new RemoteIterator < LocatedFileStatus > ( ) { private final FileStatus [ ] stats ; private int i = 0 ; { // initializer
stats = listStatus ( f , filter ) ; if ( stats == null ) { throw new FileNotFoundException ( "File " + f + " does not exist." ) ; } } @ Override public boolean hasNext ( ) { return i < stats . length ; } @ Override public LocatedFileStatus next ( ) throws IOException { if ( ! hasNext ( ) ) { throw new NoSuchElementException ( "No more entry in " + f ) ; } FileStatus result = stats [ i ++ ] ; BlockLocation [ ] locs = result . isDir ( ) ? null : getFileBlockLocations ( result , 0 , result . getLen ( ) ) ; return new LocatedFileStatus ( result , locs ) ; } } ; |
public class FileTransferNegotiator { /** * Selects an appropriate stream negotiator after examining the incoming file transfer request .
* @ param request The related file transfer request .
* @ return The file transfer object that handles the transfer
* @ throws NoStreamMethodsOfferedException If there are either no stream methods contained in the packet , or
* there is not an appropriate stream method .
* @ throws NotConnectedException
* @ throws NoAcceptableTransferMechanisms
* @ throws InterruptedException */
public StreamNegotiator selectStreamNegotiator ( FileTransferRequest request ) throws NotConnectedException , NoStreamMethodsOfferedException , NoAcceptableTransferMechanisms , InterruptedException { } } | StreamInitiation si = request . getStreamInitiation ( ) ; FormField streamMethodField = getStreamMethodField ( si . getFeatureNegotiationForm ( ) ) ; if ( streamMethodField == null ) { String errorMessage = "No stream methods contained in stanza." ; StanzaError . Builder error = StanzaError . from ( StanzaError . Condition . bad_request , errorMessage ) ; IQ iqPacket = IQ . createErrorResponse ( si , error ) ; connection ( ) . sendStanza ( iqPacket ) ; throw new FileTransferException . NoStreamMethodsOfferedException ( ) ; } // select the appropriate protocol
StreamNegotiator selectedStreamNegotiator ; try { selectedStreamNegotiator = getNegotiator ( streamMethodField ) ; } catch ( NoAcceptableTransferMechanisms e ) { IQ iqPacket = IQ . createErrorResponse ( si , StanzaError . from ( StanzaError . Condition . bad_request , "No acceptable transfer mechanism" ) ) ; connection ( ) . sendStanza ( iqPacket ) ; throw e ; } // return the appropriate negotiator
return selectedStreamNegotiator ; |
public class CmsWebdavServlet { /** * Process a LOCK WebDAV request for the specified resource . < p >
* @ param req the servlet request we are processing
* @ param resp the servlet response we are creating
* @ throws IOException if an input / output error occurs */
@ SuppressWarnings ( "unchecked" ) protected void doLock ( HttpServletRequest req , HttpServletResponse resp ) throws IOException { } } | String path = getRelativePath ( req ) ; // Check if webdav is set to read only
if ( m_readOnly ) { resp . setStatus ( CmsWebdavStatus . SC_FORBIDDEN ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( Messages . get ( ) . getBundle ( ) . key ( Messages . LOG_WEBDAV_READ_ONLY_0 ) ) ; } return ; } // Check if resource is locked
if ( isLocked ( req ) ) { resp . setStatus ( CmsWebdavStatus . SC_LOCKED ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( Messages . get ( ) . getBundle ( ) . key ( Messages . LOG_ITEM_LOCKED_1 , path ) ) ; } return ; } CmsRepositoryLockInfo lock = new CmsRepositoryLockInfo ( ) ; // Parsing depth header
String depthStr = req . getHeader ( HEADER_DEPTH ) ; if ( depthStr == null ) { lock . setDepth ( CmsRepositoryLockInfo . DEPTH_INFINITY_VALUE ) ; } else { if ( depthStr . equals ( "0" ) ) { lock . setDepth ( 0 ) ; } else { lock . setDepth ( CmsRepositoryLockInfo . DEPTH_INFINITY_VALUE ) ; } } // Parsing timeout header
int lockDuration = CmsRepositoryLockInfo . TIMEOUT_INFINITE_VALUE ; lock . setExpiresAt ( System . currentTimeMillis ( ) + ( lockDuration * 1000 ) ) ; int lockRequestType = LOCK_CREATION ; Element lockInfoNode = null ; try { SAXReader saxReader = new SAXReader ( ) ; Document document = saxReader . read ( new InputSource ( req . getInputStream ( ) ) ) ; // Get the root element of the document
Element rootElement = document . getRootElement ( ) ; lockInfoNode = rootElement ; } catch ( Exception e ) { lockRequestType = LOCK_REFRESH ; } if ( lockInfoNode != null ) { // Reading lock information
Iterator < Element > iter = lockInfoNode . elementIterator ( ) ; Element lockScopeNode = null ; Element lockTypeNode = null ; Element lockOwnerNode = null ; while ( iter . hasNext ( ) ) { Element currentElem = iter . next ( ) ; switch ( currentElem . getNodeType ( ) ) { case Node . TEXT_NODE : break ; case Node . ELEMENT_NODE : String nodeName = currentElem . getName ( ) ; if ( nodeName . endsWith ( TAG_LOCKSCOPE ) ) { lockScopeNode = currentElem ; } if ( nodeName . endsWith ( TAG_LOCKTYPE ) ) { lockTypeNode = currentElem ; } if ( nodeName . endsWith ( TAG_OWNER ) ) { lockOwnerNode = currentElem ; } break ; default : break ; } } if ( lockScopeNode != null ) { iter = lockScopeNode . elementIterator ( ) ; while ( iter . hasNext ( ) ) { Element currentElem = iter . next ( ) ; switch ( currentElem . getNodeType ( ) ) { case Node . TEXT_NODE : break ; case Node . ELEMENT_NODE : String tempScope = currentElem . getName ( ) ; if ( tempScope . indexOf ( ':' ) != - 1 ) { lock . setScope ( tempScope . substring ( tempScope . indexOf ( ':' ) + 1 ) ) ; } else { lock . setScope ( tempScope ) ; } break ; default : break ; } } if ( lock . getScope ( ) == null ) { // Bad request
resp . setStatus ( CmsWebdavStatus . SC_BAD_REQUEST ) ; } } else { // Bad request
resp . setStatus ( CmsWebdavStatus . SC_BAD_REQUEST ) ; } if ( lockTypeNode != null ) { iter = lockTypeNode . elementIterator ( ) ; while ( iter . hasNext ( ) ) { Element currentElem = iter . next ( ) ; switch ( currentElem . getNodeType ( ) ) { case Node . TEXT_NODE : break ; case Node . ELEMENT_NODE : String tempType = currentElem . getName ( ) ; if ( tempType . indexOf ( ':' ) != - 1 ) { lock . setType ( tempType . substring ( tempType . indexOf ( ':' ) + 1 ) ) ; } else { lock . setType ( tempType ) ; } break ; default : break ; } } if ( lock . getType ( ) == null ) { // Bad request
resp . setStatus ( CmsWebdavStatus . SC_BAD_REQUEST ) ; } } else { // Bad request
resp . setStatus ( CmsWebdavStatus . SC_BAD_REQUEST ) ; } if ( lockOwnerNode != null ) { iter = lockOwnerNode . elementIterator ( ) ; while ( iter . hasNext ( ) ) { Element currentElem = iter . next ( ) ; switch ( currentElem . getNodeType ( ) ) { case Node . TEXT_NODE : lock . setOwner ( lock . getOwner ( ) + currentElem . getStringValue ( ) ) ; break ; case Node . ELEMENT_NODE : lock . setOwner ( lock . getOwner ( ) + currentElem . getStringValue ( ) ) ; break ; default : break ; } } if ( lock . getOwner ( ) == null ) { // Bad request
resp . setStatus ( CmsWebdavStatus . SC_BAD_REQUEST ) ; } } else { lock . setOwner ( "" ) ; } } lock . setPath ( path ) ; lock . setUsername ( m_username ) ; if ( lockRequestType == LOCK_REFRESH ) { CmsRepositoryLockInfo currentLock = m_session . getLock ( path ) ; if ( currentLock == null ) { lockRequestType = LOCK_CREATION ; } } if ( lockRequestType == LOCK_CREATION ) { try { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( Messages . get ( ) . getBundle ( ) . key ( Messages . LOG_LOCK_ITEM_1 , lock . getOwner ( ) ) ) ; } boolean result = m_session . lock ( path , lock ) ; if ( result ) { // Add the Lock - Token header as by RFC 2518 8.10.1
// - only do this for newly created locks
resp . addHeader ( HEADER_LOCKTOKEN , "<opaquelocktoken:" + generateLockToken ( req , lock ) + ">" ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( Messages . get ( ) . getBundle ( ) . key ( Messages . LOG_LOCK_ITEM_FAILED_0 ) ) ; } } else { resp . setStatus ( CmsWebdavStatus . SC_LOCKED ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( Messages . get ( ) . getBundle ( ) . key ( Messages . LOG_LOCK_ITEM_SUCCESS_0 ) ) ; } return ; } } catch ( CmsVfsResourceNotFoundException rnfex ) { resp . setStatus ( CmsWebdavStatus . SC_NOT_FOUND ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( Messages . get ( ) . getBundle ( ) . key ( Messages . LOG_ITEM_NOT_FOUND_1 , path ) ) ; } return ; } catch ( CmsSecurityException sex ) { resp . setStatus ( CmsWebdavStatus . SC_FORBIDDEN ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( Messages . get ( ) . getBundle ( ) . key ( Messages . LOG_NO_PERMISSION_0 ) ) ; } return ; } catch ( CmsException ex ) { resp . setStatus ( CmsWebdavStatus . SC_INTERNAL_SERVER_ERROR ) ; if ( LOG . isErrorEnabled ( ) ) { LOG . error ( Messages . get ( ) . getBundle ( ) . key ( Messages . LOG_REPOSITORY_ERROR_2 , "LOCK" , path ) , ex ) ; } return ; } } // Set the status , then generate the XML response containing
// the lock information
Document doc = DocumentHelper . createDocument ( ) ; Element propElem = doc . addElement ( new QName ( TAG_PROP , Namespace . get ( DEFAULT_NAMESPACE ) ) ) ; Element lockElem = addElement ( propElem , TAG_LOCKDISCOVERY ) ; addLockElement ( lock , lockElem , generateLockToken ( req , lock ) ) ; resp . setStatus ( CmsWebdavStatus . SC_OK ) ; resp . setContentType ( "text/xml; charset=UTF-8" ) ; Writer writer = resp . getWriter ( ) ; doc . write ( writer ) ; writer . close ( ) ; |
public class TaskSlotTable { @ Nullable private TaskSlot getTaskSlot ( AllocationID allocationId ) { } } | Preconditions . checkNotNull ( allocationId ) ; return allocationIDTaskSlotMap . get ( allocationId ) ; |
public class ExampleClass { /** * An example method .
* @ param arg1 An argument .
* @ param arg2 An argument .
* @ param arg3 An argument .
* @ return All arguments stored in an array . */
public Object [ ] method ( Object arg1 , Object arg2 , Object arg3 ) { } } | return new Object [ ] { arg1 , arg2 , arg3 } ; |
public class LUDecompositionBase_ZDRM { /** * Writes the upper triangular matrix into the specified matrix .
* @ param upper Where the upper triangular matrix is writen to . */
@ Override public ZMatrixRMaj getUpper ( ZMatrixRMaj upper ) { } } | int numRows = LU . numRows < LU . numCols ? LU . numRows : LU . numCols ; int numCols = LU . numCols ; upper = UtilDecompositons_ZDRM . checkZerosLT ( upper , numRows , numCols ) ; for ( int i = 0 ; i < numRows ; i ++ ) { for ( int j = i ; j < numCols ; j ++ ) { int indexLU = LU . getIndex ( i , j ) ; int indexU = upper . getIndex ( i , j ) ; double real = LU . data [ indexLU ] ; double imaginary = LU . data [ indexLU + 1 ] ; upper . data [ indexU ] = real ; upper . data [ indexU + 1 ] = imaginary ; } } return upper ; |
public class DbgpXmlEntityParser { /** * $ NON - NLS - 1 $ */
public static IDbgpProperty parseProperty ( Element property ) { } } | /* * attributes : name , fullname , type , children , numchildren , constant , encoding , size , key , address */
// may exist as an attribute of the property or as child element
final String name = getFromChildOrAttr ( property , ATTR_NAME ) ; final String fullName = getFromChildOrAttr ( property , ATTR_FULLNAME ) ; final String type = property . getAttribute ( ATTR_TYPE ) ; // hasChildren
boolean hasChildren = false ; if ( property . hasAttribute ( ATTR_CHILDREN ) ) { hasChildren = makeBoolean ( property . getAttribute ( ATTR_CHILDREN ) ) ; } // Children count
int childrenCount = - 1 ; if ( property . hasAttribute ( ATTR_NUMCHILDREN ) ) { childrenCount = Integer . parseInt ( property . getAttribute ( ATTR_NUMCHILDREN ) ) ; } // Page
int page = 0 ; if ( property . hasAttribute ( ATTR_PAGE ) ) { page = Integer . parseInt ( property . getAttribute ( ATTR_PAGE ) ) ; } // Page Size
int pagesize = - 1 ; if ( property . hasAttribute ( ATTR_PAGE_SIZE ) ) { pagesize = Integer . parseInt ( property . getAttribute ( ATTR_PAGE_SIZE ) ) ; } // Constant
boolean constant = false ; if ( property . hasAttribute ( ATTR_CONSTANT ) ) { constant = makeBoolean ( property . getAttribute ( ATTR_CONSTANT ) ) ; } // Key
String key = null ; if ( property . hasAttribute ( ATTR_KEY ) ) { key = property . getAttribute ( ATTR_KEY ) ; } // memory address
String address = null ; if ( property . hasAttribute ( ATTR_ADDRESS ) ) { address = property . getAttribute ( ATTR_ADDRESS ) ; } // Value
String value = "" ; // $ NON - NLS - 1 $
NodeList list = property . getElementsByTagName ( "value" ) ; // $ NON - NLS - 1 $
if ( list . getLength ( ) == 0 ) { value = getEncodedValue ( property ) ; } else { value = getEncodedValue ( ( Element ) list . item ( 0 ) ) ; } // Children
IDbgpProperty [ ] availableChildren = NO_CHILDREN ; if ( hasChildren ) { // final NodeList children = property
// . getElementsByTagName ( TAG _ PROPERTY ) ;
List < Element > children = getChildElements ( property ) ; final int length = children . size ( ) ; // children . getLength ( ) ;
if ( length > 0 ) { availableChildren = new IDbgpProperty [ length ] ; for ( int i = 0 ; i < length ; ++ i ) { Element child = ( Element ) children . get ( i ) ; availableChildren [ i ] = parseProperty ( child ) ; } } } if ( childrenCount < 0 ) { childrenCount = availableChildren . length ; } return new DbgpProperty ( name , fullName , type , value , childrenCount , hasChildren , constant , key , address , availableChildren , page , pagesize ) ; |
public class PresentsDObjectMgr { /** * Performs the processing associated with an event , notifying listeners and the like . */
protected void processEvent ( DEvent event ) { } } | // look up the target object
DObject target = _objects . get ( event . getTargetOid ( ) ) ; if ( target == null ) { log . debug ( "Event target no longer exists" , "event" , event ) ; return ; } // check the event ' s permissions
if ( ! target . checkPermissions ( event ) ) { log . warning ( "Event failed permissions check" , "event" , event , "target" , target ) ; return ; } if ( dispatchEvent ( event , target ) ) { // unless requested not to , notify any proxies
target . notifyProxies ( event ) ; } |
public class Output { /** * { @ inheritDoc } */
@ Override public void writeNumber ( Number num ) { } } | buf . put ( AMF . TYPE_NUMBER ) ; buf . putDouble ( num . doubleValue ( ) ) ; |
public class Latkes { /** * Loads the local . props . */
private static void loadLocalProps ( ) { } } | if ( null == localProps ) { localProps = new Properties ( ) ; } try { InputStream resourceAsStream ; final String localPropsEnv = System . getenv ( "LATKE_LOCAL_PROPS" ) ; if ( StringUtils . isNotBlank ( localPropsEnv ) ) { LOGGER . debug ( "Loading local.properties from env var [$LATKE_LOCAL_PROPS=" + localPropsEnv + "]" ) ; resourceAsStream = new FileInputStream ( localPropsEnv ) ; } else { LOGGER . debug ( "Loading local.properties from classpath [/local.properties]" ) ; resourceAsStream = Latkes . class . getResourceAsStream ( "/local.properties" ) ; } if ( null != resourceAsStream ) { localProps . load ( resourceAsStream ) ; LOGGER . debug ( "Loaded local.properties" ) ; } } catch ( final Exception e ) { LOGGER . log ( Level . DEBUG , "Loads local.properties failed, ignored" ) ; } |
public class ListTagsForResourceResult { /** * A list of tags for the resource .
* < b > NOTE : < / b > This method appends the values to the existing list ( if any ) . Use
* { @ link # setTagList ( java . util . Collection ) } or { @ link # withTagList ( java . util . Collection ) } if you want to override
* the existing values .
* @ param tagList
* A list of tags for the resource .
* @ return Returns a reference to this object so that method calls can be chained together . */
public ListTagsForResourceResult withTagList ( Tag ... tagList ) { } } | if ( this . tagList == null ) { setTagList ( new java . util . ArrayList < Tag > ( tagList . length ) ) ; } for ( Tag ele : tagList ) { this . tagList . add ( ele ) ; } return this ; |
public class DescribeAnalysisSchemesRequest { /** * The analysis schemes you want to describe .
* @ return The analysis schemes you want to describe . */
public java . util . List < String > getAnalysisSchemeNames ( ) { } } | if ( analysisSchemeNames == null ) { analysisSchemeNames = new com . amazonaws . internal . SdkInternalList < String > ( ) ; } return analysisSchemeNames ; |
public class Operator { /** * concat 2 CharSequences
* @ param left
* @ param right
* @ return concated String */
public static CharSequence concat ( CharSequence left , CharSequence right ) { } } | if ( left instanceof Appendable ) { try { ( ( Appendable ) left ) . append ( right ) ; return left ; } catch ( IOException e ) { } } return new StringBuilder ( left ) . append ( right ) ; |
public class PlayerPlaylist { /** * Return the current track .
* @ return current track or null if none has been added to the player playlist . */
public SoundCloudTrack getCurrentTrack ( ) { } } | if ( mCurrentTrackIndex > - 1 && mCurrentTrackIndex < mSoundCloudPlaylist . getTracks ( ) . size ( ) ) { return mSoundCloudPlaylist . getTracks ( ) . get ( mCurrentTrackIndex ) ; } return null ; |
public class ContentsIdExtension { /** * Get by contents data type
* @ param type
* contents data type
* @ return contents ids */
public List < ContentsId > getIds ( String type ) { } } | List < ContentsId > contentsIds = null ; ContentsDao contentsDao = geoPackage . getContentsDao ( ) ; try { if ( contentsIdDao . isTableExists ( ) ) { QueryBuilder < Contents , String > contentsQueryBuilder = contentsDao . queryBuilder ( ) ; QueryBuilder < ContentsId , Long > contentsIdQueryBuilder = contentsIdDao . queryBuilder ( ) ; contentsQueryBuilder . where ( ) . eq ( Contents . COLUMN_DATA_TYPE , type ) ; contentsIdQueryBuilder . join ( contentsQueryBuilder ) ; contentsIds = contentsIdQueryBuilder . query ( ) ; } else { contentsIds = new ArrayList < > ( ) ; } } catch ( SQLException e ) { throw new GeoPackageException ( "Failed to query for contents id by contents data type. GeoPackage: " + geoPackage . getName ( ) + ", Type: " + type , e ) ; } return contentsIds ; |
public class FSDirectory { /** * create a directory at index pos .
* The parent path to the directory is at [ 0 , pos - 1 ] .
* All ancestors exist . Newly created one stored at index pos . */
private void unprotectedMkdir ( long inodeId , INode [ ] inodes , int pos , byte [ ] name , PermissionStatus permission , boolean inheritPermission , long timestamp ) throws QuotaExceededException { } } | inodes [ pos ] = addChild ( inodes , pos , new INodeDirectory ( inodeId , name , permission , timestamp ) , - 1 , inheritPermission ) ; |
public class qos_stats { /** * < pre >
* converts nitro response into object and returns the object array in case of get request .
* < / pre > */
protected base_resource [ ] get_nitro_response ( nitro_service service , String response ) throws Exception { } } | qos_stats [ ] resources = new qos_stats [ 1 ] ; qos_response result = ( qos_response ) service . get_payload_formatter ( ) . string_to_resource ( qos_response . class , response ) ; if ( result . errorcode != 0 ) { if ( result . errorcode == 444 ) { service . clear_session ( ) ; } if ( result . severity != null ) { if ( result . severity . equals ( "ERROR" ) ) throw new nitro_exception ( result . message , result . errorcode ) ; } else { throw new nitro_exception ( result . message , result . errorcode ) ; } } resources [ 0 ] = result . qos ; return resources ; |
public class CPInstancePersistenceImpl { /** * Returns the last cp instance in the ordered set where displayDate & lt ; & # 63 ; and status = & # 63 ; .
* @ param displayDate the display date
* @ param status the status
* @ param orderByComparator the comparator to order the set by ( optionally < code > null < / code > )
* @ return the last matching cp instance , or < code > null < / code > if a matching cp instance could not be found */
@ Override public CPInstance fetchByLtD_S_Last ( Date displayDate , int status , OrderByComparator < CPInstance > orderByComparator ) { } } | int count = countByLtD_S ( displayDate , status ) ; if ( count == 0 ) { return null ; } List < CPInstance > list = findByLtD_S ( displayDate , status , count - 1 , count , orderByComparator ) ; if ( ! list . isEmpty ( ) ) { return list . get ( 0 ) ; } return null ; |
public class CommentsForComparedCommit { /** * An array of comment objects . Each comment object contains information about a comment on the comparison between
* commits .
* @ param comments
* An array of comment objects . Each comment object contains information about a comment on the comparison
* between commits . */
public void setComments ( java . util . Collection < Comment > comments ) { } } | if ( comments == null ) { this . comments = null ; return ; } this . comments = new java . util . ArrayList < Comment > ( comments ) ; |
public class TypeHandlerUtils { /** * Creates new { @ link java . sql . Array } instance .
* Can be invoked only for JDBC4 driver
* @ param conn SQL connection
* @ param typeName array type name
* @ param elements array of elements
* @ return new { @ link java . sql . Array } instance
* @ throws org . midao . jdbc . core . exception . MjdbcSQLException */
public static Object createArrayOf ( Connection conn , String typeName , Object [ ] elements ) throws MjdbcSQLException { } } | Object result = null ; try { result = MappingUtils . invokeFunction ( conn , "createArrayOf" , new Class [ ] { String . class , Object [ ] . class } , new Object [ ] { typeName , elements } ) ; } catch ( MjdbcException ex ) { throw new MjdbcSQLException ( "createArrayOf is not supported by JDBC Driver" , ex ) ; } return result ; |
public class Base58 { /** * Encodes the given bytes in base58 . No checksum is appended .
* @ param input byte array input
* @ return string encoded in Base58 */
public static String encode ( byte [ ] input ) { } } | if ( input . length == 0 ) { return "" ; } input = copyOfRange ( input , 0 , input . length ) ; // Count leading zeroes .
int zeroCount = 0 ; while ( zeroCount < input . length && input [ zeroCount ] == 0 ) { ++ zeroCount ; } // The actual encoding .
byte [ ] temp = new byte [ input . length * 2 ] ; int j = temp . length ; int startAt = zeroCount ; while ( startAt < input . length ) { byte mod = divmod58 ( input , startAt ) ; if ( input [ startAt ] == 0 ) { ++ startAt ; } temp [ -- j ] = ( byte ) ALPHABET [ mod ] ; } // Strip extra ' 1 ' if there are some after decoding .
while ( j < temp . length && temp [ j ] == ALPHABET [ 0 ] ) { ++ j ; } // Add as many leading ' 1 ' as there were leading zeros .
while ( -- zeroCount >= 0 ) { temp [ -- j ] = ( byte ) ALPHABET [ 0 ] ; } byte [ ] output = copyOfRange ( temp , j , temp . length ) ; try { return new String ( output , "US-ASCII" ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; // Cannot happen .
} |
public class AttributeDefinition { /** * Gets a set of any { @ link org . jboss . as . controller . registry . AttributeAccess . Flag flags } used
* to indicate special characteristics of the attribute
* @ return the flags . Will not be { @ code null } but may be empty .
* @ deprecated In the next release , the return type of this method will become simply { @ code Set } and the returned object will be immutable , so any callers should update their code to reflect that */
@ Deprecated public EnumSet < AttributeAccess . Flag > getFlags ( ) { } } | if ( flags . isEmpty ( ) ) { return EnumSet . noneOf ( AttributeAccess . Flag . class ) ; } AttributeAccess . Flag [ ] array = flags . toArray ( new AttributeAccess . Flag [ flags . size ( ) ] ) ; return array . length == 1 ? EnumSet . of ( array [ 0 ] ) : EnumSet . of ( array [ 0 ] , array ) ; |
public class ObsFeatureConjoiner { /** * Loops through all examples to create the features , thereby ensuring that the FTS are initialized . */
private void extractAllFeats ( FgExampleList data , FactorTemplateList templates ) { } } | // Create a " no - op " counter .
IFgModel counts = new IFgModel ( ) { @ Override public void addAfterScaling ( FeatureVector fv , double multiplier ) { } @ Override public void add ( int feat , double addend ) { } } ; // Loop over all factors in the dataset .
for ( int i = 0 ; i < data . size ( ) ; i ++ ) { if ( i % 1000 == 0 ) { log . debug ( "Processing example: " + i ) ; } LFgExample ex = data . get ( i ) ; FactorGraph fgLat = MarginalLogLikelihood . getFgLat ( ex . getFactorGraph ( ) , ex . getGoldConfig ( ) ) ; // Create a " no - op " inferencer , which returns arbitrary marginals .
NoOpInferencer inferencer = new NoOpInferencer ( ex . getFactorGraph ( ) ) ; for ( int a = 0 ; a < ex . getFactorGraph ( ) . getNumFactors ( ) ; a ++ ) { Factor f = fgLat . getFactor ( a ) ; if ( f instanceof ObsFeatureCarrier && f instanceof TemplateFactor ) { // For each observation function extractor .
int t = templates . getTemplateId ( ( TemplateFactor ) f ) ; if ( t != - 1 ) { ( ( ObsFeatureCarrier ) f ) . getObsFeatures ( ) ; } } else { // For each standard factor .
f = ex . getFactorGraph ( ) . getFactor ( a ) ; if ( f instanceof GlobalFactor ) { ( ( GlobalFactor ) f ) . addExpectedPartials ( counts , 0 , inferencer , a ) ; } else { VarTensor marg = inferencer . getMarginalsForFactorId ( a ) ; f . addExpectedPartials ( counts , marg , 0 ) ; } } } } |
public class RuleEvaluator { /** * Return true if all entries in the " match " map pass the predicate tests for the resource
* @ param resource the resource
* @ param predicateTransformer transformer to convert a String into a Predicate check
* @ param listpred
* @ param ruleResource
* @ param sourceIdentity */
@ SuppressWarnings ( "rawtypes" ) boolean predicateMatchRules ( final Map < String , String > resource , final Function < String , Predicate < String > > predicateTransformer , final Function < List , Predicate < String > > listpred , final Map < String , Object > ruleResource , final String sourceIdentity ) { } } | for ( final Object o : ruleResource . entrySet ( ) ) { final Map . Entry entry = ( Map . Entry ) o ; final String key = ( String ) entry . getKey ( ) ; final Object test = entry . getValue ( ) ; final boolean matched = applyTest ( resource , predicateTransformer , key , test , listpred , sourceIdentity ) ; if ( ! matched ) { return false ; } } return true ; |
public class JavaSourceUtils { /** * 合并注解成员声明 */
public static AnnotationMemberDeclaration mergeAnnotationMember ( AnnotationMemberDeclaration one , AnnotationMemberDeclaration two ) { } } | if ( isAllNull ( one , two ) ) return null ; AnnotationMemberDeclaration amd = null ; if ( isAllNotNull ( one , two ) ) { amd = new AnnotationMemberDeclaration ( ) ; amd . setJavaDoc ( mergeSelective ( one . getJavaDoc ( ) , two . getJavaDoc ( ) ) ) ; amd . setComment ( mergeSelective ( one . getComment ( ) , two . getComment ( ) ) ) ; amd . setAnnotations ( mergeListNoDuplicate ( one . getAnnotations ( ) , two . getAnnotations ( ) ) ) ; amd . setModifiers ( mergeModifiers ( one . getModifiers ( ) , two . getModifiers ( ) ) ) ; amd . setName ( one . getName ( ) ) ; amd . setDefaultValue ( mergeSelective ( one . getDefaultValue ( ) , two . getDefaultValue ( ) ) ) ; amd . setType ( mergeSelective ( one . getType ( ) , two . getType ( ) ) ) ; LOG . info ( "merge AnnotationMemberDeclaration --> {}" , amd . getName ( ) ) ; } else { amd = findFirstNotNull ( one , two ) ; LOG . info ( "add AnnotationMemberDeclaration --> {}" , amd . getName ( ) ) ; } return amd ; |
public class GetTagsRequestMarshaller { /** * Marshall the given parameter object . */
public void marshall ( GetTagsRequest getTagsRequest , ProtocolMarshaller protocolMarshaller ) { } } | if ( getTagsRequest == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( getTagsRequest . getSearchString ( ) , SEARCHSTRING_BINDING ) ; protocolMarshaller . marshall ( getTagsRequest . getTimePeriod ( ) , TIMEPERIOD_BINDING ) ; protocolMarshaller . marshall ( getTagsRequest . getTagKey ( ) , TAGKEY_BINDING ) ; protocolMarshaller . marshall ( getTagsRequest . getNextPageToken ( ) , NEXTPAGETOKEN_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class Elapsed { /** * Initializes the object .
* @ param qty the amount
* @ param unit the time unit */
private void init ( final long qty , final TimeUnit unit ) { } } | long millis = unit . convert ( qty ) ; seconds = TimeUnit . MILLISECOND . convert ( millis , TimeUnit . SECOND ) % 60 ; minutes = TimeUnit . MILLISECOND . convert ( millis , TimeUnit . MINUTE ) % 60 ; hours = TimeUnit . MILLISECOND . convert ( millis , TimeUnit . HOUR ) % 24 ; days = TimeUnit . MILLISECOND . convert ( millis , TimeUnit . DAY ) ; |
public class StandardJdbcProcessor { public int executeUpdate ( String update ) throws SQLException { } } | System . out . println ( new LogEntry ( "executing: " + update ) ) ; // TODO time execution time
Connection conn = dataSource . getConnection ( ) ; Statement s = conn . createStatement ( ) ; int result = s . executeUpdate ( update ) ; conn . close ( ) ; System . out . println ( new LogEntry ( result + " rows affected" ) ) ; return result ; |
public class CmsListManager { /** * Saves the blacklist from the bean in the current list configuration . < p >
* @ param configBean the bean whose blacklist should be saved */
public void saveBlacklist ( ListConfigurationBean configBean ) { } } | if ( m_dialogWindow != null ) { m_dialogWindow . close ( ) ; m_dialogWindow = null ; } CmsObject cms = A_CmsUI . getCmsObject ( ) ; try { m_lockAction = CmsLockUtil . ensureLock ( cms , m_currentResource ) ; } catch ( CmsException e ) { CmsErrorDialog . showErrorDialog ( e ) ; return ; } try { CmsFile configFile = cms . readFile ( m_currentResource ) ; CmsXmlContent content = CmsXmlContentFactory . unmarshal ( cms , configFile ) ; // list configurations are single locale contents
Locale locale = CmsLocaleManager . MASTER_LOCALE ; int count = 0 ; while ( content . hasValue ( N_BLACKLIST , locale ) ) { content . removeValue ( N_BLACKLIST , locale , 0 ) ; } for ( CmsUUID hiddenId : configBean . getBlacklist ( ) ) { CmsXmlVfsFileValue contentVal ; contentVal = ( CmsXmlVfsFileValue ) content . addValue ( cms , N_BLACKLIST , locale , count ) ; contentVal . setIdValue ( cms , hiddenId ) ; count ++ ; } configFile . setContents ( content . marshal ( ) ) ; cms . writeFile ( configFile ) ; if ( m_lockAction . getChange ( ) . equals ( LockChange . locked ) ) { CmsLockUtil . tryUnlock ( cms , configFile ) ; } } catch ( CmsException e ) { e . printStackTrace ( ) ; } m_currentConfig = configBean ; |
public class FnDouble { /** * It returns the { @ link String } representation of the target as a currency in the
* default { @ link Locale }
* @ return the { @ link String } representation of the input as a currency */
public static final Function < Double , String > toCurrencyStr ( ) { } } | return ( Function < Double , String > ) ( ( Function ) FnNumber . toCurrencyStr ( ) ) ; |
public class DataLayout { /** * Removes a { @ link Data } so that it will no longer be observed by this layout . */
public final void removeData ( @ NonNull Data < ? > data ) { } } | checkNotNull ( data , "data" ) ; mDatas . remove ( data ) ; mDataWatcher . setDatas ( mDatas ) ; updateViews ( ) ; |
public class CmsLoginManager { /** * Checks whether a user account can be locked because of inactivity .
* @ param cms the CMS context
* @ param user the user to check
* @ return true if the user may be locked after being inactive for too long */
public boolean canLockBecauseOfInactivity ( CmsObject cms , CmsUser user ) { } } | return ! user . isManaged ( ) && ! user . isWebuser ( ) && ! OpenCms . getDefaultUsers ( ) . isDefaultUser ( user . getName ( ) ) && ! OpenCms . getRoleManager ( ) . hasRole ( cms , user . getName ( ) , CmsRole . ROOT_ADMIN ) ; |
public class CommerceAccountLocalServiceBaseImpl { /** * Sets the commerce account organization rel local service .
* @ param commerceAccountOrganizationRelLocalService the commerce account organization rel local service */
public void setCommerceAccountOrganizationRelLocalService ( com . liferay . commerce . account . service . CommerceAccountOrganizationRelLocalService commerceAccountOrganizationRelLocalService ) { } } | this . commerceAccountOrganizationRelLocalService = commerceAccountOrganizationRelLocalService ; |
public class CPTaxCategoryServiceBaseImpl { /** * Sets the cp definition link local service .
* @ param cpDefinitionLinkLocalService the cp definition link local service */
public void setCPDefinitionLinkLocalService ( com . liferay . commerce . product . service . CPDefinitionLinkLocalService cpDefinitionLinkLocalService ) { } } | this . cpDefinitionLinkLocalService = cpDefinitionLinkLocalService ; |
public class WindowSpecificationImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
public void setRES3 ( Integer newRES3 ) { } } | Integer oldRES3 = res3 ; res3 = newRES3 ; if ( eNotificationRequired ( ) ) eNotify ( new ENotificationImpl ( this , Notification . SET , AfplibPackage . WINDOW_SPECIFICATION__RES3 , oldRES3 , res3 ) ) ; |
public class PrintWriter { /** * Appends the specified character sequence to this writer .
* < p > An invocation of this method of the form < tt > out . append ( csq ) < / tt >
* behaves in exactly the same way as the invocation
* < pre >
* out . write ( csq . toString ( ) ) < / pre >
* < p > Depending on the specification of < tt > toString < / tt > for the
* character sequence < tt > csq < / tt > , the entire sequence may not be
* appended . For instance , invoking the < tt > toString < / tt > method of a
* character buffer will return a subsequence whose content depends upon
* the buffer ' s position and limit .
* @ param csq
* The character sequence to append . If < tt > csq < / tt > is
* < tt > null < / tt > , then the four characters < tt > " null " < / tt > are
* appended to this writer .
* @ return This writer
* @ since 1.5 */
public PrintWriter append ( CharSequence csq ) { } } | if ( csq == null ) write ( "null" ) ; else write ( csq . toString ( ) ) ; return this ; |
public class SimpleBlas { /** * Compute y < - x ( copy a matrix ) */
public static DoubleMatrix copy ( DoubleMatrix x , DoubleMatrix y ) { } } | // NativeBlas . dcopy ( x . length , x . data , 0 , 1 , y . data , 0 , 1 ) ;
JavaBlas . rcopy ( x . length , x . data , 0 , 1 , y . data , 0 , 1 ) ; return y ; |
public class AmazonAppStreamClient { /** * Associates the specified fleet with the specified stack .
* @ param associateFleetRequest
* @ return Result of the AssociateFleet operation returned by the service .
* @ throws LimitExceededException
* The requested limit exceeds the permitted limit for an account .
* @ throws InvalidAccountStatusException
* The resource cannot be created because your AWS account is suspended . For assistance , contact AWS
* Support .
* @ throws ResourceNotFoundException
* The specified resource was not found .
* @ throws ConcurrentModificationException
* An API error occurred . Wait a few minutes and try again .
* @ throws IncompatibleImageException
* The image does not support storage connectors .
* @ throws OperationNotPermittedException
* The attempted operation is not permitted .
* @ sample AmazonAppStream . AssociateFleet
* @ see < a href = " http : / / docs . aws . amazon . com / goto / WebAPI / appstream - 2016-12-01 / AssociateFleet " target = " _ top " > AWS API
* Documentation < / a > */
@ Override public AssociateFleetResult associateFleet ( AssociateFleetRequest request ) { } } | request = beforeClientExecution ( request ) ; return executeAssociateFleet ( request ) ; |
public class InstancedConfiguration { /** * Actual recursive lookup replacement .
* @ param base the string to resolve
* @ param seen strings already seen during this lookup , used to prevent unbound recursion
* @ return the resolved string */
private String lookupRecursively ( String base , Set < String > seen ) throws UnresolvablePropertyException { } } | // check argument
if ( base == null ) { throw new UnresolvablePropertyException ( "Can't resolve property with null value" ) ; } String resolved = base ; // Lets find pattern match to $ { key } .
// TODO ( hsaputra ) : Consider using Apache Commons StrSubstitutor .
Matcher matcher = CONF_REGEX . matcher ( base ) ; while ( matcher . find ( ) ) { String match = matcher . group ( 2 ) . trim ( ) ; if ( ! seen . add ( match ) ) { throw new RuntimeException ( ExceptionMessage . KEY_CIRCULAR_DEPENDENCY . getMessage ( match ) ) ; } if ( ! PropertyKey . isValid ( match ) ) { throw new RuntimeException ( ExceptionMessage . INVALID_CONFIGURATION_KEY . getMessage ( match ) ) ; } String value = lookupRecursively ( mProperties . get ( PropertyKey . fromString ( match ) ) , seen ) ; seen . remove ( match ) ; if ( value == null ) { throw new UnresolvablePropertyException ( ExceptionMessage . UNDEFINED_CONFIGURATION_KEY . getMessage ( match ) ) ; } LOG . debug ( "Replacing {} with {}" , matcher . group ( 1 ) , value ) ; resolved = resolved . replaceFirst ( REGEX_STRING , Matcher . quoteReplacement ( value ) ) ; } return resolved ; |
public class TransactionManager { /** * Start a short transaction with a given timeout .
* @ param timeoutInSeconds the time out period in seconds . */
public Transaction startShort ( int timeoutInSeconds ) { } } | Preconditions . checkArgument ( timeoutInSeconds > 0 , "timeout must be positive but is %s" , timeoutInSeconds ) ; txMetricsCollector . rate ( "start.short" ) ; Stopwatch timer = new Stopwatch ( ) . start ( ) ; long expiration = getTxExpiration ( timeoutInSeconds ) ; Transaction tx = startTx ( expiration , TransactionType . SHORT ) ; txMetricsCollector . histogram ( "start.short.latency" , ( int ) timer . elapsedMillis ( ) ) ; return tx ; |
public class SuffixDictionary { /** * 词语是否以该词典中的某个单词结尾
* @ param word
* @ return */
public boolean endsWith ( String word ) { } } | word = reverse ( word ) ; return trie . commonPrefixSearchWithValue ( word ) . size ( ) > 0 ; |
public class Kernel2D_S32 { /** * Creates a kernel whose elements are the specified data array and has
* the specified width .
* @ param data The array who will be the kernel ' s data . Reference is saved .
* @ param width The kernel ' s width .
* @ param offset Kernel origin ' s offset from element 0.
* @ return A new kernel . */
public static Kernel2D_S32 wrap ( int data [ ] , int width , int offset ) { } } | if ( width % 2 == 0 && width <= 0 && width * width > data . length ) throw new IllegalArgumentException ( "invalid width" ) ; Kernel2D_S32 ret = new Kernel2D_S32 ( ) ; ret . data = data ; ret . width = width ; ret . offset = offset ; return ret ; |
public class AttributeDefinition { /** * Based on the given attribute value , add capability requirements . If this definition
* is for an attribute whose value is or contains a reference to the name of some capability ,
* this method should record the addition of a requirement for the capability .
* This is a no - op in this base class . Subclasses that support attribute types that can represent
* capability references should override this method .
* @ param context the operation context
* @ param attributeValue the value of the attribute described by this object
* @ deprecated use @ { link { @ link # addCapabilityRequirements ( OperationContext , Resource , ModelNode ) } } variant */
@ Deprecated public void addCapabilityRequirements ( OperationContext context , ModelNode attributeValue ) { } } | addCapabilityRequirements ( context , null , attributeValue ) ; |
public class SoyJsPluginUtils { /** * Applies the given print directive to { @ code expr } and returns the result .
* @ param generator The CodeChunk generator to use .
* @ param expr The expression to apply the print directive to .
* @ param directive The print directive to apply .
* @ param args Print directive args , if any . */
public static Expression applyDirective ( Expression expr , SoyJsSrcPrintDirective directive , List < Expression > args , SourceLocation location , ErrorReporter errorReporter ) { } } | List < JsExpr > argExprs = Lists . transform ( args , Expression :: singleExprOrName ) ; JsExpr applied ; try { applied = directive . applyForJsSrc ( expr . singleExprOrName ( ) , argExprs ) ; } catch ( Throwable t ) { applied = report ( location , directive , t , errorReporter ) ; } RequiresCollector . IntoImmutableSet collector = new RequiresCollector . IntoImmutableSet ( ) ; expr . collectRequires ( collector ) ; for ( Expression arg : args ) { arg . collectRequires ( collector ) ; } if ( directive instanceof SoyLibraryAssistedJsSrcPrintDirective ) { for ( String name : ( ( SoyLibraryAssistedJsSrcPrintDirective ) directive ) . getRequiredJsLibNames ( ) ) { collector . add ( GoogRequire . create ( name ) ) ; } } ImmutableList . Builder < Statement > initialStatements = ImmutableList . < Statement > builder ( ) . addAll ( expr . initialStatements ( ) ) ; for ( Expression arg : args ) { initialStatements . addAll ( arg . initialStatements ( ) ) ; } return fromExpr ( applied , collector . get ( ) ) . withInitialStatements ( initialStatements . build ( ) ) ; |
public class MathExpressions { /** * Round to nearest integer
* @ param num numeric expression
* @ return round ( this ) */
public static < A extends Number & Comparable < ? > > NumberExpression < A > round ( Expression < A > num ) { } } | return Expressions . numberOperation ( num . getType ( ) , MathOps . ROUND , num ) ; |
public class ArrayContainer { /** * for use in inot range known to be nonempty */
private void negateRange ( final short [ ] buffer , final int startIndex , final int lastIndex , final int startRange , final int lastRange ) { } } | // compute the negation into buffer
int outPos = 0 ; int inPos = startIndex ; // value here always > = valInRange ,
// until it is exhausted
// n . b . , we can start initially exhausted .
int valInRange = startRange ; for ( ; valInRange < lastRange && inPos <= lastIndex ; ++ valInRange ) { if ( ( short ) valInRange != content [ inPos ] ) { buffer [ outPos ++ ] = ( short ) valInRange ; } else { ++ inPos ; } } // if there are extra items ( greater than the biggest
// pre - existing one in range ) , buffer them
for ( ; valInRange < lastRange ; ++ valInRange ) { buffer [ outPos ++ ] = ( short ) valInRange ; } if ( outPos != buffer . length ) { throw new RuntimeException ( "negateRange: outPos " + outPos + " whereas buffer.length=" + buffer . length ) ; } // copy back from buffer . . . caller must ensure there is room
int i = startIndex ; for ( short item : buffer ) { content [ i ++ ] = item ; } |
public class UtilCache { /** * Clears all expired cache entries ; also clear any cache entries where the
* SoftReference in the CacheLine object has been cleared by the gc */
public void clearExpired ( ) { } } | Iterator keys = cacheLineTable . keySet ( ) . iterator ( ) ; while ( keys . hasNext ( ) ) { Object key = keys . next ( ) ; if ( hasExpired ( key ) ) { removeObject ( key ) ; } } |
public class Metadata { /** * < p > Finds all parameters on the request definition which are annotated with the given type and returns
* the annotation instance together with the runtime argument . < / p >
* @ param type
* the { @ link Class } of the annotation to look for on the request parameters
* < br > < br >
* @ param context
* the { @ link InvocationContext } containing the request definition to extract the metadata from
* < br > < br >
* @ return an < b > unmodifiable < / b > { @ link List } of { @ link Map . Entry } instances with the annotation as
* the and the runtime argument as the < i > value < / i > ; < b > note < / b > that the implementation of
* { @ link Map . Entry # setValue ( Object ) } throws an { @ link UnsupportedOperationException }
* < br > < br >
* @ since 1.3.0 */
public static < T extends Annotation > List < Entry < T , Object > > onParams ( final Class < T > type , InvocationContext context ) { } } | assertNotNull ( type ) ; assertNotNull ( context ) ; List < Entry < T , Object > > metadata = new ArrayList < Entry < T , Object > > ( ) ; Method request = context . getRequest ( ) ; List < Object > paramValues = context . getArguments ( ) ; Annotation [ ] [ ] annotationsForAllParams = request . getParameterAnnotations ( ) ; for ( int i = 0 ; i < annotationsForAllParams . length ; i ++ ) { final Object value = paramValues . get ( i ) ; if ( value == null ) { continue ; } for ( final Annotation annotation : annotationsForAllParams [ i ] ) { if ( type . isAssignableFrom ( annotation . getClass ( ) ) ) { metadata . add ( new Map . Entry < T , Object > ( ) { @ Override public T getKey ( ) { return type . cast ( annotation ) ; } @ Override public Object getValue ( ) { return value ; } @ Override public Object setValue ( Object value ) { throw new UnsupportedOperationException ( ) ; } } ) ; break ; } } } return Collections . unmodifiableList ( metadata ) ; |
public class PolicyFactoryImpl { /** * Loads a policy from a class on the classpath .
* @ param policyImpl
* @ param handler */
protected void doLoadFromClasspath ( String policyImpl , IAsyncResultHandler < IPolicy > handler ) { } } | IPolicy rval ; String classname = policyImpl . substring ( 6 ) ; Class < ? > c = null ; // First try a simple Class . forName ( )
try { c = Class . forName ( classname ) ; } catch ( ClassNotFoundException e ) { } // Didn ' t work ? Try using this class ' s classloader .
if ( c == null ) { try { c = getClass ( ) . getClassLoader ( ) . loadClass ( classname ) ; } catch ( ClassNotFoundException e ) { } } // Still didn ' t work ? Try the thread ' s context classloader .
if ( c == null ) { try { c = Thread . currentThread ( ) . getContextClassLoader ( ) . loadClass ( classname ) ; } catch ( ClassNotFoundException e ) { } } if ( c == null ) { handler . handle ( AsyncResultImpl . < IPolicy > create ( new PolicyNotFoundException ( classname ) ) ) ; return ; } try { rval = ( IPolicy ) c . newInstance ( ) ; } catch ( InstantiationException | IllegalAccessException e ) { handler . handle ( AsyncResultImpl . < IPolicy > create ( new PolicyNotFoundException ( policyImpl , e ) ) ) ; return ; } policyCache . put ( policyImpl , rval ) ; handler . handle ( AsyncResultImpl . create ( rval ) ) ; return ; |
public class DefaultSchemaManager { /** * Update the managedSchemaMap for the entry defined by tableName and
* entityName .
* @ param tableName
* The table name of the managed schema
* @ param entityName
* The entity name of the managed schema */
@ Override public void refreshManagedSchemaCache ( String tableName , String entityName ) { } } | ManagedSchema managedSchema = managedSchemaDao . getManagedSchema ( tableName , entityName ) ; if ( managedSchema != null ) { getManagedSchemaMap ( ) . put ( getManagedSchemaMapKey ( managedSchema . getTable ( ) , managedSchema . getName ( ) ) , managedSchema ) ; } |
public class ReflectUtils { /** * Sets the specified field value while wrapping checked exception in a { @ link ShedException } .
* @ param field the field .
* @ param self the instance to get the value from .
* @ param < T > the type of the field value .
* @ return the field value . */
@ SuppressWarnings ( "unchecked" ) public static < T > T getValue ( Field field , Object self ) { } } | try { return ( T ) field . get ( self ) ; } catch ( IllegalAccessException e ) { throw ShedException . wrap ( e , ShedErrorCode . UNABLE_TO_GET_FIELD ) . put ( "field" , field . toGenericString ( ) ) ; } |
public class SourceReaderModule { /** * Get pipe line filters
* @ param fileToParse absolute URI to current file being processed */
List < XMLFilter > getProcessingPipe ( final URI fileToParse ) { } } | final List < XMLFilter > pipe = new ArrayList < > ( ) ; for ( XmlFilterModule . FilterPair pair : filters ) { final AbstractXMLFilter filter = pair . filter ; filter . setLogger ( logger ) ; filter . setJob ( job ) ; filter . setCurrentFile ( fileToParse ) ; pipe . add ( filter ) ; } return pipe ; |
public class SetOperation { /** * Used by intersection and AnotB */
static final int computeMinLgArrLongsFromCount ( final int count ) { } } | final int upperCount = ( int ) Math . ceil ( count / REBUILD_THRESHOLD ) ; final int arrLongs = max ( ceilingPowerOf2 ( upperCount ) , 1 << MIN_LG_ARR_LONGS ) ; final int newLgArrLongs = Integer . numberOfTrailingZeros ( arrLongs ) ; return newLgArrLongs ; |
public class BaseSparseNDArrayCSR { /** * Returns a subset of this array based on the specified
* indexes
* @ param indexes the indexes in to the array
* @ return a view of the array with the specified indices */
@ Override public INDArray get ( INDArrayIndex ... indexes ) { } } | // check for row / column vector and point index being 0
if ( indexes . length == 1 && indexes [ 0 ] instanceof NDArrayIndexAll || ( indexes . length == 2 && ( isRowVector ( ) && indexes [ 0 ] instanceof PointIndex && indexes [ 0 ] . offset ( ) == 0 && indexes [ 1 ] instanceof NDArrayIndexAll || isColumnVector ( ) && indexes [ 1 ] instanceof PointIndex && indexes [ 0 ] . offset ( ) == 0 && indexes [ 0 ] instanceof NDArrayIndexAll ) ) ) return this ; indexes = NDArrayIndex . resolve ( javaShapeInformation , indexes ) ; throw new UnsupportedOperationException ( "Not implemeted" ) ; |
public class ApiClient { /** * Add network interceptor to httpClient to track download progress for
* async requests . */
private void addProgressInterceptor ( ) { } } | httpClient . networkInterceptors ( ) . add ( new Interceptor ( ) { @ Override public Response intercept ( Interceptor . Chain chain ) throws IOException { final Request request = chain . request ( ) ; final Response originalResponse = chain . proceed ( request ) ; if ( request . tag ( ) instanceof ApiCallback ) { final ApiCallback callback = ( ApiCallback ) request . tag ( ) ; return originalResponse . newBuilder ( ) . body ( new ProgressResponseBody ( originalResponse . body ( ) , callback ) ) . build ( ) ; } return originalResponse ; } } ) ; |
public class InstanceValidator { /** * the instance validator had no issues against the base resource profile */
private void start ( List < ValidationMessage > errors , WrapperElement resource , WrapperElement element , StructureDefinition profile , NodeStack stack ) throws FHIRException { } } | // profile is valid , and matches the resource name
if ( rule ( errors , IssueType . STRUCTURE , element . line ( ) , element . col ( ) , stack . getLiteralPath ( ) , profile . hasSnapshot ( ) , "StructureDefinition has no snapshot - validation is against the snapshot, so it must be provided" ) ) { validateElement ( errors , profile , profile . getSnapshot ( ) . getElement ( ) . get ( 0 ) , null , null , resource , element , element . getName ( ) , stack , false ) ; checkDeclaredProfiles ( errors , resource , element , stack ) ; // specific known special validations
if ( element . getResourceType ( ) . equals ( "Bundle" ) ) validateBundle ( errors , element , stack ) ; if ( element . getResourceType ( ) . equals ( "Observation" ) ) validateObservation ( errors , element , stack ) ; } |
public class Murmur3F { /** * Special update method to hash long values very efficiently using Java ' s native little endian ( LE ) byte order .
* Note , that you cannot mix this with other ( previous ) hash updates , because it only supports 8 - bytes alignment . */
public void updateLongLE ( long value ) { } } | finished = false ; switch ( partialPos ) { case 0 : partialK1 = value ; break ; case 8 : partialK2 = value ; break ; default : throw new IllegalStateException ( "Cannot mix long with other alignments than 8: " + partialPos ) ; } partialPos += 8 ; if ( partialPos == 16 ) { applyKs ( partialK1 , partialK2 ) ; partialPos = 0 ; } length += 8 ; |
public class ListIndexRequest { /** * Specifies the ranges of indexed values that you want to query .
* < b > NOTE : < / b > This method appends the values to the existing list ( if any ) . Use
* { @ link # setRangesOnIndexedValues ( java . util . Collection ) } or
* { @ link # withRangesOnIndexedValues ( java . util . Collection ) } if you want to override the existing values .
* @ param rangesOnIndexedValues
* Specifies the ranges of indexed values that you want to query .
* @ return Returns a reference to this object so that method calls can be chained together . */
public ListIndexRequest withRangesOnIndexedValues ( ObjectAttributeRange ... rangesOnIndexedValues ) { } } | if ( this . rangesOnIndexedValues == null ) { setRangesOnIndexedValues ( new java . util . ArrayList < ObjectAttributeRange > ( rangesOnIndexedValues . length ) ) ; } for ( ObjectAttributeRange ele : rangesOnIndexedValues ) { this . rangesOnIndexedValues . add ( ele ) ; } return this ; |
public class SynchronousQueue { /** * Reconstitutes this queue from a stream ( that is , deserializes it ) .
* @ param s the stream
* @ throws ClassNotFoundException if the class of a serialized object
* could not be found
* @ throws java . io . IOException if an I / O error occurs */
private void readObject ( java . io . ObjectInputStream s ) throws java . io . IOException , ClassNotFoundException { } } | s . defaultReadObject ( ) ; if ( waitingProducers instanceof FifoWaitQueue ) transferer = new TransferQueue < E > ( ) ; else transferer = new TransferStack < E > ( ) ; |
public class NetworkWatchersInner { /** * Get network configuration diagnostic .
* @ param resourceGroupName The name of the resource group .
* @ param networkWatcherName The name of the network watcher .
* @ param parameters Parameters to get network configuration diagnostic .
* @ 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 < NetworkConfigurationDiagnosticResponseInner > beginGetNetworkConfigurationDiagnosticAsync ( String resourceGroupName , String networkWatcherName , NetworkConfigurationDiagnosticParameters parameters , final ServiceCallback < NetworkConfigurationDiagnosticResponseInner > serviceCallback ) { } } | return ServiceFuture . fromResponse ( beginGetNetworkConfigurationDiagnosticWithServiceResponseAsync ( resourceGroupName , networkWatcherName , parameters ) , serviceCallback ) ; |
public class LssParser { /** * Adds the stored attribute values to the style sheet . Resolves inherited styles . */
protected void processAttributes ( ) { } } | for ( final String tag : tags ) { for ( final String inherit : inherits ) { styleSheet . addStyles ( tag , styleSheet . getStyles ( inherit ) ) ; } styleSheet . addStyles ( tag , attributes ) ; } |
public class FTPClient { /** * Sets restart parameter of the next transfer .
* @ param restartData marker to use
* @ exception ServerException if the file does not exist or
* an error occured . */
public void setRestartMarker ( RestartData restartData ) throws IOException , ServerException { } } | Command cmd = new Command ( "REST" , restartData . toFtpCmdArgument ( ) ) ; Reply reply = null ; try { reply = controlChannel . exchange ( cmd ) ; } catch ( FTPReplyParseException e ) { throw ServerException . embedFTPReplyParseException ( e ) ; } if ( ! Reply . isPositiveIntermediate ( reply ) ) { throw ServerException . embedUnexpectedReplyCodeException ( new UnexpectedReplyCodeException ( reply ) ) ; } |
public class Schema { /** * Adds a new { @ link Analyzer } .
* @ param name the name of the { @ link Analyzer } to be added
* @ param analyzer the { @ link Analyzer } to be added
* @ return this with the specified analyzer */
public Schema analyzer ( String name , Analyzer analyzer ) { } } | if ( analyzers == null ) { analyzers = new LinkedHashMap < > ( ) ; } analyzers . put ( name , analyzer ) ; return this ; |
public class AuthenticateUserHelper { /** * Authenticate the given user and return an authenticated Subject .
* @ param authenticationService service to authenticate a user , must not be null
* @ param userName the user to authenticate , must not be null
* @ param jaasEntryName the optional JAAS configuration entry name . The system . DEFAULT JAAS entry name will be used if null or empty String is passed
* @ return the authenticated subject
* @ throws AuthenticationException if there was a problem authenticating the user , or if the userName or authenticationService is null */
public Subject authenticateUser ( AuthenticationService authenticationService , String userName , String jaasEntryName ) throws AuthenticationException { } } | return authenticateUser ( authenticationService , userName , jaasEntryName , null ) ; |
public class ManifestLoader { /** * This method adds dynamic attributes to the given { @ code manifest } .
* @ param manifest is the { @ link Manifest } to modify .
* @ param url is the { @ link URL } with the source of the manifest . */
private static void completeManifest ( Manifest manifest , URL url ) { } } | String path = url . getPath ( ) ; int start = 0 ; int end = path . length ( ) ; if ( path . endsWith ( JAR_SUFFIX ) ) { // 4 for " . jar "
end = end - JAR_SUFFIX . length ( ) + 4 ; start = path . lastIndexOf ( '/' , end ) + 1 ; } String source = path . substring ( start , end ) ; manifest . getMainAttributes ( ) . put ( MANIFEST_SOURCE , source ) ; |
public class PrivateDataManager { /** * Adds a private data provider with the specified element name and name space . The provider
* will override any providers loaded through the classpath .
* @ param elementName the XML element name .
* @ param namespace the XML namespace .
* @ param provider the private data provider . */
public static void addPrivateDataProvider ( String elementName , String namespace , PrivateDataProvider provider ) { } } | String key = XmppStringUtils . generateKey ( elementName , namespace ) ; privateDataProviders . put ( key , provider ) ; |
public class IterationSynchronizationSinkTask { @ Override public void invoke ( ) throws Exception { } } | this . headEventReader = new MutableRecordReader < > ( getEnvironment ( ) . getInputGate ( 0 ) , getEnvironment ( ) . getTaskManagerInfo ( ) . getTmpDirectories ( ) ) ; TaskConfig taskConfig = new TaskConfig ( getTaskConfiguration ( ) ) ; // store all aggregators
this . aggregators = new HashMap < > ( ) ; for ( AggregatorWithName < ? > aggWithName : taskConfig . getIterationAggregators ( getUserCodeClassLoader ( ) ) ) { aggregators . put ( aggWithName . getName ( ) , aggWithName . getAggregator ( ) ) ; } // store the aggregator convergence criterion
if ( taskConfig . usesConvergenceCriterion ( ) ) { convergenceCriterion = taskConfig . getConvergenceCriterion ( getUserCodeClassLoader ( ) ) ; convergenceAggregatorName = taskConfig . getConvergenceCriterionAggregatorName ( ) ; Preconditions . checkNotNull ( convergenceAggregatorName ) ; } // store the default aggregator convergence criterion
if ( taskConfig . usesImplicitConvergenceCriterion ( ) ) { implicitConvergenceCriterion = taskConfig . getImplicitConvergenceCriterion ( getUserCodeClassLoader ( ) ) ; implicitConvergenceAggregatorName = taskConfig . getImplicitConvergenceCriterionAggregatorName ( ) ; Preconditions . checkNotNull ( implicitConvergenceAggregatorName ) ; } maxNumberOfIterations = taskConfig . getNumberOfIterations ( ) ; // set up the event handler
int numEventsTillEndOfSuperstep = taskConfig . getNumberOfEventsUntilInterruptInIterativeGate ( 0 ) ; eventHandler = new SyncEventHandler ( numEventsTillEndOfSuperstep , aggregators , getEnvironment ( ) . getUserClassLoader ( ) ) ; headEventReader . registerTaskEventListener ( eventHandler , WorkerDoneEvent . class ) ; IntValue dummy = new IntValue ( ) ; while ( ! terminationRequested ( ) ) { if ( log . isInfoEnabled ( ) ) { log . info ( formatLogString ( "starting iteration [" + currentIteration + "]" ) ) ; } // this call listens for events until the end - of - superstep is reached
readHeadEventChannel ( dummy ) ; if ( log . isInfoEnabled ( ) ) { log . info ( formatLogString ( "finishing iteration [" + currentIteration + "]" ) ) ; } if ( checkForConvergence ( ) ) { if ( log . isInfoEnabled ( ) ) { log . info ( formatLogString ( "signaling that all workers are to terminate in iteration [" + currentIteration + "]" ) ) ; } requestTermination ( ) ; sendToAllWorkers ( new TerminationEvent ( ) ) ; } else { if ( log . isInfoEnabled ( ) ) { log . info ( formatLogString ( "signaling that all workers are done in iteration [" + currentIteration + "]" ) ) ; } AllWorkersDoneEvent allWorkersDoneEvent = new AllWorkersDoneEvent ( aggregators ) ; sendToAllWorkers ( allWorkersDoneEvent ) ; // reset all aggregators
for ( Aggregator < ? > agg : aggregators . values ( ) ) { agg . reset ( ) ; } currentIteration ++ ; } } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.