text:
import unittest
import datetime

from infi.clickhouse_orm import *

import logging
logging.getLogger("requests").setLevel(logging.WARNING)

class _EnginesHelperTestCase(unittest.TestCase):

    def setUp(self):
        self.database = Database('test-db', log_statements=True)

    def tearDown(self):
        self.database.drop_database()

class EnginesTestCase(_EnginesHelperTestCase):
    def _create_and_insert(self, model_class, **kwargs):
        self.database.create_table(model_class)
        self.database.insert([
            model_class(date='2017-01-01', event_id=23423, event_group=13, event_count=7, event_version=1, **kwargs)
        ])

    def test_merge_tree(self):
        class TestModel(SampleModel):
            engine = MergeTree('date', ('date', 'event_id', 'event_group'))
        self._create_and_insert(TestModel)

    def test_merge_tree_with_sampling(self):
        class TestModel(SampleModel):
            engine = MergeTree('date', ('date', 'event_id', 'event_group', 'intHash32(event_id)'), sampling_expr='intHash32(event_id)')
        self._create_and_insert(TestModel)

    def test_merge_tree_with_sampling__funcs(self):
        class TestModel(SampleModel):
            engine = MergeTree('date', ('date', 'event_id', 'event_group', F.intHash32(SampleModel.event_id)), sampling_expr=F.intHash32(SampleModel.event_id))
        self._create_and_insert(TestModel)

    def test_merge_tree_with_granularity(self):
        class TestModel(SampleModel):
            engine = MergeTree('date', ('date', 'event_id', 'event_group'), index_granularity=4096)
        self._create_and_insert(TestModel)

    def test_replicated_merge_tree(self):
        engine = MergeTree('date', ('date', 'event_id', 'event_group'), replica_table_path='/clickhouse/tables/{layer}-{shard}/hits', replica_name='{replica}')
        # In ClickHouse 1.1.54310 custom partitioning key was introduced and new syntax is used
        if self.database.server_version >= (1, 1, 54310):
            expected = "ReplicatedMergeTree('/clickhouse/tables/{layer}-{shard}/hits', '{replica}') PARTITION BY (toYYYYMM(`date`)) ORDER BY (date, event_id, event_group) SETTINGS index_granularity=8192"
        else:
            expected = "ReplicatedMergeTree('/clickhouse/tables/{layer}-{shard}/hits', '{replica}', date, (date, event_id, event_group), 8192)"
        self.assertEqual(engine.create_table_sql(self.database), expected)

    def test_replicated_merge_tree_incomplete(self):
        with self.assertRaises(AssertionError):
            MergeTree('date', ('date', 'event_id', 'event_group'), replica_table_path='/clickhouse/tables/{layer}-{shard}/hits')
        with self.assertRaises(AssertionError):
            MergeTree('date', ('date', 'event_id', 'event_group'), replica_name='{replica}')

    def test_collapsing_merge_tree(self):
        class TestModel(SampleModel):
            engine = CollapsingMergeTree('date', ('date', 'event_id', 'event_group'), 'event_version')
        self._create_and_insert(TestModel)

    def test_summing_merge_tree(self):
        class TestModel(SampleModel):
            engine = SummingMergeTree('date', ('date', 'event_group'), ('event_count',))
        self._create_and_insert(TestModel)

    def test_replacing_merge_tree(self):
        class TestModel(SampleModel):
            engine = ReplacingMergeTree('date', ('date', 'event_id', 'event_group'), 'event_uversion')
        self._create_and_insert(TestModel)

    def test_tiny_log(self):
        class TestModel(SampleModel):
            engine = TinyLog()
        self._create_and_insert(TestModel)

    def test_log(self):
        class TestModel(SampleModel):
            engine = Log()
        self._create_and_insert(TestModel)

    def test_memory(self):
        class TestModel(SampleModel):
            engine = Memory()
        self._create_and_insert(TestModel)

    def test_merge(self):
        class TestModel1(SampleModel):
            engine = TinyLog()

        class TestModel2(SampleModel):
            engine = TinyLog()

        class TestMergeModel(MergeModel, SampleModel):
            engine = Merge('^testmodel')

        self.database.create_table(TestModel1)
        self.database.create_table(TestModel2)
        self.database.create_table(TestMergeModel)

        # Insert operations are restricted for this model type
        with self.assertRaises(DatabaseException):
            self.database.insert([
                TestMergeModel(date='2017-01-01', event_id=23423, event_group=13, event_count=7, event_version=1)
            ])

        # Testing select
        self.database.insert([
            TestModel1(date='2017-01-01', event_id=1, event_group=1, event_count=1, event_version=1)
        ])
        self.database.insert([
            TestModel2(date='2017-01-02', event_id=2, event_group=2, event_count=2, event_version=2)
        ])
        # event_uversion is materialized field. So * won't select it and it will be zero
        res = self.database.select('SELECT *, _table, event_uversion FROM $table ORDER BY event_id', model_class=TestMergeModel)
        res = list(res)
        self.assertEqual(2, len(res))
        self.assertDictEqual({
            '_table': 'testmodel1',
            'date': datetime.date(2017, 1, 1),
            'event_id': 1,
            'event_group': 1,
            'event_count': 1,
            'event_version': 1,
            'event_uversion': 1
        }, res[0].to_dict(include_readonly=True))
        self.assertDictEqual({
            '_table': 'testmodel2',
            'date': datetime.date(2017, 1, 2),
            'event_id': 2,
            'event_group': 2,
            'event_count': 2,
            'event_version': 2,
            'event_uversion': 2
        }, res[1].to_dict(include_readonly=True))

    def test_custom_partitioning(self):
        class TestModel(SampleModel):
            engine = MergeTree(
                order_by=('date', 'event_id', 'event_group'),
                partition_key=('toYYYYMM(date)', 'event_group')
            )

        class TestCollapseModel(SampleModel):
            sign = Int8Field()

            engine = CollapsingMergeTree(
                sign_col='sign',
                order_by=('date', 'event_id', 'event_group'),
                partition_key=('toYYYYMM(date)', 'event_group')
            )

        self._create_and_insert(TestModel)
        self._create_and_insert(TestCollapseModel, sign=1)

        # Result order may be different, lets sort manually
        parts = sorted(list(SystemPart.get(self.database)), key=lambda x: x.table)

        self.assertEqual(2, len(parts))
        self.assertEqual('testcollapsemodel', parts[0].table)
        self.assertEqual('(201701, 13)'.replace(' ', ''), parts[0].partition.replace(' ', ''))
        self.assertEqual('testmodel', parts[1].table)
        self.assertEqual('(201701, 13)'.replace(' ', ''), parts[1].partition.replace(' ', ''))

    def test_custom_primary_key(self):
        if self.database.server_version < (18, 1):
            raise unittest.SkipTest('ClickHouse version too old')

        class TestModel(SampleModel):
            engine = MergeTree(
                order_by=('date', 'event_id', 'event_group'),
                partition_key=('toYYYYMM(date)',),
                primary_key=('date', 'event_id')
            )

        class TestCollapseModel(SampleModel):
            sign = Int8Field()

            engine = CollapsingMergeTree(
                sign_col='sign',
                order_by=('date', 'event_id', 'event_group'),
                partition_key=('toYYYYMM(date)',),
                primary_key=('date', 'event_id')
            )

        self._create_and_insert(TestModel)
        self._create_and_insert(TestCollapseModel, sign=1)

        self.assertEqual(2, len(list(SystemPart.get(self.database))))

class SampleModel(Model):

    date            = DateField()
    event_id        = UInt32Field()
    event_group     = UInt32Field()
    event_count     = UInt16Field()
    event_version   = Int8Field()
    event_uversion  = UInt8Field(materialized='abs(event_version)')

class DistributedTestCase(_EnginesHelperTestCase):
    def test_without_table_name(self):
        engine = Distributed('my_cluster')

        with self.assertRaises(ValueError) as cm:
            engine.create_table_sql(self.database)

        exc = cm.exception
        self.assertEqual(str(exc), 'Cannot create Distributed engine: specify an underlying table')

    def test_with_table_name(self):
        engine = Distributed('my_cluster', 'foo')
        sql = engine.create_table_sql(self.database)
        self.assertEqual(sql, 'Distributed(`my_cluster`, `test-db`, `foo`)')

    class TestModel(SampleModel):
        engine = TinyLog()

    def _create_distributed(self, shard_name, underlying=TestModel):
        class TestDistributedModel(DistributedModel, underlying):
            engine = Distributed(shard_name, underlying)

        self.database.create_table(underlying)
        self.database.create_table(TestDistributedModel)
        return TestDistributedModel

    def test_bad_cluster_name(self):
        with self.assertRaises(ServerError) as cm:
            d_model = self._create_distributed('cluster_name')
            self.database.count(d_model)

        exc = cm.exception
        self.assertEqual(exc.code, 170)
        self.assertTrue(exc.message.startswith("Requested cluster 'cluster_name' not found"))

    def test_verbose_engine_two_superclasses(self):
        class TestModel2(SampleModel):
            engine = Log()

        class TestDistributedModel(DistributedModel, self.TestModel, TestModel2):
            engine = Distributed('test_shard_localhost', self.TestModel)

        self.database.create_table(self.TestModel)
        self.database.create_table(TestDistributedModel)
        self.assertEqual(self.database.count(TestDistributedModel), 0)

    def test_minimal_engine(self):
        class TestDistributedModel(DistributedModel, self.TestModel):
            engine = Distributed('test_shard_localhost')

        self.database.create_table(self.TestModel)
        self.database.create_table(TestDistributedModel)

        self.assertEqual(self.database.count(TestDistributedModel), 0)

    def test_minimal_engine_two_superclasses(self):
        class TestModel2(SampleModel):
            engine = Log()

        class TestDistributedModel(DistributedModel, self.TestModel, TestModel2):
            engine = Distributed('test_shard_localhost')

        self.database.create_table(self.TestModel)
        with self.assertRaises(TypeError) as cm:
            self.database.create_table(TestDistributedModel)

        exc = cm.exception
        self.assertEqual(str(exc), 'When defining Distributed engine without the table_name ensure '
                                   'that your model has exactly one non-distributed superclass')

    def test_minimal_engine_no_superclasses(self):
        class TestDistributedModel(DistributedModel):
            engine = Distributed('test_shard_localhost')

        self.database.create_table(self.TestModel)
        with self.assertRaises(TypeError) as cm:
            self.database.create_table(TestDistributedModel)

        exc = cm.exception
        self.assertEqual(str(exc), 'When defining Distributed engine without the table_name ensure '
                                   'that your model has a parent model')

    def _test_insert_select(self, local_to_distributed, test_model=TestModel, include_readonly=True):
        d_model = self._create_distributed('test_shard_localhost', underlying=test_model)

        if local_to_distributed:
            to_insert, to_select = test_model, d_model
        else:
            to_insert, to_select = d_model, test_model

        self.database.insert([
            to_insert(date='2017-01-01', event_id=1, event_group=1, event_count=1, event_version=1),
            to_insert(date='2017-01-02', event_id=2, event_group=2, event_count=2, event_version=2)
        ])
        # event_uversion is materialized field. So * won't select it and it will be zero
        res = self.database.select('SELECT *, event_uversion FROM $table ORDER BY event_id',
                                   model_class=to_select)
        res = [row for row in res]
        self.assertEqual(2, len(res))
        self.assertDictEqual({
            'date': datetime.date(2017, 1, 1),
            'event_id': 1,
            'event_group': 1,
            'event_count': 1,
            'event_version': 1,
            'event_uversion': 1
        }, res[0].to_dict(include_readonly=include_readonly))
        self.assertDictEqual({
            'date': datetime.date(2017, 1, 2),
            'event_id': 2,
            'event_group': 2,
            'event_count': 2,
            'event_version': 2,
            'event_uversion': 2
        }, res[1].to_dict(include_readonly=include_readonly))

    @unittest.skip("Bad support of materialized fields in Distributed tables "
                   "https://groups.google.com/forum/#!topic/clickhouse/XEYRRwZrsSc")
    def test_insert_distributed_select_local(self):
        return self._test_insert_select(local_to_distributed=False)

    def test_insert_local_select_distributed(self):
        return self._test_insert_select(local_to_distributed=True)

    def _test_insert_distributed_select_local_no_materialized_fields(self):
        class TestModel2(self.TestModel):
            event_uversion = UInt8Field(readonly=True)

        return self._test_insert_select(local_to_distributed=False, test_model=TestModel2, include_readonly=False)


