text:
package io.debezium.server.pubsub;

import java.io.IOException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.enterprise.event.Observes;
import javax.inject.Inject;

import org.assertj.core.api.Assertions;
import org.awaitility.Awaitility;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Test;

import com.google.api.gax.core.CredentialsProvider;
import com.google.api.gax.core.NoCredentialsProvider;
import com.google.api.gax.grpc.GrpcTransportChannel;
import com.google.api.gax.rpc.FixedTransportChannelProvider;
import com.google.api.gax.rpc.NotFoundException;
import com.google.api.gax.rpc.TransportChannelProvider;
import com.google.cloud.ServiceOptions;
import com.google.cloud.pubsub.v1.AckReplyConsumer;
import com.google.cloud.pubsub.v1.MessageReceiver;
import com.google.cloud.pubsub.v1.Subscriber;
import com.google.cloud.pubsub.v1.SubscriptionAdminClient;
import com.google.cloud.pubsub.v1.SubscriptionAdminSettings;
import com.google.cloud.pubsub.v1.TopicAdminClient;
import com.google.cloud.pubsub.v1.TopicAdminSettings;
import com.google.pubsub.v1.ProjectSubscriptionName;
import com.google.pubsub.v1.PubsubMessage;
import com.google.pubsub.v1.PushConfig;
import com.google.pubsub.v1.Topic;
import com.google.pubsub.v1.TopicName;

import io.debezium.server.DebeziumServer;
import io.debezium.server.TestConfigSource;
import io.debezium.server.events.ConnectorCompletedEvent;
import io.debezium.server.events.ConnectorStartedEvent;
import io.debezium.testing.testcontainers.PostgresTestResourceLifecycleManager;
import io.debezium.util.Testing;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.quarkus.test.common.QuarkusTestResource;
import io.quarkus.test.junit.QuarkusTest;

/**
 * Integration test that verifies basic reading from PostgreSQL database and writing to a Google Cloud PubSub stream running on a Google PubSub Emulator
 *
 * @author Jiri Pechanec
 */
@QuarkusTest
@QuarkusTestResource(PostgresTestResourceLifecycleManager.class)
@QuarkusTestResource(PubSubTestResourceLifecycleManager.class)
public class PubSubIT {

    private static final int MESSAGE_COUNT = 4;
    // The topic of this name must exist and be empty
    private static final String STREAM_NAME = "testc.inventory.customers";
    private static final String SUBSCRIPTION_NAME = "testsubs";
    protected static Subscriber subscriber;
    private static ProjectSubscriptionName subscriptionName = ProjectSubscriptionName.of(ServiceOptions.getDefaultProjectId(), SUBSCRIPTION_NAME);
    private static TopicName topicName = TopicName.of(ServiceOptions.getDefaultProjectId(), STREAM_NAME);
    {
        Testing.Files.delete(TestConfigSource.OFFSET_STORE_PATH);
        Testing.Files.createTestingFile(PubSubTestConfigSource.OFFSET_STORE_PATH);
    }

    private static ManagedChannel channel;
    private static TransportChannelProvider channelProvider;
    private static CredentialsProvider credentialsProvider;

    @AfterAll
    static void stop() throws IOException {
        if (subscriber != null) {
            subscriber.stopAsync();
            subscriber.awaitTerminated();

            try (SubscriptionAdminClient subscriptionAdminClient = createSubscriptionAdminClient()) {
                subscriptionAdminClient.deleteSubscription(subscriptionName);
            }

            try (TopicAdminClient topicAdminClient = createTopicAdminClient()) {
                topicAdminClient.deleteTopic(topicName);
            }
        }
        if (channel != null && !channel.isShutdown()) {
            channel.shutdown();
        }
    }

    @Inject
    DebeziumServer server;

    private static final List<PubsubMessage> messages = Collections.synchronizedList(new ArrayList<>());

    class TestMessageReceiver implements MessageReceiver {

        @Override
        public void receiveMessage(PubsubMessage message, AckReplyConsumer consumer) {
            Testing.print("Message arrived: " + message);
            messages.add(message);
            consumer.ack();
        }
    }

    void setupDependencies(@Observes ConnectorStartedEvent event) throws IOException {
        Testing.Print.enable();

        createChannel();

        // get into a clean state before running the test
        try (SubscriptionAdminClient subscriptionAdminClient = createSubscriptionAdminClient()) {
            subscriptionAdminClient.deleteSubscription(subscriptionName);
        }
        catch (NotFoundException e) {
        }

        try (TopicAdminClient topicAdminClient = createTopicAdminClient()) {
            topicAdminClient.deleteTopic(topicName);
        }
        catch (NotFoundException e) {
        }

        // setup topic and sub
        try (TopicAdminClient topicAdminClient = createTopicAdminClient()) {
            Topic topic = topicAdminClient.createTopic(topicName);
            Testing.print("Created topic: " + topic.getName());
        }

        try (SubscriptionAdminClient subscriptionAdminClient = createSubscriptionAdminClient()) {
            int ackDeadlineSeconds = 0;
            subscriptionAdminClient.createSubscription(subscriptionName, topicName,
                    PushConfig.newBuilder().build(), ackDeadlineSeconds);
        }

        subscriber = createSubscriber();
        subscriber.startAsync().awaitRunning();

    }

    void createChannel() {
        channel = ManagedChannelBuilder.forTarget(PubSubTestResourceLifecycleManager.getEmulatorEndpoint()).usePlaintext().build();
        channelProvider = FixedTransportChannelProvider.create(GrpcTransportChannel.create(channel));
        credentialsProvider = NoCredentialsProvider.create();
        Testing.print("Executing test towards pubsub emulator running at: " + PubSubTestResourceLifecycleManager.getEmulatorEndpoint());
    }

    Subscriber createSubscriber() {
        return Subscriber.newBuilder(subscriptionName, new TestMessageReceiver())
                .setChannelProvider(channelProvider)
                .setCredentialsProvider(credentialsProvider)
                .build();

    }

    static SubscriptionAdminClient createSubscriptionAdminClient() throws IOException {
        return SubscriptionAdminClient.create(
                SubscriptionAdminSettings.newBuilder()
                        .setTransportChannelProvider(channelProvider)
                        .setCredentialsProvider(credentialsProvider)
                        .build());

    }

    static TopicAdminClient createTopicAdminClient() throws IOException {
        return TopicAdminClient.create(
                TopicAdminSettings.newBuilder()
                        .setTransportChannelProvider(channelProvider)
                        .setCredentialsProvider(credentialsProvider)
                        .build());

    }

    void connectorCompleted(@Observes ConnectorCompletedEvent event) throws Exception {
        if (!event.isSuccess()) {
            throw (Exception) event.getError().get();
        }
    }

    @Test
    public void testPubSub() throws Exception {
        Awaitility.await().atMost(Duration.ofSeconds(TestConfigSource.waitForSeconds())).until(() -> messages.size() >= MESSAGE_COUNT);
        Assertions.assertThat(messages.size() >= MESSAGE_COUNT);
    }
}


text:
package fr.tolc.jahia.intellij.plugin.cnd.psi;

import com.intellij.psi.tree.IElementType;
import com.intellij.psi.PsiElement;
import com.intellij.lang.ASTNode;
import fr.tolc.jahia.intellij.plugin.cnd.psi.impl.*;

public interface CndTypes {

  IElementType EXTENSION = new CndElementType("EXTENSION");
  IElementType EXTENSIONS = new CndElementType("EXTENSIONS");
  IElementType ITEM_TYPE = new CndElementType("ITEM_TYPE");
  IElementType NAMESPACE = new CndElementType("NAMESPACE");
  IElementType NAMESPACE_IDENTIFIER = new CndElementType("NAMESPACE_IDENTIFIER");
  IElementType NODE_OPTION = new CndElementType("NODE_OPTION");
  IElementType NODE_TYPE = new CndElementType("NODE_TYPE");
  IElementType NODE_TYPE_IDENTIFIER = new CndElementType("NODE_TYPE_IDENTIFIER");
  IElementType PROPERTY = new CndElementType("PROPERTY");
  IElementType PROPERTY_ATTRIBUTES = new CndElementType("PROPERTY_ATTRIBUTES");
  IElementType PROPERTY_CONSTRAINT = new CndElementType("PROPERTY_CONSTRAINT");
  IElementType PROPERTY_DEFAULT = new CndElementType("PROPERTY_DEFAULT");
  IElementType PROPERTY_IDENTIFIER = new CndElementType("PROPERTY_IDENTIFIER");
  IElementType PROPERTY_TYPE_MASK_OPTION = new CndElementType("PROPERTY_TYPE_MASK_OPTION");
  IElementType SUB_NODE = new CndElementType("SUB_NODE");
  IElementType SUB_NODE_ATTRIBUTES = new CndElementType("SUB_NODE_ATTRIBUTES");
  IElementType SUB_NODE_DEFAULT_TYPE = new CndElementType("SUB_NODE_DEFAULT_TYPE");
  IElementType SUB_NODE_TYPE = new CndElementType("SUB_NODE_TYPE");
  IElementType SUPER_TYPE = new CndElementType("SUPER_TYPE");
  IElementType SUPER_TYPES = new CndElementType("SUPER_TYPES");

  IElementType COLON = new CndTokenType("COLON");
  IElementType COMMA = new CndTokenType("COMMA");
  IElementType COMMENT = new CndTokenType("COMMENT");
  IElementType CRLF = new CndTokenType("CRLF");
  IElementType EQUAL = new CndTokenType("EQUAL");
  IElementType EQUAL_PROPERTY_DEFAULT_VALUE = new CndTokenType("EQUAL_PROPERTY_DEFAULT_VALUE");
  IElementType EXTENDS = new CndTokenType("EXTENDS");
  IElementType ITEMTYPE = new CndTokenType("ITEMTYPE");
  IElementType ITEMTYPE_TYPE = new CndTokenType("ITEMTYPE_TYPE");
  IElementType LEFT_ANGLE_BRACKET = new CndTokenType("LEFT_ANGLE_BRACKET");
  IElementType LEFT_BRACKET = new CndTokenType("LEFT_BRACKET");
  IElementType LEFT_ONLY_ANGLE_BRACKET = new CndTokenType("LEFT_ONLY_ANGLE_BRACKET");
  IElementType LEFT_PARENTHESIS = new CndTokenType("LEFT_PARENTHESIS");
  IElementType MINUS = new CndTokenType("MINUS");
  IElementType NAMESPACE_NAME = new CndTokenType("NAMESPACE_NAME");
  IElementType NAMESPACE_URI = new CndTokenType("NAMESPACE_URI");
  IElementType NODE_ATTRIBUTE = new CndTokenType("NODE_ATTRIBUTE");
  IElementType NODE_NAME = new CndTokenType("NODE_NAME");
  IElementType NODE_TYPE_NAME = new CndTokenType("NODE_TYPE_NAME");
  IElementType OPTION = new CndTokenType("OPTION");
  IElementType OPTION_VALUE = new CndTokenType("OPTION_VALUE");
  IElementType PLUS = new CndTokenType("PLUS");
  IElementType PROPERTY_ATTRIBUTE = new CndTokenType("PROPERTY_ATTRIBUTE");
  IElementType PROPERTY_CONSTRAINT_VALUE = new CndTokenType("PROPERTY_CONSTRAINT_VALUE");
  IElementType PROPERTY_DEFAULT_VALUE = new CndTokenType("PROPERTY_DEFAULT_VALUE");
  IElementType PROPERTY_MASK = new CndTokenType("PROPERTY_MASK");
  IElementType PROPERTY_MASK_OPTION = new CndTokenType("PROPERTY_MASK_OPTION");
  IElementType PROPERTY_MASK_OPTION_VALUE = new CndTokenType("PROPERTY_MASK_OPTION_VALUE");
  IElementType PROPERTY_NAME = new CndTokenType("PROPERTY_NAME");
  IElementType PROPERTY_TYPE = new CndTokenType("PROPERTY_TYPE");
  IElementType RIGHT_ANGLE_BRACKET = new CndTokenType("RIGHT_ANGLE_BRACKET");
  IElementType RIGHT_BRACKET = new CndTokenType("RIGHT_BRACKET");
  IElementType RIGHT_ONLY_ANGLE_BRACKET = new CndTokenType("RIGHT_ONLY_ANGLE_BRACKET");
  IElementType RIGHT_PARENTHESIS = new CndTokenType("RIGHT_PARENTHESIS");
  IElementType SINGLE_QUOTE = new CndTokenType("SINGLE_QUOTE");

