text:
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

defined('MOODLE_INTERNAL') || die();
require_once(__DIR__ . '/fixtures/task_fixtures.php');

/**
 * Test class for adhoc tasks.
 *
 * @package core
 * @category task
 * @copyright 2013 Damyon Wiese
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class core_adhoc_task_testcase extends advanced_testcase {

    public function test_get_next_adhoc_task() {
        $this->resetAfterTest(true);
        // Create an adhoc task.
        $task = new \core\task\adhoc_test_task();

        // Queue it.
        $task = \core\task\manager::queue_adhoc_task($task);

        $now = time();
        // Get it from the scheduler.
        $task = \core\task\manager::get_next_adhoc_task($now);
        $this->assertNotNull($task);
        $task->execute();

        \core\task\manager::adhoc_task_failed($task);
        // Should not get any task.
        $task = \core\task\manager::get_next_adhoc_task($now);
        $this->assertNull($task);

        // Should get the adhoc task (retry after delay).
        $task = \core\task\manager::get_next_adhoc_task($now + 120);
        $this->assertNotNull($task);
        $task->execute();

        \core\task\manager::adhoc_task_complete($task);

        // Should not get any task.
        $task = \core\task\manager::get_next_adhoc_task($now);
        $this->assertNull($task);
    }
}


text:
namespace Sequin.ClaimsAuthentication.Pipeline
{
    using System.Collections.Generic;

    public class OptOutCommandAuthorization : CommandAuthorization
    {
        public OptOutCommandAuthorization(IIdentityProvider identityProvider) : base(identityProvider) { }

        protected override bool IsAuthorized(CommandAuthorizationContext authorizationContext, IEnumerable<AuthorizeCommandAttribute> authorizationAttributes, bool isExplicitAnonymousCommand)
        {
            if (!isExplicitAnonymousCommand)
            {
                if (!authorizationContext.IsAuthenticated)
                {
                    authorizationContext.Reject();
                }
                else
                {
                    ProcessAuthorizationAttributes(authorizationContext, authorizationAttributes);
                }
            }

            return authorizationContext.IsAuthorized;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package javax.servlet;

import java.util.Collection;
import java.util.Set;

/**
 * TODO SERVLET3 - Add comments
 *
 * @since Servlet 3.0
 */
public interface ServletRegistration extends Registration {

	/**
	 * TODO
	 *
	 * @param urlPatterns
	 *            The URL patterns that this Servlet should be mapped to
	 * @return TODO
	 * @throws IllegalArgumentException
	 *             if urlPattern is null or empty
	 * @throws IllegalStateException
	 *             if the associated ServletContext has already been initialised
	 */
	public Set<String> addMapping(String... urlPatterns);

	public Collection<String> getMappings();

	public String getRunAsRole();

	public static interface Dynamic extends ServletRegistration, Registration.Dynamic {
		public void setLoadOnStartup(int loadOnStartup);

		public Set<String> setServletSecurity(ServletSecurityElement constraint);

		public void setMultipartConfig(MultipartConfigElement multipartConfig);

		public void setRunAsRole(String roleName);
	}
}


text:
package org.apache.nifi.reporting.prometheus.api;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import io.prometheus.client.SimpleCollector;
import org.apache.nifi.components.AllowableValue;
import org.apache.nifi.components.PropertyDescriptor;
import org.apache.nifi.controller.status.ConnectionStatus;
import org.apache.nifi.controller.status.PortStatus;
import org.apache.nifi.controller.status.ProcessGroupStatus;
import org.apache.nifi.controller.status.ProcessorStatus;

import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.Gauge;
import org.apache.nifi.controller.status.RemoteProcessGroupStatus;
import org.apache.nifi.controller.status.TransmissionStatus;
import org.apache.nifi.expression.ExpressionLanguageScope;
import org.apache.nifi.metrics.jvm.JvmMetrics;
import org.apache.nifi.processor.DataUnit;
import org.apache.nifi.processor.util.StandardValidators;
import org.apache.nifi.ssl.RestrictedSSLContextService;

public class PrometheusMetricsUtil {

    public static final AllowableValue METRICS_STRATEGY_ROOT = new AllowableValue("Root Process Group", "Root Process Group",
            "Send rollup metrics for the entire root process group");
    public static final AllowableValue METRICS_STRATEGY_PG = new AllowableValue("All Process Groups", "All Process Groups",
            "Send metrics for each process group");
    public static final AllowableValue METRICS_STRATEGY_COMPONENTS = new AllowableValue("All Components", "All Components",
            "Send metrics for each component in the system, to include processors, connections, controller services, etc.");

    private static final CollectorRegistry NIFI_REGISTRY = new CollectorRegistry();
    private static final CollectorRegistry JVM_REGISTRY = new CollectorRegistry();

    // Common properties/values
    public static final AllowableValue CLIENT_NONE = new AllowableValue("No Authentication", "No Authentication",
            "ReportingTask will not authenticate clients. Anyone can communicate with this ReportingTask anonymously");
    public static final AllowableValue CLIENT_WANT = new AllowableValue("Want Authentication", "Want Authentication",
            "ReportingTask will try to verify the client but if unable to verify will allow the client to communicate anonymously");
    public static final AllowableValue CLIENT_NEED = new AllowableValue("Need Authentication", "Need Authentication",
            "ReportingTask will reject communications from any client unless the client provides a certificate that is trusted by the TrustStore"
                    + "specified in the SSL Context Service");

    public static final PropertyDescriptor METRICS_ENDPOINT_PORT = new PropertyDescriptor.Builder()
            .name("prometheus-reporting-task-metrics-endpoint-port")
            .displayName("Prometheus Metrics Endpoint Port")
            .description("The Port where prometheus metrics can be accessed")
            .required(true)
            .expressionLanguageSupported(ExpressionLanguageScope.VARIABLE_REGISTRY)
            .defaultValue("9092")
            .addValidator(StandardValidators.INTEGER_VALIDATOR)
            .build();

    public static final PropertyDescriptor INSTANCE_ID = new PropertyDescriptor.Builder()
            .name("prometheus-reporting-task-instance-id")
            .displayName("Instance ID")
            .description("Id of this NiFi instance to be included in the metrics sent to Prometheus")
            .required(true)
            .expressionLanguageSupported(ExpressionLanguageScope.VARIABLE_REGISTRY)
            .defaultValue("${hostname(true)}")
            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
            .build();

    public static final PropertyDescriptor SSL_CONTEXT = new PropertyDescriptor.Builder()
            .name("prometheus-reporting-task-ssl-context")
            .displayName("SSL Context Service")
            .description("The SSL Context Service to use in order to secure the server. If specified, the server will"
                    + "accept only HTTPS requests; otherwise, the server will accept only HTTP requests")
            .required(false)
            .identifiesControllerService(RestrictedSSLContextService.class)
            .build();

    public static final PropertyDescriptor CLIENT_AUTH = new PropertyDescriptor.Builder()
            .name("prometheus-reporting-task-client-auth")
            .displayName("Client Authentication")
            .description("Specifies whether or not the Reporting Task should authenticate clients. This value is ignored if the <SSL Context Service> "
                    + "Property is not specified or the SSL Context provided uses only a KeyStore and not a TrustStore.")
            .required(true)
            .allowableValues(CLIENT_NONE, CLIENT_WANT, CLIENT_NEED)
            .defaultValue(CLIENT_NONE.getValue())
            .build();

    // Processor / Process Group metrics
    private static final Gauge AMOUNT_FLOWFILES_SENT = Gauge.build()
            .name("nifi_amount_flowfiles_sent")
            .help("Total number of FlowFiles sent by the component")
            .labelNames("instance", "component_type", "component_name", "component_id", "parent_id")
            .register(NIFI_REGISTRY);

    private static final Gauge AMOUNT_FLOWFILES_TRANSFERRED = Gauge.build()
            .name("nifi_amount_flowfiles_transferred")
            .help("Total number of FlowFiles transferred by the component")
            .labelNames("instance", "component_type", "component_name", "component_id", "parent_id")
            .register(NIFI_REGISTRY);

    private static final Gauge AMOUNT_FLOWFILES_RECEIVED = Gauge.build()
            .name("nifi_amount_flowfiles_received")
            .help("Total number of FlowFiles received by the component")
            .labelNames("instance", "component_type", "component_name", "component_id", "parent_id")
            .register(NIFI_REGISTRY);

    private static final Gauge AMOUNT_FLOWFILES_REMOVED = Gauge.build()
            .name("nifi_amount_flowfiles_removed")
            .help("Total number of FlowFiles removed by the component")
            .labelNames("instance", "component_type", "component_name", "component_id", "parent_id")
            .register(NIFI_REGISTRY);

    private static final Gauge AMOUNT_BYTES_SENT = Gauge.build()
            .name("nifi_amount_bytes_sent")
            .help("Total number of bytes sent by the component")
            .labelNames("instance", "component_type", "component_name", "component_id", "parent_id")
            .register(NIFI_REGISTRY);

    private static final Gauge AMOUNT_BYTES_READ = Gauge.build()
            .name("nifi_amount_bytes_read")
            .help("Total number of bytes read by the component")
            .labelNames("instance", "component_type", "component_name", "component_id", "parent_id")
            .register(NIFI_REGISTRY);

    private static final Gauge AMOUNT_BYTES_WRITTEN = Gauge.build()
            .name("nifi_amount_bytes_written")
            .help("Total number of bytes written by the component")
            .labelNames("instance", "component_type", "component_name", "component_id", "parent_id")
            .register(NIFI_REGISTRY);

    private static final Gauge AMOUNT_BYTES_RECEIVED = Gauge.build()
            .name("nifi_amount_bytes_received")
            .help("Total number of bytes received by the component")
            .labelNames("instance", "component_type", "component_name", "component_id", "parent_id")
            .register(NIFI_REGISTRY);

    private static final Gauge AMOUNT_BYTES_TRANSFERRED = Gauge.build()
            .name("nifi_amount_bytes_transferred")
            .help("Total number of Bytes transferred by the component")
            .labelNames("instance", "component_type", "component_name", "component_id", "parent_id")
            .register(NIFI_REGISTRY);

    private static final Gauge AMOUNT_THREADS_TOTAL_ACTIVE = Gauge.build()
            .name("nifi_amount_threads_active")
            .help("Total number of threads active for the component")
            .labelNames("instance", "component_type", "component_name", "component_id", "parent_id")
            .register(NIFI_REGISTRY);

