text:
package com.snowplowanalytics.snowplow.enrich.common
package enrichments
package registry
package apirequest

// Scalaz
import scalaz._
import Scalaz._

// json4s
import org.json4s.JInt

// specs2
import org.specs2.Specification
import org.specs2.scalaz.ValidationMatchers
import org.specs2.mock.Mockito

class CacheSpec extends Specification with ValidationMatchers with Mockito {
  def is = s2"""
  This is a specification to test the API Request enrichment cache
  Update on identical URLs           $e1
  Preserve ttl of cache              $e2
  Remove unused value                $e3
  Update on identical URLs with body $e4
  """

  def e1 = {
    val cache = Cache(3, 2)
    val key   = ApiRequestEnrichment.cacheKey(url = "http://api.acme.com/url", body = None)

    cache.put(key, JInt(42).success)
    cache.put(key, JInt(52).success)
    cache.get(key) must beSome.like {
      case v => v must beSuccessful(JInt(52))
    } and (cache.actualLoad must beEqualTo(1))
  }

  def e2 = {
    val cache = Cache(3, 2)
    val key   = ApiRequestEnrichment.cacheKey(url = "http://api.acme.com/url", body = None)
    cache.put(key, JInt(42).success)
    Thread.sleep(3000)
    cache.get(key) must beNone and (cache.actualLoad must beEqualTo(0))
  }

  def e3 = {
    val cache = Cache(2, 2)
    val key1  = ApiRequestEnrichment.cacheKey(url = "http://api.acme.com/url1", body = None)
    cache.put(key1, JInt(32).success)

    val key2 = ApiRequestEnrichment.cacheKey(url = "http://api.acme.com/url2", body = None)
    cache.put(key2, JInt(32).success)

    val key3 = ApiRequestEnrichment.cacheKey(url = "http://api.acme.com/url3", body = None)
    cache.put(key3, JInt(32).success)

    cache.get(key1) must beNone and (cache.actualLoad must beEqualTo(2))
  }

  def e4 = {
    val cache = Cache(3, 2)
    val key   = ApiRequestEnrichment.cacheKey(url = "http://api.acme.com/url", body = Some("""{"value":"42"}"""))

    cache.put(key, JInt(33).success)
    cache.put(key, JInt(42).success)
    cache.get(key) must beSome.like {
      case v => v must beSuccessful(JInt(42))
    } and (cache.actualLoad must beEqualTo(1))
  }
}


text:
package com.konkerlabs.platform.registry.business.services.api;

import java.time.Instant;
import java.util.List;

import com.konkerlabs.platform.registry.business.model.Application;
import com.konkerlabs.platform.registry.business.model.Event;
import com.konkerlabs.platform.registry.business.model.Tenant;
import com.konkerlabs.platform.registry.business.model.User;

public interface DeviceEventService {

    enum Validations {
        DEVICE_NULL("service.device_events.device.not_null"),
        CHANNEL_NULL("service.device_events.channel.not_null"),
        EVENT_NULL("service.device_events.event.not_null"),
        EVENT_PAYLOAD_NULL("service.device_events.event_payload.not_null"),
        LIMIT_NULL("service.device_events.limit.not_null");

        public String getCode() {
            return code;
        }

        private String code;

        Validations(String code) {
            this.code = code;
        }
    }

    /**
     * Return all existing incoming device events by provided arguments
     *
     * @param tenant
     * @param application
     * @param user
     * @param deviceGuid
     * @param locationGuid
     * @param startingTimestamp
     * @param endTimestamp
     * @param limit
     * @return Found events
     */
    ServiceResponse<List<Event>> findIncomingBy(Tenant tenant,
                                                Application application,
                                                User user,
                                                String deviceGuid,
                                                String locationGuid,
                                                String channel,
                                                Instant startingTimestamp,
                                                Instant endTimestamp,
                                                boolean ascending,
                                                Integer limit);

    /**
     * Return all existing incoming device events by provided arguments
     *
     * @param tenant
     * @param application
     * @param deviceGuid
     * @param locationGuid
     * @param startingTimestamp
     * @param endTimestamp
     * @param limit
     * @return Found events
     */
    ServiceResponse<List<Event>> findIncomingBy(Tenant tenant,
                                                Application application,
                                                String deviceGuid,
                                                String locationGuid,
                                                String channel,
                                                Instant startingTimestamp,
                                                Instant endTimestamp,
                                                boolean ascending,
                                                Integer limit);

    /**
     * Return all existing incoming device events by provided arguments
     *
     * @param tenant
     * @param application
     * @param user
     * @param deviceGuid
     * @param locationGuid
     * @param startingTimestamp
     * @param endTimestamp
     * @param limit
     * @return Found events
     */
    ServiceResponse<List<Event>> findOutgoingBy(Tenant tenant,
                                                Application application,
                                                User user,
                                                String deviceGuid,
                                                String locationGuid,
                                                String channel,
                                                Instant startingTimestamp,
                                                Instant endTimestamp,
                                                boolean ascending,
                                                Integer limit);

    /**
     * Return all existing incoming device events by provided arguments
     *
     * @param tenant
     * @param application
     * @param deviceGuid
     * @param locationGuid
     * @param startingTimestamp
     * @param endTimestamp
     * @param limit
     * @return Found events
     */
    ServiceResponse<List<Event>> findOutgoingBy(Tenant tenant,
                                                Application application,
                                                String deviceGuid,
                                                String locationGuid,
                                                String channel,
                                                Instant startingTimestamp,
                                                Instant endTimestamp,
                                                boolean ascending,
                                                Integer limit);
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.camel.model;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;

import org.apache.camel.Expression;
import org.apache.camel.Predicate;
import org.apache.camel.Processor;
import org.apache.camel.builder.ExpressionClause;
import org.apache.camel.model.language.ExpressionDefinition;
import org.apache.camel.processor.UnitOfWorkProcessor;
import org.apache.camel.processor.aggregate.AggregateProcessor;
import org.apache.camel.processor.aggregate.AggregationStrategy;
import org.apache.camel.processor.aggregate.GroupedExchangeAggregationStrategy;
import org.apache.camel.spi.AggregationRepository;
import org.apache.camel.spi.ExecutorServiceManager;
import org.apache.camel.spi.RouteContext;
import org.apache.camel.util.concurrent.SynchronousExecutorService;

/**
 * Represents an XML <aggregate/> element
 *
 * @version
 */
@XmlRootElement(name = "aggregate")
@XmlAccessorType(XmlAccessType.FIELD)
public class AggregateDefinition extends ProcessorDefinition<AggregateDefinition> implements ExecutorServiceAwareDefinition<AggregateDefinition> {
    @XmlElement(name = "correlationExpression", required = true)
    private ExpressionSubElementDefinition correlationExpression;
    @XmlElement(name = "completionPredicate")
    private ExpressionSubElementDefinition completionPredicate;
    @XmlElement(name = "completionTimeout")
    private ExpressionSubElementDefinition completionTimeoutExpression;
    @XmlElement(name = "completionSize")
    private ExpressionSubElementDefinition completionSizeExpression;
    @XmlTransient
    private ExpressionDefinition expression;
    @XmlElementRef
    private List<ProcessorDefinition> outputs = new ArrayList<ProcessorDefinition>();
    @XmlTransient
    private AggregationStrategy aggregationStrategy;
    @XmlTransient
    private ExecutorService executorService;
    @XmlTransient
    private AggregationRepository aggregationRepository;
    @XmlAttribute
    private Boolean parallelProcessing;
    @XmlAttribute
    private String executorServiceRef;
    @XmlAttribute
    private String aggregationRepositoryRef;
    @XmlAttribute
    private String strategyRef;
    @XmlAttribute
    private Integer completionSize;
    @XmlAttribute
    private Long completionInterval;
    @XmlAttribute
    private Long completionTimeout;
    @XmlAttribute
    private Boolean completionFromBatchConsumer;
    @XmlAttribute
    private Boolean groupExchanges;
    @XmlAttribute
    private Boolean eagerCheckCompletion;
    @XmlAttribute
    private Boolean ignoreInvalidCorrelationKeys;
    @XmlAttribute
    private Integer closeCorrelationKeyOnCompletion;
    @XmlAttribute
    private Boolean discardOnCompletionTimeout;
    @XmlAttribute
    private Boolean forceCompletionOnStop;

    public AggregateDefinition() {
    }

    public AggregateDefinition(Predicate predicate) {
        this();
        if (predicate != null) {
            setExpression(new ExpressionDefinition(predicate));
        }
    }

    public AggregateDefinition(Expression correlationExpression) {
        this();
        if (correlationExpression != null) {
            setExpression(new ExpressionDefinition(correlationExpression));
        }
    }

    public AggregateDefinition(ExpressionDefinition correlationExpression) {
        this();
        this.expression = correlationExpression;
    }

    public AggregateDefinition(Expression correlationExpression, AggregationStrategy aggregationStrategy) {
        this(correlationExpression);
        this.aggregationStrategy = aggregationStrategy;
    }

    @Override
    public String toString() {
        return "Aggregate[" + description() + " -> " + getOutputs() + "]";
    }

    protected String description() {
        return getExpression() != null ? getExpression().getLabel() : "";
    }

    @Override
    public String getShortName() {
        return "aggregate";
    }

    @Override
    public String getLabel() {
        return "aggregate[" + description() + "]";
    }

    @Override
    public Processor createProcessor(RouteContext routeContext) throws Exception {
        return createAggregator(routeContext);
    }

    protected AggregateProcessor createAggregator(RouteContext routeContext) throws Exception {
        Processor processor = this.createChildProcessor(routeContext, true);
        // wrap the aggregated route in a unit of work processor
        processor = new UnitOfWorkProcessor(routeContext, processor);

        Expression correlation = getExpression().createExpression(routeContext);
        AggregationStrategy strategy = createAggregationStrategy(routeContext);

        executorService = ProcessorDefinitionHelper.getConfiguredExecutorService(routeContext, "Aggregator", this);
        if (executorService == null) {
            // executor service is mandatory for the Aggregator
            ExecutorServiceManager executorServiceManager = routeContext.getCamelContext().getExecutorServiceManager();
            if (isParallelProcessing()) {
                executorService = executorServiceManager.newDefaultThreadPool(this, "Aggregator");
            } else {
                // we do not run in parallel mode, but use a synchronous executor, so we run in current thread
                executorService = new SynchronousExecutorService();
            }
        }
        AggregateProcessor answer = new AggregateProcessor(routeContext.getCamelContext(), processor, correlation, strategy, executorService);

        AggregationRepository repository = createAggregationRepository(routeContext);
        if (repository != null) {
            answer.setAggregationRepository(repository);
        }

        // set other options
        answer.setParallelProcessing(isParallelProcessing());
        if (getCompletionPredicate() != null) {
            Predicate predicate = getCompletionPredicate().createPredicate(routeContext);
            answer.setCompletionPredicate(predicate);
        }
        if (getCompletionTimeoutExpression() != null) {
            Expression expression = getCompletionTimeoutExpression().createExpression(routeContext);
            answer.setCompletionTimeoutExpression(expression);
        }
        if (getCompletionTimeout() != null) {
            answer.setCompletionTimeout(getCompletionTimeout());
        }
        if (getCompletionInterval() != null) {
            answer.setCompletionInterval(getCompletionInterval());
        }
        if (getCompletionSizeExpression() != null) {
            Expression expression = getCompletionSizeExpression().createExpression(routeContext);
            answer.setCompletionSizeExpression(expression);
        }
        if (getCompletionSize() != null) {
            answer.setCompletionSize(getCompletionSize());
        }
        if (getCompletionFromBatchConsumer() != null) {
            answer.setCompletionFromBatchConsumer(isCompletionFromBatchConsumer());
        }
        if (getEagerCheckCompletion() != null) {
            answer.setEagerCheckCompletion(isEagerCheckCompletion());
        }
        if (getIgnoreInvalidCorrelationKeys() != null) {
            answer.setIgnoreInvalidCorrelationKeys(isIgnoreInvalidCorrelationKeys());
        }
        if (getCloseCorrelationKeyOnCompletion() != null) {
            answer.setCloseCorrelationKeyOnCompletion(getCloseCorrelationKeyOnCompletion());
        }
        if (getDiscardOnCompletionTimeout() != null) {
            answer.setDiscardOnCompletionTimeout(isDiscardOnCompletionTimeout());
        }
        if (getForceCompletionOnStop() != null) {
            answer.setForceCompletionOnStop(getForceCompletionOnStop());
        }

        return answer;
    }

