text:
import logging
import re

from collections import namedtuple, MutableSet
from itertools import combinations

from mongo_connector import errors
from mongo_connector import compat

LOG = logging.getLogger(__name__)

_Namespace = namedtuple('Namespace', ['dest_name', 'source_name', 'gridfs',
                                      'include_fields', 'exclude_fields'])

class Namespace(_Namespace):
    def __new__(cls, dest_name=None, source_name=None, gridfs=False,
                include_fields=None, exclude_fields=None):
        include_fields = set(include_fields or [])
        exclude_fields = set(exclude_fields or [])
        return super(Namespace, cls).__new__(
            cls, dest_name, source_name, gridfs, include_fields,
            exclude_fields)

    def with_options(self, **kwargs):
        new_options = dict(
            dest_name=self.dest_name, source_name=self.source_name,
            gridfs=self.gridfs, include_fields=self.include_fields,
            exclude_fields=self.exclude_fields)
        new_options.update(kwargs)
        return Namespace(**new_options)

class RegexSet(MutableSet):
    """Set that stores both plain strings and RegexObjects.

    Membership query results are cached so that repeated lookups of the same
    string are fast.
    """
    def __init__(self, regexes, strings):
        self._regexes = set(regexes)
        self._plain = set(strings)
        self._not_found_cache = set()

    def __contains__(self, item):
        if item in self._not_found_cache:
            return False
        if item in self._plain:
            return True
        if item in self._regexes:
            return True
        for regex in self._regexes:
            if regex.match(item):
                self._plain.add(item)
                return True
        self._not_found_cache.add(item)
        return False

    def __iter__(self):
        for regex in self._regexes:
            yield regex
        for string in self._plain:
            yield string

    def __len__(self):
        return len(self._regexes) + len(self._plain)

    def add(self, string):
        self._plain.add(string)
        self._not_found_cache.discard(string)

    def discard(self, string):
        self._plain.discard(string)

    @staticmethod
    def from_namespaces(namespaces):
        regexes = set()
        strings = set()
        for ns in namespaces:
            if '*' in ns:
                regexes.add(namespace_to_regex(ns))
            else:
                strings.add(ns)
        return RegexSet(regexes, strings)

class NamespaceConfig(object):
    """Manages included and excluded namespaces.
    """
    def __init__(self, namespace_set=None, ex_namespace_set=None,
                 gridfs_set=None, dest_mapping=None, namespace_options=None,
                 include_fields=None, exclude_fields=None):
        # A mapping from non-wildcard source namespaces to a MappedNamespace
        # containing the non-wildcard target name.
        self._plain = {}
        # A mapping from non-wildcard target namespaces to their
        # corresponding non-wildcard source namespace. Namespaces have a
        # one-to-one relationship with the target system, meaning multiple
        # source namespaces cannot be merged into a single namespace in the
        # target.
        self._reverse_plain = {}
        # A mapping from non-wildcard source database names to the set of
        # non-wildcard target database names.
        self._plain_db = {}
        # A list of (re.RegexObject, MappedNamespace) tuples. regex_map maps
        # wildcard source namespaces to a MappedNamespace containing the
        # wildcard target name. When a namespace is matched, an entry is
        # created in `self.plain` for faster subsequent lookups.
        self._regex_map = []

        # Fields to include or exclude from all namespaces
        self._include_fields = validate_include_fields(include_fields)
        self._exclude_fields = validate_exclude_fields(exclude_fields)

        # Add each included namespace. Namespaces have a one-to-one
        # relationship to the target system, meaning multiple source
        # namespaces cannot be merged into a single namespace in the target.
        ex_namespace_set, namespaces = validate_namespace_options(
            namespace_set=namespace_set,
            ex_namespace_set=ex_namespace_set,
            gridfs_set=gridfs_set,
            dest_mapping=dest_mapping,
            namespace_options=namespace_options,
            include_fields=include_fields,
            exclude_fields=exclude_fields)

        # The set of, possibly wildcard, namespaces to exclude.
        self._ex_namespace_set = RegexSet.from_namespaces(ex_namespace_set)

        for namespace in namespaces:
            self._register_namespace_and_command(namespace)

    def _register_namespace_and_command(self, namespace):
        """Add a Namespace and the corresponding command namespace."""
        self._add_namespace(namespace)
        # Add the namespace for commands on this database
        cmd_name = namespace.source_name.split('.', 1)[0] + '.$cmd'
        dest_cmd_name = namespace.dest_name.split('.', 1)[0] + '.$cmd'
        self._add_namespace(Namespace(dest_name=dest_cmd_name,
                                      source_name=cmd_name))

    def _add_namespace(self, namespace):
        """Add an included and possibly renamed Namespace."""
        src_name = namespace.source_name
        if "*" in src_name:
            self._regex_map.append((namespace_to_regex(src_name),
                                    namespace))
        else:
            self._add_plain_namespace(namespace)

    def _add_plain_namespace(self, namespace):
        """Add an included and possibly renamed non-wildcard Namespace."""
        src_name = namespace.source_name
        target_name = namespace.dest_name
        src_names = self._reverse_plain.setdefault(target_name, set())
        src_names.add(src_name)
        if len(src_names) > 1:
            # Another source namespace is already mapped to this target
            existing_src = (src_names - set([src_name])).pop()
            raise errors.InvalidConfiguration(
                "Multiple namespaces cannot be combined into one target "
                "namespace. Trying to map '%s' to '%s' but there already "
                "exists a mapping from '%s' to '%s'" %
                (src_name, target_name, existing_src, target_name))

        self._plain[src_name] = namespace
        src_db, _ = src_name.split(".", 1)
        target_db, _ = target_name.split(".", 1)
        self._plain_db.setdefault(src_db, set()).add(target_db)

    def lookup(self, plain_src_ns):
        """Given a plain source namespace, return the corresponding Namespace
        object, or None if it is not included.
        """
        # Ignore the namespace if it is excluded.
        if plain_src_ns in self._ex_namespace_set:
            return None
        # Include all namespaces if there are no included namespaces.
        if not self._regex_map and not self._plain:
            return Namespace(dest_name=plain_src_ns, source_name=plain_src_ns,
                             include_fields=self._include_fields,
                             exclude_fields=self._exclude_fields)
        # First, search for the namespace in the plain namespaces.
        try:
            return self._plain[plain_src_ns]
        except KeyError:
            # Search for the namespace in the wildcard namespaces.
            for regex, namespace in self._regex_map:
                new_name = match_replace_regex(regex, plain_src_ns,
                                               namespace.dest_name)
                if not new_name:
                    continue
                # Save the new target Namespace in the plain namespaces so
                # future lookups are fast.
                new_namespace = namespace.with_options(
                    dest_name=new_name, source_name=plain_src_ns)
                self._add_plain_namespace(new_namespace)
                return new_namespace

        # Save the not included namespace to the excluded namespaces so
        # that future lookups of the same namespace are fast.
        self._ex_namespace_set.add(plain_src_ns)
        return None

    def map_namespace(self, plain_src_ns):
        """Given a plain source namespace, return the corresponding plain
        target namespace, or None if it is not included.
        """
        namespace = self.lookup(plain_src_ns)
        if namespace:
            return namespace.dest_name
        return None

    def gridfs_namespace(self, plain_src_ns):
        """Given a plain source namespace, return the corresponding plain
        target namespace if this namespace is a gridfs collection.
        """
        namespace = self.lookup(plain_src_ns)
        if namespace and namespace.gridfs:
            return namespace.dest_name
        return None

    def unmap_namespace(self, plain_target_ns):
        """Given a plain target namespace, return the corresponding source
        namespace.
        """
        # Return the same namespace if there are no included namespaces.
        if not self._regex_map and not self._plain:
            return plain_target_ns

        src_name_set = self._reverse_plain.get(plain_target_ns)
        if src_name_set:
            # Return the first (and only) item in the set
            for src_name in src_name_set:
                return src_name
        # The target namespace could also exist in the wildcard namespaces
        for _, namespace in self._regex_map:
            original_name = match_replace_regex(
                namespace_to_regex(namespace.dest_name), plain_target_ns,
                namespace.source_name)
            if original_name:
                return original_name
        return None

    def map_db(self, plain_src_db):
        """Given a plain source database, return the list of target databases.

        Individual collections in a database can be mapped to different
        target databases, so map_db can return multiple databases. This
        function must return all target database names so we make the
        following restrictions on wildcards:
        1) A wildcard appearing in the source database name must also appear
        in the target database name, eg "db*.col" => "new_db_*.new_col".
        2) A wildcard appearing in the source collection name must also appear
        in the target collection name, eg "db.col*" => "new_db.new_col*".

        This is used by the CommandHelper for the dropDatabase command.
        """
        if not self._regex_map and not self._plain:
            return [plain_src_db]
        # Lookup this namespace to seed the plain_db dictionary
        self.lookup(plain_src_db + '.$cmd')
        return list(self._plain_db.get(plain_src_db, set()))

    def projection(self, plain_src_name):
        """Return the projection for the given source namespace."""
        mapped = self.lookup(plain_src_name)
        if not mapped:
            return None
        fields = mapped.include_fields or mapped.exclude_fields
        if fields:
            include = 1 if mapped.include_fields else 0
            return dict((field, include) for field in fields)
        return None

    def get_included_databases(self):
        """Return the databases we want to include, or empty list for all.
        """
        databases = set()
        databases.update(self._plain_db.keys())

        for _, namespace in self._regex_map:
            database_name, _ = namespace.source_name.split('.', 1)
            if '*' in database_name:
                return []
            databases.add(database_name)

        return list(databases)

def _character_matches(name1, name2):
    """Yield the number of characters that match the beginning of each string.
    """
    if name1[0] == '*':
        for i in range(len(name2) + 1):
            yield 1, i
    if name2[0] == '*':
        for i in range(len(name1) + 1):
            yield i, 1
    if name1[0] == name2[0]:
        yield 1, 1

def wildcards_overlap(name1, name2):
    """Return true if two wildcard patterns can match the same string."""
    if not name1 and not name2:
        return True
    if not name1 or not name2:
        return False
    for matched1, matched2 in _character_matches(name1, name2):
        if wildcards_overlap(name1[matched1:], name2[matched2:]):
            return True
    return False

def _validate_namespace(name):
    """Validate a MongoDB namespace."""
    if name.find('.', 1, len(name) - 1) < 0:
        raise errors.InvalidConfiguration(
            "Invalid MongoDB namespace '%s'!" % (name,))