    private static final Gauge AMOUNT_THREADS_TOTAL_TERMINATED = Gauge.build()
            .name("nifi_amount_threads_terminated")
            .help("Total number of threads terminated for the component")
            .labelNames("instance", "component_type", "component_name", "component_id", "parent_id")
            .register(NIFI_REGISTRY);

    private static final Gauge SIZE_CONTENT_OUTPUT_TOTAL = Gauge.build()
            .name("nifi_size_content_output_total")
            .help("Total size of content output by the component")
            .labelNames("instance", "component_type", "component_name", "component_id", "parent_id",
                    "source_id", "source_name", "destination_id", "destination_name")
            .register(NIFI_REGISTRY);

    private static final Gauge SIZE_CONTENT_INPUT_TOTAL = Gauge.build()
            .name("nifi_size_content_input_total")
            .help("Total size of content input by the component")
            .labelNames("instance", "component_type", "component_name", "component_id", "parent_id",
                    "source_id", "source_name", "destination_id", "destination_name")
            .register(NIFI_REGISTRY);

    private static final Gauge SIZE_CONTENT_QUEUED_TOTAL = Gauge.build()
            .name("nifi_size_content_queued_total")
            .help("Total size of content queued in the component")
            .labelNames("instance", "component_type", "component_name", "component_id", "parent_id",
                    "source_id", "source_name", "destination_id", "destination_name")
            .register(NIFI_REGISTRY);

    private static final Gauge AMOUNT_ITEMS_OUTPUT = Gauge.build()
            .name("nifi_amount_items_output")
            .help("Total number of items output by the component")
            .labelNames("instance", "component_type", "component_name", "component_id", "parent_id",
                    "source_id", "source_name", "destination_id", "destination_name")
            .register(NIFI_REGISTRY);

    private static final Gauge AMOUNT_ITEMS_INPUT = Gauge.build()
            .name("nifi_amount_items_input")
            .help("Total number of items input by the component")
            .labelNames("instance", "component_type", "component_name", "component_id", "parent_id",
                    "source_id", "source_name", "destination_id", "destination_name")
            .register(NIFI_REGISTRY);

    private static final Gauge AMOUNT_ITEMS_QUEUED = Gauge.build()
            .name("nifi_amount_items_queued")
            .help("Total number of items queued by the component")
            .labelNames("instance", "component_type", "component_name", "component_id", "parent_id",
                    "source_id", "source_name", "destination_id", "destination_name")
            .register(NIFI_REGISTRY);

    // Processor metrics
    private static final Gauge PROCESSOR_COUNTERS = Gauge.build()
            .name("nifi_processor_counters")
            .help("Counters exposed by NiFi Processors")
            .labelNames("processor_name", "counter_name", "processor_id", "instance")
            .register(NIFI_REGISTRY);

    // Connection metrics
    private static final Gauge BACKPRESSURE_BYTES_THRESHOLD = Gauge.build()
            .name("nifi_backpressure_bytes_threshold")
            .help("The number of bytes that can be queued before backpressure is applied")
            .labelNames("instance", "component_type", "component_name", "component_id", "parent_id",
                    "source_id", "source_name", "destination_id", "destination_name")
            .register(NIFI_REGISTRY);

    private static final Gauge BACKPRESSURE_OBJECT_THRESHOLD = Gauge.build()
            .name("nifi_backpressure_object_threshold")
            .help("The number of flow files that can be queued before backpressure is applied")
            .labelNames("instance", "component_type", "component_name", "component_id", "parent_id",
                    "source_id", "source_name", "destination_id", "destination_name")
            .register(NIFI_REGISTRY);

    private static final Gauge IS_BACKPRESSURE_ENABLED = Gauge.build()
            .name("nifi_backpressure_enabled")
            .help("Whether backpressure has been applied for this component. Values are 0 or 1")
            .labelNames("instance", "component_type", "component_name", "component_id", "parent_id",
                    "source_id", "source_name", "destination_id", "destination_name")
            .register(NIFI_REGISTRY);

    // Port metrics
    private static final Gauge IS_TRANSMITTING = Gauge.build()
            .name("nifi_transmitting")
            .help("Whether this component is transmitting data. Values are 0 or 1")
            .labelNames("instance", "component_type", "component_name", "component_id", "parent_id", "run_status")
            .register(NIFI_REGISTRY);

    // Remote Process Group (RPG) metrics
    private static final Gauge ACTIVE_REMOTE_PORT_COUNT = Gauge.build()
            .name("nifi_active_remote_port_count")
            .help("The number of active remote ports associated with this component")
            .labelNames("instance", "component_type", "component_name", "component_id", "parent_id",
                    "source_id", "source_name", "destination_id", "destination_name")
            .register(NIFI_REGISTRY);

    private static final Gauge INACTIVE_REMOTE_PORT_COUNT = Gauge.build()
            .name("nifi_inactive_remote_port_count")
            .help("The number of inactive remote ports associated with this component")
            .labelNames("instance", "component_type", "component_name", "component_id", "parent_id",
                    "source_id", "source_name", "destination_id", "destination_name")
            .register(NIFI_REGISTRY);

    private static final Gauge AVERAGE_LINEAGE_DURATION = Gauge.build()
            .name("nifi_average_lineage_duration")
            .help("The average lineage duration (in milliseconds) for all flow file processed by this component")
            .labelNames("instance", "component_type", "component_name", "component_id", "parent_id",
                    "source_id", "source_name", "destination_id", "destination_name")
            .register(NIFI_REGISTRY);

    ///////////////////////////////////////////////////////////////
    // JVM Metrics
    ///////////////////////////////////////////////////////////////
    private static final Gauge JVM_HEAP_USED = Gauge.build()
            .name("nifi_jvm_heap_used")
            .help("NiFi JVM heap used")
            .labelNames("instance")
            .register(JVM_REGISTRY);

    private static final Gauge JVM_HEAP_USAGE = Gauge.build()
            .name("nifi_jvm_heap_usage")
            .help("NiFi JVM heap usage")
            .labelNames("instance")
            .register(JVM_REGISTRY);

    private static final Gauge JVM_HEAP_NON_USAGE = Gauge.build()
            .name("nifi_jvm_heap_non_usage")
            .help("NiFi JVM heap non usage")
            .labelNames("instance")
            .register(JVM_REGISTRY);

    private static final Gauge JVM_THREAD_COUNT = Gauge.build()
            .name("nifi_jvm_thread_count")
            .help("NiFi JVM thread count")
            .labelNames("instance")
            .register(JVM_REGISTRY);

    private static final Gauge JVM_DAEMON_THREAD_COUNT = Gauge.build()
            .name("nifi_jvm_daemon_thread_count")
            .help("NiFi JVM daemon thread count")
            .labelNames("instance")
            .register(JVM_REGISTRY);

    private static final Gauge JVM_UPTIME = Gauge.build()
            .name("nifi_jvm_uptime")
            .help("NiFi JVM uptime")
            .labelNames("instance")
            .register(JVM_REGISTRY);

    private static final Gauge JVM_FILE_DESCRIPTOR_USAGE = Gauge.build()
            .name("nifi_jvm_file_descriptor_usage")
            .help("NiFi JVM file descriptor usage")
            .labelNames("instance")
            .register(JVM_REGISTRY);

    private static final Gauge JVM_GC_RUNS = Gauge.build()
            .name("nifi_jvm_gc_runs")
            .help("NiFi JVM GC number of runs")
            .labelNames("instance", "gc_name")
            .register(JVM_REGISTRY);

    private static final Gauge JVM_GC_TIME = Gauge.build()
            .name("nifi_jvm_gc_time")
            .help("NiFi JVM GC time in milliseconds")
            .labelNames("instance", "gc_name")
            .register(JVM_REGISTRY);

