signature stringlengths 43 39.1k | implementation stringlengths 0 450k |
|---|---|
public class Smb2FlushRequest { /** * { @ inheritDoc }
* @ see jcifs . internal . smb2 . ServerMessageBlock2 # writeBytesWireFormat ( byte [ ] , int ) */
@ Override protected int writeBytesWireFormat ( byte [ ] dst , int dstIndex ) { } } | int start = dstIndex ; SMBUtil . writeInt2 ( 24 , dst , dstIndex ) ; dstIndex += 2 ; dstIndex += 2 ; // Reserved1
dstIndex += 4 ; // Reserved2
System . arraycopy ( this . fileId , 0 , dst , dstIndex , 16 ) ; dstIndex += 16 ; return dstIndex - start ; |
public class CmsSecureExportDialog { /** * Converts a property object to a field value for one of the boolean selection widgets . < p >
* @ param prop the property to convert
* @ return the field value */
private String convertPropertyToFieldValue ( CmsProperty prop ) { } } | if ( prop == null ) { return "" ; } return "" + Boolean . valueOf ( prop . getValue ( ) ) ; |
public class RateLimiterExports { /** * Creates a new instance of { @ link RateLimiterExports } with specified metrics names prefix and
* { @ link Supplier } of rate limiters
* @ param prefix the prefix of metrics names
* @ param rateLimitersSupplier the supplier of rate limiters */
public static RateLimiterExports ofSupplier ( String prefix , Supplier < Iterable < RateLimiter > > rateLimitersSupplier ) { } } | return new RateLimiterExports ( prefix , rateLimitersSupplier ) ; |
public class EndianNumbers { /** * Converts a Java float to a Big Endian int on 4 bytes .
* @ param value is the value to parse .
* @ return the parsing result */
@ Pure @ Inline ( value = "EndianNumbers.parseBEInt(Float.floatToIntBits($1))" , imported = { } } | EndianNumbers . class } ) public static byte [ ] parseBEFloat ( float value ) { return parseBEInt ( Float . floatToIntBits ( value ) ) ; |
public class SourceWaterMarks { /** * Flushes low water marks and high water marks for all the sources .
* @ return < tt > true < / tt > if flush is successful . */
public boolean flush ( ) { } } | boolean ret = true ; PrintWriter out = null ; // Save source water marks
try { // Backup the original file
if ( file . exists ( ) ) { if ( fileOriginal . exists ( ) ) { fileOriginal . delete ( ) ; } file . renameTo ( fileOriginal ) ; } // Overwrite the existing file
out = new PrintWriter ( new FileOutputStream ( file ) ) ; for ( String source : sourceWaterMarkMap . keySet ( ) ) { WaterMarkEntry wmEntry = sourceWaterMarkMap . get ( source ) ; out . println ( wmEntry ) ; } out . flush ( ) ; } catch ( IOException ioe ) { logger . error ( "Failed to flush water marks" , ioe ) ; ret = false ; } finally { if ( out != null ) { out . close ( ) ; out = null ; } } return ret ; |
public class WCOutputStream31 { /** * @ see javax . servlet . ServletOutputStream # print ( int ) */
public void print ( int i ) throws IOException { } } | if ( this . _listener != null && ! checkIfCalledFromWLonError ( ) ) { if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isDebugEnabled ( ) ) Tr . debug ( tc , "non blocking print int , WriteListener enabled: " + this . _listener ) ; this . print_NonBlocking ( Integer . toString ( i ) ) ; } else { if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isDebugEnabled ( ) ) Tr . debug ( tc , "print int" ) ; super . print ( i ) ; } |
public class UpdateRouteResponseResult { /** * Represents the response models of a route response .
* @ param responseModels
* Represents the response models of a route response .
* @ return Returns a reference to this object so that method calls can be chained together . */
public UpdateRouteResponseResult withResponseModels ( java . util . Map < String , String > responseModels ) { } } | setResponseModels ( responseModels ) ; return this ; |
public class UsersApi { /** * Get User shares
* Get User shares
* @ param userId User ID . ( required )
* @ param filter filter ( required )
* @ param count Desired count of items in the result set . ( optional )
* @ param offset Offset for pagination . ( optional )
* @ return DeviceSharingEnvelope
* @ throws ApiException If fail to call the API , e . g . server error or cannot deserialize the response body */
public DeviceSharingEnvelope listAllSharesForUser ( String userId , String filter , Integer count , Integer offset ) throws ApiException { } } | ApiResponse < DeviceSharingEnvelope > resp = listAllSharesForUserWithHttpInfo ( userId , filter , count , offset ) ; return resp . getData ( ) ; |
public class RowMutation { /** * Creates a new instance of the mutation builder . */
public static RowMutation create ( @ Nonnull String tableId , @ Nonnull String key ) { } } | return create ( tableId , ByteString . copyFromUtf8 ( key ) ) ; |
public class Input { /** * Returns InputReader for input
* @ param < T >
* @ param input Any supported input type
* @ param size Ring - buffer size
* @ param features Needed features
* @ return
* @ throws IOException */
public static < T > InputReader getInstance ( T input , int size , Set < ParserFeature > features ) throws IOException { } } | return getInstance ( input , size , UTF_8 , features ) ; |
public class LongStreamEx { /** * Returns a sequential { @ link LongStreamEx } with the specified range of the
* specified array as its source .
* @ param array the array , assumed to be unmodified during use
* @ param startInclusive the first index to cover , inclusive
* @ param endExclusive index immediately past the last index to cover
* @ return an { @ code LongStreamEx } for the array range
* @ throws ArrayIndexOutOfBoundsException if { @ code startInclusive } is
* negative , { @ code endExclusive } is less than
* { @ code startInclusive } , or { @ code endExclusive } is greater than
* the array size
* @ since 0.1.1
* @ see Arrays # stream ( long [ ] , int , int ) */
public static LongStreamEx of ( long [ ] array , int startInclusive , int endExclusive ) { } } | return of ( Arrays . spliterator ( array , startInclusive , endExclusive ) ) ; |
public class MultiViewOps { /** * Checks to see if the three fundamental matrices are consistent based on their epipoles .
* e < sub > 23 < / sub > < sup > T < / sup > F < sub > 21 < / sub > e < sub > 13 < / sub > = 0 < br >
* e < sub > 31 < / sub > < sup > T < / sup > F < sub > 32 < / sub > e < sub > 21 < / sub > = 0 < br >
* e < sub > 32 < / sub > < sup > T < / sup > F < sub > 31 < / sub > e < sub > 12 < / sub > = 0 < br >
* Section 15.4 in R . Hartley , and A . Zisserman , " Multiple View Geometry in Computer Vision " , 2nd Ed , Cambridge 2003
* @ param F21 ( Input ) Fundamental matrix between view 1 and 2
* @ param F31 ( Input ) Fundamental matrix between view 1 and 3
* @ param F32 ( Input ) Fundamental matrix between view 2 and 3 */
public static boolean fundamentalCompatible3 ( DMatrixRMaj F21 , DMatrixRMaj F31 , DMatrixRMaj F32 , double tol ) { } } | FundamentalExtractEpipoles extractEpi = new FundamentalExtractEpipoles ( ) ; Point3D_F64 e21 = new Point3D_F64 ( ) ; Point3D_F64 e12 = new Point3D_F64 ( ) ; Point3D_F64 e31 = new Point3D_F64 ( ) ; Point3D_F64 e13 = new Point3D_F64 ( ) ; Point3D_F64 e32 = new Point3D_F64 ( ) ; Point3D_F64 e23 = new Point3D_F64 ( ) ; extractEpi . process ( F21 , e21 , e12 ) ; extractEpi . process ( F31 , e31 , e13 ) ; extractEpi . process ( F32 , e32 , e23 ) ; // GeometryMath _ F64 . innerProd ( e12 , F21 , e21)
// GeometryMath _ F64 . innerProd ( e13 , F31 , e31)
double score = 0 ; score += Math . abs ( GeometryMath_F64 . innerProd ( e23 , F21 , e13 ) ) ; score += Math . abs ( GeometryMath_F64 . innerProd ( e31 , F31 , e21 ) ) ; score += Math . abs ( GeometryMath_F64 . innerProd ( e32 , F32 , e12 ) ) ; score /= 3 ; return score <= tol ; |
public class StageOrTaskActivityBehavior { /** * manual activation rule / / / / / */
protected boolean evaluateManualActivationRule ( CmmnActivityExecution execution ) { } } | boolean manualActivation = false ; CmmnActivity activity = execution . getActivity ( ) ; Object manualActivationRule = activity . getProperty ( PROPERTY_MANUAL_ACTIVATION_RULE ) ; if ( manualActivationRule != null ) { CaseControlRule rule = ( CaseControlRule ) manualActivationRule ; manualActivation = rule . evaluate ( execution ) ; } return manualActivation ; |
public class NetworkConnectionServiceImpl { /** * Gets a ConnectionFactory .
* @ param connFactoryId the identifier of the ConnectionFactory */
@ Override public < T > ConnectionFactory < T > getConnectionFactory ( final Identifier connFactoryId ) { } } | final ConnectionFactory < T > connFactory = connFactoryMap . get ( connFactoryId . toString ( ) ) ; if ( connFactory == null ) { throw new RuntimeException ( "Cannot find ConnectionFactory of " + connFactoryId + "." ) ; } return connFactory ; |
public class AmazonKinesisAsyncClient { /** * Simplified method form for invoking the MergeShards operation with an AsyncHandler .
* @ see # mergeShardsAsync ( MergeShardsRequest , com . amazonaws . handlers . AsyncHandler ) */
@ Override public java . util . concurrent . Future < MergeShardsResult > mergeShardsAsync ( String streamName , String shardToMerge , String adjacentShardToMerge , com . amazonaws . handlers . AsyncHandler < MergeShardsRequest , MergeShardsResult > asyncHandler ) { } } | return mergeShardsAsync ( new MergeShardsRequest ( ) . withStreamName ( streamName ) . withShardToMerge ( shardToMerge ) . withAdjacentShardToMerge ( adjacentShardToMerge ) , asyncHandler ) ; |
public class Promise { /** * Waits if necessary for this future to complete , and then returns its
* result . It ' s a blocking operation , do not use this method unless it is
* absolutely necessary for something . Rather use the " then " and
* " catchError " methods .
* @ param timeout
* the maximum time to wait
* @ param unit
* the time unit of the timeout argument
* @ return result Tree structure
* @ throws Exception
* any ( interruption , execution , user - level , etc . ) exception */
public Tree waitFor ( long timeout , TimeUnit unit ) throws Exception { } } | try { return future . get ( timeout , unit ) ; } catch ( ExecutionException outerError ) { Throwable cause = outerError . getCause ( ) ; if ( cause != null && cause instanceof Exception ) { throw ( Exception ) cause ; } throw outerError ; } |
public class HawkbitUIErrorHandler { /** * Method to build a notification based on an exception .
* @ param ex
* the throwable
* @ return a hawkbit error notification message */
protected HawkbitErrorNotificationMessage buildNotification ( final Throwable ex ) { } } | LOG . error ( "Error in UI: " , ex ) ; final String errorMessage = extractMessageFrom ( ex ) ; final VaadinMessageSource i18n = SpringContextHelper . getBean ( VaadinMessageSource . class ) ; return new HawkbitErrorNotificationMessage ( STYLE , i18n . getMessage ( "caption.error" ) , errorMessage , true ) ; |
public class ExperimentingCaliperRun { /** * Attempts to run each given scenario once , in the current VM . Returns a set of all of the
* scenarios that didn ' t throw a { @ link SkipThisScenarioException } . */
ImmutableSet < Experiment > dryRun ( Iterable < Experiment > experiments ) throws InvalidBenchmarkException { } } | ImmutableSet . Builder < Experiment > builder = ImmutableSet . builder ( ) ; for ( Experiment experiment : experiments ) { Class < ? > clazz = benchmarkClass . benchmarkClass ( ) ; try { Object benchmark = injector . createChildInjector ( ExperimentModule . forExperiment ( experiment ) ) . getInstance ( Key . get ( clazz ) ) ; benchmarkClass . setUpBenchmark ( benchmark ) ; try { experiment . instrumentation ( ) . dryRun ( benchmark ) ; builder . add ( experiment ) ; } finally { // discard ' benchmark ' now ; the worker will have to instantiate its own anyway
benchmarkClass . cleanup ( benchmark ) ; } } catch ( ProvisionException e ) { Throwable cause = e . getCause ( ) ; if ( cause != null ) { throw new UserCodeException ( cause ) ; } throw e ; } catch ( CreationException e ) { // Guice formatting is a little ugly
StringBuilder message = new StringBuilder ( "Could not create an instance of the benchmark class following reasons:" ) ; int errorNum = 0 ; for ( Message guiceMessage : e . getErrorMessages ( ) ) { message . append ( "\n " ) . append ( ++ errorNum ) . append ( ") " ) . append ( guiceMessage . getMessage ( ) ) ; } throw new InvalidBenchmarkException ( message . toString ( ) , e ) ; } catch ( SkipThisScenarioException innocuous ) { } } return builder . build ( ) ; |
public class Apptentive { /** * Must be called from the { @ link Application # onCreate ( ) } method in the { @ link Application } object defined in your app ' s manifest .
* @ param application Application object .
* @ param configuration Apptentive configuration containing SDK initialization data . */
public static void register ( Application application , ApptentiveConfiguration configuration ) { } } | if ( application == null ) { throw new IllegalArgumentException ( "Application is null" ) ; } if ( configuration == null ) { throw new IllegalArgumentException ( "Apptentive configuration is null" ) ; } try { ApptentiveInternal . createInstance ( application , configuration ) ; } catch ( Exception e ) { ApptentiveLog . e ( e , "Exception while registering Apptentive SDK" ) ; logException ( e ) ; } |
public class Buffer { /** * Binary search for character width which favors matching lower numbers .
* < p > Adapted from okio . Buffer */
public static int asciiSizeInBytes ( long v ) { } } | if ( v == 0 ) return 1 ; if ( v == Long . MIN_VALUE ) return 20 ; boolean negative = false ; if ( v < 0 ) { v = - v ; // making this positive allows us to compare using less - than
negative = true ; } int width = v < 100000000L ? v < 10000L ? v < 100L ? v < 10L ? 1 : 2 : v < 1000L ? 3 : 4 : v < 1000000L ? v < 100000L ? 5 : 6 : v < 10000000L ? 7 : 8 : v < 1000000000000L ? v < 10000000000L ? v < 1000000000L ? 9 : 10 : v < 100000000000L ? 11 : 12 : v < 1000000000000000L ? v < 10000000000000L ? 13 : v < 100000000000000L ? 14 : 15 : v < 100000000000000000L ? v < 10000000000000000L ? 16 : 17 : v < 1000000000000000000L ? 18 : 19 ; return negative ? width + 1 : width ; // conditionally add room for negative sign |
public class HelloWorldConnectionImpl { /** * Call helloWorld
* @ param name String name
* @ return String helloworld */
public String helloWorld ( String name ) { } } | if ( mc == null ) associate ( ) ; return mc . helloWorld ( name ) ; |
public class LeapSeconds { /** * / * [ deutsch ]
* < p > Ist die angegebene UTC - Zeit eine registrierte positive
* Schaltsekunde ? < / p >
* @ param utc elapsed SI - seconds relative to UTC epoch
* [ 1972-01-01T00:00:00Z ] including leap seconds
* @ return { @ code true } if the argument represents a registered
* positive leap second else { @ code false } */
public boolean isPositiveLS ( long utc ) { } } | if ( utc <= 0 ) { return false ; } final ExtendedLSE [ ] events = this . getEventsInDescendingOrder ( ) ; for ( int i = 0 ; i < events . length ; i ++ ) { long comp = events [ i ] . utc ( ) ; if ( comp == utc ) { return ( events [ i ] . getShift ( ) == 1 ) ; } else if ( comp < utc ) { break ; } } return false ; |
public class XPathHelper { /** * Create a new XPath expression for evaluation .
* @ param aXPath
* The pre - created XPath object . May not be < code > null < / code > .
* @ param sXPath
* The main XPath string to be evaluated
* @ return The { @ link XPathExpression } object to be used .
* @ throws IllegalArgumentException
* if the XPath cannot be compiled */
@ Nonnull public static XPathExpression createNewXPathExpression ( @ Nonnull final XPath aXPath , @ Nonnull @ Nonempty final String sXPath ) { } } | ValueEnforcer . notNull ( aXPath , "XPath" ) ; ValueEnforcer . notNull ( sXPath , "XPathExpression" ) ; try { return aXPath . compile ( sXPath ) ; } catch ( final XPathExpressionException ex ) { throw new IllegalArgumentException ( "Failed to compile XPath expression '" + sXPath + "'" , ex ) ; } |
public class RDate { /** * { @ inheritDoc } */
public final void setTimeZone ( TimeZone timezone ) { } } | if ( periods != null && ! ( periods . isEmpty ( ) && periods . isUnmodifiable ( ) ) ) { periods . setTimeZone ( timezone ) ; } else { super . setTimeZone ( timezone ) ; } |
public class RuleSubset { /** * Add a { @ link RuleLifecycleListener } to receive events when { @ link Rule } instances are evaluated , executed , and their results . */
public ListenerRegistration < RuleLifecycleListener > addLifecycleListener ( final RuleLifecycleListener listener ) { } } | this . listeners . add ( listener ) ; return new ListenerRegistration < RuleLifecycleListener > ( ) { @ Override public RuleLifecycleListener removeListener ( ) { listeners . remove ( listener ) ; return listener ; } } ; |
public class ImageStatistics { /** * < p > Computes the mean squared error ( MSE ) between the two images . < / p >
* @ param imgA first image . Not modified .
* @ param imgB second image . Not modified .
* @ return error between the two images . */
public static double meanDiffSq ( GrayF32 imgA , GrayF32 imgB ) { } } | InputSanityCheck . checkSameShape ( imgA , imgB ) ; if ( BoofConcurrency . USE_CONCURRENT ) { return ImplImageStatistics_MT . meanDiffSq ( imgA . data , imgA . startIndex , imgA . stride , imgB . data , imgB . startIndex , imgB . stride , imgA . height , imgA . width ) ; } else { return ImplImageStatistics . meanDiffSq ( imgA . data , imgA . startIndex , imgA . stride , imgB . data , imgB . startIndex , imgB . stride , imgA . height , imgA . width ) ; } |
public class GeometricDoubleBondEncoderFactory { /** * Create a permutation parity for the given neighbors . The neighbor list
* should include the other double bonded atom but in the last index .
* < pre >
* c3
* c2 = c1 = [ c3 , c4 , c1]
* c4
* < / pre >
* @ param neighbors neighbors of a double bonded atom specified by index
* @ return a new permutation parity */
static PermutationParity permutation ( int [ ] neighbors ) { } } | return neighbors . length == 2 ? PermutationParity . IDENTITY : new BasicPermutationParity ( Arrays . copyOf ( neighbors , neighbors . length - 1 ) ) ; |
public class Element { /** * ( non - Javadoc )
* @ see
* qc . automation . framework . widget . IElement # waitForElementPresent ( java . lang
* . Long ) */
public void waitForElementNotPresent ( final long time ) throws WidgetException { } } | try { waitForCommand ( new ITimerCallback ( ) { @ Override public boolean execute ( ) throws WidgetException { return ! isElementPresent ( ) ; } @ Override public String toString ( ) { return "Waiting for element with locator " + locator + " to not be present" ; } } , time ) ; } catch ( Exception e ) { throw new WidgetException ( "Error while waiting for element to be not present" , locator , e ) ; } |
public class SocketStore { /** * This method handles submitting and then waiting for the request from the
* server . It uses the ClientRequest API to actually write the request and
* then read back the response . This implementation will block for a
* response from the server .
* @ param < T > Return type
* @ param clientRequest ClientRequest implementation used to write the
* request and read the response
* @ param operationName Simple string representing the type of request
* @ return Data returned by the individual requests */
private < T > T request ( ClientRequest < T > delegate , String operationName ) { } } | long startTimeMs = - 1 ; long startTimeNs = - 1 ; if ( logger . isDebugEnabled ( ) ) { startTimeMs = System . currentTimeMillis ( ) ; } ClientRequestExecutor clientRequestExecutor = pool . checkout ( destination ) ; String debugMsgStr = "" ; startTimeNs = System . nanoTime ( ) ; BlockingClientRequest < T > blockingClientRequest = null ; try { blockingClientRequest = new BlockingClientRequest < T > ( delegate , timeoutMs ) ; clientRequestExecutor . addClientRequest ( blockingClientRequest , timeoutMs , System . nanoTime ( ) - startTimeNs ) ; boolean awaitResult = blockingClientRequest . await ( ) ; if ( awaitResult == false ) { blockingClientRequest . timeOut ( ) ; } if ( logger . isDebugEnabled ( ) ) debugMsgStr += "success" ; return blockingClientRequest . getResult ( ) ; } catch ( InterruptedException e ) { if ( logger . isDebugEnabled ( ) ) debugMsgStr += "unreachable: " + e . getMessage ( ) ; throw new UnreachableStoreException ( "Failure in " + operationName + " on " + destination + ": " + e . getMessage ( ) , e ) ; } catch ( UnreachableStoreException e ) { clientRequestExecutor . close ( ) ; if ( logger . isDebugEnabled ( ) ) debugMsgStr += "failure: " + e . getMessage ( ) ; throw new UnreachableStoreException ( "Failure in " + operationName + " on " + destination + ": " + e . getMessage ( ) , e . getCause ( ) ) ; } finally { if ( blockingClientRequest != null && ! blockingClientRequest . isComplete ( ) ) { // close the executor if we timed out
clientRequestExecutor . close ( ) ; } // Record operation time
long opTimeNs = Utils . elapsedTimeNs ( startTimeNs , System . nanoTime ( ) ) ; if ( stats != null ) { stats . recordSyncOpTimeNs ( destination , opTimeNs ) ; } if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Sync request end, type: " + operationName + " requestRef: " + System . identityHashCode ( delegate ) + " totalTimeNs: " + opTimeNs + " start time: " + startTimeMs + " end time: " + System . currentTimeMillis ( ) + " client:" + clientRequestExecutor . getSocketChannel ( ) . socket ( ) . getLocalAddress ( ) + ":" + clientRequestExecutor . getSocketChannel ( ) . socket ( ) . getLocalPort ( ) + " server: " + clientRequestExecutor . getSocketChannel ( ) . socket ( ) . getRemoteSocketAddress ( ) + " outcome: " + debugMsgStr ) ; } pool . checkin ( destination , clientRequestExecutor ) ; } |
public class EnableOnValidHandler { /** * Constructor .
* @ param record My owner ( usually passed as null , and set on addListener in setOwner ( ) ) .
* @ param field Target field .
* @ param iFieldSeq Target field .
* @ param bEnbleOnValid Enable / disable the fields on valid .
* @ param bEnableOnNew Enable / disable the fields on new .
* @ param flagField If this flag is true , do the opposite enable / disable . */
public void init ( Record record , BaseField field , String fieldName , boolean bEnableOnValid , boolean bEnableOnNew , ScreenComponent sField ) { } } | this . fieldName = fieldName ; m_fldTarget = field ; m_sField = sField ; m_bEnableOnValid = bEnableOnValid ; m_bEnableOnNew = bEnableOnNew ; super . init ( record ) ; |
public class Base16Utils { /** * This function decodes a base 16 string into its corresponding byte array .
* @ param base16 The base 16 encoded string .
* @ return The corresponding byte array . */
static public byte [ ] decode ( String base16 ) { } } | String string = base16 . replaceAll ( "\\s" , "" ) ; // remove all white space
int length = string . length ( ) ; byte [ ] bytes = new byte [ ( int ) Math . ceil ( length / 2.0 ) ] ; for ( int i = 0 ; i < bytes . length ; i ++ ) { decodeByte ( string , i , bytes ) ; } return bytes ; |
public class VisitState { /** * Enqueues the < code > / robots . txt < / code > path as the first element of the queue , if the queue is
* empty , or as the second element otherwise , possibly putting this visit state in its
* entry .
* < p > This behaviour is necessary : is this visit state
* is { @ linkplain # acquired } , the first path + query might be still need to be dequeued by a
* { @ link ParsingThread } . */
public synchronized void enqueueRobots ( ) { } } | if ( ! RuntimeConfiguration . FETCH_ROBOTS ) return ; if ( nextFetch == Long . MAX_VALUE ) return ; synchronized ( this ) { if ( pathQueries . isEmpty ( ) ) { pathQueries . enqueueFirst ( ROBOTS_PATH ) ; putInEntryIfNotAcquired ( ) ; } else { final byte [ ] first = pathQueries . dequeue ( ) ; pathQueries . enqueueFirst ( ROBOTS_PATH ) ; pathQueries . enqueueFirst ( first ) ; } } |
public class DefaultStreamHandler { /** * Helper method to deal with the { @ link FragmentListener } since it
* technically can throw exceptions and stuff so we just want to catch all
* and log and move on .
* @ param ipPacket
* @ return */
private IPPacket handleFragmentation ( final IPPacket ipPacket ) { } } | if ( this . fragmentListener == null ) { return null ; } try { return this . fragmentListener . handleFragment ( ipPacket ) ; } catch ( final Throwable t ) { logger . warn ( "Exception thrown by FragmentListener when processing the IP frame" , t ) ; } return null ; |
public class MuteDirector { /** * Called to shut down the mute director . */
public void shutdown ( ) { } } | if ( _chatdir != null ) { _chatdir . removeChatFilter ( this ) ; _chatdir = null ; } _ctx . getClient ( ) . removeClientObserver ( this ) ; |
public class SDBaseOps { /** * Convert the array to a one - hot array with walues { @ code on } and { @ code off } for each entry < br >
* If input has shape [ a , . . . , n ] then output has shape [ a , . . . , n , depth ] ,
* with { @ code out [ i , . . . , j , in [ i , . . . , j ] ] = on } with other values being set to { @ code off }
* @ param name Output variable name
* @ param indices Indices - value 0 to depth - 1
* @ param depth Number of classes
* @ return Output variable */
public SDVariable oneHot ( String name , SDVariable indices , int depth , int axis , double on , double off ) { } } | return oneHot ( name , indices , depth , axis , on , off , OneHot . DEFAULT_DTYPE ) ; |
public class CWSEvaluator { /** * 标准化评测分词器
* @ param segment 分词器
* @ param outputPath 分词预测输出文件
* @ param goldFile 测试集segmented file
* @ param dictPath 训练集单词列表
* @ return 一个储存准确率的结构
* @ throws IOException */
public static CWSEvaluator . Result evaluate ( Segment segment , String outputPath , String goldFile , String dictPath ) throws IOException { } } | IOUtil . LineIterator lineIterator = new IOUtil . LineIterator ( goldFile ) ; BufferedWriter bw = IOUtil . newBufferedWriter ( outputPath ) ; for ( String line : lineIterator ) { List < Term > termList = segment . seg ( line . replaceAll ( "\\s+" , "" ) ) ; // 一些testFile与goldFile根本不匹配 , 比如MSR的testFile有些行缺少单词 , 所以用goldFile去掉空格代替
int i = 0 ; for ( Term term : termList ) { bw . write ( term . word ) ; if ( ++ i != termList . size ( ) ) bw . write ( " " ) ; } bw . newLine ( ) ; } bw . close ( ) ; CWSEvaluator . Result result = CWSEvaluator . evaluate ( goldFile , outputPath , dictPath ) ; return result ; |
public class Validator { /** * The digits were stored as a hex value , thix switches them to an octal value .
* @ param currentHexValue
* @ param digitCount
* @ return */
private static long switchValue8 ( long currentHexValue , int digitCount ) { } } | long result = 0x7 & currentHexValue ; int shift = 0 ; while ( -- digitCount > 0 ) { shift += 3 ; currentHexValue >>>= 4 ; result |= ( 0x7 & currentHexValue ) << shift ; } return result ; |
public class ExtensionRegistry { /** * Gets information about the subsystems provided by a given { @ link org . jboss . as . controller . Extension } .
* @ param moduleName the name of the extension ' s module . Cannot be { @ code null }
* @ return map of subsystem names to information about the subsystem . */
public Map < String , SubsystemInformation > getAvailableSubsystems ( String moduleName ) { } } | Map < String , SubsystemInformation > result = null ; final ExtensionInfo info = extensions . get ( moduleName ) ; if ( info != null ) { // noinspection SynchronizationOnLocalVariableOrMethodParameter
synchronized ( info ) { result = Collections . unmodifiableMap ( new HashMap < String , SubsystemInformation > ( info . subsystems ) ) ; } } return result ; |
public class RaidNode { /** * Wait for service to finish .
* ( Normally , it runs forever . ) */
public void join ( ) { } } | try { if ( server != null ) server . join ( ) ; if ( triggerThread != null ) triggerThread . join ( ) ; if ( urfThread != null ) urfThread . join ( ) ; if ( blockFixerThread != null ) blockFixerThread . join ( ) ; if ( blockCopierThread != null ) blockCopierThread . join ( ) ; if ( corruptFileCounterThread != null ) corruptFileCounterThread . join ( ) ; if ( purgeThread != null ) purgeThread . join ( ) ; if ( statsCollectorThread != null ) statsCollectorThread . join ( ) ; } catch ( InterruptedException ie ) { // do nothing
} |
public class DeleteInputRequestMarshaller { /** * Marshall the given parameter object . */
public void marshall ( DeleteInputRequest deleteInputRequest , ProtocolMarshaller protocolMarshaller ) { } } | if ( deleteInputRequest == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( deleteInputRequest . getInputId ( ) , INPUTID_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
import java . util . * ; class SortTuples { /** * This function sorts the tuples based on an order defined by the list ' orderList ' .
* Examples :
* > > > sortTuples ( Arrays . asList ( new AbstractMap . SimpleEntry < > ( 4 , 3 ) , new AbstractMap . SimpleEntry < > ( 1 , 9 ) , new AbstractMap . SimpleEntry < > ( 2 , 10 ) , new AbstractMap . SimpleEntry < > ( 3 , 2 ) ) , Arrays . asList ( 1 , 4 , 2 , 3 ) )
* [ ( 1 , 9 ) , ( 4 , 3 ) , ( 2 , 10 ) , ( 3 , 2 ) ]
* > > > sortTuples ( Arrays . asList ( new AbstractMap . SimpleEntry < > ( 5 , 4 ) , new AbstractMap . SimpleEntry < > ( 2 , 10 ) , new AbstractMap . SimpleEntry < > ( 3 , 11 ) , new AbstractMap . SimpleEntry < > ( 4 , 3 ) ) , Arrays . asList ( 3 , 4 , 2 , 5 ) )
* [ ( 3 , 11 ) , ( 4 , 3 ) , ( 2 , 10 ) , ( 5 , 4 ) ]
* > > > sortTuples ( Arrays . asList ( new AbstractMap . SimpleEntry < > ( 6 , 3 ) , new AbstractMap . SimpleEntry < > ( 3 , 8 ) , new AbstractMap . SimpleEntry < > ( 5 , 7 ) , new AbstractMap . SimpleEntry < > ( 2 , 4 ) ) , Arrays . asList ( 2 , 5 , 3 , 6 ) )
* [ ( 2 , 4 ) , ( 5 , 7 ) , ( 3 , 8 ) , ( 6 , 3 ) ]
* @ param tupleList : A list of tuples to be sorted .
* @ param orderList : The order in which to sort the tuples .
* @ return a list of tuples sorted as per the orderList */
public static List < Map . Entry < Integer , Integer > > sortTuples ( List < Map . Entry < Integer , Integer > > tupleList , List < Integer > orderList ) { } } | Map < Integer , Integer > tuplesMap = new HashMap < > ( ) ; for ( Map . Entry < Integer , Integer > tuple : tupleList ) { tuplesMap . put ( tuple . getKey ( ) , tuple . getValue ( ) ) ; } List < Map . Entry < Integer , Integer > > sortedTuples = new ArrayList < > ( ) ; for ( Integer key : orderList ) { sortedTuples . add ( new AbstractMap . SimpleEntry < > ( key , tuplesMap . get ( key ) ) ) ; } return sortedTuples ; |
public class ManagedInstancesInner { /** * Gets a list of managed instances in a resource group .
* @ 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 .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the observable to the PagedList & lt ; ManagedInstanceInner & gt ; object */
public Observable < Page < ManagedInstanceInner > > listByResourceGroupAsync ( final String resourceGroupName ) { } } | return listByResourceGroupWithServiceResponseAsync ( resourceGroupName ) . map ( new Func1 < ServiceResponse < Page < ManagedInstanceInner > > , Page < ManagedInstanceInner > > ( ) { @ Override public Page < ManagedInstanceInner > call ( ServiceResponse < Page < ManagedInstanceInner > > response ) { return response . body ( ) ; } } ) ; |
public class PoiWriter { /** * Complete task . */
public void complete ( ) { } } | if ( this . configuration . isGeoTags ( ) ) { this . geoTagger . processBoundaries ( ) ; } NumberFormat nfMegabyte = NumberFormat . getInstance ( ) ; nfMegabyte . setMaximumFractionDigits ( 2 ) ; try { commit ( ) ; if ( this . configuration . isFilterCategories ( ) ) { filterCategories ( ) ; } writeMetadata ( ) ; this . conn . close ( ) ; postProcess ( ) ; } catch ( SQLException e ) { e . printStackTrace ( ) ; } LOGGER . info ( "Added " + nfCounts . format ( this . poiAdded ) + " POIs." ) ; this . progressManager . setMessage ( "Done." ) ; LOGGER . info ( "Estimated memory consumption: " + nfMegabyte . format ( + ( ( Runtime . getRuntime ( ) . totalMemory ( ) - Runtime . getRuntime ( ) . freeMemory ( ) ) / Math . pow ( 1024 , 2 ) ) ) + "MB" ) ; |
public class ControllerAutoSchedule { /** * Upon successful transaction commit , automatically schedules a task via the controller .
* @ see javax . transaction . Synchronization # afterCompletion ( int ) */
@ Override public void afterCompletion ( int status ) { } } | if ( status == Status . STATUS_COMMITTED ) controller . notifyOfTaskAssignment ( partitionId , taskId , expectedExecTime , binaryFlags , txTimeout ) ; |
public class IntegrationAccountsInner { /** * Logs the integration account ' s tracking events .
* @ param resourceGroupName The resource group name .
* @ param integrationAccountName The integration account name .
* @ param logTrackingEvents The callback URL parameters .
* @ 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 < Void > logTrackingEventsAsync ( String resourceGroupName , String integrationAccountName , TrackingEventsDefinition logTrackingEvents , final ServiceCallback < Void > serviceCallback ) { } } | return ServiceFuture . fromResponse ( logTrackingEventsWithServiceResponseAsync ( resourceGroupName , integrationAccountName , logTrackingEvents ) , serviceCallback ) ; |
public class RaftNetworkClient { /** * Initialize the { @ code RaftNetworkClient } instance .
* Sets up the { @ code RaftNetworkClient } client and server modules .
* Following a call to { @ code initialize ( ) } network threads are active
* but will not accept any incoming connections or establish any
* outgoing connections . As a result the caller still has
* exclusive access to underlying system resources .
* @ param nonIoExecutorService shared instance of { @ code ListeningExecutorService } used to handle any non - io tasks ( address - resolution , etc . )
* @ param serverChannelFactory instance of { @ code ServerChannelFactory } used to handle incoming connections from remote Raft servers
* @ param clientChannelFactory instance of { @ code ChannelFactory } used to create outgoing connections to remote Raft servers
* @ param receiver instance of { @ code RPCReceiver } that will be notified of incoming { @ link RaftRPC } messages
* @ throws IllegalStateException if this method is called multiple times */
public synchronized void initialize ( ListeningExecutorService nonIoExecutorService , ServerChannelFactory serverChannelFactory , ChannelFactory clientChannelFactory , RPCReceiver receiver ) { } } | checkState ( ! running ) ; checkState ( server == null ) ; checkState ( client == null ) ; final AddressResolverHandler resolverHandler = new AddressResolverHandler ( nonIoExecutorService ) ; // sharable , because it is using the default provider
final FinalUpstreamHandler finalUpstreamHandler = new FinalUpstreamHandler ( self . getId ( ) ) ; final RPCHandler rpcHandler = new RPCHandler ( self . getId ( ) , cluster . keySet ( ) , receiver ) ; final RPCConverters . RPCEncoder rpcEncoder = new RPCConverters . RPCEncoder ( mapper ) ; final RPCConverters . RPCDecoder rpcDecoder = new RPCConverters . RPCDecoder ( mapper ) ; server = new ServerBootstrap ( serverChannelFactory ) ; server . setPipelineFactory ( new ChannelPipelineFactory ( ) { @ Override public ChannelPipeline getPipeline ( ) throws Exception { ChannelPipeline pipeline = Channels . pipeline ( ) ; pipeline . addLast ( "frame-decoder" , new Framers . FrameDecoder ( ) ) ; pipeline . addLast ( "handshake" , new Handshakers . IncomingHandshakeHandler ( mapper ) ) ; pipeline . addLast ( "rpc-decoder" , rpcDecoder ) ; pipeline . addLast ( "raftrpc" , rpcHandler ) ; pipeline . addLast ( "final" , finalUpstreamHandler ) ; return pipeline ; } } ) ; client = new ClientBootstrap ( clientChannelFactory ) ; client . setPipelineFactory ( new ChannelPipelineFactory ( ) { @ Override public ChannelPipeline getPipeline ( ) throws Exception { ChannelPipeline pipeline = Channels . pipeline ( ) ; pipeline . addLast ( "resolver" , resolverHandler ) ; pipeline . addLast ( "frame-encoder" , new Framers . FrameEncoder ( ) ) ; pipeline . addLast ( "handshake" , new Handshakers . OutgoingHandshakeHandler ( self . getId ( ) , mapper ) ) ; pipeline . addLast ( "rpc-encoder" , rpcEncoder ) ; pipeline . addLast ( "final" , finalUpstreamHandler ) ; return pipeline ; } } ) ; |
public class GeographyPointValue { /** * by subtracting multiples of 360. */
private static double normalize ( double v , double range ) { } } | double a = v - Math . floor ( ( v + ( range / 2 ) ) / range ) * range ; // Make sure that a and v have the same sign
// when abs ( v ) = 180.
if ( Math . abs ( a ) == 180.0 && ( a * v ) < 0 ) { a *= - 1 ; } // The addition of 0.0 is to avoid negative
// zero , which just confuses things .
return a + 0.0 ; |
public class AbstractOccurrenceDependencyContextGenerator { /** * { @ inheritDoc } */
public SparseDoubleVector generateContext ( DependencyTreeNode [ ] tree , int focusIndex ) { } } | Queue < String > prevWords = new ArrayDeque < String > ( ) ; for ( int i = Math . max ( 0 , focusIndex - windowSize - 1 ) ; i < focusIndex ; ++ i ) prevWords . add ( getFeature ( tree [ i ] , i - focusIndex ) ) ; Queue < String > nextWords = new ArrayDeque < String > ( ) ; for ( int i = focusIndex + 1 ; i < Math . min ( focusIndex + windowSize + 1 , tree . length ) ; ++ i ) nextWords . add ( getFeature ( tree [ i ] , i - focusIndex ) ) ; SparseDoubleVector focusMeaning = new CompactSparseVector ( ) ; addContextTerms ( focusMeaning , prevWords , - 1 * prevWords . size ( ) ) ; addContextTerms ( focusMeaning , nextWords , 1 ) ; return focusMeaning ; |
public class PickleUtils { /** * read a line of text , possibly including the terminating LF char */
public static String readline ( InputStream input , boolean includeLF ) throws IOException { } } | StringBuilder sb = new StringBuilder ( ) ; while ( true ) { int c = input . read ( ) ; if ( c == - 1 ) { if ( sb . length ( ) == 0 ) throw new IOException ( "premature end of file" ) ; break ; } if ( c != '\n' || includeLF ) sb . append ( ( char ) c ) ; if ( c == '\n' ) break ; } return sb . toString ( ) ; |
public class ObjectFactory { /** * Create an instance of { @ link JAXBElement } { @ code < } { @ link SubjectType } { @ code > } } */
@ XmlElementDecl ( namespace = "urn:oasis:names:tc:xacml:2.0:context:schema:os" , name = "Subject" ) public JAXBElement < SubjectType > createSubject ( SubjectType value ) { } } | return new JAXBElement < SubjectType > ( _Subject_QNAME , SubjectType . class , null , value ) ; |
public class FileSystem { /** * Reply the basename of the specified file without all the extensions .
* @ param filename is the name to parse .
* @ return the basename of the specified file without all the extensions . */
@ Pure public static String shortBasename ( File filename ) { } } | if ( filename == null ) { return null ; } final String largeBasename = filename . getName ( ) ; final int idx = largeBasename . indexOf ( getFileExtensionCharacter ( ) ) ; if ( idx < 0 ) { return largeBasename ; } return largeBasename . substring ( 0 , idx ) ; |
public class DictImpl { /** * Creates a SoyDict implementation for a particular underlying provider map .
* < p > The map may be mutable , but will not be mutated by the DictImpl . */
public static DictImpl forProviderMap ( Map < String , ? extends SoyValueProvider > providerMap , RuntimeMapTypeTracker . Type mapType ) { } } | return new DictImpl ( providerMap , mapType ) ; |
public class MpMessages { /** * 群发语音消息给指定人
* @ param openIds
* @ param voice
* @ return */
public long voice ( List < String > openIds , String voice ) { } } | return send ( new Filter ( false , null ) , openIds , "voice" , voice ) ; |
public class PlanNode { /** * Look at nodes below this node , searching for nodes that have the supplied type . As soon as a node with a matching type is
* found , then no other nodes below it are searched .
* @ param typeToFind the type of node to find ; may not be null
* @ return the collection of nodes that are at or below this node that all have the supplied type ; never null but possibly
* empty */
public List < PlanNode > findAllFirstNodesAtOrBelow ( Type typeToFind ) { } } | List < PlanNode > results = new LinkedList < PlanNode > ( ) ; LinkedList < PlanNode > queue = new LinkedList < PlanNode > ( ) ; queue . add ( this ) ; while ( ! queue . isEmpty ( ) ) { PlanNode aNode = queue . poll ( ) ; if ( aNode . getType ( ) == Type . PROJECT ) { results . add ( aNode ) ; } else { queue . addAll ( 0 , aNode . getChildren ( ) ) ; } } return results ; |
public class DrawerBuilder { /** * Sets the activity which will be generated for the generation
* The activity is required and will be used to inflate the content in .
* After generation it is set to null to prevent a memory leak .
* @ param activity current activity which will contain the drawer */
public DrawerBuilder withActivity ( @ NonNull Activity activity ) { } } | this . mRootView = ( ViewGroup ) activity . findViewById ( android . R . id . content ) ; this . mActivity = activity ; this . mLayoutManager = new LinearLayoutManager ( mActivity ) ; return this ; |
public class SingleFieldConstraintEBLeftSide { /** * This adds a new connective . */
@ Override public void addNewConnective ( ) { } } | String factType = getExpressionLeftSide ( ) . getPreviousGenericType ( ) ; if ( factType == null ) { factType = getExpressionLeftSide ( ) . getGenericType ( ) ; } String fieldName = getExpressionLeftSide ( ) . getFieldName ( ) ; String fieldType = getExpressionLeftSide ( ) . getGenericType ( ) ; if ( this . getConnectives ( ) == null ) { this . setConnectives ( new ConnectiveConstraint [ ] { new ConnectiveConstraint ( factType , fieldName , fieldType ) } ) ; } else { final ConnectiveConstraint [ ] newList = new ConnectiveConstraint [ this . getConnectives ( ) . length + 1 ] ; for ( int i = 0 ; i < this . getConnectives ( ) . length ; i ++ ) { newList [ i ] = this . getConnectives ( ) [ i ] ; } newList [ this . getConnectives ( ) . length ] = new ConnectiveConstraint ( factType , fieldName , fieldType ) ; this . setConnectives ( newList ) ; } |
public class PersistenceXMLLoader { /** * Parses the persistence unit .
* @ param top
* the top
* @ return the persistence metadata
* @ throws Exception
* the exception */
private static PersistenceUnitMetadata parsePersistenceUnit ( final URL url , final String [ ] persistenceUnits , Element top , final String versionName ) { } } | PersistenceUnitMetadata metadata = new PersistenceUnitMetadata ( versionName , getPersistenceRootUrl ( url ) , url ) ; String puName = top . getAttribute ( "name" ) ; if ( ! Arrays . asList ( persistenceUnits ) . contains ( puName ) ) { // Returning null because this persistence unit is not intended for
// creating entity manager factory .
return null ; } if ( ! isEmpty ( puName ) ) { log . trace ( "Persistent Unit name from persistence.xml: " + puName ) ; metadata . setPersistenceUnitName ( puName ) ; String transactionType = top . getAttribute ( "transaction-type" ) ; if ( StringUtils . isEmpty ( transactionType ) || PersistenceUnitTransactionType . RESOURCE_LOCAL . name ( ) . equals ( transactionType ) ) { metadata . setTransactionType ( PersistenceUnitTransactionType . RESOURCE_LOCAL ) ; } else if ( PersistenceUnitTransactionType . JTA . name ( ) . equals ( transactionType ) ) { metadata . setTransactionType ( PersistenceUnitTransactionType . JTA ) ; } } NodeList children = top . getChildNodes ( ) ; for ( int i = 0 ; i < children . getLength ( ) ; i ++ ) { if ( children . item ( i ) . getNodeType ( ) == Node . ELEMENT_NODE ) { Element element = ( Element ) children . item ( i ) ; String tag = element . getTagName ( ) ; if ( tag . equals ( "provider" ) ) { metadata . setProvider ( getElementContent ( element ) ) ; } else if ( tag . equals ( "properties" ) ) { NodeList props = element . getChildNodes ( ) ; for ( int j = 0 ; j < props . getLength ( ) ; j ++ ) { if ( props . item ( j ) . getNodeType ( ) == Node . ELEMENT_NODE ) { Element propElement = ( Element ) props . item ( j ) ; // if element is not " property " then skip
if ( ! "property" . equals ( propElement . getTagName ( ) ) ) { continue ; } String propName = propElement . getAttribute ( "name" ) . trim ( ) ; String propValue = propElement . getAttribute ( "value" ) . trim ( ) ; if ( isEmpty ( propValue ) ) { propValue = getElementContent ( propElement , "" ) ; } metadata . getProperties ( ) . put ( propName , propValue ) ; } } } else if ( tag . equals ( "class" ) ) { metadata . getClasses ( ) . add ( getElementContent ( element ) ) ; } else if ( tag . equals ( "jar-file" ) ) { metadata . addJarFile ( getElementContent ( element ) ) ; } else if ( tag . equals ( "exclude-unlisted-classes" ) ) { String excludeUnlisted = getElementContent ( element ) ; metadata . setExcludeUnlistedClasses ( Boolean . parseBoolean ( excludeUnlisted ) ) ; } } } PersistenceUnitTransactionType transactionType = getTransactionType ( top . getAttribute ( "transaction-type" ) ) ; if ( transactionType != null ) { metadata . setTransactionType ( transactionType ) ; } return metadata ; |
public class ClassCompare { /** * appends blanks to the string if its shorter than < code > len < / code > .
* @ param sthe string to pad
* @ param lenthe minimum length for the string to have
* @ returnthe padded string */
protected String fillUp ( String s , int len ) { } } | while ( s . length ( ) < len ) s += " " ; return s ; |
public class SessionImpl { /** * { @ inheritDoc } */
public void move ( String srcAbsPath , String destAbsPath , boolean triggerEventsForDescendants ) throws ItemExistsException , PathNotFoundException , VersionException , LockException , RepositoryException { } } | // In this particular case we decide what to do whether it is a rename or a real move
move ( srcAbsPath , destAbsPath , triggerEventsForDescendants , triggerEventsForDescendants ) ; |
public class DistributedDelayQueue { /** * Same as { @ link # putMulti ( MultiItem , long ) } but allows a maximum wait time if an upper bound was set
* via { @ link QueueBuilder # maxItems } .
* @ param items items to add
* @ param delayUntilEpoch future epoch ( milliseconds ) when this item will be available to consumers
* @ param maxWait maximum wait
* @ param unit wait unit
* @ return true if items was added , false if timed out
* @ throws Exception */
public boolean putMulti ( MultiItem < T > items , long delayUntilEpoch , int maxWait , TimeUnit unit ) throws Exception { } } | Preconditions . checkArgument ( delayUntilEpoch > 0 , "delayUntilEpoch cannot be negative" ) ; queue . checkState ( ) ; return queue . internalPut ( null , items , queue . makeItemPath ( ) + epochToString ( delayUntilEpoch ) , maxWait , unit ) ; |
public class AmazonElastiCacheAsyncClient { /** * Simplified method form for invoking the DescribeReservedCacheNodesOfferings operation with an AsyncHandler .
* @ see # describeReservedCacheNodesOfferingsAsync ( DescribeReservedCacheNodesOfferingsRequest ,
* com . amazonaws . handlers . AsyncHandler ) */
@ Override public java . util . concurrent . Future < DescribeReservedCacheNodesOfferingsResult > describeReservedCacheNodesOfferingsAsync ( com . amazonaws . handlers . AsyncHandler < DescribeReservedCacheNodesOfferingsRequest , DescribeReservedCacheNodesOfferingsResult > asyncHandler ) { } } | return describeReservedCacheNodesOfferingsAsync ( new DescribeReservedCacheNodesOfferingsRequest ( ) , asyncHandler ) ; |
public class ClusterState { /** * Returns a member by ID .
* @ param id The member ID .
* @ return The member . */
public ServerMember getRemoteMember ( int id ) { } } | MemberState member = membersMap . get ( id ) ; return member != null ? member . getMember ( ) : null ; |
public class ManagedExecutorServiceImpl { /** * Declarative Services method for setting the context service reference
* @ param ref reference to the service */
@ Reference ( policy = ReferencePolicy . DYNAMIC , target = "(id=unbound)" ) protected void setContextService ( ServiceReference < WSContextService > ref ) { } } | contextSvcRef . setReference ( ref ) ; |
public class DomService { /** * Apply the " left " style attribute on the given element .
* @ param element
* The DOM element .
* @ param left
* The left value . */
public static void setLeft ( Element element , int left ) { } } | if ( Dom . isIE ( ) ) { // Limitation in IE8 . . .
while ( left > 1000000 ) { left -= 1000000 ; } while ( left < - 1000000 ) { left += 1000000 ; } } Dom . setStyleAttribute ( element , "left" , left + "px" ) ; |
public class UploadMultipartPartRequestMarshaller { /** * Marshall the given parameter object . */
public void marshall ( UploadMultipartPartRequest uploadMultipartPartRequest , ProtocolMarshaller protocolMarshaller ) { } } | if ( uploadMultipartPartRequest == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( uploadMultipartPartRequest . getAccountId ( ) , ACCOUNTID_BINDING ) ; protocolMarshaller . marshall ( uploadMultipartPartRequest . getVaultName ( ) , VAULTNAME_BINDING ) ; protocolMarshaller . marshall ( uploadMultipartPartRequest . getUploadId ( ) , UPLOADID_BINDING ) ; protocolMarshaller . marshall ( uploadMultipartPartRequest . getChecksum ( ) , CHECKSUM_BINDING ) ; protocolMarshaller . marshall ( uploadMultipartPartRequest . getRange ( ) , RANGE_BINDING ) ; protocolMarshaller . marshall ( uploadMultipartPartRequest . getBody ( ) , BODY_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class BasePanel { /** * Process the " Delete " toolbar command .
* @ return true If command was handled */
public boolean onDelete ( ) { } } | Record record = this . getMainRecord ( ) ; if ( record == null ) return false ; if ( record . getEditMode ( ) == Constants . EDIT_NONE ) return true ; if ( record . getEditMode ( ) == Constants . EDIT_ADD ) { // If they ' re adding , can ' t delete nothing !
this . onRefresh ( ) ; return true ; } try { if ( record . getEditMode ( ) != Constants . EDIT_IN_PROGRESS ) record . edit ( ) ; record . remove ( ) ; record . addNew ( ) ; this . clearStatusText ( ) ; } catch ( DBException ex ) { this . displayError ( ex ) ; return false ; } return true ; |
public class JmsSpout { /** * < code > ISpout < / code > implementation .
* Connects the JMS spout to the configured JMS destination
* topic / queue . */
@ SuppressWarnings ( "rawtypes" ) public void open ( Map conf , TopologyContext context , SpoutOutputCollector collector ) { } } | if ( this . jmsProvider == null ) { throw new IllegalStateException ( "JMS provider has not been set." ) ; } if ( this . tupleProducer == null ) { throw new IllegalStateException ( "JMS Tuple Producer has not been set." ) ; } Integer topologyTimeout = ( Integer ) conf . get ( "topology.message.timeout.secs" ) ; // TODO fine a way to get the default timeout from storm , so we ' re not hard - coding to 30 seconds ( it could change )
topologyTimeout = topologyTimeout == null ? 30 : topologyTimeout ; if ( ( topologyTimeout . intValue ( ) * 1000 ) > this . recoveryPeriod ) { LOG . warn ( "*** WARNING *** : " + "Recovery period (" + this . recoveryPeriod + " ms.) is less then the configured " + "'topology.message.timeout.secs' of " + topologyTimeout + " secs. This could lead to a message replay flood!" ) ; } this . queue = new LinkedBlockingQueue < Message > ( ) ; this . toCommit = new TreeSet < JmsMessageID > ( ) ; this . pendingMessages = new HashMap < JmsMessageID , Message > ( ) ; this . collector = collector ; try { ConnectionFactory cf = this . jmsProvider . connectionFactory ( ) ; Destination dest = this . jmsProvider . destination ( ) ; this . connection = cf . createConnection ( ) ; this . session = connection . createSession ( false , this . jmsAcknowledgeMode ) ; MessageConsumer consumer = session . createConsumer ( dest ) ; consumer . setMessageListener ( this ) ; this . connection . start ( ) ; if ( this . isDurableSubscription ( ) && this . recoveryPeriod > 0 ) { this . recoveryTimer = new Timer ( ) ; this . recoveryTimer . scheduleAtFixedRate ( new RecoveryTask ( ) , 10 , this . recoveryPeriod ) ; } } catch ( Exception e ) { LOG . warn ( "Error creating JMS connection." , e ) ; } |
public class PropositionUtil { /** * Binary search for a primitive parameter by timestamp , optimized for when
* the parameters are stored in a list that does not implement
* < code > java . util . RandomAccess < / code > .
* @ param list
* a < code > List < / code > of < code > PrimitiveParameter < / code >
* objects all with the same paramId , cannot be < code > null < / code > .
* @ param tstamp
* the timestamp we ' re interested in finding .
* @ return a < code > PrimitiveParameter < / code > , or < code > null < / code > if
* not found . */
private static < T extends TemporalProposition > int minStartIteratorBinarySearch ( List < T > list , long tstamp ) { } } | int low = 0 ; int high = list . size ( ) - 1 ; ListIterator < T > i = list . listIterator ( ) ; while ( low <= high ) { /* * We use > > > instead of > > or / 2 to avoid overflow . Sun ' s
* implementation of binary search actually doesn ' t do this ( bug
* # 5045582 ) . */
int mid = ( low + high ) >>> 1 ; TemporalProposition midVal = iteratorBinarySearchGet ( i , mid ) ; Long maxStart = midVal . getInterval ( ) . getMinimumStart ( ) ; int cmp = maxStart != null ? maxStart . compareTo ( tstamp ) : 1 ; if ( cmp < 0 ) { low = mid + 1 ; } else if ( cmp > 0 ) { high = mid - 1 ; } else { return mid ; } } return low ; |
public class CmsCopy { /** * Performs the copy operation for a single VFS resource . < p >
* @ param source the source VFS path
* @ param target the target VFS path
* @ param sitePrefix the site prefix
* @ param copyMode the copy mode for siblings
* @ param overwrite the overwrite flag
* @ throws CmsException if copying the resource fails */
protected void performSingleCopyOperation ( String source , String target , String sitePrefix , CmsResourceCopyMode copyMode , boolean overwrite ) throws CmsException { } } | // calculate the target name
String finalTarget = CmsLinkManager . getAbsoluteUri ( target , CmsResource . getParentFolder ( source ) ) ; if ( finalTarget . equals ( source ) || ( isMultiOperation ( ) && finalTarget . startsWith ( source ) ) ) { throw new CmsVfsException ( Messages . get ( ) . container ( Messages . ERR_COPY_ONTO_ITSELF_1 , finalTarget ) ) ; } try { CmsResource res = getCms ( ) . readResource ( finalTarget , CmsResourceFilter . ALL ) ; if ( res . isFolder ( ) ) { // target folder already exists , so we add the current folder name
if ( ! finalTarget . endsWith ( "/" ) ) { finalTarget += "/" ; } finalTarget = finalTarget + CmsResource . getName ( source ) ; } } catch ( CmsVfsResourceNotFoundException e ) { // target folder does not already exist , so target name is o . k .
if ( LOG . isInfoEnabled ( ) ) { LOG . info ( e . getLocalizedMessage ( ) ) ; } } // set the target parameter value
setParamTarget ( finalTarget ) ; // delete existing target resource if selected or confirmed by the user
if ( overwrite && getCms ( ) . existsResource ( finalTarget ) ) { checkLock ( finalTarget ) ; getCms ( ) . deleteResource ( finalTarget , CmsResource . DELETE_PRESERVE_SIBLINGS ) ; } // copy the resource
getCms ( ) . copyResource ( sitePrefix + source , finalTarget , copyMode ) ; |
public class AttachVolumeRequestMarshaller { /** * Marshall the given parameter object . */
public void marshall ( AttachVolumeRequest attachVolumeRequest , ProtocolMarshaller protocolMarshaller ) { } } | if ( attachVolumeRequest == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( attachVolumeRequest . getGatewayARN ( ) , GATEWAYARN_BINDING ) ; protocolMarshaller . marshall ( attachVolumeRequest . getTargetName ( ) , TARGETNAME_BINDING ) ; protocolMarshaller . marshall ( attachVolumeRequest . getVolumeARN ( ) , VOLUMEARN_BINDING ) ; protocolMarshaller . marshall ( attachVolumeRequest . getNetworkInterfaceId ( ) , NETWORKINTERFACEID_BINDING ) ; protocolMarshaller . marshall ( attachVolumeRequest . getDiskId ( ) , DISKID_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class ResourceTypeProperties { /** * Returns the required locality levels , in order of preference ,
* for the resource type .
* @ param type The type of the resource .
* @ return The list of locality levels . */
public static List < LocalityLevel > neededLocalityLevels ( ResourceType type ) { } } | List < LocalityLevel > l = new ArrayList < LocalityLevel > ( ) ; switch ( type ) { case MAP : l . add ( LocalityLevel . NODE ) ; l . add ( LocalityLevel . RACK ) ; l . add ( LocalityLevel . ANY ) ; break ; case REDUCE : l . add ( LocalityLevel . ANY ) ; break ; case JOBTRACKER : l . add ( LocalityLevel . ANY ) ; break ; default : throw new RuntimeException ( "Undefined locality behavior for " + type ) ; } return l ; |
public class JSRInlinerAdapter { /** * Detects a JSR instruction and sets a flag to indicate we will need to do
* inlining . */
@ Override public void visitJumpInsn ( final int opcode , final Label lbl ) { } } | super . visitJumpInsn ( opcode , lbl ) ; LabelNode ln = ( ( JumpInsnNode ) instructions . getLast ( ) ) . label ; if ( opcode == JSR && ! subroutineHeads . containsKey ( ln ) ) { subroutineHeads . put ( ln , new BitSet ( ) ) ; } |
public class TypedQuery { /** * Add the given list of async listeners on the { @ link com . datastax . driver . core . Row } object .
* Example of usage :
* < pre class = " code " > < code class = " java " >
* . withRowAsyncListeners ( Arrays . asList ( row - > {
* / / Do something with the row object here
* < / code > < / pre >
* Remark : < strong > You can inspect and read values from the row object < / strong > */
public TypedQuery < ENTITY > withRowAsyncListeners ( List < Function < Row , Row > > rowAsyncListeners ) { } } | this . options . setRowAsyncListeners ( Optional . of ( rowAsyncListeners ) ) ; return this ; |
public class EmbeddedView { /** * { @ inheritDoc } */
@ Override protected void initView ( ) { } } | super . initView ( ) ; this . box = new VBox ( ) ; this . box . setAlignment ( Pos . CENTER ) ; final ScrollPane scrollPane = new ScrollPane ( ) ; scrollPane . setPrefSize ( 600 , 600 ) ; scrollPane . setContent ( this . box ) ; node ( ) . setCenter ( scrollPane ) ; addNode ( EmbeddedView . ROOT_EMBEDDED_FXML . get ( ) . node ( ) ) ; // Load 2 more instance
addNode ( EmbeddedView . ROOT_EMBEDDED_FXML . getNew ( ) . node ( ) ) ; addNode ( EmbeddedView . ROOT_EMBEDDED_FXML . getNew ( ) . node ( ) ) ; |
public class ExpressionBasedActionHandler { /** * This method returns the value , associated with the expression , for the
* supplied data .
* @ param trace The trace
* @ param node The node
* @ param direction The direction
* @ param headers The optional headers
* @ param values The values
* @ return The result of the expression */
protected String getValue ( Trace trace , Node node , Direction direction , Map < String , ? > headers , Object [ ] values ) { } } | if ( expression != null ) { return expression . evaluate ( trace , node , direction , headers , values ) ; } return null ; |
public class GitlabAPI { /** * Uploads a file to a project
* @ param project
* @ param file
* @ return
* @ throws IOException on gitlab api call error */
public GitlabUpload uploadFile ( GitlabProject project , File file ) throws IOException { } } | String tailUrl = GitlabProject . URL + "/" + sanitizeProjectId ( project . getId ( ) ) + GitlabUpload . URL ; return dispatch ( ) . withAttachment ( "file" , file ) . to ( tailUrl , GitlabUpload . class ) ; |
public class VaultsInner { /** * Get the Vault details .
* @ param resourceGroupName The name of the resource group where the recovery services vault is present .
* @ param vaultName The name of the recovery services vault .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ throws CloudException thrown if the request is rejected by server
* @ throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @ return the VaultInner object if successful . */
public VaultInner getByResourceGroup ( String resourceGroupName , String vaultName ) { } } | return getByResourceGroupWithServiceResponseAsync ( resourceGroupName , vaultName ) . toBlocking ( ) . single ( ) . body ( ) ; |
public class PAbstractObject { /** * Get a property as a double or throw an exception .
* @ param key the property name */
@ Override public final double getDouble ( final String key ) { } } | Double result = optDouble ( key ) ; if ( result == null ) { throw new ObjectMissingException ( this , key ) ; } return result ; |
public class POSVerb { /** * setter for biolexicon _ id - sets
* @ generated
* @ param v value to set into the feature */
public void setBiolexicon_id ( String v ) { } } | if ( POSVerb_Type . featOkTst && ( ( POSVerb_Type ) jcasType ) . casFeat_biolexicon_id == null ) jcasType . jcas . throwFeatMissing ( "biolexicon_id" , "ch.epfl.bbp.uima.types.POSVerb" ) ; jcasType . ll_cas . ll_setStringValue ( addr , ( ( POSVerb_Type ) jcasType ) . casFeatCode_biolexicon_id , v ) ; |
public class HtmlDocletWriter { /** * Return the link to the given class .
* @ param linkInfo the information about the link .
* @ return the link for the given class . */
public Content getLink ( LinkInfoImpl linkInfo ) { } } | LinkFactoryImpl factory = new LinkFactoryImpl ( this ) ; return factory . getLink ( linkInfo ) ; |
public class HMenuScreen { /** * Get the Html keywords .
* @ return The Keywords . */
public String getHtmlKeywords ( ) { } } | Record recMenu = this . getMainRecord ( ) ; if ( recMenu . getField ( MenusModel . KEYWORDS ) . getLength ( ) > 0 ) return recMenu . getField ( MenusModel . KEYWORDS ) . toString ( ) ; else return super . getHtmlKeywords ( ) ; |
public class InverseMapper { /** * The inverse function . Input keys and values are swapped . */
public void map ( K key , V value , OutputCollector < V , K > output , Reporter reporter ) throws IOException { } } | output . collect ( value , key ) ; |
public class VoiceApi { /** * Retrieve the specified call from hold .
* @ param connId The connection ID of the call .
* @ param reasons Information on causes for , and results of , actions taken by the user of the current DN . For details about reasons , refer to the [ * Genesys Events and Models Reference Manual * ] ( https : / / docs . genesys . com / Documentation / System / Current / GenEM / Reasons ) . ( optional )
* @ param extensions Media device / hardware reason codes and similar information . For details about extensions , refer to the [ * Genesys Events and Models Reference Manual * ] ( https : / / docs . genesys . com / Documentation / System / Current / GenEM / Extensions ) . ( optional ) */
public void retrieveCall ( String connId , KeyValueCollection reasons , KeyValueCollection extensions ) throws WorkspaceApiException { } } | try { VoicecallsidanswerData retrieveData = new VoicecallsidanswerData ( ) ; retrieveData . setReasons ( Util . toKVList ( reasons ) ) ; retrieveData . setExtensions ( Util . toKVList ( extensions ) ) ; RetrieveData data = new RetrieveData ( ) ; data . data ( retrieveData ) ; ApiSuccessResponse response = this . voiceApi . retrieve ( connId , data ) ; throwIfNotOk ( "retrieveCall" , response ) ; } catch ( ApiException e ) { throw new WorkspaceApiException ( "retrieveCall failed." , e ) ; } |
public class IllegalMethodCallCheck { /** * Setter .
* @ param pIllegalMethodNames the list of method names to flag */
public void setIllegalMethodNames ( final String ... pIllegalMethodNames ) { } } | final Set < String > methodNames = new HashSet < > ( ) ; Collections . addAll ( methodNames , pIllegalMethodNames ) ; illegalMethodNames = methodNames ; |
public class SpaceAPI { /** * Adds a list of users ( either through user _ id or email ) to the space .
* @ param spaceId
* The id of the space
* @ param spaceMemberAdd
* Information about the user ( s ) to add */
public void addSpaceMembers ( int spaceId , SpaceMemberAdd spaceMemberAdd ) { } } | getResourceFactory ( ) . getApiResource ( "/space/" + spaceId + "/member/" ) . entity ( spaceMemberAdd , MediaType . APPLICATION_JSON_TYPE ) . post ( ) ; |
public class KeyDispatcher { /** * documentation inherited from interface WindowFocusListener */
public void windowLostFocus ( WindowEvent e ) { } } | // un - press any keys that were left down
if ( ! _downKeys . isEmpty ( ) ) { long now = System . currentTimeMillis ( ) ; for ( KeyEvent down : _downKeys . values ( ) ) { KeyEvent up = new KeyEvent ( down . getComponent ( ) , KeyEvent . KEY_RELEASED , now , down . getModifiers ( ) , down . getKeyCode ( ) , down . getKeyChar ( ) , down . getKeyLocation ( ) ) ; for ( int ii = 0 , nn = _listeners . size ( ) ; ii < nn ; ii ++ ) { _listeners . get ( ii ) . keyReleased ( up ) ; } } _downKeys . clear ( ) ; } |
public class EndpointMethodHelper { /** * introspectPathParams
* @ param method */
public void introspectPathParams ( ) throws DeploymentException { } } | // Section 4.3 JSR 356 - The allowed types for the @ PathParam parameters are String , any Java primitive type , or boxed version thereof .
Class < ? > [ ] pathParamTypesAllowed = { String . class , char . class , Character . class , byte . class , Byte . class , short . class , Short . class , int . class , Integer . class , long . class , Long . class , float . class , Float . class , double . class , Double . class , boolean . class , Boolean . class } ; List < Class < ? > > pathParamTypeList = Arrays . asList ( pathParamTypesAllowed ) ; Class < ? > [ ] paramTypes = method . getParameterTypes ( ) ; Annotation [ ] [ ] paramAnnotations = method . getParameterAnnotations ( ) ; boolean uriSegmentMatched = true ; for ( int i = 0 ; i < paramAnnotations . length ; i ++ ) { for ( Annotation annotation : paramAnnotations [ i ] ) { if ( annotation . annotationType ( ) == javax . websocket . server . PathParam . class ) { if ( pathParamTypeList . contains ( paramTypes [ i ] ) ) { String pathParamValue = ( ( PathParam ) annotation ) . value ( ) ; if ( pathParamValue != null && ! ( pathParamValue . isEmpty ( ) ) ) { // check if user has defined @ PathParam variable on a method , but there is no corresponding matching path segment in endpoint path
// for e . g user might have defined " @ PathParam ( " Boolean - var " ) Boolean BooleanVar " on onOpen ( ) and the server endpoint path
// is / somePath / { Integer - var } / { Long - var }
List < String > segments = Arrays . asList ( endpointPath . split ( "/" ) ) ; if ( ! ( segments . contains ( "{" + pathParamValue + "}" ) ) && ! ( segments . contains ( pathParamValue ) ) ) { // error case : @ PathParam does not match any path segment in the uri
if ( tc . isDebugEnabled ( ) ) { String msg = "@PathParam parameter " + pathParamValue + " defined on the method " + method . getName ( ) + " does not have corresponding path segment in @ServerEndpoint URI in Annotated endpoint " + method . getDeclaringClass ( ) . getName ( ) ; Tr . debug ( tc , msg ) ; } // set the parameter to null . This is needed for String type of param .
uriSegmentMatched = false ; } // create PathParamData with annotation , the parameter index which has @ PathParam declared , type of the parameter .
PathParamData paramData = new PathParamDataImpl ( pathParamValue , i , paramTypes [ i ] , uriSegmentMatched ) ; // use key for the hashmap as parameter index which has @ PathParam declared , so that we can retrieve the correct PathParamData
// during parameter value substitution
methodData . getPathParams ( ) . put ( Integer . valueOf ( i ) , paramData ) ; } else { // section 4.3 jsr 356 . The value attribute of this annotation must be present otherwise the implementation must throw an error . [ WSC - 4.3-2]
String msg = Tr . formatMessage ( tc , "missing.pathparam.value" , ( ( PathParam ) annotation ) . value ( ) , method . getName ( ) , method . getDeclaringClass ( ) . getName ( ) ) ; Tr . error ( tc , "missing.pathparam.value" , ( ( PathParam ) annotation ) . value ( ) , method . getName ( ) , method . getDeclaringClass ( ) . getName ( ) ) ; throw new DeploymentException ( msg ) ; } } else { // section 4.3 jsr 356 . " The allowed types for the @ PathParam parameters are String , any Java primitive type , or boxed version thereof . Any other type
// annotated with this annotation is an error that the implementation must report at deployment time . [ WSC - 4.3-1 ] "
String msg = Tr . formatMessage ( tc , "invalid.pathparam.type" , ( ( PathParam ) annotation ) . value ( ) , method . getName ( ) , method . getDeclaringClass ( ) . getName ( ) ) ; Tr . error ( tc , "invalid.pathparam.type" , ( ( PathParam ) annotation ) . value ( ) , method . getName ( ) , method . getDeclaringClass ( ) . getName ( ) ) ; throw new DeploymentException ( msg ) ; } } } } |
public class PhoneNumberAssociationMarshaller { /** * Marshall the given parameter object . */
public void marshall ( PhoneNumberAssociation phoneNumberAssociation , ProtocolMarshaller protocolMarshaller ) { } } | if ( phoneNumberAssociation == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( phoneNumberAssociation . getValue ( ) , VALUE_BINDING ) ; protocolMarshaller . marshall ( phoneNumberAssociation . getName ( ) , NAME_BINDING ) ; protocolMarshaller . marshall ( phoneNumberAssociation . getAssociatedTimestamp ( ) , ASSOCIATEDTIMESTAMP_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class HadoopConfigurationInjector { /** * Gets the path to the directory in which the generated links and Hadoop
* conf properties files are written .
* @ param props The Azkaban properties
* @ param workingDir The Azkaban job working directory */
public static String getPath ( Props props , String workingDir ) { } } | return new File ( workingDir , getDirName ( props ) ) . toString ( ) ; |
public class Body { /** * Answer a { @ code byte [ ] } from { @ code body } bytes .
* @ param body the ByteBuffer
* @ return String */
private static byte [ ] bufferToArray ( final ByteBuffer body ) { } } | if ( body . position ( ) > 0 ) { body . flip ( ) ; } final int length = body . limit ( ) ; final byte [ ] bytes = new byte [ length ] ; System . arraycopy ( body . array ( ) , 0 , bytes , 0 , length ) ; return bytes ; |
public class UploadOfflineData { /** * Returns a new offline data object with the specified values . */
private static OfflineData createOfflineData ( DateTime transactionTime , long transactionMicroAmount , String transactionCurrency , String conversionName , List < UserIdentifier > userIdentifiers ) { } } | StoreSalesTransaction storeSalesTransaction = new StoreSalesTransaction ( ) ; // For times use the format yyyyMMdd HHmmss [ tz ] .
// For details , see
// https : / / developers . google . com / adwords / api / docs / appendix / codes - formats # date - and - time - formats
storeSalesTransaction . setTransactionTime ( transactionTime . toString ( "yyyyMMdd HHmmss ZZZ" ) ) ; storeSalesTransaction . setConversionName ( conversionName ) ; storeSalesTransaction . setUserIdentifiers ( userIdentifiers . toArray ( new UserIdentifier [ userIdentifiers . size ( ) ] ) ) ; Money money = new Money ( ) ; money . setMicroAmount ( transactionMicroAmount ) ; MoneyWithCurrency moneyWithCurrency = new MoneyWithCurrency ( ) ; moneyWithCurrency . setMoney ( money ) ; moneyWithCurrency . setCurrencyCode ( transactionCurrency ) ; storeSalesTransaction . setTransactionAmount ( moneyWithCurrency ) ; OfflineData offlineData = new OfflineData ( ) ; offlineData . setStoreSalesTransaction ( storeSalesTransaction ) ; return offlineData ; |
public class ScriptEnvironmentManager { /** * Gets the scripting environment name given the script extension .
* @ param extension the scripting environment extension
* @ return the scripting environment name */
public String getEnvironmentNameForExtension ( String extension ) { } } | Preconditions . checkArgument ( StringUtils . isNotNullOrBlank ( extension ) , "Extension name cannot be null or empty" ) ; ScriptEngine engine = engineManager . getEngineByExtension ( extension ) ; Preconditions . checkArgument ( engine != null , extension + " is not a recognized scripting extension." ) ; return engine . getFactory ( ) . getLanguageName ( ) ; |
public class MPP14Reader { /** * The project files to which external tasks relate appear not to be
* held against each task , instead there appears to be the concept
* of the " current " external task file , i . e . the last one used .
* This method iterates through the list of tasks marked as external
* and attempts to ensure that the correct external project data ( in the
* form of a SubProject object ) is linked to the task .
* @ param externalTasks list of tasks marked as external */
private void processExternalTasks ( List < Task > externalTasks ) { } } | // Sort the list of tasks into ID order
Collections . sort ( externalTasks ) ; // Find any external tasks which don ' t have a sub project
// object , and set this attribute using the most recent
// value .
SubProject currentSubProject = null ; for ( Task currentTask : externalTasks ) { SubProject sp = currentTask . getSubProject ( ) ; if ( sp == null ) { currentTask . setSubProject ( currentSubProject ) ; // we need to set the external task project path now that we have
// the subproject for this task ( was skipped while processing the task earlier )
if ( currentSubProject != null ) { currentTask . setExternalTaskProject ( currentSubProject . getFullPath ( ) ) ; } } else { currentSubProject = sp ; } if ( currentSubProject != null ) { // System . out . println ( " Task : " + currentTask . getUniqueID ( ) + " " + currentTask . getName ( ) + " File = " + currentSubProject . getFullPath ( ) + " ID = " + currentTask . getExternalTaskID ( ) ) ;
currentTask . setProject ( currentSubProject . getFullPath ( ) ) ; } } |
public class NullAway { /** * check that nullability annotations of an overriding method are consistent with those in the
* overridden method ( both return and parameters )
* @ param overriddenMethod method being overridden
* @ param overridingMethod overriding method
* @ param memberReferenceTree if override is via a method reference , the relevant { @ link
* MemberReferenceTree } ; otherwise { @ code null } . If non - null , overridingTree is the AST of the
* referenced method
* @ param state
* @ return discovered error , or { @ link Description # NO _ MATCH } if no error */
private Description checkOverriding ( Symbol . MethodSymbol overriddenMethod , Symbol . MethodSymbol overridingMethod , @ Nullable MemberReferenceTree memberReferenceTree , VisitorState state ) { } } | final boolean isOverridenMethodUnannotated = NullabilityUtil . isUnannotated ( overriddenMethod , config ) ; final boolean overriddenMethodReturnsNonNull = ( ( isOverridenMethodUnannotated && handler . onUnannotatedInvocationGetExplicitlyNonNullReturn ( overriddenMethod , false ) ) || ( ! isOverridenMethodUnannotated && ! Nullness . hasNullableAnnotation ( overriddenMethod ) ) ) ; // if the super method returns nonnull ,
// overriding method better not return nullable
if ( overriddenMethodReturnsNonNull && Nullness . hasNullableAnnotation ( overridingMethod ) && getComputedNullness ( memberReferenceTree ) . equals ( Nullness . NULLABLE ) ) { String message ; if ( memberReferenceTree != null ) { message = "referenced method returns @Nullable, but functional interface method " + ASTHelpers . enclosingClass ( overriddenMethod ) + "." + overriddenMethod . toString ( ) + " returns @NonNull" ; } else { message = "method returns @Nullable, but superclass method " + ASTHelpers . enclosingClass ( overriddenMethod ) + "." + overriddenMethod . toString ( ) + " returns @NonNull" ; } Tree errorTree = memberReferenceTree != null ? memberReferenceTree : getTreesInstance ( state ) . getTree ( overridingMethod ) ; return errorBuilder . createErrorDescription ( new ErrorMessage ( MessageTypes . WRONG_OVERRIDE_RETURN , message ) , state . getPath ( ) , buildDescription ( errorTree ) ) ; } // if any parameter in the super method is annotated @ Nullable ,
// overriding method cannot assume @ Nonnull
return checkParamOverriding ( overridingMethod . getParameters ( ) , overriddenMethod , null , memberReferenceTree , state ) ; |
import java . util . * ; class IsOddAtOddIndex { /** * This function checks if every odd index of the input list contains odd numbers .
* > > > is _ odd _ at _ odd _ index ( [ 2 , 1 , 4 , 3 , 6 , 7 , 6 , 3 ] )
* True
* > > > is _ odd _ at _ odd _ index ( [ 4 , 1 , 2 ] )
* True
* > > > is _ odd _ at _ odd _ index ( [ 1 , 2 , 3 ] )
* False */
public static Boolean isOddAtOddIndex ( List < Integer > numbers ) { } } | for ( int i = 1 ; i < numbers . size ( ) ; i += 2 ) { if ( numbers . get ( i ) % 2 == 0 ) { return false ; } } return true ; |
public class SMailHonestPostie { protected void prepareAsync ( Postcard postcard ) { } } | if ( asyncStrategy . alwaysAsync ( postcard ) && ! postcard . isAsync ( ) ) { logger . debug ( "...Calling async() automatically by strategy: {}" , asyncStrategy ) ; postcard . async ( ) ; } |
public class Matrix { /** * Repeat elements < code > rowRepeats < / code > times in row direction and < code > colRepeats < / code > times in column direction .
* @ param rowRepeats
* @ param colRepeats
* @ return a new matrix
* @ see IntMatrix # repelem ( int , int ) */
@ Override public Matrix < T > repelem ( final int rowRepeats , final int colRepeats ) { } } | N . checkArgument ( rowRepeats > 0 && colRepeats > 0 , "rowRepeats=%s and colRepeats=%s must be bigger than 0" , rowRepeats , colRepeats ) ; final T [ ] [ ] c = N . newArray ( arrayType , rows * rowRepeats ) ; for ( int i = 0 , len = c . length ; i < len ; i ++ ) { c [ i ] = N . newArray ( componentType , cols * colRepeats ) ; } for ( int i = 0 ; i < rows ; i ++ ) { final T [ ] fr = c [ i * rowRepeats ] ; for ( int j = 0 ; j < cols ; j ++ ) { N . copy ( Array . repeat ( a [ i ] [ j ] , colRepeats ) , 0 , fr , j * colRepeats , colRepeats ) ; } for ( int k = 1 ; k < rowRepeats ; k ++ ) { N . copy ( fr , 0 , c [ i * rowRepeats + k ] , 0 , fr . length ) ; } } return new Matrix < T > ( c ) ; |
public class SpearmanCorrelation { /** * Estimates Spearman ' s Correlation for the provided data .
* @ param transposeDataList
* @ return */
public static double calculateCorrelation ( TransposeDataList transposeDataList ) { } } | Object [ ] keys = transposeDataList . keySet ( ) . toArray ( ) ; if ( keys . length != 2 ) { throw new IllegalArgumentException ( "The collection must contain observations from 2 groups." ) ; } Object keyX = keys [ 0 ] ; Object keyY = keys [ 1 ] ; FlatDataList flatDataListX = transposeDataList . get ( keyX ) . copy ( ) ; FlatDataList flatDataListY = transposeDataList . get ( keyY ) . copy ( ) ; int n = flatDataListX . size ( ) ; if ( n <= 0 || n != flatDataListY . size ( ) ) { throw new IllegalArgumentException ( "The number of observations in each group must be equal and larger than 0." ) ; } // converts the values of the X table with its Ranks
AssociativeArray tiesCounter = Ranks . getRanksFromValues ( flatDataListX ) ; // Estimate Rx _ square
double Sum_Rx_square = ( n * n - 1.0 ) * n ; for ( Object value : tiesCounter . values ( ) ) { double Ti = TypeInference . toDouble ( value ) ; Sum_Rx_square -= ( ( Ti * Ti - 1.0 ) * Ti ) ; // faster than using pow ( )
} Sum_Rx_square /= 12.0 ; // tiesCounter = null ;
// converts the values of the Y table with its Ranks
tiesCounter = Ranks . getRanksFromValues ( flatDataListY ) ; // Estimate Ry _ square
double Sum_Ry_square = ( n * n - 1.0 ) * n ; for ( Object value : tiesCounter . values ( ) ) { double Ti = TypeInference . toDouble ( value ) ; Sum_Ry_square -= ( ( Ti * Ti - 1.0 ) * Ti ) ; // faster than using pow ( )
} Sum_Ry_square /= 12.0 ; // tiesCounter = null ;
// calculate the sum of Di ^ 2
double Sum_Di_square = 0 ; for ( int j = 0 ; j < n ; ++ j ) { double di = flatDataListX . getDouble ( j ) - flatDataListY . getDouble ( j ) ; Sum_Di_square += di * di ; } // Finally we estimate the Spearman Correlation
double Rs = ( Sum_Rx_square + Sum_Ry_square - Sum_Di_square ) / ( 2.0 * Math . sqrt ( Sum_Rx_square * Sum_Ry_square ) ) ; return Rs ; |
public class SwaggerController { /** * Serves the Swagger description of the REST API . As host , fills in the host where the controller
* lives . As options for the entity names , contains only those entity names that the user can
* actually see . */
@ GetMapping ( value = "/swagger.yml" , produces = "text/yaml" ) public String swagger ( Model model , HttpServletResponse response ) { } } | response . setContentType ( "text/yaml" ) ; response . setCharacterEncoding ( "UTF-8" ) ; final UriComponents uriComponents = ServletUriComponentsBuilder . fromCurrentContextPath ( ) . build ( ) ; model . addAttribute ( "scheme" , uriComponents . getScheme ( ) ) ; String host = uriComponents . getHost ( ) ; if ( uriComponents . getPort ( ) >= 0 ) { host += ":" + uriComponents . getPort ( ) ; } model . addAttribute ( "host" , host ) ; model . addAttribute ( "entityTypes" , metaDataService . getEntityTypes ( ) . filter ( e -> ! e . isAbstract ( ) ) . map ( EntityType :: getId ) . sorted ( ) . collect ( toList ( ) ) ) ; model . addAttribute ( "attributeTypes" , AttributeType . getOptionsLowercase ( ) ) ; model . addAttribute ( "languageCodes" , getLanguageCodes ( ) . collect ( toList ( ) ) ) ; return "view-swagger" ; |
public class ModuleTypeLoader { /** * Adds the type to the cache . */
private IType cacheType ( String name , Pair < IType , ITypeLoader > pair ) { } } | if ( pair != null ) { IType type = pair . getFirst ( ) ; // We have to make sure we aren ' t replacing an existing type so we obey the return from the put .
IType oldType = _typesByName . get ( name ) ; if ( oldType != null && oldType != CACHE_MISS ) { return oldType ; } _typesByName . add ( name , type ) ; ITypeLoader typeLoader = pair . getSecond ( ) ; if ( typeLoader != null && ! typeLoader . isCaseSensitive ( ) ) { _typesByCaseInsensitiveName . put ( name , type ) ; } } return pair != null ? pair . getFirst ( ) : null ; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.