text:
import os
import sys
import time

import psutil
import pytest

import ray
from ray._private import ray_constants
from ray._private.test_utils import (
    RayTestTimeoutException,
    get_error_message,
    init_error_pubsub,
    object_memory_usage,
    run_string_as_driver,
    run_string_as_driver_nonblocking,
    wait_for_condition,
)

@pytest.mark.parametrize(
    "call_ray_start",
    [
        "ray start --head --num-cpus=1 --min-worker-port=0 "
        "--max-worker-port=0 --port 0",
    ],
    indirect=True,
)
def test_cleanup_on_driver_exit(call_ray_start):
    # This test will create a driver that creates a bunch of objects and then
    # exits. The entries in the object table should be cleaned up.
    address = call_ray_start

    ray.init(address=address)

    # Define a driver that creates a bunch of objects and exits.
    driver_script = """
import time
import ray
import numpy as np
from ray._private.test_utils import object_memory_usage
import os

ray.init(address="{}")
object_refs = [ray.put(np.zeros(200 * 1024, dtype=np.uint8))
              for i in range(1000)]
start_time = time.time()
while time.time() - start_time < 30:
    if object_memory_usage() > 0:
        break
else:
    raise Exception("Objects did not appear in object table.")

@ray.remote
def f():
    time.sleep(1)

print("success")
# Submit some tasks without waiting for them to finish. Their workers should
# still get cleaned up eventually, even if they get started after the driver
# exits.
[f.remote() for _ in range(10)]
""".format(
        address
    )

    out = run_string_as_driver(driver_script)
    assert "success" in out

    # Make sure the objects are removed from the object table.
    start_time = time.time()
    while time.time() - start_time < 30:
        if object_memory_usage() == 0:
            break
    else:
        raise Exception("Objects were not all removed from object table.")

    def all_workers_exited():
        result = True
        print("list of idle workers:")
        for proc in psutil.process_iter():
            if ray_constants.WORKER_PROCESS_TYPE_IDLE_WORKER in proc.name():
                print(f"{proc}")
                result = False
        return result

    # Check that workers are eventually cleaned up.
    wait_for_condition(all_workers_exited, timeout=15, retry_interval_ms=1000)

def test_error_isolation(call_ray_start):
    address = call_ray_start
    # Connect a driver to the Ray cluster.
    ray.init(address=address)

    # If a GRPC call exceeds timeout, the calls is cancelled at client side but
    # server may still reply to it, leading to missed message. Using a sequence
    # number to ensure no message is dropped can be the long term solution,
    # but its complexity and the fact the Ray subscribers do not use deadline
    # in production makes it less preferred.
    # Therefore, a simpler workaround is used instead: a different subscriber
    # is used for each get_error_message() call.
    subscribers = [init_error_pubsub() for _ in range(3)]

    # There shouldn't be any errors yet.
    errors = get_error_message(subscribers[0], 1, timeout=2)
    assert len(errors) == 0

    error_string1 = "error_string1"
    error_string2 = "error_string2"

    @ray.remote
    def f():
        raise Exception(error_string1)

    # Run a remote function that throws an error.
    with pytest.raises(Exception):
        ray.get(f.remote())

    # Wait for the error to appear in Redis.
    errors = get_error_message(subscribers[1], 1)

    # Make sure we got the error.
    assert len(errors) == 1
    assert error_string1 in errors[0].error_message

    # Start another driver and make sure that it does not receive this
    # error. Make the other driver throw an error, and make sure it
    # receives that error.
    driver_script = """
import ray
import time
from ray._private.test_utils import init_error_pubsub, get_error_message

ray.init(address="{}")
subscribers = [init_error_pubsub() for _ in range(2)]
time.sleep(1)
errors = get_error_message(subscribers[0], 1, timeout=2)
assert len(errors) == 0

@ray.remote
def f():
    raise Exception("{}")

try:
    ray.get(f.remote())
except Exception as e:
    pass

errors = get_error_message(subscribers[1], 1)
assert len(errors) == 1

assert "{}" in errors[0].error_message

print("success")
""".format(
        address, error_string2, error_string2
    )

    out = run_string_as_driver(driver_script)
    # Make sure the other driver succeeded.
    assert "success" in out

    # Make sure that the other error message doesn't show up for this
    # driver.
    errors = get_error_message(subscribers[2], 1)
    assert len(errors) == 1

def test_remote_function_isolation(call_ray_start):
    # This test will run multiple remote functions with the same names in
    # two different drivers. Connect a driver to the Ray cluster.
    address = call_ray_start

    ray.init(address=address)

    # Start another driver and make sure that it can define and call its
    # own commands with the same names.
    driver_script = """
import ray
import time
ray.init(address="{}")
@ray.remote
def f():
    return 3
@ray.remote
def g(x, y):
    return 4
for _ in range(10000):
    result = ray.get([f.remote(), g.remote(0, 0)])
    assert result == [3, 4]
print("success")
""".format(
        address
    )

    out = run_string_as_driver(driver_script)

    @ray.remote
    def f():
        return 1

    @ray.remote
    def g(x):
        return 2

    for _ in range(10000):
        result = ray.get([f.remote(), g.remote(0)])
        assert result == [1, 2]

    # Make sure the other driver succeeded.
    assert "success" in out

def test_driver_exiting_quickly(call_ray_start):
    # This test will create some drivers that submit some tasks and then
    # exit without waiting for the tasks to complete.
    address = call_ray_start

    ray.init(address=address)

    # Define a driver that creates an actor and exits.
    driver_script1 = """
import ray
ray.init(address="{}")
@ray.remote
class Foo:
    def __init__(self):
        pass
Foo.remote()
print("success")
""".format(
        address
    )

    # Define a driver that creates some tasks and exits.
    driver_script2 = """
import ray
ray.init(address="{}")
@ray.remote
def f():
    return 1
f.remote()
print("success")
""".format(
        address
    )

    # Create some drivers and let them exit and make sure everything is
    # still alive.
    for _ in range(3):
        out = run_string_as_driver(driver_script1)
        # Make sure the first driver ran to completion.
        assert "success" in out
        out = run_string_as_driver(driver_script2)
        # Make sure the first driver ran to completion.
        assert "success" in out

def test_drivers_named_actors(call_ray_start):
    # This test will create some drivers that submit some tasks to the same
    # named actor.
    address = call_ray_start

    ray.init(address=address, namespace="test")

    # Define a driver that creates a named actor then sleeps for a while.
    driver_script1 = """
import ray
import time
ray.init(address="{}", namespace="test")
@ray.remote
class Counter:
    def __init__(self):
        self.count = 0
    def increment(self):
        self.count += 1
        return self.count
counter = Counter.options(name="Counter").remote()
time.sleep(100)
""".format(
        address
    )

    # Define a driver that submits to the named actor and exits.
    driver_script2 = """
import ray
import time
ray.init(address="{}", namespace="test")
while True:
    try:
        counter = ray.get_actor("Counter")
        break
    except ValueError:
        time.sleep(1)
assert ray.get(counter.increment.remote()) == {}
print("success")
""".format(
        address, "{}"
    )

    process_handle = run_string_as_driver_nonblocking(driver_script1)

    for i in range(3):
        driver_script = driver_script2.format(i + 1)
        out = run_string_as_driver(driver_script)
        assert "success" in out

    process_handle.kill()

def test_receive_late_worker_logs():
    # Make sure that log messages from tasks appear in the stdout even if the
    # script exits quickly.
    log_message = "some helpful debugging message"

    # Define a driver that creates a task that prints something, ensures that
    # the task runs, and then exits.
    driver_script = """
import ray
import random
import time

log_message = "{}"

@ray.remote
class Actor:
    def log(self):
        print(log_message)

@ray.remote
def f():
    print(log_message)

ray.init(num_cpus=2)

a = Actor.remote()
ray.get([a.log.remote(), f.remote()])
ray.get([a.log.remote(), f.remote()])
""".format(
        log_message
    )

    for _ in range(2):
        out = run_string_as_driver(driver_script)
        assert out.count(log_message) == 4

@pytest.mark.parametrize(
    "call_ray_start",
    [
        "ray start --head --num-cpus=1 --num-gpus=1 "
        + "--min-worker-port=0 --max-worker-port=0 --port 0"
    ],
    indirect=True,
)
def test_drivers_release_resources(call_ray_start):
    address = call_ray_start

    # Define a driver that creates an actor and exits.
    driver_script1 = """
import time
import ray

ray.init(address="{}")

@ray.remote
def f(duration):
    time.sleep(duration)

@ray.remote(num_gpus=1)
def g(duration):
    time.sleep(duration)

@ray.remote(num_gpus=1)
class Foo:
    def __init__(self):
        pass

# Make sure some resources are available for us to run tasks.
ray.get(f.remote(0))
ray.get(g.remote(0))

# Start a bunch of actors and tasks that use resources. These should all be
# cleaned up when this driver exits.
foos = [Foo.remote() for _ in range(100)]
[f.remote(10 ** 6) for _ in range(100)]

print("success")
""".format(
        address
    )

    driver_script2 = (
        driver_script1 + "import sys\nsys.stdout.flush()\ntime.sleep(10 ** 6)\n"
    )

    def wait_for_success_output(process_handle, timeout=10):
        # Wait until the process prints "success" and then return.
        start_time = time.time()
        while time.time() - start_time < timeout:
            output_line = ray._private.utils.decode(
                process_handle.stdout.readline()
            ).strip()
            print(output_line)
            if output_line == "success":
                return
            time.sleep(1)
        raise RayTestTimeoutException("Timed out waiting for process to print success.")

    # Make sure we can run this driver repeatedly, which means that resources
    # are getting released in between.
    for _ in range(5):
        out = run_string_as_driver(driver_script1)
        # Make sure the first driver ran to completion.
        assert "success" in out
        # Also make sure that this works when the driver exits ungracefully.
        process_handle = run_string_as_driver_nonblocking(driver_script2)
        wait_for_success_output(process_handle)
        # Kill the process ungracefully.
        process_handle.kill()

if __name__ == "__main__":
    import pytest

    # Make subprocess happy in bazel.
    os.environ["LC_ALL"] = "en_US.UTF-8"
    os.environ["LANG"] = "en_US.UTF-8"
    if os.environ.get("PARALLEL_CI"):
        sys.exit(pytest.main(["-n", "auto", "--boxed", "-vs", __file__]))
    else:
        sys.exit(pytest.main(["-sv", __file__]))


text:
package nam.model.pod;

import java.io.Serializable;
import java.util.Collection;

import javax.enterprise.context.ApplicationScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import javax.inject.Named;

import org.aries.ui.validate.AbstractValidator;

import nam.model.Pod;
import nam.model.util.PodUtil;

@ApplicationScoped
@Named("podValidator")
public class PodValidator extends AbstractValidator implements Validator, Serializable {

	@Override
	public void validate(FacesContext facesContext, UIComponent uiComponent, Object value) throws ValidatorException {
		resetState();
		if (value != null) {
			if (value instanceof Pod == false)
				throwError("Unexpected value: "+value);
			Pod pod = (Pod) value;
			if (PodUtil.validate(pod) == false) {
				Collection<String> messages = getValidator().getMessages();
				getDisplay().addErrors(messages);
				throwErrors(messages);
			}
		}
	}

}

redpajama_set_name: RedPajamaGithub


text:
from oslo.serialization import jsonutils

from neutron.openstack.common import log as logging
from neutron.plugins.bigswitch import servermanager

LOG = logging.getLogger(__name__)

class HTTPResponseMock(object):
    status = 200
    reason = 'OK'

    def __init__(self, sock, debuglevel=0, strict=0, method=None,
                 buffering=False):
        pass

    def read(self):
        return "{'status': '200 OK'}"

    def getheader(self, header):
        return None

class HTTPResponseMock404(HTTPResponseMock):
    status = 404
    reason = 'Not Found'

    def read(self):
        return "{'status': '%s 404 Not Found'}" % servermanager.NXNETWORK

class HTTPResponseMock500(HTTPResponseMock):
    status = 500
    reason = 'Internal Server Error'

    def __init__(self, sock, debuglevel=0, strict=0, method=None,
                 buffering=False, errmsg='500 Internal Server Error'):
        self.errmsg = errmsg

    def read(self):
        return "{'status': '%s'}" % self.errmsg