    public static CollectorRegistry createNifiMetrics(ProcessGroupStatus status, String instanceId, String parentPGId, String componentType, String metricsStrategy) {

        final String componentId = status.getId();
        final String componentName = status.getName();

        // Clear all collectors to deal with removed/renamed components
        try {
            for (final Field field : PrometheusMetricsUtil.class.getDeclaredFields()) {
                if (Modifier.isStatic(field.getModifiers()) && (field.get(null) instanceof SimpleCollector)) {
                    SimpleCollector sc = (SimpleCollector)(field.get(null));
                    sc.clear();
                }
            }
        } catch (IllegalAccessException e) {
            // ignore
        }

        AMOUNT_FLOWFILES_SENT.labels(instanceId, componentType, componentName, componentId, parentPGId).set(status.getFlowFilesSent());
        AMOUNT_FLOWFILES_TRANSFERRED.labels(instanceId, componentType, componentName, componentId, parentPGId).set(status.getFlowFilesTransferred());
        AMOUNT_FLOWFILES_RECEIVED.labels(instanceId, componentType, componentName, componentId, parentPGId).set(status.getFlowFilesReceived());

        AMOUNT_BYTES_SENT.labels(instanceId, componentType, componentName, componentId, parentPGId).set(status.getBytesSent());
        AMOUNT_BYTES_READ.labels(instanceId, componentType, componentName, componentId, parentPGId).set(status.getBytesRead());
        AMOUNT_BYTES_WRITTEN.labels(instanceId, componentType, componentName, componentId, parentPGId).set(status.getBytesWritten());
        AMOUNT_BYTES_RECEIVED.labels(instanceId, componentType, componentName, componentId, parentPGId).set(status.getBytesReceived());
        AMOUNT_BYTES_TRANSFERRED.labels(instanceId, componentType, componentName, componentId, parentPGId).set(status.getBytesTransferred());

        SIZE_CONTENT_OUTPUT_TOTAL.labels(instanceId, componentType, componentName, componentId, parentPGId, "", "", "", "")
                .set(status.getOutputContentSize());
        SIZE_CONTENT_INPUT_TOTAL.labels(instanceId, componentType, componentName, componentId, parentPGId, "", "", "", "")
                .set(status.getInputContentSize());
        SIZE_CONTENT_QUEUED_TOTAL.labels(instanceId, componentType, componentName, componentId, parentPGId, "", "", "", "")
                .set(status.getQueuedContentSize());

        AMOUNT_ITEMS_OUTPUT.labels(instanceId, componentType, componentName, componentId, parentPGId, "", "", "", "")
                .set(status.getOutputCount());
        AMOUNT_ITEMS_INPUT.labels(instanceId, componentType, componentName, componentId, parentPGId, "", "", "", "")
                .set(status.getInputCount());
        AMOUNT_ITEMS_QUEUED.labels(instanceId, componentType, componentName, componentId, parentPGId,"", "", "", "")
                .set(status.getQueuedCount());

        AMOUNT_THREADS_TOTAL_ACTIVE.labels(instanceId, componentType, componentName, componentId, parentPGId)
                .set(status.getActiveThreadCount() == null ? 0 : status.getActiveThreadCount());
        AMOUNT_THREADS_TOTAL_TERMINATED.labels(instanceId, componentType, componentName, componentId, parentPGId)
                .set(status.getTerminatedThreadCount() == null ? 0 : status.getTerminatedThreadCount());

        // Report metrics for child process groups if specified
        if (METRICS_STRATEGY_PG.getValue().equals(metricsStrategy) || METRICS_STRATEGY_COMPONENTS.getValue().equals(metricsStrategy)) {
            status.getProcessGroupStatus().forEach((childGroupStatus) -> createNifiMetrics(childGroupStatus, instanceId, parentPGId, "ProcessGroup", metricsStrategy));
        }

        if (METRICS_STRATEGY_COMPONENTS.getValue().equals(metricsStrategy)) {
            // Report metrics for all components
            for (ProcessorStatus processorStatus : status.getProcessorStatus()) {
                Map<String, Long> counters = processorStatus.getCounters();

                if (counters != null) {
                    counters.entrySet().stream().forEach(entry -> PROCESSOR_COUNTERS
                            .labels(processorStatus.getName(), entry.getKey(), processorStatus.getId(), instanceId).set(entry.getValue()));
                }

                final String procComponentType = "Processor";
                final String procComponentId = processorStatus.getId();
                final String procComponentName = processorStatus.getName();
                final String parentId = processorStatus.getGroupId();

                AMOUNT_FLOWFILES_SENT.labels(instanceId, procComponentType, procComponentName, procComponentId, parentPGId).set(processorStatus.getFlowFilesSent());
                AMOUNT_FLOWFILES_RECEIVED.labels(instanceId, procComponentType, procComponentName, procComponentId, parentPGId).set(processorStatus.getFlowFilesReceived());
                AMOUNT_FLOWFILES_REMOVED.labels(instanceId, procComponentType, procComponentName, procComponentId, parentPGId).set(processorStatus.getFlowFilesRemoved());

                AMOUNT_BYTES_SENT.labels(instanceId, procComponentType, procComponentName, procComponentId, parentPGId).set(processorStatus.getBytesSent());
                AMOUNT_BYTES_READ.labels(instanceId, procComponentType, procComponentName, procComponentId, parentPGId).set(processorStatus.getBytesRead());
                AMOUNT_BYTES_WRITTEN.labels(instanceId, procComponentType, procComponentName, procComponentId, parentPGId).set(processorStatus.getBytesWritten());
                AMOUNT_BYTES_RECEIVED.labels(instanceId, procComponentType, procComponentName, procComponentId, parentPGId).set(processorStatus.getBytesReceived());

                SIZE_CONTENT_OUTPUT_TOTAL.labels(instanceId, procComponentType, procComponentName, procComponentId, parentPGId, "", "", "", "")
                        .set(processorStatus.getOutputBytes());
                SIZE_CONTENT_INPUT_TOTAL.labels(instanceId, procComponentType, procComponentName, procComponentId, parentPGId, "", "", "", "")
                        .set(processorStatus.getInputBytes());

                AMOUNT_ITEMS_OUTPUT.labels(instanceId, procComponentType, procComponentName, procComponentId, parentPGId, "", "", "", "")
                        .set(processorStatus.getOutputCount());
                AMOUNT_ITEMS_INPUT.labels(instanceId, procComponentType, procComponentName, procComponentId, parentPGId, "", "", "", "")
                        .set(processorStatus.getInputCount());

                AVERAGE_LINEAGE_DURATION.labels(instanceId, procComponentType, procComponentName, procComponentId, parentPGId, "", "", "", "")
                        .set(processorStatus.getAverageLineageDuration());

                AMOUNT_THREADS_TOTAL_ACTIVE.labels(instanceId, procComponentType, procComponentName, procComponentId, parentId)
                        .set(status.getActiveThreadCount() == null ? 0 : status.getActiveThreadCount());
                AMOUNT_THREADS_TOTAL_TERMINATED.labels(instanceId, procComponentType, procComponentName, procComponentId, parentId)
                        .set(status.getTerminatedThreadCount() == null ? 0 : status.getTerminatedThreadCount());

            }
            for (ConnectionStatus connectionStatus : status.getConnectionStatus()) {
                final String connComponentId = connectionStatus.getId();
                final String connComponentName = connectionStatus.getName();
                final String sourceId = connectionStatus.getSourceId();
                final String sourceName = connectionStatus.getSourceName();
                final String destinationId = connectionStatus.getDestinationId();
                final String destinationName = connectionStatus.getDestinationName();
                final String parentId = connectionStatus.getGroupId();
                final String connComponentType = "Connection";
                SIZE_CONTENT_OUTPUT_TOTAL.labels(instanceId, connComponentType, connComponentName, connComponentId, parentId, sourceId, sourceName, destinationId, destinationName)
                        .set(connectionStatus.getOutputBytes());
                SIZE_CONTENT_INPUT_TOTAL.labels(instanceId, connComponentType, connComponentName, connComponentId, parentId, sourceId, sourceName, destinationId, destinationName)
                        .set(connectionStatus.getInputBytes());
                SIZE_CONTENT_QUEUED_TOTAL.labels(instanceId, connComponentType, connComponentName, connComponentId, parentId, sourceId, sourceName, destinationId, destinationName)
                        .set(connectionStatus.getQueuedBytes());

                AMOUNT_ITEMS_OUTPUT.labels(instanceId, connComponentType, connComponentName, connComponentId, parentId, sourceId, sourceName, destinationId, destinationName)
                        .set(connectionStatus.getOutputCount());
                AMOUNT_ITEMS_INPUT.labels(instanceId, connComponentType, connComponentName, connComponentId, parentId, sourceId, sourceName, destinationId, destinationName)
                        .set(connectionStatus.getInputCount());
                AMOUNT_ITEMS_QUEUED.labels(instanceId, connComponentType, connComponentName, connComponentId, parentId, sourceId, sourceName, destinationId, destinationName)
                        .set(connectionStatus.getQueuedCount());

                BACKPRESSURE_BYTES_THRESHOLD.labels(instanceId, connComponentType, connComponentName, connComponentId, parentId, sourceId, sourceName, destinationId, destinationName)
                        .set(connectionStatus.getBackPressureBytesThreshold());
                BACKPRESSURE_OBJECT_THRESHOLD.labels(instanceId, connComponentType, connComponentName, connComponentId, parentId, sourceId, sourceName, destinationId, destinationName)
                        .set(connectionStatus.getBackPressureObjectThreshold());
                boolean isBackpressureEnabled = (connectionStatus.getBackPressureObjectThreshold() > 0 && connectionStatus.getBackPressureObjectThreshold() <= connectionStatus.getQueuedCount())
                        || (connectionStatus.getBackPressureBytesThreshold() > 0 && connectionStatus.getBackPressureBytesThreshold() <= connectionStatus.getMaxQueuedBytes());
                IS_BACKPRESSURE_ENABLED.labels(instanceId, connComponentType, connComponentName, connComponentId, parentId, sourceId, sourceName, destinationId, destinationName)
                        .set(isBackpressureEnabled ? 1 : 0);
            }
            for (PortStatus portStatus : status.getInputPortStatus()) {
                final String portComponentId = portStatus.getId();
                final String portComponentName = portStatus.getName();
                final String parentId = portStatus.getGroupId();
                final String portComponentType = "InputPort";
                AMOUNT_FLOWFILES_SENT.labels(instanceId, portComponentType, portComponentName, portComponentId, parentId).set(portStatus.getFlowFilesSent());
                AMOUNT_FLOWFILES_RECEIVED.labels(instanceId, portComponentType, portComponentName, portComponentId, parentId).set(portStatus.getFlowFilesReceived());

                AMOUNT_BYTES_SENT.labels(instanceId, portComponentType, portComponentName, portComponentId, parentId).set(portStatus.getBytesSent());
                AMOUNT_BYTES_READ.labels(instanceId, portComponentType, portComponentName, portComponentId, parentId).set(portStatus.getInputBytes());
                AMOUNT_BYTES_WRITTEN.labels(instanceId, portComponentType, portComponentName, portComponentId, parentId).set(portStatus.getOutputBytes());
                AMOUNT_BYTES_RECEIVED.labels(instanceId, portComponentType, portComponentName, portComponentId, parentId).set(portStatus.getBytesReceived());

                AMOUNT_ITEMS_OUTPUT.labels(instanceId, portComponentType, portComponentName, portComponentId, parentId, "", "", "", "")
                        .set(portStatus.getOutputCount());
                AMOUNT_ITEMS_INPUT.labels(instanceId, portComponentType, portComponentName, portComponentId, parentId, "", "", "", "")
                        .set(portStatus.getInputCount());

                final Boolean isTransmitting = portStatus.isTransmitting();
                IS_TRANSMITTING.labels(instanceId, portComponentType, portComponentName, portComponentId, parentId, portStatus.getRunStatus().name())
                        .set(isTransmitting == null ? 0 : (isTransmitting ? 1 : 0));

                AMOUNT_THREADS_TOTAL_ACTIVE.labels(instanceId, portComponentType, portComponentName, portComponentId, parentId).set(portStatus.getActiveThreadCount());
            }
            for (PortStatus portStatus : status.getOutputPortStatus()) {
                final String portComponentId = portStatus.getId();
                final String portComponentName = portStatus.getName();
                final String parentId = portStatus.getGroupId();
                final String portComponentType = "OutputPort";
                AMOUNT_FLOWFILES_SENT.labels(instanceId, portComponentType, portComponentName, portComponentId, parentId).set(portStatus.getFlowFilesSent());
                AMOUNT_FLOWFILES_RECEIVED.labels(instanceId, portComponentType, portComponentName, portComponentId).set(portStatus.getFlowFilesReceived());

                AMOUNT_BYTES_SENT.labels(instanceId, portComponentType, portComponentName, portComponentId, parentId).set(portStatus.getBytesSent());
                AMOUNT_BYTES_READ.labels(instanceId, portComponentType, portComponentName, portComponentId, parentId).set(portStatus.getInputBytes());
                AMOUNT_BYTES_WRITTEN.labels(instanceId, portComponentType, portComponentName, portComponentId, parentId).set(portStatus.getOutputBytes());
                AMOUNT_BYTES_RECEIVED.labels(instanceId, portComponentType, portComponentName, portComponentId, parentId).set(portStatus.getBytesReceived());

                AMOUNT_ITEMS_OUTPUT.labels(instanceId, portComponentType, portComponentName, portComponentId, parentId, "", "", "", "")
                        .set(portStatus.getOutputCount());
                AMOUNT_ITEMS_INPUT.labels(instanceId, portComponentType, portComponentName, portComponentId, parentId, "", "", "", "")
                        .set(portStatus.getInputCount());

                final Boolean isTransmitting = portStatus.isTransmitting();
                IS_TRANSMITTING.labels(instanceId, portComponentType, portComponentName, portComponentId, parentId, portStatus.getRunStatus().name())
                        .set(isTransmitting == null ? 0 : (isTransmitting ? 1 : 0));

                AMOUNT_THREADS_TOTAL_ACTIVE.labels(instanceId, portComponentType, portComponentName, portComponentId, parentId).set(portStatus.getActiveThreadCount());
            }
            for (RemoteProcessGroupStatus remoteProcessGroupStatus : status.getRemoteProcessGroupStatus()) {
                final String rpgComponentId = remoteProcessGroupStatus.getId();
                final String rpgComponentName = remoteProcessGroupStatus.getName();
                final String parentId = remoteProcessGroupStatus.getGroupId();
                final String rpgComponentType = "RemoteProcessGroup";

                AMOUNT_BYTES_WRITTEN.labels(instanceId, rpgComponentType, rpgComponentName, rpgComponentId, parentId).set(remoteProcessGroupStatus.getSentContentSize());
                AMOUNT_BYTES_RECEIVED.labels(instanceId, rpgComponentType, rpgComponentName, rpgComponentId, parentId).set(remoteProcessGroupStatus.getReceivedContentSize());

                AMOUNT_ITEMS_OUTPUT.labels(instanceId, rpgComponentType, rpgComponentName, rpgComponentId, parentId, "", "", "", "")
                        .set(remoteProcessGroupStatus.getSentCount());
                AMOUNT_ITEMS_INPUT.labels(instanceId, rpgComponentType, rpgComponentName, rpgComponentId, parentId, "", "", "", "")
                        .set(remoteProcessGroupStatus.getReceivedCount());

                ACTIVE_REMOTE_PORT_COUNT.labels(instanceId, rpgComponentType, rpgComponentName, rpgComponentId, parentId, "", "", "", "")
                        .set(remoteProcessGroupStatus.getActiveRemotePortCount());
                INACTIVE_REMOTE_PORT_COUNT.labels(instanceId, rpgComponentType, rpgComponentName, rpgComponentId, parentId, "", "", "", "")
                        .set(remoteProcessGroupStatus.getInactiveRemotePortCount());

                AVERAGE_LINEAGE_DURATION.labels(instanceId, rpgComponentType, rpgComponentName, rpgComponentId, parentId, "", "", "", "")
                        .set(remoteProcessGroupStatus.getAverageLineageDuration());

                IS_TRANSMITTING.labels(instanceId, rpgComponentType, rpgComponentName, rpgComponentId, parentId, remoteProcessGroupStatus.getTransmissionStatus().name())
                        .set(TransmissionStatus.Transmitting.equals(remoteProcessGroupStatus.getTransmissionStatus()) ? 1 : 0);

                AMOUNT_THREADS_TOTAL_ACTIVE.labels(instanceId, rpgComponentType, rpgComponentName, rpgComponentId, parentId).set(remoteProcessGroupStatus.getActiveThreadCount());
            }
        }

        return NIFI_REGISTRY;
    }

