signature stringlengths 43 39.1k | implementation stringlengths 0 450k |
|---|---|
public class AmazonIdentityManagementClient { /** * Lists the instance profiles that have the specified associated IAM role . If there are none , the operation returns
* an empty list . For more information about instance profiles , go to < a
* href = " https : / / docs . aws . amazon . com / IAM / latest / UserGuide / AboutInstanceProfiles . html " > About Instance Profiles < / a > .
* You can paginate the results using the < code > MaxItems < / code > and < code > Marker < / code > parameters .
* @ param listInstanceProfilesForRoleRequest
* @ return Result of the ListInstanceProfilesForRole operation returned by the service .
* @ throws NoSuchEntityException
* The request was rejected because it referenced a resource entity that does not exist . The error message
* describes the resource .
* @ throws ServiceFailureException
* The request processing has failed because of an unknown error , exception or failure .
* @ sample AmazonIdentityManagement . ListInstanceProfilesForRole
* @ see < a href = " http : / / docs . aws . amazon . com / goto / WebAPI / iam - 2010-05-08 / ListInstanceProfilesForRole "
* target = " _ top " > AWS API Documentation < / a > */
@ Override public ListInstanceProfilesForRoleResult listInstanceProfilesForRole ( ListInstanceProfilesForRoleRequest request ) { } } | request = beforeClientExecution ( request ) ; return executeListInstanceProfilesForRole ( request ) ; |
public class ConvertBufferedImage { /** * Converts a buffered image into an image of the specified type .
* @ param src Input BufferedImage which is to be converted
* @ param dst The image which it is being converted into
* @ param orderRgb If applicable , should it adjust the ordering of each color band to maintain color consistency */
public static < T extends ImageBase < T > > void convertFrom ( BufferedImage src , T dst , boolean orderRgb ) { } } | if ( dst instanceof ImageGray ) { ImageGray sb = ( ImageGray ) dst ; convertFromSingle ( src , sb , ( Class < ImageGray > ) sb . getClass ( ) ) ; } else if ( dst instanceof Planar ) { Planar ms = ( Planar ) dst ; convertFromPlanar ( src , ms , orderRgb , ms . getBandType ( ) ) ; } else if ( dst instanceof ImageInterleaved ) { convertFromInterleaved ( src , ( ImageInterleaved ) dst , orderRgb ) ; } else { throw new IllegalArgumentException ( "Unknown type " + dst . getClass ( ) . getSimpleName ( ) ) ; } |
public class JKDefaultTableModel { /** * Returns an attribute value for the cell at < code > row < / code > and
* < code > column < / code > .
* @ param row the row whose value is to be queried
* @ param column the column whose value is to be queried
* @ return the value Object at the specified cell
* @ exception ArrayIndexOutOfBoundsException if an invalid row or column was
* given */
@ Override public Object getValueAt ( final int row , final int column ) { } } | final Vector rowVector = ( Vector ) this . dataVector . elementAt ( row ) ; return rowVector . elementAt ( column ) ; |
public class KeyVaultClientCustomImpl { /** * List certificates in the specified vault .
* @ param vaultBaseUrl
* The vault name , e . g . https : / / myvault . vault . azure . net
* @ param maxresults
* Maximum number of results to return in a page . If not specified
* the service will return up to 25 results .
* @ return the PagedList & lt ; CertificateItem & gt ; if successful . */
public PagedList < CertificateItem > listCertificates ( final String vaultBaseUrl , final Integer maxresults ) { } } | return getCertificates ( vaultBaseUrl , maxresults ) ; |
public class AeshCommandPopulator { /** * Will parse the input line and populate the fields in the instance object specified by
* the given annotations .
* The instance object must be annotated with the CommandDefinition annotation @ see CommandDefinition
* Any parser errors will throw an exception
* @ param instance command
* @ param fieldName field
* public static void parseAndPopulate ( Object instance , String line )
* throws CommandLineParserException , OptionValidatorException {
* CommandLineParser parser = ParserGenerator . generateCommandLineParser ( instance . getClass ( ) ) ;
* AeshCommandPopulator populator = new AeshCommandPopulator ( parser ) ;
* populator . populateObject ( instance , parser . parse ( line ) ) ; */
private void resetField ( Object instance , String fieldName , boolean hasValue ) { } } | try { Field field = getField ( instance . getClass ( ) , fieldName ) ; if ( ! Modifier . isPublic ( field . getModifiers ( ) ) ) field . setAccessible ( true ) ; if ( field . getType ( ) . isPrimitive ( ) ) { if ( boolean . class . isAssignableFrom ( field . getType ( ) ) ) field . set ( instance , false ) ; else if ( int . class . isAssignableFrom ( field . getType ( ) ) ) field . set ( instance , 0 ) ; else if ( short . class . isAssignableFrom ( field . getType ( ) ) ) field . set ( instance , 0 ) ; else if ( char . class . isAssignableFrom ( field . getType ( ) ) ) field . set ( instance , '\u0000' ) ; else if ( byte . class . isAssignableFrom ( field . getType ( ) ) ) field . set ( instance , 0 ) ; else if ( long . class . isAssignableFrom ( field . getType ( ) ) ) field . set ( instance , 0L ) ; else if ( float . class . isAssignableFrom ( field . getType ( ) ) ) field . set ( instance , 0.0f ) ; else if ( double . class . isAssignableFrom ( field . getType ( ) ) ) field . set ( instance , 0.0d ) ; } else if ( ! hasValue && field . getType ( ) . equals ( Boolean . class ) ) { field . set ( instance , Boolean . FALSE ) ; } else field . set ( instance , null ) ; } catch ( NoSuchFieldException | IllegalAccessException e ) { e . printStackTrace ( ) ; } |
public class SecurityPolicyClient { /** * Gets a rule at the specified priority .
* < p > Sample code :
* < pre > < code >
* try ( SecurityPolicyClient securityPolicyClient = SecurityPolicyClient . create ( ) ) {
* Integer priority = 0;
* ProjectGlobalSecurityPolicyName securityPolicy = ProjectGlobalSecurityPolicyName . of ( " [ PROJECT ] " , " [ SECURITY _ POLICY ] " ) ;
* SecurityPolicyRule response = securityPolicyClient . getRuleSecurityPolicy ( priority , securityPolicy . toString ( ) ) ;
* < / code > < / pre >
* @ param priority The priority of the rule to get from the security policy .
* @ param securityPolicy Name of the security policy to which the queried rule belongs .
* @ throws com . google . api . gax . rpc . ApiException if the remote call fails */
@ BetaApi public final SecurityPolicyRule getRuleSecurityPolicy ( Integer priority , String securityPolicy ) { } } | GetRuleSecurityPolicyHttpRequest request = GetRuleSecurityPolicyHttpRequest . newBuilder ( ) . setPriority ( priority ) . setSecurityPolicy ( securityPolicy ) . build ( ) ; return getRuleSecurityPolicy ( request ) ; |
public class LRImporter { /** * Get a result from an obtain request
* @ param resumptionToken the " resumption _ token " value to use for this request
* @ return the result from this request */
public LRResult getObtainJSONData ( String resumptionToken ) throws LRException { } } | return getObtainJSONData ( null , null , null , null , resumptionToken ) ; |
public class LinkedServersInner { /** * Adds a linked server to the Redis cache ( requires Premium SKU ) .
* @ param resourceGroupName The name of the resource group .
* @ param name The name of the Redis cache .
* @ param linkedServerName The name of the linked server that is being added to the Redis cache .
* @ param parameters Parameters supplied to the Create Linked server operation .
* @ 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 < RedisLinkedServerWithPropertiesInner > createAsync ( String resourceGroupName , String name , String linkedServerName , RedisLinkedServerCreateParameters parameters , final ServiceCallback < RedisLinkedServerWithPropertiesInner > serviceCallback ) { } } | return ServiceFuture . fromResponse ( createWithServiceResponseAsync ( resourceGroupName , name , linkedServerName , parameters ) , serviceCallback ) ; |
public class ResourcePageImpl { /** * Makes a request to the service to retrieve the next page of resources
* in the collection .
* @ param extractor an optional result extractor object
* @ return the next page of results */
public ResourcePageImpl nextPage ( ResultCapture < Object > extractor ) { } } | if ( getNextToken ( ) == null ) { throw new NoSuchElementException ( "There is no next page" ) ; } ActionResult result = ActionUtils . perform ( context , listActionModel , request , extractor , getNextToken ( ) ) ; return new ResourcePageImpl ( context , listActionModel , request , result ) ; |
public class RepositoryTrigger { /** * The branches that will be included in the trigger configuration . If you specify an empty array , the trigger will
* apply to all branches .
* < note >
* While no content is required in the array , you must include the array itself .
* < / note >
* < b > NOTE : < / b > This method appends the values to the existing list ( if any ) . Use
* { @ link # setBranches ( java . util . Collection ) } or { @ link # withBranches ( java . util . Collection ) } if you want to override
* the existing values .
* @ param branches
* The branches that will be included in the trigger configuration . If you specify an empty array , the
* trigger will apply to all branches . < / p > < note >
* While no content is required in the array , you must include the array itself .
* @ return Returns a reference to this object so that method calls can be chained together . */
public RepositoryTrigger withBranches ( String ... branches ) { } } | if ( this . branches == null ) { setBranches ( new java . util . ArrayList < String > ( branches . length ) ) ; } for ( String ele : branches ) { this . branches . add ( ele ) ; } return this ; |
public class ColorServlet { /** * Renders the 1 x 1 single color PNG to the response .
* @ see ColorServlet class description
* @ param pRequest the request
* @ param pResponse the response
* @ throws IOException
* @ throws ServletException */
public void service ( ServletRequest pRequest , ServletResponse pResponse ) throws IOException , ServletException { } } | int red = 0 ; int green = 0 ; int blue = 0 ; // Get color parameter and parse color
String rgb = pRequest . getParameter ( RGB_PARAME ) ; if ( rgb != null && rgb . length ( ) >= 6 && rgb . length ( ) <= 7 ) { int index = 0 ; // If the hash ( ' # ' ) character is included , skip it .
if ( rgb . length ( ) == 7 ) { index ++ ; } try { // Two digit hex for each color
String r = rgb . substring ( index , index += 2 ) ; red = Integer . parseInt ( r , 0x10 ) ; String g = rgb . substring ( index , index += 2 ) ; green = Integer . parseInt ( g , 0x10 ) ; String b = rgb . substring ( index , index += 2 ) ; blue = Integer . parseInt ( b , 0x10 ) ; } catch ( NumberFormatException nfe ) { log ( "Wrong color format for ColorDroplet: " + rgb + ". Must be RRGGBB." ) ; } } // Set MIME type for PNG
pResponse . setContentType ( "image/png" ) ; ServletOutputStream out = pResponse . getOutputStream ( ) ; try { // Write header ( and palette chunk length )
out . write ( PNG_IMG , 0 , PLTE_CHUNK_START ) ; // Create palette chunk , excl lenght , and write
byte [ ] palette = makePalette ( red , green , blue ) ; out . write ( palette ) ; // Write image data until end
int pos = PLTE_CHUNK_START + PLTE_CHUNK_LENGTH + 4 ; out . write ( PNG_IMG , pos , PNG_IMG . length - pos ) ; } finally { out . flush ( ) ; } |
public class CalendarRecordItem { /** * Get the icon ( opt ) . Not implemented .
* @ return The icon . */
public Object getIcon ( int iIconType ) { } } | if ( m_iIconField == - 1 ) return null ; Object data = this . getFieldData ( m_iIconField ) ; if ( data instanceof PortableImage ) return ( ( PortableImage ) data ) . getImage ( ) ; // Make sure you cache this
else // if ( data instanceof ImageIcon )
return this . getFieldData ( m_iIconField ) ; // else
// return null ; |
public class TrelloImpl { /** * / * Organizations */
@ Override public List < Board > getOrganizationBoards ( String organizationId , Argument ... args ) { } } | return asList ( ( ) -> get ( createUrl ( GET_ORGANIZATION_BOARD ) . params ( args ) . asString ( ) , Board [ ] . class , organizationId ) ) ; |
public class RPCParameter { /** * Returns the type of data contained in the parameter .
* @ return Type of data . */
public HasData hasData ( ) { } } | boolean scalar = values . containsKey ( "" ) ; boolean vector = scalar ? getCount ( ) > 1 : getCount ( ) > 0 ; return scalar && vector ? HasData . BOTH : scalar ? HasData . SCALAR : vector ? HasData . VECTOR : HasData . NONE ; |
public class RegistryConfig { /** * Sets parameters .
* @ param parameters the parameters
* @ return the RegistryConfig */
public RegistryConfig setParameters ( Map < String , String > parameters ) { } } | if ( this . parameters == null ) { this . parameters = new ConcurrentHashMap < String , String > ( ) ; this . parameters . putAll ( parameters ) ; } return this ; |
public class ContactType { /** * Get the table name . */
public String getTableNames ( boolean bAddQuotes ) { } } | return ( m_tableName == null ) ? Record . formatTableNames ( CONTACT_TYPE_FILE , bAddQuotes ) : super . getTableNames ( bAddQuotes ) ; |
public class CloudSchedulerClient { /** * Creates a job .
* < p > Sample code :
* < pre > < code >
* try ( CloudSchedulerClient cloudSchedulerClient = CloudSchedulerClient . create ( ) ) {
* LocationName parent = LocationName . of ( " [ PROJECT ] " , " [ LOCATION ] " ) ;
* Job job = Job . newBuilder ( ) . build ( ) ;
* Job response = cloudSchedulerClient . createJob ( parent . toString ( ) , job ) ;
* < / code > < / pre >
* @ param parent Required .
* < p > The location name . For example : ` projects / PROJECT _ ID / locations / LOCATION _ ID ` .
* @ param job Required .
* < p > The job to add . The user can optionally specify a name for the job in
* [ name ] [ google . cloud . scheduler . v1beta1 . Job . name ] .
* [ name ] [ google . cloud . scheduler . v1beta1 . Job . name ] cannot be the same as an existing job . If a
* name is not specified then the system will generate a random unique name that will be
* returned ( [ name ] [ google . cloud . scheduler . v1beta1 . Job . name ] ) in the response .
* @ throws com . google . api . gax . rpc . ApiException if the remote call fails */
public final Job createJob ( String parent , Job job ) { } } | CreateJobRequest request = CreateJobRequest . newBuilder ( ) . setParent ( parent ) . setJob ( job ) . build ( ) ; return createJob ( request ) ; |
public class DrawerUIUtils { /** * helper to create a colorStateList for the text
* @ param text _ color
* @ param selected _ text _ color
* @ return */
public static ColorStateList getTextColorStateList ( int text_color , int selected_text_color ) { } } | return new ColorStateList ( new int [ ] [ ] { new int [ ] { android . R . attr . state_selected } , new int [ ] { } } , new int [ ] { selected_text_color , text_color } ) ; |
public class ByteBufQueue { /** * Returns the ByteBuf of the given index relatively to the { @ code first }
* index ( head ) of the queue .
* @ param n index of the ByteBuf to return ( relatively to the head of the queue )
* @ return a ByteBuf of the given index */
@ NotNull @ Contract ( pure = true ) public ByteBuf peekBuf ( int n ) { } } | assert n <= remainingBufs ( ) ; int i = first + n ; if ( i >= bufs . length ) i -= bufs . length ; return bufs [ i ] ; |
public class TitlePaneMaximizeButtonPainter { /** * Paint the background of the button using the specified colors .
* @ param g the Graphics2D context to paint with .
* @ param c the component .
* @ param width the width of the component .
* @ param height the height of the component .
* @ param colors the color set to use to paint the button . */
private void paintBackground ( Graphics2D g , JComponent c , int width , int height , ButtonColors colors ) { } } | g . setRenderingHint ( RenderingHints . KEY_ANTIALIASING , RenderingHints . VALUE_ANTIALIAS_OFF ) ; g . setColor ( colors . top ) ; g . drawLine ( 0 , 0 , width - 2 , 0 ) ; g . setColor ( colors . left ) ; g . drawLine ( 0 , 1 , 0 , height - 3 ) ; g . setColor ( colors . edge ) ; g . drawLine ( width - 1 , 0 , width - 1 , height - 2 ) ; g . drawLine ( 0 , height - 2 , width - 2 , height - 2 ) ; g . setColor ( colors . shadow ) ; g . drawLine ( 0 , height - 1 , width - 1 , height - 1 ) ; g . setColor ( colors . interior ) ; g . fillRect ( 1 , 1 , width - 1 , height - 2 ) ; |
public class AbstractPojoPropertyAccessorBuilder { /** * This method gets the according { @ link net . sf . mmm . util . pojo . descriptor . api . PojoPropertyDescriptor # getName ( )
* property - name } for the given { @ code methodName } . < br >
* This is the un - capitalized substring of the { @ code methodName } after the prefix ( given via { @ code prefixLength } ) .
* @ param methodName is the { @ link java . lang . reflect . Method # getName ( ) name } of the
* { @ link net . sf . mmm . util . pojo . descriptor . api . accessor . PojoPropertyAccessor # getAccessibleObject ( )
* accessor - method } .
* @ param prefixLength is the length of the method prefix ( e . g . 3 for " get " / " set " or 2 for " is " ) .
* @ param suffixLength is the length of the method suffix ( e . g . 4 for " Size " ) .
* @ return the requested property - name or { @ code null } if NOT available < br >
* ( { @ code methodName } . { @ link String # length ( ) length ( ) } & lt ; = { @ code prefixLength } ) . */
protected String getPropertyName ( String methodName , int prefixLength , int suffixLength ) { } } | int len = methodName . length ( ) ; int end = len - suffixLength ; if ( prefixLength < end ) { String methodSuffix = methodName . substring ( prefixLength , end ) ; StringBuffer sb = new StringBuffer ( methodSuffix ) ; sb . setCharAt ( 0 , Character . toLowerCase ( methodSuffix . charAt ( 0 ) ) ) ; return sb . toString ( ) ; } return null ; |
public class HttpSender { /** * Send a file full of events to the collector . This does zero - bytes - copy by default ( the async - http - client does
* it for us ) .
* @ param file File to send
* @ param handler callback handler for the serialization - writer library */
@ Override public void send ( final File file , final CallbackHandler handler ) { } } | log . info ( "Sending local file to collector: {}" , file . getAbsolutePath ( ) ) ; final long startTime = System . nanoTime ( ) ; final AsyncCompletionHandler < Response > asyncCompletionHandler = new AsyncCompletionHandler < Response > ( ) { @ Override public Response onCompleted ( final Response response ) { activeRequests . decrementAndGet ( ) ; if ( response . getStatusCode ( ) == 202 ) { handler . onSuccess ( file ) ; } else { handler . onError ( new IOException ( String . format ( "Received response %d: %s" , response . getStatusCode ( ) , response . getStatusText ( ) ) ) , file ) ; } sendTimer . update ( System . nanoTime ( ) - startTime , TimeUnit . NANOSECONDS ) ; return response ; // never read
} @ Override public void onThrowable ( final Throwable t ) { activeRequests . decrementAndGet ( ) ; handler . onError ( t , file ) ; } } ; final HttpJob job = new HttpJob ( client , file , asyncCompletionHandler ) ; workers . offer ( job ) ; |
public class SubscriptionIndex { /** * Get number of durable subscriptions .
* @ return number of durable subscriptions . */
public synchronized int getDurableSubscriptions ( ) { } } | if ( tc . isEntryEnabled ( ) ) SibTr . entry ( tc , "getDurableSubscriptions" ) ; if ( tc . isEntryEnabled ( ) ) SibTr . exit ( tc , "getDurableSubscriptions" , new Integer ( durableSubscriptions ) ) ; return durableSubscriptions ; |
public class SpecTopic { /** * Gets the list of Topic Relationships for this topic whose type is " NEXT " .
* @ return A list of next topic relationships */
public List < TopicRelationship > getNextTopicRelationships ( ) { } } | ArrayList < TopicRelationship > relationships = new ArrayList < TopicRelationship > ( ) ; for ( TopicRelationship relationship : topicRelationships ) { if ( relationship . getType ( ) == RelationshipType . NEXT ) { relationships . add ( relationship ) ; } } for ( TargetRelationship relationship : topicTargetRelationships ) { if ( relationship . getType ( ) == RelationshipType . NEXT ) { relationships . add ( new TopicRelationship ( relationship . getPrimaryRelationship ( ) , ( SpecTopic ) relationship . getSecondaryRelationship ( ) , relationship . getType ( ) ) ) ; } } return relationships ; |
public class ICalComponent { /** * Gets the first property of a given class .
* @ param clazz the property class
* @ param < T > the property class
* @ return the property or null if not found */
public < T extends ICalProperty > T getProperty ( Class < T > clazz ) { } } | return clazz . cast ( properties . first ( clazz ) ) ; |
public class Throwables { /** * Returns the Throwable ' s cause chain as a list . The first entry is the Throwable followed by the cause chain .
* @ param throwable The Throwable
* @ return The Throwable and its cause chain */
public static List < Throwable > getCausalChain ( final Throwable throwable ) { } } | if ( throwable == null ) { throw new NullPointerException ( "Throwable is null" ) ; } List < Throwable > causes = new ArrayList < Throwable > ( ) ; causes . add ( throwable ) ; Throwable cause = throwable . getCause ( ) ; while ( ( cause != null ) && ( ! causes . contains ( cause ) ) ) { causes . add ( cause ) ; cause = cause . getCause ( ) ; } return causes ; |
public class GenericBoJdbcDao { /** * Create / Persist a new BO to storage .
* @ param conn
* @ param bo
* @ return
* @ since 0.8.1 */
protected DaoResult create ( Connection conn , T bo ) { } } | if ( bo == null ) { return null ; } Savepoint savepoint = null ; try { try { savepoint = conn . getAutoCommit ( ) ? null : conn . setSavepoint ( ) ; int numRows = execute ( conn , calcSqlInsert ( bo ) , rowMapper . valuesForColumns ( bo , rowMapper . getInsertColumns ( ) ) ) ; DaoResult result = numRows > 0 ? new DaoResult ( DaoOperationStatus . SUCCESSFUL , bo ) : new DaoResult ( DaoOperationStatus . ERROR ) ; if ( numRows > 0 ) { invalidateCache ( bo , CacheInvalidationReason . CREATE ) ; } return result ; } catch ( DuplicatedValueException dke ) { if ( savepoint != null ) { conn . rollback ( savepoint ) ; } return new DaoResult ( DaoOperationStatus . DUPLICATED_VALUE ) ; } } catch ( SQLException e ) { throw new DaoException ( e ) ; } |
public class JXLCellFormatter { /** * ロケールを指定してセルの値をフォーマットする 。
* @ since 0.3
* @ param cell フォーマット対象のセル
* @ param locale フォーマットしたロケール 。 nullでも可能 。
* ロケールに依存する場合 、 指定したロケールにより自動的に切り替わります 。
* @ param isStartDate1904 ファイルの設定が1904年始まりかどうか 。
* { @ link JXLUtils # isDateStart1904 ( jxl . Sheet ) } で値を調べます 。
* @ return フォーマットしたセルの値 。
* @ throws IllegalArgumentException cell is null . */
public CellFormatResult format ( final Cell cell , final Locale locale , final boolean isStartDate1904 ) { } } | ArgUtils . notNull ( cell , "cell" ) ; final Locale runtimeLocale = locale != null ? locale : Locale . getDefault ( ) ; final CellType cellType = cell . getType ( ) ; if ( cellType == CellType . EMPTY ) { final CellFormatResult result = new CellFormatResult ( ) ; result . setCellType ( FormatCellType . Blank ) ; result . setText ( "" ) ; return result ; } else if ( cellType == CellType . LABEL || cellType == CellType . STRING_FORMULA ) { return getCellValue ( cell , runtimeLocale , isStartDate1904 ) ; } else if ( cellType == CellType . BOOLEAN || cellType == CellType . BOOLEAN_FORMULA ) { return getCellValue ( cell , runtimeLocale , isStartDate1904 ) ; } else if ( cellType == CellType . ERROR || cellType == CellType . FORMULA_ERROR ) { return getErrorCellValue ( cell , runtimeLocale , isStartDate1904 ) ; } else if ( cellType == CellType . DATE || cellType == CellType . DATE_FORMULA ) { return getCellValue ( cell , runtimeLocale , isStartDate1904 ) ; } else if ( cellType == CellType . NUMBER || cellType == CellType . NUMBER_FORMULA ) { return getCellValue ( cell , runtimeLocale , isStartDate1904 ) ; } else { final CellFormatResult result = new CellFormatResult ( ) ; result . setCellType ( FormatCellType . Unknown ) ; result . setText ( "" ) ; return result ; } |
public class MineBugHistory { /** * This is how dump ( ) was implemented up to and including version 0.9.5. */
public void dumpXml ( PrintStream out ) { } } | out . println ( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" ) ; out . println ( "<history>" ) ; String startData = " <data " ; String stop = "/>" ; for ( int i = 0 ; i < versionList . length ; ++ i ) { Version version = versionList [ i ] ; AppVersion appVersion = sequenceToAppVersionMap . get ( version . getSequence ( ) ) ; out . print ( " <historyItem " ) ; out . print ( "seq=\"" ) ; out . print ( i ) ; out . print ( "\" " ) ; out . print ( "version=\"" ) ; out . print ( appVersion != null ? appVersion . getReleaseName ( ) : "" ) ; out . print ( "\" " ) ; out . print ( "time=\"" ) ; if ( formatDates ) { out . print ( ( appVersion != null ? new Date ( appVersion . getTimestamp ( ) ) . toString ( ) : "" ) ) ; } else { out . print ( appVersion != null ? appVersion . getTimestamp ( ) : 0L ) ; } out . print ( "\"" ) ; out . println ( ">" ) ; String attributeName [ ] = new String [ TUPLE_SIZE ] ; attributeName [ 0 ] = "added" ; attributeName [ 1 ] = "newCode" ; attributeName [ 2 ] = "fixed" ; attributeName [ 3 ] = "removed" ; attributeName [ 4 ] = "retained" ; attributeName [ 5 ] = "dead" ; attributeName [ 6 ] = "active" ; for ( int j = 0 ; j < TUPLE_SIZE ; ++ j ) { // newCode and retained are already comprised within active
// so we skip tehm
if ( j == 1 || j == 4 ) { continue ; } out . print ( startData + " name=\"" + attributeName [ j ] + "\" value=\"" ) ; out . print ( version . get ( j ) ) ; out . print ( "\"" ) ; out . println ( stop ) ; } out . println ( " </historyItem>" ) ; } out . print ( "</history>" ) ; |
public class CPDefinitionOptionRelPersistenceImpl { /** * Clears the cache for the cp definition option rel .
* The { @ link EntityCache } and { @ link FinderCache } are both cleared by this method . */
@ Override public void clearCache ( CPDefinitionOptionRel cpDefinitionOptionRel ) { } } | entityCache . removeResult ( CPDefinitionOptionRelModelImpl . ENTITY_CACHE_ENABLED , CPDefinitionOptionRelImpl . class , cpDefinitionOptionRel . getPrimaryKey ( ) ) ; finderCache . clearCache ( FINDER_CLASS_NAME_LIST_WITH_PAGINATION ) ; finderCache . clearCache ( FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION ) ; clearUniqueFindersCache ( ( CPDefinitionOptionRelModelImpl ) cpDefinitionOptionRel , true ) ; |
public class AVIMConversation { /** * 设置当前聊天对话的属性
* @ param attr
* @ since 3.0 */
public void setAttributes ( Map < String , Object > attr ) { } } | pendingAttributes . clear ( ) ; pendingAttributes . putAll ( attr ) ; |
public class MonitorAndManagementSettings { /** * Creates a new instance of MonitorAndManagementSettings from a classpath
* resource xml settings file .
* @ param settingsXml Path of a classpath resource xml settings file
* @ return a new instance of { @ link # MonitorAndManagementSettings }
* @ throws java . io . IOException
* @ throws javax . xml . bind . JAXBException */
public static MonitorAndManagementSettings newInstance ( String settingsXml ) throws JAXBException { } } | InputStream istream = MonitorAndManagementSettings . class . getResourceAsStream ( settingsXml ) ; JAXBContext ctx = JAXBContext . newInstance ( MonitorAndManagementSettings . class ) ; return ( MonitorAndManagementSettings ) ctx . createUnmarshaller ( ) . unmarshal ( istream ) ; |
public class Frame { /** * Makes the given { @ link MethodWriter } visit the input frame of this { @ link Frame } . The visit is
* done with the { @ link MethodWriter # visitFrameStart } , { @ link MethodWriter # visitAbstractType } and
* { @ link MethodWriter # visitFrameEnd } methods .
* @ param methodWriter the { @ link MethodWriter } that should visit the input frame of this { @ link
* Frame } . */
final void accept ( final MethodWriter methodWriter ) { } } | // Compute the number of locals , ignoring TOP types that are just after a LONG or a DOUBLE , and
// all trailing TOP types .
int [ ] localTypes = inputLocals ; int nLocal = 0 ; int nTrailingTop = 0 ; int i = 0 ; while ( i < localTypes . length ) { int localType = localTypes [ i ] ; i += ( localType == LONG || localType == DOUBLE ) ? 2 : 1 ; if ( localType == TOP ) { nTrailingTop ++ ; } else { nLocal += nTrailingTop + 1 ; nTrailingTop = 0 ; } } // Compute the stack size , ignoring TOP types that are just after a LONG or a DOUBLE .
int [ ] stackTypes = inputStack ; int nStack = 0 ; i = 0 ; while ( i < stackTypes . length ) { int stackType = stackTypes [ i ] ; i += ( stackType == LONG || stackType == DOUBLE ) ? 2 : 1 ; nStack ++ ; } // Visit the frame and its content .
int frameIndex = methodWriter . visitFrameStart ( owner . bytecodeOffset , nLocal , nStack ) ; i = 0 ; while ( nLocal -- > 0 ) { int localType = localTypes [ i ] ; i += ( localType == LONG || localType == DOUBLE ) ? 2 : 1 ; methodWriter . visitAbstractType ( frameIndex ++ , localType ) ; } i = 0 ; while ( nStack -- > 0 ) { int stackType = stackTypes [ i ] ; i += ( stackType == LONG || stackType == DOUBLE ) ? 2 : 1 ; methodWriter . visitAbstractType ( frameIndex ++ , stackType ) ; } methodWriter . visitFrameEnd ( ) ; |
public class DateMath { /** * Use this instead of Instant . toString ( ) to ensure you always end up with the same pattern instead of ' smartly '
* loosing fractionals depending on what time it is .
* @ param date
* an instant
* @ return iso instant of the form " 1974-10-20T00:00:00.000Z " with 3 fractionals , always . */
public static String formatIsoDate ( Instant date ) { } } | return CONSISTENT_ISO_INSTANT . format ( date . atZone ( ZoneOffset . UTC ) ) ; |
public class BarcodeCodabar { /** * Creates the bars .
* @ param text the text to create the bars
* @ return the bars */
public static byte [ ] getBarsCodabar ( String text ) { } } | text = text . toUpperCase ( ) ; int len = text . length ( ) ; if ( len < 2 ) throw new IllegalArgumentException ( "Codabar must have at least a start and stop character." ) ; if ( CHARS . indexOf ( text . charAt ( 0 ) ) < START_STOP_IDX || CHARS . indexOf ( text . charAt ( len - 1 ) ) < START_STOP_IDX ) throw new IllegalArgumentException ( "Codabar must have one of 'ABCD' as start/stop character." ) ; byte bars [ ] = new byte [ text . length ( ) * 8 - 1 ] ; for ( int k = 0 ; k < len ; ++ k ) { int idx = CHARS . indexOf ( text . charAt ( k ) ) ; if ( idx >= START_STOP_IDX && k > 0 && k < len - 1 ) throw new IllegalArgumentException ( "In codabar, start/stop characters are only allowed at the extremes." ) ; if ( idx < 0 ) throw new IllegalArgumentException ( "The character '" + text . charAt ( k ) + "' is illegal in codabar." ) ; System . arraycopy ( BARS [ idx ] , 0 , bars , k * 8 , 7 ) ; } return bars ; |
public class OpenSSLKey { /** * Decrypts the private key with given password .
* Does nothing if the key is not encrypted .
* @ param password password to decrypt the key with .
* @ throws GeneralSecurityException whenever an error occurs during decryption . */
public void decrypt ( byte [ ] password ) throws GeneralSecurityException { } } | if ( ! isEncrypted ( ) ) { return ; } byte [ ] enc = Base64 . decode ( this . encodedKey ) ; SecretKeySpec key = getSecretKey ( password , this . initializationVector . getIV ( ) ) ; Cipher cipher = getCipher ( ) ; cipher . init ( Cipher . DECRYPT_MODE , key , this . initializationVector ) ; enc = cipher . doFinal ( enc ) ; this . intKey = getKey ( this . keyAlg , enc ) ; this . keyData = enc ; this . isEncrypted = false ; this . encodedKey = null ; |
public class CPAttachmentFileEntryLocalServiceBaseImpl { /** * Creates a new cp attachment file entry with the primary key . Does not add the cp attachment file entry to the database .
* @ param CPAttachmentFileEntryId the primary key for the new cp attachment file entry
* @ return the new cp attachment file entry */
@ Override @ Transactional ( enabled = false ) public CPAttachmentFileEntry createCPAttachmentFileEntry ( long CPAttachmentFileEntryId ) { } } | return cpAttachmentFileEntryPersistence . create ( CPAttachmentFileEntryId ) ; |
public class RungeKuttaFelberg { /** * Writes ( in ascii format ) to a specified file the values of the function described by
* differential equations in the the intermidia steps requested to go from the Initial to the
* Final time . This method is very specific for solving equations of flow in a network . It
* prints output for the flow component at all locations .
* @ param intervalStartTimeInMinutes The initial time of the solution
* @ param intervalEndTimeInMinutes The final time of the solution
* @ param timeStepInMinutes How often the values are desired
* @ param initialConditions The value of the initial condition
* @ param etpArray */
@ SuppressWarnings ( "nls" ) public void solve ( DateTime currentTimstamp , int modelTimestepInMinutes , double internalTimestepInMinutes , double [ ] initialConditions , double [ ] rainArray , double [ ] etpArray ) throws IOException { } } | isAtFinalSubtimestep = false ; double intervalStartTimeInMinutes = currentTimstamp . getMillis ( ) / 1000d / 60d ; double intervalEndTimeInMinutes = intervalStartTimeInMinutes + modelTimestepInMinutes ; // the running time inside the interval
double currentTimeInMinutes = intervalStartTimeInMinutes ; // the end time inside the interval
double targetTimeInMinutes = intervalStartTimeInMinutes ; // the object holding the iterated solution and internal timestep
CurrentTimestepSolution currentSolution = new CurrentTimestepSolution ( ) ; while ( currentTimeInMinutes < intervalEndTimeInMinutes ) { /* * split the user set time interval into smaller intervals of time timeStepInMinutes . */
targetTimeInMinutes = currentTimeInMinutes + internalTimestepInMinutes ; while ( currentTimeInMinutes < targetTimeInMinutes ) { /* * inside step the intervals of time timeStepInMinutes are splitted again in
* intervals that begin with basicTimeStepInMinutes and are changed while iteration . */
step ( currentTimeInMinutes , initialConditions , basicTimeStepInMinutes , false , currentSolution , rainArray , etpArray ) ; if ( currentTimeInMinutes + currentSolution . newTimeStepInMinutes > targetTimeInMinutes ) { break ; } basicTimeStepInMinutes = currentSolution . newTimeStepInMinutes ; currentTimeInMinutes += basicTimeStepInMinutes ; currentSolution . newTimeStepInMinutes = currentTimeInMinutes ; initialConditions = currentSolution . solution ; for ( int i = 0 ; i < initialConditions . length ; i ++ ) { if ( initialConditions [ i ] != initialConditions [ i ] ) { throw new ModelsIllegalargumentException ( "Problems occure during the integration procedure." , this . getClass ( ) . getSimpleName ( ) ) ; } } } if ( Math . abs ( targetTimeInMinutes - intervalEndTimeInMinutes ) < .0000001 ) { break ; } step ( currentTimeInMinutes , initialConditions , targetTimeInMinutes - currentTimeInMinutes , true , currentSolution , rainArray , etpArray ) ; if ( currentTimeInMinutes + currentSolution . newTimeStepInMinutes >= intervalEndTimeInMinutes ) { break ; } if ( initialConditions [ 0 ] < 1e-3 ) { System . out . println ( "Discharge in outlet less than the threshold." ) ; break ; } basicTimeStepInMinutes = currentSolution . newTimeStepInMinutes ; currentTimeInMinutes += basicTimeStepInMinutes ; currentSolution . newTimeStepInMinutes = currentTimeInMinutes ; initialConditions = currentSolution . solution ; for ( int i = 0 ; i < initialConditions . length ; i ++ ) { if ( initialConditions [ i ] != initialConditions [ i ] ) { throw new ModelsIllegalargumentException ( "Problems occure during the integration procedure." , this . getClass ( ) . getSimpleName ( ) ) ; } } if ( doLog ) { outputStream . message ( "-> " + new DateTime ( ( long ) ( currentTimeInMinutes * 60.0 * 1000.0 ) ) . toString ( OmsAdige . adigeFormatter ) + " / " + new DateTime ( ( long ) ( intervalEndTimeInMinutes * 60. * 1000. ) ) . toString ( OmsAdige . adigeFormatter ) + " Outlet Duffy Discharge: " + initialConditions [ 0 ] ) ; } // int hillslopeNum = rainArray . length ;
// for ( int i = 0 ; i < hillslopeNum ; i + + ) {
// System . out . println ( i + " Discharge " + initialConditions [ i ] + " qsub "
// + initialConditions [ i + hillslopeNum ] + " S1 "
// + initialConditions [ i + 2 * hillslopeNum ] + " S2 "
// + initialConditions [ i + 3 * hillslopeNum ] + " rain " + rainArray [ i ] ) ;
// System . out . println ( " - - - - - " ) ;
// double avg = 0.0;
// for ( int i = 0 ; i < rainArray . length ; i + + ) {
// avg = avg + rainArray [ i ] ;
// avg = avg / rainArray . length ;
// System . out . println ( " Outlet Discharge " + initialConditions [ 0 ] + " qsub "
// + initialConditions [ hillslopeNum ] + " S1 "
// + initialConditions [ 2 * hillslopeNum ] + " S2 "
// + initialConditions [ 3 * hillslopeNum ] + " rain " + avg ) ;
} isAtFinalSubtimestep = true ; if ( NumericsUtilities . dEq ( currentTimeInMinutes , intervalEndTimeInMinutes ) && initialConditions [ 0 ] > 1e-3 ) { step ( currentTimeInMinutes , initialConditions , intervalEndTimeInMinutes - currentTimeInMinutes - 1. / 60. , true , currentSolution , rainArray , etpArray ) ; basicTimeStepInMinutes = currentSolution . newTimeStepInMinutes ; currentTimeInMinutes += basicTimeStepInMinutes ; currentSolution . newTimeStepInMinutes = currentTimeInMinutes ; initialConditions = currentSolution . solution ; for ( int i = 0 ; i < initialConditions . length ; i ++ ) { if ( initialConditions [ i ] != initialConditions [ i ] ) { throw new ModelsIllegalargumentException ( "Problems occure during the integration procedure." , this . getClass ( ) . getSimpleName ( ) ) ; } } double sum = 0 ; for ( double d : rainArray ) { sum = sum + d ; } sum = sum / rainArray . length ; int hillslopeNum = rainArray . length ; double currentDischarge = initialConditions [ 0 ] + initialConditions [ hillslopeNum ] ; outputStream . message ( "-> " + new DateTime ( ( long ) ( currentTimeInMinutes * 60.0 * 1000.0 ) ) . toString ( OmsAdige . adigeFormatter ) + " / " + new DateTime ( ( long ) ( intervalEndTimeInMinutes * 60. * 1000. ) ) . toString ( OmsAdige . adigeFormatter ) + " " + currentDischarge + " with avg rain: " + sum ) ; } else { outputStream . errorMessage ( "WARNING, UNEXPECTED" ) ; } finalCond = initialConditions ; |
public class Options { /** * Returns the given option value .
* @ param key
* the option name .
* @ return the complex option */
public IComplexOption getComplexOption ( String key ) { } } | Object object = this . options . get ( key ) ; if ( object instanceof IComplexOption ) return ( IComplexOption ) object ; return null ; |
public class WorkflowDemoNERD { /** * Sometimes , you might already be using Stanford NER elsewhere in
* your application , and you ' d like to just pass the output from
* Stanford NER directly into CLAVIN , without having to re - run the
* input through Stanford NER just to use CLAVIN . This example
* shows you how to very easily do exactly that .
* @ throws IOException
* @ throws ClavinException */
private static void resolveStanfordEntities ( ) throws IOException , ClavinException { } } | /* * Start with Stanford NER - - no need to get CLAVIN involved for now . */
// instantiate Stanford NER entity extractor
InputStream mpis = WorkflowDemoNERD . class . getClassLoader ( ) . getResourceAsStream ( "models/english.all.3class.distsim.prop" ) ; Properties mp = new Properties ( ) ; mp . load ( mpis ) ; AbstractSequenceClassifier < CoreMap > namedEntityRecognizer = CRFClassifier . getJarClassifier ( "/models/english.all.3class.distsim.crf.ser.gz" , mp ) ; // Unstructured text file about Somalia to be geoparsed
File inputFile = new File ( "src/test/resources/sample-docs/Somalia-doc.txt" ) ; // Grab the contents of the text file as a String
String inputString = TextUtils . fileToString ( inputFile ) ; // extract entities from input text using Stanford NER
List < Triple < String , Integer , Integer > > entitiesFromNER = namedEntityRecognizer . classifyToCharacterOffsets ( inputString ) ; /* * Now , CLAVIN comes into play . . . */
// convert Stanford NER output to ClavinLocationResolver input
List < LocationOccurrence > locationsForCLAVIN = convertNERtoCLAVIN ( entitiesFromNER , inputString ) ; // instantiate the CLAVIN location resolver
ClavinLocationResolver clavinLocationResolver = new ClavinLocationResolver ( new LuceneGazetteer ( new File ( "./IndexDirectory" ) ) ) ; // resolve location entities extracted from input text
List < ResolvedLocation > resolvedLocations = clavinLocationResolver . resolveLocations ( locationsForCLAVIN , 1 , 1 , false ) ; // Display the ResolvedLocations found for the location names
for ( ResolvedLocation resolvedLocation : resolvedLocations ) System . out . println ( resolvedLocation ) ; |
public class ColorPickerPalette { /** * Appends a swatch to the end of the row for even - numbered rows ( starting with row 0 ) ,
* to the beginning of a row for odd - numbered rows . */
private void addSwatchToRow ( TableRow row , View swatch , int rowNumber ) { } } | if ( rowNumber % 2 == 0 ) { row . addView ( swatch ) ; } else { row . addView ( swatch , 0 ) ; } |
public class MemberSummaryBuilder { /** * Test whether the method is a getter .
* @ param element property method documentation . Needs to be either property
* method , property getter , or property setter .
* @ return true if the given documentation belongs to a getter . */
private boolean isGetter ( Element element ) { } } | final String pedName = element . getSimpleName ( ) . toString ( ) ; return pedName . startsWith ( "get" ) || pedName . startsWith ( "is" ) ; |
public class HashBiMap { /** * Constructs a new , empty bimap with the specified expected size .
* @ param expectedSize the expected number of entries
* @ throws IllegalArgumentException if the specified expected size is negative */
public static < K , V > HashBiMap < K , V > create ( int expectedSize ) { } } | return new HashBiMap < K , V > ( expectedSize ) ; |
public class Util { /** * Decode an X509 certificate chain .
* @ param codec The codec to do the decoding of the Any .
* @ param encodedCertChain The codec encoded byte [ ] containing the X509 certificate chain .
* @ return the X509 certificate chain
* @ throws SASException */
@ SuppressWarnings ( "unchecked" ) @ Sensitive public static X509Certificate [ ] decodeCertChain ( Codec codec , @ Sensitive byte [ ] encodedCertChain ) throws SASException { } } | X509Certificate [ ] certificateChain = null ; try { Any any = codec . decode_value ( encodedCertChain , X509CertificateChainHelper . type ( ) ) ; byte [ ] decodedCertificateChain = X509CertificateChainHelper . extract ( any ) ; CertificateFactory certificateFactory = CertificateFactory . getInstance ( "X.509" ) ; ByteArrayInputStream bais = new ByteArrayInputStream ( decodedCertificateChain ) ; CertPath certPath = certificateFactory . generateCertPath ( bais ) ; List < X509Certificate > certificates = ( List < X509Certificate > ) certPath . getCertificates ( ) ; certificateChain = new X509Certificate [ certificates . size ( ) ] ; for ( int i = 0 ; i < certificates . size ( ) ; i ++ ) { certificateChain [ i ] = certificates . get ( i ) ; } } catch ( Exception e ) { throw new SASException ( 1 , e ) ; } return certificateChain ; |
public class ConvertorHelper { /** * 根据class获取对应的convertor
* @ return */
public Convertor getConvertor ( Class src , Class dest ) { } } | if ( src == dest ) { // 对相同类型的直接忽略 , 不做转换
return null ; } // 按照src - > dest来取映射
Convertor convertor = repository . getConvertor ( src , dest ) ; // 处理下Array | Collection的映射
// 如果src | dest是array类型 , 取一下Array . class的映射 , 因为默认数组处理的注册直接注册了Array . class
boolean isSrcArray = src . isArray ( ) ; boolean isDestArray = dest . isArray ( ) ; if ( convertor == null && src . isArray ( ) && dest . isArray ( ) ) { convertor = arrayToArray ; } else { boolean isSrcCollection = Collection . class . isAssignableFrom ( src ) ; boolean isDestCollection = Collection . class . isAssignableFrom ( dest ) ; if ( convertor == null && isSrcArray && isDestCollection ) { convertor = arrayToCollection ; } if ( convertor == null && isDestArray && isSrcCollection ) { convertor = collectionToArray ; } if ( convertor == null && isSrcCollection && isDestCollection ) { convertor = collectionToCollection ; } } // 如果dest是string , 获取一下object - > string . ( 系统默认注册了一个Object . class - > String . class的转化 )
if ( convertor == null && dest == String . class ) { if ( src . isEnum ( ) ) { // 如果是枚举
convertor = enumToString ; } else { // 默认进行toString输出
convertor = objectToString ; } } // 如果是其中一个是String类
if ( convertor == null && src == String . class ) { if ( commonTypes . containsKey ( dest ) ) { // 另一个是Common类型
convertor = stringToCommon ; } else if ( dest . isEnum ( ) ) { // 另一个是枚举对象
convertor = stringToEnum ; } } // 如果src / dest都是Common类型 , 进行特殊处理
if ( convertor == null && commonTypes . containsKey ( src ) && commonTypes . containsKey ( dest ) ) { convertor = commonToCommon ; } return convertor ; |
public class ConnectedIconsProvider { /** * Initializes the connected icons . < br >
* Fills up the { @ link # icons } array . */
protected void initializeIcons ( ) { } } | float f = 1F / 3F ; icons [ LEFT | TOP ] = part1 . copy ( ) . clip ( 0 , 0 , f , f ) ; icons [ TOP ] = part1 . copy ( ) . clip ( f , 0 , f , f ) ; icons [ RIGHT | TOP ] = part1 . copy ( ) . clip ( 2 * f , 0 , f , f ) ; icons [ LEFT ] = part1 . copy ( ) . clip ( 0 , f , f , f ) ; icons [ NONE ] = part1 . copy ( ) . clip ( f , f , f , f ) ; icons [ RIGHT ] = part1 . copy ( ) . clip ( 2 * f , f , f , f ) ; icons [ LEFT | BOTTOM ] = part1 . copy ( ) . clip ( 0 , 2 * f , f , f ) ; icons [ BOTTOM ] = part1 . copy ( ) . clip ( f , 2 * f , f , f ) ; icons [ RIGHT | BOTTOM ] = part1 . copy ( ) . clip ( 2 * f , 2 * f , f , f ) ; icons [ LEFT | TOP | BOTTOM ] = part2 . copy ( ) . clip ( 0 , 0 , f , f ) ; icons [ TOP | BOTTOM ] = part2 . copy ( ) . clip ( f , 0 , f , f ) ; icons [ LEFT | RIGHT | TOP ] = part2 . copy ( ) . clip ( 2 * f , 0 , f , f ) ; icons [ LEFT | RIGHT ] = part2 . copy ( ) . clip ( 0 , f , f , f ) ; icons [ FULL ] = part2 . copy ( ) . clip ( f , f , f , f ) ; // icons [ LEFT | RIGHT ] = icon . copy ( ) . clip ( 2 * f , f , f , f ) ;
icons [ LEFT | RIGHT | BOTTOM ] = part2 . copy ( ) . clip ( 0 , 2 * f , f , f ) ; // icons [ TOP | BOTTOM ] = icon . copy ( ) . clip ( f , 2 * f , f , f ) ;
icons [ RIGHT | TOP | BOTTOM ] = part2 . copy ( ) . clip ( 2 * f , 2 * f , f , f ) ; initialized = true ; |
public class DescribeImagesExample { /** * Describe all available AMIs within aws - mock .
* @ return a list of AMIs */
public static List < Image > describeAllImages ( ) { } } | // pass any credentials as aws - mock does not authenticate them at all
AWSCredentials credentials = new BasicAWSCredentials ( "foo" , "bar" ) ; AmazonEC2Client amazonEC2Client = new AmazonEC2Client ( credentials ) ; // the mock endpoint for ec2 which runs on your computer
String ec2Endpoint = "http://localhost:8000/aws-mock/ec2-endpoint/" ; amazonEC2Client . setEndpoint ( ec2Endpoint ) ; // describe all AMIs in aws - mock .
DescribeImagesResult result = amazonEC2Client . describeImages ( ) ; return result . getImages ( ) ; |
public class LicenseClient { /** * Sets the access control policy on the specified resource . Replaces any existing policy .
* < p > Sample code :
* < pre > < code >
* try ( LicenseClient licenseClient = LicenseClient . create ( ) ) {
* ProjectGlobalLicenseResourceName resource = ProjectGlobalLicenseResourceName . of ( " [ PROJECT ] " , " [ RESOURCE ] " ) ;
* GlobalSetPolicyRequest globalSetPolicyRequestResource = GlobalSetPolicyRequest . newBuilder ( ) . build ( ) ;
* Policy response = licenseClient . setIamPolicyLicense ( resource . toString ( ) , globalSetPolicyRequestResource ) ;
* < / code > < / pre >
* @ param resource Name or id of the resource for this request .
* @ param globalSetPolicyRequestResource
* @ throws com . google . api . gax . rpc . ApiException if the remote call fails */
@ BetaApi public final Policy setIamPolicyLicense ( String resource , GlobalSetPolicyRequest globalSetPolicyRequestResource ) { } } | SetIamPolicyLicenseHttpRequest request = SetIamPolicyLicenseHttpRequest . newBuilder ( ) . setResource ( resource ) . setGlobalSetPolicyRequestResource ( globalSetPolicyRequestResource ) . build ( ) ; return setIamPolicyLicense ( request ) ; |
public class SearchQuery { /** * Converts the human readable string to the proper enum
* @ param type The string to parse
* @ return The parsed enum
* @ throws IllegalArgumentException if the type is missing or wsa not
* recognized */
public static SearchType parseSearchType ( final String type ) { } } | if ( type == null || type . isEmpty ( ) ) { throw new IllegalArgumentException ( "Type provided was null or empty" ) ; } if ( type . toLowerCase ( ) . equals ( "tsmeta" ) ) { return SearchType . TSMETA ; } else if ( type . toLowerCase ( ) . equals ( "tsmeta_summary" ) ) { return SearchType . TSMETA_SUMMARY ; } else if ( type . toLowerCase ( ) . equals ( "tsuids" ) ) { return SearchType . TSUIDS ; } else if ( type . toLowerCase ( ) . equals ( "uidmeta" ) ) { return SearchType . UIDMETA ; } else if ( type . toLowerCase ( ) . equals ( "annotation" ) ) { return SearchType . ANNOTATION ; } else if ( type . toLowerCase ( ) . equals ( "lookup" ) ) { return SearchType . LOOKUP ; } else { throw new IllegalArgumentException ( "Unknown type: " + type ) ; } |
public class MoreObjects { /** * { @ link Class # getSimpleName ( ) } is not GWT compatible yet , so we
* provide our own implementation . */
private static String simpleName ( Class < ? > clazz ) { } } | String name = clazz . getName ( ) ; // the nth anonymous class has a class name ending in " Outer $ n "
// and local inner classes have names ending in " Outer . $ 1Inner "
name = name . replaceAll ( "\\$[0-9]+" , "\\$" ) ; // we want the name of the inner class all by its lonesome
int start = name . lastIndexOf ( '$' ) ; // if this isn ' t an inner class , just find the start of the
// top level class name .
if ( start == - 1 ) { start = name . lastIndexOf ( '.' ) ; } return name . substring ( start + 1 ) ; |
public class BuilderFactory { /** * Return an instance of the field builder for the given class .
* @ return an instance of the field builder for the given class . */
public AbstractBuilder getFieldBuilder ( ClassWriter classWriter ) throws Exception { } } | return FieldBuilder . getInstance ( context , classWriter . getClassDoc ( ) , writerFactory . getFieldWriter ( classWriter ) ) ; |
public class NetworkUtil { /** * Convert a string URI to an object URI .
* < p > This function support the syntax " : * " for the port .
* @ param uri the string representation of the URI to parse .
* @ return the URI .
* @ throws URISyntaxException - if the given string has invalid format . */
public static URI toURI ( String uri ) throws URISyntaxException { } } | final URI u = new URI ( uri ) ; // Inspired by ZeroMQ
String adr = u . getAuthority ( ) ; if ( adr == null ) { adr = u . getPath ( ) ; } if ( adr != null && adr . endsWith ( ":*" ) ) { // $ NON - NLS - 1 $
return new URI ( u . getScheme ( ) , u . getUserInfo ( ) , adr . substring ( 0 , adr . length ( ) - 2 ) , - 1 , null , u . getQuery ( ) , u . getFragment ( ) ) ; } return u ; |
public class ConstructorWriterImpl { /** * { @ inheritDoc } */
public String [ ] getSummaryTableHeader ( ProgramElementDoc member ) { } } | String [ ] header ; if ( foundNonPubConstructor ) { header = new String [ ] { configuration . getText ( "doclet.Modifier" ) , configuration . getText ( "doclet.0_and_1" , configuration . getText ( "doclet.Constructor" ) , configuration . getText ( "doclet.Description" ) ) } ; } else { header = new String [ ] { configuration . getText ( "doclet.0_and_1" , configuration . getText ( "doclet.Constructor" ) , configuration . getText ( "doclet.Description" ) ) } ; } return header ; |
public class ConversionAnalyzer { /** * Checks for the existence of a conversion method .
* @ param destination destination field
* @ param source source field
* @ return true if the conversion method exists , false otherwise */
public boolean fieldsToCheck ( Field destination , Field source ) { } } | destinationName = destination . getName ( ) ; sourceName = source . getName ( ) ; if ( ! xml . conversionsLoad ( ) . isEmpty ( ) ) { configurationType = XML ; if ( config == DESTINATION ) { if ( existsXmlConversion ( destinationClass ) ) { membership = Membership . DESTINATION ; return true ; } if ( existsXmlConversion ( sourceClass ) ) { membership = Membership . SOURCE ; return true ; } } else { if ( existsXmlConversion ( sourceClass ) ) { membership = Membership . SOURCE ; return true ; } if ( existsXmlConversion ( destinationClass ) ) { membership = Membership . DESTINATION ; return true ; } } } configurationType = ANNOTATION ; if ( config == DESTINATION ) { if ( existsAnnotatedConversion ( destinationClass ) ) { membership = Membership . DESTINATION ; return true ; } if ( existsAnnotatedConversion ( sourceClass ) ) { membership = Membership . SOURCE ; return true ; } } else { if ( existsAnnotatedConversion ( sourceClass ) ) { membership = Membership . SOURCE ; return true ; } if ( existsAnnotatedConversion ( destinationClass ) ) { membership = Membership . DESTINATION ; return true ; } } return false ; |
public class AmazonIdentityManagementClient { /** * Sets the specified version of the global endpoint token as the token version used for the AWS account .
* By default , AWS Security Token Service ( STS ) is available as a global service , and all STS requests go to a
* single endpoint at < code > https : / / sts . amazonaws . com < / code > . AWS recommends using Regional STS endpoints to reduce
* latency , build in redundancy , and increase session token availability . For information about Regional endpoints
* for STS , see < a href = " https : / / docs . aws . amazon . com / general / latest / gr / rande . html # sts _ region " > AWS Regions and
* Endpoints < / a > in the < i > AWS General Reference < / i > .
* If you make an STS call to the global endpoint , the resulting session tokens might be valid in some Regions but
* not others . It depends on the version that is set in this operation . Version 1 tokens are valid only in AWS
* Regions that are available by default . These tokens do not work in manually enabled Regions , such as Asia Pacific
* ( Hong Kong ) . Version 2 tokens are valid in all Regions . However , version 2 tokens are longer and might affect
* systems where you temporarily store tokens . For information , see < a
* href = " https : / / docs . aws . amazon . com / IAM / latest / UserGuide / id _ credentials _ temp _ enable - regions . html " > Activating and
* Deactivating STS in an AWS Region < / a > in the < i > IAM User Guide < / i > .
* To view the current session token version , see the < code > GlobalEndpointTokenVersion < / code > entry in the response
* of the < a > GetAccountSummary < / a > operation .
* @ param setSecurityTokenServicePreferencesRequest
* @ return Result of the SetSecurityTokenServicePreferences operation returned by the service .
* @ throws ServiceFailureException
* The request processing has failed because of an unknown error , exception or failure .
* @ sample AmazonIdentityManagement . SetSecurityTokenServicePreferences
* @ see < a href = " http : / / docs . aws . amazon . com / goto / WebAPI / iam - 2010-05-08 / SetSecurityTokenServicePreferences "
* target = " _ top " > AWS API Documentation < / a > */
@ Override public SetSecurityTokenServicePreferencesResult setSecurityTokenServicePreferences ( SetSecurityTokenServicePreferencesRequest request ) { } } | request = beforeClientExecution ( request ) ; return executeSetSecurityTokenServicePreferences ( request ) ; |
public class BaasAsset { /** * Asynchronously retrieves named assets data ,
* If the named asset is a document , the document is retrieved
* otherwise attached data to the file are returned .
* @ param id the name of the asset
* @ param flags used for the request a bit or of { @ link RequestOptions } constants
* @ param handler an handler that will be handed the response
* @ return a request token */
public static RequestToken fetchData ( String id , int flags , BaasHandler < JsonObject > handler ) { } } | if ( id == null ) throw new IllegalArgumentException ( "asset id cannot be null" ) ; BaasBox box = BaasBox . getDefaultChecked ( ) ; AssetDataRequest req = new AssetDataRequest ( box , id , flags , handler ) ; return box . submitAsync ( req ) ; |
public class CmsADEManager { /** * Saves the inheritance container information . < p >
* @ param cms the current cms context
* @ param pageResource the resource or parent folder
* @ param name the inheritance name
* @ param newOrder if the element have been reordered
* @ param elements the elements
* @ throws CmsException if something goes wrong */
public void saveInheritedContainer ( CmsObject cms , CmsResource pageResource , String name , boolean newOrder , List < CmsContainerElementBean > elements ) throws CmsException { } } | CmsContainerConfigurationWriter writer = new CmsContainerConfigurationWriter ( ) ; writer . save ( cms , name , newOrder , pageResource , elements ) ; // Inheritance groups are usually reloaded directly after saving them ,
// so the cache needs to be up to date after this method is called
m_offlineContainerConfigurationCache . flushUpdates ( ) ; |
public class CmsDocumentDependency { /** * Adds another language version document dependency to this document . < p >
* @ param dep the language version document dependency to add */
public void addVariant ( CmsDocumentDependency dep ) { } } | // check if already exists
for ( CmsDocumentDependency lang : m_variants ) { if ( lang . getLocale ( ) . equals ( dep . getLocale ( ) ) ) { return ; } } dep . setType ( DependencyType . variant ) ; m_variants . add ( dep ) ; addDependency ( dep ) ; |
public class ProducerSessionProxy { /** * Proxies the identically named method on the server .
* Sends the msg to the Destination specified in the createProducerSessionCall .
* Optionally , a transaction may be supplied . Optionally , a QualityOfService may
* be supplied , which must be no stronger than that of the Destination ( otherwise
* an exception is thrown ) . If a QualityOfService is supplied then the Mesasge
* Processor will implement delivery semantics no weaker than those of the send
* call and no stronger than those of the Destination .
* @ param msg
* @ param tran
* @ throws com . ibm . wsspi . sib . core . exception . SISessionUnavailableException
* @ throws com . ibm . wsspi . sib . core . exception . SISessionDroppedException
* @ throws com . ibm . wsspi . sib . core . exception . SIConnectionUnavailableException
* @ throws com . ibm . wsspi . sib . core . exception . SIConnectionDroppedException
* @ throws com . ibm . websphere . sib . exception . SIResourceException
* @ throws com . ibm . wsspi . sib . core . exception . SIConnectionLostException
* @ throws com . ibm . wsspi . sib . core . exception . SILimitExceededException
* @ throws com . ibm . websphere . sib . exception . SIErrorException
* @ throws com . ibm . wsspi . sib . core . exception . SINotAuthorizedException
* @ throws com . ibm . websphere . sib . exception . SIIncorrectCallException
* @ throws com . ibm . websphere . sib . exception . SINotPossibleInCurrentConfigurationException */
public void send ( SIBusMessage msg , SITransaction tran ) throws SISessionUnavailableException , SISessionDroppedException , SIConnectionUnavailableException , SIConnectionDroppedException , SIResourceException , SIConnectionLostException , SILimitExceededException , SIErrorException , SINotAuthorizedException , SIIncorrectCallException , SINotPossibleInCurrentConfigurationException { } } | if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . entry ( this , tc , "send" , new Object [ ] { msg , tran } ) ; try { closeLock . readLock ( ) . lockInterruptibly ( ) ; try { checkAlreadyClosed ( ) ; // XCT Instrumentation for SIBus
// lohith liberty change
/* if ( XctSettings . isAnyEnabled ( ) )
Xct xct = Xct . current ( ) ;
if ( xct . annotationsEnabled ( ) )
Annotation annotation = new Annotation ( XctJmsConstants . XCT _ SIBUS ) . add ( XctJmsConstants . XCT _ PROXY _ SEND ) ;
annotation . associate ( XctJmsConstants . XCT _ DEST _ NAME , getDestinationAddress ( ) . getDestinationName ( ) ) ;
annotation . add ( new Annotation ( XctJmsConstants . XCT _ DEST _ TYPE ) . add ( destType . toString ( ) ) ) ;
String transacted = XctJmsConstants . XCT _ TRANSACTED _ FALSE ;
if ( tran ! = null )
transacted = XctJmsConstants . XCT _ TRANSACTED _ TRUE ;
annotation . add ( new Annotation ( XctJmsConstants . XCT _ TRANSACTED ) . add ( transacted ) ) ;
annotation . add ( new Annotation ( XctJmsConstants . XCT _ RELIABILITY ) . add ( msg . getReliability ( ) . toString ( ) ) ) ;
xct . begin ( annotation ) ;
else
xct . begin ( ) ;
String xctCorrelationIDString = Xct . current ( ) . toString ( ) ;
msg . setXctCorrelationID ( xctCorrelationIDString ) ; */
// Now we need to synchronise on the transaction object if there is one .
if ( tran != null ) { synchronized ( tran ) { // Check transaction is in a valid state .
// Enlisted for an XA UOW and not rolledback or
// completed for a local transaction .
if ( ! ( ( Transaction ) tran ) . isValid ( ) ) { throw new SIIncorrectCallException ( nls . getFormattedMessage ( "TRANSACTION_COMPLETE_SICO1022" , null , null ) ) ; } _send ( msg , tran ) ; } } else { _send ( msg , null ) ; } // lohith liberty change
/* if ( XctSettings . isAnyEnabled ( ) )
Xct xct = Xct . current ( ) ;
if ( xct . annotationsEnabled ( ) )
Annotation annotation = new Annotation ( XctJmsConstants . XCT _ SIBUS ) . add ( XctJmsConstants . XCT _ PROXY _ SEND ) ;
xct . end ( annotation ) ;
else
xct . end ( ) ; */
} finally { closeLock . readLock ( ) . unlock ( ) ; } } catch ( InterruptedException e ) { // No FFDC code needed
} if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . exit ( this , tc , "send" ) ; |
public class ExpressionsParser { /** * TODO add checks to see if an LHS that isn ' t valid for assignment shows up as a syntax error of some sort , e . g . a . b ( ) = 2; */
Rule assignmentExpression ( ) { } } | return Sequence ( assignmentLHS ( ) , set ( ) , assignmentOperator ( ) . label ( "operator" ) , group . basics . optWS ( ) , assignmentExpressionChaining ( ) . label ( "RHS" ) , set ( actions . createAssignmentExpression ( value ( ) , text ( "operator" ) , lastValue ( ) ) ) ) ; |
public class Sneaky { /** * Wrap a { @ link org . jooq . lambda . fi . util . function . CheckedBiFunction } in a { @ link BiFunction } .
* Example :
* < code > < pre >
* map . computeIfPresent ( " key " , Unchecked . biFunction ( ( k , v ) - > {
* if ( k = = null | | v = = null )
* throw new Exception ( " No nulls allowed in map " ) ;
* return 42;
* < / pre > < / code > */
public static < T , U , R > BiFunction < T , U , R > biFunction ( CheckedBiFunction < T , U , R > function ) { } } | return Unchecked . biFunction ( function , Unchecked . RETHROW_ALL ) ; |
public class AbstractXbaseCompiler { /** * / * @ Nullable */
protected String getReferenceName ( XExpression expr , ITreeAppendable b ) { } } | if ( b . hasName ( expr ) ) return b . getName ( expr ) ; if ( expr instanceof XFeatureCall ) { XFeatureCall featureCall = ( XFeatureCall ) expr ; if ( b . hasName ( featureCall . getFeature ( ) ) ) return b . getName ( featureCall . getFeature ( ) ) ; } return null ; |
public class SourceMapConsumerV3 { /** * Parses the given contents containing a source map . */
@ Override public void parse ( String contents ) throws SourceMapParseException { } } | SourceMapObject sourceMapObject = SourceMapObjectParser . parse ( contents ) ; parse ( sourceMapObject , null ) ; |
public class JDBCWorkspaceDataContainer { /** * { @ inheritDoc } */
public Long getNodesCount ( ) throws RepositoryException { } } | WorkspaceStorageConnection conn = connFactory . openConnection ( ) ; try { return conn . getNodesCount ( ) ; } finally { conn . close ( ) ; } |
public class GrailsASTUtils { /** * Adds a static method to the given class node that delegates to the given method
* and resolves the object to invoke the method on from the given expression .
* @ param expression The expression
* @ param classNode The class node
* @ param delegateMethod The delegate method
* @ return The added method node or null if it couldn ' t be added */
public static MethodNode addDelegateStaticMethod ( Expression expression , ClassNode classNode , MethodNode delegateMethod ) { } } | return addDelegateStaticMethod ( expression , classNode , delegateMethod , null , null , true ) ; |
public class ParagraphVectors { /** * This method predicts label of the document .
* Computes a similarity wrt the mean of the
* representation of words in the document
* @ param document the document
* @ return the word distances for each label */
public String predict ( List < VocabWord > document ) { } } | /* This code was transferred from original ParagraphVectors DL4j implementation , and yet to be tested */
if ( document . isEmpty ( ) ) throw new IllegalStateException ( "Document has no words inside" ) ; /* INDArray arr = Nd4j . create ( document . size ( ) , this . layerSize ) ;
for ( int i = 0 ; i < document . size ( ) ; i + + ) {
arr . putRow ( i , getWordVectorMatrix ( document . get ( i ) . getWord ( ) ) ) ; */
INDArray docMean = inferVector ( document ) ; // arr . mean ( 0 ) ;
Counter < String > distances = new Counter < > ( ) ; for ( String s : labelsSource . getLabels ( ) ) { INDArray otherVec = getWordVectorMatrix ( s ) ; double sim = Transforms . cosineSim ( docMean , otherVec ) ; distances . incrementCount ( s , ( float ) sim ) ; } return distances . argMax ( ) ; |
public class UserService { /** * This method expects absolute DNs of group members . In order to find the actual users
* the DNs need to have the base LDAP path removed .
* @ param absoluteIds
* @ return */
public Set < User > findAllMembers ( Iterable < Name > absoluteIds ) { } } | return Sets . newLinkedHashSet ( userRepo . findAll ( toRelativeIds ( absoluteIds ) ) ) ; |
public class WebDriverWaitUtils { /** * Waits until the current page ' s title contains a case - sensitive substring of the given title .
* @ param pageTitle
* title of page expected to appear */
public static void waitUntilPageTitleContains ( final String pageTitle ) { } } | logger . entering ( pageTitle ) ; Preconditions . checkArgument ( StringUtils . isNotEmpty ( pageTitle ) , "Expected Page title cannot be null (or) empty." ) ; ExpectedCondition < Boolean > condition = ExpectedConditions . titleContains ( pageTitle ) ; waitForCondition ( condition ) ; logger . exiting ( ) ; |
public class MapEventPublisherImpl { /** * Hook for actions to perform after any of { @ link # publishEvent }
* methods is executed and if there were any registrations for
* the event . This method will be invoked once per unique { @ link
* EntryEventData } generated by { @ code publishEvent } , regardless
* of the number of registrations on which the event is published .
* @ param eventDataIncludingValues the event data including all of the entry values ( old , new , merging )
* @ param eventDataExcludingValues the event data without entry values */
protected void postPublishEvent ( Collection < EntryEventData > eventDataIncludingValues , Collection < EntryEventData > eventDataExcludingValues ) { } } | // publish event data of interest to query caches ; since query cache listener registrations
// include values ( as these are required to properly filter according to the query cache ' s predicate ) ,
// we do not take into account eventDataExcludingValues , if any were generated
if ( eventDataIncludingValues != null ) { for ( EntryEventData entryEventData : eventDataIncludingValues ) { queryCacheEventPublisher . addEventToQueryCache ( entryEventData ) ; } } |
public class SMSSenderOlmImpl { /** * / * ( non - Javadoc )
* @ see org . esupportail . smsuapi . services . sms . ISMSSender
* # sendMessage ( org . esupportail . smsuapi . domain . beans . sms . SMSMessage ) */
public void sendMessage ( final SMSBroker sms ) { } } | final int smsId = sms . getId ( ) ; final String smsRecipient = sms . getRecipient ( ) ; final String smsMessage = sms . getMessage ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Entering into send message with parameter : " ) ; logger . debug ( " - message id : " + smsId ) ; logger . debug ( " - message recipient : " + smsRecipient ) ; logger . debug ( " - message : " + smsMessage ) ; } try { final String messageISOLatin = new String ( smsMessage . getBytes ( ) , "ISO-8859-1" ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "sending encoded message : " + messageISOLatin ) ; } final SMText smText = RequestFactory . createSMText ( smsId , smsRecipient , messageISOLatin ) ; smText . setNotificationLevel ( NOTIFICATION_LEVEL ) ; // only send the message if required
if ( ! simulateMessageSending ) { olmConnector . submit ( smText ) ; logger . debug ( "message with : " + " - id : " + smsId + "successfully sent" ) ; } else { logger . warn ( "Message with id : " + smsId + " not sent because simlation mode is enable" ) ; } } catch ( Throwable t ) { logger . error ( "An error occurs sending SMS : " + " - id : " + smsId + " - recipient : " + smsRecipient + " - message : " + smsMessage ) ; } |
public class ModelRegistry { /** * Registers date converters ( Date - > String - > java . sql . Date ) for specified model attributes . */
void dateFormat ( DateFormat format , String ... attributes ) { } } | convertWith ( new DateToStringConverter ( format ) , attributes ) ; convertWith ( new StringToSqlDateConverter ( format ) , attributes ) ; |
public class CommerceDiscountRulePersistenceImpl { /** * Returns the first commerce discount rule in the ordered set where commerceDiscountId = & # 63 ; .
* @ param commerceDiscountId the commerce discount ID
* @ param orderByComparator the comparator to order the set by ( optionally < code > null < / code > )
* @ return the first matching commerce discount rule
* @ throws NoSuchDiscountRuleException if a matching commerce discount rule could not be found */
@ Override public CommerceDiscountRule findByCommerceDiscountId_First ( long commerceDiscountId , OrderByComparator < CommerceDiscountRule > orderByComparator ) throws NoSuchDiscountRuleException { } } | CommerceDiscountRule commerceDiscountRule = fetchByCommerceDiscountId_First ( commerceDiscountId , orderByComparator ) ; if ( commerceDiscountRule != null ) { return commerceDiscountRule ; } StringBundler msg = new StringBundler ( 4 ) ; msg . append ( _NO_SUCH_ENTITY_WITH_KEY ) ; msg . append ( "commerceDiscountId=" ) ; msg . append ( commerceDiscountId ) ; msg . append ( "}" ) ; throw new NoSuchDiscountRuleException ( msg . toString ( ) ) ; |
public class Model { /** * Get attribute of mysql type : time */
public java . sql . Time getTime ( String attr ) { } } | return ( java . sql . Time ) attrs . get ( attr ) ; |
public class Plugin { /** * Controls the file where { @ link # load ( ) } and { @ link # save ( ) }
* persists data .
* This method can be also overridden if the plugin wants to
* use a custom { @ link XStream } instance to persist data .
* @ since 1.245 */
protected XmlFile getConfigXml ( ) { } } | return new XmlFile ( Jenkins . XSTREAM , new File ( Jenkins . getInstance ( ) . getRootDir ( ) , wrapper . getShortName ( ) + ".xml" ) ) ; |
public class Builder { /** * Starts an HTML tag . It has no effect on the plain text version .
* @ param tag the tag name
* @ param attributes attributes full text , like " style = ' color : red ' "
* @ return this builder */
public Builder tag ( String tag , String attributes ) { } } | ends . push ( "</" + tag + ">" ) ; html . a ( '<' ) . a ( tag ) . sp ( ) . a ( attributes ) . a ( '>' ) ; return this ; |
public class Code { /** * 查询基础代码是否具有扩展属性 , 一般供子类使用 。 */
public boolean hasExtPros ( ) { } } | Field [ ] fields = getClass ( ) . getDeclaredFields ( ) ; for ( int i = 0 ; i < fields . length ; i ++ ) { if ( ! ( Modifier . isFinal ( fields [ i ] . getModifiers ( ) ) || Modifier . isStatic ( fields [ i ] . getModifiers ( ) ) ) ) { return true ; } } return false ; |
public class TCPChannel { /** * @ see com . ibm . wsspi . channelfw . Channel # init ( ) */
@ Override public void init ( ) throws ChannelException { } } | if ( this . config . isInbound ( ) ) { // Customize the TCPChannel configuration object so that it knows
// what port to use for this chain .
this . endPoint = createEndPoint ( ) ; initializePort ( ) ; if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isDebugEnabled ( ) ) { Tr . debug ( tc , " listening port: " + this . endPoint . getListenPort ( ) ) ; } } |
public class RemoteLockMapImpl { /** * generate a writer lock entry for transaction tx on object obj
* and write it to the persistent storage . */
public boolean setWriter ( TransactionImpl tx , Object obj ) { } } | try { LockEntry lock = new LockEntry ( new Identity ( obj , getBroker ( ) ) . toString ( ) , tx . getGUID ( ) , System . currentTimeMillis ( ) , LockStrategyFactory . getIsolationLevel ( obj ) , LockEntry . LOCK_WRITE ) ; setWriterRemote ( lock ) ; return true ; } catch ( Throwable t ) { log . error ( "Cannot set LockEntry for object " + obj + " in transaction " + tx ) ; return false ; } |
public class ConsistencyCheck { /** * Determine the consistency level of a key
* @ param versionNodeSetMap A map that maps version to set of PrefixNodes
* @ param replicationFactor Total replication factor for the set of clusters
* @ return ConsistencyLevel Enum */
public static ConsistencyLevel determineConsistency ( Map < Value , Set < ClusterNode > > versionNodeSetMap , int replicationFactor ) { } } | boolean fullyConsistent = true ; Value latestVersion = null ; for ( Map . Entry < Value , Set < ClusterNode > > versionNodeSetEntry : versionNodeSetMap . entrySet ( ) ) { Value value = versionNodeSetEntry . getKey ( ) ; if ( latestVersion == null ) { latestVersion = value ; } else if ( value . isTimeStampLaterThan ( latestVersion ) ) { latestVersion = value ; } Set < ClusterNode > nodeSet = versionNodeSetEntry . getValue ( ) ; fullyConsistent = fullyConsistent && ( nodeSet . size ( ) == replicationFactor ) ; } if ( fullyConsistent ) { return ConsistencyLevel . FULL ; } else { // latest write consistent , effectively consistent
if ( latestVersion != null && versionNodeSetMap . get ( latestVersion ) . size ( ) == replicationFactor ) { return ConsistencyLevel . LATEST_CONSISTENT ; } // all other states inconsistent
return ConsistencyLevel . INCONSISTENT ; } |
public class MessageRouterConfigurator { /** * Lazy activation and retrieval of the MessageRouter . */
protected WsMessageRouterImpl getMessageRouter ( ) { } } | if ( msgRouter == null ) { // First activation .
msgRouter = MessageRouterSingleton . singleton ; // Pass the MessageRouter to the TrService via the TrConfigurator .
TrConfigurator . setMessageRouter ( msgRouter ) ; // Register this guy as a BundleListener , looking for new Bundles as they
// are added to the framework . Then process the already - installed bundles .
// We are looking for any / META - INF / MessageRouter . properties files defined
// in the bundles . Note : it ' s possible ( tho unlikely ) that multiple threads
// could be running this code at the same time . This is not a problem .
// The msgRouter will be informed of duplicate MessageRouter . properties
// entries , but it can handle that . One thing to note , howerver , is that the
// natural ordering of Bundles may get messed up by the BundleListener . The
// BundleListener is registered before we process the initial bundle set
// ( which we must do , otherwise we risk missing the arrival of a bundle between
// the time we ' re processing the initial set and the time we register the
// BundleListener ) . However , if the BundleListener receives a " bundle installed "
// event asynchronously while we ' re still processing the initial set , that newly
// installed bundle ' s MessageRouter properties may get overridden by a bundle
// from the initial set , which would violate the policy that the properties are
// applied in the order by which the bundles were started . So we ' re stuck between
// a rock and a hard place . Not sure what to do about that .
bundleContext . addBundleListener ( this ) ; processInitialBundles ( ) ; } return msgRouter ; |
public class CoordinatorAdminUtils { /** * Utility function that copies a string array except for the first element
* @ param arr Original array of strings
* @ return Copied array of strings */
public static String [ ] copyArrayCutFirst ( String [ ] arr ) { } } | if ( arr . length > 1 ) { String [ ] arrCopy = new String [ arr . length - 1 ] ; System . arraycopy ( arr , 1 , arrCopy , 0 , arrCopy . length ) ; return arrCopy ; } else { return new String [ 0 ] ; } |
public class CellStyleProxy { /** * インデントを設定する
* @ param indent インデントの値 */
public void setIndent ( final short indent ) { } } | if ( cell . getCellStyle ( ) . getIndention ( ) == indent ) { // 既にインデントが同じ値
return ; } cloneStyle ( ) ; cell . getCellStyle ( ) . setIndention ( indent ) ; |
public class StatusRepresentation { /** * Initializes the object to contain the given status .
* @ param source
* a string describing where the tweet came from
* @ param jsonString
* a string representing the Twitter status in JSON format
* @ return this object */
public StatusRepresentation init ( String source , String jsonString ) { } } | if ( jsonString == null || jsonString . contains ( "{" ) ) return init ( source , null , jsonString , null ) ; // if the input doesn ' t look like a JSON string , it might be a simple
// status ID
init ( source , null , null , null ) ; _id = Long . valueOf ( jsonString . trim ( ) ) ; return this ; |
public class ServletTreeRenderSupport { /** * Errors during rendering will call through this method . During the XmlHttpRequest , these
* will just be logged and we will go on .
* @ param message
* @ param e
* @ throws JspException */
protected void registerTagError ( String message , Throwable e ) throws JspException { } } | System . err . println ( "Error in rendering tree:" + message ) ; logger . error ( message , e ) ; |
public class Futures { /** * Creates a { @ link CheckedFuture } out of a normal { @ link ListenableFuture }
* and a { @ link Function } that maps from { @ link Exception } instances into the
* appropriate checked type .
* < p > The given mapping function will be applied to an
* { @ link InterruptedException } , a { @ link CancellationException } , or an
* { @ link ExecutionException } .
* See { @ link Future # get ( ) } for details on the exceptions thrown .
* @ since 9.0 ( source - compatible since 1.0) */
public static < V , X extends Exception > CheckedFuture < V , X > makeChecked ( ListenableFuture < V > future , Function < ? super Exception , X > mapper ) { } } | return new MappingCheckedFuture < V , X > ( checkNotNull ( future ) , mapper ) ; |
public class MapperHelper { /** * 配置属性
* @ param properties */
public void setProperties ( Properties properties ) { } } | config . setProperties ( properties ) ; // 注册解析器
if ( properties != null ) { String resolveClass = properties . getProperty ( "resolveClass" ) ; if ( StringUtil . isNotEmpty ( resolveClass ) ) { try { EntityHelper . setResolve ( ( EntityResolve ) Class . forName ( resolveClass ) . newInstance ( ) ) ; } catch ( Exception e ) { throw new MapperException ( "创建 " + resolveClass + " 实例失败!" , e ) ; } } } // 注册通用接口
if ( properties != null ) { String mapper = properties . getProperty ( "mappers" ) ; if ( StringUtil . isNotEmpty ( mapper ) ) { String [ ] mappers = mapper . split ( "," ) ; for ( String mapperClass : mappers ) { if ( mapperClass . length ( ) > 0 ) { registerMapper ( mapperClass ) ; } } } } |
public class PhpDependencyResolver { /** * convert phpPackage to dependencyInfo object */
private DependencyInfo createDependencyInfo ( PhpPackage phpPackage ) { } } | String groupId = getGroupIdFromName ( phpPackage ) ; String artifactId = phpPackage . getName ( ) ; String version = phpPackage . getVersion ( ) ; String commit = phpPackage . getPackageSource ( ) . getReference ( ) ; if ( StringUtils . isNotBlank ( version ) || StringUtils . isNotBlank ( commit ) ) { DependencyInfo dependencyInfo = new DependencyInfo ( groupId , artifactId , version ) ; dependencyInfo . setCommit ( commit ) ; dependencyInfo . setDependencyType ( getDependencyType ( ) ) ; if ( this . addSha1 ) { String sha1 = null ; String sha1Source = StringUtils . isNotBlank ( version ) ? version : commit ; try { sha1 = this . hashCalculator . calculateSha1ByNameVersionAndType ( artifactId , sha1Source , DependencyType . PHP ) ; } catch ( IOException e ) { logger . debug ( "Failed to calculate sha1 of: {}" , artifactId ) ; } if ( sha1 != null ) { dependencyInfo . setSha1 ( sha1 ) ; } } return dependencyInfo ; } else { logger . debug ( "The parameters version and commit of {} are null" , phpPackage . getName ( ) ) ; return null ; } |
public class HttpCommand { /** * HTTP / 1.0 200 OK
* Date : Fri , 31 Dec 1999 23:59:59 GMT
* Content - TextCommandType : text / html
* Content - Length : 1354
* @ param contentType
* @ param value */
public void setResponse ( byte [ ] contentType , byte [ ] value ) { } } | int valueSize = ( value == null ) ? 0 : value . length ; byte [ ] len = stringToBytes ( String . valueOf ( valueSize ) ) ; int size = RES_200 . length ; if ( contentType != null ) { size += CONTENT_TYPE . length ; size += contentType . length ; size += TextCommandConstants . RETURN . length ; } size += CONTENT_LENGTH . length ; size += len . length ; size += TextCommandConstants . RETURN . length ; size += TextCommandConstants . RETURN . length ; size += valueSize ; this . response = ByteBuffer . allocate ( size ) ; response . put ( RES_200 ) ; if ( contentType != null ) { response . put ( CONTENT_TYPE ) ; response . put ( contentType ) ; response . put ( TextCommandConstants . RETURN ) ; } response . put ( CONTENT_LENGTH ) ; response . put ( len ) ; response . put ( TextCommandConstants . RETURN ) ; response . put ( TextCommandConstants . RETURN ) ; if ( value != null ) { response . put ( value ) ; } response . flip ( ) ; |
public class TextCharacter { /** * Returns a copy of this TextCharacter with an SGR modifier removed . All of the currently active SGR codes
* will be carried over to the copy , except for the one specified . If the current TextCharacter doesn ' t have the
* SGR specified , it will return itself .
* @ param modifier SGR modifiers the copy should not have
* @ return Copy of the TextCharacter without the SGR modifier */
public TextCharacter withoutModifier ( SGR modifier ) { } } | if ( ! modifiers . contains ( modifier ) ) { return this ; } EnumSet < SGR > newSet = EnumSet . copyOf ( this . modifiers ) ; newSet . remove ( modifier ) ; return new TextCharacter ( character , foregroundColor , backgroundColor , newSet ) ; |
public class DurableInputHandler { /** * Issue a DeleteDurable request for an existing remote durable subscription .
* The caller is blocked until we receive a reply for this request .
* @ param req The state describing the request
* @ return One of STATUS _ OK , STATUS _ SUB _ NOT _ FOUND , or STATUS _ SUB _ GENERAL _ ERROR */
public static int issueDeleteDurableRequest ( MessageProcessor MP , String subName , String userName , SIBUuid8 remoteMEUuid ) throws SIResourceException { } } | if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . entry ( tc , "issueDeleteDurableRequest" , new Object [ ] { MP , subName , userName , remoteMEUuid } ) ; long requestID = MP . nextTick ( ) ; ControlMessage msg = createDurableDeleteDurable ( MP , subName , userName , requestID , remoteMEUuid ) ; Object result = issueRequest ( MP , msg , remoteMEUuid , DELETEDURABLE_RETRY_TIMEOUT , - 1 , // 219870 : retry forever , otherwise use DELETEDURABLE _ NUMTRIES ,
requestID ) ; if ( result == null ) { if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . exit ( tc , "issueDeleteDurableRequest" , "SIResourceException" ) ; // Timeout , throw a general error
throw new SIResourceException ( nls . getFormattedMessage ( "REMOTE_DURABLE_TIMEOUT_ERROR_CWSIP0631" , new Object [ ] { "delete" , subName , remoteMEUuid } , null ) ) ; } // Otherwise , reply should always be a ControlDurableConfirm with a status code
if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . exit ( tc , "issueDeleteDurableRequest" , new Integer ( ( ( ControlDurableConfirm ) result ) . getStatus ( ) ) ) ; return ( ( ControlDurableConfirm ) result ) . getStatus ( ) ; |
public class PackageSummaryBuilder { /** * Build the summary for the errors in this package .
* @ param node the XML element that specifies which components to document
* @ param summaryContentTree the summary tree to which the error summary will
* be added */
public void buildErrorSummary ( XMLNode node , Content summaryContentTree ) { } } | String errorTableSummary = configuration . getText ( "doclet.Member_Table_Summary" , configuration . getText ( "doclet.Error_Summary" ) , configuration . getText ( "doclet.errors" ) ) ; String [ ] errorTableHeader = new String [ ] { configuration . getText ( "doclet.Error" ) , configuration . getText ( "doclet.Description" ) } ; ClassDoc [ ] errors = packageDoc . isIncluded ( ) ? packageDoc . errors ( ) : configuration . classDocCatalog . errors ( Util . getPackageName ( packageDoc ) ) ; errors = Util . filterOutPrivateClasses ( errors , configuration . javafx ) ; if ( errors . length > 0 ) { packageWriter . addClassesSummary ( errors , configuration . getText ( "doclet.Error_Summary" ) , errorTableSummary , errorTableHeader , summaryContentTree ) ; } |
public class ComponentFactoryImpl { /** * Creates a component which contains sub - components . Currently the only such component is VTIMEZONE .
* @ param name name of the component
* @ param properties a list of component properties
* @ param components a list of sub - components ( namely standard / daylight timezones )
* @ return a component */
@ SuppressWarnings ( "unchecked" ) public < T extends Component > T createComponent ( final String name , final PropertyList properties , final ComponentList < ? extends Component > components ) { } } | Component component ; ComponentFactory factory = getFactory ( name ) ; if ( factory != null ) { component = factory . createComponent ( properties , components ) ; } else { throw new IllegalArgumentException ( "Unsupported component [" + name + "]" ) ; } return ( T ) component ; |
public class SubscriptionDebugLogInterceptor { /** * These methods are numbered in the order that an individual
* resource would go through them , for clarity and ease of
* tracing when debugging and poring over logs .
* I don ' t know if this numbering scheme makes sense . . I ' m incrementing
* by 10 for each step in the normal delivery pipeline , leaving lots of
* gaps to add things if we ever need them . */
@ Hook ( Pointcut . SUBSCRIPTION_BEFORE_PERSISTED_RESOURCE_CHECKED ) public void step20_beforeChecked ( ResourceModifiedMessage theMessage ) { } } | log ( EventCodeEnum . SUBS2 , "Checking resource {} (op={}) for matching subscriptions" , theMessage . getPayloadId ( ) , theMessage . getOperationType ( ) ) ; |
public class PayMchAPI { /** * 查询代金券批次
* @ param queryCouponStock queryCouponStock
* @ param key key
* @ return QueryCouponStockResult */
public static QueryCouponStockResult mmpaymkttransfersQuery_coupon_stock ( QueryCouponStock queryCouponStock , String key ) { } } | Map < String , String > map = MapUtil . objectToMap ( queryCouponStock ) ; String sign = SignatureUtil . generateSign ( map , queryCouponStock . getSign_type ( ) , key ) ; queryCouponStock . setSign ( sign ) ; String secapiPayRefundXML = XMLConverUtil . convertToXML ( queryCouponStock ) ; HttpUriRequest httpUriRequest = RequestBuilder . post ( ) . setHeader ( xmlHeader ) . setUri ( baseURI ( ) + "/mmpaymkttransfers/query_coupon_stock" ) . setEntity ( new StringEntity ( secapiPayRefundXML , Charset . forName ( "utf-8" ) ) ) . build ( ) ; return LocalHttpClient . executeXmlResult ( httpUriRequest , QueryCouponStockResult . class , queryCouponStock . getSign_type ( ) , key ) ; |
public class TableModelSession { /** * Get the gridtable for this record ( or create one if it doesn ' t exit ) .
* @ param gridRecord The record to get / create a gridtable for .
* @ return The gridtable . */
public GridTable getGridTable ( Record gridRecord ) { } } | GridTable gridTable = super . getGridTable ( gridRecord ) ; gridTable . setCache ( true ) ; // Typically , the client is a gridscreen which caches the records ( so I don ' t have to ! )
return gridTable ; |
public class BlogsInterface { /** * Post the specified photo to a blog . Note that the Photo . title and Photo . description are used for the blog entry title and body respectively .
* @ param photo
* The photo metadata
* @ param blogId
* The blog ID
* @ param blogPassword
* The blog password
* @ throws FlickrException */
public void postPhoto ( Photo photo , String blogId , String blogPassword ) throws FlickrException { } } | Map < String , Object > parameters = new HashMap < String , Object > ( ) ; parameters . put ( "method" , METHOD_POST_PHOTO ) ; parameters . put ( "blog_id" , blogId ) ; parameters . put ( "photo_id" , photo . getId ( ) ) ; parameters . put ( "title" , photo . getTitle ( ) ) ; parameters . put ( "description" , photo . getDescription ( ) ) ; if ( blogPassword != null ) { parameters . put ( "blog_password" , blogPassword ) ; } Response response = transportAPI . post ( transportAPI . getPath ( ) , parameters , apiKey , sharedSecret ) ; if ( response . isError ( ) ) { throw new FlickrException ( response . getErrorCode ( ) , response . getErrorMessage ( ) ) ; } |
public class MessageLogGridScreen { /** * Get the command string to restore screen . */
public String getScreenURL ( ) { } } | String strURL = super . getScreenURL ( ) ; ReferenceField fldContactType = ( ReferenceField ) this . getScreenRecord ( ) . getField ( MessageLogScreenRecord . CONTACT_TYPE_ID ) ; String strContactTypeParam = fldContactType . getFieldName ( ) ; if ( ! fldContactType . isNull ( ) ) { String strContactType = fldContactType . getReference ( ) . getField ( ContactType . CODE ) . toString ( ) ; strURL = this . addURLParam ( strURL , strContactTypeParam , strContactType ) ; } return strURL ; |
public class DropGeometryColumnGeneratorGeoDB { /** * Adds the SQL statement to drop the spatial index if it is present .
* @ param catalogName
* the catalog name .
* @ param schemaName
* the schema name .
* @ param tableName
* the table name .
* @ param database
* the database .
* @ param list
* the list of SQL statements to execute . */
protected void dropSpatialIndexIfExists ( final String catalogName , final String schemaName , final String tableName , final Database database , final List < Sql > list ) { } } | final DropSpatialIndexGeneratorGeoDB generator = new DropSpatialIndexGeneratorGeoDB ( ) ; final DropSpatialIndexStatement statement = new DropSpatialIndexStatement ( null , catalogName , schemaName , tableName ) ; list . addAll ( Arrays . asList ( generator . generateSqlIfExists ( statement , database ) ) ) ; |
public class OSchemaHelper { /** * Sets a field value for a current document
* @ param field field name
* @ param value value to set
* @ return this helper */
public OSchemaHelper field ( String field , Object value ) { } } | checkODocument ( ) ; lastDocument . field ( field , value ) ; return this ; |
public class PutEmailIdentityDkimAttributesRequestMarshaller { /** * Marshall the given parameter object . */
public void marshall ( PutEmailIdentityDkimAttributesRequest putEmailIdentityDkimAttributesRequest , ProtocolMarshaller protocolMarshaller ) { } } | if ( putEmailIdentityDkimAttributesRequest == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( putEmailIdentityDkimAttributesRequest . getEmailIdentity ( ) , EMAILIDENTITY_BINDING ) ; protocolMarshaller . marshall ( putEmailIdentityDkimAttributesRequest . getSigningEnabled ( ) , SIGNINGENABLED_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.