max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
1,442
<filename>apps/graph/graph/root_graph_controller.h #ifndef GRAPH_ROOT_GRAPH_CONTROLLER_H #define GRAPH_ROOT_GRAPH_CONTROLLER_H #include "calculation_graph_controller.h" namespace Graph { class RootGraphController : public CalculationGraphController { public: RootGraphController(Escher::Responder * parentResponder, GraphView * graphView, BannerView * bannerView, Shared::InteractiveCurveViewRange * curveViewRange, Shared::CurveViewCursor * cursor); const char * title() override; TELEMETRY_ID("Root"); private: Poincare::Coordinate2D<double> computeNewPointOfInterest(double start, double max, Poincare::Context * context, double relativePrecision, double minimalStep, double maximalStep) override; // Prevent horizontal panning to preserve search interval float cursorRightMarginRatio() override { return 0.0f; } float cursorLeftMarginRatio() override { return 0.0f; } }; } #endif
273
4,262
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.builder.endpoint.dsl; import java.util.Map; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.annotation.Generated; import org.apache.camel.ExchangePattern; import org.apache.camel.LoggingLevel; import org.apache.camel.builder.EndpointConsumerBuilder; import org.apache.camel.builder.EndpointProducerBuilder; import org.apache.camel.builder.endpoint.AbstractEndpointBuilder; import org.apache.camel.spi.ExceptionHandler; import org.apache.camel.spi.PollingConsumerPollStrategy; /** * Store and retrieve Java objects from an SQL database using JOOQ. * * Generated by camel build tools - do NOT edit this file! */ @Generated("org.apache.camel.maven.packaging.EndpointDslMojo") public interface JooqEndpointBuilderFactory { /** * Builder for endpoint consumers for the JOOQ component. */ public interface JooqEndpointConsumerBuilder extends EndpointConsumerBuilder { default AdvancedJooqEndpointConsumerBuilder advanced() { return (AdvancedJooqEndpointConsumerBuilder) this; } /** * To use a specific database configuration. * * The option is a: &lt;code&gt;org.jooq.Configuration&lt;/code&gt; * type. * * Group: common * * @param databaseConfiguration the value to set * @return the dsl builder */ default JooqEndpointConsumerBuilder databaseConfiguration( Object databaseConfiguration) { doSetProperty("databaseConfiguration", databaseConfiguration); return this; } /** * To use a specific database configuration. * * The option will be converted to a * &lt;code&gt;org.jooq.Configuration&lt;/code&gt; type. * * Group: common * * @param databaseConfiguration the value to set * @return the dsl builder */ default JooqEndpointConsumerBuilder databaseConfiguration( String databaseConfiguration) { doSetProperty("databaseConfiguration", databaseConfiguration); return this; } /** * Allows for bridging the consumer to the Camel routing Error Handler, * which mean any exceptions occurred while the consumer is trying to * pickup incoming messages, or the likes, will now be processed as a * message and handled by the routing Error Handler. By default the * consumer will use the org.apache.camel.spi.ExceptionHandler to deal * with exceptions, that will be logged at WARN or ERROR level and * ignored. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: consumer * * @param bridgeErrorHandler the value to set * @return the dsl builder */ default JooqEndpointConsumerBuilder bridgeErrorHandler( boolean bridgeErrorHandler) { doSetProperty("bridgeErrorHandler", bridgeErrorHandler); return this; } /** * Allows for bridging the consumer to the Camel routing Error Handler, * which mean any exceptions occurred while the consumer is trying to * pickup incoming messages, or the likes, will now be processed as a * message and handled by the routing Error Handler. By default the * consumer will use the org.apache.camel.spi.ExceptionHandler to deal * with exceptions, that will be logged at WARN or ERROR level and * ignored. * * The option will be converted to a &lt;code&gt;boolean&lt;/code&gt; * type. * * Default: false * Group: consumer * * @param bridgeErrorHandler the value to set * @return the dsl builder */ default JooqEndpointConsumerBuilder bridgeErrorHandler( String bridgeErrorHandler) { doSetProperty("bridgeErrorHandler", bridgeErrorHandler); return this; } /** * Delete entity after it is consumed. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: consumer * * @param consumeDelete the value to set * @return the dsl builder */ default JooqEndpointConsumerBuilder consumeDelete(boolean consumeDelete) { doSetProperty("consumeDelete", consumeDelete); return this; } /** * Delete entity after it is consumed. * * The option will be converted to a &lt;code&gt;boolean&lt;/code&gt; * type. * * Default: true * Group: consumer * * @param consumeDelete the value to set * @return the dsl builder */ default JooqEndpointConsumerBuilder consumeDelete(String consumeDelete) { doSetProperty("consumeDelete", consumeDelete); return this; } /** * If the polling consumer did not poll any files, you can enable this * option to send an empty message (no body) instead. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: consumer * * @param sendEmptyMessageWhenIdle the value to set * @return the dsl builder */ default JooqEndpointConsumerBuilder sendEmptyMessageWhenIdle( boolean sendEmptyMessageWhenIdle) { doSetProperty("sendEmptyMessageWhenIdle", sendEmptyMessageWhenIdle); return this; } /** * If the polling consumer did not poll any files, you can enable this * option to send an empty message (no body) instead. * * The option will be converted to a &lt;code&gt;boolean&lt;/code&gt; * type. * * Default: false * Group: consumer * * @param sendEmptyMessageWhenIdle the value to set * @return the dsl builder */ default JooqEndpointConsumerBuilder sendEmptyMessageWhenIdle( String sendEmptyMessageWhenIdle) { doSetProperty("sendEmptyMessageWhenIdle", sendEmptyMessageWhenIdle); return this; } /** * The number of subsequent error polls (failed due some error) that * should happen before the backoffMultipler should kick-in. * * The option is a: &lt;code&gt;int&lt;/code&gt; type. * * Group: scheduler * * @param backoffErrorThreshold the value to set * @return the dsl builder */ default JooqEndpointConsumerBuilder backoffErrorThreshold( int backoffErrorThreshold) { doSetProperty("backoffErrorThreshold", backoffErrorThreshold); return this; } /** * The number of subsequent error polls (failed due some error) that * should happen before the backoffMultipler should kick-in. * * The option will be converted to a &lt;code&gt;int&lt;/code&gt; type. * * Group: scheduler * * @param backoffErrorThreshold the value to set * @return the dsl builder */ default JooqEndpointConsumerBuilder backoffErrorThreshold( String backoffErrorThreshold) { doSetProperty("backoffErrorThreshold", backoffErrorThreshold); return this; } /** * The number of subsequent idle polls that should happen before the * backoffMultipler should kick-in. * * The option is a: &lt;code&gt;int&lt;/code&gt; type. * * Group: scheduler * * @param backoffIdleThreshold the value to set * @return the dsl builder */ default JooqEndpointConsumerBuilder backoffIdleThreshold( int backoffIdleThreshold) { doSetProperty("backoffIdleThreshold", backoffIdleThreshold); return this; } /** * The number of subsequent idle polls that should happen before the * backoffMultipler should kick-in. * * The option will be converted to a &lt;code&gt;int&lt;/code&gt; type. * * Group: scheduler * * @param backoffIdleThreshold the value to set * @return the dsl builder */ default JooqEndpointConsumerBuilder backoffIdleThreshold( String backoffIdleThreshold) { doSetProperty("backoffIdleThreshold", backoffIdleThreshold); return this; } /** * To let the scheduled polling consumer backoff if there has been a * number of subsequent idles/errors in a row. The multiplier is then * the number of polls that will be skipped before the next actual * attempt is happening again. When this option is in use then * backoffIdleThreshold and/or backoffErrorThreshold must also be * configured. * * The option is a: &lt;code&gt;int&lt;/code&gt; type. * * Group: scheduler * * @param backoffMultiplier the value to set * @return the dsl builder */ default JooqEndpointConsumerBuilder backoffMultiplier( int backoffMultiplier) { doSetProperty("backoffMultiplier", backoffMultiplier); return this; } /** * To let the scheduled polling consumer backoff if there has been a * number of subsequent idles/errors in a row. The multiplier is then * the number of polls that will be skipped before the next actual * attempt is happening again. When this option is in use then * backoffIdleThreshold and/or backoffErrorThreshold must also be * configured. * * The option will be converted to a &lt;code&gt;int&lt;/code&gt; type. * * Group: scheduler * * @param backoffMultiplier the value to set * @return the dsl builder */ default JooqEndpointConsumerBuilder backoffMultiplier( String backoffMultiplier) { doSetProperty("backoffMultiplier", backoffMultiplier); return this; } /** * Milliseconds before the next poll. * * The option is a: &lt;code&gt;long&lt;/code&gt; type. * * Default: 500 * Group: scheduler * * @param delay the value to set * @return the dsl builder */ default JooqEndpointConsumerBuilder delay(long delay) { doSetProperty("delay", delay); return this; } /** * Milliseconds before the next poll. * * The option will be converted to a &lt;code&gt;long&lt;/code&gt; type. * * Default: 500 * Group: scheduler * * @param delay the value to set * @return the dsl builder */ default JooqEndpointConsumerBuilder delay(String delay) { doSetProperty("delay", delay); return this; } /** * If greedy is enabled, then the ScheduledPollConsumer will run * immediately again, if the previous run polled 1 or more messages. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: scheduler * * @param greedy the value to set * @return the dsl builder */ default JooqEndpointConsumerBuilder greedy(boolean greedy) { doSetProperty("greedy", greedy); return this; } /** * If greedy is enabled, then the ScheduledPollConsumer will run * immediately again, if the previous run polled 1 or more messages. * * The option will be converted to a &lt;code&gt;boolean&lt;/code&gt; * type. * * Default: false * Group: scheduler * * @param greedy the value to set * @return the dsl builder */ default JooqEndpointConsumerBuilder greedy(String greedy) { doSetProperty("greedy", greedy); return this; } /** * Milliseconds before the first poll starts. * * The option is a: &lt;code&gt;long&lt;/code&gt; type. * * Default: 1000 * Group: scheduler * * @param initialDelay the value to set * @return the dsl builder */ default JooqEndpointConsumerBuilder initialDelay(long initialDelay) { doSetProperty("initialDelay", initialDelay); return this; } /** * Milliseconds before the first poll starts. * * The option will be converted to a &lt;code&gt;long&lt;/code&gt; type. * * Default: 1000 * Group: scheduler * * @param initialDelay the value to set * @return the dsl builder */ default JooqEndpointConsumerBuilder initialDelay(String initialDelay) { doSetProperty("initialDelay", initialDelay); return this; } /** * Specifies a maximum limit of number of fires. So if you set it to 1, * the scheduler will only fire once. If you set it to 5, it will only * fire five times. A value of zero or negative means fire forever. * * The option is a: &lt;code&gt;long&lt;/code&gt; type. * * Default: 0 * Group: scheduler * * @param repeatCount the value to set * @return the dsl builder */ default JooqEndpointConsumerBuilder repeatCount(long repeatCount) { doSetProperty("repeatCount", repeatCount); return this; } /** * Specifies a maximum limit of number of fires. So if you set it to 1, * the scheduler will only fire once. If you set it to 5, it will only * fire five times. A value of zero or negative means fire forever. * * The option will be converted to a &lt;code&gt;long&lt;/code&gt; type. * * Default: 0 * Group: scheduler * * @param repeatCount the value to set * @return the dsl builder */ default JooqEndpointConsumerBuilder repeatCount(String repeatCount) { doSetProperty("repeatCount", repeatCount); return this; } /** * The consumer logs a start/complete log line when it polls. This * option allows you to configure the logging level for that. * * The option is a: * &lt;code&gt;org.apache.camel.LoggingLevel&lt;/code&gt; type. * * Default: TRACE * Group: scheduler * * @param runLoggingLevel the value to set * @return the dsl builder */ default JooqEndpointConsumerBuilder runLoggingLevel( LoggingLevel runLoggingLevel) { doSetProperty("runLoggingLevel", runLoggingLevel); return this; } /** * The consumer logs a start/complete log line when it polls. This * option allows you to configure the logging level for that. * * The option will be converted to a * &lt;code&gt;org.apache.camel.LoggingLevel&lt;/code&gt; type. * * Default: TRACE * Group: scheduler * * @param runLoggingLevel the value to set * @return the dsl builder */ default JooqEndpointConsumerBuilder runLoggingLevel( String runLoggingLevel) { doSetProperty("runLoggingLevel", runLoggingLevel); return this; } /** * Allows for configuring a custom/shared thread pool to use for the * consumer. By default each consumer has its own single threaded thread * pool. * * The option is a: * &lt;code&gt;java.util.concurrent.ScheduledExecutorService&lt;/code&gt; type. * * Group: scheduler * * @param scheduledExecutorService the value to set * @return the dsl builder */ default JooqEndpointConsumerBuilder scheduledExecutorService( ScheduledExecutorService scheduledExecutorService) { doSetProperty("scheduledExecutorService", scheduledExecutorService); return this; } /** * Allows for configuring a custom/shared thread pool to use for the * consumer. By default each consumer has its own single threaded thread * pool. * * The option will be converted to a * &lt;code&gt;java.util.concurrent.ScheduledExecutorService&lt;/code&gt; type. * * Group: scheduler * * @param scheduledExecutorService the value to set * @return the dsl builder */ default JooqEndpointConsumerBuilder scheduledExecutorService( String scheduledExecutorService) { doSetProperty("scheduledExecutorService", scheduledExecutorService); return this; } /** * To use a cron scheduler from either camel-spring or camel-quartz * component. Use value spring or quartz for built in scheduler. * * The option is a: &lt;code&gt;java.lang.Object&lt;/code&gt; type. * * Default: none * Group: scheduler * * @param scheduler the value to set * @return the dsl builder */ default JooqEndpointConsumerBuilder scheduler(Object scheduler) { doSetProperty("scheduler", scheduler); return this; } /** * To use a cron scheduler from either camel-spring or camel-quartz * component. Use value spring or quartz for built in scheduler. * * The option will be converted to a * &lt;code&gt;java.lang.Object&lt;/code&gt; type. * * Default: none * Group: scheduler * * @param scheduler the value to set * @return the dsl builder */ default JooqEndpointConsumerBuilder scheduler(String scheduler) { doSetProperty("scheduler", scheduler); return this; } /** * To configure additional properties when using a custom scheduler or * any of the Quartz, Spring based scheduler. * * The option is a: &lt;code&gt;java.util.Map&amp;lt;java.lang.String, * java.lang.Object&amp;gt;&lt;/code&gt; type. * The option is multivalued, and you can use the * schedulerProperties(String, Object) method to add a value (call the * method multiple times to set more values). * * Group: scheduler * * @param key the option key * @param value the option value * @return the dsl builder */ default JooqEndpointConsumerBuilder schedulerProperties( String key, Object value) { doSetMultiValueProperty("schedulerProperties", "scheduler." + key, value); return this; } /** * To configure additional properties when using a custom scheduler or * any of the Quartz, Spring based scheduler. * * The option is a: &lt;code&gt;java.util.Map&amp;lt;java.lang.String, * java.lang.Object&amp;gt;&lt;/code&gt; type. * The option is multivalued, and you can use the * schedulerProperties(String, Object) method to add a value (call the * method multiple times to set more values). * * Group: scheduler * * @param values the values * @return the dsl builder */ default JooqEndpointConsumerBuilder schedulerProperties(Map values) { doSetMultiValueProperties("schedulerProperties", "scheduler.", values); return this; } /** * Whether the scheduler should be auto started. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: scheduler * * @param startScheduler the value to set * @return the dsl builder */ default JooqEndpointConsumerBuilder startScheduler( boolean startScheduler) { doSetProperty("startScheduler", startScheduler); return this; } /** * Whether the scheduler should be auto started. * * The option will be converted to a &lt;code&gt;boolean&lt;/code&gt; * type. * * Default: true * Group: scheduler * * @param startScheduler the value to set * @return the dsl builder */ default JooqEndpointConsumerBuilder startScheduler(String startScheduler) { doSetProperty("startScheduler", startScheduler); return this; } /** * Time unit for initialDelay and delay options. * * The option is a: * &lt;code&gt;java.util.concurrent.TimeUnit&lt;/code&gt; type. * * Default: MILLISECONDS * Group: scheduler * * @param timeUnit the value to set * @return the dsl builder */ default JooqEndpointConsumerBuilder timeUnit(TimeUnit timeUnit) { doSetProperty("timeUnit", timeUnit); return this; } /** * Time unit for initialDelay and delay options. * * The option will be converted to a * &lt;code&gt;java.util.concurrent.TimeUnit&lt;/code&gt; type. * * Default: MILLISECONDS * Group: scheduler * * @param timeUnit the value to set * @return the dsl builder */ default JooqEndpointConsumerBuilder timeUnit(String timeUnit) { doSetProperty("timeUnit", timeUnit); return this; } /** * Controls if fixed delay or fixed rate is used. See * ScheduledExecutorService in JDK for details. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: scheduler * * @param useFixedDelay the value to set * @return the dsl builder */ default JooqEndpointConsumerBuilder useFixedDelay(boolean useFixedDelay) { doSetProperty("useFixedDelay", useFixedDelay); return this; } /** * Controls if fixed delay or fixed rate is used. See * ScheduledExecutorService in JDK for details. * * The option will be converted to a &lt;code&gt;boolean&lt;/code&gt; * type. * * Default: true * Group: scheduler * * @param useFixedDelay the value to set * @return the dsl builder */ default JooqEndpointConsumerBuilder useFixedDelay(String useFixedDelay) { doSetProperty("useFixedDelay", useFixedDelay); return this; } } /** * Advanced builder for endpoint consumers for the JOOQ component. */ public interface AdvancedJooqEndpointConsumerBuilder extends EndpointConsumerBuilder { default JooqEndpointConsumerBuilder basic() { return (JooqEndpointConsumerBuilder) this; } /** * To let the consumer use a custom ExceptionHandler. Notice if the * option bridgeErrorHandler is enabled then this option is not in use. * By default the consumer will deal with exceptions, that will be * logged at WARN or ERROR level and ignored. * * The option is a: * &lt;code&gt;org.apache.camel.spi.ExceptionHandler&lt;/code&gt; type. * * Group: consumer (advanced) * * @param exceptionHandler the value to set * @return the dsl builder */ default AdvancedJooqEndpointConsumerBuilder exceptionHandler( ExceptionHandler exceptionHandler) { doSetProperty("exceptionHandler", exceptionHandler); return this; } /** * To let the consumer use a custom ExceptionHandler. Notice if the * option bridgeErrorHandler is enabled then this option is not in use. * By default the consumer will deal with exceptions, that will be * logged at WARN or ERROR level and ignored. * * The option will be converted to a * &lt;code&gt;org.apache.camel.spi.ExceptionHandler&lt;/code&gt; type. * * Group: consumer (advanced) * * @param exceptionHandler the value to set * @return the dsl builder */ default AdvancedJooqEndpointConsumerBuilder exceptionHandler( String exceptionHandler) { doSetProperty("exceptionHandler", exceptionHandler); return this; } /** * Sets the exchange pattern when the consumer creates an exchange. * * The option is a: * &lt;code&gt;org.apache.camel.ExchangePattern&lt;/code&gt; type. * * Group: consumer (advanced) * * @param exchangePattern the value to set * @return the dsl builder */ default AdvancedJooqEndpointConsumerBuilder exchangePattern( ExchangePattern exchangePattern) { doSetProperty("exchangePattern", exchangePattern); return this; } /** * Sets the exchange pattern when the consumer creates an exchange. * * The option will be converted to a * &lt;code&gt;org.apache.camel.ExchangePattern&lt;/code&gt; type. * * Group: consumer (advanced) * * @param exchangePattern the value to set * @return the dsl builder */ default AdvancedJooqEndpointConsumerBuilder exchangePattern( String exchangePattern) { doSetProperty("exchangePattern", exchangePattern); return this; } /** * A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing * you to provide your custom implementation to control error handling * usually occurred during the poll operation before an Exchange have * been created and being routed in Camel. * * The option is a: * &lt;code&gt;org.apache.camel.spi.PollingConsumerPollStrategy&lt;/code&gt; type. * * Group: consumer (advanced) * * @param pollStrategy the value to set * @return the dsl builder */ default AdvancedJooqEndpointConsumerBuilder pollStrategy( PollingConsumerPollStrategy pollStrategy) { doSetProperty("pollStrategy", pollStrategy); return this; } /** * A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing * you to provide your custom implementation to control error handling * usually occurred during the poll operation before an Exchange have * been created and being routed in Camel. * * The option will be converted to a * &lt;code&gt;org.apache.camel.spi.PollingConsumerPollStrategy&lt;/code&gt; type. * * Group: consumer (advanced) * * @param pollStrategy the value to set * @return the dsl builder */ default AdvancedJooqEndpointConsumerBuilder pollStrategy( String pollStrategy) { doSetProperty("pollStrategy", pollStrategy); return this; } } /** * Builder for endpoint producers for the JOOQ component. */ public interface JooqEndpointProducerBuilder extends EndpointProducerBuilder { default AdvancedJooqEndpointProducerBuilder advanced() { return (AdvancedJooqEndpointProducerBuilder) this; } /** * To use a specific database configuration. * * The option is a: &lt;code&gt;org.jooq.Configuration&lt;/code&gt; * type. * * Group: common * * @param databaseConfiguration the value to set * @return the dsl builder */ default JooqEndpointProducerBuilder databaseConfiguration( Object databaseConfiguration) { doSetProperty("databaseConfiguration", databaseConfiguration); return this; } /** * To use a specific database configuration. * * The option will be converted to a * &lt;code&gt;org.jooq.Configuration&lt;/code&gt; type. * * Group: common * * @param databaseConfiguration the value to set * @return the dsl builder */ default JooqEndpointProducerBuilder databaseConfiguration( String databaseConfiguration) { doSetProperty("databaseConfiguration", databaseConfiguration); return this; } /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: producer * * @param lazyStartProducer the value to set * @return the dsl builder */ default JooqEndpointProducerBuilder lazyStartProducer( boolean lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option will be converted to a &lt;code&gt;boolean&lt;/code&gt; * type. * * Default: false * Group: producer * * @param lazyStartProducer the value to set * @return the dsl builder */ default JooqEndpointProducerBuilder lazyStartProducer( String lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * Type of operation to execute on query. * * The option is a: * &lt;code&gt;org.apache.camel.component.jooq.JooqOperation&lt;/code&gt; type. * * Default: NONE * Group: producer * * @param operation the value to set * @return the dsl builder */ default JooqEndpointProducerBuilder operation(JooqOperation operation) { doSetProperty("operation", operation); return this; } /** * Type of operation to execute on query. * * The option will be converted to a * &lt;code&gt;org.apache.camel.component.jooq.JooqOperation&lt;/code&gt; type. * * Default: NONE * Group: producer * * @param operation the value to set * @return the dsl builder */ default JooqEndpointProducerBuilder operation(String operation) { doSetProperty("operation", operation); return this; } /** * To execute plain SQL query. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer * * @param query the value to set * @return the dsl builder */ default JooqEndpointProducerBuilder query(String query) { doSetProperty("query", query); return this; } } /** * Advanced builder for endpoint producers for the JOOQ component. */ public interface AdvancedJooqEndpointProducerBuilder extends EndpointProducerBuilder { default JooqEndpointProducerBuilder basic() { return (JooqEndpointProducerBuilder) this; } } /** * Builder for endpoint for the JOOQ component. */ public interface JooqEndpointBuilder extends JooqEndpointConsumerBuilder, JooqEndpointProducerBuilder { default AdvancedJooqEndpointBuilder advanced() { return (AdvancedJooqEndpointBuilder) this; } /** * To use a specific database configuration. * * The option is a: &lt;code&gt;org.jooq.Configuration&lt;/code&gt; * type. * * Group: common * * @param databaseConfiguration the value to set * @return the dsl builder */ default JooqEndpointBuilder databaseConfiguration( Object databaseConfiguration) { doSetProperty("databaseConfiguration", databaseConfiguration); return this; } /** * To use a specific database configuration. * * The option will be converted to a * &lt;code&gt;org.jooq.Configuration&lt;/code&gt; type. * * Group: common * * @param databaseConfiguration the value to set * @return the dsl builder */ default JooqEndpointBuilder databaseConfiguration( String databaseConfiguration) { doSetProperty("databaseConfiguration", databaseConfiguration); return this; } } /** * Advanced builder for endpoint for the JOOQ component. */ public interface AdvancedJooqEndpointBuilder extends AdvancedJooqEndpointConsumerBuilder, AdvancedJooqEndpointProducerBuilder { default JooqEndpointBuilder basic() { return (JooqEndpointBuilder) this; } } /** * Proxy enum for <code>org.apache.camel.component.jooq.JooqOperation</code> * enum. */ enum JooqOperation { EXECUTE, FETCH, NONE; } public interface JooqBuilders { /** * JOOQ (camel-jooq) * Store and retrieve Java objects from an SQL database using JOOQ. * * Category: database,sql * Since: 3.0 * Maven coordinates: org.apache.camel:camel-jooq * * Syntax: <code>jooq:entityType</code> * * Path parameter: entityType * JOOQ entity class * * @param path entityType * @return the dsl builder */ default JooqEndpointBuilder jooq(String path) { return JooqEndpointBuilderFactory.endpointBuilder("jooq", path); } /** * JOOQ (camel-jooq) * Store and retrieve Java objects from an SQL database using JOOQ. * * Category: database,sql * Since: 3.0 * Maven coordinates: org.apache.camel:camel-jooq * * Syntax: <code>jooq:entityType</code> * * Path parameter: entityType * JOOQ entity class * * @param componentName to use a custom component name for the endpoint * instead of the default name * @param path entityType * @return the dsl builder */ default JooqEndpointBuilder jooq(String componentName, String path) { return JooqEndpointBuilderFactory.endpointBuilder(componentName, path); } } static JooqEndpointBuilder endpointBuilder(String componentName, String path) { class JooqEndpointBuilderImpl extends AbstractEndpointBuilder implements JooqEndpointBuilder, AdvancedJooqEndpointBuilder { public JooqEndpointBuilderImpl(String path) { super(componentName, path); } } return new JooqEndpointBuilderImpl(path); } }
17,221
1,056
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.form; import org.openide.nodes.Node; /** * * @author <NAME> */ public abstract class CodeGenerator { /** * initializes a CodeGenerator for a given FormModel * @param formModel a FormModel object */ public abstract void initialize(FormModel formModel); /** * Alows the code generator to provide synthetic properties for specified * component which are specific to the code generation method. E.g. a * JavaCodeGenerator will return variableName property, as it generates * global Java variable for every component * @param component The RADComponent for which the properties are to be * obtained * @return synthetic properties for the given component. */ public Node.Property[] getSyntheticProperties(RADComponent component) { return new Node.Property[0]; } public abstract void regenerateCode(); /** * Generates the specified event handler, if it does not exist yet. * @param handlerName The name of the event handler * @param paramTypes the list of event handler parameter types * @param bodyText the body text of the event handler or null for default *(empty) one * @return true if the event handler have not existed yet and was creaated, * false otherwise */ // public abstract boolean generateEventHandler(String handlerName, // String[] paramTypes, // String[] exceptTypes, // String bodyText); /** * Changes the text of the specified event handler, if it already exists. * @param handlerName The name of the event handler * @param paramTypes the list of event handler parameter types * @param bodyText the new body text of the event handler or null for default *(empty) one * @return true if the event handler existed and was modified, false * otherwise */ // public abstract boolean changeEventHandler(final String handlerName, // final String[] paramTypes, // final String[] exceptTypes, // final String bodyText); /** * Removes the specified event handler - removes the whole method together * with the user code! * @param handlerName The name of the event handler */ // public abstract boolean deleteEventHandler(String handlerName); /** * Renames the specified event handler to the given new name. * @param oldHandlerName The old name of the event handler * @param newHandlerName The new name of the event handler * @param paramTypes the list of event handler parameter types */ // public abstract boolean renameEventHandler(String oldHandlerName, // String newHandlerName, // String[] exceptTypes, // String[] paramTypes); /** * Gets the body (text) of event handler of given name. * @param handlerName name of the event handler * @return text of the event handler body */ // public abstract String getEventHandlerText(String handlerName); /** Focuses the specified event handler in the editor. */ // public abstract void gotoEventHandler(String handlerName); /** * Returns whether the specified event handler is empty (with no user * code). Empty handlers can be deleted without user confirmation. * @return true if the event handler exists and is empty */ // public boolean isEventHandlerEmpty(String handlerName) { // return false; // } }
1,627
1,338
<filename>src/bin/debug/profile/Thread.h /* * Copyright 2008-2010, <NAME>, <EMAIL>. * Distributed under the terms of the MIT License. */ #ifndef THREAD_H #define THREAD_H #include <String.h> #include <util/DoublyLinkedList.h> #include "ProfiledEntity.h" #include "ProfileResult.h" class Image; class Team; class ThreadImage : public DoublyLinkedListLinkImpl<ThreadImage> { public: ThreadImage(Image* image, ImageProfileResult* result); ~ThreadImage(); Image* GetImage() const { return fImage; } ImageProfileResult* Result() const { return fResult; } private: Image* fImage; ImageProfileResult* fResult; }; class Thread : public ProfiledEntity, public DoublyLinkedListLinkImpl<Thread>, private ImageProfileResultContainer { public: Thread(thread_id threadID, const char* name, Team* team); virtual ~Thread(); inline thread_id ID() const; inline const char* Name() const; inline addr_t* Samples() const; inline Team* GetTeam() const; virtual int32 EntityID() const; virtual const char* EntityName() const; virtual const char* EntityType() const; inline ProfileResult* GetProfileResult() const; void SetProfileResult(ProfileResult* result); void UpdateInfo(const char* name); void SetSampleArea(area_id area, addr_t* samples); void SetInterval(bigtime_t interval); void SetLazyImages(bool lazy); status_t AddImage(Image* image); void RemoveImage(Image* image); void AddSamples(int32 count, int32 dropped, int32 stackDepth, bool variableStackDepth, int32 event); void AddSamples(addr_t* samples, int32 sampleCount); void PrintResults(); private: typedef DoublyLinkedList<ThreadImage> ImageList; private: // ImageProfileResultContainer virtual int32 CountImages() const; virtual ImageProfileResult* VisitImages(Visitor& visitor) const; virtual ImageProfileResult* FindImage(addr_t address, addr_t& _loadDelta) const; private: void _SynchronizeImages(int32 event); private: thread_id fID; BString fName; ::Team* fTeam; area_id fSampleArea; addr_t* fSamples; ProfileResult* fProfileResult; ImageList fImages; ImageList fNewImages; ImageList fOldImages; bool fLazyImages; }; thread_id Thread::ID() const { return fID; } const char* Thread::Name() const { return fName.String(); } addr_t* Thread::Samples() const { return fSamples; } Team* Thread::GetTeam() const { return fTeam; } ProfileResult* Thread::GetProfileResult() const { return fProfileResult; } #endif // THREAD_H
1,065
1,109
package org.cboard.dto; import org.springframework.security.core.GrantedAuthority; import java.util.Collection; /** * Created by yfyuan on 2016/9/29. */ public class User extends org.springframework.security.core.userdetails.User { private String userId; private String company; private String department; private String name; public User(String username, String password, Collection<? extends GrantedAuthority> authorities) { super(username, password, authorities); } public User(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities) { super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCompany() { return company; } public void setCompany(String company) { this.company = company; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } }
474
4,054
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.application.container.docprocs; import com.google.common.util.concurrent.ListenableFuture; import com.yahoo.docproc.DocumentProcessor; import com.yahoo.docproc.Processing; import com.yahoo.document.Document; import com.yahoo.document.DocumentOperation; import com.yahoo.document.DocumentPut; import com.yahoo.documentapi.messagebus.protocol.DocumentMessage; import com.yahoo.documentapi.messagebus.protocol.PutDocumentMessage; import com.yahoo.jdisc.Request; import com.yahoo.jdisc.Response; import com.yahoo.jdisc.handler.RequestDispatch; import com.yahoo.jdisc.service.CurrentContainer; import com.yahoo.messagebus.jdisc.MbusRequest; import com.yahoo.messagebus.routing.Route; import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; /** * @author <NAME> */ public class MockDispatchDocproc extends DocumentProcessor { private final Route route; private final URI uri; private final CurrentContainer currentContainer; private final List<Response> responses = new ArrayList<>(); public MockDispatchDocproc(CurrentContainer currentContainer) { this.route = Route.parse("default"); this.uri = URI.create("mbus://remotehost/source"); this.currentContainer = currentContainer; } @Override public Progress process(Processing processing) { for (DocumentOperation op : processing.getDocumentOperations()) { PutDocumentMessage message = new PutDocumentMessage((DocumentPut)op); ListenableFuture<Response> future = createRequest(message).dispatch(); try { responses.add(future.get()); } catch (ExecutionException | InterruptedException e) { throw new RuntimeException(e); } } return Progress.DONE; } private RequestDispatch createRequest(final DocumentMessage message) { return new RequestDispatch() { @Override protected Request newRequest() { return new MbusRequest(currentContainer, uri, message.setRoute(route), false); } }; } public List<Response> getResponses() { return responses; } }
803
5,317
package ysoserial.test.payloads; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.Serializable; import java.util.Random; import java.util.concurrent.Callable; import fi.iki.elonen.NanoHTTPD; import fi.iki.elonen.NanoHTTPD.Response.Status; import javassist.ClassClassPath; import javassist.ClassPool; import javassist.CtClass; import ysoserial.test.WrappedTest; /** * @author mbechler * */ public class RemoteClassLoadingTest implements WrappedTest { int port; private String command; private String className; public RemoteClassLoadingTest ( String command ) { this.command = command; this.port = new Random().nextInt(65535-1024)+1024; this.className = "Exploit-" + System.currentTimeMillis(); } public String getPayloadArgs () { return String.format("http://localhost:%d/", this.port) + ":" + this.className; } public int getHTTPPort () { return this.port; } public Callable<Object> createCallable ( Callable<Object> innerCallable ) { return new RemoteClassLoadingTestCallable(this.port, makePayloadClass(), innerCallable); } public String getExploitClassName () { return this.className; } protected byte[] makePayloadClass () { try { ClassPool pool = ClassPool.getDefault(); pool.insertClassPath(new ClassClassPath(Exploit.class)); final CtClass clazz = pool.get(Exploit.class.getName()); clazz.setName(this.className); clazz.makeClassInitializer().insertAfter("java.lang.Runtime.getRuntime().exec(\"" + command.replaceAll("\"", "\\\"") + "\");"); return clazz.toBytecode(); } catch ( Exception e ) { e.printStackTrace(); return new byte[0]; } } static class RemoteClassLoadingTestCallable extends NanoHTTPD implements Callable<Object> { private Callable<Object> innerCallable; private byte[] data; private Object waitLock = new Object(); public RemoteClassLoadingTestCallable ( int port, byte[] data, Callable<Object> innerCallable ) { super(port); this.data = data; this.innerCallable = innerCallable; } public void waitFor() throws InterruptedException { synchronized ( this.waitLock ) { this.waitLock.wait(1000); } } public Object call () throws Exception { try { setup(); Object res = this.innerCallable.call(); waitFor(); Thread.sleep(1000); return res; } finally { cleanup(); } } private void setup () throws IOException { start(NanoHTTPD.SOCKET_READ_TIMEOUT, false); } private void cleanup () { stop(); } @Override public Response serve ( IHTTPSession sess ) { System.out.println("Serving " + sess.getUri()); Response response = newFixedLengthResponse(Status.OK, "application/octet-stream", new ByteArrayInputStream(data), data.length); synchronized ( this.waitLock ) { this.waitLock.notify(); } return response; } } public static class Exploit implements Serializable { private static final long serialVersionUID = 1L; } }
1,501
335
/* * FileDialog.cpp * -------------- * Purpose: File and folder selection dialogs implementation. * Notes : (currently none) * Authors: <NAME> * The OpenMPT source code is released under the BSD license. Read LICENSE for more details. */ #include "stdafx.h" #include "FileDialog.h" #include "Mainfrm.h" #include "InputHandler.h" OPENMPT_NAMESPACE_BEGIN class CFileDialogEx : public CFileDialog { public: CFileDialogEx(bool bOpenFileDialog, LPCTSTR lpszDefExt, LPCTSTR lpszFileName, DWORD dwFlags, LPCTSTR lpszFilter, CWnd *pParentWnd, DWORD dwSize, BOOL bVistaStyle, bool preview) : CFileDialog(bOpenFileDialog ? TRUE : FALSE, lpszDefExt, lpszFileName, dwFlags, lpszFilter, pParentWnd, dwSize, bVistaStyle) , m_fileNameBuf(65536) , doPreview(preview) , played(false) { // MFC's filename buffer is way too small for multi-selections of a large number of files. _tcsncpy(m_fileNameBuf.data(), lpszFileName, m_fileNameBuf.size()); m_fileNameBuf.back() = '\0'; m_ofn.lpstrFile = m_fileNameBuf.data(); m_ofn.nMaxFile = mpt::saturate_cast<DWORD>(m_fileNameBuf.size()); } ~CFileDialogEx() { if(played) { CMainFrame::GetMainFrame()->StopPreview(); } } #if NTDDI_VERSION >= NTDDI_VISTA // MFC's AddPlace() is declared as throw() but can in fact throw if any of the COM calls fail, e.g. because the place does not exist. // Avoid this by re-implementing our own version which doesn't throw. void AddPlace(const mpt::PathString &path) { if(m_bVistaStyle && path.IsDirectory()) { CComPtr<IShellItem> shellItem; HRESULT hr = SHCreateItemFromParsingName(path.ToWide().c_str(), nullptr, IID_IShellItem, reinterpret_cast<void **>(&shellItem)); if(SUCCEEDED(hr)) { static_cast<IFileDialog*>(m_pIFileDialog)->AddPlace(shellItem, FDAP_TOP); } } } #endif protected: std::vector<TCHAR> m_fileNameBuf; CString oldName; bool doPreview, played; void OnFileNameChange() override { if(doPreview) { CString name = GetPathName(); if(!name.IsEmpty() && name != oldName) { oldName = name; if(CMainFrame::GetMainFrame()->PlaySoundFile(mpt::PathString::FromCString(name), NOTE_MIDDLEC)) { played = true; } } } CFileDialog::OnFileNameChange(); } }; // Display the file dialog. bool FileDialog::Show(CWnd *parent) { m_filenames.clear(); // First, set up the dialog... CFileDialogEx dlg(m_load, m_defaultExtension.empty() ? nullptr : m_defaultExtension.c_str(), m_defaultFilename.c_str(), OFN_EXPLORER | OFN_NOCHANGEDIR | OFN_HIDEREADONLY | OFN_ENABLESIZING | OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | (m_multiSelect ? OFN_ALLOWMULTISELECT : 0) | (m_load ? 0 : (OFN_OVERWRITEPROMPT | OFN_NOREADONLYRETURN)), m_extFilter.c_str(), parent != nullptr ? parent : CMainFrame::GetMainFrame(), 0, (mpt::OS::Windows::IsWine() || mpt::OS::Windows::Version::Current().IsBefore(mpt::OS::Windows::Version::WinVista)) ? FALSE : TRUE, m_preview && TrackerSettings::Instance().previewInFileDialogs); OPENFILENAME &ofn = dlg.GetOFN(); ofn.nFilterIndex = m_filterIndex != nullptr ? *m_filterIndex : 0; if(!m_workingDirectory.empty()) { ofn.lpstrInitialDir = m_workingDirectory.c_str(); } #if NTDDI_VERSION >= NTDDI_VISTA const auto places = { &TrackerSettings::Instance().PathPluginPresets, &TrackerSettings::Instance().PathPlugins, &TrackerSettings::Instance().PathSamples, &TrackerSettings::Instance().PathInstruments, &TrackerSettings::Instance().PathSongs, }; for(const auto place : places) { dlg.AddPlace(place->GetDefaultDir()); } for(const auto &place : m_places) { dlg.AddPlace(place); } #endif // Do it! BypassInputHandler bih; if(dlg.DoModal() != IDOK) { return false; } // Retrieve variables if(m_filterIndex != nullptr) *m_filterIndex = ofn.nFilterIndex; if(m_multiSelect) { #if NTDDI_VERSION >= NTDDI_VISTA // Multiple files might have been selected if(CComPtr<IShellItemArray> shellItems = dlg.GetResults(); shellItems != nullptr) { // Using the old-style GetNextPathName doesn't work properly when the user performs a search and selects files from different folders. // Hence we use that only as a fallback. DWORD numItems = 0; shellItems->GetCount(&numItems); for(DWORD i = 0; i < numItems; i++) { CComPtr<IShellItem> shellItem; shellItems->GetItemAt(i, &shellItem); LPWSTR filePath = nullptr; if(HRESULT hr = shellItem->GetDisplayName(SIGDN_FILESYSPATH, &filePath); SUCCEEDED(hr)) { m_filenames.push_back(mpt::PathString::FromWide(filePath)); ::CoTaskMemFree(filePath); } } } else #endif { POSITION pos = dlg.GetStartPosition(); while(pos != nullptr) { m_filenames.push_back(mpt::PathString::FromCString(dlg.GetNextPathName(pos))); } } } else { // Only one file m_filenames.push_back(mpt::PathString::FromCString(dlg.GetPathName())); } if(m_filenames.empty()) { return false; } m_workingDirectory = m_filenames.front().AsNative().substr(0, ofn.nFileOffset); m_extension = m_filenames.front().AsNative().substr(ofn.nFileExtension); return true; } // Helper callback to set start path. int CALLBACK BrowseForFolder::BrowseCallbackProc(HWND hwnd, UINT uMsg, LPARAM /*lParam*/, LPARAM lpData) { if(uMsg == BFFM_INITIALIZED && lpData != NULL) { const BrowseForFolder *that = reinterpret_cast<BrowseForFolder *>(lpData); SendMessage(hwnd, BFFM_SETSELECTION, TRUE, reinterpret_cast<LPARAM>(that->m_workingDirectory.AsNative().c_str())); } return 0; } // Display the folder dialog. bool BrowseForFolder::Show(CWnd *parent) { // Note: MFC's CFolderPickerDialog won't work on pre-Vista systems, as it tries to use OPENFILENAME. BypassInputHandler bih; TCHAR path[MAX_PATH]; BROWSEINFO bi; MemsetZero(bi); bi.hwndOwner = (parent != nullptr ? parent : theApp.m_pMainWnd)->m_hWnd; if(!m_caption.IsEmpty()) bi.lpszTitle = m_caption; bi.pszDisplayName = path; bi.ulFlags = BIF_RETURNONLYFSDIRS | BIF_USENEWUI; bi.lpfn = BrowseCallbackProc; bi.lParam = reinterpret_cast<LPARAM>(this); LPITEMIDLIST pid = SHBrowseForFolder(&bi); bool success = pid != nullptr && SHGetPathFromIDList(pid, path); CoTaskMemFree(pid); if(success) { m_workingDirectory = mpt::PathString::FromNative(path); } return success; } OPENMPT_NAMESPACE_END
2,551
6,989
<filename>venv/lib/python3.9/site-packages/configparser.py #!/usr/bin/env python # -*- coding: utf-8 -*- """Convenience module importing everything from backports.configparser.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from backports.configparser import ( RawConfigParser, ConfigParser, SafeConfigParser, SectionProxy, Interpolation, BasicInterpolation, ExtendedInterpolation, LegacyInterpolation, NoSectionError, DuplicateSectionError, DuplicateOptionError, NoOptionError, InterpolationError, InterpolationMissingOptionError, InterpolationSyntaxError, InterpolationDepthError, ParsingError, MissingSectionHeaderError, ConverterMapping, DEFAULTSECT, MAX_INTERPOLATION_DEPTH, ) from backports.configparser import Error, _UNSET, _default_dict, _ChainMap # noqa: F401 __all__ = [ "NoSectionError", "DuplicateOptionError", "DuplicateSectionError", "NoOptionError", "InterpolationError", "InterpolationDepthError", "InterpolationMissingOptionError", "InterpolationSyntaxError", "ParsingError", "MissingSectionHeaderError", "ConfigParser", "SafeConfigParser", "RawConfigParser", "Interpolation", "BasicInterpolation", "ExtendedInterpolation", "LegacyInterpolation", "SectionProxy", "ConverterMapping", "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH", ] # NOTE: names missing from __all__ imported anyway for backwards compatibility.
570
784
<gh_stars>100-1000 package jforgame.server.net.mina; import java.net.InetSocketAddress; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import jforgame.server.ServerScanPaths; import jforgame.server.net.MessageDispatcher; import jforgame.server.net.mina.filter.FloodFilter; import jforgame.server.net.mina.filter.MessageTraceFilter; import jforgame.server.net.mina.filter.ModuleEntranceFilter; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.buffer.SimpleBufferAllocator; import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder; import org.apache.mina.core.service.SimpleIoProcessorPool; import org.apache.mina.filter.codec.ProtocolCodecFilter; import org.apache.mina.transport.socket.DefaultSocketSessionConfig; import org.apache.mina.transport.socket.SocketAcceptor; import org.apache.mina.transport.socket.SocketSessionConfig; import org.apache.mina.transport.socket.nio.NioProcessor; import org.apache.mina.transport.socket.nio.NioSession; import org.apache.mina.transport.socket.nio.NioSocketAcceptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jforgame.server.ServerConfig; import jforgame.socket.ServerNode; import jforgame.socket.codec.SerializerHelper; import jforgame.socket.mina.ServerSocketIoHandler; public class MinaSocketServer implements ServerNode { private Logger logger = LoggerFactory.getLogger(MinaSocketServer.class); private static final int CPU_CORE_SIZE = Runtime.getRuntime().availableProcessors(); private static final Executor executor = Executors.newCachedThreadPool(); private static final SimpleIoProcessorPool<NioSession> pool = new SimpleIoProcessorPool<NioSession>(NioProcessor.class, executor, CPU_CORE_SIZE); private SocketAcceptor acceptor; /** * start Mina serversocket * @throws Exception */ @Override public void start() throws Exception { int serverPort = ServerConfig.getInstance().getServerPort(); IoBuffer.setUseDirectBuffer(false); IoBuffer.setAllocator(new SimpleBufferAllocator()); acceptor = new NioSocketAcceptor(pool); acceptor.setReuseAddress(true); acceptor.getSessionConfig().setAll(getSessionConfig()); logger.info("mina socket server start at port:{},正在监听客户端的连接...", serverPort); DefaultIoFilterChainBuilder filterChain = acceptor.getFilterChain(); filterChain.addLast("codec", new ProtocolCodecFilter(SerializerHelper.getInstance().getCodecFactory())); filterChain.addLast("moduleEntrance", new ModuleEntranceFilter()); filterChain.addLast("msgTrace", new MessageTraceFilter()); filterChain.addLast("flood", new FloodFilter()); //指定业务逻辑处理器 acceptor.setHandler(new ServerSocketIoHandler(new MessageDispatcher(ServerScanPaths.MESSAGE_PATH))); //设置端口号 acceptor.setDefaultLocalAddress(new InetSocketAddress(serverPort)); //启动监听 acceptor.bind(); } private SocketSessionConfig getSessionConfig() { SocketSessionConfig config = new DefaultSocketSessionConfig(); config.setKeepAlive(true); config.setReuseAddress(true); return config; } @Override public void shutdown() { if (acceptor != null) { acceptor.unbind(); acceptor.dispose(); } logger.error("---------> socket server stop successfully"); } }
1,104
2,151
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/ozone/platform/wayland/wayland_connection.h" #include <xdg-shell-unstable-v5-client-protocol.h> #include <xdg-shell-unstable-v6-client-protocol.h> #include "base/bind.h" #include "base/logging.h" #include "base/memory/ptr_util.h" #include "base/message_loop/message_loop.h" #include "base/message_loop/message_loop_current.h" #include "base/strings/string_util.h" #include "base/threading/thread_task_runner_handle.h" #include "ui/ozone/platform/wayland/wayland_object.h" #include "ui/ozone/platform/wayland/wayland_window.h" static_assert(XDG_SHELL_VERSION_CURRENT == 5, "Unsupported xdg-shell version"); namespace ui { namespace { const uint32_t kMaxCompositorVersion = 4; const uint32_t kMaxSeatVersion = 4; const uint32_t kMaxShmVersion = 1; const uint32_t kMaxXdgShellVersion = 1; } // namespace WaylandConnection::WaylandConnection() : controller_(FROM_HERE) {} WaylandConnection::~WaylandConnection() {} bool WaylandConnection::Initialize() { static const wl_registry_listener registry_listener = { &WaylandConnection::Global, &WaylandConnection::GlobalRemove, }; display_.reset(wl_display_connect(nullptr)); if (!display_) { LOG(ERROR) << "Failed to connect to Wayland display"; return false; } registry_.reset(wl_display_get_registry(display_.get())); if (!registry_) { LOG(ERROR) << "Failed to get Wayland registry"; return false; } wl_registry_add_listener(registry_.get(), &registry_listener, this); while (!PrimaryOutput() || !PrimaryOutput()->is_ready()) wl_display_roundtrip(display_.get()); if (!compositor_) { LOG(ERROR) << "No wl_compositor object"; return false; } if (!shm_) { LOG(ERROR) << "No wl_shm object"; return false; } if (!seat_) { LOG(ERROR) << "No wl_seat object"; return false; } if (!shell_v6_ && !shell_) { LOG(ERROR) << "No xdg_shell object"; return false; } return true; } bool WaylandConnection::StartProcessingEvents() { if (watching_) return true; DCHECK(display_); wl_display_flush(display_.get()); DCHECK(base::MessageLoopForUI::IsCurrent()); if (!base::MessageLoopCurrentForUI::Get()->WatchFileDescriptor( wl_display_get_fd(display_.get()), true, base::MessagePumpLibevent::WATCH_READ, &controller_, this)) return false; watching_ = true; return true; } void WaylandConnection::ScheduleFlush() { if (scheduled_flush_ || !watching_) return; DCHECK(base::MessageLoopForUI::IsCurrent()); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&WaylandConnection::Flush, base::Unretained(this))); scheduled_flush_ = true; } WaylandWindow* WaylandConnection::GetWindow(gfx::AcceleratedWidget widget) { auto it = window_map_.find(widget); return it == window_map_.end() ? nullptr : it->second; } void WaylandConnection::AddWindow(gfx::AcceleratedWidget widget, WaylandWindow* window) { window_map_[widget] = window; } void WaylandConnection::RemoveWindow(gfx::AcceleratedWidget widget) { if (touch_) touch_->RemoveTouchPoints(window_map_[widget]); window_map_.erase(widget); } WaylandOutput* WaylandConnection::PrimaryOutput() const { if (!output_list_.size()) return nullptr; return output_list_.front().get(); } void WaylandConnection::SetCursorBitmap(const std::vector<SkBitmap>& bitmaps, const gfx::Point& location) { if (!pointer_ || !pointer_->cursor()) return; pointer_->cursor()->UpdateBitmap(bitmaps, location, serial_); } int WaylandConnection::GetKeyboardModifiers() { int modifiers = 0; if (keyboard_) modifiers = keyboard_->modifiers(); return modifiers; } ClipboardDelegate* WaylandConnection::GetClipboardDelegate() { return this; } void WaylandConnection::OfferClipboardData( const ClipboardDelegate::DataMap& data_map, ClipboardDelegate::OfferDataClosure callback) { if (!data_source_) { wl_data_source* data_source = data_device_manager_->CreateSource(); data_source_.reset(new WaylandDataSource(data_source)); data_source_->set_connection(this); data_source_->WriteToClipboard(data_map); } data_source_->UpdataDataMap(data_map); std::move(callback).Run(); } void WaylandConnection::RequestClipboardData( const std::string& mime_type, ClipboardDelegate::DataMap* data_map, ClipboardDelegate::RequestDataClosure callback) { read_clipboard_closure_ = std::move(callback); DCHECK(data_map); data_map_ = data_map; data_device_->RequestSelectionData(mime_type); } bool WaylandConnection::IsSelectionOwner() { return !!data_source_; } void WaylandConnection::GetAvailableMimeTypes( ClipboardDelegate::GetMimeTypesClosure callback) { std::move(callback).Run(data_device_->GetAvailableMimeTypes()); } void WaylandConnection::DataSourceCancelled() { SetClipboardData(std::string(), std::string()); data_source_.reset(); } void WaylandConnection::SetClipboardData(const std::string& contents, const std::string& mime_type) { if (!data_map_) return; (*data_map_)[mime_type] = std::vector<uint8_t>(contents.begin(), contents.end()); if (!read_clipboard_closure_.is_null()) { auto it = data_map_->find(mime_type); DCHECK(it != data_map_->end()); std::move(read_clipboard_closure_).Run(it->second); } data_map_ = nullptr; } void WaylandConnection::OnDispatcherListChanged() { StartProcessingEvents(); } void WaylandConnection::Flush() { wl_display_flush(display_.get()); scheduled_flush_ = false; } void WaylandConnection::DispatchUiEvent(Event* event) { PlatformEventSource::DispatchEvent(event); } void WaylandConnection::OnFileCanReadWithoutBlocking(int fd) { wl_display_dispatch(display_.get()); for (const auto& window : window_map_) window.second->ApplyPendingBounds(); } void WaylandConnection::OnFileCanWriteWithoutBlocking(int fd) {} const std::vector<std::unique_ptr<WaylandOutput>>& WaylandConnection::GetOutputList() const { return output_list_; } // static void WaylandConnection::Global(void* data, wl_registry* registry, uint32_t name, const char* interface, uint32_t version) { static const wl_seat_listener seat_listener = { &WaylandConnection::Capabilities, &WaylandConnection::Name, }; static const xdg_shell_listener shell_listener = { &WaylandConnection::Ping, }; static const zxdg_shell_v6_listener shell_v6_listener = { &WaylandConnection::PingV6, }; WaylandConnection* connection = static_cast<WaylandConnection*>(data); if (!connection->compositor_ && strcmp(interface, "wl_compositor") == 0) { connection->compositor_ = wl::Bind<wl_compositor>( registry, name, std::min(version, kMaxCompositorVersion)); if (!connection->compositor_) LOG(ERROR) << "Failed to bind to wl_compositor global"; } else if (!connection->shm_ && strcmp(interface, "wl_shm") == 0) { connection->shm_ = wl::Bind<wl_shm>(registry, name, std::min(version, kMaxShmVersion)); if (!connection->shm_) LOG(ERROR) << "Failed to bind to wl_shm global"; } else if (!connection->seat_ && strcmp(interface, "wl_seat") == 0) { connection->seat_ = wl::Bind<wl_seat>(registry, name, std::min(version, kMaxSeatVersion)); if (!connection->seat_) { LOG(ERROR) << "Failed to bind to wl_seat global"; return; } wl_seat_add_listener(connection->seat_.get(), &seat_listener, connection); // TODO(tonikitoo,msisov): The connection passed to WaylandInputDevice must // have a valid data device manager. We should ideally be robust to the // compositor advertising a wl_seat first. No known compositor does this, // fortunately. if (!connection->data_device_manager_) { LOG(ERROR) << "No data device manager. Clipboard won't be fully functional"; return; } wl_data_device* data_device = connection->data_device_manager_->GetDevice(); connection->data_device_.reset( new WaylandDataDevice(connection, data_device)); } else if (!connection->shell_v6_ && strcmp(interface, "zxdg_shell_v6") == 0) { // Check for zxdg_shell_v6 first. connection->shell_v6_ = wl::Bind<zxdg_shell_v6>( registry, name, std::min(version, kMaxXdgShellVersion)); if (!connection->shell_v6_) { LOG(ERROR) << "Failed to bind to zxdg_shell_v6 global"; return; } zxdg_shell_v6_add_listener(connection->shell_v6_.get(), &shell_v6_listener, connection); } else if (!connection->shell_v6_ && !connection->shell_ && strcmp(interface, "xdg_shell") == 0) { connection->shell_ = wl::Bind<xdg_shell>( registry, name, std::min(version, kMaxXdgShellVersion)); if (!connection->shell_) { LOG(ERROR) << "Failed to bind to xdg_shell global"; return; } xdg_shell_add_listener(connection->shell_.get(), &shell_listener, connection); xdg_shell_use_unstable_version(connection->shell_.get(), XDG_SHELL_VERSION_CURRENT); } else if (base::EqualsCaseInsensitiveASCII(interface, "wl_output")) { wl::Object<wl_output> output = wl::Bind<wl_output>(registry, name, 1); if (!output) { LOG(ERROR) << "Failed to bind to wl_output global"; return; } if (!connection->output_list_.empty()) NOTIMPLEMENTED() << "Multiple screens support is not implemented"; connection->output_list_.push_back(base::WrapUnique(new WaylandOutput( connection->get_next_display_id(), output.release()))); } else if (!connection->data_device_manager_ && strcmp(interface, "wl_data_device_manager") == 0) { wl::Object<wl_data_device_manager> data_device_manager = wl::Bind<wl_data_device_manager>(registry, name, 1); if (!data_device_manager) { LOG(ERROR) << "Failed to bind to wl_data_device_manager global"; return; } connection->data_device_manager_.reset( new WaylandDataDeviceManager(data_device_manager.release())); connection->data_device_manager_->set_connection(connection); } connection->ScheduleFlush(); } // static void WaylandConnection::GlobalRemove(void* data, wl_registry* registry, uint32_t name) { NOTIMPLEMENTED(); } // static void WaylandConnection::Capabilities(void* data, wl_seat* seat, uint32_t capabilities) { WaylandConnection* connection = static_cast<WaylandConnection*>(data); if (capabilities & WL_SEAT_CAPABILITY_POINTER) { if (!connection->pointer_) { wl_pointer* pointer = wl_seat_get_pointer(connection->seat_.get()); if (!pointer) { LOG(ERROR) << "Failed to get wl_pointer from seat"; return; } connection->pointer_ = std::make_unique<WaylandPointer>( pointer, base::BindRepeating(&WaylandConnection::DispatchUiEvent, base::Unretained(connection))); connection->pointer_->set_connection(connection); } } else if (connection->pointer_) { connection->pointer_.reset(); } if (capabilities & WL_SEAT_CAPABILITY_KEYBOARD) { if (!connection->keyboard_) { wl_keyboard* keyboard = wl_seat_get_keyboard(connection->seat_.get()); if (!keyboard) { LOG(ERROR) << "Failed to get wl_keyboard from seat"; return; } connection->keyboard_ = std::make_unique<WaylandKeyboard>( keyboard, base::BindRepeating(&WaylandConnection::DispatchUiEvent, base::Unretained(connection))); connection->keyboard_->set_connection(connection); } } else if (connection->keyboard_) { connection->keyboard_.reset(); } if (capabilities & WL_SEAT_CAPABILITY_TOUCH) { if (!connection->touch_) { wl_touch* touch = wl_seat_get_touch(connection->seat_.get()); if (!touch) { LOG(ERROR) << "Failed to get wl_touch from seat"; return; } connection->touch_ = std::make_unique<WaylandTouch>( touch, base::BindRepeating(&WaylandConnection::DispatchUiEvent, base::Unretained(connection))); connection->touch_->set_connection(connection); } } else if (connection->touch_) { connection->touch_.reset(); } connection->ScheduleFlush(); } // static void WaylandConnection::Name(void* data, wl_seat* seat, const char* name) {} // static void WaylandConnection::PingV6(void* data, zxdg_shell_v6* shell_v6, uint32_t serial) { WaylandConnection* connection = static_cast<WaylandConnection*>(data); zxdg_shell_v6_pong(shell_v6, serial); connection->ScheduleFlush(); } // static void WaylandConnection::Ping(void* data, xdg_shell* shell, uint32_t serial) { WaylandConnection* connection = static_cast<WaylandConnection*>(data); xdg_shell_pong(shell, serial); connection->ScheduleFlush(); } } // namespace ui
5,370
1,127
# Copyright (C) 2018-2022 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import unittest import numpy as np from generator import generator, generate from openvino.tools.mo.ops.MatMul import MatMul from openvino.tools.mo.front.common.partial_infer.utils import int64_array, shape_array, dynamic_dimension_value from openvino.tools.mo.graph.graph import Node from unit_tests.utils.graph import build_graph_with_attrs @generator class TestMatMul(unittest.TestCase): nodes = [ ('A', {'type': 'Parameter', 'kind': 'op'}), ('A_d', {'kind': 'data'}), ('B', {'type': 'Parameter', 'kind': 'op'}), ('B_d', {'kind': 'data', 'dim_attrs': []}), ('mat_mul', {'type': 'MatMul', 'kind': 'op'}), ('mat_mul_d', {'kind': 'data', 'value': None, 'shape': None}), ('op_output', {'kind': 'op', 'op': 'Result'}), ] edges = [ ('A', 'A_d'), ('B', 'B_d'), ('A_d', 'mat_mul', {'in': 0}), ('B_d', 'mat_mul', {'in': 1}), ('mat_mul', 'mat_mul_d'), ('mat_mul_d', 'op_output'), ] @generate(*[ ([1024], [1024, 1000], [1000], False, False), ([dynamic_dimension_value], [1024, 1000], [1000], False, False), ([1024], [dynamic_dimension_value, 1000], [1000], False, False), ([1024], [1024, 1000], [1000], True, False), ([1024], [1000, 1024], [1000], True, True), ([dynamic_dimension_value], [dynamic_dimension_value, dynamic_dimension_value], [dynamic_dimension_value], True, True), ([1, 1024], [1024, 1000], [1, 1000], False, False), ([1, 1024], [1000, 1024], [1, 1000], False, True), ([1024, 1000], [1000], [1024], False, False), ([1024, 1000], [1000], [1024], False, True), ([1000, 1024], [1000], [1024], True, True), ([1000, dynamic_dimension_value], [1000], [dynamic_dimension_value], True, True), ([10, 1024], [1024, 1000], [10, 1000], False, False), ([5, 10, 1024], [1024, 1000], [5, 10, 1000], False, False), ([5, 10, 1024], [5, 1024, 1000], [5, 10, 1000], False, False), ([5, 10, 1024], [1, 1024, 1000], [5, 10, 1000], False, False), ([5, 10, 1024], [1, 1000, 1024], [5, 10, 1000], False, True), ]) def test_positive_matmul_infer(self, A_shape, B_shape, C_shape, transpose_a, transpose_b): graph = build_graph_with_attrs(nodes_with_attrs=self.nodes, edges_with_attrs=self.edges, update_nodes_attributes=[ ('A_d', {'shape': shape_array(A_shape)}), ('B_d', {'shape': shape_array(B_shape)}), ('mat_mul', {'transpose_a': transpose_a, 'transpose_b': transpose_b}), ]) node = Node(graph, 'mat_mul') MatMul.infer(node) msg = "MatMul infer failed for case: A_shape={}, B_shape={}, transpose_a={}, transpose_b={} " \ "expected_shape={}, actual_shape={}" self.assertTrue(np.array_equal(graph.node['mat_mul_d']['shape'], shape_array(C_shape)), msg.format(A_shape, B_shape, transpose_a, transpose_b, C_shape, graph.node['mat_mul_d']['shape'])) @generate(*[ (None, [1024, 1000]), (1, [1024, 1000]), ([], [1024, 1000]), ([1024, 1000], [1024, 1000]), ([5, 10, 1024], [3, 1024, 1000]), ]) def test_negative_matmul_infer(self, A_shape, B_shape): graph = build_graph_with_attrs(nodes_with_attrs=self.nodes, edges_with_attrs=self.edges, update_nodes_attributes=[ ('A_d', {'shape': np.array(A_shape)}), ('B_d', {'shape': int64_array(B_shape)}), ]) node = Node(graph, 'mat_mul') self.assertRaises(AssertionError, MatMul.infer, node)
2,047
2,151
<reponame>rhencke/engine<filename>src/third_party/swiftshader/src/D3D8/Capabilities.cpp<gh_stars>1000+ // Copyright 2016 The SwiftShader Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "Capabilities.hpp" #include "Main/Config.hpp" namespace D3D8 { bool Capabilities::Surface::RenderTarget::R8G8B8 = false; bool Capabilities::Surface::RenderTarget::R5G6B5 = true; bool Capabilities::Surface::RenderTarget::X1R5G5B5 = true; bool Capabilities::Surface::RenderTarget::A1R5G5B5 = true; bool Capabilities::Surface::RenderTarget::A4R4G4B4 = true; bool Capabilities::Surface::RenderTarget::R3G3B2 = false; bool Capabilities::Surface::RenderTarget::A8R3G3B2 = false; bool Capabilities::Surface::RenderTarget::X4R4G4B4 = true; bool Capabilities::Surface::RenderTarget::A8R8G8B8 = true; bool Capabilities::Surface::RenderTarget::X8R8G8B8 = true; bool Capabilities::Surface::RenderTarget::A8B8G8R8 = true; bool Capabilities::Surface::RenderTarget::X8B8G8R8 = true; bool Capabilities::Surface::RenderTarget::G16R16 = true; bool Capabilities::Surface::RenderTarget::A2B10G10R10 = true; bool Capabilities::Surface::DepthStencil::D32 = true; bool Capabilities::Surface::DepthStencil::D24S8 = true; bool Capabilities::Surface::DepthStencil::D24X8 = true; bool Capabilities::Surface::DepthStencil::D16 = true; bool Capabilities::Surface::A8 = true; bool Capabilities::Surface::R5G6B5 = true; bool Capabilities::Surface::X1R5G5B5 = true; bool Capabilities::Surface::A1R5G5B5 = true; bool Capabilities::Surface::A4R4G4B4 = true; bool Capabilities::Surface::R3G3B2 = true; bool Capabilities::Surface::A8R3G3B2 = true; bool Capabilities::Surface::X4R4G4B4 = true; bool Capabilities::Surface::R8G8B8 = false; bool Capabilities::Surface::X8R8G8B8 = true; bool Capabilities::Surface::A8R8G8B8 = true; bool Capabilities::Surface::X8B8G8R8 = true; bool Capabilities::Surface::A8B8G8R8 = true; bool Capabilities::Surface::P8 = false; bool Capabilities::Surface::A8P8 = false; bool Capabilities::Surface::G16R16 = true; bool Capabilities::Surface::A2B10G10R10 = true; bool Capabilities::Surface::DXT1 = true; bool Capabilities::Surface::DXT2 = true; bool Capabilities::Surface::DXT3 = true; bool Capabilities::Surface::DXT4 = true; bool Capabilities::Surface::DXT5 = true; bool Capabilities::Surface::V8U8 = true; bool Capabilities::Surface::L6V5U5 = true; bool Capabilities::Surface::X8L8V8U8 = true; bool Capabilities::Surface::Q8W8V8U8 = true; bool Capabilities::Surface::V16U16 = true; bool Capabilities::Surface::A2W10V10U10 = true; bool Capabilities::Surface::L8 = true; bool Capabilities::Surface::A4L4 = true; bool Capabilities::Surface::A8L8 = true; bool Capabilities::Volume::A8 = true; bool Capabilities::Volume::R5G6B5 = true; bool Capabilities::Volume::X1R5G5B5 = true; bool Capabilities::Volume::A1R5G5B5 = true; bool Capabilities::Volume::A4R4G4B4 = true; bool Capabilities::Volume::R3G3B2 = true; bool Capabilities::Volume::A8R3G3B2 = true; bool Capabilities::Volume::X4R4G4B4 = true; bool Capabilities::Volume::R8G8B8 = false; bool Capabilities::Volume::X8R8G8B8 = true; bool Capabilities::Volume::A8R8G8B8 = true; bool Capabilities::Volume::X8B8G8R8 = true; bool Capabilities::Volume::A8B8G8R8 = true; bool Capabilities::Volume::P8 = false; bool Capabilities::Volume::A8P8 = false; bool Capabilities::Volume::G16R16 = true; bool Capabilities::Volume::A2B10G10R10 = true; bool Capabilities::Volume::DXT1 = true; bool Capabilities::Volume::DXT2 = true; bool Capabilities::Volume::DXT3 = true; bool Capabilities::Volume::DXT4 = true; bool Capabilities::Volume::DXT5 = true; bool Capabilities::Volume::V8U8 = true; bool Capabilities::Volume::L6V5U5 = true; bool Capabilities::Volume::X8L8V8U8 = true; bool Capabilities::Volume::Q8W8V8U8 = true; bool Capabilities::Volume::V16U16 = true; bool Capabilities::Volume::A2W10V10U10 = true; bool Capabilities::Volume::L8 = true; bool Capabilities::Volume::A4L4 = true; bool Capabilities::Volume::A8L8 = true; bool Capabilities::CubeMap::RenderTarget::R8G8B8 = false; bool Capabilities::CubeMap::RenderTarget::R5G6B5 = true; bool Capabilities::CubeMap::RenderTarget::X1R5G5B5 = true; bool Capabilities::CubeMap::RenderTarget::A1R5G5B5 = true; bool Capabilities::CubeMap::RenderTarget::A4R4G4B4 = true; bool Capabilities::CubeMap::RenderTarget::R3G3B2 = false; bool Capabilities::CubeMap::RenderTarget::A8R3G3B2 = false; bool Capabilities::CubeMap::RenderTarget::X4R4G4B4 = true; bool Capabilities::CubeMap::RenderTarget::A8R8G8B8 = true; bool Capabilities::CubeMap::RenderTarget::X8R8G8B8 = true; bool Capabilities::CubeMap::RenderTarget::A8B8G8R8 = true; bool Capabilities::CubeMap::RenderTarget::X8B8G8R8 = true; bool Capabilities::CubeMap::RenderTarget::G16R16 = true; bool Capabilities::CubeMap::RenderTarget::A2B10G10R10 = true; bool Capabilities::CubeMap::DepthStencil::D32 = false; bool Capabilities::CubeMap::DepthStencil::D24S8 = false; bool Capabilities::CubeMap::DepthStencil::D24X8 = false; bool Capabilities::CubeMap::DepthStencil::D16 = false; bool Capabilities::CubeMap::A8 = true; bool Capabilities::CubeMap::R5G6B5 = true; bool Capabilities::CubeMap::X1R5G5B5 = true; bool Capabilities::CubeMap::A1R5G5B5 = true; bool Capabilities::CubeMap::A4R4G4B4 = true; bool Capabilities::CubeMap::R3G3B2 = true; bool Capabilities::CubeMap::A8R3G3B2 = true; bool Capabilities::CubeMap::X4R4G4B4 = true; bool Capabilities::CubeMap::R8G8B8 = false; bool Capabilities::CubeMap::X8R8G8B8 = true; bool Capabilities::CubeMap::A8R8G8B8 = true; bool Capabilities::CubeMap::X8B8G8R8 = true; bool Capabilities::CubeMap::A8B8G8R8 = true; bool Capabilities::CubeMap::P8 = false; bool Capabilities::CubeMap::A8P8 = false; bool Capabilities::CubeMap::G16R16 = true; bool Capabilities::CubeMap::A2B10G10R10 = true; bool Capabilities::CubeMap::DXT1 = true; bool Capabilities::CubeMap::DXT2 = true; bool Capabilities::CubeMap::DXT3 = true; bool Capabilities::CubeMap::DXT4 = true; bool Capabilities::CubeMap::DXT5 = true; bool Capabilities::CubeMap::V8U8 = true; bool Capabilities::CubeMap::L6V5U5 = true; bool Capabilities::CubeMap::X8L8V8U8 = true; bool Capabilities::CubeMap::Q8W8V8U8 = true; bool Capabilities::CubeMap::V16U16 = true; bool Capabilities::CubeMap::A2W10V10U10 = true; bool Capabilities::CubeMap::L8 = true; bool Capabilities::CubeMap::A4L4 = true; bool Capabilities::CubeMap::A8L8 = true; bool Capabilities::VolumeTexture::A8 = true; bool Capabilities::VolumeTexture::R5G6B5 = true; bool Capabilities::VolumeTexture::X1R5G5B5 = true; bool Capabilities::VolumeTexture::A1R5G5B5 = true; bool Capabilities::VolumeTexture::A4R4G4B4 = true; bool Capabilities::VolumeTexture::R3G3B2 = true; bool Capabilities::VolumeTexture::A8R3G3B2 = true; bool Capabilities::VolumeTexture::X4R4G4B4 = true; bool Capabilities::VolumeTexture::R8G8B8 = false; bool Capabilities::VolumeTexture::X8R8G8B8 = true; bool Capabilities::VolumeTexture::A8R8G8B8 = true; bool Capabilities::VolumeTexture::X8B8G8R8 = true; bool Capabilities::VolumeTexture::A8B8G8R8 = true; bool Capabilities::VolumeTexture::P8 = false; bool Capabilities::VolumeTexture::A8P8 = false; bool Capabilities::VolumeTexture::G16R16 = true; bool Capabilities::VolumeTexture::A2B10G10R10 = true; bool Capabilities::VolumeTexture::DXT1 = true; bool Capabilities::VolumeTexture::DXT2 = true; bool Capabilities::VolumeTexture::DXT3 = true; bool Capabilities::VolumeTexture::DXT4 = true; bool Capabilities::VolumeTexture::DXT5 = true; bool Capabilities::VolumeTexture::V8U8 = true; bool Capabilities::VolumeTexture::L6V5U5 = true; bool Capabilities::VolumeTexture::X8L8V8U8 = true; bool Capabilities::VolumeTexture::Q8W8V8U8 = true; bool Capabilities::VolumeTexture::V16U16 = true; bool Capabilities::VolumeTexture::A2W10V10U10 = true; bool Capabilities::VolumeTexture::L8 = true; bool Capabilities::VolumeTexture::A4L4 = true; bool Capabilities::VolumeTexture::A8L8 = true; bool Capabilities::Texture::RenderTarget::R8G8B8 = false; bool Capabilities::Texture::RenderTarget::R5G6B5 = true; bool Capabilities::Texture::RenderTarget::X1R5G5B5 = true; bool Capabilities::Texture::RenderTarget::A1R5G5B5 = true; bool Capabilities::Texture::RenderTarget::A4R4G4B4 = true; bool Capabilities::Texture::RenderTarget::R3G3B2 = false; bool Capabilities::Texture::RenderTarget::A8R3G3B2 = false; bool Capabilities::Texture::RenderTarget::X4R4G4B4 = true; bool Capabilities::Texture::RenderTarget::A8R8G8B8 = true; bool Capabilities::Texture::RenderTarget::X8R8G8B8 = true; bool Capabilities::Texture::RenderTarget::A8B8G8R8 = true; bool Capabilities::Texture::RenderTarget::X8B8G8R8 = true; bool Capabilities::Texture::RenderTarget::G16R16 = true; bool Capabilities::Texture::RenderTarget::A2B10G10R10 = true; bool Capabilities::Texture::DepthStencil::D32 = false; bool Capabilities::Texture::DepthStencil::D24S8 = false; bool Capabilities::Texture::DepthStencil::D24X8 = false; bool Capabilities::Texture::DepthStencil::D16 = false; bool Capabilities::Texture::A8 = true; bool Capabilities::Texture::R5G6B5 = true; bool Capabilities::Texture::X1R5G5B5 = true; bool Capabilities::Texture::A1R5G5B5 = true; bool Capabilities::Texture::A4R4G4B4 = true; bool Capabilities::Texture::R3G3B2 = true; bool Capabilities::Texture::A8R3G3B2 = true; bool Capabilities::Texture::X4R4G4B4 = true; bool Capabilities::Texture::R8G8B8 = false; bool Capabilities::Texture::X8R8G8B8 = true; bool Capabilities::Texture::A8R8G8B8 = true; bool Capabilities::Texture::X8B8G8R8 = true; bool Capabilities::Texture::A8B8G8R8 = true; bool Capabilities::Texture::P8 = false; bool Capabilities::Texture::A8P8 = false; bool Capabilities::Texture::G16R16 = true; bool Capabilities::Texture::A2B10G10R10 = true; bool Capabilities::Texture::DXT1 = true; bool Capabilities::Texture::DXT2 = true; bool Capabilities::Texture::DXT3 = true; bool Capabilities::Texture::DXT4 = true; bool Capabilities::Texture::DXT5 = true; bool Capabilities::Texture::V8U8 = true; bool Capabilities::Texture::L6V5U5 = true; bool Capabilities::Texture::X8L8V8U8 = true; bool Capabilities::Texture::Q8W8V8U8 = true; bool Capabilities::Texture::V16U16 = true; bool Capabilities::Texture::A2W10V10U10 = true; bool Capabilities::Texture::L8 = true; bool Capabilities::Texture::A4L4 = true; bool Capabilities::Texture::A8L8 = true; unsigned int pixelShaderVersion = D3DPS_VERSION(1, 4); unsigned int vertexShaderVersion = D3DVS_VERSION(1, 1); unsigned int textureMemory = 256 * 1024 * 1024; unsigned int maxAnisotropy = 16; }
4,120
1,379
<reponame>yongzhuo/nlp_xiaojiang<filename>ChatBot/chatbot_search/chatbot_tfserving/indexAnnoy.py # !/usr/bin/python # -*- coding: utf-8 -*- # @time : 2021/4/18 21:04 # @author : Mo # @function: annoy search from annoy import AnnoyIndex import numpy as np import os class AnnoySearch: def __init__(self, dim=768, n_cluster=100): # metric可选“angular”(余弦距离)、“euclidean”(欧几里得距离)、 “ manhattan”(曼哈顿距离)或“hamming”(海明距离) self.annoy_index = AnnoyIndex(dim, metric="angular") self.n_cluster = n_cluster self.dim = dim def k_neighbors(self, vectors, k=18): """ 搜索 """ annoy_tops = [] for v in vectors: idx, dist = self.annoy_index.get_nns_by_vector(v, k, search_k=32*k, include_distances=True) annoy_tops.append([dist, idx]) return annoy_tops def fit(self, vectors): """ annoy构建 """ for i, v in enumerate(vectors): self.annoy_index.add_item(i, v) self.annoy_index.build(self.n_cluster) def save(self, path): """ 存储 """ self.annoy_index.save(path) def load(self, path): """ 加载 """ self.annoy_index.load(path) if __name__ == '__main__': ### 索引 import random path = "model.ann" dim = 768 vectors = [[random.gauss(0, 1) for z in range(768)] for i in range(10)] an_model = AnnoySearch(dim, n_cluster=32) # Length of item vector that will be indexed an_model.fit(vectors) an_model.save(path) tops = an_model.k_neighbors([vectors[0]], 18) print(tops) del an_model ### 下载, 搜索 an_model = AnnoySearch(dim, n_cluster=32) an_model.load(path) tops = an_model.k_neighbors([vectors[0]], 6) print(tops) """ # example from annoy import AnnoyIndex import random dim = 768 vectors = [[random.gauss(0, 1) for z in range(768)] for i in range(10)] ann_model = AnnoyIndex(dim, 'angular') # Length of item vector that will be indexed for i,v in enumerate(vectors): ann_model.add_item(i, v) ann_model.build(10) # 10 trees ann_model.save("tet.ann") del ann_model u = AnnoyIndex(dim, "angular") u.load('tet.ann') # super fast, will just mmap the file v = vectors[1] idx, dist = u.get_nns_by_vector(v, 10, search_k=50 * 10, include_distances=True) print([idx, dist]) """ ### 备注说明: annoy索引 无法 增删会改查
1,215
862
<reponame>Regan-Koopmans/atlasdb /* * (c) Copyright 2020 Palantir Technologies Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.palantir.timelock.history; import com.google.common.annotations.VisibleForTesting; import com.palantir.paxos.NamespaceAndUseCase; import com.palantir.timelock.history.models.LearnerUseCase; import com.palantir.timelock.history.models.ProgressState; import com.palantir.timelock.history.sqlite.LogVerificationProgressState; import com.palantir.timelock.history.sqlite.SqlitePaxosStateLogHistory; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.sql.DataSource; public class PaxosLogHistoryProgressTracker { // VisibleForTesting - used in corruption-detection tests public static final int MAX_ROWS_ALLOWED = 250; private final LogVerificationProgressState logVerificationProgressState; private final SqlitePaxosStateLogHistory sqlitePaxosStateLogHistory; private final Map<NamespaceAndUseCase, ProgressState> verificationProgressStateCache = new ConcurrentHashMap<>(); public PaxosLogHistoryProgressTracker( DataSource dataSource, SqlitePaxosStateLogHistory sqlitePaxosStateLogHistory) { this.logVerificationProgressState = LogVerificationProgressState.create(dataSource); this.sqlitePaxosStateLogHistory = sqlitePaxosStateLogHistory; } public HistoryQuerySequenceBounds getNextPaxosLogSequenceRangeToBeVerified( NamespaceAndUseCase namespaceAndUseCase) { ProgressState progressState = getOrPopulateProgressState(namespaceAndUseCase); if (progressState.shouldResetProgressState()) { progressState = resetProgressState(namespaceAndUseCase); } return sequenceBoundsForNextHistoryQuery(progressState.lastVerifiedSeq()); } public void updateProgressState( Map<NamespaceAndUseCase, HistoryQuerySequenceBounds> namespaceAndUseCaseWiseLoadedSequenceRange) { namespaceAndUseCaseWiseLoadedSequenceRange.forEach(this::updateProgressStateForNamespaceAndUseCase); } private ProgressState getOrPopulateProgressState(NamespaceAndUseCase namespaceAndUseCase) { return verificationProgressStateCache.computeIfAbsent( namespaceAndUseCase, this::progressStatusForNamespaceAndUseCase); } private ProgressState progressStatusForNamespaceAndUseCase(NamespaceAndUseCase namespaceAndUseCase) { long lastVerifiedSeq = logVerificationProgressState.getLastVerifiedSeq( namespaceAndUseCase.namespace(), namespaceAndUseCase.useCase()); return buildProgressStatusWithLastVerifiedSeqForNamespaceAndUseCase(namespaceAndUseCase, lastVerifiedSeq); } @VisibleForTesting void updateProgressStateForNamespaceAndUseCase( NamespaceAndUseCase namespaceAndUseCase, HistoryQuerySequenceBounds bounds) { updateProgressInDbThroughCache( namespaceAndUseCase, bounds.getUpperBoundInclusive(), getOrPopulateProgressState(namespaceAndUseCase)); } private ProgressState updateProgressInDbThroughCache( NamespaceAndUseCase namespaceAndUseCase, long lastVerifiedSequence, ProgressState currentState) { ProgressState newProgressState = ProgressState.builder() .greatestSeqNumberToBeVerified(currentState.greatestSeqNumberToBeVerified()) .lastVerifiedSeq(lastVerifiedSequence) .build(); verificationProgressStateCache.put(namespaceAndUseCase, newProgressState); logVerificationProgressState.updateProgress( namespaceAndUseCase.namespace(), namespaceAndUseCase.useCase(), lastVerifiedSequence); return newProgressState; } private ProgressState resetProgressState(NamespaceAndUseCase namespaceAndUseCase) { logVerificationProgressState.setInitialProgress(namespaceAndUseCase.namespace(), namespaceAndUseCase.useCase()); ProgressState resetProgressState = buildProgressStatusWithLastVerifiedSeqForNamespaceAndUseCase( namespaceAndUseCase, LogVerificationProgressState.INITIAL_PROGRESS); verificationProgressStateCache.put(namespaceAndUseCase, resetProgressState); return resetProgressState; } private long getLatestLearnedSequenceForNamespaceAndUseCase(NamespaceAndUseCase namespaceAndUseCase) { return sqlitePaxosStateLogHistory.getGreatestLogEntry( namespaceAndUseCase.namespace(), LearnerUseCase.createLearnerUseCase(namespaceAndUseCase.useCase())); } private ProgressState buildProgressStatusWithLastVerifiedSeqForNamespaceAndUseCase( NamespaceAndUseCase namespaceAndUseCase, long lastVerifiedSeq) { return ProgressState.builder() .lastVerifiedSeq(lastVerifiedSeq) .greatestSeqNumberToBeVerified(getLatestLearnedSequenceForNamespaceAndUseCase(namespaceAndUseCase)) .build(); } private HistoryQuerySequenceBounds sequenceBoundsForNextHistoryQuery(long lastVerified) { return HistoryQuerySequenceBounds.of(lastVerified + 1, lastVerified + MAX_ROWS_ALLOWED); } }
1,914
1,062
/** * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cppunit/TestFixture.h> #include <cppunit/extensions/HelperMacros.h> #include "coord/coord_api.h" namespace MR4C { class TestSimpleEastNorthTrans : public CPPUNIT_NS::TestFixture { CPPUNIT_TEST_SUITE(TestSimpleEastNorthTrans); CPPUNIT_TEST(testFromLatLon); CPPUNIT_TEST(testRoundTripConversion); CPPUNIT_TEST_SUITE_END(); private: SimpleEastNorthTrans* m_trans; public: void setUp() { // using miles here m_trans = new SimpleEastNorthTrans(4000); } void tearDown() { delete m_trans; } void testFromLatLon() { double eps = 1; LatLonCoord latlon = LatLonCoord::fromDegrees(60, 135); EastNorthCoord expected(9425, 4189); EastNorthCoord actual = m_trans->toEastNorth(latlon); CPPUNIT_ASSERT_DOUBLES_EQUAL(expected.getEast(), actual.getEast(), eps); CPPUNIT_ASSERT_DOUBLES_EQUAL(expected.getNorth(), actual.getNorth(), eps); } void testRoundTripConversion() { EastNorthCoord en(1500, 2000); LatLonCoord ll = m_trans->toLatLon(en); EastNorthCoord en2 = m_trans->toEastNorth(ll); CPPUNIT_ASSERT_EQUAL(en, en2); } }; CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(TestSimpleEastNorthTrans, "TestSimpleEastNorthTrans"); }
680
3,172
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os os.environ['XPARL'] = 'True' import parl import unittest @parl.remote_class(max_memory=350) class Actor(object): def __init__(self, x=10): self.x = x self.data = [] def add_500mb(self): self.data.append(os.urandom(500 * 1024**2)) self.x += 1 return self.x class TestLocalActor(unittest.TestCase): def test_create_actors_without_pre_connection(self): actor = Actor() if __name__ == '__main__': unittest.main()
380
648
{"resourceType":"DataElement","id":"CodeSystem.valueSet","meta":{"lastUpdated":"2017-04-19T07:44:43.294+10:00"},"url":"http://hl7.org/fhir/DataElement/CodeSystem.valueSet","status":"draft","experimental":true,"stringency":"fully-specified","element":[{"id":"CodeSystem.valueSet","path":"CodeSystem.valueSet","short":"Canonical URL for value set with entire code system","definition":"Canonical URL of value set that contains the entire code system.","comment":"The definition of the value set SHALL include all codes from this code system, and it SHALL be immutable.","min":0,"max":"1","type":[{"code":"uri"}],"isSummary":true}]}
167
5,133
<reponame>Saljack/mapstruct<filename>processor/src/test/resources/fixtures/org/mapstruct/ap/test/collection/adder/SourceTargetMapperStrategyDefaultImpl.java /* * Copyright MapStruct Authors. * * Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0 */ package org.mapstruct.ap.test.collection.adder; import javax.annotation.Generated; import org.mapstruct.ap.test.collection.adder._target.Target; import org.mapstruct.ap.test.collection.adder.source.Source; @Generated( value = "org.mapstruct.ap.MappingProcessor", date = "2017-04-09T23:05:40+0200", comments = "version: , compiler: javac, environment: Java 1.8.0_121 (Oracle Corporation)" ) public class SourceTargetMapperStrategyDefaultImpl implements SourceTargetMapperStrategyDefault { private final PetMapper petMapper = new PetMapper(); @Override public Target shouldFallBackToAdder(Source source) throws DogException { if ( source == null ) { return null; } Target target = new Target(); try { target.setPets( petMapper.toPets( source.getPets() ) ); } catch ( CatException e ) { throw new RuntimeException( e ); } return target; } }
468
1,585
<reponame>j-xiong/ompi /* -*- Mode: C; c-basic-offset:4 ; indent-tabs-mode:nil -*- */ /* * Copyright (c) 2004-2005 The Trustees of Indiana University and Indiana * University Research and Technology * Corporation. All rights reserved. * Copyright (c) 2004-2005 The University of Tennessee and The University * of Tennessee Research Foundation. All rights * reserved. * Copyright (c) 2004-2005 High Performance Computing Center Stuttgart, * University of Stuttgart. All rights reserved. * Copyright (c) 2004-2005 The Regents of the University of California. * All rights reserved. * Copyright (c) 2011-2012 Cisco Systems, Inc. All rights reserved. * Copyright (c) 2014-2016 Los Alamos National Security, LLC. All rights * reserved. * Copyright (c) 2015 Research Organization for Information Science * and Technology (RIST). All rights reserved. * $COPYRIGHT$ * * Additional copyrights may follow * * $HEADER$ */ #include "ompi_config.h" #include "ompi/mpi/fortran/mpif-h/bindings.h" #include "ompi/mpi/fortran/base/constants.h" #if OMPI_BUILD_MPI_PROFILING #if OPAL_HAVE_WEAK_SYMBOLS #pragma weak PMPI_RACCUMULATE = ompi_raccumulate_f #pragma weak pmpi_raccumulate = ompi_raccumulate_f #pragma weak pmpi_raccumulate_ = ompi_raccumulate_f #pragma weak pmpi_raccumulate__ = ompi_raccumulate_f #pragma weak PMPI_Raccumulate_f = ompi_raccumulate_f #pragma weak PMPI_Raccumulate_f08 = ompi_raccumulate_f #else OMPI_GENERATE_F77_BINDINGS (PMPI_RACCUMULATE, pmpi_raccumulate, pmpi_raccumulate_, pmpi_raccumulate__, pompi_raccumulate_f, (char *origin_addr, MPI_Fint *origin_count, MPI_Fint *origin_datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *target_count, MPI_Fint *target_datatype, MPI_Fint *op, MPI_Fint *win, MPI_Fint *request, MPI_Fint *ierr), (origin_addr, origin_count, origin_datatype, target_rank, target_disp, target_count, target_datatype, op, win, request, ierr) ) #endif #endif #if OPAL_HAVE_WEAK_SYMBOLS #pragma weak MPI_RACCUMULATE = ompi_raccumulate_f #pragma weak mpi_raccumulate = ompi_raccumulate_f #pragma weak mpi_raccumulate_ = ompi_raccumulate_f #pragma weak mpi_raccumulate__ = ompi_raccumulate_f #pragma weak MPI_Raccumulate_f = ompi_raccumulate_f #pragma weak MPI_Raccumulate_f08 = ompi_raccumulate_f #else #if ! OMPI_BUILD_MPI_PROFILING OMPI_GENERATE_F77_BINDINGS (MPI_RACCUMULATE, mpi_raccumulate, mpi_raccumulate_, mpi_raccumulate__, ompi_raccumulate_f, (char *origin_addr, MPI_Fint *origin_count, MPI_Fint *origin_datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *target_count, MPI_Fint *target_datatype, MPI_Fint *op, MPI_Fint *win, MPI_Fint *request, MPI_Fint *ierr), (origin_addr, origin_count, origin_datatype, target_rank, target_disp, target_count, target_datatype, op, win, request, ierr) ) #else #define ompi_raccumulate_f pompi_raccumulate_f #endif #endif void ompi_raccumulate_f(char *origin_addr, MPI_Fint *origin_count, MPI_Fint *origin_datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *target_count, MPI_Fint *target_datatype, MPI_Fint *op, MPI_Fint *win, MPI_Fint *request, MPI_Fint *ierr) { int ierr_c; MPI_Datatype c_origin_datatype = PMPI_Type_f2c(*origin_datatype); MPI_Datatype c_target_datatype = PMPI_Type_f2c(*target_datatype); MPI_Win c_win = PMPI_Win_f2c(*win); MPI_Op c_op = PMPI_Op_f2c(*op); MPI_Request c_req; ierr_c = PMPI_Raccumulate(OMPI_F2C_BOTTOM(origin_addr), OMPI_FINT_2_INT(*origin_count), c_origin_datatype, OMPI_FINT_2_INT(*target_rank), *target_disp, OMPI_FINT_2_INT(*target_count), c_target_datatype, c_op, c_win, &c_req); if (NULL != ierr) *ierr = OMPI_INT_2_FINT(ierr_c); if (MPI_SUCCESS == ierr_c) { *request = PMPI_Request_c2f(c_req); } }
2,445
382
# coding: utf-8 """ joplin-web """ from django.conf import settings from django.urls import reverse from joplin_api import JoplinApiSync import logging from rich import console console = console.Console() logger = logging.getLogger("joplin_web.app") joplin = JoplinApiSync(token=settings.JOPLIN_WEBCLIPPER_TOKEN) def tags_to_string(my_tags): """ tags list to string with all tags :param my_tags: list :return string """ tags = '' for tag in my_tags: tags += tag if len(my_tags) > 1: tags += ',' return tags def tag_for_notes(data): """ alter the original data to add the tag related to the note :param data: data list :return: json """ payload = [] for note in data.json(): tag = joplin.get_notes_tags(note['id']) new_note = note new_note['tag'] = tag.json() if tag else '' payload.append(new_note) logger.debug(payload) return payload def nb_notes_by_tag(tags): """ get the number of notes in each tag :param tags: tags list :return: """ data = [] # get the number of notes of each tag, if any for tag in tags: nb_notes = 0 res_tags_notes = joplin.get_tags_notes(tag['id']) if len(res_tags_notes.json()): nb_notes = len(res_tags_notes.json()) item = dict() item['nb_notes'] = nb_notes item['text'] = f"{tag['title']} ({nb_notes})" item['href'] = reverse('notes_tag', args=[tag['id']]) data.append(item) logger.debug(data) return data def nb_notes_by_folder(folders): """ get the number of notes in each folder :param folders: folders list :return: json """ data = [] # get the number of notes of each folder, if any for folder in folders: nb_notes = 0 res_folders_notes = joplin.get_folders_notes(folder['id']) if len(res_folders_notes.json()): nb_notes = len(res_folders_notes.json()) # item = folder item = dict() item['nb_notes'] = nb_notes item['text'] = f"{folder['title']} ({nb_notes})" item['href'] = reverse('notes_folder', args=[folder['id']]) if 'children' in folder: # due to bstreeview, need to adapt data # children = nodes # title = text children = nb_notes_by_folder(folder['children']) item['nodes'] = children data.append(item) logger.debug(data) return data
1,119
348
<gh_stars>100-1000 {"nom":"Miribel","circ":"2ème circonscription","dpt":"Ain","inscrits":6793,"abs":4069,"votants":2724,"blancs":168,"nuls":49,"exp":2507,"res":[{"nuance":"MDM","nom":"<NAME>","voix":1340},{"nuance":"LR","nom":"<NAME>","voix":1167}]}
103
343
<filename>magnet/utils/__init__.py from ._node import summarize
19
335
<reponame>duruyi/rb<filename>rb/testing.py import os import time import uuid import shutil import socket import tempfile from contextlib import contextmanager from subprocess import Popen, PIPE from rb.cluster import Cluster from rb.utils import itervalues devnull = open(os.devnull, "r+") class Server(object): def __init__(self, cl, socket_path): self._cl = cl self.socket_path = socket_path def test_connection(self): try: s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) s.connect(self.socket_path) except IOError: return False return True def signal_stop(self): if self._cl is not None: self._cl.kill() def close(self): if self._cl is not None: self.signal_stop() self._cl.wait() self._cl = None try: os.remove(self.socket_path) except OSError: pass class TestSetup(object): """The test setup is a convenient way to spawn multiple redis servers for testing and to shut them down automatically. This can be used as a context manager to automatically terminate the clients. """ def __init__(self, servers=4, databases_each=8, server_executable="redis-server"): self._fd_dir = tempfile.mkdtemp() self.databases_each = databases_each self.server_executable = server_executable self.servers = [] for server in range(servers): self.spawn_server() def __enter__(self): return self def __exit__(self, exc_type, exc_value, tb): self.close() def make_cluster(self): """Creates a correctly configured cluster from the servers spawned. This also automatically waits for the servers to be up. """ self.wait_for_servers() hosts = [] host_id = 0 for server in self.servers: for x in range(self.databases_each): hosts.append( { "host_id": host_id, "unix_socket_path": server.socket_path, "db": x, } ) host_id += 1 return Cluster( hosts, pool_options={"encoding": "utf-8", "decode_responses": True} ) def spawn_server(self): """Spawns a new server and adds it to the pool.""" socket_path = os.path.join(self._fd_dir, str(uuid.uuid4())) cl = Popen([self.server_executable, "-"], stdin=PIPE, stdout=devnull) cl.stdin.write( ( """ port 0 unixsocket %(path)s databases %(databases)d save "" """ % {"path": socket_path, "databases": self.databases_each,} ).encode("utf-8") ) cl.stdin.flush() cl.stdin.close() self.servers.append(Server(cl, socket_path)) def wait_for_servers(self, timeout=10): """Waits for all servers to to be up and running.""" unconnected_servers = dict((x.socket_path, x) for x in self.servers) now = time.time() while unconnected_servers: for server in itervalues(unconnected_servers): if server.test_connection(): unconnected_servers.pop(server.socket_path, None) break if time.time() > now + timeout: return False if unconnected_servers: time.sleep(0.05) return True def close(self): """Closes the test setup which shuts down all redis servers.""" for server in self.servers: server.signal_stop() for server in self.servers: server.close() try: shutil.rmtree(self._fd_dir) except (OSError, IOError): pass def __del__(self): try: self.close() except Exception: pass @contextmanager def make_test_cluster(*args, **kwargs): """Convenient shortcut for creating a test setup and then a cluster from it. This must be used as a context manager:: from rb.testing import make_test_cluster with make_test_cluster() as cluster: ... """ with TestSetup(*args, **kwargs) as ts: cluster = ts.make_cluster() try: yield cluster finally: cluster.disconnect_pools()
2,149
416
<gh_stars>100-1000 package org.springframework.roo.classpath.layers; /** * Convenience class for addon developers wishing to implement their own * {@link LayerProvider}. * * @author <NAME> * @author <NAME> * @since 1.2.0 */ public abstract class LayerAdapter implements LayerProvider { @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final LayerProvider other = (LayerProvider) obj; return getLayerPosition() == other.getLayerPosition(); } @Override public int hashCode() { return getLayerPosition(); } }
242
352
import sys import re from ._common import exec_in_terminal PLATFORM = sys.platform def available_cpus(): """ Detects the number of logical CPUs subscriptable by this process. On Linux, this checks /proc/self/status for limits set by taskset, on other platforms taskset do not exist so simply uses multiprocessing. This should be a good estimate of how many cpu cores Jax/XLA sees. """ if PLATFORM.startswith("linux"): try: m = re.search( r"(?m)^Cpus_allowed:\s*(.*)$", open("/proc/self/status").read() ) if m: res = bin(int(m.group(1).replace(",", ""), 16)).count("1") if res > 0: return res except IOError: pass else: import multiprocessing return multiprocessing.cpu_count() ## Taken from https://github.com/matthew-brett/x86cpu/blob/530f89f678aba501381e94be5325b9c91b878a32/x86cpu/tests/info_getters.py#L24 ## SYSCTL_KEY_TRANSLATIONS = dict( model="model_display", family="family_display", extmodel="extended_model", extfamily="extended_family", ) SYSCTL_FLAG_TRANSLATIONS = { "sse4.1": "sse4_1", "sse4.2": "sse4_2", } def cpu_info(): if PLATFORM.startswith("darwin"): return get_sysctl_cpu() elif PLATFORM.startswith("linux"): return get_proc_cpuinfo() else: raise ValueError(f"Unsupported platform {PLATFORM}") def get_sysctl_cpu(): sysctl_text = exec_in_terminal(["sysctl", "-a"]) info = {} for line in sysctl_text.splitlines(): if not line.startswith("machdep.cpu."): continue line = line.strip()[len("machdep.cpu.") :] key, value = line.split(": ", 1) key = SYSCTL_KEY_TRANSLATIONS.get(key, key) try: value = int(value) except ValueError: pass info[key] = value flags = [flag.lower() for flag in info["features"].split()] info["flags"] = [SYSCTL_FLAG_TRANSLATIONS.get(flag, flag) for flag in flags] info["unknown_flags"] = ["3dnow"] info["supports_avx"] = "hw.optional.avx1_0: 1\n" in sysctl_text info["supports_avx2"] = "hw.optionxwal.avx2_0: 1\n" in sysctl_text return info PCPUINFO_KEY_TRANSLATIONS = { "vendor_id": "vendor", "model": "model_display", "family": "family_display", "model name": "brand", } def get_proc_cpuinfo(): with open("/proc/cpuinfo", "rt") as fobj: pci_lines = fobj.readlines() info = {} for line in pci_lines: line = line.strip() if line == "": # End of first processor break key, value = line.split(":", 1) key, value = key.strip(), value.strip() key = PCPUINFO_KEY_TRANSLATIONS.get(key, key) try: value = int(value) except ValueError: pass info[key] = value info["flags"] = info["flags"].split() # cpuinfo records presence of Prescott New Instructions, Intel's code name # for SSE3. if "pni" in info["flags"]: info["flags"].append("sse3") info["unknown_flags"] = ["3dnow"] info["supports_avx"] = "avx" in info["flags"] info["supports_avx2"] = "avx2" in info["flags"] return info
1,510
1,025
<gh_stars>1000+ //================================================================================== // Copyright (c) 2016 , Advanced Micro Devices, Inc. All rights reserved. // /// \author AMD Developer Tools Team /// \file gsOpenGLMonitor.cpp /// //================================================================================== //------------------------------ gsOpenGLMonitor.cpp ------------------------------ // Infra: #include <AMDTBaseTools/Include/gtAssert.h> #include <AMDTBaseTools/Include/AMDTDefinitions.h> #include <AMDTBaseTools/Include/gtIgnoreCompilerWarnings.h> #include <AMDTOSWrappers/Include/osCriticalSectionLocker.h> #include <AMDTOSWrappers/Include/osDebuggingFunctions.h> #include <AMDTOSWrappers/Include/osDebugLog.h> #include <AMDTOSWrappers/Include/osOSDefinitions.h> #include <AMDTAPIClasses/Include/apCounterID.h> #include <AMDTOSWrappers/Include/osThread.h> #include <AMDTOSWrappers/Include/osTime.h> #include <AMDTAPIClasses/Include/apDefinitions.h> #include <AMDTAPIClasses/Include/apMonitoredFunctionsManager.h> #include <AMDTAPIClasses/Include/Events/apContextDataSnapshotWasUpdatedEvent.h> #include <AMDTAPIClasses/Include/Events/apRenderContextCreatedEvent.h> #include <AMDTAPIClasses/Include/Events/apRenderContextDeletedEvent.h> #include <AMDTServerUtilities/Include/suBreakpointsManager.h> #include <AMDTServerUtilities/Include/suGlobalVariables.h> #include <AMDTServerUtilities/Include/suSpyAPIFunctions.h> #include <AMDTServerUtilities/Include/suSlowMotionDelay.h> // Local: #include <src/gsGLDebugOutputManager.h> #include <src/gsExtensionsManager.h> #include <src/gsMonitoredFunctionPointers.h> #include <src/gsOpenGLMonitor.h> #include <src/gsOpenGLSpyInitFuncs.h> #include <src/gsStringConstants.h> #include <src/gsWrappersCommon.h> #include <src/gsMemoryMonitor.h> // For debugging purposes: #include <src/gsAPIFunctionsImplementations.h> #if ((AMDT_BUILD_TARGET == AMDT_LINUX_OS) && (AMDT_LINUX_VARIANT == AMDT_GENERIC_LINUX_VARIANT)) // Linux generic only stuff: #include <X11/Xlib.h> #elif ((AMDT_BUILD_TARGET == AMDT_LINUX_OS) && (AMDT_LINUX_VARIANT == AMDT_MAC_OS_X_LINUX_VARIANT)) // According to Kent Miller from apple, we should use these instead of the regular ones // since they ignore the dispatch and run faster. The equivalents are 310 and 311 // respectively (same names, without the "NoDispatch"). #define kCGLCPGPUVertexProcessingNoDispatch ((CGLContextParameter)1310) #define kCGLCPGPUFragmentProcessingNoDispatch ((CGLContextParameter)1311) #ifdef _GR_IPHONE_BUILD #include <src/gsEAGLWrappers.h> #ifdef _GR_IPHONE_DEVICE_BUILD #include <AMDTServerUtilities/Include/suSpyBreakpointImplementation.h> #endif #endif #elif (AMDT_BUILD_TARGET == AMDT_WINDOWS_OS) #if AMDT_ADDRESS_SPACE_TYPE == AMDT_64_BIT_ADDRESS_SPACE #include <intrin.h> #endif #endif // Static members initializations: gsOpenGLMonitor* gsOpenGLMonitor::_pMySingleInstance = NULL; // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::instance // Description: Returns the single instance of the gsOpenGLMonitor class // Author: <NAME> // Date: 5/7/2003 // --------------------------------------------------------------------------- gsOpenGLMonitor& gsOpenGLMonitor::instance() { if (_pMySingleInstance == NULL) { // Make sure we're not creating ourselves twice: static bool onlyOnce = true; GT_ASSERT(onlyOnce); onlyOnce = false; _pMySingleInstance = new gsOpenGLMonitor; GT_ASSERT(_pMySingleInstance); _pMySingleInstance->initialize(); } return *_pMySingleInstance; } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::gsOpenGLMonitor // Description: Constructor. // Author: <NAME> // Date: 11/5/2004 // --------------------------------------------------------------------------- gsOpenGLMonitor::gsOpenGLMonitor() : suITechnologyMonitor(), _wasOpenGLServerInitialized(false), #if AMDT_BUILD_TARGET == AMDT_WINDOWS_OS #ifdef OA_DEBUGGER_USE_AMD_GPA _ATIPerformanceCountersMgr(_shouldInitializePerformanceCounters), #endif #endif _openGLError(GL_NO_ERROR), _isOpenGLFlushForced(false), _isInteractiveBreakOn(true), _isDuringDebuggedProcessTermination(false) { } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::initialize // Description: Initialize function - this is called by the instance() function after // creating the single instance. Any initializations that requires // gsOpenGLMonitor::instance() should be done here (or the assert inside // instance() will trigger). // Author: <NAME> // Date: 4/9/2012 // --------------------------------------------------------------------------- void gsOpenGLMonitor::initialize() { // Initialize generic breakpoints - generic breakpoints are initialized before the monitors // are initialized. At this stage the monitor should check the status of each generic breakpoint // and set it. This must be done here, and not in base class since onGenericBreakpointSet is a virtual function: for (int i = (int)AP_BREAK_ON_GL_ERROR; i < (int)AP_AMOUNT_OF_GENERIC_BREAKPOINT_TYPES; i++) { // Check if the generic type is on: apGenericBreakpointType genericType = (apGenericBreakpointType)i; bool isOn = suBreakpointsManager::instance().breakOnGenericBreakpoint(genericType); onGenericBreakpointSet(genericType, isOn); } } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::~gsOpenGLMonitor // Description: Destructor. // Author: <NAME> // Date: 11/5/2004 // --------------------------------------------------------------------------- gsOpenGLMonitor::~gsOpenGLMonitor() { if (_shouldInitializePerformanceCounters) { #if (AMDT_BUILD_TARGET == AMDT_WINDOWS_OS) #ifdef OA_DEBUGGER_USE_AMD_GPA { bool rc = _ATIPerformanceCountersMgr.terminate(); GT_ASSERT(rc); } #endif #endif } // The OpenGL monitor is only destroyed during the OpenGL spy termination: bool rcTer = gsPerformOpenGLMonitorTerminationActions(); GT_ASSERT(rcTer); } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::onDebuggedProcessTerminationAlert // Description: Is called before the debugged process or this DLL is terminated. // Author: <NAME> // Date: 25/1/2005 // --------------------------------------------------------------------------- void gsOpenGLMonitor::onDebuggedProcessTerminationAlert() { // Only perform these operations once: if (!_isDuringDebuggedProcessTermination) { // Mark the debugged process is being terminated: _isDuringDebuggedProcessTermination = true; // Notify the render context monitors: int noOfRenderContexts = (int)_contextsMonitors.size(); for (int i = 0; i < noOfRenderContexts; i++) { _contextsMonitors[i]->onDebuggedProcessTerminationAlert(); } // Notify the OpenGL context monitors: for (int i = 1; i < noOfRenderContexts; i++) { // Mark the render context texture as not updated: gsRenderContextMonitor* pContextMonitor = renderContextMonitor(i); if (pContextMonitor != NULL) { pContextMonitor->markTextureParametersAsNonUpdated(); } } } } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::beforeDebuggedProcessSuspended // Description: Called before the debugged process is suspended // Author: <NAME> // Date: 10/12/2009 // --------------------------------------------------------------------------- void gsOpenGLMonitor::beforeDebuggedProcessSuspended() { } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::afterDebuggedProcessResumed // Description: Called once the debugged process is resumed from suspension. // Author: <NAME> // Date: 10/12/2009 // --------------------------------------------------------------------------- void gsOpenGLMonitor::afterDebuggedProcessResumed() { } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::beforeBreakpointException // Description: Called by a thread before a breakpoint exception is thrown by it // Author: <NAME> // Date: 13/12/2009 // --------------------------------------------------------------------------- void gsOpenGLMonitor::beforeBreakpointException(bool isInOpenGLBeginEndBlock) { // If "Interactive break" mode is on (and we are not in a glBegin-glEnd block or the process termination): if (_isInteractiveBreakOn && !isInOpenGLBeginEndBlock && !_isDuringDebuggedProcessTermination) { // Display the current render context content to the user: displayCurrentRenderContextContent(); } } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::afterBreakpointException // Description: Called by a thread after a breakpoint exception it threw is passed // Author: <NAME> // Date: 13/12/2009 // --------------------------------------------------------------------------- void gsOpenGLMonitor::afterBreakpointException(bool isInOpenGLBeginEndBlock) { // If "Interactive break" mode is on (and we are not in a glBegin-glEnd block or the process termination): if (_isInteractiveBreakOn && !isInOpenGLBeginEndBlock && !_isDuringDebuggedProcessTermination) { // After getting back from the breakpoint, we need to call displayCurrentRenderContextContent() again, // since when running on graphic boards that implement "real SwapBuffers" (not implementing SwapBuffers // by copy), we need to return the buffers to the state they were before the breakpoint exception: displayCurrentRenderContextContent(); } // Clear OpenGL error: // (If we are here, it means that the debugger resumed the debugged process run). _openGLError = GL_NO_ERROR; } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::onDebuggedProcessExecutionModeChanged // Description: Called when the debugged process execution mode is changed to newExecutionMode // Author: <NAME> // Date: 22/12/2009 // --------------------------------------------------------------------------- void gsOpenGLMonitor::onDebuggedProcessExecutionModeChanged(apExecutionMode newExecutionMode) { if (newExecutionMode == AP_PROFILING_MODE) { // We just changed to Profile Mode, clear the calls statistics: int amountOfContexts = (int)_contextsMonitors.size(); for (int i = 0; i < amountOfContexts; i++) { gsRenderContextMonitor* pContextMonitor = renderContextMonitor(i); if (pContextMonitor != NULL) { pContextMonitor->callsStatisticsLogger().clearFunctionCallsStatistics(); } } } } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::onBeforeKernelDebugging // Description: When we're within a kernel debugging session, we cannot update // context data snapshot. Therefore, we go through all the existing // contexts before the kernel debugging, and update them. // Author: <NAME> // Date: 5/4/2011 // --------------------------------------------------------------------------- void gsOpenGLMonitor::onBeforeKernelDebugging() { // Go through each of the context monitors: int amountOfContexts = (int)_contextsMonitors.size(); for (int i = 1; i < amountOfContexts; i++) { gsRenderContextMonitor* pContextMonitor = renderContextMonitor(i); GT_IF_WITH_ASSERT(pContextMonitor != NULL) { // If the context was not deleted, update its data snapshot: if (!pContextMonitor->wasDeleted()) { // Make the input render context the API thread's current render context: (void) gs_stat_openGLMonitorInstance.currentThreadRenderContextSpyId(); bool rcMakeCurrent = gsMakeRenderContextCurrent(i); GT_IF_WITH_ASSERT(rcMakeCurrent) { // Update the context's data snapshot: bool rcUpdateSnapshot = pContextMonitor->updateContextDataSnapshot(); GT_ASSERT(rcUpdateSnapshot); // Get its static buffers monitor, and update the static buffer: gsStaticBuffersMonitor& buffersMtr = pContextMonitor->buffersMonitor(); bool rcUpdateDims = buffersMtr.updateStaticBuffersDimensions(); GT_ASSERT(rcUpdateDims); // Report the context snapshot: apContextDataSnapshotWasUpdatedEvent contextUpdatedEvent(apContextID(AP_OPENGL_CONTEXT, i), false); bool rcEve = suForwardEventToClient(contextUpdatedEvent); GT_ASSERT(rcEve); } } } } } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::threadCurrentRenderContext // Description: Inputs a thread id and returns its current render context id. // Arguments - threadId - The input thread id. // Return Val: int - The output render context id, or 0 if the input thread // does not have a current render context. // Author: <NAME> // Date: 5/5/2005 // --------------------------------------------------------------------------- int gsOpenGLMonitor::threadCurrentRenderContext(const osThreadId& threadId) const { int retVal = _threadsMonitor.threadCurrentRenderContext(threadId); return retVal; } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::renderContextCurrentThread // Description: Inputs a render context and outputs the thread that uses this // render context as "current render context". // Arguments: renderContextId - The input render context spy id. // Return Val: osThreadId - The output thread id, or OS_NO_THREAD_ID if no thread // uses the input render context as "current render context". // Author: <NAME> // Date: 31/1/2008 // --------------------------------------------------------------------------- osThreadId gsOpenGLMonitor::renderContextCurrentThread(int renderContextId) const { osThreadId retVal = _threadsMonitor.renderContextCurrentThread(renderContextId); return retVal; } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::onContextCreation // Description: // Is called when a render context is created. // Adds a render context to the list of OpenGL render contexts created by the // debugged application. // Arguments: // pDeviceContext - The render context device context. // pRenderContext - The render context handle. // const int* attribList - the render context attributes list // bool isDebugFlagForced - true iff CodeXL forced a debug bit on / off // Author: <NAME> // Date: 12/5/2004 // --------------------------------------------------------------------------- void gsOpenGLMonitor::onContextCreation(oaDeviceContextHandle pDeviceContext, oaOpenGLRenderContextHandle pRenderContext, apMonitoredFunctionId creationFunc, const int* attribList, bool isDebugFlagForced) { // Lock the critical section that controls the access to _contextsMonitors osCriticalSectionLocker criticalSectionLocker(_renderContextsMonitorsCS); // Calculate the context Spy id: int contextSpyId = (int)_contextsMonitors.size(); // Create a render context monitor: gsRenderContextMonitor* pNewRenderContextMonitor = new gsRenderContextMonitor(contextSpyId, pDeviceContext, pRenderContext, _shouldInitializePerformanceCounters, creationFunc, attribList, isDebugFlagForced); // Add the new context data to the _contextsMonitors vector: _contextsMonitors.push_back(pNewRenderContextMonitor); // Initialize the render context monitor: initializeRenderContextMonitor(*pNewRenderContextMonitor); // Leave the critical section: criticalSectionLocker.leaveCriticalSection(); // Output debug message: gtString debugMsg; debugMsg.appendFormattedString(GS_STR_renderContextWasCreated, contextSpyId); GT_IF_WITH_ASSERT(apMonitoredFunctionsAmount > creationFunc) { debugMsg.append(L" (").append(apMonitoredFunctionsManager::instance().monitoredFunctionName(creationFunc)).append(')'); } OS_OUTPUT_DEBUG_LOG(debugMsg.asCharArray(), OS_DEBUG_LOG_INFO); if (_shouldInitializePerformanceCounters) { // Notify other classes about the context creation event: _spyPerformanceCountersMgr.onContextCreatedEvent(contextSpyId); #if (AMDT_BUILD_TARGET == AMDT_WINDOWS_OS) #ifdef OA_DEBUGGER_USE_AMD_GPA { _ATIPerformanceCountersMgr.onContextCreatedEvent(contextSpyId); } #endif #endif } gsExtensionsManager& theExtensionsMgr = gsExtensionsManager::instance(); theExtensionsMgr.onContextCreatedEvent(contextSpyId); // Notify the debugger about the context creation: osThreadId currentThreadId = osGetCurrentThreadId(); apRenderContextCreatedEvent renderContextCreatedEvent(currentThreadId, contextSpyId); bool rcEve = suForwardEventToClient(renderContextCreatedEvent); GT_ASSERT(rcEve); } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::beforeContextDeletion // Description: Is called when a render context is about to be deleted. Note // that this function comes before the actual call to gl..DeleteContext // Author: <NAME> // Date: 11/11/2008 // --------------------------------------------------------------------------- void gsOpenGLMonitor::beforeContextDeletion(oaOpenGLRenderContextHandle pRenderContext) { // Search for the deleted context spy id: int deletedContextSpyId = renderContextSpyId(pRenderContext); // If we didn't find the input context: GT_IF_WITH_ASSERT_EX((deletedContextSpyId > 0), GS_STR_UnkownContextHandleUsed) { // Get the current execution mode: apExecutionMode debuggedProcessExecutionMode = suDebuggedProcessExecutionMode(); if (debuggedProcessExecutionMode != AP_PROFILING_MODE) { // Check if this is the last context using allocated objects: int contextsAmount = amountOfContexts(); unsigned int numberOfContextsWithSameLists = 0; int sharedContext = deletedContextSpyId; replaceContextIDWithListHolder(sharedContext); const gsRenderContextMonitor* pDeletedContextMonitor = NULL; for (int i = 1; i < contextsAmount; i++) { int currentContextShared = i; replaceContextIDWithListHolder(currentContextShared); const gsRenderContextMonitor* pCurrentRC = renderContextMonitor(i); GT_IF_WITH_ASSERT(pCurrentRC != NULL) { if (currentContextShared == sharedContext) { // Only count RCs that weren't already deleted: if (!pCurrentRC->wasDeleted()) { numberOfContextsWithSameLists++; } } // While we are running through the OpenGL Monitors, we need to notify // the one about to be deleted that it is about to be deleted: if (i == deletedContextSpyId) { // Perform before context deletion actions: pDeletedContextMonitor = pCurrentRC; } } } // We should have at least one context sharing the same lists - the context we deleted. GT_ASSERT(numberOfContextsWithSameLists > 0); GT_IF_WITH_ASSERT(pDeletedContextMonitor != NULL) { pDeletedContextMonitor->beforeContextDeletion(); } // If this is the last context holding these lists: if (numberOfContextsWithSameLists == 1) { // Handle memory leak check: apContextID deleteContextID(AP_OPENGL_CONTEXT, deletedContextSpyId); gsMemoryMonitor::instance().beforeContextDeletion(deleteContextID); } } // Output debug message: gtString debugMsg; debugMsg.appendFormattedString(GS_STR_renderContextAboutToBeDeleted, deletedContextSpyId); OS_OUTPUT_DEBUG_LOG(debugMsg.asCharArray(), OS_DEBUG_LOG_INFO); // Notify the debugger about the context deletion: osThreadId currentThreadId = osGetCurrentThreadId(); apRenderContextDeletedEvent renderContextDeletedEvent(currentThreadId, deletedContextSpyId); bool rcEve = suForwardEventToClient(renderContextDeletedEvent); GT_ASSERT(rcEve); } } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::afterContextDeletion // Description: Is called after a render context is deleted. Note that in windows, // this function is called only if the call to wglDeleteContext is // successful. // Arguments: pRenderContext - The render context win32 HGLRC // Author: <NAME> // Date: 27/7/2005 // --------------------------------------------------------------------------- void gsOpenGLMonitor::afterContextDeletion(oaOpenGLRenderContextHandle pRenderContext) { // Search for the deleted context spy id: int deletedContextSpyId = renderContextSpyId(pRenderContext); // If we didn't find the input context: GT_IF_WITH_ASSERT_EX((deletedContextSpyId > 0), GS_STR_UnkownContextHandleUsed) { #if AMDT_BUILD_TARGET == AMDT_WINDOWS_OS // Remove the context from being a current context of any thread: _threadsMonitor.removeRenderContextFromAllThreads(pRenderContext); #endif if (_shouldInitializePerformanceCounters) { // Notify the spy performance counters manager about the context deletion event: _spyPerformanceCountersMgr.onContextDeletedEvent(deletedContextSpyId); #if (AMDT_BUILD_TARGET == AMDT_WINDOWS_OS) #ifdef OA_DEBUGGER_USE_AMD_GPA { // Notify the ATI performance counters manager about the context deletion event: _ATIPerformanceCountersMgr.onContextDeletedEvent(deletedContextSpyId); } #endif #endif } // Notify the render context monitor about the context deletion event: gsRenderContextMonitor* pContextMonitor = renderContextMonitor(deletedContextSpyId); GT_IF_WITH_ASSERT(pContextMonitor != NULL) { pContextMonitor->onContextDeletion(); } // Output debug message: gtString debugMsg; debugMsg.appendFormattedString(GS_STR_renderContextWasDeleted, deletedContextSpyId); OS_OUTPUT_DEBUG_LOG(debugMsg.asCharArray(), OS_DEBUG_LOG_INFO); // Notice: // We don't delete the render context monitor since we would like // to keep its data (calls history log, etc)). } } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::currentThreadRenderContextSpyId // Description: Returns the current render context of the calling thread. // Return Val: int - Will get the spy id of the render context that is the // "current render context" of the thread that called this function. // Author: <NAME> // Date: 6/11/2005 // --------------------------------------------------------------------------- int gsOpenGLMonitor::currentThreadRenderContextSpyId() const { int retVal = _threadsMonitor.currentThreadRenderContextSpyId(); return retVal; } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::beforeContextMadeCurrent // Description: Is called before a new context is made the current context // of the calling thread. // Arguments: pRenderContext - The context that is going to be the new // "current context" of the calling thread. // Author: <NAME> // Date: 3/11/2005 // --------------------------------------------------------------------------- void gsOpenGLMonitor::beforeContextMadeCurrent(oaOpenGLRenderContextHandle hRC) { // Get the "old" render context of the calling thread: int oldContextId = currentThreadRenderContextSpyId(); // If this is a real context: if (0 < oldContextId) { // Will get the input context spy id: int newContextId = 0; // if this input context is the NULL context: void* phRC = (void*)hRC; if (phRC == NULL) { newContextId = 0; } else { // Get the input context spy id: newContextId = renderContextSpyId(hRC); if (newContextId == -1) { // Error: Unrecognized context: newContextId = 0; GT_ASSERT_EX(0, GS_STR_UnkownContextHandleUsed); } } // It this is a "real" context change: if (oldContextId != newContextId) { gsRenderContextMonitor* pContextMonitor = renderContextMonitor(oldContextId); GT_IF_WITH_ASSERT(pContextMonitor != NULL) { // Notify the context that it was removed from being the current context of a thread: pContextMonitor->onContextRemovedFromBeingCurrent(); } } } } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::onContextMadeCurrent // Description: // Is called when the debugged application makes a context the active context // of the current thread. // Arguments: hDC - OS handle of the device context of the draw surface. // draw - The drawable into which OpenGL will draw. // read - The drawable from which OpenGL will read. // hRC - The render context OS handle. // Author: <NAME> // Date: 12/5/2004 // Implementation Notes: // We expect: // - The amount of contexts to be low. // - The amount of active context switches to be low. // --------------------------------------------------------------------------- void gsOpenGLMonitor::onContextMadeCurrent(oaDeviceContextHandle hDC, oaDrawableHandle draw, oaDrawableHandle read, oaOpenGLRenderContextHandle hRC) { // Will get the input context spy id: int contextId = 0; // If this is a real context: void* phRC = (void*)hRC; if (phRC != NULL) { // Get the context spy id: contextId = renderContextSpyId(hRC); } // If this is not a registered context: if (contextId == -1) { // Mark that this thread uses an unknown context: contextId = AP_NULL_CONTEXT_ID; // Trigger an assertion: GT_ASSERT_EX(0, GS_STR_UnkownContextHandleUsed); } // Log the current thread context id: _threadsMonitor.setCurrentThreadCurrentContext(hDC, draw, read, contextId); if (contextId != AP_NULL_CONTEXT_ID) { // Notify the context monitor that its context became the active context: gsRenderContextMonitor* pContextMonitor = renderContextMonitor(contextId); GT_IF_WITH_ASSERT(pContextMonitor != NULL) { pContextMonitor->onContextMadeCurrent(hDC); } } // Also update the TLS, if possible: gsUpdateTLSVariableValues(); } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::onFrameTerminatorCall // Description: Is called when a frame terminator function is called. // Author: <NAME> // Date: 13/3/2006 // --------------------------------------------------------------------------- void gsOpenGLMonitor::onFrameTerminatorCall() { // In profile mode, we do the checks here instead of in addFunctionCall() // to slow down execution less often: su_stat_theBreakpointsManager.waitOnDebuggedProcessSuspension(); // Get the current thread render context monitor: suContextMonitor* pCurrentThreadRenderContextMonitor = currentThreadContextMonitor(); if (pCurrentThreadRenderContextMonitor) { // If we are supposed to break on the next frame terminator: if (su_stat_theBreakpointsManager.breakAtTheNextFrame()) { // clear the flag: su_stat_theBreakpointsManager.setBreakAtTheNextFrame(false); // break the execution (frame terminators will never be in a begin-end block): triggerBreakpointException(AP_FRAME_BREAKPOINT_HIT, GL_NO_ERROR, false); } // Notify the render context monitor: pCurrentThreadRenderContextMonitor->onFrameTerminatorCall(); // If we are in profiling mode: apExecutionMode debuggedProcessExecutionMode = suDebuggedProcessExecutionMode(); if (debuggedProcessExecutionMode == AP_PROFILING_MODE) { // If we should break the debugged process execution: if (su_stat_theBreakpointsManager.isBreakDebuggedProcessExecutionFlagOn()) { // Break the debugged process execution: apContextID contextId(AP_OPENGL_CONTEXT, currentThreadRenderContextSpyId()); su_stat_theBreakpointsManager.testAndTriggerBeforeFuncExecutionBreakpoints(ap_glClear, contextId); } } } } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::verifyOpenGLServerInitialized // Description: Makes sure the OpenGL server is initialized. // Author: <NAME> // Date: 29/6/2016 // --------------------------------------------------------------------------- void gsOpenGLMonitor::verifyOpenGLServerInitialized() { // If the OpenGL Server was not initialized yet, initialize it: if (!_wasOpenGLServerInitialized) { bool rcSpyInit = gsOpenGLSpyInit(); GT_ASSERT(rcSpyInit); _wasOpenGLServerInitialized = true; } } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::renderContextDeviceContext // Description: Returns the device context of a given render context. // Author: <NAME> // Date: 6/9/2004 // --------------------------------------------------------------------------- void* gsOpenGLMonitor::renderContextDeviceContext(int renderContextId) { void* retVal = NULL; // Sanity test: int renderContextsAmount = amountOfContexts(); if ((0 < renderContextId) && (renderContextId < renderContextsAmount)) { gsRenderContextMonitor* pContextMonitor = renderContextMonitor(renderContextId); GT_IF_WITH_ASSERT(pContextMonitor != NULL) { pContextMonitor->deviceContextOSHandle(); } } return retVal; } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::renderContextPixelFormat // Description: Inputs a render context and returns its selected pixel format. // Arguments: renderContextId - The render context spy id. // Return Val: int - Will get the pixel format OS id. // (Or -1 in case of failure) // Author: <NAME> // Date: 6/9/2004 // --------------------------------------------------------------------------- oaPixelFormatId gsOpenGLMonitor::renderContextPixelFormat(int renderContextId) { oaPixelFormatId retVal = OA_NO_PIXEL_FORMAT_ID; // Sanity test: int renderContextsAmount = amountOfContexts(); if ((0 < renderContextId) && (renderContextId < renderContextsAmount)) { gsRenderContextMonitor* pContextMonitor = renderContextMonitor(renderContextId); GT_IF_WITH_ASSERT(pContextMonitor != NULL) { retVal = pContextMonitor->pixelFormatId(); } } return retVal; } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::onShareLists // Description: // Arguments: a - the context "giving" the list // b - the context "taking" the list // This is supposed to share display lists, VBOs/IBOs, programs + shaders, // textures, FBOs, PBOs // Author: <NAME> // Date: 11/6/2008 // --------------------------------------------------------------------------- void gsOpenGLMonitor::onShareLists(oaOpenGLRenderContextHandle firstContextHandle, oaOpenGLRenderContextHandle secondContextHandle) { // Get render context spy ids: int firstContextSpyId = renderContextSpyId(firstContextHandle); int secondContextSpyId = renderContextSpyId(secondContextHandle); // Get the first and second context monitors: gsRenderContextMonitor* pFirstContextMonitor = renderContextMonitor(firstContextSpyId); gsRenderContextMonitor* pSecondContextMonitor = renderContextMonitor(secondContextSpyId); GT_IF_WITH_ASSERT((firstContextSpyId > 0) && (secondContextSpyId > 0) && (pSecondContextMonitor != NULL) && (pFirstContextMonitor != NULL)) { // Get the second context sharing object id: int secondObjectSharingContextID = pSecondContextMonitor->getObjectSharingContextID(); gsRenderContextMonitor* pSecondObjectSharingContextIDMonitor = renderContextMonitor(secondObjectSharingContextID); // If we try to get the list from a context which itself shares a list, we go directly to the // source rather than have a chain. replaceContextIDWithListHolder(secondContextSpyId); // If we're using circular logic (eg 1->2 and then 2->1), ignore the command as it's ineffective. if (firstContextSpyId != secondContextSpyId) { // Set this render context to point at the other one pSecondContextMonitor->setObjectSharingContext(firstContextSpyId, pFirstContextMonitor, true); // If the we pointed to another context before, update it on the change: if (pSecondObjectSharingContextIDMonitor != NULL) { pSecondObjectSharingContextIDMonitor->setObjectSharingContext(firstContextSpyId, pFirstContextMonitor); } // Make sure that render contexts pointing to us or the context we pointed to are notified: int numberOfRCs = (int)_contextsMonitors.size(); for (int l = 1; l < numberOfRCs; l++) { // Get curret render context monitor: gsRenderContextMonitor* pCurrentContextMonitor = renderContextMonitor(l); int lp = pCurrentContextMonitor->getObjectSharingContextID(); if ((lp == secondContextSpyId) || ((secondObjectSharingContextID != -1) && (lp == secondObjectSharingContextID))) { pCurrentContextMonitor->setObjectSharingContext(firstContextSpyId, pFirstContextMonitor); } } } } } // --------------------------------------------------------------------------- // Name: replaceContextIDWithListHolder // Description: If the renderContext number renderContextId is sharing another // context's lists, change that variable to represent the context // which holds the information. // Author: <NAME> // Date: 11/6/2008 // --------------------------------------------------------------------------- void gsOpenGLMonitor::replaceContextIDWithListHolder(int& renderContextId) const { const gsRenderContextMonitor* pContextMonitor = renderContextMonitor(renderContextId); if (pContextMonitor != NULL) { int shareListsHolder = pContextMonitor->getObjectSharingContextID(); if (shareListsHolder != -1) { renderContextId = shareListsHolder; } } } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::renderContextMonitor // Description: Inputs a render context id and returns its render context monitor. // (Or null, if a context of that id does not exist) // Author: <NAME> // Date: 19/4/2005 // --------------------------------------------------------------------------- const gsRenderContextMonitor* gsOpenGLMonitor::renderContextMonitor(int renderContextId) const { const gsRenderContextMonitor* retVal = NULL; // Index range test: int renderContextsAmount = amountOfContexts(); GT_IF_WITH_ASSERT((0 < renderContextId) && (renderContextId < renderContextsAmount)) { retVal = (const gsRenderContextMonitor*)_contextsMonitors[renderContextId]; } return retVal; } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::renderContextMonitor // Description: Inputs a render context id and returns its render context monitor. // (Or null, if a context of that id does not exist) // Author: <NAME> // Date: 19/4/2005 // --------------------------------------------------------------------------- gsRenderContextMonitor* gsOpenGLMonitor::renderContextMonitor(int renderContextId) { gsRenderContextMonitor* retVal = NULL; // Index range test: int renderContextsAmount = amountOfContexts(); GT_IF_WITH_ASSERT((0 < renderContextId) && (renderContextId < renderContextsAmount)) { retVal = (gsRenderContextMonitor*)_contextsMonitors[renderContextId]; } return retVal; } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::currentThreadRenderContextMonitor // Description: Returns const access to the current thread's render context monitor. // or NULL if the current thread does not have a current render context. // Author: <NAME> // Date: 5/4/2005 // --------------------------------------------------------------------------- const gsRenderContextMonitor* gsOpenGLMonitor::currentThreadRenderContextMonitor() const { const gsRenderContextMonitor* pRetVal = NULL; int currentContextId = currentThreadRenderContextSpyId(); if (currentContextId > 0) { pRetVal = renderContextMonitor(currentContextId); } return pRetVal; } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::currentThreadRenderContextMonitor // Description: Returns the current thread's render context monitor. // or NULL if the current thread does not have a current render // context. // Author: <NAME> // Date: 5/4/2005 // --------------------------------------------------------------------------- gsRenderContextMonitor* gsOpenGLMonitor::currentThreadRenderContextMonitor() { gsRenderContextMonitor* pRetVal = NULL; int currentContextId = currentThreadRenderContextSpyId(); // If this is not a NULL context: if (currentContextId > 0) { pRetVal = renderContextMonitor(currentContextId); } return pRetVal; } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::currentThreadContextMonitor // Description: Returns const access to the current thread's context monitor. // When the current thread's context is NULL, return a pointer to the // none context monitor // Notice: Use this function when the object needed is a pointer to an // suContextMonitor. Only when gsRenderContextMonitor functionality is // requested, use currentThreadRenderContextMonitor // Author: <NAME> // Date: 22/3/2010 // --------------------------------------------------------------------------- const suContextMonitor* gsOpenGLMonitor::currentThreadContextMonitor() const { const suContextMonitor* pRetVal = NULL; int currentContextId = currentThreadRenderContextSpyId(); if (currentContextId >= 0) { pRetVal = _contextsMonitors[currentContextId]; } return pRetVal; } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::currentThreadContextMonitor // Description: Returns const access to the current thread's context monitor. // When the current thread's context is NULL, return a pointer to the // none context monitor // Notice: Use this function when the object needed is a pointer to an // suContextMonitor. Only when gsRenderContextMonitor functionality is // requested, use currentThreadRenderContextMonitor // Author: <NAME> // Date: 22/3/2010 // --------------------------------------------------------------------------- suContextMonitor* gsOpenGLMonitor::currentThreadContextMonitor() { suContextMonitor* pRetVal = NULL; int currentContextId = currentThreadRenderContextSpyId(); // If this is not a NULL context: if (currentContextId >= 0) { pRetVal = _contextsMonitors[currentContextId]; } return pRetVal; } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::boundTexture // Description: Inputs a bind target and returns the name of the texture that is // bind to this target. // Arguments: bindTarget - The queried bind target. // Return Val: GLuint - The bounded texture, or 0 if there is no texture bounded // to this target. // Author: <NAME> // Date: 12/1/2005 // --------------------------------------------------------------------------- GLuint gsOpenGLMonitor::boundTexture(GLenum bindTarget) const { GLuint retVal = 0; apTextureType bindTargetAsTextureType = apTextureBindTargetToTextureType(bindTarget); if (bindTargetAsTextureType != AP_UNKNOWN_TEXTURE_TYPE) { // Get the current render context monitor: const gsRenderContextMonitor* pRenderContextMonitor = currentThreadRenderContextMonitor(); GT_IF_WITH_ASSERT(pRenderContextMonitor != NULL) { pRenderContextMonitor->activeTextureUnitIndex(); int activeTexUnitIndex = pRenderContextMonitor->activeTextureUnitIndex(); retVal = pRenderContextMonitor->bindTextureName(activeTexUnitIndex, bindTargetAsTextureType); } } return retVal; } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::forcedStubTextureName // Description: Returns the forced stub texture name for an input bind target. // Author: <NAME> // Date: 4/3/2005 // --------------------------------------------------------------------------- GLuint gsOpenGLMonitor::forcedStubTextureName(GLenum bindTarget) const { GLuint retVal = 0; // Get the current render context monitor: const gsRenderContextMonitor* pRenderContextMonitor = currentThreadRenderContextMonitor(); GT_IF_WITH_ASSERT(pRenderContextMonitor != NULL) { const gsTexturesMonitor* texturesMtr = pRenderContextMonitor->texturesMonitor(); retVal = texturesMtr->forcedStubTextureObjectName(bindTarget); } return retVal; } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::activeProgram // Description: Returns the currently active program for this thread. // This is to be used in function wrappers. // Author: <NAME> // Date: 9/9/2013 // --------------------------------------------------------------------------- GLuint gsOpenGLMonitor::activeProgram() const { GLuint retVal = 0; const gsRenderContextMonitor* pCurrentThreadRenderContextMonitor = gs_stat_openGLMonitorInstance.currentThreadRenderContextMonitor(); if (NULL != pCurrentThreadRenderContextMonitor) { retVal = pCurrentThreadRenderContextMonitor->activeProgramName(); } return retVal; } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::addFunctionCall // Description: // Logs a monitored function call into the active render context call history logger. // Triggers monitored functions breakpoint events. // Arguments: apMonitoredFunctionId calledFunctionId - the logged function id. // argumentsAmount - The amount of function arguments. // ... - Function arguments in va_list style. // Author: <NAME> // Date: 11/5/2004 // --------------------------------------------------------------------------- void gsOpenGLMonitor::addFunctionCall(apMonitoredFunctionId calledFunctionId, int argumentsAmount, ...) { // If the OpenGL Server was not initialized yet, initialize it: if (!_wasOpenGLServerInitialized) { bool rcSpyInit = gsOpenGLSpyInit(); GT_ASSERT(rcSpyInit); _wasOpenGLServerInitialized = true; } // Get the render context that is current to the calling thread: suContextMonitor* pRenderContextMonitor = currentThreadContextMonitor(); GT_IF_WITH_ASSERT(pRenderContextMonitor != NULL) { // Notify the render context monitor that a monitored function was called: pRenderContextMonitor->onMonitoredFunctionCall(); // Do not perform the below actions while in profiling mode: apExecutionMode debuggedProcessExecutionMode = suDebuggedProcessExecutionMode(); if (debuggedProcessExecutionMode != AP_PROFILING_MODE) { // If the render context is not during context data update: bool isDuringContextDataUpdate = pRenderContextMonitor->isDuringContextDataUpdate(); if (!isDuringContextDataUpdate) { // Get a pointer to the arguments list: va_list pCurrentArgument; va_start(pCurrentArgument, argumentsAmount); su_stat_theBreakpointsManager.waitOnDebuggedProcessSuspension(); // Add the function call to the render context loggers: pRenderContextMonitor->addFunctionCall(calledFunctionId, argumentsAmount, pCurrentArgument, AP_DEPRECATION_NONE); // Execute before monitored function execution actions: beforeMonitoredFunctionExecutionActions(calledFunctionId); // Free the arguments list: va_end(pCurrentArgument); } } } // ------------ Spy debugging code -------------- // Notice: The below section is used for spy debugging. // Please leave it commented out. bool foo1 = false; if (foo1) { gtVector<GLuint> vbos; vbos.push_back(1); gaUpdateVBORawDataImpl(1, vbos); } /* bool foo2 = false; if (foo2) { int foundIndex = -1; bool rc = gaFindCurrentFrameFunctionCallImpl(1, AP_SEARCH_INDICES_DOWN,0, "glcolor", false,foundIndex); }*/ /* bool foo3 = false; if (foo3) { gtPtrVector<apFunctionCallStatistics*> vecvec; bool rc = gaGetLastFrameFunctionCallsStatisticsImpl(1, vecvec); int i = 3; i++; } */ /* bool foo4 = false; if (foo4) { gtVector<GLuint> textureNames; textureNames.push_back(1); bool rc = gaUpdateCurrentThreadTextureRawDataImpl(textureNames); int i = 3; i++; } */ } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::beforeMonitoredFunctionExecutionActions // Description: Perform OpenGL monitor actions that should be executed BEFORE // the monitored function is executed. // Arguments: apMonitoredFunctionId monitoredFunctionId - the monitored function id // Author: <NAME> // Date: 14/11/2004 // --------------------------------------------------------------------------- void gsOpenGLMonitor::beforeMonitoredFunctionExecutionActions(apMonitoredFunctionId monitoredFunctionId) { // Test and trigger BEFORE function execution breakpoints: testAndTriggerBeforeFuncExecutionBreakpoints(monitoredFunctionId); // If slow motion mode is on: int slowMotionDelayTimeUnits = suSlowMotionDelayTimeUnits(); if (slowMotionDelayTimeUnits > 0) { // Perform the slow motion delay: suPerformSlowMotionDelay(slowMotionDelayTimeUnits); } } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::afterMonitoredFunctionExecutionActions // Description: Perform OpenGL monitor actions that should be executed AFTER // the monitored function is executed. // Author: <NAME> // Date: 14/11/2004 // --------------------------------------------------------------------------- void gsOpenGLMonitor::afterMonitoredFunctionExecutionActions(apMonitoredFunctionId calledFunctionId) { // Do not perform the below actions in profiling mode: apExecutionMode debuggedProcessExecutionMode = suDebuggedProcessExecutionMode(); if (debuggedProcessExecutionMode != AP_PROFILING_MODE) { // Will get true iff we are during context data snapshot update: bool isDuringContextDataUpdate = false; // Get current thread's render context monitor: suContextMonitor* pContextMonitor = currentThreadContextMonitor(); GT_IF_WITH_ASSERT(pContextMonitor != NULL) { // If the render context is not during context data update: isDuringContextDataUpdate = pContextMonitor->isDuringContextDataUpdate(); if (!isDuringContextDataUpdate) { // Get the function calls monitor: gsCallsHistoryLogger* pActiveContextLogger = (gsCallsHistoryLogger*)pContextMonitor->callsHistoryLogger(); GT_IF_WITH_ASSERT(pActiveContextLogger != NULL) { // If OpenGL flush is forced: if (_isOpenGLFlushForced) { #ifdef _GR_IPHONE_BUILD // The iPhone cannot draw directly into the front buffer, so we simply swap the buffers: gsRenderContextMonitor* pRenderContextMonitor = (gsRenderContextMonitor*)pContextMonitor; if (pRenderContextMonitor != NULL) { gsSwapEAGLContextBuffers(pRenderContextMonitor->renderContextOSHandle()); } #else // If we are not in a glBegin - glEnd block: if (!(pActiveContextLogger->isInOpenGLBeginEndBlock())) { // Flush the graphics pipeline: SU_BEFORE_EXECUTING_REAL_FUNCTION(ap_glFlush); gs_stat_realFunctionPointers.glFlush(); SU_AFTER_EXECUTING_REAL_FUNCTION(ap_glFlush); } #endif } } // Update state change function status: pContextMonitor->afterMonitoredFunctionExecutionActions(calledFunctionId); } } if (!isDuringContextDataUpdate) { // Test and trigger AFTER function execution breakpoints: testAndTriggerAfterFuncExecutionBreakpoints(calledFunctionId); } } } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::onGenericBreakpointSet // Description: Set / Unset a generic breakpoint // Arguments: apGenericBreakpointType breakpointType // bool isOn // Return Val: void // Author: <NAME> // Date: 7/7/2011 // --------------------------------------------------------------------------- void gsOpenGLMonitor::onGenericBreakpointSet(apGenericBreakpointType breakpointType, bool isOn) { if (breakpointType == AP_BREAK_ON_GL_ERROR) { // Notify the contexts forced modes managers: int amountOfContexts = (int)_contextsMonitors.size(); for (int i = 1; i < amountOfContexts; i++) { // Get the render context monitor: gsRenderContextMonitor* pContextMonitor = renderContextMonitor(i); GT_IF_WITH_ASSERT(pContextMonitor != NULL) { pContextMonitor->onBreakOnOpenGLErrorModeChanged(isOn); } } } } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::forceOpenGLPolygonRasterMode // Description: // Force an input raster mode on OpenGL. // I.E: OpenGL API calls will not be able to change the raster mode that this // function sets. // // Arguments: rasterMode - The forced raster mode. // Author: <NAME> // Date: 11/11/2004 // --------------------------------------------------------------------------- void gsOpenGLMonitor::forceOpenGLPolygonRasterMode(apRasterMode rasterMode) { // Notify the initialize force mode manager with the change: _initForceModesManager.forcePolygonRasterMode(rasterMode); // Notify all the active render contexts: int amountOfContexts = (int)_contextsMonitors.size(); for (int i = 1; i < amountOfContexts; i++) { // Get the render context monitor: gsRenderContextMonitor* pContextMonitor = renderContextMonitor(i); GT_IF_WITH_ASSERT(pContextMonitor != NULL) { gsForcedModesManager& contextForcedModesMgr = pContextMonitor->forcedModesManager(); contextForcedModesMgr.forcePolygonRasterMode(rasterMode); } } } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::cancelOpenGLPolygonRasterModeForcing // Description: Cancels the "Force OpenGL render mode" mode. // Author: <NAME> // Date: 14/11/2004 // --------------------------------------------------------------------------- void gsOpenGLMonitor::cancelOpenGLPolygonRasterModeForcing() { // Notify the initialize force mode manager with the change: _initForceModesManager.cancelPolygonRasterModeForcing(); // Notify all the active render contexts: int amountOfContexts = (int)_contextsMonitors.size(); for (int i = 1; i < amountOfContexts; i++) { // Get the render context monitor: gsRenderContextMonitor* pContextMonitor = renderContextMonitor(i); GT_IF_WITH_ASSERT(pContextMonitor != NULL) { gsForcedModesManager& contextForcedModesMgr = pContextMonitor->forcedModesManager(); contextForcedModesMgr.cancelPolygonRasterModeForcing(); } } } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::forceStubMode // Description: Forces a stub mode. // Arguments: apOpenGLForcedModeType stubType - the stub type // bool isStubForced // Return Val: void // Author: <NAME> // Date: 9/5/2010 // --------------------------------------------------------------------------- void gsOpenGLMonitor::forceStubMode(apOpenGLForcedModeType stubType, bool isStubForced) { // Notify the initialize force mode manager with the change: _initForceModesManager.forceStub(stubType, isStubForced); // Notify all the active render contexts: int amountOfContexts = (int)_contextsMonitors.size(); for (int i = 1; i < amountOfContexts; i++) { // Get the render context monitor: gsRenderContextMonitor* pContextMonitor = renderContextMonitor(i); GT_IF_WITH_ASSERT(pContextMonitor != NULL) { gsForcedModesManager& contextForcedModesMgr = pContextMonitor->forcedModesManager(); contextForcedModesMgr.forceStub(stubType, isStubForced); } } } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::setGLDebugOutputLoggingEnabled // Description: Applies debug output logging parameter to all contexts // Author: <NAME> // Date: 29/6/2014 // --------------------------------------------------------------------------- void gsOpenGLMonitor::setGLDebugOutputLoggingEnabled(bool enabled) { // Notify the initialize force mode manager with the change: _initForceModesManager.setGLDebugOutputLoggingEnabled(enabled); // Notify all the active render contexts: int amountOfContexts = (int)_contextsMonitors.size(); for (int i = 1; i < amountOfContexts; i++) { // Get the render context monitor: gsRenderContextMonitor* pContextMonitor = renderContextMonitor(i); GT_IF_WITH_ASSERT(pContextMonitor != NULL) { gsForcedModesManager& contextForcedModesMgr = pContextMonitor->forcedModesManager(); contextForcedModesMgr.setGLDebugOutputLoggingEnabled(enabled); } } } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::setGLDebugOutputSeverityEnabled // Description: Applies debug output logging parameter to all contexts // Author: <NAME> // Date: 29/6/2014 // --------------------------------------------------------------------------- void gsOpenGLMonitor::setGLDebugOutputSeverityEnabled(apGLDebugOutputSeverity severity, bool enabled) { // Notify the initialize force mode manager with the change: _initForceModesManager.setGLDebugOutputSeverityEnabled(severity, enabled); // Notify all the active render contexts: int amountOfContexts = (int)_contextsMonitors.size(); for (int i = 1; i < amountOfContexts; i++) { // Get the render context monitor: gsRenderContextMonitor* pContextMonitor = renderContextMonitor(i); GT_IF_WITH_ASSERT(pContextMonitor != NULL) { gsForcedModesManager& contextForcedModesMgr = pContextMonitor->forcedModesManager(); contextForcedModesMgr.setGLDebugOutputSeverityEnabled(severity, enabled); } } } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::setGLDebugOutputKindMask // Description: Applies debug output logging parameter to all contexts // Author: <NAME> // Date: 29/6/2014 // --------------------------------------------------------------------------- void gsOpenGLMonitor::setGLDebugOutputKindMask(const gtUInt64& mask) { // Notify the initialize force mode manager with the change: _initForceModesManager.setGLDebugOutputKindMask(mask); // Notify all the active render contexts: int amountOfContexts = (int)_contextsMonitors.size(); for (int i = 1; i < amountOfContexts; i++) { // Get the render context monitor: gsRenderContextMonitor* pContextMonitor = renderContextMonitor(i); GT_IF_WITH_ASSERT(pContextMonitor != NULL) { gsForcedModesManager& contextForcedModesMgr = pContextMonitor->forcedModesManager(); contextForcedModesMgr.setGLDebugOutputKindMask(mask); } } } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::handleForeignContextExtensionFuncCall // Description: // Handles a case in which the debugged process calls an extgension function // who's pointer was not retrieved into the current context. // // - On OpenGL + WGL, this is happens when the debugged process asks for an extension // function pointer at context A, but calls the function pointer while context B is // the active context. This is illegal in WGL terminology, therefore we rasize an // AP_FOREIGN_CONTEXT_EXTENSION_FUNC_CALL_ERROR error. // // - In OpenGL ES + EGL this is a legal operation. Therefore, no error is triggered. // // Arguments: extensionFunctionName - The name of the called extension function. // Author: <NAME> // Date: 22/3/2005 // Implementation details: // - To imitate current drivers action at this case: look for this function pointer // at other contexts, and copy the function pointer to this context extension // function pointers structure. // - If the function pointer is not found in other contexts, try getting it using // wglGetProcAddress (this happends when using OpenGL ES + EGL, where some extension // functions are now OpenGL ES core functions). // --------------------------------------------------------------------------- void gsOpenGLMonitor::handleForeignContextExtensionFuncCall(const wchar_t* extensionFunctionName, bool& extensionFuncPtrFound) { extensionFuncPtrFound = false; // Get the associated function id: apMonitoredFunctionId associatedFuncId = su_stat_theMonitoredFunMgr.monitoredFunctionId(extensionFunctionName); // Sanity check: GT_IF_WITH_ASSERT(associatedFuncId != -1) { // Try to copy the function pointer from another context: gsExtensionsManager& theExtensionsManager = gsExtensionsManager::instance(); extensionFuncPtrFound = theExtensionsManager.copyExtensionPointerFromOtherContexts(associatedFuncId); // If we didn't find the extension function pointer in other contexts: // (This can happen when calling OpenGL ES core functions that are OpenGL extension functions) if (!extensionFuncPtrFound) { // Try to get the extension function pointer from the system: extensionFuncPtrFound = theExtensionsManager.getExtensionPointerFromSystem(associatedFuncId); GT_ASSERT(extensionFuncPtrFound); } // Getting extension function pointer from one render context and called this function pointer in another render context // is not legal under WGL. However, it is legal under GLX and EGL. #if AMDT_BUILD_TARGET == AMDT_WINDOWS_OS { #ifndef OS_OGL_ES_IMPLEMENTATION_DLL_BUILD { // Generate a detected process event: int currentContextId = currentThreadRenderContextSpyId(); gtString errorDescription = GS_STR_foreignExtensionCallError1; errorDescription.appendFormattedString(L"(%ls)", extensionFunctionName); errorDescription += GS_STR_foreignExtensionCallError2; errorDescription.appendFormattedString(L" (context #%d) ", currentContextId); if (!extensionFuncPtrFound) { errorDescription += GS_STR_extensionCallIgnored; } // Yaki 12/10/2005: // A lot of users that use GLEW (or other OpenGL extensions wrapping libraries) complained that they // get this error a lot of times. This force them to disable the "Break on detected errors" test and they // cannot use it to catch other errors. // So, Instead of reporting a detected error and breaking the debugged process run, we only generate a // debug string (for more details, see Case 470). gtString dbgString = L"CodeXL warning: "; dbgString += errorDescription; osOutputDebugString(dbgString); // reportDetectedError(AP_FOREIGN_CONTEXT_EXTENSION_FUNC_CALL_ERROR, errorDescription, associatedFuncId); } #endif } #endif } } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::handleForeignContextExtensionFuncCall // Description: For Linux builds, converts the first parameter of // handleForeignContextExtensionFuncCall from an ASCII string // Author: <NAME> // Date: 19/7/2011 // --------------------------------------------------------------------------- void gsOpenGLMonitor::handleForeignContextExtensionFuncCall(const char* extensionFunctionName, bool& extensionFuncPtrFound) { // Convert to unicode: gtString extensionFunctionNameAsUnicodeString; extensionFunctionNameAsUnicodeString.fromASCIIString(extensionFunctionName); // Send to the real function: handleForeignContextExtensionFuncCall(extensionFunctionNameAsUnicodeString.asCharArray(), extensionFuncPtrFound); } // -------------------- private functions ------------------ // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::testOpenGLBreakpoints // Description: The function checks for specific OpenGL breakpoints, and set the // break reason if there is a breakpoint. // Author: <NAME> // Date: 26/11/2009 // --------------------------------------------------------------------------- void gsOpenGLMonitor::testOpenGLBreakpoints(apMonitoredFunctionId monitoredFunctionId, apBreakReason& breakReason) { #if ((AMDT_BUILD_TARGET == AMDT_LINUX_OS) && (AMDT_LINUX_VARIANT == AMDT_MAC_OS_X_LINUX_VARIANT)) if (su_stat_theBreakpointsManager.breakOnGenericBreakpoint(AP_BREAK_ON_SOFTWARE_FALLBACK)) { // Check if the function is a draw function: bool isDrawFunction = ((apMonitoredFunctionsManager::instance().monitoredFunctionType(monitoredFunctionId) & AP_DRAW_FUNC) != 0); if (isDrawFunction) { // Check for software fallbacks: bool vertexSFB = false; bool fragmentSFB = false; #if ((AMDT_BUILD_TARGET == AMDT_LINUX_OS) && (AMDT_LINUX_VARIANT == AMDT_MAC_OS_X_LINUX_VARIANT)) { // This only works with CGL: #ifndef _GR_IPHONE_BUILD // In Mac OS X, we check for software fallbacks by checking after each // draw call if the GPU is used for vertex operations and fragment ones: GLint paramValue = 0; CGLContextObj currentContext = currentThreadRenderContextMonitor()->renderContextOSHandle(); SU_BEFORE_EXECUTING_REAL_FUNCTION(ap_CGLGetParameter); CGLError errCode = gs_stat_realFunctionPointers.CGLGetParameter(currentContext , kCGLCPGPUVertexProcessingNoDispatch, &paramValue); GT_IF_WITH_ASSERT(errCode == kCGLNoError) { vertexSFB = (paramValue == GL_FALSE); } paramValue = 0; errCode = gs_stat_realFunctionPointers.CGLGetParameter(currentContext , kCGLCPGPUFragmentProcessingNoDispatch, &paramValue); GT_IF_WITH_ASSERT(errCode == kCGLNoError) { fragmentSFB = (paramValue == GL_FALSE); } SU_AFTER_EXECUTING_REAL_FUNCTION(ap_CGLGetParameter); #endif } #endif if (vertexSFB || fragmentSFB) { // We had a Software Fallback, report it! breakReason = AP_SOFTWARE_FALLBACK_BREAKPOINT_HIT; } } } #else // Resolve the compiler warning for the Linux variant (void)(monitoredFunctionId); (void)(breakReason); #endif } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::testAndTriggerBeforeFuncExecutionBreakpoints // Description: // Tests if there is a breakpoint at the input monitored function. // If there is - triggers a breakpoint event. // // This function tests for breakpoints that should be raised BEFORE the // monitored function is executed. // Arguments: apMonitoredFunctionId monitoredFunctionId - the monitored function id // Author: <NAME> // Date: 16/6/2004 // --------------------------------------------------------------------------- void gsOpenGLMonitor::testAndTriggerBeforeFuncExecutionBreakpoints(apMonitoredFunctionId monitoredFunctionId) { // Initialize a break reason: apBreakReason breakReason = AP_FOREIGN_BREAK_HIT; // First test OpenGL specific breakpoints reason: testOpenGLBreakpoints(monitoredFunctionId, breakReason); // Check if we are in a begin-end block: int currentContextId = currentThreadRenderContextSpyId(); bool isInGLBeginEndBlock = false; // Get the render context wrapper object: if (currentContextId != AP_NULL_CONTEXT_ID) { gsRenderContextMonitor* pRenderContextMonitor = renderContextMonitor(currentContextId); if (pRenderContextMonitor != NULL) { isInGLBeginEndBlock = pRenderContextMonitor->isInOpenGLBeginEndBlock(); // If this context needs to test for undetected OpenGL errors, do so now: if (su_stat_theBreakpointsManager.breakOnGenericBreakpoint(AP_BREAK_ON_GL_ERROR)) { if (pRenderContextMonitor->isOpenGLErrorCheckNeededOnModeTurnedOn()) { pRenderContextMonitor->checkForOpenGLErrorAfterModeChange(); } } } } if (breakReason == AP_FOREIGN_BREAK_HIT) { // Check the 'common' (spy utilities) breakpoints reasons: apContextID contextId(AP_OPENGL_CONTEXT, currentContextId); su_stat_theBreakpointsManager.testAndTriggerBeforeFuncExecutionBreakpoints(monitoredFunctionId, contextId, isInGLBeginEndBlock); } else // (breakReason != AP_FOREIGN_BREAK_HIT) { // Trigger a breakpoint exception: triggerBreakpointException(breakReason, GL_NO_ERROR, isInGLBeginEndBlock); } } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::triggerBreakpointException // Description: Allows clients to trigger a breakpoint exception. // Arguments: breakReason - The reason why we triggered the breakpoint exception. // opeglError - OpenGL error associated with the triggered breakpoint, // or GL_NO_ERROR if there is no associated error. // isInGLBeginEndBlock - true iff we are in a glBegin-glEnd block. // Author: <NAME> // Date: 8/3/2006 // --------------------------------------------------------------------------- void gsOpenGLMonitor::triggerBreakpointException(apBreakReason breakReason, GLenum opeglError, bool isInGLBeginEndBlock) { // Log the break reason and error (they are retrieved by the debugger when it // catch the breakpoint exception): _openGLError = opeglError; // Set the breakpoint reason: su_stat_theBreakpointsManager.beforeTriggeringBreakpoint(); su_stat_theBreakpointsManager.setBreakReason(breakReason); // Get the breakpoint function Id: apMonitoredFunctionId monitoredFunctionId = apMonitoredFunctionsAmount; const gsRenderContextMonitor* pCurrentThreadContextMonitor = currentThreadRenderContextMonitor(); if (pCurrentThreadContextMonitor != NULL) { const suCallsHistoryLogger* pCallsHistoryLogger = pCurrentThreadContextMonitor->callsHistoryLogger(); GT_IF_WITH_ASSERT(pCallsHistoryLogger != NULL) { monitoredFunctionId = pCallsHistoryLogger->lastCalledFunctionId(); } } // Trigger breakpoint exception: int currentContextId = currentThreadRenderContextSpyId(); apContextID contextId(AP_OPENGL_CONTEXT, currentContextId); su_stat_theBreakpointsManager.triggerBreakpointException(contextId, monitoredFunctionId, isInGLBeginEndBlock); su_stat_theBreakpointsManager.afterTriggeringBreakpoint(); } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::reportDetectedError // Description: Reports a detected error from the current OpenGL context // Author: <NAME> // Date: 21/1/2010 // --------------------------------------------------------------------------- void gsOpenGLMonitor::reportDetectedError(apErrorCode errorCode, const gtString& errorDescription, apMonitoredFunctionId associatedFuncId) { int currentThreadGLContext = currentThreadRenderContextSpyId(); apContextID contextId(AP_OPENGL_CONTEXT, currentThreadGLContext); su_stat_theBreakpointsManager.reportDetectedError(contextId, errorCode, errorDescription, associatedFuncId); } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::testAndTriggerAfterFuncExecutionBreakpoints // Description: // Tests if there is a breakpoint caused by input monitored function. // If there is - triggers a breakpoint event. // // This function tests for breakpoints that should be raised AFTER the // monitored function is executed. // Arguments: apMonitoredFunctionId monitoredFunctionId - the monitored function id // Author: <NAME> // Date: 16/6/2004 // --------------------------------------------------------------------------- void gsOpenGLMonitor::testAndTriggerAfterFuncExecutionBreakpoints(apMonitoredFunctionId monitoredFunctionId) { // If we need to test for OpenGL errors: if (su_stat_theBreakpointsManager.breakOnGenericBreakpoint(AP_BREAK_ON_GL_ERROR)) { // If this is not the NULL context: int currentContextId = currentThreadRenderContextSpyId(); if (currentContextId != AP_NULL_CONTEXT_ID) { const gsRenderContextMonitor* pRenderContextMonitor = renderContextMonitor(currentContextId); GT_IF_WITH_ASSERT(pRenderContextMonitor != NULL) { // If the mode was just turned on, we need to wait for one more function call, so that the context won't // report former OpenGL errors as belonging to this function: if (!pRenderContextMonitor->isOpenGLErrorCheckNeededOnModeTurnedOn()) { bool isInOpenGLBeginEndBlock = pRenderContextMonitor->isInOpenGLBeginEndBlock(); // This is AFTER the function call, so we need to reverse the value for glBegin and glEnd: if (monitoredFunctionId == ap_glBegin) { isInOpenGLBeginEndBlock = true; } else if (monitoredFunctionId == ap_glEnd) { isInOpenGLBeginEndBlock = false; } // If we are not at a glBegin glEnd block: // (We are not allowed to call glGetError inside a glBegin glEnd block) if (!isInOpenGLBeginEndBlock) { // If there is an OpenGL error: SU_BEFORE_EXECUTING_REAL_FUNCTION(ap_glGetError); GLenum openGLError = gs_stat_realFunctionPointers.glGetError(); SU_AFTER_EXECUTING_REAL_FUNCTION(ap_glGetError); if (openGLError != GL_NO_ERROR) { // Trigger an "OpenGL error" breakpoint exception: triggerBreakpointException(AP_OPENGL_ERROR_BREAKPOINT_HIT, openGLError, false); } } } } } } } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::updateCurrentContextDataSnapshot // Description: Updates the data snapshot of the current thread's // current render context. // Author: <NAME> // Date: 28/1/2007 // --------------------------------------------------------------------------- void gsOpenGLMonitor::updateCurrentContextDataSnapshot() { // Get the current thread render context: gsRenderContextMonitor* pRenderContextMon = currentThreadRenderContextMonitor(); GT_IF_WITH_ASSERT(pRenderContextMon != NULL) { // Get the context id: int renderContextId = pRenderContextMon->spyId(); // If this is a real context: if (renderContextId > 0) { // Update the context data: bool rc = pRenderContextMon->updateContextDataSnapshot(); GT_ASSERT(rc); } } } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::initializeRenderContextMonitor // Description: Initializes a render context monitor. // Arguments: renderContextMonitor - The render context monitor to be initialized. // Author: <NAME> // Date: 3/11/2005 // --------------------------------------------------------------------------- void gsOpenGLMonitor::initializeRenderContextMonitor(gsRenderContextMonitor& renderContextMonitor) { // Get the context spy id: int contextSpyId = renderContextMonitor.spyId(); // If the created context is not the NULL context: if ((contextSpyId != 0)) { // Set the render context pixel format: // Get the context device context handle: #if AMDT_BUILD_TARGET == AMDT_WINDOWS_OS oaDeviceContextHandle hDeviceContext = renderContextMonitor.deviceContextOSHandle(); int pixelFormatId = ::GetPixelFormat(hDeviceContext); renderContextMonitor.setPixelFormatId(pixelFormatId); #elif AMDT_BUILD_TARGET == AMDT_LINUX_OS // This is done when we create the context with glXCreateContext / CGLCreateContext #else #error Unsupported platform #endif // Get the new context forced modes manager: gsForcedModesManager& newContextForcedModeMgr = renderContextMonitor.forcedModesManager(); // Copy the force mode settings from the init force modes manager: newContextForcedModeMgr.copyForcedModesFromOtherManager(_initForceModesManager); } // If the text log files are active: bool areHTMLLogFilesActive = suAreHTMLLogFilesActive(); if (areHTMLLogFilesActive) { // Start log file recording: suCallsHistoryLogger* pCallsLogger = renderContextMonitor.callsHistoryLogger(); GT_IF_WITH_ASSERT(pCallsLogger != NULL) { pCallsLogger->startHTMLLogFileRecording(); } } } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::renderContextSpyId // Description: Inputs a render context OS handle (casted into void*) and returns // the render context spy id. // (Or -1 if this context is not known to this class) // Author: <NAME> // Date: 14/11/2005 // Implementation notes: // We assume that the amount of render context is low (up to 20), so a linear // search is a fast solution. // --------------------------------------------------------------------------- int gsOpenGLMonitor::renderContextSpyId(oaOpenGLRenderContextHandle pRenderContext) { int retVal = -1; // Iterate spy monitored context (last context to first, assuming that the last // contexts are more active): int amountOfContexts = (int)_contextsMonitors.size(); for (int i = (amountOfContexts - 1); 0 < i; i--) { gsRenderContextMonitor* pContextMonitor = renderContextMonitor(i); GT_IF_WITH_ASSERT(pContextMonitor != NULL) { // We found the input context oaOpenGLRenderContextHandle currentRenderContextOSHandle = pContextMonitor->renderContextOSHandle(); if (currentRenderContextOSHandle == pRenderContext) { retVal = i; break; } } } return retVal; } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::displayCurrentRenderContextContent // Description: // Display the current render context content to the user. // I.E: // - For single buffered contexts - calls glFlush. // - For double buffered contexts - calls SwapBuffers. // // Return Val: bool - Success / failure. // Author: <NAME> // Date: 23/7/2006 // --------------------------------------------------------------------------- bool gsOpenGLMonitor::displayCurrentRenderContextContent() { bool retVal = true; // Get the render context wrapper: gsRenderContextMonitor* pActiveRenderCtxMtr = currentThreadRenderContextMonitor(); if (pActiveRenderCtxMtr != NULL) { // Flush its content to its draw surface (usually the screen): retVal = pActiveRenderCtxMtr->flushContentToDrawSurface(); } return retVal; } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::doesDebugForcedContextExist // Description: Check if there is a debug context with debug flag forced // Arguments: bool isDebugContext - is the debug flag on // Author: <NAME> // Date: 7/7/2010 // --------------------------------------------------------------------------- bool gsOpenGLMonitor::doesDebugForcedContextExist(bool isDebugContext) { bool retVal = false; // Iterate the render contexts and search for a forced debug context: int amountOfContexts = (int)_contextsMonitors.size(); for (int i = 1; i < amountOfContexts; i++) { gsRenderContextMonitor* pContextMonitor = renderContextMonitor(i); if (pContextMonitor != NULL) { if (pContextMonitor->isDebugContextFlagForced() && pContextMonitor->isDebugContext() == isDebugContext) { retVal = true; break; } } } return retVal; } // --------------------------------------------------------------------------- // Name: gsOpenGLMonitor::checkForProcessMemoryLeaks // Description: Check for process termination memory leaks // Author: <NAME> // Date: 18/7/2010 // --------------------------------------------------------------------------- void gsOpenGLMonitor::checkForProcessMemoryLeaks() { //Check memory leaks when OpenGL is unloaded: gsMemoryMonitor::instance().beforeSpyTermination(); }
29,097
1,338
// NodeInfo.h #ifndef NET_FS_NODE_INFO_H #define NET_FS_NODE_INFO_H #include <sys/stat.h> #include "Request.h" #include "ServerNodeID.h" struct NodeInfo : public RequestMember { virtual void ShowAround(RequestMemberVisitor* visitor); inline NodeID GetID() const; struct stat st; int64 revision; }; // GetID inline NodeID NodeInfo::GetID() const { return NodeID(st.st_dev, st.st_ino); } #endif // NET_FS_NODE_INFO_H
183
3,084
#ifndef __INC_SMBIOS_H #define __INC_SMBIOS_H #if (SMBIOS_SUPPORT == 1) #define SMBIOSBUFSize 0x1000 typedef enum _SMBIOS_TYPE{ SMBIOS_BIOS_INFORMATION = 0, SMBIOS_SYSTEM_INFORMATION = 1, SMBIOS_BASE_BOARD_INFORMATION = 2, SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS = 3, SMBIOS_PROCESSOR_INFORMATION = 4, SMBIOS_MEMORY_CONTROLLER_INFORMATION = 5, SMBIOS_MEMORY_MODULE_INFORMATION = 6, SMBIOS_CACHE_INFORMATION = 7, SMBIOS_PORT_CONNECTOR_INFORMATION = 8, SMBIOS_SYSTEM_SLOTS = 9, SMBIOS_ON_BOARD_DEVICES_INFORMATION = 10, SMBIOS_OEM_STRINGS = 11, SMBIOS_MUTUAL_AUTHENTICATION = 133, SMBIOS_MAX = 127, SMBIOS_SKU = 248 }SMBIOS_TYPE; typedef enum _SMBIOS_STATUS{ SMBIOS_STATUS_SUCCESS = 0, SMBIOS_STATUS_WMIOpenBlockFail = 1, SMBIOS_STATUS_AllocateMemFail = 2, SMBIOS_STATUS_WMIQueryDataFail = 3, SMBIOS_STATUS_MutualAuthSuccess = 4, SMBIOS_STATUS_MutualAuthFail = 5, SMBIOS_STATUS_FAILURE = 6 }SMBIOS_STATUS; typedef enum _UEFI_STATUS{ UEFI_STATUS_SUCCESS = 0, UEFI_STATUS_AllocateMemFail = 1, UEFI_STATUS_GetUEFIFail = 2, UEFI_STATUS_ProfileNotDefined = 3, UEFI_STATUS_ProfileUnknown = 4, UEFI_STATUS_UnsupportedOS = 5, UEFI_STATUS_FAILURE = 6 }UEFI_STATUS; typedef enum _UEFI_PROFILE{ UEFI_PROFILE_UNDEFINED = 0, UEFI_PROFILE_LENOVO_CHINA = 1, UEFI_PROFILE_MAX = 100 }UEFI_PROFILE; typedef struct _SMBIOS_DATA{ u4Byte country; u1Byte SAR_Power; u8Byte ProcessorID; BOOLEAN bAsusTX201; BOOLEAN bWABTSeries; BOOLEAN bB550; #if(MUTUAL_AUTHENTICATION == 1) SMBIOS_STATUS MutualAuth; BOOLEAN MutualAuthEnable; BOOLEAN MutualAuthFail; #endif }SMBIOS_DATA, *PSMBIOS_DATA; #if(MUTUAL_AUTHENTICATION == 1) #define SMBIOS_SET_MA_ENABLE(_Adapter, _Enable) (GET_HAL_DATA(_Adapter)->SmbiosData.MutualAuthEnable = _Enable) #define SMBIOS_GET_MA_STATUS(_Adapter) (GET_HAL_DATA(_Adapter)->SmbiosData.MutualAuthFail) #endif #define SMBIOS_GET_COUNTRY_CODE(_Adapter) (GET_HAL_DATA(_Adapter)->SmbiosData.country) #define SMBIOS_GET_SAR_TABLE(_Adapter) (GET_HAL_DATA(_Adapter)->SmbiosData.SAR_Power) #define SMBIOS_GET_PROCESSOR_ID(_Adapter) (GET_HAL_DATA(_Adapter)->SmbiosData.ProcessorID) #define SMBIOS_GET_IS_B550(_Adapter) (GET_HAL_DATA(_Adapter)->SmbiosData.bB550) VOID SmbiosCheckSystemInfo( IN PADAPTER Adapter ); VOID UEFICheckSystemInfo( IN PADAPTER Adapter ); #if(MUTUAL_AUTHENTICATION == 1) VOID SmbiosGetMutualAuth( IN PADAPTER Adapter, IN pu1Byte pSMBIOSData, IN ULONG RemainLen ); VOID MutualAuthWorkItemCallback( IN PVOID pContext ); VOID SmbiosCheckMutualAuth( IN PADAPTER Adapter ); #else #define SmbiosGetMutualAuth(_Adapter, _pSMBIOSData, _RemainLen) #define SmbiosCheckMutualAuth(_Adapter) #endif #else #define SMBIOS_DATA u1Byte #define SMBIOS_GET_MA_STATUS(_Adapter) FALSE #define SMBIOS_GET_COUNTRY_CODE(_Adapter) 0 #define SMBIOS_GET_SAR_TABLE(_Adapter) 0 #define SMBIOS_GET_PROCESSOR_ID(_Adapter) 0 #define SMBIOS_GET_IS_B550(_Adapter) 0 #define UEFICheckSystemInfo(_Adapter) #define SmbiosCheckSystemInfo(_Adapter) #define SmbiosGetMutualAuth(_Adapter, _pSMBIOSData, _RemainLen) #define MutualAuthWorkItemCallback(_pContext) NULL #define SmbiosCheckMutualAuth(_Adapter) #endif #endif
1,716
1,350
<gh_stars>1000+ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.eventhubs.generated; import com.azure.core.util.Context; /** Samples for PrivateEndpointConnections List. */ public final class PrivateEndpointConnectionsListSamples { /* * x-ms-original-file: specification/eventhub/resource-manager/Microsoft.EventHub/stable/2021-11-01/examples/NameSpaces/PrivateEndPointConnectionList.json */ /** * Sample code: NameSpaceCreate. * * @param azure The entry point for accessing resource management APIs in Azure. */ public static void nameSpaceCreate(com.azure.resourcemanager.AzureResourceManager azure) { azure .eventHubs() .manager() .serviceClient() .getPrivateEndpointConnections() .list("SDK-EventHub-4794", "sdk-Namespace-5828", Context.NONE); } }
365
585
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.solr.core; /** * Used to request notification when the core is closed. * <p> * Call {@link org.apache.solr.core.SolrCore#addCloseHook(org.apache.solr.core.CloseHook)} during the {@link org.apache.solr.util.plugin.SolrCoreAware#inform(SolrCore)} method to * add a close hook to your object. * <p> * The close hook can be useful for releasing objects related to the request handler (for instance, if you have a JDBC DataSource or something like that) */ public abstract class CloseHook { /** * Method called when the given SolrCore object is closing / shutting down but before the update handler and * searcher(s) are actually closed * <br> * <b>Important:</b> Keep the method implementation as short as possible. If it were to use any heavy i/o , network connections - * it might be a better idea to launch in a separate Thread so as to not to block the process of * shutting down a given SolrCore instance. * * @param core SolrCore object that is shutting down / closing */ public abstract void preClose(SolrCore core); /** * Method called when the given SolrCore object has been shut down and update handlers and searchers are closed * <br> * Use this method for post-close clean up operations e.g. deleting the index from disk. * <br> * <b>The core's passed to the method is already closed and therefore, its update handler or searcher should *NOT* be used</b> * * <b>Important:</b> Keep the method implementation as short as possible. If it were to use any heavy i/o , network connections - * it might be a better idea to launch in a separate Thread so as to not to block the process of * shutting down a given SolrCore instance. */ public abstract void postClose(SolrCore core); }
703
2,206
/* * ****************************************************************************** * * * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * See the NOTICE file distributed with this work for additional * * information regarding copyright ownership. * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * * License for the specific language governing permissions and limitations * * under the License. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package org.deeplearning4j.text.sentenceiterator; import org.deeplearning4j.BaseDL4JTest; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.nd4j.common.resources.Resources; import org.nd4j.common.tests.tags.TagNames; import java.io.File; import static org.junit.jupiter.api.Assertions.assertEquals; public class AggregatingSentenceIteratorTest extends BaseDL4JTest { @Test() @Timeout(30000) @Disabled("Needs verification, could be permissions issues: g.opentest4j.AssertionFailedError: expected: <388648> but was: <262782> at line 60") @Tag(TagNames.NEEDS_VERIFY) public void testHasNext() throws Exception { File file = Resources.asFile("/big/raw_sentences.txt"); BasicLineIterator iterator = new BasicLineIterator(file); BasicLineIterator iterator2 = new BasicLineIterator(file); AggregatingSentenceIterator aggr = new AggregatingSentenceIterator.Builder().addSentenceIterator(iterator) .addSentenceIterator(iterator2).build(); int cnt = 0; while (aggr.hasNext()) { String line = aggr.nextSentence(); cnt++; } assertEquals((97162 * 2), cnt); aggr.reset(); while (aggr.hasNext()) { String line = aggr.nextSentence(); cnt++; } assertEquals((97162 * 4), cnt); } }
814
1,655
#include "JsonLoadException.hpp" #include <tinyformat/tinyformat.hpp> namespace Tungsten { JsonLoadException::JsonLoadException(const Path &path) : _description(tfm::format("Unable to load file '%s'", path.fileName())), _what(_description) { } JsonLoadException::JsonLoadException(const std::string &description, const std::string &excerpt) : _description(description), _excerpt(excerpt), _what(tfm::format("%s\n\n%s", _description, _excerpt)) { } }
164
1,947
#include "gurka.h" #include "test.h" #include <gtest/gtest.h> using namespace valhalla; /*************************************************************/ TEST(Standalone, avoid_service) { // Test to make sure bicycle routes do not use highway:service to cut // corners near intersections const std::string ascii_map = R"( A----B----C | | D----E | F)"; const gurka::ways ways = {{"AB", {{"highway", "secondary"}}}, {"BC", {{"highway", "secondary"}}}, {"CE", {{"highway", "tertiary"}}}, {"EF", {{"highway", "tertiary"}}}, {"BD", {{"highway", "service"}}}, {"DE", {{"highway", "service"}}}}; const auto layout = gurka::detail::map_to_coordinates(ascii_map, 100); auto map = gurka::buildtiles(layout, ways, {}, {}, "test/data/gurka_avoid_service"); auto result = gurka::do_action(valhalla::Options::route, map, {"A", "F"}, "bicycle"); // Make sure the path doesn't take service road "B-D-E" gurka::assert::raw::expect_path(result, {"AB", "BC", "CE", "EF"}); } void validate_path(const valhalla::Api& result, const std::vector<std::string>& expected_names) { ASSERT_EQ(result.trip().routes(0).legs_size(), 1); auto leg = result.trip().routes(0).legs(0); gurka::assert::raw::expect_path(result, expected_names); } const std::vector<std::string>& costing = {"auto", "taxi", "bus", "truck", "motorcycle", "motor_scooter", "pedestrian"}; class ServiceRoadsTest : public ::testing::Test { protected: static gurka::map service_streets_map; static void SetUpTestSuite() { const std::string ascii_map = R"( A-1----B--------E-----2-F | | | | | | | | G | | | | C--------D \ I )"; const gurka::ways ways = { {"AB", {{"highway", "secondary"}}}, {"BE", {{"highway", "service"}}}, {"EF", {{"highway", "secondary"}}}, {"FG", {{"highway", "secondary"}}}, {"BC", {{"highway", "secondary"}}}, {"CD", {{"highway", "secondary"}}}, {"DE", {{"highway", "secondary"}}}, {"DI", {{"highway", "residential"}}}, }; const auto layout = gurka::detail::map_to_coordinates(ascii_map, 100); service_streets_map = gurka::buildtiles(layout, ways, {}, {}, "test/data/gurka_service_streets"); } }; gurka::map ServiceRoadsTest::service_streets_map = {}; TEST_F(ServiceRoadsTest, test_default_value) { for (const auto& c : costing) if (c == "motor_scooter" || c == "pedestrian") // For current exmple and with these costings route is not affected validate_path(gurka::do_action(valhalla::Options::route, service_streets_map, {"1", "2"}, c), {"AB", "BE", "EF"}); else validate_path(gurka::do_action(valhalla::Options::route, service_streets_map, {"1", "2"}, c), {"AB", "BC", "CD", "DE", "EF"}); } TEST_F(ServiceRoadsTest, test_use_service_roads) { // favor service roads for (const auto& c : costing) if (c == "truck") // truck is also impacted by 'low_class_penalty' option which is non-zero by default validate_path(gurka::do_action(valhalla::Options::route, service_streets_map, {"1", "2"}, c, {{"/costing_options/" + c + "/service_penalty", "0"}, {"/costing_options/" + c + "/service_factor", "0.1"}, {"/costing_options/" + c + "/low_class_penalty", "0"}}), {"AB", "BE", "EF"}); else validate_path(gurka::do_action(valhalla::Options::route, service_streets_map, {"1", "2"}, c, {{"/costing_options/" + c + "/service_penalty", "0"}, {"/costing_options/" + c + "/service_factor", "0.1"}}), {"AB", "BE", "EF"}); } TEST_F(ServiceRoadsTest, test_avoid_service_roads) { // avoid service roads for (const auto& c : costing) validate_path(gurka::do_action(valhalla::Options::route, service_streets_map, {"1", "2"}, c, {{"/costing_options/" + c + "/service_penalty", "300"}, {"/costing_options/" + c + "/service_factor", "8"}}), {"AB", "BC", "CD", "DE", "EF"}); } TEST(Standalone, service_and_internal) { const std::string ascii_map = R"( A----B----C | | D----E----F )"; const gurka::ways ways = {{"AB", {{"highway", "trunk"}, {"oneway", "yes"}}}, {"BC", {{"highway", "trunk"}, {"oneway", "yes"}}}, {"FE", {{"highway", "trunk"}, {"oneway", "yes"}}}, {"ED", {{"highway", "trunk"}, {"oneway", "yes"}}}, {"CF", {{"highway", "trunk_link"}, {"oneway", "yes"}}}, {"BE", {{"highway", "service"}, {"internal_intersection", "true"}, {"oneway", "yes"}}}}; const auto layout = gurka::detail::map_to_coordinates(ascii_map, 100); // BE is an internal and service edge. { const auto map = gurka::buildtiles(layout, ways, {}, {}, "test/data/gurka_service_and_internal_0", {{"mjolnir.data_processing.infer_internal_intersections", "false"}}); const auto reader = test::make_clean_graphreader(map.config.get_child("mjolnir")); const auto edge = gurka::findEdgeByNodes(*reader, map.nodes, "B", "E"); EXPECT_TRUE(std::get<1>(edge)->internal()); const auto result = gurka::do_action(valhalla::Options::route, map, {"A", "D"}, "auto"); gurka::assert::raw::expect_path(result, {"AB", "BE", "ED"}); } // BE is a service edge. { const auto map = gurka::buildtiles(layout, ways, {}, {}, "test/data/gurka_service_and_internal_1", {{"mjolnir.data_processing.infer_internal_intersections", "true"}}); const auto reader = test::make_clean_graphreader(map.config.get_child("mjolnir")); const auto edge = gurka::findEdgeByNodes(*reader, map.nodes, "B", "E"); EXPECT_FALSE(std::get<1>(edge)->internal()); const auto result = gurka::do_action(valhalla::Options::route, map, {"A", "D"}, "auto"); gurka::assert::raw::expect_path(result, {"AB", "BC", "CF", "FE", "ED"}); } }
2,948
14,668
<gh_stars>1000+ // Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_ENTERPRISE_REPORTING_PREFS_H_ #define CHROME_BROWSER_ENTERPRISE_REPORTING_PREFS_H_ class PrefRegistrySimple; namespace user_prefs { class PrefRegistrySyncable; } namespace enterprise_reporting { extern const char kLastUploadVersion[]; extern const char kCloudExtensionRequestUploadedIds[]; void RegisterLocalStatePrefs(PrefRegistrySimple* registry); void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry); } // namespace enterprise_reporting #endif // CHROME_BROWSER_ENTERPRISE_REPORTING_PREFS_H_
235
3,704
package cn.stylefeng.guns.config; import org.mybatis.spring.annotation.MapperScan; import org.springframework.context.annotation.Configuration; /** * 配置mapper包扫描 * * @author fengshuonan * @date 2020/12/13 16:11 */ @Configuration @MapperScan(basePackages = {"cn.stylefeng.**.mapper"}) public class MapperScanConfiguration { }
128
2,211
// Copyright (c) 2014 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.xwalk.test.util; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; public class ActivityToCausePause extends Activity { private static ActivityToCausePause instance = null; public static void pauseActivity(Context activity) { Intent intent = new Intent(activity, ActivityToCausePause.class); intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT); activity.startActivity(intent); } public static void resumeActivity() { if (instance != null) instance.finish(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); assert(instance == null); instance = this; } @Override public void onDestroy() { super.onDestroy(); instance = null; } }
357
1,969
<reponame>alexhagen/abseil-py # Copyright 2018 The Abseil Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Test helper for argparse_flags_test.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import random from absl import app from absl import flags from absl.flags import argparse_flags FLAGS = flags.FLAGS flags.DEFINE_string('absl_echo', None, 'The echo message from absl.flags.') def parse_flags_simple(argv): """Simple example for absl.flags + argparse.""" parser = argparse_flags.ArgumentParser( description='A simple example of argparse_flags.') parser.add_argument( '--argparse_echo', help='The echo message from argparse_flags') return parser.parse_args(argv[1:]) def main_simple(args): print('--absl_echo is', FLAGS.absl_echo) print('--argparse_echo is', args.argparse_echo) def roll_dice(args): print('Rolled a dice:', random.randint(1, args.num_faces)) def shuffle(args): inputs = list(args.inputs) random.shuffle(inputs) print('Shuffled:', ' '.join(inputs)) def parse_flags_subcommands(argv): """Subcommands example for absl.flags + argparse.""" parser = argparse_flags.ArgumentParser( description='A subcommands example of argparse_flags.') parser.add_argument('--argparse_echo', help='The echo message from argparse_flags') subparsers = parser.add_subparsers(help='The command to execute.') roll_dice_parser = subparsers.add_parser( 'roll_dice', help='Roll a dice.') roll_dice_parser.add_argument('--num_faces', type=int, default=6) roll_dice_parser.set_defaults(command=roll_dice) shuffle_parser = subparsers.add_parser( 'shuffle', help='Shuffle inputs.') shuffle_parser.add_argument( 'inputs', metavar='I', nargs='+', help='Inputs to shuffle.') shuffle_parser.set_defaults(command=shuffle) return parser.parse_args(argv[1:]) def main_subcommands(args): main_simple(args) args.command(args) if __name__ == '__main__': main_func_name = os.environ['MAIN_FUNC'] flags_parser_func_name = os.environ['FLAGS_PARSER_FUNC'] app.run(main=globals()[main_func_name], flags_parser=globals()[flags_parser_func_name])
951
493
/* ========================= eCAL LICENSE ================================= * * Copyright (C) 2016 - 2020 Continental Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * ========================= eCAL LICENSE ================================= */ #include "task_tree_model.h" #include "CustomQt/QAbstractTreeItem.h" #include "tree_item_types.h" #include "globals.h" TaskTreeModel::TaskTreeModel(QObject *parent) :QAbstractTreeModel(parent) { } TaskTreeModel::~TaskTreeModel() { } void TaskTreeModel::reload() { reload(Globals::EcalSysInstance()->GetTaskList()); } void TaskTreeModel::reload(const std::list<std::shared_ptr<EcalSysTask>>& task_list) { removeAllChildren(); // Load the new data QList<QAbstractTreeItem*> task_item_list; for (auto& task : task_list) { TaskTreeItem* task_item = new TaskTreeItem(task); task_item_list.push_back(task_item); } insertItems(task_item_list); } int TaskTreeModel::columnCount(const QModelIndex &/*parent*/) const { return (int)Columns::COLUMN_COUNT; } QVariant TaskTreeModel::headerData(int section, Qt::Orientation orientation, int role) const { if (role == Qt::DisplayRole && orientation == Qt::Orientation::Horizontal) { return columnLabels.at((Columns)section); } return QAbstractTreeModel::headerData(section, orientation, role); } void TaskTreeModel::setHeaderLabel(Columns column, const QString& label) { columnLabels[column] = label; emit headerDataChanged(Qt::Orientation::Horizontal, (int) column, (int) column); } int TaskTreeModel::mapColumnToItem(int model_column, int tree_item_type) const { switch ((TreeItemType)tree_item_type) { case TreeItemType::Task: return task_tree_item_column_mapping.at((Columns)(model_column)); default: return -1; } } QModelIndex TaskTreeModel::index(const std::shared_ptr<EcalSysTask>& task, int column) { QList<QAbstractTreeItem*> task_items = findItems( [&task](QAbstractTreeItem* item) { return ((item->type() == (int)TreeItemType::Task) && static_cast<TaskTreeItem*>(item)->getTask() == task); } ); if (task_items.size() > 0) { return index(task_items.first(), column); } else { return QModelIndex(); } } void TaskTreeModel::updateTask(std::shared_ptr<EcalSysTask> task) { QList<QAbstractTreeItem*> items = findItems( [&task](QAbstractTreeItem* item) { return ((item->type() == (int)TreeItemType::Task) && static_cast<TaskTreeItem*>(item)->getTask() == task); } ); for (auto& item : items) { updateItem(item); } } void TaskTreeModel::addTask(std::shared_ptr<EcalSysTask> new_task) { TaskTreeItem* task_item = new TaskTreeItem(new_task); insertItem(task_item); } void TaskTreeModel::removeTask(std::shared_ptr<EcalSysTask> task) { QList<QAbstractTreeItem*> items = findItems( [&task](QAbstractTreeItem* item) { return ((item->type() == (int)TreeItemType::Task) && static_cast<TaskTreeItem*>(item)->getTask() == task); } ); for (auto& item : items) { removeItem(item); } }
1,229
3,372
<filename>aws-java-sdk-route53/src/main/java/com/amazonaws/services/route53/model/ResourceRecordSet.java /* * Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.route53.model; import java.io.Serializable; import javax.annotation.Generated; /** * <p> * Information about the resource record set to create or delete. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ResourceRecordSet" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ResourceRecordSet implements Serializable, Cloneable { /** * <p> * For <code>ChangeResourceRecordSets</code> requests, the name of the record that you want to create, update, or * delete. For <code>ListResourceRecordSets</code> responses, the name of a record in the specified hosted zone. * </p> * <p> * <b>ChangeResourceRecordSets Only</b> * </p> * <p> * Enter a fully qualified domain name, for example, <code>www.example.com</code>. You can optionally include a * trailing dot. If you omit the trailing dot, Amazon Route 53 assumes that the domain name that you specify is * fully qualified. This means that Route 53 treats <code>www.example.com</code> (without a trailing dot) and * <code>www.example.com.</code> (with a trailing dot) as identical. * </p> * <p> * For information about how to specify characters other than <code>a-z</code>, <code>0-9</code>, and <code>-</code> * (hyphen) and how to specify internationalized domain names, see <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DomainNameFormat.html">DNS Domain Name Format</a> * in the <i>Amazon Route 53 Developer Guide</i>. * </p> * <p> * You can use the asterisk (*) wildcard to replace the leftmost label in a domain name, for example, * <code>*.example.com</code>. Note the following: * </p> * <ul> * <li> * <p> * The * must replace the entire label. For example, you can't specify <code>*prod.example.com</code> or * <code>prod*.example.com</code>. * </p> * </li> * <li> * <p> * The * can't replace any of the middle labels, for example, marketing.*.example.com. * </p> * </li> * <li> * <p> * If you include * in any position other than the leftmost label in a domain name, DNS treats it as an * character * (ASCII 42), not as a wildcard. * </p> * <important> * <p> * You can't use the * wildcard for resource records sets that have a type of NS. * </p> * </important></li> * </ul> * <p> * You can use the * wildcard as the leftmost label in a domain name, for example, <code>*.example.com</code>. You * can't use an * for one of the middle labels, for example, <code>marketing.*.example.com</code>. In addition, the * * must replace the entire label; for example, you can't specify <code>prod*.example.com</code>. * </p> */ private String name; /** * <p> * The DNS record type. For information about different record types and how data is encoded for them, see <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/ResourceRecordTypes.html">Supported DNS Resource * Record Types</a> in the <i>Amazon Route 53 Developer Guide</i>. * </p> * <p> * Valid values for basic resource record sets: <code>A</code> | <code>AAAA</code> | <code>CAA</code> | * <code>CNAME</code> | <code>DS</code> |<code>MX</code> | <code>NAPTR</code> | <code>NS</code> | <code>PTR</code> | * <code>SOA</code> | <code>SPF</code> | <code>SRV</code> | <code>TXT</code> * </p> * <p> * Values for weighted, latency, geolocation, and failover resource record sets: <code>A</code> | <code>AAAA</code> * | <code>CAA</code> | <code>CNAME</code> | <code>MX</code> | <code>NAPTR</code> | <code>PTR</code> | * <code>SPF</code> | <code>SRV</code> | <code>TXT</code>. When creating a group of weighted, latency, geolocation, * or failover resource record sets, specify the same value for all of the resource record sets in the group. * </p> * <p> * Valid values for multivalue answer resource record sets: <code>A</code> | <code>AAAA</code> | <code>MX</code> | * <code>NAPTR</code> | <code>PTR</code> | <code>SPF</code> | <code>SRV</code> | <code>TXT</code> * </p> * <note> * <p> * SPF records were formerly used to verify the identity of the sender of email messages. However, we no longer * recommend that you create resource record sets for which the value of <code>Type</code> is <code>SPF</code>. RFC * 7208, <i>Sender Policy Framework (SPF) for Authorizing Use of Domains in Email, Version 1</i>, has been updated * to say, * "...[I]ts existence and mechanism defined in [RFC4408] have led to some interoperability issues. Accordingly, its use is no longer appropriate for SPF version 1; implementations are not to use it." * In RFC 7208, see section 14.1, <a href="http://tools.ietf.org/html/rfc7208#section-14.1">The SPF DNS Record * Type</a>. * </p> * </note> * <p> * Values for alias resource record sets: * </p> * <ul> * <li> * <p> * <b>Amazon API Gateway custom regional APIs and edge-optimized APIs:</b> <code>A</code> * </p> * </li> * <li> * <p> * <b>CloudFront distributions:</b> <code>A</code> * </p> * <p> * If IPv6 is enabled for the distribution, create two resource record sets to route traffic to your distribution, * one with a value of <code>A</code> and one with a value of <code>AAAA</code>. * </p> * </li> * <li> * <p> * <b>Amazon API Gateway environment that has a regionalized subdomain</b>: <code>A</code> * </p> * </li> * <li> * <p> * <b>ELB load balancers:</b> <code>A</code> | <code>AAAA</code> * </p> * </li> * <li> * <p> * <b>Amazon S3 buckets:</b> <code>A</code> * </p> * </li> * <li> * <p> * <b>Amazon Virtual Private Cloud interface VPC endpoints</b> <code>A</code> * </p> * </li> * <li> * <p> * <b>Another resource record set in this hosted zone:</b> Specify the type of the resource record set that you're * creating the alias for. All values are supported except <code>NS</code> and <code>SOA</code>. * </p> * <note> * <p> * If you're creating an alias record that has the same name as the hosted zone (known as the zone apex), you can't * route traffic to a record for which the value of <code>Type</code> is <code>CNAME</code>. This is because the * alias record must have the same type as the record you're routing traffic to, and creating a CNAME record for the * zone apex isn't supported even for an alias record. * </p> * </note></li> * </ul> */ private String type; /** * <p> * <i>Resource record sets that have a routing policy other than simple:</i> An identifier that differentiates among * multiple resource record sets that have the same combination of name and type, such as multiple weighted resource * record sets named acme.example.com that have a type of A. In a group of resource record sets that have the same * name and type, the value of <code>SetIdentifier</code> must be unique for each resource record set. * </p> * <p> * For information about routing policies, see <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-policy.html">Choosing a Routing * Policy</a> in the <i>Amazon Route 53 Developer Guide</i>. * </p> */ private String setIdentifier; /** * <p> * <i>Weighted resource record sets only:</i> Among resource record sets that have the same combination of DNS name * and type, a value that determines the proportion of DNS queries that Amazon Route 53 responds to using the * current resource record set. Route 53 calculates the sum of the weights for the resource record sets that have * the same combination of DNS name and type. Route 53 then responds to queries based on the ratio of a resource's * weight to the total. Note the following: * </p> * <ul> * <li> * <p> * You must specify a value for the <code>Weight</code> element for every weighted resource record set. * </p> * </li> * <li> * <p> * You can only specify one <code>ResourceRecord</code> per weighted resource record set. * </p> * </li> * <li> * <p> * You can't create latency, failover, or geolocation resource record sets that have the same values for the * <code>Name</code> and <code>Type</code> elements as weighted resource record sets. * </p> * </li> * <li> * <p> * You can create a maximum of 100 weighted resource record sets that have the same values for the <code>Name</code> * and <code>Type</code> elements. * </p> * </li> * <li> * <p> * For weighted (but not weighted alias) resource record sets, if you set <code>Weight</code> to <code>0</code> for * a resource record set, Route 53 never responds to queries with the applicable value for that resource record set. * However, if you set <code>Weight</code> to <code>0</code> for all resource record sets that have the same * combination of DNS name and type, traffic is routed to all resources with equal probability. * </p> * <p> * The effect of setting <code>Weight</code> to <code>0</code> is different when you associate health checks with * weighted resource record sets. For more information, see <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-configuring-options.html">Options * for Configuring Route 53 Active-Active and Active-Passive Failover</a> in the <i>Amazon Route 53 Developer * Guide</i>. * </p> * </li> * </ul> */ private Long weight; /** * <p> * <i>Latency-based resource record sets only:</i> The Amazon EC2 Region where you created the resource that this * resource record set refers to. The resource typically is an Amazon Web Services resource, such as an EC2 instance * or an ELB load balancer, and is referred to by an IP address or a DNS domain name, depending on the record type. * </p> * <note> * <p> * Although creating latency and latency alias resource record sets in a private hosted zone is allowed, it's not * supported. * </p> * </note> * <p> * When Amazon Route 53 receives a DNS query for a domain name and type for which you have created latency resource * record sets, Route 53 selects the latency resource record set that has the lowest latency between the end user * and the associated Amazon EC2 Region. Route 53 then returns the value that is associated with the selected * resource record set. * </p> * <p> * Note the following: * </p> * <ul> * <li> * <p> * You can only specify one <code>ResourceRecord</code> per latency resource record set. * </p> * </li> * <li> * <p> * You can only create one latency resource record set for each Amazon EC2 Region. * </p> * </li> * <li> * <p> * You aren't required to create latency resource record sets for all Amazon EC2 Regions. Route 53 will choose the * region with the best latency from among the regions that you create latency resource record sets for. * </p> * </li> * <li> * <p> * You can't create non-latency resource record sets that have the same values for the <code>Name</code> and * <code>Type</code> elements as latency resource record sets. * </p> * </li> * </ul> */ private String region; /** * <p> * <i>Geolocation resource record sets only:</i> A complex type that lets you control how Amazon Route 53 responds * to DNS queries based on the geographic origin of the query. For example, if you want all queries from Africa to * be routed to a web server with an IP address of <code>192.0.2.111</code>, create a resource record set with a * <code>Type</code> of <code>A</code> and a <code>ContinentCode</code> of <code>AF</code>. * </p> * <note> * <p> * Although creating geolocation and geolocation alias resource record sets in a private hosted zone is allowed, * it's not supported. * </p> * </note> * <p> * If you create separate resource record sets for overlapping geographic regions (for example, one resource record * set for a continent and one for a country on the same continent), priority goes to the smallest geographic * region. This allows you to route most queries for a continent to one resource and to route queries for a country * on that continent to a different resource. * </p> * <p> * You can't create two geolocation resource record sets that specify the same geographic location. * </p> * <p> * The value <code>*</code> in the <code>CountryCode</code> element matches all geographic locations that aren't * specified in other geolocation resource record sets that have the same values for the <code>Name</code> and * <code>Type</code> elements. * </p> * <important> * <p> * Geolocation works by mapping IP addresses to locations. However, some IP addresses aren't mapped to geographic * locations, so even if you create geolocation resource record sets that cover all seven continents, Route 53 will * receive some DNS queries from locations that it can't identify. We recommend that you create a resource record * set for which the value of <code>CountryCode</code> is <code>*</code>. Two groups of queries are routed to the * resource that you specify in this record: queries that come from locations for which you haven't created * geolocation resource record sets and queries from IP addresses that aren't mapped to a location. If you don't * create a <code>*</code> resource record set, Route 53 returns a "no answer" response for queries from those * locations. * </p> * </important> * <p> * You can't create non-geolocation resource record sets that have the same values for the <code>Name</code> and * <code>Type</code> elements as geolocation resource record sets. * </p> */ private GeoLocation geoLocation; /** * <p> * <i>Failover resource record sets only:</i> To configure failover, you add the <code>Failover</code> element to * two resource record sets. For one resource record set, you specify <code>PRIMARY</code> as the value for * <code>Failover</code>; for the other resource record set, you specify <code>SECONDARY</code>. In addition, you * include the <code>HealthCheckId</code> element and specify the health check that you want Amazon Route 53 to * perform for each resource record set. * </p> * <p> * Except where noted, the following failover behaviors assume that you have included the <code>HealthCheckId</code> * element in both resource record sets: * </p> * <ul> * <li> * <p> * When the primary resource record set is healthy, Route 53 responds to DNS queries with the applicable value from * the primary resource record set regardless of the health of the secondary resource record set. * </p> * </li> * <li> * <p> * When the primary resource record set is unhealthy and the secondary resource record set is healthy, Route 53 * responds to DNS queries with the applicable value from the secondary resource record set. * </p> * </li> * <li> * <p> * When the secondary resource record set is unhealthy, Route 53 responds to DNS queries with the applicable value * from the primary resource record set regardless of the health of the primary resource record set. * </p> * </li> * <li> * <p> * If you omit the <code>HealthCheckId</code> element for the secondary resource record set, and if the primary * resource record set is unhealthy, Route 53 always responds to DNS queries with the applicable value from the * secondary resource record set. This is true regardless of the health of the associated endpoint. * </p> * </li> * </ul> * <p> * You can't create non-failover resource record sets that have the same values for the <code>Name</code> and * <code>Type</code> elements as failover resource record sets. * </p> * <p> * For failover alias resource record sets, you must also include the <code>EvaluateTargetHealth</code> element and * set the value to true. * </p> * <p> * For more information about configuring failover for Route 53, see the following topics in the <i>Amazon Route 53 * Developer Guide</i>: * </p> * <ul> * <li> * <p> * <a href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover.html">Route 53 Health Checks and * DNS Failover</a> * </p> * </li> * <li> * <p> * <a href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-private-hosted-zones.html"> * Configuring Failover in a Private Hosted Zone</a> * </p> * </li> * </ul> */ private String failover; /** * <p> * <i>Multivalue answer resource record sets only</i>: To route traffic approximately randomly to multiple * resources, such as web servers, create one multivalue answer record for each resource and specify * <code>true</code> for <code>MultiValueAnswer</code>. Note the following: * </p> * <ul> * <li> * <p> * If you associate a health check with a multivalue answer resource record set, Amazon Route 53 responds to DNS * queries with the corresponding IP address only when the health check is healthy. * </p> * </li> * <li> * <p> * If you don't associate a health check with a multivalue answer record, Route 53 always considers the record to be * healthy. * </p> * </li> * <li> * <p> * Route 53 responds to DNS queries with up to eight healthy records; if you have eight or fewer healthy records, * Route 53 responds to all DNS queries with all the healthy records. * </p> * </li> * <li> * <p> * If you have more than eight healthy records, Route 53 responds to different DNS resolvers with different * combinations of healthy records. * </p> * </li> * <li> * <p> * When all records are unhealthy, Route 53 responds to DNS queries with up to eight unhealthy records. * </p> * </li> * <li> * <p> * If a resource becomes unavailable after a resolver caches a response, client software typically tries another of * the IP addresses in the response. * </p> * </li> * </ul> * <p> * You can't create multivalue answer alias records. * </p> */ private Boolean multiValueAnswer; /** * <p> * The resource record cache time to live (TTL), in seconds. Note the following: * </p> * <ul> * <li> * <p> * If you're creating or updating an alias resource record set, omit <code>TTL</code>. Amazon Route 53 uses the * value of <code>TTL</code> for the alias target. * </p> * </li> * <li> * <p> * If you're associating this resource record set with a health check (if you're adding a <code>HealthCheckId</code> * element), we recommend that you specify a <code>TTL</code> of 60 seconds or less so clients respond quickly to * changes in health status. * </p> * </li> * <li> * <p> * All of the resource record sets in a group of weighted resource record sets must have the same value for * <code>TTL</code>. * </p> * </li> * <li> * <p> * If a group of weighted resource record sets includes one or more weighted alias resource record sets for which * the alias target is an ELB load balancer, we recommend that you specify a <code>TTL</code> of 60 seconds for all * of the non-alias weighted resource record sets that have the same name and type. Values other than 60 seconds * (the TTL for load balancers) will change the effect of the values that you specify for <code>Weight</code>. * </p> * </li> * </ul> */ private Long tTL; /** * <p> * Information about the resource records to act upon. * </p> * <note> * <p> * If you're creating an alias resource record set, omit <code>ResourceRecords</code>. * </p> * </note> */ private com.amazonaws.internal.SdkInternalList<ResourceRecord> resourceRecords; /** * <p> * <i>Alias resource record sets only:</i> Information about the Amazon Web Services resource, such as a CloudFront * distribution or an Amazon S3 bucket, that you want to route traffic to. * </p> * <p> * If you're creating resource records sets for a private hosted zone, note the following: * </p> * <ul> * <li> * <p> * You can't create an alias resource record set in a private hosted zone to route traffic to a CloudFront * distribution. * </p> * </li> * <li> * <p> * Creating geolocation alias resource record sets or latency alias resource record sets in a private hosted zone is * unsupported. * </p> * </li> * <li> * <p> * For information about creating failover resource record sets in a private hosted zone, see <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-private-hosted-zones.html" * >Configuring Failover in a Private Hosted Zone</a> in the <i>Amazon Route 53 Developer Guide</i>. * </p> * </li> * </ul> */ private AliasTarget aliasTarget; /** * <p> * If you want Amazon Route 53 to return this resource record set in response to a DNS query only when the status of * a health check is healthy, include the <code>HealthCheckId</code> element and specify the ID of the applicable * health check. * </p> * <p> * Route 53 determines whether a resource record set is healthy based on one of the following: * </p> * <ul> * <li> * <p> * By periodically sending a request to the endpoint that is specified in the health check * </p> * </li> * <li> * <p> * By aggregating the status of a specified group of health checks (calculated health checks) * </p> * </li> * <li> * <p> * By determining the current state of a CloudWatch alarm (CloudWatch metric health checks) * </p> * </li> * </ul> * <important> * <p> * Route 53 doesn't check the health of the endpoint that is specified in the resource record set, for example, the * endpoint specified by the IP address in the <code>Value</code> element. When you add a <code>HealthCheckId</code> * element to a resource record set, Route 53 checks the health of the endpoint that you specified in the health * check. * </p> * </important> * <p> * For more information, see the following topics in the <i>Amazon Route 53 Developer Guide</i>: * </p> * <ul> * <li> * <p> * <a href= * "https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-determining-health-of-endpoints.html">How * Amazon Route 53 Determines Whether an Endpoint Is Healthy</a> * </p> * </li> * <li> * <p> * <a href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover.html">Route 53 Health Checks and * DNS Failover</a> * </p> * </li> * <li> * <p> * <a href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-private-hosted-zones.html"> * Configuring Failover in a Private Hosted Zone</a> * </p> * </li> * </ul> * <p> * <b>When to Specify HealthCheckId</b> * </p> * <p> * Specifying a value for <code>HealthCheckId</code> is useful only when Route 53 is choosing between two or more * resource record sets to respond to a DNS query, and you want Route 53 to base the choice in part on the status of * a health check. Configuring health checks makes sense only in the following configurations: * </p> * <ul> * <li> * <p> * <b>Non-alias resource record sets</b>: You're checking the health of a group of non-alias resource record sets * that have the same routing policy, name, and type (such as multiple weighted records named www.example.com with a * type of A) and you specify health check IDs for all the resource record sets. * </p> * <p> * If the health check status for a resource record set is healthy, Route 53 includes the record among the records * that it responds to DNS queries with. * </p> * <p> * If the health check status for a resource record set is unhealthy, Route 53 stops responding to DNS queries using * the value for that resource record set. * </p> * <p> * If the health check status for all resource record sets in the group is unhealthy, Route 53 considers all * resource record sets in the group healthy and responds to DNS queries accordingly. * </p> * </li> * <li> * <p> * <b>Alias resource record sets</b>: You specify the following settings: * </p> * <ul> * <li> * <p> * You set <code>EvaluateTargetHealth</code> to true for an alias resource record set in a group of resource record * sets that have the same routing policy, name, and type (such as multiple weighted records named www.example.com * with a type of A). * </p> * </li> * <li> * <p> * You configure the alias resource record set to route traffic to a non-alias resource record set in the same * hosted zone. * </p> * </li> * <li> * <p> * You specify a health check ID for the non-alias resource record set. * </p> * </li> * </ul> * <p> * If the health check status is healthy, Route 53 considers the alias resource record set to be healthy and * includes the alias record among the records that it responds to DNS queries with. * </p> * <p> * If the health check status is unhealthy, Route 53 stops responding to DNS queries using the alias resource record * set. * </p> * <note> * <p> * The alias resource record set can also route traffic to a <i>group</i> of non-alias resource record sets that * have the same routing policy, name, and type. In that configuration, associate health checks with all of the * resource record sets in the group of non-alias resource record sets. * </p> * </note></li> * </ul> * <p> * <b>Geolocation Routing</b> * </p> * <p> * For geolocation resource record sets, if an endpoint is unhealthy, Route 53 looks for a resource record set for * the larger, associated geographic region. For example, suppose you have resource record sets for a state in the * United States, for the entire United States, for North America, and a resource record set that has <code>*</code> * for <code>CountryCode</code> is <code>*</code>, which applies to all locations. If the endpoint for the state * resource record set is unhealthy, Route 53 checks for healthy resource record sets in the following order until * it finds a resource record set for which the endpoint is healthy: * </p> * <ul> * <li> * <p> * The United States * </p> * </li> * <li> * <p> * North America * </p> * </li> * <li> * <p> * The default resource record set * </p> * </li> * </ul> * <p> * <b>Specifying the Health Check Endpoint by Domain Name</b> * </p> * <p> * If your health checks specify the endpoint only by domain name, we recommend that you create a separate health * check for each endpoint. For example, create a health check for each <code>HTTP</code> server that is serving * content for <code>www.example.com</code>. For the value of <code>FullyQualifiedDomainName</code>, specify the * domain name of the server (such as <code>us-east-2-www.example.com</code>), not the name of the resource record * sets (<code>www.example.com</code>). * </p> * <important> * <p> * Health check results will be unpredictable if you do the following: * </p> * <ul> * <li> * <p> * Create a health check that has the same value for <code>FullyQualifiedDomainName</code> as the name of a resource * record set. * </p> * </li> * <li> * <p> * Associate that health check with the resource record set. * </p> * </li> * </ul> * </important> */ private String healthCheckId; /** * <p> * When you create a traffic policy instance, Amazon Route 53 automatically creates a resource record set. * <code>TrafficPolicyInstanceId</code> is the ID of the traffic policy instance that Route 53 created this resource * record set for. * </p> * <important> * <p> * To delete the resource record set that is associated with a traffic policy instance, use * <code>DeleteTrafficPolicyInstance</code>. Route 53 will delete the resource record set automatically. If you * delete the resource record set by using <code>ChangeResourceRecordSets</code>, Route 53 doesn't automatically * delete the traffic policy instance, and you'll continue to be charged for it even though it's no longer in use. * </p> * </important> */ private String trafficPolicyInstanceId; /** * Default constructor for ResourceRecordSet object. Callers should use the setter or fluent setter (with...) * methods to initialize the object after creating it. */ public ResourceRecordSet() { } /** * Constructs a new ResourceRecordSet object. Callers should use the setter or fluent setter (with...) methods to * initialize any additional object members. * * @param name * For <code>ChangeResourceRecordSets</code> requests, the name of the record that you want to create, * update, or delete. For <code>ListResourceRecordSets</code> responses, the name of a record in the * specified hosted zone.</p> * <p> * <b>ChangeResourceRecordSets Only</b> * </p> * <p> * Enter a fully qualified domain name, for example, <code>www.example.com</code>. You can optionally include * a trailing dot. If you omit the trailing dot, Amazon Route 53 assumes that the domain name that you * specify is fully qualified. This means that Route 53 treats <code>www.example.com</code> (without a * trailing dot) and <code>www.example.com.</code> (with a trailing dot) as identical. * </p> * <p> * For information about how to specify characters other than <code>a-z</code>, <code>0-9</code>, and * <code>-</code> (hyphen) and how to specify internationalized domain names, see <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DomainNameFormat.html">DNS Domain Name * Format</a> in the <i>Amazon Route 53 Developer Guide</i>. * </p> * <p> * You can use the asterisk (*) wildcard to replace the leftmost label in a domain name, for example, * <code>*.example.com</code>. Note the following: * </p> * <ul> * <li> * <p> * The * must replace the entire label. For example, you can't specify <code>*prod.example.com</code> or * <code>prod*.example.com</code>. * </p> * </li> * <li> * <p> * The * can't replace any of the middle labels, for example, marketing.*.example.com. * </p> * </li> * <li> * <p> * If you include * in any position other than the leftmost label in a domain name, DNS treats it as an * * character (ASCII 42), not as a wildcard. * </p> * <important> * <p> * You can't use the * wildcard for resource records sets that have a type of NS. * </p> * </important></li> * </ul> * <p> * You can use the * wildcard as the leftmost label in a domain name, for example, <code>*.example.com</code> * . You can't use an * for one of the middle labels, for example, <code>marketing.*.example.com</code>. In * addition, the * must replace the entire label; for example, you can't specify * <code>prod*.example.com</code>. * @param type * The DNS record type. For information about different record types and how data is encoded for them, see <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/ResourceRecordTypes.html">Supported DNS * Resource Record Types</a> in the <i>Amazon Route 53 Developer Guide</i>. * </p> * <p> * Valid values for basic resource record sets: <code>A</code> | <code>AAAA</code> | <code>CAA</code> | * <code>CNAME</code> | <code>DS</code> |<code>MX</code> | <code>NAPTR</code> | <code>NS</code> | * <code>PTR</code> | <code>SOA</code> | <code>SPF</code> | <code>SRV</code> | <code>TXT</code> * </p> * <p> * Values for weighted, latency, geolocation, and failover resource record sets: <code>A</code> | * <code>AAAA</code> | <code>CAA</code> | <code>CNAME</code> | <code>MX</code> | <code>NAPTR</code> | * <code>PTR</code> | <code>SPF</code> | <code>SRV</code> | <code>TXT</code>. When creating a group of * weighted, latency, geolocation, or failover resource record sets, specify the same value for all of the * resource record sets in the group. * </p> * <p> * Valid values for multivalue answer resource record sets: <code>A</code> | <code>AAAA</code> | * <code>MX</code> | <code>NAPTR</code> | <code>PTR</code> | <code>SPF</code> | <code>SRV</code> | * <code>TXT</code> * </p> * <note> * <p> * SPF records were formerly used to verify the identity of the sender of email messages. However, we no * longer recommend that you create resource record sets for which the value of <code>Type</code> is * <code>SPF</code>. RFC 7208, <i>Sender Policy Framework (SPF) for Authorizing Use of Domains in Email, * Version 1</i>, has been updated to say, * "...[I]ts existence and mechanism defined in [RFC4408] have led to some interoperability issues. Accordingly, its use is no longer appropriate for SPF version 1; implementations are not to use it." * In RFC 7208, see section 14.1, <a href="http://tools.ietf.org/html/rfc7208#section-14.1">The SPF DNS * Record Type</a>. * </p> * </note> * <p> * Values for alias resource record sets: * </p> * <ul> * <li> * <p> * <b>Amazon API Gateway custom regional APIs and edge-optimized APIs:</b> <code>A</code> * </p> * </li> * <li> * <p> * <b>CloudFront distributions:</b> <code>A</code> * </p> * <p> * If IPv6 is enabled for the distribution, create two resource record sets to route traffic to your * distribution, one with a value of <code>A</code> and one with a value of <code>AAAA</code>. * </p> * </li> * <li> * <p> * <b>Amazon API Gateway environment that has a regionalized subdomain</b>: <code>A</code> * </p> * </li> * <li> * <p> * <b>ELB load balancers:</b> <code>A</code> | <code>AAAA</code> * </p> * </li> * <li> * <p> * <b>Amazon S3 buckets:</b> <code>A</code> * </p> * </li> * <li> * <p> * <b>Amazon Virtual Private Cloud interface VPC endpoints</b> <code>A</code> * </p> * </li> * <li> * <p> * <b>Another resource record set in this hosted zone:</b> Specify the type of the resource record set that * you're creating the alias for. All values are supported except <code>NS</code> and <code>SOA</code>. * </p> * <note> * <p> * If you're creating an alias record that has the same name as the hosted zone (known as the zone apex), you * can't route traffic to a record for which the value of <code>Type</code> is <code>CNAME</code>. This is * because the alias record must have the same type as the record you're routing traffic to, and creating a * CNAME record for the zone apex isn't supported even for an alias record. * </p> * </note></li> */ public ResourceRecordSet(String name, String type) { setName(name); setType(type); } /** * Constructs a new ResourceRecordSet object. Callers should use the setter or fluent setter (with...) methods to * initialize any additional object members. * * @param name * For <code>ChangeResourceRecordSets</code> requests, the name of the record that you want to create, * update, or delete. For <code>ListResourceRecordSets</code> responses, the name of a record in the * specified hosted zone.</p> * <p> * <b>ChangeResourceRecordSets Only</b> * </p> * <p> * Enter a fully qualified domain name, for example, <code>www.example.com</code>. You can optionally include * a trailing dot. If you omit the trailing dot, Amazon Route 53 assumes that the domain name that you * specify is fully qualified. This means that Route 53 treats <code>www.example.com</code> (without a * trailing dot) and <code>www.example.com.</code> (with a trailing dot) as identical. * </p> * <p> * For information about how to specify characters other than <code>a-z</code>, <code>0-9</code>, and * <code>-</code> (hyphen) and how to specify internationalized domain names, see <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DomainNameFormat.html">DNS Domain Name * Format</a> in the <i>Amazon Route 53 Developer Guide</i>. * </p> * <p> * You can use the asterisk (*) wildcard to replace the leftmost label in a domain name, for example, * <code>*.example.com</code>. Note the following: * </p> * <ul> * <li> * <p> * The * must replace the entire label. For example, you can't specify <code>*prod.example.com</code> or * <code>prod*.example.com</code>. * </p> * </li> * <li> * <p> * The * can't replace any of the middle labels, for example, marketing.*.example.com. * </p> * </li> * <li> * <p> * If you include * in any position other than the leftmost label in a domain name, DNS treats it as an * * character (ASCII 42), not as a wildcard. * </p> * <important> * <p> * You can't use the * wildcard for resource records sets that have a type of NS. * </p> * </important></li> * </ul> * <p> * You can use the * wildcard as the leftmost label in a domain name, for example, <code>*.example.com</code> * . You can't use an * for one of the middle labels, for example, <code>marketing.*.example.com</code>. In * addition, the * must replace the entire label; for example, you can't specify * <code>prod*.example.com</code>. * @param type * The DNS record type. For information about different record types and how data is encoded for them, see <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/ResourceRecordTypes.html">Supported DNS * Resource Record Types</a> in the <i>Amazon Route 53 Developer Guide</i>. * </p> * <p> * Valid values for basic resource record sets: <code>A</code> | <code>AAAA</code> | <code>CAA</code> | * <code>CNAME</code> | <code>DS</code> |<code>MX</code> | <code>NAPTR</code> | <code>NS</code> | * <code>PTR</code> | <code>SOA</code> | <code>SPF</code> | <code>SRV</code> | <code>TXT</code> * </p> * <p> * Values for weighted, latency, geolocation, and failover resource record sets: <code>A</code> | * <code>AAAA</code> | <code>CAA</code> | <code>CNAME</code> | <code>MX</code> | <code>NAPTR</code> | * <code>PTR</code> | <code>SPF</code> | <code>SRV</code> | <code>TXT</code>. When creating a group of * weighted, latency, geolocation, or failover resource record sets, specify the same value for all of the * resource record sets in the group. * </p> * <p> * Valid values for multivalue answer resource record sets: <code>A</code> | <code>AAAA</code> | * <code>MX</code> | <code>NAPTR</code> | <code>PTR</code> | <code>SPF</code> | <code>SRV</code> | * <code>TXT</code> * </p> * <note> * <p> * SPF records were formerly used to verify the identity of the sender of email messages. However, we no * longer recommend that you create resource record sets for which the value of <code>Type</code> is * <code>SPF</code>. RFC 7208, <i>Sender Policy Framework (SPF) for Authorizing Use of Domains in Email, * Version 1</i>, has been updated to say, * "...[I]ts existence and mechanism defined in [RFC4408] have led to some interoperability issues. Accordingly, its use is no longer appropriate for SPF version 1; implementations are not to use it." * In RFC 7208, see section 14.1, <a href="http://tools.ietf.org/html/rfc7208#section-14.1">The SPF DNS * Record Type</a>. * </p> * </note> * <p> * Values for alias resource record sets: * </p> * <ul> * <li> * <p> * <b>Amazon API Gateway custom regional APIs and edge-optimized APIs:</b> <code>A</code> * </p> * </li> * <li> * <p> * <b>CloudFront distributions:</b> <code>A</code> * </p> * <p> * If IPv6 is enabled for the distribution, create two resource record sets to route traffic to your * distribution, one with a value of <code>A</code> and one with a value of <code>AAAA</code>. * </p> * </li> * <li> * <p> * <b>Amazon API Gateway environment that has a regionalized subdomain</b>: <code>A</code> * </p> * </li> * <li> * <p> * <b>ELB load balancers:</b> <code>A</code> | <code>AAAA</code> * </p> * </li> * <li> * <p> * <b>Amazon S3 buckets:</b> <code>A</code> * </p> * </li> * <li> * <p> * <b>Amazon Virtual Private Cloud interface VPC endpoints</b> <code>A</code> * </p> * </li> * <li> * <p> * <b>Another resource record set in this hosted zone:</b> Specify the type of the resource record set that * you're creating the alias for. All values are supported except <code>NS</code> and <code>SOA</code>. * </p> * <note> * <p> * If you're creating an alias record that has the same name as the hosted zone (known as the zone apex), you * can't route traffic to a record for which the value of <code>Type</code> is <code>CNAME</code>. This is * because the alias record must have the same type as the record you're routing traffic to, and creating a * CNAME record for the zone apex isn't supported even for an alias record. * </p> * </note></li> */ public ResourceRecordSet(String name, RRType type) { setName(name); setType(type.toString()); } /** * <p> * For <code>ChangeResourceRecordSets</code> requests, the name of the record that you want to create, update, or * delete. For <code>ListResourceRecordSets</code> responses, the name of a record in the specified hosted zone. * </p> * <p> * <b>ChangeResourceRecordSets Only</b> * </p> * <p> * Enter a fully qualified domain name, for example, <code>www.example.com</code>. You can optionally include a * trailing dot. If you omit the trailing dot, Amazon Route 53 assumes that the domain name that you specify is * fully qualified. This means that Route 53 treats <code>www.example.com</code> (without a trailing dot) and * <code>www.example.com.</code> (with a trailing dot) as identical. * </p> * <p> * For information about how to specify characters other than <code>a-z</code>, <code>0-9</code>, and <code>-</code> * (hyphen) and how to specify internationalized domain names, see <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DomainNameFormat.html">DNS Domain Name Format</a> * in the <i>Amazon Route 53 Developer Guide</i>. * </p> * <p> * You can use the asterisk (*) wildcard to replace the leftmost label in a domain name, for example, * <code>*.example.com</code>. Note the following: * </p> * <ul> * <li> * <p> * The * must replace the entire label. For example, you can't specify <code>*prod.example.com</code> or * <code>prod*.example.com</code>. * </p> * </li> * <li> * <p> * The * can't replace any of the middle labels, for example, marketing.*.example.com. * </p> * </li> * <li> * <p> * If you include * in any position other than the leftmost label in a domain name, DNS treats it as an * character * (ASCII 42), not as a wildcard. * </p> * <important> * <p> * You can't use the * wildcard for resource records sets that have a type of NS. * </p> * </important></li> * </ul> * <p> * You can use the * wildcard as the leftmost label in a domain name, for example, <code>*.example.com</code>. You * can't use an * for one of the middle labels, for example, <code>marketing.*.example.com</code>. In addition, the * * must replace the entire label; for example, you can't specify <code>prod*.example.com</code>. * </p> * * @param name * For <code>ChangeResourceRecordSets</code> requests, the name of the record that you want to create, * update, or delete. For <code>ListResourceRecordSets</code> responses, the name of a record in the * specified hosted zone.</p> * <p> * <b>ChangeResourceRecordSets Only</b> * </p> * <p> * Enter a fully qualified domain name, for example, <code>www.example.com</code>. You can optionally include * a trailing dot. If you omit the trailing dot, Amazon Route 53 assumes that the domain name that you * specify is fully qualified. This means that Route 53 treats <code>www.example.com</code> (without a * trailing dot) and <code>www.example.com.</code> (with a trailing dot) as identical. * </p> * <p> * For information about how to specify characters other than <code>a-z</code>, <code>0-9</code>, and * <code>-</code> (hyphen) and how to specify internationalized domain names, see <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DomainNameFormat.html">DNS Domain Name * Format</a> in the <i>Amazon Route 53 Developer Guide</i>. * </p> * <p> * You can use the asterisk (*) wildcard to replace the leftmost label in a domain name, for example, * <code>*.example.com</code>. Note the following: * </p> * <ul> * <li> * <p> * The * must replace the entire label. For example, you can't specify <code>*prod.example.com</code> or * <code>prod*.example.com</code>. * </p> * </li> * <li> * <p> * The * can't replace any of the middle labels, for example, marketing.*.example.com. * </p> * </li> * <li> * <p> * If you include * in any position other than the leftmost label in a domain name, DNS treats it as an * * character (ASCII 42), not as a wildcard. * </p> * <important> * <p> * You can't use the * wildcard for resource records sets that have a type of NS. * </p> * </important></li> * </ul> * <p> * You can use the * wildcard as the leftmost label in a domain name, for example, <code>*.example.com</code> * . You can't use an * for one of the middle labels, for example, <code>marketing.*.example.com</code>. In * addition, the * must replace the entire label; for example, you can't specify * <code>prod*.example.com</code>. */ public void setName(String name) { this.name = name; } /** * <p> * For <code>ChangeResourceRecordSets</code> requests, the name of the record that you want to create, update, or * delete. For <code>ListResourceRecordSets</code> responses, the name of a record in the specified hosted zone. * </p> * <p> * <b>ChangeResourceRecordSets Only</b> * </p> * <p> * Enter a fully qualified domain name, for example, <code>www.example.com</code>. You can optionally include a * trailing dot. If you omit the trailing dot, Amazon Route 53 assumes that the domain name that you specify is * fully qualified. This means that Route 53 treats <code>www.example.com</code> (without a trailing dot) and * <code>www.example.com.</code> (with a trailing dot) as identical. * </p> * <p> * For information about how to specify characters other than <code>a-z</code>, <code>0-9</code>, and <code>-</code> * (hyphen) and how to specify internationalized domain names, see <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DomainNameFormat.html">DNS Domain Name Format</a> * in the <i>Amazon Route 53 Developer Guide</i>. * </p> * <p> * You can use the asterisk (*) wildcard to replace the leftmost label in a domain name, for example, * <code>*.example.com</code>. Note the following: * </p> * <ul> * <li> * <p> * The * must replace the entire label. For example, you can't specify <code>*prod.example.com</code> or * <code>prod*.example.com</code>. * </p> * </li> * <li> * <p> * The * can't replace any of the middle labels, for example, marketing.*.example.com. * </p> * </li> * <li> * <p> * If you include * in any position other than the leftmost label in a domain name, DNS treats it as an * character * (ASCII 42), not as a wildcard. * </p> * <important> * <p> * You can't use the * wildcard for resource records sets that have a type of NS. * </p> * </important></li> * </ul> * <p> * You can use the * wildcard as the leftmost label in a domain name, for example, <code>*.example.com</code>. You * can't use an * for one of the middle labels, for example, <code>marketing.*.example.com</code>. In addition, the * * must replace the entire label; for example, you can't specify <code>prod*.example.com</code>. * </p> * * @return For <code>ChangeResourceRecordSets</code> requests, the name of the record that you want to create, * update, or delete. For <code>ListResourceRecordSets</code> responses, the name of a record in the * specified hosted zone.</p> * <p> * <b>ChangeResourceRecordSets Only</b> * </p> * <p> * Enter a fully qualified domain name, for example, <code>www.example.com</code>. You can optionally * include a trailing dot. If you omit the trailing dot, Amazon Route 53 assumes that the domain name that * you specify is fully qualified. This means that Route 53 treats <code>www.example.com</code> (without a * trailing dot) and <code>www.example.com.</code> (with a trailing dot) as identical. * </p> * <p> * For information about how to specify characters other than <code>a-z</code>, <code>0-9</code>, and * <code>-</code> (hyphen) and how to specify internationalized domain names, see <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DomainNameFormat.html">DNS Domain Name * Format</a> in the <i>Amazon Route 53 Developer Guide</i>. * </p> * <p> * You can use the asterisk (*) wildcard to replace the leftmost label in a domain name, for example, * <code>*.example.com</code>. Note the following: * </p> * <ul> * <li> * <p> * The * must replace the entire label. For example, you can't specify <code>*prod.example.com</code> or * <code>prod*.example.com</code>. * </p> * </li> * <li> * <p> * The * can't replace any of the middle labels, for example, marketing.*.example.com. * </p> * </li> * <li> * <p> * If you include * in any position other than the leftmost label in a domain name, DNS treats it as an * * character (ASCII 42), not as a wildcard. * </p> * <important> * <p> * You can't use the * wildcard for resource records sets that have a type of NS. * </p> * </important></li> * </ul> * <p> * You can use the * wildcard as the leftmost label in a domain name, for example, * <code>*.example.com</code>. You can't use an * for one of the middle labels, for example, * <code>marketing.*.example.com</code>. In addition, the * must replace the entire label; for example, you * can't specify <code>prod*.example.com</code>. */ public String getName() { return this.name; } /** * <p> * For <code>ChangeResourceRecordSets</code> requests, the name of the record that you want to create, update, or * delete. For <code>ListResourceRecordSets</code> responses, the name of a record in the specified hosted zone. * </p> * <p> * <b>ChangeResourceRecordSets Only</b> * </p> * <p> * Enter a fully qualified domain name, for example, <code>www.example.com</code>. You can optionally include a * trailing dot. If you omit the trailing dot, Amazon Route 53 assumes that the domain name that you specify is * fully qualified. This means that Route 53 treats <code>www.example.com</code> (without a trailing dot) and * <code>www.example.com.</code> (with a trailing dot) as identical. * </p> * <p> * For information about how to specify characters other than <code>a-z</code>, <code>0-9</code>, and <code>-</code> * (hyphen) and how to specify internationalized domain names, see <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DomainNameFormat.html">DNS Domain Name Format</a> * in the <i>Amazon Route 53 Developer Guide</i>. * </p> * <p> * You can use the asterisk (*) wildcard to replace the leftmost label in a domain name, for example, * <code>*.example.com</code>. Note the following: * </p> * <ul> * <li> * <p> * The * must replace the entire label. For example, you can't specify <code>*prod.example.com</code> or * <code>prod*.example.com</code>. * </p> * </li> * <li> * <p> * The * can't replace any of the middle labels, for example, marketing.*.example.com. * </p> * </li> * <li> * <p> * If you include * in any position other than the leftmost label in a domain name, DNS treats it as an * character * (ASCII 42), not as a wildcard. * </p> * <important> * <p> * You can't use the * wildcard for resource records sets that have a type of NS. * </p> * </important></li> * </ul> * <p> * You can use the * wildcard as the leftmost label in a domain name, for example, <code>*.example.com</code>. You * can't use an * for one of the middle labels, for example, <code>marketing.*.example.com</code>. In addition, the * * must replace the entire label; for example, you can't specify <code>prod*.example.com</code>. * </p> * * @param name * For <code>ChangeResourceRecordSets</code> requests, the name of the record that you want to create, * update, or delete. For <code>ListResourceRecordSets</code> responses, the name of a record in the * specified hosted zone.</p> * <p> * <b>ChangeResourceRecordSets Only</b> * </p> * <p> * Enter a fully qualified domain name, for example, <code>www.example.com</code>. You can optionally include * a trailing dot. If you omit the trailing dot, Amazon Route 53 assumes that the domain name that you * specify is fully qualified. This means that Route 53 treats <code>www.example.com</code> (without a * trailing dot) and <code>www.example.com.</code> (with a trailing dot) as identical. * </p> * <p> * For information about how to specify characters other than <code>a-z</code>, <code>0-9</code>, and * <code>-</code> (hyphen) and how to specify internationalized domain names, see <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DomainNameFormat.html">DNS Domain Name * Format</a> in the <i>Amazon Route 53 Developer Guide</i>. * </p> * <p> * You can use the asterisk (*) wildcard to replace the leftmost label in a domain name, for example, * <code>*.example.com</code>. Note the following: * </p> * <ul> * <li> * <p> * The * must replace the entire label. For example, you can't specify <code>*prod.example.com</code> or * <code>prod*.example.com</code>. * </p> * </li> * <li> * <p> * The * can't replace any of the middle labels, for example, marketing.*.example.com. * </p> * </li> * <li> * <p> * If you include * in any position other than the leftmost label in a domain name, DNS treats it as an * * character (ASCII 42), not as a wildcard. * </p> * <important> * <p> * You can't use the * wildcard for resource records sets that have a type of NS. * </p> * </important></li> * </ul> * <p> * You can use the * wildcard as the leftmost label in a domain name, for example, <code>*.example.com</code> * . You can't use an * for one of the middle labels, for example, <code>marketing.*.example.com</code>. In * addition, the * must replace the entire label; for example, you can't specify * <code>prod*.example.com</code>. * @return Returns a reference to this object so that method calls can be chained together. */ public ResourceRecordSet withName(String name) { setName(name); return this; } /** * <p> * The DNS record type. For information about different record types and how data is encoded for them, see <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/ResourceRecordTypes.html">Supported DNS Resource * Record Types</a> in the <i>Amazon Route 53 Developer Guide</i>. * </p> * <p> * Valid values for basic resource record sets: <code>A</code> | <code>AAAA</code> | <code>CAA</code> | * <code>CNAME</code> | <code>DS</code> |<code>MX</code> | <code>NAPTR</code> | <code>NS</code> | <code>PTR</code> | * <code>SOA</code> | <code>SPF</code> | <code>SRV</code> | <code>TXT</code> * </p> * <p> * Values for weighted, latency, geolocation, and failover resource record sets: <code>A</code> | <code>AAAA</code> * | <code>CAA</code> | <code>CNAME</code> | <code>MX</code> | <code>NAPTR</code> | <code>PTR</code> | * <code>SPF</code> | <code>SRV</code> | <code>TXT</code>. When creating a group of weighted, latency, geolocation, * or failover resource record sets, specify the same value for all of the resource record sets in the group. * </p> * <p> * Valid values for multivalue answer resource record sets: <code>A</code> | <code>AAAA</code> | <code>MX</code> | * <code>NAPTR</code> | <code>PTR</code> | <code>SPF</code> | <code>SRV</code> | <code>TXT</code> * </p> * <note> * <p> * SPF records were formerly used to verify the identity of the sender of email messages. However, we no longer * recommend that you create resource record sets for which the value of <code>Type</code> is <code>SPF</code>. RFC * 7208, <i>Sender Policy Framework (SPF) for Authorizing Use of Domains in Email, Version 1</i>, has been updated * to say, * "...[I]ts existence and mechanism defined in [RFC4408] have led to some interoperability issues. Accordingly, its use is no longer appropriate for SPF version 1; implementations are not to use it." * In RFC 7208, see section 14.1, <a href="http://tools.ietf.org/html/rfc7208#section-14.1">The SPF DNS Record * Type</a>. * </p> * </note> * <p> * Values for alias resource record sets: * </p> * <ul> * <li> * <p> * <b>Amazon API Gateway custom regional APIs and edge-optimized APIs:</b> <code>A</code> * </p> * </li> * <li> * <p> * <b>CloudFront distributions:</b> <code>A</code> * </p> * <p> * If IPv6 is enabled for the distribution, create two resource record sets to route traffic to your distribution, * one with a value of <code>A</code> and one with a value of <code>AAAA</code>. * </p> * </li> * <li> * <p> * <b>Amazon API Gateway environment that has a regionalized subdomain</b>: <code>A</code> * </p> * </li> * <li> * <p> * <b>ELB load balancers:</b> <code>A</code> | <code>AAAA</code> * </p> * </li> * <li> * <p> * <b>Amazon S3 buckets:</b> <code>A</code> * </p> * </li> * <li> * <p> * <b>Amazon Virtual Private Cloud interface VPC endpoints</b> <code>A</code> * </p> * </li> * <li> * <p> * <b>Another resource record set in this hosted zone:</b> Specify the type of the resource record set that you're * creating the alias for. All values are supported except <code>NS</code> and <code>SOA</code>. * </p> * <note> * <p> * If you're creating an alias record that has the same name as the hosted zone (known as the zone apex), you can't * route traffic to a record for which the value of <code>Type</code> is <code>CNAME</code>. This is because the * alias record must have the same type as the record you're routing traffic to, and creating a CNAME record for the * zone apex isn't supported even for an alias record. * </p> * </note></li> * </ul> * * @param type * The DNS record type. For information about different record types and how data is encoded for them, see <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/ResourceRecordTypes.html">Supported DNS * Resource Record Types</a> in the <i>Amazon Route 53 Developer Guide</i>.</p> * <p> * Valid values for basic resource record sets: <code>A</code> | <code>AAAA</code> | <code>CAA</code> | * <code>CNAME</code> | <code>DS</code> |<code>MX</code> | <code>NAPTR</code> | <code>NS</code> | * <code>PTR</code> | <code>SOA</code> | <code>SPF</code> | <code>SRV</code> | <code>TXT</code> * </p> * <p> * Values for weighted, latency, geolocation, and failover resource record sets: <code>A</code> | * <code>AAAA</code> | <code>CAA</code> | <code>CNAME</code> | <code>MX</code> | <code>NAPTR</code> | * <code>PTR</code> | <code>SPF</code> | <code>SRV</code> | <code>TXT</code>. When creating a group of * weighted, latency, geolocation, or failover resource record sets, specify the same value for all of the * resource record sets in the group. * </p> * <p> * Valid values for multivalue answer resource record sets: <code>A</code> | <code>AAAA</code> | * <code>MX</code> | <code>NAPTR</code> | <code>PTR</code> | <code>SPF</code> | <code>SRV</code> | * <code>TXT</code> * </p> * <note> * <p> * SPF records were formerly used to verify the identity of the sender of email messages. However, we no * longer recommend that you create resource record sets for which the value of <code>Type</code> is * <code>SPF</code>. RFC 7208, <i>Sender Policy Framework (SPF) for Authorizing Use of Domains in Email, * Version 1</i>, has been updated to say, * "...[I]ts existence and mechanism defined in [RFC4408] have led to some interoperability issues. Accordingly, its use is no longer appropriate for SPF version 1; implementations are not to use it." * In RFC 7208, see section 14.1, <a href="http://tools.ietf.org/html/rfc7208#section-14.1">The SPF DNS * Record Type</a>. * </p> * </note> * <p> * Values for alias resource record sets: * </p> * <ul> * <li> * <p> * <b>Amazon API Gateway custom regional APIs and edge-optimized APIs:</b> <code>A</code> * </p> * </li> * <li> * <p> * <b>CloudFront distributions:</b> <code>A</code> * </p> * <p> * If IPv6 is enabled for the distribution, create two resource record sets to route traffic to your * distribution, one with a value of <code>A</code> and one with a value of <code>AAAA</code>. * </p> * </li> * <li> * <p> * <b>Amazon API Gateway environment that has a regionalized subdomain</b>: <code>A</code> * </p> * </li> * <li> * <p> * <b>ELB load balancers:</b> <code>A</code> | <code>AAAA</code> * </p> * </li> * <li> * <p> * <b>Amazon S3 buckets:</b> <code>A</code> * </p> * </li> * <li> * <p> * <b>Amazon Virtual Private Cloud interface VPC endpoints</b> <code>A</code> * </p> * </li> * <li> * <p> * <b>Another resource record set in this hosted zone:</b> Specify the type of the resource record set that * you're creating the alias for. All values are supported except <code>NS</code> and <code>SOA</code>. * </p> * <note> * <p> * If you're creating an alias record that has the same name as the hosted zone (known as the zone apex), you * can't route traffic to a record for which the value of <code>Type</code> is <code>CNAME</code>. This is * because the alias record must have the same type as the record you're routing traffic to, and creating a * CNAME record for the zone apex isn't supported even for an alias record. * </p> * </note></li> * @see RRType */ public void setType(String type) { this.type = type; } /** * <p> * The DNS record type. For information about different record types and how data is encoded for them, see <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/ResourceRecordTypes.html">Supported DNS Resource * Record Types</a> in the <i>Amazon Route 53 Developer Guide</i>. * </p> * <p> * Valid values for basic resource record sets: <code>A</code> | <code>AAAA</code> | <code>CAA</code> | * <code>CNAME</code> | <code>DS</code> |<code>MX</code> | <code>NAPTR</code> | <code>NS</code> | <code>PTR</code> | * <code>SOA</code> | <code>SPF</code> | <code>SRV</code> | <code>TXT</code> * </p> * <p> * Values for weighted, latency, geolocation, and failover resource record sets: <code>A</code> | <code>AAAA</code> * | <code>CAA</code> | <code>CNAME</code> | <code>MX</code> | <code>NAPTR</code> | <code>PTR</code> | * <code>SPF</code> | <code>SRV</code> | <code>TXT</code>. When creating a group of weighted, latency, geolocation, * or failover resource record sets, specify the same value for all of the resource record sets in the group. * </p> * <p> * Valid values for multivalue answer resource record sets: <code>A</code> | <code>AAAA</code> | <code>MX</code> | * <code>NAPTR</code> | <code>PTR</code> | <code>SPF</code> | <code>SRV</code> | <code>TXT</code> * </p> * <note> * <p> * SPF records were formerly used to verify the identity of the sender of email messages. However, we no longer * recommend that you create resource record sets for which the value of <code>Type</code> is <code>SPF</code>. RFC * 7208, <i>Sender Policy Framework (SPF) for Authorizing Use of Domains in Email, Version 1</i>, has been updated * to say, * "...[I]ts existence and mechanism defined in [RFC4408] have led to some interoperability issues. Accordingly, its use is no longer appropriate for SPF version 1; implementations are not to use it." * In RFC 7208, see section 14.1, <a href="http://tools.ietf.org/html/rfc7208#section-14.1">The SPF DNS Record * Type</a>. * </p> * </note> * <p> * Values for alias resource record sets: * </p> * <ul> * <li> * <p> * <b>Amazon API Gateway custom regional APIs and edge-optimized APIs:</b> <code>A</code> * </p> * </li> * <li> * <p> * <b>CloudFront distributions:</b> <code>A</code> * </p> * <p> * If IPv6 is enabled for the distribution, create two resource record sets to route traffic to your distribution, * one with a value of <code>A</code> and one with a value of <code>AAAA</code>. * </p> * </li> * <li> * <p> * <b>Amazon API Gateway environment that has a regionalized subdomain</b>: <code>A</code> * </p> * </li> * <li> * <p> * <b>ELB load balancers:</b> <code>A</code> | <code>AAAA</code> * </p> * </li> * <li> * <p> * <b>Amazon S3 buckets:</b> <code>A</code> * </p> * </li> * <li> * <p> * <b>Amazon Virtual Private Cloud interface VPC endpoints</b> <code>A</code> * </p> * </li> * <li> * <p> * <b>Another resource record set in this hosted zone:</b> Specify the type of the resource record set that you're * creating the alias for. All values are supported except <code>NS</code> and <code>SOA</code>. * </p> * <note> * <p> * If you're creating an alias record that has the same name as the hosted zone (known as the zone apex), you can't * route traffic to a record for which the value of <code>Type</code> is <code>CNAME</code>. This is because the * alias record must have the same type as the record you're routing traffic to, and creating a CNAME record for the * zone apex isn't supported even for an alias record. * </p> * </note></li> * </ul> * * @return The DNS record type. For information about different record types and how data is encoded for them, see * <a href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/ResourceRecordTypes.html">Supported * DNS Resource Record Types</a> in the <i>Amazon Route 53 Developer Guide</i>.</p> * <p> * Valid values for basic resource record sets: <code>A</code> | <code>AAAA</code> | <code>CAA</code> | * <code>CNAME</code> | <code>DS</code> |<code>MX</code> | <code>NAPTR</code> | <code>NS</code> | * <code>PTR</code> | <code>SOA</code> | <code>SPF</code> | <code>SRV</code> | <code>TXT</code> * </p> * <p> * Values for weighted, latency, geolocation, and failover resource record sets: <code>A</code> | * <code>AAAA</code> | <code>CAA</code> | <code>CNAME</code> | <code>MX</code> | <code>NAPTR</code> | * <code>PTR</code> | <code>SPF</code> | <code>SRV</code> | <code>TXT</code>. When creating a group of * weighted, latency, geolocation, or failover resource record sets, specify the same value for all of the * resource record sets in the group. * </p> * <p> * Valid values for multivalue answer resource record sets: <code>A</code> | <code>AAAA</code> | * <code>MX</code> | <code>NAPTR</code> | <code>PTR</code> | <code>SPF</code> | <code>SRV</code> | * <code>TXT</code> * </p> * <note> * <p> * SPF records were formerly used to verify the identity of the sender of email messages. However, we no * longer recommend that you create resource record sets for which the value of <code>Type</code> is * <code>SPF</code>. RFC 7208, <i>Sender Policy Framework (SPF) for Authorizing Use of Domains in Email, * Version 1</i>, has been updated to say, * "...[I]ts existence and mechanism defined in [RFC4408] have led to some interoperability issues. Accordingly, its use is no longer appropriate for SPF version 1; implementations are not to use it." * In RFC 7208, see section 14.1, <a href="http://tools.ietf.org/html/rfc7208#section-14.1">The SPF DNS * Record Type</a>. * </p> * </note> * <p> * Values for alias resource record sets: * </p> * <ul> * <li> * <p> * <b>Amazon API Gateway custom regional APIs and edge-optimized APIs:</b> <code>A</code> * </p> * </li> * <li> * <p> * <b>CloudFront distributions:</b> <code>A</code> * </p> * <p> * If IPv6 is enabled for the distribution, create two resource record sets to route traffic to your * distribution, one with a value of <code>A</code> and one with a value of <code>AAAA</code>. * </p> * </li> * <li> * <p> * <b>Amazon API Gateway environment that has a regionalized subdomain</b>: <code>A</code> * </p> * </li> * <li> * <p> * <b>ELB load balancers:</b> <code>A</code> | <code>AAAA</code> * </p> * </li> * <li> * <p> * <b>Amazon S3 buckets:</b> <code>A</code> * </p> * </li> * <li> * <p> * <b>Amazon Virtual Private Cloud interface VPC endpoints</b> <code>A</code> * </p> * </li> * <li> * <p> * <b>Another resource record set in this hosted zone:</b> Specify the type of the resource record set that * you're creating the alias for. All values are supported except <code>NS</code> and <code>SOA</code>. * </p> * <note> * <p> * If you're creating an alias record that has the same name as the hosted zone (known as the zone apex), * you can't route traffic to a record for which the value of <code>Type</code> is <code>CNAME</code>. This * is because the alias record must have the same type as the record you're routing traffic to, and creating * a CNAME record for the zone apex isn't supported even for an alias record. * </p> * </note></li> * @see RRType */ public String getType() { return this.type; } /** * <p> * The DNS record type. For information about different record types and how data is encoded for them, see <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/ResourceRecordTypes.html">Supported DNS Resource * Record Types</a> in the <i>Amazon Route 53 Developer Guide</i>. * </p> * <p> * Valid values for basic resource record sets: <code>A</code> | <code>AAAA</code> | <code>CAA</code> | * <code>CNAME</code> | <code>DS</code> |<code>MX</code> | <code>NAPTR</code> | <code>NS</code> | <code>PTR</code> | * <code>SOA</code> | <code>SPF</code> | <code>SRV</code> | <code>TXT</code> * </p> * <p> * Values for weighted, latency, geolocation, and failover resource record sets: <code>A</code> | <code>AAAA</code> * | <code>CAA</code> | <code>CNAME</code> | <code>MX</code> | <code>NAPTR</code> | <code>PTR</code> | * <code>SPF</code> | <code>SRV</code> | <code>TXT</code>. When creating a group of weighted, latency, geolocation, * or failover resource record sets, specify the same value for all of the resource record sets in the group. * </p> * <p> * Valid values for multivalue answer resource record sets: <code>A</code> | <code>AAAA</code> | <code>MX</code> | * <code>NAPTR</code> | <code>PTR</code> | <code>SPF</code> | <code>SRV</code> | <code>TXT</code> * </p> * <note> * <p> * SPF records were formerly used to verify the identity of the sender of email messages. However, we no longer * recommend that you create resource record sets for which the value of <code>Type</code> is <code>SPF</code>. RFC * 7208, <i>Sender Policy Framework (SPF) for Authorizing Use of Domains in Email, Version 1</i>, has been updated * to say, * "...[I]ts existence and mechanism defined in [RFC4408] have led to some interoperability issues. Accordingly, its use is no longer appropriate for SPF version 1; implementations are not to use it." * In RFC 7208, see section 14.1, <a href="http://tools.ietf.org/html/rfc7208#section-14.1">The SPF DNS Record * Type</a>. * </p> * </note> * <p> * Values for alias resource record sets: * </p> * <ul> * <li> * <p> * <b>Amazon API Gateway custom regional APIs and edge-optimized APIs:</b> <code>A</code> * </p> * </li> * <li> * <p> * <b>CloudFront distributions:</b> <code>A</code> * </p> * <p> * If IPv6 is enabled for the distribution, create two resource record sets to route traffic to your distribution, * one with a value of <code>A</code> and one with a value of <code>AAAA</code>. * </p> * </li> * <li> * <p> * <b>Amazon API Gateway environment that has a regionalized subdomain</b>: <code>A</code> * </p> * </li> * <li> * <p> * <b>ELB load balancers:</b> <code>A</code> | <code>AAAA</code> * </p> * </li> * <li> * <p> * <b>Amazon S3 buckets:</b> <code>A</code> * </p> * </li> * <li> * <p> * <b>Amazon Virtual Private Cloud interface VPC endpoints</b> <code>A</code> * </p> * </li> * <li> * <p> * <b>Another resource record set in this hosted zone:</b> Specify the type of the resource record set that you're * creating the alias for. All values are supported except <code>NS</code> and <code>SOA</code>. * </p> * <note> * <p> * If you're creating an alias record that has the same name as the hosted zone (known as the zone apex), you can't * route traffic to a record for which the value of <code>Type</code> is <code>CNAME</code>. This is because the * alias record must have the same type as the record you're routing traffic to, and creating a CNAME record for the * zone apex isn't supported even for an alias record. * </p> * </note></li> * </ul> * * @param type * The DNS record type. For information about different record types and how data is encoded for them, see <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/ResourceRecordTypes.html">Supported DNS * Resource Record Types</a> in the <i>Amazon Route 53 Developer Guide</i>.</p> * <p> * Valid values for basic resource record sets: <code>A</code> | <code>AAAA</code> | <code>CAA</code> | * <code>CNAME</code> | <code>DS</code> |<code>MX</code> | <code>NAPTR</code> | <code>NS</code> | * <code>PTR</code> | <code>SOA</code> | <code>SPF</code> | <code>SRV</code> | <code>TXT</code> * </p> * <p> * Values for weighted, latency, geolocation, and failover resource record sets: <code>A</code> | * <code>AAAA</code> | <code>CAA</code> | <code>CNAME</code> | <code>MX</code> | <code>NAPTR</code> | * <code>PTR</code> | <code>SPF</code> | <code>SRV</code> | <code>TXT</code>. When creating a group of * weighted, latency, geolocation, or failover resource record sets, specify the same value for all of the * resource record sets in the group. * </p> * <p> * Valid values for multivalue answer resource record sets: <code>A</code> | <code>AAAA</code> | * <code>MX</code> | <code>NAPTR</code> | <code>PTR</code> | <code>SPF</code> | <code>SRV</code> | * <code>TXT</code> * </p> * <note> * <p> * SPF records were formerly used to verify the identity of the sender of email messages. However, we no * longer recommend that you create resource record sets for which the value of <code>Type</code> is * <code>SPF</code>. RFC 7208, <i>Sender Policy Framework (SPF) for Authorizing Use of Domains in Email, * Version 1</i>, has been updated to say, * "...[I]ts existence and mechanism defined in [RFC4408] have led to some interoperability issues. Accordingly, its use is no longer appropriate for SPF version 1; implementations are not to use it." * In RFC 7208, see section 14.1, <a href="http://tools.ietf.org/html/rfc7208#section-14.1">The SPF DNS * Record Type</a>. * </p> * </note> * <p> * Values for alias resource record sets: * </p> * <ul> * <li> * <p> * <b>Amazon API Gateway custom regional APIs and edge-optimized APIs:</b> <code>A</code> * </p> * </li> * <li> * <p> * <b>CloudFront distributions:</b> <code>A</code> * </p> * <p> * If IPv6 is enabled for the distribution, create two resource record sets to route traffic to your * distribution, one with a value of <code>A</code> and one with a value of <code>AAAA</code>. * </p> * </li> * <li> * <p> * <b>Amazon API Gateway environment that has a regionalized subdomain</b>: <code>A</code> * </p> * </li> * <li> * <p> * <b>ELB load balancers:</b> <code>A</code> | <code>AAAA</code> * </p> * </li> * <li> * <p> * <b>Amazon S3 buckets:</b> <code>A</code> * </p> * </li> * <li> * <p> * <b>Amazon Virtual Private Cloud interface VPC endpoints</b> <code>A</code> * </p> * </li> * <li> * <p> * <b>Another resource record set in this hosted zone:</b> Specify the type of the resource record set that * you're creating the alias for. All values are supported except <code>NS</code> and <code>SOA</code>. * </p> * <note> * <p> * If you're creating an alias record that has the same name as the hosted zone (known as the zone apex), you * can't route traffic to a record for which the value of <code>Type</code> is <code>CNAME</code>. This is * because the alias record must have the same type as the record you're routing traffic to, and creating a * CNAME record for the zone apex isn't supported even for an alias record. * </p> * </note></li> * @return Returns a reference to this object so that method calls can be chained together. * @see RRType */ public ResourceRecordSet withType(String type) { setType(type); return this; } /** * <p> * The DNS record type. For information about different record types and how data is encoded for them, see <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/ResourceRecordTypes.html">Supported DNS Resource * Record Types</a> in the <i>Amazon Route 53 Developer Guide</i>. * </p> * <p> * Valid values for basic resource record sets: <code>A</code> | <code>AAAA</code> | <code>CAA</code> | * <code>CNAME</code> | <code>DS</code> |<code>MX</code> | <code>NAPTR</code> | <code>NS</code> | <code>PTR</code> | * <code>SOA</code> | <code>SPF</code> | <code>SRV</code> | <code>TXT</code> * </p> * <p> * Values for weighted, latency, geolocation, and failover resource record sets: <code>A</code> | <code>AAAA</code> * | <code>CAA</code> | <code>CNAME</code> | <code>MX</code> | <code>NAPTR</code> | <code>PTR</code> | * <code>SPF</code> | <code>SRV</code> | <code>TXT</code>. When creating a group of weighted, latency, geolocation, * or failover resource record sets, specify the same value for all of the resource record sets in the group. * </p> * <p> * Valid values for multivalue answer resource record sets: <code>A</code> | <code>AAAA</code> | <code>MX</code> | * <code>NAPTR</code> | <code>PTR</code> | <code>SPF</code> | <code>SRV</code> | <code>TXT</code> * </p> * <note> * <p> * SPF records were formerly used to verify the identity of the sender of email messages. However, we no longer * recommend that you create resource record sets for which the value of <code>Type</code> is <code>SPF</code>. RFC * 7208, <i>Sender Policy Framework (SPF) for Authorizing Use of Domains in Email, Version 1</i>, has been updated * to say, * "...[I]ts existence and mechanism defined in [RFC4408] have led to some interoperability issues. Accordingly, its use is no longer appropriate for SPF version 1; implementations are not to use it." * In RFC 7208, see section 14.1, <a href="http://tools.ietf.org/html/rfc7208#section-14.1">The SPF DNS Record * Type</a>. * </p> * </note> * <p> * Values for alias resource record sets: * </p> * <ul> * <li> * <p> * <b>Amazon API Gateway custom regional APIs and edge-optimized APIs:</b> <code>A</code> * </p> * </li> * <li> * <p> * <b>CloudFront distributions:</b> <code>A</code> * </p> * <p> * If IPv6 is enabled for the distribution, create two resource record sets to route traffic to your distribution, * one with a value of <code>A</code> and one with a value of <code>AAAA</code>. * </p> * </li> * <li> * <p> * <b>Amazon API Gateway environment that has a regionalized subdomain</b>: <code>A</code> * </p> * </li> * <li> * <p> * <b>ELB load balancers:</b> <code>A</code> | <code>AAAA</code> * </p> * </li> * <li> * <p> * <b>Amazon S3 buckets:</b> <code>A</code> * </p> * </li> * <li> * <p> * <b>Amazon Virtual Private Cloud interface VPC endpoints</b> <code>A</code> * </p> * </li> * <li> * <p> * <b>Another resource record set in this hosted zone:</b> Specify the type of the resource record set that you're * creating the alias for. All values are supported except <code>NS</code> and <code>SOA</code>. * </p> * <note> * <p> * If you're creating an alias record that has the same name as the hosted zone (known as the zone apex), you can't * route traffic to a record for which the value of <code>Type</code> is <code>CNAME</code>. This is because the * alias record must have the same type as the record you're routing traffic to, and creating a CNAME record for the * zone apex isn't supported even for an alias record. * </p> * </note></li> * </ul> * * @param type * The DNS record type. For information about different record types and how data is encoded for them, see <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/ResourceRecordTypes.html">Supported DNS * Resource Record Types</a> in the <i>Amazon Route 53 Developer Guide</i>.</p> * <p> * Valid values for basic resource record sets: <code>A</code> | <code>AAAA</code> | <code>CAA</code> | * <code>CNAME</code> | <code>DS</code> |<code>MX</code> | <code>NAPTR</code> | <code>NS</code> | * <code>PTR</code> | <code>SOA</code> | <code>SPF</code> | <code>SRV</code> | <code>TXT</code> * </p> * <p> * Values for weighted, latency, geolocation, and failover resource record sets: <code>A</code> | * <code>AAAA</code> | <code>CAA</code> | <code>CNAME</code> | <code>MX</code> | <code>NAPTR</code> | * <code>PTR</code> | <code>SPF</code> | <code>SRV</code> | <code>TXT</code>. When creating a group of * weighted, latency, geolocation, or failover resource record sets, specify the same value for all of the * resource record sets in the group. * </p> * <p> * Valid values for multivalue answer resource record sets: <code>A</code> | <code>AAAA</code> | * <code>MX</code> | <code>NAPTR</code> | <code>PTR</code> | <code>SPF</code> | <code>SRV</code> | * <code>TXT</code> * </p> * <note> * <p> * SPF records were formerly used to verify the identity of the sender of email messages. However, we no * longer recommend that you create resource record sets for which the value of <code>Type</code> is * <code>SPF</code>. RFC 7208, <i>Sender Policy Framework (SPF) for Authorizing Use of Domains in Email, * Version 1</i>, has been updated to say, * "...[I]ts existence and mechanism defined in [RFC4408] have led to some interoperability issues. Accordingly, its use is no longer appropriate for SPF version 1; implementations are not to use it." * In RFC 7208, see section 14.1, <a href="http://tools.ietf.org/html/rfc7208#section-14.1">The SPF DNS * Record Type</a>. * </p> * </note> * <p> * Values for alias resource record sets: * </p> * <ul> * <li> * <p> * <b>Amazon API Gateway custom regional APIs and edge-optimized APIs:</b> <code>A</code> * </p> * </li> * <li> * <p> * <b>CloudFront distributions:</b> <code>A</code> * </p> * <p> * If IPv6 is enabled for the distribution, create two resource record sets to route traffic to your * distribution, one with a value of <code>A</code> and one with a value of <code>AAAA</code>. * </p> * </li> * <li> * <p> * <b>Amazon API Gateway environment that has a regionalized subdomain</b>: <code>A</code> * </p> * </li> * <li> * <p> * <b>ELB load balancers:</b> <code>A</code> | <code>AAAA</code> * </p> * </li> * <li> * <p> * <b>Amazon S3 buckets:</b> <code>A</code> * </p> * </li> * <li> * <p> * <b>Amazon Virtual Private Cloud interface VPC endpoints</b> <code>A</code> * </p> * </li> * <li> * <p> * <b>Another resource record set in this hosted zone:</b> Specify the type of the resource record set that * you're creating the alias for. All values are supported except <code>NS</code> and <code>SOA</code>. * </p> * <note> * <p> * If you're creating an alias record that has the same name as the hosted zone (known as the zone apex), you * can't route traffic to a record for which the value of <code>Type</code> is <code>CNAME</code>. This is * because the alias record must have the same type as the record you're routing traffic to, and creating a * CNAME record for the zone apex isn't supported even for an alias record. * </p> * </note></li> * @see RRType */ public void setType(RRType type) { withType(type); } /** * <p> * The DNS record type. For information about different record types and how data is encoded for them, see <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/ResourceRecordTypes.html">Supported DNS Resource * Record Types</a> in the <i>Amazon Route 53 Developer Guide</i>. * </p> * <p> * Valid values for basic resource record sets: <code>A</code> | <code>AAAA</code> | <code>CAA</code> | * <code>CNAME</code> | <code>DS</code> |<code>MX</code> | <code>NAPTR</code> | <code>NS</code> | <code>PTR</code> | * <code>SOA</code> | <code>SPF</code> | <code>SRV</code> | <code>TXT</code> * </p> * <p> * Values for weighted, latency, geolocation, and failover resource record sets: <code>A</code> | <code>AAAA</code> * | <code>CAA</code> | <code>CNAME</code> | <code>MX</code> | <code>NAPTR</code> | <code>PTR</code> | * <code>SPF</code> | <code>SRV</code> | <code>TXT</code>. When creating a group of weighted, latency, geolocation, * or failover resource record sets, specify the same value for all of the resource record sets in the group. * </p> * <p> * Valid values for multivalue answer resource record sets: <code>A</code> | <code>AAAA</code> | <code>MX</code> | * <code>NAPTR</code> | <code>PTR</code> | <code>SPF</code> | <code>SRV</code> | <code>TXT</code> * </p> * <note> * <p> * SPF records were formerly used to verify the identity of the sender of email messages. However, we no longer * recommend that you create resource record sets for which the value of <code>Type</code> is <code>SPF</code>. RFC * 7208, <i>Sender Policy Framework (SPF) for Authorizing Use of Domains in Email, Version 1</i>, has been updated * to say, * "...[I]ts existence and mechanism defined in [RFC4408] have led to some interoperability issues. Accordingly, its use is no longer appropriate for SPF version 1; implementations are not to use it." * In RFC 7208, see section 14.1, <a href="http://tools.ietf.org/html/rfc7208#section-14.1">The SPF DNS Record * Type</a>. * </p> * </note> * <p> * Values for alias resource record sets: * </p> * <ul> * <li> * <p> * <b>Amazon API Gateway custom regional APIs and edge-optimized APIs:</b> <code>A</code> * </p> * </li> * <li> * <p> * <b>CloudFront distributions:</b> <code>A</code> * </p> * <p> * If IPv6 is enabled for the distribution, create two resource record sets to route traffic to your distribution, * one with a value of <code>A</code> and one with a value of <code>AAAA</code>. * </p> * </li> * <li> * <p> * <b>Amazon API Gateway environment that has a regionalized subdomain</b>: <code>A</code> * </p> * </li> * <li> * <p> * <b>ELB load balancers:</b> <code>A</code> | <code>AAAA</code> * </p> * </li> * <li> * <p> * <b>Amazon S3 buckets:</b> <code>A</code> * </p> * </li> * <li> * <p> * <b>Amazon Virtual Private Cloud interface VPC endpoints</b> <code>A</code> * </p> * </li> * <li> * <p> * <b>Another resource record set in this hosted zone:</b> Specify the type of the resource record set that you're * creating the alias for. All values are supported except <code>NS</code> and <code>SOA</code>. * </p> * <note> * <p> * If you're creating an alias record that has the same name as the hosted zone (known as the zone apex), you can't * route traffic to a record for which the value of <code>Type</code> is <code>CNAME</code>. This is because the * alias record must have the same type as the record you're routing traffic to, and creating a CNAME record for the * zone apex isn't supported even for an alias record. * </p> * </note></li> * </ul> * * @param type * The DNS record type. For information about different record types and how data is encoded for them, see <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/ResourceRecordTypes.html">Supported DNS * Resource Record Types</a> in the <i>Amazon Route 53 Developer Guide</i>.</p> * <p> * Valid values for basic resource record sets: <code>A</code> | <code>AAAA</code> | <code>CAA</code> | * <code>CNAME</code> | <code>DS</code> |<code>MX</code> | <code>NAPTR</code> | <code>NS</code> | * <code>PTR</code> | <code>SOA</code> | <code>SPF</code> | <code>SRV</code> | <code>TXT</code> * </p> * <p> * Values for weighted, latency, geolocation, and failover resource record sets: <code>A</code> | * <code>AAAA</code> | <code>CAA</code> | <code>CNAME</code> | <code>MX</code> | <code>NAPTR</code> | * <code>PTR</code> | <code>SPF</code> | <code>SRV</code> | <code>TXT</code>. When creating a group of * weighted, latency, geolocation, or failover resource record sets, specify the same value for all of the * resource record sets in the group. * </p> * <p> * Valid values for multivalue answer resource record sets: <code>A</code> | <code>AAAA</code> | * <code>MX</code> | <code>NAPTR</code> | <code>PTR</code> | <code>SPF</code> | <code>SRV</code> | * <code>TXT</code> * </p> * <note> * <p> * SPF records were formerly used to verify the identity of the sender of email messages. However, we no * longer recommend that you create resource record sets for which the value of <code>Type</code> is * <code>SPF</code>. RFC 7208, <i>Sender Policy Framework (SPF) for Authorizing Use of Domains in Email, * Version 1</i>, has been updated to say, * "...[I]ts existence and mechanism defined in [RFC4408] have led to some interoperability issues. Accordingly, its use is no longer appropriate for SPF version 1; implementations are not to use it." * In RFC 7208, see section 14.1, <a href="http://tools.ietf.org/html/rfc7208#section-14.1">The SPF DNS * Record Type</a>. * </p> * </note> * <p> * Values for alias resource record sets: * </p> * <ul> * <li> * <p> * <b>Amazon API Gateway custom regional APIs and edge-optimized APIs:</b> <code>A</code> * </p> * </li> * <li> * <p> * <b>CloudFront distributions:</b> <code>A</code> * </p> * <p> * If IPv6 is enabled for the distribution, create two resource record sets to route traffic to your * distribution, one with a value of <code>A</code> and one with a value of <code>AAAA</code>. * </p> * </li> * <li> * <p> * <b>Amazon API Gateway environment that has a regionalized subdomain</b>: <code>A</code> * </p> * </li> * <li> * <p> * <b>ELB load balancers:</b> <code>A</code> | <code>AAAA</code> * </p> * </li> * <li> * <p> * <b>Amazon S3 buckets:</b> <code>A</code> * </p> * </li> * <li> * <p> * <b>Amazon Virtual Private Cloud interface VPC endpoints</b> <code>A</code> * </p> * </li> * <li> * <p> * <b>Another resource record set in this hosted zone:</b> Specify the type of the resource record set that * you're creating the alias for. All values are supported except <code>NS</code> and <code>SOA</code>. * </p> * <note> * <p> * If you're creating an alias record that has the same name as the hosted zone (known as the zone apex), you * can't route traffic to a record for which the value of <code>Type</code> is <code>CNAME</code>. This is * because the alias record must have the same type as the record you're routing traffic to, and creating a * CNAME record for the zone apex isn't supported even for an alias record. * </p> * </note></li> * @return Returns a reference to this object so that method calls can be chained together. * @see RRType */ public ResourceRecordSet withType(RRType type) { this.type = type.toString(); return this; } /** * <p> * <i>Resource record sets that have a routing policy other than simple:</i> An identifier that differentiates among * multiple resource record sets that have the same combination of name and type, such as multiple weighted resource * record sets named acme.example.com that have a type of A. In a group of resource record sets that have the same * name and type, the value of <code>SetIdentifier</code> must be unique for each resource record set. * </p> * <p> * For information about routing policies, see <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-policy.html">Choosing a Routing * Policy</a> in the <i>Amazon Route 53 Developer Guide</i>. * </p> * * @param setIdentifier * <i>Resource record sets that have a routing policy other than simple:</i> An identifier that * differentiates among multiple resource record sets that have the same combination of name and type, such * as multiple weighted resource record sets named acme.example.com that have a type of A. In a group of * resource record sets that have the same name and type, the value of <code>SetIdentifier</code> must be * unique for each resource record set. </p> * <p> * For information about routing policies, see <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-policy.html">Choosing a Routing * Policy</a> in the <i>Amazon Route 53 Developer Guide</i>. */ public void setSetIdentifier(String setIdentifier) { this.setIdentifier = setIdentifier; } /** * <p> * <i>Resource record sets that have a routing policy other than simple:</i> An identifier that differentiates among * multiple resource record sets that have the same combination of name and type, such as multiple weighted resource * record sets named acme.example.com that have a type of A. In a group of resource record sets that have the same * name and type, the value of <code>SetIdentifier</code> must be unique for each resource record set. * </p> * <p> * For information about routing policies, see <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-policy.html">Choosing a Routing * Policy</a> in the <i>Amazon Route 53 Developer Guide</i>. * </p> * * @return <i>Resource record sets that have a routing policy other than simple:</i> An identifier that * differentiates among multiple resource record sets that have the same combination of name and type, such * as multiple weighted resource record sets named acme.example.com that have a type of A. In a group of * resource record sets that have the same name and type, the value of <code>SetIdentifier</code> must be * unique for each resource record set. </p> * <p> * For information about routing policies, see <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-policy.html">Choosing a Routing * Policy</a> in the <i>Amazon Route 53 Developer Guide</i>. */ public String getSetIdentifier() { return this.setIdentifier; } /** * <p> * <i>Resource record sets that have a routing policy other than simple:</i> An identifier that differentiates among * multiple resource record sets that have the same combination of name and type, such as multiple weighted resource * record sets named acme.example.com that have a type of A. In a group of resource record sets that have the same * name and type, the value of <code>SetIdentifier</code> must be unique for each resource record set. * </p> * <p> * For information about routing policies, see <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-policy.html">Choosing a Routing * Policy</a> in the <i>Amazon Route 53 Developer Guide</i>. * </p> * * @param setIdentifier * <i>Resource record sets that have a routing policy other than simple:</i> An identifier that * differentiates among multiple resource record sets that have the same combination of name and type, such * as multiple weighted resource record sets named acme.example.com that have a type of A. In a group of * resource record sets that have the same name and type, the value of <code>SetIdentifier</code> must be * unique for each resource record set. </p> * <p> * For information about routing policies, see <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-policy.html">Choosing a Routing * Policy</a> in the <i>Amazon Route 53 Developer Guide</i>. * @return Returns a reference to this object so that method calls can be chained together. */ public ResourceRecordSet withSetIdentifier(String setIdentifier) { setSetIdentifier(setIdentifier); return this; } /** * <p> * <i>Weighted resource record sets only:</i> Among resource record sets that have the same combination of DNS name * and type, a value that determines the proportion of DNS queries that Amazon Route 53 responds to using the * current resource record set. Route 53 calculates the sum of the weights for the resource record sets that have * the same combination of DNS name and type. Route 53 then responds to queries based on the ratio of a resource's * weight to the total. Note the following: * </p> * <ul> * <li> * <p> * You must specify a value for the <code>Weight</code> element for every weighted resource record set. * </p> * </li> * <li> * <p> * You can only specify one <code>ResourceRecord</code> per weighted resource record set. * </p> * </li> * <li> * <p> * You can't create latency, failover, or geolocation resource record sets that have the same values for the * <code>Name</code> and <code>Type</code> elements as weighted resource record sets. * </p> * </li> * <li> * <p> * You can create a maximum of 100 weighted resource record sets that have the same values for the <code>Name</code> * and <code>Type</code> elements. * </p> * </li> * <li> * <p> * For weighted (but not weighted alias) resource record sets, if you set <code>Weight</code> to <code>0</code> for * a resource record set, Route 53 never responds to queries with the applicable value for that resource record set. * However, if you set <code>Weight</code> to <code>0</code> for all resource record sets that have the same * combination of DNS name and type, traffic is routed to all resources with equal probability. * </p> * <p> * The effect of setting <code>Weight</code> to <code>0</code> is different when you associate health checks with * weighted resource record sets. For more information, see <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-configuring-options.html">Options * for Configuring Route 53 Active-Active and Active-Passive Failover</a> in the <i>Amazon Route 53 Developer * Guide</i>. * </p> * </li> * </ul> * * @param weight * <i>Weighted resource record sets only:</i> Among resource record sets that have the same combination of * DNS name and type, a value that determines the proportion of DNS queries that Amazon Route 53 responds to * using the current resource record set. Route 53 calculates the sum of the weights for the resource record * sets that have the same combination of DNS name and type. Route 53 then responds to queries based on the * ratio of a resource's weight to the total. Note the following:</p> * <ul> * <li> * <p> * You must specify a value for the <code>Weight</code> element for every weighted resource record set. * </p> * </li> * <li> * <p> * You can only specify one <code>ResourceRecord</code> per weighted resource record set. * </p> * </li> * <li> * <p> * You can't create latency, failover, or geolocation resource record sets that have the same values for the * <code>Name</code> and <code>Type</code> elements as weighted resource record sets. * </p> * </li> * <li> * <p> * You can create a maximum of 100 weighted resource record sets that have the same values for the * <code>Name</code> and <code>Type</code> elements. * </p> * </li> * <li> * <p> * For weighted (but not weighted alias) resource record sets, if you set <code>Weight</code> to * <code>0</code> for a resource record set, Route 53 never responds to queries with the applicable value for * that resource record set. However, if you set <code>Weight</code> to <code>0</code> for all resource * record sets that have the same combination of DNS name and type, traffic is routed to all resources with * equal probability. * </p> * <p> * The effect of setting <code>Weight</code> to <code>0</code> is different when you associate health checks * with weighted resource record sets. For more information, see <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-configuring-options.html" * >Options for Configuring Route 53 Active-Active and Active-Passive Failover</a> in the <i>Amazon Route 53 * Developer Guide</i>. * </p> * </li> */ public void setWeight(Long weight) { this.weight = weight; } /** * <p> * <i>Weighted resource record sets only:</i> Among resource record sets that have the same combination of DNS name * and type, a value that determines the proportion of DNS queries that Amazon Route 53 responds to using the * current resource record set. Route 53 calculates the sum of the weights for the resource record sets that have * the same combination of DNS name and type. Route 53 then responds to queries based on the ratio of a resource's * weight to the total. Note the following: * </p> * <ul> * <li> * <p> * You must specify a value for the <code>Weight</code> element for every weighted resource record set. * </p> * </li> * <li> * <p> * You can only specify one <code>ResourceRecord</code> per weighted resource record set. * </p> * </li> * <li> * <p> * You can't create latency, failover, or geolocation resource record sets that have the same values for the * <code>Name</code> and <code>Type</code> elements as weighted resource record sets. * </p> * </li> * <li> * <p> * You can create a maximum of 100 weighted resource record sets that have the same values for the <code>Name</code> * and <code>Type</code> elements. * </p> * </li> * <li> * <p> * For weighted (but not weighted alias) resource record sets, if you set <code>Weight</code> to <code>0</code> for * a resource record set, Route 53 never responds to queries with the applicable value for that resource record set. * However, if you set <code>Weight</code> to <code>0</code> for all resource record sets that have the same * combination of DNS name and type, traffic is routed to all resources with equal probability. * </p> * <p> * The effect of setting <code>Weight</code> to <code>0</code> is different when you associate health checks with * weighted resource record sets. For more information, see <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-configuring-options.html">Options * for Configuring Route 53 Active-Active and Active-Passive Failover</a> in the <i>Amazon Route 53 Developer * Guide</i>. * </p> * </li> * </ul> * * @return <i>Weighted resource record sets only:</i> Among resource record sets that have the same combination of * DNS name and type, a value that determines the proportion of DNS queries that Amazon Route 53 responds to * using the current resource record set. Route 53 calculates the sum of the weights for the resource record * sets that have the same combination of DNS name and type. Route 53 then responds to queries based on the * ratio of a resource's weight to the total. Note the following:</p> * <ul> * <li> * <p> * You must specify a value for the <code>Weight</code> element for every weighted resource record set. * </p> * </li> * <li> * <p> * You can only specify one <code>ResourceRecord</code> per weighted resource record set. * </p> * </li> * <li> * <p> * You can't create latency, failover, or geolocation resource record sets that have the same values for the * <code>Name</code> and <code>Type</code> elements as weighted resource record sets. * </p> * </li> * <li> * <p> * You can create a maximum of 100 weighted resource record sets that have the same values for the * <code>Name</code> and <code>Type</code> elements. * </p> * </li> * <li> * <p> * For weighted (but not weighted alias) resource record sets, if you set <code>Weight</code> to * <code>0</code> for a resource record set, Route 53 never responds to queries with the applicable value * for that resource record set. However, if you set <code>Weight</code> to <code>0</code> for all resource * record sets that have the same combination of DNS name and type, traffic is routed to all resources with * equal probability. * </p> * <p> * The effect of setting <code>Weight</code> to <code>0</code> is different when you associate health checks * with weighted resource record sets. For more information, see <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-configuring-options.html" * >Options for Configuring Route 53 Active-Active and Active-Passive Failover</a> in the <i>Amazon Route 53 * Developer Guide</i>. * </p> * </li> */ public Long getWeight() { return this.weight; } /** * <p> * <i>Weighted resource record sets only:</i> Among resource record sets that have the same combination of DNS name * and type, a value that determines the proportion of DNS queries that Amazon Route 53 responds to using the * current resource record set. Route 53 calculates the sum of the weights for the resource record sets that have * the same combination of DNS name and type. Route 53 then responds to queries based on the ratio of a resource's * weight to the total. Note the following: * </p> * <ul> * <li> * <p> * You must specify a value for the <code>Weight</code> element for every weighted resource record set. * </p> * </li> * <li> * <p> * You can only specify one <code>ResourceRecord</code> per weighted resource record set. * </p> * </li> * <li> * <p> * You can't create latency, failover, or geolocation resource record sets that have the same values for the * <code>Name</code> and <code>Type</code> elements as weighted resource record sets. * </p> * </li> * <li> * <p> * You can create a maximum of 100 weighted resource record sets that have the same values for the <code>Name</code> * and <code>Type</code> elements. * </p> * </li> * <li> * <p> * For weighted (but not weighted alias) resource record sets, if you set <code>Weight</code> to <code>0</code> for * a resource record set, Route 53 never responds to queries with the applicable value for that resource record set. * However, if you set <code>Weight</code> to <code>0</code> for all resource record sets that have the same * combination of DNS name and type, traffic is routed to all resources with equal probability. * </p> * <p> * The effect of setting <code>Weight</code> to <code>0</code> is different when you associate health checks with * weighted resource record sets. For more information, see <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-configuring-options.html">Options * for Configuring Route 53 Active-Active and Active-Passive Failover</a> in the <i>Amazon Route 53 Developer * Guide</i>. * </p> * </li> * </ul> * * @param weight * <i>Weighted resource record sets only:</i> Among resource record sets that have the same combination of * DNS name and type, a value that determines the proportion of DNS queries that Amazon Route 53 responds to * using the current resource record set. Route 53 calculates the sum of the weights for the resource record * sets that have the same combination of DNS name and type. Route 53 then responds to queries based on the * ratio of a resource's weight to the total. Note the following:</p> * <ul> * <li> * <p> * You must specify a value for the <code>Weight</code> element for every weighted resource record set. * </p> * </li> * <li> * <p> * You can only specify one <code>ResourceRecord</code> per weighted resource record set. * </p> * </li> * <li> * <p> * You can't create latency, failover, or geolocation resource record sets that have the same values for the * <code>Name</code> and <code>Type</code> elements as weighted resource record sets. * </p> * </li> * <li> * <p> * You can create a maximum of 100 weighted resource record sets that have the same values for the * <code>Name</code> and <code>Type</code> elements. * </p> * </li> * <li> * <p> * For weighted (but not weighted alias) resource record sets, if you set <code>Weight</code> to * <code>0</code> for a resource record set, Route 53 never responds to queries with the applicable value for * that resource record set. However, if you set <code>Weight</code> to <code>0</code> for all resource * record sets that have the same combination of DNS name and type, traffic is routed to all resources with * equal probability. * </p> * <p> * The effect of setting <code>Weight</code> to <code>0</code> is different when you associate health checks * with weighted resource record sets. For more information, see <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-configuring-options.html" * >Options for Configuring Route 53 Active-Active and Active-Passive Failover</a> in the <i>Amazon Route 53 * Developer Guide</i>. * </p> * </li> * @return Returns a reference to this object so that method calls can be chained together. */ public ResourceRecordSet withWeight(Long weight) { setWeight(weight); return this; } /** * <p> * <i>Latency-based resource record sets only:</i> The Amazon EC2 Region where you created the resource that this * resource record set refers to. The resource typically is an Amazon Web Services resource, such as an EC2 instance * or an ELB load balancer, and is referred to by an IP address or a DNS domain name, depending on the record type. * </p> * <note> * <p> * Although creating latency and latency alias resource record sets in a private hosted zone is allowed, it's not * supported. * </p> * </note> * <p> * When Amazon Route 53 receives a DNS query for a domain name and type for which you have created latency resource * record sets, Route 53 selects the latency resource record set that has the lowest latency between the end user * and the associated Amazon EC2 Region. Route 53 then returns the value that is associated with the selected * resource record set. * </p> * <p> * Note the following: * </p> * <ul> * <li> * <p> * You can only specify one <code>ResourceRecord</code> per latency resource record set. * </p> * </li> * <li> * <p> * You can only create one latency resource record set for each Amazon EC2 Region. * </p> * </li> * <li> * <p> * You aren't required to create latency resource record sets for all Amazon EC2 Regions. Route 53 will choose the * region with the best latency from among the regions that you create latency resource record sets for. * </p> * </li> * <li> * <p> * You can't create non-latency resource record sets that have the same values for the <code>Name</code> and * <code>Type</code> elements as latency resource record sets. * </p> * </li> * </ul> * * @param region * <i>Latency-based resource record sets only:</i> The Amazon EC2 Region where you created the resource that * this resource record set refers to. The resource typically is an Amazon Web Services resource, such as an * EC2 instance or an ELB load balancer, and is referred to by an IP address or a DNS domain name, depending * on the record type.</p> <note> * <p> * Although creating latency and latency alias resource record sets in a private hosted zone is allowed, it's * not supported. * </p> * </note> * <p> * When Amazon Route 53 receives a DNS query for a domain name and type for which you have created latency * resource record sets, Route 53 selects the latency resource record set that has the lowest latency between * the end user and the associated Amazon EC2 Region. Route 53 then returns the value that is associated with * the selected resource record set. * </p> * <p> * Note the following: * </p> * <ul> * <li> * <p> * You can only specify one <code>ResourceRecord</code> per latency resource record set. * </p> * </li> * <li> * <p> * You can only create one latency resource record set for each Amazon EC2 Region. * </p> * </li> * <li> * <p> * You aren't required to create latency resource record sets for all Amazon EC2 Regions. Route 53 will * choose the region with the best latency from among the regions that you create latency resource record * sets for. * </p> * </li> * <li> * <p> * You can't create non-latency resource record sets that have the same values for the <code>Name</code> and * <code>Type</code> elements as latency resource record sets. * </p> * </li> * @see ResourceRecordSetRegion */ public void setRegion(String region) { this.region = region; } /** * <p> * <i>Latency-based resource record sets only:</i> The Amazon EC2 Region where you created the resource that this * resource record set refers to. The resource typically is an Amazon Web Services resource, such as an EC2 instance * or an ELB load balancer, and is referred to by an IP address or a DNS domain name, depending on the record type. * </p> * <note> * <p> * Although creating latency and latency alias resource record sets in a private hosted zone is allowed, it's not * supported. * </p> * </note> * <p> * When Amazon Route 53 receives a DNS query for a domain name and type for which you have created latency resource * record sets, Route 53 selects the latency resource record set that has the lowest latency between the end user * and the associated Amazon EC2 Region. Route 53 then returns the value that is associated with the selected * resource record set. * </p> * <p> * Note the following: * </p> * <ul> * <li> * <p> * You can only specify one <code>ResourceRecord</code> per latency resource record set. * </p> * </li> * <li> * <p> * You can only create one latency resource record set for each Amazon EC2 Region. * </p> * </li> * <li> * <p> * You aren't required to create latency resource record sets for all Amazon EC2 Regions. Route 53 will choose the * region with the best latency from among the regions that you create latency resource record sets for. * </p> * </li> * <li> * <p> * You can't create non-latency resource record sets that have the same values for the <code>Name</code> and * <code>Type</code> elements as latency resource record sets. * </p> * </li> * </ul> * * @return <i>Latency-based resource record sets only:</i> The Amazon EC2 Region where you created the resource that * this resource record set refers to. The resource typically is an Amazon Web Services resource, such as an * EC2 instance or an ELB load balancer, and is referred to by an IP address or a DNS domain name, depending * on the record type.</p> <note> * <p> * Although creating latency and latency alias resource record sets in a private hosted zone is allowed, * it's not supported. * </p> * </note> * <p> * When Amazon Route 53 receives a DNS query for a domain name and type for which you have created latency * resource record sets, Route 53 selects the latency resource record set that has the lowest latency * between the end user and the associated Amazon EC2 Region. Route 53 then returns the value that is * associated with the selected resource record set. * </p> * <p> * Note the following: * </p> * <ul> * <li> * <p> * You can only specify one <code>ResourceRecord</code> per latency resource record set. * </p> * </li> * <li> * <p> * You can only create one latency resource record set for each Amazon EC2 Region. * </p> * </li> * <li> * <p> * You aren't required to create latency resource record sets for all Amazon EC2 Regions. Route 53 will * choose the region with the best latency from among the regions that you create latency resource record * sets for. * </p> * </li> * <li> * <p> * You can't create non-latency resource record sets that have the same values for the <code>Name</code> and * <code>Type</code> elements as latency resource record sets. * </p> * </li> * @see ResourceRecordSetRegion */ public String getRegion() { return this.region; } /** * <p> * <i>Latency-based resource record sets only:</i> The Amazon EC2 Region where you created the resource that this * resource record set refers to. The resource typically is an Amazon Web Services resource, such as an EC2 instance * or an ELB load balancer, and is referred to by an IP address or a DNS domain name, depending on the record type. * </p> * <note> * <p> * Although creating latency and latency alias resource record sets in a private hosted zone is allowed, it's not * supported. * </p> * </note> * <p> * When Amazon Route 53 receives a DNS query for a domain name and type for which you have created latency resource * record sets, Route 53 selects the latency resource record set that has the lowest latency between the end user * and the associated Amazon EC2 Region. Route 53 then returns the value that is associated with the selected * resource record set. * </p> * <p> * Note the following: * </p> * <ul> * <li> * <p> * You can only specify one <code>ResourceRecord</code> per latency resource record set. * </p> * </li> * <li> * <p> * You can only create one latency resource record set for each Amazon EC2 Region. * </p> * </li> * <li> * <p> * You aren't required to create latency resource record sets for all Amazon EC2 Regions. Route 53 will choose the * region with the best latency from among the regions that you create latency resource record sets for. * </p> * </li> * <li> * <p> * You can't create non-latency resource record sets that have the same values for the <code>Name</code> and * <code>Type</code> elements as latency resource record sets. * </p> * </li> * </ul> * * @param region * <i>Latency-based resource record sets only:</i> The Amazon EC2 Region where you created the resource that * this resource record set refers to. The resource typically is an Amazon Web Services resource, such as an * EC2 instance or an ELB load balancer, and is referred to by an IP address or a DNS domain name, depending * on the record type.</p> <note> * <p> * Although creating latency and latency alias resource record sets in a private hosted zone is allowed, it's * not supported. * </p> * </note> * <p> * When Amazon Route 53 receives a DNS query for a domain name and type for which you have created latency * resource record sets, Route 53 selects the latency resource record set that has the lowest latency between * the end user and the associated Amazon EC2 Region. Route 53 then returns the value that is associated with * the selected resource record set. * </p> * <p> * Note the following: * </p> * <ul> * <li> * <p> * You can only specify one <code>ResourceRecord</code> per latency resource record set. * </p> * </li> * <li> * <p> * You can only create one latency resource record set for each Amazon EC2 Region. * </p> * </li> * <li> * <p> * You aren't required to create latency resource record sets for all Amazon EC2 Regions. Route 53 will * choose the region with the best latency from among the regions that you create latency resource record * sets for. * </p> * </li> * <li> * <p> * You can't create non-latency resource record sets that have the same values for the <code>Name</code> and * <code>Type</code> elements as latency resource record sets. * </p> * </li> * @return Returns a reference to this object so that method calls can be chained together. * @see ResourceRecordSetRegion */ public ResourceRecordSet withRegion(String region) { setRegion(region); return this; } /** * <p> * <i>Latency-based resource record sets only:</i> The Amazon EC2 Region where you created the resource that this * resource record set refers to. The resource typically is an Amazon Web Services resource, such as an EC2 instance * or an ELB load balancer, and is referred to by an IP address or a DNS domain name, depending on the record type. * </p> * <note> * <p> * Although creating latency and latency alias resource record sets in a private hosted zone is allowed, it's not * supported. * </p> * </note> * <p> * When Amazon Route 53 receives a DNS query for a domain name and type for which you have created latency resource * record sets, Route 53 selects the latency resource record set that has the lowest latency between the end user * and the associated Amazon EC2 Region. Route 53 then returns the value that is associated with the selected * resource record set. * </p> * <p> * Note the following: * </p> * <ul> * <li> * <p> * You can only specify one <code>ResourceRecord</code> per latency resource record set. * </p> * </li> * <li> * <p> * You can only create one latency resource record set for each Amazon EC2 Region. * </p> * </li> * <li> * <p> * You aren't required to create latency resource record sets for all Amazon EC2 Regions. Route 53 will choose the * region with the best latency from among the regions that you create latency resource record sets for. * </p> * </li> * <li> * <p> * You can't create non-latency resource record sets that have the same values for the <code>Name</code> and * <code>Type</code> elements as latency resource record sets. * </p> * </li> * </ul> * * @param region * <i>Latency-based resource record sets only:</i> The Amazon EC2 Region where you created the resource that * this resource record set refers to. The resource typically is an Amazon Web Services resource, such as an * EC2 instance or an ELB load balancer, and is referred to by an IP address or a DNS domain name, depending * on the record type.</p> <note> * <p> * Although creating latency and latency alias resource record sets in a private hosted zone is allowed, it's * not supported. * </p> * </note> * <p> * When Amazon Route 53 receives a DNS query for a domain name and type for which you have created latency * resource record sets, Route 53 selects the latency resource record set that has the lowest latency between * the end user and the associated Amazon EC2 Region. Route 53 then returns the value that is associated with * the selected resource record set. * </p> * <p> * Note the following: * </p> * <ul> * <li> * <p> * You can only specify one <code>ResourceRecord</code> per latency resource record set. * </p> * </li> * <li> * <p> * You can only create one latency resource record set for each Amazon EC2 Region. * </p> * </li> * <li> * <p> * You aren't required to create latency resource record sets for all Amazon EC2 Regions. Route 53 will * choose the region with the best latency from among the regions that you create latency resource record * sets for. * </p> * </li> * <li> * <p> * You can't create non-latency resource record sets that have the same values for the <code>Name</code> and * <code>Type</code> elements as latency resource record sets. * </p> * </li> * @see ResourceRecordSetRegion */ public void setRegion(ResourceRecordSetRegion region) { withRegion(region); } /** * <p> * <i>Latency-based resource record sets only:</i> The Amazon EC2 Region where you created the resource that this * resource record set refers to. The resource typically is an Amazon Web Services resource, such as an EC2 instance * or an ELB load balancer, and is referred to by an IP address or a DNS domain name, depending on the record type. * </p> * <note> * <p> * Although creating latency and latency alias resource record sets in a private hosted zone is allowed, it's not * supported. * </p> * </note> * <p> * When Amazon Route 53 receives a DNS query for a domain name and type for which you have created latency resource * record sets, Route 53 selects the latency resource record set that has the lowest latency between the end user * and the associated Amazon EC2 Region. Route 53 then returns the value that is associated with the selected * resource record set. * </p> * <p> * Note the following: * </p> * <ul> * <li> * <p> * You can only specify one <code>ResourceRecord</code> per latency resource record set. * </p> * </li> * <li> * <p> * You can only create one latency resource record set for each Amazon EC2 Region. * </p> * </li> * <li> * <p> * You aren't required to create latency resource record sets for all Amazon EC2 Regions. Route 53 will choose the * region with the best latency from among the regions that you create latency resource record sets for. * </p> * </li> * <li> * <p> * You can't create non-latency resource record sets that have the same values for the <code>Name</code> and * <code>Type</code> elements as latency resource record sets. * </p> * </li> * </ul> * * @param region * <i>Latency-based resource record sets only:</i> The Amazon EC2 Region where you created the resource that * this resource record set refers to. The resource typically is an Amazon Web Services resource, such as an * EC2 instance or an ELB load balancer, and is referred to by an IP address or a DNS domain name, depending * on the record type.</p> <note> * <p> * Although creating latency and latency alias resource record sets in a private hosted zone is allowed, it's * not supported. * </p> * </note> * <p> * When Amazon Route 53 receives a DNS query for a domain name and type for which you have created latency * resource record sets, Route 53 selects the latency resource record set that has the lowest latency between * the end user and the associated Amazon EC2 Region. Route 53 then returns the value that is associated with * the selected resource record set. * </p> * <p> * Note the following: * </p> * <ul> * <li> * <p> * You can only specify one <code>ResourceRecord</code> per latency resource record set. * </p> * </li> * <li> * <p> * You can only create one latency resource record set for each Amazon EC2 Region. * </p> * </li> * <li> * <p> * You aren't required to create latency resource record sets for all Amazon EC2 Regions. Route 53 will * choose the region with the best latency from among the regions that you create latency resource record * sets for. * </p> * </li> * <li> * <p> * You can't create non-latency resource record sets that have the same values for the <code>Name</code> and * <code>Type</code> elements as latency resource record sets. * </p> * </li> * @return Returns a reference to this object so that method calls can be chained together. * @see ResourceRecordSetRegion */ public ResourceRecordSet withRegion(ResourceRecordSetRegion region) { this.region = region.toString(); return this; } /** * <p> * <i>Geolocation resource record sets only:</i> A complex type that lets you control how Amazon Route 53 responds * to DNS queries based on the geographic origin of the query. For example, if you want all queries from Africa to * be routed to a web server with an IP address of <code>192.0.2.111</code>, create a resource record set with a * <code>Type</code> of <code>A</code> and a <code>ContinentCode</code> of <code>AF</code>. * </p> * <note> * <p> * Although creating geolocation and geolocation alias resource record sets in a private hosted zone is allowed, * it's not supported. * </p> * </note> * <p> * If you create separate resource record sets for overlapping geographic regions (for example, one resource record * set for a continent and one for a country on the same continent), priority goes to the smallest geographic * region. This allows you to route most queries for a continent to one resource and to route queries for a country * on that continent to a different resource. * </p> * <p> * You can't create two geolocation resource record sets that specify the same geographic location. * </p> * <p> * The value <code>*</code> in the <code>CountryCode</code> element matches all geographic locations that aren't * specified in other geolocation resource record sets that have the same values for the <code>Name</code> and * <code>Type</code> elements. * </p> * <important> * <p> * Geolocation works by mapping IP addresses to locations. However, some IP addresses aren't mapped to geographic * locations, so even if you create geolocation resource record sets that cover all seven continents, Route 53 will * receive some DNS queries from locations that it can't identify. We recommend that you create a resource record * set for which the value of <code>CountryCode</code> is <code>*</code>. Two groups of queries are routed to the * resource that you specify in this record: queries that come from locations for which you haven't created * geolocation resource record sets and queries from IP addresses that aren't mapped to a location. If you don't * create a <code>*</code> resource record set, Route 53 returns a "no answer" response for queries from those * locations. * </p> * </important> * <p> * You can't create non-geolocation resource record sets that have the same values for the <code>Name</code> and * <code>Type</code> elements as geolocation resource record sets. * </p> * * @param geoLocation * <i>Geolocation resource record sets only:</i> A complex type that lets you control how Amazon Route 53 * responds to DNS queries based on the geographic origin of the query. For example, if you want all queries * from Africa to be routed to a web server with an IP address of <code>192.0.2.111</code>, create a resource * record set with a <code>Type</code> of <code>A</code> and a <code>ContinentCode</code> of <code>AF</code> * .</p> <note> * <p> * Although creating geolocation and geolocation alias resource record sets in a private hosted zone is * allowed, it's not supported. * </p> * </note> * <p> * If you create separate resource record sets for overlapping geographic regions (for example, one resource * record set for a continent and one for a country on the same continent), priority goes to the smallest * geographic region. This allows you to route most queries for a continent to one resource and to route * queries for a country on that continent to a different resource. * </p> * <p> * You can't create two geolocation resource record sets that specify the same geographic location. * </p> * <p> * The value <code>*</code> in the <code>CountryCode</code> element matches all geographic locations that * aren't specified in other geolocation resource record sets that have the same values for the * <code>Name</code> and <code>Type</code> elements. * </p> * <important> * <p> * Geolocation works by mapping IP addresses to locations. However, some IP addresses aren't mapped to * geographic locations, so even if you create geolocation resource record sets that cover all seven * continents, Route 53 will receive some DNS queries from locations that it can't identify. We recommend * that you create a resource record set for which the value of <code>CountryCode</code> is <code>*</code>. * Two groups of queries are routed to the resource that you specify in this record: queries that come from * locations for which you haven't created geolocation resource record sets and queries from IP addresses * that aren't mapped to a location. If you don't create a <code>*</code> resource record set, Route 53 * returns a "no answer" response for queries from those locations. * </p> * </important> * <p> * You can't create non-geolocation resource record sets that have the same values for the <code>Name</code> * and <code>Type</code> elements as geolocation resource record sets. */ public void setGeoLocation(GeoLocation geoLocation) { this.geoLocation = geoLocation; } /** * <p> * <i>Geolocation resource record sets only:</i> A complex type that lets you control how Amazon Route 53 responds * to DNS queries based on the geographic origin of the query. For example, if you want all queries from Africa to * be routed to a web server with an IP address of <code>192.0.2.111</code>, create a resource record set with a * <code>Type</code> of <code>A</code> and a <code>ContinentCode</code> of <code>AF</code>. * </p> * <note> * <p> * Although creating geolocation and geolocation alias resource record sets in a private hosted zone is allowed, * it's not supported. * </p> * </note> * <p> * If you create separate resource record sets for overlapping geographic regions (for example, one resource record * set for a continent and one for a country on the same continent), priority goes to the smallest geographic * region. This allows you to route most queries for a continent to one resource and to route queries for a country * on that continent to a different resource. * </p> * <p> * You can't create two geolocation resource record sets that specify the same geographic location. * </p> * <p> * The value <code>*</code> in the <code>CountryCode</code> element matches all geographic locations that aren't * specified in other geolocation resource record sets that have the same values for the <code>Name</code> and * <code>Type</code> elements. * </p> * <important> * <p> * Geolocation works by mapping IP addresses to locations. However, some IP addresses aren't mapped to geographic * locations, so even if you create geolocation resource record sets that cover all seven continents, Route 53 will * receive some DNS queries from locations that it can't identify. We recommend that you create a resource record * set for which the value of <code>CountryCode</code> is <code>*</code>. Two groups of queries are routed to the * resource that you specify in this record: queries that come from locations for which you haven't created * geolocation resource record sets and queries from IP addresses that aren't mapped to a location. If you don't * create a <code>*</code> resource record set, Route 53 returns a "no answer" response for queries from those * locations. * </p> * </important> * <p> * You can't create non-geolocation resource record sets that have the same values for the <code>Name</code> and * <code>Type</code> elements as geolocation resource record sets. * </p> * * @return <i>Geolocation resource record sets only:</i> A complex type that lets you control how Amazon Route 53 * responds to DNS queries based on the geographic origin of the query. For example, if you want all queries * from Africa to be routed to a web server with an IP address of <code>192.0.2.111</code>, create a * resource record set with a <code>Type</code> of <code>A</code> and a <code>ContinentCode</code> of * <code>AF</code>.</p> <note> * <p> * Although creating geolocation and geolocation alias resource record sets in a private hosted zone is * allowed, it's not supported. * </p> * </note> * <p> * If you create separate resource record sets for overlapping geographic regions (for example, one resource * record set for a continent and one for a country on the same continent), priority goes to the smallest * geographic region. This allows you to route most queries for a continent to one resource and to route * queries for a country on that continent to a different resource. * </p> * <p> * You can't create two geolocation resource record sets that specify the same geographic location. * </p> * <p> * The value <code>*</code> in the <code>CountryCode</code> element matches all geographic locations that * aren't specified in other geolocation resource record sets that have the same values for the * <code>Name</code> and <code>Type</code> elements. * </p> * <important> * <p> * Geolocation works by mapping IP addresses to locations. However, some IP addresses aren't mapped to * geographic locations, so even if you create geolocation resource record sets that cover all seven * continents, Route 53 will receive some DNS queries from locations that it can't identify. We recommend * that you create a resource record set for which the value of <code>CountryCode</code> is <code>*</code>. * Two groups of queries are routed to the resource that you specify in this record: queries that come from * locations for which you haven't created geolocation resource record sets and queries from IP addresses * that aren't mapped to a location. If you don't create a <code>*</code> resource record set, Route 53 * returns a "no answer" response for queries from those locations. * </p> * </important> * <p> * You can't create non-geolocation resource record sets that have the same values for the <code>Name</code> * and <code>Type</code> elements as geolocation resource record sets. */ public GeoLocation getGeoLocation() { return this.geoLocation; } /** * <p> * <i>Geolocation resource record sets only:</i> A complex type that lets you control how Amazon Route 53 responds * to DNS queries based on the geographic origin of the query. For example, if you want all queries from Africa to * be routed to a web server with an IP address of <code>192.0.2.111</code>, create a resource record set with a * <code>Type</code> of <code>A</code> and a <code>ContinentCode</code> of <code>AF</code>. * </p> * <note> * <p> * Although creating geolocation and geolocation alias resource record sets in a private hosted zone is allowed, * it's not supported. * </p> * </note> * <p> * If you create separate resource record sets for overlapping geographic regions (for example, one resource record * set for a continent and one for a country on the same continent), priority goes to the smallest geographic * region. This allows you to route most queries for a continent to one resource and to route queries for a country * on that continent to a different resource. * </p> * <p> * You can't create two geolocation resource record sets that specify the same geographic location. * </p> * <p> * The value <code>*</code> in the <code>CountryCode</code> element matches all geographic locations that aren't * specified in other geolocation resource record sets that have the same values for the <code>Name</code> and * <code>Type</code> elements. * </p> * <important> * <p> * Geolocation works by mapping IP addresses to locations. However, some IP addresses aren't mapped to geographic * locations, so even if you create geolocation resource record sets that cover all seven continents, Route 53 will * receive some DNS queries from locations that it can't identify. We recommend that you create a resource record * set for which the value of <code>CountryCode</code> is <code>*</code>. Two groups of queries are routed to the * resource that you specify in this record: queries that come from locations for which you haven't created * geolocation resource record sets and queries from IP addresses that aren't mapped to a location. If you don't * create a <code>*</code> resource record set, Route 53 returns a "no answer" response for queries from those * locations. * </p> * </important> * <p> * You can't create non-geolocation resource record sets that have the same values for the <code>Name</code> and * <code>Type</code> elements as geolocation resource record sets. * </p> * * @param geoLocation * <i>Geolocation resource record sets only:</i> A complex type that lets you control how Amazon Route 53 * responds to DNS queries based on the geographic origin of the query. For example, if you want all queries * from Africa to be routed to a web server with an IP address of <code>192.0.2.111</code>, create a resource * record set with a <code>Type</code> of <code>A</code> and a <code>ContinentCode</code> of <code>AF</code> * .</p> <note> * <p> * Although creating geolocation and geolocation alias resource record sets in a private hosted zone is * allowed, it's not supported. * </p> * </note> * <p> * If you create separate resource record sets for overlapping geographic regions (for example, one resource * record set for a continent and one for a country on the same continent), priority goes to the smallest * geographic region. This allows you to route most queries for a continent to one resource and to route * queries for a country on that continent to a different resource. * </p> * <p> * You can't create two geolocation resource record sets that specify the same geographic location. * </p> * <p> * The value <code>*</code> in the <code>CountryCode</code> element matches all geographic locations that * aren't specified in other geolocation resource record sets that have the same values for the * <code>Name</code> and <code>Type</code> elements. * </p> * <important> * <p> * Geolocation works by mapping IP addresses to locations. However, some IP addresses aren't mapped to * geographic locations, so even if you create geolocation resource record sets that cover all seven * continents, Route 53 will receive some DNS queries from locations that it can't identify. We recommend * that you create a resource record set for which the value of <code>CountryCode</code> is <code>*</code>. * Two groups of queries are routed to the resource that you specify in this record: queries that come from * locations for which you haven't created geolocation resource record sets and queries from IP addresses * that aren't mapped to a location. If you don't create a <code>*</code> resource record set, Route 53 * returns a "no answer" response for queries from those locations. * </p> * </important> * <p> * You can't create non-geolocation resource record sets that have the same values for the <code>Name</code> * and <code>Type</code> elements as geolocation resource record sets. * @return Returns a reference to this object so that method calls can be chained together. */ public ResourceRecordSet withGeoLocation(GeoLocation geoLocation) { setGeoLocation(geoLocation); return this; } /** * <p> * <i>Failover resource record sets only:</i> To configure failover, you add the <code>Failover</code> element to * two resource record sets. For one resource record set, you specify <code>PRIMARY</code> as the value for * <code>Failover</code>; for the other resource record set, you specify <code>SECONDARY</code>. In addition, you * include the <code>HealthCheckId</code> element and specify the health check that you want Amazon Route 53 to * perform for each resource record set. * </p> * <p> * Except where noted, the following failover behaviors assume that you have included the <code>HealthCheckId</code> * element in both resource record sets: * </p> * <ul> * <li> * <p> * When the primary resource record set is healthy, Route 53 responds to DNS queries with the applicable value from * the primary resource record set regardless of the health of the secondary resource record set. * </p> * </li> * <li> * <p> * When the primary resource record set is unhealthy and the secondary resource record set is healthy, Route 53 * responds to DNS queries with the applicable value from the secondary resource record set. * </p> * </li> * <li> * <p> * When the secondary resource record set is unhealthy, Route 53 responds to DNS queries with the applicable value * from the primary resource record set regardless of the health of the primary resource record set. * </p> * </li> * <li> * <p> * If you omit the <code>HealthCheckId</code> element for the secondary resource record set, and if the primary * resource record set is unhealthy, Route 53 always responds to DNS queries with the applicable value from the * secondary resource record set. This is true regardless of the health of the associated endpoint. * </p> * </li> * </ul> * <p> * You can't create non-failover resource record sets that have the same values for the <code>Name</code> and * <code>Type</code> elements as failover resource record sets. * </p> * <p> * For failover alias resource record sets, you must also include the <code>EvaluateTargetHealth</code> element and * set the value to true. * </p> * <p> * For more information about configuring failover for Route 53, see the following topics in the <i>Amazon Route 53 * Developer Guide</i>: * </p> * <ul> * <li> * <p> * <a href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover.html">Route 53 Health Checks and * DNS Failover</a> * </p> * </li> * <li> * <p> * <a href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-private-hosted-zones.html"> * Configuring Failover in a Private Hosted Zone</a> * </p> * </li> * </ul> * * @param failover * <i>Failover resource record sets only:</i> To configure failover, you add the <code>Failover</code> * element to two resource record sets. For one resource record set, you specify <code>PRIMARY</code> as the * value for <code>Failover</code>; for the other resource record set, you specify <code>SECONDARY</code>. In * addition, you include the <code>HealthCheckId</code> element and specify the health check that you want * Amazon Route 53 to perform for each resource record set.</p> * <p> * Except where noted, the following failover behaviors assume that you have included the * <code>HealthCheckId</code> element in both resource record sets: * </p> * <ul> * <li> * <p> * When the primary resource record set is healthy, Route 53 responds to DNS queries with the applicable * value from the primary resource record set regardless of the health of the secondary resource record set. * </p> * </li> * <li> * <p> * When the primary resource record set is unhealthy and the secondary resource record set is healthy, Route * 53 responds to DNS queries with the applicable value from the secondary resource record set. * </p> * </li> * <li> * <p> * When the secondary resource record set is unhealthy, Route 53 responds to DNS queries with the applicable * value from the primary resource record set regardless of the health of the primary resource record set. * </p> * </li> * <li> * <p> * If you omit the <code>HealthCheckId</code> element for the secondary resource record set, and if the * primary resource record set is unhealthy, Route 53 always responds to DNS queries with the applicable * value from the secondary resource record set. This is true regardless of the health of the associated * endpoint. * </p> * </li> * </ul> * <p> * You can't create non-failover resource record sets that have the same values for the <code>Name</code> and * <code>Type</code> elements as failover resource record sets. * </p> * <p> * For failover alias resource record sets, you must also include the <code>EvaluateTargetHealth</code> * element and set the value to true. * </p> * <p> * For more information about configuring failover for Route 53, see the following topics in the <i>Amazon * Route 53 Developer Guide</i>: * </p> * <ul> * <li> * <p> * <a href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover.html">Route 53 Health * Checks and DNS Failover</a> * </p> * </li> * <li> * <p> * <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-private-hosted-zones.html"> * Configuring Failover in a Private Hosted Zone</a> * </p> * </li> * @see ResourceRecordSetFailover */ public void setFailover(String failover) { this.failover = failover; } /** * <p> * <i>Failover resource record sets only:</i> To configure failover, you add the <code>Failover</code> element to * two resource record sets. For one resource record set, you specify <code>PRIMARY</code> as the value for * <code>Failover</code>; for the other resource record set, you specify <code>SECONDARY</code>. In addition, you * include the <code>HealthCheckId</code> element and specify the health check that you want Amazon Route 53 to * perform for each resource record set. * </p> * <p> * Except where noted, the following failover behaviors assume that you have included the <code>HealthCheckId</code> * element in both resource record sets: * </p> * <ul> * <li> * <p> * When the primary resource record set is healthy, Route 53 responds to DNS queries with the applicable value from * the primary resource record set regardless of the health of the secondary resource record set. * </p> * </li> * <li> * <p> * When the primary resource record set is unhealthy and the secondary resource record set is healthy, Route 53 * responds to DNS queries with the applicable value from the secondary resource record set. * </p> * </li> * <li> * <p> * When the secondary resource record set is unhealthy, Route 53 responds to DNS queries with the applicable value * from the primary resource record set regardless of the health of the primary resource record set. * </p> * </li> * <li> * <p> * If you omit the <code>HealthCheckId</code> element for the secondary resource record set, and if the primary * resource record set is unhealthy, Route 53 always responds to DNS queries with the applicable value from the * secondary resource record set. This is true regardless of the health of the associated endpoint. * </p> * </li> * </ul> * <p> * You can't create non-failover resource record sets that have the same values for the <code>Name</code> and * <code>Type</code> elements as failover resource record sets. * </p> * <p> * For failover alias resource record sets, you must also include the <code>EvaluateTargetHealth</code> element and * set the value to true. * </p> * <p> * For more information about configuring failover for Route 53, see the following topics in the <i>Amazon Route 53 * Developer Guide</i>: * </p> * <ul> * <li> * <p> * <a href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover.html">Route 53 Health Checks and * DNS Failover</a> * </p> * </li> * <li> * <p> * <a href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-private-hosted-zones.html"> * Configuring Failover in a Private Hosted Zone</a> * </p> * </li> * </ul> * * @return <i>Failover resource record sets only:</i> To configure failover, you add the <code>Failover</code> * element to two resource record sets. For one resource record set, you specify <code>PRIMARY</code> as the * value for <code>Failover</code>; for the other resource record set, you specify <code>SECONDARY</code>. * In addition, you include the <code>HealthCheckId</code> element and specify the health check that you * want Amazon Route 53 to perform for each resource record set.</p> * <p> * Except where noted, the following failover behaviors assume that you have included the * <code>HealthCheckId</code> element in both resource record sets: * </p> * <ul> * <li> * <p> * When the primary resource record set is healthy, Route 53 responds to DNS queries with the applicable * value from the primary resource record set regardless of the health of the secondary resource record set. * </p> * </li> * <li> * <p> * When the primary resource record set is unhealthy and the secondary resource record set is healthy, Route * 53 responds to DNS queries with the applicable value from the secondary resource record set. * </p> * </li> * <li> * <p> * When the secondary resource record set is unhealthy, Route 53 responds to DNS queries with the applicable * value from the primary resource record set regardless of the health of the primary resource record set. * </p> * </li> * <li> * <p> * If you omit the <code>HealthCheckId</code> element for the secondary resource record set, and if the * primary resource record set is unhealthy, Route 53 always responds to DNS queries with the applicable * value from the secondary resource record set. This is true regardless of the health of the associated * endpoint. * </p> * </li> * </ul> * <p> * You can't create non-failover resource record sets that have the same values for the <code>Name</code> * and <code>Type</code> elements as failover resource record sets. * </p> * <p> * For failover alias resource record sets, you must also include the <code>EvaluateTargetHealth</code> * element and set the value to true. * </p> * <p> * For more information about configuring failover for Route 53, see the following topics in the <i>Amazon * Route 53 Developer Guide</i>: * </p> * <ul> * <li> * <p> * <a href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover.html">Route 53 Health * Checks and DNS Failover</a> * </p> * </li> * <li> * <p> * <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-private-hosted-zones.html" * >Configuring Failover in a Private Hosted Zone</a> * </p> * </li> * @see ResourceRecordSetFailover */ public String getFailover() { return this.failover; } /** * <p> * <i>Failover resource record sets only:</i> To configure failover, you add the <code>Failover</code> element to * two resource record sets. For one resource record set, you specify <code>PRIMARY</code> as the value for * <code>Failover</code>; for the other resource record set, you specify <code>SECONDARY</code>. In addition, you * include the <code>HealthCheckId</code> element and specify the health check that you want Amazon Route 53 to * perform for each resource record set. * </p> * <p> * Except where noted, the following failover behaviors assume that you have included the <code>HealthCheckId</code> * element in both resource record sets: * </p> * <ul> * <li> * <p> * When the primary resource record set is healthy, Route 53 responds to DNS queries with the applicable value from * the primary resource record set regardless of the health of the secondary resource record set. * </p> * </li> * <li> * <p> * When the primary resource record set is unhealthy and the secondary resource record set is healthy, Route 53 * responds to DNS queries with the applicable value from the secondary resource record set. * </p> * </li> * <li> * <p> * When the secondary resource record set is unhealthy, Route 53 responds to DNS queries with the applicable value * from the primary resource record set regardless of the health of the primary resource record set. * </p> * </li> * <li> * <p> * If you omit the <code>HealthCheckId</code> element for the secondary resource record set, and if the primary * resource record set is unhealthy, Route 53 always responds to DNS queries with the applicable value from the * secondary resource record set. This is true regardless of the health of the associated endpoint. * </p> * </li> * </ul> * <p> * You can't create non-failover resource record sets that have the same values for the <code>Name</code> and * <code>Type</code> elements as failover resource record sets. * </p> * <p> * For failover alias resource record sets, you must also include the <code>EvaluateTargetHealth</code> element and * set the value to true. * </p> * <p> * For more information about configuring failover for Route 53, see the following topics in the <i>Amazon Route 53 * Developer Guide</i>: * </p> * <ul> * <li> * <p> * <a href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover.html">Route 53 Health Checks and * DNS Failover</a> * </p> * </li> * <li> * <p> * <a href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-private-hosted-zones.html"> * Configuring Failover in a Private Hosted Zone</a> * </p> * </li> * </ul> * * @param failover * <i>Failover resource record sets only:</i> To configure failover, you add the <code>Failover</code> * element to two resource record sets. For one resource record set, you specify <code>PRIMARY</code> as the * value for <code>Failover</code>; for the other resource record set, you specify <code>SECONDARY</code>. In * addition, you include the <code>HealthCheckId</code> element and specify the health check that you want * Amazon Route 53 to perform for each resource record set.</p> * <p> * Except where noted, the following failover behaviors assume that you have included the * <code>HealthCheckId</code> element in both resource record sets: * </p> * <ul> * <li> * <p> * When the primary resource record set is healthy, Route 53 responds to DNS queries with the applicable * value from the primary resource record set regardless of the health of the secondary resource record set. * </p> * </li> * <li> * <p> * When the primary resource record set is unhealthy and the secondary resource record set is healthy, Route * 53 responds to DNS queries with the applicable value from the secondary resource record set. * </p> * </li> * <li> * <p> * When the secondary resource record set is unhealthy, Route 53 responds to DNS queries with the applicable * value from the primary resource record set regardless of the health of the primary resource record set. * </p> * </li> * <li> * <p> * If you omit the <code>HealthCheckId</code> element for the secondary resource record set, and if the * primary resource record set is unhealthy, Route 53 always responds to DNS queries with the applicable * value from the secondary resource record set. This is true regardless of the health of the associated * endpoint. * </p> * </li> * </ul> * <p> * You can't create non-failover resource record sets that have the same values for the <code>Name</code> and * <code>Type</code> elements as failover resource record sets. * </p> * <p> * For failover alias resource record sets, you must also include the <code>EvaluateTargetHealth</code> * element and set the value to true. * </p> * <p> * For more information about configuring failover for Route 53, see the following topics in the <i>Amazon * Route 53 Developer Guide</i>: * </p> * <ul> * <li> * <p> * <a href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover.html">Route 53 Health * Checks and DNS Failover</a> * </p> * </li> * <li> * <p> * <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-private-hosted-zones.html"> * Configuring Failover in a Private Hosted Zone</a> * </p> * </li> * @return Returns a reference to this object so that method calls can be chained together. * @see ResourceRecordSetFailover */ public ResourceRecordSet withFailover(String failover) { setFailover(failover); return this; } /** * <p> * <i>Failover resource record sets only:</i> To configure failover, you add the <code>Failover</code> element to * two resource record sets. For one resource record set, you specify <code>PRIMARY</code> as the value for * <code>Failover</code>; for the other resource record set, you specify <code>SECONDARY</code>. In addition, you * include the <code>HealthCheckId</code> element and specify the health check that you want Amazon Route 53 to * perform for each resource record set. * </p> * <p> * Except where noted, the following failover behaviors assume that you have included the <code>HealthCheckId</code> * element in both resource record sets: * </p> * <ul> * <li> * <p> * When the primary resource record set is healthy, Route 53 responds to DNS queries with the applicable value from * the primary resource record set regardless of the health of the secondary resource record set. * </p> * </li> * <li> * <p> * When the primary resource record set is unhealthy and the secondary resource record set is healthy, Route 53 * responds to DNS queries with the applicable value from the secondary resource record set. * </p> * </li> * <li> * <p> * When the secondary resource record set is unhealthy, Route 53 responds to DNS queries with the applicable value * from the primary resource record set regardless of the health of the primary resource record set. * </p> * </li> * <li> * <p> * If you omit the <code>HealthCheckId</code> element for the secondary resource record set, and if the primary * resource record set is unhealthy, Route 53 always responds to DNS queries with the applicable value from the * secondary resource record set. This is true regardless of the health of the associated endpoint. * </p> * </li> * </ul> * <p> * You can't create non-failover resource record sets that have the same values for the <code>Name</code> and * <code>Type</code> elements as failover resource record sets. * </p> * <p> * For failover alias resource record sets, you must also include the <code>EvaluateTargetHealth</code> element and * set the value to true. * </p> * <p> * For more information about configuring failover for Route 53, see the following topics in the <i>Amazon Route 53 * Developer Guide</i>: * </p> * <ul> * <li> * <p> * <a href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover.html">Route 53 Health Checks and * DNS Failover</a> * </p> * </li> * <li> * <p> * <a href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-private-hosted-zones.html"> * Configuring Failover in a Private Hosted Zone</a> * </p> * </li> * </ul> * * @param failover * <i>Failover resource record sets only:</i> To configure failover, you add the <code>Failover</code> * element to two resource record sets. For one resource record set, you specify <code>PRIMARY</code> as the * value for <code>Failover</code>; for the other resource record set, you specify <code>SECONDARY</code>. In * addition, you include the <code>HealthCheckId</code> element and specify the health check that you want * Amazon Route 53 to perform for each resource record set.</p> * <p> * Except where noted, the following failover behaviors assume that you have included the * <code>HealthCheckId</code> element in both resource record sets: * </p> * <ul> * <li> * <p> * When the primary resource record set is healthy, Route 53 responds to DNS queries with the applicable * value from the primary resource record set regardless of the health of the secondary resource record set. * </p> * </li> * <li> * <p> * When the primary resource record set is unhealthy and the secondary resource record set is healthy, Route * 53 responds to DNS queries with the applicable value from the secondary resource record set. * </p> * </li> * <li> * <p> * When the secondary resource record set is unhealthy, Route 53 responds to DNS queries with the applicable * value from the primary resource record set regardless of the health of the primary resource record set. * </p> * </li> * <li> * <p> * If you omit the <code>HealthCheckId</code> element for the secondary resource record set, and if the * primary resource record set is unhealthy, Route 53 always responds to DNS queries with the applicable * value from the secondary resource record set. This is true regardless of the health of the associated * endpoint. * </p> * </li> * </ul> * <p> * You can't create non-failover resource record sets that have the same values for the <code>Name</code> and * <code>Type</code> elements as failover resource record sets. * </p> * <p> * For failover alias resource record sets, you must also include the <code>EvaluateTargetHealth</code> * element and set the value to true. * </p> * <p> * For more information about configuring failover for Route 53, see the following topics in the <i>Amazon * Route 53 Developer Guide</i>: * </p> * <ul> * <li> * <p> * <a href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover.html">Route 53 Health * Checks and DNS Failover</a> * </p> * </li> * <li> * <p> * <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-private-hosted-zones.html"> * Configuring Failover in a Private Hosted Zone</a> * </p> * </li> * @see ResourceRecordSetFailover */ public void setFailover(ResourceRecordSetFailover failover) { withFailover(failover); } /** * <p> * <i>Failover resource record sets only:</i> To configure failover, you add the <code>Failover</code> element to * two resource record sets. For one resource record set, you specify <code>PRIMARY</code> as the value for * <code>Failover</code>; for the other resource record set, you specify <code>SECONDARY</code>. In addition, you * include the <code>HealthCheckId</code> element and specify the health check that you want Amazon Route 53 to * perform for each resource record set. * </p> * <p> * Except where noted, the following failover behaviors assume that you have included the <code>HealthCheckId</code> * element in both resource record sets: * </p> * <ul> * <li> * <p> * When the primary resource record set is healthy, Route 53 responds to DNS queries with the applicable value from * the primary resource record set regardless of the health of the secondary resource record set. * </p> * </li> * <li> * <p> * When the primary resource record set is unhealthy and the secondary resource record set is healthy, Route 53 * responds to DNS queries with the applicable value from the secondary resource record set. * </p> * </li> * <li> * <p> * When the secondary resource record set is unhealthy, Route 53 responds to DNS queries with the applicable value * from the primary resource record set regardless of the health of the primary resource record set. * </p> * </li> * <li> * <p> * If you omit the <code>HealthCheckId</code> element for the secondary resource record set, and if the primary * resource record set is unhealthy, Route 53 always responds to DNS queries with the applicable value from the * secondary resource record set. This is true regardless of the health of the associated endpoint. * </p> * </li> * </ul> * <p> * You can't create non-failover resource record sets that have the same values for the <code>Name</code> and * <code>Type</code> elements as failover resource record sets. * </p> * <p> * For failover alias resource record sets, you must also include the <code>EvaluateTargetHealth</code> element and * set the value to true. * </p> * <p> * For more information about configuring failover for Route 53, see the following topics in the <i>Amazon Route 53 * Developer Guide</i>: * </p> * <ul> * <li> * <p> * <a href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover.html">Route 53 Health Checks and * DNS Failover</a> * </p> * </li> * <li> * <p> * <a href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-private-hosted-zones.html"> * Configuring Failover in a Private Hosted Zone</a> * </p> * </li> * </ul> * * @param failover * <i>Failover resource record sets only:</i> To configure failover, you add the <code>Failover</code> * element to two resource record sets. For one resource record set, you specify <code>PRIMARY</code> as the * value for <code>Failover</code>; for the other resource record set, you specify <code>SECONDARY</code>. In * addition, you include the <code>HealthCheckId</code> element and specify the health check that you want * Amazon Route 53 to perform for each resource record set.</p> * <p> * Except where noted, the following failover behaviors assume that you have included the * <code>HealthCheckId</code> element in both resource record sets: * </p> * <ul> * <li> * <p> * When the primary resource record set is healthy, Route 53 responds to DNS queries with the applicable * value from the primary resource record set regardless of the health of the secondary resource record set. * </p> * </li> * <li> * <p> * When the primary resource record set is unhealthy and the secondary resource record set is healthy, Route * 53 responds to DNS queries with the applicable value from the secondary resource record set. * </p> * </li> * <li> * <p> * When the secondary resource record set is unhealthy, Route 53 responds to DNS queries with the applicable * value from the primary resource record set regardless of the health of the primary resource record set. * </p> * </li> * <li> * <p> * If you omit the <code>HealthCheckId</code> element for the secondary resource record set, and if the * primary resource record set is unhealthy, Route 53 always responds to DNS queries with the applicable * value from the secondary resource record set. This is true regardless of the health of the associated * endpoint. * </p> * </li> * </ul> * <p> * You can't create non-failover resource record sets that have the same values for the <code>Name</code> and * <code>Type</code> elements as failover resource record sets. * </p> * <p> * For failover alias resource record sets, you must also include the <code>EvaluateTargetHealth</code> * element and set the value to true. * </p> * <p> * For more information about configuring failover for Route 53, see the following topics in the <i>Amazon * Route 53 Developer Guide</i>: * </p> * <ul> * <li> * <p> * <a href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover.html">Route 53 Health * Checks and DNS Failover</a> * </p> * </li> * <li> * <p> * <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-private-hosted-zones.html"> * Configuring Failover in a Private Hosted Zone</a> * </p> * </li> * @return Returns a reference to this object so that method calls can be chained together. * @see ResourceRecordSetFailover */ public ResourceRecordSet withFailover(ResourceRecordSetFailover failover) { this.failover = failover.toString(); return this; } /** * <p> * <i>Multivalue answer resource record sets only</i>: To route traffic approximately randomly to multiple * resources, such as web servers, create one multivalue answer record for each resource and specify * <code>true</code> for <code>MultiValueAnswer</code>. Note the following: * </p> * <ul> * <li> * <p> * If you associate a health check with a multivalue answer resource record set, Amazon Route 53 responds to DNS * queries with the corresponding IP address only when the health check is healthy. * </p> * </li> * <li> * <p> * If you don't associate a health check with a multivalue answer record, Route 53 always considers the record to be * healthy. * </p> * </li> * <li> * <p> * Route 53 responds to DNS queries with up to eight healthy records; if you have eight or fewer healthy records, * Route 53 responds to all DNS queries with all the healthy records. * </p> * </li> * <li> * <p> * If you have more than eight healthy records, Route 53 responds to different DNS resolvers with different * combinations of healthy records. * </p> * </li> * <li> * <p> * When all records are unhealthy, Route 53 responds to DNS queries with up to eight unhealthy records. * </p> * </li> * <li> * <p> * If a resource becomes unavailable after a resolver caches a response, client software typically tries another of * the IP addresses in the response. * </p> * </li> * </ul> * <p> * You can't create multivalue answer alias records. * </p> * * @param multiValueAnswer * <i>Multivalue answer resource record sets only</i>: To route traffic approximately randomly to multiple * resources, such as web servers, create one multivalue answer record for each resource and specify * <code>true</code> for <code>MultiValueAnswer</code>. Note the following:</p> * <ul> * <li> * <p> * If you associate a health check with a multivalue answer resource record set, Amazon Route 53 responds to * DNS queries with the corresponding IP address only when the health check is healthy. * </p> * </li> * <li> * <p> * If you don't associate a health check with a multivalue answer record, Route 53 always considers the * record to be healthy. * </p> * </li> * <li> * <p> * Route 53 responds to DNS queries with up to eight healthy records; if you have eight or fewer healthy * records, Route 53 responds to all DNS queries with all the healthy records. * </p> * </li> * <li> * <p> * If you have more than eight healthy records, Route 53 responds to different DNS resolvers with different * combinations of healthy records. * </p> * </li> * <li> * <p> * When all records are unhealthy, Route 53 responds to DNS queries with up to eight unhealthy records. * </p> * </li> * <li> * <p> * If a resource becomes unavailable after a resolver caches a response, client software typically tries * another of the IP addresses in the response. * </p> * </li> * </ul> * <p> * You can't create multivalue answer alias records. */ public void setMultiValueAnswer(Boolean multiValueAnswer) { this.multiValueAnswer = multiValueAnswer; } /** * <p> * <i>Multivalue answer resource record sets only</i>: To route traffic approximately randomly to multiple * resources, such as web servers, create one multivalue answer record for each resource and specify * <code>true</code> for <code>MultiValueAnswer</code>. Note the following: * </p> * <ul> * <li> * <p> * If you associate a health check with a multivalue answer resource record set, Amazon Route 53 responds to DNS * queries with the corresponding IP address only when the health check is healthy. * </p> * </li> * <li> * <p> * If you don't associate a health check with a multivalue answer record, Route 53 always considers the record to be * healthy. * </p> * </li> * <li> * <p> * Route 53 responds to DNS queries with up to eight healthy records; if you have eight or fewer healthy records, * Route 53 responds to all DNS queries with all the healthy records. * </p> * </li> * <li> * <p> * If you have more than eight healthy records, Route 53 responds to different DNS resolvers with different * combinations of healthy records. * </p> * </li> * <li> * <p> * When all records are unhealthy, Route 53 responds to DNS queries with up to eight unhealthy records. * </p> * </li> * <li> * <p> * If a resource becomes unavailable after a resolver caches a response, client software typically tries another of * the IP addresses in the response. * </p> * </li> * </ul> * <p> * You can't create multivalue answer alias records. * </p> * * @return <i>Multivalue answer resource record sets only</i>: To route traffic approximately randomly to multiple * resources, such as web servers, create one multivalue answer record for each resource and specify * <code>true</code> for <code>MultiValueAnswer</code>. Note the following:</p> * <ul> * <li> * <p> * If you associate a health check with a multivalue answer resource record set, Amazon Route 53 responds to * DNS queries with the corresponding IP address only when the health check is healthy. * </p> * </li> * <li> * <p> * If you don't associate a health check with a multivalue answer record, Route 53 always considers the * record to be healthy. * </p> * </li> * <li> * <p> * Route 53 responds to DNS queries with up to eight healthy records; if you have eight or fewer healthy * records, Route 53 responds to all DNS queries with all the healthy records. * </p> * </li> * <li> * <p> * If you have more than eight healthy records, Route 53 responds to different DNS resolvers with different * combinations of healthy records. * </p> * </li> * <li> * <p> * When all records are unhealthy, Route 53 responds to DNS queries with up to eight unhealthy records. * </p> * </li> * <li> * <p> * If a resource becomes unavailable after a resolver caches a response, client software typically tries * another of the IP addresses in the response. * </p> * </li> * </ul> * <p> * You can't create multivalue answer alias records. */ public Boolean getMultiValueAnswer() { return this.multiValueAnswer; } /** * <p> * <i>Multivalue answer resource record sets only</i>: To route traffic approximately randomly to multiple * resources, such as web servers, create one multivalue answer record for each resource and specify * <code>true</code> for <code>MultiValueAnswer</code>. Note the following: * </p> * <ul> * <li> * <p> * If you associate a health check with a multivalue answer resource record set, Amazon Route 53 responds to DNS * queries with the corresponding IP address only when the health check is healthy. * </p> * </li> * <li> * <p> * If you don't associate a health check with a multivalue answer record, Route 53 always considers the record to be * healthy. * </p> * </li> * <li> * <p> * Route 53 responds to DNS queries with up to eight healthy records; if you have eight or fewer healthy records, * Route 53 responds to all DNS queries with all the healthy records. * </p> * </li> * <li> * <p> * If you have more than eight healthy records, Route 53 responds to different DNS resolvers with different * combinations of healthy records. * </p> * </li> * <li> * <p> * When all records are unhealthy, Route 53 responds to DNS queries with up to eight unhealthy records. * </p> * </li> * <li> * <p> * If a resource becomes unavailable after a resolver caches a response, client software typically tries another of * the IP addresses in the response. * </p> * </li> * </ul> * <p> * You can't create multivalue answer alias records. * </p> * * @param multiValueAnswer * <i>Multivalue answer resource record sets only</i>: To route traffic approximately randomly to multiple * resources, such as web servers, create one multivalue answer record for each resource and specify * <code>true</code> for <code>MultiValueAnswer</code>. Note the following:</p> * <ul> * <li> * <p> * If you associate a health check with a multivalue answer resource record set, Amazon Route 53 responds to * DNS queries with the corresponding IP address only when the health check is healthy. * </p> * </li> * <li> * <p> * If you don't associate a health check with a multivalue answer record, Route 53 always considers the * record to be healthy. * </p> * </li> * <li> * <p> * Route 53 responds to DNS queries with up to eight healthy records; if you have eight or fewer healthy * records, Route 53 responds to all DNS queries with all the healthy records. * </p> * </li> * <li> * <p> * If you have more than eight healthy records, Route 53 responds to different DNS resolvers with different * combinations of healthy records. * </p> * </li> * <li> * <p> * When all records are unhealthy, Route 53 responds to DNS queries with up to eight unhealthy records. * </p> * </li> * <li> * <p> * If a resource becomes unavailable after a resolver caches a response, client software typically tries * another of the IP addresses in the response. * </p> * </li> * </ul> * <p> * You can't create multivalue answer alias records. * @return Returns a reference to this object so that method calls can be chained together. */ public ResourceRecordSet withMultiValueAnswer(Boolean multiValueAnswer) { setMultiValueAnswer(multiValueAnswer); return this; } /** * <p> * <i>Multivalue answer resource record sets only</i>: To route traffic approximately randomly to multiple * resources, such as web servers, create one multivalue answer record for each resource and specify * <code>true</code> for <code>MultiValueAnswer</code>. Note the following: * </p> * <ul> * <li> * <p> * If you associate a health check with a multivalue answer resource record set, Amazon Route 53 responds to DNS * queries with the corresponding IP address only when the health check is healthy. * </p> * </li> * <li> * <p> * If you don't associate a health check with a multivalue answer record, Route 53 always considers the record to be * healthy. * </p> * </li> * <li> * <p> * Route 53 responds to DNS queries with up to eight healthy records; if you have eight or fewer healthy records, * Route 53 responds to all DNS queries with all the healthy records. * </p> * </li> * <li> * <p> * If you have more than eight healthy records, Route 53 responds to different DNS resolvers with different * combinations of healthy records. * </p> * </li> * <li> * <p> * When all records are unhealthy, Route 53 responds to DNS queries with up to eight unhealthy records. * </p> * </li> * <li> * <p> * If a resource becomes unavailable after a resolver caches a response, client software typically tries another of * the IP addresses in the response. * </p> * </li> * </ul> * <p> * You can't create multivalue answer alias records. * </p> * * @return <i>Multivalue answer resource record sets only</i>: To route traffic approximately randomly to multiple * resources, such as web servers, create one multivalue answer record for each resource and specify * <code>true</code> for <code>MultiValueAnswer</code>. Note the following:</p> * <ul> * <li> * <p> * If you associate a health check with a multivalue answer resource record set, Amazon Route 53 responds to * DNS queries with the corresponding IP address only when the health check is healthy. * </p> * </li> * <li> * <p> * If you don't associate a health check with a multivalue answer record, Route 53 always considers the * record to be healthy. * </p> * </li> * <li> * <p> * Route 53 responds to DNS queries with up to eight healthy records; if you have eight or fewer healthy * records, Route 53 responds to all DNS queries with all the healthy records. * </p> * </li> * <li> * <p> * If you have more than eight healthy records, Route 53 responds to different DNS resolvers with different * combinations of healthy records. * </p> * </li> * <li> * <p> * When all records are unhealthy, Route 53 responds to DNS queries with up to eight unhealthy records. * </p> * </li> * <li> * <p> * If a resource becomes unavailable after a resolver caches a response, client software typically tries * another of the IP addresses in the response. * </p> * </li> * </ul> * <p> * You can't create multivalue answer alias records. */ public Boolean isMultiValueAnswer() { return this.multiValueAnswer; } /** * <p> * The resource record cache time to live (TTL), in seconds. Note the following: * </p> * <ul> * <li> * <p> * If you're creating or updating an alias resource record set, omit <code>TTL</code>. Amazon Route 53 uses the * value of <code>TTL</code> for the alias target. * </p> * </li> * <li> * <p> * If you're associating this resource record set with a health check (if you're adding a <code>HealthCheckId</code> * element), we recommend that you specify a <code>TTL</code> of 60 seconds or less so clients respond quickly to * changes in health status. * </p> * </li> * <li> * <p> * All of the resource record sets in a group of weighted resource record sets must have the same value for * <code>TTL</code>. * </p> * </li> * <li> * <p> * If a group of weighted resource record sets includes one or more weighted alias resource record sets for which * the alias target is an ELB load balancer, we recommend that you specify a <code>TTL</code> of 60 seconds for all * of the non-alias weighted resource record sets that have the same name and type. Values other than 60 seconds * (the TTL for load balancers) will change the effect of the values that you specify for <code>Weight</code>. * </p> * </li> * </ul> * * @param tTL * The resource record cache time to live (TTL), in seconds. Note the following:</p> * <ul> * <li> * <p> * If you're creating or updating an alias resource record set, omit <code>TTL</code>. Amazon Route 53 uses * the value of <code>TTL</code> for the alias target. * </p> * </li> * <li> * <p> * If you're associating this resource record set with a health check (if you're adding a * <code>HealthCheckId</code> element), we recommend that you specify a <code>TTL</code> of 60 seconds or * less so clients respond quickly to changes in health status. * </p> * </li> * <li> * <p> * All of the resource record sets in a group of weighted resource record sets must have the same value for * <code>TTL</code>. * </p> * </li> * <li> * <p> * If a group of weighted resource record sets includes one or more weighted alias resource record sets for * which the alias target is an ELB load balancer, we recommend that you specify a <code>TTL</code> of 60 * seconds for all of the non-alias weighted resource record sets that have the same name and type. Values * other than 60 seconds (the TTL for load balancers) will change the effect of the values that you specify * for <code>Weight</code>. * </p> * </li> */ public void setTTL(Long tTL) { this.tTL = tTL; } /** * <p> * The resource record cache time to live (TTL), in seconds. Note the following: * </p> * <ul> * <li> * <p> * If you're creating or updating an alias resource record set, omit <code>TTL</code>. Amazon Route 53 uses the * value of <code>TTL</code> for the alias target. * </p> * </li> * <li> * <p> * If you're associating this resource record set with a health check (if you're adding a <code>HealthCheckId</code> * element), we recommend that you specify a <code>TTL</code> of 60 seconds or less so clients respond quickly to * changes in health status. * </p> * </li> * <li> * <p> * All of the resource record sets in a group of weighted resource record sets must have the same value for * <code>TTL</code>. * </p> * </li> * <li> * <p> * If a group of weighted resource record sets includes one or more weighted alias resource record sets for which * the alias target is an ELB load balancer, we recommend that you specify a <code>TTL</code> of 60 seconds for all * of the non-alias weighted resource record sets that have the same name and type. Values other than 60 seconds * (the TTL for load balancers) will change the effect of the values that you specify for <code>Weight</code>. * </p> * </li> * </ul> * * @return The resource record cache time to live (TTL), in seconds. Note the following:</p> * <ul> * <li> * <p> * If you're creating or updating an alias resource record set, omit <code>TTL</code>. Amazon Route 53 uses * the value of <code>TTL</code> for the alias target. * </p> * </li> * <li> * <p> * If you're associating this resource record set with a health check (if you're adding a * <code>HealthCheckId</code> element), we recommend that you specify a <code>TTL</code> of 60 seconds or * less so clients respond quickly to changes in health status. * </p> * </li> * <li> * <p> * All of the resource record sets in a group of weighted resource record sets must have the same value for * <code>TTL</code>. * </p> * </li> * <li> * <p> * If a group of weighted resource record sets includes one or more weighted alias resource record sets for * which the alias target is an ELB load balancer, we recommend that you specify a <code>TTL</code> of 60 * seconds for all of the non-alias weighted resource record sets that have the same name and type. Values * other than 60 seconds (the TTL for load balancers) will change the effect of the values that you specify * for <code>Weight</code>. * </p> * </li> */ public Long getTTL() { return this.tTL; } /** * <p> * The resource record cache time to live (TTL), in seconds. Note the following: * </p> * <ul> * <li> * <p> * If you're creating or updating an alias resource record set, omit <code>TTL</code>. Amazon Route 53 uses the * value of <code>TTL</code> for the alias target. * </p> * </li> * <li> * <p> * If you're associating this resource record set with a health check (if you're adding a <code>HealthCheckId</code> * element), we recommend that you specify a <code>TTL</code> of 60 seconds or less so clients respond quickly to * changes in health status. * </p> * </li> * <li> * <p> * All of the resource record sets in a group of weighted resource record sets must have the same value for * <code>TTL</code>. * </p> * </li> * <li> * <p> * If a group of weighted resource record sets includes one or more weighted alias resource record sets for which * the alias target is an ELB load balancer, we recommend that you specify a <code>TTL</code> of 60 seconds for all * of the non-alias weighted resource record sets that have the same name and type. Values other than 60 seconds * (the TTL for load balancers) will change the effect of the values that you specify for <code>Weight</code>. * </p> * </li> * </ul> * * @param tTL * The resource record cache time to live (TTL), in seconds. Note the following:</p> * <ul> * <li> * <p> * If you're creating or updating an alias resource record set, omit <code>TTL</code>. Amazon Route 53 uses * the value of <code>TTL</code> for the alias target. * </p> * </li> * <li> * <p> * If you're associating this resource record set with a health check (if you're adding a * <code>HealthCheckId</code> element), we recommend that you specify a <code>TTL</code> of 60 seconds or * less so clients respond quickly to changes in health status. * </p> * </li> * <li> * <p> * All of the resource record sets in a group of weighted resource record sets must have the same value for * <code>TTL</code>. * </p> * </li> * <li> * <p> * If a group of weighted resource record sets includes one or more weighted alias resource record sets for * which the alias target is an ELB load balancer, we recommend that you specify a <code>TTL</code> of 60 * seconds for all of the non-alias weighted resource record sets that have the same name and type. Values * other than 60 seconds (the TTL for load balancers) will change the effect of the values that you specify * for <code>Weight</code>. * </p> * </li> * @return Returns a reference to this object so that method calls can be chained together. */ public ResourceRecordSet withTTL(Long tTL) { setTTL(tTL); return this; } /** * <p> * Information about the resource records to act upon. * </p> * <note> * <p> * If you're creating an alias resource record set, omit <code>ResourceRecords</code>. * </p> * </note> * * @return Information about the resource records to act upon.</p> <note> * <p> * If you're creating an alias resource record set, omit <code>ResourceRecords</code>. * </p> */ public java.util.List<ResourceRecord> getResourceRecords() { if (resourceRecords == null) { resourceRecords = new com.amazonaws.internal.SdkInternalList<ResourceRecord>(); } return resourceRecords; } /** * <p> * Information about the resource records to act upon. * </p> * <note> * <p> * If you're creating an alias resource record set, omit <code>ResourceRecords</code>. * </p> * </note> * * @param resourceRecords * Information about the resource records to act upon.</p> <note> * <p> * If you're creating an alias resource record set, omit <code>ResourceRecords</code>. * </p> */ public void setResourceRecords(java.util.Collection<ResourceRecord> resourceRecords) { if (resourceRecords == null) { this.resourceRecords = null; return; } this.resourceRecords = new com.amazonaws.internal.SdkInternalList<ResourceRecord>(resourceRecords); } /** * <p> * Information about the resource records to act upon. * </p> * <note> * <p> * If you're creating an alias resource record set, omit <code>ResourceRecords</code>. * </p> * </note> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setResourceRecords(java.util.Collection)} or {@link #withResourceRecords(java.util.Collection)} if you * want to override the existing values. * </p> * * @param resourceRecords * Information about the resource records to act upon.</p> <note> * <p> * If you're creating an alias resource record set, omit <code>ResourceRecords</code>. * </p> * @return Returns a reference to this object so that method calls can be chained together. */ public ResourceRecordSet withResourceRecords(ResourceRecord... resourceRecords) { if (this.resourceRecords == null) { setResourceRecords(new com.amazonaws.internal.SdkInternalList<ResourceRecord>(resourceRecords.length)); } for (ResourceRecord ele : resourceRecords) { this.resourceRecords.add(ele); } return this; } /** * <p> * Information about the resource records to act upon. * </p> * <note> * <p> * If you're creating an alias resource record set, omit <code>ResourceRecords</code>. * </p> * </note> * * @param resourceRecords * Information about the resource records to act upon.</p> <note> * <p> * If you're creating an alias resource record set, omit <code>ResourceRecords</code>. * </p> * @return Returns a reference to this object so that method calls can be chained together. */ public ResourceRecordSet withResourceRecords(java.util.Collection<ResourceRecord> resourceRecords) { setResourceRecords(resourceRecords); return this; } /** * <p> * <i>Alias resource record sets only:</i> Information about the Amazon Web Services resource, such as a CloudFront * distribution or an Amazon S3 bucket, that you want to route traffic to. * </p> * <p> * If you're creating resource records sets for a private hosted zone, note the following: * </p> * <ul> * <li> * <p> * You can't create an alias resource record set in a private hosted zone to route traffic to a CloudFront * distribution. * </p> * </li> * <li> * <p> * Creating geolocation alias resource record sets or latency alias resource record sets in a private hosted zone is * unsupported. * </p> * </li> * <li> * <p> * For information about creating failover resource record sets in a private hosted zone, see <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-private-hosted-zones.html" * >Configuring Failover in a Private Hosted Zone</a> in the <i>Amazon Route 53 Developer Guide</i>. * </p> * </li> * </ul> * * @param aliasTarget * <i>Alias resource record sets only:</i> Information about the Amazon Web Services resource, such as a * CloudFront distribution or an Amazon S3 bucket, that you want to route traffic to. </p> * <p> * If you're creating resource records sets for a private hosted zone, note the following: * </p> * <ul> * <li> * <p> * You can't create an alias resource record set in a private hosted zone to route traffic to a CloudFront * distribution. * </p> * </li> * <li> * <p> * Creating geolocation alias resource record sets or latency alias resource record sets in a private hosted * zone is unsupported. * </p> * </li> * <li> * <p> * For information about creating failover resource record sets in a private hosted zone, see <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-private-hosted-zones.html" * >Configuring Failover in a Private Hosted Zone</a> in the <i>Amazon Route 53 Developer Guide</i>. * </p> * </li> */ public void setAliasTarget(AliasTarget aliasTarget) { this.aliasTarget = aliasTarget; } /** * <p> * <i>Alias resource record sets only:</i> Information about the Amazon Web Services resource, such as a CloudFront * distribution or an Amazon S3 bucket, that you want to route traffic to. * </p> * <p> * If you're creating resource records sets for a private hosted zone, note the following: * </p> * <ul> * <li> * <p> * You can't create an alias resource record set in a private hosted zone to route traffic to a CloudFront * distribution. * </p> * </li> * <li> * <p> * Creating geolocation alias resource record sets or latency alias resource record sets in a private hosted zone is * unsupported. * </p> * </li> * <li> * <p> * For information about creating failover resource record sets in a private hosted zone, see <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-private-hosted-zones.html" * >Configuring Failover in a Private Hosted Zone</a> in the <i>Amazon Route 53 Developer Guide</i>. * </p> * </li> * </ul> * * @return <i>Alias resource record sets only:</i> Information about the Amazon Web Services resource, such as a * CloudFront distribution or an Amazon S3 bucket, that you want to route traffic to. </p> * <p> * If you're creating resource records sets for a private hosted zone, note the following: * </p> * <ul> * <li> * <p> * You can't create an alias resource record set in a private hosted zone to route traffic to a CloudFront * distribution. * </p> * </li> * <li> * <p> * Creating geolocation alias resource record sets or latency alias resource record sets in a private hosted * zone is unsupported. * </p> * </li> * <li> * <p> * For information about creating failover resource record sets in a private hosted zone, see <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-private-hosted-zones.html" * >Configuring Failover in a Private Hosted Zone</a> in the <i>Amazon Route 53 Developer Guide</i>. * </p> * </li> */ public AliasTarget getAliasTarget() { return this.aliasTarget; } /** * <p> * <i>Alias resource record sets only:</i> Information about the Amazon Web Services resource, such as a CloudFront * distribution or an Amazon S3 bucket, that you want to route traffic to. * </p> * <p> * If you're creating resource records sets for a private hosted zone, note the following: * </p> * <ul> * <li> * <p> * You can't create an alias resource record set in a private hosted zone to route traffic to a CloudFront * distribution. * </p> * </li> * <li> * <p> * Creating geolocation alias resource record sets or latency alias resource record sets in a private hosted zone is * unsupported. * </p> * </li> * <li> * <p> * For information about creating failover resource record sets in a private hosted zone, see <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-private-hosted-zones.html" * >Configuring Failover in a Private Hosted Zone</a> in the <i>Amazon Route 53 Developer Guide</i>. * </p> * </li> * </ul> * * @param aliasTarget * <i>Alias resource record sets only:</i> Information about the Amazon Web Services resource, such as a * CloudFront distribution or an Amazon S3 bucket, that you want to route traffic to. </p> * <p> * If you're creating resource records sets for a private hosted zone, note the following: * </p> * <ul> * <li> * <p> * You can't create an alias resource record set in a private hosted zone to route traffic to a CloudFront * distribution. * </p> * </li> * <li> * <p> * Creating geolocation alias resource record sets or latency alias resource record sets in a private hosted * zone is unsupported. * </p> * </li> * <li> * <p> * For information about creating failover resource record sets in a private hosted zone, see <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-private-hosted-zones.html" * >Configuring Failover in a Private Hosted Zone</a> in the <i>Amazon Route 53 Developer Guide</i>. * </p> * </li> * @return Returns a reference to this object so that method calls can be chained together. */ public ResourceRecordSet withAliasTarget(AliasTarget aliasTarget) { setAliasTarget(aliasTarget); return this; } /** * <p> * If you want Amazon Route 53 to return this resource record set in response to a DNS query only when the status of * a health check is healthy, include the <code>HealthCheckId</code> element and specify the ID of the applicable * health check. * </p> * <p> * Route 53 determines whether a resource record set is healthy based on one of the following: * </p> * <ul> * <li> * <p> * By periodically sending a request to the endpoint that is specified in the health check * </p> * </li> * <li> * <p> * By aggregating the status of a specified group of health checks (calculated health checks) * </p> * </li> * <li> * <p> * By determining the current state of a CloudWatch alarm (CloudWatch metric health checks) * </p> * </li> * </ul> * <important> * <p> * Route 53 doesn't check the health of the endpoint that is specified in the resource record set, for example, the * endpoint specified by the IP address in the <code>Value</code> element. When you add a <code>HealthCheckId</code> * element to a resource record set, Route 53 checks the health of the endpoint that you specified in the health * check. * </p> * </important> * <p> * For more information, see the following topics in the <i>Amazon Route 53 Developer Guide</i>: * </p> * <ul> * <li> * <p> * <a href= * "https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-determining-health-of-endpoints.html">How * Amazon Route 53 Determines Whether an Endpoint Is Healthy</a> * </p> * </li> * <li> * <p> * <a href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover.html">Route 53 Health Checks and * DNS Failover</a> * </p> * </li> * <li> * <p> * <a href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-private-hosted-zones.html"> * Configuring Failover in a Private Hosted Zone</a> * </p> * </li> * </ul> * <p> * <b>When to Specify HealthCheckId</b> * </p> * <p> * Specifying a value for <code>HealthCheckId</code> is useful only when Route 53 is choosing between two or more * resource record sets to respond to a DNS query, and you want Route 53 to base the choice in part on the status of * a health check. Configuring health checks makes sense only in the following configurations: * </p> * <ul> * <li> * <p> * <b>Non-alias resource record sets</b>: You're checking the health of a group of non-alias resource record sets * that have the same routing policy, name, and type (such as multiple weighted records named www.example.com with a * type of A) and you specify health check IDs for all the resource record sets. * </p> * <p> * If the health check status for a resource record set is healthy, Route 53 includes the record among the records * that it responds to DNS queries with. * </p> * <p> * If the health check status for a resource record set is unhealthy, Route 53 stops responding to DNS queries using * the value for that resource record set. * </p> * <p> * If the health check status for all resource record sets in the group is unhealthy, Route 53 considers all * resource record sets in the group healthy and responds to DNS queries accordingly. * </p> * </li> * <li> * <p> * <b>Alias resource record sets</b>: You specify the following settings: * </p> * <ul> * <li> * <p> * You set <code>EvaluateTargetHealth</code> to true for an alias resource record set in a group of resource record * sets that have the same routing policy, name, and type (such as multiple weighted records named www.example.com * with a type of A). * </p> * </li> * <li> * <p> * You configure the alias resource record set to route traffic to a non-alias resource record set in the same * hosted zone. * </p> * </li> * <li> * <p> * You specify a health check ID for the non-alias resource record set. * </p> * </li> * </ul> * <p> * If the health check status is healthy, Route 53 considers the alias resource record set to be healthy and * includes the alias record among the records that it responds to DNS queries with. * </p> * <p> * If the health check status is unhealthy, Route 53 stops responding to DNS queries using the alias resource record * set. * </p> * <note> * <p> * The alias resource record set can also route traffic to a <i>group</i> of non-alias resource record sets that * have the same routing policy, name, and type. In that configuration, associate health checks with all of the * resource record sets in the group of non-alias resource record sets. * </p> * </note></li> * </ul> * <p> * <b>Geolocation Routing</b> * </p> * <p> * For geolocation resource record sets, if an endpoint is unhealthy, Route 53 looks for a resource record set for * the larger, associated geographic region. For example, suppose you have resource record sets for a state in the * United States, for the entire United States, for North America, and a resource record set that has <code>*</code> * for <code>CountryCode</code> is <code>*</code>, which applies to all locations. If the endpoint for the state * resource record set is unhealthy, Route 53 checks for healthy resource record sets in the following order until * it finds a resource record set for which the endpoint is healthy: * </p> * <ul> * <li> * <p> * The United States * </p> * </li> * <li> * <p> * North America * </p> * </li> * <li> * <p> * The default resource record set * </p> * </li> * </ul> * <p> * <b>Specifying the Health Check Endpoint by Domain Name</b> * </p> * <p> * If your health checks specify the endpoint only by domain name, we recommend that you create a separate health * check for each endpoint. For example, create a health check for each <code>HTTP</code> server that is serving * content for <code>www.example.com</code>. For the value of <code>FullyQualifiedDomainName</code>, specify the * domain name of the server (such as <code>us-east-2-www.example.com</code>), not the name of the resource record * sets (<code>www.example.com</code>). * </p> * <important> * <p> * Health check results will be unpredictable if you do the following: * </p> * <ul> * <li> * <p> * Create a health check that has the same value for <code>FullyQualifiedDomainName</code> as the name of a resource * record set. * </p> * </li> * <li> * <p> * Associate that health check with the resource record set. * </p> * </li> * </ul> * </important> * * @param healthCheckId * If you want Amazon Route 53 to return this resource record set in response to a DNS query only when the * status of a health check is healthy, include the <code>HealthCheckId</code> element and specify the ID of * the applicable health check.</p> * <p> * Route 53 determines whether a resource record set is healthy based on one of the following: * </p> * <ul> * <li> * <p> * By periodically sending a request to the endpoint that is specified in the health check * </p> * </li> * <li> * <p> * By aggregating the status of a specified group of health checks (calculated health checks) * </p> * </li> * <li> * <p> * By determining the current state of a CloudWatch alarm (CloudWatch metric health checks) * </p> * </li> * </ul> * <important> * <p> * Route 53 doesn't check the health of the endpoint that is specified in the resource record set, for * example, the endpoint specified by the IP address in the <code>Value</code> element. When you add a * <code>HealthCheckId</code> element to a resource record set, Route 53 checks the health of the endpoint * that you specified in the health check. * </p> * </important> * <p> * For more information, see the following topics in the <i>Amazon Route 53 Developer Guide</i>: * </p> * <ul> * <li> * <p> * <a href= * "https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-determining-health-of-endpoints.html" * >How Amazon Route 53 Determines Whether an Endpoint Is Healthy</a> * </p> * </li> * <li> * <p> * <a href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover.html">Route 53 Health * Checks and DNS Failover</a> * </p> * </li> * <li> * <p> * <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-private-hosted-zones.html"> * Configuring Failover in a Private Hosted Zone</a> * </p> * </li> * </ul> * <p> * <b>When to Specify HealthCheckId</b> * </p> * <p> * Specifying a value for <code>HealthCheckId</code> is useful only when Route 53 is choosing between two or * more resource record sets to respond to a DNS query, and you want Route 53 to base the choice in part on * the status of a health check. Configuring health checks makes sense only in the following configurations: * </p> * <ul> * <li> * <p> * <b>Non-alias resource record sets</b>: You're checking the health of a group of non-alias resource record * sets that have the same routing policy, name, and type (such as multiple weighted records named * www.example.com with a type of A) and you specify health check IDs for all the resource record sets. * </p> * <p> * If the health check status for a resource record set is healthy, Route 53 includes the record among the * records that it responds to DNS queries with. * </p> * <p> * If the health check status for a resource record set is unhealthy, Route 53 stops responding to DNS * queries using the value for that resource record set. * </p> * <p> * If the health check status for all resource record sets in the group is unhealthy, Route 53 considers all * resource record sets in the group healthy and responds to DNS queries accordingly. * </p> * </li> * <li> * <p> * <b>Alias resource record sets</b>: You specify the following settings: * </p> * <ul> * <li> * <p> * You set <code>EvaluateTargetHealth</code> to true for an alias resource record set in a group of resource * record sets that have the same routing policy, name, and type (such as multiple weighted records named * www.example.com with a type of A). * </p> * </li> * <li> * <p> * You configure the alias resource record set to route traffic to a non-alias resource record set in the * same hosted zone. * </p> * </li> * <li> * <p> * You specify a health check ID for the non-alias resource record set. * </p> * </li> * </ul> * <p> * If the health check status is healthy, Route 53 considers the alias resource record set to be healthy and * includes the alias record among the records that it responds to DNS queries with. * </p> * <p> * If the health check status is unhealthy, Route 53 stops responding to DNS queries using the alias resource * record set. * </p> * <note> * <p> * The alias resource record set can also route traffic to a <i>group</i> of non-alias resource record sets * that have the same routing policy, name, and type. In that configuration, associate health checks with all * of the resource record sets in the group of non-alias resource record sets. * </p> * </note></li> * </ul> * <p> * <b>Geolocation Routing</b> * </p> * <p> * For geolocation resource record sets, if an endpoint is unhealthy, Route 53 looks for a resource record * set for the larger, associated geographic region. For example, suppose you have resource record sets for a * state in the United States, for the entire United States, for North America, and a resource record set * that has <code>*</code> for <code>CountryCode</code> is <code>*</code>, which applies to all locations. If * the endpoint for the state resource record set is unhealthy, Route 53 checks for healthy resource record * sets in the following order until it finds a resource record set for which the endpoint is healthy: * </p> * <ul> * <li> * <p> * The United States * </p> * </li> * <li> * <p> * North America * </p> * </li> * <li> * <p> * The default resource record set * </p> * </li> * </ul> * <p> * <b>Specifying the Health Check Endpoint by Domain Name</b> * </p> * <p> * If your health checks specify the endpoint only by domain name, we recommend that you create a separate * health check for each endpoint. For example, create a health check for each <code>HTTP</code> server that * is serving content for <code>www.example.com</code>. For the value of * <code>FullyQualifiedDomainName</code>, specify the domain name of the server (such as * <code>us-east-2-www.example.com</code>), not the name of the resource record sets ( * <code>www.example.com</code>). * </p> * <important> * <p> * Health check results will be unpredictable if you do the following: * </p> * <ul> * <li> * <p> * Create a health check that has the same value for <code>FullyQualifiedDomainName</code> as the name of a * resource record set. * </p> * </li> * <li> * <p> * Associate that health check with the resource record set. * </p> * </li> * </ul> */ public void setHealthCheckId(String healthCheckId) { this.healthCheckId = healthCheckId; } /** * <p> * If you want Amazon Route 53 to return this resource record set in response to a DNS query only when the status of * a health check is healthy, include the <code>HealthCheckId</code> element and specify the ID of the applicable * health check. * </p> * <p> * Route 53 determines whether a resource record set is healthy based on one of the following: * </p> * <ul> * <li> * <p> * By periodically sending a request to the endpoint that is specified in the health check * </p> * </li> * <li> * <p> * By aggregating the status of a specified group of health checks (calculated health checks) * </p> * </li> * <li> * <p> * By determining the current state of a CloudWatch alarm (CloudWatch metric health checks) * </p> * </li> * </ul> * <important> * <p> * Route 53 doesn't check the health of the endpoint that is specified in the resource record set, for example, the * endpoint specified by the IP address in the <code>Value</code> element. When you add a <code>HealthCheckId</code> * element to a resource record set, Route 53 checks the health of the endpoint that you specified in the health * check. * </p> * </important> * <p> * For more information, see the following topics in the <i>Amazon Route 53 Developer Guide</i>: * </p> * <ul> * <li> * <p> * <a href= * "https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-determining-health-of-endpoints.html">How * Amazon Route 53 Determines Whether an Endpoint Is Healthy</a> * </p> * </li> * <li> * <p> * <a href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover.html">Route 53 Health Checks and * DNS Failover</a> * </p> * </li> * <li> * <p> * <a href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-private-hosted-zones.html"> * Configuring Failover in a Private Hosted Zone</a> * </p> * </li> * </ul> * <p> * <b>When to Specify HealthCheckId</b> * </p> * <p> * Specifying a value for <code>HealthCheckId</code> is useful only when Route 53 is choosing between two or more * resource record sets to respond to a DNS query, and you want Route 53 to base the choice in part on the status of * a health check. Configuring health checks makes sense only in the following configurations: * </p> * <ul> * <li> * <p> * <b>Non-alias resource record sets</b>: You're checking the health of a group of non-alias resource record sets * that have the same routing policy, name, and type (such as multiple weighted records named www.example.com with a * type of A) and you specify health check IDs for all the resource record sets. * </p> * <p> * If the health check status for a resource record set is healthy, Route 53 includes the record among the records * that it responds to DNS queries with. * </p> * <p> * If the health check status for a resource record set is unhealthy, Route 53 stops responding to DNS queries using * the value for that resource record set. * </p> * <p> * If the health check status for all resource record sets in the group is unhealthy, Route 53 considers all * resource record sets in the group healthy and responds to DNS queries accordingly. * </p> * </li> * <li> * <p> * <b>Alias resource record sets</b>: You specify the following settings: * </p> * <ul> * <li> * <p> * You set <code>EvaluateTargetHealth</code> to true for an alias resource record set in a group of resource record * sets that have the same routing policy, name, and type (such as multiple weighted records named www.example.com * with a type of A). * </p> * </li> * <li> * <p> * You configure the alias resource record set to route traffic to a non-alias resource record set in the same * hosted zone. * </p> * </li> * <li> * <p> * You specify a health check ID for the non-alias resource record set. * </p> * </li> * </ul> * <p> * If the health check status is healthy, Route 53 considers the alias resource record set to be healthy and * includes the alias record among the records that it responds to DNS queries with. * </p> * <p> * If the health check status is unhealthy, Route 53 stops responding to DNS queries using the alias resource record * set. * </p> * <note> * <p> * The alias resource record set can also route traffic to a <i>group</i> of non-alias resource record sets that * have the same routing policy, name, and type. In that configuration, associate health checks with all of the * resource record sets in the group of non-alias resource record sets. * </p> * </note></li> * </ul> * <p> * <b>Geolocation Routing</b> * </p> * <p> * For geolocation resource record sets, if an endpoint is unhealthy, Route 53 looks for a resource record set for * the larger, associated geographic region. For example, suppose you have resource record sets for a state in the * United States, for the entire United States, for North America, and a resource record set that has <code>*</code> * for <code>CountryCode</code> is <code>*</code>, which applies to all locations. If the endpoint for the state * resource record set is unhealthy, Route 53 checks for healthy resource record sets in the following order until * it finds a resource record set for which the endpoint is healthy: * </p> * <ul> * <li> * <p> * The United States * </p> * </li> * <li> * <p> * North America * </p> * </li> * <li> * <p> * The default resource record set * </p> * </li> * </ul> * <p> * <b>Specifying the Health Check Endpoint by Domain Name</b> * </p> * <p> * If your health checks specify the endpoint only by domain name, we recommend that you create a separate health * check for each endpoint. For example, create a health check for each <code>HTTP</code> server that is serving * content for <code>www.example.com</code>. For the value of <code>FullyQualifiedDomainName</code>, specify the * domain name of the server (such as <code>us-east-2-www.example.com</code>), not the name of the resource record * sets (<code>www.example.com</code>). * </p> * <important> * <p> * Health check results will be unpredictable if you do the following: * </p> * <ul> * <li> * <p> * Create a health check that has the same value for <code>FullyQualifiedDomainName</code> as the name of a resource * record set. * </p> * </li> * <li> * <p> * Associate that health check with the resource record set. * </p> * </li> * </ul> * </important> * * @return If you want Amazon Route 53 to return this resource record set in response to a DNS query only when the * status of a health check is healthy, include the <code>HealthCheckId</code> element and specify the ID of * the applicable health check.</p> * <p> * Route 53 determines whether a resource record set is healthy based on one of the following: * </p> * <ul> * <li> * <p> * By periodically sending a request to the endpoint that is specified in the health check * </p> * </li> * <li> * <p> * By aggregating the status of a specified group of health checks (calculated health checks) * </p> * </li> * <li> * <p> * By determining the current state of a CloudWatch alarm (CloudWatch metric health checks) * </p> * </li> * </ul> * <important> * <p> * Route 53 doesn't check the health of the endpoint that is specified in the resource record set, for * example, the endpoint specified by the IP address in the <code>Value</code> element. When you add a * <code>HealthCheckId</code> element to a resource record set, Route 53 checks the health of the endpoint * that you specified in the health check. * </p> * </important> * <p> * For more information, see the following topics in the <i>Amazon Route 53 Developer Guide</i>: * </p> * <ul> * <li> * <p> * <a href= * "https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-determining-health-of-endpoints.html" * >How Amazon Route 53 Determines Whether an Endpoint Is Healthy</a> * </p> * </li> * <li> * <p> * <a href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover.html">Route 53 Health * Checks and DNS Failover</a> * </p> * </li> * <li> * <p> * <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-private-hosted-zones.html" * >Configuring Failover in a Private Hosted Zone</a> * </p> * </li> * </ul> * <p> * <b>When to Specify HealthCheckId</b> * </p> * <p> * Specifying a value for <code>HealthCheckId</code> is useful only when Route 53 is choosing between two or * more resource record sets to respond to a DNS query, and you want Route 53 to base the choice in part on * the status of a health check. Configuring health checks makes sense only in the following configurations: * </p> * <ul> * <li> * <p> * <b>Non-alias resource record sets</b>: You're checking the health of a group of non-alias resource record * sets that have the same routing policy, name, and type (such as multiple weighted records named * www.example.com with a type of A) and you specify health check IDs for all the resource record sets. * </p> * <p> * If the health check status for a resource record set is healthy, Route 53 includes the record among the * records that it responds to DNS queries with. * </p> * <p> * If the health check status for a resource record set is unhealthy, Route 53 stops responding to DNS * queries using the value for that resource record set. * </p> * <p> * If the health check status for all resource record sets in the group is unhealthy, Route 53 considers all * resource record sets in the group healthy and responds to DNS queries accordingly. * </p> * </li> * <li> * <p> * <b>Alias resource record sets</b>: You specify the following settings: * </p> * <ul> * <li> * <p> * You set <code>EvaluateTargetHealth</code> to true for an alias resource record set in a group of resource * record sets that have the same routing policy, name, and type (such as multiple weighted records named * www.example.com with a type of A). * </p> * </li> * <li> * <p> * You configure the alias resource record set to route traffic to a non-alias resource record set in the * same hosted zone. * </p> * </li> * <li> * <p> * You specify a health check ID for the non-alias resource record set. * </p> * </li> * </ul> * <p> * If the health check status is healthy, Route 53 considers the alias resource record set to be healthy and * includes the alias record among the records that it responds to DNS queries with. * </p> * <p> * If the health check status is unhealthy, Route 53 stops responding to DNS queries using the alias * resource record set. * </p> * <note> * <p> * The alias resource record set can also route traffic to a <i>group</i> of non-alias resource record sets * that have the same routing policy, name, and type. In that configuration, associate health checks with * all of the resource record sets in the group of non-alias resource record sets. * </p> * </note></li> * </ul> * <p> * <b>Geolocation Routing</b> * </p> * <p> * For geolocation resource record sets, if an endpoint is unhealthy, Route 53 looks for a resource record * set for the larger, associated geographic region. For example, suppose you have resource record sets for * a state in the United States, for the entire United States, for North America, and a resource record set * that has <code>*</code> for <code>CountryCode</code> is <code>*</code>, which applies to all locations. * If the endpoint for the state resource record set is unhealthy, Route 53 checks for healthy resource * record sets in the following order until it finds a resource record set for which the endpoint is * healthy: * </p> * <ul> * <li> * <p> * The United States * </p> * </li> * <li> * <p> * North America * </p> * </li> * <li> * <p> * The default resource record set * </p> * </li> * </ul> * <p> * <b>Specifying the Health Check Endpoint by Domain Name</b> * </p> * <p> * If your health checks specify the endpoint only by domain name, we recommend that you create a separate * health check for each endpoint. For example, create a health check for each <code>HTTP</code> server that * is serving content for <code>www.example.com</code>. For the value of * <code>FullyQualifiedDomainName</code>, specify the domain name of the server (such as * <code>us-east-2-www.example.com</code>), not the name of the resource record sets ( * <code>www.example.com</code>). * </p> * <important> * <p> * Health check results will be unpredictable if you do the following: * </p> * <ul> * <li> * <p> * Create a health check that has the same value for <code>FullyQualifiedDomainName</code> as the name of a * resource record set. * </p> * </li> * <li> * <p> * Associate that health check with the resource record set. * </p> * </li> * </ul> */ public String getHealthCheckId() { return this.healthCheckId; } /** * <p> * If you want Amazon Route 53 to return this resource record set in response to a DNS query only when the status of * a health check is healthy, include the <code>HealthCheckId</code> element and specify the ID of the applicable * health check. * </p> * <p> * Route 53 determines whether a resource record set is healthy based on one of the following: * </p> * <ul> * <li> * <p> * By periodically sending a request to the endpoint that is specified in the health check * </p> * </li> * <li> * <p> * By aggregating the status of a specified group of health checks (calculated health checks) * </p> * </li> * <li> * <p> * By determining the current state of a CloudWatch alarm (CloudWatch metric health checks) * </p> * </li> * </ul> * <important> * <p> * Route 53 doesn't check the health of the endpoint that is specified in the resource record set, for example, the * endpoint specified by the IP address in the <code>Value</code> element. When you add a <code>HealthCheckId</code> * element to a resource record set, Route 53 checks the health of the endpoint that you specified in the health * check. * </p> * </important> * <p> * For more information, see the following topics in the <i>Amazon Route 53 Developer Guide</i>: * </p> * <ul> * <li> * <p> * <a href= * "https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-determining-health-of-endpoints.html">How * Amazon Route 53 Determines Whether an Endpoint Is Healthy</a> * </p> * </li> * <li> * <p> * <a href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover.html">Route 53 Health Checks and * DNS Failover</a> * </p> * </li> * <li> * <p> * <a href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-private-hosted-zones.html"> * Configuring Failover in a Private Hosted Zone</a> * </p> * </li> * </ul> * <p> * <b>When to Specify HealthCheckId</b> * </p> * <p> * Specifying a value for <code>HealthCheckId</code> is useful only when Route 53 is choosing between two or more * resource record sets to respond to a DNS query, and you want Route 53 to base the choice in part on the status of * a health check. Configuring health checks makes sense only in the following configurations: * </p> * <ul> * <li> * <p> * <b>Non-alias resource record sets</b>: You're checking the health of a group of non-alias resource record sets * that have the same routing policy, name, and type (such as multiple weighted records named www.example.com with a * type of A) and you specify health check IDs for all the resource record sets. * </p> * <p> * If the health check status for a resource record set is healthy, Route 53 includes the record among the records * that it responds to DNS queries with. * </p> * <p> * If the health check status for a resource record set is unhealthy, Route 53 stops responding to DNS queries using * the value for that resource record set. * </p> * <p> * If the health check status for all resource record sets in the group is unhealthy, Route 53 considers all * resource record sets in the group healthy and responds to DNS queries accordingly. * </p> * </li> * <li> * <p> * <b>Alias resource record sets</b>: You specify the following settings: * </p> * <ul> * <li> * <p> * You set <code>EvaluateTargetHealth</code> to true for an alias resource record set in a group of resource record * sets that have the same routing policy, name, and type (such as multiple weighted records named www.example.com * with a type of A). * </p> * </li> * <li> * <p> * You configure the alias resource record set to route traffic to a non-alias resource record set in the same * hosted zone. * </p> * </li> * <li> * <p> * You specify a health check ID for the non-alias resource record set. * </p> * </li> * </ul> * <p> * If the health check status is healthy, Route 53 considers the alias resource record set to be healthy and * includes the alias record among the records that it responds to DNS queries with. * </p> * <p> * If the health check status is unhealthy, Route 53 stops responding to DNS queries using the alias resource record * set. * </p> * <note> * <p> * The alias resource record set can also route traffic to a <i>group</i> of non-alias resource record sets that * have the same routing policy, name, and type. In that configuration, associate health checks with all of the * resource record sets in the group of non-alias resource record sets. * </p> * </note></li> * </ul> * <p> * <b>Geolocation Routing</b> * </p> * <p> * For geolocation resource record sets, if an endpoint is unhealthy, Route 53 looks for a resource record set for * the larger, associated geographic region. For example, suppose you have resource record sets for a state in the * United States, for the entire United States, for North America, and a resource record set that has <code>*</code> * for <code>CountryCode</code> is <code>*</code>, which applies to all locations. If the endpoint for the state * resource record set is unhealthy, Route 53 checks for healthy resource record sets in the following order until * it finds a resource record set for which the endpoint is healthy: * </p> * <ul> * <li> * <p> * The United States * </p> * </li> * <li> * <p> * North America * </p> * </li> * <li> * <p> * The default resource record set * </p> * </li> * </ul> * <p> * <b>Specifying the Health Check Endpoint by Domain Name</b> * </p> * <p> * If your health checks specify the endpoint only by domain name, we recommend that you create a separate health * check for each endpoint. For example, create a health check for each <code>HTTP</code> server that is serving * content for <code>www.example.com</code>. For the value of <code>FullyQualifiedDomainName</code>, specify the * domain name of the server (such as <code>us-east-2-www.example.com</code>), not the name of the resource record * sets (<code>www.example.com</code>). * </p> * <important> * <p> * Health check results will be unpredictable if you do the following: * </p> * <ul> * <li> * <p> * Create a health check that has the same value for <code>FullyQualifiedDomainName</code> as the name of a resource * record set. * </p> * </li> * <li> * <p> * Associate that health check with the resource record set. * </p> * </li> * </ul> * </important> * * @param healthCheckId * If you want Amazon Route 53 to return this resource record set in response to a DNS query only when the * status of a health check is healthy, include the <code>HealthCheckId</code> element and specify the ID of * the applicable health check.</p> * <p> * Route 53 determines whether a resource record set is healthy based on one of the following: * </p> * <ul> * <li> * <p> * By periodically sending a request to the endpoint that is specified in the health check * </p> * </li> * <li> * <p> * By aggregating the status of a specified group of health checks (calculated health checks) * </p> * </li> * <li> * <p> * By determining the current state of a CloudWatch alarm (CloudWatch metric health checks) * </p> * </li> * </ul> * <important> * <p> * Route 53 doesn't check the health of the endpoint that is specified in the resource record set, for * example, the endpoint specified by the IP address in the <code>Value</code> element. When you add a * <code>HealthCheckId</code> element to a resource record set, Route 53 checks the health of the endpoint * that you specified in the health check. * </p> * </important> * <p> * For more information, see the following topics in the <i>Amazon Route 53 Developer Guide</i>: * </p> * <ul> * <li> * <p> * <a href= * "https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-determining-health-of-endpoints.html" * >How Amazon Route 53 Determines Whether an Endpoint Is Healthy</a> * </p> * </li> * <li> * <p> * <a href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover.html">Route 53 Health * Checks and DNS Failover</a> * </p> * </li> * <li> * <p> * <a * href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-private-hosted-zones.html"> * Configuring Failover in a Private Hosted Zone</a> * </p> * </li> * </ul> * <p> * <b>When to Specify HealthCheckId</b> * </p> * <p> * Specifying a value for <code>HealthCheckId</code> is useful only when Route 53 is choosing between two or * more resource record sets to respond to a DNS query, and you want Route 53 to base the choice in part on * the status of a health check. Configuring health checks makes sense only in the following configurations: * </p> * <ul> * <li> * <p> * <b>Non-alias resource record sets</b>: You're checking the health of a group of non-alias resource record * sets that have the same routing policy, name, and type (such as multiple weighted records named * www.example.com with a type of A) and you specify health check IDs for all the resource record sets. * </p> * <p> * If the health check status for a resource record set is healthy, Route 53 includes the record among the * records that it responds to DNS queries with. * </p> * <p> * If the health check status for a resource record set is unhealthy, Route 53 stops responding to DNS * queries using the value for that resource record set. * </p> * <p> * If the health check status for all resource record sets in the group is unhealthy, Route 53 considers all * resource record sets in the group healthy and responds to DNS queries accordingly. * </p> * </li> * <li> * <p> * <b>Alias resource record sets</b>: You specify the following settings: * </p> * <ul> * <li> * <p> * You set <code>EvaluateTargetHealth</code> to true for an alias resource record set in a group of resource * record sets that have the same routing policy, name, and type (such as multiple weighted records named * www.example.com with a type of A). * </p> * </li> * <li> * <p> * You configure the alias resource record set to route traffic to a non-alias resource record set in the * same hosted zone. * </p> * </li> * <li> * <p> * You specify a health check ID for the non-alias resource record set. * </p> * </li> * </ul> * <p> * If the health check status is healthy, Route 53 considers the alias resource record set to be healthy and * includes the alias record among the records that it responds to DNS queries with. * </p> * <p> * If the health check status is unhealthy, Route 53 stops responding to DNS queries using the alias resource * record set. * </p> * <note> * <p> * The alias resource record set can also route traffic to a <i>group</i> of non-alias resource record sets * that have the same routing policy, name, and type. In that configuration, associate health checks with all * of the resource record sets in the group of non-alias resource record sets. * </p> * </note></li> * </ul> * <p> * <b>Geolocation Routing</b> * </p> * <p> * For geolocation resource record sets, if an endpoint is unhealthy, Route 53 looks for a resource record * set for the larger, associated geographic region. For example, suppose you have resource record sets for a * state in the United States, for the entire United States, for North America, and a resource record set * that has <code>*</code> for <code>CountryCode</code> is <code>*</code>, which applies to all locations. If * the endpoint for the state resource record set is unhealthy, Route 53 checks for healthy resource record * sets in the following order until it finds a resource record set for which the endpoint is healthy: * </p> * <ul> * <li> * <p> * The United States * </p> * </li> * <li> * <p> * North America * </p> * </li> * <li> * <p> * The default resource record set * </p> * </li> * </ul> * <p> * <b>Specifying the Health Check Endpoint by Domain Name</b> * </p> * <p> * If your health checks specify the endpoint only by domain name, we recommend that you create a separate * health check for each endpoint. For example, create a health check for each <code>HTTP</code> server that * is serving content for <code>www.example.com</code>. For the value of * <code>FullyQualifiedDomainName</code>, specify the domain name of the server (such as * <code>us-east-2-www.example.com</code>), not the name of the resource record sets ( * <code>www.example.com</code>). * </p> * <important> * <p> * Health check results will be unpredictable if you do the following: * </p> * <ul> * <li> * <p> * Create a health check that has the same value for <code>FullyQualifiedDomainName</code> as the name of a * resource record set. * </p> * </li> * <li> * <p> * Associate that health check with the resource record set. * </p> * </li> * </ul> * @return Returns a reference to this object so that method calls can be chained together. */ public ResourceRecordSet withHealthCheckId(String healthCheckId) { setHealthCheckId(healthCheckId); return this; } /** * <p> * When you create a traffic policy instance, Amazon Route 53 automatically creates a resource record set. * <code>TrafficPolicyInstanceId</code> is the ID of the traffic policy instance that Route 53 created this resource * record set for. * </p> * <important> * <p> * To delete the resource record set that is associated with a traffic policy instance, use * <code>DeleteTrafficPolicyInstance</code>. Route 53 will delete the resource record set automatically. If you * delete the resource record set by using <code>ChangeResourceRecordSets</code>, Route 53 doesn't automatically * delete the traffic policy instance, and you'll continue to be charged for it even though it's no longer in use. * </p> * </important> * * @param trafficPolicyInstanceId * When you create a traffic policy instance, Amazon Route 53 automatically creates a resource record set. * <code>TrafficPolicyInstanceId</code> is the ID of the traffic policy instance that Route 53 created this * resource record set for.</p> <important> * <p> * To delete the resource record set that is associated with a traffic policy instance, use * <code>DeleteTrafficPolicyInstance</code>. Route 53 will delete the resource record set automatically. If * you delete the resource record set by using <code>ChangeResourceRecordSets</code>, Route 53 doesn't * automatically delete the traffic policy instance, and you'll continue to be charged for it even though * it's no longer in use. * </p> */ public void setTrafficPolicyInstanceId(String trafficPolicyInstanceId) { this.trafficPolicyInstanceId = trafficPolicyInstanceId; } /** * <p> * When you create a traffic policy instance, Amazon Route 53 automatically creates a resource record set. * <code>TrafficPolicyInstanceId</code> is the ID of the traffic policy instance that Route 53 created this resource * record set for. * </p> * <important> * <p> * To delete the resource record set that is associated with a traffic policy instance, use * <code>DeleteTrafficPolicyInstance</code>. Route 53 will delete the resource record set automatically. If you * delete the resource record set by using <code>ChangeResourceRecordSets</code>, Route 53 doesn't automatically * delete the traffic policy instance, and you'll continue to be charged for it even though it's no longer in use. * </p> * </important> * * @return When you create a traffic policy instance, Amazon Route 53 automatically creates a resource record set. * <code>TrafficPolicyInstanceId</code> is the ID of the traffic policy instance that Route 53 created this * resource record set for.</p> <important> * <p> * To delete the resource record set that is associated with a traffic policy instance, use * <code>DeleteTrafficPolicyInstance</code>. Route 53 will delete the resource record set automatically. If * you delete the resource record set by using <code>ChangeResourceRecordSets</code>, Route 53 doesn't * automatically delete the traffic policy instance, and you'll continue to be charged for it even though * it's no longer in use. * </p> */ public String getTrafficPolicyInstanceId() { return this.trafficPolicyInstanceId; } /** * <p> * When you create a traffic policy instance, Amazon Route 53 automatically creates a resource record set. * <code>TrafficPolicyInstanceId</code> is the ID of the traffic policy instance that Route 53 created this resource * record set for. * </p> * <important> * <p> * To delete the resource record set that is associated with a traffic policy instance, use * <code>DeleteTrafficPolicyInstance</code>. Route 53 will delete the resource record set automatically. If you * delete the resource record set by using <code>ChangeResourceRecordSets</code>, Route 53 doesn't automatically * delete the traffic policy instance, and you'll continue to be charged for it even though it's no longer in use. * </p> * </important> * * @param trafficPolicyInstanceId * When you create a traffic policy instance, Amazon Route 53 automatically creates a resource record set. * <code>TrafficPolicyInstanceId</code> is the ID of the traffic policy instance that Route 53 created this * resource record set for.</p> <important> * <p> * To delete the resource record set that is associated with a traffic policy instance, use * <code>DeleteTrafficPolicyInstance</code>. Route 53 will delete the resource record set automatically. If * you delete the resource record set by using <code>ChangeResourceRecordSets</code>, Route 53 doesn't * automatically delete the traffic policy instance, and you'll continue to be charged for it even though * it's no longer in use. * </p> * @return Returns a reference to this object so that method calls can be chained together. */ public ResourceRecordSet withTrafficPolicyInstanceId(String trafficPolicyInstanceId) { setTrafficPolicyInstanceId(trafficPolicyInstanceId); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getName() != null) sb.append("Name: ").append(getName()).append(","); if (getType() != null) sb.append("Type: ").append(getType()).append(","); if (getSetIdentifier() != null) sb.append("SetIdentifier: ").append(getSetIdentifier()).append(","); if (getWeight() != null) sb.append("Weight: ").append(getWeight()).append(","); if (getRegion() != null) sb.append("Region: ").append(getRegion()).append(","); if (getGeoLocation() != null) sb.append("GeoLocation: ").append(getGeoLocation()).append(","); if (getFailover() != null) sb.append("Failover: ").append(getFailover()).append(","); if (getMultiValueAnswer() != null) sb.append("MultiValueAnswer: ").append(getMultiValueAnswer()).append(","); if (getTTL() != null) sb.append("TTL: ").append(getTTL()).append(","); if (getResourceRecords() != null) sb.append("ResourceRecords: ").append(getResourceRecords()).append(","); if (getAliasTarget() != null) sb.append("AliasTarget: ").append(getAliasTarget()).append(","); if (getHealthCheckId() != null) sb.append("HealthCheckId: ").append(getHealthCheckId()).append(","); if (getTrafficPolicyInstanceId() != null) sb.append("TrafficPolicyInstanceId: ").append(getTrafficPolicyInstanceId()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ResourceRecordSet == false) return false; ResourceRecordSet other = (ResourceRecordSet) obj; if (other.getName() == null ^ this.getName() == null) return false; if (other.getName() != null && other.getName().equals(this.getName()) == false) return false; if (other.getType() == null ^ this.getType() == null) return false; if (other.getType() != null && other.getType().equals(this.getType()) == false) return false; if (other.getSetIdentifier() == null ^ this.getSetIdentifier() == null) return false; if (other.getSetIdentifier() != null && other.getSetIdentifier().equals(this.getSetIdentifier()) == false) return false; if (other.getWeight() == null ^ this.getWeight() == null) return false; if (other.getWeight() != null && other.getWeight().equals(this.getWeight()) == false) return false; if (other.getRegion() == null ^ this.getRegion() == null) return false; if (other.getRegion() != null && other.getRegion().equals(this.getRegion()) == false) return false; if (other.getGeoLocation() == null ^ this.getGeoLocation() == null) return false; if (other.getGeoLocation() != null && other.getGeoLocation().equals(this.getGeoLocation()) == false) return false; if (other.getFailover() == null ^ this.getFailover() == null) return false; if (other.getFailover() != null && other.getFailover().equals(this.getFailover()) == false) return false; if (other.getMultiValueAnswer() == null ^ this.getMultiValueAnswer() == null) return false; if (other.getMultiValueAnswer() != null && other.getMultiValueAnswer().equals(this.getMultiValueAnswer()) == false) return false; if (other.getTTL() == null ^ this.getTTL() == null) return false; if (other.getTTL() != null && other.getTTL().equals(this.getTTL()) == false) return false; if (other.getResourceRecords() == null ^ this.getResourceRecords() == null) return false; if (other.getResourceRecords() != null && other.getResourceRecords().equals(this.getResourceRecords()) == false) return false; if (other.getAliasTarget() == null ^ this.getAliasTarget() == null) return false; if (other.getAliasTarget() != null && other.getAliasTarget().equals(this.getAliasTarget()) == false) return false; if (other.getHealthCheckId() == null ^ this.getHealthCheckId() == null) return false; if (other.getHealthCheckId() != null && other.getHealthCheckId().equals(this.getHealthCheckId()) == false) return false; if (other.getTrafficPolicyInstanceId() == null ^ this.getTrafficPolicyInstanceId() == null) return false; if (other.getTrafficPolicyInstanceId() != null && other.getTrafficPolicyInstanceId().equals(this.getTrafficPolicyInstanceId()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode()); hashCode = prime * hashCode + ((getType() == null) ? 0 : getType().hashCode()); hashCode = prime * hashCode + ((getSetIdentifier() == null) ? 0 : getSetIdentifier().hashCode()); hashCode = prime * hashCode + ((getWeight() == null) ? 0 : getWeight().hashCode()); hashCode = prime * hashCode + ((getRegion() == null) ? 0 : getRegion().hashCode()); hashCode = prime * hashCode + ((getGeoLocation() == null) ? 0 : getGeoLocation().hashCode()); hashCode = prime * hashCode + ((getFailover() == null) ? 0 : getFailover().hashCode()); hashCode = prime * hashCode + ((getMultiValueAnswer() == null) ? 0 : getMultiValueAnswer().hashCode()); hashCode = prime * hashCode + ((getTTL() == null) ? 0 : getTTL().hashCode()); hashCode = prime * hashCode + ((getResourceRecords() == null) ? 0 : getResourceRecords().hashCode()); hashCode = prime * hashCode + ((getAliasTarget() == null) ? 0 : getAliasTarget().hashCode()); hashCode = prime * hashCode + ((getHealthCheckId() == null) ? 0 : getHealthCheckId().hashCode()); hashCode = prime * hashCode + ((getTrafficPolicyInstanceId() == null) ? 0 : getTrafficPolicyInstanceId().hashCode()); return hashCode; } @Override public ResourceRecordSet clone() { try { return (ResourceRecordSet) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
116,803
868
from .racecar import Racecar
7
1,086
#pragma once #include <string> namespace Documentation { class CppReference { public: static std::string get_url(const std::string &symbol) noexcept; }; }
57
421
<reponame>YaronWong/AndroidLocalizePlugin package com.airsaid.localization.utils; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; /** * @author airsaid */ class TextUtilTest { @Test void isEmptyOrSpacesLineBreak() { assertTrue(TextUtil.isEmptyOrSpacesLineBreak(null)); assertTrue(TextUtil.isEmptyOrSpacesLineBreak("")); assertTrue(TextUtil.isEmptyOrSpacesLineBreak(" ")); assertTrue(TextUtil.isEmptyOrSpacesLineBreak(" ")); assertTrue(TextUtil.isEmptyOrSpacesLineBreak("\r")); assertTrue(TextUtil.isEmptyOrSpacesLineBreak("\n")); assertTrue(TextUtil.isEmptyOrSpacesLineBreak("\r\n")); assertTrue(TextUtil.isEmptyOrSpacesLineBreak(" \r\n ")); assertTrue(TextUtil.isEmptyOrSpacesLineBreak(" \r \n ")); assertFalse(TextUtil.isEmptyOrSpacesLineBreak("text")); assertFalse(TextUtil.isEmptyOrSpacesLineBreak("text ")); assertFalse(TextUtil.isEmptyOrSpacesLineBreak(" text")); assertFalse(TextUtil.isEmptyOrSpacesLineBreak(" text ")); assertFalse(TextUtil.isEmptyOrSpacesLineBreak("\ntext")); assertFalse(TextUtil.isEmptyOrSpacesLineBreak("text\n")); assertFalse(TextUtil.isEmptyOrSpacesLineBreak("\rtext")); assertFalse(TextUtil.isEmptyOrSpacesLineBreak("text\r")); assertFalse(TextUtil.isEmptyOrSpacesLineBreak("\r\ntext\r\n")); } }
520
416
package org.simpleflatmapper.map.setter; import org.simpleflatmapper.converter.Context; public interface FloatContextualSetter<T> { void setFloat(T target, float value, Context context) throws Exception; }
70
777
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/metrics/metrics_reporting_default_state.h" #include "components/metrics/metrics_pref_names.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" namespace metrics { void RegisterMetricsReportingStatePrefs(PrefRegistrySimple* registry) { registry->RegisterIntegerPref(prefs::kMetricsDefaultOptIn, EnableMetricsDefault::DEFAULT_UNKNOWN); } void RecordMetricsReportingDefaultState(PrefService* local_state, EnableMetricsDefault default_state) { DCHECK_EQ(GetMetricsReportingDefaultState(local_state), EnableMetricsDefault::DEFAULT_UNKNOWN); local_state->SetInteger(prefs::kMetricsDefaultOptIn, default_state); } EnableMetricsDefault GetMetricsReportingDefaultState(PrefService* local_state) { return static_cast<EnableMetricsDefault>( local_state->GetInteger(prefs::kMetricsDefaultOptIn)); } } // namespace metrics
407
346
#ifndef MAINMENUSCREEN_H #define MAINMENUSCREEN_H #include "ScreenIDs.h" void InitMainMenu(void); void ClearMainMenu(void); ScreenID MainMenuScreenHandle(void); #endif
66
344
<gh_stars>100-1000 package com.clickhouse.client.stream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.EOFException; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; import java.math.BigInteger; import java.net.URL; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collections; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiFunction; import com.clickhouse.client.ClickHouseByteBuffer; import com.clickhouse.client.ClickHouseInputStream; import com.clickhouse.client.ClickHouseOutputStream; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class InputStreamImplTest { static class CustomReader { private final byte[] delimiters; CustomReader(byte... delimiters) { this.delimiters = delimiters; } int read(byte[] bytes, int position, int limit) { int count = 0; for (int i = position; i < limit; i++) { byte b = bytes[i]; count++; for (byte d : delimiters) { if (b == d) { return count; } } } return -1; } } protected byte[] toByteArray(int... bytes) { byte[] b = ClickHouseByteBuffer.EMPTY_BYTES; if (bytes != null) { b = new byte[bytes.length]; for (int i = 0; i < b.length; i++) { b[i] = (byte) (0xFF & bytes[i]); } } return b; } ClickHouseInputStream generateInputStream(Boolean closed, int[] bytes) { if (closed || (bytes != null && bytes.length == 0)) { return new IterableByteArrayInputStream(Collections.emptyList(), null); } else if (bytes == null) { return new IterableByteArrayInputStream(null, null); } else { return new IterableByteArrayInputStream(Arrays.asList(new byte[][] { toByteArray(bytes) }), null); } } @DataProvider(name = "streamProvider") private Object[][] getInputStreamProvider() { return new Object[][] { new BiFunction[] { (c, b) -> { boolean closed = (boolean) c; int[] bytes = (int[]) b; IterableByteArrayInputStream in; if (bytes == null) { in = new IterableByteArrayInputStream(null, null); } else if (bytes.length == 0) { in = new IterableByteArrayInputStream(Collections.emptyList(), null); } else { in = new IterableByteArrayInputStream( Arrays.asList(new byte[][] { toByteArray(bytes) }), null); } if (closed) { try { in.close(); } catch (IOException e) { // ignore } } return in; }, } }; } private File generateTempFile(int... bytes) { try { File f = File.createTempFile("test_", "_input_stream"); if (bytes != null && bytes.length > 0) { try (FileOutputStream out = new FileOutputStream(f)) { for (int b : bytes) { out.write(b); } out.flush(); } } return f; } catch (IOException e) { throw new UncheckedIOException(e); } } private URL generateTempUrl(int... bytes) { try { return generateTempFile(bytes).toURI().toURL(); } catch (IOException e) { throw new UncheckedIOException(e); } } @DataProvider(name = "emptyInputStreamProvider") private Object[][] getEmptyInputStreams() { return new Object[][] { // empty input stream { EmptyInputStream.INSTANCE }, { ClickHouseInputStream.empty() }, // custom objects { ClickHouseInputStream.of((Object[]) null, Object.class, o -> new byte[] { 1, 2, 3 }, null) }, { ClickHouseInputStream.of((Iterable<Object>) null, Object.class, o -> new byte[] { 1, 2, 3 }, null) }, { ClickHouseInputStream.of(new Object[0], Object.class, o -> new byte[] { 1, 2, 3 }, null) }, { ClickHouseInputStream.of(Collections.emptyList(), Object.class, o -> new byte[] { 1, 2, 3 }, null) }, { ClickHouseInputStream.of(Arrays.asList(1, 2, 3, 4, 5), Integer.class, i -> new byte[0], null) }, // bytes { ClickHouseInputStream.of(new byte[0][]) }, { ClickHouseInputStream.of(new byte[0]) }, { ClickHouseInputStream.of((byte[]) null) }, { ClickHouseInputStream.of(new byte[0], null) }, { ClickHouseInputStream.of(null, new byte[0]) }, { ClickHouseInputStream.of(new byte[0], new byte[0]) }, { ClickHouseInputStream.of((byte[]) null, (byte[]) null) }, // byte buffer { ClickHouseInputStream.of(new ByteBuffer[0]) }, { ClickHouseInputStream.of(ByteBuffer.wrap(new byte[0])) }, { ClickHouseInputStream.of((ByteBuffer) null) }, { ClickHouseInputStream.of(ByteBuffer.wrap(new byte[0]), null) }, { ClickHouseInputStream.of(null, ByteBuffer.wrap(new byte[0])) }, { ClickHouseInputStream.of(ByteBuffer.wrap(new byte[0]), ByteBuffer.wrap(new byte[0])) }, { ClickHouseInputStream.of((ByteBuffer) null, (ByteBuffer) null) }, // files { ClickHouseInputStream.of(new File[0]) }, { ClickHouseInputStream.of(generateTempFile()) }, { ClickHouseInputStream.of((File) null) }, { ClickHouseInputStream.of(generateTempFile(), null) }, { ClickHouseInputStream.of(null, generateTempFile()) }, { ClickHouseInputStream.of(generateTempFile(), generateTempFile()) }, { ClickHouseInputStream.of((File) null, (File) null) }, // input streams { ClickHouseInputStream.of(new ByteArrayInputStream[0]) }, { ClickHouseInputStream.of(new ByteArrayInputStream(new byte[0])) }, { ClickHouseInputStream.of((ByteArrayInputStream) null) }, { ClickHouseInputStream.of(new ByteArrayInputStream(new byte[0]), null) }, { ClickHouseInputStream.of(null, new ByteArrayInputStream(new byte[0])) }, { ClickHouseInputStream.of(new ByteArrayInputStream(new byte[0]), new ByteArrayInputStream(new byte[0])) }, { ClickHouseInputStream.of((ByteArrayInputStream) null, (ByteArrayInputStream) null) }, // strings { ClickHouseInputStream.of(new String[0]) }, { ClickHouseInputStream.of("") }, { ClickHouseInputStream.of((String) null) }, { ClickHouseInputStream.of("", null) }, { ClickHouseInputStream.of(null, "") }, { ClickHouseInputStream.of("", "") }, { ClickHouseInputStream.of((String) null, (String) null) }, // urls { ClickHouseInputStream.of(new URL[0]) }, { ClickHouseInputStream.of(generateTempUrl()) }, { ClickHouseInputStream.of((URL) null) }, { ClickHouseInputStream.of(generateTempUrl(), null) }, { ClickHouseInputStream.of(null, generateTempUrl()) }, { ClickHouseInputStream.of(generateTempUrl(), generateTempUrl()) }, { ClickHouseInputStream.of((URL) null, (URL) null) }, }; } @DataProvider(name = "inputStreamProvider") private Object[][] getInputStreamsWithData() { return new Object[][] { // "efghip" -> 0x65 0x66 0x67 0x68 0x69 0x70 // custom objects { ClickHouseInputStream.of(new BigInteger[] { BigInteger.ZERO, BigInteger.ONE }, BigInteger.class, b -> b == BigInteger.ZERO ? new byte[] { 0x65, 0x66 } : new byte[] { 0x67, 0x68, 0x69, 0x70 }, null) }, { ClickHouseInputStream.of(Collections.singletonList(new Object()), Object.class, o -> new byte[] { 0x65, 0x66, 0x67, 0x68, 0x69, 0x70 }, null) }, // bytes { ClickHouseInputStream .of(new byte[][] { { 0x65, 0x66, 0x67, 0x68, 0x69, 0x70 } }) }, { ClickHouseInputStream .of(new byte[][] { { 0x65 }, { 0x66 }, { 0x67 }, { 0x68 }, { 0x69 }, { 0x70 } }) }, { ClickHouseInputStream .of(new byte[][] { { 0x65 }, null, { 0x66, 0x67, 0x68 }, new byte[0], { 0x69, 0x70 } }) }, // byte buffer { ClickHouseInputStream .of(new ByteBuffer[] { ByteBuffer.wrap(new byte[] { 0x65, 0x66, 0x67, 0x68, 0x69, 0x70 }) }) }, { ClickHouseInputStream .of(new ByteBuffer[] { ByteBuffer .wrap(new byte[] { 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x70, 0x71 }, 1, 6) }) }, { ClickHouseInputStream .of(new ByteBuffer[] { ByteBuffer.wrap(new byte[] { 0x65 }), ByteBuffer.wrap(new byte[] { 0x66 }), ByteBuffer.wrap(new byte[] { 0x67 }), ByteBuffer.wrap(new byte[] { 0x68 }), ByteBuffer.wrap(new byte[] { 0x69 }), ByteBuffer.wrap(new byte[] { 0x70 }) }) }, { ClickHouseInputStream .of(new ByteBuffer[] { ByteBuffer.wrap(new byte[] { 0x64, 0x65, 0x66 }, 1, 1), ByteBuffer.wrap(new byte[] { 0x64, 0x65, 0x66, 0x67 }, 2, 2), ByteBuffer.wrap(new byte[] { 0x68, 0x69, 0x70, 0x71 }, 0, 3) }) }, // files { ClickHouseInputStream.of(generateTempFile(0x65, 0x66, 0x67, 0x68, 0x69, 0x70)) }, { ClickHouseInputStream.of(generateTempFile(0x65), generateTempFile(0x66), generateTempFile(0x67), generateTempFile(0x68), generateTempFile(0x69), generateTempFile(0x70)) }, { ClickHouseInputStream.of(generateTempFile(0x65), generateTempFile(0x66, 0x67), generateTempFile(0x68, 0x69, 0x70)) }, // input streams { ClickHouseInputStream .of(new InputStream[] { new ByteArrayInputStream(new byte[] { 0x65, 0x66, 0x67, 0x68, 0x69, 0x70 }) }) }, { ClickHouseInputStream .of(new InputStream[] { new ByteArrayInputStream(new byte[] { 0x65 }), new ByteArrayInputStream(new byte[] { 0x66 }), new ByteArrayInputStream(new byte[] { 0x67 }), new ByteArrayInputStream(new byte[] { 0x68 }), new ByteArrayInputStream(new byte[] { 0x69 }), new ByteArrayInputStream(new byte[] { 0x70 }) }) }, { ClickHouseInputStream .of(new InputStream[] { new ByteArrayInputStream(new byte[] { 0x65 }), null, new ByteArrayInputStream(new byte[] { 0x66, 0x67, 0x68 }), null, new ByteArrayInputStream(new byte[] { 0x69, 0x70 }) }) }, // strings { ClickHouseInputStream.of("efghip") }, { ClickHouseInputStream.of("e", "fg", "hip") }, { ClickHouseInputStream.of("", "efg", "h", "ip", "") }, // urls { ClickHouseInputStream.of(generateTempUrl(0x65, 0x66, 0x67, 0x68, 0x69, 0x70)) }, { ClickHouseInputStream.of(generateTempUrl(0x65), generateTempUrl(0x66), generateTempUrl(0x67), generateTempUrl(0x68), generateTempUrl(0x69), generateTempUrl(0x70)) }, { ClickHouseInputStream.of(generateTempUrl(0x65, 0x66, 0x67), generateTempUrl(0x68, 0x69), generateTempUrl(0x70)) }, }; } @DataProvider(name = "streamWithData") private Object[][] getInputStreamWithData() { return new Object[][] { new Object[] { new WrappedInputStream( new ByteArrayInputStream(new byte[] { -1, 1, 2, 3, 4, 5, 6 }, 1, 5), 1, null) }, new Object[] { new IterableByteArrayInputStream( Arrays.asList(new byte[] { 1 }, new byte[] { 2, 3, 4 }, new byte[] { 5 }), null) }, new Object[] { new IterableByteArrayInputStream( Arrays.asList(null, new byte[0], new byte[] { 1, 2, 3 }, new byte[0], null, new byte[] { 4, 5 }, null, new byte[0], null), null) }, new Object[] { new IterableByteBufferInputStream( Arrays.asList(null, ByteBuffer.allocateDirect(0), ByteBuffer.wrap(new byte[] { -1, 1, 2, 3, -4 }, 1, 3), ByteBuffer.allocate(0), null, ByteBuffer.wrap(new byte[] { 4, 5 }), null, ByteBuffer.allocate(0), null), null) } }; } @Test(dataProvider = "emptyInputStreamProvider", groups = { "unit" }) public void testEmptyInputStream(ClickHouseInputStream in) throws IOException { Assert.assertFalse(in.isClosed(), "Should be openned for read by default"); Assert.assertEquals(in.read(), -1); Assert.assertEquals(in.read(new byte[0], 0, 0), 0); Assert.assertEquals(in.read(new byte[2], 1, 1), -1); Assert.assertEquals(in.read(new byte[0]), 0); Assert.assertEquals(in.read(new byte[1]), -1); Assert.assertEquals(in.skip(0L), 0L); Assert.assertEquals(in.skip(1L), 0L); Assert.assertEquals(in.skip(Long.MAX_VALUE), 0L); Assert.assertEquals(in.peek(), -1); Assert.assertEquals(in.available(), 0); Assert.assertEquals(in.peek(), -1); Assert.assertEquals(in.available(), 0); Assert.assertFalse(in.isClosed(), "Should be still openned"); in.close(); if (in == EmptyInputStream.INSTANCE) { Assert.assertFalse(in.isClosed(), "EmptyInputStream can never be closed"); } else { Assert.assertTrue(in.isClosed(), "Should have been closed"); } } @Test(dataProvider = "inputStreamProvider", groups = { "unit" }) public void testReadFromInputStream(ClickHouseInputStream in) throws IOException { Assert.assertFalse(in.isClosed(), "Should be openned for read by default"); while (in.peek() != -1) { Assert.assertTrue(in.available() > 0, "Should have more to read"); Assert.assertEquals(in.peek(), in.read()); } Assert.assertEquals(in.available(), 0); Assert.assertEquals(in.read(), -1); Assert.assertFalse(in.isClosed(), "Should be still openning"); in.close(); Assert.assertTrue(in.isClosed(), "Should have been closed"); } @Test(dataProvider = "inputStreamProvider", groups = { "unit" }) public void testReadAllFromInputStream(ClickHouseInputStream in) throws IOException { Assert.assertFalse(in.isClosed(), "Should be openned for read by default"); byte[] bytes = new byte[8]; Assert.assertEquals(in.read(bytes, 1, 6), 6); Assert.assertEquals(new String(bytes, 1, 6), "efghip"); Assert.assertEquals(in.read(bytes), -1); Assert.assertFalse(in.isClosed(), "Should be still openning"); in.close(); Assert.assertTrue(in.isClosed(), "Should have been closed"); } @Test(dataProvider = "inputStreamProvider", groups = { "unit" }) public void testReadByteFromInputStream(ClickHouseInputStream in) throws IOException { Assert.assertFalse(in.isClosed(), "Should be openned for read by default"); StringBuilder builder = new StringBuilder(); while (in.available() > 0) { builder.append((char) in.readByte()); } Assert.assertEquals(builder.toString(), "efghip"); Assert.assertFalse(in.isClosed(), "Should be still openning"); Assert.assertThrows(EOFException.class, () -> in.readByte()); Assert.assertTrue(in.isClosed(), "Should have been closed"); } @Test(dataProvider = "inputStreamProvider", groups = { "unit" }) public void testReadBytesFromInputStream(ClickHouseInputStream in) throws IOException { Assert.assertFalse(in.isClosed(), "Should be openned for read by default"); Assert.assertEquals(new String(in.readBytes(2)), "ef"); Assert.assertEquals(new String(in.readBytes(1)), "g"); Assert.assertEquals(new String(in.readBytes(3)), "hip"); Assert.assertFalse(in.isClosed(), "Should be still openning"); Assert.assertThrows(EOFException.class, () -> in.readBytes(1)); Assert.assertTrue(in.isClosed(), "Should have been closed"); } @Test(dataProvider = "inputStreamProvider", groups = { "unit" }) public void testReadBytesAllFromInputStream(ClickHouseInputStream in) throws IOException { Assert.assertFalse(in.isClosed(), "Should be openned for read by default"); Assert.assertEquals(new String(in.readBytes(6)), "efghip"); Assert.assertFalse(in.isClosed(), "Should be still openning"); Assert.assertThrows(EOFException.class, () -> in.readBytes(1)); Assert.assertTrue(in.isClosed(), "Should have been closed"); } @Test(dataProvider = "inputStreamProvider", groups = { "unit" }) public void testReadBufferFromInputStream(ClickHouseInputStream in) throws IOException { Assert.assertFalse(in.isClosed(), "Should be openned for read by default"); Assert.assertEquals(in.readBuffer(3).asUnicodeString(), "efg"); Assert.assertEquals(in.readBuffer(2).asUnicodeString(), "hi"); Assert.assertEquals(in.readBuffer(1).asUnicodeString(), "p"); Assert.assertFalse(in.isClosed(), "Should be still openning"); Assert.assertThrows(EOFException.class, () -> in.readBuffer(1)); Assert.assertTrue(in.isClosed(), "Should have been closed"); } @Test(dataProvider = "inputStreamProvider", groups = { "unit" }) public void testReadCustomFromInputStream(ClickHouseInputStream in) throws IOException { Assert.assertFalse(in.isClosed(), "Should be openned for read by default"); Assert.assertEquals(in.readCustom((b, o, l) -> 0).asAsciiString(), ""); Assert.assertEquals(in.readCustom((b, o, l) -> 1).asAsciiString(), "e"); final AtomicInteger i = new AtomicInteger(2); Assert.assertEquals( in.readCustom((b, o, l) -> i.get() < (l - o) ? i.get() : i.getAndAdd(0 - l + o) * 0 - 1) .asAsciiString(), "fg"); i.set(3); Assert.assertEquals( in.readCustom((b, o, l) -> i.get() < (l - o) ? i.get() : i.getAndAdd(0 - l + o) * 0 - 1) .asAsciiString(), "hip"); Assert.assertTrue(in.isClosed(), "Should have been closed"); } @Test(dataProvider = "inputStreamProvider", groups = { "unit" }) public void testReadCustomAllFromInputStream(ClickHouseInputStream in) throws IOException { Assert.assertFalse(in.isClosed(), "Should be openned for read by default"); Assert.assertEquals(in.readCustom((b, o, l) -> -1).asAsciiString(), "efghip"); Assert.assertTrue(in.isClosed(), "Should have been closed"); } @Test(dataProvider = "inputStreamProvider", groups = { "unit" }) public void testReadCustomOneAndRestFromInputStream(ClickHouseInputStream in) throws IOException { Assert.assertFalse(in.isClosed(), "Should be openned for read by default"); Assert.assertEquals(in.readCustom((b, o, l) -> 1).asAsciiString(), "e"); Assert.assertEquals(in.readCustom((b, o, l) -> -1).asAsciiString(), "fghip"); Assert.assertTrue(in.isClosed(), "Should have been closed"); } @Test(dataProvider = "inputStreamProvider", groups = { "unit" }) public void testReadCustomOneByOneFromInputStream(ClickHouseInputStream in) throws IOException { Assert.assertFalse(in.isClosed(), "Should be openned for read by default"); StringBuilder builder = new StringBuilder(); while (in.available() > 0) { builder.append(in.readCustom((b, o, l) -> 1).asAsciiString()); } Assert.assertEquals(builder.toString(), "efghip"); Assert.assertEquals(in.readCustom((b, o, l) -> (int) System.currentTimeMillis() % 2).asAsciiString(), ""); Assert.assertTrue(in.isClosed(), "Should have been closed"); } @Test(dataProvider = "inputStreamProvider", groups = { "unit" }) public void testReadPartsFromInputStream(ClickHouseInputStream in) throws IOException { Assert.assertFalse(in.isClosed(), "Should be openned for read by default"); byte[] bytes = new byte[8]; Assert.assertEquals(in.read(bytes, 2, 4), 4); Assert.assertEquals(new String(bytes, 2, 4), "efgh"); Assert.assertEquals(in.read(bytes, 6, 1), 1); Assert.assertEquals(bytes[6], 0x69); Assert.assertTrue(in.available() > 0, "Should have more to read"); Assert.assertFalse(in.isClosed(), "Should be still openning"); in.close(); Assert.assertTrue(in.isClosed(), "Should have been closed"); } @Test(dataProvider = "inputStreamProvider", groups = { "unit" }) public void testPipeInputStream(ClickHouseInputStream in) throws IOException { Assert.assertFalse(in.isClosed(), "Should be openned for read by default"); ByteArrayOutputStream out = new ByteArrayOutputStream(); ClickHouseOutputStream wrapper = ClickHouseOutputStream.of(out); Assert.assertEquals(in.pipe(wrapper), 6L); wrapper.flush(); Assert.assertEquals(new String(out.toByteArray()), "efghip"); Assert.assertTrue(in.isClosed(), "Should have been closed"); } @Test(dataProvider = "emptyInputStreamProvider", groups = { "unit" }) public void testReadByteFromEmptyInputStream(ClickHouseInputStream in) throws IOException { Assert.assertFalse(in.isClosed(), "Should be openned for read by default"); Assert.assertThrows(EOFException.class, () -> in.readByte()); if (in == EmptyInputStream.INSTANCE) { Assert.assertFalse(in.isClosed(), "EmptyInputStream can never be closed"); } else { Assert.assertTrue(in.isClosed(), "Should have been closed"); } } @Test(dataProvider = "emptyInputStreamProvider", groups = { "unit" }) public void testReadBytesFromEmptyInputStream(ClickHouseInputStream in) throws IOException { Assert.assertFalse(in.isClosed(), "Should be openned for read by default"); Assert.assertEquals(in.readBytes(-1), new byte[0]); Assert.assertEquals(in.readBytes(0), new byte[0]); Assert.assertThrows(EOFException.class, () -> in.readBytes(1)); if (in == EmptyInputStream.INSTANCE) { Assert.assertFalse(in.isClosed(), "EmptyInputStream can never be closed"); } else { Assert.assertTrue(in.isClosed(), "Should have been closed"); } } @Test(dataProvider = "emptyInputStreamProvider", groups = { "unit" }) public void testReadBufferFromEmptyInputStream(ClickHouseInputStream in) throws IOException { Assert.assertFalse(in.isClosed(), "Should be openned for read by default"); Assert.assertEquals(in.readBuffer(-1), ClickHouseByteBuffer.newInstance()); Assert.assertEquals(in.readBuffer(0), ClickHouseByteBuffer.newInstance()); Assert.assertThrows(EOFException.class, () -> in.readBuffer(1)); if (in == EmptyInputStream.INSTANCE) { Assert.assertFalse(in.isClosed(), "EmptyInputStream can never be closed"); } else { Assert.assertTrue(in.isClosed(), "Should have been closed"); } } @Test(dataProvider = "emptyInputStreamProvider", groups = { "unit" }) public void testReadCustomFromEmptyInputStream(ClickHouseInputStream in) throws IOException { Assert.assertFalse(in.isClosed(), "Should be openned for read by default"); Assert.assertEquals(in.readCustom((b, o, l) -> (int) (System.currentTimeMillis() % 2)), ClickHouseByteBuffer.newInstance()); if (in == EmptyInputStream.INSTANCE) { Assert.assertFalse(in.isClosed(), "EmptyInputStream can never be closed"); } else { Assert.assertTrue(in.isClosed(), "Should have been closed"); } } @Test(dataProvider = "emptyInputStreamProvider", groups = { "unit" }) public void testPipeEmptyInputStream(ClickHouseInputStream in) throws IOException { Assert.assertFalse(in.isClosed(), "Should be openned for read by default"); ByteArrayOutputStream out = new ByteArrayOutputStream(); Assert.assertEquals(in.pipe(ClickHouseOutputStream.of(out)), 0L); if (in == EmptyInputStream.INSTANCE) { Assert.assertFalse(in.isClosed(), "EmptyInputStream can never be closed"); } else { Assert.assertTrue(in.isClosed(), "Should have been closed"); } } @Test(dataProvider = "streamProvider", groups = { "unit" }) public void testNullEmptyOrClosedInput(BiFunction<Boolean, int[], ClickHouseInputStream> newStreamFunc) throws IOException { Assert.assertThrows(IllegalArgumentException.class, () -> newStreamFunc.apply(false, null)); ClickHouseInputStream empty = newStreamFunc.apply(false, new int[0]); Assert.assertEquals(empty.isClosed(), false); Assert.assertEquals(empty.available(), 0); Assert.assertEquals(empty.read(), -1); Assert.assertEquals(empty.read(), -1); Assert.assertEquals(empty.read(new byte[1]), -1); Assert.assertEquals(empty.read(new byte[1]), -1); Assert.assertEquals(empty.readBytes(0), new byte[0]); Assert.assertThrows(EOFException.class, () -> empty.readByte()); Assert.assertEquals(empty.isClosed(), true); Assert.assertThrows(IOException.class, () -> empty.read()); ClickHouseInputStream empty1 = newStreamFunc.apply(false, new int[0]); Assert.assertEquals(empty1.isClosed(), false); Assert.assertThrows(EOFException.class, () -> empty1.readBytes(1)); Assert.assertEquals(empty1.isClosed(), true); Assert.assertThrows(IOException.class, () -> empty1.read()); ClickHouseInputStream chIn = newStreamFunc.apply(true, new int[] { 123 }); Assert.assertEquals(chIn.isClosed(), true); Assert.assertEquals(chIn.available(), 0); Assert.assertEquals(chIn.isClosed(), true); Assert.assertEquals(ClickHouseInputStream.of(chIn), chIn); Assert.assertEquals(chIn.readBytes(0), new byte[0]); Assert.assertThrows(IOException.class, () -> chIn.readBytes(1)); Assert.assertThrows(IOException.class, () -> chIn.read()); Assert.assertThrows(IOException.class, () -> chIn.readByte()); Assert.assertEquals(chIn.read(new byte[0]), 0); chIn.close(); Assert.assertEquals(chIn.isClosed(), true); } @Test(dataProvider = "streamWithData", groups = { "unit" }) public void testReadCustom(ClickHouseInputStream input) throws IOException { try (ClickHouseInputStream in = input) { Assert.assertEquals(in.readCustom((bytes, position, limit) -> 0), ClickHouseByteBuffer.newInstance()); Assert.assertEquals(in.readCustom((bytes, position, limit) -> 1).compact(), ClickHouseByteBuffer.of(new byte[] { 1 })); Assert.assertEquals(in.readCustom((bytes, position, limit) -> { int count = 0; for (int i = position; i < limit; i++) { count++; if (bytes[i] == 4) { return count; } } return -1; }).compact(), ClickHouseByteBuffer.of(new byte[] { 2, 3, 4 })); Assert.assertEquals(in.readCustom((bytes, position, limit) -> -1).compact(), ClickHouseByteBuffer.of(new byte[] { 5 })); Assert.assertTrue(in.isClosed(), "Input stream should have been closed"); Assert.assertThrows(IOException.class, () -> in.readCustom((bytes, position, limit) -> 0)); } Assert.assertThrows(IOException.class, () -> input.readCustom((bytes, position, limit) -> -1)); } @Test(groups = { "unit" }) public void testReadCustomArray() throws IOException { try (ClickHouseInputStream in = new IterableByteArrayInputStream( Arrays.asList(null, new byte[0], new byte[] { 1, 2, 3 }, new byte[0], null, new byte[] { 4, 5 }, null, new byte[0], null), null)) { Assert.assertEquals(in.readCustom(null), ClickHouseByteBuffer.newInstance()); Assert.assertFalse(in.isClosed(), "Stream should not be closed"); Assert.assertEquals(in.readCustom(new CustomReader((byte) 5, (byte) 2)::read), ClickHouseByteBuffer.of(new byte[] { 1, 2, 3 }, 0, 2)); Assert.assertFalse(in.isClosed(), "Stream should not be closed"); Assert.assertEquals(in.readCustom(new CustomReader((byte) 5)::read), ClickHouseByteBuffer.of(new byte[] { 3, 4, 5 })); Assert.assertFalse(in.isClosed(), "Stream should not be closed"); Assert.assertEquals(in.readCustom(new CustomReader((byte) 6)::read), ClickHouseByteBuffer.newInstance()); Assert.assertTrue(in.isClosed(), "Stream should have been closed"); } try (ClickHouseInputStream in = new IterableByteArrayInputStream( Arrays.asList(null, new byte[0], new byte[] { 1, 2, 3 }, new byte[0], null, new byte[] { 4, 5 }, null, new byte[0], null), null)) { Assert.assertFalse(in.isClosed(), "Stream should not be closed"); Assert.assertEquals(in.readCustom(new CustomReader((byte) 0)::read), ClickHouseByteBuffer.of(new byte[] { 1, 2, 3, 4, 5 })); Assert.assertTrue(in.isClosed(), "Stream should have been closed"); Assert.assertEquals(in.readCustom(null), ClickHouseByteBuffer.newInstance()); Assert.assertThrows(IOException.class, () -> { in.readCustom(new CustomReader((byte) 1, (byte) 2)::read); }); } byte[] bytes = "萌\\N懵\\t哒\t🤣。".getBytes(StandardCharsets.UTF_8); try (ClickHouseInputStream in = new IterableByteArrayInputStream( Arrays.asList(null, new byte[0], bytes, new byte[0], null, "ab".getBytes(StandardCharsets.US_ASCII), null, new byte[0], null), null)) { Assert.assertFalse(in.isClosed(), "Stream should not be closed"); Assert.assertEquals(in.readCustom(new CustomReader((byte) '\n', (byte) '\t')::read), ClickHouseByteBuffer.of(bytes, 0, 14)); Assert.assertFalse(in.isClosed(), "Stream should not be closed"); Assert.assertEquals(in.readCustom(new CustomReader((byte) '\t', (byte) '\n')::read), ClickHouseByteBuffer.of("🤣。ab".getBytes(StandardCharsets.UTF_8), 0, 9)); Assert.assertTrue(in.isClosed(), "Stream should have been closed"); Assert.assertThrows(IOException.class, () -> { in.readCustom((b, o, l) -> { int count = 0; for (int i = o; i < l; i++) { byte v = b[i]; count++; if (v == (byte) 1 || v == (byte) 2) { return count; } } return -1; }); }); } } @Test(groups = { "unit" }) public void testReadCustomBuffer() throws IOException { try (ClickHouseInputStream in = new IterableByteBufferInputStream( Arrays.asList(null, ByteBuffer.allocateDirect(0), ByteBuffer.wrap(new byte[] { -1, 1, 2, 3, -4 }, 1, 3), ByteBuffer.allocate(0), null, ByteBuffer.wrap(new byte[] { 4, 5 }), null, ByteBuffer.allocate(0), null), null)) { Assert.assertEquals(in.readCustom(null), ClickHouseByteBuffer.newInstance()); Assert.assertFalse(in.isClosed(), "Stream should not be closed"); Assert.assertEquals(in.readCustom(new CustomReader((byte) 5, (byte) 2)::read).compact(), ClickHouseByteBuffer.of(new byte[] { 1, 2 }, 0, 2)); Assert.assertFalse(in.isClosed(), "Stream should not be closed"); Assert.assertEquals(in.readCustom(new CustomReader((byte) 5)::read), ClickHouseByteBuffer.of(new byte[] { 3, 4, 5 })); Assert.assertFalse(in.isClosed(), "Stream should not be closed"); Assert.assertEquals(in.readCustom(new CustomReader((byte) 6)::read), ClickHouseByteBuffer.newInstance()); Assert.assertTrue(in.isClosed(), "Stream should have been closed"); } try (ClickHouseInputStream in = new IterableByteBufferInputStream( Arrays.asList(null, ByteBuffer.allocateDirect(0), ByteBuffer.wrap(new byte[] { 1, 2, 3 }), ByteBuffer.allocate(0), null, ByteBuffer.wrap(new byte[] { 4, 5 }), null, ByteBuffer.allocate(0), null), null)) { Assert.assertFalse(in.isClosed(), "Stream should not be closed"); Assert.assertEquals(in.readCustom(new CustomReader((byte) 0)::read), ClickHouseByteBuffer.of(new byte[] { 1, 2, 3, 4, 5 })); Assert.assertTrue(in.isClosed(), "Stream should have been closed"); Assert.assertEquals(in.readCustom(null), ClickHouseByteBuffer.newInstance()); Assert.assertThrows(IOException.class, () -> in.readCustom(new CustomReader((byte) 1, (byte) 2)::read)); } byte[] bytes = "萌\\N懵\\t哒\t🤣。".getBytes(StandardCharsets.UTF_8); try (ClickHouseInputStream in = new IterableByteBufferInputStream( Arrays.asList(null, ByteBuffer.allocate(0), ByteBuffer.wrap(bytes), ByteBuffer.allocateDirect(0), null, ByteBuffer.wrap("ab".getBytes(StandardCharsets.US_ASCII)), null, ByteBuffer.allocateDirect(0), null), null)) { Assert.assertFalse(in.isClosed(), "Stream should not be closed"); Assert.assertEquals(in.readCustom(new CustomReader((byte) '\n', (byte) '\t')::read).compact(), ClickHouseByteBuffer.of(bytes, 0, 14).compact()); Assert.assertFalse(in.isClosed(), "Stream should not be closed"); Assert.assertEquals(in.readCustom(new CustomReader((byte) '\t', (byte) '\n')::read), ClickHouseByteBuffer.of("🤣。ab".getBytes(StandardCharsets.UTF_8), 0, 9)); Assert.assertTrue(in.isClosed(), "Stream should have been closed"); Assert.assertThrows(IOException.class, () -> in.readCustom(new CustomReader((byte) 1, (byte) 2)::read)); } } }
17,122
938
package slimeknights.tconstruct.common.registration; import net.minecraft.block.AbstractBlock; import net.minecraft.block.Block; import net.minecraft.item.BlockItem; import net.minecraft.item.Item; import net.minecraft.util.IStringSerializable; import net.minecraftforge.fml.RegistryObject; import slimeknights.mantle.registration.deferred.BlockDeferredRegister; import slimeknights.mantle.registration.object.EnumObject; import slimeknights.mantle.registration.object.ItemObject; import java.util.function.Function; import java.util.function.Supplier; public class BlockDeferredRegisterExtension extends BlockDeferredRegister { public BlockDeferredRegisterExtension(String modID) { super(modID); } /** * Creates a new metal item object * @param name Metal name * @param tagName Name to use for tags for this block * @param blockSupplier Supplier for the block * @param blockItem Block item * @param itemProps Properties for the item * @return Metal item object */ public MetalItemObject registerMetal(String name, String tagName, Supplier<Block> blockSupplier, Function<Block,? extends BlockItem> blockItem, Item.Properties itemProps) { ItemObject<Block> block = register(name + "_block", blockSupplier, blockItem); Supplier<Item> itemSupplier = () -> new Item(itemProps); RegistryObject<Item> ingot = itemRegister.register(name + "_ingot", itemSupplier); RegistryObject<Item> nugget = itemRegister.register(name + "_nugget", itemSupplier); return new MetalItemObject(tagName, block, ingot, nugget); } /** * Creates a new metal item object * @param name Metal name * @param blockSupplier Supplier for the block * @param blockItem Block item * @param itemProps Properties for the item * @return Metal item object */ public MetalItemObject registerMetal(String name, Supplier<Block> blockSupplier, Function<Block,? extends BlockItem> blockItem, Item.Properties itemProps) { return registerMetal(name, name, blockSupplier, blockItem, itemProps); } /** * Creates a new metal item object * @param name Metal name * @param tagName Name to use for tags for this block * @param blockProps Properties for the block * @param blockItem Block item * @param itemProps Properties for the item * @return Metal item object */ public MetalItemObject registerMetal(String name, String tagName, AbstractBlock.Properties blockProps, Function<Block,? extends BlockItem> blockItem, Item.Properties itemProps) { return registerMetal(name, tagName, () -> new Block(blockProps), blockItem, itemProps); } /** * Creates a new metal item object * @param name Metal name * @param blockProps Properties for the block * @param blockItem Block item * @param itemProps Properties for the item * @return Metal item object */ public MetalItemObject registerMetal(String name, AbstractBlock.Properties blockProps, Function<Block,? extends BlockItem> blockItem, Item.Properties itemProps) { return registerMetal(name, name, blockProps, blockItem, itemProps); } /** * Registers a block with enum variants, but no item form * @param values Enum value list * @param name Suffix after value name * @param mapper Function to map types to blocks * @param <T> Type of enum * @param <B> Type of block * @return Enum object */ public <T extends Enum<T> & IStringSerializable, B extends Block> EnumObject<T, B> registerEnumNoItem(T[] values, String name, Function<T, ? extends B> mapper) { return registerEnum(values, name, (fullName, value) -> this.registerNoItem(fullName, () -> mapper.apply(value))); } }
1,193
1,029
package net.anumbrella.lkshop.model; import net.anumbrella.lkshop.http.RetrofitHttp; import net.anumbrella.lkshop.model.bean.CommentOrderDataModel; import net.anumbrella.lkshop.model.bean.OrderDataModel; import net.anumbrella.lkshop.utils.BaseUtils; import java.util.List; import okhttp3.OkHttpClient; import okhttp3.ResponseBody; import retrofit2.Callback; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; /** * author:Anumbrella * Date:16/6/9 下午8:56 */ public class OrderAllDataModel { public static void getOrderDataFromNet(Subscriber<List<OrderDataModel>> subscriber, String uid) { OkHttpClient.Builder builder = new OkHttpClient.Builder(); RetrofitHttp.getRetrofit(builder.build()).getAllOrderData("getAllOrderData", uid) .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(subscriber); } public static void deleteOrderData(Callback<ResponseBody> responseBodyCallback, String uid, String pid, String oid) { OkHttpClient.Builder builder = new OkHttpClient.Builder(); RetrofitHttp.getRetrofit(builder.build()).deleteOrderData("deleteOrderData", BaseUtils.encrypt(uid), BaseUtils.encrypt(pid), BaseUtils.encrypt(oid)) .enqueue(responseBodyCallback); } public static void publishCommentData(Callback<ResponseBody> responseBodyCallback, CommentOrderDataModel data) { OkHttpClient.Builder builder = new OkHttpClient.Builder(); RetrofitHttp.getRetrofit(builder.build()).publishComment("publishCommentData", data).enqueue(responseBodyCallback); } }
627
575
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_ACCOUNT_MANAGER_CORE_ACCOUNT_MANAGER_UTIL_H_ #define COMPONENTS_ACCOUNT_MANAGER_CORE_ACCOUNT_MANAGER_UTIL_H_ #include "base/optional.h" #include "chromeos/crosapi/mojom/account_manager.mojom.h" #include "components/account_manager_core/account.h" #include "components/account_manager_core/account_addition_result.h" class GoogleServiceAuthError; namespace account_manager { // Returns `base::nullopt` if `mojom_account` cannot be parsed. COMPONENT_EXPORT(ACCOUNT_MANAGER_CORE) base::Optional<account_manager::Account> FromMojoAccount( const crosapi::mojom::AccountPtr& mojom_account); COMPONENT_EXPORT(ACCOUNT_MANAGER_CORE) crosapi::mojom::AccountPtr ToMojoAccount( const account_manager::Account& account); // Returns `base::nullopt` if `mojom_account_key` cannot be parsed. COMPONENT_EXPORT(ACCOUNT_MANAGER_CORE) base::Optional<account_manager::AccountKey> FromMojoAccountKey( const crosapi::mojom::AccountKeyPtr& mojom_account_key); COMPONENT_EXPORT(ACCOUNT_MANAGER_CORE) crosapi::mojom::AccountKeyPtr ToMojoAccountKey( const account_manager::AccountKey& account_key); // Returns `base::nullopt` if `account_type` cannot be parsed. COMPONENT_EXPORT(ACCOUNT_MANAGER_CORE) base::Optional<account_manager::AccountType> FromMojoAccountType( const crosapi::mojom::AccountType& account_type); COMPONENT_EXPORT(ACCOUNT_MANAGER_CORE) crosapi::mojom::AccountType ToMojoAccountType( const account_manager::AccountType& account_type); // Returns `base::nullopt` if `mojo_error` cannot be parsed. This probably means // that a new error type was added, so it should be considered a persistent // error. COMPONENT_EXPORT(ACCOUNT_MANAGER_CORE) base::Optional<GoogleServiceAuthError> FromMojoGoogleServiceAuthError( const crosapi::mojom::GoogleServiceAuthErrorPtr& mojo_error); COMPONENT_EXPORT(ACCOUNT_MANAGER_CORE) crosapi::mojom::GoogleServiceAuthErrorPtr ToMojoGoogleServiceAuthError( GoogleServiceAuthError error); COMPONENT_EXPORT(ACCOUNT_MANAGER_CORE) base::Optional<account_manager::AccountAdditionResult> FromMojoAccountAdditionResult( const crosapi::mojom::AccountAdditionResultPtr& mojo_result); COMPONENT_EXPORT(ACCOUNT_MANAGER_CORE) crosapi::mojom::AccountAdditionResultPtr ToMojoAccountAdditionResult( account_manager::AccountAdditionResult result); } // namespace account_manager #endif // COMPONENTS_ACCOUNT_MANAGER_CORE_ACCOUNT_MANAGER_UTIL_H_
912
1,217
#pragma once #include <limits> #include "aabb.hpp" #include "portable.hpp" namespace My { ENUM(GeometryType){kBox, kCapsule, kCone, kCylinder, kPlane, kPolyhydron, kSphere, kTriangle}; class Geometry { public: explicit Geometry(GeometryType geometry_type) : m_kGeometryType(geometry_type){}; Geometry() = delete; virtual ~Geometry() = default; // GetAabb returns the axis aligned bounding box in the coordinate frame of // the given transform trans. virtual void GetAabb(const Matrix4X4f& trans, Vector3f& aabbMin, Vector3f& aabbMax) const = 0; virtual void GetBoundingSphere(Vector3f& center, float& radius) const; // GetAngularMotionDisc returns the maximum radius needed for Conservative // Advancement to handle // time-of-impact with rotations. [[nodiscard]] virtual float GetAngularMotionDisc() const; // CalculateTemporalAabb calculates the enclosing aabb for the moving object // over interval [0..timeStep) result is conservative void CalculateTemporalAabb(const Matrix4X4f& curTrans, const Vector3f& linvel, const Vector3f& angvel, float timeStep, Vector3f& temporalAabbMin, Vector3f& temporalAabbMax) const; [[nodiscard]] GeometryType GetGeometryType() const { return m_kGeometryType; }; protected: GeometryType m_kGeometryType; float m_fMargin = std::numeric_limits<float>::epsilon(); Vector3f m_color; }; } // namespace My
648
745
<filename>social_core/backends/mailru.py """ Mail.ru OAuth2 backend, docs at: https://python-social-auth.readthedocs.io/en/latest/backends/mailru.html """ from hashlib import md5 from urllib.parse import unquote from .oauth import BaseOAuth2 class MailruOAuth2(BaseOAuth2): """Mail.ru authentication backend""" name = 'mailru-oauth2' ID_KEY = 'uid' AUTHORIZATION_URL = 'https://connect.mail.ru/oauth/authorize' ACCESS_TOKEN_URL = 'https://connect.mail.ru/oauth/token' ACCESS_TOKEN_METHOD = 'POST' EXTRA_DATA = [('refresh_token', 'refresh_token'), ('expires_in', 'expires')] def get_user_details(self, response): """Return user details from Mail.ru request""" fullname, first_name, last_name = self.get_user_names( first_name=unquote(response['first_name']), last_name=unquote(response['last_name']) ) return {'username': unquote(response['nick']), 'email': unquote(response['email']), 'fullname': fullname, 'first_name': first_name, 'last_name': last_name} def user_data(self, access_token, *args, **kwargs): """Return user data from Mail.ru REST API""" key, secret = self.get_key_and_secret() data = {'method': 'users.getInfo', 'session_key': access_token, 'app_id': key, 'secure': '1'} param_list = sorted(list(item + '=' + data[item] for item in data)) data['sig'] = md5( (''.join(param_list) + secret).encode('utf-8') ).hexdigest() return self.get_json('http://www.appsmail.ru/platform/api', params=data)[0] class MRGOAuth2(BaseOAuth2): name = 'mailru' ID_KEY = 'email' AUTHORIZATION_URL = 'https://oauth.mail.ru/login' ACCESS_TOKEN_URL = 'https://oauth.mail.ru/token' ACCESS_TOKEN_METHOD = 'POST' EXTRA_DATA = [('refresh_token', 'refresh_token'), ('expires_in', 'expires')] REDIRECT_STATE = False def get_user_details(self, response): return { 'gender': response.get('gender'), 'fullname': response.get('name'), 'username': response.get('name'), 'first_name': response.get('first_name'), 'last_name': response.get('last_name'), 'locale': response.get('locale'), 'email': response.get('email'), 'address': response.get('address'), 'birthday': response.get('birthday'), 'image': response.get('image'), } def user_data(self, access_token, *args, **kwargs): return self.get_json('https://oauth.mail.ru/userinfo', params={'access_token': access_token})
1,280
649
<gh_stars>100-1000 import asyncio import json from concurrent.futures import ProcessPoolExecutor import trafaret as t import yaml from .consts import PROJ_ROOT from .exceptions import JsonValidaitonError from .worker import warm def load_config(fname): with open(fname, 'rt') as f: data = yaml.load(f) # TODO: add config validation return data Comment = t.Dict({ t.Key('comment'): t.String, }) CommentList = t.List(Comment, max_length=10) ModerateView = t.Dict({ t.Key('toxic'): t.Float[0:1], t.Key('severe_toxic'): t.Float[0:1], t.Key('obscene'): t.Float[0:1], t.Key('insult'): t.Float[0:1], t.Key('identity_hate'): t.Float[0:1], }) ModerateList = t.List(ModerateView) def validate_payload(raw_payload, schema): payload = raw_payload.decode(encoding='UTF-8') try: parsed = json.loads(payload) except ValueError: raise JsonValidaitonError('Payload is not json serialisable') try: data = schema(parsed) except t.DataError as exc: result = exc.as_dict() raise JsonValidaitonError(result) return data async def setup_executor(app, conf): n = conf['max_workers'] executor = ProcessPoolExecutor(max_workers=n) path = str(PROJ_ROOT / conf['model_path']) loop = asyncio.get_event_loop() run = loop.run_in_executor fs = [run(executor, warm, path) for i in range(0, n)] await asyncio.gather(*fs) async def close_executor(app): # TODO: figureout timeout for shutdown executor.shutdown(wait=True) app.on_cleanup.append(close_executor) app['executor'] = executor return executor
684
389
<reponame>andyyangdong/vester // // VSImagePickerController.h // Vesper // // Created by <NAME> on 4/17/13. // Copyright (c) 2013 Q Branch LLC. All rights reserved. // #import <Foundation/Foundation.h> /*Get a picture from the user and return it in a callback. The image will be resized down from the original image to a size suitable for syncing. The original image will also be saved to the user's camera roll.*/ @interface VSImagePickerController : NSObject <UIImagePickerControllerDelegate, UINavigationControllerDelegate> - (instancetype)initWithViewController:(UIViewController *)viewController; /*When the callback is called, it's safe to release this object. If user cancels, the callback will be called with a nil UIImage.*/ - (void)runImagePickerForSourceType:(UIImagePickerControllerSourceType)sourceType callback:(QSImageResultBlock)callback; @end
251
1,050
#include <filter.hpp> #include <vector> #include <iostream> bool greater_than_four(int i) { return i > 4; } class LessThanValue { private: int compare_val; public: LessThanValue() = delete; LessThanValue(int v) : compare_val(v) { } bool operator() (int i) { return i < this->compare_val; } }; int main() { std::vector<int> ns{1, 5, 6, 0, 7, 2, 3, 8, 3, 0, 2, 1}; std::cout << "ns = { "; for (auto&& i : ns) { std::cout << i << ' '; } std::cout << "}\n"; std::cout << "Greater than 4 (function pointer)\n"; for (auto&& i : iter::filter(greater_than_four, ns)) { std::cout << i << '\n'; } std::cout << "Less than 4 (lambda)\n"; for (auto&& i : iter::filter([] (const int i) { return i < 4; }, ns)) { std::cout << i << '\n'; } LessThanValue lv(4); std::cout << "Less than 4 (callable object)\n"; for (auto&& i : iter::filter(lv, ns)) { std::cout << i << '\n'; } // filter(seq) with no predicate uses the truthiness of the values std::cout << "Nonzero ints filter(ns)\n"; for (auto&& i : iter::filter(ns)) { std::cout << i << '\n'; } std::cout << "odd numbers\n"; for (auto&& i : iter::filter([] (const int i) {return i % 2;}, ns)) { std::cout << i << '\n'; } }
645
347
package org.ovirt.engine.core.common.businessentities.gluster; import java.io.Serializable; import java.util.Objects; import org.ovirt.engine.core.compat.Guid; public class GlusterServerHook implements Serializable { private static final long serialVersionUID = -8502820314459844040L; private Guid hookId; private Guid serverId; private String serverName; private GlusterHookStatus status; private GlusterHookContentType contentType; private String checksum; public Guid getHookId() { return hookId; } public void setHookId(Guid hookId) { this.hookId = hookId; } public Guid getServerId() { return serverId; } public void setServerId(Guid serverId) { this.serverId = serverId; } public String getServerName() { return serverName; } public void setServerName(String serverName) { this.serverName = serverName; } public GlusterHookStatus getStatus() { return status; } public void setStatus(GlusterHookStatus status) { this.status = status; } public void setStatus(String status) { if (status != null) { this.status = GlusterHookStatus.valueOf(status); } else { this.status = null; } } public GlusterHookContentType getContentType() { return contentType; } public void setContentType(GlusterHookContentType contentType) { this.contentType = contentType; } public void setContentType(String contentType) { if (contentType != null) { this.contentType = GlusterHookContentType.valueOf(contentType); } else { this.contentType = null; } } public String getChecksum() { return checksum; } public void setChecksum(String checksum) { this.checksum = checksum; } @Override public int hashCode() { return Objects.hash( hookId, serverId, status, contentType, checksum ); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof GlusterServerHook)) { return false; } GlusterServerHook serverHook = (GlusterServerHook) obj; return Objects.equals(hookId, serverHook.hookId) && Objects.equals(serverId, serverHook.serverId) && Objects.equals(status, serverHook.status) && Objects.equals(contentType, serverHook.contentType) && Objects.equals(checksum, serverHook.checksum); } }
1,177
1,105
// Copyright Contributors to the Open Shading Language project. // SPDX-License-Identifier: BSD-3-Clause // https://github.com/AcademySoftwareFoundation/OpenShadingLanguage #ifndef __OSL_XMACRO_OPNAME # error must define __OSL_XMACRO_OPNAME to name of unary operation before including this header #endif #ifndef __OSL_XMACRO_OP # define __OSL_XMACRO_OP __OSL_XMACRO_OPNAME #endif #ifndef __OSL_XMACRO_IN_TRANSFORM # define __OSL_XMACRO_IN_TRANSFORM(...) __VA_ARGS__ #endif #ifdef __OSL_XMACRO_UNIFORM_IN # define __OSL_XMACRO_IN_TRANSFORM_INT(...) __OSL_XMACRO_IN_TRANSFORM(1.0/(2*raytype("camera"))) #else # define __OSL_XMACRO_IN_TRANSFORM_INT(...) __OSL_XMACRO_IN_TRANSFORM(__VA_ARGS__) #endif #ifndef __OSL_XMACRO_OUT_TRANSFORM # define __OSL_XMACRO_OUT_TRANSFORM(out) out #endif #ifndef __OSL_XMACRO_STRIPE_TRANSFORM # define __OSL_XMACRO_STRIPE_TRANSFORM(...) (__VA_ARGS__)/2 #endif #ifndef __OSL_CONCAT # define __OSL_CONCAT_INDIRECT(A, B) A##B # define __OSL_CONCAT(A, B) __OSL_CONCAT_INDIRECT(A, B) # define __OSL_CONCAT3(A, B, C) __OSL_CONCAT(__OSL_CONCAT(A, B), C) #endif shader __OSL_CONCAT3(test_, __OSL_XMACRO_OPNAME, _int)(int numStripes = 0, output int out_int = 1, ) { int int_in = int(__OSL_XMACRO_IN_TRANSFORM_INT(((P[0] + P[1]) * 0.5))); // Exercise the op unmasked int int_val = __OSL_XMACRO_OP(int_in); // Exercise the op masked if ((numStripes != 0) && (int(P[0]*P[0]*P[1]*2*numStripes)%2 == 0)) { int_val = __OSL_XMACRO_OP(int(__OSL_XMACRO_STRIPE_TRANSFORM(int_in))); } out_int = __OSL_XMACRO_OUT_TRANSFORM(int_val); }
857
358
# Copyright (c) 2012-2021, <NAME> <<EMAIL>> # All rights reserved. # # See LICENSE file for full license. from .aws import Action as BaseAction from .aws import BaseARN service_name = "Amazon Lookout for Equipment" prefix = "lookoutequipment" class Action(BaseAction): def __init__(self, action: str = None) -> None: super().__init__(prefix, action) class ARN(BaseARN): def __init__(self, resource: str = "", region: str = "", account: str = "") -> None: super().__init__( service=prefix, resource=resource, region=region, account=account ) CreateDataset = Action("CreateDataset") CreateInferenceScheduler = Action("CreateInferenceScheduler") CreateModel = Action("CreateModel") DeleteDataset = Action("DeleteDataset") DeleteInferenceScheduler = Action("DeleteInferenceScheduler") DeleteModel = Action("DeleteModel") DescribeDataIngestionJob = Action("DescribeDataIngestionJob") DescribeDataset = Action("DescribeDataset") DescribeInferenceScheduler = Action("DescribeInferenceScheduler") DescribeModel = Action("DescribeModel") ListDataIngestionJobs = Action("ListDataIngestionJobs") ListDatasets = Action("ListDatasets") ListInferenceExecutions = Action("ListInferenceExecutions") ListInferenceSchedulers = Action("ListInferenceSchedulers") ListModels = Action("ListModels") ListTagsForResource = Action("ListTagsForResource") StartDataIngestionJob = Action("StartDataIngestionJob") StartInferenceScheduler = Action("StartInferenceScheduler") StopInferenceScheduler = Action("StopInferenceScheduler") TagResource = Action("TagResource") UntagResource = Action("UntagResource") UpdateInferenceScheduler = Action("UpdateInferenceScheduler")
535
602
<filename>persistence-api/src/main/java/io/stargate/db/datastore/ArrayListBackedRow.java package io.stargate.db.datastore; import static java.lang.String.format; import com.datastax.oss.driver.api.core.ProtocolVersion; import com.datastax.oss.driver.api.core.type.DataType; import com.datastax.oss.driver.api.core.type.codec.registry.CodecRegistry; import io.stargate.db.schema.Column; import java.nio.ByteBuffer; import java.util.List; import java.util.stream.Collectors; import javax.annotation.Nonnull; import javax.annotation.Nullable; public class ArrayListBackedRow implements Row { private final List<Column> columns; private final List<ByteBuffer> values; private final ProtocolVersion protocolVersion; public ArrayListBackedRow( List<Column> columns, List<ByteBuffer> values, ProtocolVersion protocolVersion) { assert columns.size() == values.size(); this.columns = columns; this.values = values; this.protocolVersion = protocolVersion; } @Override public List<Column> columns() { return columns; } private void checkIndex(int index) { if (index < 0 || index >= columns.size()) { throw new IndexOutOfBoundsException( format("Index %d is out of bounds: the row has %d columns", index, columns.size())); } } @Override public int firstIndexOf(@Nonnull String column) { for (int i = 0; i < columns.size(); i++) { if (columns.get(i).name().equals(column)) { return i; } } throw new IllegalArgumentException( format("Column '%s' is not defined in the Row's metadata.", column)); } @Nonnull @Override public DataType getType(@Nonnull String column) { return getType(firstIndexOf(column)); } @Nonnull @Override public DataType getType(int i) { checkIndex(i); return columns.get(i).type().codec().getCqlType(); } @Nullable @Override public ByteBuffer getBytesUnsafe(int i) { checkIndex(i); return values.get(i); } @Override public int size() { return values.size(); } @Nonnull @Override public CodecRegistry codecRegistry() { return Column.CODEC_REGISTRY; } @Nonnull @Override public ProtocolVersion protocolVersion() { return protocolVersion; } @Override public String toString() { return columns().stream() .map(c -> format("%s=%s", c.name(), getObject(c.name()))) .collect(Collectors.joining(", ", "{", "}")); } }
874
496
#include <cstdio> #include <cstring> #include <vector> #include <map> using namespace std; #define IPS_ADDRESS_EXTERN 0x01 #define IPS_ADDRESS_GLOBAL 0x02 /* * TODO: Change this program to create RLE expressions. * It now can _read_ them, but.. */ namespace { vector<unsigned char> ROM; vector<bool> Touched; void WriteByte(unsigned addr, unsigned char value) { ROM[addr] = value; Touched[addr] = true; } void WriteShort(unsigned addr, unsigned short value) { unsigned oldvalue = ROM[addr] | (ROM[addr+1] << 8); fprintf(stderr, "Writing %04X @ %06X (was %04X)\n", value, addr, oldvalue); WriteByte(addr, value & 255); WriteByte(addr+1, value >> 8); } void WriteCheckSumPair(unsigned addr, unsigned sum1) { sum1 &= 0xFFFF; WriteShort(addr+2, sum1); WriteShort(addr+0, sum1 ^ 0xFFFF); } } int main(int argc, const char *const *argv) { if(argc != 1+3) { fprintf(stderr, "fixchecksum: Fixes SNES patch checksum.\n" "Copyright (C) 1992,2005 Bisqwit (http://iki.fi/bisqwit/)\n" "Usage: fixchecksum ipsfile.ips oldfile newfile\n"); return -1; } const char *patchfn = argv[1]; const char *origfn = argv[2]; const char *resfn = argv[3]; FILE *fp = fopen(patchfn, "rb"); if(!fp) { perror(patchfn); } FILE *original = fopen(origfn, "rb"); if(!original) { if(!strcmp(origfn, "-")) original = stdin; else perror(origfn); } if(!fp || !original) return -1; setbuf(fp, NULL); setbuf(original, NULL); unsigned char Buf[5]; fread(Buf, 1, 5, fp); if(strncmp((const char *)Buf, "PATCH", 5)) { fprintf(stderr, "This isn't a patch!\n"); arf:fclose(fp); arf2: if(original)fclose(original); return -1; } while(!feof(original)) { char tmp[4096]; int c = fread(tmp, 1, sizeof tmp, original); if(c < 0 && ferror(original)) { perror("fread"); goto arf2; } if(!c) break; ROM.insert(ROM.end(), tmp, tmp+c); } fclose(original); original=NULL; Touched.resize(ROM.size()); // unsigned col=0; for(;;) { bool rle=false; int wanted,c = fread(Buf, 1, 3, fp); if(c < 0 && ferror(fp)) { ipserr: perror("fread"); goto arf; } if(c < (wanted=3)) { ipseof: fprintf(stderr, "Unexpected end of file (%s) - wanted %d, got %d\n", patchfn, wanted, c); goto arf; } if(!strncmp((const char *)Buf, "EOF", 3))break; unsigned pos = (((unsigned)Buf[0]) << 16) |(((unsigned)Buf[1]) << 8) | ((unsigned)Buf[2]); c = fread(Buf, 1, 2, fp); if(c < 0 && ferror(fp)) { fprintf(stderr, "Got pos %X\n", pos); goto ipserr; } if(c < (wanted=2)) { goto ipseof; } unsigned len = (((unsigned)Buf[0]) << 8) | ((unsigned)Buf[1]); if(len==0) { rle=true; c = fread(Buf, 1, 2, fp); if(c < 0 && ferror(fp)) { fprintf(stderr, "Got pos %X\n", pos); goto ipserr; } if(c < (wanted=2)) { goto ipseof; } len = (((unsigned)Buf[0]) << 8) | ((unsigned)Buf[1]); } // fprintf(stderr, "%06X <- %-5u ", pos, len); // if(++col == 5) { fprintf(stderr, "\n"); col=0; } vector<char> Buf2(len); if(rle) { c = fread(&Buf2[0], 1, 1, fp); if(c < 0 && ferror(fp)) { goto ipserr; } if(c != (wanted=(int)1)) { goto ipseof; } for(unsigned c=1; c<len; ++c) Buf2[c] = Buf2[0]; } else { c = fread(&Buf2[0], 1, len, fp); if(c < 0 && ferror(fp)) { goto ipserr; } if(c != (wanted=(int)len)) { goto ipseof; } } if(pos == IPS_ADDRESS_EXTERN || pos == IPS_ADDRESS_GLOBAL) { /* Ignore these */ } else { if(pos+len > ROM.size()) { unsigned newsize = pos+len; fprintf(stderr, "Warning: ROM will grow from %lu to %u (%u+%u)\n", (unsigned long) ROM.size(), newsize, pos,len); Touched.resize(newsize); ROM.resize(newsize); } for(unsigned a=0; a<len; ++a) WriteByte(pos+a, Buf2[a]); } } // if(col) fprintf(stderr, "\n"); fclose(fp); unsigned CalculatedSize = (ROM.size() / 0x2000) * 0x2000; unsigned size = CalculatedSize; for(unsigned power2=0; ; ++power2) if(!(size >>= 1)) { size = 1 << power2; break; } unsigned sum1=0, remainder=CalculatedSize-size; unsigned offset = ROM.size() - CalculatedSize; /* First create dummy checksums, so that we won't calculate invalid values */ WriteCheckSumPair(offset + 0xFFDC, 0); if(CalculatedSize >= 0x410000) { /* ExHiROM must have $008000 mirrored at $408000 */ for(unsigned a=0x8000; a<=0xFFFF; ++a) WriteByte(offset+0x400000+a, ROM[offset+a]); } for(unsigned a=0; a<size; ++a) sum1 += ROM[offset+a]; if(remainder) { unsigned sum2 = 0; for(unsigned a=0; a<remainder; ++a) sum2 += ROM[offset+size+a]; // Multiply because of mirroring sum1 += sum2 * (size / remainder); } WriteCheckSumPair(offset + 0xFFDC, sum1); if(CalculatedSize >= 0x410000) { WriteCheckSumPair(offset + 0x40FFDC, sum1); } fprintf(stderr, "ROM size $%lX (calculated $%X, 2pow $%X, remainder $%X, offset $%X)\n", (unsigned long) ROM.size(), CalculatedSize, size, remainder, offset); FILE *resultfile = fopen(resfn, "wb"); if(!resultfile) { perror(resfn); return -1; } fprintf(resultfile, "PATCH"); const unsigned MaxHunkSize = 20000; /* Format: 24bit offset, 16-bit size, then data; repeat */ for(unsigned a=0; a<ROM.size(); ++a) { if(!Touched[a])continue; putc((a >>16)&255, resultfile); putc((a >> 8)&255, resultfile); putc((a )&255, resultfile); unsigned offs=a, c=0; while(a < ROM.size() && Touched[a]) { if(c == MaxHunkSize) { --a; break; } ++c, ++a; } putc((c>> 8)&255, resultfile); putc((c )&255, resultfile); int ret = fwrite(&ROM[offs], 1, c, resultfile); if(ret < 0 || ret != (int)c) { fprintf(stderr, " fwrite failed: %d != %d - this patch will be broken.\n", ret, (int)c); perror("fwrite"); } } fwrite("EOF", 1, 3, resultfile); fclose(resultfile); return 0; }
3,523
1,909
package org.knowm.xchange.idex; import static java.lang.Integer.max; import static java.lang.Integer.min; import static java.util.Arrays.asList; import static org.web3j.crypto.Hash.sha3; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.math.BigInteger; import java.util.LinkedList; import java.util.List; import org.bouncycastle.util.encoders.Hex; import org.web3j.crypto.ECKeyPair; import org.web3j.crypto.Sign; import org.web3j.crypto.Sign.SignatureData; public class IdexSignature { static /** Generate v, r, s values from payload */ SignatureData generateSignature(String apiSecret, List<List<String>> data) { byte[] rawhash = null; byte[] saltBytes; byte[] bytes = null; String[] last = new String[1]; BigInteger apiSecret1; ECKeyPair ecKeyPair; try (ByteArrayOutputStream sig_arr = new ByteArrayOutputStream()) { for (List<String> d : data) { String data1 = d.get(1); /* remove 0x prefix and convert to bytes*/ byte[] segment = new byte[0]; byte[] r = new byte[0]; last[0] = new LinkedList<>(asList(data1.toLowerCase().split("0x"))).getLast(); switch (d.get(2)) { case "address": { segment = new byte[20]; r = new BigInteger(last[0], 16).toByteArray(); break; } case "uint256": { segment = new byte[32]; r = new BigInteger(last[0], 10).toByteArray(); break; } } int segLen = segment.length; int rlen = min(max(segLen, r.length), r.length); int oversize = r.length - segLen; System.arraycopy( r, oversize > 0 ? oversize : 0, segment, oversize > 0 ? 0 : (segLen - rlen), min(segLen, rlen)); sig_arr.write(segment); } rawhash = sha3(sig_arr.toByteArray()); } catch (IOException e) { e.printStackTrace(); } // salt the hashed packed string saltBytes = "\u0019Ethereum Signed Message:\n32".getBytes(); assert (new String(Hex.toHexString(saltBytes)).toLowerCase() == "19457468657265756d205369676e6564204d6573736167653a0a3332"); byte[] salted = null; try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) { byteArrayOutputStream.write(saltBytes); byteArrayOutputStream.write(rawhash); salted = bytes = byteArrayOutputStream.toByteArray(); // sha3(bytes); } catch (IOException e) { e.printStackTrace(); } last[0] = new LinkedList<>(asList(apiSecret.split("0x"))).getLast(); apiSecret1 = new BigInteger(last[0], 16); ecKeyPair = ECKeyPair.create(apiSecret1); SignatureData signatureData; signatureData = Sign.signMessage(/* message = */ salted, /* keyPair= */ ecKeyPair); return signatureData; } }
1,285
634
<filename>modules/desktop-awt/desktop-ui-impl/src/main/java/consulo/ui/desktop/internal/image/DesktopImage.java package consulo.ui.desktop.internal.image; import consulo.ui.image.Image; import javax.annotation.Nonnull; import java.util.function.Function; /** * @author VISTALL * @since 2020-10-05 */ public interface DesktopImage<I extends DesktopImage<I>> extends Image { @Nonnull @SuppressWarnings("unchecked") default I copyWithTargetIconLibrary(@Nonnull String iconLibraryId, @Nonnull Function<Image, Image> converter) { return (I)this; } @Nonnull @SuppressWarnings("unchecked") default I copyWithScale(float scale) { return (I)this; } }
227
1,930
<filename>RichEditorViewSample/Pods/Target Support Files/RichEditorView/RichEditorView-umbrella.h<gh_stars>1000+ #ifdef __OBJC__ #import <UIKit/UIKit.h> #else #ifndef FOUNDATION_EXPORT #if defined(__cplusplus) #define FOUNDATION_EXPORT extern "C" #else #define FOUNDATION_EXPORT extern #endif #endif #endif #import "CJWWebView+HackishAccessoryHiding.h" FOUNDATION_EXPORT double RichEditorViewVersionNumber; FOUNDATION_EXPORT const unsigned char RichEditorViewVersionString[];
167
543
<reponame>anastasiard/riiablo<filename>excel/annotation-processor/src/main/java/com/riiablo/excel/SerializedWithAnnotatedElement.java package com.riiablo.excel; import javax.lang.model.element.TypeElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.MirroredTypeException; import com.riiablo.excel.annotation.SerializedWith; public class SerializedWithAnnotatedElement { static SerializedWithAnnotatedElement get(TypeElement element) { SerializedWith annotation = element.getAnnotation(SerializedWith.class); if (annotation == null) return null; return new SerializedWithAnnotatedElement(element, annotation); } SerializedWith annotation; TypeElement element; String canonicalName; String simpleName; SerializedWithAnnotatedElement(TypeElement element, SerializedWith annotation) { this.element = element; this.annotation = annotation; try { Class<?> clazz = annotation.value(); canonicalName = clazz.getCanonicalName(); simpleName = clazz.getSimpleName(); } catch (MirroredTypeException t) { DeclaredType mirroredType = (DeclaredType) t.getTypeMirror(); TypeElement mirroredElement = (TypeElement) mirroredType.asElement(); canonicalName = mirroredElement.getQualifiedName().toString(); simpleName = mirroredElement.getSimpleName().toString(); } } }
443
350
<reponame>zqn1996-alan/talkback /* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.accessibility.talkback.focusmanagement.interpreter; import androidx.annotation.Nullable; import android.view.accessibility.AccessibilityWindowInfo; import com.google.android.accessibility.utils.AccessibilityWindowInfoUtils; import com.google.android.accessibility.utils.StringBuilderUtils; import com.google.android.accessibility.utils.WindowsDelegate; import java.util.Objects; /** * A helper class to get the active window and window titles on the current screen. * * <p><strong>Note: </strong>This class is not responsible for recycling {@code activeWindow}. */ public final class ScreenState implements WindowsDelegate { private final AccessibilityWindowInfo activeWindow; private WindowsDelegate windowsDelegate; private long screenTransitionStartTime = 0; public ScreenState( WindowsDelegate windowsDelegate, AccessibilityWindowInfo activeWindow, long eventTime) { this.windowsDelegate = windowsDelegate; this.activeWindow = activeWindow; this.screenTransitionStartTime = eventTime; } /** Returns title of window with given window ID. */ @Override public CharSequence getWindowTitle(int windowId) { return windowsDelegate.getWindowTitle(windowId); } /** Returns whether is split screen mode. */ @Override public boolean isSplitScreenMode() { return windowsDelegate.isSplitScreenMode(); } /** Returns the current active window. */ @Nullable public AccessibilityWindowInfo getActiveWindow() { return activeWindow; } /** Returns the transition start time of the screen state. */ public long getScreenTransitionStartTime() { return screenTransitionStartTime; } @Override public boolean equals(Object other) { if (!(other instanceof ScreenState)) { return false; } if (other == this) { return true; } ScreenState otherScreen = (ScreenState) other; if (screenTransitionStartTime != ((ScreenState) other).getScreenTransitionStartTime()) { return false; } return AccessibilityWindowInfoUtils.equals(activeWindow, otherScreen.activeWindow); } @Override public int hashCode() { return Objects.hash( (activeWindow == null ? 0 : activeWindow.hashCode()), screenTransitionStartTime); } @Override public String toString() { return StringBuilderUtils.joinFields( StringBuilderUtils.optionalSubObj("activeWindow", activeWindow), StringBuilderUtils.optionalInt("screenTransitionStartTime", screenTransitionStartTime, 0)); } }
907
2,482
<gh_stars>1000+ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.nutch.util; import org.junit.Assert; import org.junit.Test; /** Unit tests for PrefixStringMatcher. */ public class TestPrefixStringMatcher { private final static int NUM_TEST_ROUNDS = 20; private final static int MAX_TEST_PREFIXES = 100; private final static int MAX_PREFIX_LEN = 10; private final static int NUM_TEST_INPUTS_PER_ROUND = 100; private final static int MAX_INPUT_LEN = 20; private final static char[] alphabet = new char[] { 'a', 'b', 'c', 'd', // 'e', 'f', 'g', 'h', 'i', 'j', // 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', // 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4', // '5', '6', '7', '8', '9', '0' }; private String makeRandString(int minLen, int maxLen) { int len = minLen + (int) (Math.random() * (maxLen - minLen)); char[] chars = new char[len]; for (int pos = 0; pos < len; pos++) { chars[pos] = alphabet[(int) (Math.random() * alphabet.length)]; } return new String(chars); } @Test public void testPrefixMatcher() { int numMatches = 0; int numInputsTested = 0; for (int round = 0; round < NUM_TEST_ROUNDS; round++) { // build list of prefixes int numPrefixes = (int) (Math.random() * MAX_TEST_PREFIXES); String[] prefixes = new String[numPrefixes]; for (int i = 0; i < numPrefixes; i++) { prefixes[i] = makeRandString(0, MAX_PREFIX_LEN); } PrefixStringMatcher prematcher = new PrefixStringMatcher(prefixes); // test random strings for prefix matches for (int i = 0; i < NUM_TEST_INPUTS_PER_ROUND; i++) { String input = makeRandString(0, MAX_INPUT_LEN); boolean matches = false; int longestMatch = -1; int shortestMatch = -1; for (int j = 0; j < prefixes.length; j++) { if ((prefixes[j].length() > 0) && input.startsWith(prefixes[j])) { matches = true; int matchSize = prefixes[j].length(); if (matchSize > longestMatch) longestMatch = matchSize; if ((matchSize < shortestMatch) || (shortestMatch == -1)) shortestMatch = matchSize; } } if (matches) numMatches++; numInputsTested++; Assert.assertTrue("'" + input + "' should " + (matches ? "" : "not ") + "match!", matches == prematcher.matches(input)); if (matches) { Assert.assertTrue(shortestMatch == prematcher.shortestMatch(input) .length()); Assert.assertTrue(input.substring(0, shortestMatch).equals( prematcher.shortestMatch(input))); Assert.assertTrue(longestMatch == prematcher.longestMatch(input) .length()); Assert.assertTrue(input.substring(0, longestMatch).equals( prematcher.longestMatch(input))); } } } System.out.println("got " + numMatches + " matches out of " + numInputsTested + " tests"); } }
1,509
1,317
# # Copyright defined in LICENSE.txt # import os import sys import lmdb import struct import varint def delete_file(filepath): if os.path.exists(filepath): os.remove(filepath) def convert_db(filename1): if not os.path.exists(filename1): print 'the file does not exist' quit() filename2 = filename1 + '-converted' delete_file(filename2) print 'converting', filename, 'to', filename2, '...' env1 = lmdb.open(filename1, subdir=False, max_dbs=1024) env2 = lmdb.open(filename2, subdir=False, max_dbs=1024) pages_db1 = [None] # the first element (0) stores None maxpg_db1 = [None] pages_db2 = [None] # the first element (0) stores None maxpg_db2 = [None] with env1.begin(buffers=True) as txn1: with env2.begin(buffers=True) as txn2: value = txn1.get('last_branch_id') num_branches = struct.unpack('i', value)[0] print 'branches:', num_branches for branch_id in range(1, num_branches + 1): dbname = 'b' + str(branch_id) + '-pages' pages_db1.append(env1.open_db(dbname)) pages_db2.append(env2.open_db(dbname)) dbname = 'b' + str(branch_id) + '-maxpage' maxpg_db1.append(env1.open_db(dbname, integerkey=True)) maxpg_db2.append(env2.open_db(dbname)) with env1.begin(buffers=True) as txn1: with env2.begin(write=True, buffers=True) as txn2: txn2.put('last_branch_id', varint.encode(num_branches)) value = txn1.get('change_counter') value = struct.unpack('i', value)[0] value = varint.encode(value) txn2.put('change_counter', value) for branch_id in range(1, num_branches + 1): prefix = 'b' + str(branch_id) key = prefix + '.name' name = txn1.get(key) print 'processing branch:', name txn2.put(key, name) key = prefix + '.visible' value = txn1.get(key) value = struct.unpack('i', value)[0] value = varint.encode(value) txn2.put(key, value) key = prefix + '.source_branch' value = txn1.get(key) value = struct.unpack('i', value)[0] value = varint.encode(value) txn2.put(key, value) key = prefix + '.source_commit' value = txn1.get(key) value = struct.unpack('i', value)[0] value = varint.encode(value) txn2.put(key, value) key = prefix + '.last_commit' value = txn1.get(key) value = struct.unpack('i', value)[0] value = varint.encode(value) txn2.put(key, value) # iterate all the keys from the sub-db db1 = pages_db1[branch_id] db2 = pages_db2[branch_id] for key, value in txn1.cursor(db=db1): # read the key pgno = struct.unpack('>i', key[0:4])[0] commit = struct.unpack('>i', key[4:8] )[0] print 'page', pgno, 'commit', commit # write the new key key2 = varint.encode(pgno) + varint.encode(commit) txn2.put(key2, value, db=db2) # iterate all the keys from the sub-db db1 = maxpg_db1[branch_id] db2 = maxpg_db2[branch_id] for key, value in txn1.cursor(db=db1): # read the key commit = struct.unpack('i', key)[0] print 'commit', commit # write the new key key2 = varint.encode(commit) txn2.put(key2, value, db=db2) env1.close() env2.close() print 'done. you can open it with the command: sqlite3 "file:' + filename2 + '?branches=on"' if len(sys.argv) == 1: print 'usage: python', sys.argv[0], '<db_file>' quit() filename = sys.argv[1] convert_db(filename)
2,279
428
<gh_stars>100-1000 package loon.live2d; import loon.BaseIO; import loon.geom.Vector2f; import loon.live2d.draw.*; import loon.live2d.framework.L2DModelMatrix; import loon.live2d.graphics.*; import loon.live2d.id.*; import loon.live2d.io.*; import loon.live2d.model.*; import loon.opengl.GLEx; import loon.utils.ArrayByte; public abstract class ALive2DModel { protected static int idNo; protected ModelImpl modelImpl; protected ModelContext modeContext; protected int flagError; static { ALive2DModel.idNo = 0; } public ALive2DModel() { this.modelImpl = null; this.modeContext = null; this.flagError = 0; ++ALive2DModel.idNo; this.modeContext = new ModelContext(this); } public void setModelImpl(final ModelImpl m) { this.modelImpl = m; } public ModelImpl getModelImpl() { if (this.modelImpl == null) { (this.modelImpl = new ModelImpl()).initDirect(); } return this.modelImpl; } public float getCanvasWidth() { if (this.modelImpl == null) { return 0.0f; } return this.modelImpl.getCanvasWidth(); } public float getCanvasHeight() { if (this.modelImpl == null) { return 0.0f; } return this.modelImpl.getCanvasHeight(); } public float getParamFloat(final String paramID) { return this.modeContext .getParamFloat(this.modeContext.getParamIndex(ParamID.getID(paramID))); } public void setParamFloat(final String paramID, final float value) { this.modeContext.setParamFloat(this.modeContext.getParamIndex(ParamID.getID(paramID)), value); } public void setParamFloat(final String paramID, final float value, final float weight) { this.setParamFloat(this.modeContext.getParamIndex(ParamID.getID(paramID)), value, weight); } public void addToParamFloat(final String paramID, final float value) { this.addToParamFloat(paramID, value, 1.0f); } public void addToParamFloat(final String paramID, final float value, final float weight) { this.addToParamFloat(this.modeContext.getParamIndex(ParamID.getID(paramID)), value, weight); } public void multParamFloat(final String paramID, final float mult) { this.multParamFloat(paramID, mult, 1.0f); } public void multParamFloat(final String paramID, final float mult, final float weight) { this.multParamFloat(this.modeContext.getParamIndex(ParamID.getID(paramID)), mult, weight); } public void loadParam() { this.modeContext.loadParam(); } public void saveParam() { this.modeContext.saveParam(); } public void init() { this.modeContext.init(); } public void update() { this.modeContext.update(); } public int generateModelTextureNo() { return -1; } public void releaseModelTextureNo(final int no) { } public abstract void deleteTextures(); public abstract void draw(L2DModelMatrix matrix, GLEx g); public static void loadModel_exe(final ALive2DModel ret, final String filepath) { try { final ArrayByte bin = new ArrayByte(BaseIO.loadBytes(filepath)); loadModel_exe(ret, bin); bin.close(); } catch (Exception ex) { ex.printStackTrace(); } } public static void loadModel_exe(final ALive2DModel ret, final ArrayByte bin) { try { final BReader bReader = new BReader(bin); final byte f = bReader.readByte(); final byte f2 = bReader.readByte(); final byte f3 = bReader.readByte(); if (f != 109 || f2 != 111 || f3 != 99) { throw new Live2DException("Model load error , Unknown fomart."); } final byte ver = bReader.readByte(); bReader.setVersion(ver); if (ver > 11) { ret.flagError |= 0x2; throw new Live2DException( "Model load error , Illegal data version error.\n"); } final ModelImpl modelImpl = (ModelImpl) bReader.reader(); if (ver >= 8 && bReader.readInt() != -2004318072) { ret.flagError |= 0x1; throw new Live2DException("Model load error , EOF not found."); } ret.setModelImpl(modelImpl); ret.getModelContext().init(); } catch (Exception modeContext) { throw new Live2DException(modeContext, "Model load error , Unknown error "); } } public int getParamIndex(final String paramID) { return this.modeContext.getParamIndex(ParamID.getID(paramID)); } public float getParamFloat(final int paramIndex) { return this.modeContext.getParamFloat(paramIndex); } public void setParamFloat(final int paramIndex, final float value) { this.modeContext.setParamFloat(paramIndex, value); } public void setParamFloat(final int paramIndex, final float value, final float weight) { this.modeContext.setParamFloat(paramIndex, this.modeContext.getParamFloat(paramIndex) * (1.0f - weight) + value * weight); } public void addToParamFloat(final int paramIndex, final float value) { this.addToParamFloat(paramIndex, value, 1.0f); } public void addToParamFloat(final int paramIndex, final float value, final float weight) { this.modeContext.setParamFloat(paramIndex, this.modeContext.getParamFloat(paramIndex) + value * weight); } public void multParamFloat(final int paramIndex, final float mult) { this.multParamFloat(paramIndex, mult, 1.0f); } public void multParamFloat(final int paramIndex, final float mult, final float weight) { this.modeContext.setParamFloat(paramIndex, this.modeContext.getParamFloat(paramIndex) * (1.0f + (mult - 1.0f) * weight)); } public ModelContext getModelContext() { return this.modeContext; } public int getErrorFlags() { return this.flagError; } public void setupPartsOpacityGroup_alphaImpl(final String[] paramGroup, final String[] partsIDGroup, final float deltaTimeSec, final float CLEAR_TIME_SEC) { int n = -1; float n2 = 0.0f; final float n3 = 0.5f; final float n4 = 0.15f; if (deltaTimeSec == 0.0f) { for (int i = 0; i < paramGroup.length; ++i) { this.setPartsOpacity(partsIDGroup[i], (this.getParamFloat(paramGroup[i]) != 0.0f) ? 1 : 0); } return; } if (paramGroup.length == 1) { final boolean b = this.getParamFloat(paramGroup[0]) != 0.0f; final String s = partsIDGroup[0]; final float partsOpacity = this.getPartsOpacity(s); final float n5 = deltaTimeSec / CLEAR_TIME_SEC; float opacity; if (b) { opacity = partsOpacity + n5; if (opacity > 1.0f) { opacity = 1.0f; } } else { opacity = partsOpacity - n5; if (opacity < 0.0f) { opacity = 0.0f; } } this.setPartsOpacity(s, opacity); } else { for (int j = 0; j < paramGroup.length; ++j) { if (this.getParamFloat(paramGroup[j]) != 0.0f) { if (n >= 0) { break; } n = j; n2 = this.getPartsOpacity(partsIDGroup[j]) + deltaTimeSec / CLEAR_TIME_SEC; if (n2 > 1.0f) { n2 = 1.0f; } } } if (n < 0) { n = 0; n2 = 1.0f; this.loadParam(); this.setParamFloat(paramGroup[n], n2); this.saveParam(); } for (int k = 0; k < paramGroup.length; ++k) { final String partsID = partsIDGroup[k]; if (n == k) { this.setPartsOpacity(partsID, n2); } else { float partsOpacity2 = this.getPartsOpacity(partsID); float n6; if (n2 < n3) { n6 = n2 * (n3 - 1.0f) / n3 + 1.0f; } else { n6 = (1.0f - n2) * n3 / (1.0f - n3); } if ((1.0f - n6) * (1.0f - n2) > n4) { n6 = 1.0f - n4 / (1.0f - n2); } if (partsOpacity2 > n6) { partsOpacity2 = n6; } this.setPartsOpacity(partsID, partsOpacity2); } } } } public void setPartsOpacity(final String partsID, final float opacity) { final int partsDataIndex = this.modeContext.getPartsDataIndex(PartsDataID .getID(partsID)); if (partsDataIndex < 0) { return; } this.setPartsOpacity(partsDataIndex, opacity); } public void setPartsOpacity(final int partsIndex, final float opacity) { this.modeContext.setPartsOpacity(partsIndex, opacity); } public int getPartsDataIndex(final String partsID) { return this.modeContext.getPartsDataIndex(PartsDataID.getID(partsID)); } public int getPartsDataIndex(final PartsDataID partsID) { return this.modeContext.getPartsDataIndex(partsID); } public float getPartsOpacity(final String partsID) { final int partsDataIndex = this.modeContext.getPartsDataIndex(PartsDataID .getID(partsID)); if (partsDataIndex < 0) { return 0.0f; } return this.getPartsOpacity(partsDataIndex); } public float getPartsOpacity(final int partsIndex) { return this.modeContext.getPartsOpacity(partsIndex); } public abstract DrawParam getDrawParam(); public DrawParam setScale(float sx, float sy) { DrawParam param = getDrawParam(); if (param != null) { param.setScale(sx, sy); return param; } return null; } public DrawParam setLocation(float x, float y) { DrawParam param = getDrawParam(); if (param != null) { param.setLocation(x, y); return param; } return null; } public Vector2f getDrawParamScale() { DrawParam param = getDrawParam(); if (param != null) { return param.getScale(); } return new Vector2f(1f, 1f); } public Vector2f getDrawParamLocation() { DrawParam param = getDrawParam(); if (param != null) { return param.getLocation(); } return new Vector2f(0, 0); } public int getDrawDataIndex(final String drawDataID) { return this.modeContext.getDrawDataIndex(DrawDataID.getID(drawDataID)); } public IDrawData getDrawData(final int drawIndex) { return this.modeContext.getDrawData(drawIndex); } public float[] getTransformedPoints(final int drawIndex) { final IDrawContext drawContext = this.modeContext.getDrawContext(drawIndex); if (drawContext instanceof DrawDataImpl.aa) { return ((DrawDataImpl.aa) drawContext).a(); } return null; } public short[] getIndexArray(final int drawIndex) { final IDrawData drawData = this.modeContext.getDrawData(drawIndex); if (drawData instanceof DrawDataImpl) { return ((DrawDataImpl) drawData).h(); } return null; } public void setPremultipliedAlpha(final boolean b) { this.getDrawParam().setPremultipliedAlpha(b); } public boolean isPremultipliedAlpha() { return this.getDrawParam().isPremultipliedAlpha(); } }
3,915
575
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_APP_HISTORY_APP_HISTORY_NAVIGATE_EVENT_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_APP_HISTORY_APP_HISTORY_NAVIGATE_EVENT_H_ #include "third_party/blink/public/web/web_frame_load_type.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise.h" #include "third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value.h" #include "third_party/blink/renderer/core/dom/events/event.h" #include "third_party/blink/renderer/core/execution_context/execution_context_lifecycle_observer.h" #include "third_party/blink/renderer/platform/heap/heap_allocator.h" #include "third_party/blink/renderer/platform/heap/member.h" #include "third_party/blink/renderer/platform/supplementable.h" #include "third_party/blink/renderer/platform/weborigin/kurl.h" namespace blink { class AppHistory; class AppHistoryNavigateEventInit; class ExceptionState; class FormData; class ScriptPromise; class AppHistoryNavigateEvent final : public Event, public ExecutionContextClient { DEFINE_WRAPPERTYPEINFO(); public: static AppHistoryNavigateEvent* Create(ExecutionContext* context, const AtomicString& type, AppHistoryNavigateEventInit* init) { return MakeGarbageCollected<AppHistoryNavigateEvent>(context, type, init); } AppHistoryNavigateEvent(ExecutionContext* context, const AtomicString& type, AppHistoryNavigateEventInit* init); bool Fire(AppHistory*, bool same_document); void SetUrl(const KURL& url) { url_ = url; } void SetFrameLoadType(WebFrameLoadType type) { frame_load_type_ = type; } void SetStateObject(SerializedScriptValue* state) { state_object_ = state; } bool canRespond() const { return can_respond_; } bool userInitiated() const { return user_initiated_; } bool hashChange() const { return hash_change_; } FormData* formData() const { return form_data_; } void respondWith(ScriptState*, ScriptPromise newNavigationAction, ExceptionState&); const AtomicString& InterfaceName() const final; void Trace(Visitor*) const final; private: bool can_respond_; bool user_initiated_; bool hash_change_; Member<FormData> form_data_; KURL url_; WebFrameLoadType frame_load_type_ = WebFrameLoadType::kStandard; scoped_refptr<SerializedScriptValue> state_object_; ScriptPromise completion_promise_; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_CORE_APP_HISTORY_APP_HISTORY_NAVIGATE_EVENT_H_
1,077
5,169
{ "name": "LFBPageController", "version": "1.0.0", "summary": "一款仿网易标题滚动切换页面的框架", "description": "简单易容的标题滚动切换页面框架,通过点击标题或者滑动页面,切换页面和标题...", "homepage": "https://github.com/LiuFuBo1991/LFBPageController", "license": "MIT", "authors": { "liufubo": "<EMAIL>" }, "social_media_url": "http://www.jianshu.com/u/7d935e492eec", "platforms": { "ios": "8.0" }, "source": { "git": "https://github.com/LiuFuBo1991/LFBPageController.git", "tag": "1.0.0" }, "source_files": [ "LFBPageController", "LFBPageController/**/*.{h,m,md}" ], "requires_arc": true }
377
852
<reponame>ckamtsikis/cmssw #include "CalibFormats/SiPixelObjects/interface/PixelFEDTestDAC.h" #include "CalibFormats/SiPixelObjects/interface/PixelTimeFormatter.h" #include <cstring> #include <cassert> #include <map> #include <sstream> using namespace std; using namespace pos; PixelFEDTestDAC::PixelFEDTestDAC(std::vector<std::vector<std::string> > &tableMat) { std::string mthn = "[PixelFEDTestDAC::PixelFEDTestDAC()]\t\t\t "; const unsigned long int UB = 200; const unsigned long int B = 500; const unsigned long int offset = 0; vector<unsigned int> pulseTrain(256), pixelDCol(1), pixelPxl(2), pixelTBMHeader(3), pixelTBMTrailer(3); unsigned int DCol, LorR, start = 15; std::string line; std::string::size_type loc1, loc2, loc3, loc4; unsigned long int npos = std::string::npos; int i; std::map<std::string, int> colM; std::vector<std::string> colNames; /** EXTENSION_TABLE_NAME: PIXEL_CALIB_CLOB (VIEW: CONF_KEY_PIXEL_CALIB_V) CONFIG_KEY NOT NULL VARCHAR2(80) KEY_TYPE NOT NULL VARCHAR2(80) KEY_ALIAS NOT NULL VARCHAR2(80) VERSION VARCHAR2(40) KIND_OF_COND NOT NULL VARCHAR2(40) CALIB_TYPE VARCHAR2(200) CALIB_OBJ_DATA_FILE NOT NULL VARCHAR2(200) CALIB_OBJ_DATA_CLOB NOT NULL CLOB */ colNames.push_back("CONFIG_KEY"); colNames.push_back("KEY_TYPE"); colNames.push_back("KEY_ALIAS"); colNames.push_back("VERSION"); colNames.push_back("KIND_OF_COND"); colNames.push_back("CALIB_TYPE"); colNames.push_back("CALIB_OBJ_DATA_FILE"); colNames.push_back("CALIB_OBJ_DATA_CLOB"); for (unsigned int c = 0; c < tableMat[0].size(); c++) { for (unsigned int n = 0; n < colNames.size(); n++) { if (tableMat[0][c] == colNames[n]) { colM[colNames[n]] = c; break; } } } //end for for (unsigned int n = 0; n < colNames.size(); n++) { if (colM.find(colNames[n]) == colM.end()) { std::cerr << __LINE__ << "]\t" << mthn << "Couldn't find in the database the column with name " << colNames[n] << std::endl; assert(0); } } std::istringstream fin; fin.str(tableMat[1][colM["CALIB_OBJ_DATA_CLOB"]]); // Initialise the pulseTrain to offset+black for (unsigned int i = 0; i < pulseTrain.size(); ++i) { pulseTrain[i] = offset + B; } i = start; getline(fin, line); mode_ = line; assert(mode_ == "EmulatedPhysics" || mode_ == "FEDBaselineWithTestDACs" || mode_ == "FEDAddressLevelWithTestDACs"); while (!fin.eof()) { getline(fin, line); if (line.find("TBMHeader") != npos) { loc1 = line.find('('); if (loc1 == npos) { cout << __LINE__ << "]\t" << mthn << "'(' not found after TBMHeader.\n"; break; } loc2 = line.find(')', loc1 + 1); if (loc2 == npos) { cout << __LINE__ << "]\t" << mthn << "')' not found after TBMHeader.\n"; break; } int TBMHeader = atoi(line.substr(loc1 + 1, loc2 - loc1 - 1).c_str()); pulseTrain[i] = UB; ++i; pulseTrain[i] = UB; ++i; pulseTrain[i] = UB; ++i; pulseTrain[i] = B; ++i; pixelTBMHeader = decimalToBaseX(TBMHeader, 4, 4); pulseTrain[i] = levelEncoder(pixelTBMHeader[3]); ++i; pulseTrain[i] = levelEncoder(pixelTBMHeader[2]); ++i; pulseTrain[i] = levelEncoder(pixelTBMHeader[1]); ++i; pulseTrain[i] = levelEncoder(pixelTBMHeader[0]); ++i; } else if (line.find("ROCHeader") != std::string::npos) { loc1 = line.find('('); if (loc1 == npos) { cout << __LINE__ << "]\t" << mthn << "'(' not found after ROCHeader.\n"; break; } loc2 = line.find(')', loc1 + 1); if (loc2 == npos) { cout << __LINE__ << "]\t" << mthn << "')' not found after ROCHeader.\n"; break; } int LastDAC = atoi(line.substr(loc1 + 1, loc2 - loc1 - 1).c_str()); std::cout << "--------------" << std::endl; pulseTrain[i] = UB; ++i; pulseTrain[i] = B; ++i; pulseTrain[i] = levelEncoder(LastDAC); ++i; } else if (line.find("PixelHit") != std::string::npos) { loc1 = line.find('('); if (loc1 == npos) { cout << __LINE__ << "]\t" << mthn << "'(' not found after PixelHit.\n"; break; } loc2 = line.find(',', loc1 + 1); if (loc2 == npos) { cout << __LINE__ << "]\t" << mthn << "',' not found after the first argument of PixelHit.\n"; break; } loc3 = line.find(',', loc2 + 1); if (loc3 == npos) { cout << __LINE__ << "]\t" << mthn << "'.' not found after the second argument of PixelHit.\n"; break; } loc4 = line.find(')', loc3 + 1); if (loc4 == npos) { cout << __LINE__ << "]\t" << mthn << "')' not found after the third argument of PixelHit.\n"; break; } int column = atoi(line.substr(loc1 + 1, loc2 - loc1 - 1).c_str()); int row = atoi(line.substr(loc2 + 1, loc3 - loc2 - 1).c_str()); int charge = atoi(line.substr(loc3 + 1, loc4 - loc3 - 1).c_str()); DCol = int(column / 2); LorR = int(column - DCol * 2); pixelDCol = decimalToBaseX(DCol, 6, 2); pixelPxl = decimalToBaseX((80 - row) * 2 + LorR, 6, 3); std::cout << "Pxl = " << pixelPxl[2] << pixelPxl[1] << pixelPxl[0] << ", DCol= " << pixelDCol[1] << pixelDCol[0] << std::endl; pulseTrain[i] = levelEncoder(pixelDCol[1]); ++i; pulseTrain[i] = levelEncoder(pixelDCol[0]); ++i; pulseTrain[i] = levelEncoder(pixelPxl[2]); ++i; pulseTrain[i] = levelEncoder(pixelPxl[1]); ++i; pulseTrain[i] = levelEncoder(pixelPxl[0]); ++i; pulseTrain[i] = charge; ++i; } else if (line.find("TBMTrailer") != std::string::npos) { loc1 = line.find('('); if (loc1 == npos) { cout << __LINE__ << "]\t" << mthn << "'(' not found after TBMTrailer.\n"; break; } loc2 = line.find(')', loc1 + 1); if (loc2 == npos) { cout << __LINE__ << "]\t" << mthn << "')' not found after TBMTrailer.\n"; break; } int TBMTrailer = atoi(line.substr(loc1 + 1, loc2 - loc1 - 1).c_str()); pulseTrain[i] = UB; ++i; pulseTrain[i] = UB; ++i; pulseTrain[i] = B; ++i; pulseTrain[i] = B; ++i; pixelTBMTrailer = decimalToBaseX(TBMTrailer, 4, 4); pulseTrain[i] = levelEncoder(pixelTBMTrailer[3]); ++i; pulseTrain[i] = levelEncoder(pixelTBMTrailer[2]); ++i; pulseTrain[i] = levelEncoder(pixelTBMTrailer[1]); ++i; pulseTrain[i] = levelEncoder(pixelTBMTrailer[0]); ++i; } } // fin.close(); dacs_ = pulseTrain; } PixelFEDTestDAC::PixelFEDTestDAC(std::string filename) { std::string mthn = "[PixelFEDTestDAC::PixelFEDTestDAC()]\t\t\t\t "; const unsigned long int UB = 200; const unsigned long int B = 500; const unsigned long int offset = 0; vector<unsigned int> pulseTrain(256), pixelDCol(1), pixelPxl(2), pixelTBMHeader(3), pixelTBMTrailer(3); unsigned int DCol, LorR, start = 15; std::string line; std::string::size_type loc1, loc2, loc3, loc4; unsigned long int npos = std::string::npos; int i; // Initialise the pulseTrain to offset+black for (unsigned int i = 0; i < pulseTrain.size(); ++i) { pulseTrain[i] = offset + B; } ifstream fin(filename.c_str()); i = start; getline(fin, line); mode_ = line; assert(mode_ == "EmulatedPhysics" || mode_ == "FEDBaselineWithTestDACs" || mode_ == "FEDAddressLevelWithTestDACs"); while (!fin.eof()) { getline(fin, line); if (line.find("TBMHeader") != npos) { loc1 = line.find('('); if (loc1 == npos) { cout << __LINE__ << "]\t" << mthn << "'(' not found after TBMHeader.\n"; break; } loc2 = line.find(')', loc1 + 1); if (loc2 == npos) { cout << __LINE__ << "]\t" << mthn << "')' not found after TBMHeader.\n"; break; } int TBMHeader = atoi(line.substr(loc1 + 1, loc2 - loc1 - 1).c_str()); pulseTrain[i] = UB; ++i; pulseTrain[i] = UB; ++i; pulseTrain[i] = UB; ++i; pulseTrain[i] = B; ++i; pixelTBMHeader = decimalToBaseX(TBMHeader, 4, 4); pulseTrain[i] = levelEncoder(pixelTBMHeader[3]); ++i; pulseTrain[i] = levelEncoder(pixelTBMHeader[2]); ++i; pulseTrain[i] = levelEncoder(pixelTBMHeader[1]); ++i; pulseTrain[i] = levelEncoder(pixelTBMHeader[0]); ++i; } else if (line.find("ROCHeader") != std::string::npos) { loc1 = line.find('('); if (loc1 == npos) { cout << __LINE__ << "]\t" << mthn << "'(' not found after ROCHeader.\n"; break; } loc2 = line.find(')', loc1 + 1); if (loc2 == npos) { cout << __LINE__ << "]\t" << mthn << "')' not found after ROCHeader.\n"; break; } int LastDAC = atoi(line.substr(loc1 + 1, loc2 - loc1 - 1).c_str()); std::cout << "--------------" << std::endl; pulseTrain[i] = UB; ++i; pulseTrain[i] = B; ++i; pulseTrain[i] = levelEncoder(LastDAC); ++i; } else if (line.find("PixelHit") != std::string::npos) { loc1 = line.find('('); if (loc1 == npos) { cout << __LINE__ << "]\t" << mthn << "'(' not found after PixelHit.\n"; break; } loc2 = line.find(',', loc1 + 1); if (loc2 == npos) { cout << __LINE__ << "]\t" << mthn << "',' not found after the first argument of PixelHit.\n"; break; } loc3 = line.find(',', loc2 + 1); if (loc3 == npos) { cout << __LINE__ << "]\t" << mthn << "'.' not found after the second argument of PixelHit.\n"; break; } loc4 = line.find(')', loc3 + 1); if (loc4 == npos) { cout << __LINE__ << "]\t" << mthn << "')' not found after the third argument of PixelHit.\n"; break; } int column = atoi(line.substr(loc1 + 1, loc2 - loc1 - 1).c_str()); int row = atoi(line.substr(loc2 + 1, loc3 - loc2 - 1).c_str()); int charge = atoi(line.substr(loc3 + 1, loc4 - loc3 - 1).c_str()); DCol = int(column / 2); LorR = int(column - DCol * 2); pixelDCol = decimalToBaseX(DCol, 6, 2); pixelPxl = decimalToBaseX((80 - row) * 2 + LorR, 6, 3); std::cout << "Pxl = " << pixelPxl[2] << pixelPxl[1] << pixelPxl[0] << ", DCol= " << pixelDCol[1] << pixelDCol[0] << std::endl; pulseTrain[i] = levelEncoder(pixelDCol[1]); ++i; pulseTrain[i] = levelEncoder(pixelDCol[0]); ++i; pulseTrain[i] = levelEncoder(pixelPxl[2]); ++i; pulseTrain[i] = levelEncoder(pixelPxl[1]); ++i; pulseTrain[i] = levelEncoder(pixelPxl[0]); ++i; pulseTrain[i] = charge; ++i; } else if (line.find("TBMTrailer") != std::string::npos) { loc1 = line.find('('); if (loc1 == npos) { cout << __LINE__ << "]\t" << mthn << "'(' not found after TBMTrailer.\n"; break; } loc2 = line.find(')', loc1 + 1); if (loc2 == npos) { cout << __LINE__ << "]\t" << mthn << "')' not found after TBMTrailer.\n"; break; } int TBMTrailer = atoi(line.substr(loc1 + 1, loc2 - loc1 - 1).c_str()); pulseTrain[i] = UB; ++i; pulseTrain[i] = UB; ++i; pulseTrain[i] = B; ++i; pulseTrain[i] = B; ++i; pixelTBMTrailer = decimalToBaseX(TBMTrailer, 4, 4); pulseTrain[i] = levelEncoder(pixelTBMTrailer[3]); ++i; pulseTrain[i] = levelEncoder(pixelTBMTrailer[2]); ++i; pulseTrain[i] = levelEncoder(pixelTBMTrailer[1]); ++i; pulseTrain[i] = levelEncoder(pixelTBMTrailer[0]); ++i; } } fin.close(); dacs_ = pulseTrain; } unsigned int PixelFEDTestDAC::levelEncoder(int level) { unsigned int pulse; switch (level) { case 0: pulse = 450; break; case 1: pulse = 500; break; case 2: pulse = 550; break; case 3: pulse = 600; break; case 4: pulse = 650; break; case 5: pulse = 700; break; default: assert(0); break; } return pulse; } vector<unsigned int> PixelFEDTestDAC::decimalToBaseX(unsigned int a, unsigned int x, unsigned int length) { vector<unsigned int> ans(100, 0); int i = 0; while (a > 0) { ans[i] = a % x; //ans.push_back(a%x); a = a / x; i += 1; } if (length > 0) ans.resize(length); else ans.resize(i); return ans; } //============================================================================================= void PixelFEDTestDAC::writeXMLHeader(pos::PixelConfigKey key, int version, std::string path, std::ofstream *outstream, std::ofstream *out1stream, std::ofstream *out2stream) const { std::string mthn = "[PixelFEDTestDAC::writeXMLHeader()]\t\t\t "; std::stringstream maskFullPath; // writeASCII(path) ; maskFullPath << path << "/PixelCalib_Test_" << PixelTimeFormatter::getmSecTime() << ".xml"; std::cout << __LINE__ << "]\t" << mthn << "Writing to: " << maskFullPath.str() << std::endl; outstream->open(maskFullPath.str().c_str()); *outstream << "<?xml version='1.0' encoding='UTF-8' standalone='yes'?>" << std::endl; *outstream << "<ROOT xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>" << std::endl; *outstream << "" << std::endl; *outstream << " <HEADER>" << std::endl; *outstream << " <TYPE>" << std::endl; *outstream << " <EXTENSION_TABLE_NAME>PIXEL_CALIB_CLOB</EXTENSION_TABLE_NAME>" << std::endl; *outstream << " <NAME>Calibration Object Clob</NAME>" << std::endl; *outstream << " </TYPE>" << std::endl; *outstream << " <RUN>" << std::endl; *outstream << " <RUN_TYPE>PixelFEDTestDAC</RUN_TYPE>" << std::endl; *outstream << " <RUN_NUMBER>1</RUN_NUMBER>" << std::endl; *outstream << " <RUN_BEGIN_TIMESTAMP>" << PixelTimeFormatter::getTime() << "</RUN_BEGIN_TIMESTAMP>" << std::endl; *outstream << " <LOCATION>CERN P5</LOCATION>" << std::endl; *outstream << " </RUN>" << std::endl; *outstream << " </HEADER>" << std::endl; *outstream << "" << std::endl; *outstream << " <DATA_SET>" << std::endl; *outstream << "" << std::endl; *outstream << " <VERSION>" << version << "</VERSION>" << std::endl; *outstream << " <COMMENT_DESCRIPTION>No comment defined: this class does NOT inherit from " "PixelCalibBase</COMMENT_DESCRIPTION>" << std::endl; *outstream << " <CREATED_BY_USER>Unknown user</CREATED_BY_USER>" << std::endl; *outstream << "" << std::endl; *outstream << " <PART>" << std::endl; *outstream << " <NAME_LABEL>CMS-PIXEL-ROOT</NAME_LABEL>" << std::endl; *outstream << " <KIND_OF_PART>Detector ROOT</KIND_OF_PART>" << std::endl; *outstream << " </PART>" << std::endl; } //============================================================================================= void PixelFEDTestDAC::writeXML(std::ofstream *outstream, std::ofstream *out1stream, std::ofstream *out2stream) const { std::string mthn = "[PixelFEDTestDAC::writeXML()]\t\t\t "; *outstream << " " << std::endl; *outstream << " <DATA>" << std::endl; *outstream << " <CALIB_OBJ_DATA_FILE>./fedtestdac.dat</CALIB_OBJ_DATA_FILE>" << std::endl; *outstream << " <CALIB_TYPE>fedtestdac</CALIB_TYPE>" << std::endl; *outstream << " </DATA>" << std::endl; *outstream << " " << std::endl; } //============================================================================================= void PixelFEDTestDAC::writeXMLTrailer(std::ofstream *outstream, std::ofstream *out1stream, std::ofstream *out2stream) const { std::string mthn = "[PixelFEDTestDAC::writeXMLTrailer()]\t\t\t "; *outstream << " </DATA_SET>" << std::endl; *outstream << "</ROOT>" << std::endl; outstream->close(); std::cout << __LINE__ << "]\t" << mthn << "Data written " << std::endl; }
7,654
884
/* * Copyright 2014 - 2021 Blazebit. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blazebit.persistence; /** * An interface for builders that support sorting. * This is related to the fact, that a query builder supports order by clauses. * * @param <T> The concrete builder type * @author <NAME> * @since 1.0.0 */ public interface OrderByBuilder<T extends OrderByBuilder<T>> { /** * Like {@link BaseQueryBuilder#orderBy(java.lang.String, boolean, boolean) } but with <code>nullFirst</code> set to false. * * @param expression The expression for the order by clause * @param ascending Wether the order should be ascending or descending. * @return The query builder for chaining calls * @since 1.4.0 */ public T orderBy(String expression, boolean ascending); /** * Adds an order by clause with the given expression to the query. * * @param expression The expression for the order by clause * @param ascending Wether the order should be ascending or descending. * @param nullFirst Wether null elements should be ordered first or not. * @return The query builder for chaining calls */ public T orderBy(String expression, boolean ascending, boolean nullFirst); /** * Like {@link BaseQueryBuilder#orderByAsc(java.lang.String, boolean) } but with <code>nullFirst</code> set to false. * * @param expression The expression for the order by clause * @return The query builder for chaining calls */ public T orderByAsc(String expression); /** * Like {@link BaseQueryBuilder#orderBy(java.lang.String, boolean, boolean) } but with <code>ascending</code> set to true. * * @param expression The expression for the order by clause * @param nullFirst Wether null elements should be ordered first or not. * @return The query builder for chaining calls */ public T orderByAsc(String expression, boolean nullFirst); /** * Like {@link BaseQueryBuilder#orderByDesc(java.lang.String, boolean) } but with <code>nullFirst</code> set to false. * * @param expression The expression for the order by clause * @return The query builder for chaining calls */ public T orderByDesc(String expression); /** * Like {@link BaseQueryBuilder#orderBy(java.lang.String, boolean, boolean) } but with <code>ascending</code> set to false. * * @param expression The expression for the order by clause * @param nullFirst Wether null elements should be ordered first or not. * @return The query builder for chaining calls */ public T orderByDesc(String expression, boolean nullFirst); // NOTE: JPA 4.6.16 says that subqueries are only allowed in WHERE and HAVING // TODO: order by subqueries? }
1,019
1,761
# Sensor Sleep Mode Example. # This example demonstrates the sensor sleep mode. The sleep mode saves around # 40mA when enabled and it's automatically cleared when calling sensor reset(). import sensor, image, time sensor.reset() # Reset and initialize the sensor. sensor.set_pixformat(sensor.GRAYSCALE) # Set pixel format to RGB565 (or GRAYSCALE) sensor.set_framesize(sensor.QVGA) # Set frame size to QVGA (320x240) sensor.skip_frames(time = 3000) # Capture frames for 3000ms. sensor.sleep(True) # Enable sensor sleep mode (saves about 40mA).
204
6,215
# # Copyright (c) 2021 Airbyte, Inc., all rights reserved. # import json from abc import ABC from datetime import datetime from typing import Any, Dict, Iterable, List, Mapping, MutableMapping, Optional, Tuple import pendulum import requests from airbyte_cdk import AirbyteLogger from airbyte_cdk.models import AirbyteStream, SyncMode from airbyte_cdk.sources import AbstractSource from airbyte_cdk.sources.streams.http import HttpStream from .zuora_auth import ZuoraAuthenticator from .zuora_endpoint import get_url_base from .zuora_errors import ( ZOQLQueryCannotProcessObject, ZOQLQueryFailed, ZOQLQueryFieldCannotResolveAltCursor, ZOQLQueryFieldCannotResolveCursor, ) from .zuora_excluded_streams import ZUORA_EXCLUDED_STREAMS class ZuoraStream(HttpStream, ABC): """ Parent class for all other classes, except of SourceZuora. """ # Define primary key primary_key = "id" # Define possible cursor_fields cursor_field = "updateddate" alt_cursor_field = "createddate" def __init__(self, config: Dict): super().__init__(authenticator=config["authenticator"]) self._url_base = config["url_base"] self.start_date = config["start_date"] self.window_in_days = config["window_in_days"] self._config = config @property def url_base(self) -> str: return self._url_base def next_page_token(self, response: requests.Response) -> Optional[Mapping[str, Any]]: """ Abstractmethod HTTPStream CDK dependency """ return None def request_params(self, stream_state: Mapping[str, Any], **kwargs) -> MutableMapping[str, Any]: """ Abstractmethod HTTPStream CDK dependency """ return {} def base_query_params(self, stream_state: Mapping[str, Any], **kwargs) -> MutableMapping[str, Any]: """ Returns base query parameters for default CDK request_json_body method """ return {"compression": "NONE", "output": {"target": "S3"}, "outputFormat": "JSON"} class ZuoraBase(ZuoraStream): """ Base child class, provides main functionality for next classes: - ZuoraObjectsBase, ZuoraListObjects, ZuoraDescribeObject """ def path(self, **kwargs) -> str: """ Abstractmethod HTTPStream CDK dependency """ return "" def request_kwargs(self, stream_slice: Mapping[str, Any] = None, **kwargs) -> Mapping[str, Any]: """ Override of default CDK method to return date_slices as stream_slices """ return stream_slice if stream_slice else {} def get_zuora_data(self, date_slice: Dict, config: Dict, full_object: bool = False) -> Iterable[Mapping[str, Any]]: """ This is the wrapper for 'Submit > Check > Get' operation. :: job_id - string with submited job_id EXAMPLE: '5a96ee43-e874-4a25-a9b4-004b39fe82a4' for more information see: ZuoraSubmitJob :: job_data_url - response object with: - 'queryStatus': ["completed", "in_progress", "failed", "canceled", "aborted"], - 'errorMessage': if there in any error on the server side during job execution - 'dataFile': if the execution was succesfull returns URL for jsonl file for more information see: ZuoraJobStatusCheck :: ZuoraGetJobResult - reads the 'dataFile' URL and outputs the data records for completed job for more information see: ZuoraGetJobResult :: full_object - boolean, indicates whether to fetch the whole object without any filtering, default `False` """ if full_object: # If the cursor is not available, we fetch whole object job_query = self.query(stream_name=self.name, full_object=True) else: # Default prepared job with Cursor job_query = self.query(stream_name=self.name, cursor_field=self.cursor_field, date_slice=date_slice) job_id: List[str] = ZuoraSubmitJob(job_query, config).read_records(sync_mode=None) job_data_url: List = ZuoraJobStatusCheck(list(job_id)[0], config).read_records(sync_mode=None) yield from ZuoraGetJobResult(list(job_data_url)[0]).read_records(sync_mode=None) def _send_request(self, request: requests.PreparedRequest, request_kwargs: Mapping[str, Any]) -> requests.Response: """ Override for _send_request CDK method to send HTTP request to the Zuora API """ try: # try to fetch with default cursor_field = UpdatedDate yield from self.get_zuora_data(date_slice=request_kwargs, config=self._config) except ZOQLQueryCannotProcessObject: # do nothing if we cannot resolve the object pass except ZOQLQueryFieldCannotResolveCursor: """ The default cursor_field is "updateddate" sometimes it's not supported by certain streams. We need to swith the default cursor field to alternative one, and retry again the whole operation, submit the new job to the server. We also need to save the state in the end of the sync. So this switch is needed as fast and easy way of resolving the cursor_field for streams that support only the "createddate" """ # cursor_field switch to alternative = CreatedDate self.cursor_field = self.alt_cursor_field try: """ The alternative cursor_field is "createddate", it could be also not available for some custom objects. In this case, we fetch the whole object without any filtering. """ # retry the whole operation with alternative cursor yield from self.get_zuora_data(date_slice=request_kwargs, config=self._config) except ZOQLQueryFieldCannotResolveAltCursor: # if we fail to use the alternative cursor - fetch the whole object # retry the whole operation yield from self.get_zuora_data(date_slice=request_kwargs, config=self._config, full_object=True) except ZOQLQueryCannotProcessObject: # do nothing if we cannot resolve the object pass def parse_response(self, response: requests.Response, **kwargs) -> str: yield from response class ZuoraObjectsBase(ZuoraBase): """ Main class for all the Zuora data streams (Zuora Object names), provides functionality for dynamically created classes as streams of data. """ @property def state_checkpoint_interval(self) -> int: return self.window_in_days @staticmethod def to_datetime_str(date: datetime) -> str: """ Custom method. Returns the formated datetime string in a way Zuora API endpoint recognises it as timestamp. :: Output example: '2021-07-15 07:45:55 -07:00' FROMAT : "%Y-%m-%d %H:%M:%S.%f %Z" """ return date.strftime("%Y-%m-%d %H:%M:%S.%f %Z") def get_cursor_from_schema(self, schema: Dict) -> str: """ Get the cursor_field from the stream's schema rather that take it from the class attribute If the stream doesn't support 'updateddate', then we use 'createddate'. If the stream doesn't support 'createddate', then stream is `full_refresh` only. """ if self.cursor_field in schema: # when UpdatedDate is availalbe return self.cursor_field elif self.alt_cursor_field in schema: # when CreatedDate is availalbe return self.alt_cursor_field else: return None def get_json_schema(self) -> Mapping[str, Any]: """ Override get_json_schema CDK method to retrieve the schema information for Zuora Object dynamicaly. """ schema = list(ZuoraDescribeObject(self.name, config=self._config).read_records(sync_mode=None)) return {"type": "object", "properties": {key: d[key] for d in schema for key in d}} def as_airbyte_stream(self) -> AirbyteStream: """ Override as_airbyte_stream CDK method to replace default 'default_cursor_field' behaviour, :: We use the cursor_field defined inside schema instead of using class attribute by default. :: But we still need the default class attribute 'cursor_field' in order to CDK read_records works properly. """ stream = super().as_airbyte_stream() stream_cursor = self.get_cursor_from_schema(stream.json_schema["properties"]) if stream_cursor: stream.default_cursor_field = [stream_cursor] else: # When there is no cursor available in the stream, we do Full-Refresh only. stream.supported_sync_modes = [SyncMode.full_refresh] stream.source_defined_cursor = True # default CDK for full-refresh stream.default_cursor_field = [] # default CDK for full-refresh return stream def get_updated_state(self, current_stream_state: MutableMapping[str, Any], latest_record: Mapping[str, Any]) -> Mapping[str, Any]: """ Update the state value, default CDK method. """ updated_state = max(latest_record.get(self.cursor_field, ""), current_stream_state.get(self.cursor_field, "")) return {self.cursor_field: updated_state} if updated_state else {} def query(self, stream_name: str, cursor_field: str = None, date_slice: Dict = None, full_object: bool = False) -> str: """ Custom method. Returns the SQL-like query in a way Zuora API endpoint accepts the jobs. """ if full_object: return f"""select * from {stream_name}""" return f""" select * from {stream_name} where {cursor_field} >= TIMESTAMP '{date_slice.get('start_date')}' and {cursor_field} <= TIMESTAMP '{date_slice.get('end_date')}' order by {cursor_field} asc """ def stream_slices(self, stream_state: Mapping[str, Any] = None, **kwargs) -> Iterable[Optional[Mapping[str, Any]]]: """ Override default stream_slices CDK method to provide date_slices as page chunks for data fetch. Returns list of dict, example: { "start_date": "2020-01-01 00:00:00 -07:00", "end_date": "2021-12-31 00:00:00 -07:00" }, ... """ start_date = pendulum.parse(self.start_date).astimezone() end_date = pendulum.now().astimezone() # Determine stream_state, if no stream_state we use start_date if stream_state: state = stream_state.get(self.cursor_field, stream_state.get(self.alt_cursor_field)) start_date = pendulum.parse(state) if state else self.start_date # use the lowest date between start_date and self.end_date, otherwise API fails if start_date is in future start_date = min(start_date, end_date) date_slices = [] while start_date <= end_date: end_date_slice = start_date.add(days=self.window_in_days) date_slices.append({"start_date": self.to_datetime_str(start_date), "end_date": self.to_datetime_str(end_date_slice)}) start_date = end_date_slice return date_slices class ZuoraListObjects(ZuoraBase): """ Provides functionality to retrieve the list of Zuora Objects as list of object names. """ def query(self, **kwargs) -> str: return "SHOW TABLES" def parse_response(self, response: requests.Response, **kwargs) -> Iterable[Mapping]: self.logger.info("Retrieving the list of available Objects from Zuora") return [name["Table"] for name in response] class ZuoraDescribeObject(ZuoraBase): """ Provides functionality to retrive Zuora Object (stream) schema dynamicaly from the endpoint, convert it into JSONSchema types, for the connector's catalog. """ def __init__(self, zuora_object_name: str, config: Dict): super().__init__(config) self.zuora_object_name = zuora_object_name def query(self, **kwargs) -> str: self.logger.info(f"Getting schema information for {self.zuora_object_name}") return f"DESCRIBE {self.zuora_object_name}" def parse_response(self, response: requests.Response, **kwargs) -> List[Dict]: """ Response example: [ {'Column': 'taxexempteffectivedate', 'Type': 'date', 'Extra': '', 'Comment': 'TaxExemptEffectiveDate'}, {'Column': 'invoicetemplateid', 'Type': 'varchar', 'Extra': '', 'Comment': 'InvoiceTemplateId'}... ] """ type_number = ["number", "null"] type_string = ["string", "null"] type_object = ["object", "null"] type_array = ["array", "null"] type_bool = ["boolean", "null"] type_mapping = { "decimal(22,9)": type_number, "decimal": type_number, "integer": type_number, "int": type_number, "bigint": type_number, "smallint": type_number, "double": type_number, "float": type_number, "timestamp": type_number, "date": type_string, "datetime": type_string, "timestamp with time zone": type_string, "picklist": type_string, "text": type_string, "varchar": type_string, "zoql": type_object, "binary": type_object, "json": type_object, "xml": type_object, "blob": type_object, "list": type_array, "array": type_array, "boolean": type_bool, "bool": type_bool, } json_schema = {} for field in response: json_type = type_mapping.get(field.get("Type"), type_string) json_schema[field.get("Column")] = {"type": json_type} return [json_schema] class ZuoraSubmitJob(ZuoraStream): """ Provides functionality to submit ZOQL Data Query job on the server. Return job_id as comfirmation of the successfully submited job. """ http_method = "POST" def __init__(self, query: str, config: Dict): super().__init__(config) self.query = query def path(self, **kwargs) -> str: return "/query/jobs" def request_body_json(self, **kwargs) -> Optional[Mapping]: """ Override of default CDK method to return SQL-like query and use it in _send_request method. """ params = self.base_query_params(stream_state=None) params["query"] = self.query return params def parse_response(self, response: requests.Response, **kwargs) -> List[str]: """ Response example: {'data': { 'id': 'c6f25f91-5357-4fec-a00d-9009cc1ae856', 'query': 'DESCRIBE account', # This could be SELECT statement or DESCRIBE or SHOW {object} 'useIndexJoin': False, 'sourceData': 'LIVE', 'queryStatus': 'accepted', 'remainingRetries': 3, 'retries': 3, 'updatedOn': '2021-07-26T15:33:48.287Z', 'createdBy': '84f78cea-8a5b-4332-933f-27439fe3b87b' } } """ return [response.json()["data"]["id"]] class ZuoraJobStatusCheck(ZuoraStream): """ Provedes functionaluty to check the status of submited job on the server. :: There are ["completed", "in_progress", "failed", "canceled", "aborted"] statuses available in check response. The check operation returns either dataFile URL or error message describing the error. """ def __init__(self, job_id: str, config: Dict): super().__init__(config) self.job_id = job_id def path(self, **kwargs) -> str: return f"/query/jobs/{self.job_id}" def parse_response(self, response: requests.Response, **kwargs) -> List[str]: return [response.json()["data"]["dataFile"]] def _send_request(self, request: requests.PreparedRequest, request_kwargs: Mapping[str, Any]) -> requests.Response: """ Override of default CDK method _send_request to check the status of submited job iteratevely, until it's either "completed" or "failed" or "canceled" for any reason. Response example: {'data': { 'id': 'c6f25f91-5357-4fec-a00d-9009cc1ae856', 'query': 'DESCRIBE account', 'useIndexJoin': False, 'sourceData': 'LIVE', 'queryStatus': 'completed', 'dataFile': 'https://owl-auw2-sbx01-query-result.s3.us-west-2.amazonaws.com/c6f25f91-5357-4fec-a00d-9009cc1ae856_2779514650704989.jsonl?....', 'outputRows': 53, 'processingTime': 516, 'remainingRetries': 3, 'retries': 3, 'updatedOn': '2021-07-26T15:33:48.803Z', 'createdBy': '84f78cea-8a5b-4332-933f-27439fe3b87b' } } """ # Define the job error statuses errors = ["failed", "canceled", "aborted"] # Error msg: the cursor_field cannot be resolved cursor_error = f"Column '{self.cursor_field}' cannot be resolved" alt_cursor_error = f"Column '{self.alt_cursor_field}' cannot be resolved" # Error msg: cannot process object obj_read_error = "failed to process object" status = None success = "completed" while status != success: """ There is no opportunity for the infinity loop because the operation performs on the server-side, there are query run-time limitations: if the query time is longer than 120 min, the server will output the error with the corresponding message for the user in the output, by raising `ZOQLQueryFailed` exception. """ response: requests.Response = self._session.send(request, **request_kwargs) job_check = response.json() status = job_check["data"]["queryStatus"] if status in errors and cursor_error in job_check["data"]["errorMessage"]: raise ZOQLQueryFieldCannotResolveCursor elif status in errors and obj_read_error in job_check["data"]["errorMessage"]: raise ZOQLQueryCannotProcessObject elif status in errors and alt_cursor_error in job_check["data"]["errorMessage"]: raise ZOQLQueryFieldCannotResolveAltCursor elif status in errors: raise ZOQLQueryFailed(response) return response class ZuoraGetJobResult(HttpStream): """ Provides functionality to retrive the records from the file formed by submited and successfully completed job DataFile URL example: {'data': { 'id': 'c6f25f91-5357-4fec-a00d-9009cc1ae856', ..., ..., 'dataFile': 'https://owl-auw2-sbx01-query-result.s3.us-west-2.amazonaws.com/c6f25f91-5357-4fec-a00d-9009cc1ae856_2779514650704989.jsonl?....', ..., ..., 'createdBy': '84f78cea-8a5b-4332-933f-27439fe3b87b' } } """ primary_key = None def __init__(self, url: str): super().__init__() # initiate authenticator = NoAuth(), _session self.url = url # accept incoming dataFile URL @property def url_base(self): return self.url def path(self, **kwargs) -> str: """ Abstractmethod HTTPStream CDK dependency """ return "" def next_page_token(self, response: requests.Response) -> Optional[Mapping[str, Any]]: """ Abstractmethod HTTPStream CDK dependency """ return None def parse_response(self, response: requests.Response, **kwargs) -> str: """ Return records from JSONLines file from dataFile URL. """ for line in response.text.splitlines(): yield json.loads(line) class SourceZuora(AbstractSource): def check_connection(self, logger: AirbyteLogger, config: Mapping[str, Any]) -> Tuple[bool, any]: """ Testing connection availability for the connector by granting the token. """ # Define the endpoint from user's config url_base = get_url_base(config["tenant_endpoint"]) try: ZuoraAuthenticator( token_refresh_endpoint=f"{url_base}/oauth/token", client_id=config["client_id"], client_secret=config["client_secret"], refresh_token=None, # Zuora doesn't have Refresh Token parameter. ).get_auth_header() return True, None except Exception as e: return False, e def streams(self, config: Mapping[str, Any]) -> List[ZuoraStream]: """ Mapping a input config of the user input configuration as defined in the connector spec. Defining streams to run by building stream classes dynamically. """ # Define the endpoint from user's config url_base = get_url_base(config["tenant_endpoint"]) # Get Authotization Header with Access Token authenticator = ZuoraAuthenticator( token_refresh_endpoint=f"{url_base}/oauth/token", client_id=config["client_id"], client_secret=config["client_secret"], refresh_token=None, # Zuora doesn't have Refresh Token parameter. ) config["authenticator"] = authenticator config["url_base"] = url_base # List available objects (streams) names from Zuora # Example: zuora_stream_names = ["account", "country", "user"] zuora_stream_names = ZuoraListObjects(config).read_records(sync_mode=None) streams: List[ZuoraStream] = [] for stream_name in zuora_stream_names: if stream_name not in ZUORA_EXCLUDED_STREAMS: # construct ZuoraReadStreams sub-class for each stream_name stream_class = type(stream_name, (ZuoraObjectsBase,), {}) # instancetiate a stream with config stream_instance = stream_class(config) streams.append(stream_instance) return streams
9,640
3,084
/*++ Copyright (c) Microsoft Corporation. All rights reserved. Module Name: fail_library1.c Abstract: Template library that can be used together with a driver for testing the seamless build feature of SDV via defect injection. This library is not functional and not intended as a sample for real software development projects. It only provides a skeleton for building a defective library. Environment: Kernel mode --*/ #include "fail_library1.h" VOID SDVTest_wdf_DriverCreate() { return; } VOID SDVTest_wdf_DeviceInitAPI( _In_ PWDFDEVICE_INIT DeviceInit ) { WdfDeviceInitSetIoType(DeviceInit, WdfDeviceIoBuffered); return; } VOID SDVTest_wdf_MdlAfterReqCompletionIoctl( _In_ WDFREQUEST Request, _In_ PMDL Mdl ) { NTSTATUS status; status = WdfRequestRetrieveInputWdmMdl(Request, &Mdl); if(status==STATUS_SUCCESS) { return; } else { return; } } VOID SDVTest_wdf_MemoryAfterReqCompletionIntIoctlAdd( _In_ WDFMEMORY Memory ) { WDF_MEMORY_DESCRIPTOR memoryDescriptor; WDF_MEMORY_DESCRIPTOR_INIT_HANDLE(&memoryDescriptor, Memory, NULL); return; } VOID SDVTest_wdf_MdlAfterReqCompletionIntIoctlAdd( _In_ PMDL Mdl ) { ULONG byteOffset; byteOffset = MmGetMdlByteOffset(Mdl); return; } VOID SDVTest_wdf_MarkCancOnCancReqDispatch( _In_ WDFREQUEST Request ) { WdfRequestMarkCancelable(Request, SDVTest_EvtRequestCancel); return; } VOID SDVTest_EvtRequestCancel( _In_ WDFREQUEST Request ) { WdfRequestComplete(Request, STATUS_CANCELLED); }
808
532
/******************************************************************************* MODELUTILS.C Author: <NAME> Date: 03-JAN-91 Copyright (c) 1992-5 MusculoGraphics, Inc. All rights reserved. Portions of this source code are copyrighted by MusculoGraphics, Inc. Description: Routines: delete_model : deletes a model check_gencoord_wrapping : checks boundaries of gencoord value makegencform : makes the gencoord form for a model getjointvarnum : given a dof name, returns a dof number getjointvarname : given dof number, returns dof name (e.g. tx) *******************************************************************************/ #include "universal.h" #include "globals.h" #include "functions.h" /*************** DEFINES (for this file only) *********************************/ /*************** STATIC GLOBAL VARIABLES (for this file only) *****************/ static void delete_display_lists(ModelStruct* model); static void destroy_model_menus(ModelStruct* model); /*************** EXTERNED VARIABLES (declared in another file) ****************/ /*************** PROTOTYPES for STATIC FUNCTIONS (for this file only) *********/ #if OPENSMAC #undef ENGINE #define ENGINE 1 #endif #if ! ENGINE void delete_scene(Scene* scene) { int i; // TODO_SCENE delete_model(scene->model[0]); FREE_IFNOTNULL(scene->model); FREE_IFNOTNULL(scene->snapshot_file_suffix); FREE_IFNOTNULL(scene->movie_file); free(scene); for (i=0; i<SCENEBUFFER; i++) { if (gScene[i] == scene) { gScene[i] = NULL; break; } } adjust_main_menu(); } /* DELETE_MODEL: this routine deletes a model from the system. It closes the * model window, frees the model structures, deletes the model window from * the window list, updates the pop-up model menu, and checks to make sure * no tools are currently set to the model. */ void delete_model(ModelStruct* ms) { int i, j; char buf[1024]; MotionModelOptions* mmo; Scene* scene = get_first_scene_containing_model(ms); if (is_model_realtime(ms) == rtMocap) { #if INCLUDE_EVA_REALTIME stop_realtime_mocap_stream(); #endif } else if (is_model_realtime(ms) == rtSimulation) { #if ! SIMM_VIEWER // DPTODO #endif } glutDeleteMutex(ms->modelLock); glutSetWindow(scene->window_glut_id); /* Post the MODEL_DELETED event before deleting the motions * (which will post MOTION_DELETED events for each one). This * requires more checking by each tool when handling a * MOTION_DELETED event (to see if the model still exists or * not), but is more efficient because the tool will not * update itself for each motion deleted and then update itself * again when the whole model is deleted. * The model pointer is included in the MODEL_DELETED event so * that the tools can check to see if they are currently set to * the deleted model. But the modelnum is also needed to index * into the array of tool/model options (e.g., meop, pmop). */ make_and_queue_simm_event(MODEL_DELETED, ms->modelnum, ms, NULL, ZERO, ZERO); for (i = 0; i < ms->motion_array_size; i++) { if (ms->motion[i]) { delete_motion(ms, ms->motion[i], no); FREE_IFNOTNULL(ms->motion[i]); } } destroy_model_menus(ms); // In order to delete the window from the GUI as quickly as possible, // only the tasks that must be done before the window is // removed are done before calling delete_window(). This // means that deleting the bone display lists, which used // to be done inside free_model(), is done separately, here. // These display lists can only be deleted when the window // in which they were created is current. delete_display_lists(ms); delete_window(scene->window_glut_id); sprintf(buf, "Deleted model %s.", ms->name); purge_simm_events_for_struct(scene, SCENE_INPUT_EVENT); purge_simm_events_for_model(ms->modelnum, MODEL_ADDED); free_model(ms->modelnum); root.nummodels--; updatemodelmenu(); message(buf, 0, DEFAULT_MESSAGE_X_OFFSET); } static void delete_display_lists(ModelStruct* model) { int i, j; Scene* scene = get_first_scene_containing_model(model); if (scene && scene->window_glut_id != -1) { int savedID = glutGetWindow(); glutSetWindow(scene->window_glut_id); // Delete the muscle display lists. glDeleteLists(model->dis.muscle_cylinder_id, 1); glDeleteLists(model->dis.muscle_point_id, 1); // Delete the bone, springfloor, contact object, and force matte display lists. for (i=0; i<model->numsegments; i++) { if (model->segment[i].defined == yes) { for (j=0; j<model->segment[i].numBones; j++) delete_polyhedron_display_list(&model->segment[i].bone[j], NULL); for (j=0; j<model->segment[i].numContactObjects; j++) delete_polyhedron_display_list(model->segment[i].contactObject[j].poly, NULL); if (model->segment[i].springFloor) delete_polyhedron_display_list(model->segment[i].springFloor->poly, NULL); if (model->segment[i].forceMatte) delete_polyhedron_display_list(model->segment[i].forceMatte->poly, NULL); } } // Delete the wrap object display lists. for (i=0; i<model->num_wrap_objects; i++) glDeleteLists(model->wrapobj[i]->display_list, 1); // Delete the world object display lists. for (i=0; i<model->numworldobjects; i++) delete_polyhedron_display_list(model->worldobj[i].wobj, NULL); // Delete the constraint object display lists. for (i=0; i<model->num_constraint_objects; i++) glDeleteLists(model->constraintobj[i].display_list, 1); // Delete the materials. for (i=0; i<model->dis.mat.num_materials; i++) { if (model->dis.mat.materials[i].normal_list) glDeleteLists(model->dis.mat.materials[i].normal_list,1); if (model->dis.mat.materials[i].highlighted_list) glDeleteLists(model->dis.mat.materials[i].highlighted_list,1); FREE_IFNOTNULL(model->dis.mat.materials[i].name); } FREE_IFNOTNULL(model->dis.mat.materials); glutSetWindow(savedID); } } static void destroy_model_menus(ModelStruct* model) { int i; glutDestroyMenu(model->musclegroupmenu); glutDestroyMenu(model->jointmenu); glutDestroyMenu(model->xvarmenu); glutDestroyMenu(model->gencoordmenu); glutDestroyMenu(model->gencoordmenu2); if (model->gencoord_group_menu) glutDestroyMenu(model->gencoord_group_menu); glutDestroyMenu(model->momentgencmenu); glutDestroyMenu(model->momentarmgencmenu); glutDestroyMenu(model->momentarmnumgencmenu); glutDestroyMenu(model->maxmomentgencmenu); glutDestroyMenu(model->segmentmenu); glutDestroyMenu(model->motionplotmenu); glutDestroyMenu(model->motionmenu); glutDestroyMenu(model->motionwithrealtimemenu); glutDestroyMenu(model->material_menu); if (model->markerMenu) glutDestroyMenu(model->markerMenu); for (i = 0; i < model->numsegments; i++) glutDestroyMenu(model->segment[i].drawmodemenu); for (i = 0; i < model->numseggroups; i++) glutDestroyMenu(model->seggroup[i].displaymodemenu); for (i = 0; i < model->numworldobjects; i++) glutDestroyMenu(model->worldobj[i].drawmodemenu); glutDestroyMenu(model->dis.view_menu); glutDestroyMenu(model->dis.allsegsdrawmodemenu); glutDestroyMenu(model->dis.allligsdrawmodemenu); glutDestroyMenu(model->dis.allworlddrawmodemenu); glutDestroyMenu(model->dis.alldrawmodemenu); if (model->dis.eachsegdrawmodemenu > 0) glutDestroyMenu(model->dis.eachsegdrawmodemenu); glutDestroyMenu(model->dis.maindrawmodemenu); } #endif /* ENGINE */ double check_gencoord_wrapping(GeneralizedCoord* gc, double change) { double new_value, range; new_value = gc->value + change; /* If the gencoord is not allowed to wrap, then clamp * it within its range of motion. You do not need to * check if the gencoord is unclamped because that * variable is only relevant when reading gencoord values * from a motion file or typing them into the gencoord * field in the ModelViewer (and in neither case is this * function called). */ if (gc->wrap == no) { if (new_value < gc->range.start) return (gc->range.start); else if (new_value > gc->range.end) return (gc->range.end); else return (new_value); } range = gc->range.end - gc->range.start; while (new_value > gc->range.end) new_value -= range; while (new_value < gc->range.start) new_value += range; return (new_value); } #if ! ENGINE /* MAKEGENCFORM: this routine makes the form for changing gencoord values. * It also makes the checkbox panel for setting clamp/unclamp * for the gencoords and lock/unlock for the gencoords. */ ReturnCode makegencform(ModelStruct* ms) { int i, name_len; Form* form; CheckBoxPanel* check; form = &ms->gencform; form->numoptions = ms->numgencoords; form->selected_item = -1; form->cursor_position = 0; form->highlight_start = 0; form->title = NULL; ms->longest_genc_name = 0; form->option = (FormItem*)simm_malloc(form->numoptions*sizeof(FormItem)); if (form->option == NULL) return code_bad; for (i=0; i<form->numoptions; i++) { form->option[i].justify = yes; form->option[i].active = yes; form->option[i].visible = yes; form->option[i].editable = yes; form->option[i].use_alternate_colors = no; form->option[i].decimal_places = 3; form->option[i].data = NULL; mstrcpy(&form->option[i].name, ms->gencoord[i]->name); name_len = glueGetStringWidth(root.gfont.defaultfont, ms->gencoord[i]->name); if (name_len > ms->longest_genc_name) ms->longest_genc_name = name_len; SET_BOX1221(form->option[i].box,0,75,-FORM_FIELD_YSPACING*i, form->option[i].box.y2-FORM_FIELD_HEIGHT); } /* make the gencoord checkbox panel */ check = &ms->gc_chpanel; check->title = "C"; check->type = normal_checkbox; check->numoptions = ms->numgencoords; check->checkbox = (CheckBox*)simm_malloc(check->numoptions*sizeof(CheckBox)); if (check->checkbox == NULL) error(exit_program,tool_message); for (i=0; i<check->numoptions; i++) { check->checkbox[i].just = right; check->checkbox[i].active = yes; check->checkbox[i].visible = yes; if (ms->gencoord[i]->clamped == no) check->checkbox[i].state = off; else check->checkbox[i].state = on; check->checkbox[i].name = NULL; check->checkbox[i].box.x1 = form->option[i].box.x1; check->checkbox[i].box.x2 = check->checkbox[i].box.x1 + CHECKBOX_XSIZE*2/3; check->checkbox[i].box.y1 = form->option[i].box.y1; check->checkbox[i].box.y2 = check->checkbox[i].box.y1 + CHECKBOX_YSIZE*2/3; check->checkbox[i].use_alternate_colors = no; } /* make the gencoord lock checkbox panel */ check = &ms->gc_lockPanel; check->title = "L"; //NULL; check->type = normal_checkbox; check->numoptions = ms->numgencoords; check->checkbox = (CheckBox*)simm_malloc(check->numoptions*sizeof(CheckBox)); if (check->checkbox == NULL) error(exit_program,tool_message); for (i=0; i<check->numoptions; i++) { check->checkbox[i].just = right; check->checkbox[i].active = yes; check->checkbox[i].visible = yes; if (ms->gencoord[i]->locked == no) check->checkbox[i].state = off; else check->checkbox[i].state = on; check->checkbox[i].name = NULL; check->checkbox[i].box.x1 = form->option[i].box.x1; check->checkbox[i].box.x2 = check->checkbox[i].box.x1 + CHECKBOX_XSIZE*2/3; check->checkbox[i].box.y1 = form->option[i].box.y1; check->checkbox[i].box.y2 = check->checkbox[i].box.y1 + CHECKBOX_YSIZE*2/3; } return code_fine; } ReturnCode make_dynparams_form(ModelStruct* ms) { int i, name_len, num_options; Form* form; if (ms->default_muscle) num_options = ms->default_muscle->num_dynamic_params + 1; // one extra for muscle model else num_options = 1; // one extra for muscle model form = &ms->dynparamsform; form->numoptions = num_options; form->selected_item = -1; form->cursor_position = 0; form->highlight_start = 0; form->title = NULL; ms->longest_dynparam_name = 0; form->option = (FormItem*)simm_malloc(form->numoptions*sizeof(FormItem)); if (form->option == NULL) return code_bad; ms->dynparamsSize = 0; for (i=0; i<form->numoptions; i++) { form->option[i].justify = yes; form->option[i].active = yes; form->option[i].visible = yes; form->option[i].editable = yes; form->option[i].use_alternate_colors = no; form->option[i].data = NULL; if (i == num_options - 1) { form->option[i].decimal_places = 0; mstrcpy(&form->option[i].name, "muscle_model"); } else { form->option[i].decimal_places = 3; mstrcpy(&form->option[i].name, ms->default_muscle->dynamic_param_names[i]); } name_len = glueGetStringWidth(root.gfont.defaultfont, form->option[i].name); if (name_len > ms->longest_dynparam_name) ms->longest_dynparam_name = name_len; SET_BOX1221(form->option[i].box, 0, 90,-FORM_FIELD_YSPACING*i, form->option[i].box.y2-FORM_FIELD_HEIGHT); ms->dynparamsSize = form->option[i].box.y2 - FORM_FIELD_HEIGHT; } ms->longest_dynparam_name -= 30; return code_fine; } #endif /* ENGINE */ /* GETJOINTVARNUM: */ int getjointvarnum(char string[]) { if (STRINGS_ARE_EQUAL(string,"r1")) return (0); if (STRINGS_ARE_EQUAL(string,"r2")) return (1); if (STRINGS_ARE_EQUAL(string,"r3")) return (2); if (STRINGS_ARE_EQUAL(string,"tx")) return (3); if (STRINGS_ARE_EQUAL(string,"ty")) return (4); if (STRINGS_ARE_EQUAL(string,"tz")) return (5); if (STRINGS_ARE_EQUAL(string,"order")) return (6); if (STRINGS_ARE_EQUAL(string,"axis1")) return (7); if (STRINGS_ARE_EQUAL(string,"axis2")) return (8); if (STRINGS_ARE_EQUAL(string,"axis3")) return (9); if (STRINGS_ARE_EQUAL(string,"segments")) return (10); return (-1); } /* GETJOINTVARNAME: */ char* getjointvarname(int num) { switch (num) { case 0: return ("r1"); case 1: return ("r2"); case 2: return ("r3"); case 3: return ("tx"); case 4: return ("ty"); case 5: return ("tz"); case 6: return ("order"); case 7: return ("axis1"); case 8: return ("axis2"); case 9: return ("axis3"); case 10: return ("name"); default: return (""); } } #if ! ENGINE SBoolean isVisible(double pt[]) { if (pt[0] >= UNDEFINED_DOUBLE) return no; if (pt[1] >= UNDEFINED_DOUBLE) return no; if (pt[2] >= UNDEFINED_DOUBLE) return no; return yes; } void hack_tool_updates(ModelStruct* model, int model_index) { int i; SimmEvent se; /* Hack: update all the tools so they know the model was deleted. * This is done in cases where the updates must happen immediately, * rather than just pushing a SIMM event on the queue. */ se.event_code = MODEL_DELETED; se.model_index = model_index; se.struct_ptr1 = (void*)model; se.struct_ptr2 = NULL; se.field1 = ZERO; se.field2 = ZERO; se.mouse_x = 0; se.mouse_y = 0; se.key_modifiers = 0; se.window_id = -1; se.object = 0; for (i = 0; i < TOOLBUFFER; i++) { if (tool[i].used == yes && (se.event_code & tool[i].simm_event_mask) == se.event_code) (*tool[i].simm_event_handler)(se); } } #endif /* ENGINE */
6,677
3,269
<filename>compiler/IREmitter/Payload/tools/postprocess_payload.cc #include <iostream> #include <llvm/Bitcode/BitcodeWriter.h> #include <llvm/IR/DebugInfo.h> #include <llvm/IR/Module.h> #include <llvm/IR/Verifier.h> #include <llvm/IRReader/IRReader.h> #include <llvm/Support/FileSystem.h> #include <llvm/Support/SourceMgr.h> using llvm::BitcodeWriter; using llvm::LLVMContext; using llvm::Module; using llvm::SMDiagnostic; using llvm::StringRef; namespace { // Mark all `sorbet_` functions defined in the payload with `internal` linkage, so that they are available for inlining, // but are GC'd if they aren't used. // // NOTE: marking these functions as `internal` is the same as marking them `static` in codegen-payload.c. However, if we // were to mark them all static, the compiler would prune them all out and we'd be left with an empty payload. We want // these functions to be private to code-generation, and there's just not a great way to say that in the c source. void setSorbetFunctionLinkage(Module &module) { for (auto &fun : module.functions()) { auto name = fun.getName(); if (fun.isDeclaration()) { // When given ruby code like the following: // if cond // ABC.new(1) // else // DEF.new(1) // end // We emit something like the following: // %1 = <cond> // br i1 %1, label %BB1, label %BB2 // BB1: // class = sorbet_i_getRubyClass("ABC") // sorbet_i_send(class, "new") // BB2: // class = sorbet_i_getRubyClass("DEF") // sorbet_i_send(class, "new") // LLVM notices that ABC and DEF are string constants of the same length, and replaces this with: // class = sorbet_i_getRubyClass(phi "ABC", "DEF") // sorbet_i_send(class, "new") // This causes an issue, because sorbet_i_getRubyClass can only handle constants, and returns undef when // it encounters the phi node. // By marking sorbet_i_getRubyClass and sorbet_i_getRubyConstant as nomerge, we are telling LLVM not to // attempt to dedup calls to them, and emit the original LLVM code instead. if (name.equals("sorbet_i_getRubyClass") || name.equals("sorbet_i_getRubyConstant")) { fun.addFnAttr(llvm::Attribute::NoMerge); } continue; } // Keep the special keep-alive functions as external, as they will be explicitly removed by a pass late in // the compiler's pipeline. if (name.startswith("sorbet_exists_to_keep_alive_") && fun.hasExternalLinkage()) { continue; } // Set all of the `external` (default linkage) functions defined in the payload to `internal` linkage, as any // other functions have more specific linkage set explicitly in the source. if (name.startswith("sorbet_") && fun.hasExternalLinkage()) { fun.setLinkage(llvm::GlobalValue::InternalLinkage); } } } // Mark ruby constant globals explicitly as constants -- we know that values like `rb_cClass` etc are never going to // change once the vm has initialized. // // quoting spec: // > LLVM explicitly allows declarations of global variables to be marked constant, even if the final definition of the // > global is not. This capability can be used to enable slightly better optimization of the program, but requires the // > language definition to guarantee that optimizations based on the ‘constantness’ are valid for the translation units // > that do not include the definition. void markRubyConstants(Module &module) { for (auto &cnst : module.globals()) { auto name = cnst.getName(); // TODO: this should be expanded to `rb_e` and `rb_m` as well if (name.startswith("rb_c") && cnst.getUnnamedAddr() == llvm::GlobalValue::UnnamedAddr::Local) { cnst.setConstant(true); } } } void clearModuleFlags(Module &module) { // Remove the llvm.module.flags debug metadata, as it will raise verification errors when inlining functions defined // in the payload if it's present. if (auto *flags = module.getModuleFlagsMetadata()) { flags->eraseFromParent(); } // Remove the llvm.ident metadata as we don't really need to include information about the version of clang we used // to generate the payload. if (auto *ident = module.getNamedMetadata("llvm.ident")) { ident->eraseFromParent(); } } } // namespace int main(int argc, char **argv) { if (argc != 3) { std::cerr << "Usage: postprocess_payload <payload.bc> <output.bc>" << std::endl; return 1; } LLVMContext ctx; SMDiagnostic errors; auto module = llvm::parseIRFile(StringRef(argv[1]), errors, ctx); setSorbetFunctionLinkage(*module); markRubyConstants(*module); clearModuleFlags(*module); // We strip out information that makes debug info work in clearModuleFlags, so strip everything out as that will // happen when the payload is loaded by sorbet. llvm::StripDebugInfo(*module); // Sanity check the changes we make if (llvm::verifyModule(*module, &llvm::errs())) { return 1; } std::error_code ec; llvm::raw_fd_ostream out(argv[2], ec, llvm::sys::fs::OF_None); llvm::WriteBitcodeToFile(*module, out); out.flush(); return 0; }
2,108
3,882
"""Tests for slices.""" from pytype.tests import test_base class SliceTest(test_base.BaseTest): """Tests for the SLICE_<n> opcodes, as well as for __getitem__(slice).""" def test_getslice(self): ty = self.Infer(""" x = [1,2,3] a = x[:] b = x[1:] c = x[1:2] d = x[1:2:3] e = x[:2:3] f = x[1::3] g = x[1:2:] """, deep=False) self.assertTypesMatchPytd(ty, """ from typing import List x = ... # type: List[int] a = ... # type: List[int] b = ... # type: List[int] c = ... # type: List[int] d = ... # type: List[int] e = ... # type: List[int] f = ... # type: List[int] g = ... # type: List[int] """) def test_slice_getitem(self): ty = self.Infer(""" class Foo: def __getitem__(self, s): return s Foo()[:] """, deep=False) self.assertTypesMatchPytd(ty, """ from typing import Tuple class Foo: def __getitem__(self, s: slice) -> slice: ... """) if __name__ == "__main__": test_base.main()
540
3,083
<reponame>utumen/binnavi // Copyright 2011-2016 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.security.zynamics.binnavi.Gui.Debug.MemoryRefreshButton.Actions; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.ImageIcon; import javax.swing.JFrame; import com.google.common.base.Preconditions; import com.google.security.zynamics.binnavi.CMain; import com.google.security.zynamics.binnavi.Gui.Debug.MemoryRefreshButton.IRefreshRangeProvider; import com.google.security.zynamics.binnavi.Gui.Debug.MemoryRefreshButton.Implementations.CMemorySelectionFunctions; import com.google.security.zynamics.binnavi.Gui.GraphWindows.Panels.IFrontEndDebuggerProvider; import com.google.security.zynamics.binnavi.debug.debugger.interfaces.IDebugger; import com.google.security.zynamics.zylib.disassembly.IAddress; /** * Action class that can be used to refresh the current memory section. */ public final class CRefreshAction extends AbstractAction { /** * Used for serialization. */ private static final long serialVersionUID = 3258591696396189580L; /** * Parent window used for dialogs. */ private final JFrame m_parent; /** * Describes the debug GUI perspective where the refresh action takes place. */ private final IFrontEndDebuggerProvider m_debugPerspectiveModel; /** * Provides information about the range to refresh. */ private final IRefreshRangeProvider m_rangeProvider; /** * Provides information about the stack memory to refresh. */ private final IRefreshRangeProvider m_stackRangeProvider; /** * Creates a new refresh memory action object. * * @param parent Parent window used for dialogs. * @param debugPerspectiveModel Describes the debug GUI perspective where the refresh action takes * place. * @param rangeProvider Provides information about the range to refresh. * @param stackRangeProvider Provides information about the stack to refresh. */ public CRefreshAction(final JFrame parent, final IFrontEndDebuggerProvider debugPerspectiveModel, final IRefreshRangeProvider rangeProvider, final IRefreshRangeProvider stackRangeProvider) { Preconditions.checkNotNull(parent, "IE01448: Parent argument can not be null"); Preconditions.checkNotNull( debugPerspectiveModel, "IE01449: Debug perspective model argument can not be null"); m_parent = parent; m_debugPerspectiveModel = debugPerspectiveModel; m_rangeProvider = rangeProvider; m_stackRangeProvider = stackRangeProvider; putValue(Action.SMALL_ICON, new ImageIcon(CMain.class.getResource("data/memoryupdate_up.jpg"))); putValue(Action.SHORT_DESCRIPTION, "Refresh Memory"); } @Override public void actionPerformed(final ActionEvent event) { final IDebugger debugger = m_debugPerspectiveModel.getCurrentSelectedDebugger(); if (debugger != null) { CMemorySelectionFunctions.refreshMemory( m_parent, debugger, m_rangeProvider.getAddress(), m_rangeProvider.getSize()); final IAddress stackAddress = m_stackRangeProvider.getAddress(); final int size = m_stackRangeProvider.getSize(); if (stackAddress != null && size != 0) { CMemorySelectionFunctions.refreshMemory(m_parent, debugger, stackAddress, size); } } } }
1,187
819
/* * Copyright (c) 2016, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #ifndef FATAL_INCLUDE_fatal_type_deprecated_type_map_h #define FATAL_INCLUDE_fatal_type_deprecated_type_map_h #include <fatal/type/conditional.h> #include <fatal/type/deprecated/transform.h> #include <fatal/type/deprecated/type_list.h> #include <fatal/type/deprecated/type_pair.h> #include <fatal/type/deprecated/type_tag.h> #include <type_traits> #include <utility> #include <typeinfo> namespace fatal { //////////////////////////////////////// // IMPLEMENTATION FORWARD DECLARATION // //////////////////////////////////////// namespace detail { namespace type_map_impl { template <typename...> struct build_pair_list; template <typename, typename...> struct concat; template <typename, template <typename...> class, template <typename...> class> struct transform; template < typename, typename, template <typename...> class, template <typename...> class > struct transform_at; template <typename, template <typename...> class, template <typename...> class> struct invert_transform; template <typename, typename, typename...> struct find; template <typename, typename...> struct get; template <template <typename...> class, typename> struct separate; template <typename...> struct cluster; struct visit_not_found {}; template <typename, typename> struct visit_visitor; template <typename> struct binary_search_comparer; } // namespace type_map_impl { } // namespace detail { ////////////// // type_map // ////////////// /** * Type map for template metaprogramming. * * Most operations, unless noted otherwise, are compile-time evaluated. * * Compile-time operations have no side-effects. I.e.: operations that would * mutate the map upon which they are performed actually create a new map. * * @author: <NAME> <<EMAIL>> */ template <typename... Args> class type_map { // private to `type_map` so that `contains` will never have false negatives struct not_found_tag_impl {}; public: /** * The underlying type_list of type_pair<TKey, TMapped> used for * implementing this map. */ using contents = type_list<Args...>; /** * The size of this map. */ static constexpr std::size_t size = sizeof...(Args); static_assert(size == contents::size, "size mismatch"); /** * A boolean telling whether this map is empty or not. * This is the same as `type_map::size == 0`. */ static constexpr bool empty = sizeof...(Args) == 0; static_assert(empty == contents::empty, "empty property mismatch"); /** * A list of all the keys in this map. The order of the keys are guaranteed * to follow `contents`'s order. */ using keys = typename contents::template transform<type_get_first>; /** * A list of all the mapped types in this map. The order of the mapped types * are guaranteed to follow `contents`'s order. */ using mapped = typename contents::template transform<type_get_second>; // TODO: DOCUMENT AND TEST template < template <typename...> class TMappedTransform = identity, template <typename...> class TKeyTransform = identity > using transform = type_map< typename detail::type_map_impl::transform< Args, TKeyTransform, TMappedTransform >::type... >; // TODO: DOCUMENT AND TEST template < typename TKey, template <typename...> class TMappedTransform = identity, template <typename...> class TKeyTransform = identity > using transform_at = type_map< typename detail::type_map_impl::transform_at< TKey, Args, TKeyTransform, TMappedTransform >::type... >; // TODO: DOCUMENT AND TEST template < template <typename...> class TTransform, template <typename...> class TMappedTransform = identity, template <typename...> class TKeyTransform = identity > using apply = typename transform<TMappedTransform, TKeyTransform> ::contents::template apply<TTransform>; // TODO: DOCUMENT AND TEST template <typename... UArgs> using append = type_map<Args..., UArgs...>; // TODO: DOCUMENT AND TEST template <typename T> using concat = typename detail::type_map_impl::concat<T, Args...>::type; /** * Inverts the key and mapped types of this `type_map`. * * Optionally, it can apply a transformation to the key (`TKeyTransform`) * and mapped value (`TMappedTransform`) before inverting. * * Example: * * using map = type_map< * type_pair<int, bool>, * type_pair<float, long> * >; * * // yields `type_map< * // type_pair<bool, int>, * // type_pair<long, float> * // >` * using result1 = map::invert<>; * * // yields `type_map< * // type_pair<Bar<bool>, Foo<int>>, * // type_pair<Bar<long>, Foo<float>> * // >` * template <typename> struct Foo {}; * template <typename> struct Bar {}; * using result2 = map::invert<Foo, Bar>; * * @author: <NAME> <<EMAIL>> */ template < template <typename...> class TKeyTransform = identity, template <typename...> class TMappedTransform = identity > using invert = type_map< typename detail::type_map_impl::invert_transform< Args, TKeyTransform, TMappedTransform >::type... >; /** * Finds the first pair with key `TKey` and returns the mapped type. * * If there's no pair in this map with key `TKey` then `TDefault` is returned * (defaults to `type_not_found_tag` when omitted). * * Example: * * using map = type_map<type_pair<int, double>, type_pair<bool, long>>; * * // yields `double` * using result1 = map::find<int>; * * // yields `type_not_found_tag` * using result2 = map::find<float>; * * // yields `void` * using result3 = map::find<float, void>; */ template <typename TKey, typename TDefault = type_not_found_tag> using find = typename detail::type_map_impl::find< TDefault, TKey, Args... >::type; /** * Finds the first pair with key `TKey` and returns the mapped type. * * If there's no pair in this map with key `TKey` then it fails to compile. * * Example: * * using map = type_map<type_pair<int, double>, type_pair<bool, long>>; * * // yields `double` * using result1 = map::find<int>; * * // fails to compile * using result2 = map::get<float>; */ template <typename TKey> using get = typename detail::type_map_impl::get<TKey, Args...>::type; /** * Finds the first pair whose key is accepted by the predicate `TPredicate`, * and returns the pair as a `type_pair<Key, Mapped>`. * * If there's no pair in this map whose key is accepted by the predicate * then `TDefault` is returned (defaults to `type_not_found_tag` when * omitted). * * Example: * * using map = type_map<type_pair<int, double>, type_pair<bool, long>>; * * template <typename TLHS> * struct predicate { * template <typename TRHS> * using apply = std::is_same<TLHS, TRHS>; * }; * * // yields `double` * using result1 = map::search<predicate<int>::apply>; * * // yields `type_not_found_tag` * using result2 = map::search<predicate<float>::apply>; * * // yields `void` * using result3 = map::search<predicate<float>::apply, void>; */ template < template <typename...> class TPredicate, typename TDefault = type_not_found_tag > using search = typename contents::template search< compose<type_get_first, TPredicate>::template apply, TDefault >; /** * Tells whether there is a mapping where T is the key. * * Example: * * using map = type_map<type_pair<int, double>>; * * // yields `true` * map::contains<int>::value * * // yields `false` * map::contains<bool>::value */ template <typename T> using contains = typename keys::template contains<T>; /** * TODO: FIX DOCS * * Inserts the given `TKey` and `TValue` pair before all elements of this map. * * There are two overloads, one accepting the key and mapped type * (push_front<TKey, TMapped>) and another accepting a `type_pair` * (push_front<type_pair<TKey, TMapped>>). * * Note that keys are not necessarily unique. Inserting an existing key * will create duplicate entries for it. * * Example: * * using map = type_map< * type_pair<int, bool>, * type_pair<float, double> * >; * * // yields `type_map< * // type_pair<short, long>, * // type_pair<int, bool>, * // type_pair<float, double> * // >` * using result1 = map::push_front<short, long>; * * // yields `type_map< * // type_pair<short, long>, * // type_pair<int, bool>, * // type_pair<float, double> * // >` * using result2 = map::push_front<type_pair<short, long>>; * * @author: <NAME> <<EMAIL>> */ template <typename... UArgs> using push_front = typename detail::type_map_impl::build_pair_list<UArgs...> ::type::template apply_back<fatal::type_map, Args...>; /** * Inserts the given `TKey` and `TValue` pair after all elements of this map. * * Note that keys are not necessarily unique. Inserting an existing key * will create duplicate entries for it. * * Example: * * using map = type_map< * type_pair<int, bool>, * type_pair<float, double> * >; * * // yields `type_map< * // type_pair<int, bool>, * // type_pair<float, double>, * // type_pair<short, long> * // >` * using result1 = map::push_back<short, long>; * * // yields `type_map< * // type_pair<int, bool>, * // type_pair<float, double>, * // type_pair<short, long>, * // type_pair<void, unsigned> * // >` * using result2 = map::push_back< * short, long, * void, unsigned * >; * * @author: <NAME> <<EMAIL>> */ template <typename... UArgs> using push_back = typename detail::type_map_impl::build_pair_list<UArgs...> ::type::template apply_front<fatal::type_map, Args...>; /** * TODO: IT SHOULD INSERT AFTER A SPECIFIC KEY, OR END OF MAP IF NOT FOUND * * Inserts a new mapping into the type_map, in no specified order. * * Note that keys are not necessarily unique. Inserting an existing key * will create duplicate entries for it. Should you need unique mappings, * use `replace` instead. * * Example: * * using map = type_map<type_pair<int, double>>; * * // yields `type_map< * // type_pair<int, double>, * // type_pair<float, long> * // >` * using result1 = map::insert<float, long>; * * // yields `type_map< * // type_pair<int, double>, * // type_pair<float, long>, * // type_pair<void, unsigned> * // >` * using result2 = map::insert< * float, long, * void, unsigned * >; */ template <typename... UArgs> using insert = push_back<UArgs...>; /** * Inserts a new `TKey`, `TValue` mapping into the type_map in its sorted * position according to the order provided by `TLessComparer` when applied * to the keys. * * `TLessComparer` defaults to `comparison_transform::less_than` when omitted. * * Example: * * template <int Value> * using val = std::integral_constant<int, Value>; * * using map = type_map< * type_pair<val<0>, bool>, * type_pair<val<3>, double> * >; * * // yields `type_map< * // type_pair<val<0>, bool>, * // type_pair<val<2>, long>, * // type_pair<val<3>, double> * // >` * using result = map::insert_sorted< * comparison_transform::less_than, val<2>, long * >; */ template < typename TKey, typename TValue, template <typename...> class TLessComparer = comparison_transform::less_than > using insert_sorted = typename contents::template insert_sorted< type_pair<TKey, TValue>, type_get_first_comparer<TLessComparer>::template compare >::template apply<fatal::type_map>; /** * Inserts a new `type_pair` mapping into the type_map in its sorted position * according to the order provided by `TLessComparer` when applied to the * keys. * * `TLessComparer` defaults to `comparison_transform::less_than` when omitted. * * Example: * * template <int Value> * using val = std::integral_constant<int, Value>; * * using map = type_map< * type_pair<val<0>, bool>, * type_pair<val<3>, double> * > map; * * // yields `type_map< * // type_pair<val<0>, bool>, * // type_pair<val<1>, int>, * // type_pair<val<3>, double> * // >` * using result = map::insert_pair_sorted< * comparison_transform::less_than, * type_pair<val<1>, int> * >; */ template < typename TPair, template <typename...> class TLessComparer = comparison_transform::less_than > using insert_pair_sorted = typename contents::template insert_sorted< TPair, type_get_first_comparer<TLessComparer>::template compare >::template apply<fatal::type_map>; /** * Replaces with `TMapped` the mapped type of all pairs with key `TKey`. * * Example: * * // yields `type_map<type_pair<int, double>>` * using result1 = type_map<type_pair<int, long>>::replace<int, double>; * * // yields `type_map< * // type_pair<int, double>, * // type_pair<float, short>, * // type_pair<int, double> * // >` * using result2 = type_map< * type_pair<int, long>, * type_pair<float, short>, * type_pair<int, bool> * >::replace<int, double>; */ template <typename TKey, typename TMapped> using replace = typename type_map::template transform_at< TKey, fixed_transform<TMapped>::template apply >; /** * Removes all entries where given types are the key from the type map. * * Example: * * using map = type_map< * type_pair<int, bool>, * type_pair<int, float>, * type_pair<void, std::string>, * type_pair<float, double>, * type_pair<bool, bool> * >; * * // yields `type_map<type_pair<float, double>, type_pair<bool, bool>>` * using result = map::remove<int, void>; */ template <typename... UArgs> using remove = typename contents::template reject< compose< type_get_first, type_list<UArgs...>::template contains >::template apply >::template apply<fatal::type_map>; /** * Returns a pair with two `type_map`s. One (first) with the pairs whose keys * got accepted by the predicate and the other (second) with the pairs whose * keys weren't accepted by it. * * `TPredicate` is a std::integral_constant-like template whose value * evaluates to a boolean when fed with a key from this map. * * Example: * * using map = type_map< * type_pair<int, bool>, * type_pair<int, float>, * type_pair<void, std::string>, * type_pair<float, double>, * type_pair<bool, bool> * >; * * // yields `type_pair< * // type_map< * // type_pair<int, bool>, * // type_pair<int, float>, * // type_pair<bool, bool> * // >, * // type_map< * // type_pair<void, std::string>, * // type_pair<float, double> * // > * // >` * using result = map::separate<std::is_integral>; * * @author: <NAME> <<EMAIL>> */ template <template <typename...> class TPredicate> using separate = typename detail::type_map_impl::separate< TPredicate, contents >::type; /** * Returns a `type_map` containing the pairs whose keys got accepted by * the predicate. * * `TPredicate` is a std::integral_constant-like template whose value * evaluates to a boolean when fed with a key from this map. * * Example: * * using map = type_map< * type_pair<int, bool>, * type_pair<int, float>, * type_pair<void, std::string>, * type_pair<float, double>, * type_pair<bool, bool> * >; * * // yields `type_map< * // type_pair<int, bool>, * // type_pair<int, float>, * // type_pair<bool, bool> * // >` * using result = map::filter<std::is_integral>; * * @author: <NAME> <<EMAIL>> */ template <template <typename...> class TPredicate> using filter = typename separate<TPredicate>::first; /** * Returns a `type_map` containing the pairs whose keys did not get * accepted by the predicate. * * `TPredicate` is a std::integral_constant-like template whose value * evaluates to a boolean when fed with a key from this map. * * Example: * * using map = type_map< * type_pair<int, bool>, * type_pair<int, float>, * type_pair<void, std::string>, * type_pair<float, double>, * type_pair<bool, bool> * >; * * // yields `type_map< * // type_pair<void, std::string>, * // type_pair<float, double> * // >` * using result = map::reject<std::is_integral>; * * @author: <NAME> <<EMAIL>> */ template <template <typename...> class TPredicate> using reject = typename separate<TPredicate>::second; /** * Sorts this `type_map` by key using the stable merge sort algorithm, * according to the given type comparer `TLessComparer`. * * `TLessComparer` must represent a total order relation between all types. * * The default comparer is `comparison_transform::less_than`, which sorts * in a non-decreasing order. * * Example: * * using map = type_map< * type_pair<T<0>, void>, * type_pair<T<1>, short>, * type_pair<T<4>, double>, * type_pair<T<2>, bool>, * type_pair<T<1>, int>, * type_pair<T<3>, float> * >; * * // yields `type_map< * // type_pair<T<0>, void>, * // type_pair<T<1>, short>, * // type_pair<T<1>, int>, * // type_pair<T<2>, bool>, * // type_pair<T<3>, float>, * // type_pair<T<4>, double> * // >` * using result = map::sort<>; * * @author: <NAME> <<EMAIL>> */ template < template <typename...> class TLessComparer = comparison_transform::less_than > using sort = typename contents::template sort< type_get_first_comparer<TLessComparer>::template compare >::template apply<fatal::type_map>; template < template <typename...> class TKeyTransform = identity, template <typename...> class TMappedTransform = identity > using cluster = typename detail::type_map_impl::cluster< typename detail::type_map_impl::transform< Args, TKeyTransform, TMappedTransform >::type... >::type; template < template <typename...> class TPredicate, typename V, typename... VArgs > static constexpr std::size_t foreach_if(V &&visitor, VArgs &&...args) { return contents::template foreach_if<TPredicate>( std::forward<V>(visitor), std::forward<VArgs>(args)... ); } template <typename V, typename... VArgs> static constexpr bool foreach(V &&visitor, VArgs &&...args) { return contents::foreach( std::forward<V>(visitor), std::forward<VArgs>(args)... ); } template <typename TKey, typename TVisitor, typename... VArgs> static constexpr bool visit(TVisitor &&visitor, VArgs &&...args) { using mapped = find<TKey, detail::type_map_impl::visit_not_found>; return detail::type_map_impl::visit_visitor<TKey, mapped>::visit( std::forward<TVisitor>(visitor), std::forward<VArgs>(args)... ); } /** * Performs a binary search on this map's keys (assumes the map is sorted), * comparing against the given `needle`. * * If a matching key is found, the visitor is called with the following * arguments: * - an instance of `indexed_type_tag< * type_pair<MatchingKey, MappedType>, * Index * >` * - the `needle` * - the list of additional arguments `args` given to * the visitor * * in other words, with this general signature: * * template < * typename TKey, typename TMapped, std::size_t Index, * typename TNeedle, * typename... VArgs * > * void operator ()( * indexed_type_tag<type_pair<TKey, TMapped>, Index>, * TNeedle &&needle, * VArgs &&...args * ); * * Returns `true` when found, `false` otherwise. * * The comparison is performed using the given `TComparer`'s method, whose * signature must follow this pattern: * * template <typename TNeedle, typename TKey, std::size_t Index> * static int compare(TNeedle &&needle, indexed_type_tag<TKey, Index>); * * which effectivelly compares `needle` against the key type `TKey`. The * result must be < 0, > 0 or == 0 if `needle` is, respectively, less than, * greather than or equal to `TKey`. `Index` is the position of the pair with * key `TKey` in this type map and can also be used in the comparison if * needed. * * `TComparer` defaults to `type_value_comparer` which compares an * std::integral_constant-like value to a runtime value. * * The sole purpose of `args` is to be passed along to the visitor, it is not * used by this method in any way. It could also be safely omitted. * * The visitor will be called at most once, iff a match is found. Otherwise it * will not be called. The boolean returned by this method can be used to tell * whether the visitor has been called or not. * * See each operation's documentation below for further details. * * Note: this is a runtime facility. * * Example comparer used on examples below: * * template <char c> using chr = std::integral_constant<char, c>; * template <int n> using int_val = std::integral_constant<int, n>; * * template <char c> using chr = std::integral_constant<char, c>; * * struct cmp { * template <char c, std::size_t Index> * static int compare(char needle, indexed_type_tag<chr<c>, Index>) { * return static_cast<int>(needle) - c; * }; * * template <int n, std::size_t Index> * static int compare(int needle, indexed_type_tag<int_val<n>, Index>) { * return needle - n; * }; * }; */ template <typename TComparer = type_value_comparer> struct binary_search { /** * Performs a binary search for a key that * is an exact match of the `needle`. * * Refer to the `binary_search` documentation above for more details. * * Note: this is a runtime facility. * * Example: * * struct visitor { * template <char Key, char Mapped, std::size_t Index> * void operator ()( * indexed_type_tag<type_pair<chr<Key>, chr<Mapped>>, Index>, * char needle * ) { * assert(needle == Key); * std::cout << "key '" << needle << "' found at index " << Index * << " mapping '" << Mapped << '\'' * << std::endl; * }; * }; * * using map = type_map< * type_pair<chr<'a'>, chr<'A'>>, * type_pair<chr<'e'>, chr<'E'>>, * type_pair<chr<'i'>, chr<'I'>>, * type_pair<chr<'o'>, chr<'O'>>, * type_pair<chr<'u'>, chr<'U'>> * >; * * // yields `false` * map::binary_search::exact<cmp>('x', visitor()); * * // yields `true` and prints `"key 'i' found at index 2 mapping 'I'"` * map::binary_search<cmp>::exact('i', visitor()); */ template <typename TNeedle, typename TVisitor, typename... VArgs> static constexpr bool exact( TNeedle &&needle, TVisitor &&visitor, VArgs &&...args ) { return contents::template binary_search< detail::type_map_impl::binary_search_comparer<TComparer> >::exact( std::forward<TNeedle>(needle), std::forward<TVisitor>(visitor), std::forward<VArgs>(args)... ); } /** * Performs a binary search for the greatest key that is less than * or equal to (<=) the `needle`. This is analogous to `std::lower_bound`. * * Refer to the `binary_search` documentation above for more details. * * Note: this is a runtime facility. * * Example: * * struct visitor { * template <int Key, int Mapped, std::size_t Index> * void operator ()( * indexed_type_tag<type_pair<int_val<Key>, int_val<Mapped>>, Index>, * int needle * ) { * assert(Key <= needle); * std::cout << needle << "'s lower bound " << n * << " found at index " << Index << " mapping " << Mapped * << std::endl; * }; * }; * * using map = type_map< * type_pair<int_val<10>, int_val<100>>, * type_pair<int_val<30>, int_val<300>>, * type_pair<int_val<50>, int_val<500>>, * type_pair<int_val<70>, int_val<700>> * >; * * // yields `false` * map::binary_search<cmp>::lower_bound(5, visitor()); * * // yields `true` and prints * // `"11's lower bound 10 found at index 0 mapping 100"` * map::binary_search<cmp>::lower_bound(11, visitor()); * * // yields `true` and prints * // `"68's lower bound 50 found at index 2 mapping 500"` * map::binary_search<cmp>::lower_bound(68, visitor()); * * // yields `true` and prints * // `"70's lower bound 70 found at index 3 mapping 700"` * map::binary_search<cmp>::lower_bound(70, visitor()); */ template <typename TNeedle, typename TVisitor, typename... VArgs> static constexpr bool lower_bound( TNeedle &&needle, TVisitor &&visitor, VArgs &&...args ) { return contents::template binary_search< detail::type_map_impl::binary_search_comparer<TComparer> >::lower_bound( std::forward<TNeedle>(needle), std::forward<TVisitor>(visitor), std::forward<VArgs>(args)... ); } /** * Performs a binary search for the least key that is greater than (>) * the `needle`. This is analogous to `std::upper_bound`. * * Refer to the `binary_search` documentation above for more details. * * Note: this is a runtime facility. * * Example: * * struct visitor { * template <int Key, int Mapped, std::size_t Index> * void operator ()( * indexed_type_pair_tag<int_val<Key>, int_val<Mapped>, Index>, * int needle * ) { * assert(Key > needle); * std::cout << needle << "'s upper bound " << n * << " found at index " << Index << " mapping " << Mapped * << std::endl; * }; * }; * * using list = int_seq<10, 30, 50, 70>; * * // yields `false` * map::binary_search<cmp>::upper_bound(70, visitor()); * * // yields `true` and prints * // `"5's upper bound 10 found at index 0 mapping 100"` * map::binary_search<cmp>::upper_bound(5, visitor()); * * // yields `true` and prints * // `"31's upper bound 50 found at index 2 mapping 500"` * map::binary_search<cmp>::upper_bound(31, visitor()); */ template <typename TNeedle, typename TVisitor, typename... VArgs> static constexpr bool upper_bound( TNeedle &&needle, TVisitor &&visitor, VArgs &&...args ) { return contents::template binary_search< detail::type_map_impl::binary_search_comparer<TComparer> >::upper_bound( std::forward<TNeedle>(needle), std::forward<TVisitor>(visitor), std::forward<VArgs>(args)... ); } }; }; /////////////////////////////// // STATIC MEMBERS DEFINITION // /////////////////////////////// template <typename... Args> constexpr std::size_t type_map<Args...>::size; template <typename... Args> constexpr bool type_map<Args...>::empty; ///////////////////// // SUPPORT LIBRARY // ///////////////////// ///////////////////// // type_get_traits // ///////////////////// /** * Specialization of `type_get_traits` so that `type_get` supports `type_map`. * * @author: <NAME> <<EMAIL>> */ template <typename... Args> struct type_get_traits<type_map<Args...>> { template <std::size_t Index> using supported = std::integral_constant<bool, (Index < sizeof...(Args))>; template <std::size_t Index> using type = typename type_map<Args...>::contents::template at<Index>; }; //////////////////// // build_type_map // //////////////////// /** * Convenience mechanism to construct new type maps. * * It receives a flat list of `TKey, TMapped` types. * * Example: * * // yields an empty `type_map<>` * using empty = build_type_map<>; * * // yields `type_map<type_pair<int, double>>` * using result1 = build_type_map<int, double>; * * // yields * // type_map< * // type_pair<int, bool>, * // type_pair<double, float>, * // type_pair<void, std::string>, * // > map * using result2 = build_type_map<int, bool, double, float, void, std::string>; */ template <typename... Args> using build_type_map = typename detail::type_map_impl::build_pair_list<Args...> ::type::template apply<type_map>; /////////////////// // type_map_from // /////////////////// /** * Creates a `type_map` out of a `type_list`. * * For each element `T` of the list, a corresponding key/value pair will be * added to the map, by applying an optional `TKeyTransform` to obtain the key. * An optional transform can also be applied to `T` to obtain the mapped value. * The default transform uses `T` itself. * * Example: * * using list = type_list<int, bool, double>; * * template <typename> struct Foo {}; * template <typename> struct Bar {}; * * // yield `type_map< * // type_pair<Foo<int>, int>, * // type_pair<Foo<bool>, bool>, * // type_pair<Foo<double>, double> * // >` * using result1 = type_map_from<Foo>::list<list>; * * // yield `type_map< * // type_pair<Foo<int>, Bar<int>>, * // type_pair<Foo<bool>, Bar<bool>>, * // type_pair<Foo<double>, Bar<double>> * // >` * using result2 = type_map_from<Foo, Bar>::list<list>; * * // yield `type_map< * // type_pair<int, int>, * // type_pair<bool, bool>, * // type_pair<double, double> * // >` * using result3 = type_map_from<>::list<list>; * * @author: <NAME> <<EMAIL>> */ template < template <typename...> class TKeyTransform = identity, template <typename...> class TValueTransform = identity > struct type_map_from { template <typename... UArgs> using args = type_map< typename type_pair_from< TKeyTransform, TValueTransform >::template type<UArgs>... >; template <typename UList> using list = typename UList::template apply<args>; }; ///////////////////// // clustered_index // ///////////////////// namespace detail { template < template <typename...> class TTransform, template <typename...> class... TTransforms > struct clustered_index_impl { template <typename TList> using apply = typename type_map_from<TTransform> ::template list<TList> ::template cluster<> ::template transform< clustered_index_impl<TTransforms...>::template apply >; }; template <template <typename...> class TTransform> struct clustered_index_impl<TTransform> { template <typename TList> using apply = typename type_map_from<TTransform>::template list<TList>; }; } // namespace detail { ///////////////////// // clustered_index // ///////////////////// template < typename TList, template <typename...> class TTransform, template <typename...> class... TTransforms > using clustered_index = typename detail::clustered_index_impl< TTransform, TTransforms... >::template apply<TList>; //////////////////////////// // IMPLEMENTATION DETAILS // //////////////////////////// ///////////////////////// // recursive_type_sort // ///////////////////////// /** * Specialization of `recursive_type_sort` for `type_map`. * * @author: <NAME> <<EMAIL>> */ template <typename... T, std::size_t Depth> struct recursive_type_sort_impl<type_map<T...>, Depth> { using type = conditional< (Depth > 0), typename type_map<T...> ::template sort<> ::template transform< recursive_type_sort<Depth - 1>::template apply >, type_map<T...> >; }; namespace detail { namespace type_map_impl { ///////////////////// // build_pair_list // ///////////////////// template <typename TKey, typename TValue, typename... Args> struct build_pair_list<TKey, TValue, Args...> { using type = typename build_pair_list<Args...>::type::template push_front< type_pair<TKey, TValue> >; }; template <> struct build_pair_list<> { using type = type_list<>; }; //////////// // concat // //////////// template < template <typename...> class T, typename... Suffix, typename... Prefix > struct concat<T<Suffix...>, Prefix...> { using type = type_map<Prefix..., Suffix...>; }; /////////////// // transform // /////////////// template < typename TPair, template <typename...> class TKeyTransform, template <typename...> class TMappedTransform > struct transform { using type = typename TPair::template transform< TKeyTransform, TMappedTransform >; }; ////////////////// // transform_at // ////////////////// template < typename TKey, typename TPair, template <typename...> class TKeyTransform, template <typename...> class TMappedTransform > struct transform_at { using type = conditional< std::is_same<TKey, type_get_first<TPair>>::value, typename TPair::template transform<TKeyTransform, TMappedTransform>, TPair >; }; //////////// // invert // //////////// template < typename TPair, template <typename...> class TKeyTransform, template <typename...> class TMappedTransform > struct invert_transform { using type = typename TPair::template transform< TKeyTransform, TMappedTransform >::invert; }; ////////// // find // ////////// template <typename TDefault, typename TKey> struct find<TDefault, TKey> { using type = TDefault; }; template <typename TDefault, typename TKey, typename TValue, typename... Args> struct find<TDefault, TKey, type_pair<TKey, TValue>, Args...> { using type = TValue; }; template <typename TDefault, typename TKey, typename T, typename... Args> struct find<TDefault, TKey, T, Args...> { using type = typename find<TDefault, TKey, Args...>::type; }; ///////// // get // ///////// template <typename TKey, typename TValue, typename... Args> struct get<TKey, type_pair<TKey, TValue>, Args...> { using type = TValue; }; template <typename TKey, typename T, typename... Args> struct get<TKey, T, Args...> { using type = typename get<TKey, Args...>::type; }; ////////////// // separate // ////////////// template <template <typename...> class TPredicate, typename TList> struct separate { using separated = typename TList::template separate< compose<type_get_first, TPredicate>::template apply >; using type = type_pair< typename type_get_first<separated>::template apply<type_map>, typename type_get_second<separated>::template apply<type_map> >; }; ///////////// // cluster // ///////////// template <typename T> struct cluster_transform { template <typename U> using add = typename U::template push_back<T>; }; template <typename... Args> struct cluster { using type = type_map<>; }; template <typename T, typename... Args> struct cluster<T, Args...> { using tail = typename cluster<Args...>::type; using key = type_get_first<T>; using mapped = type_get_second<T>; using type = conditional< tail::template contains<key>::value, typename tail::template transform_at< key, cluster_transform<mapped>::template add >, typename tail::template push_back<key, type_list<mapped>> >; }; /////////// // visit // /////////// template <typename TKey, typename TMapped> struct visit_visitor { template <typename TVisitor, typename... VArgs> static constexpr bool visit(TVisitor &&visitor, VArgs &&...args) { // comma operator needed due to C++11's constexpr restrictions return visitor( type_pair<TKey, TMapped>(), std::forward<VArgs>(args)... ), true; } }; template <typename TKey> struct visit_visitor<TKey, visit_not_found> { template <typename TVisitor, typename... VArgs> static constexpr bool visit(TVisitor &&, VArgs &&...) { return false; } }; /////////////////// // binary_search // /////////////////// template <typename TComparer> struct binary_search_comparer { template <typename TNeedle, typename TKey, typename TValue, std::size_t Index> static constexpr int compare( TNeedle &&needle, indexed_type_tag<type_pair<TKey, TValue>, Index> ) { return TComparer::compare( std::forward<TNeedle>(needle), indexed_type_tag<TKey, Index>{} ); } }; } // namespace type_map_impl { } // namespace detail { } // namespace fatal { #endif // FATAL_INCLUDE_fatal_type_deprecated_type_map_h
14,250
965
// CBrush::CBrush. CBrush brush1; // Must initialize! brush1.CreateSolidBrush(RGB(0, 0, 255)); // Blue brush. CRect rc; GetClientRect(&rc); ScreenToClient(&rc); // Save original brush. CBrush *pOrigBrush = (CBrush *)pDC->SelectObject(&brush1); // Paint upper left corner with blue brush. pDC->Rectangle(0, 0, rc.Width() / 2, rc.Height() / 2); // These constructors throw resource exceptions. try { // CBrush::CBrush(COLORREF crColor) CBrush brush2(RGB(255, 0, 0)); // Solid red brush. // CBrush::CBrush(int nIndex, COLORREF crColor) // Hatched green brush. CBrush brush3(HS_DIAGCROSS, RGB(0, 255, 0)); // CBrush::CBrush(CBitmap* pBitmap) CBitmap bmp; // Load a resource bitmap. bmp.LoadBitmap(IDB_BRUSH); CBrush brush4(&bmp); pDC->SelectObject(&brush2); // Paint upper right corner with red brush. pDC->Rectangle(rc.Width() / 2, 0, rc.Width(), rc.Height() / 2); pDC->SelectObject(&brush3); // Paint lower left corner with green hatched brush. pDC->Rectangle(0, rc.Height() / 2, rc.Width() / 2, rc.Height()); pDC->SelectObject(&brush4); // Paint lower right corner with resource brush. pDC->Rectangle(rc.Width() / 2, rc.Height() / 2, rc.Width(), rc.Height()); } catch (CResourceException *e) { e->ReportError(); e->Delete(); } // Reselect original brush into device context. pDC->SelectObject(pOrigBrush);
599
973
/*_########################################################################## _## _## Copyright (C) 2016 Pcap4J.org _## _########################################################################## */ package org.pcap4j.packet.namednumber; import java.util.HashMap; import java.util.Map; /** * Type and subtype of an IEEE802.11 frame * * @see <a href="http://standards.ieee.org/getieee802/download/802.11-2012.pdf">IEEE802.11</a> * @author <NAME> * @since pcap4j 1.7.0 */ public final class Dot11FrameType extends NamedNumber<Byte, Dot11FrameType> { /** */ private static final long serialVersionUID = 863329177944877431L; /** Association request: 0 (00 0000) */ public static final Dot11FrameType ASSOCIATION_REQUEST = new Dot11FrameType((byte) 0, "Association request"); /** Association response: 1 (00 0001) */ public static final Dot11FrameType ASSOCIATION_RESPONSE = new Dot11FrameType((byte) 1, "Association response"); /** Reassociation request: 2 (00 0010) */ public static final Dot11FrameType REASSOCIATION_REQUEST = new Dot11FrameType((byte) 2, "Reassociation request"); /** Reassociation response: 3 (00 0011) */ public static final Dot11FrameType REASSOCIATION_RESPONSE = new Dot11FrameType((byte) 3, "Reassociation response"); /** Probe request: 4 (00 0100) */ public static final Dot11FrameType PROBE_REQUEST = new Dot11FrameType((byte) 4, "Probe request"); /** Probe response: 5 (00 0101) */ public static final Dot11FrameType PROBE_RESPONSE = new Dot11FrameType((byte) 5, "Probe response"); /** Timing Advertisement: 6 (00 0110) */ public static final Dot11FrameType TIMING_ADVERTISEMENT = new Dot11FrameType((byte) 6, "Timing Advertisement"); /** Beacon: 8 (00 1000) */ public static final Dot11FrameType BEACON = new Dot11FrameType((byte) 8, "Beacon"); /** ATIM: 9 (00 1001) */ public static final Dot11FrameType ATIM = new Dot11FrameType((byte) 9, "ATIM"); /** Disassociation: 10 (00 1010) */ public static final Dot11FrameType DISASSOCIATION = new Dot11FrameType((byte) 10, "Disassociation"); /** Authentication: 11 (00 1011) */ public static final Dot11FrameType AUTHENTICATION = new Dot11FrameType((byte) 11, "Authentication"); /** Deauthentication: 12 (00 1100) */ public static final Dot11FrameType DEAUTHENTICATION = new Dot11FrameType((byte) 12, "Deauthentication"); /** Action: 13 (00 1101) */ public static final Dot11FrameType ACTION = new Dot11FrameType((byte) 13, "Action"); /** Action No Ack: 14 (00 1110) */ public static final Dot11FrameType ACTION_NO_ACK = new Dot11FrameType((byte) 14, "Action No Ack"); /** Control Wrapper: 23 (01 0111) */ public static final Dot11FrameType CONTROL_WRAPPER = new Dot11FrameType((byte) 23, "Control Wrapper"); /** Block Ack Request: 24 (01 1000) */ public static final Dot11FrameType BLOCK_ACK_REQUEST = new Dot11FrameType((byte) 24, "Block Ack Request"); /** Block Ack: 25 (01 1001) */ public static final Dot11FrameType BLOCK_ACK = new Dot11FrameType((byte) 25, "Block Ack"); /** PS-Poll: 26 (01 1010) */ public static final Dot11FrameType PS_POLL = new Dot11FrameType((byte) 26, "PS-Poll"); /** RTS: 27 (01 1011) */ public static final Dot11FrameType RTS = new Dot11FrameType((byte) 27, "RTS"); /** CTS: 28 (01 1100) */ public static final Dot11FrameType CTS = new Dot11FrameType((byte) 28, "CTS"); /** ACK: 29 (01 1101) */ public static final Dot11FrameType ACK = new Dot11FrameType((byte) 29, "ACK"); /** CF-End: 30 (01 1110) */ public static final Dot11FrameType CF_END = new Dot11FrameType((byte) 30, "CF-End"); /** CF-End + CF-Ack: 31 (01 1111) */ public static final Dot11FrameType CF_END_CF_ACK = new Dot11FrameType((byte) 31, "CF-End + CF-Ack"); /** Data: 32 (10 0000) */ public static final Dot11FrameType DATA = new Dot11FrameType((byte) 32, "Data"); /** Data + CF-Ack: 33 (10 0001) */ public static final Dot11FrameType DATA_CF_ACK = new Dot11FrameType((byte) 33, "Data + CF-Ack"); /** Data + CF-Poll: 34 (10 0010) */ public static final Dot11FrameType DATA_CF_POLL = new Dot11FrameType((byte) 34, "Data + CF-Poll"); /** Data + CF-Ack + CF-Poll: 35 (10 0011) */ public static final Dot11FrameType DATA_CF_ACK_CF_POLL = new Dot11FrameType((byte) 35, "Data + CF-Ack + CF-Poll"); /** Null (no data): 36 (10 0100) */ public static final Dot11FrameType NULL = new Dot11FrameType((byte) 36, "Null"); /** CF-Ack (no data): 37 (10 0101) */ public static final Dot11FrameType CF_ACK = new Dot11FrameType((byte) 37, "CF-Ack"); /** CF-Poll (no data): 38 (10 0110) */ public static final Dot11FrameType CF_POLL = new Dot11FrameType((byte) 38, "CF-Poll"); /** CF-Ack + CF-Poll (no data): 39 (10 0111) */ public static final Dot11FrameType CF_ACK_CF_POLL = new Dot11FrameType((byte) 39, "CF-Ack + CF-Poll"); /** QoS Data: 40 (10 1000) */ public static final Dot11FrameType QOS_DATA = new Dot11FrameType((byte) 40, "QoS Data"); /** QoS Data + CF-Ack: 41 (10 1001) */ public static final Dot11FrameType QOS_DATA_CF_ACK = new Dot11FrameType((byte) 41, "QoS Data + CF-Ack"); /** QoS Data + CF-Poll: 42 (10 1010) */ public static final Dot11FrameType QOS_DATA_CF_POLL = new Dot11FrameType((byte) 42, "QoS Data + CF-Poll"); /** QoS Data + CF-Ack + CF-Poll: 43 (10 1011) */ public static final Dot11FrameType QOS_DATA_CF_ACK_CF_POLL = new Dot11FrameType((byte) 43, "QoS Data + CF-Ack + CF-Poll"); /** QoS Null (no data): 44 (10 1100) */ public static final Dot11FrameType QOS_NULL = new Dot11FrameType((byte) 44, "QoS Null"); /** QoS CF-Poll (no data): 46 (10 1110) */ public static final Dot11FrameType QOS_CF_POLL = new Dot11FrameType((byte) 46, "QoS CF-Poll"); /** QoS CF-Ack + CF-Poll (no data): 47 (10 1111) */ public static final Dot11FrameType QOS_CF_ACK_CF_POLL = new Dot11FrameType((byte) 47, "QoS CF-Ack + CF-Poll"); private static final Map<Byte, Dot11FrameType> registry = new HashMap<Byte, Dot11FrameType>(); static { registry.put(ASSOCIATION_REQUEST.value(), ASSOCIATION_REQUEST); registry.put(ASSOCIATION_RESPONSE.value(), ASSOCIATION_RESPONSE); registry.put(REASSOCIATION_REQUEST.value(), REASSOCIATION_REQUEST); registry.put(REASSOCIATION_RESPONSE.value(), REASSOCIATION_RESPONSE); registry.put(PROBE_REQUEST.value(), PROBE_REQUEST); registry.put(PROBE_RESPONSE.value(), PROBE_RESPONSE); registry.put(TIMING_ADVERTISEMENT.value(), TIMING_ADVERTISEMENT); registry.put(BEACON.value(), BEACON); registry.put(ATIM.value(), ATIM); registry.put(DISASSOCIATION.value(), DISASSOCIATION); registry.put(AUTHENTICATION.value(), AUTHENTICATION); registry.put(DEAUTHENTICATION.value(), DEAUTHENTICATION); registry.put(ACTION.value(), ACTION); registry.put(ACTION_NO_ACK.value(), ACTION_NO_ACK); registry.put(CONTROL_WRAPPER.value(), CONTROL_WRAPPER); registry.put(BLOCK_ACK_REQUEST.value(), BLOCK_ACK_REQUEST); registry.put(BLOCK_ACK.value(), BLOCK_ACK); registry.put(PS_POLL.value(), PS_POLL); registry.put(RTS.value(), RTS); registry.put(CTS.value(), CTS); registry.put(ACK.value(), ACK); registry.put(CF_END.value(), CF_END); registry.put(CF_END_CF_ACK.value(), CF_END_CF_ACK); registry.put(DATA.value(), DATA); registry.put(DATA_CF_ACK.value(), DATA_CF_ACK); registry.put(DATA_CF_POLL.value(), DATA_CF_POLL); registry.put(DATA_CF_ACK_CF_POLL.value(), DATA_CF_ACK_CF_POLL); registry.put(NULL.value(), NULL); registry.put(CF_ACK.value(), CF_ACK); registry.put(CF_POLL.value(), CF_POLL); registry.put(CF_ACK_CF_POLL.value(), CF_ACK_CF_POLL); registry.put(QOS_DATA.value(), QOS_DATA); registry.put(QOS_DATA_CF_ACK.value(), QOS_DATA_CF_ACK); registry.put(QOS_DATA_CF_POLL.value(), QOS_DATA_CF_POLL); registry.put(QOS_DATA_CF_ACK_CF_POLL.value(), QOS_DATA_CF_ACK_CF_POLL); registry.put(QOS_NULL.value(), QOS_NULL); registry.put(QOS_CF_POLL.value(), QOS_CF_POLL); registry.put(QOS_CF_ACK_CF_POLL.value(), QOS_CF_ACK_CF_POLL); } private final Type type; /** * @param value value * @param name name */ public Dot11FrameType(Byte value, String name) { super(value, name); if ((value & 0xC0) != 0) { throw new IllegalArgumentException(value + " is invalid value. (value & 0xC0) must be 0."); } switch (value >> 4) { case 0: this.type = Type.MANAGEMENT; break; case 1: this.type = Type.CONTROL; break; case 2: this.type = Type.DATA; break; case 3: this.type = Type.RESERVED; break; default: throw new AssertionError("Never get here."); } } /** @return type */ public Type getType() { return type; } /** * @param value value * @return a Dot11FrameType object. */ public static Dot11FrameType getInstance(Byte value) { if (registry.containsKey(value)) { return registry.get(value); } else { return new Dot11FrameType(value, "unknown"); } } /** * @param number number * @return a Dot11FrameType object. */ public static Dot11FrameType register(Dot11FrameType number) { return registry.put(number.value(), number); } @Override public int compareTo(Dot11FrameType o) { return value().compareTo(o.value()); } /** */ @Override public String valueAsString() { return String.valueOf(value() & 0xFF); } /** * Type of IEEE802.11 frame * * @see <a href="http://standards.ieee.org/getieee802/download/802.11-2012.pdf">IEEE802.11</a> * @author <NAME> * @since pcap4j 1.7.0 */ public static enum Type { /** Management (00) */ MANAGEMENT(0), /** Control (01) */ CONTROL(1), /** Data (10) */ DATA(2), /** Reserved (11) */ RESERVED(3); private final int value; private Type(int value) { this.value = value; } /** @return value */ public int getValue() { return value; } } }
3,810
3,508
<reponame>Anshul1507/Leetcode package com.fishercoder; import com.fishercoder.solutions._1; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.assertArrayEquals; public class _1Test { private static _1.Solution1 solution1; private static int[] nums; @BeforeClass public static void setup() { solution1 = new _1.Solution1(); } @Test public void test1() { nums = new int[]{2, 7, 11, 15}; assertArrayEquals(new int[]{0, 1}, solution1.twoSum(nums, 9)); } }
226
307
/* * Copyright 2017 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * */ package com.netflix.spinnaker.halyard.cli.command.v1.config.pubsubs.subscription; import com.beust.jcommander.Parameters; import com.netflix.spinnaker.halyard.cli.command.v1.NestableCommand; import com.netflix.spinnaker.halyard.cli.services.v1.Daemon; import com.netflix.spinnaker.halyard.cli.services.v1.OperationHandler; import com.netflix.spinnaker.halyard.cli.ui.v1.AnsiUi; import com.netflix.spinnaker.halyard.config.model.v1.node.Subscription; import java.util.HashMap; import java.util.Map; import lombok.AccessLevel; import lombok.Getter; @Parameters(separators = "=") public abstract class AbstractEditSubscriptionCommand<T extends Subscription> extends AbstractHasSubscriptionCommand { @Getter(AccessLevel.PROTECTED) private Map<String, NestableCommand> subcommands = new HashMap<>(); @Getter(AccessLevel.PUBLIC) private String commandName = "edit"; protected abstract Subscription editSubscription(T subscription); public String getShortDescription() { return "Edit an subscription in the " + getPubsubName() + " pubsub."; } @Override protected void executeThis() { String subscriptionName = getSubscriptionName(); String pubsubName = getPubsubName(); String currentDeployment = getCurrentDeployment(); // Disable validation here, since we don't want an illegal config to prevent us from fixing it. Subscription subscription = new OperationHandler<Subscription>() .setFailureMesssage( "Failed to get subscription " + subscriptionName + " for pubsub " + pubsubName + ".") .setOperation( Daemon.getSubscription(currentDeployment, pubsubName, subscriptionName, false)) .get(); int originaHash = subscription.hashCode(); subscription = editSubscription((T) subscription); if (originaHash == subscription.hashCode()) { AnsiUi.failure("No changes supplied."); return; } new OperationHandler<Void>() .setFailureMesssage( "Failed to edit subscription " + subscriptionName + " for pubsub " + pubsubName + ".") .setSuccessMessage( "Successfully edited subscription " + subscriptionName + " for pubsub " + pubsubName + ".") .setOperation( Daemon.setSubscription( currentDeployment, pubsubName, subscriptionName, !noValidate, subscription)) .get(); } }
1,141
3,799
<filename>slice/slice-view/src/main/java/androidx/slice/widget/SliceContent.java /* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.slice.widget; import static android.app.slice.Slice.HINT_SHORTCUT; import static android.app.slice.Slice.HINT_TITLE; import static android.app.slice.Slice.SUBTYPE_COLOR; import static android.app.slice.Slice.SUBTYPE_CONTENT_DESCRIPTION; import static android.app.slice.Slice.SUBTYPE_LAYOUT_DIRECTION; import static android.app.slice.SliceItem.FORMAT_ACTION; import static android.app.slice.SliceItem.FORMAT_IMAGE; import static android.app.slice.SliceItem.FORMAT_INT; import static android.app.slice.SliceItem.FORMAT_SLICE; import static android.app.slice.SliceItem.FORMAT_TEXT; import static androidx.slice.core.SliceHints.LARGE_IMAGE; import static androidx.slice.core.SliceHints.UNKNOWN_IMAGE; import static androidx.slice.widget.SliceViewUtil.resolveLayoutDirection; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.pm.ProviderInfo; import android.graphics.drawable.Drawable; import android.net.Uri; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import androidx.annotation.RestrictTo; import androidx.core.graphics.drawable.IconCompat; import androidx.slice.Slice; import androidx.slice.SliceItem; import androidx.slice.SliceUtils; import androidx.slice.core.SliceAction; import androidx.slice.core.SliceActionImpl; import androidx.slice.core.SliceQuery; /** * Base class representing content that can be displayed. */ @RequiresApi(19) public class SliceContent { /** * @hide */ protected SliceItem mSliceItem; /** * @hide */ protected SliceItem mColorItem; /** * @hide */ protected SliceItem mLayoutDirItem; /** * @hide */ protected SliceItem mContentDescr; /** * @hide */ protected int mRowIndex; public SliceContent(@Nullable Slice slice) { if (slice == null) return; init(new SliceItem(slice, FORMAT_SLICE, null, slice.getHints())); // Built from a slice implies it's top level and index shouldn't matter mRowIndex = -1; } /** * @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY) public SliceContent(@Nullable SliceItem item, int rowIndex) { if (item == null) return; init(item); mRowIndex = rowIndex; } private void init(SliceItem item) { mSliceItem = item; if (FORMAT_SLICE.equals(item.getFormat()) || FORMAT_ACTION.equals(item.getFormat())) { mColorItem = SliceQuery.findTopLevelItem(item.getSlice(), FORMAT_INT, SUBTYPE_COLOR, null, null); mLayoutDirItem = SliceQuery.findTopLevelItem(item.getSlice(), FORMAT_INT, SUBTYPE_LAYOUT_DIRECTION, null, null); } mContentDescr = SliceQuery.findSubtype(item, FORMAT_TEXT, SUBTYPE_CONTENT_DESCRIPTION); } /** * @return the slice item used to construct this content. * @hide */ @Nullable public SliceItem getSliceItem() { return mSliceItem; } /** * @return the accent color to use for this content or -1 if no color is set. * @hide */ public int getAccentColor() { return mColorItem != null ? mColorItem.getInt() : -1; } /** * @return the layout direction to use for this content or -1 if no direction set. * @hide */ public int getLayoutDir() { return mLayoutDirItem != null ? resolveLayoutDirection(mLayoutDirItem.getInt()) : -1; } /** * @return the content description to use for this row if set. * @hide */ @Nullable public CharSequence getContentDescription() { return mContentDescr != null ? mContentDescr.getText() : null; } /** * @return the row index of this content, or -1 if no row index is set. * @hide */ public int getRowIndex() { return mRowIndex; } /** * @return the desired height of this content based on the provided mode and context or the * default height if context is null. * @hide */ public int getHeight(SliceStyle style, SliceViewPolicy policy) { return 0; } /** * @return whether this content is valid to display or not. * @hide */ public boolean isValid() { return mSliceItem != null; } /** * @return the action that represents the shortcut. * @hide */ @Nullable public SliceAction getShortcut(@Nullable Context context) { if (mSliceItem == null) { // Can't make something from nothing return null; } SliceItem iconItem = null; SliceItem labelItem = null; int imageMode = UNKNOWN_IMAGE; // Prefer something properly hinted String[] hints = new String[]{HINT_TITLE, HINT_SHORTCUT}; SliceItem actionItem = SliceQuery.find(mSliceItem, FORMAT_ACTION, hints, null); if (actionItem != null) { iconItem = SliceQuery.find(actionItem, FORMAT_IMAGE, HINT_TITLE, null); labelItem = SliceQuery.find(actionItem, FORMAT_TEXT, (String) null, null); } if (actionItem == null) { // No hinted action; just use the first one actionItem = SliceQuery.find(mSliceItem, FORMAT_ACTION, (String) null, null); } // First fallback: any hinted image and text if (iconItem == null) { iconItem = SliceQuery.find(mSliceItem, FORMAT_IMAGE, HINT_TITLE, null); } if (labelItem == null) { labelItem = SliceQuery.find(mSliceItem, FORMAT_TEXT, HINT_TITLE, null); } // Second fallback: first image and text if (iconItem == null) { iconItem = SliceQuery.find(mSliceItem, FORMAT_IMAGE, (String) null, null); } if (labelItem == null) { labelItem = SliceQuery.find(mSliceItem, FORMAT_TEXT, (String) null, null); } // Fill in anything we don't have with app data if (iconItem != null) { imageMode = SliceUtils.parseImageMode(iconItem); } if (context != null) { return fallBackToAppData(context, labelItem, iconItem, imageMode, actionItem); } if (iconItem != null && actionItem != null && labelItem != null) { return new SliceActionImpl(actionItem.getAction(), iconItem.getIcon(), imageMode, labelItem.getText()); } return null; } private SliceAction fallBackToAppData(Context context, SliceItem textItem, SliceItem iconItem, int iconMode, SliceItem actionItem) { SliceItem slice = SliceQuery.find(mSliceItem, FORMAT_SLICE, (String) null, null); if (slice == null) { // Can't make something out of nothing return null; } Uri uri = slice.getSlice().getUri(); IconCompat shortcutIcon = iconItem != null ? iconItem.getIcon() : null; CharSequence shortcutAction = textItem != null ? textItem.getText() : null; if (context != null) { PackageManager pm = context.getPackageManager(); ProviderInfo providerInfo = pm.resolveContentProvider(uri.getAuthority(), 0); ApplicationInfo appInfo = providerInfo != null ? providerInfo.applicationInfo : null; if (appInfo != null) { if (shortcutIcon == null) { Drawable icon = pm.getApplicationIcon(appInfo); shortcutIcon = SliceViewUtil.createIconFromDrawable(icon); iconMode = LARGE_IMAGE; } if (shortcutAction == null) { shortcutAction = pm.getApplicationLabel(appInfo); } if (actionItem == null) { Intent launchIntent = pm.getLaunchIntentForPackage(appInfo.packageName); if (launchIntent != null) { actionItem = new SliceItem( PendingIntent.getActivity(context, 0, launchIntent, PendingIntent.FLAG_IMMUTABLE), new Slice.Builder(uri).build(), FORMAT_ACTION, null /* subtype */, new String[]{}); } } } } if (actionItem == null) { Intent intent = new Intent(); PendingIntent pi = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE); actionItem = new SliceItem(pi, null, FORMAT_ACTION, null, null); } if (shortcutAction != null && shortcutIcon != null && actionItem != null) { return new SliceActionImpl(actionItem.getAction(), shortcutIcon, iconMode, shortcutAction); } return null; } }
4,023
575
<reponame>Ron423c/chromium<filename>chrome/updater/external_constants.cc // Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/updater/external_constants.h" #include "chrome/updater/constants.h" #include "chrome/updater/external_constants_override.h" #include "chrome/updater/updater_branding.h" #include "url/gurl.h" namespace updater { namespace { class DefaultExternalConstants : public ExternalConstants { public: DefaultExternalConstants() : ExternalConstants(nullptr) {} ~DefaultExternalConstants() override = default; // Overrides of ExternalConstants: std::vector<GURL> UpdateURL() const override { return std::vector<GURL>{GURL(UPDATE_CHECK_URL)}; } bool UseCUP() const override { return true; } double InitialDelay() const override { return kInitialDelay; } int ServerKeepAliveSeconds() const override { return kServerKeepAliveSeconds; } }; } // namespace ExternalConstants::ExternalConstants( std::unique_ptr<ExternalConstants> next_provider) : next_provider_(std::move(next_provider)) {} ExternalConstants::~ExternalConstants() = default; std::unique_ptr<ExternalConstants> CreateExternalConstants() { std::unique_ptr<ExternalConstants> overrider = ExternalConstantsOverrider::FromDefaultJSONFile( std::make_unique<DefaultExternalConstants>()); return overrider ? std::move(overrider) : std::make_unique<DefaultExternalConstants>(); } std::unique_ptr<ExternalConstants> CreateDefaultExternalConstantsForTesting() { return std::make_unique<DefaultExternalConstants>(); } } // namespace updater
556
1,936
#ifndef MAPLAB_COMMON_HISTOGRAMS_INL_H_ #define MAPLAB_COMMON_HISTOGRAMS_INL_H_ #include <algorithm> #include <vector> #include <glog/logging.h> namespace common { namespace histograms { template <typename InputScalar> Eigen::MatrixXd histogram2d( const Eigen::Matrix<InputScalar, 2, Eigen::Dynamic>& points, const size_t num_x_bins, const size_t num_y_bins) { typedef Eigen::Matrix<InputScalar, Eigen::Dynamic, Eigen::Dynamic> MatrixX; Eigen::Matrix<InputScalar, 2, Eigen::Dynamic> positive_points( 2, points.cols()); positive_points.template topRows<1>() = points.template topRows<1>() - MatrixX::Constant( 1, points.cols(), points.template topRows<1>().minCoeff()); positive_points.template bottomRows<1>() = points.template bottomRows<1>() - MatrixX::Constant( 1, points.cols(), points.template bottomRows<1>().minCoeff()); const InputScalar x_max = positive_points.template topRows<1>().maxCoeff(); const InputScalar y_max = positive_points.template bottomRows<1>().maxCoeff(); Eigen::MatrixXi bin_counts(num_y_bins, num_x_bins); bin_counts.setZero(); for (int i = 0; i < positive_points.cols(); ++i) { const size_t row = std::min( static_cast<size_t>(floor(positive_points(1, i) * num_y_bins / y_max)), num_y_bins - 1); const size_t col = std::min( static_cast<size_t>(floor(positive_points(0, i) * num_x_bins / x_max)), num_x_bins - 1); ++bin_counts(row, col); } CHECK_GT(num_x_bins, 0u); CHECK_GT(num_y_bins, 0u); const double bin_density = (x_max / num_x_bins) * (y_max / num_y_bins); return bin_counts.cast<double>() / bin_density; } template <typename InputScalar> Eigen::MatrixXd downsample( const Eigen::Matrix<InputScalar, Eigen::Dynamic, Eigen::Dynamic>& input, const size_t num_x_bins, const size_t num_y_bins) { CHECK_GT(input.rows(), 0); CHECK_GT(input.cols(), 0); CHECK_GT(num_x_bins, 0u); CHECK_GT(num_y_bins, 0u); Eigen::MatrixXd bin_sums(num_y_bins, num_x_bins); bin_sums.setZero(); for (size_t x_index = 0; x_index < input.cols(); ++x_index) { const int x = x_index * num_x_bins / input.cols(); for (int y_index = 0; y_index < input.rows(); ++y_index) { const int y = y_index * num_y_bins / input.rows(); bin_sums(y, x) += input(y_index, x_index); } } CHECK_GE(input.cols(), num_x_bins); CHECK_GE(input.rows(), num_y_bins); const double bin_density = (input.cols() / num_x_bins) * (input.rows() / num_y_bins); return bin_sums / bin_density; } template <typename InputScalar> Eigen::MatrixXd downsampleWithIndexAsX( const std::vector<std::vector<InputScalar>>& y_values, const size_t num_x_bins, const size_t num_y_bins) { static_assert( std::is_integral<InputScalar>::value, "Input scalar must be integral"); const size_t x_ceiling = y_values.size(); CHECK_GT(x_ceiling, 0); InputScalar y_max = static_cast<InputScalar>(0); for (const std::vector<InputScalar>& y_of_x : y_values) { InputScalar vec_y_max = *std::max_element(y_of_x.begin(), y_of_x.end()); if (vec_y_max > y_max) { y_max = vec_y_max; } } const InputScalar y_ceiling = y_max + static_cast<InputScalar>(1); Eigen::MatrixXi bin_counts(num_y_bins, num_x_bins); bin_counts.setZero(); for (size_t x_index = 0u; x_index < x_ceiling; ++x_index) { const int x = x_index * num_x_bins / x_ceiling; for (size_t y_index = 0u; y_index < y_values[x_index].size(); ++y_index) { const int y = y_values[x_index][y_index] * num_y_bins / y_ceiling; ++bin_counts(y, x); } } const double bin_density = (static_cast<double>(x_ceiling) / num_x_bins) * (static_cast<double>(y_ceiling) / num_y_bins); return bin_counts.cast<double>() / bin_density; } } // namespace histograms } // namespace common #endif // MAPLAB_COMMON_HISTOGRAMS_INL_H_
1,749
348
<reponame>chamberone/Leaflet.PixiOverlay<filename>docs/data/leg-t1/059/05915054.json {"nom":"Bavinchove","circ":"15ème circonscription","dpt":"Nord","inscrits":745,"abs":361,"votants":384,"blancs":8,"nuls":3,"exp":373,"res":[{"nuance":"REM","nom":"Mme <NAME>","voix":119},{"nuance":"FN","nom":"<NAME>","voix":85},{"nuance":"LR","nom":"<NAME>","voix":61},{"nuance":"FI","nom":"<NAME>","voix":46},{"nuance":"UDI","nom":"M. <NAME>","voix":29},{"nuance":"SOC","nom":"M. <NAME>","voix":13},{"nuance":"ECO","nom":"<NAME>","voix":10},{"nuance":"ECO","nom":"<NAME>","voix":6},{"nuance":"EXG","nom":"M. <NAME>","voix":3},{"nuance":"DIV","nom":"Mme <NAME>","voix":1}]}
271
1,604
<gh_stars>1000+ # SPDX-License-Identifier: MIT import struct from enum import IntEnum from m1n1.proxyutils import RegMonitor from m1n1.utils import * from m1n1.trace.dart import DARTTracer from m1n1.trace.asc import ASCTracer, EP, EPState, msg, msg_log, DIR from m1n1.fw.smc import * ASCTracer = ASCTracer._reloadcls() class SMCEpTracer(EP): BASE_MESSAGE = SMCMessage def __init__(self, tracer, epid): super().__init__(tracer, epid) self.state.sram_addr = None self.state.verbose = 1 self.state.rb = {} Initialize = msg_log(SMC_INITIALIZE, DIR.TX, SMCInitialize) Notification = msg_log(SMC_NOTIFICATION, DIR.RX) @msg(SMC_WRITE_KEY, DIR.TX, SMCWriteKey) def WriteKey(self, msg): key = msg.KEY.to_bytes(4, byteorder="big").decode("ascii") data = self.hv.iface.readmem(self.state.sram_addr, msg.SIZE) self.log(f"[{msg.ID:x}] >W: <{key}> = {data.hex()}") return True @msg(SMC_READ_KEY, DIR.TX, SMCReadKey) def ReadKey(self, msg): key = msg.KEY.to_bytes(4, byteorder="big").decode("ascii") self.state.rb[msg.ID] = msg.TYPE, key, msg.SIZE self.log(f"[{msg.ID:x}] >R: <{key}> = ...") return True @msg(SMC_GET_KEY_INFO, DIR.TX, SMCGetKeyInfo) def GetInfo(self, msg): key = msg.KEY.to_bytes(4, byteorder="big").decode("ascii") self.state.rb[msg.ID] = msg.TYPE, key, None self.log(f"[{msg.ID:x}] >Get Info: <{key}>") return True @msg(None, DIR.RX, Register64) def RXMsg(self, msg): if self.state.sram_addr is None: self.log(f"SRAM address: {msg.value:#x}") self.state.sram_addr = msg.value return True msg = SMCResult(msg.value) if msg.RESULT != 0: self.log(f"[{msg.ID:x}] <Err: 0x{msg.RESULT:02x}") return True if msg.ID in self.state.rb: msgtype, key, size = self.state.rb.pop(msg.ID) if msgtype == SMC_READ_KEY: if size <= 4: data = hex(msg.VALUE) else: data = self.hv.iface.readmem(self.state.sram_addr, msg.SIZE).hex() self.log(f"[{msg.ID:x}] <R: <{key}> = {data}") return True elif msgtype == SMC_GET_KEY_INFO: data = self.hv.iface.readmem(self.state.sram_addr, 6) size, type, flags = struct.unpack("B4sB", data) self.log(f"[{msg.ID:x}] <Info: <{key}>: size={size} type={type.decode('ascii')} flags={flags:#x}") return True self.log(f"[{msg.ID:x}] <OK {msg!r}") return True class SMCTracer(ASCTracer): ENDPOINTS = { 0x20: SMCEpTracer } def handle_msg(self, direction, r0, r1): super().handle_msg(direction, r0, r1) smc_tracer = SMCTracer(hv, "/arm-io/smc", verbose=1) smc_tracer.start()
1,516
3,921
<reponame>sherlockhouse/luaandroid<filename>Android/LuaViewSDK/src/com/taobao/luaview/userdata/constants/UDFontWeight.java /* * Created by LuaView. * Copyright (c) 2017, Alibaba Group. All rights reserved. * * This source code is licensed under the MIT. * For the full copyright and license information,please view the LICENSE file in the root directory of this source tree. */ package com.taobao.luaview.userdata.constants; import android.text.TextUtils; import com.taobao.luaview.fun.mapper.LuaViewLib; import com.taobao.luaview.userdata.base.BaseLuaTable; import org.luaj.vm2.Globals; import org.luaj.vm2.LuaValue; /** * FontWeight 用户数据封装 * * @author song * @date 15/9/6 */ @LuaViewLib(revisions = {"20170306已对标", "ios不支持数值"}) public class UDFontWeight extends BaseLuaTable { public static final String WEIGHT_NORMAL = "normal"; public static final String WEIGHT_BOLD = "bold"; public static final int WEIGHT_NORMAL_INT = 400; public static final int WEIGHT_BOLD_INT = 700; public UDFontWeight(Globals globals, LuaValue metatable) { super(globals, metatable); init(); } private void init() { this.set("NORMAL", WEIGHT_NORMAL_INT); this.set("BOLD", WEIGHT_BOLD_INT); } public static int getValue(final String name) { if (!TextUtils.isEmpty(name)) { if (WEIGHT_NORMAL.equalsIgnoreCase(name)) { return WEIGHT_NORMAL_INT; } else if (WEIGHT_BOLD.equalsIgnoreCase(name)) { return WEIGHT_BOLD_INT; } } return WEIGHT_NORMAL_INT; } }
672
14,668
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chromecast.base; /** * Represents a type with only one possible instance. * * Retrieved by calling the static unit() function. * In algebraic type theory, this is the 1 (or "Singleton") type. * * Useful in generic method signatures to represent returning nothing (because Void is not * instantiable). */ public final class Unit { private static final Unit sInstance = new Unit(); private Unit() {} public static Unit unit() { return sInstance; } }
184
679
<reponame>Grosskopf/openoffice<filename>main/dbaccess/source/ui/tabledesign/TableDesignHelpBar.cxx /************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_dbui.hxx" #ifndef DBAUI_TABLEDESIGNHELPBAR_HXX #include "TableDesignHelpBar.hxx" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _SVEDIT_HXX #include <svtools/svmedit.hxx> #endif #ifndef _DBA_DBACCESS_HELPID_HRC_ #include "dbaccess_helpid.hrc" #endif #include <memory> using namespace dbaui; #define STANDARD_MARGIN 6 //================================================================== // class OTableDesignHelpBar //================================================================== DBG_NAME(OTableDesignHelpBar) //------------------------------------------------------------------------------ OTableDesignHelpBar::OTableDesignHelpBar( Window* pParent ) : TabPage( pParent, WB_3DLOOK ) { DBG_CTOR(OTableDesignHelpBar,NULL); m_pTextWin = new MultiLineEdit( this, WB_VSCROLL | WB_LEFT | WB_BORDER | WB_NOTABSTOP | WB_READONLY); m_pTextWin->SetHelpId(HID_TABLE_DESIGN_HELP_WINDOW); m_pTextWin->SetReadOnly(); m_pTextWin->SetControlBackground( GetSettings().GetStyleSettings().GetFaceColor() ); m_pTextWin->Show(); } //------------------------------------------------------------------------------ OTableDesignHelpBar::~OTableDesignHelpBar() { DBG_DTOR(OTableDesignHelpBar,NULL); ::std::auto_ptr<Window> aTemp(m_pTextWin); m_pTextWin = NULL; } //------------------------------------------------------------------------------ void OTableDesignHelpBar::SetHelpText( const String& rText ) { DBG_CHKTHIS(OTableDesignHelpBar,NULL); if(m_pTextWin) m_pTextWin->SetText( rText ); Invalidate(); } //------------------------------------------------------------------------------ void OTableDesignHelpBar::Resize() { DBG_CHKTHIS(OTableDesignHelpBar,NULL); ////////////////////////////////////////////////////////////////////// // Abmessungen parent window Size aOutputSize( GetOutputSizePixel() ); ////////////////////////////////////////////////////////////////////// // TextWin anpassen if(m_pTextWin) m_pTextWin->SetPosSizePixel( Point(STANDARD_MARGIN+1, STANDARD_MARGIN+1), Size(aOutputSize.Width()-(2*STANDARD_MARGIN)-2, aOutputSize.Height()-(2*STANDARD_MARGIN)-2) ); } //------------------------------------------------------------------------------ long OTableDesignHelpBar::PreNotify( NotifyEvent& rNEvt ) { if (rNEvt.GetType() == EVENT_LOSEFOCUS) SetHelpText(String()); return TabPage::PreNotify(rNEvt); } // ----------------------------------------------------------------------------- sal_Bool OTableDesignHelpBar::isCopyAllowed() { return m_pTextWin && m_pTextWin->GetSelected().Len(); } // ----------------------------------------------------------------------------- sal_Bool OTableDesignHelpBar::isCutAllowed() { return sal_False; } // ----------------------------------------------------------------------------- sal_Bool OTableDesignHelpBar::isPasteAllowed() { return sal_False; } // ----------------------------------------------------------------------------- void OTableDesignHelpBar::cut() { } // ----------------------------------------------------------------------------- void OTableDesignHelpBar::copy() { if ( m_pTextWin ) m_pTextWin->Copy(); } // ----------------------------------------------------------------------------- void OTableDesignHelpBar::paste() { }
1,221
2,085
<filename>exercises/fr/solution_03_06.py import spacy # Définis le composant personnalisé def length_component(doc): # Obtiens la longueur du doc doc_length = len(doc) print(f"Ce document comporte {doc_length} tokens.") # Retourne le doc return doc # Charge le petit modèle français nlp = spacy.load("fr_core_news_sm") # Ajoute le composant en premier dans le pipeline # et affiche les noms des composants nlp.add_pipe(length_component, first=True) print(nlp.pipe_names) # Traite un texte doc = nlp("Ceci est une phrase.")
210
23,901
<reponame>deepneuralmachine/google-research # coding=utf-8 # Copyright 2021 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """WT5 metrics.""" import numpy as np import sklearn.metrics import t5.evaluation def esnli_metric(targets, predictions): """Compute label accuracy and BLEU score for e-SNLI predictions. This function gets the label and explanation and computes accuracy and BLEU score on the explanation. Args: targets: list of dict of label and explanation predictions: list of dict of label and explanation Returns: a dict with accuracy and bleu score. """ def get_label_and_explanation(answers): """Helper function to get lists of labels and explanations from a dict.""" labels = [] explanations_1 = [] explanations_2 = [] for answer in answers: for key, value in answer.items(): if key == "label": labels.append(value) # In e-snli, the authors only use the first two explanations to compute # the BLEU score. elif key == "explanations": explanations_1.append("" if not value else value[0]) if len(value) > 1: explanations_2.append(value[1]) else: raise RuntimeError( "Unexpected key:%s provided. to metric fn." % (key)) if explanations_2: return labels, [explanations_1, explanations_2] else: return labels, explanations_1 def get_first_explanation_length(explanations): return len(explanations) if isinstance(explanations, str) else len( explanations[0]) target_labels, target_explanations = get_label_and_explanation(targets) # The model can only predict one explanation for prediction in predictions: if prediction["explanations"]: prediction["explanations"] = [prediction["explanations"][0]] prediction_labels, prediction_explanations = get_label_and_explanation( predictions) return { "accuracy": t5.evaluation.metrics.accuracy(target_labels, prediction_labels) ["accuracy"], "bleu": t5.evaluation.metrics.bleu(target_explanations, prediction_explanations)["bleu"], "expln1_length": get_first_explanation_length(prediction_explanations) } def extractive_explanations_metric(targets, predictions): """Compute label accuracy and macro F1 score for explanations.""" def get_labels_spans_and_expls(answers): """Gets a list of labels and spans from a list of dicts.""" labels = [] spans = [] span_arrays = [] explanations = [] for answer in answers: for key, value in answer.items(): if key == "label": labels.append(value) elif key == "overlap_spans": spans.append(value) elif key == "span_array": span_arrays.append(value) elif key == "explanations": explanations.append(value) else: raise ValueError("Unexpected key found in answers dict: %s" % key) return labels, spans, span_arrays, explanations labels_t, spans_t, arrays_t, _ = get_labels_spans_and_expls(targets) labels_p, spans_p, arrays_p, explns_p = get_labels_spans_and_expls( predictions) # Compute f1 score for each example in the target prediction pair f1_scores = [] for gt_span, pred_span in zip(spans_t, spans_p): elem_prec = len(set(gt_span) & set(pred_span)) / len(pred_span) if pred_span else 0 elem_rec = len(set(gt_span) & set(pred_span)) / len(gt_span) if gt_span else 0 if elem_prec == 0 or elem_rec == 0: elem_f1 = 0 else: elem_f1 = 2 * elem_prec * elem_rec / (elem_prec + elem_rec) f1_scores.append(elem_f1) exact_match_f1 = np.mean(f1_scores) * 100 partial_match_f1 = 100 * np.mean( [sklearn.metrics.f1_score(t, p) for t, p in zip(arrays_t, arrays_p)] ) def get_avg_num_explanations(explanations): total_explns = 0 for e in explanations: total_explns += len(e) return float(total_explns)/len(explanations) if explanations else 0.0 return { "accuracy": 100 * sklearn.metrics.accuracy_score(labels_t, labels_p), "f1": exact_match_f1, "partial match f1": partial_match_f1, "avg_explanation_count": get_avg_num_explanations(explns_p), }
1,910
14,668
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/system/phonehub/animated_loading_card.h" #include "ui/compositor/layer.h" #include "ui/compositor/paint_recorder.h" #include "ui/gfx/color_utils.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/rect_f.h" #include "ui/views/layout/layout_provider.h" namespace ash { AnimatedLoadingCard::AnimatedLoadingCard() { SetPaintToLayer(); layer()->SetFillsBoundsOpaquely(false); layer()->SetFillsBoundsCompletely(false); } AnimatedLoadingCard::~AnimatedLoadingCard() = default; void AnimatedLoadingCard::OnPaint(gfx::Canvas* canvas) { View::OnPaint(canvas); const SkColor color = SkColorSetRGB(241, 243, 244); cc::PaintFlags flags; flags.setShader(cc::PaintShader::MakeColor(color)); gfx::Rect local_bounds = gfx::Rect(layer()->size()); const float dsf = canvas->UndoDeviceScaleFactor(); gfx::RectF local_bounds_f = gfx::RectF(local_bounds); local_bounds_f.Scale(dsf); canvas->DrawRect(gfx::ToEnclosingRect(local_bounds_f), flags); } } // namespace ash
422
402
package com.vaadin.flow; import org.hamcrest.Description; import org.hamcrest.TypeSafeMatcher; import org.junit.Assert; import org.junit.Test; import org.openqa.selenium.By; import com.vaadin.flow.testutil.ChromeBrowserTest; import static org.hamcrest.Matchers.isEmptyString; import static org.hamcrest.Matchers.isOneOf; import static org.hamcrest.Matchers.not; public class InitialExtendedClientDetailsIT extends ChromeBrowserTest { private final TypeSafeMatcher<String> isParseableAsInteger() { return new TypeSafeMatcher<String>() { @Override protected boolean matchesSafely(String s) { try { Integer.parseInt(s); return true; } catch (NumberFormatException nfe) { return false; } } @Override public void describeTo(Description description) { description.appendText("only digits"); } }; } @Test public void verifyClientDetails() { open(); Assert.assertThat(findElement(By.id("screenWidth")).getText(), isParseableAsInteger()); Assert.assertThat(findElement(By.id("screenHeight")).getText(), isParseableAsInteger()); Assert.assertThat(findElement(By.id("windowInnerWidth")).getText(), isParseableAsInteger()); Assert.assertThat(findElement(By.id("windowInnerHeight")).getText(), isParseableAsInteger()); Assert.assertThat(findElement(By.id("bodyClientWidth")).getText(), isParseableAsInteger()); Assert.assertThat(findElement(By.id("bodyClientHeight")).getText(), isParseableAsInteger()); Assert.assertThat(findElement(By.id("timezoneOffset")).getText(), isParseableAsInteger()); Assert.assertThat(findElement(By.id("timeZoneId")).getText(), not(isEmptyString())); Assert.assertThat(findElement(By.id("rawTimezoneOffset")).getText(), isParseableAsInteger()); Assert.assertThat(findElement(By.id("DSTSavings")).getText(), isParseableAsInteger()); Assert.assertThat(findElement(By.id("DSTInEffect")).getText(), isOneOf("true", "false")); Assert.assertThat(findElement(By.id("currentDate")).getText(), not(isEmptyString())); Assert.assertThat(findElement(By.id("touchDevice")).getText(), isOneOf("true", "false")); Assert.assertThat(findElement(By.id("windowName")).getText(), not(isEmptyString())); } }
1,222
5,169
{ "name": "ICLocationFramework", "version": "3.0", "summary": "Description of ICLocationFramework for cocoapods.", "description": "This component helps you to get location via calling only a single function and get it in callback.", "homepage": "https://github.com/kritikamiddha/ICLocationFrameworkRepo", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "<NAME>": "<EMAIL>" }, "source": { "http": "https://github.com/kritikamiddha/ICLocationFrameworkRepo/releases/download/3.0/SelfieCheckFramework.zip" }, "platforms": { "ios": "10.0" }, "ios": { "vendored_frameworks": "SelfieCheckFramework.framework" }, "swift_version": "4.0" }
265
598
""" Command line program for filtering line-based Eliot logs. """ from __future__ import unicode_literals, absolute_import if __name__ == "__main__": import eliot.filter eliot.filter.main() import sys from datetime import datetime, timedelta from json import JSONEncoder from ._bytesjson import dumps, loads class _DatetimeJSONEncoder(JSONEncoder): """ JSON encoder that supports L{datetime}. """ def default(self, o): if isinstance(o, datetime): return o.isoformat() return JSONEncoder.default(self, o) class EliotFilter(object): """ Filter Eliot log lines using a Python expression. @ivar code: A Python code object, the compiled filter expression. """ _SKIP = object() def __init__(self, expr, incoming, output): """ @param expr: A Python expression that will be called for each log message. @type expr: L{str} @param incoming: An iterable of L{bytes}, each of which is a serialized Eliot message. @param output: A file to which output should be written. @type output: L{file} or a file-like object. """ self.code = compile(expr, "<string>", "eval") self.incoming = incoming self.output = output def run(self): """ For each incoming message, decode the JSON, evaluate expression, encode as JSON and write that to the output file. """ for line in self.incoming: message = loads(line) result = self._evaluate(message) if result is self._SKIP: continue self.output.write(dumps(result, cls=_DatetimeJSONEncoder) + b"\n") def _evaluate(self, message): """ Evaluate the expression with the given Python object in its locals. @param message: A decoded JSON input. @return: The resulting object. """ return eval( self.code, globals(), { "J": message, "timedelta": timedelta, "datetime": datetime, "SKIP": self._SKIP, }, ) USAGE = b"""\ Usage: cat eliot.log | python -m eliot.filter <expr> Read JSON-expression per line from stdin, and filter it using a Python expression <expr>. The expression will have a local `J` containing decoded JSON. `datetime` and `timedelta` from Python's `datetime` module are also available as locals, containing the corresponding classes. `SKIP` is also available, if it's the expression result that indicates nothing should be output. The output will be written to stdout using JSON serialization. `datetime` objects will be serialized to ISO format. Examples: - Pass through the messages unchanged: $ cat eliot.log | python -m eliot.filter J - Retrieve a specific field from a specific message type, dropping messages of other types: $ cat eliot.log | python -m eliot.filter \\ "J['field'] if J.get('message_type') == 'my:message' else SKIP" """ def main(sys=sys): """ Run the program. Accept arguments from L{sys.argv}, read from L{sys.stdin}, write to L{sys.stdout}. @param sys: An object with same interface and defaulting to the L{sys} module. """ if len(sys.argv) != 2: sys.stderr.write(USAGE) return 1 EliotFilter(sys.argv[1], sys.stdin, sys.stdout).run() return 0
1,345
1,473
/* * Copyright 2020 NAVER Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.navercorp.pinpoint.common.server.bo.grpc; import com.navercorp.pinpoint.common.server.bo.SpanBo; import com.navercorp.pinpoint.common.server.bo.SpanChunkBo; import com.navercorp.pinpoint.common.server.bo.SpanEventBo; import com.navercorp.pinpoint.common.server.bo.filter.SpanEventFilter; import com.navercorp.pinpoint.common.server.util.AcceptedTimeService; import com.navercorp.pinpoint.grpc.Header; import com.navercorp.pinpoint.grpc.trace.PSpan; import com.navercorp.pinpoint.grpc.trace.PSpanChunk; import com.navercorp.pinpoint.grpc.trace.PSpanEvent; import java.util.ArrayList; import java.util.List; import java.util.Objects; /** * @author <NAME>(emeroad) */ public class CollectorGrpcSpanFactory implements GrpcSpanFactory { private final SpanEventFilter spanEventFilter; private final AcceptedTimeService acceptedTimeService; private final GrpcSpanBinder grpcBinder; public CollectorGrpcSpanFactory(GrpcSpanBinder grpcBinder, SpanEventFilter spanEventFilter, AcceptedTimeService acceptedTimeService) { this.grpcBinder = Objects.requireNonNull(grpcBinder, "grpcBinder"); this.spanEventFilter = spanEventFilter; this.acceptedTimeService = acceptedTimeService; } @Override public SpanBo buildSpanBo(PSpan pSpan, Header header) { final SpanBo spanBo = this.grpcBinder.bindSpanBo(pSpan, header); final long acceptedTime = acceptedTimeService.getAcceptedTime(); spanBo.setCollectorAcceptTime(acceptedTime); final List<PSpanEvent> pSpanEventList = pSpan.getSpanEventList(); List<SpanEventBo> spanEventBos = buildSpanEventBoList(pSpanEventList); spanBo.addSpanEventBoList(spanEventBos); return spanBo; } @Override public SpanChunkBo buildSpanChunkBo(PSpanChunk pSpanChunk, Header header) { final SpanChunkBo spanChunkBo = this.grpcBinder.bindSpanChunkBo(pSpanChunk, header); final long acceptedTime = acceptedTimeService.getAcceptedTime(); spanChunkBo.setCollectorAcceptTime(acceptedTime); final List<PSpanEvent> pSpanEventList = pSpanChunk.getSpanEventList(); List<SpanEventBo> spanEventList = buildSpanEventBoList(pSpanEventList); spanChunkBo.addSpanEventBoList(spanEventList); return spanChunkBo; } private List<SpanEventBo> buildSpanEventBoList(List<PSpanEvent> pSpanEventList) { final List<SpanEventBo> spanEventBos = this.grpcBinder.bindSpanEventBoList(pSpanEventList); if (applyFilter(spanEventBos)) { return filter(spanEventBos); } return spanEventBos; } private boolean applyFilter(List<SpanEventBo> spanEventBoList) { if (spanEventFilter == null) { return false; } for (SpanEventBo spanEventBo : spanEventBoList) { if (spanEventFilter.filter(spanEventBo) == SpanEventFilter.REJECT) { return true; } } return false; } private List<SpanEventBo> filter(List<SpanEventBo> spanEventBoList) { final List<SpanEventBo> filteredList = new ArrayList<>(); for (SpanEventBo spanEventBo : spanEventBoList) { if (spanEventFilter.filter(spanEventBo) == SpanEventFilter.ACCEPT) { filteredList.add(spanEventBo); } } return filteredList; } }
1,515
647
<reponame>gilbertguoze/trick<filename>trick_source/data_products/Log/darwin_dl.c /* * This file is a wrapper for the dlopen, dlclose, dlsym and dlerror * routines for Darwin */ #ifdef __APPLE__ #include <stdio.h> #include <string.h> #include <stdlib.h> #include "darwin_dl.h" char dyn_buf[1024]; char noerror[] = "noerror"; static char *dyn_error = NULL; void *dlopen(const char *filename, int mode) { NSObjectFileImage image; dyn_error = NULL; if (NSCreateObjectFileImageFromFile(filename, &image) != NSObjectFileImageSuccess) { dyn_error = "Could not open file"; return NULL; } return NSLinkModule(image, filename, NSLINKMODULE_OPTION_PRIVATE); } void dlclose(void *handle) { dyn_error = NULL; NSUnLinkModule(handle, FALSE); return; } void *dlsym(void *handle, char *funcname) { NSSymbol symbol; int cb = strlen(funcname) + 2; char *symname = (char *) alloca(cb); sprintf(symname, "_%s", funcname); dyn_error = NULL; symbol = NSLookupSymbolInModule(handle, symname); if (symbol) { return (void *) NSAddressOfSymbol(symbol); } else { sprintf(dyn_buf, "Symbol [%s] not found", symname); dyn_error = dyn_buf; return (void *) NULL; } } char *dlerror(void) { return dyn_error; } #endif
690