class HTTPConnectionMock(object):

    def __init__(self, server, port, timeout):
        self.response = None
        self.broken = False
        # Port 9000 is the broken server
        if port == 9000:
            self.broken = True
            errmsg = "This server is broken, please try another"
            self.response = HTTPResponseMock500(None, errmsg=errmsg)

    def request(self, action, uri, body, headers):
        LOG.debug("Request: action=%(action)s, uri=%(uri)r, "
                  "body=%(body)s, headers=%(headers)s",
                  {'action': action, 'uri': uri,
                   'body': body, 'headers': headers})
        if self.broken and "ExceptOnBadServer" in uri:
            raise Exception("Broken server got an unexpected request")
        if self.response:
            return

        # detachment may return 404 and plugin shouldn't die
        if uri.endswith('attachment') and action == 'DELETE':
            self.response = HTTPResponseMock404(None)
        else:
            self.response = HTTPResponseMock(None)

        # Port creations/updates must contain binding information
        if ('port' in uri and 'attachment' not in uri
            and 'binding' not in body and action in ('POST', 'PUT')):
            errmsg = "Port binding info missing in port request '%s'" % body
            self.response = HTTPResponseMock500(None, errmsg=errmsg)
            return

        return

    def getresponse(self):
        return self.response

    def close(self):
        pass

class HTTPConnectionMock404(HTTPConnectionMock):

    def __init__(self, server, port, timeout):
        self.response = HTTPResponseMock404(None)
        self.broken = True

class HTTPConnectionMock500(HTTPConnectionMock):

    def __init__(self, server, port, timeout):
        self.response = HTTPResponseMock500(None)
        self.broken = True

class VerifyMultiTenantFloatingIP(HTTPConnectionMock):

    def request(self, action, uri, body, headers):
        # Only handle network update requests
        if 'network' in uri and 'tenant' in uri and 'ports' not in uri:
            req = jsonutils.loads(body)
            if 'network' not in req or 'floatingips' not in req['network']:
                msg = _("No floating IPs in request"
                        "uri=%(uri)s, body=%(body)s") % {'uri': uri,
                                                         'body': body}
                raise Exception(msg)
            distinct_tenants = []
            for flip in req['network']['floatingips']:
                if flip['tenant_id'] not in distinct_tenants:
                    distinct_tenants.append(flip['tenant_id'])
            if len(distinct_tenants) < 2:
                msg = _("Expected floating IPs from multiple tenants."
                        "uri=%(uri)s, body=%(body)s") % {'uri': uri,
                                                         'body': body}
                raise Exception(msg)
        super(VerifyMultiTenantFloatingIP,
              self).request(action, uri, body, headers)

class HTTPSMockBase(HTTPConnectionMock):
    expected_cert = ''
    combined_cert = None

    def __init__(self, host, port=None, key_file=None, cert_file=None,
                 strict=None, timeout=None, source_address=None):
        self.host = host
        super(HTTPSMockBase, self).__init__(host, port, timeout)

    def request(self, method, url, body=None, headers={}):
        self.connect()
        super(HTTPSMockBase, self).request(method, url, body, headers)

class HTTPSNoValidation(HTTPSMockBase):

    def connect(self):
        if self.combined_cert:
            raise Exception('combined_cert set on NoValidation')

class HTTPSCAValidation(HTTPSMockBase):
    expected_cert = 'DUMMYCERTIFICATEAUTHORITY'

    def connect(self):
        contents = get_cert_contents(self.combined_cert)
        if self.expected_cert not in contents:
            raise Exception('No dummy CA cert in cert_file')

class HTTPSHostValidation(HTTPSMockBase):
    expected_cert = 'DUMMYCERTFORHOST%s'

    def connect(self):
        contents = get_cert_contents(self.combined_cert)
        expected = self.expected_cert % self.host
        if expected not in contents:
            raise Exception(_('No host cert for %(server)s in cert %(cert)s'),
                            {'server': self.host, 'cert': contents})

def get_cert_contents(path):
    raise Exception('METHOD MUST BE MOCKED FOR TEST')


text:
<?php

	$about = array(
		'name' => 'Italiano',
		'author' => array(
			'name' => 'Simone Economo',
			'email' => 'my.ekoes@gmail.com',
			'website' => 'http://lineheight.net',
		),
		'release-date' => '2010-02-27',
	);

	/**
	 * Export Ensemble
	 */
	$dictionary = array(

		'Missing File' =>
		'File mancante',

		'Install Symphony Version %s' =>
		'Installa Symphony versione %s',

		'It appears that install.sql is either missing or not readable. This is required to populate the database and must be uploaded before installation can commence. Ensure that PHP has read permissions.' =>
		'Sembra che il file install.sql non esista o non abbia i permessi in lettura. Senza questo file, non è possibile popolare il database e avviare l\'installazione. Assicurati che PHP abbia i permessi in lettura.',

		'Existing Installation' =>
		'Installazione pre-esistente',

		'It appears that Symphony has already been installed at this location.' =>
		'Sembra che Symphony sia già stato installato in questa cartella.',

		'Export Ensemble cannot be installed, since the "ZipArchive" class is not available. Ensure that PHP was compiled with the --enable-zip flag.' =>
		'L\'estensione \'Export Ensemble\' non può essere installata perché la classe "ZipArchive" non è disponibile. Assicurati di aver compilato PHP con l\'opzione --enable-zip.',

		'Export Ensemble' =>
		'Esporta Ensemble',

		'Warning: It appears you do not have the "ZipArchive" class available. Ensure that PHP was compiled with --enable-zip' =>
		'Attenzione: Sembra che la classe "ZipArchive" non sia disponibile. Assicurati che PHP sia stato compilato con l\'opzione --enable-zip',

		'Create' =>
		'Crea l\'archivio',

		'Packages entire site as a .zip archive for download.' =>
		'Comprime l\'intero sito in un pacchetto .zip pronto da scaricare.',

	);


text:
package com.github.rjeschke.neetutils.iterables;

import java.util.Iterator;

import com.github.rjeschke.neetutils.fn.FnMapping;

/**
 *
 * @author René Jeschke (rene_jeschke@yahoo.de)
 *
 * @param <A>
 * @param <B>
 */
class XIterableMap<A, B> extends AbstractXIterable<B>
{
    private final Iterable<? extends A> iterable;
    private final FnMapping<A, B>       mapping;

    public XIterableMap(final Iterable<? extends A> iterable, final FnMapping<A, B> mapping)
    {
        this.iterable = iterable;
        this.mapping = mapping;
    }

    @Override
    public Iterator<B> iterator()
    {
        return new XIterableMap.XIterator<>(this.iterable.iterator(), this.mapping);
    }

    private final static class XIterator<A, B> implements Iterator<B>
    {
        private final Iterator<? extends A> iterator;
        private final FnMapping<A, B>       mapping;

        public XIterator(final Iterator<? extends A> iterator, final FnMapping<A, B> mapping)
        {
            this.iterator = iterator;
            this.mapping = mapping;
        }

        @Override
        public boolean hasNext()
        {
            return this.iterator.hasNext();
        }

        @Override
        public B next()
        {
            return this.mapping.applyMapping(this.iterator.next());
        }

        @Override
        public void remove()
        {
            throw new IllegalStateException("XIterators are read-only.");
        }
    }
}


text:
/* eslint-disable import/prefer-default-export */
/* eslint-disable no-undef */
import axios from 'axios';
import { browserHistory } from 'react-router';
import * as actionTypes from '../actionTypes';
import setAuthorizationToken from '../../utils/setAuth';

/**
 * searchDocuments
 * @export
 * @param {Object} query
 * @param {Object} offset
 * @returns {Object} object
 */
export default (query, offset) => {
  return (dispatch) => {
    const token = window.localStorage.getItem('token');
    setAuthorizationToken(token);
    return axios.get('/api/search/document', {
      params: {
        query,
        offset
      }
    })
    .then((documents) => {
      const data = documents.data.documents
      dispatch({
        type: actionTypes.SEARCH_DOCS_COMPLETE,
        data,
        query,
        status: 'success',
        pageCount: documents.data.metadata.pages
      });
      Materialize.toast("Here's what we found", 2000, 'green');
    })
    .catch((error) => {
      let errorData;
        if(error.response.data.errors !== undefined) {
          errorData = error.response.data.errors[0].message
        } else {
          errorData = error.response.data.message
        }
        Materialize.toast(
          errorData, 3000, 'red');
      dispatch({
        type: actionTypes.SEARCH_DOCS_FAILED,
        status: 'failed',
        error: error.message
      });
    });
  };
};


text:
package thaumcraft.api.wands;

import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StatCollector;

import org.apache.logging.log4j.LogManager;

import thaumcraft.api.aspects.Aspect;
import thaumcraft.api.aspects.AspectList;

public class FocusUpgradeType {

	public static FocusUpgradeType[] types = new FocusUpgradeType[20];

	public short id;

	public ResourceLocation icon;

	public String name;

	public String text;

	/**
	 * What aspects are used to calculate the cost of this upgrade. The amounts given is ignored, just the type is used for the calculation.
	 */
	public AspectList aspects;

	public FocusUpgradeType(int id, ResourceLocation icon, String name, String text, AspectList aspects) {
		this.id = (short) id;
		this.icon = icon;
		this.name = name;
		this.text = text;
		this.aspects = aspects;

		if (id<types.length && types[id]!=null) {
			LogManager.getLogger("THAUMCRAFT").fatal("Focus Upgrade id "+id+" already occupied. Ignoring.");
			return;
		}

		// allocate space
		if (id>=types.length) {
			FocusUpgradeType[] temp = new FocusUpgradeType[id+1];
			System.arraycopy(types, 0, temp, 0, types.length);
			types = temp;
		}

		types[id] = this;
	}

	public String getLocalizedName() {
		return StatCollector.translateToLocal(name);
	}

	public String getLocalizedText() {
		return StatCollector.translateToLocal(text);
	}

	@Override
	public boolean equals(Object obj) {
		if (obj instanceof FocusUpgradeType) {
			return this.id == ((FocusUpgradeType)obj).id;
		} else return false;
	}

	// basic upgrade types
	public static FocusUpgradeType potency = new FocusUpgradeType( 0,
			new ResourceLocation("thaumcraft", "textures/foci/potency.png"),
			"focus.upgrade.potency.name","focus.upgrade.potency.text",
			new AspectList().add(Aspect.WEAPON,1));

	public static FocusUpgradeType frugal = new FocusUpgradeType( 1,
			new ResourceLocation("thaumcraft", "textures/foci/frugal.png"),
			"focus.upgrade.frugal.name","focus.upgrade.frugal.text",
			new AspectList().add(Aspect.HUNGER,1));

	public static FocusUpgradeType treasure = new FocusUpgradeType( 2,
			new ResourceLocation("thaumcraft", "textures/foci/treasure.png"),
			"focus.upgrade.treasure.name","focus.upgrade.treasure.text",
			new AspectList().add(Aspect.GREED,1));

	public static FocusUpgradeType enlarge = new FocusUpgradeType( 3,
			new ResourceLocation("thaumcraft", "textures/foci/enlarge.png"),
			"focus.upgrade.enlarge.name","focus.upgrade.enlarge.text",
			new AspectList().add(Aspect.TRAVEL,1));

	public static FocusUpgradeType alchemistsfire = new FocusUpgradeType( 4,
			new ResourceLocation("thaumcraft", "textures/foci/alchemistsfire.png"),
			"focus.upgrade.alchemistsfire.name","focus.upgrade.alchemistsfire.text",
			new AspectList().add(Aspect.ENERGY,1).add(Aspect.SLIME,1));

	public static FocusUpgradeType alchemistsfrost = new FocusUpgradeType( 5,
			new ResourceLocation("thaumcraft", "textures/foci/alchemistsfrost.png"),
			"focus.upgrade.alchemistsfrost.name","focus.upgrade.alchemistsfrost.text",
			new AspectList().add(Aspect.COLD,1).add(Aspect.TRAP,1));

	public static FocusUpgradeType architect = new FocusUpgradeType( 6,
			new ResourceLocation("thaumcraft", "textures/foci/architect.png"),
			"focus.upgrade.architect.name","focus.upgrade.architect.text",
			new AspectList().add(Aspect.CRAFT,1));

	public static FocusUpgradeType extend = new FocusUpgradeType( 7,
			new ResourceLocation("thaumcraft", "textures/foci/extend.png"),
			"focus.upgrade.extend.name","focus.upgrade.extend.text",
			new AspectList().add(Aspect.EXCHANGE,1));

	public static FocusUpgradeType silktouch = new FocusUpgradeType( 8,
			new ResourceLocation("thaumcraft", "textures/foci/silktouch.png"),
			"focus.upgrade.silktouch.name","focus.upgrade.silktouch.text",
			new AspectList().add(Aspect.GREED,1));

}


text:
'''
Created on Apr 30, 2015

@author: pekzeki
'''

from pymongo import MongoClient
import networkx as nx
from network_analysis import graph_analysis as GA

degreeness_attack_list = ['rpOyqD_893cqmDAtJLbdog',
         'lC0KGXmIhyjzghBUlVnkhQ',
         'OXWWC30x-1Ee0B6hXLLZfw',
         'TWIg1Jx2jGiC8UqaKpNorw',
         'Q9SKKZgbTMf5fXTQerFdqw']

