text:
<!DOCTYPE html>

<meta content="text/html; charset=utf-8" http-equiv="Content-Type">

<title>module Authority - Rails Application Documentation</title>

<link type="text/css" media="screen" href="./rdoc.css" rel="stylesheet">

    Home
    Classes
    Methods

  <form action="#" method="get" accept-charset="utf-8">

      <input type="text" name="search" placeholder="Search" id="search-field"
             title="Type to search, Up and Down to navigate, Enter to load">

  </form>

Defined In

app/roles/authority.rb

Methods

#add_access

#allow_read_for?

#dev_access_for?

#guest_access_for?

#master_access_for?

#report_access_for?

#repository_masters

#repository_readers

#repository_writers

#reset_access

Pages

README_FOR_APP

Class and Module Index

Gitlab

Gitlab::API

Gitlab::APIHelpers

Gitlab::AppLogger

Gitlab::Auth

Gitlab::Encode

Gitlab::Entities

Gitlab::Entities::Hook

Gitlab::Entities::Issue

Gitlab::Entities::Milestone

Gitlab::Entities::Project

Gitlab::Entities::ProjectMember

Gitlab::Entities::ProjectSnippet

Gitlab::Entities::RepoCommit

Gitlab::Entities::RepoObject

Gitlab::Entities::SSHKey

Gitlab::Entities::User

Gitlab::Entities::UserBasic

Gitlab::Entities::UserLogin

Gitlab::FileEditor

Gitlab::GitLogger

Gitlab::Gitolite

Gitlab::Gitolite::AccessDenied

Gitlab::GitoliteConfig

Gitlab::GitoliteConfig::PullError

Gitlab::GitoliteConfig::PushError

Gitlab::GraphCommit

Gitlab::InlineDiff

Gitlab::Issues

Gitlab::Logger

Gitlab::Markdown

Gitlab::Merge

Gitlab::Milestones

Gitlab::Projects

Gitlab::Satellite

Gitlab::Session

Gitlab::Theme

Gitlab::Users

Admin

Admin::DashboardController

Admin::GroupsController

Admin::HooksController

Admin::LogsController

Admin::ProjectsController

Admin::ResqueController

Admin::TeamMembersController

Admin::UsersController

Notes

Notes::CreateContext

Notes::LoadContext

Redcarpet

Redcarpet::Render

Redcarpet::Render::GitlabHTML

ExtractsPath

ExtractsPath::InvalidPathError

FileSizeValidator

FileSizeValidator::Helper

Grack

Grack::Auth

IssueCommonality

IssueCommonality::ClassMethods

StaticModel

StaticModel::ClassMethods

Ability

Account

ActivityObserver

AdminController

ApplicationController

ApplicationDecorator

ApplicationHelper

AttachmentUploader

Authority

BaseContext

BlameController

BlobController

Commit

CommitController

CommitDecorator

CommitLoadContext

CommitsController

CommitsHelper

CompareController

DashboardController

DeployKeysController

ErrorsController

Event

EventDecorator

EventsHelper

GitHost

GitlabMarkdownHelper

Group

GroupsController

HelpController

HooksController

Issue

IssueObserver

IssuesBulkUpdateContext

IssuesController

IssuesHelper

IssuesListContext

Key

KeyObserver

KeysController

LabelsController

MergeRequest

MergeRequestObserver

MergeRequestsController

MergeRequestsHelper

MergeRequestsLoadContext

Milestone

MilestonesController

Note

NoteObserver

NotesController

NotesHelper

Notify

OmniauthCallbacksController

PostReceive

ProfileController

ProfileHelper

Project

ProjectHook

ProjectObserver

ProjectResourceController

ProjectsController

ProjectsHelper

ProtectedBranch

ProtectedBranchesController

PushEvent

PushObserver

RefsController

RepositoriesController

Repository

SearchContext

SearchController

Snippet

SnippetsController

SnippetsHelper

SystemHook

SystemHookObserver

SystemHookWorker

TabHelper

TagsHelper

Team

TeamMembersController

TestHookContext

Tree

TreeController

TreeDecorator

TreeHelper

User

UserObserver

UsersProject

UsersProjectObserver

Votes

WebHook

Wiki

WikisController

module Authority

Public Instance Methods

          add_access(user, *access)
          click to toggle source

Compatible with all access rights Should be rewrited for new access rights

# File app/roles/authority.rb, line 4
def add_access(user, *access)
  access = if access.include?(:admin)
             { project_access: UsersProject::MASTER }
           elsif access.include?(:write)
             { project_access: UsersProject::DEVELOPER }
           else
             { project_access: UsersProject::REPORTER }
           end
  opts = { user: user }
  opts.merge!(access)
  users_projects.create(opts)
end

          allow_read_for?(user)
          click to toggle source

# File app/roles/authority.rb, line 39
def allow_read_for?(user)
  !users_projects.where(user_id: user.id).empty?
end

          dev_access_for?(user)
          click to toggle source

# File app/roles/authority.rb, line 51
def dev_access_for?(user)
  !users_projects.where(user_id: user.id, project_access: [UsersProject::DEVELOPER, UsersProject::MASTER]).empty?
end

          guest_access_for?(user)
          click to toggle source

# File app/roles/authority.rb, line 43
def guest_access_for?(user)
  !users_projects.where(user_id: user.id).empty?
end

          master_access_for?(user)
          click to toggle source

# File app/roles/authority.rb, line 55
def master_access_for?(user)
  !users_projects.where(user_id: user.id, project_access: [UsersProject::MASTER]).empty?
end

          report_access_for?(user)
          click to toggle source

# File app/roles/authority.rb, line 47
def report_access_for?(user)
  !users_projects.where(user_id: user.id, project_access: [UsersProject::REPORTER, UsersProject::DEVELOPER, UsersProject::MASTER]).empty?
end

          repository_masters()
          click to toggle source

# File app/roles/authority.rb, line 33
def repository_masters
  keys = Key.joins({user: :users_projects}).
    where("users_projects.project_id = ? AND users_projects.project_access = ?", id, UsersProject::MASTER)
  keys.map(&:identifier)
end

          repository_readers()
          click to toggle source

# File app/roles/authority.rb, line 21
def repository_readers
  keys = Key.joins({user: :users_projects}).
    where("users_projects.project_id = ? AND users_projects.project_access = ?", id, UsersProject::REPORTER)
  keys.map(&:identifier) + deploy_keys.map(&:identifier)
end

          repository_writers()
          click to toggle source

# File app/roles/authority.rb, line 27
def repository_writers
  keys = Key.joins({user: :users_projects}).
    where("users_projects.project_id = ? AND users_projects.project_access = ?", id, UsersProject::DEVELOPER)
  keys.map(&:identifier)
end

          reset_access(user)
          click to toggle source

# File app/roles/authority.rb, line 17
def reset_access(user)
  users_projects.where(project_id: self.id, user_id: user.id).destroy if self.id
end

[Validate]

Generated by RDoc 3.12.

Generated with the Darkfish Rdoc Generator 3.


text:
#include <gtest/gtest.h>

extern "C"
{
#include "aeron_alloc.h"
#include "util/aeron_strutil.h"
}
#undef max

class StrUtilTest : public testing::Test
{
public:
    StrUtilTest() = default;
};

TEST_F(StrUtilTest, shouldHandleSingleValue)
{
    const int max_tokens = 10;
    char *tokens[max_tokens];
    char input[] = "single_token";

    int num_tokens = aeron_tokenise(input, ',', max_tokens, tokens);

    EXPECT_EQ(num_tokens, 1);
    EXPECT_STREQ(tokens[0], "single_token");
}

TEST_F(StrUtilTest, shouldHandleMultipleValues)
{
    const int max_tokens = 10;
    char *tokens[max_tokens];
    char input[] = "token_a,token_b,token_c";

    int num_tokens = aeron_tokenise(input, ',', max_tokens, tokens);

    EXPECT_EQ(num_tokens, 3);
    EXPECT_STREQ(tokens[0], "token_c");
    EXPECT_STREQ(tokens[1], "token_b");
    EXPECT_STREQ(tokens[2], "token_a");
}

TEST_F(StrUtilTest, shouldHandleMoreThanSpecifiedTokens)
{
    const int max_tokens = 2;
    char *tokens[max_tokens];
    char input[] = "token_a,token_b,token_c";

    int num_tokens = aeron_tokenise(input, ',', max_tokens, tokens);

    EXPECT_EQ(num_tokens, -ERANGE);
    EXPECT_STREQ(tokens[0], "token_c");
    EXPECT_STREQ(tokens[1], "token_b");
}

TEST_F(StrUtilTest, shouldFormatNumericStrings)
{
    char buffer[AERON_FORMAT_NUMBER_TO_LOCALE_STR_LEN];

    EXPECT_STREQ("999", aeron_format_number_to_locale(999, buffer, sizeof(buffer)));
    EXPECT_STREQ("-999", aeron_format_number_to_locale(-999, buffer, sizeof(buffer)));

    if (strcmp(localeconv()->thousands_sep, ".") == 0)
    {
        EXPECT_STREQ("999.999", aeron_format_number_to_locale(999999, buffer, sizeof(buffer)));
        EXPECT_STREQ("-999.999", aeron_format_number_to_locale(-999999, buffer, sizeof(buffer)));
        EXPECT_STREQ("999.999.999", aeron_format_number_to_locale(999999999, buffer, sizeof(buffer)));
        EXPECT_STREQ("-999.999.999", aeron_format_number_to_locale(-999999999, buffer, sizeof(buffer)));
        EXPECT_STREQ("10.000.000.000", aeron_format_number_to_locale(10000000000, buffer, sizeof(buffer)));
        EXPECT_STREQ("-999.9", aeron_format_number_to_locale(-999999999, buffer, 7));
    }
    else
    {
        EXPECT_STREQ("999,999", aeron_format_number_to_locale(999999, buffer, sizeof(buffer)));
        EXPECT_STREQ("-999,999", aeron_format_number_to_locale(-999999, buffer, sizeof(buffer)));
        EXPECT_STREQ("999,999,999", aeron_format_number_to_locale(999999999, buffer, sizeof(buffer)));
        EXPECT_STREQ("-999,999,999", aeron_format_number_to_locale(-999999999, buffer, sizeof(buffer)));
        EXPECT_STREQ("10,000,000,000", aeron_format_number_to_locale(10000000000, buffer, sizeof(buffer)));
        EXPECT_STREQ("-999,9", aeron_format_number_to_locale(-999999999, buffer, 7));
    }

    EXPECT_LT(
        strlen(aeron_format_number_to_locale(INT64_MIN, buffer, sizeof(buffer))),
        (size_t)AERON_FORMAT_NUMBER_TO_LOCALE_STR_LEN);
}