    @Override
    protected void configureChild(ProcessorDefinition output) {
        if (expression != null && expression instanceof ExpressionClause) {
            ExpressionClause clause = (ExpressionClause) expression;
            if (clause.getExpressionType() != null) {
                // if using the Java DSL then the expression may have been set using the
                // ExpressionClause which is a fancy builder to define expressions and predicates
                // using fluent builders in the DSL. However we need afterwards a callback to
                // reset the expression to the expression type the ExpressionClause did build for us
                expression = clause.getExpressionType();
                // set the correlation expression from the expression type, as the model definition
                // would then be accurate
                correlationExpression = new ExpressionSubElementDefinition();
                correlationExpression.setExpressionType(clause.getExpressionType());
            }
        }
    }

    private AggregationStrategy createAggregationStrategy(RouteContext routeContext) {
        AggregationStrategy strategy = getAggregationStrategy();
        if (strategy == null && strategyRef != null) {
            strategy = routeContext.lookup(strategyRef, AggregationStrategy.class);
        }

        if (groupExchanges != null && groupExchanges) {
            if (strategy != null || strategyRef != null) {
                throw new IllegalArgumentException("Options groupExchanges and AggregationStrategy cannot be enabled at the same time");
            }
            if (eagerCheckCompletion != null && !eagerCheckCompletion) {
                throw new IllegalArgumentException("Option eagerCheckCompletion cannot be false when groupExchanges has been enabled");
            }
            // set eager check to enabled by default when using grouped exchanges
            setEagerCheckCompletion(true);
            // if grouped exchange is enabled then use special strategy for that
            strategy = new GroupedExchangeAggregationStrategy();
        }

        if (strategy == null) {
            throw new IllegalArgumentException("AggregationStrategy or AggregationStrategyRef must be set on " + this);
        }
        return strategy;
    }

    private AggregationRepository createAggregationRepository(RouteContext routeContext) {
        AggregationRepository repository = getAggregationRepository();
        if (repository == null && aggregationRepositoryRef != null) {
            repository = routeContext.lookup(aggregationRepositoryRef, AggregationRepository.class);
            if (repository == null) {
                throw new IllegalArgumentException("AggregationRepositoryRef " + aggregationRepositoryRef + " not found in registry.");
            }
        }
        return repository;
    }

    public AggregationStrategy getAggregationStrategy() {
        return aggregationStrategy;
    }

    public void setAggregationStrategy(AggregationStrategy aggregationStrategy) {
        this.aggregationStrategy = aggregationStrategy;
    }

    public String getAggregationStrategyRef() {
        return strategyRef;
    }

    public void setAggregationStrategyRef(String aggregationStrategyRef) {
        this.strategyRef = aggregationStrategyRef;
    }

    public Integer getCompletionSize() {
        return completionSize;
    }

    public void setCompletionSize(Integer completionSize) {
        this.completionSize = completionSize;
    }

    public Long getCompletionInterval() {
        return completionInterval;
    }

    public void setCompletionInterval(Long completionInterval) {
        this.completionInterval = completionInterval;
    }

    public Long getCompletionTimeout() {
        return completionTimeout;
    }

    public void setCompletionTimeout(Long completionTimeout) {
        this.completionTimeout = completionTimeout;
    }

    public ExpressionSubElementDefinition getCompletionPredicate() {
        return completionPredicate;
    }

    public void setCompletionPredicate(ExpressionSubElementDefinition completionPredicate) {
        this.completionPredicate = completionPredicate;
    }

    public ExpressionSubElementDefinition getCompletionTimeoutExpression() {
        return completionTimeoutExpression;
    }

    public void setCompletionTimeoutExpression(ExpressionSubElementDefinition completionTimeoutExpression) {
        this.completionTimeoutExpression = completionTimeoutExpression;
    }

    public ExpressionSubElementDefinition getCompletionSizeExpression() {
        return completionSizeExpression;
    }

    public void setCompletionSizeExpression(ExpressionSubElementDefinition completionSizeExpression) {
        this.completionSizeExpression = completionSizeExpression;
    }

    public Boolean getGroupExchanges() {
        return groupExchanges;
    }

    public boolean isGroupExchanges() {
        return groupExchanges != null && groupExchanges;
    }

    public void setGroupExchanges(Boolean groupExchanges) {
        this.groupExchanges = groupExchanges;
    }

    public Boolean getCompletionFromBatchConsumer() {
        return completionFromBatchConsumer;
    }

    public boolean isCompletionFromBatchConsumer() {
        return completionFromBatchConsumer != null && completionFromBatchConsumer;
    }

    public void setCompletionFromBatchConsumer(Boolean completionFromBatchConsumer) {
        this.completionFromBatchConsumer = completionFromBatchConsumer;
    }

    public ExecutorService getExecutorService() {
        return executorService;
    }

    public void setExecutorService(ExecutorService executorService) {
        this.executorService = executorService;
    }

    public Boolean getParallelProcessing() {
        return parallelProcessing;
    }

    public boolean isParallelProcessing() {
        return parallelProcessing != null && parallelProcessing;
    }

    public void setParallelProcessing(boolean parallelProcessing) {
        this.parallelProcessing = parallelProcessing;
    }

    public String getExecutorServiceRef() {
        return executorServiceRef;
    }

    public void setExecutorServiceRef(String executorServiceRef) {
        this.executorServiceRef = executorServiceRef;
    }

    public String getStrategyRef() {
        return strategyRef;
    }

    public void setStrategyRef(String strategyRef) {
        this.strategyRef = strategyRef;
    }

    public Boolean getEagerCheckCompletion() {
        return eagerCheckCompletion;
    }

    public boolean isEagerCheckCompletion() {
        return eagerCheckCompletion != null && eagerCheckCompletion;
    }

    public void setEagerCheckCompletion(Boolean eagerCheckCompletion) {
        this.eagerCheckCompletion = eagerCheckCompletion;
    }

    public Boolean getIgnoreInvalidCorrelationKeys() {
        return ignoreInvalidCorrelationKeys;
    }

    public boolean isIgnoreInvalidCorrelationKeys() {
        return ignoreInvalidCorrelationKeys != null && ignoreInvalidCorrelationKeys;
    }

    public void setIgnoreInvalidCorrelationKeys(Boolean ignoreInvalidCorrelationKeys) {
        this.ignoreInvalidCorrelationKeys = ignoreInvalidCorrelationKeys;
    }

    public Integer getCloseCorrelationKeyOnCompletion() {
        return closeCorrelationKeyOnCompletion;
    }

    public void setCloseCorrelationKeyOnCompletion(Integer closeCorrelationKeyOnCompletion) {
        this.closeCorrelationKeyOnCompletion = closeCorrelationKeyOnCompletion;
    }

    public AggregationRepository getAggregationRepository() {
        return aggregationRepository;
    }

    public void setAggregationRepository(AggregationRepository aggregationRepository) {
        this.aggregationRepository = aggregationRepository;
    }

    public String getAggregationRepositoryRef() {
        return aggregationRepositoryRef;
    }

    public void setAggregationRepositoryRef(String aggregationRepositoryRef) {
        this.aggregationRepositoryRef = aggregationRepositoryRef;
    }

    public Boolean getDiscardOnCompletionTimeout() {
        return discardOnCompletionTimeout;
    }

    public boolean isDiscardOnCompletionTimeout() {
        return discardOnCompletionTimeout != null && discardOnCompletionTimeout;
    }

    public void setDiscardOnCompletionTimeout(Boolean discardOnCompletionTimeout) {
        this.discardOnCompletionTimeout = discardOnCompletionTimeout;
    }

    // Fluent API
    //-------------------------------------------------------------------------

    /**
     * Use eager completion checking which means that the {{completionPredicate}} will use the incoming Exchange.
     * At opposed to without eager completion checking the {{completionPredicate}} will use the aggregated Exchange.
     *
     * @return builder
     */
    public AggregateDefinition eagerCheckCompletion() {
        setEagerCheckCompletion(true);
        return this;
    }

    /**
     * If a correlation key cannot be successfully evaluated it will be ignored by logging a {{DEBUG}} and then just
     * ignore the incoming Exchange.
     *
     * @return builder
     */
    public AggregateDefinition ignoreInvalidCorrelationKeys() {
        setIgnoreInvalidCorrelationKeys(true);
        return this;
    }

    /**
     * Closes a correlation key when its complete. Any late received exchanges which has a correlation key
     * that has been closed, it will be defined and a {@link org.apache.camel.processor.aggregate.ClosedCorrelationKeyException}
     * is thrown.
     *
     * @param capacity the maximum capacity of the closed correlation key cache.
     *                 Use <tt>0</tt> or negative value for unbounded capacity.
     * @return builder
     */
    public AggregateDefinition closeCorrelationKeyOnCompletion(int capacity) {
        setCloseCorrelationKeyOnCompletion(capacity);
        return this;
    }

    /**
     * Discards the aggregated message on completion timeout.
     *

     * This means on timeout the aggregated message is dropped and not sent out of the aggregator.
     *
     * @return builder
     */
    public AggregateDefinition discardOnCompletionTimeout() {
        setDiscardOnCompletionTimeout(true);
        return this;
    }

    /**
     * Enables the batch completion mode where we aggregate from a {@link org.apache.camel.BatchConsumer}
     * and aggregate the total number of exchanges the {@link org.apache.camel.BatchConsumer} has reported
     * as total by checking the exchange property {@link org.apache.camel.Exchange#BATCH_COMPLETE} when its complete.
     *
     * @return builder
     */
    public AggregateDefinition completionFromBatchConsumer() {
        setCompletionFromBatchConsumer(true);
        return this;
    }

    /**
     * Sets the completion size, which is the number of aggregated exchanges which would
     * cause the aggregate to consider the group as complete and send out the aggregated exchange.
     *
     * @param completionSize  the completion size
     * @return builder
     */
    public AggregateDefinition completionSize(int completionSize) {
        setCompletionSize(completionSize);
        return this;
    }