    public static CollectorRegistry createJvmMetrics(JvmMetrics jvmMetrics, String instanceId) {
        JVM_HEAP_USED.labels(instanceId).set(jvmMetrics.heapUsed(DataUnit.B));
        JVM_HEAP_USAGE.labels(instanceId).set(jvmMetrics.heapUsage());
        JVM_HEAP_NON_USAGE.labels(instanceId).set(jvmMetrics.nonHeapUsage());

        JVM_THREAD_COUNT.labels(instanceId).set(jvmMetrics.threadCount());
        JVM_DAEMON_THREAD_COUNT.labels(instanceId).set(jvmMetrics.daemonThreadCount());

        JVM_UPTIME.labels(instanceId).set(jvmMetrics.uptime());
        JVM_FILE_DESCRIPTOR_USAGE.labels(instanceId).set(jvmMetrics.fileDescriptorUsage());

        jvmMetrics.garbageCollectors()
                .forEach((name, stat) -> {
                    JVM_GC_RUNS.labels(instanceId, name).set(stat.getRuns());
                    JVM_GC_TIME.labels(instanceId, name).set(stat.getTime(TimeUnit.MILLISECONDS));
                });

        return JVM_REGISTRY;
    }

}


text:
<?php

namespace PHPExiftool\Driver\Tag\Nikon;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class ExposureBracketValue extends AbstractTag
{

    protected $Id = 25;

    protected $Name = 'ExposureBracketValue';

    protected $FullName = 'Nikon::Main';

    protected $GroupName = 'Nikon';

    protected $g0 = 'MakerNotes';

    protected $g1 = 'Nikon';

    protected $g2 = 'Camera';

    protected $Type = 'rational64s';

    protected $Writable = true;

    protected $Description = 'Exposure Bracket Value';

    protected $flag_Permanent = true;

}


text:
/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId])
/******/ 			return installedModules[moduleId].exports;
/******/
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			exports: {},
/******/ 			id: moduleId,
/******/ 			loaded: false
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.loaded = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {

	'use strict';

	var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();

	function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

	function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }

	var _toImport = __webpack_require__(1);

	var _toImport2 = _interopRequireDefault(_toImport);

	console.log(_toImport2['default']);

	angular.module('test', []).controller('testCtrl', ["$scope", function ($scope) {}]).factory('testFactory', ["$cacheFactory", function ($cacheFactory) {
		return {};
	}]).service('testNotAnnotated', function () {
		return {};
	}).directive('testDirective', ["$timeout", function ($timeout) {
		return {
			restrict: 'E',
			controller: ["$scope", function controller($scope) {}]
		};
	}]).controller('someCtrl', someCtrl);

	function toAnnotate($scope) {
		'ngInject';
	}
	toAnnotate.$inject = ["$scope"];

	var someCtrl = (function () {
		function someCtrl($scope) {
			_classCallCheck(this, someCtrl);

			this.doSomething();
		}
		someCtrl.$inject = ["$scope"];

		_createClass(someCtrl, [{
			key: 'doSomething',
			value: function doSomething() {}
		}]);

		return someCtrl;
	})();

	console.log('after annotated function');

/***/ },
/* 1 */
/***/ function(module, exports) {

	'use strict';

	Object.defineProperty(exports, '__esModule', {
	  value: true
	});
	exports['default'] = 'babel-test';
	module.exports = exports['default'];

/***/ }
/******/ ]);
//# sourceMappingURL=build.js.map


text:
#ifndef RANDOMVARIABLES_EVALUATEDVARIABLE_H
#define RANDOMVARIABLES_EVALUATEDVARIABLE_H

#include <ostream>
#include <istream>

namespace PsuedoRandomGenerators {
	class RandomNumber;
}

namespace RandomVariables {
	/**
	 *
	 * EvaluatedVariable
	 *
	 * When this class is initialized it uses the random number generator to create a random value and then stores only the value.
	 * A copy will only copy the value and not create a new random value.
	 * The stored value is immutable.
	 *
	 **/
	template<typename T>
	class EvaluatedVariable
	{
		T m_val;
	public:
		EvaluatedVariable(PsuedoRandomGenerators::RandomNumber*);
		EvaluatedVariable(const EvaluatedVariable<T>&);
		EvaluatedVariable(PsuedoRandomGenerators::RandomNumber*, double bias);
		EvaluatedVariable(PsuedoRandomGenerators::RandomNumber*, T min, T max);

		EvaluatedVariable<T>& operator=(EvaluatedVariable);

		T operator()(void) { return m_val; }
		inline bool operator==(const EvaluatedVariable& rhs) { return m_val == rhs.m_val; };
		inline bool operator!=(const EvaluatedVariable& rhs) { return !operator==(rhs); };
		inline bool operator< (const EvaluatedVariable& rhs) { return m_val < rhs.m_val; };
		inline bool operator> (const EvaluatedVariable& rhs) { return !operator< (rhs) && !operator==(rhs); };
		inline bool operator<=(const EvaluatedVariable& rhs) { return !operator> (rhs); };
		inline bool operator>=(const EvaluatedVariable& rhs) { return !operator< (rhs); };

		T operator!() { return !m_val; }
		T operator&&(EvaluatedVariable o) { return m_val && o.m_val; }
		T operator||(EvaluatedVariable o) { return m_val || o.m_val; }

		T operator~() { return ~m_val; }
		T operator&(EvaluatedVariable o) { return m_val & o.m_val; }
		T operator|(EvaluatedVariable o) { return m_val | o.m_val; }
		T operator^(EvaluatedVariable o) { return m_val ^ o.m_val; }
	};

}

#endif


text:
<?xml version="1.0" encoding="utf-8" ?>
<athletes>
<athlete>
<athlete_id>118894</athlete_id>
<birthdate>03.12.1992</birthdate>
<birthyear>1992</birthyear>
<firstname>Ayanleh</firstname>
<lastname>Souleiman</lastname>
<height>172</height>
<weight>60</weight>
<gender>M</gender>
<club></club><nationality>DJI</nationality><birthplace></birthplace><accomplishments>
<line number="0">
<description>World Indoor Champion</description>
<details>
<detail disciplines="1500" year="2014"/>
</details>
</line>
<line number="1">
<description>World Championships Bronze Medallist</description>
<details>
<detail disciplines="800" year="2013"/>
</details>
</line>
<line number="2">
<description>4th at Olympic Games</description>
<details>
<detail disciplines="1500" year="2016"/>
</details>
</line>
<line number="3">
<description>5th at World Indoor Championships</description>
<details>
<detail disciplines="1500" year="2012"/>
</details>
</line>
<line number="4">
<description>African Champion</description>
<details>
<detail disciplines="1500" year="2014"/>
</details>
</line>
<line number="5">
<description>African Championships Silver Medallist</description>
<details>
<detail disciplines="1500" year="2012"/>
</details>
</line>
</accomplishments>
</athlete>
</athletes>