TEST_F(StrUtilTest, shouldHandleConsecutiveDelimeters)
{
    const int max_tokens = 10;
    char *tokens[max_tokens];
    char input[] = ",,token_a,,,,token_b,,token_c";

    int num_tokens = aeron_tokenise(input, ',', max_tokens, tokens);

    EXPECT_EQ(num_tokens, 3);
    EXPECT_STREQ(tokens[0], "token_c");
    EXPECT_STREQ(tokens[1], "token_b");
    EXPECT_STREQ(tokens[2], "token_a");
}

TEST_F(StrUtilTest, shouldHandleMaxRangeWithConsecutiveDelimeters)
{
    const int max_tokens = 3;
    char *tokens[max_tokens];
    char input[] = ",,token_a,,,,token_b,,token_c";

    int num_tokens = aeron_tokenise(input, ',', max_tokens, tokens);

    EXPECT_EQ(num_tokens, 3);
    EXPECT_STREQ(tokens[0], "token_c");
    EXPECT_STREQ(tokens[1], "token_b");
    EXPECT_STREQ(tokens[2], "token_a");
}

TEST_F(StrUtilTest, shouldHandleTrailingTokens)
{
    const int max_tokens = 6;
    char *tokens[max_tokens];
    char input[] = "token_a,token_b,token_c,,,,";

    int num_tokens = aeron_tokenise(input, ',', max_tokens, tokens);

    EXPECT_EQ(num_tokens, 3);
    EXPECT_STREQ(tokens[0], "token_c");
    EXPECT_STREQ(tokens[1], "token_b");
    EXPECT_STREQ(tokens[2], "token_a");
}

TEST_F(StrUtilTest, shouldHandleNull)
{
    const int max_tokens = 3;
    char *tokens[max_tokens];

    int num_tokens = aeron_tokenise(nullptr, ',', max_tokens, tokens);

    EXPECT_EQ(num_tokens, -EINVAL);
}

TEST_F(StrUtilTest, checkStringLength)
{
    size_t length_initial_value = 1;
    const char str1[] = {'h', 'e', 'l', 'l', 'o', '\0'};
    EXPECT_FALSE(aeron_str_length(str1, 5, nullptr));
    EXPECT_TRUE(aeron_str_length(str1, 6, nullptr));

    size_t length = length_initial_value;
    EXPECT_FALSE(aeron_str_length(str1, 5, &length));
    EXPECT_EQ(length_initial_value, length);

    length = length_initial_value;
    EXPECT_TRUE(aeron_str_length(str1, 6, &length));
    EXPECT_EQ(5U, length);
}

TEST_F(StrUtilTest, checkStringLengthEmptyAndNull)
{
    size_t length_initial_value = 1;
    const char* str1 = "";
    EXPECT_TRUE(aeron_str_length(str1, 5, nullptr));
    EXPECT_TRUE(aeron_str_length(nullptr, 5, nullptr));

    size_t length = length_initial_value;
    EXPECT_TRUE(aeron_str_length(str1, 5, &length));
    EXPECT_EQ(0U, length);

    length = length_initial_value;
    EXPECT_TRUE(aeron_str_length(nullptr, 5, &length));
    EXPECT_EQ(length_initial_value, length);
}

redpajama_set_name: RedPajamaGithub


text:
import { Plugin } from "postcss";

declare namespace localByDefault {
    interface Options {
        mode?: "global" | "local" | "pure";
        rewriteUrl?: (global: boolean, url: string) => string;
    }

    type LocalByDefault = Plugin<Options>;
}

declare const localByDefault: localByDefault.LocalByDefault;
export = localByDefault;


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

<title>All Classes</title>
<meta name="date" content="2015-03-18">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

All Classes

AbstractCourse

AbstractCourseSnapshot

Assignment

AssignmentCategory

AssignmentGrade

AssignmentSubmission

Course

CourseAccessor

CourseManager

CourseManager.CourseEntries

CourseModifier

CourseSnapshot

CurveSetting

DeleteCommand

GraderObject

GradeSchema

Identity

LatePolicy

LetterGrade

Permission

Role

RoleManager

Session

SpestConsts

StudentRecord

Subject

UndoRedo

User


text:
package org.apache.ignite.internal.client.integration;

import org.apache.ignite.*;
import org.apache.ignite.cache.affinity.rendezvous.*;
import org.apache.ignite.cluster.*;
import org.apache.ignite.compute.*;
import org.apache.ignite.configuration.*;
import org.apache.ignite.internal.*;
import org.apache.ignite.internal.client.*;
import org.apache.ignite.internal.client.balancer.*;
import org.apache.ignite.internal.client.ssl.*;
import org.apache.ignite.internal.managers.communication.*;
import org.apache.ignite.internal.processors.cache.*;
import org.apache.ignite.internal.processors.cache.distributed.*;
import org.apache.ignite.internal.processors.cache.transactions.*;
import org.apache.ignite.internal.processors.cache.version.*;
import org.apache.ignite.internal.util.typedef.*;
import org.apache.ignite.lang.*;
import org.apache.ignite.plugin.extensions.communication.*;
import org.apache.ignite.resources.*;
import org.apache.ignite.spi.*;
import org.apache.ignite.spi.communication.tcp.*;
import org.apache.ignite.spi.discovery.tcp.*;
import org.apache.ignite.spi.discovery.tcp.ipfinder.*;
import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.*;
import org.apache.ignite.testframework.*;
import org.apache.ignite.testframework.junits.common.*;
import org.jetbrains.annotations.*;

import java.util.*;
import java.util.concurrent.*;

import static java.util.concurrent.TimeUnit.*;
import static org.apache.ignite.cache.CacheAtomicityMode.*;
import static org.apache.ignite.cache.CacheMode.*;
import static org.apache.ignite.cache.CacheWriteSynchronizationMode.*;

/**
 * Tests basic client behavior with multiple nodes.
 */
@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
public abstract class ClientAbstractMultiNodeSelfTest extends GridCommonAbstractTest {
    /** */
    private static final TcpDiscoveryIpFinder IP_FINDER = new TcpDiscoveryVmIpFinder(true);

    /** Partitioned cache name. */
    private static final String PARTITIONED_CACHE_NAME = "partitioned";

    /** Replicated cache name. */
    private static final String REPLICATED_CACHE_NAME = "replicated";

    /** Replicated async cache name. */
    private static final String REPLICATED_ASYNC_CACHE_NAME = "replicated_async";

    /** Nodes count. */
    public static final int NODES_CNT = 5;

    /**
     * Topology update frequency.
     * Set it longer than router's, so we wouldn't receive failures
     * caused only by obsolete topology on router.
     */
    static final int TOP_REFRESH_FREQ = 2500;

    /** Path to jetty config. */
    public static final String REST_JETTY_CFG = "modules/clients/src/test/resources/jetty/rest-jetty.xml";

    /** Path to jetty config with SSl enabled. */
    public static final String REST_JETTY_SSL_CFG = "modules/clients/src/test/resources/jetty/rest-jetty-ssl.xml";

    /** Host. */
    public static final String HOST = "127.0.0.1";

    /** Base for tcp rest ports. */
    public static final int REST_TCP_PORT_BASE = 12345;

    /** Base for http rest ports, defined in {@link #REST_JETTY_CFG}. */
    public static final int REST_HTTP_PORT_BASE = 11080;

    /** Base for https rest ports, defined in {@link #REST_JETTY_SSL_CFG}. */
    public static final int REST_HTTPS_PORT_BASE = 11443;

    /** */
    private static volatile boolean commSpiEnabled;

    /** Flag to enable REST in node configuration. */
    private boolean restEnabled = true;

    /** Client instance for each test. */
    private GridClient client;

    /**
     * @return Client protocol that should be used.
     */
    protected abstract GridClientProtocol protocol();

    /**
     * @return Server address to create first connection.
     */
    protected abstract String serverAddress();

    /**
     * @return SSL context factory to use if SSL or {@code null} to disable SSL usage.
     */
    @Nullable protected GridSslContextFactory sslContextFactory() {
        return null;
    }

    /** {@inheritDoc} */
    @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
        IgniteConfiguration c = super.getConfiguration(gridName);

        c.setLocalHost(HOST);

        assert c.getConnectorConfiguration() == null;

        if (restEnabled) {
            ConnectorConfiguration clientCfg = new ConnectorConfiguration();

            clientCfg.setPort(REST_TCP_PORT_BASE);

            GridSslContextFactory sslCtxFactory = sslContextFactory();

            if (sslCtxFactory != null) {
                clientCfg.setSslEnabled(true);
                clientCfg.setSslContextFactory(sslCtxFactory);
            }

            c.setConnectorConfiguration(clientCfg);
        }

        TcpDiscoverySpi disco = new TcpDiscoverySpi();

        disco.setIpFinder(IP_FINDER);

        c.setDiscoverySpi(disco);

        TestCommunicationSpi spi = new TestCommunicationSpi();

        spi.setLocalPort(GridTestUtils.getNextCommPort(getClass()));

        c.setCommunicationSpi(spi);

        c.setCacheConfiguration(cacheConfiguration(null), cacheConfiguration(PARTITIONED_CACHE_NAME),
            cacheConfiguration(REPLICATED_CACHE_NAME), cacheConfiguration(REPLICATED_ASYNC_CACHE_NAME));

        c.setPublicThreadPoolSize(40);

        c.setSystemThreadPoolSize(40);