    /**
     * Sets the completion size, which is the number of aggregated exchanges which would
     * cause the aggregate to consider the group as complete and send out the aggregated exchange.
     *
     * @param completionSize  the completion size as an {@link org.apache.camel.Expression} which is evaluated as a {@link Integer} type
     * @return builder
     */
    public AggregateDefinition completionSize(Expression completionSize) {
        setCompletionSizeExpression(new ExpressionSubElementDefinition(completionSize));
        return this;
    }

    /**
     * Sets the completion interval, which would cause the aggregate to consider the group as complete
     * and send out the aggregated exchange.
     *
     * @param completionInterval  the interval in millis
     * @return the builder
     */
    public AggregateDefinition completionInterval(long completionInterval) {
        setCompletionInterval(completionInterval);
        return this;
    }

    /**
     * Sets the completion timeout, which would cause the aggregate to consider the group as complete
     * and send out the aggregated exchange.
     *
     * @param completionTimeout  the timeout in millis
     * @return the builder
     */
    public AggregateDefinition completionTimeout(long completionTimeout) {
        setCompletionTimeout(completionTimeout);
        return this;
    }

    /**
     * Sets the completion timeout, which would cause the aggregate to consider the group as complete
     * and send out the aggregated exchange.
     *
     * @param completionTimeout  the timeout as an {@link Expression} which is evaluated as a {@link Long} type
     * @return the builder
     */
    public AggregateDefinition completionTimeout(Expression completionTimeout) {
        setCompletionTimeoutExpression(new ExpressionSubElementDefinition(completionTimeout));
        return this;
    }

    /**
     * Sets the aggregate strategy to use
     *
     * @param aggregationStrategy  the aggregate strategy to use
     * @return the builder
     */
    public AggregateDefinition aggregationStrategy(AggregationStrategy aggregationStrategy) {
        setAggregationStrategy(aggregationStrategy);
        return this;
    }

    /**
     * Sets the aggregate strategy to use
     *
     * @param aggregationStrategyRef  reference to the strategy to lookup in the registry
     * @return the builder
     */
    public AggregateDefinition aggregationStrategyRef(String aggregationStrategyRef) {
        setAggregationStrategyRef(aggregationStrategyRef);
        return this;
    }

    /**
     * Sets the custom aggregate repository to use.
     *

     * Will by default use {@link org.apache.camel.processor.aggregate.MemoryAggregationRepository}
     *
     * @param aggregationRepository  the aggregate repository to use
     * @return the builder
     */
    public AggregateDefinition aggregationRepository(AggregationRepository aggregationRepository) {
        setAggregationRepository(aggregationRepository);
        return this;
    }

    /**
     * Sets the custom aggregate repository to use
     *

     * Will by default use {@link org.apache.camel.processor.aggregate.MemoryAggregationRepository}
     *
     * @param aggregationRepositoryRef  reference to the repository to lookup in the registry
     * @return the builder
     */
    public AggregateDefinition aggregationRepositoryRef(String aggregationRepositoryRef) {
        setAggregationRepositoryRef(aggregationRepositoryRef);
        return this;
    }

    /**
     * Enables grouped exchanges, so the aggregator will group all aggregated exchanges into a single
     * combined Exchange holding all the aggregated exchanges in a {@link java.util.List} as a exchange
     * property with the key {@link org.apache.camel.Exchange#GROUPED_EXCHANGE}.
     *
     * @return the builder
     */
    public AggregateDefinition groupExchanges() {
        setGroupExchanges(true);
        // must use eager check when using grouped exchanges
        setEagerCheckCompletion(true);
        return this;
    }

    /**
     * Sets the predicate used to determine if the aggregation is completed
     *
     * @param predicate  the predicate
     * @return the builder
     */
    public AggregateDefinition completionPredicate(Predicate predicate) {
        checkNoCompletedPredicate();
        setCompletionPredicate(new ExpressionSubElementDefinition(predicate));
        return this;
    }

     /**
     * Sets the force completion on stop flag, which considers the current group as complete
     * and sends out the aggregated exchange when the stop event is executed
     *
     * @return builder
     */
    public AggregateDefinition forceCompletionOnStop() {
        setForceCompletionOnStop(true);
        return this;
    }

    public Boolean getForceCompletionOnStop() {
        return forceCompletionOnStop;
    }

    public boolean isForceCompletionOnStop() {
        return forceCompletionOnStop != null && forceCompletionOnStop;
    }

    public void setForceCompletionOnStop(Boolean forceCompletionOnStop) {
        this.forceCompletionOnStop = forceCompletionOnStop;
    }

    /**
     * Sending the aggregated output in parallel
     *
     * @return the builder
     */
    public AggregateDefinition parallelProcessing() {
        setParallelProcessing(true);
        return this;
    }

    public AggregateDefinition executorService(ExecutorService executorService) {
        setExecutorService(executorService);
        return this;
    }

    public AggregateDefinition executorServiceRef(String executorServiceRef) {
        setExecutorServiceRef(executorServiceRef);
        return this;
    }

    protected void checkNoCompletedPredicate() {
        if (getCompletionPredicate() != null) {
            throw new IllegalArgumentException("There is already a completionPredicate defined for this aggregator: " + this);
        }
    }

    public void setCorrelationExpression(ExpressionSubElementDefinition correlationExpression) {
        this.correlationExpression = correlationExpression;
    }

    public ExpressionSubElementDefinition getCorrelationExpression() {
        return correlationExpression;
    }

    // Section - Methods from ExpressionNode
    // Needed to copy methods from ExpressionNode here so that I could specify the
    // correlation expression as optional in JAXB

    public ExpressionDefinition getExpression() {
        if (expression == null && correlationExpression != null) {
            expression = correlationExpression.getExpressionType();
        }
        return expression;
    }

    public void setExpression(ExpressionDefinition expression) {
        this.expression = expression;
    }

    public List<ProcessorDefinition> getOutputs() {
        return outputs;
    }

    public boolean isOutputSupported() {
        return true;
    }

    public void setOutputs(List<ProcessorDefinition> outputs) {
        this.outputs = outputs;
    }

}


text:
//
// InvocationExpression.cs
//
// Author:
//   Jb Evain (jbevain@novell.com)
//
// (C) 2008 Novell, Inc. (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;

namespace System.Linq.Expressions {

	public sealed class InvocationExpression : Expression {

		Expression expression;
		ReadOnlyCollection<Expression> arguments;

		public Expression Expression {
			get { return expression; }
		}

		public ReadOnlyCollection<Expression> Arguments {
			get { return arguments; }
		}

		internal InvocationExpression (Expression expression, Type type, ReadOnlyCollection<Expression> arguments)
			: base (ExpressionType.Invoke, type)
		{
			this.expression = expression;
			this.arguments = arguments;
		}

#if !FULL_AOT_RUNTIME
		internal override void Emit (EmitContext ec)
		{
			ec.EmitCall (expression, arguments, expression.Type.GetInvokeMethod ());
		}
#endif
	}
}


text:
#ifndef __KPR_MUTEX_H__
#define __KPR_MUTEX_H__

#include "KPRTypes.h"
#include <errno.h>

namespace kpr
{
class Mutex
{
public:
    Mutex();
    ~Mutex();

    void Lock()const;
    void Unlock()const;
    bool TryLock()const;
	bool TryLock(int timeout) const;

    ThreadId GetOwner()const;

private:
    Mutex(const Mutex&);
    const Mutex& operator=(const Mutex&);

    mutable pthread_mutex_t m_mutex;
    friend class Condition;
};

class RWMutex
{
public:
    RWMutex();
    ~RWMutex();

    void ReadLock()const;
    void WriteLock()const;
    bool TryReadLock()const;
	bool TryReadLock(int timeout) const;
    bool TryWriteLock()const;
	bool TryWriteLock(int timeout)const;
    void Unlock()const;

    ThreadId GetOwner()const;

private:
    RWMutex(const RWMutex&);
    const RWMutex& operator=(const RWMutex&);

    mutable pthread_rwlock_t m_mutex;
    friend class Condition;
};

class RecursiveMutex
{
public:
    RecursiveMutex();
    ~RecursiveMutex();

    bool Lock()const;
    bool Unlock()const;
    bool TryLock()const;

    ThreadId GetOwner()const;

    unsigned int GetCount()const
    {
        return m_count;
    }

private:
    RecursiveMutex(const RecursiveMutex&);

    const RecursiveMutex& operator=(const RecursiveMutex&);

    bool  lock(int count);
    bool  tryLock();
    bool unlock();

    unsigned int reset4Condvar();

private:
    pthread_mutex_t m_mutex;
    Mutex m_internal;
    mutable unsigned int m_count;
    mutable ThreadId m_owner;

    friend class Condition;
    friend class ConditionHelper;
};
}
#endif


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
com.genzis.filtro Class Hierarchy
</TITLE>

<META NAME="date" CONTENT="2014-01-12">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
      Use
    Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Hierarchy For Package com.genzis.filtro

Package Hierarchies:
All Packages

Class Hierarchy

java.lang.Object

java.util.AbstractCollection<E> (implements java.util.Collection<E>)

java.util.AbstractList<E> (implements java.util.List<E>)

java.util.ArrayList<E> (implements java.lang.Cloneable, java.util.List<E>, java.util.RandomAccess, java.io.Serializable)

com.genzis.filtro.FilterList<T> (implements java.util.List<E>)

java.util.AbstractSet<E> (implements java.util.Set<E>)

java.util.HashSet<E> (implements java.lang.Cloneable, java.io.Serializable, java.util.Set<E>)

com.genzis.filtro.FilterSet<T> (implements java.util.Set<E>)

java.util.AbstractMap<K,V> (implements java.util.Map<K,V>)

java.util.HashMap<K,V> (implements java.lang.Cloneable, java.util.Map<K,V>, java.io.Serializable)

com.genzis.filtro.FilterMap<K,V> (implements java.util.Map<K,V>)

com.genzis.filtro.Filters

Interface Hierarchy

com.genzis.filtro.Filter<T>

      Overview
      Package
      Class
      Use
    Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
from vuln_corp import db, models

# roles 1-Admin 2-Customer
db.session.add(models.Groups('Admin'))
db.session.add(models.Groups('customer'))

db.session.add(models.User('admin', 'Jeff', 'Neel', 'admin@mil.gov', 'pw', 1, 'About admin'))
db.session.add(models.User('customer', 'Jeff', 'Neel', 'customer@iastate.edu', 'pw', 2, 'About customer'))
db.session.commit()


text:
from django.db import models, IntegrityError
from django.db.models import Manager
from django.shortcuts import get_object_or_404
from django.contrib.contenttypes.models import ContentType

# Import python libraries
import urllib

# Import django models
from spiders.models import Spider
from scrapesessions.models import SpiderSession

class DataItem(models.Model):
    """
    Represents a scraped data item
    """

    spider = models.ForeignKey(Spider)
    date_scraped = models.DateTimeField()
    link = models.URLField()
    referrer = models.URLField()
    title = models.CharField(max_length=255)
    session = models.ForeignKey(SpiderSession, blank=True, null=True)

    # Some optional stored metadata
    filename = models.CharField(max_length=255, blank=True, null=True)
    filesize = models.PositiveIntegerField(blank=True, null=True)
    last_modification_date = models.DateTimeField(blank=True, null=True)