def _validate_namespaces(namespaces):
    """Validate wildcards and renaming in namespaces.

    Target namespaces should have the same number of wildcards as the source.
    No target namespaces overlap exactly with each other. Logs a warning
    when wildcard namespaces have a chance of overlapping.
    """
    for source, namespace in namespaces.items():
        target = namespace.dest_name
        _validate_namespace(source)
        _validate_namespace(target)
        if source.count("*") > 1 or target.count("*") > 1:
            raise errors.InvalidConfiguration(
                "The namespace mapping from '%s' to '%s' cannot contain more "
                "than one '*' character." % (source, target))
        if source.count("*") != target.count("*"):
            raise errors.InvalidConfiguration(
                "The namespace mapping from '%s' to '%s' must contain the "
                "same number of '*' characters." % (source, target))
        if '*' not in source:
            continue
        # Make sure that wildcards are not moved from database name to
        # collection name or vice versa, eg "db*.foo" => "db.foo_*"
        if wildcard_in_db(source) and not wildcard_in_db(target) or (
                    not wildcard_in_db(source) and wildcard_in_db(target)):
            raise errors.InvalidConfiguration(
                "The namespace mapping from '%s' to '%s' is invalid. A '*' "
                "that appears in the source database name must also appear"
                "in the target database name. A '*' that appears in the "
                "source collection name must also appear in the target "
                "collection name" % (source, target))

    for source1, source2 in combinations(namespaces.keys(), 2):
        if wildcards_overlap(source1, source2):
            LOG.warning('Namespaces "%s" and "%s" may match the '
                        'same source namespace.', source1, source2)
        target1 = namespaces[source1].dest_name
        target2 = namespaces[source2].dest_name
        if target1 == target2:
            raise errors.InvalidConfiguration(
                "Multiple namespaces cannot be combined into one target "
                "namespace. Trying to map '%s' to '%s' but '%s' already "
                "corresponds to '%s' in the target system." %
                (source2, target2, source1, target1))
        if wildcards_overlap(target1, target2):
            LOG.warning(
                "Multiple namespaces cannot be combined into one target "
                "namespace. Mapping from '%s' to '%s' might overlap "
                "with mapping from '%s' to '%s'." %
                (source2, target2, source1, target1))

def _merge_namespace_options(namespace_set=None, ex_namespace_set=None,
                             gridfs_set=None, dest_mapping=None,
                             namespace_options=None,
                             include_fields=None, exclude_fields=None):
    """Merges namespaces options together.

    The first is the set of excluded namespaces and the second is a mapping
    from source namespace to Namespace instances.
    """
    namespace_set = set(namespace_set or [])
    ex_namespace_set = set(ex_namespace_set or [])
    gridfs_set = set(gridfs_set or [])
    dest_mapping = dest_mapping or {}
    namespace_options = namespace_options or {}
    include_fields = set(include_fields or [])
    exclude_fields = set(exclude_fields or [])
    namespaces = {}

    for source_name, options_or_str in namespace_options.items():
        if isinstance(options_or_str, dict):
            namespace_set.add(source_name)
            if options_or_str.get('gridfs'):
                gridfs_set.add(source_name)
            namespaces[source_name] = Namespace(
                dest_name=options_or_str.get('rename'),
                include_fields=options_or_str.get('includeFields'),
                exclude_fields=options_or_str.get('excludeFields'),
                gridfs=options_or_str.get('gridfs', False))
        elif compat.is_string(options_or_str):
            namespace_set.add(source_name)
            namespaces[source_name] = Namespace(dest_name=options_or_str)
        elif options_or_str:
            namespace_set.add(source_name)
        else:
            ex_namespace_set.add(source_name)

    # Add namespaces that are renamed but not in namespace_options
    for source_name, target_name in dest_mapping.items():
        namespaces[source_name] = namespaces.get(
            source_name, Namespace()).with_options(dest_name=target_name)

    # Add namespaces that are included but not in namespace_options
    for included_name in namespace_set:
        if included_name not in namespaces:
            namespaces[included_name] = Namespace()

    # Add namespaces that are excluded but not in namespace_options
    for gridfs_name in gridfs_set:
        namespaces[gridfs_name] = namespaces.get(
            gridfs_name, Namespace()).with_options(gridfs=True)

    # Add source, destination name, and globally included and excluded fields
    for included_name in namespaces:
        namespace = namespaces[included_name]
        namespace = namespace.with_options(
            source_name=included_name,
            include_fields=validate_include_fields(include_fields,
                                                   namespace.include_fields),
            exclude_fields=validate_exclude_fields(exclude_fields,
                                                   namespace.exclude_fields))
        # The default destination name is the same as the source.
        if not namespace.dest_name:
            namespace = namespace.with_options(dest_name=included_name)
        namespaces[included_name] = namespace

    return ex_namespace_set, namespaces

def validate_namespace_options(namespace_set=None, ex_namespace_set=None,
                               gridfs_set=None, dest_mapping=None,
                               namespace_options=None,
                               include_fields=None, exclude_fields=None):
    ex_namespace_set, namespaces = _merge_namespace_options(
        namespace_set=namespace_set,
        ex_namespace_set=ex_namespace_set,
        gridfs_set=gridfs_set,
        dest_mapping=dest_mapping,
        namespace_options=namespace_options,
        include_fields=include_fields,
        exclude_fields=exclude_fields)

    for excluded_name in ex_namespace_set:
        _validate_namespace(excluded_name)
        if excluded_name in namespaces:
            raise errors.InvalidConfiguration(
                "Cannot include namespace '%s', it is already excluded." %
                (excluded_name,))

    for namespace in namespaces.values():
        if namespace.include_fields and namespace.exclude_fields:
            raise errors.InvalidConfiguration(
                "Cannot mix include fields and exclude fields in "
                "namespace mapping for: '%s'" % (namespace.source_name,))

        if namespace.gridfs and namespace.dest_name != namespace.source_name:
            raise errors.InvalidConfiguration(
                "GridFS namespaces cannot be renamed: '%s'" % (
                    namespace.source_name,))

    _validate_namespaces(namespaces)
    return ex_namespace_set, namespaces.values()

def match_replace_regex(regex, src_namespace, dest_namespace):
    """Return the new mapped namespace if the src_namespace matches the
    regex."""
    match = regex.match(src_namespace)
    if match:
        return dest_namespace.replace('*', match.group(1))
    return None

def wildcard_in_db(namespace):
    """Return True if a wildcard character appears in the database name."""
    return namespace.find('*') < namespace.find('.')

def namespace_to_regex(namespace):
    """Create a RegexObject from a wildcard namespace."""
    db_name, coll_name = namespace.split('.', 1)
    # A database name cannot contain a '.' character
    db_regex = re.escape(db_name).replace('\*', '([^.]*)')
    # But a collection name can.
    coll_regex = re.escape(coll_name).replace('\*', '(.*)')
    return re.compile(r'\A' + db_regex + r'\.' + coll_regex + r'\Z')

def validate_include_fields(include_fields, namespace_fields=None):
    include_fields = set(include_fields or [])
    namespace_fields = set(namespace_fields or [])
    merged = include_fields | namespace_fields
    if merged:
        merged.add('_id')
    return merged

def validate_exclude_fields(exclude_fields, namespace_fields=None):
    exclude_fields = set(exclude_fields or [])
    namespace_fields = set(namespace_fields or [])
    merged = exclude_fields | namespace_fields
    if '_id' in merged:
        LOG.warning("Cannot exclude '_id' field, ignoring")
        merged.discard('_id')
    return merged


text:
using System.Collections.Generic;

namespace Zags.DataAccess
{
    public class PaginatedResponse<T>
    {
        public PaginationInfo PaginationInfo { get; set; }
        public string ErrorMessage { get; set; }
        public IEnumerable<T> Items { get; set; }