closeness_attack_list = ['rpOyqD_893cqmDAtJLbdog',
         'lC0KGXmIhyjzghBUlVnkhQ',
         '7zpDhrRZRTGCkAh3SHbEww',
         '_A_2A-bjADJTKBoWd_B5qg',
         'TWIg1Jx2jGiC8UqaKpNorw']

betweenness_attack_list = ['rpOyqD_893cqmDAtJLbdog',
         'lC0KGXmIhyjzghBUlVnkhQ',
         '7zpDhrRZRTGCkAh3SHbEww',
         'OXWWC30x-1Ee0B6hXLLZfw',
         'TWIg1Jx2jGiC8UqaKpNorw']

def attacked_graph(attack_list):

    G = nx.Graph()
    for user in user_collection.find():
        G.add_node(user.get("_id"))
        friend_list = user.get("friends")
        for friend in friend_list:
            G.add_edge(user.get("_id"), friend)

    for number in attack_list:
        G.remove_node(number)

    return G

client = MongoClient()
db = client.yelp
user_collection = db.user_il_filtered
review_collection = db.review_il_filtered
business_collection = db.business_il_filtered

#D = attacked_graph(degreeness_attack_list)
#C = attacked_graph(closeness_attack_list)
B = attacked_graph(betweenness_attack_list)

#GA.analyze(D, "degreeness_attack")
#GA.analyze(C, "closeness_attack")
GA.analyze(B, "betweenness_attack")


text:
This set of MATLAB scripts creates an en face image map of reticular pseudodrusen from a macular cube scan.

## Instructions

- use multi_tif_to_arr('tifname.tif') to load a multipage tiff into MATLAB array structure
- use extract_enface(mac_cube_arr,slab_size) to generate an RPD en face image

## Components

- multi_tif_to_arr.m : Convert multi page tiff to matlab array structure
- flatten_bscan.m : Flatten an OCT B-scan image at the level of the RPE
- flatten_cube.m : Flatten a mac cube by iterratively calling flatten_bscan
- rpe_contour.m : script to identify RPE contour on an OCT b-scan
- extract_enface.m : wrapper script which simplifies generation of flattened en face images from structural OCT data


text:
'use strict';
import * as React from 'react';
import StyleSheet from '../../StyleSheet/StyleSheet';
import Text from '../../Text/Text';
import View from '../View/View';
import type {DatePickerIOSType} from './DatePickerIOS.flow';

class DummyDatePickerIOS extends React.Component {
  render() {
    return (
      <View style={[styles.dummyDatePickerIOS, this.props.style]}>
        <Text style={styles.datePickerText}>
          DatePickerIOS is not supported on this platform!
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  dummyDatePickerIOS: {
    height: 100,
    width: 300,
    backgroundColor: '#ffbcbc',
    borderWidth: 1,
    borderColor: 'red',
    alignItems: 'center',
    justifyContent: 'center',
    margin: 10,
  },
  datePickerText: {
    color: '#333333',
    margin: 20,
  },
});

module.exports = (DummyDatePickerIOS: DatePickerIOSType);


text:
from hazelcast.protocol.builtin import FixSizedTypesCodec, CodecUtil
from hazelcast.serialization.bits import *
from hazelcast.protocol.client_message import END_FRAME_BUF, END_FINAL_FRAME_BUF, SIZE_OF_FRAME_LENGTH_AND_FLAGS, create_initial_buffer_custom
from hazelcast.core import SimpleEntryView
from hazelcast.protocol.builtin import DataCodec

_COST_ENCODE_OFFSET = 2 * SIZE_OF_FRAME_LENGTH_AND_FLAGS
_COST_DECODE_OFFSET = 0
_CREATION_TIME_ENCODE_OFFSET = _COST_ENCODE_OFFSET + LONG_SIZE_IN_BYTES
_CREATION_TIME_DECODE_OFFSET = _COST_DECODE_OFFSET + LONG_SIZE_IN_BYTES
_EXPIRATION_TIME_ENCODE_OFFSET = _CREATION_TIME_ENCODE_OFFSET + LONG_SIZE_IN_BYTES
_EXPIRATION_TIME_DECODE_OFFSET = _CREATION_TIME_DECODE_OFFSET + LONG_SIZE_IN_BYTES
_HITS_ENCODE_OFFSET = _EXPIRATION_TIME_ENCODE_OFFSET + LONG_SIZE_IN_BYTES
_HITS_DECODE_OFFSET = _EXPIRATION_TIME_DECODE_OFFSET + LONG_SIZE_IN_BYTES
_LAST_ACCESS_TIME_ENCODE_OFFSET = _HITS_ENCODE_OFFSET + LONG_SIZE_IN_BYTES
_LAST_ACCESS_TIME_DECODE_OFFSET = _HITS_DECODE_OFFSET + LONG_SIZE_IN_BYTES
_LAST_STORED_TIME_ENCODE_OFFSET = _LAST_ACCESS_TIME_ENCODE_OFFSET + LONG_SIZE_IN_BYTES
_LAST_STORED_TIME_DECODE_OFFSET = _LAST_ACCESS_TIME_DECODE_OFFSET + LONG_SIZE_IN_BYTES
_LAST_UPDATE_TIME_ENCODE_OFFSET = _LAST_STORED_TIME_ENCODE_OFFSET + LONG_SIZE_IN_BYTES
_LAST_UPDATE_TIME_DECODE_OFFSET = _LAST_STORED_TIME_DECODE_OFFSET + LONG_SIZE_IN_BYTES
_VERSION_ENCODE_OFFSET = _LAST_UPDATE_TIME_ENCODE_OFFSET + LONG_SIZE_IN_BYTES
_VERSION_DECODE_OFFSET = _LAST_UPDATE_TIME_DECODE_OFFSET + LONG_SIZE_IN_BYTES
_TTL_ENCODE_OFFSET = _VERSION_ENCODE_OFFSET + LONG_SIZE_IN_BYTES
_TTL_DECODE_OFFSET = _VERSION_DECODE_OFFSET + LONG_SIZE_IN_BYTES
_MAX_IDLE_ENCODE_OFFSET = _TTL_ENCODE_OFFSET + LONG_SIZE_IN_BYTES
_MAX_IDLE_DECODE_OFFSET = _TTL_DECODE_OFFSET + LONG_SIZE_IN_BYTES
_INITIAL_FRAME_SIZE = _MAX_IDLE_ENCODE_OFFSET + LONG_SIZE_IN_BYTES - SIZE_OF_FRAME_LENGTH_AND_FLAGS

class SimpleEntryViewCodec:
    @staticmethod
    def encode(buf, simple_entry_view, is_final=False):
        initial_frame_buf = create_initial_buffer_custom(_INITIAL_FRAME_SIZE)
        FixSizedTypesCodec.encode_long(initial_frame_buf, _COST_ENCODE_OFFSET, simple_entry_view.cost)
        FixSizedTypesCodec.encode_long(initial_frame_buf, _CREATION_TIME_ENCODE_OFFSET, simple_entry_view.creation_time)
        FixSizedTypesCodec.encode_long(initial_frame_buf, _EXPIRATION_TIME_ENCODE_OFFSET, simple_entry_view.expiration_time)
        FixSizedTypesCodec.encode_long(initial_frame_buf, _HITS_ENCODE_OFFSET, simple_entry_view.hits)
        FixSizedTypesCodec.encode_long(initial_frame_buf, _LAST_ACCESS_TIME_ENCODE_OFFSET, simple_entry_view.last_access_time)
        FixSizedTypesCodec.encode_long(initial_frame_buf, _LAST_STORED_TIME_ENCODE_OFFSET, simple_entry_view.last_stored_time)
        FixSizedTypesCodec.encode_long(initial_frame_buf, _LAST_UPDATE_TIME_ENCODE_OFFSET, simple_entry_view.last_update_time)
        FixSizedTypesCodec.encode_long(initial_frame_buf, _VERSION_ENCODE_OFFSET, simple_entry_view.version)
        FixSizedTypesCodec.encode_long(initial_frame_buf, _TTL_ENCODE_OFFSET, simple_entry_view.ttl)
        FixSizedTypesCodec.encode_long(initial_frame_buf, _MAX_IDLE_ENCODE_OFFSET, simple_entry_view.max_idle)
        buf.extend(initial_frame_buf)
        DataCodec.encode(buf, simple_entry_view.key)
        DataCodec.encode(buf, simple_entry_view.value)
        if is_final:
            buf.extend(END_FINAL_FRAME_BUF)
        else:
            buf.extend(END_FRAME_BUF)

    @staticmethod
    def decode(msg):
        msg.next_frame()
        initial_frame = msg.next_frame()
        cost = FixSizedTypesCodec.decode_long(initial_frame.buf, _COST_DECODE_OFFSET)
        creation_time = FixSizedTypesCodec.decode_long(initial_frame.buf, _CREATION_TIME_DECODE_OFFSET)
        expiration_time = FixSizedTypesCodec.decode_long(initial_frame.buf, _EXPIRATION_TIME_DECODE_OFFSET)
        hits = FixSizedTypesCodec.decode_long(initial_frame.buf, _HITS_DECODE_OFFSET)
        last_access_time = FixSizedTypesCodec.decode_long(initial_frame.buf, _LAST_ACCESS_TIME_DECODE_OFFSET)
        last_stored_time = FixSizedTypesCodec.decode_long(initial_frame.buf, _LAST_STORED_TIME_DECODE_OFFSET)
        last_update_time = FixSizedTypesCodec.decode_long(initial_frame.buf, _LAST_UPDATE_TIME_DECODE_OFFSET)
        version = FixSizedTypesCodec.decode_long(initial_frame.buf, _VERSION_DECODE_OFFSET)
        ttl = FixSizedTypesCodec.decode_long(initial_frame.buf, _TTL_DECODE_OFFSET)
        max_idle = FixSizedTypesCodec.decode_long(initial_frame.buf, _MAX_IDLE_DECODE_OFFSET)
        key = DataCodec.decode(msg)
        value = DataCodec.decode(msg)
        CodecUtil.fast_forward_to_end_frame(msg)
        return SimpleEntryView(key, value, cost, creation_time, expiration_time, hits, last_access_time, last_stored_time, last_update_time, version, ttl, max_idle)


text:
#import "NSObject.h"

// Not exported
@interface CXCommon : NSObject
{
}

+ (void)initialize;

@end


text:
require File.dirname(__FILE__) + '/../../../spec_helper'

with_feature :encoding do
  describe "Encoding::Converter.asciicompat_encoding" do
    it "accepts an encoding name as a String argument" do
      lambda { Encoding::Converter.asciicompat_encoding('UTF-8') }.
        should_not raise_error
    end

    it "coerces non-String/Encoding objects with #to_str" do
      str = mock('string')
      str.should_receive(:to_str).twice.and_return('string')
      Encoding::Converter.asciicompat_encoding(str)
    end

    it "accepts an Encoding object as an argument" do
      Encoding::Converter.
        asciicompat_encoding(Encoding.find("ISO-2022-JP")).
        should == Encoding::Converter.asciicompat_encoding("ISO-2022-JP")
    end

    it "returns a corresponding ASCII compatible encoding for ASCII-incompatible encodings" do
      Encoding::Converter.asciicompat_encoding('UTF-16BE').should == Encoding::UTF_8
      Encoding::Converter.asciicompat_encoding("ISO-2022-JP").should == Encoding.find("stateless-ISO-2022-JP")
    end

    it "returns nil when the given encoding is ASCII compatible" do
      Encoding::Converter.asciicompat_encoding('ASCII').should be_nil
      Encoding::Converter.asciicompat_encoding('UTF-8').should be_nil
    end

    it "handles encoding names who resolve to nil encodings" do
      internal = Encoding.default_internal
      Encoding.default_internal = nil
      Encoding::Converter.asciicompat_encoding('internal').should be_nil
      Encoding.default_internal = internal
    end

    it "returns nil if called with an encoding it returned previously" do
      internal = Encoding.default_internal
      Encoding.name_list.each do |name|
        asciicompat = Encoding::Converter.asciicompat_encoding(name)
        next if asciicompat.nil?
        Encoding::Converter.asciicompat_encoding(asciicompat).should be_nil
      end
    end
  end
end


text:
import { Component, ViewChild, ViewEncapsulation } from '@angular/core';

import { jqxValidatorComponent } from '../../../jqwidgets-ts/angular_jqxvalidator';
import { jqxPasswordInputComponent } from '../../../jqwidgets-ts/angular_jqxpasswordinput';
import { jqxDateTimeInputComponent } from '../../../jqwidgets-ts/angular_jqxdatetimeinput';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    encapsulation: ViewEncapsulation.None
})

