text:
"""celery.backends.base"""
from __future__ import absolute_import

import time
import sys

from datetime import timedelta

from kombu import serialization

from .. import states
from ..datastructures import LRUCache
from ..exceptions import TimeoutError, TaskRevokedError
from ..utils import timeutils
from ..utils.encoding import bytes_to_str, ensure_bytes, from_utf8
from ..utils.serialization import (get_pickled_exception,
                                   get_pickleable_exception,
                                   create_exception_cls)

EXCEPTION_ABLE_CODECS = frozenset(["pickle", "yaml"])
is_py3k = sys.version_info >= (3, 0)

def unpickle_backend(cls, args, kwargs):
    """Returns an unpickled backend."""
    return cls(*args, **kwargs)

class BaseBackend(object):
    """Base backend class."""
    READY_STATES = states.READY_STATES
    UNREADY_STATES = states.UNREADY_STATES
    EXCEPTION_STATES = states.EXCEPTION_STATES

    TimeoutError = TimeoutError

    #: Time to sleep between polling each individual item
    #: in `ResultSet.iterate`. as opposed to the `interval`
    #: argument which is for each pass.
    subpolling_interval = None

    #: If true the backend must implement :meth:`get_many`.
    supports_native_join = False

    def __init__(self, *args, **kwargs):
        from ..app import app_or_default
        self.app = app_or_default(kwargs.get("app"))
        self.serializer = kwargs.get("serializer",
                                     self.app.conf.CELERY_RESULT_SERIALIZER)
        (self.content_type,
         self.content_encoding,
         self.encoder) = serialization.registry._encoders[self.serializer]

    def encode(self, data):
        _, _, payload = serialization.encode(data, serializer=self.serializer)
        return payload

    def decode(self, payload):
        payload = is_py3k and payload or str(payload)
        return serialization.decode(payload,
                                    content_type=self.content_type,
                                    content_encoding=self.content_encoding)

    def prepare_expires(self, value, type=None):
        if value is None:
            value = self.app.conf.CELERY_TASK_RESULT_EXPIRES
        if isinstance(value, timedelta):
            value = timeutils.timedelta_seconds(value)
        if value is not None and type:
            return type(value)
        return value

    def encode_result(self, result, status):
        if status in self.EXCEPTION_STATES and isinstance(result, Exception):
            return self.prepare_exception(result)
        else:
            return self.prepare_value(result)

    def store_result(self, task_id, result, status, traceback=None):
        """Store the result and status of a task."""
        raise NotImplementedError(
                "store_result is not supported by this backend.")

    def mark_as_started(self, task_id, **meta):
        """Mark a task as started"""
        return self.store_result(task_id, meta, status=states.STARTED)

    def mark_as_done(self, task_id, result):
        """Mark task as successfully executed."""
        return self.store_result(task_id, result, status=states.SUCCESS)

    def mark_as_failure(self, task_id, exc, traceback=None):
        """Mark task as executed with failure. Stores the execption."""
        return self.store_result(task_id, exc, status=states.FAILURE,
                                 traceback=traceback)

    def mark_as_retry(self, task_id, exc, traceback=None):
        """Mark task as being retries. Stores the current
        exception (if any)."""
        return self.store_result(task_id, exc, status=states.RETRY,
                                 traceback=traceback)

    def mark_as_revoked(self, task_id):
        return self.store_result(task_id, TaskRevokedError(),
                                 status=states.REVOKED, traceback=None)

    def prepare_exception(self, exc):
        """Prepare exception for serialization."""
        if self.serializer in EXCEPTION_ABLE_CODECS:
            return get_pickleable_exception(exc)
        return {"exc_type": type(exc).__name__, "exc_message": str(exc)}

    def exception_to_python(self, exc):
        """Convert serialized exception to Python exception."""
        if self.serializer in EXCEPTION_ABLE_CODECS:
            return get_pickled_exception(exc)
        return create_exception_cls(from_utf8(exc["exc_type"]),
                                    sys.modules[__name__])

    def prepare_value(self, result):
        """Prepare value for storage."""
        return result

    def forget(self, task_id):
        raise NotImplementedError("%s does not implement forget." % (
                    self.__class__))

    def wait_for(self, task_id, timeout=None, propagate=True, interval=0.5):
        """Wait for task and return its result.

        If the task raises an exception, this exception
        will be re-raised by :func:`wait_for`.

        If `timeout` is not :const:`None`, this raises the
        :class:`celery.exceptions.TimeoutError` exception if the operation
        takes longer than `timeout` seconds.

        """

        time_elapsed = 0.0

        while True:
            status = self.get_status(task_id)
            if status == states.SUCCESS:
                return self.get_result(task_id)
            elif status in states.PROPAGATE_STATES:
                result = self.get_result(task_id)
                if propagate:
                    raise result
                return result
            # avoid hammering the CPU checking status.
            time.sleep(interval)
            time_elapsed += interval
            if timeout and time_elapsed >= timeout:
                raise TimeoutError("The operation timed out.")

    def cleanup(self):
        """Backend cleanup. Is run by
        :class:`celery.task.DeleteExpiredTaskMetaTask`."""
        pass

    def process_cleanup(self):
        """Cleanup actions to do at the end of a task worker process."""
        pass

    def get_status(self, task_id):
        """Get the status of a task."""
        raise NotImplementedError(
                "get_status is not supported by this backend.")

    def get_result(self, task_id):
        """Get the result of a task."""
        raise NotImplementedError(
                "get_result is not supported by this backend.")

    def get_traceback(self, task_id):
        """Get the traceback for a failed task."""
        raise NotImplementedError(
                "get_traceback is not supported by this backend.")

    def save_taskset(self, taskset_id, result):
        """Store the result and status of a task."""
        raise NotImplementedError(
                "save_taskset is not supported by this backend.")

    def restore_taskset(self, taskset_id, cache=True):
        """Get the result of a taskset."""
        raise NotImplementedError(
                "restore_taskset is not supported by this backend.")

    def delete_taskset(self, taskset_id):
        raise NotImplementedError(
                "delete_taskset is not supported by this backend.")

    def reload_task_result(self, task_id):
        """Reload task result, even if it has been previously fetched."""
        raise NotImplementedError(
                "reload_task_result is not supported by this backend.")

    def reload_taskset_result(self, task_id):
        """Reload taskset result, even if it has been previously fetched."""
        raise NotImplementedError(
                "reload_taskset_result is not supported by this backend.")

    def on_chord_part_return(self, task, propagate=False):
        pass

    def on_chord_apply(self, setid, body, result=None, **kwargs):
        from ..registry import tasks
        kwargs["result"] = [r.task_id for r in result]
        tasks["celery.chord_unlock"].apply_async((setid, body, ), kwargs,
                                                 countdown=1)

    def __reduce__(self, args=(), kwargs={}):
        return (unpickle_backend, (self.__class__, args, kwargs))

class BaseDictBackend(BaseBackend):

    def __init__(self, *args, **kwargs):
        super(BaseDictBackend, self).__init__(*args, **kwargs)
        self._cache = LRUCache(limit=kwargs.get("max_cached_results") or
                                 self.app.conf.CELERY_MAX_CACHED_RESULTS)

    def store_result(self, task_id, result, status, traceback=None, **kwargs):
        """Store task result and status."""
        result = self.encode_result(result, status)
        return self._store_result(task_id, result, status, traceback, **kwargs)

    def forget(self, task_id):
        self._cache.pop(task_id, None)
        self._forget(task_id)

    def _forget(self, task_id):
        raise NotImplementedError("%s does not implement forget." % (
                    self.__class__))

    def get_status(self, task_id):
        """Get the status of a task."""
        return self.get_task_meta(task_id)["status"]

    def get_traceback(self, task_id):
        """Get the traceback for a failed task."""
        return self.get_task_meta(task_id).get("traceback")

    def get_result(self, task_id):
        """Get the result of a task."""
        meta = self.get_task_meta(task_id)
        if meta["status"] in self.EXCEPTION_STATES:
            return self.exception_to_python(meta["result"])
        else:
            return meta["result"]

    def get_task_meta(self, task_id, cache=True):
        if cache:
            try:
                return self._cache[task_id]
            except KeyError:
                pass

        meta = self._get_task_meta_for(task_id)
        if cache and meta.get("status") == states.SUCCESS:
            self._cache[task_id] = meta
        return meta

    def reload_task_result(self, task_id):
        self._cache[task_id] = self.get_task_meta(task_id, cache=False)

    def reload_taskset_result(self, taskset_id):
        self._cache[taskset_id] = self.get_taskset_meta(taskset_id,
                                                        cache=False)

    def get_taskset_meta(self, taskset_id, cache=True):
        if cache:
            try:
                return self._cache[taskset_id]
            except KeyError:
                pass

        meta = self._restore_taskset(taskset_id)
        if cache and meta is not None:
            self._cache[taskset_id] = meta
        return meta

    def restore_taskset(self, taskset_id, cache=True):
        """Get the result for a taskset."""
        meta = self.get_taskset_meta(taskset_id, cache=cache)
        if meta:
            return meta["result"]

    def save_taskset(self, taskset_id, result):
        """Store the result of an executed taskset."""
        return self._save_taskset(taskset_id, result)

    def delete_taskset(self, taskset_id):
        self._cache.pop(taskset_id, None)
        return self._delete_taskset(taskset_id)

class KeyValueStoreBackend(BaseDictBackend):
    task_keyprefix = ensure_bytes("celery-task-meta-")
    taskset_keyprefix = ensure_bytes("celery-taskset-meta-")
    chord_keyprefix = ensure_bytes("chord-unlock-")

    def get(self, key):
        raise NotImplementedError("Must implement the get method.")

    def mget(self, keys):
        raise NotImplementedError("Does not support get_many")

    def set(self, key, value):
        raise NotImplementedError("Must implement the set method.")

    def delete(self, key):
        raise NotImplementedError("Must implement the delete method")

    def get_key_for_task(self, task_id):
        """Get the cache key for a task by id."""
        return self.task_keyprefix + ensure_bytes(task_id)

    def get_key_for_taskset(self, taskset_id):
        """Get the cache key for a taskset by id."""
        return self.taskset_keyprefix + ensure_bytes(taskset_id)

    def get_key_for_chord(self, taskset_id):
        """Get the cache key for the chord waiting on taskset with given id."""
        return self.chord_keyprefix + ensure_bytes(taskset_id)

    def _strip_prefix(self, key):
        """Takes bytes, emits string."""
        for prefix in self.task_keyprefix, self.taskset_keyprefix:
            if key.startswith(prefix):
                return bytes_to_str(key[len(prefix):])
        return bytes_to_str(key)

    def _mget_to_results(self, values, keys):
        if hasattr(values, "items"):
            # client returns dict so mapping preserved.
            return dict((self._strip_prefix(k), self.decode(v))
                            for k, v in values.iteritems()
                                if v is not None)
        else:
            # client returns list so need to recreate mapping.
            return dict((bytes_to_str(keys[i]), self.decode(value))
                            for i, value in enumerate(values)
                                if value is not None)

    def get_many(self, task_ids, timeout=None, interval=0.5):
        ids = set(task_ids)
        cached_ids = set()
        for task_id in ids:
            try:
                cached = self._cache[task_id]
            except KeyError:
                pass
            else:
                if cached["status"] in states.READY_STATES:
                    yield bytes_to_str(task_id), cached
                    cached_ids.add(task_id)

        ids ^= cached_ids
        iterations = 0
        while ids:
            keys = list(ids)
            r = self._mget_to_results(self.mget([self.get_key_for_task(k)
                                                    for k in keys]), keys)
            self._cache.update(r)
            ids ^= set(map(bytes_to_str, r))
            for key, value in r.iteritems():
                yield bytes_to_str(key), value
            if timeout and iterations * interval >= timeout:
                raise TimeoutError("Operation timed out (%s)" % (timeout, ))
            time.sleep(interval)  # don't busy loop.
            iterations += 0

    def _forget(self, task_id):
        self.delete(self.get_key_for_task(task_id))

    def _store_result(self, task_id, result, status, traceback=None):
        meta = {"status": status, "result": result, "traceback": traceback}
        self.set(self.get_key_for_task(task_id), self.encode(meta))
        return result

    def _save_taskset(self, taskset_id, result):
        self.set(self.get_key_for_taskset(taskset_id),
                 self.encode({"result": result}))
        return result

    def _delete_taskset(self, taskset_id):
        self.delete(self.get_key_for_taskset(taskset_id))

    def _get_task_meta_for(self, task_id):
        """Get task metadata for a task by id."""
        meta = self.get(self.get_key_for_task(task_id))
        if not meta:
            return {"status": states.PENDING, "result": None}
        return self.decode(meta)

    def _restore_taskset(self, taskset_id):
        """Get task metadata for a task by id."""
        meta = self.get(self.get_key_for_taskset(taskset_id))
        if meta:
            return self.decode(meta)

