signature stringlengths 43 39.1k | implementation stringlengths 0 450k |
|---|---|
public class AIStream { /** * Turn a Q / G to V / U . Associate with the V / U tick the in - memory reference to the message and whether the message
* was delivered .
* @ return The Q / G tick , from which the consumer key and time issued can be obtained */
public AIRequestedTick updateRequestToValue ( long tick , AIMessageItem msgItem , boolean valueDelivered , SendDispatcher sendDispatcher ) { } } | if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . entry ( tc , "updateRequestToValue" , new Object [ ] { Long . valueOf ( tick ) , msgItem , Boolean . valueOf ( valueDelivered ) } ) ; AIRequestedTick rt = null ; _targetStream . setCursor ( tick ) ; TickRange tickRange = _targetStream . getNext ( ) ; if ( tickRange . type == TickRange . Requested ) { rt = ( AIRequestedTick ) tickRange . value ; RemoteDispatchableKey ck = rt . getRemoteDispatchableKey ( ) ; // The tick keeps the in - memory Java reference of the message object if valueDelivered = false ,
// the constructor takes the reference to extract reliability and priority
// Re - enter the ck as part of the V / U ' s state , just in case ordered
// delivery applies to consumer cardinality other than one
AIValueTick valueTick = new AIValueTick ( tick , msgItem , valueDelivered , ck , rt . getOriginalTimeout ( ) , rt . getIssueTime ( ) , msgItem . getMessage ( ) . getRedeliveredCount ( ) . intValue ( ) ) ; TickRange valueRange = new TickRange ( TickRange . Value , tick , tick ) ; valueRange . value = valueTick ; valueRange . valuestamp = tick ; _targetStream . writeRange ( valueRange ) ; if ( rt . getTimeout ( ) > 0L || rt . getTimeout ( ) == _mp . getCustomProperties ( ) . get_infinite_timeout ( ) ) { if ( rt . isSlowed ( ) ) { _slowedGetTOM . removeTimeoutEntry ( rt ) ; } else { _eagerGetTOM . removeTimeoutEntry ( rt ) ; } } } else if ( tickRange . type == TickRange . Accepted ) { sendDispatcher . sendAccept ( tick ) ; } else if ( tickRange . type == TickRange . Rejected ) { AIRejectedRange rr = ( AIRejectedRange ) tickRange . value ; sendDispatcher . sendReject ( tick , tick , rr . unlockCount , rr . recovery ) ; } else if ( tickRange . type == TickRange . Completed ) { sendDispatcher . sendCompleted ( tick , tick ) ; } if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . exit ( tc , "updateRequestToValue" , rt ) ; return rt ; |
public class ListDeliveryStreamsResult { /** * The names of the delivery streams .
* @ param deliveryStreamNames
* The names of the delivery streams . */
public void setDeliveryStreamNames ( java . util . Collection < String > deliveryStreamNames ) { } } | if ( deliveryStreamNames == null ) { this . deliveryStreamNames = null ; return ; } this . deliveryStreamNames = new java . util . ArrayList < String > ( deliveryStreamNames ) ; |
public class CommentsForComparedCommitMarshaller { /** * Marshall the given parameter object . */
public void marshall ( CommentsForComparedCommit commentsForComparedCommit , ProtocolMarshaller protocolMarshaller ) { } } | if ( commentsForComparedCommit == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( commentsForComparedCommit . getRepositoryName ( ) , REPOSITORYNAME_BINDING ) ; protocolMarshaller . marshall ( commentsForComparedCommit . getBeforeCommitId ( ) , BEFORECOMMITID_BINDING ) ; protocolMarshaller . marshall ( commentsForComparedCommit . getAfterCommitId ( ) , AFTERCOMMITID_BINDING ) ; protocolMarshaller . marshall ( commentsForComparedCommit . getBeforeBlobId ( ) , BEFOREBLOBID_BINDING ) ; protocolMarshaller . marshall ( commentsForComparedCommit . getAfterBlobId ( ) , AFTERBLOBID_BINDING ) ; protocolMarshaller . marshall ( commentsForComparedCommit . getLocation ( ) , LOCATION_BINDING ) ; protocolMarshaller . marshall ( commentsForComparedCommit . getComments ( ) , COMMENTS_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class DefaultGroovyMethods { /** * Support the subscript operator with a range for a double array
* @ param array a double array
* @ param range a range indicating the indices for the items to retrieve
* @ return list of the retrieved doubles
* @ since 1.0 */
@ SuppressWarnings ( "unchecked" ) public static List < Double > getAt ( double [ ] array , Range range ) { } } | return primitiveArrayGet ( array , range ) ; |
public class UUIDConverter { /** * { @ inheritDoc } */
public Object convert ( String value , TypeLiteral < ? > toType ) { } } | try { return UUID . fromString ( value ) ; } catch ( Throwable t ) { throw new ProvisionException ( "String value '" + value + "' is not a valid UUID" , t ) ; } |
public class QueueContainer { /** * Commits the effects of the { @ link # txnPollReserve ( long , String ) } } . Also deletes the item data from the queue
* data store if it is configured and enabled .
* @ param itemId the ID of the item which was polled inside a transaction
* @ return the data of the polled item
* @ throws HazelcastException if there was any exception while removing the item from the queue data store */
public Data txnCommitPollBackup ( long itemId ) { } } | TxQueueItem item = txMap . remove ( itemId ) ; if ( item == null ) { logger . warning ( "txnCommitPoll operation-> No txn item for itemId: " + itemId ) ; return null ; } if ( store . isEnabled ( ) ) { try { store . delete ( item . getItemId ( ) ) ; } catch ( Exception e ) { logger . severe ( "Error during store delete: " + item . getItemId ( ) , e ) ; } } return item . getData ( ) ; |
public class SecretDetector { /** * Masks given text between begin position and end position .
* @ param text text to mask
* @ param begPos begin position ( inclusive )
* @ param endPos end position ( exclusive )
* @ return masked text */
private static String maskText ( String text , int begPos , int endPos ) { } } | // Convert the SQL statement to a char array to obe able to modify it .
char [ ] chars = text . toCharArray ( ) ; // Mask the value in the SQL statement using * .
for ( int curPos = begPos ; curPos < endPos ; curPos ++ ) { chars [ curPos ] = '☺' ; } // Convert it back to a string
return String . valueOf ( chars ) ; |
public class JmsMsgConsumerImpl { /** * This method is used to remove an existing asynchronous consumer
* from the core consumer object , and reset the JMS consumer back to
* sychronous receipt mode .
* 13/01/04 Modified so that it can be called repeatedly , and restores
* the started state of the core consumer session after running . */
private void removeAsyncListener ( ) throws JMSException { } } | if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . entry ( this , tc , "removeAsyncListener" ) ; // if the consumer is null , there is nothing to do
if ( consumer != null ) { try { // stop the coreConsumerSession
coreConsumerSession . stop ( ) ; // remove the callback
coreConsumerSession . deregisterAsynchConsumerCallback ( ) ; // restart the coreConsumerSession if necessary
if ( session . getState ( ) == STARTED ) { // Do not deliver message immediately on start .
coreConsumerSession . start ( false ) ; } // null out our consumer instance
consumer = null ; } catch ( SIIncorrectCallException sice ) { // No FFDC code needed
// stop / start methods ok for default message . deregisterAsynchConsumerCallback can throw
// an SIIincorrectCallException is session is not stopped , but this shouldn ' t be possible
// with the code above .
// d238447 FFDC review . See comment in next catch block . Generate FFDC .
throw ( JMSException ) JmsErrorUtils . newThrowable ( JMSException . class , "EXCEPTION_RECEIVED_CWSIA0085" , new Object [ ] { sice , "JmsMsgConsumerImpl.removeAsyncListener" } , sice , "JmsMsgConsumerImpl.removeASyncListener#1" , this , tc ) ; } catch ( SIException sice ) { // No FFDC code needed
// stop / start methods ok for default message . deregisterAsynchConsumerCallback can throw
// an SIIincorrectCallException is session is not stopped , but this shouldn ' t be possible
// with the code above .
// d238447 FFDC review . We are dealing with :
// SISessionUnavailableException , SISessionDroppedException ,
// SIConnectionUnavailableException , SIConnectionDroppedException ,
// SIResourceException , SIConnectionLostException ;
// SIIncorrectCallException
// Of these SIIncorrectCallE is probably the only one that warrents FFDC at this level ,
// so a new catch block for IncorrectCallE added above , no FFDCs here .
throw ( JMSException ) JmsErrorUtils . newThrowable ( JMSException . class , "EXCEPTION_RECEIVED_CWSIA0085" , new Object [ ] { sice , "JmsMsgConsumerImpl.removeAsyncListener" } , sice , null , // null probeId = no FFDC .
this , tc ) ; } } if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . exit ( this , tc , "removeAsyncListener" ) ; |
public class GHUtility { /** * Creates unique positive number for specified edgeId taking into account the direction defined
* by nodeA , nodeB and reverse . */
public static int createEdgeKey ( int nodeA , int nodeB , int edgeId , boolean reverse ) { } } | edgeId = edgeId << 1 ; if ( reverse ) return ( nodeA > nodeB ) ? edgeId : edgeId + 1 ; return ( nodeA > nodeB ) ? edgeId + 1 : edgeId ; |
public class BeanMappingConfigHelper { /** * 单例方法 */
public static BeanMappingConfigHelper getInstance ( ) { } } | if ( singleton == null ) { synchronized ( BeanMappingConfigHelper . class ) { if ( singleton == null ) { // double check
singleton = new BeanMappingConfigHelper ( ) ; } } } return singleton ; |
public class PageSectionStyle { /** * Append a footer / header to styles . xml / automatic - styles
* @ param util an util
* @ param appendable the destination
* @ param pageSectionType the type if pageSectionStyle is null .
* @ throws IOException if an I / O error occurs */
public void appendFooterHeaderStyleXMLToAutomaticStyle ( final XMLUtil util , final Appendable appendable , final Type pageSectionType ) throws IOException { } } | appendable . append ( "<style:" ) . append ( pageSectionType . getTypeName ( ) ) . append ( "-style>" ) ; appendable . append ( "<style:header-footer-properties" ) ; util . appendAttribute ( appendable , "fo:min-height" , this . minHeight . toString ( ) ) ; this . margins . appendXMLContent ( util , appendable ) ; appendable . append ( "/></style:" ) . append ( pageSectionType . getTypeName ( ) ) . append ( "-style>" ) ; |
public class DynamicDomainObjectMerger { /** * Merges the given target object into the source one .
* @ param from can be { @ literal null } .
* @ param target can be { @ literal null } .
* @ param nullPolicy how to handle { @ literal null } values in the source object . */
@ Override public void merge ( final Object from , final Object target , final NullHandlingPolicy nullPolicy ) { } } | if ( from == null || target == null ) { return ; } final BeanWrapper fromWrapper = beanWrapper ( from ) ; final BeanWrapper targetWrapper = beanWrapper ( target ) ; final DomainTypeAdministrationConfiguration domainTypeAdministrationConfiguration = configuration . forManagedDomainType ( target . getClass ( ) ) ; final PersistentEntity < ? , ? > entity = domainTypeAdministrationConfiguration . getPersistentEntity ( ) ; entity . doWithProperties ( new SimplePropertyHandler ( ) { @ Override public void doWithPersistentProperty ( PersistentProperty < ? > persistentProperty ) { Object sourceValue = fromWrapper . getPropertyValue ( persistentProperty . getName ( ) ) ; Object targetValue = targetWrapper . getPropertyValue ( persistentProperty . getName ( ) ) ; if ( entity . isIdProperty ( persistentProperty ) ) { return ; } if ( nullSafeEquals ( sourceValue , targetValue ) ) { return ; } if ( propertyIsHiddenInFormView ( persistentProperty , domainTypeAdministrationConfiguration ) ) { return ; } if ( nullPolicy == APPLY_NULLS || sourceValue != null ) { targetWrapper . setPropertyValue ( persistentProperty . getName ( ) , sourceValue ) ; } } } ) ; entity . doWithAssociations ( new SimpleAssociationHandler ( ) { @ Override @ SuppressWarnings ( "unchecked" ) public void doWithAssociation ( Association < ? extends PersistentProperty < ? > > association ) { PersistentProperty < ? > persistentProperty = association . getInverse ( ) ; Object fromValue = fromWrapper . getPropertyValue ( persistentProperty . getName ( ) ) ; Object targetValue = targetWrapper . getPropertyValue ( persistentProperty . getName ( ) ) ; if ( propertyIsHiddenInFormView ( persistentProperty , domainTypeAdministrationConfiguration ) ) { return ; } if ( ( fromValue == null && nullPolicy == APPLY_NULLS ) ) { targetWrapper . setPropertyValue ( persistentProperty . getName ( ) , fromValue ) ; } if ( persistentProperty . isCollectionLike ( ) ) { Collection < Object > sourceCollection = ( Collection ) fromValue ; Collection < Object > targetCollection = ( Collection ) targetValue ; Collection < Object > candidatesForAddition = candidatesForAddition ( sourceCollection , targetCollection , persistentProperty ) ; Collection < Object > candidatesForRemoval = candidatesForRemoval ( sourceCollection , targetCollection , persistentProperty ) ; removeReferencedItems ( targetCollection , candidatesForRemoval ) ; addReferencedItems ( targetCollection , candidatesForAddition ) ; return ; } if ( ! nullSafeEquals ( fromValue , targetWrapper . getPropertyValue ( persistentProperty . getName ( ) ) ) ) { targetWrapper . setPropertyValue ( persistentProperty . getName ( ) , fromValue ) ; } } } ) ; |
public class PaperSize { /** * Sees if the specified work matches any of the units full name or short name . */
public static PaperSize lookup ( String word ) { } } | for ( PaperSize paper : values ) { if ( paper . name . compareToIgnoreCase ( word ) == 0 ) { return paper ; } } return null ; |
public class AlwaysAllowReadPermissionEvaluator { /** * Grants READ permission on the user object of the currently logged in
* user . Uses default implementation otherwise . */
@ Override public boolean hasPermission ( User user , E entity , Permission permission ) { } } | // always grant READ access ( " unsecured " object )
if ( permission . equals ( Permission . READ ) ) { LOG . trace ( "Granting READ access on " + entity . getClass ( ) . getSimpleName ( ) + " with ID " + entity . getId ( ) ) ; return true ; } // call parent implementation
return super . hasPermission ( user , entity , permission ) ; |
public class S3TaskClientImpl { /** * { @ inheritDoc } */
@ Override public EnableStreamingTaskResult enableStreaming ( String spaceId , boolean secure ) throws ContentStoreException { } } | EnableStreamingTaskParameters taskParams = new EnableStreamingTaskParameters ( ) ; taskParams . setSpaceId ( spaceId ) ; taskParams . setSecure ( secure ) ; return EnableStreamingTaskResult . deserialize ( contentStore . performTask ( StorageTaskConstants . ENABLE_STREAMING_TASK_NAME , taskParams . serialize ( ) ) ) ; |
public class VnSyllParser { /** * Parses the secondary vowel . */
private void parseSecondaryVowel ( ) { } } | if ( ! validViSyll ) return ; // get the current and next character in the syllable string
char curChar , nextChar ; if ( iCurPos > strSyllable . length ( ) - 1 ) { validViSyll = false ; return ; } curChar = strSyllable . charAt ( iCurPos ) ; if ( iCurPos == strSyllable . length ( ) - 1 ) nextChar = '$' ; else nextChar = strSyllable . charAt ( iCurPos + 1 ) ; // get the tone and the original vowel ( without tone )
TONE tone = TONE . NO_TONE ; int idx1 = vnVowels . indexOf ( curChar ) ; int idx2 = vnVowels . indexOf ( nextChar ) ; if ( idx1 == - 1 ) return ; // current char is not a vowel
tone = TONE . getTone ( idx1 % 6 ) ; curChar = vnVowels . charAt ( ( idx1 / 6 ) * 6 ) ; if ( idx2 == - 1 ) { // next char is not a vowel
strSecondaryVowel = ZERO ; return ; } nextChar = vnVowels . charAt ( ( idx2 / 6 ) * 6 ) ; if ( tone . getValue ( ) == TONE . NO_TONE . getValue ( ) ) tone = TONE . getTone ( idx2 % 6 ) ; // Check the secondary vowel
if ( curChar == 'o' ) { if ( nextChar == 'a' || nextChar == 'e' ) { strSecondaryVowel += curChar ; iCurPos ++ ; } else strSecondaryVowel = ZERO ; // oo
return ; } else if ( curChar == 'u' ) { if ( nextChar != 'i' && nextChar != '$' ) { strSecondaryVowel += curChar ; iCurPos ++ ; } else strSecondaryVowel = ZERO ; return ; } |
public class ResultSetIterator { /** * Check for a subsequent item in the ResultSet .
* @ return < code > true < / code > if there is another element ; < code > false < / code > otherwise
* @ throws IllegalStateException when a { @ link SQLException } occurs advancing the ResultSet */
public boolean hasNext ( ) { } } | if ( _rs == null ) return false ; if ( _primed ) return true ; try { _primed = _rs . next ( ) ; return _primed ; } catch ( SQLException sql ) { String msg = "An exception occurred reading from the Iterator. Cause: " + sql ; LOGGER . error ( msg , sql ) ; throw new IllegalStateException ( msg , sql ) ; } |
public class RealWebSocket { /** * For testing : receive a single frame and return true if there are more frames to read . Invoked
* only by the reader thread . */
boolean processNextFrame ( ) throws IOException { } } | try { reader . processNextFrame ( ) ; return receivedCloseCode == - 1 ; } catch ( Exception e ) { failWebSocket ( e , null ) ; return false ; } |
public class Maybe { /** * Calls the shared consumer with the success value sent via onSuccess for each
* MaybeObserver that subscribes to the current Maybe .
* < img width = " 640 " height = " 358 " src = " https : / / raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / doOnSuccess . m . png " alt = " " >
* < dl >
* < dt > < b > Scheduler : < / b > < / dt >
* < dd > { @ code doOnSuccess } does not operate by default on a particular { @ link Scheduler } . < / dd >
* < / dl >
* @ param onSuccess the consumer called with the success value of onSuccess
* @ return the new Maybe instance */
@ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Maybe < T > doOnSuccess ( Consumer < ? super T > onSuccess ) { } } | return RxJavaPlugins . onAssembly ( new MaybePeek < T > ( this , Functions . emptyConsumer ( ) , // onSubscribe
ObjectHelper . requireNonNull ( onSuccess , "onSubscribe is null" ) , Functions . emptyConsumer ( ) , // onError
Functions . EMPTY_ACTION , // onComplete
Functions . EMPTY_ACTION , // ( onSuccess | onError | onComplete )
Functions . EMPTY_ACTION // dispose
) ) ; |
public class VodClient { /** * Transcode the media again . Only status is FAILED or PUBLISHED media can use .
* @ param request The request object containing mediaid
* @ return */
public GetMediaSourceDownloadResponse getMediaSourceDownload ( GetMediaSourceDownloadRequest request ) { } } | checkStringNotEmpty ( request . getMediaId ( ) , "Media ID should not be null or empty!" ) ; InternalRequest internalRequest = createRequest ( HttpMethodName . GET , request , PATH_MEDIA , request . getMediaId ( ) ) ; internalRequest . addParameter ( PARA_DOWNLOAD , null ) ; internalRequest . addParameter ( PARA_EXPIREDINSECONDS , String . valueOf ( request . getExpiredInSeconds ( ) ) ) ; return invokeHttpClient ( internalRequest , GetMediaSourceDownloadResponse . class ) ; |
public class RestExceptionMapper { /** * Gets the full stack trace for the given exception and returns it as a
* string .
* @ param data */
private String getStackTrace ( AbstractRestException data ) { } } | StringBuilderWriter writer = new StringBuilderWriter ( ) ; try { data . printStackTrace ( new PrintWriter ( writer ) ) ; return writer . getBuilder ( ) . toString ( ) ; } finally { writer . close ( ) ; } |
public class MarkdownParser { /** * Extract all the referencable objects from the given content .
* @ param text the content to parse .
* @ return the referencables objects */
@ SuppressWarnings ( "static-method" ) protected ReferenceContext extractReferencableElements ( String text ) { } } | final ReferenceContext context = new ReferenceContext ( ) ; // Visit the links and record the transformations
final MutableDataSet options = new MutableDataSet ( ) ; final Parser parser = Parser . builder ( options ) . build ( ) ; final Node document = parser . parse ( text ) ; final Pattern pattern = Pattern . compile ( SECTION_PATTERN_AUTONUMBERING ) ; NodeVisitor visitor = new NodeVisitor ( new VisitHandler < > ( Paragraph . class , it -> { final Matcher matcher = pattern . matcher ( it . getContentChars ( ) ) ; if ( matcher . find ( ) ) { final String number = matcher . group ( 2 ) ; final String title = matcher . group ( 3 ) ; final String key1 = computeHeaderId ( number , title ) ; final String key2 = computeHeaderId ( null , title ) ; context . registerSection ( key1 , key2 , title ) ; } } ) ) ; visitor . visitChildren ( document ) ; visitor = new NodeVisitor ( new VisitHandler < > ( Heading . class , it -> { String key = it . getAnchorRefId ( ) ; final String title = it . getAnchorRefText ( ) ; final String key2 = computeHeaderId ( null , title ) ; if ( Strings . isEmpty ( key ) ) { key = key2 ; } context . registerSection ( key , key2 , title ) ; } ) ) ; visitor . visitChildren ( document ) ; return context ; |
public class MsWordUtils { /** * 获取一个新的XWPFRun对象
* @ param alignment 对齐方式
* @ return { @ link XWPFRun } */
public static XWPFRun getNewRun ( ParagraphAlignment alignment ) { } } | createXwpfDocumentIfNull ( ) ; XWPFParagraph paragraph = xwpfDocument . createParagraph ( ) ; paragraph . setAlignment ( alignment ) ; return paragraph . createRun ( ) ; |
public class MetadataUtils { /** * Provides a substring with collection name .
* @ param id
* string consisting of concatenation of collection name , / , & _ key .
* @ return collection name ( or null if no key delimiter is present ) */
public static String determineCollectionFromId ( final String id ) { } } | final int delimiter = id . indexOf ( KEY_DELIMITER ) ; return delimiter == - 1 ? null : id . substring ( 0 , delimiter ) ; |
public class MaskedCardAdapter { /** * Sets the selected source to the one whose ID is identical to the input string , if such
* a value is found .
* @ param sourceId a stripe ID to search for among the list of { @ link CustomerSource } objects
* @ return { @ code true } if the value was found , { @ code false } if not */
boolean setSelectedSource ( @ NonNull String sourceId ) { } } | for ( int i = 0 ; i < mCustomerSourceList . size ( ) ; i ++ ) { if ( sourceId . equals ( mCustomerSourceList . get ( i ) . getId ( ) ) ) { updateSelectedIndex ( i ) ; return true ; } } return false ; |
public class Mode { /** * Adds a set of attribute actions to be performed in this mode
* for attributes in a specified namespace .
* @ param ns The namespace pattern .
* @ param wildcard The wildcard character .
* @ param actions The set of attribute actions .
* @ return true if successfully added , that is the namespace was
* not already present in the attributeMap , otherwise false , the
* caller should signal a script error in this case . */
boolean bindAttribute ( String ns , String wildcard , AttributeActionSet actions ) { } } | NamespaceSpecification nss = new NamespaceSpecification ( ns , wildcard ) ; if ( nssAttributeMap . get ( nss ) != null ) return false ; for ( Enumeration e = nssAttributeMap . keys ( ) ; e . hasMoreElements ( ) ; ) { NamespaceSpecification nssI = ( NamespaceSpecification ) e . nextElement ( ) ; if ( nss . compete ( nssI ) ) { return false ; } } nssAttributeMap . put ( nss , actions ) ; return true ; |
public class Vector4d { /** * / * ( non - Javadoc )
* @ see org . joml . Vector4dc # add ( double , double , double , double , org . joml . Vector4d ) */
public Vector4d add ( double x , double y , double z , double w , Vector4d dest ) { } } | dest . x = this . x + x ; dest . y = this . y + y ; dest . z = this . z + z ; dest . w = this . w + w ; return dest ; |
public class SubFileFilter { /** * Get the foreign field that references this record .
* There can be more than one , so supply an index until you get a null .
* @ param iCount The index of the reference to retrieve
* @ return The referenced field */
public BaseField getReferencedField ( int iIndex ) { } } | if ( m_recordMain != null ) return m_recordMain . getKeyArea ( ) . getField ( iIndex ) ; if ( iIndex == 0 ) return m_fldMainFile ; if ( iIndex == 1 ) return m_fldMainFile2 ; if ( iIndex == 2 ) return m_fldMainFile3 ; return null ; |
public class FileCopier { /** * 拷贝文件 , 只用于内部 , 不做任何安全检查 < br >
* 情况如下 :
* < pre >
* 1 、 如果目标是一个不存在的路径 , 则目标以文件对待 ( 自动创建父级目录 ) 比如 : / dest / aaa , 如果aaa不存在 , 则aaa被当作文件名
* 2 、 如果目标是一个已存在的目录 , 则文件拷贝到此目录下 , 文件名与原文件名一致
* < / pre >
* @ param src 源文件 , 必须为文件
* @ param dest 目标文件 , 如果非覆盖模式必须为目录
* @ throws IORuntimeException IO异常 */
private void internalCopyFile ( File src , File dest ) throws IORuntimeException { } } | if ( null != copyFilter && false == copyFilter . accept ( src ) ) { // 被过滤的文件跳过
return ; } // 如果已经存在目标文件 , 切为不覆盖模式 , 跳过之
if ( dest . exists ( ) ) { if ( dest . isDirectory ( ) ) { // 目标为目录 , 目录下创建同名文件
dest = new File ( dest , src . getName ( ) ) ; } if ( dest . exists ( ) && false == isOverride ) { // 非覆盖模式跳过
return ; } } else { // 路径不存在则创建父目录
dest . getParentFile ( ) . mkdirs ( ) ; } final ArrayList < CopyOption > optionList = new ArrayList < > ( 2 ) ; if ( isOverride ) { optionList . add ( StandardCopyOption . REPLACE_EXISTING ) ; } if ( isCopyAttributes ) { optionList . add ( StandardCopyOption . COPY_ATTRIBUTES ) ; } try { Files . copy ( src . toPath ( ) , dest . toPath ( ) , optionList . toArray ( new CopyOption [ optionList . size ( ) ] ) ) ; } catch ( IOException e ) { throw new IORuntimeException ( e ) ; } |
public class SwaggerBuilder { /** * Returns the appropriate Swagger Property instance for a given object class .
* @ param swagger
* @ param objectClass
* @ return a SwaggerProperty instance */
protected Property getSwaggerProperty ( Swagger swagger , Class < ? > objectClass ) { } } | Property swaggerProperty = null ; if ( byte . class == objectClass || Byte . class == objectClass ) { // STRING
swaggerProperty = new StringProperty ( "byte" ) ; } else if ( char . class == objectClass || Character . class == objectClass ) { // CHAR is STRING LEN 1
StringProperty property = new StringProperty ( ) ; property . setMaxLength ( 1 ) ; swaggerProperty = property ; } else if ( short . class == objectClass || Short . class == objectClass ) { // SHORT is INTEGER with 16 - bit max & min
IntegerProperty property = new IntegerProperty ( ) ; property . setMinimum ( BigDecimal . valueOf ( Short . MIN_VALUE ) ) ; property . setMaximum ( BigDecimal . valueOf ( Short . MAX_VALUE ) ) ; swaggerProperty = property ; } else if ( int . class == objectClass || Integer . class == objectClass ) { // INTEGER
swaggerProperty = new IntegerProperty ( ) ; } else if ( long . class == objectClass || Long . class == objectClass ) { // LONG
swaggerProperty = new LongProperty ( ) ; } else if ( float . class == objectClass || Float . class == objectClass ) { // FLOAT
swaggerProperty = new FloatProperty ( ) ; } else if ( double . class == objectClass || Double . class == objectClass ) { // DOUBLE
swaggerProperty = new DoubleProperty ( ) ; } else if ( BigDecimal . class == objectClass ) { // DECIMAL
swaggerProperty = new DecimalProperty ( ) ; } else if ( boolean . class == objectClass || Boolean . class == objectClass ) { // BOOLEAN
swaggerProperty = new BooleanProperty ( ) ; } else if ( String . class == objectClass ) { // STRING
swaggerProperty = new StringProperty ( ) ; } else if ( Date . class == objectClass || Timestamp . class == objectClass ) { // DATETIME
swaggerProperty = new DateTimeProperty ( ) ; } else if ( java . sql . Date . class == objectClass ) { // DATE
swaggerProperty = new DateProperty ( ) ; } else if ( java . sql . Time . class == objectClass ) { // TIME - > STRING
StringProperty property = new StringProperty ( ) ; property . setPattern ( "HH:mm:ss" ) ; swaggerProperty = property ; } else if ( UUID . class == objectClass ) { // UUID
swaggerProperty = new UUIDProperty ( ) ; } else if ( objectClass . isEnum ( ) ) { // ENUM
StringProperty property = new StringProperty ( ) ; List < String > enumValues = new ArrayList < > ( ) ; for ( Object enumValue : objectClass . getEnumConstants ( ) ) { enumValues . add ( ( ( Enum ) enumValue ) . name ( ) ) ; } property . setEnum ( enumValues ) ; swaggerProperty = property ; } else if ( FileItem . class == objectClass ) { // FILE UPLOAD
swaggerProperty = new FileProperty ( ) ; } else { // Register a Model class
String modelRef = registerModel ( swagger , objectClass ) ; swaggerProperty = new RefProperty ( modelRef ) ; } return swaggerProperty ; |
public class XSLTComponent { /** * / * ( non - Javadoc )
* @ see org . apereo . portal . rendering . StAXPipelineComponent # getXmlStreamReader ( java . lang . Object , java . lang . Object ) */
@ Override public PipelineEventReader < XMLEventReader , XMLEvent > getEventReader ( HttpServletRequest request , HttpServletResponse response ) { } } | final PipelineEventReader < XMLEventReader , XMLEvent > pipelineEventReader = this . wrappedComponent . getEventReader ( request , response ) ; final Transformer transformer = this . transformerSource . getTransformer ( request , response ) ; // Setup a URIResolver based on the current resource loader
transformer . setURIResolver ( this . uriResolver ) ; // Configure the Transformer via injected class
if ( this . xsltParameterSource != null ) { final Map < String , Object > transformerParameters = this . xsltParameterSource . getParameters ( request , response ) ; if ( transformerParameters != null ) { this . logger . debug ( "{} - Setting Transformer Parameters: " , this . beanName , transformerParameters ) ; for ( final Map . Entry < String , Object > transformerParametersEntry : transformerParameters . entrySet ( ) ) { final String name = transformerParametersEntry . getKey ( ) ; final Object value = transformerParametersEntry . getValue ( ) ; if ( value != null ) { transformer . setParameter ( name , value ) ; } } } final Properties outputProperties = this . xsltParameterSource . getOutputProperties ( request , response ) ; if ( outputProperties != null ) { this . logger . debug ( "{} - Setting Transformer Output Properties: " , this . beanName , outputProperties ) ; transformer . setOutputProperties ( outputProperties ) ; } } // The event reader from the previous component in the pipeline
final XMLEventReader eventReader = pipelineEventReader . getEventReader ( ) ; // Wrap the event reader in a stream reader to avoid a JDK bug
final XMLStreamReader streamReader ; try { streamReader = new FixedXMLEventStreamReader ( eventReader ) ; } catch ( XMLStreamException e ) { throw new RuntimeException ( "Failed to create XMLStreamReader from XMLEventReader" , e ) ; } final Source xmlReaderSource = new StAXSource ( streamReader ) ; // Setup logging for the transform
transformer . setErrorListener ( this . errorListener ) ; // Transform to a SAX ContentHandler to avoid JDK bug :
// http : / / bugs . sun . com / bugdatabase / view _ bug . do ? bug _ id = 6775588
final XMLEventBufferWriter eventWriterBuffer = new XMLEventBufferWriter ( ) ; final ContentHandler contentHandler = StaxUtils . createContentHandler ( eventWriterBuffer ) ; contentHandler . setDocumentLocator ( new LocatorImpl ( ) ) ; final SAXResult outputTarget = new SAXResult ( contentHandler ) ; try { this . logger . debug ( "{} - Begining XML Transformation" , this . beanName ) ; transformer . transform ( xmlReaderSource , outputTarget ) ; this . logger . debug ( "{} - XML Transformation complete" , this . beanName ) ; } catch ( TransformerException e ) { throw new RuntimeException ( "Failed to transform document" , e ) ; } final String mediaType = transformer . getOutputProperty ( OutputKeys . MEDIA_TYPE ) ; final List < XMLEvent > eventBuffer = eventWriterBuffer . getEventBuffer ( ) ; final XMLEventReader outputEventReader = new XMLEventBufferReader ( eventBuffer . listIterator ( ) ) ; final Map < String , String > outputProperties = pipelineEventReader . getOutputProperties ( ) ; final PipelineEventReaderImpl < XMLEventReader , XMLEvent > pipelineEventReaderImpl = new PipelineEventReaderImpl < XMLEventReader , XMLEvent > ( outputEventReader , outputProperties ) ; pipelineEventReaderImpl . setOutputProperty ( OutputKeys . MEDIA_TYPE , mediaType ) ; return pipelineEventReaderImpl ; |
public class Resource { /** * Builds and returns a valid { @ link HttpUrl } pointing to the given { @ link Endpoint } ' s host
* and with all the supplied segments concatenated .
* @ param endpoint The Omise API { @ link Endpoint } to point to .
* @ param path The base API path .
* @ param segments Additional URL path segments that should be appended .
* @ return An { @ link HttpUrl } instance . */
protected HttpUrl buildUrl ( Endpoint endpoint , String path , String ... segments ) { } } | Preconditions . checkNotNull ( endpoint ) ; Preconditions . checkNotNull ( path ) ; HttpUrl . Builder builder = endpoint . buildUrl ( ) . addPathSegment ( path ) ; for ( String segment : segments ) { if ( segment == null || segment . isEmpty ( ) ) { continue ; } builder = builder . addPathSegment ( segment ) ; } return builder . build ( ) ; |
public class SystemInputJson { /** * Returns the Not ( ContainsAny ) condition represented by the given JSON object or an empty
* value if no such condition is found . */
private static Optional < ICondition > asContainsNone ( JsonObject json ) { } } | return json . containsKey ( HAS_NONE_KEY ) ? Optional . of ( new Not ( new ContainsAny ( toIdentifiers ( json . getJsonArray ( HAS_NONE_KEY ) ) ) ) ) : Optional . empty ( ) ; |
public class DateUtils { /** * Warning : may rely on default timezone !
* @ return the datetime , { @ code null } if stringDate is null
* @ throws IllegalArgumentException if stringDate is not a correctly formed date or datetime
* @ since 6.1 */
@ CheckForNull public static Date parseDateOrDateTime ( @ Nullable String stringDate ) { } } | if ( stringDate == null ) { return null ; } OffsetDateTime odt = parseOffsetDateTimeQuietly ( stringDate ) ; if ( odt != null ) { return Date . from ( odt . toInstant ( ) ) ; } LocalDate ld = parseLocalDateQuietly ( stringDate ) ; checkArgument ( ld != null , "Date '%s' cannot be parsed as either a date or date+time" , stringDate ) ; return Date . from ( ld . atStartOfDay ( ZoneId . systemDefault ( ) ) . toInstant ( ) ) ; |
public class Matrix3x2d { /** * Apply a rotation transformation to this matrix by rotating the given amount of radians and store the result in < code > dest < / code > .
* If < code > M < / code > is < code > this < / code > matrix and < code > R < / code > the rotation matrix ,
* then the new matrix will be < code > M * R < / code > . So when transforming a
* vector < code > v < / code > with the new matrix by using < code > M * R * v < / code > , the rotation will be applied first !
* @ param ang
* the angle in radians
* @ param dest
* will hold the result
* @ return dest */
public Matrix3x2d rotate ( double ang , Matrix3x2d dest ) { } } | double cos = Math . cos ( ang ) ; double sin = Math . sin ( ang ) ; double rm00 = cos ; double rm01 = sin ; double rm10 = - sin ; double rm11 = cos ; double nm00 = m00 * rm00 + m10 * rm01 ; double nm01 = m01 * rm00 + m11 * rm01 ; dest . m10 = m00 * rm10 + m10 * rm11 ; dest . m11 = m01 * rm10 + m11 * rm11 ; dest . m00 = nm00 ; dest . m01 = nm01 ; dest . m20 = m20 ; dest . m21 = m21 ; return dest ; |
public class TmdbTV { /** * Get the content ratings for a specific TV show id .
* @ param tvID
* @ return
* @ throws com . omertron . themoviedbapi . MovieDbException */
public ResultList < ContentRating > getTVContentRatings ( int tvID ) throws MovieDbException { } } | TmdbParameters parameters = new TmdbParameters ( ) ; parameters . add ( Param . ID , tvID ) ; URL url = new ApiUrl ( apiKey , MethodBase . TV ) . subMethod ( MethodSub . CONTENT_RATINGS ) . buildUrl ( parameters ) ; WrapperGenericList < ContentRating > wrapper = processWrapper ( getTypeReference ( ContentRating . class ) , url , "content rating" ) ; return wrapper . getResultsList ( ) ; |
public class ProductScan { /** * Moves the scan to the next record . The method moves to the next RHS
* record , if possible . Otherwise , it moves to the next LHS record and the
* first RHS record . If there are no more LHS records , the method returns
* false .
* @ see Scan # next ( ) */
@ Override public boolean next ( ) { } } | if ( isLhsEmpty ) return false ; if ( s2 . next ( ) ) return true ; else if ( ! ( isLhsEmpty = ! s1 . next ( ) ) ) { s2 . beforeFirst ( ) ; return s2 . next ( ) ; } else { return false ; } |
public class DBRef { /** * Convert the DBRef object to a DBREF record as it is used in PDB files
* @ return a PDB - DBREF formatted line */
@ Override public String toPDB ( ) { } } | StringBuffer buf = new StringBuffer ( ) ; toPDB ( buf ) ; return buf . toString ( ) ; |
public class PreferenceActivity { /** * Obtains , whether the split screen layout should be used on tablets , from the activities
* theme . */
private void obtainUseSplitScreen ( ) { } } | boolean useSplitScreen = ThemeUtil . getBoolean ( this , R . attr . useSplitScreen , true ) ; useSplitScreen ( useSplitScreen ) ; |
public class EventExtractor { /** * Splits events of a row if they contain a gap . Gaps are found using the
* token index ( provided as ANNIS specific { @ link SFeature } . Inserted events
* have a special style to mark them as gaps .
* @ param row
* @ param graph
* @ param startTokenIndex token index of the first token in the match
* @ param endTokenIndex token index of the last token in the match */
private static void splitRowsOnGaps ( Row row , final SDocumentGraph graph , long startTokenIndex , long endTokenIndex ) { } } | ListIterator < GridEvent > itEvents = row . getEvents ( ) . listIterator ( ) ; while ( itEvents . hasNext ( ) ) { GridEvent event = itEvents . next ( ) ; int lastTokenIndex = - 1 ; // sort the coveredIDs
LinkedList < String > sortedCoveredToken = new LinkedList < > ( event . getCoveredIDs ( ) ) ; Collections . sort ( sortedCoveredToken , new Comparator < String > ( ) { @ Override public int compare ( String o1 , String o2 ) { SNode node1 = graph . getNode ( o1 ) ; SNode node2 = graph . getNode ( o2 ) ; if ( node1 == node2 ) { return 0 ; } if ( node1 == null ) { return - 1 ; } if ( node2 == null ) { return + 1 ; } RelannisNodeFeature feat1 = ( RelannisNodeFeature ) node1 . getFeature ( ANNIS_NS , FEAT_RELANNIS_NODE ) . getValue ( ) ; RelannisNodeFeature feat2 = ( RelannisNodeFeature ) node2 . getFeature ( ANNIS_NS , FEAT_RELANNIS_NODE ) . getValue ( ) ; long tokenIndex1 = feat1 . getTokenIndex ( ) ; long tokenIndex2 = feat2 . getTokenIndex ( ) ; return Long . compare ( tokenIndex1 , tokenIndex2 ) ; } } ) ; // first calculate all gaps
List < GridEvent > gaps = new LinkedList < > ( ) ; for ( String id : sortedCoveredToken ) { SNode node = graph . getNode ( id ) ; RelannisNodeFeature feat = ( RelannisNodeFeature ) node . getFeature ( ANNIS_NS , FEAT_RELANNIS_NODE ) . getValue ( ) ; long tokenIndexRaw = feat . getTokenIndex ( ) ; tokenIndexRaw = clip ( tokenIndexRaw , startTokenIndex , endTokenIndex ) ; int tokenIndex = ( int ) ( tokenIndexRaw - startTokenIndex ) ; // sanity check
if ( tokenIndex >= event . getLeft ( ) && tokenIndex <= event . getRight ( ) ) { int diff = tokenIndex - lastTokenIndex ; if ( lastTokenIndex >= 0 && diff > 1 ) { // we detected a gap
GridEvent gap = new GridEvent ( event . getId ( ) + "_gap_" + gaps . size ( ) , lastTokenIndex + 1 , tokenIndex - 1 , "" ) ; gap . setGap ( true ) ; gaps . add ( gap ) ; } lastTokenIndex = tokenIndex ; } else { // reset gap search when discovered there were token we use for
// hightlighting but do not actually cover
lastTokenIndex = - 1 ; } } // end for each covered token id
ListIterator < GridEvent > itGaps = gaps . listIterator ( ) ; // remember the old right value
int oldRight = event . getRight ( ) ; int gapNr = 0 ; while ( itGaps . hasNext ( ) ) { GridEvent gap = itGaps . next ( ) ; if ( gapNr == 0 ) { // shorten original event
event . setRight ( gap . getLeft ( ) - 1 ) ; } // insert the real gap
itEvents . add ( gap ) ; int rightBorder = oldRight ; if ( itGaps . hasNext ( ) ) { // don ' t use the old event right border since the gap should only go until
// the next event
GridEvent nextGap = itGaps . next ( ) ; itGaps . previous ( ) ; rightBorder = nextGap . getLeft ( ) - 1 ; } // insert a new event node that covers the rest of the event
GridEvent after = new GridEvent ( event ) ; after . setId ( event . getId ( ) + "_after_" + gapNr ) ; after . setLeft ( gap . getRight ( ) + 1 ) ; after . setRight ( rightBorder ) ; itEvents . add ( after ) ; gapNr ++ ; } } |
public class MSExcelParser { /** * Check if document matches the metadata filters for HSSF documents
* @ return true , if it matches , false if not */
private boolean checkFilteredHSSF ( ) { } } | HSSFWorkbook currentHSSFWorkbook = ( HSSFWorkbook ) this . currentWorkbook ; SummaryInformation summaryInfo = currentHSSFWorkbook . getSummaryInformation ( ) ; boolean matchAll = true ; boolean matchFull = true ; boolean matchOnce = false ; if ( this . hocr . getMetaDataFilter ( ) . get ( MATCH_ALL ) != null ) { if ( "true" . equalsIgnoreCase ( this . hocr . getMetaDataFilter ( ) . get ( MATCH_ALL ) ) ) { matchAll = true ; } else if ( "false" . equalsIgnoreCase ( this . hocr . getMetaDataFilter ( ) . get ( MATCH_ALL ) ) ) { matchAll = false ; } else { LOG . error ( "Metadata property matchAll not defined correctly. Assuming that at only least one attribute needs to match" ) ; } } String corePropertyName ; corePropertyName = "applicationname" ; if ( this . hocr . getMetaDataFilter ( ) . get ( corePropertyName ) != null ) { String coreProp = summaryInfo . getApplicationName ( ) ; if ( ( coreProp != null ) && ( coreProp . matches ( this . hocr . getMetaDataFilter ( ) . get ( corePropertyName ) ) ) ) { matchOnce = true ; } else { matchFull = false ; } } corePropertyName = "author" ; if ( this . hocr . getMetaDataFilter ( ) . get ( corePropertyName ) != null ) { String coreProp = summaryInfo . getAuthor ( ) ; if ( ( coreProp != null ) && ( coreProp . matches ( this . hocr . getMetaDataFilter ( ) . get ( corePropertyName ) ) ) ) { matchOnce = true ; } else { matchFull = false ; } } corePropertyName = "charcount" ; if ( this . hocr . getMetaDataFilter ( ) . get ( corePropertyName ) != null ) { int coreProp = summaryInfo . getCharCount ( ) ; if ( String . valueOf ( coreProp ) . matches ( this . hocr . getMetaDataFilter ( ) . get ( corePropertyName ) ) ) { matchOnce = true ; } else { matchFull = false ; } } corePropertyName = "comments" ; if ( this . hocr . getMetaDataFilter ( ) . get ( corePropertyName ) != null ) { String coreProp = summaryInfo . getComments ( ) ; if ( ( coreProp != null ) && ( coreProp . matches ( this . hocr . getMetaDataFilter ( ) . get ( corePropertyName ) ) ) ) { matchOnce = true ; } else { matchFull = false ; } } corePropertyName = "createddatetime" ; if ( this . hocr . getMetaDataFilter ( ) . get ( corePropertyName ) != null ) { Date coreProp = summaryInfo . getCreateDateTime ( ) ; if ( ( coreProp != null ) && ( coreProp . toString ( ) . matches ( this . hocr . getMetaDataFilter ( ) . get ( corePropertyName ) ) ) ) { matchOnce = true ; } else { matchFull = false ; } } corePropertyName = "edittime" ; if ( this . hocr . getMetaDataFilter ( ) . get ( corePropertyName ) != null ) { long coreProp = summaryInfo . getEditTime ( ) ; if ( String . valueOf ( coreProp ) . matches ( this . hocr . getMetaDataFilter ( ) . get ( corePropertyName ) ) ) { matchOnce = true ; } else { matchFull = false ; } } corePropertyName = "keywords" ; if ( this . hocr . getMetaDataFilter ( ) . get ( corePropertyName ) != null ) { String coreProp = summaryInfo . getKeywords ( ) ; if ( ( coreProp != null ) && ( coreProp . matches ( this . hocr . getMetaDataFilter ( ) . get ( corePropertyName ) ) ) ) { matchOnce = true ; } else { matchFull = false ; } } corePropertyName = "lastauthor" ; if ( this . hocr . getMetaDataFilter ( ) . get ( corePropertyName ) != null ) { String coreProp = summaryInfo . getLastAuthor ( ) ; if ( ( coreProp != null ) && ( coreProp . matches ( this . hocr . getMetaDataFilter ( ) . get ( corePropertyName ) ) ) ) { matchOnce = true ; } else { matchFull = false ; } } corePropertyName = "lastprinted" ; if ( this . hocr . getMetaDataFilter ( ) . get ( corePropertyName ) != null ) { Date coreProp = summaryInfo . getLastPrinted ( ) ; if ( ( coreProp != null ) && ( coreProp . toString ( ) . matches ( this . hocr . getMetaDataFilter ( ) . get ( corePropertyName ) ) ) ) { matchOnce = true ; } else { matchFull = false ; } } corePropertyName = "lastsavedatetime" ; if ( this . hocr . getMetaDataFilter ( ) . get ( corePropertyName ) != null ) { Date coreProp = summaryInfo . getLastSaveDateTime ( ) ; if ( ( coreProp != null ) && ( coreProp . toString ( ) . matches ( this . hocr . getMetaDataFilter ( ) . get ( corePropertyName ) ) ) ) { matchOnce = true ; } else { matchFull = false ; } } corePropertyName = "pagecount" ; if ( this . hocr . getMetaDataFilter ( ) . get ( corePropertyName ) != null ) { int coreProp = summaryInfo . getPageCount ( ) ; if ( String . valueOf ( coreProp ) . matches ( this . hocr . getMetaDataFilter ( ) . get ( corePropertyName ) ) ) { matchOnce = true ; } else { matchFull = false ; } } corePropertyName = "revnumber" ; if ( this . hocr . getMetaDataFilter ( ) . get ( corePropertyName ) != null ) { String coreProp = summaryInfo . getRevNumber ( ) ; if ( ( coreProp != null ) && ( coreProp . matches ( this . hocr . getMetaDataFilter ( ) . get ( corePropertyName ) ) ) ) { matchOnce = true ; } else { matchFull = false ; } } corePropertyName = "security" ; if ( this . hocr . getMetaDataFilter ( ) . get ( corePropertyName ) != null ) { int coreProp = summaryInfo . getSecurity ( ) ; if ( String . valueOf ( coreProp ) . matches ( this . hocr . getMetaDataFilter ( ) . get ( corePropertyName ) ) ) { matchOnce = true ; } else { matchFull = false ; } } corePropertyName = "subject" ; if ( this . hocr . getMetaDataFilter ( ) . get ( corePropertyName ) != null ) { String coreProp = summaryInfo . getSubject ( ) ; if ( ( coreProp != null ) && ( coreProp . matches ( this . hocr . getMetaDataFilter ( ) . get ( corePropertyName ) ) ) ) { matchOnce = true ; } else { matchFull = false ; } } corePropertyName = "template" ; if ( this . hocr . getMetaDataFilter ( ) . get ( corePropertyName ) != null ) { String coreProp = summaryInfo . getTemplate ( ) ; if ( ( coreProp != null ) && ( coreProp . matches ( this . hocr . getMetaDataFilter ( ) . get ( corePropertyName ) ) ) ) { matchOnce = true ; } else { matchFull = false ; } } corePropertyName = "title" ; if ( this . hocr . getMetaDataFilter ( ) . get ( corePropertyName ) != null ) { String coreProp = summaryInfo . getTitle ( ) ; if ( ( coreProp != null ) && ( coreProp . matches ( this . hocr . getMetaDataFilter ( ) . get ( corePropertyName ) ) ) ) { matchOnce = true ; } else { matchFull = false ; } } corePropertyName = "wordcount" ; if ( this . hocr . getMetaDataFilter ( ) . get ( corePropertyName ) != null ) { int coreProp = summaryInfo . getWordCount ( ) ; if ( String . valueOf ( coreProp ) . matches ( this . hocr . getMetaDataFilter ( ) . get ( corePropertyName ) ) ) { matchOnce = true ; } else { matchFull = false ; } } if ( ! ( matchAll ) ) { return matchOnce ; } else { return matchFull ; } |
public class SystemPropertiesUtil { /** * 读取Double类型的系统变量 , 为空时返回null . */
public static Double getDouble ( String propertyName ) { } } | return NumberUtil . toDoubleObject ( System . getProperty ( propertyName ) , null ) ; |
public class AutoJsonRpcClientProxyCreator { /** * Registers a new proxy bean with the bean factory . */
private void registerJsonProxyBean ( DefaultListableBeanFactory defaultListableBeanFactory , String className , String path ) { } } | BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder . rootBeanDefinition ( JsonProxyFactoryBean . class ) . addPropertyValue ( "serviceUrl" , appendBasePath ( path ) ) . addPropertyValue ( "serviceInterface" , className ) ; if ( objectMapper != null ) { beanDefinitionBuilder . addPropertyValue ( "objectMapper" , objectMapper ) ; } if ( contentType != null ) { beanDefinitionBuilder . addPropertyValue ( "contentType" , contentType ) ; } defaultListableBeanFactory . registerBeanDefinition ( className + "-clientProxy" , beanDefinitionBuilder . getBeanDefinition ( ) ) ; |
public class KeyJpaFinderIT { /** * Request all the keys marked as approximate . */
@ Test public void get_approx_default_translation ( ) { } } | KeySearchCriteria criteria = new KeySearchCriteria ( null , true , null , null ) ; PaginatedView < KeyRepresentation > keyRepresentations = keyFinder . findKeysWithTheirDefaultTranslation ( FIRST_RANGE , criteria ) ; assertThat ( keyRepresentations . getPageSize ( ) ) . isEqualTo ( 1 ) ; KeyRepresentation representation = keyRepresentations . getView ( ) . get ( 0 ) ; assertThat ( representation . getDefaultLocale ( ) ) . isEqualTo ( EN ) ; assertThat ( representation . getTranslation ( ) ) . isEqualTo ( TRANSLATION_EN ) ; |
public class AlexaInput { /** * Checks if a slot is contained in the intent request and has a value which is a
* phonetic sibling of the string given to this method . This method picks the correct
* algorithm depending on the locale coming in with the speechlet request . For example the
* German locale compares the slot value and the given value with the Cologne phonetic
* algorithm whereas english locales result in this method using the Double Metaphone algorithm .
* @ param slotName name of the slot to look after
* @ param value the value
* @ return True , if slot value and given value are phonetically equal */
public boolean hasSlotIsPhoneticallyEqual ( final String slotName , final String value ) { } } | return getLocale ( ) . equals ( "de-DE" ) ? hasSlotIsCologneEqual ( slotName , value ) : hasSlotIsDoubleMetaphoneEqual ( slotName , value ) ; |
public class BsfUtils { /** * Selects the Date Pattern to use based on the given Locale if the input
* format is null
* @ param locale
* Locale ( may be the result of a call to selectLocale )
* @ param format
* optional Input format String , given as Moment . js date format
* @ return Moment . js Date Pattern eg . DD / MM / YYYY */
public static String selectMomentJSDateFormat ( Locale locale , String format ) { } } | String selFormat ; if ( format == null ) { selFormat = ( ( SimpleDateFormat ) DateFormat . getDateInstance ( DateFormat . SHORT , locale ) ) . toPattern ( ) ; // Since DateFormat . SHORT is silly , return a smart format
if ( selFormat . equals ( "M/d/yy" ) ) { return "MM/DD/YYYY" ; } if ( selFormat . equals ( "d/M/yy" ) ) { return "DD/MM/YYYY" ; } return LocaleUtils . javaToMomentFormat ( selFormat ) ; } else { selFormat = format ; } return selFormat ; |
public class XResourceBundle { /** * Return the resource file suffic for the indicated locale
* For most locales , this will be based the language code . However
* for Chinese , we do distinguish between Taiwan and PRC
* @ param locale the locale
* @ return an String suffix which canbe appended to a resource name */
private static final String getResourceSuffix ( Locale locale ) { } } | String lang = locale . getLanguage ( ) ; String country = locale . getCountry ( ) ; String variant = locale . getVariant ( ) ; String suffix = "_" + locale . getLanguage ( ) ; if ( lang . equals ( "zh" ) ) suffix += "_" + country ; if ( country . equals ( "JP" ) ) suffix += "_" + country + "_" + variant ; return suffix ; |
public class Constraints { /** * Returns a ConditionalPropertyConstraint : one property will trigger the
* validation of another .
* @ see ConditionalPropertyConstraint */
public PropertyConstraint ifTrue ( PropertyConstraint ifConstraint , PropertyConstraint [ ] thenConstraints , PropertyConstraint [ ] elseConstraints ) { } } | return new ConditionalPropertyConstraint ( ifConstraint , new CompoundPropertyConstraint ( new And ( thenConstraints ) ) , new CompoundPropertyConstraint ( new And ( elseConstraints ) ) ) ; |
public class BeanInfoUtil { /** * Builds a method descriptor that is exposed for scripting everywhere . */
public static MethodDescriptor buildScriptableMethodDescriptor ( Class actionClass , String methodName , String [ ] parameterNames , Class [ ] parameterTypes ) { } } | MethodDescriptor md = _buildMethodDescriptor ( actionClass , methodName , parameterNames , parameterTypes , parameterTypes ) ; makeScriptable ( md ) ; return md ; |
public class AbstractDecompiler { /** * Decompiles all . class files and nested archives in the given archive .
* Nested archives will be decompiled into directories matching the name of the archive , e . g .
* < code > foo . ear / bar . jar / src / com / foo / bar / Baz . java < / code > .
* Required directories will be created as needed .
* @ param archive The archive containing source files and archives .
* @ param outputDir The directory where decompiled . java files will be placed .
* @ returns Result with all decompilation failures . Never throws . */
@ Override public DecompilationResult decompileArchive ( Path archive , Path outputDir , DecompilationListener listener ) throws DecompilationException { } } | return decompileArchive ( archive , outputDir , null , listener ) ; |
public class EnumPreference { /** * Set the value for the preference */
@ Override public void set ( E value ) { } } | if ( value == null ) throw new NullPointerException ( "value" ) ; this . set ( value . ordinal ( ) ) ; |
public class Component { /** * Create a ( deep ) copy of this component .
* @ return the component copy
* @ throws IOException where an error occurs reading the component data
* @ throws ParseException where parsing component data fails
* @ throws URISyntaxException where component data contains an invalid URI */
public Component copy ( ) throws ParseException , IOException , URISyntaxException { } } | // Deep copy properties . .
final PropertyList < Property > newprops = new PropertyList < Property > ( getProperties ( ) ) ; return new ComponentFactoryImpl ( ) . createComponent ( getName ( ) , newprops ) ; |
public class WCheckBoxSelectExample { /** * When a WCheckBoxSelect is added to a WFieldLayout the legend is moved . The first CheckBoxSelect has a frame , the
* second doesn ' t */
private void addInsideAFieldLayoutExamples ( ) { } } | add ( new WHeading ( HeadingLevel . H3 , "WCheckBoxSelect inside a WFieldLayout" ) ) ; add ( new ExplanatoryText ( "When a WCheckBoxSelect is inside a WField its label is exposed in a way which appears and behaves like a regular " + "HTML label. This allows WCheckBoxSelects to be used in a layout with simple form controls (such as WTextField) and produce a " + "consistent and predicatable interface. The third example in this set uses a null label and a toolTip to hide the labelling " + "element. This can lead to user confusion and is not recommended." ) ) ; WFieldLayout layout = new WFieldLayout ( ) ; layout . setLabelWidth ( 25 ) ; add ( layout ) ; String [ ] options = new String [ ] { "Dog" , "Cat" , "Bird" , "Turtle" } ; WCheckBoxSelect select = new WCheckBoxSelect ( options ) ; layout . addField ( "Select some animals" , select ) ; String [ ] options2 = new String [ ] { "Parrot" , "Galah" , "Cockatoo" , "Lyre" } ; select = new WCheckBoxSelect ( options2 ) ; layout . addField ( "Select some birds" , select ) ; select . setFrameless ( true ) ; // a tooltip can be used as a label stand - in even in a WField
String [ ] options3 = new String [ ] { "Carrot" , "Beet" , "Brocolli" , "Bacon - the perfect vegetable" } ; select = new WCheckBoxSelect ( options3 ) ; layout . addField ( ( WLabel ) null , select ) ; select . setToolTip ( "Veggies" ) ; select = new WCheckBoxSelect ( "australian_state" ) ; layout . addField ( "Select a state" , select ) . getLabel ( ) . setHint ( "This is an ajax trigger" ) ; add ( new WAjaxControl ( select , layout ) ) ; |
public class CronOutputSchedule { /** * ( non - Javadoc )
* @ see com . nokia . dempsy . output . OutputExecuter # stop ( ) */
@ Override public void stop ( ) { } } | try { // gracefully shutting down
scheduler . shutdown ( false ) ; } catch ( final SchedulerException se ) { LOGGER . error ( "Error occurred while stopping the cron scheduler : " + se . getMessage ( ) , se ) ; } |
public class Cursor { /** * Set a { @ link CursorTheme } for this cursor . Use the { @ link CursorManager # getCursorThemes ( ) }
* call to know all the available cursor themes .
* Make sure that the theme cursor type matches this { @ link Cursor } else this call will return
* an { @ link IllegalArgumentException } .
* @ param theme the { @ link CursorTheme } to be set . */
public void setCursorTheme ( final CursorTheme theme ) { } } | if ( theme == mCursorTheme || theme == null ) { // nothing to do , return
return ; } if ( theme . getCursorType ( ) != mCursorType ) { throw new IllegalArgumentException ( "Cursor Theme does not match the cursor type" ) ; } if ( mCursorAsset != null ) { mCursorAsset . reset ( this ) ; } if ( mCursorTheme != null ) { mCursorTheme . unload ( this ) ; } mCursorTheme = theme ; mAudioManager . loadTheme ( mCursorTheme ) ; theme . load ( this ) ; if ( mCursorAsset != null ) { mCursorAsset = mCursorTheme . getAsset ( mCursorAsset . getAction ( ) ) ; if ( mCursorAsset == null ) { mCursorAsset = mCursorTheme . getAsset ( Action . DEFAULT ) ; } mCursorAsset . set ( this ) ; } |
public class CmsObjectWrapper { /** * Writes a resource to the OpenCms VFS , including it ' s content . < p >
* Iterates through all configured resource wrappers till the first returns not < code > null < / code > . < p >
* @ see I _ CmsResourceWrapper # writeFile ( CmsObject , CmsFile )
* @ see CmsObject # writeFile ( CmsFile )
* @ param resource the resource to write
* @ return the written resource ( may have been modified )
* @ throws CmsException if something goes wrong */
public CmsFile writeFile ( CmsFile resource ) throws CmsException { } } | CmsFile res = null ; // remove the added UTF - 8 marker
if ( needUtf8Marker ( resource ) ) { resource . setContents ( CmsResourceWrapperUtils . removeUtf8Marker ( resource . getContents ( ) ) ) ; } String resourcename = m_cms . getSitePath ( resource ) ; if ( ! m_cms . existsResource ( resourcename ) ) { // iterate through all wrappers and call " writeFile " till one does not return null
List < I_CmsResourceWrapper > wrappers = getWrappers ( ) ; Iterator < I_CmsResourceWrapper > iter = wrappers . iterator ( ) ; while ( iter . hasNext ( ) ) { I_CmsResourceWrapper wrapper = iter . next ( ) ; res = wrapper . writeFile ( m_cms , resource ) ; if ( res != null ) { break ; } } // delegate the call to the CmsObject
if ( res == null ) { res = m_cms . writeFile ( resource ) ; } } else { res = m_cms . writeFile ( resource ) ; } return res ; |
public class HttpUtil { /** * Checks if request and request method are not null
* @ param request { @ link HttpServletRequest } to check
* @ return true if sane , false otherwise */
public static boolean isSaneRequest ( HttpServletRequest request ) { } } | if ( request != null && request . getMethod ( ) != null ) { return true ; } return false ; |
public class Cartographer { /** * Print the json representation of an array to the given writer . Primitive arrays cannot be cast
* to Object [ ] , to this method accepts the raw object and uses { @ link Array # getLength ( Object ) } and
* { @ link Array # get ( Object , int ) } to read the array . */
private static void arrayToWriter ( Object array , JsonWriter writer ) throws IOException { } } | writer . beginArray ( ) ; for ( int i = 0 , size = Array . getLength ( array ) ; i < size ; i ++ ) { writeValue ( Array . get ( array , i ) , writer ) ; } writer . endArray ( ) ; |
public class IntList { /** * Checks if the specified element is found in the list .
* @ param e element to be found
* @ return result of check */
public final boolean contains ( final int e ) { } } | for ( int i = 0 ; i < size ; ++ i ) if ( list [ i ] == e ) return true ; return false ; |
public class DatabaseMetaData { /** * { @ inheritDoc } */
public ResultSet getPrimaryKeys ( final String catalog , final String schema , final String table ) throws SQLException { } } | return RowLists . rowList6 ( String . class , String . class , String . class , String . class , Short . class , String . class ) . withLabel ( 1 , "TABLE_CAT" ) . withLabel ( 2 , "TABLE_SCHEM" ) . withLabel ( 3 , "TABLE_NAME" ) . withLabel ( 4 , "COLUMN_NAME" ) . withLabel ( 5 , "KEY_SEQ" ) . withLabel ( 6 , "PK_NAME" ) . resultSet ( ) ; |
public class ValidateUtils { /** * Number Validation
* @ param context
* @ param input
* @ param minValue
* @ param maxValue
* @ param allowNull
* @ return */
public static Double validateNumber ( final String context , final String input , final long minValue , final long maxValue , final boolean allowNull ) throws ValidationException { } } | return validator . getValidNumber ( context , input , minValue , maxValue , allowNull ) ; |
public class ActiveMqQueue { /** * Init method .
* @ return
* @ throws Exception */
public ActiveMqQueue < ID , DATA > init ( ) throws Exception { } } | if ( connectionFactory == null ) { setConnectionFactory ( buildConnectionFactory ( ) , true ) ; } super . init ( ) ; if ( connectionFactory == null ) { throw new IllegalStateException ( "ActiveMQ Connection factory is null." ) ; } return this ; |
public class ChemModelRenderer { /** * Setup the transformations necessary to draw this Chem Model .
* @ param chemModel
* @ param screen */
@ Override public void setup ( IChemModel chemModel , Rectangle screen ) { } } | this . setScale ( chemModel ) ; Rectangle2D bounds = BoundsCalculator . calculateBounds ( chemModel ) ; if ( bounds != null ) this . modelCenter = new Point2d ( bounds . getCenterX ( ) , bounds . getCenterY ( ) ) ; this . drawCenter = new Point2d ( screen . getCenterX ( ) , screen . getCenterY ( ) ) ; this . setup ( ) ; |
public class Properties { /** * Returns the comment for the specified key , or null if there is none .
* Any embedded newline sequences will be replaced by \ n characters .
* @ param key
* @ return */
public String getComment ( String key ) { } } | String raw = getRawComment ( key ) ; return cookComment ( raw ) ; |
public class ItemUtils { /** * Checks whether two { @ link ItemStack itemStacks } can be stacked together
* @ param stack1 first itemStack
* @ param stack2 second itemStack
* @ return true , if the itemStack can be stacked , false otherwise */
public static boolean areItemStacksStackable ( ItemStack stack1 , ItemStack stack2 ) { } } | return ! ( stack1 . isEmpty ( ) || stack2 . isEmpty ( ) ) && stack1 . isStackable ( ) && stack1 . getItem ( ) == stack2 . getItem ( ) && ( ! stack2 . getHasSubtypes ( ) || stack2 . getMetadata ( ) == stack1 . getMetadata ( ) ) && ItemStack . areItemStackTagsEqual ( stack2 , stack1 ) ; |
public class PropertyNameResolver { /** * Remove the last property expresson from the current expression .
* @ param expression The property expression
* @ return The new expression value , with first property
* expression removed - null if there are no more expressions */
public String remove ( String expression ) { } } | if ( expression == null || expression . length ( ) == 0 ) { return null ; } String property = next ( expression ) ; if ( expression . length ( ) == property . length ( ) ) { return null ; } int start = property . length ( ) ; if ( expression . charAt ( start ) == Nested ) start ++ ; return expression . substring ( start ) ; |
public class TimeZoneFormat { /** * Sets the decimal digit characters used for localized GMT format .
* @ param digits a string contains the decimal digit characters from 0 to 9 n the ascending order .
* @ return this object .
* @ throws IllegalArgumentException when the string did not contain ten characters .
* @ throws UnsupportedOperationException when this object is frozen .
* @ see # getGMTOffsetDigits ( ) */
public TimeZoneFormat setGMTOffsetDigits ( String digits ) { } } | if ( isFrozen ( ) ) { throw new UnsupportedOperationException ( "Attempt to modify frozen object" ) ; } if ( digits == null ) { throw new NullPointerException ( "Null GMT offset digits" ) ; } String [ ] digitArray = toCodePoints ( digits ) ; if ( digitArray . length != 10 ) { throw new IllegalArgumentException ( "Length of digits must be 10" ) ; } _gmtOffsetDigits = digitArray ; return this ; |
public class ClassLoaderUtil { /** * 获取 { @ link ClassLoader } < br >
* 获取顺序如下 : < br >
* < pre >
* 1 、 获取当前线程的ContextClassLoader
* 2 、 获取 { @ link ClassLoaderUtil } 类对应的ClassLoader
* 3 、 获取系统ClassLoader ( { @ link ClassLoader # getSystemClassLoader ( ) } )
* < / pre >
* @ return 类加载器 */
public static ClassLoader getClassLoader ( ) { } } | ClassLoader classLoader = getContextClassLoader ( ) ; if ( classLoader == null ) { classLoader = ClassLoaderUtil . class . getClassLoader ( ) ; if ( null == classLoader ) { classLoader = ClassLoader . getSystemClassLoader ( ) ; } } return classLoader ; |
public class DistributedSocketFactory { /** * Returns an index which is positive , but may be out of the factory list
* bounds . */
protected int selectFactoryIndex ( Object session ) throws ConnectException { } } | Random rnd ; if ( session != null ) { return session . hashCode ( ) & 0x7fffffff ; } else if ( ( rnd = mRnd ) != null ) { return rnd . nextInt ( ) >>> 1 ; } else { synchronized ( mFactories ) { return mFactoryIndex ++ & 0x7fffffff ; } } |
public class RenditionMetadata { /** * Checks if this rendition matches the given width / height / ration restrictions .
* @ param minWidth Min . width
* @ param minHeight Min . height
* @ param maxWidth Max . width
* @ param maxHeight Max . height
* @ param ratio Ratio
* @ return true if matches */
public boolean matches ( long minWidth , long minHeight , long maxWidth , long maxHeight , double ratio ) { } } | if ( minWidth > 0 && getWidth ( ) < minWidth ) { return false ; } if ( minHeight > 0 && getHeight ( ) < minHeight ) { return false ; } if ( maxWidth > 0 && getWidth ( ) > maxWidth ) { return false ; } if ( maxHeight > 0 && getHeight ( ) > maxHeight ) { return false ; } if ( ratio > 0 ) { double renditionRatio = ( double ) getWidth ( ) / ( double ) getHeight ( ) ; if ( ! Ratio . matches ( renditionRatio , ratio ) ) { return false ; } } return true ; |
public class ParaObjectUtils { /** * Constructs a new instance of a core object .
* @ param < P > the object type
* @ param type the simple name of a class
* @ return a new instance of a core class . Defaults to { @ link com . erudika . para . core . Sysprop } .
* @ see # toClass ( java . lang . String ) */
public static < P extends ParaObject > P toObject ( String type ) { } } | try { return ( P ) toClass ( type ) . getConstructor ( ) . newInstance ( ) ; } catch ( Exception ex ) { logger . error ( null , ex ) ; return null ; } |
public class ServerLogReaderTransactional { /** * Setup the input stream to be consumed by the reader , with retries on
* failures . */
private void setupIngestStreamWithRetries ( long txid ) throws IOException { } } | for ( int i = 0 ; i < inputStreamRetries ; i ++ ) { try { setupCurrentEditStream ( txid ) ; return ; } catch ( IOException e ) { if ( i == inputStreamRetries - 1 ) { throw new IOException ( "Cannot obtain stream for txid: " + txid , e ) ; } LOG . info ( "Error :" , e ) ; } sleep ( 1000 ) ; LOG . info ( "Retrying to get edit input stream for txid: " + txid + ", tried: " + ( i + 1 ) + " times" ) ; } |
public class MismatchedBasePairParameters { /** * This is an implementation for finding non - canonical base pairs when there may be missing or overhanging bases .
* @ param chains The list of chains already found to be nucleic acids .
* @ return The list of the atom groups ( residues ) that are pairs , as a Pair of nucleic acid Groups . */
@ Override public List < Pair < Group > > findPairs ( List < Chain > chains ) { } } | List < Pair < Group > > result = new ArrayList < > ( ) ; boolean lastFoundPair = false ; for ( int i = 0 ; i < chains . size ( ) ; i ++ ) { Chain c = chains . get ( i ) ; String sequence = c . getAtomSequence ( ) ; for ( int m = 0 ; m < sequence . length ( ) ; m ++ ) { boolean foundPair = false ; Integer type1 , type2 ; for ( int j = i + 1 ; j < chains . size ( ) && ! foundPair ; j ++ ) { Chain c2 = chains . get ( j ) ; if ( j > i + 1 && c . getAtomSequence ( ) . equals ( c2 . getAtomSequence ( ) ) && nonredundant ) continue ; String sequence2 = c2 . getAtomSequence ( ) ; for ( int k = c2 . getAtomSequence ( ) . length ( ) - 1 ; k >= 0 && ! foundPair ; k -- ) { if ( canonical && ! BasePairParameters . match ( sequence . charAt ( m ) , sequence2 . charAt ( k ) , useRNA ) ) continue ; Group g1 = c . getAtomGroup ( m ) ; Group g2 = c2 . getAtomGroup ( k ) ; type1 = BASE_MAP . get ( g1 . getPDBName ( ) ) ; type2 = BASE_MAP . get ( g2 . getPDBName ( ) ) ; if ( type1 == null || type2 == null ) continue ; Atom a1 = g1 . getAtom ( "C1'" ) ; Atom a2 = g2 . getAtom ( "C1'" ) ; if ( a1 == null || a2 == null ) continue ; // C1 ' - C1 ' distance is one useful criteria
if ( Math . abs ( a1 . getCoordsAsPoint3d ( ) . distance ( a2 . getCoordsAsPoint3d ( ) ) - 10.0 ) > 4.0 ) continue ; Pair < Group > ga = new Pair < > ( g1 , g2 ) ; // TODO is this call needed ? ? JD 2018-03-07
@ SuppressWarnings ( "unused" ) Matrix4d data = basePairReferenceFrame ( ga ) ; // if the stagger is greater than 2 Å , it ' s not really paired .
if ( Math . abs ( pairParameters [ 5 ] ) > maxStagger ) continue ; // similarly , extreme shear and stretch is not a good base pair
if ( Math . abs ( pairParameters [ 3 ] ) > maxShear ) continue ; if ( Math . abs ( pairParameters [ 4 ] ) > maxStretch ) continue ; // if the propeller is ridiculous it ' s also not that good of a pair .
if ( Math . abs ( pairParameters [ 1 ] ) > maxPropeller ) { continue ; } result . add ( ga ) ; pairingNames . add ( useRNA ? BASE_LIST_RNA [ type1 ] + BASE_LIST_RNA [ type2 ] : BASE_LIST_DNA [ type1 ] + BASE_LIST_DNA [ type2 ] ) ; foundPair = true ; } if ( ! foundPair && lastFoundPair ) { if ( pairSequence . length ( ) > 0 && pairSequence . charAt ( pairSequence . length ( ) - 1 ) != ' ' ) pairSequence += ' ' ; } if ( foundPair ) pairSequence += ( c . getAtomSequence ( ) . charAt ( i ) ) ; lastFoundPair = foundPair ; } } } return result ; |
public class AfplibPackageImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
public EEnum getResourceObjectIncludeObjType ( ) { } } | if ( resourceObjectIncludeObjTypeEEnum == null ) { resourceObjectIncludeObjTypeEEnum = ( EEnum ) EPackage . Registry . INSTANCE . getEPackage ( AfplibPackage . eNS_URI ) . getEClassifiers ( ) . get ( 189 ) ; } return resourceObjectIncludeObjTypeEEnum ; |
public class AutoPrefixerPostProcessor { /** * Initialize the postprocessor */
private void initialize ( JawrConfig config ) { } } | StopWatch stopWatch = new StopWatch ( "Initializing JS engine for Autoprefixer" ) ; stopWatch . start ( ) ; // Load JavaScript Script Engine
String script = config . getProperty ( AUTOPREFIXER_SCRIPT_LOCATION , AUTOPREFIXER_SCRIPT_DEFAULT_LOCATION ) ; String jsEngineName = config . getJavascriptEngineName ( AUTOPREFIXER_JS_ENGINE ) ; jsEngine = new JavascriptEngine ( jsEngineName , true ) ; jsEngine . getBindings ( ) . put ( "logger" , LOGGER ) ; try ( InputStream inputStream = getResourceInputStream ( config , script ) ) { jsEngine . evaluate ( "autoprefixer.js" , inputStream ) ; } catch ( IOException e ) { throw new BundlingProcessException ( e ) ; } String strOptions = config . getProperty ( AUTOPREFIXER_SCRIPT_OPTIONS , AUTOPREFIXER_DEFAULT_OPTIONS ) ; this . options = jsEngine . execEval ( strOptions ) ; jsEngine . evaluate ( "initAutoPrefixer.js" , String . format ( "if(logger.isDebugEnabled()){ logger.debug('Autoprefixer config : '+autoprefixer(%s).info());}" , strOptions ) ) ; jsEngine . evaluate ( "jawrAutoPrefixerProcess.js" , "function process(cssSource, opts){\n" + "var result = autoprefixer.process.apply(autoprefixer, [cssSource, opts]);\n" + "if(result.warnings){\n" + "result.warnings().forEach(function(message){\n" + "if(logger.isWarnEnabled()){\n" + "logger.warn(message.toString());\n" + "}\n" + "});}\n" + "return result.css;\n" + "}" ) ; stopWatch . stop ( ) ; if ( PERF_LOGGER . isDebugEnabled ( ) ) { PERF_LOGGER . debug ( stopWatch . shortSummary ( ) ) ; } |
public class FontSize { /** * Returns the font size expressed in pixels .
* @ return Pixels . */
public final int toPixel ( ) { } } | if ( unit == FontSizeUnit . PIXEL ) { return Math . round ( size ) ; } if ( unit == FontSizeUnit . EM ) { return Math . round ( 16 * size ) ; } if ( unit == FontSizeUnit . PERCENT ) { return Math . round ( size / 100 * 16 ) ; } if ( unit == FontSizeUnit . POINT ) { return Math . round ( size / 3 * 4 ) ; } throw new IllegalStateException ( "Unknown unit: " + unit ) ; |
public class SpeexPacketFactory { /** * Creates the appropriate { @ link SpeexPacket }
* instance based on the type . */
public static SpeexPacket create ( OggPacket packet ) { } } | // Special header types detection
if ( isSpeexSpecial ( packet ) ) { return new SpeexInfo ( packet ) ; } if ( packet . getSequenceNumber ( ) == 1 && packet . getGranulePosition ( ) == 0 ) { return new SpeexTags ( packet ) ; } return new SpeexAudioData ( packet ) ; |
public class FastMath { /** * Internal helper method for expm1
* @ param x number to compute shifted exponential
* @ param hiPrecOut receive high precision result for - 1.0 < x < 1.0
* @ return exp ( x ) - 1 */
private static double expm1 ( double x , double hiPrecOut [ ] ) { } } | if ( x != x || x == 0.0 ) { // NaN or zero
return x ; } if ( x <= - 1.0 || x >= 1.0 ) { // If not between + / - 1.0
// return exp ( x ) - 1.0;
double hiPrec [ ] = new double [ 2 ] ; exp ( x , 0.0 , hiPrec ) ; if ( x > 0.0 ) { return - 1.0 + hiPrec [ 0 ] + hiPrec [ 1 ] ; } else { final double ra = - 1.0 + hiPrec [ 0 ] ; double rb = - ( ra + 1.0 - hiPrec [ 0 ] ) ; rb += hiPrec [ 1 ] ; return ra + rb ; } } double baseA ; double baseB ; double epsilon ; boolean negative = false ; if ( x < 0.0 ) { x = - x ; negative = true ; } { int intFrac = ( int ) ( x * 1024.0 ) ; double tempA = ExpFracTable . EXP_FRAC_TABLE_A [ intFrac ] - 1.0 ; double tempB = ExpFracTable . EXP_FRAC_TABLE_B [ intFrac ] ; double temp = tempA + tempB ; tempB = - ( temp - tempA - tempB ) ; tempA = temp ; temp = tempA * HEX_40000000 ; baseA = tempA + temp - temp ; baseB = tempB + ( tempA - baseA ) ; epsilon = x - intFrac / 1024.0 ; } /* Compute expm1 ( epsilon ) */
double zb = 0.008336750013465571 ; zb = zb * epsilon + 0.041666663879186654 ; zb = zb * epsilon + 0.16666666666745392 ; zb = zb * epsilon + 0.49999999999999994 ; zb = zb * epsilon ; zb = zb * epsilon ; double za = epsilon ; double temp = za + zb ; zb = - ( temp - za - zb ) ; za = temp ; temp = za * HEX_40000000 ; temp = za + temp - temp ; zb += za - temp ; za = temp ; /* Combine the parts . expm1 ( a + b ) = expm1 ( a ) + expm1 ( b ) + expm1 ( a ) * expm1 ( b ) */
double ya = za * baseA ; // double yb = za * baseB + zb * baseA + zb * baseB ;
temp = ya + za * baseB ; double yb = - ( temp - ya - za * baseB ) ; ya = temp ; temp = ya + zb * baseA ; yb += - ( temp - ya - zb * baseA ) ; ya = temp ; temp = ya + zb * baseB ; yb += - ( temp - ya - zb * baseB ) ; ya = temp ; // ya = ya + za + baseA ;
// yb = yb + zb + baseB ;
temp = ya + baseA ; yb += - ( temp - baseA - ya ) ; ya = temp ; temp = ya + za ; // yb + = ( ya > za ) ? - ( temp - ya - za ) : - ( temp - za - ya ) ;
yb += - ( temp - ya - za ) ; ya = temp ; temp = ya + baseB ; // yb + = ( ya > baseB ) ? - ( temp - ya - baseB ) : - ( temp - baseB - ya ) ;
yb += - ( temp - ya - baseB ) ; ya = temp ; temp = ya + zb ; // yb + = ( ya > zb ) ? - ( temp - ya - zb ) : - ( temp - zb - ya ) ;
yb += - ( temp - ya - zb ) ; ya = temp ; if ( negative ) { /* Compute expm1 ( - x ) = - expm1 ( x ) / ( expm1 ( x ) + 1) */
double denom = 1.0 + ya ; double denomr = 1.0 / denom ; double denomb = - ( denom - 1.0 - ya ) + yb ; double ratio = ya * denomr ; temp = ratio * HEX_40000000 ; final double ra = ratio + temp - temp ; double rb = ratio - ra ; temp = denom * HEX_40000000 ; za = denom + temp - temp ; zb = denom - za ; rb += ( ya - za * ra - za * rb - zb * ra - zb * rb ) * denomr ; // f ( x ) = x / 1 + x
// Compute f ' ( x )
// Product rule : d ( uv ) = du * v + u * dv
// Chain rule : d ( f ( g ( x ) ) = f ' ( g ( x ) ) * f ( g ' ( x ) )
// d ( 1 / x ) = - 1 / ( x * x )
// d ( 1/1 + x ) = - 1 / ( ( 1 + x ) ^ 2 ) * 1 = - 1 / ( ( 1 + x ) * ( 1 + x ) )
// d ( x / 1 + x ) = - x / ( ( 1 + x ) ( 1 + x ) ) + 1/1 + x = 1 / ( ( 1 + x ) ( 1 + x ) )
// Adjust for yb
rb += yb * denomr ; // numerator
rb += - ya * denomb * denomr * denomr ; // denominator
// negate
ya = - ra ; yb = - rb ; } if ( hiPrecOut != null ) { hiPrecOut [ 0 ] = ya ; hiPrecOut [ 1 ] = yb ; } return ya + yb ; |
public class PrefsTransformer { /** * Gets the net transform .
* @ param typeName the type name
* @ return the net transform */
static PrefsTransform getNetTransform ( TypeName typeName ) { } } | if ( URL . class . getName ( ) . equals ( typeName . toString ( ) ) ) { return new UrlPrefsTransform ( ) ; } return null ; |
public class PackedDecimal { /** * Verschiebt den Dezimalpunkt um n Stellen nach links .
* @ param n Anzahl Stellen
* @ return eine neue { @ link PackedDecimal } */
public PackedDecimal movePointLeft ( int n ) { } } | BigDecimal result = toBigDecimal ( ) . movePointLeft ( n ) ; return PackedDecimal . valueOf ( result ) ; |
public class MicrochipPotentiometerDeviceController { /** * Sets the wiper ' s value in the device .
* @ param channel Which wiper
* @ param value The wiper ' s value
* @ param nonVolatile volatile or non - volatile value
* @ throws IOException Thrown if communication fails or device returned a malformed result */
public void setValue ( final DeviceControllerChannel channel , final int value , final boolean nonVolatile ) throws IOException { } } | if ( channel == null ) { throw new RuntimeException ( "null-channel is not allowed. For devices " + "knowing just one wiper Channel.A is mandatory for " + "parameter 'channel'" ) ; } if ( value < 0 ) { throw new RuntimeException ( "only positive values are allowed! Got value '" + value + "' for writing to channel '" + channel . name ( ) + "'" ) ; } // choose proper memory address ( see TABLE 4-1)
byte memAddr = nonVolatile ? channel . getNonVolatileMemoryAddress ( ) : channel . getVolatileMemoryAddress ( ) ; // write the value to the device
write ( memAddr , value ) ; |
public class MediaType { /** * Return a replica of this instance with its quality value removed .
* @ return the same instance if the media type doesn ' t contain a quality value , or a new one otherwise */
public MediaType removeQualityValue ( ) { } } | if ( ! this . parameters . containsKey ( PARAM_QUALITY_FACTOR ) ) { return this ; } Map < String , String > params = new LinkedHashMap < String , String > ( this . parameters ) ; params . remove ( PARAM_QUALITY_FACTOR ) ; return new MediaType ( this , params ) ; |
public class ElasticsearchClusterRunner { /** * Return a master node .
* @ return master node */
public synchronized Node masterNode ( ) { } } | final ClusterState state = client ( ) . admin ( ) . cluster ( ) . prepareState ( ) . execute ( ) . actionGet ( ) . getState ( ) ; final String name = state . nodes ( ) . getMasterNode ( ) . getName ( ) ; return getNode ( name ) ; |
public class RomanticTransaction { @ Override public void begin ( ) throws NotSupportedException , SystemException { } } | if ( ThreadCacheContext . exists ( ) ) { // in action or task
requestPath = ThreadCacheContext . findRequestPath ( ) ; entryMethod = ThreadCacheContext . findEntryMethod ( ) ; userBean = ThreadCacheContext . findUserBean ( ) ; } transactionBeginMillis = System . currentTimeMillis ( ) ; super . begin ( ) ; // actually begin here
saveRomanticTransactionToThread ( ) ; |
public class AppointmentGridScreen { /** * SetupSFields Method . */
public void setupSFields ( ) { } } | this . getRecord ( Appointment . APPOINTMENT_FILE ) . getField ( Appointment . START_DATE_TIME ) . setupDefaultView ( this . getNextLocation ( ScreenConstants . NEXT_LOGICAL , ScreenConstants . ANCHOR_DEFAULT ) , this , ScreenConstants . DEFAULT_DISPLAY ) ; this . getRecord ( Appointment . APPOINTMENT_FILE ) . getField ( Appointment . END_DATE_TIME ) . setupDefaultView ( this . getNextLocation ( ScreenConstants . NEXT_LOGICAL , ScreenConstants . ANCHOR_DEFAULT ) , this , ScreenConstants . DEFAULT_DISPLAY ) ; this . getRecord ( Appointment . APPOINTMENT_FILE ) . getField ( Appointment . DESCRIPTION ) . setupDefaultView ( this . getNextLocation ( ScreenConstants . NEXT_LOGICAL , ScreenConstants . ANCHOR_DEFAULT ) , this , ScreenConstants . DEFAULT_DISPLAY ) ; this . getRecord ( Appointment . APPOINTMENT_FILE ) . getField ( Appointment . CALENDAR_CATEGORY_ID ) . setupDefaultView ( this . getNextLocation ( ScreenConstants . NEXT_LOGICAL , ScreenConstants . ANCHOR_DEFAULT ) , this , ScreenConstants . DEFAULT_DISPLAY ) ; |
public class AAFClient { /** * Returns a Post Object . . . same as " create "
* @ param cls
* @ return
* @ throws APIException */
public < T > Post < T > post ( Class < T > cls ) throws APIException { } } | return new Post < T > ( this , getDF ( cls ) ) ; |
public class GBlurImageOps { /** * Applies a median filter .
* @ param input Input image . Not modified .
* @ param output ( Optional ) Storage for output image , Can be null . Modified .
* @ param radius Radius of the median blur function .
* @ param < T > Input image type .
* @ return Output blurred image . */
public static < T extends ImageBase < T > > T median ( T input , @ Nullable T output , int radius , @ Nullable WorkArrays work ) { } } | if ( input instanceof GrayU8 ) { return ( T ) BlurImageOps . median ( ( GrayU8 ) input , ( GrayU8 ) output , radius , ( IWorkArrays ) work ) ; } else if ( input instanceof GrayF32 ) { return ( T ) BlurImageOps . median ( ( GrayF32 ) input , ( GrayF32 ) output , radius ) ; } else if ( input instanceof Planar ) { return ( T ) BlurImageOps . median ( ( Planar ) input , ( Planar ) output , radius , work ) ; } else { throw new IllegalArgumentException ( "Unsupported image type" ) ; } |
public class CollectorUtils { /** * Find the item for which the supplied projection returns the minimum value ( variant for non - naturally - comparable
* projected values ) .
* @ param projection The projection to apply to each item .
* @ param comparator The comparator to use to compare the projected values .
* @ param < T > The type of each item .
* @ param < Y > The type of the projected value to compare on .
* @ return The collector . */
public static < T , Y > Collector < T , ? , Optional < T > > minBy ( Function < T , Y > projection , Comparator < Y > comparator ) { } } | return Collectors . minBy ( ( a , b ) -> { Y element1 = projection . apply ( a ) ; Y element2 = projection . apply ( b ) ; return comparator . compare ( element1 , element2 ) ; } ) ; |
public class GrpcTrailersUtil { /** * Converts the given gRPC status code , and optionally an error message , to headers . The headers will be
* either trailers - only or normal trailers based on { @ code headersSent } , whether leading headers have
* already been sent to the client . */
public static HttpHeaders statusToTrailers ( int code , @ Nullable String message , boolean headersSent ) { } } | final HttpHeaders trailers ; if ( headersSent ) { // Normal trailers .
trailers = new DefaultHttpHeaders ( ) ; } else { // Trailers only response
trailers = new DefaultHttpHeaders ( true , 3 , true ) . status ( HttpStatus . OK ) . set ( HttpHeaderNames . CONTENT_TYPE , "application/grpc+proto" ) ; } trailers . add ( GrpcHeaderNames . GRPC_STATUS , Integer . toString ( code ) ) ; if ( message != null ) { trailers . add ( GrpcHeaderNames . GRPC_MESSAGE , StatusMessageEscaper . escape ( message ) ) ; } return trailers ; |
public class AWSUtil { /** * If the provider is ASSUME _ ROLE , then the credentials for assuming this role are determined
* recursively .
* @ param configProps the configuration properties
* @ param configPrefix the prefix of the config properties for this credentials provider ,
* e . g . aws . credentials . provider for the base credentials provider ,
* aws . credentials . provider . role . provider for the credentials provider
* for assuming a role , and so on . */
private static AWSCredentialsProvider getCredentialsProvider ( final Properties configProps , final String configPrefix ) { } } | CredentialProvider credentialProviderType ; if ( ! configProps . containsKey ( configPrefix ) ) { if ( configProps . containsKey ( AWSConfigConstants . accessKeyId ( configPrefix ) ) && configProps . containsKey ( AWSConfigConstants . secretKey ( configPrefix ) ) ) { // if the credential provider type is not specified , but the Access Key ID and Secret Key are given , it will default to BASIC
credentialProviderType = CredentialProvider . BASIC ; } else { // if the credential provider type is not specified , it will default to AUTO
credentialProviderType = CredentialProvider . AUTO ; } } else { credentialProviderType = CredentialProvider . valueOf ( configProps . getProperty ( configPrefix ) ) ; } switch ( credentialProviderType ) { case ENV_VAR : return new EnvironmentVariableCredentialsProvider ( ) ; case SYS_PROP : return new SystemPropertiesCredentialsProvider ( ) ; case PROFILE : String profileName = configProps . getProperty ( AWSConfigConstants . profileName ( configPrefix ) , null ) ; String profileConfigPath = configProps . getProperty ( AWSConfigConstants . profilePath ( configPrefix ) , null ) ; return ( profileConfigPath == null ) ? new ProfileCredentialsProvider ( profileName ) : new ProfileCredentialsProvider ( profileConfigPath , profileName ) ; case BASIC : return new AWSCredentialsProvider ( ) { @ Override public AWSCredentials getCredentials ( ) { return new BasicAWSCredentials ( configProps . getProperty ( AWSConfigConstants . accessKeyId ( configPrefix ) ) , configProps . getProperty ( AWSConfigConstants . secretKey ( configPrefix ) ) ) ; } @ Override public void refresh ( ) { // do nothing
} } ; case ASSUME_ROLE : final AWSSecurityTokenService baseCredentials = AWSSecurityTokenServiceClientBuilder . standard ( ) . withCredentials ( getCredentialsProvider ( configProps , AWSConfigConstants . roleCredentialsProvider ( configPrefix ) ) ) . withRegion ( configProps . getProperty ( AWSConfigConstants . AWS_REGION ) ) . build ( ) ; return new STSAssumeRoleSessionCredentialsProvider . Builder ( configProps . getProperty ( AWSConfigConstants . roleArn ( configPrefix ) ) , configProps . getProperty ( AWSConfigConstants . roleSessionName ( configPrefix ) ) ) . withExternalId ( configProps . getProperty ( AWSConfigConstants . externalId ( configPrefix ) ) ) . withStsClient ( baseCredentials ) . build ( ) ; default : case AUTO : return new DefaultAWSCredentialsProviderChain ( ) ; } |
public class OptionsApi { /** * Replace old options with new .
* The POST operation will replace CloudCluster / Options with new values
* @ param body Body Data ( required )
* @ return ApiResponse & lt ; OptionsPostResponseStatusSuccess & gt ;
* @ throws ApiException If fail to call the API , e . g . server error or cannot deserialize the response body */
public ApiResponse < OptionsPostResponseStatusSuccess > optionsPostWithHttpInfo ( OptionsPost body ) throws ApiException { } } | com . squareup . okhttp . Call call = optionsPostValidateBeforeCall ( body , null , null ) ; Type localVarReturnType = new TypeToken < OptionsPostResponseStatusSuccess > ( ) { } . getType ( ) ; return apiClient . execute ( call , localVarReturnType ) ; |
public class PrcRevealTaxCat { /** * < p > Process entity request . < / p >
* @ param pAddParam additional param
* @ param pRequestData Request Data
* @ throws Exception - an exception */
@ Override public final void process ( final Map < String , Object > pAddParam , final IRequestData pRequestData ) throws Exception { } } | String taxDestIdStr = pRequestData . getParameter ( "taxDestId" ) ; Long taxDestId = Long . parseLong ( taxDestIdStr ) ; String itemIdStr = pRequestData . getParameter ( "itemId" ) ; Long itemId = Long . parseLong ( itemIdStr ) ; String nmEnt = pRequestData . getParameter ( "nmEnt" ) ; String destTaxItemLnNm ; String itemNm ; if ( SalesInvoiceServiceLine . class . getSimpleName ( ) . equals ( nmEnt ) ) { destTaxItemLnNm = DestTaxServSelLn . class . getSimpleName ( ) . toUpperCase ( ) ; itemNm = ServiceToSale . class . getSimpleName ( ) . toUpperCase ( ) ; } else if ( PurchaseInvoiceServiceLine . class . getSimpleName ( ) . equals ( nmEnt ) ) { destTaxItemLnNm = DestTaxServPurchLn . class . getSimpleName ( ) . toUpperCase ( ) ; itemNm = ServicePurchased . class . getSimpleName ( ) . toUpperCase ( ) ; } else if ( PurchaseInvoiceLine . class . getSimpleName ( ) . equals ( nmEnt ) || SalesInvoiceLine . class . getSimpleName ( ) . equals ( nmEnt ) || SalesReturnLine . class . getSimpleName ( ) . equals ( nmEnt ) || PurchaseReturnLine . class . getSimpleName ( ) . equals ( nmEnt ) ) { destTaxItemLnNm = DestTaxGoodsLn . class . getSimpleName ( ) . toUpperCase ( ) ; itemNm = InvItem . class . getSimpleName ( ) . toUpperCase ( ) ; } else { throw new ExceptionWithCode ( ExceptionWithCode . WRONG_PARAMETER , "Wrong line type " + nmEnt ) ; } String query = lazyGetQueryRevealTaxCat ( ) ; query = query . replace ( ":ITEMNM" , itemNm ) ; query = query . replace ( ":DESTTAXITEMLNNM" , destTaxItemLnNm ) ; query = query . replace ( ":ITEMID" , itemId . toString ( ) ) ; query = query . replace ( ":TAXDESTID" , taxDestId . toString ( ) ) ; InvItemTaxCategory taxCategory = new InvItemTaxCategory ( ) ; IRecordSet < RS > recordSet = null ; AccSettings as = ( AccSettings ) pAddParam . get ( "accSet" ) ; RoundingMode rounding = as . getSalTaxRoundMode ( ) ; try { this . srvDatabase . setIsAutocommit ( false ) ; this . srvDatabase . setTransactionIsolation ( ISrvDatabase . TRANSACTION_READ_UNCOMMITTED ) ; this . srvDatabase . beginTransaction ( ) ; recordSet = getSrvDatabase ( ) . retrieveRecords ( query ) ; if ( recordSet . moveToFirst ( ) ) { Long dtlId = recordSet . getLong ( "DTLID" ) ; Integer tdrm = null ; Long tcId = recordSet . getLong ( "DTCID" ) ; String tcd = null ; String tcn = null ; Double tcRate = null ; if ( dtlId == null ) { tcn = recordSet . getString ( "OTCNAME" ) ; tcd = recordSet . getString ( "OTCDESCR" ) ; tcId = recordSet . getLong ( "OTCID" ) ; tcRate = recordSet . getDouble ( "OTCRATE" ) ; } else if ( tcId != null ) { tdrm = recordSet . getInteger ( "DTRM" ) ; tcd = recordSet . getString ( "DTCDESCR" ) ; tcn = recordSet . getString ( "DTCNAME" ) ; tcRate = recordSet . getDouble ( "DTCRATE" ) ; } taxCategory . setItsId ( tcId ) ; taxCategory . setItsName ( tcn ) ; taxCategory . setTaxesDescription ( tcd ) ; if ( tdrm != null ) { rounding = RoundingMode . class . getEnumConstants ( ) [ tdrm ] ; } if ( tcRate != null ) { taxCategory . setAggrOnlyPercent ( BigDecimal . valueOf ( tcRate ) ) ; } if ( recordSet . moveToNext ( ) ) { throw new ExceptionWithCode ( ExceptionWithCode . SOMETHING_WRONG , "There are multiply tax category results for item id/tax dest.id/entity: " + itemId + "/" + taxDestId + "/" + nmEnt ) ; } } this . srvDatabase . commitTransaction ( ) ; } catch ( Exception ex ) { this . srvDatabase . rollBackTransaction ( ) ; throw ex ; } finally { if ( recordSet != null ) { recordSet . close ( ) ; } this . srvDatabase . releaseResources ( ) ; } pRequestData . setAttribute ( "taxRounding" , rounding ) ; pRequestData . setAttribute ( "taxCategory" , taxCategory ) ; |
public class FileUtil { /** * Copies source file to target .
* @ param source source file to copy .
* @ param target destination to copy to .
* @ return target as File .
* @ throws IOException when unable to copy . */
public static File copyFile ( String source , String target ) throws IOException { } } | FileChannel inputChannel = null ; FileChannel outputChannel = null ; try { inputChannel = new FileInputStream ( source ) . getChannel ( ) ; outputChannel = new FileOutputStream ( target ) . getChannel ( ) ; outputChannel . transferFrom ( inputChannel , 0 , inputChannel . size ( ) ) ; } finally { if ( inputChannel != null ) { inputChannel . close ( ) ; } if ( outputChannel != null ) { outputChannel . close ( ) ; } } return new File ( target ) ; |
public class Indexers { /** * Creates a function that maps multidimensional indices to 1D indices .
* The function will create consecutive 1D indices for indices that
* are given in colexicographical order .
* @ param size The size of the array to index
* @ return The indexer function
* @ throws NullPointerException If the given size is < code > null < / code > . */
public static ToIntFunction < IntTuple > colexicographicalIndexer ( IntTuple size ) { } } | Objects . requireNonNull ( size , "The size is null" ) ; IntTuple sizeProducts = IntTupleFunctions . exclusiveScan ( size , 1 , ( a , b ) -> a * b , null ) ; return indices -> IntTuples . dot ( indices , sizeProducts ) ; |
public class KmeansCalculator { /** * 配列の平均値を算出する 。
* @ param base ベース配列
* @ param target 平均算出対象配列
* @ return 平均値配列 */
protected static double [ ] average ( double [ ] base , double [ ] target ) { } } | int dataNum = base . length ; double [ ] average = new double [ dataNum ] ; for ( int index = 0 ; index < dataNum ; index ++ ) { average [ index ] = ( base [ index ] + target [ index ] ) / 2.0 ; } return average ; |
public class ResponseValidator { /** * validate a given response content object with media content type " application / json "
* uri , httpMethod , statusCode , DEFAULT _ MEDIA _ TYPE is to locate the schema to validate
* @ param responseContent response content needs to be validated
* @ param uri original uri of the request
* @ param httpMethod eg . " put " or " get "
* @ param statusCode eg . 200 , 400
* @ return Status */
public Status validateResponseContent ( Object responseContent , String uri , String httpMethod , String statusCode ) { } } | return validateResponseContent ( responseContent , uri , httpMethod , statusCode , JSON_MEDIA_TYPE ) ; |
public class OPSHandler { /** * condition2 is false . */
protected void checkDependentCondition ( MessageId id , boolean condition1 , boolean condition2 , EPUBLocation location ) { } } | if ( condition1 && ! condition2 ) { report . message ( id , location ) ; } |
public class StringUtils { /** * Convert evaluated attribute value into a String . */
String convertToString ( Object value ) { } } | if ( value == null ) { return null ; } else if ( value instanceof String ) { return ( String ) value ; } else if ( value instanceof List ) { List < ? > list = ( ( List < ? > ) value ) ; if ( list . size ( ) == 0 ) { return EvaluationContext . EMPTY_STRING ; } else if ( list . size ( ) == 1 ) { String strValue = String . valueOf ( list . get ( 0 ) ) ; return escapeValue ( strValue ) ; } else { StringBuilder builder = new StringBuilder ( ) ; Iterator < ? > iterator = list . iterator ( ) ; while ( iterator . hasNext ( ) ) { String strValue = String . valueOf ( iterator . next ( ) ) ; strValue = escapeValue ( strValue ) ; builder . append ( strValue ) ; if ( iterator . hasNext ( ) ) { builder . append ( ", " ) ; } } return builder . toString ( ) ; } } else if ( value instanceof String [ ] ) { String [ ] array = ( String [ ] ) value ; if ( array . length == 0 ) { return EvaluationContext . EMPTY_STRING ; } else if ( array . length == 1 ) { return escapeValue ( array [ 0 ] ) ; } else { StringBuilder builder = new StringBuilder ( ) ; for ( int i = 0 ; i < array . length ; i ++ ) { String strValue = escapeValue ( array [ i ] ) ; builder . append ( strValue ) ; if ( i + 1 < array . length ) { builder . append ( ", " ) ; } } return builder . toString ( ) ; } } else if ( value . getClass ( ) . isArray ( ) ) { int size = Array . getLength ( value ) ; if ( size == 0 ) { return EvaluationContext . EMPTY_STRING ; } else if ( size == 1 ) { String strValue = String . valueOf ( Array . get ( value , 0 ) ) ; return escapeValue ( strValue ) ; } else { StringBuilder builder = new StringBuilder ( ) ; for ( int i = 0 ; i < size ; i ++ ) { String strValue = String . valueOf ( Array . get ( value , i ) ) ; strValue = escapeValue ( strValue ) ; builder . append ( strValue ) ; if ( i + 1 < size ) { builder . append ( ", " ) ; } } return builder . toString ( ) ; } } else { return value . toString ( ) ; } |
public class GuildController { /** * Modifies the complete { @ link net . dv8tion . jda . core . entities . Role Role } set of the specified { @ link net . dv8tion . jda . core . entities . Member Member }
* < br > The provided roles will replace all current Roles of the specified Member .
* < p > < u > The new roles < b > must not < / b > contain the Public Role of the Guild < / u >
* < h1 > Warning < / h1 >
* < b > This may < u > not < / u > be used together with any other role add / remove / modify methods for the same Member
* within one event listener cycle ! The changes made by this require cache updates which are triggered by
* lifecycle events which are received later . This may only be called again once the specific Member has been updated
* by a { @ link net . dv8tion . jda . core . events . guild . member . GenericGuildMemberEvent GenericGuildMemberEvent } targeting the same Member . < / b >
* < p > Possible { @ link net . dv8tion . jda . core . requests . ErrorResponse ErrorResponses } caused by
* the returned { @ link net . dv8tion . jda . core . requests . RestAction RestAction } include the following :
* < ul >
* < li > { @ link net . dv8tion . jda . core . requests . ErrorResponse # MISSING _ PERMISSIONS MISSING _ PERMISSIONS }
* < br > The Members Roles could not be modified due to a permission discrepancy < / li >
* < li > { @ link net . dv8tion . jda . core . requests . ErrorResponse # MISSING _ ACCESS MISSING _ ACCESS }
* < br > We were removed from the Guild before finishing the task < / li >
* < li > { @ link net . dv8tion . jda . core . requests . ErrorResponse # UNKNOWN _ MEMBER UNKNOWN _ MEMBER }
* < br > The target Member was removed from the Guild before finishing the task < / li >
* < / ul >
* @ param member
* A { @ link net . dv8tion . jda . core . entities . Member Member } of which to override the Roles of
* @ param roles
* New collection of { @ link net . dv8tion . jda . core . entities . Role Roles } for the specified Member
* @ throws net . dv8tion . jda . core . exceptions . InsufficientPermissionException
* If the currently logged in account does not have { @ link net . dv8tion . jda . core . Permission # MANAGE _ ROLES Permission . MANAGE _ ROLES }
* @ throws net . dv8tion . jda . core . exceptions . HierarchyException
* If the provided roles are higher in the Guild ' s hierarchy
* and thus cannot be modified by the currently logged in account
* @ throws IllegalArgumentException
* < ul >
* < li > If any of the provided arguments is { @ code null } < / li >
* < li > If any of the provided arguments is not from this Guild < / li >
* < li > If any of the specified { @ link net . dv8tion . jda . core . entities . Role Roles } is managed < / li >
* < li > If any of the specified { @ link net . dv8tion . jda . core . entities . Role Roles } is the { @ code Public Role } of this Guild < / li >
* < / ul >
* @ return { @ link net . dv8tion . jda . core . requests . restaction . AuditableRestAction AuditableRestAction }
* @ see # modifyMemberRoles ( Member , Collection ) */
@ CheckReturnValue public AuditableRestAction < Void > modifyMemberRoles ( Member member , Collection < Role > roles ) { } } | Checks . notNull ( member , "Member" ) ; Checks . notNull ( roles , "Roles" ) ; checkGuild ( member . getGuild ( ) , "Member" ) ; roles . forEach ( role -> { Checks . notNull ( role , "Role in collection" ) ; checkGuild ( role . getGuild ( ) , "Role: " + role . toString ( ) ) ; checkPosition ( role ) ; } ) ; Checks . check ( ! roles . contains ( getGuild ( ) . getPublicRole ( ) ) , "Cannot add the PublicRole of a Guild to a Member. All members have this role by default!" ) ; // Return an empty rest action if there were no changes
final List < Role > memberRoles = member . getRoles ( ) ; if ( memberRoles . size ( ) == roles . size ( ) && memberRoles . containsAll ( roles ) ) return new AuditableRestAction . EmptyRestAction < > ( getGuild ( ) . getJDA ( ) ) ; // Make sure that the current managed roles are preserved and no new ones are added .
List < Role > currentManaged = memberRoles . stream ( ) . filter ( Role :: isManaged ) . collect ( Collectors . toList ( ) ) ; List < Role > newManaged = roles . stream ( ) . filter ( Role :: isManaged ) . collect ( Collectors . toList ( ) ) ; if ( ! currentManaged . isEmpty ( ) || ! newManaged . isEmpty ( ) ) { if ( ! newManaged . containsAll ( currentManaged ) ) { currentManaged . removeAll ( newManaged ) ; throw new IllegalArgumentException ( "Cannot remove managed roles from a member! Roles: " + currentManaged . toString ( ) ) ; } if ( ! currentManaged . containsAll ( newManaged ) ) { newManaged . removeAll ( currentManaged ) ; throw new IllegalArgumentException ( "Cannot add managed roles to a member! Roles: " + newManaged . toString ( ) ) ; } } // This is identical to the rest action stuff in # modifyMemberRoles ( Member , Collection < Role > , Collection < Role > )
JSONObject body = new JSONObject ( ) . put ( "roles" , roles . stream ( ) . map ( Role :: getId ) . collect ( Collectors . toList ( ) ) ) ; Route . CompiledRoute route = Route . Guilds . MODIFY_MEMBER . compile ( getGuild ( ) . getId ( ) , member . getUser ( ) . getId ( ) ) ; return new AuditableRestAction < Void > ( getGuild ( ) . getJDA ( ) , route , body ) { @ Override protected void handleResponse ( Response response , Request < Void > request ) { if ( response . isOk ( ) ) request . onSuccess ( null ) ; else request . onFailure ( response ) ; } } ; |
public class BufferByteInput { /** * { @ inheritDoc }
* @ param source { @ inheritDoc }
* @ return { @ inheritDoc } */
@ Override public BufferByteInput < T > source ( final T source ) { } } | return ( BufferByteInput < T > ) super . source ( source ) ; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.