    class Meta:
        verbose_name_plural = 'Data Items'
        verbose_name = 'Data Item'
        ordering = ['-date_scraped', 'referrer']
        unique_together = ['link', 'title']

    def __unicode__(self):
        return u'%s, %s,  -  %s' % (unicode(self.date_scraped),
                                    unicode(self.spider.title),
                                    unicode(self.title))

    def get_filename(self):
        name_components = self.link.split('/')
        if ".pdf" in name_components[-1]:
            return name_components[-1]

    def set_cached_data(self, with_url_data=False):
        if self.filename == None:
            self.filename = self.get_filename()

        if self.filesize == None or self.last_modification_date == None and with_url_data == True:
            try:
                data = urllib.urlopen(self.link)
            except:
                data = None

            try:
                filesize_string = data.info()['Content-Length']
                self.filesize = int(filesize_string)
            except:
                self.filesize = None

            try:
                last_modification_date_string = data.info()['Last-Modified']
                self.last_modification_date = datetime.strptime(last_modification_date_string, '%a, %d %b %Y %H:%M:%S %Z')
            except:
                self.last_modification_date = None

    def simple_save(self, *args, **kwargs):
        super(DataItem, self).save(*args, **kwargs) # Call the "real" save() method.


text:
#ifndef __OPENSPACE_CORE___SESSIONRECORDING___H__
#define __OPENSPACE_CORE___SESSIONRECORDING___H__

#include <openspace/properties/propertyowner.h>

#include <openspace/navigation/keyframenavigator.h>
#include <openspace/properties/scalar/boolproperty.h>
#include <openspace/scripting/lualibrary.h>
#include <vector>
#include <chrono>

namespace openspace::interaction {

struct ConversionError : public ghoul::RuntimeError {
    explicit ConversionError(std::string msg);
};

class SessionRecording : public properties::PropertyOwner {
public:

    inline static const std::string FileHeaderTitle = "OpenSpace_record/playback";
    inline static const std::string HeaderCameraAscii = "camera";
    inline static const std::string HeaderTimeAscii = "time";
    inline static const std::string HeaderScriptAscii = "script";
    inline static const std::string HeaderCommentAscii = "#";
    inline static const char HeaderCameraBinary = 'c';
    inline static const char HeaderTimeBinary = 't';
    inline static const char HeaderScriptBinary = 's';
    inline static const std::string FileExtensionBinary = ".osrec";
    inline static const std::string FileExtensionAscii = ".osrectxt";

    enum class DataMode {
        Ascii = 0,
        Binary,
        Unknown
    };

    enum class SessionState {
        Idle = 0,
        Recording,
        Playback,
        PlaybackPaused
    };

    struct Timestamps {
        double timeOs;
        double timeRec;
        double timeSim;
    };

    /*
     * Struct for storing a script substring that, if found in a saved script,
     * will be replaced by its substringReplacement counterpart.
     */
    struct ScriptSubstringReplace {
        std::string substringFound;
        std::string substringReplacement;
        ScriptSubstringReplace(std::string found, std::string replace)
            : substringFound(found)
            , substringReplacement(replace) {}
    };

    static const size_t FileHeaderVersionLength = 5;
    char FileHeaderVersion[FileHeaderVersionLength+1] = "01.00";
    char TargetConvertVersion[FileHeaderVersionLength+1] = "01.00";
    static const char DataFormatAsciiTag = 'A';
    static const char DataFormatBinaryTag = 'B';
    static const size_t keyframeHeaderSize_bytes = 33;
    static const size_t saveBufferCameraSize_min = 82;
    static const size_t saveBufferStringSize_max = 2000;
    static const size_t _saveBufferMaxSize_bytes = keyframeHeaderSize_bytes +
        + saveBufferCameraSize_min + saveBufferStringSize_max;

    using CallbackHandle = int;
    using StateChangeCallback = std::function<void()>;

    SessionRecording();
    SessionRecording(bool isGlobal);

    ~SessionRecording() override;

    /**
     * Used to de-initialize the session recording feature. Any recording or playback
     * in progress will be stopped, files closed, and keyframes in memory deleted.
     */
    void deinitialize();

    /**
     * This is called with every rendered frame. If in recording state, the camera
     * state will be saved to the recording file (if its state has changed since last).
     * If in playback state, the next keyframe will be used (if it is time to do so).
     */
    void preSynchronization();

    /**
     * If enabled, calling this function will render information about the session
     * recording that is currently taking place to the screen.
     */
    void render();

    /**
     * Current time based on playback mode
     */
    double currentTime() const;

    /**
     * Fixed delta time set by user for use during saving of frame during playback mode
     */
    double fixedDeltaTimeDuringFrameOutput() const;

    /**
     * Returns the number of microseconds that have elapsed since playback started, if
     * playback is set to be in the mode where a screenshot is captured with every
     * rendered frame (enableTakeScreenShotDuringPlayback() is used to enable this mode).
     * At the start of playback, this timer is set to the current steady_clock value.
     * However, during playback it is incremented by the fixed framerate of the playback
     * rather than the actual clock value (as in normal operation).
     *
     * \returns number of microseconds elapsed since playback started in terms of the
     *          number of rendered frames multiplied by the fixed time increment per
     *          frame
     */
    std::chrono::steady_clock::time_point currentPlaybackInterpolationTime() const;

    /**
     * Returns the simulated application time. This simulated application time is only
     * used when playback is set to be in the mode where a screenshot is captured with
     * every rendered frame (enableTakeScreenShotDuringPlayback() is used to enable this
     * mode). At the start of playback, this timer is set to the value of the current
     * applicationTime function provided by the window delegate (used during normal
     * mode or playback). However, during playback it is incremented by the fixed
     * framerate of the playback rather than the actual clock value.
     *
     * \returns application time in seconds, for use in playback-with-frames mode
     */
    double currentApplicationInterpolationTime() const;

    /**
     * Starts a recording session, which will save data to the provided filename
     * according to the data format specified, and will continue until recording is
     * stopped using stopRecording() method.
     *
     * \param filename file saved with recorded keyframes.
     *
     * \returns true if recording to file starts without errors.
     */
    bool startRecording(const std::string& filename);

    /**
     * Starts a recording session, which will save data to the provided filename
     * in ASCII data format until recording is stopped using stopRecording() method.
     *
     * \param filename file saved with recorded keyframes.
     *
     * \return \c true if recording to file starts without errors
     */
    void setRecordDataFormat(DataMode dataMode);

    /**
     * Used to stop a recording in progress. If open, the recording file will be closed,
     * and all keyframes deleted from memory.
     */
    void stopRecording();

    /**
     * Used to check if a session recording is in progress.
     *
     * \return true if recording is in progress
     */
    bool isRecording() const;

    /**
     * Starts a playback session, which can run in one of three different time modes.
     *
     * \param filename file containing recorded keyframes to play back. The file path
     *                 is relative to the base recordings directory specified in the
     *                 config file by the RECORDINGS variable
     * \param timeMode which of the 3 time modes to use for time reference during
     * \param forceSimTimeAtStart if true simulation time is forced to that of playback
     *        playback: recorded time, application time, or simulation time. See the
     *        LuaLibrary entry for SessionRecording for details on these time modes
     * \param loop if true then the file will playback in loop mode, continuously
     *             looping back to the beginning until it is manually stopped
     *
     * \return \c true if recording to file starts without errors
     */
    bool startPlayback(std::string& filename, KeyframeTimeRef timeMode,
        bool forceSimTimeAtStart, bool loop);

    /**
     * Used to stop a playback in progress. If open, the playback file will be closed,
     * and all keyframes deleted from memory.
     */
    void stopPlayback();

    /**
     * Returns playback pause status.
     *
     * \return \c true if playback is paused
     */
    bool isPlaybackPaused();

    /**
     * Pauses a playback session. This does both the normal pause functionality of
     * setting simulation delta time to zero, and pausing the progression through the
     * timeline.
     *
     * \param pause if true, then will set playback timeline progression to zero
     */
    void setPlaybackPause(bool pause);

    /**
     * Enables that rendered frames should be saved during playback
     * \param fps Number of frames per second.
     */
    void enableTakeScreenShotDuringPlayback(int fps);

    /**
     * Used to disable that renderings are saved during playback
     */
    void disableTakeScreenShotDuringPlayback();

    /**
     * Used to check if a session playback is in progress.
     * \returns true if playback is in progress.
     */
    bool isPlayingBack() const;

    /**
     * Is saving frames during playback
     */
    bool isSavingFramesDuringPlayback() const;

    /**
     * Used to obtain the state of idle/recording/playback.
     *
     * \return int value of state as defined by struct SessionState
     */
    SessionState state() const;

    /**
     * Used to trigger a save of the camera states (position, rotation, focus node,
     * whether it is following the rotation of a node, and timestamp). The data will be
     * saved to the recording file only if a recording is currently in progress.
     */
    void saveCameraKeyframeToTimeline();

    /**
     * Used to trigger a save of the current timing states. The data will be saved to the
     * recording file only if a recording is currently in progress.
     */
    void saveTimeKeyframeToTimeline();

    /**
     * Used to trigger a save of a script to the recording file, but only if a recording
     * is currently in progress.
     *
     * \param scriptToSave String of the Lua command to be saved
     */
    void saveScriptKeyframeToTimeline(std::string scriptToSave);

    /**
     * \return The Lua library that contains all Lua functions available to affect the
     * interaction
     */
    static openspace::scripting::LuaLibrary luaLibrary();

    /**
     * Used to request a callback for notification of playback state change.
     *
     * \param cb function handle for callback
     *
     * \return CallbackHandle value of callback number
     */
    CallbackHandle addStateChangeCallback(StateChangeCallback cb);

    /**
     * Removes the callback for notification of playback state change.
     *
     * \param callback function handle for the callback
     */
    void removeStateChangeCallback(CallbackHandle handle);

    /**
     * Provides list of available playback files.
     *
     * \return vector of filenames in recordings dir
     */
    std::vector<std::string> playbackList() const;

    /**
     * Reads a camera keyframe from a binary format playback file, and populates input
     * references with the parameters of the keyframe.
     *
     * \param times reference to a timestamps structure which contains recorded times
     * \param kf reference to a camera keyframe which contains camera details
     * \param file an ifstream reference to the playback file being read
     * \param lineN keyframe number in playback file where this keyframe resides
     *
     * \return true if data read has no errors
     */
    bool readCameraKeyframeBinary(Timestamps& times,
        datamessagestructures::CameraKeyframe& kf, std::ifstream& file, int lineN);

    /**
     * Reads a camera keyframe from an ascii format playback file, and populates input
     * references with the parameters of the keyframe.
     *
     * \param times reference to a timestamps structure which contains recorded times
     * \param kf reference to a camera keyframe which contains camera details
     * \param currentParsingLine string containing the most current line that was read
     * \param lineN line number in playback file where this keyframe resides
     *
     * \return true if data read has no errors
     */
    bool readCameraKeyframeAscii(Timestamps& times,
        datamessagestructures::CameraKeyframe& kf, std::string currentParsingLine,
        int lineN);