  class Factory {
    public static PsiElement createElement(ASTNode node) {
      IElementType type = node.getElementType();
      if (type == EXTENSION) {
        return new CndExtensionImpl(node);
      }
      else if (type == EXTENSIONS) {
        return new CndExtensionsImpl(node);
      }
      else if (type == ITEM_TYPE) {
        return new CndItemTypeImpl(node);
      }
      else if (type == NAMESPACE) {
        return new CndNamespaceImpl(node);
      }
      else if (type == NAMESPACE_IDENTIFIER) {
        return new CndNamespaceIdentifierImpl(node);
      }
      else if (type == NODE_OPTION) {
        return new CndNodeOptionImpl(node);
      }
      else if (type == NODE_TYPE) {
        return new CndNodeTypeImpl(node);
      }
      else if (type == NODE_TYPE_IDENTIFIER) {
        return new CndNodeTypeIdentifierImpl(node);
      }
      else if (type == PROPERTY) {
        return new CndPropertyImpl(node);
      }
      else if (type == PROPERTY_ATTRIBUTES) {
        return new CndPropertyAttributesImpl(node);
      }
      else if (type == PROPERTY_CONSTRAINT) {
        return new CndPropertyConstraintImpl(node);
      }
      else if (type == PROPERTY_DEFAULT) {
        return new CndPropertyDefaultImpl(node);
      }
      else if (type == PROPERTY_IDENTIFIER) {
        return new CndPropertyIdentifierImpl(node);
      }
      else if (type == PROPERTY_TYPE_MASK_OPTION) {
        return new CndPropertyTypeMaskOptionImpl(node);
      }
      else if (type == SUB_NODE) {
        return new CndSubNodeImpl(node);
      }
      else if (type == SUB_NODE_ATTRIBUTES) {
        return new CndSubNodeAttributesImpl(node);
      }
      else if (type == SUB_NODE_DEFAULT_TYPE) {
        return new CndSubNodeDefaultTypeImpl(node);
      }
      else if (type == SUB_NODE_TYPE) {
        return new CndSubNodeTypeImpl(node);
      }
      else if (type == SUPER_TYPE) {
        return new CndSuperTypeImpl(node);
      }
      else if (type == SUPER_TYPES) {
        return new CndSuperTypesImpl(node);
      }
      throw new AssertionError("Unknown element type: " + type);
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
package com.sqb.designpattern.strategy;

public class Multiply extends AbstractCalculator implements ICalculator {

    @Override
    public int calculate(String exp) {
        int arrayInt[] = split(exp, "\\*");
        return arrayInt[0] * arrayInt[1];
    }

}


text:
from django.forms import ModelForm, Select

from ide.models.user import UserSettings

class SettingsForm(ModelForm):
    class Meta:
        model = UserSettings
        exclude = ('user', 'accepted_terms', 'whats_new')
        widgets = {
            'use_spaces': Select
        }


text:
using namespace std::tr2::sys;

size_t sizeStringToSectorCount(const std::string &value)
{
    std::stringstream stream(value);

    size_t size;
    char unit;

    stream >> size;

    if (stream.fail())
        throw std::exception("invalid size");

    stream >> unit;

    if (stream.fail())
        unit = 0;

    switch (unit)
    {
        case 0:
            return size;

        case 'k':
        case 'K':
            return (size * 1024) / 512;

        case 'm':
        case 'M':
            return (size * 1024 * 1024) / 512;

        case 'g':
        case 'G':
            return (size * 1024 * 1024 * 1024) / 512;

        default:
            throw std::exception("invalid size unit");
    }
}

int makeImage(
    const std::string &image,
    const std::string &size,
    const std::string &volumeLabel,
    const std::string &bootloader,
    const std::string &root)
{
    try
    {
        auto &rootPath = path(root);

        if (!exists(rootPath))
            throw std::exception("root doesn't exist");

        if (!is_directory(rootPath))
            throw std::exception("root must be a directory");

        auto &disk = Disk::create(image, sizeStringToSectorCount(size));
        Fat32Disk::format(disk, volumeLabel);

        auto &fat32Disk = std::make_shared<Fat32Disk>(disk);

        auto &it = recursive_directory_iterator(rootPath);
        auto &end = recursive_directory_iterator();

        auto &currentDir = fat32Disk->root();
        auto currentDepth = 0;

        for (; it != end; it++)
        {
            auto &e = *it;

            auto &entryPath = e.path();
            auto &entryFileName = entryPath.filename().string();

            while (currentDepth > it.depth())
            {
                currentDir = currentDir->up();
                currentDepth--;
            }

            if (is_directory(entryPath))
            {
                currentDepth++;

                if (!currentDir->add(entryFileName, FatAttrib::Directory))
                    throw std::exception("failed to create directory entry");

                currentDir = currentDir->directory(entryFileName);
                continue;
            }

            {
                if (!currentDir->add(entryFileName, FatAttrib::File))
                    throw std::exception("failed to create file entry");

                auto &output = currentDir->file(entryFileName);

                std::ifstream input(entryPath, std::ios::binary);

                if (!input.is_open())
                    throw std::exception("failed to open input file");

                while (true)
                {
                    char buffer[4096];
                    input.read(buffer, sizeof(buffer));
                    auto bytesRead = input.gcount();

                    if (bytesRead == 0)
                    {
                        if (input.eof())
                            break;

                        if (input.fail())
                            throw std::exception("failed to read from input file");
                    }

                    output.write(buffer, (size_t)bytesRead);
                }
            }
        }

        if (bootloader != "")
        {
            std::ifstream bootFile(bootloader, std::ios::binary);
            if (!bootFile.is_open())
                throw std::exception("failed to open bootloader");

            Fat32Bpb currentBpb;
            disk->readSector(0, &currentBpb);

            Fat32Bpb newBpb;
            bootFile.read((char*)&newBpb, sizeof(Fat32Bpb));

            if (bootFile.fail() || bootFile.gcount() != sizeof(Fat32Bpb))
                throw std::exception("failed to read bootloader");

            std::memcpy(currentBpb.jump, newBpb.jump, sizeof(Fat32Bpb::jump));
            std::memcpy(currentBpb.code, newBpb.code, sizeof(Fat32Bpb::code));
            currentBpb.bootSig = newBpb.bootSig;

            disk->writeSector(0, &currentBpb);
        }
    }
    catch (std::exception &e)
    {
        std::cout << "error: " << e.what() << std::endl;
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}

void usage()
{
    std::cout << "usage: mknsfat32fs [-o output.img] [-s size] [-l volumeLabel] [-b boot.bin] path" << std::endl;
}

int main(int argc, char *argv[])
{
    std::string image = "disk.img";
    std::string size = "10M";
    std::string volumeLabel;
    std::string bootloader;
    std::string root;

    if (argc < 1)
    {
        usage();
        return EXIT_FAILURE;
    }

    for (int i = 1; i < argc; i++)
    {
        std::string arg = argv[i];

        if (arg == "-o" || arg == "-s" || arg == "-l" || arg == "-b")
        {
            i++;

            if (i >= argc - 1)
            {
                usage();
                return EXIT_FAILURE;
            }

            if (arg == "-o")
                image = argv[i];
            else if (arg == "-s")
                size = argv[i];
            else if (arg == "-l")
                volumeLabel = argv[i];
            else if (arg == "-b")
                bootloader = argv[i];
            else
            {
                usage();
                return EXIT_FAILURE;
            }

            continue;
        }

        root = arg;
        break;
    }

    if (root == "")
    {
        usage();
        return EXIT_FAILURE;
    }

    return makeImage(image, size, volumeLabel, bootloader, root);
}


text:
#include <limits.h>
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/mman.h>
#include "test.h"
#include "../peterson/peterson.h"

static void* shared = NULL;

static int* value = NULL;

static void* flag_turn = NULL;
static struct peterson* peterson = NULL;

static pid_t* process = NULL;

struct test* prepare(int n)
{
	struct test* test = NULL;
	int i;

	if(!(shared = mmap(NULL, peterson_flag_turn_size(n) + sizeof(*peterson) + sizeof(*value) + sizeof(*test) * n, PROT_READ|PROT_WRITE, MAP_ANON|MAP_SHARED, -1, 0)))
		return NULL;
	flag_turn = shared;
	peterson = shared + peterson_flag_turn_size(n);
	peterson_initial(peterson, n, flag_turn);

	value = shared + peterson_flag_turn_size(n) + sizeof(*peterson);
	*value = 0;
	test = shared + peterson_flag_turn_size(n) + sizeof(*peterson)  + sizeof(*value);

	if(!(process = malloc(sizeof(*process) * n)))
		return NULL;

	for(i = 0; i < n; i++)
	{
		process[i] = -1;
		test[i].id = i;
		test[i].value = value;
	}
	return test;
}

void startroutine(int id, void* (*routine)(void*), void* arg)
{
	process[id] = fork();
	if(0 == process[id]) /* child */
	{
		routine(arg);
		exit(0);
	}
	else
	if(0 > process[id])
		printf("startroutine failed\n");
}

void waitroutine(int id)
{
	waitpid(process[id], NULL, 0);
}

void lock(int i)
{
	peterson_lock(peterson, i);
}

void unlock(int i)
{
	peterson_unlock(peterson, i);
}


text:
/*
	WindowLog.cpp
	(c)2000 Palestar Inc, Richard Lyle
*/

#include "Debug/Assert.h"
#include "Interface/GameDocument.h"
#include "Interface/WindowLog.h"

//----------------------------------------------------------------------------

IMPLEMENT_FACTORY( WindowLog, WindowText );
REGISTER_FACTORY_KEY( WindowLog, 4240986808537713705 );

WindowLog::WindowLog() : m_LastChatCount( 0 )
{}

const int CHAT_BUFFER_SIZE = 4096;
const int MAX_MESSAGES = 256;

void WindowLog::onUpdate( float t )
{
	WindowText::onUpdate( t );

	GameClient * pClient = ((GameDocument *)document())->client();
	ASSERT( pClient );

	if ( pClient->chatCount() != m_LastChatCount )
	{
		if ( pClient->chatCount() < m_LastChatCount )
			m_LastChatCount = 0;
		m_LastChatCount = Max( pClient->chatCount() - MAX_MESSAGES, m_LastChatCount );

		// append messages to chat log
		CharString log = text();
		for(;m_LastChatCount<pClient->chatCount();m_LastChatCount++)
		{
			log += pClient->chat( m_LastChatCount );
			log += "\n";
		}

		// keep the log under a managable length
		int length = log.length();
		while( length > CHAT_BUFFER_SIZE )
		{
			log.right( log.length() - (log.find( '\n' ) + 1) );
			length = log.length();
		}
		setText( log );
	}

	// scroll the parent frame to the last line of text
	NodeWindow * pParent = WidgetCast<NodeWindow>( parent() );
	if ( pParent != NULL && pParent->visible() )
	{
		// display the last line of text
		if ( (pParent->flags() & NodeWindow::SCROLLING) == 0 )
		{
			SizeInt content = pParent->contentSize();
			SizeInt visible = pParent->window().size();
			if ( content.height > visible.height )
				pParent->setOffset( PointInt( 0, content.height - visible.height) );
		}
	}
}

//----------------------------------------------------------------------------
//EOF


text:
package org.elasticsearch.xpack.watcher.notification.email.attachment;

import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.xpack.watcher.common.http.HttpProxy;
import org.elasticsearch.xpack.watcher.common.http.BasicAuth;

import java.io.IOException;
import java.util.Objects;

public class ReportingAttachment implements EmailAttachmentParser.EmailAttachment {

    static final ParseField INLINE = new ParseField("inline");
    static final ParseField AUTH = new ParseField("auth");
    static final ParseField PROXY = new ParseField("proxy");
    static final ParseField INTERVAL = new ParseField("interval");
    static final ParseField RETRIES = new ParseField("retries");
    static final ParseField URL = new ParseField("url");

    private final boolean inline;
    private final String id;
    private final BasicAuth auth;
    private final String url;
    private final TimeValue interval;
    private final Integer retries;
    private final HttpProxy proxy;

    ReportingAttachment(String id, String url, boolean inline, @Nullable TimeValue interval, @Nullable Integer retries,
                        @Nullable BasicAuth auth, @Nullable HttpProxy proxy) {
        this.id = id;
        this.url = url;
        this.retries = retries;
        this.inline = inline;
        this.auth = auth;
        this.interval = interval;
        this.proxy = proxy;
        if (retries != null && retries < 0) {
            throw new IllegalArgumentException("Retries for attachment must be >= 0");
        }
    }

    @Override
    public String type() {
        return ReportingAttachmentParser.TYPE;
    }

    @Override
    public String id() {
        return id;
    }

    @Override
    public boolean inline() {
        return inline;
    }

    public BasicAuth auth() {
        return auth;
    }

    public String url() {
        return url;
    }

    public TimeValue interval() {
        return interval;
    }

    public Integer retries() {
        return retries;
    }

    public HttpProxy proxy() {
        return proxy;
    }

    @Override
    public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
        builder.startObject(id).startObject(ReportingAttachmentParser.TYPE)
                .field(URL.getPreferredName(), url);

        if (retries != null) {
            builder.field(RETRIES.getPreferredName(), retries);
        }

        if (interval != null) {
            builder.field(INTERVAL.getPreferredName(), interval);
        }

        if (inline) {
            builder.field(INLINE.getPreferredName(), inline);
        }

        if (auth != null) {
            builder.startObject(AUTH.getPreferredName());
            builder.field(BasicAuth.TYPE, auth, params);
            builder.endObject();
        }

        if (proxy != null) {
            proxy.toXContent(builder, params);
        }

        return builder.endObject().endObject();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        ReportingAttachment otherAttachment = (ReportingAttachment) o;
        return Objects.equals(id, otherAttachment.id) && Objects.equals(url, otherAttachment.url) &&
               Objects.equals(interval, otherAttachment.interval) && Objects.equals(inline, otherAttachment.inline) &&
               Objects.equals(retries, otherAttachment.retries) && Objects.equals(auth, otherAttachment.auth) &&
               Objects.equals(proxy, otherAttachment.proxy);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, url, interval, inline, retries, auth, proxy);
    }
}


text:
#include "precompiled.h"
#include "EventInstancer.h"

#include "../../../Include/Rocket/Core/Python/ConverterScriptObject.h"

#include "../../../Include/Rocket/Core/Factory.h"

#include "EventWrapper.h"
#include "EventInterface.h"
#include "EventListenerInstancer.h"

namespace Rocket {
namespace Core {
namespace Python {

static PyObject* py_event = NULL;

void EventInterface::InitialisePythonInterface()
{
	// Define the event.
	py_event = python::class_< Event, EventWrapper, boost::noncopyable >("event", python::init< const char*, Rocket::Core::Dictionary&, bool >())
		.add_property("type", python::make_function( &Event::GetType, python::return_value_policy< python::return_by_value >()))
		.add_property("target_element", python::make_function(&Event::GetTargetElement, python::return_value_policy< python::return_by_value >()))
		.add_property("current_element", python::make_function(&Event::GetCurrentElement, python::return_value_policy< python::return_by_value >()))
		.add_property("parameters", python::make_function(&EventInterface::GetParameters, python::return_value_policy< python::return_by_value >()))
		.def("StopPropagation", &Event::StopPropagation)
		.ptr();

	Rocket::Core::Python::ConverterScriptObject< Event >();
}

void EventInterface::InitialiseRocketInterface()
{
	// Redefine the event instancer.
	Factory::RegisterEventInstancer(new EventInstancer(py_event))->RemoveReference();
	Factory::RegisterEventListenerInstancer(new EventListenerInstancer())->RemoveReference();
}

const Rocket::Core::Dictionary& EventInterface::GetParameters(EventWrapper* self)
{
	return *self->GetParameters();
}

}
}
}


text:
<component name="libraryTable">
  <library name="org.apache.maven:maven-resolver-provider" type="repository">
    <properties maven-id="org.apache.maven:maven-resolver-provider:3.6.1">
      <exclude>
        <dependency maven-id="org.slf4j:slf4j-api" />
        <dependency maven-id="javax.inject:javax.inject" />
        <dependency maven-id="org.apache.commons:commons-lang3" />
      </exclude>
    </properties>
    <CLASSES>
      <root url="jar://$MAVEN_REPOSITORY$/org/apache/maven/maven-resolver-provider/3.6.1/maven-resolver-provider-3.6.1.jar!/" />
      <root url="jar://$MAVEN_REPOSITORY$/org/apache/maven/maven-model/3.6.1/maven-model-3.6.1.jar!/" />
      <root url="jar://$MAVEN_REPOSITORY$/org/apache/maven/maven-model-builder/3.6.1/maven-model-builder-3.6.1.jar!/" />
      <root url="jar://$MAVEN_REPOSITORY$/org/codehaus/plexus/plexus-interpolation/1.25/plexus-interpolation-1.25.jar!/" />
      <root url="jar://$MAVEN_REPOSITORY$/org/codehaus/plexus/plexus-component-annotations/1.7.1/plexus-component-annotations-1.7.1.jar!/" />
      <root url="jar://$MAVEN_REPOSITORY$/org/apache/maven/maven-artifact/3.6.1/maven-artifact-3.6.1.jar!/" />
      <root url="jar://$MAVEN_REPOSITORY$/org/apache/maven/maven-builder-support/3.6.1/maven-builder-support-3.6.1.jar!/" />
      <root url="jar://$MAVEN_REPOSITORY$/org/apache/maven/maven-repository-metadata/3.6.1/maven-repository-metadata-3.6.1.jar!/" />
      <root url="jar://$MAVEN_REPOSITORY$/org/apache/maven/resolver/maven-resolver-api/1.3.3/maven-resolver-api-1.3.3.jar!/" />
      <root url="jar://$MAVEN_REPOSITORY$/org/apache/maven/resolver/maven-resolver-spi/1.3.3/maven-resolver-spi-1.3.3.jar!/" />
      <root url="jar://$MAVEN_REPOSITORY$/org/apache/maven/resolver/maven-resolver-util/1.3.3/maven-resolver-util-1.3.3.jar!/" />
      <root url="jar://$MAVEN_REPOSITORY$/org/apache/maven/resolver/maven-resolver-impl/1.3.3/maven-resolver-impl-1.3.3.jar!/" />
      <root url="jar://$MAVEN_REPOSITORY$/org/codehaus/plexus/plexus-utils/3.2.0/plexus-utils-3.2.0.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES />
  </library>
</component>


text:
<?php

class TicketHasArticle extends ActiveRecord\Model {
    static $table_name = 'ticket_has_articles';

