text:
"use strict";
var Fiber = require('./fibers');
var util = require('util');
module.exports = Future;
Function.prototype.future = function() {
	var fn = this;
	var ret = function() {
		return new FiberFuture(fn, this, arguments);
	};
	ret.toString = function() {
		return '<<Future '+ fn+ '.future()>>';
	};
	return ret;
};

function Future() {}

/**
 * Wrap a node-style async function to return a future in place of using a callback.
 */
Future.wrap = function(fn, idx) {
	idx = idx === undefined ? fn.length - 1 : idx;
	return function() {
		var args = Array.prototype.slice.call(arguments);
		if (args.length > idx) {
			throw new Error('function expects no more than '+ idx+ ' arguments');
		}
		var future = new Future;
		args[idx] = future.resolver();
		fn.apply(this, args);
		return future;
	};
};

/**
 * Wait on a series of futures and then return. If the futures throw an exception this function
 * /won't/ throw it back. You can get the value of the future by calling get() on it directly. If
 * you want to wait on a single future you're better off calling future.wait() on the instance.
 */
Future.wait = function wait(/* ... */) {

	// Normalize arguments + pull out a FiberFuture for reuse if possible
	var futures = [], singleFiberFuture;
	for (var ii = 0; ii < arguments.length; ++ii) {
		var arg = arguments[ii];
		if (arg instanceof Future) {
			// Ignore already resolved fibers
			if (arg.isResolved()) {
				continue;
			}
			// Look for fiber reuse
			if (!singleFiberFuture && arg instanceof FiberFuture && !arg.started) {
				singleFiberFuture = arg;
				continue;
			}
			futures.push(arg);
		} else if (arg instanceof Array) {
			for (var jj = 0; jj < arg.length; ++jj) {
				var aarg = arg[jj];
				if (aarg instanceof Future) {
					// Ignore already resolved fibers
					if (aarg.isResolved()) {
						continue;
					}
					// Look for fiber reuse
					if (!singleFiberFuture && aarg instanceof FiberFuture && !aarg.started) {
						singleFiberFuture = aarg;
						continue;
					}
					futures.push(aarg);
				} else {
					throw new Error(aarg+ ' is not a future');
				}
			}
		} else {
			throw new Error(arg+ ' is not a future');
		}
	}

	// Resumes current fiber
	var fiber = Fiber.current;
	if (!fiber) {
		throw new Error('Can\'t wait without a fiber');
	}

	// Resolve all futures
	var pending = futures.length + (singleFiberFuture ? 1 : 0);
	function cb() {
		if (!--pending) {
			fiber.run();
		}
	}
	for (var ii = 0; ii < futures.length; ++ii) {
		futures[ii].resolve(cb);
	}

	// Reusing a fiber?
	if (singleFiberFuture) {
		singleFiberFuture.started = true;
		try {
			singleFiberFuture.return(
				singleFiberFuture.fn.apply(singleFiberFuture.context, singleFiberFuture.args));
		} catch(e) {
			singleFiberFuture.throw(e);
		}
		--pending;
	}

	// Yield this fiber
	if (pending) {
		Fiber.yield();
	}
};

Future.prototype = {
	/**
	 * Return the value of this future. If the future hasn't resolved yet this will throw an error.
	 */
	get: function() {
		if (!this.resolved) {
			throw new Error('Future must resolve before value is ready');
		} else if (this.error) {
			// Link the stack traces up
			var stack = {}, error = this.error instanceof Object ? this.error : new Error(this.error);
			var longError = Object.create(error);
			Error.captureStackTrace(stack, Future.prototype.get);
			Object.defineProperty(longError, 'stack', {
				get: function() {
					var baseStack = error.stack;
					if (baseStack) {
						baseStack = baseStack.split('\n');
						return [baseStack[0]]
							.concat(stack.stack.split('\n').slice(1))
							.concat('    - - - - -')
							.concat(baseStack.slice(1))
							.join('\n');
					} else {
						return stack.stack;
					}
				},
				enumerable: true,
			});
			throw longError;
		} else {
			return this.value;
		}
	},

	/**
	 * Mark this future as returned. All pending callbacks will be invoked immediately.
	 */
	"return": function(value) {
		if (this.resolved) {
			throw new Error('Future resolved more than once');
		}
		this.value = value;
		this.resolved = true;

		var callbacks = this.callbacks;
		if (callbacks) {
			delete this.callbacks;
			for (var ii = 0; ii < callbacks.length; ++ii) {
				try {
					var ref = callbacks[ii];
					if (ref[1]) {
						ref[1](value);
					} else {
						ref[0](undefined, value);
					}
				} catch(ex) {
					console.log(String(ex.stack || ex.message || ex));
					process.exit(1);
				}
			}
		}
	},

	/**
	 * Throw from this future as returned. All pending callbacks will be invoked immediately.
	 */
	"throw": function(error) {
		if (this.resolved) {
			throw new Error('Future resolved more than once');
		} else if (!error) {
			throw new Error('Must throw non-empty error');
		}
		this.error = error;
		this.resolved = true;

		var callbacks = this.callbacks;
		if (callbacks) {
			delete this.callbacks;
			for (var ii = 0; ii < callbacks.length; ++ii) {
				try {
					var ref = callbacks[ii];
					if (ref[1]) {
						ref[0].throw(error);
					} else {
						ref[0](error);
					}
				} catch(ex) {
					console.log(ex.stack || ex);
					process.exit(1);
				}
			}
		}
	},

	/**
	 * "detach" this future. Basically this is useful if you want to run a task in a future, you
	 * aren't interested in its return value, but if it throws you don't want the exception to be
	 * lost. If this fiber throws, an exception will be thrown to the event loop and node will
	 * probably fall down.
	 */
	detach: function() {
		this.resolve(function(err) {
			if (err) {
				throw err;
			}
		});
	},

	/**
	 * Returns whether or not this future has resolved yet.
	 */
	isResolved: function() {
		return this.resolved === true;
	},

	/**
	 * Returns a node-style function which will mark this future as resolved when called.
	 */
	resolver: function() {
		return function(err, val) {
			if (err) {
				this.throw(err);
			} else {
				this.return(val);
			}
		}.bind(this);
	},

	/**
	 * Waits for this future to resolve and then invokes a callback.
	 *
	 * If two arguments are passed, the first argument is a future which will be thrown to in the case
	 * of error, and the second is a function(val){} callback.
	 *
	 * If only one argument is passed it is a standard function(err, val){} callback.
	 */
	resolve: function(arg1, arg2) {
		if (this.resolved) {
			if (arg2) {
				if (this.error) {
					arg1.throw(this.error);
				} else {
					arg2(this.value);
				}
			} else {
				arg1(this.error, this.value);
			}
		} else {
			(this.callbacks = this.callbacks || []).push([arg1, arg2]);
		}
		return this;
	},

	/**
	 * Resolve only in the case of success
	 */
	resolveSuccess: function(cb) {
		this.resolve(function(err, val) {
			if (err) {
				return;
			}
			cb(val);
		});
		return this;
	},

	/**
	 * Propogate results to another future.
	 */
	proxy: function(future) {
		this.resolve(function(err, val) {
			if (err) {
				future.throw(err);
			} else {
				future.return(val);
			}
		});
	},

	/**
	 * Propogate only errors to an another future or array of futures.
	 */
	proxyErrors: function(futures) {
		this.resolve(function(err) {
			if (!err) {
				return;
			}
			if (futures instanceof Array) {
				for (var ii = 0; ii < futures.length; ++ii) {
					futures[ii].throw(err);
				}
			} else {
				futures.throw(err);
			}
		});
		return this;
	},

	/**
	 * Differs from its functional counterpart in that it actually resolves the future. Thus if the
	 * future threw, future.wait() will throw.
	 */
	wait: function() {
		if (this.isResolved()) {
			return this.get();
		}
		Future.wait(this);
		return this.get();
	},
};

/**
 * A function call which loads inside a fiber automatically and returns a future.
 */
function FiberFuture(fn, context, args) {
	this.fn = fn;
	this.context = context;
	this.args = args;
	this.started = false;
	var that = this;
	process.nextTick(function() {
		if (!that.started) {
			that.started = true;
			Fiber(function() {
				try {
					that.return(fn.apply(context, args));
				} catch(e) {
					that.throw(e);
				}
			}).run();
		}
	});
}
util.inherits(FiberFuture, Future);


text:
include(LibFindMacros)

# Use pkg-config to get hints about paths
libfind_pkg_check_modules(FFTW3F_PKGCONF fftw3f)

# attempt to find static library first if this is set
if(FFTW3F_STATIC_LIBRARY)
  set(FFTW3F_STATIC libfftw3f.a)
endif(FFTW3F_STATIC_LIBRARY)

# additional hints
if(MINGW)
  set(CMAKE_PREFIX_PATH ${CMAKE_PREFIX_PATH} C:/Mingw)
endif(MINGW)

if(MSVC)
  set(CMAKE_PREFIX_PATH ${CMAKE_PREFIX_PATH} D:/devlib/vc/fftw)
endif(MSVC)

# Include dir
find_path(FFTW3F_INCLUDE_DIR
  NAMES fftw3.h
  PATHS ${FFTW3F_PKGCONF_INCLUDE_DIRS}
)

# Finally the library itself
find_library(FFTW3F_LIBRARY
  NAMES ${FFTW3F_STATIC} fftw3f libfftw3f-3.lib
  PATHS ${FFTW3F_PKGCONF_LIBRARY_DIRS}
)

# Set the include dir variables and the libraries and let libfind_process do the rest.
# NOTE: Singular variables for this library, plural for libraries this this lib depends on.
set(FFTW3F_PROCESS_INCLUDES FFTW3F_INCLUDE_DIR)
set(FFTW3F_PROCESS_LIBS FFTW3F_LIBRARY)
libfind_process(FFTW3F)

redpajama_set_name: RedPajamaGithub


text:
from __future__ import absolute_import

import logging

from django.db import DataError, IntegrityError, router, transaction
from django.db.models import F

from sentry import eventstream
from sentry.app import tsdb
from sentry import similarity
from sentry.tasks.base import instrumented_task, track_group_async_operation

logger = logging.getLogger("sentry.merge")
delete_logger = logging.getLogger("sentry.deletions.async")

EXTRA_MERGE_MODELS = []

