signature stringlengths 43 39.1k | implementation stringlengths 0 450k |
|---|---|
public class sslvserver { /** * Use this API to unset the properties of sslvserver resource .
* Properties that need to be unset are specified in args array . */
public static base_response unset ( nitro_service client , sslvserver resource , String [ ] args ) throws Exception { } } | sslvserver unsetresource = new sslvserver ( ) ; unsetresource . vservername = resource . vservername ; return unsetresource . unset_resource ( client , args ) ; |
public class Parser { /** * A { @ link Parser } that first runs { @ code before } from the input start ,
* then runs { @ code after } from the input ' s end , and only
* then runs { @ code this } on what ' s left from the input .
* In effect , { @ code this } behaves reluctantly , giving
* { @ code after } a chance to grab input that would have been consumed by { @ code this }
* otherwise .
* @ deprecated This method probably only works in the simplest cases . And it ' s a character - level
* parser only . Use it at your own risk . It may be deleted later when we find a better way . */
@ Deprecated public final Parser < T > reluctantBetween ( Parser < ? > before , Parser < ? > after ) { } } | return new ReluctantBetweenParser < T > ( before , this , after ) ; |
public class SelectPictureActivity { /** * Method which will process the captured image */
@ Override public void onActivityResult ( int requestCode , int resultCode , Intent data ) { } } | super . onActivityResult ( requestCode , resultCode , data ) ; // verify if the image was gotten successfully
if ( requestCode == REQUEST_TAKE_CAMERA_PHOTO && resultCode == Activity . RESULT_OK ) { new ImageCompressionAsyncTask ( this ) . execute ( mCurrentPhotoPath , Environment . getExternalStoragePublicDirectory ( Environment . DIRECTORY_PICTURES ) + "/Silicompressor/images" ) ; } else if ( requestCode == REQUEST_TAKE_VIDEO && resultCode == RESULT_OK ) { if ( data . getData ( ) != null ) { // create destination directory
File f = new File ( Environment . getExternalStoragePublicDirectory ( Environment . DIRECTORY_MOVIES ) + "/Silicompressor/videos" ) ; if ( f . mkdirs ( ) || f . isDirectory ( ) ) // compress and output new video specs
new VideoCompressAsyncTask ( this ) . execute ( mCurrentPhotoPath , f . getPath ( ) ) ; } } |
public class FieldMarshaller { /** * Returns true if we should use the generated field marshaller methods that allow us to work
* around our inability to read and write protected and private fields of a { @ link Streamable } . */
protected static boolean useFieldAccessors ( ) { } } | try { SecurityManager security = System . getSecurityManager ( ) ; if ( security != null ) { security . checkPermission ( new ReflectPermission ( "suppressAccessChecks" ) ) ; } return false ; } catch ( SecurityException se ) { return true ; } |
public class AnnotationInfo { /** * アノテーションの属性名を指定して 、 アノテーションの値を取得する 。
* @ param name 属性名 。
* @ return 存在しない属性名の場合 、 nullを返します 。 */
public String getAttribute ( final String name ) { } } | for ( AttributeInfo item : attributes ) { if ( item . name . equals ( name ) ) { return item . value ; } } return null ; |
public class TargetSpecifications { /** * { @ link Specification } for retrieving { @ link Target } s by " like attribute
* value " .
* @ param searchText
* to be filtered on
* @ return the { @ link Target } { @ link Specification } */
public static Specification < JpaTarget > likeAttributeValue ( final String searchText ) { } } | return ( targetRoot , query , cb ) -> { final String searchTextToLower = searchText . toLowerCase ( ) ; final MapJoin < JpaTarget , String , String > attributeMap = targetRoot . join ( JpaTarget_ . controllerAttributes , JoinType . LEFT ) ; query . distinct ( true ) ; return cb . like ( cb . lower ( attributeMap . value ( ) ) , searchTextToLower ) ; } ; |
public class TransformationDescription { /** * Adds a split regex transformation step to the transformation description . The value of the source field is split
* based on the split string as regular expression into parts . Based on the given index , the result will be set to
* the target field . The index needs to be an integer value . All fields need to be of the type String . */
public void splitRegexField ( String sourceField , String targetField , String regexString , String index ) { } } | TransformationStep step = new TransformationStep ( ) ; step . setTargetField ( targetField ) ; step . setSourceFields ( sourceField ) ; step . setOperationParameter ( TransformationConstants . REGEX_PARAM , regexString ) ; step . setOperationParameter ( TransformationConstants . INDEX_PARAM , index ) ; step . setOperationName ( "splitRegex" ) ; steps . add ( step ) ; |
public class NodeEntryImpl { /** * Extract the port string from a string in the pattern " hostname : port "
* @ param host the hostname
* @ return the extracted port string , or null if the pattern is not matched . */
public static String extractPort ( final String host ) { } } | if ( containsPort ( host ) ) { return host . substring ( host . indexOf ( ":" ) + 1 , host . length ( ) ) ; } else { return null ; } |
public class LimitedInputStream { /** * / * ( non - Javadoc )
* @ see java . io . InputStream # read ( byte [ ] , int , int ) */
@ Override public int read ( byte [ ] b , int off , int len ) throws IOException { } } | int bytes = inner . read ( b , off , Math . min ( len , remaining ) ) ; if ( bytes > 0 ) { remaining -= bytes ; } return bytes ; |
public class DiagnosticsInner { /** * Get Detectors .
* Get Detectors .
* @ param nextPageLink The NextLink from the previous successful call to List operation .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ throws DefaultErrorResponseException thrown if the request is rejected by server
* @ throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @ return the PagedList & lt ; DetectorDefinitionInner & gt ; object if successful . */
public PagedList < DetectorDefinitionInner > listSiteDetectorsSlotNext ( final String nextPageLink ) { } } | ServiceResponse < Page < DetectorDefinitionInner > > response = listSiteDetectorsSlotNextSinglePageAsync ( nextPageLink ) . toBlocking ( ) . single ( ) ; return new PagedList < DetectorDefinitionInner > ( response . body ( ) ) { @ Override public Page < DetectorDefinitionInner > nextPage ( String nextPageLink ) { return listSiteDetectorsSlotNextSinglePageAsync ( nextPageLink ) . toBlocking ( ) . single ( ) . body ( ) ; } } ; |
public class InternalTransaction { /** * Create the extrnal transaction for use by the public interface
* from this InternalTransaction .
* To detect orphaned Transactions , ie . Transactions not referenced elsewhere in the JVM ,
* we will keep a reference to the internalTransaction and make a weak reference to the
* container we pass to the application . When the container Transaction appears on the
* orphanTransactionsQueue we know the calling application has lost all references to it .
* At this point we can attempt to reuse it .
* @ return transaction the new transaction . */
protected synchronized final Transaction getExternalTransaction ( ) { } } | final String methodName = "getExternalTransaction" ; if ( Tracing . isAnyTracingEnabled ( ) && trace . isEntryEnabled ( ) ) trace . entry ( this , cclass , methodName ) ; Transaction transaction = null ; // For return .
if ( transactionReference != null ) transaction = ( Transaction ) transactionReference . get ( ) ; if ( transaction == null ) { transaction = new Transaction ( this ) ; // Make a WeakReference that becomes Enqueued as a result of the external Transaction becoming unreferenced .
transactionReference = new TransactionReference ( this , transaction ) ; } // if ( transaction = = null ) .
if ( Tracing . isAnyTracingEnabled ( ) && trace . isEntryEnabled ( ) ) trace . exit ( this , cclass , methodName , new Object [ ] { transaction } ) ; return transaction ; |
public class RevisionDecoder { /** * Decodes a Paste operation .
* @ param blockSize _ S
* length of a S block
* @ param blockSize _ B
* length of a B block
* @ return DiffPart , Paste operation
* @ throws DecodingException
* if the decoding failed */
private DiffPart decodePaste ( final int blockSize_S , final int blockSize_B , final BitReader r ) throws DecodingException { } } | if ( blockSize_S < 1 || blockSize_B < 1 ) { throw new DecodingException ( "Invalid value for blockSize_S: " + blockSize_S + " or blockSize_B: " + blockSize_B ) ; } int s = r . read ( blockSize_S ) ; int b = r . read ( blockSize_B ) ; DiffPart part = new DiffPart ( DiffAction . PASTE ) ; part . setStart ( s ) ; part . setText ( Integer . toString ( b ) ) ; r . skip ( ) ; return part ; |
public class Association { /** * Method to initialize the Cache of this CacheObjectInterface . */
public static void initialize ( ) { } } | if ( InfinispanCache . get ( ) . exists ( Association . IDCACHE ) ) { InfinispanCache . get ( ) . < Long , Association > getCache ( Association . IDCACHE ) . clear ( ) ; } else { InfinispanCache . get ( ) . < Long , Association > getCache ( Association . IDCACHE ) . addListener ( new CacheLogListener ( Association . LOG ) ) ; } |
public class Parent { /** * Gets the parentType value for this Parent .
* @ return parentType * < span class = " constraint ReadOnly " > This field is read only and
* will be ignored when sent to the API . < / span > */
public com . google . api . ads . adwords . axis . v201809 . cm . ParentParentType getParentType ( ) { } } | return parentType ; |
public class DescribeLayersRequestMarshaller { /** * Marshall the given parameter object . */
public void marshall ( DescribeLayersRequest describeLayersRequest , ProtocolMarshaller protocolMarshaller ) { } } | if ( describeLayersRequest == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( describeLayersRequest . getStackId ( ) , STACKID_BINDING ) ; protocolMarshaller . marshall ( describeLayersRequest . getLayerIds ( ) , LAYERIDS_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class Matrix { /** * Returns whether the matrix is the same as this matrix .
* @ param B
* @ return */
public boolean eq ( final Matrix B ) { } } | final Matrix A = this ; if ( ( B . m_rows != A . m_rows ) || ( B . m_columns != A . m_columns ) ) { return false ; } for ( int i = 0 ; i < m_rows ; i ++ ) { for ( int j = 0 ; j < m_columns ; j ++ ) { if ( A . m_data [ i ] [ j ] != B . m_data [ i ] [ j ] ) { return false ; } } } return true ; |
public class AbstractInconsistencyRepair { /** * Rollback data . */
protected void rollback ( WorkspaceStorageConnection conn ) { } } | try { if ( conn != null ) { conn . rollback ( ) ; } } catch ( IllegalStateException e ) { LOG . error ( "Can not rollback connection" , e ) ; } catch ( RepositoryException e ) { LOG . error ( "Can not rollback connection" , e ) ; } |
public class DenseDoubleMatrix { /** * Sets the row to a given double array . */
public void setRow ( int row , double [ ] value ) { } } | for ( int i = 0 ; i < value . length ; i ++ ) { this . matrix [ translate ( row , i , numRows ) ] = value [ i ] ; } |
public class TimerUtil { /** * The event definition on which the timer is based .
* Takes in an optional execution , if missing the { @ link NoExecutionVariableScope } will be used ( eg Timer start event ) */
public static TimerJobEntity createTimerEntityForTimerEventDefinition ( TimerEventDefinition timerEventDefinition , boolean isInterruptingTimer , ExecutionEntity executionEntity , String jobHandlerType , String jobHandlerConfig ) { } } | ProcessEngineConfigurationImpl processEngineConfiguration = Context . getProcessEngineConfiguration ( ) ; String businessCalendarRef = null ; Expression expression = null ; ExpressionManager expressionManager = processEngineConfiguration . getExpressionManager ( ) ; // ACT - 1415 : timer - declaration on start - event may contain expressions NOT
// evaluating variables but other context , evaluating should happen nevertheless
VariableScope scopeForExpression = executionEntity ; if ( scopeForExpression == null ) { scopeForExpression = NoExecutionVariableScope . getSharedInstance ( ) ; } if ( StringUtils . isNotEmpty ( timerEventDefinition . getTimeDate ( ) ) ) { businessCalendarRef = DueDateBusinessCalendar . NAME ; expression = expressionManager . createExpression ( timerEventDefinition . getTimeDate ( ) ) ; } else if ( StringUtils . isNotEmpty ( timerEventDefinition . getTimeCycle ( ) ) ) { businessCalendarRef = CycleBusinessCalendar . NAME ; expression = expressionManager . createExpression ( timerEventDefinition . getTimeCycle ( ) ) ; } else if ( StringUtils . isNotEmpty ( timerEventDefinition . getTimeDuration ( ) ) ) { businessCalendarRef = DurationBusinessCalendar . NAME ; expression = expressionManager . createExpression ( timerEventDefinition . getTimeDuration ( ) ) ; } if ( StringUtils . isNotEmpty ( timerEventDefinition . getCalendarName ( ) ) ) { businessCalendarRef = timerEventDefinition . getCalendarName ( ) ; Expression businessCalendarExpression = expressionManager . createExpression ( businessCalendarRef ) ; businessCalendarRef = businessCalendarExpression . getValue ( scopeForExpression ) . toString ( ) ; } if ( expression == null ) { throw new ActivitiException ( "Timer needs configuration (either timeDate, timeCycle or timeDuration is needed) (" + timerEventDefinition . getId ( ) + ")" ) ; } BusinessCalendar businessCalendar = processEngineConfiguration . getBusinessCalendarManager ( ) . getBusinessCalendar ( businessCalendarRef ) ; String dueDateString = null ; Date duedate = null ; Object dueDateValue = expression . getValue ( scopeForExpression ) ; if ( dueDateValue instanceof String ) { dueDateString = ( String ) dueDateValue ; } else if ( dueDateValue instanceof Date ) { duedate = ( Date ) dueDateValue ; } else if ( dueDateValue instanceof DateTime ) { // JodaTime support
duedate = ( ( DateTime ) dueDateValue ) . toDate ( ) ; } else if ( dueDateValue != null ) { throw new ActivitiException ( "Timer '" + executionEntity . getActivityId ( ) + "' was not configured with a valid duration/time, either hand in a java.util.Date or a String in format 'yyyy-MM-dd'T'hh:mm:ss'" ) ; } if ( duedate == null && dueDateString != null ) { duedate = businessCalendar . resolveDuedate ( dueDateString ) ; } TimerJobEntity timer = null ; if ( duedate != null ) { timer = Context . getCommandContext ( ) . getTimerJobEntityManager ( ) . create ( ) ; timer . setJobType ( JobEntity . JOB_TYPE_TIMER ) ; timer . setRevision ( 1 ) ; timer . setJobHandlerType ( jobHandlerType ) ; timer . setJobHandlerConfiguration ( jobHandlerConfig ) ; timer . setExclusive ( true ) ; timer . setRetries ( processEngineConfiguration . getAsyncExecutorNumberOfRetries ( ) ) ; timer . setDuedate ( duedate ) ; if ( executionEntity != null ) { timer . setExecution ( executionEntity ) ; timer . setProcessDefinitionId ( executionEntity . getProcessDefinitionId ( ) ) ; timer . setProcessInstanceId ( executionEntity . getProcessInstanceId ( ) ) ; // Inherit tenant identifier ( if applicable )
if ( executionEntity . getTenantId ( ) != null ) { timer . setTenantId ( executionEntity . getTenantId ( ) ) ; } } } if ( StringUtils . isNotEmpty ( timerEventDefinition . getTimeCycle ( ) ) ) { // See ACT - 1427 : A boundary timer with a cancelActivity = ' true ' , doesn ' t need to repeat itself
boolean repeat = ! isInterruptingTimer ; // ACT - 1951 : intermediate catching timer events shouldn ' t repeat according to spec
if ( executionEntity != null ) { FlowElement currentElement = executionEntity . getCurrentFlowElement ( ) ; if ( currentElement instanceof IntermediateCatchEvent ) { repeat = false ; } } if ( repeat ) { String prepared = prepareRepeat ( dueDateString ) ; timer . setRepeat ( prepared ) ; } } if ( timer != null && executionEntity != null ) { timer . setExecution ( executionEntity ) ; timer . setProcessDefinitionId ( executionEntity . getProcessDefinitionId ( ) ) ; // Inherit tenant identifier ( if applicable )
if ( executionEntity . getTenantId ( ) != null ) { timer . setTenantId ( executionEntity . getTenantId ( ) ) ; } } return timer ; |
public class MultiFormatter { /** * httl . properties : formatters + = httl . spi . formatters . NumberFormatter */
public void setFormatters ( Formatter < ? > [ ] formatters ) { } } | if ( formatters != null && formatters . length > 0 ) { for ( Formatter < ? > formatter : formatters ) { if ( formatter != null ) { Class < ? > type = ClassUtils . getGenericClass ( formatter . getClass ( ) ) ; if ( type != null ) { this . formatters . put ( type , formatter ) ; } } } Map < Class < ? > , Formatter < ? > > sorted = new TreeMap < Class < ? > , Formatter < ? > > ( ClassComparator . COMPARATOR ) ; sorted . putAll ( this . formatters ) ; this . sortedFormatters = Collections . unmodifiableMap ( sorted ) ; } |
public class SigarNativeBindingLoader { /** * Extracts the native bindings for sigar and tells sigar where to find them .
* @ return < code > false < / code > , if sigar has already been set up , < code > true < / code > otherwise
* @ throws Exception */
public static boolean loadNativeSigarBindings ( ) throws Exception { } } | final String sigarPath = System . getProperty ( SIGAR_PATH ) ; if ( sigarPath != null ) { // sigar is already set up
return false ; } final File tempDirectory = new File ( System . getProperty ( "java.io.tmpdir" ) , "sigar" ) ; tempDirectory . mkdir ( ) ; loadNativeSigarBindings ( tempDirectory ) ; return true ; |
public class MongoIndexSetService { /** * { @ inheritDoc } */
@ Override public List < IndexSetConfig > findPaginated ( Set < String > indexSetIds , int limit , int skip ) { } } | final List < DBQuery . Query > idQuery = indexSetIds . stream ( ) . map ( id -> DBQuery . is ( "_id" , id ) ) . collect ( Collectors . toList ( ) ) ; final DBQuery . Query query = DBQuery . or ( idQuery . toArray ( new DBQuery . Query [ 0 ] ) ) ; return ImmutableList . copyOf ( collection . find ( query ) . sort ( DBSort . asc ( "title" ) ) . skip ( skip ) . limit ( limit ) . toArray ( ) ) ; |
public class AbstractSessionManager { public void stop ( ) { } } | // Invalidate all sessions to cause unbind events
ArrayList sessions = new ArrayList ( _sessions . values ( ) ) ; for ( Iterator i = sessions . iterator ( ) ; i . hasNext ( ) ; ) { Session session = ( Session ) i . next ( ) ; session . invalidate ( ) ; } _sessions . clear ( ) ; // stop the scavenger
SessionScavenger scavenger = _scavenger ; _scavenger = null ; if ( scavenger != null ) scavenger . interrupt ( ) ; |
public class ElemApplyImport { /** * Add a child to the child list .
* < ! ELEMENT xsl : apply - imports EMPTY >
* @ param newChild New element to append to this element ' s children list
* @ return null , xsl : apply - Imports cannot have children */
public ElemTemplateElement appendChild ( ElemTemplateElement newChild ) { } } | error ( XSLTErrorResources . ER_CANNOT_ADD , new Object [ ] { newChild . getNodeName ( ) , this . getNodeName ( ) } ) ; // " Can not add " + ( ( ElemTemplateElement ) newChild ) . m _ elemName +
// " to " + this . m _ elemName ) ;
return null ; |
public class PolicyAssignmentsInner { /** * Gets a policy assignment .
* @ param scope The scope of the policy assignment .
* @ param policyAssignmentName The name of the policy assignment to get .
* @ 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 < PolicyAssignmentInner > getAsync ( String scope , String policyAssignmentName , final ServiceCallback < PolicyAssignmentInner > serviceCallback ) { } } | return ServiceFuture . fromResponse ( getWithServiceResponseAsync ( scope , policyAssignmentName ) , serviceCallback ) ; |
public class ParaObjectUtils { /** * Returns a map of the core data types .
* @ return a map of type plural - type singular form */
public static Map < String , String > getCoreTypes ( ) { } } | if ( CORE_TYPES . isEmpty ( ) ) { try { for ( Class < ? extends ParaObject > clazz : getCoreClassesMap ( ) . values ( ) ) { ParaObject p = clazz . getConstructor ( ) . newInstance ( ) ; CORE_TYPES . put ( p . getPlural ( ) , p . getType ( ) ) ; } } catch ( Exception ex ) { logger . error ( null , ex ) ; } } return Collections . unmodifiableMap ( CORE_TYPES ) ; |
public class AbstractTypeConvertingMap { /** * Helper method for obtaining float value from parameter
* @ param name The name of the parameter
* @ return The double value or null if there isn ' t one */
public Float getFloat ( String name ) { } } | Object o = get ( name ) ; if ( o instanceof Number ) { return ( ( Number ) o ) . floatValue ( ) ; } if ( o != null ) { try { String string = o . toString ( ) ; if ( string != null ) { return Float . parseFloat ( string ) ; } } catch ( NumberFormatException e ) { } } return null ; |
public class TopicAdminClient { /** * / * package - private */
final PublishResponse publish ( ProjectTopicName topic , List < PubsubMessage > messages ) { } } | PublishRequest request = PublishRequest . newBuilder ( ) . setTopic ( topic == null ? null : topic . toString ( ) ) . addAllMessages ( messages ) . build ( ) ; return publish ( request ) ; |
public class N { /** * Returns the < code > length / 2 + 1 < / code > largest value in the specified array .
* @ param a an array , must not be null or empty
* @ return the median value in the array
* @ see # median ( int . . . ) */
@ SafeVarargs public static char median ( final char ... a ) { } } | N . checkArgNotNullOrEmpty ( a , "The spcified array 'a' can not be null or empty" ) ; return median ( a , 0 , a . length ) ; |
public class KerasUpsampling1D { /** * Get layer output type .
* @ param inputType Array of InputTypes
* @ return output type as InputType
* @ throws InvalidKerasConfigurationException Invalid Keras config */
@ Override public InputType getOutputType ( InputType ... inputType ) throws InvalidKerasConfigurationException { } } | if ( inputType . length > 1 ) throw new InvalidKerasConfigurationException ( "Keras Upsampling 1D layer accepts only one input (received " + inputType . length + ")" ) ; return this . getUpsampling1DLayer ( ) . getOutputType ( - 1 , inputType [ 0 ] ) ; |
public class Scanner { /** * Closes this scanner .
* < p > If this scanner has not yet been closed then if its underlying
* { @ linkplain java . lang . Readable readable } also implements the { @ link
* java . io . Closeable } interface then the readable ' s < tt > close < / tt > method
* will be invoked . If this scanner is already closed then invoking this
* method will have no effect .
* < p > Attempting to perform search operations after a scanner has
* been closed will result in an { @ link IllegalStateException } . */
public void close ( ) { } } | if ( closed ) return ; if ( source instanceof Closeable ) { try { ( ( Closeable ) source ) . close ( ) ; } catch ( IOException ioe ) { lastException = ioe ; } } sourceClosed = true ; source = null ; closed = true ; |
public class SFSSLConnectionSocketFactory { /** * Decide cipher suites that will be passed into the SSLConnectionSocketFactory
* @ return List of cipher suites . */
private static String [ ] decideCipherSuites ( ) { } } | String sysCipherSuites = System . getProperty ( "https.cipherSuites" ) ; String [ ] cipherSuites = sysCipherSuites != null ? sysCipherSuites . split ( "," ) : // use jdk default cipher suites
( ( SSLServerSocketFactory ) SSLServerSocketFactory . getDefault ( ) ) . getDefaultCipherSuites ( ) ; // cipher suites need to be picked up in code explicitly for jdk 1.7
// https : / / stackoverflow . com / questions / 44378970/
if ( logger . isTraceEnabled ( ) ) { logger . trace ( "Cipher suites used: {}" , Arrays . toString ( cipherSuites ) ) ; } return cipherSuites ; |
public class PJsonArray { /** * Get the element as a boolean .
* @ param i the index of the element to access */
@ Override public final boolean getBool ( final int i ) { } } | try { return this . array . getBoolean ( i ) ; } catch ( JSONException e ) { throw new ObjectMissingException ( this , "[" + i + "]" ) ; } |
public class PrettySharedPreferences { /** * Call to get a { @ link com . tale . prettysharedpreferences . FloatEditor } object for the specific
* key . < code > NOTE : < / code > There is a unique { @ link com . tale . prettysharedpreferences . TypeEditor }
* object for a unique key .
* @ param key The name of the preference .
* @ return { @ link com . tale . prettysharedpreferences . FloatEditor } object to be store or retrieve
* a { @ link java . lang . Float } value . */
protected FloatEditor getFloatEditor ( String key ) { } } | TypeEditor typeEditor = TYPE_EDITOR_MAP . get ( key ) ; if ( typeEditor == null ) { typeEditor = new FloatEditor ( this , sharedPreferences , key ) ; TYPE_EDITOR_MAP . put ( key , typeEditor ) ; } else if ( ! ( typeEditor instanceof FloatEditor ) ) { throw new IllegalArgumentException ( String . format ( "key %s is already used for other type" , key ) ) ; } return ( FloatEditor ) typeEditor ; |
public class TypeCheck { /** * This is the meat of the type checking . It is basically one big switch ,
* with each case representing one type of parse tree node . The individual
* cases are usually pretty straightforward .
* @ param t The node traversal object that supplies context , such as the
* scope chain to use in name lookups as well as error reporting .
* @ param n The node being visited .
* @ param parent The parent of the node n . */
@ Override public void visit ( NodeTraversal t , Node n , Node parent ) { } } | JSType childType ; JSType leftType ; JSType rightType ; Node left ; Node right ; // To be explicitly set to false if the node is not typeable .
boolean typeable = true ; switch ( n . getToken ( ) ) { case CAST : Node expr = n . getFirstChild ( ) ; JSType exprType = getJSType ( expr ) ; JSType castType = getJSType ( n ) ; // TODO ( johnlenz ) : determine if we can limit object literals in some
// way .
if ( ! expr . isObjectLit ( ) ) { validator . expectCanCast ( n , castType , exprType ) ; } ensureTyped ( n , castType ) ; expr . setJSTypeBeforeCast ( exprType ) ; if ( castType . restrictByNotNullOrUndefined ( ) . isSubtypeOf ( exprType ) || expr . isObjectLit ( ) ) { expr . setJSType ( castType ) ; } break ; case NAME : typeable = visitName ( t , n , parent ) ; break ; case COMMA : ensureTyped ( n , getJSType ( n . getLastChild ( ) ) ) ; break ; case THIS : ensureTyped ( n , t . getTypedScope ( ) . getTypeOfThis ( ) ) ; break ; case NULL : ensureTyped ( n , NULL_TYPE ) ; break ; case NUMBER : ensureTyped ( n , NUMBER_TYPE ) ; break ; case GETTER_DEF : case SETTER_DEF : // Object literal keys are handled with OBJECTLIT
break ; case ARRAYLIT : ensureTyped ( n , ARRAY_TYPE ) ; break ; case REGEXP : ensureTyped ( n , REGEXP_TYPE ) ; break ; case GETPROP : visitGetProp ( t , n ) ; typeable = ! ( parent . isAssign ( ) && parent . getFirstChild ( ) == n ) ; break ; case GETELEM : visitGetElem ( n ) ; // The type of GETELEM is always unknown , so no point counting that .
// If that unknown leaks elsewhere ( say by an assignment to another
// variable ) , then it will be counted .
typeable = false ; break ; case VAR : case LET : case CONST : visitVar ( t , n ) ; typeable = false ; break ; case NEW : visitNew ( n ) ; break ; case CALL : visitCall ( t , n ) ; typeable = ! parent . isExprResult ( ) ; break ; case RETURN : visitReturn ( t , n ) ; typeable = false ; break ; case YIELD : visitYield ( t , n ) ; break ; case SUPER : case NEW_TARGET : case AWAIT : ensureTyped ( n ) ; break ; case DEC : case INC : left = n . getFirstChild ( ) ; checkPropCreation ( left ) ; validator . expectNumber ( left , getJSType ( left ) , "increment/decrement" ) ; ensureTyped ( n , NUMBER_TYPE ) ; break ; case VOID : ensureTyped ( n , VOID_TYPE ) ; break ; case STRING : case TYPEOF : case TEMPLATELIT : case TEMPLATELIT_STRING : ensureTyped ( n , STRING_TYPE ) ; break ; case TAGGED_TEMPLATELIT : visitTaggedTemplateLit ( n ) ; ensureTyped ( n ) ; break ; case BITNOT : childType = getJSType ( n . getFirstChild ( ) ) ; if ( ! childType . matchesNumberContext ( ) ) { report ( n , BIT_OPERATION , NodeUtil . opToStr ( n . getToken ( ) ) , childType . toString ( ) ) ; } else { this . validator . expectNumberStrict ( n , childType , "bitwise NOT" ) ; } ensureTyped ( n , NUMBER_TYPE ) ; break ; case POS : case NEG : left = n . getFirstChild ( ) ; if ( n . getToken ( ) == Token . NEG ) { // We are more permissive with + , because it is used to coerce to number
validator . expectNumber ( left , getJSType ( left ) , "sign operator" ) ; } ensureTyped ( n , NUMBER_TYPE ) ; break ; case EQ : case NE : case SHEQ : case SHNE : { left = n . getFirstChild ( ) ; right = n . getLastChild ( ) ; if ( left . isTypeOf ( ) ) { if ( right . isString ( ) ) { checkTypeofString ( right , right . getString ( ) ) ; } } else if ( right . isTypeOf ( ) && left . isString ( ) ) { checkTypeofString ( left , left . getString ( ) ) ; } leftType = getJSType ( left ) ; rightType = getJSType ( right ) ; // We do not want to warn about explicit comparisons to VOID . People
// often do this if they think their type annotations screwed up .
// We do want to warn about cases where people compare things like
// ( Array | null ) = = ( Function | null )
// because it probably means they screwed up .
// This heuristic here is not perfect , but should catch cases we
// care about without too many false negatives .
JSType leftTypeRestricted = leftType . restrictByNotNullOrUndefined ( ) ; JSType rightTypeRestricted = rightType . restrictByNotNullOrUndefined ( ) ; TernaryValue result = TernaryValue . UNKNOWN ; if ( n . getToken ( ) == Token . EQ || n . isNE ( ) ) { result = leftTypeRestricted . testForEquality ( rightTypeRestricted ) ; if ( n . isNE ( ) ) { result = result . not ( ) ; } } else { // SHEQ or SHNE
if ( ! leftTypeRestricted . canTestForShallowEqualityWith ( rightTypeRestricted ) ) { result = n . getToken ( ) == Token . SHEQ ? TernaryValue . FALSE : TernaryValue . TRUE ; } } if ( result != TernaryValue . UNKNOWN ) { report ( n , DETERMINISTIC_TEST , leftType . toString ( ) , rightType . toString ( ) , result . toString ( ) ) ; } ensureTyped ( n , BOOLEAN_TYPE ) ; break ; } case LT : case LE : case GT : case GE : Node leftSide = n . getFirstChild ( ) ; Node rightSide = n . getLastChild ( ) ; leftType = getJSType ( leftSide ) ; rightType = getJSType ( rightSide ) ; if ( rightType . isUnknownType ( ) ) { // validate comparable left
validator . expectStringOrNumber ( leftSide , leftType , "left side of comparison" ) ; } else if ( leftType . isUnknownType ( ) ) { // validate comparable right
validator . expectStringOrNumber ( rightSide , rightType , "right side of comparison" ) ; } else if ( rightType . isNumber ( ) ) { validator . expectNumber ( leftSide , leftType , "left side of numeric comparison" ) ; } else if ( leftType . isNumber ( ) ) { validator . expectNumber ( rightSide , rightType , "right side of numeric comparison" ) ; } else { String errorMsg = "expected matching types in comparison" ; this . validator . expectMatchingTypesStrict ( n , leftType , rightType , errorMsg ) ; if ( ! leftType . matchesNumberContext ( ) || ! rightType . matchesNumberContext ( ) ) { // Whether the comparison is numeric will be determined at runtime
// each time the expression is evaluated . Regardless , both operands
// should match a string context .
String message = "left side of comparison" ; validator . expectString ( leftSide , leftType , message ) ; validator . expectNotNullOrUndefined ( t , leftSide , leftType , message , getNativeType ( STRING_TYPE ) ) ; message = "right side of comparison" ; validator . expectString ( rightSide , rightType , message ) ; validator . expectNotNullOrUndefined ( t , rightSide , rightType , message , getNativeType ( STRING_TYPE ) ) ; } } ensureTyped ( n , BOOLEAN_TYPE ) ; break ; case IN : left = n . getFirstChild ( ) ; right = n . getLastChild ( ) ; rightType = getJSType ( right ) ; validator . expectStringOrSymbol ( left , getJSType ( left ) , "left side of 'in'" ) ; validator . expectObject ( n , rightType , "'in' requires an object" ) ; if ( rightType . isStruct ( ) ) { report ( right , IN_USED_WITH_STRUCT ) ; } ensureTyped ( n , BOOLEAN_TYPE ) ; break ; case INSTANCEOF : left = n . getFirstChild ( ) ; right = n . getLastChild ( ) ; rightType = getJSType ( right ) . restrictByNotNullOrUndefined ( ) ; validator . expectAnyObject ( left , getJSType ( left ) , "deterministic instanceof yields false" ) ; validator . expectActualObject ( right , rightType , "instanceof requires an object" ) ; ensureTyped ( n , BOOLEAN_TYPE ) ; break ; case ASSIGN : visitAssign ( t , n ) ; typeable = false ; break ; case ASSIGN_LSH : case ASSIGN_RSH : case ASSIGN_URSH : case ASSIGN_DIV : case ASSIGN_MOD : case ASSIGN_BITOR : case ASSIGN_BITXOR : case ASSIGN_BITAND : case ASSIGN_SUB : case ASSIGN_ADD : case ASSIGN_MUL : case ASSIGN_EXPONENT : checkPropCreation ( n . getFirstChild ( ) ) ; // fall through
case LSH : case RSH : case URSH : case DIV : case MOD : case BITOR : case BITXOR : case BITAND : case SUB : case ADD : case MUL : case EXPONENT : visitBinaryOperator ( n . getToken ( ) , n ) ; break ; case TRUE : case FALSE : case NOT : case DELPROP : ensureTyped ( n , BOOLEAN_TYPE ) ; break ; case CASE : JSType switchType = getJSType ( parent . getFirstChild ( ) ) ; JSType caseType = getJSType ( n . getFirstChild ( ) ) ; validator . expectSwitchMatchesCase ( n , switchType , caseType ) ; typeable = false ; break ; case WITH : { Node child = n . getFirstChild ( ) ; childType = getJSType ( child ) ; validator . expectObject ( child , childType , "with requires an object" ) ; typeable = false ; break ; } case FUNCTION : visitFunction ( n ) ; break ; case CLASS : visitClass ( n ) ; break ; // These nodes have no interesting type behavior .
// These nodes require data flow analysis .
case PARAM_LIST : case STRING_KEY : case MEMBER_FUNCTION_DEF : case COMPUTED_PROP : case LABEL : case LABEL_NAME : case SWITCH : case BREAK : case CATCH : case TRY : case SCRIPT : case MODULE_BODY : case EXPR_RESULT : case BLOCK : case ROOT : case EMPTY : case DEFAULT_CASE : case CONTINUE : case DEBUGGER : case THROW : case DO : case IF : case WHILE : case FOR : case TEMPLATELIT_SUB : case REST : case DESTRUCTURING_LHS : typeable = false ; break ; case ARRAY_PATTERN : ensureTyped ( n ) ; validator . expectAutoboxesToIterable ( n , getJSType ( n ) , "array pattern destructuring requires an Iterable" ) ; break ; case OBJECT_PATTERN : visitObjectPattern ( n ) ; break ; case DEFAULT_VALUE : checkCanAssignToWithScope ( t , n , n . getFirstChild ( ) , getJSType ( n . getSecondChild ( ) ) , /* info = */
null , "default value has wrong type" ) ; // Every other usage of a destructuring pattern is checked while visiting the pattern ,
// but default values are different because they are a conditional assignment and the
// pattern is not given the default value ' s type
Node lhs = n . getFirstChild ( ) ; Node rhs = n . getSecondChild ( ) ; if ( lhs . isArrayPattern ( ) ) { validator . expectAutoboxesToIterable ( rhs , getJSType ( rhs ) , "array pattern destructuring requires an Iterable" ) ; } else if ( lhs . isObjectPattern ( ) ) { // Verify that the value is not null / undefined , since those can ' t be destructured .
validator . expectObject ( rhs , getJSType ( rhs ) , "cannot destructure a 'null' or 'undefined' default value" ) ; } typeable = false ; break ; case CLASS_MEMBERS : { JSType typ = parent . getJSType ( ) . toMaybeFunctionType ( ) . getInstanceType ( ) ; for ( Node child = n . getFirstChild ( ) ; child != null ; child = child . getNext ( ) ) { visitObjectOrClassLiteralKey ( child , n . getParent ( ) , typ ) ; } typeable = false ; break ; } case FOR_IN : Node obj = n . getSecondChild ( ) ; if ( getJSType ( obj ) . isStruct ( ) ) { report ( obj , IN_USED_WITH_STRUCT ) ; } typeable = false ; break ; case FOR_OF : case FOR_AWAIT_OF : ensureTyped ( n . getSecondChild ( ) ) ; typeable = false ; break ; // These nodes are typed during the type inference .
case AND : case HOOK : case OBJECTLIT : case OR : if ( n . getJSType ( ) != null ) { // If we didn ' t run type inference .
ensureTyped ( n ) ; } else { // If this is an enum , then give that type to the objectlit as well .
if ( n . isObjectLit ( ) && ( parent . getJSType ( ) instanceof EnumType ) ) { ensureTyped ( n , parent . getJSType ( ) ) ; } else { ensureTyped ( n ) ; } } if ( n . isObjectLit ( ) ) { JSType typ = getJSType ( n ) ; for ( Node key : n . children ( ) ) { visitObjectOrClassLiteralKey ( key , n , typ ) ; } } break ; case SPREAD : checkSpread ( n ) ; typeable = false ; break ; default : report ( n , UNEXPECTED_TOKEN , n . getToken ( ) . toString ( ) ) ; ensureTyped ( n ) ; break ; } // Visit the body of blockless arrow functions
if ( NodeUtil . isBlocklessArrowFunctionResult ( n ) ) { visitImplicitReturnExpression ( t , n ) ; } // Visit the loop initializer of a for - of loop
// We do this check here , instead of when visiting FOR _ OF , in order to get the correct
// TypedScope .
if ( ( n . getParent ( ) . isForOf ( ) || n . getParent ( ) . isForAwaitOf ( ) ) && n . getParent ( ) . getFirstChild ( ) == n ) { checkForOfTypes ( t , n . getParent ( ) ) ; } // Don ' t count externs since the user ' s code may not even use that part .
typeable = typeable && ! inExterns ; if ( typeable ) { doPercentTypedAccounting ( n ) ; } checkJsdocInfoContainsObjectWithBadKey ( n ) ; |
public class Box { /** * Sets the box parameters to the values contained in the supplied vectors .
* @ return a reference to this box , for chaining . */
public Box set ( IVector3 minExtent , IVector3 maxExtent ) { } } | _minExtent . set ( minExtent ) ; _maxExtent . set ( maxExtent ) ; return this ; |
public class RecommendationsInner { /** * Reset all recommendation opt - out settings for an app .
* Reset all recommendation opt - out settings for an app .
* @ param resourceGroupName Name of the resource group to which the resource belongs .
* @ param siteName Name of the app .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ throws CloudException thrown if the request is rejected by server
* @ throws RuntimeException all other wrapped checked exceptions if the request fails to be sent */
public void resetAllFiltersForWebApp ( String resourceGroupName , String siteName ) { } } | resetAllFiltersForWebAppWithServiceResponseAsync ( resourceGroupName , siteName ) . toBlocking ( ) . single ( ) . body ( ) ; |
public class ZipUtils { /** * Attempt to recursively delete a file .
* Do not retry in case of a failure .
* A test must be done to verify that the file exists before
* invoking this method : If the file does not exist , the
* delete operation will fail .
* @ param file The file to recursively delete .
* @ return Null if the file was deleted . The first file which
* could not be deleted if the file could not be deleted . */
@ Trivial public static File delete ( File file ) { } } | String methodName = "delete" ; String filePath ; if ( tc . isDebugEnabled ( ) ) { filePath = file . getAbsolutePath ( ) ; } else { filePath = null ; } if ( file . isDirectory ( ) ) { if ( filePath != null ) { Tr . debug ( tc , methodName + ": Delete directory [ " + filePath + " ]" ) ; } File firstFailure = null ; File [ ] subFiles = file . listFiles ( ) ; if ( subFiles != null ) { for ( File subFile : subFiles ) { File nextFailure = delete ( subFile ) ; if ( ( nextFailure != null ) && ( firstFailure == null ) ) { firstFailure = nextFailure ; } } } if ( firstFailure != null ) { if ( filePath != null ) { Tr . debug ( tc , methodName + ": Cannot delete [ " + filePath + " ]" + " Child [ " + firstFailure . getAbsolutePath ( ) + " ] could not be deleted." ) ; } return firstFailure ; } } else { if ( filePath != null ) { Tr . debug ( tc , methodName + ": Delete simple file [ " + filePath + " ]" ) ; } } if ( ! file . delete ( ) ) { if ( filePath != null ) { Tr . debug ( tc , methodName + ": Failed to delete [ " + filePath + " ]" ) ; } return file ; } else { if ( filePath != null ) { Tr . debug ( tc , methodName + ": Deleted [ " + filePath + " ]" ) ; } return null ; } |
public class ParameterParser { /** * Parse the arguments .
* @ param args arguments
* @ return a list of strings which are not parameters , e . g . a list of file
* name . */
public List < String > parse ( String [ ] args ) { } } | // merge args & defaults
List < String > extras = new ArrayList < > ( ) ; List < String > filteredArgs = filterMonadics ( args ) ; // detect and fill mons
for ( int i = 0 ; i < filteredArgs . size ( ) ; i ++ ) { String key = filteredArgs . get ( i ) ; if ( key . equalsIgnoreCase ( "-h" ) || key . equalsIgnoreCase ( "-help" ) ) { System . out . println ( usage ) ; System . exit ( 0 ) ; } if ( parameters . containsKey ( key ) ) { Parameter param = parameters . get ( key ) ; param . value = filteredArgs . get ( i + 1 ) ; switch ( param . paramType ) { case INTEGER : try { Integer . parseInt ( param . value ) ; } catch ( Exception ex ) { System . err . println ( "Invalid parameter " + param . name + ' ' + param . value ) ; System . err . println ( usage ) ; System . exit ( 1 ) ; } break ; case FLOAT : try { Double . parseDouble ( param . value ) ; } catch ( Exception ex ) { System . err . println ( "Invalid parameter " + param . name + ' ' + param . value ) ; System . err . println ( usage ) ; System . exit ( 1 ) ; } break ; default : // Just to remove unmatched case warning
} i ++ ; } else { extras . add ( key ) ; } } for ( String key : parameters . keySet ( ) ) { Parameter param = parameters . get ( key ) ; if ( param . mandatory && param . value == null ) { System . err . println ( "Missing mandatory parameter: " + key ) ; System . err . println ( usage ) ; System . exit ( 1 ) ; } } return extras ; // parsed + defaults |
public class ServiceLocator { /** * This method helps in obtaining the topic factory
* @ return the factory for the factory to get topic connections from */
public TopicConnectionFactory getTopicConnectionFactory ( String topicConnFactoryName ) throws ServiceLocatorException { } } | TopicConnectionFactory factory = null ; try { if ( cache . containsKey ( topicConnFactoryName ) ) { factory = ( TopicConnectionFactory ) cache . get ( topicConnFactoryName ) ; } else { factory = ( TopicConnectionFactory ) ic . lookup ( topicConnFactoryName ) ; cache . put ( topicConnFactoryName , factory ) ; } } catch ( NamingException ne ) { throw new ServiceLocatorException ( ne ) ; } catch ( Exception e ) { throw new ServiceLocatorException ( e ) ; } return factory ; |
public class GeneralizedParetoDistribution { /** * CDF of GPD distribution
* @ param val Value
* @ param mu Location parameter mu
* @ param sigma Scale parameter sigma
* @ param xi Shape parameter xi ( = - kappa )
* @ return CDF at position x . */
public static double cdf ( double val , double mu , double sigma , double xi ) { } } | val = ( val - mu ) / sigma ; // Check support :
if ( val < 0 ) { return 0. ; } if ( xi < 0 && val > - 1. / xi ) { return 1. ; } return 1 - FastMath . pow ( 1 + xi * val , - 1. / xi ) ; |
public class AbstractDataServiceVisitor { /** * browse valid methods and write equivalent js methods in writer
* @ param methodElements
* @ param classname
* @ param writer
* @ return
* @ throws IOException */
void browseAndWriteMethods ( List < ExecutableElement > methodElements , String classname , Writer writer ) throws IOException { } } | Collection < String > methodProceeds = new ArrayList < > ( ) ; boolean first = true ; for ( ExecutableElement methodElement : methodElements ) { if ( isConsiderateMethod ( methodProceeds , methodElement ) ) { if ( ! first ) { writer . append ( COMMA ) . append ( CR ) ; } visitMethodElement ( classname , methodElement , writer ) ; first = false ; } } |
public class MessageSelectingQueueChannel { /** * Consume messages on the channel via message selector . Timeout forces several retries
* with polling interval setting .
* @ param selector
* @ param timeout
* @ return */
public Message < ? > receive ( MessageSelector selector , long timeout ) { } } | long timeLeft = timeout ; Message < ? > message = receive ( selector ) ; while ( message == null && timeLeft > 0 ) { timeLeft -= pollingInterval ; if ( RETRY_LOG . isDebugEnabled ( ) ) { RETRY_LOG . debug ( "No message received with message selector - retrying in " + ( timeLeft > 0 ? pollingInterval : pollingInterval + timeLeft ) + "ms" ) ; } try { Thread . sleep ( timeLeft > 0 ? pollingInterval : pollingInterval + timeLeft ) ; } catch ( InterruptedException e ) { RETRY_LOG . warn ( "Thread interrupted while waiting for retry" , e ) ; } message = receive ( selector ) ; } return message ; |
public class PropertiesConfig { /** * Method to read propeties file and store the data */
private void readProperties ( ) { } } | InputStream input = null ; try { input = getClass ( ) . getClassLoader ( ) . getResourceAsStream ( PROP_FILE_NAME ) ; if ( input == null ) { logger . info ( "Unnable to find " + PROP_FILE_NAME ) ; return ; } prop . load ( input ) ; } catch ( Exception e ) { logger . info ( "exception in PropertiesConfig readProperties" ) ; } finally { if ( input != null ) { try { input . close ( ) ; } catch ( Exception e ) { logger . info ( "exception in PropertiesConfig readProperties finally" ) ; } } } |
public class EvaluatorManager { /** * Process an evaluator message that indicates that the evaluator shut down cleanly .
* @ param message */
private synchronized void onEvaluatorDone ( final EvaluatorStatusPOJO message ) { } } | assert message . getState ( ) == State . DONE ; LOG . log ( Level . FINEST , "Evaluator {0} done." , getId ( ) ) ; // Send an ACK to the Evaluator .
sendEvaluatorControlMessage ( EvaluatorRuntimeProtocol . EvaluatorControlProto . newBuilder ( ) . setTimestamp ( System . currentTimeMillis ( ) ) . setIdentifier ( getId ( ) ) . setDoneEvaluator ( EvaluatorRuntimeProtocol . DoneEvaluatorProto . newBuilder ( ) . build ( ) ) . build ( ) ) ; this . stateManager . setDone ( ) ; this . messageDispatcher . onEvaluatorCompleted ( new CompletedEvaluatorImpl ( this . evaluatorId ) ) ; this . close ( ) ; |
public class Inflector { /** * Generates a camel case version of a phrase from underscore .
* @ param underscore underscore version of a word to converted to camel case .
* @ param capitalizeFirstChar set to true if first character needs to be capitalized , false if not .
* @ return camel case version of underscore . */
public static String camelize ( String underscore , boolean capitalizeFirstChar ) { } } | StringBuilder result = new StringBuilder ( ) ; StringTokenizer st = new StringTokenizer ( underscore , "_" ) ; while ( st . hasMoreTokens ( ) ) { result . append ( capitalize ( st . nextToken ( ) ) ) ; } return capitalizeFirstChar ? result . toString ( ) : result . substring ( 0 , 1 ) . toLowerCase ( ) + result . substring ( 1 ) ; |
public class ManagedObjectFactoryImpl { /** * ( non - Javadoc )
* @ see com . ibm . ws . managedobject . ManagedObjectFactory # createManagedObject ( java . lang . Object , com . ibm . ws . managedobject . ManagedObjectInvocationContext ) */
@ Override public ManagedObject < T > createManagedObject ( T existingInstance , ManagedObjectInvocationContext < T > invocationContext ) { } } | if ( existingInstance == null ) { throw new IllegalArgumentException ( "Existing instance must not be null" ) ; } return new ManagedObjectImpl < T > ( existingInstance ) ; |
public class ServiceObjectivesInner { /** * Gets a database service objective .
* @ param resourceGroupName The name of the resource group that contains the resource . You can obtain this value from the Azure Resource Manager API or the portal .
* @ param serverName The name of the server .
* @ param serviceObjectiveName The name of the service objective to retrieve .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ throws CloudException thrown if the request is rejected by server
* @ throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @ return the ServiceObjectiveInner object if successful . */
public ServiceObjectiveInner get ( String resourceGroupName , String serverName , String serviceObjectiveName ) { } } | return getWithServiceResponseAsync ( resourceGroupName , serverName , serviceObjectiveName ) . toBlocking ( ) . single ( ) . body ( ) ; |
public class Element { /** * Add a new element attribute
* @ param attributeName attribute name
* @ param attributeValue attribute value
* @ throws XmlModelException XML model exception */
public void addAttribute ( String attributeName , String attributeValue ) throws XmlModelException { } } | String name = attributeName . trim ( ) ; String value = attributeValue . trim ( ) ; if ( attributesMap . containsKey ( name ) ) { throw new XmlModelException ( "Duplicate attribute: " + name ) ; } attributeNames . add ( name ) ; attributesMap . put ( name , new Attribute ( name , value ) ) ; |
public class ChannelServiceRestAdapter { /** * HTTP POST to create a channel , returns location to new resource which can
* then be long polled . Since the channel id may later change to be a UUID ,
* not using a PUT but rather POST with used id being returned
* @ param ccid cluster controller id
* @ param atmosphereTrackingId tracking id for atmosphere
* @ return location to new resource */
@ POST @ Produces ( { } } | MediaType . TEXT_PLAIN } ) public Response createChannel ( @ QueryParam ( "ccid" ) String ccid , @ HeaderParam ( ChannelServiceConstants . X_ATMOSPHERE_TRACKING_ID ) String atmosphereTrackingId ) { try { log . info ( "CREATE channel for channel ID: {}" , ccid ) ; if ( ccid == null || ccid . isEmpty ( ) ) throw new JoynrHttpException ( Status . BAD_REQUEST , JOYNRMESSAGINGERROR_CHANNELNOTSET ) ; Channel channel = channelService . getChannel ( ccid ) ; if ( channel != null ) { String encodedChannelLocation = response . encodeURL ( channel . getLocation ( ) . toString ( ) ) ; return Response . ok ( ) . entity ( encodedChannelLocation ) . header ( "Location" , encodedChannelLocation ) . header ( "bp" , channel . getBounceProxy ( ) . getId ( ) ) . build ( ) ; } // look for an existing bounce proxy handling the channel
channel = channelService . createChannel ( ccid , atmosphereTrackingId ) ; String encodedChannelLocation = response . encodeURL ( channel . getLocation ( ) . toString ( ) ) ; log . debug ( "encoded channel URL " + channel . getLocation ( ) + " to " + encodedChannelLocation ) ; return Response . created ( URI . create ( encodedChannelLocation ) ) . entity ( encodedChannelLocation ) . header ( "bp" , channel . getBounceProxy ( ) . getId ( ) ) . build ( ) ; } catch ( WebApplicationException ex ) { throw ex ; } catch ( Exception e ) { throw new WebApplicationException ( e ) ; } |
public class AmazonRDSClient { /** * Returns information about DB snapshots . This API action supports pagination .
* @ param describeDBSnapshotsRequest
* @ return Result of the DescribeDBSnapshots operation returned by the service .
* @ throws DBSnapshotNotFoundException
* < i > DBSnapshotIdentifier < / i > doesn ' t refer to an existing DB snapshot .
* @ sample AmazonRDS . DescribeDBSnapshots
* @ see < a href = " http : / / docs . aws . amazon . com / goto / WebAPI / rds - 2014-10-31 / DescribeDBSnapshots " target = " _ top " > AWS API
* Documentation < / a > */
@ Override public DescribeDBSnapshotsResult describeDBSnapshots ( DescribeDBSnapshotsRequest request ) { } } | request = beforeClientExecution ( request ) ; return executeDescribeDBSnapshots ( request ) ; |
public class VirtualMachineScaleSetsInner { /** * Reimages ( upgrade the operating system ) one or more virtual machines in a VM scale set .
* @ param resourceGroupName The name of the resource group .
* @ param vmScaleSetName The name of the VM scale set .
* @ 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 < OperationStatusResponseInner > beginReimageAsync ( String resourceGroupName , String vmScaleSetName , final ServiceCallback < OperationStatusResponseInner > serviceCallback ) { } } | return ServiceFuture . fromResponse ( beginReimageWithServiceResponseAsync ( resourceGroupName , vmScaleSetName ) , serviceCallback ) ; |
public class XMLStreamEventsSync { /** * Go successively into the given elements . */
public boolean goInto ( ElementContext rootContext , String ... innerElements ) throws IOException , XMLException { } } | ElementContext parent = rootContext ; for ( int i = 0 ; i < innerElements . length ; ++ i ) { if ( ! nextInnerElement ( parent , innerElements [ i ] ) ) return false ; parent = event . context . getFirst ( ) ; } return true ; |
public class EventManager { /** * Register the given observer to be triggered if the given event type is triggered .
* @ param event type
* @ param observer event observer
* @ param < T > relating type */
public < T > void register ( Class < T > event , EventObserver < T > observer ) { } } | if ( event == null ) { throw new IllegalArgumentException ( "Null Event type passed to register" ) ; } if ( observer == null ) { throw new IllegalArgumentException ( "Null observer passed to register" ) ; } nullSafeGet ( event ) . add ( observer ) ; |
public class Navigator { /** * Navigates back . If current location is null it doesn ' t take any effect . When controllerClass
* is null , navigate to the very first location and clear all history prior to it , otherwise
* navigate to location with given locationId and clear history prior to it . Then a
* { @ link NavigationManager . Event . OnLocationBack } event will be raised .
* @ param controllerClass the controller class type */
public void back ( Class < ? extends Controller > controllerClass ) { } } | String toLocationId = controllerClass == null ? null : controllerClass . getName ( ) ; navigateBackToLoc ( toLocationId ) ; |
public class ListenerCollection { /** * Removes a { @ link org . vaadin . spring . events . internal . ListenerCollection . Listener } previously added by
* { @ link # add ( org . vaadin . spring . events . internal . ListenerCollection . Listener ) } .
* If no listener definition is found in the collection , nothing happens .
* @ param listener the listener to remove , never { @ code null } .
* @ see # add ( org . vaadin . spring . events . internal . ListenerCollection . Listener ) */
public void remove ( Listener listener ) { } } | logger . trace ( "Removing listener [{}]" , listener ) ; synchronized ( listeners ) { listeners . remove ( listener ) ; } synchronized ( weakListeners ) { weakListeners . remove ( listener ) ; } |
public class BeanO { /** * Create an interval timer whose first expiration occurs at a given
* point in time and whose subsequent expirations occur after a
* specified interval . < p >
* @ param initialExpiration The point in time at which the first timer
* expiration must occur .
* @ param intervalDuration The number of milliseconds that must elapse
* between timer expiration notifications .
* Expiration notifications are scheduled relative
* to the time of the first expiration . If expiration
* is delayed ( e . g . due to the interleaving of other
* method calls on the bean ) two or more expiration
* notifications may occur in close succession to
* " catch up " .
* @ param timerConfig Wrapper of application information to be delivered along with the timer
* expiration notification . Has indication of persistent vs NP .
* @ return The newly created Timer .
* @ exception IllegalArgumentException If initialExpiration is null , or
* initialExpiration . getTime ( ) is negative , or intervalDuration
* is negative .
* @ exception IllegalStateException If this method is invoked while the
* instance is in a state that does not allow access to this method .
* @ exception EJBException If this method fails due to a system - level failure . */
@ Override public Timer createIntervalTimer ( Date initialExpiration , long intervalDuration , TimerConfig timerConfig ) throws IllegalArgumentException , IllegalStateException , EJBException { } } | final boolean isTraceOn = TraceComponent . isAnyTracingEnabled ( ) ; // F743-425 . CodRev
boolean persistent = ( timerConfig == null ? true : timerConfig . isPersistent ( ) ) ; Serializable info = ( timerConfig == null ? ( Serializable ) null : timerConfig . getInfo ( ) ) ; if ( isTraceOn && tc . isEntryEnabled ( ) ) { Tr . entry ( tc , "createIntervalTimer: " + initialExpiration + ", " + intervalDuration + ": " + info + ", " + persistent , this ) ; // F743-425.1
} // Bean must implement TimedObject interface or have a timeout method to create a timer .
if ( ! home . beanMetaData . isTimedObject ) { IllegalStateException ise ; ise = new IllegalStateException ( "Timer Service: Bean does not " + "implement TimedObject: " + beanId ) ; if ( isTraceOn && tc . isDebugEnabled ( ) ) { Tr . debug ( tc , "createIntervalTimer: " + ise ) ; // F743-425.1
} throw ise ; } // Determine if this bean is in a state that allows timer service
// method access - throws IllegalStateException if not allowed .
checkTimerServiceAccess ( ) ; IllegalArgumentException iae = null ; // Make sure the arguments are valid . . . .
if ( initialExpiration == null || initialExpiration . getTime ( ) < 0 ) { iae = new IllegalArgumentException ( "TimerService: initialExpiration not " + "a valid value: " + initialExpiration ) ; } else if ( intervalDuration < 0 ) { iae = new IllegalArgumentException ( "TimerService: intervalDuration not " + "a valid value: " + intervalDuration ) ; } if ( iae != null ) { if ( isTraceOn && tc . isDebugEnabled ( ) ) Tr . debug ( tc , "createIntervalTimer: " + iae ) ; // F743-425.1
throw iae ; } Timer timer = container . getEJBRuntime ( ) . createTimer ( this , initialExpiration , intervalDuration , null , info , persistent ) ; // F743-13022
if ( isTraceOn && tc . isEntryEnabled ( ) ) Tr . exit ( tc , "createIntervalTimer: " + timer ) ; // F743-425.1
return timer ; |
public class ChunkImpl { /** * If not already created , a new < code > processor < / code > element with the given value will be created .
* Otherwise , the existing < code > processor < / code > element will be returned .
* @ return a new or existing instance of < code > ItemProcessor < Chunk < T > > < / code > */
public ItemProcessor < Chunk < T > > getOrCreateProcessor ( ) { } } | Node node = childNode . getOrCreate ( "processor" ) ; ItemProcessor < Chunk < T > > processor = new ItemProcessorImpl < Chunk < T > > ( this , "processor" , childNode , node ) ; return processor ; |
public class GraphicsUtilities { /** * < p > Returns a new translucent compatible image of the specified width and
* height . That is , the returned < code > BufferedImage < / code > is compatible with
* the graphics hardware . If the method is called in a headless
* environment , then the returned BufferedImage will be compatible with
* the source image . < / p >
* @ see # createCompatibleImage ( java . awt . image . BufferedImage )
* @ see # createCompatibleImage ( java . awt . image . BufferedImage , int , int )
* @ see # createCompatibleImage ( int , int )
* @ see # loadCompatibleImage ( java . net . URL )
* @ see # toCompatibleImage ( java . awt . image . BufferedImage )
* @ param width the width of the new image
* @ param height the height of the new image
* @ return a new translucent compatible < code > BufferedImage < / code > of the
* specified width and height */
public static BufferedImage createCompatibleTranslucentImage ( int width , int height ) { } } | return isHeadless ( ) ? new BufferedImage ( width , height , BufferedImage . TYPE_INT_ARGB ) : getGraphicsConfiguration ( ) . createCompatibleImage ( width , height , Transparency . TRANSLUCENT ) ; |
public class appqoecustomresp { /** * Use this API to change appqoecustomresp resources . */
public static base_responses change ( nitro_service client , appqoecustomresp resources [ ] ) throws Exception { } } | base_responses result = null ; if ( resources != null && resources . length > 0 ) { appqoecustomresp updateresources [ ] = new appqoecustomresp [ resources . length ] ; for ( int i = 0 ; i < resources . length ; i ++ ) { updateresources [ i ] = new appqoecustomresp ( ) ; updateresources [ i ] . name = resources [ i ] . name ; } result = perform_operation_bulk_request ( client , updateresources , "update" ) ; } return result ; |
public class GlobalMercator { /** * Converts EPSG : 900913 to pyramid pixel coordinates in given zoom level
* @ param mx
* @ param my
* @ param zoom
* @ return */
public int [ ] MetersToPixels ( double mx , double my , int zoom ) { } } | double res = Resolution ( zoom ) ; int px = ( int ) Math . round ( ( mx + originShift ) / res ) ; int py = ( int ) Math . round ( ( my + originShift ) / res ) ; return new int [ ] { px , py } ; |
public class TeaToolsUtils { /** * Create a version information string based on what the build process
* provided . The string is of the form " M . m . r " or
* " M . m . r . bbbb " ( i . e . 1.1.0.0004 ) if the build number can be retrieved .
* Returns < code > null < / code > if the version string cannot be retrieved . */
public String getPackageVersion ( String packageName ) { } } | if ( packageName == null || packageName . trim ( ) . length ( ) == 0 ) { return null ; } if ( ! packageName . endsWith ( "." ) ) { packageName = packageName + "." ; } String className = packageName + "PackageInfo" ; Class < ? > packageInfoClass = getClassForName ( className ) ; if ( packageInfoClass == null ) { return null ; } String productVersion = null ; String buildNumber = null ; try { Method getProductVersionMethod = packageInfoClass . getMethod ( "getProductVersion" , EMPTY_CLASS_ARRAY ) ; productVersion = ( String ) getProductVersionMethod . invoke ( null , EMPTY_OBJECT_ARRAY ) ; Method getBuildNumberMethod = packageInfoClass . getMethod ( "getBuildNumber" , EMPTY_CLASS_ARRAY ) ; buildNumber = ( String ) getBuildNumberMethod . invoke ( null , EMPTY_OBJECT_ARRAY ) ; } catch ( Throwable t ) { // Just eat it
} if ( productVersion != null && productVersion . length ( ) > 0 && buildNumber != null && buildNumber . length ( ) > 0 ) { productVersion += '.' + buildNumber ; } return productVersion ; |
public class SSLUtils { /** * This method is called for tracing in various places . It returns a string that
* represents the buffer including hashcode , position , limit , and capacity .
* @ param src
* @ param buffer buffer to get debug info on
* @ return StringBuilder */
public static StringBuilder getBufferTraceInfo ( StringBuilder src , WsByteBuffer buffer ) { } } | StringBuilder sb = ( null == src ) ? new StringBuilder ( 64 ) : src ; if ( null == buffer ) { return sb . append ( "null" ) ; } sb . append ( "hc=" ) . append ( buffer . hashCode ( ) ) ; sb . append ( " pos=" ) . append ( buffer . position ( ) ) ; sb . append ( " lim=" ) . append ( buffer . limit ( ) ) ; sb . append ( " cap=" ) . append ( buffer . capacity ( ) ) ; return sb ; |
public class ZeroBitCounter { /** * This Java method counts the number of non - set bits ( i . e . , bits that are ' 0 ' ) from 1 to the given number .
* Examples :
* count _ zero _ bits ( 2 ) - > 1
* count _ zero _ bits ( 5 ) - > 4
* count _ zero _ bits ( 14 ) - > 17
* @ param number The upper limit of the range 1 to n ( inclusive ) in which the unset bits will be counted .
* @ return Returns the total count of unset bits from 1 to the given number . */
public static int countZeroBits ( int number ) { } } | int zeroBitCount = 0 ; for ( int i = 1 ; i <= number ; i ++ ) { int binaryRepresentation = i ; while ( binaryRepresentation != 0 ) { if ( ( binaryRepresentation % 2 ) == 0 ) { zeroBitCount ++ ; } binaryRepresentation = binaryRepresentation / 2 ; } } return zeroBitCount ; |
public class CmsContainerpageController { /** * Returns a map of the container drag targets . < p >
* @ return the drag targets */
public Map < String , org . opencms . ade . containerpage . client . ui . CmsContainerPageContainer > getContainerTargets ( ) { } } | Map < String , org . opencms . ade . containerpage . client . ui . CmsContainerPageContainer > result = new HashMap < String , org . opencms . ade . containerpage . client . ui . CmsContainerPageContainer > ( ) ; for ( Entry < String , org . opencms . ade . containerpage . client . ui . CmsContainerPageContainer > entry : m_targetContainers . entrySet ( ) ) { if ( entry . getValue ( ) . isEditable ( ) && ( ! isDetailPage ( ) || ( entry . getValue ( ) . isDetailOnly ( ) || entry . getValue ( ) . isDetailView ( ) ) ) ) { result . put ( entry . getKey ( ) , entry . getValue ( ) ) ; } } return result ; |
public class CollationElementIterator { /** * Set a new source string for iteration , and reset the offset
* to the beginning of the text .
* @ param source the new source string for iteration . */
public void setText ( String source ) { } } | string_ = source ; // TODO : do we need to remember the source string in a field ?
CollationIterator newIter ; boolean numeric = rbc_ . settings . readOnly ( ) . isNumeric ( ) ; if ( rbc_ . settings . readOnly ( ) . dontCheckFCD ( ) ) { newIter = new UTF16CollationIterator ( rbc_ . data , numeric , string_ , 0 ) ; } else { newIter = new FCDUTF16CollationIterator ( rbc_ . data , numeric , string_ , 0 ) ; } iter_ = newIter ; otherHalf_ = 0 ; dir_ = 0 ; |
public class FedoraRepositoryRestore { /** * This method runs a repository restore .
* @ param bodyStream the body stream
* @ return response
* @ throws IOException if IO exception occurred */
@ POST public Response runRestore ( final InputStream bodyStream ) throws IOException { } } | if ( null == bodyStream ) { throw new WebApplicationException ( serverError ( ) . entity ( "Request body must not be null" ) . build ( ) ) ; } final String body = IOUtils . toString ( bodyStream ) ; final File backupDirectory = new File ( body . trim ( ) ) ; if ( ! backupDirectory . exists ( ) ) { throw new WebApplicationException ( serverError ( ) . entity ( "Backup directory does not exist: " + backupDirectory . getAbsolutePath ( ) ) . build ( ) ) ; } final Collection < Throwable > problems = repositoryService . restoreRepository ( session . getFedoraSession ( ) , backupDirectory ) ; if ( ! problems . isEmpty ( ) ) { LOGGER . error ( "Problems restoring up the repository:" ) ; // Report the problems ( we ' ll just print them out ) . . .
final String problemsOutput = problems . stream ( ) . map ( Throwable :: getMessage ) . peek ( LOGGER :: error ) . collect ( joining ( "\n" ) ) ; throw new WebApplicationException ( serverError ( ) . entity ( problemsOutput ) . build ( ) ) ; } return noContent ( ) . header ( "Warning" , "This endpoint will be moving to an extension module in a future release of Fedora" ) . build ( ) ; |
public class AggregateFunctionRepository { /** * Associates an aggregate function ID with a { @ link VortexAggregateFunction } and a { @ link VortexAggregatePolicy } . */
public Tuple < VortexAggregateFunction , VortexAggregatePolicy > put ( final int aggregateFunctionId , final VortexAggregateFunction aggregateFunction , final VortexAggregatePolicy policy ) { } } | return aggregateFunctionMap . put ( aggregateFunctionId , new Tuple < > ( aggregateFunction , policy ) ) ; |
public class IPTC { /** * Reads the IPTC .
* @ param tv the TagValue containing the array of bytes of the IPTC */
public void read ( TagValue tv , String filename ) { } } | originalValue = tv . getValue ( ) ; File file = new File ( filename ) ; IIMReader reader = null ; SubIIMInputStream subStream = null ; try { int offset = tv . getReadOffset ( ) ; int length = tv . getReadlength ( ) ; subStream = new SubIIMInputStream ( new FileIIMInputStream ( file ) , offset , length ) ; reader = new IIMReader ( subStream , new IIMDataSetInfoFactory ( ) ) ; IIMFile iimFileReader = new IIMFile ( ) ; iimFileReader . readFrom ( reader , 0 ) ; List < DataSet > lds = new ArrayList < DataSet > ( ) ; for ( DataSet ds : iimFileReader . getDataSets ( ) ) { ds . getData ( ) ; lds . add ( ds ) ; } iimFile = new IIMFile ( ) ; iimFile . setDataSets ( lds ) ; tv . reset ( ) ; tv . add ( this ) ; reader . close ( ) ; subStream . close ( ) ; } catch ( IOException e ) { // e . printStackTrace ( ) ;
try { reader . close ( ) ; subStream . close ( ) ; } catch ( Exception ex ) { } } catch ( InvalidDataSetException e ) { // e . printStackTrace ( ) ;
try { reader . close ( ) ; subStream . close ( ) ; } catch ( Exception ex ) { } } |
public class IPDImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
@ Override public boolean eIsSet ( int featureID ) { } } | switch ( featureID ) { case AfplibPackage . IPD__IOC_ADAT : return IOC_ADAT_EDEFAULT == null ? iocAdat != null : ! IOC_ADAT_EDEFAULT . equals ( iocAdat ) ; case AfplibPackage . IPD__IMAGE_DATA : return IMAGE_DATA_EDEFAULT == null ? imageData != null : ! IMAGE_DATA_EDEFAULT . equals ( imageData ) ; } return super . eIsSet ( featureID ) ; |
public class DelegatedClientFactory { /** * Configure bitbucket client .
* @ param properties the properties */
protected void configureBitBucketClient ( final Collection < BaseClient > properties ) { } } | val bb = pac4jProperties . getBitbucket ( ) ; if ( StringUtils . isNotBlank ( bb . getId ( ) ) && StringUtils . isNotBlank ( bb . getSecret ( ) ) ) { val client = new BitbucketClient ( bb . getId ( ) , bb . getSecret ( ) ) ; configureClient ( client , bb ) ; LOGGER . debug ( "Created client [{}] with identifier [{}]" , client . getName ( ) , client . getKey ( ) ) ; properties . add ( client ) ; } |
public class PagingParams { /** * Creates a new PagingParams from a list of key - value pairs called tuples .
* @ param tuples a list of values where odd elements are keys and the following
* even elements are values
* @ return a newly created PagingParams . */
public static PagingParams fromTuples ( Object ... tuples ) { } } | AnyValueMap map = AnyValueMap . fromTuples ( tuples ) ; return PagingParams . fromMap ( map ) ; |
public class Ra10XmlGen { /** * write Connector Version
* @ param out output writer
* @ throws IOException io exception */
@ Override void writeConnectorVersion ( Writer out ) throws IOException { } } | out . write ( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" ) ; writeEol ( out ) ; writeEol ( out ) ; out . write ( "<!--" ) ; writeEol ( out ) ; writeHeader ( null , out ) ; out . write ( "-->" ) ; writeEol ( out ) ; writeEol ( out ) ; out . write ( "<!DOCTYPE connector PUBLIC" ) ; writeEol ( out ) ; out . write ( " \"-//Sun Microsystems, Inc.//DTD Connector 1.0//EN\"" ) ; writeEol ( out ) ; out . write ( " \"http://java.sun.com/dtd/connector_1_0.dtd\">" ) ; writeEol ( out ) ; writeEol ( out ) ; out . write ( "<connector>" ) ; writeEol ( out ) ; |
public class Util { /** * Get this image ' s full filename .
* @ param filename The filename of this image ( if no path , assumes images / buttons ; if not ext assumes . gif ) .
* @ param strSubDirectory The sub - directory .
* @ return The full ( relative ) filename for this image . */
public static String getImageFilename ( String strFilename , String strSubDirectory ) { } } | if ( ( strFilename == null ) || ( strFilename . length ( ) == 0 ) ) return null ; // A null will tell a JButton not to load an image
if ( strFilename . indexOf ( '.' ) == - 1 ) strFilename += ".gif" ; strFilename = Util . getFullFilename ( strFilename , strSubDirectory , Constant . IMAGE_LOCATION , true ) ; return strFilename ; |
public class DateTimeField { /** * This method gets called when a bound property is changed .
* This is required to listen to changes by the date popup control .
* @ param evt A PropertyChangeEvent object describing the event source and the property that has changed . */
public void propertyChange ( PropertyChangeEvent evt ) { } } | if ( MenuConstants . DATE . equalsIgnoreCase ( evt . getPropertyName ( ) ) ) if ( evt . getNewValue ( ) instanceof java . util . Date ) this . setDateTime ( ( java . util . Date ) evt . getNewValue ( ) , true , DBConstants . SCREEN_MOVE ) ; |
public class LogLinearXY { /** * Decodes a single example .
* @ param model The log - linear model .
* @ param ex The example to decode .
* @ return A pair containing the most likely label ( i . e . value of y ) and the
* distribution over y values . */
public Pair < String , VarTensor > decode ( FgModel model , LogLinearExample llex ) { } } | LFgExample ex = getFgExample ( llex ) ; MbrDecoderPrm prm = new MbrDecoderPrm ( ) ; prm . infFactory = getBpPrm ( ) ; MbrDecoder decoder = new MbrDecoder ( prm ) ; decoder . decode ( model , ex ) ; List < VarTensor > marginals = decoder . getVarMarginals ( ) ; VarConfig vc = decoder . getMbrVarConfig ( ) ; String stateName = vc . getStateName ( ex . getFactorGraph ( ) . getVar ( 0 ) ) ; if ( marginals . size ( ) != 1 ) { throw new IllegalStateException ( "Example is not from a LogLinearData factory" ) ; } return new Pair < String , VarTensor > ( stateName , marginals . get ( 0 ) ) ; |
public class DatabaseSession { /** * Free the objects .
* This method is called from the remote client , and frees this session . */
public void freeRemoteSession ( ) throws RemoteException { } } | try { if ( m_database . getTableCount ( ) == 0 ) m_database . free ( ) ; // Free if this is my private database , or there are no tables left
} catch ( Exception ex ) { ex . printStackTrace ( ) ; } super . freeRemoteSession ( ) ; |
public class MessageAPI { /** * 群发消息给用户 。
* 本方法调用需要账户为微信已认证账户
* @ param message 消息主体
* @ param isToAll 是否发送给全部用户 。 false时需要填写groupId , true时可忽略groupId树形
* @ param groupId 群组ID
* @ param openIds 群发用户
* @ return 群发结果
* @ deprecated 微信不再建议使用群组概念 , 用标签代替 */
@ Deprecated public GetSendMessageResponse sendMessageToUser ( BaseMsg message , boolean isToAll , String groupId , String [ ] openIds ) { } } | BeanUtil . requireNonNull ( message , "message is null" ) ; LOG . debug ( "群发消息......" ) ; String url = BASE_API_URL + "cgi-bin/message/mass/sendall?access_token=#" ; final Map < String , Object > params = new HashMap < String , Object > ( ) ; Map < String , Object > filterMap = new HashMap < String , Object > ( ) ; filterMap . put ( "is_to_all" , isToAll ) ; if ( ! isToAll ) { BeanUtil . requireNonNull ( groupId , "groupId is null" ) ; filterMap . put ( "group_id" , groupId ) ; } params . put ( "filter" , filterMap ) ; if ( message instanceof MpNewsMsg ) { params . put ( "msgtype" , "mpnews" ) ; MpNewsMsg msg = ( MpNewsMsg ) message ; Map < String , Object > mpNews = new HashMap < String , Object > ( ) ; mpNews . put ( "media_id" , msg . getMediaId ( ) ) ; params . put ( "mpnews" , mpNews ) ; } else if ( message instanceof TextMsg ) { params . put ( "msgtype" , "text" ) ; TextMsg msg = ( TextMsg ) message ; Map < String , Object > text = new HashMap < String , Object > ( ) ; text . put ( "content" , msg . getContent ( ) ) ; params . put ( "text" , text ) ; } else if ( message instanceof VoiceMsg ) { params . put ( "msgtype" , "voice" ) ; VoiceMsg msg = ( VoiceMsg ) message ; Map < String , Object > voice = new HashMap < String , Object > ( ) ; voice . put ( "media_id" , msg . getMediaId ( ) ) ; params . put ( "voice" , voice ) ; } else if ( message instanceof ImageMsg ) { params . put ( "msgtype" , "image" ) ; ImageMsg msg = ( ImageMsg ) message ; Map < String , Object > image = new HashMap < String , Object > ( ) ; image . put ( "media_id" , msg . getMediaId ( ) ) ; params . put ( "image" , image ) ; } else if ( message instanceof VideoMsg ) { // TODO 此处方法特别
} BaseResponse response = executePost ( url , JSONUtil . toJson ( params ) ) ; String resultJson = isSuccess ( response . getErrcode ( ) ) ? response . getErrmsg ( ) : response . toJsonString ( ) ; return JSONUtil . toBean ( resultJson , GetSendMessageResponse . class ) ; |
public class CalendarConverter { /** * Gets the chronology .
* If a chronology is specified then it is used .
* Otherwise , it is the GJChronology if a GregorianCalendar is used ,
* BuddhistChronology if a BuddhistCalendar is used or ISOChronology otherwise .
* The time zone is extracted from the calendar if possible , default used if not .
* @ param object the Calendar to convert , must not be null
* @ param chrono the chronology to use , null means use Calendar
* @ return the chronology , never null
* @ throws NullPointerException if the object is null
* @ throws ClassCastException if the object is an invalid type */
public Chronology getChronology ( Object object , Chronology chrono ) { } } | if ( chrono != null ) { return chrono ; } Calendar cal = ( Calendar ) object ; DateTimeZone zone = null ; try { zone = DateTimeZone . forTimeZone ( cal . getTimeZone ( ) ) ; } catch ( IllegalArgumentException ex ) { zone = DateTimeZone . getDefault ( ) ; } return getChronology ( cal , zone ) ; |
public class Util { /** * Closes { @ code socket } , ignoring any checked exceptions . Does nothing if { @ code socket } is
* null . */
public static void closeQuietly ( Socket socket ) { } } | if ( socket != null ) { try { socket . close ( ) ; } catch ( AssertionError e ) { if ( ! isAndroidGetsocknameError ( e ) ) throw e ; } catch ( RuntimeException rethrown ) { throw rethrown ; } catch ( Exception ignored ) { } } |
public class VirtualHost { /** * IDNA ASCII conversion , case normalization and validation . */
static String normalizeDefaultHostname ( String defaultHostname ) { } } | requireNonNull ( defaultHostname , "defaultHostname" ) ; if ( needsNormalization ( defaultHostname ) ) { defaultHostname = IDN . toASCII ( defaultHostname , IDN . ALLOW_UNASSIGNED ) ; } if ( ! HOSTNAME_PATTERN . matcher ( defaultHostname ) . matches ( ) ) { throw new IllegalArgumentException ( "defaultHostname: " + defaultHostname ) ; } return Ascii . toLowerCase ( defaultHostname ) ; |
public class TokenMatcher { /** * Group list .
* @ param groupName the group name
* @ return the list */
public List < HString > group ( String groupName ) { } } | return Collections . unmodifiableList ( match . getCaptures ( ) . get ( groupName ) ) ; |
public class ProcessStarter { /** * Includes the given System Property as part of the start .
* @ param name The System Property Name .
* @ param value The System Property Value . This will have toString ( ) invoked on it .
* @ return This object instance . */
public ProcessStarter sysProp ( String name , Object value ) { } } | this . systemProps . put ( name , value . toString ( ) ) ; return this ; |
public class GraphHopperStorage { /** * parses a string like [ a , b , c ] */
private List < String > parseList ( String listStr ) { } } | String trimmed = listStr . trim ( ) ; String [ ] items = trimmed . substring ( 1 , trimmed . length ( ) - 1 ) . split ( "," ) ; List < String > result = new ArrayList < > ( ) ; for ( String item : items ) { String s = item . trim ( ) ; if ( ! s . isEmpty ( ) ) { result . add ( s ) ; } } return result ; |
public class JobInProgress { /** * returns the ( cache ) level at which the nodes matches */
private int getMatchingLevelForNodes ( Node n1 , Node n2 ) { } } | int count = 0 ; do { if ( n1 . equals ( n2 ) ) { return count ; } ++ count ; n1 = n1 . getParent ( ) ; n2 = n2 . getParent ( ) ; } while ( n1 != null && n2 != null ) ; return this . maxLevel ; |
public class ExceptionUtils { /** * < p > Removes common frames from the cause trace given the two stack traces . < / p >
* @ param causeFrames stack trace of a cause throwable
* @ param wrapperFrames stack trace of a wrapper throwable
* @ throws IllegalArgumentException if either argument is null
* @ since 2.0 */
public static void removeCommonFrames ( final List < String > causeFrames , final List < String > wrapperFrames ) { } } | if ( causeFrames == null || wrapperFrames == null ) { throw new IllegalArgumentException ( "The List must not be null" ) ; } int causeFrameIndex = causeFrames . size ( ) - 1 ; int wrapperFrameIndex = wrapperFrames . size ( ) - 1 ; while ( causeFrameIndex >= 0 && wrapperFrameIndex >= 0 ) { // Remove the frame from the cause trace if it is the same
// as in the wrapper trace
final String causeFrame = causeFrames . get ( causeFrameIndex ) ; final String wrapperFrame = wrapperFrames . get ( wrapperFrameIndex ) ; if ( causeFrame . equals ( wrapperFrame ) ) { causeFrames . remove ( causeFrameIndex ) ; } causeFrameIndex -- ; wrapperFrameIndex -- ; } |
public class SARLDescriptionLabelProvider { /** * Replies the image for an attribute .
* @ param attribute describes the attribute .
* @ return the image descriptor . */
public ImageDescriptor image ( SarlField attribute ) { } } | return this . images . forField ( attribute . getVisibility ( ) , this . adornments . get ( this . jvmModelAssociations . getJvmField ( attribute ) ) ) ; |
public class MappedJournalSegmentReader { /** * Reads the next entry in the segment . */
@ SuppressWarnings ( "unchecked" ) private void readNext ( ) { } } | // Compute the index of the next entry in the segment .
final long index = getNextIndex ( ) ; // Mark the buffer so it can be reset if necessary .
buffer . mark ( ) ; try { // Read the length of the entry .
final int length = buffer . getInt ( ) ; // If the buffer length is zero then return .
if ( length <= 0 || length > maxEntrySize ) { buffer . reset ( ) ; nextEntry = null ; return ; } // Read the checksum of the entry .
long checksum = buffer . getInt ( ) & 0xFFFFFFFFL ; // Compute the checksum for the entry bytes .
final CRC32 crc32 = new CRC32 ( ) ; ByteBuffer slice = buffer . slice ( ) ; slice . limit ( length ) ; crc32 . update ( slice ) ; // If the stored checksum equals the computed checksum , return the entry .
if ( checksum == crc32 . getValue ( ) ) { slice . rewind ( ) ; E entry = namespace . deserialize ( slice ) ; nextEntry = new Indexed < > ( index , entry , length ) ; buffer . position ( buffer . position ( ) + length ) ; } else { buffer . reset ( ) ; nextEntry = null ; } } catch ( BufferUnderflowException e ) { buffer . reset ( ) ; nextEntry = null ; } |
public class TileSet { /** * Returns a prepared version of the image that would be used by the tile at the specified
* index . Because tilesets are often used simply to provide access to a collection of uniform
* images , this method is provided to bypass the creation of a { @ link Tile } object when all
* that is desired is access to the underlying image . */
public Mirage getTileMirage ( int tileIndex , Colorization [ ] zations ) { } } | Rectangle bounds = computeTileBounds ( tileIndex , new Rectangle ( ) ) ; Mirage mirage = null ; if ( checkTileIndex ( tileIndex ) ) { if ( _improv == null ) { log . warning ( "Aiya! Tile set missing image provider" , "path" , _imagePath ) ; } else { mirage = _improv . getTileImage ( _imagePath , bounds , zations ) ; } } if ( mirage == null ) { mirage = new BufferedMirage ( ImageUtil . createErrorImage ( bounds . width , bounds . height ) ) ; } return mirage ; |
public class AttributeService { /** * Get the attributes for a feature , and put them in the feature object .
* The attributes are converted lazily if requested by the layer .
* The feature is filled into the passed feature object . If the feature should not be visible according to security ,
* null is returned ( the original ( passed ) feature should be discarded in that case ) . The attributes are filtered
* according to security settings . The editable and deletable states for the feature are also set .
* @ param layer layer which contains the feature
* @ param feature feature for the result
* @ param featureBean plain object for feature
* @ return feature with filled attributes or null when feature not visible
* @ throws LayerException problem converting attributes */
public InternalFeature getAttributes ( VectorLayer layer , InternalFeature feature , Object featureBean ) throws LayerException { } } | String layerId = layer . getId ( ) ; Map < String , Attribute > featureAttributes = getRealAttributes ( layer , featureBean ) ; feature . setAttributes ( featureAttributes ) ; // to allow isAttributeReadable to see full object
addSyntheticAttributes ( feature , featureAttributes , layer ) ; if ( securityContext . isFeatureVisible ( layerId , feature ) ) { feature . setAttributes ( filterAttributes ( layerId , layer . getLayerInfo ( ) . getFeatureInfo ( ) . getAttributesMap ( ) , feature , featureAttributes ) ) ; feature . setEditable ( securityContext . isFeatureUpdateAuthorized ( layerId , feature ) ) ; feature . setDeletable ( securityContext . isFeatureDeleteAuthorized ( layerId , feature ) ) ; return feature ; } return null ; |
public class KeyStoreUtil { /** * Gets an array of trust managers for a given store + password .
* @ param pathInfo
* @ return
* @ throws Exception */
public static TrustManager [ ] getTrustManagers ( Info pathInfo ) throws Exception { } } | File trustStoreFile = new File ( pathInfo . store ) ; if ( ! trustStoreFile . isFile ( ) ) { throw new Exception ( "No TrustManager: " + pathInfo . store + " does not exist." ) ; } String trustStorePassword = pathInfo . password ; TrustManagerFactory tmf = TrustManagerFactory . getInstance ( TrustManagerFactory . getDefaultAlgorithm ( ) ) ; KeyStore truststore = KeyStore . getInstance ( "JKS" ) ; FileInputStream fis = new FileInputStream ( pathInfo . store ) ; truststore . load ( fis , trustStorePassword . toCharArray ( ) ) ; fis . close ( ) ; tmf . init ( truststore ) ; return tmf . getTrustManagers ( ) ; |
public class IntStreamEx { /** * Returns a stream consisting of all elements from this stream until the
* first element which does not match the given predicate is found
* ( including the first mismatching element ) .
* This is a < a href = " package - summary . html # StreamOps " > quasi - intermediate
* operation < / a > .
* While this operation is quite cheap for sequential stream , it can be
* quite expensive on parallel pipelines .
* @ param predicate a non - interfering , stateless predicate to apply to
* elements .
* @ return the new stream .
* @ since 0.5.5
* @ see # takeWhile ( IntPredicate ) */
public IntStreamEx takeWhileInclusive ( IntPredicate predicate ) { } } | Objects . requireNonNull ( predicate ) ; return delegate ( new TakeDrop . TDOfInt ( spliterator ( ) , false , true , predicate ) ) ; |
public class Node { /** * The user subscribes to the node using the supplied jid . The
* bare jid portion of this one must match the jid for the connection .
* Please note that the { @ link Subscription . State } should be checked
* on return since more actions may be required by the caller .
* { @ link Subscription . State # pending } - The owner must approve the subscription
* request before messages will be received .
* { @ link Subscription . State # unconfigured } - If the { @ link Subscription # isConfigRequired ( ) } is true ,
* the caller must configure the subscription before messages will be received . If it is false
* the caller can configure it but is not required to do so .
* @ param jid The jid to subscribe as .
* @ return The subscription
* @ throws XMPPErrorException
* @ throws NoResponseException
* @ throws NotConnectedException
* @ throws InterruptedException */
public Subscription subscribe ( String jid ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { } } | PubSub pubSub = createPubsubPacket ( Type . set , new SubscribeExtension ( jid , getId ( ) ) ) ; PubSub reply = sendPubsubPacket ( pubSub ) ; return reply . getExtension ( PubSubElementType . SUBSCRIPTION ) ; |
public class CassandraDataHandlerBase { /** * From thrift row .
* @ param < E >
* the element type
* @ param clazz
* the clazz
* @ param m
* the m
* @ param tr
* the cr
* @ return the e
* @ throws Exception
* the exception */
public < E > E fromThriftRow ( Class < E > clazz , EntityMetadata m , DataRow < SuperColumn > tr ) throws Exception { } } | // Instantiate a new instance
E e = null ; // Set row - key . Note :
// Get a name - > field map for super - columns
Map < String , Field > columnNameToFieldMap = new HashMap < String , Field > ( ) ; Map < String , Field > superColumnNameToFieldMap = new HashMap < String , Field > ( ) ; MetadataUtils . populateColumnAndSuperColumnMaps ( m , columnNameToFieldMap , superColumnNameToFieldMap , kunderaMetadata ) ; Collection embeddedCollection = null ; Field embeddedCollectionField = null ; for ( SuperColumn sc : tr . getColumns ( ) ) { if ( e == null ) { // Instantiate a new instance
e = clazz . newInstance ( ) ; // Set row - key .
PropertyAccessorHelper . setId ( e , m , tr . getId ( ) ) ; } String scName = PropertyAccessorFactory . STRING . fromBytes ( String . class , sc . getName ( ) ) ; String scNamePrefix = null ; if ( scName . indexOf ( Constants . EMBEDDED_COLUMN_NAME_DELIMITER ) != - 1 ) { scNamePrefix = MetadataUtils . getEmbeddedCollectionPrefix ( scName ) ; embeddedCollectionField = superColumnNameToFieldMap . get ( scNamePrefix ) ; embeddedCollection = MetadataUtils . getEmbeddedCollectionInstance ( embeddedCollectionField ) ; Object embeddedObject = populateEmbeddedObject ( sc , m ) ; embeddedCollection . add ( embeddedObject ) ; PropertyAccessorHelper . set ( e , embeddedCollectionField , embeddedCollection ) ; } else { boolean intoRelations = false ; if ( scName . equals ( Constants . FOREIGN_KEY_EMBEDDED_COLUMN_NAME ) ) { intoRelations = true ; } for ( Column column : sc . getColumns ( ) ) { if ( column != null ) { String name = PropertyAccessorFactory . STRING . fromBytes ( String . class , column . getName ( ) ) ; byte [ ] value = column . getValue ( ) ; if ( value == null ) { continue ; } if ( intoRelations ) { String foreignKeys = PropertyAccessorFactory . STRING . fromBytes ( String . class , value ) ; Set < String > keys = MetadataUtils . deserializeKeys ( foreignKeys ) ; } else { // set value of the field in the bean
Field field = columnNameToFieldMap . get ( name ) ; Object embeddedObject = PropertyAccessorHelper . getObject ( e , scName ) ; PropertyAccessorHelper . set ( embeddedObject , field , value ) ; } } } } } if ( log . isInfoEnabled ( ) ) { log . info ( "Returning entity {} for class {}" , e , clazz ) ; } return e ; |
public class JKHttpUtil { /** * Download file to temp .
* @ param fileUrl the file url
* @ param ext the ext
* @ return the file
* @ throws IOException Signals that an I / O exception has occurred . */
public static File downloadFileToTemp ( final String fileUrl , final String ext ) throws IOException { } } | final File file = File . createTempFile ( "jk-" , ext ) ; JKHttpUtil . downloadFile ( fileUrl , file . getAbsolutePath ( ) ) ; return file ; |
public class RaftContext { /** * Unregisters server handlers on the configured protocol . */
private void unregisterHandlers ( RaftServerProtocol protocol ) { } } | protocol . unregisterOpenSessionHandler ( ) ; protocol . unregisterCloseSessionHandler ( ) ; protocol . unregisterKeepAliveHandler ( ) ; protocol . unregisterMetadataHandler ( ) ; protocol . unregisterConfigureHandler ( ) ; protocol . unregisterInstallHandler ( ) ; protocol . unregisterJoinHandler ( ) ; protocol . unregisterReconfigureHandler ( ) ; protocol . unregisterLeaveHandler ( ) ; protocol . unregisterTransferHandler ( ) ; protocol . unregisterAppendHandler ( ) ; protocol . unregisterPollHandler ( ) ; protocol . unregisterVoteHandler ( ) ; protocol . unregisterCommandHandler ( ) ; protocol . unregisterQueryHandler ( ) ; |
public class DeleteDomainNameRequestMarshaller { /** * Marshall the given parameter object . */
public void marshall ( DeleteDomainNameRequest deleteDomainNameRequest , ProtocolMarshaller protocolMarshaller ) { } } | if ( deleteDomainNameRequest == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( deleteDomainNameRequest . getDomainName ( ) , DOMAINNAME_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class UrlSyntaxProviderImpl { /** * Tries to determine the encoded from the request , if not available falls back to configured
* default .
* @ param request The current request .
* @ return The encoding to use . */
protected String getEncoding ( HttpServletRequest request ) { } } | final String encoding = request . getCharacterEncoding ( ) ; if ( encoding != null ) { return encoding ; } return this . defaultEncoding ; |
public class StringUtils { /** * Parse the given { @ code localeString } value into a { @ link Locale } .
* < p > This is the inverse operation of { @ link Locale # toString Locale ' s toString } .
* @ param localeString the locale { @ code String } , following { @ code Locale ' s }
* { @ code toString ( ) } format ( " en " , " en _ UK " , etc ) ;
* also accepts spaces as separators , as an alternative to underscores
* @ return a corresponding { @ code Locale } instance
* @ throws IllegalArgumentException in case of an invalid locale specification */
public static Locale parseLocaleString ( String localeString ) { } } | String [ ] parts = tokenize ( localeString , "_ " , false ) ; String language = ( parts . length > 0 ? parts [ 0 ] : EMPTY ) ; String country = ( parts . length > 1 ? parts [ 1 ] : EMPTY ) ; validateLocalePart ( language ) ; validateLocalePart ( country ) ; String variant = EMPTY ; if ( parts . length > 2 ) { // There is definitely a variant , and it is everything after the country
// code sans the separator between the country code and the variant .
int endIndexOfCountryCode = localeString . indexOf ( country , language . length ( ) ) + country . length ( ) ; // Strip off any leading ' _ ' and whitespace , what ' s left is the variant .
variant = trimLeadingWhitespace ( localeString . substring ( endIndexOfCountryCode ) ) ; if ( variant . startsWith ( "_" ) ) { variant = trimLeadingCharacter ( variant , '_' ) ; } } return ( language . length ( ) > 0 ? new Locale ( language , country , variant ) : null ) ; |
public class CommerceCountryPersistenceImpl { /** * Removes all the commerce countries where groupId = & # 63 ; and billingAllowed = & # 63 ; and active = & # 63 ; from the database .
* @ param groupId the group ID
* @ param billingAllowed the billing allowed
* @ param active the active */
@ Override public void removeByG_B_A ( long groupId , boolean billingAllowed , boolean active ) { } } | for ( CommerceCountry commerceCountry : findByG_B_A ( groupId , billingAllowed , active , QueryUtil . ALL_POS , QueryUtil . ALL_POS , null ) ) { remove ( commerceCountry ) ; } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.