text:
#include "access/pxfutils.h"

#include "catalog/catalog.h"
#include "catalog/pg_tablespace.h"
#include "commands/dbcommands.h"
#include "miscadmin.h"
#include "utils/builtins.h"
#include <net/if.h>
#include <ifaddrs.h>
#include <sys/socket.h>
#include <netdb.h>

/* Wrapper for libchurl */
static void process_request(ClientContext* client_context, char *uri);

/* checks if two ip strings are equal */
bool are_ips_equal(char *ip1, char *ip2)
{
	if ((ip1 == NULL) || (ip2 == NULL))
		return false;
	return (strcmp(ip1, ip2) == 0);
}

/* override port str with given new port int */
void port_to_str(char **port, int new_port)
{
	char tmp[INT32_CHAR_SIZE];

	if (!port)
		elog(ERROR, "unexpected internal error in pxfutils.c");
	if (*port)
		pfree(*port);

	Assert((new_port <= 65535) && (new_port >= 1)); /* legal port range */
	pg_ltoa(new_port, tmp);
	*port = pstrdup(tmp);
}

/*
 * get_hdfs_location_from_filespace
 *
 * Get hdfs location from pg_filespace_entry
 * The returned path needs to be pfreed by the caller.
 */
void get_hdfs_location_from_filespace(char** path)
{
	Assert(NULL != path);
	Oid dtsoid = get_database_dts(MyDatabaseId);
	GetFilespacePathForTablespace(dtsoid, path);

	Assert(NULL != *path);
	Assert(strlen(*path) < FilespaceLocationBlankPaddedWithNullTermLen);

	elog(DEBUG2, "found hdfs location is %s", *path);
}

/*
 * call_rest
 *
 * Creates the REST message and sends it to the PXF service located on
 * <hadoop_uri->host>:<hadoop_uri->port>
 */
void
call_rest(GPHDUri *hadoop_uri,
		  ClientContext *client_context,
		  char *rest_msg)
{
	StringInfoData request;
	initStringInfo(&request);

	appendStringInfo(&request, rest_msg,
								hadoop_uri->host,
								hadoop_uri->port,
								PXF_SERVICE_PREFIX,
								PXF_VERSION);

	/* send the request. The response will exist in rest_buf.data */
	process_request(client_context, request.data);
	pfree(request.data);
}

/*
 * Wrapper for libchurl
 */
static void process_request(ClientContext* client_context, char *uri)
{
	size_t n = 0;
	char buffer[RAW_BUF_SIZE];

	print_http_headers(client_context->http_headers);
	client_context->handle = churl_init_download(uri, client_context->http_headers);
	if (client_context->handle == NULL)
		elog(ERROR, "Unsuccessful connection to uri: %s", uri);
	memset(buffer, 0, RAW_BUF_SIZE);
	resetStringInfo(&(client_context->the_rest_buf));

	/*
	 * This try-catch ensures that in case of an exception during the "communication with PXF and the accumulation of
	 * PXF data in client_context->the_rest_buf", we still get to terminate the libcurl connection nicely and avoid
	 * leaving the PXF server connection hung.
	 */
	PG_TRY();
	{
		/* read some bytes to make sure the connection is established */
		churl_read_check_connectivity(client_context->handle);
		while ((n = churl_read(client_context->handle, buffer, sizeof(buffer))) != 0)
		{
			appendBinaryStringInfo(&(client_context->the_rest_buf), buffer, n);
			memset(buffer, 0, RAW_BUF_SIZE);
		}
		churl_cleanup(client_context->handle, false);
	}
	PG_CATCH();
	{
		if (client_context->handle)
			churl_cleanup(client_context->handle, true);
		PG_RE_THROW();
	}
	PG_END_TRY();

}

/*
 * Finds ip address of any available loopback interface(ipv4/ipv6).
 * Returns ip for ipv4 addresses and [ip] for ipv6 addresses.
 *
 */
char* get_loopback_ip_addr()
{
	struct ifaddrs *ifaddr, *ifa;
	int family, s, n;
	char host[NI_MAXHOST];
	char *loopback_addr = NULL;

	if (getifaddrs(&ifaddr) == -1) {
		elog(ERROR, "Unable to obtain list of network interfaces.");
	}

	for (ifa = ifaddr, n = 0; ifa != NULL; ifa = ifa->ifa_next, n++) {
		if (ifa->ifa_addr == NULL)
			continue;

		family = ifa->ifa_addr->sa_family;

		if (family == AF_INET || family == AF_INET6) {
			s = getnameinfo(ifa->ifa_addr,
					(family == AF_INET) ?
							sizeof(struct sockaddr_in) :
							sizeof(struct sockaddr_in6), host, NI_MAXHOST,
					NULL, 0, NI_NUMERICHOST);
			if (s != 0) {
				elog(WARNING, "Unable to get name information for interface, getnameinfo() failed: %s\n", gai_strerror(s));
			}

			//get loopback interface
			if (ifa->ifa_flags & IFF_LOOPBACK) {
				if (family == AF_INET)
				{
					loopback_addr = palloc0(strlen(host) + 1);
					sprintf(loopback_addr, "%s", host);
				}
				else
				{
					loopback_addr = palloc0(strlen(host) + 3);
					sprintf(loopback_addr, "[%s]", host);
				}
				break;
			}
		}
	}

	freeifaddrs(ifaddr);

	if (loopback_addr == NULL || !loopback_addr[0])
		elog(ERROR, "Unable to get loop back address");

	return loopback_addr;
}

/*
 * Replaces first occurrence of replace in string with replacement.
 * Caller is responsible for releasing memory allocated for result.
 *
 */
char* replace_string(const char* string, const char* replace, const char* replacement)
{
	char* replaced = NULL;
	char* start = strstr(string, replace);
	if (start)
	{
		char* before_token = pnstrdup(string, start - string);
		char* after_token = pstrdup(string + (start - string) + strlen(replace));
		replaced = palloc0(strlen(before_token) + strlen(replacement) + strlen(after_token) + 1);
		sprintf(replaced, "%s%s%s", before_token, replacement, after_token);

		//release memory
		pfree(before_token);
		pfree(after_token);
	} else
	{
		replaced = palloc0(strlen(string) + 1);
		sprintf(replaced, "%s", string);
	}

	return replaced;

}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Kwejk\MemsBundle\Controller\Comment;

use Admingenerated\KwejkMemsBundle\BaseCommentController\NewController as BaseNewController;

/**
 * NewController
 */
class NewController extends BaseNewController
{
}


text:
package net.emaze.dysfunctional;

import java.util.Comparator;
import java.util.Iterator;
import java.util.function.BiFunction;
import java.util.function.BinaryOperator;
import java.util.function.Predicate;
import net.emaze.dysfunctional.contracts.dbc;
import net.emaze.dysfunctional.iterations.ArrayIterator;
import net.emaze.dysfunctional.order.ComparableComparator;
import net.emaze.dysfunctional.reductions.Any;
import net.emaze.dysfunctional.reductions.Count;
import net.emaze.dysfunctional.reductions.Every;
import net.emaze.dysfunctional.reductions.Reductor;

/**
 * reduce, any, every, count, maximum, minimum.
 *
 * @author rferranti
 */
public abstract class Reductions {

    /**
     * Reduces an iterator of elements using the passed function.
     *
     * @param <E> the element type parameter
     * @param <R> the result type parameter
     * @param iterator the iterator to be consumed
     * @param function the reduction function
     * @param init the initial value for reductions
     * @return the reduced value
     */
    public static <E, R> R reduce(Iterator<E> iterator, BiFunction<R, E, R> function, R init) {
        return new Reductor<>(function, init).apply(iterator);
    }

    /**
     * Reduces an iterator of elements using the passed function.
     *
     * @param <E> the element type parameter
     * @param <R> the result type parameter
     * @param iterable the iterable to be consumed
     * @param function the reduction function
     * @param init the initial value for reductions
     * @return the reduced value
     */
    public static <E, R> R reduce(Iterable<E> iterable, BiFunction<R, E, R> function, R init) {
        dbc.precondition(iterable != null, "cannot call reduce with a null iterable");
        return new Reductor<>(function, init).apply(iterable.iterator());
    }

    /**
     * Reduces an array of elements using the passed function.
     *
     * @param <E> the element type parameter
     * @param <R> the result type parameter
     * @param array the array to be consumed
     * @param function the reduction function
     * @param init the initial value for reductions
     * @return the reduced value
     */
    public static <E, R> R reduce(E[] array, BiFunction<R, E, R> function, R init) {
        return new Reductor<>(function, init).apply(new ArrayIterator<E>(array));
    }

    /**
     * Yields true if ANY predicate application on the given iterable yields
     * true (giving up on the first positive match).
     *
     * @param <E> the iterable element type parameter
     * @param iterable the iterable where elements are fetched from
     * @param predicate the predicate applied to every element until a match is
     * found
     * @return true if ANY predicate application yields true (gives up on the
     * first positive match)
     */
    public static <E> boolean any(Iterable<E> iterable, Predicate<E> predicate) {
        dbc.precondition(iterable != null, "cannot call any with a null iterable");
        return new Any<E>(predicate).test(iterable.iterator());
    }

    /**
     * Yields true if ANY predicate application on the given iterator yields
     * true (giving up on the first positive match).
     *
     * @param <E> the iterator element type parameter
     * @param iterator the iterator where elements are fetched from
     * @param predicate the predicate applied to every element until a match is
     * found
     * @return true if ANY predicate application yields true (gives up on the
     * first positive match)
     */
    public static <E> boolean any(Iterator<E> iterator, Predicate<E> predicate) {
        return new Any<E>(predicate).test(iterator);
    }

    /**
     * Yields true if ANY predicate application on the given array yields true
     * (giving up on the first positive match).
     *
     * @param <E> the array element type parameter
     * @param array the array where elements are fetched from
     * @param predicate the predicate applied to every element until a match is
     * found
     * @return true if ANY predicate application yields true (gives up on the
     * first positive match)
     */
    public static <E> boolean any(E[] array, Predicate<E> predicate) {
        return new Any<E>(predicate).test(new ArrayIterator<E>(array));
    }

    /**
     * Yields true if EVERY predicate application on the given iterable yields
     * true.
     *
     * @param <E> the iterable element type parameter
     * @param iterable the iterable where elements are fetched from
     * @param predicate the predicate applied to every element fetched from the
     * iterable
     * @return true if EVERY predicate application yields true
     */
    public static <E> boolean every(Iterable<E> iterable, Predicate<E> predicate) {
        dbc.precondition(iterable != null, "cannot call every with a null iterable");
        return new Every<E>(predicate).test(iterable.iterator());
    }

    /**
     * Yields true if EVERY predicate application on the given iterator yields
     * true.
     *
     * @param <E> the iterator element type parameter
     * @param iterator the iterator where elements are fetched from
     * @param predicate the predicate applied to every element fetched from the
     * iterator
     * @return true if EVERY predicate application yields true
     */
    public static <E> boolean every(Iterator<E> iterator, Predicate<E> predicate) {
        return new Every<E>(predicate).test(iterator);
    }

    /**
     * Yields true if EVERY predicate application on the given array yields
     * true.
     *
     * @param <E> the array element type parameter
     * @param array the array where elements are fetched from
     * @param predicate the predicate applied to every element fetched from the
     * array
     * @return true if EVERY predicate application yields true
     */
    public static <E> boolean every(E[] array, Predicate<E> predicate) {
        return new Every<E>(predicate).test(new ArrayIterator<E>(array));
    }

    /**
     * Counts elements contained in the iterator.
     *
     * @param <E> the iterator element type parameter
     * @param iterator the iterator to be consumed
     * @return the size of the iterator
     */
    public static <E> long count(Iterator<E> iterator) {
        return reduce(iterator, new Count<E>(), 0l);
    }