        public SortingInfo SortingInfo { get; set; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package util.misc;

import gui.GUIMain;
import util.Timer;
import util.Utils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

/**
 * Created by Palehorse68 on 2/22/2016.
 */
public class Race extends Thread {

    private int time;
    private Timer raceTime, voteTime;
    private boolean isDone, votingDone;
    private String channel;

    public boolean isDone() {
        return isDone;
    }

    public boolean votingDone() {
    	return votingDone;
    }

    private ArrayList<Guess> guesses;

    public Race(String channel, int time) {
        this.channel = channel;
        isDone = votingDone = false;
        this.time = time;
        this.guesses = new ArrayList<Guess>();

    }

    public synchronized void addGuess(String user, String message) {
    	String messageGuess = findGuess(message);
    	if (messageGuess.equals("") || messageGuess == null) return;

    	if (userHasVoted(user)){
    		Guess oldGuess = getUserGuess(user);
    		oldGuess.decrease(user);
    	}

    	Guess guess = getGuess(messageGuess);
    	if (guess != null){
    		//That guess already exists, just add the user
    		guess.increment(user);
    	} else {
    		//This is the first person to guess the number, so create it and add the user
	    	Guess newGuess = new Guess(messageGuess, Integer.parseInt(messageGuess));
	    	newGuess.increment(user);
	    	guesses.add(newGuess);
    	}
    }

    @Override
    public synchronized void start() {
        raceTime = new Timer(Utils.handleInt(60));
        voteTime = new Timer(Utils.handleInt(time));
        printStart();
        super.start();
    }

    @Override
    public void run() {

    	while (!GUIMain.shutDown && raceTime.isRunning()) {
            try {
                Thread.sleep(20);
            } catch (Exception ignored) {
            }
            if (!voteTime.isRunning() && !votingDone()){
            	votingDone = true;
                printVoteOver();
            }
        }
        if (!isDone) {
            isDone = true;
        }
    }

    @Override
    public void interrupt() {
        isDone = true;
        super.interrupt();
    }

    /**
     * Gets an Option that the user is in, otherwise null.
     *
     * @param guess The number to check.
     * @return The option they voted for, otherwise null.
     */
    private synchronized Guess getGuess(String guess) {
        for (Guess o : guesses) {
            if (o.name.equals(guess)) return o;
        }
        return null;
    }

    private synchronized Guess getUserGuess(String user) {
    	for (Guess o : guesses){
    		for (String guessUser : o.voters){
    			if (guessUser.equalsIgnoreCase(user)) return o;
    		}
    	}

    	return null;
    }

    private synchronized boolean userHasVoted(String user){
    	for (Guess o : guesses) {
    		for (String voter : o.voters) {
                if (voter.equalsIgnoreCase(user)) {
                    return true;
                }
            }
    	}

    	return false;
    }

    class Guess implements Comparable<Guess> {
        String name;
        ArrayList<String> voters;
        int count = 0;
        int compare;

        Guess(String name, int compareIndex) {
            this.name = name;
            compare = compareIndex;
            voters = new ArrayList<>();
        }

        void increment(String name) {
            count++;
            voters.add(name);
        }

        void decrease(String name) {
            count--;
            voters.remove(name);
        }

        @Override
        public int compareTo(Guess o) {
            if (o.count > this.count) {
                return -1;
            } else if (o.count == this.count) {
                return 0;
            } else {
                return 1;
            }
        }
    }

    public void printStart() {
        GUIMain.currentSettings.accountManager.getBot().sendMessage(channel, "/me A wild Dampe race has appeared! Everybody has " +
         time + " seconds to enter a guess! Any 2-digit number you type will be registered!");
    }

    public synchronized void printVoteOver() {
    	ArrayList<Guess> results = getSortedOptions();
    	if (results.isEmpty()){
    		GUIMain.currentSettings.accountManager.getBot().sendMessage(channel, "/me Voting is now closed! Nobody guessed. Dampe wins. WinWaker");
    	} else {
	    	Guess most = results.get(0);
	    	GUIMain.currentSettings.accountManager.getBot().sendMessage(channel, "/me Voting is now closed! The most common guess was " +
	    	most.name + " with " + most.count + (most.count > 1 ? " guesses." : " guess."));
    	}
    }

    public void judgeRace(String result){
    	if (!votingDone()) {
    		votingDone = false;
    		printVoteOver();
    	}

    	Guess correctGuess = getGuess(result);
    	String verb = "were", noun = "winners";

    	if (correctGuess == null || correctGuess.count == 0) {
    		GUIMain.currentSettings.accountManager.getBot().sendMessage(channel, "/me The race finished in " + result + " seconds. Nobody guessed correctly. BibleThump");
    	} else {
    		StringBuilder sb = new StringBuilder();
    		if (correctGuess.count == 1) {
    			verb = "was";
    			noun = "winner";
    		}
    		sb.append("/me The race finished in " + result + " seconds. There " + verb +" " + correctGuess.count + " " + noun + ". " + correctGuess.voters.toString());
    		GUIMain.currentSettings.accountManager.getBot().sendMessage(channel, sb.toString());
    	}

    }

    private ArrayList<Guess> getSortedOptions() {
        ArrayList<Guess> results = new ArrayList<>();
        guesses.forEach(results::add);
        Collections.sort(results);//sort into ascending based on votes
        Collections.reverse(results);//make it descending
        return results;
    }

    private String findGuess(String message){
    	String toReturn = "";
    	if (message == null || message.isEmpty()) return toReturn;
    	//This pattern attempts to capture 2 digit numbers that fall at the beginning of a line,
    	//the end of a line, or surround by space on either side.
    	//Matches: 33, My guess is 33, My guess is 33 and I'm going to win
    	//Fails: 123, 12:45, 33.17, My guess is 33., My guess is 33.75
    	Pattern p = Pattern.compile("(?:^| )(\\d{2})(?:$| )");
    	Matcher m = p.matcher(message);
    	if (m.find()){
    		toReturn = m.group();
    	}

    	return toReturn.trim();

    }
}


text:
package templates

import (
	"html/template"
	"sync"
)

//go:generate qtc

const (
	fortuneHTML = `<!DOCTYPE html>

<title>Fortunes</title>

id
message

{{range .}}

{{.ID}}
{{.Message}}

{{end}}

`
)

var (
	// FortuneTemplate ...
	FortuneTemplate = template.Must(template.New("fortune.html").Parse(fortuneHTML))
)

// Fortune struct
type Fortune struct {
	ID      int    `json:"id,omitempty"`
	Message string `json:"message,omitempty"`
}

// FortunesPool *sync.Pool
var FortunesPool *sync.Pool

// InitFortunesPool ()
func InitFortunesPool() {
	FortunesPool = &sync.Pool{
		New: func() interface{} {
			return make([]Fortune, 0, 16)
		},
	}
}


text:
#pragma once

#include <typeinfo>

namespace Patterns
{
	// Базовый класс-метка для глобальных объектов
	class GlobalObjectBase
	{
	protected:
		size_t m_hash_code;

	public:
		virtual ~GlobalObjectBase() {}

		size_t GetTypeHashCode() const { return m_hash_code; }
		virtual void RecalcHashCode() { m_hash_code = typeid(*this).hash_code(); }
	};

	// Базовый класс для объектов, которым нужно
	//	обновление Update(float dt)
	//	инициализация/деинициализация - Init/Release
	class GameGlobalObject : public GlobalObjectBase
	{
	public:
		virtual ~GameGlobalObject() {}

		virtual void Update(float dt) {}
		virtual void Init() {}
		virtual void Release() {}
	};

} // Patterns


text:
namespace pmlc::rt::llvm {
namespace {

class Runtime final : public pmlc::rt::Runtime {
public:
  std::size_t deviceCount() const noexcept final { return 1; }
  std::shared_ptr<pmlc::rt::Device> device(std::size_t idx) {
    if (idx) {
      throw std::out_of_range{"Invalid device index"};
    }
    return dev;
  }

private:
  std::shared_ptr<Device> dev = std::make_shared<Device>();
};

} // namespace

extern void registerBuiltins();
extern void registerOpenMP();

void registerRuntime() {
  registerBuiltins();
  registerOpenMP();
  registerRuntime("llvm_cpu", std::make_shared<Runtime>());
}

} // namespace pmlc::rt::llvm


text:
% Author:  Giovanni Di Liberto
% Date:    19/01/2015
% Project: Vocoding Project
%
% This code splits the raw eeg into trials and conditions

clc
close all
clear all

subj = 'DDtask';

currentTrialNumber = 0;

for fileIdx = 1:2
    % Reading raw .bdf file
    fileName = ['/media/diliberg/System/WS15/eeg/' subj '/original/' subj num2str(fileIdx) '.bdf'];
    [EEG_raw, trigs] = Read_bdf(fileName);

    % Getting triggers
%     trigs2 = trigs;
    trigs=trigs-min(trigs);
    trigs(trigs>256) = trigs(trigs>256)-min(trigs(trigs>256));
    trigs(trigs>256) = trigs(trigs>256)-min(trigs(trigs>256));

    % Trick to add trial numbers
	x=diff(trigs);
%     x(x==254);
%     trigs(find(x==254)) = [222,222,1:100]; % The first two trials were repeated
    trialsIdxStart = find(x==254);
%     if fileIdx == 1
%         trialsIdxStart = trialsIdxStart(3:end); % The first two trials were repeated
%     end
    trialsIdxEnd = [trialsIdxStart(2:end)-8,length(trigs)];
    trialsIdxEnd - trialsIdxStart; % This should give us the trial length.. why is the variability so bad? Anyway, We trust the 254 as trial start, that should be guaranteed

    % For each trial Slow
    trialCount = 1;
    for i = 1:length(trialsIdxStart);
        trialCount

        startSample = trialsIdxStart(i);
        endSample = trialsIdxEnd(i);

        eeg = EEG_raw(:,startSample:endSample);
        localTrig = trigs(:,startSample:endSample);

        % Channel swap (if needed)
%          eeg(135,:) = eeg(129,:);
%          eeg(136,:) = eeg(130,:);

        if fileIdx == 1
            outputFileName = ['/media/diliberg/System/WS15/eeg/' subj '/' subj '_noTask_' num2str(trialCount) '.mat'];
        elseif fileIdx == 2
            outputFileName = ['/media/diliberg/System/WS15/eeg/' subj '/' subj '_task_' num2str(trialCount) '.mat'];
        end
        save(outputFileName, 'eeg', 'localTrig');

        trialCount = trialCount + 1;
    end
end


text:
//
// Copyright (c) Microsoft Corporation.  All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

/// <reference path='services.ts' />

var debugObjectHost = (<any>this);

module ts {
    export interface ScriptSnapshotShim {
        /** Gets a portion of the script snapshot specified by [start, end). */
        getText(start: number, end: number): string;

        /** Gets the length of this script snapshot. */
        getLength(): number;

        /**
         * Returns a JSON-encoded value of the type:
         *   { span: { start: number; length: number }; newLength: number }
         *
         * Or undefined value if there was no change.
         */
        getChangeRange(oldSnapshot: ScriptSnapshotShim): string;
    }

    export interface Logger {
        log(s: string): void;
        trace(s: string): void;
        error(s: string): void;
    }

    /** Public interface of the host of a language service shim instance.*/
    export interface LanguageServiceShimHost extends Logger {
        getCompilationSettings(): string;

        /** Returns a JSON-encoded value of the type: string[] */
        getScriptFileNames(): string;
        getScriptVersion(fileName: string): string;
        getScriptSnapshot(fileName: string): ScriptSnapshotShim;
        getLocalizedDiagnosticMessages(): string;
        getCancellationToken(): CancellationToken;
        getCurrentDirectory(): string;
        getDefaultLibFileName(options: string): string;
        getNewLine?(): string;
    }

    ///
    /// Pre-processing
    ///
    // Note: This is being using by the host (VS) and is marshaled back and forth.
    // When changing this make sure the changes are reflected in the managed side as well
    export interface IFileReference {
        path: string;
        position: number;
        length: number;
    }

    /** Public interface of a language service instance shim. */
    export interface ShimFactory {
        registerShim(shim: Shim): void;
        unregisterShim(shim: Shim): void;
    }

    export interface Shim {
        dispose(dummy: any): void;
    }

    export interface LanguageServiceShim extends Shim {
        languageService: LanguageService;

        dispose(dummy: any): void;

        refresh(throwOnError: boolean): void;

        cleanupSemanticCache(): void;

        getSyntacticDiagnostics(fileName: string): string;
        getSemanticDiagnostics(fileName: string): string;
        getCompilerOptionsDiagnostics(): string;

        getSyntacticClassifications(fileName: string, start: number, length: number): string;
        getSemanticClassifications(fileName: string, start: number, length: number): string;

        getCompletionsAtPosition(fileName: string, position: number): string;
        getCompletionEntryDetails(fileName: string, position: number, entryName: string): string;

        getQuickInfoAtPosition(fileName: string, position: number): string;

        getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): string;
        getBreakpointStatementAtPosition(fileName: string, position: number): string;

        getSignatureHelpItems(fileName: string, position: number): string;

        /**
         * Returns a JSON-encoded value of the type:
         * { canRename: boolean, localizedErrorMessage: string, displayName: string, fullDisplayName: string, kind: string, kindModifiers: string, triggerSpan: { start; length } }
         */
        getRenameInfo(fileName: string, position: number): string;

        /**
         * Returns a JSON-encoded value of the type:
         * { fileName: string, textSpan: { start: number, length: number } }[]
         */
        findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): string;

        /**
         * Returns a JSON-encoded value of the type:
         * { fileName: string; textSpan: { start: number; length: number}; kind: string; name: string; containerKind: string; containerName: string }
         *
         * Or undefined value if no definition can be found.
         */
        getDefinitionAtPosition(fileName: string, position: number): string;

        /**
         * Returns a JSON-encoded value of the type:
         * { fileName: string; textSpan: { start: number; length: number}; isWriteAccess: boolean }[]
         */
        getReferencesAtPosition(fileName: string, position: number): string;

        /**
         * Returns a JSON-encoded value of the type:
         * { definition: <encoded>; references: <encoded>[] }[]
         */
        findReferences(fileName: string, position: number): string;

        /**
         * Returns a JSON-encoded value of the type:
         * { fileName: string; textSpan: { start: number; length: number}; isWriteAccess: boolean }[]
         */
        getOccurrencesAtPosition(fileName: string, position: number): string;

        /**
         * Returns a JSON-encoded value of the type:
         * { name: string; kind: string; kindModifiers: string; containerName: string; containerKind: string; matchKind: string; fileName: string; textSpan: { start: number; length: number}; } [] = [];
         */
        getNavigateToItems(searchValue: string, maxResultCount?: number): string;

        /**
         * Returns a JSON-encoded value of the type:
         * { text: string; kind: string; kindModifiers: string; bolded: boolean; grayed: boolean; indent: number; spans: { start: number; length: number; }[]; childItems: <recursive use of this type>[] } [] = [];
         */
        getNavigationBarItems(fileName: string): string;

        /**
         * Returns a JSON-encoded value of the type:
         * { textSpan: { start: number, length: number }; hintSpan: { start: number, length: number }; bannerText: string; autoCollapse: boolean } [] = [];
         */
        getOutliningSpans(fileName: string): string;

        getTodoComments(fileName: string, todoCommentDescriptors: string): string;

        getBraceMatchingAtPosition(fileName: string, position: number): string;
        getIndentationAtPosition(fileName: string, position: number, options: string/*Services.EditorOptions*/): string;

        getFormattingEditsForRange(fileName: string, start: number, end: number, options: string/*Services.FormatCodeOptions*/): string;
        getFormattingEditsForDocument(fileName: string, options: string/*Services.FormatCodeOptions*/): string;
        getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: string/*Services.FormatCodeOptions*/): string;