    static $has_many = array(
    array("article_has_attachments"),
    );

    static $belongs_to = array(
     array('ticket'),
     array(
           	'client',
            'foreign_key' => 'email',
            'primary_key' => 'from',
        ),
  );

}


text:
sleep 20

# set the default audio output to be the headphone jack
amixer cset numid=3 1

# set audio volume to full
amixer sset PCM 100%

# play our tune
cat /home/pi/world-o-techno/world-o-techno.rb|sonic_pi


text:
require 'rails_helper'

describe "Comment" do
  let (:user) {User.create(name: "Bob Jones", username: "bob3000", email: "bob@gmail.com", password: "lbla;jfa;")}
  let (:game) {Game.create(name: "Monopoly", description: "Really fun", min_number_of_players: 2, max_number_of_players: 4, min_duration_of_game: 90, max_duration_of_game: 180)}
  let (:comment) {Comment.create(user: user, game: game, body: "fda;kslfja;lskfk;lasdfls;j;lak")}

  it "should belong to the appropriate user" do
    expect(comment.user).to eq(user)
  end

  it "should belong to the appropriate game" do
    expect(comment.game).to eq(game)
  end
end


text:
test_name 'structured custom facts can be cached' do
  tag 'risk:high'

  require 'facter/acceptance/user_fact_utils'
  extend Facter::Acceptance::UserFactUtils

  fact_file = 'custom_fact.rb'
  fact_1_name = 'key1.key2'
  fact_2_name = 'key1.key3'
  fact_1_value = 'test1'
  fact_2_value = 'test2'

  fact_content = <<-RUBY
  Facter.add('#{fact_1_name}') do
    setcode do
      "#{fact_1_value}"
    end
  end

  Facter.add('#{fact_2_name}') do
    setcode do
      "#{fact_2_value}"
    end
  end
  RUBY

  cached_file_content = <<~RUBY
    {
      "#{fact_1_name}": "#{fact_1_value}",
      "#{fact_2_name}": "#{fact_2_value}",
      "cache_format_version": 1
    }
  RUBY

  partial_file_content = <<~RUBY
    {
      "#{fact_2_name}": "#{fact_2_value}",
      "cache_format_version": 1
    }
  RUBY

  config_data = <<~HOCON
    facts : {
      ttls : [
          { "cached-custom-facts" : 3 days }
      ]
    }
    fact-groups : {
      cached-custom-facts : ["key1"],
    }

    global : {
      force-dot-resolution : true
    }
  HOCON

  agents.each do |agent|
    cache_folder = get_cached_facts_dir(agent['platform'], on(agent, facter('kernelmajversion')).stdout.chomp.to_f)

    config_dir = get_default_fact_dir(agent['platform'], on(agent, facter('kernelmajversion')).stdout.chomp.to_f)
    config_file = File.join(config_dir, 'facter.conf')
    agent.mkdir_p(config_dir)
    create_remote_file(agent, config_file, config_data)

    fact_dir = agent.tmpdir('custom_facts')
    fact_file = File.join(fact_dir, fact_file)
    create_remote_file(agent, fact_file, fact_content)

    teardown do
      agent.rm_rf(fact_dir)
      agent.rm_rf(config_dir)
      agent.rm_rf(cache_folder)
    end

    step 'creates the cache for part of the fact' do
      on(agent, facter("--custom-dir=#{fact_dir} key1.key3"))

      result = agent.file_exist?("#{cache_folder}/cached-custom-facts")
      assert_equal(true, result)

      cat_output = agent.cat("#{cache_folder}/cached-custom-facts")
      assert_match(
        partial_file_content.chomp,
        cat_output.strip,
        'Expected cached custom fact file to contain fact information'
      )
    end

    step 'creates the cache for full fact' do
      on(agent, facter("--custom-dir=#{fact_dir} key1"))

      result = agent.file_exist?("#{cache_folder}/cached-custom-facts")
      assert_equal(true, result)

      cat_output = agent.cat("#{cache_folder}/cached-custom-facts")
      assert_match(
        cached_file_content.chomp,
        cat_output.strip,
        'Expected cached custom fact file to contain fact information'
      )
    end

