idx int64 0 41.2k | question stringlengths 74 4.21k | target stringlengths 5 888 |
|---|---|---|
21,100 | private Map < String , List < String > > shakeHands ( ) throws WebSocketException { Socket socket = mSocketConnector . getSocket ( ) ; WebSocketInputStream input = openInputStream ( socket ) ; WebSocketOutputStream output = openOutputStream ( socket ) ; String key = generateWebSocketKey ( ) ; writeHandshake ( output , ... | Perform the opening handshake . |
21,101 | private WebSocketInputStream openInputStream ( Socket socket ) throws WebSocketException { try { return new WebSocketInputStream ( new BufferedInputStream ( socket . getInputStream ( ) ) ) ; } catch ( IOException e ) { throw new WebSocketException ( WebSocketError . SOCKET_INPUT_STREAM_FAILURE , "Failed to get the inpu... | Open the input stream of the WebSocket connection . The stream is used by the reading thread . |
21,102 | private WebSocketOutputStream openOutputStream ( Socket socket ) throws WebSocketException { try { return new WebSocketOutputStream ( new BufferedOutputStream ( socket . getOutputStream ( ) ) ) ; } catch ( IOException e ) { throw new WebSocketException ( WebSocketError . SOCKET_OUTPUT_STREAM_FAILURE , "Failed to get th... | Open the output stream of the WebSocket connection . The stream is used by the writing thread . |
21,103 | private void writeHandshake ( WebSocketOutputStream output , String key ) throws WebSocketException { mHandshakeBuilder . setKey ( key ) ; String requestLine = mHandshakeBuilder . buildRequestLine ( ) ; List < String [ ] > headers = mHandshakeBuilder . buildHeaders ( ) ; String handshake = HandshakeBuilder . build ( re... | Send an opening handshake request to the WebSocket server . |
21,104 | private Map < String , List < String > > readHandshake ( WebSocketInputStream input , String key ) throws WebSocketException { return new HandshakeReader ( this ) . readHandshake ( input , key ) ; } | Receive an opening handshake response from the WebSocket server . |
21,105 | private void startThreads ( ) { ReadingThread readingThread = new ReadingThread ( this ) ; WritingThread writingThread = new WritingThread ( this ) ; synchronized ( mThreadsLock ) { mReadingThread = readingThread ; mWritingThread = writingThread ; } readingThread . callOnThreadCreated ( ) ; writingThread . callOnThread... | Start both the reading thread and the writing thread . |
21,106 | private void stopThreads ( long closeDelay ) { ReadingThread readingThread ; WritingThread writingThread ; synchronized ( mThreadsLock ) { readingThread = mReadingThread ; writingThread = mWritingThread ; mReadingThread = null ; mWritingThread = null ; } if ( readingThread != null ) { readingThread . requestStop ( clos... | Stop both the reading thread and the writing thread . |
21,107 | void onReadingThreadStarted ( ) { boolean bothStarted = false ; synchronized ( mThreadsLock ) { mReadingThreadStarted = true ; if ( mWritingThreadStarted ) { bothStarted = true ; } } callOnConnectedIfNotYet ( ) ; if ( bothStarted ) { onThreadsStarted ( ) ; } } | Called by the reading thread as its first step . |
21,108 | void onReadingThreadFinished ( WebSocketFrame closeFrame ) { synchronized ( mThreadsLock ) { mReadingThreadFinished = true ; mServerCloseFrame = closeFrame ; if ( mWritingThreadFinished == false ) { return ; } } onThreadsFinished ( ) ; } | Called by the reading thread as its last step . |
21,109 | void onWritingThreadFinished ( WebSocketFrame closeFrame ) { synchronized ( mThreadsLock ) { mWritingThreadFinished = true ; mClientCloseFrame = closeFrame ; if ( mReadingThreadFinished == false ) { return ; } } onThreadsFinished ( ) ; } | Called by the writing thread as its last step . |
21,110 | private PerMessageCompressionExtension findAgreedPerMessageCompressionExtension ( ) { if ( mAgreedExtensions == null ) { return null ; } for ( WebSocketExtension extension : mAgreedExtensions ) { if ( extension instanceof PerMessageCompressionExtension ) { return ( PerMessageCompressionExtension ) extension ; } } retur... | Find a per - message compression extension from among the agreed extensions . |
21,111 | public static byte [ ] getBytesUTF8 ( String string ) { if ( string == null ) { return null ; } try { return string . getBytes ( "UTF-8" ) ; } catch ( UnsupportedEncodingException e ) { return null ; } } | Get a UTF - 8 byte array representation of the given string . |
21,112 | public static String toOpcodeName ( int opcode ) { switch ( opcode ) { case CONTINUATION : return "CONTINUATION" ; case TEXT : return "TEXT" ; case BINARY : return "BINARY" ; case CLOSE : return "CLOSE" ; case PING : return "PING" ; case PONG : return "PONG" ; default : break ; } if ( 0x1 <= opcode && opcode <= 0x7 ) {... | Convert a WebSocket opcode into a string representation . |
21,113 | public static String readLine ( InputStream in , String charset ) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; while ( true ) { int b = in . read ( ) ; if ( b == - 1 ) { if ( baos . size ( ) == 0 ) { return null ; } else { break ; } } if ( b == '\n' ) { break ; } if ( b != '\r' ) { ... | Read a line from the given stream . |
21,114 | public static int min ( int [ ] values ) { int min = Integer . MAX_VALUE ; for ( int i = 0 ; i < values . length ; ++ i ) { if ( values [ i ] < min ) { min = values [ i ] ; } } return min ; } | Find the minimum value from the given array . |
21,115 | public static int max ( int [ ] values ) { int max = Integer . MIN_VALUE ; for ( int i = 0 ; i < values . length ; ++ i ) { if ( max < values [ i ] ) { max = values [ i ] ; } } return max ; } | Find the maximum value from the given array . |
21,116 | private static int [ ] createIntArray ( int size , int initialValue ) { int [ ] array = new int [ size ] ; for ( int i = 0 ; i < size ; ++ i ) { array [ i ] = initialValue ; } return array ; } | Create an array whose elements have the given initial value . |
21,117 | protected < X > Specification < ENTITY > equalsSpecification ( Function < Root < ENTITY > , Expression < X > > metaclassFunction , final X value ) { return ( root , query , builder ) -> builder . equal ( metaclassFunction . apply ( root ) , value ) ; } | Generic method which based on a Root< ; ENTITY> ; returns an Expression which type is the same as the given value type . |
21,118 | public T get ( String key ) { purge ( ) ; final Value val = map . get ( key ) ; final long time = System . currentTimeMillis ( ) ; return val != null && time < val . expire ? val . token : null ; } | Get a token from the cache . |
21,119 | public void put ( String key , T token ) { purge ( ) ; if ( map . containsKey ( key ) ) { map . remove ( key ) ; } final long time = System . currentTimeMillis ( ) ; map . put ( key , new Value ( token , time + expireMillis ) ) ; latestWriteTime = time ; } | Put a token in the cache . If a token already exists for the given key it is replaced . |
21,120 | protected Parameter createPageParameter ( ParameterContext context ) { ModelReference intModel = createModelRefFactory ( context ) . apply ( resolver . resolve ( Integer . TYPE ) ) ; return new ParameterBuilder ( ) . name ( getPageName ( ) ) . parameterType ( PAGE_TYPE ) . modelRef ( intModel ) . description ( PAGE_DES... | Create a page parameter . Override it if needed . Set a default value for example . |
21,121 | protected Parameter createSizeParameter ( ParameterContext context ) { ModelReference intModel = createModelRefFactory ( context ) . apply ( resolver . resolve ( Integer . TYPE ) ) ; return new ParameterBuilder ( ) . name ( getSizeName ( ) ) . parameterType ( SIZE_TYPE ) . modelRef ( intModel ) . description ( SIZE_DES... | Create a size parameter . Override it if needed . Set a default value for example . |
21,122 | protected Parameter createSortParameter ( ParameterContext context ) { ModelReference stringModel = createModelRefFactory ( context ) . apply ( resolver . resolve ( List . class , String . class ) ) ; return new ParameterBuilder ( ) . name ( getSortName ( ) ) . parameterType ( SORT_TYPE ) . modelRef ( stringModel ) . a... | Create a sort parameter . Override it if needed . Set a default value or further description for example . |
21,123 | public V get ( K key ) throws CacheException { logger . debug ( "get key [" + key + "]" ) ; if ( key == null ) { return null ; } try { Object redisCacheKey = getRedisCacheKey ( key ) ; byte [ ] rawValue = redisManager . get ( keySerializer . serialize ( redisCacheKey ) ) ; if ( rawValue == null ) { return null ; } V va... | get shiro authorization redis key - value |
21,124 | public int size ( ) { Long longSize = 0L ; try { longSize = new Long ( redisManager . dbSize ( keySerializer . serialize ( this . keyPrefix + "*" ) ) ) ; } catch ( SerializationException e ) { logger . error ( "get keys error" , e ) ; } return longSize . intValue ( ) ; } | get all authorization key - value quantity |
21,125 | public void del ( byte [ ] key ) { if ( key == null ) { return ; } Jedis jedis = getJedis ( ) ; try { jedis . del ( key ) ; } finally { jedis . close ( ) ; } } | Delete a key - value pair . |
21,126 | public Long dbSize ( byte [ ] pattern ) { long dbSize = 0L ; Jedis jedis = getJedis ( ) ; try { ScanParams params = new ScanParams ( ) ; params . count ( count ) ; params . match ( pattern ) ; byte [ ] cursor = ScanParams . SCAN_POINTER_START_BINARY ; ScanResult < byte [ ] > scanResult ; do { scanResult = jedis . scan ... | Return the size of redis db . |
21,127 | public Set < byte [ ] > keys ( byte [ ] pattern ) { Set < byte [ ] > keys = new HashSet < byte [ ] > ( ) ; Jedis jedis = getJedis ( ) ; try { ScanParams params = new ScanParams ( ) ; params . count ( count ) ; params . match ( pattern ) ; byte [ ] cursor = ScanParams . SCAN_POINTER_START_BINARY ; ScanResult < byte [ ] ... | Return all the keys of Redis db . Filtered by pattern . |
21,128 | public static NumberList delta ( Map < String , Object > currentMap , Map < String , Object > previousMap ) { LinkedHashMap < String , Long > values = new LinkedHashMap < String , Long > ( currentMap . size ( ) ) ; if ( currentMap . size ( ) != previousMap . size ( ) ) { throw new IllegalArgumentException ( "Maps must ... | This assumes both maps contain the same keys . If they don t then keys will be lost . |
21,129 | public static NumberList deltaInverse ( Map < String , Object > map ) { LinkedHashMap < String , Long > values = new LinkedHashMap < String , Long > ( map . size ( ) ) ; for ( Entry < String , Object > k : map . entrySet ( ) ) { Object v = k . getValue ( ) ; Number current = getNumber ( v ) ; long d = - current . longV... | Return a NubmerList with the inverse of the given values . |
21,130 | @ SuppressWarnings ( "unused" ) private static Observable < GroupedObservable < TypeAndNameKey , Map < String , Object > > > aggregateUsingFlattenedGroupBy ( Observable < GroupedObservable < InstanceKey , Map < String , Object > > > stream ) { Observable < Map < String , Object > > allData = stream . flatMap ( instance... | Flatten the stream and then do nested groupBy . This matches the mental model and is simple but serializes the stream to a single thread which is bad for performance . |
21,131 | private static Observable < Map < String , Object > > tombstone ( Observable < Map < String , Object > > instanceStream , InstanceKey instanceKey ) { return instanceStream . publish ( is -> { Observable < Map < String , Object > > tombstone = is . collect ( ( ) -> new HashSet < TypeAndNameKey > ( ) , ( listOfTypeAndNam... | Append tombstone events to each instanceStream when they terminate so that the last values from the stream will be removed from all aggregates down stream . |
21,132 | public static Properties getFromInstanceConfig ( InstanceConfig defaultInstanceConfig ) { PropertyBasedInstanceConfig config = new PropertyBasedInstanceConfig ( new ConfigCollectionImpl ( defaultInstanceConfig , null ) ) ; return config . getProperties ( ) ; } | Return the default properties given an instance config |
21,133 | public static InstanceConfig newDefaultInstanceConfig ( BackupProvider provider ) { List < EncodedConfigParser . FieldValue > backupDefaultValues = Lists . newArrayList ( ) ; if ( provider != null ) { for ( BackupConfigSpec spec : provider . getConfigs ( ) ) { backupDefaultValues . add ( new EncodedConfigParser . Field... | Return the standard default properties as an instance config |
21,134 | public List < String > toDisplayList ( final String separator , ExhibitorArguments . LogDirection logDirection ) { Iterable < String > transformed = Iterables . transform ( queue , new Function < Message , String > ( ) { public String apply ( Message message ) { return message . date + separator + message . type + sepa... | Return the current window lines |
21,135 | public void add ( Type type , String message , Throwable exception ) { String queueMessage = message ; if ( ( type == Type . ERROR ) && ( exception != null ) ) { queueMessage += " (" + getExceptionMessage ( exception ) + ")" ; } if ( type . addToUI ( ) ) { while ( queue . size ( ) > windowSizeLines ) { queue . remove (... | Add a log message with an exception |
21,136 | public static String getExceptionMessage ( Throwable exception ) { StringWriter out = new StringWriter ( ) ; exception . printStackTrace ( new PrintWriter ( out ) ) ; BufferedReader in = new BufferedReader ( new StringReader ( out . toString ( ) ) ) ; try { StringBuilder str = new StringBuilder ( ) ; for ( ; ; ) { Stri... | Convert an exception into a log message |
21,137 | public String getValue ( final String field ) { FieldValue fieldValue = Iterables . find ( fieldValues , new Predicate < FieldValue > ( ) { public boolean apply ( FieldValue fv ) { return fv . getField ( ) . equals ( field ) ; } } , null ) ; return ( fieldValue != null ) ? fieldValue . getValue ( ) : null ; } | Return the value for the given field or null |
21,138 | public static DefaultResourceConfig newApplicationConfig ( UIContext context ) { final Set < Object > singletons = getSingletons ( context ) ; final Set < Class < ? > > classes = getClasses ( ) ; return new DefaultResourceConfig ( ) { public Set < Class < ? > > getClasses ( ) { return classes ; } public Set < Object > ... | Return a new Jersey config instance that correctly supplies all needed Exhibitor objects |
21,139 | public ServerList filterOutObservers ( ) { Iterable < ServerSpec > filtered = Iterables . filter ( specs , new Predicate < ServerSpec > ( ) { public boolean apply ( ServerSpec spec ) { return spec . getServerType ( ) != ServerType . OBSERVER ; } } ) ; return new ServerList ( Lists . newArrayList ( filtered ) ) ; } | Return this server list with any observers removed |
21,140 | public void start ( ) { for ( QueueGroups group : QueueGroups . values ( ) ) { final DelayQueue < ActivityHolder > thisQueue = queues . get ( group ) ; service . submit ( new Runnable ( ) { public void run ( ) { try { while ( ! Thread . currentThread ( ) . isInterrupted ( ) ) { ActivityHolder holder = thisQueue . take ... | The queue must be started |
21,141 | public synchronized void add ( QueueGroups group , Activity activity ) { add ( group , activity , 0 , TimeUnit . MILLISECONDS ) ; } | Add an activity to the given queue |
21,142 | public synchronized void add ( QueueGroups group , Activity activity , long delay , TimeUnit unit ) { ActivityHolder holder = new ActivityHolder ( activity , TimeUnit . MILLISECONDS . convert ( delay , unit ) ) ; queues . get ( group ) . offer ( holder ) ; } | Add an activity to the given queue that executes after a specified delay |
21,143 | public synchronized void replace ( QueueGroups group , Activity activity ) { replace ( group , activity , 0 , TimeUnit . MILLISECONDS ) ; } | Replace the given activity in the given queue . If not in the queue adds it to the queue . |
21,144 | public static String getHostname ( ) { String host = "unknown" ; try { return InetAddress . getLocalHost ( ) . getHostName ( ) ; } catch ( UnknownHostException e ) { } return host ; } | Return this VM s hostname if possible |
21,145 | public void start ( ) throws Exception { Preconditions . checkState ( state . compareAndSet ( State . LATENT , State . STARTED ) ) ; backupManager . restoreAll ( ) ; activityQueue . start ( ) ; configManager . start ( ) ; monitorRunningInstance . start ( ) ; cleanupManager . start ( ) ; backupManager . start ( ) ; auto... | Start the app |
21,146 | public List < BackupMetaData > getAvailableBackups ( ) throws Exception { Map < String , String > config = getBackupConfig ( ) ; return backupProvider . get ( ) . getAvailableBackups ( exhibitor , config ) ; } | Return list of available backups |
21,147 | public BackupStream getBackupStream ( BackupMetaData metaData ) throws Exception { return backupProvider . get ( ) . getBackupStream ( exhibitor , metaData , getBackupConfig ( ) ) ; } | Return a stream for the specified backup |
21,148 | public void restoreAll ( ) throws Exception { if ( ! backupProvider . isPresent ( ) ) { log . info ( "No backup provider configured. Skipping restore." ) ; return ; } ZooKeeperLogFiles logFiles = new ZooKeeperLogFiles ( exhibitor ) ; log . info ( "Restoring log files from backup." ) ; if ( ! logFiles . isValid ( ) ) { ... | Restore all known logs |
21,149 | public void restore ( BackupMetaData backup , File destinationFile ) throws Exception { File tempFile = File . createTempFile ( "exhibitor-backup" , ".tmp" ) ; OutputStream out = new FileOutputStream ( tempFile ) ; InputStream in = null ; try { backupProvider . get ( ) . downloadBackup ( exhibitor , backup , out , getB... | Restore the given key to the given file |
21,150 | public static By byAttribute ( String attributeName , String attributeValue ) { return By . cssSelector ( String . format ( "[%s='%s']" , attributeName , attributeValue ) ) ; } | Find elements having attribute with given value . |
21,151 | public static List < String > texts ( Collection < WebElement > elements ) { return elements . stream ( ) . map ( ElementsCollection :: getText ) . collect ( toList ( ) ) ; } | Fail - safe method for retrieving texts of given elements . |
21,152 | public static String elementsToString ( Driver driver , Collection < WebElement > elements ) { if ( elements == null ) { return "[not loaded yet...]" ; } if ( elements . isEmpty ( ) ) { return "[]" ; } StringBuilder sb = new StringBuilder ( 256 ) ; sb . append ( "[\n\t" ) ; for ( WebElement element : elements ) { if ( ... | Outputs string presentation of the element s collection |
21,153 | public void start ( ) { proxy . setTrustAllServers ( true ) ; if ( outsideProxy != null ) { proxy . setChainedProxy ( getProxyAddress ( outsideProxy ) ) ; } addRequestFilter ( "authentication" , new AuthenticationFilter ( ) ) ; addRequestFilter ( "requestSizeWatchdog" , new RequestSizeWatchdog ( ) ) ; addResponseFilter... | Start the server |
21,154 | public Proxy createSeleniumProxy ( ) { return isEmpty ( config . proxyHost ( ) ) ? ClientUtil . createSeleniumProxy ( proxy ) : ClientUtil . createSeleniumProxy ( proxy , inetAddressResolver . getInetAddressByName ( config . proxyHost ( ) ) ) ; } | Converts this proxy to a selenium proxy that can be used by webdriver |
21,155 | @ SuppressWarnings ( "unchecked" ) public < T extends RequestFilter > T requestFilter ( String name ) { return ( T ) requestFilters . get ( name ) ; } | Get request filter by name |
21,156 | @ SuppressWarnings ( "unchecked" ) public < T extends ResponseFilter > T responseFilter ( String name ) { return ( T ) responseFilters . get ( name ) ; } | Get response filter by name |
21,157 | public static Condition value ( final String expectedValue ) { return new Condition ( "value" ) { public boolean apply ( Driver driver , WebElement element ) { return Html . text . contains ( getAttributeValue ( element , "value" ) , expectedValue ) ; } public String toString ( ) { return name + " '" + expectedValue + ... | Assert that element has given value attribute as substring NB! Ignores difference in non - visible characters like spaces non - breakable spaces tabs newlines etc . |
21,158 | public static Condition matchText ( final String regex ) { return new Condition ( "match text" ) { public boolean apply ( Driver driver , WebElement element ) { return Html . text . matches ( element . getText ( ) , regex ) ; } public String toString ( ) { return name + " '" + regex + '\'' ; } } ; } | Assert that given element s text matches given regular expression |
21,159 | public static Condition selectedText ( final String expectedText ) { return new Condition ( "selectedText" ) { String actualResult = "" ; public boolean apply ( Driver driver , WebElement element ) { actualResult = driver . executeJavaScript ( "return arguments[0].value.substring(arguments[0].selectionStart, arguments[... | Checks for selected text on a given input web element |
21,160 | public static Condition and ( String name , final Condition ... condition ) { return new Condition ( name ) { private Condition lastFailedCondition ; public boolean apply ( Driver driver , WebElement element ) { for ( Condition c : condition ) { if ( ! c . apply ( driver , element ) ) { lastFailedCondition = c ; return... | Check if element matches ALL given conditions . |
21,161 | private Object convertStringToNearestObjectType ( String value ) { switch ( value ) { case "true" : return true ; case "false" : return false ; default : { if ( NumberUtils . isParsable ( value ) ) { return Integer . parseInt ( value ) ; } return value ; } } } | Converts String to Boolean \ Integer or returns original String . |
21,162 | private boolean isScrolling ( ) { float scrolledX = Math . abs ( accumulatedScrollOffset . x ) ; int expectedScrollX = Math . abs ( width * monthsScrolledSoFar ) ; return scrolledX < expectedScrollX - 5 || scrolledX > expectedScrollX + 5 ; } | as it maybe off by a few pixels |
21,163 | private void drawEventsWithPlus ( Canvas canvas , float xPosition , float yPosition , List < Event > eventsList ) { for ( int j = 0 , k = - 2 ; j < 3 ; j ++ , k += 2 ) { Event event = eventsList . get ( j ) ; float xStartPosition = xPosition + ( xIndicatorOffset * k ) ; if ( j == 2 ) { dayPaint . setColor ( multiEventI... | draw 2 eventsByMonthAndYearMap followed by plus indicator to show there are more than 2 eventsByMonthAndYearMap |
21,164 | int getDayOfWeek ( Calendar calendar ) { int dayOfWeek = calendar . get ( Calendar . DAY_OF_WEEK ) - firstDayOfWeekToDraw ; dayOfWeek = dayOfWeek < 0 ? 7 + dayOfWeek : dayOfWeek ; return dayOfWeek ; } | it returns 0 - 6 where 0 is Sunday instead of 1 |
21,165 | private void drawCircle ( Canvas canvas , float x , float y , int color , float circleScale ) { dayPaint . setColor ( color ) ; if ( animationStatus == ANIMATE_INDICATORS ) { float maxRadius = circleScale * bigCircleIndicatorRadius * 1.4f ; drawCircle ( canvas , growfactorIndicator > maxRadius ? maxRadius : growfactorI... | Draw Circle on certain days to highlight them |
21,166 | private String getKeyForCalendarEvent ( Calendar cal ) { return cal . get ( Calendar . YEAR ) + "_" + cal . get ( Calendar . MONTH ) ; } | E . g . 4 2016 becomes 2016_4 |
21,167 | public void unfixDialogDimens ( ) { Logr . d ( "Reset the fixed dimensions to allow for re-measurement" ) ; getLayoutParams ( ) . height = LayoutParams . MATCH_PARENT ; getLayoutParams ( ) . width = LayoutParams . MATCH_PARENT ; requestLayout ( ) ; } | This method should only be called if the calendar is contained in a dialog and it should only be called when the screen has been rotated and the dialog should be re - measured . |
21,168 | AtomicInteger inflightRequests ( Id id ) { return Utils . computeIfAbsent ( inflightRequests , id , i -> new AtomicInteger ( ) ) ; } | Return the number of inflight requests associated with the given id . |
21,169 | Function < String , String > limiterForKey ( String key ) { return Utils . computeIfAbsent ( limiters , key , k -> CardinalityLimiters . rollup ( 25 ) ) ; } | Return the cardinality limiter for a given key . This is used to protect the metrics backend from a metrics explosion if some dimensions have a high cardinality . |
21,170 | void log ( IpcLogEntry entry ) { Level level = entry . getLevel ( ) ; Predicate < Marker > enabled ; BiConsumer < Marker , String > log ; switch ( level ) { case TRACE : enabled = logger :: isTraceEnabled ; log = logger :: trace ; break ; case DEBUG : enabled = logger :: isDebugEnabled ; log = logger :: debug ; break ;... | Called by the entry to log the request . |
21,171 | public static SeqServerGroup parse ( String asg ) { int d1 = asg . indexOf ( '-' ) ; int d2 = asg . indexOf ( '-' , d1 + 1 ) ; int dN = asg . lastIndexOf ( '-' ) ; if ( dN < 0 || ! isSequence ( asg , dN ) ) { dN = asg . length ( ) ; } return new SeqServerGroup ( asg , d1 , d2 , dN ) ; } | Create a new instance of a server group object by parsing the group name . |
21,172 | private static CharSequence substr ( CharSequence str , int s , int e ) { return ( s >= e ) ? null : CharBuffer . wrap ( str , s , e ) ; } | The substring method will create a copy of the substring in JDK 8 and probably newer versions . To reduce the number of allocations we use a char buffer to return a view with just that subset . |
21,173 | public static IdBuilder < Builder > builder ( Registry registry ) { return new IdBuilder < Builder > ( registry ) { protected Builder createTypeBuilder ( Id id ) { return new Builder ( registry , id ) ; } } ; } | Return a builder for configuring and retrieving and instance of a percentile distribution summary . If the distribution summary has dynamic dimensions then the builder can be used with the new dimensions . If the id is the same as an existing distribution summary then it will update the same underlying distribution sum... |
21,174 | private Counter counterFor ( int i ) { Counter c = counters . get ( i ) ; if ( c == null ) { Id counterId = id . withTags ( Statistic . percentile , new BasicTag ( "percentile" , TAG_VALUES [ i ] ) ) ; c = registry . counter ( counterId ) ; counters . set ( i , c ) ; } return c ; } | accessed for a distribution summary . |
21,175 | public double percentile ( double p ) { long [ ] counts = new long [ PercentileBuckets . length ( ) ] ; for ( int i = 0 ; i < counts . length ; ++ i ) { counts [ i ] = counterFor ( i ) . count ( ) ; } return PercentileBuckets . percentile ( counts , p ) ; } | Computes the specified percentile for this distribution summary . |
21,176 | public void max ( double v ) { if ( Double . isFinite ( v ) ) { double max = get ( ) ; while ( isGreaterThan ( v , max ) && ! compareAndSet ( max , v ) ) { max = value . get ( ) ; } } } | Set the current value to the maximum of the current value or the provided value . |
21,177 | static byte [ ] encode ( Map < String , String > commonTags , List < Measurement > measurements ) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; JsonGenerator gen = FACTORY . createGenerator ( baos ) ; gen . writeStartArray ( ) ; Map < String , Integer > strings = buildStringTable ( g... | Encode the measurements to a JSON payload that can be sent to the aggregator . |
21,178 | public static SparkValueFunction fromConfig ( Config config , String key ) { return fromPatternList ( config . getConfigList ( key ) ) ; } | Create a value function based on a config . |
21,179 | @ SuppressWarnings ( "unchecked" ) protected < T extends Meter > T getOrCreate ( Id id , Class < T > cls , T dflt , Function < Id , T > factory ) { try { Preconditions . checkNotNull ( id , "id" ) ; Meter m = Utils . computeIfAbsent ( meters , id , i -> compute ( factory . apply ( i ) , dflt ) ) ; if ( ! cls . isAssign... | Helper used to get or create an instance of a core meter type . This is mostly used internally to this implementation but may be useful in rare cases for creating customizations based on a core type in a sub - class . |
21,180 | protected void removeExpiredMeters ( ) { int total = 0 ; int expired = 0 ; Iterator < Map . Entry < Id , Meter > > it = meters . entrySet ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { ++ total ; Map . Entry < Id , Meter > entry = it . next ( ) ; Meter m = entry . getValue ( ) ; if ( m . hasExpired ( ) ) { ++ expire... | Can be called by sub - classes to remove expired meters from the internal map . The SwapMeter types that are returned will lookup a new copy on the next access . |
21,181 | private void cleanupCachedState ( ) { int total = 0 ; int expired = 0 ; Iterator < Map . Entry < Id , Object > > it = state . entrySet ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { ++ total ; Map . Entry < Id , Object > entry = it . next ( ) ; Object obj = entry . getValue ( ) ; if ( obj instanceof Meter && ( ( Met... | Cleanup any expired meter patterns stored in the state . It should only be used as a cache so the entry should get recreated if needed . |
21,182 | public static BucketDistributionSummary get ( Id id , BucketFunction f ) { return get ( Spectator . globalRegistry ( ) , id , f ) ; } | Creates a distribution summary object that manages a set of distribution summaries based on the bucket function supplied . Calling record will be mapped to the record on the appropriate distribution summary . |
21,183 | static String getServletPath ( HttpServletRequest request ) { String servletPath = request . getServletPath ( ) ; if ( hackWorks && PACKAGE . equals ( request . getClass ( ) . getPackage ( ) . getName ( ) ) ) { try { Object outer = get ( request , "this$0" ) ; Object servletPipeline = get ( outer , "servletPipeline" ) ... | Helper to get the servlet path for the request . |
21,184 | public < E extends Enum < E > > T withTag ( String k , Enum < E > v ) { return withTag ( k , v . name ( ) ) ; } | Add an additional tag value based on the name of the enum . |
21,185 | public IpcLogEntry withException ( Throwable exception ) { this . exception = exception ; if ( statusDetail == null ) { statusDetail = exception . getClass ( ) . getSimpleName ( ) ; } if ( status == null ) { status = IpcStatus . forException ( exception ) ; } return this ; } | Set the exception that was thrown while trying to execute the request . This will be logged and can be used to fill in the error reason . |
21,186 | public IpcLogEntry withUri ( String uri , String path ) { this . uri = uri ; this . path = path ; return this ; } | Set the URI and path for the request . |
21,187 | public void log ( ) { if ( logger != null ) { if ( registry != null ) { if ( isClient ( ) ) { recordClientMetrics ( ) ; } else { recordServerMetrics ( ) ; } } if ( inflightId != null ) { logger . inflightRequests ( inflightId ) . decrementAndGet ( ) ; } logger . log ( this ) ; } else { reset ( ) ; } } | Log the request . This entry will potentially be reused after this is called . The user should not attempt any further modifications to the state of this entry . |
21,188 | void reset ( ) { logger = null ; level = Level . DEBUG ; marker = null ; startTime = - 1L ; startNanos = - 1L ; latency = - 1L ; owner = null ; result = null ; protocol = null ; status = null ; statusDetail = null ; exception = null ; attempt = null ; attemptFinal = null ; vip = null ; endpoint = null ; clientRegion = ... | Resets this log entry so the instance can be reused . This helps to reduce allocations . |
21,189 | void resetForRetry ( ) { startTime = - 1L ; startNanos = - 1L ; latency = - 1L ; result = null ; status = null ; statusDetail = null ; exception = null ; attempt = null ; attemptFinal = null ; vip = null ; serverRegion = null ; serverZone = null ; serverApp = null ; serverCluster = null ; serverAsg = null ; serverNode ... | Partially reset this log entry so it can be used for another request attempt . Any attributes that can change for a given request need to be cleared . |
21,190 | public static PatternMatcher compile ( String pattern ) { String p = pattern ; boolean ignoreCase = false ; if ( p . startsWith ( "(?i)" ) ) { ignoreCase = true ; p = pattern . substring ( 4 ) ; } if ( p . length ( ) > 0 ) { p = "^.*(" + p + ").*$" ; } Parser parser = new Parser ( PatternUtils . expandEscapedChars ( p ... | Compile a pattern string and return a matcher that can be used to check if string values match the pattern . Pattern matchers are can be reused many times and are thread safe . |
21,191 | static IllegalArgumentException error ( String message , String str , int pos ) { return new IllegalArgumentException ( message + "\n" + context ( str , pos ) ) ; } | Create an IllegalArgumentException with a message including context based on the position . |
21,192 | static UnsupportedOperationException unsupported ( String message , String str , int pos ) { return new UnsupportedOperationException ( message + "\n" + context ( str , pos ) ) ; } | Create an UnsupportedOperationException with a message including context based on the position . |
21,193 | @ SuppressWarnings ( "PMD.NcssCount" ) static String expandEscapedChars ( String str ) { StringBuilder builder = new StringBuilder ( ) ; for ( int i = 0 ; i < str . length ( ) ; ++ i ) { char c = str . charAt ( i ) ; if ( c == '\\' ) { ++ i ; if ( i >= str . length ( ) ) { throw error ( "dangling escape" , str , i ) ; ... | Expand escaped characters . Escapes that are needed for structural elements of the pattern will not be expanded . |
21,194 | @ SuppressWarnings ( "PMD.NcssCount" ) static String escape ( String str ) { StringBuilder builder = new StringBuilder ( ) ; for ( int i = 0 ; i < str . length ( ) ; ++ i ) { char c = str . charAt ( i ) ; switch ( c ) { case '\t' : builder . append ( "\\t" ) ; break ; case '\n' : builder . append ( "\\n" ) ; break ; ca... | Escape a string so it will be interpreted as a literal character sequence when processed as a regular expression . |
21,195 | static Matcher ignoreCase ( Matcher matcher ) { if ( matcher instanceof CharClassMatcher ) { CharClassMatcher m = matcher . as ( ) ; return new CharClassMatcher ( m . set ( ) , true ) ; } else if ( matcher instanceof CharSeqMatcher ) { CharSeqMatcher m = matcher . as ( ) ; return new CharSeqMatcher ( m . pattern ( ) , ... | Convert to a matchers that ignores the case . |
21,196 | static Matcher head ( Matcher matcher ) { if ( matcher instanceof SeqMatcher ) { List < Matcher > ms = matcher . < SeqMatcher > as ( ) . matchers ( ) ; return ms . get ( 0 ) ; } else { return matcher ; } } | Returns the first matcher from a sequence . |
21,197 | static Matcher tail ( Matcher matcher ) { if ( matcher instanceof SeqMatcher ) { List < Matcher > ms = matcher . < SeqMatcher > as ( ) . matchers ( ) ; return SeqMatcher . create ( ms . subList ( 1 , ms . size ( ) ) ) ; } else { return TrueMatcher . INSTANCE ; } } | Returns all but the first matcher from a sequence or True if there is only a single matcher in the sequence . |
21,198 | static DefaultPlaceholderId createWithFactories ( String name , Iterable < TagFactory > tagFactories , Registry registry ) { if ( tagFactories == null ) { return new DefaultPlaceholderId ( name , registry ) ; } else { FactorySorterAndDeduplicator sorter = new FactorySorterAndDeduplicator ( tagFactories ) ; return new D... | Creates a new id with the specified name and collection of factories . |
21,199 | private DefaultPlaceholderId createNewId ( Consumer < FactorySorterAndDeduplicator > consumer ) { FactorySorterAndDeduplicator sorter = new FactorySorterAndDeduplicator ( tagFactories ) ; consumer . accept ( sorter ) ; return new DefaultPlaceholderId ( name , sorter . asCollection ( ) , registry ) ; } | Creates a new dynamic id based on the factories associated with this id and whatever additions are made by the specified consumer . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.