        getEmitOutput(fileName: string): string;
    }

    export interface ClassifierShim extends Shim {
        getClassificationsForLine(text: string, lexState: EndOfLineState, syntacticClassifierAbsent?: boolean): string;
    }

    export interface CoreServicesShim extends Shim {
        getPreProcessedFileInfo(fileName: string, sourceText: IScriptSnapshot): string;
        getDefaultCompilationSettings(): string;
    }

    function logInternalError(logger: Logger, err: Error) {
        logger.log("*INTERNAL ERROR* - Exception in typescript services: " + err.message);
    }

    class ScriptSnapshotShimAdapter implements IScriptSnapshot {
        private lineStartPositions: number[] = null;

        constructor(private scriptSnapshotShim: ScriptSnapshotShim) {
        }

        public getText(start: number, end: number): string {
            return this.scriptSnapshotShim.getText(start, end);
        }

        public getLength(): number {
            return this.scriptSnapshotShim.getLength();
        }

        public getChangeRange(oldSnapshot: IScriptSnapshot): TextChangeRange {
            var oldSnapshotShim = <ScriptSnapshotShimAdapter>oldSnapshot;
            var encoded = this.scriptSnapshotShim.getChangeRange(oldSnapshotShim.scriptSnapshotShim);
            if (encoded == null) {
                return null;
            }

            var decoded: { span: { start: number; length: number; }; newLength: number; } = JSON.parse(encoded);
            return createTextChangeRange(
                createTextSpan(decoded.span.start, decoded.span.length), decoded.newLength);
        }
    }

    export class LanguageServiceShimHostAdapter implements LanguageServiceHost {
        private files: string[];

        constructor(private shimHost: LanguageServiceShimHost) {
        }

        public log(s: string): void {
            this.shimHost.log(s);
        }

        public trace(s: string): void {
            this.shimHost.trace(s);
        }

        public error(s: string): void {
            this.shimHost.error(s);
        }

        public getCompilationSettings(): CompilerOptions {
            var settingsJson = this.shimHost.getCompilationSettings();
            if (settingsJson == null || settingsJson == "") {
                throw Error("LanguageServiceShimHostAdapter.getCompilationSettings: empty compilationSettings");
                return null;
            }
            return <CompilerOptions>JSON.parse(settingsJson);
        }

        public getScriptFileNames(): string[] {
            var encoded = this.shimHost.getScriptFileNames();
            return this.files = JSON.parse(encoded);
        }

        public getScriptSnapshot(fileName: string): IScriptSnapshot {
            // Shim the API changes for 1.5 release. This should be removed once
            // TypeScript 1.5 has shipped.
            if (this.files && this.files.indexOf(fileName) < 0) {
                return undefined;
            }
            var scriptSnapshot = this.shimHost.getScriptSnapshot(fileName);
            return scriptSnapshot && new ScriptSnapshotShimAdapter(scriptSnapshot);
        }

        public getScriptVersion(fileName: string): string {
            return this.shimHost.getScriptVersion(fileName);
        }

        public getLocalizedDiagnosticMessages(): any {
            var diagnosticMessagesJson = this.shimHost.getLocalizedDiagnosticMessages();
            if (diagnosticMessagesJson == null || diagnosticMessagesJson == "") {
                return null;
            }

            try {
                return JSON.parse(diagnosticMessagesJson);
            }
            catch (e) {
                this.log(e.description || "diagnosticMessages.generated.json has invalid JSON format");
                return null;
            }
        }

        public getCancellationToken(): CancellationToken {
            return this.shimHost.getCancellationToken();
        }

        public getCurrentDirectory(): string {
            return this.shimHost.getCurrentDirectory();
        }

        public getDefaultLibFileName(options: CompilerOptions): string {
            // Wrap the API changes for 1.5 release. This try/catch
            // should be removed once TypeScript 1.5 has shipped.
            try {
                return this.shimHost.getDefaultLibFileName(JSON.stringify(options));
            }
            catch (e) {
                return "";
            }
        }
    }

    function simpleForwardCall(logger: Logger, actionDescription: string, action: () => any): any {
        logger.log(actionDescription);
        var start = Date.now();
        var result = action();
        var end = Date.now();
        logger.log(actionDescription + " completed in " + (end - start) + " msec");
        if (typeof (result) === "string") {
            var str = <string>result;
            if (str.length > 128) {
                str = str.substring(0, 128) + "...";
            }
            logger.log("  result.length=" + str.length + ", result='" + JSON.stringify(str) + "'");
        }
        return result;
    }

    function forwardJSONCall(logger: Logger, actionDescription: string, action: () => any): string {
        try {
            var result = simpleForwardCall(logger, actionDescription, action);
            return JSON.stringify({ result: result });
        }
        catch (err) {
            if (err instanceof OperationCanceledException) {
                return JSON.stringify({ canceled: true });
            }
            logInternalError(logger, err);
            err.description = actionDescription;
            return JSON.stringify({ error: err });
        }
    }

    class ShimBase implements Shim {
        constructor(private factory: ShimFactory) {
            factory.registerShim(this);
        }
        public dispose(dummy: any): void {
            this.factory.unregisterShim(this);
        }
    }

    class LanguageServiceShimObject extends ShimBase implements LanguageServiceShim {
        private logger: Logger;

        constructor(factory: ShimFactory,
            private host: LanguageServiceShimHost,
            public languageService: LanguageService) {
            super(factory);
            this.logger = this.host;
        }

        public forwardJSONCall(actionDescription: string, action: () => any): string {
            return forwardJSONCall(this.logger, actionDescription, action);
        }

        /// DISPOSE

        /**
         * Ensure (almost) deterministic release of internal Javascript resources when
         * some external native objects holds onto us (e.g. Com/Interop).
         */
        public dispose(dummy: any): void {
            this.logger.log("dispose()");
            this.languageService.dispose();
            this.languageService = null;

            // force a GC
            if (debugObjectHost && debugObjectHost.CollectGarbage) {
                debugObjectHost.CollectGarbage();
                this.logger.log("CollectGarbage()");
            }

            this.logger = null;

            super.dispose(dummy);
        }

        /// REFRESH

        /**
         * Update the list of scripts known to the compiler
         */
        public refresh(throwOnError: boolean): void {
            this.forwardJSONCall(
                "refresh(" + throwOnError + ")",
                () => {
                    return <any>null;
                });
        }

        public cleanupSemanticCache(): void {
            this.forwardJSONCall(
                "cleanupSemanticCache()",
                () => {
                    this.languageService.cleanupSemanticCache();
                    return <any>null;
                });
        }

        private realizeDiagnostics(diagnostics: Diagnostic[]): { message: string; start: number; length: number; category: string; }[]{
            var newLine = this.getNewLine();
            return diagnostics.map(d => this.realizeDiagnostic(d, newLine));
        }

        private realizeDiagnostic(diagnostic: Diagnostic, newLine: string): { message: string; start: number; length: number; category: string; } {
            return {
                message: flattenDiagnosticMessageText(diagnostic.messageText, newLine),
                start: diagnostic.start,
                length: diagnostic.length,
                /// TODO: no need for the tolowerCase call
                category: DiagnosticCategory[diagnostic.category].toLowerCase(),
                code: diagnostic.code
            };
        }

        public getSyntacticClassifications(fileName: string, start: number, length: number): string {
            return this.forwardJSONCall(
                "getSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")",
                () => {
                    var classifications = this.languageService.getSyntacticClassifications(fileName, createTextSpan(start, length));
                    return classifications;
                });
        }

        public getSemanticClassifications(fileName: string, start: number, length: number): string {
            return this.forwardJSONCall(
                "getSemanticClassifications('" + fileName + "', " + start + ", " + length + ")",
                () => {
                    var classifications = this.languageService.getSemanticClassifications(fileName, createTextSpan(start, length));
                    return classifications;
                });
        }

        private getNewLine(): string {
            return this.host.getNewLine ? this.host.getNewLine() : "\r\n";
        }

        public getSyntacticDiagnostics(fileName: string): string {
            return this.forwardJSONCall(
                "getSyntacticDiagnostics('" + fileName + "')",
                () => {
                    var diagnostics = this.languageService.getSyntacticDiagnostics(fileName);
                    return this.realizeDiagnostics(diagnostics);
                });
        }

        public getSemanticDiagnostics(fileName: string): string {
            return this.forwardJSONCall(
                "getSemanticDiagnostics('" + fileName + "')",
                () => {
                    var diagnostics = this.languageService.getSemanticDiagnostics(fileName);
                    return this.realizeDiagnostics(diagnostics);
                });
        }

        public getCompilerOptionsDiagnostics(): string {
            return this.forwardJSONCall(
                "getCompilerOptionsDiagnostics()",
                () => {
                    var diagnostics = this.languageService.getCompilerOptionsDiagnostics();
                    return this.realizeDiagnostics(diagnostics);
                });
        }

        /// QUICKINFO

        /**
         * Computes a string representation of the type at the requested position
         * in the active file.
         */
        public getQuickInfoAtPosition(fileName: string, position: number): string {
            return this.forwardJSONCall(
                "getQuickInfoAtPosition('" + fileName + "', " + position + ")",
                () => {
                    var quickInfo = this.languageService.getQuickInfoAtPosition(fileName, position);
                    return quickInfo;
                });
        }

        /// NAMEORDOTTEDNAMESPAN