    step 'resolves the fact' do
      on(agent, facter("--custom-dir=#{fact_dir} key1 --json")) do |facter_output|
        assert_equal(
          {
            'key1' => {
              'key2' => fact_1_value,
              'key3' => fact_2_value
            }
          },
          JSON.parse(facter_output.stdout.chomp)
        )
      end
    end
  end
end


text:
external help file: Microsoft.Azure.Commands.Compute.dll-Help.xml
ms.assetid: 05E6155D-4F0E-406B-9312-77AD97EF66EE
online version:
schema: 2.0.0
---

# New-AzureRmVM

## SYNOPSIS
Creates a virtual machine.

## SYNTAX

```
New-AzureRmVM [-ResourceGroupName] <String> [-Location] <String> [-VM] <PSVirtualMachine>
 [-DisableBginfoExtension] [-Tags <Hashtable>] [-LicenseType <String>] [-WhatIf] [-Confirm]
 [<CommonParameters>]
```

## DESCRIPTION
The **New-AzureRmVM** cmdlet creates a virtual machine in Azure.
This cmdlet takes a virtual machine object as input.
Use the New-AzureRmVMConfig cmdlet to create a virtual machine object.
Other cmdlets can be used to configure the virtual machine, such as Set-AzureRmVMOperatingSystem, Set-AzureRmVMSourceImage, Add-AzureRmVMNetworkInterface, and Set-AzureRmVMOSDisk.

## EXAMPLES

### Example 1: Create a virtual machine
```
PS C:\># Variables
## Global
$ResourceGroupName = "ResourceGroup11"
$Location = "WestEurope"

## Storage
$StorageName = "GeneralStorage6cc"
$StorageType = "Standard_GRS"

## Network
$InterfaceName = "ServerInterface06"
$Subnet1Name = "Subnet1"
$VNetName = "VNet09"
$VNetAddressPrefix = "10.0.0.0/16"
$VNetSubnetAddressPrefix = "10.0.0.0/24"

## Compute
$VMName = "VirtualMachine12"
$ComputerName = "Server22"
$VMSize = "Standard_A2"
$OSDiskName = $VMName + "OSDisk"

# Resource Group
New-AzureRmResourceGroup -Name $ResourceGroupName -Location $Location

# Storage
$StorageAccount = New-AzureRmStorageAccount -ResourceGroupName $ResourceGroupName -Name $StorageName -Type $StorageType -Location $Location

# Network
$PIp = New-AzureRmPublicIpAddress -Name $InterfaceName -ResourceGroupName $ResourceGroupName -Location $Location -AllocationMethod Dynamic
$SubnetConfig = New-AzureRmVirtualNetworkSubnetConfig -Name $Subnet1Name -AddressPrefix $VNetSubnetAddressPrefix
$VNet = New-AzureRmVirtualNetwork -Name $VNetName -ResourceGroupName $ResourceGroupName -Location $Location -AddressPrefix $VNetAddressPrefix -Subnet $SubnetConfig
$Interface = New-AzureRmNetworkInterface -Name $InterfaceName -ResourceGroupName $ResourceGroupName -Location $Location -SubnetId $VNet.Subnets[0].Id -PublicIpAddressId $PIp.Id

# Compute

## Setup local VM object
$Credential = Get-Credential
$VirtualMachine = New-AzureRmVMConfig -VMName $VMName -VMSize $VMSize
$VirtualMachine = Set-AzureRmVMOperatingSystem -VM $VirtualMachine -Windows -ComputerName $ComputerName -Credential $Credential -ProvisionVMAgent -EnableAutoUpdate
$VirtualMachine = Set-AzureRmVMSourceImage -VM $VirtualMachine -PublisherName MicrosoftWindowsServer -Offer WindowsServer -Skus 2012-R2-Datacenter -Version "latest"
$VirtualMachine = Add-AzureRmVMNetworkInterface -VM $VirtualMachine -Id $Interface.Id
$OSDiskUri = $StorageAccount.PrimaryEndpoints.Blob.ToString() + "vhds/" + $OSDiskName + ".vhd"
$VirtualMachine = Set-AzureRmVMOSDisk -VM $VirtualMachine -Name $OSDiskName -VhdUri $OSDiskUri -CreateOption FromImage

## Create the VM in Azure
New-AzureRmVM -ResourceGroupName $ResourceGroupName -Location $Location -VM $VirtualMachine
```

This example script shows how to create a virtual machine.
This script uses several other cmdlets.

### Example 2: Create a virtual machine from a custom user image
```
PS C:\>## VM Account
# Credentials for Local Admin account you created in the sysprepped (generalized) vhd image
$VMLocalAdminUser = "LocalAdminUser"
$VMLocalAdminSecurePassword = ConvertTo-SecureString "Password" -AsPlainText -Force
## Azure Account
$LocationName = "westus"
$ResourceGroupName = "MyResourceGroup"
# This a Premium_LRS storage account.
# It is required in order to run a client VM with efficiency and high performance.
$StorageAccount = "Mydisk"

## VM
$OSDiskName = "MyClient"
$ComputerName = "MyClientVM"
$OSDiskUri = "https://Mydisk.blob.core.windows.net/disks/MyOSDisk.vhd"
$SourceImageUri = "https://Mydisk.blob.core.windows.net/vhds/MyOSImage.vhd"
$VMName = "MyVM"
# Modern hardware environment with fast disk, high IOPs performance.
# Required to run a client VM with efficiency and performance
$VMSize = "Standard_DS3"
$OSDiskCaching = "ReadWrite"
$OSCreateOption = "FromImage"

## Networking
$DNSNameLabel = "mydnsname" # mydnsname.westus.cloudapp.azure.com
$NetworkName = "MyNet"
$NICName = "MyNIC"
$PublicIPAddressName = "MyPIP"
$SubnetName = "MySubnet"
$SubnetAddressPrefix = "10.0.0.0/24"
$VnetAddressPrefix = "10.0.0.0/16"

$SingleSubnet = New-AzureRmVirtualNetworkSubnetConfig -Name $SubnetName -AddressPrefix $SubnetAddressPrefix
$Vnet = New-AzureRmVirtualNetwork -Name $NetworkName -ResourceGroupName $ResourceGroupName -Location $LocationName -AddressPrefix $VnetAddressPrefix -Subnet $SingleSubnet
$PIP = New-AzureRmPublicIpAddress -Name $PublicIPAddressName -DomainNameLabel $DNSNameLabel -ResourceGroupName $ResourceGroupName -Location $LocationName -AllocationMethod Dynamic
$NIC = New-AzureRmNetworkInterface -Name $NICName -ResourceGroupName $ResourceGroupName -Location $LocationName -SubnetId $Vnet.Subnets[0].Id -PublicIpAddressId $PIP.Id

$Crededntial = New-Object System.Management.Automation.PSCredential ($VMLocalAdminUser, $VMLocalAdminSecurePassword);

$VirtualMachine = New-AzureRmVMConfig -VMName $VMName -VMSize $VMSize
$VirtualMachine = Set-AzureRmVMOperatingSystem -VM $VirtualMachine -Windows -ComputerName $ComputerName -Credential $Credential -ProvisionVMAgent -EnableAutoUpdate
$VirtualMachine = Add-AzureRmVMNetworkInterface -VM $VirtualMachine -Id $NIC.Id
$VirtualMachine = Set-AzureRmVMOSDisk -VM $VirtualMachine -Name $OSDiskName -VhdUri $OSDiskUri -SourceImageUri $SourceImageUri -Caching $OSDiskCaching -CreateOption $OSCreateOption -Windows

New-AzureRmVM -ResourceGroupName $ResourceGroupName -Location $LocationName -VM $VirtualMachine -Verbose
```

This example takes an existing sys-prepped, generalized custom operating system image and attaches a data disk to it, provisions a new network, deploys the VHD, and runs it.

This script can be used for automatic provisioning because it uses the local virtual machine admin credentials inline instead of calling **Get-Credential** which requires user interaction.

This script assumes that you are already logged into your Azure account.
You can confirm your login status by using the **Get-AzureSubscription** cmdlet.

## PARAMETERS

### -DisableBginfoExtension
Indicates that this cmdlet does not install the **BG Info** extension on the virtual machine.

```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:

Required: False
Position: 4
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -LicenseType
Specifies a license type, which indicates that the image or disk for the virtual machine was licensed on-premises.
This value is used only for images that contain the Windows Server operating system.
The acceptable values for this parameter are:

- Windows_Client
- Windows_Server

This value cannot be updated.
If you specify this parameter for an update, the value must match the initial value for the virtual machine.

```yaml
Type: String
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -Location
Specifies a location for the virtual machine.

```yaml
Type: String
Parameter Sets: (All)
Aliases:

Required: True
Position: 2
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -ResourceGroupName
Specifies the name of a resource group.

```yaml
Type: String
Parameter Sets: (All)
Aliases:

Required: True
Position: 1
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -Tags
Specifies that resources and resource groups can be tagged with a set of name-value pairs.
Adding tags to resources enables you to group resources together across resource groups and to create your own views.
Each resource or resource group can have a maximum of 15 tags.

```yaml
Type: Hashtable
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -VM
Specifies a local virtual machine to create.
To obtain a virtual machine object, use the New-AzureRmVMConfig cmdlet.
Other cmdlets can be used to configure the virtual machine, such as Set-AzureRmVMOperatingSystem, Set-AzureRmVMSourceImage, and Add-AzureRmVMNetworkInterface.

```yaml
Type: PSVirtualMachine
Parameter Sets: (All)
Aliases: VMProfile

Required: True
Position: 3
Default value: None
Accept pipeline input: True (ByPropertyName, ByValue)
Accept wildcard characters: False
```

### -Confirm
Prompts you for confirmation before running the cmdlet.

```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases: cf

Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```

### -WhatIf
Shows what would happen if the cmdlet runs.

The cmdlet is not run.

```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases: wi

Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```

### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216).

## INPUTS

## OUTPUTS

## NOTES

## RELATED LINKS

[Get-AzureRmVM](./Get-AzureRmVM.md)

[Remove-AzureRmVM](./Remove-AzureRmVM.md)

[Restart-AzureRmVM](./Restart-AzureRmVM.md)

[Start-AzureRmVM](./Start-AzureRmVM.md)

[Stop-AzureRmVM](./Stop-AzureRmVM.md)

[Update-AzureRmVM](./Update-AzureRmVM.md)

[Add-AzureRmVMDataDisk](./Add-AzureRmVMDataDisk.md)

[Add-AzureRmVMNetworkInterface](./Add-AzureRmVMNetworkInterface.md)

[New-AzureRmVMConfig](./New-AzureRmVMConfig.md)

[Set-AzureRmVMOperatingSystem](./Set-AzureRmVMOperatingSystem.md)

[Set-AzureRmVMSourceImage](./Set-AzureRmVMSourceImage.md)

[Set-AzureRmVMOSDisk](./Set-AzureRmVMOSDisk.md)


text:
namespace mscorlib
{
	namespace System
	{
		namespace Threading
		{

			//Public Methods
			void AsyncFlowControl::Undo()
			{
					Global::InvokeMethod("mscorlib", "System.Threading", "AsyncFlowControl", 0, NULL, "Undo", __native_object__, 0, NULL, NULL, NULL);
			}

			void AsyncFlowControl::Dispose()
			{
					Global::InvokeMethod("mscorlib", "System.Threading", "AsyncFlowControl", 0, NULL, "Dispose", __native_object__, 0, NULL, NULL, NULL);
			}

			mscorlib::System::Int32 AsyncFlowControl::GetHashCode()
			{
					MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Threading", "AsyncFlowControl", 0, NULL, "GetHashCode", __native_object__, 0, NULL, NULL, NULL);
					return *(mscorlib::System::Int32*)mono_object_unbox(__result__);
			}

			mscorlib::System::Boolean AsyncFlowControl::Equals(mscorlib::System::Object obj)
			{
					MonoType *__parameter_types__[1];
					void *__parameters__[1];
					__parameter_types__[0] = Global::GetType(typeid(obj).name());
					__parameters__[0] = (MonoObject*)obj;
					MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Threading", "AsyncFlowControl", 0, NULL, "Equals", __native_object__, 1, __parameter_types__, __parameters__, NULL);
					return *(mscorlib::System::Boolean*)mono_object_unbox(__result__);
			}

			mscorlib::System::Boolean AsyncFlowControl::Equals(mscorlib::System::Threading::AsyncFlowControl obj)
			{
					MonoType *__parameter_types__[1];
					void *__parameters__[1];
					__parameter_types__[0] = Global::GetType(typeid(obj).name());
					__parameters__[0] = (MonoObject*)obj;
					MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Threading", "AsyncFlowControl", 0, NULL, "Equals", __native_object__, 1, __parameter_types__, __parameters__, NULL);
					return *(mscorlib::System::Boolean*)mono_object_unbox(__result__);
			}

		}
	}
}


text:
using System.Threading.Tasks;

namespace HTMLinjectorServices
{
    /// <summary>
    /// Platform independent representation of a File
    /// </summary>
    public interface IFile
    {
        /// <summary>
        /// Gets the file name not including path
        /// </summary>
        /// <value>The file name</value>
        string Name { get; }

        /// <summary>
        /// The full file name including path
        /// </summary>
        /// <value>The file path</value>
        string Path { get; }

        /// <summary>
        /// Returns the contents of the file
        /// </summary>
        /// <returns>The text contained in the file</returns>
        Task<string> ReadAllTextAsync();
    }
}


text:
#ifndef MODULES_DREAMVIEW_BACKEND_HMI_HMI_WORKER_H_
#define MODULES_DREAMVIEW_BACKEND_HMI_HMI_WORKER_H_

#include <string>
#include <vector>

#include "boost/thread/locks.hpp"
#include "boost/thread/shared_mutex.hpp"

#include "modules/canbus/proto/chassis.pb.h"
#include "modules/common/macro.h"
#include "modules/dreamview/proto/hmi_config.pb.h"
#include "modules/dreamview/proto/hmi_status.pb.h"
#include "modules/monitor/proto/system_status.pb.h"

/**
 * @namespace apollo::dreamview
 * @brief apollo::dreamview
 */
namespace apollo {
namespace dreamview {

using ChangeModeHandler = std::function<void(const std::string&)>;
using ChangeMapHandler = std::function<void(const std::string&)>;
using ChangeVehicleHandler = std::function<void(const std::string&)>;

// Singleton worker which does the actual work of HMI actions.
class HMIWorker {
 public:
  // High level HMI action trigger.
  bool Trigger(const HMIAction action);

  // Run a command on current system mode.
  void RunModeCommand(const std::string& command_name);
  // Run a command on given module.
  int RunModuleCommand(const std::string& module, const std::string& command);
  // Run a command on given hardware.
  int RunHardwareCommand(const std::string& hardware,
                         const std::string& command);
  // Run a command on given tool.
  int RunToolCommand(const std::string& tool, const std::string& command);

  // Update system status.
  void UpdateSystemStatus(const apollo::monitor::SystemStatus& system_status);

  // Register event handlers.
  void RegisterChangeModeHandler(ChangeModeHandler handler) {
    change_mode_handlers_.emplace_back(handler);
  }
  void RegisterChangeMapHandler(ChangeMapHandler handler) {
    change_map_handlers_.emplace_back(handler);
  }
  void RegisterChangeVehicleHandler(ChangeVehicleHandler handler) {
    change_vehicle_handlers_.emplace_back(handler);
  }
  // Change current mode, map, vehicle and driving mode.
  void ChangeToMode(const std::string& mode_name);
  void ChangeToMap(const std::string& map_name);
  void ChangeToVehicle(const std::string& vehicle_name);
  static bool ChangeToDrivingMode(
      const apollo::canbus::Chassis::DrivingMode mode);

  // Submit a DriveEvent.
  static void SubmitDriveEvent(const uint64_t event_time_ms,
                               const std::string& event_msg,
                               const std::vector<std::string>& event_types);

  // Get current config and status.
  inline const HMIConfig& GetConfig() const { return config_; }
  const HMIStatus GetStatus() const;

  // HMIStatus is updated frequently by multiple threads, including web workers
  // and ROS message callback. Please apply proper read/write lock when
  // accessing it.
  inline boost::shared_mutex& GetStatusMutex() { return status_mutex_; }

 private:
  HMIConfig config_;
  HMIStatus status_;
  mutable boost::shared_mutex status_mutex_;

  std::vector<ChangeModeHandler> change_mode_handlers_;
  std::vector<ChangeMapHandler> change_map_handlers_;
  std::vector<ChangeVehicleHandler> change_vehicle_handlers_;

  DECLARE_SINGLETON(HMIWorker);
};

}  // namespace dreamview
}  // namespace apollo

#endif  // MODULES_DREAMVIEW_BACKEND_HMI_HMI_WORKER_H_


text:
'use strict'

const uniformResultsValidator = require('./uniform-results-validator')

async function uniformResultsExecutor (t = () => {}, parentScope = [], sharedState = {}) {
  const scope = [...parentScope, uniformResultsExecutor.name]
  const {jetta, config, errorCategory, m, ev, requestParams} = sharedState
  const rExpectedOK = requestParams.expectedOK
  const rState = requestParams.state
  const rURL = requestParams.url

  let cachedInputOptions
  let cachedInputURL
  let callCount = 0
  let rOptions = requestParams.options
  let resultsToReturn = null

  function wasCalledAsyncCheck (wasCalledAsync = true, localScope = []) {
    t.true(wasCalledAsync, m(localScope, `was called asyncronously`))
  }

  function mutatedCheck (url, options, cachedURL, cachedOptions, localScope = []) {
    let useOptions
    let useCachedOptions

    switch (typeof options) {
      case 'undefined':
        useOptions = undefined
        break
      case 'string':
        useOptions = options
        break
      default:
        if (options === null) {
          useOptions = null
        } else {
          useOptions = Object.assign({}, options, {cookieManager: null})
        }
    }

    switch (typeof cachedOptions) {
      case 'undefined':
        useCachedOptions = undefined
        break
      case 'string':
        useCachedOptions = cachedOptions
        break
      default:
        if (cachedOptions === null) {
          useCachedOptions = null
        } else {
          useCachedOptions = Object.assign({}, cachedOptions, {cookieManager: null})
        }
    }

    t.deepEqual(url, cachedURL, m(localScope, `request should not mutate given URLs`))
    t.deepEqual(useOptions, useCachedOptions, m(localScope, `request should not mutate given options`))
  }

  switch (typeof rOptions) {
    case 'undefined':
      cachedInputOptions = undefined
      break
    case 'string':
      cachedInputOptions = rOptions
      break
    default:
      if (rOptions === null) {
        cachedInputOptions = null
      } else {
        cachedInputOptions = Object.assign({}, rOptions)
      }
  }

  switch (typeof rURL) {
    case 'undefined':
      cachedInputURL = undefined
      break
    case 'string':
      cachedInputURL = rURL
      break
    default:
      if (rURL === null) {
        cachedInputURL = null
      } else {
        cachedInputURL = Object.assign({}, rURL)
      }
  }

  Object.freeze(cachedInputOptions)
  Object.freeze(cachedInputURL)

  if (rExpectedOK === true) {
    resultsToReturn = await new Promise((resolve, reject) => {
      let wasCalledAsync = false

      function okRequestResults (error, results) {
        wasCalledAsyncCheck(wasCalledAsync, scope)
        mutatedCheck(rURL, rOptions, cachedInputURL, cachedInputOptions, scope)

        callCount++

        t.equal(error, null, m(scope, `error should be \`null\``))

        if (error !== null) {
          console.log('extended for debugging:')
          console.dir(error, {depth: 10})
        }

        if (callCount > 1) {
          t.fail(m(scope, `called more than once`))
        }

        resolve(results)
      }

      if (rOptions === undefined) {
        jetta.request(rURL, okRequestResults, rState)
      } else {
        jetta.request(rURL, rOptions, okRequestResults, rState)
      }

      wasCalledAsync = true
    })
  } else {
    for (let i = 0, len = config.currentAvailableLangs.length; i < len; i++) {
      const preferredErrorLanguage = config.currentAvailableLangs[i]
      const nestedScope = [...scope, `request error check`, preferredErrorLanguage]
      let optionsWasNotValidObject = false

      if (typeof rOptions !== 'object' || rOptions === null) {
        optionsWasNotValidObject = true

        rOptions = {}
        cachedInputOptions = {}
      }

      rOptions.preferredErrorLanguage = preferredErrorLanguage
      cachedInputOptions = Object.assign({}, cachedInputOptions, {preferredErrorLanguage})

      Object.freeze(cachedInputOptions)

      resultsToReturn = await new Promise((resolve, reject) => {
        let wasCalledAsync = false

        jetta.request(rURL, rOptions, (error, results) => {
          wasCalledAsyncCheck(wasCalledAsync, nestedScope)
          mutatedCheck(rURL, rOptions, cachedInputURL, cachedInputOptions, nestedScope)

          callCount++

          if (error === null || results.error === null) {
            t.fail(m(nestedScope, `expected error response`))
          } else if (callCount === 1) {
            ev({t, scope: nestedScope, e: error, errorCategory, preferredErrorLanguage})
          } else {
            t.fail(m(nestedScope, `called more than once`))
          }

          resolve(results)
        }, rState)

        wasCalledAsync = true
      })

      if (optionsWasNotValidObject === true) {
        rOptions = null
      }
    }
  }

  uniformResultsValidator(t, scope, Object.assign({}, sharedState, {results: resultsToReturn}))

  return resultsToReturn
}