class DisabledBackend(BaseBackend):
    _cache = {}   # need this attribute to reset cache in tests.

    def store_result(self, *args, **kwargs):
        pass

    def _is_disabled(self, *args, **kwargs):
        raise NotImplementedError("No result backend configured.  "
                "Please see the documentation for more information.")
    wait_for = get_status = get_result = get_traceback = _is_disabled


text:
import { TestBed } from '@angular/core/testing';
import { Component, ViewChild } from '@angular/core';
import * as Infragistics from '../../public-api';

describe('Infragistics Angular Linear Gauge', () => {

    beforeEach(() => {
        TestBed.configureTestingModule({
            declarations: [Infragistics.IgLinearGaugeComponent, TestComponent]
        });
    });

    it('should initialize correctly', (done) => {
        const template = '
<ig-linear-gauge widgetId="lGauge" [(options)]="opts"></ig-linear-gauge>
';
        TestBed.overrideComponent(TestComponent, {
            set: {
                template
            }
        });
        TestBed.compileComponents().then(() => {
            const fixture = TestBed.createComponent(TestComponent);
            fixture.detectChanges();
            expect(fixture.debugElement.componentInstance.viewChild instanceof Infragistics.IgLinearGaugeComponent)
                .toBe(true);
            done();
        });
    });
});

@Component({
    selector: 'test-cmp',
    template: '

' // "Component 'TestComponent' must have either 'template' or 'templateUrl' set."
})
class TestComponent {
    private opts: any;

    @ViewChild(Infragistics.IgLinearGaugeComponent, { static: true }) public viewChild: Infragistics.IgLinearGaugeComponent;

    constructor() {
        this.opts = {
            height: '80px',
            width: '100%',
            value: 27,
            maximumValue: 30,
            ranges: [{ startValue: 0, endValue: 22, name: 'target' }]
        };
    }
}

redpajama_set_name: RedPajamaGithub


text: default_app_config = 'polls.apps.PollsConfig'


text:
package org.apache.commons.imaging.color;

/**
 * Represents a color in the DIN99 color space, a derivation of the CIE LAB color space.
 *
 * @see de.wikipedia.org/wiki/DIN99-Farbraum
 * @see Comparison of the metrics between the CIELAB and the DIN99 uniform
 *      color spaces
 * @see DIN99b P.284:
 *      Uniform_colour_spaces_based_on_the_DIN99_colour-difference_formula
 * @since 1.0-alpha3
 */
public final class ColorDin99Lab {

    public final double L99;

    public final double a99;

    public final double b99;

    public ColorDin99Lab(final double L99, final double a99, final double b99) {
        this.L99 = L99;
        this.a99 = a99;
        this.b99 = b99;
    }

    @Override
    public String toString() {
        return "{L: " + L99 + ", a: " + a99 + ", b: " + b99 + "}";
    }

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

        final ColorDin99Lab that = (ColorDin99Lab) o;
        if (Double.compare(that.L99, L99) != 0) {
            return false;
        }
        if (Double.compare(that.a99, a99) != 0) {
            return false;
        }
        if (Double.compare(that.b99, b99) != 0) {
            return false;
        }

        return true;
    }

    @Override
    public int hashCode() {
        int result;
        long temp;
        temp = Double.doubleToLongBits(L99);
        result = (int) (temp ^ temp >>> 32);
        temp = Double.doubleToLongBits(a99);
        result = 31 * result + (int) (temp ^ temp >>> 32);
        temp = Double.doubleToLongBits(b99);
        result = 31 * result + (int) (temp ^ temp >>> 32);
        return result;
    }
}


text:
var jwt = require("../.");
var assert = require('chai').assert;

describe('buffer payload', function () {
  it('should work', function () {
    var payload = new Buffer('TkJyotZe8NFpgdfnmgINqg==', 'base64');
    var token = jwt.sign(payload, "signing key");
    assert.equal(jwt.decode(token), payload.toString());
  });
});


text:
from dune.pymor.core.bindings   import (
     prepare_python_bindings, inject_lib_dune_pymor, inject_lib_dune_stuff,finalize_python_bindings)