        /**
         * Computes span information of the name or dotted name at the requested position
         * in the active file.
         */
        public getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): string {
            return this.forwardJSONCall(
                "getNameOrDottedNameSpan('" + fileName + "', " + startPos + ", " + endPos + ")",
                () => {
                    var spanInfo = this.languageService.getNameOrDottedNameSpan(fileName, startPos, endPos);
                    return spanInfo;
                });
        }

        /**
         * STATEMENTSPAN
         * Computes span information of statement at the requested position in the active file.
         */
        public getBreakpointStatementAtPosition(fileName: string, position: number): string {
            return this.forwardJSONCall(
                "getBreakpointStatementAtPosition('" + fileName + "', " + position + ")",
                () => {
                    var spanInfo = this.languageService.getBreakpointStatementAtPosition(fileName, position);
                    return spanInfo;
                });
        }

        /// SIGNATUREHELP

        public getSignatureHelpItems(fileName: string, position: number): string {
            return this.forwardJSONCall(
                "getSignatureHelpItems('" + fileName + "', " + position + ")",
                () => {
                    var signatureInfo = this.languageService.getSignatureHelpItems(fileName, position);
                    return signatureInfo;
                });
        }

        /// GOTO DEFINITION

        /**
         * Computes the definition location and file for the symbol
         * at the requested position.
         */
        public getDefinitionAtPosition(fileName: string, position: number): string {
            return this.forwardJSONCall(
                "getDefinitionAtPosition('" + fileName + "', " + position + ")",
                () => {
                    return this.languageService.getDefinitionAtPosition(fileName, position);
                });
        }

        public getRenameInfo(fileName: string, position: number): string {
            return this.forwardJSONCall(
                "getRenameInfo('" + fileName + "', " + position + ")",
                () => {
                    return this.languageService.getRenameInfo(fileName, position);
                });
        }

        public findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): string {
            return this.forwardJSONCall(
                "findRenameLocations('" + fileName + "', " + position + ", " + findInStrings + ", " + findInComments + ")",
                () => {
                    return this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments);
                });
        }

        /// GET BRACE MATCHING
        public getBraceMatchingAtPosition(fileName: string, position: number): string {
            return this.forwardJSONCall(
                "getBraceMatchingAtPosition('" + fileName + "', " + position + ")",
                () => {
                    var textRanges = this.languageService.getBraceMatchingAtPosition(fileName, position);
                    return textRanges;
                });
        }

        /// GET SMART INDENT
        public getIndentationAtPosition(fileName: string, position: number, options: string /*Services.EditorOptions*/): string {
            return this.forwardJSONCall(
                "getIndentationAtPosition('" + fileName + "', " + position + ")",
                () => {
                    var localOptions: EditorOptions = JSON.parse(options);
                    return this.languageService.getIndentationAtPosition(fileName, position, localOptions);
                });
        }

        /// GET REFERENCES

        public getReferencesAtPosition(fileName: string, position: number): string {
            return this.forwardJSONCall(
                "getReferencesAtPosition('" + fileName + "', " + position + ")",
                () => {
                    return this.languageService.getReferencesAtPosition(fileName, position);
                });
        }

        public findReferences(fileName: string, position: number): string {
            return this.forwardJSONCall(
                "findReferences('" + fileName + "', " + position + ")",
                () => {
                    return this.languageService.findReferences(fileName, position);
                });
        }

        public getOccurrencesAtPosition(fileName: string, position: number): string {
            return this.forwardJSONCall(
                "getOccurrencesAtPosition('" + fileName + "', " + position + ")",
                () => {
                    return this.languageService.getOccurrencesAtPosition(fileName, position);
                });
        }

        /// COMPLETION LISTS

        /**
         * Get a string based representation of the completions
         * to provide at the given source position and providing a member completion
         * list if requested.
         */
        public getCompletionsAtPosition(fileName: string, position: number) {
            return this.forwardJSONCall(
                "getCompletionsAtPosition('" + fileName + "', " + position + ")",
                () => {
                    var completion = this.languageService.getCompletionsAtPosition(fileName, position);
                    return completion;
                });
        }

        /** Get a string based representation of a completion list entry details */
        public getCompletionEntryDetails(fileName: string, position: number, entryName: string) {
            return this.forwardJSONCall(
                "getCompletionEntryDetails('" + fileName + "', " + position + ", " + entryName + ")",
                () => {
                    var details = this.languageService.getCompletionEntryDetails(fileName, position, entryName);
                    return details;
                });
        }

        public getFormattingEditsForRange(fileName: string, start: number, end: number, options: string/*Services.FormatCodeOptions*/): string {
            return this.forwardJSONCall(
                "getFormattingEditsForRange('" + fileName + "', " + start + ", " + end + ")",
                () => {
                    var localOptions: ts.FormatCodeOptions = JSON.parse(options);
                    var edits = this.languageService.getFormattingEditsForRange(fileName, start, end, localOptions);
                    return edits;
                });
        }

        public getFormattingEditsForDocument(fileName: string, options: string/*Services.FormatCodeOptions*/): string {
            return this.forwardJSONCall(
                "getFormattingEditsForDocument('" + fileName + "')",
                () => {
                    var localOptions: ts.FormatCodeOptions = JSON.parse(options);
                    var edits = this.languageService.getFormattingEditsForDocument(fileName, localOptions);
                    return edits;
                });
        }

        public getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: string/*Services.FormatCodeOptions*/): string {
            return this.forwardJSONCall(
                "getFormattingEditsAfterKeystroke('" + fileName + "', " + position + ", '" + key + "')",
                () => {
                    var localOptions: ts.FormatCodeOptions = JSON.parse(options);
                    var edits = this.languageService.getFormattingEditsAfterKeystroke(fileName, position, key, localOptions);
                    return edits;
                });
        }

        /// NAVIGATE TO

        /** Return a list of symbols that are interesting to navigate to */
        public getNavigateToItems(searchValue: string, maxResultCount?: number): string {
            return this.forwardJSONCall(
                "getNavigateToItems('" + searchValue + "', " + maxResultCount+ ")",
                () => {
                    var items = this.languageService.getNavigateToItems(searchValue, maxResultCount);
                    return items;
                });
        }

        public getNavigationBarItems(fileName: string): string {
            return this.forwardJSONCall(
                "getNavigationBarItems('" + fileName + "')",
                () => {
                    var items = this.languageService.getNavigationBarItems(fileName);
                    return items;
                });
        }

        public getOutliningSpans(fileName: string): string {
            return this.forwardJSONCall(
                "getOutliningSpans('" + fileName + "')",
                () => {
                    var items = this.languageService.getOutliningSpans(fileName);
                    return items;
                });
        }

        public getTodoComments(fileName: string, descriptors: string): string {
            return this.forwardJSONCall(
                "getTodoComments('" + fileName + "')",
                () => {
                    var items = this.languageService.getTodoComments(fileName, JSON.parse(descriptors));
                    return items;
                });
        }

        /// Emit
        public getEmitOutput(fileName: string): string {
            return this.forwardJSONCall(
                "getEmitOutput('" + fileName + "')",
                () => {
                    var output = this.languageService.getEmitOutput(fileName);
                    // Shim the API changes for 1.5 release. This should be removed once
                    // TypeScript 1.5 has shipped.
                    (<any>output).emitOutputStatus = output.emitSkipped ? 1 : 0;
                    return output;
                });
        }
    }

    class ClassifierShimObject extends ShimBase implements ClassifierShim {
        public classifier: Classifier;

        constructor(factory: ShimFactory) {
            super(factory);
            this.classifier = createClassifier();
        }

        /// COLORIZATION
        public getClassificationsForLine(text: string, lexState: EndOfLineState, classifyKeywordsInGenerics?: boolean): string {
            var classification = this.classifier.getClassificationsForLine(text, lexState, classifyKeywordsInGenerics);
            var items = classification.entries;
            var result = "";
            for (var i = 0; i < items.length; i++) {
                result += items[i].length + "\n";
                result += items[i].classification + "\n";
            }
            result += classification.finalLexState;
            return result;
        }
    }

    class CoreServicesShimObject extends ShimBase implements CoreServicesShim {
        constructor(factory: ShimFactory, public logger: Logger) {
            super(factory);
        }

        private forwardJSONCall(actionDescription: string, action: () => any): any {
            return forwardJSONCall(this.logger, actionDescription, action);
        }

        public getPreProcessedFileInfo(fileName: string, sourceTextSnapshot: IScriptSnapshot): string {
            return this.forwardJSONCall(
                "getPreProcessedFileInfo('" + fileName + "')",
                () => {
                    var result = preProcessFile(sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength()));
                    var convertResult = {
                        referencedFiles: <IFileReference[]>[],
                        importedFiles: <IFileReference[]>[],
                        isLibFile: result.isLibFile
                    };

                    forEach(result.referencedFiles, refFile => {
                        convertResult.referencedFiles.push({
                            path: normalizePath(refFile.fileName),
                            position: refFile.pos,
                            length: refFile.end - refFile.pos
                        });
                    });

                    forEach(result.importedFiles, importedFile => {
                        convertResult.importedFiles.push({
                            path: normalizeSlashes(importedFile.fileName),
                            position: importedFile.pos,
                            length: importedFile.end - importedFile.pos
                        });
                    });
                    return convertResult;
                });
        }

        public getDefaultCompilationSettings(): string {
            return this.forwardJSONCall(
                "getDefaultCompilationSettings()",
                () => {
                    return getDefaultCompilerOptions();
                });
        }
    }

    export class TypeScriptServicesFactory implements ShimFactory {
        private _shims: Shim[] = [];
        private documentRegistry: DocumentRegistry = createDocumentRegistry();

        /*
         * Returns script API version.
         */
        public getServicesVersion(): string {
            return servicesVersion;
        }

        public createLanguageServiceShim(host: LanguageServiceShimHost): LanguageServiceShim {
            try {
                var hostAdapter = new LanguageServiceShimHostAdapter(host);
                var languageService = createLanguageService(hostAdapter, this.documentRegistry);
                return new LanguageServiceShimObject(this, host, languageService);
            }
            catch (err) {
                logInternalError(host, err);
                throw err;
            }
        }

        public createClassifierShim(logger: Logger): ClassifierShim {
            try {
                return new ClassifierShimObject(this);
            }
            catch (err) {
                logInternalError(logger, err);
                throw err;
            }
        }

        public createCoreServicesShim(logger: Logger): CoreServicesShim {
            try {
                return new CoreServicesShimObject(this, logger);
            }
            catch (err) {
                logInternalError(logger, err);
                throw err;
            }
        }

        public close(): void {
            // Forget all the registered shims
            this._shims = [];
            this.documentRegistry = createDocumentRegistry();
        }

        public registerShim(shim: Shim): void {
            this._shims.push(shim);
        }

        public unregisterShim(shim: Shim): void {
            for (var i = 0, n = this._shims.length; i < n; i++) {
                if (this._shims[i] === shim) {
                    delete this._shims[i];
                    return;
                }
            }

            throw new Error("Invalid operation");
        }
    }

    // Here we expose the TypeScript services as an external module
    // so that it may be consumed easily like a node module.
    declare var module: any;
    if (typeof module !== "undefined" && module.exports) {
        module.exports = ts;
    }
}

/// TODO: this is used by VS, clean this up on both sides of the interface
module TypeScript.Services {
    export var TypeScriptServicesFactory = ts.TypeScriptServicesFactory;
}

let toolsVersion = "1.4";


text:
using Sakuno.ING.Game.Models.MasterData;