    /**
     * Reads a time keyframe from a binary format playback file, and populates input
     * references with the parameters of the keyframe.
     *
     * \param times reference to a timestamps structure which contains recorded times
     * \param kf reference to a time keyframe which contains time details
     * \param file an ifstream reference to the playback file being read
     * \param lineN keyframe number in playback file where this keyframe resides
     *
     * \return true if data read has no errors
     */
    bool readTimeKeyframeBinary(Timestamps& times,
        datamessagestructures::TimeKeyframe& kf, std::ifstream& file, int lineN);

    /**
     * Reads a time keyframe from an ascii format playback file, and populates input
     * references with the parameters of the keyframe.
     *
     * \param times reference to a timestamps structure which contains recorded times
     * \param kf reference to a time keyframe which contains time details
     * \param currentParsingLine string containing the most current line that was read
     * \param lineN line number in playback file where this keyframe resides
     *
     * \return true if data read has no errors
     */
    bool readTimeKeyframeAscii(Timestamps& times,
        datamessagestructures::TimeKeyframe& kf, std::string currentParsingLine,
        int lineN);

    /**
     * Reads a script keyframe from a binary format playback file, and populates input
     * references with the parameters of the keyframe.
     *
     * \param times reference to a timestamps structure which contains recorded times
     * \param kf reference to a script keyframe which contains the size of the script
     *        (in chars) and the text itself
     * \param file an ifstream reference to the playback file being read
     * \param lineN keyframe number in playback file where this keyframe resides
     *
     * \return true if data read has no errors
     */
    bool readScriptKeyframeBinary(Timestamps& times,
        datamessagestructures::ScriptMessage& kf, std::ifstream& file, int lineN);

    /**
     * Reads a script keyframe from an ascii format playback file, and populates input
     * references with the parameters of the keyframe.
     *
     * \param times reference to a timestamps structure which contains recorded times
     * \param kf reference to a script keyframe which contains the size of the script
     *        (in chars) and the text itself
     * \param currentParsingLine string containing the most current line that was read
     * \param lineN line number in playback file where this keyframe resides
     *
     * \return true if data read has no errors
     */
    bool readScriptKeyframeAscii(Timestamps& times,
        datamessagestructures::ScriptMessage& kf, std::string currentParsingLine,
        int lineN);

    /**
     * Writes a camera keyframe to a binary format recording file using a CameraKeyframe
     *
     * \param times reference to a timestamps structure which contains recorded times
     * \param kf reference to a camera keyframe which contains the camera details
     * \param kfBuffer a buffer temporarily used for preparing data to be written
     * \param file an ofstream reference to the recording file being written-to
     */
    void saveCameraKeyframeBinary(Timestamps& times,
        datamessagestructures::CameraKeyframe& kf, unsigned char* kfBuffer,
        std::ofstream& file);

    /**
     * Writes a camera keyframe to an ascii format recording file using a CameraKeyframe
     *
     * \param times reference to a timestamps structure which contains recorded times
     * \param kf reference to a camera keyframe which contains the camera details
     * \param file an ofstream reference to the recording file being written-to
     */
    void saveCameraKeyframeAscii(Timestamps& times,
        datamessagestructures::CameraKeyframe& kf, std::ofstream& file);

    /**
     * Writes a time keyframe to a binary format recording file using a TimeKeyframe
     *
     * \param times reference to a timestamps structure which contains recorded times
     * \param kf reference to a time keyframe which contains the time details
     * \param kfBuffer a buffer temporarily used for preparing data to be written
     * \param file an ofstream reference to the recording file being written-to
     */
    void saveTimeKeyframeBinary(Timestamps& times,
        datamessagestructures::TimeKeyframe& kf, unsigned char* kfBuffer,
        std::ofstream& file);

    /**
     * Writes a time keyframe to an ascii format recording file using a TimeKeyframe
     *
     * \param times reference to a timestamps structure which contains recorded times
     * \param kf reference to a time keyframe which contains the time details
     * \param file an ofstream reference to the recording file being written-to
     */
    void saveTimeKeyframeAscii(Timestamps& times,
        datamessagestructures::TimeKeyframe& kf, std::ofstream& file);

    /**
     * Writes a script keyframe to a binary format recording file using a ScriptMessage
     *
     * \param times reference to a timestamps structure which contains recorded times
     * \param sm reference to a ScriptMessage object which contains the script details
     * \param smBuffer a buffer temporarily used for preparing data to be written
     * \param file an ofstream reference to the recording file being written-to
     */
    void saveScriptKeyframeBinary(Timestamps& times,
        datamessagestructures::ScriptMessage& sm, unsigned char* smBuffer,
        std::ofstream& file);

    /**
     * Writes a script keyframe to an ascii format recording file using a ScriptMessage
     *
     * \param times reference to a timestamps structure which contains recorded times
     * \param sm reference to a ScriptMessage which contains the script details
     * \param file an ofstream reference to the recording file being written-to
     */
    void saveScriptKeyframeAscii(Timestamps& times,
        datamessagestructures::ScriptMessage& sm, std::ofstream& file);

    /**
     * Since session recordings only record changes, the initial conditions aren't
     * preserved when a playback starts. This function is called whenever a property
     * value is set and a recording is in progress. Before the set happens, this
     * function will read the current value of the property and store it so that when
     * the recording is finished, the initial state will be added as a set property
     * command at the beginning of the recording file, to be applied when playback
     * starts.
     *
     * \param prop The property being set
     */
    void savePropertyBaseline(properties::Property& prop);

    /**
     * Reads header information from a session recording file
     *
     * \param stream reference to ifstream that contains the session recording file data
     * \param readLen_chars number of characters to be read, which may be the expected
     *        length of the header line, or an arbitrary number of characters within it
     */
    static std::string readHeaderElement(std::ifstream& stream, size_t readLen_chars);

    /**
     * Reads header information from a session recording file
     *
     * \param stringstream reference to ifstream that contains the session recording file
     *        data
     * \param readLen_chars number of characters to be read, which may be the expected
     *        length of the header line, or an arbitrary number of characters within it
     */
    static std::string readHeaderElement(std::stringstream& stream, size_t readLen_chars);

    /**
     * Writes a header to a binary recording file buffer
     *
     * \param times reference to a timestamps structure which contains recorded times
     * \param type single character signifying the keyframe type
     * \param kfBuffer the char buffer holding the recording info to be written
     * \param idx index into write buffer (this is updated with the num of chars written)
     */
    static void saveHeaderBinary(Timestamps& times, char type, unsigned char* kfBuffer,
        size_t& idx);

    /**
     * Writes a header to an ascii recording file buffer
     *
     * \param times reference to a timestamps structure which contains recorded times
     * \param type string signifying the keyframe type
     * \param line the stringstream buffer being written to
     */
    static void saveHeaderAscii(Timestamps& times, const std::string& type,
        std::stringstream& line);

    /**
     * Saves a keyframe to an ascii recording file
     *
     * \param entry the ascii string version of the keyframe (any type)
     * \param file ofstream object to write to
     */
    static void saveKeyframeToFile(std::string entry, std::ofstream& file);

    /**
     * Checks if a specified recording file ends with a particular file extension
     *
     * \param filename the name of the file to record to
     * \param extension the file extension to check for
     */
    static bool hasFileExtension(std::string filename, std::string extension);

    /**
     * Converts file format of a session recording file to the current format version
     * (will determine the file format conversion to convert from based on the file's
     * header version number).
     *
     * \param filename name of the file to convert
     * \param depth iteration number to prevent runaway recursion (init call with zero)
     *
     * \return string containing the filename of the previous conversion step. This is
     *         used if there are multiple conversion steps where each step has to use
     *         the output of the previous.
     */
    std::string convertFile(std::string filename, int depth = 0);

    /**
     * Converts file format of a session recording file to the current format version
     * (will determine the file format conversion to convert from based on the file's
     * header version number). Accepts a relative path (currently from task runner dir)
     * rather than a path assumed to be relative to ${RECORDINGS}.
     *
     * \param filename name of the file to convert
     */
    void convertFileRelativePath(std::string filenameRelative);

    /**
     * Goes to legacy session recording inherited class, and calls its convertFile()
     * method, and then returns the resulting conversion filename.
     *
     * \param filename name of the file to convert
     * \param depth iteration number to prevent runaway recursion (init call with zero)
     *
     * \return string containing the filename of the conversion
     */
    virtual std::string getLegacyConversionResult(std::string filename, int depth);

    /*
     * Version string for file format version currently supported by this class
     *
     * \return string of the file format version this class supports
     */
    virtual std::string fileFormatVersion();

    /*
     * Version string for file format version that a conversion operation will convert
     * to (e.g. upgrades to this version). This is only relevant for inherited classes
     * that support conversion from legacy versions (if called in the base class, it
     * will return its own current version).
     *
     * \return string of the file format version this class supports
     */
    virtual std::string targetFileFormatVersion();

    /*
     * Determines a filename for the conversion result based on the original filename
     * and the file format version number.
     *
     * \param filename source filename to be converted
     *
     * \return pathname of the converted version of the file
     */
    std::string determineConversionOutFilename(const std::string filename, DataMode mode);

protected:
    properties::BoolProperty _renderPlaybackInformation;
    properties::BoolProperty _ignoreRecordedScale;

    enum class RecordedType {
        Camera = 0,
        Time,
        Script,
        Invalid
    };
    struct TimelineEntry {
        RecordedType keyframeType;
        unsigned int idxIntoKeyframeTypeArray;
        Timestamps t3stamps;
    };
    double _timestampRecordStarted = 0.0;
    Timestamps _timestamps3RecordStarted{ 0.0, 0.0, 0.0 };
    double _timestampPlaybackStarted_application = 0.0;
    double _timestampPlaybackStarted_simulation = 0.0;
    double _timestampApplicationStarted_simulation = 0.0;
    bool hasCameraChangedFromPrev(datamessagestructures::CameraKeyframe kfNew);
    double appropriateTimestamp(Timestamps t3stamps);
    double equivalentSimulationTime(double timeOs, double timeRec, double timeSim);
    double equivalentApplicationTime(double timeOs, double timeRec, double timeSim);
    void recordCurrentTimePauseState();
    void recordCurrentTimeRate();
    bool handleRecordingFile(std::string filenameIn);
    static bool isPath(std::string& filename);
    void removeTrailingPathSlashes(std::string& filename);
    bool playbackCamera();
    bool playbackTimeChange();
    bool playbackScript();
    bool playbackAddEntriesToTimeline();
    void signalPlaybackFinishedForComponent(RecordedType type);
    void handlePlaybackEnd();

    bool findFirstCameraKeyframeInTimeline();
    Timestamps generateCurrentTimestamp3(double keyframeTime);
    static void saveStringToFile(const std::string& s, unsigned char* kfBuffer,
        size_t& idx, std::ofstream& file);
    static void saveKeyframeToFileBinary(unsigned char* bufferSource, size_t size,
        std::ofstream& file);

    bool addKeyframe(Timestamps t3stamps,
        interaction::KeyframeNavigator::CameraPose keyframe, int lineNum);
    bool addKeyframe(Timestamps t3stamps,
        datamessagestructures::TimeKeyframe keyframe, int lineNum);
    bool addKeyframe(Timestamps t3stamps,
        std::string scriptToQueue, int lineNum);
    bool addKeyframeToTimeline(std::vector<TimelineEntry>& timeline, RecordedType type,
            size_t indexIntoTypeKeyframes, Timestamps t3stamps, int lineNum);