from dune.pymor.core.wrapmodule import wrap_dune_stuff_module, wrap_module


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>mobi.qubits.tradingac</groupId>
    <artifactId>tradingac</artifactId>
    <version>0.2.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.2.5.RELEASE</version>
    </parent>

	<properties>
	 	<java.version>1.8</java.version>
		<axon.version>2.4.2</axon.version>
	</properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>

         <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <!--
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
         -->

		<dependency>
			<groupId>com.github.fakemongo</groupId>
			<artifactId>fongo</artifactId>
			<version>1.6.2</version>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework.hateoas</groupId>
			<artifactId>spring-hateoas</artifactId>
		</dependency>

        <!-- tag::tests[] -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- end::tests[] -->

		<dependency>
			<groupId>org.mongodb</groupId>
			<artifactId>mongo-java-driver</artifactId>
		</dependency>

		<dependency>
			<groupId>org.axonframework</groupId>
			<artifactId>axon-core</artifactId>
			<version>${axon.version}</version>
		</dependency>
		<dependency>
			<groupId>org.axonframework</groupId>
			<artifactId>axon-integration</artifactId>
			<version>${axon.version}</version>
		</dependency>

        <dependency>
			<groupId>org.axonframework</groupId>
			<artifactId>axon-mongo</artifactId>
			<version>${axon.version}</version>
		</dependency>

        <dependency>
			<groupId>org.axonframework</groupId>
			<artifactId>axon-test</artifactId>
			<version>${axon.version}</version>
		</dependency>

		<dependency>
			<groupId>org.glassfish.jersey.core</groupId>
			<artifactId>jersey-client</artifactId>
			<version>2.17</version>
		</dependency>

		<dependency>
			<groupId>javax.ws.rs</groupId>
			<artifactId>javax.ws.rs-api</artifactId>
			<version>2.0.1</version>
		</dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <artifactId>maven-failsafe-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>


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.

Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Imports Microsoft.VisualStudio.Text.Projection

Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense
    Public Class CSharpCompletionCommandHandlerTests_Projections

        <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
        Public Async Function TestSimpleWithJustSubjectBuffer() As System.Threading.Tasks.Task
            Using state = TestState.CreateCSharpTestState(
                <Document><![CDATA[
using System;

public class _Page_Default_cshtml : System.Web.WebPages.WebPage {
private static object @__o;
#line hidden

public override void Execute() {

#line 1 "Default.cshtml"
               __o = AppDomain$$
#line default
#line hidden
}
}]]></Document>)

                state.SendTypeChars(".Curr")
                Await state.WaitForAsynchronousOperationsAsync()
                Await state.AssertSelectedCompletionItem(displayText:="CurrentDomain")
                state.SendTab()
                Assert.Contains("__o = AppDomain.CurrentDomain", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
            End Using
        End Function

        <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
        Public Async Function TestAfterDot() As System.Threading.Tasks.Task
            Using state = TestState.CreateCSharpTestState(
                <Document><![CDATA[
{|S2:
class C
{
    void Goo()
    {
        System$$
    }
}
|}]]></Document>)
                Dim subjectDocument = state.Workspace.Documents.First()
                Dim firstProjection = state.Workspace.CreateProjectionBufferDocument(
                    <Document>
{|S1: @|}
{|S2:|}
                    </Document>.NormalizedValue, {subjectDocument}, LanguageNames.CSharp, options:=ProjectionBufferOptions.WritableLiteralSpans)

                Dim topProjectionBuffer = state.Workspace.CreateProjectionBufferDocument(
                <Document>
{|S1:|}
{|S2:|}
                              </Document>.NormalizedValue, {firstProjection}, LanguageNames.CSharp, options:=ProjectionBufferOptions.WritableLiteralSpans)

                Dim view = topProjectionBuffer.GetTextView()
                Dim buffer = subjectDocument.GetTextBuffer()

                state.SendTypeCharsToSpecificViewAndBuffer(".", view, buffer)
                Await state.AssertCompletionSession()

                state.SendTypeCharsToSpecificViewAndBuffer("Cons", view, buffer)
                Await state.WaitForAsynchronousOperationsAsync()
                Await state.AssertSelectedCompletionItem(displayText:="Console")
            End Using
        End Function

        <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
        Public Async Function TestInObjectCreationExpression() As System.Threading.Tasks.Task
            Using state = TestState.CreateCSharpTestState(
                <Document><![CDATA[
{|S2:
class C
{
    void Goo()
    {
        string s = new$$
    }
}
|}]]></Document>)
                Dim subjectDocument = state.Workspace.Documents.First()
                Dim firstProjection = state.Workspace.CreateProjectionBufferDocument(
                    <Document>
{|S1: @|}
{|S2:|}
                    </Document>.NormalizedValue, {subjectDocument}, LanguageNames.CSharp, options:=ProjectionBufferOptions.WritableLiteralSpans)

                Dim topProjectionBuffer = state.Workspace.CreateProjectionBufferDocument(
                <Document>
{|S1:|}
{|S2:|}
                              </Document>.NormalizedValue, {firstProjection}, LanguageNames.CSharp, options:=ProjectionBufferOptions.WritableLiteralSpans)

                Dim view = topProjectionBuffer.GetTextView()
                Dim buffer = subjectDocument.GetTextBuffer()

                state.SendTypeCharsToSpecificViewAndBuffer(" ", view, buffer)
                Await state.WaitForAsynchronousOperationsAsync()
                Await state.AssertSelectedCompletionItem(displayText:="string", isHardSelected:=True)
            End Using
        End Function

        <WorkItem(771761, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/771761")>
        <WpfFact(Skip:="https://github.com/dotnet/roslyn/issues/24846"), Trait(Traits.Feature, Traits.Features.Completion)>
        Public Async Function TestRegionCompletionCommitFormatting() As System.Threading.Tasks.Task
            Using state = TestState.CreateCSharpTestState(
                <Document><![CDATA[
{|S2:
class C
{
    void Goo()
    {
        $$
    }
}
|}]]></Document>)
                Dim subjectDocument = state.Workspace.Documents.First()
                Dim firstProjection = state.Workspace.CreateProjectionBufferDocument(
                    <Document>
{|S1: @|}
{|S2:|}
                    </Document>.NormalizedValue, {subjectDocument}, LanguageNames.CSharp, options:=ProjectionBufferOptions.WritableLiteralSpans)

                Dim topProjectionBuffer = state.Workspace.CreateProjectionBufferDocument(
                <Document>
{|S1:|}
{|S2:|}
                              </Document>.NormalizedValue, {firstProjection}, LanguageNames.CSharp, options:=ProjectionBufferOptions.WritableLiteralSpans)

                Dim view = topProjectionBuffer.GetTextView()
                Dim buffer = subjectDocument.GetTextBuffer()

                state.SendTypeCharsToSpecificViewAndBuffer("#reg", view, buffer)
                Await state.WaitForAsynchronousOperationsAsync()
                Await state.AssertSelectedCompletionItem(displayText:="region", shouldFormatOnCommit:=True)

            End Using
        End Function
    End Class
End Namespace


text:
package com.streamsets.pipeline.stage.origin.tcp;

import com.streamsets.pipeline.api.StageException;
import com.streamsets.pipeline.api.base.OnRecordErrorException;

/**
 * Supports stopping an SDC pipeline by its ID, specifically in response to its configured behavior for error record
 * handling (i.e. an {@link OnRecordErrorException}
 */
public interface StopPipelineHandler {

  /**
   * Stop the pipeline (by whatever mechanism is defined)
   *
   * @param pipelineId the SDC pipeline ID to stop
   * @param error the Exception that triggered this stop, should not be null
   */
  void stopPipeline(String pipelineId, StageException error);
}


text:
\hypertarget{test__inprod__analytic_8f90}{}\section{test\+\_\+inprod\+\_\+analytic.\+f90 File Reference}
\label{test__inprod__analytic_8f90}\index{test\+\_\+inprod\+\_\+analytic.\+f90@{test\+\_\+inprod\+\_\+analytic.\+f90}}
\subsection*{Functions/\+Subroutines}
\begin{DoxyCompactItemize}
\item
program \hyperlink{test__inprod__analytic_8f90_ab39906c756570260b929dab5e6f182c1}{inprod\+\_\+analytic\+\_\+test}
\begin{DoxyCompactList}\small\item\em Small program to print the inner products. \end{DoxyCompactList}\end{DoxyCompactItemize}

\subsection{Function/\+Subroutine Documentation}
\index{test\+\_\+inprod\+\_\+analytic.\+f90@{test\+\_\+inprod\+\_\+analytic.\+f90}!inprod\+\_\+analytic\+\_\+test@{inprod\+\_\+analytic\+\_\+test}}
\index{inprod\+\_\+analytic\+\_\+test@{inprod\+\_\+analytic\+\_\+test}!test\+\_\+inprod\+\_\+analytic.\+f90@{test\+\_\+inprod\+\_\+analytic.\+f90}}
\subsubsection[{\texorpdfstring{inprod\+\_\+analytic\+\_\+test}{inprod_analytic_test}}]{\setlength{\rightskip}{0pt plus 5cm}program inprod\+\_\+analytic\+\_\+test (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
)}\hypertarget{test__inprod__analytic_8f90_ab39906c756570260b929dab5e6f182c1}{}\label{test__inprod__analytic_8f90_ab39906c756570260b929dab5e6f182c1}

Small program to print the inner products.

\begin{DoxyCopyright}{Copyright}
2015 Lesley De Cruz \& Jonathan Demaeyer. See \hyperlink{LICENSE_8txt}{L\+I\+C\+E\+N\+S\+E.\+txt} for license information.
\end{DoxyCopyright}
\begin{DoxyRemark}{Remarks}
Print in the same order as test\+\_\+inprod.\+lua
\end{DoxyRemark}

Definition at line 18 of file test\+\_\+inprod\+\_\+analytic.\+f90.


text:
package com.xds.todo.activity;

import com.xds.todo.R;
import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.animation.Animator.AnimatorListener;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class slideItemView extends RelativeLayout implements OnClickListener {

	private TextView content_view;
	private Button delBtn;
	private Button almBtn;

	private Context context;

	private int downX;

	public slideItemView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		initView(context);
	}

	public slideItemView(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public slideItemView(Context context) {
		this(context, null);
	}

	private void initView(Context context) {
		this.context = context;
		View v = LayoutInflater.from(context).inflate(R.layout.item_view, this);

		content_view = (TextView) v.findViewById(R.id.content_view);
		delBtn = (Button) v.findViewById(R.id.delete_view);
		almBtn = (Button) v.findViewById(R.id.alarm_view);

		content_view.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				return handleTouch(v, event);
			}
		});
		content_view.setOnClickListener(this);
		delBtn.setOnClickListener(this);
		almBtn.setOnClickListener(this);
	}

	boolean result = false;// true:ÔÊÐíÒƶ¯£¬×èÖ¹µã»÷
	boolean isOpen = false;// ÅжÏÊÇ·ñÒÑÕ¹¿ª

	protected boolean handleTouch(View v, MotionEvent event) {
		int bottomWidth = delBtn.getWidth() + almBtn.getWidth();
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:

			downX = (int) event.getRawX();
			break;
		case MotionEvent.ACTION_MOVE:

			int dx = (int) (event.getRawX() - downX);// ÊÖÖ¸Òƶ¯µÄ¾àÀë
			if (isOpen) {// ´ò¿ª×´Ì¬
				if (dx > 0 && dx < bottomWidth) {
					v.setTranslationX(dx - bottomWidth);
					result = true;
				}
			} else {// ¹Ø±Õ״̬
				if (dx < 0 && Math.abs(dx) <= bottomWidth) {
					v.setTranslationX(dx);
					result = true;
				}
			}
			break;
		case MotionEvent.ACTION_CANCEL:
		case MotionEvent.ACTION_UP:

			float ddx = v.getTranslationX();// »ñÈ¡itemÒѾÒƶ¯µÄÆ«ÒÆÁ¿
			if (ddx < 0 && ddx > -(bottomWidth / 2)) {
				// Òª¹Ø±Õ
				ObjectAnimator oa1 = ObjectAnimator.ofFloat(v, "translationX",
						ddx, 0).setDuration(100);// ¿É±ä²ÎÊýµÄ¸öÊýΪ2ʱ£¬±íÃ÷µÚÒ»¸öÊÇÆð'ֵ£¬µÚ¶þ¸öÊÇÖÕÖ¹Öµ
				oa1.start();
				oa1.addListener(new AnimatorListener() {

					@Override
					public void onAnimationStart(Animator animation) {
					}

					@Override
					public void onAnimationRepeat(Animator animation) {
					}

					// ¶¯»½áÊøʱ
					@Override
					public void onAnimationEnd(Animator animation) {
						isOpen = false;
						result = false;// ¿ÉÒÔµã»÷
					}

					// ¶¯»È¡Ïûʱ
					@Override
					public void onAnimationCancel(Animator animation) {
						isOpen = false;
						result = false;// ¿ÉÒÔµã»÷
					}
				});
			}
			// Òª´ò¿ª
			if (ddx <= -(bottomWidth / 2) && ddx >= -bottomWidth) {// Ïò×óÒƶ¯¾àÀ볬¹ýÒ»¸ö°´Å¥µÄ¾àÀëÇÒ²»´óÓÚÁ½¸ö°´Å¥µÄ¿í¶È
				ObjectAnimator oa1 = ObjectAnimator.ofFloat(v, "translationX",
						ddx, -bottomWidth).setDuration(100);// ¿É±ä²ÎÊýµÄ¸öÊýΪ2ʱ£¬±íÃ÷µÚÒ»¸öÊÇÆð'ֵ£¬µÚ¶þ¸öÊÇÖÕÖ¹Öµ
				oa1.start();
				result = true;// ¿ÉÒÔµã»÷
				isOpen = true;
			}
			break;
		}
		return result;// itemÕ¹¿ªÊ±·µ»Øtrue£¬²»¿ÉÒÔµã»÷£¬µ«Á½¸ö°´Å¥¿ÉÒÔ
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.content_view:
			Toast.makeText(context, "content data", Toast.LENGTH_SHORT).show();
			break;
		case R.id.delete_view:
			Toast.makeText(context, "delete data", Toast.LENGTH_SHORT).show();
			break;
		case R.id.alarm_view:
			Toast.makeText(context, "alarm data", Toast.LENGTH_SHORT).show();
			break;
		}
	}

}


text:
package com.onlinetechvision.spark.hazelcast.connector.rdd

import java.util.Properties

import com.hazelcast.config.ClasspathXmlConfig
import com.hazelcast.core._
import com.onlinetechvision.spark.hazelcast.connector.{User, DistributedObjectType}
import com.onlinetechvision.spark.hazelcast.connector.config.SparkHazelcastConfig._
import org.apache.spark.{SparkConf, SparkContext}

/**
  * Created by eren.avsarogullari on 3/8/16.
  */
object WriteDistributedListToRDD {

  def main(args: Array[String]) {

    val HazelcastXMLFileName = "hazelcast_config.xml"
    val HazelcastDistributedListName = "test_distributed_list"

    // Spark Context is created...
    val sc = new SparkContext(new SparkConf().setAppName("spark-hazelcast").setMaster("local"))

    // Distributed List is created with the content...
    val hzInstance = Hazelcast.getOrCreateHazelcastInstance(new ClasspathXmlConfig(HazelcastXMLFileName))
    val distributedList: IList[User] = hzInstance.getList(HazelcastDistributedListName)
    (1 to 100).foreach(index => distributedList.add(new User(index, s"name$index", s"surname$index")))

    // Spark Hazelcast properties are created...
    val sparkHazelcastProperties = new Properties()
    sparkHazelcastProperties.put(HazelcastXMLConfigFileName, HazelcastXMLFileName)
    sparkHazelcastProperties.put(HazelcastDistributedObjectName, HazelcastDistributedListName)
    sparkHazelcastProperties.put(HazelcastDistributedObjectType, DistributedObjectType.IList)

    // Distributed List is written to Spark as a RDD...
    val userRDD = new HazelcastItemRDD[User](sc, sparkHazelcastProperties)
    println(s"userRDD has got ${userRDD.count} elements.")

    // Prints elements of 'userRDD'
    userRDD.take(100).foreach(println)

  }

}


text:
//
//  Majordomo Protocol broker.
//  A minimal Go implementation of the Majordomo Protocol as defined in
//  http://rfc.zeromq.org/spec:7 and http://rfc.zeromq.org/spec:8.
//

package main

import (
	zmq "github.com/pebbe/zmq2"
	"github.com/pebbe/zmq2/examples/mdapi"

	"fmt"
	"log"
	"os"
	"runtime"
	"time"
)