namespace Sakuno.ING.Game.Json
{
#nullable disable
    internal sealed class MasterDataJson
    {
        public RawShipInfo[] api_mst_ship { get; set; }
        public RawSlotItemTypeInfo[] api_mst_slotitem_equiptype { get; set; }
        public SlotItemInfoId[] api_mst_equip_exslot { get; set; }
        public RawExtraSlotSlotItemAllowListJson[] api_mst_equip_exslot_ship { get; set; }
        public RawShipTypeInfo[] api_mst_stype { get; set; }
        public RawSlotItemInfo[] api_mst_slotitem { get; set; }
        public RawUseItem[] api_mst_useitem { get; set; }
        public RawMapArea[] api_mst_maparea { get; set; }
        public RawMapInfo[] api_mst_mapinfo { get; set; }
        public RawMapBgmInfo[] api_mst_mapbgm { get; set; }
        public RawExpeditionInfo[] api_mst_mission { get; set; }
        public RawShipEquipLimitation[] api_mst_equip_ship { get; set; }
    }
#nullable enable
}


text:
from database import Session
from database.models import LeaderBoardEntry, UberAccount

from twisted.internet.defer import Deferred, succeed
from twisted.python import log

class LeaderParser(object):
    """
    Retrieves most recently cached rankings for the specified league.
    Provides deferred functions that can be called from other Twisted
    applications.
    """

    def __init__(self):
        """Initialize a database session."""
        log.msg("Initializing Ubernet Leaderboard parser.")
        self.session = Session()

    def top(self, league):
        """Start an update and return a deferred containing the results."""
        updateDeferred = succeed(None)
        newDeferred = Deferred()

        league = league.capitalize()

        def updateDone(value):
            """Callback method for update."""
            entries = (self.session.query(LeaderBoardEntry.uid,
                                          UberAccount.dname)
                           .outerjoin(UberAccount,
                                      UberAccount.uid == LeaderBoardEntry.uid)
                           .filter(LeaderBoardEntry.game == "Titans",
                                   LeaderBoardEntry.league == league)
                           .order_by(LeaderBoardEntry.rank))

            newDeferred.callback([e[1] for e in entries])

            self.session.close()

        updateDeferred.addCallback(updateDone)

        return newDeferred


text:
<?php echo "<?xml version='1.0' encoding='ISO-8859-1'?>"; ?>
<!DOCTYPE OrderList SYSTEM 'http://xcp.xpertfulfillment.com/xml/OrderList.dtd'>
<OrderList MerchantName='Holistic Labs Ltd' MerchantId='164'>

<?php foreach ($orders as $order): ?>
<Order id='<?php echo $order['public_id']; ?>'>
	<AddressInfo type='ship'>
		<Name><?php echo htmlspecialchars($order['name']); ?></Name>
		<Company> </Company>
		<Address1><?php echo htmlspecialchars($order['address1']); ?></Address1>
		<Address2><?php echo !empty($order['address2']) ? htmlspecialchars($order['address2']) : ''; ?></Address2>
		<City><?php echo $order['city']; ?></City>
		<State><?php echo $order['state']; ?></State>
		<Country><?php echo $order['country']; ?></Country>
		<Zip><?php echo $order['zip']; ?></Zip>
		<Phone><?php echo $order['phone']; ?></Phone>
		<Email><?php echo $order['email']; ?></Email>
	</AddressInfo>
	<AddressInfo type='bill'>
		<Name><?php echo $order['name']; ?></Name>
		<Company> </Company>
		<Address1><?php echo $order['address1']; ?></Address1>
		<Address2><?php echo !empty($order['address2']) ? $order['address2'] : ''; ?></Address2>
		<City><?php echo $order['city']; ?></City>
		<State><?php echo $order['state']; ?></State>
		<Country><?php echo $order['country']; ?></Country>
		<Zip><?php echo $order['zip']; ?></Zip>
		<Phone><?php echo $order['phone']; ?></Phone>
		<Email><?php echo $order['email']; ?></Email>
	</AddressInfo>
	<ShippingMethod><?php echo $order['shipping_method']; ?></ShippingMethod>
	<Insurance>0</Insurance>
	<ReqSignature>0</ReqSignature>
		<?php $i = 0; ?>
		<?php foreach ($order['items'] as $item): ?>
		<Item num='<?php echo $i++; ?>'>
			<ProductId><?php echo $item['sku']; ?></ProductId>
			<Quantity><?php echo $item['quantity']; ?></Quantity>
		</Item>
		<?php endforeach; ?>
	<orderRef></orderRef>
	<SpecialInstructions><?php echo htmlentities($order['comments'])?></SpecialInstructions>
</Order>
<?php endforeach; ?>
</OrderList>


text:
package runtime

var Fadd64 = fadd64
var Fsub64 = fsub64
var Fmul64 = fmul64
var Fdiv64 = fdiv64
var F64to32 = f64to32
var F32to64 = f32to64
var Fcmp64 = fcmp64
var Fintto64 = fintto64
var F64toint = f64toint

func entersyscall()
func exitsyscall()

var Entersyscall = entersyscall
var Exitsyscall = exitsyscall


text:
package main

import (
	"log"

	"github.com/gorilla/securecookie"
)

const (
	defaultHashKeySize  = 64
	defaultBlockKeySize = 32
)

func validHashKey(key string) []byte {
	if key == "" {
		hashKey := securecookie.GenerateRandomKey(defaultHashKeySize)
		if hashKey == nil {
			log.Fatal("could not generate random hash key, exiting...")
		}
		log.Println("Note: Using auto generated hash key.")
		log.Println("Note: Values signed with this key will be invalidated on server restart. Use -hashkey='<strong random key>' instead.")
		return hashKey
	}
	hashKey := []byte(key)
	if len(hashKey) != 32 && len(hashKey) != 64 {
		log.Fatal("hash key should be 32 or 64 bytes, exiting...", len(hashKey))
	}
	return hashKey
}

func validBlockKey(key string) []byte {
	if key == "" {
		blockKey := securecookie.GenerateRandomKey(defaultBlockKeySize)
		if blockKey == nil {
			log.Fatal("could not generate random block key, exiting...")
		}
		log.Println("Note: Using auto generated block key.")
		log.Println("Note: Values encrypted with this key will be invalidated on server restart. Use -blockkey='<strong random key>' instead.")
		return blockKey
	}
	blockKey := []byte(key)
	if len(blockKey) != 32 {
		log.Fatal("block key should be 32 bytes, exiting...")
	}
	return blockKey
}

func validCSRFKey(key string) []byte {
	if key == "" {
		log.Println("No CSRF key provided, exiting...")
		log.Fatal("The CSRF key should be 32-bytes long and persist across application restarts. Use -csrfkey='<strong random key>'.")
	}
	csrfKey := []byte(key)
	if len(csrfKey) != 32 {
		log.Fatal("CSRF key should be 32 bytes, exiting...")
	}
	return csrfKey
}


text:
'use strict'

export default (props) => (
  props ?

 {props.profile.name}

 : null
)


text:
package com.facebook.buck.python;

import static com.facebook.buck.rules.BuildableProperties.Kind.LIBRARY;

import com.facebook.buck.cxx.CxxPlatform;
import com.facebook.buck.rules.BuildRuleParams;
import com.facebook.buck.rules.BuildableProperties;
import com.facebook.buck.rules.NoopBuildRule;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.TargetGraph;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;

import java.nio.file.Path;

public class PythonLibrary extends NoopBuildRule implements PythonPackagable {

  private static final BuildableProperties OUTPUT_TYPE = new BuildableProperties(LIBRARY);

  private final ImmutableMap<Path, SourcePath> srcs;
  private final ImmutableMap<Path, SourcePath> resources;
  private final Optional<Boolean> zipSafe;

  public PythonLibrary(
      BuildRuleParams params,
      SourcePathResolver resolver,
      ImmutableMap<Path, SourcePath> srcs,
      ImmutableMap<Path, SourcePath> resources,
      Optional<Boolean> zipSafe) {
    super(params, resolver);
    this.srcs = srcs;
    this.resources = resources;
    this.zipSafe = zipSafe;
  }

  @Override
  public PythonPackageComponents getPythonPackageComponents(
      TargetGraph targetGraph,
      CxxPlatform cxxPlatform) {
    return PythonPackageComponents.of(
        srcs,
        resources,
        ImmutableMap.<Path, SourcePath>of(),
        ImmutableSet.<SourcePath>of(),
        zipSafe);
  }

  @Override
  public BuildableProperties getProperties() {
    return OUTPUT_TYPE;
  }

  public ImmutableMap<Path, SourcePath> getSrcs() {
    return srcs;
  }

}


text:
#ifndef AV1_COMMON_FILTER_H_
#define AV1_COMMON_FILTER_H_

#include <assert.h>

#include "./aom_config.h"
#include "aom/aom_integer.h"
#include "aom_dsp/aom_filter.h"
#include "aom_ports/mem.h"

#ifdef __cplusplus
extern "C" {
#endif

#define MAX_FILTER_TAP 8

typedef enum ATTRIBUTE_PACKED {
  EIGHTTAP_REGULAR,
  EIGHTTAP_SMOOTH,
  MULTITAP_SHARP,
  BILINEAR,
  INTERP_FILTERS_ALL,
  SWITCHABLE_FILTERS = BILINEAR,
  SWITCHABLE = SWITCHABLE_FILTERS + 1, /* the last switchable one */
  EXTRA_FILTERS = INTERP_FILTERS_ALL - SWITCHABLE_FILTERS,
} InterpFilter;

// With CONFIG_DUAL_FILTER, pack two InterpFilter's into a uint32_t: since
// there are at most 10 filters, we can use 16 bits for each and have more than
// enough space. This reduces argument passing and unifies the operation of
// setting a (pair of) filters.
//
// Without CONFIG_DUAL_FILTER,
typedef uint32_t InterpFilters;
static INLINE InterpFilter av1_extract_interp_filter(InterpFilters filters,
                                                     int x_filter) {
  return (InterpFilter)((filters >> (x_filter ? 16 : 0)) & 0xffff);
}

static INLINE InterpFilters av1_make_interp_filters(InterpFilter y_filter,
                                                    InterpFilter x_filter) {
  uint16_t y16 = y_filter & 0xffff;
  uint16_t x16 = x_filter & 0xffff;
  return y16 | ((uint32_t)x16 << 16);
}

static INLINE InterpFilters av1_broadcast_interp_filter(InterpFilter filter) {
  return av1_make_interp_filters(filter, filter);
}

static INLINE InterpFilter av1_unswitchable_filter(InterpFilter filter) {
  return filter == SWITCHABLE ? EIGHTTAP_REGULAR : filter;
}

#define LOG_SWITCHABLE_FILTERS \
  2 /* (1 << LOG_SWITCHABLE_FILTERS) > SWITCHABLE_FILTERS */

#define MAX_SUBPEL_TAPS 12
#define SWITCHABLE_FILTER_CONTEXTS ((SWITCHABLE_FILTERS + 1) * 4)
#define INTER_FILTER_COMP_OFFSET (SWITCHABLE_FILTERS + 1)
#define INTER_FILTER_DIR_OFFSET ((SWITCHABLE_FILTERS + 1) * 2)

typedef struct InterpFilterParams {
  const int16_t *filter_ptr;
  uint16_t taps;
  uint16_t subpel_shifts;
  InterpFilter interp_filter;
} InterpFilterParams;

const int16_t *av1_get_interp_filter_kernel(const InterpFilter interp_filter);

InterpFilterParams av1_get_interp_filter_params_with_block_size(
    const InterpFilter interp_filter, const int w);

static INLINE const int16_t *av1_get_interp_filter_subpel_kernel(
    const InterpFilterParams filter_params, const int subpel) {
  return filter_params.filter_ptr + filter_params.taps * subpel;
}

#ifdef __cplusplus
}  // extern "C"
#endif