text:
'use strict';
angular.module('simpleSearch',['angularSpinner']);

var context = require.context('.', true, /\.js$/);
context.keys().forEach(context);


text:
import os
import re
import time
from datetime import datetime, timedelta

import sys, requests, json

import bdd_test_util

OPENCHAIN_REST_PORT = 5000

class ContainerData:
	def __init__(self, containerName, ipAddress):
		self.containerName = containerName
		self.ipAddress = ipAddress

def parseComposeOutput(context):
    """Parses the compose output results and set appropriate values into context"""
    # Use the prefix to get the container name
    containerNamePrefix = os.path.basename(os.getcwd()) + "_"
    containerNames = []
    for l in context.compose_error.splitlines():
    	print(l.split())
    	containerNames.append(l.split()[1])

    print(containerNames)
    # Now get the Network Address for each name, and set the ContainerData onto the context.
    containerDataList = []
    for containerName in containerNames:
    	output, error, returncode = \
        	bdd_test_util.cli_call(context, ["docker", "inspect", "--format",  "{{ .NetworkSettings.IPAddress }}", containerName], expect_success=True)
        print("container {0} has address = {1}".format(containerName, output.splitlines()[0]))
        containerDataList.append(ContainerData(containerName, output.splitlines()[0]))
        setattr(context, "compose_containers", containerDataList)
    print("")

def ipFromContainerNamePart(namePart, containerDataList):
	"""Returns the IPAddress based upon a name part of the full container name"""
	ip = None
	containerNamePrefix = os.path.basename(os.getcwd()) + "_"
	for containerData in containerDataList:
	    if containerData.containerName.startswith(containerNamePrefix + namePart):
	    	ip = containerData.ipAddress
	if ip == None:
		raise Exception("Could not find container with namePart = {0}".format(namePart))
	return ip

def buildUrl(ipAddress, path):
	return "http://{0}:{1}{2}".format(ipAddress, OPENCHAIN_REST_PORT, path)

@given(u'we compose "{composeYamlFile}"')
def step_impl(context, composeYamlFile):
	# Use the uninstalled version of `cf active-deploy` rather than the installed version on the OS $PATH
    #cmd = os.path.dirname(os.path.abspath(__file__)) + "/../../../cf_update/v1/cf_update.py"

    # Expand $vars, e.g. "--path $PATH" becomes "--path /bin"
    #args = re.sub('\$\w+', lambda v: os.getenv(v.group(0)[1:]), composeYamlFile)
    context.compose_yaml = composeYamlFile
    context.compose_output, context.compose_error, context.compose_returncode = \
        bdd_test_util.cli_call(context, ["docker-compose", "-f", composeYamlFile, "up","--force-recreate", "-d"], expect_success=True)
    assert context.compose_returncode == 0, "docker-compose failed to bring up {0}".format(composeYamlFile)
    parseComposeOutput(context)

@when(u'requesting "{path}" from "{containerName}"')
def step_impl(context, path, containerName):
    ipAddress = ipFromContainerNamePart(containerName, context.compose_containers)
    request_url = buildUrl(ipAddress, path)
    print("Requesting path = {0}".format(request_url))
    resp = requests.get(request_url, headers={'Accept': 'application/json'})
    assert resp.status_code == 200, "Failed to GET url %s:  %s" % (request_url,resp.text)
    context.response = resp
    print("")

@then(u'I should get a JSON response with "{attribute}" = "{expectedValue}"')
def step_impl(context, attribute, expectedValue):
    assert attribute in context.response.json(), "Attribute not found in response (%s)" %(attribute)
    foundValue = context.response.json()[attribute]
    assert (str(foundValue) == expectedValue), "For attribute %s, expected (%s), instead found (%s)" % (attribute, expectedValue, foundValue)

@given(u'I wait "{seconds}" seconds')
def step_impl(context, seconds):
    time.sleep(float(seconds))

@when(u'I wait "{seconds}" seconds')
def step_impl(context, seconds):
    time.sleep(float(seconds))

@then(u'I wait "{seconds}" seconds')
def step_impl(context, seconds):
    time.sleep(float(seconds))

@when(u'I deploy chaincode "{chaincodePath}" with ctor "{ctor}" to "{containerName}"')
def step_impl(context, chaincodePath, ctor, containerName):
    ipAddress = ipFromContainerNamePart(containerName, context.compose_containers)
    request_url = buildUrl(ipAddress, "/devops/deploy")
    print("Requesting path = {0}".format(request_url))
    args = []
    if 'table' in context:
	   # There is ctor arguments
	   args = context.table[0].cells
    typeGolang = 1
    # Create a ChaincodeSpec structure
    chaincodeSpec = {
        "type": typeGolang,
        "chaincodeID": {
            "path" : chaincodePath,
            "name" : ""
        },
        "ctorMsg":  {
            "function" : ctor,
            "args" : args
        }
    }
    resp = requests.post(request_url, headers={'Content-type': 'application/json'}, data=json.dumps(chaincodeSpec))
    assert resp.status_code == 200, "Failed to POST to %s:  %s" %(request_url, resp.text)
    context.response = resp
    chaincodeName = resp.json()['message']
    chaincodeSpec['chaincodeID']['name'] = chaincodeName
    context.chaincodeSpec = chaincodeSpec
    print(json.dumps(chaincodeSpec, indent=4))
    print("")

@then(u'I should have received a chaincode name')
def step_impl(context):
    if 'chaincodeSpec' in context:
        assert context.chaincodeSpec['chaincodeID']['name'] != ""
        # Set the current transactionID to the name passed back
        context.transactionID = context.chaincodeSpec['chaincodeID']['name']
    else:
        fail('chaincodeSpec not in context')

@when(u'I invoke chaincode "{chaincodeName}" function name "{functionName}" on "{containerName}"')
def step_impl(context, chaincodeName, functionName, containerName):
    assert 'chaincodeSpec' in context, "chaincodeSpec not found in context"
    # Update hte chaincodeSpec ctorMsg for invoke
    args = []
    if 'table' in context:
       # There is ctor arguments
       args = context.table[0].cells
    context.chaincodeSpec['ctorMsg']['function'] = functionName
    context.chaincodeSpec['ctorMsg']['args'] = args
    # Invoke the POST
    chaincodeInvocationSpec = {
        "chaincodeSpec" : context.chaincodeSpec
    }
    ipAddress = ipFromContainerNamePart(containerName, context.compose_containers)
    request_url = buildUrl(ipAddress, "/devops/invoke")
    print("POSTing path = {0}".format(request_url))

    resp = requests.post(request_url, headers={'Content-type': 'application/json'}, data=json.dumps(chaincodeInvocationSpec))
    assert resp.status_code == 200, "Failed to POST to %s:  %s" %(request_url, resp.text)
    context.response = resp
    print(json.dumps(resp.json(), indent = 4))
    print("RESULT from invokde o fchaincode ")
    print("RESULT from invokde o fchaincode ")
    # TODO: Put these back in once TX id is available in message field of JSON response for invoke.
    transactionID = resp.json()['message']
    context.transactionID = transactionID

@then(u'I should have received a transactionID')
def step_impl(context):
    assert 'transactionID' in context, 'transactionID not found in context'
    assert context.transactionID != ""
    pass

@when(u'I query chaincode "{chaincodeName}" function name "{functionName}" on "{containerName}"')
def step_impl(context, chaincodeName, functionName, containerName):
    invokeChaincode(context, "query", containerName)
    print(json.dumps(context.response.json(), indent = 4))
    print("")
    #raise NotImplementedError(u'STEP: When I query chaincode "example2" function name "query" with "a" on "vp0":')

def invokeChaincode(context, functionName, containerName):
    assert 'chaincodeSpec' in context, "chaincodeSpec not found in context"
    # Update hte chaincodeSpec ctorMsg for invoke
    args = []
    if 'table' in context:
       # There is ctor arguments
       args = context.table[0].cells
    context.chaincodeSpec['ctorMsg']['function'] = functionName
    context.chaincodeSpec['ctorMsg']['args'] = args
    # Invoke the POST
    chaincodeInvocationSpec = {
        "chaincodeSpec" : context.chaincodeSpec
    }
    ipAddress = ipFromContainerNamePart(containerName, context.compose_containers)
    request_url = buildUrl(ipAddress, "/devops/{0}".format(functionName))
    print("POSTing path = {0}".format(request_url))

    resp = requests.post(request_url, headers={'Content-type': 'application/json'}, data=json.dumps(chaincodeInvocationSpec))
    assert resp.status_code == 200, "Failed to POST to %s:  %s" %(request_url, resp.text)
    context.response = resp

@then(u'I wait "{seconds}" seconds for chaincode to build')
def step_impl(context, seconds):
    """ This step takes into account the chaincodeImagesUpToDate tag, in which case the wait is reduce to some default seconds"""
    reducedWaitTime = 4
    if 'chaincodeImagesUpToDate' in context.tags:
        print("Assuming images are up to date, sleeping for {0} seconds instead of {1} in scenario {2}".format(reducedWaitTime, seconds, context.scenario.name))
        time.sleep(float(reducedWaitTime))
    else:
        time.sleep(float(seconds))

@then(u'I wait "{seconds}" seconds for transaction to be committed to block on "{containerName}"')
def step_impl(context, seconds, containerName):
    assert 'transactionID' in context, "transactionID not found in context"
    ipAddress = ipFromContainerNamePart(containerName, context.compose_containers)
    request_url = buildUrl(ipAddress, "/transactions/{0}".format(context.transactionID))
    print("GETing path = {0}".format(request_url))

    resp = requests.get(request_url, headers={'Accept': 'application/json'})
    assert resp.status_code == 200, "Failed to POST to %s:  %s" %(request_url, resp.text)
    context.response = resp

def multiRequest(context, seconds, containerDataList, pathBuilderFunc):
    """Perform a multi request against the system"""
    # Build map of "containerName" : response
    respMap = {container.containerName:None for container in containerDataList}
    # Set the max time before stopping attempts
    maxTime = datetime.now() + timedelta(seconds = int(seconds))
    for container in containerDataList:
        ipAddress = container.ipAddress
        request_url = buildUrl(ipAddress, pathBuilderFunc(context, container))

        # Loop unless failure or time exceeded
        while (datetime.now() < maxTime):
            print("GETing path = {0}".format(request_url))
            resp = requests.get(request_url, headers={'Accept': 'application/json'})
            respMap[container.containerName] = resp
        else:
            raise Exception("Max time exceeded waiting for multiRequest with current response map = {0}".format(respMap))