@instrumented_task(
    name="sentry.tasks.merge.merge_groups",
    queue="merge",
    default_retry_delay=60 * 5,
    max_retries=None,
)
@track_group_async_operation
def merge_groups(
    from_object_ids=None,
    to_object_id=None,
    transaction_id=None,
    recursed=False,
    eventstream_state=None,
    **kwargs
):
    # TODO(mattrobenolt): Write tests for all of this
    from sentry.models import (
        Activity,
        Group,
        GroupAssignee,
        GroupEnvironment,
        GroupHash,
        GroupRuleStatus,
        GroupSubscription,
        Environment,
        EventAttachment,
        UserReport,
        GroupRedirect,
        GroupMeta,
        get_group_with_redirect,
    )

    if not (from_object_ids and to_object_id):
        logger.error("group.malformed.missing_params", extra={"transaction_id": transaction_id})
        return False

    # Operate on one "from" group per task iteration. The task is recursed
    # until each group has been merged.
    from_object_id = from_object_ids[0]

    try:
        new_group, _ = get_group_with_redirect(to_object_id)
    except Group.DoesNotExist:
        logger.warn(
            "group.malformed.invalid_id",
            extra={"transaction_id": transaction_id, "old_object_ids": from_object_ids},
        )
        return False

    if not recursed:
        logger.info(
            "merge.queued",
            extra={
                "transaction_id": transaction_id,
                "new_group_id": new_group.id,
                "old_group_ids": from_object_ids,
                # TODO(jtcunning): figure out why these are full seq scans and/or alternative solution
                # 'new_event_id': getattr(new_group.event_set.order_by('-id').first(), 'id', None),
                # 'old_event_id': getattr(group.event_set.order_by('-id').first(), 'id', None),
                # 'new_hash_id': getattr(new_group.grouphash_set.order_by('-id').first(), 'id', None),
                # 'old_hash_id': getattr(group.grouphash_set.order_by('-id').first(), 'id', None),
            },
        )

    try:
        group = Group.objects.select_related("project").get(id=from_object_id)
    except Group.DoesNotExist:
        from_object_ids.remove(from_object_id)

        logger.warn(
            "group.malformed.invalid_id",
            extra={"transaction_id": transaction_id, "old_object_id": from_object_id},
        )
    else:
        model_list = tuple(EXTRA_MERGE_MODELS) + (
            Activity,
            GroupAssignee,
            GroupEnvironment,
            GroupHash,
            GroupRuleStatus,
            GroupSubscription,
            EventAttachment,
            UserReport,
            GroupRedirect,
            GroupMeta,
        )

        has_more = merge_objects(
            model_list, group, new_group, logger=logger, transaction_id=transaction_id
        )

        if not has_more:
            # There are no more objects to merge for *this* "from" group, remove it
            # from the list of "from" groups that are being merged, and finish the
            # work for this group.
            from_object_ids.remove(from_object_id)

            similarity.merge(group.project, new_group, [group], allow_unsafe=True)

            environment_ids = list(
                Environment.objects.filter(projects=group.project).values_list("id", flat=True)
            )

            for model in [tsdb.models.group]:
                tsdb.merge(
                    model,
                    new_group.id,
                    [group.id],
                    environment_ids=environment_ids
                    if model in tsdb.models_with_environment_support
                    else None,
                )

            for model in [tsdb.models.users_affected_by_group]:
                tsdb.merge_distinct_counts(
                    model,
                    new_group.id,
                    [group.id],
                    environment_ids=environment_ids
                    if model in tsdb.models_with_environment_support
                    else None,
                )

            for model in [
                tsdb.models.frequent_releases_by_group,
                tsdb.models.frequent_environments_by_group,
            ]:
                tsdb.merge_frequencies(
                    model,
                    new_group.id,
                    [group.id],
                    environment_ids=environment_ids
                    if model in tsdb.models_with_environment_support
                    else None,
                )

            previous_group_id = group.id

            with transaction.atomic():
                GroupRedirect.create_for_group(group, new_group)
                group.delete()
            delete_logger.info(
                "object.delete.executed",
                extra={
                    "object_id": previous_group_id,
                    "transaction_id": transaction_id,
                    "model": Group.__name__,
                },
            )

            new_group.update(
                # TODO(dcramer): ideally these would be SQL clauses
                first_seen=min(group.first_seen, new_group.first_seen),
                last_seen=max(group.last_seen, new_group.last_seen),
            )
            try:
                # it's possible to hit an out of range value for counters
                new_group.update(
                    times_seen=F("times_seen") + group.times_seen,
                    num_comments=F("num_comments") + group.num_comments,
                )
            except DataError:
                pass

    if from_object_ids:
        # This task is recursed until `from_object_ids` is empty and all
        # "from" groups have merged into the `to_group_id`.
        merge_groups.delay(
            from_object_ids=from_object_ids,
            to_object_id=to_object_id,
            transaction_id=transaction_id,
            recursed=True,
            eventstream_state=eventstream_state,
        )
    elif eventstream_state:
        # All `from_object_ids` have been merged!
        eventstream.end_merge(eventstream_state)

def _get_event_environment(event, project, cache):
    from sentry.models import Environment

    environment_name = event.get_tag("environment")

    if environment_name not in cache:
        try:
            environment = Environment.get_for_organization_id(
                project.organization_id, environment_name
            )
        except Environment.DoesNotExist:
            logger.warn(
                "event.environment.does_not_exist",
                extra={"project_id": project.id, "environment_name": environment_name},
            )
            environment = Environment.get_or_create(project, environment_name)

        cache[environment_name] = environment

    return cache[environment_name]

def merge_objects(models, group, new_group, limit=1000, logger=None, transaction_id=None):
    has_more = False
    for model in models:
        all_fields = [f.name for f in model._meta.get_fields()]

        # Not all models have a 'project' or 'project_id' field, but we make a best effort
        # to filter on one if it is available.
        # Also note that all_fields doesn't contain f.attname
        # (django ForeignKeys have only attribute "attname" where "_id" is implicitly appended)
        # but we still want to check for "project_id" because some models define a project_id bigint.
        has_project = "project_id" in all_fields or "project" in all_fields

        if has_project:
            project_qs = model.objects.filter(project_id=group.project_id)
        else:
            project_qs = model.objects.all()

        has_group = "group" in all_fields
        if has_group:
            queryset = project_qs.filter(group=group)
        else:
            queryset = project_qs.filter(group_id=group.id)

        for obj in queryset[:limit]:
            try:
                with transaction.atomic(using=router.db_for_write(model)):
                    if has_group:
                        project_qs.filter(id=obj.id).update(group=new_group)
                    else:
                        project_qs.filter(id=obj.id).update(group_id=new_group.id)
            except IntegrityError:
                delete = True
            else:
                delete = False

            if delete:
                # Before deleting, we want to merge in counts
                if hasattr(model, "merge_counts"):
                    obj.merge_counts(new_group)

                obj_id = obj.id
                obj.delete()

                if logger is not None:
                    delete_logger.debug(
                        "object.delete.executed",
                        extra={
                            "object_id": obj_id,
                            "transaction_id": transaction_id,
                            "model": model.__name__,
                        },
                    )
            has_more = True

        if has_more:
            return True
    return has_more


