signature stringlengths 43 39.1k | implementation stringlengths 0 450k |
|---|---|
public class Tuple3 { /** * Apply this tuple as arguments to a function . */
public final < R > R map ( Function3 < ? super T1 , ? super T2 , ? super T3 , ? extends R > function ) { } } | return function . apply ( v1 , v2 , v3 ) ; |
public class VoiceApi { /** * Perform a single - step transfer to the specified destination .
* @ param connId The connection ID of the call to transfer .
* @ param destination The number where the call should be transferred . */
public void singleStepTransfer ( String connId , String destination ) throws WorkspaceApiException { } } | this . singleStepTransfer ( connId , destination , null , null , null , null ) ; |
public class ClasspathUtils { /** * Tries to find a resource with the given name in the classpath .
* @ param resourceName the name of the resource
* @ return the URL to the found resource or < b > null < / b > if the resource
* cannot be found */
public static URL locateOnClasspath ( String resourceName ) { } } | URL url = null ; // attempt to load from the context classpath
ClassLoader loader = Thread . currentThread ( ) . getContextClassLoader ( ) ; if ( loader != null ) { url = loader . getResource ( resourceName ) ; if ( url != null ) { log . debug ( "Located '{}' in the context classpath" , resourceName ) ; } } // attempt to load from the system classpath
if ( url == null ) { url = ClassLoader . getSystemResource ( resourceName ) ; if ( url != null ) { log . debug ( "Located '{}' in the system classpath" , resourceName ) ; } } return url ; |
public class OSGiConfigUtils { /** * Get the current application name using the CDIService . During CDI startup , the CDIService knows which application it is currently working with so we can ask it !
* @ param bundleContext the context to use to find the CDIService
* @ return The application name */
public static String getCDIAppName ( BundleContext bundleContext ) { } } | String appName = null ; if ( FrameworkState . isValid ( ) ) { // Get the CDIService
CDIService cdiService = getCDIService ( bundleContext ) ; if ( cdiService != null ) { appName = cdiService . getCurrentApplicationContextID ( ) ; } } return appName ; |
public class ParentViewHolder { /** * Triggers expansion of the parent . */
@ UiThread protected void expandView ( ) { } } | setExpanded ( true ) ; onExpansionToggled ( false ) ; if ( mParentViewHolderExpandCollapseListener != null ) { mParentViewHolderExpandCollapseListener . onParentExpanded ( getAdapterPosition ( ) ) ; } |
public class RegExAnnotator { /** * Invokes this annotator ' s analysis logic . This annotator uses the java regular expression
* package to find annotations using the regular expressions defined by its configuration
* parameters .
* @ param aCAS
* the CAS to process
* @ throws AnalysisEngineProcessException
* if a failure occurs during processing .
* @ see CasAnnotator _ ImplBase # process ( CAS ) */
public void process ( CAS aCAS ) throws AnalysisEngineProcessException { } } | // add " fake " separator to cas text , computes offsets
final int [ ] offsets ; StringBuilder sb = new StringBuilder ( ) ; try { int currPos = 0 ; offsets = new int [ ( ( int ) ( aCAS . getDocumentText ( ) . length ( ) * 1.7 ) ) + 100 ] ; Collection < Token > tokens = JCasUtil . select ( aCAS . getJCas ( ) , Token . class ) ; for ( final Token token : tokens ) { // System . out . println ( token . getCoveredText ( ) + " [ "
// + token . getBegin ( ) + " : " + token . getEnd ( ) + " ] " ) ;
sb . append ( token . getCoveredText ( ) + TOKEN_SEPARATOR ) ; for ( int i = 0 ; i < ( token . getEnd ( ) - token . getBegin ( ) ) ; i ++ ) { offsets [ currPos ++ ] = token . getBegin ( ) + i ; } offsets [ currPos ++ ] = token . getEnd ( ) ; offsets [ currPos ++ ] = token . getEnd ( ) ; } } catch ( CASException e ) { throw new AnalysisEngineProcessException ( e ) ; } final String matchValue = sb . toString ( ) ; // iterate over all concepts one after the other to process them
for ( int i = 0 ; i < this . regexConcepts . length ; i ++ ) { // System . out . println ( this . regexConcepts [ i ] ) ;
// list of all annotation that must be added to the CAS for this
// concept
ArrayList < FeatureStructure > annotsToAdd = new ArrayList < FeatureStructure > ( ) ; // get the rules for the current concept
Rule [ ] conceptRules = this . regexConcepts [ i ] . getRules ( ) ; boolean foundMatch = false ; for ( int ruleCount = 0 ; ruleCount < conceptRules . length ; ruleCount ++ ) { // get the regex pattern for the current rule
Pattern pattern = conceptRules [ ruleCount ] . getRegexPattern ( ) ; // get the match type where the rule should be processed on
Type matchType = conceptRules [ ruleCount ] . getMatchType ( ) ; if ( null == matchType ) { // ren : dunno why it fails . . .
matchType = aCAS . getDocumentAnnotation ( ) . getType ( ) ; } // get match type iterator from the CAS
FSIterator < ? > mtIterator = aCAS . getAnnotationIndex ( matchType ) . iterator ( ) ; // / String matchValue = null ;
AnnotationFS currentAnnot = null ; // iterate over all match type annotations where the
// current rule should be processed on
while ( mtIterator . hasNext ( ) ) { // get next match type annotation
currentAnnot = ( AnnotationFS ) mtIterator . next ( ) ; // check filter features , if all conditions are true
FilterFeature [ ] filterFeatures = conceptRules [ ruleCount ] . getMatchTypeFilterFeatures ( ) ; boolean passed = true ; for ( int ff = 0 ; ff < filterFeatures . length ; ff ++ ) { // get the current filterFeature featurePath value
String featureValue = filterFeatures [ ff ] . getFeaturePath ( ) . getValue ( currentAnnot ) ; // check if feature value is set
if ( featureValue != null ) { // create matcher for the current feature value
Matcher matcher = filterFeatures [ ff ] . getPattern ( ) . matcher ( featureValue ) ; // check matches - use MATCH _ COMPLETE
if ( ! matcher . matches ( ) ) { // no match - stop processing
passed = false ; break ; } } else { // feature value not set - stop processing
passed = false ; break ; } } // check if the filter feature check passed all conditions
if ( ! passed ) { // conditions for the current annotation not passed , go on
// with the next
continue ; } // get the specified feature path value from the current
// annotation to run the regex on
// / matchValue = conceptRules [ ruleCount ] . getMatchTypeFeaturePath ( ) . getValue ( currentAnnot ) ;
// check matchValue result , if it is null we don ' t have to match
// anything and can go on with the next annotation
if ( matchValue == null ) { continue ; } // try to match the current pattern on the text
Matcher matcher = pattern . matcher ( matchValue ) ; // check the match strategy we have for this rule
// MatchStrategy - MATCH _ ALL
if ( conceptRules [ ruleCount ] . getMatchStrategy ( ) == Rule . MATCH_ALL ) { int pos = 0 ; while ( matcher . find ( pos ) ) { // we have a match
// check rule exceptions
if ( ! matchRuleExceptions ( conceptRules [ ruleCount ] . getExceptions ( ) , aCAS , currentAnnot ) ) { // create annotations and features
processConceptInstructions ( matcher , currentAnnot , matchValue , aCAS , this . regexConcepts [ i ] , ruleCount , annotsToAdd , offsets ) ; // set match found
foundMatch = true ; } // set start match position for the next match to the
// current end match position
if ( matcher . end ( ) == pos ) { // Special case : matched the empty string . If at the end of the input , need
// to break .
if ( pos == matchValue . length ( ) ) { break ; } // Otherwise increment search pos so as not to loop .
++ pos ; } else { // Default case : match was non - empty .
pos = matcher . end ( ) ; } } } // MatchStrategy - MATCH _ COMPLETE
else if ( conceptRules [ ruleCount ] . getMatchStrategy ( ) == Rule . MATCH_COMPLETE ) { if ( matcher . matches ( ) ) { // we have a match
// check rule exceptions
if ( ! matchRuleExceptions ( conceptRules [ ruleCount ] . getExceptions ( ) , aCAS , currentAnnot ) ) { // create annotations and features
processConceptInstructions ( matcher , currentAnnot , matchValue , aCAS , this . regexConcepts [ i ] , ruleCount , annotsToAdd , offsets ) ; // set match found
foundMatch = true ; } } } // MatchStrategy - MATCH _ FIRST
else if ( conceptRules [ ruleCount ] . getMatchStrategy ( ) == Rule . MATCH_FIRST ) { if ( matcher . find ( ) ) { // we have a match
// check rule exceptions
if ( ! matchRuleExceptions ( conceptRules [ ruleCount ] . getExceptions ( ) , aCAS , currentAnnot ) ) { // create annotations and features
processConceptInstructions ( matcher , currentAnnot , matchValue , aCAS , this . regexConcepts [ i ] , ruleCount , annotsToAdd , offsets ) ; // set match found
foundMatch = true ; } } } // all analysis is done , we can go to the next annotation
} if ( foundMatch ) { // check setting of processAllConceptRules to decide if
// we go on with the next rule or not
if ( ! this . regexConcepts [ i ] . processAllConceptRules ( ) ) { // we found a match for the current rule and we don ' t want go
// on with further rules of this concept
break ; } } } // add all created annotations to the CAS index before moving to the
// next concept
for ( int x = 0 ; x < annotsToAdd . size ( ) ; x ++ ) { aCAS . getIndexRepository ( ) . addFS ( annotsToAdd . get ( x ) ) ; } // reset last rule exception annotation since we move to the next rule
// and everything is new
this . lastRuleExceptionAnnotation = null ; } |
public class FlowTypeCheck { /** * In this case , we are assuming the environments are exclusive from each other
* ( i . e . this is the opposite of threading them through ) . For example , consider
* this case :
* < pre >
* function f ( int | null x ) - > ( bool r ) :
* return ( x is null ) | | ( x > = 0)
* < / pre >
* The environment produced by the left condition is < code > { x - > null } < / code > . We
* cannot thread this environment into the right condition as , clearly , it ' s not
* correct . Instead , we want to thread through the environment which arises on
* the assumption the fist case is false . That would be < code > { x - > ! null } < / code > .
* Finally , the resulting environment is simply the union of the two
* environments from each case .
* @ param operands
* @ param sign
* @ param environment
* @ return */
private Environment checkLogicalDisjunction ( Expr . LogicalOr expr , boolean sign , Environment environment ) { } } | Tuple < Expr > operands = expr . getOperands ( ) ; if ( sign ) { Environment [ ] refinements = new Environment [ operands . size ( ) ] ; for ( int i = 0 ; i != operands . size ( ) ; ++ i ) { refinements [ i ] = checkCondition ( operands . get ( i ) , sign , environment ) ; // The clever bit . Recalculate assuming opposite sign .
environment = checkCondition ( operands . get ( i ) , ! sign , environment ) ; } // Done .
return FlowTypeUtils . union ( refinements ) ; } else { for ( int i = 0 ; i != operands . size ( ) ; ++ i ) { environment = checkCondition ( operands . get ( i ) , sign , environment ) ; } return environment ; } |
public class ParaClient { /** * Converts Markdown to HTML .
* @ param markdownString Markdown
* @ return HTML */
public String markdownToHtml ( String markdownString ) { } } | MultivaluedMap < String , String > params = new MultivaluedHashMap < > ( ) ; params . putSingle ( "md" , markdownString ) ; return getEntity ( invokeGet ( "utils/md2html" , params ) , String . class ) ; |
public class Strman { /** * Ensures that the value ends with suffix . If it doesn ' t , it ' s appended . This operation is case sensitive .
* @ param value The input String
* @ param suffix The substr to be ensured to be right
* @ return The string which is guarenteed to start with substr */
public static String ensureRight ( final String value , final String suffix ) { } } | return ensureRight ( value , suffix , true ) ; |
public class ArraysUtil { /** * Concatenate all the arrays in the list into a vector .
* @ param arrays List of arrays .
* @ return Vector . */
public static int [ ] ConcatenateInt ( List < int [ ] > arrays ) { } } | int size = 0 ; for ( int i = 0 ; i < arrays . size ( ) ; i ++ ) { size += arrays . get ( i ) . length ; } int [ ] all = new int [ size ] ; int idx = 0 ; for ( int i = 0 ; i < arrays . size ( ) ; i ++ ) { int [ ] v = arrays . get ( i ) ; for ( int j = 0 ; j < v . length ; j ++ ) { all [ idx ++ ] = v [ i ] ; } } return all ; |
public class Fibers { /** * Blocks on the input fibers and creates a new list from the results . The result list is the same order as the
* input list .
* @ param time to wait for all requests to complete
* @ param unit the time is in
* @ param fibers to combine */
@ SuppressWarnings ( "unchecked" ) public static < V > List < V > get ( long time , TimeUnit unit , Fiber < V > ... fibers ) throws InterruptedException , TimeoutException { } } | return FiberUtil . get ( time , unit , fibers ) ; |
public class XtextSemanticSequencer { /** * Contexts :
* Disjunction returns ParameterReference
* Disjunction . Disjunction _ 1_0 returns ParameterReference
* Conjunction returns ParameterReference
* Conjunction . Conjunction _ 1_0 returns ParameterReference
* Negation returns ParameterReference
* Atom returns ParameterReference
* ParenthesizedCondition returns ParameterReference
* ParameterReference returns ParameterReference
* Constraint :
* parameter = [ Parameter | ID ] */
protected void sequence_ParameterReference ( ISerializationContext context , ParameterReference semanticObject ) { } } | if ( errorAcceptor != null ) { if ( transientValues . isValueTransient ( semanticObject , XtextPackage . Literals . PARAMETER_REFERENCE__PARAMETER ) == ValueTransient . YES ) errorAcceptor . accept ( diagnosticProvider . createFeatureValueMissing ( semanticObject , XtextPackage . Literals . PARAMETER_REFERENCE__PARAMETER ) ) ; } SequenceFeeder feeder = createSequencerFeeder ( context , semanticObject ) ; feeder . accept ( grammarAccess . getParameterReferenceAccess ( ) . getParameterParameterIDTerminalRuleCall_0_1 ( ) , semanticObject . eGet ( XtextPackage . Literals . PARAMETER_REFERENCE__PARAMETER , false ) ) ; feeder . finish ( ) ; |
public class MultimediaPickerFragment { /** * An extremely simple method for identifying multimedia . This
* could be improved , but it ' s good enough for this example .
* @ param file which could be an image or a video
* @ return true if the file can be previewed , false otherwise */
protected boolean isMultimedia ( File file ) { } } | // noinspection SimplifiableIfStatement
if ( isDir ( file ) ) { return false ; } String path = file . getPath ( ) . toLowerCase ( ) ; for ( String ext : MULTIMEDIA_EXTENSIONS ) { if ( path . endsWith ( ext ) ) { return true ; } } return false ; |
public class Relation { /** * Returns the number of & lt ; key , value & gt ; pairs in
* < code > this < / code > relation . Linear in the size of the
* relation . This may be also implemented in O ( 1 ) by
* incrementally updating a < code > size < / code > field , but that may
* complicate the code in the presence of subclassing , etc . Will
* think about it if it becomes a problem . */
public int size ( ) { } } | int size = 0 ; for ( K key : keys ( ) ) { size += getValues ( key ) . size ( ) ; } return size ; |
public class JcrRepository { /** * Determine the initial delay before the garbage collection process ( es ) should be run , based upon the supplied initial
* expression . Note that the initial expression specifies the hours and minutes in local time , whereas this method should
* return the delay in milliseconds after the current time .
* @ param initialTimeExpression the expression of the form " < code > hh : mm < / code > " ; never null
* @ return the number of milliseconds after now that the process ( es ) should be started */
protected long determineInitialDelay ( String initialTimeExpression ) { } } | Matcher matcher = RepositoryConfiguration . INITIAL_TIME_PATTERN . matcher ( initialTimeExpression ) ; if ( matcher . matches ( ) ) { int hours = Integer . valueOf ( matcher . group ( 1 ) ) ; int mins = Integer . valueOf ( matcher . group ( 2 ) ) ; LocalDateTime dateTime = LocalDateTime . of ( LocalDate . now ( ZoneOffset . UTC ) , LocalTime . of ( hours , mins ) ) ; long delay = dateTime . toInstant ( ZoneOffset . UTC ) . toEpochMilli ( ) - System . currentTimeMillis ( ) ; if ( delay <= 0L ) { delay = dateTime . plusDays ( 1 ) . toInstant ( ZoneOffset . UTC ) . toEpochMilli ( ) - System . currentTimeMillis ( ) ; } if ( delay < 10000L ) delay += 10000L ; // at least 10 second delay to let repository finish starting . . .
assert delay >= 0 ; return delay ; } String msg = JcrI18n . invalidGarbageCollectionInitialTime . text ( repositoryName ( ) , initialTimeExpression ) ; throw new IllegalArgumentException ( msg ) ; |
public class JcrTools { /** * Execute the supplied JCR - SQL2 query and , if printing is enabled , print out the results .
* @ param session the session
* @ param jcrSql2 the JCR - SQL2 query
* @ param expectedNumberOfResults the expected number of rows in the results , or - 1 if this is not to be checked
* @ param variables the variables for the query
* @ return the results
* @ throws RepositoryException */
public QueryResult printQuery ( Session session , String jcrSql2 , long expectedNumberOfResults , Variable ... variables ) throws RepositoryException { } } | Map < String , String > keyValuePairs = new HashMap < String , String > ( ) ; for ( Variable var : variables ) { keyValuePairs . put ( var . key , var . value ) ; } return printQuery ( session , jcrSql2 , Query . JCR_SQL2 , expectedNumberOfResults , keyValuePairs ) ; |
public class CodecSearchTree { /** * Search mtas tree .
* @ param treeItem the tree item
* @ param startPosition the start position
* @ param endPosition the end position
* @ param in the in
* @ param isSinglePoint the is single point
* @ param isStoreAdditionalId the is store additional id
* @ param objectRefApproxOffset the object ref approx offset
* @ param list the list
* @ param nodeRefApproxOffset the node ref approx offset
* @ param checkList the check list
* @ throws IOException Signals that an I / O exception has occurred . */
private static void searchMtasTree ( MtasTreeItem treeItem , int startPosition , int endPosition , IndexInput in , AtomicBoolean isSinglePoint , AtomicBoolean isStoreAdditionalId , long objectRefApproxOffset , ArrayList < MtasTreeHit < ? > > list , AtomicLong nodeRefApproxOffset , ArrayList < MtasTreeItem > checkList ) throws IOException { } } | if ( startPosition <= treeItem . max ) { // match current node
if ( ( endPosition >= treeItem . left ) && ( startPosition <= treeItem . right ) ) { for ( int i = 0 ; i < treeItem . objectRefs . length ; i ++ ) { list . add ( new MtasTreeHit < > ( treeItem . left , treeItem . right , treeItem . objectRefs [ i ] , treeItem . additionalIds == null ? 0 : treeItem . additionalIds [ i ] , treeItem . additionalRefs == null ? 0 : treeItem . additionalRefs [ i ] ) ) ; } } // check leftChild
if ( ! treeItem . leftChild . equals ( treeItem . ref ) ) { MtasTreeItem treeItemLeft = getMtasTreeItem ( treeItem . leftChild , isSinglePoint , isStoreAdditionalId , nodeRefApproxOffset , in , objectRefApproxOffset ) ; if ( treeItemLeft . max >= startPosition ) { checkList . add ( treeItemLeft ) ; } } // check rightChild
if ( treeItem . left <= endPosition ) { if ( ! treeItem . rightChild . equals ( treeItem . ref ) ) { MtasTreeItem treeItemRight = getMtasTreeItem ( treeItem . rightChild , isSinglePoint , isStoreAdditionalId , nodeRefApproxOffset , in , objectRefApproxOffset ) ; if ( ( treeItemRight . left >= endPosition ) || ( treeItemRight . max >= startPosition ) ) { checkList . add ( treeItemRight ) ; } } } } |
public class JavacProcessingEnvironment { /** * Convert import - style string for supported annotations into a
* regex matching that string . If the string is not a valid
* import - style string , return a regex that won ' t match anything . */
private static Pattern importStringToPattern ( boolean allowModules , String s , Processor p , Log log ) { } } | String module ; String pkg ; int slash = s . indexOf ( '/' ) ; if ( slash == ( - 1 ) ) { if ( s . equals ( "*" ) ) { return MatchingUtils . validImportStringToPattern ( s ) ; } module = allowModules ? ".*/" : "" ; pkg = s ; } else { module = Pattern . quote ( s . substring ( 0 , slash + 1 ) ) ; pkg = s . substring ( slash + 1 ) ; } if ( MatchingUtils . isValidImportString ( pkg ) ) { return Pattern . compile ( module + MatchingUtils . validImportStringToPatternString ( pkg ) ) ; } else { log . warning ( "proc.malformed.supported.string" , s , p . getClass ( ) . getName ( ) ) ; return noMatches ; // won ' t match any valid identifier
} |
public class AudioWife { /** * Sets the audio pause functionality on click event of the view passed in as a parameter . You
* can set { @ link android . widget . Button } or an { @ link android . widget . ImageView } as audio pause control . Audio pause
* functionality will be unavailable if this method is not called .
* @ see nl . changer . audiowife . AudioWife # addOnPauseClickListener ( android . view . View . OnClickListener ) */
public AudioWife setPauseView ( View pause ) { } } | if ( pause == null ) { throw new NullPointerException ( "PauseView cannot be null" ) ; } if ( mHasDefaultUi ) { Log . w ( TAG , "Already using default UI. Setting pause view will have no effect" ) ; return this ; } mPauseButton = pause ; initOnPauseClick ( ) ; return this ; |
public class DynamoDBQueryModelDAO { @ Override public T findUniqueUsingQueryModel ( QueryModel queryModel ) throws NoSuchItemException , TooManyItemsException , JeppettoException { } } | DynamoDBIterable < T > dynamoDBIterable = ( DynamoDBIterable < T > ) findUsingQueryModel ( queryModel ) ; dynamoDBIterable . setLimit ( 1 ) ; Iterator < T > results = dynamoDBIterable . iterator ( ) ; if ( ! results . hasNext ( ) ) { throw new NoSuchItemException ( ) ; } T result = results . next ( ) ; if ( dynamoDBIterable . hasResultsPastLimit ( ) ) { throw new TooManyItemsException ( ) ; } return result ; |
public class InstallerModule { /** * Search for matching installer . Extension may match multiple installer , but only one will be actually
* used ( note that installers are ordered )
* @ param type extension type
* @ param holder extensions holder bean
* @ return matching installer or null if no matching installer found */
@ SuppressWarnings ( "unchecked" ) private FeatureInstaller findInstaller ( final Class < ? > type , final ExtensionsHolder holder ) { } } | for ( FeatureInstaller installer : holder . getInstallers ( ) ) { if ( installer . matches ( type ) ) { return installer ; } } return null ; |
public class Utils { /** * Convert character to hex representation by representing each byte ' s
* value as upper - cased hex string , as in URL - encoding . */
protected static String convertNonNCNameChar ( char c ) { } } | String str = "" + c ; byte [ ] bytes = str . getBytes ( ) ; StringBuilder sb = new StringBuilder ( 4 ) ; for ( int i = 0 ; i < bytes . length ; i ++ ) { sb . append ( String . format ( "%x" , bytes [ i ] ) ) ; } return sb . toString ( ) . toUpperCase ( ) ; |
public class AnyAdapter { /** * Unmarshals an Object ( expect to be a DOM Element ) into an Attribute .
* @ see javax . xml . bind . annotation . adapters . XmlAdapter # unmarshal ( java . lang . Object ) */
public org . openprovenance . prov . model . Attribute unmarshal ( Object value ) { } } | // System . out . println ( " AnyAdapter unmarshalling for " + value ) ;
if ( value instanceof org . w3c . dom . Element ) { org . w3c . dom . Element el = ( org . w3c . dom . Element ) value ; return domProcessor . unmarshallAttribute ( el , pFactory , vconv ) ; } /* if ( value instanceof JAXBElement ) {
JAXBElement < ? > je = ( JAXBElement < ? > ) value ;
return pFactory . newAttribute ( je . getName ( ) , je . getValue ( ) , vconv ) ; */
return null ; |
public class NewChunk { /** * Append all of ' nc ' onto the current NewChunk . Kill nc . */
public void add ( NewChunk nc ) { } } | assert _cidx >= 0 ; assert _sparseLen <= _len ; assert nc . _sparseLen <= nc . _len : "_sparseLen = " + nc . _sparseLen + ", _len = " + nc . _len ; if ( nc . _len == 0 ) return ; if ( _len == 0 ) { _ls = nc . _ls ; nc . _ls = null ; _xs = nc . _xs ; nc . _xs = null ; _id = nc . _id ; nc . _id = null ; _ds = nc . _ds ; nc . _ds = null ; _sparseLen = nc . _sparseLen ; _len = nc . _len ; return ; } if ( nc . sparse ( ) != sparse ( ) ) { // for now , just make it dense
cancel_sparse ( ) ; nc . cancel_sparse ( ) ; } if ( _ds != null ) throw H2O . unimpl ( ) ; while ( _sparseLen + nc . _sparseLen >= _xs . length ) _xs = MemoryManager . arrayCopyOf ( _xs , _xs . length << 1 ) ; _ls = MemoryManager . arrayCopyOf ( _ls , _xs . length ) ; System . arraycopy ( nc . _ls , 0 , _ls , _sparseLen , nc . _sparseLen ) ; System . arraycopy ( nc . _xs , 0 , _xs , _sparseLen , nc . _sparseLen ) ; if ( _id != null ) { assert nc . _id != null ; _id = MemoryManager . arrayCopyOf ( _id , _xs . length ) ; System . arraycopy ( nc . _id , 0 , _id , _sparseLen , nc . _sparseLen ) ; for ( int i = _sparseLen ; i < _sparseLen + nc . _sparseLen ; ++ i ) _id [ i ] += _len ; } else assert nc . _id == null ; _sparseLen += nc . _sparseLen ; _len += nc . _len ; nc . _ls = null ; nc . _xs = null ; nc . _id = null ; nc . _sparseLen = nc . _len = 0 ; assert _sparseLen <= _len ; |
public class TextUtils { /** * Checks whether a text ends with a specified suffix .
* @ param caseSensitive whether the comparison must be done in a case - sensitive or case - insensitive way .
* @ param text the text to be checked for suffixes .
* @ param suffix the suffix to be searched .
* @ return whether the text ends with the suffix or not . */
public static boolean endsWith ( final boolean caseSensitive , final CharSequence text , final CharSequence suffix ) { } } | if ( text == null ) { throw new IllegalArgumentException ( "Text cannot be null" ) ; } if ( suffix == null ) { throw new IllegalArgumentException ( "Suffix cannot be null" ) ; } if ( text instanceof String && suffix instanceof String ) { return ( caseSensitive ? ( ( String ) text ) . endsWith ( ( String ) suffix ) : endsWith ( caseSensitive , text , 0 , text . length ( ) , suffix , 0 , suffix . length ( ) ) ) ; } return endsWith ( caseSensitive , text , 0 , text . length ( ) , suffix , 0 , suffix . length ( ) ) ; |
public class RuleOptionsImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
@ Override public Object eGet ( int featureID , boolean resolve , boolean coreType ) { } } | switch ( featureID ) { case SimpleAntlrPackage . RULE_OPTIONS__OPTIONS : return getOptions ( ) ; case SimpleAntlrPackage . RULE_OPTIONS__ELEMENT : return getElement ( ) ; } return super . eGet ( featureID , resolve , coreType ) ; |
public class ArrayTrie { @ Override public V get ( ByteBuffer b , int offset , int len ) { } } | int t = 0 ; for ( int i = 0 ; i < len ; i ++ ) { byte c = b . get ( offset + i ) ; int index = __lookup [ c & 0x7f ] ; if ( index >= 0 ) { int idx = t * ROW_SIZE + index ; t = _rowIndex [ idx ] ; if ( t == 0 ) return null ; } else { char [ ] big = _bigIndex == null ? null : _bigIndex [ t ] ; if ( big == null ) return null ; t = big [ c ] ; if ( t == 0 ) return null ; } } return ( V ) _value [ t ] ; |
public class HistoricJobLogManager { /** * byte array delete / / / / / */
protected void deleteExceptionByteArrayByParameterMap ( String key , Object value ) { } } | EnsureUtil . ensureNotNull ( key , value ) ; Map < String , Object > parameterMap = new HashMap < String , Object > ( ) ; parameterMap . put ( key , value ) ; getDbEntityManager ( ) . delete ( ByteArrayEntity . class , "deleteExceptionByteArraysByIds" , parameterMap ) ; |
public class Matrix4x3d { /** * Set this matrix to a rotation transformation to make < code > - z < / code >
* point along < code > dir < / code > .
* This is equivalent to calling
* { @ link # setLookAt ( Vector3dc , Vector3dc , Vector3dc ) setLookAt ( ) }
* with < code > eye = ( 0 , 0 , 0 ) < / code > and < code > center = dir < / code > .
* In order to apply the lookalong transformation to any previous existing transformation ,
* use { @ link # lookAlong ( Vector3dc , Vector3dc ) } .
* @ see # setLookAlong ( Vector3dc , Vector3dc )
* @ see # lookAlong ( Vector3dc , Vector3dc )
* @ param dir
* the direction in space to look along
* @ param up
* the direction of ' up '
* @ return this */
public Matrix4x3d setLookAlong ( Vector3dc dir , Vector3dc up ) { } } | return setLookAlong ( dir . x ( ) , dir . y ( ) , dir . z ( ) , up . x ( ) , up . y ( ) , up . z ( ) ) ; |
public class JSONArray { /** * Put or replace an int value . If the index is greater than the length of
* the JSONArray , then null elements will be added as necessary to pad
* it out .
* @ param index The subscript .
* @ param value An int value .
* @ return this
* @ throws JSONException If the index is negative . */
public JSONArray put ( int index , int value ) throws JSONException { } } | put ( index , Integer . valueOf ( value ) ) ; return this ; |
public class BitfinexSymbols { /** * returns symbol for raw order book channel
* @ param currencyPair of raw order book channel
* @ return symbol */
public static BitfinexOrderBookSymbol rawOrderBook ( final BitfinexCurrencyPair currencyPair ) { } } | return new BitfinexOrderBookSymbol ( currencyPair , BitfinexOrderBookSymbol . Precision . R0 , null , null ) ; |
public class AntClassLoader { /** * Returns a stream to read the requested resource name from this loader .
* @ param name The name of the resource for which a stream is required .
* Must not be < code > null < / code > .
* @ return a stream to the required resource or < code > null < / code > if
* the resource cannot be found on the loader ' s classpath . */
private InputStream loadResource ( String name ) { } } | // we need to search the components of the path to see if we can
// find the class we want .
InputStream stream = null ; Enumeration e = pathComponents . elements ( ) ; while ( e . hasMoreElements ( ) && stream == null ) { File pathComponent = ( File ) e . nextElement ( ) ; stream = getResourceStream ( pathComponent , name ) ; } return stream ; |
public class MediaIntents { /** * Open the media player to play the given media
* @ param path The file path of the media to play .
* @ param type The mime type
* @ return the intent */
public static Intent newPlayMediaFileIntent ( String path , String type ) { } } | return newPlayMediaIntent ( Uri . fromFile ( new File ( path ) ) , type ) ; |
public class PinEntryEditText { /** * Request focus on this PinEntryEditText */
public void focus ( ) { } } | requestFocus ( ) ; // Show keyboard
InputMethodManager inputMethodManager = ( InputMethodManager ) getContext ( ) . getSystemService ( Context . INPUT_METHOD_SERVICE ) ; inputMethodManager . showSoftInput ( this , 0 ) ; |
public class CmsListItem { /** * Adds the main widget to the list item . < p >
* In most cases , the widget will be a list item widget . If this is the case , then further calls to { @ link CmsListItem # getListItemWidget ( ) } will
* return the widget which was passed as a parameter to this method . Otherwise , the method will return null . < p >
* @ param widget the main content widget */
protected void addMainWidget ( Widget widget ) { } } | assert m_mainWidget == null ; assert m_listItemWidget == null ; if ( widget instanceof CmsListItemWidget ) { m_listItemWidget = ( CmsListItemWidget ) widget ; } m_mainWidget = widget ; |
public class KeyVaultClientBaseImpl { /** * Creates or updates a new storage account . This operation requires the storage / set permission .
* @ param vaultBaseUrl The vault name , for example https : / / myvault . vault . azure . net .
* @ param storageAccountName The name of the storage account .
* @ param resourceId Storage account resource id .
* @ param activeKeyName Current active storage account key name .
* @ param autoRegenerateKey whether keyvault should manage the storage account for the user .
* @ param regenerationPeriod The key regeneration time duration specified in ISO - 8601 format .
* @ param storageAccountAttributes The attributes of the storage account .
* @ param tags Application specific metadata in the form of key - value pairs .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ throws KeyVaultErrorException thrown if the request is rejected by server
* @ throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @ return the StorageBundle object if successful . */
public StorageBundle setStorageAccount ( String vaultBaseUrl , String storageAccountName , String resourceId , String activeKeyName , boolean autoRegenerateKey , String regenerationPeriod , StorageAccountAttributes storageAccountAttributes , Map < String , String > tags ) { } } | return setStorageAccountWithServiceResponseAsync ( vaultBaseUrl , storageAccountName , resourceId , activeKeyName , autoRegenerateKey , regenerationPeriod , storageAccountAttributes , tags ) . toBlocking ( ) . single ( ) . body ( ) ; |
public class MetadataProviderImpl { /** * Return the { @ link TypeMetadata } for a given type .
* The metadata will be created if it does not exist yet .
* @ param type
* The type .
* @ return The { @ link TypeMetadata } . */
private TypeMetadata getOrCreateTypeMetadata ( Class < ? > type ) { } } | AnnotatedType annotatedType = new AnnotatedType ( type ) ; TypeMetadata typeMetadata = metadataByType . get ( annotatedType . getAnnotatedElement ( ) ) ; if ( typeMetadata == null ) { typeMetadata = createTypeMetadata ( annotatedType ) ; LOGGER . debug ( "Registering class {}" , annotatedType . getName ( ) ) ; metadataByType . put ( annotatedType . getAnnotatedElement ( ) , typeMetadata ) ; } return typeMetadata ; |
public class BitmapIterationBenchmark { /** * General benchmark of bitmap iteration , this is a part of { @ link org . apache . druid . segment . IndexMerger # merge } and
* query processing on both realtime and historical nodes . */
@ Benchmark public int iter ( IterState state ) { } } | ImmutableBitmap bitmap = state . bitmap ; return iter ( bitmap ) ; |
public class MetamodelSource { /** * Save this instance representation as a Java source file . The Java source
* file is saved as the name adding ' _ ' prefix to the entity class name and
* into the same package as the entity class . If the source file has been
* already saved , this method deletes the file and then creates the file
* newly .
* @ throws Exception If source file saving is failed due to any exception . */
public void save ( ) throws Exception { } } | Filer filer = environment . getFiler ( ) ; FileObject resource = filer . getResource ( StandardLocation . SOURCE_OUTPUT , packageName , metamodelName + ".java" ) ; File file = new File ( resource . toUri ( ) . toString ( ) ) ; if ( file . exists ( ) ) { file . delete ( ) ; } StringBuilder source = new StringBuilder ( ) ; source . append ( String . format ( PACKAGE_TEMPLATE , packageName ) . toString ( ) ) ; source . append ( IMPORT_TEMPLATE ) ; StringBuilder buffer = new StringBuilder ( String . format ( CONSTRUCTOR_TEMPLATE , metamodelName , entityName , metamodelName , entityName ) . toString ( ) ) ; StringBuilder embedded = new StringBuilder ( ) ; Set < String > embeddeds = new HashSet < String > ( ) ; Elements elementUtils = environment . getElementUtils ( ) ; for ( VariableElement field : ElementFilter . fieldsIn ( elementUtils . getAllMembers ( element ) ) ) { if ( ! isTransient ( field ) ) { String name = field . getSimpleName ( ) . toString ( ) ; TypeMirror type = field . asType ( ) ; if ( isEmbedded ( type ) ) { if ( ! embeddeds . contains ( type . toString ( ) ) ) { embeddeds . add ( type . toString ( ) ) ; embedded . append ( toEmbedded ( type ) ) ; } String e = metamodelName + "." + toEmbeddedName ( environment . getTypeUtils ( ) . asElement ( field . asType ( ) ) . getSimpleName ( ) . toString ( ) ) ; buffer . append ( String . format ( EMBEDDED_TEMPLATE , e , name , e , name ) ) ; } else if ( isEntity ( type ) ) { // Owned child entity object .
String metamodel = toMetamodelName ( field . asType ( ) . toString ( ) ) ; buffer . append ( String . format ( METAMODEL_TEMPLATE , metamodel , name , metamodel , name ) ) ; } else if ( isComparable ( type ) ) { buffer . append ( new Formatter ( ) . format ( COMPARABLE_PROPERTY_TEMPLATE , entityName , box ( type ) , name , entityName , box ( type ) , toRawType ( box ( type ) ) , name ) . toString ( ) ) ; } else { buffer . append ( new Formatter ( ) . format ( NON_COMPARABLE_PROPERTY_TEMPLATE , entityName , box ( type ) , name , entityName , box ( type ) , toRawType ( box ( type ) ) , name ) . toString ( ) ) ; } } } source . append ( String . format ( CLASS_TEMPLATE , metamodelName , entityName , buffer . append ( embedded ) ) ) ; PrintWriter writer = new PrintWriter ( filer . createSourceFile ( packageName + "." + metamodelName , element ) . openWriter ( ) ) ; writer . write ( source . toString ( ) ) ; writer . close ( ) ; |
public class BitVector { /** * specialized implementation for the common case of setting an individual bit */
private void performSetAdj ( int position , boolean value ) { } } | checkMutable ( ) ; final int i = position >> ADDRESS_BITS ; final long m = 1L << ( position & ADDRESS_MASK ) ; if ( value ) { bits [ i ] |= m ; } else { bits [ i ] &= ~ m ; } |
public class BeanQuery { /** * Create a BeanQuery instance without the function of convert result into Map
* function . If you just want to filter bean collection , sort bean collection
* and want to get the execute result as a list of beans , you should use this
* method to create a BeanQuery instance .
* @ deprecated use { @ link # select ( Class ) } method instead */
public static < T > BeanQuery < T > selectBean ( Class < T > beanClass ) { } } | return new BeanQuery < T > ( new BeanSelector < T > ( beanClass ) ) ; |
public class JSONRPCExporter { /** * Unregister all servlets registered by this exporter . */
private void unregisterAllServlets ( ) { } } | for ( String endpoint : registeredServlets ) { registeredServlets . remove ( endpoint ) ; web . unregister ( endpoint ) ; LOG . info ( "endpoint {} unregistered" , endpoint ) ; } |
public class MyArrays { /** * 计算熵
* @ param c 概率数组
* @ return */
public static float entropy ( float [ ] c ) { } } | float e = 0.0f ; for ( int i = 0 ; i < c . length ; i ++ ) { if ( c [ i ] != 0.0 && c [ i ] != 1 ) { e -= c [ i ] * Math . log ( c [ i ] ) ; } } return e ; |
public class SQLUtils { /** * 获得主键in ( ? ) 的where子句 , 包含where关键字 。 会自动处理软删除条件
* @ param clazz
* @ return */
public static String getKeyInWhereSQL ( Class < ? > clazz ) { } } | Field keyField = DOInfoReader . getOneKeyColumn ( clazz ) ; return autoSetSoftDeleted ( "WHERE " + getColumnName ( keyField . getAnnotation ( Column . class ) ) + " in (?)" , clazz ) ; |
public class MessageCodeGenerator { /** * キーの候補を生成する 。
* < p > コンテキストのキーの形式として 、 次の優先順位に一致したものを返す 。
* @ param code 元となるメッセージのコード
* @ param objectName オブジェクト名 ( クラスのフルパス )
* @ param field フィールド名 ( 指定しない場合はnullを設定する )
* @ param fieldType フィールドのクラスタイプ ( 指定しない場合はnullを設定する )
* @ return */
public String [ ] generateCodes ( final String code , final String objectName , final String field , final Class < ? > fieldType ) { } } | final String baseCode = getPrefix ( ) . isEmpty ( ) ? code : getPrefix ( ) + code ; final List < String > codeList = new ArrayList < > ( ) ; final List < String > fieldList = new ArrayList < > ( ) ; buildFieldList ( field , fieldList ) ; addCodes ( codeList , baseCode , objectName , fieldList ) ; if ( Utils . isNotEmpty ( field ) ) { int dotIndex = field . lastIndexOf ( '.' ) ; if ( dotIndex > 0 ) { buildFieldList ( field . substring ( dotIndex + 1 ) , fieldList ) ; } } addCodes ( codeList , code , null , fieldList ) ; if ( fieldType != null ) { addCode ( codeList , code , null , fieldType . getName ( ) ) ; // 列挙型の場合は 、 java . lang . Enumとしてクラスタイプを追加する 。
if ( Enum . class . isAssignableFrom ( fieldType ) ) { addCode ( codeList , code , null , Enum . class . getName ( ) ) ; } // 数値型の場合は 、 java . lang . Numberとしてクラスタイプを追加する 。
if ( Number . class . isAssignableFrom ( fieldType ) ) { addCode ( codeList , code , null , Number . class . getName ( ) ) ; } } addCode ( codeList , code , null , null ) ; return codeList . toArray ( new String [ codeList . size ( ) ] ) ; |
public class HtmlParser { /** * Test if this tag , the prospective parent , can accept the proposed child .
* @ param child potential child tag .
* @ return true if this can contain child . */
boolean canContain ( Tag parent , Tag child ) { } } | Validate . notNull ( child ) ; if ( child . isBlock ( ) && ! parent . canContainBlock ( ) ) return false ; if ( ! child . isBlock ( ) && parent . isData ( ) ) return false ; if ( closingOptional . contains ( parent . getName ( ) ) && parent . getName ( ) . equals ( child . getName ( ) ) ) return false ; if ( parent . isEmpty ( ) || parent . isData ( ) ) return false ; // head can only contain a few . if more than head in here , modify to have a list of valids
// TODO : ( could solve this with walk for ancestor )
if ( parent . getName ( ) . equals ( "head" ) ) { if ( headTags . contains ( child . getName ( ) ) ) return true ; else return false ; } // dt and dd ( in dl )
if ( parent . getName ( ) . equals ( "dt" ) && child . getName ( ) . equals ( "dd" ) ) return false ; if ( parent . getName ( ) . equals ( "dd" ) && child . getName ( ) . equals ( "dt" ) ) return false ; return true ; |
public class IstioAssistant { /** * Deploys application reading resources from classpath , matching the given regular expression .
* For example istio / . * \ \ . json will deploy all resources ending with json placed at istio classpath directory .
* @ param pattern to match the resources . */
public List < IstioResource > deployIstioResourcesFromClasspathPattern ( String pattern ) { } } | final List < IstioResource > istioResources = new ArrayList < > ( ) ; final FastClasspathScanner fastClasspathScanner = new FastClasspathScanner ( ) ; fastClasspathScanner . matchFilenamePattern ( pattern , ( FileMatchProcessor ) ( relativePath , inputStream , lengthBytes ) -> { istioResources . addAll ( deployIstioResources ( inputStream ) ) ; inputStream . close ( ) ; } ) . scan ( ) ; return istioResources ; |
public class BackgroundApplier { /** * { @ inheritDoc } */
public Map < String , String > parse ( Map < String , String > style ) { } } | Map < String , String > mapRtn = new HashMap < String , String > ( ) ; String bg = style . get ( BACKGROUND ) ; String bgColor = null ; if ( StringUtils . isNotBlank ( bg ) ) { for ( String bgAttr : bg . split ( "(?<=\\)|\\w|%)\\s+(?=\\w)" ) ) { if ( ( bgColor = CssUtils . processColor ( bgAttr ) ) != null ) { mapRtn . put ( BACKGROUND_COLOR , bgColor ) ; break ; } } } bg = style . get ( BACKGROUND_COLOR ) ; if ( StringUtils . isNotBlank ( bg ) && ( bgColor = CssUtils . processColor ( bg ) ) != null ) { mapRtn . put ( BACKGROUND_COLOR , bgColor ) ; } if ( bgColor != null ) { bgColor = mapRtn . get ( BACKGROUND_COLOR ) ; if ( "#ffffff" . equals ( bgColor ) ) { mapRtn . remove ( BACKGROUND_COLOR ) ; } } return mapRtn ; |
public class CmsSiteManagerImpl { /** * Returns < code > true < / code > if the given root path matches any of the stored additional sites . < p >
* @ param rootPath the root path to check
* @ return < code > true < / code > if the given root path matches any of the stored additional sites */
private String lookupAdditionalSite ( String rootPath ) { } } | for ( int i = 0 , size = m_additionalSiteRoots . size ( ) ; i < size ; i ++ ) { String siteRoot = m_additionalSiteRoots . get ( i ) ; if ( rootPath . startsWith ( siteRoot + "/" ) ) { return siteRoot ; } } return null ; |
public class BusNetworkLayer { /** * Invoked when a bus line was removed from the attached network .
* < p > This function exists to allow be override to provide a specific behaviour
* when a bus line has been removed .
* @ param line is the removed line .
* @ param index is the index of the bus line .
* @ return < code > true < / code > if the events was fired , otherwise < code > false < / code > . */
protected boolean onBusLineRemoved ( BusLine line , int index ) { } } | if ( this . autoUpdate . get ( ) ) { try { removeMapLayerAt ( index ) ; return true ; } catch ( Throwable exception ) { } } return false ; |
public class WeakArrayList { /** * Fire the reference release event .
* @ param released is the count of released objects . */
protected void fireReferenceRelease ( int released ) { } } | final List < ReferenceListener > list = this . listeners ; if ( list != null && ! list . isEmpty ( ) ) { for ( final ReferenceListener listener : list ) { listener . referenceReleased ( released ) ; } } |
public class Script { /** * Verifies that this script ( interpreted as a scriptSig ) correctly spends the given scriptPubKey , enabling all
* validation rules .
* @ param txContainingThis The transaction in which this input scriptSig resides .
* Accessing txContainingThis from another thread while this method runs results in undefined behavior .
* @ param scriptSigIndex The index in txContainingThis of the scriptSig ( note : NOT the index of the scriptPubKey ) .
* @ param scriptPubKey The connected scriptPubKey containing the conditions needed to claim the value .
* @ deprecated Use { @ link # correctlySpends ( Transaction , int , TransactionWitness , Coin , Script , Set ) }
* instead so that verification flags do not change as new verification options
* are added . */
@ Deprecated public void correctlySpends ( Transaction txContainingThis , long scriptSigIndex , Script scriptPubKey ) throws ScriptException { } } | correctlySpends ( txContainingThis , scriptSigIndex , scriptPubKey , ALL_VERIFY_FLAGS ) ; |
public class GrassLegacyUtilities { /** * Fill polygon areas mapping on a raster
* @ param active the active region
* @ param polygon the jts polygon geometry
* @ param raster the empty raster data to be filled
* @ param rasterToMap the map from which the values to fill raster are taken ( if null , the value
* parameter is used )
* @ param value the value to set if a second map is not given
* @ param monitor */
public static void rasterizePolygonGeometry ( Window active , Geometry polygon , RasterData raster , RasterData rasterToMap , double value , IHMProgressMonitor monitor ) { } } | GeometryFactory gFactory = new GeometryFactory ( ) ; int rows = active . getRows ( ) ; int cols = active . getCols ( ) ; double delta = active . getWEResolution ( ) / 4.0 ; monitor . beginTask ( "rasterizing..." , rows ) ; // $ NON - NLS - 1 $
for ( int i = 0 ; i < rows ; i ++ ) { monitor . worked ( 1 ) ; // do scan line to fill the polygon
Coordinate west = rowColToCenterCoordinates ( active , i , 0 ) ; Coordinate east = rowColToCenterCoordinates ( active , i , cols - 1 ) ; LineString line = gFactory . createLineString ( new Coordinate [ ] { west , east } ) ; if ( polygon . intersects ( line ) ) { Geometry internalLines = polygon . intersection ( line ) ; Coordinate [ ] coords = internalLines . getCoordinates ( ) ; for ( int j = 0 ; j < coords . length ; j = j + 2 ) { Coordinate startC = new Coordinate ( coords [ j ] . x + delta , coords [ j ] . y ) ; Coordinate endC = new Coordinate ( coords [ j + 1 ] . x - delta , coords [ j + 1 ] . y ) ; int [ ] startcol = coordinateToNearestRowCol ( active , startC ) ; int [ ] endcol = coordinateToNearestRowCol ( active , endC ) ; if ( startcol == null || endcol == null ) { // vertex is outside of the region , ignore it
continue ; } /* * the part in between has to be filled */
for ( int k = startcol [ 1 ] ; k <= endcol [ 1 ] ; k ++ ) { if ( rasterToMap != null ) { raster . setValueAt ( i , k , rasterToMap . getValueAt ( i , k ) ) ; } else { raster . setValueAt ( i , k , value ) ; } } } } } |
public class JsonUtils { /** * Json字符串转Java对象 */
public static Object json2Object ( String jsonString , Class < ? > c ) { } } | if ( jsonString == null || "" . equals ( jsonString ) ) { return "" ; } else { try { return objectMapper . readValue ( jsonString , c ) ; } catch ( Exception e ) { log . warn ( "json error:" + e . getMessage ( ) ) ; } } return "" ; |
public class ExtendedSwidProcessor { /** * Defines product supported languages ( tag : supported _ languages ) .
* @ param supportedLanguagesList
* product supported languages
* @ return a reference to this object . */
public ExtendedSwidProcessor setSupportedLanguages ( final String ... supportedLanguagesList ) { } } | SupportedLanguagesComplexType slct = new SupportedLanguagesComplexType ( ) ; if ( supportedLanguagesList . length > 0 ) { for ( String supportedLanguage : supportedLanguagesList ) { slct . getLanguage ( ) . add ( new Token ( supportedLanguage , idGenerator . nextId ( ) ) ) ; } } swidTag . setSupportedLanguages ( slct ) ; return this ; |
public class CHFWBundle { /** * DS method for setting the event reference .
* @ param service */
@ Reference ( service = EventEngine . class , cardinality = ReferenceCardinality . MANDATORY ) protected void setEventService ( EventEngine service ) { } } | this . eventService = service ; |
public class NNStorage { /** * See if any of removed storages is " writable " again , and can be returned
* into service . */
void attemptRestoreRemovedStorage ( ) { } } | // if directory is " alive " - copy the images there . . .
if ( removedStorageDirs . size ( ) == 0 ) return ; // nothing to restore
/* We don ' t want more than one thread trying to restore at a time */
synchronized ( this . restorationLock ) { LOG . info ( "attemptRestoreRemovedStorage: check removed(failed) " + "storage. removedStorages size = " + removedStorageDirs . size ( ) ) ; for ( Iterator < StorageDirectory > it = this . removedStorageDirs . iterator ( ) ; it . hasNext ( ) ; ) { StorageDirectory sd = it . next ( ) ; File root = sd . getRoot ( ) ; LOG . info ( "attemptRestoreRemovedStorage: currently disabled dir " + root . getAbsolutePath ( ) + "; type=" + sd . getStorageDirType ( ) + ";canwrite=" + root . canWrite ( ) ) ; try { if ( root . exists ( ) && root . canWrite ( ) ) { LOG . info ( "attemptRestoreRemovedStorage: restoring dir " + sd . getRoot ( ) . getAbsolutePath ( ) ) ; this . addStorageDir ( sd ) ; // restore
it . remove ( ) ; sd . lock ( ) ; } } catch ( IOException e ) { LOG . warn ( "attemptRestoreRemovedStorage: failed to restore " + sd . getRoot ( ) . getAbsolutePath ( ) , e ) ; } } } |
public class ArrayHeap { /** * Finds the object with the minimum key , removes it from the heap ,
* and returns it .
* @ return the object with minimum key */
public E extractMin ( ) { } } | if ( isEmpty ( ) ) { throw new NoSuchElementException ( ) ; } HeapEntry < E > minEntry = indexToEntry . get ( 0 ) ; int lastIndex = size ( ) - 1 ; if ( lastIndex > 0 ) { HeapEntry < E > lastEntry = indexToEntry . get ( lastIndex ) ; swap ( lastEntry , minEntry ) ; removeLast ( minEntry ) ; heapifyDown ( lastEntry ) ; } else { removeLast ( minEntry ) ; } return minEntry . object ; |
public class WindowedEventCounter { /** * Record a new event . */
public void mark ( ) { } } | final long currentTimeMillis = clock . currentTimeMillis ( ) ; synchronized ( queue ) { if ( queue . size ( ) == capacity ) { /* * we ' re all filled up already , let ' s dequeue the oldest
* timestamp to make room for this new one . */
queue . removeFirst ( ) ; } queue . addLast ( currentTimeMillis ) ; } |
public class BaseEntity { /** * Returns the property value as a blob .
* @ throws DatastoreException if no such property
* @ throws ClassCastException if value is not a blob */
@ SuppressWarnings ( "unchecked" ) public Blob getBlob ( String name ) { } } | return ( ( Value < Blob > ) getValue ( name ) ) . get ( ) ; |
public class RawPacket { /** * Read a integer from this packet at specified offset
* @ param off start offset of the integer to be read
* @ return the integer to be read */
public int readInt ( int off ) { } } | this . buffer . rewind ( ) ; return ( ( buffer . get ( off ++ ) & 0xFF ) << 24 ) | ( ( buffer . get ( off ++ ) & 0xFF ) << 16 ) | ( ( buffer . get ( off ++ ) & 0xFF ) << 8 ) | ( buffer . get ( off ++ ) & 0xFF ) ; |
public class SimilarityCosineAlgorithm { /** * @ param secondVector Vector for search
* @ param entry Entry that must be search
* @ param < T > First vector class type
* @ param < K > axis class type
* @ return */
private < T extends FacetRank , K extends FacetRank > Optional < K > getVectorAxis ( @ NotNull Collection < K > secondVector , T entry ) { } } | return secondVector . stream ( ) . filter ( facet -> { return Facet . same ( facet . getKey ( ) , entry . getKey ( ) ) ; } ) . findFirst ( ) ; |
public class PlanAssembler { /** * Generate best cost plans for a list of derived tables , which
* we call FROM sub - queries and common table queries .
* @ param subqueryNodes - list of FROM sub - queries .
* @ return ParsedResultAccumulator */
private ParsedResultAccumulator getBestCostPlanForEphemeralScans ( List < StmtEphemeralTableScan > scans ) { } } | int nextPlanId = m_planSelector . m_planId ; boolean orderIsDeterministic = true ; boolean hasSignificantOffsetOrLimit = false ; String contentNonDeterminismMessage = null ; for ( StmtEphemeralTableScan scan : scans ) { if ( scan instanceof StmtSubqueryScan ) { nextPlanId = planForParsedSubquery ( ( StmtSubqueryScan ) scan , nextPlanId ) ; // If we can ' t plan this , then give up .
if ( ( ( StmtSubqueryScan ) scan ) . getBestCostPlan ( ) == null ) { return null ; } } else if ( scan instanceof StmtCommonTableScan ) { nextPlanId = planForCommonTableQuery ( ( StmtCommonTableScan ) scan , nextPlanId ) ; if ( ( ( StmtCommonTableScan ) scan ) . getBestCostBasePlan ( ) == null ) { return null ; } } else { throw new PlanningErrorException ( "Unknown scan plan type." ) ; } orderIsDeterministic = scan . isOrderDeterministic ( orderIsDeterministic ) ; contentNonDeterminismMessage = scan . contentNonDeterminismMessage ( contentNonDeterminismMessage ) ; hasSignificantOffsetOrLimit = scan . hasSignificantOffsetOrLimit ( hasSignificantOffsetOrLimit ) ; } // need to reset plan id for the entire SQL
m_planSelector . m_planId = nextPlanId ; return new ParsedResultAccumulator ( orderIsDeterministic , hasSignificantOffsetOrLimit , contentNonDeterminismMessage ) ; |
public class PatternToken { /** * Checks whether an exception matches .
* @ param token AnalyzedToken to check matching against
* @ return True if any of the exceptions matches ( logical disjunction ) . */
public boolean isExceptionMatched ( AnalyzedToken token ) { } } | if ( exceptionSet ) { for ( PatternToken testException : exceptionList ) { if ( ! testException . exceptionValidNext ) { if ( testException . isMatched ( token ) ) { return true ; } } } } return false ; |
public class VariationalAutoencoder { /** * This method ADDS additional TrainingListener to existing listeners
* @ param listeners */
@ Override public void addListeners ( TrainingListener ... listeners ) { } } | if ( this . trainingListeners == null ) { setListeners ( listeners ) ; return ; } for ( TrainingListener listener : listeners ) trainingListeners . add ( listener ) ; |
public class ButtonCellRenderer { /** * When the mouse is pressed the editor is invoked . If you then then drag
* the mouse to another cell before releasing it , the editor is still
* active . Make sure editing is stopped when the mouse is released . */
@ Override public void mousePressed ( MouseEvent e ) { } } | if ( table . isEditing ( ) && table . getCellEditor ( ) == this ) { isButtonColumnEditor = true ; } |
public class ManagedChannelImpl { /** * Must be run from syncContext */
private void enterIdleMode ( ) { } } | // nameResolver and loadBalancer are guaranteed to be non - null . If any of them were null ,
// either the idleModeTimer ran twice without exiting the idle mode , or the task in shutdown ( )
// did not cancel idleModeTimer , or enterIdle ( ) ran while shutdown or in idle , all of
// which are bugs .
shutdownNameResolverAndLoadBalancer ( true ) ; delayedTransport . reprocess ( null ) ; channelLogger . log ( ChannelLogLevel . INFO , "Entering IDLE state" ) ; channelStateManager . gotoState ( IDLE ) ; if ( inUseStateAggregator . isInUse ( ) ) { exitIdleMode ( ) ; } |
public class SystemObserver { /** * Return the current running mode type . May be one of
* { UI _ MODE _ TYPE _ NORMAL Configuration . UI _ MODE _ TYPE _ NORMAL } ,
* { UI _ MODE _ TYPE _ DESK Configuration . UI _ MODE _ TYPE _ DESK } ,
* { UI _ MODE _ TYPE _ CAR Configuration . UI _ MODE _ TYPE _ CAR } ,
* { UI _ MODE _ TYPE _ TELEVISION Configuration . UI _ MODE _ TYPE _ TELEVISION } ,
* { # UI _ MODE _ TYPE _ APPLIANCE Configuration . UI _ MODE _ TYPE _ APPLIANCE } , or
* { # UI _ MODE _ TYPE _ WATCH Configuration . UI _ MODE _ TYPE _ WATCH } . */
static String getUIMode ( Context context ) { } } | String mode = "UI_MODE_TYPE_UNDEFINED" ; UiModeManager modeManager = null ; try { if ( context != null ) { modeManager = ( UiModeManager ) context . getSystemService ( UI_MODE_SERVICE ) ; } if ( modeManager != null ) { switch ( modeManager . getCurrentModeType ( ) ) { case 1 : mode = "UI_MODE_TYPE_NORMAL" ; break ; case 2 : mode = "UI_MODE_TYPE_DESK" ; break ; case 3 : mode = "UI_MODE_TYPE_CAR" ; break ; case 4 : mode = "UI_MODE_TYPE_TELEVISION" ; break ; case 5 : mode = "UI_MODE_TYPE_APPLIANCE" ; break ; case 6 : mode = "UI_MODE_TYPE_WATCH" ; break ; case 0 : default : break ; } } } catch ( Exception e ) { // Have seen reports of " DeadSystemException " from UiModeManager .
} return mode ; |
public class LdapTemplate { /** * { @ inheritDoc } */
@ Override public void search ( Name base , String filter , int searchScope , boolean returningObjFlag , NameClassPairCallbackHandler handler ) { } } | search ( base , filter , getDefaultSearchControls ( searchScope , returningObjFlag , ALL_ATTRIBUTES ) , handler ) ; |
public class Story { /** * Useful when debugging a ( very short ) story , to visualise the state of the
* story . Add this call as a watch and open the extended text . A left - arrow mark
* will denote the current point of the story . It ' s only recommended that this
* is used on very short debug stories , since it can end up generate a large
* quantity of text otherwise . */
public String buildStringOfHierarchy ( ) { } } | StringBuilder sb = new StringBuilder ( ) ; getMainContentContainer ( ) . buildStringOfHierarchy ( sb , 0 , state . getCurrentPointer ( ) . resolve ( ) ) ; return sb . toString ( ) ; |
public class Provider { /** * Add a service . If a service of the same type with the same algorithm
* name exists and it was added using { @ link # putService putService ( ) } ,
* it is replaced by the new service .
* This method also places information about this service
* in the provider ' s Hashtable values in the format described in the
* < a href = " { @ docRoot } openjdk - redirect . html ? v = 8 & path = / technotes / guides / security / crypto / CryptoSpec . html " >
* Java Cryptography Architecture API Specification & amp ; Reference < / a > .
* < p > Also , if there is a security manager , its
* < code > checkSecurityAccess < / code > method is called with the string
* < code > " putProviderProperty . " + name < / code > , where < code > name < / code > is
* the provider name , to see if it ' s ok to set this provider ' s property
* values . If the default implementation of < code > checkSecurityAccess < / code >
* is used ( that is , that method is not overriden ) , then this results in
* a call to the security manager ' s < code > checkPermission < / code > method with
* a < code > SecurityPermission ( " putProviderProperty . " + name ) < / code >
* permission .
* @ param s the Service to add
* @ throws SecurityException
* if a security manager exists and its < code > { @ link
* java . lang . SecurityManager # checkSecurityAccess } < / code > method denies
* access to set property values .
* @ throws NullPointerException if s is null
* @ since 1.5 */
protected synchronized void putService ( Service s ) { } } | check ( "putProviderProperty." + name ) ; // if ( debug ! = null ) {
// debug . println ( name + " . putService ( ) : " + s ) ;
if ( s == null ) { throw new NullPointerException ( ) ; } if ( s . getProvider ( ) != this ) { throw new IllegalArgumentException ( "service.getProvider() must match this Provider object" ) ; } if ( serviceMap == null ) { serviceMap = new LinkedHashMap < ServiceKey , Service > ( ) ; } servicesChanged = true ; String type = s . getType ( ) ; String algorithm = s . getAlgorithm ( ) ; ServiceKey key = new ServiceKey ( type , algorithm , true ) ; // remove existing service
implRemoveService ( serviceMap . get ( key ) ) ; serviceMap . put ( key , s ) ; for ( String alias : s . getAliases ( ) ) { serviceMap . put ( new ServiceKey ( type , alias , true ) , s ) ; } putPropertyStrings ( s ) ; |
public class DelegatingScript { /** * Sets the delegation target . */
public void setDelegate ( Object delegate ) { } } | this . delegate = delegate ; this . metaClass = InvokerHelper . getMetaClass ( delegate . getClass ( ) ) ; |
public class IonStreamUtils { /** * writes an IonList with a series of IonBool values . This
* starts a List , writes the values ( without any annoations )
* and closes the list . For text and tree writers this is
* just a convienience , but for the binary writer it can be
* optimized internally .
* @ param values boolean values to populate the list with */
public static void writeBoolList ( IonWriter writer , boolean [ ] values ) throws IOException { } } | if ( writer instanceof _Private_ListWriter ) { ( ( _Private_ListWriter ) writer ) . writeBoolList ( values ) ; return ; } writer . stepIn ( IonType . LIST ) ; for ( int ii = 0 ; ii < values . length ; ii ++ ) { writer . writeBool ( values [ ii ] ) ; } writer . stepOut ( ) ; |
public class BeanData { /** * Gets the effective scope to use in the meta .
* @ return the scope */
public String getEffectiveMetaScope ( ) { } } | String scope = beanMetaScope ; if ( "smart" . equals ( scope ) ) { scope = typeScope ; } return "package" . equals ( scope ) ? "" : scope + " " ; |
public class DefaultDataGridURLBuilder { /** * Get a URL query parameter map that will change the data grid ' s page value to display the
* < i > previous < / i > page in a data set relative to the current page . This map also contains all of
* the other existing URL parameters . The { @ link Map } contains key / value pairs of type
* String / String [ ] .
* @ return the URL and data grid state needed to change to the < i > previous < / i > page for a data grid */
public Map getQueryParamsForPreviousPage ( ) { } } | Map params = _codec . getExistingParams ( ) ; Map newParams = new HashMap ( ) ; PagerModel pagerModel = getDataGridState ( ) . getPagerModel ( ) ; assert pagerModel != null ; addSortParams ( newParams ) ; addFilterParams ( newParams ) ; newParams . putAll ( _codec . buildPageParamMap ( new Integer ( pagerModel . getRowForPreviousPage ( ) ) , new Integer ( pagerModel . getPageSize ( ) ) ) ) ; params = mergeMaps ( params , newParams ) ; params = transformMap ( params ) ; return params ; |
public class ExtensionUtils { /** * " add " an object in a readonly { @ link Set } . This method return a new Set which contains the passed set and object
* to add .
* @ param readonly the { @ link Set } to add an object to
* @ param obj the object to add
* @ return the new { @ link Set } */
public static < T > Set < T > append ( Set < T > readonly , T obj ) { } } | Set < T > writable = readonly != null ? new HashSet < > ( readonly ) : new HashSet < > ( ) ; writable . add ( obj ) ; return writable ; |
public class FlowConfigClient { /** * Create a flow configuration
* @ param flowConfig flow configuration attributes
* @ throws RemoteInvocationException */
public void createFlowConfig ( FlowConfig flowConfig ) throws RemoteInvocationException { } } | LOG . debug ( "createFlowConfig with groupName " + flowConfig . getId ( ) . getFlowGroup ( ) + " flowName " + flowConfig . getId ( ) . getFlowName ( ) ) ; CreateIdRequest < ComplexResourceKey < FlowId , EmptyRecord > , FlowConfig > request = _flowconfigsRequestBuilders . create ( ) . input ( flowConfig ) . build ( ) ; ResponseFuture < IdResponse < ComplexResourceKey < FlowId , EmptyRecord > > > flowConfigResponseFuture = _restClient . get ( ) . sendRequest ( request ) ; flowConfigResponseFuture . getResponse ( ) ; |
public class ResourceUtils { /** * Returns a resource on the classpath as a Properties object
* @ param loader
* The classloader used to load the resource
* @ param resource
* The resource to find
* @ throws IOException
* If the resource cannot be found or read
* @ return The resource */
public static Properties getResourceAsProperties ( ClassLoader loader , String resource ) throws IOException { } } | Properties props = new Properties ( ) ; InputStream in = null ; String propfile = resource ; in = getResourceAsStream ( loader , propfile ) ; props . load ( in ) ; in . close ( ) ; return props ; |
public class EventConsumer { void readAttributeAndPush ( EventChannelStruct eventChannelStruct , EventCallBackStruct callbackStruct ) { } } | // Check if known event name
boolean found = false ; for ( int i = 0 ; ! found && i < eventNames . length ; i ++ ) found = callbackStruct . event_name . equals ( eventNames [ i ] ) ; if ( ! found ) return ; // Else do the synchronous call
DeviceAttribute deviceAttribute = null ; DevicePipe devicePipe = null ; AttributeInfoEx info = null ; DeviceInterface deviceInterface = null ; DevError [ ] err = null ; String domain_name = callbackStruct . device . name ( ) + "/" + callbackStruct . attr_name ; boolean old_transp = callbackStruct . device . get_transparency_reconnection ( ) ; callbackStruct . device . set_transparency_reconnection ( true ) ; try { callbackStruct . setSynchronousDone ( false ) ; if ( callbackStruct . event_name . equals ( eventNames [ ATT_CONF_EVENT ] ) ) { info = callbackStruct . device . get_attribute_info_ex ( callbackStruct . attr_name ) ; } else if ( callbackStruct . event_name . equals ( eventNames [ PIPE_EVENT ] ) ) { devicePipe = callbackStruct . device . readPipe ( callbackStruct . attr_name ) ; } else if ( callbackStruct . event_name . equals ( eventNames [ INTERFACE_CHANGE ] ) ) { deviceInterface = new DeviceInterface ( callbackStruct . device ) ; } else { deviceAttribute = callbackStruct . device . read_attribute ( callbackStruct . attr_name ) ; } callbackStruct . setSynchronousDone ( true ) ; // The reconnection worked fine . The heartbeat should come back now ,
// when the notifd has not closed the connection .
// Increase the counter to detect when the heartbeat is not coming back .
eventChannelStruct . has_notifd_closed_the_connection ++ ; } catch ( DevFailed e ) { err = e . errors ; } callbackStruct . device . set_transparency_reconnection ( old_transp ) ; // Build event data and push it .
// ToDo DevIntrChange
EventData eventData = new EventData ( callbackStruct . device , domain_name , callbackStruct . event_name , callbackStruct . event_type , getSource ( eventChannelStruct . consumer ) , deviceAttribute , devicePipe , info , null , deviceInterface , err ) ; if ( callbackStruct . use_ev_queue ) { EventQueue ev_queue = callbackStruct . device . getEventQueue ( ) ; ev_queue . insert_event ( eventData ) ; } else { callbackStruct . callback . push_event ( eventData ) ; } |
public class Tree { /** * Associates the specified Map ( ~ = JSON object ) container with the
* specified path . If the structure previously contained a mapping for the
* path , the old value is replaced . Sample code : < br >
* < br >
* Tree response = . . . < br >
* Tree headers = response . getMeta ( ) . putMap ( " headers " , true ) ; < br >
* headers . put ( " Content - Type " , " text / html " ) ;
* @ param path
* path with which the specified Map is to be associated
* @ param putIfAbsent
* if true and the specified key is not already associated with a
* value associates it with the given value and returns the new
* Map , else returns the previous Map
* @ return Tree of the new Map */
public Tree putMap ( String path , boolean putIfAbsent ) { } } | return putObjectInternal ( path , new LinkedHashMap < String , Object > ( ) , putIfAbsent ) ; |
public class Substance { /** * syntactic sugar */
public SubstanceInstanceComponent addInstance ( ) { } } | SubstanceInstanceComponent t = new SubstanceInstanceComponent ( ) ; if ( this . instance == null ) this . instance = new ArrayList < SubstanceInstanceComponent > ( ) ; this . instance . add ( t ) ; return t ; |
public class DiskClient { /** * Resizes the specified persistent disk . You can only increase the size of the disk .
* < p > Sample code :
* < pre > < code >
* try ( DiskClient diskClient = DiskClient . create ( ) ) {
* ProjectZoneDiskName disk = ProjectZoneDiskName . of ( " [ PROJECT ] " , " [ ZONE ] " , " [ DISK ] " ) ;
* DisksResizeRequest disksResizeRequestResource = DisksResizeRequest . newBuilder ( ) . build ( ) ;
* Operation response = diskClient . resizeDisk ( disk . toString ( ) , disksResizeRequestResource ) ;
* < / code > < / pre >
* @ param disk The name of the persistent disk .
* @ param disksResizeRequestResource
* @ throws com . google . api . gax . rpc . ApiException if the remote call fails */
@ BetaApi public final Operation resizeDisk ( String disk , DisksResizeRequest disksResizeRequestResource ) { } } | ResizeDiskHttpRequest request = ResizeDiskHttpRequest . newBuilder ( ) . setDisk ( disk ) . setDisksResizeRequestResource ( disksResizeRequestResource ) . build ( ) ; return resizeDisk ( request ) ; |
public class FailoverGroupsInner { /** * Fails over from the current primary server to this server .
* @ param resourceGroupName The name of the resource group that contains the resource . You can obtain this value from the Azure Resource Manager API or the portal .
* @ param serverName The name of the server containing the failover group .
* @ param failoverGroupName The name of the failover group .
* @ param serviceCallback the async ServiceCallback to handle successful and failed responses .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the { @ link ServiceFuture } object */
public ServiceFuture < FailoverGroupInner > beginFailoverAsync ( String resourceGroupName , String serverName , String failoverGroupName , final ServiceCallback < FailoverGroupInner > serviceCallback ) { } } | return ServiceFuture . fromResponse ( beginFailoverWithServiceResponseAsync ( resourceGroupName , serverName , failoverGroupName ) , serviceCallback ) ; |
public class IfcRepresentationItemImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
@ SuppressWarnings ( "unchecked" ) public EList < IfcStyledItem > getStyledByItem ( ) { } } | return ( EList < IfcStyledItem > ) eGet ( Ifc2x3tc1Package . Literals . IFC_REPRESENTATION_ITEM__STYLED_BY_ITEM , true ) ; |
public class RegisteredHttpServiceImpl { /** * { @ inheritDoc } */
@ Override public void unregister ( String alias ) { } } | synchronized ( servletLock ) { Servlet servlet = container . getHandlerRegistry ( ) . removeServletByAlias ( alias ) ; if ( servlet != null ) this . localServlets . remove ( servlet ) ; } |
public class NioTCPSession { /** * Blocking write using temp selector
* @ param channel
* @ param message
* @ param writeBuffer
* @ return
* @ throws IOException
* @ throws ClosedChannelException */
protected final Object blockingWrite ( SelectableChannel channel , WriteMessage message , IoBuffer writeBuffer ) throws IOException , ClosedChannelException { } } | SelectionKey tmpKey = null ; Selector writeSelector = null ; int attempts = 0 ; int bytesProduced = 0 ; try { while ( writeBuffer . hasRemaining ( ) ) { long len = doRealWrite ( channel , writeBuffer ) ; if ( len > 0 ) { attempts = 0 ; bytesProduced += len ; statistics . statisticsWrite ( len ) ; } else { attempts ++ ; if ( writeSelector == null ) { writeSelector = SelectorFactory . getSelector ( ) ; if ( writeSelector == null ) { // Continue using the main one .
continue ; } tmpKey = channel . register ( writeSelector , SelectionKey . OP_WRITE ) ; } if ( writeSelector . select ( 1000 ) == 0 ) { if ( attempts > 2 ) { throw new IOException ( "Client disconnected" ) ; } } } } if ( ! writeBuffer . hasRemaining ( ) && message . getWriteFuture ( ) != null ) { message . getWriteFuture ( ) . setResult ( Boolean . TRUE ) ; } } finally { if ( tmpKey != null ) { tmpKey . cancel ( ) ; tmpKey = null ; } if ( writeSelector != null ) { // Cancel the key .
writeSelector . selectNow ( ) ; SelectorFactory . returnSelector ( writeSelector ) ; } } scheduleWritenBytes . addAndGet ( 0 - bytesProduced ) ; return message . getMessage ( ) ; |
public class CreateDateExtensions { /** * Creates a new Date object from the given values .
* @ param year
* The year .
* @ param month
* The month .
* @ param day
* The day .
* @ param hour
* The hour .
* @ param min
* The minute .
* @ param sec
* The second .
* @ return Returns the created Date object . */
public static Date newDate ( final int year , final int month , final int day , final int hour , final int min , final int sec ) { } } | return newDate ( year , month , day , hour , min , sec , 0 ) ; |
public class CssFormatter { /** * Write a comment . The compress formatter do nothing .
* @ param msg the comment including the comment markers
* @ return a reference to this object */
CssFormatter comment ( String msg ) { } } | getOutput ( ) . append ( insets ) . append ( msg ) . append ( '\n' ) ; return this ; |
public class AsynchronousRequest { /** * For more info on exchange coins API go < a href = " https : / / wiki . guildwars2 . com / wiki / API : 2 / commerce / exchange / coins " > here < / a > < br / >
* Give user the access to { @ link Callback # onResponse ( Call , Response ) } and { @ link Callback # onFailure ( Call , Throwable ) } methods for custom interactions
* @ param currency exchange currency type
* @ param quantity The amount to exchange
* @ param callback callback that is going to be used for { @ link Call # enqueue ( Callback ) }
* @ throws GuildWars2Exception invalid value
* @ throws NullPointerException if given { @ link Callback } is empty
* @ see Exchange Exchange info */
public void getExchangeInfo ( Exchange . Type currency , long quantity , Callback < Exchange > callback ) throws GuildWars2Exception , NullPointerException { } } | isValueValid ( quantity ) ; gw2API . getExchangeInfo ( currency . name ( ) , Long . toString ( quantity ) ) . enqueue ( callback ) ; |
public class OBaseParser { /** * Parses the next word . If no word is found or the parsed word is not present in the word array received as parameter then a
* SyntaxError exception with the custom message received as parameter is thrown . It returns the word parsed if any .
* @ param iUpperCase
* True if must return UPPERCASE , otherwise false
* @ param iCustomMessage
* Custom message to include in case of SyntaxError exception
* @ param iSeparators
* Separator characters
* @ return The word parsed */
protected String parserRequiredWord ( final boolean iUpperCase , final String iCustomMessage , String iSeparators ) { } } | if ( iSeparators == null ) iSeparators = " =><(),\r\n" ; parserNextWord ( iUpperCase , iSeparators ) ; if ( parserLastWord . length ( ) == 0 ) throwSyntaxErrorException ( iCustomMessage ) ; return parserLastWord . toString ( ) ; |
public class TimestampInterval { /** * / * [ deutsch ]
* < p > Erzeugt ein unbegrenztes halb - offenes Intervall ab dem angegebenen
* Startzeitpunkt . < / p >
* @ param start timestamp of lower boundary ( inclusive )
* @ return new timestamp interval
* @ since 2.0 */
public static TimestampInterval since ( PlainTimestamp start ) { } } | Boundary < PlainTimestamp > future = Boundary . infiniteFuture ( ) ; return new TimestampInterval ( Boundary . of ( CLOSED , start ) , future ) ; |
public class RecursiveObjectWriter { /** * Copies content of one object to another object by recursively reading all
* properties from source object and then recursively writing them to
* destination object .
* @ param dest a destination object to write properties to .
* @ param src a source object to read properties from */
public static void copyProperties ( Object dest , Object src ) { } } | if ( dest == null || src == null ) return ; Map < String , Object > values = RecursiveObjectReader . getProperties ( src ) ; setProperties ( dest , values ) ; |
public class LdapCompensatingTransactionOperationFactory { /** * @ see org . springframework . transaction . compensating .
* CompensatingTransactionOperationFactory
* # createRecordingOperation ( java . lang . Object , java . lang . String ) */
public CompensatingTransactionOperationRecorder createRecordingOperation ( Object resource , String operation ) { } } | if ( ObjectUtils . nullSafeEquals ( operation , LdapTransactionUtils . BIND_METHOD_NAME ) ) { log . debug ( "Bind operation recorded" ) ; return new BindOperationRecorder ( createLdapOperationsInstance ( ( DirContext ) resource ) ) ; } else if ( ObjectUtils . nullSafeEquals ( operation , LdapTransactionUtils . REBIND_METHOD_NAME ) ) { log . debug ( "Rebind operation recorded" ) ; return new RebindOperationRecorder ( createLdapOperationsInstance ( ( DirContext ) resource ) , renamingStrategy ) ; } else if ( ObjectUtils . nullSafeEquals ( operation , LdapTransactionUtils . RENAME_METHOD_NAME ) ) { log . debug ( "Rename operation recorded" ) ; return new RenameOperationRecorder ( createLdapOperationsInstance ( ( DirContext ) resource ) ) ; } else if ( ObjectUtils . nullSafeEquals ( operation , LdapTransactionUtils . MODIFY_ATTRIBUTES_METHOD_NAME ) ) { return new ModifyAttributesOperationRecorder ( createLdapOperationsInstance ( ( DirContext ) resource ) ) ; } else if ( ObjectUtils . nullSafeEquals ( operation , LdapTransactionUtils . UNBIND_METHOD_NAME ) ) { return new UnbindOperationRecorder ( createLdapOperationsInstance ( ( DirContext ) resource ) , renamingStrategy ) ; } log . warn ( "No suitable CompensatingTransactionOperationRecorder found for method " + operation + ". Operation will not be transacted." ) ; return new NullOperationRecorder ( ) ; |
public class RestEventManager { /** * { @ inheritDoc } */
@ Override public void addAttack ( Attack attack ) { } } | // make request
target . path ( "api" ) . path ( "v1.0" ) . path ( "attacks" ) . request ( ) . header ( clientApplicationIdName , clientApplicationIdValue ) . post ( Entity . entity ( attack , MediaType . APPLICATION_JSON ) , Attack . class ) ; |
public class Utils { /** * Converts the given query JSON into a Query object
* @ param queryInputStream query JSON stream
* @ return Query object containing the query
* @ throws JsonParseException Thrown if JSON parsing failed
* @ throws JsonMappingException Thrown if there was a problem mapping the JSON
* @ throws IOException Thrown by the readValue method */
public static Query getQuery ( InputStream queryInputStream ) throws JsonParseException , JsonMappingException , IOException { } } | return JSON_MAPPER . readValue ( queryInputStream , Query . class ) ; |
public class AbstractArmeriaCentralDogmaBuilder { /** * Sets the interval between health check requests in milliseconds . The default value is
* { @ value # DEFAULT _ HEALTH _ CHECK _ INTERVAL _ MILLIS } milliseconds .
* @ param healthCheckIntervalMillis the interval between health check requests in milliseconds .
* { @ code 0 } disables health check requests . */
public final B healthCheckIntervalMillis ( long healthCheckIntervalMillis ) { } } | checkArgument ( healthCheckIntervalMillis >= 0 , "healthCheckIntervalMillis: %s (expected: >= 0)" , healthCheckIntervalMillis ) ; healthCheckInterval = Duration . ofMillis ( healthCheckIntervalMillis ) ; return self ( ) ; |
public class ExamplePnP { /** * Uses robust techniques to remove outliers */
public Se3_F64 estimateOutliers ( List < Point2D3D > observations ) { } } | // We can no longer trust that each point is a real observation . Let ' s use RANSAC to separate the points
// You will need to tune the number of iterations and inlier threshold ! ! !
ModelMatcherMultiview < Se3_F64 , Point2D3D > ransac = FactoryMultiViewRobust . pnpRansac ( new ConfigPnP ( ) , new ConfigRansac ( 300 , 1.0 ) ) ; ransac . setIntrinsic ( 0 , intrinsic ) ; // Observations must be in normalized image coordinates ! See javadoc of pnpRansac
if ( ! ransac . process ( observations ) ) throw new RuntimeException ( "Probably got bad input data with NaN inside of it" ) ; System . out . println ( "Inlier size " + ransac . getMatchSet ( ) . size ( ) ) ; Se3_F64 worldToCamera = ransac . getModelParameters ( ) ; // You will most likely want to refine this solution too . Can make a difference with real world data
RefinePnP refine = FactoryMultiView . pnpRefine ( 1e-8 , 200 ) ; Se3_F64 refinedWorldToCamera = new Se3_F64 ( ) ; // notice that only the match set was passed in
if ( ! refine . fitModel ( ransac . getMatchSet ( ) , worldToCamera , refinedWorldToCamera ) ) throw new RuntimeException ( "Refined failed! Input probably bad..." ) ; return refinedWorldToCamera ; |
public class LPAAddParameter { /** * Performs parameter child element creation in the passed in Element .
* @ param node the parent node in which to create the parameter .
* @ param name the name of the parameter to be created .
* @ param value the value of the parameter to be created . */
static void addParameterChild ( Element node , String name , String value ) { } } | if ( node != null ) { Document doc = node . getOwnerDocument ( ) ; Element parm = doc . createElement ( Constants . ELM_PARAMETER ) ; parm . setAttribute ( Constants . ATT_NAME , name ) ; parm . setAttribute ( Constants . ATT_VALUE , value ) ; /* * Set the override attribute to ' yes ' . This isn ' t persisted since
* this is determined upon loading the layout based upon the
* channel definition . But for code that references this in - memory
* value like ChannelStaticData it needs to be set . */
parm . setAttribute ( Constants . ATT_OVERRIDE , Constants . CAN_OVERRIDE ) ; node . appendChild ( parm ) ; } |
public class KeyboardManager { /** * documentation inherited from interface KeyEventDispatcher */
public boolean dispatchKeyEvent ( KeyEvent e ) { } } | // bail if we ' re not enabled , we haven ' t the focus , or we ' re not
// showing on - screen
if ( ! _enabled || ! _focus || ! _target . isShowing ( ) ) { // log . info ( " dispatchKeyEvent [ enabled = " + _ enabled +
// " , focus = " + _ focus +
// " , showing = " + ( ( _ target = = null ) ? " N / A " :
// " " + _ target . isShowing ( ) ) + " ] . " ) ;
return false ; } // handle key press and release events
switch ( e . getID ( ) ) { case KeyEvent . KEY_PRESSED : return keyPressed ( e ) ; case KeyEvent . KEY_RELEASED : return keyReleased ( e ) ; case KeyEvent . KEY_TYPED : return keyTyped ( e ) ; default : return false ; } |
public class JavaParser { /** * src / main / resources / org / drools / compiler / semantics / java / parser / Java . g : 269:1 : compilationUnit : ( annotations ) ? ( packageDeclaration ) ? ( importDeclaration ) * ( typeDeclaration ) * ; */
public final void compilationUnit ( ) throws RecognitionException { } } | int compilationUnit_StartIndex = input . index ( ) ; try { if ( state . backtracking > 0 && alreadyParsedRule ( input , 1 ) ) { return ; } // src / main / resources / org / drools / compiler / semantics / java / parser / Java . g : 270:5 : ( ( annotations ) ? ( packageDeclaration ) ? ( importDeclaration ) * ( typeDeclaration ) * )
// src / main / resources / org / drools / compiler / semantics / java / parser / Java . g : 270:7 : ( annotations ) ? ( packageDeclaration ) ? ( importDeclaration ) * ( typeDeclaration ) *
{ // src / main / resources / org / drools / compiler / semantics / java / parser / Java . g : 270:7 : ( annotations ) ?
int alt1 = 2 ; int LA1_0 = input . LA ( 1 ) ; if ( ( LA1_0 == 58 ) ) { int LA1_1 = input . LA ( 2 ) ; if ( ( LA1_1 == Identifier ) ) { int LA1_21 = input . LA ( 3 ) ; if ( ( synpred1_Java ( ) ) ) { alt1 = 1 ; } } } switch ( alt1 ) { case 1 : // src / main / resources / org / drools / compiler / semantics / java / parser / Java . g : 270:7 : annotations
{ pushFollow ( FOLLOW_annotations_in_compilationUnit81 ) ; annotations ( ) ; state . _fsp -- ; if ( state . failed ) return ; } break ; } // src / main / resources / org / drools / compiler / semantics / java / parser / Java . g : 271:9 : ( packageDeclaration ) ?
int alt2 = 2 ; int LA2_0 = input . LA ( 1 ) ; if ( ( LA2_0 == 99 ) ) { alt2 = 1 ; } switch ( alt2 ) { case 1 : // src / main / resources / org / drools / compiler / semantics / java / parser / Java . g : 271:9 : packageDeclaration
{ pushFollow ( FOLLOW_packageDeclaration_in_compilationUnit92 ) ; packageDeclaration ( ) ; state . _fsp -- ; if ( state . failed ) return ; } break ; } // src / main / resources / org / drools / compiler / semantics / java / parser / Java . g : 272:9 : ( importDeclaration ) *
loop3 : while ( true ) { int alt3 = 2 ; int LA3_0 = input . LA ( 1 ) ; if ( ( LA3_0 == 89 ) ) { alt3 = 1 ; } switch ( alt3 ) { case 1 : // src / main / resources / org / drools / compiler / semantics / java / parser / Java . g : 272:9 : importDeclaration
{ pushFollow ( FOLLOW_importDeclaration_in_compilationUnit103 ) ; importDeclaration ( ) ; state . _fsp -- ; if ( state . failed ) return ; } break ; default : break loop3 ; } } // src / main / resources / org / drools / compiler / semantics / java / parser / Java . g : 273:9 : ( typeDeclaration ) *
loop4 : while ( true ) { int alt4 = 2 ; int LA4_0 = input . LA ( 1 ) ; if ( ( LA4_0 == ENUM || LA4_0 == 52 || LA4_0 == 58 || LA4_0 == 63 || LA4_0 == 72 || LA4_0 == 83 || LA4_0 == 93 || LA4_0 == 96 || ( LA4_0 >= 100 && LA4_0 <= 102 ) || ( LA4_0 >= 106 && LA4_0 <= 107 ) || LA4_0 == 110 || LA4_0 == 114 || LA4_0 == 119 ) ) { alt4 = 1 ; } switch ( alt4 ) { case 1 : // src / main / resources / org / drools / compiler / semantics / java / parser / Java . g : 273:9 : typeDeclaration
{ pushFollow ( FOLLOW_typeDeclaration_in_compilationUnit114 ) ; typeDeclaration ( ) ; state . _fsp -- ; if ( state . failed ) return ; } break ; default : break loop4 ; } } } } catch ( RecognitionException re ) { reportError ( re ) ; recover ( input , re ) ; } finally { // do for sure before leaving
if ( state . backtracking > 0 ) { memoize ( input , 1 , compilationUnit_StartIndex ) ; } } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.