#endif  // AV1_COMMON_FILTER_H_


text:
<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;

class ArticleSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run(\Faker\Generator $faker)
    {
        /** @var \App\Property $property */
        $properties = \App\Property::all();

        $sections = \App\Section::factory()->count(3)->create();
        $tags = \App\Model\Tag::factory()->count(10)->create();

        /** @var \Illuminate\Database\Eloquent\Collection $articles */
        $articles = \App\Article::factory()->count(50)->create([
            'property_uuid' => $properties->random()->uuid,
        ])->each(function (\App\Article $article) use ($sections, $tags) {
            $article->sections()->save($sections[rand(0, count($sections)-1)]);
            $article->tags()->save($tags[rand(0, count($tags)-1)]);
        });

        $authors = \App\Author::factory()->count(5)->create();
        $articles->each(function (\App\Article $article) use ($authors) {
            $article->authors()->attach($authors->random());
        });

        $articles->each(function (\App\Article $article) use ($faker) {
            $article->conversions()->saveMany(
                \App\Conversion::factory()->count($faker->numberBetween(5,20))->make([
                    'article_id' => $article->id,
                ])
            );
        });
    }
}


text:
define([
	"dojo/_base/array",
	"dojo/_base/declare",
	"dojo/_base/lang",
	"dojo/sniff",
	"dojo/dom",
	"dojo/dom-class",
	"dojo/dom-construct",
	"dijit/_Contained",
	"dijit/_Container",
	"dijit/_WidgetBase",
	"./iconUtils",
	"./lazyLoadUtils",
	"./_css3",
	"require",
	"dojo/has!dojo-bidi?dojox/mobile/bidi/Accordion"
], function(array, declare, lang, has, dom, domClass, domConstruct, Contained, Container, WidgetBase, iconUtils, lazyLoadUtils, css3, require, BidiAccordion){

	// module:
	//		dojox/mobile/Accordion

	// inner class
	var _AccordionTitle = declare([WidgetBase, Contained], {
		// summary:
		//		A widget for the title of the accordion.

		// label: String
		//		The title of the accordion.
		label: "Label",

		// icon1: String
		//		A path for the unselected (typically dark) icon. If icon is not
		//		specified, the iconBase parameter of the parent widget is used.
		icon1: "",

		// icon2: String
		//		A path for the selected (typically highlight) icon. If icon is
		//		not specified, the iconBase parameter of the parent widget or
		//		icon1 is used.
		icon2: "",

		// iconPos1: String
		//		The position of an aggregated unselected (typically dark)
		//		icon. IconPos1 is a comma-separated list of values like
		//		top,left,width,height (ex. "0,0,29,29"). If iconPos1 is not
		//		specified, the iconPos parameter of the parent widget is used.
		iconPos1: "",

		// iconPos2: String
		//		The position of an aggregated selected (typically highlight)
		//		icon. IconPos2 is a comma-separated list of values like
		//		top,left,width,height (ex. "0,0,29,29"). If iconPos2 is not
		//		specified, the iconPos parameter of the parent widget or
		//		iconPos1 is used.
		iconPos2: "",

		// selected: Boolean
		//		If true, the widget is in the selected state.
		selected: false,

		// baseClass: String
		//		The name of the CSS class of this widget.
		baseClass: "mblAccordionTitle",

		buildRendering: function(){
			this.inherited(arguments);

			var a = this.anchorNode = domConstruct.create("a", {
				className: "mblAccordionTitleAnchor"
			}, this.domNode);
			a.href = "javascript:void(0)"; // for a11y

			// text box
			this.textBoxNode = domConstruct.create("div", {className:"mblAccordionTitleTextBox"}, a);
			this.labelNode = domConstruct.create("span", {
				className: "mblAccordionTitleLabel",
				innerHTML: this._cv ? this._cv(this.label) : this.label
			}, this.textBoxNode);

			this._isOnLine = this.inheritParams();
		},

		postCreate: function(){
			this.connect(this.domNode, "onclick", "_onClick");
			dom.setSelectable(this.domNode, false);
		},

		inheritParams: function(){
			var parent = this.getParent();
			if(parent){
				if(this.icon1 && parent.iconBase &&
					parent.iconBase.charAt(parent.iconBase.length - 1) === '/'){
					this.icon1 = parent.iconBase + this.icon1;
				}
				if(!this.icon1){ this.icon1 = parent.iconBase; }
				if(!this.iconPos1){ this.iconPos1 = parent.iconPos; }
				if(this.icon2 && parent.iconBase &&
					parent.iconBase.charAt(parent.iconBase.length - 1) === '/'){
					this.icon2 = parent.iconBase + this.icon2;
				}
				if(!this.icon2){ this.icon2 = parent.iconBase || this.icon1; }
				if(!this.iconPos2){ this.iconPos2 = parent.iconPos || this.iconPos1; }
			}
			return !!parent;
		},

		_setIcon: function(icon, n){
			// tags:
			//		private
			if(!this.getParent()){ return; } // icon may be invalid because inheritParams is not called yet
			this._set("icon" + n, icon);
			if(!this["iconParentNode" + n]){
				this["iconParentNode" + n] = domConstruct.create("div",
					{className:"mblAccordionIconParent mblAccordionIconParent" + n}, this.anchorNode, "first");
			}
			this["iconNode" + n] = iconUtils.setIcon(icon, this["iconPos" + n],
				this["iconNode" + n], this.alt, this["iconParentNode" + n]);
			this["icon" + n] = icon;
			domClass.toggle(this.domNode, "mblAccordionHasIcon", icon && icon !== "none");
		},

		_setIcon1Attr: function(icon){
			// tags:
			//		private
			this._setIcon(icon, 1);
		},

		_setIcon2Attr: function(icon){
			// tags:
			//		private
			this._setIcon(icon, 2);
		},

		startup: function(){
			if(this._started){ return; }
			if(!this._isOnLine){
				this.inheritParams();
			}
			if(!this._isOnLine){
				this.set({ // retry applying the attribute
					icon1: this.icon1,
					icon2: this.icon2
				});
			}
			this.inherited(arguments);
		},

		_onClick: function(e){
			// summary:
			//		Internal handler for click events.
			// tags:
			//		private
			if(this.onClick(e) === false){ return; } // user's click action
			var p = this.getParent();
			if(!p.fixedHeight && this.contentWidget.domNode.style.display !== "none"){
				p.collapse(this.contentWidget, !p.animation);
			}else{
				p.expand(this.contentWidget, !p.animation);
			}
		},

		onClick: function(/*Event*/ /*===== e =====*/){
			// summary:
			//		User-defined function to handle clicks
			// tags:
			//		callback
		},

		_setSelectedAttr: function(/*Boolean*/selected){
			// tags:
			//		private
			domClass.toggle(this.domNode, "mblAccordionTitleSelected", selected);
			this._set("selected", selected);
		}
	});

	var Accordion = declare(has("dojo-bidi") ? "dojox.mobile.NonBidiAccordion" : "dojox.mobile.Accordion", [WidgetBase, Container, Contained], {
		// summary:
		//		A container widget that can display a group of child panes in a stacked format.
		// description:
		//		Typically, dojox/mobile/Pane, dojox/mobile/Container, or dojox/mobile/ContentPane are
		//		used as child widgets, but Accordion requires no specific child widget.
		//		Accordion supports three modes for opening child panes: multiselect, fixed-height,
		//		and single-select. Accordion can have rounded corners, and it can lazy-load the
		//		content modules.

		// iconBase: String
		//		The default icon path for child widgets.
		iconBase: "",

		// iconPos: String
		//		The default icon position for child widgets.
		iconPos: "",

		// fixedHeight: Boolean
		//		If true, the entire accordion widget has fixed height regardless
		//		of the height of each pane; in this mode, there is always an open pane and
		//		collapsing a pane can only be done by opening a different pane.
		fixedHeight: false,

		// singleOpen: Boolean
		//		If true, only one pane is open at a time. The current open pane
		//		is collapsed, when another pane is opened.
		singleOpen: false,

		// animation: Boolean
		//		If true, animation is used when a pane is opened or
		//		collapsed. The animation works only on webkit browsers.
		animation: true,

		// roundRect: Boolean
		//		If true, the widget shows rounded corners.
		//		Adding the "mblAccordionRoundRect" class to domNode has the same effect.
		roundRect: false,

		/* internal properties */
		duration: .3, // [seconds]

		// baseClass: String
		//		The name of the CSS class of this widget.
		baseClass: "mblAccordion",

		// _openSpace: [private] Number|String
		_openSpace: 1,

		startup: function(){
			if(this._started){ return; }

			if(domClass.contains(this.domNode, "mblAccordionRoundRect")){
				this.roundRect = true;
			}else if(this.roundRect){
				domClass.add(this.domNode, "mblAccordionRoundRect");
			}

			if(this.fixedHeight){
				this.singleOpen = true;
			}
			var children = this.getChildren();
			array.forEach(children, this._setupChild, this);
			var sel;
			array.forEach(children, function(child){
				child.startup();
				child._at.startup();
				this.collapse(child, true);
				if(child.selected){
					sel = child;
				}
			}, this);
			if(!sel && this.fixedHeight){
				sel = children[children.length - 1];
			}
			if(sel){
				this.expand(sel, true);
			}else{
				this._updateLast();
			}
			setTimeout(lang.hitch(this, function(){ this.resize(); }), 0);

			this._started = true;
		},

		_setupChild: function(/*Widget*/ child){
			// tags:
			//		private
			if(child.domNode.style.overflow != "hidden"){
				child.domNode.style.overflow = this.fixedHeight ? "auto" : "hidden";
			}
			child._at = new _AccordionTitle({
				label: child.label,
				alt: child.alt,
				icon1: child.icon1,
				icon2: child.icon2,
				iconPos1: child.iconPos1,
				iconPos2: child.iconPos2,
				contentWidget: child
			});
			domConstruct.place(child._at.domNode, child.domNode, "before");
			domClass.add(child.domNode, "mblAccordionPane");
		},

		addChild: function(/*Widget*/ widget, /*int?*/ insertIndex){
			this.inherited(arguments);
			if(this._started){
				this._setupChild(widget);
				widget._at.startup();
				if(widget.selected){
					this.expand(widget, true);
					setTimeout(function(){
						widget.domNode.style.height = "";
					}, 0);
				}else{
					this.collapse(widget);
				}
			}
		},

		removeChild: function(/*Widget|int*/ widget){
			if(typeof widget == "number"){
				widget = this.getChildren()[widget];
			}
			if(widget){
				widget._at.destroy();
			}
			this.inherited(arguments);
		},

		getChildren: function(){
			return array.filter(this.inherited(arguments), function(child){
				return !(child instanceof _AccordionTitle);
			});
		},

		getSelectedPanes: function(){
			return array.filter(this.getChildren(), function(pane){
				return pane.domNode.style.display != "none";
			});
		},

		resize: function(){
			if(this.fixedHeight){
				var panes = array.filter(this.getChildren(), function(child){ // active pages
					return child._at.domNode.style.display != "none";
				});
				var openSpace = this.domNode.clientHeight; // height of all panes
				array.forEach(panes, function(child){
					openSpace -= child._at.domNode.offsetHeight;
				});
				this._openSpace = openSpace > 0 ? openSpace : 0;
				var sel = this.getSelectedPanes()[0];
				sel.domNode.style[css3.name("transition")] = "";
				sel.domNode.style.height = this._openSpace + "px";
			}
		},

		_updateLast: function(){
			// tags:
			//		private
			var children = this.getChildren();
			array.forEach(children, function(c, i){
				// add "mblAccordionTitleLast" to the last, closed accordion title
				domClass.toggle(c._at.domNode, "mblAccordionTitleLast",
					i === children.length - 1 && !domClass.contains(c._at.domNode, "mblAccordionTitleSelected"))
			}, this);
		},

		expand: function(/*Widget*/pane, /*boolean*/noAnimation){
			// summary:
			//		Expands the given pane to make it visible.
			// pane:
			//		A pane widget to expand.
			// noAnimation:
			//		If true, the pane expands immediately without animation effect.
			if(pane.lazy){
				lazyLoadUtils.instantiateLazyWidgets(pane.containerNode, pane.requires);
				pane.lazy = false;
			}
			var children = this.getChildren();
			array.forEach(children, function(c, i){
				c.domNode.style[css3.name("transition")] = noAnimation ? "" : "height "+this.duration+"s linear";
				if(c === pane){
					c.domNode.style.display = "";
					var h;
					if(this.fixedHeight){
						h = this._openSpace;
					}else{
						h = parseInt(c.height || c.domNode.getAttribute("height")); // ScrollableView may have the height property
						if(!h){
							c.domNode.style.height = "";
							h = c.domNode.offsetHeight;
							c.domNode.style.height = "0px";
						}
					}
					setTimeout(function(){ // necessary for webkitTransition to work
						c.domNode.style.height = h + "px";
					}, 0);
					this.select(pane);
				}else if(this.singleOpen){
					this.collapse(c, noAnimation);
				}
			}, this);
			this._updateLast();
		},

		collapse: function(/*Widget*/pane, /*boolean*/noAnimation){
			// summary:
			//		Collapses the given pane to close it.
			// pane:
			//		A pane widget to collapse.
			// noAnimation:
			//		If true, the pane collapses immediately without animation effect.
			if(pane.domNode.style.display === "none"){ return; } // already collapsed
			pane.domNode.style[css3.name("transition")] = noAnimation ? "" : "height "+this.duration+"s linear";
			pane.domNode.style.height = "0px";
			if(!has("css3-animations") || noAnimation){
				pane.domNode.style.display = "none";
				this._updateLast();
			}else{
				// Adding a webkitTransitionEnd handler to panes may cause conflict
				// when the panes already have the one. (e.g. ScrollableView)
				var _this = this;
				setTimeout(function(){
					pane.domNode.style.display = "none";
					_this._updateLast();

					// Need to call parent view's resize() especially when the Accordion is
					// on a ScrollableView, the ScrollableView is scrolled to
					// the bottom, and then expand any other pane while in the
					// non-fixed singleOpen mode.
					if(!_this.fixedHeight && _this.singleOpen){
						for(var v = _this.getParent(); v; v = v.getParent()){
							if(domClass.contains(v.domNode, "mblView")){
								if(v && v.resize){ v.resize(); }
								break;
							}
						}
					}
				}, this.duration*1000);
			}
			this.deselect(pane);
		},

		select: function(/*Widget*/pane){
			// summary:
			//		Highlights the title bar of the given pane.
			// pane:
			//		A pane widget to highlight.
			pane._at.set("selected", true);
		},

		deselect: function(/*Widget*/pane){
			// summary:
			//		Unhighlights the title bar of the given pane.
			// pane:
			//		A pane widget to unhighlight.
			pane._at.set("selected", false);
		}
	});

	Accordion.ChildWidgetProperties = {
		// summary:
		//		These properties can be specified for the children of a dojox/mobile/Accordion.

		// alt: String
		//		The alternate text of the Accordion title.
		alt: "",
		// label: String
		//		The label of the Accordion title.
		label: "",
		// icon1: String
		//		The unselected icon of the Accordion title.
		icon1: "",
		// icon2: String
		//		The selected icon of the Accordion title.
		icon2: "",
		// iconPos1: String
		//		The position ("top,left,width,height") of the unselected aggregated icon of the Accordion title.
		iconPos1: "",
		// iconPos2: String
		//		The position ("top,left,width,height") of the selected aggregated icon of the Accordion title.
		iconPos2: "",
		// selected: Boolean
		//		The selected state of the Accordion title.
		selected: false,
		// lazy: Boolean
		//		Specifies that the Accordion child must be lazily loaded.
		lazy: false
	};

	// Since any widget can be specified as an Accordion child, mix ChildWidgetProperties
	// into the base widget class.  (This is a hack, but it's effective.)
	// This is for the benefit of the parser.   Remove for 2.0.  Also, hide from doc viewer.
	lang.extend(WidgetBase, /*===== {} || =====*/ Accordion.ChildWidgetProperties);

	return has("dojo-bidi") ? declare("dojox.mobile.Accordion", [Accordion, BidiAccordion]) : Accordion;
});