    void initializePlayback_time(double now);
    void initializePlayback_modeFlags();
    bool initializePlayback_timeline();
    void initializePlayback_triggerStart();
    void moveAheadInTime();
    void lookForNonCameraKeyframesThatHaveComeDue(double currTime);
    void updateCameraWithOrWithoutNewKeyframes(double currTime);
    bool isTimeToHandleNextNonCameraKeyframe(double currTime);
    bool processNextNonCameraKeyframeAheadInTime();
    bool findNextFutureCameraIndex(double currTime);
    bool processCameraKeyframe(double now);
    bool processScriptKeyframe();
    bool readSingleKeyframeCamera(datamessagestructures::CameraKeyframe& kf,
        Timestamps& times, DataMode mode, std::ifstream& file,
        std::string& inLine, const int lineNum);
    void saveSingleKeyframeCamera(datamessagestructures::CameraKeyframe& kf,
        Timestamps& times, DataMode mode, std::ofstream& file, unsigned char* buffer);
    bool readSingleKeyframeTime(datamessagestructures::TimeKeyframe& kf,
        Timestamps& times, DataMode mode, std::ifstream& file, std::string& inLine,
        const int lineNum);
    void saveSingleKeyframeTime(datamessagestructures::TimeKeyframe& kf,
        Timestamps& times, DataMode mode, std::ofstream& file, unsigned char* buffer);
    bool readSingleKeyframeScript(datamessagestructures::ScriptMessage& kf,
        Timestamps& times, DataMode mode, std::ifstream& file, std::string& inLine,
        const int lineNum);
    void saveSingleKeyframeScript(datamessagestructures::ScriptMessage& kf,
        Timestamps& times, DataMode mode, std::ofstream& file, unsigned char* buffer);
    void saveScriptKeyframeToPropertiesBaseline(std::string script);
    bool isPropertyAllowedForBaseline(const std::string& propString);
    unsigned int findIndexOfLastCameraKeyframeInTimeline();
    bool doesTimelineEntryContainCamera(unsigned int index) const;
    bool doesStartWithSubstring(const std::string& s, const std::string& matchSubstr);
    void trimCommandsFromScriptIfFound(std::string& script);
    void replaceCommandsFromScriptIfFound(std::string& script);

    RecordedType getNextKeyframeType();
    RecordedType getPrevKeyframeType();
    double getNextTimestamp();
    double getPrevTimestamp();
    void cleanUpPlayback();
    void cleanUpRecording();
    void cleanUpTimelinesAndKeyframes();
    bool convertEntries(std::string& inFilename, std::stringstream& inStream,
        DataMode mode, int lineNum, std::ofstream& outFile);
    virtual bool convertCamera(std::stringstream& inStream, DataMode mode, int lineNum,
        std::string& inputLine, std::ofstream& outFile, unsigned char* buff);
    virtual bool convertTimeChange(std::stringstream& inStream, DataMode mode,
        int lineNum, std::string& inputLine, std::ofstream& outFile, unsigned char* buff);
    virtual bool convertScript(std::stringstream& inStream, DataMode mode, int lineNum,
        std::string& inputLine, std::ofstream& outFile, unsigned char* buff);
    DataMode readModeFromHeader(std::string filename);
    void readPlaybackHeader_stream(std::stringstream& conversionInStream,
        std::string& version, DataMode& mode);
    void populateListofLoadedSceneGraphNodes();

    void checkIfScriptUsesScenegraphNode(std::string s);
    bool checkForScenegraphNodeAccessScene(std::string& s);
    bool checkForScenegraphNodeAccessNav(std::string& navTerm);
    std::string extractScenegraphNodeFromScene(std::string& s);
    bool checkIfInitialFocusNodeIsLoaded(unsigned int firstCamIndex);
    std::string isolateTermFromQuotes(std::string s);
    void eraseSpacesFromString(std::string& s);
    std::string getNameFromSurroundingQuotes(std::string& s);

    static void writeToFileBuffer(unsigned char* buf, size_t& idx, double src);
    static void writeToFileBuffer(unsigned char* buf, size_t& idx, std::vector<char>& cv);
    static void writeToFileBuffer(unsigned char* buf, size_t& idx, unsigned char c);
    static void writeToFileBuffer(unsigned char* buf, size_t& idx, bool b);
    void readFileIntoStringStream(std::string filename,
        std::ifstream& inputFstream, std::stringstream& stream);

    DataMode _recordingDataMode = DataMode::Binary;
    SessionState _state = SessionState::Idle;
    SessionState _lastState = SessionState::Idle;
    std::string _playbackFilename;
    std::ifstream _playbackFile;
    std::string _playbackLineParsing;
    std::ofstream _recordFile;
    int _playbackLineNum = 1;
    int _recordingEntryNum = 1;
    KeyframeTimeRef _playbackTimeReferenceMode;
    datamessagestructures::CameraKeyframe _prevRecordedCameraKeyframe;
    bool _playbackActive_camera = false;
    bool _playbackActive_time = false;
    bool _playbackActive_script = false;
    bool _hasHitEndOfCameraKeyframes = false;
    bool _playbackPausedWithinDeltaTimePause = false;
    bool _playbackLoopMode = false;
    bool _playbackForceSimTimeAtStart = false;
    double _playbackPauseOffset = 0.0;
    double _previousTime = 0.0;

    bool _saveRenderingDuringPlayback = false;
    double _saveRenderingDeltaTime = 1.0 / 30.0;
    double _saveRenderingCurrentRecordedTime = 0.0;
    std::chrono::steady_clock::duration _saveRenderingDeltaTime_interpolation_usec;
    std::chrono::steady_clock::time_point _saveRenderingCurrentRecordedTime_interpolation;
    double _saveRenderingCurrentApplicationTime_interpolation = 0.0;
    long long _saveRenderingClockInterpolation_countsPerSec = 1;
    bool _saveRendering_isFirstFrame = true;

    unsigned char _keyframeBuffer[_saveBufferMaxSize_bytes];

    bool _cleanupNeededRecording = false;
    bool _cleanupNeededPlayback = false;
    const std::string scriptReturnPrefix = "return ";

    std::vector<interaction::KeyframeNavigator::CameraPose> _keyframesCamera;
    std::vector<datamessagestructures::TimeKeyframe> _keyframesTime;
    std::vector<std::string> _keyframesScript;
    std::vector<TimelineEntry> _timeline;

    std::vector<std::string> _keyframesSavePropertiesBaseline_scripts;
    std::vector<TimelineEntry> _keyframesSavePropertiesBaseline_timeline;
    std::vector<std::string> _propertyBaselinesSaved;
    const std::vector<std::string> _propertyBaselineRejects = {
        "NavigationHandler.OrbitalNavigator.Anchor",
        "NavigationHandler.OrbitalNavigator.Aim",
        "NavigationHandler.OrbitalNavigator.RetargetAnchor",
        "NavigationHandler.OrbitalNavigator.RetargetAim"
    };
    //A script that begins with an exact match of any of the strings contained in
    // _scriptRejects will not be recorded
    const std::vector<std::string> _scriptRejects = {
        "openspace.sessionRecording.enableTakeScreenShotDuringPlayback",
        "openspace.sessionRecording.startPlayback",
        "openspace.sessionRecording.stopPlayback",
        "openspace.sessionRecording.startRecording",
        "openspace.sessionRecording.stopRecording",
        "openspace.scriptScheduler.clear"
    };
    const std::vector<std::string> _navScriptsUsingNodes = {
        "RetargetAnchor",
        "Anchor",
        "Aim"
    };
    //Any script snippet included in this vector will be trimmed from any script
    // from the script manager, before it is recorded in the session recording file.
    // The remainder of the script will be retained.
    const std::vector<std::string> _scriptsToBeTrimmed = {
        "openspace.sessionRecording.togglePlaybackPause"
    };
    //Any script snippet included in this vector will be trimmed from any script
    // from the script manager, before it is recorded in the session recording file.
    // The remainder of the script will be retained.
    const std::vector<ScriptSubstringReplace> _scriptsToBeReplaced = {
        {
            "openspace.time.pauseToggleViaKeyboard",
            "openspace.time.interpolateTogglePause"
        }
    };
    std::vector<std::string> _loadedNodes;

    unsigned int _idxTimeline_nonCamera = 0;
    unsigned int _idxTime = 0;
    unsigned int _idxScript = 0;

    unsigned int _idxTimeline_cameraPtrNext = 0;
    unsigned int _idxTimeline_cameraPtrPrev = 0;

    unsigned int _idxTimeline_cameraFirstInTimeline = 0;
    double _cameraFirstInTimeline_timestamp = 0;

    int _nextCallbackHandle = 0;
    std::vector<std::pair<CallbackHandle, StateChangeCallback>> _stateChangeCallbacks;

    DataMode _conversionDataMode = DataMode::Binary;
    int _conversionLineNum = 1;
    const int _maximumRecursionDepth = 50;
};

// Instructions for bumping the file format version with new changes:
//
// 1. Create a new subclass with the current version # in its name, such as:
//    SessionRecording_legacy_####, which inherits from SessionRecording
// 2. Override any method that changes in the new version. This includes both
//    methods in SessionRecording class and structs in
//    openspace::datamessagestructure that do data read/writes. Make the modified
//    method/struct virtual, and override it in the new legacy subclass. This
//    override will contain the code as it is before the new changes. This will
//    need to be done in every legacy subclass/struct that exists, but only if that
//    subclass does NOT already contain an override of that method/struct.
// 3. Override FileHeaderVersion with the version # of the new subclass (which is
//    the version being replaced by the new changes).
// 4. Override TargetConvertVersion with the version # with the new changes. This
//    is now the version that this legacy subclass converts up to.
// 5. Override getLegacyConversionResult method so that it creates an instance of
//    the new version subclass. This is how the current version looks back to the
//    legacy version that preceded it.
// 6. The convert method for frame types that changed will need to be changed
//    (for example SessionRecording_legacy_0085::convertScript uses its own
//    override of script keyframe for the conversion functionality).

class SessionRecording_legacy_0085 : public SessionRecording {
public:
    SessionRecording_legacy_0085() : SessionRecording() {}
    ~SessionRecording_legacy_0085() override {}
    char FileHeaderVersion[FileHeaderVersionLength+1] = "00.85";
    char TargetConvertVersion[FileHeaderVersionLength+1] = "01.00";
    std::string fileFormatVersion() override {
        return std::string(FileHeaderVersion);
    }
    std::string targetFileFormatVersion() override {
        return std::string(TargetConvertVersion);
    }
    std::string getLegacyConversionResult(std::string filename, int depth) override;

    struct ScriptMessage_legacy_0085 : public datamessagestructures::ScriptMessage {
        void read(std::istream* in) override {
            size_t strLen;
            //Read string length from file
            in->read(reinterpret_cast<char*>(&strLen), sizeof(strLen));
            if (strLen > saveBufferStringSize_max) {
                throw ConversionError("Invalid script size for conversion read");
            }
            //Read back full string
            std::vector<char> temp(strLen + 1);
            in->read(temp.data(), strLen);
            temp[strLen] = '\0';

            _script.erase();
            _script = temp.data();
        }
    };

protected:
    bool convertScript(std::stringstream& inStream, DataMode mode, int lineNum,
        std::string& inputLine, std::ofstream& outFile, unsigned char* buffer) override;
};

} // namespace openspace

#include "sessionrecording.inl"

#endif // __OPENSPACE_CORE___SESSIONRECORDING___H__


text:
<?php

defined('_JEXEC') or die;

/**
 * View to edit a contact.
 *
 * @since  1.6
 */
class ContactViewContact extends JViewLegacy
{
	/**
	 * The JForm object
	 *
	 * @var  JForm
	 */
	protected $form;