text:
Dashboard application useful for showcasing [CrossFit](http://journal.crossfit.com) WOD results using data from [Beyond The Whiteboard](http://beyondthewhiteboard.com) and powered by [Dashing.io](http://dashing.io).

## Setup / Install

### 1. Define the following environment variables:

* BTWB_USERNAME
* BTWB_PASSWORD
* BTWB_BOX (1-example-crossfit)

> The Girls Dashboard needs your login credentials in order to query BTWB information specific to your box.

### 2. Determine which Girls and Heros you want to highlight by editing the following YAML files:

* girls.yml
* heros.yml

### 3. Setup and Deploy to Heroku as instructed at [Dashing.io](http://shopify.github.com/dashing).

## Example

I built The Girls Dashboard for [SnoRidge CrossFit](http://srcf.joecode.com). I've configured the dashboard to work best on a 1080p LCD display.  [Enjoy](http://srcf.joecode.com).

## Technology

* [http://shopify.github.com/dashing](http://shopify.github.com/dashing)
* [https://github.com/QubitProducts/dashing-contrib](https://github.com/QubitProducts/dashing-contrib)
* [http://www.nokogiri.org](http://www.nokogiri.org)
* [https://github.com/jnunemaker/httparty](https://github.com/jnunemaker/httparty)


text:
namespace Smellyriver.TankInspector.Modeling
{
	internal class InventorSkill : CrewSkill
    {
        public const string SkillDomain = "crewSkill:inventor";
        public const string RadioDistanceFactorSkillKey = "radioDistanceFactor";

        public override DuplicatedCrewSkillPolicy DuplicatedCrewSkillPolicy => DuplicatedCrewSkillPolicy.Highest;

	    public override string[] EffectiveDomains => new[] { SkillDomain };

	    public override CrewRoleType CrewRole => CrewRoleType.Radioman;
	    protected override CrewSkillType Type => CrewSkillType.Skill;

	    public InventorSkill(Database database)
            : base(database)
        {

        }

        protected override void Execute(ModificationContext context, double level)
        {
            context.SetValue(this.EffectiveDomains[0], RadioDistanceFactorSkillKey, this.Parameters["radioDistanceFactorPerLevel"] * level);
        }

        protected override void Clear(ModificationContext context)
        {
            context.SetValue(this.EffectiveDomains[0], RadioDistanceFactorSkillKey, 0);
        }
    }
}


text:
@javax.xml.bind.annotation.XmlSchema(namespace = "http://core.nip.nibss/")
package ng.com.nibss.nip.core;


text:
This project provides an interceptor to enrich event body with custom data. The implementation consist of:

- EnrichedEventBody: represents enriched event body. The enriched event will have 2 attributes: extraData and message.
    extraData will be fed with the custom data set in the configuration file (see below) while message will preserve
    the original event body string. The enriched event is then serialized to a JSON object.
- EnrichmentInterceptor: implements the Flume interceptor interface. The intercept() method will add the custom data
    to the original event body and serialize it back as a JSON string.
- JSONStringSerializer: the JSON serializer

## How to use

Clone the project:

```sh
$ git clone https://github.com/keedio/flume-enrichment-interceptor-skeleton.git
```

Build with Maven:

```sh
$ mvn clean install
```

The jar file will be installed in your local maven repository and can be found in the target/ subdirectory also. Add it
to your Flume classpath.

Configure your agent to use this interceptor, setting the following options in your configuration file:

```ini
# interceptor
a1.sources.r1.interceptors = i1
a1.sources.r1.interceptors.i1.type = org.keedio.flume.interceptor.enrichment.interceptor.EnrichmentInterceptor$EnrichmentBuilder
# Full path to the properties file that contains the extra data to enrich the event with
a1.sources.r1.interceptors.i1.properties.filename = /path/to/filename.properties
# The format of incoming events ( DEFAULT | enriched )
a1.sources.r1.interceptors.i1.event.type = DEFAULT

# A map of regexps, where each regexp may be composed of Named captured groups according syntax (?<name>regex).
# On applying regexps to the message, the first match will enrich de data.
a1.sources.r1.interceptors.i1.custom.regexp.1 = (?<name>regex)
a1.sources.r1.interceptors.i1.custom.regexp.2 = (?<nameA>regex)\\METACHARACTER(?<nameB>regex)\\..
.......................
a1.sources.r1.interceptors.i1.custom.regexp.n =

# In case that the input is a (optionally multiple) key-value pair string, there's no need to use named groups. It also supports regexps where one group will act as the key (default index: 1), and other group will act as the value (default index: 2)
a1.sources.r1.interceptors.i1.custom.regexp.1 = (\w+)=([^\"\s]+)
a1.sources.r1.interceptors.i1.custom.regexp.2 = (\w+)=[\"]([^\"]+)[\"]
.......................
a1.sources.r1.interceptors.i1.custom.regexp.n =
# If there are multiple regexps, the capture groups for key and value will be the same for all
# The capture group indexes for key and value can be modified by the next configuration
a1.sources.r1.interceptors.i1.custom.group.regexp.key = 1
a1.sources.r1.interceptors.i1.custom.group.regexp.value = 2

# If the regexps are using some reserved characters which are wrongly handled by some tool administrator (for example, Ambari with character "=" inside a property value), there's the possibility to encode the regexps in order to avoid problems
# In order to be recognized as UrlEncoded, the property "regexp.is.urlencoded" must be true
a1.sources.r1.interceptors.i1.custom.regexp.1 = %28%5Cw%2B%29%3D%28%5B%5E%5C%22%5Cs%5D%2B%29
a1.sources.r1.interceptors.i1.custom.regexp.2 = %28%5Cw%2B%29%3D%5B%5C%22%5D%28%5B%5E%5C%22%5D%2B%29%5B%5C%22%5D
a1.sources.r1.interceptors.i1.regexp.is.urlencoded = true
```

Example of custom properties:
```ini
hostname = localhost
domain = localdomain
```

The enriched event body will contain:
```json
{
 "extraData":{"hostname": "localhost", "domain": "localdomain"},
 "message": "the original body string"
}
```

Besides the properties of the file, the fields extracted by regexp are added.
The fields of the first regexp having correspondence with the log entry are
appended as new pairs in extradata and if any correspondence regexp has no match,
nothing is added:

Example of regexp:
```ini
a1.sources.r1.interceptors.i1.custom.regexp.1 = (?<date>\\d{4}-\\d{2}-\\d{2}+)\\s(?<time>\\d{2}:\\d{2}:\\d{2}+)\\s
```
Example of log to match:
```ini
"2015-04-23 07:16:08 (whatever)"
```

The enriched event body will contain two new pairs in the extradata:
```json
{
 "extraData":{"hostname": "localhost", "domain": "localdomain", "date": "2015-04-23", "time": "07:16:08"},
 "message": "the original body string"
}
```

Thanks to tony19: https://github.com/tony19/named-regexp :

Althoug Java 7 allows named captured groups, flume-enrich-interceptor is using named-regexp 0.2.3 tony19's library because it adds
interesting features, example  (?\<foo_foo\>regex) or (?\<foo foo\>regex) are not allowed in Java 7.

## Needed dependencies

You need to deploy the following jars in order to use this interceptor:

* http://search.maven.org/remotecontent?filepath=com/github/tony19/named-regexp/0.2.3/named-regexp-0.2.3.jar
* http://search.maven.org/remotecontent?filepath=com/googlecode/juniversalchardet/juniversalchardet/1.0.3/juniversalchardet-1.0.3.jar
* http://search.maven.org/remotecontent?filepath=org/codehaus/jackson/jackson-mapper-asl/1.9.13/jackson-mapper-asl-1.9.13.jar
* http://search.maven.org/remotecontent?filepath=org/codehaus/jackson/jackson-core-asl/1.9.13/jackson-core-asl-1.9.13.jar

## Changes from version 0.0.1

Update package's name convention.
Added regexp in flume's context.

EnrichedEventBody.message is now a String (was byte[]).


text:
<?php

class MySQLiHelpers {
	private $db = null;

	public function __construct(\mysqli $conn) {
		$this->db = $conn;
	}

	/**
	 * helper function for MySQLi db queries
	 *
	 * @param string $query
	 * @param string|null $types
	 * @param array|null $params
	 * @param bool $one
	 * @return mixed an associative array of results for selects, affected rows for updates, insert_id for inserts and null on any error
	 */
	public function query(string $query, string $types = null, array $params = null, bool $single = false) {
		$query = trim($query);
		try {
			if (!$this->db) {
				throw new \Exception('no database connection established');
			}

			if (($types || $params) && strlen($types) !== count($params)) {
				throw new \Exception('db query error: type/param mismatch');
			}

			$stmt = $this->db->prepare($query);

			if (!$stmt) {
				throw new \Exception($this->db->error);
			}

			if (!empty($types) && !empty($params)) {
				$stmt->bind_param($types, ...$params);
			}

			$stmt->execute();

			if (preg_match('/^INSERT/i', $query)) {
				$data = $stmt->insert_id;
			} else if (preg_match('/^SELECT/i', $query)) {
				$data = $single
					? $stmt->get_result()->fetch_array(MYSQLI_ASSOC)
					: $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
			} else {
				$data = $stmt->affected_rows;
			}

			$stmt->close();
			return $data;
		} catch (\Exception $e) {
			error_log($e->getMessage() . $query);
		}
		return null;
	}

	// get a single result as an associative array for selects
	public function queryOne(string $query, string $types = null, array $params = null) {
		return $this->query($query, $types, $params, true);
	}
}


text:
body, ul {
    font-size: 16px;
    font-family: "Times New Roman";
    margin: 0px;
    padding: 0px;
}
#root .avengers .avenger .preview {
    display: none;
    height: 225px;
}
.avengers {
    list-style-type: none;
}
#root .avengers .avenger {
    float: left;
    display: block;
    position: relative;
    font-weight: bold;
    padding-left: 16px;
    padding-right: 14.5px;
    padding-top: 10px;
    padding-bottom: 11px;
    border: 3px solid black;
    border-right: none;
    border-top-left-radius: 13px;
    border-collapse: collapse;
}
#root .avengers .avenger:last-child {
    border-right: 3px solid black;
}
#root .avengers .avenger:hover .preview {
    display: inline-block;
    left: 0px;
    top: 44px;
    padding: 20px;
    position: fixed;
    border-bottom: 3px solid black;
    border-left: 3px solid black;
    border-right: 3px solid black;
    background-color: #CCCCCC;
    width: 590px;
}
#root .avengers .avenger .skills {
    float: right;
    display: block;
    position: absolute;
    top: 38px;
    right: 35px;
    list-style-type: none;
    font-size: 20px;
    margin-top: 0px;
    padding-bottom: 0px;
    text-transform: capitalize;
}
#root .avengers .avenger li {
    display: block;
    font-size: 20px;
    padding: 20px;
    font-weight: normal;
}
#root .avengers .avenger li:nth-child(odd) {
    text-align: center;
}
#root .avengers .avenger:last-of-type .skills {
    right: 60px;
}
#root .avengers .avenger:hover {
    background-color: #CCCCCC;
    border-right: 3px solid;
    display: block;
    border-bottom-color: #FFFFFF;
}
#root .avengers .name:hover {
    text-decoration: underline;
}
#root .avengers .avenger .preview img {
    width: 400px;
    height: 225px;
    display: inline-block;
    border: 5px solid #FFFFFF;
    border-radius: 5px;
    margin-top: -5px;
}
#root > ul > li > div > ul> li:hover {
    text-decoration: underline;
}


text:
require 'spec_helper'

include TwitterCldr::Formatters::Plurals

describe Rules do
  describe "#get_resource" do
    it "calls eval on the hash that gets returned, lambdas and all" do
      result = Rules.send(:get_resource, :ru)

      result.should include(:keys, :rule)
      result[:keys].size.should == 4
      result[:rule].should be_a(Proc)
    end
  end

  describe "#rule_for" do
    it "returns :one for English 1, :other for everything else" do
      Rules.rule_for(1, :en).should == :one
      [5, 9, 10, 20, 60, 99, 100, 103, 141].each do |num|
        Rules.rule_for(num, :en).should == :other
      end
    end

    it "returns the correct values for Russian rules" do
      rules = {
          :one  => [1, 101],
          :few  => [2, 3, 4, 102],
          :many => ((5..11).to_a + [111])
      }

      rules.each do |rule, examples|
        examples.each { |n| Rules.rule_for(n, :ru).should == rule }
      end
    end

    it "returns :other if there's an error" do
      stub(Rules).get_resource { lambda { raise "Jelly beans" } }
      Rules.rule_for(1, :en).should == :other
      Rules.rule_for(1, :ru).should == :other
    end
  end

  describe "#all_for" do
    it "returns a list of all applicable rules for the given locale" do
      Rules.all_for(:en).should =~ [:one, :other]
      Rules.all_for(:ru).should =~ [:one, :few, :many, :other]
    end

    it "returns nil on error" do
      stub(Rules).get_resource { lambda { raise "Jelly beans" } }
      Rules.all_for(:en).should be_nil
      Rules.all_for(:ru).should be_nil
    end
  end

  describe "#all" do
    it "gets rules for the default locale (usually supplied by FastGettext)" do
      mock(TwitterCldr).locale { :ru }
      Rules.all.should =~ [:one, :few, :many, :other]
    end
  end
end


text:
from __future__ import division, absolute_import, division
from sklearn.preprocessing import LabelEncoder
from .base import _validate_X_y_ratio_classes
from ..utils import get_random_state, DEFAULT_SEED
from . import base
import numpy as np

__all__ = [
    'over_sample_balance'
]

def over_sample_balance(X, y, balance_ratio=0.2, random_state=DEFAULT_SEED):
    """One strategy for balancing data is to over-sample the minority class until it is
    represented at the prescribed ``balance_ratio``. While there is significant literature
    to show that this is not the best technique, and can sometimes lead to over-fitting, there
    are instances wherein it works quite well.

    Parameters
    ----------
    X : array-like, shape (n_samples, n_features)
        Training vectors as real numbers, where ``n_samples`` is the number of
        samples and ``n_features`` is the number of input features.

    y : array-like, shape (n_samples,)
        Training labels as integers, where ``n_samples`` is the number of samples.
        ``n_samples`` should be equal to the ``n_samples`` in ``X``.

    balance_ratio : float, optional (default=0.2)
        The minimum acceptable ratio of $MINORITY_CLASS : $MAJORITY_CLASS representation,
        where 0 < ``ratio`` <= 1

    random_state : int or None, optional (default=None)
        The seed to construct the random state to generate random selections.
    """
    random_state = get_random_state(random_state).state

    # validate before copying arrays around...
    X, y, n_classes, present_classes, \
        counts, majority_label, target_count = _validate_X_y_ratio_classes(X, y, balance_ratio)

    # encode y, in case they are not numeric (we need them to be for np.ones)
    le = LabelEncoder()
    le.fit(present_classes)
    y_transform = le.transform(y)  # make numeric

    # we'll vstack/concatenate to these
    out_X, out_y = X.copy(), y_transform.copy()

    # iterate the present classes
    for label in present_classes:
        if label == majority_label:
            continue

        # get the transformed label
        label_transform = le.transform([label])[0]

        while True:
            # use the out_X, out_y copies. Since we're oversamping,
            # it doesn't matter if we're drawing from the out_X matrix.
            # also, this way we can better keep track of how many we've drawn.
            mask = out_y == label_transform
            n_req = target_count - mask.sum()

            # terminal case
            if n_req == 0:
                break

            # draw a sample, take first n_req:
            idcs = np.arange(out_X.shape[0])[mask]  # get the indices, mask them
            sample = out_X[random_state.permutation(idcs), :][:n_req]

            # vstack
            out_X = np.vstack([out_X, sample])

            # concatenate. Use sample length, since it might be < n_req
            out_y = np.concatenate([out_y, np.ones(sample.shape[0], dtype=np.int16) * label_transform])

    return out_X, le.inverse_transform(out_y)


text:
""".. Ignore pydocstyle D400.

=====================
Elastic Index Builder
=====================

"""
import inspect
import os
import re
import uuid
from importlib import import_module

from django.apps import apps
from django.db import models
from django.db.models.fields.related_descriptors import ManyToManyDescriptor
from django.db.models.signals import m2m_changed, post_delete, post_save, pre_delete

from resolwe.test.utils import is_testing

from .composer import composer
from .indices import BaseIndex
from .utils import prepare_connection

__all__ = (
    'index_builder',
    'ManyToManyDependency',
)

# UUID used in tests to make sure that no index is re-used.
TESTING_UUID = str(uuid.uuid4())

