signature stringlengths 43 39.1k | implementation stringlengths 0 450k |
|---|---|
public class ValidationFilter { /** * Validate and fix { @ code href } or { @ code conref } attribute for URI validity .
* @ return modified attributes , { @ code null } if there have been no changes */
private AttributesImpl validateReference ( final String attrName , final Attributes atts , final AttributesImpl modified ) { } } | AttributesImpl res = modified ; final String href = atts . getValue ( attrName ) ; if ( href != null ) { try { new URI ( href ) ; } catch ( final URISyntaxException e ) { switch ( processingMode ) { case STRICT : throw new RuntimeException ( MessageUtils . getMessage ( "DOTJ054E" , attrName , href ) . setLocation ( locator ) + ": " + e . getMessage ( ) , e ) ; case SKIP : logger . error ( MessageUtils . getMessage ( "DOTJ054E" , attrName , href ) . setLocation ( locator ) + ", using invalid value." ) ; break ; case LAX : try { final URI uri = new URI ( URLUtils . clean ( href . trim ( ) ) ) ; if ( res == null ) { res = new AttributesImpl ( atts ) ; } res . setValue ( res . getIndex ( attrName ) , uri . toASCIIString ( ) ) ; logger . error ( MessageUtils . getMessage ( "DOTJ054E" , attrName , href ) . setLocation ( locator ) + ", using '" + uri . toASCIIString ( ) + "'." ) ; } catch ( final URISyntaxException e1 ) { logger . error ( MessageUtils . getMessage ( "DOTJ054E" , attrName , href ) . setLocation ( locator ) + ", using invalid value." ) ; } break ; } } } return res ; |
public class FeatureList { /** * Create a list of all features that have the specified group id , as defined by
* the group ( ) method of the features .
* @ param groupid The group to match .
* @ return A list of features having the specified group id . */
public FeatureList selectByGroup ( String groupid ) { } } | FeatureList list = new FeatureList ( ) ; for ( FeatureI f : this ) { if ( f . group ( ) . equals ( groupid ) ) { list . add ( f ) ; } } return list ; |
public class APIDescriptor { /** * Add a required HTTP header . If this HTTP header is not present , invocation
* will not be possible .
* @ param sHeaderName
* The name of the required HTTP header . May be < code > null < / code > or
* empty in which case the header is ignored .
* @ return this for chaining
* @ see # addRequiredHeaders ( String . . . ) */
@ Nonnull public final APIDescriptor addRequiredHeader ( @ Nullable final String sHeaderName ) { } } | if ( StringHelper . hasText ( sHeaderName ) ) m_aRequiredHeaders . add ( sHeaderName ) ; return this ; |
public class PoiAPI { /** * 获取门店类目表
* @ param accessToken accessToken
* @ return result */
public static CategoryListResult getWxCategory ( String accessToken ) { } } | HttpUriRequest httpUriRequest = RequestBuilder . post ( ) . setUri ( BASE_URI + "/cgi-bin/poi/getwxcategory" ) . addParameter ( PARAM_ACCESS_TOKEN , API . accessToken ( accessToken ) ) . build ( ) ; return LocalHttpClient . executeJsonResult ( httpUriRequest , CategoryListResult . class ) ; |
public class Op { /** * Returns the minimum between the two parameters
* @ param a
* @ param b
* @ return ` \ min ( a , b ) ` */
public static double min ( double a , double b ) { } } | if ( Double . isNaN ( a ) ) { return b ; } if ( Double . isNaN ( b ) ) { return a ; } return a < b ? a : b ; |
public class CassandraCpoAdapter { /** * Removes the Objects contained in the collection from the datasource . The assumption is that the object exists in
* the datasource . This method stores the objects contained in the collection in the datasource . The objects in the
* collection will be treated as one transaction , assuming the datasource supports transactions .
* This means that if one of the objects fail being deleted in the datasource then the CpoAdapter should stop
* processing the remainder of the collection , and if supported , rollback all the objects deleted thus far .
* < pre > Example :
* < code >
* class SomeObject so = null ;
* class CpoAdapter cpo = null ;
* try {
* cpo = new CpoAdapter ( new JdbcDataSourceInfo ( driver , url , user , password , 1,1 , false ) ) ;
* } catch ( CpoException ce ) {
* / / Handle the error
* cpo = null ;
* if ( cpo ! = null ) {
* ArrayList al = new ArrayList ( ) ;
* for ( int i = 0 ; i < 3 ; i + + ) {
* so = new SomeObject ( ) ;
* so . setId ( 1 ) ;
* so . setName ( " SomeName " ) ;
* al . add ( so ) ;
* try {
* cpo . deleteObjects ( al ) ;
* } catch ( CpoException ce ) {
* / / Handle the error
* < / code >
* < / pre >
* @ param coll This is a collection of objects that have been defined within the metadata of the datasource . If the
* class is not defined an exception will be thrown .
* @ return The number of objects deleted from the datasource
* @ throws CpoException Thrown if there are errors accessing the datasource */
@ Override public < T > long deleteObjects ( Collection < T > coll ) throws CpoException { } } | return processUpdateGroup ( coll , CpoAdapter . DELETE_GROUP , null , null , null , null ) ; |
public class GCMRegistrar { /** * Sets whether the device was successfully registered in the server side . */
public static void setRegisteredOnServer ( Context context , boolean flag ) { } } | final SharedPreferences prefs = getGCMPreferences ( context ) ; Editor editor = prefs . edit ( ) ; editor . putBoolean ( PROPERTY_ON_SERVER , flag ) ; // set the flag ' s expiration date
long lifespan = getRegisterOnServerLifespan ( context ) ; long expirationTime = System . currentTimeMillis ( ) + lifespan ; Log . v ( TAG , "Setting registeredOnServer status as " + flag + " until " + new Timestamp ( expirationTime ) ) ; editor . putLong ( PROPERTY_ON_SERVER_EXPIRATION_TIME , expirationTime ) ; editor . commit ( ) ; |
public class InsertHandler { /** * ( non - Javadoc )
* @ see javax . faces . view . facelets . FaceletHandler # apply ( javax . faces . view . facelets . FaceletContext , javax . faces . component . UIComponent ) */
public void apply ( FaceletContext ctx , UIComponent parent ) throws IOException , FacesException , FaceletException , ELException { } } | AbstractFaceletContext actx = ( AbstractFaceletContext ) ctx ; actx . extendClient ( this ) ; boolean found = false ; try { found = actx . includeDefinition ( parent , this . name ) ; } finally { actx . popExtendedClient ( this ) ; } if ( ! found ) { this . nextHandler . apply ( ctx , parent ) ; } |
public class UtilES { /** * Returns the object inside Writable
* @ param object
* @ return
* @ throws IllegalAccessException
* @ throws InstantiationException
* @ throws InvocationTargetException
* @ throws NoSuchMethodException */
private static Writable getWritableFromObject ( Object object ) { } } | Writable writable = null ; if ( object instanceof String ) { writable = new Text ( object . toString ( ) ) ; } else if ( object instanceof Long ) { writable = new LongWritable ( ( Long ) object ) ; } else { writable = new IntWritable ( ( Integer ) object ) ; } // writable = writable ! = null ? writable : new Text ( " " ) ;
return writable ; |
public class FileServletWrapper { /** * PM92967 , pulled up method */
protected int getContentLength ( boolean update ) { } } | if ( update ) { contentLength = ( int ) this . getFileSize ( update ) ; return contentLength ; } else { if ( contentLength == - 1 ) { contentLength = ( int ) this . getFileSize ( update ) ; return contentLength ; } else { return contentLength ; } } |
public class AbstractModule { /** * Registers a Filter type with the module . The name of the component is
* derived from the class name , e . g .
* < pre >
* / / Derived name is " myFilter " . Java package is omitted .
* filter ( com . example . MyFilter . class ) ;
* < / pre >
* @ param klass Filter type */
public < F extends Filter > AbstractModule filter ( Class < F > klass ) { } } | String className = Strings . simpleName ( klass ) ; String name = Strings . decapitalize ( className ) ; JSFunction < NGFilter > filterFactory = JSFunction . create ( new DefaultFilterFactory < F > ( name , klass ) ) ; FilterDependencyInspector inspector = GWT . create ( FilterDependencyInspector . class ) ; JSArray < String > dependencies = JSArray . create ( inspector . inspect ( klass ) ) ; ngo . filter ( name , dependencies , filterFactory ) ; return this ; |
public class ReflectionUtils { /** * Create an object for the given class and initialize it from conf
* @ param theClass class of which an object is created
* @ param conf Configuration
* @ return a new object */
@ SuppressWarnings ( "unchecked" ) public static < T > T newInstance ( Class < T > theClass , Configuration conf ) { } } | return newInstance ( theClass , conf , true ) ; |
public class Matrix4d { /** * Create a view and projection matrix from a given < code > eye < / code > position , a given bottom left corner position < code > p < / code > of the near plane rectangle
* and the extents of the near plane rectangle along its local < code > x < / code > and < code > y < / code > axes , and store the resulting matrices
* in < code > projDest < / code > and < code > viewDest < / code > .
* This method creates a view and perspective projection matrix assuming that there is a pinhole camera at position < code > eye < / code >
* projecting the scene onto the near plane defined by the rectangle .
* All positions and lengths are in the same ( world ) unit .
* @ param eye
* the position of the camera
* @ param p
* the bottom left corner of the near plane rectangle ( will map to the bottom left corner in window coordinates )
* @ param x
* the direction and length of the local " bottom / top " X axis / side of the near plane rectangle
* @ param y
* the direction and length of the local " left / right " Y axis / side of the near plane rectangle
* @ param nearFarDist
* the distance between the far and near plane ( the near plane will be calculated by this method ) .
* If the special value { @ link Double # POSITIVE _ INFINITY } is used , the far clipping plane will be at positive infinity .
* If the special value { @ link Double # NEGATIVE _ INFINITY } is used , the near and far planes will be swapped and
* the near clipping plane will be at positive infinity .
* If a negative value is used ( except for { @ link Double # NEGATIVE _ INFINITY } ) the near and far planes will be swapped
* @ param zeroToOne
* whether to use Vulkan ' s and Direct3D ' s NDC z range of < code > [ 0 . . + 1 ] < / code > when < code > true < / code >
* or whether to use OpenGL ' s NDC z range of < code > [ - 1 . . + 1 ] < / code > when < code > false < / code >
* @ param projDest
* will hold the resulting projection matrix
* @ param viewDest
* will hold the resulting view matrix */
public static void projViewFromRectangle ( Vector3d eye , Vector3d p , Vector3d x , Vector3d y , double nearFarDist , boolean zeroToOne , Matrix4d projDest , Matrix4d viewDest ) { } } | double zx = y . y * x . z - y . z * x . y , zy = y . z * x . x - y . x * x . z , zz = y . x * x . y - y . y * x . x ; double zd = zx * ( p . x - eye . x ) + zy * ( p . y - eye . y ) + zz * ( p . z - eye . z ) ; double zs = zd >= 0 ? 1 : - 1 ; zx *= zs ; zy *= zs ; zz *= zs ; zd *= zs ; viewDest . setLookAt ( eye . x , eye . y , eye . z , eye . x + zx , eye . y + zy , eye . z + zz , y . x , y . y , y . z ) ; double px = viewDest . m00 * p . x + viewDest . m10 * p . y + viewDest . m20 * p . z + viewDest . m30 ; double py = viewDest . m01 * p . x + viewDest . m11 * p . y + viewDest . m21 * p . z + viewDest . m31 ; double tx = viewDest . m00 * x . x + viewDest . m10 * x . y + viewDest . m20 * x . z ; double ty = viewDest . m01 * y . x + viewDest . m11 * y . y + viewDest . m21 * y . z ; double len = Math . sqrt ( zx * zx + zy * zy + zz * zz ) ; double near = zd / len , far ; if ( Double . isInfinite ( nearFarDist ) && nearFarDist < 0.0 ) { far = near ; near = Double . POSITIVE_INFINITY ; } else if ( Double . isInfinite ( nearFarDist ) && nearFarDist > 0.0 ) { far = Double . POSITIVE_INFINITY ; } else if ( nearFarDist < 0.0 ) { far = near ; near = near + nearFarDist ; } else { far = near + nearFarDist ; } projDest . setFrustum ( px , px + tx , py , py + ty , near , far , zeroToOne ) ; |
public class FXBinder { /** * Start point of the fluent API to create a binding .
* @ param property the Dolphin Platform property
* @ return binder that can be used by the fluent API to create binding . */
public static NumericDolphinBinder < Float > bindFloat ( Property < Float > property ) { } } | requireNonNull ( property , "property" ) ; return new FloatDolphinBinder ( property ) ; |
public class TableMetadataBuilder { /** * Set the cluster key .
* @ param fields the fields
* @ return the table metadata builder */
@ TimerJ public TableMetadataBuilder withClusterKey ( String ... fields ) { } } | for ( String field : fields ) { clusterKey . add ( new ColumnName ( tableName , field ) ) ; } return this ; |
public class ClockSkewDetector { /** * Search for the self - published client time on { @ link # mDev } .
* @ return XML element with client and server timestamp
* @ throws IfmapErrorResult
* @ throws IfmapException */
private Element searchTime ( ) throws IfmapErrorResult , IfmapException { } } | SearchRequest sr ; SearchResult res ; List < ResultItem > items ; ResultItem ri ; List < Document > mlist ; Node node ; String resultFilter = IfmapStrings . OP_METADATA_PREFIX + ":client-time[@" + IfmapStrings . PUBLISHER_ID_ATTR + " = \"" + mSsrc . getPublisherId ( ) + "\"]" ; sr = Requests . createSearchReq ( null , 0 , null , null , resultFilter , mDev ) ; sr . addNamespaceDeclaration ( IfmapStrings . OP_METADATA_PREFIX , IfmapStrings . OP_METADATA_NS_URI ) ; res = mSsrc . search ( sr ) ; items = res . getResultItems ( ) ; if ( items . size ( ) > 1 ) { IfmapJLog . warn ( "time sync: weird result item count: " + items . size ( ) ) ; } if ( items . size ( ) == 0 ) { throw new IfmapException ( "time sync" , "No ResultItems for search!" ) ; } ri = items . get ( 0 ) ; mlist = ri . getMetadata ( ) ; if ( mlist . size ( ) > 1 ) { IfmapJLog . warn ( "time sync: multiple client-time elements: " + mlist . size ( ) ) ; } if ( mlist . size ( ) == 0 ) { throw new IfmapException ( "time sync" , "No client-time metadata!" ) ; } // Take the last one in the list , hoping that it is the most current
// one .
Document clientTime = mlist . get ( mlist . size ( ) - 1 ) ; node = clientTime . getFirstChild ( ) ; if ( node . getNodeType ( ) != Node . ELEMENT_NODE ) { throw new IfmapException ( "time sync" , "Metadata is not element" ) ; } return ( Element ) node ; |
public class Configuration { private int convertToInt ( Object o , int defaultValue ) { } } | if ( o . getClass ( ) == Integer . class ) { return ( Integer ) o ; } else if ( o . getClass ( ) == Long . class ) { long value = ( Long ) o ; if ( value <= Integer . MAX_VALUE && value >= Integer . MIN_VALUE ) { return ( int ) value ; } else { LOG . warn ( "Configuration value {} overflows/underflows the integer type." , value ) ; return defaultValue ; } } else { try { return Integer . parseInt ( o . toString ( ) ) ; } catch ( NumberFormatException e ) { LOG . warn ( "Configuration cannot evaluate value {} as an integer number" , o ) ; return defaultValue ; } } |
public class CmsPopup { /** * Sets the height for the popup content . < p >
* @ param height the height in pixels */
public void setHeight ( int height ) { } } | if ( height <= 0 ) { m_containerElement . getStyle ( ) . clearWidth ( ) ; m_main . getStyle ( ) . clearHeight ( ) ; } else { int contentHeight = height - 6 ; if ( hasCaption ( ) ) { contentHeight = contentHeight - 36 ; } if ( hasButtons ( ) ) { contentHeight = contentHeight - 34 ; } contentHeight = contentHeight - m_contentHeightCorrection ; m_main . getStyle ( ) . setHeight ( contentHeight , Unit . PX ) ; } |
public class BlockCanaryContext { /** * Provide white list , entry in white list will not be shown in ui list .
* @ return return null if you don ' t need white - list filter . */
public List < String > provideWhiteList ( ) { } } | LinkedList < String > whiteList = new LinkedList < > ( ) ; whiteList . add ( "org.chromium" ) ; return whiteList ; |
public class Sql { /** * Performs the given SQL query calling the given Closure with each row of the result set .
* The row will be a < code > GroovyResultSet < / code > which is a < code > ResultSet < / code >
* that supports accessing the fields using property style notation and ordinal index values .
* Example usages :
* < pre >
* sql . eachRow ( " select * from PERSON where firstname like ' S % ' " ) { row - >
* println " $ row . firstname $ { row [ 2 ] } } "
* sql . eachRow " call my _ stored _ proc _ returning _ resultset ( ) " , {
* println it . firstname
* < / pre >
* Resource handling is performed automatically where appropriate .
* @ param sql the sql statement
* @ param closure called for each row with a GroovyResultSet
* @ throws SQLException if a database access error occurs */
public void eachRow ( String sql , Closure closure ) throws SQLException { } } | eachRow ( sql , ( Closure ) null , closure ) ; |
public class SdkConfigurationPropertyMarshaller { /** * Marshall the given parameter object . */
public void marshall ( SdkConfigurationProperty sdkConfigurationProperty , ProtocolMarshaller protocolMarshaller ) { } } | if ( sdkConfigurationProperty == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( sdkConfigurationProperty . getName ( ) , NAME_BINDING ) ; protocolMarshaller . marshall ( sdkConfigurationProperty . getFriendlyName ( ) , FRIENDLYNAME_BINDING ) ; protocolMarshaller . marshall ( sdkConfigurationProperty . getDescription ( ) , DESCRIPTION_BINDING ) ; protocolMarshaller . marshall ( sdkConfigurationProperty . getRequired ( ) , REQUIRED_BINDING ) ; protocolMarshaller . marshall ( sdkConfigurationProperty . getDefaultValue ( ) , DEFAULTVALUE_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class XmlValidate { /** * Run method . */
public static void main ( String [ ] args ) { } } | if ( args . length < 1 ) { System . out . println ( "Usage: validate <file.xml>" ) ; } else { try { XmlValidator xmlValidator = new XmlValidator ( ) ; File xmlFile = new File ( args [ 0 ] ) ; // Un - comment to enable DTD / XSL caching .
/* File cacheDir = new File ( new File ( url . getFile ( ) ) , " entity _ cache " ) ;
if ( ! cacheDir . exists ( ) & & ! cacheDir . mkdirs ( ) ) {
Assert . fail ( " Could not make entity _ cache directory ! " ) ;
XmlEntityResolver entityResolver = new XmlEntityResolver ( cacheDir ) ; */
XmlEntityResolver entityResolver = null ; XmlErrorHandler errorHandler = new XmlErrorHandler ( ) ; XmlValidationResult result = xmlValidator . validate ( xmlFile , entityResolver , errorHandler ) ; if ( result != null ) { System . out . println ( " bDtd: " + result . bDtdUsed ) ; System . out . println ( " bXsd: " + result . bXsdUsed ) ; System . out . println ( "bWellformed: " + result . bWellformed ) ; System . out . println ( " bValid: " + result . bValid ) ; } else { System . out . println ( "Unable to validate file!" ) ; } } catch ( Throwable t ) { t . printStackTrace ( ) ; } } |
public class ThreadedAuditQueue { /** * / * ( non - Javadoc )
* @ see org . openhealthtools . ihe . atna . auditor . queue . AuditMessageQueue # sendAuditEvent ( org . openhealthtools . ihe . atna . auditor . events . AuditEventMessage , java . net . InetAddress , int ) */
public void sendAuditEvent ( AuditEventMessage msg , InetAddress destination , int port ) { } } | thread . getMessagesToSend ( ) . add ( msg ) ; |
public class CoinbaseProMarketDataService { /** * Get trades data for a specific currency pair
* < p > If invoked with only the currency pair , the method will make a single api call , returning
* the default number ( currently 100 ) of the most recent trades . If invoked with either optional
* argument the other must be specified as well .
* @ param currencyPair Currency pair to obtain trades for ( required )
* @ param args [ 0 ] fromTradeId ( Long ) Return Trades with tradeIds greater than or equal to this
* value . Additional values may be returned . ( optional )
* @ param args [ 1 ] toTradeId ( Long ) Return Trades with tradeIds up to but not including this value
* ( optional )
* @ return A Trades object holding the requested trades */
@ Override public Trades getTrades ( CurrencyPair currencyPair , Object ... args ) throws IOException , RateLimitExceededException { } } | if ( args . length == 0 ) { return CoinbaseProAdapters . adaptTrades ( getCoinbaseProTrades ( currencyPair ) , currencyPair ) ; } else if ( ( args . length == 2 ) && ( args [ 0 ] instanceof Long ) && ( args [ 1 ] instanceof Long ) ) { Long fromTradeId = ( Long ) args [ 0 ] ; Long toTradeId = ( Long ) args [ 1 ] ; log . debug ( "fromTradeId: {}, toTradeId: {}" , fromTradeId , toTradeId ) ; Long latestTradeId = toTradeId ; CoinbaseProTrades CoinbaseProTrades = new CoinbaseProTrades ( ) ; for ( ; ; ) { CoinbaseProTrades CoinbaseProTradesNew = getCoinbaseProTradesExtended ( currencyPair , latestTradeId , 100 ) ; CoinbaseProTrades . addAll ( CoinbaseProTradesNew ) ; log . debug ( "latestTradeId: {}, earliest-latest: {}-{}, trades: {}" , latestTradeId , CoinbaseProTrades . getEarliestTradeId ( ) , CoinbaseProTrades . getLatestTradeId ( ) , CoinbaseProTrades ) ; latestTradeId = CoinbaseProTrades . getEarliestTradeId ( ) ; if ( CoinbaseProTradesNew . getEarliestTradeId ( ) == null ) { break ; } if ( CoinbaseProTrades . getEarliestTradeId ( ) <= fromTradeId ) { break ; } } log . debug ( "earliest-latest: {}-{}" , CoinbaseProTrades . getEarliestTradeId ( ) , CoinbaseProTrades . getLatestTradeId ( ) ) ; if ( log . isDebugEnabled ( ) ) { CoinbaseProTrades . stream ( ) . forEach ( System . out :: println ) ; } return CoinbaseProAdapters . adaptTrades ( CoinbaseProTrades , currencyPair ) ; } throw new IllegalArgumentException ( "Invalid arguments passed to getTrades" ) ; |
public class HTTPAnnounceRequestMessage { /** * Build the announce request URL for the given tracker announce URL .
* @ param trackerAnnounceURL The tracker ' s announce URL .
* @ return The URL object representing the announce request URL . */
public URL buildAnnounceURL ( URL trackerAnnounceURL ) throws UnsupportedEncodingException , MalformedURLException { } } | String base = trackerAnnounceURL . toString ( ) ; StringBuilder url = new StringBuilder ( base ) ; url . append ( base . contains ( "?" ) ? "&" : "?" ) . append ( "info_hash=" ) . append ( URLEncoder . encode ( new String ( this . getInfoHash ( ) , Constants . BYTE_ENCODING ) , Constants . BYTE_ENCODING ) ) . append ( "&peer_id=" ) . append ( URLEncoder . encode ( new String ( this . getPeerId ( ) , Constants . BYTE_ENCODING ) , Constants . BYTE_ENCODING ) ) . append ( "&port=" ) . append ( this . getPort ( ) ) . append ( "&uploaded=" ) . append ( this . getUploaded ( ) ) . append ( "&downloaded=" ) . append ( this . getDownloaded ( ) ) . append ( "&left=" ) . append ( this . getLeft ( ) ) . append ( "&compact=" ) . append ( this . isCompact ( ) ? 1 : 0 ) . append ( "&no_peer_id=" ) . append ( this . canOmitPeerId ( ) ? 1 : 0 ) ; if ( this . getEvent ( ) != null && ! RequestEvent . NONE . equals ( this . getEvent ( ) ) ) { url . append ( "&event=" ) . append ( this . getEvent ( ) . getEventName ( ) ) ; } if ( this . getIp ( ) != null ) { url . append ( "&ip=" ) . append ( this . getIp ( ) ) ; } return new URL ( url . toString ( ) ) ; |
public class Nodes { /** * Flatten , in parallel , a { @ link Node . OfLong } . A flattened node is one that
* has no children . If the node is already flat , it is simply returned .
* @ implSpec
* If a new node is to be created , a new long [ ] array is created whose length
* is { @ link Node # count ( ) } . Then the node tree is traversed and leaf node
* elements are placed in the array concurrently by leaf tasks at the
* correct offsets .
* @ param node the node to flatten
* @ return a flat { @ code Node . OfLong } */
public static Node . OfLong flattenLong ( Node . OfLong node ) { } } | if ( node . getChildCount ( ) > 0 ) { long size = node . count ( ) ; if ( size >= MAX_ARRAY_SIZE ) throw new IllegalArgumentException ( BAD_SIZE ) ; long [ ] array = new long [ ( int ) size ] ; new ToArrayTask . OfLong ( node , array , 0 ) . invoke ( ) ; return node ( array ) ; } else { return node ; } |
public class Processor { /** * Process the given file ( as bytes ) and return the information record .
* @ param bytes
* The file to process as a byte array .
* @ param fileName
* The name of the file being processed .
* @ param knownTypesOnly
* If set , file types known to the class are only processed . If
* set to < code > false < / code > and a class is not defined
* explicitely for this type , { @ link File } class will be used to
* produce the { @ link Artifact } .
* @ return Information record of type { @ link Artifact } */
public static Artifact process ( byte [ ] bytes , String fileName , Boolean knownTypesOnly ) { } } | String fileType = Processor . getFileType ( fileName ) ; if ( ! knownTypesOnly || ( knownTypesOnly && Processor . isKnownType ( fileType ) ) ) { // Only handle types we know about eg : . class . jar
Class < ? > cls = Processor . getProcessor ( fileType ) ; if ( AbstractFile . class . isAssignableFrom ( cls ) ) { try { // TOOD : Maybe find a better way of doing this .
Constructor < ? > ctor ; ctor = cls . getConstructor ( byte [ ] . class , String . class ) ; Object object ; object = ctor . newInstance ( new Object [ ] { bytes , fileName } ) ; return ( ( FingerprintInterface ) object ) . getRecord ( ) ; } catch ( NoSuchMethodException e ) { } catch ( SecurityException e ) { } catch ( InstantiationException e ) { } catch ( IllegalAccessException e ) { } catch ( IllegalArgumentException e ) { } catch ( InvocationTargetException e ) { } catch ( Exception e ) { } } } return null ; |
public class StringValueData { /** * { @ inheritDoc } */
protected boolean internalEquals ( ValueData another ) { } } | if ( another instanceof StringValueData ) { return ( ( StringValueData ) another ) . value . equals ( value ) ; } return false ; |
public class SqlQueryStatement { /** * Append Join for SQL92 Syntax */
private void appendJoinSQL92 ( Join join , StringBuffer where , StringBuffer buf ) { } } | if ( join . isOuter ) { buf . append ( " LEFT OUTER JOIN " ) ; } else { buf . append ( " INNER JOIN " ) ; } if ( join . right . hasJoins ( ) ) { buf . append ( "(" ) ; appendTableWithJoins ( join . right , where , buf ) ; buf . append ( ")" ) ; } else { appendTableWithJoins ( join . right , where , buf ) ; } buf . append ( " ON " ) ; join . appendJoinEqualities ( buf ) ; |
public class Event { /** * For given type defined with the instance parameter , this trigger is
* searched by typeID and index position . If the trigger exists , the
* trigger is updated . Otherwise the trigger is created .
* @ param _ instance type instance to update with this attribute
* @ param _ typeName name of the type to update
* @ return Instance of the updated or inserted Trigger , null in case of
* error */
public Instance updateInDB ( final Instance _instance , final String _typeName ) { } } | Instance ret = null ; try { final long typeID = _instance . getId ( ) ; final long progID = getProgID ( _typeName ) ; final QueryBuilder queryBldr = new QueryBuilder ( Type . get ( this . event . getName ( ) ) ) ; queryBldr . addWhereAttrEqValue ( "Abstract" , typeID ) ; queryBldr . addWhereAttrEqValue ( "Name" , this . name ) ; final InstanceQuery query = queryBldr . getQuery ( ) ; query . executeWithoutAccessCheck ( ) ; final Update update ; if ( query . next ( ) ) { update = new Update ( query . getCurrentValue ( ) ) ; } else { update = new Insert ( this . event . getName ( ) ) ; update . add ( "Abstract" , typeID ) ; update . add ( "IndexPosition" , this . index ) ; update . add ( "Name" , this . name ) ; } update . add ( "JavaProg" , progID ) ; update . add ( "Method" , this . method ) ; update . executeWithoutAccessCheck ( ) ; ret = update . getInstance ( ) ; update . close ( ) ; } catch ( final EFapsException e ) { Event . LOG . error ( "updateInDB(Instance, String)" , e ) ; // CHECKSTYLE : OFF
} catch ( final Exception e ) { // CHECKSTYLE : ON
Event . LOG . error ( "updateInDB(Instance, String)" , e ) ; } return ret ; |
public class CharMatcher { /** * Returns a matcher with identical behavior to the given { @ link Character } - based predicate , but
* which operates on primitive { @ code char } instances instead .
* @ param predicate the predicate
* @ return the char matcher */
public static CharMatcher forPredicate ( final Predicate < ? super Character > predicate ) { } } | checkNotNull ( predicate ) ; if ( predicate instanceof CharMatcher ) { return ( CharMatcher ) predicate ; } return new CharMatcher ( ) { @ Override public boolean matches ( char c ) { return predicate . apply ( c ) ; } @ Override public boolean apply ( Character character ) { return predicate . apply ( checkNotNull ( character ) ) ; } @ Override public String toString ( ) { return "CharMatcher.forPredicate(" + predicate + ")" ; } } ; |
public class Int2IntHashMap { /** * Get the minimum value stored in the map . If the map is empty then it will return { @ link # missingValue ( ) }
* @ return the minimum value stored in the map . */
public int minValue ( ) { } } | final int missingValue = this . missingValue ; int min = size == 0 ? missingValue : Integer . MAX_VALUE ; final int [ ] entries = this . entries ; @ DoNotSub final int length = entries . length ; for ( @ DoNotSub int valueIndex = 1 ; valueIndex < length ; valueIndex += 2 ) { final int value = entries [ valueIndex ] ; if ( value != missingValue ) { min = Math . min ( min , value ) ; } } return min ; |
public class Main { /** * This function calculates the product of two integers without utilizing the * operator .
* Example :
* > > > productOfIntegers ( 10 , 20)
* 200
* > > > productOfIntegers ( 5 , 10)
* 50
* > > > productOfIntegers ( 4 , 8)
* 32 */
public static int productOfIntegers ( int a , int b ) { } public static void main ( String [ ] args ) { System . out . println ( productOfIntegers ( 10 , 20 ) ) ; System . out . println ( productOfIntegers ( 5 , 10 ) ) ; System . out . println ( productOfIntegers ( 4 , 8 ) ) ; } } | if ( b < 0 ) { return - productOfIntegers ( a , - b ) ; } else if ( b == 0 ) { return 0 ; } else if ( b == 1 ) { return a ; } else { return a + productOfIntegers ( a , b - 1 ) ; } |
public class UCharacter { /** * < p > Returns the titlecase version of the argument string .
* < p > Position for titlecasing is determined by the argument break
* iterator , hence the user can customize his break iterator for
* a specialized titlecasing . In this case only the forward iteration
* needs to be implemented .
* If the break iterator passed in is null , the default Unicode algorithm
* will be used to determine the titlecase positions .
* < p > Only positions returned by the break iterator will be title cased ,
* character in between the positions will all be in lower case .
* < p > Casing is dependent on the default locale and context - sensitive
* @ param str source string to be performed on
* @ param breakiter break iterator to determine the positions in which
* the character should be title cased .
* @ return lowercase version of the argument string */
public static String toTitleCase ( String str , BreakIterator breakiter ) { } } | return toTitleCase ( Locale . getDefault ( ) , str , breakiter , 0 ) ; |
public class filterprebodyinjection { /** * Use this API to update filterprebodyinjection . */
public static base_response update ( nitro_service client , filterprebodyinjection resource ) throws Exception { } } | filterprebodyinjection updateresource = new filterprebodyinjection ( ) ; updateresource . prebody = resource . prebody ; return updateresource . update_resource ( client ) ; |
public class ExampleSection { /** * Selects an example .
* @ param example the example to select .
* @ param exampleName the name of the example being selected . */
public void selectExample ( final WComponent example , final String exampleName ) { } } | WComponent currentExample = container . getChildAt ( 0 ) . getParent ( ) ; if ( currentExample != null && currentExample . getClass ( ) . equals ( example . getClass ( ) ) ) { // Same example selected , do nothing
return ; } resetExample ( ) ; container . removeAll ( ) ; this . getDecoratedLabel ( ) . setBody ( new WText ( exampleName ) ) ; WApplication app = WebUtilities . getAncestorOfClass ( WApplication . class , this ) ; if ( app != null ) { app . setTitle ( exampleName ) ; } if ( example instanceof ErrorComponent ) { tabset . getTab ( 0 ) . setText ( "Error" ) ; source . setSource ( null ) ; } else { String className = example . getClass ( ) . getName ( ) ; WDefinitionList list = new WDefinitionList ( WDefinitionList . Type . COLUMN ) ; container . add ( list ) ; list . addTerm ( "Example path" , new WText ( className . replaceAll ( "\\." , " / " ) ) ) ; list . addTerm ( "Example JavaDoc" , new JavaDocText ( getSource ( className ) ) ) ; container . add ( new WHorizontalRule ( ) ) ; tabset . getTab ( 0 ) . setText ( example . getClass ( ) . getSimpleName ( ) ) ; source . setSource ( getSource ( className ) ) ; } container . add ( example ) ; example . setLocked ( true ) ; |
public class SynchronizedPDUSender { /** * ( non - Javadoc )
* @ see org . jsmpp . PDUSender # sendUnbind ( java . io . OutputStream , int ) */
public byte [ ] sendUnbind ( OutputStream os , int sequenceNumber ) throws IOException { } } | synchronized ( os ) { return pduSender . sendUnbind ( os , sequenceNumber ) ; } |
public class IsotopePatternRule { /** * Validate the isotope pattern of this IMolecularFormula . Important , first
* you have to add with the { @ link # setParameters ( Object [ ] ) } a IMolecularFormulaSet
* which represents the isotope pattern to compare .
* @ param formula Parameter is the IMolecularFormula
* @ return A double value meaning 1.0 True , 0.0 False */
@ Override public double validate ( IMolecularFormula formula ) throws CDKException { } } | logger . info ( "Start validation of " , formula ) ; IsotopePatternGenerator isotopeGe = new IsotopePatternGenerator ( 0.1 ) ; IsotopePattern patternIsoPredicted = isotopeGe . getIsotopes ( formula ) ; IsotopePattern patternIsoNormalize = IsotopePatternManipulator . normalize ( patternIsoPredicted ) ; return is . compare ( pattern , patternIsoNormalize ) ; |
public class Command { /** * Print the usage for the command .
* By default , this prints the description and available parameters . */
public void usage ( ) { } } | String commandName = "" ; String commandDescription = "" ; CLICommand commandAnnotation = this . getClass ( ) . getAnnotation ( CLICommand . class ) ; if ( commandAnnotation == null ) { Parameters commandParameters = this . getClass ( ) . getAnnotation ( Parameters . class ) ; if ( commandParameters != null ) { commandName = commandParameters . commandNames ( ) [ 0 ] ; commandDescription = commandParameters . commandDescription ( ) ; } } else { commandName = commandAnnotation . name ( ) ; commandDescription = commandAnnotation . description ( ) ; } Console . info ( "Help for [" + commandName + "]." ) ; if ( commandDescription != null && ! commandDescription . isEmpty ( ) ) { Console . info ( "Description: " + commandDescription ) ; } JCommander comm = new JCommander ( this ) ; comm . setProgramName ( commandName ) ; comm . usage ( ) ; |
public class ScottClassTransformer { /** * Based on the structure of the class and the supplied configuration , determine
* the concrete instrumentation actions for the class .
* @ param classfileBuffer class to be analyzed
* @ param configuration configuration settings
* @ return instrumentation actions to be applied */
private InstrumentationActions calculateTransformationParameters ( byte [ ] classfileBuffer , Configuration configuration ) { } } | DiscoveryClassVisitor discoveryClassVisitor = new DiscoveryClassVisitor ( configuration ) ; new ClassReader ( classfileBuffer ) . accept ( discoveryClassVisitor , 0 ) ; return discoveryClassVisitor . getTransformationParameters ( ) . build ( ) ; |
public class BigtableDataClientWrapper { /** * { @ inheritDoc } */
@ Override public ApiFuture < List < FlatRow > > readFlatRowsAsync ( Query request ) { } } | return ApiFutureUtil . adapt ( delegate . readFlatRowsAsync ( request . toProto ( requestContext ) ) ) ; |
public class RouteMatcher { /** * Specify a handler that will be called for a matching HTTP PATCH
* @ param pattern The simple pattern
* @ param handler The handler to call */
public RouteMatcher patch ( String pattern , Handler < HttpServerRequest > handler ) { } } | addPattern ( pattern , handler , patchBindings ) ; return this ; |
public class AnnotationUtils { /** * Return whether the given element is annotated with the given annotation stereotypes .
* @ param element The element
* @ param stereotypes The stereotypes
* @ return True if it is */
protected boolean hasStereotype ( Element element , String ... stereotypes ) { } } | return hasStereotype ( element , Arrays . asList ( stereotypes ) ) ; |
public class ExceptionUtils { /** * Gets a short message summarising the exception .
* The message returned is of the form
* { ClassNameWithoutPackage } : { ThrowableMessage }
* @ param th the throwable to get a message for , null returns empty string
* @ return the message , non - null
* @ since Commons Lang 2.2 */
public static String getMessage ( final Throwable th ) { } } | if ( th == null ) { return StringUtils . EMPTY ; } final String clsName = ClassUtils . getShortClassName ( th , null ) ; final String msg = th . getMessage ( ) ; return clsName + ": " + StringUtils . defaultString ( msg ) ; |
public class ExampleSegmentColor { /** * Shows a color image and allows the user to select a pixel , convert it to HSV , print
* the HSV values , and calls the function below to display similar pixels . */
public static void printClickedColor ( final BufferedImage image ) { } } | ImagePanel gui = new ImagePanel ( image ) ; gui . addMouseListener ( new MouseAdapter ( ) { @ Override public void mouseClicked ( MouseEvent e ) { float [ ] color = new float [ 3 ] ; int rgb = image . getRGB ( e . getX ( ) , e . getY ( ) ) ; ColorHsv . rgbToHsv ( ( rgb >> 16 ) & 0xFF , ( rgb >> 8 ) & 0xFF , rgb & 0xFF , color ) ; System . out . println ( "H = " + color [ 0 ] + " S = " + color [ 1 ] + " V = " + color [ 2 ] ) ; showSelectedColor ( "Selected" , image , color [ 0 ] , color [ 1 ] ) ; } } ) ; ShowImages . showWindow ( gui , "Color Selector" ) ; |
public class CmsSolrSpellchecker { /** * Parse JSON parameters from this request .
* @ param jsonRequest The request in the JSON format .
* @ return CmsSpellcheckingRequest object that contains parsed parameters or null , if JSON input is not well
* defined . */
private CmsSpellcheckingRequest parseJsonRequest ( JSONObject jsonRequest ) { } } | final String id = jsonRequest . optString ( JSON_ID ) ; final JSONObject params = jsonRequest . optJSONObject ( JSON_PARAMS ) ; if ( null == params ) { LOG . debug ( "Invalid JSON request: No field \"params\" defined. " ) ; return null ; } final JSONArray words = params . optJSONArray ( JSON_WORDS ) ; final String lang = params . optString ( JSON_LANG , LANG_DEFAULT ) ; if ( null == words ) { LOG . debug ( "Invalid JSON request: No field \"words\" defined. " ) ; return null ; } // Convert JSON array to array of type String
final List < String > wordsToCheck = new LinkedList < String > ( ) ; for ( int i = 0 ; i < words . length ( ) ; i ++ ) { final String word = words . opt ( i ) . toString ( ) ; wordsToCheck . add ( word ) ; if ( Character . isUpperCase ( word . codePointAt ( 0 ) ) ) { wordsToCheck . add ( word . toLowerCase ( ) ) ; } } return new CmsSpellcheckingRequest ( wordsToCheck . toArray ( new String [ wordsToCheck . size ( ) ] ) , lang , id ) ; |
public class Localizable { /** * Goes through the list of preferred wrappers , and returns the value stored the hashtable with
* the ' most good ' matching key , or null if there are no matches . */
private E getBest ( Locale ... preferredLocales ) { } } | long bestGoodness = 0 ; Locale bestKey = null ; for ( Locale locale : preferredLocales ) { for ( Locale key : values . keySet ( ) ) { long goodness = computeGoodness ( locale , key ) ; if ( goodness > bestGoodness ) bestKey = key ; } } if ( bestKey != null ) return exactGet ( bestKey ) ; return null ; |
public class BaseNDArrayFactory { /** * Create a random ndarray with the given shape using the given rng
* @ param shape the shape of the ndarray
* @ param r the random generator to use
* @ return the random ndarray with the specified shape */
@ Override public INDArray rand ( int [ ] shape , org . nd4j . linalg . api . rng . Random r ) { } } | INDArray ret = r . nextDouble ( shape ) ; return ret ; |
public class MetadataContext { /** * Invokes { @ link DatabaseMetaData # getIndexInfo ( java . lang . String , java . lang . String , java . lang . String , boolean ,
* boolean ) } with given arguments and returns bound information .
* @ param catalog catalog the value for { @ code catalog } parameter
* @ param schema schema the value for { @ code schema } parameter
* @ param table table the value for { @ code table } parameter
* @ param unique unique the value for { @ code unique } parameter
* @ param approximate approximate the value for { @ code approximage } parameter
* @ return a list of index info
* @ throws SQLException if a database error occurs . */
public List < IndexInfo > getIndexInfo ( final String catalog , final String schema , final String table , final boolean unique , final boolean approximate ) throws SQLException { } } | final List < IndexInfo > list = new ArrayList < > ( ) ; try ( ResultSet results = databaseMetadata . getIndexInfo ( catalog , schema , table , unique , approximate ) ) { if ( results != null ) { bind ( results , IndexInfo . class , list ) ; } } return list ; |
public class WhileyFileParser { /** * Check whether we have duplicate case conditions or not . Observe that this is
* relatively simplistic and does not perform any complex simplifications .
* Therefore , some duplicates are missed because they require simplification .
* For example , the condition < code > 1 + 1 < / code > and < code > 2 < / code > are not
* considered duplicates here . See # 648 for more . */
private void checkForDuplicateConditions ( List < Stmt . Case > cases ) { } } | HashSet < Expr > seen = new HashSet < > ( ) ; for ( int i = 0 ; i != cases . size ( ) ; ++ i ) { Stmt . Case c = cases . get ( i ) ; Tuple < Expr > conditions = c . getConditions ( ) ; // Check whether any of these conditions already seen .
for ( int j = 0 ; j != conditions . size ( ) ; ++ j ) { Expr condition = conditions . get ( j ) ; if ( seen . contains ( condition ) ) { syntaxError ( "duplicate case label" , condition ) ; } else { seen . add ( condition ) ; } } } |
public class Directory { /** * this method only exists for performance reason */
private static int _fillArrayName ( Array arr , Resource directory , ResourceFilter filter , int count ) { } } | if ( filter == null || filter instanceof ResourceNameFilter ) { ResourceNameFilter rnf = filter == null ? null : ( ResourceNameFilter ) filter ; String [ ] list = directory . list ( ) ; if ( list == null || list . length == 0 ) return count ; for ( int i = 0 ; i < list . length ; i ++ ) { if ( rnf == null || rnf . accept ( directory , list [ i ] ) ) { arr . appendEL ( list [ i ] ) ; } } } else { Resource [ ] list = directory . listResources ( ) ; if ( list == null || list . length == 0 ) return count ; for ( int i = 0 ; i < list . length ; i ++ ) { if ( filter . accept ( list [ i ] ) ) { arr . appendEL ( list [ i ] . getName ( ) ) ; } } } return count ; |
public class CommonOps_DDF4 { /** * < p > Performs matrix to vector multiplication : < br >
* < br >
* c = a * b < br >
* < br >
* c < sub > i < / sub > = & sum ; < sub > k = 1 : n < / sub > { a < sub > ik < / sub > * b < sub > k < / sub > }
* @ param a The left matrix in the multiplication operation . Not modified .
* @ param b The right vector in the multiplication operation . Not modified .
* @ param c Where the results of the operation are stored . Modified . */
public static void mult ( DMatrix4x4 a , DMatrix4 b , DMatrix4 c ) { } } | c . a1 = a . a11 * b . a1 + a . a12 * b . a2 + a . a13 * b . a3 + a . a14 * b . a4 ; c . a2 = a . a21 * b . a1 + a . a22 * b . a2 + a . a23 * b . a3 + a . a24 * b . a4 ; c . a3 = a . a31 * b . a1 + a . a32 * b . a2 + a . a33 * b . a3 + a . a34 * b . a4 ; c . a4 = a . a41 * b . a1 + a . a42 * b . a2 + a . a43 * b . a3 + a . a44 * b . a4 ; |
public class CTCImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
@ Override public void eSet ( int featureID , Object newValue ) { } } | switch ( featureID ) { case AfplibPackage . CTC__CON_DATA : setConData ( ( byte [ ] ) newValue ) ; return ; } super . eSet ( featureID , newValue ) ; |
public class Gather { /** * Sort elements by special ordering
* @ param ordering
* @ return */
public Gather < T > order ( Ordering < T > ordering ) { } } | Collection < T > sorted = ordering . sortedCopy ( list ( ) ) ; elements = Optional . fromNullable ( sorted ) ; return this ; |
public class AgiRequestImpl { /** * Parses the given parameter string and caches the result .
* @ param s the parameter string to parse
* @ return a Map made up of parameter names their values */
private synchronized Map < String , String [ ] > parseParameters ( String s ) { } } | Map < String , List < String > > parameterMap ; Map < String , String [ ] > result ; StringTokenizer st ; parameterMap = new HashMap < > ( ) ; result = new HashMap < > ( ) ; if ( s == null ) { return result ; } st = new StringTokenizer ( s , "&" ) ; while ( st . hasMoreTokens ( ) ) { String parameter ; Matcher parameterMatcher ; String name ; String value ; List < String > values ; parameter = st . nextToken ( ) ; parameterMatcher = PARAMETER_PATTERN . matcher ( parameter ) ; if ( parameterMatcher . matches ( ) ) { try { name = URLDecoder . decode ( parameterMatcher . group ( 1 ) , "UTF-8" ) ; value = URLDecoder . decode ( parameterMatcher . group ( 2 ) , "UTF-8" ) ; } catch ( UnsupportedEncodingException e ) { logger . error ( "Unable to decode parameter '" + parameter + "'" , e ) ; continue ; } } else { try { name = URLDecoder . decode ( parameter , "UTF-8" ) ; value = "" ; } catch ( UnsupportedEncodingException e ) { logger . error ( "Unable to decode parameter '" + parameter + "'" , e ) ; continue ; } } if ( parameterMap . get ( name ) == null ) { values = new ArrayList < > ( ) ; values . add ( value ) ; parameterMap . put ( name , values ) ; } else { values = parameterMap . get ( name ) ; values . add ( value ) ; } } for ( Map . Entry < String , List < String > > entry : parameterMap . entrySet ( ) ) { String [ ] valueArray ; valueArray = new String [ entry . getValue ( ) . size ( ) ] ; result . put ( entry . getKey ( ) , entry . getValue ( ) . toArray ( valueArray ) ) ; } return result ; |
public class Eh107Configuration { /** * Creates a new JSR - 107 { @ link Configuration } from the provided { @ link CacheConfiguration } obtained through a
* { @ link Builder } .
* @ param ehcacheConfigBuilder the native Ehcache configuration through a builder
* @ param < K > the key type
* @ param < V > the value type
* @ return a JSR - 107 configuration */
public static < K , V > Configuration < K , V > fromEhcacheCacheConfiguration ( Builder < ? extends CacheConfiguration < K , V > > ehcacheConfigBuilder ) { } } | return new Eh107ConfigurationWrapper < > ( ehcacheConfigBuilder . build ( ) ) ; |
public class WxCryptUtil { /** * 微信公众号支付签名算法 ( 详见 : http : / / pay . weixin . qq . com / wiki / doc / api / index . php ? chapter = 4_3)
* @ param packageParams 原始参数
* @ param signKey 加密Key ( 即 商户Key )
* @ param charset 编码
* @ return 签名字符串 */
public static String createSign ( Map < String , String > packageParams , String signKey ) { } } | SortedMap < String , String > sortedMap = new TreeMap < String , String > ( ) ; sortedMap . putAll ( packageParams ) ; List < String > keys = new ArrayList < String > ( packageParams . keySet ( ) ) ; Collections . sort ( keys ) ; StringBuffer toSign = new StringBuffer ( ) ; for ( String key : keys ) { String value = packageParams . get ( key ) ; if ( null != value && ! "" . equals ( value ) && ! "sign" . equals ( key ) && ! "key" . equals ( key ) ) { toSign . append ( key + "=" + value + "&" ) ; } } toSign . append ( "key=" + signKey ) ; String sign = DigestUtils . md5Hex ( toSign . toString ( ) ) . toUpperCase ( ) ; return sign ; |
public class Utils { /** * NULL and range safe get ( ) */
public static < T > T get ( List < T > data , int position ) { } } | return position < 0 || position >= Utils . sizeOf ( data ) ? null : data . get ( position ) ; |
public class NetworkParameters { /** * The flags indicating which script validation tests should be applied to
* the given transaction . Enables support for alternative blockchains which enable
* tests based on different criteria .
* @ param block block the transaction belongs to .
* @ param transaction to determine flags for .
* @ param height height of the block , if known , null otherwise . Returned
* tests should be a safe subset if block height is unknown . */
public EnumSet < Script . VerifyFlag > getTransactionVerificationFlags ( final Block block , final Transaction transaction , final VersionTally tally , final Integer height ) { } } | final EnumSet < Script . VerifyFlag > verifyFlags = EnumSet . noneOf ( Script . VerifyFlag . class ) ; if ( block . getTimeSeconds ( ) >= NetworkParameters . BIP16_ENFORCE_TIME ) verifyFlags . add ( Script . VerifyFlag . P2SH ) ; // Start enforcing CHECKLOCKTIMEVERIFY , ( BIP65 ) for block . nVersion = 4
// blocks , when 75 % of the network has upgraded :
if ( block . getVersion ( ) >= Block . BLOCK_VERSION_BIP65 && tally . getCountAtOrAbove ( Block . BLOCK_VERSION_BIP65 ) > this . getMajorityEnforceBlockUpgrade ( ) ) { verifyFlags . add ( Script . VerifyFlag . CHECKLOCKTIMEVERIFY ) ; } return verifyFlags ; |
public class MembershipTypeHandlerImpl { /** * Notifying listeners after membership type deletion .
* @ param type
* the membership which is used in delete operation
* @ throws Exception
* if any listener failed to handle the event */
private void postDelete ( MembershipType type ) throws Exception { } } | for ( MembershipTypeEventListener listener : listeners ) { listener . postDelete ( type ) ; } |
public class Compiler { /** * Compiler recovery in case of internal AbortCompilation event */
protected void handleInternalException ( AbortCompilation abortException , CompilationUnitDeclaration unit ) { } } | /* special treatment for SilentAbort : silently cancelling the compilation process */
if ( abortException . isSilent ) { if ( abortException . silentException == null ) { return ; } throw abortException . silentException ; } /* uncomment following line to see where the abort came from */
// abortException . printStackTrace ( ) ;
// Exception may tell which compilation result it is related , and which problem caused it
CompilationResult result = abortException . compilationResult ; if ( result == null && unit != null ) { result = unit . compilationResult ; // current unit being processed ?
} // Lookup environment may be in middle of connecting types
if ( result == null && this . lookupEnvironment . unitBeingCompleted != null ) { result = this . lookupEnvironment . unitBeingCompleted . compilationResult ; } if ( result == null ) { synchronized ( this ) { if ( this . unitsToProcess != null && this . totalUnits > 0 ) result = this . unitsToProcess [ this . totalUnits - 1 ] . compilationResult ; } } // last unit in beginToCompile ?
if ( result != null && ! result . hasBeenAccepted ) { /* distant problem which could not be reported back there ? */
if ( abortException . problem != null ) { recordDistantProblem : { CategorizedProblem distantProblem = abortException . problem ; CategorizedProblem [ ] knownProblems = result . problems ; for ( int i = 0 ; i < result . problemCount ; i ++ ) { if ( knownProblems [ i ] == distantProblem ) { // already recorded
break recordDistantProblem ; } } if ( distantProblem instanceof DefaultProblem ) { // fixup filename TODO ( philippe ) should improve API to make this official
( ( DefaultProblem ) distantProblem ) . setOriginatingFileName ( result . getFileName ( ) ) ; } result . record ( distantProblem , unit , true ) ; } } else { /* distant internal exception which could not be reported back there */
if ( abortException . exception != null ) { this . handleInternalException ( abortException . exception , null , result ) ; return ; } } /* hand back the compilation result */
if ( ! result . hasBeenAccepted ) { this . requestor . acceptResult ( result . tagAsAccepted ( ) ) ; } } else { abortException . printStackTrace ( ) ; } |
public class CProductLocalServiceUtil { /** * Updates the c product in the database or adds it if it does not yet exist . Also notifies the appropriate model listeners .
* @ param cProduct the c product
* @ return the c product that was updated */
public static com . liferay . commerce . product . model . CProduct updateCProduct ( com . liferay . commerce . product . model . CProduct cProduct ) { } } | return getService ( ) . updateCProduct ( cProduct ) ; |
public class ProductSegmentation { /** * Sets the adUnitSegments value for this ProductSegmentation .
* @ param adUnitSegments * The ad unit targeting segmentation . For each ad unit segment ,
* { @ link AdUnitTargeting # includeDescendants } must be true .
* < p > This attribute is optional . */
public void setAdUnitSegments ( com . google . api . ads . admanager . axis . v201805 . AdUnitTargeting [ ] adUnitSegments ) { } } | this . adUnitSegments = adUnitSegments ; |
public class NMMin { /** * Evaluate ( ) method */
@ Override public void evaluate ( IntegerSolution solution ) { } } | int approximationToN ; int approximationToM ; approximationToN = 0 ; approximationToM = 0 ; for ( int i = 0 ; i < solution . getNumberOfVariables ( ) ; i ++ ) { int value = solution . getVariableValue ( i ) ; approximationToN += Math . abs ( valueN - value ) ; approximationToM += Math . abs ( valueM - value ) ; } solution . setObjective ( 0 , approximationToN ) ; solution . setObjective ( 1 , approximationToM ) ; |
public class SimpleNameTokeniser { /** * Provides a naive camel case splitter to work on character only string .
* @ param name a character only string
* @ return an Array list of components of the input string that result from
* splitting on LCUC boundaries . */
private static List < String > tokeniseOnLowercaseToUppercase ( String name ) { } } | List < String > splits = new ArrayList < > ( ) ; // the following stores data in pairs ( start , finish , start , . . . )
ArrayList < Integer > candidateBoundaries = new ArrayList < > ( ) ; // now process the array looking for boundaries
for ( Integer index = 0 ; index < name . length ( ) ; index ++ ) { if ( index == 0 ) { // the first character is always a boundary
candidateBoundaries . add ( index ) ; } else { if ( Character . isUpperCase ( name . codePointAt ( index ) ) && Character . isLowerCase ( name . codePointAt ( index - 1 ) ) ) { candidateBoundaries . add ( index - 1 ) ; candidateBoundaries . add ( index ) ; } } // now check whether this is the terminal character .
// and record it to give us the final boundary
if ( index == name . length ( ) - 1 ) { candidateBoundaries . add ( index ) ; } } if ( candidateBoundaries . size ( ) % 2 == 1 ) { LOGGER . warn ( "Odd number of boundaries found for: \"{}\"" , name ) ; } for ( int i = 0 ; i < candidateBoundaries . size ( ) ; i += 2 ) { splits . add ( name . substring ( candidateBoundaries . get ( i ) , candidateBoundaries . get ( i + 1 ) + 1 ) ) ; } return splits ; |
public class CmsLruCache { /** * Adds a new object to this cache . < p >
* If add the same object more than once ,
* the object is touched instead . < p >
* @ param theCacheObject the object being added to the cache
* @ return true if the object was added to the cache , false if the object was denied because its cache costs were higher than the allowed max . cache costs per object */
public synchronized boolean add ( I_CmsLruCacheObject theCacheObject ) { } } | if ( theCacheObject == null ) { // null can ' t be added or touched in the cache
return false ; } // only objects with cache costs < the max . allowed object cache costs can be cached !
if ( ( m_maxObjectCosts != - 1 ) && ( theCacheObject . getLruCacheCosts ( ) > m_maxObjectCosts ) ) { if ( LOG . isInfoEnabled ( ) ) { LOG . info ( Messages . get ( ) . getBundle ( ) . key ( Messages . LOG_CACHE_COSTS_TOO_HIGH_2 , new Integer ( theCacheObject . getLruCacheCosts ( ) ) , new Integer ( m_maxObjectCosts ) ) ) ; } return false ; } if ( ! isCached ( theCacheObject ) ) { // add the object to the list of all cached objects in the cache
addHead ( theCacheObject ) ; } else { touch ( theCacheObject ) ; } // check if the cache has to trash the last - recently - used objects before adding a new object
if ( m_objectCosts > m_maxCacheCosts ) { gc ( ) ; } return true ; |
public class FessMessages { /** * Add the created action message for the key ' constraints . Max . message ' with parameters .
* < pre >
* message : { item } must be less than or equal to { value } .
* < / pre >
* @ param property The property name for the message . ( NotNull )
* @ param value The parameter value for message . ( NotNull )
* @ return this . ( NotNull ) */
public FessMessages addConstraintsMaxMessage ( String property , String value ) { } } | assertPropertyNotNull ( property ) ; add ( property , new UserMessage ( CONSTRAINTS_Max_MESSAGE , value ) ) ; return this ; |
public class ValidatingCallbackHandler { /** * / * ( non - Javadoc )
* @ see org . jboss . as . cli . operation . OperationParser . CallbackHandler # propertyName ( java . lang . String ) */
@ Override public void propertyName ( int index , String propertyName ) throws OperationFormatException { } } | // TODO this is not nice
if ( propertyName . length ( ) > 1 && propertyName . charAt ( 0 ) == '-' && propertyName . charAt ( 1 ) == '-' ) { assertValidParameterName ( propertyName . substring ( 2 ) ) ; } else if ( propertyName . length ( ) > 0 && propertyName . charAt ( 0 ) == '-' ) { assertValidParameterName ( propertyName . substring ( 1 ) ) ; } else { assertValidParameterName ( propertyName ) ; } validatedPropertyName ( index , propertyName ) ; |
public class IndexerWorkItemQueue { /** * Queue a work item and handle it asynchronously .
* @ param aItem
* The item to be added . May not be < code > null < / code > . */
public void queueObject ( @ Nonnull final IIndexerWorkItem aItem ) { } } | ValueEnforcer . notNull ( aItem , "Item" ) ; m_aImmediateCollector . queueObject ( aItem ) ; |
public class AbstractParsedStmt { /** * Populate the statement ' s paramList from the " parameters " element . Each
* parameter has an id and an index , both of which are numeric . It also has
* a type and an indication of whether it ' s a vector parameter . For each
* parameter , we create a ParameterValueExpression , named pve , which holds
* the type and vector parameter indication . We add the pve to two maps ,
* m _ paramsById and m _ paramsByIndex .
* A parameter ' s index attribute is its offset in the parameters array which
* is used to determine the parameter ' s value in the EE at runtime .
* Some parameters are generated after we generate VoltXML but before we plan ( constants may
* become parameters in ad hoc queries so their plans may be cached ) . In this case
* the index of the parameter is already set . Otherwise , the parameter ' s index will have been
* set in HSQL .
* @ param paramsNode */
protected void parseParameters ( VoltXMLElement root ) { } } | VoltXMLElement paramsNode = null ; for ( VoltXMLElement node : root . children ) { if ( node . name . equalsIgnoreCase ( "parameters" ) ) { paramsNode = node ; break ; } } if ( paramsNode == null ) { return ; } for ( VoltXMLElement node : paramsNode . children ) { if ( node . name . equalsIgnoreCase ( "parameter" ) ) { long id = Long . parseLong ( node . attributes . get ( "id" ) ) ; String typeName = node . attributes . get ( "valuetype" ) ; String isVectorParam = node . attributes . get ( "isvector" ) ; // Get the index for this parameter in the EE ' s parameter vector
String indexAttr = node . attributes . get ( "index" ) ; assert ( indexAttr != null ) ; int index = Integer . parseInt ( indexAttr ) ; VoltType type = VoltType . typeFromString ( typeName ) ; ParameterValueExpression pve = new ParameterValueExpression ( ) ; pve . setParameterIndex ( index ) ; pve . setValueType ( type ) ; if ( isVectorParam != null && isVectorParam . equalsIgnoreCase ( "true" ) ) { pve . setParamIsVector ( ) ; } m_paramsById . put ( id , pve ) ; getParamsByIndex ( ) . put ( index , pve ) ; } } |
public class AnnotationInstanceProvider { /** * Returns an instance of the given annotation type with attribute values specified in the map .
* < ul >
* < li >
* For { @ link Annotation } , array and enum types the values must exactly match the declared return type of the attribute or a
* { @ link ClassCastException } will result . < / li >
* < li >
* For character types the the value must be an instance of { @ link Character } or { @ link String } . < / li >
* < li >
* Numeric types do not have to match exactly , as they are converted using { @ link Number } . < / li >
* < / ul >
* If am member does not have a corresponding entry in the value map then the annotations default value will be used .
* If the annotation member does not have a default value then a NullMemberException will be thrown
* @ param annotationType the type of the annotation instance to generate
* @ param values the attribute values of this annotation */
public static < T extends Annotation > T get ( Class < T > annotationType , Map < String , ? > values ) { } } | if ( annotationType == null ) { throw new IllegalArgumentException ( "Must specify an annotation" ) ; } Class < ? > clazz = Proxy . getProxyClass ( annotationType . getClassLoader ( ) , annotationType , Serializable . class ) ; AnnotationInvocationHandler handler = new AnnotationInvocationHandler ( values , annotationType ) ; // create a new instance by obtaining the constructor via relection
try { return annotationType . cast ( clazz . getConstructor ( new Class [ ] { InvocationHandler . class } ) . newInstance ( new Object [ ] { handler } ) ) ; } catch ( IllegalArgumentException e ) { throw new IllegalStateException ( "Error instantiating proxy for annotation. Annotation type: " + annotationType , e ) ; } catch ( InstantiationException e ) { throw new IllegalStateException ( "Error instantiating proxy for annotation. Annotation type: " + annotationType , e ) ; } catch ( IllegalAccessException e ) { throw new IllegalStateException ( "Error instantiating proxy for annotation. Annotation type: " + annotationType , e ) ; } catch ( InvocationTargetException e ) { throw new IllegalStateException ( "Error instantiating proxy for annotation. Annotation type: " + annotationType , e . getCause ( ) ) ; } catch ( SecurityException e ) { throw new IllegalStateException ( "Error accessing proxy constructor for annotation. Annotation type: " + annotationType , e ) ; } catch ( NoSuchMethodException e ) { throw new IllegalStateException ( "Error accessing proxy constructor for annotation. Annotation type: " + annotationType , e ) ; } |
public class NodeUtils { /** * Get the output setting for this node , or if this node has no document ( or parent ) , retrieve the default output
* settings */
static Document . OutputSettings outputSettings ( Node node ) { } } | Document owner = node . ownerDocument ( ) ; return owner != null ? owner . outputSettings ( ) : ( new Document ( "" ) ) . outputSettings ( ) ; |
public class InMemoryBulkheadRegistry { /** * { @ inheritDoc } */
@ Override public Bulkhead bulkhead ( String name , String configName ) { } } | return computeIfAbsent ( name , ( ) -> Bulkhead . of ( name , getConfiguration ( configName ) . orElseThrow ( ( ) -> new ConfigurationNotFoundException ( configName ) ) ) ) ; |
public class FilterUtil { /** * Find the first " label - like " column ( matching { @ link TypeUtil # GUESSED _ LABEL }
* ) in a bundle .
* @ param bundle Bundle
* @ return Column number , or { @ code - 1 } . */
public static int findLabelColumn ( MultipleObjectsBundle bundle ) { } } | for ( int i = 0 ; i < bundle . metaLength ( ) ; i ++ ) { if ( TypeUtil . GUESSED_LABEL . isAssignableFromType ( bundle . meta ( i ) ) ) { return i ; } } return - 1 ; |
public class TextUtil { /** * Join the elements of the given array with the given join text .
* The { @ code prefix } and { @ code postfix } values will be put
* just before and just after each element respectively .
* @ param joinText the text to use for joining .
* @ param prefix the text to put as prefix .
* @ param postfix the text to put as postfix .
* @ param elements the parts of text to join .
* @ return the joining text */
@ Pure public static String join ( String joinText , String prefix , String postfix , Iterable < ? > elements ) { } } | final StringBuilder buffer = new StringBuilder ( ) ; String txt ; for ( final Object e : elements ) { if ( e != null ) { txt = e . toString ( ) ; if ( txt != null && txt . length ( ) > 0 ) { if ( buffer . length ( ) > 0 ) { buffer . append ( joinText ) ; } if ( prefix != null ) { buffer . append ( prefix ) ; } buffer . append ( txt ) ; if ( postfix != null ) { buffer . append ( postfix ) ; } } } } return buffer . toString ( ) ; |
public class ElasticPoolActivitiesInner { /** * Returns elastic pool activities .
* @ param resourceGroupName The name of the resource group that contains the resource . You can obtain this value from the Azure Resource Manager API or the portal .
* @ param serverName The name of the server .
* @ param elasticPoolName The name of the elastic pool for which to get the current activity .
* @ param serviceCallback the async ServiceCallback to handle successful and failed responses .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the { @ link ServiceFuture } object */
public ServiceFuture < List < ElasticPoolActivityInner > > listByElasticPoolAsync ( String resourceGroupName , String serverName , String elasticPoolName , final ServiceCallback < List < ElasticPoolActivityInner > > serviceCallback ) { } } | return ServiceFuture . fromResponse ( listByElasticPoolWithServiceResponseAsync ( resourceGroupName , serverName , elasticPoolName ) , serviceCallback ) ; |
public class MapPrinter { /** * Start a print .
* @ param jobId the job ID
* @ param specJson the client json request .
* @ param out the stream to write to . */
public final Processor . ExecutionContext print ( final String jobId , final PJsonObject specJson , final OutputStream out ) throws Exception { } } | final OutputFormat format = getOutputFormat ( specJson ) ; final File taskDirectory = this . workingDirectories . getTaskDirectory ( ) ; try { return format . print ( jobId , specJson , getConfiguration ( ) , this . configFile . getParentFile ( ) , taskDirectory , out ) ; } finally { this . workingDirectories . removeDirectory ( taskDirectory ) ; } |
public class Log { /** * / * TRACE */
public static void trace ( String msg ) { } } | log ( null , LEVEL_TRACE , msg , null , null , null , null , null , null , null , null , null , null , null , null , null , null , 0 ) ; |
public class SlotHash { /** * Partition keys by slot - hash . The resulting map honors order of the keys .
* @ param codec codec to encode the key
* @ param keys iterable of keys
* @ param < K > Key type .
* @ param < V > Value type .
* @ result map between slot - hash and an ordered list of keys . */
static < K , V > Map < Integer , List < K > > partition ( RedisCodec < K , V > codec , Iterable < K > keys ) { } } | Map < Integer , List < K > > partitioned = new HashMap < > ( ) ; for ( K key : keys ) { int slot = getSlot ( codec . encodeKey ( key ) ) ; if ( ! partitioned . containsKey ( slot ) ) { partitioned . put ( slot , new ArrayList < > ( ) ) ; } Collection < K > list = partitioned . get ( slot ) ; list . add ( key ) ; } return partitioned ; |
public class IfcConstraintImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
@ SuppressWarnings ( "unchecked" ) public EList < IfcConstraintClassificationRelationship > getClassifiedAs ( ) { } } | return ( EList < IfcConstraintClassificationRelationship > ) eGet ( Ifc2x3tc1Package . Literals . IFC_CONSTRAINT__CLASSIFIED_AS , true ) ; |
public class MatrixMultProduct_DDRM { /** * Computes the inner product of A times A and stores the results in B . The inner product is symmetric and this
* function will only store the lower triangle . The value of the upper triangular matrix is undefined .
* < p > B = A < sup > T < / sup > * A < / sup >
* @ param A ( Input ) Matrix
* @ param B ( Output ) Storage for output . */
public static void inner_reorder_lower ( DMatrix1Row A , DMatrix1Row B ) { } } | final int cols = A . numCols ; B . reshape ( cols , cols ) ; Arrays . fill ( B . data , 0 ) ; for ( int i = 0 ; i < cols ; i ++ ) { for ( int j = 0 ; j <= i ; j ++ ) { B . data [ i * cols + j ] += A . data [ i ] * A . data [ j ] ; } for ( int k = 1 ; k < A . numRows ; k ++ ) { int indexRow = k * cols ; double valI = A . data [ i + indexRow ] ; int indexB = i * cols ; for ( int j = 0 ; j <= i ; j ++ ) { B . data [ indexB ++ ] += valI * A . data [ indexRow ++ ] ; } } } |
public class BaseClassFinderService { /** * TODO - There must be a way to get the class loader ? ? ? ? */
private ResourceBundle getResourceBundleFromBundle ( Object resource , String baseName , Locale locale , String versionRange ) { } } | ResourceBundle resourceBundle = null ; if ( resource == null ) { Object classAccess = this . getClassBundleService ( null , baseName , versionRange , null , 0 ) ; if ( classAccess != null ) { if ( ( classAccess != null ) && ( USE_NO_RESOURCE_HACK ) ) { try { URL url = classAccess . getClass ( ) . getClassLoader ( ) . getResource ( baseName ) ; InputStream stream = url . openStream ( ) ; resourceBundle = new PropertyResourceBundle ( stream ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } else { ClassLoader loader = classAccess . getClass ( ) . getClassLoader ( ) ; resourceBundle = ResourceBundle . getBundle ( baseName , locale , loader ) ; } } } else { Bundle bundle = this . findBundle ( resource , bundleContext , ClassFinderActivator . getPackageName ( baseName , true ) , versionRange ) ; if ( USE_NO_RESOURCE_HACK ) { try { // TODO - If I have to do this , then I will have to link up the resourcebundle using the locales .
baseName = baseName . replace ( '.' , File . separatorChar ) + ClassFinderActivator . PROPERTIES ; URL url = bundle . getEntry ( baseName ) ; if ( url != null ) resourceBundle = new PropertyResourceBundle ( url . openStream ( ) ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } else { ClassLoader loader = bundle . getClass ( ) . getClassLoader ( ) ; resourceBundle = ResourceBundle . getBundle ( baseName , locale , loader ) ; } } return resourceBundle ; |
public class PnPLepetitEPnP { /** * Score a solution based on distance between control points . Closer the camera
* control points are from the world control points the better the score . This is
* similar to how optimization score works and not the way recommended in the original
* paper . */
private double score ( double betas [ ] ) { } } | UtilLepetitEPnP . computeCameraControl ( betas , nullPts , solutionPts , numControl ) ; int index = 0 ; double score = 0 ; for ( int i = 0 ; i < numControl ; i ++ ) { Point3D_F64 si = solutionPts . get ( i ) ; Point3D_F64 wi = controlWorldPts . get ( i ) ; for ( int j = i + 1 ; j < numControl ; j ++ , index ++ ) { double ds = si . distance ( solutionPts . get ( j ) ) ; double dw = wi . distance ( controlWorldPts . get ( j ) ) ; score += ( ds - dw ) * ( ds - dw ) ; } } return score ; |
public class CausticUtil { /** * Converts 4 byte color components to a normalized float color .
* @ param r The red component
* @ param b The blue component
* @ param g The green component
* @ param a The alpha component
* @ return The color as a 4 float vector */
public static Vector4f fromIntRGBA ( int r , int g , int b , int a ) { } } | return new Vector4f ( ( r & 0xff ) / 255f , ( g & 0xff ) / 255f , ( b & 0xff ) / 255f , ( a & 0xff ) / 255f ) ; |
public class TypeUtils { /** * Validates that the old field mapping can be replaced with new field mapping
* @ param oldFieldMapping
* @ param newFieldMapping */
public static void validateUpdate ( FieldMapping oldFieldMapping , FieldMapping newFieldMapping ) throws TypeUpdateException { } } | Map < String , AttributeInfo > newFields = newFieldMapping . fields ; for ( AttributeInfo attribute : oldFieldMapping . fields . values ( ) ) { if ( newFields . containsKey ( attribute . name ) ) { AttributeInfo newAttribute = newFields . get ( attribute . name ) ; // If old attribute is also in new definition , only allowed change is multiplicity change from REQUIRED to OPTIONAL
if ( ! newAttribute . equals ( attribute ) ) { if ( attribute . multiplicity == Multiplicity . REQUIRED && newAttribute . multiplicity == Multiplicity . OPTIONAL ) { continue ; } else { throw new TypeUpdateException ( "Attribute " + attribute . name + " can't be updated" ) ; } } } else { // If old attribute is missing in new definition , return false as attributes can ' t be deleted
throw new TypeUpdateException ( "Old Attribute " + attribute . name + " is missing" ) ; } } // Only new attributes
Set < String > newAttributes = new HashSet < > ( ImmutableList . copyOf ( newFields . keySet ( ) ) ) ; newAttributes . removeAll ( oldFieldMapping . fields . keySet ( ) ) ; for ( String attributeName : newAttributes ) { AttributeInfo newAttribute = newFields . get ( attributeName ) ; // New required attribute can ' t be added
if ( newAttribute . multiplicity == Multiplicity . REQUIRED ) { throw new TypeUpdateException ( "Can't add required attribute " + attributeName ) ; } } |
public class FctBnAccEntitiesProcessors { /** * < p > Get sales return good line utility . < / p >
* @ param pAddParam additional param
* @ return sales return good line utility
* @ throws Exception - an exception */
protected final UtlInvLine < RS , SalesReturn , SalesReturnLine , SalesReturnTaxLine , SalesReturnGoodsTaxLine > lazyGetUtlSalRetGdLn ( final Map < String , Object > pAddParam ) throws Exception { } } | UtlInvLine < RS , SalesReturn , SalesReturnLine , SalesReturnTaxLine , SalesReturnGoodsTaxLine > utlInvLn = this . utlSalRetGdLn ; if ( utlInvLn == null ) { utlInvLn = new UtlInvLine < RS , SalesReturn , SalesReturnLine , SalesReturnTaxLine , SalesReturnGoodsTaxLine > ( ) ; utlInvLn . setUtlInvBase ( lazyGetUtlInvBase ( pAddParam ) ) ; utlInvLn . setInvTxMeth ( lazyGetSalRetTxMeth ( pAddParam ) ) ; utlInvLn . setIsMutable ( false ) ; utlInvLn . setNeedMkTxCat ( true ) ; utlInvLn . setLtlCl ( SalesReturnGoodsTaxLine . class ) ; utlInvLn . setDstTxItLnCl ( DestTaxGoodsLn . class ) ; FactoryPersistableBase < SalesReturnGoodsTaxLine > fctLtl = new FactoryPersistableBase < SalesReturnGoodsTaxLine > ( ) ; fctLtl . setObjectClass ( SalesReturnGoodsTaxLine . class ) ; fctLtl . setDatabaseId ( getSrvDatabase ( ) . getIdDatabase ( ) ) ; utlInvLn . setFctLineTxLn ( fctLtl ) ; // assigning fully initialized object :
this . utlSalRetGdLn = utlInvLn ; } return utlInvLn ; |
public class RouteFiltersInner { /** * Creates or updates a route filter in a specified resource group .
* @ param resourceGroupName The name of the resource group .
* @ param routeFilterName The name of the route filter .
* @ param routeFilterParameters Parameters supplied to the create or update route filter operation .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the observable for the request */
public Observable < RouteFilterInner > createOrUpdateAsync ( String resourceGroupName , String routeFilterName , RouteFilterInner routeFilterParameters ) { } } | return createOrUpdateWithServiceResponseAsync ( resourceGroupName , routeFilterName , routeFilterParameters ) . map ( new Func1 < ServiceResponse < RouteFilterInner > , RouteFilterInner > ( ) { @ Override public RouteFilterInner call ( ServiceResponse < RouteFilterInner > response ) { return response . body ( ) ; } } ) ; |
public class UserDataHelper { /** * Reconfigures the messaging .
* @ param etcDir the KARAF _ ETC directory
* @ param msgData the messaging configuration parameters */
public void reconfigureMessaging ( String etcDir , Map < String , String > msgData ) throws IOException { } } | String messagingType = msgData . get ( MessagingConstants . MESSAGING_TYPE_PROPERTY ) ; Logger . getLogger ( getClass ( ) . getName ( ) ) . fine ( "Messaging type for reconfiguration: " + messagingType ) ; if ( ! Utils . isEmptyOrWhitespaces ( etcDir ) && ! Utils . isEmptyOrWhitespaces ( messagingType ) ) { // Write the messaging configuration
File f = new File ( etcDir , "net.roboconf.messaging." + messagingType + ".cfg" ) ; Logger logger = Logger . getLogger ( getClass ( ) . getName ( ) ) ; Properties props = Utils . readPropertiesFileQuietly ( f , logger ) ; props . putAll ( msgData ) ; props . remove ( MessagingConstants . MESSAGING_TYPE_PROPERTY ) ; Utils . writePropertiesFile ( props , f ) ; // Set the messaging type
f = new File ( etcDir , Constants . KARAF_CFG_FILE_AGENT ) ; props = Utils . readPropertiesFileQuietly ( f , Logger . getLogger ( getClass ( ) . getName ( ) ) ) ; if ( messagingType != null ) { props . put ( Constants . MESSAGING_TYPE , messagingType ) ; Utils . writePropertiesFile ( props , f ) ; } } |
public class SocketExtensions { /** * Closes the given client socket .
* @ param clientSocket
* The client socket to close .
* @ return Returns true if the client socket is closed otherwise false . */
public static boolean closeClientSocket ( final Socket clientSocket ) { } } | boolean closed = true ; try { close ( clientSocket ) ; } catch ( final IOException e ) { LOGGER . error ( "IOException occured by trying to close the client socket." , e ) ; closed = false ; } finally { try { close ( clientSocket ) ; } catch ( final IOException e ) { LOGGER . error ( "IOException occured by trying to close the client socket." , e ) ; closed = false ; } } return closed ; |
public class NamespaceSupport { /** * Controls whether namespace declaration attributes are placed
* into the { @ link # NSDECL NSDECL } namespace
* by { @ link # processName processName ( ) } . This may only be
* changed before any contexts have been pushed .
* @ param value the namespace declaration attribute state . A value of true
* enables this feature , a value of false disables it .
* @ since SAX 2.1alpha
* @ exception IllegalStateException when attempting to set this
* after any context has been pushed . */
public void setNamespaceDeclUris ( boolean value ) { } } | if ( contextPos != 0 ) throw new IllegalStateException ( ) ; if ( value == namespaceDeclUris ) return ; namespaceDeclUris = value ; if ( value ) currentContext . declarePrefix ( "xmlns" , NSDECL ) ; else { contexts [ contextPos ] = currentContext = new Context ( ) ; currentContext . declarePrefix ( "xml" , XMLNS ) ; } |
public class NetUtils { /** * Util method to build socket addr from either :
* < host >
* < host > : < post >
* < fs > : / / < host > : < port > / < path > */
public static InetSocketAddress createSocketAddr ( String target , int defaultPort ) { } } | int colonIndex = target . indexOf ( ':' ) ; if ( colonIndex < 0 && defaultPort == - 1 ) { throw new RuntimeException ( "Not a host:port pair: " + target ) ; } String hostname = "" ; int port = - 1 ; if ( ! target . contains ( "/" ) ) { if ( colonIndex == - 1 ) { hostname = target ; } else { // must be the old style < host > : < port >
hostname = target . substring ( 0 , colonIndex ) ; port = Integer . parseInt ( target . substring ( colonIndex + 1 ) ) ; } } else { // a new uri
try { URI addr = new URI ( target ) ; hostname = addr . getHost ( ) ; port = addr . getPort ( ) ; } catch ( URISyntaxException use ) { LOG . fatal ( use ) ; } } if ( port == - 1 ) { port = defaultPort ; } if ( getStaticResolution ( hostname ) != null ) { hostname = getStaticResolution ( hostname ) ; } return new InetSocketAddress ( hostname , port ) ; |
public class LruCache { /** * Puts a new item in the cache if the current value matches oldValue .
* @ param key the key
* @ param value the new value
* @ param testValue the value to test against the current
* @ return true if the put succeeds */
public boolean compareAndPut ( V testValue , K key , V value ) { } } | V result = compareAndPut ( testValue , key , value , true ) ; return testValue == result ; |
public class Dao { /** * Deletes all rows from a table
* @ param table The table to delete
* @ return < b > deferred < / b > Observable with the number of deleted rows */
@ CheckResult protected Observable < Integer > delete ( @ NonNull final String table ) { } } | return delete ( table , null ) ; |
public class CliDispatcher { /** * Returns all commands in alphabetic order
* @ return the list of commands */
public List < String > commands ( boolean sys , boolean app ) { } } | C . List < String > list = C . newList ( ) ; Act . Mode mode = Act . mode ( ) ; boolean all = ! sys && ! app ; for ( String s : registry . keySet ( ) ) { boolean isSysCmd = s . startsWith ( "act." ) ; if ( isSysCmd && ! sys && ! all ) { continue ; } if ( ! isSysCmd && ! app && ! all ) { continue ; } CliHandler h = registry . get ( s ) ; if ( h . appliedIn ( mode ) ) { list . add ( s ) ; } } return list . sorted ( new $ . Comparator < String > ( ) { @ Override public int compare ( String o1 , String o2 ) { boolean b1 = ( o1 . startsWith ( "act." ) ) ; boolean b2 = ( o2 . startsWith ( "act." ) ) ; if ( b1 & ! b2 ) { return - 1 ; } if ( ! b1 & b2 ) { return 1 ; } return o1 . compareTo ( o2 ) ; } } ) ; |
public class CmsAliasErrorColumn { /** * Gets the comparator which should be used for this column . < p >
* @ return the comparator used for this column */
public static Comparator < CmsAliasTableRow > getComparator ( ) { } } | return new Comparator < CmsAliasTableRow > ( ) { public int compare ( CmsAliasTableRow o1 , CmsAliasTableRow o2 ) { String err1 = getValueInternal ( o1 ) ; String err2 = getValueInternal ( o2 ) ; if ( ( err1 == null ) && ( err2 == null ) ) { return 0 ; } if ( err1 == null ) { return - 1 ; } if ( err2 == null ) { return 1 ; } return 0 ; } } ; |
public class JsonAsserterImpl { /** * { @ inheritDoc } */
@ SuppressWarnings ( "unchecked" ) public < T > JsonAsserter assertThat ( String path , Matcher < T > matcher ) { } } | T obj = null ; try { obj = JsonPath . < T > read ( jsonObject , path ) ; } catch ( Exception e ) { final AssertionError assertionError = new AssertionError ( String . format ( "Error reading JSON path [%s]" , path ) ) ; assertionError . initCause ( e ) ; throw assertionError ; } if ( ! matcher . matches ( obj ) ) { throw new AssertionError ( String . format ( "JSON path [%s] doesn't match.\nExpected:\n%s\nActual:\n%s" , path , matcher . toString ( ) , obj ) ) ; } return this ; |
public class RefCapablePropertyResourceBundle { /** * Replaces positional substitution patterns of the form % { \ d } with
* corresponding element of the given subs array .
* Note that % { \ d } numbers are 1 - based , so we lok for subs [ x - 1 ] . */
public String posSubst ( String s , String [ ] subs , int behavior ) { } } | Matcher matcher = posPattern . matcher ( s ) ; int previousEnd = 0 ; StringBuffer sb = new StringBuffer ( ) ; String varValue ; int varIndex ; String condlVal ; // Conditional : value
while ( matcher . find ( ) ) { varIndex = Integer . parseInt ( matcher . group ( 1 ) ) - 1 ; condlVal = ( ( matcher . groupCount ( ) > 1 ) ? matcher . group ( 2 ) : null ) ; varValue = ( ( varIndex < subs . length ) ? subs [ varIndex ] : null ) ; if ( condlVal != null ) { // Replace varValue ( the value to be substituted ) , with
// the post - : + portion of the expression .
varValue = ( ( varValue == null ) ? "" : condlVal . replaceAll ( "\\Q%" + ( varIndex + 1 ) + "\\E\\b" , RefCapablePropertyResourceBundle . literalize ( varValue ) ) ) ; } // System . err . println ( " Behavior : " + behavior ) ;
if ( varValue == null ) switch ( behavior ) { case THROW_BEHAVIOR : throw new RuntimeException ( Integer . toString ( subs . length ) + " positional values given, but property string " + "contains (" + matcher . group ( ) + ")." ) ; case EMPTYSTRING_BEHAVIOR : varValue = "" ; case NOOP_BEHAVIOR : break ; default : throw new RuntimeException ( "Undefined value for behavior: " + behavior ) ; } sb . append ( s . substring ( previousEnd , matcher . start ( ) ) + ( ( varValue == null ) ? matcher . group ( ) : varValue ) ) ; previousEnd = matcher . end ( ) ; } return ( previousEnd < 1 ) ? s : ( sb . toString ( ) + s . substring ( previousEnd ) ) ; |
public class CDKMCS { /** * Removes all redundant solution .
* @ param graphList the list of structure to clean
* @ return the list cleaned
* @ throws org . openscience . cdk . exception . CDKException if there is atom problem in obtaining
* subgraphs */
private static List < IAtomContainer > getMaximum ( ArrayList < IAtomContainer > graphList , boolean shouldMatchBonds ) throws CDKException { } } | List < IAtomContainer > reducedGraphList = ( List < IAtomContainer > ) graphList . clone ( ) ; for ( int i = 0 ; i < graphList . size ( ) ; i ++ ) { IAtomContainer graphI = graphList . get ( i ) ; for ( int j = i + 1 ; j < graphList . size ( ) ; j ++ ) { IAtomContainer graphJ = graphList . get ( j ) ; // Gi included in Gj or Gj included in Gi then
// reduce the irrelevant solution
if ( isSubgraph ( graphJ , graphI , shouldMatchBonds ) ) { reducedGraphList . remove ( graphI ) ; } else if ( isSubgraph ( graphI , graphJ , shouldMatchBonds ) ) { reducedGraphList . remove ( graphJ ) ; } } } return reducedGraphList ; |
public class OuterMsgId { /** * 从httpRequest的Header内摘取出msgId , 处于安全考虑 , 我们只摘取standalone节点传入的msgId < br >
* 如果取不到那么返回null */
public static String get ( FullHttpRequest fullHttpRequest ) { } } | HttpHeaders httpHeaders = fullHttpRequest . headers ( ) ; if ( isNodeLegal ( httpHeaders ) && ! StringUtil . isEmpty ( httpHeaders . get ( Constant . XIAN_MSG_ID_HEADER ) ) ) { return httpHeaders . get ( Constant . XIAN_MSG_ID_HEADER ) ; } return null ; |
public class VTensor { /** * Gets the value of the entry corresponding to the given indices .
* @ param indices The indices of the multi - dimensional array .
* @ return The current value . */
public double get ( int ... indices ) { } } | checkIndices ( indices ) ; int c = getConfigIdx ( indices ) ; return values . get ( c ) ; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.