signature
stringlengths
43
39.1k
implementation
stringlengths
0
450k
public class StreamBlockQueue { /** * Only allow two blocks in memory , put the rest in the persistent deque */ public void offer ( StreamBlock streamBlock ) throws IOException { } }
m_persistentDeque . offer ( streamBlock . asBBContainer ( ) ) ; long unreleasedSeqNo = streamBlock . unreleasedSequenceNumber ( ) ; if ( m_memoryDeque . size ( ) < 2 ) { StreamBlock fromPBD = pollPersistentDeque ( false ) ; if ( ( streamBlock . startSequenceNumber ( ) == fromPBD . startSequenceNumber ( ) ) && ( unreleasedSeqNo > streamBlock . startSequenceNumber ( ) ) ) { fromPBD . releaseTo ( unreleasedSeqNo - 1 ) ; } }
public class OutHamp { /** * Sends a stream message to a given address */ public void stream ( OutputStream os , HeadersAmp headers , String from , long qId , String address , String methodName , PodRef podCaller , ResultStream < ? > result , Object [ ] args ) throws IOException { } }
init ( os ) ; OutH3 out = _out ; if ( out == null ) { return ; } if ( log . isLoggable ( Level . FINEST ) ) { log . finest ( "hamp-stream-w " + methodName + ( args != null ? Arrays . asList ( args ) : "[]" ) + " {to:" + address + ", from:" + from + "}" ) ; } out . writeLong ( MessageTypeHamp . STREAM . ordinal ( ) ) ; writeHeaders ( out , headers ) ; writeFromAddress ( out , from ) ; out . writeLong ( qId ) ; writeMethod ( out , address , methodName , podCaller ) ; out . writeObject ( result ) ; writeArgs ( out , args ) ; // out . flushBuffer ( ) ; out . flush ( ) ;
public class GroupBy { /** * Creates and chain a Having object for filtering the aggregated values * from the the GROUP BY clause . * @ param expression The expression * @ return The Having object that represents the HAVING clause of the query . */ @ NonNull @ Override public Having having ( @ NonNull Expression expression ) { } }
if ( expression == null ) { throw new IllegalArgumentException ( "expression cannot be null." ) ; } return new Having ( this , expression ) ;
public class KillmailsApi { /** * Get a single killmail ( asynchronously ) Return a single killmail from its * ID and hash - - - This route is cached for up to 1209600 seconds * @ param killmailHash * The killmail hash for verification ( required ) * @ param killmailId * The killmail ID to be queried ( required ) * @ param datasource * The server name you would like data from ( optional , default to * tranquility ) * @ param ifNoneMatch * ETag from a previous request . A 304 will be returned if this * matches the current ETag ( optional ) * @ param callback * The callback to be executed when the API call finishes * @ return The request call * @ throws ApiException * If fail to process the API call , e . g . serializing the request * body object */ public com . squareup . okhttp . Call getKillmailsKillmailIdKillmailHashAsync ( String killmailHash , Integer killmailId , String datasource , String ifNoneMatch , final ApiCallback < KillmailResponse > callback ) throws ApiException { } }
com . squareup . okhttp . Call call = getKillmailsKillmailIdKillmailHashValidateBeforeCall ( killmailHash , killmailId , datasource , ifNoneMatch , callback ) ; Type localVarReturnType = new TypeToken < KillmailResponse > ( ) { } . getType ( ) ; apiClient . executeAsync ( call , localVarReturnType , callback ) ; return call ;
public class EmvParser { /** * Method used to create GPO command and execute it * @ param pPdol * PDOL raw data * @ return return data * @ throws CommunicationException communication error */ protected byte [ ] getGetProcessingOptions ( final byte [ ] pPdol ) throws CommunicationException { } }
// List Tag and length from PDOL List < TagAndLength > list = TlvUtil . parseTagAndLength ( pPdol ) ; ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; try { out . write ( EmvTags . COMMAND_TEMPLATE . getTagBytes ( ) ) ; // COMMAND // TEMPLATE out . write ( TlvUtil . getLength ( list ) ) ; // ADD total length if ( list != null ) { for ( TagAndLength tl : list ) { out . write ( template . get ( ) . getTerminal ( ) . constructValue ( tl ) ) ; } } } catch ( IOException ioe ) { LOGGER . error ( "Construct GPO Command:" + ioe . getMessage ( ) , ioe ) ; } return template . get ( ) . getProvider ( ) . transceive ( new CommandApdu ( CommandEnum . GPO , out . toByteArray ( ) , 0 ) . toBytes ( ) ) ;
public class CommerceNotificationTemplatePersistenceImpl { /** * Returns the commerce notification template where uuid = & # 63 ; and groupId = & # 63 ; or throws a { @ link NoSuchNotificationTemplateException } if it could not be found . * @ param uuid the uuid * @ param groupId the group ID * @ return the matching commerce notification template * @ throws NoSuchNotificationTemplateException if a matching commerce notification template could not be found */ @ Override public CommerceNotificationTemplate findByUUID_G ( String uuid , long groupId ) throws NoSuchNotificationTemplateException { } }
CommerceNotificationTemplate commerceNotificationTemplate = fetchByUUID_G ( uuid , groupId ) ; if ( commerceNotificationTemplate == null ) { StringBundler msg = new StringBundler ( 6 ) ; msg . append ( _NO_SUCH_ENTITY_WITH_KEY ) ; msg . append ( "uuid=" ) ; msg . append ( uuid ) ; msg . append ( ", groupId=" ) ; msg . append ( groupId ) ; msg . append ( "}" ) ; if ( _log . isDebugEnabled ( ) ) { _log . debug ( msg . toString ( ) ) ; } throw new NoSuchNotificationTemplateException ( msg . toString ( ) ) ; } return commerceNotificationTemplate ;
public class Symbol { /** * An accessor method for the type attributes of this symbol . * Attributes of class symbols should be accessed through the accessor * method to make sure that the class symbol is loaded . */ public List < Attribute . TypeCompound > getRawTypeAttributes ( ) { } }
return ( metadata == null ) ? List . < Attribute . TypeCompound > nil ( ) : metadata . getTypeAttributes ( ) ;
public class GrahamScanConvexHull2D { /** * Add a single point to the list ( this does not compute the hull ! ) * @ param point Point to add */ public void add ( double ... point ) { } }
if ( this . ok ) { this . points = new ArrayList < > ( this . points ) ; this . ok = false ; } this . points . add ( point ) ; // Update data set extends minmaxX . put ( point [ 0 ] ) ; minmaxY . put ( point [ 1 ] ) ;
public class ExecutorFilter { /** * Create an OrderedThreadPool executor . * @ param corePoolSize The initial pool sizePoolSize * @ param maximumPoolSize The maximum pool size * @ param keepAliveTime Default duration for a thread * @ param unit Time unit used for the keepAlive value * @ param threadFactory The factory used to create threads * @ param queueHandler The queue used to store events * @ return An instance of the created Executor */ private Executor createDefaultExecutor ( int corePoolSize , int maximumPoolSize , long keepAliveTime , TimeUnit unit , ThreadFactory threadFactory , IoEventQueueHandler queueHandler ) { } }
// Create a new Executor Executor executor = new OrderedThreadPoolExecutor ( corePoolSize , maximumPoolSize , keepAliveTime , unit , threadFactory , queueHandler ) ; return executor ;
public class PropertiesUtil { /** * Returns the Properties formatted as a String * @ param props properties * @ return String format from the Properties * @ throws java . io . IOException if an error occurs */ public static String stringFromProperties ( Properties props ) throws IOException { } }
ByteArrayOutputStream baos = new ByteArrayOutputStream ( 2048 ) ; props . store ( baos , null ) ; String propsString ; propsString = URLEncoder . encode ( baos . toString ( "ISO-8859-1" ) , "ISO-8859-1" ) ; return propsString ;
public class DefaultPrefixConfig { /** * Gets the iterator . * @ return the iterator */ private Iterator < String > getIterator ( ) { } }
final Set < String > copy = getPrefixes ( ) ; final Iterator < String > copyIt = copy . iterator ( ) ; return new Iterator < String > ( ) { private String lastOne = null ; @ Override public boolean hasNext ( ) { return copyIt . hasNext ( ) ; } @ Override public String next ( ) { if ( copyIt . hasNext ( ) ) { lastOne = copyIt . next ( ) ; } else { throw new NoSuchElementException ( ) ; } return lastOne ; } @ Override public void remove ( ) { try { lock . writeLock ( ) . lock ( ) ; prefixes . remove ( lastOne ) ; } finally { lock . writeLock ( ) . unlock ( ) ; } } } ;
public class CmsShellCommands { /** * Checks whether the given user already exists . < p > * @ param name the user name * @ return < code > true < / code > if the given user already exists */ private boolean existsUser ( String name ) { } }
CmsUser user = null ; try { user = m_cms . readUser ( name ) ; } catch ( CmsException e ) { // this will happen , if the user does not exist } return user != null ;
public class ManagementModule { /** * Get an < code > Array < / code > of < code > AbstractInvocationHandler < / code > s . The * ordering is ascending alphabetical , determined by the module parameter * names that begin with the string " decorator " , e . g . " decorator1 " , * " decorator2 " . * @ return An array InvocationHandlers */ private AbstractInvocationHandler [ ] getInvocationHandlers ( ) throws Exception { } }
List < String > pNames = new ArrayList < String > ( ) ; Iterator < String > it = parameterNames ( ) ; String param ; while ( it . hasNext ( ) ) { param = it . next ( ) ; if ( param . startsWith ( "decorator" ) ) { pNames . add ( param ) ; } } Collections . sort ( pNames ) ; AbstractInvocationHandler [ ] invocationHandlers = new AbstractInvocationHandler [ pNames . size ( ) ] ; for ( int i = 0 ; i < pNames . size ( ) ; i ++ ) { invocationHandlers [ i ] = getInvocationHandler ( getParameter ( pNames . get ( i ) ) ) ; if ( invocationHandlers [ i ] instanceof ModuleConfiguredInvocationHandler ) { ( ( ModuleConfiguredInvocationHandler ) invocationHandlers [ i ] ) . init ( this . getServer ( ) ) ; } } return invocationHandlers ;
public class FnJodaToString { /** * It converts the input { @ link BaseDateTime } into a { @ link String } by means of the given pattern or style * ( depending on the value of formatType parameter ) . * @ param formatType the format { @ link FormatType } * @ param format string with the format used for the output * @ param locale { @ link Locale } to be used * @ return the { @ link String } created from the input and arguments */ public static final Function < BaseDateTime , String > fromBaseDateTime ( final FormatType formatType , final String format , final Locale locale ) { } }
return FnJodaString . baseDateTimeToStr ( FnJodaString . FormatType . valueOf ( formatType . name ( ) ) , format , locale ) ;
public class TeaServletAdmin { /** * Provides an ordered array of available templates using a * handy wrapper class . */ @ SuppressWarnings ( "unchecked" ) public TemplateWrapper [ ] getKnownTemplates ( ) { } }
if ( mTemplateOrdering == null ) { setTemplateOrdering ( "name" ) ; } Comparator < TemplateWrapper > comparator = BeanComparator . forClass ( TemplateWrapper . class ) . orderBy ( "name" ) ; Set < TemplateWrapper > known = new TreeSet < TemplateWrapper > ( comparator ) ; TemplateLoader . Template [ ] loaded = mTeaServletEngine . getTemplateSource ( ) . getLoadedTemplates ( ) ; if ( loaded != null ) { for ( int j = 0 ; j < loaded . length ; j ++ ) { TeaServletAdmin . TemplateWrapper wrapper = new TemplateWrapper ( loaded [ j ] , TeaServletInvocationStats . getInstance ( ) . getStatistics ( loaded [ j ] . getName ( ) , null ) , TeaServletInvocationStats . getInstance ( ) . getStatistics ( loaded [ j ] . getName ( ) , "__substitution" ) , TeaServletRequestStats . getInstance ( ) . getStats ( loaded [ j ] . getName ( ) ) ) ; try { known . add ( wrapper ) ; } catch ( ClassCastException cce ) { mTeaServletEngine . getLog ( ) . warn ( cce ) ; } } } String [ ] allNames = mTeaServletEngine . getTemplateSource ( ) . getKnownTemplateNames ( ) ; if ( allNames != null ) { for ( int j = 0 ; j < allNames . length ; j ++ ) { TeaServletAdmin . TemplateWrapper wrapper = new TemplateWrapper ( allNames [ j ] , TeaServletInvocationStats . getInstance ( ) . getStatistics ( allNames [ j ] , null ) , TeaServletInvocationStats . getInstance ( ) . getStatistics ( allNames [ j ] , "__substitution" ) , TeaServletRequestStats . getInstance ( ) . getStats ( allNames [ j ] ) ) ; try { known . add ( wrapper ) ; } catch ( ClassCastException cce ) { mTeaServletEngine . getLog ( ) . warn ( cce ) ; } } } List < TemplateWrapper > v = new ArrayList < TemplateWrapper > ( known ) ; Collections . sort ( v , mTemplateOrdering ) ; // return ( TeaServletAdmin . TemplateWrapper [ ] ) known . toArray ( new TemplateWrapper [ known . size ( ) ] ) ; return v . toArray ( new TemplateWrapper [ v . size ( ) ] ) ;
public class Util { /** * Checks just the flags field of the preamble . Allowed flags are Read Only , Empty , Compact , and * ordered . * @ param flags the flags field */ static void checkHeapFlags ( final int flags ) { } }
// only used by checkPreLongsFlagsCap and test final int allowedFlags = READ_ONLY_FLAG_MASK | EMPTY_FLAG_MASK | COMPACT_FLAG_MASK | ORDERED_FLAG_MASK ; final int flagsMask = ~ allowedFlags ; if ( ( flags & flagsMask ) > 0 ) { throw new SketchesArgumentException ( "Possible corruption: Invalid flags field: " + Integer . toBinaryString ( flags ) ) ; }
public class PrimitiveUtils { /** * Read float . * @ param value the value * @ param defaultValue the default value * @ return the float */ public static Float readFloat ( String value , Float defaultValue ) { } }
if ( ! StringUtils . hasText ( value ) ) return defaultValue ; return Float . valueOf ( value ) ;
public class NetworkEndpointGroupClient { /** * Lists the network endpoints in the specified network endpoint group . * < p > Sample code : * < pre > < code > * try ( NetworkEndpointGroupClient networkEndpointGroupClient = NetworkEndpointGroupClient . create ( ) ) { * ProjectZoneNetworkEndpointGroupName networkEndpointGroup = ProjectZoneNetworkEndpointGroupName . of ( " [ PROJECT ] " , " [ ZONE ] " , " [ NETWORK _ ENDPOINT _ GROUP ] " ) ; * NetworkEndpointGroupsListEndpointsRequest networkEndpointGroupsListEndpointsRequestResource = NetworkEndpointGroupsListEndpointsRequest . newBuilder ( ) . build ( ) ; * for ( NetworkEndpointWithHealthStatus element : networkEndpointGroupClient . listNetworkEndpointsNetworkEndpointGroups ( networkEndpointGroup . toString ( ) , networkEndpointGroupsListEndpointsRequestResource ) . iterateAll ( ) ) { * / / doThingsWith ( element ) ; * < / code > < / pre > * @ param networkEndpointGroup The name of the network endpoint group from which you want to * generate a list of included network endpoints . It should comply with RFC1035. * @ param networkEndpointGroupsListEndpointsRequestResource * @ throws com . google . api . gax . rpc . ApiException if the remote call fails */ @ BetaApi public final ListNetworkEndpointsNetworkEndpointGroupsPagedResponse listNetworkEndpointsNetworkEndpointGroups ( String networkEndpointGroup , NetworkEndpointGroupsListEndpointsRequest networkEndpointGroupsListEndpointsRequestResource ) { } }
ListNetworkEndpointsNetworkEndpointGroupsHttpRequest request = ListNetworkEndpointsNetworkEndpointGroupsHttpRequest . newBuilder ( ) . setNetworkEndpointGroup ( networkEndpointGroup ) . setNetworkEndpointGroupsListEndpointsRequestResource ( networkEndpointGroupsListEndpointsRequestResource ) . build ( ) ; return listNetworkEndpointsNetworkEndpointGroups ( request ) ;
public class BucketIamSnippets { /** * Example of adding a member to the Bucket - level IAM */ public Policy addBucketIamMember ( String bucketName , Role role , Identity identity ) { } }
// [ START add _ bucket _ iam _ member ] // Initialize a Cloud Storage client Storage storage = StorageOptions . getDefaultInstance ( ) . getService ( ) ; // Get IAM Policy for a bucket Policy policy = storage . getIamPolicy ( bucketName ) ; // Add identity to Bucket - level IAM role Policy updatedPolicy = storage . setIamPolicy ( bucketName , policy . toBuilder ( ) . addIdentity ( role , identity ) . build ( ) ) ; if ( updatedPolicy . getBindings ( ) . get ( role ) . contains ( identity ) ) { System . out . printf ( "Added %s with role %s to %s\n" , identity , role , bucketName ) ; } // [ END add _ bucket _ iam _ member ] return updatedPolicy ;
public class PlaceholderSupport { /** * Adds placeholder support to a { @ link DifferenceEngineConfigurer } . * @ param configurer the configurer to add support to * @ param placeholderOpeningDelimiterRegex regular expression for * the opening delimiter of placeholder , defaults to { @ link * PlaceholderDifferenceEvaluator # PLACEHOLDER _ DEFAULT _ OPENING _ DELIMITER _ REGEX } * if the parameter is null or blank * @ param placeholderClosingDelimiterRegex regular expression for * the closing delimiter of placeholder , defaults to { @ link * PlaceholderDifferenceEvaluator # PLACEHOLDER _ DEFAULT _ CLOSING _ DELIMITER _ REGEX } * if the parameter is null or blank * @ return the configurer with placeholder support added in */ public static < D extends DifferenceEngineConfigurer < D > > D withPlaceholderSupportUsingDelimiters ( D configurer , String placeholderOpeningDelimiterRegex , String placeholderClosingDelimiterRegex ) { } }
return configurer . withDifferenceEvaluator ( new PlaceholderDifferenceEvaluator ( placeholderOpeningDelimiterRegex , placeholderClosingDelimiterRegex ) ) ;
public class LoopBarView { /** * Sets new gravity for selector * @ param selectionGravity int value of gravity . Must be one of { @ link GravityAttr } */ public final void setGravity ( @ GravityAttr int selectionGravity ) { } }
mOrientationState . setSelectionGravity ( selectionGravity ) ; // note that mFlContainerSelected should be in FrameLayout FrameLayout . LayoutParams params = ( LayoutParams ) mFlContainerSelected . getLayoutParams ( ) ; params . gravity = mOrientationState . getSelectionGravity ( ) ; mOrientationState . setSelectionMargin ( mSelectionMargin , params ) ; mFlContainerSelected . setLayoutParams ( params ) ; mSelectionGravity = selectionGravity ; invalidate ( ) ; if ( mOuterAdapter != null ) { mOuterAdapter . setSelectedGravity ( selectionGravity ) ; }
public class JCalendarDualField { /** * Set this component ' s name . * Make sure the text component has the same name . * @ param name The name to set . */ public void setName ( String name ) { } }
super . setName ( name ) ; m_tf . setName ( name ) ; if ( m_button != null ) m_button . setName ( name ) ; if ( m_buttonTime != null ) m_buttonTime . setName ( name ) ;
public class UtilOptimize { /** * Iterate until the line search converges or the maximum number of iterations has been exceeded . * The maximum number of steps is specified . A step is defined as the number of times the * optimization parameters are changed . * @ param search Search algorithm * @ param maxSteps Maximum number of steps . * @ return Value returned by { @ link IterativeOptimization # iterate } */ public static boolean process ( IterativeOptimization search , int maxSteps ) { } }
for ( int i = 0 ; i < maxSteps ; i ++ ) { boolean converged = step ( search ) ; if ( converged ) { return search . isConverged ( ) ; } } return true ;
public class IO { /** * Copy Stream in to Stream out until EOF or exception . * in own thread */ public static void copyThread ( InputStream in , OutputStream out ) { } }
try { instance ( ) . run ( new Job ( in , out ) ) ; } catch ( InterruptedException e ) { log . warn ( LogSupport . EXCEPTION , e ) ; }
public class CmsJspImageBean { /** * Returns the image height percentage relative to the image width as a String . < p > * In case a ratio has been used to scale the image , the height percentage is * calculated based on the ratio , not on the actual image pixel size . * This is done to avoid rounding differences . < p > * @ return the image height percentage relative to the image width */ public String getRatioHeightPercentage ( ) { } }
if ( m_ratioHeightPercentage == null ) { m_ratioHeightPercentage = calcRatioHeightPercentage ( getScaler ( ) . getWidth ( ) , getScaler ( ) . getHeight ( ) ) ; } return m_ratioHeightPercentage ;
public class OrmLiteDefaultContentProvider { /** * This method is called after the onUpdate processing has been handled . If you ' re a need , * you can override this method . * @ param result * This is the return value of onUpdate method . * @ param uri * This is the Uri of target . * @ param target * This is identical to the argument of onUpdate method . * It is MatcherPattern objects that match to evaluate Uri by UriMatcher . You can * access information in the tables and columns , ContentUri , MimeType etc . * @ param parameter * This is identical to the argument of onUpdate method . * Arguments passed to the update ( ) method . * @ since 1.0.4 */ protected void onUpdateCompleted ( int result , Uri uri , MatcherPattern target , UpdateParameters parameter ) { } }
this . getContext ( ) . getContentResolver ( ) . notifyChange ( uri , null ) ;
public class CmsBasicFormField { /** * Utility method for creating a basic form field . < p > * @ param propertyConfig the property configuration * @ param additionalParams the additional parameters * @ return the newly created form fields */ public static CmsBasicFormField createField ( CmsXmlContentProperty propertyConfig , Map < String , String > additionalParams ) { } }
return createField ( propertyConfig , propertyConfig . getName ( ) , CmsWidgetFactoryRegistry . instance ( ) , additionalParams , false ) ;
public class PersistTachyon { /** * Split key name composed of tachyon : / / < client - uri > / filename into two parts : * - client - uri without tachyon : / / prefix * - filename * And returns both components . */ private static String [ ] decodeKey ( Key k ) { } }
String s = new String ( ( k . isChunkKey ( ) ) ? Arrays . copyOfRange ( k . _kb , Vec . KEY_PREFIX_LEN , k . _kb . length ) : k . _kb ) ; return decode ( s ) ;
public class RegexValidator { /** * Validate a value against the set of regular expressions . * @ param value The value to validate . * @ return < code > true < / code > if the value is valid otherwise < code > false < / code > . */ public boolean isValid ( String value ) { } }
if ( value == null ) { return false ; } for ( int i = 0 ; i < patterns . length ; i ++ ) { if ( patterns [ i ] . matcher ( value ) . matches ( ) ) { return true ; } } return false ;
public class LruWindowTinyLfuPolicy { /** * Returns all variations of this policy based on the configuration parameters . */ public static Set < Policy > policies ( Config config ) { } }
LruWindowTinyLfuSettings settings = new LruWindowTinyLfuSettings ( config ) ; return settings . percentMain ( ) . stream ( ) . map ( percentMain -> new LruWindowTinyLfuPolicy ( percentMain , settings ) ) . collect ( toSet ( ) ) ;
public class JMElasticsearchBulk { /** * Send with bulk processor and object mapper . * @ param object the object * @ param index the index * @ param type the type */ public void sendWithBulkProcessorAndObjectMapper ( Object object , String index , String type ) { } }
sendWithBulkProcessorAndObjectMapper ( object , index , type , null ) ;
public class BlocksMap { /** * counts number of containing nodes . Better than using iterator . */ int numNodes ( Block b ) { } }
BlockInfo info = blocks . get ( b ) ; return info == null ? 0 : info . numNodes ( ) ;
public class EbsConfiguration { /** * An array of Amazon EBS volume specifications attached to a cluster instance . * @ return An array of Amazon EBS volume specifications attached to a cluster instance . */ public java . util . List < EbsBlockDeviceConfig > getEbsBlockDeviceConfigs ( ) { } }
if ( ebsBlockDeviceConfigs == null ) { ebsBlockDeviceConfigs = new com . amazonaws . internal . SdkInternalList < EbsBlockDeviceConfig > ( ) ; } return ebsBlockDeviceConfigs ;
public class FirewallPolicyService { /** * Update firewall policy * @ param firewallPolicy firewall policy * @ param config firewall policy config * @ return OperationFuture wrapper for firewall policy */ public OperationFuture < FirewallPolicy > update ( FirewallPolicy firewallPolicy , FirewallPolicyConfig config ) { } }
FirewallPolicyMetadata metadata = findByRef ( firewallPolicy ) ; firewallPolicyClient . update ( metadata . getDataCenterId ( ) , metadata . getId ( ) , composeFirewallPolicyRequest ( config ) ) ; return new OperationFuture < > ( firewallPolicy , new NoWaitingJobFuture ( ) ) ;
public class UriEscape { /** * Perform am URI path segment < strong > unescape < / strong > operation * on a < tt > Reader < / tt > input using < tt > UTF - 8 < / tt > as encoding , writing results to a < tt > Writer < / tt > . * This method will unescape every percent - encoded ( < tt > % HH < / tt > ) sequences present in input , * even for those characters that do not need to be percent - encoded in this context ( unreserved characters * can be percent - encoded even if / when this is not required , though it is not generally considered a * good practice ) . * This method will use < tt > UTF - 8 < / tt > in order to determine the characters specified in the * percent - encoded byte sequences . * This method is < strong > thread - safe < / strong > . * @ param reader the < tt > Reader < / tt > reading the text to be unescaped . * @ param writer the < tt > java . io . Writer < / tt > to which the unescaped result will be written . Nothing will * be written at all to this writer if input is < tt > null < / tt > . * @ throws IOException if an input / output exception occurs * @ since 1.1.2 */ public static void unescapeUriPathSegment ( final Reader reader , final Writer writer ) throws IOException { } }
unescapeUriPathSegment ( reader , writer , DEFAULT_ENCODING ) ;
public class XMLOutputter { /** * Checks all invariants . This check should be performed at the end of * every method that changes the internal state of this object . * @ throws Error if the state of this < code > XMLOutputter < / code > is invalid . */ private final void checkInvariants ( ) throws Error { } }
if ( _lineBreak == null ) { throw new Error ( "_lineBreak == null" ) ; } else if ( _lineBreak == LineBreak . NONE && _indentation . length ( ) > 0 ) { throw new Error ( "_lineBreak == LineBreak.NONE && _indentation = \"" + _indentation + "\"." ) ; } else if ( _elementStack == null ) { throw new Error ( "_elementStack (" + _elementStack + " == null" ) ; } else if ( _elementStackSize < 0 ) { throw new Error ( "_elementStackSize (" + _elementStackSize + ") < 0" ) ; }
public class CellTypeProteinConcentration { /** * getter for celltype - gets * @ generated * @ return value of the feature */ public CellType getCelltype ( ) { } }
if ( CellTypeProteinConcentration_Type . featOkTst && ( ( CellTypeProteinConcentration_Type ) jcasType ) . casFeat_celltype == null ) jcasType . jcas . throwFeatMissing ( "celltype" , "ch.epfl.bbp.uima.types.CellTypeProteinConcentration" ) ; return ( CellType ) ( jcasType . ll_cas . ll_getFSForRef ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( CellTypeProteinConcentration_Type ) jcasType ) . casFeatCode_celltype ) ) ) ;
public class ListConfigurationSetsResult { /** * A list of configuration sets . * @ param configurationSets * A list of configuration sets . */ public void setConfigurationSets ( java . util . Collection < ConfigurationSet > configurationSets ) { } }
if ( configurationSets == null ) { this . configurationSets = null ; return ; } this . configurationSets = new com . amazonaws . internal . SdkInternalList < ConfigurationSet > ( configurationSets ) ;
public class DefaultParameterEquivalencer { /** * Obtain the destinationNamespace equivalent value of sourceValue in sourceNamespace * @ param sourceNamespace resourceLocation of source namespace * @ param destinationNamespace resourceLocation of destination namespace * @ param sourceValue * @ return equivalent value , may be null . */ private String doFindEquivalence ( final String sourceNamespace , final String destinationNamespace , final String sourceValue ) { } }
JDBMEquivalenceLookup sourceLookup = openEquivalences . get ( sourceNamespace ) ; if ( sourceLookup == null ) { return null ; } final SkinnyUUID sourceUUID = sourceLookup . lookup ( sourceValue ) ; if ( sourceUUID == null ) { return null ; } return doFindEquivalence ( destinationNamespace , sourceUUID ) ;
public class DE9IMRelation { /** * Check if the spatial relation between two { @ link GeometricShapeVariable } s is of a given type . * @ param gv1 The source { @ link GeometricShapeVariable } . * @ param gv2 The destination { @ link GeometricShapeVariable } . * @ param t The type of relation to check . * @ return < code > true < / code > iff the given variables are in the given relation . */ public static boolean isRelation ( GeometricShapeVariable gv1 , GeometricShapeVariable gv2 , DE9IMRelation . Type t ) { } }
try { String methodName = t . name ( ) . substring ( 0 , 1 ) . toLowerCase ( ) + t . name ( ) . substring ( 1 ) ; Method m = Geometry . class . getMethod ( methodName , Geometry . class ) ; Geometry g1 = ( ( GeometricShapeDomain ) gv1 . getDomain ( ) ) . getGeometry ( ) ; Geometry g2 = ( ( GeometricShapeDomain ) gv2 . getDomain ( ) ) . getGeometry ( ) ; return ( ( Boolean ) m . invoke ( g1 , g2 ) ) ; } catch ( NoSuchMethodException e ) { e . printStackTrace ( ) ; } catch ( SecurityException e ) { e . printStackTrace ( ) ; } catch ( IllegalAccessException e ) { e . printStackTrace ( ) ; } catch ( IllegalArgumentException e ) { e . printStackTrace ( ) ; } catch ( InvocationTargetException e ) { e . printStackTrace ( ) ; } return false ;
public class PathService { /** * Creates a hash code for the given path . */ public int hash ( JimfsPath path ) { } }
int hash = 31 ; hash = 31 * hash + getFileSystem ( ) . hashCode ( ) ; final Name root = path . root ( ) ; final ImmutableList < Name > names = path . names ( ) ; if ( equalityUsesCanonicalForm ) { // use hash codes of names themselves , which are based on the canonical form hash = 31 * hash + ( root == null ? 0 : root . hashCode ( ) ) ; for ( Name name : names ) { hash = 31 * hash + name . hashCode ( ) ; } } else { // use hash codes from toString ( ) form of names hash = 31 * hash + ( root == null ? 0 : root . toString ( ) . hashCode ( ) ) ; for ( Name name : names ) { hash = 31 * hash + name . toString ( ) . hashCode ( ) ; } } return hash ;
public class TreeNavigationView { /** * create navigation in a recursive way . * @ param pitem the item to add new items * @ param plist the list of the navigation entries * @ param pactiveEntry the active entry */ public void createRecursiveNavigation ( final TreeItem pitem , final List < NavigationEntryInterface > plist , final NavigationEntryInterface pactiveEntry ) { } }
for ( final NavigationEntryInterface navEntry : plist ) { final TreeItem newItem ; if ( navEntry instanceof NavigationEntryFolder ) { newItem = new TreeItem ( navEntry . getMenuValue ( ) ) ; createRecursiveNavigation ( newItem , ( ( NavigationEntryFolder ) navEntry ) . getSubEntries ( ) , pactiveEntry ) ; newItem . setState ( navEntry . isOpenOnStartup ( ) ) ; } else if ( navEntry instanceof NavigationLink ) { final Anchor link = ( ( NavigationLink ) navEntry ) . getAnchor ( ) ; link . setStylePrimaryName ( resources . navigationStyle ( ) . link ( ) ) ; newItem = new TreeItem ( link ) ; } else if ( navEntry . getToken ( ) == null ) { newItem = null ; } else { final InlineHyperlink entryPoint = GWT . create ( InlineHyperlink . class ) ; entryPoint . setHTML ( navEntry . getMenuValue ( ) ) ; entryPoint . setTargetHistoryToken ( navEntry . getFullToken ( ) ) ; entryPoint . setStylePrimaryName ( resources . navigationStyle ( ) . link ( ) ) ; newItem = new TreeItem ( entryPoint ) ; navigationMap . put ( newItem , navEntry ) ; } if ( newItem != null ) { pitem . addItem ( newItem ) ; if ( pactiveEntry != null && pactiveEntry . equals ( navEntry ) ) { selectedItem = newItem ; selectedItem . setSelected ( true ) ; } } }
public class Fn { /** * Synchronized { @ code Predicate } * @ param mutex to synchronized on * @ param predicate * @ return */ @ Beta public static < T > Predicate < T > sp ( final Object mutex , final Predicate < T > predicate ) { } }
N . checkArgNotNull ( mutex , "mutex" ) ; N . checkArgNotNull ( predicate , "predicate" ) ; return new Predicate < T > ( ) { @ Override public boolean test ( T t ) { synchronized ( mutex ) { return predicate . test ( t ) ; } } } ;
public class BooleanFormula { /** * / * ( non - Javadoc ) * @ see java . util . Set # removeAll ( java . util . Collection ) */ @ Override public boolean removeAll ( Collection < ? > collection ) { } }
if ( booleanTerms == null ) { return false ; } return booleanTerms . removeAll ( collection ) ;
public class WhereClauseParser { /** * Parse where . * @ param shardingRule databases and tables sharding rule * @ param sqlStatement SQL statement * @ param items select items */ public void parse ( final ShardingRule shardingRule , final SQLStatement sqlStatement , final List < SelectItem > items ) { } }
aliasExpressionParser . parseTableAlias ( ) ; if ( lexerEngine . skipIfEqual ( DefaultKeyword . WHERE ) ) { parseWhere ( shardingRule , sqlStatement , items ) ; }
public class XsdEmitter { /** * Create an XML Schema element from a COBOL data item . * @ param xsdDataItem COBOL data item decorated with XSD attributes * @ return the XML schema element */ public XmlSchemaElement createXmlSchemaElement ( final XsdDataItem xsdDataItem ) { } }
// Let call add root elements if he needs to so for now pretend this is // not a root element XmlSchemaElement element = new XmlSchemaElement ( getXsd ( ) , false ) ; element . setName ( xsdDataItem . getXsdElementName ( ) ) ; if ( xsdDataItem . getMaxOccurs ( ) != 1 ) { element . setMaxOccurs ( xsdDataItem . getMaxOccurs ( ) ) ; } if ( xsdDataItem . getMinOccurs ( ) != 1 ) { element . setMinOccurs ( xsdDataItem . getMinOccurs ( ) ) ; } /* * Create this element schema type , then if its a simple type set it as * an anonymous type . Otherwise , it is a named complex type , so * reference it by name . */ XmlSchemaType xmlSchemaType = createXmlSchemaType ( xsdDataItem ) ; if ( xmlSchemaType == null ) { return null ; } if ( xmlSchemaType instanceof XmlSchemaSimpleType ) { element . setSchemaType ( xmlSchemaType ) ; } else { element . setSchemaTypeName ( xmlSchemaType . getQName ( ) ) ; } if ( getConfig ( ) . addLegStarAnnotations ( ) ) { element . setAnnotation ( _annotationEmitter . createLegStarAnnotation ( xsdDataItem ) ) ; } return element ;
public class XMLParser { /** * Returns true once { @ code limit - position > = minimum } . If the data is * exhausted before that many characters are available , this returns false . * @ param minimum the minimum * @ return true , if successful * @ throws IOException Signals that an I / O exception has occurred . * @ throws KriptonRuntimeException the kripton runtime exception */ private boolean fillBuffer ( int minimum ) throws IOException , KriptonRuntimeException { } }
// If we ' ve exhausted the current content source , remove it while ( nextContentSource != null ) { if ( position < limit ) { throw new KriptonRuntimeException ( "Unbalanced entity!" , true , this . getLineNumber ( ) , this . getColumnNumber ( ) , getPositionDescription ( ) , null ) ; } popContentSource ( ) ; if ( limit - position >= minimum ) { return true ; } } // Before clobbering the old characters , update where buffer starts for ( int i = 0 ; i < position ; i ++ ) { if ( buffer [ i ] == '\n' ) { bufferStartLine ++ ; bufferStartColumn = 0 ; } else { bufferStartColumn ++ ; } } if ( bufferCapture != null ) { bufferCapture . append ( buffer , 0 , position ) ; } if ( limit != position ) { limit -= position ; System . arraycopy ( buffer , position , buffer , 0 , limit ) ; } else { limit = 0 ; } position = 0 ; int total ; while ( ( total = reader . read ( buffer , limit , buffer . length - limit ) ) != - 1 ) { limit += total ; if ( limit >= minimum ) { return true ; } } return false ;
public class Smushing { /** * Workouts the amount of characters that can be smushed across all lines . * @ param figletFont Font definition * @ param char1 Message so far * @ param char2 Char to be added * @ return Maximum overlay across all lines */ @ SuppressWarnings ( "StatementWithEmptyBody" ) private static int calculateOverlay ( FigletFont figletFont , char [ ] [ ] char1 , char [ ] [ ] char2 ) { } }
if ( figletFont . smushingRulesToApply . getHorizontalLayout ( ) == SmushingRule . Layout . FULL_WIDTH ) { return 0 ; } int maxPotentialOverlay = figletFont . maxLine ; for ( int l = 0 ; l < figletFont . height ; l ++ ) { if ( char1 [ l ] == null ) { char1 [ l ] = new char [ 0 ] ; } char [ ] c1 = char1 [ l ] ; char [ ] c2 = char2 [ l ] ; int c1Length = c1 . length - 1 ; int c2Length = c2 . length - 1 ; int c1EmptyCount ; int c2EmptyCount ; for ( c1EmptyCount = 0 ; c1EmptyCount < c1Length && c1 [ c1Length - c1EmptyCount ] == ' ' ; c1EmptyCount ++ ) { } for ( c2EmptyCount = 0 ; c2EmptyCount < c2Length && c2 [ c2EmptyCount ] == ' ' ; c2EmptyCount ++ ) { } int overlay = c1EmptyCount + c2EmptyCount ; if ( c1EmptyCount <= c1Length && c2EmptyCount <= c2Length ) { if ( figletFont . smushingRulesToApply . getHorizontalLayout ( ) == SmushingRule . Layout . SMUSHING && SmushingRule . HORIZONTAL_SMUSHING . smushes ( c1 [ c1Length - c1EmptyCount ] , c2 [ c2EmptyCount ] , figletFont . hardblank ) || figletFont . smushingRulesToApply . smushesHorizontal ( c1 [ c1Length - c1EmptyCount ] , c2 [ c2EmptyCount ] , figletFont . hardblank ) ) { overlay ++ ; } } if ( overlay < maxPotentialOverlay ) { maxPotentialOverlay = overlay ; } } return maxPotentialOverlay ;
public class WebSiteManagementClientImpl { /** * Gets a list of meters for a given location . * Gets a list of meters for a given location . * @ param serviceCallback the async ServiceCallback to handle successful and failed responses . * @ throws IllegalArgumentException thrown if parameters fail the validation * @ return the { @ link ServiceFuture } object */ public ServiceFuture < List < BillingMeterInner > > listBillingMetersAsync ( final ListOperationCallback < BillingMeterInner > serviceCallback ) { } }
return AzureServiceFuture . fromPageResponse ( listBillingMetersSinglePageAsync ( ) , new Func1 < String , Observable < ServiceResponse < Page < BillingMeterInner > > > > ( ) { @ Override public Observable < ServiceResponse < Page < BillingMeterInner > > > call ( String nextPageLink ) { return listBillingMetersNextSinglePageAsync ( nextPageLink ) ; } } , serviceCallback ) ;
public class BufferUtil { /** * Allocate a buffer and fill it from a channel . The returned * buffer will be rewound to the begining . * @ return Buffer containing size bytes from the channel . * @ throws IOException if the channel read does . * @ throws EOFException if a end of stream is encountered * before the full size is read . */ public static ByteBuffer allocateAndReadAll ( int size , ReadableByteChannel channel ) throws IOException { } }
ByteBuffer buf = ByteBuffer . allocate ( size ) ; int justRead ; int totalRead = 0 ; // FIXME , this will be a tight loop if the channel is non - blocking . . . while ( totalRead < size ) { logger . debug ( "reading totalRead={}" , totalRead ) ; if ( ( justRead = channel . read ( buf ) ) < 0 ) throw new EOFException ( "Unexpected end of stream after reading " + totalRead + " bytes" ) ; totalRead += justRead ; } buf . rewind ( ) ; return buf ;
public class Stream { /** * Filters out fields from a stream , resulting in a Stream containing only the fields specified by ` keepFields ` . * For example , if you had a Stream ` mystream ` containing the fields ` [ " a " , " b " , " c " , " d " ] ` , calling " * ` ` ` java * mystream . project ( new Fields ( " b " , " d " ) ) * would produce a stream containing only the fields ` [ " b " , " d " ] ` . * @ param keepFields The fields in the Stream to keep * @ return */ public Stream project ( Fields keepFields ) { } }
projectionValidation ( keepFields ) ; return _topology . addSourcedNode ( this , new ProcessorNode ( _topology . getUniqueStreamId ( ) , _name , keepFields , new Fields ( ) , new ProjectedProcessor ( keepFields ) ) ) ;
public class CompareHelper { /** * Compare the passed items and handle < code > null < / code > values correctly . A * < code > null < / code > value is always smaller than a non - < code > null < / code > * value . * @ param < DATATYPE > * Any object to be used . Both need to be of the same type . * @ param aObj1 * First object to compare . May be < code > null < / code > . * @ param aObj2 * Second object to compare . May be < code > null < / code > . * @ param aComp * The comparator to be used if both parameters are not * < code > null < / code > . The comparator itself may not be * < code > null < / code > . * @ param bNullValuesComeFirst * if < code > true < / code > < code > null < / code > values are ordered before * non - < code > null < / code > values * @ return 0 if they are equal ( or both < code > null < / code > ) , - 1 or + 1. */ public static < DATATYPE > int compare ( @ Nullable final DATATYPE aObj1 , @ Nullable final DATATYPE aObj2 , @ Nonnull final Comparator < ? super DATATYPE > aComp , final boolean bNullValuesComeFirst ) { } }
if ( EqualsHelper . identityEqual ( aObj1 , aObj2 ) ) return 0 ; if ( aObj1 == null ) return bNullValuesComeFirst ? - 1 : + 1 ; if ( aObj2 == null ) return bNullValuesComeFirst ? + 1 : - 1 ; return aComp . compare ( aObj1 , aObj2 ) ;
public class AsymmetricCipher { /** * 非对称加密构造器 * @ param privateKey PKCS8格式的私钥 ( BASE64 encode过的 ) * @ param publicKey X509格式的公钥 ( BASE64 encode过的 ) * @ return AsymmetricCipher */ public static CipherUtil buildInstance ( byte [ ] privateKey , byte [ ] publicKey ) { } }
PrivateKey priKey = KeyTools . getPrivateKeyFromPKCS8 ( Algorithms . RSA . name ( ) , new ByteArrayInputStream ( privateKey ) ) ; PublicKey pubKey = KeyTools . getPublicKeyFromX509 ( Algorithms . RSA . name ( ) , new ByteArrayInputStream ( publicKey ) ) ; return buildInstance ( priKey , pubKey ) ;
public class AFPTwister { /** * orig name : transPdb */ private static void transformOrigPDB ( int n , int [ ] res1 , int [ ] res2 , Atom [ ] ca1 , Atom [ ] ca2 , AFPChain afpChain , int blockNr ) throws StructureException { } }
logger . debug ( "transforming original coordinates {} len1: {} res1: {} len2: {} res2: {}" , n , ca1 . length , res1 . length , ca2 . length , res2 . length ) ; Atom [ ] cod1 = getAtoms ( ca1 , res1 , n , false ) ; Atom [ ] cod2 = getAtoms ( ca2 , res2 , n , false ) ; // double * cod1 = pro1 - > Cod4Res ( n , res1 ) ; // double * cod2 = pro2 - > Cod4Res ( n , res2 ) ; Matrix4d transform = SuperPositions . superpose ( Calc . atomsToPoints ( cod1 ) , Calc . atomsToPoints ( cod2 ) ) ; Matrix r = Matrices . getRotationJAMA ( transform ) ; Atom t = Calc . getTranslationVector ( transform ) ; logger . debug ( "transPdb: transforming orig coordinates with matrix: {}" , r ) ; if ( afpChain != null ) { Matrix [ ] ms = afpChain . getBlockRotationMatrix ( ) ; if ( ms == null ) ms = new Matrix [ afpChain . getBlockNum ( ) ] ; ms [ blockNr ] = r ; Atom [ ] shifts = afpChain . getBlockShiftVector ( ) ; if ( shifts == null ) shifts = new Atom [ afpChain . getBlockNum ( ) ] ; shifts [ blockNr ] = t ; afpChain . setBlockRotationMatrix ( ms ) ; afpChain . setBlockShiftVector ( shifts ) ; } for ( Atom a : ca2 ) Calc . transform ( a . getGroup ( ) , transform ) ;
public class JobTargetExecutionsInner { /** * Lists the target executions of a job step execution . * @ param resourceGroupName The name of the resource group that contains the resource . You can obtain this value from the Azure Resource Manager API or the portal . * @ param serverName The name of the server . * @ param jobAgentName The name of the job agent . * @ param jobName The name of the job to get . * @ param jobExecutionId The id of the job execution * @ param stepName The name of the step . * @ throws IllegalArgumentException thrown if parameters fail the validation * @ return the observable to the PagedList & lt ; JobExecutionInner & gt ; object */ public Observable < ServiceResponse < Page < JobExecutionInner > > > listByStepWithServiceResponseAsync ( final String resourceGroupName , final String serverName , final String jobAgentName , final String jobName , final UUID jobExecutionId , final String stepName ) { } }
return listByStepSinglePageAsync ( resourceGroupName , serverName , jobAgentName , jobName , jobExecutionId , stepName ) . concatMap ( new Func1 < ServiceResponse < Page < JobExecutionInner > > , Observable < ServiceResponse < Page < JobExecutionInner > > > > ( ) { @ Override public Observable < ServiceResponse < Page < JobExecutionInner > > > call ( ServiceResponse < Page < JobExecutionInner > > page ) { String nextPageLink = page . body ( ) . nextPageLink ( ) ; if ( nextPageLink == null ) { return Observable . just ( page ) ; } return Observable . just ( page ) . concatWith ( listByStepNextWithServiceResponseAsync ( nextPageLink ) ) ; } } ) ;
public class StoredPaymentChannelServerStates { /** * < p > Puts the given channel in the channels map and automatically closes it 2 hours before its refund transaction * becomes spendable . < / p > * < p > Because there must be only one , canonical { @ link StoredServerChannel } per channel , this method throws if the * channel is already present in the set of channels . < / p > */ public void putChannel ( final StoredServerChannel channel ) { } }
lock . lock ( ) ; try { checkArgument ( mapChannels . put ( channel . contract . getTxId ( ) , checkNotNull ( channel ) ) == null ) ; // Add the difference between real time and Utils . now ( ) so that test - cases can use a mock clock . Date autocloseTime = new Date ( ( channel . refundTransactionUnlockTimeSecs + CHANNEL_EXPIRE_OFFSET ) * 1000L + ( System . currentTimeMillis ( ) - Utils . currentTimeMillis ( ) ) ) ; log . info ( "Scheduling channel for automatic closure at {}: {}" , autocloseTime , channel ) ; channelTimeoutHandler . schedule ( new TimerTask ( ) { @ Override public void run ( ) { log . info ( "Auto-closing channel: {}" , channel ) ; try { closeChannel ( channel ) ; } catch ( Exception e ) { // Something went wrong closing the channel - we catch // here or else we take down the whole Timer . log . error ( "Auto-closing channel failed" , e ) ; } } } , autocloseTime ) ; } finally { lock . unlock ( ) ; } updatedChannel ( channel ) ;
public class SetVaultAccessPolicyRequestMarshaller { /** * Marshall the given parameter object . */ public void marshall ( SetVaultAccessPolicyRequest setVaultAccessPolicyRequest , ProtocolMarshaller protocolMarshaller ) { } }
if ( setVaultAccessPolicyRequest == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( setVaultAccessPolicyRequest . getAccountId ( ) , ACCOUNTID_BINDING ) ; protocolMarshaller . marshall ( setVaultAccessPolicyRequest . getVaultName ( ) , VAULTNAME_BINDING ) ; protocolMarshaller . marshall ( setVaultAccessPolicyRequest . getPolicy ( ) , POLICY_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; }
public class EscapedFunctions2 { /** * month translation * @ param buf The buffer to append into * @ param parsedArgs arguments * @ throws SQLException if something wrong happens */ public static void sqlmonth ( StringBuilder buf , List < ? extends CharSequence > parsedArgs ) throws SQLException { } }
singleArgumentFunctionCall ( buf , "extract(month from " , "month" , parsedArgs ) ;
public class IOUtil { /** * Converts a resource into a temporary file that can be read by objects * that look up files by name . Returns the file that was created . The file * will be deleted when the program exits . * @ param resourceName the resource to convert . Cannot be < code > null < / code > . * @ param filePrefix the prefix of the temporary file . Cannot be * < code > null < / code > . * @ param fileSuffix the suffix of the temporary file . * @ return a temporary { @ link File } . * @ throws IOException if an error occurs while writing the contents of the * resource to the temporary file . */ public static File resourceToFile ( String resourceName , String filePrefix , String fileSuffix ) throws IOException { } }
BufferedReader reader = new BufferedReader ( new InputStreamReader ( getResourceAsStream ( resourceName ) ) ) ; File outFile = File . createTempFile ( filePrefix , fileSuffix ) ; BufferedWriter writer = new BufferedWriter ( new OutputStreamWriter ( new FileOutputStream ( outFile ) ) ) ; int c ; while ( ( c = reader . read ( ) ) != - 1 ) { writer . write ( c ) ; } reader . close ( ) ; writer . close ( ) ; outFile . deleteOnExit ( ) ; return outFile ;
public class TemplateEngines { /** * This method is used to search for a specific class , telling if loading the engine would succeed . This is * typically used to avoid loading optional modules . * @ param config the configuration * @ param db database instance * @ param engineClassName engine class , used both as a hint to find it and to create the engine itself . @ return null if the engine is not available , an instance of the engine otherwise */ private static AbstractTemplateEngine tryLoadEngine ( final JBakeConfiguration config , final ContentStore db , String engineClassName ) { } }
try { @ SuppressWarnings ( "unchecked" ) Class < ? extends AbstractTemplateEngine > engineClass = ( Class < ? extends AbstractTemplateEngine > ) Class . forName ( engineClassName , false , TemplateEngines . class . getClassLoader ( ) ) ; Constructor < ? extends AbstractTemplateEngine > ctor = engineClass . getConstructor ( JBakeConfiguration . class , ContentStore . class ) ; return ctor . newInstance ( config , db ) ; } catch ( Throwable e ) { // not all engines might be necessary , therefore only emit class loading issue with level warn LOGGER . warn ( "unable to load engine" , e ) ; return null ; }
public class SqlTransientExceptionDetector { /** * Determines if the SQL exception a duplicate value in unique index . * @ param se the exception * @ return true if it is a code 23505 , otherwise false */ public static boolean isSqlStateDuplicateValueInUniqueIndex ( SQLException se ) { } }
String sqlState = se . getSQLState ( ) ; return sqlState != null && ( sqlState . equals ( "23505" ) || se . getMessage ( ) . contains ( "duplicate value in unique index" ) ) ;
public class TransformXMLInterceptor { /** * Override preparePaint in order to perform processing specific to this interceptor . * @ param request the request being responded to . */ @ Override public void preparePaint ( final Request request ) { } }
if ( doTransform && request instanceof ServletRequest ) { HttpServletRequest httpServletRequest = ( ( ServletRequest ) request ) . getBackingRequest ( ) ; String userAgentString = httpServletRequest . getHeader ( "User-Agent" ) ; /* It is possible to opt out on a case by case basis by setting a flag on the ua string . * This helps custom user agents that do not support HTML as well as facilitating debugging . */ if ( userAgentString != null && userAgentString . contains ( NO_XSLT_FLAG ) ) { doTransform = false ; } String debugCookie = ServletUtil . extractCookie ( httpServletRequest , DEBUG_REQUEST ) ; if ( "true" . equals ( debugCookie ) ) { debugRequested = true ; } } super . preparePaint ( request ) ;
public class TransformCliProcessor { /** * Process the transform sub command * @ param ns Namespace which contains parsed commandline arguments * @ return true if the transform is successful , false if an error occured */ @ Override public boolean process ( Namespace ns ) { } }
Chainr chainr ; try { chainr = ChainrFactory . fromFile ( ( File ) ns . get ( "spec" ) ) ; } catch ( Exception e ) { JoltCliUtilities . printToStandardOut ( "Chainr failed to load spec file." , SUPPRESS_OUTPUT ) ; e . printStackTrace ( System . out ) ; return false ; } File file = ns . get ( "input" ) ; Object input = JoltCliUtilities . readJsonInput ( file , SUPPRESS_OUTPUT ) ; Object output ; try { output = chainr . transform ( input ) ; } catch ( Exception e ) { JoltCliUtilities . printToStandardOut ( "Chainr failed to run spec file." , SUPPRESS_OUTPUT ) ; return false ; } Boolean uglyPrint = ns . getBoolean ( "u" ) ; return JoltCliUtilities . printJsonObject ( output , uglyPrint , SUPPRESS_OUTPUT ) ;
public class AbstractCommand { /** * Add a number of { @ link CommandFaceDescriptor } s to this Command . * @ param faceDescriptors a { @ link Map } which contains & lt ; faceDescriptorId , * CommandFaceDescriptor & gt ; pairs . */ public void setFaceDescriptors ( Map faceDescriptors ) { } }
Assert . notNull ( faceDescriptors ) ; Iterator it = faceDescriptors . entrySet ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { Map . Entry entry = ( Map . Entry ) it . next ( ) ; String faceDescriptorId = ( String ) entry . getKey ( ) ; CommandFaceDescriptor faceDescriptor = ( CommandFaceDescriptor ) entry . getValue ( ) ; setFaceDescriptor ( faceDescriptorId , faceDescriptor ) ; }
public class ChannelUpgradeHandler { /** * Add a protocol to this handler . * @ param productString the product string to match * @ param openListener the open listener to call */ public void addProtocol ( String productString , ChannelListener < ? super StreamConnection > openListener ) { } }
addProtocol ( productString , openListener , null ) ;
public class ManyQuery { /** * Execute the query asynchronously * @ param lm * The loader manager to use for loading the data * @ param handler * The ResultHandler to notify of the query result and any updates to that result . * @ param respondsToUpdatedOf * A list of models excluding the queried model that should also trigger a update to the result if they change . * @ return the id of the loader . */ public int getAsync ( android . support . v4 . app . LoaderManager lm , ResultHandler < T > handler , Class < ? extends Model > ... respondsToUpdatedOf ) { } }
if ( Model . class . isAssignableFrom ( resultClass ) ) { respondsToUpdatedOf = Utils . concatArrays ( respondsToUpdatedOf , new Class [ ] { resultClass } ) ; } final int loaderId = placeholderQuery . hashCode ( ) ; lm . restartLoader ( loaderId , null , getSupportLoaderCallbacks ( rawQuery , resultClass , handler , respondsToUpdatedOf ) ) ; return loaderId ;
public class ESigService { /** * Tests if the esig item of the specified type and unique id exists . * @ param esigType The esig type . * @ param id The unique id . * @ return True if a matching item exists in the list . */ @ Override public boolean exist ( IESigType esigType , String id ) { } }
return eSigList . indexOf ( esigType , id ) >= 0 ;
public class EnvironmentCheck { /** * Stylesheet extension entrypoint : Dump a basic Xalan * environment report from getEnvironmentHash ( ) to a Node . * < p > Copy of writeEnvironmentReport that creates a Node suitable * for other processing instead of a properties - like text output . * @ param container Node to append our report to * @ param factory Document providing createElement , etc . services * @ param h Hash presumably from { @ link # getEnvironmentHash ( ) } * @ see # writeEnvironmentReport ( Hashtable ) * for an equivalent that writes to a PrintWriter instead */ public void appendEnvironmentReport ( Node container , Document factory , Hashtable h ) { } }
if ( ( null == container ) || ( null == factory ) ) { return ; } try { Element envCheckNode = factory . createElement ( "EnvironmentCheck" ) ; envCheckNode . setAttribute ( "version" , "$Revision: 468646 $" ) ; container . appendChild ( envCheckNode ) ; if ( null == h ) { Element statusNode = factory . createElement ( "status" ) ; statusNode . setAttribute ( "result" , "ERROR" ) ; statusNode . appendChild ( factory . createTextNode ( "appendEnvironmentReport called with null Hashtable!" ) ) ; envCheckNode . appendChild ( statusNode ) ; return ; } boolean errors = false ; Element hashNode = factory . createElement ( "environment" ) ; envCheckNode . appendChild ( hashNode ) ; for ( Enumeration keys = h . keys ( ) ; keys . hasMoreElements ( ) ; /* no increment portion */ ) { Object key = keys . nextElement ( ) ; String keyStr = ( String ) key ; try { // Special processing for classes found . . if ( keyStr . startsWith ( FOUNDCLASSES ) ) { Vector v = ( Vector ) h . get ( keyStr ) ; // errors | = logFoundJars ( v , keyStr ) ; errors |= appendFoundJars ( hashNode , factory , v , keyStr ) ; } // . . normal processing for all other entries else { // Note : we could just check for the ERROR key by itself , // since we now set that , but since we have to go // through the whole hash anyway , do it this way , // which is safer for maintenance if ( keyStr . startsWith ( ERROR ) ) { errors = true ; } Element node = factory . createElement ( "item" ) ; node . setAttribute ( "key" , keyStr ) ; node . appendChild ( factory . createTextNode ( ( String ) h . get ( keyStr ) ) ) ; hashNode . appendChild ( node ) ; } } catch ( Exception e ) { errors = true ; Element node = factory . createElement ( "item" ) ; node . setAttribute ( "key" , keyStr ) ; node . appendChild ( factory . createTextNode ( ERROR + " Reading " + key + " threw: " + e . toString ( ) ) ) ; hashNode . appendChild ( node ) ; } } // end of for . . . Element statusNode = factory . createElement ( "status" ) ; statusNode . setAttribute ( "result" , ( errors ? "ERROR" : "OK" ) ) ; envCheckNode . appendChild ( statusNode ) ; } catch ( Exception e2 ) { System . err . println ( "appendEnvironmentReport threw: " + e2 . toString ( ) ) ; e2 . printStackTrace ( ) ; }
public class RestClientUtil { /** * 获取文档 , 通过options设置获取文档的参数 * @ param indexName * @ param indexType * @ param documentId * @ param options * @ return * @ throws ElasticSearchException */ public < T > T getDocument ( String indexName , String indexType , String documentId , Map < String , Object > options , Class < T > beanType ) throws ElasticSearchException { } }
try { SearchHit searchResult = this . client . executeRequest ( BuildTool . buildGetDocumentRequest ( indexName , indexType , documentId , options ) , null , new GetDocumentResponseHandler ( beanType ) , ClientUtil . HTTP_GET ) ; return ResultUtil . buildObject ( searchResult , beanType ) ; } catch ( ElasticSearchException e ) { return ResultUtil . hand404HttpRuntimeException ( e , beanType , ResultUtil . OPERTYPE_getDocument ) ; }
public class MultiInstanceCommandClass { /** * Create a MULTI _ CHANNEL _ CAPABILITY _ GET command . * @ param nodeId the target node ID * @ param endPoint the endpoint ID * @ return a DataFrame instance */ public DataFrame createMultiChannelCapabilityGet ( byte nodeId , byte endPoint ) { } }
if ( getVersion ( ) < 2 ) { throw new ZWaveRuntimeException ( "MULTI_CHANNEL_CAPABILITY_GET is not available in command class version 1" ) ; } return createSendDataFrame ( "MULTI_CHANNEL_CAPABILITY_GET" , nodeId , new byte [ ] { MultiInstanceCommandClass . ID , MULTI_CHANNEL_CAPABILITY_GET , endPoint } , true ) ;
public class EnumGene { /** * Create a new enum gene from the given valid genes and the chosen allele * index . * @ param < A > the allele type * @ param alleleIndex the index of the allele for this gene . * @ param validAlleles the array of valid alleles . * @ return a new { @ code EnumGene } with the given with the allele * { @ code validAlleles [ alleleIndex ] } * @ throws java . lang . IllegalArgumentException if the give valid alleles * array is empty of the allele index is out of range . */ @ SafeVarargs public static < A > EnumGene < A > of ( final int alleleIndex , final A ... validAlleles ) { } }
return new EnumGene < > ( alleleIndex , ISeq . of ( validAlleles ) ) ;
public class AuthDataServiceImpl { /** * { @ inheritDoc } */ @ Override public Subject getSubject ( ManagedConnectionFactory managedConnectionFactory , String jaasEntryName , Map < String , Object > loginData ) throws LoginException { } }
if ( jaasEntryName != null ) { return createSubjectUsingJAAS ( jaasEntryName , managedConnectionFactory , loginData ) ; } else { return createSubjectUsingAuthData ( managedConnectionFactory , loginData ) ; }
public class DeploymentNode { /** * Adds a child deployment node . * @ param name the name of the deployment node * @ param description a short description * @ param technology the technology * @ param instances the number of instances * @ return a DeploymentNode object */ public DeploymentNode addDeploymentNode ( String name , String description , String technology , int instances ) { } }
return addDeploymentNode ( name , description , technology , instances , null ) ;
public class AbstractFileRoutesLoader { /** * Helper method . Validates that the format of the controller and method is valid ( i . e . in the form of controller # method ) . * @ param beanAndMethod the beanAndMethod string to be validated . * @ return the same beanAndMethod that was received as an argument . * @ throws ParseException if the format of the controller and method is not valid . */ private String validateControllerAndMethod ( String beanAndMethod , int line ) throws ParseException { } }
int hashPos = beanAndMethod . indexOf ( '#' ) ; if ( hashPos == - 1 ) { throw new ParseException ( "Unrecognized format for '" + beanAndMethod + "'" , line ) ; } return beanAndMethod ;
public class AVUser { /** * whether user is authenticated or not . * @ return */ @ JSONField ( serialize = false ) public boolean isAuthenticated ( ) { } }
// TODO : need to support thirdparty login . String sessionToken = getSessionToken ( ) ; return ! StringUtil . isEmpty ( sessionToken ) ;
public class NumberGauge { /** * { @ inheritDoc } */ @ Override public Number getValue ( int pollerIdx ) { } }
Number n = numberRef . get ( ) ; return n != null ? n : Double . NaN ;
public class ResourceClient { /** * Upload file , only support image file ( jpg , bmp , gif , png ) currently , * file size should not larger than 8M . * @ param path Necessary , the native path of the file you want to upload * @ param fileType should be " image " or " file " or " voice " * @ return UploadResult * @ throws APIConnectionException connect exception * @ throws APIRequestException request exception */ public UploadResult uploadFile ( String path , String fileType ) throws APIConnectionException , APIRequestException { } }
Preconditions . checkArgument ( null != path , "filename is necessary" ) ; Preconditions . checkArgument ( fileType . equals ( "image" ) || fileType . equals ( "file" ) || fileType . equals ( "voice" ) , "Illegal file type!" ) ; File file = new File ( path ) ; if ( file . exists ( ) && file . isFile ( ) ) { long fileSize = file . length ( ) ; if ( fileSize > 8 * 1024 * 1024 ) { throw new IllegalArgumentException ( "File size should not larger than 8M" ) ; } try { // 换行符 final String newLine = "\r\n" ; final String boundaryPrefix = "--" ; // 定义数据分隔线 String BOUNDARY = "========7d4a6d158c9" ; URL url = new URL ( _baseUrl + resourcePath + "?type=" + fileType ) ; HttpURLConnection conn = ( HttpURLConnection ) url . openConnection ( ) ; conn . setRequestMethod ( "POST" ) ; conn . setDoOutput ( true ) ; conn . setDoInput ( true ) ; conn . setUseCaches ( false ) ; conn . setRequestProperty ( "connection" , "Keep-Alive" ) ; conn . setRequestProperty ( "Charset" , "UTF-8" ) ; conn . setRequestProperty ( "Authorization" , this . authCode ) ; conn . setRequestProperty ( "Content-Type" , "multipart/form-data; boundary=" + BOUNDARY ) ; OutputStream out = new DataOutputStream ( conn . getOutputStream ( ) ) ; StringBuilder sb = new StringBuilder ( ) ; sb . append ( boundaryPrefix ) ; sb . append ( BOUNDARY ) ; sb . append ( newLine ) ; sb . append ( "Content-Disposition: form-data;name=\"" + fileType + "\";filename=\"" + path + "\"" + newLine ) ; sb . append ( "Content-Type:application/octet-stream" ) ; // 参数头设置完以后需要两个换行 , 然后才是参数内容 sb . append ( newLine ) ; sb . append ( newLine ) ; out . write ( sb . toString ( ) . getBytes ( ) ) ; DataInputStream dataInputStream = new DataInputStream ( new FileInputStream ( file ) ) ; byte [ ] bufferOut = new byte [ 1024 ] ; int bytes = 0 ; while ( ( bytes = dataInputStream . read ( bufferOut ) ) != - 1 ) { out . write ( bufferOut , 0 , bytes ) ; } out . write ( newLine . getBytes ( ) ) ; dataInputStream . close ( ) ; // 定义最后数据分隔线 , 即 - - 加上BOUNDARY再加上 - - 。 byte [ ] end_data = ( newLine + boundaryPrefix + BOUNDARY + boundaryPrefix + newLine ) . getBytes ( ) ; // 写上结尾标识 out . write ( end_data ) ; out . flush ( ) ; out . close ( ) ; LOG . debug ( "Send request - POST" + " " + url ) ; int status1 = conn . getResponseCode ( ) ; StringBuffer stringBuffer = new StringBuffer ( ) ; InputStream in = null ; if ( status1 / 100 == 2 ) { in = conn . getInputStream ( ) ; } else { in = conn . getErrorStream ( ) ; } if ( null != in ) { InputStreamReader responseContent = new InputStreamReader ( in , "UTF-8" ) ; char [ ] quota = new char [ 1024 ] ; int remaining ; while ( ( remaining = responseContent . read ( quota ) ) > 0 ) { stringBuffer . append ( quota , 0 , remaining ) ; } } ResponseWrapper wrapper = new ResponseWrapper ( ) ; String responseContent1 = stringBuffer . toString ( ) ; wrapper . responseCode = status1 ; wrapper . responseContent = responseContent1 ; String quota1 = conn . getHeaderField ( "X-Rate-Limit-Limit" ) ; String remaining1 = conn . getHeaderField ( "X-Rate-Limit-Remaining" ) ; String reset = conn . getHeaderField ( "X-Rate-Limit-Reset" ) ; wrapper . setRateLimit ( quota1 , remaining1 , reset ) ; if ( status1 >= 200 && status1 < 300 ) { LOG . debug ( "Succeed to get response OK - responseCode:" + status1 ) ; LOG . debug ( "Response Content - " + responseContent1 ) ; } else { if ( status1 < 300 || status1 >= 400 ) { LOG . warn ( "Got error response - responseCode:" + status1 + ", responseContent:" + responseContent1 ) ; wrapper . setErrorObject ( ) ; throw new APIRequestException ( wrapper ) ; } LOG . warn ( "Normal response but unexpected - responseCode:" + status1 + ", responseContent:" + responseContent1 ) ; } return UploadResult . fromResponse ( wrapper , UploadResult . class ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } else { throw new IllegalArgumentException ( "File name is invalid, please check again" ) ; } return null ;
public class ClustersInner { /** * Stops a Kusto cluster . * @ param resourceGroupName The name of the resource group containing the Kusto cluster . * @ param clusterName The name of the Kusto cluster . * @ 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 */ public void stop ( String resourceGroupName , String clusterName ) { } }
stopWithServiceResponseAsync ( resourceGroupName , clusterName ) . toBlocking ( ) . last ( ) . body ( ) ;
public class HandlerReference { /** * Create a new { @ link HandlerReference } from the given values . * @ param component the component * @ param method the method * @ param priority the priority * @ param filter the filter * @ return the handler reference */ public static HandlerReference newRef ( ComponentType component , Method method , int priority , HandlerScope filter ) { } }
if ( handlerTracking . isLoggable ( Level . FINE ) ) { return new VerboseHandlerReference ( component , method , priority , filter ) ; } else { return new HandlerReference ( component , method , priority , filter ) ; }
public class DecimalStyle { /** * Obtains symbols for the specified locale . * This method provides access to locale sensitive symbols . * @ param locale the locale , not null * @ return the info , not null */ public static DecimalStyle of ( Locale locale ) { } }
Jdk8Methods . requireNonNull ( locale , "locale" ) ; DecimalStyle info = CACHE . get ( locale ) ; if ( info == null ) { info = create ( locale ) ; CACHE . putIfAbsent ( locale , info ) ; info = CACHE . get ( locale ) ; } return info ;
public class OMVRBTree { /** * Returns < tt > true < / tt > if this map maps one or more keys to the specified value . More formally , returns < tt > true < / tt > if and * only if this map contains at least one mapping to a value < tt > v < / tt > such that * < tt > ( value = = null ? v = = null : value . equals ( v ) ) < / tt > . This operation will probably require time linear in the map size for most * implementations . * @ param value * value whose presence in this map is to be tested * @ return < tt > true < / tt > if a mapping to < tt > value < / tt > exists ; < tt > false < / tt > otherwise * @ since 1.2 */ @ Override public boolean containsValue ( final Object value ) { } }
for ( OMVRBTreeEntry < K , V > e = getFirstEntry ( ) ; e != null ; e = next ( e ) ) if ( valEquals ( value , e . getValue ( ) ) ) return true ; return false ;
public class JMRandom { /** * Gets bounded number . * @ param random the random * @ param inclusiveLowerBound the inclusive lower bound * @ param exclusiveUpperBound the exclusive upper bound * @ return the bounded number */ public static int getBoundedNumber ( Random random , int inclusiveLowerBound , int exclusiveUpperBound ) { } }
return random . nextInt ( exclusiveUpperBound - inclusiveLowerBound ) + inclusiveLowerBound ;
public class FileService { /** * copy files into sourceFolder into destination folder * @ param copyResourcesMojo * Implementation of mojo with goal ' copy ' * @ param sourceFolder * The source folder * @ param destinationFolder * The destination folder * @ param resource * Resource to process * @ param isFlatten * @ throws InvalidSourceException * Exception throw if source is not valid * @ throws IOException * Exception throw if invalid manipulation files */ static void copyFilesIntoOutputDirectory ( CopyResourcesMojo copyResourcesMojo , File sourceFolder , File destinationFolder , Resource resource , boolean isFlatten ) throws InvalidSourceException , IOException { } }
// check if ( sourceFolder . isFile ( ) ) { throw new InvalidSourceException ( "Expected folder as source, not a file : '" + sourceFolder + "'" ) ; } if ( destinationFolder . isFile ( ) ) { throw new InvalidSourceException ( "Expected destination as source" ) ; } copyResourcesMojo . getLog ( ) . debug ( "Find file into '" + sourceFolder + "'" ) ; // find files into source folder Set < String > files = findFiles ( sourceFolder ) ; copyResourcesMojo . getLog ( ) . debug ( "files before processing :" + files ) ; // process with optional include / exclude options files = processIncludeExclude ( copyResourcesMojo , resource , files ) ; if ( files != null ) { for ( String file : files ) { // source BufferedInputStream reader = new BufferedInputStream ( new FileInputStream ( file ) ) ; // destination StringBuilder finalFile = buildAbsoluteFinalFile ( file , sourceFolder . getAbsolutePath ( ) , destinationFolder , isFlatten ) ; // prepare writer FileUtils . createIntermediateFolders ( String . valueOf ( finalFile ) ) ; BufferedOutputStream writer = new BufferedOutputStream ( new FileOutputStream ( finalFile . toString ( ) , false ) ) ; // copy try { FileUtils . writeFile ( reader , writer ) ; } catch ( IOException e ) { throw e ; } finally { // close all writer . close ( ) ; reader . close ( ) ; } } copyResourcesMojo . getLog ( ) . info ( files . size ( ) + " files in outputDirectory." ) ; }
public class XmlUtils { /** * Converts the an XML file input stream to XML payload . * @ param in the XML file input stream * @ return the payload represents the XML file * @ throws ApiException problem transforming XML to string */ public static String xmlToString ( InputStream in ) throws AlipayApiException { } }
Element root = getRootElementFromStream ( in ) ; return nodeToString ( root ) ;
public class Geomem { /** * Returns a { @ link Predicate } that returns true if and only if a point is * within the bounding box , exclusive of the top ( north ) and left ( west ) * edges . * @ param topLeftLat * latitude of top left point ( north west ) * @ param topLeftLon * longitude of top left point ( north west ) * @ param bottomRightLat * latitude of bottom right point ( south east ) * @ param bottomRightLon * longitude of bottom right point ( south east ) * @ return predicate */ @ VisibleForTesting Predicate < Info < T , R > > createRegionFilter ( final double topLeftLat , final double topLeftLon , final double bottomRightLat , final double bottomRightLon ) { } }
return new Predicate < Info < T , R > > ( ) { @ Override public boolean apply ( Info < T , R > info ) { return info . lat ( ) >= bottomRightLat && info . lat ( ) < topLeftLat && info . lon ( ) > topLeftLon && info . lon ( ) <= bottomRightLon ; } } ;
public class NumberUtil { /** * 将10进制的String安全的转化为Long . * 当str为空或非数字字符串时 , 返回default值 */ public static Long toLongObject ( @ Nullable String str , Long defaultValue ) { } }
if ( StringUtils . isEmpty ( str ) ) { return defaultValue ; } try { return Long . valueOf ( str ) ; } catch ( final NumberFormatException nfe ) { return defaultValue ; }
public class ListPlaybackConfigurationsResult { /** * Array of playback configurations . This might be all the available configurations or a subset , depending on the * settings that you provide and the total number of configurations stored . * @ param items * Array of playback configurations . This might be all the available configurations or a subset , depending on * the settings that you provide and the total number of configurations stored . */ public void setItems ( java . util . Collection < PlaybackConfiguration > items ) { } }
if ( items == null ) { this . items = null ; return ; } this . items = new java . util . ArrayList < PlaybackConfiguration > ( items ) ;
public class ManagedInstancesInner { /** * Updates a managed instance . * @ param resourceGroupName The name of the resource group that contains the resource . You can obtain this value from the Azure Resource Manager API or the portal . * @ param managedInstanceName The name of the managed instance . * @ param parameters The requested managed instance resource state . * @ throws IllegalArgumentException thrown if parameters fail the validation * @ return the observable for the request */ public Observable < ManagedInstanceInner > updateAsync ( String resourceGroupName , String managedInstanceName , ManagedInstanceUpdate parameters ) { } }
return updateWithServiceResponseAsync ( resourceGroupName , managedInstanceName , parameters ) . map ( new Func1 < ServiceResponse < ManagedInstanceInner > , ManagedInstanceInner > ( ) { @ Override public ManagedInstanceInner call ( ServiceResponse < ManagedInstanceInner > response ) { return response . body ( ) ; } } ) ;
public class Select { /** * Returns the selected item or < code > null < / code > if no item is selected . * @ return the selected items list */ public Option getSelectedItem ( ) { } }
for ( Entry < OptionElement , Option > entry : itemMap . entrySet ( ) ) { Option opt = entry . getValue ( ) ; if ( opt . isSelected ( ) ) return opt ; } return null ;
public class CompressUtils { /** * 字符串压缩为GZIP字节数组 * @ param str * @ param encoding * @ return */ public static byte [ ] gzipCompress ( String str , String encoding ) { } }
if ( str == null || str . length ( ) == 0 ) { return null ; } ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; GZIPOutputStream gzip ; try { gzip = new GZIPOutputStream ( out ) ; gzip . write ( str . getBytes ( encoding ) ) ; gzip . close ( ) ; } catch ( IOException e ) { } return out . toByteArray ( ) ;
public class InChITautomerGenerator { /** * Pops and pushes its ways through the InChI connection table to build up a simple molecule . * @ param inputInchi user input InChI * @ param inputMolecule user input molecule * @ param inchiAtomsByPosition * @ return molecule with single bonds and no hydrogens . */ private IAtomContainer connectAtoms ( String inputInchi , IAtomContainer inputMolecule , Map < Integer , IAtom > inchiAtomsByPosition ) throws CDKException { } }
String inchi = inputInchi ; inchi = inchi . substring ( inchi . indexOf ( '/' ) + 1 ) ; inchi = inchi . substring ( inchi . indexOf ( '/' ) + 1 ) ; String connections = inchi . substring ( 1 , inchi . indexOf ( '/' ) ) ; Pattern connectionPattern = Pattern . compile ( "(-|\\(|\\)|,|([0-9])*)" ) ; Matcher match = connectionPattern . matcher ( connections ) ; Stack < IAtom > atomStack = new Stack < IAtom > ( ) ; IAtomContainer inchiMolGraph = inputMolecule . getBuilder ( ) . newInstance ( IAtomContainer . class ) ; boolean pop = false ; boolean push = true ; while ( match . find ( ) ) { String group = match . group ( ) ; push = true ; if ( ! group . isEmpty ( ) ) { if ( group . matches ( "[0-9]*" ) ) { IAtom atom = inchiAtomsByPosition . get ( Integer . valueOf ( group ) ) ; if ( ! inchiMolGraph . contains ( atom ) ) inchiMolGraph . addAtom ( atom ) ; IAtom prevAtom = null ; if ( atomStack . size ( ) != 0 ) { if ( pop ) { prevAtom = atomStack . pop ( ) ; } else { prevAtom = atomStack . get ( atomStack . size ( ) - 1 ) ; } IBond bond = inputMolecule . getBuilder ( ) . newInstance ( IBond . class , prevAtom , atom , IBond . Order . SINGLE ) ; inchiMolGraph . addBond ( bond ) ; } if ( push ) { atomStack . push ( atom ) ; } } else if ( group . equals ( "-" ) ) { pop = true ; push = true ; } else if ( group . equals ( "," ) ) { atomStack . pop ( ) ; pop = false ; push = false ; } else if ( group . equals ( "(" ) ) { pop = false ; push = true ; } else if ( group . equals ( ")" ) ) { atomStack . pop ( ) ; pop = true ; push = true ; } else { throw new CDKException ( "Unexpected token " + group + " in connection table encountered." ) ; } } } // put any unconnected atoms in the output as well for ( IAtom at : inchiAtomsByPosition . values ( ) ) { if ( ! inchiMolGraph . contains ( at ) ) inchiMolGraph . addAtom ( at ) ; } return inchiMolGraph ;
public class SQLUtils { /** * 获得主键where子句 , 包含where关键字 。 会自动处理软删除条件 * @ param t * @ param keyValues 返回传入sql的参数 , 如果提供list则写入 * @ return 返回值前面会带空格 , 以确保安全 。 * @ throws NoKeyColumnAnnotationException * @ throws NullKeyValueException */ public static < T > String getKeysWhereSQL ( T t , List < Object > keyValues ) throws NoKeyColumnAnnotationException , NullKeyValueException { } }
List < Field > keyFields = DOInfoReader . getKeyColumns ( t . getClass ( ) ) ; List < Object > _keyValues = new ArrayList < Object > ( ) ; String where = joinWhereAndGetValue ( keyFields , "AND" , _keyValues , t ) ; // 检查主键不允许为null for ( Object value : keyValues ) { if ( value == null ) { throw new NullKeyValueException ( ) ; } } if ( keyValues != null ) { keyValues . addAll ( _keyValues ) ; } return autoSetSoftDeleted ( "WHERE " + where , t . getClass ( ) ) ;
public class JobLauncherUtils { /** * Utility method that takes in a { @ link List } of { @ link WorkUnit } s , and flattens them . It builds up * the flattened list by checking each element of the given list , and seeing if it is an instance of * { @ link MultiWorkUnit } . If it is then it calls itself on the { @ link WorkUnit } s returned by * { @ link MultiWorkUnit # getWorkUnits ( ) } . If not , then it simply adds the { @ link WorkUnit } to the * flattened list . * @ param workUnits is a { @ link List } containing either { @ link WorkUnit } s or { @ link MultiWorkUnit } s * @ return a { @ link List } of flattened { @ link WorkUnit } s */ public static List < WorkUnit > flattenWorkUnits ( Collection < WorkUnit > workUnits ) { } }
List < WorkUnit > flattenedWorkUnits = Lists . newArrayList ( ) ; for ( WorkUnit workUnit : workUnits ) { if ( workUnit instanceof MultiWorkUnit ) { flattenedWorkUnits . addAll ( flattenWorkUnits ( ( ( MultiWorkUnit ) workUnit ) . getWorkUnits ( ) ) ) ; } else { flattenedWorkUnits . add ( workUnit ) ; } } return flattenedWorkUnits ;
public class SquigglyUtils { /** * Converts an object to an instance of the target type . * @ param mapper the object mapper * @ param source the source to convert * @ param targetType the target class type * @ return target instance * @ see SquigglyUtils # objectify ( ObjectMapper , Object , Class ) */ public static < T > T objectify ( ObjectMapper mapper , Object source , JavaType targetType ) { } }
try { return mapper . readValue ( mapper . writeValueAsBytes ( source ) , targetType ) ; } catch ( RuntimeException e ) { throw e ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; }
public class AbstractCodeCreator { /** * Gets a property by it ' s name * @ param name the name of the property to find * @ return the property or EMPTY */ public CreatorProperty findPropertyValue ( String name ) { } }
return properties ( ) . stream ( ) . filter ( p -> name . equals ( p . getName ( ) ) ) . findFirst ( ) . orElse ( EMPTY ) ;
public class TreeWalker { /** * End processing of given node * @ param node Node we just finished processing * @ throws org . xml . sax . SAXException */ protected void endNode ( Node node ) throws org . xml . sax . SAXException { } }
switch ( node . getNodeType ( ) ) { case Node . DOCUMENT_NODE : break ; case Node . ELEMENT_NODE : String ns = m_dh . getNamespaceOfNode ( node ) ; if ( null == ns ) ns = "" ; this . m_contentHandler . endElement ( ns , m_dh . getLocalNameOfNode ( node ) , node . getNodeName ( ) ) ; if ( m_Serializer == null ) { // Don ' t bother with endPrefixMapping calls if the ContentHandler is a // SerializationHandler because SerializationHandler ' s ignore the // endPrefixMapping ( ) calls anyways . . . . This is an optimization . Element elem_node = ( Element ) node ; NamedNodeMap atts = elem_node . getAttributes ( ) ; int nAttrs = atts . getLength ( ) ; // do the endPrefixMapping calls in reverse order // of the startPrefixMapping calls for ( int i = ( nAttrs - 1 ) ; 0 <= i ; i -- ) { final Node attr = atts . item ( i ) ; final String attrName = attr . getNodeName ( ) ; final int colon = attrName . indexOf ( ':' ) ; final String prefix ; if ( attrName . equals ( "xmlns" ) || attrName . startsWith ( "xmlns:" ) ) { // Use " " instead of null , as Xerces likes " " for the // name of the default namespace . Fix attributed // to " Steven Murray " < smurray @ ebt . com > . if ( colon < 0 ) prefix = "" ; else prefix = attrName . substring ( colon + 1 ) ; this . m_contentHandler . endPrefixMapping ( prefix ) ; } else if ( colon > 0 ) { prefix = attrName . substring ( 0 , colon ) ; this . m_contentHandler . endPrefixMapping ( prefix ) ; } } { String uri = elem_node . getNamespaceURI ( ) ; if ( uri != null ) { String prefix = elem_node . getPrefix ( ) ; if ( prefix == null ) prefix = "" ; this . m_contentHandler . endPrefixMapping ( prefix ) ; } } } break ; case Node . CDATA_SECTION_NODE : break ; case Node . ENTITY_REFERENCE_NODE : { EntityReference eref = ( EntityReference ) node ; if ( m_contentHandler instanceof LexicalHandler ) { LexicalHandler lh = ( ( LexicalHandler ) this . m_contentHandler ) ; lh . endEntity ( eref . getNodeName ( ) ) ; } } break ; default : }
public class CmsJspTagContainer { /** * Internal action method . < p > * @ return EVAL _ BODY _ BUFFERED * @ see javax . servlet . jsp . tagext . Tag # doStartTag ( ) */ @ Override public int doStartTag ( ) { } }
if ( CmsFlexController . isCmsRequest ( pageContext . getRequest ( ) ) ) { m_paramState = new ParamState ( CmsFlexController . getController ( pageContext . getRequest ( ) ) . getCurrentRequest ( ) ) ; m_paramState . init ( ) ; } return EVAL_BODY_BUFFERED ;
public class KinesisStreamShard { /** * Utility function to convert { @ link KinesisStreamShard } into the new { @ link StreamShardMetadata } model . * @ param kinesisStreamShard the { @ link KinesisStreamShard } to be converted * @ return the converted { @ link StreamShardMetadata } */ public static StreamShardMetadata convertToStreamShardMetadata ( KinesisStreamShard kinesisStreamShard ) { } }
StreamShardMetadata streamShardMetadata = new StreamShardMetadata ( ) ; streamShardMetadata . setStreamName ( kinesisStreamShard . getStreamName ( ) ) ; streamShardMetadata . setShardId ( kinesisStreamShard . getShard ( ) . getShardId ( ) ) ; streamShardMetadata . setParentShardId ( kinesisStreamShard . getShard ( ) . getParentShardId ( ) ) ; streamShardMetadata . setAdjacentParentShardId ( kinesisStreamShard . getShard ( ) . getAdjacentParentShardId ( ) ) ; if ( kinesisStreamShard . getShard ( ) . getHashKeyRange ( ) != null ) { streamShardMetadata . setStartingHashKey ( kinesisStreamShard . getShard ( ) . getHashKeyRange ( ) . getStartingHashKey ( ) ) ; streamShardMetadata . setEndingHashKey ( kinesisStreamShard . getShard ( ) . getHashKeyRange ( ) . getEndingHashKey ( ) ) ; } if ( kinesisStreamShard . getShard ( ) . getSequenceNumberRange ( ) != null ) { streamShardMetadata . setStartingSequenceNumber ( kinesisStreamShard . getShard ( ) . getSequenceNumberRange ( ) . getStartingSequenceNumber ( ) ) ; streamShardMetadata . setEndingSequenceNumber ( kinesisStreamShard . getShard ( ) . getSequenceNumberRange ( ) . getEndingSequenceNumber ( ) ) ; } return streamShardMetadata ;
public class AModuleModulesAssistantTC { /** * Generate the exportdefs list of definitions . The exports list of export declarations is processed by searching * the defs list of locally defined objects . The exportdefs field is populated with the result . * @ param m */ public void processExports ( AModuleModules m ) { } }
if ( m . getExports ( ) != null ) { m . getExportdefs ( ) . clear ( ) ; if ( ! m . getIsDLModule ( ) ) { m . getExportdefs ( ) . addAll ( getDefinitions ( m . getExports ( ) , m . getDefs ( ) ) ) ; } else { m . getExportdefs ( ) . addAll ( getDefinitions ( m . getExports ( ) ) ) ; } }
public class ConstituencyTreeFactor { /** * Returns true if the boolean chart represents a set of spans that form a * valid constituency tree , false otherwise . */ private static boolean isTree ( int n , boolean [ ] [ ] chart ) { } }
if ( ! chart [ 0 ] [ n ] ) { // Root must be a span . return false ; } for ( int width = 1 ; width <= n ; width ++ ) { for ( int start = 0 ; start <= n - width ; start ++ ) { int end = start + width ; if ( width == 1 ) { if ( ! chart [ start ] [ end ] ) { // All width 1 spans must be set . return false ; } } else { if ( chart [ start ] [ end ] ) { // Count the number of pairs of child spans which could have been combined to form this span . int childPairCount = 0 ; for ( int mid = start + 1 ; mid <= end - 1 ; mid ++ ) { if ( chart [ start ] [ mid ] && chart [ mid ] [ end ] ) { childPairCount ++ ; } } if ( childPairCount != 1 ) { // This span should have been built from exactly one pair of child spans . return false ; } } } } } return true ;