        return c;
    }

    /**
     * @param cacheName Cache name.
     * @return Cache configuration.
     * @throws Exception In case of error.
     */
    private CacheConfiguration cacheConfiguration(@Nullable String cacheName) throws Exception {
        CacheConfiguration cfg = defaultCacheConfiguration();

        cfg.setAtomicityMode(TRANSACTIONAL);

        if (cacheName == null)
            cfg.setCacheMode(LOCAL);
        else if (PARTITIONED_CACHE_NAME.equals(cacheName)) {
            cfg.setCacheMode(PARTITIONED);

            cfg.setBackups(0);
        }
        else
            cfg.setCacheMode(REPLICATED);

        cfg.setName(cacheName);

        cfg.setWriteSynchronizationMode(REPLICATED_ASYNC_CACHE_NAME.equals(cacheName) ? FULL_ASYNC : FULL_SYNC);

        cfg.setAffinity(new RendezvousAffinityFunction());

        return cfg;
    }

    /** {@inheritDoc} */
    @Override protected void beforeTestsStarted() throws Exception {
        startGridsMultiThreaded(NODES_CNT);
    }

    /** {@inheritDoc} */
    @Override protected void afterTestsStopped() throws Exception {
        info("Stopping grids.");

        stopAllGrids();
    }

    /** {@inheritDoc} */
    @Override protected void beforeTest() throws Exception {
        client = GridClientFactory.start(clientConfiguration());
    }

    /** {@inheritDoc} */
    @Override protected void afterTest() throws Exception {
        if (client != null) {
            GridClientFactory.stop(client.id(), false);

            client = null;
        }
    }

    /**
     * @throws Exception If failed.
     */
    public void testEmptyProjections() throws Exception {
        final GridClientCompute dflt = client.compute();

        Collection<? extends GridClientNode> nodes = dflt.nodes();

        assertEquals(NODES_CNT, nodes.size());

        Iterator<? extends GridClientNode> iter = nodes.iterator();

        final GridClientCompute singleNodePrj = dflt.projection(Collections.singletonList(iter.next()));

        final GridClientNode second = iter.next();

        final GridClientPredicate<GridClientNode> noneFilter = new GridClientPredicate<GridClientNode>() {
            @Override public boolean apply(GridClientNode node) {
                return false;
            }
        };

        final GridClientPredicate<GridClientNode> targetFilter = new GridClientPredicate<GridClientNode>() {
            @Override public boolean apply(GridClientNode node) {
                return node.nodeId().equals(second.nodeId());
            }
        };

        GridTestUtils.assertThrows(log(), new Callable<Object>() {
            @Override public Object call() throws Exception {
                return singleNodePrj.projection(second);
            }
        }, GridClientException.class, null);

        GridTestUtils.assertThrows(log(), new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                return singleNodePrj.projection(targetFilter);
            }
        }, GridClientException.class, null);
    }

    /**
     * @throws Exception If failed.
     */
    public void testProjectionRun() throws Exception {
        GridClientCompute dflt = client.compute();

        Collection<? extends GridClientNode> nodes = dflt.nodes();

        assertEquals(NODES_CNT, nodes.size());

        for (int i = 0; i < NODES_CNT; i++) {
            Ignite g = grid(i);

            assert g != null;

            GridClientNode clientNode = dflt.node(g.cluster().localNode().id());

            assertNotNull("Client node for " + g.cluster().localNode().id() + " was not found", clientNode);

            GridClientCompute prj = dflt.projection(clientNode);

            String res = prj.execute(TestTask.class.getName(), null);

            assertNotNull(res);

            assertEquals(g.cluster().localNode().id().toString(), res);
        }
    }

    /**
     * @throws Exception If failed.
     */
    public void testTopologyListener() throws Exception {
        final Collection<UUID> added = new ArrayList<>(1);
        final Collection<UUID> rmvd = new ArrayList<>(1);

        final CountDownLatch addedLatch = new CountDownLatch(1);
        final CountDownLatch rmvLatch = new CountDownLatch(1);

        assertEquals(NODES_CNT, client.compute().refreshTopology(false, false).size());

        GridClientTopologyListener lsnr = new GridClientTopologyListener() {
            @Override public void onNodeAdded(GridClientNode node) {
                added.add(node.nodeId());

                addedLatch.countDown();
            }

            @Override public void onNodeRemoved(GridClientNode node) {
                rmvd.add(node.nodeId());

                rmvLatch.countDown();
            }
        };

        client.addTopologyListener(lsnr);

        try {
            Ignite g = startGrid(NODES_CNT + 1);

            UUID id = g.cluster().localNode().id();

            assertTrue(addedLatch.await(2 * TOP_REFRESH_FREQ, MILLISECONDS));

            assertEquals(1, added.size());
            assertEquals(id, F.first(added));

            stopGrid(NODES_CNT + 1);

            assertTrue(rmvLatch.await(2 * TOP_REFRESH_FREQ, MILLISECONDS));

            assertEquals(1, rmvd.size());
            assertEquals(id, F.first(rmvd));
        }
        finally {
            client.removeTopologyListener(lsnr);

            stopGrid(NODES_CNT + 1);
        }
    }

    /**
     * @return Client configuration for the test.
     */
    protected GridClientConfiguration clientConfiguration() throws GridClientException {
        GridClientConfiguration cfg = new GridClientConfiguration();

        cfg.setBalancer(getBalancer());

        cfg.setTopologyRefreshFrequency(TOP_REFRESH_FREQ);

        cfg.setProtocol(protocol());
        cfg.setServers(Arrays.asList(serverAddress()));
        cfg.setSslContextFactory(sslContextFactory());

        GridClientDataConfiguration loc = new GridClientDataConfiguration();

        GridClientDataConfiguration partitioned = new GridClientDataConfiguration();

        partitioned.setName(PARTITIONED_CACHE_NAME);
        partitioned.setAffinity(new GridClientPartitionAffinity());

        GridClientDataConfiguration replicated = new GridClientDataConfiguration();
        replicated.setName(REPLICATED_CACHE_NAME);

        GridClientDataConfiguration replicatedAsync = new GridClientDataConfiguration();
        replicatedAsync.setName(REPLICATED_ASYNC_CACHE_NAME);

        cfg.setDataConfigurations(Arrays.asList(loc, partitioned, replicated, replicatedAsync));

        return cfg;
    }

    /**
     * Gets client load balancer.
     *
     * @return Load balancer.
     */
    protected GridClientLoadBalancer getBalancer() {
        return new GridClientRoundRobinBalancer();
    }

    /**
     * Test task. Returns a tuple in which first component is id of node that has split the task,
     * and second component is count of nodes that executed jobs.
     */
    private static class TestTask extends ComputeTaskSplitAdapter<Object, String> {
        /** */
        @IgniteInstanceResource
        private Ignite ignite;

        /** Count of tasks this job was split to. */
        private int gridSize;

        /** {@inheritDoc} */
        @Override protected Collection<? extends ComputeJob> split(int gridSize, Object arg) {
            Collection<ComputeJobAdapter> jobs = new ArrayList<>(gridSize);

            this.gridSize = gridSize;

            final String locNodeId = ignite.cluster().localNode().id().toString();

            for (int i = 0; i < gridSize; i++) {
                jobs.add(new ComputeJobAdapter() {
                    @SuppressWarnings("OverlyStrongTypeCast")
                    @Override public Object execute() {
                        try {
                            Thread.sleep(1000);
                        }
                        catch (InterruptedException ignored) {
                            Thread.currentThread().interrupt();
                        }

                        return new IgniteBiTuple<>(locNodeId, 1);
                    }
                });
            }

            return jobs;
        }

        /** {@inheritDoc} */
        @Override public String reduce(List<ComputeJobResult> results) {
            int sum = 0;

            String locNodeId = null;

            for (ComputeJobResult res : results) {
                IgniteBiTuple<String, Integer> part = res.getData();

                if (locNodeId == null)
                    locNodeId = part.get1();

                Integer i = part.get2();

                if (i != null)
                    sum += i;
            }

            assert gridSize == sum;

            return locNodeId;
        }
    }

    /**
     * Communication SPI which checks cache flags.
     */
    @SuppressWarnings("unchecked")
    private static class TestCommunicationSpi extends TcpCommunicationSpi {
        /** {@inheritDoc} */
        @Override public void sendMessage(ClusterNode node, Message msg)
            throws IgniteSpiException {
            checkSyncFlags((GridIoMessage)msg);

            super.sendMessage(node, msg);
        }

        /**
         * Check if flags in correct state.
         *
         * @param msg Message.
         */
        private void checkSyncFlags(GridIoMessage msg) {
            if (!commSpiEnabled)
                return;

            Object o = msg.message();

            if (!(o instanceof GridDistributedLockRequest))
                return;

            IgniteKernal g = (IgniteKernal)G.ignite(ignite.configuration().getNodeId());

            GridCacheContext<Object, Object> cacheCtx = g.internalCache(REPLICATED_ASYNC_CACHE_NAME).context();

            IgniteTxManager tm = cacheCtx.tm();

            GridCacheVersion v = ((GridCacheVersionable)o).version();

            IgniteInternalTx t = tm.tx(v);

            if (t.hasWriteKey(cacheCtx.txKey(cacheCtx.toCacheKeyObject("x1"))))
                assertFalse("Invalid tx flags: " + t, t.syncCommit());
            else if (t.hasWriteKey(cacheCtx.txKey(cacheCtx.toCacheKeyObject("x2"))))
            assertTrue("Invalid tx flags: " + t, t.syncCommit());
            else if (t.hasWriteKey(cacheCtx.txKey(cacheCtx.toCacheKeyObject("x3"))))
                assertFalse("Invalid tx flags: " + t, t.syncCommit());
            else if (t.hasWriteKey(cacheCtx.txKey(cacheCtx.toCacheKeyObject("x4"))))
                assertTrue("Invalid tx flags: " + t, t.syncCommit());
        }
    }
}


text: export { default } from 'ember-spotify/utils/default-for';


text:
<?php
$lang['result']				= "Resultaat";
$lang['results']			= "Resultaten";
$lang['data_for_result']	= "Data voor resultaat %s";
$lang['add_result'] 		= "Voeg resultaat toe";
$lang['result_added']		= "Nieuwe resultaat %s succesvol toegevoegd.";
$lang['edit_result']		= "Bewerk resultaat %s";
$lang['result_edited'] 		= "Resultaat %s succesvol bewerkt.";
$lang['sure_delete_result']	= "Weet u zeker dat u dit resultaat wilt verwijderen?";
$lang['result_deleted'] 	= "Resultaat succesvol verwijderd.";

$lang['phasenr'] 			= "Phase number";
$lang['phase'] 				= "Phase";
$lang['trial'] 				= "Trial";
$lang['lookingtime'] 		= "Lookingtime (in ms)";
$lang['nrlooks']		 	= "# views";
?>


text:
require File.expand_path("../../../../spec/e2e", __FILE__)
require "rspec"
require "net/http"

RSpec.describe "Datastore E2E test" do
  before do
    @url = E2E.url
  end

  it "returns what we expect" do
    uri = URI.parse(@url)
    response = Net::HTTP.get(uri)
    expect(response).to include("Last 10 visits:")
    expect(response).to include("Time:")
    expect(response).to include("UTC Addr:")
  end
end


text:
import React from 'react'
import {NativeAnimated, NativeEasing} from './native-wrappers.native'
import * as Styles from '../styles'
import type {Props} from './switch-toggle'

class SwitchToggle extends React.PureComponent<Props> {
  _offset = new NativeAnimated.Value(this._getOffset())
  _animation: any = null

  _getOffset() {
    return this.props.on ? enabledOffset : disabledOffset
  }

  componentDidUpdate(prevProps: Props) {
    if (prevProps.on === this.props.on) {
      return
    }
    this._animation?.stop()
    this._animation = NativeAnimated.timing(this._offset, {
      duration: 100,
      easing: NativeEasing.linear,
      toValue: this._getOffset(),
      useNativeDriver: false,
    })
    this._animation.start()
  }
  render() {
    return (
      <NativeAnimated.View
        style={Styles.collapseStyles([
          styles.outer,
          {
            backgroundColor: this._offset.interpolate({
              inputRange: [disabledOffset, enabledOffset],
              outputRange: [
                Styles.undynamicColor(Styles.globalColors.greyDark),
                Styles.undynamicColor(Styles.globalColors[this.props.color]),
              ],
            }),
          },
          this.props.style,
        ] as any)}
      >
        <NativeAnimated.View
          style={Styles.collapseStyles([styles.inner, {marginLeft: this._offset}] as any)}
        />
      </NativeAnimated.View>
    )
  }
}

export default SwitchToggle

const disabledOffset = 2
const enabledOffset = 22

