signature stringlengths 43 39.1k | implementation stringlengths 0 450k |
|---|---|
public class AnnotatedTextBuilder { /** * Add any global meta data about the document to be checked . Some rules may use this information .
* Unless you ' re using your own rules for which you know useful keys , you probably want to
* use { @ link # addGlobalMetaData ( AnnotatedText . MetaDataKey , String ) } .
* @ since 3.9 */
public AnnotatedTextBuilder addGlobalMetaData ( String key , String value ) { } } | customMetaData . put ( key , value ) ; return this ; |
public class TtlRunnable { /** * Unwrap { @ link TtlRunnable } to the original / underneath one .
* this method is { @ code null } - safe , when input { @ code Runnable } parameter is { @ code null } , return { @ code null } ;
* if input { @ code Runnable } parameter is not a { @ link TtlRunnable } just return input { @ code Runnable } .
* so { @ code TtlRunnable . unwrap ( TtlRunnable . get ( runnable ) ) } will always return the same input { @ code runnable } object .
* @ see # get ( Runnable )
* @ since 2.10.2 */
@ Nullable public static Runnable unwrap ( @ Nullable Runnable runnable ) { } } | if ( ! ( runnable instanceof TtlRunnable ) ) return runnable ; else return ( ( TtlRunnable ) runnable ) . getRunnable ( ) ; |
public class InternationalizationServiceSingleton { /** * A bundle tracked by the { @ code BundleTracker } has been removed .
* This method is called after a bundle is no longer being tracked by the
* { @ code BundleTracker } .
* @ param bundle The { @ code Bundle } that has been removed .
* @ param event The bundle event which caused this customizer method to be
* called or { @ code null } if there is no bundle event associated
* with the call to this method .
* @ param list The tracked object for the specified bundle . */
@ Override public void removedBundle ( Bundle bundle , BundleEvent event , List < I18nExtension > list ) { } } | String current = Long . toString ( System . currentTimeMillis ( ) ) ; for ( I18nExtension extension : list ) { synchronized ( this ) { extensions . remove ( extension ) ; etags . put ( extension . locale ( ) , current ) ; } } LOGGER . info ( "Bundle {} ({}) does not offer the {} resource bundle(s) anymore" , bundle . getSymbolicName ( ) , bundle . getBundleId ( ) , list . size ( ) ) ; |
public class RouteMatcher { /** * Specify a handler that will be called for a matching HTTP CONNECT
* @ param regex A regular expression
* @ param handler The handler to call */
public RouteMatcher connectWithRegEx ( String regex , Handler < HttpServerRequest > handler ) { } } | addRegEx ( regex , handler , connectBindings ) ; return this ; |
public class FoundationsRegistry { /** * Retrieves the foundation associated to an address . < br >
* If no foundation exists for such address , one will be generated .
* @ param candidate
* The ICE candidate
* @ return The foundation associated to the candidate address . */
public String assignFoundation ( IceCandidate candidate ) { } } | String identifier = computeIdentifier ( candidate ) ; synchronized ( this . foundations ) { String foundation = this . foundations . get ( identifier ) ; if ( foundation == null ) { this . currentFoundation ++ ; foundation = String . valueOf ( this . currentFoundation ) ; this . foundations . put ( identifier , foundation ) ; } candidate . setFoundation ( foundation ) ; return foundation ; } |
public class NavigationAlertView { /** * Shows this alert view to let user report a problem for the given number of milliseconds */
public void showReportProblem ( ) { } } | if ( ! isEnabled ) { return ; } final Handler handler = new Handler ( ) ; handler . postDelayed ( new Runnable ( ) { @ Override public void run ( ) { show ( getContext ( ) . getString ( R . string . report_problem ) , NavigationConstants . ALERT_VIEW_PROBLEM_DURATION , true ) ; } } , THREE_SECOND_DELAY_IN_MILLIS ) ; |
public class ActionDrawerItem { /** * Called to create this view
* @ param inflater the layout inflater to inflate a layout from system
* @ param container the container the layout is going to be placed in
* @ return */
@ Override public View onCreateView ( LayoutInflater inflater , ViewGroup container , int highlightColor ) { } } | Context ctx = inflater . getContext ( ) ; View view = inflater . inflate ( R . layout . navdrawer_item , container , false ) ; ImageView iconView = ButterKnife . findById ( view , R . id . icon ) ; TextView titleView = ButterKnife . findById ( view , R . id . title ) ; // Set the text
FontLoader . apply ( titleView , Face . ROBOTO_MEDIUM ) ; titleView . setText ( text ) ; // Set the icon , if provided
iconView . setVisibility ( icon > 0 ? View . VISIBLE : View . GONE ) ; if ( icon > 0 ) iconView . setImageResource ( icon ) ; // configure its appearance according to whether or not it ' s selected
titleView . setTextColor ( selected ? highlightColor : UIUtils . getColorAttr ( ctx , android . R . attr . textColorPrimary ) ) ; iconView . setColorFilter ( selected ? highlightColor : ctx . getResources ( ) . getColor ( R . color . navdrawer_icon_tint ) ) ; return view ; |
public class RequestContext { /** * Gets the data model of renderer bound with this context .
* @ return data model , returns { @ code null } if not found */
public Map < String , Object > getDataModel ( ) { } } | final AbstractResponseRenderer renderer = getRenderer ( ) ; if ( null == renderer ) { return null ; } return renderer . getRenderDataModel ( ) ; |
public class MoreCollectors { /** * Adapts a { @ code Collector } to perform an additional finishing
* transformation .
* Unlike { @ link Collectors # collectingAndThen ( Collector , Function ) } this
* method returns a
* < a href = " package - summary . html # ShortCircuitReduction " > short - circuiting
* collector < / a > if the downstream collector is short - circuiting .
* @ param < T > the type of the input elements
* @ param < A > intermediate accumulation type of the downstream collector
* @ param < R > result type of the downstream collector
* @ param < RR > result type of the resulting collector
* @ param downstream a collector
* @ param finisher a function to be applied to the final result of the
* downstream collector
* @ return a collector which performs the action of the downstream
* collector , followed by an additional finishing step
* @ see Collectors # collectingAndThen ( Collector , Function )
* @ since 0.4.0 */
public static < T , A , R , RR > Collector < T , A , RR > collectingAndThen ( Collector < T , A , R > downstream , Function < R , RR > finisher ) { } } | Predicate < A > finished = finished ( downstream ) ; if ( finished != null ) { return new CancellableCollectorImpl < > ( downstream . supplier ( ) , downstream . accumulator ( ) , downstream . combiner ( ) , downstream . finisher ( ) . andThen ( finisher ) , finished , downstream . characteristics ( ) . contains ( Characteristics . UNORDERED ) ? UNORDERED_CHARACTERISTICS : NO_CHARACTERISTICS ) ; } return Collectors . collectingAndThen ( downstream , finisher ) ; |
public class Utils { /** * Assert that the given org . w3c . doc . Node is a comment element or a Text element and
* that it ontains whitespace only , otherwise throw an IllegalArgumentException using
* the given error message . This is helpful when nothing is expected at a certain
* place in a DOM tree , yet comments or whitespace text nodes can appear .
* @ param node A DOM Node object .
* @ param errMsg String used to in the IllegalArgumentException
* constructor if thrown .
* @ throws IllegalArgumentException If the expression is false . */
public static void requireEmptyText ( Node node , String errMsg ) throws IllegalArgumentException { } } | require ( ( node instanceof Text ) || ( node instanceof Comment ) , errMsg + ": " + node . toString ( ) ) ; if ( node instanceof Text ) { Text text = ( Text ) node ; String textValue = text . getData ( ) ; require ( textValue . trim ( ) . length ( ) == 0 , errMsg + ": " + textValue ) ; } |
public class CmsResourceTreeContainer { /** * Initializes the root level of the tree . < p >
* @ param cms the CMS context
* @ param root the root folder */
public void initRoot ( CmsObject cms , CmsResource root ) { } } | addTreeItem ( cms , root , null ) ; readTreeLevel ( cms , root . getStructureId ( ) ) ; |
public class RegularPactTask { /** * Closes the given stub using its { @ link Function # close ( ) } method . If the close call produces
* an exception , a new exception with a standard error message is created , using the encountered exception
* as its cause .
* @ param stub The user code instance to be closed .
* @ throws Exception Thrown , if the user code ' s close method produces an exception . */
public static void closeUserCode ( Function stub ) throws Exception { } } | try { stub . close ( ) ; } catch ( Throwable t ) { throw new Exception ( "The user defined 'close()' method caused an exception: " + t . getMessage ( ) , t ) ; } |
public class InterruptedException { /** * Re - interrupt the current thread and constructs an < code > InterruptedException < / code >
* with the specified detail message .
* @ param message the detail message .
* @ param cause original { @ code InterruptedException } */
public static InterruptedException newInterruptedException ( String message , java . lang . InterruptedException cause ) { } } | Thread . currentThread ( ) . interrupt ( ) ; return new InterruptedException ( message , cause ) ; |
public class ShardingRule { /** * Get table sharding strategy .
* Use default table sharding strategy if not found .
* @ param tableRule table rule
* @ return table sharding strategy */
public ShardingStrategy getTableShardingStrategy ( final TableRule tableRule ) { } } | return null == tableRule . getTableShardingStrategy ( ) ? defaultTableShardingStrategy : tableRule . getTableShardingStrategy ( ) ; |
public class StorageKey { /** * Replaces all of the values in this { @ link StorageKey } with values from the given
* { @ code entity } .
* @ param entity an entity to reuse this { @ code StorageKey } for
* @ return this updated { @ code StorageKey }
* @ throws IllegalStateException
* If the { @ code entity } cannot be used to produce a value for each
* field in the { @ code PartitionStrategy }
* @ since 0.9.0 */
@ SuppressWarnings ( "unchecked" ) public < E > StorageKey reuseFor ( E entity , @ Nullable Map < String , Object > provided , EntityAccessor < E > accessor ) { } } | accessor . keyFor ( entity , provided , this ) ; return this ; |
public class MaterialCalendarView { /** * { @ inheritDoc } */
@ Override protected void onLayout ( boolean changed , int left , int top , int right , int bottom ) { } } | final int count = getChildCount ( ) ; final int parentLeft = getPaddingLeft ( ) ; final int parentWidth = right - left - parentLeft - getPaddingRight ( ) ; int childTop = getPaddingTop ( ) ; for ( int i = 0 ; i < count ; i ++ ) { final View child = getChildAt ( i ) ; if ( child . getVisibility ( ) == View . GONE ) { continue ; } final int width = child . getMeasuredWidth ( ) ; final int height = child . getMeasuredHeight ( ) ; int delta = ( parentWidth - width ) / 2 ; int childLeft = parentLeft + delta ; child . layout ( childLeft , childTop , childLeft + width , childTop + height ) ; childTop += height ; } |
public class RythmEngine { /** * Render template with source specified by { @ link java . io . File file instance }
* and an array of render args . Render result return as a String
* < p > See { @ link # getTemplate ( java . io . File , Object . . . ) } for note on
* render args < / p >
* @ param file the template source file
* @ param args render args array
* @ return render result */
public String render ( File file , Object ... args ) { } } | try { if ( ! file . exists ( ) ) throw new RuntimeException ( "template '" + file . getName ( ) + "' does not exist!" ) ; if ( ! file . canRead ( ) ) throw new RuntimeException ( "template '" + file . getName ( ) + "' not readable!" ) ; ITemplate t = getTemplate ( file , args ) ; if ( t == null ) throw new RuntimeException ( "template '" + file . getName ( ) + "' load failed!" ) ; return t . render ( ) ; } finally { renderCleanUp ( ) ; } |
public class ThriftServlet { /** * 验证服务是否启动 */
@ Override protected void doGet ( HttpServletRequest request , HttpServletResponse response ) throws IOException { } } | PrintWriter w = response . getWriter ( ) ; w . write ( String . format ( "This is ikasoa server (%s) ." , serverName ) ) ; w . close ( ) ; |
public class DatePicker { /** * zEventTextFieldChanged , This is called whenever the text in the date picker text field has
* changed , whether programmatically or by the user .
* If the current text contains a valid date , it will be stored in the variable lastValidDate .
* Otherwise , the lastValidDate will not be changed .
* This will also call the function to indicate to the user if the currently text is a valid
* date , invalid text , or a vetoed date . These indications are created by using font , color , and
* background changes of the text field . */
private void zEventTextFieldChanged ( ) { } } | if ( settings == null ) { return ; } // Skip this function if it should not be run .
if ( skipTextFieldChangedFunctionWhileTrue ) { return ; } // Gather some variables that we will need .
String dateText = dateTextField . getText ( ) ; boolean textIsEmpty = dateText . trim ( ) . isEmpty ( ) ; DateVetoPolicy vetoPolicy = settings . getVetoPolicy ( ) ; boolean nullIsAllowed = settings . getAllowEmptyDates ( ) ; // If the text is not empty , then try to parse the date .
LocalDate parsedDate = null ; if ( ! textIsEmpty ) { parsedDate = InternalUtilities . getParsedDateOrNull ( dateText , settings . getFormatForDatesCommonEra ( ) , settings . getFormatForDatesBeforeCommonEra ( ) , settings . getFormatsForParsing ( ) , settings . getLocale ( ) ) ; } // If the date was parsed successfully , then check it against the veto policy .
boolean dateIsVetoed = false ; if ( parsedDate != null ) { dateIsVetoed = InternalUtilities . isDateVetoed ( vetoPolicy , parsedDate ) ; } // If the date is a valid empty date , then set the last valid date to null .
if ( textIsEmpty && nullIsAllowed ) { zInternalSetLastValidDateAndNotifyListeners ( null ) ; } // If the date is a valid parsed date , then store the last valid date .
if ( ( ! textIsEmpty ) && ( parsedDate != null ) && ( dateIsVetoed == false ) ) { zInternalSetLastValidDateAndNotifyListeners ( parsedDate ) ; } // Draw the date status indications for the user .
zDrawTextFieldIndicators ( ) ; // Fire a change event for beans binding .
firePropertyChange ( "text" , null , dateTextField . getText ( ) ) ; |
public class StringParser { /** * Parse the given { @ link String } as { @ link Short } with radix
* { @ value # DEFAULT _ RADIX } .
* @ param sStr
* The string to parse . May be < code > null < / code > .
* @ return < code > null < / code > if the string does not represent a valid value . */
@ Nullable public static Short parseShortObj ( @ Nullable final String sStr ) { } } | return parseShortObj ( sStr , DEFAULT_RADIX , null ) ; |
public class CacheUtil { /** * 生成字符串的HashCode
* @ param buf
* @ return int hashCode */
private static int getHashCode ( String buf ) { } } | int hash = 5381 ; int len = buf . length ( ) ; while ( len -- > 0 ) { hash = ( ( hash << 5 ) + hash ) + buf . charAt ( len ) ; } return hash ; |
public class JDBCConnection { /** * # ifdef JAVA6 */
public boolean isWrapperFor ( java . lang . Class < ? > iface ) throws java . sql . SQLException { } } | checkClosed ( ) ; return ( iface != null && iface . isAssignableFrom ( this . getClass ( ) ) ) ; |
public class ConfusionMatrix { /** * Computes the total number of times the class was predicted by the classifier . */
public synchronized int getPredictedTotal ( T predicted ) { } } | int total = 0 ; for ( T actual : classes ) { total += getCount ( actual , predicted ) ; } return total ; |
public class JsonWriter { /** * Writes { @ code value } directly to the writer without quoting or
* escaping .
* @ param value the literal string value , or null to encode a null literal .
* @ return this writer . */
public JsonWriter jsonValue ( String value ) throws IOException { } } | if ( value == null ) { return nullValue ( ) ; } writeDeferredName ( ) ; beforeValue ( ) ; out . append ( value ) ; return this ; |
public class JDBCDatabaseMetaData { /** * Retrieves a description of the access rights for each table available
* in a catalog . Note that a table privilege applies to one or
* more columns in the table . It would be wrong to assume that
* this privilege applies to all columns ( this may be true for
* some systems but is not true for all . )
* < P > Only privileges matching the schema and table name
* criteria are returned . They are ordered by TABLE _ SCHEM ,
* TABLE _ NAME , and PRIVILEGE .
* < P > Each privilige description has the following columns :
* < OL >
* < LI > < B > TABLE _ CAT < / B > String = > table catalog ( may be < code > null < / code > )
* < LI > < B > TABLE _ SCHEM < / B > String = > table schema ( may be < code > null < / code > )
* < LI > < B > TABLE _ NAME < / B > String = > table name
* < LI > < B > GRANTOR < / B > = > grantor of access ( may be < code > null < / code > )
* < LI > < B > GRANTEE < / B > String = > grantee of access
* < LI > < B > PRIVILEGE < / B > String = > name of access ( SELECT ,
* INSERT , UPDATE , REFRENCES , . . . )
* < LI > < B > IS _ GRANTABLE < / B > String = > " YES " if grantee is permitted
* to grant to others ; " NO " if not ; < code > null < / code > if unknown
* < / OL >
* < ! - - start release - specific documentation - - >
* < div class = " ReleaseSpecificDocumentation " >
* < h3 > HSQLDB - Specific Information : < / h3 > < p >
* HSQLDB supports the SQL Standard . It treats unquoted identifiers as
* case insensitive in SQL and stores
* them in upper case ; it treats quoted identifiers as case sensitive and
* stores them verbatim . All JDBCDatabaseMetaData methods perform
* case - sensitive comparison between name ( pattern ) arguments and the
* corresponding identifier values as they are stored in the database .
* Therefore , care must be taken to specify name arguments precisely
* ( including case ) as they are stored in the database . < p >
* Since 1.7.2 , this feature is supported by default . If the jar is
* compiled without org . hsqldb _ voltpatches . DatabaseInformationFull or
* org . hsqldb _ voltpatches . DatabaseInformationMain , the feature is
* not supported . The default implementation is
* { @ link org . hsqldb _ voltpatches . dbinfo . DatabaseInformationFull } .
* < / div >
* < ! - - end release - specific documentation - - >
* @ param catalog a catalog name ; must match the catalog name as it
* is stored in the database ; " " retrieves those without a catalog ;
* < code > null < / code > means that the catalog name should not be used to narrow
* the search
* @ param schemaPattern a schema name pattern ; must match the schema name
* as it is stored in the database ; " " retrieves those without a schema ;
* < code > null < / code > means that the schema name should not be used to narrow
* the search
* @ param tableNamePattern a table name pattern ; must match the
* table name as it is stored in the database
* @ return < code > ResultSet < / code > - each row is a table privilege description
* @ exception SQLException if a database access error occurs
* @ see # getSearchStringEscape */
public ResultSet getTablePrivileges ( String catalog , String schemaPattern , String tableNamePattern ) throws SQLException { } } | schemaPattern = translateSchema ( schemaPattern ) ; String sql = "SELECT TABLE_CATALOG TABLE_CAT, TABLE_SCHEMA TABLE_SCHEM," + "TABLE_NAME, GRANTOR, GRANTEE, PRIVILEGE_TYPE PRIVILEGE, IS_GRANTABLE " + "FROM INFORMATION_SCHEMA.TABLE_PRIVILEGES WHERE TRUE " + and ( "TABLE_CATALOG" , "=" , catalog ) + and ( "TABLE_SCHEMA" , "LIKE" , schemaPattern ) + and ( "TABLE_NAME" , "LIKE" , tableNamePattern ) ; /* if ( wantsIsNull ( tableNamePattern ) ) {
return executeSelect ( " SYSTEM _ TABLEPRIVILEGES " , " 0 = 1 " ) ; */
// By default , the query already returns a result ordered by
// TABLE _ SCHEM , TABLE _ NAME , and PRIVILEGE . . .
return execute ( sql ) ; |
public class Utility { /** * Replace every occurrence of the strings in the map with the new data . */
public static String replace ( String string , Map < String , String > ht ) { } } | return Utility . replace ( new StringBuilder ( string ) , ht ) . toString ( ) ; |
public class Keys { /** * Generates a 32 - byte secret key .
* @ return a 32 - byte secret key */
public static byte [ ] generateSecretKey ( ) { } } | final byte [ ] k = new byte [ KEY_LEN ] ; final SecureRandom random = new SecureRandom ( ) ; random . nextBytes ( k ) ; return k ; |
public class CholeskyDecompositionBlock_DDRM { /** * Performs Choleksy decomposition on the provided matrix .
* If the matrix is not positive definite then this function will return
* false since it can ' t complete its computations . Not all errors will be
* found .
* @ return True if it was able to finish the decomposition . */
@ Override protected boolean decomposeLower ( ) { } } | if ( n < blockWidth ) B . reshape ( 0 , 0 , false ) ; else B . reshape ( blockWidth , n - blockWidth , false ) ; int numBlocks = n / blockWidth ; int remainder = n % blockWidth ; if ( remainder > 0 ) { numBlocks ++ ; } B . numCols = n ; for ( int i = 0 ; i < numBlocks ; i ++ ) { B . numCols -= blockWidth ; if ( B . numCols > 0 ) { // apply cholesky to the current block
if ( ! chol . decompose ( T , ( i * blockWidth ) * T . numCols + i * blockWidth , blockWidth ) ) return false ; int indexSrc = i * blockWidth * T . numCols + ( i + 1 ) * blockWidth ; int indexDst = ( i + 1 ) * blockWidth * T . numCols + i * blockWidth ; // B = L ^ ( - 1 ) * B
solveL_special ( chol . getL ( ) . data , T , indexSrc , indexDst , B ) ; int indexL = ( i + 1 ) * blockWidth * n + ( i + 1 ) * blockWidth ; // c = c - a ^ T * a
symmRankTranA_sub ( B , T , indexL ) ; } else { int width = remainder > 0 ? remainder : blockWidth ; if ( ! chol . decompose ( T , ( i * blockWidth ) * T . numCols + i * blockWidth , width ) ) return false ; } } // zero the top right corner .
for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { t [ i * n + j ] = 0.0 ; } } return true ; |
public class SARLRuntimeEnvironmentTab { /** * Loads the SARL runtime environment from the launch configuration ' s preference store .
* @ param config the config to load the runtime environment from */
protected void selectSREFromConfig ( ILaunchConfiguration config ) { } } | final boolean notify = this . sreBlock . getNotify ( ) ; final boolean changed ; try { this . sreBlock . setNotify ( false ) ; if ( this . accessor . getUseSystemSREFlag ( config ) ) { changed = this . sreBlock . selectSystemWideSRE ( ) ; } else if ( this . accessor . getUseProjectSREFlag ( config ) ) { changed = this . sreBlock . selectProjectSRE ( ) ; } else { final String sreId = this . accessor . getSREId ( config ) ; final ISREInstall sre = SARLRuntime . getSREFromId ( Strings . nullToEmpty ( sreId ) ) ; changed = this . sreBlock . selectSpecificSRE ( sre ) ; } } finally { this . sreBlock . setNotify ( notify ) ; } if ( changed ) { updateLaunchConfigurationDialog ( ) ; } |
public class AbstractMSBuildPluginMojo { /** * Return project configurations for the specified platform and configuration filtered by name using the specified
* Pattern .
* @ param platform the platform to parse for
* @ param configuration the configuration to parse for
* @ param filterRegex a Pattern to use to filter the projects
* @ return a list of VCProject objects containing configuration for the specified platform and configuration
* @ throws MojoExecutionException if parsing fails */
protected List < VCProject > getParsedProjects ( BuildPlatform platform , BuildConfiguration configuration , String filterRegex ) throws MojoExecutionException { } } | Pattern filterPattern = null ; List < VCProject > filteredList = new ArrayList < VCProject > ( ) ; if ( filterRegex != null ) { filterPattern = Pattern . compile ( filterRegex ) ; } for ( VCProject vcProject : getParsedProjects ( platform , configuration ) ) { if ( filterPattern == null ) { filteredList . add ( vcProject ) ; } else { Matcher prjExcludeMatcher = filterPattern . matcher ( vcProject . getName ( ) ) ; if ( ! prjExcludeMatcher . matches ( ) ) { filteredList . add ( vcProject ) ; } } } return filteredList ; |
public class AbstractObjectStore { /** * ( non - Javadoc )
* @ see com . ibm . ws . objectManager . ObjectStore # close ( ) */
public synchronized void close ( ) throws ObjectManagerException { } } | // Invalidate out all ManagedObjects in inMemory Tokens to prevent them
// from being used after shutdown .
for ( java . util . Iterator tokenIterator = inMemoryTokens . values ( ) . iterator ( ) ; tokenIterator . hasNext ( ) ; ) { java . lang . ref . Reference reference = ( java . lang . ref . Reference ) tokenIterator . next ( ) ; if ( reference != null ) { Token token = ( Token ) reference . get ( ) ; if ( token != null ) token . invalidate ( ) ; } // if ( reference ! = null ) .
} // for inMemoryTokens .
// Help garbage collection .
inMemoryTokens . clear ( ) ; inMemoryTokens = null ; |
public class TaskOperations { /** * Updates the specified task .
* @ param jobId
* The ID of the job containing the task .
* @ param taskId
* The ID of the task .
* @ param constraints
* Constraints that apply to this task . If null , the task is given
* the default constraints .
* @ throws BatchErrorException
* Exception thrown when an error response is received from the
* Batch service .
* @ throws IOException
* Exception thrown when there is an error in
* serialization / deserialization of data sent to / received from the
* Batch service . */
public void updateTask ( String jobId , String taskId , TaskConstraints constraints ) throws BatchErrorException , IOException { } } | updateTask ( jobId , taskId , constraints , null ) ; |
public class UnderFileSystemUtils { /** * Creates an empty file .
* @ param ufs instance of { @ link UnderFileSystem }
* @ param path path to the file */
public static void touch ( UnderFileSystem ufs , String path ) throws IOException { } } | OutputStream os = ufs . create ( path ) ; os . close ( ) ; |
public class Chain { /** * Set the member service
* @ param memberServices The MemberServices instance */
public void setMemberServices ( MemberServices memberServices ) { } } | this . memberServices = memberServices ; if ( memberServices instanceof MemberServicesImpl ) { this . cryptoPrimitives = ( ( MemberServicesImpl ) memberServices ) . getCrypto ( ) ; } |
public class IOUtils { /** * Drains the input stream and closes it . */
public static void drain ( InputStream in ) throws IOException { } } | org . apache . commons . io . IOUtils . copy ( in , new NullStream ( ) ) ; in . close ( ) ; |
public class AbstractCompositeHandler { /** * { @ inheritDoc } */
public boolean isQuery ( final String sql ) { } } | for ( final Pattern p : queryDetection ) { if ( p . matcher ( sql ) . lookingAt ( ) ) { return true ; } // end of if
} // end of for
return false ; |
public class EventGridSubscriber { /** * Checks if an event mapping with the given eventType exists .
* @ param eventType the event type name .
* @ return true if the mapping exists , false otherwise . */
@ Beta public boolean containsCustomEventMappingFor ( final String eventType ) { } } | if ( eventType == null || eventType . isEmpty ( ) ) { return false ; } else { return this . eventTypeToEventDataMapping . containsKey ( canonicalizeEventType ( eventType ) ) ; } |
public class AttributeUtils { /** * Casts or evaluates an expression then casts to the provided type . */
public static < T > T resolveValue ( Object value , Class < T > type , ELContext elContext ) { } } | if ( value == null ) { return null ; } else if ( value instanceof ValueExpression ) { return resolveValue ( ( ValueExpression ) value , type , elContext ) ; } else { return type . cast ( value ) ; } |
public class HFClient { /** * Get signature for update channel configuration
* @ param updateChannelConfiguration
* @ param signer
* @ return byte array with the signature
* @ throws InvalidArgumentException */
public byte [ ] getUpdateChannelConfigurationSignature ( UpdateChannelConfiguration updateChannelConfiguration , User signer ) throws InvalidArgumentException { } } | clientCheck ( ) ; Channel systemChannel = Channel . newSystemChannel ( this ) ; return systemChannel . getUpdateChannelConfigurationSignature ( updateChannelConfiguration , signer ) ; |
public class Converters { /** * Registers all the Java Time converters .
* @ param builder The GSON builder to register the converters with .
* @ return A reference to { @ code builder } . */
public static GsonBuilder registerAll ( GsonBuilder builder ) { } } | if ( builder == null ) { throw new NullPointerException ( "builder cannot be null" ) ; } registerLocalDate ( builder ) ; registerLocalDateTime ( builder ) ; registerLocalTime ( builder ) ; registerOffsetDateTime ( builder ) ; registerOffsetTime ( builder ) ; registerZonedDateTime ( builder ) ; registerInstant ( builder ) ; return builder ; |
public class KeenQueryClient { /** * Count Unique query with only the required arguments .
* Query API info here : https : / / keen . io / docs / api / # count - unique
* @ param eventCollection The name of the event collection you are analyzing .
* @ param targetProperty The name of the property you are analyzing .
* @ param timeframe The { @ link RelativeTimeframe } or { @ link AbsoluteTimeframe } .
* @ return The count unique query response .
* @ throws IOException If there was an error communicating with the server or
* an error message received from the server . */
public long countUnique ( String eventCollection , String targetProperty , Timeframe timeframe ) throws IOException { } } | Query queryParams = new Query . Builder ( QueryType . COUNT_UNIQUE ) . withEventCollection ( eventCollection ) . withTargetProperty ( targetProperty ) . withTimeframe ( timeframe ) . build ( ) ; QueryResult result = execute ( queryParams ) ; return queryResultToLong ( result ) ; |
public class AbstractClient { /** * or web client invocation has returned */
protected void prepareConduitSelector ( Message message , URI currentURI , boolean proxy ) { } } | try { cfg . prepareConduitSelector ( message ) ; } catch ( Fault ex ) { LOG . warning ( "Failure to prepare a message from conduit selector" ) ; } message . getExchange ( ) . put ( ConduitSelector . class , cfg . getConduitSelector ( ) ) ; message . getExchange ( ) . put ( Service . class , cfg . getConduitSelector ( ) . getEndpoint ( ) . getService ( ) ) ; String address = ( String ) message . get ( Message . ENDPOINT_ADDRESS ) ; // custom conduits may override the initial / current address
if ( address . startsWith ( HTTP_SCHEME ) && ! address . equals ( currentURI . toString ( ) ) ) { URI baseAddress = URI . create ( address ) ; currentURI = calculateNewRequestURI ( baseAddress , currentURI , proxy ) ; message . put ( Message . ENDPOINT_ADDRESS , currentURI . toString ( ) ) ; message . put ( Message . REQUEST_URI , currentURI . toString ( ) ) ; } message . put ( Message . BASE_PATH , getBaseURI ( ) . toString ( ) ) ; |
public class RRDToolWriter { /** * Calls out to the rrdtool binary with the ' create ' command . */
protected void rrdToolCreateDatabase ( RrdDef def ) throws Exception { } } | List < String > commands = new ArrayList < > ( ) ; commands . add ( this . binaryPath + "/rrdtool" ) ; commands . add ( "create" ) ; commands . add ( this . outputFile . getCanonicalPath ( ) ) ; commands . add ( "-s" ) ; commands . add ( String . valueOf ( def . getStep ( ) ) ) ; for ( DsDef dsdef : def . getDsDefs ( ) ) { commands . add ( getDsDefStr ( dsdef ) ) ; } for ( ArcDef adef : def . getArcDefs ( ) ) { commands . add ( getRraStr ( adef ) ) ; } ProcessBuilder pb = new ProcessBuilder ( commands ) ; Process process = pb . start ( ) ; try { checkErrorStream ( process ) ; } finally { IOUtils . closeQuietly ( process . getInputStream ( ) ) ; IOUtils . closeQuietly ( process . getOutputStream ( ) ) ; IOUtils . closeQuietly ( process . getErrorStream ( ) ) ; } |
public class LocalQueue { /** * Commit get operations on this queue ( messages are removed )
* @ return true if a store commit is required to ensure data safety */
public boolean remove ( LocalSession localSession , TransactionItem [ ] items ) throws JMSException { } } | checkNotClosed ( ) ; checkTransactionLock ( ) ; int volatileCommitted = 0 ; int persistentCommitted = 0 ; synchronized ( storeLock ) { for ( int n = 0 ; n < items . length ; n ++ ) { TransactionItem transactionItem = items [ n ] ; if ( transactionItem . getDestination ( ) != this ) continue ; if ( traceEnabled ) log . trace ( localSession + " COMMIT " + transactionItem . getMessageId ( ) ) ; // Delete message from store
if ( transactionItem . getDeliveryMode ( ) == DeliveryMode . PERSISTENT ) { persistentStore . delete ( transactionItem . getHandle ( ) ) ; persistentCommitted ++ ; } else { volatileStore . delete ( transactionItem . getHandle ( ) ) ; volatileCommitted ++ ; } } } acknowledgedGetCount . addAndGet ( volatileCommitted + persistentCommitted ) ; if ( persistentCommitted > 0 && requiresTransactionalUpdate ( ) ) { pendingChanges = true ; return true ; } else return false ; |
public class HeapKeyedStateBackend { @ SuppressWarnings ( "unchecked" ) @ Nonnull @ Override public < T extends HeapPriorityQueueElement & PriorityComparable & Keyed > KeyGroupedInternalPriorityQueue < T > create ( @ Nonnull String stateName , @ Nonnull TypeSerializer < T > byteOrderedElementSerializer ) { } } | final HeapPriorityQueueSnapshotRestoreWrapper existingState = registeredPQStates . get ( stateName ) ; if ( existingState != null ) { // TODO we implement the simple way of supporting the current functionality , mimicking keyed state
// because this should be reworked in FLINK - 9376 and then we should have a common algorithm over
// StateMetaInfoSnapshot that avoids this code duplication .
TypeSerializerSchemaCompatibility < T > compatibilityResult = existingState . getMetaInfo ( ) . updateElementSerializer ( byteOrderedElementSerializer ) ; if ( compatibilityResult . isIncompatible ( ) ) { throw new FlinkRuntimeException ( new StateMigrationException ( "For heap backends, the new priority queue serializer must not be incompatible." ) ) ; } else { registeredPQStates . put ( stateName , existingState . forUpdatedSerializer ( byteOrderedElementSerializer ) ) ; } return existingState . getPriorityQueue ( ) ; } else { final RegisteredPriorityQueueStateBackendMetaInfo < T > metaInfo = new RegisteredPriorityQueueStateBackendMetaInfo < > ( stateName , byteOrderedElementSerializer ) ; return createInternal ( metaInfo ) ; } |
public class AbstractDatabaseConfiguration { /** * Returns the temp directory . The default temp directory is APP _ CACHE _ DIR / Couchbase / tmp .
* If a custom database directory is set , the temp directory will be
* CUSTOM _ DATABASE _ DIR / Couchbase / tmp . */
private String getTempDir ( ) { } } | return ( ! customDir ) ? CouchbaseLite . getTmpDirectory ( TEMP_DIR_NAME ) : CouchbaseLite . getTmpDirectory ( directory , TEMP_DIR_NAME ) ; |
public class ClientBehaviorBase { /** * < p class = " changed _ added _ 2_0 " > Convenience method to return the
* { @ link ClientBehaviorRenderer } instance associated with this
* { @ link ClientBehavior } , if any ; otherwise , return
* < code > null < / code > . < / p >
* @ param context { @ link FacesContext } for the request we are processing
* @ return { @ link ClientBehaviorRenderer } instance from the current { @ link RenderKit } or null .
* @ throws NullPointerException if < code > context < / code > is null .
* @ since 2.0 */
protected ClientBehaviorRenderer getRenderer ( FacesContext context ) { } } | if ( null == context ) { throw new NullPointerException ( ) ; } ClientBehaviorRenderer renderer = null ; String rendererType = getRendererType ( ) ; if ( null != rendererType ) { RenderKit renderKit = context . getRenderKit ( ) ; if ( null != renderKit ) { renderer = renderKit . getClientBehaviorRenderer ( rendererType ) ; } if ( null == renderer ) { if ( logger . isLoggable ( Level . FINE ) ) { logger . fine ( "Can't get behavior renderer for type " + rendererType ) ; } } } else { if ( logger . isLoggable ( Level . FINE ) ) { logger . fine ( "No renderer-type for behavior " + this . getClass ( ) . getName ( ) ) ; } } return renderer ; |
public class MonocleView { /** * DnD */
@ Override protected int notifyDragEnter ( int x , int y , int absx , int absy , int recommendedDropAction ) { } } | return super . notifyDragEnter ( x , y , absx , absy , recommendedDropAction ) ; |
public class Box { /** * Helper method for { @ link # intersects ( Ray3 ) } . Determines whether the ray intersects the box
* at the plane where y equals the value specified . */
protected boolean intersectsY ( IRay3 ray , float y ) { } } | IVector3 origin = ray . origin ( ) , dir = ray . direction ( ) ; float t = ( y - origin . y ( ) ) / dir . y ( ) ; if ( t < 0f ) { return false ; } float ix = origin . x ( ) + t * dir . x ( ) , iz = origin . z ( ) + t * dir . z ( ) ; return ix >= _minExtent . x && ix <= _maxExtent . x && iz >= _minExtent . z && iz <= _maxExtent . z ; |
public class StrictModeUtils { /** * Turn on Strict Mode options . Good idea for dev builds .
* See : http : / / developer . android . com / reference / android / os / StrictMode . html */
public static void enableStrictModeForDevRelease ( ) { } } | StrictMode . setThreadPolicy ( new StrictMode . ThreadPolicy . Builder ( ) . detectDiskReads ( ) . detectDiskWrites ( ) . detectNetwork ( ) . penaltyFlashScreen ( ) . build ( ) ) ; |
public class ConfigManager { /** * Reload the pools config and update all in - memory values
* @ throws ParserConfigurationException
* @ throws SAXException
* @ throws IOException */
private void reloadPoolsConfig ( ) throws IOException , SAXException , ParserConfigurationException { } } | if ( poolsConfigFileName == null ) { return ; } Set < String > newPoolGroupNameSet = new HashSet < String > ( ) ; Set < PoolInfo > newPoolInfoSet = new HashSet < PoolInfo > ( ) ; TypePoolGroupNameMap < Integer > newTypePoolNameGroupToMax = new TypePoolGroupNameMap < Integer > ( ) ; TypePoolGroupNameMap < Integer > newTypePoolNameGroupToMin = new TypePoolGroupNameMap < Integer > ( ) ; TypePoolInfoMap < Integer > newTypePoolInfoToMax = new TypePoolInfoMap < Integer > ( ) ; TypePoolInfoMap < Integer > newTypePoolInfoToMin = new TypePoolInfoMap < Integer > ( ) ; Map < PoolInfo , ScheduleComparator > newPoolInfoToComparator = new HashMap < PoolInfo , ScheduleComparator > ( ) ; Map < PoolInfo , Double > newPoolInfoToWeight = new HashMap < PoolInfo , Double > ( ) ; Map < PoolInfo , Integer > newPoolInfoToPriority = new HashMap < PoolInfo , Integer > ( ) ; Map < PoolInfo , String > newPoolInfoToWhitelist = new HashMap < PoolInfo , String > ( ) ; Map < PoolInfo , PoolInfo > newJobExceedsLimitPoolRedirect = new HashMap < PoolInfo , PoolInfo > ( ) ; Map < PoolInfo , Long > newPoolJobSizeLimit = new HashMap < PoolInfo , Long > ( ) ; Element root = getRootElement ( poolsConfigFileName ) ; NodeList elements = root . getChildNodes ( ) ; for ( int i = 0 ; i < elements . getLength ( ) ; ++ i ) { Node node = elements . item ( i ) ; if ( ! ( node instanceof Element ) ) { continue ; } Element element = ( Element ) node ; if ( matched ( element , GROUP_TAG_NAME ) ) { String groupName = element . getAttribute ( NAME_ATTRIBUTE ) ; if ( ! newPoolGroupNameSet . add ( groupName ) ) { LOG . debug ( "Already added group " + groupName ) ; } NodeList groupFields = element . getChildNodes ( ) ; for ( int j = 0 ; j < groupFields . getLength ( ) ; ++ j ) { Node groupNode = groupFields . item ( j ) ; if ( ! ( groupNode instanceof Element ) ) { continue ; } Element field = ( Element ) groupNode ; for ( ResourceType type : TYPES ) { if ( matched ( field , MIN_TAG_NAME_PREFIX + type ) ) { int val = Integer . parseInt ( getText ( field ) ) ; newTypePoolNameGroupToMin . put ( type , groupName , val ) ; } if ( matched ( field , MAX_TAG_NAME_PREFIX + type ) ) { int val = Integer . parseInt ( getText ( field ) ) ; newTypePoolNameGroupToMax . put ( type , groupName , val ) ; } } if ( matched ( field , REDIRECT_JOB_WITH_LIMIT ) ) { loadPoolInfoToRedirect ( groupName , field . getAttribute ( SOURCE_ATTRIBUTE ) , field . getAttribute ( DESTINATION_ATTRIBUTE ) , field . getAttribute ( JOB_INPUT_SIZE_LIMIT_ATTRIBUTE ) , newJobExceedsLimitPoolRedirect , newPoolJobSizeLimit ) ; } if ( matched ( field , POOL_TAG_NAME ) ) { PoolInfo poolInfo = new PoolInfo ( groupName , field . getAttribute ( "name" ) ) ; if ( ! newPoolInfoSet . add ( poolInfo ) ) { LOG . warn ( "Already added pool info " + poolInfo ) ; } NodeList poolFields = field . getChildNodes ( ) ; for ( int k = 0 ; k < poolFields . getLength ( ) ; ++ k ) { Node poolNode = poolFields . item ( k ) ; if ( ! ( poolNode instanceof Element ) ) { continue ; } Element poolField = ( Element ) poolNode ; for ( ResourceType type : TYPES ) { if ( matched ( poolField , MIN_TAG_NAME_PREFIX + type ) ) { int val = Integer . parseInt ( getText ( poolField ) ) ; newTypePoolInfoToMin . put ( type , poolInfo , val ) ; } if ( matched ( poolField , MAX_TAG_NAME_PREFIX + type ) ) { int val = Integer . parseInt ( getText ( poolField ) ) ; newTypePoolInfoToMax . put ( type , poolInfo , val ) ; } } if ( matched ( poolField , PREEMPTABILITY_MODE_TAG_NAME ) ) { boolean val = Boolean . parseBoolean ( getText ( poolField ) ) ; if ( ! val ) { nonPreemptablePools . add ( poolInfo ) ; } } if ( matched ( poolField , REQUEST_MAX_MODE_TAG_NAME ) ) { boolean val = Boolean . parseBoolean ( getText ( poolField ) ) ; if ( val ) { requestMaxPools . add ( poolInfo ) ; } } if ( matched ( poolField , SCHEDULING_MODE_TAG_NAME ) ) { ScheduleComparator val = ScheduleComparator . valueOf ( getText ( poolField ) ) ; newPoolInfoToComparator . put ( poolInfo , val ) ; } if ( matched ( poolField , WEIGHT_TAG_NAME ) ) { double val = Double . parseDouble ( getText ( poolField ) ) ; newPoolInfoToWeight . put ( poolInfo , val ) ; } if ( matched ( poolField , PRIORITY_TAG_NAME ) ) { int val = Integer . parseInt ( getText ( poolField ) ) ; newPoolInfoToPriority . put ( poolInfo , val ) ; } if ( matched ( poolField , WHITELIST_TAG_NAME ) ) { newPoolInfoToWhitelist . put ( poolInfo , getText ( poolField ) ) ; } } } } } } synchronized ( this ) { this . poolGroupNameSet = newPoolGroupNameSet ; this . poolInfoSet = Collections . unmodifiableSet ( newPoolInfoSet ) ; this . typePoolGroupNameToMax = newTypePoolNameGroupToMax ; this . typePoolGroupNameToMin = newTypePoolNameGroupToMin ; this . typePoolInfoToMax = newTypePoolInfoToMax ; this . typePoolInfoToMin = newTypePoolInfoToMin ; this . poolInfoToComparator = newPoolInfoToComparator ; this . poolInfoToWeight = newPoolInfoToWeight ; this . poolInfoToPriority = newPoolInfoToPriority ; this . poolInfoToWhitelist = newPoolInfoToWhitelist ; this . jobExceedsLimitPoolRedirect = newJobExceedsLimitPoolRedirect ; this . poolJobSizeLimit = newPoolJobSizeLimit ; } |
public class DisplacedList { /** * Inherited from ArrayList
* @ param index
* @ return */
@ Override public T remove ( int index ) { } } | if ( displacement != null ) { return super . get ( index - displacement ) ; } return super . remove ( index ) ; |
public class UserHandlerImpl { /** * { @ inheritDoc } */
public User setEnabled ( String userName , boolean enabled , boolean broadcast ) throws Exception , UnsupportedOperationException { } } | User foundUser = findUserByName ( userName , UserStatus . ANY ) ; if ( foundUser == null || foundUser . isEnabled ( ) == enabled ) { return foundUser ; } synchronized ( foundUser . getUserName ( ) ) { Session session = service . getStorageSession ( ) ; try { ( ( UserImpl ) foundUser ) . setEnabled ( enabled ) ; if ( broadcast ) preSetEnabled ( foundUser ) ; Node node = getUserNode ( session , ( UserImpl ) foundUser ) ; if ( enabled ) { if ( ! node . canAddMixin ( JCROrganizationServiceImpl . JOS_DISABLED ) ) { node . removeMixin ( JCROrganizationServiceImpl . JOS_DISABLED ) ; PropertyIterator pi = node . getReferences ( ) ; while ( pi . hasNext ( ) ) { Node n = pi . nextProperty ( ) . getParent ( ) ; if ( ! n . canAddMixin ( JCROrganizationServiceImpl . JOS_DISABLED ) ) { n . removeMixin ( JCROrganizationServiceImpl . JOS_DISABLED ) ; } } } } else { if ( node . canAddMixin ( JCROrganizationServiceImpl . JOS_DISABLED ) ) { node . addMixin ( JCROrganizationServiceImpl . JOS_DISABLED ) ; PropertyIterator pi = node . getReferences ( ) ; while ( pi . hasNext ( ) ) { Node n = pi . nextProperty ( ) . getParent ( ) ; if ( n . canAddMixin ( JCROrganizationServiceImpl . JOS_DISABLED ) ) { n . addMixin ( JCROrganizationServiceImpl . JOS_DISABLED ) ; } } } } session . save ( ) ; if ( broadcast ) postSetEnabled ( foundUser ) ; putInCache ( foundUser ) ; } finally { session . logout ( ) ; } return foundUser ; } |
public class DNSInput { /** * Resets the current position of the input stream to the specified index ,
* and clears the active region .
* @ param index The position to continue parsing at .
* @ throws IllegalArgumentException The index is not within the input . */
public void jump ( int index ) { } } | if ( index >= array . length ) { throw new IllegalArgumentException ( "cannot jump past " + "end of input" ) ; } pos = index ; end = array . length ; |
public class PropertyFile { public void load ( final Reader r ) throws IOException { } } | try ( BufferedReader in = new BufferedReader ( r ) ) { entries . clear ( ) ; vars . clear ( ) ; String line = in . readLine ( ) ; while ( line != null ) { // Parse the line
if ( line . length ( ) == 0 ) { entries . add ( new BlankLine ( ) ) ; } else { char c = line . charAt ( 0 ) ; if ( c == COMMENT_CHAR ) { if ( ! line . startsWith ( COMMENT_INST ) ) { // Don ' t load instance comments
entries . add ( new Comment ( line . substring ( 1 ) ) ) ; } } else if ( c == ' ' ) { // If it starts with a space let ' s call it a blank line
entries . add ( new BlankLine ( ) ) ; } else { // Name = Value pair
// TODO - handle escaped characters ( notably , \ = and \ n )
final int equalsIndex = line . indexOf ( '=' ) ; if ( equalsIndex != - 1 ) { String name = line . substring ( 0 , equalsIndex ) . trim ( ) ; String value = line . substring ( equalsIndex + 1 ) ; NameValuePair nvp = new NameValuePair ( name , value ) ; if ( vars . containsKey ( nvp . name ) ) { log . warn ( "{load} duplicate entry '" + nvp . name + "': overwriting previous value" ) ; } entries . add ( nvp ) ; vars . put ( caseSensitive ? nvp . name : nvp . name . toLowerCase ( ) , nvp ) ; } else { log . error ( "Malformed line in property file: " + line ) ; } } } line = in . readLine ( ) ; } hook_loaded ( ) ; } |
public class SimpleHTMLTag { /** * Returns a property of this tag by key , if present .
* @ param key Property key
* @ return Property value or null */
public String getProperty ( String key ) { } } | key = UniformUtils . checkPropertyNameAndLowerCase ( key ) ; if ( properties == null ) { return null ; } return properties . get ( key ) ; |
public class SimpleBitfinexApiBroker { /** * Find the channel for the given symbol
* @ param symbol
* @ return */
private Integer getChannelForSymbol ( final BitfinexStreamSymbol symbol ) { } } | synchronized ( channelIdToHandlerMap ) { return channelIdToHandlerMap . values ( ) . stream ( ) . filter ( v -> Objects . equals ( v . getSymbol ( ) , symbol ) ) . map ( ChannelCallbackHandler :: getChannelId ) . findFirst ( ) . orElse ( null ) ; } |
public class UpdateBuilder { /** * Updates fields in the document referred to by this DocumentReference . If the document doesn ' t
* exist yet , the update will fail .
* @ param documentReference The DocumentReference to update .
* @ param fields A Map containing the fields and values with which to update the document .
* @ return The instance for chaining . */
@ Nonnull public T update ( @ Nonnull DocumentReference documentReference , @ Nonnull Map < String , Object > fields ) { } } | return performUpdate ( documentReference , convertToFieldPaths ( fields , /* splitOnDots = */
true ) , Precondition . exists ( true ) ) ; |
public class LocationAttributes { /** * Returns the line number of an element ( DOM flavor )
* @ param elem
* the element that holds the location information
* @ return the element ' s line number or < code > - 1 < / code > if < code > elem < / code >
* has no location information . */
public static int getLine ( Element elem ) { } } | Attr attr = elem . getAttributeNodeNS ( URI , LINE_ATTR ) ; return attr != null ? Integer . parseInt ( attr . getValue ( ) ) : - 1 ; |
public class ASpatialDb { /** * Get the geometries of a table inside a given envelope .
* @ param tableName
* the table name .
* @ param envelope
* the envelope to check .
* @ param prePostWhere an optional set of 3 parameters . The parameters are : a
* prefix wrapper for geom , a postfix for the same and a where string
* to apply . They all need to be existing if the parameter is passed .
* @ return The list of geometries intersecting the envelope .
* @ throws Exception */
public List < Geometry > getGeometriesIn ( String tableName , Envelope envelope , String ... prePostWhere ) throws Exception { } } | List < Geometry > geoms = new ArrayList < Geometry > ( ) ; List < String > wheres = new ArrayList < > ( ) ; String pre = "" ; String post = "" ; String where = "" ; if ( prePostWhere != null && prePostWhere . length == 3 ) { if ( prePostWhere [ 0 ] != null ) pre = prePostWhere [ 0 ] ; if ( prePostWhere [ 1 ] != null ) post = prePostWhere [ 1 ] ; if ( prePostWhere [ 2 ] != null ) { where = prePostWhere [ 2 ] ; wheres . add ( where ) ; } } GeometryColumn gCol = getGeometryColumnsForTable ( tableName ) ; String sql = "SELECT " + pre + gCol . geometryColumnName + post + " FROM " + tableName ; if ( envelope != null ) { double x1 = envelope . getMinX ( ) ; double y1 = envelope . getMinY ( ) ; double x2 = envelope . getMaxX ( ) ; double y2 = envelope . getMaxY ( ) ; wheres . add ( getSpatialindexBBoxWherePiece ( tableName , null , x1 , y1 , x2 , y2 ) ) ; } if ( wheres . size ( ) > 0 ) { sql += " WHERE " + DbsUtilities . joinBySeparator ( wheres , " AND " ) ; } String _sql = sql ; IGeometryParser geometryParser = getType ( ) . getGeometryParser ( ) ; return execOnConnection ( connection -> { try ( IHMStatement stmt = connection . createStatement ( ) ; IHMResultSet rs = stmt . executeQuery ( _sql ) ) { while ( rs . next ( ) ) { Geometry geometry = geometryParser . fromResultSet ( rs , 1 ) ; geoms . add ( geometry ) ; } return geoms ; } } ) ; |
public class TaskInfo { /** * < code > optional . alluxio . grpc . job . Status status = 3 ; < / code > */
public alluxio . grpc . Status getStatus ( ) { } } | alluxio . grpc . Status result = alluxio . grpc . Status . valueOf ( status_ ) ; return result == null ? alluxio . grpc . Status . UNKNOWN : result ; |
public class PurgeMojo { /** * Purges the local copy of the NVD .
* @ throws MojoExecutionException thrown if there is an exception executing
* the goal
* @ throws MojoFailureException thrown if dependency - check is configured to
* fail the build */
@ Override protected void runCheck ( ) throws MojoExecutionException , MojoFailureException { } } | if ( getConnectionString ( ) != null && ! getConnectionString ( ) . isEmpty ( ) ) { final String msg = "Unable to purge the local NVD when using a non-default connection string" ; if ( this . isFailOnError ( ) ) { throw new MojoFailureException ( msg ) ; } getLog ( ) . error ( msg ) ; } else { populateSettings ( ) ; final File db ; try { db = new File ( getSettings ( ) . getDataDirectory ( ) , getSettings ( ) . getString ( Settings . KEYS . DB_FILE_NAME , "odc.mv.db" ) ) ; if ( db . exists ( ) ) { if ( db . delete ( ) ) { getLog ( ) . info ( "Database file purged; local copy of the NVD has been removed" ) ; } else { final String msg = String . format ( "Unable to delete '%s'; please delete the file manually" , db . getAbsolutePath ( ) ) ; if ( this . isFailOnError ( ) ) { throw new MojoFailureException ( msg ) ; } getLog ( ) . error ( msg ) ; } } else { final String msg = String . format ( "Unable to purge database; the database file does not exist: %s" , db . getAbsolutePath ( ) ) ; if ( this . isFailOnError ( ) ) { throw new MojoFailureException ( msg ) ; } getLog ( ) . error ( msg ) ; } } catch ( IOException ex ) { final String msg = "Unable to delete the database" ; if ( this . isFailOnError ( ) ) { throw new MojoExecutionException ( msg , ex ) ; } getLog ( ) . error ( msg ) ; } getSettings ( ) . cleanup ( ) ; } |
public class FtpClient { /** * Performs store file operation .
* @ param command
* @ param context */
protected FtpMessage storeFile ( PutCommand command , TestContext context ) { } } | try { String localFilePath = context . replaceDynamicContentInString ( command . getFile ( ) . getPath ( ) ) ; String remoteFilePath = addFileNameToTargetPath ( localFilePath , context . replaceDynamicContentInString ( command . getTarget ( ) . getPath ( ) ) ) ; String dataType = context . replaceDynamicContentInString ( Optional . ofNullable ( command . getFile ( ) . getType ( ) ) . orElse ( DataType . BINARY . name ( ) ) ) ; try ( InputStream localFileInputStream = getLocalFileInputStream ( command . getFile ( ) . getPath ( ) , dataType , context ) ) { ftpClient . setFileType ( getFileType ( dataType ) ) ; if ( ! ftpClient . storeFile ( remoteFilePath , localFileInputStream ) ) { throw new IOException ( "Failed to put file to FTP server. Remote path: " + remoteFilePath + ". Local file path: " + localFilePath + ". FTP reply: " + ftpClient . getReplyString ( ) ) ; } } } catch ( IOException e ) { throw new CitrusRuntimeException ( "Failed to put file to FTP server" , e ) ; } return FtpMessage . putResult ( ftpClient . getReplyCode ( ) , ftpClient . getReplyString ( ) , isPositive ( ftpClient . getReplyCode ( ) ) ) ; |
public class FilesystemConnector { /** * dsId and dsVersionId may be null */
private InputStream getStream ( String pid , String dsId , String dsVersionId ) { } } | File file = getFile ( pid , dsId , dsVersionId ) ; try { return new FileInputStream ( file ) ; } catch ( FileNotFoundException e ) { return null ; } |
public class AbstractValidateableDialogPreference { /** * Initializes the preference .
* @ param attributeSet
* The attribute set , the attributes should be obtained from , as an instance of the type
* { @ link AttributeSet }
* @ param defaultStyle
* The default style to apply to this preference . If 0 , no style will be applied ( beyond
* what is included in the theme ) . This may either be an attribute resource , whose value
* will be retrieved from the current theme , or an explicit style resource
* @ param defaultStyleResource
* A resource identifier of a style resource that supplies default values for the
* preference , used only if the default style is 0 or can not be found in the theme . Can
* be 0 to not look for defaults */
private void initialize ( final AttributeSet attributeSet , @ AttrRes final int defaultStyle , @ StyleRes final int defaultStyleResource ) { } } | validators = new LinkedHashSet < > ( ) ; validationListeners = new ListenerList < > ( ) ; obtainStyledAttributes ( attributeSet , defaultStyle , defaultStyleResource ) ; |
public class VoiceApi { /** * Complete a transfer
* Complete a previously initiated two - step transfer using the provided IDs .
* @ param id The connection ID of the consult call ( established ) . ( required )
* @ param completeTransferData ( required )
* @ return ApiResponse & lt ; ApiSuccessResponse & gt ;
* @ throws ApiException If fail to call the API , e . g . server error or cannot deserialize the response body */
public ApiResponse < ApiSuccessResponse > completeTransferWithHttpInfo ( String id , CompleteTransferData completeTransferData ) throws ApiException { } } | com . squareup . okhttp . Call call = completeTransferValidateBeforeCall ( id , completeTransferData , null , null ) ; Type localVarReturnType = new TypeToken < ApiSuccessResponse > ( ) { } . getType ( ) ; return apiClient . execute ( call , localVarReturnType ) ; |
public class BooleanExpression { /** * 获得表达式的结果 。 子类可以重载这个方法 。
* @ param context
* @ return result */
public boolean evaluate ( Object context ) { } } | switch ( operatorType ) { case OPERATOR_AND : for ( BooleanExpression e : children ) { if ( e . evaluate ( context ) == false ) { return false ; } } return true ; case OPERATOR_OR : for ( BooleanExpression e : children ) { if ( e . evaluate ( context ) == true ) { return true ; } } return false ; case OPERATOR_NOT : if ( children . size ( ) != 1 ) { throw new UnsupportedOperationException ( "One and only one operand is allowed for NOT operator." ) ; } BooleanExpression e = children . get ( 0 ) ; return ! e . evaluate ( context ) ; default : throw new UnsupportedOperationException ( "Operand should implement its own evaluation method." ) ; } |
public class ValidationMessageManager { /** * Applies the message parameters and returns the message
* from one of the message bundles .
* @ param key property key
* @ param params message parameters to be used in message ' s place holders
* @ return Resource value or place - holder error String */
public static String getString ( String key , Object ... params ) { } } | String message = getStringSafely ( key ) ; if ( params != null && params . length > 0 ) { return MessageFormat . format ( message , params ) ; } else { return message ; } |
public class EntryStream { /** * Returns an { @ code EntryStream } object which contains the entries of
* supplied { @ code Map } .
* @ param < K > the type of map keys
* @ param < V > the type of map values
* @ param map the map to create the stream from
* @ return a new { @ code EntryStream } */
public static < K , V > EntryStream < K , V > of ( Map < K , V > map ) { } } | return of ( map . entrySet ( ) . stream ( ) ) ; |
public class CmsSitemapController { /** * Loads all available galleries for the current sub site . < p > */
public void loadGalleries ( ) { } } | CmsRpcAction < Map < CmsGalleryType , List < CmsGalleryFolderEntry > > > action = new CmsRpcAction < Map < CmsGalleryType , List < CmsGalleryFolderEntry > > > ( ) { @ Override public void execute ( ) { start ( 500 , false ) ; getService ( ) . getGalleryData ( m_data . getRoot ( ) . getSitePath ( ) , this ) ; } @ Override protected void onResponse ( Map < CmsGalleryType , List < CmsGalleryFolderEntry > > result ) { storeGalleryTypes ( result . keySet ( ) ) ; CmsSitemapView . getInstance ( ) . displayGalleries ( result ) ; stop ( false ) ; } } ; action . execute ( ) ; |
public class NumberColumn { /** * { @ inheritDoc } */
@ Override protected int readData ( byte [ ] buffer , int offset ) { } } | FixedSizeItemsBlock data = new FixedSizeItemsBlock ( ) . read ( buffer , offset ) ; offset = data . getOffset ( ) ; byte [ ] [ ] rawData = data . getData ( ) ; m_data = new Double [ rawData . length ] ; for ( int index = 0 ; index < rawData . length ; index ++ ) { m_data [ index ] = FastTrackUtility . getDouble ( rawData [ index ] , 0 ) ; } return offset ; |
public class LoggerFactory { /** * Return the single class name from a class - name string . */
public static String getSimpleClassName ( String className ) { } } | // get the last part of the class name
String [ ] parts = className . split ( "\\." ) ; if ( parts . length <= 1 ) { return className ; } else { return parts [ parts . length - 1 ] ; } |
public class SystemExiter { /** * Invokes the exit logger if and only if no ExitLogger was previously invoked .
* @ param logger the logger . Cannot be { @ code null } */
public static void logBeforeExit ( ExitLogger logger ) { } } | try { if ( logged . compareAndSet ( false , true ) ) { logger . logExit ( ) ; } } catch ( Throwable ignored ) { // ignored
} |
public class AtomContainerSet { /** * Get an iterator for this AtomContainerSet .
* @ return A new Iterator for this AtomContainerSet . */
@ Override public Iterable < IAtomContainer > atomContainers ( ) { } } | return new Iterable < IAtomContainer > ( ) { @ Override public Iterator < IAtomContainer > iterator ( ) { return new AtomContainerIterator ( ) ; } } ; |
public class AtomPlacer3D { /** * Gets the farthestAtom attribute of the AtomPlacer3D object .
* @ param refAtomPoint Description of the Parameter
* @ param ac Description of the Parameter
* @ return The farthestAtom value */
public IAtom getFarthestAtom ( Point3d refAtomPoint , IAtomContainer ac ) { } } | double distance = 0 ; IAtom atom = null ; for ( int i = 0 ; i < ac . getAtomCount ( ) ; i ++ ) { if ( ac . getAtom ( i ) . getPoint3d ( ) != null ) { if ( Math . abs ( refAtomPoint . distance ( ac . getAtom ( i ) . getPoint3d ( ) ) ) > distance ) { atom = ac . getAtom ( i ) ; distance = Math . abs ( refAtomPoint . distance ( ac . getAtom ( i ) . getPoint3d ( ) ) ) ; } } } return atom ; |
public class Utils { /** * Load and encode image into Base64.
* @ param in stream to read image
* @ param maxSize max size of image , if less or zero then don ' t rescale
* @ return null if it was impossible to load image for its format , loaded
* prepared image
* @ throws IOException if any error during conversion or loading
* @ since 1.4.0 */
@ Nullable public static String rescaleImageAndEncodeAsBase64 ( @ Nonnull final InputStream in , final int maxSize ) throws IOException { } } | final Image image = ImageIO . read ( in ) ; String result = null ; if ( image != null ) { result = rescaleImageAndEncodeAsBase64 ( image , maxSize ) ; } return result ; |
public class SQLBooleanResultSet { /** * Returns true if there is at least one result */
@ Override public boolean getValue ( ) throws OntopConnectionException { } } | if ( hasRead ) throw new IllegalStateException ( "getValue() can only called once!" ) ; hasRead = true ; try { return set . next ( ) ; } catch ( SQLException e ) { throw new OntopConnectionException ( e ) ; } |
public class TreeUtil { /** * Search for components implementing a particular class name .
* @ param root the root component to search from
* @ param className the class name to search for
* @ param includeRoot check the root component as well
* @ param visibleOnly true if process visible only
* @ return the list of components implementing the class name */
public static List < ComponentWithContext > findComponentsByClass ( final WComponent root , final String className , final boolean includeRoot , final boolean visibleOnly ) { } } | FindComponentsByClassVisitor visitor = new FindComponentsByClassVisitor ( root , className , includeRoot ) ; doTraverse ( root , visibleOnly , visitor ) ; return visitor . getResult ( ) == null ? Collections . EMPTY_LIST : visitor . getResult ( ) ; |
public class BindTransformer { /** * Get java . util type Transformable
* @ param type
* the type
* @ return the util transform */
static BindTransform getUtilTransform ( TypeName type ) { } } | String typeName = type . toString ( ) ; // Integer . class . getCanonicalName ( ) . equals ( typeName )
if ( Date . class . getCanonicalName ( ) . equals ( typeName ) ) { return new DateBindTransform ( ) ; } if ( Locale . class . getCanonicalName ( ) . equals ( typeName ) ) { return new LocaleBindTransform ( ) ; } if ( Currency . class . getCanonicalName ( ) . equals ( typeName ) ) { return new CurrencyBindTransform ( ) ; } if ( Calendar . class . getCanonicalName ( ) . equals ( typeName ) ) { return new CalendarBindTransform ( ) ; } if ( TimeZone . class . getCanonicalName ( ) . equals ( typeName ) ) { return new TimeZoneBindTransform ( ) ; } return null ; |
public class PageSqlKit { /** * 未来考虑处理字符串常量中的字符 :
* 1 : select * from article where title = ' select * from '
* 此例可以正常处理 , 因为在第一个 from 之处就会正确返回
* 2 : select ( select x from t where y = ' select * from . . . ' ) as a from article
* 此例无法正常处理 , 暂时交由 paginateByFullSql ( . . . )
* 3 : 如果一定要处理上例中的问题 , 还要了解不同数据库有关字符串常量的定界符细节 */
private static int getIndexOfFrom ( String sql ) { } } | int parenDepth = 0 ; char c ; for ( int i = start , end = sql . length ( ) - 5 ; i < end ; i ++ ) { c = sql . charAt ( i ) ; if ( c >= SIZE ) { continue ; } c = charTable [ c ] ; if ( c == NULL ) { continue ; } if ( c == '(' ) { parenDepth ++ ; continue ; } if ( c == ')' ) { if ( parenDepth == 0 ) { throw new RuntimeException ( "Can not match left paren '(' for right paren ')': " + sql ) ; } parenDepth -- ; continue ; } if ( parenDepth > 0 ) { continue ; } if ( c == 'f' && charTable [ sql . charAt ( i + 1 ) ] == 'r' && charTable [ sql . charAt ( i + 2 ) ] == 'o' && charTable [ sql . charAt ( i + 3 ) ] == 'm' ) { c = sql . charAt ( i + 4 ) ; // 测试用例 : " select count ( * ) from ( select * from account limit 3 ) as t "
if ( charTable [ c ] == ' ' || c == '(' ) { // 判断 from 后方字符
c = sql . charAt ( i - 1 ) ; if ( charTable [ c ] == ' ' || c == ')' ) { // 判断 from 前方字符
return i ; } } } } return - 1 ; |
public class TransactionSignature { /** * Returns true if the given signature is has canonical encoding , and will thus be accepted as standard by
* Bitcoin Core . DER and the SIGHASH encoding allow for quite some flexibility in how the same structures
* are encoded , and this can open up novel attacks in which a man in the middle takes a transaction and then
* changes its signature such that the transaction hash is different but it ' s still valid . This can confuse wallets
* and generally violates people ' s mental model of how Bitcoin should work , thus , non - canonical signatures are now
* not relayed by default . */
public static boolean isEncodingCanonical ( byte [ ] signature ) { } } | // See Bitcoin Core ' s IsCanonicalSignature , https : / / bitcointalk . org / index . php ? topic = 8392 . msg127623 # msg127623
// A canonical signature exists of : < 30 > < total len > < 02 > < len R > < R > < 02 > < len S > < S > < hashtype >
// Where R and S are not negative ( their first byte has its highest bit not set ) , and not
// excessively padded ( do not start with a 0 byte , unless an otherwise negative number follows ,
// in which case a single 0 byte is necessary and even required ) .
// Empty signatures , while not strictly DER encoded , are allowed .
if ( signature . length == 0 ) return true ; if ( signature . length < 9 || signature . length > 73 ) return false ; int hashType = ( signature [ signature . length - 1 ] & 0xff ) & ~ Transaction . SigHash . ANYONECANPAY . value ; // mask the byte to prevent sign - extension hurting us
if ( hashType < Transaction . SigHash . ALL . value || hashType > Transaction . SigHash . SINGLE . value ) return false ; // " wrong type " " wrong length marker "
if ( ( signature [ 0 ] & 0xff ) != 0x30 || ( signature [ 1 ] & 0xff ) != signature . length - 3 ) return false ; int lenR = signature [ 3 ] & 0xff ; if ( 5 + lenR >= signature . length || lenR == 0 ) return false ; int lenS = signature [ 5 + lenR ] & 0xff ; if ( lenR + lenS + 7 != signature . length || lenS == 0 ) return false ; // R value type mismatch R value negative
if ( signature [ 4 - 2 ] != 0x02 || ( signature [ 4 ] & 0x80 ) == 0x80 ) return false ; if ( lenR > 1 && signature [ 4 ] == 0x00 && ( signature [ 4 + 1 ] & 0x80 ) != 0x80 ) return false ; // R value excessively padded
// S value type mismatch S value negative
if ( signature [ 6 + lenR - 2 ] != 0x02 || ( signature [ 6 + lenR ] & 0x80 ) == 0x80 ) return false ; if ( lenS > 1 && signature [ 6 + lenR ] == 0x00 && ( signature [ 6 + lenR + 1 ] & 0x80 ) != 0x80 ) return false ; // S value excessively padded
return true ; |
public class CEDescrBuilderImpl { /** * { @ inheritDoc } */
public CEDescrBuilder < CEDescrBuilder < P , T > , NotDescr > not ( ) { } } | CEDescrBuilder < CEDescrBuilder < P , T > , NotDescr > not = new CEDescrBuilderImpl < CEDescrBuilder < P , T > , NotDescr > ( this , new NotDescr ( ) ) ; ( ( ConditionalElementDescr ) descr ) . addDescr ( not . getDescr ( ) ) ; return not ; |
public class AbstractGrabber { /** * / * ( non - Javadoc )
* @ see au . edu . jcu . v4l4j . FrameGrabber # startCapture ( ) */
@ Override public final void startCapture ( ) throws V4L4JException { } } | state . start ( ) ; // make sure we have a push source
if ( pushSource == null ) { state . rollback ( ) ; throw new V4L4JException ( "setCaptureCallback() must be called with a valid " + "callback object before startCapture()" ) ; } // start the push source and wait until it ' s blocked on getVideoFrame ( )
pushSource . startCapture ( ) ; state . waitForAtLeastOneUser ( ) ; try { // start video capture and enqueue all buffers
start ( object ) ; } catch ( V4L4JException e ) { // Error starting the capture . . .
// stop the push source thread
pushSource . stopCapture ( ) ; // return to previous state
state . rollback ( ) ; // propagate exception
throw e ; } // change state to STARTED
state . commit ( ) ; // put all frames into the available queue and wake up push source thread
synchronized ( availableVideoFrames ) { availableVideoFrames . addAll ( videoFrames ) ; availableVideoFrames . notifyAll ( ) ; } |
public class ClientStats { /** * < p > Using the latency bucketing statistics gathered by the client , estimate
* the k - percentile latency value for the time period covered by this stats
* instance . < / p >
* < p > For example , k = . 5 returns an estimate of the median . k = 0 returns the
* minimum . k = 1.0 returns the maximum . < / p >
* < p > Latencies longer than the highest trackable value ( 10 seconds ) will be
* reported as multiple entries at the highest trackable value < / p >
* @ param percentile A floating point number between 0.0 and 1.0.
* @ return An estimate of k - percentile latency in whole milliseconds . */
public int kPercentileLatency ( double percentile ) { } } | if ( m_latencyHistogram . getTotalCount ( ) == 0 ) return 0 ; percentile = Math . max ( 0.0D , percentile ) ; // Convert from micros to millis for return value , round to nearest integer
return ( int ) ( Math . round ( m_latencyHistogram . getValueAtPercentile ( percentile * 100.0D ) ) / 1000.0 ) ; |
public class ContextUtil { /** * Converst a ResponseCtx object to its string representation .
* @ param resCtx
* the ResponseCtx object
* @ return the String representation of the ResponseCtx object */
public String makeResponseCtx ( ResponseCtx resCtx ) { } } | ByteArrayOutputStream response = new ByteArrayOutputStream ( ) ; resCtx . encode ( response , new Indenter ( ) ) ; return new String ( response . toByteArray ( ) ) ; |
public class CouchbaseAsyncBucket { /** * Helper method to encapsulate the logic of enriching the exception with detailed status info . */
private static < X extends CouchbaseException , R extends CouchbaseResponse > X addDetails ( X ex , R r ) { } } | return Utils . addDetails ( ex , r ) ; |
public class JSLockedMessageEnumeration { /** * / * ( non - Javadoc )
* @ see com . ibm . wsspi . sib . core . LockedMessageEnumeration # unlockCurrent ( boolean ) */
public void unlockCurrent ( boolean redeliveryCountUnchanged ) throws SISessionUnavailableException , SISessionDroppedException , SIResourceException , SIConnectionLostException , SIIncorrectCallException , SIErrorException , SIMPMessageNotLockedException { } } | if ( TraceComponent . isAnyTracingEnabled ( ) && CoreSPILockedMessageEnumeration . tc . isEntryEnabled ( ) ) SibTr . entry ( CoreSPILockedMessageEnumeration . tc , "unlockCurrent" , new Object [ ] { new Integer ( hashCode ( ) ) , this , new Boolean ( redeliveryCountUnchanged ) } ) ; checkValidState ( "unlockCurrent" ) ; localConsumerPoint . checkNotClosed ( ) ; SIMPMessageNotLockedException notLockedException = null ; synchronized ( this ) { // check that there is a valid current message
checkCurrentMessageAvailable ( null ) ; if ( localConsumerPoint . getConsumerManager ( ) . getDestination ( ) . isOrdered ( ) ) { unlockAll ( ) ; } else { if ( currentMsg != null ) { // Remember that we ' ve just unlocked this message , they may want to re - lock it
// later
currentUnlockedMessage = currentMsg ; // We only actualy need to unlock it if it ' s actually in the MS
if ( currentMsg . isStored ) { SIMPMessage msg = ( SIMPMessage ) ( currentMsg . message ) ; try { if ( msg != null ) { msg . unlockMsg ( msg . getLockID ( ) , null , ! redeliveryCountUnchanged ) ; } } catch ( NotInMessageStore e ) { // No FFDC code needed
SibTr . exception ( tc , e ) ; // See defect 387591
// We should only get this exception if the message was deleted via
// the controllable objects i . e . the admin console . If we are here for
// another reason that we have a real error .
SibTr . error ( tc , "INTERNAL_MESSAGING_ERROR_CWSIP0002" , new Object [ ] { "com.ibm.ws.sib.processor.impl.JSLockedMessageEnumeration" , "1:445:1.8.1.10" , e } ) ; notLockedException = new SIMPMessageNotLockedException ( nls . getFormattedMessage ( "INTERNAL_MESSAGING_ERROR_CWSIP0002" , new Object [ ] { "com.ibm.ws.sib.processor.impl.JSLockedMessageEnumeration" , "1:453:1.8.1.10" , e } , null ) , new SIMessageHandle [ ] { msg . getMessage ( ) . getMessageHandle ( ) } ) ; notLockedException . initCause ( e . getCause ( ) ) ; } catch ( MessageStoreException e ) { // MessageStoreException shouldn ' t occur so FFDC .
FFDCFilter . processException ( e , "com.ibm.ws.sib.processor.impl.JSLockedMessageEnumeration.unlockCurrent" , "1:465:1.8.1.10" , this ) ; SibTr . exception ( tc , e ) ; SibTr . error ( tc , "INTERNAL_MESSAGING_ERROR_CWSIP0002" , new Object [ ] { "com.ibm.ws.sib.processor.impl.JSLockedMessageEnumeration" , "1:472:1.8.1.10" , e } ) ; if ( TraceComponent . isAnyTracingEnabled ( ) && CoreSPILockedMessageEnumeration . tc . isEntryEnabled ( ) ) SibTr . exit ( CoreSPILockedMessageEnumeration . tc , "unlockCurrent" , e ) ; throw new SIResourceException ( nls . getFormattedMessage ( "INTERNAL_MESSAGING_ERROR_CWSIP0002" , new Object [ ] { "com.ibm.ws.sib.processor.impl.JSLockedMessageEnumeration" , "1:483:1.8.1.10" , e } , null ) , e ) ; } } } } // synchronized
// Decrement the number of active messages for this consumer ( outside the LME lock )
localConsumerPoint . removeActiveMessages ( 1 ) ; if ( notLockedException != null ) { if ( TraceComponent . isAnyTracingEnabled ( ) && CoreSPILockedMessageEnumeration . tc . isEntryEnabled ( ) ) SibTr . exit ( CoreSPILockedMessageEnumeration . tc , "unlockCurrent" , this ) ; throw notLockedException ; } } if ( TraceComponent . isAnyTracingEnabled ( ) && CoreSPILockedMessageEnumeration . tc . isEntryEnabled ( ) ) SibTr . exit ( CoreSPILockedMessageEnumeration . tc , "unlockCurrent" , this ) ; |
public class HMac { /** * 初始化
* @ param algorithm 算法
* @ param key 密钥 { @ link SecretKey }
* @ return { @ link HMac }
* @ throws CryptoException Cause by IOException */
public HMac init ( String algorithm , SecretKey key ) { } } | try { mac = Mac . getInstance ( algorithm ) ; if ( null != key ) { this . secretKey = key ; } else { this . secretKey = SecureUtil . generateKey ( algorithm ) ; } mac . init ( this . secretKey ) ; } catch ( Exception e ) { throw new CryptoException ( e ) ; } return this ; |
public class MediaSpec { /** * Checks whether a value coresponds to the given criteria .
* @ param required the required value
* @ param current the tested value or { @ code null } for invalid value
* @ param min { @ code true } when the required value is the minimal one
* @ param max { @ code true } when the required value is the maximal one
* @ return { @ code true } when the value matches the criteria . */
protected boolean valueMatches ( Integer required , int current , boolean min , boolean max ) { } } | if ( required != null ) { if ( min ) return ( current >= required ) ; else if ( max ) return ( current <= required ) ; else return current == required ; } else return false ; // invalid values don ' t match |
public class PersistentPageFile { /** * Set the next page id to the given value . If this means that any page ids
* stored in < code > emptyPages < / code > are smaller than
* < code > next _ page _ id < / code > , they are removed from this file ' s observation
* stack .
* @ param next _ page _ id the id of the next page to be inserted ( if there are no
* more empty pages to be filled ) */
@ Override public void setNextPageID ( int next_page_id ) { } } | this . nextPageID = next_page_id ; while ( ! emptyPages . isEmpty ( ) && emptyPages . peek ( ) >= this . nextPageID ) { emptyPages . pop ( ) ; } |
public class ColumnText { /** * Makes this instance an independent copy of < CODE > org < / CODE > .
* @ param org the original < CODE > ColumnText < / CODE >
* @ return itself */
public ColumnText setACopy ( ColumnText org ) { } } | setSimpleVars ( org ) ; if ( org . bidiLine != null ) bidiLine = new BidiLine ( org . bidiLine ) ; return this ; |
public class ValidatorProcess { /** * Open the connection to the Fedora server . */
private static RemoteObjectSource openObjectSource ( ServiceInfo serviceInfo ) { } } | try { return new RemoteObjectSource ( serviceInfo ) ; } catch ( ServiceException e ) { throw new IllegalStateException ( "Failed to initialize " + "the ValidatorProcess: " , e ) ; } catch ( IOException e ) { throw new IllegalStateException ( "Failed to initialize " + "the ValidatorProcess: " , e ) ; } |
public class NotificationCenter { /** * / * package */
void updateEntryState ( NotificationEntry entry ) { } } | synchronized ( entry . mLock ) { final int id = entry . ID ; if ( entry . priority == null ) { entry . priority = NotificationEntry . DEFAULT_PRIORITY ; } if ( entry . mFlag != entry . mPrevFlag ) { final int diff = entry . mPrevFlag ^ entry . mFlag & entry . mFlag ; if ( DBG ) { Log . d ( TAG , "updateEntryState: entryId=" + entry . ID + ", flag=" + entry . mFlag + ", prev=" + entry . mPrevFlag + ", diff=" + diff ) ; } if ( ( diff & NotificationEntry . FLAG_REQUEST_SEND ) != 0 ) { mPendings . addEntry ( entry . ID , entry ) ; if ( entry . mTargets == 0 ) { onSendAsDefault ( entry ) ; } else { onSendRequested ( entry ) ; } } if ( ( diff & NotificationEntry . FLAG_REQUEST_UPDATE ) != 0 ) { entry . mFlag &= ~ NotificationEntry . FLAG_REQUEST_UPDATE ; if ( entry . mTargets == 0 ) { onUpdateAsDefault ( entry ) ; } else { onUpdateRequested ( entry ) ; } } else if ( ( diff & NotificationEntry . FLAG_REQUEST_CANCEL ) != 0 ) { if ( entry . mTargets == entry . mCancels ) { removeEntry ( entry . ID ) ; } else { onCancelRequested ( entry ) ; } } else if ( ( diff & NotificationEntry . FLAG_SEND_FINISHED ) != 0 ) { entry . mFlag &= ~ NotificationEntry . FLAG_SEND_FINISHED ; addEntry ( entry . ID , entry ) ; } else if ( ( diff & NotificationEntry . FLAG_SEND_IGNORED ) != 0 ) { entry . mFlag &= ~ NotificationEntry . FLAG_SEND_IGNORED ; if ( entry . mTargets == entry . mIgnores ) { onSendAsDefault ( entry ) ; } } else if ( ( diff & NotificationEntry . FLAG_UPDATE_FINISHED ) != 0 ) { entry . mFlag &= ~ NotificationEntry . FLAG_UPDATE_FINISHED ; if ( entry . mTargets == entry . mUpdates ) { updateEntry ( entry ) ; } } else if ( ( diff & NotificationEntry . FLAG_CANCEL_FINISHED ) != 0 ) { entry . mFlag &= ~ NotificationEntry . FLAG_CANCEL_FINISHED ; if ( entry . mTargets == entry . mCancels ) { removeEntry ( entry . ID ) ; } } entry . mPrevFlag = entry . mFlag ; } } |
public class OctTreeNode { /** * Move this node in the given new node .
* < p > This function is preferred to a sequence of calls
* to { @ link # removeFromParent ( ) } and { @ link # setChildAt ( int , OctTreeNode ) }
* because it fires a limited set of events dedicated to the move
* the node .
* @ param newParent is the new parent for this node .
* @ param zone is the position of this node in the new parent .
* @ return < code > true < / code > on success , otherwise < code > false < / code > . */
public boolean moveTo ( N newParent , OctTreeZone zone ) { } } | if ( zone != null ) { return moveTo ( newParent , zone . ordinal ( ) ) ; } return false ; |
public class ScribeIndex { /** * Gets a property scribe by XML local name and namespace .
* @ param qname the XML local name and namespace
* @ return the property scribe or a { @ link XmlScribe } if not found */
public ICalPropertyScribe < ? extends ICalProperty > getPropertyScribe ( QName qname ) { } } | ICalPropertyScribe < ? extends ICalProperty > scribe = experimentalPropByQName . get ( qname ) ; if ( scribe == null ) { scribe = standardPropByQName . get ( qname ) ; } if ( scribe == null || ! scribe . getSupportedVersions ( ) . contains ( ICalVersion . V2_0 ) ) { if ( XCalNamespaceContext . XCAL_NS . equals ( qname . getNamespaceURI ( ) ) ) { return new RawPropertyScribe ( qname . getLocalPart ( ) . toUpperCase ( ) ) ; } return getPropertyScribe ( Xml . class ) ; } return scribe ; |
public class TrajectorySplineFit { /** * Calculates a spline to a trajectory . Attention : The spline is fitted through a rotated version of the trajectory .
* To fit the spline the trajectory is rotated into its main direction . You can access this rotated trajectory by
* { @ link # getRotatedTrajectory ( ) getRotatedTrajectory } .
* @ return The fitted spline */
public PolynomialSplineFunction calculateSpline ( ) { } } | successfull = false ; /* * 1 . Calculate the minimum bounding rectangle */
ArrayList < Point2D . Double > points = new ArrayList < Point2D . Double > ( ) ; for ( int i = 0 ; i < t . size ( ) ; i ++ ) { Point2D . Double p = new Point2D . Double ( ) ; p . setLocation ( t . get ( i ) . x , t . get ( i ) . y ) ; points . add ( p ) ; } /* * 1.1 Rotate that the major axis is parallel with the xaxis */
Array2DRowRealMatrix gyr = RadiusGyrationTensor2D . getRadiusOfGyrationTensor ( t ) ; EigenDecomposition eigdec = new EigenDecomposition ( gyr ) ; double inRad = - 1 * Math . atan2 ( eigdec . getEigenvector ( 0 ) . getEntry ( 1 ) , eigdec . getEigenvector ( 0 ) . getEntry ( 0 ) ) ; boolean doTransform = ( Math . abs ( Math . abs ( inRad ) - Math . PI ) > 0.001 ) ; if ( doTransform ) { angleRotated = inRad ; for ( int i = 0 ; i < t . size ( ) ; i ++ ) { double x = t . get ( i ) . x ; double y = t . get ( i ) . y ; double newX = x * Math . cos ( inRad ) - y * Math . sin ( inRad ) ; double newY = x * Math . sin ( inRad ) + y * Math . cos ( inRad ) ; rotatedTrajectory . add ( newX , newY , 0 ) ; points . get ( i ) . setLocation ( newX , newY ) ; } // for ( int i = 0 ; i < rect . length ; i + + ) {
// rect [ i ] . setLocation ( rect [ i ] . x * Math . cos ( inRad ) - rect [ i ] . y * Math . sin ( inRad ) , rect [ i ] . x * Math . sin ( inRad ) + rect [ i ] . y * Math . cos ( inRad ) ) ;
} else { angleRotated = 0 ; rotatedTrajectory = t ; } /* * 2 . Divide the rectangle in n equal segments
* 2.1 Calculate line in main direction
* 2.2 Project the points in onto this line
* 2.3 Calculate the distance between the start of the line and the projected point
* 2.4 Assign point to segment according to distance of ( 2.3) */
List < List < Point2D . Double > > pointsInSegments = null ; boolean allSegmentsContainingAtLeastTwoPoints = true ; int indexSmallestX = 0 ; double segmentWidth = 0 ; do { double smallestX = Double . MAX_VALUE ; double largestX = Double . MIN_VALUE ; for ( int i = 0 ; i < points . size ( ) ; i ++ ) { if ( points . get ( i ) . x < smallestX ) { smallestX = points . get ( i ) . x ; indexSmallestX = i ; } if ( points . get ( i ) . x > largestX ) { largestX = points . get ( i ) . x ; } } allSegmentsContainingAtLeastTwoPoints = true ; segmentWidth = ( largestX - smallestX ) / nSegments ; pointsInSegments = new ArrayList < List < Point2D . Double > > ( nSegments ) ; for ( int i = 0 ; i < nSegments ; i ++ ) { pointsInSegments . add ( new ArrayList < Point2D . Double > ( ) ) ; } for ( int i = 0 ; i < points . size ( ) ; i ++ ) { int index = ( int ) Math . abs ( ( points . get ( i ) . x / segmentWidth ) ) ; if ( index > ( nSegments - 1 ) ) { index = ( nSegments - 1 ) ; } pointsInSegments . get ( index ) . add ( points . get ( i ) ) ; } for ( int i = 0 ; i < pointsInSegments . size ( ) ; i ++ ) { if ( pointsInSegments . get ( i ) . size ( ) < 2 ) { if ( nSegments > 2 ) { nSegments -- ; i = pointsInSegments . size ( ) ; allSegmentsContainingAtLeastTwoPoints = false ; } } } } while ( allSegmentsContainingAtLeastTwoPoints == false ) ; /* * 3 . Calculate the mean standard deviation over each segment : < s > */
// Point2D . Double eMajorP1 = new Point2D . Double ( p1 . x - ( p3 . x - p1 . x ) / 2.0 , p1 . y - ( p3 . y - p1 . y ) / 2.0 ) ;
// Point2D . Double eMajorP2 = new Point2D . Double ( p2 . x - ( p3 . x - p1 . x ) / 2.0 , p2 . y - ( p3 . y - p1 . y ) / 2.0 ) ;
double sumSDOrthogonal = 0 ; int Nsum = 0 ; CenterOfGravityFeature cogf = new CenterOfGravityFeature ( rotatedTrajectory ) ; Point2D . Double cog = new Point2D . Double ( cogf . evaluate ( ) [ 0 ] , cogf . evaluate ( ) [ 1 ] ) ; Point2D . Double eMajorP1 = cog ; Point2D . Double eMajorP2 = new Point2D . Double ( cog . getX ( ) + 1 , cog . getY ( ) ) ; for ( int i = 0 ; i < nSegments ; i ++ ) { StandardDeviation sd = new StandardDeviation ( ) ; double [ ] distances = new double [ pointsInSegments . get ( i ) . size ( ) ] ; for ( int j = 0 ; j < pointsInSegments . get ( i ) . size ( ) ; j ++ ) { int factor = 1 ; if ( isLeft ( eMajorP1 , eMajorP2 , pointsInSegments . get ( i ) . get ( j ) ) ) { factor = - 1 ; } distances [ j ] = factor * distancePointLine ( eMajorP1 , eMajorP2 , pointsInSegments . get ( i ) . get ( j ) ) ; } if ( distances . length > 0 ) { sd . setData ( distances ) ; sumSDOrthogonal += sd . evaluate ( ) ; Nsum ++ ; } } double s = sumSDOrthogonal / Nsum ; if ( segmentWidth < Math . pow ( 10 , - 15 ) ) { return null ; } if ( s < Math . pow ( 10 , - 15 ) ) { // If standard deviation is zero , replace it with the half of the segment width
s = segmentWidth / 2 ; } // rotatedTrajectory . showTrajectory ( " rot " ) ;
/* * 4 . Build a kd - tree */
KDTree < Point2D . Double > kdtree = new KDTree < Point2D . Double > ( 2 ) ; for ( int i = 0 ; i < points . size ( ) ; i ++ ) { try { // To ensure that all points have a different key , add small random number
kdtree . insert ( new double [ ] { points . get ( i ) . x , points . get ( i ) . y } , points . get ( i ) ) ; } catch ( KeySizeException e ) { e . printStackTrace ( ) ; } catch ( KeyDuplicateException e ) { // Do nothing ! It is not important
} } /* * 5 . Using the first point f in trajectory and calculate the center of mass
* of all points around f ( radius : 3 * < s > ) ) */
List < Point2D . Double > near = null ; Point2D . Double first = points . get ( indexSmallestX ) ; // minDistancePointToLine ( p1 , p3 , points ) ;
double r1 = 3 * s ; try { near = kdtree . nearestEuclidean ( new double [ ] { first . x , first . y } , r1 ) ; } catch ( KeySizeException e ) { e . printStackTrace ( ) ; } double cx = 0 ; double cy = 0 ; for ( int i = 0 ; i < near . size ( ) ; i ++ ) { cx += near . get ( i ) . x ; cy += near . get ( i ) . y ; } cx /= near . size ( ) ; cy /= near . size ( ) ; splineSupportPoints = new ArrayList < Point2D . Double > ( ) ; splineSupportPoints . add ( new Point2D . Double ( cx , cy ) ) ; /* * 6 . The second point is determined by finding the center - of - mass of particles in the p / 2 radian
* section of an annulus , r1 < r < 2r1 , that is directed toward the angle with the highest number
* of particles within p / 2 radians .
* 7 . This second point is then used as the center of the annulus for choosing the third point , and the process is repeated ( 6 . & 7 . ) . */
/* * 6.1 Find all points in the annolous */
/* * 6.2 Write each point in a coordinate system centered at the center of the sphere , calculate direction and
* check if it in the allowed bounds */
int nCircleSegments = 100 ; double deltaRad = 2 * Math . PI / nCircleSegments ; boolean stop = false ; int minN = 7 ; double tempr1 = r1 ; double allowedDeltaDirection = 0.5 * Math . PI ; while ( stop == false ) { List < Point2D . Double > nearestr1 = null ; List < Point2D . Double > nearest2xr1 = null ; try { nearestr1 = kdtree . nearestEuclidean ( new double [ ] { splineSupportPoints . get ( splineSupportPoints . size ( ) - 1 ) . x , splineSupportPoints . get ( splineSupportPoints . size ( ) - 1 ) . y } , tempr1 ) ; nearest2xr1 = kdtree . nearestEuclidean ( new double [ ] { splineSupportPoints . get ( splineSupportPoints . size ( ) - 1 ) . x , splineSupportPoints . get ( splineSupportPoints . size ( ) - 1 ) . y } , 2 * tempr1 ) ; } catch ( KeySizeException e ) { // TODO Auto - generated catch block
e . printStackTrace ( ) ; } nearest2xr1 . removeAll ( nearestr1 ) ; double lThreshRad = 0 ; double hThreshRad = Math . PI / 2 ; double stopThresh = 2 * Math . PI ; if ( splineSupportPoints . size ( ) > 1 ) { double directionInRad = Math . atan2 ( splineSupportPoints . get ( splineSupportPoints . size ( ) - 1 ) . y - splineSupportPoints . get ( splineSupportPoints . size ( ) - 2 ) . y , splineSupportPoints . get ( splineSupportPoints . size ( ) - 1 ) . x - splineSupportPoints . get ( splineSupportPoints . size ( ) - 2 ) . x ) + Math . PI ; lThreshRad = directionInRad - allowedDeltaDirection / 2 - Math . PI / 4 ; if ( lThreshRad < 0 ) { lThreshRad = 2 * Math . PI + lThreshRad ; } if ( lThreshRad > 2 * Math . PI ) { lThreshRad = lThreshRad - 2 * Math . PI ; } hThreshRad = directionInRad + allowedDeltaDirection / 2 + Math . PI / 4 ; if ( hThreshRad < 0 ) { hThreshRad = 2 * Math . PI + hThreshRad ; } if ( hThreshRad > 2 * Math . PI ) { hThreshRad = hThreshRad - 2 * Math . PI ; } stopThresh = directionInRad + allowedDeltaDirection / 2 - Math . PI / 4 ; if ( stopThresh > 2 * Math . PI ) { stopThresh = stopThresh - 2 * Math . PI ; } } double newCx = 0 ; double newCy = 0 ; int newCN = 0 ; int candN = 0 ; // Find center with highest density of points
double lastDist = 0 ; double newDist = 0 ; do { lastDist = Math . min ( Math . abs ( lThreshRad - stopThresh ) , 2 * Math . PI - Math . abs ( lThreshRad - stopThresh ) ) ; candN = 0 ; double candCx = 0 ; double candCy = 0 ; for ( int i = 0 ; i < nearest2xr1 . size ( ) ; i ++ ) { Point2D . Double centerOfCircle = splineSupportPoints . get ( splineSupportPoints . size ( ) - 1 ) ; Vector2d relativeToCircle = new Vector2d ( nearest2xr1 . get ( i ) . x - centerOfCircle . x , nearest2xr1 . get ( i ) . y - centerOfCircle . y ) ; relativeToCircle . normalize ( ) ; double angleInRadians = Math . atan2 ( relativeToCircle . y , relativeToCircle . x ) + Math . PI ; if ( lThreshRad < hThreshRad ) { if ( angleInRadians > lThreshRad && angleInRadians < hThreshRad ) { candCx += nearest2xr1 . get ( i ) . x ; candCy += nearest2xr1 . get ( i ) . y ; candN ++ ; } } else { if ( angleInRadians > lThreshRad || angleInRadians < hThreshRad ) { candCx += nearest2xr1 . get ( i ) . x ; candCy += nearest2xr1 . get ( i ) . y ; candN ++ ; } } } if ( candN > 0 && candN > newCN ) { candCx /= candN ; candCy /= candN ; newCx = candCx ; newCy = candCy ; newCN = candN ; } lThreshRad += deltaRad ; hThreshRad += deltaRad ; if ( lThreshRad > 2 * Math . PI ) { lThreshRad = lThreshRad - 2 * Math . PI ; } if ( hThreshRad > 2 * Math . PI ) { hThreshRad = hThreshRad - 2 * Math . PI ; } newDist = Math . min ( Math . abs ( lThreshRad - stopThresh ) , 2 * Math . PI - Math . abs ( lThreshRad - stopThresh ) ) ; } while ( ( newDist - lastDist ) > 0 ) ; // Check if the new center is valid
if ( splineSupportPoints . size ( ) > 1 ) { double currentDirectionInRad = Math . atan2 ( splineSupportPoints . get ( splineSupportPoints . size ( ) - 1 ) . y - splineSupportPoints . get ( splineSupportPoints . size ( ) - 2 ) . y , splineSupportPoints . get ( splineSupportPoints . size ( ) - 1 ) . x - splineSupportPoints . get ( splineSupportPoints . size ( ) - 2 ) . x ) + Math . PI ; double candDirectionInRad = Math . atan2 ( newCy - splineSupportPoints . get ( splineSupportPoints . size ( ) - 1 ) . y , newCx - splineSupportPoints . get ( splineSupportPoints . size ( ) - 1 ) . x ) + Math . PI ; double dDir = Math . max ( currentDirectionInRad , candDirectionInRad ) - Math . min ( currentDirectionInRad , candDirectionInRad ) ; if ( dDir > 2 * Math . PI ) { dDir = 2 * Math . PI - dDir ; } if ( dDir > allowedDeltaDirection ) { stop = true ; } } boolean enoughPoints = ( newCN < minN ) ; boolean isNormalRadius = Math . abs ( tempr1 - r1 ) < Math . pow ( 10 , - 18 ) ; boolean isExtendedRadius = Math . abs ( tempr1 - 3 * r1 ) < Math . pow ( 10 , - 18 ) ; if ( enoughPoints && isNormalRadius ) { // Not enough points , extend search radius
tempr1 = 3 * r1 ; } else if ( enoughPoints && isExtendedRadius ) { // Despite radius extension : Not enough points !
stop = true ; } else if ( stop == false ) { splineSupportPoints . add ( new Point2D . Double ( newCx , newCy ) ) ; tempr1 = r1 ; } } // Sort
Collections . sort ( splineSupportPoints , new Comparator < Point2D . Double > ( ) { public int compare ( Point2D . Double o1 , Point2D . Double o2 ) { if ( o1 . x < o2 . x ) { return - 1 ; } if ( o1 . x > o2 . x ) { return 1 ; } return 0 ; } } ) ; // Add endpoints
if ( splineSupportPoints . size ( ) > 1 ) { Vector2d start = new Vector2d ( splineSupportPoints . get ( 0 ) . x - splineSupportPoints . get ( 1 ) . x , splineSupportPoints . get ( 0 ) . y - splineSupportPoints . get ( 1 ) . y ) ; start . normalize ( ) ; start . scale ( r1 * 8 ) ; splineSupportPoints . add ( 0 , new Point2D . Double ( splineSupportPoints . get ( 0 ) . x + start . x , splineSupportPoints . get ( 0 ) . y + start . y ) ) ; Vector2d end = new Vector2d ( splineSupportPoints . get ( splineSupportPoints . size ( ) - 1 ) . x - splineSupportPoints . get ( splineSupportPoints . size ( ) - 2 ) . x , splineSupportPoints . get ( splineSupportPoints . size ( ) - 1 ) . y - splineSupportPoints . get ( splineSupportPoints . size ( ) - 2 ) . y ) ; end . normalize ( ) ; end . scale ( r1 * 6 ) ; splineSupportPoints . add ( new Point2D . Double ( splineSupportPoints . get ( splineSupportPoints . size ( ) - 1 ) . x + end . x , splineSupportPoints . get ( splineSupportPoints . size ( ) - 1 ) . y + end . y ) ) ; } else { Vector2d majordir = new Vector2d ( - 1 , 0 ) ; majordir . normalize ( ) ; majordir . scale ( r1 * 8 ) ; splineSupportPoints . add ( 0 , new Point2D . Double ( splineSupportPoints . get ( 0 ) . x + majordir . x , splineSupportPoints . get ( 0 ) . y + majordir . y ) ) ; majordir . scale ( - 1 ) ; splineSupportPoints . add ( new Point2D . Double ( splineSupportPoints . get ( splineSupportPoints . size ( ) - 1 ) . x + majordir . x , splineSupportPoints . get ( splineSupportPoints . size ( ) - 1 ) . y + majordir . y ) ) ; } // Interpolate spline
double [ ] supX = new double [ splineSupportPoints . size ( ) ] ; double [ ] supY = new double [ splineSupportPoints . size ( ) ] ; for ( int i = 0 ; i < splineSupportPoints . size ( ) ; i ++ ) { supX [ i ] = splineSupportPoints . get ( i ) . x ; supY [ i ] = splineSupportPoints . get ( i ) . y ; } SplineInterpolator sIinter = new SplineInterpolator ( ) ; spline = sIinter . interpolate ( supX , supY ) ; successfull = true ; return spline ; |
public class ProcessingContext { /** * Find the annotation searching the inheritance hierarchy . */
< A extends Annotation > A findAnnotation ( TypeElement element , Class < A > anno ) { } } | final A annotation = element . getAnnotation ( anno ) ; if ( annotation != null ) { return annotation ; } final TypeMirror typeMirror = element . getSuperclass ( ) ; if ( typeMirror . getKind ( ) == TypeKind . NONE ) { return null ; } final TypeElement element1 = ( TypeElement ) typeUtils . asElement ( typeMirror ) ; return findAnnotation ( element1 , anno ) ; |
public class CmsForm { /** * Removes all fields for the given group . < p >
* @ param group the group for which the fields should be removed */
public void removeGroup ( String group ) { } } | if ( m_fieldsByGroup . get ( group ) != null ) { List < I_CmsFormField > fieldsToRemove = new ArrayList < I_CmsFormField > ( m_fieldsByGroup . get ( group ) ) ; for ( I_CmsFormField field : fieldsToRemove ) { removeField ( field ) ; } } m_fieldsByGroup . removeAll ( group ) ; |
public class JsonAppendableWriter { /** * Closes this JSON writer and flushes the underlying { @ link Appendable } if it is also { @ link Flushable } .
* @ throws JsonWriterException
* if the underlying { @ link Flushable } { @ link Appendable } failed to flush . */
public void done ( ) throws JsonWriterException { } } | super . doneInternal ( ) ; if ( appendable instanceof Flushable ) { try { ( ( Flushable ) appendable ) . flush ( ) ; } catch ( IOException e ) { throw new JsonWriterException ( e ) ; } } |
public class SimpleSpringMemcached { /** * < b > IMPORTANT : < / b > This operation is not atomic as the underlying implementation
* ( memcached ) does not provide a way to do it . */
@ Override public ValueWrapper putIfAbsent ( Object key , Object value ) { } } | Assert . notNull ( key , "key parameter is mandatory" ) ; Assert . isAssignable ( String . class , key . getClass ( ) ) ; ValueWrapper valueWrapper = get ( key ) ; if ( valueWrapper == null ) { try { this . memcachedClientIF . add ( ( String ) key , this . expiration , value ) . get ( ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; } catch ( ExecutionException e ) { throw new IllegalArgumentException ( "Error writing key" + key , e ) ; } return null ; } else { return valueWrapper ; } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.