export class AppComponent {
    @ViewChild('myValidator') myValidator: jqxValidatorComponent;
    @ViewChild('dateTimeInput') dateTimeInput: jqxDateTimeInputComponent;
    @ViewChild('passwordInput') passwordInput: jqxPasswordInputComponent;
    @ViewChild('confirmPasswordInput') confirmPasswordInput: jqxPasswordInputComponent;

    initialDate: Date = new Date(2014, 4, 1);

    sendButton(): void {
        this.myValidator.validate(document.getElementById('form'));
    }

    rules =
    [
        { input: '.userInput', message: 'Username is required!', action: 'keyup, blur', rule: 'required' },
        { input: '.userInput', message: 'Your username must be between 3 and 12 characters!', action: 'keyup, blur', rule: 'length=3,12' },
        { input: '.realNameInput', message: 'Real Name is required!', action: 'keyup, blur', rule: 'required' },
        { input: '.realNameInput', message: 'Your real name must contain only letters!', action: 'keyup', rule: 'notNumber' },
        { input: '.realNameInput', message: 'Your real name must be between 3 and 12 characters!', action: 'keyup', rule: 'length=2,12' },
        {
            input: '.birthInput', message: 'Your birth date must be between 1/1/1900 and 1/1/2014.', action: 'valueChanged',
            rule: (input: any, commit: any): any => {
                let date = this.dateTimeInput.value();
                let result = date.getFullYear() >= 1900 && date.getFullYear() <= 2014;
                return result;
            }
        },
        { input: '.passwordInput', message: 'Password is required!', action: 'keyup, blur', rule: 'required' },
        { input: '.passwordInput', message: 'Your password must be between 4 and 12 characters!', action: 'keyup, blur', rule: 'length=4,12' },
        { input: '.passwordConfirmInput', message: 'Password is required!', action: 'keyup, blur', rule: 'required' },
        {
            input: '.passwordConfirmInput', message: 'Passwords doesn\'t match!', action: 'keyup, focus',
            rule: (input: any, commit: any): boolean => {
                if (this.passwordInput.val() === this.confirmPasswordInput.val()) {
                    return true;
                }
                return false;
            }
        },
        { input: '.emailInput', message: 'E-mail is required!', action: 'keyup, blur', rule: 'required' },
        { input: '.emailInput', message: 'Invalid e-mail!', action: 'keyup', rule: 'email' },
        { input: '.ssnInput', message: 'Invalid SSN!', action: 'valuechanged, blur', rule: 'ssn' },
        { input: '.phoneInput', message: 'Invalid phone number!', action: 'valuechanged, blur', rule: 'phone' },
        { input: '.zipInput', message: 'Invalid zip code!', action: 'valuechanged, blur', rule: 'zipCode' },
        { input: '#acceptCheckBox', message: 'You have to accept the terms', action: 'change', rule: 'required', position: 'right:0,0' }
    ];
}


text:
'use strict';

import * as strings from 'vs/base/common/strings';
import { TPromise } from 'vs/base/common/winjs.base';
import { EditorInput, EditorModel, ITextEditorModel } from 'vs/workbench/common/editor';
import URI from 'vs/base/common/uri';
import { IReference, IDisposable, dispose } from 'vs/base/common/lifecycle';
import { telemetryURIDescriptor } from 'vs/platform/telemetry/common/telemetryUtils';
import { ITextModelService } from 'vs/editor/common/services/resolverService';
import { marked } from 'vs/base/common/marked/marked';
import { Schemas } from 'vs/base/common/network';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { ILifecycleService, ShutdownReason } from 'vs/platform/lifecycle/common/lifecycle';
import { IHashService } from 'vs/workbench/services/hash/common/hashService';

export class WalkThroughModel extends EditorModel {

	constructor(
		private mainRef: IReference<ITextEditorModel>,
		private snippetRefs: IReference<ITextEditorModel>[]
	) {
		super();
	}

	get main() {
		return this.mainRef.object;
	}

	get snippets() {
		return this.snippetRefs.map(snippet => snippet.object);
	}

	dispose() {
		this.snippetRefs.forEach(ref => ref.dispose());
		this.mainRef.dispose();
		super.dispose();
	}
}

export interface WalkThroughInputOptions {
	readonly typeId: string;
	readonly name: string;
	readonly description?: string;
	readonly resource: URI;
	readonly telemetryFrom: string;
	readonly onReady?: (container: HTMLElement) => void;
}

export class WalkThroughInput extends EditorInput {

	private disposables: IDisposable[] = [];

	private promise: TPromise<WalkThroughModel>;

	private resolveTime: number;
	private maxTopScroll = 0;
	private maxBottomScroll = 0;

	constructor(
		private options: WalkThroughInputOptions,
		@ITelemetryService private telemetryService: ITelemetryService,
		@ILifecycleService lifecycleService: ILifecycleService,
		@ITextModelService private textModelResolverService: ITextModelService,
		@IHashService private hashService: IHashService
	) {
		super();
		this.disposables.push(lifecycleService.onShutdown(e => this.disposeTelemetry(e)));
	}

	getResource(): URI {
		return this.options.resource;
	}

	getTypeId(): string {
		return this.options.typeId;
	}

	getName(): string {
		return this.options.name;
	}

	getDescription(): string {
		return this.options.description || '';
	}

	getTelemetryFrom(): string {
		return this.options.telemetryFrom;
	}

	getTelemetryDescriptor(): object {
		const descriptor = super.getTelemetryDescriptor();
		descriptor['target'] = this.getTelemetryFrom();
		descriptor['resource'] = telemetryURIDescriptor(this.options.resource, path => this.hashService.createSHA1(path));
		/* __GDPR__FRAGMENT__
			"EditorTelemetryDescriptor" : {
				"target" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
				"resource": { "${inline}": [ "${URIDescriptor}" ] }
			}
		*/
		return descriptor;
	}

	get onReady() {
		return this.options.onReady;
	}

	resolve(refresh?: boolean): TPromise<WalkThroughModel> {
		if (!this.promise) {
			this.resolveTelemetry();
			this.promise = this.textModelResolverService.createModelReference(this.options.resource)
				.then(ref => {
					if (strings.endsWith(this.getResource().path, '.html')) {
						return new WalkThroughModel(ref, []);
					}

					const snippets: TPromise<IReference<ITextEditorModel>>[] = [];
					let i = 0;
					const renderer = new marked.Renderer();
					renderer.code = (code, lang) => {
						const resource = this.options.resource.with({ scheme: Schemas.walkThroughSnippet, fragment: `${i++}.${lang}` });
						snippets.push(this.textModelResolverService.createModelReference(resource));
						return '';
					};

					const markdown = ref.object.textEditorModel.getLinesContent().join('\n');
					marked(markdown, { renderer });

					return TPromise.join(snippets)
						.then(refs => new WalkThroughModel(ref, refs));
				});
		}

		return this.promise;
	}

	matches(otherInput: any): boolean {
		if (super.matches(otherInput) === true) {
			return true;
		}

		if (otherInput instanceof WalkThroughInput) {
			let otherResourceEditorInput = <WalkThroughInput>otherInput;

			// Compare by properties
			return otherResourceEditorInput.options.resource.toString() === this.options.resource.toString();
		}

		return false;
	}

	dispose(): void {
		this.disposables = dispose(this.disposables);

		if (this.promise) {
			this.promise.then(model => model.dispose());
			this.promise = null;
		}

		this.disposeTelemetry();

		super.dispose();
	}

	public relativeScrollPosition(topScroll: number, bottomScroll: number) {
		this.maxTopScroll = Math.max(this.maxTopScroll, topScroll);
		this.maxBottomScroll = Math.max(this.maxBottomScroll, bottomScroll);
	}

	private resolveTelemetry() {
		if (!this.resolveTime) {
			this.resolveTime = Date.now();
			/* __GDPR__
				"resolvingInput" : {
					"target" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
				}
			*/
			this.telemetryService.publicLog('resolvingInput', {
				target: this.getTelemetryFrom(),
			});
		}
	}

	private disposeTelemetry(reason?: ShutdownReason) {
		if (this.resolveTime) {
			/* __GDPR__
				"disposingInput" : {
					"target" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
					"timeSpent": { "classification": "SystemMetaData", "purpose": "PerformanceAndHealth" },
					"reason": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
					"maxTopScroll": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
					"maxBottomScroll": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
				}
			*/
			this.telemetryService.publicLog('disposingInput', {
				target: this.getTelemetryFrom(),
				timeSpent: (Date.now() - this.resolveTime) / 60,
				reason: reason ? ShutdownReason[reason] : 'DISPOSE',
				maxTopScroll: this.maxTopScroll,
				maxBottomScroll: this.maxBottomScroll,
			});
			this.resolveTime = null;
		}
	}
}


text:
namespace AvansApp.Models.Enums
{
    public enum ScheduleType
    {
        Group,
        Teacher,
        Classroom
    }
}


text:
using System;

namespace Mjcheetham.VisualStudio.ProjectSystemMonitor
{
    internal class SolutionOpenedEventArgs : EventArgs
    {
        public bool NewSolution { get; }

        public SolutionOpenedEventArgs(bool newSolution)
        {
            NewSolution = newSolution;
        }
    }
}


text:
package io.github.dinolupo.javaeetest.business.order.entity;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

/**
 *
 * @author Dino Lupo <https://dinolupo.github.io>
 */
@Entity(name = "T_ORDER")
public class Order implements Serializable {

    @Id
    @GeneratedValue
    private Long id;

    private String trackingNumber;

    public Order(String trackingNumber) {
        this.trackingNumber = trackingNumber;
    }

    public Order() {
    }

    public String getTrackingNumber() {
        return trackingNumber;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

}


text:
using StyleCop;
using StyleCop.CSharp;

namespace Microsoft.OData.StyleCop
{
    [SourceAnalyzer(typeof(CsParser))]
    public class LineLengthRule : SourceAnalyzer
    {
        private const string LineLengthProperty = "LineLength";
        private const string RuleName = "LineMustNotBeTooLong";

        public override void AnalyzeDocument(CodeDocument document)
        {
            var csharpDocument = (CsDocument)document;
            if (csharpDocument.RootElement != null && !csharpDocument.RootElement.Generated)
            {
                if (IsRuleEnabled(csharpDocument, RuleName))
                {
                    CheckLineLength(csharpDocument);
                }
            }
        }

        private void CheckLineLength(CsDocument csharpDocument)
        {
            var lengthProperty = GetSetting(csharpDocument.Settings, LineLengthProperty) as IntProperty;
            if (lengthProperty == null)
            {
                return;
            }

            using (var reader = csharpDocument.SourceCode.Read())
            {
                string line;
                var lineNumber = 0;
                while ((line = reader.ReadLine()) != null)
                {
                    lineNumber++;
                    if (line.Length > lengthProperty.Value)
                    {
                        AddViolation(
                            csharpDocument.RootElement,
                            lineNumber,
                            RuleName,
                            lengthProperty.Value);
                    }
                }
            }
        }
    }
}


text:
package com.nexters.vobble.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import android.widget.Toast;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.analytics.tracking.android.Fields;
import com.google.analytics.tracking.android.MapBuilder;
import com.nexters.vobble.R;
import com.nexters.vobble.core.App;

public class BaseFragmentActivity extends FragmentActivity {
    private int mLoadingStackCount = 0;
    private View mLoadingView;
    private AlertDialog mAlertDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mLoadingView = LayoutInflater.from(this).inflate(R.layout.view_loading, null);
		mLoadingView.setVisibility(View.INVISIBLE);
	}

    @Override
	protected void onStart() {
		super.onStart();
		EasyTracker.getInstance(this).activityStart(this);
		App.getGaTracker().set(Fields.SCREEN_NAME, (String) getTitle());
		App.getGaTracker().send(MapBuilder.createAppView().build());
	}

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        ((ViewGroup) getWindow().getDecorView().findViewById(android.R.id.content)).addView(mLoadingView);
    }

    @Override
	protected void onStop() {
		super.onStop();
		EasyTracker.getInstance(this).activityStop(this);
	}

	public synchronized void showLoading() {
		mLoadingStackCount++;
		mLoadingView.setVisibility(View.VISIBLE);
	}

	public synchronized void hideLoading() {
		mLoadingStackCount--;
		if(mLoadingStackCount <= 0) {
			mLoadingStackCount = 0;
			mLoadingView.setVisibility(View.INVISIBLE);
		}
	}

    public void showShortToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

	public void showAlert(int resId) {
		showAlert(getString(resId));
	}

	public void showAlert(String message) {
        if (mAlertDialog != null && mAlertDialog.isShowing())
            return;

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(message);
        builder.setPositiveButton(R.string.ok, null);

        mAlertDialog = builder.create();
        mAlertDialog.show();

        TextView messageText = (TextView) mAlertDialog.findViewById(android.R.id.message);
        messageText.setGravity(Gravity.CENTER);
	}
}