module.exports = uniformResultsExecutor


text:
#include "riptide_autonomy/tslam.h"

#define PI 3.141592653

// Slope and y-int for Maelstrom x-accel to x-velocity
#define A2V_SLOPE 0.5 //0.2546
#define A2V_INT .1090

/* TSlam - Order of Execution:
1. Read map, calculate distances and angles.
2. Set attitude cmd (only enable roll/pitch).
3. Check pitch (roll is probably fine).
4. Set search depth. Check search depth.
5. Set search heading. Check heading.
6. Move forward (initiate timer in case).
7. Abort (brake if required).
*/

// TODO: Configure TSlam to take us back to a previous location or to a different part of the path
// TODO: Add move forward, backwards, left, and right functionality for moving around other objects

TSlam::TSlam(BeAutonomous *master)
{
  this->master = master;

  if (master->competition_id == rc::COMPETITION_SEMIS)
    task_map_file = rc::FILE_MAP_SEMIS;
  else
    task_map_file = rc::FILE_MAP_FINALS;

  task_map = YAML::LoadFile(task_map_file);
  ROS_INFO("TSlam: Loaded map");

  TSlam::Initialize();
  ROS_INFO("TSlam: Initialized");
}

void TSlam::Initialize()
{
  delta_x = 0;
  delta_y = 0;
  angle = 0;
  search_heading = 0;

  start_x = 0;
  start_y = 0;
  eta = 0;
  x_vel = 0;

  for (int i = 0; i < sizeof(active_subs) / sizeof(active_subs[0]); i++)
    active_subs[i]->shutdown();
}

void TSlam::ReadMap()
{
  if (current_x == 420)
  {
    current_x = task_map["task_map"]["dock_x"][quadrant].as<double>();
    current_y = task_map["task_map"]["dock_y"][quadrant].as<double>();
  }

  if (quadrant < 4)
  {
    start_x = task_map["task_map"]["map"][master->task_id]["start_x"][quadrant].as<double>();
    start_y = task_map["task_map"]["map"][master->task_id]["start_y"][quadrant].as<double>();

    end_x = task_map["task_map"]["map"][master->task_id]["end_x"][quadrant].as<double>();
    end_y = task_map["task_map"]["map"][master->task_id]["end_y"][quadrant].as<double>();

    if (master->run_single_task && master->task_order.size() == 1)
    {
      current_x = start_x + master->relative_current_x;
      current_y = start_y + master->relative_current_y;
    }
  }
  else
  {
    current_x = 420;
    current_y = 420;
    start_x = 420;
    start_y = 420;
  }

  // Verify current_x and current_y were not set to an arbitrarily large number
  if (abs(current_x) > 55)
  {
    current_x = 0;
    ROS_INFO("ERROR: Current X not initialized properly, exceeded limit. Setting to 0.");
  }
  if (abs(current_y) > 40)
  {
    current_y = 0;
    ROS_INFO("ERROR: Current Y not initialized properly, exceeded limit. Setting to 0.");
  }

  ROS_INFO("Next Task (%s) Start X: %f", master->task_name.c_str(), start_x);
  ROS_INFO("Next Task (%s) Start Y: %f", master->task_name.c_str(), start_y);
}

void TSlam::SetPos(double x, double y)
{
  current_x = x;
  current_y = y;
}

void TSlam::SetEndPos()
{
  current_x = end_x;
  current_y = end_y;
}

void TSlam::EndMission()
{
  current_x = 420;
  current_y = 420;
}

// Calculate eta for TSlam to bring vehicle to next task
void TSlam::CalcETA(double Ax, double dist)
{
  if (Ax >= 0.6 && Ax <= 1.25)
  { // Eqn only valid for Ax=[0.6, 1.25] m/s^2
    //x_vel = A2V_SLOPE * Ax + A2V_INT;
    eta = dist / x_vel;
  }
  else
    eta = 0;
}

