signature stringlengths 43 39.1k | implementation stringlengths 0 450k |
|---|---|
public class WaveformPreviewComponent { /** * Create an image of the proper size to hold a new waveform preview image and draw it . */
private void updateWaveform ( WaveformPreview preview ) { } } | this . preview . set ( preview ) ; if ( preview == null ) { waveformImage . set ( null ) ; } else { BufferedImage image = new BufferedImage ( preview . segmentCount , preview . maxHeight , BufferedImage . TYPE_INT_RGB ) ; Graphics g = image . getGraphics ( ) ; g . setColor ( Color . BLACK ) ; g . fillRect ( 0 , 0 , preview . segmentCount , preview . maxHeight ) ; for ( int segment = 0 ; segment < preview . segmentCount ; segment ++ ) { g . setColor ( preview . segmentColor ( segment , false ) ) ; g . drawLine ( segment , preview . maxHeight , segment , preview . maxHeight - preview . segmentHeight ( segment , false ) ) ; if ( preview . isColor ) { // We have a front color segment to draw on top .
g . setColor ( preview . segmentColor ( segment , true ) ) ; g . drawLine ( segment , preview . maxHeight , segment , preview . maxHeight - preview . segmentHeight ( segment , true ) ) ; } } waveformImage . set ( image ) ; } |
public class HalMediaTypeConfiguration { /** * ( non - Javadoc )
* @ see org . springframework . hateoas . config . HypermediaMappingInformation # configureObjectMapper ( com . fasterxml . jackson . databind . ObjectMapper ) */
@ Override public ObjectMapper configureObjectMapper ( ObjectMapper mapper ) { } } | mapper . disable ( DeserializationFeature . FAIL_ON_UNKNOWN_PROPERTIES ) ; mapper . registerModule ( new Jackson2HalModule ( ) ) ; mapper . setHandlerInstantiator ( new Jackson2HalModule . HalHandlerInstantiator ( relProvider , curieProvider . getIfAvailable ( ( ) -> CurieProvider . NONE ) , messageSourceAccessor , halConfiguration . getIfAvailable ( HalConfiguration :: new ) ) ) ; return mapper ; |
public class DbXmlPolicyIndex { /** * ( non - Javadoc )
* @ see
* org . fcrepo . server . security . xacml . pdp . data . PolicyDataManager # addPolicy
* ( java . lang . String , java . lang . String ) */
@ Override public String addPolicy ( String name , String document ) throws PolicyIndexException { } } | String docName = null ; DbXmlManager . writeLock . lock ( ) ; try { XmlDocument doc = makeDocument ( name , document ) ; docName = doc . getName ( ) ; log . debug ( "Adding document: " + docName ) ; m_dbXmlManager . container . putDocument ( doc , m_dbXmlManager . updateContext ) ; setLastUpdate ( System . currentTimeMillis ( ) ) ; } catch ( XmlException xe ) { if ( xe . getErrorCode ( ) == XmlException . UNIQUE_ERROR ) { throw new PolicyIndexException ( "Document already exists: " + docName ) ; } else { throw new PolicyIndexException ( "Error adding policy: " + xe . getMessage ( ) , xe ) ; } } finally { DbXmlManager . writeLock . unlock ( ) ; } return docName ; |
public class Futures { /** * Registers an exception listener to the given CompletableFuture for a particular type of exception .
* @ param completableFuture The Future to register to .
* @ param exceptionClass The type of exception to listen to .
* @ param exceptionListener The Listener to register .
* @ param < T > The Type of the future ' s result .
* @ param < E > The Type of the exception . */
@ SuppressWarnings ( "unchecked" ) public static < T , E extends Throwable > void exceptionListener ( CompletableFuture < T > completableFuture , Class < E > exceptionClass , Consumer < E > exceptionListener ) { } } | completableFuture . whenComplete ( ( r , ex ) -> { if ( ex != null && exceptionClass . isAssignableFrom ( ex . getClass ( ) ) ) { Callbacks . invokeSafely ( exceptionListener , ( E ) ex , null ) ; } } ) ; |
public class BaseMojo { /** * Add any relevant project dependencies to the classpath . Takes
* includeProjectDependencies into consideration . */
@ SuppressWarnings ( "unchecked" ) protected void addRelevantProjectDependencies ( Set < Artifact > artifacts ) throws Exception { } } | getLog ( ) . debug ( "Project Dependencies will be included." ) ; Set < Artifact > dependencies = project . getArtifacts ( ) ; getLog ( ) . debug ( "There are " + dependencies . size ( ) + " dependencies in the project" ) ; // system scope dependencies are not returned by maven 2.0 . See MEXEC - 17
dependencies . addAll ( getAllNonTestOrProvidedScopedDependencies ( ) ) ; Iterator < Artifact > iter = dependencies . iterator ( ) ; while ( iter . hasNext ( ) ) { Artifact classPathElement = iter . next ( ) ; getLog ( ) . debug ( "Adding project dependency artifact: " + classPathElement . getArtifactId ( ) + " to classpath" ) ; artifacts . add ( classPathElement ) ; } |
public class MagicFormatter { /** * Formats the extracted value assigned and returns the associated string */
public void format ( StringBuilder sb , Object value ) { } } | if ( prefix != null ) { sb . append ( prefix ) ; } if ( percentExpression != null && value != null ) { percentExpression . append ( value , sb ) ; } if ( suffix != null ) { sb . append ( suffix ) ; } |
public class HTTPRequest { /** * Retry .
* @ param maxRetries Maximum number of retries
* @ param retryable Function to determine if call should be retried
* @ param waitStrategy Function to calculate the time to wait between two retries
* @ return this */
public HTTPRequest retry ( final int maxRetries , final Retryable retryable , final WaitStrategy waitStrategy ) { } } | if ( maxRetries <= 0 ) { throw new IllegalArgumentException ( "maxRetries must be > 0" ) ; } if ( retryable == null ) { throw new IllegalArgumentException ( "retryable must not be null" ) ; } if ( waitStrategy == null ) { throw new IllegalArgumentException ( "waitStrategy must not be null" ) ; } this . maxRetries = maxRetries ; this . retryable = retryable ; this . waitStrategy = waitStrategy ; return this ; |
public class Cache { /** * 为哈希表 key 中的域 field 加上浮点数增量 increment 。
* 如果哈希表中没有域 field , 那么 HINCRBYFLOAT 会先将域 field 的值设为 0 , 然后再执行加法操作 。
* 如果键 key 不存在 , 那么 HINCRBYFLOAT 会先创建一个哈希表 , 再创建域 field , 最后再执行加法操作 。
* 当以下任意一个条件发生时 , 返回一个错误 :
* 1 : 域 field 的值不是字符串类型 ( 因为 redis 中的数字和浮点数都以字符串的形式保存 , 所以它们都属于字符串类型 )
* 2 : 域 field 当前的值或给定的增量 increment 不能解释 ( parse ) 为双精度浮点数 ( double precision floating point number )
* HINCRBYFLOAT 命令的详细功能和 INCRBYFLOAT 命令类似 , 请查看 INCRBYFLOAT 命令获取更多相关信息 。 */
public Double hincrByFloat ( Object key , Object field , double value ) { } } | Jedis jedis = getJedis ( ) ; try { return jedis . hincrByFloat ( keyToBytes ( key ) , fieldToBytes ( field ) , value ) ; } finally { close ( jedis ) ; } |
public class ConfFileUtils { /** * Return URL for given filename
* @ param fileName
* @ return
* URL */
public static URL getURLForFile ( String fileName ) { } } | URL url = null ; if ( fileName != null ) { File file = new File ( fileName ) ; if ( file != null && file . exists ( ) ) { try { url = file . toURL ( ) ; } catch ( MalformedURLException e ) { throw new IllegalArgumentException ( "file.toURL() failed for '" + file + "'" ) ; } } } return url ; |
public class ServiceAdmin { @ GET @ Path ( "user" ) @ Produces ( MediaType . APPLICATION_JSON ) @ HttpCache public List < RUserDto > getUsers ( ) { } } | DbConn cnx = null ; try { cnx = Helpers . getDbSession ( ) ; return MetaService . getUsers ( cnx ) ; } finally { Helpers . closeQuietly ( cnx ) ; } |
public class AbstractHttpMessageConverter { /** * This implementation delegates to { @ link # getDefaultContentType ( Object ) } if a content
* type was not provided , calls { @ link # getContentLength } , and sets the corresponding headers
* on the output message . It then calls { @ link # writeInternal } . */
public final void write ( T t , MediaType contentType , HttpOutputMessage outputMessage ) throws IOException , HttpMessageNotWritableException { } } | HttpHeaders headers = outputMessage . getHeaders ( ) ; if ( headers . getContentType ( ) == null ) { MediaType contentTypeToUse = contentType ; if ( contentType == null || contentType . isWildcardType ( ) || contentType . isWildcardSubtype ( ) ) { contentTypeToUse = getDefaultContentType ( t ) ; } if ( contentTypeToUse != null ) { headers . setContentType ( contentTypeToUse ) ; } } if ( headers . getContentLength ( ) == - 1 ) { Long contentLength = getContentLength ( t , headers . getContentType ( ) ) ; if ( contentLength != null ) { headers . setContentLength ( contentLength ) ; } } writeInternal ( t , outputMessage ) ; outputMessage . getBody ( ) . flush ( ) ; |
public class AppStateVM { /** * Notify from Modules about contacts state changed
* @ param isEmpty is contacts empty */
public synchronized void onContactsChanged ( boolean isEmpty ) { } } | if ( isContactsEmpty . get ( ) != isEmpty ) { context . getPreferences ( ) . putBool ( "app.contacts.empty" , isEmpty ) ; isContactsEmpty . change ( isEmpty ) ; } if ( ! isEmpty ) { if ( isAppEmpty . get ( ) ) { context . getPreferences ( ) . putBool ( "app.empty" , false ) ; isAppEmpty . change ( false ) ; } } |
public class AuthConfig { private String createAuthEncoded ( ) { } } | JsonObject ret = new JsonObject ( ) ; putNonNull ( ret , "username" , username ) ; putNonNull ( ret , "password" , password ) ; putNonNull ( ret , "email" , email ) ; putNonNull ( ret , "auth" , auth ) ; try { return encodeBase64ChunkedURLSafeString ( ret . toString ( ) . getBytes ( "UTF-8" ) ) ; } catch ( UnsupportedEncodingException e ) { return encodeBase64ChunkedURLSafeString ( ret . toString ( ) . getBytes ( ) ) ; } |
public class Frontend { /** * just a helper method for all frontends . Is it at the right place here ? */
public static boolean loginAtStart ( ) { } } | boolean loginAtStart = Application . getInstance ( ) . isLoginRequired ( ) || Configuration . get ( "MjLoginAtStart" , "false" ) . equals ( "true" ) ; if ( loginAtStart && ! Backend . getInstance ( ) . isAuthenticationActive ( ) ) { throw new IllegalStateException ( "Login required but authorization is not configured!" ) ; } return loginAtStart ; |
public class InMemoryValueInspector { /** * { @ inheritDoc } .
* If present in the cache , return the cached { @ link com . typesafe . config . Config } for given input
* Otherwise , simply delegate the functionality to the internal { ConfigStoreValueInspector } and store the value into cache */
@ Override public Map < ConfigKeyPath , Config > getOwnConfigs ( Collection < ConfigKeyPath > configKeys ) { } } | Collection < ConfigKeyPath > configKeysNotInCache = new ArrayList < > ( ) ; Map < ConfigKeyPath , Config > result = new HashMap < > ( ) ; for ( ConfigKeyPath configKey : configKeys ) { Config cachedValue = this . ownConfigCache . getIfPresent ( configKey ) ; if ( cachedValue == null ) { configKeysNotInCache . add ( configKey ) ; } else { result . put ( configKey , cachedValue ) ; } } // for ConfigKeyPath which are not in cache
if ( configKeysNotInCache . size ( ) > 0 ) { Map < ConfigKeyPath , Config > configsFromFallBack = this . valueFallback . getOwnConfigs ( configKeysNotInCache ) ; this . ownConfigCache . putAll ( configsFromFallBack ) ; result . putAll ( configsFromFallBack ) ; } return result ; |
public class AbstractDataBinder { /** * Notifies all listeners , that the data binder is showing data , which has been loaded either
* asynchronously or from cache .
* @ param key
* The key of the data , which has be loaded , as an instance of the generic type KeyType .
* The key may not be null
* @ param data
* The data , which has been loaded , as an instance of the generic type DataType or null ,
* if no data has been loaded
* @ param view
* The view , which is used to display the data , as an instance of the generic type
* ViewType . The view may not be null
* @ param params
* An array , which contains optional parameters , as an array of the type ParamType or an
* empty array , if no parameters should be used */
@ SafeVarargs private final void notifyOnFinished ( @ NonNull final KeyType key , @ Nullable final DataType data , @ NonNull final ViewType view , @ NonNull final ParamType ... params ) { } } | for ( Listener < DataType , KeyType , ViewType , ParamType > listener : listeners ) { listener . onFinished ( this , key , data , view , params ) ; } |
public class JavaSmsApi { /** * 通过模板发送短信 ( 不推荐 )
* @ param apikey apikey
* @ param tpl _ id 模板id
* @ param tpl _ value 模板变量值
* @ param mobile 接受的手机号
* @ return json格式字符串 */
public static Single < String > tplSendSms ( String apikey , long tpl_id , String tpl_value , String mobile ) { } } | Map < String , String > params = new HashMap < > ( ) ; params . put ( "apikey" , apikey ) ; params . put ( "tpl_id" , String . valueOf ( tpl_id ) ) ; params . put ( "tpl_value" , tpl_value ) ; params . put ( "mobile" , mobile ) ; return post ( URI_TPL_SEND_SMS , params ) ; |
public class DataEncryption { /** * Encrypts the specified plainText using AES - 256 . This method uses the default secret key .
* @ param plainText the text to encrypt
* @ return the encrypted bytes
* @ throws Exception a number of exceptions may be thrown
* @ since 1.3.0 */
public static byte [ ] encryptAsBytes ( final String plainText ) throws Exception { } } | final SecretKey secretKey = KeyManager . getInstance ( ) . getSecretKey ( ) ; return encryptAsBytes ( secretKey , plainText ) ; |
public class Flowables { /** * Returns a cached { @ link Flowable } like { @ link Flowable # cache ( ) } except that
* the cache can be reset by calling { @ link CachedFlowable # reset ( ) } .
* @ param source
* the observable to be cached .
* @ param < T >
* the generic type of the source
* @ return a cached observable whose cache can be reset . */
public static < T > CachedFlowable < T > cache ( Flowable < T > source ) { } } | return new CachedFlowable < T > ( source ) ; |
public class EventBus { /** * Overload { @ link # emit ( EventObject , Object . . . ) } for performance tuning .
* @ see # emit ( EventObject , Object . . . ) */
public EventBus emit ( ActEvent event , Object ... args ) { } } | return _emitWithOnceBus ( eventContext ( event , args ) ) ; |
public class ListValue { /** * ( non - Javadoc )
* @ see java . util . List # addAll ( int , java . util . Collection ) */
@ Override public boolean addAll ( final int index , final Collection < ? extends V > c ) { } } | return this . list . addAll ( index , c ) ; |
public class Captions { /** * Source files for the input sidecar captions used during the transcoding process . To omit all sidecar captions ,
* leave < code > CaptionSources < / code > blank .
* @ param captionSources
* Source files for the input sidecar captions used during the transcoding process . To omit all sidecar
* captions , leave < code > CaptionSources < / code > blank .
* @ return Returns a reference to this object so that method calls can be chained together . */
@ Deprecated public Captions withCaptionSources ( java . util . Collection < CaptionSource > captionSources ) { } } | setCaptionSources ( captionSources ) ; return this ; |
public class Matrix4d { /** * Set the value of the matrix element at column 2 and row 1.
* @ param m21
* the new value
* @ return this */
public Matrix4d m21 ( double m21 ) { } } | this . m21 = m21 ; properties &= ~ PROPERTY_ORTHONORMAL ; if ( m21 != 0.0 ) properties &= ~ ( PROPERTY_IDENTITY | PROPERTY_PERSPECTIVE | PROPERTY_TRANSLATION ) ; return this ; |
public class DateTimeUtils { /** * Because the date passed as argument can be in java format , and because not all formats are compatible
* with joda - time , this method checks if the date string is valid with java . In this way we can use the
* proper DateTime without changing the output .
* @ param date date passed as argument
* @ return true if is a java date */
public static boolean isDateValid ( String date , Locale locale ) { } } | try { DateFormat format = DateFormat . getDateTimeInstance ( DateFormat . DEFAULT , DateFormat . DEFAULT , locale ) ; format . parse ( date ) ; return true ; } catch ( ParseException e ) { return false ; } |
public class MapBuilder { /** * Adds the map value to the provided map under the provided field name , if it should be
* included . The supplier is only invoked if the field is to be included . */
public MapBuilder addMap ( String fieldName , boolean include , Supplier < Map < String , ? > > supplier ) { } } | if ( include ) { Map < String , ? > value = supplier . get ( ) ; if ( value != null && ! value . isEmpty ( ) ) { map . put ( getFieldName ( fieldName ) , value ) ; } } return this ; |
public class CopyHelper { /** * Check if an object is copyable using the { @ link # copy ( Object ) } method .
* @ param thing : the object that needs to be copied
* @ return : true if { @ link CopyHelper } can copy this thing , false otherwise */
public static boolean isCopyable ( Object thing ) { } } | if ( ( thing instanceof Copyable ) || ( thing instanceof byte [ ] ) || ( isImmutableType ( thing ) ) ) { return true ; } return false ; |
public class CmsDriverManager { /** * Add a new group to the Cms . < p >
* Only the admin can do this .
* Only users , which are in the group " administrators " are granted . < p >
* @ param dbc the current database context
* @ param id the id of the new group
* @ param name the name of the new group
* @ param description the description for the new group
* @ param flags the flags for the new group
* @ param parent the name of the parent group ( or < code > null < / code > )
* @ return new created group
* @ throws CmsException if the creation of the group failed
* @ throws CmsIllegalArgumentException if the length of the given name was below 1 */
public CmsGroup createGroup ( CmsDbContext dbc , CmsUUID id , String name , String description , int flags , String parent ) throws CmsIllegalArgumentException , CmsException { } } | // check the group name
OpenCms . getValidationHandler ( ) . checkGroupName ( CmsOrganizationalUnit . getSimpleName ( name ) ) ; // trim the name
name = name . trim ( ) ; // check the OU
readOrganizationalUnit ( dbc , CmsOrganizationalUnit . getParentFqn ( name ) ) ; // get the id of the parent group if necessary
if ( CmsStringUtil . isNotEmpty ( parent ) ) { CmsGroup parentGroup = readGroup ( dbc , parent ) ; if ( ! parentGroup . isRole ( ) && ! CmsOrganizationalUnit . getParentFqn ( parent ) . equals ( CmsOrganizationalUnit . getParentFqn ( name ) ) ) { throw new CmsDataAccessException ( Messages . get ( ) . container ( Messages . ERR_PARENT_GROUP_MUST_BE_IN_SAME_OU_3 , CmsOrganizationalUnit . getSimpleName ( name ) , CmsOrganizationalUnit . getParentFqn ( name ) , parent ) ) ; } } // create the group
CmsGroup group = getUserDriver ( dbc ) . createGroup ( dbc , id , name , description , flags , parent ) ; // if the group is in fact a role , initialize it
if ( group . isVirtual ( ) ) { // get all users that have the given role
String groupname = CmsRole . valueOf ( group ) . getGroupName ( ) ; Iterator < CmsUser > it = getUsersOfGroup ( dbc , groupname , true , false , true ) . iterator ( ) ; while ( it . hasNext ( ) ) { CmsUser user = it . next ( ) ; // put them in the new group
addUserToGroup ( dbc , user . getName ( ) , group . getName ( ) , true ) ; } } // put it into the cache
m_monitor . cacheGroup ( group ) ; if ( ! dbc . getProjectId ( ) . isNullUUID ( ) ) { // group modified event is not needed
return group ; } // fire group modified event
Map < String , Object > eventData = new HashMap < String , Object > ( ) ; eventData . put ( I_CmsEventListener . KEY_GROUP_NAME , group . getName ( ) ) ; eventData . put ( I_CmsEventListener . KEY_GROUP_ID , group . getId ( ) . toString ( ) ) ; eventData . put ( I_CmsEventListener . KEY_USER_ACTION , I_CmsEventListener . VALUE_GROUP_MODIFIED_ACTION_CREATE ) ; OpenCms . fireCmsEvent ( new CmsEvent ( I_CmsEventListener . EVENT_GROUP_MODIFIED , eventData ) ) ; // return it
return group ; |
public class LocaleData { /** * Gets the LocaleData object associated with the ULocale specified in locale
* @ param locale Locale with thich the locale data object is associated .
* @ return A locale data object . */
public static final LocaleData getInstance ( ULocale locale ) { } } | LocaleData ld = new LocaleData ( ) ; ld . bundle = ( ICUResourceBundle ) UResourceBundle . getBundleInstance ( ICUData . ICU_BASE_NAME , locale ) ; ld . langBundle = ( ICUResourceBundle ) UResourceBundle . getBundleInstance ( ICUData . ICU_LANG_BASE_NAME , locale ) ; ld . noSubstitute = false ; return ld ; |
public class QueryHelper { /** * 获得请求中的页码 */
public static int getPageIndex ( ) { } } | String pageIndex = Params . get ( PAGENO ) ; int resultno = 1 ; if ( Strings . isNotBlank ( pageIndex ) ) resultno = Numbers . toInt ( pageIndex . trim ( ) ) ; if ( resultno < 1 ) resultno = Page . DEFAULT_PAGE_NUM ; return resultno ; |
public class FeaturesParser { /** * Get the features collection from a GeoJson URL .
* @ param template the template
* @ param geoJsonUrl what to parse
* @ return the feature collection */
public final SimpleFeatureCollection treatStringAsURL ( final Template template , final String geoJsonUrl ) throws IOException { } } | URL url ; try { url = FileUtils . testForLegalFileUrl ( template . getConfiguration ( ) , new URL ( geoJsonUrl ) ) ; } catch ( MalformedURLException e ) { return null ; } final String geojsonString ; if ( url . getProtocol ( ) . equalsIgnoreCase ( "file" ) ) { geojsonString = IOUtils . toString ( url , Constants . DEFAULT_CHARSET . name ( ) ) ; } else { geojsonString = URIUtils . toString ( this . httpRequestFactory , url ) ; } return treatStringAsGeoJson ( geojsonString ) ; |
public class DeleteOperationServiceImpl { /** * Deletes from an XML ( provided as String or file ) the element / attribute / value of element at a given XPath .
* @ param inputs inputs
* @ return a String representation of the modified XML
* @ throws Exception in case something goes wrong */
@ Override public String execute ( EditXmlInputs inputs ) throws Exception { } } | Document doc = XmlUtils . createDocument ( inputs . getXml ( ) , inputs . getFilePath ( ) , inputs . getParsingFeatures ( ) ) ; NodeList nodeList = XmlUtils . readNode ( doc , inputs . getXpath1 ( ) , XmlUtils . getNamespaceContext ( inputs . getXml ( ) , inputs . getFilePath ( ) ) ) ; Node node ; Node parentNode ; for ( int i = 0 ; i < nodeList . getLength ( ) ; i ++ ) { node = nodeList . item ( i ) ; if ( Constants . Inputs . TYPE_ELEM . equals ( inputs . getType ( ) ) && node != doc . getDocumentElement ( ) ) { // check if provided xpath doesn ' t contain root node
parentNode = node . getParentNode ( ) ; parentNode . removeChild ( node ) ; } else if ( Constants . Inputs . TYPE_TEXT . equals ( inputs . getType ( ) ) ) { node . setTextContent ( Constants . Inputs . EMPTY_STRING ) ; } else if ( Constants . Inputs . TYPE_ATTR . equals ( inputs . getType ( ) ) ) { ( ( Element ) node ) . removeAttribute ( inputs . getName ( ) ) ; } } return DocumentUtils . documentToString ( doc ) ; |
public class Dim { /** * Converts the given script object to a string . */
public String objectToString ( Object object ) { } } | DimIProxy action = new DimIProxy ( this , IPROXY_OBJECT_TO_STRING ) ; action . object = object ; action . withContext ( ) ; return action . stringResult ; |
public class MsgpackIOUtil { /** * Merges the { @ code message } from the { @ link MessageBufferInput } using the given { @ code schema } . */
public static < T > void mergeFrom ( MessageBufferInput in , T message , Schema < T > schema , boolean numeric ) throws IOException { } } | MessageUnpacker unpacker = MessagePack . newDefaultUnpacker ( in ) ; try { mergeFrom ( unpacker , message , schema , numeric ) ; } finally { unpacker . close ( ) ; } |
public class RAWrapperEECImpl { /** * Overrides the default serialization . */
private void writeObject ( ObjectOutputStream s ) throws IOException { } } | ObjectOutputStream . PutField putField = s . putFields ( ) ; putField . put ( "version" , version ) ; putField . put ( "resourceAdapterKey" , resourceAdapterKey ) ; s . writeFields ( ) ; |
public class DBAdapter { /** * Marks inbox message as read for given messageId
* @ param messageId String messageId
* @ return boolean value depending on success of operation */
synchronized boolean markReadMessageForId ( String messageId , String userId ) { } } | if ( messageId == null || userId == null ) return false ; final String tName = Table . INBOX_MESSAGES . getName ( ) ; try { final SQLiteDatabase db = dbHelper . getWritableDatabase ( ) ; ContentValues cv = new ContentValues ( ) ; cv . put ( IS_READ , 1 ) ; db . update ( Table . INBOX_MESSAGES . getName ( ) , cv , _ID + " = ? AND " + USER_ID + " = ?" , new String [ ] { messageId , userId } ) ; return true ; } catch ( final SQLiteException e ) { getConfigLogger ( ) . verbose ( "Error removing stale records from " + tName , e ) ; return false ; } finally { dbHelper . close ( ) ; } |
public class TIFFLZWDecoder { /** * Append < code > newString < / code > to the end of < code > oldString < / code > . */
public byte [ ] composeString ( byte oldString [ ] , byte newString ) { } } | int length = oldString . length ; byte string [ ] = new byte [ length + 1 ] ; System . arraycopy ( oldString , 0 , string , 0 , length ) ; string [ length ] = newString ; return string ; |
public class QrCodeAlignmentPatternLocator { /** * Localizizes the alignment pattern crudely by searching for the black box in the center by looking
* for its edges in the gray scale image
* @ return true if success or false if it doesn ' t resemble an alignment pattern */
boolean localize ( QrCode . Alignment pattern , float guessY , float guessX ) { } } | // sample along the middle . Try to not sample the outside edges which could confuse it
for ( int i = 0 ; i < arrayY . length ; i ++ ) { float x = guessX - 1.5f + i * 3f / 12.0f ; float y = guessY - 1.5f + i * 3f / 12.0f ; arrayX [ i ] = reader . read ( guessY , x ) ; arrayY [ i ] = reader . read ( y , guessX ) ; } // TODO turn this into an exhaustive search of the array for best up and down point ?
int downX = greatestDown ( arrayX ) ; if ( downX == - 1 ) return false ; int upX = greatestUp ( arrayX , downX ) ; if ( upX == - 1 ) return false ; int downY = greatestDown ( arrayY ) ; if ( downY == - 1 ) return false ; int upY = greatestUp ( arrayY , downY ) ; if ( upY == - 1 ) return false ; pattern . moduleFound . x = guessX - 1.5f + ( downX + upX ) * 3f / 24.0f ; pattern . moduleFound . y = guessY - 1.5f + ( downY + upY ) * 3f / 24.0f ; reader . gridToImage ( ( float ) pattern . moduleFound . y , ( float ) pattern . moduleFound . x , pattern . pixel ) ; return true ; |
public class X509ProxyCertPathValidator { protected void checkRestrictedProxy ( TBSCertificateStructure proxy , CertPath certPath , int index ) throws CertPathValidatorException , IOException { } } | ProxyCertInfo info = ProxyCertificateUtil . getProxyCertInfo ( proxy ) ; ProxyPolicy policy = info . getProxyPolicy ( ) ; String pl = policy . getPolicyLanguage ( ) . getId ( ) ; ProxyPolicyHandler handler = null ; if ( this . policyHandlers != null ) { handler = this . policyHandlers . get ( pl ) ; } if ( handler == null ) { throw new CertPathValidatorException ( "Unknown policy, no handler registered to validate policy " + pl ) ; } handler . validate ( info , certPath , index ) ; |
public class LoggingConfiguration { /** * Set the logging level for a particular package / class .
* @ param pkg Package
* @ param level Level name
* @ throws IllegalArgumentException thrown when logger or level was not found */
public static void setLevelFor ( String pkg , String level ) throws IllegalArgumentException { } } | Logger logr = Logger . getLogger ( pkg ) ; if ( logr == null ) { throw new IllegalArgumentException ( "Logger not found." ) ; } // Can also throw an IllegalArgumentException
java . util . logging . Level lev = Level . parse ( level ) ; logr . setLevel ( lev ) ; |
public class ClassWriter { /** * Write constant pool to pool buffer .
* Note : during writing , constant pool
* might grow since some parts of constants still need to be entered . */
void writePool ( Pool pool ) throws PoolOverflow , StringOverflow { } } | int poolCountIdx = poolbuf . length ; poolbuf . appendChar ( 0 ) ; int i = 1 ; while ( i < pool . pp ) { Object value = pool . pool [ i ] ; Assert . checkNonNull ( value ) ; if ( value instanceof Method || value instanceof Variable ) value = ( ( DelegatedSymbol ) value ) . getUnderlyingSymbol ( ) ; if ( value instanceof MethodSymbol ) { MethodSymbol m = ( MethodSymbol ) value ; if ( ! m . isDynamic ( ) ) { poolbuf . appendByte ( ( m . owner . flags ( ) & INTERFACE ) != 0 ? CONSTANT_InterfaceMethodref : CONSTANT_Methodref ) ; poolbuf . appendChar ( pool . put ( m . owner ) ) ; poolbuf . appendChar ( pool . put ( nameType ( m ) ) ) ; } else { // invokedynamic
DynamicMethodSymbol dynSym = ( DynamicMethodSymbol ) m ; MethodHandle handle = new MethodHandle ( dynSym . bsmKind , dynSym . bsm , types ) ; DynamicMethod dynMeth = new DynamicMethod ( dynSym , types ) ; bootstrapMethods . put ( dynMeth , handle ) ; // init cp entries
pool . put ( names . BootstrapMethods ) ; pool . put ( handle ) ; for ( Object staticArg : dynSym . staticArgs ) { pool . put ( staticArg ) ; } poolbuf . appendByte ( CONSTANT_InvokeDynamic ) ; poolbuf . appendChar ( bootstrapMethods . size ( ) - 1 ) ; poolbuf . appendChar ( pool . put ( nameType ( dynSym ) ) ) ; } } else if ( value instanceof VarSymbol ) { VarSymbol v = ( VarSymbol ) value ; poolbuf . appendByte ( CONSTANT_Fieldref ) ; poolbuf . appendChar ( pool . put ( v . owner ) ) ; poolbuf . appendChar ( pool . put ( nameType ( v ) ) ) ; } else if ( value instanceof Name ) { poolbuf . appendByte ( CONSTANT_Utf8 ) ; byte [ ] bs = ( ( Name ) value ) . toUtf ( ) ; poolbuf . appendChar ( bs . length ) ; poolbuf . appendBytes ( bs , 0 , bs . length ) ; if ( bs . length > Pool . MAX_STRING_LENGTH ) throw new StringOverflow ( value . toString ( ) ) ; } else if ( value instanceof ClassSymbol ) { ClassSymbol c = ( ClassSymbol ) value ; if ( c . owner . kind == TYP ) pool . put ( c . owner ) ; poolbuf . appendByte ( CONSTANT_Class ) ; if ( c . type . hasTag ( ARRAY ) ) { poolbuf . appendChar ( pool . put ( typeSig ( c . type ) ) ) ; } else { poolbuf . appendChar ( pool . put ( names . fromUtf ( externalize ( c . flatname ) ) ) ) ; enterInner ( c ) ; } } else if ( value instanceof NameAndType ) { NameAndType nt = ( NameAndType ) value ; poolbuf . appendByte ( CONSTANT_NameandType ) ; poolbuf . appendChar ( pool . put ( nt . name ) ) ; poolbuf . appendChar ( pool . put ( typeSig ( nt . uniqueType . type ) ) ) ; } else if ( value instanceof Integer ) { poolbuf . appendByte ( CONSTANT_Integer ) ; poolbuf . appendInt ( ( ( Integer ) value ) . intValue ( ) ) ; } else if ( value instanceof Long ) { poolbuf . appendByte ( CONSTANT_Long ) ; poolbuf . appendLong ( ( ( Long ) value ) . longValue ( ) ) ; i ++ ; } else if ( value instanceof Float ) { poolbuf . appendByte ( CONSTANT_Float ) ; poolbuf . appendFloat ( ( ( Float ) value ) . floatValue ( ) ) ; } else if ( value instanceof Double ) { poolbuf . appendByte ( CONSTANT_Double ) ; poolbuf . appendDouble ( ( ( Double ) value ) . doubleValue ( ) ) ; i ++ ; } else if ( value instanceof String ) { poolbuf . appendByte ( CONSTANT_String ) ; poolbuf . appendChar ( pool . put ( names . fromString ( ( String ) value ) ) ) ; } else if ( value instanceof UniqueType ) { Type type = ( ( UniqueType ) value ) . type ; if ( type instanceof MethodType ) { poolbuf . appendByte ( CONSTANT_MethodType ) ; poolbuf . appendChar ( pool . put ( typeSig ( ( MethodType ) type ) ) ) ; } else { if ( type . hasTag ( CLASS ) ) enterInner ( ( ClassSymbol ) type . tsym ) ; poolbuf . appendByte ( CONSTANT_Class ) ; poolbuf . appendChar ( pool . put ( xClassName ( type ) ) ) ; } } else if ( value instanceof MethodHandle ) { MethodHandle ref = ( MethodHandle ) value ; poolbuf . appendByte ( CONSTANT_MethodHandle ) ; poolbuf . appendByte ( ref . refKind ) ; poolbuf . appendChar ( pool . put ( ref . refSym ) ) ; } else { Assert . error ( "writePool " + value ) ; } i ++ ; } if ( pool . pp > Pool . MAX_ENTRIES ) throw new PoolOverflow ( ) ; putChar ( poolbuf , poolCountIdx , pool . pp ) ; |
public class UtilShapePolygon { /** * Finds the intersections between the four lines and converts it into a quadrilateral
* @ param lines Assumes lines are ordered */
public static boolean convert ( LineGeneral2D_F64 [ ] lines , Polygon2D_F64 poly ) { } } | for ( int i = 0 ; i < poly . size ( ) ; i ++ ) { int j = ( i + 1 ) % poly . size ( ) ; if ( null == Intersection2D_F64 . intersection ( lines [ i ] , lines [ j ] , poly . get ( j ) ) ) return false ; } return true ; |
public class SparkLine { /** * Defines the visibility of the start / stop indicators
* @ param START _ STOP _ INDICATOR _ VISIBLE */
public void setStartStopIndicatorVisible ( final boolean START_STOP_INDICATOR_VISIBLE ) { } } | startStopIndicatorVisible = START_STOP_INDICATOR_VISIBLE ; init ( INNER_BOUNDS . width , INNER_BOUNDS . height ) ; repaint ( INNER_BOUNDS ) ; |
public class NonIterableSet { /** * Adds all elements of collection < code > coll < / code > to
* < code > this < / code > set . Returns < code > true < / code > iff we added
* at least one new element to this non - iterable set . */
public boolean addAll ( Collection < T > coll ) { } } | boolean newData = false ; for ( T elem : coll ) { if ( set . add ( elem ) ) { newData = true ; } } return newData ; |
public class AnnotateThen { /** * { @ inheritDoc } */
public void call ( Result result ) { } } | if ( result . isException ( ) ) { statistics . exception ( ) ; annotable . annotate ( Annotations . exception ( result . getException ( ) ) ) ; return ; } annotable . annotate ( new Annotation ( ) { public void writeDown ( Text text ) { StringBuilder content = new StringBuilder ( text . getContent ( ) ) ; Object [ ] arguments = message . arguments ( ) ; MatchResult matchResult = message . matchResult ( ) ; // Backwards since we are replacing text with real positions
for ( int index = arguments . length - 1 ; index >= 0 ; index -- ) { int start = matchResult . start ( index + 1 ) ; int end = matchResult . end ( index + 1 ) ; if ( arguments [ index ] instanceof Expectation ) { Expectation expectation = ( Expectation ) arguments [ index ] ; if ( expectation . meets ( ) ) { String span = String . format ( "<span style='%s: %s;'>%s</span>" , Styles . BACKGROUND_COLOR , Colors . GREEN , expectation . getExpected ( ) ) ; content . replace ( start , end , span ) ; statistics . right ( ) ; } else { String span = String . format ( "<span style='%s: %s;'>%s</span>" , Styles . BACKGROUND_COLOR , Colors . RED , expectation . getDescribe ( ) ) ; content . replace ( start , end , span ) ; statistics . wrong ( ) ; } } } text . setContent ( content . toString ( ) ) ; } } ) ; |
public class ServiceClientImpl { /** * / * ( non - Javadoc )
* @ see com . ibm . g11n . pipeline . client . ServiceClient # getDocumentTranslationRequests ( ) */
@ Override public Map < String , DocumentTranslationRequestData > getDocumentTranslationRequests ( ) throws ServiceException { } } | GetDocumentTranslationRequestsResponse resp = invokeApiJson ( "GET" , escapePathSegment ( account . getInstanceId ( ) ) + "/v2/doc-trs" , null , GetDocumentTranslationRequestsResponse . class ) ; if ( resp . getStatus ( ) == Status . ERROR ) { throw new ServiceException ( resp . getMessage ( ) ) ; } Map < String , DocumentTranslationRequestData > resultTRs = new TreeMap < > ( ) ; for ( Entry < String , RestDocumentTranslationRequest > trEntry : resp . translationRequests . entrySet ( ) ) { String id = trEntry . getKey ( ) ; RestDocumentTranslationRequest tr = trEntry . getValue ( ) ; resultTRs . put ( id , new DocumentTranslationRequestDataImpl ( id , tr ) ) ; } return resultTRs ; |
public class MultiLayerNetwork { /** * Perform minibatch training on all minibatches in the DataSetIterator for 1 epoch . < br >
* Note that this method does not do layerwise pretraining . < br >
* For pretraining use method pretrain . . { @ link # pretrain ( DataSetIterator ) } < br >
* @ param iterator Training data ( DataSetIterator ) */
@ Override public void fit ( DataSetIterator iterator ) { } } | try { fitHelper ( iterator ) ; } catch ( OutOfMemoryError e ) { CrashReportingUtil . writeMemoryCrashDump ( this , e ) ; throw e ; } |
public class RpcInvokeContext { /** * 删除响应透传数据
* @ param key Key
* @ return Value 删掉的值 */
public String removeResponseBaggage ( String key ) { } } | if ( BAGGAGE_ENABLE && key != null ) { return responseBaggage . remove ( key ) ; } return null ; |
public class ModuleUiExtensions { /** * Fetch all ui extensions from the configured space by a query .
* @ param query controls what to return .
* @ return specific ui extensions for a specific space .
* @ throws IllegalArgumentException if configured space id is null .
* @ throws IllegalArgumentException if configured environment id is null .
* @ see CMAClient . Builder # setSpaceId ( String )
* @ see CMAClient . Builder # setEnvironmentId ( String ) */
public CMAArray < CMAUiExtension > fetchAll ( Map < String , String > query ) { } } | return fetchAll ( spaceId , environmentId , query ) ; |
public class SufficientStatisticsBatch { /** * Adds the statistics in { @ code other } to { @ code this } .
* @ param other */
public void increment ( SufficientStatisticsBatch other ) { } } | statistics . increment ( other . statistics , 1.0 ) ; loglikelihood += other . loglikelihood ; numExamples += other . numExamples ; |
public class MiniTemplatorParser { /** * Returns the variable number of the newly registered variable . */
private int registerVariable ( String varName ) { } } | int varNo = varTabCnt ++ ; if ( varTabCnt > varTab . length ) { varTab = ( String [ ] ) resizeArray ( varTab , 2 * varTabCnt ) ; } varTab [ varNo ] = varName ; varNameToNoMap . put ( varName . toUpperCase ( ) , new Integer ( varNo ) ) ; return varNo ; |
public class AbstractBcX509CertificateGenerator { /** * Extend TBS certificate depending of certificate version .
* @ param builder the X . 509 TBS certificate builder received from # getTBSCertificateBuilder ( ) .
* @ param issuer the certified public key of the issuer of the certificate , or null for self signed one .
* @ param subjectName the subject name .
* @ param subject the subject public key .
* @ param parameters the X . 509 certificate parameters .
* @ throws IOException on encoding error . */
protected void extendsTBSCertificate ( BcX509TBSCertificateBuilder builder , CertifiedPublicKey issuer , PrincipalIndentifier subjectName , PublicKeyParameters subject , X509CertificateParameters parameters ) throws IOException { } } | // Do nothing by default . |
public class JsonOutput { /** * Writes a JSON int .
* @ param value the value
* @ throws IOException if an error occurs */
void writeInt ( int value ) throws IOException { } } | if ( ( value & 0xfffffff8 ) == 0 ) { output . append ( ( char ) ( value + 48 ) ) ; } else { output . append ( Integer . toString ( value ) ) ; } |
public class RemoteBundleContextClient { /** * { @ inheritDoc } */
public long installBundle ( final String bundleLocation , final byte [ ] bundle ) throws TestContainerException { } } | try { return getRemoteBundleContext ( ) . installBundle ( bundleLocation , bundle ) ; } catch ( RemoteException e ) { throw new TestContainerException ( "Remote exception" , e ) ; } catch ( BundleException e ) { throw new TestContainerException ( "Bundle cannot be installed" , e ) ; } |
public class CPRuleUserSegmentRelPersistenceImpl { /** * Returns the cp rule user segment rel with the primary key or throws a { @ link com . liferay . portal . kernel . exception . NoSuchModelException } if it could not be found .
* @ param primaryKey the primary key of the cp rule user segment rel
* @ return the cp rule user segment rel
* @ throws NoSuchCPRuleUserSegmentRelException if a cp rule user segment rel with the primary key could not be found */
@ Override public CPRuleUserSegmentRel findByPrimaryKey ( Serializable primaryKey ) throws NoSuchCPRuleUserSegmentRelException { } } | CPRuleUserSegmentRel cpRuleUserSegmentRel = fetchByPrimaryKey ( primaryKey ) ; if ( cpRuleUserSegmentRel == null ) { if ( _log . isDebugEnabled ( ) ) { _log . debug ( _NO_SUCH_ENTITY_WITH_PRIMARY_KEY + primaryKey ) ; } throw new NoSuchCPRuleUserSegmentRelException ( _NO_SUCH_ENTITY_WITH_PRIMARY_KEY + primaryKey ) ; } return cpRuleUserSegmentRel ; |
public class Scoreboard { /** * 4 ) restart completion and repair completion can ' t overwrite each other */
private static boolean isComparable ( CompleteTransactionTask c1 , CompleteTransactionTask c2 ) { } } | return c1 . getMsgTxnId ( ) == c2 . getMsgTxnId ( ) && MpRestartSequenceGenerator . isForRestart ( c1 . getTimestamp ( ) ) == MpRestartSequenceGenerator . isForRestart ( c2 . getTimestamp ( ) ) ; |
public class ZooKeeperConfiguration { /** * Return a managed Curator connection . This created connection will be wrapped in a
* { @ link ManagedCuratorFramework } and offered to the provided { @ link LifecycleEnvironment } parameter . */
public CuratorFramework newManagedCurator ( LifecycleEnvironment env ) { } } | CuratorFramework curator = newCurator ( ) ; env . manage ( new ManagedCuratorFramework ( curator ) ) ; return curator ; |
public class TrainingsImpl { /** * Gets the number of images tagged with the provided { tagIds } .
* The filtering is on an and / or relationship . For example , if the provided tag ids are for the " Dog " and
* " Cat " tags , then only images tagged with Dog and / or Cat will be returned .
* @ param projectId The project id
* @ param iterationId The iteration id . Defaults to workspace
* @ param tagIds A list of tags ids to filter the images to count . Defaults to all tags when null .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the observable to the Integer object */
public Observable < ServiceResponse < Integer > > getTaggedImageCountWithServiceResponseAsync ( UUID projectId , UUID iterationId , List < String > tagIds ) { } } | if ( projectId == null ) { throw new IllegalArgumentException ( "Parameter projectId is required and cannot be null." ) ; } if ( this . client . apiKey ( ) == null ) { throw new IllegalArgumentException ( "Parameter this.client.apiKey() is required and cannot be null." ) ; } Validator . validate ( tagIds ) ; String tagIdsConverted = this . client . serializerAdapter ( ) . serializeList ( tagIds , CollectionFormat . CSV ) ; return service . getTaggedImageCount ( projectId , iterationId , tagIdsConverted , this . client . apiKey ( ) , this . client . acceptLanguage ( ) , this . client . userAgent ( ) ) . flatMap ( new Func1 < Response < ResponseBody > , Observable < ServiceResponse < Integer > > > ( ) { @ Override public Observable < ServiceResponse < Integer > > call ( Response < ResponseBody > response ) { try { ServiceResponse < Integer > clientResponse = getTaggedImageCountDelegate ( response ) ; return Observable . just ( clientResponse ) ; } catch ( Throwable t ) { return Observable . error ( t ) ; } } } ) ; |
public class DTMDocumentImpl { /** * Given an expanded - name ID , return the local name part .
* @ param ExpandedNameID an ID that represents an expanded - name .
* @ return String Local name of this node . */
public String getLocalNameFromExpandedNameID ( int ExpandedNameID ) { } } | // Get expanded name
String expandedName = m_localNames . indexToString ( ExpandedNameID ) ; // Remove prefix from expanded name
int colonpos = expandedName . indexOf ( ":" ) ; String localName = expandedName . substring ( colonpos + 1 ) ; return localName ; |
public class IntegerMapperBuilder { /** * Returns the { @ link IntegerMapper } represented by this { @ link MapperBuilder } .
* @ param field the name of the field to be built
* @ return the { @ link IntegerMapper } represented by this */
@ Override public IntegerMapper build ( String field ) { } } | return new IntegerMapper ( field , column , validated , boost ) ; |
public class CoreCondo { /** * Evaluate the list of deferred action after the list of masks has been updated .
* < p > Must be invoked under { @ link # maskLock } */
private void evaluateDeferredAfterMaskUpdate ( ) { } } | final Iterator < DeferredAction < M > > it = this . deferred . iterator ( ) ; while ( it . hasNext ( ) ) { final DeferredAction < M > d = it . next ( ) ; /* is the current action still masked ? */
if ( masks . stream ( ) . anyMatch ( p -> p . test ( d . metadata ) ) ) { continue ; } it . remove ( ) ; d . runnable . run ( ) ; } |
public class BridgeFactory { /** * Finds or creates a near object for the given far object .
* @ param farObject The far object that is to be wrapped by the near object
* @ return The near object that corresponds to the given far object */
public Object getNearObject ( Object farObject ) { } } | Object nearObject = null ; if ( farObject instanceof BridgeFacet ) { BridgeFacet facet = ( BridgeFacet ) farObject ; if ( facet . hasBridgeFacets ( ) ) { BridgeFacets facets = facet . getBridgeFacets ( ) ; if ( facets . hasNearObject ( ) ) { nearObject = nearType . cast ( facets . getNearObject ( ) ) ; } } } if ( nearObject == null ) { if ( ! farType . isInstance ( farObject ) ) { RuntimeException exception = new ClassCastException ( "Class: " + display ( farType ) + ": object: " + display ( farObject ) ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( "Far type: " + display ( farType ) , exception ) ; } throw exception ; } Class < ? > [ ] interfaces = new Class [ ] { BridgeFacet . class } ; final BridgeFacets facets ; if ( farObject instanceof BaseBridgeFacet && ( ( BaseBridgeFacet ) farObject ) . hasBridgeFacets ( ) ) { facets = ( ( BaseBridgeFacet ) farObject ) . getBridgeFacets ( ) ; } else { Map < Integer , Object > helperInstances = new HashMap < > ( ) ; for ( int i = 0 ; i < helpers . length ; i ++ ) { Object helper = helpers [ i ] ; if ( helper instanceof Class ) { Class < ? > helperType = ( Class < ? > ) helper ; try { Object helperInstance = helperType . newInstance ( ) ; helperInstances . put ( i , helperInstance ) ; } catch ( Throwable throwable ) { throw ExceptionWrapper . wrap ( throwable ) ; } } } facets = new BridgeFacets ( farType . cast ( farObject ) , this , helperInstances ) ; for ( Object helperInstance : helperInstances . values ( ) ) { if ( helperInstance instanceof BaseBridgeFacet ) { ( ( BaseBridgeFacet ) helperInstance ) . setBridgeFacets ( facets ) ; } } } if ( farObject instanceof BaseBridgeFacet && ! ( ( BaseBridgeFacet ) farObject ) . hasBridgeFacets ( ) ) { ( ( BaseBridgeFacet ) farObject ) . setBridgeFacets ( facets ) ; } nearObject = newProxyInstance ( getClass ( ) . getClassLoader ( ) , nearType , interfaces , ( object , method , parameters ) -> { Object result ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( "Facets getter: " + display ( facetsGetter ) ) ; } if ( method . equals ( facetsGetter ) ) { result = facets ; } else if ( method . equals ( facetsChecker ) ) { result = Boolean . TRUE ; } else { Binding binding = methodMap . get ( method ) ; if ( binding == null ) { String message = "No binding found: " + display ( nearType ) + ": " + display ( method ) ; logger . warn ( message ) ; throw new UnsupportedOperationException ( message ) ; } result = binding . invoke ( facets , parameters ) ; Class < ? > returnType = method . getReturnType ( ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( "Return type: " + displayWithTypes ( returnType ) ) ; } if ( result instanceof TypedIterable ) { TypedIterable < ? > typedIterable = ( TypedIterable < ? > ) result ; Class < ? > baseType = typedIterable . getType ( ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( "Iterable base type: " + display ( baseType ) ) ; } if ( registry . hasFarType ( baseType ) ) { Class < ? > type = getNearType ( baseType ) ; result = getAdaptedIterable ( returnType , typedIterable , type ) ; } else if ( registry . hasNearType ( baseType ) ) { result = getAdaptedIterable ( returnType , typedIterable , baseType ) ; } else if ( logger . isTraceEnabled ( ) ) { logger . trace ( "Iterable base type not found in registry" ) ; } } else if ( registry . hasNearType ( returnType ) ) { Class < ? > farType1 = registry . getFarType ( method . getReturnType ( ) ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( "Far type of return type: " + display ( farType1 ) ) ; } if ( farType1 . isInstance ( result ) ) { BridgeFactory factory = registry . getBridgeFactory ( farType1 ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( "Far type of return type factory: " + display ( factory . getFarType ( ) ) ) ; logger . trace ( "Result: " + display ( result ) ) ; logger . trace ( "Return type: " + display ( returnType ) + ": factory PO type: " + display ( factory . getNearType ( ) ) ) ; } try { result = factory . getNearObject ( result ) ; } catch ( ClassCastException exception ) { if ( logger . isTraceEnabled ( ) ) { logger . trace ( "Stack trace" , exception ) ; } throw exception ; } } } else if ( logger . isTraceEnabled ( ) ) { logger . trace ( "Not adapted" ) ; } } return result ; } ) ; facets . setNearObject ( nearObject ) ; } return nearObject ; |
public class IndentedLinesBuilder { /** * Appends some parts to the current line .
* @ param parts The parts to append .
* @ return This object . */
public IndentedLinesBuilder appendParts ( Object ... parts ) { } } | for ( Object part : parts ) { sb . append ( part ) ; } return this ; |
public class CassandraCpoAdapter { /** * getWriteSession returns the write session for Cassandra
* @ return A Session object for writing
* @ throws CpoException */
protected Session getWriteSession ( ) throws CpoException { } } | Session session ; try { session = getWriteDataSource ( ) . getSession ( ) ; } catch ( Throwable t ) { String msg = "getWriteConnection(): failed" ; logger . error ( msg , t ) ; throw new CpoException ( msg , t ) ; } return session ; |
public class AccountsInner { /** * Updates the specified Data Lake Store account information .
* @ param resourceGroupName The name of the Azure resource group .
* @ param accountName The name of the Data Lake Store account .
* @ param parameters Parameters supplied to update the Data Lake Store account .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ throws CloudException thrown if the request is rejected by server
* @ throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @ return the DataLakeStoreAccountInner object if successful . */
public DataLakeStoreAccountInner beginUpdate ( String resourceGroupName , String accountName , UpdateDataLakeStoreAccountParameters parameters ) { } } | return beginUpdateWithServiceResponseAsync ( resourceGroupName , accountName , parameters ) . toBlocking ( ) . single ( ) . body ( ) ; |
public class CProductLocalServiceBaseImpl { /** * Returns the c product matching the UUID and group .
* @ param uuid the c product ' s UUID
* @ param groupId the primary key of the group
* @ return the matching c product , or < code > null < / code > if a matching c product could not be found */
@ Override public CProduct fetchCProductByUuidAndGroupId ( String uuid , long groupId ) { } } | return cProductPersistence . fetchByUUID_G ( uuid , groupId ) ; |
public class ShardingProxyContext { /** * Initialize proxy context .
* @ param authentication authentication
* @ param props properties */
public void init ( final Authentication authentication , final Properties props ) { } } | this . authentication = authentication ; shardingProperties = new ShardingProperties ( props ) ; |
public class RaidShell { /** * Apply operation specified by ' cmd ' on all parameters
* starting from argv [ startindex ] . */
private int showConfig ( String cmd , String argv [ ] , int startindex ) throws IOException { } } | int exitCode = 0 ; PolicyInfo [ ] all = raidnode . getAllPolicies ( ) ; for ( PolicyInfo p : all ) { out . println ( p ) ; } return exitCode ; |
public class MediaAPI { /** * 上传群发文章素材 。
* @ param articles 上传的文章信息
* @ return 响应对象 */
public UploadMediaResponse uploadNews ( List < Article > articles ) { } } | UploadMediaResponse response ; String url = BASE_API_URL + "cgi-bin/media/uploadnews?access_token=#" ; final Map < String , Object > params = new HashMap < String , Object > ( ) ; params . put ( "articles" , articles ) ; BaseResponse r = executePost ( url , JSONUtil . toJson ( params ) ) ; response = JSONUtil . toBean ( r . getErrmsg ( ) , UploadMediaResponse . class ) ; return response ; |
public class JShellTool { /** * Completion of help , commands and subjects */
private CompletionProvider helpCompletion ( ) { } } | return ( code , cursor , anchor ) -> { List < Suggestion > result ; int pastSpace = code . indexOf ( ' ' ) + 1 ; // zero if no space
if ( pastSpace == 0 ) { // initially suggest commands ( with slash ) and subjects ,
// however , if their subject starts without slash , include
// commands without slash
boolean noslash = code . length ( ) > 0 && ! code . startsWith ( "/" ) ; result = new FixedCompletionProvider ( commands . values ( ) . stream ( ) . filter ( cmd -> cmd . kind . showInHelp || cmd . kind == CommandKind . HELP_SUBJECT ) . map ( c -> ( ( noslash && c . command . startsWith ( "/" ) ) ? c . command . substring ( 1 ) : c . command ) + " " ) . toArray ( String [ ] :: new ) ) . completionSuggestions ( code , cursor , anchor ) ; } else if ( code . startsWith ( "/se" ) || code . startsWith ( "se" ) ) { result = new FixedCompletionProvider ( SET_SUBCOMMANDS ) . completionSuggestions ( code . substring ( pastSpace ) , cursor - pastSpace , anchor ) ; } else { result = Collections . emptyList ( ) ; } anchor [ 0 ] += pastSpace ; return result ; } ; |
public class SubstitutionMatrixHelper { /** * reads in a substitution matrix from a resource file */
private static InputStreamReader getReader ( String file ) { } } | String resourcePathPrefix = "matrices/" ; return new InputStreamReader ( SubstitutionMatrixHelper . class . getResourceAsStream ( String . format ( "/%s.txt" , resourcePathPrefix + file ) ) ) ; |
public class DistributedWorkManagerImpl { /** * { @ inheritDoc } */
public void localDoWork ( Work work ) throws WorkException { } } | if ( transport != null ) { checkTransport ( ) ; if ( getLongRunningThreadPool ( ) != null && WorkManagerUtil . isLongRunning ( work ) ) { transport . updateLongRunningFree ( getLocalAddress ( ) , getLongRunningThreadPool ( ) . getNumberOfFreeThreads ( ) - 1 ) ; } else { transport . updateShortRunningFree ( getLocalAddress ( ) , getShortRunningThreadPool ( ) . getNumberOfFreeThreads ( ) - 1 ) ; } WorkEventListener wel = new WorkEventListener ( WorkManagerUtil . isLongRunning ( work ) , getShortRunningThreadPool ( ) , getLongRunningThreadPool ( ) , getLocalAddress ( ) , transport ) ; super . doWork ( work , WorkManager . INDEFINITE , null , wel ) ; } else { super . doWork ( work ) ; } |
public class XML { /** * Verifies that the global mapping exist in aClass .
* @ param aClass class to check
* @ return this intance of XML */
private XML checksGlobalExistence ( Class < ? > aClass ) { } } | if ( ! classExists ( aClass ) ) Error . xmlClassInexistent ( this . xmlPath , aClass ) ; if ( findXmlClass ( aClass ) . global == null ) Error . xmlGlobalInexistent ( aClass ) ; return this ; |
public class MutableBigInteger { /** * Calculate the multiplicative inverse of 2 ^ k mod mod , where mod is odd . */
static MutableBigInteger modInverseBP2 ( MutableBigInteger mod , int k ) { } } | // Copy the mod to protect original
return fixup ( new MutableBigInteger ( 1 ) , new MutableBigInteger ( mod ) , k ) ; |
public class ValgrindStack { /** * Returns the last frame ( counted from the bottom of the stack ) of a function which is in ' our ' code
* @ param basedir
* @ return ValgrindFrame frame or null */
@ Nullable public ValgrindFrame getLastOwnFrame ( String basedir ) { } } | String workdir = FilenameUtils . normalize ( basedir ) ; for ( ValgrindFrame frame : frames ) { if ( isInside ( frame . getDir ( ) , workdir ) ) { return frame ; } } return null ; |
public class Sitemap { /** * / * setter */
public void setEntries ( Map < String , String > entries ) { } } | for ( String id : entries . keySet ( ) ) { specs . put ( id , new ObjURISpec ( Utils . extractUriSpecFromSitemapMatch ( entries . get ( id ) ) ) ) ; } |
public class Database { /** * Provides access to partitioned Cloudant < tt > Search < / tt > APIs .
* Only available in partitioned databases . To verify a database is partitioned call
* { @ link Database # info ( ) } and check that { @ link DbInfo . Props # getProps ( ) } returns
* { @ code true } .
* < p > Example usage : < / p >
* < pre >
* { @ code
* / / Search query over partition ' aves ' using design document _ id ' _ design / views101 ' and
* / / search index ' partitioned _ animals ' .
* List < Bird > birds = db . search ( " aves " , " views101 / partitioned _ animals " )
* . query ( " name : puffin " , Bird . class ) ;
* < / pre >
* @ param partitionKey database partition key
* @ param searchIndexId the design document with the name of the index to search
* @ return Search object for searching the index
* @ see < a
* href = " https : / / console . bluemix . net / docs / services / Cloudant / api / search . html # search "
* target = " _ blank " > Search < / a > */
public Search search ( String partitionKey , String searchIndexId ) { } } | return new Search ( client , this , partitionKey , searchIndexId ) ; |
public class CommerceVirtualOrderItemUtil { /** * Returns the commerce virtual order item with the primary key or throws a { @ link NoSuchVirtualOrderItemException } if it could not be found .
* @ param commerceVirtualOrderItemId the primary key of the commerce virtual order item
* @ return the commerce virtual order item
* @ throws NoSuchVirtualOrderItemException if a commerce virtual order item with the primary key could not be found */
public static CommerceVirtualOrderItem findByPrimaryKey ( long commerceVirtualOrderItemId ) throws com . liferay . commerce . product . type . virtual . order . exception . NoSuchVirtualOrderItemException { } } | return getPersistence ( ) . findByPrimaryKey ( commerceVirtualOrderItemId ) ; |
public class ApplicationExtensions { /** * Sets the RootRequestMapper for the given application from the given httpPort and httpsPort .
* Note : if the configuration type is RuntimeConfigurationType . DEVELOPMENT then only HTTP scheme
* will be returned .
* @ param application
* the application
* @ param httpPort
* the http port
* @ param httpsPort
* the https port */
public static void setRootRequestMapperForDevelopment ( final Application application , final int httpPort , final int httpsPort ) { } } | application . setRootRequestMapper ( new HttpsMapper ( application . getRootRequestMapper ( ) , new HttpsConfig ( httpPort , httpsPort ) ) { @ Override protected Scheme getDesiredSchemeFor ( final Class < ? extends IRequestablePage > pageClass ) { if ( application . getConfigurationType ( ) . equals ( RuntimeConfigurationType . DEVELOPMENT ) ) { // is in development mode , returning Scheme . HTTP . . .
return Scheme . HTTP ; } else { // not in development mode , letting the mapper decide
return super . getDesiredSchemeFor ( pageClass ) ; } } } ) ; |
public class RtpStatistics { /** * Calculates a random interval to transmit the next RTCP report , according
* to < a
* href = " http : / / tools . ietf . org / html / rfc3550 # section - 6.3.1 " > RFC3550 < / a > .
* @ param initial
* Whether an RTCP packet was already sent or not . Usually the
* minimum interval for the first packet is lower than the rest .
* @ return the new transmission interval , in milliseconds */
public long rtcpInterval ( boolean initial ) { } } | return RtcpIntervalCalculator . calculateInterval ( initial , weSent , senders , members , rtcpAvgSize , rtcpBw , RTCP_BW_FRACTION , RTCP_SENDER_BW_FRACTION , RTCP_RECEIVER_BW_FRACTION ) ; |
public class MtasSolrStatus { /** * Gets the long .
* @ param response
* the response
* @ param args
* the args
* @ return the long */
private final Long getLong ( NamedList < Object > response , String ... args ) { } } | Object objectItem = response . findRecursive ( args ) ; if ( objectItem != null && objectItem instanceof Long ) { return ( Long ) objectItem ; } else { return null ; } |
public class LazyCsvAnnotationBeanReader { /** * ヘッダー情報を指定して 、 カラム情報の初期化を行います 。
* < p > ヘッダーの位置を元にカラムの番号を決定します 。 < / p >
* @ param headers CSVのヘッダー情報 。 実際のCSVファイルの内容と一致する必要があります 。
* @ throws SuperCsvNoMatchColumnSizeException ヘッダーのサイズ ( カラム数 ) がBean定義と一致しない場合 。
* @ throws SuperCsvNoMatchHeaderException ヘッダーの値がBean定義と一致しない場合 。
* @ throws SuperCsvException 引数firstLineCheck = trueのとき 、 このメソッドが1行目以外の読み込み時に呼ばれた場合 。 */
public void init ( final String ... headers ) { } } | setupMappingColumns ( headers ) ; this . beanMappingCache = BeanMappingCache . create ( beanMapping ) ; if ( beanMappingCache . getOriginal ( ) . isValidateHeader ( ) ) { try { validateHeader ( headers , beanMapping . getHeader ( ) ) ; } catch ( SuperCsvNoMatchColumnSizeException | SuperCsvNoMatchHeaderException e ) { // convert exception and format to message .
errorMessages . addAll ( exceptionConverter . convertAndFormat ( e , beanMappingCache . getOriginal ( ) ) ) ; throw e ; } } // 初期化完了
this . initialized = true ; |
public class AbstractPojoPathNavigator { /** * This method { @ link PojoPathFunction # get ( Object , String , PojoPathContext ) gets } the single
* { @ link CachingPojoPath # getSegment ( ) segment } of the given { @ code currentPath } from the
* { @ link net . sf . mmm . util . pojo . api . Pojo } given by { @ code parentPojo } . If the result is { @ code null } and
* { @ link PojoPathState # getMode ( ) mode } is { @ link PojoPathMode # CREATE _ IF _ NULL } it
* { @ link PojoPathFunction # create ( Object , String , PojoPathContext ) creates } the missing object .
* @ param currentPath is the current { @ link CachingPojoPath } to evaluate .
* @ param context is the { @ link PojoPathContext context } for this operation .
* @ param state is the { @ link # createState ( Object , String , PojoPathMode , PojoPathContext ) state } of this operation .
* @ param function is the { @ link PojoPathFunction } for evaluation .
* @ return the result of the evaluation . It might be { @ code null } according to the { @ link PojoPathState # getMode ( )
* mode } . */
@ SuppressWarnings ( { } } | "unchecked" , "rawtypes" } ) protected Object getFromFunction ( CachingPojoPath currentPath , PojoPathContext context , PojoPathState state , PojoPathFunction function ) { Object parentPojo = currentPath . parent . pojo ; // TODO : convert parentPojo from parentPojoType to function . getInputClass ( )
// if necessary .
Object result = function . get ( parentPojo , currentPath . getFunction ( ) , context ) ; if ( ( result == null ) && ( state . mode == PojoPathMode . CREATE_IF_NULL ) ) { result = function . create ( parentPojo , currentPath . getFunction ( ) , context ) ; if ( result == null ) { throw new PojoPathCreationException ( state . rootPath . pojo , currentPath . getPojoPath ( ) ) ; } } if ( ! function . isDeterministic ( ) ) { state . setCachingDisabled ( ) ; } return result ; |
public class AddDynamicPageFeed { /** * Sets custom targeting for the page feed URLs based on a list of labels .
* @ param adWordsServices
* @ param session
* @ param adGroupId
* @ param dsaPageUrlLabel */
private static void addDsaTargeting ( AdWordsServicesInterface adWordsServices , AdWordsSession session , Long adGroupId , String dsaPageUrlLabel ) throws ApiException , RemoteException { } } | // Get the AdGroupCriterionService .
AdGroupCriterionServiceInterface adGroupCriterionService = adWordsServices . get ( session , AdGroupCriterionServiceInterface . class ) ; // Create a webpage criterion .
Webpage webpage = new Webpage ( ) ; WebpageParameter parameter = new WebpageParameter ( ) ; parameter . setCriterionName ( "Test criterion" ) ; webpage . setParameter ( parameter ) ; // Add a condition for label = specified _ label _ name .
WebpageCondition condition = new WebpageCondition ( ) ; condition . setOperand ( WebpageConditionOperand . CUSTOM_LABEL ) ; condition . setArgument ( dsaPageUrlLabel ) ; parameter . setConditions ( new WebpageCondition [ ] { condition } ) ; BiddableAdGroupCriterion criterion = new BiddableAdGroupCriterion ( ) ; criterion . setAdGroupId ( adGroupId ) ; criterion . setCriterion ( webpage ) ; // Set a custom bid for this criterion .
BiddingStrategyConfiguration biddingStrategyConfiguration = new BiddingStrategyConfiguration ( ) ; CpcBid cpcBid = new CpcBid ( ) ; Money money = new Money ( ) ; money . setMicroAmount ( 1_500_000L ) ; cpcBid . setBid ( money ) ; biddingStrategyConfiguration . setBids ( new Bids [ ] { cpcBid } ) ; criterion . setBiddingStrategyConfiguration ( biddingStrategyConfiguration ) ; AdGroupCriterionOperation operation = new AdGroupCriterionOperation ( ) ; operation . setOperand ( criterion ) ; operation . setOperator ( Operator . ADD ) ; BiddableAdGroupCriterion newCriterion = ( BiddableAdGroupCriterion ) adGroupCriterionService . mutate ( new AdGroupCriterionOperation [ ] { operation } ) . getValue ( 0 ) ; System . out . printf ( "Web page criterion with ID %d and status '%s' was created.%n" , newCriterion . getCriterion ( ) . getId ( ) , newCriterion . getUserStatus ( ) ) ; |
public class PluginManager { /** * PRIVATE - LOADER PART */
private void loadPlugins ( ) { } } | final List < T > finalPluginsList = new ArrayList < T > ( ) ; pluginsList = new ArrayList < T > ( ) ; pluginsMap = new HashMap < String , T > ( ) ; String className = null ; try { final Class < T > [ ] classes = getClasses ( ) ; for ( final Class < T > clazz : classes ) { className = clazz . getName ( ) ; final T plugin = clazz . newInstance ( ) ; if ( plugin instanceof DelegatingModuleParser ) { ( ( DelegatingModuleParser ) plugin ) . setFeedParser ( parentParser ) ; } if ( plugin instanceof DelegatingModuleGenerator ) { ( ( DelegatingModuleGenerator ) plugin ) . setFeedGenerator ( parentGenerator ) ; } pluginsMap . put ( getKey ( plugin ) , plugin ) ; // to preserve the order of definition in the rome . properties files
pluginsList . add ( plugin ) ; } final Collection < T > plugins = pluginsMap . values ( ) ; for ( final T plugin : plugins ) { // to remove overridden plugin impls
finalPluginsList . add ( plugin ) ; } final Iterator < T > iterator = pluginsList . iterator ( ) ; while ( iterator . hasNext ( ) ) { final T plugin = iterator . next ( ) ; if ( ! finalPluginsList . contains ( plugin ) ) { iterator . remove ( ) ; } } } catch ( final Exception ex ) { throw new RuntimeException ( "could not instantiate plugin " + className , ex ) ; } catch ( final ExceptionInInitializerError er ) { throw new RuntimeException ( "could not instantiate plugin " + className , er ) ; } |
public class PractitionerRole { /** * syntactic sugar */
public PractitionerRoleAvailableTimeComponent addAvailableTime ( ) { } } | PractitionerRoleAvailableTimeComponent t = new PractitionerRoleAvailableTimeComponent ( ) ; if ( this . availableTime == null ) this . availableTime = new ArrayList < PractitionerRoleAvailableTimeComponent > ( ) ; this . availableTime . add ( t ) ; return t ; |
public class CreateDeploymentGroupRequest { /** * Information about triggers to create when the deployment group is created . For examples , see < a
* href = " https : / / docs . aws . amazon . com / codedeploy / latest / userguide / how - to - notify - sns . html " > Create a Trigger for an AWS
* CodeDeploy Event < / a > in the AWS CodeDeploy User Guide .
* @ param triggerConfigurations
* Information about triggers to create when the deployment group is created . For examples , see < a
* href = " https : / / docs . aws . amazon . com / codedeploy / latest / userguide / how - to - notify - sns . html " > Create a Trigger for
* an AWS CodeDeploy Event < / a > in the AWS CodeDeploy User Guide . */
public void setTriggerConfigurations ( java . util . Collection < TriggerConfig > triggerConfigurations ) { } } | if ( triggerConfigurations == null ) { this . triggerConfigurations = null ; return ; } this . triggerConfigurations = new com . amazonaws . internal . SdkInternalList < TriggerConfig > ( triggerConfigurations ) ; |
public class OutputDataConfigMarshaller { /** * Marshall the given parameter object . */
public void marshall ( OutputDataConfig outputDataConfig , ProtocolMarshaller protocolMarshaller ) { } } | if ( outputDataConfig == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( outputDataConfig . getKmsKeyId ( ) , KMSKEYID_BINDING ) ; protocolMarshaller . marshall ( outputDataConfig . getS3OutputPath ( ) , S3OUTPUTPATH_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class LasUtils { /** * Compare two { @ link LasRecord } s .
* @ param dot1 the first record .
* @ param dot2 the second record .
* @ return < code > true < / code > , if the records are the same . */
public static boolean lasRecordEqual ( LasRecord dot1 , LasRecord dot2 ) { } } | double delta = 0.000001 ; boolean check = NumericsUtilities . dEq ( dot1 . x , dot2 . x , delta ) ; if ( ! check ) { return false ; } check = NumericsUtilities . dEq ( dot1 . y , dot2 . y , delta ) ; if ( ! check ) { return false ; } check = NumericsUtilities . dEq ( dot1 . z , dot2 . z , delta ) ; if ( ! check ) { return false ; } check = dot1 . intensity == dot2 . intensity ; if ( ! check ) { return false ; } check = dot1 . classification == dot2 . classification ; if ( ! check ) { return false ; } check = dot1 . returnNumber == dot2 . returnNumber ; if ( ! check ) { return false ; } check = dot1 . numberOfReturns == dot2 . numberOfReturns ; if ( ! check ) { return false ; } return true ; |
public class MatchResponse { /** * Merges the roles , sslRequired , and accessPrecluded fields according to the
* Servlet 2.3 and 3.0 specifications .
* @ param matchResponse
* @ return */
public MatchResponse merge ( MatchResponse matchResponse ) { } } | if ( matchResponse == null || matchResponse == this ) { return this ; } else { boolean mergedSSLRequired = mergeSSLRequired ( matchResponse . isSSLRequired ( ) ) ; boolean mergedAccessPrecluded = mergeAccessPrecluded ( matchResponse . isAccessPrecluded ( ) ) ; List < String > mergedRoles = mergeRoles ( matchResponse . getRoles ( ) , mergedAccessPrecluded ) ; return new MatchResponse ( mergedRoles , mergedSSLRequired , mergedAccessPrecluded ) ; } |
public class EqualityInference { /** * Dumps the inference equalities as equality expressions that are partitioned by the symbolScope .
* All stored equalities are returned in a compact set and will be classified into three groups as determined by the symbol scope :
* < ol >
* < li > equalities that fit entirely within the symbol scope < / li >
* < li > equalities that fit entirely outside of the symbol scope < / li >
* < li > equalities that straddle the symbol scope < / li >
* < / ol >
* < pre >
* Example :
* Stored Equalities :
* a = b = c
* d = e = f = g
* Symbol Scope :
* a , b , d , e
* Output EqualityPartition :
* Scope Equalities :
* a = b
* d = e
* Complement Scope Equalities
* f = g
* Scope Straddling Equalities
* a = c
* d = f
* < / pre > */
public EqualityPartition generateEqualitiesPartitionedBy ( Predicate < Symbol > symbolScope ) { } } | ImmutableSet . Builder < Expression > scopeEqualities = ImmutableSet . builder ( ) ; ImmutableSet . Builder < Expression > scopeComplementEqualities = ImmutableSet . builder ( ) ; ImmutableSet . Builder < Expression > scopeStraddlingEqualities = ImmutableSet . builder ( ) ; for ( Collection < Expression > equalitySet : equalitySets . asMap ( ) . values ( ) ) { Set < Expression > scopeExpressions = new LinkedHashSet < > ( ) ; Set < Expression > scopeComplementExpressions = new LinkedHashSet < > ( ) ; Set < Expression > scopeStraddlingExpressions = new LinkedHashSet < > ( ) ; // Try to push each non - derived expression into one side of the scope
for ( Expression expression : filter ( equalitySet , not ( derivedExpressions :: contains ) ) ) { Expression scopeRewritten = rewriteExpression ( expression , symbolScope , false ) ; if ( scopeRewritten != null ) { scopeExpressions . add ( scopeRewritten ) ; } Expression scopeComplementRewritten = rewriteExpression ( expression , not ( symbolScope ) , false ) ; if ( scopeComplementRewritten != null ) { scopeComplementExpressions . add ( scopeComplementRewritten ) ; } if ( scopeRewritten == null && scopeComplementRewritten == null ) { scopeStraddlingExpressions . add ( expression ) ; } } // Compile the equality expressions on each side of the scope
Expression matchingCanonical = getCanonical ( scopeExpressions ) ; if ( scopeExpressions . size ( ) >= 2 ) { for ( Expression expression : filter ( scopeExpressions , not ( equalTo ( matchingCanonical ) ) ) ) { scopeEqualities . add ( new ComparisonExpression ( ComparisonExpression . Operator . EQUAL , matchingCanonical , expression ) ) ; } } Expression complementCanonical = getCanonical ( scopeComplementExpressions ) ; if ( scopeComplementExpressions . size ( ) >= 2 ) { for ( Expression expression : filter ( scopeComplementExpressions , not ( equalTo ( complementCanonical ) ) ) ) { scopeComplementEqualities . add ( new ComparisonExpression ( ComparisonExpression . Operator . EQUAL , complementCanonical , expression ) ) ; } } // Compile the scope straddling equality expressions
List < Expression > connectingExpressions = new ArrayList < > ( ) ; connectingExpressions . add ( matchingCanonical ) ; connectingExpressions . add ( complementCanonical ) ; connectingExpressions . addAll ( scopeStraddlingExpressions ) ; connectingExpressions = ImmutableList . copyOf ( filter ( connectingExpressions , Predicates . notNull ( ) ) ) ; Expression connectingCanonical = getCanonical ( connectingExpressions ) ; if ( connectingCanonical != null ) { for ( Expression expression : filter ( connectingExpressions , not ( equalTo ( connectingCanonical ) ) ) ) { scopeStraddlingEqualities . add ( new ComparisonExpression ( ComparisonExpression . Operator . EQUAL , connectingCanonical , expression ) ) ; } } } return new EqualityPartition ( scopeEqualities . build ( ) , scopeComplementEqualities . build ( ) , scopeStraddlingEqualities . build ( ) ) ; |
public class ConsentDecisionCouchDbRepository { /** * Find a consent decision by + long + ID and principal name . For CouchDb , this ID is randomly generated and the pair should be unique , with a very high
* probability , but is not guaranteed . This method is mostly only used by tests .
* @ param principal User to search for .
* @ param id decision id to search for .
* @ return First consent decision matching principal and id . */
@ View ( name = "by_principal_and_id" , map = "function(doc) {emit([doc.principal, doc.id], doc)}" ) public CouchDbConsentDecision findByPrincipalAndId ( final String principal , final long id ) { } } | val view = createQuery ( "by_principal_and_id" ) . key ( ComplexKey . of ( principal , id ) ) . limit ( 1 ) . includeDocs ( true ) ; return db . queryView ( view , CouchDbConsentDecision . class ) . stream ( ) . findFirst ( ) . orElse ( null ) ; |
public class CommercePriceListPersistenceImpl { /** * Removes all the commerce price lists where groupId = & # 63 ; and status & ne ; & # 63 ; from the database .
* @ param groupId the group ID
* @ param status the status */
@ Override public void removeByG_NotS ( long groupId , int status ) { } } | for ( CommercePriceList commercePriceList : findByG_NotS ( groupId , status , QueryUtil . ALL_POS , QueryUtil . ALL_POS , null ) ) { remove ( commercePriceList ) ; } |
public class WikiPageUtil { /** * Returns the encoded string - all special symbols will be replaced by
* % [ HEX HEX ] sequence , where [ HEX HEX ] is the hexadecimal code of the
* escaped symbol ( see RFC - 2616
* http : / / www . w3 . org / Protocols / rfc2616 / rfc2616 . html ) .
* @ param str the string to encode
* @ return the encoded string . */
public static String encodeHttpParams ( String str ) { } } | if ( str == null ) { return "" ; } StringBuffer buf = new StringBuffer ( ) ; char [ ] array = str . toCharArray ( ) ; for ( int i = 0 ; i < array . length ; i ++ ) { char ch = array [ i ] ; if ( ( ch >= 'a' && ch <= 'z' ) || ( ch >= 'A' && ch <= 'Z' ) || ( ch >= '0' && ch <= '9' ) || Character . isDigit ( ch ) || Arrays . binarySearch ( HTTP_RESERVED_SYMBOLS , ch ) >= 0 || Arrays . binarySearch ( HTTP_UNRESERVED_SYMBOLS , ch ) >= 0 ) { buf . append ( array [ i ] ) ; } else { buf . append ( "%" + Integer . toHexString ( array [ i ] ) ) ; } } return buf . toString ( ) ; |
public class HubVirtualNetworkConnectionsInner { /** * Retrieves the details of all HubVirtualNetworkConnections .
* @ param nextPageLink The NextLink from the previous successful call to List operation .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the observable to the PagedList & lt ; HubVirtualNetworkConnectionInner & gt ; object */
public Observable < Page < HubVirtualNetworkConnectionInner > > listNextAsync ( final String nextPageLink ) { } } | return listNextWithServiceResponseAsync ( nextPageLink ) . map ( new Func1 < ServiceResponse < Page < HubVirtualNetworkConnectionInner > > , Page < HubVirtualNetworkConnectionInner > > ( ) { @ Override public Page < HubVirtualNetworkConnectionInner > call ( ServiceResponse < Page < HubVirtualNetworkConnectionInner > > response ) { return response . body ( ) ; } } ) ; |
public class CommerceWarehouseUtil { /** * Removes the commerce warehouse with the primary key from the database . Also notifies the appropriate model listeners .
* @ param commerceWarehouseId the primary key of the commerce warehouse
* @ return the commerce warehouse that was removed
* @ throws NoSuchWarehouseException if a commerce warehouse with the primary key could not be found */
public static CommerceWarehouse remove ( long commerceWarehouseId ) throws com . liferay . commerce . exception . NoSuchWarehouseException { } } | return getPersistence ( ) . remove ( commerceWarehouseId ) ; |
public class MMAXAnnotation { /** * getter for attributeList - gets List of attributes of the MMAX annotation .
* @ generated
* @ return value of the feature */
public FSArray getAttributeList ( ) { } } | if ( MMAXAnnotation_Type . featOkTst && ( ( MMAXAnnotation_Type ) jcasType ) . casFeat_attributeList == null ) jcasType . jcas . throwFeatMissing ( "attributeList" , "de.julielab.jules.types.mmax.MMAXAnnotation" ) ; return ( FSArray ) ( jcasType . ll_cas . ll_getFSForRef ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( MMAXAnnotation_Type ) jcasType ) . casFeatCode_attributeList ) ) ) ; |
public class SchemaService { /** * Return the { @ link ApplicationDefinition } for the application in the given tenant .
* Null is returned if no application is found with the given name and tenant .
* @ return The { @ link ApplicationDefinition } for the given application or null if no
* no such application is defined in the default tenant . */
public ApplicationDefinition getApplication ( Tenant tenant , String appName ) { } } | checkServiceState ( ) ; return getApplicationDefinition ( tenant , appName ) ; |
public class AbstractMemberWriter { /** * Add the modifier for the member . The modifiers are ordered as specified
* by < em > The Java Language Specification < / em > .
* @ param member the member for which teh modifier will be added .
* @ param htmltree the content tree to which the modifier information will be added . */
protected void addModifiers ( Element member , Content htmltree ) { } } | Set < Modifier > set = new TreeSet < > ( member . getModifiers ( ) ) ; // remove the ones we really don ' t need
set . remove ( NATIVE ) ; set . remove ( SYNCHRONIZED ) ; set . remove ( STRICTFP ) ; // According to JLS , we should not be showing public modifier for
// interface methods .
if ( ( utils . isField ( member ) || utils . isMethod ( member ) ) && ( ( writer instanceof ClassWriterImpl && utils . isInterface ( ( ( ClassWriterImpl ) writer ) . getTypeElement ( ) ) || writer instanceof AnnotationTypeWriterImpl ) ) ) { // Remove the implicit abstract and public modifiers
if ( utils . isMethod ( member ) && ( utils . isInterface ( member . getEnclosingElement ( ) ) || utils . isAnnotationType ( member . getEnclosingElement ( ) ) ) ) { set . remove ( ABSTRACT ) ; set . remove ( PUBLIC ) ; } if ( ! utils . isMethod ( member ) ) { set . remove ( PUBLIC ) ; } } if ( ! set . isEmpty ( ) ) { String mods = set . stream ( ) . map ( Modifier :: toString ) . collect ( Collectors . joining ( " " ) ) ; htmltree . addContent ( mods ) ; htmltree . addContent ( Contents . SPACE ) ; } |
public class OpenTSDBMessageFormatter { /** * Add the tag ( s ) for typeNames .
* @ param result - the result of the JMX query .
* @ param resultString - current form of the metric string .
* @ return String - the updated metric string with the necessary tag ( s ) added . */
protected void addTypeNamesTags ( StringBuilder resultString , Result result ) { } } | if ( mergeTypeNamesTags ) { // Produce a single tag with all the TypeName keys concatenated and all the values joined with ' _ ' .
String typeNameValues = TypeNameValuesStringBuilder . getDefaultBuilder ( ) . build ( typeNames , result . getTypeName ( ) ) ; addTag ( resultString , StringUtils . join ( typeNames , "" ) , typeNameValues ) ; } else { Map < String , String > typeNameMap = TypeNameValue . extractMap ( result . getTypeName ( ) ) ; for ( String oneTypeName : typeNames ) { String value = typeNameMap . get ( oneTypeName ) ; if ( value == null ) value = "" ; addTag ( resultString , oneTypeName , value ) ; } } |
public class Curve25519 { /** * Calculates a Unique Curve25519 signature .
* @ param privateKey The private Curve25519 key to create the signature with .
* @ param message The message to sign .
* @ return A 96 - byte signature . */
public byte [ ] calculateVrfSignature ( byte [ ] privateKey , byte [ ] message ) { } } | if ( privateKey == null || privateKey . length != 32 ) { throw new IllegalArgumentException ( "Invalid private key!" ) ; } byte [ ] random = provider . getRandom ( 64 ) ; return provider . calculateVrfSignature ( random , privateKey , message ) ; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.