    /**
     * Counts elements contained in the iterable.
     *
     * @param <E> the iterable element type parameter
     * @param iterable the iterable to be consumed
     * @return the size of the iterable
     */
    public static <E> long count(Iterable<E> iterable) {
        dbc.precondition(iterable != null, "cannot call count with a null iterable");
        return count(iterable.iterator());
    }

    /**
     * Counts elements contained in the iterator.
     *
     * @param <E> the iterator element type parameter
     * @param iterator the iterator to be consumed
     * @return the size of the iterator
     */
    public static <E> int counti(Iterator<E> iterator) {
        final long value = reduce(iterator, new Count<E>(), 0l);
        dbc.state(value <= Integer.MAX_VALUE, "iterator size overflows an integer");
        return (int) value;
    }

    /**
     * Counts elements contained in the iterable.
     *
     * @param <E> the iterable element type parameter
     * @param iterable the iterable to be consumed
     * @return the size of the iterator
     */
    public static <E> int counti(Iterable<E> iterable) {
        dbc.precondition(iterable != null, "cannot call counti with a null iterable");
        return counti(iterable.iterator());
    }

    /**
     * Returns the max element contained in the iterator
     *
     * @param <E> the iterator element type parameter
     * @param <C> the comparator type parameter
     * @param iterator the iterator to be consumed
     * @param comparator the comparator to be used to evaluate the max element
     * @param init the initial value to be used
     * @return the max element contained in the iterator
     */
    public static <E, C extends Comparator<E>> E maximum(Iterator<E> iterator, C comparator, E init) {
        return Reductions.reduce(iterator, BinaryOperator.maxBy(comparator), init);
    }

    /**
     * Returns the max element contained in the iterator
     *
     * @param <E> the iterator element type parameter
     * @param iterator the iterator to be consumed
     * @param init the initial value to be used
     * @return the max element contained in the iterator
     */
    public static <E extends Comparable<E>> E maximum(Iterator<E> iterator, E init) {
        return Reductions.reduce(iterator, BinaryOperator.maxBy(new ComparableComparator<E>()), init);
    }

    /**
     * Returns the min element contained in the iterator
     *
     * @param <E> the iterator element type parameter
     * @param <C> the comparator type parameter
     * @param iterator the iterator to be consumed
     * @param comparator the comparator to be used to evaluate the min element
     * @param init the initial value to be used
     * @return the min element contained in the iterator
     */
    public static <E, C extends Comparator<E>> E minimum(Iterator<E> iterator, C comparator, E init) {
        return Reductions.reduce(iterator, BinaryOperator.minBy(comparator), init);
    }

    /**
     * Returns the min element contained in the iterator
     *
     * @param <E> the iterator element type parameter
     * @param iterator the iterator to be consumed
     * @param init the initial value to be used
     * @return the min element contained in the iterator
     */
    public static <E extends Comparable<E>> E minimum(Iterator<E> iterator, E init) {
        return Reductions.reduce(iterator, BinaryOperator.minBy(new ComparableComparator<E>()), init);
    }
}


text:
package swf

import (
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/client"
	"github.com/aws/aws-sdk-go/aws/client/metadata"
	"github.com/aws/aws-sdk-go/aws/request"
	"github.com/aws/aws-sdk-go/aws/signer/v4"
	"github.com/aws/aws-sdk-go/private/protocol/jsonrpc"
)

// The Amazon Simple Workflow Service (Amazon SWF) makes it easy to build applications
// that use Amazon's cloud to coordinate work across distributed components.
// In Amazon SWF, a task represents a logical unit of work that is performed
// by a component of your workflow. Coordinating tasks in a workflow involves
// managing intertask dependencies, scheduling, and concurrency in accordance
// with the logical flow of the application.
//
// Amazon SWF gives you full control over implementing tasks and coordinating
// them without worrying about underlying complexities such as tracking their
// progress and maintaining their state.
//
// This documentation serves as reference only. For a broader overview of the
// Amazon SWF programming model, see the Amazon SWF Developer Guide (http://docs.aws.amazon.com/amazonswf/latest/developerguide/).
//The service client's operations are safe to be used concurrently.
// It is not safe to mutate any of the client's properties though.
type SWF struct {
	*client.Client
}

// Used for custom client initialization logic
var initClient func(*client.Client)

// Used for custom request initialization logic
var initRequest func(*request.Request)

// A ServiceName is the name of the service the client will make API calls to.
const ServiceName = "swf"

// New creates a new instance of the SWF client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
//     // Create a SWF client from just a session.
//     svc := swf.New(mySession)
//
//     // Create a SWF client with additional configuration
//     svc := swf.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func New(p client.ConfigProvider, cfgs ...*aws.Config) *SWF {
	c := p.ClientConfig(ServiceName, cfgs...)
	return newClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion)
}

// newClient creates, initializes and returns a new service client instance.
func newClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion string) *SWF {
	svc := &SWF{
		Client: client.New(
			cfg,
			metadata.ClientInfo{
				ServiceName:   ServiceName,
				SigningRegion: signingRegion,
				Endpoint:      endpoint,
				APIVersion:    "2012-01-25",
				JSONVersion:   "1.0",
				TargetPrefix:  "SimpleWorkflowService",
			},
			handlers,
		),
	}

	// Handlers
	svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
	svc.Handlers.Build.PushBackNamed(jsonrpc.BuildHandler)
	svc.Handlers.Unmarshal.PushBackNamed(jsonrpc.UnmarshalHandler)
	svc.Handlers.UnmarshalMeta.PushBackNamed(jsonrpc.UnmarshalMetaHandler)
	svc.Handlers.UnmarshalError.PushBackNamed(jsonrpc.UnmarshalErrorHandler)

	// Run custom client initialization if present
	if initClient != nil {
		initClient(svc.Client)
	}

	return svc
}

// newRequest creates a new request for a SWF operation and runs any
// custom request initialization.
func (c *SWF) newRequest(op *request.Operation, params, data interface{}) *request.Request {
	req := c.NewRequest(op, params, data)

	// Run custom request initialization if present
	if initRequest != nil {
		initRequest(req)
	}

	return req
}


text:
(function(scope) {
  'use strict';

  var ChildNodeInterface = scope.ChildNodeInterface;
  var Node = scope.wrappers.Node;
  var mixin = scope.mixin;
  var registerWrapper = scope.registerWrapper;

  var OriginalCharacterData = window.CharacterData;

  function CharacterData(node) {
    Node.call(this, node);
  }
  CharacterData.prototype = Object.create(Node.prototype);
  mixin(CharacterData.prototype, {
    get textContent() {
      return this.data;
    },
    set textContent(value) {
      this.data = value;
    }
  });

  mixin(CharacterData.prototype, ChildNodeInterface);

  registerWrapper(OriginalCharacterData, CharacterData,
                  document.createTextNode(''));

  scope.wrappers.CharacterData = CharacterData;
})(this.ShadowDOMPolyfill);


text:
from django.contrib.auth import get_user_model
from rest_framework import serializers

from .models import Catastrophe

class CatastropheSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Catastrophe
        fields = ('name', 'description', 'arrival_date', 'url', 'more_info', )

class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = get_user_model()
        fields = ('username', 'is_staff', )


text:
import pickle
import numpy as np
import matplotlib.pyplot as plt
import os
from src import loadseg
from PIL import Image

"""
module to handle saliency map data
"""

class Smap():
    def __init__(self, data, directory):
        self.directory = directory
        self.data = data
        category = os.path.join(directory, "category.dump")

        with open(category, "r") as f:
            self.category = pickle.load(f)

    def get_image_path(self, index):
        """
        get path to original image in broden
        """
        path = os.path.join(self.data.directory,
                            "images", data.image[index]["image"])
        return path

    def open_saliency_map(self, index):
        """
        get numpy array for saliency
        """
        path = os.path.join(self.directory, "{}.npy".format(index))
        print(path)
        smap = np.load(path)
        return smap

    def save_masked_image(self, index, threshold=0.8):
        """
        return original image with masking by saliency map
        """

        smap = self.open_saliency_map(index)

        # normalize smap to range from 0 to 1
        smap = smap / smap.max()
        smap = 1 - smap
        im = Image.new("RGBA", smap.shape, "black")
        imarray = np.asarray(im)
        imarray.flags.writeable = True
        imarray = imarray.astype(np.float32)

        # changing alpha is equivalent to changing imarray[:, :, 3]
        imarray[:, :, 3] = smap
        alpha = imarray[:, :, 3]
        alpha = alpha ** 3

        alpha = alpha * 255

        condition = (np.where(alpha < 255 * threshold))

        alpha[condition] = 0
        # converting array to image and reshapre
        imarray[:, :, 3] = alpha
        im = Image.fromarray(imarray.astype(np.uint8))
        original_image = Image.open(self.get_image_path(index))
        im = im.resize(original_image.size, resample=Image.BILINEAR)

        # merge two pictures
        original_image.paste(im, (0, 0), im)

        # save image
        original_image.save(os.path.join(self.directory,
                                         "Images", "{}.png".format(index)))

if __name__ == "__main__":
    print("loading data...")
    data = loadseg.SegmentationData("dataset/broden1_227")
    smap = Smap(data, "test")
    for i in range(10):
        smap.save_masked_image(i, threshold=0.6)


text:
from __future__ import print_function

"""

    These are tests for writing and processing designspace.designspace documents
        - write various designspaces
        - read them
        - process them using the test fonts
        - show masters can be read from different directories
        - show instances can be generated into different directories
        - do some basic output testing.

"""

import os

import defcon.objects.font
import mutatorMath.objects.error

from mutatorMath.ufo.document import DesignSpaceDocumentWriter, DesignSpaceDocumentReader
from mutatorMath.objects.location import Location

def stripPrefix(d):
    # strip the "public.kern" prefixes from d
    new = []
    for pair, value in d:
        a, b = pair
        if "public.kern" in a:
            a = a[13:]
        if "public.kern" in b:
            b = b[13:]
        new.append(((a,b), value))
    return sorted(new)

#t = [(('V', 'public.kern2.@MMK_R_A'), -100), (('public.kern1.@MMK_L_A', 'V'), -100)]
#stripPrefix(t)