const styles = Styles.styleSheetCreate(() => ({
  inner: {
    backgroundColor: Styles.undynamicColor(Styles.globalColors.white),
    borderRadius: 12,
    height: 24,
    width: 24,
  },
  outer: {
    ...Styles.globalStyles.flexBoxRow,
    alignItems: 'center',
    borderRadius: 14,
    flexShrink: 0,
    height: 28,
    width: 48,
  },
}))


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;

namespace MetaDslx.CodeAnalysis.Syntax.InternalSyntax
{
    /// <summary>
    /// Keeps a sliding buffer over the SourceText of a file for the lexer. Also
    /// provides the lexer with the ability to keep track of a current "lexeme"
    /// by leaving a marker and advancing ahead the offset. The lexer can then
    /// decide to "keep" the lexeme by erasing the marker, or abandon the current
    /// lexeme by moving the offset back to the marker.
    /// </summary>
    public sealed class SlidingTextWindow : IDisposable
    {
        /// <summary>
        /// In many cases, e.g. PeekChar, we need the ability to indicate that there are
        /// no characters left and we have reached the end of the stream, or some other
        /// invalid or not present character was asked for. Due to perf concerns, things
        /// like nullable or out variables are not viable. Instead we need to choose a
        /// char value which can never be legal.
        ///
        /// In .NET, all characters are represented in 16 bits using the UTF-16 encoding.
        /// Fortunately for us, there are a variety of different bit patterns which
        /// are *not* legal UTF-16 characters. 0xffff (char.MaxValue) is one of these
        /// characters -- a legal Unicode code point, but not a legal UTF-16 bit pattern.
        /// </summary>
        public const char InvalidCharacter = char.MaxValue;

        private const int DefaultWindowLength = 2048;

        private readonly SourceText _text;                 // Source of text to parse.
        private int _basis;                                // Offset of the window relative to the SourceText start.
        private int _offset;                               // Offset from the start of the window.
        private List<int> _resetStack;
        private readonly int _textEnd;                     // Absolute end position
        private char[] _characterWindow;                   // Moveable window of chars from source text
        private int _characterWindowCount;                 // # of valid characters in chars buffer

        private int _lexemeStart;                          // Start of current lexeme relative to the window start.

        private int _minLexemeLookahead;
        private int _maxLexemeLookahead;
        private int _minLookahead;
        private int _maxLookahead;

        // Example for the above variables:
        // The text starts at 0.
        // The window onto the text starts at basis.
        // The current character is at (basis + offset), AKA the current "Position".
        // The current lexeme started at (basis + lexemeStart), which is <= (basis + offset)
        // The current lexeme is the characters between the lexemeStart and the offset.

        private readonly StringTable _strings;

        private static readonly ObjectPool<char[]> s_windowPool = new ObjectPool<char[]>(() => new char[DefaultWindowLength]);

        public SlidingTextWindow(SourceText text)
        {
            _text = text;
            _basis = 0;
            _offset = 0;
            _resetStack = new List<int>();
            _textEnd = text.Length;
            _strings = StringTable.GetInstance();
            _characterWindow = s_windowPool.Allocate();
            _lexemeStart = 0;
            _minLookahead = int.MaxValue;
            _maxLookahead = int.MinValue;
            _minLexemeLookahead = int.MaxValue;
            _maxLexemeLookahead = int.MinValue;
        }

        public void Dispose()
        {
            if (_characterWindow != null)
            {
                s_windowPool.Free(_characterWindow);
                _characterWindow = null;
                _strings.Free();
            }
        }

        public SourceText Text => _text;

        /// <summary>
        /// The current absolute position in the text file.
        /// </summary>
        public int Position
        {
            get
            {
                return _basis + _offset;
            }
        }

        /// <summary>
        /// The current offset inside the window (relative to the window start).
        /// </summary>
        public int Offset
        {
            get
            {
                return _offset;
            }
        }

        /// <summary>
        /// The buffer backing the current window.
        /// </summary>
        public char[] CharacterWindow
        {
            get
            {
                return _characterWindow;
            }
        }

        /// <summary>
        /// Returns the start of the current lexeme relative to the window start.
        /// </summary>
        public int LexemeRelativeStart
        {
            get
            {
                return _lexemeStart;
            }
        }

        /// <summary>
        /// Number of characters in the character window.
        /// </summary>
        public int CharacterWindowCount
        {
            get
            {
                return _characterWindowCount;
            }
        }

        /// <summary>
        /// The absolute position of the start of the current lexeme in the given
        /// SourceText.
        /// </summary>
        public int LexemeStartPosition
        {
            get
            {
                return _basis + _lexemeStart;
            }
        }

        /// <summary>
        /// The number of characters in the current lexeme.
        /// </summary>
        public int Width
        {
            get
            {
                return _offset - _lexemeStart;
            }
        }

        public int MinLookahead => _minLookahead;
        public int MaxLookahead => _maxLookahead;
        public int MinLexemeLookahead => _minLexemeLookahead;
        public int MaxLexemeLookahead => _maxLexemeLookahead;

        /// <summary>
        /// Start parsing a new lexeme.
        /// </summary>
        public void Start()
        {
            _lexemeStart = _offset;
            _minLexemeLookahead = int.MaxValue;
            _maxLexemeLookahead = int.MinValue;
        }

        public int GetResetPoint()
        {
            _resetStack.Add(_basis + _offset);
            return _resetStack.Count;
        }

        public void Reset(int resetPoint)
        {
            Debug.Assert(resetPoint == _resetStack.Count);
            var position = _resetStack[_resetStack.Count - 1];
            _resetStack.RemoveAt(_resetStack.Count - 1);
            ResetTo(position);
        }

        public void ReleaseResetPoint(int resetPoint)
        {
            Debug.Assert(resetPoint == _resetStack.Count);
            _resetStack.RemoveAt(_resetStack.Count - 1);
        }

        public void ResetTo(int position)
        {
            if (position < _basis)
            {
                Debug.Assert(true);
            }
            // if position is within already read character range then just use what we have
            int relative = position - _basis;
            if (relative >= 0 && relative <= _characterWindowCount)
            {
                _offset = relative;
            }
            else
            {
                var resetPoint = position;
                if (_resetStack.Count > 0) resetPoint = _resetStack[0] - _basis;

                // we need to reread text buffer
                int amountToRead = Math.Min(_text.Length, resetPoint + _characterWindow.Length) - resetPoint;
                amountToRead = Math.Max(amountToRead, 0);
                if (amountToRead > 0)
                {
                    _text.CopyTo(resetPoint, _characterWindow, 0, amountToRead);
                }

                _lexemeStart = resetPoint - position;
                _offset = resetPoint - position;
                _basis = resetPoint;
                _characterWindowCount = amountToRead;
            }
        }

        private bool MoreChars(int delta = 0)
        {
            if (_offset + delta >= _characterWindowCount)
            {
                if (this.Position + delta >= _textEnd)
                {
                    return false;
                }

                // if lexeme scanning is sufficiently into the char buffer,
                // then refocus the window onto the lexeme
                if (_lexemeStart > (_characterWindowCount / 4))
                {
                    Array.Copy(_characterWindow,
                        _lexemeStart,
                        _characterWindow,
                        0,
                        _characterWindowCount - _lexemeStart);
                    _characterWindowCount -= _lexemeStart;
                    _offset -= _lexemeStart;
                    _basis += _lexemeStart;
                    _lexemeStart = 0;
                }

                if (_characterWindowCount >= _characterWindow.Length)
                {
                    // grow char array, since we need more contiguous space
                    char[] oldWindow = _characterWindow;
                    char[] newWindow = new char[_characterWindow.Length * 2];
                    Array.Copy(oldWindow, 0, newWindow, 0, _characterWindowCount);
                    s_windowPool.ForgetTrackedObject(oldWindow, newWindow);
                    _characterWindow = newWindow;
                }

                int amountToRead = Math.Min(_textEnd - (_basis + _characterWindowCount),
                    _characterWindow.Length - _characterWindowCount);
                _text.CopyTo(_basis + _characterWindowCount,
                    _characterWindow,
                    _characterWindowCount,
                    amountToRead);
                _characterWindowCount += amountToRead;
                return amountToRead > 0;
            }

            return true;
        }

        /// <summary>
        /// After reading <see cref=" InvalidCharacter"/>, a consumer can determine
        /// if the InvalidCharacter was in the user's source or a sentinel.
        ///
        /// Comments and string literals are allowed to contain any Unicode character.
        /// </summary>
        /// <returns></returns>
        internal bool IsReallyAtEnd()
        {
            return _offset >= _characterWindowCount && Position >= _textEnd;
        }

        /// <summary>
        /// Advance the current position by one. No guarantee that this
        /// position is valid.
        /// </summary>
        public void AdvanceChar()
        {
            _offset++;
        }

        /// <summary>
        /// Advance the current position by n. No guarantee that this position
        /// is valid.
        /// </summary>
        public void AdvanceChar(int n)
        {
            _offset += n;
        }

        /// <summary>
        /// Grab the next character and advance the position.
        /// </summary>
        /// <returns>
        /// The next character, <see cref="InvalidCharacter" /> if there were no characters
        /// remaining.
        /// </returns>
        public char NextChar()
        {
            char c = PeekChar();
            if (c != InvalidCharacter)
            {
                this.AdvanceChar();
            }
            return c;
        }

        /// <summary>
        /// Gets the next character if there are any characters in the
        /// SourceText. May advance the window if we are at the end.
        /// </summary>
        /// <returns>
        /// The next character if any are available. InvalidCharacter otherwise.
        /// </returns>
        public char PeekChar()
        {
            _minLexemeLookahead = Math.Min(_minLexemeLookahead, 1);
            _maxLexemeLookahead = Math.Max(_maxLexemeLookahead, 1);
            _minLookahead = Math.Min(_minLookahead, _minLexemeLookahead);
            _maxLookahead = Math.Max(_maxLookahead, _maxLexemeLookahead);

            if (_offset >= _characterWindowCount
                && !MoreChars())
            {
                return InvalidCharacter;
            }

            // N.B. MoreChars may update the offset.
            return _characterWindow[_offset];
        }

        /// <summary>
        /// Gets the character at the given offset to the current position if
        /// the position is valid within the SourceText.
        /// </summary>
        /// <returns>
        /// The next character if any are available. InvalidCharacter otherwise.
        /// </returns>
        public char PeekChar(int delta)
        {
            _minLexemeLookahead = Math.Min(_minLexemeLookahead, delta);
            _maxLexemeLookahead = Math.Max(_maxLexemeLookahead, delta);
            _minLookahead = Math.Min(_minLookahead, _minLexemeLookahead);
            _maxLookahead = Math.Max(_maxLookahead, _maxLexemeLookahead);

            char ch;
            if (_offset + delta >= _characterWindowCount && !MoreChars(delta))
            {
                ch = InvalidCharacter;
            }
            else
            {
                // N.B. MoreChars may update the offset.
                ch = _characterWindow[_offset + delta];
            }

            return ch;
        }