	/**
	 * The active item
	 *
	 * @var  object
	 */
	protected $item;

	/**
	 * The model state
	 *
	 * @var  object
	 */
	protected $state;

	/**
	 * Display the view.
	 *
	 * @param   string  $tpl  The name of the template file to parse; automatically searches through the template paths.
	 *
	 * @return  mixed  A string if successful, otherwise an Error object.
	 */
	public function display($tpl = null)
	{
		// Initialise variables.
		$this->form  = $this->get('Form');
		$this->item  = $this->get('Item');
		$this->state = $this->get('State');

		// Check for errors.
		if (count($errors = $this->get('Errors')))
		{
			throw new Exception(implode("\n", $errors), 500);
		}

		// If we are forcing a language in modal (used for associations).
		if ($this->getLayout() === 'modal' && $forcedLanguage = JFactory::getApplication()->input->get('forcedLanguage', '', 'cmd'))
		{
			// Set the language field to the forcedLanguage and disable changing it.
			$this->form->setValue('language', null, $forcedLanguage);
			$this->form->setFieldAttribute('language', 'readonly', 'true');

			// Only allow to select categories with All language or with the forced language.
			$this->form->setFieldAttribute('catid', 'language', '*,' . $forcedLanguage);

			// Only allow to select tags with All language or with the forced language.
			$this->form->setFieldAttribute('tags', 'language', '*,' . $forcedLanguage);
		}

		$this->addToolbar();

		return parent::display($tpl);
	}

	/**
	 * Add the page title and toolbar.
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	protected function addToolbar()
	{
		JFactory::getApplication()->input->set('hidemainmenu', true);

		$user       = JFactory::getUser();
		$userId     = $user->id;
		$isNew      = ($this->item->id == 0);
		$checkedOut = !($this->item->checked_out == 0 || $this->item->checked_out == $userId);

		// Since we don't track these assets at the item level, use the category id.
		$canDo = JHelperContent::getActions('com_contact', 'category', $this->item->catid);

		JToolbarHelper::title($isNew ? JText::_('COM_CONTACT_MANAGER_CONTACT_NEW') : JText::_('COM_CONTACT_MANAGER_CONTACT_EDIT'), 'address contact');

		// Build the actions for new and existing records.
		if ($isNew)
		{
			// For new records, check the create permission.
			if ($isNew && (count($user->getAuthorisedCategories('com_contact', 'core.create')) > 0))
			{
				JToolbarHelper::apply('contact.apply');
				JToolbarHelper::save('contact.save');
				JToolbarHelper::save2new('contact.save2new');
			}

			JToolbarHelper::cancel('contact.cancel');
		}
		else
		{
			// Since it's an existing record, check the edit permission, or fall back to edit own if the owner.
			$itemEditable = $canDo->get('core.edit') || ($canDo->get('core.edit.own') && $this->item->created_by == $userId);

			// Can't save the record if it's checked out and editable
			if (!$checkedOut && $itemEditable)
			{
				JToolbarHelper::apply('contact.apply');
				JToolbarHelper::save('contact.save');

				// We can save this record, but check the create permission to see if we can return to make a new one.
				if ($canDo->get('core.create'))
				{
					JToolbarHelper::save2new('contact.save2new');
				}
			}

			// If checked out, we can still save
			if ($canDo->get('core.create'))
			{
				JToolbarHelper::save2copy('contact.save2copy');
			}

			if (JComponentHelper::isEnabled('com_contenthistory') && $this->state->params->get('save_history', 0) && $itemEditable)
			{
				JToolbarHelper::versions('com_contact.contact', $this->item->id);
			}

			JToolbarHelper::cancel('contact.cancel', 'JTOOLBAR_CLOSE');
		}

		JToolbarHelper::divider();
		JToolbarHelper::help('JHELP_COMPONENTS_CONTACTS_CONTACTS_EDIT');
	}
}


text:
/**
 *  RouterConfig collect route information from each feature and combine them
 *  with ngRoute.
 *
 *
 *  @author  <%= answers.username %>
 *  @date    <%= answers.date %>
 *
 */
define(['lib/ConfiguratorBase', 'lib/Pluck', 'lib/Omit'], function(ConfiguratorBase, pluck, omit) {

    class Configurator extends ConfiguratorBase {
        constructor(features, app) {
            super(features, app);
        }

        _routeConfig($locationProvider, $routeProvider){
            //config each router
            this.routes.forEach(function(ro) {
                $routeProvider
                    .when(ro.when, omit(ro, ['when']));
            });

            //config default page
            var defaultRouter = this.routes.filter(route => route.isDefault)[0];
            if (defaultRouter) {
                $routeProvider.otherwise({
                    redirectTo: defaultRouter.when
                });
            }
            <% if (answers.pushState) { %>
            $locationProvider.html5Mode({
                enabled: true,
                requireBase: true
            }); <% } else { %>
            $locationProvider.html5Mode(false); <% } %>
        }

        _filterRoutes(){
            return this.features
                .filter(feature => feature.routes && feature.routes.length > 0)
                .map(feature => feature.routes)
                .reduce((previous, current) => previous.concat(current), []);
        }

        _startupWarning(routes, defaultRoutes){
            if (defaultRoutes.length === 0) {
                console.warn('There is no any default route set. Try setting isDefault to the route you preferred');
            } else if (defaultRoutes.length > 1) {
                var defaultWhens = pluck(defaultRoutes, 'when');
                console.warn('You have set [' + defaultRoutes.length + '] default routes, they are [' + defaultWhens.join(', ') + ']. Try to correct it');
            }

            var routeWhens = pluck(routes, 'when').sort();

            for (var i = 0; i < routeWhens.length - 1; i++) {
                if (routeWhens[i] === routeWhens[i + 1]) {
                    throw new Error('Duplicated Route: [ ' + routeWhens[i] + ' ]');
                }
            }
        }

        execute() {
            if (!this.features || this.features.length === 0) {
                console.warn('No features loaded');
                return;
            }

            this.routes = this._filterRoutes();

            var defaultRoutes = this.routes.filter(route => route.isDefault);

            this._startupWarning(this.routes, defaultRoutes);

            this.constant('Routes', this.routes);

            var routeConfig = this._routeConfig.bind(this);
            routeConfig.$inject = ['$locationProvider', '$routeProvider'];

            this.config(routeConfig);
        }
    }

    return Configurator;
});


text:
ALTER TABLE CMS_SITE ADD COLUMN PARENT_ID BIGINT;
ALTER TABLE CMS_SITE ADD CONSTRAINT FK_CMS_SITE_PARENT FOREIGN KEY(PARENT_ID) REFERENCES CMS_SITE(ID);


text:
#ifndef QT_NO_QWS_MOUSE_QVFB

#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>

#include <qvfbhdr.h>
#include <qmousevfb_qws.h>
#include <qwindowsystem_qws.h>
#include <qsocketnotifier.h>
#include <qapplication.h>
#include <qtimer.h>
#include <private/qcore_unix_p.h> // overrides QT_OPEN

QT_BEGIN_NAMESPACE

QVFbMouseHandler::QVFbMouseHandler(const QString &driver, const QString &device)
    : QObject(), QWSMouseHandler(driver, device)
{
    QString mouseDev = device;
    if (device.isEmpty())
        mouseDev = QLatin1String("/dev/vmouse");

    mouseFD = QT_OPEN(mouseDev.toLatin1().constData(), O_RDWR | O_NDELAY);
    if (mouseFD == -1) {
        perror("QVFbMouseHandler::QVFbMouseHandler");
        qWarning("QVFbMouseHander: Unable to open device %s",
                 qPrintable(mouseDev));
        return;
    }

    // Clear pending input
    char buf[2];
    while (QT_READ(mouseFD, buf, 1) > 0) { }

    mouseIdx = 0;

    mouseNotifier = new QSocketNotifier(mouseFD, QSocketNotifier::Read, this);
    connect(mouseNotifier, SIGNAL(activated(int)),this, SLOT(readMouseData()));
}

QVFbMouseHandler::~QVFbMouseHandler()
{
    if (mouseFD >= 0)
        QT_CLOSE(mouseFD);
}

void QVFbMouseHandler::resume()
{
    mouseNotifier->setEnabled(true);
}

void QVFbMouseHandler::suspend()
{
    mouseNotifier->setEnabled(false);
}

void QVFbMouseHandler::readMouseData()
{
    int n;
    do {
        n = QT_READ(mouseFD, mouseBuf+mouseIdx, mouseBufSize-mouseIdx);
        if (n > 0)
            mouseIdx += n;
    } while (n > 0);

    int idx = 0;
    static const int packetsize = sizeof(QPoint) + 2*sizeof(int);
    while (mouseIdx-idx >= packetsize) {
        uchar *mb = mouseBuf+idx;
        QPoint mousePos = *reinterpret_cast<QPoint *>(mb);
        mb += sizeof(QPoint);
        int bstate = *reinterpret_cast<int *>(mb);
        mb += sizeof(int);
        int wheel = *reinterpret_cast<int *>(mb);
//        limitToScreen(mousePos);
        mouseChanged(mousePos, bstate, wheel);
        idx += packetsize;
    }

    int surplus = mouseIdx - idx;
    for (int i = 0; i < surplus; i++)
        mouseBuf[i] = mouseBuf[idx+i];
    mouseIdx = surplus;
}

QT_END_NAMESPACE

#endif // QT_NO_QWS_MOUSE_QVFB


text:
import { assert } from 'chai';

import { AbstractRule } from '../../src/rules/abstract-rule';
import { Multiple } from '../../src/rules/multiple';

describe('Multiple', () => {

    it('is rule', () => {
        assert.instanceOf(new Multiple(0), AbstractRule);
    });

    it('values is valid', () => {
        assert.isTrue(new Multiple(0).validate(0));
        assert.isTrue(new Multiple(1).validate(0));
        assert.isTrue(new Multiple(1).validate(1));
        assert.isTrue(new Multiple(1).validate(2));
        assert.isTrue(new Multiple(1).validate(3));
        assert.isTrue(new Multiple(5).validate(0));
        assert.isTrue(new Multiple(5).validate(5));
        assert.isTrue(new Multiple(5).validate(10));
        assert.isTrue(new Multiple(5).validate(20));
        assert.isTrue(new Multiple(5).validate(500));
        assert.isTrue(new Multiple(5).validate(-5));
        assert.isTrue(new Multiple(5).validate(-10));
        assert.isTrue(new Multiple(5).validate(-500));
        assert.isTrue(new Multiple(1.5).validate(3));
        assert.isTrue(new Multiple(1.5).validate(6));
        assert.isTrue(new Multiple(1.5).validate('6'));
    });

    it('values is not valid', () => {
        assert.isFalse(new Multiple(0).validate(1));
        assert.isFalse(new Multiple(0).validate(''));
        assert.isFalse(new Multiple(1).validate('a'));
        assert.isFalse(new Multiple(1).validate('foo'));
        assert.isFalse(new Multiple(5).validate(11));
        assert.isFalse(new Multiple(5).validate(3));
        assert.isFalse(new Multiple(5).validate(-1));
        assert.isFalse(new Multiple(3).validate(4));
        assert.isFalse(new Multiple(10).validate(-8));
        assert.isFalse(new Multiple(10).validate(57));
        assert.isFalse(new Multiple(10).validate(21));
        assert.isFalse(new Multiple(0).validate(1));
        assert.isFalse(new Multiple(0).validate(2));
        assert.isFalse(new Multiple(1.5).validate(4));
        assert.isFalse(new Multiple(1.5).validate(2));
        assert.isFalse(new Multiple(1.5).validate('2'));
    });

});


text:
#ifndef RenderLayerCompositor_h
#define RenderLayerCompositor_h

#include "core/rendering/RenderLayer.h"
#include "core/rendering/compositing/CompositingReasonFinder.h"
#include "platform/graphics/GraphicsLayerClient.h"
#include "wtf/HashMap.h"

namespace blink {

class DocumentLifecycle;
class GraphicsLayer;
class GraphicsLayerFactory;
class Page;
class RenderPart;
class ScrollingCoordinator;

enum CompositingUpdateType {
    CompositingUpdateNone,
    CompositingUpdateAfterGeometryChange,
    CompositingUpdateAfterCompositingInputChange,
    CompositingUpdateRebuildTree,
};

enum CompositingStateTransitionType {
    NoCompositingStateChange,
    AllocateOwnCompositedLayerMapping,
    RemoveOwnCompositedLayerMapping,
    PutInSquashingLayer,
    RemoveFromSquashingLayer
};

// RenderLayerCompositor manages the hierarchy of
// composited RenderLayers. It determines which RenderLayers
// become compositing, and creates and maintains a hierarchy of
// GraphicsLayers based on the RenderLayer painting order.
//
// There is one RenderLayerCompositor per RenderView.

class RenderLayerCompositor FINAL : public GraphicsLayerClient {
    WTF_MAKE_FAST_ALLOCATED;
public:
    explicit RenderLayerCompositor(RenderView&);
    virtual ~RenderLayerCompositor();