def test1():
    """
    >>> import time
    >>> from mutatorMath.ufo.document import initializeLogger
    >>> testRoot = os.path.join(os.path.dirname(__file__), 'data')
    >>> documentPath = os.path.join(testRoot, 'exporttest_basic.designspace')
    >>> sourcePath = os.path.join(testRoot, 'sources')
    >>> instancePath = os.path.join(testRoot, 'instances')
    >>> master1Path = os.path.join(testRoot, )
    >>> #logPath = None #
    >>> logPath = os.path.join(testRoot, "tests.log")
    >>> if logPath is not None:
    ...     if os.path.exists(logPath):
    ...         os.remove(logPath)
    ...     initializeLogger(logPath)
    >>> ufoVersion=2
    >>> roundGeometry=True      # this will trigger some fails if run with a pre-ufo3 fontMath.

    >>> doc = DesignSpaceDocumentWriter(documentPath, verbose=True)
    >>> doc.addSource(
    ...        os.path.join(sourcePath, "light", "LightCondensed.ufo"),
    ...        name="master_1",
    ...        location=dict(width=0),
    ...        copyLib=True,            # change to see the copy Lib test fail
    ...        copyGroups=True,         # change to see assertions fail on groupSource and instance groups.
    ...        copyInfo=True,
    ...        copyFeatures=True,
    ...        muteKerning=False,
    ...        muteInfo=True,
    ...        mutedGlyphNames=['a',],
    ...        familyName="ExplicitSourceFamilyName",
    ...        styleName="ExplicitSourceStyleName",)
    >>> doc.addSource(
    ...        os.path.join(sourcePath, "light", "LightWide.ufo"),
    ...        name="master_2",
    ...        location=dict(width=1),
    ...        copyLib=False,
    ...        copyGroups=False,
    ...        copyInfo=False,
    ...        muteKerning=True,
    ...        muteInfo=True,
    ...        mutedGlyphNames=['b'] )
    >>> testOutputFileName = os.path.join(instancePath, "A", "testOutput_glyphs.ufo")
    >>> glyphMasters = [('M', "master_1", dict(width=0)), ('M', "master_2", dict(width=1)), ]
    >>> doc.startInstance(fileName=testOutputFileName,
    ...       familyName="TestFamily",
    ...       styleName="TestStyleName",
    ...       location=dict(width=(0.2, 0.8)))
    >>> doc.writeGlyph("M", unicodes=[0xff], location=dict(width=0.9), masters=None, note="testnote123")
    >>> doc.writeGlyph("N", location=dict(width=0.7), masters=glyphMasters)
    >>> doc.endInstance()
    >>> doc.save()
    >>> doc = DesignSpaceDocumentReader(documentPath, ufoVersion, roundGeometry=roundGeometry, verbose=True, logPath=logPath)
    >>> doc.process(makeGlyphs=True, makeKerning=False, makeInfo=False)

        # check if we found the UFOs
    >>> assert "master_1" in doc.sources
    >>> assert "master_2" in doc.sources

        # check if we are reading the muting flags
    >>> assert doc.libSource == 'master_1'
    >>> assert doc.groupsSource == 'master_1'
    >>> assert doc.libSource == 'master_1'
    >>> assert doc.muted == {'info': ['master_1', 'master_2'], 'glyphs': {'master_2': ['b'], 'master_1': ['a']}, 'kerning': ['master_2']}

        # check the locations
    >>> fontObj, loc = doc.sources['master_1']
    >>> loc.asTuple()
    (('width', 0.0),)
    >>> loc.asTuple()
    (('width', 0.0),)
    >>> fontObj, loc = doc.sources['master_2']
    >>> loc.asTuple()
    (('width', 1.0),)

        # check the instances
    >>> assert os.path.basename(testOutputFileName) in doc.results
    >>> resultUFOPath = doc.results[os.path.basename(testOutputFileName)]
    >>> instance = defcon.objects.font.Font(resultUFOPath)

        # note: the next assertion will fail if the calculations were made with the
        # pre-ufo3 fontMath.

    >>> assert instance['M'].unicodes == [0xff]

        # check the groups
    >>> ('testGroup', ['E', 'F', 'H']) in list(instance.groups.items())
    True

        # check the lib
    >>> assert "testLibItemKey" in instance.lib.keys()

        # check the feature text was copied from the source
    >>> assert "Hi_this_is_the_feature." in instance.features.text

        # basic kerning processing.
    >>> documentPath = os.path.join(testRoot, 'exporttest_kerning.designspace')
    >>> doc = DesignSpaceDocumentWriter(documentPath, verbose=True)
    >>> doc.addSource(
    ...        os.path.join(sourcePath, "light", "LightCondensed.ufo"),
    ...        name="master_1",
    ...        location=dict(weight=0),
    ...        copyLib=True,
    ...        copyGroups=True,
    ...        copyInfo=True,
    ...        muteKerning=False,
    ...        muteInfo=False)
    >>> doc.addSource(
    ...        os.path.join(sourcePath, "bold", "BoldCondensed.ufo"),
    ...        name="master_2",
    ...        location=dict(weight=1),
    ...        copyLib=False,
    ...        copyGroups=False,
    ...        copyInfo=False,
    ...        muteKerning=False,
    ...        muteInfo=False )
    >>> testOutputFileName = os.path.join(instancePath, "B", "testOutput_kerning.ufo")
    >>> doc.startInstance(fileName=testOutputFileName, familyName="TestFamily", styleName="TestStyleName", location=dict(weight=0.6))

        # give this kerning master a different location
    >>> #doc.writeKerning(location=dict(weight=1))
    >>> #doc.endInstance()
    >>> #doc.save()
    >>> #doc = DesignSpaceDocumentReader(documentPath, ufoVersion, roundGeometry=roundGeometry, verbose=True, logPath=logPath)
    >>> #doc.process(makeGlyphs=False, makeKerning=True, makeInfo=False)
    >>> #assert os.path.basename(testOutputFileName) in doc.results
    >>> #resultUFOPath = doc.results[os.path.basename(testOutputFileName)]
    >>> #instance = defcon.objects.font.Font(resultUFOPath)
    >>> #assert sorted(instance.kerning.items()) == stripPrefix([(('@MMK_L_A', 'V'), 100), (('V', '@MMK_R_A'), 100)])

        # test the effects of muting the kerning
    >>> documentPath = os.path.join(testRoot, 'exporttest_kerning_muted.designspace')
    >>> doc = DesignSpaceDocumentWriter(documentPath, verbose=True)
    >>> doc.addSource(
    ...        os.path.join(sourcePath, "light", "LightCondensed.ufo"),
    ...        name="master_1",
    ...        location=dict(weight=0),
    ...        copyLib=True,
    ...        copyGroups=True,
    ...        copyInfo=True,
    ...        muteKerning=False,
    ...        muteInfo=False)
    >>> doc.addSource(
    ...        os.path.join(sourcePath, "bold", "BoldCondensed.ufo"),
    ...        name="master_2",
    ...        location=dict(weight=1),
    ...        copyLib=False,
    ...        copyGroups=False,
    ...        copyInfo=False,
    ...        muteKerning=True,    # mute a master at a non-origin location!
    ...        muteInfo=False )
    >>> testOutputFileName = os.path.join(instancePath, "C", "testOutput_kerning_muted.ufo")
    >>> testLocation = dict(weight=0.6)        # change this location to see calculation assertions fail.
    >>> doc.startInstance(fileName=testOutputFileName, familyName="TestFamily", styleName="TestStyleName", location=testLocation)
    >>> doc.writeKerning()
    >>> doc.endInstance()
    >>> doc.save()
    >>> doc = DesignSpaceDocumentReader(documentPath, ufoVersion, roundGeometry=roundGeometry, verbose=True, logPath=logPath)
    >>> paths = doc.getSourcePaths()
    >>> len(paths)
    2
    >>> doc.process(makeGlyphs=False, makeKerning=True, makeInfo=False)
    >>> assert doc.groupsSource == 'master_1'
    >>> assert os.path.basename(testOutputFileName) in doc.results
    >>> resultUFOPath = doc.results[os.path.basename(testOutputFileName)]
    >>> instance = defcon.objects.font.Font(resultUFOPath)

        # the bold condensed kerning master has been muted, we expect the light condensed data in the instance
    >>> assert [(('@MMK_L_A', 'V'), -100), (('V', '@MMK_R_A'), -100)] == stripPrefix(sorted(instance.kerning.items()))

        # info data
        #   calculating fields
        #   copying fields
    >>> documentPath = os.path.join(testRoot, 'exporttest_info.designspace')
    >>> doc = DesignSpaceDocumentWriter(documentPath, verbose=True)
    >>> doc.addSource(
    ...        os.path.join(sourcePath, "light", "LightCondensed.ufo"),
    ...        name="master_1",
    ...        location=dict(weight=0),
    ...        copyLib=False,
    ...        copyGroups=False,
    ...        copyInfo=True,       # flip to False and see some assertions fail
    ...        muteKerning=True,
    ...        muteInfo=False)
    >>> doc.addSource(
    ...        os.path.join(sourcePath, "bold", "BoldCondensed.ufo"),
    ...        name="master_2",
    ...        location=dict(weight=1),
    ...        copyLib=False,
    ...        copyGroups=False,
    ...        copyInfo=False,
    ...        muteKerning=True,
    ...        muteInfo=False )
    >>> testOutputFileName = os.path.join(instancePath, "D", "testOutput_info.ufo")
    >>> testLocation = dict(weight=0.5)       # change this location to see calculation assertions fail.
    >>> doc.startInstance(
    ...        fileName=testOutputFileName,
    ...        familyName="TestFamily",
    ...        styleName="TestStyleName",
    ...        location=testLocation,
    ...        postScriptFontName="TestPostScriptFontNameValue",
    ...        styleMapFamilyName="TestStyleMapFamilyNameValue",
    ...        styleMapStyleName="bold italic",
    ...        )
    >>> doc.writeInfo()
    >>> doc.endInstance()
    >>> doc.save()
    >>> doc = DesignSpaceDocumentReader(documentPath, ufoVersion, roundGeometry=roundGeometry, verbose=True, logPath=logPath)
    >>> doc.process(makeGlyphs=False, makeKerning=False, makeInfo=True)

    >>> assert os.path.basename(testOutputFileName) in doc.results
    >>> resultUFOPath = doc.results[os.path.basename(testOutputFileName)]
    >>> instance = defcon.objects.font.Font(resultUFOPath)

        # example calculated values
    >>> assert instance.info.ascender == 750
    >>> assert instance.info.capHeight == 750

        # example copied values
    >>> assert instance.info.versionMajor == 1
    >>> assert instance.info.openTypeOS2VendorID == "LTTR"
    >>> assert instance.info.copyright == "License same as MutatorMath. BSD 3-clause. [test-token: C]"

        # test the build script
    >>> documentPath = os.path.join(testRoot, 'exporttest_build.designspace')
    >>> doc = DesignSpaceDocumentWriter(documentPath, verbose=True)
    >>> doc.addSource(
    ...        os.path.join(sourcePath, "light", "LightCondensed.ufo"),
    ...        name="master_1",
    ...        location=dict(weight=0),
    ...        copyLib=True,
    ...        copyGroups=True,
    ...        copyInfo=True,
    ...        muteKerning=False,
    ...        muteInfo=False)
    >>> doc.addSource(
    ...        os.path.join(sourcePath, "bold", "BoldCondensed.ufo"),
    ...        name="master_2",
    ...        location=dict(weight=1),
    ...        copyLib=False,
    ...        copyGroups=False,
    ...        copyInfo=False,
    ...        muteKerning=False,
    ...        muteInfo=False )
    >>> testOutputFileName = os.path.join(instancePath, "E", "testOutput_build.ufo")
    >>> testLocation = dict(weight=0.25)       # change this location to see calculation assertions fail.
    >>> doc.startInstance(
    ...        fileName=testOutputFileName,
    ...        familyName="TestFamily",
    ...        styleName="TestStyleName",
    ...        location=testLocation)
    >>> doc.writeInfo()
    >>> doc.writeKerning()
    >>> doc.endInstance()
    >>> doc.save()

        # test build function -- single designspace file
    >>> from mutatorMath.ufo import build
    >>> import os
    >>> import posixpath
    >>> here = os.path.join(os.path.dirname(__file__), 'data', 'exporttest_basic.designspace')
    >>> results = build(here, outputUFOFormatVersion=2)
    >>> ufoFullPath = results[0]['testOutput_glyphs.ufo']
    >>> ufoRelPath = os.path.relpath(ufoFullPath, os.path.dirname(__file__))
    >>> posixRelPath = posixpath.join(*ufoRelPath.split(os.path.sep))
    >>> posixRelPath
    'data/instances/A/testOutput_glyphs.ufo'

    # test the axes elements
    >>> documentPath = os.path.join(testRoot, 'warpmap_test.designspace')
    >>> doc = DesignSpaceDocumentWriter(documentPath, verbose=True)
    >>> def grow(base, factor, steps):
    ...     return [(i*100, int(round(base*(1+factor)**i))) for i in range(steps)]
    >>> doc.addAxis("wght", "weight", 0, 1000, 0, grow(100,0.55,11))
    >>> doc.addSource(
    ...        os.path.join(sourcePath, "stems", "StemThin.ufo"),
    ...        name="master_1",
    ...        location=dict(weight=0),
    ...        copyLib=True,
    ...        copyGroups=True,
    ...        copyInfo=True,
    ...        muteKerning=False,
    ...        muteInfo=False)
    >>> doc.addSource(
    ...        os.path.join(sourcePath, "stems", "StemBold.ufo"),
    ...        name="master_2",
    ...        location=dict(weight=1000),
    ...        copyLib=False,
    ...        copyGroups=False,
    ...        copyInfo=False,
    ...        muteKerning=False,
    ...        muteInfo=False )
    >>> testOutputFileName = os.path.join(instancePath, "W", "StemOutput.ufo")
    >>> testLocation = dict(weight=0)       # change this location to see calculation assertions fail.
    >>> doc.startInstance(
    ...        fileName=testOutputFileName,
    ...        familyName="TestFamily",
    ...        styleName="Warped",
    ...        location=testLocation)
    >>> doc.writeInfo()
    >>> doc.writeKerning()
    >>> glyphMasters = [('I', "master_1", dict(weight=0)), ('I', "master_2", dict(weight=1000)), ]
    >>> for i in range(0, 1000, 50):
    ...    doc.writeGlyph("I.%04d"%i, location=dict(weight=i), masters=glyphMasters)
    ...
    >>> doc.endInstance()
    >>> doc.save()

    >>> doc = DesignSpaceDocumentReader(documentPath, ufoVersion, roundGeometry=roundGeometry, verbose=True, logPath=logPath)
    >>> doc.process(makeGlyphs=True, makeKerning=False, makeInfo=False)

    >>> documentPath = os.path.join(testRoot, 'no_warpmap_test.designspace')
    >>> doc = DesignSpaceDocumentWriter(documentPath, verbose=True)
    >>> doc.addAxis("wght", "weight", 0, 1000, 0)
    >>> doc.addSource(
    ...        os.path.join(sourcePath, "stems", "StemThin.ufo"),
    ...        name="master_1",
    ...        location=dict(weight=0),
    ...        copyLib=True,
    ...        copyGroups=True,
    ...        copyInfo=True,
    ...        muteKerning=False,
    ...        muteInfo=False)
    >>> doc.addSource(
    ...        os.path.join(sourcePath, "stems", "StemBold.ufo"),
    ...        name="master_2",
    ...        location=dict(weight=1000),
    ...        copyLib=False,
    ...        copyGroups=False,
    ...        copyInfo=False,
    ...        muteKerning=False,
    ...        muteInfo=False )
    >>> testOutputFileName = os.path.join(instancePath, "W", "StemOutput_nowarp.ufo")
    >>> testLocation = dict(weight=0)       # change this location to see calculation assertions fail.
    >>> doc.startInstance(
    ...        fileName=testOutputFileName,
    ...        familyName="TestFamily",
    ...        styleName="NotWarped",
    ...        location=testLocation)
    >>> doc.writeInfo()
    >>> doc.writeKerning()
    >>> glyphMasters = [('I', "master_1", dict(weight=0)), ('I', "master_2", dict(weight=1000)), ]
    >>> for i in range(0, 1000, 50):
    ...    doc.writeGlyph("I.%04d"%i, location=dict(weight=i), masters=glyphMasters)
    ...
    >>> doc.endInstance()
    >>> doc.save()

    >>> doc = DesignSpaceDocumentReader(documentPath, ufoVersion, roundGeometry=roundGeometry, verbose=True, logPath=logPath)
    >>> doc.process(makeGlyphs=True, makeKerning=False, makeInfo=False)

    # test the axes element
    >>> from pprint import pprint
    >>> documentPath = os.path.join(testRoot, 'axes_test.designspace')
    >>> doc = DesignSpaceDocumentWriter(documentPath, verbose=True)
    >>> def grow(base, factor, steps):
    ...     return [(i*100, int(round(base*(1+factor)**i))) for i in range(steps)]

    >>> # axis with a warp map
    >>> warpMap = grow(100,0.55,11)
    >>> doc.addAxis("wght", "weight", -1000, 1000, 0, warpMap)
    >>> # axis without a warp map
    >>> doc.addAxis("wdth", "width", 0, 1000, 0)
    >>> doc.save()

    >>> doc = DesignSpaceDocumentReader(documentPath, ufoVersion, roundGeometry=roundGeometry, verbose=True, logPath=logPath)
    >>> pprint(doc.axes)
    {'weight': {'default': 0.0,
                'map': [(0.0, 100.0),
                        (100.0, 155.0),
                        (200.0, 240.0),
                        (300.0, 372.0),
                        (400.0, 577.0),
                        (500.0, 895.0),
                        (600.0, 1387.0),
                        (700.0, 2149.0),
                        (800.0, 3332.0),
                        (900.0, 5164.0),
                        (1000.0, 8004.0)],
                'maximum': 1000.0,
                'minimum': -1000.0,
                'name': 'weight',
                'tag': 'wght'},
     'width': {'default': 0.0,
               'map': [],
               'maximum': 1000.0,
               'minimum': 0.0,
               'name': 'width',
               'tag': 'wdth'}}

    >>> doc.process(makeGlyphs=False, makeKerning=False, makeInfo=False)
    """