// Keeps heading in the range determined by the IMU [180, -180]
double TSlam::KeepHeadingInRange(double input)
{
  if (input > 180)
    return (input - 360.0);
  else if (input < -180)
    return (input + 360.0);
  else
    return input;
}

void TSlam::Start()
{
  pitchValidator = new ErrorValidator(master->pitch_thresh, master->error_duration);
  yawValidator = new ErrorValidator(master->yaw_thresh, master->error_duration);
  depthValidator = new ErrorValidator(master->depth_thresh, master->error_duration);

  quadrant = master->quadrant;
  ROS_INFO("TSlam: Quadrant %i", quadrant);

  user_defined_y_axis_heading = task_map["task_map"]["user_defined_y_axis_heading"][quadrant].as<double>();
  x_vel = master->tslam_velocity;
  brake_duration = master->brake_duration;
  ROS_INFO("TSlam: Loaded a few variables from task_map");

  // Calculate heading to point towards next task
  TSlam::ReadMap();
  delta_x = start_x - current_x;
  delta_y = start_y - current_y;
  angle = atan2(delta_y, delta_x) * 180 / PI;
  double offset = angle - 90;
  search_heading = user_defined_y_axis_heading + offset; // Center about user_defined_y_axis_heading
  search_heading = TSlam::KeepHeadingInRange(search_heading);

  ROS_INFO("Cur X: %f", current_x);
  ROS_INFO("Cur Y: %f", current_y);
  ROS_INFO("TSlam: Quadrant search heading: %f", angle);
  ROS_INFO("TSlam: Global search heading: %f", search_heading);

  // Calculate distance and ETA
  distance = sqrt(delta_x * delta_x + delta_y * delta_y);
  TSlam::CalcETA(master->search_accel, distance);
  tslam_duration = 1 * eta;
  ROS_INFO("TSlam: Distance %f with eta of %f sec at %f m/s", distance, eta, x_vel);

  // Publish attitude command
  // TODO: either keep current heading or go to heading at same time so yaw is not disabled
  attitude_cmd.roll_active = true;
  attitude_cmd.pitch_active = true;
  attitude_cmd.yaw_active = false; // Rotate to heading once search depth is reached
  attitude_cmd.euler_rpy.x = 0;
  attitude_cmd.euler_rpy.y = 0;
  attitude_cmd.euler_rpy.z = search_heading;
  master->attitude_pub.publish(attitude_cmd);

  attitude_status_sub = master->nh.subscribe<riptide_msgs::ControlStatusAngular>("/status/controls/angular", 1, &TSlam::PitchAttitudeStatusCB, this);
  ROS_INFO("TSlam: Checking pitch error");
}

// Must first validate pitch so vehicle can submerge properly
void TSlam::PitchAttitudeStatusCB(const riptide_msgs::ControlStatusAngular::ConstPtr &status_msg)
{
  if (pitchValidator->Validate(status_msg->pitch.error))
  {
    pitchValidator->Reset();
    attitude_status_sub.shutdown();

    // Publish depth command
    depth_cmd.active = true;
    depth_cmd.depth = master->search_depth;
    master->depth_pub.publish(depth_cmd);
    depth_status_sub = master->nh.subscribe<riptide_msgs::ControlStatus>("/status/controls/depth", 1, &TSlam::DepthStatusCB, this);
    ROS_INFO("TSlam: Pitch good. Now checking depth.");
  }
}

void TSlam::DepthStatusCB(const riptide_msgs::ControlStatus::ConstPtr &status_msg)
{
  if (depthValidator->Validate(status_msg->error))
  {
    depthValidator->Reset();
    depth_status_sub.shutdown();

    attitude_cmd.yaw_active = true;
    master->attitude_pub.publish(attitude_cmd);
    attitude_status_sub = master->nh.subscribe<riptide_msgs::ControlStatusAngular>("/status/controls/angular", 1, &TSlam::YawAttitudeStatusCB, this);
    ROS_INFO("TSlam: Reached depth, now checking heading.");
  }
}

// Validate heading after depth is reached
void TSlam::YawAttitudeStatusCB(const riptide_msgs::ControlStatusAngular::ConstPtr &status_msg)
{
  if (yawValidator->Validate(status_msg->yaw.error))
  {
    yawValidator->Reset();
    attitude_status_sub.shutdown();
    master->StartTask(); // Start next task - will override accelerations if placed after
    ROS_INFO("TSlam: starting next task %i", master->task_id);

    // Drive forward
    std_msgs::Float64 msg;
    msg.data = master->search_accel;
    master->x_accel_pub.publish(msg);
    ROS_INFO("TSlam: Search accel: %f", master->search_accel);

    timer = master->nh.createTimer(ros::Duration(tslam_duration), &TSlam::AbortTSlamTimer, this, true);
    ROS_INFO("TSlam: Moving forward. Abort timer initiated. ETA: %f", tslam_duration);
  }
}

void TSlam::AbortTSlamTimer(const ros::TimerEvent &event)
{
  TSlam::Abort(true);
}

void TSlam::BrakeTimer(const ros::TimerEvent &event)
{
  std_msgs::Float64 msg;
  msg.data = 0;
  master->x_accel_pub.publish(msg);
  ROS_INFO("TSlam: Thruster brake applied");
}

// Shutdown all active subscribers
void TSlam::Abort(bool apply_brake)
{
  TSlam::Initialize();

  timer.stop();
  std_msgs::Float64 msg;
  if (apply_brake)
  {
    msg.data = -(master->search_accel);
    master->x_accel_pub.publish(msg);
    timer = master->nh.createTimer(ros::Duration(brake_duration), &TSlam::BrakeTimer, this, true);
    ROS_INFO("TSlam: Aborting. Braking now.");
  }
  else
  {
    msg.data = 0;
    master->x_accel_pub.publish(msg);
  }
}


text:
class Line
  attr_reader :number, :patch_position

  def initialize(number:, content:, patch_position:)
    @number = number
    @content = content
    @patch_position = patch_position
  end

  def changed?
    true
  end
end


text:
package org.bitcoins.node.constant

case object NodeConstants {
  val userAgent = "/bitcoin-s:1.9.7/"
}


text:
package de.cronn.jira.sync.service;

import java.net.URL;
import java.time.Instant;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

import de.cronn.jira.sync.config.JiraConnectionProperties;
import de.cronn.jira.sync.domain.JiraComment;
import de.cronn.jira.sync.domain.JiraComponent;
import de.cronn.jira.sync.domain.JiraField;
import de.cronn.jira.sync.domain.JiraFieldsUpdate;
import de.cronn.jira.sync.domain.JiraIssue;
import de.cronn.jira.sync.domain.JiraIssueUpdate;
import de.cronn.jira.sync.domain.JiraPriority;
import de.cronn.jira.sync.domain.JiraProject;
import de.cronn.jira.sync.domain.JiraRemoteLink;
import de.cronn.jira.sync.domain.JiraResolution;
import de.cronn.jira.sync.domain.JiraServerInfo;
import de.cronn.jira.sync.domain.JiraTransition;
import de.cronn.jira.sync.domain.JiraUser;
import de.cronn.jira.sync.domain.JiraVersion;

public interface JiraService extends AutoCloseable {

	String getUrl();

	void login(JiraConnectionProperties connectionProperties, boolean source);

	void logout();

	void evictAllCaches();

	@Override
	void close();

	JiraServerInfo getServerInfo();

	JiraUser getMyself();

	JiraUser getUserByName(String username);

	JiraIssue getIssueByKey(String key);

	JiraIssue getIssueByKeyWithChangelog(String issueKey);

	Map<String, Object> getAllowedValuesForCustomField(String projectKey, String customFieldId);

	JiraProject getProjectByKey(String projectKey);

	List<JiraProject> getProjects();

	List<JiraPriority> getPriorities();

	List<JiraResolution> getResolutions();

	List<JiraField> getFields();

	List<JiraVersion> getVersions(String projectKey);

	List<JiraComponent> getComponents(String projectKey);

	List<JiraIssue> getIssuesByFilterId(String filterId, Collection<String> customFields);

	List<JiraRemoteLink> getRemoteLinks(String issueKey, Instant ifModifiedSince);

	List<JiraTransition> getTransitions(String issueKey);

	void addRemoteLink(JiraIssue fromIssue, JiraIssue toIssue, JiraService toJiraService, URL remoteLinkIcon);

	JiraComment addComment(String issueKey, String commentText);

	void updateComment(String issueKey, String commentId, String commentText);

	JiraIssue createIssue(JiraIssue issue);

	default void updateIssue(String issueKey, Consumer<JiraFieldsUpdate> fieldsUpdateConsumer) {
		JiraIssueUpdate jiraIssueUpdate = new JiraIssueUpdate();
		fieldsUpdateConsumer.accept(jiraIssueUpdate.getOrCreateFields());
		updateIssue(issueKey, jiraIssueUpdate);
	}

	void updateIssue(String issueKey, JiraIssueUpdate issueUpdate);

	void transitionIssue(String issueKey, JiraIssueUpdate issueUpdate);

	JiraField findField(String fieldName);

	JiraField findFieldById(String id);

	boolean isSource();

}


text:
export interface MediaQueryResults {
  [key: string]: boolean;
}

export interface MediaQueryRule {
  id: string;
  maxWidth?: number;
  minWidth?: number;
  orientation?: string;
  type?: string;
}

export interface MediaQueryUpdate {
  mql: MediaQueryList;
  rule: MediaQueryRule;
}


text:
require "phantomjs"
require "mini_magick"
require "firaq/engine"
require "firaq/meh"

module Firaq
  def self.root
    File.dirname __dir__
  end
end


text:
import mimetypes
import os
import shutil
import sys
import tempfile
import uuid

from datetime import datetime, timedelta
from collections import namedtuple

import pygit2

from celery import current_task
from django_statsd.clients import statsd

from django.conf import settings
from django.db import connections
from django.utils import translation
from django.utils.functional import cached_property

import olympia.core.logger

from olympia import amo
from olympia.amo.utils import id_to_path
from olympia.versions.models import Version
from olympia.files.utils import extract_extension_to_dest, get_all_files

from .models import GitExtractionEntry

log = olympia.core.logger.getLogger('z.git_storage')

# A mixture of Blob and TreeEntry
TreeEntryWrapper = namedtuple('Entry', 'tree_entry, path, blob')

BRANCHES = {
    amo.CHANNEL_LISTED: 'listed',
    amo.CHANNEL_UNLISTED: 'unlisted',
}

# Constants from libgit2 includes/git2/diff.h
# while they're not in upstream pygit2 I added them here (cgrebs)
# We don't have all line constants here though since we don't
# really make use of them in the frontend.
GIT_DIFF_LINE_CONTEXT = ' '
GIT_DIFF_LINE_ADDITION = '+'
GIT_DIFF_LINE_DELETION = '-'
# Both files have no LF at end
GIT_DIFF_LINE_CONTEXT_EOFNL = '='
# Old has no LF at end, new does
GIT_DIFF_LINE_ADD_EOFNL = '>'
# Old has LF at end, new does not
GIT_DIFF_LINE_DEL_EOFNL = '<'

# This matches typing in addons-frontend
GIT_DIFF_LINE_MAPPING = {
    GIT_DIFF_LINE_CONTEXT: 'normal',
    GIT_DIFF_LINE_ADDITION: 'insert',
    GIT_DIFF_LINE_DELETION: 'delete',
    GIT_DIFF_LINE_CONTEXT_EOFNL: 'normal-eofnl',
    GIT_DIFF_LINE_ADD_EOFNL: 'insert-eofnl',
    GIT_DIFF_LINE_DEL_EOFNL: 'delete-eofnl',
}

# Prefix folder name we are using to store extracted add-on data to avoid any
# clashes, e.g with .git folders.
EXTRACTED_PREFIX = 'extracted'

# Rename and copy threshold, 50% is the default git threshold
SIMILARITY_THRESHOLD = 50