@then(u'I wait up to "{seconds}" seconds for transaction to be committed to all peers')
def step_impl(context, seconds):
    assert 'transactionID' in context, "transactionID not found in context"
    assert 'compose_containers' in context, "compose_containers not found in context"

    # Build map of "containerName" : resp.statusCode
    respMap = {container.containerName:0 for container in context.compose_containers}

    # Set the max time before stopping attempts
    maxTime = datetime.now() + timedelta(seconds = int(seconds))
    for container in context.compose_containers:
        ipAddress = container.ipAddress
        request_url = buildUrl(ipAddress, "/transactions/{0}".format(context.transactionID))

        # Loop unless failure or time exceeded
        while (datetime.now() < maxTime):
            print("GETing path = {0}".format(request_url))
            resp = requests.get(request_url, headers={'Accept': 'application/json'})
            if resp.status_code == 404:
                # Pause then try again
                respMap[container.containerName] = 404
                time.sleep(1)
                continue
            elif resp.status_code == 200:
                # Success, continue
                respMap[container.containerName] = 200
                break
            else:
                raise Exception("Error requesting {0}, returned result code = {1}".format(request_url, resp.status_code))
        else:
            raise Exception("Max time exceeded waiting for transactions with current response map = {0}".format(respMap))
    print("Result of request to all peers = {0}".format(respMap))
    print("")

@when(u'I query chaincode "{chaincodeName}" function name "{functionName}" on all peers')
def step_impl(context, chaincodeName, functionName):
    assert 'chaincodeSpec' in context, "chaincodeSpec not found in context"
    assert 'compose_containers' in context, "compose_containers not found in context"
    # Update the chaincodeSpec ctorMsg for invoke
    args = []
    if 'table' in context:
       # There is ctor arguments
       args = context.table[0].cells
    context.chaincodeSpec['ctorMsg']['function'] = functionName
    context.chaincodeSpec['ctorMsg']['args'] = args #context.table[0].cells if ('table' in context) else []
    # Invoke the POST
    chaincodeInvocationSpec = {
        "chaincodeSpec" : context.chaincodeSpec
    }
    responses = []
    for container in context.compose_containers:
        request_url = buildUrl(container.ipAddress, "/devops/{0}".format(functionName))
        print("POSTing path = {0}".format(request_url))
        resp = requests.post(request_url, headers={'Content-type': 'application/json'}, data=json.dumps(chaincodeInvocationSpec))
        assert resp.status_code == 200, "Failed to POST to %s:  %s" %(request_url, resp.text)
        responses.append(resp)
    context.responses = responses

@then(u'I should get a JSON response from all peers with "{attribute}" = "{expectedValue}"')
def step_impl(context, attribute, expectedValue):
    assert 'responses' in context, "responses not found in context"
    for resp in context.responses:
        assert attribute in resp.json(), "Attribute not found in response (%s)" %(attribute)
        foundValue = resp.json()[attribute]
        assert (str(foundValue) == expectedValue), "For attribute %s, expected (%s), instead found (%s)" % (attribute, expectedValue, foundValue)


text:
var sqlite3 = require('sqlite3').verbose();
var db_name = (process.env.NODE_ENV == 'test') ? ':memory:' : 'db.sqlite';
var db = db(new sqlite3.Database(db_name));

function db(conn) {
    conn.serialize(function () {
        conn.run('CREATE TABLE IF NOT EXISTS players (id INTEGER PRIMARY KEY AUTOINCREMENT, username VARCHAR(128))');
        conn.run('CREATE TABLE IF NOT EXISTS rounds (id INTEGER PRIMARY KEY AUTOINCREMENT, victor INTEGER, game INTEGER, FOREIGN KEY (victor) REFERENCES players (id), FOREIGN KEY (game) REFERENCES games (id))');
        conn.run('CREATE TABLE IF NOT EXISTS choices (id INTEGER PRIMARY KEY AUTOINCREMENT, option VARCHAR(128), player INTEGER, round INTEGER, FOREIGN KEY (player) REFERENCES players (id), FOREIGN KEY (round) REFERENCES rounds (id))');
        conn.run('CREATE TABLE IF NOT EXISTS games (id INTEGER PRIMARY KEY AUTOINCREMENT, date_played DATETIME, game_type INTEGER, FOREIGN KEY (game_type) REFERENCES game_types (id))');
        conn.run('CREATE TABLE IF NOT EXISTS game_types (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(128), num_of_players INTEGER)');
    });

    return conn;
}

exports.db = db;

// expects choices to be [{player: player, choice: str}]
exports.save_round = function (victor, game, choices, callback) {
    if (game == null || choices == null) {
        throw "#db save_round cannot be called with null game or choices";
    }

    db.serialize(function () {
        game_id(game, function (game_id) {
            player_id(victor, function (p_id) {
                db.run('INSERT INTO rounds (victor, game) VALUES (?, ?)', p_id, game_id, function (err) {
                    if (err) {
                        throw err;
                    }

                    var round_id = this.lastID;

                    function _save_choices(selections, round_id, callback) {
                        if (choices.length > 0) {
                            var selection = selections.pop();
                            player_id(selection.player, function (id) {
                                db.run('INSERT INTO choices (option, player, round) VALUES (?, ?, ?)', selection.choice, id, round_id, function (err) {
                                    if (err) {
                                        throw err;
                                    }

                                    _save_choices(selections, round_id, callback);
                                })
                            })
                        } else {
                            if (callback) {
                                return callback();
                            }
                        }
                    }

                    _save_choices(choices, round_id, callback);
                })
            })
        })
    })
}

function player_id(player, callback) {
    // @TODO: validate player has required fields
    if (player == undefined || player.hasOwnProperty('username') == false) {
        return player_id({username: 'Tied'}, callback);
    }

    db.get('SELECT id FROM players WHERE username = ?', player.username, function (err, row) {
        var player_id = row;

        if (player_id == undefined) {
            db.run('INSERT INTO players (username) VALUES (?)', player.username, function (err) {
                if (err) {
                    throw err;
                }

                callback(this.lastID);
            });
        } else {
            callback(player_id.id);
        }
    })
}

function game_id(game, callback) {
    game_type_id(game, function (game_type_id) {
        db.get('SELECT id FROM games WHERE game_type = ? AND date_played = ?', game_type_id, GAME_START_TIME, function (err, row) {
            var game_id = row;

            if (game_id == undefined) {
                db.run('INSERT INTO games (game_type, date_played) VALUES (?, ?)', game_type_id, GAME_START_TIME, function (err) {
                    if (err) {
                        throw err;
                    }

                    callback(this.lastID);
                });
            } else {
                callback(game_id.id);
            }
        })
    })
}

function game_type_id(game, callback) {
    // @TODO: validate game has required fields
    db.get('SELECT id FROM game_types WHERE name = ? AND num_of_players = ?', game.display_name, game.num_per_round, function (err, row) {
        var type_id = row;

        if (type_id == undefined) {
            db.run('INSERT INTO game_types (name, num_of_players) VALUES (?, ?)', game.display_name, game.num_per_round, function (err) {
                if (err) {
                    throw err;
                }

                callback(this.lastID);
            });
        } else {
            callback(type_id.id);
        }
    })
}


text:
require 'test_helper'
class UserSigninIntegrationTest < Capybara::Rails::TestCase
  # Testing screens for tasks

  include Warden::Test::Helpers
  Warden.test_mode!

  describe 'Logged in user' do
    before do
      @user = users(:user_1)
      login_as(@user, :scope => :user)
    end
  end
end


text:
<?php

namespace Magento\Framework\App;

use Magento\Framework\App\Cache\ManagerApp;
use Magento\Framework\Shell\ComplexParameter;

require __DIR__ . '/../../app/bootstrap.php';

$usage = 'Usage: php -f cache.php -- [--' . ManagerApp::KEY_SET . '=1|0]'
    . ' [--' . ManagerApp::KEY_CLEAN . ']'
    . ' [--' . ManagerApp::KEY_FLUSH . ']'
    . ' [--' . ManagerApp::KEY_TYPES . '=<type1>,<type2>,...]'
    . ' [--bootstrap=' . escapeshellarg('INIT_PARAM=foo&ANOTHER_PARAM[key]=bar') . ']
    --' . ManagerApp::KEY_TYPES . ' - list of cache types, comma-separated. If omitted, all caches will be affected
    --' . ManagerApp::KEY_SET . ' - enable or disable the specified cache types
    --' . ManagerApp::KEY_CLEAN . ' - clean data of the specified cache types
    --' . ManagerApp::KEY_FLUSH . ' - destroy all data in storage that the specified cache types reside on
    --bootstrap - add or override parameters of the bootstrap' . PHP_EOL;
$longOpts = [
    ManagerApp::KEY_SET . '::',
    ManagerApp::KEY_CLEAN,
    ManagerApp::KEY_FLUSH,
    ManagerApp::KEY_TYPES . '::',
    'bootstrap::',
];
$opt = getopt('', $longOpts);
if (empty($opt)) {
    echo $usage;
}

try {
    $bootstrapParam = new ComplexParameter('bootstrap');
    $params = $bootstrapParam->mergeFromArgv($_SERVER, $_SERVER);
    $params[Bootstrap::PARAM_REQUIRE_MAINTENANCE] = null;
    $bootstrap = Bootstrap::create(BP, $params);
    /** @var ManagerApp $app */
    $app = $bootstrap->createApplication('Magento\Framework\App\Cache\ManagerApp', ['requestArgs' => $opt]);
    $bootstrap->run($app);
} catch (\Exception $e) {
    echo $e;
    exit(1);
}


text:
"""Routing and dispatching tools."""

import asyncio
import re
from aiohttp import hdrs
from aiohttp.abc import AbstractRouter, AbstractMatchInfo
from aiohttp.protocol import HttpVersion11
from hypr.web_exceptions import HTTPMethodNotAllowed, HTTPNotFound, \
                                HTTPInternalServerError, HTTPTemporaryRedirect
from aiohttp.web import Response
from hypr.converters import DEFAULT_CONVERTERS
from hypr.providers import Provider
from hypr.globals import LocalStorage
from hypr.serializers import json_serializer

__all__ = ('Dispatcher', 'Rule')