        /// <summary>
        /// If the next characters in the window match the given string,
        /// then advance past those characters.  Otherwise, do nothing.
        /// </summary>
        private bool AdvanceIfMatches(string desired)
        {
            int length = desired.Length;

            for (int i = 0; i < length; i++)
            {
                if (PeekChar(i) != desired[i])
                {
                    return false;
                }
            }

            AdvanceChar(length);
            return true;
        }

        private SyntaxDiagnosticInfo CreateIllegalEscapeDiagnostic(int start)
        {
            return new SyntaxDiagnosticInfo(start - this.LexemeStartPosition,
                this.Position - start,
                InternalErrorCode.ERR_IllegalEscape);
        }

        public string Intern(StringBuilder text)
        {
            return _strings.Add(text);
        }

        public string Intern(char[] array, int start, int length)
        {
            return _strings.Add(array, start, length);
        }

        public string GetInternedText()
        {
            return this.Intern(_characterWindow, _lexemeStart, this.Width);
        }

        public string GetText(bool intern)
        {
            return this.GetText(this.LexemeStartPosition, this.Width, intern);
        }

        public string GetText(int position, int length, bool intern)
        {
            int offset = position - _basis;

            // PERF: Whether interning or not, there are some frequently occurring
            // easy cases we can pick off easily.
            switch (length)
            {
                case 0:
                    return string.Empty;

                case 1:
                    if (_characterWindow[offset] == ' ')
                    {
                        return " ";
                    }
                    if (_characterWindow[offset] == '\n')
                    {
                        return "\n";
                    }
                    break;

                case 2:
                    char firstChar = _characterWindow[offset];
                    if (firstChar == '\r' && _characterWindow[offset + 1] == '\n')
                    {
                        return "\r\n";
                    }
                    if (firstChar == '/' && _characterWindow[offset + 1] == '/')
                    {
                        return "//";
                    }
                    break;

                case 3:
                    if (_characterWindow[offset] == '/' && _characterWindow[offset + 1] == '/' && _characterWindow[offset + 2] == ' ')
                    {
                        return "// ";
                    }
                    break;
            }

            if (intern)
            {
                return this.Intern(_characterWindow, offset, length);
            }
            else
            {
                return new string(_characterWindow, offset, length);
            }
        }

        internal static char GetCharsFromUtf32(uint codepoint, out char lowSurrogate)
        {
            if (codepoint < (uint)0x00010000)
            {
                lowSurrogate = InvalidCharacter;
                return (char)codepoint;
            }
            else
            {
                Debug.Assert(codepoint > 0x0000FFFF && codepoint <= 0x0010FFFF);
                lowSurrogate = (char)((codepoint - 0x00010000) % 0x0400 + 0xDC00);
                return (char)((codepoint - 0x00010000) / 0x0400 + 0xD800);
            }
        }
    }
}


text:
namespace content {

class MediaStreamRequestForUI;
class SettingsRequester;

// MediaStreamUIController is responsible for getting user permission to use
// a media capture device as well as selecting what device to use.
class CONTENT_EXPORT MediaStreamUIController {
 public:
  explicit MediaStreamUIController(SettingsRequester* requester);
  virtual ~MediaStreamUIController();

  // Called when a new request for the capture device access is made.
  // Users are responsbile for cancel the pending request if they don't wait
  // for the result from the UI.
  void MakeUIRequest(const std::string& label,
                     int render_process_id,
                     int render_view_id,
                     const StreamOptions& stream_components,
                     const GURL& security_origin,
                     MediaStreamRequestType request_type,
                     const std::string& requested_device_id);

  // Called to cancel a pending UI request of capture device access when the
  // user has no action for the media stream InfoBar.
  void CancelUIRequest(const std::string& label);

  // Called by the InfoBar when the user grants/denies access to some devices
  // to the webpage. This is placed here, so the request can be cleared from the
  // list of pending requests, instead of letting the InfoBar itself respond to
  // the requester. An empty list of devices means that access has been denied.
  // This method must be called on the IO thread.
  void PostResponse(const std::string& label,
                    const MediaStreamDevices& devices);

  // Called to signal the UI indicator that the devices are opened.
  void NotifyUIIndicatorDevicesOpened(
      int render_process_id,
      int render_view_id,
      const MediaStreamDevices& devices);

  // Called to signal the UI indicator that the devices are closed.
  void NotifyUIIndicatorDevicesClosed(
      int render_process_id,
      int render_view_id,
      const MediaStreamDevices& devices);

  // Used for testing only. This function is called to use faked UI, which is
  // needed for server based tests. The first non-opened device(s) will be
  // picked.
  void UseFakeUI();

 private:
  typedef std::map<std::string, MediaStreamRequestForUI*> UIRequests;

  // Returns true if the UI is already processing a request for this render
  // view.
  bool IsUIBusy(int render_process_id, int render_view_id);

  // Process the next pending request and bring it up to the UI on the given
  // page for user approval.
  void ProcessNextRequestForView(int render_process_id, int render_view_id);

  // Posts a request to be approved/denied by UI.
  void PostRequestToUI(const std::string& label);

  // Posts a request to fake UI which is used for testing purpose.
  void PostRequestToFakeUI(const std::string& label);

  SettingsRequester* requester_;
  UIRequests requests_;

  // See comment above for method UseFakeUI. Used for automated testing.
  bool use_fake_ui_;

  base::WeakPtrFactory<MediaStreamUIController> weak_ptr_factory_;

  DISALLOW_COPY_AND_ASSIGN(MediaStreamUIController);
};

}  // namespace content

#endif  // CONTENT_BROWSER_RENDERER_HOST_MEDIA_MEDIA_STREAM_UI_CONTROLLER_H_


text:
from oslo_config import cfg
import six

from sahara import conductor as c
from sahara import context
from sahara.service.castellan import utils as key_manager
from sahara.service.edp.oozie.workflow_creator import hive_workflow
from sahara.service.edp.oozie.workflow_creator import java_workflow
from sahara.service.edp.oozie.workflow_creator import mapreduce_workflow
from sahara.service.edp.oozie.workflow_creator import pig_workflow
from sahara.service.edp.oozie.workflow_creator import shell_workflow
from sahara.swift import swift_helper as sw
from sahara.swift import utils as su
from sahara.utils import edp
from sahara.utils import xmlutils

conductor = c.API
CONF = cfg.CONF

class BaseFactory(object):
    def _separate_edp_configs(self, job_dict):
        configs = {}
        edp_configs = {}
        if 'configs' in job_dict:
            for k, v in six.iteritems(job_dict['configs']):
                if k.startswith('edp.'):
                    edp_configs[k] = v
                elif not k.startswith('oozie.'):
                    # 'oozie.' configs have been written to the properties file
                    configs[k] = v
        return configs, edp_configs

    def _prune_edp_configs(self, job_dict):
        if job_dict is None:
            return {}, {}

        # Rather than copy.copy, we make this by hand
        # to avoid FrozenClassError when we update 'configs'
        pruned_job_dict = {}
        for k, v in six.iteritems(job_dict):
            pruned_job_dict[k] = v

        # Separate out "edp." configs into its own dictionary
        configs, edp_configs = self._separate_edp_configs(job_dict)

        # Prune the new job_dict so it does not hold "edp." configs
        pruned_job_dict['configs'] = configs

        return pruned_job_dict, edp_configs

    def _update_dict(self, dest, src):
        if src is not None:
            for key, value in six.iteritems(dest):
                if hasattr(value, "update"):
                    new_vals = src.get(key, {})
                    value.update(new_vals)

    def update_job_dict(self, job_dict, exec_dict):
        pruned_exec_dict, edp_configs = self._prune_edp_configs(exec_dict)
        self._update_dict(job_dict, pruned_exec_dict)

        # Add the separated "edp." configs to the job_dict
        job_dict['edp_configs'] = edp_configs

        # Args are listed, not named. Simply replace them.
        job_dict['args'] = pruned_exec_dict.get('args', [])

        # Find all swift:// paths in args, configs, and params and
        # add the .sahara suffix to the container if it is not there
        # already
        job_dict['args'] = [
            # TODO(tmckay) args for Pig can actually be -param name=value
            # and value could conceivably contain swift paths
            su.inject_swift_url_suffix(arg) for arg in job_dict['args']]

        for k, v in six.iteritems(job_dict.get('configs', {})):
            job_dict['configs'][k] = su.inject_swift_url_suffix(v)

        for k, v in six.iteritems(job_dict.get('params', {})):
            job_dict['params'][k] = su.inject_swift_url_suffix(v)

    def get_configs(self, input_data, output_data, proxy_configs=None):
        configs = {}

        if proxy_configs:
            configs[sw.HADOOP_SWIFT_USERNAME] = proxy_configs.get(
                'proxy_username')
            configs[sw.HADOOP_SWIFT_PASSWORD] = key_manager.get_secret(
                proxy_configs.get('proxy_password'))
            configs[sw.HADOOP_SWIFT_TRUST_ID] = proxy_configs.get(
                'proxy_trust_id')
            configs[sw.HADOOP_SWIFT_DOMAIN_NAME] = CONF.proxy_user_domain_name
            return configs

        for src in (input_data, output_data):
            if src.type == "swift" and hasattr(src, "credentials"):
                if "user" in src.credentials:
                    configs[sw.HADOOP_SWIFT_USERNAME] = src.credentials['user']
                if "password" in src.credentials:
                    configs[sw.HADOOP_SWIFT_PASSWORD] = (
                        key_manager.get_secret(src.credentials['password']))
                break
        return configs

    def get_params(self, input_data, output_data, data_source_urls):
        return {'INPUT': data_source_urls[input_data.id],
                'OUTPUT': data_source_urls[output_data.id]}

class PigFactory(BaseFactory):
    def __init__(self, job):
        super(PigFactory, self).__init__()

        self.name = self.get_script_name(job)

    def get_script_name(self, job):
        return conductor.job_main_name(context.ctx(), job)

    def get_workflow_xml(self, cluster, job_configs, input_data, output_data,
                         hdfs_user, data_source_urls):
        proxy_configs = job_configs.get('proxy_configs')
        job_dict = {'configs': self.get_configs(input_data, output_data,
                                                proxy_configs),
                    'params': self.get_params(input_data, output_data,
                                              data_source_urls),
                    'args': []}
        self.update_job_dict(job_dict, job_configs)
        creator = pig_workflow.PigWorkflowCreator()
        creator.build_workflow_xml(self.name,
                                   configuration=job_dict['configs'],
                                   params=job_dict['params'],
                                   arguments=job_dict['args'])
        return creator.get_built_workflow_xml()

class HiveFactory(BaseFactory):
    def __init__(self, job):
        super(HiveFactory, self).__init__()

        self.name = self.get_script_name(job)

    def get_script_name(self, job):
        return conductor.job_main_name(context.ctx(), job)

    def get_workflow_xml(self, cluster, job_configs, input_data, output_data,
                         hdfs_user, data_source_urls):
        proxy_configs = job_configs.get('proxy_configs')
        job_dict = {'configs': self.get_configs(input_data, output_data,
                                                proxy_configs),
                    'params': self.get_params(input_data, output_data,
                                              data_source_urls)}
        self.update_job_dict(job_dict, job_configs)

        creator = hive_workflow.HiveWorkflowCreator()
        creator.build_workflow_xml(self.name,
                                   edp.get_hive_shared_conf_path(hdfs_user),
                                   configuration=job_dict['configs'],
                                   params=job_dict['params'])
        return creator.get_built_workflow_xml()