const (
	//  We'd normally pull these from config data

	HEARTBEAT_LIVENESS = 3                       //  3-5 is reasonable
	HEARTBEAT_INTERVAL = 2500 * time.Millisecond //  msecs
	HEARTBEAT_EXPIRY   = HEARTBEAT_INTERVAL * HEARTBEAT_LIVENESS
)

//  The broker class defines a single broker instance:

type Broker struct {
	socket       *zmq.Socket         //  Socket for clients & workers
	verbose      bool                //  Print activity to stdout
	endpoint     string              //  Broker binds to this endpoint
	services     map[string]*Service //  Hash of known services
	workers      map[string]*Worker  //  Hash of known workers
	waiting      []*Worker           //  List of waiting workers
	heartbeat_at time.Time           //  When to send HEARTBEAT
}

//  The service class defines a single service instance:

type Service struct {
	broker   *Broker    //  Broker instance
	name     string     //  Service name
	requests [][]string //  List of client requests
	waiting  []*Worker  //  List of waiting workers
}

//  The worker class defines a single worker, idle or active:

type Worker struct {
	broker    *Broker   //  Broker instance
	id_string string    //  Identity of worker as string
	identity  string    //  Identity frame for routing
	service   *Service  //  Owning service, if known
	expiry    time.Time //  Expires at unless heartbeat
}

//  Here are the constructor and destructor for the broker:

func NewBroker(verbose bool) (broker *Broker, err error) {

	//  Initialize broker state
	broker = &Broker{
		verbose:      verbose,
		services:     make(map[string]*Service),
		workers:      make(map[string]*Worker),
		waiting:      make([]*Worker, 0),
		heartbeat_at: time.Now().Add(HEARTBEAT_INTERVAL),
	}
	broker.socket, err = zmq.NewSocket(zmq.ROUTER)
	runtime.SetFinalizer(broker, (*Broker).Close)
	return
}

func (broker *Broker) Close() (err error) {
	if broker.socket != nil {
		err = broker.socket.Close()
		broker.socket = nil
	}
	return
}

//  The bind method binds the broker instance to an endpoint. We can call
//  this multiple times. Note that MDP uses a single socket for both clients
//  and workers:

func (broker *Broker) Bind(endpoint string) (err error) {
	err = broker.socket.Bind(endpoint)
	if err != nil {
		log.Println("E: MDP broker/0.2.0 failed to bind at", endpoint)
		return
	}
	log.Println("I: MDP broker/0.2.0 is active at", endpoint)
	return
}

//  The WorkerMsg method processes one READY, REPLY, HEARTBEAT or
//  DISCONNECT message sent to the broker by a worker:

func (broker *Broker) WorkerMsg(sender string, msg []string) {
	//  At least, command
	if len(msg) == 0 {
		panic("len(msg) == 0")
	}

	command, msg := popStr(msg)
	id_string := fmt.Sprintf("%q", sender)
	_, worker_ready := broker.workers[id_string]
	worker := broker.WorkerRequire(sender)

	switch command {
	case mdapi.MDPW_READY:
		if worker_ready { //  Not first command in session
			worker.Delete(true)
		} else if len(sender) >= 4 /*  Reserved service name */ && sender[:4] == "mmi." {
			worker.Delete(true)
		} else {
			//  Attach worker to service and mark as idle
			worker.service = broker.ServiceRequire(msg[0])
			worker.Waiting()
		}
	case mdapi.MDPW_REPLY:
		if worker_ready {
			//  Remove & save client return envelope and insert the
			//  protocol header and service name, then rewrap envelope.
			client, msg := unwrap(msg)
			broker.socket.SendMessage(client, "", mdapi.MDPC_CLIENT, worker.service.name, msg)
			worker.Waiting()
		} else {
			worker.Delete(true)
		}
	case mdapi.MDPW_HEARTBEAT:
		if worker_ready {
			worker.expiry = time.Now().Add(HEARTBEAT_EXPIRY)
		} else {
			worker.Delete(true)
		}
	case mdapi.MDPW_DISCONNECT:
		worker.Delete(false)
	default:
		log.Printf("E: invalid input message %q\n", msg)
	}
}

//  Process a request coming from a client. We implement MMI requests
//  directly here (at present, we implement only the mmi.service request):

func (broker *Broker) ClientMsg(sender string, msg []string) {
	//  Service name + body
	if len(msg) < 2 {
		panic("len(msg) < 2")
	}

	service_frame, msg := popStr(msg)
	service := broker.ServiceRequire(service_frame)

	//  Set reply return identity to client sender
	m := []string{sender, ""}
	msg = append(m, msg...)

	//  If we got a MMI service request, process that internally
	if len(service_frame) >= 4 && service_frame[:4] == "mmi." {
		var return_code string
		if service_frame == "mmi.service" {
			name := msg[len(msg)-1]
			service, ok := broker.services[name]
			if ok && len(service.waiting) > 0 {
				return_code = "200"
			} else {
				return_code = "404"
			}
		} else {
			return_code = "501"
		}

		msg[len(msg)-1] = return_code

		//  Remove & save client return envelope and insert the
		//  protocol header and service name, then rewrap envelope.
		client, msg := unwrap(msg)
		broker.socket.SendMessage(client, "", mdapi.MDPC_CLIENT, service_frame, msg)
	} else {
		//  Else dispatch the message to the requested service
		service.Dispatch(msg)
	}
}

//  The purge method deletes any idle workers that haven't pinged us in a
//  while. We hold workers from oldest to most recent, so we can stop
//  scanning whenever we find a live worker. This means we'll mainly stop
//  at the first worker, which is essential when we have large numbers of
//  workers (since we call this method in our critical path):

func (broker *Broker) Purge() {
	now := time.Now()
	for len(broker.waiting) > 0 {
		if broker.waiting[0].expiry.After(now) {
			break //  Worker is alive, we're done here
		}
		if broker.verbose {
			log.Println("I: deleting expired worker:", broker.waiting[0].id_string)
		}
		broker.waiting[0].Delete(false)
	}
}

//  Here is the implementation of the methods that work on a service:

//  Lazy constructor that locates a service by name, or creates a new
//  service if there is no service already with that name.

func (broker *Broker) ServiceRequire(service_frame string) (service *Service) {
	name := service_frame
	service, ok := broker.services[name]
	if !ok {
		service = &Service{
			broker:   broker,
			name:     name,
			requests: make([][]string, 0),
			waiting:  make([]*Worker, 0),
		}
		broker.services[name] = service
		if broker.verbose {
			log.Println("I: added service:", name)
		}
	}
	return
}

//  The dispatch method sends requests to waiting workers:

func (service *Service) Dispatch(msg []string) {

	if len(msg) > 0 {
		//  Queue message if any
		service.requests = append(service.requests, msg)
	}

	service.broker.Purge()
	for len(service.waiting) > 0 && len(service.requests) > 0 {
		var worker *Worker
		worker, service.waiting = popWorker(service.waiting)
		service.broker.waiting = delWorker(service.broker.waiting, worker)
		msg, service.requests = popMsg(service.requests)
		worker.Send(mdapi.MDPW_REQUEST, "", msg)
	}
}

//  Here is the implementation of the methods that work on a worker:

//  Lazy constructor that locates a worker by identity, or creates a new
//  worker if there is no worker already with that identity.

func (broker *Broker) WorkerRequire(identity string) (worker *Worker) {

	//  broker.workers is keyed off worker identity
	id_string := fmt.Sprintf("%q", identity)
	worker, ok := broker.workers[id_string]
	if !ok {
		worker = &Worker{
			broker:    broker,
			id_string: id_string,
			identity:  identity,
		}
		broker.workers[id_string] = worker
		if broker.verbose {
			log.Printf("I: registering new worker: %s\n", id_string)
		}
	}
	return
}

//  The delete method deletes the current worker.

func (worker *Worker) Delete(disconnect bool) {
	if disconnect {
		worker.Send(mdapi.MDPW_DISCONNECT, "", []string{})
	}

	if worker.service != nil {
		worker.service.waiting = delWorker(worker.service.waiting, worker)
	}
	worker.broker.waiting = delWorker(worker.broker.waiting, worker)
	delete(worker.broker.workers, worker.id_string)
}

//  The send method formats and sends a command to a worker. The caller may
//  also provide a command option, and a message payload:

func (worker *Worker) Send(command, option string, msg []string) (err error) {
	n := 4
	if option != "" {
		n++
	}
	m := make([]string, n, n+len(msg))
	m = append(m, msg...)

	//  Stack protocol envelope to start of message
	if option != "" {
		m[4] = option
	}
	m[3] = command
	m[2] = mdapi.MDPW_WORKER

	//  Stack routing envelope to start of message
	m[1] = ""
	m[0] = worker.identity

	if worker.broker.verbose {
		log.Printf("I: sending %s to worker %q\n", mdapi.MDPS_COMMANDS[command], m)
	}
	_, err = worker.broker.socket.SendMessage(m)
	return
}

//  This worker is now waiting for work

func (worker *Worker) Waiting() {
	//  Queue to broker and service waiting lists
	worker.broker.waiting = append(worker.broker.waiting, worker)
	worker.service.waiting = append(worker.service.waiting, worker)
	worker.expiry = time.Now().Add(HEARTBEAT_EXPIRY)
	worker.service.Dispatch([]string{})
}

//  Finally here is the main task. We create a new broker instance and
//  then processes messages on the broker socket:

func main() {
	verbose := false
	if len(os.Args) > 1 && os.Args[1] == "-v" {
		verbose = true
	}

	broker, _ := NewBroker(verbose)
	broker.Bind("tcp://*:5555")

	poller := zmq.NewPoller()
	poller.Add(broker.socket, zmq.POLLIN)

	//  Get and process messages forever or until interrupted
	for {
		polled, err := poller.Poll(HEARTBEAT_INTERVAL)
		if err != nil {
			break //  Interrupted
		}

		//  Process next input message, if any
		if len(polled) > 0 {
			msg, err := broker.socket.RecvMessage(0)
			if err != nil {
				break //  Interrupted
			}
			if broker.verbose {
				log.Printf("I: received message: %q\n", msg)
			}
			sender, msg := popStr(msg)
			_, msg = popStr(msg)
			header, msg := popStr(msg)

			switch header {
			case mdapi.MDPC_CLIENT:
				broker.ClientMsg(sender, msg)
			case mdapi.MDPW_WORKER:
				broker.WorkerMsg(sender, msg)
			default:
				log.Printf("E: invalid message: %q\n", msg)
			}
		}
		//  Disconnect and delete any expired workers
		//  Send heartbeats to idle workers if needed
		if time.Now().After(broker.heartbeat_at) {
			broker.Purge()
			for _, worker := range broker.waiting {
				worker.Send(mdapi.MDPW_HEARTBEAT, "", []string{})
			}
			broker.heartbeat_at = time.Now().Add(HEARTBEAT_INTERVAL)
		}
	}
	log.Println("W: interrupt received, shutting down...")
}

//  Pops frame off front of message and returns it as 'head'
//  If next frame is empty, pops that empty frame.
//  Return remaining frames of message as 'tail'
func unwrap(msg []string) (head string, tail []string) {
	head = msg[0]
	if len(msg) > 1 && msg[1] == "" {
		tail = msg[2:]
	} else {
		tail = msg[1:]
	}
	return
}