# Some official mimetypes belong to the `text` category, even though their
# names don't include `text/`.
MIMETYPE_CATEGORY_MAPPING = {
    'application/json': 'text',
    'application/xml': 'text',
}

# Some mimetypes need to be hanged to some other mimetypes.
MIMETYPE_COMPAT_MAPPING = {
    # See: https://github.com/mozilla/addons-server/issues/11382
    'image/svg': 'image/svg+xml',
    # See: https://github.com/mozilla/addons-server/issues/11383
    'image/x-ms-bmp': 'image/bmp',
    # See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types#textjavascript  # noqa
    'application/javascript': 'text/javascript',
}

class BrokenRefError(RuntimeError):
    pass

class MissingMasterBranchError(RuntimeError):
    pass

def get_mime_type_for_blob(tree_or_blob, name):
    """Returns the mimetype and type category for a git blob.

    The type category can be ``image``, ``directory``, ``text`` or ``binary``.
    """
    if tree_or_blob == pygit2.GIT_OBJ_TREE:
        return 'application/octet-stream', 'directory'

    (mimetype, _) = mimetypes.guess_type(name)
    # We use `text/plain` as default.
    mimetype = MIMETYPE_COMPAT_MAPPING.get(mimetype, mimetype or 'text/plain')
    known_type_cagegories = ('image', 'text')
    default_type_category = 'binary'
    # If mimetype has an explicit category, use it.
    type_category = (
        MIMETYPE_CATEGORY_MAPPING.get(mimetype, mimetype.split('/')[0])
        if mimetype
        else default_type_category
    )

    return (
        mimetype,
        default_type_category
        if type_category not in known_type_cagegories
        else type_category,
    )

class TemporaryWorktree:
    def __init__(self, repository):
        self.git_repository = repository
        self.name = uuid.uuid4().hex
        self.temp_directory = tempfile.mkdtemp(dir=settings.TMP_PATH)
        self.path = os.path.join(self.temp_directory, self.name)
        self.extraction_target_path = os.path.join(self.path, EXTRACTED_PREFIX)
        self.obj = None
        self.repo = None

    def __enter__(self):
        self.obj = self.git_repository.add_worktree(self.name, self.path)
        self.repo = pygit2.Repository(self.obj.path)

        # Clean the workdir (of the newly created worktree)
        for entry in self.repo[self.repo.head.target].tree:
            path = os.path.join(self.path, entry.name)

            if os.path.isfile(path):
                os.unlink(path)
            else:
                shutil.rmtree(path)

        os.makedirs(self.extraction_target_path)

        return self

    def __exit__(self, type, value, traceback):
        # Remove temp directory
        shutil.rmtree(self.temp_directory)

        # Prune temp worktree
        if self.obj is not None:
            self.obj.prune(True)

        # Remove worktree ref in upstream repository
        self.git_repository.lookup_branch(self.name).delete()