class MapReduceFactory(BaseFactory):

    def get_configs(self, input_data, output_data, proxy_configs,
                    data_source_urls):
        configs = super(MapReduceFactory, self).get_configs(input_data,
                                                            output_data,
                                                            proxy_configs)
        configs['mapred.input.dir'] = data_source_urls[input_data.id]
        configs['mapred.output.dir'] = data_source_urls[output_data.id]
        return configs

    def _get_streaming(self, job_dict):
        prefix = 'edp.streaming.'
        return {k[len(prefix):]: v for (k, v) in six.iteritems(
            job_dict['edp_configs']) if k.startswith(prefix)}

    def get_workflow_xml(self, cluster, job_configs, input_data, output_data,
                         hdfs_user, data_source_urls):
        proxy_configs = job_configs.get('proxy_configs')
        job_dict = {'configs': self.get_configs(input_data, output_data,
                                                proxy_configs,
                                                data_source_urls)}
        self.update_job_dict(job_dict, job_configs)
        creator = mapreduce_workflow.MapReduceWorkFlowCreator()
        creator.build_workflow_xml(configuration=job_dict['configs'],
                                   streaming=self._get_streaming(job_dict))
        return creator.get_built_workflow_xml()

class JavaFactory(BaseFactory):

    def _get_java_configs(self, job_dict):
        main_class = job_dict['edp_configs']['edp.java.main_class']
        java_opts = job_dict['edp_configs'].get('edp.java.java_opts', None)
        args = job_dict['args']
        if edp.is_adapt_for_oozie_enabled(job_dict['edp_configs']):
            if args:
                args = [main_class] + args
            else:
                args = [main_class]
            main_class = 'org.openstack.sahara.edp.MainWrapper'
        return main_class, java_opts, args

    def get_configs(self, proxy_configs=None):
        configs = {}

        if proxy_configs:
            configs[sw.HADOOP_SWIFT_USERNAME] = proxy_configs.get(
                'proxy_username')
            configs[sw.HADOOP_SWIFT_PASSWORD] = key_manager.get_secret(
                proxy_configs.get('proxy_password'))
            configs[sw.HADOOP_SWIFT_TRUST_ID] = proxy_configs.get(
                'proxy_trust_id')
            configs[sw.HADOOP_SWIFT_DOMAIN_NAME] = CONF.proxy_user_domain_name
            return configs

        return configs

    def get_workflow_xml(self, cluster, job_configs, *args, **kwargs):
        proxy_configs = job_configs.get('proxy_configs')
        job_dict = {'configs': self.get_configs(proxy_configs=proxy_configs),
                    'args': []}
        self.update_job_dict(job_dict, job_configs)

        main_class, java_opts, args = self._get_java_configs(job_dict)
        creator = java_workflow.JavaWorkflowCreator()
        creator.build_workflow_xml(main_class,
                                   configuration=job_dict['configs'],
                                   java_opts=java_opts,
                                   arguments=args)
        return creator.get_built_workflow_xml()

class ShellFactory(BaseFactory):

    def __init__(self, job):
        self.name, self.file_names = self.get_file_names(job)

    def get_file_names(self, job):
        ctx = context.ctx()
        return (conductor.job_main_name(ctx, job),
                conductor.job_lib_names(ctx, job))

    def get_configs(self):
        return {'configs': {},
                'params': {},
                'args': []}

    def get_workflow_xml(self, cluster, job_configs, *args, **kwargs):
        job_dict = self.get_configs()
        self.update_job_dict(job_dict, job_configs)
        creator = shell_workflow.ShellWorkflowCreator()
        creator.build_workflow_xml(self.name,
                                   configuration=job_dict['configs'],
                                   env_vars=job_dict['params'],
                                   arguments=job_dict['args'],
                                   files=self.file_names)
        return creator.get_built_workflow_xml()

def _get_creator(job):

    def make_PigFactory():
        return PigFactory(job)

    def make_HiveFactory():
        return HiveFactory(job)

    def make_ShellFactory():
        return ShellFactory(job)

    type_map = {
        edp.JOB_TYPE_HIVE: make_HiveFactory,
        edp.JOB_TYPE_JAVA: JavaFactory,
        edp.JOB_TYPE_MAPREDUCE: MapReduceFactory,
        edp.JOB_TYPE_MAPREDUCE_STREAMING: MapReduceFactory,
        edp.JOB_TYPE_PIG: make_PigFactory,
        edp.JOB_TYPE_SHELL: make_ShellFactory
    }

    return type_map[job.type]()

def get_workflow_xml(job, cluster, job_configs, *args, **kwargs):
    return _get_creator(job).get_workflow_xml(
        cluster, job_configs, *args, **kwargs)

def get_possible_job_config(job_type):
    if not edp.compare_job_type(job_type, *edp.JOB_TYPES_ALL):
        return None

    if edp.compare_job_type(job_type, edp.JOB_TYPE_JAVA):
        return {'job_config': {'configs': [], 'args': []}}

    if edp.compare_job_type(job_type, edp.JOB_TYPE_SHELL):
        return {'job_config': {'configs': [], 'params': {}, 'args': []}}

    if edp.compare_job_type(job_type,
                            edp.JOB_TYPE_MAPREDUCE, edp.JOB_TYPE_PIG):
        cfg = xmlutils.load_hadoop_xml_defaults(
            'service/edp/resources/mapred-default.xml')
        if edp.compare_job_type(job_type, edp.JOB_TYPE_MAPREDUCE):
            cfg += get_possible_mapreduce_configs()
    elif edp.compare_job_type(job_type, edp.JOB_TYPE_HIVE):
        cfg = xmlutils.load_hadoop_xml_defaults(
            'service/edp/resources/hive-default.xml')

    config = {'configs': cfg}
    if edp.compare_job_type(job_type, edp.JOB_TYPE_PIG, edp.JOB_TYPE_HIVE):
        config.update({'params': {}})
    if edp.compare_job_type(job_type, edp.JOB_TYPE_PIG):
        config.update({'args': []})
    return {'job_config': config}

def get_possible_mapreduce_configs():
    '''return a list of possible configuration values for map reduce jobs.'''
    cfg = xmlutils.load_hadoop_xml_defaults(
        'service/edp/resources/mapred-job-config.xml')
    return cfg


text:
#ifndef PageActivityAssertionToken_h
#define PageActivityAssertionToken_h

#include <wtf/Noncopyable.h>

namespace WebCore {

class PageThrottler;

class PageActivityAssertionToken {
    WTF_MAKE_NONCOPYABLE(PageActivityAssertionToken);
public:
    ~PageActivityAssertionToken();

    void invalidate();

private:
    friend class Page;
    PageActivityAssertionToken(PageThrottler*);

    PageThrottler* m_throttler;
};

}

#endif // PageActivityAssertionToken_h


text:
""" A universal module with functions / classes without dependencies. """
import sys
import contextlib
import functools
import re
from ast import literal_eval

from jedi._compatibility import unicode, reraise
from jedi import settings

class UncaughtAttributeError(Exception):
    """
    Important, because `__getattr__` and `hasattr` catch AttributeErrors
    implicitly. This is really evil (mainly because of `__getattr__`).
    `hasattr` in Python 2 is even more evil, because it catches ALL exceptions.
    Therefore this class originally had to be derived from `BaseException`
    instead of `Exception`.  But because I removed relevant `hasattr` from
    the code base, we can now switch back to `Exception`.

    :param base: return values of sys.exc_info().
    """

def safe_property(func):
    return property(reraise_uncaught(func))

def reraise_uncaught(func):
    """
    Re-throw uncaught `AttributeError`.

    Usage:  Put ``@rethrow_uncaught`` in front of the function
    which does **not** suppose to raise `AttributeError`.

    AttributeError is easily get caught by `hasattr` and another
    ``except AttributeError`` clause.  This becomes problem when you use
    a lot of "dynamic" attributes (e.g., using ``@property``) because you
    can't distinguish if the property does not exist for real or some code
    inside of the "dynamic" attribute through that error.  In a well
    written code, such error should not exist but getting there is very
    difficult.  This decorator is to help us getting there by changing
    `AttributeError` to `UncaughtAttributeError` to avoid unexpected catch.
    This helps us noticing bugs earlier and facilitates debugging.

    .. note:: Treating StopIteration here is easy.
              Add that feature when needed.
    """
    @functools.wraps(func)
    def wrapper(*args, **kwds):
        try:
            return func(*args, **kwds)
        except AttributeError:
            exc_info = sys.exc_info()
            reraise(UncaughtAttributeError(exc_info[1]), exc_info[2])
    return wrapper

class PushBackIterator(object):
    def __init__(self, iterator):
        self.pushes = []
        self.iterator = iterator
        self.current = None

    def push_back(self, value):
        self.pushes.append(value)

    def __iter__(self):
        return self

    def next(self):
        """ Python 2 Compatibility """
        return self.__next__()

    def __next__(self):
        if self.pushes:
            self.current = self.pushes.pop()
        else:
            self.current = next(self.iterator)
        return self.current

@contextlib.contextmanager
def scale_speed_settings(factor):
    a = settings.max_executions
    b = settings.max_until_execution_unique
    settings.max_executions *= factor
    settings.max_until_execution_unique *= factor
    try:
        yield
    finally:
        settings.max_executions = a
        settings.max_until_execution_unique = b

def indent_block(text, indention='    '):
    """This function indents a text block with a default of four spaces."""
    temp = ''
    while text and text[-1] == '\n':
        temp += text[-1]
        text = text[:-1]
    lines = text.split('\n')
    return '\n'.join(map(lambda s: indention + s, lines)) + temp

@contextlib.contextmanager
def ignored(*exceptions):
    """
    Context manager that ignores all of the specified exceptions. This will
    be in the standard library starting with Python 3.4.
    """
    try:
        yield
    except exceptions:
        pass

def source_to_unicode(source, encoding=None):
    def detect_encoding():
        """
        For the implementation of encoding definitions in Python, look at:
        - http://www.python.org/dev/peps/pep-0263/
        - http://docs.python.org/2/reference/lexical_analysis.html#encoding-declarations
        """
        byte_mark = literal_eval(r"b'\xef\xbb\xbf'")
        if source.startswith(byte_mark):
            # UTF-8 byte-order mark
            return 'utf-8'

        first_two_lines = re.match(r'(?:[^\n]*\n){0,2}', str(source)).group(0)
        possible_encoding = re.search(r"coding[=:]\s*([-\w.]+)",
                                      first_two_lines)
        if possible_encoding:
            return possible_encoding.group(1)
        else:
            # the default if nothing else has been set -> PEP 263
            return encoding if encoding is not None else 'iso-8859-1'

    if isinstance(source, unicode):
        # only cast str/bytes
        return source

    # cast to unicode by default
    return unicode(source, detect_encoding(), 'replace')