def bender_and_mutatorTest():
    """
    >>> from mutatorMath.objects.bender import Bender
    >>> from mutatorMath.objects.location import Location
    >>> from mutatorMath.objects.mutator import buildMutator

    >>> w = {'aaaa':{
    ...     'map': [(300, 50),
    ...          (400, 100),
    ...          (700, 150)],
    ...     'name':'aaaaAxis',
    ...     'tag':'aaaa',
    ...     'minimum':0,
    ...     'maximum':1000,
    ...     'default':0}}

    >>> b = Bender(w)
    >>> assert b(dict(aaaa=300)) == {'aaaa': 50}
    >>> assert b(dict(aaaa=400)) == {'aaaa': 100}
    >>> assert b(dict(aaaa=700)) == {'aaaa': 150}

    master locations are always in internal design coordinates, thus they are
    considered to be already mapped or bent.

    >>> items = [
    ...     (Location(aaaa=50), 0),
    ...     (Location(aaaa=100), 50),
    ...     (Location(aaaa=150), 100),
    ... ]

    >>> bias, mut = buildMutator(items, w, bias=Location(aaaa=100))
    >>> bias
    <Location aaaa:100 >

    >>> bias, mut = buildMutator(items, w, bias=Location(aaaa=150))
    >>> bias
    <Location aaaa:150 >

    >>> bias, mut = buildMutator(items, w, bias=Location(aaaa=50))
    >>> bias
    <Location aaaa:50 >

    >>> expect = sorted([(('aaaa', 100),), (('aaaa', 50),), ()])
    >>> expect
    [(), (('aaaa', 50),), (('aaaa', 100),)]

    >>> got = sorted(mut.keys())
    >>> got
    [(), (('aaaa', 50),), (('aaaa', 100),)]

    >>> assert got == expect

    Instance location are not bent by default, i.e. are interpreted as internal
    design coordinates:
    >>> assert mut.makeInstance(Location(aaaa=50)) == 0
    >>> assert mut.makeInstance(Location(aaaa=100)) == 50
    >>> assert mut.makeInstance(Location(aaaa=150)) == 100

    If bend=True, instance locations are interpreted as user-space coordinates
    >>> assert mut.makeInstance(Location(aaaa=300), bend=True) == 0
    >>> assert mut.makeInstance(Location(aaaa=400), bend=True) == 50
    >>> assert mut.makeInstance(Location(aaaa=700), bend=True) == 100
    """

if __name__ == '__main__':
    import sys
    import doctest
    sys.exit(doctest.testmod().failed)


text:
import React from "react";
import TestRenderer from "react-test-renderer";
import { iterator } from "@times-components/test-utils";
import ArticleSummary, { ArticleSummaryContent } from "../src/article-summary";
import defaultFixture from "../fixtures/default";

jest.mock("@times-components/article-byline", () => ({
  __esModule: true,
  ArticleBylineOpinion: "ArticleBylineOpinion",
  default: "ArticleByline"
}));
jest.mock("@times-components/ts-components", () => ({
  __esModule: true,
  ...jest.requireActual("@times-components/ts-components"),
  ArticleFlags: "ArticleFlags"
}));
jest.mock("@times-components/article-label", () => "ArticleLabel");
jest.mock("@times-components/date-publication", () => "DatePublication");
jest.mock("@times-components/video-label", () => "VideoLabel");

export default () => {
  const headline = "Test Headline";
  const label = "Test label";
  const paragraph = "Test paragraph";
  const ast = [
    {
      attributes: {},
      children: [
        {
          attributes: {
            value: "Test"
          },
          children: [],
          name: "text"
        }
      ],
      name: "paragraph"
    }
  ];

  const tests = [
    {
      name: "article summary component with a single paragraph",
      test: () => {
        const testInstance = TestRenderer.create(
          <ArticleSummary
            {...defaultFixture({
              headline,
              label,
              paragraph
            })}
          />
        );

        expect(testInstance.toJSON()).toMatchSnapshot();
      }
    },
    {
      name: "article summary content component with the given style",
      test: () => {
        const testInstance = TestRenderer.create(
          <ArticleSummaryContent ast={ast} />
        );

        expect(testInstance.toJSON()).toMatchSnapshot();
      }
    },
    {
      name:
        "article summary content component with white space height and lineHeight",
      test: () => {
        const testInstance = TestRenderer.create(
          <ArticleSummaryContent
            ast={ast}
            style={{ lineHeight: 30 }}
            whiteSpaceHeight={60}
          />
        );

        expect(testInstance.toJSON()).toMatchSnapshot();
      }
    },
    {
      name: "article summary content component without white space height",
      test: () => {
        const testInstance = TestRenderer.create(
          <ArticleSummaryContent ast={ast} whiteSpaceHeight={0} />
        );

        expect(testInstance.toJSON()).toMatchSnapshot();
      }
    }
  ];

  iterator(tests);
};


text:
golang-driver
=============