_rule_re = re.compile(r'''
    (?P<static>[^<]*)                           # static rule data
    <
    (?:
        (?P<converter>[a-zA-Z_][a-zA-Z0-9_]*)   # converter name
        (?:\((?P<args>.*?)\))?                  # converter arguments
        \:                                      # variable delimiter
    )?
    (?P<variable>[a-zA-Z_][a-zA-Z0-9_]*)        # variable name
    >
''', re.VERBOSE)

_converter_args_re = re.compile(r'''
    ((?P<name>\w+)\s*=\s*)?
    (?P<value>
        True|False|
        \d+.\d+|
        \d+.|
        \d+|
        \w+|
        [urUR]?(?P<stringval>"[^"]*?"|'[^']*')
    )\s*,
''', re.VERBOSE | re.UNICODE)

_PYTHON_CONSTANTS = {
    'None':     None,
    'True':     True,
    'False':    False
}

def _pythonize(value):
    if value in _PYTHON_CONSTANTS:
        return _PYTHON_CONSTANTS[value]
    for convert in int, float:
        try:
            return convert(value)
        except ValueError:
            pass
    if value[:1] == value[-1:] and value[0] in '"\'':
        value = value[1:-1]
    return str(value)

def get_converter(converter_name, args, kwargs):
    """Looks up the converter for the given parameter."""

    err_msg = 'The converter {!r} does not exist'

    if converter_name not in DEFAULT_CONVERTERS:
        raise LookupError(err_msg.format(converter_name))
    return DEFAULT_CONVERTERS[converter_name](*args, **kwargs)

def parse_converter_args(argstr):
    """
    """
    argstr += ','
    args = []
    kwargs = {}

    for item in _converter_args_re.finditer(argstr):
        value = item.group('stringval')
        if value is None:
            value = item.group('value')
        value = _pythonize(value)
        if not item.group('name'):
            args.append(value)
        else:
            name = item.group('name')
            kwargs[name] = value

    return tuple(args), kwargs

def parse_rule(rule):
    """
    Parse a rule and return it as a generator. Each iteration yields tuples
    in the form ``(converter, arguments, variable)``. If the converter is
    `None` it's static url part, otherwise it's a dynamic one.
    """
    pos = 0
    end = len(rule)

    do_match = _rule_re.match
    used_names = set()

    while pos < end:
        match = do_match(rule, pos)
        if match is None:
            break
        data = match.groupdict()
        if data['static']:
            yield None, None, data['static']

        variable = data['variable']
        converter = data['converter'] or 'default'

        if variable in used_names:
            raise ValueError('variable name %r used twice.' % variable)
        used_names.add(variable)

        yield converter, data['args'] or None, variable
        pos = match.end()

    if pos < end:
        remaining = rule[pos:]
        if '>' in remaining or '<' in remaining:
            raise ValueError('malformed url rule: %r' % rule)
        yield None, None, remaining

# compatibility with asyncio.web original Application
@asyncio.coroutine
def _defaultExpectHandler(request):
    """Default handler for Except: 100-continue"""
    if request.version == HttpVersion11:
        request.transport.write(b'HTTP/1.1 100 Continue\r\n\r\n')

class MatchInfo(dict, AbstractMatchInfo):

    def __init__(self, match_dict, rule, provider):
        super().__init__(match_dict)
        self._provider = provider
        self._rule = rule

    @property
    def route(self):
        return self._rule

    @property
    def handler(self):

        def ensure_response(request):

            rv = yield from self._provider.local_dispatcher(request)

            status_or_headers = headers = None
            if isinstance(rv, tuple):
                rv, status_or_headers, headers = rv + (None,) * (3 - len(rv))

            if rv is None:
                raise HTTPInternalServerError()

            if isinstance(status_or_headers, (list, dict)):
                headers, status_or_headers = status_or_headers, None

            if not isinstance(rv, Response):

                data = rv

                rv = Response(headers=headers, status=status_or_headers or 200,
                              content_type='application/json')

                pp = request.args.get('_pprint', '').lower() in ('true', '1')
                rv.text = json_serializer(data, pretty_print=pp)
                headers = status_or_headers = None

            if status_or_headers is not None:
                if isinstance(status_or_headers, int):
                    rv.status = status_or_headers

            if headers:
                rv.headers.extend(headers)

            return rv

        return ensure_response

    def __repr__(self):
        return "<MatchInfo {}: {}>".format(super().__repr__(), self.rule)

class Rule:

    def __init__(self, url, endpoint=None, methods=None, expect_handler=None):

        err_msg = 'Coroutine is expected, got {!r}'

        self.url = url
        self.endpoint = endpoint

        if methods is None:
            self.methods = hdrs.METH_ANY
        else:
            self.methods = set([m.upper() for m in methods])

        if expect_handler is None:
            expect_handler = _defaultExpectHandler
        assert asyncio.iscoroutinefunction(expect_handler), \
            err_msg.format(expect_handler)

        self.arguments = set()
        self.is_leaf = not url.endswith('/')
        self._trace = self._converters = self._regex = None

    def compile(self):
        """Compiles the regular expression and stores it."""

        self._trace = []
        self._converters = {}

        regex_parts = []

        def _build_regex(rule):

            for converter, arguments, variable in parse_rule(rule):
                if converter is None:
                    regex_parts.append(re.escape(variable))
                    self._trace.append((False, variable))
                else:
                    if arguments:
                        c_args, c_kwargs = parse_converter_args(arguments)
                    else:
                        c_args = ()
                        c_kwargs = {}
                    convobj = get_converter(converter, c_args, c_kwargs)
                    regex_parts.append('(?P<{}>{})'.format(variable,
                                                           convobj.regex))
                    self._converters[variable] = convobj
                    self._trace.append((True, variable))
                    self.arguments.add(str(variable))

        _build_regex(self.is_leaf and self.url or self.url.rstrip('/'))
        if not self.is_leaf:
            self._trace.append((False, '/'))

        regex = r'^{}{}$'.format(
            ''.join(regex_parts),
            not self.is_leaf and '(?<!/)(?P<__suffix__>/?)' or ''
        )

        self._regex = re.compile(regex, re.UNICODE)

    def match(self, path):
        """
        Check if the rule matches a given path.

        If the rule matches a dict with the converted values is returned,
        otherwise the return value is `None`.
        """

        m = self._regex.search(path)
        if m is not None:
            groups = m.groupdict()

            if not self.is_leaf and not groups.pop('__suffix__'):
                raise HTTPTemporaryRedirect(path + '/')

            result = {}
            for name, value in groups.items():
                try:
                    value = self._converters[name].to_python(value)
                except ValueError:
                    return
                result[str(name)] = value

            return result

class Dispatcher(AbstractRouter):

    def __init__(self):

        super().__init__()

        self._rules = []
        self._providers = {}

    @asyncio.coroutine
    def resolve(self, request):

        # initialize the local storage
        LocalStorage().set('request', request)

        path = request.path
        method = request.method

        allowed_methods = set()

        for rule in self._rules:
            match_dict = rule.match(path)

            if match_dict is None:
                continue

            if rule.methods == hdrs.METH_ANY or method in rule.methods:
                provider = self._providers[rule.endpoint]
                return MatchInfo(match_dict, rule, provider)

            allowed_methods.update(rule.methods)

        if allowed_methods:
            raise HTTPMethodNotAllowed(method, allowed_methods)
        else:
            raise HTTPNotFound()

    def add_provider(self, provider, *urls, endpoint=None, methods=None):
        """
        Register a provider for one or multiple given URLs.
        """

        err_msg = [
            'A Provider is required',
            'The endpoint {!r} already exists',
            'URL should be started with \'/\''
        ]

        # if the endpoint is not provided, use the name of the provider as the
        # endpoint
        if endpoint is None:
            endpoint = provider.__name__

        # if available methods are not specified, use the list of the
        # implemented methods in the provider.
        if methods is None:
            methods = provider._methods

        # some sanity checks
        assert issubclass(provider, Provider), err_msg[0]
        assert endpoint not in self._providers, err_msg[1].format(endpoint)

        for path in urls:
            if not path.startswith('/'):
                raise ValueError(err_msg[2])
            rule = Rule(path, endpoint, methods)
            rule.compile()

            self._rules.append(rule)

        if urls:
            self._providers[endpoint] = provider()

    def propagate(self, app):

        for endpoint, provider in dict(self._providers).items():
            for subrule in provider._subrules(app, prefixes=tuple(self.iter_rules(endpoint))):
                entry = provider.__class__
                ep, urls, target = subrule
                self.add_provider(entry, *urls, endpoint=ep, methods=target._methods)

    def get_provider(self, endpoint):

        instance = self._providers.get(endpoint, None)

        if instance is not None:
            return instance.__class__

    def iter_rules(self, endpoint=None):

        return (rule.url for rule in self._rules if endpoint is None
                or rule.endpoint == endpoint)


text:
require 'spec_helper'