class BuildArgumentsCache:
    """Cache for storing arguments for index builder.

    If set value contains a queryset, it is evaluated and later
    recreated to prevent influence from database changes.

    """

    def __init__(self):
        """Initialize cache."""
        self._cache = {}

    def _get_cache_key(self, obj):
        """Derive cache key for given object."""
        if obj is not None:
            return obj.pk

        return obj

    def _clean_cache(self, obj):
        """Clean cache."""
        del self._cache[self._get_cache_key(obj)]

    def set(self, obj, build_kwargs):
        """Set cached value."""
        assert self._get_cache_key(obj) not in self._cache

        if build_kwargs is None:
            build_kwargs = {}

        cached = {}
        if 'queryset' in build_kwargs:
            cached = {
                'model': build_kwargs['queryset'].model,
                'pks': list(build_kwargs['queryset'].values_list('pk', flat=True)),
            }

        elif 'obj' in build_kwargs:
            cached = {
                'obj': build_kwargs['obj'],
            }

        self._cache[self._get_cache_key(obj)] = cached

    def take(self, obj):
        """Get cached value and clean cache."""
        cached = self._cache[self._get_cache_key(obj)]
        build_kwargs = {}

        if 'model' in cached and 'pks' in cached:
            build_kwargs['queryset'] = cached['model'].objects.filter(pk__in=cached['pks'])

        elif 'obj' in cached:
            if cached['obj'].__class__.objects.filter(pk=cached['obj'].pk).exists():
                build_kwargs['obj'] = cached['obj']
            else:
                # Object was deleted in the meantime.
                build_kwargs['queryset'] = cached['obj'].__class__.objects.none()

        self._clean_cache(obj)

        return build_kwargs

class ElasticSignal:
    """Class for creating signals to update/create indexes.

    To register the signal, add the following code::

        signal = ElasticSignal(<my_signal>, <method_name>)
        signal.connect(<signal_type>, [sender=<my_model>])

    You may later disconnect the signal by calling::

        signal.disconnect()

    ``signal type`` can be i.e. ``django.db.models.signals.pre_save``.

    """

    def __init__(self, index, method_name, pass_kwargs=False):
        """Initialize signal."""
        self.index = index
        self.method_name = method_name
        self.pass_kwargs = pass_kwargs
        self.connections = []

    def connect(self, signal, **kwargs):
        """Connect a specific signal type to this receiver."""
        signal.connect(self, **kwargs)
        self.connections.append((signal, kwargs))

    def disconnect(self):
        """Disconnect all connected signal types from this receiver."""
        for signal, kwargs in self.connections:
            signal.disconnect(self, **kwargs)

    def __call__(self, sender, instance, **kwargs):
        """Process signal."""
        method = getattr(self.index, self.method_name)
        if self.pass_kwargs:
            method(obj=instance, **kwargs)
        else:
            method(obj=instance)

class Dependency:
    """Abstract base class for index model dependencies."""

    def __init__(self, model):
        """Construct dependency."""
        self.model = model
        self.index = None

    def connect(self, index):
        """Connect signals needed for dependency updates.

        Pre- and post-delete signals have to be handled separately, as:

          * in the pre-delete signal we have the information which
            objects to rebuild, but affected relations are still
            presented, so rebuild would reflect in the wrong (outdated)
            indices
          * in the post-delete signal indices can be rebuild corectly,
            but there is no information which objects to rebuild, as
            affected relations were already deleted

        To bypass this, list of objects should be stored in the
        pre-delete signal indexing should be triggered in the
        post-delete signal.
        """
        self.index = index

        signal = ElasticSignal(self, 'process', pass_kwargs=True)
        signal.connect(post_save, sender=self.model)
        signal.connect(pre_delete, sender=self.model)

        pre_delete_signal = ElasticSignal(self, 'process_predelete', pass_kwargs=True)
        pre_delete_signal.connect(pre_delete, sender=self.model)

        post_delete_signal = ElasticSignal(self, 'process_delete', pass_kwargs=True)
        post_delete_signal.connect(post_delete, sender=self.model)

        return [signal, pre_delete_signal, post_delete_signal]

    def process(self, obj, **kwargs):
        """Process signals from dependencies."""
        raise NotImplementedError

    def process_predelete(self, obj, **kwargs):
        """Process signals from dependencies."""
        raise NotImplementedError

    def process_delete(self, obj, **kwargs):
        """Process signals from dependencies."""
        raise NotImplementedError

class ManyToManyDependency(Dependency):
    """Dependency on a many-to-many relation."""

    def __init__(self, field):
        """Construct m2m dependency."""
        # We use None as the model as we cannot determine it until assigned to an index.
        super().__init__(None)

        self.accessor = None
        self.field = field
        # Cache for pre/post-delete signals.
        self.delete_cache = BuildArgumentsCache()
        # Cache for pre/post-remove action in m2m_changed signal.
        self.remove_cache = BuildArgumentsCache()

    def connect(self, index):
        """Connect signals needed for dependency updates."""
        # Determine which model is the target model as either side of the relation
        # may be passed as `field`.
        if index.object_type == self.field.rel.model:
            self.model = self.field.rel.related_model
            self.accessor = self.field.rel.field.attname
        else:
            self.model = self.field.rel.model
            if self.field.rel.symmetrical:
                # Symmetrical m2m relation on self has no reverse accessor.
                raise NotImplementedError(
                    'Dependencies on symmetrical M2M relations are not supported due '
                    'to strange handling of the m2m_changed signal which only makes '
                    'half of the relation visible during signal execution. For now you '
                    'need to use symmetrical=False on the M2M field definition.'
                )
            else:
                self.accessor = self.field.rel.get_accessor_name()

        # Connect signals.
        signals = super().connect(index)

        m2m_signal = ElasticSignal(self, 'process_m2m', pass_kwargs=True)
        m2m_signal.connect(m2m_changed, sender=self.field.through)
        signals.append(m2m_signal)

        # If the relation has a custom through model, we need to subscribe to it.
        if not self.field.rel.through._meta.auto_created:  # pylint: disable=protected-access
            signal = ElasticSignal(self, 'process_m2m_through_save', pass_kwargs=True)
            signal.connect(post_save, sender=self.field.rel.through)
            signals.append(signal)

            signal = ElasticSignal(self, 'process_m2m_through_pre_delete', pass_kwargs=True)
            signal.connect(pre_delete, sender=self.field.rel.through)
            signals.append(signal)

            signal = ElasticSignal(self, 'process_m2m_through_post_delete', pass_kwargs=True)
            signal.connect(post_delete, sender=self.field.rel.through)
            signals.append(signal)

        return signals

    def filter(self, obj, update_fields=None):
        """Determine if dependent object should be processed.

        If ``False`` is returned, processing of the dependent object will
        be aborted.
        """
        pass

    def _filter(self, objects, **kwargs):
        """Determine if dependent object should be processed."""
        for obj in objects:
            if self.filter(obj, **kwargs) is False:
                return False

        return True

    def _get_build_kwargs(self, obj, pk_set=None, action=None, update_fields=None, reverse=None, **kwargs):
        """Prepare arguments for rebuilding indices."""
        if action is None:
            # Check filter before rebuilding index.
            if not self._filter([obj], update_fields=update_fields):
                return

            queryset = getattr(obj, self.accessor).all()

            # Special handling for relations to self.
            if self.field.rel.model == self.field.rel.related_model:
                queryset = queryset.union(getattr(obj, self.field.rel.get_accessor_name()).all())

            return {'queryset': queryset}
        else:
            # Update to relation itself, only update the object in question.
            if self.field.rel.model == self.field.rel.related_model:
                # Special case, self-reference, update both ends of the relation.
                pks = set()
                if self._filter(self.model.objects.filter(pk__in=pk_set)):
                    pks.add(obj.pk)

                if self._filter(self.model.objects.filter(pk__in=[obj.pk])):
                    pks.update(pk_set)

                return {'queryset': self.index.object_type.objects.filter(pk__in=pks)}
            elif isinstance(obj, self.model):
                # Need to switch the role of object and pk_set.
                result = {'queryset': self.index.object_type.objects.filter(pk__in=pk_set)}
                pk_set = {obj.pk}
            else:
                result = {'obj': obj}

            if action != 'post_clear':
                # Check filter before rebuilding index.
                if not self._filter(self.model.objects.filter(pk__in=pk_set)):
                    return

            return result

    def process_predelete(self, obj, pk_set=None, action=None, update_fields=None, **kwargs):
        """Render the queryset of influenced objects and cache it."""
        build_kwargs = self._get_build_kwargs(obj, pk_set, action, update_fields, **kwargs)
        self.delete_cache.set(obj, build_kwargs)

    def process_delete(self, obj, pk_set=None, action=None, update_fields=None, **kwargs):
        """Recreate queryset from the index and rebuild the index."""
        build_kwargs = self.delete_cache.take(obj)

        if build_kwargs:
            self.index.build(**build_kwargs)

    def process_m2m(self, obj, pk_set=None, action=None, update_fields=None, cache_key=None, **kwargs):
        """Process signals from dependencies.

        Remove signal is processed in two parts. For details see:
        :func:`~Dependency.connect`
        """
        if action not in (None, 'post_add', 'pre_remove', 'post_remove', 'post_clear'):
            return

        if action == 'post_remove':
            build_kwargs = self.remove_cache.take(cache_key)
        else:
            build_kwargs = self._get_build_kwargs(obj, pk_set, action, update_fields, **kwargs)

        if action == 'pre_remove':
            self.remove_cache.set(cache_key, build_kwargs)
            return

        if build_kwargs:
            self.index.build(**build_kwargs)

    def _process_m2m_through(self, obj, action):
        """Process custom M2M through model actions."""
        source = getattr(obj, self.field.rel.field.m2m_field_name())
        target = getattr(obj, self.field.rel.field.m2m_reverse_field_name())

        pk_set = set()
        if target:
            pk_set.add(target.pk)

        self.process_m2m(source, pk_set, action=action, reverse=False, cache_key=obj)

    def process_m2m_through_save(self, obj, created=False, **kwargs):
        """Process M2M post save for custom through model."""
        # We are only interested in signals that establish relations.
        if not created:
            return

        self._process_m2m_through(obj, 'post_add')

    def process_m2m_through_pre_delete(self, obj, **kwargs):
        """Process M2M pre delete for custom through model."""
        self._process_m2m_through(obj, 'pre_remove')

    def process_m2m_through_post_delete(self, obj, **kwargs):
        """Process M2M post delete for custom through model."""
        self._process_m2m_through(obj, 'post_remove')

    def process(self, obj, pk_set=None, action=None, update_fields=None, **kwargs):
        """Process signals from dependencies."""
        build_kwargs = self._get_build_kwargs(obj, pk_set, action, update_fields, **kwargs)

        if build_kwargs:
            self.index.build(**build_kwargs)