Golang wrapper of the DataStax/Cassandra [C/C++ driver 2.1 api](https://github.com/datastax/cpp-driver)

Basic support for prepared statements and ad hoc queries. Lacking support for collections, but that will be remedied shortly.

### Build

1. Build and install the DataStax [C/C++ driver 2.1 api](https://github.com/datastax/cpp-driver)
1. Install `go get github.com/mstump/golang-driver/cassandra`
1. Run the example `go run $GOPATH/src/github.com/mstump/golang-driver/examples/basic.go`

### Example Usage

```go
package main

import (
	"fmt"
	"golang-driver/cassandra"
)

func main() {
	cluster := cassandra.NewCluster()
	cluster.SetContactPoints("cassandra")
	defer cluster.Finalize()

	session := cassandra.NewSession()
	defer session.Finalize()

	sessfuture := cluster.SessionConnect(session)
	sessfuture.Wait()
	defer sessfuture.Finalize()

	statement := cassandra.NewStatement("select cluster_name from system.local;", 0)
	defer statement.Finalize()

	stmtfuture := session.Execute(statement)
	stmtfuture.Wait()
	defer stmtfuture.Finalize()

	result := stmtfuture.Result()
	defer result.Finalize()

	fmt.Printf("Clusters:\r\n")
	for result.Next() {
		var clusterName string
		result.Scan(&clusterName)
		fmt.Printf("%s\n", clusterName)
	}

	fmt.Printf("DONE.\r\n")
}
```


text:
'use strict';

var mongodbWorkshopFilters = angular.module('mongodbWorkshopFilters', []);

mongodbWorkshopFilters.filter(
    'restrictLength',
    [
        function () {
            return function (text) {
                return text.substring(0, 150) + ' [...]';
            }
        }
    ]
);


text:
package eu.ehealth.ws_client.xsd;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *

 * Clase Java para CommunicationList complex type.
 *
 *

 * El siguiente fragmento de esquema especifica el contenido que se espera que
 * haya en esta clase.
 *
 *

 * <complexType name="CommunicationList">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="Communication" type="{http://aladdin-project.eu/xsd}Communication" maxOccurs="unbounded" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "CommunicationList", propOrder = { "communication" })
public class CommunicationList
{

	@XmlElement(name = "Communication")
	protected List<Communication> communication;

	public CommunicationList()
	{
	}

	public CommunicationList(
			eu.ehealth.ws_client.xsd.Communication[] communication)
	{
		try {
			this.communication = Arrays.asList(communication);;
		}
		catch (Exception ex) {}
	}

	/**
	 * Gets the value of the communication property.
	 *
	 *

	 * This accessor method returns a reference to the live list, not a
	 * snapshot. Therefore any modification you make to the returned list will
	 * be present inside the JAXB object. This is why there is not a
	 * set method for the communication property.
	 *
	 *

	 * For example, to add a new item, do as follows:
	 *
	 *

	 * getCommunication().add(newItem);
	 *

	 *
	 *
	 *

	 * Objects of the following type(s) are allowed in the list
	 * {@link Communication }
	 *
	 *
	 */
	public List<Communication> getCommunication()
	{
		if (communication == null)
		{
			communication = new ArrayList<Communication>();
		}
		return this.communication;
	}

}


text:
HOST_OS=$1
shift

# Space for global provisioning procedures

# For user specific provision use usr/bootstrap.sh
if [ -f /vagrant-usr/bootstrap.sh ]; then
	. /vagrant-usr/bootstrap.sh
	echo "-I|Provision usr/bootstrap.sh finished!"
fi

echo "-I|Provision finished!"


text:
package api

import (
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/client-go/pkg/fields"
)

func addDefaultingFuncs(scheme *runtime.Scheme) error {
	return scheme.AddDefaultingFuncs(
		func(obj *ListOptions) {
			if obj.LabelSelector == nil {
				obj.LabelSelector = labels.Everything()
			}
			if obj.FieldSelector == nil {
				obj.FieldSelector = fields.Everything()
			}
		},
	)
}


text:
import * as types from '../../store/mutation-types'
import recentlyViewedMutations from '../../store/mutations'

describe('RecentlyViewed mutations', () => {
  beforeEach(() => {
    jest.clearAllMocks()
  })

  describe('RECENTLY_VIEWED_ADD_ITEM', () => {
    it('adds a product to recently viewed if none of its sku is there yet', () => {
      const stateMock = {
        items: []
      }
      const product = {
        qty: 123,
        sku: 'foo'
      }
      const expectedState = {
        items: [
          {
            qty: 123,
            sku: 'foo'
          }
        ]
      }
      const wrapper = (mutations: any) => mutations[types.RECENTLY_VIEWED_ADD_ITEM](stateMock, { product })

      wrapper(recentlyViewedMutations)

      expect(stateMock).toEqual(expectedState)
    })

    it('don\'t adds a product to recently viewed if there is one with the same sku', () => {
      const stateMock = {
        items: [
          {
            qty: 123,
            sku: 'foo'
          }
        ]
      }
      const product = {
        qty: 123,
        sku: 'foo'
      }
      const expectedState = {
        items: [
          {
            qty: 123,
            sku: 'foo'
          }
        ]
      }
      const wrapper = (mutations: any) => mutations[types.RECENTLY_VIEWED_ADD_ITEM](stateMock, { product })

      wrapper(recentlyViewedMutations)

      expect(stateMock).toEqual(expectedState)
    })
  })

  describe('RECENTLY_VIEWED_LOAD', () => {
    it('loads recently viewed items with given products', () => {
      const stateMock = {
        items: []
      }
      const product = {
        qty: 123,
        sku: 'foo'
      }
      const expectedState = {
        items: [
          {
            qty: 123,
            sku: 'foo'
          }
        ]
      }
      const wrapper = (mutations: any) => mutations[types.RECENTLY_VIEWED_LOAD](stateMock, [ product ])

      wrapper(recentlyViewedMutations)

      expect(stateMock).toEqual(expectedState)
    })
  })
})


text:
from django.http import HttpResponse, Http404
from django.template import RequestContext, loader
from django.shortcuts import render
from django.utils import simplejson
from django.utils.translation import ugettext as _

from tinymce.widgets import get_language_config

def textareas_js(request, name, lang=None):
    """
    Returns a HttpResponse whose content is a JavaScript file. The template
    is loaded from 'tinymce/<name>_textareas.js' or
    '<name>/tinymce_textareas.js'. Optionally, the lang argument sets the
    content language.
    """
    template_files = (
        'tinymce/%s_textareas.js' % name,
        '%s/tinymce_textareas.js' % name,
    )
    template = loader.select_template(template_files)

    vars = get_language_config(lang)
    vars['content_language'] = lang
    context = RequestContext(request, vars)

    return HttpResponse(template.render(context),
            content_type="application/x-javascript")

def preview(request, name):
    """
    Returns a HttpResponse whose content is an HTML file that is used
    by the TinyMCE preview plugin. The template is loaded from
    'tinymce/<name>_preview.html' or '<name>/tinymce_preview.html'.
    """
    template_files = (
        'tinymce/%s_preview.html' % name,
        '%s/tinymce_preview.html' % name,
    )
    template = loader.select_template(template_files)
    return HttpResponse(template.render(RequestContext(request)),
            content_type="text/html")

def filebrowser_js(request):
    url = request.GET.get('url')
    if not url:
        raise Http404
    return render(request, 'tinymce/filebrowser.js', {'url': url},
                  content_type='application/x-javascript')


text:
class Product(object):
    pass

class Inventory(object):
    def __init__(self):
        self.__items = []

    def add_new_item(self, product):
        if type(product) == Product:
            self.__items.append(product)
            print("new item added")
        else:
            raise ValueError("Invalid Item")

    def get_number_of_items(self):
        return len(self.__items)

my_inventory = Inventory()
my_inventory.add_new_item(Product())
my_inventory.add_new_item(Product())
print(my_inventory.get_number_of_items())

print(my_inventory.__items)
my_inventory.add_new_item(object)


text:
package esa.obeos.metadataeditor.model.api;

public interface IMdeVisitor
{
    public void beginVisit(final IMdeElement element) throws Exception;

    public void endVisit(final IMdeElement element) throws Exception;
}


text:
package com.cottsoft.design.patterns.creational.polymorphicfactory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cottsoft.design.patterns.Log;

/**
 * Description:<br>
 * 多态工厂(Polymorphic Factory),简单工厂和工厂方法的合体
 * @author  Simon.Hoo(Info@cottsoft.com)
 * @date    2005年03月03日
 * @version v1.0.0
 */
public class PolymorphicFactory {
	private Logger logger = LoggerFactory.getLogger(PolymorphicFactory.class);

	//定义三家工厂:中国人工厂,美国人工厂,英国人工厂
	private static PersonFactory chineseFactory,americanFactory,britishFactory;

	//定义三种人类:中国人,美国人,英国人
	private static IPerson chinese,american,british;

	public static void main(String[] args) {
		//实例化厂家工厂:
		chineseFactory = new PolymorphicFactory().new ChineseFactory();
		americanFactory = new PolymorphicFactory().new AmericanFactory();
		britishFactory = new PolymorphicFactory().new BritishFactory();

		//每间工厂创建对应的人类
		chinese = chineseFactory.factory();
		american = americanFactory.factory();
		british = britishFactory.factory();

		//具体人类做具体的事:
		chinese.msg();
		american.msg();
		british.msg();
	}

	/**
	 * 抽像工厂
	 * @author  Simon.Hoo(Info@cottsoft.com)
	 * @version v1.0.0
	 */
	public abstract class PersonFactory{
		public abstract IPerson factory();
	}

	/**
	 * 具体工厂:中国人工厂
	 * @author  Simon.Hoo(Info@cottsoft.com)
	 * @version v1.0.0
	 */
	public class ChineseFactory extends PersonFactory{
		@Override
		public IPerson factory() {
			return new ChineseImpl();
		}
	}

	/**
	 * 具体工厂:美国人工厂
	 * @author  Simon.Hoo(Info@cottsoft.com)
	 * @version v1.0.0
	 */
	public class AmericanFactory extends PersonFactory{
		@Override
		public IPerson factory() {
			return new AmericanImpl();
		}
	}

	/**
	 * 具体工厂:英国人工厂
	 * @author  Simon.Hoo(Info@cottsoft.com)
	 * @version v1.0.0
	 */
	public class BritishFactory extends PersonFactory{
		@Override
		public IPerson factory() {
			return new BritishImpl();
		}
	}

	/**
	 * 抽像人类
	 * @author  Simon.Hoo(Info@cottsoft.com)
	 * @version v1.0.0
	 */
	public abstract class IPerson{

		/**
		 * 吃饭
		 */
		public abstract void eat();

		/**
		 * 走路
		 */
		public abstract void walk();

		/**
		 * 工作
		 */
		public abstract void work();

		public void msg(){
			eat();
			walk();
			work();
		}
	}

	/**
	 * 具体人类:中国人
	 * @author  Simon.Hoo(Info@cottsoft.com)
	 * @version v1.0.0
	 */
	public class ChineseImpl extends IPerson{
		private String location;

		public ChineseImpl(){
			Log.log(logger, getLocation());
			speakChinese();
		}
		public String getLocation() {
			return location==null?"亚洲":location;
		}

		public void setLocation(String location) {
			this.location = location;
		}

		@Override
		public void eat() {
			Log.log(logger, "中国人吃中餐。");
		}

		@Override
		public void walk() {
			Log.log(logger, "中国人在中国的地盘上行走。");
		}

		@Override
		public void work() {
			Log.log(logger, "中国人在中国公司工作。");
		}

		public void speakChinese(){
			Log.log(logger, "中国人说中国话。");
		}
	}

	/**
	 * 具体人类:美国人
	 * @author  Simon.Hoo(Info@cottsoft.com)
	 * @version v1.0.0
	 */
	public class AmericanImpl extends IPerson{
		private String greenCard;

		public AmericanImpl(){
			Log.log(logger, getGreenCard());
			war();
		}
		public String getGreenCard() {
			return greenCard==null?"美国绿卡":greenCard;
		}

		public void setGreenCard(String greenCard) {
			this.greenCard = greenCard;
		}

		@Override
		public void eat() {
			Log.log(logger, "美国人吃火鸡。");
		}

		@Override
		public void walk() {
			Log.log(logger, "美国人在全世界行走。");
		}

		@Override
		public void work() {
			Log.log(logger, "美国人在全世界工作。");
		}

		public void war(){
			Log.log(logger, "美国人爱打仗。");
		}
	}

	/**
	 * 具体人类:英国人
	 * @author  Simon.Hoo(Info@cottsoft.com)
	 * @version v1.0.0
	 */
	public class BritishImpl extends IPerson{
		public String gentleman;

		public BritishImpl(){
			Log.log(logger, getGentleman());
			action();
		}
		public String getGentleman() {
			return gentleman==null?"英国人很绅士":gentleman;
		}

		public void setGentleman(String gentleman) {
			this.gentleman = gentleman;
		}

		@Override
		public void eat() {
			Log.log(logger, "英国人爱吃西餐。");
		}

		@Override
		public void walk() {
			Log.log(logger, "英国跟着美国人在全世界行走。");
		}

		@Override
		public void work() {
			Log.log(logger, "英国人在欧洲工作。");
		}

		public void action(){
			Log.log(logger, "英国人老爱跟着美国人屁股后面屁点屁点的打仗。");
		}

	}

}


text:
var music = null;
var sounds = {};
var mySoundAnalyser = null;

//////////////////////////////////////////////////////////////////////////////////// TRUCS PROCESSING
function preload() {
    music = loadSound("assets/musics/David Guetta - Tomorrow Can Wait - Summer Eletrohits 5.mp3", function () {
        console.log('Music loaded !');
        music.setVolume(0.1);
        music.play();

        mySoundAnalyser = new p5.FFT();
    });
    music.setVolume(0.1);

    sounds['W'] = loadSound('assets/sounds/drumkit1.mp3');
    sounds['W'].setVolume(1);

    sounds['X'] = loadSound('assets/sounds/5331.MP3');
    sounds['X'].setVolume(1);

    sounds['C'] = loadSound('assets/sounds/drumkit3.mp3');
    sounds['C'].setVolume(1);

    sounds['V'] = loadSound('assets/sounds/drumkit4.mp3');
    sounds['V'].setVolume(1);

    sounds['B'] = loadSound('assets/sounds/HINHINHIN.mp3');
    sounds['B'].setVolume(0.5);

    sounds['N'] = loadSound('assets/sounds/non.mp3');
    sounds['N'].setVolume(0.5);

    // Pour cacher le cnnvas processing
    $('#p5_loading').hide();
    $('#defaultCanvas0').hide();
}

function setup() {
    // Pour le chargement de la musique
}


text:
<app-table
  #table
  [mouseOverActive]="hasMap"
  [idSelector]="idSelector"
  [selectedIdSelector]="selectedIdSelector"
  [canSelect]="canSelect"
  [dataSource]="dataSource"
  [itemsSelected]="itemsSelected"
  [columnsToDisplay]="columnsToDisplay"
  [totalSelectableItems]="totalShipments"
  [selectDisabled]="changeDisabled"
  (selectAll)="onSelectAll()"
  (deselectAll)="onDeselectAll()"
  (selectedChange)="onSelectionChange($event)"
  matSort
  [matSortActive]="sort?.active"
  [matSortDirection]="sort?.direction"
  (matSortChange)="onSortChange($event)"
  (mouseEnterRow)="onMouseEnterRow($event)"
  (mouseExitRow)="onMouseExitRow($event)">
  <ng-container matColumnDef="id" sticky>
    ID

      <ng-container *ngIf="item.first">{{ item.shipment.id }}</ng-container>

  </ng-container>
  <ng-container matColumnDef="label">
    Label

      <ng-container *ngIf="item.first">
        <ng-container *ngIf="item.shipment.label | splitLabel as labels; else listNilCharacter">
          {{ label }}
        </ng-container>
      </ng-container>

  </ng-container>
  <ng-container matColumnDef="type" sticky>
    Type

      <ng-container *ngIf="item.first">{{ item.shipment.shipmentType }}</ng-container>

  </ng-container>
  <ng-container matColumnDef="visitRequest.label">
    Visit Label

      <ng-container *ngIf="item.visitRequest.label | splitLabel as labels; else listNilCharacter">
        {{ label }}
      </ng-container>

  </ng-container>
  <ng-container matColumnDef="visitRequest.pickup">
    Visit Type

      {{ item.visitRequest.pickup ? 'Pickup' : 'Delivery' }}

  </ng-container>
  <ng-container matColumnDef="visitRequest.timeWindow">
    Time Window

      <ng-container
        *ngIf="findVisitRequestTimeWindow(item.visitRequest) as timeWindow; else listNilCharacter">
        <ng-container
          *ngIf="
            timeWindow | formatHardTimeWindow: duration:timezoneOffset as tw;
            else listNilCharacter
          ">

            {{ tw.startTime }}<ng-container *ngIf="tw.startTime && tw.endTime"> - </ng-container
            >{{ tw.endTime }}
            <ng-container *ngIf="item.visitRequest.timeWindows.length - 1 as otherCount">
              +{{ otherCount }}
            </ng-container>

            {{ tw.startDate }}<ng-container *ngIf="tw.startDate && tw.endDate"> - </ng-container
            >{{ tw.endDate }}

        </ng-container>
      </ng-container>

  </ng-container>
  <ng-container matColumnDef="visitRequest.softTimeWindow">
    Soft Time Window

      <ng-container
        *ngIf="findVisitRequestTimeWindow(item.visitRequest) as timeWindow; else listNilCharacter">
        <ng-container
          *ngIf="
            timeWindow | formatSoftTimeWindow: duration:timezoneOffset as tw;
            else listNilCharacter
          ">

            {{ tw.startTime }}<ng-container *ngIf="tw.startTime && tw.endTime"> - </ng-container
            >{{ tw.endTime }}

            {{ tw.startDate }}<ng-container *ngIf="tw.startDate && tw.endDate"> - </ng-container
            >{{ tw.endDate }}

        </ng-container>
      </ng-container>

  </ng-container>
  <ng-container matColumnDef="visitRequest.duration">
    Duration (mm:ss)

      <ng-container *ngIf="item.visitRequest.duration?.seconds != null; else listNilCharacter">
        {{ secondsToFormattedTime(item.visitRequest.duration) }}
      </ng-container>

  </ng-container>
  <ng-container matColumnDef="visitRequest.cost">
    Cost

      <ng-container *ngIf="item.visitRequest.cost != null; else listNilCharacter">
        {{ item.visitRequest.cost }}
      </ng-container>

  </ng-container>
  <ng-container
    *ngFor="let demandType of demandTypes; let i = index"
    [matColumnDef]="'shipment.demands.' + i">

      Load Demand
      ({{ demandType }})

      <ng-container>
        {{ (item.shipment?.loadDemands && item.shipment.loadDemands[demandType]?.amount) || '-' }}
      </ng-container>

  </ng-container>
  <ng-container matColumnDef="menu" stickyEnd>

      <ng-container *ngIf="item.first">

          <button
            class="menu-button"
            type="button"
            mat-icon-button
            [attr.title]="editLabel(item)"
            (click)="onEdit(item.shipment.id)">
            <mat-icon>create</mat-icon>
          </button>
          <button
            class="menu-button"
            type="button"
            mat-icon-button
            [attr.title]="deleteLabel(item)"
            (click)="onDelete(item)">
            <mat-icon>delete</mat-icon>
          </button>

      </ng-container>

  </ng-container>
  <ng-template #listNilCharacter>
    -
  </ng-template>
</app-table>
<button
  mat-fab
  class="add-shipment"
  type="button"
  color=""
  title="Add shipment"
  (click)="add.emit()"
  [disabled]="changeDisabled">
  <mat-icon svgIcon="add_color"></mat-icon>
</button>
<mat-menu #hardTimeWindowsMenu="matMenu" class="time-windows-panel">
  <ng-template matMenuContent let-timeWindows="timeWindows">
    <ng-container *ngFor="let timeWindow of timeWindows.slice(1)">

          {{ tw.startTime }}<ng-container *ngIf="tw.startTime && tw.endTime"> - </ng-container
          >{{ tw.endTime }}

          {{ tw.startDate }}<ng-container *ngIf="tw.startDate && tw.endDate"> - </ng-container
          >{{ tw.endDate }}

    </ng-container>
  </ng-template>
</mat-menu>


text:
namespace expenseApp.expenses {

    interface IEmployeeScope extends ng.IScope {
        employee;
    }

    class ExpenseChildController {

        orderby: string = 'product';
        reverse: boolean = false;
        expensesTotal: number = 0.00;
        employee;

        static $inject = ['$scope', '$window', '$location', 'expenseApp.services.dataService', 'expenseApp.services.modalService'];
        constructor(private $scope: IEmployeeScope, private $window:ng.IWindowService, private $location: ng.ILocationService,
                    private dataService: expenseApp.services.DataService,
                    private modalService: expenseApp.services.ModalService) {
            //See if parent $scope has an employee that's inherited (ExpensesController)
            if (this.$scope.employee) {
                this.employee = this.$scope.employee;
                this.updateTotal(this.$scope.employee);
            //Employee not available yet so listen for availability (EmployeeExpensesController)
            } else {
                this.$scope.$on('employee', (event, employee) => {
                    this.employee = employee;
                    this.updateTotal(employee);
                });
            }
        }

        setOrder(orderby) {
            if (orderby === this.orderby) {
                this.reverse = !this.reverse;
            }
            this.orderby = orderby;
        }

        updateTotal(employee) {
            if (employee && employee.expenses) {
                var total = 0.00;
                for (var i = 0; i < employee.expenses.length; i++) {
                    var order = employee.expenses[i];
                    total += order.orderTotal;
                }
                this.expensesTotal = total;
            }
        }
    }

    angular.module('expenseApp').controller('ExpenseChildController', ExpenseChildController);

}


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

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
org.apache.log4j.jmx (Apache Log4j 1.2.17 API)
</TITLE>

<META NAME="date" CONTENT="2012-05-06">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

org.apache.log4j.jmx

Classes

AbstractDynamicMBean

Agent

AppenderDynamicMBean

HierarchyDynamicMBean

LayoutDynamicMBean

LoggerDynamicMBean


text:
/**
 * @file        test/helpers.h
 * @author      Aleksander Zdyb <a.zdyb@samsung.com>
 * @version     1.0
 * @brief       Helper functions for tests
 */

#ifndef HELPERS_H
#define HELPERS_H

#include <vector>

#include "types/PolicyKey.h"
#include "types/PolicyBucketId.h"

namespace Cynara {

namespace Helpers {

PolicyKey generatePolicyKey(const PolicyKeyFeature::ValueType &sufix = "");
PolicyBucketId generateBucketId(const PolicyBucketId &sufix = "");

template <class Collection>
Collection pickFromCollection(const Collection &original, const std::vector<unsigned> &idx) {
    Collection filtered;
    filtered.reserve(idx.size());
    for (const auto &i : idx) {
        filtered.push_back(original.at(i));
    }
    return filtered;
}

} // namespace Helpers

} // namespace Cynara

#endif // HELPERS_H


text:
<?php
/**
 * Template Name: Journal
 * This is the default basic template
 *
 * @package David James
 * @subpackage david-james
 * @since David James 1.0.1
 */

get_header();
?>
<?php include (TEMPLATEPATH . '/nav-main.php'); ?>

  <?php $queryBlog = new WP_Query(array( 'posts_per_page' => 5)); ?>
  <?php if ($queryBlog->have_posts()) : while ($queryBlog->have_posts()) : $queryBlog->the_post(); ?>

      <?php $thumbnail = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), array(1200, 350) ); ?>
      <?php if ($thumbnail[0]) : ?>
      <img class="blog-list__image" src="<?php echo $thumbnail[0]; ?>" alt="<?php echo the_title(); ?>" />
      <?php endif; ?>

