idx int64 0 41.2k | question stringlengths 83 4.15k | target stringlengths 5 715 |
|---|---|---|
10,100 | public static Distribution addSample ( double value , Distribution distribution ) { Builder builder = distribution . toBuilder ( ) ; switch ( distribution . getBucketOptionCase ( ) ) { case EXPLICIT_BUCKETS : updateStatistics ( value , builder ) ; updateExplicitBuckets ( value , builder ) ; return builder . build ( ) ; case EXPONENTIAL_BUCKETS : updateStatistics ( value , builder ) ; updateExponentialBuckets ( value , builder ) ; return builder . build ( ) ; case LINEAR_BUCKETS : updateStatistics ( value , builder ) ; updateLinearBuckets ( value , builder ) ; return builder . build ( ) ; default : throw new IllegalArgumentException ( MSG_UNKNOWN_BUCKET_OPTION_TYPE ) ; } } | Updates as new distribution that contains value added to an existing one . |
10,101 | public synchronized void start ( ) { if ( running ) { log . atInfo ( ) . log ( "%s is already started" , this ) ; return ; } log . atInfo ( ) . log ( "starting %s" , this ) ; this . stopped = false ; this . running = true ; this . reportStopwatch . reset ( ) . start ( ) ; try { schedulerThread = threads . newThread ( new Runnable ( ) { public void run ( ) { scheduleFlushes ( ) ; } } ) ; schedulerThread . start ( ) ; } catch ( RuntimeException e ) { log . atInfo ( ) . log ( BACKGROUND_THREAD_ERROR ) ; schedulerThread = null ; initializeFlushing ( ) ; } } | Starts processing . |
10,102 | public void stop ( ) { Preconditions . checkState ( running , "Cannot stop if it's not running" ) ; synchronized ( this ) { log . atInfo ( ) . log ( "stopping client background thread and flushing the report aggregator" ) ; for ( ReportRequest req : reportAggregator . clear ( ) ) { try { transport . services ( ) . report ( serviceName , req ) . execute ( ) ; } catch ( IOException e ) { log . atSevere ( ) . withCause ( e ) . log ( "direct send of a report request failed" ) ; } } this . stopped = true ; if ( isRunningSchedulerDirectly ( ) ) { resetIfStopped ( ) ; } this . scheduler = null ; } } | Stops processing . |
10,103 | public CheckResponse check ( CheckRequest req ) { startIfStopped ( ) ; statistics . totalChecks . incrementAndGet ( ) ; Stopwatch w = Stopwatch . createStarted ( ticker ) ; CheckResponse resp = checkAggregator . check ( req ) ; statistics . totalCheckCacheLookupTimeMillis . addAndGet ( w . elapsed ( TimeUnit . MILLISECONDS ) ) ; if ( resp != null ) { statistics . checkHits . incrementAndGet ( ) ; log . atFiner ( ) . log ( "using cached check response for %s: %s" , req , resp ) ; return resp ; } try { w . reset ( ) . start ( ) ; resp = transport . services ( ) . check ( serviceName , req ) . execute ( ) ; statistics . totalCheckTransportTimeMillis . addAndGet ( w . elapsed ( TimeUnit . MILLISECONDS ) ) ; checkAggregator . addResponse ( req , resp ) ; return resp ; } catch ( IOException e ) { log . atSevere ( ) . withCause ( e ) . log ( "direct send of a check request %s failed" , req ) ; return null ; } } | Process a check request . |
10,104 | public void report ( ReportRequest req ) { startIfStopped ( ) ; statistics . totalReports . incrementAndGet ( ) ; statistics . reportedOperations . addAndGet ( req . getOperationsCount ( ) ) ; Stopwatch w = Stopwatch . createStarted ( ticker ) ; boolean reported = reportAggregator . report ( req ) ; statistics . totalReportCacheUpdateTimeMillis . addAndGet ( w . elapsed ( TimeUnit . MILLISECONDS ) ) ; if ( ! reported ) { try { statistics . directReports . incrementAndGet ( ) ; w . reset ( ) . start ( ) ; transport . services ( ) . report ( serviceName , req ) . execute ( ) ; statistics . totalTransportedReportTimeMillis . addAndGet ( w . elapsed ( TimeUnit . MILLISECONDS ) ) ; } catch ( IOException e ) { log . atSevere ( ) . withCause ( e ) . log ( "direct send of a report request %s failed" , req ) ; } } if ( isRunningSchedulerDirectly ( ) ) { try { scheduler . run ( false ) ; } catch ( InterruptedException e ) { log . atSevere ( ) . withCause ( e ) . log ( "direct run of scheduler failed" ) ; } } logStatistics ( ) ; } | Process a report request . |
10,105 | public Set < TraceeBackendProvider > getBackendProviders ( ) { final Map < ClassLoader , Set < TraceeBackendProvider > > cacheCopy = providersPerClassloader ; final Set < TraceeBackendProvider > providerFromContextClassLoader = getTraceeProviderFromClassloader ( cacheCopy , GetClassLoader . fromContext ( ) ) ; if ( ! providerFromContextClassLoader . isEmpty ( ) ) { return providerFromContextClassLoader ; } else { return getTraceeProviderFromClassloader ( cacheCopy , GetClassLoader . fromClass ( BackendProviderResolver . class ) ) ; } } | Find correct backend provider for the current context classloader . If no context classloader is available a fallback with the classloader of this resolver class is taken |
10,106 | Set < TraceeBackendProvider > getDefaultTraceeBackendProvider ( ) { try { final ClassLoader classLoader = GetClassLoader . fromContext ( ) ; final Class < ? > slf4jTraceeBackendProviderClass = Class . forName ( "io.tracee.backend.slf4j.Slf4jTraceeBackendProvider" , true , classLoader ) ; final TraceeBackendProvider instance = ( TraceeBackendProvider ) slf4jTraceeBackendProviderClass . newInstance ( ) ; updatedCache ( classLoader , Collections . singleton ( instance ) ) ; return Collections . singleton ( instance ) ; } catch ( ClassNotFoundException | InstantiationException | IllegalAccessException | ClassCastException e ) { return Collections . emptySet ( ) ; } } | Loads the default implementation |
10,107 | public static java . util . Set < String > all ( ) { java . util . Set < String > set = new java . util . HashSet < String > ( ) ; set . add ( CLOUD_PLATFORM ) ; set . add ( SERVICECONTROL ) ; return java . util . Collections . unmodifiableSet ( set ) ; } | Returns an unmodifiable set that contains all scopes declared by this class . |
10,108 | public void filter ( final ClientRequestContext requestContext ) { if ( ! backend . isEmpty ( ) && backend . getConfiguration ( ) . shouldProcessContext ( OutgoingRequest ) ) { final Map < String , String > filtered = backend . getConfiguration ( ) . filterDeniedParams ( backend . copyToMap ( ) , OutgoingRequest ) ; requestContext . getHeaders ( ) . putSingle ( TraceeConstants . TPIC_HEADER , transportSerialization . render ( filtered ) ) ; } } | This method handles the outgoing request |
10,109 | public void filter ( final ClientRequestContext requestContext , final ClientResponseContext responseContext ) { final List < String > serializedHeaders = responseContext . getHeaders ( ) . get ( TraceeConstants . TPIC_HEADER ) ; if ( serializedHeaders != null && backend . getConfiguration ( ) . shouldProcessContext ( IncomingResponse ) ) { final Map < String , String > parsed = transportSerialization . parse ( serializedHeaders ) ; backend . putAll ( backend . getConfiguration ( ) . filterDeniedParams ( parsed , IncomingResponse ) ) ; } } | This method handles the incoming response |
10,110 | public static String stripTrailingSlash ( String s ) { return s == null ? null : CharMatcher . is ( '/' ) . trimTrailingFrom ( s ) ; } | Strips the trailing slash from a string if it has a trailing slash ; otherwise return the string unchanged . |
10,111 | public static Timestamp fromEpoch ( long epochMillis ) { return Timestamp . newBuilder ( ) . setNanos ( ( int ) ( ( epochMillis % MILLIS_PER_SECOND ) * NANOS_PER_MILLI ) ) . setSeconds ( epochMillis / MILLIS_PER_SECOND ) . build ( ) ; } | Obtain the current time from the unix epoch |
10,112 | public static void pushCurrentThreadValidationContext ( Supplier < String > supplier ) { Stack < Supplier < String > > stack = contextLocal . get ( ) ; if ( stack == null ) { stack = new Stack < > ( ) ; contextLocal . set ( stack ) ; } stack . push ( supplier ) ; } | Sets the validation context description . Each thread has its own description so this is thread safe . |
10,113 | public boolean report ( ReportRequest req ) { if ( cache == null ) { return false ; } Preconditions . checkArgument ( req . getServiceName ( ) . equals ( serviceName ) , "service name mismatch" ) ; if ( hasHighImportanceOperation ( req ) ) { return false ; } Map < String , Operation > bySignature = opsBySignature ( req ) ; synchronized ( cache ) { for ( Map . Entry < String , Operation > entry : bySignature . entrySet ( ) ) { String signature = entry . getKey ( ) ; OperationAggregator agg = cache . getIfPresent ( signature ) ; if ( agg == null ) { cache . put ( signature , new OperationAggregator ( entry . getValue ( ) , kinds ) ) ; } else { agg . add ( entry . getValue ( ) ) ; } } } return true ; } | Adds a report request to this instance s cache . |
10,114 | public static String getRealHttpMethod ( ServletRequest req ) { HttpServletRequest httpRequest = ( HttpServletRequest ) req ; String method = ( String ) httpRequest . getAttribute ( HTTP_METHOD_OVERRIDE_ATTRIBUTE ) ; if ( method != null ) { return method ; } return httpRequest . getMethod ( ) ; } | Get the real HTTP method for the request taking into account the X - HTTP - Method - Override header . |
10,115 | public PathTemplate parentTemplate ( ) { int i = segments . size ( ) ; Segment seg = segments . get ( -- i ) ; if ( seg . kind ( ) == SegmentKind . END_BINDING ) { while ( i > 0 && segments . get ( -- i ) . kind ( ) != SegmentKind . BINDING ) { } } if ( i == 0 ) { throw new ValidationException ( "template does not have a parent" ) ; } return new PathTemplate ( segments . subList ( 0 , i ) , urlEncoding ) ; } | Returns a template for the parent of this template . |
10,116 | public PathTemplate withoutVars ( ) { StringBuilder result = new StringBuilder ( ) ; ListIterator < Segment > iterator = segments . listIterator ( ) ; boolean start = true ; while ( iterator . hasNext ( ) ) { Segment seg = iterator . next ( ) ; switch ( seg . kind ( ) ) { case BINDING : case END_BINDING : break ; default : if ( ! start ) { result . append ( seg . separator ( ) ) ; } else { start = false ; } result . append ( seg . value ( ) ) ; } } return create ( result . toString ( ) , urlEncoding ) ; } | Returns a template where all variable bindings have been replaced by wildcards but which is equivalent regards matching to this one . |
10,117 | public String singleVar ( ) { if ( bindings . size ( ) == 1 ) { return bindings . entrySet ( ) . iterator ( ) . next ( ) . getKey ( ) ; } return null ; } | Returns the name of a singleton variable used by this template . If the template does not contain a single variable returns null . |
10,118 | public void validate ( String path , String exceptionMessagePrefix ) { if ( ! matches ( path ) ) { throw new ValidationException ( String . format ( "%s: Parameter \"%s\" must be in the form \"%s\"" , exceptionMessagePrefix , path , this . toString ( ) ) ) ; } } | Throws a ValidationException if the template doesn t match the path . The exceptionMessagePrefix parameter will be prepended to the ValidationException message . |
10,119 | public ImmutableMap < String , String > validatedMatch ( String path , String exceptionMessagePrefix ) { ImmutableMap < String , String > matchMap = match ( path ) ; if ( matchMap == null ) { throw new ValidationException ( String . format ( "%s: Parameter \"%s\" must be in the form \"%s\"" , exceptionMessagePrefix , path , this . toString ( ) ) ) ; } return matchMap ; } | Matches the path returning a map from variable names to matched values . All matched values will be properly unescaped using URL encoding rules . If the path does not match the template throws a ValidationException . The exceptionMessagePrefix parameter will be prepended to the ValidationException message . |
10,120 | public ImmutableMap < String , String > match ( String path ) { return match ( path , false ) ; } | Matches the path returning a map from variable names to matched values . All matched values will be properly unescaped using URL encoding rules . If the path does not match the template null is returned . |
10,121 | private ImmutableMap < String , String > match ( String path , boolean forceHostName ) { Segment last = segments . get ( segments . size ( ) - 1 ) ; if ( last . kind ( ) == SegmentKind . CUSTOM_VERB ) { Matcher matcher = CUSTOM_VERB_PATTERN . matcher ( path ) ; if ( ! matcher . find ( ) || ! decodeUrl ( matcher . group ( 1 ) ) . equals ( last . value ( ) ) ) { return null ; } path = path . substring ( 0 , matcher . start ( 0 ) ) ; } boolean withHostName = path . startsWith ( "//" ) ; if ( withHostName ) { path = path . substring ( 2 ) ; } List < String > input = SLASH_SPLITTER . splitToList ( path ) ; int inPos = 0 ; Map < String , String > values = Maps . newLinkedHashMap ( ) ; if ( withHostName || forceHostName ) { if ( input . isEmpty ( ) ) { return null ; } String hostName = input . get ( inPos ++ ) ; if ( withHostName ) { hostName = "//" + hostName ; } values . put ( HOSTNAME_VAR , hostName ) ; } if ( ! match ( input , inPos , segments , 0 , values ) ) { return null ; } return ImmutableMap . copyOf ( values ) ; } | Matches a path . |
10,122 | private boolean match ( List < String > input , int inPos , List < Segment > segments , int segPos , Map < String , String > values ) { String currentVar = null ; while ( segPos < segments . size ( ) ) { Segment seg = segments . get ( segPos ++ ) ; switch ( seg . kind ( ) ) { case END_BINDING : currentVar = null ; continue ; case BINDING : currentVar = seg . value ( ) ; continue ; case CUSTOM_VERB : break ; default : if ( inPos >= input . size ( ) ) { return false ; } String next = decodeUrl ( input . get ( inPos ++ ) ) ; if ( seg . kind ( ) == SegmentKind . LITERAL ) { if ( ! seg . value ( ) . equals ( next ) ) { return false ; } } if ( currentVar != null ) { String current = values . get ( currentVar ) ; if ( current == null ) { values . put ( currentVar , next ) ; } else { values . put ( currentVar , current + "/" + next ) ; } } if ( seg . kind ( ) == SegmentKind . PATH_WILDCARD ) { int segsToMatch = 0 ; for ( int i = segPos ; i < segments . size ( ) ; i ++ ) { switch ( segments . get ( i ) . kind ( ) ) { case BINDING : case END_BINDING : continue ; default : segsToMatch ++ ; } } int available = ( input . size ( ) - inPos ) - segsToMatch ; while ( available -- > 0 ) { values . put ( currentVar , values . get ( currentVar ) + "/" + decodeUrl ( input . get ( inPos ++ ) ) ) ; } } } } return inPos == input . size ( ) ; } | indicating whether the match was successful . |
10,123 | public String encode ( String ... values ) { ImmutableMap . Builder < String , String > builder = ImmutableMap . builder ( ) ; int i = 0 ; for ( String value : values ) { builder . put ( "$" + i ++ , value ) ; } return instantiate ( builder . build ( ) ) ; } | Instantiates the template from the given positional parameters . The template must not be build from named bindings but only contain wildcards . Each parameter position corresponds to a wildcard of the according position in the template . |
10,124 | public List < String > decode ( String path ) { Map < String , String > match = match ( path ) ; if ( match == null ) { throw new IllegalArgumentException ( String . format ( "template '%s' does not match '%s'" , this , path ) ) ; } List < String > result = Lists . newArrayList ( ) ; for ( Map . Entry < String , String > entry : match . entrySet ( ) ) { String key = entry . getKey ( ) ; if ( ! key . startsWith ( "$" ) ) { throw new IllegalArgumentException ( "template must not contain named bindings" ) ; } int i = Integer . parseInt ( key . substring ( 1 ) ) ; while ( result . size ( ) <= i ) { result . add ( "" ) ; } result . set ( i , entry . getValue ( ) ) ; } return ImmutableList . copyOf ( result ) ; } | Matches the template into a list of positional values . The template must not be build from named bindings but only contain wildcards . For each wildcard in the template a value is returned at corresponding position in the list . |
10,125 | private static boolean peek ( ListIterator < Segment > segments , SegmentKind ... kinds ) { int start = segments . nextIndex ( ) ; boolean success = false ; for ( SegmentKind kind : kinds ) { if ( ! segments . hasNext ( ) || segments . next ( ) . kind ( ) != kind ) { success = false ; break ; } } if ( success ) { return true ; } restore ( segments , start ) ; return false ; } | the list iterator in its state . |
10,126 | public void filter ( final ContainerRequestContext containerRequestContext ) { if ( backend . getConfiguration ( ) . shouldProcessContext ( IncomingRequest ) ) { final List < String > serializedTraceeHeaders = containerRequestContext . getHeaders ( ) . get ( TraceeConstants . TPIC_HEADER ) ; if ( serializedTraceeHeaders != null && ! serializedTraceeHeaders . isEmpty ( ) ) { final Map < String , String > parsed = transportSerialization . parse ( serializedTraceeHeaders ) ; backend . putAll ( backend . getConfiguration ( ) . filterDeniedParams ( parsed , IncomingRequest ) ) ; } } Utilities . generateInvocationIdIfNecessary ( backend ) ; } | This method handles the incoming request |
10,127 | public void filter ( final ContainerRequestContext requestContext , final ContainerResponseContext responseContext ) { if ( backend . getConfiguration ( ) . shouldProcessContext ( OutgoingResponse ) ) { final Map < String , String > filtered = backend . getConfiguration ( ) . filterDeniedParams ( backend . copyToMap ( ) , OutgoingResponse ) ; responseContext . getHeaders ( ) . putSingle ( TraceeConstants . TPIC_HEADER , transportSerialization . render ( filtered ) ) ; } backend . clear ( ) ; } | This method handles the outgoing response |
10,128 | public Map < String , String > parseSoapHeader ( final Element soapHeader ) { final NodeList tpicHeaders = soapHeader . getElementsByTagNameNS ( TraceeConstants . SOAP_HEADER_NAMESPACE , TraceeConstants . TPIC_HEADER ) ; final HashMap < String , String > contextMap = new HashMap < > ( ) ; if ( tpicHeaders != null && tpicHeaders . getLength ( ) > 0 ) { final int items = tpicHeaders . getLength ( ) ; for ( int i = 0 ; i < items ; i ++ ) { contextMap . putAll ( parseTpicHeader ( ( Element ) tpicHeaders . item ( i ) ) ) ; } } return contextMap ; } | Retrieves the first TPIC header element out of the soap header and parse it |
10,129 | public void renderSoapHeader ( final Map < String , String > context , final SOAPHeader soapHeader ) { renderSoapHeader ( SOAP_HEADER_MARSHALLER , context , soapHeader ) ; } | Renders a given context map into a given soapHeader . |
10,130 | protected Client createClient ( String configServiceName ) throws GeneralSecurityException , IOException { return new Client . Builder ( configServiceName ) . setStatsLogFrequency ( statsLogFrequency ( ) ) . setHttpTransport ( new NetHttpTransport ( ) ) . build ( ) ; } | A template method for constructing clients . |
10,131 | private static String constructOpenIdUrl ( String issuer ) { String url = issuer ; if ( ! URI . create ( issuer ) . isAbsolute ( ) ) { url = HTTPS_PROTOCOL_PREFIX + issuer ; } if ( ! url . endsWith ( "/" ) ) { url += "/" ; } return url + OPEN_ID_CONFIG_PATH ; } | Construct the OpenID discovery URL based on the issuer . |
10,132 | protected void writeTraceeContextToMessage ( Message message ) throws JMSException { if ( ! backend . isEmpty ( ) && backend . getConfiguration ( ) . shouldProcessContext ( AsyncDispatch ) ) { final Map < String , String > filteredContext = backend . getConfiguration ( ) . filterDeniedParams ( backend . copyToMap ( ) , AsyncDispatch ) ; final String contextAsString = httpHeaderSerialization . render ( filteredContext ) ; message . setStringProperty ( TraceeConstants . TPIC_HEADER , contextAsString ) ; } } | Writes the current TraceeContext to the given javaee message . This method is idempotent . |
10,133 | public UserInfo authenticate ( HttpServletRequest httpServletRequest , AuthInfo authInfo , String serviceName ) { Preconditions . checkNotNull ( httpServletRequest ) ; Preconditions . checkNotNull ( authInfo ) ; Optional < String > maybeAuthToken = extractAuthToken ( httpServletRequest ) ; if ( ! maybeAuthToken . isPresent ( ) ) { throw new UnauthenticatedException ( "No auth token is contained in the HTTP request" ) ; } JwtClaims jwtClaims = this . authTokenDecoder . decode ( maybeAuthToken . get ( ) ) ; UserInfo userInfo = toUserInfo ( jwtClaims ) ; String issuer = userInfo . getIssuer ( ) ; if ( ! this . issuersToProviderIds . containsKey ( issuer ) ) { throw new UnauthenticatedException ( "Unknown issuer: " + issuer ) ; } String providerId = this . issuersToProviderIds . get ( issuer ) ; if ( ! authInfo . isProviderIdAllowed ( providerId ) ) { String message = "The requested method does not allowed this provider id: " + providerId ; throw new UnauthenticatedException ( message ) ; } checkJwtClaims ( jwtClaims ) ; Set < String > audiences = userInfo . getAudiences ( ) ; boolean hasServiceName = audiences . contains ( serviceName ) ; Set < String > allowedAudiences = authInfo . getAudiencesForProvider ( providerId ) ; if ( ! hasServiceName && Sets . intersection ( audiences , allowedAudiences ) . isEmpty ( ) ) { throw new UnauthenticatedException ( "Audiences not allowed" ) ; } return userInfo ; } | Authenticate the current HTTP request . |
10,134 | private void checkJwtClaims ( JwtClaims jwtClaims ) { Optional < NumericDate > expiration = getDateClaim ( ReservedClaimNames . EXPIRATION_TIME , jwtClaims ) ; if ( ! expiration . isPresent ( ) ) { throw new UnauthenticatedException ( "Missing expiration field" ) ; } Optional < NumericDate > notBefore = getDateClaim ( ReservedClaimNames . NOT_BEFORE , jwtClaims ) ; NumericDate currentTime = NumericDate . fromMilliseconds ( clock . currentTimeMillis ( ) ) ; if ( expiration . get ( ) . isBefore ( currentTime ) ) { throw new UnauthenticatedException ( "The auth token has already expired" ) ; } if ( notBefore . isPresent ( ) && notBefore . get ( ) . isAfter ( currentTime ) ) { String message = "Current time is earlier than the \"nbf\" time" ; throw new UnauthenticatedException ( message ) ; } } | Check whether the JWT claims should be accepted . |
10,135 | public static String getCurrentContextClassLoaderClassPath ( ) { URLClassLoader contextClassLoader = ( URLClassLoader ) Thread . currentThread ( ) . getContextClassLoader ( ) ; return getUrlClassLoaderClassPath ( contextClassLoader ) ; } | Assumes that the context class loader of the current thread is a URLClassLoader and will throw a runtime exception if it is not . |
10,136 | public static LambdaFactory get ( LambdaFactoryConfiguration configuration ) { JavaCompiler compiler = Optional . ofNullable ( configuration . getJavaCompiler ( ) ) . orElseThrow ( JavaCompilerNotFoundException :: new ) ; return new LambdaFactory ( configuration . getDefaultHelperClassSourceProvider ( ) , configuration . getClassFactory ( ) , compiler , configuration . getImports ( ) , configuration . getStaticImports ( ) , configuration . getCompilationClassPath ( ) , configuration . getParentClassLoader ( ) ) ; } | Returns a LambdaFactory instance with the given configuration . |
10,137 | public < T > T createLambda ( String code , TypeReference < T > typeReference ) throws LambdaCreationException { String helperClassSource = helperProvider . getHelperClassSource ( typeReference . toString ( ) , code , imports , staticImports ) ; try { Class < ? > helperClass = classFactory . createClass ( helperProvider . getHelperClassName ( ) , helperClassSource , javaCompiler , createOptionsForCompilationClasspath ( compilationClassPath ) , parentClassLoader ) ; Method lambdaReturningMethod = helperClass . getMethod ( helperProvider . getLambdaReturningMethodName ( ) ) ; @ SuppressWarnings ( "unchecked" ) T lambda = ( T ) lambdaReturningMethod . invoke ( null ) ; return lambda ; } catch ( ReflectiveOperationException | RuntimeException | NoClassDefFoundError e ) { throw new LambdaCreationException ( e ) ; } catch ( ClassCompilationException classCompilationException ) { throw new LambdaCreationException ( classCompilationException ) ; } } | Creates lambda from the given code . |
10,138 | public Long zadd ( final String key , final ZsetPair scoremember , final ZsetPair ... scoresmembers ) throws WrongTypeException { if ( scoremember == null ) { return null ; } Map < String , Double > sms = new HashMap < String , Double > ( ) ; sms . put ( scoremember . member , scoremember . score ) ; for ( ZsetPair pair : scoresmembers ) { if ( pair == null ) { continue ; } sms . put ( pair . member , pair . score ) ; } Object ret = command ( "zadd" , key , sms ) ; if ( ret instanceof WrongTypeException ) { throw ( WrongTypeException ) ret ; } return ( Long ) ret ; } | multi & watch are both abstract . |
10,139 | public Set < Instance > runOnceOn ( InetAddress localhost ) throws IOException { logger . debug ( "Running query on {}" , localhost ) ; initialQuestion = new Question ( service , domain ) ; instances = Collections . synchronizedSet ( new HashSet < > ( ) ) ; try { Thread listener = null ; if ( localhost != TEST_SUITE_ADDRESS ) { openSocket ( localhost ) ; listener = listenForResponses ( ) ; while ( ! isServerIsListening ( ) ) { logger . debug ( "Server is not yet listening" ) ; } } ask ( initialQuestion ) ; if ( listener != null ) { try { listener . join ( ) ; } catch ( InterruptedException e ) { logger . error ( "InterruptedException while listening for mDNS responses: " , e ) ; } } } finally { closeSocket ( ) ; } return instances ; } | Synchronously runs the Query a single time . |
10,140 | private void fetchMissingRecords ( ) throws IOException { logger . debug ( "Records includes:" ) ; records . forEach ( r -> logger . debug ( "{}" , r ) ) ; for ( PtrRecord ptr : records . stream ( ) . filter ( r -> r instanceof PtrRecord ) . map ( r -> ( PtrRecord ) r ) . collect ( Collectors . toList ( ) ) ) { fetchMissingSrvRecordsFor ( ptr ) ; fetchMissingTxtRecordsFor ( ptr ) ; } for ( SrvRecord srv : records . stream ( ) . filter ( r -> r instanceof SrvRecord ) . map ( r -> ( SrvRecord ) r ) . collect ( Collectors . toList ( ) ) ) { fetchMissingAddressRecordsFor ( srv ) ; } } | Verify that each PTR record has corresponding SRV TXT and either A or AAAA records . Request any that are missing . |
10,141 | public boolean matches ( String path , MatchingStrategy matchingStrategy ) { return path != null && matchingStrategy . matches ( clause , path ) ; } | Checks if path matches access path |
10,142 | public void addGroup ( Group section ) { if ( section != null ) { if ( section . isAnyAgent ( ) ) { if ( this . defaultSection == null ) { this . defaultSection = section ; } else { this . defaultSection . getAccessList ( ) . importAccess ( section . getAccessList ( ) ) ; } } else { Group exact = findExactSection ( section ) ; if ( exact == null ) { groups . add ( section ) ; } else { exact . getAccessList ( ) . importAccess ( section . getAccessList ( ) ) ; } } } } | Adds section . |
10,143 | private Group findExactSection ( Group section ) { for ( Group s : groups ) { if ( s . isExact ( section ) ) { return s ; } } return null ; } | Finds exact section . |
10,144 | public RobotsTxt readRobotsTxt ( InputStream inputStream ) throws IOException { BufferedReader reader = new BufferedReader ( new InputStreamReader ( inputStream , "UTF-8" ) ) ; Group currentGroup = null ; boolean startGroup = false ; RobotsTxtImpl robots = new RobotsTxtImpl ( matchingStrategy , winningStrategy ) ; for ( Entry entry = readEntry ( reader ) ; entry != null ; entry = readEntry ( reader ) ) { switch ( entry . getKey ( ) . toUpperCase ( ) ) { case "USER-AGENT" : if ( ! startGroup && currentGroup != null ) { robots . addGroup ( currentGroup ) ; currentGroup = null ; } if ( currentGroup == null ) { currentGroup = new Group ( ) ; } currentGroup . addUserAgent ( entry . getValue ( ) ) ; startGroup = true ; break ; case "DISALLOW" : if ( currentGroup != null ) { boolean access = entry . getValue ( ) . isEmpty ( ) ; currentGroup . addAccess ( new Access ( currentGroup , entry . getSource ( ) , entry . getValue ( ) , access ) ) ; startGroup = false ; } break ; case "ALLOW" : if ( currentGroup != null ) { boolean access = ! entry . getValue ( ) . isEmpty ( ) ; currentGroup . addAccess ( new Access ( currentGroup , entry . getSource ( ) , entry . getValue ( ) , access ) ) ; startGroup = false ; } break ; case "CRAWL-DELAY" : if ( currentGroup != null ) { try { int crawlDelay = Integer . parseInt ( entry . getValue ( ) ) ; currentGroup . setCrawlDelay ( crawlDelay ) ; startGroup = false ; } catch ( NumberFormatException ex ) { } } else { } break ; case "HOST" : robots . setHost ( entry . getValue ( ) ) ; startGroup = false ; break ; case "SITEMAP" : robots . getSitemaps ( ) . add ( entry . getValue ( ) ) ; startGroup = false ; break ; default : startGroup = false ; break ; } } if ( currentGroup != null ) { robots . addGroup ( currentGroup ) ; } return robots ; } | Reads robots txt . |
10,145 | private Entry readEntry ( BufferedReader reader ) throws IOException { for ( String line = reader . readLine ( ) ; line != null ; line = reader . readLine ( ) ) { Entry entry = parseEntry ( line ) ; if ( entry != null ) { return entry ; } } return null ; } | Reads next entry from the reader . |
10,146 | public boolean isExact ( Group group ) { if ( isAnyAgent ( ) && group . isAnyAgent ( ) ) return true ; if ( ( isAnyAgent ( ) && ! group . isAnyAgent ( ) || ( ! isAnyAgent ( ) && group . isAnyAgent ( ) ) ) ) return false ; return group . userAgents . stream ( ) . anyMatch ( sectionUserAgent -> userAgents . stream ( ) . anyMatch ( userAgent -> userAgent . equalsIgnoreCase ( sectionUserAgent ) ) ) ; } | Checks if group is exact in terms of user agents . |
10,147 | public void addUserAgent ( String userAgent ) { if ( userAgent . equals ( "*" ) ) { anyAgent = true ; } else { this . userAgents . add ( userAgent ) ; } } | Adds user agent . |
10,148 | public boolean matchUserAgent ( String userAgent ) { if ( anyAgent ) return true ; if ( ! anyAgent && userAgent == null ) return false ; return userAgents . stream ( ) . anyMatch ( agent -> agent . equalsIgnoreCase ( userAgent ) ) ; } | Checks if the section is applicable for a given user agent . |
10,149 | public static Path getNextPath ( String prefix ) { Path path ; do { path = Paths . get ( String . format ( "%s%s" , prefix , Integer . toString ( nextDumpPathSuffix ) ) ) ; nextDumpPathSuffix ++ ; } while ( Files . exists ( path ) ) ; return path ; } | Get the next sequential Path for a binary dump file ensuring we don t overwrite any existing files . |
10,150 | public static void printBuffer ( byte [ ] buffer , String msg ) { StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 ; i < buffer . length ; i ++ ) { if ( i % 20 == 0 ) { sb . append ( "\n\t" ) ; } sb . append ( String . format ( "%02x" , buffer [ i ] ) ) ; } logger . info ( "{}: {}" , msg , sb . toString ( ) ) ; } | Print a formatted version of |
10,151 | public < T > T getHeader ( String name , Class < T > type ) { return ( T ) headers . get ( name ) ; } | Get a header value casting to expected type . |
10,152 | public static long readVariableValueLength ( final byte [ ] array , final int offset , final boolean reverse ) { long len = 0 ; byte v ; long p = 0 ; int i = offset ; do { v = array [ i ] ; len += ( ( long ) ( v & ( byte ) 0x7f ) ) << p ; p += 7 ; if ( reverse ) { -- i ; } else { ++ i ; } } while ( ( v & ( byte ) 0x80 ) != 0 ) ; return len ; } | read a variable length integer in unsigned LEB128 format |
10,153 | protected VPackSlice translateUnchecked ( ) { final VPackSlice result = attributeTranslator . translate ( getAsInt ( ) ) ; return result != null ? result : new VPackSlice ( ) ; } | translates an integer key into a string without checks |
10,154 | public void prepare ( Map stormConf , TopologyContext context , OutputCollector collector ) { if ( this . jmsProvider == null || this . producer == null ) { throw new IllegalStateException ( "JMS Provider and MessageProducer not set." ) ; } this . collector = collector ; LOG . debug ( "Connecting JMS.." ) ; try { ConnectionFactory cf = this . jmsProvider . connectionFactory ( ) ; Destination dest = this . jmsProvider . destination ( ) ; this . connection = cf . createConnection ( ) ; this . session = connection . createSession ( this . jmsTransactional , this . jmsAcknowledgeMode ) ; this . messageProducer = session . createProducer ( dest ) ; connection . start ( ) ; } catch ( Exception e ) { LOG . warn ( "Error creating JMS connection." , e ) ; } } | Initializes JMS resources . |
10,155 | public static < E > E decorateElement ( Class < E > clazz , WebElement webElement ) { WiseDecorator decorator = new WiseDecorator ( new DefaultElementLocatorFactory ( webElement ) ) ; return decorator . decorate ( clazz , webElement ) ; } | Decorates a webElement . |
10,156 | public static < E > List < E > decorateElements ( Class < E > clazz , List < WebElement > webElements ) { List < E > elements = Lists . newArrayList ( ) ; for ( WebElement webElement : webElements ) { E element = decorateElement ( clazz , webElement ) ; if ( element != null ) elements . add ( element ) ; } return elements ; } | Decorates a list of webElements . |
10,157 | void addCallbacks ( Consumer < ? super T > successCallback , Consumer < Throwable > failureCallback , Executor executor ) { Objects . requireNonNull ( successCallback , "'successCallback' must not be null" ) ; Objects . requireNonNull ( failureCallback , "'failureCallback' must not be null" ) ; Objects . requireNonNull ( executor , "'executor' must not be null" ) ; synchronized ( mutex ) { state = state . addCallbacks ( successCallback , failureCallback , executor ) ; } } | Adds the given callbacks to this registry . |
10,158 | boolean success ( T result ) { State < T > oldState ; synchronized ( mutex ) { if ( state . isCompleted ( ) ) { return false ; } oldState = state ; state = state . getSuccessState ( result ) ; } oldState . callSuccessCallbacks ( result ) ; return true ; } | To be called to set the result value . |
10,159 | boolean failure ( Throwable failure ) { State < T > oldState ; synchronized ( mutex ) { if ( state . isCompleted ( ) ) { return false ; } oldState = state ; state = state . getFailureState ( failure ) ; } oldState . callFailureCallbacks ( failure ) ; return true ; } | To be called to set the failure exception |
10,160 | public < E > E initNextPage ( Class < E > clazz ) { return WisePageFactory . initElements ( this . driver , clazz ) ; } | Instantiates the next page of the user navigation and initialize its elements . |
10,161 | private static < T > void acceptResult ( CompletableCompletionStage < T > s , Supplier < ? extends T > supplier ) { try { s . complete ( supplier . get ( ) ) ; } catch ( Throwable e ) { handleFailure ( s , e ) ; } } | Accepts result provided by the Supplier . If an exception is thrown by the supplier completes exceptionally . |
10,162 | private static < T > BiConsumer < T , Throwable > completeHandler ( CompletableCompletionStage < T > s ) { return ( result , failure ) -> { if ( failure == null ) { s . complete ( result ) ; } else { handleFailure ( s , failure ) ; } } ; } | Handler that can be used in whenComplete method . |
10,163 | public final < T > CompletionStage < T > completedStage ( T value ) { CompletableCompletionStage < T > result = createCompletionStage ( ) ; result . complete ( value ) ; return result ; } | Returns a new CompletionStage that is already completed with the given value . |
10,164 | public final < U > CompletionStage < U > supplyAsync ( Supplier < U > supplier ) { return supplyAsync ( supplier , defaultAsyncExecutor ) ; } | Returns a new CompletionStage that is asynchronously completed by a task running in the defaultAsyncExecutor with the value obtained by calling the given Supplier . |
10,165 | public final < U > CompletionStage < U > supplyAsync ( Supplier < U > supplier , Executor executor ) { Objects . requireNonNull ( supplier , "supplier must not be null" ) ; return completedStage ( null ) . thenApplyAsync ( ( ignored ) -> supplier . get ( ) , executor ) ; } | Returns a new CompletionStage that is asynchronously completed by a task running in the given executor with the value obtained by calling the given Supplier . Subsequent completion stages will use defaultAsyncExecutor as their default executor . |
10,166 | public final CompletionStage < Void > runAsync ( Runnable runnable , Executor executor ) { Objects . requireNonNull ( runnable , "runnable must not be null" ) ; return completedStage ( null ) . thenRunAsync ( runnable , executor ) ; } | Returns a new CompletionStage that is asynchronously completed by a task running in the given executor after it runs the given action . Subsequent completion stages will use defaultAsyncExecutor as their default executor . |
10,167 | public static < E > void rootElement ( WebElement root , E element ) { if ( element == null || root == null ) return ; if ( element instanceof WebElement ) return ; for ( Class < ? > clazz = element . getClass ( ) ; ! clazz . equals ( Object . class ) ; clazz = clazz . getSuperclass ( ) ) { if ( Enhancer . isEnhanced ( clazz ) ) continue ; Field [ ] fields = clazz . getDeclaredFields ( ) ; for ( Field field : fields ) { setRootElementField ( root , element , field ) ; } } } | Injects the root webelement into an element . |
10,168 | public static < E > void rootDriver ( WebDriver root , E page ) { if ( page == null || root == null ) return ; for ( Class < ? > clazz = page . getClass ( ) ; ! clazz . equals ( Object . class ) ; clazz = clazz . getSuperclass ( ) ) { if ( Enhancer . isEnhanced ( clazz ) ) continue ; Field [ ] fields = clazz . getDeclaredFields ( ) ; for ( Field field : fields ) { setRootDriverField ( root , page , field ) ; } } } | Injects the webdriver into a page . |
10,169 | public static WebDriver getDriver ( ) { WebDriver driver = WEB_DRIVER_THREAD_LOCAL . get ( ) ; if ( driver == null ) throw new IllegalStateException ( "Driver not set on the WiseContext" ) ; return driver ; } | Retrieves the WebDriver of the current thread . |
10,170 | public static < A extends Annotation > boolean isAnnotationPresent ( Class < ? > clazz , Class < A > annotationType ) { if ( findAnnotation ( clazz , annotationType ) != null ) return true ; return false ; } | Verifies if an annotation is present at a class type hierarchy . |
10,171 | public static < T > T initElements ( SearchContext searchContext , T instance ) { Class < ? > currentInstanceHierarchyClass = instance . getClass ( ) ; while ( currentInstanceHierarchyClass != Object . class ) { proxyElements ( searchContext , instance , currentInstanceHierarchyClass ) ; currentInstanceHierarchyClass = currentInstanceHierarchyClass . getSuperclass ( ) ; } return instance ; } | Initializes the elements of an existing object . |
10,172 | public SearchResults search ( OmdbParameters searchParams ) throws OMDBException { SearchResults resultList ; if ( ! searchParams . has ( Param . APIKEY ) ) { searchParams . add ( Param . APIKEY , this . apiKey ) ; } String url = OmdbUrlBuilder . create ( searchParams ) ; LOG . trace ( "URL: {}" , url ) ; String jsonData = requestWebPage ( OmdbUrlBuilder . generateUrl ( url ) ) ; try { resultList = mapper . readValue ( jsonData , SearchResults . class ) ; } catch ( IOException ex ) { throw new OMDBException ( ApiExceptionType . MAPPING_FAILED , jsonData , 0 , url , ex ) ; } return resultList ; } | Execute a search using the passed parameters . |
10,173 | public SearchResults search ( String title ) throws OMDBException { return search ( new OmdbBuilder ( ) . setApiKey ( apiKey ) . setSearchTerm ( title ) . build ( ) ) ; } | Get a list of movies using the movie title . |
10,174 | public OmdbVideoFull getInfo ( OmdbParameters parameters ) throws OMDBException { OmdbVideoFull result ; if ( ! parameters . has ( Param . APIKEY ) ) { parameters . add ( Param . APIKEY , this . apiKey ) ; } URL url = OmdbUrlBuilder . createUrl ( parameters ) ; String jsonData = requestWebPage ( url ) ; try { result = mapper . readValue ( jsonData , OmdbVideoFull . class ) ; if ( result == null || ! result . isResponse ( ) ) { throw new OMDBException ( ApiExceptionType . ID_NOT_FOUND , result == null ? "No data returned" : result . getError ( ) ) ; } } catch ( IOException ex ) { throw new OMDBException ( ApiExceptionType . MAPPING_FAILED , jsonData , 0 , url , ex ) ; } return result ; } | Get movie information using the supplied parameters |
10,175 | protected void handleUnknown ( String key , Object value ) { StringBuilder unknown = new StringBuilder ( this . getClass ( ) . getSimpleName ( ) ) ; unknown . append ( ": Unknown property='" ) . append ( key ) ; unknown . append ( "' value='" ) . append ( value ) . append ( "'" ) ; LOG . trace ( unknown . toString ( ) ) ; } | Handle unknown properties and print a message |
10,176 | public static String create ( final OmdbParameters params ) throws OMDBException { StringBuilder sb = new StringBuilder ( BASE_URL ) ; sb . append ( DELIMITER_FIRST ) ; if ( params . has ( Param . APIKEY ) ) { String apikey = ( String ) params . get ( Param . APIKEY ) ; sb . append ( Param . APIKEY . getValue ( ) ) . append ( apikey ) ; } else { throw new OMDBException ( ApiExceptionType . AUTH_FAILURE , "Must include an ApiKey to make a call" ) ; } sb . append ( DELIMITER_SUBSEQUENT ) ; if ( params . has ( Param . SEARCH ) ) { String search = ( String ) params . get ( Param . SEARCH ) ; sb . append ( Param . SEARCH . getValue ( ) ) . append ( search . replace ( " " , "+" ) ) ; } else if ( params . has ( Param . IMDB ) ) { sb . append ( Param . IMDB . getValue ( ) ) . append ( params . get ( Param . IMDB ) ) ; } else if ( params . has ( Param . TITLE ) ) { String title = ( String ) params . get ( Param . TITLE ) ; sb . append ( Param . TITLE . getValue ( ) ) . append ( title . replace ( " " , "+" ) ) ; } else { throw new OMDBException ( ApiExceptionType . INVALID_URL , "Must include a search or ID" ) ; } appendParam ( params , Param . YEAR , sb ) ; if ( params . has ( Param . PLOT ) && ( PlotType ) params . get ( Param . PLOT ) != PlotType . getDefault ( ) ) { appendParam ( params , Param . PLOT , sb ) ; } appendParam ( params , Param . TOMATOES , sb ) ; appendParam ( params , Param . RESULT , sb ) ; appendParam ( params , Param . DATA , sb ) ; appendParam ( params , Param . VERSION , sb ) ; appendParam ( params , Param . CALLBACK , sb ) ; LOG . trace ( "Created URL: {}" , sb . toString ( ) ) ; return sb . toString ( ) ; } | Create the String representation of the URL for passed parameters |
10,177 | private static void appendParam ( final OmdbParameters params , final Param key , StringBuilder sb ) { if ( params . has ( key ) ) { sb . append ( DELIMITER_SUBSEQUENT ) . append ( key . getValue ( ) ) . append ( params . get ( key ) ) ; } } | Append a parameter and value to the URL line |
10,178 | public static URL generateUrl ( final String url ) throws OMDBException { try { return new URL ( url ) ; } catch ( MalformedURLException ex ) { throw new OMDBException ( ApiExceptionType . INVALID_URL , "Failed to create URL" , url , ex ) ; } } | Generate a URL object from a String URL |
10,179 | public OmdbBuilder setSearchTerm ( final String searchTerm ) throws OMDBException { if ( StringUtils . isBlank ( searchTerm ) ) { throw new OMDBException ( ApiExceptionType . UNKNOWN_CAUSE , "Must provide a search term!" ) ; } params . add ( Param . SEARCH , searchTerm ) ; return this ; } | Set the search term |
10,180 | public OmdbBuilder setImdbId ( final String imdbId ) throws OMDBException { if ( StringUtils . isBlank ( imdbId ) ) { throw new OMDBException ( ApiExceptionType . UNKNOWN_CAUSE , "Must provide an IMDB ID!" ) ; } params . add ( Param . IMDB , imdbId ) ; return this ; } | A valid IMDb ID |
10,181 | public OmdbBuilder setTitle ( final String title ) throws OMDBException { if ( StringUtils . isBlank ( title ) ) { throw new OMDBException ( ApiExceptionType . UNKNOWN_CAUSE , "Must provide a title!" ) ; } params . add ( Param . TITLE , title ) ; return this ; } | The title to search for |
10,182 | public OmdbBuilder setTypeMovie ( ) { if ( ! ResultType . isDefault ( ResultType . MOVIE ) ) { params . add ( Param . RESULT , ResultType . MOVIE ) ; } return this ; } | Limit the results to movies |
10,183 | public OmdbBuilder setTypeSeries ( ) { if ( ! ResultType . isDefault ( ResultType . SERIES ) ) { params . add ( Param . RESULT , ResultType . SERIES ) ; } return this ; } | Limit the results to series |
10,184 | public OmdbBuilder setTypeEpisode ( ) { if ( ! ResultType . isDefault ( ResultType . EPISODE ) ) { params . add ( Param . RESULT , ResultType . EPISODE ) ; } return this ; } | Limit the results to episodes |
10,185 | public OmdbBuilder setPlot ( final PlotType plotType ) { if ( ! PlotType . isDefault ( plotType ) ) { params . add ( Param . PLOT , plotType ) ; } return this ; } | Return short or full plot . |
10,186 | public OmdbBuilder setPlotFull ( ) { if ( ! PlotType . isDefault ( PlotType . FULL ) ) { params . add ( Param . PLOT , PlotType . FULL ) ; } return this ; } | Return the long plot |
10,187 | public OmdbBuilder setPlotShort ( ) { if ( ! PlotType . isDefault ( PlotType . SHORT ) ) { params . add ( Param . PLOT , PlotType . SHORT ) ; } return this ; } | Return the short plot |
10,188 | public OmdbBuilder setTomatoes ( boolean tomatoes ) { if ( DEFAULT_TOMATOES != tomatoes ) { params . add ( Param . TOMATOES , tomatoes ) ; } return this ; } | Include or exclude Rotten Tomatoes ratings . |
10,189 | public OmdbBuilder setApiKey ( final String apiKey ) throws OMDBException { if ( StringUtils . isBlank ( apiKey ) ) { throw new OMDBException ( ApiExceptionType . AUTH_FAILURE , "Must provide an ApiKey" ) ; } params . add ( Param . APIKEY , apiKey ) ; return this ; } | Set the ApiKey |
10,190 | public void add ( Param key , Object value ) { if ( defaults . containsKey ( key ) && defaults . get ( key ) . equals ( value ) ) { return ; } parameters . put ( key , value ) ; } | Add a parameter to the collection |
10,191 | public void setDateTypeFace ( String fontName ) { mDateTypeFace = Typeface . createFromAsset ( mContext . getAssets ( ) , "fonts/" + fontName ) ; mDateTypeFaceSet = true ; } | Apply the specified TypeFace to the date font OPTIONAL |
10,192 | public void setMonthTypeFace ( String fontName ) { mMonthTypeFace = Typeface . createFromAsset ( mContext . getAssets ( ) , "fonts/" + fontName ) ; mMonthTypeFaceSet = true ; } | Apply the specified TypeFace to the month font OPTIONAL |
10,193 | public static int getDefaultSize ( final int size , final int measureSpec ) { final int result ; final int specMode = MeasureSpec . getMode ( measureSpec ) ; final int specSize = MeasureSpec . getSize ( measureSpec ) ; switch ( specMode ) { case MeasureSpec . AT_MOST : result = Math . min ( size , specSize ) ; break ; case MeasureSpec . EXACTLY : result = specSize ; break ; default : result = size ; break ; } return result ; } | Utility to return a default size . Uses the supplied size if the MeasureSpec imposed no constraints . Will get larger if allowed by the MeasureSpec . |
10,194 | public void setAdapter ( final BaseCircularViewAdapter adapter ) { mAdapter = adapter ; if ( mAdapter != null ) { mAdapter . registerDataSetObserver ( mAdapterDataSetObserver ) ; } postInvalidate ( ) ; } | Set the adapter to use on this view . |
10,195 | public double distanceFromCenter ( final float x , final float y ) { return Math . sqrt ( Math . pow ( x - this . x , 2 ) + Math . pow ( y - this . y , 2 ) ) ; } | Get the distance from the given point to the center of this object . |
10,196 | public void updateDrawableState ( int state , boolean flag ) { final int oldState = mCombinedState ; if ( flag ) mCombinedState |= state ; else mCombinedState &= ~ state ; if ( oldState != mCombinedState ) { setState ( VIEW_STATE_SETS [ mCombinedState ] ) ; } } | Either remove or add a state to the combined state . |
10,197 | public void setVisibility ( int visibility ) { if ( this . visibility != visibility ) { final boolean hasSpace = this . visibility == View . VISIBLE || this . visibility == View . INVISIBLE ; final boolean removingSpace = visibility == View . GONE ; final boolean change = hasSpace && removingSpace ; this . visibility = visibility ; if ( change && mAdapterDataSetObserver != null ) { mAdapterDataSetObserver . onChanged ( ) ; } else { invalidate ( ) ; } } } | Set the enabled state of this view . |
10,198 | public int onTouchEvent ( final MotionEvent event ) { int status = - 2 ; if ( visibility != View . GONE ) { final int action = event . getAction ( ) ; final boolean isEventInCenterCircle = isInCenterCircle ( event . getX ( ) , event . getY ( ) ) ; if ( action == MotionEvent . ACTION_DOWN ) { if ( isEventInCenterCircle ) { updateDrawableState ( VIEW_STATE_PRESSED , true ) ; status = MotionEvent . ACTION_DOWN ; } } else if ( action == MotionEvent . ACTION_UP ) { final boolean isPressed = ( mCombinedState & VIEW_STATE_PRESSED ) != 0 ; if ( isPressed && isEventInCenterCircle ) { updateDrawableState ( VIEW_STATE_PRESSED , false ) ; status = MotionEvent . ACTION_UP ; } } else if ( action == MotionEvent . ACTION_MOVE ) { if ( ! isEventInCenterCircle ) { updateDrawableState ( VIEW_STATE_PRESSED , false ) ; } } } return status ; } | Act on a touch event . Returns a status based on what action was taken . |
10,199 | public Date getExpirationDateAsDate ( ) { if ( hasExpirationDate ( ) ) { final LocalDateTime endOfMonth = expirationDate . atEndOfMonth ( ) . atStartOfDay ( ) . plus ( 1 , ChronoUnit . DAYS ) . minus ( 1 , ChronoUnit . NANOS ) ; final Instant instant = endOfMonth . atZone ( ZoneId . systemDefault ( ) ) . toInstant ( ) ; final Date date = new Date ( instant . toEpochMilli ( ) ) ; return date ; } else { return null ; } } | Gets the card expiration date as a java . util . Date object . Returns null if no date is available . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.