class IndexBuilder:
    """Find indexes and register corresponding signals.

    Indexes are auto collected from ``elastic_indexes.py`` files from
    all Django registered apps

    Post-save and pre-delete signals are registered for objects
    specified in ``object_type`` attribute of each index.

    """

    def __init__(self):
        """Initialize index builder object."""
        #: list of index builders
        self.indexes = []

        #: list of registered signals
        self.signals = []

        prepare_connection()

        self.discover_indexes()
        self.register_signals()

    def _connect_signal(self, index):
        """Create signals for building indexes."""
        post_save_signal = ElasticSignal(index, 'build')
        post_save_signal.connect(post_save, sender=index.object_type)
        self.signals.append(post_save_signal)

        post_delete_signal = ElasticSignal(index, 'remove_object')
        post_delete_signal.connect(post_delete, sender=index.object_type)
        self.signals.append(post_delete_signal)

        # Connect signals for all dependencies.
        for dependency in index.get_dependencies():
            # Automatically convert m2m fields to dependencies.
            if isinstance(dependency, (models.ManyToManyField, ManyToManyDescriptor)):
                dependency = ManyToManyDependency(dependency)
            elif not isinstance(dependency, Dependency):
                raise TypeError("Unsupported dependency type: {}".format(repr(dependency)))

            signal = dependency.connect(index)
            self.signals.extend(signal)

    def unregister_signals(self):
        """Delete signals for building indexes."""
        for signal in self.signals:
            signal.disconnect()
        self.signals = []

    def register_signals(self):
        """Register signals for all indexes."""
        for index in self.indexes:
            if index.object_type:
                self._connect_signal(index)

    def create_mappings(self):
        """Create mappings for all indexes."""
        for index in self.indexes:
            index.create_mapping()

    def discover_indexes(self):
        """Save list of index builders into ``_index_builders``."""
        self.indexes = []

        for app_config in apps.get_app_configs():
            indexes_path = '{}.elastic_indexes'.format(app_config.name)
            try:
                indexes_module = import_module(indexes_path)

                for attr_name in dir(indexes_module):
                    attr = getattr(indexes_module, attr_name)
                    if inspect.isclass(attr) and issubclass(attr, BaseIndex) and attr is not BaseIndex:
                        # Make sure that parallel tests have different indices.
                        if is_testing():
                            index = attr.document_class._doc_type.index  # pylint: disable=protected-access
                            testing_postfix = '_test_{}_{}'.format(TESTING_UUID, os.getpid())

                            if not index.endswith(testing_postfix):
                                # Replace current postfix with the new one.
                                if attr.testing_postfix:
                                    index = index[:-len(attr.testing_postfix)]
                                index = index + testing_postfix
                                attr.testing_postfix = testing_postfix

                            attr.document_class._doc_type.index = index  # pylint: disable=protected-access

                        index = attr()

                        # Apply any extensions defined for the given index. Currently index extensions are
                        # limited to extending "mappings".
                        for extension in composer.get_extensions(attr):
                            mapping = getattr(extension, 'mapping', {})
                            index.mapping.update(mapping)

                        self.indexes.append(index)
            except ImportError as ex:
                if not re.match('No module named .*elastic_indexes.*', str(ex)):
                    raise

    def build(self, obj=None, queryset=None, push=True):
        """Trigger building of the indexes.

        Support passing ``obj`` parameter to the indexes, so we can
        trigger build only for one object.
        """
        for index in self.indexes:
            index.build(obj, queryset, push)

    def push(self, index=None):
        """Push built documents to ElasticSearch.

        If ``index`` is specified, only that index will be pushed.
        """
        for ind in self.indexes:
            if index and not isinstance(ind, index):
                continue
            ind.push()

    def delete(self, skip_mapping=False):
        """Delete all entries from ElasticSearch."""
        for index in self.indexes:
            index.destroy()
            if not skip_mapping:
                index.create_mapping()

    def remove_object(self, obj):
        """Delete given object from all indexes."""
        for index in self.indexes:
            index.remove_object(obj)

    def destroy(self):
        """Delete all indexes from Elasticsearch and index builder."""
        self.unregister_signals()
        for index in self.indexes:
            index.destroy()
        self.indexes = []

index_builder = IndexBuilder()  # pylint: disable=invalid-name


text:
using System.Collections.Generic;
using System.Linq;
using Assets.Scripts.Attributes;
using Assets.Scripts.Managers;
using Assets.Scripts.Utility;
using UnityEngine;
using GameEvent = Assets.Scripts.Constants.GameEvent;

namespace Assets.Scripts.GameScripts.GameLogic.LevelMechanics.Section.SectionObjectives
{
    [AddComponentMenu("LevelMechanics/Section/SectionObjectiveTracker")]
    public class SectionObjectiveTracker : SectionLogic
    {
        public List<SectionObjective> Objectives;
        private const float StartTrackObjectivesDelay = 1.5f;
        private const float TrackObjectivesInterval = 1.0f;

        [GameEvent(GameEvent.OnLevelEnded)]
        public void OnLevelEnded()
        {
            TriggerGameEvent(GameEvent.OnSectionObjectivesCompleted, SectionId);
        }

        public override void OnSectionActivated(int sectionId)
        {
            base.OnSectionActivated(sectionId);
            if (sectionId == SectionId)
            {
                InvokeRepeating("TrackObjective", StartTrackObjectivesDelay, TrackObjectivesInterval);
            }
        }

        public void TrackObjective()
        {
            if (GameManager.Instance.PlayerMainCharacter.HitPointAtZero())
            {
                CancelInvoke();
                return;
            }
            if (Objectives.All(o => o.ObjectiveCompleted()) && !GameScriptManager.Destroyed)
            {
                CancelInvoke();
                TriggerGameEvent(GameEvent.OnSectionObjectivesCompleted, SectionId);
            }
        }

        protected override void FirstTimeInitialize()
        {
            base.FirstTimeInitialize();
            Objectives = GetComponents<SectionObjective>().ToList();
        }

        protected override void Deinitialize()
        {
        }
    }
}


text:
title: "Create tissue-specific databases"
author: "Kevin Vervier"
date: "April 17, 2017"
output: html_document
---

In this vignette, we detail how tissue-specific databases were created using publicly available data sets. Results from this vignette are used in sources, like vignette 'estimate_distributions'.

# How to build tissue-related genes list using PubMed