written by <?php the_author(); ?> | <?php the_time('F j, Y'); ?>

<a href="<?php echo the_permalink();?>"><?php the_title(); ?>

        <?php the_excerpt(); ?>

  <?php endwhile; endif; wp_reset_postdata(); ?>

<?php get_footer(); ?>


text:
<?php

namespace Reeser\Form;

use Zend\Form\Form;
use Zend\Form\Element;

class InformeForm extends Form
{

    function __construct($name = null)
    {
        parent::__construct("mono_form");

        $this->setAttribute('method', 'post');

        // para prevenir ataques Cross Site Request Forgery
        $this->add(new Element\Csrf('csrf'));

        // tab Actividad
        $this->add(array(
            'type' => 'Reeser\Form\Fieldset\Actividad',
        ));

         // BOTONERA
         $this->add(array(
            'type' => 'Zend\Form\Element\Submit',
            'name' => 'submitbutton',
            'attributes' => array(
                'id' => 'submitbutton',
                'value' => 'Finalizar',
                'class' => 'btn btn-success pull-right'
                )
        ));
        // ./BOTONERA
    }
}

?>


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

		<title>survey</title>


text:
# Disallow Redeclaring Variables (no-redeclare)

In JavaScript, it's possible to redeclare the same variable name using `var`. This can lead to confusion as to where the variable is actually declared and initialized.

## Rule Details

This rule is aimed at eliminating variables that have multiple declarations in the same scope.

Examples of **incorrect** code for this rule:

```js
/*eslint no-redeclare: "error"*/

var a = 3;
var a = 10;
```

Examples of **correct** code for this rule:

```js
/*eslint no-redeclare: "error"*/

var a = 3;
// ...
a = 10;
```

## Options

This rule takes one optional argument, an object with a boolean property `"builtinGlobals"`. It defaults to `false`.
If set to `true`, this rule also checks redeclaration of built-in globals, such as `Object`, `Array`, `Number`...

### builtinGlobals

Examples of **incorrect** code for the `{ "builtinGlobals": true }` option:

```js
/*eslint no-redeclare: ["error", { "builtinGlobals": true }]*/

var Object = 0;
```

Examples of **incorrect** code for the `{ "builtinGlobals": true }` option and the `browser` environment:

```js
/*eslint no-redeclare: ["error", { "builtinGlobals": true }]*/
/*eslint-env browser*/

var top = 0;
```

The `browser` environment has many built-in global variables (for example, `top`). Some of built-in global variables cannot be redeclared.


text:
package cgeo.geocaching.ui.dialog;

import butterknife.ButterKnife;

import cgeo.geocaching.R;

import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TimePicker;

import java.util.Calendar;

public class TimeDialog extends DialogFragment {

    public interface TimeDialogParent {
        abstract public void setTime(final Calendar date);
    }

    private Calendar date;

