idx int64 0 41.2k | question stringlengths 74 4.04k | target stringlengths 7 750 |
|---|---|---|
26,200 | String expandIri ( String value , boolean relative , boolean vocab , Map < String , Object > context , Map < String , Boolean > defined ) throws JsonLdError { if ( value == null || JsonLdUtils . isKeyword ( value ) ) { return value ; } if ( context != null && context . containsKey ( value ) && ! Boolean . TRUE . equals ( defined . get ( value ) ) ) { this . createTermDefinition ( context , value , defined ) ; } if ( vocab && this . termDefinitions . containsKey ( value ) ) { final Map < String , Object > td = ( Map < String , Object > ) this . termDefinitions . get ( value ) ; if ( td != null ) { return ( String ) td . get ( JsonLdConsts . ID ) ; } else { return null ; } } final int colIndex = value . indexOf ( ":" ) ; if ( colIndex >= 0 ) { final String prefix = value . substring ( 0 , colIndex ) ; final String suffix = value . substring ( colIndex + 1 ) ; if ( "_" . equals ( prefix ) || suffix . startsWith ( "//" ) ) { return value ; } if ( context != null && context . containsKey ( prefix ) && ( ! defined . containsKey ( prefix ) || defined . get ( prefix ) == false ) ) { this . createTermDefinition ( context , prefix , defined ) ; } if ( this . termDefinitions . containsKey ( prefix ) ) { return ( String ) ( ( Map < String , Object > ) this . termDefinitions . get ( prefix ) ) . get ( JsonLdConsts . ID ) + suffix ; } return value ; } if ( vocab && this . containsKey ( JsonLdConsts . VOCAB ) ) { return this . get ( JsonLdConsts . VOCAB ) + value ; } else if ( relative ) { return JsonLdUrl . resolve ( ( String ) this . get ( JsonLdConsts . BASE ) , value ) ; } else if ( context != null && JsonLdUtils . isRelativeIri ( value ) ) { throw new JsonLdError ( Error . INVALID_IRI_MAPPING , "not an absolute IRI: " + value ) ; } return value ; } | IRI Expansion Algorithm |
26,201 | public String getContainer ( String property ) { if ( property == null ) { return null ; } if ( JsonLdConsts . GRAPH . equals ( property ) ) { return JsonLdConsts . SET ; } if ( ! property . equals ( JsonLdConsts . TYPE ) && JsonLdUtils . isKeyword ( property ) ) { return property ; } final Map < String , Object > td = ( Map < String , Object > ) termDefinitions . get ( property ) ; if ( td == null ) { return null ; } return ( String ) td . get ( JsonLdConsts . CONTAINER ) ; } | Retrieve container mapping . |
26,202 | private static String hashQuads ( String id , Map < String , Object > bnodes , UniqueNamer namer ) { if ( ( ( Map < String , Object > ) bnodes . get ( id ) ) . containsKey ( "hash" ) ) { return ( String ) ( ( Map < String , Object > ) bnodes . get ( id ) ) . get ( "hash" ) ; } final List < Map < String , Object > > quads = ( List < Map < String , Object > > ) ( ( Map < String , Object > ) bnodes . get ( id ) ) . get ( "quads" ) ; final List < String > nquads = new ArrayList < String > ( ) ; for ( int i = 0 ; i < quads . size ( ) ; ++ i ) { nquads . add ( toNQuad ( ( RDFDataset . Quad ) quads . get ( i ) , quads . get ( i ) . get ( "name" ) != null ? ( String ) ( ( Map < String , Object > ) quads . get ( i ) . get ( "name" ) ) . get ( "value" ) : null , id ) ) ; } Collections . sort ( nquads ) ; final String hash = sha1hash ( nquads ) ; ( ( Map < String , Object > ) bnodes . get ( id ) ) . put ( "hash" , hash ) ; return hash ; } | Hashes all of the quads about a blank node . |
26,203 | private static String sha1hash ( Collection < String > nquads ) { try { final MessageDigest md = MessageDigest . getInstance ( "SHA-1" ) ; for ( final String nquad : nquads ) { md . update ( nquad . getBytes ( "UTF-8" ) ) ; } return encodeHex ( md . digest ( ) ) ; } catch ( final NoSuchAlgorithmException e ) { throw new RuntimeException ( e ) ; } catch ( final UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } } | A helper class to sha1 hash all the strings in a collection |
26,204 | public JsonLdOptions copy ( ) { final JsonLdOptions copy = new JsonLdOptions ( base ) ; copy . setCompactArrays ( compactArrays ) ; copy . setExpandContext ( expandContext ) ; copy . setProcessingMode ( processingMode ) ; copy . setDocumentLoader ( documentLoader ) ; copy . setEmbed ( embed ) ; copy . setExplicit ( explicit ) ; copy . setOmitDefault ( omitDefault ) ; copy . setOmitGraph ( omitGraph ) ; copy . setFrameExpansion ( frameExpansion ) ; copy . setPruneBlankNodeIdentifiers ( pruneBlankNodeIdentifiers ) ; copy . setRequireAll ( requireAll ) ; copy . setAllowContainerSetOnType ( allowContainerSetOnType ) ; copy . setUseRdfType ( useRdfType ) ; copy . setUseNativeTypes ( useNativeTypes ) ; copy . setProduceGeneralizedRdf ( produceGeneralizedRdf ) ; copy . format = format ; copy . useNamespaces = useNamespaces ; copy . outputForm = outputForm ; return copy ; } | Creates a shallow copy of this JsonLdOptions object . |
26,205 | private static void removeEmbed ( FramingContext state , String id ) { final Map < String , EmbedNode > links = state . uniqueEmbeds ; final EmbedNode embed = links . get ( id ) ; final Object parent = embed . parent ; final String property = embed . property ; final Map < String , Object > node = newMap ( JsonLdConsts . ID , id ) ; if ( JsonLdUtils . isNode ( parent ) ) { final List < Object > newvals = new ArrayList < Object > ( ) ; final List < Object > oldvals = ( List < Object > ) ( ( Map < String , Object > ) parent ) . get ( property ) ; for ( final Object v : oldvals ) { if ( v instanceof Map && Obj . equals ( ( ( Map < String , Object > ) v ) . get ( JsonLdConsts . ID ) , id ) ) { newvals . add ( node ) ; } else { newvals . add ( v ) ; } } ( ( Map < String , Object > ) parent ) . put ( property , newvals ) ; } removeDependents ( links , id ) ; } | Removes an existing embed . |
26,206 | private static void addFrameOutput ( FramingContext state , Object parent , String property , Object output ) { if ( parent instanceof Map ) { List < Object > prop = ( List < Object > ) ( ( Map < String , Object > ) parent ) . get ( property ) ; if ( prop == null ) { prop = new ArrayList < Object > ( ) ; ( ( Map < String , Object > ) parent ) . put ( property , prop ) ; } prop . add ( output ) ; } else { ( ( List ) parent ) . add ( output ) ; } } | Adds framing output to the given parent . |
26,207 | public RDFDataset toRDF ( ) throws JsonLdError { final Map < String , Object > nodeMap = newMap ( ) ; nodeMap . put ( JsonLdConsts . DEFAULT , newMap ( ) ) ; generateNodeMap ( this . value , nodeMap ) ; final RDFDataset dataset = new RDFDataset ( this ) ; for ( final String graphName : nodeMap . keySet ( ) ) { if ( JsonLdUtils . isRelativeIri ( graphName ) ) { continue ; } final Map < String , Object > graph = ( Map < String , Object > ) nodeMap . get ( graphName ) ; dataset . graphToRDF ( graphName , graph ) ; } return dataset ; } | Adds RDF triples for each graph in the current node map to an RDF dataset . |
26,208 | public Object normalize ( Map < String , Object > dataset ) throws JsonLdError { final List < Object > quads = new ArrayList < Object > ( ) ; final Map < String , Object > bnodes = newMap ( ) ; for ( String graphName : dataset . keySet ( ) ) { final List < Map < String , Object > > triples = ( List < Map < String , Object > > ) dataset . get ( graphName ) ; if ( JsonLdConsts . DEFAULT . equals ( graphName ) ) { graphName = null ; } for ( final Map < String , Object > quad : triples ) { if ( graphName != null ) { if ( graphName . indexOf ( "_:" ) == 0 ) { final Map < String , Object > tmp = newMap ( ) ; tmp . put ( "type" , "blank node" ) ; tmp . put ( "value" , graphName ) ; quad . put ( "name" , tmp ) ; } else { final Map < String , Object > tmp = newMap ( ) ; tmp . put ( "type" , "IRI" ) ; tmp . put ( "value" , graphName ) ; quad . put ( "name" , tmp ) ; } } quads . add ( quad ) ; final String [ ] attrs = new String [ ] { "subject" , "object" , "name" } ; for ( final String attr : attrs ) { if ( quad . containsKey ( attr ) && "blank node" . equals ( ( ( Map < String , Object > ) quad . get ( attr ) ) . get ( "type" ) ) ) { final String id = ( String ) ( ( Map < String , Object > ) quad . get ( attr ) ) . get ( "value" ) ; if ( ! bnodes . containsKey ( id ) ) { bnodes . put ( id , new LinkedHashMap < String , List < Object > > ( ) { { put ( "quads" , new ArrayList < Object > ( ) ) ; } } ) ; } ( ( List < Object > ) ( ( Map < String , Object > ) bnodes . get ( id ) ) . get ( "quads" ) ) . add ( quad ) ; } } } } final NormalizeUtils normalizeUtils = new NormalizeUtils ( quads , bnodes , new UniqueNamer ( "_:c14n" ) , opts ) ; return normalizeUtils . hashBlankNodes ( bnodes . keySet ( ) ) ; } | Performs RDF normalization on the given JSON - LD input . |
26,209 | public static CallStackElement create ( CallStackElement parent , String signature , long startTimestamp ) { CallStackElement cse ; if ( useObjectPooling ) { cse = objectPool . poll ( ) ; if ( cse == null ) { cse = new CallStackElement ( ) ; } } else { cse = new CallStackElement ( ) ; } cse . executionTime = startTimestamp ; cse . signature = signature ; if ( parent != null ) { cse . parent = parent ; parent . children . add ( cse ) ; } return cse ; } | This static factory method also sets the parent - child relationships . |
26,210 | public void beforeTransformation ( TypeDescription typeDescription , ClassLoader classLoader ) { if ( isPreventDuplicateTransformation ( ) ) { Dispatcher . put ( getClassAlreadyTransformedKey ( typeDescription , classLoader ) , Boolean . TRUE ) ; } if ( DEBUG_INSTRUMENTATION && logger . isDebugEnabled ( ) ) { logger . debug ( "TRANSFORM {} ({})" , typeDescription . getName ( ) , getClass ( ) . getSimpleName ( ) ) ; } } | This method is called before the transformation . You can stop the transformation from happening by returning false from this method . |
26,211 | public static String getCallerSignature ( ) { if ( Stagemonitor . getPlugin ( CorePlugin . class ) . getIncludePackages ( ) . isEmpty ( ) ) { return null ; } if ( javaLangAccessObject != null ) { return getCallerSignatureSharedSecrets ( ) ; } else { return getCallerSignatureGetStackTrace ( ) ; } } | Returns the signature of the method inside the monitored codebase which was last executed . |
26,212 | public static void reset ( MeasurementSession measurementSession ) { started = false ; disabled = false ; if ( configuration == null ) { reloadPluginsAndConfiguration ( ) ; } if ( measurementSession == null ) { CorePlugin corePlugin = getPlugin ( CorePlugin . class ) ; measurementSession = new MeasurementSession ( corePlugin . getApplicationName ( ) , corePlugin . getHostName ( ) , corePlugin . getInstanceName ( ) ) ; } onShutdownActions . add ( AgentAttacher . performRuntimeAttachment ( ) ) ; startMonitoring ( measurementSession ) ; healthCheckRegistry . register ( "Startup" , new HealthCheck ( ) { protected Result check ( ) throws Exception { if ( started ) { return Result . healthy ( ) ; } else { return Result . unhealthy ( "stagemonitor is not started" ) ; } } } ) ; logStatus ( ) ; new ConfigurationLogger ( ) . logConfiguration ( configuration ) ; } | Should only be used outside of this class by the internal unit tests |
26,213 | public boolean isPasswordCorrect ( String password ) { final String actualPassword = configurationRegistry . getString ( updateConfigPasswordKey ) ; return "" . equals ( actualPassword ) || actualPassword != null && actualPassword . equals ( password ) ; } | Validates a password . |
26,214 | public T convert ( String name ) throws IllegalArgumentException { if ( name == null ) { throw new IllegalArgumentException ( "Cant convert 'null' to " + enumClass . getSimpleName ( ) ) ; } try { return Enum . valueOf ( enumClass , name ) ; } catch ( IllegalArgumentException e ) { } try { return Enum . valueOf ( enumClass , name . toUpperCase ( ) ) ; } catch ( IllegalArgumentException e ) { } try { return Enum . valueOf ( enumClass , name . toUpperCase ( ) . replace ( "-" , "_" ) ) ; } catch ( IllegalArgumentException e ) { } throw new IllegalArgumentException ( "Can't convert " + name + " to " + enumClass . getSimpleName ( ) ) ; } | Converts a String into an Enum . |
26,215 | protected void doGet ( HttpServletRequest req , HttpServletResponse resp ) throws ServletException , IOException { if ( alertingPlugin . getAlertSender ( ) != null ) { JsonUtils . writeJsonToOutputStream ( alertingPlugin . getAlertSender ( ) . getAvailableAlerters ( ) , resp . getOutputStream ( ) ) ; } else { JsonUtils . writeJsonToOutputStream ( Collections . emptyList ( ) , resp . getOutputStream ( ) ) ; } } | Returns all available alerters |
26,216 | private void addRemotePropertiesConfigurationSources ( ConfigurationRegistry configuration , CorePlugin corePlugin ) { final List < URL > configurationUrls = corePlugin . getRemotePropertiesConfigUrls ( ) ; if ( corePlugin . isDeactivateStagemonitorIfRemotePropertyServerIsDown ( ) ) { assertRemotePropertiesServerIsAvailable ( configurationUrls . get ( 0 ) ) ; } logger . debug ( "Loading RemotePropertiesConfigurationSources with: configurationUrls = " + configurationUrls ) ; final HttpClient sharedHttpClient = new HttpClient ( ) ; for ( URL configUrl : configurationUrls ) { final RemotePropertiesConfigurationSource source = new RemotePropertiesConfigurationSource ( sharedHttpClient , configUrl ) ; configuration . addConfigurationSourceAfter ( source , SimpleSource . class ) ; } configuration . reloadAllConfigurationOptions ( ) ; } | Creates and registers a RemotePropertiesConfigurationSource for each configuration url |
26,217 | private void assertRemotePropertiesServerIsAvailable ( final URL configUrl ) { new HttpClient ( ) . send ( "HEAD" , configUrl . toExternalForm ( ) , new HashMap < String , String > ( ) , null , new HttpClient . ResponseHandler < Void > ( ) { public Void handleResponse ( HttpRequest < ? > httpRequest , InputStream is , Integer statusCode , IOException e ) throws IOException { if ( e != null || statusCode != 200 ) { throw new IllegalStateException ( "Remote properties are not available at " + configUrl + ", http status code: " + statusCode , e ) ; } return null ; } } ) ; } | Does a simple HEAD request to a configuration endpoint to check if it s reachable . If not an IllegalStateException is thrown |
26,218 | private CounterMetricFamily fromCounter ( List < Map . Entry < MetricName , Counter > > countersWithSameName ) { final Map . Entry < MetricName , Counter > first = countersWithSameName . get ( 0 ) ; final MetricName firstName = first . getKey ( ) ; final CounterMetricFamily metricFamily = new CounterMetricFamily ( firstName . getName ( ) , getHelpMessage ( firstName , first . getValue ( ) ) , firstName . getTagKeys ( ) ) ; for ( Map . Entry < MetricName , Counter > entry : countersWithSameName ) { metricFamily . addMetric ( entry . getKey ( ) . getTagValues ( ) , entry . getValue ( ) . getCount ( ) ) ; } return metricFamily ; } | Export counter as prometheus counter . |
26,219 | private MetricFamilySamples fromTimer ( List < Map . Entry < MetricName , Timer > > histogramsWithSameName ) { final SummaryMetricFamily summaryMetricFamily = getSummaryMetricFamily ( histogramsWithSameName , "_seconds" ) ; for ( Map . Entry < MetricName , Timer > entry : histogramsWithSameName ) { addSummaryMetric ( summaryMetricFamily , entry . getKey ( ) , entry . getValue ( ) . getSnapshot ( ) , SECONDS_IN_NANOS , entry . getValue ( ) . getCount ( ) ) ; } return summaryMetricFamily ; } | Export dropwizard Timer as a histogram . Use TIME_UNIT as time unit . |
26,220 | @ SuppressWarnings ( "unchecked" ) public static < T > T get ( String key , Class < T > valueClass ) { return ( T ) values . get ( key ) ; } | Gets a shared value by it s key |
26,221 | public static synchronized Runnable performRuntimeAttachment ( ) { if ( runtimeAttached || ! corePlugin . isStagemonitorActive ( ) || ! corePlugin . isAttachAgentAtRuntime ( ) ) { return NOOP_ON_SHUTDOWN_ACTION ; } runtimeAttached = true ; final List < ClassFileTransformer > classFileTransformers = new ArrayList < ClassFileTransformer > ( ) ; final AutoEvictingCachingBinaryLocator binaryLocator = new AutoEvictingCachingBinaryLocator ( ) ; if ( assertNoDifferentStagemonitorVersionIsDeployedOnSameJvm ( ) && initInstrumentation ( ) ) { final long start = System . currentTimeMillis ( ) ; classFileTransformers . add ( initByteBuddyClassFileTransformer ( binaryLocator ) ) ; if ( corePlugin . isDebugInstrumentation ( ) ) { logger . info ( "Attached agents in {} ms" , System . currentTimeMillis ( ) - start ) ; } TimedElementMatcherDecorator . logMetrics ( ) ; } return new Runnable ( ) { public void run ( ) { for ( ClassFileTransformer classFileTransformer : classFileTransformers ) { instrumentation . removeTransformer ( classFileTransformer ) ; } hashCodesOfClassLoadersToIgnore . add ( ClassUtils . getIdentityString ( AgentAttacher . class . getClassLoader ( ) ) ) ; binaryLocator . close ( ) ; } } ; } | Attaches the profiler and other instrumenters at runtime so that it is not necessary to add the - javaagent command line argument . |
26,222 | public static void registerMBean ( final ObjectInstance objectInstance , final String mBeanAttributeName , MetricName metricName , Metric2Registry metricRegistry ) { metricRegistry . register ( metricName , new Gauge < Object > ( ) { public Object getValue ( ) { return getValueFromMBean ( objectInstance , mBeanAttributeName ) ; } } ) ; } | Registers a MBean into the MetricRegistry |
26,223 | public void registerAll ( Metric2Set metrics ) throws IllegalArgumentException { for ( Map . Entry < MetricName , Metric > entry : metrics . getMetrics ( ) . entrySet ( ) ) { register ( entry . getKey ( ) , entry . getValue ( ) ) ; } } | Given a metric set registers them . |
26,224 | public void registerAny ( Metric2Set metrics ) { for ( Map . Entry < MetricName , Metric > entry : metrics . getMetrics ( ) . entrySet ( ) ) { registerNewMetrics ( entry . getKey ( ) , entry . getValue ( ) ) ; } } | Given a metric set registers the ones not already registered . This method prevents IllegalArgumentException |
26,225 | public void registerNewMetrics ( MetricName name , Metric metric ) { final Set < MetricName > registeredNames = getNames ( ) ; if ( ! registeredNames . contains ( name ) ) { try { register ( name , metric ) ; } catch ( IllegalArgumentException e ) { } } } | Only registers the metric if it is not already registered |
26,226 | public MimeMessage createMimeMessage ( Session session ) throws MessagingException { if ( isEmpty ( htmlPart ) && isEmpty ( textPart ) ) { throw new IllegalArgumentException ( "Missing email content" ) ; } final MimeMessage msg = new MimeMessage ( session ) ; msg . setSubject ( subject ) ; msg . setFrom ( new InternetAddress ( from ) ) ; msg . setContent ( createMultiPart ( ) ) ; msg . setRecipients ( Message . RecipientType . TO , InternetAddress . parse ( recipients , false ) ) ; return msg ; } | Creates a MimeMessage containing given Multipart . Subject sender and content and session will be set . |
26,227 | private Multipart createMultiPart ( ) throws MessagingException { Multipart multipart = new MimeMultipart ( "alternative" ) ; if ( textPart != null ) { multipart . addBodyPart ( ( BodyPart ) createTextMimePart ( ) ) ; } if ( htmlPart != null ) { multipart . addBodyPart ( ( BodyPart ) createHtmlMimePart ( ) ) ; } return multipart ; } | Creates a Multipart from present parts . |
26,228 | private MimePart createHtmlMimePart ( ) throws MessagingException { MimePart bodyPart = new MimeBodyPart ( ) ; bodyPart . setContent ( htmlPart , "text/html; charset=utf-8" ) ; return bodyPart ; } | Creates a MimePart from HTML part . |
26,229 | private MimePart createTextMimePart ( ) throws MessagingException { MimePart bodyPart = new MimeBodyPart ( ) ; bodyPart . setText ( textPart ) ; return bodyPart ; } | Creates a MimePart from text part . |
26,230 | public PreExecutionInterceptorContext mustCollectCallTree ( String reason ) { logger . debug ( "Must collect call tree because {}" , reason ) ; mustCollectCallTree = true ; collectCallTree = true ; return this ; } | Makes sure that a call tree is collected for the current request . In other words profiles this request . |
26,231 | public PreExecutionInterceptorContext shouldNotCollectCallTree ( String reason ) { if ( ! mustCollectCallTree ) { logger . debug ( "Should not collect call tree because {}" , reason ) ; collectCallTree = false ; } return this ; } | Requests that this request should not be profiled |
26,232 | public List < CheckResult > check ( MetricName actualTarget , Map < String , Number > currentValuesByMetric ) { SortedMap < CheckResult . Status , List < Threshold > > sortedThresholds = new TreeMap < CheckResult . Status , List < Threshold > > ( thresholds ) ; for ( Map . Entry < CheckResult . Status , List < Threshold > > entry : sortedThresholds . entrySet ( ) ) { List < CheckResult > results = checkThresholds ( entry . getValue ( ) , entry . getKey ( ) , actualTarget , currentValuesByMetric ) ; if ( ! results . isEmpty ( ) ) { return results ; } } return Collections . emptyList ( ) ; } | Performs threshold checks for the whole check group |
26,233 | public Map < String , Boolean > getNamesOfConfigurationSources ( ) { final Map < String , Boolean > result = new LinkedHashMap < String , Boolean > ( ) ; for ( ConfigurationSource configurationSource : configurationSources ) { result . put ( configurationSource . getName ( ) , configurationSource . isSavingPossible ( ) ) ; } return result ; } | Returns a map with the names of all configuration sources as key and a boolean indicating whether the configuration source supports saving as value |
26,234 | public void reload ( String key ) { if ( configurationOptionsByKey . containsKey ( key ) ) { configurationOptionsByKey . get ( key ) . reload ( false ) ; } } | Reloads a specific dynamic configuration option . |
26,235 | public String getString ( String key ) { if ( key == null || key . isEmpty ( ) ) { return null ; } String property = null ; for ( ConfigurationSource configurationSource : configurationSources ) { property = configurationSource . getValue ( key ) ; if ( property != null ) { break ; } } return property ; } | Gets the value of a configuration key as string |
26,236 | public URL getElasticsearchUrl ( ) { final List < URL > urls = elasticsearchUrls . getValue ( ) ; if ( urls . isEmpty ( ) ) { return null ; } final int index = accessesToElasticsearchUrl . getAndIncrement ( ) % urls . size ( ) ; URL elasticsearchURL = urls . get ( index ) ; final String defaultUsernameValue = elasticsearchDefaultUsername . getValue ( ) ; final String defaultPasswordValue = elasticsearchDefaultPassword . getValue ( ) ; if ( elasticsearchURL . getUserInfo ( ) == null && ! defaultUsernameValue . isEmpty ( ) && ! defaultPasswordValue . isEmpty ( ) ) { try { String username = URLEncoder . encode ( defaultUsernameValue , "UTF-8" ) ; String password = URLEncoder . encode ( defaultPasswordValue , "UTF-8" ) ; StringBuilder stringBuilder = new StringBuilder ( ) ; stringBuilder . append ( elasticsearchURL . getProtocol ( ) ) . append ( "://" ) . append ( username ) . append ( ":" ) . append ( password ) . append ( "@" ) . append ( elasticsearchURL . getHost ( ) ) . append ( ":" ) . append ( elasticsearchURL . getPort ( ) ) . append ( elasticsearchURL . getPath ( ) ) ; return new URL ( stringBuilder . toString ( ) ) ; } catch ( Exception e ) { logger . error ( e . getMessage ( ) , e ) ; } } return elasticsearchURL ; } | Cycles through all provided Elasticsearch URLs and returns one |
26,237 | public void update ( T newValue , String configurationSourceName ) throws IOException { final String newValueAsString = valueConverter . toString ( newValue ) ; configuration . save ( key , newValueAsString , configurationSourceName ) ; } | Updates the existing value with a new one |
26,238 | public boolean isDefault ( ) { return ( valueAsString != null && valueAsString . equals ( defaultValueAsString ) ) || ( valueAsString == null && defaultValueAsString == null ) ; } | Returns true if the current value is equal to the default value |
26,239 | public String toGraphiteName ( ) { StringBuilder sb = new StringBuilder ( GraphiteSanitizer . sanitizeGraphiteMetricSegment ( name ) ) ; for ( String value : tags . values ( ) ) { sb . append ( '.' ) . append ( GraphiteSanitizer . sanitizeGraphiteMetricSegment ( value ) ) ; } return sb . toString ( ) ; } | Converts a metrics 2 . 0 name into a graphite compliant name by appending all tag values to the metric name |
26,240 | public final List < Router > getChildRouters ( ) { List < Router > routers = new ArrayList < > ( childRouters . size ( ) ) ; routers . addAll ( childRouters ) ; return routers ; } | Returns all of this Controller s child Routers |
26,241 | public boolean handleBack ( ) { List < RouterTransaction > childTransactions = new ArrayList < > ( ) ; for ( ControllerHostedRouter childRouter : childRouters ) { childTransactions . addAll ( childRouter . getBackstack ( ) ) ; } Collections . sort ( childTransactions , new Comparator < RouterTransaction > ( ) { public int compare ( RouterTransaction o1 , RouterTransaction o2 ) { return o2 . transactionIndex - o1 . transactionIndex ; } } ) ; for ( RouterTransaction transaction : childTransactions ) { Controller childController = transaction . controller ; if ( childController . isAttached ( ) && childController . getRouter ( ) . handleBack ( ) ) { return true ; } } return false ; } | Should be overridden if this Controller needs to handle the back button being pressed . |
26,242 | public List < RouterTransaction > getBackstack ( ) { List < RouterTransaction > list = new ArrayList < > ( backstack . size ( ) ) ; Iterator < RouterTransaction > backstackIterator = backstack . reverseIterator ( ) ; while ( backstackIterator . hasNext ( ) ) { list . add ( backstackIterator . next ( ) ) ; } return list ; } | Returns the current backstack ordered from root to most recently pushed . |
26,243 | public void rebindIfNeeded ( ) { ThreadUtils . ensureMainThread ( ) ; Iterator < RouterTransaction > backstackIterator = backstack . reverseIterator ( ) ; while ( backstackIterator . hasNext ( ) ) { RouterTransaction transaction = backstackIterator . next ( ) ; if ( transaction . controller . getNeedsAttach ( ) ) { performControllerChange ( transaction , null , true , new SimpleSwapChangeHandler ( false ) ) ; } else { setControllerRouter ( transaction . controller ) ; } } } | Attaches this Router s existing backstack to its container if one exists . |
26,244 | private void ensureOrderedTransactionIndices ( List < RouterTransaction > backstack ) { List < Integer > indices = new ArrayList < > ( backstack . size ( ) ) ; for ( RouterTransaction transaction : backstack ) { transaction . ensureValidIndex ( getTransactionIndexer ( ) ) ; indices . add ( transaction . transactionIndex ) ; } Collections . sort ( indices ) ; for ( int i = 0 ; i < backstack . size ( ) ; i ++ ) { backstack . get ( i ) . transactionIndex = indices . get ( i ) ; } } | developer rearranging the backstack at runtime . |
26,245 | public Bundle saveInstanceState ( ) { Bundle bundle = new Bundle ( ) ; bundle . putBundle ( KEY_VIEW_CONTROLLER_BUNDLE , controller . saveInstanceState ( ) ) ; if ( pushControllerChangeHandler != null ) { bundle . putBundle ( KEY_PUSH_TRANSITION , pushControllerChangeHandler . toBundle ( ) ) ; } if ( popControllerChangeHandler != null ) { bundle . putBundle ( KEY_POP_TRANSITION , popControllerChangeHandler . toBundle ( ) ) ; } bundle . putString ( KEY_TAG , tag ) ; bundle . putInt ( KEY_INDEX , transactionIndex ) ; bundle . putBoolean ( KEY_ATTACHED_TO_ROUTER , attachedToRouter ) ; return bundle ; } | Used to serialize this transaction into a Bundle |
26,246 | protected ActionBar getActionBar ( ) { ActionBarProvider actionBarProvider = ( ( ActionBarProvider ) getActivity ( ) ) ; return actionBarProvider != null ? actionBarProvider . getSupportActionBar ( ) : null ; } | be accessed . In a production app this would use Dagger instead . |
26,247 | private static String driverVersion ( ) { Package pkg = Session . class . getPackage ( ) ; if ( pkg != null && pkg . getImplementationVersion ( ) != null ) { return pkg . getImplementationVersion ( ) ; } return "dev" ; } | Extracts the driver version from the driver jar MANIFEST . MF file . |
26,248 | private StatementResult addCompany ( final Transaction tx , final String name ) { return tx . run ( "CREATE (:Company {name: $name})" , parameters ( "name" , name ) ) ; } | Create a company node |
26,249 | private StatementResult addPerson ( final Transaction tx , final String name ) { return tx . run ( "CREATE (:Person {name: $name})" , parameters ( "name" , name ) ) ; } | Create a person node |
26,250 | private StatementResult employ ( final Transaction tx , final String person , final String company ) { return tx . run ( "MATCH (person:Person {name: $person_name}) " + "MATCH (company:Company {name: $company_name}) " + "CREATE (person)-[:WORKS_FOR]->(company)" , parameters ( "person_name" , person , "company_name" , company ) ) ; } | This relies on the person first having been created . |
26,251 | private StatementResult makeFriends ( final Transaction tx , final String person1 , final String person2 ) { return tx . run ( "MATCH (a:Person {name: $person_1}) " + "MATCH (b:Person {name: $person_2}) " + "MERGE (a)-[:KNOWS]->(b)" , parameters ( "person_1" , person1 , "person_2" , person2 ) ) ; } | Create a friendship between two people . |
26,252 | private StatementResult printFriends ( final Transaction tx ) { StatementResult result = tx . run ( "MATCH (a)-[:KNOWS]->(b) RETURN a.name, b.name" ) ; while ( result . hasNext ( ) ) { Record record = result . next ( ) ; System . out . println ( String . format ( "%s knows %s" , record . get ( "a.name" ) . asString ( ) , record . get ( "b.name" ) . toString ( ) ) ) ; } return result ; } | Match and display all friendships . |
26,253 | public static void checkArgument ( Object argument , Class < ? > expectedClass ) { if ( ! expectedClass . isInstance ( argument ) ) { throw new IllegalArgumentException ( "Argument expected to be of type: " + expectedClass . getName ( ) + " but was: " + argument ) ; } } | Assert that given argument is of expected type . |
26,254 | public static AuthToken kerberos ( String base64EncodedTicket ) { Objects . requireNonNull ( base64EncodedTicket , "Ticket can't be null" ) ; Map < String , Value > map = newHashMapWithSize ( 3 ) ; map . put ( SCHEME_KEY , value ( "kerberos" ) ) ; map . put ( PRINCIPAL_KEY , value ( "" ) ) ; map . put ( CREDENTIALS_KEY , value ( base64EncodedTicket ) ) ; return new InternalAuthToken ( map ) ; } | The kerberos authentication scheme using a base64 encoded ticket |
26,255 | public static < T > Publisher < T > createEmptyPublisher ( Supplier < CompletionStage < Void > > supplier ) { return Mono . create ( sink -> supplier . get ( ) . whenComplete ( ( ignore , completionError ) -> { Throwable error = Futures . completionExceptionCause ( completionError ) ; if ( error != null ) { sink . error ( error ) ; } else { sink . success ( ) ; } } ) ) ; } | The publisher created by this method will either succeed without publishing anything or fail with an error . |
26,256 | private void load ( ) throws IOException { if ( ! knownHosts . exists ( ) ) { return ; } assertKnownHostFileReadable ( ) ; try ( BufferedReader reader = new BufferedReader ( new FileReader ( knownHosts ) ) ) { String line ; while ( ( line = reader . readLine ( ) ) != null ) { if ( ( ! line . trim ( ) . startsWith ( "#" ) ) ) { String [ ] strings = line . split ( " " ) ; if ( strings [ 0 ] . trim ( ) . equals ( serverId ) ) { fingerprint = strings [ 1 ] . trim ( ) ; return ; } } } } } | Try to load the certificate form the file if the server we ve connected is a known server . |
26,257 | public static String fingerprint ( X509Certificate cert ) throws CertificateException { try { MessageDigest md = MessageDigest . getInstance ( "SHA-512" ) ; md . update ( cert . getEncoded ( ) ) ; return ByteBufUtil . hexDump ( md . digest ( ) ) ; } catch ( NoSuchAlgorithmException e ) { throw new CertificateException ( "Cannot use TLS on this platform, because SHA-512 message digest algorithm is not available: " + e . getMessage ( ) , e ) ; } } | Calculate the certificate fingerprint - simply the SHA - 512 hash of the DER - encoded certificate . |
26,258 | public CompletionStage < ClusterComposition > lookupClusterComposition ( RoutingTable routingTable , ConnectionPool connectionPool ) { CompletableFuture < ClusterComposition > result = new CompletableFuture < > ( ) ; lookupClusterComposition ( routingTable , connectionPool , 0 , 0 , result ) ; return result ; } | Given the current routing table and connection pool use the connection composition provider to fetch a new cluster composition which would be used to update the routing table and connection pool . |
26,259 | public static void saveX509Cert ( String certStr , File certFile ) throws IOException { try ( BufferedWriter writer = new BufferedWriter ( new FileWriter ( certFile ) ) ) { writer . write ( BEGIN_CERT ) ; writer . newLine ( ) ; writer . write ( certStr ) ; writer . newLine ( ) ; writer . write ( END_CERT ) ; writer . newLine ( ) ; } } | Save a certificate to a file in base 64 binary format with BEGIN and END strings |
26,260 | public static void saveX509Cert ( Certificate cert , File certFile ) throws GeneralSecurityException , IOException { saveX509Cert ( new Certificate [ ] { cert } , certFile ) ; } | Save a certificate to a file . Remove all the content in the file if there is any before . |
26,261 | public static void saveX509Cert ( Certificate [ ] certs , File certFile ) throws GeneralSecurityException , IOException { try ( BufferedWriter writer = new BufferedWriter ( new FileWriter ( certFile ) ) ) { for ( Certificate cert : certs ) { String certStr = Base64 . getEncoder ( ) . encodeToString ( cert . getEncoded ( ) ) . replaceAll ( "(.{64})" , "$1\n" ) ; writer . write ( BEGIN_CERT ) ; writer . newLine ( ) ; writer . write ( certStr ) ; writer . newLine ( ) ; writer . write ( END_CERT ) ; writer . newLine ( ) ; } } } | Save a list of certificates into a file |
26,262 | public static void loadX509Cert ( File certFile , KeyStore keyStore ) throws GeneralSecurityException , IOException { try ( BufferedInputStream inputStream = new BufferedInputStream ( new FileInputStream ( certFile ) ) ) { CertificateFactory certFactory = CertificateFactory . getInstance ( "X.509" ) ; int certCount = 0 ; while ( inputStream . available ( ) > 0 ) { try { Certificate cert = certFactory . generateCertificate ( inputStream ) ; certCount ++ ; loadX509Cert ( cert , "neo4j.javadriver.trustedcert." + certCount , keyStore ) ; } catch ( CertificateException e ) { if ( e . getCause ( ) != null && e . getCause ( ) . getMessage ( ) . equals ( "Empty input" ) ) { return ; } throw new IOException ( "Failed to load certificate from `" + certFile . getAbsolutePath ( ) + "`: " + certCount + " : " + e . getMessage ( ) , e ) ; } } } } | Load the certificates written in X . 509 format in a file to a key store . |
26,263 | public static void loadX509Cert ( Certificate cert , String certAlias , KeyStore keyStore ) throws KeyStoreException { keyStore . setCertificateEntry ( certAlias , cert ) ; } | Load a certificate to a key store with a name |
26,264 | public static String X509CertToString ( String cert ) { String cert64CharPerLine = cert . replaceAll ( "(.{64})" , "$1\n" ) ; return BEGIN_CERT + "\n" + cert64CharPerLine + "\n" + END_CERT + "\n" ; } | Convert a certificate in base 64 binary format with BEGIN and END strings |
26,265 | public Statement withUpdatedParameters ( Value updates ) { if ( updates == null || updates . isEmpty ( ) ) { return this ; } else { Map < String , Value > newParameters = newHashMapWithSize ( Math . max ( parameters . size ( ) , updates . size ( ) ) ) ; newParameters . putAll ( parameters . asMap ( ofValue ( ) ) ) ; for ( Map . Entry < String , Value > entry : updates . asMap ( ofValue ( ) ) . entrySet ( ) ) { Value value = entry . getValue ( ) ; if ( value . isNull ( ) ) { newParameters . remove ( entry . getKey ( ) ) ; } else { newParameters . put ( entry . getKey ( ) , value ) ; } } return withParameters ( value ( newParameters ) ) ; } } | Create a new statement with new parameters derived by updating this statement s parameters using the given updates . |
26,266 | public BoltServerAddress resolve ( ) throws UnknownHostException { String ipAddress = InetAddress . getByName ( host ) . getHostAddress ( ) ; if ( ipAddress . equals ( host ) ) { return this ; } else { return new BoltServerAddress ( host , ipAddress , port ) ; } } | Resolve the host name down to an IP address if not already resolved . |
26,267 | public static GoogleConnector getInstance ( ) { if ( instance == null ) { try { instance = new GoogleConnector ( ) ; } catch ( Exception e ) { throw new RuntimeException ( "The GoogleConnector could not be instanced!" , e ) ; } } return instance ; } | On demand instance creator method used to get the single instance of this google authenticator class . |
26,268 | synchronized void removeCredential ( String accountId ) throws IOException { DataStore < StoredCredential > sc = StoredCredential . getDefaultDataStore ( dataStoreFactory ) ; sc . delete ( accountId ) ; calendarService = null ; geoService = null ; } | Deletes the stored credentials for the given account id . This means the next time the user must authorize the app to access his calendars . |
26,269 | boolean isAuthorized ( String accountId ) { try { DataStore < StoredCredential > sc = StoredCredential . getDefaultDataStore ( dataStoreFactory ) ; return sc . containsKey ( accountId ) ; } catch ( IOException e ) { return false ; } } | Checks if the given account id has already been authorized and the user granted access to his calendars info . |
26,270 | public synchronized GoogleCalendarService getCalendarService ( String accountId ) throws IOException { if ( calendarService == null ) { Credential credential = impl_getStoredCredential ( accountId ) ; if ( credential == null ) { throw new UnsupportedOperationException ( "The account has not been authorized yet!" ) ; } calendarService = new GoogleCalendarService ( impl_createService ( credential ) ) ; } return calendarService ; } | Instances a new calendar service for the given google account user name . This requires previous authorization to get the service so if the user has not granted access to his data this method will start the authorization process automatically ; this attempts to open the login google page in the default browser . |
26,271 | GoogleAccount getAccountInfo ( String accountId ) throws IOException { Credential credential = impl_getStoredCredential ( accountId ) ; if ( credential == null ) { throw new UnsupportedOperationException ( "The account has not been authorized yet!" ) ; } Userinfoplus info = impl_requestUserInfo ( credential ) ; GoogleAccount account = new GoogleAccount ( ) ; account . setId ( accountId ) ; account . setName ( info . getName ( ) ) ; return account ; } | Requests the user info for the given account . This requires previous authorization from the user so this might start the process . |
26,272 | public final ObjectProperty < Insets > extraPaddingProperty ( ) { if ( extraPadding == null ) { extraPadding = new StyleableObjectProperty < Insets > ( new Insets ( 2 , 0 , 9 , 0 ) ) { public CssMetaData < AllDayView , Insets > getCssMetaData ( ) { return StyleableProperties . EXTRA_PADDING ; } public Object getBean ( ) { return AllDayView . this ; } public String getName ( ) { return "extraPadding" ; } } ; } return extraPadding ; } | Extra padding to be used inside of the view above and below the full day entries . This is required as the regular padding is already used for other styling purposes . |
26,273 | public final DoubleProperty rowHeightProperty ( ) { if ( rowHeight == null ) { rowHeight = new StyleableDoubleProperty ( 20 ) { public CssMetaData < AllDayView , Number > getCssMetaData ( ) { return StyleableProperties . ROW_HEIGHT ; } public Object getBean ( ) { return AllDayView . this ; } public String getName ( ) { return "rowHeight" ; } } ; } return rowHeight ; } | The height for each row shown by the view . This value determines the total height of the view . |
26,274 | public final DoubleProperty rowSpacingProperty ( ) { if ( rowSpacing == null ) { rowSpacing = new StyleableDoubleProperty ( 2 ) { public CssMetaData < AllDayView , Number > getCssMetaData ( ) { return StyleableProperties . ROW_SPACING ; } public Object getBean ( ) { return AllDayView . this ; } public String getName ( ) { return "rowSpacing" ; } } ; } return rowSpacing ; } | Stores the spacing between rows in the view . |
26,275 | public final DoubleProperty columnSpacingProperty ( ) { if ( columnSpacing == null ) { columnSpacing = new StyleableDoubleProperty ( 2 ) { public CssMetaData < AllDayView , Number > getCssMetaData ( ) { return StyleableProperties . COLUMN_SPACING ; } public Object getBean ( ) { return AllDayView . this ; } public String getName ( ) { return "columnSpacing" ; } } ; } return columnSpacing ; } | Stores the spacing between columns in the view . |
26,276 | public void show ( Window owner ) { InvalidationListener viewTypeListener = obs -> loadDropDownValues ( getDate ( ) ) ; if ( dialog != null ) { dialog . show ( ) ; } else { TimeRangeView timeRange = getSettingsView ( ) . getTimeRangeView ( ) ; Scene scene = new Scene ( this ) ; dialog = new Stage ( ) ; dialog . initOwner ( owner ) ; dialog . setScene ( scene ) ; dialog . sizeToScene ( ) ; dialog . centerOnScreen ( ) ; dialog . setTitle ( Messages . getString ( "PrintView.TITLE_LABEL" ) ) ; dialog . initModality ( Modality . APPLICATION_MODAL ) ; if ( getPrintIcon ( ) != null ) dialog . getIcons ( ) . add ( getPrintIcon ( ) ) ; dialog . setOnHidden ( obs -> { timeRange . cleanOldValues ( ) ; timeRange . viewTypeProperty ( ) . removeListener ( viewTypeListener ) ; } ) ; dialog . setOnShown ( obs -> timeRange . viewTypeProperty ( ) . addListener ( viewTypeListener ) ) ; dialog . show ( ) ; } } | Creates an application - modal dialog and shows it after adding the print view to it . |
26,277 | public int approximateIntervalInDays ( ) { int freqLengthDays ; int nPerPeriod = 0 ; switch ( this . freq ) { case DAILY : freqLengthDays = 1 ; break ; case WEEKLY : freqLengthDays = 7 ; if ( ! this . byDay . isEmpty ( ) ) { nPerPeriod = this . byDay . size ( ) ; } break ; case MONTHLY : freqLengthDays = 30 ; if ( ! this . byDay . isEmpty ( ) ) { for ( WeekdayNum day : byDay ) { nPerPeriod += 0 != day . num ? 1 : 4 ; } } else { nPerPeriod = this . byMonthDay . length ; } break ; case YEARLY : freqLengthDays = 365 ; int monthCount = 12 ; if ( 0 != this . byMonth . length ) { monthCount = this . byMonth . length ; } if ( ! this . byDay . isEmpty ( ) ) { for ( WeekdayNum day : byDay ) { nPerPeriod += ( 0 != day . num ? 1 : 4 ) * monthCount ; } } else if ( 0 != this . byMonthDay . length ) { nPerPeriod += monthCount * this . byMonthDay . length ; } else { nPerPeriod += this . byYearDay . length ; } break ; default : freqLengthDays = 0 ; } if ( 0 == nPerPeriod ) { nPerPeriod = 1 ; } return ( ( freqLengthDays / nPerPeriod ) * this . interval ) ; } | an approximate number of days between occurences . |
26,278 | public String toIcal ( ) { StringBuilder buf = new StringBuilder ( ) ; buf . append ( this . getName ( ) . toUpperCase ( ) ) ; buf . append ( ";TZID=\"" ) . append ( tzid . getID ( ) ) . append ( '"' ) ; buf . append ( ";VALUE=" ) . append ( valueType . toIcal ( ) ) ; if ( hasExtParams ( ) ) { for ( Map . Entry < String , String > param : getExtParams ( ) . entrySet ( ) ) { String k = param . getKey ( ) , v = param . getValue ( ) ; if ( ICAL_SPECIALS . matcher ( v ) . find ( ) ) { v = "\"" + v + "\"" ; } buf . append ( ';' ) . append ( k ) . append ( '=' ) . append ( v ) ; } } buf . append ( ':' ) ; for ( int i = 0 ; i < datesUtc . length ; ++ i ) { if ( 0 != i ) { buf . append ( ',' ) ; } DateValue v = datesUtc [ i ] ; buf . append ( v ) ; if ( v instanceof TimeValue ) { buf . append ( 'Z' ) ; } } return buf . toString ( ) ; } | returns a String containing ical content lines . |
26,279 | static Predicate < DateValue > byDayFilter ( final WeekdayNum [ ] days , final boolean weeksInYear , final Weekday wkst ) { return new Predicate < DateValue > ( ) { public boolean apply ( DateValue date ) { Weekday dow = Weekday . valueOf ( date ) ; int nDays ; Weekday dow0 ; int instance ; if ( weeksInYear ) { nDays = TimeUtils . yearLength ( date . year ( ) ) ; dow0 = Weekday . firstDayOfWeekInMonth ( date . year ( ) , 1 ) ; instance = TimeUtils . dayOfYear ( date . year ( ) , date . month ( ) , date . day ( ) ) ; } else { nDays = TimeUtils . monthLength ( date . year ( ) , date . month ( ) ) ; dow0 = Weekday . firstDayOfWeekInMonth ( date . year ( ) , date . month ( ) ) ; instance = date . day ( ) - 1 ; } int dateWeekNo ; if ( wkst . javaDayNum <= dow . javaDayNum ) { dateWeekNo = 1 + ( instance / 7 ) ; } else { dateWeekNo = ( instance / 7 ) ; } for ( int i = days . length ; -- i >= 0 ; ) { WeekdayNum day = days [ i ] ; if ( day . wday == dow ) { int weekNo = day . num ; if ( 0 == weekNo ) { return true ; } if ( weekNo < 0 ) { weekNo = Util . invertWeekdayNum ( day , dow0 , nDays ) ; } if ( dateWeekNo == weekNo ) { return true ; } } } return false ; } } ; } | constructs a day filter based on a BYDAY rule . |
26,280 | static Predicate < DateValue > weekIntervalFilter ( final int interval , final Weekday wkst , final DateValue dtStart ) { return new Predicate < DateValue > ( ) { DateValue wkStart ; { DTBuilder wkStartB = new DTBuilder ( dtStart ) ; wkStartB . day -= ( 7 + Weekday . valueOf ( dtStart ) . javaDayNum - wkst . javaDayNum ) % 7 ; wkStart = wkStartB . toDate ( ) ; } public boolean apply ( DateValue date ) { int daysBetween = TimeUtils . daysBetween ( date , wkStart ) ; if ( daysBetween < 0 ) { daysBetween += ( interval * 7 * ( 1 + daysBetween / ( - 7 * interval ) ) ) ; } int off = ( daysBetween / 7 ) % interval ; return 0 == off ; } } ; } | constructs a filter that accepts only every interval - th week from the week containing dtStart . |
26,281 | static Predicate < DateValue > byMinuteFilter ( int [ ] minutes ) { long minutesByBit = 0 ; for ( int minute : minutes ) { minutesByBit |= 1L << minute ; } if ( ( minutesByBit & LOW_60_BITS ) == LOW_60_BITS ) { return Predicates . alwaysTrue ( ) ; } final long bitField = minutesByBit ; return new Predicate < DateValue > ( ) { public boolean apply ( DateValue date ) { if ( ! ( date instanceof TimeValue ) ) { return false ; } TimeValue tv = ( TimeValue ) date ; return ( bitField & ( 1L << tv . minute ( ) ) ) != 0 ; } } ; } | constructs a minute filter based on a BYMINUTE rule . |
26,282 | static Predicate < DateValue > bySecondFilter ( int [ ] seconds ) { long secondsByBit = 0 ; for ( int second : seconds ) { secondsByBit |= 1L << second ; } if ( ( secondsByBit & LOW_60_BITS ) == LOW_60_BITS ) { return Predicates . alwaysTrue ( ) ; } final long bitField = secondsByBit ; return new Predicate < DateValue > ( ) { public boolean apply ( DateValue date ) { if ( ! ( date instanceof TimeValue ) ) { return false ; } TimeValue tv = ( TimeValue ) date ; return ( bitField & ( 1L << tv . second ( ) ) ) != 0 ; } } ; } | constructs a second filter based on a BYMINUTE rule . |
26,283 | public final boolean isExtendedMonth ( YearMonth month ) { if ( month != null ) { YearMonth extendedStart = getExtendedStartMonth ( ) ; if ( ( month . equals ( extendedStart ) || month . isAfter ( extendedStart ) ) && month . isBefore ( getStartMonth ( ) ) ) { return true ; } YearMonth extendedEnd = getExtendedEndMonth ( ) ; if ( ( month . equals ( extendedEnd ) || month . isBefore ( extendedEnd ) ) && month . isAfter ( getEndMonth ( ) ) ) { return true ; } } return false ; } | A simple check to see if the given month is part of the extended months . |
26,284 | public final boolean isVisibleDate ( LocalDate date ) { if ( date != null ) { YearMonth extendedStart = getExtendedStartMonth ( ) ; YearMonth extendedEnd = getExtendedEndMonth ( ) ; LocalDate startDate = extendedStart . atDay ( 1 ) ; LocalDate endDate = extendedEnd . atEndOfMonth ( ) ; if ( ( date . equals ( startDate ) || date . isAfter ( startDate ) ) && ( date . equals ( endDate ) || date . isBefore ( endDate ) ) ) { return true ; } } return false ; } | Determines if the given date is currently showing is part of the view . This method uses the extended start and end months . |
26,285 | public static long secsSinceEpoch ( DateValue date ) { long result = fixedFromGregorian ( date ) * SECS_PER_DAY ; if ( date instanceof TimeValue ) { TimeValue time = ( TimeValue ) date ; result += time . second ( ) + 60 * ( time . minute ( ) + 60 * time . hour ( ) ) ; } return result ; } | Compute the number of seconds from the Proleptic Gregorian epoch to the given time . |
26,286 | public static DateValue toDateValue ( DateValue dv ) { return ( ! ( dv instanceof TimeValue ) ? dv : new DateValueImpl ( dv . year ( ) , dv . month ( ) , dv . day ( ) ) ) ; } | a DateValue with the same year month and day as the given instance that is not a TimeValue . |
26,287 | public static String getString ( String key ) { try { return RESOURCE_BUNDLE . getString ( key ) ; } catch ( MissingResourceException e ) { return '!' + key + '!' ; } } | Returns the translation for the given key . |
26,288 | protected void updateStyles ( ) { DayEntryView view = getSkinnable ( ) ; Entry < ? > entry = getEntry ( ) ; Calendar calendar = entry . getCalendar ( ) ; if ( entry instanceof DraggedEntry ) { calendar = ( ( DraggedEntry ) entry ) . getOriginalCalendar ( ) ; } if ( calendar == null ) { return ; } view . getStyleClass ( ) . setAll ( "default-style-entry" , calendar . getStyle ( ) + "-entry" ) ; if ( entry . isRecurrence ( ) ) { view . getStyleClass ( ) . add ( "recurrence" ) ; } startTimeLabel . getStyleClass ( ) . setAll ( "start-time-label" , "default-style-entry-time-label" , calendar . getStyle ( ) + "-entry-time-label" ) ; titleLabel . getStyleClass ( ) . setAll ( "title-label" , "default-style-entry-title-label" , calendar . getStyle ( ) + "-entry-title-label" ) ; } | This methods updates the styles of the node according to the entry settings . |
26,289 | protected Label createTitleLabel ( ) { Label label = new Label ( ) ; label . setWrapText ( true ) ; label . setMinSize ( 0 , 0 ) ; return label ; } | The label used to show the title . |
26,290 | protected void updateLabels ( ) { Entry < ? > entry = getEntry ( ) ; startTimeLabel . setText ( formatTime ( entry . getStartTime ( ) ) ) ; titleLabel . setText ( formatTitle ( entry . getTitle ( ) ) ) ; } | This method will be called if the labels need to be updated . |
26,291 | static void rollToNextWeekStart ( DTBuilder builder , Weekday wkst ) { DateValue bd = builder . toDate ( ) ; builder . day += ( 7 - ( ( 7 + ( Weekday . valueOf ( bd ) . javaDayNum - wkst . javaDayNum ) ) % 7 ) ) % 7 ; builder . normalize ( ) ; } | advances builder to the earliest day on or after builder that falls on wkst . |
26,292 | static DateValue nextWeekStart ( DateValue d , Weekday wkst ) { DTBuilder builder = new DTBuilder ( d ) ; builder . day += ( 7 - ( ( 7 + ( Weekday . valueOf ( d ) . javaDayNum - wkst . javaDayNum ) ) % 7 ) ) % 7 ; return builder . toDate ( ) ; } | the earliest day on or after d that falls on wkst . |
26,293 | static int [ ] uniquify ( int [ ] ints , int start , int end ) { IntSet iset = new IntSet ( ) ; for ( int i = end ; -- i >= start ; ) { iset . add ( ints [ i ] ) ; } return iset . toIntArray ( ) ; } | returns a sorted unique copy of ints . |
26,294 | static int dayNumToDate ( Weekday dow0 , int nDays , int weekNum , Weekday dow , int d0 , int nDaysInMonth ) { int firstDateOfGivenDow = 1 + ( ( 7 + dow . javaDayNum - dow0 . javaDayNum ) % 7 ) ; int date ; if ( weekNum > 0 ) { date = ( ( weekNum - 1 ) * 7 ) + firstDateOfGivenDow - d0 ; } else { int lastDateOfGivenDow = firstDateOfGivenDow + ( 7 * 54 ) ; lastDateOfGivenDow -= 7 * ( ( lastDateOfGivenDow - nDays + 6 ) / 7 ) ; date = lastDateOfGivenDow + 7 * ( weekNum + 1 ) - d0 ; } if ( date <= 0 || date > nDaysInMonth ) { return 0 ; } return date ; } | given a weekday number such as - 1SU returns the day of the month that it falls on . The weekday number may be refer to a week in the current month in some contexts or a week in the current year in other contexts . |
26,295 | static int invertWeekdayNum ( WeekdayNum weekdayNum , Weekday dow0 , int nDays ) { assert weekdayNum . num < 0 ; return countInPeriod ( weekdayNum . wday , dow0 , nDays ) + weekdayNum . num + 1 ; } | Compute an absolute week number given a relative one . The day number - 1SU refers to the last Sunday so if there are 5 Sundays in a period that starts on dow0 with nDays then - 1SU is 5SU . Depending on where its used it may refer to the last Sunday of the year or of the month . |
26,296 | static int countInPeriod ( Weekday dow , Weekday dow0 , int nDays ) { if ( dow . javaDayNum >= dow0 . javaDayNum ) { return 1 + ( ( nDays - ( dow . javaDayNum - dow0 . javaDayNum ) - 1 ) / 7 ) ; } else { return 1 + ( ( nDays - ( 7 - ( dow0 . javaDayNum - dow . javaDayNum ) ) - 1 ) / 7 ) ; } } | the number of occurences of dow in a period nDays long where the first day of the period has day of week dow0 . |
26,297 | public List < Slice > getUnloadedSlices ( List < Slice > slices ) { List < Slice > unloadedSlices = new ArrayList < > ( slices ) ; unloadedSlices . removeAll ( loadedSlices ) ; unloadedSlices . removeAll ( inProgressSlices ) ; return unloadedSlices ; } | Takes the list of slices and removes those already loaded . |
26,298 | public static RecurrenceIterator createRecurrenceIterator ( String rdata , DateValue dtStart , TimeZone tzid , boolean strict ) throws ParseException { return createRecurrenceIterable ( rdata , dtStart , tzid , strict ) . iterator ( ) ; } | given a block of RRULE EXRULE RDATE and EXDATE content lines parse them into a single recurrence iterator . |
26,299 | public static RecurrenceIterator createRecurrenceIterator ( RDateList rdates ) { DateValue [ ] dates = rdates . getDatesUtc ( ) ; Arrays . sort ( dates ) ; int k = 0 ; for ( int i = 1 ; i < dates . length ; ++ i ) { if ( ! dates [ i ] . equals ( dates [ k ] ) ) { dates [ ++ k ] = dates [ i ] ; } } if ( ++ k < dates . length ) { DateValue [ ] uniqueDates = new DateValue [ k ] ; System . arraycopy ( dates , 0 , uniqueDates , 0 , k ) ; dates = uniqueDates ; } return new RDateIteratorImpl ( dates ) ; } | create a recurrence iterator from an rdate or exdate list . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.