def splitlines(string):
    """
    A splitlines for Python code. In contrast to Python's ``str.splitlines``,
    looks at form feeds and other special characters as normal text. Just
    splits ``\n`` and ``\r\n``.
    Also different: Returns ``['']`` for an empty string input.
    """
    return re.split('\n|\r\n', string)


text:
<!DOCTYPE html>

 <link rel="icon" type="image/ico" href="favicon.ico">
<title>RFClean</title>

Welcome!

This site is still under construction. Come back later for cool new stuff!


text: js downloader


text:
<?php
// WARNING, this is a read only file created by import scripts
// WARNING
// WARNING,  Changes made to this file will be clobbered
// WARNING
// WARNING,  Please make changes on poeditor instead of here
//
//
?>
subject: Гостевой ваучер отправлен

{alternative:plain}

Товарищ!

Ваучер для доступа к {cfg:site_name} был отправлен {guest.email}.

С наилучшими пожеланиями,
{cfg:site_name}

{alternative:html}

    Товарищ!

    Ваучер для доступа к {cfg:site_name} был отправлен {guest.email}.

    С наилучшими пожеланиями,

    {cfg:site_name}


text:
function Remove-IisMimeMap
{
    <#
    .SYNOPSIS
    Removes a file extension to MIME type map from an entire web server.

    .DESCRIPTION
    IIS won't serve static files unless they have an entry in the MIME map.  Use this function toremvoe an existing MIME map entry.  If one doesn't exist, nothing happens.  Not even an error.

    If a specific website has the file extension in its MIME map, that site will continue to serve files with those extensions.

    .LINK
    Get-IisMimeMap

    .LINK
    Set-IisMimeMap

    .EXAMPLE
    Remove-IisMimeMap -FileExtension '.m4v' -MimeType 'video/x-m4v'

    Removes the `.m4v` file extension so that IIS will no longer serve those files.
    #>
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true)]
        [string]
        # The file extension whose MIME map to remove.
        $FileExtension
    )

    $staticContent = Get-IisConfigurationSection -SectionPath 'system.webServer/staticContent'
    $mimeMapCollection = $staticContent.GetCollection()
    $mimeMapToRemove = $mimeMapCollection |
                            Where-Object { $_['fileExtension'] -eq $FileExtension }
    if( -not $mimeMapToRemove )
    {
        Write-Verbose ('MIME map for file extension {0} not found.' -f $FileExtension)
        return
    }

    $mimeMapCollection.Remove( $mimeMapToRemove )
    $staticContent.CommitChanges()
}


text:
package org.apache.ignite.testframework.junits;

import javax.cache.Cache;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.IgniteTransactions;
import org.apache.ignite.Ignition;
import org.apache.ignite.cache.CacheAtomicityMode;
import org.apache.ignite.cache.CacheMemoryMode;
import org.apache.ignite.cache.CacheMode;
import org.apache.ignite.cache.CachePeekMode;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.configuration.NearCacheConfiguration;
import org.apache.ignite.internal.IgniteEx;
import org.apache.ignite.internal.IgniteKernal;
import org.apache.ignite.internal.cluster.ClusterTopologyCheckedException;
import org.apache.ignite.internal.processors.cache.GridCacheContext;
import org.apache.ignite.internal.processors.cache.H2CacheStoreStrategy;
import org.apache.ignite.internal.processors.cache.MapCacheStoreStrategy;
import org.apache.ignite.internal.processors.cache.TestCacheStoreStrategy;
import org.apache.ignite.internal.util.lang.GridAbsPredicateX;
import org.apache.ignite.internal.util.typedef.X;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.testframework.GridTestUtils;
import org.apache.ignite.testframework.configvariations.CacheStartMode;
import org.apache.ignite.transactions.Transaction;
import org.jetbrains.annotations.Nullable;

import static org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL;
import static org.apache.ignite.cache.CacheMemoryMode.OFFHEAP_TIERED;
import static org.apache.ignite.cache.CacheMemoryMode.ONHEAP_TIERED;

/**
 * Abstract class for cache configuration variations tests.
 */
public abstract class IgniteCacheConfigVariationsAbstractTest extends IgniteConfigVariationsAbstractTest {
    /** */
    protected static final int CLIENT_NEAR_ONLY_IDX = 2;

    /** Test timeout. */
    private static final long TEST_TIMEOUT = 30 * 1000;

    /** */
    protected static TestCacheStoreStrategy storeStgy;

    /** {@inheritDoc} */
    @Override protected long getTestTimeout() {
        return TEST_TIMEOUT;
    }

    /** {@inheritDoc} */
    @Override protected final void beforeTestsStarted() throws Exception {
        initStoreStrategy();
        assert testsCfg != null;
        assert !testsCfg.withClients() || testsCfg.gridCount() >= 3;

        assert testsCfg.testedNodeIndex() >= 0 : "testedNodeIdx: " + testedNodeIdx;

        testedNodeIdx = testsCfg.testedNodeIndex();

        if (testsCfg.isStartCache()) {
            final CacheStartMode cacheStartMode = testsCfg.cacheStartMode();
            final int cnt = testsCfg.gridCount();

            if (cacheStartMode == CacheStartMode.STATIC) {
                info("All nodes will be stopped, new " + cnt + " nodes will be started.");

                Ignition.stopAll(true);

                for (int i = 0; i < cnt; i++) {
                    String gridName = getTestGridName(i);

                    IgniteConfiguration cfg = optimize(getConfiguration(gridName));

                    if (i != CLIENT_NODE_IDX && i != CLIENT_NEAR_ONLY_IDX) {
                        CacheConfiguration cc = cacheConfiguration();

                        cc.setName(cacheName());

                        cfg.setCacheConfiguration(cc);
                    }

                    startGrid(gridName, cfg, null);
                }

                if (testsCfg.withClients() && testsCfg.gridCount() > CLIENT_NEAR_ONLY_IDX)
                    grid(CLIENT_NEAR_ONLY_IDX).createNearCache(cacheName(), new NearCacheConfiguration());
            }
            else if (cacheStartMode == null || cacheStartMode == CacheStartMode.DYNAMIC) {
                super.beforeTestsStarted();

                startCachesDinamically();
            }
            else
                throw new IllegalArgumentException("Unknown cache start mode: " + cacheStartMode);
        }

        if (testsCfg.gridCount() > 1)
            checkTopology(testsCfg.gridCount());

        awaitPartitionMapExchange();

        for (int i = 0; i < gridCount(); i++)
            info("Grid " + i + ": " + grid(i).localNode().id());

        if (testsCfg.withClients()) {
            if (testedNodeIdx != SERVER_NODE_IDX)
                assertEquals(testedNodeIdx == CLIENT_NEAR_ONLY_IDX, nearEnabled());

            info(">>> Starting set of tests [testedNodeIdx=" + testedNodeIdx
                + ", id=" + grid(testedNodeIdx).localNode().id()
                + ", isClient=" + isClientMode()
                + ", nearEnabled=" + nearEnabled() + "]");
        }
    }

    /** Initialize {@link #storeStgy} with respect to the nature of the test */
    void initStoreStrategy() throws IgniteCheckedException {
        if (storeStgy == null)
            storeStgy = isMultiJvm() ? new H2CacheStoreStrategy() : new MapCacheStoreStrategy();
    }

    /**
     * Starts caches dynamically.
     *
     * @throws Exception If failed.
     */
    private void startCachesDinamically() throws Exception {
        for (int i = 0; i < gridCount(); i++) {
            info("Starting cache dinamically on grid: " + i);

            IgniteEx grid = grid(i);

            if (i != CLIENT_NODE_IDX && i != CLIENT_NEAR_ONLY_IDX) {
                CacheConfiguration cc = cacheConfiguration();

                cc.setName(cacheName());

                grid.getOrCreateCache(cc);
            }

            if (testsCfg.withClients() && i == CLIENT_NEAR_ONLY_IDX && grid(i).configuration().isClientMode())
                grid(CLIENT_NEAR_ONLY_IDX).createNearCache(cacheName(), new NearCacheConfiguration());
        }

        awaitPartitionMapExchange();

        for (int i = 0; i < gridCount(); i++)
            assertNotNull(jcache(i));

        for (int i = 0; i < gridCount(); i++)
            assertEquals("Cache is not empty [idx=" + i + ", entrySet=" + jcache(i).localEntries() + ']',
                0, jcache(i).localSize(CachePeekMode.ALL));
    }

    /** {@inheritDoc} */
    @Override protected boolean expectedClient(String testGridName) {
        return getTestGridName(CLIENT_NODE_IDX).equals(testGridName)
            || getTestGridName(CLIENT_NEAR_ONLY_IDX).equals(testGridName);
    }

    /** {@inheritDoc} */
    @Override protected void afterTestsStopped() throws Exception {
        if (testsCfg.isStopCache()) {
            for (int i = 0; i < gridCount(); i++) {
                info("Destroing cache on grid: " + i);

                IgniteCache<String, Integer> cache = jcache(i);

                assert i != 0 || cache != null;

                if (cache != null)
                    cache.destroy();
            }
        }

        storeStgy.resetStore();

        super.afterTestsStopped();
    }

    /** {@inheritDoc} */
    @Override protected void beforeTest() throws Exception {
        super.beforeTest();

        if (testsCfg.awaitPartitionMapExchange())
            awaitPartitionMapExchange();

        assert jcache().unwrap(Ignite.class).transactions().tx() == null;

        assertEquals(0, jcache().localSize());
        assertEquals(0, jcache().size());
    }