    public static TimeDialog getInstance(final Calendar date) {
        final TimeDialog timeDialog = new TimeDialog();
        final Bundle args = new Bundle();
        args.putSerializable("date", date);
        timeDialog.setArguments(args);
        return timeDialog;
    }

    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NO_TITLE, 0);
        final Bundle args = getArguments();
        date = (Calendar) args.getSerializable("date");
    }

    @Override
    public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.time, container, false);

        final TimePicker picker = ButterKnife.findById(view, R.id.picker);
        picker.setCurrentHour(date.get(Calendar.HOUR_OF_DAY));
        picker.setCurrentMinute(date.get(Calendar.MINUTE));
        picker.setOnTimeChangedListener(new TimePickerListener());
        picker.setIs24HourView(DateFormat.is24HourFormat(getActivity()));
        return view;
    }

    private class TimePickerListener implements TimePicker.OnTimeChangedListener {

        @Override
        public void onTimeChanged(final TimePicker picker, final int hour, final int minutes) {
            date.set(Calendar.HOUR_OF_DAY, hour);
            date.set(Calendar.MINUTE, minutes);

            ((TimeDialogParent) getActivity()).setTime(date);

        }
    }
}


text:
import re
import string

class Filter(object):

    def __init__(self):
        self.filtered_word_list = []
        self.readIO()

    def check(self, word_input):
        res = word_input
        for e in self.filtered_word_list:
            # print(e)
            if e in word_input:
                res = res.replace(e, '*' * len(e))
        return res

    def readIO(self):
        with open('demo.txt', 'r') as f:
            s_temp = f.readline().strip()
            while s_temp != "":
                self.filtered_word_list.append(s_temp)
                s_temp = f.readline().strip()

if __name__ == "__main__":
    filter_obj = Filter()
    while True:
        word_input = input("Enter a sentence to check >")
        str_ans = filter_obj.check(word_input)
        print(str_ans)


text:
Deface::Override.new(
  virtual_path: 'spree/admin/shared/sub_menu/_configuration',
  name: 'add_zopim_settings_to_admin_configurations_menu',
  insert_bottom: '[data-hook="admin_configurations_sidebar_menu"]',
  text: '<%= configurations_sidebar_menu_item Spree.t(:zopim_settings), edit_admin_zopim_setting_path %>'
)


text:
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var o;"undefined"!=typeof window?o=window:"undefined"!=typeof global?o=global:"undefined"!=typeof self&&(o=self);var n=o;n=n.bespoke||(n.bespoke={}),n=n.plugins||(n.plugins={}),n.touch=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
var startTimer = function(duration, display) {
  var timer = duration, seconds;
  setInterval(function () {
      seconds = parseInt(timer % 60, 10);
      display.innerHTML = seconds;
      if (--timer < 0) {
          timer = duration;
      }
  }, 1000);
};

module.exports = function(options) {
  return function(deck) {
    var igniteParent = document.createElement('div'),
    igniteBar = document.createElement('div'),
    igniteTimer = document.createElement('div'),
      prop = options === 'vertical' ? 'height' : 'width',

      interval = null, countDown = null;

    igniteParent.className = 'ignite-parent';
    igniteBar.className = 'ignite-bar';
    igniteTimer.className = 'timer-bar';
    igniteParent.appendChild(igniteBar);
    igniteParent.appendChild(igniteTimer);
    deck.parent.appendChild(igniteParent);

    deck.on('activate', function(e) {
      igniteBar.innerHTML = (e.index + 1) + '/' + deck.slides.length;
      if (!interval) {
        countDown = startTimer(14, igniteTimer);
        interval = setInterval(function(e) {
            deck.next();
          }
        ,15000);
        deck.slide(0);
      }

    });
  };
};

},{}]},{},[1])
(1)
});


text:
require('./js/gridEdit');
require('./templates');


text:
"use strict";
const assert = require('assert');

/**
 * Base class for page objects.
 */
class Page {
    open(path) {
        browser.url('/' + path);
        this.openedUrl = path;
    }

    isOnPage(urlRegexp) {
        const url = browser.getUrl();
        const regexp = urlRegexp || this.openedUrl;
        return url.match(regexp);
    }

    assertIsOnPage(urlRegexp) {
        assert(this.isOnPage(urlRegexp), "Browser did not navigate to " + urlRegexp);
    }
}

module.exports = Page;


text:
echo "Generating list of Crires files without extensions."
for NAME in $(ls C*.fits); do
    #echo $NAME
    echo "${NAME%.*}"

done


text:
static const CGFloat labelPadding = 10;

// Private
@interface MWCaptionView () {
    id <MWPhoto> _photo;
    UIToolbar *_contentView;
    UILabel *_label;
    CGFloat maxHeight;
    BOOL tappedLabel;
}
@end

@implementation MWCaptionView

- (id)initWithPhoto:(id<MWPhoto>)photo {
    self = [super initWithFrame:CGRectMake(0, 0, 320, 44)]; // Random initial frame
    if (self) {
        UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc]
                                                 initWithTarget:self action:@selector(tapped:)];
        maxHeight = 75;
        // Specify that the gesture must be a single tap
        tapRecognizer.numberOfTapsRequired = 1;

//        // Add the tap gesture recognizer to the view
        [self addGestureRecognizer:tapRecognizer];
        self.userInteractionEnabled = YES;
        _photo = photo;
        if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7")) {
            // Use iOS 7 blurry goodness
        } else {
            // Transparent black with no gloss
            CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
            UIGraphicsBeginImageContext(rect.size);
            CGContextRef context = UIGraphicsGetCurrentContext();
            CGContextSetFillColorWithColor(context, [[UIColor colorWithWhite:0 alpha:0.6] CGColor]);
            CGContextFillRect(context, rect);
            UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
        }
        self.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin;
        [self setupCaption];
    }
    return self;
}

- (CGSize)sizeThatFits:(CGSize)size {
    //CGFloat maxHeight = 9999;
    if (_label.numberOfLines > 0) maxHeight = _label.font.leading*_label.numberOfLines;
    CGSize textSize;
    if ([NSString instancesRespondToSelector:@selector(boundingRectWithSize:options:attributes:context:)]) {
        textSize = [_label.text boundingRectWithSize:CGSizeMake(size.width - labelPadding*2, maxHeight)
                                             options:NSStringDrawingUsesLineFragmentOrigin
                                          attributes:@{NSFontAttributeName:_label.font}
                                             context:nil].size;
    } else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
        textSize = [_label.text sizeWithFont:_label.font
                           constrainedToSize:CGSizeMake(size.width - labelPadding*2, maxHeight)
                               lineBreakMode:_label.lineBreakMode];
#pragma clang diagnostic pop
    }
    return CGSizeMake(size.width, textSize.height + labelPadding * 2);
}

- (void)setupCaption {
    _contentView = [[UIToolbar alloc] initWithFrame:self.bounds];
    _contentView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7")) {
        // Use iOS 7 blurry goodness
        _contentView.barStyle = UIBarStyleBlackTranslucent;
        _contentView.tintColor = nil;
        _contentView.barTintColor = nil;
        _contentView.barStyle = UIBarStyleBlackTranslucent;
        [_contentView setBackgroundImage:nil forToolbarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
        self.layer.allowsGroupOpacity = NO;
        } else {
            // Transparent black with no gloss
            CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
            UIGraphicsBeginImageContext(rect.size);
            CGContextRef context = UIGraphicsGetCurrentContext();
            CGContextSetFillColorWithColor(context, [[UIColor colorWithWhite:0 alpha:0.6] CGColor]);
            CGContextFillRect(context, rect);
            UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            [_contentView setBackgroundImage:image forToolbarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
        }
    [self addSubview:_contentView];
    _label = [[UILabel alloc] initWithFrame:CGRectIntegral(CGRectMake(labelPadding, 0,
                                                       self.bounds.size.width-labelPadding*2,
                                                       self.bounds.size.height))];
    _label.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    _label.opaque = NO;
    _label.backgroundColor = [UIColor clearColor];
    if (SYSTEM_VERSION_LESS_THAN(@"6")) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
        _label.textAlignment = UITextAlignmentCenter;
        _label.lineBreakMode = UILineBreakModeWordWrap;
#pragma clang diagnostic pop
    } else {
        _label.textAlignment = NSTextAlignmentCenter;
        _label.lineBreakMode = NSLineBreakByWordWrapping;
    }

    _label.numberOfLines = 0;
    _label.textColor = [UIColor whiteColor];
    if (SYSTEM_VERSION_LESS_THAN(@"7")) {
        // Shadow on 6 and below
        _label.shadowColor = [UIColor blackColor];
        _label.shadowOffset = CGSizeMake(1, 1);
    }
    _label.font = [UIFont systemFontOfSize:10];
    if ([_photo respondsToSelector:@selector(caption)]) {
        _label.text = [_photo caption] ? [_photo caption] : @" ";
    }
    [_contentView addSubview:_label];
}

- (IBAction)tapped:(UITapGestureRecognizer *)recognizer {
    if (maxHeight == 75) {
        maxHeight = 9999;
        [self sizeToFit];
    } else {
        maxHeight = 75;
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:@"tappedCaptionNotification" object:nil];
}

@end


text:
<?php namespace MThaller\PhpCups\Exceptions;

class CommandNotDefinedException extends \Exception {

}


text:
'use strict';

/**
* Returns the first row index at which a given one-dimensional array of types can be found in a two-dimensional reference array of types (or `-1` if not found).
*
* ## Notes
*
* -   The intended use case for this function is for type dispatch (i.e., given a set of array data types, find a matching interface according the interface's accepted array data types).
* -   The function assumes that `x` is stored in row-major order.
* -   The function assumes that the number of indexed elements in `y` equals the number of columns in `x`.
* -   The function returns a row index. To convert to a linear index, multiply `strideX1` by the return value.
*
* @private
* @param {NonNegativeInteger} N - number of rows in `x` (size of first dimension)
* @param {NonNegativeInteger} M - number of columns in `x` (size of second dimension)
* @param {ArrayLikeObject} x - input two-dimensional reference array
* @param {integer} strideX1 - `x` stride length along first dimension
* @param {integer} strideX2 - `x` stride length along second dimension
* @param {NonNegativeInteger} offsetX - `x` starting index
* @param {ArrayLikeObject} y - search array
* @param {integer} strideY - `y` stride length
* @param {NonNegativeInteger} offsetY - `y` starting index
* @returns {integer} row index (if found) and `-1` otherwise
*
* @example
* // Define a reference array to search:
* var types = [
*     'float64', 'float64', 'float64',
*     'float32', 'float32', 'float32',
*     'uint32', 'uint32', 'float64',
*     'int32', 'int32', 'float64',
*     'uint16', 'uint16', 'float64',
*     'int16', 'int16', 'float64',
*     'uint8', 'uint8', 'float64',
*     'int8', 'int8', 'float64'
* ];
*
* // Define reference array dimensions:
* var N = 8; // rows
* var M = 3; // columns
*
* // Define a search array:
* y1 = [
*     'float32', 'float32', 'float32',
* ];
*
* // Find the list of types:
* var r1 = indexOfTypes( N, M, types, M, 1, 0, y1, 1, 0 );
* // returns 1
*
// Define a search array:
* y2 = [
*     'float32', 'float32', 'float64',
* ];
*
* // Find the list of types:
* var r2 = indexOfTypes( N, M, types, M, 1, 0, y2, 1, 0 );
* // returns -1
*/
function indexOfTypes( N, M, x, strideX1, strideX2, offsetX, y, strideY, offsetY ) { // eslint-disable-line max-len
	var ix;
	var iy;
	var i;
	var j;

	// Search for the first row which matches `y`...
	ix = offsetX;
	for ( i = 0; i < N; i++ ) {
		iy = offsetY;
		for ( j = 0; j < M; j++ ) {
			if ( x[ ix+(j*strideX2) ] !== y[ iy ] ) {
				break;
			}
			iy += strideY;
		}
		// If we successfully iterated over all columns, then that means we've found a match...
		if ( j === M ) {
			return i;
		}
		ix += strideX1;
	}
	return -1;
}

// EXPORTS //

module.exports = indexOfTypes;


text:
@interface ttLoginRegisterVc : UIViewController

@end