describe CommitRange do
  describe 'modules' do
    subject { described_class }

    it { is_expected.to include_module(Referable) }
  end

  let(:sha_from) { 'f3f85602' }
  let(:sha_to)   { 'e86e1013' }

  let(:range)  { described_class.new("#{sha_from}...#{sha_to}") }
  let(:range2) { described_class.new("#{sha_from}..#{sha_to}") }

  it 'raises ArgumentError when given an invalid range string' do
    expect { described_class.new("Foo") }.to raise_error(ArgumentError)
  end

  describe '#to_s' do
    it 'is correct for three-dot syntax' do
      expect(range.to_s).to eq "#{sha_from[0..7]}...#{sha_to[0..7]}"
    end

    it 'is correct for two-dot syntax' do
      expect(range2.to_s).to eq "#{sha_from[0..7]}..#{sha_to[0..7]}"
    end
  end

  describe '#to_reference' do
    let(:project) { double('project', to_reference: 'namespace1/project') }

    before do
      range.project = project
    end

    it 'returns a String reference to the object' do
      expect(range.to_reference).to eq range.to_s
    end

    it 'supports a cross-project reference' do
      cross = double('project')
      expect(range.to_reference(cross)).to eq "#{project.to_reference}@#{range.to_s}"
    end
  end

  describe '#reference_title' do
    it 'returns the correct String for three-dot ranges' do
      expect(range.reference_title).to eq "Commits #{sha_from} through #{sha_to}"
    end

    it 'returns the correct String for two-dot ranges' do
      expect(range2.reference_title).to eq "Commits #{sha_from}^ through #{sha_to}"
    end
  end

  describe '#to_param' do
    it 'includes the correct keys' do
      expect(range.to_param.keys).to eq %i(from to)
    end

    it 'includes the correct values for a three-dot range' do
      expect(range.to_param).to eq({ from: sha_from, to: sha_to })
    end

    it 'includes the correct values for a two-dot range' do
      expect(range2.to_param).to eq({ from: sha_from + '^', to: sha_to })
    end
  end

  describe '#exclude_start?' do
    it 'is false for three-dot ranges' do
      expect(range.exclude_start?).to eq false
    end

    it 'is true for two-dot ranges' do
      expect(range2.exclude_start?).to eq true
    end
  end

  describe '#valid_commits?' do
    context 'without a project' do
      it 'returns nil' do
        expect(range.valid_commits?).to be_nil
      end
    end

    it 'accepts an optional project argument' do
      project1 = double('project1').as_null_object
      project2 = double('project2').as_null_object

      # project1 gets assigned through the accessor, but ignored when not given
      # as an argument to `valid_commits?`
      expect(project1).not_to receive(:present?)
      range.project = project1

      # project2 gets passed to `valid_commits?`
      expect(project2).to receive(:present?).and_return(false)

      range.valid_commits?(project2)
    end

    context 'with a project' do
      let(:project) { double('project', repository: double('repository')) }

      context 'with a valid repo' do
        before do
          expect(project).to receive(:valid_repo?).and_return(true)
          range.project = project
        end

        it 'is false when `sha_from` is invalid' do
          expect(project.repository).to receive(:commit).with(sha_from).and_return(false)
          expect(project.repository).not_to receive(:commit).with(sha_to)
          expect(range).not_to be_valid_commits
        end

        it 'is false when `sha_to` is invalid' do
          expect(project.repository).to receive(:commit).with(sha_from).and_return(true)
          expect(project.repository).to receive(:commit).with(sha_to).and_return(false)
          expect(range).not_to be_valid_commits
        end

        it 'is true when both `sha_from` and `sha_to` are valid' do
          expect(project.repository).to receive(:commit).with(sha_from).and_return(true)
          expect(project.repository).to receive(:commit).with(sha_to).and_return(true)
          expect(range).to be_valid_commits
        end
      end

      context 'without a valid repo' do
        before do
          expect(project).to receive(:valid_repo?).and_return(false)
          range.project = project
        end

        it 'returns false' do
          expect(range).not_to be_valid_commits
        end
      end
    end
  end
end


text:
#ifndef GRIB_INTERFACE_H
#define GRIB_INTERFACE_H

int grib_c_read_any_from_file(int *fid, char *buffer, int *nbytes);
int grib_c_write_file(int *fid, char *buffer, int *nbytes);
int grib_c_read_file(int *fid, char *buffer, int *nbytes);
int grib_c_open_file(int *fid, char *name, char *op);
int grib_c_close_file(int *fid);
int grib_c_multi_support_on(void);
int grib_c_multi_support_off(void);
int grib_c_iterator_new(int *gid, int *iterid, int *mode);
int grib_c_iterator_next(int *iterid, double *lat, double *lon, double *value);
int grib_c_iterator_delete(int *iterid);
int grib_c_keys_iterator_new(int *gid, int *iterid, char *name_space);
int grib_c_keys_iterator_next(int *iterid);
int grib_c_keys_iterator_get_name(int *iterid, char *name, int len);
int grib_c_keys_iterator_rewind(int *kiter);
int grib_c_keys_iterator_delete(int *iterid);
int codes_c_bufr_keys_iterator_new(int *gid, int *iterid);
int codes_c_bufr_keys_iterator_next(int *iterid);
int codes_c_bufr_keys_iterator_get_name(int *iterid, char *name, int len);
int codes_c_bufr_keys_iterator_rewind(int *kiter);
int codes_c_bufr_keys_iterator_delete(int *iterid);

int grib_c_gribex_mode_on(void);
int grib_c_gribex_mode_off(void);
int grib_c_skip_computed(int *iterid);
int grib_c_skip_coded(int *iterid);
int grib_c_skip_edition_specific(int *iterid);
int grib_c_skip_duplicates(int *iterid);
int grib_c_skip_read_only(int *iterid);
int grib_c_skip_function(int *iterid);
int grib_c_new_from_message(int *gid, void *buffer, size_t *bufsize);
int grib_c_new_from_message_copy(int *gid, void *buffer, size_t *bufsize);
int grib_c_grib_new_from_samples(int *gid, char *name);
int grib_c_bufr_new_from_samples(int *gid, char *name);
int grib_c_clone(int *gidsrc, int *giddest);
int grib_c_copy_namespace(int *gidsrc, char *name, int *giddest);
int grib_c_count_in_file(FILE *f, int *n);
int grib_c_new_from_file(FILE *f, int *gid, int headers_only);
int grib_c_new_any_from_file(FILE *f, int headers_only,int *gid);
int grib_c_new_bufr_from_file(FILE *f, int headers_only,int *gid);
int grib_c_new_gts_from_file(FILE *f,int headers_only, int *gid);
int grib_c_new_metar_from_file(FILE* f,int headers_only, int* gid);
int grib_c_new_from_index(int *iid, int *gid);
int grib_c_index_new_from_file(char *file, char *keys, int *gid);
int grib_c_index_add_file(int* iid, char* file);
int grib_c_index_release(int *hid);
int grib_c_multi_release(int *hid);
int grib_c_release(int *hid);
int grib_c_dump(int *gid);
int grib_c_print(int *gid, char *key);
int grib_c_get_error_string(int *err, char *buf, int len);
int grib_c_get_size_int(int *gid, char *key, int *val);
int grib_c_get_size_long(int *gid, char *key, long *val);
int grib_c_index_get_size_int(int *gid, char *key, int *val);
int grib_c_index_get_size_long(int *gid, char *key, long *val);
int grib_c_get_int(int *gid, char *key, int *val);
int grib_c_get_long(int *gid, char *key, long *val);
int grib_c_get_double(int *gid, char *key, double *val);
int grib_c_get_int_array(int *gid, char *key, int *val, int *size);
int grib_c_get_long_array(int *gid, char *key, long *val, int *size);
int grib_c_index_get_string(int *gid, char *key, char *val, int *eachsize, int *size);
int grib_c_index_get_long(int *gid, char *key, long *val, int *size);
int grib_c_index_get_int(int *gid, char *key, int *val, int *size);
int grib_c_index_get_real8(int *gid, char *key, double *val, int *size);
int grib_c_set_int_array(int *gid, char *key, int *val, int *size);
int grib_c_set_long_array(int *gid, char *key, long *val, int *size);
int grib_c_set_int(int *gid, char *key, int *val);
int grib_c_set_long(int *gid, char *key, long *val);
int grib_c_set_missing(int *gid, char *key);
int grib_c_set_key_vals(int* gid, char* keyvals);
int grib_c_is_missing(int *gid, char *key, int *isMissing);
int grib_c_is_defined(int *gid, char *key, int *isDefined);
int grib_c_set_real4(int *gid, char *key, float *val);
int grib_c_get_real4_element(int *gid, char *key, int *index, float *val);
int grib_c_get_real4_elements(int *gid, char *key, int *index, float *val, int *size);
int grib_c_get_real4(int *gid, char *key, float *val);
int grib_c_get_real4_array(int *gid, char *key, float *val, int *size);
int grib_c_set_real4_array(int *gid, char *key, float *val, int *size);
int grib_c_index_select_real8(int *gid, char *key, double *val);
int grib_c_index_select_string(int *gid, char *key, char *val);
int grib_c_index_select_int(int *gid, char *key, int *val);
int grib_c_index_select_long(int *gid, char *key, long *val);
int grib_c_set_real8(int *gid, char *key, double *val);
int grib_c_get_real8(int *gid, char *key, double *val);
int grib_c_get_real8_element(int *gid, char *key, int *index, double *val);
int grib_c_get_real8_elements(int *gid, char *key, int *index, double *val, int *size);
int grib_c_find_nearest_four_single(int *gid, int *is_lsm, double *inlat, double *inlon, double *outlats, double *outlons, double *values, double *distances, int *indexes);
int grib_c_find_nearest_single(int *gid, int *is_lsm, double *inlats, double *inlons, double *outlats, double *outlons, double *values, double *distances, int *indexes);
int grib_c_find_nearest_multiple(int *gid, int *is_lsm, double *inlats, double *inlons, double *outlats, double *outlons, double *values, double *distances, int *indexes, int *npoints);
int grib_c_get_real8_array(int *gid, char *key, double *val, int *size);
int grib_c_set_real8_array(int *gid, char *key, double *val, int *size);
int grib_c_get_string(int *gid, char *key, char *val, size_t *lsize);
int grib_c_get_string_array(int* gid, char* key, char** val, size_t *lsize);
int grib_c_set_string(int *gid, char *key, char *val, int len2);
int grib_c_set_string_array(int *gid, char *key, const char **val);
int grib_c_get_data_real4(int *gid, float *lats, float *lons, float *values, size_t *size);
/*int grib_c_get_data_real8(int *gid, double *lats, double *lons, double *values, size_t *size);*/
int grib_c_get_message_size(int *gid, size_t *len);
int grib_c_get_message_offset(int *gid, size_t *len);
int grib_c_copy_message(int *gid, void *mess, size_t *len);
int grib_c_bufr_copy_data(int *msgid_src, int *msgid_dst);
void grib_c_check(int *err, char *call, char *str);
int grib_c_write(int *gid, FILE *f);
int grib_c_multi_new(int* mgid);
int grib_c_multi_write(int *gid, FILE *f);
int grib_c_multi_append(int *ingid, int *sec, int *mgid);
int grib_c_set_double_array(int* gid, char* key, double*val, int* size);
int grib_c_set_double(int* gid, char* key, double*val);
int grib_c_get_native_type(int* gid, char* key, int* type);
int grib_c_index_write(int* gid, char* file);
int grib_c_index_read(char* file, int* gid);
void no_fail_on_wrong_length(int flag);
long grib_c_get_api_version(void);
void grib_c_gts_header_on(void);
void grib_c_gts_header_off(void);
int grib_c_get_message(int *gid, const void **msg, size_t *size);
int grib_c_get_string_length(int* gid, char* key, size_t* val);
void grib_c_set_definitions_path(const char* path);
void grib_c_set_samples_path(const char* path);

#endif