    /** {@inheritDoc} */
    @Override protected void afterTest() throws Exception {
        Transaction tx = jcache().unwrap(Ignite.class).transactions().tx();

        if (tx != null) {
            tx.close();

            fail("Cache transaction remained after test completion: " + tx);
        }

        String cacheIsNotEmptyMsg = null;

        for (int i = 0; i < gridCount(); i++) {
            info("Checking grid: " + i);

            while (true) {
                try {
                    final int fi = i;

                    boolean cacheIsEmpty = GridTestUtils.waitForCondition(
                        // Preloading may happen as nodes leave, so we need to wait.
                        new GridAbsPredicateX() {
                            @Override public boolean applyx() throws IgniteCheckedException {
                                jcache(fi).removeAll();

                                if (jcache(fi).size(CachePeekMode.ALL) > 0) {
                                    for (Cache.Entry<?, ?> k : jcache(fi).localEntries())
                                        jcache(fi).remove(k.getKey());
                                }

                                int locSize = jcache(fi).localSize(CachePeekMode.ALL);

                                if (locSize != 0) {
                                    info(">>>>> Debug localSize for grid: " + fi + " is " + locSize);
                                    info(">>>>> Debug ONHEAP  localSize for grid: " + fi + " is "
                                        + jcache(fi).localSize(CachePeekMode.ONHEAP));
                                    info(">>>>> Debug OFFHEAP localSize for grid: " + fi + " is "
                                        + jcache(fi).localSize(CachePeekMode.OFFHEAP));
                                    info(">>>>> Debug PRIMARY localSize for grid: " + fi + " is "
                                        + jcache(fi).localSize(CachePeekMode.PRIMARY));
                                    info(">>>>> Debug BACKUP  localSize for grid: " + fi + " is "
                                        + jcache(fi).localSize(CachePeekMode.BACKUP));
                                    info(">>>>> Debug NEAR    localSize for grid: " + fi + " is "
                                        + jcache(fi).localSize(CachePeekMode.NEAR));
                                    info(">>>>> Debug SWAP    localSize for grid: " + fi + " is "
                                        + jcache(fi).localSize(CachePeekMode.SWAP));
                                }

                                return locSize == 0;
                            }
                        }, 10_000);

                    if (cacheIsEmpty)
                        assertTrue("Cache is not empty: " + " localSize = " + jcache(fi).localSize(CachePeekMode.ALL)
                            + ", local entries " + entrySet(jcache(fi).localEntries()), cacheIsEmpty);

                    int primaryKeySize = jcache(i).localSize(CachePeekMode.PRIMARY);
                    int keySize = jcache(i).localSize();
                    int size = jcache(i).localSize();
                    int globalSize = jcache(i).size();
                    int globalPrimarySize = jcache(i).size(CachePeekMode.PRIMARY);

                    info("Size after [idx=" + i +
                        ", size=" + size +
                        ", keySize=" + keySize +
                        ", primarySize=" + primaryKeySize +
                        ", globalSize=" + globalSize +
                        ", globalPrimarySize=" + globalPrimarySize +
                        ", entrySet=" + jcache(i).localEntries() + ']');

                    if (!cacheIsEmpty) {
                        cacheIsNotEmptyMsg = "Cache is not empty: localSize = "
                            + jcache(fi).localSize(CachePeekMode.ALL) + ", local entries "
                            + entrySet(jcache(fi).localEntries());

                        break;
                    }

                    assertEquals("Cache is not empty [idx=" + i + ", entrySet=" + jcache(i).localEntries() + ']',
                        0, jcache(i).localSize(CachePeekMode.ALL));

                    break;
                }
                catch (Exception e) {
                    if (X.hasCause(e, ClusterTopologyCheckedException.class)) {
                        info("Got topology exception while tear down (will retry in 1000ms).");

                        U.sleep(1000);
                    }
                    else
                        throw e;
                }
            }

            if (cacheIsNotEmptyMsg != null)
                break;

            for (Cache.Entry entry : jcache(i).localEntries(CachePeekMode.SWAP))
                jcache(i).remove(entry.getKey());
        }

        assert jcache().unwrap(Ignite.class).transactions().tx() == null;

        if (cacheIsNotEmptyMsg == null)
            assertEquals("Cache is not empty", 0, jcache().localSize(CachePeekMode.ALL));

        storeStgy.resetStore();

        // Restore cache if current cache has garbage.
        if (cacheIsNotEmptyMsg != null) {
            for (int i = 0; i < gridCount(); i++) {
                info("Destroing cache on grid: " + i);

                IgniteCache<String, Integer> cache = jcache(i);

                assert i != 0 || cache != null;

                if (cache != null)
                    cache.destroy();
            }

            assertTrue(GridTestUtils.waitForCondition(new GridAbsPredicateX() {
                @Override public boolean applyx() {
                    for (int i = 0; i < gridCount(); i++) {
                        if (jcache(i) != null)
                            return false;
                    }

                    return true;
                }
            }, 10_000));

            startCachesDinamically();

            log.warning(cacheIsNotEmptyMsg);

            throw new IllegalStateException(cacheIsNotEmptyMsg);
        }

        assertEquals(0, jcache().localSize());
        assertEquals(0, jcache().size());
    }

    /**
     * Put entry to cache store.
     *
     * @param key Key.
     * @param val Value.
     */
    protected void putToStore(Object key, Object val) {
        if (!storeEnabled())
            throw new IllegalStateException("Failed to put to store because store is disabled.");

        storeStgy.putToStore(key, val);
    }

    /**
     * @return Default cache mode.
     */
    protected CacheMode cacheMode() {
        CacheMode mode = cacheConfiguration().getCacheMode();

        return mode == null ? CacheConfiguration.DFLT_CACHE_MODE : mode;
    }

    /**
     * @return Load previous value flag.
     */
    protected boolean isLoadPreviousValue() {
        return cacheConfiguration().isLoadPreviousValue();
    }

    /**
     * @return Cache atomicity mode.
     */
    protected CacheAtomicityMode atomicityMode() {
        return cacheConfiguration().getAtomicityMode();
    }

    /**
     * @return {@code True} if values should be stored off-heap.
     */
    protected CacheMemoryMode memoryMode() {
        return cacheConfiguration().getMemoryMode();
    }

    /**
     * @return {@code True} if swap should happend after localEvict() call.
     */
    protected boolean swapAfterLocalEvict() {
        if (memoryMode() == OFFHEAP_TIERED)
            return false;

        return memoryMode() == ONHEAP_TIERED ? (!offheapEnabled() && swapEnabled()) : swapEnabled();
    }

    /**
     * @return {@code True} if store is enabled.
     */
    protected boolean storeEnabled() {
        return cacheConfiguration().getCacheStoreFactory() != null;
    }

    /**
     * @return {@code True} if offheap memory is enabled.
     */
    protected boolean offheapEnabled() {
        return cacheConfiguration().getOffHeapMaxMemory() >= 0;
    }

    /**
     * @return {@code True} if swap is enabled.
     */
    protected boolean swapEnabled() {
        return cacheConfiguration().isSwapEnabled();
    }

    /**
     * @return {@code true} if near cache should be enabled.
     */
    protected boolean nearEnabled() {
        return grid(testedNodeIdx).cachex(cacheName()).context().isNear();
    }

    /**
     * @return {@code True} if transactions are enabled.
     * @see #txShouldBeUsed()
     */
    protected boolean txEnabled() {
        return atomicityMode() == TRANSACTIONAL;
    }

    /**
     * @return Cache configuration.
     */
    protected CacheConfiguration cacheConfiguration() {
        return testsCfg.configurationFactory().cacheConfiguration(getTestGridName(testedNodeIdx));
    }

    /**
     * @return {@code True} if transactions should be used.
     */
    protected boolean txShouldBeUsed() {
        return txEnabled() && !isMultiJvm();
    }

    /**
     * @return {@code True} if locking is enabled.
     */
    protected boolean lockingEnabled() {
        return txEnabled();
    }

    /**
     * @return Default cache instance.
     */
    @SuppressWarnings({"unchecked"})
    @Override protected <K, V> IgniteCache<K, V> jcache() {
        return jcache(testedNodeIdx);
    }

    /**
     * @return A not near-only cache.
     */
    protected IgniteCache<String, Integer> serverNodeCache() {
        return jcache(SERVER_NODE_IDX);
    }

    /**
     * @return Cache name.
     */
    protected String cacheName() {
        return "testcache-" + testsCfg.description().hashCode();
    }

    /**
     * @return Transactions instance.
     */
    protected IgniteTransactions transactions() {
        return grid(0).transactions();
    }

    /**
     * @param idx Index of grid.
     * @return Default cache.
     */
    @SuppressWarnings({"unchecked"})
    @Override protected <K, V> IgniteCache<K, V> jcache(int idx) {
        return ignite(idx).cache(cacheName());
    }

    /**
     * @param idx Index of grid.
     * @return Cache context.
     */
    protected GridCacheContext<String, Integer> context(final int idx) {
        if (isRemoteJvm(idx) && !isRemoteJvm())
            throw new UnsupportedOperationException("Operation can't be done automatically via proxy. " +
                "Send task with this logic on remote jvm instead.");

        return ((IgniteKernal)grid(idx)).<String, Integer>internalCache(cacheName()).context();
    }

    /**
     * @param cache Cache.
     * @return {@code True} if cache has OFFHEAP_TIERED memory mode.
     */
    protected static <K, V> boolean offheapTiered(IgniteCache<K, V> cache) {
        return cache.getConfiguration(CacheConfiguration.class).getMemoryMode() == OFFHEAP_TIERED;
    }

    /**
     * Executes regular peek or peek from swap.
     *
     * @param cache Cache projection.
     * @param key Key.
     * @return Value.
     */
    @Nullable protected static <K, V> V peek(IgniteCache<K, V> cache, K key) {
        return offheapTiered(cache) ? cache.localPeek(key, CachePeekMode.SWAP, CachePeekMode.OFFHEAP) :
            cache.localPeek(key, CachePeekMode.ONHEAP);
    }

    /**
     * @param cache Cache.
     * @param key Key.
     * @return {@code True} if cache contains given key.
     * @throws Exception If failed.
     */
    @SuppressWarnings("unchecked")
    protected static boolean containsKey(IgniteCache cache, Object key) throws Exception {
        return offheapTiered(cache) ? cache.localPeek(key, CachePeekMode.OFFHEAP) != null : cache.containsKey(key);
    }
}


text:
import {client as WebSocketClient} from "websocket"
import query from "./database"
import {sleep} from "./misc"

const endpoint = "wss://qa.sockets.stackexchange.com/"

var connection
   ,connected = false
   ,messageQueue = []
   ,reconnectAttempts = 0

const emit = function(message) {
  if (!connected) messageQueue.push(message)
  else connection.sendUTF(message)
}

const subscriptions = {}

export const subscribe = function(action, callback) {
  if (action in subscriptions) throw new Error("This action has already been subscribed.")
  subscriptions[action] = callback
  emit(action)
}
export const unsubscribe = function(action) {
  if (action in subscriptions) {
    emit(`-${action}`)
    Reflect.deleteProperty(subscriptions, action)
  }
}

const handleMessage = function(rawMessage) {
  const {action, data: rawData} = JSON.parse(rawMessage.utf8Data)
       ,data = JSON.parse(rawData)
  if (action in subscriptions) {
    subscriptions[action](data)
  }
}

const client = new WebSocketClient()

client.on("connect", newConnection=> {
  connection = newConnection
  connected = true
  reconnectAttempts = 0
  connection.on("message", handleMessage)
  connection.on("close", async (reasonCode, description)=> {
    connected = false
    if (++reconnectAttempts <= 5) {
      await sleep(5000)
      client.connect(endpoint)
    } else {
      throw new Error("Couldn't reconnect to WebSockets endpoint.")
    }
  })
  messageQueue.forEach(connection.sendUTF.bind(connection))
  messageQueue = []
})

client.on("connectFailed", errorDescription=> {
  throw new Error(`WebSocket connection failed, error: ${errorDescription}`)
})

client.connect(endpoint, null, null, {
  "User-Agent": `New-SO-Review/${require("../package.json").version} (https://github.com/Gothdo/New-SO-Review)`
})