signature stringlengths 43 39.1k | implementation stringlengths 0 450k |
|---|---|
public class JodaAuditListener { /** * set audit informations , doesn ' t modify createdDate and createdBy once
* set . Only works with DomainObjects that implement the JodaAuditable
* interface . In other cases a IllegalArgumentException is thrown .
* @ param entity
* @ return */
@ PreUpdate @ PrePersist private void changeAuditInformation ( JodaAuditable auditableEntity ) { } } | DateTime lastUpdated = new DateTime ( ) ; auditableEntity . setLastUpdated ( lastUpdated ) ; String lastUpdatedBy = ServiceContextStore . getCurrentUser ( ) ; auditableEntity . setLastUpdatedBy ( lastUpdatedBy ) ; if ( auditableEntity . getCreatedDate ( ) == null ) auditableEntity . setCreatedDate ( lastUpdated ) ; if ( auditableEntity . getCreatedBy ( ) == null ) auditableEntity . setCreatedBy ( lastUpdatedBy ) ; |
public class KafkaWorkUnitPacker { /** * Pack a list of { @ link WorkUnit } s into a smaller number of { @ link MultiWorkUnit } s ,
* using the worst - fit - decreasing algorithm .
* Each { @ link WorkUnit } is assigned to the { @ link MultiWorkUnit } with the smallest load . */
protected List < WorkUnit > worstFitDecreasingBinPacking ( List < WorkUnit > groups , int numOfMultiWorkUnits ) { } } | // Sort workunit groups by data size desc
Collections . sort ( groups , LOAD_DESC_COMPARATOR ) ; MinMaxPriorityQueue < MultiWorkUnit > pQueue = MinMaxPriorityQueue . orderedBy ( LOAD_ASC_COMPARATOR ) . expectedSize ( numOfMultiWorkUnits ) . create ( ) ; for ( int i = 0 ; i < numOfMultiWorkUnits ; i ++ ) { MultiWorkUnit multiWorkUnit = MultiWorkUnit . createEmpty ( ) ; setWorkUnitEstSize ( multiWorkUnit , 0 ) ; pQueue . add ( multiWorkUnit ) ; } for ( WorkUnit group : groups ) { MultiWorkUnit lightestMultiWorkUnit = pQueue . poll ( ) ; addWorkUnitToMultiWorkUnit ( group , lightestMultiWorkUnit ) ; pQueue . add ( lightestMultiWorkUnit ) ; } LinkedList < MultiWorkUnit > pQueue_filtered = new LinkedList ( ) ; while ( ! pQueue . isEmpty ( ) ) { MultiWorkUnit multiWorkUnit = pQueue . poll ( ) ; if ( multiWorkUnit . getWorkUnits ( ) . size ( ) != 0 ) { pQueue_filtered . offer ( multiWorkUnit ) ; } } logMultiWorkUnitInfo ( pQueue_filtered ) ; double minLoad = getWorkUnitEstLoad ( pQueue_filtered . peekFirst ( ) ) ; double maxLoad = getWorkUnitEstLoad ( pQueue_filtered . peekLast ( ) ) ; LOG . info ( String . format ( "Min load of multiWorkUnit = %f; Max load of multiWorkUnit = %f; Diff = %f%%" , minLoad , maxLoad , ( maxLoad - minLoad ) / maxLoad * 100.0 ) ) ; this . state . setProp ( MIN_MULTIWORKUNIT_LOAD , minLoad ) ; this . state . setProp ( MAX_MULTIWORKUNIT_LOAD , maxLoad ) ; List < WorkUnit > multiWorkUnits = Lists . newArrayList ( ) ; multiWorkUnits . addAll ( pQueue_filtered ) ; return multiWorkUnits ; |
public class JSONHelpers { /** * Returns { @ link String } value mapped to { @ code e } , or the empty string if the mapping doesn ' t
* exist .
* @ param json
* @ param e
* @ return */
public static < P extends Enum < P > > String optString ( final JSONObject json , P e ) { } } | return json . optString ( e . name ( ) ) ; |
public class ImageTileSkin { /** * * * * * * Initialization * * * * * */
@ Override protected void initGraphics ( ) { } } | super . initGraphics ( ) ; imageListener = ( o , ov , nv ) -> { if ( nv != null ) { imgView . setImage ( tile . getImage ( ) ) ; } } ; titleText = new Text ( ) ; titleText . setFill ( tile . getTitleColor ( ) ) ; Helper . enableNode ( titleText , ! tile . getTitle ( ) . isEmpty ( ) ) ; text = new Text ( tile . getText ( ) ) ; text . setFill ( tile . getTextColor ( ) ) ; Helper . enableNode ( text , tile . isTextVisible ( ) ) ; imgView = new ImageView ( tile . getImage ( ) ) ; roundFrame = new Circle ( ) ; roundFrame . setFill ( Color . TRANSPARENT ) ; rectangularFrame = new Rectangle ( ) ; rectangularFrame . setFill ( Color . TRANSPARENT ) ; graphicContainer = new StackPane ( ) ; graphicContainer . setMinSize ( size * 0.9 , tile . isTextVisible ( ) ? size * 0.72 : size * 0.795 ) ; graphicContainer . setMaxSize ( size * 0.9 , tile . isTextVisible ( ) ? size * 0.72 : size * 0.795 ) ; graphicContainer . setPrefSize ( size * 0.9 , tile . isTextVisible ( ) ? size * 0.72 : size * 0.795 ) ; graphicContainer . getChildren ( ) . setAll ( roundFrame , rectangularFrame , imgView ) ; getPane ( ) . getChildren ( ) . addAll ( titleText , graphicContainer , text ) ; |
public class UserService { /** * Retrieves the user corresponding to the given AuthenticatedUser from the
* database .
* @ param authenticationProvider
* The AuthenticationProvider on behalf of which the user is being
* retrieved .
* @ param authenticatedUser
* The AuthenticatedUser to retrieve the corresponding ModeledUser of .
* @ return
* The ModeledUser which corresponds to the given AuthenticatedUser , or
* null if no such user exists .
* @ throws GuacamoleException
* If a ModeledUser object for the user corresponding to the given
* AuthenticatedUser cannot be created . */
public ModeledUser retrieveUser ( AuthenticationProvider authenticationProvider , AuthenticatedUser authenticatedUser ) throws GuacamoleException { } } | // If we already queried this user , return that rather than querying again
if ( authenticatedUser instanceof ModeledAuthenticatedUser ) return ( ( ModeledAuthenticatedUser ) authenticatedUser ) . getUser ( ) ; // Get username
String username = authenticatedUser . getIdentifier ( ) ; // Retrieve corresponding user model , if such a user exists
UserModel userModel = userMapper . selectOne ( username ) ; if ( userModel == null ) return null ; // Create corresponding user object , set up cyclic reference
ModeledUser user = getObjectInstance ( null , userModel ) ; user . setCurrentUser ( new ModeledAuthenticatedUser ( authenticatedUser , authenticationProvider , user ) ) ; // Return already - authenticated user
return user ; |
public class SSLConfiguration { /** * Creates the trust managers required to initiate the { @ link SSLContext } , using a JKS keystore as an input .
* @ param filepath - the path to the JKS keystore .
* @ param keystorePassword - the keystore ' s password .
* @ return { @ link TrustManager } array , that will be used to initiate the { @ link SSLContext } .
* @ throws Exception */
private static TrustManagerFactory createTrustManagers ( String filepath , String keystorePassword ) throws KeyStoreException , FileNotFoundException , IOException , NoSuchAlgorithmException , CertificateException { } } | KeyStore trustStore = KeyStore . getInstance ( "JKS" ) ; try ( InputStream trustStoreIS = new FileInputStream ( filepath ) ) { trustStore . load ( trustStoreIS , keystorePassword . toCharArray ( ) ) ; } TrustManagerFactory trustFactory = TrustManagerFactory . getInstance ( TrustManagerFactory . getDefaultAlgorithm ( ) ) ; trustFactory . init ( trustStore ) ; return trustFactory ; |
public class NetworkConfig { /** * Returns the specified JsonValue as a String , or null if it ' s not a string */
private static String getJsonValueAsString ( JsonValue value ) { } } | return ( value != null && value . getValueType ( ) == ValueType . STRING ) ? ( ( JsonString ) value ) . getString ( ) : null ; |
public class XmpDirectory { /** * Gets a map of all XMP properties in this directory .
* This is required because XMP properties are represented as strings , whereas the rest of this library
* uses integers for keys . */
@ NotNull public Map < String , String > getXmpProperties ( ) { } } | Map < String , String > propertyValueByPath = new HashMap < String , String > ( ) ; if ( _xmpMeta != null ) { try { IteratorOptions options = new IteratorOptions ( ) . setJustLeafnodes ( true ) ; for ( Iterator i = _xmpMeta . iterator ( options ) ; i . hasNext ( ) ; ) { XMPPropertyInfo prop = ( XMPPropertyInfo ) i . next ( ) ; String path = prop . getPath ( ) ; String value = prop . getValue ( ) ; if ( path != null && value != null ) { propertyValueByPath . put ( path , value ) ; } } } catch ( XMPException ignored ) { } } return Collections . unmodifiableMap ( propertyValueByPath ) ; |
public class ModuleWebhooks { /** * Change the content of a webhook .
* This will take the webhooks id and update it on the backend .
* @ param webhook The webhook retrieved beforehand to be changed .
* @ return The from the backend returned , changed webhook .
* @ throws IllegalArgumentException if webhook is null .
* @ throws IllegalArgumentException if webhookId is null .
* @ throws IllegalArgumentException if spaceId is null .
* @ throws IllegalArgumentException if version is null . */
public CMAWebhook update ( CMAWebhook webhook ) { } } | assertNotNull ( webhook , "webhook" ) ; final String webhookId = getResourceIdOrThrow ( webhook , "webhook" ) ; final String spaceId = getSpaceIdOrThrow ( webhook , "webhook" ) ; final Integer version = getVersionOrThrow ( webhook , "webhook" ) ; return service . update ( version , spaceId , webhookId , webhook ) . blockingFirst ( ) ; |
public class ObjectUtil { /** * 判断指定对象是否为空 , 支持 :
* < pre >
* 1 . CharSequence
* 2 . Map
* 3 . Iterable
* 4 . Iterator
* 5 . Array
* < / pre >
* @ param obj 被判断的对象
* @ return 是否为空 , 如果类型不支持 , 返回false
* @ since 4.5.7 */
@ SuppressWarnings ( "rawtypes" ) public static boolean isEmpty ( Object obj ) { } } | if ( null == obj ) { return true ; } if ( obj instanceof CharSequence ) { return StrUtil . isEmpty ( ( CharSequence ) obj ) ; } else if ( obj instanceof Map ) { return MapUtil . isEmpty ( ( Map ) obj ) ; } else if ( obj instanceof Iterable ) { return IterUtil . isEmpty ( ( Iterable ) obj ) ; } else if ( obj instanceof Iterator ) { return IterUtil . isEmpty ( ( Iterator ) obj ) ; } else if ( ArrayUtil . isArray ( obj ) ) { return ArrayUtil . isEmpty ( obj ) ; } return false ; |
public class BackchannelAuthenticationRequest { /** * Set the value of { @ code parameters } which are the request parameters
* that the backchannel authentication endpoint of the OpenID provider
* implementation received from the client application .
* This method converts the given map into a string in
* { @ code application / x - www - form - urlencoded } and passes it to
* { @ link # setParameters ( String ) } method .
* @ param parameters
* Request parameters .
* @ return
* { @ code this } object . */
public BackchannelAuthenticationRequest setParameters ( Map < String , String [ ] > parameters ) { } } | return setParameters ( URLCoder . formUrlEncode ( parameters ) ) ; |
public class TSSConfigHelper { /** * Returns a TSSConfig object initialized with the input object
* as an XML string .
* @ param addrMap TODO
* @ return a TSSConfig object
* @ throws org . apache . geronimo . common . propertyeditor . PropertyEditorException
* An IOException occured . */
public static TSSConfig getTSSConfig ( Map < String , Object > props , Map < OptionsKey , List < TransportAddress > > addrMap , Bundle bundle ) throws Exception { } } | TSSConfig tssConfig = new TSSConfig ( ) ; List < Map < String , Object > > tssConfigs = Nester . nest ( CSIV2_CONFIGURATION , props ) ; if ( ! tssConfigs . isEmpty ( ) ) { Map < String , Object > properties = tssConfigs . get ( 0 ) ; // tssConfig . setInherit ( ( Boolean ) properties . get ( INHERIT ) ) ;
List < Map < String , Object > > mechList = Nester . nest ( COMPOUND_SEC_MECH_TYPE_LIST , properties ) ; // TODO liberty get the ssl transport info from the corbabean ?
// List < Map < String , Object > > transportMechGroups = mechInfo . get ( SSL _ OPTIONS ) ;
// if ( ! transportMechGroups . isEmpty ( ) ) {
// Map < String , Object > transportMechGroup = transportMechGroups . get ( 0 ) ;
// String type = ( String ) transportMechGroup . get ( CONFIG _ REFERENCE _ TYPE ) ;
// if ( SSL _ TRANSPORT _ MECH . equals ( type ) ) {
// tssConfig . setTransport _ mech ( extractSSL ( transportMechGroup ) ) ;
// } else if ( SECIOP _ TRANSPORT _ MECH . equals ( type ) ) {
// throw new IllegalStateException ( " SECIOP processing not implemented " ) ;
// } else {
// throw new IllegalStateException ( " Unrecognized transport mech type : " + type ) ;
// } else {
// tssConfig . setTransport _ mech ( new TSSNULLTransportConfig ( ) ) ;
// List < Map < String , Object > > secmechlists = mechInfo . get ( COMPOUND _ SEC _ MECH _ TYPE _ LIST ) ;
// if ( ! secmechlists . isEmpty ( ) ) {
// Map < String , Object > secMechList = secmechlists . get ( 0 ) ;
TSSCompoundSecMechListConfig mechListConfig = tssConfig . getMechListConfig ( ) ; mechListConfig . setStateful ( ( Boolean ) properties . get ( STATEFUL ) ) ; // List < Map < String , Object > > mechList = Nester . nest ( COMPOUND _ SECH _ MECH _ LIST , secMechList ) ;
for ( Map < String , Object > mech : mechList ) { TSSCompoundSecMechConfig cMech = extractCompoundSecMech ( mech , addrMap , bundle ) ; // cMech . setTransport _ mech ( tssConfig . getTransport _ mech ( ) ) ;
mechListConfig . add ( cMech ) ; } } return tssConfig ; |
public class RedisClient { /** * On release connection .
* @ param connection
* redis connection instance . */
private void onCleanup ( Object connection ) { } } | // if not running within transaction boundary
if ( this . connection != null ) { if ( settings != null ) { ( ( Jedis ) connection ) . configResetStat ( ) ; } factory . releaseConnection ( ( Jedis ) this . connection ) ; } this . connection = null ; |
public class MathBindings { /** * Binding for { @ link java . lang . Math # log ( double ) }
* @ param a a value
* @ return the value ln & nbsp ; { @ code a } , the natural logarithm of
* { @ code a } . */
public static DoubleBinding log ( final ObservableDoubleValue a ) { } } | return createDoubleBinding ( ( ) -> Math . log ( a . get ( ) ) , a ) ; |
public class SinglePerturbationNeighbourhood { /** * Check if it is possible to swap a selected and unselected item .
* @ param solution solution for which moves are generated
* @ param addCandidates set of candidate IDs to be added
* @ param deleteCandidates set of candidate IDs to be deleted
* @ return < code > true < / code > if it is possible to perform a swap */
private boolean canSwap ( SubsetSolution solution , Set < Integer > addCandidates , Set < Integer > deleteCandidates ) { } } | return ! addCandidates . isEmpty ( ) && ! deleteCandidates . isEmpty ( ) && isValidSubsetSize ( solution . getNumSelectedIDs ( ) ) ; |
public class SnapshotTaskClientImpl { /** * { @ inheritDoc } */
@ Override public CleanupSnapshotTaskResult cleanupSnapshot ( String spaceId ) throws ContentStoreException { } } | CleanupSnapshotTaskParameters taskParams = new CleanupSnapshotTaskParameters ( ) ; taskParams . setSpaceId ( spaceId ) ; String taskResult = contentStore . performTask ( SnapshotConstants . CLEANUP_SNAPSHOT_TASK_NAME , taskParams . serialize ( ) ) ; return CleanupSnapshotTaskResult . deserialize ( taskResult ) ; |
public class InternationalizationServiceSingleton { /** * A bundle is being added to the { @ code BundleTracker } .
* This method is called before a bundle which matched the search parameters
* of the { @ code BundleTracker } is added to the
* { @ code BundleTracker } . This method should return the object to be
* tracked for the specified { @ code Bundle } . The returned object is
* stored in the { @ code BundleTracker } and is available from the
* { @ link org . osgi . util . tracker . BundleTracker # getObject ( org . osgi . framework . Bundle ) getObject } method .
* @ param bundle The { @ code Bundle } being added to the
* { @ code BundleTracker } .
* @ param event The bundle event which caused this customizer method to be
* called or { @ code null } if there is no bundle event associated
* with the call to this method .
* @ return The object to be tracked for the specified { @ code Bundle }
* object or { @ code null } if the specified { @ code Bundle }
* object should not be tracked . */
@ Override public List < I18nExtension > addingBundle ( Bundle bundle , BundleEvent event ) { } } | List < I18nExtension > list = ExtenderUtils . analyze ( "/i18n/" , bundle ) ; if ( list . isEmpty ( ) ) { return null ; } String current = Long . toString ( System . currentTimeMillis ( ) ) ; LOGGER . info ( list . size ( ) + " resource bundle(s) loaded from {} ({})" , bundle . getSymbolicName ( ) , bundle . getBundleId ( ) ) ; for ( I18nExtension extension : list ) { extensions . add ( extension ) ; etags . put ( extension . locale ( ) , current ) ; } return list ; |
public class AgentsAlreadyRunningAssessmentException { /** * @ return */
@ com . fasterxml . jackson . annotation . JsonProperty ( "agents" ) public java . util . List < AgentAlreadyRunningAssessment > getAgents ( ) { } } | return agents ; |
public class StringHelper { /** * Get a concatenated String from all elements of the passed map , separated by
* the specified separator strings .
* @ param sSepOuter
* The separator to use for separating the map entries . May not be
* < code > null < / code > .
* @ param sSepInner
* The separator to use for separating the key from the value . May not be
* < code > null < / code > .
* @ param aElements
* The map to convert . May be < code > null < / code > or empty .
* @ return The concatenated string .
* @ param < KEYTYPE >
* Map key type
* @ param < VALUETYPE >
* Map value type */
@ Nonnull public static < KEYTYPE , VALUETYPE > String getImploded ( @ Nonnull final String sSepOuter , @ Nonnull final String sSepInner , @ Nullable final Map < KEYTYPE , VALUETYPE > aElements ) { } } | return getImplodedMapped ( sSepOuter , sSepInner , aElements , String :: valueOf , String :: valueOf ) ; |
public class Force { /** * Increase direction with input value .
* @ param extrp The extrapolation value .
* @ param direction The direction to add . */
public void addDirection ( double extrp , Direction direction ) { } } | addDirection ( extrp , direction . getDirectionHorizontal ( ) , direction . getDirectionVertical ( ) ) ; |
public class FFDCLogger { /** * Appends a single line of FFDC information .
* @ param info the information to add .
* @ return this FFDC logger . */
public final FFDCLogger append ( String info ) { } } | lines . add ( new StringBuffer ( ) . append ( info ) . append ( AdapterUtil . EOLN ) . toString ( ) ) ; return this ; |
public class Tags { /** * Return a new { @ code Tags } instance by concatenating the specified tags and key / value pairs .
* @ param tags the first set of tags
* @ param keyValues the additional key / value pairs to add
* @ return the merged tags */
public static Tags concat ( @ Nullable Iterable < ? extends Tag > tags , @ Nullable String ... keyValues ) { } } | return Tags . of ( tags ) . and ( keyValues ) ; |
public class LToDblFunctionBuilder { /** * One of ways of creating builder . This is possibly the least verbose way where compiler should be able to guess the generic parameters . */
@ Nonnull public static < T > LToDblFunction < T > toDblFunctionFrom ( Consumer < LToDblFunctionBuilder < T > > buildingFunction ) { } } | LToDblFunctionBuilder builder = new LToDblFunctionBuilder ( ) ; buildingFunction . accept ( builder ) ; return builder . build ( ) ; |
public class OMVRBTree { /** * Returns the key corresponding to the specified Entry .
* @ throws NoSuchElementException
* if the Entry is null */
static < K > K key ( OMVRBTreeEntry < K , ? > e ) { } } | if ( e == null ) throw new NoSuchElementException ( ) ; return e . getKey ( ) ; |
public class L1Regularizer { /** * Estimates the penalty by adding the L1 regularization .
* @ param l1
* @ param weights
* @ param < K >
* @ return */
public static < K > double estimatePenalty ( double l1 , Map < K , Double > weights ) { } } | double penalty = 0.0 ; if ( l1 > 0.0 ) { double sumAbsWeights = 0.0 ; for ( double w : weights . values ( ) ) { sumAbsWeights += Math . abs ( w ) ; } penalty = l1 * sumAbsWeights ; } return penalty ; |
public class CommerceOrderItemUtil { /** * Returns the first commerce order item in the ordered set where commerceOrderId = & # 63 ; and subscription = & # 63 ; .
* @ param commerceOrderId the commerce order ID
* @ param subscription the subscription
* @ param orderByComparator the comparator to order the set by ( optionally < code > null < / code > )
* @ return the first matching commerce order item
* @ throws NoSuchOrderItemException if a matching commerce order item could not be found */
public static CommerceOrderItem findByC_S_First ( long commerceOrderId , boolean subscription , OrderByComparator < CommerceOrderItem > orderByComparator ) throws com . liferay . commerce . exception . NoSuchOrderItemException { } } | return getPersistence ( ) . findByC_S_First ( commerceOrderId , subscription , orderByComparator ) ; |
public class NetworkInterfacesInner { /** * Gets information about the specified network interface .
* @ param resourceGroupName The name of the resource group .
* @ param networkInterfaceName The name of the network interface .
* @ 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 NetworkInterfaceInner object if successful . */
public NetworkInterfaceInner getByResourceGroup ( String resourceGroupName , String networkInterfaceName ) { } } | return getByResourceGroupWithServiceResponseAsync ( resourceGroupName , networkInterfaceName ) . toBlocking ( ) . single ( ) . body ( ) ; |
public class OCDImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
@ Override public void eUnset ( int featureID ) { } } | switch ( featureID ) { case AfplibPackage . OCD__OBJ_CDAT : setObjCdat ( OBJ_CDAT_EDEFAULT ) ; return ; } super . eUnset ( featureID ) ; |
public class JsonReader { /** * Check if the passed reader can be resembled to valid Json content . This is
* accomplished by fully parsing the Json each time the method is called . This
* consumes < b > less memory < / b > than calling any of the < code > read . . . < / code >
* methods and checking for a non - < code > null < / code > result .
* @ param aReader
* The reader to use . May not be < code > null < / code > .
* @ return < code > true < / code > if the Json is valid according to the version ,
* < code > false < / code > if not */
public static boolean isValidJson ( @ Nonnull @ WillClose final Reader aReader ) { } } | ValueEnforcer . notNull ( aReader , "Reader" ) ; return _validateJson ( StreamHelper . getBuffered ( aReader ) ) . isValid ( ) ; |
public class TypeAnnotationPosition { /** * Create a { @ code TypeAnnotationPosition } for a method receiver parameter .
* @ param location The type path .
* @ param onLambda The lambda for this parameter .
* @ param pos The position from the associated tree node . */
public static TypeAnnotationPosition methodReceiver ( final List < TypePathEntry > location , final JCLambda onLambda , final int pos ) { } } | return new TypeAnnotationPosition ( TargetType . METHOD_RECEIVER , pos , Integer . MIN_VALUE , onLambda , Integer . MIN_VALUE , Integer . MIN_VALUE , location ) ; |
public class UndecidedNode { /** * Compress this tree into the AutoBuffer */
@ Override public AutoBuffer compress ( AutoBuffer ab , AutoBuffer abAux ) { } } | int pos = ab . position ( ) ; if ( _nodeType == 0 ) size ( ) ; // Sets _ nodeType & _ size both
ab . put1 ( _nodeType ) ; // Includes left - child skip - size bits
assert _split != null ; // Not a broken root non - decision ?
assert _split . _col >= 0 ; ab . put2 ( ( short ) _split . _col ) ; ab . put1 ( ( byte ) _split . _nasplit . value ( ) ) ; // Save split - at - value or group
if ( _split . _nasplit != DHistogram . NASplitDir . NAvsREST ) { if ( _split . _equal == 0 || _split . _equal == 1 ) ab . put4f ( _splat ) ; else if ( _split . _equal == 2 ) _split . _bs . compress2 ( ab ) ; else _split . _bs . compress3 ( ab ) ; } if ( abAux != null ) { abAux . put4 ( _nid ) ; abAux . put4 ( _tree . node ( _nids [ 0 ] ) . numNodes ( ) ) ; // number of nodes in the left subtree ; this used to be ' parent node id '
abAux . put4f ( ( float ) _split . _n0 ) ; abAux . put4f ( ( float ) _split . _n1 ) ; abAux . put4f ( ( float ) _split . _p0 ) ; abAux . put4f ( ( float ) _split . _p1 ) ; abAux . put4f ( ( float ) _split . _se0 ) ; abAux . put4f ( ( float ) _split . _se1 ) ; abAux . put4 ( _nids [ 0 ] ) ; abAux . put4 ( _nids [ 1 ] ) ; } Node left = _tree . node ( _nids [ 0 ] ) ; if ( ( _nodeType & 48 ) == 0 ) { // Size bits are optional for left leaves !
int sz = left . size ( ) ; if ( sz < 256 ) ab . put1 ( sz ) ; else if ( sz < 65535 ) ab . put2 ( ( short ) sz ) ; else if ( sz < ( 1 << 24 ) ) ab . put3 ( sz ) ; else ab . put4 ( sz ) ; // 1 < < 31-1
} // now write the subtree in
left . compress ( ab , abAux ) ; Node rite = _tree . node ( _nids [ 1 ] ) ; rite . compress ( ab , abAux ) ; assert _size == ab . position ( ) - pos : "reported size = " + _size + " , real size = " + ( ab . position ( ) - pos ) ; return ab ; |
public class FacesImpl { /** * Divide candidate faces into groups based on face similarity .
* @ param faceIds Array of candidate faceId created by Face - Detect . The maximum is 1000 faces
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ throws APIErrorException thrown if the request is rejected by server
* @ throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @ return the GroupResult object if successful . */
public GroupResult group ( List < UUID > faceIds ) { } } | return groupWithServiceResponseAsync ( faceIds ) . toBlocking ( ) . single ( ) . body ( ) ; |
public class ProteinModificationRegistry { /** * Lazy Initialization the static variables and register common modifications .
* just opens the stream to ptm _ list . xml and delegates to lazyInit ( InputStream ) for parsing . */
private static synchronized void lazyInit ( ) { } } | if ( registry == null ) { InputStream isXml = ProteinModification . class . getResourceAsStream ( DIR_XML_PTM_LIST ) ; lazyInit ( isXml ) ; } |
public class AgentPreviewMarshaller { /** * Marshall the given parameter object . */
public void marshall ( AgentPreview agentPreview , ProtocolMarshaller protocolMarshaller ) { } } | if ( agentPreview == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( agentPreview . getHostname ( ) , HOSTNAME_BINDING ) ; protocolMarshaller . marshall ( agentPreview . getAgentId ( ) , AGENTID_BINDING ) ; protocolMarshaller . marshall ( agentPreview . getAutoScalingGroup ( ) , AUTOSCALINGGROUP_BINDING ) ; protocolMarshaller . marshall ( agentPreview . getAgentHealth ( ) , AGENTHEALTH_BINDING ) ; protocolMarshaller . marshall ( agentPreview . getAgentVersion ( ) , AGENTVERSION_BINDING ) ; protocolMarshaller . marshall ( agentPreview . getOperatingSystem ( ) , OPERATINGSYSTEM_BINDING ) ; protocolMarshaller . marshall ( agentPreview . getKernelVersion ( ) , KERNELVERSION_BINDING ) ; protocolMarshaller . marshall ( agentPreview . getIpv4Address ( ) , IPV4ADDRESS_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class AVIMImageMessage { /** * 获取图片的宽度
* @ return */
public int getWidth ( ) { } } | Map < String , Object > metaData = getFileMetaData ( ) ; if ( metaData != null && metaData . containsKey ( IMAGE_WIDTH ) ) { return parseIntValue ( metaData . get ( IMAGE_WIDTH ) ) ; } return 0 ; |
public class QueryExecuter { /** * Gets the elements in the common upstream or downstream of the seed
* @ param sourceSet Seed to the query
* @ param model BioPAX model
* @ param direction UPSTREAM or DOWNSTREAM
* @ param limit Length limit for the search
* @ param filters for filtering graph elements
* @ return BioPAX elements in the result */
public static Set < BioPAXElement > runCommonStream ( Set < BioPAXElement > sourceSet , Model model , Direction direction , int limit , Filter ... filters ) { } } | Graph graph ; if ( model . getLevel ( ) == BioPAXLevel . L3 ) { graph = new GraphL3 ( model , filters ) ; } else return Collections . emptySet ( ) ; Collection < Set < Node > > source = prepareNodeSets ( sourceSet , graph ) ; if ( sourceSet . size ( ) < 2 ) return Collections . emptySet ( ) ; CommonStreamQuery query = new CommonStreamQuery ( source , direction , limit ) ; Set < GraphObject > resultWrappers = query . run ( ) ; return convertQueryResult ( resultWrappers , graph , false ) ; |
public class StringUtils { /** * < p > Splits the provided text into an array , separator specified .
* This is an alternative to using StringTokenizer . < / p >
* < p > The separator is not included in the returned String array .
* Adjacent separators are treated as one separator .
* For more control over the split use the StrTokenizer class . < / p >
* < p > A { @ code null } input String returns { @ code null } . < / p >
* < pre >
* StringUtils . split ( null , * ) = null
* StringUtils . split ( " " , * ) = [ ]
* StringUtils . split ( " a . b . c " , ' . ' ) = [ " a " , " b " , " c " ]
* StringUtils . split ( " a . . b . c " , ' . ' ) = [ " a " , " b " , " c " ]
* StringUtils . split ( " a : b : c " , ' . ' ) = [ " a : b : c " ]
* StringUtils . split ( " a b c " , ' ' ) = [ " a " , " b " , " c " ]
* < / pre >
* @ param str the String to parse , may be null
* @ param separatorChar the character used as the delimiter
* @ return an list of parsed Strings , { @ code null } if null String input */
public static List < String > split ( String str , char separatorChar ) { } } | List < String > list = new ArrayList < String > ( ) ; if ( str == null || str . length ( ) == 0 ) { return list ; } if ( str . indexOf ( separatorChar ) == - 1 ) { list . add ( str ) ; return list ; } int start = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( str . charAt ( i ) == separatorChar ) { String token = str . substring ( start , i ) . trim ( ) ; if ( token . length ( ) > 0 ) { list . add ( token ) ; } start = i + 1 ; } } String token = str . substring ( start , str . length ( ) ) . trim ( ) ; if ( token . length ( ) > 0 ) { list . add ( token ) ; } return list ; |
public class HtmlBuilder { /** * Build a HTML Table with given CSS class for a string .
* Use this method if given content contains HTML snippets , prepared with { @ link HtmlBuilder # htmlEncode ( String ) } .
* @ param clazz class for table element
* @ param content content string
* @ return HTML table element as string */
public static String tableClassHtmlContent ( String clazz , String ... content ) { } } | return tagClassHtmlContent ( Html . Tag . TABLE , clazz , content ) ; |
public class DrawerItem { /** * Sets an image mode to the drawer item
* @ param imageMode Image mode to set */
public DrawerItem setImageMode ( int imageMode ) { } } | if ( imageMode != ICON && imageMode != AVATAR && imageMode != SMALL_AVATAR ) { throw new IllegalArgumentException ( "Image mode must be either ICON or AVATAR." ) ; } mImageMode = imageMode ; notifyDataChanged ( ) ; return this ; |
public class CollectionUtilsImpl { /** * { @ inheritDoc } */
public < T > void forAllDoSynchronized ( final Collection < ? extends T > collection , final Closure < T > closure ) { } } | synchronized ( collection ) { forAllDo ( collection , closure ) ; } |
public class CmsPublishEngine { /** * Returns a publish job based on its publish history id . < p >
* The returned publish job may be an enqueued , running or finished publish job . < p >
* @ param publishHistoryId the publish history id to search for
* @ return the publish job with the given publish history id , or < code > null < / code > */
public CmsPublishJobBase getJobByPublishHistoryId ( CmsUUID publishHistoryId ) { } } | // try current running job
if ( ( m_currentPublishThread != null ) && m_currentPublishThread . getPublishJob ( ) . getPublishHistoryId ( ) . equals ( publishHistoryId ) ) { return new CmsPublishJobRunning ( m_currentPublishThread . getPublishJob ( ) ) ; } // try enqueued jobs
Iterator < CmsPublishJobEnqueued > itEnqueuedJobs = getPublishQueue ( ) . asList ( ) . iterator ( ) ; while ( itEnqueuedJobs . hasNext ( ) ) { CmsPublishJobEnqueued enqueuedJob = itEnqueuedJobs . next ( ) ; if ( enqueuedJob . getPublishList ( ) . getPublishHistoryId ( ) . equals ( publishHistoryId ) ) { return enqueuedJob ; } } // try finished jobs
Iterator < CmsPublishJobFinished > itFinishedJobs = getPublishHistory ( ) . asList ( ) . iterator ( ) ; while ( itFinishedJobs . hasNext ( ) ) { CmsPublishJobFinished finishedJob = itFinishedJobs . next ( ) ; if ( finishedJob . getPublishHistoryId ( ) . equals ( publishHistoryId ) ) { return finishedJob ; } } return null ; |
public class SpectatorExecutionInterceptor { /** * For network errors there will not be a response so the status will not have been set . This
* method looks for a flag in the attributes to see if we need to close off the log entry for
* the attempt . */
private boolean isStatusSet ( ExecutionAttributes attrs ) { } } | Boolean s = attrs . getAttribute ( STATUS_IS_SET ) ; return s != null && s ; |
public class ProcfsBasedProcessTree { /** * Make sure that the given pid is a process group leader and then
* destroy the process group .
* @ param pgrpId Process group id of to - be - killed - processes
* @ param interval The time to wait before sending SIGKILL
* after sending SIGTERM
* @ param inBackground Process is to be killed in the back ground with
* a separate thread */
public static void assertAndDestroyProcessGroup ( String pgrpId , long interval , boolean inBackground ) throws IOException { } } | // Make sure that the pid given is a process group leader
if ( ! checkPidPgrpidForMatch ( pgrpId , PROCFS ) ) { throw new IOException ( "Process with PID " + pgrpId + " is not a process group leader." ) ; } destroyProcessGroup ( pgrpId , interval , inBackground ) ; |
public class NamingLookupResponseCodec { /** * Decodes bytes to an iterable of name assignments .
* @ param buf the byte array
* @ return a naming lookup response
* @ throws org . apache . reef . io . network . naming . exception . NamingRuntimeException */
@ Override public NamingLookupResponse decode ( final byte [ ] buf ) { } } | final AvroNamingLookupResponse avroResponse = AvroUtils . fromBytes ( buf , AvroNamingLookupResponse . class ) ; final List < NameAssignment > nas = new ArrayList < > ( avroResponse . getTuples ( ) . size ( ) ) ; for ( final AvroNamingAssignment tuple : avroResponse . getTuples ( ) ) { nas . add ( new NameAssignmentTuple ( factory . getNewInstance ( tuple . getId ( ) . toString ( ) ) , new InetSocketAddress ( tuple . getHost ( ) . toString ( ) , tuple . getPort ( ) ) ) ) ; } return new NamingLookupResponse ( nas ) ; |
public class QueryDSL { /** * < p > parse . < / p >
* @ param expression a { @ link java . lang . String } object .
* @ return a { @ link java . util . List } object . */
public static List < QueryExprMeta > parse ( String expression ) { } } | QueryParser parser = parser ( tokens ( expression ) ) ; try { return parse ( parser ) ; } catch ( ParseCancellationException | RecognitionException e ) { RecognitionException err ; if ( e instanceof ParseCancellationException ) { err = ( RecognitionException ) e . getCause ( ) ; } else { err = ( RecognitionException ) e ; } throw new QuerySyntaxException ( Messages . get ( "dsl.parse.err" , err . getOffendingToken ( ) . getCharPositionInLine ( ) ) , e ) ; } |
public class PactDslJsonArray { /** * Element that must be a boolean
* @ param example example boolean to use for generated bodies */
public PactDslJsonArray booleanType ( Boolean example ) { } } | body . put ( example ) ; matchers . addRule ( rootPath + appendArrayIndex ( 0 ) , TypeMatcher . INSTANCE ) ; return this ; |
public class AsyncFile { /** * Checks the file size . For non - regular or non - existing files returns < code > null < / code > .
* @ param executor executor for running tasks in another thread
* @ param path the path of the file to check
* @ return file size if given path is a regular file and < code > null < / code > if it is a directory or it does not exist */
public static Promise < Long > size ( Executor executor , Path path ) { } } | return Promise . ofBlockingCallable ( executor , ( ) -> Files . isRegularFile ( path ) ? Files . size ( path ) : null ) ; |
public class AddJobFlowStepsRequest { /** * A list of < a > StepConfig < / a > to be executed by the job flow .
* < b > NOTE : < / b > This method appends the values to the existing list ( if any ) . Use
* { @ link # setSteps ( java . util . Collection ) } or { @ link # withSteps ( java . util . Collection ) } if you want to override the
* existing values .
* @ param steps
* A list of < a > StepConfig < / a > to be executed by the job flow .
* @ return Returns a reference to this object so that method calls can be chained together . */
public AddJobFlowStepsRequest withSteps ( StepConfig ... steps ) { } } | if ( this . steps == null ) { setSteps ( new com . amazonaws . internal . SdkInternalList < StepConfig > ( steps . length ) ) ; } for ( StepConfig ele : steps ) { this . steps . add ( ele ) ; } return this ; |
public class SparkDl4jMultiLayer { /** * Score the examples individually , using a specified batch size . Unlike { @ link # calculateScore ( JavaRDD , boolean ) } ,
* this method returns a score for each example separately < br >
* Note : The provided JavaPairRDD has a key that is associated with each example and returned score . < br >
* < b > Note : < / b > The DataSet objects passed in must have exactly one example in them ( otherwise : can ' t have a 1:1 association
* between keys and data sets to score )
* @ param data Data to score
* @ param includeRegularizationTerms If true : include the l1 / l2 regularization terms with the score ( if any )
* @ param < K > Key type
* @ return A { @ code JavaPairRDD < K , Double > } containing the scores of each example
* @ see MultiLayerNetwork # scoreExamples ( DataSet , boolean ) */
public < K > JavaPairRDD < K , Double > scoreExamples ( JavaPairRDD < K , DataSet > data , boolean includeRegularizationTerms , int batchSize ) { } } | return data . mapPartitionsToPair ( new ScoreExamplesWithKeyFunction < K > ( sc . broadcast ( network . params ( ) ) , sc . broadcast ( conf . toJson ( ) ) , includeRegularizationTerms , batchSize ) ) ; |
public class BeanWrapperUtils { /** * Check if the bean type can be wrapped or not .
* @ param bean
* the bean instance
* @ return false if null or valid type , true if primitive type or string */
public static boolean isInvalid ( Object bean ) { } } | if ( bean == null ) { return false ; } return isPrimitiveOrWrapper ( bean . getClass ( ) ) || INVALID_TYPES . contains ( bean . getClass ( ) ) || isInstanceOfInvalid ( bean . getClass ( ) ) ; |
public class ClassHelper { /** * Get the class name of the passed object . If the object itself is of type
* { @ link Class } , its name is retrieved , other { @ link # getClass ( ) } is called .
* @ param aObject
* The object who ' s class name is to be retrieved .
* @ return < code > & quot ; null & quot ; < / code > for a < code > null < / code > parameter */
@ Nonnull @ Nonempty public static String getSafeClassName ( @ Nullable final Object aObject ) { } } | if ( aObject instanceof Class < ? > ) return ( ( Class < ? > ) aObject ) . getName ( ) ; if ( aObject != null ) return aObject . getClass ( ) . getName ( ) ; return "null" ; |
public class PoliciesCache { /** * Create a cache from a directory source
* @ param rootDir base director
* @ return cache */
public static PoliciesCache fromDir ( File rootDir , final Set < Attribute > forcedContext ) { } } | return fromSourceProvider ( YamlProvider . getDirProvider ( rootDir ) , forcedContext ) ; |
public class ConfigTreeBuilder { /** * Looks for all pojo objects on all configuration paths and select unique pojos . This may be used later
* to bind configuration part by type ( as its uniquely identify location ) .
* @ param items all parsed configuration paths
* @ return list of unique custom configuration objects */
private static List < ConfigPath > resolveUniqueTypePaths ( final List < ConfigPath > items ) { } } | final Map < Class , ConfigPath > index = new HashMap < > ( ) ; final List < Class > duplicates = new ArrayList < > ( ) ; for ( ConfigPath item : items ) { final Class type = item . getDeclaredType ( ) ; if ( ! item . isCustomType ( ) || duplicates . contains ( type ) ) { continue ; } if ( index . containsKey ( type ) ) { // type not unique
index . remove ( type ) ; duplicates . add ( type ) ; } else { index . put ( type , item ) ; } } return index . isEmpty ( ) ? Collections . emptyList ( ) : new ArrayList < > ( index . values ( ) ) ; |
public class CommsByteBuffer { /** * This method will work out what JFap exception Id we should flow across the wire when sending
* an exception back . For all defined SI exceptions we will resolve them into their JFap constant
* value . For any other exception we will return EXCEPTION _ INTERNAL _ ERROR .
* Care should be taken in adding exceptions to this method . They need to be checked for in the
* correct order as instanceof will match an instance to it ' s class and any of it ' s parents .
* Therefore , check the lowest level first , then go up the tree .
* @ param exception
* @ return Returns the JFap exception Id for the exception passed in */
private short getExceptionId ( Throwable exception ) { } } | if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . entry ( tc , "getExceptionId" ) ; short exceptionId = CommsConstants . EXCEPTION_INTERNAL_ERROR ; // * * * * * Do the SIIncorrectExcecption branch and all its subclasses
if ( exception instanceof SIInvalidDestinationPrefixException ) exceptionId = CommsConstants . SI_INVALID_DESTINATION_PREFIX_EXCEPTION ; else if ( exception instanceof SIDiscriminatorSyntaxException ) exceptionId = CommsConstants . SI_DISCRIMINATOR_SYNTAX_EXCEPTION ; else if ( exception instanceof SISelectorSyntaxException ) exceptionId = CommsConstants . SI_SELECTOR_SYNTAX_EXCEPTION ; else if ( exception instanceof SIInsufficientDataForFactoryTypeException ) exceptionId = CommsConstants . SI_INSUFFICIENT_DATA_FOR_FACT_EXCEPTION ; else if ( exception instanceof SIIncorrectCallException ) exceptionId = CommsConstants . SI_INCORRECT_CALL_EXCEPTION ; // * * * * * Now the SIAuthenticationException branch
else if ( exception instanceof SIAuthenticationException ) exceptionId = CommsConstants . SI_AUTHENTICATION_EXCEPTION ; // * * * * * Now the SINotPossibleInCurrentConfigurationException branch
else if ( exception instanceof SINotAuthorizedException ) exceptionId = CommsConstants . SI_NOT_AUTHORISED_EXCEPTION ; else if ( exception instanceof SINotPossibleInCurrentConfigurationException ) exceptionId = CommsConstants . SI_NOT_POSSIBLE_IN_CUR_CONFIG_EXCEPTION ; // * * * * * Now the SINotPossibleInCurrentStateException branch
else if ( exception instanceof SISessionDroppedException ) exceptionId = CommsConstants . SI_SESSION_DROPPED_EXCEPTION ; else if ( exception instanceof SISessionUnavailableException ) exceptionId = CommsConstants . SI_SESSION_UNAVAILABLE_EXCEPTION ; else if ( exception instanceof SIDurableSubscriptionAlreadyExistsException ) exceptionId = CommsConstants . SI_DURSUB_ALREADY_EXISTS_EXCEPTION ; else if ( exception instanceof SIDurableSubscriptionMismatchException ) exceptionId = CommsConstants . SI_DURSUB_MISMATCH_EXCEPTION ; else if ( exception instanceof SIDurableSubscriptionNotFoundException ) exceptionId = CommsConstants . SI_DURSUB_NOT_FOUND_EXCEPTION ; else if ( exception instanceof SIConnectionDroppedException ) exceptionId = CommsConstants . SI_CONNECTION_DROPPED_EXCEPTION ; else if ( exception instanceof SIConnectionUnavailableException ) exceptionId = CommsConstants . SI_CONNECTION_UNAVAILABLE_EXCEPTION ; else if ( exception instanceof SIDataGraphFormatMismatchException ) exceptionId = CommsConstants . SI_DATAGRAPH_FORMAT_MISMATCH_EXCEPTION ; else if ( exception instanceof SIDataGraphSchemaNotFoundException ) exceptionId = CommsConstants . SI_DATAGRAPH_SCHEMA_NOT_FOUND_EXCEPTION ; else if ( exception instanceof SIDestinationLockedException ) exceptionId = CommsConstants . SI_DESTINATION_LOCKED_EXCEPTION ; else if ( exception instanceof SITemporaryDestinationNotFoundException ) exceptionId = CommsConstants . SI_TEMPORARY_DEST_NOT_FOUND_EXCEPTION ; // * * * * * Now the SIMessageException branch
else if ( exception instanceof SIMessageException ) exceptionId = CommsConstants . SI_MESSAGE_EXCEPTION ; // * * * * * Now the SIResourceException branch
else if ( exception instanceof SILimitExceededException ) exceptionId = CommsConstants . SI_LIMIT_EXCEEDED_EXCEPTION ; else if ( exception instanceof SIConnectionLostException ) exceptionId = CommsConstants . SI_CONNECTION_LOST_EXCEPTION ; else if ( exception instanceof SIRollbackException ) exceptionId = CommsConstants . SI_ROLLBACK_EXCEPTION ; else if ( exception instanceof SIResourceException ) exceptionId = CommsConstants . SI_RESOURCE_EXCEPTION ; // * * * * * Now the SINotSupportedException branch
else if ( exception instanceof SIMessageDomainNotSupportedException ) exceptionId = CommsConstants . SI_MSG_DOMAIN_NOT_SUPPORTED_EXCEPTION ; else if ( exception instanceof SINotSupportedException ) exceptionId = CommsConstants . SI_NOT_SUPPORTED_EXCEPTION ; // * * * * * Now the SIDataGraphException
else if ( exception instanceof SIDataGraphException ) exceptionId = CommsConstants . SI_DATAGRAPH_EXCEPTION ; // * * * * * Now the SICommandInvocationFailedException
else if ( exception instanceof SICommandInvocationFailedException ) exceptionId = CommsConstants . SI_COMMAND_INVOCATION_FAILED_EXCEPTION ; // * * * * * Now the SIMessageNotLockedException
else if ( exception instanceof SIMessageNotLockedException ) exceptionId = CommsConstants . SI_MESSAGE_NOT_LOCKED_EXCEPTION ; // * * * * * And the runtime one
else if ( exception instanceof SIErrorException ) exceptionId = CommsConstants . SI_ERROR_EXCEPTION ; // * * * * * Now the top level SIException
else if ( exception instanceof SIException ) exceptionId = CommsConstants . SI_EXCEPTION ; // Don ' t forget XA
else if ( exception instanceof XAException ) exceptionId = CommsConstants . EXCEPTION_XAEXCEPTION ; if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . exit ( tc , "getExceptionId" , "" + exceptionId ) ; return exceptionId ; |
public class BaasBox { /** * Asynchronously sends a raw rest request to the server that is specified by
* the parameters passed in .
* @ param method the method to use
* @ param endpoint the resource
* @ param body an optional jsono bject
* @ param authenticate true if the client should try to refresh authentication automatically
* @ param handler a callback to handle the json response
* @ return a raw { @ link com . baasbox . android . json . JsonObject } response wrapped as { @ link com . baasbox . android . BaasResult } */
@ Deprecated public RequestToken rest ( int method , String endpoint , JsonArray body , boolean authenticate , BaasHandler < JsonObject > handler ) { } } | return rest ( method , endpoint , body , 0 , authenticate , handler ) ; |
public class BaseBundleActivator { /** * Setup the application properties .
* Override this to set the properties .
* @ param bundleContext BundleContext */
public void init ( ) { } } | Dictionary < String , String > properties = getConfigurationProperties ( this . getProperties ( ) , false ) ; this . setProperties ( properties ) ; this . setProperty ( BundleConstants . SERVICE_PID , getServicePid ( ) ) ; this . setProperty ( BundleConstants . SERVICE_CLASS , getServiceClassName ( ) ) ; |
public class WordDataReader { /** * / * ( non - Javadoc )
* @ see jvntextpro . data . DataReader # readFile ( java . lang . String ) */
@ Override public List < Sentence > readFile ( String datafile ) { } } | try { BufferedReader reader = new BufferedReader ( new InputStreamReader ( new FileInputStream ( datafile ) , "UTF-8" ) ) ; String line = null ; List < Sentence > data = new ArrayList < Sentence > ( ) ; while ( ( line = reader . readLine ( ) ) != null ) { Sentence sentence = new Sentence ( ) ; if ( line . startsWith ( "#" ) ) continue ; StringTokenizer tk = new StringTokenizer ( line , " " ) ; while ( tk . hasMoreTokens ( ) ) { String word = "" , tag = null ; if ( ! isTrainReading ) { String token = tk . nextToken ( ) ; word = token ; sentence . addTWord ( word , tag ) ; } else { String token = tk . nextToken ( ) ; for ( int i = 0 ; i < tags . length ; ++ i ) { String labelPart = "/" + tags [ i ] ; if ( token . endsWith ( labelPart ) ) { word = token . substring ( 0 , token . length ( ) - labelPart . length ( ) ) ; tag = tags [ i ] ; break ; } } sentence . addTWord ( word , tag ) ; } } data . add ( sentence ) ; } reader . close ( ) ; return data ; } catch ( Exception e ) { System . out . println ( e . getMessage ( ) ) ; return new ArrayList < Sentence > ( ) ; // empty array
} |
public class VoltDecimalHelper { /** * Serialize the { @ link java . math . BigDecimal BigDecimal } to Volt ' s fixed precision and scale 16 - byte format .
* @ param bd { @ link java . math . BigDecimal BigDecimal } to serialize
* @ param buf { @ link java . nio . ByteBuffer ByteBuffer } to serialize the < code > BigDecimal < / code > to
* @ throws RuntimeException Thrown if the precision is out of range , or the scale is out of range and rounding is not enabled . */
static public void serializeBigDecimal ( BigDecimal bd , ByteBuffer buf ) { } } | if ( bd == null ) { serializeNull ( buf ) ; return ; } int decimalScale = bd . scale ( ) ; if ( decimalScale > kDefaultScale ) { bd = roundToScale ( bd , kDefaultScale , getRoundingMode ( ) ) ; decimalScale = bd . scale ( ) ; } int overallPrecision = bd . precision ( ) ; final int wholeNumberPrecision = overallPrecision - decimalScale ; if ( wholeNumberPrecision > 26 ) { throw new RuntimeException ( "Precision of " + bd + " to the left of the decimal point is " + wholeNumberPrecision + " and the max is 26" ) ; } final int scalingFactor = Math . max ( 0 , kDefaultScale - decimalScale ) ; BigInteger scalableBI = bd . unscaledValue ( ) ; // * enable to debug * / System . out . println ( " DEBUG BigDecimal : " + bd ) ;
// * enable to debug * / System . out . println ( " DEBUG unscaled : " + scalableBI ) ;
scalableBI = scalableBI . multiply ( scaleFactors [ scalingFactor ] ) ; // * enable to debug * / System . out . println ( " DEBUG scaled to picos : " + scalableBI ) ;
final byte wholePicos [ ] = scalableBI . toByteArray ( ) ; if ( wholePicos . length > 16 ) { throw new RuntimeException ( "Precision of " + bd + " is > 38 digits" ) ; } boolean isNegative = ( scalableBI . signum ( ) < 0 ) ; buf . put ( expandToLength16 ( wholePicos , isNegative ) ) ; |
public class CheckpointListener { /** * Load a MultiLayerNetwork for the given checkpoint that resides in the specified root directory
* @ param rootDir Root directory for the checkpoint
* @ param checkpoint Checkpoint model to load
* @ return The loaded model */
public static MultiLayerNetwork loadCheckpointMLN ( File rootDir , Checkpoint checkpoint ) { } } | return loadCheckpointMLN ( rootDir , checkpoint . getCheckpointNum ( ) ) ; |
public class OkHostnameVerifier { /** * Returns true if { @ code certificate } matches { @ code ipAddress } . */
private boolean verifyIpAddress ( String ipAddress , X509Certificate certificate ) { } } | List < String > altNames = getSubjectAltNames ( certificate , ALT_IPA_NAME ) ; for ( int i = 0 , size = altNames . size ( ) ; i < size ; i ++ ) { if ( ipAddress . equalsIgnoreCase ( altNames . get ( i ) ) ) { return true ; } } return false ; |
public class SQLiteExecutor { /** * The properties will be ignored by update / updateAll / batchUpdate operations if the input is an entity .
* @ param targetClass
* @ param writeOnlyPropNames */
public static void registerWriteOnlyProps ( Class < ? > targetClass , Collection < String > writeOnlyPropNames ) { } } | N . checkArgument ( N . isEntity ( targetClass ) , ClassUtil . getCanonicalClassName ( targetClass ) + " is not an entity class with getter/setter methods" ) ; N . checkArgNotNullOrEmpty ( writeOnlyPropNames , "'writeOnlyPropNames'" ) ; final Set < String > set = new HashSet < String > ( ) ; for ( String propName : writeOnlyPropNames ) { set . add ( ClassUtil . getPropNameByMethod ( ClassUtil . getPropGetMethod ( targetClass , propName ) ) ) ; } if ( readOrWriteOnlyPropNamesMap . containsKey ( targetClass ) ) { readOrWriteOnlyPropNamesMap . get ( targetClass ) . addAll ( set ) ; } else { readOrWriteOnlyPropNamesMap . put ( targetClass , set ) ; } |
public class DumpFileCreator { /** * Computes the best file to save the response to the current page . */
public File createDumpFile ( final File dir , final String extension , final String urlString , final String additionalInfo ) { } } | URI uri = URI . create ( urlString ) ; String path = uri . getPath ( ) ; if ( path == null ) { log . warn ( "Cannot create dump file for URI: " + uri ) ; return null ; } String name = PATTERN_FIRST_LAST_SLASH . matcher ( path ) . replaceAll ( "$1" ) ; name = PATTERN_ILLEGAL_CHARS . matcher ( name ) . replaceAll ( "_" ) ; Key key = Key . get ( dir . getPath ( ) , extension ) ; MutableInt counter = countersMap . get ( key ) ; if ( counter == null ) { counter = new MutableInt ( ) ; countersMap . put ( key , counter ) ; } int counterValue = counter . intValue ( ) ; counter . increment ( ) ; StringBuilder sb = new StringBuilder ( ) ; sb . append ( String . format ( "%04d" , counterValue ) ) ; sb . append ( '_' ) ; sb . append ( name ) ; if ( StringUtils . isNotBlank ( additionalInfo ) ) { sb . append ( "_" ) ; sb . append ( additionalInfo ) ; } sb . append ( "." ) ; sb . append ( extension ) ; return new File ( dir , sb . toString ( ) ) ; |
public class CSSColorHelper { /** * Get the passed values as CSS HSLA color value
* @ param fHue
* Hue - is scaled to 0-359
* @ param fSaturation
* Saturation - is scaled to 0-100
* @ param fLightness
* Lightness - is scaled to 0-100
* @ param fOpacity
* Opacity - is scaled to 0-1
* @ return The CSS string to use */
@ Nonnull @ Nonempty public static String getHSLAColorValue ( final float fHue , final float fSaturation , final float fLightness , final float fOpacity ) { } } | return new StringBuilder ( 32 ) . append ( CCSSValue . PREFIX_HSLA_OPEN ) . append ( getHSLHueValue ( fHue ) ) . append ( ',' ) . append ( getHSLPercentageValue ( fSaturation ) ) . append ( "%," ) . append ( getHSLPercentageValue ( fLightness ) ) . append ( "%," ) . append ( getOpacityToUse ( fOpacity ) ) . append ( CCSSValue . SUFFIX_HSLA_CLOSE ) . toString ( ) ; |
public class AsciiSet { /** * Create a set containing ascii characters using a simple pattern . The pattern is similar
* to a character set in regex . For example , { @ code ABC } would contain the characters
* { @ code A } , { @ code B } , and { @ code C } . Ranges are supported so all uppercase letters could
* be specified as { @ code A - Z } . The dash , { @ code - } , will be included as part of the set if
* it is at the start or end of the pattern .
* @ param pattern
* String specification of the character set .
* @ return
* Set containing the characters specified in { @ code pattern } . */
public static AsciiSet fromPattern ( String pattern ) { } } | final boolean [ ] members = new boolean [ 128 ] ; final int n = pattern . length ( ) ; for ( int i = 0 ; i < n ; ++ i ) { final char c = pattern . charAt ( i ) ; if ( c >= members . length ) { throw new IllegalArgumentException ( "invalid pattern, '" + c + "' is not ascii" ) ; } final boolean isStartOrEnd = i == 0 || i == n - 1 ; if ( isStartOrEnd || c != '-' ) { members [ c ] = true ; } else { final char s = pattern . charAt ( i - 1 ) ; final char e = pattern . charAt ( i + 1 ) ; for ( char v = s ; v <= e ; ++ v ) { members [ v ] = true ; } } } return new AsciiSet ( members ) ; |
public class AbstractShape3i { /** * Add listener on geometry changes .
* @ param listener the listener . */
protected synchronized void addShapeGeometryChangeListener ( ShapeGeometryChangeListener listener ) { } } | assert listener != null : AssertMessages . notNullParameter ( ) ; if ( this . geometryListeners == null ) { this . geometryListeners = new WeakArrayList < > ( ) ; } this . geometryListeners . add ( listener ) ; |
public class CmsSerialDateView { /** * Handle a " current till end " change event .
* @ param event the change event . */
@ UiHandler ( "m_currentTillEndCheckBox" ) void onCurrentTillEndChange ( ValueChangeEvent < Boolean > event ) { } } | if ( handleChange ( ) ) { m_controller . setCurrentTillEnd ( event . getValue ( ) ) ; } |
public class TaskLogsMonitor { /** * Get the logFileDetails of all the list of attempts passed .
* @ param lInfo
* @ return a map of task to the log - file detail
* @ throws IOException */
private Map < Task , Map < LogName , LogFileDetail > > getAllLogsFileDetails ( final List < Task > allAttempts ) throws IOException { } } | Map < Task , Map < LogName , LogFileDetail > > taskLogFileDetails = new HashMap < Task , Map < LogName , LogFileDetail > > ( ) ; for ( Task task : allAttempts ) { Map < LogName , LogFileDetail > allLogsFileDetails ; allLogsFileDetails = TaskLog . getAllLogsFileDetails ( task . getTaskID ( ) , task . isTaskCleanupTask ( ) ) ; taskLogFileDetails . put ( task , allLogsFileDetails ) ; } return taskLogFileDetails ; |
public class InterpretedContainerImpl { /** * { @ inheritDoc } */
@ Override public Iterator < Entry > iterator ( ) { } } | Iterator < ArtifactEntry > iter = delegate . iterator ( ) ; if ( structureHelperSaysWeAreRoot != null ) { return new WrapperedIterator ( iter , root , rootOverlay , factoryHolder , structureHelper , structureHelperLocalRootDelegate ) ; } else { return new WrapperedIterator ( iter , root , rootOverlay , factoryHolder , structureHelper , null ) ; } |
public class Partition { /** * Returns all objects from leftCollection whole images are a disjoin from rightCollection ,
* none of the resulting objects has an image in rightCollection . Compares objects using = = .
* Note that lefts with no image show up in the result . */
public static List getDisconnected ( Collection leftCollection , Graph relation , Collection rightCollection ) { } } | List disconnected ; Iterator iter ; Object left ; EdgeIterator relationIter ; disconnected = new ArrayList ( ) ; iter = leftCollection . iterator ( ) ; while ( iter . hasNext ( ) ) { left = iter . next ( ) ; relationIter = relation . edges ( ) ; while ( relationIter . step ( ) ) { if ( relationIter . left ( ) == left ) { if ( ! rightCollection . contains ( relationIter . right ( ) ) ) { relationIter = null ; break ; } } } if ( relationIter != null ) { disconnected . add ( left ) ; } } return disconnected ; |
public class XTraceBufferedImpl { /** * ( non - Javadoc )
* @ see java . util . List # add ( int , java . lang . Object ) */
public void add ( int index , XEvent event ) { } } | try { events . insert ( event , index ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } |
public class AjaxAddableTabbedPanel { /** * On remove tab removes the given tab if it does exists .
* @ param target
* the target
* @ param tab
* the tab */
public void onRemoveTab ( final AjaxRequestTarget target , final T tab ) { } } | final int index = getTabs ( ) . indexOf ( tab ) ; if ( 0 <= index ) { onRemoveTab ( target , index ) ; } |
public class RdfUtils { /** * Convert quads from an external form to a skolemized form
* @ param svc the resource service
* @ param baseUrl the base URL
* @ return a mapping function */
public static Function < Quad , Quad > skolemizeQuads ( final ResourceService svc , final String baseUrl ) { } } | return quad -> rdf . createQuad ( quad . getGraphName ( ) . orElse ( PreferUserManaged ) , ( BlankNodeOrIRI ) svc . toInternal ( svc . skolemize ( quad . getSubject ( ) ) , baseUrl ) , quad . getPredicate ( ) , svc . toInternal ( svc . skolemize ( quad . getObject ( ) ) , baseUrl ) ) ; |
public class IOUtils { /** * Ensures that the given directory exists ( if not , it ' s created , including all the parent directories . )
* @ return
* This method returns the ' dir ' parameter so that the method call flows better . */
public static File mkdirs ( File dir ) throws IOException { } } | try { return Files . createDirectories ( fileToPath ( dir ) ) . toFile ( ) ; } catch ( UnsupportedOperationException e ) { throw new IOException ( e ) ; } |
public class FirestoreException { /** * Creates a FirestoreException with the provided GRPC Status code and message in a nested
* exception .
* @ return The FirestoreException */
static FirestoreException serverRejected ( Status status , String message , Object ... params ) { } } | return new FirestoreException ( String . format ( message , params ) , status ) ; |
public class XmlInputStream { /** * Might not actually push back anything but usually will .
* @ return true if at end - of - file
* @ throws IOException thrown if there is an IO exception in the underlying
* steam */
private boolean readIntoPushBack ( ) throws IOException { } } | // File finished ?
boolean eof = false ; // Next char .
final int ch = in . read ( ) ; if ( ch >= 0 ) { // Discard whitespace at start ?
if ( ! ( pulled == 0 && isWhiteSpace ( ch ) ) ) { // Good code .
pulled += 1 ; // Parse out the & stuff ;
if ( ch == '&' ) { // Process the &
readAmpersand ( ) ; } else { // Not an ' & ' , just append .
pushBack . append ( ( char ) ch ) ; } } } else { // Hit end of file .
eof = true ; } return eof ; |
public class PropertyChangeListeners { /** * Recursively add the given property change listener to the given
* object and all its sub - objects
* @ param object The object
* @ param propertyChangeListener The property change listener
* @ param processedObjects The set of objects that have already been
* processed . */
private static void addRecursive ( Object object , PropertyChangeListener propertyChangeListener , Set < Object > processedObjects ) { } } | Objects . requireNonNull ( processedObjects , "The processedObjects may not be null" ) ; if ( object == null ) { return ; } if ( processedObjects . contains ( object ) ) { return ; } processedObjects . add ( object ) ; if ( object . getClass ( ) . isArray ( ) ) { int length = Array . getLength ( object ) ; for ( int i = 0 ; i < length ; i ++ ) { Object element = Array . get ( object , i ) ; addRecursive ( element , propertyChangeListener , processedObjects ) ; } return ; } PropertyChangeUtils . tryAddPropertyChangeListenerUnchecked ( object , propertyChangeListener ) ; List < String > propertyNames = BeanUtils . getMutablePropertyNamesOptional ( object . getClass ( ) ) ; for ( String propertyName : propertyNames ) { Object value = BeanUtils . invokeReadMethodOptional ( object , propertyName ) ; addRecursive ( value , propertyChangeListener , processedObjects ) ; } |
public class ReaderInputStream { /** * an IOException thrown by overrides of the read ( ) method . */
@ Override public int read ( byte [ ] b , int off , int len ) throws IOException { } } | if ( b == null ) { throw new NullPointerException ( ) ; } else if ( off < 0 || len < 0 || len > b . length - off ) { throw new IndexOutOfBoundsException ( ) ; } else if ( len == 0 ) { return 0 ; } if ( endOfInput && ! bbuf . hasRemaining ( ) ) { return - 1 ; } int totalRead = 0 ; while ( len > 0 && ! endOfInput ) { if ( bbuf . hasRemaining ( ) ) { int remaining = Math . min ( len , bbuf . remaining ( ) ) ; bbuf . get ( b , off , remaining ) ; totalRead += remaining ; off += remaining ; len -= remaining ; if ( len == 0 ) { return totalRead ; } } advance ( ) ; } if ( endOfInput && ! bbuf . hasRemaining ( ) && totalRead == 0 ) { return - 1 ; } return totalRead ; |
public class InstrumentedInvokerFactory { /** * Factory method for MeteredInvoker . */
private Invoker metered ( Invoker invoker , List < Method > meteredMethods ) { } } | ImmutableMap . Builder < String , Meter > meters = new ImmutableMap . Builder < > ( ) ; for ( Method m : meteredMethods ) { Metered annotation = m . getAnnotation ( Metered . class ) ; final String name = chooseName ( annotation . name ( ) , annotation . absolute ( ) , m ) ; Meter meter = metricRegistry . meter ( name ) ; meters . put ( m . getName ( ) , meter ) ; } return new InstrumentedInvokers . MeteredInvoker ( invoker , meters . build ( ) ) ; |
public class UCharacterNameReader { /** * Reads an individual record of AlgorithmNames
* @ return an instance of AlgorithNames if read is successful otherwise null
* @ exception IOException thrown when file read error occurs or data is corrupted */
private UCharacterName . AlgorithmName readAlg ( ) throws IOException { } } | UCharacterName . AlgorithmName result = new UCharacterName . AlgorithmName ( ) ; int rangestart = m_byteBuffer_ . getInt ( ) ; int rangeend = m_byteBuffer_ . getInt ( ) ; byte type = m_byteBuffer_ . get ( ) ; byte variant = m_byteBuffer_ . get ( ) ; if ( ! result . setInfo ( rangestart , rangeend , type , variant ) ) { return null ; } int size = m_byteBuffer_ . getChar ( ) ; if ( type == UCharacterName . AlgorithmName . TYPE_1_ ) { char factor [ ] = ICUBinary . getChars ( m_byteBuffer_ , variant , 0 ) ; result . setFactor ( factor ) ; size -= ( variant << 1 ) ; } StringBuilder prefix = new StringBuilder ( ) ; char c = ( char ) ( m_byteBuffer_ . get ( ) & 0x00FF ) ; while ( c != 0 ) { prefix . append ( c ) ; c = ( char ) ( m_byteBuffer_ . get ( ) & 0x00FF ) ; } result . setPrefix ( prefix . toString ( ) ) ; size -= ( ALG_INFO_SIZE_ + prefix . length ( ) + 1 ) ; if ( size > 0 ) { byte string [ ] = new byte [ size ] ; m_byteBuffer_ . get ( string ) ; result . setFactorString ( string ) ; } return result ; |
public class Lexer { private Token text ( ) { } } | String val = scan1 ( "^(?:\\| ?| )([^\\n]+)" ) ; if ( StringUtils . isEmpty ( val ) ) { val = scan1 ( "^\\|?( )" ) ; if ( StringUtils . isEmpty ( val ) ) { val = scan1 ( "^(<[^\\n]*)" ) ; } } if ( StringUtils . isNotEmpty ( val ) ) { return new Text ( val , lineno ) ; } return null ; |
public class NodeTypes { /** * Determine if the named property on the node type is a reference property .
* @ param nodeTypeName the name of the node type ; may not be null
* @ param propertyName the name of the property definition ; may not be null
* @ return true if the property is a { @ link PropertyType # REFERENCE } , { @ link PropertyType # WEAKREFERENCE } , or
* { @ link org . modeshape . jcr . api . PropertyType # SIMPLE _ REFERENCE } , or false otherwise */
public boolean isReferenceProperty ( Name nodeTypeName , Name propertyName ) { } } | JcrNodeType type = getNodeType ( nodeTypeName ) ; if ( type != null ) { for ( JcrPropertyDefinition propDefn : type . allPropertyDefinitions ( propertyName ) ) { int requiredType = propDefn . getRequiredType ( ) ; if ( requiredType == PropertyType . REFERENCE || requiredType == PropertyType . WEAKREFERENCE || requiredType == org . modeshape . jcr . api . PropertyType . SIMPLE_REFERENCE ) { return true ; } } } return false ; |
public class Interpolate1D_F32 { /** * Searches the x array by bisecting it . This takes advantage of the data being
* monotonic . This finds a center index which has the following property :
* x [ center ] & le ; val & lt ; x [ center + 1]
* From that it selects index0 which is center - M / 2.
* @ param valThe value that is to be interpolated .
* @ param lowerLimit Lower limit for x index .
* @ param upperLimit The largest possible index of x */
protected void bisectionSearch ( float val , int lowerLimit , int upperLimit ) { } } | while ( upperLimit - lowerLimit > 1 ) { int middle = ( upperLimit + lowerLimit ) / 2 ; if ( val >= x [ middle ] && ascend ) { lowerLimit = middle ; } else { upperLimit = middle ; } } // decide if it should hunt or locate next time
doHunt = Math . abs ( lowerLimit - center ) > dj ; // make sure the points sampled for the polynomial are all within bounds
center = lowerLimit ; index0 = center - M / 2 ; if ( index0 + M > size ) { index0 = size - M ; } else if ( index0 < 0 ) { index0 = 0 ; } |
public class Cnf { /** * Returns true if the given disjunction is universally true . */
public static boolean isTautology ( IDisjunct disjunct ) { } } | boolean tautology = false ; if ( disjunct != null ) { IAssertion [ ] assertions = IteratorUtils . toArray ( disjunct . getAssertions ( ) , IAssertion . class ) ; int max = assertions . length ; int maxCompared = max - 1 ; for ( int compared = 0 ; ! tautology && compared < maxCompared ; compared ++ ) { IAssertion assertCompared = assertions [ compared ] ; for ( int other = compared + 1 ; ! tautology && other < max ; tautology = assertCompared . negates ( assertions [ other ++ ] ) ) ; } } return tautology ; |
public class StatusBar { /** * { @ inheritDoc } */
public void islandPopulationUpdate ( int islandIndex , final PopulationData < ? extends Object > populationData ) { } } | islandPopulationSize . compareAndSet ( - 1 , populationData . getPopulationSize ( ) ) ; SwingUtilities . invokeLater ( new Runnable ( ) { public void run ( ) { // Only update the label if the time has advanced . Sometimes , due to threading
// variations , later updates have shorter elapsed times .
if ( populationData . getElapsedTime ( ) > epochTime ) { epochTime = populationData . getElapsedTime ( ) ; timeLabel . setText ( formatTime ( elapsedTime + epochTime ) ) ; } } } ) ; |
public class ContentKeyPoliciesInner { /** * Create or update an Content Key Policy .
* Create or update a Content Key Policy in the Media Services account .
* @ param resourceGroupName The name of the resource group within the Azure subscription .
* @ param accountName The Media Services account name .
* @ param contentKeyPolicyName The Content Key Policy name .
* @ param parameters The request parameters
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ throws ApiErrorException thrown if the request is rejected by server
* @ throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @ return the ContentKeyPolicyInner object if successful . */
public ContentKeyPolicyInner createOrUpdate ( String resourceGroupName , String accountName , String contentKeyPolicyName , ContentKeyPolicyInner parameters ) { } } | return createOrUpdateWithServiceResponseAsync ( resourceGroupName , accountName , contentKeyPolicyName , parameters ) . toBlocking ( ) . single ( ) . body ( ) ; |
public class GetExportSnapshotRecordsRequestMarshaller { /** * Marshall the given parameter object . */
public void marshall ( GetExportSnapshotRecordsRequest getExportSnapshotRecordsRequest , ProtocolMarshaller protocolMarshaller ) { } } | if ( getExportSnapshotRecordsRequest == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( getExportSnapshotRecordsRequest . getPageToken ( ) , PAGETOKEN_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class NioGroovyMethods { /** * This method is used to throw useful exceptions when the eachFile * and eachDir closure methods
* are used incorrectly .
* @ param self The directory to check
* @ throws java . io . FileNotFoundException if the given directory does not exist
* @ throws IllegalArgumentException if the provided Path object does not represent a directory
* @ since 2.3.0 */
private static void checkDir ( Path self ) throws FileNotFoundException , IllegalArgumentException { } } | if ( ! Files . exists ( self ) ) throw new FileNotFoundException ( self . toAbsolutePath ( ) . toString ( ) ) ; if ( ! Files . isDirectory ( self ) ) throw new IllegalArgumentException ( "The provided Path object is not a directory: " + self . toAbsolutePath ( ) ) ; |
public class EvaluationBinary { /** * Calculate the G - measure for the given output
* @ param output The specified output
* @ return The G - measure for the specified output */
public double gMeasure ( int output ) { } } | double precision = precision ( output ) ; double recall = recall ( output ) ; return EvaluationUtils . gMeasure ( precision , recall ) ; |
public class MembershipHandlerImpl { /** * Use this method to find all the memberships of an user in any group . */
private MembershipsByUserWrapper findMembershipsByUser ( Session session , String userName ) throws Exception { } } | Node userNode ; try { userNode = utils . getUserNode ( session , userName ) ; } catch ( PathNotFoundException e ) { return new MembershipsByUserWrapper ( new ArrayList < Membership > ( ) , new ArrayList < Node > ( ) ) ; } List < Membership > memberships = new ArrayList < Membership > ( ) ; List < Node > refUserNodes = new ArrayList < Node > ( ) ; PropertyIterator refUserProps = userNode . getReferences ( ) ; while ( refUserProps . hasNext ( ) ) { Node refUserNode = refUserProps . nextProperty ( ) . getParent ( ) ; Node groupNode = refUserNode . getParent ( ) . getParent ( ) ; memberships . addAll ( findMembershipsByUserAndGroup ( session , refUserNode , groupNode ) ) ; refUserNodes . add ( refUserNode ) ; } return new MembershipsByUserWrapper ( memberships , refUserNodes ) ; |
public class WSuggestions { /** * { @ inheritDoc } */
@ Override public void handleRequest ( final Request request ) { } } | // Check if this suggestion list is the current AJAX trigger
if ( AjaxHelper . isCurrentAjaxTrigger ( this ) ) { String filter = request . getParameter ( getId ( ) ) ; setAjaxFilter ( filter ) ; doHandleAjaxRefresh ( ) ; } |
public class FnDouble { /** * Determines whether the target object and the specified object are NOT equal
* by calling the < tt > equals < / tt > method on the target object .
* @ param object the { @ link Double } to compare to the target
* @ return false if both objects are equal , true if not . */
public static final Function < Double , Boolean > notEq ( final Double object ) { } } | return ( Function < Double , Boolean > ) ( ( Function ) FnObject . notEq ( object ) ) ; |
public class Bootstrap { /** * Use this factory method to create your own dataset overriding bundled one
* @ param locale will be used to assess langCode for data file
* @ param dataFilePrefix prefix of the data file - final pattern will be jfairy . yml and dataFilePrefix _ { langCode } . yml
* @ return Fairy instance */
public static Fairy create ( Locale locale , String dataFilePrefix ) { } } | return builder ( ) . withLocale ( locale ) . withFilePrefix ( dataFilePrefix ) . build ( ) ; |
public class SqlUtil { /** * 获取拼接参数后的sql .
* @ param sql sql
* @ param param 参数列表
* @ return 拼接后的sql */
public static String getSQL ( String sql , StatementParameter param ) { } } | int i = 0 ; while ( sql . indexOf ( '?' ) > - 1 ) { if ( param == null ) { throw new InvalidParamDataAccessException ( "没有设置参数." ) ; } if ( i >= param . size ( ) ) { return sql ; } Class < ? > type = param . getType ( i ) ; Object obj = param . getObject ( i ) ; String value = getValue ( type , obj ) ; sql = sql . substring ( 0 , sql . indexOf ( '?' ) ) + value + sql . substring ( sql . indexOf ( '?' ) + 1 , sql . length ( ) ) ; i ++ ; } return sql ; |
public class LdeSessionUtil { /** * Serializes the session attributes of the given session .
* @ param session the session to persist . */
public static synchronized void serializeSessionAttributes ( final HttpSession session ) { } } | if ( session != null ) { File file = new File ( SERIALIZE_SESSION_NAME ) ; if ( ! file . exists ( ) || file . canWrite ( ) ) { // Retrieve the session attributes
List data = new ArrayList ( ) ; for ( Enumeration keyEnum = session . getAttributeNames ( ) ; keyEnum . hasMoreElements ( ) ; ) { String attributeName = ( String ) keyEnum . nextElement ( ) ; Object attributeValue = session . getAttribute ( attributeName ) ; if ( attributeValue instanceof Serializable ) { data . add ( attributeName ) ; data . add ( attributeValue ) ; } else { LOG . error ( "Skipping attribute \"" + attributeName + "\" as it is not Serializable" ) ; } } // Write them to the file
FileOutputStream fos = null ; ObjectOutputStream oos = null ; try { fos = new FileOutputStream ( file ) ; oos = new ObjectOutputStream ( fos ) ; oos . writeObject ( data ) ; } catch ( Exception e ) { LOG . error ( "Failed to write serialized session to " + file , e ) ; } finally { if ( oos != null ) { StreamUtil . safeClose ( oos ) ; } else { StreamUtil . safeClose ( fos ) ; } } } else { LOG . warn ( "Unable to write serialized session to " + file ) ; } } |
public class ByteArrayDiskQueue { /** * Enqueues a byte array to this queue .
* @ param array the array to be enqueued . */
public synchronized void enqueue ( final byte [ ] array ) throws IOException { } } | assert array != null ; byteDiskQueue . enqueueInt ( array . length ) ; byteDiskQueue . enqueue ( array ) ; size ++ ; |
public class RequestUtils { /** * < p > Finds all < b > < i > constant < / i > form parameters < / b > in the given { @ link InvocationContext } . < / p >
* < p > Constant form parameters are introduced with @ { @ link Param } at < b > request level < / b > using
* the @ { @ link FormParams } annotation . < / p >
* @ param context
* the { @ link InvocationContext } from which all { @ link FormParams } annotations applied
* on the endpoint method will be extracted
* < br > < br >
* @ return an < b > unmodifiable < / b > { @ link List } which aggregates all the @ { @ link Param } annotations
* found on the { @ link FormParams } annotation
* < br > < br >
* @ throws NullPointerException
* if the supplied { @ link InvocationContext } was { @ code null }
* < br > < br >
* @ since 1.3.0 */
static List < Param > findStaticFormParams ( InvocationContext context ) { } } | Method request = assertNotNull ( context ) . getRequest ( ) ; FormParams formParams = request . getAnnotation ( FormParams . class ) ; return Collections . unmodifiableList ( formParams != null ? Arrays . asList ( formParams . value ( ) ) : new ArrayList < Param > ( ) ) ; |
public class DataFileWriter { /** * Creates a new output file and writes the header information .
* @ throws ConfigurationException
* if an error occurred while accessing the configuration
* @ throws IOException
* if an error occurred while writing a file */
protected void writeHeader ( ) throws ConfigurationException , IOException { } } | if ( writer != null ) { writer . close ( ) ; } this . fileCounter ++ ; String filePath = PATH_OUTPUT_DATA_FILES + this . outputName + "_" + fileCounter + ".csv" ; this . dataFile = new File ( filePath ) ; this . writer = new BufferedWriter ( new OutputStreamWriter ( new BufferedOutputStream ( new FileOutputStream ( filePath ) ) , WIKIPEDIA_ENCODING ) ) ; this . writer . flush ( ) ; |
public class DefaultLogger { /** * Prints a message to a PrintStream .
* @ param message The message to print . Should not be < code > null < / code > .
* @ param stream A PrintStream to print the message to . Must not be
* < code > null < / code > .
* @ param priority The priority of the message . ( Ignored in this
* implementation . ) */
private void printMessage ( final String message , final PrintStream stream , final int priority ) { } } | if ( useColor && priority == Project . MSG_ERR ) { stream . print ( ANSI_RED ) ; stream . print ( message ) ; stream . println ( ANSI_RESET ) ; } else { stream . println ( message ) ; } |
public class BaseResourceIndexedSearchParam { /** * Applies a fast and consistent hashing algorithm to a set of strings */
static long hash ( String ... theValues ) { } } | Hasher hasher = HASH_FUNCTION . newHasher ( ) ; for ( String next : theValues ) { if ( next == null ) { hasher . putByte ( ( byte ) 0 ) ; } else { next = UrlUtil . escapeUrlParam ( next ) ; byte [ ] bytes = next . getBytes ( Charsets . UTF_8 ) ; hasher . putBytes ( bytes ) ; } hasher . putBytes ( DELIMITER_BYTES ) ; } HashCode hashCode = hasher . hash ( ) ; return hashCode . asLong ( ) ; |
public class ChunkOutputStream { /** * Write the data to column if the configured chunk size is reached or if the
* stream should be closed
* @ param close
* @ throws IOException */
private void writeData ( boolean close ) throws IOException { } } | if ( pos != 0 && ( close || pos == chunk . length - 1 ) ) { byte [ ] data ; if ( pos != chunk . length - 1 ) { data = new byte [ ( int ) pos + 1 ] ; // we need to adjust the array
System . arraycopy ( chunk , 0 , data , 0 , data . length ) ; } else { data = chunk ; } try { mutator . insert ( key , cf , HFactory . createColumn ( chunkPos , data , LongSerializer . get ( ) , BytesArraySerializer . get ( ) ) ) ; } catch ( HectorException e ) { throw new IOException ( "Unable to write data" , e ) ; } chunkPos ++ ; pos = 0 ; } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.