func popStr(ss []string) (s string, ss2 []string) {
	s = ss[0]
	ss2 = ss[1:]
	return
}

func popMsg(msgs [][]string) (msg []string, msgs2 [][]string) {
	msg = msgs[0]
	msgs2 = msgs[1:]
	return
}

func popWorker(workers []*Worker) (worker *Worker, workers2 []*Worker) {
	worker = workers[0]
	workers2 = workers[1:]
	return
}

func delWorker(workers []*Worker, worker *Worker) []*Worker {
	for i := 0; i < len(workers); i++ {
		if workers[i] == worker {
			workers = append(workers[:i], workers[i+1:]...)
			i--
		}
	}
	return workers
}


text:
import type { Config } from '@jest/types';
import type { ChangedFilesPromise, Options, Repos } from './types';
export type { ChangedFiles, ChangedFilesPromise } from './types';
export declare const getChangedFilesForRoots: (roots: Array<Config.Path>, options: Options) => ChangedFilesPromise;
export declare const findRepos: (roots: Array<Config.Path>) => Promise<Repos>;


text:
/*
Filename: editingState.js
Author: Zach Lambert
Last Updated: 17 Apr 2017
Description: Handles state for position editing

posEditingState: posEditOn, initCoords, newCoords
 */

import React from 'react';

const defState2 = {
	posEditOn: false,
	initCoords: {
		left: '',
		top: '',
	},
	newCoords: {
		left: '',
		top: '',
	},
}

export const posEditReducer = (state = defState2, action) => {

	switch (action.type) {

		case 'START_POS_EDIT':
			return Object.assign({}, state, {
				posEditOn: true,
				initCoords: Object.assign({}, state.initCoords, {
					left: action.left,
					top: action.top
				}),
			});
		break;

		case 'END_POS_EDIT':
			return Object.assign({}, state, {posEditOn: false});
		break;

		case 'UPDATE_POS':
		return Object.assign({}, state, {
			newCoords: Object.assign({}, state.newCoords, {
				left: action.left,
				top: action.top
			}),
		});
		break;

		case 'RESET_POS':
		return Object.assign({}, state, {
			newCoords: Object.assign({}, state.newCoords, {
				left: state.initCoords.left,
				top: state.initCoords.top
			}),
			posEditOn: false,
		});
		break;

		case 'CLEAR_POS':

		return defState2;

		break;

		default:
		return state;
	}
}


text:
<?php
namespace ACSEO\Bundle\SQLServerBundle\Driver;

use Realestate\MssqlBundle\Driver\PDODblib\Driver as Driver;
use ACSEO\Bundle\SQLServerBundle\Platforms\SQLServerDblibPlatform;

/**
 * Driver
 */
class SQLServerDriver extends Driver
{
    /**
     * Get Database Platform
     *
     * @return AbstractPlatform database platform
     */
    public function getDatabasePlatform()
    {
        return new SQLServerDblibPlatform();
    }

}


text:
Evented-queue
=============

A queue implementation that emits events when items are enqueued/dequeued

I wanted to build a system that would emit an event whenever a an item was enqueued or dequeued from a standard queue. Of course this is fairly trivial, but it's something I find myself using time and time again.

## Methodology