text:
@interface NSObject (LCFastSingleton) <LC_CMD_IMP>

+ (instancetype) LC_SINGLETON_CUSTOM_METHOD_NAME;
+ (instancetype) LCSingleton;

@end


text:
import logging
import errno

from functools import partial

from . import _seq
from ._seq import *

logger = logging.getLogger("alsa.seq")

class Client(_seq.SeqClient):
    __slots__ = ()
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.event_classes.update(EVENT_CLASS_MAP)

    def asyncio_subscribe_events(self, loop, callback):
        loop.add_reader(self.fileno(), partial(self._incoming, callback))

    def _incoming(self, callback):
        logger.debug("   input pending")
        while True:
            try:
                event = self.event_input()
            except OSError as err:
                if err.errno == errno.ENOSPC:
                    logger.warning("Input queue overflow, events lost")
                elif err.errno == errno.EAGAIN:
                    logger.debug("   no more events pending")
                    break
                elif err.errno == errno.EINTR:
                    logger.debug("   EINTR")
                    continue
                else:
                    raise
            logger.debug("   got event: %r:", event)
            callback(event)

class SeqEvent(_seq.SeqEvent):
    __slots__ = ()
    def _repr(self, details):
        if (self.flags & TIME_STAMP_MASK) == TIME_STAMP_TICK:
            ts_prefix = "@#"
            ts_val = self.tick
            ts_val_s = str(ts_val)
        else:
            ts_prefix = "@"
            ts_val = self.tv_sec + 0.000000001 * self.tv_nsec
            ts_val_s = "{:.3}".format(ts_val)

        if (self.flags & TIME_MODE_MASK) == TIME_MODE_REL and ts_val > 0:
            ts_prefix += "+"

        return ("<{0.__class__.__name__} {1} {2}"
                " from {0.source_client}:{0.source_port}"
                " to {0.dest_client}:{0.dest_port}"
                ">".format(self, details, ts_prefix + ts_val_s))

    def __repr__(self):
        return self._repr(self.type)

class NoteEvent(_seq.SeqNoteEvent):
    __slots__ = ()
    def __repr__(self):
        return SeqEvent._repr(self,
            "#{0.note} velocity={0.velocity} duration={0.duration}"
            .format(self))

class NoteOnEvent(_seq.SeqNoteOnEvent):
    __slots__ = ()
    def __repr__(self):
        return SeqEvent._repr(self,
            "#{0.note} velocity={0.velocity}"
            .format(self))

class NoteOffEvent(_seq.SeqNoteOffEvent):
    __slots__ = ()
    def __repr__(self):
        return SeqEvent._repr(self,
            "#{0.note} velocity={0.velocity}"
            .format(self))

class ControlChangeEvent(_seq.SeqControlChangeEvent):
    __slots__ = ()
    def __repr__(self):
        return SeqEvent._repr(self,
            "#{0.param} value={0.value}"
            .format(self))

class ControlChange14bitEvent(_seq.SeqControlChange14bitEvent):
    __slots__ = ()
    def __repr__(self):
        return SeqEvent._repr(self,
            "#{0.param} value={0.value}"
            .format(self))

class ProgramChangeEvent(_seq.SeqProgramChangeEvent):
    __slots__ = ()
    def __repr__(self):
        return SeqEvent._repr(self,
            "#{0.value}"
            .format(self))

class _AddressEvent(_seq.SeqAddressEvent):
    __slots__ = ()
    def __repr__(self):
        return SeqEvent._repr(self, "{0.client}:{0.port}" .format(self))

class ClientStartEvent(_AddressEvent):
    __slots__ = ()
    def __init__(self, client=0, port=0, **kwargs):
        super().__init__(EVENT_CLIENT_START, client, port, **kwargs)

class ClientExitEvent(_AddressEvent):
    __slots__ = ()
    def __init__(self, client=0, port=0, **kwargs):
        super().__init__(EVENT_CLIENT_EXIT, client, port, **kwargs)

class ClientChangeEvent(_AddressEvent):
    __slots__ = ()
    def __init__(self, client=0, port=0, **kwargs):
        super().__init__(EVENT_CLIENT_CHANGE, client, port, **kwargs)

class PortStartEvent(_AddressEvent):
    __slots__ = ()
    def __init__(self, client=0, port=0, **kwargs):
        super().__init__(EVENT_PORT_START, client, port, **kwargs)

class PortExitEvent(_AddressEvent):
    __slots__ = ()
    def __init__(self, client=0, port=0, **kwargs):
        super().__init__(EVENT_PORT_EXIT, client, port, **kwargs)

class PortChangeEvent(_AddressEvent):
    __slots__ = ()
    def __init__(self, client=0, port=0, **kwargs):
        super().__init__(EVENT_PORT_CHANGE, client, port, **kwargs)

EVENT_CLASS_MAP = {
        None: SeqEvent, # default
        EVENT_NOTE: NoteEvent,
        EVENT_NOTEON: NoteOnEvent,
        EVENT_NOTEOFF: NoteOffEvent,
        EVENT_CONTROLLER: ControlChangeEvent,
        EVENT_CONTROL14: ControlChange14bitEvent,
        EVENT_PGMCHANGE: ProgramChangeEvent,
        EVENT_CLIENT_START: ClientStartEvent,
        EVENT_CLIENT_EXIT: ClientExitEvent,
        EVENT_CLIENT_CHANGE: ClientChangeEvent,
        EVENT_PORT_START: PortStartEvent,
        EVENT_PORT_EXIT: PortExitEvent,
        EVENT_PORT_CHANGE: PortChangeEvent,
        }


text:
layout: event
category: event
title: Tableau
rsvp: http://www.meetup.com/Maptime-Boulder/events/227858588/
---

Come learn about Tableau! a data visualization tool that can be a great asset for work in GIS.