class AddonGitRepository:

    GIT_DESCRIPTION = '.git/description'

    def __init__(self, addon_or_id, package_type='addon'):
        from olympia.addons.models import Addon

        assert package_type in ('addon',)

        # Always enforce the search path being set to our ROOT
        # setting. This is sad, libgit tries to fetch the global git
        # config file (~/.gitconfig) and falls over permission errors while
        # doing so in our web-environment.
        # We are setting this here to avoid creating a unnecessary global
        # state but since this is overwriting a global value in pygit2 it
        # affects all pygit2 calls.

        # https://github.com/libgit2/pygit2/issues/339
        # https://github.com/libgit2/libgit2/issues/2122
        git_home = settings.ROOT
        pygit2.option(
            pygit2.GIT_OPT_SET_SEARCH_PATH, pygit2.GIT_CONFIG_LEVEL_GLOBAL, git_home
        )

        # This will cause .keep file existence checks to be skipped when
        # accessing packfiles, which can help performance with remote
        # filesystems.
        # See: https://github.com/mozilla/addons-server/issues/13019
        pygit2.option(pygit2.GIT_OPT_DISABLE_PACK_KEEP_FILE_CHECKS, True)

        # Enable calling fsync() for various operations touching .git
        pygit2.option(pygit2.GIT_OPT_ENABLE_FSYNC_GITDIR, True)

        self.addon_id = (
            addon_or_id.pk if isinstance(addon_or_id, Addon) else addon_or_id
        )

        self.git_repository_path = os.path.join(
            settings.GIT_FILE_STORAGE_PATH,
            id_to_path(self.addon_id, breadth=2),
            package_type,
        )

    @property
    def is_extracted(self):
        return os.path.exists(self.git_repository_path)

    @property
    def is_recent(self):
        git_description_path = os.path.join(
            self.git_repository_path, self.GIT_DESCRIPTION
        )
        if not self.is_extracted or not os.path.exists(git_description_path):
            return False
        # A git repository is recent when it was created less than 1 hour ago.
        an_hour_ago = datetime.utcnow() - timedelta(hours=1)
        mtime = datetime.utcfromtimestamp(
            os.path.getmtime(
                # There is no way to get the creation time of a file/folder on
                # most UNIX systems, so we use a file that is created by
                # default but never modified (GIT_DESCRIPTION) to determine
                # whether a git repository is recent or not.
                git_description_path
            )
        )
        return mtime > an_hour_ago

    @cached_property
    def git_repository(self):
        if not self.is_extracted:
            os.makedirs(self.git_repository_path)
            git_repository = pygit2.init_repository(
                path=self.git_repository_path, bare=False
            )
            # Write first commit to 'master' to act as HEAD
            tree = git_repository.TreeBuilder().write()
            git_repository.create_commit(
                'HEAD',  # ref
                self.get_author(),  # author, using addons-robot
                self.get_author(),  # commiter, using addons-robot
                'Initializing repository',  # message
                tree,  # tree
                [],
            )  # parents

            log.info('Initialized git repository "%s"', self.git_repository_path)
        else:
            git_repository = pygit2.Repository(self.git_repository_path)

            # We have to verify that the 'master' branch exists because we
            # might have mis-initialized repositories in the past.
            # See: https://github.com/mozilla/addons-server/issues/14127
            try:
                master_ref = 'refs/heads/master'
                git_repository.lookup_reference(master_ref)
            except KeyError:
                message = f'Reference "{master_ref}" not found'
                log.exception(message)
                raise MissingMasterBranchError(message)

        return git_repository

    def delete(self):
        if not self.is_extracted:
            log.error('called delete() on a non-extracted git repository')
            return
        # Reset the git hash of each version of the add-on related to this git
        # repository.
        Version.unfiltered.filter(addon_id=self.addon_id).update(git_hash='')
        shutil.rmtree(self.git_repository_path)

    @classmethod
    def extract_and_commit_from_version(cls, version, author=None, note=None):
        """Extract the XPI from `version` and comit it.

        This is doing the following:

        * Create a temporary `git worktree`_
        * Remove all files in that worktree
        * Extract the xpi behind `version` into the worktree
        * Commit all files

        Kinda like doing::

            $ workdir_name=$(uuid)
            $ mkdir /tmp/$workdir_name
            $ git worktree add /tmp/$workdir_name
            Preparing worktree (new branch 'af4172e4-d8c7…')
            HEAD is now at 8c5223e Initial commit

            $ git worktree list
            /tmp/addon-repository                      8c5223e [master]
            /tmp/af4172e4-d8c7-4486-a5f2-316458da91ff  8c5223e [af4172e4-d8c7…]

            $ unzip dingrafowl-falcockalo-lockapionk.zip -d /tmp/$workdir_name
            Archive:  dingrafowl-falcockalo-lockapionk.zip
             extracting: /tmp/af4172e4-d8c7…/manifest.json

            $ pushd /tmp/$workdir_name
            /tmp/af4172e4-d8c7-4486-a5f2-316458da91ff /tmp/addon-repository

            $ git status
            On branch af4172e4-d8c7-4486-a5f2-316458da91ff
            Untracked files:
              (use "git add <file>..." to include in what will be committed)

                    manifest.json

            $ git add *
            $ git commit -a -m "Creating new version"
            [af4172e4-d8c7-4486-a5f2-316458da91ff c4285f8] Creating new version
            …
            $ cd addon-repository
            $ git checkout -b listed
            Switched to a new branch 'listed'

            # We don't technically do a full cherry-pick but it's close enough
            # and does almost what we do. We are technically commiting
            # directly on top of the branch as if we checked out the branch
            # in the worktree (via -b) but pygit doesn't properly support that
            # so we "simply" set the parents correctly.
            $ git cherry-pick c4285f8
            [listed a4d0f63] Creating new version…

        This ignores the fact that there may be a race-condition of two
        versions being created at the same time. Since all relevant file based
        work is done in a temporary worktree there won't be any conflicts and
        usually the last upload simply wins the race and we're setting the
        HEAD of the branch (listed/unlisted) to that specific commit.

        .. _`git worktree`: https://git-scm.com/docs/git-worktree
        """
        current_language = translation.get_language()

        try:
            # Make sure we're always using the en-US locale by default
            # to have unified commit messages and avoid any __str__
            # to give us wrong results
            translation.activate('en-US')

            repo = cls(version.addon.id, package_type='addon')
            branch = repo.find_or_create_branch(BRANCHES[version.channel])
            note = f' ({note})' if note else ''

            commit = repo._commit_through_worktree(
                file_obj=version.file,
                message=(
                    'Create new version {version} ({version_id}) for '
                    '{addon} from {file_obj}{note}'.format(
                        version=repr(version),
                        version_id=version.id,
                        addon=repr(version.addon),
                        file_obj=repr(version.file),
                        note=note,
                    )
                ),
                author=author,
                branch=branch,
            )

            if (
                current_task
                and current_task.request.id is not None
                and not current_task.request.is_eager
            ):
                # Extraction might have taken a while, and our connection might
                # be gone and we haven't realized it. Django cleans up
                # connections after CONN_MAX_AGE but only during the
                # request/response cycle, so if we're inside a task let's do it
                # ourselves before using the database again - it will
                # automatically reconnect if needed (use 'default' since we
                # want the primary db where writes go).
                connections['default'].close_if_unusable_or_obsolete()

            # Set the latest git hash on the related version.
            version.update(git_hash=commit.hex)
        finally:
            translation.activate(current_language)
        return repo

    def get_author(self, user=None):
        if user is not None:
            author_name = f'User {user.id}'
            author_email = user.email
        else:
            author_name = 'Mozilla Add-ons Robot'
            author_email = 'addons-dev-automation+github@mozilla.com'
        return pygit2.Signature(name=author_name, email=author_email)

    def find_or_create_branch(self, name):
        """Lookup or create the branch named `name`"""
        try:
            branch = self.git_repository.branches.get(name)
        except pygit2.GitError:
            message = f'Reference for branch "{name}" is broken'
            log.exception(message)
            raise BrokenRefError(message)

        if branch is None:
            branch = self.git_repository.create_branch(
                name, self.git_repository.head.peel()
            )

        return branch

    def _commit_through_worktree(self, file_obj, message, author, branch):
        """
        Create a temporary worktree that we can use to unpack the extension
        without disturbing the current git workdir since it creates a new
        temporary directory where we extract to.
        """
        with TemporaryWorktree(self.git_repository) as worktree:
            if file_obj:
                # Now extract the extension to the workdir
                extract_extension_to_dest(
                    source=file_obj.file.path,
                    dest=worktree.extraction_target_path,
                    force_fsync=True,
                )

            # Stage changes, `TemporaryWorktree` always cleans the whole
            # directory so we can simply add all changes and have the correct
            # state.

            # Fetch all files and strip the absolute path but keep the
            # `extracted/` prefix
            files = get_all_files(worktree.extraction_target_path, worktree.path, '')

            # Make sure the index is up to date
            worktree.repo.index.read()

            # For security reasons git doesn't allow adding .git subdirectories
            # anywhere in the repository. So we're going to rename them and add
            # a random postfix.
            # In order to disable the effect of the special git config files,
            # we also have to postfix them.
            files_to_rename = (
                '.git',
                '.gitattributes',
                '.gitconfig',
                '.gitignore',
                '.gitmodules',
            )
            # Sort files by path length to rename the deepest files first.
            files.sort(key=len, reverse=True)
            for filename in files:
                if os.path.basename(filename) in files_to_rename:
                    renamed = f'{filename}.{uuid.uuid4().hex[:8]}'
                    shutil.move(
                        os.path.join(worktree.path, filename),
                        os.path.join(worktree.path, renamed),
                    )

            # Add all changes to the index (git add --all ...)
            worktree.repo.index.add_all()
            worktree.repo.index.write()

            tree = worktree.repo.index.write_tree()

            # Now create an commit directly on top of the respective branch
            oid = worktree.repo.create_commit(
                None,
                # author, using the actual uploading user if possible.
                self.get_author(author),
                # committer, using addons-robot because that's the user
                # actually doing the commit.
                self.get_author(),
                message,
                tree,
                # Set the current branch HEAD as the parent of this commit
                # so that it'll go straight into the branches commit log
                #
                # We use `lookup_reference` to fetch the most up-to-date
                # reference to the branch in order to avoid an error described
                # in: https://github.com/mozilla/addons-server/issues/13932
                [self.git_repository.lookup_reference(branch.name).target],
            )

            # Fetch the commit object
            commit = worktree.repo.get(oid)

            # And set the commit we just created as HEAD of the relevant
            # branch, and updates the reflog. This does not require any
            # merges.
            #
            # We use `lookup_reference` to fetch the most up-to-date reference
            # to the branch in order to avoid an error described in:
            # https://github.com/mozilla/addons-server/issues/13932
            self.git_repository.lookup_reference(branch.name).set_target(commit.hex)

        return commit

    def get_root_tree(self, commit):
        """Return the root tree object.

        This doesn't contain the ``EXTRACTED_PREFIX`` prefix folder.
        """
        # When `commit` is a commit hash, e.g passed to us through the API
        # serializers we have to fetch the actual commit object to proceed.
        if isinstance(commit, str):
            commit = self.git_repository.revparse_single(commit)

        return self.git_repository[commit.tree[EXTRACTED_PREFIX].oid]

    def iter_tree(self, tree):
        """Recursively iterate through a tree.
        This includes the directories.
        """
        for tree_entry in tree:
            tree_or_blob = self.git_repository[tree_entry.oid]

            if isinstance(tree_or_blob, pygit2.Tree):
                yield TreeEntryWrapper(
                    blob=None, tree_entry=tree_entry, path=tree_entry.name
                )
                for child in self.iter_tree(tree_or_blob):
                    yield TreeEntryWrapper(
                        blob=child.blob,
                        tree_entry=child.tree_entry,
                        path=os.path.join(tree_entry.name, child.path),
                    )
            else:
                yield TreeEntryWrapper(
                    blob=tree_or_blob, tree_entry=tree_entry, path=tree_entry.name
                )

    def get_raw_diff(self, commit, parent=None, include_unmodified=False):
        """Return the raw diff object.

        This is cached as we'll be calling it multiple times, e.g
        once to render the actual diff and again to fetch specific
        status information (added, removed etc) in a later step.
        """
        diff_cache = getattr(self, '_diff_cache', {})

        flags = pygit2.GIT_DIFF_NORMAL | pygit2.GIT_DIFF_IGNORE_WHITESPACE_CHANGE

        if include_unmodified:
            flags |= pygit2.GIT_DIFF_INCLUDE_UNMODIFIED

        try:
            return diff_cache[(commit, parent, include_unmodified)]
        except KeyError:
            if parent is None:
                retval = self.get_root_tree(commit).diff_to_tree(
                    # We always show the whole file by default
                    context_lines=sys.maxsize,
                    interhunk_lines=0,
                    flags=flags,
                    swap=True,
                )
            else:
                retval = self.git_repository.diff(
                    self.get_root_tree(parent),
                    self.get_root_tree(commit),
                    # We always show the whole file by default
                    context_lines=sys.maxsize,
                    flags=flags,
                    interhunk_lines=0,
                )

            diff_cache[(commit, parent, include_unmodified)] = retval
            self._diff_cache = diff_cache

        return retval

    def get_diff(self, commit, parent=None, pathspec=None):
        """Get a diff from `parent` to `commit`.

        If `parent` is not given we assume it's the first commit and handle
        it accordingly.

        :param pathspec: If a list of files is given we only retrieve a list
                         for them.
        """
        diff = self.get_raw_diff(
            commit, parent=parent, include_unmodified=pathspec is not None
        )

        changes = []

        for patch in diff:
            # Support for this hasn't been implemented upstream yet, we'll
            # work on this upstream if needed but for now just selecting
            # files based on `pathspec` works for us.
            if pathspec and patch.delta.old_file.path not in pathspec:
                continue

            if parent is None:
                changes.append(self._render_patch(patch, commit, commit, pathspec))
            else:
                changes.append(self._render_patch(patch, commit, parent, pathspec))
        return changes

    def get_deltas(self, commit, parent, pathspec=None):
        """Only fetch deltas from `parent` to `commit`.

        This method specifically does not render any textual changes
        but fetches as few details as possible to use a different
        `pygit2` API to retrieve changes and to improve performance
        significantly.

        The entries returned are fairly similar to what `get_diff`
        returns but don't include `hunks`, `lines_deleted` / `lines_added`
        as well as `new_ending_new_line` and `old_ending_new_line`

        We also don't expose `size` and `is_binary` as it's unreliable since
        the `deltas` iterator tries to not examine the files content if
        possible - so they might have wrong values.
        """
        diff = self.get_raw_diff(
            commit, parent=parent, include_unmodified=pathspec is not None
        )

        deltas = []

        for delta in diff.deltas:
            if pathspec and delta.old_file.path not in pathspec:
                continue

            deltas.append(
                {
                    'path': delta.new_file.path,
                    'mode': delta.status_char(),
                    'old_path': delta.old_file.path,
                    'parent': commit if parent is None else parent,
                    'hash': commit,
                }
            )

        return deltas

    def _render_patch(self, patch, commit, parent, pathspec=None):
        """
        This will be moved to a proper drf serializer in the future
        but until the format isn't set we'll keep it like that to simplify
        experimentation.
        """
        old_ending_new_line = True
        new_ending_new_line = True

        hunks = []

        for hunk in patch.hunks:
            changes = []

            for line in hunk.lines:
                # Properly set line ending changes. We can do it directly
                # in the for-loop as line-ending changes should always be
                # present at the very end of a file so there's no risk of
                # these values being overwritten.
                origin = line.origin

                if origin == GIT_DIFF_LINE_CONTEXT_EOFNL:
                    old_ending_new_line = new_ending_new_line = False
                elif origin == GIT_DIFF_LINE_ADD_EOFNL:
                    old_ending_new_line = False
                elif origin == GIT_DIFF_LINE_DEL_EOFNL:
                    new_ending_new_line = False

                changes.append(
                    {
                        'content': line.content.rstrip('\r\n'),
                        'type': GIT_DIFF_LINE_MAPPING[origin],
                        # Can be `-1` for additions
                        'old_line_number': line.old_lineno,
                        'new_line_number': line.new_lineno,
                    }
                )

            hunks.append(
                {
                    'header': hunk.header.rstrip('\r\n'),
                    'old_start': hunk.old_start,
                    'new_start': hunk.new_start,
                    'old_lines': hunk.old_lines,
                    'new_lines': hunk.new_lines,
                    'changes': changes,
                }
            )

        # We are exposing unchanged files fully to the frontend client
        # so that it can show them for an better review experience.
        # We are using the "include unmodified"-flag for git but that
        # doesn't render any hunks and there's no way to enforce it.
        # Unfortunately that means we have to simulate line changes and
        # hunk data for unmodified files.
        # Unchanged files are *only* exposed in case of explicitly requesting
        # a diff view for an file. That way we increase performance for
        # reguar unittests and full-tree diffs.
        generate_unmodified_fake_diff = (
            not patch.delta.is_binary
            and pathspec is not None
            and (
                patch.delta.status == pygit2.GIT_DELTA_UNMODIFIED
                or (
                    # See:
                    # https://github.com/mozilla/addons-server/issues/15966
                    patch.delta.status == pygit2.GIT_DELTA_MODIFIED
                    and len(hunks) == 0
                )
            )
        )

        if generate_unmodified_fake_diff:
            tree = self.get_root_tree(commit)
            blob_or_tree = tree[patch.delta.new_file.path]
            actual_blob = self.git_repository[blob_or_tree.oid]
            mime_category = get_mime_type_for_blob(
                blob_or_tree.type, patch.delta.new_file.path
            )[1]

            if mime_category == 'text':
                data = actual_blob.data
                changes = [
                    {
                        'content': line,
                        'type': GIT_DIFF_LINE_MAPPING[GIT_DIFF_LINE_CONTEXT],
                        'old_line_number': lineno,
                        'new_line_number': lineno,
                    }
                    for lineno, line in enumerate(data.split(b'\n'), start=1)
                ]

                hunks.append(
                    {
                        'header': '@@ -0 +0 @@',
                        'old_start': 0,
                        'new_start': 0,
                        'old_lines': changes[-1]['old_line_number'],
                        'new_lines': changes[-1]['new_line_number'],
                        'changes': changes,
                    }
                )

        entry = {
            'path': patch.delta.new_file.path,
            'size': patch.delta.new_file.size,
            'lines_added': patch.line_stats[1],
            'lines_deleted': patch.line_stats[2],
            'is_binary': patch.delta.is_binary,
            'mode': patch.delta.status_char(),
            'hunks': hunks,
            'old_path': patch.delta.old_file.path,
            'parent': parent,
            'hash': commit,
            'new_ending_new_line': new_ending_new_line,
            'old_ending_new_line': old_ending_new_line,
        }

        return entry

def skip_git_extraction(version):
    return version.addon.type != amo.ADDON_EXTENSION

def create_git_extraction_entry(version):
    if skip_git_extraction(version):
        log.debug(
            'Skipping git extraction of add-on "%s" not a web-extension.',
            version.addon.id,
        )
        return

    log.info('Adding add-on "%s" to the git extraction queue.', version.addon.id)
    GitExtractionEntry.objects.create(addon=version.addon)

def extract_version_to_git(version_id):
    """Extract a `Version` into our git storage backend."""
    # We extract deleted or disabled versions as well so we need to make sure
    # we can access them.
    version = Version.unfiltered.get(pk=version_id)

    if skip_git_extraction(version):
        # We log a warning message because this should not happen (as the CRON
        # task should not select non-webextension versions).
        log.warning(
            'Skipping git extraction of add-on "%s": not a web-extension.',
            version.addon.id,
        )
        return

    log.info('Extracting version "%s" into git backend', version_id)

    try:
        with statsd.timer('git.extraction.version'):
            repo = AddonGitRepository.extract_and_commit_from_version(version=version)
        statsd.incr('git.extraction.version.success')
    except Exception as exc:
        statsd.incr('git.extraction.version.failure')
        raise exc

    log.info('Extracted version "%s" into "%s".', version_id, repo.git_repository_path)


text:
from base import *
from top import *
from device import *
from settings import *


text:
package com.sematext.solr.handler.component;

import org.apache.solr.common.util.NamedList;

/**
 * Implement this class with code which should process original Solr spellchecker's suggestions.
 *
 * For instance, instance
 * of this class could have static properties which describe best match, frequency etc. Since method process will be
 * invoked for each suggestion, you can compare each suggestion with others and possibly create resulting list with
 * acceptable suggestions.
 *
 * Instances of this class are intended to be used with method ReSearcherUtils.iterateOverSpellcheckerSuggestionsForWord().
 *
 * @author sematext, http://www.sematext.com/
 */
public interface SpellcheckerSuggestionProcessor {
  /**
   * Method which will be invoked on each suggestion.
   *
   * @param wordData - data about some suggestion, for instance, by using wordData.get("frequency"), frequency information
   * @param nameValue - name of node for which data wordData is provided (for instance, when iterating over all
   *                    incorrect words, nameValue will contain name of incorrect word)
   * can be extracted
   */
  void process(NamedList<Object> wordData, String nameValue);

  /**
   * Provides a to perform some logic after processing of all suggestions was finished.
   */
  void afterProcessingFinished();
}