signature stringlengths 43 39.1k | implementation stringlengths 0 450k |
|---|---|
public class PrcWageCopy { /** * < p > Process entity request . < / p >
* @ param pAddParam additional param , e . g . return this line ' s
* document in " nextEntity " for farther process
* @ param pRequestData Request Data
* @ param pEntity Entity to process
* @ return Entity processed for farther process or null
* @ throws Exception - an exception */
@ Override public final Wage process ( final Map < String , Object > pAddParam , final Wage pEntity , final IRequestData pRequestData ) throws Exception { } } | Wage entity = this . prcAccEntityPbCopy . process ( pAddParam , pEntity , pRequestData ) ; entity . setReversedId ( null ) ; entity . setItsTotal ( BigDecimal . ZERO ) ; entity . setItsDate ( new Date ( ) ) ; entity . setHasMadeAccEntries ( false ) ; entity . setTotalTaxesEmployer ( BigDecimal . ZERO ) ; entity . setTotalTaxesEmployee ( BigDecimal . ZERO ) ; entity . setNetWage ( BigDecimal . ZERO ) ; return entity ; |
public class CmsAliasModeColumn { /** * Creates the options for the select box . < p >
* @ return the options for the select box */
public static List < String > createOptions ( ) { } } | List < String > result = new ArrayList < String > ( ) ; result . add ( nameLookup . get ( CmsAliasMode . permanentRedirect ) ) ; result . add ( nameLookup . get ( CmsAliasMode . redirect ) ) ; result . add ( nameLookup . get ( CmsAliasMode . page ) ) ; return result ; |
public class DriverLauncher { /** * Update job status and notify the waiting thread . */
public synchronized void setStatusAndNotify ( final LauncherStatus newStatus ) { } } | LOG . log ( Level . FINEST , "Set status: {0} -> {1}" , new Object [ ] { this . status , newStatus } ) ; this . status = newStatus ; this . notify ( ) ; |
public class CmsExtendedWorkflowManager { /** * Helper method for generating the workflow response which should be sent when publishing the resources would break relations . < p >
* @ param userCms the user ' s CMS context
* @ param publishResources the resources whose links would be broken
* @ return the workflow response */
protected CmsWorkflowResponse getPublishBrokenRelationsResponse ( CmsObject userCms , List < CmsPublishResource > publishResources ) { } } | List < CmsWorkflowAction > actions = new ArrayList < CmsWorkflowAction > ( ) ; String forcePublishLabel = Messages . get ( ) . getBundle ( getLocale ( userCms ) ) . key ( Messages . GUI_WORKFLOW_ACTION_FORCE_PUBLISH_0 ) ; CmsWorkflowAction forcePublish = new CmsWorkflowAction ( ACTION_FORCE_PUBLISH , forcePublishLabel , true , true ) ; actions . add ( forcePublish ) ; return new CmsWorkflowResponse ( false , Messages . get ( ) . getBundle ( getLocale ( userCms ) ) . key ( Messages . GUI_BROKEN_LINKS_0 ) , publishResources , actions , null ) ; |
public class MonthDay { /** * Queries this month - day using the specified query .
* This queries this month - day using the specified query strategy object .
* The { @ code TemporalQuery } object defines the logic to be used to
* obtain the result . Read the documentation of the query to understand
* what the result of this method will be .
* The result of this method is obtained by invoking the
* { @ link TemporalQuery # queryFrom ( TemporalAccessor ) } method on the
* specified query passing { @ code this } as the argument .
* @ param < R > the type of the result
* @ param query the query to invoke , not null
* @ return the query result , null may be returned ( defined by the query )
* @ throws DateTimeException if unable to query ( defined by the query )
* @ throws ArithmeticException if numeric overflow occurs ( defined by the query ) */
@ SuppressWarnings ( "unchecked" ) @ Override public < R > R query ( TemporalQuery < R > query ) { } } | if ( query == TemporalQueries . chronology ( ) ) { return ( R ) IsoChronology . INSTANCE ; } return super . query ( query ) ; |
public class MapExtractor { /** * { @ inheritDoc } */
public T extract ( Object target ) { } } | if ( target == null ) { return null ; } if ( ! ( target instanceof Map ) ) { throw new IllegalArgumentException ( "Extraction target is not a Map" ) ; } return ( T ) ( ( Map ) target ) . get ( key ) ; |
public class BaseDistribution { /** * { @ inheritDoc }
* The default implementation returns
* < ul >
* < li > { @ link # getSupportLowerBound ( ) } for { @ code p = 0 } , < / li >
* < li > { @ link # getSupportUpperBound ( ) } for { @ code p = 1 } . < / li >
* < / ul > */
@ Override public double inverseCumulativeProbability ( final double p ) throws OutOfRangeException { } } | /* * IMPLEMENTATION NOTES
* Where applicable , use is made of the one - sided Chebyshev inequality
* to bracket the root . This inequality states that
* P ( X - mu > = k * sig ) < = 1 / ( 1 + k ^ 2 ) ,
* mu : mean , sig : standard deviation . Equivalently
* 1 - P ( X < mu + k * sig ) < = 1 / ( 1 + k ^ 2 ) ,
* F ( mu + k * sig ) > = k ^ 2 / ( 1 + k ^ 2 ) .
* For k = sqrt ( p / ( 1 - p ) ) , we find
* F ( mu + k * sig ) > = p ,
* and ( mu + k * sig ) is an upper - bound for the root .
* Then , introducing Y = - X , mean ( Y ) = - mu , sd ( Y ) = sig , and
* P ( Y > = - mu + k * sig ) < = 1 / ( 1 + k ^ 2 ) ,
* P ( - X > = - mu + k * sig ) < = 1 / ( 1 + k ^ 2 ) ,
* P ( X < = mu - k * sig ) < = 1 / ( 1 + k ^ 2 ) ,
* F ( mu - k * sig ) < = 1 / ( 1 + k ^ 2 ) .
* For k = sqrt ( ( 1 - p ) / p ) , we find
* F ( mu - k * sig ) < = p ,
* and ( mu - k * sig ) is a lower - bound for the root .
* In cases where the Chebyshev inequality does not apply , geometric
* progressions 1 , 2 , 4 , . . . and - 1 , - 2 , - 4 , . . . are used to bracket
* the root . */
if ( p < 0.0 || p > 1.0 ) { throw new OutOfRangeException ( p , 0 , 1 ) ; } double lowerBound = getSupportLowerBound ( ) ; if ( p == 0.0 ) { return lowerBound ; } double upperBound = getSupportUpperBound ( ) ; if ( p == 1.0 ) { return upperBound ; } final double mu = getNumericalMean ( ) ; final double sig = FastMath . sqrt ( getNumericalVariance ( ) ) ; final boolean chebyshevApplies ; chebyshevApplies = ! ( Double . isInfinite ( mu ) || Double . isNaN ( mu ) || Double . isInfinite ( sig ) || Double . isNaN ( sig ) ) ; if ( lowerBound == Double . NEGATIVE_INFINITY ) { if ( chebyshevApplies ) { lowerBound = mu - sig * FastMath . sqrt ( ( 1. - p ) / p ) ; } else { lowerBound = - 1.0 ; while ( cumulativeProbability ( lowerBound ) >= p ) { lowerBound *= 2.0 ; } } } if ( upperBound == Double . POSITIVE_INFINITY ) { if ( chebyshevApplies ) { upperBound = mu + sig * FastMath . sqrt ( p / ( 1. - p ) ) ; } else { upperBound = 1.0 ; while ( cumulativeProbability ( upperBound ) < p ) { upperBound *= 2.0 ; } } } final UnivariateFunction toSolve = new UnivariateFunction ( ) { public double value ( final double x ) { return cumulativeProbability ( x ) - p ; } } ; double x = UnivariateSolverUtils . solve ( toSolve , lowerBound , upperBound , getSolverAbsoluteAccuracy ( ) ) ; if ( ! isSupportConnected ( ) ) { /* Test for plateau . */
final double dx = getSolverAbsoluteAccuracy ( ) ; if ( x - dx >= getSupportLowerBound ( ) ) { double px = cumulativeProbability ( x ) ; if ( cumulativeProbability ( x - dx ) == px ) { upperBound = x ; while ( upperBound - lowerBound > dx ) { final double midPoint = 0.5 * ( lowerBound + upperBound ) ; if ( cumulativeProbability ( midPoint ) < px ) { lowerBound = midPoint ; } else { upperBound = midPoint ; } } return upperBound ; } } } return x ; |
public class DefaultFaceletContext { /** * { @ inheritDoc } */
@ Override public void setAttribute ( String name , Object value ) { } } | if ( _varMapper != null ) { if ( value == null ) { _varMapper . setVariable ( name , null ) ; } else { _varMapper . setVariable ( name , _facelet . getExpressionFactory ( ) . createValueExpression ( value , Object . class ) ) ; } } |
public class Phenotype { /** * Return a new phenotype with the the genotype of this and with new
* fitness function , fitness scaler and generation .
* @ param generation the generation of the new phenotype .
* @ param function the ( new ) fitness scaler of the created phenotype .
* @ param scaler the ( new ) fitness scaler of the created phenotype
* @ return a new phenotype with the given values .
* @ throws NullPointerException if one of the values is { @ code null } .
* @ throws IllegalArgumentException if the given { @ code generation } is
* { @ code < 0 } .
* @ deprecated Will be removed in a later version */
@ Deprecated public Phenotype < G , C > newInstance ( final long generation , final Function < ? super Genotype < G > , ? extends C > function , final Function < ? super C , ? extends C > scaler ) { } } | return of ( _genotype , generation , function , scaler ) ; |
public class AbstractFilterButtons { /** * Insert the update icons next to the filter tags in target , distribution
* and software module tags / types tables */
public void addUpdateColumn ( ) { } } | if ( alreadyContainsColumn ( SPUIDefinitions . UPDATE_FILTER_BUTTON_COLUMN ) ) { return ; } deleteColumnIfVisible ( SPUIDefinitions . DELETE_FILTER_BUTTON_COLUMN ) ; addGeneratedColumn ( SPUIDefinitions . UPDATE_FILTER_BUTTON_COLUMN , ( source , itemId , columnId ) -> addUpdateCell ( itemId ) ) ; |
public class SnitchProperties { /** * Get a snitch property value or return defaultValue if not defined . */
public String get ( String propertyName , String defaultValue ) { } } | return properties . getProperty ( propertyName , defaultValue ) ; |
public class HystrixServoMetricsPublisherCollapser { /** * Servo will flatten metric names as : getServoTypeTag ( ) _ getServoInstanceTag ( ) _ monitorName
* An implementation note . If there ' s a version mismatch between hystrix - core and hystrix - servo - metric - publisher ,
* the code below may reference a HystrixEventType . Collapser that does not exist in hystrix - core . If this happens ,
* a j . l . NoSuchFieldError occurs . Since this data is not being generated by hystrix - core , it ' s safe to count it as 0
* and we should log an error to get users to update their dependency set . */
private List < Monitor < ? > > getServoMonitors ( ) { } } | List < Monitor < ? > > monitors = new ArrayList < Monitor < ? > > ( ) ; monitors . add ( new InformationalMetric < String > ( MonitorConfig . builder ( "name" ) . build ( ) ) { @ Override public String getValue ( ) { return key . name ( ) ; } } ) ; // allow Servo and monitor to know exactly at what point in time these stats are for so they can be plotted accurately
monitors . add ( new GaugeMetric ( MonitorConfig . builder ( "currentTime" ) . withTag ( DataSourceLevel . DEBUG ) . build ( ) ) { @ Override public Number getValue ( ) { return System . currentTimeMillis ( ) ; } } ) ; // collapser event cumulative metrics
monitors . add ( safelyGetCumulativeMonitor ( "countRequestsBatched" , new Func0 < HystrixEventType . Collapser > ( ) { @ Override public HystrixEventType . Collapser call ( ) { return HystrixEventType . Collapser . ADDED_TO_BATCH ; } } ) ) ; monitors . add ( safelyGetCumulativeMonitor ( "countBatches" , new Func0 < HystrixEventType . Collapser > ( ) { @ Override public HystrixEventType . Collapser call ( ) { return HystrixEventType . Collapser . BATCH_EXECUTED ; } } ) ) ; monitors . add ( safelyGetCumulativeMonitor ( "countResponsesFromCache" , new Func0 < HystrixEventType . Collapser > ( ) { @ Override public HystrixEventType . Collapser call ( ) { return HystrixEventType . Collapser . RESPONSE_FROM_CACHE ; } } ) ) ; // batch size distribution metrics
monitors . add ( getBatchSizeMeanMonitor ( "batchSize_mean" ) ) ; monitors . add ( getBatchSizePercentileMonitor ( "batchSize_percentile_25" , 25 ) ) ; monitors . add ( getBatchSizePercentileMonitor ( "batchSize_percentile_50" , 50 ) ) ; monitors . add ( getBatchSizePercentileMonitor ( "batchSize_percentile_75" , 75 ) ) ; monitors . add ( getBatchSizePercentileMonitor ( "batchSize_percentile_95" , 95 ) ) ; monitors . add ( getBatchSizePercentileMonitor ( "batchSize_percentile_99" , 99 ) ) ; monitors . add ( getBatchSizePercentileMonitor ( "batchSize_percentile_99_5" , 99.5 ) ) ; monitors . add ( getBatchSizePercentileMonitor ( "batchSize_percentile_100" , 100 ) ) ; // shard size distribution metrics
monitors . add ( getShardSizeMeanMonitor ( "shardSize_mean" ) ) ; monitors . add ( getShardSizePercentileMonitor ( "shardSize_percentile_25" , 25 ) ) ; monitors . add ( getShardSizePercentileMonitor ( "shardSize_percentile_50" , 50 ) ) ; monitors . add ( getShardSizePercentileMonitor ( "shardSize_percentile_75" , 75 ) ) ; monitors . add ( getShardSizePercentileMonitor ( "shardSize_percentile_95" , 95 ) ) ; monitors . add ( getShardSizePercentileMonitor ( "shardSize_percentile_99" , 99 ) ) ; monitors . add ( getShardSizePercentileMonitor ( "shardSize_percentile_99_5" , 99.5 ) ) ; monitors . add ( getShardSizePercentileMonitor ( "shardSize_percentile_100" , 100 ) ) ; // properties ( so the values can be inspected and monitored )
monitors . add ( new InformationalMetric < Number > ( MonitorConfig . builder ( "propertyValue_rollingStatisticalWindowInMilliseconds" ) . build ( ) ) { @ Override public Number getValue ( ) { return properties . metricsRollingStatisticalWindowInMilliseconds ( ) . get ( ) ; } } ) ; monitors . add ( new InformationalMetric < Boolean > ( MonitorConfig . builder ( "propertyValue_requestCacheEnabled" ) . build ( ) ) { @ Override public Boolean getValue ( ) { return properties . requestCacheEnabled ( ) . get ( ) ; } } ) ; monitors . add ( new InformationalMetric < Number > ( MonitorConfig . builder ( "propertyValue_maxRequestsInBatch" ) . build ( ) ) { @ Override public Number getValue ( ) { return properties . maxRequestsInBatch ( ) . get ( ) ; } } ) ; monitors . add ( new InformationalMetric < Number > ( MonitorConfig . builder ( "propertyValue_timerDelayInMilliseconds" ) . build ( ) ) { @ Override public Number getValue ( ) { return properties . timerDelayInMilliseconds ( ) . get ( ) ; } } ) ; return monitors ; |
public class Parser { /** * Parse string to check presence of INSERT keyword regardless of case .
* @ param query char [ ] of the query statement
* @ param offset position of query to start checking
* @ return boolean indicates presence of word */
public static boolean parseInsertKeyword ( final char [ ] query , int offset ) { } } | if ( query . length < ( offset + 7 ) ) { return false ; } return ( query [ offset ] | 32 ) == 'i' && ( query [ offset + 1 ] | 32 ) == 'n' && ( query [ offset + 2 ] | 32 ) == 's' && ( query [ offset + 3 ] | 32 ) == 'e' && ( query [ offset + 4 ] | 32 ) == 'r' && ( query [ offset + 5 ] | 32 ) == 't' ; |
public class FeatureAttributeWindow { /** * Build the entire widget .
* @ param layer layer */
private void buildWidget ( VectorLayer layer ) { } } | mapModel = layer . getMapModel ( ) ; setTitle ( I18nProvider . getAttribute ( ) . getAttributeWindowTitle ( "" ) ) ; setCanDragReposition ( true ) ; setCanDragResize ( true ) ; attributeTable = new FeatureAttributeEditor ( layer , true , factory ) ; toolStrip = new ToolStrip ( ) ; toolStrip . setWidth100 ( ) ; toolStrip . setPadding ( WidgetLayout . marginSmall ) ; toolStrip . addMember ( new ZoomButton ( ) ) ; editButton = new EditButton ( ) ; LayoutSpacer spacer = new LayoutSpacer ( ) ; spacer . setWidth ( 2 ) ; toolStrip . addMember ( spacer ) ; if ( editingAllowed ) { toolStrip . addMember ( editButton ) ; } savePanel = new HLayout ( WidgetLayout . marginSmall ) ; saveButton = new SaveButton ( ) ; IButton resetButton = new ResetButton ( ) ; IButton cancelButton = new CancelButton ( ) ; savePanel . addMember ( saveButton ) ; savePanel . addMember ( resetButton ) ; savePanel . addMember ( cancelButton ) ; savePanel . setVisible ( false ) ; savePanel . setAlign ( Alignment . CENTER ) ; savePanel . setPadding ( WidgetLayout . marginSmall ) ; VLayout layout = new VLayout ( ) ; layout . addMember ( toolStrip ) ; layout . addMember ( attributeTable ) ; layout . addMember ( savePanel ) ; layout . setWidth ( WidgetLayout . featureAttributeWindowLayoutWidth ) ; addItem ( layout ) ; // Set the save button as disabled at startup :
addDrawHandler ( new DrawHandler ( ) { public void onDraw ( DrawEvent event ) { saveButton . setDisabled ( true ) ; } } ) ; |
public class IabHelper { /** * Dispose of object , releasing resources . It ' s very important to call this
* method when you are done with this object . It will release any resources
* used by it such as service connections . Naturally , once the object is
* disposed of , it can ' t be used again . */
public void dispose ( ) { } } | logDebug ( "Disposing." ) ; mSetupDone = false ; if ( mServiceConn != null ) { logDebug ( "Unbinding from service." ) ; if ( mContext != null ) mContext . unbindService ( mServiceConn ) ; } mDisposed = true ; mContext = null ; mServiceConn = null ; mService = null ; mPurchaseListener = null ; |
public class Event { /** * Prevents the invocation of further handlers ( like { @ link # stop ( ) }
* and ( in addition ) the invocation of any added completed events .
* @ param mayInterruptIfRunning ignored
* @ return ` false ` if the event has already been completed
* @ see java . util . concurrent . Future # cancel ( boolean ) */
@ Override public boolean cancel ( boolean mayInterruptIfRunning ) { } } | if ( ! completed && ! cancelled ) { stop ( ) ; cancelled = true ; return true ; } return false ; |
public class ParserAdapter { /** * Internal setup method .
* @ param parser The embedded parser .
* @ exception java . lang . NullPointerException If the parser parameter
* is null . */
private void setup ( Parser parser ) { } } | if ( parser == null ) { throw new NullPointerException ( "Parser argument must not be null" ) ; } this . parser = parser ; atts = new AttributesImpl ( ) ; nsSupport = new NamespaceSupport ( ) ; attAdapter = new AttributeListAdapter ( ) ; |
public class BaseScriptPlugin { /** * Create the command array for the data context .
* @ param localDataContext data
* @ return command array */
protected String [ ] createScriptArgs ( final Map < String , Map < String , String > > localDataContext ) { } } | final ScriptPluginProvider plugin = getProvider ( ) ; final File scriptfile = plugin . getScriptFile ( ) ; final String scriptargs = plugin . getScriptArgs ( ) ; final String [ ] scriptargsarray = plugin . getScriptArgsArray ( ) ; final String scriptinterpreter = plugin . getScriptInterpreter ( ) ; final boolean interpreterargsquoted = plugin . getInterpreterArgsQuoted ( ) ; return getScriptExecHelper ( ) . createScriptArgs ( localDataContext , scriptargs , scriptargsarray , scriptinterpreter , interpreterargsquoted , scriptfile . getAbsolutePath ( ) ) ; |
public class Strs { /** * Search target string to find the first index of any string in the given string array
* @ param target
* @ param indexWith
* @ return */
public static int indexAny ( String target , String ... indexWith ) { } } | return indexAny ( target , 0 , Arrays . asList ( indexWith ) ) ; |
public class GossipManager { /** * Starts the client . Specifically , start the various cycles for this protocol . Start the gossip
* thread and start the receiver thread . */
public void run ( ) { } } | for ( LocalGossipMember member : members . keySet ( ) ) { if ( member != me ) { member . startTimeoutTimer ( ) ; } } try { passiveGossipThread = passiveGossipThreadClass . getConstructor ( GossipManager . class ) . newInstance ( this ) ; gossipThreadExecutor . execute ( passiveGossipThread ) ; activeGossipThread = activeGossipThreadClass . getConstructor ( GossipManager . class ) . newInstance ( this ) ; gossipThreadExecutor . execute ( activeGossipThread ) ; } catch ( InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e1 ) { throw new RuntimeException ( e1 ) ; } GossipService . LOGGER . debug ( "The GossipService is started." ) ; while ( gossipServiceRunning . get ( ) ) { try { // TODO
TimeUnit . MILLISECONDS . sleep ( 1 ) ; } catch ( InterruptedException e ) { GossipService . LOGGER . warn ( "The GossipClient was interrupted." ) ; } } |
public class OWLOntologyID_CustomFieldSerializer { /** * Serializes the content of the object into the
* { @ link com . google . gwt . user . client . rpc . SerializationStreamWriter } .
* @ param streamWriter the { @ link com . google . gwt . user . client . rpc . SerializationStreamWriter } to write the
* object ' s content to
* @ param instance the object instance to serialize
* @ throws com . google . gwt . user . client . rpc . SerializationException
* if the serialization operation is not
* successful */
@ Override public void serializeInstance ( SerializationStreamWriter streamWriter , OWLOntologyID instance ) throws SerializationException { } } | serialize ( streamWriter , instance ) ; |
public class ClassWriter { /** * Given a symbol , return its name - and - type . */
NameAndType nameType ( Symbol sym ) { } } | return new NameAndType ( sym . name , sym . externalType ( types ) , types ) ; // the NameAndType is generated from a symbol reference , and the
// adjustment of adding an additional this $ n parameter needs to be made . |
public class WriterUtils { /** * Get the { @ link Path } corresponding the the relative file path for a given { @ link org . apache . gobblin . writer . DataWriter } .
* This method retrieves the value of { @ link ConfigurationKeys # WRITER _ FILE _ PATH } from the given { @ link State } . It also
* constructs the default value of the { @ link ConfigurationKeys # WRITER _ FILE _ PATH } if not is not specified in the given
* { @ link State } .
* @ param state is the { @ link State } corresponding to a specific { @ link org . apache . gobblin . writer . DataWriter } .
* @ param numBranches is the total number of branches for the given { @ link State } .
* @ param branchId is the id for the specific branch that the { { @ link org . apache . gobblin . writer . DataWriter } will write to .
* @ return a { @ link Path } specifying the relative directory where the { @ link org . apache . gobblin . writer . DataWriter } will write to . */
public static Path getWriterFilePath ( State state , int numBranches , int branchId ) { } } | if ( state . contains ( ForkOperatorUtils . getPropertyNameForBranch ( ConfigurationKeys . WRITER_FILE_PATH , numBranches , branchId ) ) ) { return new Path ( state . getProp ( ForkOperatorUtils . getPropertyNameForBranch ( ConfigurationKeys . WRITER_FILE_PATH , numBranches , branchId ) ) ) ; } switch ( getWriterFilePathType ( state ) ) { case NAMESPACE_TABLE : return getNamespaceTableWriterFilePath ( state ) ; case TABLENAME : return WriterUtils . getTableNameWriterFilePath ( state ) ; default : return WriterUtils . getDefaultWriterFilePath ( state , numBranches , branchId ) ; } |
public class SBaseButton { /** * Get the best guess for the command name .
* This is usually used to get the command to perform for a canned button .
* @ return The button command ( or the best guess for the command ) . */
public String getButtonCommand ( ) { } } | String strCommand = m_strCommand ; if ( strCommand == null ) strCommand = this . getButtonDesc ( ) ; if ( ( strCommand == null ) || ( strCommand . equals ( Constants . BLANK ) ) ) strCommand = m_strImageButton ; // Use image name until the image is loaded
return strCommand ; |
public class Cache { /** * 存放 key value 对到 redis , 并将 key 的生存时间设为 seconds ( 以秒为单位 ) 。
* 如果 key 已经存在 , SETEX 命令将覆写旧值 。 */
public String setex ( Object key , int seconds , Object value ) { } } | Jedis jedis = getJedis ( ) ; try { return jedis . setex ( keyToBytes ( key ) , seconds , valueToBytes ( value ) ) ; } finally { close ( jedis ) ; } |
public class inat { /** * Use this API to update inat resources . */
public static base_responses update ( nitro_service client , inat resources [ ] ) throws Exception { } } | base_responses result = null ; if ( resources != null && resources . length > 0 ) { inat updateresources [ ] = new inat [ resources . length ] ; for ( int i = 0 ; i < resources . length ; i ++ ) { updateresources [ i ] = new inat ( ) ; updateresources [ i ] . name = resources [ i ] . name ; updateresources [ i ] . privateip = resources [ i ] . privateip ; updateresources [ i ] . tcpproxy = resources [ i ] . tcpproxy ; updateresources [ i ] . ftp = resources [ i ] . ftp ; updateresources [ i ] . tftp = resources [ i ] . tftp ; updateresources [ i ] . usip = resources [ i ] . usip ; updateresources [ i ] . usnip = resources [ i ] . usnip ; updateresources [ i ] . proxyip = resources [ i ] . proxyip ; updateresources [ i ] . mode = resources [ i ] . mode ; } result = update_bulk_request ( client , updateresources ) ; } return result ; |
public class PushbuttonField { /** * Gets the button appearance .
* @ throws IOException on error
* @ throws DocumentException on error
* @ return the button appearance */
public PdfAppearance getAppearance ( ) throws IOException , DocumentException { } } | PdfAppearance app = getBorderAppearance ( ) ; Rectangle box = new Rectangle ( app . getBoundingBox ( ) ) ; if ( ( text == null || text . length ( ) == 0 ) && ( layout == LAYOUT_LABEL_ONLY || ( image == null && template == null && iconReference == null ) ) ) { return app ; } if ( layout == LAYOUT_ICON_ONLY && image == null && template == null && iconReference == null ) return app ; BaseFont ufont = getRealFont ( ) ; boolean borderExtra = borderStyle == PdfBorderDictionary . STYLE_BEVELED || borderStyle == PdfBorderDictionary . STYLE_INSET ; float bw2 = borderWidth ; if ( borderExtra ) { bw2 *= 2 ; } float offsetX = ( borderExtra ? 2 * borderWidth : borderWidth ) ; offsetX = Math . max ( offsetX , 1 ) ; float offX = Math . min ( bw2 , offsetX ) ; tp = null ; float textX = Float . NaN ; float textY = 0 ; float fsize = fontSize ; float wt = box . getWidth ( ) - 2 * offX - 2 ; float ht = box . getHeight ( ) - 2 * offX ; float adj = ( iconFitToBounds ? 0 : offX + 1 ) ; int nlayout = layout ; if ( image == null && template == null && iconReference == null ) nlayout = LAYOUT_LABEL_ONLY ; Rectangle iconBox = null ; while ( true ) { switch ( nlayout ) { case LAYOUT_LABEL_ONLY : case LAYOUT_LABEL_OVER_ICON : if ( text != null && text . length ( ) > 0 && wt > 0 && ht > 0 ) { fsize = calculateFontSize ( wt , ht ) ; textX = ( box . getWidth ( ) - ufont . getWidthPoint ( text , fsize ) ) / 2 ; textY = ( box . getHeight ( ) - ufont . getFontDescriptor ( BaseFont . ASCENT , fsize ) ) / 2 ; } case LAYOUT_ICON_ONLY : if ( nlayout == LAYOUT_LABEL_OVER_ICON || nlayout == LAYOUT_ICON_ONLY ) iconBox = new Rectangle ( box . getLeft ( ) + adj , box . getBottom ( ) + adj , box . getRight ( ) - adj , box . getTop ( ) - adj ) ; break ; case LAYOUT_ICON_TOP_LABEL_BOTTOM : if ( text == null || text . length ( ) == 0 || wt <= 0 || ht <= 0 ) { nlayout = LAYOUT_ICON_ONLY ; continue ; } float nht = box . getHeight ( ) * 0.35f - offX ; if ( nht > 0 ) fsize = calculateFontSize ( wt , nht ) ; else fsize = 4 ; textX = ( box . getWidth ( ) - ufont . getWidthPoint ( text , fsize ) ) / 2 ; textY = offX - ufont . getFontDescriptor ( BaseFont . DESCENT , fsize ) ; iconBox = new Rectangle ( box . getLeft ( ) + adj , textY + fsize , box . getRight ( ) - adj , box . getTop ( ) - adj ) ; break ; case LAYOUT_LABEL_TOP_ICON_BOTTOM : if ( text == null || text . length ( ) == 0 || wt <= 0 || ht <= 0 ) { nlayout = LAYOUT_ICON_ONLY ; continue ; } nht = box . getHeight ( ) * 0.35f - offX ; if ( nht > 0 ) fsize = calculateFontSize ( wt , nht ) ; else fsize = 4 ; textX = ( box . getWidth ( ) - ufont . getWidthPoint ( text , fsize ) ) / 2 ; textY = box . getHeight ( ) - offX - fsize ; if ( textY < offX ) textY = offX ; iconBox = new Rectangle ( box . getLeft ( ) + adj , box . getBottom ( ) + adj , box . getRight ( ) - adj , textY + ufont . getFontDescriptor ( BaseFont . DESCENT , fsize ) ) ; break ; case LAYOUT_LABEL_LEFT_ICON_RIGHT : if ( text == null || text . length ( ) == 0 || wt <= 0 || ht <= 0 ) { nlayout = LAYOUT_ICON_ONLY ; continue ; } float nw = box . getWidth ( ) * 0.35f - offX ; if ( nw > 0 ) fsize = calculateFontSize ( wt , nw ) ; else fsize = 4 ; if ( ufont . getWidthPoint ( text , fsize ) >= wt ) { nlayout = LAYOUT_LABEL_ONLY ; fsize = fontSize ; continue ; } textX = offX + 1 ; textY = ( box . getHeight ( ) - ufont . getFontDescriptor ( BaseFont . ASCENT , fsize ) ) / 2 ; iconBox = new Rectangle ( textX + ufont . getWidthPoint ( text , fsize ) , box . getBottom ( ) + adj , box . getRight ( ) - adj , box . getTop ( ) - adj ) ; break ; case LAYOUT_ICON_LEFT_LABEL_RIGHT : if ( text == null || text . length ( ) == 0 || wt <= 0 || ht <= 0 ) { nlayout = LAYOUT_ICON_ONLY ; continue ; } nw = box . getWidth ( ) * 0.35f - offX ; if ( nw > 0 ) fsize = calculateFontSize ( wt , nw ) ; else fsize = 4 ; if ( ufont . getWidthPoint ( text , fsize ) >= wt ) { nlayout = LAYOUT_LABEL_ONLY ; fsize = fontSize ; continue ; } textX = box . getWidth ( ) - ufont . getWidthPoint ( text , fsize ) - offX - 1 ; textY = ( box . getHeight ( ) - ufont . getFontDescriptor ( BaseFont . ASCENT , fsize ) ) / 2 ; iconBox = new Rectangle ( box . getLeft ( ) + adj , box . getBottom ( ) + adj , textX - 1 , box . getTop ( ) - adj ) ; break ; } break ; } if ( textY < box . getBottom ( ) + offX ) textY = box . getBottom ( ) + offX ; if ( iconBox != null && ( iconBox . getWidth ( ) <= 0 || iconBox . getHeight ( ) <= 0 ) ) iconBox = null ; boolean haveIcon = false ; float boundingBoxWidth = 0 ; float boundingBoxHeight = 0 ; PdfArray matrix = null ; if ( iconBox != null ) { if ( image != null ) { tp = new PdfTemplate ( writer ) ; tp . setBoundingBox ( new Rectangle ( image ) ) ; writer . addDirectTemplateSimple ( tp , PdfName . FRM ) ; tp . addImage ( image , image . getWidth ( ) , 0 , 0 , image . getHeight ( ) , 0 , 0 ) ; haveIcon = true ; boundingBoxWidth = tp . getBoundingBox ( ) . getWidth ( ) ; boundingBoxHeight = tp . getBoundingBox ( ) . getHeight ( ) ; } else if ( template != null ) { tp = new PdfTemplate ( writer ) ; tp . setBoundingBox ( new Rectangle ( template . getWidth ( ) , template . getHeight ( ) ) ) ; writer . addDirectTemplateSimple ( tp , PdfName . FRM ) ; tp . addTemplate ( template , template . getBoundingBox ( ) . getLeft ( ) , template . getBoundingBox ( ) . getBottom ( ) ) ; haveIcon = true ; boundingBoxWidth = tp . getBoundingBox ( ) . getWidth ( ) ; boundingBoxHeight = tp . getBoundingBox ( ) . getHeight ( ) ; } else if ( iconReference != null ) { PdfDictionary dic = ( PdfDictionary ) PdfReader . getPdfObject ( iconReference ) ; if ( dic != null ) { Rectangle r2 = PdfReader . getNormalizedRectangle ( dic . getAsArray ( PdfName . BBOX ) ) ; matrix = dic . getAsArray ( PdfName . MATRIX ) ; haveIcon = true ; boundingBoxWidth = r2 . getWidth ( ) ; boundingBoxHeight = r2 . getHeight ( ) ; } } } if ( haveIcon ) { float icx = iconBox . getWidth ( ) / boundingBoxWidth ; float icy = iconBox . getHeight ( ) / boundingBoxHeight ; if ( proportionalIcon ) { switch ( scaleIcon ) { case SCALE_ICON_IS_TOO_BIG : icx = Math . min ( icx , icy ) ; icx = Math . min ( icx , 1 ) ; break ; case SCALE_ICON_IS_TOO_SMALL : icx = Math . min ( icx , icy ) ; icx = Math . max ( icx , 1 ) ; break ; case SCALE_ICON_NEVER : icx = 1 ; break ; default : icx = Math . min ( icx , icy ) ; break ; } icy = icx ; } else { switch ( scaleIcon ) { case SCALE_ICON_IS_TOO_BIG : icx = Math . min ( icx , 1 ) ; icy = Math . min ( icy , 1 ) ; break ; case SCALE_ICON_IS_TOO_SMALL : icx = Math . max ( icx , 1 ) ; icy = Math . max ( icy , 1 ) ; break ; case SCALE_ICON_NEVER : icx = icy = 1 ; break ; default : break ; } } float xpos = iconBox . getLeft ( ) + ( iconBox . getWidth ( ) - ( boundingBoxWidth * icx ) ) * iconHorizontalAdjustment ; float ypos = iconBox . getBottom ( ) + ( iconBox . getHeight ( ) - ( boundingBoxHeight * icy ) ) * iconVerticalAdjustment ; app . saveState ( ) ; app . rectangle ( iconBox . getLeft ( ) , iconBox . getBottom ( ) , iconBox . getWidth ( ) , iconBox . getHeight ( ) ) ; app . clip ( ) ; app . newPath ( ) ; if ( tp != null ) app . addTemplate ( tp , icx , 0 , 0 , icy , xpos , ypos ) ; else { float cox = 0 ; float coy = 0 ; if ( matrix != null && matrix . size ( ) == 6 ) { PdfNumber nm = matrix . getAsNumber ( 4 ) ; if ( nm != null ) cox = nm . floatValue ( ) ; nm = matrix . getAsNumber ( 5 ) ; if ( nm != null ) coy = nm . floatValue ( ) ; } app . addTemplateReference ( iconReference , PdfName . FRM , icx , 0 , 0 , icy , xpos - cox * icx , ypos - coy * icy ) ; } app . restoreState ( ) ; } if ( ! Float . isNaN ( textX ) ) { app . saveState ( ) ; app . rectangle ( offX , offX , box . getWidth ( ) - 2 * offX , box . getHeight ( ) - 2 * offX ) ; app . clip ( ) ; app . newPath ( ) ; if ( textColor == null ) app . resetGrayFill ( ) ; else app . setColorFill ( textColor ) ; app . beginText ( ) ; app . setFontAndSize ( ufont , fsize ) ; app . setTextMatrix ( textX , textY ) ; app . showText ( text ) ; app . endText ( ) ; app . restoreState ( ) ; } return app ; |
public class CompressionUtil { /** * Decode lz to string string .
* @ param data the data
* @ param dictionary the dictionary
* @ return the string */
public static String decodeLZToString ( byte [ ] data , String dictionary ) { } } | try { return new String ( decodeLZ ( data ) , "UTF-8" ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } |
public class PlanNode { /** * Remove all children from this node . All nodes immediately become orphaned . The resulting list will be mutable .
* @ return a copy of all the of the children that were removed ( and which have no parent ) ; never null */
public List < PlanNode > removeAllChildren ( ) { } } | if ( this . children . isEmpty ( ) ) { return new ArrayList < PlanNode > ( 0 ) ; } List < PlanNode > copyOfChildren = new ArrayList < PlanNode > ( this . children ) ; for ( Iterator < PlanNode > childIter = this . children . iterator ( ) ; childIter . hasNext ( ) ; ) { PlanNode child = childIter . next ( ) ; childIter . remove ( ) ; child . parent = null ; } return copyOfChildren ; |
public class StringUtil { /** * Converts a comma - separated String to an array of doubles .
* @ param pString The comma - separated string
* @ param pDelimiters The delimiter string
* @ return a { @ code double } array
* @ throws NumberFormatException if any of the elements are not parseable
* as a double */
public static double [ ] toDoubleArray ( String pString , String pDelimiters ) { } } | if ( isEmpty ( pString ) ) { return new double [ 0 ] ; } // Some room for improvement here . . .
String [ ] temp = toStringArray ( pString , pDelimiters ) ; double [ ] array = new double [ temp . length ] ; for ( int i = 0 ; i < array . length ; i ++ ) { array [ i ] = Double . valueOf ( temp [ i ] ) ; // Double . parseDouble ( ) is 1.2 . . .
} return array ; |
public class RTED_InfoTree_Opt { /** * Initialization method .
* @ param t1
* @ param t2 */
public void init ( LblTree t1 , LblTree t2 ) { } } | LabelDictionary ld = new LabelDictionary ( ) ; it1 = new InfoTree ( t1 , ld ) ; it2 = new InfoTree ( t2 , ld ) ; size1 = it1 . getSize ( ) ; size2 = it2 . getSize ( ) ; IJ = new int [ Math . max ( size1 , size2 ) ] [ Math . max ( size1 , size2 ) ] ; delta = new double [ size1 ] [ size2 ] ; deltaBit = new byte [ size1 ] [ size2 ] ; costV = new long [ 3 ] [ size1 ] [ size2 ] ; costW = new long [ 3 ] [ size2 ] ; // Calculate delta between every leaf in G ( empty tree ) and all the nodes in F .
// Calculate it both sides : leafs of F and nodes of G & leafs of G and nodes of
int [ ] labels1 = it1 . getInfoArray ( POST2_LABEL ) ; int [ ] labels2 = it2 . getInfoArray ( POST2_LABEL ) ; int [ ] sizes1 = it1 . getInfoArray ( POST2_SIZE ) ; int [ ] sizes2 = it2 . getInfoArray ( POST2_SIZE ) ; for ( int x = 0 ; x < sizes1 . length ; x ++ ) { // for all nodes of initially left tree
for ( int y = 0 ; y < sizes2 . length ; y ++ ) { // for all nodes of initially right tree
// This is an attempt for distances of single - node subtree and anything alse
// The differences between pairs of labels are stored
if ( labels1 [ x ] == labels2 [ y ] ) { deltaBit [ x ] [ y ] = 0 ; } else { deltaBit [ x ] [ y ] = 1 ; // if this set , the labels differ , cost of relabeling is set
// to costMatch
} if ( sizes1 [ x ] == 1 && sizes2 [ y ] == 1 ) { // both nodes are leafs
delta [ x ] [ y ] = 0 ; } else { if ( sizes1 [ x ] == 1 ) { delta [ x ] [ y ] = sizes2 [ y ] - 1 ; } if ( sizes2 [ y ] == 1 ) { delta [ x ] [ y ] = sizes1 [ x ] - 1 ; } } } } |
public class AsianOption { /** * This method returns the value random variable of the product within the specified model , evaluated at a given evalutationTime .
* Note : For a lattice this is often the value conditional to evalutationTime , for a Monte - Carlo simulation this is the ( sum of ) value discounted to evaluation time .
* Cashflows prior evaluationTime are not considered .
* @ param evaluationTime The time on which this products value should be observed .
* @ param model The model used to price the product .
* @ return The random variable representing the value of the product discounted to evaluation time
* @ throws net . finmath . exception . CalculationException Thrown if the valuation fails , specific cause may be available via the < code > cause ( ) < / code > method . */
@ Override public RandomVariableInterface getValue ( double evaluationTime , AssetModelMonteCarloSimulationInterface model ) throws CalculationException { } } | // Calculate average
RandomVariableInterface average = model . getRandomVariableForConstant ( 0.0 ) ; for ( double time : timesForAveraging ) { RandomVariableInterface underlying = model . getAssetValue ( time , underlyingIndex ) ; average = average . add ( underlying ) ; } average = average . div ( timesForAveraging . getNumberOfTimes ( ) ) ; // The payoff : values = max ( underlying - strike , 0)
RandomVariableInterface values = average . sub ( strike ) . floor ( 0.0 ) ; // Discounting . . .
RandomVariableInterface numeraireAtMaturity = model . getNumeraire ( maturity ) ; RandomVariableInterface monteCarloWeights = model . getMonteCarloWeights ( maturity ) ; values = values . div ( numeraireAtMaturity ) . mult ( monteCarloWeights ) ; // . . . to evaluation time .
RandomVariableInterface numeraireAtEvalTime = model . getNumeraire ( evaluationTime ) ; RandomVariableInterface monteCarloProbabilitiesAtEvalTime = model . getMonteCarloWeights ( evaluationTime ) ; values = values . mult ( numeraireAtEvalTime ) . div ( monteCarloProbabilitiesAtEvalTime ) ; return values ; |
public class ThemeUtil { /** * Obtains the text , which corresponds to a specific resource id , from a context ' s theme . If the
* given resource id is invalid , a { @ link NotFoundException } will be thrown .
* @ param context
* The context , which should be used , as an instance of the class { @ link Context } . The
* context may not be null
* @ param resourceId
* The resource id of the attribute , which should be obtained , as an { @ link Integer }
* value . The resource id must corresponds to a valid theme attribute
* @ return The text , which has been obtained , as an instance of the type { @ link CharSequence } */
public static CharSequence getText ( @ NonNull final Context context , @ AttrRes final int resourceId ) { } } | return getText ( context , - 1 , resourceId ) ; |
public class IdlToDSMojo { /** * Various steps needing to be done for each IDD */
private void processService ( Service service ) throws Exception { } } | getLog ( ) . info ( " Service: " + service . getServiceName ( ) ) ; Document iddDoc = parseIddFile ( service . getServiceName ( ) ) ; // 1 . validate
if ( ! isOffline ( ) ) { getLog ( ) . debug ( "Validating XML.." ) ; new XmlValidator ( resolver ) . validate ( iddDoc ) ; } // 2 . generate outputs
generateJavaCode ( service , iddDoc ) ; |
public class Node { /** * Inserts a Sibling into the linked list just prior to this Node
* @ param node Node to be made the prevSibling */
public void insertSiblingBefore ( Node node ) throws ChildNodeException { } } | if ( node != null ) { node . setPrevSibling ( getPrevSibling ( ) ) ; node . setNextSibling ( this ) ; } |
public class Boxing { /** * Transforms any array into an array of { @ code short } .
* @ param src source array
* @ param srcPos start position
* @ param len length
* @ return short array */
public static short [ ] unboxShorts ( Object src , int srcPos , int len ) { } } | return unboxShorts ( array ( src ) , srcPos , len ) ; |
public class ListValidationEditor { /** * Sets the ListEditor ' s backing data .
* If a null is passed in , the ListEditor will have no backing list and edits cannot be made .
* @ param value a List of data objects of type T */
@ Override public void setValue ( final List < T > value ) { } } | if ( list == null && value == null ) { // fast exit
return ; } if ( list != null && list . isSameValue ( value ) ) { // setting the same value as the one being edited
list . refresh ( ) ; return ; } if ( list != null ) { // Having entire value reset , so dump the wrapper gracefully
list . detach ( ) ; } if ( value == null ) { list = null ; } else { list = new ListValidationEditorWrapper < > ( value , chain , editorSource , parentDriver ) ; list . attach ( ) ; } |
public class UriTemplate { /** * Creates a new { @ link UriTemplate } with the current { @ link TemplateVariable } s augmented with the given ones .
* @ param variables must not be { @ literal null } .
* @ return will never be { @ literal null } . */
public UriTemplate with ( TemplateVariables variables ) { } } | Assert . notNull ( variables , "TemplateVariables must not be null!" ) ; if ( variables . equals ( TemplateVariables . NONE ) ) { return this ; } UriComponents components = UriComponentsBuilder . fromUriString ( baseUri ) . build ( ) ; List < TemplateVariable > result = new ArrayList < > ( ) ; for ( TemplateVariable variable : variables ) { boolean isRequestParam = variable . isRequestParameterVariable ( ) ; boolean alreadyPresent = components . getQueryParams ( ) . containsKey ( variable . getName ( ) ) ; if ( isRequestParam && alreadyPresent ) { continue ; } if ( variable . isFragment ( ) && StringUtils . hasText ( components . getFragment ( ) ) ) { continue ; } result . add ( variable ) ; } return new UriTemplate ( baseUri , this . variables . concat ( result ) ) ; |
public class HierarchicalContextRunner { /** * Returns a { @ link TestClassValidator } that validates the { @ link TestClass } instance after the
* { @ link HierarchicalContextRunner } has been created for the corresponding { @ link Class } . To use multiple
* { @ link TestClassValidator } s , please use the { @ link BooleanValidator } AND and OR to group your validators .
* Note : Clients may override this method to add or remove validators .
* @ return a { @ link TestClassValidator } */
protected TestClassValidator getValidator ( ) { } } | return BooleanValidator . AND ( ConstructorValidator . VALID_CONSTRUCTOR , BooleanValidator . OR ( ChildrenCountValidator . CONTEXT_HIERARCHIES , ChildrenCountValidator . TEST_METHODS ) , FixtureValidator . BEFORE_CLASS_METHODS , FixtureValidator . AFTER_CLASS_METHODS , FixtureValidator . BEFORE_METHODS , FixtureValidator . AFTER_METHODS , FixtureValidator . TEST_METHODS , RuleValidator . CLASS_RULE_VALIDATOR , RuleValidator . CLASS_RULE_METHOD_VALIDATOR , RuleValidator . RULE_VALIDATOR , RuleValidator . RULE_METHOD_VALIDATOR ) ; |
public class CopyFieldHandler { /** * Constructor .
* @ param field The basefield owner of this listener ( usually null and set on setOwner ( ) ) .
* @ param iFieldSeq The field sequence in this record to move this listener ' s field to .
* @ param field The field to move this listener ' s field to .
* @ param fldCheckMark Only move if this field evaluates to true . */
public void init ( BaseField field , BaseField fldDest , Converter fldCheckMark , String fieldName ) { } } | BaseField fldSource = null ; boolean bClearIfThisNull = true ; boolean bOnlyIfDestNull = false ; boolean bDontMoveNull = false ; super . init ( field , fldDest , fldSource , bClearIfThisNull , bOnlyIfDestNull , bDontMoveNull ) ; this . setRespondsToMode ( DBConstants . INIT_MOVE , false ) ; // By default , only respond to screen and init moves
this . setRespondsToMode ( DBConstants . READ_MOVE , false ) ; // Usually , you only want to move a string on screen change
this . fieldName = fieldName ; m_convCheckMark = fldCheckMark ; |
public class HlsGroupSettings { /** * Choose one or more ad marker types to pass SCTE35 signals through to this group of Apple HLS outputs .
* @ param adMarkers
* Choose one or more ad marker types to pass SCTE35 signals through to this group of Apple HLS outputs .
* @ return Returns a reference to this object so that method calls can be chained together .
* @ see HlsAdMarkers */
public HlsGroupSettings withAdMarkers ( HlsAdMarkers ... adMarkers ) { } } | java . util . ArrayList < String > adMarkersCopy = new java . util . ArrayList < String > ( adMarkers . length ) ; for ( HlsAdMarkers value : adMarkers ) { adMarkersCopy . add ( value . toString ( ) ) ; } if ( getAdMarkers ( ) == null ) { setAdMarkers ( adMarkersCopy ) ; } else { getAdMarkers ( ) . addAll ( adMarkersCopy ) ; } return this ; |
public class S3ResourceClassificationMarshaller { /** * Marshall the given parameter object . */
public void marshall ( S3ResourceClassification s3ResourceClassification , ProtocolMarshaller protocolMarshaller ) { } } | if ( s3ResourceClassification == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( s3ResourceClassification . getBucketName ( ) , BUCKETNAME_BINDING ) ; protocolMarshaller . marshall ( s3ResourceClassification . getPrefix ( ) , PREFIX_BINDING ) ; protocolMarshaller . marshall ( s3ResourceClassification . getClassificationType ( ) , CLASSIFICATIONTYPE_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class Token { /** * Creates a token that represents an identifier . */
public static Token newIdentifier ( String text , int startLine , int startColumn ) { } } | return new Token ( Types . IDENTIFIER , text , startLine , startColumn ) ; |
public class CommerceTaxFixedRateAddressRelPersistenceImpl { /** * Returns a range of all the commerce tax fixed rate address rels where commerceTaxMethodId = & # 63 ; .
* Useful when paginating results . Returns a maximum of < code > end - start < / code > instances . < code > start < / code > and < code > end < / code > are not primary keys , they are indexes in the result set . Thus , < code > 0 < / code > refers to the first result in the set . Setting both < code > start < / code > and < code > end < / code > to { @ link QueryUtil # ALL _ POS } will return the full result set . If < code > orderByComparator < / code > is specified , then the query will include the given ORDER BY logic . If < code > orderByComparator < / code > is absent and pagination is required ( < code > start < / code > and < code > end < / code > are not { @ link QueryUtil # ALL _ POS } ) , then the query will include the default ORDER BY logic from { @ link CommerceTaxFixedRateAddressRelModelImpl } . If both < code > orderByComparator < / code > and pagination are absent , for performance reasons , the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order .
* @ param commerceTaxMethodId the commerce tax method ID
* @ param start the lower bound of the range of commerce tax fixed rate address rels
* @ param end the upper bound of the range of commerce tax fixed rate address rels ( not inclusive )
* @ return the range of matching commerce tax fixed rate address rels */
@ Override public List < CommerceTaxFixedRateAddressRel > findByCommerceTaxMethodId ( long commerceTaxMethodId , int start , int end ) { } } | return findByCommerceTaxMethodId ( commerceTaxMethodId , start , end , null ) ; |
public class Session { /** * Forces some user to unpublish a Stream . OpenVidu Browser will trigger the
* proper events on the client - side ( < code > streamDestroyed < / code > ) with reason
* set to " forceUnpublishByServer " . < br >
* You can get < code > streamId < / code > parameter with
* { @ link io . openvidu . java . client . Session # getActiveConnections ( ) } and then for
* each Connection you can call
* { @ link io . openvidu . java . client . Connection # getPublishers ( ) } . Finally
* { @ link io . openvidu . java . client . Publisher # getStreamId ( ) } ) will give you the
* < code > streamId < / code > . Remember to call
* { @ link io . openvidu . java . client . Session # fetch ( ) } before to fetch the current
* actual properties of the Session from OpenVidu Server
* @ throws OpenViduJavaClientException
* @ throws OpenViduHttpException */
public void forceUnpublish ( String streamId ) throws OpenViduJavaClientException , OpenViduHttpException { } } | HttpDelete request = new HttpDelete ( OpenVidu . urlOpenViduServer + OpenVidu . API_SESSIONS + "/" + this . sessionId + "/stream/" + streamId ) ; request . setHeader ( HttpHeaders . CONTENT_TYPE , "application/x-www-form-urlencoded" ) ; HttpResponse response ; try { response = OpenVidu . httpClient . execute ( request ) ; } catch ( IOException e ) { throw new OpenViduJavaClientException ( e . getMessage ( ) , e . getCause ( ) ) ; } try { int statusCode = response . getStatusLine ( ) . getStatusCode ( ) ; if ( ( statusCode == org . apache . http . HttpStatus . SC_NO_CONTENT ) ) { for ( Connection connection : this . activeConnections . values ( ) ) { // Try to remove the Publisher from the Connection publishers collection
if ( connection . publishers . remove ( streamId ) != null ) { continue ; } // Try to remove the Publisher from the Connection subscribers collection
connection . subscribers . remove ( streamId ) ; } log . info ( "Stream {} unpublished" , streamId ) ; } else { throw new OpenViduHttpException ( statusCode ) ; } } finally { EntityUtils . consumeQuietly ( response . getEntity ( ) ) ; } |
public class MemoryCache { /** * Empty the reference queue and remove all corresponding entries
* from the cache .
* This method should be called at the beginning of each public
* method . */
private void emptyQueue ( ) { } } | if ( queue == null ) { return ; } int startSize = cacheMap . size ( ) ; while ( true ) { @ SuppressWarnings ( "unchecked" ) CacheEntry < K , V > entry = ( CacheEntry < K , V > ) queue . poll ( ) ; if ( entry == null ) { break ; } K key = entry . getKey ( ) ; if ( key == null ) { // key is null , entry has already been removed
continue ; } CacheEntry < K , V > currentEntry = cacheMap . remove ( key ) ; // check if the entry in the map corresponds to the expired
// entry . If not , readd the entry
if ( ( currentEntry != null ) && ( entry != currentEntry ) ) { cacheMap . put ( key , currentEntry ) ; } } if ( DEBUG ) { int endSize = cacheMap . size ( ) ; if ( startSize != endSize ) { System . out . println ( "*** Expunged " + ( startSize - endSize ) + " entries, " + endSize + " entries left" ) ; } } |
public class VortexWorkerManager { /** * Sends an { @ link VortexAggregateFunction } and its { @ link VortexFunction } to a
* { @ link org . apache . reef . vortex . evaluator . VortexWorker } . */
< TInput , TOutput > void sendAggregateFunction ( final int aggregateFunctionId , final VortexAggregateFunction < TOutput > aggregateFunction , final VortexFunction < TInput , TOutput > function , final VortexAggregatePolicy policy ) { } } | final TaskletAggregationRequest < TInput , TOutput > taskletAggregationRequest = new TaskletAggregationRequest < > ( aggregateFunctionId , aggregateFunction , function , policy ) ; // The send is synchronous such that we make sure that the aggregate function is sent to the
// target worker before attempting to launch an aggregateable tasklet on it .
vortexRequestor . send ( reefTask , taskletAggregationRequest ) ; |
public class ExitStandbyResult { /** * The activities related to moving instances out of < code > Standby < / code > mode .
* @ param activities
* The activities related to moving instances out of < code > Standby < / code > mode . */
public void setActivities ( java . util . Collection < Activity > activities ) { } } | if ( activities == null ) { this . activities = null ; return ; } this . activities = new com . amazonaws . internal . SdkInternalList < Activity > ( activities ) ; |
public class BogusSslContextFactory { /** * Get SSLContext singleton .
* @ return SSLContext
* @ throws java . security . GeneralSecurityException */
public static SSLContext getInstance ( boolean server ) throws GeneralSecurityException { } } | SSLContext retInstance = null ; if ( server ) { if ( serverInstance == null ) { synchronized ( BogusSslContextFactory . class ) { if ( serverInstance == null ) { try { serverInstance = createBougusServerSslContext ( ) ; } catch ( Exception ioe ) { throw new GeneralSecurityException ( "Can't create Server SSLContext:" + ioe ) ; } } } } retInstance = serverInstance ; } else { if ( clientInstance == null ) { synchronized ( BogusSslContextFactory . class ) { if ( clientInstance == null ) { clientInstance = createBougusClientSslContext ( ) ; } } } retInstance = clientInstance ; } return retInstance ; |
public class QuickConstructorGenerator { /** * Returns a factory instance for one type of object . Each method in the
* interface defines a constructor via its parameters . Any checked
* exceptions declared thrown by the constructor must also be declared by
* the method . The method return types can be the same type as the
* constructed object or a supertype .
* < p > Here is a contrived example for constructing strings . In practice ,
* such a string factory is useless , since the " new " operator can be
* invoked directly .
* < pre >
* public interface StringFactory {
* String newEmptyString ( ) ;
* String newStringFromChars ( char [ ] chars ) ;
* String newStringFromBytes ( byte [ ] bytes , String charsetName )
* throws UnsupportedEncodingException ;
* < / pre >
* Here ' s an example of it being used :
* < pre >
* StringFactory sf = QuickConstructorGenerator . getInstance ( String . class , StringFactory . class ) ;
* String str = sf . newStringFromChars ( new char [ ] { ' h ' , ' e ' , ' l ' , ' l ' , ' o ' } ) ;
* < / pre >
* @ param objectType type of object to construct
* @ param factory interface defining which objects can be constructed
* @ throws IllegalArgumentException if factory type is not an interface or
* if it is malformed */
@ SuppressWarnings ( "unchecked" ) public static synchronized < F > F getInstance ( final Class < ? > objectType , final Class < F > factory ) { } } | Cache < Class < ? > , Object > innerCache = cCache . get ( factory ) ; if ( innerCache == null ) { innerCache = new SoftValueCache ( 5 ) ; cCache . put ( factory , innerCache ) ; } F instance = ( F ) innerCache . get ( objectType ) ; if ( instance != null ) { return instance ; } if ( objectType == null ) { throw new IllegalArgumentException ( "No object type" ) ; } if ( factory == null ) { throw new IllegalArgumentException ( "No factory type" ) ; } if ( ! factory . isInterface ( ) ) { throw new IllegalArgumentException ( "Factory must be an interface" ) ; } final Cache < Class < ? > , Object > fInnerCache = innerCache ; return AccessController . doPrivileged ( new PrivilegedAction < F > ( ) { public F run ( ) { return getInstance ( fInnerCache , objectType , factory ) ; } } ) ; |
public class ClassPath { /** * Load all classes in the fileJar
* @ param fileJar
* @ throws IOException */
public void loadJar ( File fileJar ) throws IOException { } } | JarFile jar = null ; try { jar = new JarFile ( fileJar ) ; Enumeration < JarEntry > enumerations = jar . entries ( ) ; JarEntry entry = null ; byte [ ] classByte = null ; ByteArrayOutputStream byteStream = null ; String fileName = null ; String className = null ; Class < ? > jarClass = null ; while ( enumerations . hasMoreElements ( ) ) { entry = ( JarEntry ) enumerations . nextElement ( ) ; if ( entry . isDirectory ( ) ) continue ; // skip directories
fileName = entry . getName ( ) ; if ( ! fileName . endsWith ( ".class" ) ) continue ; // skip non classes
InputStream is = jar . getInputStream ( entry ) ; byteStream = new ByteArrayOutputStream ( ) ; IO . write ( byteStream , is ) ; classByte = byteStream . toByteArray ( ) ; className = formatClassName ( fileName ) ; Debugger . println ( this , "className=" + className ) ; jarClass = defineClass ( className , classByte , 0 , classByte . length , null ) ; classes . put ( className , jarClass ) ; classByte = null ; byteStream = null ; } // end while
} finally { if ( jar != null ) { try { jar . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } } |
public class DataTable { /** * Creates a new instance with the given column setup . At least one column
* must be specified in the table . Rows are allowed to be empty .
* Columns should be unique , but the table doesn ' t enforce this .
* @ param columns columns for the table
* @ return new DataTable
* @ throws NoColumnsException if the list is empty */
public static DataTable createBasicInstance ( List < String > columns ) throws NoColumnsException { } } | List < DataColumn > list = new ArrayList < DataColumn > ( ) ; for ( String column : columns ) { list . add ( new DataColumn ( column ) ) ; } return new DataTable ( list ) ; |
public class GenericResponses { /** * Create a new { @ link GenericResponseBuilder } for a not acceptable response .
* @ param variants list of variants that were available
* @ return a new builder */
public static < T > GenericResponseBuilder < T > notAcceptable ( List < Variant > variants ) { } } | return GenericResponses . < T > status ( Response . Status . NOT_ACCEPTABLE ) . variants ( variants ) ; |
public class WaveformRender { /** * Render a waveform of a wave file
* @ param wave Wave object
* @ param timeStep time interval in second , as known as 1 / fps
* @ see RGB graphic rendered */
public BufferedImage renderWaveform ( Wave wave , int width ) { } } | // for signed signals , the middle is 0 ( - 1 ~ 1)
double middleLine = 0 ; // usually 8bit is unsigned
if ( wave . getWaveHeader ( ) . getBitsPerSample ( ) == 8 ) { // for unsigned signals , the middle is 0.5 ( 0 ~ 1)
middleLine = 0.5 ; } double [ ] nAmplitudes = wave . getNormalizedAmplitudes ( ) ; // int width = ( int ) ( nAmplitudes . length / wave . getWaveHeader ( ) . getSampleRate ( ) / timeStep ) ;
int height = width / 3 ; int middle = height / 2 ; int magnifier = 10000 ; int numSamples = nAmplitudes . length ; int numSamplePerTimeFrame = numSamples / width ; int [ ] scaledPosAmplitudes = new int [ width ] ; int [ ] scaledNegAmplitudes = new int [ width ] ; // width scaling
for ( int i = 0 ; i < width ; i ++ ) { double sumPosAmplitude = 0 ; double sumNegAmplitude = 0 ; int startSample = i * numSamplePerTimeFrame ; for ( int j = 0 ; j < numSamplePerTimeFrame ; j ++ ) { double a = nAmplitudes [ startSample + j ] ; if ( a > middleLine ) { sumPosAmplitude += ( a - middleLine ) ; } else { sumNegAmplitude += ( a - middleLine ) ; } } int scaledPosAmplitude = ( int ) ( sumPosAmplitude / numSamplePerTimeFrame * magnifier + middle ) ; int scaledNegAmplitude = ( int ) ( sumNegAmplitude / numSamplePerTimeFrame * magnifier + middle ) ; scaledPosAmplitudes [ i ] = scaledPosAmplitude ; scaledNegAmplitudes [ i ] = scaledNegAmplitude ; } // render wave form image
BufferedImage bufferedImage = new BufferedImage ( width , height , BufferedImage . TYPE_INT_RGB ) ; // set default white background
Graphics2D graphics = bufferedImage . createGraphics ( ) ; graphics . setPaint ( new Color ( 255 , 255 , 255 ) ) ; graphics . fillRect ( 0 , 0 , bufferedImage . getWidth ( ) , bufferedImage . getHeight ( ) ) ; for ( int i = 0 ; i < width ; i ++ ) { for ( int j = scaledNegAmplitudes [ i ] ; j < scaledPosAmplitudes [ i ] ; j ++ ) { int y = height - j ; // j from - ve to + ve , i . e . draw from top to bottom
if ( y < 0 ) { y = 0 ; } else if ( y >= height ) { y = height - 1 ; } bufferedImage . setRGB ( i , y , 0 ) ; } } return bufferedImage ; |
public class ApiUtil { public static String [ ] toStringArray ( final String objname , final DbAttribute [ ] attributes , final int mode ) { } } | final int nb_attr = attributes . length ; // Copy object name and nb attrib to String array
final ArrayList < String > list = new ArrayList < String > ( ) ; list . add ( objname ) ; list . add ( Integer . toString ( nb_attr ) ) ; for ( DbAttribute attribute : attributes ) { // Copy Attrib name and nb prop to String array
list . add ( attribute . name ) ; list . add ( "" + attribute . size ( ) ) ; for ( int j = 0 ; j < attribute . size ( ) ; j ++ ) { // Copy data to String array
list . add ( attribute . get_property_name ( j ) ) ; final String [ ] values = attribute . get_value ( j ) ; if ( mode != 1 ) { list . add ( "" + values . length ) ; } list . addAll ( Arrays . asList ( values ) ) ; } } // alloacte a String array
final String [ ] array = new String [ list . size ( ) ] ; for ( int i = 0 ; i < list . size ( ) ; i ++ ) { array [ i ] = list . get ( i ) ; } return array ; |
public class UITextFormatter { /** * Process the provided String as Markdown and return the created IHCNode .
* @ param sMD
* The Markdown source to be invoked . May be < code > null < / code > .
* @ return Either the processed markdown code or in case of an internal error
* a { @ link HCTextNode } which contains the source text . */
@ Nonnull public static IHCNode markdown ( @ Nullable final String sMD ) { } } | try { final HCNodeList aNL = MARKDOWN_PROC . process ( sMD ) . getNodeList ( ) ; // Replace a single < p > element with its contents
if ( aNL . getChildCount ( ) == 1 && aNL . getChildAtIndex ( 0 ) instanceof HCP ) return ( ( HCP ) aNL . getChildAtIndex ( 0 ) ) . getAllChildrenAsNodeList ( ) ; return aNL ; } catch ( final Exception ex ) { LOGGER . warn ( "Failed to markdown '" + sMD + "': " + ex . getMessage ( ) ) ; return new HCTextNode ( sMD ) ; } |
public class CompositeELResolver { /** * Attemps to resolve and invoke the given < code > method < / code > on the given
* < code > base < / code > object by querying all component resolvers .
* < p > If this resolver handles the given ( base , method ) pair ,
* the < code > propertyResolved < / code > property of the
* < code > ELContext < / code > object must be set to < code > true < / code >
* by the resolver , before returning . If this property is not
* < code > true < / code > after this method is called , the caller should ignore
* the return value . < / p >
* < p > First , < code > propertyResolved < / code > is set to < code > false < / code > on
* the provided < code > ELContext < / code > . < / p >
* < p > Next , for each component resolver in this composite :
* < ol >
* < li > The < code > invoke ( ) < / code > method is called , passing in
* the provided < code > context < / code > , < code > base < / code > ,
* < code > method < / code > , < code > paramTypes < / code > , and
* < code > params < / code > . < / li >
* < li > If the < code > ELContext < / code > ' s < code > propertyResolved < / code >
* flag is < code > false < / code > then iteration continues . < / li >
* < li > Otherwise , iteration stops and no more component resolvers are
* considered . The value returned by < code > getValue ( ) < / code > is
* returned by this method . < / li >
* < / ol > < / p >
* < p > If none of the component resolvers were able to perform this
* operation , the value < code > null < / code > is returned and the
* < code > propertyResolved < / code > flag remains set to
* < code > false < / code > < / p > .
* < p > Any exception thrown by component resolvers during the iteration
* is propagated to the caller of this method . < / p >
* @ param context The context of this evaluation .
* @ param base The bean on which to invoke the method
* @ param method The simple name of the method to invoke .
* Will be coerced to a < code > String < / code > .
* @ param paramTypes An array of Class objects identifying the
* method ' s formal parameter types , in declared order .
* Use an empty array if the method has no parameters .
* Can be < code > null < / code > , in which case the method ' s formal
* parameter types are assumed to be unknown .
* @ param params The parameters to pass to the method , or
* < code > null < / code > if no parameters .
* @ return The result of the method invocation ( < code > null < / code > if
* the method has a < code > void < / code > return type ) .
* @ since EL 2.2 */
public Object invoke ( ELContext context , Object base , Object method , Class < ? > [ ] paramTypes , Object [ ] params ) { } } | context . setPropertyResolved ( false ) ; Object value ; for ( int i = 0 ; i < size ; i ++ ) { value = elResolvers [ i ] . invoke ( context , base , method , paramTypes , params ) ; if ( context . isPropertyResolved ( ) ) { return value ; } } return null ; |
public class HandTemplateDevice { /** * This method is called using JNI */
public void processData ( ) { } } | // get number of hands
float handNum = readbackBuffer . get ( 0 ) ; int count = 1 ; boolean rightHandProcessed = false ; boolean leftHandProcessed = false ; for ( int handCount = 0 ; handCount < handNum ; handCount ++ ) { IOHand ioHand ; HandIODevice device ; if ( handCount == 0 ) { ioHand = rightHand ; device = rightDevice ; rightHandProcessed = true ; GVRSceneObject right = rightHand . getSceneObject ( ) ; if ( ! right . isEnabled ( ) ) { rightHand . getSceneObject ( ) . setEnable ( true ) ; device . setVisible ( true ) ; } } else { ioHand = leftHand ; device = leftDevice ; leftHandProcessed = true ; GVRSceneObject left = leftHand . getSceneObject ( ) ; if ( ! left . isEnabled ( ) ) { leftHand . getSceneObject ( ) . setEnable ( true ) ; device . setVisible ( true ) ; } } // Process Thumbs
IOFinger ioFinger = ioHand . getIOFinger ( IOFinger . THUMB ) ; for ( int boneNum = 0 ; boneNum < 4 ; boneNum ++ ) { IOJoint ioJoint = ioFinger . getIOJoint ( boneNum + 1 ) ; if ( ioJoint != null ) { ioJoint . setPosition ( readbackBuffer . get ( count ) , readbackBuffer . get ( count + 1 ) , readbackBuffer . get ( count + 2 ) ) ; } count = count + 3 ; } setBones ( ioFinger ) ; if ( handCount == 0 ) { // right hand
for ( int fingerNum = 1 ; fingerNum < 5 ; fingerNum ++ ) { ioFinger = ioHand . getIOFinger ( fingerNum ) ; for ( int boneNum = 0 ; boneNum < 4 ; boneNum ++ ) { IOJoint ioJoint = ioFinger . getIOJoint ( boneNum + 1 ) ; if ( ioJoint != null ) { ioJoint . setPosition ( readbackBuffer . get ( count ) , readbackBuffer . get ( count + 1 ) , readbackBuffer . get ( count + 2 ) ) ; } count = count + 3 ; } setBones ( ioFinger ) ; } } else { // left hand
for ( int fingerNum = 4 ; fingerNum > 0 ; fingerNum -- ) { ioFinger = ioHand . getIOFinger ( fingerNum ) ; for ( int boneNum = 0 ; boneNum < 4 ; boneNum ++ ) { IOJoint ioJoint = ioFinger . getIOJoint ( boneNum + 1 ) ; if ( ioJoint != null ) { ioJoint . setPosition ( readbackBuffer . get ( count ) , readbackBuffer . get ( count + 1 ) , readbackBuffer . get ( count + 2 ) ) ; } count = count + 3 ; } setBones ( ioFinger ) ; } } // get palm position
ioHand . getPalmSceneObject ( ) . getTransform ( ) . setPosition ( readbackBuffer . get ( count ) , readbackBuffer . get ( count + 1 ) , readbackBuffer . get ( count + 2 ) ) ; count = count + 3 ; cursorRotation . identity ( ) ; device . process ( ioHand . getIOFinger ( IOFinger . INDEX ) . getIOJoint ( IOJoint . TIP ) . getPosition ( ) , cursorRotation ) ; } if ( ! rightHandProcessed ) { GVRSceneObject right = rightHand . getSceneObject ( ) ; if ( right . isEnabled ( ) ) { rightHand . getSceneObject ( ) . setEnable ( false ) ; } rightDevice . setVisible ( false ) ; } if ( ! leftHandProcessed ) { GVRSceneObject left = leftHand . getSceneObject ( ) ; if ( left . isEnabled ( ) ) { leftHand . getSceneObject ( ) . setEnable ( false ) ; } leftDevice . setVisible ( false ) ; } |
public class RGraph { /** * Builds the initial extension set . This is the
* set of node that may be used as seed for the
* RGraph parsing . This set depends on the constrains
* defined by the user .
* @ param c1 constraint in the graph G1
* @ param c2 constraint in the graph G2
* @ return the new extension set */
private BitSet buildB ( BitSet c1 , BitSet c2 ) { } } | this . c1 = c1 ; this . c2 = c2 ; BitSet bs = new BitSet ( ) ; // only nodes that fulfill the initial constrains
// are allowed in the initial extension set : B
for ( Iterator < RNode > i = graph . iterator ( ) ; i . hasNext ( ) ; ) { RNode rn = i . next ( ) ; if ( ( c1 . get ( rn . rMap . id1 ) || c1 . isEmpty ( ) ) && ( c2 . get ( rn . rMap . id2 ) || c2 . isEmpty ( ) ) ) { bs . set ( graph . indexOf ( rn ) ) ; } } return bs ; |
public class JWTUtils { /** * Helper method to create a JWT token for the JWT flow
* @ param publicKeyFilename the filename of the RSA public key
* @ param privateKeyFilename the filename of the RSA private key
* @ param oAuthBasePath DocuSign OAuth base path ( account - d . docusign . com for the developer sandbox
* and account . docusign . com for the production platform )
* @ param clientId DocuSign OAuth Client Id ( AKA Integrator Key )
* @ param userId DocuSign user Id to be impersonated ( This is a UUID )
* @ param expiresIn number of seconds remaining before the JWT assertion is considered as invalid
* @ return a fresh JWT token
* @ throws JWTCreationException if not able to create a JWT token from the input parameters
* @ throws IOException if there is an issue with either the public or private file */
public static String generateJWTAssertion ( String publicKeyFilename , String privateKeyFilename , String oAuthBasePath , String clientId , String userId , long expiresIn ) throws JWTCreationException , IOException { } } | String token = null ; if ( expiresIn <= 0L ) { throw new IllegalArgumentException ( "expiresIn should be a non-negative value" ) ; } if ( publicKeyFilename == null || "" . equals ( publicKeyFilename ) || privateKeyFilename == null || "" . equals ( privateKeyFilename ) || oAuthBasePath == null || "" . equals ( oAuthBasePath ) || clientId == null || "" . equals ( clientId ) || userId == null || "" . equals ( userId ) ) { throw new IllegalArgumentException ( "One of the arguments is null or empty" ) ; } try { RSAPublicKey publicKey = readPublicKeyFromFile ( publicKeyFilename , "RSA" ) ; RSAPrivateKey privateKey = readPrivateKeyFromFile ( privateKeyFilename , "RSA" ) ; Algorithm algorithm = Algorithm . RSA256 ( publicKey , privateKey ) ; long now = System . currentTimeMillis ( ) ; token = JWT . create ( ) . withIssuer ( clientId ) . withSubject ( userId ) . withAudience ( oAuthBasePath ) . withNotBefore ( new Date ( now ) ) . withExpiresAt ( new Date ( now + expiresIn * 1000 ) ) . withClaim ( "scope" , "signature" ) . sign ( algorithm ) ; } catch ( JWTCreationException e ) { throw e ; } catch ( IOException e ) { throw e ; } return token ; |
public class ImageMath { /** * A variant of the gamma function .
* @ param a the number to apply gain to
* @ param b the gain parameter . 0.5 means no change , smaller values reduce gain , larger values increase gain .
* @ return the output value */
public static float gain ( float a , float b ) { } } | /* float p = ( float ) Math . log ( 1.0 - b ) / ( float ) Math . log ( 0.5 ) ;
if ( a < . 001)
return 0.0f ;
else if ( a > . 999)
return 1.0f ;
if ( a < 0.5)
return ( float ) Math . pow ( 2 * a , p ) / 2;
else
return 1.0f - ( float ) Math . pow ( 2 * ( 1 . - a ) , p ) / 2; */
float c = ( 1.0f / b - 2.0f ) * ( 1.0f - 2.0f * a ) ; if ( a < 0.5 ) return a / ( c + 1.0f ) ; else return ( c - a ) / ( c - 1.0f ) ; |
public class EventServiceImpl { /** * { @ inheritDoc }
* If the execution is rejected , the rejection count is increased and a failure is logged .
* The event callback is not re - executed .
* @ param callback the callback to execute on a random event thread */
@ Override public void executeEventCallback ( Runnable callback ) { } } | if ( ! nodeEngine . isRunning ( ) ) { return ; } try { eventExecutor . execute ( callback ) ; } catch ( RejectedExecutionException e ) { rejectedCount . inc ( ) ; if ( eventExecutor . isLive ( ) ) { logFailure ( "EventQueue overloaded! Failed to execute event callback: %s" , callback ) ; } } |
public class ServiceImplBeanType { /** * { @ inheritDoc } */
@ Override public void describe ( Diagnostics diag ) { } } | diag . describeIfSet ( "ejb-link" , ejb_link ) ; diag . describeIfSet ( "servlet-link" , servlet_link ) ; |
public class LongPipeline { /** * Stateless intermediate ops from LongStream */
@ Override public final DoubleStream asDoubleStream ( ) { } } | return new DoublePipeline . StatelessOp < Long > ( this , StreamShape . LONG_VALUE , StreamOpFlag . NOT_SORTED | StreamOpFlag . NOT_DISTINCT ) { @ Override public Sink < Long > opWrapSink ( int flags , Sink < Double > sink ) { return new Sink . ChainedLong < Double > ( sink ) { @ Override public void accept ( long t ) { downstream . accept ( ( double ) t ) ; } } ; } } ; |
public class UsingInstrumentation { /** * Creates an instrumentation - based class injector .
* @ param folder The folder to be used for storing jar files .
* @ param target A representation of the target path to which classes are to be appended .
* @ param instrumentation The instrumentation to use for appending to the class path or the boot path .
* @ return An appropriate class injector that applies instrumentation . */
public static ClassInjector of ( File folder , Target target , Instrumentation instrumentation ) { } } | return new UsingInstrumentation ( folder , target , instrumentation , new RandomString ( ) ) ; |
public class SivMode { /** * Convenience method , if you are using the javax . crypto API . This is just a wrapper for { @ link # encrypt ( byte [ ] , byte [ ] , byte [ ] , byte [ ] . . . ) } .
* @ param ctrKey SIV mode requires two separate keys . You can use one long key , which is splitted in half . See https : / / tools . ietf . org / html / rfc5297 # section - 2.2
* @ param macKey SIV mode requires two separate keys . You can use one long key , which is splitted in half . See https : / / tools . ietf . org / html / rfc5297 # section - 2.2
* @ param plaintext Your plaintext , which shall be encrypted .
* @ param associatedData Optional associated data , which gets authenticated but not encrypted .
* @ return IV + Ciphertext as a concatenated byte array .
* @ throws IllegalArgumentException if keys are invalid or { @ link SecretKey # getEncoded ( ) } is not supported . */
public byte [ ] encrypt ( SecretKey ctrKey , SecretKey macKey , byte [ ] plaintext , byte [ ] ... associatedData ) { } } | final byte [ ] ctrKeyBytes = ctrKey . getEncoded ( ) ; final byte [ ] macKeyBytes = macKey . getEncoded ( ) ; if ( ctrKeyBytes == null || macKeyBytes == null ) { throw new IllegalArgumentException ( "Can't get bytes of given key." ) ; } try { return encrypt ( ctrKeyBytes , macKeyBytes , plaintext , associatedData ) ; } finally { Arrays . fill ( ctrKeyBytes , ( byte ) 0 ) ; Arrays . fill ( macKeyBytes , ( byte ) 0 ) ; } |
public class RequestServer { /** * Top - level dispatch handling */
public void doGeneric ( String method , HttpServletRequest request , HttpServletResponse response ) { } } | try { ServletUtils . startTransaction ( request . getHeader ( "User-Agent" ) ) ; // Note that getServletPath does an un - escape so that the % 24 of job id ' s are turned into $ characters .
String uri = request . getServletPath ( ) ; Properties headers = new Properties ( ) ; Enumeration < String > en = request . getHeaderNames ( ) ; while ( en . hasMoreElements ( ) ) { String key = en . nextElement ( ) ; String value = request . getHeader ( key ) ; headers . put ( key , value ) ; } final String contentType = request . getContentType ( ) ; Properties parms = new Properties ( ) ; String postBody = null ; if ( System . getProperty ( H2O . OptArgs . SYSTEM_PROP_PREFIX + "debug.cors" ) != null ) { response . setHeader ( "Access-Control-Allow-Origin" , "*" ) ; response . setHeader ( "Access-Control-Allow-Headers" , "Content-Type" ) ; } if ( contentType != null && contentType . startsWith ( MIME_JSON ) ) { StringBuffer jb = new StringBuffer ( ) ; String line = null ; try { BufferedReader reader = request . getReader ( ) ; while ( ( line = reader . readLine ( ) ) != null ) jb . append ( line ) ; } catch ( Exception e ) { throw new H2OIllegalArgumentException ( "Exception reading POST body JSON for URL: " + uri ) ; } postBody = jb . toString ( ) ; } else { // application / x - www - form - urlencoded
Map < String , String [ ] > parameterMap ; parameterMap = request . getParameterMap ( ) ; for ( Map . Entry < String , String [ ] > entry : parameterMap . entrySet ( ) ) { String key = entry . getKey ( ) ; String [ ] values = entry . getValue ( ) ; if ( values . length == 1 ) { parms . put ( key , values [ 0 ] ) ; } else if ( values . length > 1 ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( "[" ) ; boolean first = true ; for ( String value : values ) { if ( ! first ) sb . append ( "," ) ; sb . append ( "\"" ) . append ( value ) . append ( "\"" ) ; first = false ; } sb . append ( "]" ) ; parms . put ( key , sb . toString ( ) ) ; } } } // Make serve ( ) call .
NanoResponse resp = serve ( uri , method , headers , parms , postBody ) ; // Un - marshal Nano response back to Jetty .
String choppedNanoStatus = resp . status . substring ( 0 , 3 ) ; assert ( choppedNanoStatus . length ( ) == 3 ) ; int sc = Integer . parseInt ( choppedNanoStatus ) ; ServletUtils . setResponseStatus ( response , sc ) ; response . setContentType ( resp . mimeType ) ; Properties header = resp . header ; Enumeration < Object > en2 = header . keys ( ) ; while ( en2 . hasMoreElements ( ) ) { String key = ( String ) en2 . nextElement ( ) ; String value = header . getProperty ( key ) ; response . setHeader ( key , value ) ; } resp . writeTo ( response . getOutputStream ( ) ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; ServletUtils . setResponseStatus ( response , 500 ) ; Log . err ( e ) ; // Trying to send an error message or stack trace will produce another IOException . . .
} finally { ServletUtils . logRequest ( method , request , response ) ; // Handle shutdown if it was requested .
if ( H2O . getShutdownRequested ( ) ) { ( new Thread ( ) { public void run ( ) { boolean [ ] confirmations = new boolean [ H2O . CLOUD . size ( ) ] ; if ( H2O . SELF . index ( ) >= 0 ) { confirmations [ H2O . SELF . index ( ) ] = true ; } for ( H2ONode n : H2O . CLOUD . _memary ) { if ( n != H2O . SELF ) new RPC < > ( n , new UDPRebooted . ShutdownTsk ( H2O . SELF , n . index ( ) , 1000 , confirmations , 0 ) ) . call ( ) ; } try { Thread . sleep ( 2000 ) ; } catch ( Exception ignore ) { } int failedToShutdown = 0 ; // shutdown failed
for ( boolean b : confirmations ) if ( ! b ) failedToShutdown ++ ; Log . info ( "Orderly shutdown: " + ( failedToShutdown > 0 ? failedToShutdown + " nodes failed to shut down! " : "" ) + " Shutting down now." ) ; H2O . closeAll ( ) ; H2O . exit ( failedToShutdown ) ; } } ) . start ( ) ; } ServletUtils . endTransaction ( ) ; } |
public class HtmlEncoder { /** * Translates the alignment value .
* @ param alignment the alignment value
* @ return the translated value */
public static String getAlignment ( int alignment ) { } } | switch ( alignment ) { case Element . ALIGN_LEFT : return HtmlTags . ALIGN_LEFT ; case Element . ALIGN_CENTER : return HtmlTags . ALIGN_CENTER ; case Element . ALIGN_RIGHT : return HtmlTags . ALIGN_RIGHT ; case Element . ALIGN_JUSTIFIED : case Element . ALIGN_JUSTIFIED_ALL : return HtmlTags . ALIGN_JUSTIFIED ; case Element . ALIGN_TOP : return HtmlTags . ALIGN_TOP ; case Element . ALIGN_MIDDLE : return HtmlTags . ALIGN_MIDDLE ; case Element . ALIGN_BOTTOM : return HtmlTags . ALIGN_BOTTOM ; case Element . ALIGN_BASELINE : return HtmlTags . ALIGN_BASELINE ; default : return "" ; } |
public class Utf8Util { /** * Custom UTF - 8 encoding . Generates UTF - 8 byte sequence for the specified char [ ] . The UTF - 8 byte sequence is
* encoded in the specified ByteBuffer .
* @ param srcBuf the source char [ ] to be encoded as UTF - 8 byte sequence
* @ param srcOffset offset in the char [ ] from where the conversion to UTF - 8 should begin
* @ param srcLength the number of chars to be encoded as UTF - 8 bytes
* @ param dest the destination ByteBuffer
* @ param destOffset offset in the ByteBuffer starting where the encoded UTF - 8 bytes should be copied
* @ return the number of bytes encoded */
public static int charstoUTF8Bytes ( char [ ] srcBuf , int srcOffset , int srcLength , ByteBuffer dest , int destOffset ) { } } | int destMark = destOffset ; for ( int i = srcOffset ; i < srcLength ; ) { char ch = srcBuf [ i ] ; if ( ch < 0x0080 ) { dest . put ( destOffset ++ , ( byte ) ch ) ; } else if ( ch < 0x0800 ) { dest . put ( destOffset ++ , ( byte ) ( 0xc0 | ( ch >> 6 ) ) ) ; dest . put ( destOffset ++ , ( byte ) ( 0x80 | ( ( ch >> 0 ) & 0x3f ) ) ) ; } else if ( ( ( ch >= 0x0800 ) && ( ch <= 0xD7FF ) ) || ( ( ch >= 0xE000 ) && ( ch <= 0xFFFF ) ) ) { dest . put ( destOffset ++ , ( byte ) ( 0xe0 | ( ch >> 12 ) ) ) ; dest . put ( destOffset ++ , ( byte ) ( 0x80 | ( ( ch >> 6 ) & 0x3F ) ) ) ; dest . put ( destOffset ++ , ( byte ) ( 0x80 | ( ( ch >> 0 ) & 0x3F ) ) ) ; } else if ( ( ch >= Character . MIN_SURROGATE ) && ( ch <= Character . MAX_SURROGATE ) ) { // Surrogate pair
if ( i == srcBuf . length ) { throw new IllegalStateException ( format ( MSG_INVALID_CODEPOINT , ch ) ) ; } char ch1 = ch ; char ch2 = srcBuf [ ++ i ] ; if ( ch1 > Character . MAX_HIGH_SURROGATE ) { throw new IllegalStateException ( format ( MSG_INVALID_CODEPOINT , ch1 ) ) ; } int codePoint = Character . toCodePoint ( ch1 , ch2 ) ; // int codePoint = ( ( ( ch1 & 0x03FF ) < < 10 ) | ( ch2 & 0x03FF ) ) + Character . MIN _ SUPPLEMENTARY _ CODE _ POINT ;
dest . put ( destOffset ++ , ( byte ) ( 0xf0 | ( codePoint >> 18 ) ) ) ; dest . put ( destOffset ++ , ( byte ) ( 0x80 | ( ( codePoint >> 12 ) & 0x3F ) ) ) ; dest . put ( destOffset ++ , ( byte ) ( 0x80 | ( ( codePoint >> 6 ) & 0x3F ) ) ) ; dest . put ( destOffset ++ , ( byte ) ( 0x80 | ( ( codePoint >> 0 ) & 0x3F ) ) ) ; } else { throw new IllegalStateException ( format ( MSG_INVALID_CODEPOINT , ch ) ) ; } i ++ ; } return destOffset - destMark ; |
public class JSON { /** * parse json .
* @ param reader json source .
* @ param types target type array .
* @ return result .
* @ throws IOException
* @ throws ParseException */
public static Object [ ] parse ( Reader reader , Class < ? > [ ] types , Converter < Object , Map < String , Object > > mc ) throws IOException , ParseException { } } | return ( Object [ ] ) parse ( reader , new JSONVisitor ( types , new JSONValue ( mc ) ) , JSONToken . LSQUARE ) ; |
public class SiftDetector { /** * Detects SIFT features inside the input image
* @ param input Input image . Not modified . */
public void process ( GrayF32 input ) { } } | scaleSpace . initialize ( input ) ; detections . reset ( ) ; do { // scale from octave to input image
pixelScaleToInput = scaleSpace . pixelScaleCurrentToInput ( ) ; // detect features in the image
for ( int j = 1 ; j < scaleSpace . getNumScales ( ) + 1 ; j ++ ) { // not really sure how to compute the scale for features found at a particular DoG image
// using the average resulted in less visually appealing circles in a test image
sigmaLower = scaleSpace . computeSigmaScale ( j - 1 ) ; sigmaTarget = scaleSpace . computeSigmaScale ( j ) ; sigmaUpper = scaleSpace . computeSigmaScale ( j + 1 ) ; // grab the local DoG scale space images
dogLower = scaleSpace . getDifferenceOfGaussian ( j - 1 ) ; dogTarget = scaleSpace . getDifferenceOfGaussian ( j ) ; dogUpper = scaleSpace . getDifferenceOfGaussian ( j + 1 ) ; detectFeatures ( j ) ; } } while ( scaleSpace . computeNextOctave ( ) ) ; |
public class AbstractValidate { /** * < p > Validate that the specified argument iterable is neither { @ code null } nor contains any elements that are { @ code null } ; otherwise throwing an exception with the specified message . < / p >
* < pre > Validate . noNullElements ( myCollection , " The collection contains null at position % d " ) ; < / pre >
* < p > If the iterable is { @ code null } , then the message in the exception is & quot ; The validated object is null & quot ; . < / p > < p > If the iterable has a { @ code null } element , then the iteration index of
* the invalid element is appended to the { @ code values } argument . < / p >
* @ param < T >
* the iterable type
* @ param iterable
* the iterable to check , validated not null by this method
* @ param message
* the { @ link String # format ( String , Object . . . ) } exception message if invalid , not null
* @ param values
* the optional values for the formatted exception message , null array not recommended
* @ return the validated iterable ( never { @ code null } method for chaining )
* @ throws NullPointerValidationException
* if the array is { @ code null }
* @ throws IllegalArgumentException
* if an element is { @ code null }
* @ see # noNullElements ( Iterable ) */
public < T extends Iterable < ? > > T noNullElements ( final T iterable , final String message , final Object ... values ) { } } | notNull ( iterable ) ; final int index = indexOfNullElement ( iterable ) ; if ( index != - 1 ) { fail ( String . format ( message , ArrayUtils . addAll ( this , values , index ) ) ) ; } return iterable ; |
public class Security { /** * Returns an array containing all installed providers that satisfy the
* specified selection criterion , or null if no such providers have been
* installed . The returned providers are ordered
* according to their < a href =
* " # insertProviderAt ( java . security . Provider , int ) " > preference order < / a > .
* < p > A cryptographic service is always associated with a particular
* algorithm or type . For example , a digital signature service is
* always associated with a particular algorithm ( e . g . , DSA ) ,
* and a CertificateFactory service is always associated with
* a particular certificate type ( e . g . , X . 509 ) .
* < p > The selection criterion must be specified in one of the following two
* formats :
* < ul >
* < li > < i > & lt ; crypto _ service > . & lt ; algorithm _ or _ type > < / i > < p > The
* cryptographic service name must not contain any dots .
* < p > A
* provider satisfies the specified selection criterion iff the provider
* implements the
* specified algorithm or type for the specified cryptographic service .
* < p > For example , " CertificateFactory . X . 509"
* would be satisfied by any provider that supplied
* a CertificateFactory implementation for X . 509 certificates .
* < li > < i > & lt ; crypto _ service > . & lt ; algorithm _ or _ type >
* & lt ; attribute _ name > : & lt attribute _ value > < / i >
* < p > The cryptographic service name must not contain any dots . There
* must be one or more space charaters between the
* < i > & lt ; algorithm _ or _ type > < / i > and the < i > & lt ; attribute _ name > < / i > .
* < p > A provider satisfies this selection criterion iff the
* provider implements the specified algorithm or type for the specified
* cryptographic service and its implementation meets the
* constraint expressed by the specified attribute name / value pair .
* < p > For example , " Signature . SHA1withDSA KeySize : 1024 " would be
* satisfied by any provider that implemented
* the SHA1withDSA signature algorithm with a keysize of 1024 ( or larger ) .
* < / ul >
* < p > See the < a href =
* " { @ docRoot } openjdk - redirect . html ? v = 8 & path = / technotes / guides / security / StandardNames . html " >
* Java Cryptography Architecture Standard Algorithm Name Documentation < / a >
* for information about standard cryptographic service names , standard
* algorithm names and standard attribute names .
* @ param filter the criterion for selecting
* providers . The filter is case - insensitive .
* @ return all the installed providers that satisfy the selection
* criterion , or null if no such providers have been installed .
* @ throws InvalidParameterException
* if the filter is not in the required format
* @ throws NullPointerException if filter is null
* @ see # getProviders ( java . util . Map )
* @ since 1.3 */
public static Provider [ ] getProviders ( String filter ) { } } | String key = null ; String value = null ; int index = filter . indexOf ( ':' ) ; if ( index == - 1 ) { key = filter ; value = "" ; } else { key = filter . substring ( 0 , index ) ; value = filter . substring ( index + 1 ) ; } Hashtable < String , String > hashtableFilter = new Hashtable < > ( 1 ) ; hashtableFilter . put ( key , value ) ; return ( getProviders ( hashtableFilter ) ) ; |
public class ContentSpec { /** * Set the BookVersion of the Book the Content Specification represents .
* @ param bookVersion The Book Version . */
public void setBookVersion ( final String bookVersion ) { } } | if ( bookVersion == null && this . bookVersion == null ) { return ; } else if ( bookVersion == null ) { removeChild ( this . bookVersion ) ; this . bookVersion = null ; } else if ( this . bookVersion == null ) { this . bookVersion = new KeyValueNode < String > ( CommonConstants . CS_BOOK_VERSION_TITLE , bookVersion ) ; appendChild ( this . bookVersion , false ) ; } else { this . bookVersion . setValue ( bookVersion ) ; } |
public class SqlAgentFactoryImpl { /** * { @ inheritDoc }
* @ see jp . co . future . uroborosql . SqlAgentFactory # setDefaultMapKeyCaseFormat ( jp . co . future . uroborosql . utils . CaseFormat ) */
@ Override public SqlAgentFactory setDefaultMapKeyCaseFormat ( final CaseFormat defaultMapKeyCaseFormat ) { } } | getDefaultProps ( ) . put ( PROPS_KEY_DEFAULT_MAP_KEY_CASE_FORMAT , defaultMapKeyCaseFormat . toString ( ) ) ; return this ; |
public class RecognizerErrorHandler { /** * Simplify error message text for end users .
* @ param e exception that occurred
* @ param msg as formatted by ANTLR
* @ return a more readable error message */
public static String makeUserMsg ( final RecognitionException e , final String msg ) { } } | if ( e instanceof NoViableAltException ) { return msg . replace ( "no viable alternative at" , "unrecognized" ) ; } else if ( e instanceof UnwantedTokenException ) { return msg . replace ( "extraneous input" , "unexpected token" ) ; } else if ( e instanceof MismatchedTokenException ) { if ( msg . contains ( "mismatched input '<EOF>'" ) ) { return msg . replace ( "mismatched input '<EOF>' expecting" , "reached end of file looking for" ) ; } else { return msg . replace ( "mismatched input" , "unexpected token" ) ; } } else if ( e instanceof EarlyExitException ) { return msg . replace ( "required (...)+ loop did not match anything" , "required tokens not found" ) ; } else if ( e instanceof FailedPredicateException ) { if ( msg . contains ( "picture_string failed predicate: {Unbalanced parentheses}" ) ) { return "Unbalanced parentheses in picture string" ; } if ( msg . contains ( "PICTURE_PART failed predicate: {Contains invalid picture symbols}" ) ) { return "Picture string contains invalid symbols" ; } if ( msg . contains ( "PICTURE_PART failed predicate: {Syntax error in last picture clause}" ) ) { return "Syntax error in last picture clause" ; } if ( msg . contains ( "DATA_NAME failed predicate: {Syntax error in last clause}" ) ) { return "Syntax error in last COBOL clause" ; } } return msg ; |
public class PlotBoxTLSmall { /** * Get a buffered image of this chart
* @ param width The width of the image
* @ param height The height of the image
* @ return A buffered image of this chart . */
public BufferedImage getBufferedImage ( int width , int height ) { } } | BufferedImage bi = chart . createBufferedImage ( width , height ) ; return bi ; |
public class SettingLoader { /** * 加载设置文件
* @ param urlResource 配置文件URL
* @ return 加载是否成功 */
public boolean load ( UrlResource urlResource ) { } } | if ( urlResource == null ) { throw new NullPointerException ( "Null setting url define!" ) ; } log . debug ( "Load setting file [{}]" , urlResource ) ; InputStream settingStream = null ; try { settingStream = urlResource . getStream ( ) ; load ( settingStream ) ; } catch ( Exception e ) { log . error ( e , "Load setting error!" ) ; return false ; } finally { IoUtil . close ( settingStream ) ; } return true ; |
public class DestinationManager { /** * Returns the topicSpaceName of the foreign topicSpace
* @ param String The busname of the foreign TS
* @ param SIBUuid12 The uuid of the TS on this bus
* @ return String The foreign TS name */
public String getTopicSpaceMapping ( String busName , SIBUuid12 topicSpace ) { } } | if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . entry ( tc , "getTopicSpaceMapping" , new Object [ ] { busName , topicSpace } ) ; VirtualLinkDefinition linkDef = getLinkDefinition ( busName ) ; // this is only called internally so we shall include invisible dests in the lookup
String topicSpaceName = getDestinationInternal ( topicSpace , true ) . getName ( ) ; String mapping = null ; if ( linkDef != null && linkDef . getTopicSpaceMappings ( ) != null ) mapping = ( String ) linkDef . getTopicSpaceMappings ( ) . get ( topicSpaceName ) ; else // Local ME
mapping = topicSpaceName ; if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . exit ( tc , "getTopicSpaceMapping" , mapping ) ; return mapping ; |
public class CoffeeScriptCompilerMojo { /** * Finds and compiles coffeescript files .
* @ throws MojoExecutionException if the compilation failed . */
@ Override public void execute ( ) throws MojoExecutionException { } } | coffee = npm ( this , COFFEE_SCRIPT_NPM_NAME , coffeeScriptVersion ) ; try { if ( getInternalAssetsDirectory ( ) . isDirectory ( ) ) { getLog ( ) . info ( "Compiling CoffeeScript files from " + getInternalAssetsDirectory ( ) . getAbsolutePath ( ) ) ; invokeCoffeeScriptCompiler ( getInternalAssetsDirectory ( ) , getInternalAssetOutputDirectory ( ) ) ; } if ( getExternalAssetsDirectory ( ) . isDirectory ( ) ) { getLog ( ) . info ( "Compiling CoffeeScript files from " + getExternalAssetsDirectory ( ) . getAbsolutePath ( ) ) ; invokeCoffeeScriptCompiler ( getExternalAssetsDirectory ( ) , getExternalAssetsOutputDirectory ( ) ) ; } } catch ( WatchingException e ) { throw new MojoExecutionException ( "Error during the CoffeeScript compilation" , e ) ; } |
public class AssetServicesImpl { /** * Create a new asset ( version 1 ) on the file system . */
public void createAsset ( String path , byte [ ] content ) throws ServiceException { } } | int lastSlash = path . lastIndexOf ( '/' ) ; File assetFile = new File ( assetRoot + "/" + path . substring ( 0 , lastSlash ) . replace ( '.' , '/' ) + path . substring ( lastSlash ) ) ; try { FileHelper . writeToFile ( new ByteArrayInputStream ( content ) , assetFile ) ; AssetRevision rev = new AssetRevision ( ) ; rev . setVersion ( 1 ) ; rev . setModDate ( new Date ( ) ) ; getVersionControl ( ) . setRevision ( assetFile , rev ) ; } catch ( Exception ex ) { throw new ServiceException ( ServiceException . INTERNAL_ERROR , ex . getMessage ( ) ) ; } |
public class PostTextResult { /** * A map of key - value pairs representing the session - specific context information .
* @ param sessionAttributes
* A map of key - value pairs representing the session - specific context information .
* @ return Returns a reference to this object so that method calls can be chained together . */
public PostTextResult withSessionAttributes ( java . util . Map < String , String > sessionAttributes ) { } } | setSessionAttributes ( sessionAttributes ) ; return this ; |
public class PrcItemSpecificsRetrieve { /** * < p > Process entity request . < / p >
* @ param pReqVars additional request scoped vars
* document in " nextEntity " for farther process
* @ param pRequestData Request Data
* @ param pEntity Entity to process
* @ return Entity processed for farther process or null
* @ throws Exception - an exception */
@ Override public final AItemSpecifics < T , ID > process ( final Map < String , Object > pReqVars , final AItemSpecifics < T , ID > pEntity , final IRequestData pRequestData ) throws Exception { } } | AItemSpecifics < T , ID > entity = this . prcEntityRetrieve . process ( pReqVars , pEntity , pRequestData ) ; if ( entity . getSpecifics ( ) . getItsType ( ) != null && entity . getSpecifics ( ) . getItsType ( ) . equals ( ESpecificsItemType . BIGDECIMAL ) ) { if ( entity . getNumericValue1 ( ) == null ) { entity . setNumericValue1 ( BigDecimal . ZERO ) ; } if ( entity . getLongValue1 ( ) == null ) { entity . setLongValue2 ( 2L ) ; } pReqVars . put ( "RSisUsePrecision" + entity . getLongValue2 ( ) , true ) ; } return entity ; |
public class GSMBitPacker { /** * Unpack a byte array according to the GSM bit - packing algorithm .
* Read the full description in the documentation of the
* < code > pack < / code > method .
* @ see # pack ( byte [ ] )
* @ param packed The packed byte array .
* @ return A new byte array containing the unpacked bytes . */
static public byte [ ] unpack ( byte [ ] packed ) { } } | if ( packed == null ) { return null ; } int unpackedLen = ( packed . length * 8 ) / 7 ; byte [ ] unpacked = new byte [ unpackedLen ] ; int len = unpacked . length ; int current = 0 ; int bitpos = 0 ; for ( int i = 0 ; i < len ; i ++ ) { // remove top bit and assign first half of partial bits
unpacked [ i ] = ( byte ) ( ( ( packed [ current ] & 0xFF ) >> bitpos ) & 0x7F ) ; // remove top bit and assign second half of partial bits ( if exist )
if ( bitpos >= 2 ) unpacked [ i ] |= ( byte ) ( ( packed [ ++ current ] << ( 8 - bitpos ) ) & 0x7F ) ; bitpos = ( bitpos + 7 ) % 8 ; if ( bitpos == 0 ) current ++ ; } // this fixes an ambiguity bug in the specs
// where the last of 8 packed bytes is 0
// and it ' s impossible to distinguish whether it is a
// trailing ' @ ' character ( which is mapped to 0)
// or extra zero - bit padding for 7 actual data bytes .
// we opt for the latter , since it ' s far more likely ,
// at the cost of losing a trailing ' @ ' character
// in strings whose unpacked size modulo 8 is 0,
// and whose last character is ' @ ' .
// an application that wishes to handle this rare case
// properly must disambiguate this case externally , such
// as by obtaining the original string length , and
// appending the trailing ' @ ' if the length
// shows that there is one character missing .
if ( len % 8 == 0 && len > 0 && unpacked [ len - 1 ] == 0 ) { // System . err . println ( " Hit special case . . . " ) ;
byte [ ] fixed = new byte [ len - 1 ] ; System . arraycopy ( unpacked , 0 , fixed , 0 , len - 1 ) ; unpacked = fixed ; } return unpacked ; |
public class Stats { /** * Any provider that may be used for StatsComponent can be added here . */
@ DefaultVisibilityForTesting static StatsComponent loadStatsComponent ( @ Nullable ClassLoader classLoader ) { } } | try { // Call Class . forName with literal string name of the class to help shading tools .
return Provider . createInstance ( Class . forName ( "io.opencensus.impl.stats.StatsComponentImpl" , /* initialize = */
true , classLoader ) , StatsComponent . class ) ; } catch ( ClassNotFoundException e ) { logger . log ( Level . FINE , "Couldn't load full implementation for StatsComponent, now trying to load lite " + "implementation." , e ) ; } try { // Call Class . forName with literal string name of the class to help shading tools .
return Provider . createInstance ( Class . forName ( "io.opencensus.impllite.stats.StatsComponentImplLite" , /* initialize = */
true , classLoader ) , StatsComponent . class ) ; } catch ( ClassNotFoundException e ) { logger . log ( Level . FINE , "Couldn't load lite implementation for StatsComponent, now using " + "default implementation for StatsComponent." , e ) ; } return NoopStats . newNoopStatsComponent ( ) ; |
public class DateCaster { /** * converts the given string to a date following simple and fast parsing rules ( no international
* formats )
* @ param str
* @ param convertingType one of the following values : - CONVERTING _ TYPE _ NONE : number are not
* converted at all - CONVERTING _ TYPE _ YEAR : integers are handled as years -
* CONVERTING _ TYPE _ OFFSET : numbers are handled as offset from 1899-12-30 00:00:00 UTC
* @ param alsoMonthString allow that the month is defined as english word ( jan , janauary . . . )
* @ param timeZone
* @ param defaultValue
* @ return */
public static DateTime toDateSimple ( String str , short convertingType , boolean alsoMonthString , TimeZone timeZone , DateTime defaultValue ) { } } | str = StringUtil . trim ( str , "" ) ; DateString ds = new DateString ( str ) ; // Timestamp
if ( ds . isCurrent ( '{' ) && ds . isLast ( '}' ) ) { return _toDateSimpleTS ( ds , timeZone , defaultValue ) ; } DateTime res = parseDateTime ( str , ds , convertingType , alsoMonthString , timeZone , defaultValue ) ; if ( res == defaultValue && Decision . isNumber ( str ) ) { return numberToDate ( timeZone , Caster . toDoubleValue ( str , Double . NaN ) , convertingType , defaultValue ) ; } return res ; |
public class CommerceSubscriptionEntryPersistenceImpl { /** * Returns a range of all the commerce subscription entries where subscriptionStatus = & # 63 ; .
* Useful when paginating results . Returns a maximum of < code > end - start < / code > instances . < code > start < / code > and < code > end < / code > are not primary keys , they are indexes in the result set . Thus , < code > 0 < / code > refers to the first result in the set . Setting both < code > start < / code > and < code > end < / code > to { @ link QueryUtil # ALL _ POS } will return the full result set . If < code > orderByComparator < / code > is specified , then the query will include the given ORDER BY logic . If < code > orderByComparator < / code > is absent and pagination is required ( < code > start < / code > and < code > end < / code > are not { @ link QueryUtil # ALL _ POS } ) , then the query will include the default ORDER BY logic from { @ link CommerceSubscriptionEntryModelImpl } . If both < code > orderByComparator < / code > and pagination are absent , for performance reasons , the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order .
* @ param subscriptionStatus the subscription status
* @ param start the lower bound of the range of commerce subscription entries
* @ param end the upper bound of the range of commerce subscription entries ( not inclusive )
* @ return the range of matching commerce subscription entries */
@ Override public List < CommerceSubscriptionEntry > findBySubscriptionStatus ( int subscriptionStatus , int start , int end ) { } } | return findBySubscriptionStatus ( subscriptionStatus , start , end , null ) ; |
public class SpanContextUtil { /** * Adds logging tags to the provided { @ link Span } and closes it when the log is finished .
* The span cannot be used further after this method has been called . */
public static void closeSpan ( Span span , RequestLog log ) { } } | SpanTags . addTags ( span , log ) ; span . finish ( wallTimeMicros ( log , log . responseEndTimeNanos ( ) ) ) ; |
public class AmazonIdentityManagementClient { /** * Adds or updates an inline policy document that is embedded in the specified IAM role .
* When you embed an inline policy in a role , the inline policy is used as part of the role ' s access ( permissions )
* policy . The role ' s trust policy is created at the same time as the role , using < a > CreateRole < / a > . You can update
* a role ' s trust policy using < a > UpdateAssumeRolePolicy < / a > . For more information about IAM roles , go to < a
* href = " https : / / docs . aws . amazon . com / IAM / latest / UserGuide / roles - toplevel . html " > Using Roles to Delegate Permissions
* and Federate Identities < / a > .
* A role can also have a managed policy attached to it . To attach a managed policy to a role , use
* < a > AttachRolePolicy < / a > . To create a new managed policy , use < a > CreatePolicy < / a > . For information about policies ,
* see < a href = " https : / / docs . aws . amazon . com / IAM / latest / UserGuide / policies - managed - vs - inline . html " > Managed Policies
* and Inline Policies < / a > in the < i > IAM User Guide < / i > .
* For information about limits on the number of inline policies that you can embed with a role , see < a
* href = " https : / / docs . aws . amazon . com / IAM / latest / UserGuide / LimitationsOnEntities . html " > Limitations on IAM
* Entities < / a > in the < i > IAM User Guide < / i > .
* < note >
* Because policy documents can be large , you should use POST rather than GET when calling
* < code > PutRolePolicy < / code > . For general information about using the Query API with IAM , go to < a
* href = " https : / / docs . aws . amazon . com / IAM / latest / UserGuide / IAM _ UsingQueryAPI . html " > Making Query Requests < / a > in the
* < i > IAM User Guide < / i > .
* < / note >
* @ param putRolePolicyRequest
* @ return Result of the PutRolePolicy operation returned by the service .
* @ throws LimitExceededException
* The request was rejected because it attempted to create resources beyond the current AWS account limits .
* The error message describes the limit exceeded .
* @ throws MalformedPolicyDocumentException
* The request was rejected because the policy document was malformed . The error message describes the
* specific error .
* @ throws NoSuchEntityException
* The request was rejected because it referenced a resource entity that does not exist . The error message
* describes the resource .
* @ throws UnmodifiableEntityException
* The request was rejected because only the service that depends on the service - linked role can modify or
* delete the role on your behalf . The error message includes the name of the service that depends on this
* service - linked role . You must request the change through that service .
* @ throws ServiceFailureException
* The request processing has failed because of an unknown error , exception or failure .
* @ sample AmazonIdentityManagement . PutRolePolicy
* @ see < a href = " http : / / docs . aws . amazon . com / goto / WebAPI / iam - 2010-05-08 / PutRolePolicy " target = " _ top " > AWS API
* Documentation < / a > */
@ Override public PutRolePolicyResult putRolePolicy ( PutRolePolicyRequest request ) { } } | request = beforeClientExecution ( request ) ; return executePutRolePolicy ( request ) ; |
public class MatrixFeatures_DDRM { /** * Checks to see if a matrix is orthogonal or isometric .
* @ param Q The matrix being tested . Not modified .
* @ param tol Tolerance .
* @ return True if it passes the test . */
public static boolean isOrthogonal ( DMatrixRMaj Q , double tol ) { } } | if ( Q . numRows < Q . numCols ) { throw new IllegalArgumentException ( "The number of rows must be more than or equal to the number of columns" ) ; } DMatrixRMaj u [ ] = CommonOps_DDRM . columnsToVector ( Q , null ) ; for ( int i = 0 ; i < u . length ; i ++ ) { DMatrixRMaj a = u [ i ] ; for ( int j = i + 1 ; j < u . length ; j ++ ) { double val = VectorVectorMult_DDRM . innerProd ( a , u [ j ] ) ; if ( ! ( Math . abs ( val ) <= tol ) ) return false ; } } return true ; |
public class FloatArray { /** * ( non - Javadoc )
* @ see java . util . AbstractList # addAll ( int , java . util . Collection ) */
@ Override public boolean addAll ( int index , Collection < ? extends Float > c ) { } } | if ( index < 0 || index > size ) { throw new IndexOutOfBoundsException ( ) ; } ensureCapacity ( size + c . size ( ) ) ; size += c . size ( ) ; for ( int i = size + c . size ( ) - 1 , j = size - 1 ; j >= index ; i -- , j -- ) { elements [ i ] = elements [ j ] ; } for ( float e : c ) { elements [ index ++ ] = e ; } return c . size ( ) > 0 ; |
public class CPDefinitionInventoryPersistenceImpl { /** * Returns the cp definition inventory where uuid = & # 63 ; and groupId = & # 63 ; or throws a { @ link NoSuchCPDefinitionInventoryException } if it could not be found .
* @ param uuid the uuid
* @ param groupId the group ID
* @ return the matching cp definition inventory
* @ throws NoSuchCPDefinitionInventoryException if a matching cp definition inventory could not be found */
@ Override public CPDefinitionInventory findByUUID_G ( String uuid , long groupId ) throws NoSuchCPDefinitionInventoryException { } } | CPDefinitionInventory cpDefinitionInventory = fetchByUUID_G ( uuid , groupId ) ; if ( cpDefinitionInventory == null ) { StringBundler msg = new StringBundler ( 6 ) ; msg . append ( _NO_SUCH_ENTITY_WITH_KEY ) ; msg . append ( "uuid=" ) ; msg . append ( uuid ) ; msg . append ( ", groupId=" ) ; msg . append ( groupId ) ; msg . append ( "}" ) ; if ( _log . isDebugEnabled ( ) ) { _log . debug ( msg . toString ( ) ) ; } throw new NoSuchCPDefinitionInventoryException ( msg . toString ( ) ) ; } return cpDefinitionInventory ; |
public class AppServiceEnvironmentsInner { /** * Create or update a worker pool .
* Create or update a worker pool .
* @ param resourceGroupName Name of the resource group to which the resource belongs .
* @ param name Name of the App Service Environment .
* @ param workerPoolName Name of the worker pool .
* @ param workerPoolEnvelope Properties of the worker pool .
* @ 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 < WorkerPoolResourceInner > beginCreateOrUpdateWorkerPoolAsync ( String resourceGroupName , String name , String workerPoolName , WorkerPoolResourceInner workerPoolEnvelope , final ServiceCallback < WorkerPoolResourceInner > serviceCallback ) { } } | return ServiceFuture . fromResponse ( beginCreateOrUpdateWorkerPoolWithServiceResponseAsync ( resourceGroupName , name , workerPoolName , workerPoolEnvelope ) , serviceCallback ) ; |
public class StreamRecord { /** * The primary key attribute ( s ) for the DynamoDB item that was modified .
* @ param keys
* The primary key attribute ( s ) for the DynamoDB item that was modified .
* @ return Returns a reference to this object so that method calls can be chained together . */
public StreamRecord withKeys ( java . util . Map < String , AttributeValue > keys ) { } } | setKeys ( keys ) ; return this ; |
public class PhoneIntents { /** * Creates an intent that will allow to send an SMS without specifying the phone number
* @ param body The text to send
* @ return the intent */
public static Intent newSmsIntent ( Context context , String body ) { } } | return newSmsIntent ( context , body , ( String [ ] ) null ) ; |
public class LazyReact { /** * Start a reactive flow from a JDK Iterator
* < pre >
* { @ code
* Iterator < Integer > iterator ;
* new LazyReact ( 10,10 ) . from ( iterator )
* . map ( this : : process ) ;
* < / pre >
* @ param iterator SimpleReact will iterate over this iterator concurrently to skip the reactive dataflow
* @ return FutureStream */
@ SuppressWarnings ( "unchecked" ) public < U > FutureStream < U > from ( final Iterator < U > iterator ) { } } | return fromStream ( StreamSupport . stream ( Spliterators . spliteratorUnknownSize ( iterator , Spliterator . ORDERED ) , false ) ) ; |
public class ILUT { /** * Copies the dense array back into the sparse vector , applying a numerical
* dropping rule and keeping only a given number of entries */
private void gather ( double [ ] z , SparseVector v , double taui , int d ) { } } | // Number of entries in the lower and upper part of the original matrix
int nl = 0 , nu = 0 ; for ( VectorEntry e : v ) { if ( e . index ( ) < d ) nl ++ ; else if ( e . index ( ) > d ) nu ++ ; } v . zero ( ) ; // Entries in the L part of the vector
lower . clear ( ) ; for ( int i = 0 ; i < d ; ++ i ) if ( Math . abs ( z [ i ] ) > taui ) lower . add ( new IntDoubleEntry ( i , z [ i ] ) ) ; // Entries in the U part of the vector
upper . clear ( ) ; for ( int i = d + 1 ; i < z . length ; ++ i ) if ( Math . abs ( z [ i ] ) > taui ) upper . add ( new IntDoubleEntry ( i , z [ i ] ) ) ; // Sort in descending order
Collections . sort ( lower ) ; Collections . sort ( upper ) ; // Always keep the diagonal
v . set ( d , z [ d ] ) ; // Keep at most nl + p lower entries
for ( int i = 0 ; i < Math . min ( nl + p , lower . size ( ) ) ; ++ i ) { IntDoubleEntry e = lower . get ( i ) ; v . set ( e . index , e . value ) ; } // Keep at most nu + p upper entries
for ( int i = 0 ; i < Math . min ( nu + p , upper . size ( ) ) ; ++ i ) { IntDoubleEntry e = upper . get ( i ) ; v . set ( e . index , e . value ) ; } |
public class AbstractGISTreeSetNode { /** * { @ inheritDoc }
* < p > Caution : This function does not replies the bounding
* object itself , but a copy of it .
* See { @ link # getBounds ( ) } to obtain the object itself .
* @ see # getBounds ( ) */
@ Override @ Pure public Rectangle2d getObjectBounds ( ) { } } | final Rectangle2d b = new Rectangle2d ( ) ; final Rectangle2afp < ? , ? , ? , ? , ? , ? > bb = getBounds ( ) ; if ( bb != null && ! bb . isEmpty ( ) ) { b . set ( bb . getMinX ( ) , bb . getMinY ( ) , bb . getWidth ( ) , bb . getHeight ( ) ) ; } return b ; |
public class RawEmailMarshaller { /** * Marshall the given parameter object . */
public void marshall ( RawEmail rawEmail , ProtocolMarshaller protocolMarshaller ) { } } | if ( rawEmail == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( rawEmail . getData ( ) , DATA_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class Expiring { /** * Sets the default expire time and unit */
public Expiring < T > withDefault ( long expireTime , TimeUnit expireUnit ) { } } | checkArgument ( expireTime > 0 ) ; this . defaultExpireTime = Optional . of ( expireTime ) ; this . defaultExpireUnit = Optional . of ( expireUnit ) ; return this ; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.