When an item is enqueued, a "itemenqueued" event is emitted. Any listners are informed and can fire an event as a result. The same is true for dequeueing of items. An "itemdequeued" event is fired. (although I don't see this being used as much). A "queueemptied" event can alert listeners when the queue has no more items.

##Installation

You can install EventedQueue via npm:

    npm install EventedQueue

Add it to your project by including it:

    var EventedQueue = require('../evented-queue.js');

##Adding items to an EventedQueue

Right now, the EventedQueue system is extremely simple. Just add the script to your page and instantiate an instance of EventedQueue:

    var myEventedQueue = new EventedQueue();

You may start enqueueing items with

    var item = Object/Array/String/Number;
    myEventedQueue.enqueue(item);

**Note:** When enqueing an array, it will be added just like any other type. It's constituent components will not be added one by one.

If you have an existing array of items you'd like to enqueue, you can use

    var items = [item1, item2, item3];
    myEventedQueue.enqueueMultiple(items);

**Note:** These items will be appended to the end of an existing queue using the Javascript Array.splice method. They will be queued in the order that they are specified in the existing array.

##Removing items from an EventedQueue
Queues are read from left to right. The left is known as the head. The right is known as the tail. Dequeueing an item from a queue means removing the item from the first position or head of the queue.

You can dequeue an item using

    var myItem = myEventedQueue.dequeue();

## Checking if an EventedQueue is empty

EventedQueue has a convenience method to check if the queue is empty:

    var item = "hello, is it me you're looking for?";
    var lionelsQueue = new EventedQueue();
    lionelsQueue.empty();
     //returns false

## Events fired when enqueing and dequeueing items

Here's where the fun begins. Perhaps you want to fire an event every time an item is added to the queue. Simply attach an event listner to the EventedQueue's "itemenqueued" event

    myEventedQueue.addEventListener('itemenqueued', function () { ... }, false);

Currently no additional information is returned.

To attach an event any time an item is dequeued, the process is similar:

    myEventedQueue.addEventListener('itemdequeued', function () { ... }, false);

If dequeueing items leads to an empty queue, EventedQueue emits a 'queueemptied' event.

    myEventedQueue.addEventListener('queueemptied', function() {
      console.log('Yay! our work here is done!');
    }, false);

## Adding multiple items

Naturally, there are times when one will want to add items in bulk. Emitting an event for 400 items, for example, might be overkill. For this reason, EventedQueue has an **enqueueMultiple** method which takes an array and adds its items at one time. It emits one event. This is the preferred method if a large amount of items will be added - or if an unknown number of items will be added.

    var lionelsHits = [
      'Dancing on the Ceiling',
      'Ballerina Girl',
      'Running With The Night',
      'All Night Long'
    ];

    var lionelsQueue = new EventedQueue();
    lioneleQueue.enqueueMultiple(lionelsHits);

This will emit a single event, yet add multiple items.

##Clearing an EventedQueue

To clear all items from a queue without firing an event:

    myEventQueue.clear();

##Checking whether an EventedQueue is empty

Although an EventedQueue will emit an event when the queue is empty, a convenience method exists just in case:

    myEventedQueue.empty(); //true


text:
<?php

namespace Kassko\Test\UnitTestsGenerator\PlanModel;

use Kassko\Test\UnitTestsGenerator\PlanModel\AbstractExpectation;
use Kassko\Test\UnitTestsGenerator\PlanModel\Path;
use Kassko\Test\UnitTestsGenerator\PlanModel\Value;

/**
 * ResultExpectation
 */
class ResultExpectation extends AbstractExpectation
{
    /**
     * @var Value
     */
    private $result;
    /**
     * @var Path
     */
    private $path;

    /**
     * @param Value $result
     * @param Path  $path
     * @param bool  $enabled (default)
     */
    public function __construct(Value $result, Path $path, $enabled = true)
    {
        parent::__construct($enabled);

        $this->expectation = $result;
        $this->path = $path;
    }

    /**
     * @return Value
     */
    public function getResult()
    {
        return $this->expectation;
    }

    /**
     * @return Path
     */
    public function getPath()
    {
        return $this->path;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="app_primary_colour">#FF5722</color>
    <color name="app_primary_colour_dark">#FF5722</color>
    <color name="app_accent_colour">#FBE9E7</color>

    <color name="dark_background">#333</color>
    <color name="full_black">#000</color>
    <color name="full_white">#fff</color>
    <color name="medium_gray">#666</color>
    <color name="light_gray">#999</color>
    <color name="translucent_gray">#20000000</color>
    <color name="clear_button_text">#0099FF</color>
</resources>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=9"/>
    <meta name="generator" content="Doxygen 1.8.6"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <title>Generic Image Library: bit_aligned_image5_type< Size1, Size2, Size3, Size4, Size5, Layout, Alloc > Struct Template Reference</title>
    <link href="tabs.css" rel="stylesheet" type="text/css"/>

    <link href="doxygen.css" rel="stylesheet" type="text/css" />
    <link href="doxygen-boost.css" rel="stylesheet" type="text/css"/>

Main Page

Modules

Classes

Files

Class List

Class Index

Class Hierarchy

Class Members

boost

gil

bit_aligned_image5_type

List of all members

bit_aligned_image5_type< Size1, Size2, Size3, Size4, Size5, Layout, Alloc > Struct Template Reference
packed_image_type,bit_aligned_image_type

Returns the type of a five channel bit-aligned image given the bit size of its channels and its layout.
 More...

#include <metafunctions.hpp>

Inheritance diagram for bit_aligned_image5_type< Size1, Size2, Size3, Size4, Size5, Layout, Alloc >:

  <map id="bit_aligned_image5_type< Size1, Size2, Size3, Size4, Size5, Layout, Alloc >_map" name="bit_aligned_image5_type< Size1, Size2, Size3, Size4, Size5, Layout, Alloc >_map">
<area href="structboost_1_1gil_1_1bit__aligned__image__type.html" alt="bit_aligned_image_type< mpl::vector5_c< unsigned, Size1, Size2, Size3, Size4, Size5 >, Layout, Alloc >" shape="rect" coords="0,0,610,24"/>
</map>

Additional Inherited Members

 Public Types inherited from bit_aligned_image_type< mpl::vector5_c< unsigned, Size1, Size2, Size3, Size4, Size5 >, Layout, Alloc >

typedef image

< bit_alignedref_t, false,

Alloc > 	type

Detailed Description

template<unsigned Size1, unsigned Size2, unsigned Size3, unsigned Size4, unsigned Size5, typename Layout, typename Alloc = std::allocator<unsigned char>>

struct boost::gil::bit_aligned_image5_type< Size1, Size2, Size3, Size4, Size5, Layout, Alloc >

Returns the type of a five channel bit-aligned image given the bit size of its channels and its layout.

The documentation for this struct was generated from the following file:

metafunctions.hpp

     <address class="footer">

        Generated on Wed Dec 5 2018 20:05:51 for Generic Image Library by  doxygen 1.8.6

    </address>


text:
@interface BeerStyle : NSObject

@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSString *description;

- (id) initWithArray:(NSArray *)arr;

@end


text:
package org.apache.commons.io.input;

import static org.apache.commons.io.IOUtils.EOF;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CoderResult;
import java.nio.charset.CodingErrorAction;
import java.util.Objects;

import org.apache.commons.io.Charsets;

/**
 * Implements an {@link InputStream} to read from String, StringBuffer, StringBuilder or CharBuffer.
 *

 * Note: Supports {@link #mark(int)} and {@link #reset()}.
 *

 *
 * @since 2.2
 */
public class CharSequenceInputStream extends InputStream {

    private static final int BUFFER_SIZE = 2048;

    private static final int NO_MARK = -1;

    private final CharsetEncoder charsetEncoder;
    private final CharBuffer cBuf;
    private final ByteBuffer bBuf;

    private int cBufMark; // position in cBuf
    private int bBufMark; // position in bBuf

    /**
     * Constructs a new instance with a buffer size of 2048.
     *
     * @param cs the input character sequence.
     * @param charset the character set name to use.
     * @throws IllegalArgumentException if the buffer is not large enough to hold a complete character.
     */
    public CharSequenceInputStream(final CharSequence cs, final Charset charset) {
        this(cs, charset, BUFFER_SIZE);
    }

    /**
     * Constructs a new instance.
     *
     * @param cs the input character sequence.
     * @param charset the character set name to use, null maps to the default Charset.
     * @param bufferSize the buffer size to use.
     * @throws IllegalArgumentException if the buffer is not large enough to hold a complete character.
     */
    public CharSequenceInputStream(final CharSequence cs, final Charset charset, final int bufferSize) {
        // @formatter:off
        this.charsetEncoder = Charsets.toCharset(charset).newEncoder()
            .onMalformedInput(CodingErrorAction.REPLACE)
            .onUnmappableCharacter(CodingErrorAction.REPLACE);
        // @formatter:on
        // Ensure that buffer is long enough to hold a complete character
        this.bBuf = ByteBuffer.allocate(ReaderInputStream.checkMinBufferSize(charsetEncoder, bufferSize));
        this.bBuf.flip();
        this.cBuf = CharBuffer.wrap(cs);
        this.cBufMark = NO_MARK;
        this.bBufMark = NO_MARK;
    }

    /**
     * Constructs a new instance with a buffer size of 2048.
     *
     * @param cs the input character sequence.
     * @param charset the character set name to use.
     * @throws IllegalArgumentException if the buffer is not large enough to hold a complete character.
     */
    public CharSequenceInputStream(final CharSequence cs, final String charset) {
        this(cs, charset, BUFFER_SIZE);
    }

    /**
     * Constructs a new instance.
     *
     * @param cs the input character sequence.
     * @param charset the character set name to use, null maps to the default Charset.
     * @param bufferSize the buffer size to use.
     * @throws IllegalArgumentException if the buffer is not large enough to hold a complete character.
     */
    public CharSequenceInputStream(final CharSequence cs, final String charset, final int bufferSize) {
        this(cs, Charsets.toCharset(charset), bufferSize);
    }

    /**
     * Return an estimate of the number of bytes remaining in the byte stream.
     * @return the count of bytes that can be read without blocking (or returning EOF).
     *
     * @throws IOException if an error occurs (probably not possible).
     */
    @Override
    public int available() throws IOException {
        // The cached entries are in bBuf; since encoding always creates at least one byte
        // per character, we can add the two to get a better estimate (e.g. if bBuf is empty)
        // Note that the previous implementation (2.4) could return zero even though there were
        // encoded bytes still available.
        return this.bBuf.remaining() + this.cBuf.remaining();
    }

    @Override
    public void close() throws IOException {
        // noop
    }

    /**
     * Fills the byte output buffer from the input char buffer.
     *
     * @throws CharacterCodingException
     *             an error encoding data.
     */
    private void fillBuffer() throws CharacterCodingException {
        this.bBuf.compact();
        final CoderResult result = this.charsetEncoder.encode(this.cBuf, this.bBuf, true);
        if (result.isError()) {
            result.throwException();
        }
        this.bBuf.flip();
    }

    /**
     * Gets the CharsetEncoder.
     *
     * @return the CharsetEncoder.
     */
    CharsetEncoder getCharsetEncoder() {
        return charsetEncoder;
    }

    /**
     * {@inheritDoc}
     * @param readlimit max read limit (ignored).
     */
    @Override
    public synchronized void mark(final int readlimit) {
        this.cBufMark = this.cBuf.position();
        this.bBufMark = this.bBuf.position();
        this.cBuf.mark();
        this.bBuf.mark();
        // It would be nice to be able to use mark & reset on the cBuf and bBuf;
        // however the bBuf is re-used so that won't work
    }

    @Override
    public boolean markSupported() {
        return true;
    }

    @Override
    public int read() throws IOException {
        for (;;) {
            if (this.bBuf.hasRemaining()) {
                return this.bBuf.get() & 0xFF;
            }
            fillBuffer();
            if (!this.bBuf.hasRemaining() && !this.cBuf.hasRemaining()) {
                return EOF;
            }
        }
    }

    @Override
    public int read(final byte[] b) throws IOException {
        return read(b, 0, b.length);
    }

    @Override
    public int read(final byte[] array, int off, int len) throws IOException {
        Objects.requireNonNull(array, "array");
        if (len < 0 || off + len > array.length) {
            throw new IndexOutOfBoundsException("Array Size=" + array.length + ", offset=" + off + ", length=" + len);
        }
        if (len == 0) {
            return 0; // must return 0 for zero length read
        }
        if (!this.bBuf.hasRemaining() && !this.cBuf.hasRemaining()) {
            return EOF;
        }
        int bytesRead = 0;
        while (len > 0) {
            if (this.bBuf.hasRemaining()) {
                final int chunk = Math.min(this.bBuf.remaining(), len);
                this.bBuf.get(array, off, chunk);
                off += chunk;
                len -= chunk;
                bytesRead += chunk;
            } else {
                fillBuffer();
                if (!this.bBuf.hasRemaining() && !this.cBuf.hasRemaining()) {
                    break;
                }
            }
        }
        return bytesRead == 0 && !this.cBuf.hasRemaining() ? EOF : bytesRead;
    }

    @Override
    public synchronized void reset() throws IOException {
        //
        // This is not the most efficient implementation, as it re-encodes from the beginning.
        //
        // Since the bBuf is re-used, in general it's necessary to re-encode the data.
        //
        // It should be possible to apply some optimisations however:
        // + use mark/reset on the cBuf and bBuf. This would only work if the buffer had not been (re)filled since
        // the mark. The code would have to catch InvalidMarkException - does not seem possible to check if mark is
        // valid otherwise. + Try saving the state of the cBuf before each fillBuffer; it might be possible to
        // restart from there.
        //
        if (this.cBufMark != NO_MARK) {
            // if cBuf is at 0, we have not started reading anything, so skip re-encoding
            if (this.cBuf.position() != 0) {
                this.charsetEncoder.reset();
                this.cBuf.rewind();
                this.bBuf.rewind();
                this.bBuf.limit(0); // rewind does not clear the buffer
                while(this.cBuf.position() < this.cBufMark) {
                    this.bBuf.rewind(); // empty the buffer (we only refill when empty during normal processing)
                    this.bBuf.limit(0);
                    fillBuffer();
                }
            }
            if (this.cBuf.position() != this.cBufMark) {
                throw new IllegalStateException("Unexpected CharBuffer position: actual=" + cBuf.position() + " " +
                        "expected=" + this.cBufMark);
            }
            this.bBuf.position(this.bBufMark);
            this.cBufMark = NO_MARK;
            this.bBufMark = NO_MARK;
        }
    }

    @Override
    public long skip(long n) throws IOException {
        //
        // This could be made more efficient by using position to skip within the current buffer.
        //
        long skipped = 0;
        while (n > 0 && available() > 0) {
            this.read();
            n--;
            skipped++;
        }
        return skipped;
    }

}


text:
package main

import (
	"bufio"
	"errors"
	"flag"
	"fmt"
	"log"
	"math"
	"os"
	"strconv"
	"strings"
)

func check(e error) {
	if e != nil {
		panic(e)
	}
}

// Each Barber takes a certain amount of time to cut hair (cutTime).
// barberNumbers should start at 1.
type Barber struct {
	cutTime, barberNumber int
}

// Returns the number of customers who can be serviced by a given time.
//
// A serviced customer is one who has been completed or is actively having their
// hair cut.
func numCustomersServiced(barbers []Barber, minutes int) int {
	// When we start, <number of barbers> amount of customers are being serviced
	sum := len(barbers)
	// Figure out how many people each individual barber could have serviced in
	// this much time.
	for _, b := range barbers {
		sum += minutes / b.cutTime
	}
	return sum
}

func splitString(str string) []int {
	splitString := strings.Fields(str)
	ints := make([]int, len(splitString))
	for i, s := range splitString {
		output, err := strconv.Atoi(s)
		check(err)
		ints[i] = output
	}
	return ints
}

// Returns the relevant information for the next problem
//
// Each problem is described on two lines:
//  1. First line includes the number of barbers and the customer position
//  2. Second line has the cutting times for each barber
//
// Returns a tuple of (<all the barbers in a []Barber list, the customerNumber).
// These have all be converted into ints (instead of strings).
//
// Returns error when EOF is reached (ie: no more problems).
func readNextProblem(scanner *bufio.Scanner) ([]Barber, int, error) {
	if !scanner.Scan() {
		return nil, 0, errors.New("All done!")
	}

	firstLine := splitString(scanner.Text())
	numBarbers := firstLine[0]
	customerNumber := firstLine[1]

	if !scanner.Scan() {
		panic("EOF at unexpected time")
	}
	barberTimes := splitString(scanner.Text())

	if len(barberTimes) != numBarbers {
		log.Panicf("Found %d barbers, expected to find %d\n",
			len(barberTimes), numBarbers)
	}

	barbers := make([]Barber, numBarbers)
	for b, barberTime := range barberTimes {
		// barberNumbers start at 1
		barbers[b] = Barber{barberTime, b + 1}
	}

	return barbers, customerNumber, nil
}

func solve(barbers []Barber, customerNumber int) int {
	// If the customer is one of the first, just return their place in line.
	if customerNumber <= len(barbers) {
		return customerNumber
	}

	// First we find an upper bound - a number of minutes in which we KNOW our
	// customer must be taken in.
	upperBound := 1
	for numCustomersServiced(barbers, upperBound) < customerNumber {
		upperBound *= 2
	}

	// Now we loop until we find (lowerBound, upperBound) pair s.t. we know the
	// upperBound is the time at which our customer would be taken.

	// We know it is the correct time when the lowerBound would not be enough time
	// and the upperBound is enough time. If we continually cut them in half, this
	// will happen when they're one minute apart.
	lowerBound := 0
	for upperBound-lowerBound != 1 {
		// Test a new bound of an int directly in the middle of our two bounds
		newBound := (upperBound + lowerBound) / 2
		if numCustomersServiced(barbers, newBound) < customerNumber {
			lowerBound = newBound
		} else {
			upperBound = newBound
		}
	}

	customerCutTime := upperBound
	log.Printf("Our customer will go at minute %d", customerCutTime)

	numCustomersBeingServiced := numCustomersServiced(barbers, customerCutTime-1)
	log.Printf("When minute %d starts, %d customers are already being serviced",
		customerCutTime, numCustomersBeingServiced)

	// We know how many customers are being serviced when our minute starts.
	// Assign them to barbers in order until we reach our customer number.
	for _, barber := range barbers {
		if math.Mod(float64(customerCutTime), float64(barber.cutTime)) == 0 {
			numCustomersBeingServiced++
			if numCustomersBeingServiced == customerNumber {
				return barber.barberNumber
			}
		}
	}

	panic(errors.New("Couldn't find a matching barber"))
}

func main() {
	filenamePointer := flag.String(
		"input-file", "input-test.txt", "filename to read input")
	flag.Parse()
	file, err := os.Open(*filenamePointer)
	check(err)
	defer file.Close()

	scanner := bufio.NewScanner(file)

	// First line is the number of problems
	read_from_file := scanner.Scan()
	if !read_from_file {
		panic("couldn't read input")
	}
	num_problems, err := strconv.Atoi(scanner.Text())
	check(err)
	log.Printf("num_problems: %d\n", num_problems)

	out, err := os.Create("output.txt")
	check(err)
	defer out.Sync()
	for i := 0; i < num_problems; i++ {
		barbers, customerNumber, done := readNextProblem(scanner)
		if done != nil {
			break
		}

		barberNumber := solve(barbers, customerNumber)
		log.Printf("Our customer uses barber number %d", barberNumber)
		// Cases are 1-s based
		out.WriteString(fmt.Sprintf("Case #%d: %d\n", i+1, barberNumber))
	}
}


text:
package de.fuberlin.wiwiss.r2r.functions;

import java.util.ArrayList;
import java.util.List;

import java.math.BigInteger;
import java.math.BigDecimal;

import de.fuberlin.wiwiss.r2r.Function;
import de.fuberlin.wiwiss.r2r.FunctionFactory;
import de.fuberlin.wiwiss.r2r.functions.HelperFunctions.DataType;

public class NegateFunctionFactory implements FunctionFactory {
private NegateFunction function = null;

	public Function getInstance() {
		if(function==null)
			function = new NegateFunction();

		return function;
	}

	private class NegateFunction implements Function {

		public String getURI() {
			return "negate";
		}

		public List<String> execute(List<List<String>> arguments, String hint) {
			List<String> result = new ArrayList<String>();
			if(arguments.size()<1)
				throw new IllegalArgumentException("Not enough arguments!");

			List<String> argument = arguments.get(0);

			if(argument.size()<1)
				throw new IllegalArgumentException("Not enough arguments!");

			DataType type = HelperFunctions.getDataTypeInformationOfArgument(argument);

			if(type==DataType.String)
				throw new IllegalArgumentException("Non-numerical argument for negate-function!");
			if(type==DataType.Integer) {
				BigInteger intResult = new BigInteger(argument.get(0)).negate();
				result.add(intResult.toString());
			} else if(type==DataType.Int) {
				Integer intResult = -Integer.parseInt(argument.get(0));
				result.add(intResult.toString());
			} else if(type==DataType.Long) {
				Long longResult = -Long.parseLong(argument.get(0));
				result.add(longResult.toString());
			} else if(type==DataType.Decimal) {
				BigDecimal decimalResult = new BigDecimal(argument.get(0)).negate();
				result.add(decimalResult.toString());
			} else if(type==DataType.Double) {
				Double doubleResult = -Double.parseDouble(argument.get(0));
				result.add(doubleResult.toString());
			}

			return result;
		}
	}
}


text:
package com.amazonaws.services.dynamodbv2.document;

import java.util.List;

import com.amazonaws.services.dynamodbv2.document.internal.InternalUtils;
import com.amazonaws.services.dynamodbv2.model.QueryResult;

/**
 * The outcome of query on DynamoDB table.
 */
public class QueryOutcome {
    private final QueryResult result;

    /**
     * @param result the low-level result; must not be null
     */
    public QueryOutcome(QueryResult result) {
        if (result == null)
            throw new IllegalArgumentException();
        this.result = result;
    }

    /**
     * Returns a non-null list of the returned items; can be empty.
     */
    public List<Item> getItems() {
        return InternalUtils.toItemList(result.getItems());
    }

    /**
     * Returns a non-null low-level result returned from the server side.
     */
    public QueryResult getQueryResult() {
        return result;
    }

    @Override
    public String toString() {
        return String.valueOf(result);
    }
}


text:
sigmod14
========

Sigmod 2014 Contest


text: from .pipeline import Pipeline


text:
title: Docker Swarm
author: Chris Ward, Claus Matzinger
description: Combining Crate with Docker Swarm allows for scalable clusters spread across data centers.

Docker Swarm is a great cluster orchestration tool that has been integrated into the Docker engine starting with their 1.12 release. Since this tooling is perfect for creating Crate clusters, we want to show you how to get three nodes of our SQL database working together.

## Prerequisites

 - [Docker machine](https://docs.docker.com/machine/install-machine/)
 - [A working Docker installation](https://docs.docker.com/engine/installation/)
 - A couple of nodes (for a development setup virtual machines work as well) with SSH access and Linux

Having that handy will provide a solid starting point for creating a Crate cluster.

## Setup

We are using 3 type-0 machines from our friends at [Packet.net](https://packet.net). To provision those (CentOS 7) machines, we have `docker-machine` take care of installing the Docker daemon by issuing this command on your development machine (for each of the nodes you want to provision). Be sure to replace <MANAGER-IP> with your actual IPs, `crate-sw-X` is the name of each node.

```bash
$ docker-machine create -d generic —generic-ip-address <MANAGER-IP> —generic-ssh-user root crate-sw-1
Running pre-create checks...
Creating machine...
(crate-sw-1) No SSH key specified. Assuming an existing key at the default location.
Waiting for machine to be running, this may take a few minutes...
Detecting operating system of created instance...
Waiting for SSH to be available...
Detecting the provisioner...
Provisioning with centos...
Copying certs to the local machine directory...
Copying certs to the remote machine...
Setting Docker configuration on the remote daemon...
Checking connection to Docker...
Docker is up and running!
To see how to connect your Docker Client to the Docker Engine running on this virtual machine, run: docker-machine env crate-sw-1
```

With Docker installed on every machine, we now have to join them into a swarm, but first let's check if all the machines are available:

```bash
$ docker-machine ls
NAME         ACTIVE   DRIVER       STATE     URL                         SWARM   DOCKER    ERRORS
crate-sw-1   -        generic      Running   tcp://<IP1>:2376           v1.12.1
crate-sw-2   -        generic      Running   tcp://<IP2>:2376           v1.12.1
crate-sw-3   -        generic      Running   tcp://<IP3>:2376           v1.12.1
```

## Gather Your Swarm

For the machines to work together, we can create a swarm with [Docker's Swarm](https://docs.docker.com/engine/swarm/) feature, which works in a Master-Slave configuration. Hence, in order to continue, choose one of these machines to become the master node:

```bash
$ eval $(docker-machine env crate-sw-1) # connect your local docker client to the remote machine
$ docker swarm init --advertise-addr <MANAGER-IP>:2377
Swarm initialized: current node (4dbxlrkuxnq7m36p7u8hiwba4) is now a manager.

To add a worker to this swarm, run the following command:

    docker swarm join \
    --token <TOKEN> \
    <MANAGER-IP>:2377

To add a manager to this swarm, run 'docker swarm join-token manager' and follow the instructions.
```

As the output of the previous command already suggests, join the worker nodes like this:

```bash
$ eval $(docker-machine env crate-sw-2) # connect the local docker client to one of the worker nodes
$ docker swarm join --token <TOKEN> <MANAGER-IP>:2377
This node joined a swarm as a worker.
$ eval $(docker-machine env crate-sw-3) # connect the local docker client to the other worker node
$ docker swarm join --token <TOKEN> <MANAGER-IP>:2377
This node joined a swarm as a worker.
```

Your swarm is now up and running, ready for a deployment.

## Ready to Serve

For the Crate cluster to talk to the nodes, we still need a network, which - for now - will be a Docker overlay network. For a production deployment, this should be a more informed choice since a software-emulated network connection might not perform as expected. In order to create the network run the following command:

```bash
$ docker network create -d overlay crate-network
6p7nxdurhzw2hcwy3bjm2z2wo
```

Finally we are able to run Crate on top of the Docker cluster! For this, a `docker service` is required - which is created by this command:

```bash
$ eval $(docker-machine env crate-sw-1) # connect your local docker client to the remote machine
$ docker service create \
    --name crate \
    --network crate-network \
    --mode global \
    --endpoint-mode dnsrr \
    --update-parallelism 1 \
    --update-delay 60s \
    --mount type=bind,source=/tmp,target=/data \
  crate:latest \
    crate \
    -Cdiscovery.zen.ping.unicast.hosts=crate \
    -Cgateway.expected_nodes=3 \
    -Cdiscovery.zen.minimum_master_nodes=2 \
    -Cgateway.recover_after_nodes=2 \
    -Cnetwork.bind=_site_
```

There are several things that need explanation in there:

```bash
    --name crate #\
    --network crate-network \
    --mode global \
```
These lines name the cluster 'crate', add the previously created overlay network to the service and set the scaling mode to "global", which means that there will always one container per node. Next the parameters:

```bash
    --endpoint-mode dnsrr \
    --update-parallelism 1 \
    --update-delay 60s \
    --mount type=bind,source=/tmp,target=/data \
```

define the endpoint mode to be 'dnsrr' (DNS round robin - the dns entry 'crate' should cycle through the available IP addresses), `update-parallelism` and `update-delay` set how many instances should be updated in parallel and with what delay. Finally there is some volume mapping to ensure Crate is writing data to a persistent volume outside of the container (*don't use /tmp 's tmpfs for storing data. It will be gone after restarting*).

```bash
  crate:latest \
    crate \
    -Cdiscovery.zen.ping.unicast.hosts=crate \
    -Cgateway.expected_nodes=3 \
    -Cdiscovery.zen.minimum_master_nodes=2 \
    -Cgateway.recover_after_nodes=2 \
    -Cnetwork.bind=_site_
```
This part is the same for many Docker deployments of Crate:

  - *Unicast hosts:* the Docker DNS record 'crate' (the service name) maps an IP address to the service name and let's the nodes discover each other
  - *Quorum parameters:*  since we are working with a 3-node cluster, the `expected_nodes`, `minimum_master_nodes`, and `recover_after_nodes` are [set accordingly][1]
  - *Set Crate's network binding:* the last line tells Crate to explicitly listen and bind to the IPv4 address of `eth0` (check if this is your `crate-network` NIC); required to work around container networking magic

## Scaling

By running the docker service in 'global mode', it automatically assigns one instance per node only. This means that by changing the number of nodes in a swarm, it will automatically scale up or down (also think of [reconfiguring the quorums][1])). To take control of this behavior, we recommend customizing [service constraints](https://docs.docker.com/engine/reference/commandline/service_create/#/specify-service-constraints-constraint) and labels. Alternatively 'replication mode' would allow for explicit scaling, but will also deploy more than one instance per machine, which is *greatly discouraged* since it gives a false impression about replication and resource availability.

## Next Steps

This setup gives you a working cluster but by setting the endpoint-mode to `DNSRR`, Docker disables its included load balancer and does not assign a public IP or port mapping to the cluster. The _other_ setting `VIP` (virtual IP) would provide a load-balanced public endpoint, but prohibits communication between the nodes. While we (and others) [consider this a bug](https://github.com/docker/docker/issues/25016), a fix by Docker has yet (as of mid-September 2016) to be released.

However since the ports are mapped automatically, there are steps to remedy this:

  - Use NGINX (or any reverse proxy server) to distribute requests among the swarm nodes by enumerating all container IPs in an [upstream section](http://nginx.org/en/docs/http/ngx_http_upstream_module.html)
  - Use a firewall ([firewalld](https://docs.fedoraproject.org/en-US/Fedora/19/html/Security_Guide/sec-Configure_Port_Forwarding-CLI.html), [IPTables](https://www.digitalocean.com/community/tutorials/how-to-forward-ports-through-a-linux-gateway-with-iptables), [UFW](https://help.ubuntu.com/lts/serverguide/firewall.html) ...) to forward requests to the ports to the containers (but be aware that the overlay network also requires [certain ports](http://stackoverflow.com/questions/37312055/can-firewalld-work-with-the-docker-overlay-network))


text:
<?php

namespace hflan\BlogBundle\Controller;

use hflan\BlogBundle\Entity\Article;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Doctrine\ORM\EntityManager;
use Knp\Component\Pager\Paginator;

class PublicController extends Controller
{
    /**
     * @var EntityManager
     */
    private $em;

    /**
     * @var Paginator
     */
    private $paginator;

    /**
     * @Template
     */
    public function homeAction()
    {
        $articles = $this->em->getRepository('hflanBlogBundle:Article')->queryAll($this->get('translator')->getLocale(), true);
        $pagination = $this->paginator->paginate($articles, 1, 5);

        $fbArticles = $this->get('hflan.facebook_api')->call('hf.lan.esiee?fields=feed.limit(10).fields(message,picture,type,link,from,actions,full_picture)');

        return array(
            'articles' => $pagination,
            'fbArticles' => $fbArticles,
        );
    }

    /**
     * @Template
     */
    public function indexAction($page)
    {
        $articles = $this->em->getRepository('hflanBlogBundle:Article')->queryAll($this->get('translator')->getLocale(), true);
        $pagination = $this->paginator->paginate($articles, $page, 7);

        return array(
            'pagination' => $pagination,
        );
    }

    /**
     * @Template
     */
    public function showAction(Article $article)
    {
        return array(
            'article' => $article,
        );
    }
}


text:
module Ziwei
  module Utils
    module CalcCommons
      module ClassMethods
      end

      module InstanceMethods
        def calc_self_body_position(birth_hour, birth_month)
          hour_index = Configs::Branches::Indexes[birth_hour]
          month_index = Configs::Branches::Indexes[birth_month]

          self_index = limit_inc(month_index, -hour_index+1)
          body_index = limit_inc(month_index, hour_index-1)

          [
            Configs::Branches::Orders[self_index],
            Configs::Branches::Orders[body_index]
          ]
        end

        def calc_palaces_positions(self_position)
          self_index = Configs::Branches::Indexes[self_position]

          branches = Configs::Branches::Names.keys
          palaces = Configs::Palaces::Orders

          merge_sequences_from_index(branches, palaces, self_index)
        end

        def calc_cuc(self_position, birth_year_stem)
          start_element = Configs::Wuxing::ElementsByBranches[self_position]
          start_element_index = Configs::Wuxing::Elements.index(start_element)
          counting_steps = Configs::Stems::Indexes[birth_year_stem]
          cuc_index = limit_inc(start_element_index, counting_steps, 5, 0)

          cuc_element = Configs::Wuxing::Elements[cuc_index]
          cuc_number = Configs::Wuxing::CucByElements[cuc_element]

          [cuc_element, cuc_number]
        end

        def calc_opportunity_ages(self_position, cuc_number, fate_direction)
          self_index = Configs::Branches::Indexes[self_position]

          branches = Configs::Branches::Names.keys
          ages = (0..11).map {|mult| cuc_number + 10*mult}

          merge_sequences_from_index(branches, ages, self_index, fate_direction == -1)
        end

        def calc_connected_palace_coordinates(self_position)
          self_index = Configs::Branches::Indexes[self_position]
          self_coordinate = Configs::Palaces::DrawingRootCoordinates[self_position]

          opposite_index = limit_inc(self_index, 6)
          opposite_position = Configs::Branches::Orders[opposite_index]
          opposite_coordinate = Configs::Palaces::DrawingRootCoordinates[opposite_position]

          trilogy_element = Configs::BranchSets::Trilogy::ByBranches[self_position]
          same_set_positions = Configs::BranchSets::Trilogy::ByElements[trilogy_element] - [self_position]
          same_set_coordinates = same_set_positions.map {|position|
            Configs::Palaces::DrawingRootCoordinates[position]
          }

          ([opposite_coordinate] + same_set_coordinates).map {|from_coordinate|
            [from_coordinate, self_coordinate]
          }
        end

        def merge_sequences_from_index(first_sequence, second_sequence, merge_index, reversed_order = false)
          second_seq = second_sequence.dup

          # re-arrange second sequence in order of first one,
          # skip if merge_index is 1 (2 sequences have identical order)
          if merge_index != 1
            second_seq = unless reversed_order
              second_seq[(12-merge_index+1)..-1] + second_seq[0..(12-merge_index)]
            else
              second_seq[0..merge_index-1].reverse + second_seq[merge_index..-1].reverse
            end
          end

          Hash[[first_sequence, second_seq].transpose]
        end
      end

      def self.included(receiver)
        receiver.extend         ClassMethods
        receiver.send :include, InstanceMethods
      end
    end
  end
end


text:
package com.example.alexeyglushkov.wordteacher.courselistmodules.courselistmodule.view;

import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.ItemTouchHelper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.alexeyglushkov.tools.TimeTools;
import com.example.alexeyglushkov.wordteacher.R;

import java.util.Date;
import java.util.List;
import java.util.Locale;

import com.example.alexeyglushkov.wordteacher.listmodule.view.BaseListAdaptor;
import com.example.alexeyglushkov.wordteacher.model.Card;
import com.example.alexeyglushkov.wordteacher.model.CardProgress;
import com.example.alexeyglushkov.wordteacher.tools.DeleteTouchHelper;
import com.example.alexeyglushkov.wordteacher.model.Course;

/**
 * Created by alexeyglushkov on 08.05.16.
 */
public class CourseListAdapter extends BaseListAdaptor<CourseListAdapter.ViewHolder, Course> implements DeleteTouchHelper.Listener {
    private Listener listener;
    private ItemTouchHelper deleteTouchHelper;

    //// Initialization

    public CourseListAdapter(Listener listener) {
        this.listener = listener;
        this.deleteTouchHelper = new ItemTouchHelper(new DeleteTouchHelper(this));
    }

    //// Events

    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
        deleteTouchHelper.attachToRecyclerView(recyclerView);
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cell_course, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        final Course course = getItems().get(position);
        bindWordNameTextView(holder, course);
        bindWordCountTextView(holder, course);
        bindProgressTextView(holder, course);
        bindListener(holder, course);
    }

    //// Actions

    @Override
    public void cleanup() {
        super.cleanup();
        listener = null;
        deleteTouchHelper = null;
    }

    private void bindWordNameTextView(ViewHolder holder, Course course) {
        holder.nameTextview.setText(course.getTitle());
    }

    private void bindWordCountTextView(ViewHolder holder, Course course) {
        String format = holder.itemView.getContext().getResources().getString(R.string.set_word_count_formant);
        String description = String.format(Locale.US, format, course.getCards().size());
        holder.wordCountTextView.setText(description);
    }

    private void bindProgressTextView(ViewHolder holder, Course course) {
        int inProgressCount = course.getInProgressCards().size();
        if (inProgressCount > 0 && inProgressCount == course.getCards().size()) {
            holder.inProgressTextView.setVisibility(View.VISIBLE);

            List<Card> waitingCards = course.getReadyToLearnCards();
            int waitingCardCount = waitingCards.size();
            if (waitingCardCount != 0) {
                String waitingFormat = holder.itemView.getContext().getResources().getString(R.string.cell_course_waiting_words);
                String inProgressString = String.format(Locale.US, waitingFormat, waitingCardCount);
                holder.inProgressTextView.setText(inProgressString);

            } else {
                Date date = getEarliestWaitCard(course.getCards());
                if (date != null) {
                    long duration = date.getTime() - new Date().getTime();
                    String format = holder.itemView.getContext().getString(R.string.cell_course_revise_time);
                    String timeString = String.format(Locale.US, format, TimeTools.getDurationString(duration));
                    holder.inProgressTextView.setText(timeString);
                } else {
                    holder.inProgressTextView.setText(R.string.cell_course_no_waiting_words);
                }
            }

        } else if (inProgressCount > 0) {
            holder.inProgressTextView.setVisibility(View.VISIBLE);
            String inProgressFormat = holder.itemView.getContext().getResources().getString(R.string.cell_course_in_progress);
            String inProgressString = String.format(Locale.US, inProgressFormat, inProgressCount);
            holder.inProgressTextView.setText(inProgressString);

        } else {
            holder.inProgressTextView.setText(null);
            holder.inProgressTextView.setVisibility(View.INVISIBLE);
        }
    }

    private Date getEarliestWaitCard(List<Card> waitingCards) {
        Date result = null;
        for (Card card : waitingCards) {
            CardProgress progress = card.getProgress();
            if (progress != null && !progress.isCompleted()) {
                Date lessonDate = progress.getNextLessonDate();
                if (result != null) {
                    result = lessonDate.compareTo(result) == -1 ? lessonDate : result;
                } else {
                    result = lessonDate;
                }
            }
        }

        return result;
    }

    private void bindListener(ViewHolder holder, final Course course) {
        holder.cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listener.onCourseClicked(v, course);
            }
        });

        holder.menuButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listener.onCourseMenuClicked(v, course);
            }
        });
    }

    public void onItemDeleted(RecyclerView.ViewHolder holder, int index, int position) {
        Course course = getItems().get(index);
        listener.onCourseViewDeleted(holder.itemView, course);

        deleteDataAtIndex(index);
        notifyItemRemoved(position);
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        public View cardView;
        public TextView nameTextview;
        public TextView wordCountTextView;
        public TextView inProgressTextView;
        public ImageView menuButton;

        public ViewHolder(View itemView) {
            super(itemView);
            cardView = itemView.findViewById(R.id.card);
            nameTextview = (TextView)itemView.findViewById(R.id.name);
            wordCountTextView = (TextView)itemView.findViewById(R.id.wordCount);
            menuButton = (ImageView)itemView.findViewById(R.id.menuButton);
            inProgressTextView = (TextView)itemView.findViewById(R.id.inProgressCount);
        }
    }

    public interface Listener {
        void onCourseClicked(View view, Course card);
        void onCourseMenuClicked(View view, Course card);
        void onCourseViewDeleted(View view, Course course);
    }
}


text:
from beritest_tools import BaseBERITestCase
from nose.plugins.attrib import attr

#
# Test cswr (store word via capability, offset by register) with a constrained
# capability.
#

class test_cp2_cswr_unpriv(BaseBERITestCase):
    @attr('capabilities')
    def test_cp2_cswr_underflow(self):
        '''Test that cswr did not write below constrained capability'''
        self.assertRegisterEqual(self.MIPS.a0, 0x0, "cswr underflow with constrained capability")

    @attr('capabilities')
    def test_cp2_cswr_data(self):
        '''Test that cswr wrote correctly via constrained capability'''
        self.assertRegisterEqual(self.MIPS.a1, 0x0123456789abcdef, "cswr data written incorrectly with constrained capability")

    @attr('capabilities')
    def test_cp2_cswr_overflow(self):
        '''Test that cswr did not write above constrained capability'''
        self.assertRegisterEqual(self.MIPS.a2, 0x0, "cswr overflow with constrained capability")