Website to download the software ( yes you have to download it to use it ): [http://www.tableau.com/](http://www.tableau.com/) (The latest version is 9.2)

Here is a link to download the sample data we'll be using tonight! [Sample Data](/boulder/assets/tableau/County_Health_Rankings.csv)


text:
package humanhex

import (
	"bytes"
	"fmt"
)

// eww, this is bad and i feel bad
func readable(b byte) bool {
	switch {
	case b < 0x20:
		return false
	case b > 0x7f:
		return false
	default:
		return true
	}
}

// less eww
func lookahead(b []byte, p int) int {
	var i = p
	for ; i < len(b); i++ {
		if !readable(b[i]) {
			break
		}
	}
	return i - p
}

// String will return a more human-consumable representation of the bytes in b.
// m specifies the number of contiguous human-friendly bytes required before we
// will display it directly. 2 is a good default. 0 is undefined and panics.
// Note that human-consumable and human-friendly here are limited in scope to
// North American, English-speaking humans. Maybe Go's rune type can do some
// more heavy lifting on our behalf down the road?
func String(b []byte, m int) string {
	if m == 0 {
		panic("invalid value 0 for m")
	}
	out := &bytes.Buffer{}
	for i := 0; i < len(b); {
		if contig := lookahead(b, i); contig >= m {
			out.WriteString(string(b[i : i+contig]))
			i += contig
		} else {
			out.WriteString(fmt.Sprintf("\\x%02x", b[i]))
			i++
		}
	}
	return out.String()
}


text:
import Ember from 'ember';

export default Ember.Route.extend({

  beforeModel() {
    return this.transitionTo('main');
  }

});


text:
package net.sf.json.sample;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;

/**
 * @author Andres Almiray <aalmiray@users.sourceforge.net>
 */
public class UnstandardBean {
   private boolean bool = true;
   private int id;
   private int integer = 42;
   private String string = "json";

   public UnstandardBean( int id ) {
      this.id = id;
   }

   public boolean equals( Object obj ) {
      if( obj == this ){
         return true;
      }
      if( obj == null ){
         return false;
      }
      if( !UnstandardBean.class.isAssignableFrom( obj.getClass() ) ){
         return false;
      }
      return EqualsBuilder.reflectionEquals( this, obj );
   }

   public int getId() {
      return id;
   }

   public int getInteger() {
      return integer;
   }

   public String getString() {
      return string;
   }

   public int hashCode() {
      return HashCodeBuilder.reflectionHashCode( this );
   }

   public boolean isBool() {
      return bool;
   }

   public void setBool( boolean bool ) {
      this.bool = bool;
   }

   public void setInteger( int integer ) {
      this.integer = integer;
   }

   public void setString( String string ) {
      this.string = string;
   }

   public String toString() {
      return ToStringBuilder.reflectionToString( this, ToStringStyle.MULTI_LINE_STYLE );
   }
}


text:
require 'spec_helper'

describe "admin_payment_methods/index" do
  before(:each) do
    assign(:admin_payment_methods, [
      stub_model(Admin::AccountsPaymentMethod,
        :payment_type => "Payment Type"
      ),
      stub_model(Admin::AccountsPaymentMethod,
        :payment_type => "Payment Type"
      )
    ])
  end

  it "renders a list of admin_payment_methods" do
    render
    # Run the generator again with the --webrat flag if you want to use webrat matchers
    assert_select "tr>td", :text => "Payment Type".to_s, :count => 2
  end
end


text:
from bar4py.shortfuncs import opjoin
from bar4py import Dictionary, CameraParameters, createWebPlayer

# Configs.
CONFIG = {
    'app_name': 'Hello BAR4Py',
    'marker_path': './static/marker',
    'marker_type': '*.jpg',
    'camera_file': './static/camera/camera_640x480.json',
    'dictionary_file': './static/dictionary/dictionary.json',
    'animate_file': './static/animate/animate.js',
    'port': 8000,
    'debug': False,
}

# Build WebAPP arguments.
dictionary = Dictionary()
dictionary.buildByDirectory(
    filetype=CONFIG['marker_type'],
    path=CONFIG['marker_path']
) # yapf: disable
cameraParameters = CameraParameters()
cameraParameters.readFromJsonFile(CONFIG['camera_file'])

# Create WebAR player.
player = createWebPlayer(__name__, dictionary, cameraParameters,
                         player_rect=(0, 35, 640, 480),
                         app_args={'APP_TITLE': CONFIG['app_name']}) # yapf: disable

# Set dictionary options
import json
with open(CONFIG['dictionary_file'], 'r') as f:
    dictionary_opts = json.load(f)
player.setDictionaryOptions(dictionary_opts)

# Set models animate.
with open(CONFIG['animate_file'], 'r') as f:
    animate_js = f.read()
player.setAnimate(animate_js)

if __name__ == '__main__': player.run(port=CONFIG['port'], debug=CONFIG['debug']) # yapf: disable


text:
import './browser-polyfill';
export * from './index';


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
in Engler & Prantl, Nat. Pflanzenfam. (Leipzig), Teil. <b>I</b> 1*: 188 (1906)

#### Original name
Lichen laetevirens Lightf.

### Remarks
null


text:
/*
 * This header describes the external API interface for the Roomba
 */

#include <stdint.h>

typedef enum
{
	SLEEP,
    PASSIVE,
    SAFE,
    FULL
} roomba_mode_t;

typedef enum
{
    DEFAULT,
    SPOT,
    MAX
} clean_mode_t;

/*
 * Initalizes the ROI interface.
 * This causes the current mode to be changed to safe.
 */
void initialize_roomba();

void test_move();

/*
 * Sets the Roomba into Passive, Safe, or Full mode.
 * The current mode restricts the operations available to the Roomba.
 * See ROI spec for details.
 * Possible mode transitions:
 *		PASSIVE -> SAFE
 *		FULL	-> SAFE
 *		SAFE	-> FULL
 *		SAFE	-> SLEEP
 *		FULL	-> SLEEP
 *		SLEEP	-> PASSIVE
 */
void set_mode(roomba_mode_t mode);

/*
 * Starts the Roomba's clean cycle. The clean cycle can be one of Default
 * Spot, or Max.
 * See ROI spec for details on the different cleaning modes.
 * This causes the current mode to be changed to passive.
 */
void start_clean(clean_mode_t mode);

/*
 * Starts the Roomba's return to docking station algorithm.
 * Only works if a cleaning mode currently active.
 * This changes the current mode to passive.
 */
void send_dock();

/*
 * Set the speed for the left and right drive wheels.
 * The speed should be in mm/s and ranges from -500 - 500
 * Requires current mode to be Safe or Full
 */
void set_wheel_speeds(int16_t left_wheel, int16_t right_wheel);

/*
 * Play the song specified by the number between 1-4
 * Works in any mode
 */
void play_song(uint8_t song_number);


text:
import fs = require('fs')
import { Request, Response, NextFunction } from 'express'
import { UserModel } from '../models/user'

const utils = require('../lib/utils')
const security = require('../lib/insecurity')
const logger = require('../lib/logger')
const fileType = require('file-type')

module.exports = function fileUpload () {
  return async (req: Request, res: Response, next: NextFunction) => {
    const file = req.file
    const buffer = file?.buffer
    const uploadedFileType = await fileType.fromBuffer(buffer)

    if (uploadedFileType === undefined) {
      res.status(500)
      next(new Error('Illegal file type'))
    } else {
      if (uploadedFileType !== null && utils.startsWith(uploadedFileType.mime, 'image')) {
        const loggedInUser = security.authenticatedUsers.get(req.cookies.token)
        if (loggedInUser) {
          fs.open(`frontend/dist/frontend/assets/public/images/uploads/${loggedInUser.data.id}.${uploadedFileType.ext}`, 'w', function (err, fd) {
            if (err != null) logger.warn('Error opening file: ' + err.message)
            // @ts-expect-error
            fs.write(fd, buffer, 0, buffer.length, null, function (err) {
              if (err != null) logger.warn('Error writing file: ' + err.message)
              fs.close(fd, function () { })
            })
          })
          UserModel.findByPk(loggedInUser.data.id).then(async (user: UserModel | null) => {
            if (user) {
              return await user.update({ profileImage: `assets/public/images/uploads/${loggedInUser.data.id}.${uploadedFileType.ext}` })
            }
          }).catch((error: Error) => {
            next(error)
          })
          res.location(process.env.BASE_PATH + '/profile')
          res.redirect(process.env.BASE_PATH + '/profile')
        } else {
          next(new Error('Blocked illegal activity by ' + req.connection.remoteAddress))
        }
      } else {
        res.status(415)
        next(new Error(`Profile image upload does not accept this file type${uploadedFileType ? (': ' + uploadedFileType.mime) : '.'}`))
      }
    }
  }
}


text:
import express = require('express');

function handleNotFound(req, res) {
  if (req.accepts('html')) {
    res
      .status(404)
      .render('404');
  } else {
    res.send(404, { error: 'not found' });
  }
}

export function setup(app: express.Application): void {
  app.all('*', handleNotFound);
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<channel name="xfce4-keyboard-shortcuts" version="1.0">
  <property name="commands" type="empty">
    <property name="default" type="empty">
      <property name="<Alt>F1" type="empty"/>
      <property name="<Alt>F2" type="empty">
        <property name="startup-notify" type="empty"/>
      </property>
      <property name="<Alt>F3" type="empty">
        <property name="startup-notify" type="empty"/>
      </property>
      <property name="<Primary><Alt>Delete" type="empty"/>
      <property name="XF86Display" type="empty"/>
      <property name="<Super>p" type="empty"/>
      <property name="<Primary>Escape" type="empty"/>
      <property name="XF86WWW" type="empty"/>
      <property name="XF86Mail" type="empty"/>
    </property>
    <property name="custom" type="empty">
      <property name="<Alt>F1" type="string" value="xfce4-popup-applicationsmenu"/>
      <property name="<Alt>F3" type="string" value="xfce4-appfinder"/>
      <property name="<Alt>F2" type="string" value="xfce4-appfinder --collapsed"/>
      <property name="<Primary><Alt>Delete" type="string" value="xflock4"/>
      <property name="XF86Mail" type="string" value="exo-open --launch MailReader"/>
      <property name="XF86Display" type="string" value="xfce4-display-settings --minimal"/>
      <property name="XF86WWW" type="string" value="exo-open --launch WebBrowser"/>
      <property name="<Super>p" type="string" value="xfce4-display-settings --minimal"/>
      <property name="<Primary>Escape" type="string" value="xfdesktop --menu"/>
      <property name="override" type="bool" value="true"/>
    </property>
  </property>
  <property name="xfwm4" type="empty">
    <property name="default" type="empty">
      <property name="<Alt>Insert" type="empty"/>
      <property name="Escape" type="empty"/>
      <property name="Left" type="empty"/>
      <property name="Right" type="empty"/>
      <property name="Up" type="empty"/>
      <property name="Down" type="empty"/>
      <property name="<Alt>Tab" type="empty"/>
      <property name="<Alt><Shift>Tab" type="empty"/>
      <property name="<Alt>Delete" type="empty"/>
      <property name="<Control><Alt>Down" type="empty"/>
      <property name="<Control><Alt>Left" type="empty"/>
      <property name="<Shift><Alt>Page_Down" type="empty"/>
      <property name="<Alt>F4" type="empty"/>
      <property name="<Alt>F6" type="empty"/>
      <property name="<Alt>F7" type="empty"/>
      <property name="<Alt>F8" type="empty"/>
      <property name="<Alt>F9" type="empty"/>
      <property name="<Alt>F10" type="empty"/>
      <property name="<Alt>F11" type="empty"/>
      <property name="<Alt>F12" type="empty"/>
      <property name="<Control><Shift><Alt>Left" type="empty"/>
      <property name="<Alt><Control>End" type="empty"/>
      <property name="<Alt><Control>Home" type="empty"/>
      <property name="<Control><Shift><Alt>Right" type="empty"/>
      <property name="<Control><Shift><Alt>Up" type="empty"/>
      <property name="<Alt><Control>KP_1" type="empty"/>
      <property name="<Alt><Control>KP_2" type="empty"/>
      <property name="<Alt><Control>KP_3" type="empty"/>
      <property name="<Alt><Control>KP_4" type="empty"/>
      <property name="<Alt><Control>KP_5" type="empty"/>
      <property name="<Alt><Control>KP_6" type="empty"/>
      <property name="<Alt><Control>KP_7" type="empty"/>
      <property name="<Alt><Control>KP_8" type="empty"/>
      <property name="<Alt><Control>KP_9" type="empty"/>
      <property name="<Alt>space" type="empty"/>
      <property name="<Shift><Alt>Page_Up" type="empty"/>
      <property name="<Control><Alt>Right" type="empty"/>
      <property name="<Control><Alt>d" type="empty"/>
      <property name="<Control><Alt>Up" type="empty"/>
      <property name="<Super>Tab" type="empty"/>
      <property name="<Control>F1" type="empty"/>
      <property name="<Control>F2" type="empty"/>
      <property name="<Control>F3" type="empty"/>
      <property name="<Control>F4" type="empty"/>
      <property name="<Control>F5" type="empty"/>
      <property name="<Control>F6" type="empty"/>
      <property name="<Control>F7" type="empty"/>
      <property name="<Control>F8" type="empty"/>
      <property name="<Control>F9" type="empty"/>
      <property name="<Control>F10" type="empty"/>
      <property name="<Control>F11" type="empty"/>
      <property name="<Control>F12" type="empty"/>
    </property>
    <property name="custom" type="empty">
      <property name="<Control>F3" type="string" value="workspace_3_key"/>
      <property name="<Control>F4" type="string" value="workspace_4_key"/>
      <property name="<Control>F5" type="string" value="workspace_5_key"/>
      <property name="<Control>F6" type="string" value="workspace_6_key"/>
      <property name="<Control>F7" type="string" value="workspace_7_key"/>
      <property name="<Control>F8" type="string" value="workspace_8_key"/>
      <property name="<Control>F9" type="string" value="workspace_9_key"/>
      <property name="<Alt>Tab" type="string" value="cycle_windows_key"/>
      <property name="<Control><Alt>Right" type="string" value="right_workspace_key"/>
      <property name="Left" type="string" value="left_key"/>
      <property name="<Control><Alt>d" type="string" value="show_desktop_key"/>
      <property name="<Control><Shift><Alt>Left" type="string" value="move_window_left_key"/>
      <property name="<Control><Shift><Alt>Right" type="string" value="move_window_right_key"/>
      <property name="Up" type="string" value="up_key"/>
      <property name="<Alt>F4" type="string" value="close_window_key"/>
      <property name="<Alt>F6" type="string" value="stick_window_key"/>
      <property name="<Control><Alt>Down" type="string" value="down_workspace_key"/>
      <property name="<Alt>F7" type="string" value="move_window_key"/>
      <property name="<Alt>F9" type="string" value="hide_window_key"/>
      <property name="<Alt>F11" type="string" value="fullscreen_key"/>
      <property name="<Alt>F8" type="string" value="resize_window_key"/>
      <property name="<Super>Tab" type="string" value="switch_window_key"/>
      <property name="Escape" type="string" value="cancel_key"/>
      <property name="<Alt><Control>KP_1" type="string" value="move_window_workspace_1_key"/>
      <property name="<Alt><Control>KP_2" type="string" value="move_window_workspace_2_key"/>
      <property name="<Alt><Control>KP_3" type="string" value="move_window_workspace_3_key"/>
      <property name="<Alt><Control>KP_4" type="string" value="move_window_workspace_4_key"/>
      <property name="<Alt><Control>KP_5" type="string" value="move_window_workspace_5_key"/>
      <property name="<Alt><Control>KP_6" type="string" value="move_window_workspace_6_key"/>
      <property name="Down" type="string" value="down_key"/>
      <property name="<Control><Shift><Alt>Up" type="string" value="move_window_up_key"/>
      <property name="<Shift><Alt>Page_Down" type="string" value="lower_window_key"/>
      <property name="<Alt>F12" type="string" value="above_key"/>
      <property name="<Alt><Control>KP_8" type="string" value="move_window_workspace_8_key"/>
      <property name="<Alt><Control>KP_9" type="string" value="move_window_workspace_9_key"/>
      <property name="Right" type="string" value="right_key"/>
      <property name="<Alt>F10" type="string" value="maximize_window_key"/>
      <property name="<Control><Alt>Up" type="string" value="up_workspace_key"/>
      <property name="<Control>F10" type="string" value="workspace_10_key"/>
      <property name="<Alt><Control>KP_7" type="string" value="move_window_workspace_7_key"/>
      <property name="<Alt><Control>End" type="string" value="move_window_next_workspace_key"/>
      <property name="<Alt>Delete" type="string" value="del_workspace_key"/>
      <property name="<Control><Alt>Left" type="string" value="left_workspace_key"/>
      <property name="<Control>F12" type="string" value="workspace_12_key"/>
      <property name="<Alt>space" type="string" value="popup_menu_key"/>
      <property name="<Alt><Shift>Tab" type="string" value="cycle_reverse_windows_key"/>
      <property name="<Shift><Alt>Page_Up" type="string" value="raise_window_key"/>
      <property name="<Alt>Insert" type="string" value="add_workspace_key"/>
      <property name="<Alt><Control>Home" type="string" value="move_window_prev_workspace_key"/>
      <property name="<Control>F2" type="string" value="workspace_2_key"/>
      <property name="<Control>F1" type="string" value="workspace_1_key"/>
      <property name="<Control>F11" type="string" value="workspace_11_key"/>
      <property name="override" type="bool" value="true"/>
    </property>
  </property>
  <property name="providers" type="array">
    <value type="string" value="commands"/>
    <value type="string" value="xfwm4"/>
  </property>
</channel>


text:
<!DOCTYPE html>

        <meta charset="UTF-8">


text:
local skynet = require "skynet"

local GPIO = require "GPIO"

require("ul_time")

local wifiCar

local Wheel = {}
Wheel.__index = Wheel

function Wheel.new( pin )
    local obj = {}
    obj.pin = pin
    obj.state = 2
    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(pin[1],GPIO.OUT)
    GPIO.setup(pin[2],GPIO.OUT)
    return setmetatable(obj,Wheel)
end

function Wheel:change( state )
    if self.state == state then
        return
    end

    if state == 0 then
        GPIO.output(self.pin[1],GPIO.LOW)
        GPIO.output(self.pin[2],GPIO.LOW)
    elseif state == 1 then
        GPIO.output(self.pin[2],GPIO.HIGH)
        GPIO.output(self.pin[1],GPIO.LOW)
    elseif state == -1 then
        GPIO.output(self.pin[1],GPIO.HIGH)
        GPIO.output(self.pin[2],GPIO.LOW)
    end
end

function Wheel:forward()
    self:change(1)
end

function Wheel:stop(  )
    self:change(0)
end

function Wheel:back(  )
    self:change(-1)
end

local Car = {}

Car.__index = Car
Car.CT_User = 0
Car.CT_Auto = 1

function Car.new( is4Wheel )
    local obj = {}
    obj.is4Wheel = is4Wheel

    obj.fl = Wheel.new({13,15,"fl"})
    obj.fr = Wheel.new({16,18,"fr"})

    if obj.is4Wheel == true then
        obj.bl = Wheel.new({19,21,"bl"})
        obj.br = Wheel.new({22,24,"br"})
    end

    obj.speed = 10
    obj.xspeed = 0   --right    +   left  -
    obj.yspeed = 0   --forward  +   back  -

    GPIO.setup {
        channel = 21,
        direction = GPIO.OUT,
        initial = GPIO.LOW,
    }
    obj.pwmA = GPIO.newPWM(21,100)

    obj.pwmA:start(100)

    GPIO.setup {
        channel = 19,
        direction = GPIO.OUT,
        initial = GPIO.LOW,
    }
    obj.pwmB = GPIO.newPWM(19,100)

    obj.pwmB:start(100)

    obj.pwmA:ChangeDutyCycle(100)
    obj.pwmB:ChangeDutyCycle(100)
    --obj.pwmA:stop()

    obj.waveTrigger = 11
    obj.waveEcho = 12

    GPIO.setup(obj.waveTrigger ,GPIO.OUT)
    GPIO.setup(obj.waveEcho ,GPIO.IN)

    return setmetatable(obj,Car)
end

function Car:getDistance()
    return self.distance
end

function Car:loopDistance( )
    GPIO.output(self.waveTrigger, GPIO.LOW)
    os.delay_s(0.5)
    GPIO.output(self.waveTrigger, GPIO.HIGH)
    os.delay_us(10)
    GPIO.output(self.waveTrigger, GPIO.LOW)
    local start
    local elapsed
    local stop

    _,start = os.timeofday()
    print(GPIO.input(self.waveEcho))
    while GPIO.input(self.waveEcho)==GPIO.LOW do
        _,start = os.timeofday()
    end
    while GPIO.input(self.waveEcho)==GPIO.HIGH do
         _,stop = os.timeofday()
    end
    if stop < start then
        print(start,stop,"A")
        stop = stop + 1000000
    end
    elapsed = stop-start

    self.distance = elapsed * 0.000001 * 34300 / 2
    if self.distance < 0 then
        print(start,stop,"B")
    end

    print(string.format("Distance : %.1f" ,self.distance))

end

function Car:left( )
    self.fl:back()
    self.fr:forward()

    if self.is4Wheel ==true then
        self.bl:back()
        self.br:forward()
    end
end

function Car:right( )
    self.fl:forward()
    self.fr:back()

    if self.is4Wheel ==true then
        self.bl:forward()
        self.br:back()
    end

end

function Car:forward( )
    self.fl:forward()
    self.fr:forward()
    if self.is4Wheel ==true then
        self.bl:forward()
        self.br:forward()
    end

end

function Car:back( )
    self.fl:back()
    self.fr:back()

    if self.is4Wheel ==true then
        self.bl:back()
        self.br:back()
    end

end

function Car:stop( )
    self.fl:stop()
    self.fr:stop()

    if self.is4Wheel ==true then
        self.bl:stop()
        self.br:stop()
    end
end

function accept.dir(side,dir )
    if side ==2 then
        if dir == 0 then                    --DEFAULT = 0,
            wifiCar.xspeed = 0
        elseif dir == 1 then                --D_UP = 1,
            wifiCar.xspeed =   wifiCar.speed
        elseif dir == 2 then                --D_DOWN = 2,
            wifiCar.xspeed = - wifiCar.speed
        elseif dir == 5 then                --D_LEFT_UP = 5,
            wifiCar.xspeed =   wifiCar.speed
        elseif dir == 6 then                --D_LEFT_DOWN = 6,
            wifiCar.xspeed = - wifiCar.speed
        elseif dir == 7 then                --D_RIGHT_UP = 7,
            wifiCar.xspeed =   wifiCar.speed
        elseif dir == 8 then                --D_RIGHT_DOWN =8
            wifiCar.xspeed = - wifiCar.speed
        else
            wifiCar.xspeed = 0
        end
    else
        if dir == 0 then                    --DEFAULT = 0,
            wifiCar.yspeed = 0
        elseif dir == 3 then                --D_LEFT = 3,
            wifiCar.yspeed = - wifiCar.speed
        elseif dir == 4 then                --D_RIGHT = 4,
            wifiCar.yspeed =   wifiCar.speed
        elseif dir == 5 then                --D_LEFT_UP = 5,
            wifiCar.yspeed = - wifiCar.speed
        elseif dir == 6 then                --D_LEFT_DOWN = 6,
            wifiCar.yspeed = - wifiCar.speed
        elseif dir == 7 then                --D_RIGHT_UP = 7,
            wifiCar.yspeed =   wifiCar.speed
        elseif dir == 8 then                --D_RIGHT_DOWN =8
            wifiCar.yspeed =   wifiCar.speed
        else
            wifiCar.yspeed = 0
        end
    end

end

local function loop( ... )
    local time = skynet.time()
    -- print("dis A")
    -- wifiCar:loopDistance()
    -- print("dis B")
    if wifiCar.xspeed > 0 then
        wifiCar:right()
    elseif wifiCar.xspeed < 0 then
        wifiCar:left()
    else
        if wifiCar.yspeed > 0 then
            wifiCar:forward()
        elseif wifiCar.yspeed < 0 then
            wifiCar:back()
        end
    end

    if wifiCar.xspeed ==0 and wifiCar.yspeed == 0 then
        wifiCar:stop()
    end

    local delayTime = (skynet.time()-time)*100
    if delayTime > 10 then
        print("error loop time > 1s  maybe io busy")
        delayTime = 9
    end
    skynet.timeout(10-delayTime,loop)
end

function exit( )
    GPIO.cleanup()
end

function init( )
    GPIO.cleanup()
    GPIO.setwarnings(true)
    GPIO.setmode(GPIO.BOARD)

    wifiCar = Car.new(false)
    wifiCar:stop()

    loop()
end


text:
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *     Copyright 2012 Couchbase, Inc
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

#include "config.h"

#include <algorithm>
#include <vector>

#include "bgfetcher.h"
#include "ep_engine.h"
#include "executorthread.h"
#include "kv_bucket.h"
#include "kvshard.h"

const double BgFetcher::sleepInterval = MIN_SLEEP_TIME;

BgFetcher::BgFetcher(KVBucket& s, KVShard& k)
    : BgFetcher(&s, &k, s.getEPEngine().getEpStats()) {
}

void BgFetcher::start() {
    bool inverse = false;
    pendingFetch.compare_exchange_strong(inverse, true);
    ExecutorPool* iom = ExecutorPool::get();
    ExTask task = new MultiBGFetcherTask(&(store->getEPEngine()), this, false);
    this->setTaskId(task->getId());
    iom->schedule(task, READER_TASK_IDX);
}

void BgFetcher::stop() {
    bool inverse = true;
    pendingFetch.compare_exchange_strong(inverse, false);
    ExecutorPool::get()->cancel(taskId);
}

void BgFetcher::notifyBGEvent(void) {
    ++stats.numRemainingBgItems;
    bool inverse = false;
    if (pendingFetch.compare_exchange_strong(inverse, true)) {
        ExecutorPool::get()->wake(taskId);
    }
}

size_t BgFetcher::doFetch(VBucket::id_type vbId,
                          vb_bgfetch_queue_t& itemsToFetch) {
    hrtime_t startTime(gethrtime());
    LOG(EXTENSION_LOG_DEBUG, "BgFetcher is fetching data, vBucket = %d "
        "numDocs = %" PRIu64 ", startTime = %" PRIu64,
        vbId, uint64_t(itemsToFetch.size()), startTime/1000000);

    shard->getROUnderlying()->getMulti(vbId, itemsToFetch);

    std::vector<bgfetched_item_t> fetchedItems;
    for (const auto& fetch : itemsToFetch) {
        auto& key = fetch.first;
        const vb_bgfetch_item_ctx_t& bg_item_ctx = fetch.second;

        for (const auto& itm : bg_item_ctx.bgfetched_list) {
            // We don't want to transfer ownership of itm here as we clean it
            // up at the end of this method in clearItems()
            fetchedItems.push_back(std::make_pair(key, itm.get()));
        }
    }

    if (fetchedItems.size() > 0) {
        store->completeBGFetchMulti(vbId, fetchedItems, startTime);
        stats.getMultiHisto.add((gethrtime() - startTime) / 1000,
                                fetchedItems.size());
    }

    clearItems(vbId, itemsToFetch);
    return fetchedItems.size();
}

void BgFetcher::clearItems(VBucket::id_type vbId,
                           vb_bgfetch_queue_t& itemsToFetch) {
    for (auto& fetch : itemsToFetch) {
        // every fetched item belonging to the same key shares
        // a single data buffer, just delete it from the first fetched item
        fetch.second.bgfetched_list.front()->delValue();
    }
}

bool BgFetcher::run(GlobalTask *task) {
    size_t num_fetched_items = 0;
    bool inverse = true;
    pendingFetch.compare_exchange_strong(inverse, false);

    std::vector<uint16_t> bg_vbs(pendingVbs.size());
    {
        LockHolder lh(queueMutex);
        bg_vbs.assign(pendingVbs.begin(), pendingVbs.end());
        pendingVbs.clear();
    }

    for (const uint16_t vbId : bg_vbs) {
        RCPtr<VBucket> vb = shard->getBucket(vbId);
        if (vb) {
            // Requeue the bg fetch task if vbucket DB file is not created yet.
            if (vb->isBucketCreation()) {
                {
                    LockHolder lh(queueMutex);
                    pendingVbs.insert(vbId);
                }
                bool inverse = false;
                pendingFetch.compare_exchange_strong(inverse, true);
                continue;
            }

            auto items = vb->getBGFetchItems();
            if (items.size() > 0) {
                num_fetched_items += doFetch(vbId, items);
            }
        }
    }

    stats.numRemainingBgItems.fetch_sub(num_fetched_items);

    if (!pendingFetch.load()) {
        // wait a bit until next fetch request arrives
        double sleep = std::max(store->getBGFetchDelay(), sleepInterval);
        task->snooze(sleep);

        if (pendingFetch.load()) {
            // check again a new fetch request could have arrived
            // right before calling above snooze()
            task->snooze(0);
        }
    }
    return true;
}

bool BgFetcher::pendingJob() const {
    for (const auto vbid : shard->getVBuckets()) {
        RCPtr<VBucket> vb = shard->getBucket(vbid);
        if (vb && vb->hasPendingBGFetchItems()) {
            return true;
        }
    }
    return false;
}


text:
/* This file contains dummy references to libgcc.a functions to force the
 * dynamic linker to copy their definition into the final libc.so binary.
 *
 * They are required to ensure backwards binary compatibility with
 * Android 1.5, 1.6 and even 3.0  system images. Some applications built
 * using the NDK require them to be here.
 *
 * Now, for a more elaborate description of the issue:
 *
 * libgcc.a is a compiler-specific library containing various helper
 * functions used to implement certain operations that are not necessarily
 * supported by the target CPU. For example, integer division doesn't have a
 * corresponding CPU instruction on ARMv5, and is instead implemented in the
 * compiler-generated machine code as a call to an __idiv helper function.
 *
 * Normally, one has to place libgcc.a in the link command used to generate
 * target binaries (shared libraries and executables) after all objects and
 * static libraries, but before dependent shared libraries, i.e. something
 * like:
 *         gcc <options> -o libfoo.so  foo.a libgcc.a -lc -lm
 *
 * This ensures that any helper function needed by the code in foo.a is copied
 * into the final libfoo.so. Unfortunately, the Android build system has been
 * using this instead:
 *
 *         gcc <options> -o libfoo.so foo.a -lc -lm libgcc.a
 *
 * The problem with this is that if one helper function needed by foo.a has
 * already been copied into libc.so or libm.so, then nothing will be copied
 * into libfoo.so. Instead, a symbol import definition will be added to it
 * so libfoo.so can directly call the one in libc.so at runtime.
 *
 * When changing toolchains for 2.0, the set of helper functions copied to
 * libc.so changed, which resulted in some native shared libraries generated
 * with the NDK to fail to load properly.
 *
 * The NDK has been fixed after 1.6_r1 to use the correct link command, so
 * any native shared library generated with it should now be safe from that
 * problem. On the other hand, existing shared libraries distributed with
 * applications that were generated with a previous version of the NDK
 * still need all 1.5/1.6 helper functions in libc.so and libn.so
 *
 * After 3.2, the toolchain was updated again, adding __aeabi_f2uiz to the
 * list of requirements. Technically, this is due to mis-linked NDK libraries
 * but it is easier to add a single function here than asking several app
 * developers to fix their build.
 *
 * Final note: some of the functions below should really be in libm.so to
 *             completely reflect the state of 1.5/1.6 system images. However,
 *             since libm.so depends on libc.so, it's easier to put all of
 *             these in libc.so instead, since the dynamic linker will always
 *             search in libc.so before libm.so for dependencies.
 */

#define   COMPAT_FUNCTIONS_LIST \
    XX(__adddf3)             \
    XX(__addsf3)             \
    XX(__aeabi_cdcmpeq)      \
    XX(__aeabi_cdcmple)      \
    XX(__aeabi_cdrcmple)     \
    XX(__aeabi_d2f)          \
    XX(__aeabi_d2iz)         \
    XX(__aeabi_dadd)         \
    XX(__aeabi_dcmpeq)       \
    XX(__aeabi_dcmpge)       \
    XX(__aeabi_dcmpgt)       \
    XX(__aeabi_dcmple)       \
    XX(__aeabi_dcmplt)       \
    XX(__aeabi_dcmpun)       \
    XX(__aeabi_ddiv)         \
    XX(__aeabi_dmul)         \
    XX(__aeabi_drsub)        \
    XX(__aeabi_dsub)         \
    XX(__aeabi_f2d)          \
    XX(__aeabi_f2iz)         \
    XX(__aeabi_f2uiz)        \
    XX(__aeabi_fadd)         \
    XX(__aeabi_fcmpun)       \
    XX(__aeabi_fdiv)         \
    XX(__aeabi_fmul)         \
    XX(__aeabi_frsub)        \
    XX(__aeabi_fsub)         \
    XX(__aeabi_i2d)          \
    XX(__aeabi_i2f)          \
    XX(__aeabi_l2d)          \
    XX(__aeabi_l2f)          \
    XX(__aeabi_lmul)         \
    XX(__aeabi_ui2d)         \
    XX(__aeabi_ui2f)         \
    XX(__aeabi_ul2d)         \
    XX(__aeabi_ul2f)         \
    XX(__cmpdf2)             \
    XX(__divdf3)             \
    XX(__divsf3)             \
    XX(__eqdf2)             \
    XX(__extendsfdf2)        \
    XX(__fixdfsi)            \
    XX(__fixsfsi)            \
    XX(__floatdidf)          \
    XX(__floatdisf)          \
    XX(__floatsidf)          \
    XX(__floatsisf)          \
    XX(__floatundidf)        \
    XX(__floatundisf)        \
    XX(__floatunsidf)        \
    XX(__floatunsisf)        \
    XX(__gedf2)              \
    XX(__gtdf2)              \
    XX(__ledf2)              \
    XX(__ltdf2)              \
    XX(__muldf3)             \
    XX(__muldi3)             \
    XX(__mulsf3)             \
    XX(__nedf2)              \
    XX(__subdf3)             \
    XX(__subsf3)             \
    XX(__truncdfsf2)         \
    XX(__unorddf2)           \
    XX(__unordsf2)           \

#define  XX(f)    extern void f(void);
COMPAT_FUNCTIONS_LIST
#undef XX

void  __bionic_libgcc_compat_hooks(void)
{
#define XX(f)    f();
COMPAT_FUNCTIONS_LIST
#undef XX
}


text:
package flag

import (
	"reflect"
	"testing"
)

func TestStringColonSeparatedMultimapStringString(t *testing.T) {
	var nilMap map[string][]string
	cases := []struct {
		desc   string
		m      *ColonSeparatedMultimapStringString
		expect string
	}{
		{"nil", NewColonSeparatedMultimapStringString(&nilMap), ""},
		{"empty", NewColonSeparatedMultimapStringString(&map[string][]string{}), ""},
		{"empty key", NewColonSeparatedMultimapStringString(
			&map[string][]string{
				"": {"foo"},
			}),
			":foo"},
		{"one key", NewColonSeparatedMultimapStringString(
			&map[string][]string{
				"one": {"foo"},
			}),
			"one:foo"},
		{"two keys", NewColonSeparatedMultimapStringString(
			&map[string][]string{
				"one": {"foo"},
				"two": {"bar"},
			}),
			"one:foo,two:bar"},
		{"two keys, multiple items in one key", NewColonSeparatedMultimapStringString(
			&map[string][]string{
				"one": {"foo", "baz"},
				"two": {"bar"},
			}),
			"one:foo,one:baz,two:bar"},
		{"three keys, multiple items in one key", NewColonSeparatedMultimapStringString(
			&map[string][]string{
				"a": {"hello"},
				"b": {"again", "beautiful"},
				"c": {"world"},
			}),
			"a:hello,b:again,b:beautiful,c:world"},
	}
	for _, c := range cases {
		t.Run(c.desc, func(t *testing.T) {
			str := c.m.String()
			if c.expect != str {
				t.Fatalf("expect %q but got %q", c.expect, str)
			}
		})
	}
}

func TestSetColonSeparatedMultimapStringString(t *testing.T) {
	var nilMap map[string][]string
	cases := []struct {
		desc   string
		vals   []string
		start  *ColonSeparatedMultimapStringString
		expect *ColonSeparatedMultimapStringString
		err    string
	}{
		// we initialize the map with a default key that should be cleared by Set
		{"clears defaults", []string{""},
			NewColonSeparatedMultimapStringString(&map[string][]string{"default": {}}),
			&ColonSeparatedMultimapStringString{
				initialized: true,
				Multimap:    &map[string][]string{}}, ""},
		// make sure we still allocate for "initialized" multimaps where Multimap was initially set to a nil map
		{"allocates map if currently nil", []string{""},
			&ColonSeparatedMultimapStringString{initialized: true, Multimap: &nilMap},
			&ColonSeparatedMultimapStringString{
				initialized: true,
				Multimap:    &map[string][]string{},
			}, ""},
		// for most cases, we just reuse nilMap, which should be allocated by Set, and is reset before each test case
		{"empty", []string{""},
			NewColonSeparatedMultimapStringString(&nilMap),
			&ColonSeparatedMultimapStringString{
				initialized: true,
				Multimap:    &map[string][]string{}}, ""},
		{"empty key", []string{":foo"},
			NewColonSeparatedMultimapStringString(&nilMap),
			&ColonSeparatedMultimapStringString{
				initialized: true,
				Multimap: &map[string][]string{
					"": {"foo"},
				}}, ""},
		{"one key", []string{"one:foo"},
			NewColonSeparatedMultimapStringString(&nilMap),
			&ColonSeparatedMultimapStringString{
				initialized: true,
				Multimap: &map[string][]string{
					"one": {"foo"},
				}}, ""},
		{"two keys", []string{"one:foo,two:bar"},
			NewColonSeparatedMultimapStringString(&nilMap),
			&ColonSeparatedMultimapStringString{
				initialized: true,
				Multimap: &map[string][]string{
					"one": {"foo"},
					"two": {"bar"},
				}}, ""},
		{"two keys with space", []string{"one:foo, two:bar"},
			NewColonSeparatedMultimapStringString(&nilMap),
			&ColonSeparatedMultimapStringString{
				initialized: true,
				Multimap: &map[string][]string{
					"one": {"foo"},
					"two": {"bar"},
				}}, ""},
		{"two keys, multiple items in one key", []string{"one: foo, two:bar, one:baz"},
			NewColonSeparatedMultimapStringString(&nilMap),
			&ColonSeparatedMultimapStringString{
				initialized: true,
				Multimap: &map[string][]string{
					"one": {"foo", "baz"},
					"two": {"bar"},
				}}, ""},
		{"three keys, multiple items in one key", []string{"a:hello,b:again,c:world,b:beautiful"},
			NewColonSeparatedMultimapStringString(&nilMap),
			&ColonSeparatedMultimapStringString{
				initialized: true,
				Multimap: &map[string][]string{
					"a": {"hello"},
					"b": {"again", "beautiful"},
					"c": {"world"},
				}}, ""},
		{"three keys, multiple items in one key, multiple Set invocations", []string{"a:hello,b:again", "c:world", "b:beautiful"},
			NewColonSeparatedMultimapStringString(&nilMap),
			&ColonSeparatedMultimapStringString{
				initialized: true,
				Multimap: &map[string][]string{
					"a": {"hello"},
					"b": {"again", "beautiful"},
					"c": {"world"},
				}}, ""},
		{"missing value", []string{"a"},
			NewColonSeparatedMultimapStringString(&nilMap),
			nil,
			"malformed pair, expect string:string"},
		{"no target", []string{"a:foo"},
			NewColonSeparatedMultimapStringString(nil),
			nil,
			"no target (nil pointer to map[string][]string)"},
	}

	for _, c := range cases {
		nilMap = nil
		t.Run(c.desc, func(t *testing.T) {
			var err error
			for _, val := range c.vals {
				err = c.start.Set(val)
				if err != nil {
					break
				}
			}
			if c.err != "" {
				if err == nil || err.Error() != c.err {
					t.Fatalf("expect error %s but got %v", c.err, err)
				}
				return
			} else if err != nil {
				t.Fatalf("unexpected error: %v", err)
			}
			if !reflect.DeepEqual(c.expect, c.start) {
				t.Fatalf("expect %#v but got %#v", c.expect, c.start)
			}
		})
	}
}

func TestRoundTripColonSeparatedMultimapStringString(t *testing.T) {
	cases := []struct {
		desc   string
		vals   []string
		expect string
	}{
		{"empty", []string{""}, ""},
		{"empty key", []string{":foo"}, ":foo"},
		{"one key", []string{"one:foo"}, "one:foo"},
		{"two keys", []string{"one:foo,two:bar"}, "one:foo,two:bar"},
		{"two keys, multiple items in one key", []string{"one:foo, two:bar, one:baz"}, "one:foo,one:baz,two:bar"},
		{"three keys, multiple items in one key", []string{"a:hello,b:again,c:world,b:beautiful"}, "a:hello,b:again,b:beautiful,c:world"},
		{"three keys, multiple items in one key, multiple Set invocations", []string{"a:hello,b:again", "c:world", "b:beautiful"}, "a:hello,b:again,b:beautiful,c:world"},
	}

	for _, c := range cases {
		t.Run(c.desc, func(t *testing.T) {
			m := NewColonSeparatedMultimapStringString(&map[string][]string{})
			for _, val := range c.vals {
				if err := m.Set(val); err != nil {
					t.Fatalf("unexpected error: %v", err)
				}
			}
			str := m.String()
			if c.expect != str {
				t.Fatalf("expect %q but got %q", c.expect, str)
			}
		})
	}
}

func TestEmptyColonSeparatedMultimapStringString(t *testing.T) {
	var nilMap map[string][]string
	cases := []struct {
		desc   string
		val    *ColonSeparatedMultimapStringString
		expect bool
	}{
		{"nil", NewColonSeparatedMultimapStringString(&nilMap), true},
		{"empty", NewColonSeparatedMultimapStringString(&map[string][]string{}), true},
		{"populated", NewColonSeparatedMultimapStringString(&map[string][]string{"foo": {}}), false},
	}
	for _, c := range cases {
		t.Run(c.desc, func(t *testing.T) {
			result := c.val.Empty()
			if result != c.expect {
				t.Fatalf("expect %t but got %t", c.expect, result)
			}
		})
	}
}


text:
'use strict';

(function(factory) {
  if (typeof module === 'object' && module.exports) {
    // CommonJS
    factory(module.exports, {
      chai: require('chai')
    });
  } else if (typeof self === 'object') {
    // Window or WorkerGlobalScope
    if (typeof self.chai === 'undefined') {
        throw new Error('Dependency not found.');
      }
    factory(self, self);
  }
}(function(exports, required) {
  var assert = required.chai.assert;

  var TaskTest = exports.TaskTest = function() {
    this.candidateId = 42;
  };
  TaskTest.NAME =
    'Type ㄅㄟˊㄅㄟˊㄅㄟˊㄅㄟˊ,ㄊ, with MAX_SOUNDS_LENGTH=4, ' +
    'overflows one phrase from the composed typo result.';
  TaskTest.prototype = {
    config: {
      MAX_SOUNDS_LENGTH: 4
    },
    tasks: [
      {
        fn: 'handleKey',
        args: ['ㄅㄟˊㄅㄟˊㄅㄟˊㄅㄟˊ'],
        wait: true,
        checkReturnedValue: function(returnedValue) {
          assert(returnedValue, 'Expected handled.');
        },
        expectCallbacks: ['compositionupdate', 'candidateschange'],
        checkCallbackValues: function(values) {
          assert.strictEqual(values.compositionupdate, 'ㄅㄟˊㄅㄟˊㄅㄟˊㄅㄟˊ');
          assert.deepEqual(values.candidateschange,
            [['ㄅㄟˊㄅㄟˊㄅㄟˊㄅㄟˊ', this.candidateId++],
             ['ㄅㄟˊ', this.candidateId++]]);
        }
      },
      {
        fn: 'handleKey',
        args: ['ㄊ'],
        wait: true,
        checkReturnedValue: function(returnedValue) {
          assert(returnedValue, 'Expected handled.');
        },
        expectCallbacks:
          ['compositionupdate', 'candidateschange', 'compositionend'],
        checkCallbackValues: function(values) {
          assert.strictEqual(values.compositionend, 'ㄅㄟˊ');
          assert.strictEqual(values.compositionupdate, 'ㄅㄟˊㄅㄟˊㄅㄟˊㄊ');
          assert.deepEqual(values.candidateschange,
            [['ㄅㄟˊㄅㄟˊㄅㄟˊ台', this.candidateId++],
             ['ㄅㄟˊ', this.candidateId++]]);
        }
      }
    ]
  };
}));