text:
import * as React from 'react';
import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs';
import * as pageProps from 'docs/data/material/migration/migration-v4/v5-component-changes.md?@mui/markdown';

export default function Page() {
  return <MarkdownDocs {...pageProps} />;
}


text:
cur
===

Create custom shell commands on the fly


text:
require "spec_helper"

describe Notifier do
  describe "sync_email" do
    let(:mail) { Notifier.sync_email([], 'admin@example.com') }

    it "renders the headers" do
      config = ""
      mail.subject.should eq("Camfed Data Import for #{Date.today.to_s}")
      mail.to.should eq(["admin@example.com"])
      mail.from.should eq(["camfed.notification@gmail.com"])
    end

  end

end


text:
<?php

namespace AppBundle\Security\Factory;

use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\SecurityFactoryInterface;
use Symfony\Component\Config\Definition\Builder\NodeDefinition;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\DefinitionDecorator;

final class OAuthSecurityFactory implements SecurityFactoryInterface
{
    const PROVIDER_NAME = 'strava_auth';

    public function create(ContainerBuilder $container, $id, $config, $userProvider, $defaultEntryPoint)
    {
        $name = self::PROVIDER_NAME;
        $providerId = "security.authentication.provider.$name.$id";
        $container
            ->setDefinition($providerId, new DefinitionDecorator("$name.security.authentication.provider"));

        $listenerId = "security.authentication.listener.$name.$id";
        $container
            ->setDefinition($listenerId, new DefinitionDecorator("$name.security.authentication.listener"));

        return array($providerId, $listenerId, $defaultEntryPoint);
    }

    public function getPosition()
    {
        return 'pre_auth';
    }

    public function getKey()
    {
        return self::PROVIDER_NAME;
    }

    public function addConfiguration(NodeDefinition $builder)
    {
        return;
    }
}


text:
import React, { Component } from "react";
import { connect } from "react-redux";

@connect( state => ( { developers: state.developers} ))
class DeveloperPage extends Component {

  static propTypes = {
    name: React.PropTypes.string,
    developers: React.PropTypes.object
  }

  render() {
    const { name, developers } = this.props;
    const developer = developers[name];
    return (

User page of { name }

          Twitter: <a href={ `https://twitter.com/${developer.twitter}` }>
            @{ developer.twitter }

          Github: <a href={ `https://github.com/${developer.github}` }>
            https://github.com/{ developer.github }

    );
  }
}

export default DeveloperPage;


text:
namespace edash_packager {

class MediaInfo;

namespace media {

class VodMediaInfoDumpMuxerListener : public MuxerListener {
 public:
  VodMediaInfoDumpMuxerListener(const std::string& output_file_name);
  ~VodMediaInfoDumpMuxerListener() override;

  /// @name MuxerListener implementation overrides.
  /// @{
  void OnEncryptionInfoReady(bool is_initial_encryption_info,
                             FourCC protection_scheme,
                             const std::vector<uint8_t>& default_key_id,
                             const std::vector<uint8_t>& iv,
                             const std::vector<ProtectionSystemSpecificInfo>&
                                 key_system_info) override;
  void OnMediaStart(const MuxerOptions& muxer_options,
                    const StreamInfo& stream_info,
                    uint32_t time_scale,
                    ContainerType container_type) override;
  void OnSampleDurationReady(uint32_t sample_duration) override;
  void OnMediaEnd(bool has_init_range,
                  uint64_t init_range_start,
                  uint64_t init_range_end,
                  bool has_index_range,
                  uint64_t index_range_start,
                  uint64_t index_range_end,
                  float duration_seconds,
                  uint64_t file_size) override;
  void OnNewSegment(const std::string& file_name,
                    uint64_t start_time,
                    uint64_t duration,
                    uint64_t segment_file_size) override;
  /// @}

  /// Write @a media_info to @a output_file_path in human readable format.
  /// @param media_info is the MediaInfo to write out.
  /// @param output_file_path is the path of the output file.
  /// @return true on success, false otherwise.
  // TODO(rkuroiwa): Move this to muxer_listener_internal and rename
  // muxer_listener_internal to muxer_listener_util.
  static bool WriteMediaInfoToFile(const MediaInfo& media_info,
                                   const std::string& output_file_path);

 private:

  std::string output_file_name_;
  scoped_ptr<MediaInfo> media_info_;

  bool is_encrypted_;
  // Storage for values passed to OnEncryptionInfoReady().
  FourCC protection_scheme_;
  std::string default_key_id_;
  std::vector<ProtectionSystemSpecificInfo> key_system_info_;

  DISALLOW_COPY_AND_ASSIGN(VodMediaInfoDumpMuxerListener);
};

}  // namespace media
}  // namespace edash_packager

#endif  // MEDIA_EVENT_VOD_MEDIA_INFO_DUMP_MUXER_LISTENER_H_


text:
class Thing {
    constructor() {

    }
}

export = Thing


text:
using UnityEngine;
using System.Collections;

public class FriendGameMaster : MonoBehaviour {

    public NewPlayerMove playerMove;
    public FriendMove friendMove;

    public bool playerSwitched;

	// Use this for initialization
	void Start ()
    {
        friendMove.enabled = false;

	}

	// Update is called once per frame
	void Update ()
    {
        if (Input.GetKeyDown(KeyCode.E))
        {
            playerSwitched = !playerSwitched;

        }

        if (playerSwitched)
        {
            playerMove.enabled = false;
            friendMove.enabled = true;
        }
        else if (!playerSwitched)
        {
            playerMove.enabled = true;
            friendMove.enabled = false;

        }

	}
}