    void updateIfNeededRecursive();

    // Return true if this RenderView is in "compositing mode" (i.e. has one or more
    // composited RenderLayers)
    bool inCompositingMode() const;
    // FIXME: Replace all callers with inCompositingMdoe and remove this function.
    bool staleInCompositingMode() const;
    // This will make a compositing layer at the root automatically, and hook up to
    // the native view/window system.
    void setCompositingModeEnabled(bool);

    // Returns true if the accelerated compositing is enabled
    bool hasAcceleratedCompositing() const { return m_hasAcceleratedCompositing; }
    bool layerSquashingEnabled() const;

    bool preferCompositingToLCDTextEnabled() const;

    bool rootShouldAlwaysComposite() const;

    // Copy the accelerated compositing related flags from Settings
    void updateAcceleratedCompositingSettings();

    // Used to indicate that a compositing update will be needed for the next frame that gets drawn.
    void setNeedsCompositingUpdate(CompositingUpdateType);

    void didLayout();

    // Whether layer's compositedLayerMapping needs a GraphicsLayer to clip z-order children of the given RenderLayer.
    bool clipsCompositingDescendants(const RenderLayer*) const;

    // Whether the given layer needs an extra 'contents' layer.
    bool needsContentsCompositingLayer(const RenderLayer*) const;

    bool supportsFixedRootBackgroundCompositing() const;
    bool needsFixedRootBackgroundLayer(const RenderLayer*) const;
    GraphicsLayer* fixedRootBackgroundLayer() const;
    void setNeedsUpdateFixedBackground() { m_needsUpdateFixedBackground = true; }

    // Issue paint invalidations of the appropriate layers when the given RenderLayer starts or stops being composited.
    void paintInvalidationOnCompositingChange(RenderLayer*);

    void fullyInvalidatePaint();

    RenderLayer* rootRenderLayer() const;
    GraphicsLayer* rootGraphicsLayer() const;
    GraphicsLayer* scrollLayer() const;
    GraphicsLayer* containerLayer() const;

    // We don't always have a root transform layer. This function lazily allocates one
    // and returns it as required.
    GraphicsLayer* ensureRootTransformLayer();

    enum RootLayerAttachment {
        RootLayerUnattached,
        RootLayerAttachedViaChromeClient,
        RootLayerAttachedViaEnclosingFrame
    };

    RootLayerAttachment rootLayerAttachment() const { return m_rootLayerAttachment; }
    void updateRootLayerAttachment();
    void updateRootLayerPosition();

    void setIsInWindow(bool);

    static RenderLayerCompositor* frameContentsCompositor(RenderPart*);
    // Return true if the layers changed.
    static bool parentFrameContentLayers(RenderPart*);

    // Update the geometry of the layers used for clipping and scrolling in frames.
    void frameViewDidChangeLocation(const IntPoint& contentsOffset);
    void frameViewDidChangeSize();
    void frameViewDidScroll();
    void frameViewScrollbarsExistenceDidChange();
    void rootFixedBackgroundsChanged();

    bool scrollingLayerDidChange(RenderLayer*);

    String layerTreeAsText(LayerTreeFlags);

    GraphicsLayer* layerForHorizontalScrollbar() const { return m_layerForHorizontalScrollbar.get(); }
    GraphicsLayer* layerForVerticalScrollbar() const { return m_layerForVerticalScrollbar.get(); }
    GraphicsLayer* layerForScrollCorner() const { return m_layerForScrollCorner.get(); }

    void resetTrackedPaintInvalidationRects();
    void setTracksPaintInvalidations(bool);

    virtual String debugName(const GraphicsLayer*) OVERRIDE;
    DocumentLifecycle& lifecycle() const;

    void updatePotentialCompositingReasonsFromStyle(RenderLayer*);

    // Whether the layer could ever be composited.
    bool canBeComposited(const RenderLayer*) const;

    // FIXME: Move allocateOrClearCompositedLayerMapping to CompositingLayerAssigner once we've fixed
    // the compositing chicken/egg issues.
    bool allocateOrClearCompositedLayerMapping(RenderLayer*, CompositingStateTransitionType compositedLayerUpdate);

    void updateDirectCompositingReasons(RenderLayer*);

    void setOverlayLayer(GraphicsLayer*);

    bool inOverlayFullscreenVideo() const { return m_inOverlayFullscreenVideo; }

private:
#if ENABLE(ASSERT)
    void assertNoUnresolvedDirtyBits();
#endif

    // GraphicsLayerClient implementation
    virtual void notifyAnimationStarted(const GraphicsLayer*, double) OVERRIDE { }
    virtual void paintContents(const GraphicsLayer*, GraphicsContext&, GraphicsLayerPaintingPhase, const IntRect&) OVERRIDE;

    virtual bool isTrackingPaintInvalidations() const OVERRIDE;

    void updateWithoutAcceleratedCompositing(CompositingUpdateType);
    void updateIfNeeded();

    void ensureRootLayer();
    void destroyRootLayer();

    void attachRootLayer(RootLayerAttachment);
    void detachRootLayer();

    void updateOverflowControlsLayers();

    Page* page() const;

    GraphicsLayerFactory* graphicsLayerFactory() const;
    ScrollingCoordinator* scrollingCoordinator() const;

    void enableCompositingModeIfNeeded();

    bool requiresHorizontalScrollbarLayer() const;
    bool requiresVerticalScrollbarLayer() const;
    bool requiresScrollCornerLayer() const;

    void applyOverlayFullscreenVideoAdjustment();

    RenderView& m_renderView;
    OwnPtr<GraphicsLayer> m_rootContentLayer;
    OwnPtr<GraphicsLayer> m_rootTransformLayer;

    CompositingReasonFinder m_compositingReasonFinder;

    CompositingUpdateType m_pendingUpdateType;

    bool m_hasAcceleratedCompositing;
    bool m_compositing;

    // The root layer doesn't composite if it's a non-scrollable frame.
    // So, after a layout we set this dirty bit to know that we need
    // to recompute whether the root layer should composite even if
    // none of its descendants composite.
    // FIXME: Get rid of all the callers of setCompositingModeEnabled
    // except the one in updateIfNeeded, then rename this to
    // m_compositingDirty.
    bool m_rootShouldAlwaysCompositeDirty;
    bool m_needsUpdateFixedBackground;
    bool m_isTrackingPaintInvalidations; // Used for testing.

    RootLayerAttachment m_rootLayerAttachment;

    // Enclosing container layer, which clips for iframe content
    OwnPtr<GraphicsLayer> m_containerLayer;
    OwnPtr<GraphicsLayer> m_scrollLayer;

    // Enclosing layer for overflow controls and the clipping layer
    OwnPtr<GraphicsLayer> m_overflowControlsHostLayer;

    // Layers for overflow controls
    OwnPtr<GraphicsLayer> m_layerForHorizontalScrollbar;
    OwnPtr<GraphicsLayer> m_layerForVerticalScrollbar;
    OwnPtr<GraphicsLayer> m_layerForScrollCorner;
#if USE(RUBBER_BANDING)
    OwnPtr<GraphicsLayer> m_layerForOverhangShadow;
#endif

    bool m_inOverlayFullscreenVideo;
};

} // namespace blink

#endif // RenderLayerCompositor_h


text:
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using JetBrains.Annotations;
using UnityEngine;

[AddComponentMenu("NGUI/Examples/Set Color on Selection"), ExecuteInEditMode, RequireComponent(typeof(UIWidget))]
// ReSharper disable once CheckNamespace
public class SetColorOnSelection : MonoBehaviour
{
    [CompilerGenerated]
    private static Dictionary<string, int> f__switchSmap4;
    private UIWidget mWidget;

    [UsedImplicitly]
    private void OnSelectionChange(string val)
    {
        if (this.mWidget == null)
        {
            this.mWidget = GetComponent<UIWidget>();
        }
        string key = val;
        if (key != null)
        {
            int num;
            if (f__switchSmap4 == null)
            {
                Dictionary<string, int> dictionary = new Dictionary<string, int>(7)
                {
                    { "White", 0 },
                    { "Red", 1 },
                    { "Green", 2 },
                    { "Blue", 3 },
                    { "Yellow", 4 },
                    { "Cyan", 5 },
                    { "Magenta", 6 }
                };
                f__switchSmap4 = dictionary;
            }
            if (f__switchSmap4.TryGetValue(key, out num))
            {
                switch (num)
                {
                    case 0:
                        this.mWidget.color = Color.white;
                        break;

                    case 1:
                        this.mWidget.color = Color.red;
                        break;

                    case 2:
                        this.mWidget.color = Color.green;
                        break;

                    case 3:
                        this.mWidget.color = Color.blue;
                        break;

                    case 4:
                        this.mWidget.color = Color.yellow;
                        break;

                    case 5:
                        this.mWidget.color = Color.cyan;
                        break;

                    case 6:
                        this.mWidget.color = Color.magenta;
                        break;
                }
            }
        }
    }
}