Require to download gene to pubmed ID database (ftp://ftp.ncbi.nih.gov/gene/DATA/gene2pumed.gz our version is from May 2016) and unzip it

Load Pubmed data mapping gene ID to publication ID
```{r}
pubmed = read.table('gene2pubmed')
# filter non-human organisms
pubmed = pubmed[pubmed$V1 == '9606',]
```
Query tissue, with a query in both titles and abstracts
```{r}
id=getIDs("your_tissue[Title] OR your_tissue[abstract]")
idx = which(pubmed$V3 %in% id) # map PubMed query to gene2pubmed table
genes.tissue = pubmed$V2[idx] # keep genes found in query
```

Create a table with gene ID, gen symbol and number of citations (decreasing order)

```{r}
library(org.Hs.eg.db)
genes.tissue.db = cbind(names(sort(table(as.character(genes.tissue)),decreasing=TRUE)[sort(table(as.character(genes.tissue)),decreasing=TRUE) > 4]),
                       annotate::getSYMBOL(names(sort(table(as.character(genes.tissue)),decreasing=TRUE)[sort(table(as.character(genes.tissue)),decreasing=TRUE) > 4]), data='org.Hs.eg')
                       ,sort(table(as.character(genes.tissue)),decreasing=TRUE)[sort(table(as.character(genes.tissue)),decreasing=TRUE) > 4])
colnames(genes.tissue.db) = c('GeneId','GeneSymbol','Citations')
```

Get corresponding gene locations

```{r}
library('biomaRt')
genes <- genes.tissue.db[,'GeneSymbol']
ensembl = useEnsembl(biomart="ensembl", dataset="hsapiens_gene_ensembl", GRCh=37) #keep genome reference uniform !
genes_pos <- getBM(attributes=c('ensembl_gene_id','hgnc_id','hgnc_symbol','chromosome_name','start_position','end_position'), filters = 'hgnc_symbol', values = unique(genes), mart = ensembl)
genes_pos = genes_pos[order(genes_pos$chromosome_name,genes_pos$start_position),]

#filter all non-standard chromosome names
filt.gene.list= genes_pos[which(genes_pos$chromosome_name%in%c(1:22,'X','Y')),]
# realign with a match needed because not the same dimension
idx = match(genes.tissue.db[,'GeneSymbol'],filt.gene.list$hgnc_symbol)

if(length(which(is.na(idx)))>0){
  db = filt.gene.list[idx[-which(is.na(idx))],]
  db = cbind(db,genes.tissue.db[-which(is.na(idx)),'Citations'])
}else{
  db = filt.gene.list[idx,]
  db = cbind(db,genes.tissue.db[,'Citations'])
}
colnames(db)[7] = 'Citations'

# tissue gene database
write.table(db,file='your_tissue_genes.db',row.names = F,quote = F)
```

### How to build the non-tissue gene database

Here, use any database containing coding genes for hg19 (we used BRAINSPAN project list of genes: http://brainspan.org/api/v2/well_known_file_download/267666527)
```{r}
gene.info = read.csv('coding_genes_database',header=T)
# filter tissue genes
sub.db = gene.info[-which(gene.info$gene_symbol %in% db[,'hgnc_symbol']),]
# get their positions
library(biomaRt)
ensembl = useEnsembl(biomart="ensembl", dataset="hsapiens_gene_ensembl", GRCh=37) #keep genome reference uniform !
genes_pos <- getBM(attributes=c('ensembl_gene_id','hgnc_id','hgnc_symbol','chromosome_name','start_position','end_position'), filters = 'hgnc_symbol', values = unique(sub.db$gene_symbol), mart = ensembl)
genes_pos = genes_pos[order(genes_pos$chromosome_name,genes_pos$start_position),]
write.table(genes_pos,file='your_background_genes.db',row.names = F,quote = F)
```

# Create databases for tissue and non-tissue RoadMap Epigenomics(RME) methylation levels

Raw data can be downloaded at http://egg2.wustl.edu/roadmap/data/byDataType/dnamethylation/DMRs/WGBS_DMRs_v2.tsv.gz

Code for splitting the RME consildated epigenomces file in two parts
```{r}
 system('cut -f 1,2,3,add_columns_corresponding_to_tissue WGBS_DMRs_v2.tsv >> WGBS_DMRs_v2_tissue.tsv') # column examples for Heart: 25,31,32,37,38
 system('cut -f 1-3,add_columns_corresponding_to_nontissue /WGBS_DMRs_v2.tsv >> WGBS_DMRs_v2_non_tissue.tsv') # non-heart columns: 24,26-30,33-36,39-43
```

Code for applying mean function to RME data
```{r}
#load tissue db
db.tissue = read.table(file='WGBS_DMRs_v2_tissue.tsv',header=T)
tmp = cbind(db.tissue[,1:3],apply(db.tissue,1,function(x)mean(as.numeric(x[-c(1:3)]),na.rm=T)))
tmp[which(is.nan(tmp[,4])),4] = NA
colnames(tmp) = c('chr','start','end','average_methylation')
write.table(tmp,file='WGBS_DMRs_v2_tissue_average.tsv',quote=F,row.names = F)
#load non-tissue db
db.bgd = read.table(file='WGBS_DMRs_v2_non_tissue.tsv',header=T)
tmp = cbind(db.bgd[,1:3],apply(db.bgd,1,function(x)mean(as.numeric(x[-c(1:3)]),na.rm=T)))
tmp[which(is.nan(tmp[,4])),4] = NA
colnames(tmp) = c('chr','start','end','average_methylation')
write.table(tmp,file='WGBS_DMRs_v2_non_tissue_average.tsv',quote=F,row.names = F)
```

# Create tissue and non-tissue GTEx eQTLs database

The raw data (V6) can be accessed through GTEx portal (http://gtexportal.org/home/datasets/GTEx_Analysis_V6_eQTLs.tar.gz)

```{r}
tissue.files= list.files('path_to_unzip_GTEx_files',pattern = 'your_tissue_name') #e.g., 'Heart'

#store SNPs info for tissue eQTL
snp.matrix = NULL
for(file in tissue.files){
  x = read.delim(file,header=T,as.is = T)
  snp.matrix = rbind(snp.matrix,cbind(x$rs_id_dbSNP142_GRCh37p13,x$snp_chrom,x$snp_pos,x$ref,x$alt,x$gene_name,x$tss_position,x$tss_distance,file))
}
colnames(snp.matrix) = c('rs_id_dbSNP142_GRCh37p13','snp_chrom','snp_pos','ref','alt','gene','tss_position','tss_distance','source')
write.table(snp.matrix,file='your_tissue_eQTL.db',quote=F,row.names = F)

#non-tissue eQTLs
files = list.files('path_to_unzip_GTEx_files',pattern = '.snpgenes')
# filter tissue files
files = files[-which(files %in% tissue.files)]
#store SNPs info for non-tissue eQTL
snp.matrix = NULL
for(file in files){
  x = read.delim(en.dir %&% file,header=T,as.is = T)
  snp.matrix = rbind(snp.matrix,cbind(x$rs_id_dbSNP142_GRCh37p13,x$snp_chrom,x$snp_pos,x$ref,x$alt,x$gene_name,x$tss_position,x$tss_distance,file))
}
colnames(snp.matrix) = c('rs_id_dbSNP142_GRCh37p13','snp_chrom','snp_pos','ref','alt','gene','tss_position','tss_distance','source')

write.table(snp.matrix,file='your_background_eQTL.db',quote=F,row.names = F)
```

# Create fetal heart enhancers database

```{r}
# load the catalog
db = read.csv('their_fetal_enhancer.db',header=TRUE) # example found here http://www.nature.com/article-assets/npg/ncomms/2016/161005/ncomms12923/extref/ncomms12923-s3.xlsx
# number of enhancers with PreNatal score higher than postNatal
length(which(db$score_Prenatal > db$score_Postnatal)) # 27,375
idx = which(db$score_Prenatal > db$score_Postnatal)

db = db[idx,]

# remove chr X and Y
db = db[-which(db$chromosome%in%c('chrX','chrY')),] # 349 non autosomal --> 27,026 candidate regions

# score > 0.2
#length(which(db$score_All > 0.2)) # 5,919 regions
length(which(db$score_Prenatal > 0.2)) # 8,991 regions

db = db[which(db$score_Prenatal > 0.2),]

#table(db$overlaps.gene.body.) # 2,927 that do not overlap gene body

############
# formatting
db = db[,c(1,2,3,6,8,9,10)]
db$chromosome = gsub('chr','',db$chromosome)
db = db[order(db$chromosome,db$start,decreasing = FALSE),]

write.csv(db,file='your_fetal_enhancer.db',row.names = FALSE)
```


text:
<!DOCTYPE html>

Test for crbug.com/249578: viewSpec's ViewBoxParams.

There should be 2 green boxes below:

<object width="30" height="30" data="resources/viewspec-viewboxparams.svg#svgView(viewBox(100,100,30,30))"></object>
<object width="30" height="30" data="resources/viewspec-viewboxparams.svg#svgView(viewBox(110,110,10,10))"></object>

There should be 3 blue boxes below:

<object width="30" height="30" data="resources/viewspec-viewboxparams.svg#svgView(viewBox(0))"></object>
<object width="30" height="30" data="resources/viewspec-viewboxparams.svg#svgView(viewBox(10,10,-1,-1)"></object>
<object width="30" height="30" data="resources/viewspec-viewboxparams.svg#svgView(viewBox(100;100;30;30))"></object>


text:
Pop PHP Framework
=================

Documentation : Geo
-------------------

Home

La composante Geo fournit simplement un wrapper API orientée objet pour
l'extension GeoIP de PHP.

    use Pop\Geo\Geo;

    $geo1 = new Geo('123.123.123.123');
    $geo2 = new Geo('234.234.234.234');

    print_r($geo->getHostInfo());

    echo $geo1->distanceTo($geo2, 4);
    //echo $geo1->distanceTo($geo2->latitude, $geo2->longitude, 4);

\(c) 2009-2014 [Moc 10 Media, LLC.](http://www.moc10media.com) All
Rights Reserved.


text:
using System;
using System.Collections;
using System.ComponentModel;
using System.Linq;
using System.Collections.Generic;
using System.Reflection;
using TrackableEntities.Client.Tests.Entities.Mocks;
using TrackableEntities.Client.Tests.Entities.FamilyModels;
using TrackableEntities.Client.Tests.Entities.NorthwindModels;
using TrackableEntities.Common;
using Xunit;

namespace TrackableEntities.Client.Tests.Extensions
{
    public class TrackableExtensionsTests
    {
        #region Setup

        // Mock database
        MockFamily _family;

        public TrackableExtensionsTests()
        {
            // Create new mock database for each test
            _family = new MockFamily();
        }

        #endregion

        #region Set Tracking Tests

        [Fact]
        public void Parent_Set_Tracking_Should_Enable_Tracking_For_Children()
        {
            // Arrange
            var parent = _family.Parent;

            // Act
            parent.SetTracking(true);

            // Assert
            IEnumerable<bool> trackings = GetTrackings(parent);
            Assert.True(trackings.All(t => t));
        }

        [Fact]
        public void Parent_Set_Tracking_Should_Disable_Tracking_For_Children()
        {
            // Arrange
            var parent = _family.Parent;
            parent.SetTracking(true);

            // Act
            parent.SetTracking(false);

            // Assert
            IEnumerable<bool> trackings = GetTrackings(parent);
            Assert.True(trackings.All(t => !t));
        }

        [Fact]
        public void Collection_Set_Tracking_Should_Enable_Tracking_For_Children()
        {
            // Arrange
            var parent = _family.Parent;
            var changeTracker = new ChangeTrackingCollection<Parent>();
            changeTracker.Add(parent);

            // Act
            changeTracker.Tracking = true;

            // Assert
            Assert.True(changeTracker.Tracking);
            IEnumerable<bool> trackings = GetTrackings(parent);
            Assert.True(trackings.All(t => t));
        }

        [Fact]
        public void Collection_Ctor_Should_Disable_Tracking_For_Children()
        {
            // Arrange
            var parent = _family.Parent;

            // Act
            var changeTracker = new ChangeTrackingCollection<Parent>(parent);

            // Assert
            Assert.True(changeTracker.Tracking);
            IEnumerable<bool> trackings = GetTrackings(parent);
            Assert.True(trackings.All(t => t));
        }

        #endregion

        #region Set State Tests

        [Fact]
        public void Parent_Set_State_As_Added_Should_Mark_Children_As_Added()
        {
            // Arrange
            var parent = _family.Parent;

            // Act
            parent.SetState(TrackingState.Added, null);

            // Assert
            IEnumerable<TrackingState> trackings = GetStates(parent);
            Assert.True(trackings.All(t => t == TrackingState.Added));
        }

        [Fact]
        public void Parent_Set_State_As_Deleted_Should_Mark_Children_As_Deleted()
        {
            // Arrange
            var parent = _family.Parent;

            // Act
            parent.SetState(TrackingState.Deleted, null);

            // Assert
            IEnumerable<TrackingState> trackings = GetStates(parent);
            Assert.True(trackings.All(t => t == TrackingState.Deleted));
        }

        [Fact]
        public void Parent_Set_State_As_Deleted_Should_Mark_Added_Children_As_Unchanged()
        {
            // NOTE: Deleting an added child should not mark it as deleted, but mark
            // it as unchanged because it says it was not really added in the first place.

            // Arrange
            var parent = _family.Parent;
            parent.TrackingState = TrackingState.Added;
            parent.Children.ToList().ForEach(c1 =>
            {
                c1.TrackingState = TrackingState.Added;
                c1.Children.ToList().ForEach(c2 =>
                {
                    c2.TrackingState = TrackingState.Added;
                    c2.Children.ToList().ForEach(c3 =>
                    {
                        c3.TrackingState = TrackingState.Added;
                    });
                });
            });

            // Act
            parent.SetState(TrackingState.Deleted, null);

            // Assert
            IEnumerable<TrackingState> trackings = GetStates(parent);
            Assert.True(trackings.All(t => t == TrackingState.Unchanged));
        }

        [Fact]
        public void Collection_Set_State_As_Deleted_Should_Mark_Children_As_Deleted()
        {
            // Arrange
            var parent = _family.Parent;
            var changeTracker = new ChangeTrackingCollection<Parent>(parent);

            // Act
            changeTracker.Remove(parent);

            // Assert
            Assert.Equal(TrackingState.Deleted, parent.TrackingState);
            IEnumerable<TrackingState> trackings = GetStates(parent);
            Assert.True(trackings.All(t => t == TrackingState.Deleted));
        }

        [Fact]
        public void Collection_Added_Set_State_As_Deleted_Should_Mark_Children_As_Unchanged()
        {
            // Arrange
            var parent = _family.Parent;
            var changeTracker = new ChangeTrackingCollection<Parent>(true);
            changeTracker.Add(parent);

            // Act
            changeTracker.Remove(parent);

            // Assert
            Assert.Equal(TrackingState.Unchanged, parent.TrackingState);
            IEnumerable<TrackingState> trackings = GetStates(parent);
            Assert.True(trackings.All(t => t == TrackingState.Unchanged));
        }

        [Fact]
        public void Parent_Set_Modified_Props_Should_Set_Children()
        {
            // Arrange
            var parent = _family.Parent;

            // Act
            parent.SetModifiedProperties(new List<string> { "Children" });

            // Assert
            IEnumerable<ICollection<string>> modifieds = GetModifieds(parent);
            Assert.True(modifieds.All(t => t.Contains("Children")));
        }

        [Fact]
        public void Child_Set_Modified_Props_Should_Not_Set_Parent_Siblings()
        {
            // NOTE: SetModifiedProperties should only set ModifiedProperties on
            // downstream 1-M entities.

            // Arrange
            const string propName = "UnitPrice";
            var nw = new MockNorthwind();
            var order = nw.Orders[0];
            var customer = order.Customer;
            var detail1 = order.OrderDetails[0];
            var detail2 = order.OrderDetails[1];
            var detail3 = order.OrderDetails[2];
            detail1.Order = order;
            detail2.Order = order;
            detail3.Order = order;

            var visitationHelper = new ObjectVisitationHelper(null);
            visitationHelper.TryVisit(order.OrderDetails);

            // Act
            detail1.SetModifiedProperties(new List<string> { propName }, visitationHelper.Clone());

            // Assert
            Assert.Null(order.ModifiedProperties);
            Assert.Null(customer.ModifiedProperties);
            Assert.Null(detail1.ModifiedProperties);
            Assert.Null(detail2.ModifiedProperties);
            Assert.Null(detail3.ModifiedProperties);
        }

        #endregion

        #region GetChanges Tests

        [Fact]
        public void Collection_GetChanges_Should_Add_Only_Modified_Children()
        {
            // Arrange
            var parent = new Parent("Parent")
            {
                Children = new ChangeTrackingCollection<Child>
                    {
                        new Child("Child1"),
                        new Child("Child2")
                    }
            };
            var changeTracker = new ChangeTrackingCollection<Parent>(parent);
            parent.Children[0].Name += "_Changed";

            // Act
            var changes = changeTracker.GetChanges();
            var changedParent = changes.First();

            // Assert
            Assert.Equal(1, changes.Count);
            Assert.Equal(1, changedParent.Children.Count);
        }

        [Fact]
        public void Collection_GetChanges_Should_Add_Only_Deleted_Children()
        {
            // Arrange
            var parent = new Parent("Parent")
            {
                Children = new ChangeTrackingCollection<Child>
                    {
                        new Child("Child1")
                    }
            };
            var changeTracker = new ChangeTrackingCollection<Parent>(parent);
            parent.Children.RemoveAt(0);

            // Act
            var changes = changeTracker.GetChanges();
            var changedParent = changes.First();

            // Assert
            Assert.Equal(1, changes.Count);
            Assert.Equal(1, changedParent.Children.Count);
        }

        [Fact]
        public void Collection_GetChanges_Should_Add_Only_Added_Modified_Deleted_Children()
        {
            // Arrange
            var parent = new Parent("Parent")
            {
                Children = new ChangeTrackingCollection<Child>
                    {
                        new Child("Child1"),
                        new Child("Child2"),
                        new Child("Child3")
                    }
            };
            var changeTracker = new ChangeTrackingCollection<Parent>(parent);
            parent.Children.Add(new Child("Child4"));
            parent.Children[0].Name += "_Changed";
            parent.Children.RemoveAt(2);

            // Act
            var changes = changeTracker.GetChanges();
            var changedParent = changes.First();

            // Assert
            Assert.Equal(1, changes.Count);
            Assert.Equal(3, changedParent.Children.Count);
        }

        #endregion

        #region Clone Tests

        [Fact]
        public void Clone_Should_Deep_Copy_Object()
        {
            // Arrange
            var parentOrig = _family.Parent;

            // Act
            var parentCopy = parentOrig.Clone<Parent>();

            // Assert
            Assert.NotSame(parentOrig, parentCopy);
            Assert.NotSame(parentOrig.Children[0], parentCopy.Children[0]);
            Assert.NotSame(parentOrig.Children[1], parentCopy.Children[1]);
            Assert.NotSame(parentOrig.Children[2], parentCopy.Children[2]);
            Assert.NotSame(parentOrig.Children[0].Children[0], parentCopy.Children[0].Children[0]);
            Assert.NotSame(parentOrig.Children[1].Children[0], parentCopy.Children[1].Children[0]);
            Assert.NotSame(parentOrig.Children[2].Children[0], parentCopy.Children[2].Children[0]);
        }

        [Fact]
        public void Collection_Clone_Should_Deep_Copy_Category()
        {
            // Arrange
            var database = new MockNorthwind();
            var categoryOrig = database.Categories[0];

            // Act
            var categoryCopy = categoryOrig.Clone<Category>();

            // Assert
            Assert.NotSame(categoryOrig, categoryCopy);
            Assert.NotSame(categoryOrig.Products[0], categoryCopy.Products[0]);
            Assert.NotSame(categoryOrig.Products[1], categoryCopy.Products[1]);
            Assert.Equal(categoryOrig.Products.Count, categoryCopy.Products.Count);
            for (int i = 0; i < categoryOrig.Products.Count; ++i)
                Assert.Same(categoryOrig.Products[i].GetType(), categoryCopy.Products[i].GetType());
        }

        [Fact]
        public void Collection_Clone_Should_Deep_Copy_Product()
        {
            // Arrange
            var database = new MockNorthwind();
            var productOrig = database.Products[0];

            // Act
            var productCopy = productOrig.Clone<Product>();

            // Assert
            Assert.NotSame(productOrig, productCopy);
            Assert.NotSame(productOrig.Category, productCopy.Category);
        }

        #endregion

        #region Restore and Remove Deletes Tests

        [Fact]
        public void Collection_Restore_Deletes_Should_Add_Deleted_Items()
        {
            // Arrange
            var parent = new Parent("Parent")
            {
                Children = new ChangeTrackingCollection<Child>
                    {
                        new Child("Child1"),
                        new Child("Child2"),
                        new Child("Child3")
                    }
            };
            parent.Children.Tracking = true;
            parent.Children.RemoveAt(2);

            // Act
            var trackableColl = (ITrackingCollection)parent.Children;
            trackableColl.RestoreDeletes();

            // Assert
            Assert.Equal(3, trackableColl.Count);
        }

        [Fact]
        public void Collection_Remove_Deletes_Should_Remove_Added_Deleted_Items()
        {
            // Arrange
            var parent = new Parent("Parent")
            {
                Children = new ChangeTrackingCollection<Child>
                    {
                        new Child("Child1"),
                        new Child("Child2"),
                        new Child("Child3")
                    }
            };
            parent.Children[0].TrackingState = TrackingState.Deleted;
            parent.Children.Tracking = true;
            parent.Children.RemoveAt(0);
            parent.Children.RestoreDeletes();

            // Act
            var trackableColl = (ITrackingCollection)parent.Children;
            trackableColl.RemoveRestoredDeletes();

            // Assert
            Assert.Equal(2, trackableColl.Count);
        }

        [Fact]
        public void Item_Restore_Deletes_Should_Recursively_Add_Deleted_Items()
        {
            // Arrange
            var parent = new Parent("Parent")
            {
                Children = new ChangeTrackingCollection<Child>
                    {
                        new Child("Child1")
                        {
                            Children = new ChangeTrackingCollection<Child>
                                {
                                    new Child("Grandchild1"),
                                    new Child("Grandchild2")
                                }
                        }
                    }
            };
            var count = parent.Children[0].Children.Count;
            parent.SetTracking(true);
            parent.Children[0].Children.RemoveAt(1);

            // Act
            parent.Children[0].Children.RestoreDeletes();

            // Assert
            Assert.Equal(count, parent.Children[0].Children.Count);
        }

        [Fact]
        public void Item_Remove_Deletes_Should_Recursively_Remove_Added_Deleted_Items()
        {
            // Arrange
            var parent = new Parent("Parent")
            {
                Children = new ChangeTrackingCollection<Child>
                    {
                        new Child("Child1")
                        {
                            Children = new ChangeTrackingCollection<Child>
                                {
                                    new Child("Grandchild1"),
                                    new Child("Grandchild2")
                                }
                        }
                    }
            };
            var deleted = parent.Children[0].Children[1];
            parent.Children[0].Children.Tracking = true;
            parent.Children[0].Children.RemoveAt(1);
            parent.Children[0].Children.RestoreDeletes();

            // Act
            var trackableColl = (ITrackingCollection)parent.Children[0].Children;
            trackableColl.RemoveRestoredDeletes();

            // Assert
            Assert.Equal(1, parent.Children[0].Children.Count);
            Assert.DoesNotContain(deleted, (ITrackingCollection<Child>)trackableColl);
        }

        [Fact]
        public void Order_Remove_Deletes_Should_Remove_Deleted_OrderDetails()
        {
            // Arrange
            var database = new MockNorthwind();
            var order = database.Orders[0];
            var deleted1 = order.OrderDetails[0];
            var deleted2 = order.OrderDetails[2];
            var changeTracker = new ChangeTrackingCollection<Order>(order);
            order.OrderDetails.Remove(deleted1);
            order.OrderDetails.Remove(deleted2);
            changeTracker.RestoreDeletes();

            // Act
            changeTracker.RemoveRestoredDeletes();

            // Assert
            Assert.Equal(1, order.OrderDetails.Count);
            Assert.DoesNotContain(deleted1, changeTracker.Cast<object>());
            Assert.DoesNotContain(deleted2, changeTracker.Cast<object>());
        }

        #endregion

        #region IsEquatable Tests

        [Fact]
        public void IsEquatable_Should_Return_False_If_SetEntityIdentifier_Not_Called()
        {
            // Arrange
            var northwind = new MockNorthwind();
            var customer1 = northwind.Customers[0];
            var customer2 = northwind.Customers[1];

            // Act
            bool areEquatable = customer1.IsEquatable(customer2);

            // Assert
            Assert.False(areEquatable);
        }

        [Fact]
        public void IsEquatable_Should_Return_True_If_SetEntityIdentifier_Called()
        {
            // Arrange
            var northwind = new MockNorthwind();
            var customer1 = northwind.Customers[0];
            var customer2 = northwind.Customers[1];
            customer1.SetEntityIdentifier();
            customer2.SetEntityIdentifier(customer1);

            // Act
            bool areEquatable = customer1.IsEquatable(customer2);

            // Assert
            Assert.True(areEquatable);
        }

        [Fact]
        public void IsEquatable_Should_Return_False_If_EntityIdentifier_Cleared()
        {
            // Arrange
            var northwind = new MockNorthwind();
            var customer1 = northwind.Customers[0];
            var customer2 = northwind.Customers[1];
            customer1.SetEntityIdentifier();
            customer2.SetEntityIdentifier(customer1);

            customer1.SetEntityIdentifier(new Customer()); // Cleared

            // Act
            bool areEquatable = customer1.IsEquatable(customer2);

            // Assert
            Assert.False(areEquatable);
        }

        [Fact]
        public void IsEquatable_Should_Return_False_If_EntityIdentifier_Reset()
        {
            // Arrange
            var northwind = new MockNorthwind();
            var customer1 = northwind.Customers[0];
            var customer2 = northwind.Customers[1];
            customer1.SetEntityIdentifier();
            customer2.SetEntityIdentifier(customer1);
            bool wereEquatable = customer1.IsEquatable(customer2);

            // Act
            customer1.SetEntityIdentifier(new Customer()); // Cleared
            customer1.SetEntityIdentifier(); // Reset
            bool areEquatable = customer1.IsEquatable(customer2);

            // Assert
            Assert.True(wereEquatable);
            Assert.False(areEquatable);
        }

        #endregion

        #region NotifyPropertyChanged Tests

        [Fact]
        public void Product_Property_Setter_Should_Fire_PropertyChanged_Event()
        {
            // Arrange
            var northwind = new MockNorthwind();
            var product = northwind.Products[0];
            var subscriber = new Subscriber<Product>
            {
                Model = product
            };

            // Act
            product.ProductName += "_X";

            // Assert
            Assert.True(subscriber.ModelChanged);
            Assert.Equal("ProductName", subscriber.ChangedPropertyName);
        }

        [Fact]
        public void PromotionalProduct_Property_Setter_Should_Fire_PropertyChanged_Event()
        {
            // Arrange
            var northwind = new MockNorthwind();
            var product = northwind.Products.OfType<PromotionalProduct>().First();
            var subscriber = new Subscriber<Product>
            {
                Model = product
            };

            // Act
            product.PromoCode += "_X";

            // Assert
            Assert.True(subscriber.ModelChanged);
            Assert.Equal("PromoCode", subscriber.ChangedPropertyName);
        }

        #endregion

        #region Helper Methods

        private IEnumerable<bool> GetTrackings(Parent parent)
        {
            var trackings = new List<bool>();
            trackings.Add(parent.Children.Tracking);
            trackings.AddRange(from c in parent.Children
                               let ch = c.Children
                               select ch.Tracking);
            trackings.AddRange(from c in parent.Children
                               from gc in c.Children
                               let ch = gc.Children
                               select ch.Tracking);
            return trackings;
        }

        private IEnumerable<TrackingState> GetStates(Parent parent)
        {
            var trackings = new List<TrackingState>();
            trackings.AddRange(from c in parent.Children
                               select c.TrackingState);
            trackings.AddRange(from c in parent.Children
                               from gc in c.Children
                               select gc.TrackingState);
            trackings.AddRange(from c in parent.Children
                               from gc in c.Children
                               from ggc in gc.Children
                               select ggc.TrackingState);
            return trackings;
        }

        private IEnumerable<ICollection<string>> GetModifieds(Parent parent)
        {
            var modifieds = new List<ICollection<string>>();
            modifieds.AddRange(from c in parent.Children
                               select c.ModifiedProperties);
            modifieds.AddRange(from c in parent.Children
                               from gc in c.Children
                               select gc.ModifiedProperties);
            modifieds.AddRange(from c in parent.Children
                               from gc in c.Children
                               from ggc in gc.Children
                               select ggc.ModifiedProperties);
            return modifieds;
        }

        #endregion

        #region Helper Classes

        class Subscriber<TModel>
            where TModel : INotifyPropertyChanged
        {
            public TModel Model
            {
                set
                {
                    _model = value;
                    _model.PropertyChanged += OnPropertyChanged;
                }
            }
            private TModel _model;

            public bool ModelChanged { get; private set; }
            public string ChangedPropertyName { get; private set; }

            void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
            {
                ModelChanged = true;
                ChangedPropertyName = e.PropertyName;
            }
        }

        #endregion
    }
}


text:
"""
    SleekXMPP: The Sleek XMPP Library
    Copyright (C) 2011 Nathanael C. Fritz, Lance J.T. Stout
    This file is part of SleekXMPP.

    See the file LICENSE for copying permission.
"""

import datetime as dt

from sleekxmpp.plugins import BasePlugin, register_plugin
from sleekxmpp.thirdparty import tzutc, tzoffset, parse_iso

# =====================================================================
# To make it easier for stanzas without direct access to plugin objects
# to use the XEP-0082 utility methods, we will define them as top-level
# functions and then just reference them in the plugin itself.

def parse(time_str):
    """
    Convert a string timestamp into a datetime object.

    Arguments:
        time_str -- A formatted timestamp string.
    """
    return parse_iso(time_str)

def format_date(time_obj):
    """
    Return a formatted string version of a date object.

    Format:
        YYYY-MM-DD

    Arguments:
        time_obj -- A date or datetime object.
    """
    if isinstance(time_obj, dt.datetime):
        time_obj = time_obj.date()
    return time_obj.isoformat()

def format_time(time_obj):
    """
    Return a formatted string version of a time object.

    format:
        hh:mm:ss[.sss][TZD]

    arguments:
        time_obj -- A time or datetime object.
    """
    if isinstance(time_obj, dt.datetime):
        time_obj = time_obj.timetz()
    timestamp = time_obj.isoformat()
    if time_obj.tzinfo == tzutc():
        timestamp = timestamp[:-6]
        return '%sZ' % timestamp
    return timestamp

def format_datetime(time_obj):
    """
    Return a formatted string version of a datetime object.

    Format:
        YYYY-MM-DDThh:mm:ss[.sss]TZD

    arguments:
        time_obj -- A datetime object.
    """
    timestamp = time_obj.isoformat('T')
    if time_obj.tzinfo == tzutc():
        timestamp = timestamp[:-6]
        return '%sZ' % timestamp
    return timestamp

def date(year=None, month=None, day=None, obj=False):
    """
    Create a date only timestamp for the given instant.

    Unspecified components default to their current counterparts.

    Arguments:
        year   -- Integer value of the year (4 digits)
        month  -- Integer value of the month
        day    -- Integer value of the day of the month.
        obj    -- If True, return the date object instead
                  of a formatted string. Defaults to False.
    """
    today = dt.datetime.utcnow()
    if year is None:
        year = today.year
    if month is None:
        month = today.month
    if day is None:
        day = today.day
    value = dt.date(year, month, day)
    if obj:
        return value
    return format_date(value)

def time(hour=None, min=None, sec=None, micro=None, offset=None, obj=False):
    """
    Create a time only timestamp for the given instant.

    Unspecified components default to their current counterparts.

    Arguments:
        hour   -- Integer value of the hour.
        min    -- Integer value of the number of minutes.
        sec    -- Integer value of the number of seconds.
        micro  -- Integer value of the number of microseconds.
        offset -- Either a positive or negative number of seconds
                  to offset from UTC to match a desired timezone,
                  or a tzinfo object.
        obj    -- If True, return the time object instead
                  of a formatted string. Defaults to False.
    """
    now = dt.datetime.utcnow()
    if hour is None:
        hour = now.hour
    if min is None:
        min = now.minute
    if sec is None:
        sec = now.second
    if micro is None:
        micro = now.microsecond
    if offset is None:
        offset = tzutc()
    elif not isinstance(offset, dt.tzinfo):
        offset = tzoffset(None, offset)
    value = dt.time(hour, min, sec, micro, offset)
    if obj:
        return value
    return format_time(value)

def datetime(year=None, month=None, day=None, hour=None,
             min=None, sec=None, micro=None, offset=None,
             separators=True, obj=False):
    """
    Create a datetime timestamp for the given instant.

    Unspecified components default to their current counterparts.

    Arguments:
        year   -- Integer value of the year (4 digits)
        month  -- Integer value of the month
        day    -- Integer value of the day of the month.
        hour   -- Integer value of the hour.
        min    -- Integer value of the number of minutes.
        sec    -- Integer value of the number of seconds.
        micro  -- Integer value of the number of microseconds.
        offset -- Either a positive or negative number of seconds
                  to offset from UTC to match a desired timezone,
                  or a tzinfo object.
        obj    -- If True, return the datetime object instead
                  of a formatted string. Defaults to False.
    """
    now = dt.datetime.utcnow()
    if year is None:
        year = now.year
    if month is None:
        month = now.month
    if day is None:
        day = now.day
    if hour is None:
        hour = now.hour
    if min is None:
        min = now.minute
    if sec is None:
        sec = now.second
    if micro is None:
        micro = now.microsecond
    if offset is None:
        offset = tzutc()
    elif not isinstance(offset, dt.tzinfo):
        offset = tzoffset(None, offset)

    value = dt.datetime(year, month, day, hour,
                       min, sec, micro, offset)
    if obj:
        return value
    return format_datetime(value)

class XEP_0082(BasePlugin):

    """
    XEP-0082: XMPP Date and Time Profiles

    XMPP uses a subset of the formats allowed by ISO 8601 as a matter of
    pragmatism based on the relatively few formats historically used by
    the XMPP.

    Also see <http://www.xmpp.org/extensions/xep-0082.html>.

    Methods:
        date            -- Create a time stamp using the Date profile.
        datetime        -- Create a time stamp using the DateTime profile.
        time            -- Create a time stamp using the Time profile.
        format_date     -- Format an existing date object.
        format_datetime -- Format an existing datetime object.
        format_time     -- Format an existing time object.
        parse           -- Convert a time string into a Python datetime object.
    """

    name = 'xep_0082'
    description = 'XEP-0082: XMPP Date and Time Profiles'
    dependencies = set()

    def plugin_init(self):
        """Start the XEP-0082 plugin."""
        self.date = date
        self.datetime = datetime
        self.time = time
        self.format_date = format_date
        self.format_datetime = format_datetime
        self.format_time = format_time
        self.parse = parse

register_plugin(XEP_0082)


text:
layout: page
title: "HIST 3019: Seminar in Asian and African History Statistics"
comments: true
description: "blanks"
keywords: "HIST,3019,CU,Boulder"
---

#### GRADE AND WORKLOAD STATISTICS

**Percent withdrawn**: 1.67%

**Percent incomplete**: 0.0%

**Average grade** (4.0 scale): 3.11

**Standard deviation in grades** (4.0 scale): 0.37

**Average workload** (raw): 3.14

**Standard deviation in workload** (raw): 0.31

#### COURSE AND INSTRUCTOR RATINGS/INFORMATION

**Average course rating** (6 point scale): 5.17

**Standard deviation in course rating** (6 point scale): 0.45

**Average instructor rating** (6 point scale): 5.56

**Standard deviation in instructor rating** (6 point scale): 0.31

**Instructors**: Mithi Mukherjee, Myles Gregory Osborne

#### GENERAL CLASS INFORMATION

**Years provided**: Spring 2007, Spring 2009, Spring 2010, Fall 2010

**Credits**: 3

**RAP/Honors class?** RAP

**Number of Sections**: 4

**Department**: HIST

**College**: College of Arts and Sciences

**A&S Division**: Arts and Humanities

**Level**: Upper

**Activity**: SEM - Seminar


text:
require 'spec_helper'

describe ExpressionValidator do
  it 'has a version number' do
    expect(ExpressionValidator::VERSION).not_to be nil
  end

  it 'does something useful' do
    expect(false).to eq(true)
  end
end


text:
package com.intellij.execution.ui.layout;

public enum PlaceInGrid {
  left, center, right, bottom
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<theDavidBox>
	<request>
		<arg0>set_slide_show_effect</arg0>
		<arg1>fade</arg1>
		<module>setting</module>
	</request>
	<response></response>
	<returnValue>0</returnValue>
</theDavidBox>


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.

namespace Microsoft.Azure.Search
{
    using System;
    using Microsoft.Azure.Search.Models;

    /// <summary>
    /// Indicates that the field can be used in filter expressions.
    /// </summary>
    [AttributeUsage(AttributeTargets.Property)]
    public class IsFilterableAttribute : Attribute
    {
    }
}


text:
public class JLS_14_20_TryStatement_5 {
    public static void main(String[] args) {
	int[] array = new int[101];

	// The aim of these test cases are to check for exceptions
	// arising from conditions (which become edge conditions)
	try {
	    if(array[101] == 0) {
		System.out.println("SHOULDN'T GET HERE");
	    }
	} catch(Exception e) {
	    System.out.println("CAUGHT Exception from If");
	}

	try {
	    for(int i=0;array[i] != 10; ++i) {
		i = i + 1;
	    }
	} catch(Exception e) {
	    System.out.println("CAUGHT Exception from For");
	}
    }
}


text:
package uk.ac.ebi.eva.server.ws;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import uk.ac.ebi.eva.commons.core.models.AnnotationMetadata;
import uk.ac.ebi.eva.commons.mongodb.services.AnnotationMetadataService;
import uk.ac.ebi.eva.lib.utils.QueryResponse;
import uk.ac.ebi.eva.lib.utils.QueryResult;

import java.util.Arrays;
import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.BDDMockito.given;

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class AnnotationMetadataWSServerTest {

    private List<AnnotationMetadata> annotationMetadataList;

    @Autowired
    private TestRestTemplate restTemplate;

    @MockBean
    private AnnotationMetadataService service;

    @Before
    public void setUp() throws Exception {
        annotationMetadataList = Arrays.asList(new AnnotationMetadata("75", "75"),
                new AnnotationMetadata("74", "74"));

        given(service.findAllByOrderByCacheVersionDescVepVersionDesc()).willReturn(annotationMetadataList);
    }

    @Test
    public void testFetAnnotationMetadata() {
        String url = "/v1/annotation?species=mmusculus_grcm38";
        ResponseEntity<QueryResponse<QueryResult<AnnotationMetadata>>> response = restTemplate.exchange(
                url, HttpMethod.GET, null,
                new ParameterizedTypeReference<QueryResponse<QueryResult<AnnotationMetadata>>>() {
                });
        assertEquals(HttpStatus.OK, response.getStatusCode());

        QueryResponse<QueryResult<AnnotationMetadata>> queryResponse = response.getBody();
        assertEquals(1, queryResponse.getResponse().size());

        List<AnnotationMetadata> results = queryResponse.getResponse().get(0).getResult();
        assertEquals(annotationMetadataList.size(), results.size());

        for (AnnotationMetadata result : results) {
            assertTrue(annotationMetadataList.contains(result));
        }
    }

}


text:
import BrandBand from './BrandBand';

export { BrandBand };


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GLR.Grammar.String {
    public abstract class Terminal : GLR.Grammar.Terminal<string> {
        public static Terminal T(string t) { return new StringTerminal(t); }

        public static implicit operator Terminal(string t) {
            return new StringTerminal(t);
        }
    }
}