signature stringlengths 43 39.1k | implementation stringlengths 0 450k |
|---|---|
public class Utils { /** * Return true or false if the input is a long
* @ param input
* @ return boolean */
public static boolean isLong ( String input ) { } } | try { Long . parseLong ( input ) ; return true ; } catch ( Exception e ) { return false ; } |
public class SoftMethodStorage { /** * stores a single method
* @ param method
* @ param methodsMap */
private void storeMethod ( Method method , Map < Key , Array > methodsMap ) { } } | Key methodName = KeyImpl . init ( method . getName ( ) ) ; Array methodArgs ; synchronized ( methodsMap ) { methodArgs = methodsMap . get ( methodName ) ; if ( methodArgs == null ) { methodArgs = new ArrayImpl ( ) ; methodsMap . put ( methodName , methodArgs ) ; } } storeArgs ( method , methodArgs ) ; // Modifier . isStatic ( method . getModifiers ( ) ) ; |
public class JCusparse { /** * < pre >
* Description : Compute the incomplete - Cholesky factorization with 0 fill - in ( IC0)
* of the matrix A stored in block - CSR format based on the information in the opaque
* structure info that was obtained from the analysis phase ( bsrsv2 _ analysis ) .
* This routine implements algorithm 1 for this problem .
* < / pre > */
public static int cusparseXbsric02_zeroPivot ( cusparseHandle handle , bsric02Info info , Pointer position ) { } } | return checkResult ( cusparseXbsric02_zeroPivotNative ( handle , info , position ) ) ; |
public class MimeUtil { /** * Adds the entry .
* @ param aStringArray the a string array */
private static void addEntry ( final ArrayList < String > aStringArray ) { } } | try { final MagicMimeEntry magicEntry = new MagicMimeEntry ( aStringArray ) ; mMagicMimeEntries . add ( magicEntry ) ; } catch ( final InvalidMagicMimeEntryException e ) { } |
public class lbmetrictable { /** * Use this API to update lbmetrictable resources . */
public static base_responses update ( nitro_service client , lbmetrictable resources [ ] ) throws Exception { } } | base_responses result = null ; if ( resources != null && resources . length > 0 ) { lbmetrictable updateresources [ ] = new lbmetrictable [ resources . length ] ; for ( int i = 0 ; i < resources . length ; i ++ ) { updateresources [ i ] = new lbmetrictable ( ) ; updateresources [ i ] . metrictable = resources [ i ] . metrictable ; updateresources [ i ] . metric = resources [ i ] . metric ; updateresources [ i ] . Snmpoid = resources [ i ] . Snmpoid ; } result = update_bulk_request ( client , updateresources ) ; } return result ; |
public class SlidingDrawer { /** * Offsets the menu relative to its original position based on the position of the content .
* @ param offsetPixels The number of pixels the content if offset . */
private void offsetMenu ( int offsetPixels ) { } } | if ( ! mOffsetMenu || mMenuSize == 0 ) { return ; } final int width = getWidth ( ) ; final int height = getHeight ( ) ; final int menuSize = mMenuSize ; final int sign = ( int ) ( mOffsetPixels / Math . abs ( mOffsetPixels ) ) ; final float openRatio = Math . abs ( mOffsetPixels ) / menuSize ; final int offset = ( int ) ( - 0.25f * ( ( 1.0f - openRatio ) * menuSize ) * sign ) ; switch ( getPosition ( ) ) { case LEFT : { if ( USE_TRANSLATIONS ) { if ( offsetPixels > 0 ) { mMenuContainer . setTranslationX ( offset ) ; } else { mMenuContainer . setTranslationX ( - menuSize ) ; } } else { mMenuContainer . offsetLeftAndRight ( offset - mMenuContainer . getLeft ( ) ) ; mMenuContainer . setVisibility ( offsetPixels == 0 ? INVISIBLE : VISIBLE ) ; } break ; } case RIGHT : { if ( USE_TRANSLATIONS ) { if ( offsetPixels != 0 ) { mMenuContainer . setTranslationX ( offset ) ; } else { mMenuContainer . setTranslationX ( menuSize ) ; } } else { final int oldOffset = mMenuContainer . getRight ( ) - width ; final int offsetBy = offset - oldOffset ; mMenuContainer . offsetLeftAndRight ( offsetBy ) ; mMenuContainer . setVisibility ( offsetPixels == 0 ? INVISIBLE : VISIBLE ) ; } break ; } case TOP : { if ( USE_TRANSLATIONS ) { if ( offsetPixels > 0 ) { mMenuContainer . setTranslationY ( offset ) ; } else { mMenuContainer . setTranslationY ( - menuSize ) ; } } else { mMenuContainer . offsetTopAndBottom ( offset - mMenuContainer . getTop ( ) ) ; mMenuContainer . setVisibility ( offsetPixels == 0 ? INVISIBLE : VISIBLE ) ; } break ; } case BOTTOM : { if ( USE_TRANSLATIONS ) { if ( offsetPixels != 0 ) { mMenuContainer . setTranslationY ( offset ) ; } else { mMenuContainer . setTranslationY ( menuSize ) ; } } else { final int oldOffset = mMenuContainer . getBottom ( ) - height ; final int offsetBy = offset - oldOffset ; mMenuContainer . offsetTopAndBottom ( offsetBy ) ; mMenuContainer . setVisibility ( offsetPixels == 0 ? INVISIBLE : VISIBLE ) ; } break ; } } |
public class Base64 { /** * Encodes a byte array into Base64 notation .
* Example options : < pre >
* GZIP : gzip - compresses object before encoding it .
* DO _ BREAK _ LINES : break lines at 76 characters
* < i > Note : Technically , this makes your encoding non - compliant . < / i >
* < / pre >
* Example : < code > encodeBytes ( myData , Base64 . GZIP ) < / code > or
* Example : < code > encodeBytes ( myData , Base64 . GZIP | Base64 . DO _ BREAK _ LINES ) < / code >
* < p > As of v 2.3 , if there is an error with the GZIP stream ,
* the method will throw an java . io . IOException . < b > This is new to v2.3 ! < / b >
* In earlier versions , it just returned a null value , but
* in retrospect that ' s a pretty poor way to handle it . < / p >
* @ param source The data to convert
* @ param off Offset in array where conversion should begin
* @ param len Length of data to convert
* @ param options Specified options
* @ return The Base64 - encoded data as a String
* @ see Base64 # GZIP
* @ see Base64 # DO _ BREAK _ LINES
* @ throws java . io . IOException if there is an error
* @ throws NullPointerException if source array is null
* @ throws IllegalArgumentException if source array , offset , or length are invalid
* @ since 2.0 */
@ edu . umd . cs . findbugs . annotations . SuppressWarnings ( value = "DM_DEFAULT_ENCODING" ) public static String encodeBytes ( byte [ ] source , int off , int len , int options ) throws java . io . IOException { } } | byte [ ] encoded = encodeBytesToBytes ( source , off , len , options ) ; // Return value according to relevant encoding .
try { return new String ( encoded , PREFERRED_ENCODING ) ; } // end try
catch ( java . io . UnsupportedEncodingException uue ) { return new String ( encoded ) ; } // end catch |
public class NetworkCalibration { /** * Estimate the discharge for each time and for each pipes .
* It can work with a single rain time step ( if there is an actual rain ) or search the maximum rain time , if the rain is unknown and
* the rain data are builtthroghout the rain possibility curve .
* It work throgout 2 loop :
* < ol >
* < li > The first on the head pipes .
* < li > The second on the pipes which are internal .
* < / ol > */
@ Override public void geoSewer ( ) throws Exception { } } | if ( ! foundMaxrainTime ) { evaluateDischarge ( lastTimeDischarge , lastTimeFillDegree , tpMaxCalibration ) ; } else { /* * start to evaluate the discharge from 15 minutes , evaluate the nearsted value to 15 minutes . */
int minTime = ( int ) ModelsEngine . approximate2Multiple ( INITIAL_TIME , dt ) ; double qMax = 0 ; for ( int i = minTime ; i < tpMaxCalibration ; i = i + dt ) { tpMax = i ; double [ ] [ ] timeDischarge = createMatrix ( ) ; double [ ] [ ] timeFillDegree = createMatrix ( ) ; double q = evaluateDischarge ( timeDischarge , timeFillDegree , i ) ; if ( q > qMax ) { qMax = q ; lastTimeDischarge = timeDischarge ; lastTimeFillDegree = timeFillDegree ; } else if ( q < qMax ) { break ; } if ( isFill ) { break ; } } } getNetData ( ) ; |
public class CardinalityLimiters { /** * Allows the clock to be specified for testing . See { @ link # mostFrequent ( int ) } for
* details on the usage . */
static Function < String , String > mostFrequent ( int n , Clock clock ) { } } | return new MostFrequentLimiter ( Math . min ( n , MAX_LIMIT ) , clock ) ; |
public class CmsClientProperty { /** * Makes a " lazy copy " of a map of properties , which will create properties on lookup if they don ' t already exist . < p >
* @ param properties the properties to copy
* @ return the lazy copy of the properties */
public static Map < String , CmsClientProperty > makeLazyCopy ( Map < String , CmsClientProperty > properties ) { } } | if ( properties == null ) { return null ; } return toLazyMap ( copyProperties ( properties ) ) ; |
public class EasyXls { /** * 导入xls到List
* @ param config 配置
* @ param inputStream xls文件流
* @ return List对象
* @ throws Exception */
public static List < ? > xls2List ( ExcelConfig config , InputStream inputStream ) throws Exception { } } | return XlsUtil . xls2List ( config , inputStream ) ; |
public class AssociateTargetCommandInstruction { /** * ( non - Javadoc )
* @ see net . roboconf . core . commands . AbstractCommandInstruction # doValidate ( ) */
@ Override public List < ParsingError > doValidate ( ) { } } | List < ParsingError > result = new ArrayList < > ( ) ; if ( Utils . isEmptyOrWhitespaces ( this . targetId ) ) result . add ( error ( ErrorCode . CMD_INVALID_TARGET_ID , value ( this . targetId ) ) ) ; Instance resolvedInstance ; if ( ( resolvedInstance = this . context . resolveInstance ( this . scopedInstancePath ) ) == null ) result . add ( error ( ErrorCode . CMD_NO_MATCHING_INSTANCE , instance ( this . scopedInstancePath ) ) ) ; else if ( ! InstanceHelpers . isTarget ( resolvedInstance ) ) result . add ( error ( ErrorCode . CMD_NOT_A_SCOPED_INSTANCE ) ) ; return result ; |
public class AbstractComponentRegistry { /** * Retrieves a component factory instance capable of constructing components of a specified type . If the factory
* doesn ' t exist in the registry , one is created .
* @ param componentClass type of component to construct
* @ return component factory capable of constructing such components */
protected AbstractComponentFactory getFactory ( Class < ? > componentClass ) { } } | String cfClass = getComponentMetadataRepo ( ) . findFactoryForComponent ( componentClass ) ; if ( cfClass == null ) { throw new CacheConfigurationException ( "No registered default factory for component '" + componentClass + "' found!" ) ; } return basicComponentRegistry . getComponent ( cfClass , AbstractComponentFactory . class ) . wired ( ) ; |
public class CouchDBQuery { /** * Recursively populate entity .
* @ param m
* the m
* @ param client
* the client
* @ return the list */
@ Override protected List recursivelyPopulateEntities ( EntityMetadata m , Client client ) { } } | List < EnhanceEntity > ls = populateEntities ( m , client ) ; return setRelationEntities ( ls , client , m ) ; |
public class SRTServletRequest { /** * { @ inheritDoc } Returns the user Principal if authenticated , null otherwise .
* This logic is delegatd to the registered IWebAppSecurityCollaborator . */
public java . security . Principal getUserPrincipal ( ) { } } | if ( WCCustomProperties . CHECK_REQUEST_OBJECT_IN_USE ) { checkRequestObjectInUse ( ) ; } IWebAppSecurityCollaborator webAppSec = null ; if ( getDispatchContext ( ) != null && getDispatchContext ( ) . getWebApp ( ) != null ) { webAppSec = CollaboratorHelperImpl . getCurrentSecurityCollaborator ( getDispatchContext ( ) . getWebApp ( ) ) ; } else { webAppSec = CollaboratorHelperImpl . getCurrentSecurityCollaborator ( ) ; } if ( webAppSec != null ) { if ( TraceComponent . isAnyTracingEnabled ( ) && logger . isLoggable ( Level . FINE ) ) { // 306998.15
logger . logp ( Level . FINE , CLASS_NAME , "getUserPrincipal" , "calling getUserPrincipal on " + webAppSec . getClass ( ) . getName ( ) ) ; } return webAppSec . getUserPrincipal ( ) ; } else { if ( TraceComponent . isAnyTracingEnabled ( ) && logger . isLoggable ( Level . FINE ) ) { // 306998.15
logger . logp ( Level . FINE , CLASS_NAME , "getUserPrincipal" , "returning null" ) ; } // No IWebAppSecurityCollaborator means no security , so no Principal
return null ; } |
public class ColorPository { /** * Returns a random starting color from the specified color class . */
public ColorRecord getRandomStartingColor ( String className , Random rand ) { } } | // make sure the class exists
ClassRecord record = getClassRecord ( className ) ; return ( record == null ) ? null : record . randomStartingColor ( rand ) ; |
public class AbstractReaderModule { /** * Add the given file the wait list if it has not been parsed .
* @ param ref reference to absolute system path */
void addToWaitList ( final Reference ref ) { } } | final URI file = ref . filename ; assert file . isAbsolute ( ) && file . getFragment ( ) == null ; if ( doneList . contains ( file ) || waitList . contains ( ref ) || file . equals ( currentFile ) ) { return ; } waitList . add ( ref ) ; |
public class PixelMath { /** * Divide each element by a scalar value . Both input and output images can be the same instance .
* @ param input The input image . Not modified .
* @ param denominator What each element is divided by .
* @ param output The output image . Modified . */
public static void divide ( GrayU8 input , double denominator , GrayU8 output ) { } } | output . reshape ( input . width , input . height ) ; int columns = input . width ; if ( BoofConcurrency . USE_CONCURRENT ) { ImplPixelMath_MT . divideU_A ( input . data , input . startIndex , input . stride , denominator , output . data , output . startIndex , output . stride , input . height , columns ) ; } else { ImplPixelMath . divideU_A ( input . data , input . startIndex , input . stride , denominator , output . data , output . startIndex , output . stride , input . height , columns ) ; } |
public class TasksInner { /** * Create or update task .
* The tasks resource is a nested , proxy - only resource representing work performed by a DMS instance . The PUT method creates a new task or updates an existing one , although since tasks have no mutable custom properties , there is little reason to update an existing one .
* @ param groupName Name of the resource group
* @ param serviceName Name of the service
* @ param projectName Name of the project
* @ param taskName Name of the Task
* @ param parameters Information about the task
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the observable to the ProjectTaskInner object */
public Observable < ServiceResponse < ProjectTaskInner > > createOrUpdateWithServiceResponseAsync ( String groupName , String serviceName , String projectName , String taskName , ProjectTaskInner parameters ) { } } | if ( this . client . subscriptionId ( ) == null ) { throw new IllegalArgumentException ( "Parameter this.client.subscriptionId() is required and cannot be null." ) ; } if ( groupName == null ) { throw new IllegalArgumentException ( "Parameter groupName is required and cannot be null." ) ; } if ( serviceName == null ) { throw new IllegalArgumentException ( "Parameter serviceName is required and cannot be null." ) ; } if ( projectName == null ) { throw new IllegalArgumentException ( "Parameter projectName is required and cannot be null." ) ; } if ( taskName == null ) { throw new IllegalArgumentException ( "Parameter taskName is required and cannot be null." ) ; } if ( parameters == null ) { throw new IllegalArgumentException ( "Parameter parameters is required and cannot be null." ) ; } if ( this . client . apiVersion ( ) == null ) { throw new IllegalArgumentException ( "Parameter this.client.apiVersion() is required and cannot be null." ) ; } Validator . validate ( parameters ) ; return service . createOrUpdate ( this . client . subscriptionId ( ) , groupName , serviceName , projectName , taskName , parameters , this . client . apiVersion ( ) , this . client . acceptLanguage ( ) , this . client . userAgent ( ) ) . flatMap ( new Func1 < Response < ResponseBody > , Observable < ServiceResponse < ProjectTaskInner > > > ( ) { @ Override public Observable < ServiceResponse < ProjectTaskInner > > call ( Response < ResponseBody > response ) { try { ServiceResponse < ProjectTaskInner > clientResponse = createOrUpdateDelegate ( response ) ; return Observable . just ( clientResponse ) ; } catch ( Throwable t ) { return Observable . error ( t ) ; } } } ) ; |
public class ExpandoMetaClassCreationHandle { /** * / * ( non - Javadoc )
* @ see groovy . lang . MetaClassRegistry . MetaClassCreationHandle # create ( java . lang . Class , groovy . lang . MetaClassRegistry ) */
protected MetaClass createNormalMetaClass ( Class theClass , MetaClassRegistry registry ) { } } | if ( theClass != ExpandoMetaClass . class ) { return new ExpandoMetaClass ( theClass , true , true ) ; } else { return super . createNormalMetaClass ( theClass , registry ) ; } |
public class ConsoleWrapper { /** * Reads text from the input String , prompting with the given String .
* The values entered on the console are masked ( not echoed back to
* the console ) .
* @ param prompt
* @ return String read from input . */
public String readMaskedText ( String prompt ) { } } | if ( ! isInputStreamAvailable ( ) ) { stderr . println ( CommandUtils . getCMessage ( "error.inputConsoleNotAvailable" ) ) ; return null ; } try { char [ ] in = console . readPassword ( prompt ) ; if ( in == null ) { return null ; } else { return String . valueOf ( in ) ; } } catch ( IOError e ) { stderr . println ( "Exception while reading stdin: " + e . getMessage ( ) ) ; e . printStackTrace ( stderr ) ; } return null ; |
public class Comparison { /** * Another pid with region specification */
public final static float PID ( String seq1 , String seq2 , int start , int end ) { } } | int s1len = seq1 . length ( ) ; int s2len = seq2 . length ( ) ; int len = Math . min ( s1len , s2len ) ; if ( end < len ) { len = end ; } if ( len < start ) { start = len - 1 ; // we just use a single residue for the difference
} int bad = 0 ; char chr1 ; char chr2 ; for ( int i = start ; i < len ; i ++ ) { chr1 = seq1 . charAt ( i ) ; chr2 = seq2 . charAt ( i ) ; if ( 'a' <= chr1 && chr1 <= 'z' ) { // TO UPPERCASE ! ! !
// Faster than toUpperCase
chr1 -= caseShift ; } if ( 'a' <= chr2 && chr2 <= 'z' ) { // TO UPPERCASE ! ! !
// Faster than toUpperCase
chr2 -= caseShift ; } if ( chr1 != chr2 && ! isGap ( chr1 ) && ! isGap ( chr2 ) ) { bad ++ ; } } return ( ( float ) 100 * ( len - bad ) ) / len ; |
public class PatriciaTrie { /** * Test membership in this trie
* @ param key to test if exists
* @ return true if trie contains key */
@ Override public boolean containsKey ( Object key ) { } } | if ( key == null ) { throw new NullPointerException ( "Key can not be null" ) ; } if ( ! ( key instanceof String ) ) { throw new ClassCastException ( "Only String keys are supported -- got " + key . getClass ( ) ) ; } return get ( key ) != null ; |
public class RiakBeanSerializerModifier { /** * Checks if the property has any of the Riak annotations on it or the
* Jackson JsonProperty annotation .
* If a Riak annotation is present without the Jackson JsonProperty
* annotation , this will return false .
* If a property has been annotated with both the Jackson JsonProperty
* annotation and a Riak annotation , the Jackson annotation takes precedent
* and this will return true .
* @ param beanPropertyWriter a { @ link BeanPropertyWriter } to check for Riak *
* annotations
* @ return true if the property is not Riak annotated or is Jackson
* JsonProperty annotated , false otherwise */
private boolean keepProperty ( BeanPropertyWriter beanPropertyWriter ) { } } | if ( beanPropertyWriter . getAnnotation ( JsonProperty . class ) != null ) { return true ; } for ( Class < ? extends Annotation > annotation : RIAK_ANNOTATIONS ) { if ( beanPropertyWriter . getAnnotation ( annotation ) != null ) { return false ; } } return true ; |
public class Matchers { /** * Matches an AST node if its type is a { @ code void } type . */
public static < T extends Tree > Matcher < T > isVoidType ( ) { } } | return new Matcher < T > ( ) { @ Override public boolean matches ( T t , VisitorState state ) { Type type = getType ( t ) ; return type != null && state . getTypes ( ) . isSameType ( type , state . getSymtab ( ) . voidType ) ; } } ; |
public class DefaultServletHttpRequestHandler { /** * Process the actual dispatching .
* @ param request current HTTP servlet request
* @ param response current HTTP servlet response
* @ return true , if successful
* @ throws ServletException the servlet exception
* @ throws IOException if an input or output error occurs while the servlet is handling the HTTP request */
public boolean handle ( HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException { } } | if ( defaultServletName != null ) { RequestDispatcher rd = servletContext . getNamedDispatcher ( defaultServletName ) ; if ( rd == null ) { throw new IllegalStateException ( "A RequestDispatcher could not be located for the default servlet '" + defaultServletName + "'" ) ; } rd . forward ( request , response ) ; return true ; } else { return false ; } |
public class AWSElasticBeanstalkClient { /** * Describes the version of the platform .
* @ param describePlatformVersionRequest
* @ return Result of the DescribePlatformVersion operation returned by the service .
* @ throws InsufficientPrivilegesException
* The specified account does not have sufficient privileges for one or more AWS services .
* @ throws ElasticBeanstalkServiceException
* A generic service exception has occurred .
* @ sample AWSElasticBeanstalk . DescribePlatformVersion
* @ see < a href = " http : / / docs . aws . amazon . com / goto / WebAPI / elasticbeanstalk - 2010-12-01 / DescribePlatformVersion "
* target = " _ top " > AWS API Documentation < / a > */
@ Override public DescribePlatformVersionResult describePlatformVersion ( DescribePlatformVersionRequest request ) { } } | request = beforeClientExecution ( request ) ; return executeDescribePlatformVersion ( request ) ; |
public class OnChangeEvictingCache { /** * The transaction will be executed . While it is running , any semantic state change
* in the given resource will be ignored and the cache will not be cleared . */
public < Result , Param extends Resource > Result execWithoutCacheClear ( Param resource , IUnitOfWork < Result , Param > transaction ) throws WrappedException { } } | CacheAdapter cacheAdapter = getOrCreate ( resource ) ; try { cacheAdapter . ignoreNotifications ( ) ; return transaction . exec ( resource ) ; } catch ( RuntimeException e ) { throw e ; } catch ( Exception e ) { throw new WrappedException ( e ) ; } finally { cacheAdapter . listenToNotifications ( ) ; } |
public class ExtensionHelp { /** * Sets whether or not the help is enabled ( menu item , buttons and help for the components ) .
* The call to this method has no effect if the view is not initialised .
* @ param enabled { @ code true } if the help should be enabled , { @ code false } otherwise
* @ see # findHelpSetUrl ( ) */
private void setHelpEnabled ( boolean enabled ) { } } | if ( getView ( ) == null ) { return ; } JRootPane rootPane = getView ( ) . getMainFrame ( ) . getRootPane ( ) ; if ( enabled && findHelpSetUrl ( ) != null ) { createHelpBroker ( ) ; loadAddOnHelpSets ( ExtensionFactory . getAddOnLoader ( ) . getAddOnCollection ( ) . getInstalledAddOns ( ) ) ; getMenuHelpZapUserGuide ( ) . addActionListener ( showHelpActionListener ) ; getMenuHelpZapUserGuide ( ) . setToolTipText ( null ) ; getMenuHelpZapUserGuide ( ) . setEnabled ( true ) ; // Enable the top level F1 help key
hb . enableHelpKey ( rootPane , "zap.intro" , hs , "javax.help.SecondaryWindow" , null ) ; for ( Entry < JComponent , String > entry : componentsWithHelp . entrySet ( ) ) { hb . enableHelp ( entry . getKey ( ) , entry . getValue ( ) , hs ) ; } getHelpButton ( ) . setToolTipText ( Constant . messages . getString ( "help.button.tooltip" ) ) ; getHelpButton ( ) . setEnabled ( true ) ; } else { String toolTipNoHelp = Constant . messages . getString ( "help.error.nohelp" ) ; getMenuHelpZapUserGuide ( ) . setEnabled ( false ) ; getMenuHelpZapUserGuide ( ) . setToolTipText ( toolTipNoHelp ) ; getMenuHelpZapUserGuide ( ) . removeActionListener ( showHelpActionListener ) ; rootPane . unregisterKeyboardAction ( KeyStroke . getKeyStroke ( KeyEvent . VK_HELP , 0 ) ) ; rootPane . unregisterKeyboardAction ( KeyStroke . getKeyStroke ( KeyEvent . VK_F1 , 0 ) ) ; removeHelpProperties ( rootPane ) ; for ( JComponent component : componentsWithHelp . keySet ( ) ) { removeHelpProperties ( component ) ; } getHelpButton ( ) . setEnabled ( false ) ; getHelpButton ( ) . setToolTipText ( toolTipNoHelp ) ; hb = null ; hs = null ; showHelpActionListener = null ; } |
public class RowToXmlObjectMapper { /** * map a row from the ResultSet to an XmlObject instance
* @ return An XmlObject instance . */
public Object mapRowToReturnType ( ) { } } | Object resultObject = null ; if ( _columnCount == 1 ) { final int typeId = _tmf . getTypeId ( _returnTypeClass ) ; try { if ( typeId != TypeMappingsFactory . TYPE_UNKNOWN ) { return extractColumnValue ( 1 , typeId ) ; } else { // we still might want a single value ( i . e . java . util . Date )
Object val = extractColumnValue ( 1 , typeId ) ; if ( _returnTypeClass . isAssignableFrom ( val . getClass ( ) ) ) { return val ; } } } catch ( SQLException e ) { throw new ControlException ( e . getMessage ( ) , e ) ; } } if ( _setterMethods == null ) { try { getResultSetMappings ( ) ; } catch ( SQLException e ) { throw new ControlException ( e . getMessage ( ) , e ) ; } } resultObject = XmlObject . Factory . newInstance ( new XmlOptions ( ) . setDocumentType ( _schemaType ) ) ; for ( int i = 1 ; i < _setterMethods . length ; i ++ ) { Method setterMethod = _setterMethods [ i ] . getSetter ( ) ; Object resultValue = null ; try { resultValue = extractColumnValue ( i , _setterMethods [ i ] . getParameterType ( ) ) ; // if the setter is for an xmlbean enum type , convert the extracted resultset column
// value to the proper xmlbean enum type . All xmlbean enums are derived from the class
// StringEnumAbstractBase
if ( _setterMethods [ i ] . getParameterType ( ) == TypeMappingsFactory . TYPE_XMLBEAN_ENUM ) { Class parameterClass = _setterMethods [ i ] . getParameterClass ( ) ; Method m = parameterClass . getMethod ( "forString" , new Class [ ] { String . class } ) ; resultValue = m . invoke ( null , new Object [ ] { resultValue } ) ; } _args [ 0 ] = resultValue ; setterMethod . invoke ( resultObject , _args ) ; if ( _setterMethods [ i ] . getNilable ( ) != null ) { if ( _resultSet . wasNull ( ) ) { _setterMethods [ i ] . getNilable ( ) . invoke ( resultObject , ( Object [ ] ) null ) ; } } } catch ( SQLException se ) { throw new ControlException ( se . getMessage ( ) , se ) ; } catch ( IllegalArgumentException iae ) { try { ResultSetMetaData md = _resultSet . getMetaData ( ) ; throw new ControlException ( "The declared Java type for method " + setterMethod . getName ( ) + setterMethod . getParameterTypes ( ) [ 0 ] . toString ( ) + " is incompatible with the SQL format of column " + md . getColumnName ( i ) . toString ( ) + md . getColumnTypeName ( i ) . toString ( ) + " which returns objects of type " + resultValue . getClass ( ) . getName ( ) ) ; } catch ( SQLException e ) { throw new ControlException ( e . getMessage ( ) , e ) ; } } catch ( IllegalAccessException e ) { throw new ControlException ( "IllegalAccessException when trying to access method " + setterMethod . getName ( ) , e ) ; } catch ( NoSuchMethodException e ) { throw new ControlException ( "NoSuchMethodException when trying to map schema enum value using Enum.forString()." , e ) ; } catch ( InvocationTargetException e ) { throw new ControlException ( "IllegalInvocationException when trying to access method " + setterMethod . getName ( ) , e ) ; } } return resultObject ; |
public class StorageSnippets { /** * [ VARIABLE " my _ blob _ name " ] */
public Blob getBlobFromId ( String bucketName , String blobName ) { } } | // [ START getBlobFromId ]
BlobId blobId = BlobId . of ( bucketName , blobName ) ; Blob blob = storage . get ( blobId ) ; // [ END getBlobFromId ]
return blob ; |
public class ElementFactory { /** * Sets some Rectangle properties ( for a Cell , Table , . . . ) . */
private static void setRectangleProperties ( Rectangle rect , Properties attributes ) { } } | String value ; value = attributes . getProperty ( ElementTags . BORDERWIDTH ) ; if ( value != null ) { rect . setBorderWidth ( Float . parseFloat ( value + "f" ) ) ; } int border = 0 ; if ( Utilities . checkTrueOrFalse ( attributes , ElementTags . LEFT ) ) { border |= Rectangle . LEFT ; } if ( Utilities . checkTrueOrFalse ( attributes , ElementTags . RIGHT ) ) { border |= Rectangle . RIGHT ; } if ( Utilities . checkTrueOrFalse ( attributes , ElementTags . TOP ) ) { border |= Rectangle . TOP ; } if ( Utilities . checkTrueOrFalse ( attributes , ElementTags . BOTTOM ) ) { border |= Rectangle . BOTTOM ; } rect . setBorder ( border ) ; String r = attributes . getProperty ( ElementTags . RED ) ; String g = attributes . getProperty ( ElementTags . GREEN ) ; String b = attributes . getProperty ( ElementTags . BLUE ) ; if ( r != null || g != null || b != null ) { int red = 0 ; int green = 0 ; int blue = 0 ; if ( r != null ) red = Integer . parseInt ( r ) ; if ( g != null ) green = Integer . parseInt ( g ) ; if ( b != null ) blue = Integer . parseInt ( b ) ; rect . setBorderColor ( new Color ( red , green , blue ) ) ; } else { rect . setBorderColor ( Markup . decodeColor ( attributes . getProperty ( ElementTags . BORDERCOLOR ) ) ) ; } r = ( String ) attributes . remove ( ElementTags . BGRED ) ; g = ( String ) attributes . remove ( ElementTags . BGGREEN ) ; b = ( String ) attributes . remove ( ElementTags . BGBLUE ) ; value = attributes . getProperty ( ElementTags . BACKGROUNDCOLOR ) ; if ( r != null || g != null || b != null ) { int red = 0 ; int green = 0 ; int blue = 0 ; if ( r != null ) red = Integer . parseInt ( r ) ; if ( g != null ) green = Integer . parseInt ( g ) ; if ( b != null ) blue = Integer . parseInt ( b ) ; rect . setBackgroundColor ( new Color ( red , green , blue ) ) ; } else if ( value != null ) { rect . setBackgroundColor ( Markup . decodeColor ( value ) ) ; } else { value = attributes . getProperty ( ElementTags . GRAYFILL ) ; if ( value != null ) { rect . setGrayFill ( Float . parseFloat ( value + "f" ) ) ; } } |
public class ScanObjectH3 { /** * Reads the Hessian value as an object . */
void readString ( StringBuilder sb ) throws IOException { } } | while ( true ) { int ch = read ( ) ; int len ; switch ( ch ) { default : _peek = ch ; return ; case 0x00 : case 0x01 : case 0x02 : case 0x03 : case 0x04 : case 0x05 : case 0x06 : case 0x07 : case 0x08 : case 0x09 : case 0x0a : case 0x0b : case 0x0c : case 0x0d : case 0x0e : case 0x0f : case 0x10 : case 0x11 : case 0x12 : case 0x13 : case 0x14 : case 0x15 : case 0x16 : case 0x17 : case 0x18 : case 0x19 : case 0x1a : case 0x1b : case 0x1c : case 0x1d : case 0x1e : case 0x1f : len = ch - 0x00 ; readString ( sb , len ) ; return ; case 0x30 : case 0x31 : case 0x32 : case 0x33 : len = ( ( ch - 0x30 ) << 8 ) + read ( ) ; readString ( sb , len ) ; return ; case 'S' : len = readShort ( ) ; readString ( sb , len ) ; return ; case 'R' : len = readShort ( ) ; readString ( sb , len ) ; break ; } } |
public class MtasSpanQuery { /** * Initialize .
* @ param minimum the minimum
* @ param maximum the maximum */
private void initialize ( Integer minimum , Integer maximum ) { } } | minimumSpanWidth = minimum ; maximumSpanWidth = maximum ; spanWidth = ( minimum != null && maximum != null && minimum . equals ( maximum ) ) ? minimum : null ; singlePositionQuery = spanWidth != null && spanWidth . equals ( 1 ) ; |
public class FieldContent { /** * Get the value object . This call blocks the caller until
* a value is set ( ! = null ) .
* @ return the value */
synchronized Object getValue ( ) { } } | while ( value == NULL ) { try { wait ( ) ; } catch ( InterruptedException ex ) { throw new RuntimeException ( ex ) ; } } return value ; |
public class DenyAssignmentsInner { /** * Gets deny assignments for a resource group .
* @ param nextPageLink The NextLink from the previous successful call to List operation .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the observable to the PagedList & lt ; DenyAssignmentInner & gt ; object */
public Observable < Page < DenyAssignmentInner > > listByResourceGroupNextAsync ( final String nextPageLink ) { } } | return listByResourceGroupNextWithServiceResponseAsync ( nextPageLink ) . map ( new Func1 < ServiceResponse < Page < DenyAssignmentInner > > , Page < DenyAssignmentInner > > ( ) { @ Override public Page < DenyAssignmentInner > call ( ServiceResponse < Page < DenyAssignmentInner > > response ) { return response . body ( ) ; } } ) ; |
public class StorageWriter { /** * Cleanup files */
private void cleanup ( List < File > inputFiles ) { } } | for ( File f : inputFiles ) { if ( f . exists ( ) ) { if ( f . delete ( ) ) { LOGGER . log ( Level . INFO , "Deleted temporary file {0}" , f . getName ( ) ) ; } } } if ( tempFolder . delete ( ) ) { LOGGER . log ( Level . INFO , "Deleted temporary folder at {0}" , tempFolder . getAbsolutePath ( ) ) ; } |
public class RegionCommitmentClient { /** * Creates a commitment in the specified project using the data included in the request .
* < p > Sample code :
* < pre > < code >
* try ( RegionCommitmentClient regionCommitmentClient = RegionCommitmentClient . create ( ) ) {
* ProjectRegionName region = ProjectRegionName . of ( " [ PROJECT ] " , " [ REGION ] " ) ;
* Commitment commitmentResource = Commitment . newBuilder ( ) . build ( ) ;
* Operation response = regionCommitmentClient . insertRegionCommitment ( region . toString ( ) , commitmentResource ) ;
* < / code > < / pre >
* @ param region Name of the region for this request .
* @ param commitmentResource Represents a Commitment resource . Creating a Commitment resource
* means that you are purchasing a committed use contract with an explicit start and end time .
* You can create commitments based on vCPUs and memory usage and receive discounted rates .
* For full details , read Signing Up for Committed Use Discounts .
* < p > Committed use discounts are subject to Google Cloud Platform ' s Service Specific Terms .
* By purchasing a committed use discount , you agree to these terms . Committed use discounts
* will not renew , so you must purchase a new commitment to continue receiving discounts . ( = =
* resource _ for beta . commitments = = ) ( = = resource _ for v1 . commitments = = )
* @ throws com . google . api . gax . rpc . ApiException if the remote call fails */
@ BetaApi public final Operation insertRegionCommitment ( String region , Commitment commitmentResource ) { } } | InsertRegionCommitmentHttpRequest request = InsertRegionCommitmentHttpRequest . newBuilder ( ) . setRegion ( region ) . setCommitmentResource ( commitmentResource ) . build ( ) ; return insertRegionCommitment ( request ) ; |
public class ArrayMath { /** * Returns the sum of the portion of an array of numbers between
* < code > fromIndex < / code > , inclusive , and < code > toIndex < / code > , exclusive .
* Returns 0 if < code > fromIndex < / code > & gt ; = < code > toIndex < / code > . */
public static double sum ( double [ ] a , int fromIndex , int toIndex ) { } } | double result = 0.0 ; for ( int i = fromIndex ; i < toIndex ; i ++ ) { result += a [ i ] ; } return result ; |
public class LegacySpy { /** * Alias for { @ link # verifyBetween ( int , int , Threads , Query ) } with arguments 0 , { @ code allowedStatements } , { @ code threads } , { @ link Query # ANY }
* @ since 2.0 */
@ Deprecated public C verifyAtMost ( int allowedStatements , Threads threadMatcher ) throws WrongNumberOfQueriesError { } } | return verify ( SqlQueries . maxQueries ( allowedStatements ) . threads ( threadMatcher ) ) ; |
public class CompositeUtils { /** * Given a Factory Name return the generic type parameters of the factory ( The actual
* repository class , and its properties class ) .
* @ param beanFactory Spring Bean Factory
* @ param factoryName name of the factory
* @ return generic type params of the factory */
public static Type [ ] getEnvironmentRepositoryFactoryTypeParams ( ConfigurableListableBeanFactory beanFactory , String factoryName ) { } } | MethodMetadata methodMetadata = ( MethodMetadata ) beanFactory . getBeanDefinition ( factoryName ) . getSource ( ) ; Class < ? > factoryClass = null ; try { factoryClass = Class . forName ( methodMetadata . getReturnTypeName ( ) ) ; } catch ( ClassNotFoundException e ) { throw new IllegalStateException ( e ) ; } Optional < AnnotatedType > annotatedFactoryType = Arrays . stream ( factoryClass . getAnnotatedInterfaces ( ) ) . filter ( i -> { ParameterizedType parameterizedType = ( ParameterizedType ) i . getType ( ) ; return parameterizedType . getRawType ( ) . equals ( EnvironmentRepositoryFactory . class ) ; } ) . findFirst ( ) ; ParameterizedType factoryParameterizedType = ( ParameterizedType ) annotatedFactoryType . orElse ( factoryClass . getAnnotatedSuperclass ( ) ) . getType ( ) ; return factoryParameterizedType . getActualTypeArguments ( ) ; |
public class PTSaxton2006 { /** * Equation 22 for calculating Saturated conductivity ( bulk soil ) , mm / h
* @ param slsnd Sand weight percentage by layer ( [ 0,100 ] % )
* @ param slcly Clay weight percentage by layer ( [ 0,100 ] % )
* @ param omPct Organic matter weight percentage by layer ( [ 0,100 ] % ) , ( =
* SLOC * 1.72)
* @ param slcf Grave weight fraction by layer ( g / g ) */
public static String calcSatBulk ( String slsnd , String slcly , String omPct , String slcf ) { } } | String satMatric = calcSatMatric ( slsnd , slcly , omPct ) ; String slbdm = calcNormalDensity ( slsnd , slcly , omPct ) ; String alpha = divide ( slbdm , "2.65" ) ; String ratio = divide ( substract ( "1" , slcf ) , substract ( "1" , slcf , product ( "-1.5" , slcf , alpha ) ) ) ; String ret = product ( satMatric , ratio ) ; LOG . debug ( "Calculate result for Saturated conductivity (bulk soil), mm/h is {}" , ret ) ; return ret ; |
public class CacheInterceptor { /** * Returns a new source that writes bytes to { @ code cacheRequest } as they are read by the source
* consumer . This is careful to discard bytes left over when the stream is closed ; otherwise we
* may never exhaust the source stream and therefore not complete the cached response . */
private Response cacheWritingResponse ( final CacheRequest cacheRequest , Response response ) throws IOException { } } | // Some apps return a null body ; for compatibility we treat that like a null cache request .
if ( cacheRequest == null ) return response ; Sink cacheBodyUnbuffered = cacheRequest . body ( ) ; if ( cacheBodyUnbuffered == null ) return response ; final BufferedSource source = response . body ( ) . source ( ) ; final BufferedSink cacheBody = Okio . buffer ( cacheBodyUnbuffered ) ; Source cacheWritingSource = new Source ( ) { boolean cacheRequestClosed ; @ Override public long read ( Buffer sink , long byteCount ) throws IOException { long bytesRead ; try { bytesRead = source . read ( sink , byteCount ) ; } catch ( IOException e ) { if ( ! cacheRequestClosed ) { cacheRequestClosed = true ; cacheRequest . abort ( ) ; // Failed to write a complete cache response .
} throw e ; } if ( bytesRead == - 1 ) { if ( ! cacheRequestClosed ) { cacheRequestClosed = true ; cacheBody . close ( ) ; // The cache response is complete !
} return - 1 ; } sink . copyTo ( cacheBody . buffer ( ) , sink . size ( ) - bytesRead , bytesRead ) ; cacheBody . emitCompleteSegments ( ) ; return bytesRead ; } @ Override public Timeout timeout ( ) { return source . timeout ( ) ; } @ Override public void close ( ) throws IOException { if ( ! cacheRequestClosed && ! discard ( this , ExchangeCodec . DISCARD_STREAM_TIMEOUT_MILLIS , MILLISECONDS ) ) { cacheRequestClosed = true ; cacheRequest . abort ( ) ; } source . close ( ) ; } } ; String contentType = response . header ( "Content-Type" ) ; long contentLength = response . body ( ) . contentLength ( ) ; return response . newBuilder ( ) . body ( new RealResponseBody ( contentType , contentLength , Okio . buffer ( cacheWritingSource ) ) ) . build ( ) ; |
public class CouchbaseConnection { /** * Inserts a { @ link JsonDocument } if it does not exist already .
* @ param documentId the unique ID of the document
* @ param json the JSON String representing the document to store
* @ return the newly created { @ link JsonDocument }
* @ see Bucket # insert ( Document ) */
public JsonDocument insert ( String documentId , String json ) { } } | return this . bucket . insert ( JsonDocument . create ( documentId , JsonObject . fromJson ( json ) ) ) ; |
public class ForkJoinTask { /** * Waits if necessary for at most the given time for the computation
* to complete , and then retrieves its result , if available .
* @ param timeout the maximum time to wait
* @ param unit the time unit of the timeout argument
* @ return the computed result
* @ throws CancellationException if the computation was cancelled
* @ throws ExecutionException if the computation threw an
* exception
* @ throws InterruptedException if the current thread is not a
* member of a ForkJoinPool and was interrupted while waiting
* @ throws TimeoutException if the wait timed out */
public final V get ( long timeout , TimeUnit unit ) throws InterruptedException , ExecutionException , TimeoutException { } } | if ( Thread . interrupted ( ) ) throw new InterruptedException ( ) ; // Messy in part because we measure in nanosecs , but wait in millisecs
int s ; long ns , ms ; if ( ( s = status ) >= 0 && ( ns = unit . toNanos ( timeout ) ) > 0L ) { long deadline = System . nanoTime ( ) + ns ; ForkJoinPool p = null ; ForkJoinPool . WorkQueue w = null ; Thread t = Thread . currentThread ( ) ; if ( t instanceof ForkJoinWorkerThread ) { ForkJoinWorkerThread wt = ( ForkJoinWorkerThread ) t ; p = wt . pool ; w = wt . workQueue ; s = p . helpJoinOnce ( w , this ) ; // no retries on failure
} boolean canBlock = false ; boolean interrupted = false ; try { while ( ( s = status ) >= 0 ) { if ( w != null && w . runState < 0 ) cancelIgnoringExceptions ( this ) ; else if ( ! canBlock ) { if ( p == null || p . tryCompensate ( this , null ) ) canBlock = true ; } else { if ( ( ms = TimeUnit . NANOSECONDS . toMillis ( ns ) ) > 0L && U . compareAndSwapInt ( this , STATUS , s , s | SIGNAL ) ) { synchronized ( this ) { if ( status >= 0 ) { try { wait ( ms ) ; } catch ( InterruptedException ie ) { if ( p == null ) interrupted = true ; } } else notifyAll ( ) ; } } if ( ( s = status ) < 0 || interrupted || ( ns = deadline - System . nanoTime ( ) ) <= 0L ) break ; } } } finally { if ( p != null && canBlock ) p . incrementActiveCount ( ) ; } if ( interrupted ) throw new InterruptedException ( ) ; } if ( ( s &= DONE_MASK ) != NORMAL ) { Throwable ex ; if ( s == CANCELLED ) throw new CancellationException ( ) ; if ( s != EXCEPTIONAL ) throw new TimeoutException ( ) ; if ( ( ex = getThrowableException ( ) ) != null ) throw new ExecutionException ( ex ) ; } return getRawResult ( ) ; |
public class FormulaStringRepresentation { /** * Returns a bracketed string version of a given formula .
* @ param formula the formula
* @ return { @ code " ( " + formula . toString ( ) + " ) " } */
protected String bracket ( final Formula formula ) { } } | return String . format ( "%s%s%s" , this . lbr ( ) , this . toString ( formula ) , this . rbr ( ) ) ; |
public class Client { /** * Proxy creator function .
* @ param serviceClazz service interface .
* @ param errorMapper error mapper .
* @ param < T > type of service interface .
* @ return proxied service object . */
public < T > T forService ( Class < T > serviceClazz , ClientErrorMapper errorMapper ) { } } | // noinspection unchecked
return ( T ) proxyMap . computeIfAbsent ( serviceClazz , ( clazz ) -> { Map < Method , MethodInfo > methods = Reflect . methodsInfo ( serviceClazz ) ; return Proxy . newProxyInstance ( serviceClazz . getClassLoader ( ) , new Class [ ] { serviceClazz } , new RemoteInvocationHandler ( transport , methods , codec , errorMapper ) ) ; |
public class IO { /** * Zip a list of sobject into a single sobject .
* @ param objects
* the sobjects to be zipped .
* @ return an sobject that is a zip package of ` objects ` . */
public static ISObject zip ( ISObject ... objects ) { } } | ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; ZipOutputStream zos = new ZipOutputStream ( baos ) ; try { for ( ISObject obj : objects ) { ZipEntry entry = new ZipEntry ( obj . getAttribute ( SObject . ATTR_FILE_NAME ) ) ; InputStream is = obj . asInputStream ( ) ; zos . putNextEntry ( entry ) ; copy ( is , zos , false ) ; zos . closeEntry ( ) ; } } catch ( IOException e ) { throw E . ioException ( e ) ; } finally { close ( zos ) ; } return SObject . of ( Codec . encodeUrl ( S . random ( ) ) , baos . toByteArray ( ) ) ; |
public class SparkComputationGraph { /** * Perform evaluation on serialized MultiDataSet objects on disk , ( potentially in any format ) , that are loaded using an { @ link MultiDataSetLoader } . < br >
* Uses the default number of workers ( model replicas per JVM ) of { @ link # DEFAULT _ EVAL _ WORKERS } with the default
* minibatch size of { @ link # DEFAULT _ EVAL _ SCORE _ BATCH _ SIZE }
* @ param data List of paths to the data ( that can be loaded as / converted to DataSets )
* @ param loader Used to load MultiDataSets from their paths
* @ param emptyEvaluations Evaluations to perform
* @ return Evaluation */
public IEvaluation [ ] doEvaluation ( JavaRDD < String > data , MultiDataSetLoader loader , IEvaluation ... emptyEvaluations ) { } } | return doEvaluation ( data , DEFAULT_EVAL_WORKERS , DEFAULT_EVAL_SCORE_BATCH_SIZE , null , loader , emptyEvaluations ) ; |
public class FFMQConnectionFactory { /** * ( non - Javadoc )
* @ see javax . jms . ConnectionFactory # createConnection ( ) */
@ Override public final Connection createConnection ( ) throws JMSException { } } | String username = getStringProperty ( Context . SECURITY_PRINCIPAL , null ) ; String password = getStringProperty ( Context . SECURITY_CREDENTIALS , null ) ; return createConnection ( username , password ) ; |
public class Util { /** * Returns the index of the first character in { @ code input } that is either a control character
* ( like { @ code \ u0000 or \ n } ) or a non - ASCII character . Returns - 1 if { @ code input } has no such
* characters . */
public static int indexOfControlOrNonAscii ( String input ) { } } | for ( int i = 0 , length = input . length ( ) ; i < length ; i ++ ) { char c = input . charAt ( i ) ; if ( c <= '\u001f' || c >= '\u007f' ) { return i ; } } return - 1 ; |
public class FilterJoinVisitor { /** * Removes all the filter join leaf nodes that were converted . Returns true if at least one node
* has been removed . */
private boolean removeConvertedNodes ( AbstractNode node ) { } } | boolean nodeRemoved = false ; Iterator < AbstractNode > it = node . getChildren ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { FilterJoinNode child = ( FilterJoinNode ) it . next ( ) ; if ( child . getState ( ) . equals ( FilterJoinNode . State . CONVERTED ) ) { it . remove ( ) ; nodeRemoved |= true ; } else { nodeRemoved |= this . removeConvertedNodes ( child ) ? true : false ; } } return nodeRemoved ; |
public class SigningProfileMarshaller { /** * Marshall the given parameter object . */
public void marshall ( SigningProfile signingProfile , ProtocolMarshaller protocolMarshaller ) { } } | if ( signingProfile == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( signingProfile . getProfileName ( ) , PROFILENAME_BINDING ) ; protocolMarshaller . marshall ( signingProfile . getSigningMaterial ( ) , SIGNINGMATERIAL_BINDING ) ; protocolMarshaller . marshall ( signingProfile . getPlatformId ( ) , PLATFORMID_BINDING ) ; protocolMarshaller . marshall ( signingProfile . getSigningParameters ( ) , SIGNINGPARAMETERS_BINDING ) ; protocolMarshaller . marshall ( signingProfile . getStatus ( ) , STATUS_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class WindowUtils { /** * Tries to make the given { @ link Window } non - opqaue ( transparent ) across
* platforms and JREs . This method is not guaranteed to succeed , and will
* fail silently if the given { @ code Window } cannot be made non - opaque .
* < p > This method is useful , for example , when creating a HUD style window
* that is semi - transparent , and thus doesn ' t want the window background to
* be drawn . < / p >
* @ param window the { @ code Window } to make non - opaque . */
public static void makeWindowNonOpaque ( Window window ) { } } | if ( PlatformUtils . isJava6 ( ) ) { // on non - mac platforms , try to use the facilities of Java 6 update 10.
if ( ! PlatformUtils . isMac ( ) ) { quietlyTryToMakeWindowNonOqaque ( window ) ; } else { window . setBackground ( UIManager . getColor ( "seaGlassTransparent" ) ) ; } } |
public class ObjectFactory { /** * Create an instance of { @ link JAXBElement } { @ code < } { @ link ElementaryFunctionsType } { @ code > } } */
@ XmlElementDecl ( namespace = "http://www.w3.org/1998/Math/MathML" , name = "arcsin" ) public JAXBElement < ElementaryFunctionsType > createArcsin ( ElementaryFunctionsType value ) { } } | return new JAXBElement < ElementaryFunctionsType > ( _Arcsin_QNAME , ElementaryFunctionsType . class , null , value ) ; |
public class Time { /** * Generate Time Reports for a Specific Team / Comapny / Agency
* @ param company Company ID
* @ param team ( Optional ) Team ID
* @ param agency ( Optional ) Agency ID
* @ param params ( Optional ) Parameters
* @ param hideFinDetails ( Optional ) Hides all financial details
* @ throwsJSONException If error occurred
* @ return { @ link JSONObject } */
private JSONObject _getByType ( String company , String team , String agency , HashMap < String , String > params , Boolean hideFinDetails ) throws JSONException { } } | String url = "" ; if ( team != null ) { url = "/teams/" + team ; if ( hideFinDetails ) { url = url + "/hours" ; } } else if ( agency != null ) { url = "/agencies/" + agency ; } return oClient . get ( "/timereports/v1/companies/" + company + url , params ) ; |
public class DateUtils { /** * 获得给定时间的第二天零时的日期对象 例如 : 若给定时间为 ( 2004-08-01 11:30:58 ) , 将获得 ( 2004-08-02
* 00:00:00 ) 的日期对象 若给定时间为 ( 2004-08-31 11:30:58 ) , 将获得 ( 2004-09-01 00:00:00 ) 的日期对象
* @ param dt Date 给定的java . util . Date对象
* @ return Date java . util . Date对象 */
public static Date getNextDay ( Date dt ) { } } | if ( dt == null ) { return dt ; } Calendar cal = new GregorianCalendar ( ) ; cal . setTime ( dt ) ; // return new GregorianCalendar ( cal . get ( Calendar . YEAR ) , cal
// . get ( Calendar . MONTH ) , cal . get ( Calendar . DAY _ OF _ MONTH ) + 1 ) / / 这个方法会出现
// 32 号的情况
// . getTime ( ) ;
// modified by zhuqian 2009-03-25
cal . add ( Calendar . DAY_OF_YEAR , 1 ) ; return cal . getTime ( ) ; |
public class TimerSupport { /** * return tick observable for each user , user should handle the observable with cell ' s lifecycle
* @ param interval timer interval , in TimeUnit . SECOND
* @ param total total event count
* @ param intermediate true , get event immediately
* @ return
* @ since 3.0.0 */
public Observable < Long > getTickObservable ( int interval , int total , boolean intermediate ) { } } | return Observable . intervalRange ( 0 , total , intermediate ? 0 : interval , interval , TimeUnit . SECONDS ) ; |
public class SplitPaneLayout { /** * Convenience for calling own measure method . */
private void remeasure ( ) { } } | // TODO : Performance : Guard against calling too often , can it be done without requestLayout ?
forceLayout ( ) ; measure ( MeasureSpec . makeMeasureSpec ( getMeasuredWidth ( ) , MeasureSpec . EXACTLY ) , MeasureSpec . makeMeasureSpec ( getMeasuredHeight ( ) , MeasureSpec . EXACTLY ) ) ; requestLayout ( ) ; |
public class LicensesInterface { /** * Sets the license for a photo .
* This method requires authentication with ' write ' permission .
* @ param photoId
* The photo to update the license for .
* @ param licenseId
* The license to apply , or 0 ( zero ) to remove the current license .
* @ throws FlickrException */
public void setLicense ( String photoId , int licenseId ) throws FlickrException { } } | Map < String , Object > parameters = new HashMap < String , Object > ( ) ; parameters . put ( "method" , METHOD_SET_LICENSE ) ; parameters . put ( "photo_id" , photoId ) ; parameters . put ( "license_id" , Integer . toString ( licenseId ) ) ; // Note : This method requires an HTTP POST request .
Response response = transportAPI . post ( transportAPI . getPath ( ) , parameters , apiKey , sharedSecret ) ; if ( response . isError ( ) ) { throw new FlickrException ( response . getErrorCode ( ) , response . getErrorMessage ( ) ) ; } // This method has no specific response - It returns an empty sucess response if it completes without error . |
public class TaskManagerService { /** * Check the given task to see if we should and can execute it . */
private void checkTaskForExecution ( ApplicationDefinition appDef , Task task ) { } } | Tenant tenant = Tenant . getTenant ( appDef ) ; m_logger . debug ( "Checking task '{}' in tenant '{}'" , task . getTaskID ( ) , tenant ) ; synchronized ( m_executeLock ) { Iterator < DColumn > colIter = DBService . instance ( tenant ) . getAllColumns ( TaskManagerService . TASKS_STORE_NAME , task . getTaskID ( ) ) . iterator ( ) ; TaskRecord taskRecord = null ; if ( ! colIter . hasNext ( ) ) { taskRecord = storeTaskRecord ( tenant , task ) ; } else { taskRecord = buildTaskRecord ( task . getTaskID ( ) , colIter ) ; } if ( taskShouldExecute ( task , taskRecord ) && canHandleMoreTasks ( ) ) { attemptToExecuteTask ( appDef , task , taskRecord ) ; } } |
public class ListGlobalTablesResult { /** * List of global table names .
* @ param globalTables
* List of global table names . */
public void setGlobalTables ( java . util . Collection < GlobalTable > globalTables ) { } } | if ( globalTables == null ) { this . globalTables = null ; return ; } this . globalTables = new java . util . ArrayList < GlobalTable > ( globalTables ) ; |
public class CrudAPICodeGen { /** * public DeleteWithOptions delete ( . . . ) {
* validate keys not null
* return DeleteWithOptions ( rte , clazz , meta , keys ) ; */
private static MethodSpec buildDeleteByKeys ( EntityMetaSignature signature ) { } } | ParameterizedTypeName returnType = genericType ( DELETE_WITH_OPTIONS , signature . entityRawClass ) ; final MethodSpec . Builder builder = MethodSpec . methodBuilder ( "deleteById" ) . addJavadoc ( "Delete an entity using its complete primary key" ) . addModifiers ( Modifier . PUBLIC ) . addStatement ( "$T keys = new $T<>()" , LIST_OBJECT , ARRAY_LIST ) . addStatement ( "$T encodedKeys = new $T<>()" , LIST_OBJECT , ARRAY_LIST ) ; signature . fieldMetaSignatures . stream ( ) . filter ( x -> x . context . columnType == PARTITION ) . map ( x -> Tuple3 . of ( x . context . fieldName , x . sourceType , ( PartitionKeyInfo ) x . context . columnInfo ) ) . sorted ( PARTITION_KEY_SORTER ) . forEach ( tuple -> builder . addJavadoc ( "@param $L partition key '$L'" , tuple . _1 ( ) , tuple . _1 ( ) ) . addParameter ( tuple . _2 ( ) , tuple . _1 ( ) , Modifier . FINAL ) . addStatement ( "$T.validateNotNull($L, $S, $S)" , VALIDATOR , tuple . _1 ( ) , "Partition key '%s' should not be null" , tuple . _1 ( ) ) . addStatement ( "keys.add($L)" , tuple . _1 ( ) ) . addStatement ( "encodedKeys.add($L.$L.encodeFromJava($N, cassandraOptions))" , signature . className + META_SUFFIX , tuple . _1 ( ) , tuple . _1 ( ) ) ) ; signature . fieldMetaSignatures . stream ( ) . filter ( x -> x . context . columnType == CLUSTERING ) . map ( x -> Tuple3 . of ( x . context . fieldName , x . sourceType , ( ClusteringColumnInfo ) x . context . columnInfo ) ) . sorted ( CLUSTERING_COLUMN_SORTER ) . forEach ( tuple -> builder . addJavadoc ( "@param $L clustering column '$L'" , tuple . _1 ( ) , tuple . _1 ( ) ) . addParameter ( tuple . _2 ( ) , tuple . _1 ( ) , Modifier . FINAL ) . addStatement ( "$T.validateNotNull($L, $S, $S)" , VALIDATOR , tuple . _1 ( ) , "Partition key '%s' should not be null" , tuple . _1 ( ) ) . addStatement ( "keys.add($L)" , tuple . _1 ( ) ) . addStatement ( "encodedKeys.add($L.$L.encodeFromJava($N, cassandraOptions))" , signature . className + META_SUFFIX , tuple . _1 ( ) , tuple . _1 ( ) ) ) ; builder . addJavadoc ( "@return DeleteWithOptions<$T>" , signature . entityRawClass ) ; builder . addStatement ( "final Object[] partitionKeysValues = keys.toArray()" ) . addStatement ( "final Object[] encodedPartitionKeyValues = encodedKeys.toArray()" ) . addStatement ( "return new $T(entityClass, meta, rte, partitionKeysValues, encodedPartitionKeyValues, $T.empty(), cassandraOptions)" , returnType , OPTIONAL ) . returns ( returnType ) ; return builder . build ( ) ; |
public class CmsToolBar { /** * Updates the button visibility according o the given widow width . < p >
* @ param width the window width */
protected void updateButtonVisibility ( int width ) { } } | if ( ! m_buttonsFolded && ( m_foldingThreshhold > width ) ) { foldButtons ( ) ; } else if ( m_buttonsFolded && ( width > m_foldingThreshhold ) ) { unfoldButtons ( ) ; } |
public class FlatFileWriter { /** * Writes a flat file block to an output stream . Does not write
* anything if the line is empty . */
protected void writeBlock ( Writer writer , String firstLineHeader , String header , String block ) throws IOException { } } | writeBlock ( writer , firstLineHeader , header , block , wrapType , wrapChar , header . length ( ) ) ; |
public class Metadata { /** * Remove all values for the given key without returning them . This is a minor performance
* optimization if you do not need the previous values . */
@ ExperimentalApi ( "https://github.com/grpc/grpc-java/issues/4691" ) public < T > void discardAll ( Key < T > key ) { } } | if ( isEmpty ( ) ) { return ; } int writeIdx = 0 ; int readIdx = 0 ; for ( ; readIdx < size ; readIdx ++ ) { if ( bytesEqual ( key . asciiName ( ) , name ( readIdx ) ) ) { continue ; } name ( writeIdx , name ( readIdx ) ) ; value ( writeIdx , value ( readIdx ) ) ; writeIdx ++ ; } int newSize = writeIdx ; // Multiply by two since namesAndValues is interleaved .
Arrays . fill ( namesAndValues , writeIdx * 2 , len ( ) , null ) ; size = newSize ; |
public class JpaHelper { /** * build a single String from a List of objects with a given separator and prefix
* @ param values
* @ param separator
* @ param prefix
* @ return */
public static String toSeparatedString ( List < ? > values , String separator , String prefix ) { } } | StringBuilder result = new StringBuilder ( ) ; for ( Object each : values ) { if ( each == null ) { continue ; } if ( result . length ( ) > 0 ) { result . append ( separator ) ; } if ( prefix != null ) { result . append ( String . valueOf ( each ) ) ; } else { result . append ( prefix + String . valueOf ( each ) ) ; } } return result . toString ( ) ; |
public class HtmlWriter { /** * Returns an HtmlTree for the SCRIPT tag .
* @ return an HtmlTree for the SCRIPT tag */
protected HtmlTree getWinTitleScript ( ) { } } | HtmlTree script = HtmlTree . SCRIPT ( ) ; if ( winTitle != null && winTitle . length ( ) > 0 ) { String scriptCode = "<!--" + DocletConstants . NL + " try {" + DocletConstants . NL + " if (location.href.indexOf('is-external=true') == -1) {" + DocletConstants . NL + " parent.document.title=\"" + escapeJavaScriptChars ( winTitle ) + "\";" + DocletConstants . NL + " }" + DocletConstants . NL + " }" + DocletConstants . NL + " catch(err) {" + DocletConstants . NL + " }" + DocletConstants . NL + "//-->" + DocletConstants . NL ; RawHtml scriptContent = new RawHtml ( scriptCode ) ; script . addContent ( scriptContent ) ; } return script ; |
public class DescribeEventDetailsRequest { /** * A list of event ARNs ( unique identifiers ) . For example :
* < code > " arn : aws : health : us - east - 1 : : event / EC2 / EC2 _ INSTANCE _ RETIREMENT _ SCHEDULED / EC2 _ INSTANCE _ RETIREMENT _ SCHEDULED _ ABC123 - CDE456 " , " arn : aws : health : us - west - 1 : : event / EBS / AWS _ EBS _ LOST _ VOLUME / AWS _ EBS _ LOST _ VOLUME _ CHI789 _ JKL101 " < / code >
* < b > NOTE : < / b > This method appends the values to the existing list ( if any ) . Use
* { @ link # setEventArns ( java . util . Collection ) } or { @ link # withEventArns ( java . util . Collection ) } if you want to
* override the existing values .
* @ param eventArns
* A list of event ARNs ( unique identifiers ) . For example :
* < code > " arn : aws : health : us - east - 1 : : event / EC2 / EC2 _ INSTANCE _ RETIREMENT _ SCHEDULED / EC2 _ INSTANCE _ RETIREMENT _ SCHEDULED _ ABC123 - CDE456 " , " arn : aws : health : us - west - 1 : : event / EBS / AWS _ EBS _ LOST _ VOLUME / AWS _ EBS _ LOST _ VOLUME _ CHI789 _ JKL101 " < / code >
* @ return Returns a reference to this object so that method calls can be chained together . */
public DescribeEventDetailsRequest withEventArns ( String ... eventArns ) { } } | if ( this . eventArns == null ) { setEventArns ( new java . util . ArrayList < String > ( eventArns . length ) ) ; } for ( String ele : eventArns ) { this . eventArns . add ( ele ) ; } return this ; |
public class FindOps { /** * Constructs a { @ code TerminalOp } for streams of objects .
* @ param < T > the type of elements of the stream
* @ param mustFindFirst whether the { @ code TerminalOp } must produce the
* first element in the encounter order
* @ return a { @ code TerminalOp } implementing the find operation */
public static < T > TerminalOp < T , Optional < T > > makeRef ( boolean mustFindFirst ) { } } | return new FindOp < > ( mustFindFirst , StreamShape . REFERENCE , Optional . empty ( ) , Optional :: isPresent , FindSink . OfRef :: new ) ; |
public class CPFriendlyURLEntryUtil { /** * Returns the last cp friendly url entry in the ordered set where groupId = & # 63 ; and classNameId = & # 63 ; and classPK = & # 63 ; .
* @ param groupId the group ID
* @ param classNameId the class name ID
* @ param classPK the class pk
* @ param orderByComparator the comparator to order the set by ( optionally < code > null < / code > )
* @ return the last matching cp friendly url entry , or < code > null < / code > if a matching cp friendly url entry could not be found */
public static CPFriendlyURLEntry fetchByG_C_C_Last ( long groupId , long classNameId , long classPK , OrderByComparator < CPFriendlyURLEntry > orderByComparator ) { } } | return getPersistence ( ) . fetchByG_C_C_Last ( groupId , classNameId , classPK , orderByComparator ) ; |
public class Expressions { /** * Create a new Template expression
* @ param cl type of expression
* @ param template template
* @ param args template parameters
* @ return template expression */
public static < T extends Enum < T > > EnumTemplate < T > enumTemplate ( Class < ? extends T > cl , String template , Object ... args ) { } } | return enumTemplate ( cl , createTemplate ( template ) , ImmutableList . copyOf ( args ) ) ; |
public class XFactoryNaiveImpl { /** * / * ( non - Javadoc )
* @ see org . deckfour . xes . model . factory . XModelFactory # createAttributeContinuous ( java . lang . String , double , org . deckfour . xes . extension . XExtension ) */
public XAttributeContinuous createAttributeContinuous ( String key , double value , XExtension extension ) { } } | return new XAttributeContinuousImpl ( intern ( key ) , value , extension ) ; |
public class DomainsInner { /** * Get ownership identifier for domain .
* Get ownership identifier for domain .
* @ param resourceGroupName Name of the resource group to which the resource belongs .
* @ param domainName Name of domain .
* @ param name Name of identifier .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ throws DefaultErrorResponseException thrown if the request is rejected by server
* @ throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @ return the DomainOwnershipIdentifierInner object if successful . */
public DomainOwnershipIdentifierInner getOwnershipIdentifier ( String resourceGroupName , String domainName , String name ) { } } | return getOwnershipIdentifierWithServiceResponseAsync ( resourceGroupName , domainName , name ) . toBlocking ( ) . single ( ) . body ( ) ; |
public class RedmineManager { /** * Generic method to search for issues .
* @ param pParameters the http parameters key / value pairs to append to the rest api request
* @ return empty list if not issues with this summary field exist , never NULL
* @ throws RedmineAuthenticationException invalid or no API access key is used with the server , which
* requires authorization . Check the constructor arguments .
* @ throws NotFoundException
* @ throws RedmineException */
public List < Issue > getIssues ( Map < String , String > pParameters ) throws RedmineException { } } | Set < NameValuePair > params = new HashSet < NameValuePair > ( ) ; for ( final Entry < String , String > param : pParameters . entrySet ( ) ) { params . add ( new BasicNameValuePair ( param . getKey ( ) , param . getValue ( ) ) ) ; } return transport . getObjectsList ( Issue . class , params ) ; |
public class DateTimeFormatter { /** * Fully parses the text producing an object of the specified type .
* Most applications should use this method for parsing .
* It parses the entire text to produce the required date - time .
* The query is typically a method reference to a { @ code from ( TemporalAccessor ) } method .
* For example :
* < pre >
* LocalDateTime dt = parser . parse ( str , LocalDateTime : : from ) ;
* < / pre >
* If the parse completes without reading the entire length of the text ,
* or a problem occurs during parsing or merging , then an exception is thrown .
* @ param < T > the type of the parsed date - time
* @ param text the text to parse , not null
* @ param query the query defining the type to parse to , not null
* @ return the parsed date - time , not null
* @ throws DateTimeParseException if unable to parse the requested result */
public < T > T parse ( CharSequence text , TemporalQuery < T > query ) { } } | Objects . requireNonNull ( text , "text" ) ; Objects . requireNonNull ( query , "query" ) ; try { return parseResolved0 ( text , null ) . query ( query ) ; } catch ( DateTimeParseException ex ) { throw ex ; } catch ( RuntimeException ex ) { throw createError ( text , ex ) ; } |
public class Score { /** * Run after the doAll scoring to convert the MetricsBuilder to a ModelMetrics */
private ModelMetrics makeModelMetrics ( SharedTreeModel model , Frame fr , Frame adaptedFr , Frame preds ) { } } | ModelMetrics mm ; if ( model . _output . nclasses ( ) == 2 && _computeGainsLift ) { assert preds != null : "Predictions were pre-created" ; mm = _mb . makeModelMetrics ( model , fr , adaptedFr , preds ) ; } else { boolean calculatePreds = preds == null && model . _parms . _distribution == DistributionFamily . huber ; // FIXME : PUBDEV - 4992 we should avoid doing full scoring !
if ( calculatePreds ) { Log . warn ( "Going to calculate predictions from scratch. This can be expensive for large models! See PUBDEV-4992" ) ; preds = model . score ( fr ) ; } mm = _mb . makeModelMetrics ( model , fr , null , preds ) ; if ( calculatePreds && ( preds != null ) ) preds . remove ( ) ; } return mm ; |
public class Grid { /** * / * package */
void appendFailedModelParameters ( Object [ ] rawParams , Exception e ) { } } | assert rawParams != null : "Raw parameters should be always != null !" ; appendFailedModelParameters ( null , ArrayUtils . toString ( rawParams ) , e . getMessage ( ) , StringUtils . toString ( e ) ) ; |
public class Symm { /** * Helper function for String API of " Encode "
* use " getBytes " with appropriate char encoding , etc .
* @ param str
* @ return
* @ throws IOException */
public String encode ( String str ) throws IOException { } } | byte [ ] array ; try { array = str . getBytes ( encoding ) ; } catch ( IOException e ) { array = str . getBytes ( ) ; // take default
} // Calculate expected size to avoid any buffer expansion copies within the ByteArrayOutput code
ByteArrayOutputStream baos = new ByteArrayOutputStream ( ( int ) ( array . length * 1.363 ) ) ; // account for 4 bytes for 3 and a byte or two more
encode ( new ByteArrayInputStream ( array ) , baos ) ; return baos . toString ( encoding ) ; |
public class Window { /** * Moves the point given by X and Y to be on the grid of the active region .
* @ param x the easting of the arbitrary point
* @ param y the northing of the arbitrary point
* @ param activeWindow the active window from which to take the grid
* @ return the snapped point */
public static Point2D . Double snapToNextHigherInActiveRegionResolution ( double x , double y , Window activeWindow ) { } } | double minx = activeWindow . getRectangle ( ) . getBounds2D ( ) . getMinX ( ) ; double ewres = activeWindow . getWEResolution ( ) ; double xsnap = minx + ( Math . ceil ( ( x - minx ) / ewres ) * ewres ) ; double miny = activeWindow . getRectangle ( ) . getBounds2D ( ) . getMinY ( ) ; double nsres = activeWindow . getNSResolution ( ) ; double ysnap = miny + ( Math . ceil ( ( y - miny ) / nsres ) * nsres ) ; return new Point2D . Double ( xsnap , ysnap ) ; |
public class ReferenceField { /** * Synchronize this refernce field with this record .
* Adds the behaviors to sync this field and the record .
* Used for popup screenfields where the referencerecord has a detail to display on change .
* @ param record The reference record to synchronize . */
public void syncReference ( Record record ) { } } | this . setReferenceRecord ( record ) ; BaseField recordKeyField = ( BaseField ) record . getCounterField ( ) ; if ( ( recordKeyField . isNull ( ) ) && ( ! this . isNull ( ) ) && ( ! record . isModified ( ) ) && ( record . getEditMode ( ) != DBConstants . EDIT_CURRENT ) && ( record . getEditMode ( ) != DBConstants . EDIT_IN_PROGRESS ) && ( ( record . getOpenMode ( ) & DBConstants . OPEN_REFRESH_AND_LOCK_ON_CHANGE_STRATEGY ) == 0 ) ) { recordKeyField . moveFieldToThis ( this , DBConstants . DISPLAY , DBConstants . SCREEN_MOVE ) ; // Start with this field ' s value if you arn ' t going to mess up the record
recordKeyField . setModified ( false ) ; } else this . setReference ( record , DBConstants . DISPLAY , DBConstants . SCREEN_MOVE ) ; // If the screen field is changed , make sure the passed in header record ' s key field is changed to match .
MoveOnChangeHandler listener = ( MoveOnChangeHandler ) this . getListener ( MoveOnChangeHandler . class . getName ( ) ) ; if ( ( listener == null ) || ( listener . getDestField ( ) != recordKeyField ) ) this . addListener ( new MoveOnChangeHandler ( recordKeyField , null ) ) ; // If the record is externally selected , sync the record ' s key with the screenfield
MoveOnValidHandler listener2 = ( MoveOnValidHandler ) record . getListener ( MoveOnValidHandler . class . getName ( ) ) ; if ( ( listener2 == null ) || ( listener2 . getSourceField ( ) != recordKeyField ) ) record . addListener ( new MoveOnValidHandler ( this , recordKeyField ) ) ; MainReadOnlyHandler listener3 = ( MainReadOnlyHandler ) recordKeyField . getListener ( MainReadOnlyHandler . class . getName ( ) ) ; if ( listener3 == null ) recordKeyField . addListener ( new MainReadOnlyHandler ( null ) ) ; |
public class AlbumUtils { /** * Generate a random jpg file path .
* @ return file path .
* @ deprecated use { @ link # randomJPGPath ( Context ) } instead . */
@ NonNull @ Deprecated public static String randomJPGPath ( ) { } } | File bucket = Environment . getExternalStoragePublicDirectory ( Environment . DIRECTORY_DCIM ) ; return randomJPGPath ( bucket ) ; |
public class LatentRelationalAnalysis { /** * Loads the analogies from an input file .
* The file must contain word pairs in the form of A : B separated by newlines .
* @ param analogy _ file a { @ code String } containing the absolute path to the analogy file . */
public void loadAnalogiesFromFile ( String analogy_file ) { } } | try { Scanner sc = new Scanner ( new File ( analogy_file ) ) ; while ( sc . hasNext ( ) ) { String analogy = sc . next ( ) ; if ( ! isAnalogyFormat ( analogy ) ) { System . err . println ( "\"" + analogy + "\" not in proper format." ) ; continue ; } String analogy_pair [ ] = analogy . split ( ":" ) ; String A = analogy_pair [ 0 ] ; String B = analogy_pair [ 1 ] ; // 1 . Find alternates for A and B
Synset [ ] A_prime = findAlternatives ( A ) ; Synset [ ] B_prime = findAlternatives ( B ) ; // 2 . Filter phrases
ArrayList < String > tmp = new ArrayList < String > ( filterPhrases ( INDEX_DIR , A , B , A_prime , B_prime ) ) ; filtered_phrases . addAll ( tmp ) ; original_to_alternates . put ( A + ":" + B , tmp ) ; } sc . close ( ) ; } catch ( Exception e ) { System . err . println ( "Could not read file." ) ; } |
public class SrvGetUserCredentials { /** * < p > Retrieve User Credentials . < / p >
* @ param pUserName User Name
* @ return User Credentials
* @ throws Exception - an exception */
@ Override public final UserCredentials retrieveUserCredentials ( final String pUserName ) throws Exception { } } | String query = "select USERTOMCAT.ITSUSER as ITSUSER, ITSPASSWORD, ITSROLE" + " from USERTOMCAT join USERROLETOMCAT on USERROLETOMCAT.ITSUSER =" + " USERTOMCAT.ITSUSER where USERTOMCAT.ITSUSER = '" + pUserName + "';" ; UserCredentials result = null ; IRecordSet < RS > recordSet = null ; try { this . srvDatabase . setIsAutocommit ( false ) ; this . srvDatabase . setTransactionIsolation ( ISrvDatabase . TRANSACTION_READ_UNCOMMITTED ) ; this . srvDatabase . beginTransaction ( ) ; recordSet = getSrvDatabase ( ) . retrieveRecords ( query ) ; if ( recordSet . moveToFirst ( ) ) { ArrayList < String > roles = new ArrayList < String > ( ) ; do { if ( result == null ) { result = new UserCredentials ( ) ; result . setUserName ( recordSet . getString ( "ITSUSER" ) ) ; result . setUserPassword ( recordSet . getString ( "ITSPASSWORD" ) ) ; } roles . add ( recordSet . getString ( "ITSROLE" ) ) ; } while ( recordSet . moveToNext ( ) ) ; result . setUserRoles ( roles . toArray ( new String [ roles . size ( ) ] ) ) ; } this . srvDatabase . commitTransaction ( ) ; } catch ( Exception ex ) { this . srvDatabase . rollBackTransaction ( ) ; throw ex ; } finally { this . srvDatabase . releaseResources ( ) ; if ( recordSet != null ) { recordSet . close ( ) ; } } return result ; |
public class AnnotationDescImpl { /** * Returns the annotation type of this annotation . */
public AnnotationTypeDoc annotationType ( ) { } } | ClassSymbol atsym = ( ClassSymbol ) annotation . type . tsym ; if ( annotation . type . isErroneous ( ) ) { env . warning ( null , "javadoc.class_not_found" , annotation . type . toString ( ) ) ; return new AnnotationTypeDocImpl ( env , atsym ) ; } else { return ( AnnotationTypeDoc ) env . getClassDoc ( atsym ) ; } |
public class BaseActionForm { /** * Run all validation ( declarative validation from annotations and the result of { @ link org . apache . beehive . netui . pageflow . Validatable # validate } ) on
* a given bean .
* @ param bean the bean to validate .
* @ param beanName the name of the bean , to be passed to Validator to look up declarative validation rules .
* @ param mapping the current ActionMapping .
* @ param request the current HttpServletRequest .
* @ return an ActionErrors object containing errors that occurred during bean validation . */
protected ActionErrors validateBean ( Object bean , String beanName , ActionMapping mapping , HttpServletRequest request ) { } } | MessageResources messageResources = ( MessageResources ) request . getAttribute ( Globals . MESSAGES_KEY ) ; ExpressionAwareMessageResources . update ( messageResources , bean ) ; // See if this action uses a form that defines its own message resources . If so , use those , or combine them
// with the message resources from the current module .
if ( mapping instanceof PageFlowActionMapping ) { PageFlowActionMapping pfam = ( PageFlowActionMapping ) mapping ; String bundle = pfam . getFormBeanMessageResourcesKey ( ) ; if ( bundle != null ) { MessageResources formBeanResources = ( MessageResources ) request . getAttribute ( bundle ) ; ExpressionAwareMessageResources . update ( formBeanResources , bean ) ; if ( formBeanResources != null ) { if ( messageResources != null ) { formBeanResources = new MergedMessageResources ( messageResources , formBeanResources ) ; } request . setAttribute ( Globals . MESSAGES_KEY , formBeanResources ) ; messageResources = formBeanResources ; } } } ServletContext servletContext = getServlet ( ) . getServletContext ( ) ; // If there ' s still no MessageResources for this request , create one that can evaluate expressions .
if ( messageResources == null ) { messageResources = new ExpressionAwareMessageResources ( bean , request , servletContext ) ; request . setAttribute ( Globals . MESSAGES_KEY , messageResources ) ; } ActionErrors errors = new ActionErrors ( ) ; // If the ValidatorPlugIn was initialized for this module , run it .
if ( Resources . getValidatorResources ( servletContext , request ) != null ) { try { // Run validations associated with the bean .
Validator beanV = initValidator ( beanName , bean , servletContext , request , errors , page ) ; validatorResults = beanV . validate ( ) ; // Run validations associated with the action .
Validator actionV = initValidator ( mapping . getPath ( ) , bean , servletContext , request , errors , page ) ; validatorResults . merge ( actionV . validate ( ) ) ; } catch ( ValidatorException e ) { _log . error ( e . getMessage ( ) , e ) ; } } // If this bean implements our Validatable interface , run its validate method .
if ( bean instanceof Validatable ) { ( ( Validatable ) bean ) . validate ( mapping , request , errors ) ; } // Add any additional errors specified by a subclass .
ActionErrors additionalActionErrors = getAdditionalActionErrors ( mapping , request ) ; if ( additionalActionErrors != null ) { mergeActionErrors ( errors , additionalActionErrors ) ; } return errors ; |
public class GenbankWriterHelper { /** * Write a collection of NucleotideSequences to a file
* @ param outputStream
* @ param dnaSequences
* @ throws Exception */
public static void writeNucleotideSequence ( OutputStream outputStream , Collection < DNASequence > dnaSequences ) throws Exception { } } | writeNucleotideSequence ( outputStream , dnaSequences , LINEAR_DNA ) ; |
public class OAuthConsumerContextFilter { /** * Get the URL to which to redirect the user for authorization of protected resources .
* @ param details The resource for which to get the authorization url .
* @ param requestToken The request token .
* @ param callbackURL The callback URL .
* @ return The URL . */
protected String getUserAuthorizationRedirectURL ( ProtectedResourceDetails details , OAuthConsumerToken requestToken , String callbackURL ) { } } | try { String baseURL = details . getUserAuthorizationURL ( ) ; StringBuilder builder = new StringBuilder ( baseURL ) ; char appendChar = baseURL . indexOf ( '?' ) < 0 ? '?' : '&' ; builder . append ( appendChar ) . append ( "oauth_token=" ) ; builder . append ( URLEncoder . encode ( requestToken . getValue ( ) , "UTF-8" ) ) ; if ( ! details . isUse10a ( ) ) { builder . append ( '&' ) . append ( "oauth_callback=" ) ; builder . append ( URLEncoder . encode ( callbackURL , "UTF-8" ) ) ; } return builder . toString ( ) ; } catch ( UnsupportedEncodingException e ) { throw new IllegalStateException ( e ) ; } |
public class Ifc2x3tc1PackageImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
public EClass getIfcPerformanceHistory ( ) { } } | if ( ifcPerformanceHistoryEClass == null ) { ifcPerformanceHistoryEClass = ( EClass ) EPackage . Registry . INSTANCE . getEPackage ( Ifc2x3tc1Package . eNS_URI ) . getEClassifiers ( ) . get ( 346 ) ; } return ifcPerformanceHistoryEClass ; |
public class AnnotationTypeRequiredMemberWriterImpl { /** * { @ inheritDoc } */
protected Content getNavSummaryLink ( TypeElement typeElement , boolean link ) { } } | if ( link ) { return writer . getHyperLink ( SectionName . ANNOTATION_TYPE_REQUIRED_ELEMENT_SUMMARY , contents . navAnnotationTypeRequiredMember ) ; } else { return contents . navAnnotationTypeRequiredMember ; } |
public class SQLExecutor { /** * The connection opened in the transaction will be automatically closed after the transaction is committed or rolled back .
* DON ' T close it again by calling the close method .
* @ param isolationLevel
* @ param forUpdateOnly
* @ return
* @ deprecated */
@ Deprecated @ Override public SQLTransaction beginTransaction ( IsolationLevel isolationLevel , boolean forUpdateOnly ) { } } | return super . beginTransaction ( isolationLevel , forUpdateOnly ) ; |
public class FileUtil { /** * Returns extension of the file . Returns null if there is no extension */
public static String getExtension ( String fileName ) { } } | int dot = fileName . lastIndexOf ( '.' ) ; return dot == - 1 ? null : fileName . substring ( dot + 1 ) ; |
public class CompressedTexture { /** * Loads a file into memory ; detects type , and calls the appropriate
* { @ link GVRCompressedTextureLoader # parse ( byte [ ] , Reader ) } method .
* @ param stream
* InputStream containing a compressed texture file
* @ param maxLength
* Max length to read . - 1 for unlimited .
* @ param closeStream
* Close { @ code stream } on exit ?
* @ return Normally , one and only one { @ link GVRCompressedTextureLoader }
* will recognize the file , and this method will return a
* { @ link CompressedTexture } , ready to be passed to EGL via
* { @ link CompressedTexture # glCompressedTexImage2D ( int , int ) } . If no
* loaders recognize the file , or if multiple loaders recognize the
* file , this method will return < code > null < / null > .
* @ throws IOException
* Does not catch any internal exceptions */
static CompressedTexture load ( InputStream stream , int maxLength , boolean closeStream ) throws IOException { } } | byte [ ] data ; try { data = maxLength >= 0 ? readBytes ( stream , maxLength ) : readBytes ( stream ) ; } finally { if ( closeStream ) { stream . close ( ) ; } } Reader reader = new Reader ( data ) ; GVRCompressedTextureLoader valid = null ; List < GVRCompressedTextureLoader > loaders = GVRCompressedTextureLoader . getLoaders ( ) ; synchronized ( loaders ) { for ( GVRCompressedTextureLoader loader : loaders ) { if ( loader . sniff ( data , reader ) ) { if ( valid != null ) { throw new IllegalArgumentException ( "Multiple loaders think this smells right" ) ; } valid = loader ; } reader . reset ( ) ; } if ( valid == null ) { throw new IllegalArgumentException ( "No loader thinks this smells right" ) ; } return valid . parse ( data , reader ) ; } |
public class ImgUtil { /** * 水平翻转图像
* @ param image 图像
* @ param outFile 输出文件
* @ throws IORuntimeException IO异常
* @ since 3.2.2 */
public static void flip ( Image image , File outFile ) throws IORuntimeException { } } | write ( flip ( image ) , outFile ) ; |
public class AnnotationManager { /** * Set default values for annotations .
* Initial annotation take precedence over the default annotation when both annotation types are present
* @ param defaultAnnotations default value for annotations */
public void setDefaults ( Annotation [ ] defaultAnnotations ) { } } | if ( defaultAnnotations == null ) { return ; } for ( Annotation each : defaultAnnotations ) { Class < ? extends Annotation > key = each . annotationType ( ) ; if ( Title . class . equals ( key ) || Description . class . equals ( key ) ) { continue ; } if ( ! annotations . containsKey ( key ) ) { annotations . put ( key , each ) ; } } |
public class CommerceCurrencyLocalServiceBaseImpl { /** * Returns a range of commerce currencies matching the UUID and company .
* @ param uuid the UUID of the commerce currencies
* @ param companyId the primary key of the company
* @ param start the lower bound of the range of commerce currencies
* @ param end the upper bound of the range of commerce currencies ( not inclusive )
* @ param orderByComparator the comparator to order the results by ( optionally < code > null < / code > )
* @ return the range of matching commerce currencies , or an empty list if no matches were found */
@ Override public List < CommerceCurrency > getCommerceCurrenciesByUuidAndCompanyId ( String uuid , long companyId , int start , int end , OrderByComparator < CommerceCurrency > orderByComparator ) { } } | return commerceCurrencyPersistence . findByUuid_C ( uuid , companyId , start , end , orderByComparator ) ; |
public class CmsImageCacheHelper { /** * Visits all cached images in the given directory . < p >
* @ param cms the cms context
* @ param directory the directory to visit
* @ param withVariations if also variations should be read
* @ param showSize if it is needed to compute the image size
* @ param statsOnly if only statistical information should be retrieved */
private void visitImages ( CmsObject cms , File directory , boolean withVariations , boolean showSize , boolean statsOnly ) { } } | if ( ! directory . canRead ( ) || ! directory . isDirectory ( ) ) { return ; } File [ ] files = directory . listFiles ( ) ; for ( int i = 0 ; i < files . length ; i ++ ) { File f = files [ i ] ; if ( f . isDirectory ( ) ) { visitImages ( cms , f , withVariations , showSize , statsOnly ) ; continue ; } visitImage ( cms , f , withVariations , showSize , statsOnly ) ; } |
public class TargetQueryRenderer { /** * Transforms the given < code > OBDAQuery < / code > into a string . The method requires
* a prefix manager to shorten full IRI name . */
public static String encode ( ImmutableList < TargetAtom > body , PrefixManager prefixManager ) { } } | TurtleWriter turtleWriter = new TurtleWriter ( ) ; for ( TargetAtom atom : body ) { String subject , predicate , object = "" ; String originalString = atom . getProjectionAtom ( ) . getPredicate ( ) . toString ( ) ; if ( isUnary ( atom . getProjectionAtom ( ) ) ) { ImmutableTerm subjectTerm = atom . getSubstitutedTerm ( 0 ) ; subject = getDisplayName ( subjectTerm , prefixManager ) ; predicate = "a" ; object = getAbbreviatedName ( originalString , prefixManager , false ) ; if ( originalString . equals ( object ) ) { object = "<" + object + ">" ; } } else if ( originalString . equals ( "triple" ) ) { ImmutableTerm subjectTerm = atom . getSubstitutedTerm ( 0 ) ; subject = getDisplayName ( subjectTerm , prefixManager ) ; ImmutableTerm predicateTerm = atom . getSubstitutedTerm ( 1 ) ; predicate = getDisplayName ( predicateTerm , prefixManager ) ; ImmutableTerm objectTerm = atom . getSubstitutedTerm ( 2 ) ; object = getDisplayName ( objectTerm , prefixManager ) ; } else { ImmutableTerm subjectTerm = atom . getSubstitutedTerm ( 0 ) ; subject = getDisplayName ( subjectTerm , prefixManager ) ; predicate = getAbbreviatedName ( originalString , prefixManager , false ) ; if ( originalString . equals ( predicate ) ) { predicate = "<" + predicate + ">" ; } ImmutableTerm objectTerm = atom . getSubstitutedTerm ( 1 ) ; object = getDisplayName ( objectTerm , prefixManager ) ; } turtleWriter . put ( subject , predicate , object ) ; } return turtleWriter . print ( ) ; |
public class RedisStorage { /** * Get the names of all of the < code > { @ link org . quartz . Trigger } < / code > s that have the given group name .
* @ param matcher the matcher with which to compare group names
* @ param jedis a thread - safe Redis connection
* @ return the set of all TriggerKeys which have the given group name */
@ Override public Set < TriggerKey > getTriggerKeys ( GroupMatcher < TriggerKey > matcher , Jedis jedis ) { } } | Set < TriggerKey > triggerKeys = new HashSet < > ( ) ; if ( matcher . getCompareWithOperator ( ) == StringMatcher . StringOperatorName . EQUALS ) { final String triggerGroupSetKey = redisSchema . triggerGroupSetKey ( new TriggerKey ( "" , matcher . getCompareToValue ( ) ) ) ; final Set < String > triggers = jedis . smembers ( triggerGroupSetKey ) ; if ( triggers != null ) { for ( final String trigger : triggers ) { triggerKeys . add ( redisSchema . triggerKey ( trigger ) ) ; } } } else { List < Response < Set < String > > > triggerGroups = new ArrayList < > ( ) ; Pipeline pipe = jedis . pipelined ( ) ; for ( final String triggerGroupSetKey : jedis . smembers ( redisSchema . triggerGroupsSet ( ) ) ) { if ( matcher . getCompareWithOperator ( ) . evaluate ( redisSchema . triggerGroup ( triggerGroupSetKey ) , matcher . getCompareToValue ( ) ) ) { triggerGroups . add ( pipe . smembers ( triggerGroupSetKey ) ) ; } } pipe . sync ( ) ; for ( Response < Set < String > > triggerGroup : triggerGroups ) { if ( triggerGroup . get ( ) != null ) { for ( final String trigger : triggerGroup . get ( ) ) { triggerKeys . add ( redisSchema . triggerKey ( trigger ) ) ; } } } } return triggerKeys ; |
public class Reflector { /** * convert Object from src to trg Type , if possible
* @ param src Object to convert
* @ param srcClass Source Class
* @ param trgClass Target Class
* @ return converted Object
* @ throws PageException */
public static Object convert ( Object src , Class trgClass , RefInteger rating ) throws PageException { } } | if ( rating != null ) { Object trg = _convert ( src , trgClass ) ; if ( src == trg ) { rating . plus ( 10 ) ; return trg ; } if ( src == null || trg == null ) { rating . plus ( 0 ) ; return trg ; } if ( isInstaneOf ( src . getClass ( ) , trg . getClass ( ) ) ) { rating . plus ( 9 ) ; return trg ; } if ( src . equals ( trg ) ) { rating . plus ( 8 ) ; return trg ; } // different number
boolean bothNumbers = src instanceof Number && trg instanceof Number ; if ( bothNumbers && ( ( Number ) src ) . doubleValue ( ) == ( ( Number ) trg ) . doubleValue ( ) ) { rating . plus ( 7 ) ; return trg ; } String sSrc = Caster . toString ( src , null ) ; String sTrg = Caster . toString ( trg , null ) ; if ( sSrc != null && sTrg != null ) { // different number types
if ( src instanceof Number && trg instanceof Number && sSrc . equals ( sTrg ) ) { rating . plus ( 6 ) ; return trg ; } // looks the same
if ( sSrc . equals ( sTrg ) ) { rating . plus ( 5 ) ; return trg ; } if ( sSrc . equalsIgnoreCase ( sTrg ) ) { rating . plus ( 4 ) ; return trg ; } } // CF Equal
try { if ( Operator . equals ( src , trg , false , true ) ) { rating . plus ( 3 ) ; return trg ; } } catch ( Throwable t ) { ExceptionUtil . rethrowIfNecessary ( t ) ; } return trg ; } return _convert ( src , trgClass ) ; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.