text:
export interface IHelperTransform {
    toLowerCase(data: string): string;
    toUpperCase(data: string): string;
    toMongoId(id: string): object;
    toDate(dateStr: string): Date;
    toMoment(dateStr: string): object;
    toInt(data: string): number;
    toFloat(data: string, dec?: number): number;
    toSaltHash(pwd: string): string;
    stripXss(str: string): string;
}
export declare class HelperTransform implements IHelperTransform {
    private logger;
    private chance;
    constructor(debug: boolean);
    /**
     * Transforms the given string to Lower Case
     * @param data Data to be transformed
     *
     * @returns upperCased string
     */
    toLowerCase(data: string): string;
    /**
     * Transforms the given string to Upper Case
     * @param data Data to be transformed
     *
     * @returns lowerCase string
     */
    toUpperCase(data: string): string;
    /**
     * Transforms mongo id to Mongo Object id
     * @param id Mongo Document id in string
     *
     * @returns MongoObjectId
     */
    toMongoId(id: string): object;
    /**
     * Transforms the given string to Date Object
     * @param dateStr Date string
     *
     * @returns Date Object
     */
    toDate(dateStr: string): Date;
    /**
     * Transforms the given string to moment object
     * @param dateStr Moment Date String
     *
     * @returns moment object
     */
    toMoment(dateStr: string): object;
    /**
     * Parse string to number
     * @param data number in string
     *
     * @returns parsed number
     */
    toInt(data: string): number;
    /**
     * Parses string to float
     * @param data float in string
     * @param dec decimal points
     *
     * @return parsed float
     */
    toFloat(data: string, dec?: number): number;
    /**
     * Adds salt and hashes the given the string
     * @param pwd Password
     *
     * @return salth hashed password
     */
    toSaltHash(pwd: string): string;
    /**
     * Removes all the html tags and the data inbetween the tags
     * @param str
     *
     * @return string without tags
     */
    stripXss(str: string): string;
}

redpajama_set_name: RedPajamaGithub


text:
define([
	'iweb/CoreModule',
	'./report-roc/RocReportView',
	'./report-roc/RocReportController',
	'./report-roc/RocFormView',
	'./report-roc/RocFormController'
	],

	function(Core,  RocReportView, RocReportController, RocFormView, RocFormController) {

		var RocReportModule = function(){};

		RocReportModule.prototype.load = function(){

			var rocReportView = Ext.create('modules.report-roc.RocReportView');

			///var rocForm = Ext.create('modules.report-roc.RocFormView');
			//rocReportView.add(rocForm);

		};

		return new RocReportModule();
	}
);


text:
package org.jbox2d.common;

import java.io.Serializable;

// updated to rev 100

/** A transform contains translation and rotation. It is used to represent the position and orientation of rigid frames. */
public class Transform implements Serializable {
	private static final long serialVersionUID = 1L;

	/** The translation caused by the transform */
	public final Vec2 p;

	/** A matrix representing a rotation */
	public final Rot q;

	/** The default constructor. */
	public Transform () {
		p = new Vec2();
		q = new Rot();
	}

	/** Initialize as a copy of another transform. */
	public Transform (final Transform xf) {
		p = xf.p.clone();
		q = xf.q.clone();
	}

	/** Initialize using a position vector and a rotation matrix. */
	public Transform (final Vec2 _position, final Rot _R) {
		p = _position.clone();
		q = _R.clone();
	}

	/** Set this to equal another transform. */
	public final Transform set (final Transform xf) {
		p.set(xf.p);
		q.set(xf.q);
		return this;
	}

	/** Set this based on the position and angle.
	 *
	 * @param p
	 * @param angle */
	public final void set (Vec2 p, float angle) {
		this.p.set(p);
		q.set(angle);
	}

	/** Set this to the identity transform. */
	public final void setIdentity () {
		p.setZero();
		q.setIdentity();
	}

	public final static Vec2 mul (final Transform T, final Vec2 v) {
		return new Vec2((T.q.c * v.x - T.q.s * v.y) + T.p.x, (T.q.s * v.x + T.q.c * v.y) + T.p.y);
	}

	public final static void mulToOut (final Transform T, final Vec2 v, final Vec2 out) {
		final float tempy = (T.q.s * v.x + T.q.c * v.y) + T.p.y;
		out.x = (T.q.c * v.x - T.q.s * v.y) + T.p.x;
		out.y = tempy;
	}

	public final static void mulToOutUnsafe (final Transform T, final Vec2 v, final Vec2 out) {
		assert (v != out);
		out.x = (T.q.c * v.x - T.q.s * v.y) + T.p.x;
		out.y = (T.q.s * v.x + T.q.c * v.y) + T.p.y;
	}

	public final static Vec2 mulTrans (final Transform T, final Vec2 v) {
		final float px = v.x - T.p.x;
		final float py = v.y - T.p.y;
		return new Vec2((T.q.c * px + T.q.s * py), (-T.q.s * px + T.q.c * py));
	}

	public final static void mulTransToOut (final Transform T, final Vec2 v, final Vec2 out) {
		final float px = v.x - T.p.x;
		final float py = v.y - T.p.y;
		final float tempy = (-T.q.s * px + T.q.c * py);
		out.x = (T.q.c * px + T.q.s * py);
		out.y = tempy;
	}

	public final static void mulTransToOutUnsafe (final Transform T, final Vec2 v, final Vec2 out) {
		assert (v != out);
		final float px = v.x - T.p.x;
		final float py = v.y - T.p.y;
		out.x = (T.q.c * px + T.q.s * py);
		out.y = (-T.q.s * px + T.q.c * py);
	}

	public final static Transform mul (final Transform A, final Transform B) {
		Transform C = new Transform();
		Rot.mulUnsafe(A.q, B.q, C.q);
		Rot.mulToOutUnsafe(A.q, B.p, C.p);
		C.p.addLocal(A.p);
		return C;
	}

	public final static void mulToOut (final Transform A, final Transform B, final Transform out) {
		assert (out != A);
		Rot.mul(A.q, B.q, out.q);
		Rot.mulToOut(A.q, B.p, out.p);
		out.p.addLocal(A.p);
	}

	public final static void mulToOutUnsafe (final Transform A, final Transform B, final Transform out) {
		assert (out != B);
		assert (out != A);
		Rot.mulUnsafe(A.q, B.q, out.q);
		Rot.mulToOutUnsafe(A.q, B.p, out.p);
		out.p.addLocal(A.p);
	}

	private static Vec2 pool = new Vec2();

	public final static Transform mulTrans (final Transform A, final Transform B) {
		Transform C = new Transform();
		Rot.mulTransUnsafe(A.q, B.q, C.q);
		pool.set(B.p).subLocal(A.p);
		Rot.mulTransUnsafe(A.q, pool, C.p);
		return C;
	}

	public final static void mulTransToOut (final Transform A, final Transform B, final Transform out) {
		assert (out != A);
		Rot.mulTrans(A.q, B.q, out.q);
		pool.set(B.p).subLocal(A.p);
		Rot.mulTrans(A.q, pool, out.p);
	}

	public final static void mulTransToOutUnsafe (final Transform A, final Transform B, final Transform out) {
		assert (out != A);
		assert (out != B);
		Rot.mulTransUnsafe(A.q, B.q, out.q);
		pool.set(B.p).subLocal(A.p);
		Rot.mulTransUnsafe(A.q, pool, out.p);
	}

	@Override
	public final String toString () {
		String s = "XForm:\n";
		s += "Position: " + p + "\n";
		s += "R: \n" + q + "\n";
		return s;
	}
}


text:
$toolsDir = "$(Split-Path -Parent $MyInvocation.MyCommand.Definition)"

$installerExe    = Join-Path $toolsDir "TreeSize-x64-Full.exe"
$restartExitCode = 3010
$installerArgs   = "/verysilent /norestart /restartexitcode=$restartExitCode"

$validExitCodes = @(
    0,               # all ok
    $restartExitCode #reboot required
)

Install-ChocolateyInstallPackage -PackageName $env:chocolateyPackageName `
    -File $installerExe -FileType 'exe' -ValidExitCodes $validExitCodes `
    -SilentArgs $installerArgs


text:
/**
 * Test for the IO class, limited to the jsonp part
 */
Aria.classDefinition({
    $classpath : "test.aria.core.io.JSONPTest",
    $extends : "aria.jsunit.TestCase",
    $dependencies : ["test.aria.core.test.IOFilterSample"],
    $constructor : function () {
        this.$TestCase.constructor.call(this);
        this.defaultTestTimeout = 10000;
    },
    $prototype : {
        tearDown : function () {
            aria.core.IO.$unregisterListeners(this);

            // Check that we didn't forget any timer on IO
            var timers = 0, id;
            for (id in aria.core.IO._poll) {
                if (aria.core.IO._poll.hasOwnProperty(id)) {
                    timers += 1;
                }
            }
            for (id in aria.core.IO._timeOut) {
                if (aria.core.IO._timeOut.hasOwnProperty(id)) {
                    timers += 1;
                }
            }
            this.assertEquals(timers, 0, "Undisposed pending timers on aria.core.IO");

            // Check that we don't have pending requests
            var requests = 0;
            for (id in aria.core.IO.pendingRequests) {
                if (aria.core.IO.pendingRequests.hasOwnProperty(id)) {
                    requests += 1;
                }
            }

            this.assertEquals(requests, 0, "Undisposed pending requests on aria.core.IO");
        },

        /**
         * Test a missing file, error callback should be called
         */
        testAsyncError : function () {
            aria.core.IO.jsonp({
                url : "jsonp_that_doesnt_exist",
                timeout : 1000,
                callback : {
                    fn : this._onTestErrorSuccess,
                    scope : this,
                    onerror : this._onTestErrorError,
                    onerrorScope : this,
                    args : "Call1"
                }
            });
        },
        _onTestErrorSuccess : function () {
            try {
                this.fail("Success function shouldn't be called");
            } catch (er) {}

            this.notifyTestEnd("testAsyncError");
        },
        _onTestErrorError : function (request, cbArgs) {
            try {
                this.assertTrue(!!request.url, "Missing request url");
                this.assertTrue(request.url.indexOf("jsonp_that_doesnt_exist") === 0, "Wrong URL: " + request.url);
                this.assertEquals(cbArgs, "Call1", "Arguments different from expected");
            } catch (er) {}

            this.notifyTestEnd("testAsyncError");
        },

        /**
         * Generic error callback for jsonp requests that shouldn't fail
         * @param {Object} response Response object
         * @param {String} testName Name of the test that failed
         */
        onTestGenericError : function (response, testName) {
            try {
                this.fail(response.url + " shouldn't fail.");
            } catch (er) {}

            this.notifyTestEnd(testName);
        },

        /**
         * Test that a local request works.
         */
        testAsyncLocal : function () {
            var url = aria.core.DownloadMgr.resolveURL("test/aria/core/test/SampleString.jsonp");
            var reqId = aria.core.IO.jsonp({
                url : url,
                timeout : 1000,
                callback : {
                    fn : this._onTestLocalStringSuccess,
                    scope : this,
                    onerror : this.onTestGenericError,
                    onerrorScope : this,
                    args : {
                        testName : "testAsyncLocal",
                        url : url
                    }
                }
            });

            aria.core.IO.evalJsonPforTestSampleString = function (json) {
                aria.core.transport.JsonP["_jsonp" + reqId].call(aria.core.transport.JsonP, json);
            };
        },
        _onTestLocalStringSuccess : function (response, args) {
            var testName = args.testName;
            try {
                this.assertTrue(!!response.url, "Missing response url");
                this.assertTrue(response.url.indexOf(args.url) === 0, "Wrong URL: " + response.url);
                this.assertEquals(response.responseJSON, "something", "Wrong Response: " + response.responseJSON);
            } catch (er) {}

            delete aria.core.IO["evalJsonPforTestSampleString"];

            this.notifyTestEnd(testName);
        },

        /**
         * Test that a local request works.
         */
        testAsyncLocalObject : function () {
            var url = aria.core.DownloadMgr.resolveURL("test/aria/core/test/SampleObject.jsonp");
            // We need to add some functions on IO because we don't have a server
            var reqId = aria.core.IO.jsonp({
                url : url,
                timeout : 1000,
                callback : {
                    fn : this._onTestLocalObjectSuccess,
                    scope : this,
                    onerror : this.onTestGenericError,
                    onerrorScope : this,
                    args : {
                        testName : "testAsyncLocalObject",
                        url : url
                    }
                }
            });

            aria.core.IO.evalJsonPforTestSampleObject = function (json) {
                aria.core.transport.JsonP["_jsonp" + reqId].call(aria.core.transport.JsonP, json);
            };
        },
        _onTestLocalObjectSuccess : function (response, args) {
            var testName = args.testName;
            try {
                this.assertTrue(!!response.url, "Missing response url");
                this.assertTrue(response.url.indexOf(args.url) === 0, "Wrong URL: " + response.url);
                this.assertEquals(response.responseJSON.something, "complex", "Wrong Response: "
                        + response.responseJSON);
            } catch (er) {}

            delete aria.core.IO["evalJsonPforTestSampleObject"];

            this.notifyTestEnd(testName);
        },

        /**
         * Test that a local request works.
         */
        testAsyncRemote : function () {
            aria.core.IO.jsonp({
                url : "http://jsfiddle.net/echo/jsonp/?query=ariatemplates",
                timeout : 5000,
                callback : {
                    fn : this._onTestRemoteSuccess,
                    scope : this,
                    onerror : this.onTestGenericError,
                    onerrorScope : this,
                    args : "testAsyncRemote"
                }
            });
        },
        _onTestRemoteSuccess : function (response, testName) {
            try {
                this.assertTrue(response.url.indexOf("http://jsfiddle.net/echo/jsonp/?query=ariatemplates") === 0, "Wrong URL: "
                        + response.url);
                this.assertEquals(response.responseJSON.query, "ariatemplates");
            } catch (er) {}

            this.notifyTestEnd(testName);
        },

        /**
         * Test redirecting a JSON-P request to a static file.
         */
        testAsyncRedirectJSONPToFile : function () {
            var oSelf = this;
            var request;
            var filterParam = {
                classpath : "test.aria.core.test.IOFilterSample",
                initArgs : {
                    onRequest : function (req) {
                        try {
                            oSelf.assertTrue(req == request);
                            oSelf.assertTrue(req.jsonp != null);
                            this.redirectToFile(req, "test/aria/core/test/TestFile.json");
                            oSelf.assertTrue(req.jsonp == null);
                        } catch (e) {
                            this.handleAsyncTestError(e, false);
                        }
                    }
                }
            };
            aria.core.IOFiltersMgr.addFilter(filterParam);
            request = {
                url : "http://jsfiddle.net/echo/jsonp/?query=ariatemplates",
                timeout : 5000,
                callback : {
                    fn : function (res) {
                        try {
                            this.assertTrue(res == request.res);
                            this.assertTrue(res.responseText != null);
                            var json = res.responseJSON;
                            this.assertTrue(json != null);
                            this.assertTrue(json.result == "OK");
                            this.assertTrue(json.content == "[Some content]");
                        } catch (e) {
                            this.handleAsyncTestError(e, false);
                        }
                        aria.core.IOFiltersMgr.removeFilter(filterParam);
                        this.notifyTestEnd("testAsyncRedirectJSONPToFile");
                    },
                    scope : this,
                    onerror : function () {
                        aria.core.IOFiltersMgr.removeFilter(filterParam);
                        this.fail("The request should not have failed.");
                    },
                    onerrorScope : this
                }
            };
            aria.core.IO.jsonp(request);
        },

        /**
         * Test redirecting an XHR request to JSON-P.
         */
        testAsyncRedirectXHRToJSONP : function () {
            var oSelf = this;
            var request;
            var filterParam = {
                classpath : "test.aria.core.test.IOFilterSample",
                initArgs : {
                    onRequest : function (req) {
                        try {
                            oSelf.assertTrue(req == request);
                            oSelf.assertTrue(req.jsonp == null);
                            req.url = "http://jsfiddle.net/echo/jsonp/?query=ariatemplates";
                            req.jsonp = "callback";
                        } catch (e) {
                            this.handleAsyncTestError(e, false);
                        }
                    }
                }
            };
            aria.core.IOFiltersMgr.addFilter(filterParam);
            request = {
                expectedResponseType : "text",
                url : aria.core.DownloadMgr.resolveURL("test/aria/core/test/TestFile.json"),
                timeout : 5000,
                callback : {
                    fn : function (res) {
                        try {
                            this.assertTrue(res == request.res);
                            this.assertEquals(res.responseJSON.query, "ariatemplates");
                            this.assertTrue(res.responseText != null);
                            var json = aria.utils.Json.load(res.responseText, this);
                            this.assertEquals(json.query, "ariatemplates");
                        } catch (e) {
                            this.handleAsyncTestError(e, false);
                        }
                        aria.core.IOFiltersMgr.removeFilter(filterParam);
                        this.notifyTestEnd("testAsyncRedirectJSONPToFile");
                    },
                    scope : this,
                    onerror : function () {
                        aria.core.IOFiltersMgr.removeFilter(filterParam);
                        this.fail("The request should not have failed.");
                    },
                    onerrorScope : this
                }
            };
            aria.core.IO.asyncRequest(request);
        },

        /**
         * Test redirecting a FileLoader request to JSON-P.
         */
        testAsyncRedirectFileLoaderToJSONP : function () {
            var fileToBeRequested = "test/aria/core/test/fileRedirectedToJsonP.txt";
            var oSelf = this;
            var filterCalled = false;
            var filter = new test.aria.core.test.IOFilterSample({
                onRequest : function (req) {
                    try {
                        var sender = req.sender;
                        if (sender && sender.classpath == "aria.core.FileLoader"
                                && sender.logicalPaths[0] == fileToBeRequested) {
                            oSelf.assertFalse(filterCalled);
                            filterCalled = true;
                            req.jsonp = "callback";
                            req.url = aria.core.DownloadMgr.resolveURL("test/aria/core/test/SampleString.jsonp");
                            aria.core.IO.evalJsonPforTestSampleString = function (json) {
                                aria.core.transport.JsonP["_jsonp" + req.id].call(aria.core.transport.JsonP, json);
                            };
                        }
                    } catch (e) {
                        this.handleAsyncTestError(e, false);
                    }
                }
            });
            aria.core.IOFiltersMgr.addFilter(filter);
            aria.core.DownloadMgr.clearFile(fileToBeRequested, true); // make sure the file is not in the cache
            aria.core.DownloadMgr.loadFile(fileToBeRequested, {
                fn : function (res) {
                    try {
                        delete aria.core.IO["evalJsonPforTestSampleString"];
                        this.assertTrue(filterCalled);
                        this.assertFalse(res.downloadFailed);
                        var fileContent = aria.core.DownloadMgr.getFileContent(fileToBeRequested);
                        this.assertTrue(fileContent == "something");
                    } catch (e) {
                        this.handleAsyncTestError(e, false);
                    }
                    aria.core.IOFiltersMgr.removeFilter(filter);
                    this.notifyTestEnd("testAsyncRedirectFileLoaderToJSONP");
                },
                scope : this
            });
        }
    }
});


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Lichen inquinans Sm.

### Remarks
null


text:
#ifndef LIGHT_PLAYER_WORK_HPP
#define LIGHT_PLAYER_WORK_HPP

#include <functional>

namespace lp {

using Work = std::function<void()>;

} // namespace lp

#endif // LIGHT_PLAYER_WORK_HPP


text:
namespace kruto {

bool File::isRelative(const char *pFileName)
{
	if(pFileName == NULL || *pFileName == '\0')
		return true;

	if(*pFileName == '/' || *pFileName == '\\' || strstr(pFileName, "..") || strstr(pFileName, "::"))
	{
		Console::log("[file] cannot access %s (outside of sandbox)", pFileName);
		return true;
	}

	return false;
}

bool File::isTypeOf(const char *pFileName, const char *pType)
{
	int lf = strlen(pFileName);
	int lt = strlen(pType);

	const char *sf = pFileName + lf;
	const char *st = pType + lt;

	if(lf < lt)
		return false;

	while(lt--)
	{
		if(*st-- != *sf--)
			return false;
	}

	return true;
}

char *File::read(const char *pFileName, size_t *pSize)
{
	if(File::isRelative(pFileName))
		return NULL;

	FILE *fp = fopen(pFileName, "r");
	if(fp == NULL)
		return NULL;

	size_t offset = fseek(fp, 0L, SEEK_END);
	size_t size = ftell(fp);
	fseek(fp, offset, SEEK_SET);

	char *buffer = new char[size+1];
	fread(buffer, sizeof(char), size, fp);
	buffer[size] = '\0';

	fclose(fp);

	if(pSize != NULL)
		*pSize = size;

	return buffer;
}

}


text:
import sys

doclines = """A collection of ASN.1-based protocols modules.

   A collection of ASN.1 modules expressed in form of pyasn1 classes.
   Includes protocols PDUs definition (SNMP, LDAP etc.) and various
   data structures (X.509, PKCS etc.).
"""

doclines = [x.strip() for x in doclines.split('\n') if x]

classifiers = """\
Development Status :: 5 - Production/Stable
Environment :: Console
Intended Audience :: Developers
Intended Audience :: Education
Intended Audience :: Information Technology
Intended Audience :: System Administrators
Intended Audience :: Telecommunications Industry
License :: OSI Approved :: BSD License
Natural Language :: English
Operating System :: OS Independent
Programming Language :: Python :: 2
Programming Language :: Python :: 2.4
Programming Language :: Python :: 2.5
Programming Language :: Python :: 2.6
Programming Language :: Python :: 2.7
Programming Language :: Python :: 3
Programming Language :: Python :: 3.2
Programming Language :: Python :: 3.3
Programming Language :: Python :: 3.4
Programming Language :: Python :: 3.5
Programming Language :: Python :: 3.6
Programming Language :: Python :: 3.7
Topic :: Communications
Topic :: System :: Monitoring
Topic :: System :: Networking :: Monitoring
Topic :: Software Development :: Libraries :: Python Modules
"""

def howto_install_setuptools():
    print("""
   Error: You need setuptools Python package!

   It's very easy to install it, just type (as root on Linux):

   wget https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py
   python ez_setup.py

   Then you could make eggs from this package.
""")

if sys.version_info[:2] < (2, 4):
    print("ERROR: this package requires Python 2.4 or later!")
    sys.exit(1)

try:
    from setuptools import setup, Command

    params = {
        'zip_safe': True,
        'install_requires': ['pyasn1>=0.4.6,<0.5.0']
    }

except ImportError:
    for arg in sys.argv:
        if 'egg' in arg:
            howto_install_setuptools()
            sys.exit(1)

    from distutils.core import setup, Command

    if sys.version_info[:2] > (2, 4):
        params = {
            'requires': ['pyasn1(>=0.4.6,<0.5.0)']
        }
    else:
        params = {
            'requires': ['pyasn1']
        }

params.update(
    {'name': 'pyasn1-modules',
     'version': open('pyasn1_modules/__init__.py').read().split('\'')[1],
     'description': doclines[0],
     'long_description': ' '.join(doclines[1:]),
     'maintainer': 'Ilya Etingof <etingof@gmail.com>',
     'author': 'Ilya Etingof',
     'author_email': 'etingof@gmail.com',
     'url': 'https://github.com/etingof/pyasn1-modules',
     'platforms': ['any'],
     'classifiers': [x for x in classifiers.split('\n') if x],
     'license': 'BSD-2-Clause',
     'packages': ['pyasn1_modules']}
)

# handle unittest discovery feature
try:
    import unittest2 as unittest
except ImportError:
    import unittest

class PyTest(Command):
    user_options = []

    def initialize_options(self):
        pass

    def finalize_options(self):
        pass

    def run(self):
        suite = unittest.TestLoader().loadTestsFromNames(
            ['tests.__main__.suite']
        )

        unittest.TextTestRunner(verbosity=2).run(suite)

params['cmdclass'] = {
    'test': PyTest,
    'tests': PyTest
}

setup(**params)


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

		<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
		<title>TrAP Tests 1.3 Reference Package com.ericsson.research.trap.tests</title>
		<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="style" />

        	com.ericsson.research.trap.tests

Classes

            	CleanupTest

            	HttpToWebsocketSwitchingTest

            	JSClientStart

            	JSServerStart

            	MiscellaneousTests

            	PeerToPeerTest

            	TransportDarwinTest

            	TransportSwitchingTest


text:
import React, {Component, PropTypes} from "react";

import CSSModules from 'react-css-modules';
import styles from "../../../../scss/_code-box.scss";

import _ from "lodash";

import StaticJSCode  from "./static-js-code";
import JSColorMap    from "./js-color-map";
import JSArrMap      from "./js-arr-map";

class JSView extends React.Component {
  constructor(){
    super();
  }
  render () {
    const{dispatch, jsView, pixelCount, columnCount, rowCount, xPos, yPos, rectColor} = this.props;
    if(jsView){
      return(

let canvas, ctx, tileSize = {pixelCount}, map = [

          <JSArrMap {...this.props} />
          <StaticJSCode />
          <JSColorMap {...this.props} />

      );
    }
    return(

    );
  }
}

export default JSView;


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Task03_LoginPages
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void ButtonLogin_OnClick(object sender, EventArgs e)
        {
            var cookie = new HttpCookie("UserName", this.TextBoxInput.Text);
            cookie.Expires = DateTime.Now.AddMinutes(1);

            Response.Cookies.Add(cookie);
            Response.Redirect("~/Secure.aspx");
        }
    }
}


text:
<ion-view>

    <ion-content scroll="false" class="padding text-align-center">

Peid

            <sign-in ng-switch-when="signIn"></sign-in>
            <logged-in ng-switch-when="loggedIn"></logged-in>
            <update-profile ng-switch-when="updateProfile"></update-profile>

WTF

    </ion-content>
</ion-view>


text:
Djortunes (`django_fortunes` app)
=================================

`django_fortunes`'s a [Django](http://www.djangoproject.com/) application to store fortunes (snippets of quotes, eg. IRC/IM ones). Originally inspired by the « [Fortunes](http://fortunes.inertie.org/) » application, by [Maurice Svay](http://svay.com/).

![screenshot](http://files.droplr.com/files/6619162/RKP6D.djortunes.png "Example app screen")

I'm discovering and learning both [Python](http://python.org/) and [Django](http://www.djangoproject.com/) while coding it, so don't expect too much reliability, but I would warmly welcome any code review against the code :)

If you're curious enough, you might check out the [Symfony version of this app](http://github.com/n1k0/sftunes).

Prerequisites
-------------

* Django 1.2 or more recent
* `django-registration` 0.7
* Eventually, the `django-debug-toolbar` if you plan to use the provided sample `settings_local.py.sample` file for a standard dev environment

Installation
------------

Djortunes ship as a standalone application (located in the `django_fortunes` directory), and a sample Django project is also provided as an example of use (in the `django_fortunes_example` directory).

The better way to install dependencies (using a `virtualenv` is highly encouraged) is by using the provided `pip` requirements file:

    $ pip install -r requirements.txt

You can adjust and override the project settings by configuring a custom settings file: a sample `settings_local.py.sample` file is provided within the example project directory. You can safely rename it `settings_local.py` and tweak its values.

Then, just run the `./manage.py runserver` within the `django_fortunes_example` directory:

    $ cd django_fortunes_example
    $ ./manage.py runserver --settings=settings_local

Configuration
-------------

Several settings are available in the `django_fortunes` application, and you can override their defaults in your project's `settings.py` configuration file:

    # Maximum number of fortunes to be shown in lists
    FORTUNES_MAX_PER_PAGE = 10

    # Maximum number of top fortune authors to display in the sidebar
    FORTUNES_MAX_TOP_CONTRIBUTORS = 5

License
-------

This work is released under the terms of the [MIT license](http://en.wikipedia.org/wiki/MIT_License).

Authors
-------

* [Nicolas Perriault](http://github.com/n1k0)
* [Florent Messa](http://github.com/thoas)


text:
package com.jmethods.catatumbo;

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

/**
 * Used for annotating a method as an entity listener method. The annotated method will be invoked
 * before deleting an entity. This annotation can be applied to a method within an {@link Entity},
 * {@link MappedSuperClass} or an {@link EntityListener}.
 *
 * @see EntityListeners
 * @see EntityListener
 *
 * @author Sai Pullabhotla
 *
 */
@Retention(RUNTIME)
@Target(METHOD)
public @interface PreDelete {
  // Marker
}


text:
draft: true
author:
  description: Researches geodesy at the University of Bonn
  email: roelof@wobbly.earth
  github: https://github.com/strawpants
  image: /images/WBlogo_64x64.png
  name: Roelof Rietbroek
  twitter: https://twitter.com/
  website: http://wobbly.earth/about
cardheaderimage: /images/sun-pudding.jpg
cardthumbimage: /images/sun-pudding.jpg
images:
    - :/images/sun-pudding_og.jpg"
cardtitlecolor: white
date: 2016-10-07
description: A Wobbly Earth
categories:
    - "post"
tags:
    - "Wobbly Earth"
    - "Earth rotation"
    - "geocenter"
    - "surface loading"
    - "jelly"
levels:
    - "somewhat technical"
title: "A Wobbly Earth"
tweetshare:  "A wobbly Earth"
sitemap:
    changefreq: "monthly"
    priority: 0.6
---

#### The Jellypudding Analogy

Most people think the Earth is a sphere, while geodesists joke that [the Earth's is a potato](http://www.gfz-potsdam.de/en/media-communication/mediathek/image-galleries/geoid-the-potsdam-gravity-potato/). And you can even find some funny folks who believe the Earth is flat and only 6000 years old. If it was up to me, I would happily claim that the Earthe is a giant jellypudding. <!--more-->

The jellypudding analogy helps in explaining some important concepts I use regularly in my research, and it sheds some light on the reason why I chose the domain [wobbly.earth](/).
If you substitute the solid part of the Earth by jelly, it is not hard to understand that, when revolving around the sun, the Earth is going to wobble a fair bit along the way. In reality, these wobbles are much much smaller than when the Earth would be made of jelly, but they are nevertheless detectable by accurate geodetic measurements techniques.

#### The wobbly Earth's rotational axis
One thing that is moving is the orientation of the Earth's rotation axis.

#### mass movement causes the Earth to deform (elastic visco-elastic)

#### The center of mass and center of figure move with respect to each other


text:
import { Box, Col, Row, Separator, Serif, Spacer } from "@artsy/palette"
import { SearchApp_viewer } from "v2/__generated__/SearchApp_viewer.graphql"
import { AppContainer } from "v2/Apps/Components/AppContainer"
import { HorizontalPadding } from "v2/Apps/Components/HorizontalPadding"
import { NavigationTabsFragmentContainer as NavigationTabs } from "v2/Apps/Search/Components/NavigationTabs"
import { SearchMeta } from "v2/Apps/Search/Components/SearchMeta"
import { withSystemContext } from "v2/Artsy"
import { track } from "v2/Artsy/Analytics"
import * as Schema from "v2/Artsy/Analytics/Schema"

import { Footer } from "v2/Components/Footer"
import { RecentlyViewedQueryRenderer as RecentlyViewed } from "v2/Components/RecentlyViewed"

import { RouterState, withRouter } from "found"
import React, { useEffect, useState } from "react"
import { createFragmentContainer, graphql } from "react-relay"
import { TrackingProp } from "react-tracking"
import { get } from "v2/Utils/get"
import { ZeroState } from "./Components/ZeroState"

export interface Props extends RouterState {
  viewer: SearchApp_viewer
  tracking: TrackingProp
}

const TotalResults: React.SFC<{ count: number; term: string }> = ({
  count,
  term,
}) => {
  const formatResults = () =>
    `${count.toLocaleString()} Result${count > 1 ? "s" : ""} for "${term}"`
  const [results, setResults] = useState(formatResults())

  useEffect(() => {
    setResults(formatResults())
  }, [count])

  return <Serif size="5">{results}</Serif>
}

@track({
  context_page: Schema.PageName.SearchPage,
})
export class SearchApp extends React.Component<Props> {
  renderResults(count: number, artworkCount: number) {
    const {
      viewer,
      match: { location },
    } = this.props
    const { searchConnection } = viewer
    const {
      query: { term },
    } = location

    return (
      <>
        <Spacer mb={4} />
        <Row>
          <Col>
            <TotalResults count={count} term={term} />
            <Spacer mb={4} />
            <span id="jumpto--searchResultTabs" />
            <NavigationTabs
              artworkCount={artworkCount}
              term={term}
              searchableConnection={searchConnection}
            />
            <Box minHeight="30vh">{this.props.children}</Box>
          </Col>
        </Row>

        {this.renderFooter()}
      </>
    )
  }

  renderFooter() {
    return (
      <>
        <Row>
          <Col>
            <RecentlyViewed />
          </Col>
        </Row>

        <Separator mt={6} mb={3} />

        <Row>
          <Col>
            <Footer />
          </Col>
        </Row>
      </>
    )
  }

  render() {
    const {
      viewer,
      match: { location },
    } = this.props
    const { searchConnection, artworksConnection } = viewer
    const { query } = location
    const { term } = query

    const { aggregations } = searchConnection
    const artworkCount = get(artworksConnection, f => f.counts.total, 0)

    let countWithoutArtworks: number = 0
    const typeAggregation = aggregations.find(agg => agg.slice === "TYPE")
      .counts

    typeAggregation.forEach(({ count, name }) => {
      if (name !== "artwork") {
        countWithoutArtworks += count
      }
    })

    const hasResults = !!(countWithoutArtworks || artworkCount)

    return (
      <AppContainer>
        <HorizontalPadding>
          {/* NOTE: react-head automatically moves these tags to the <head> element */}
          <SearchMeta term={term} />
          {hasResults ? (
            this.renderResults(
              countWithoutArtworks + artworkCount,
              artworkCount
            )
          ) : (
              <Box mt={3}>
                <ZeroState term={term} />
                {this.renderFooter()}
              </Box>
            )}
          <Spacer mb={3} />
        </HorizontalPadding>
      </AppContainer>
    )
  }
}

export const SearchAppFragmentContainer = createFragmentContainer(
  withSystemContext(withRouter(SearchApp)),
  {
    viewer: graphql`
      fragment SearchApp_viewer on Viewer
        @argumentDefinitions(term: { type: "String!", defaultValue: "" }) {
        searchConnection(query: $term, first: 1, aggregations: [TYPE]) {
          aggregations {
            slice
            counts {
              count
              name
            }
          }
          ...NavigationTabs_searchableConnection
          edges {
            node {
              ... on SearchableItem {
                slug
                displayLabel
                displayType
              }
            }
          }
        }
        artworksConnection(keyword: $term, size: 0, aggregations: [TOTAL]) {
          counts {
            total
          }
        }
      }
    `,
  }
)

// Top-level route needs to be exported for bundle splitting in the router
export default SearchAppFragmentContainer


text:
angular.module("mdl")
.directive("mdlButton",function ButtonDirective(){
	var stl=angular.element('\n\
	');

	function applyStyle(_style){
		var style=document.querySelectorAll("style#"+_style.id);
		if(style.length==0){
			try{
				document.body.appendChild(_style);
			}catch(err){
				setTimeout(function(){applyStyle(_style)},1000);
			}
		}
	}
	applyStyle(stl[0]);

	return {
			priority: 1,
			restrict: 'E',
			transclude: {
			},
			template:'\
\
<button type="button" class="mdl-chip">\
    Button Chip\
</button>\
',
			compile:function(tElm,tAttrs,transclude){
			  	console.debug("Button-compile",tElm.html())
				return {
				  pre:function(scope, elm, attrs,ctrl,transcludeFn){
				  	console.debug("Button-pre",elm.html(),(transcludeFn(scope)));
				  },
				  post:function(scope, elm, attrs,ctrl,transcludeFn){
				  	console.debug("Button-post",elm.html(),(transcludeFn(scope)));

			  }
			}
		}
	}
})


text:
// ----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ----------------------------------------------------------------------------

using System.Reflection;
using System.Windows;
using Microsoft.WindowsAzure.MobileServices.TestFramework;

namespace Microsoft.WindowsAzure.MobileServices.Test
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        /// <summary>
        /// Gets the test harness used by the application.
        /// </summary>
        public static TestHarness Harness { get; private set; }

        /// <summary>
        /// Initialize the test harness.
        /// </summary>
        static App()
        {
            Harness = new TestHarness();
            Harness.Platform = TestPlatform.Net45;
            Harness.LoadTestAssembly(typeof(FunctionalTestBase).GetTypeInfo().Assembly);
        }

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            if (e.Args.Length > 0)
                Harness.SetAutoConfig(e.Args[0]);
        }
    }
}


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

    function ChangePasswordController($scope) {

        var vm = this;

        vm.$onInit = onInit;
        vm.$onDestroy = onDestroy;
        vm.doChange = doChange;
        vm.cancelChange = cancelChange;
        vm.showOldPass = showOldPass;
        vm.showCancelBtn = showCancelBtn;
        vm.newPasswordKeyUp = newPasswordKeyUp;

        var unsubscribe = [];

        function resetModel(isNew) {
            //the model config will contain an object, if it does not we'll create defaults
            //NOTE: We will not support doing the password regex on the client side because the regex on the server side
            //based on the membership provider cannot always be ported to js from .net directly.
            /*
            {
                hasPassword: true/false,
                requiresQuestionAnswer: true/false,
                enableReset: true/false,
                enablePasswordRetrieval: true/false,
                minPasswordLength: 10
            }
            */

            vm.showReset = false;

            //set defaults if they are not available
            if (vm.config.disableToggle === undefined) {
                vm.config.disableToggle = false;
            }
            if (vm.config.hasPassword === undefined) {
                vm.config.hasPassword = false;
            }
            if (vm.config.enablePasswordRetrieval === undefined) {
                vm.config.enablePasswordRetrieval = true;
            }
            if (vm.config.requiresQuestionAnswer === undefined) {
                vm.config.requiresQuestionAnswer = false;
            }
            //don't enable reset if it is new - that doesn't make sense
            if (isNew === "true") {
                vm.config.enableReset = false;
            }
            else if (vm.config.enableReset === undefined) {
                vm.config.enableReset = true;
            }

            if (vm.config.minPasswordLength === undefined) {
                vm.config.minPasswordLength = 0;
            }

            // Check non-alpha pwd settings for tooltip display
            if (vm.config.minNonAlphaNumericChars === undefined) {
                vm.config.minNonAlphaNumericChars = 0;
            }

            //set the model defaults
            if (!Utilities.isObject(vm.passwordValues)) {
                //if it's not an object then just create a new one
                vm.passwordValues = {
                    newPassword: null,
                    oldPassword: null,
                    reset: null,
                    answer: null
                };
            }
            else {
                //just reset the values

                if (!isNew) {
                    //if it is new, then leave the generated pass displayed
                    vm.passwordValues.newPassword = null;
                    vm.passwordValues.oldPassword = null;
                }
                vm.passwordValues.reset = null;
                vm.passwordValues.answer = null;
            }

            //the value to compare to match passwords
            if (!isNew) {
                vm.passwordValues.confirm = "";
            }
            else if (vm.passwordValues.newPassword && vm.passwordValues.newPassword.length > 0) {
                //if it is new and a new password has been set, then set the confirm password too
                vm.passwordValues.confirm = vm.passwordValues.newPassword;
            }

        }

        //when the scope is destroyed we need to unsubscribe
        function onDestroy() {
            for (var u in unsubscribe) {
                unsubscribe[u]();
            }
        }

        function onInit() {
            //listen for the saved event, when that occurs we'll
            //change to changing = false;
            unsubscribe.push($scope.$on("formSubmitted", function () {
                if (vm.config.disableToggle === false) {
                    vm.changing = false;
                }
            }));

            unsubscribe.push($scope.$on("formSubmitting", function () {
                //if there was a previously generated password displaying, clear it
                if (vm.changing && vm.passwordValues) {
                    vm.passwordValues.generatedPassword = null;
                }
                else if (!vm.changing) {
                    //we are not changing, so the model needs to be null
                    vm.passwordValues = null;
                }
            }));

            resetModel(vm.isNew);

            //if there is no password saved for this entity , it must be new so we do not allow toggling of the change password, it is always there
            //with validators turned on.
            vm.changing = vm.config.disableToggle === true || !vm.config.hasPassword;

            //we're not currently changing so set the model to null
            if (!vm.changing) {
                vm.passwordValues = null;
            }
        }

        function doChange() {
            resetModel();
            vm.changing = true;
            //if there was a previously generated password displaying, clear it
            vm.passwordValues.generatedPassword = null;
            vm.passwordValues.confirm = null;
        };

        function cancelChange() {
            vm.changing = false;
            //set model to null
            vm.passwordValues = null;
        };

        function showOldPass() {
            return vm.config.hasPassword &&
                !vm.config.allowManuallyChangingPassword &&
                !vm.config.enablePasswordRetrieval && !vm.showReset;
        };

        // TODO: I don't think we need this or the cancel button, this can be up to the editor rendering this component
        function showCancelBtn() {
            return vm.config.disableToggle !== true && vm.config.hasPassword;
        };

        function newPasswordKeyUp(event) {
            vm.passwordVal = event.target.value;
        }
    }

    var component = {
        templateUrl: 'views/components/users/change-password.html',
        controller: ChangePasswordController,
        controllerAs: 'vm',
        bindings: {
            isNew: "<",
            passwordValues: "=", //TODO: Do we need bi-directional vals?
            config: "=" //TODO: Do we need bi-directional vals?
            //TODO: Do we need callbacks?
        }
    };

    angular.module('umbraco.directives').component('changePassword', component);

})();


text:
package com.dremio.plugins.util.awsauth;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.s3a.AnonymousAWSCredentialsProvider;
import org.apache.hadoop.fs.s3a.Constants;
import org.apache.hadoop.fs.s3a.SimpleAWSCredentialsProvider;

import com.dremio.aws.SharedInstanceProfileCredentialsProvider;
import com.dremio.service.coordinator.DremioAssumeRoleCredentialsProviderV2;

import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;

/**
 * Factory to provide the appropriate AWSCredentialsProvider based on a Configuration.
 *
 * Note: This package can hopefully be used in the future to consolidate very
 * similar code in S3, Hive, and Glue plugins, but that was out of scope for
 * the current work.
 */
public final class DremioAWSCredentialsProviderFactoryV2 {

  // AWS Credential providers
  public static final String ACCESS_KEY_PROVIDER = SimpleAWSCredentialsProvider.NAME;
  public static final String EC2_METADATA_PROVIDER = "com.amazonaws.auth.InstanceProfileCredentialsProvider";
  public static final String NONE_PROVIDER = AnonymousAWSCredentialsProvider.NAME;
  public static final String ASSUME_ROLE_PROVIDER = "com.dremio.plugins.s3.store.STSCredentialProviderV1";
  // Credential provider for DCS data roles
  public static final String DREMIO_ASSUME_ROLE_PROVIDER = "com.dremio.service.coordinator" +
    ".DremioAssumeRoleCredentialsProviderV1";
  public static final String GLUE_DREMIO_ASSUME_ROLE_PROVIDER = "com.dremio.exec.store.hive.GlueDremioAssumeRoleCredentialsProviderV1";
  public static final String AWS_PROFILE_PROVIDER = "com.dremio.plugins.s3.store.AWSProfileCredentialsProviderV1";

  private DremioAWSCredentialsProviderFactoryV2() {
  }

  /**
   * Constructs and returns the appropriate AWSCredentialsProvider.
   * @return
   */
  public static AwsCredentialsProvider getAWSCredentialsProvider(Configuration config) {

    switch(config.get(Constants.AWS_CREDENTIALS_PROVIDER)) {
      case ACCESS_KEY_PROVIDER:
        return StaticCredentialsProvider.create(AwsBasicCredentials.create(
          config.get(Constants.ACCESS_KEY), config.get(Constants.SECRET_KEY)));
      case EC2_METADATA_PROVIDER:
        return new SharedInstanceProfileCredentialsProvider();
      case NONE_PROVIDER:
        return AnonymousCredentialsProvider.create();
      case DREMIO_ASSUME_ROLE_PROVIDER:
        return new DremioAssumeRoleCredentialsProviderV2();
      case GLUE_DREMIO_ASSUME_ROLE_PROVIDER:
        return new GlueDremioAssumeRoleCredentialsProviderV2();
      case ASSUME_ROLE_PROVIDER:
        return new STSCredentialProviderV2(config);
      case AWS_PROFILE_PROVIDER:
        return new AWSProfileCredentialsProviderV2(config);
      default:
        throw new IllegalStateException("Invalid AWSCredentialsProvider provided: " + config.get(Constants.AWS_CREDENTIALS_PROVIDER));
    }
  }
}


text:
package bytetrie

import (
	"testing"

	"fmt"
	"github.com/akolb1/filetypes/bytetrie"
)

// TestEmpty checks properties of an empty tree
func TestEmpty(t *testing.T) {
	t.Parallel()
	trie := bytetrie.New()
	depth := trie.MaxDepth()
	if depth != 0 {
		t.Error("MaxDepth() is non-zero for an empty trie")
	}
	result, ok := trie.Get([]byte{0})
	if result != nil || ok {
		t.Error("Empty trie has a value")
	}
}

func TestInsert(t *testing.T) {
	// Various inputs that are inserted in a tree
	t.Parallel()
	trie := bytetrie.New()

	inputs := map[string]int{
		"hello":         1,
		"world":         2,
		"help":          3,
		"work":          4,
		"SomeLongWord":  5,
		"SomeOtherWord": 6,
	}

	// Something not in a trie
	badword := "What?"

	// Values in a tree that were visited during the walk
	visited := map[string]bool{}
	// Initialize visited to all false and insert all inputs into a tree
	longest := 0
	for k, v := range inputs {
		visited[k] = false
		trie.Insert(v, []byte(k))
		// Calculate the longest key length
		if longest < len(k) {
			longest = len(k)
		}
	}

	if longest != trie.MaxDepth() {
		t.Errorf("MaxDepth(): expected %d, got %d", longest,
			trie.MaxDepth())
	}
	// Walk the trie manually and make sure that we can get every value
	for k, v := range inputs {
		v1, ok := trie.Get([]byte(k))
		if !ok {
			t.Errorf("Key %s missing from trie", k)
		}
		if v1 != v {
			t.Errorf("Key %s: expected value %d, got %d", k, v, v1)
		}
	}

	// Verify Match()
	for k, v := range inputs {
		longerKey := k + "foo"
		v1, ok := trie.Match([]byte(longerKey))
		if !ok {
			t.Errorf("Value %s doesn't match", longerKey)
		}
		if v1 != v {
			t.Errorf("Match Key %s: expected value %d, got %d",
				k, v, v1)
		}
	}

	// Walk the trie and make sure everything is there
	walker := func(key []byte, val interface{}) {
		skey := string(key)
		visited[skey] = true
		if val != inputs[skey] {
			t.Errorf("Key %s: expected value %d, got %d",
				skey, inputs[skey], val)
		}
	}

	trie.Do(walker)

	// Make sure we visited every node
	for k, v := range visited {
		if !v {
			t.Errorf("Skipped key %s", k)
		}
	}

	// Make sure that a word not in a trie doesn't match
	{
		v, ok := trie.Get([]byte(badword))
		if v != nil || ok {
			t.Error("Get() returns true for a missing word")
		}
		v, ok = trie.Match([]byte(badword))
		if v != nil || ok {
			t.Error("Match() returns true for a missing word")
		}
	}
}

func Example() {
	trie := bytetrie.New()
	trie.Insert(true, []byte("hello"))
	trie.Insert(true, []byte("world"))
	trie.Insert(true, []byte("help"))
	trie.Insert(true, []byte("work"))
	trie.PrintKeys()
}

func ExampleTrie_Get() {
	trie := bytetrie.New()
	trie.Insert(1, []byte("hello"))
	trie.Insert(2, []byte("world"))
	trie.Insert(3, []byte("help"))
	trie.Insert(4, []byte("work"))
	value, ok := trie.Get([]byte("help"))
	fmt.Println(value, ok)
	// Output: 3 true
}

func ExampleTrie_Match() {
	trie := bytetrie.New()
	trie.Insert(1, []byte("hello"))
	trie.Insert(2, []byte("world"))
	trie.Insert(3, []byte("help"))
	trie.Insert(4, []byte("work"))
	value, ok := trie.Match([]byte("hello world"))
	fmt.Println(value, ok)
	// Output: 1 true
}

func ExampleTrie_Do() {
	trie := bytetrie.New()
	trie.Insert(1, []byte("hello"))
	trie.Insert(2, []byte("world"))
	trie.Insert(3, []byte("help"))
	trie.Insert(4, []byte("work"))
	// Count number of entries in a tree and total of all values
	count := 0
	total := 0
	counter := func(key []byte, val interface{}) {
		intval := val.(int)
		total += intval
		count++

	}
	trie.Do(counter)
	fmt.Println(count, total)
	// Output: 4 10
}


text:
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <script type="text/javascript">
    console.log("================ start");

    var s = new String("Hello, world!");
    console.log(s.toString());

    var a = new String(" abc ");
    console.log(typeof a);
    console.log(a instanceof String);
    console.log(Object.prototype.toString.call(a));

    console.log(a);

    console.log(Object.prototype.toString.call([1,2,3]));
    console.log(Object.prototype.toString.call(/regex-literal/i));
    console.log(Object.prototype.toString.call(null));
    console.log(Object.prototype.toString.call(undefined));
    console.log(Object.prototype.toString.call("abc"));
    console.log(Object.prototype.toString.call(42));
    console.log(Object.prototype.toString.call(true));

    console.log("================ end");
  </script>
  <body>

  </body>
</html>


text:
package play;

import java.awt.BorderLayout;
import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JPanel;

import controller.DataController;

import stage.Game;

import engine.GameEngine;

/**
 *
 * @author David Chou
 *
 */

/*
 * This class stores all of the different components of the Engine into one component.
 * It also ensures that they can interact with each other. The current components are:
 * 		Controller (inserted into the JPanel)
 * 		MenuBar
 * 			File
 * 				Open
 * 				Quit
 */
public class EngineFrame extends JFrame{

	private EnginePanel myPanel;
	private JMenuBar myMenuBar;

	private DataController myController;

	public EngineFrame() {
		myController = new DataController();
		initializeViewSpecs();
		addPanel();
		addMenu();
		finalizeView();
	}

	private void initializeViewSpecs() {
		setPreferredSize(new Dimension(800, 600));
		setLayout(new BorderLayout());
	}

	private void addPanel() {
		myPanel = new EnginePanel(myController);
		add(myPanel, BorderLayout.CENTER);
	}

	private void addMenu() {
		myMenuBar = new PlayMenuBar(myController, myPanel.getEngine());
		setJMenuBar(myMenuBar);
	}

	private void finalizeView() {
		pack();
		setVisible(true);
	}

}


text:
@class IssueModel;
@interface MomentsCell : UITableViewCell
@property (nonatomic ,strong) IssueModel * issueItem;

@end


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Composition;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.VisualStudio.Utilities;

namespace Microsoft.VisualStudio.LanguageServices.LiveShare.Client.Debugging
{
    [ExportContentTypeLanguageService(ContentTypeNames.CSharpLspContentTypeName, StringConstants.CSharpLspLanguageName), Shared]
    internal class CSharpLspContentTypeLanguageService : IContentTypeLanguageService
    {
        private readonly IContentTypeRegistryService _contentTypeRegistry;

        [ImportingConstructor]
        public CSharpLspContentTypeLanguageService(IContentTypeRegistryService contentTypeRegistry)
        {
            _contentTypeRegistry = contentTypeRegistry;
        }

        public IContentType GetDefaultContentType()
        {
            return _contentTypeRegistry.GetContentType(StringConstants.CSharpLspLanguageName);
        }
    }
}


text:
"""A script for running Robot Framework's acceptance tests.

Usage:  run_atests.py interpreter [options] datasource(s)

Data sources are paths to directories or files under `robot` folder.

Available options are the same that can be used with Robot Framework.
See its help (e.g. `pybot --help`) for more information.

The specified interpreter is used by acceptance tests under `robot` to
run test cases under `testdata`. It can be simply `python` or `jython`
(if they are in PATH) or to a path a selected interpreter (e.g.
`/usr/bin/python26`). Note that this script itself must always be
executed with Python 2.6 or newer.

Examples:
$ atest/run_atests.py python --test example atest/robot
$ atest/run_atests.py /usr/bin/jython25 atest/robot/tags/tag_doc.txt
"""

import os
import shutil
import signal
import subprocess
import sys
import tempfile
from os.path import abspath, basename, dirname, exists, join, normpath, splitext

if sys.version_info < (2, 6):
    sys.exit('Running this script requires Python 2.6 or newer.')

CURDIR = dirname(abspath(__file__))
RUNNER = normpath(join(CURDIR, '..', 'src', 'robot', 'run.py'))
ARGUMENTS = ' '.join('''
--doc RobotSPFrameworkSPacceptanceSPtests
--reporttitle RobotSPFrameworkSPTestSPReport
--logtitle RobotSPFrameworkSPTestSPLog
--metadata Interpreter:%(INTERPRETER)s
--metadata Platform:%(PLATFORM)s
--variable INTERPRETER:%(INTERPRETER)s
--variable PYTHON:%(PYTHON)s
--variable JYTHON:%(JYTHON)s
--variable IRONPYTHON:%(IRONPYTHON)s
--variable STANDALONE_JYTHON:NO
--pythonpath %(PYTHONPATH)s
--include %(INCLUDE)s
--outputdir %(OUTPUTDIR)s
--output output.xml
--report report.html
--log log.html
--splitlog
--escape space:SP
--escape star:STAR
--escape paren1:PAR1
--escape paren2:PAR2
--critical regression
--SuiteStatLevel 3
--TagStatCombine jybotNOTpybot
--TagStatCombine pybotNOTjybot
--TagStatExclude pybot
--TagStatExclude jybot
--TagStatExclude x-*
'''.strip().split())

def atests(interpreter_path, *params):
    interpreter = _get_interpreter_basename(interpreter_path)
    resultdir, tempdir = _get_result_and_temp_dirs(interpreter)
    args = ARGUMENTS % {
        'PYTHONPATH' : join(CURDIR, 'resources'),
        'OUTPUTDIR' : resultdir,
        'INTERPRETER': interpreter_path,
        'PYTHON': interpreter_path if 'python' in interpreter else '',
        'JYTHON': interpreter_path if 'jython' in interpreter else '',
        'IRONPYTHON': interpreter_path if 'ipy' in interpreter else '',
        'PLATFORM': sys.platform,
        'INCLUDE': 'jybot' if 'jython' in interpreter else 'pybot'
    }
    if os.name == 'nt':
        args += ' --exclude x-exclude-on-windows'
    if sys.platform == 'darwin' and 'python' in interpreter:
        args += ' --exclude x-exclude-on-osx-python'
    if 'ipy' in interpreter:
        args += ' --noncritical x-fails-on-ipy'
    command = '%s %s %s %s' % (sys.executable, RUNNER, args, ' '.join(params))
    environ = dict(os.environ, TEMPDIR=tempdir)
    print 'Running command\n%s\n' % command
    sys.stdout.flush()
    signal.signal(signal.SIGINT, signal.SIG_IGN)
    return subprocess.call(command.split(), env=environ)

def _get_interpreter_basename(interpreter):
    interpreter = basename(interpreter)
    base, ext  = splitext(interpreter)
    if ext.lower() in ('.sh', '.bat', '.cmd', '.exe'):
        return base
    return interpreter

def _get_result_and_temp_dirs(interpreter):
    resultdir = join(CURDIR, 'results', interpreter)
    tempdir = join(tempfile.gettempdir(), 'robottests', interpreter)
    if exists(resultdir):
        shutil.rmtree(resultdir)
    if exists(tempdir):
        shutil.rmtree(tempdir)
    os.makedirs(tempdir)
    return resultdir, tempdir

if __name__ == '__main__':
    if len(sys.argv) == 1 or '--help' in sys.argv:
        print __doc__
        rc = 251
    else:
        rc = atests(*sys.argv[1:])
    sys.exit(rc)


text:
import re
import requests
import logging
import asyncio
import json
from urllib.parse import urlparse
from bs4 import BeautifulSoup, SoupStrainer

logging.basicConfig(level=logging.DEBUG)

class PDFExaminer:
    def __init__(self, url):

        self.url = url
        self.tasks = []
        self.json = []
        self.loop = asyncio.get_event_loop()

        coros = [asyncio.ensure_future(self.__get_first_page(self.url))]
        futures = [self.loop.run_until_complete(c) for c in coros]

        logging.debug('Finished __get_first_page: {}'.format(futures))
        logging.debug('Finished __get_first_page: {} json objects'.format(len(self.json)))

    async def __get_first_page(self, url):

        logging.debug('Running: __get_first_page(), on {}'.format(url))

        req = requests.get(url)
        req_q = asyncio.Queue()
        req_q.put_nowait(req)

        coros = [await asyncio.ensure_future(self.__get_first_page_a(req_q))]

        [logging.debug('Finished: __get_first_page: {}'.format(c)) for c in coros]

    async def __get_first_page_a(self, queue):

        logging.debug('Running: __get_first_page_a()')

        # host = urlparse(self.url).netloc

        while not queue.empty():

            req = await queue.get()
            content = req.content

            if req.status_code == 200:

                tag = 'a'
                # Search for <a> tags containing 'pdfsearch.php'
                tag = SoupStrainer(tag, href=re.compile('pdfsearch.php'))
                parsed = BeautifulSoup(content, 'html.parser', parse_only=tag)

                # all the href's
                hrefs = [t['href'] for t in parsed]

                # pdfsearch.php?hash=8108fb536c55ef61d58603360f42296f
                regex = '(?<=pdfsearch[\.]php[\?]hash=)[a-fA-F0-9]*'
                regex = re.compile(regex)

                md5_q = asyncio.Queue()
                for h in hrefs:
                    m = re.findall(regex, h)
                    if len(m) > 0:
                        md5_q.put_nowait(m[0])

                coros = [await asyncio.ensure_future(self.__get_second_page(md5_q))]

                [logging.debug('Finished: __get_first_page_a: {}'.format(c)) for c in coros]

            else:
                raise logging.error(req.status_code)

    async def __get_second_page(self, queue):

        logging.debug('Running: __get_second_page()')

        while not queue.empty():

            md5 = await queue.get()
            # Old URL for file data info in HTML
            url = 'https://www.malwaretracker.com/pdfdata.php?md5=' + md5 + '&type=document'
            # New URL for file data in JSON!
            url = 'https://www.pdfexaminer.com/pdfapirep.php?type=json&md5=' + md5
            req = requests.get(url)
            json_content = req.content
            json_content = json.loads(req.content)

            self.json.append(json_content)

            logging.debug('Finished: __get_second_page: {}'.format(md5))

r = PDFExaminer('https://www.pdfexaminer.com/pdfrecent.php')


text:
from copy import deepcopy

import numpy as np

from .evoked import _generate_noise
from ..event import _get_stim_channel
from ..io.pick import pick_types, pick_info, pick_channels
from ..source_estimate import VolSourceEstimate
from ..cov import make_ad_hoc_cov, read_cov
from ..bem import fit_sphere_to_headshape, make_sphere_model, read_bem_solution
from ..io import RawArray, _BaseRaw
from ..chpi import read_head_pos, head_pos_to_trans_rot_t, _get_hpi_info
from ..io.constants import FIFF
from ..forward import (_magnetic_dipole_field_vec, _merge_meg_eeg_fwds,
                       _stc_src_sel, convert_forward_solution,
                       _prepare_for_forward, _transform_orig_meg_coils,
                       _compute_forwards, _to_forward_dict)
from ..transforms import _get_trans, transform_surface_to
from ..source_space import _ensure_src, _points_outside_surface
from ..source_estimate import _BaseSourceEstimate
from ..utils import logger, verbose, check_random_state, warn
from ..parallel import check_n_jobs
from ..externals.six import string_types

def _log_ch(start, info, ch):
    """Helper to log channel information"""
    if ch is not None:
        extra, just, ch = ' stored on channel:', 50, info['ch_names'][ch]
    else:
        extra, just, ch = ' not stored', 0, ''
    logger.info((start + extra).ljust(just) + ch)

@verbose
def simulate_raw(raw, stc, trans, src, bem, cov='simple',
                 blink=False, ecg=False, chpi=False, head_pos=None,
                 mindist=1.0, interp='cos2', iir_filter=None, n_jobs=1,
                 random_state=None, verbose=None):
    """Simulate raw data with head movements

    Parameters
    ----------
    raw : instance of Raw
        The raw template to use for simulation. The ``info``, ``times``,
        and potentially ``first_samp`` properties will be used.
    stc : instance of SourceEstimate
        The source estimate to use to simulate data. Must have the same
        sample rate as the raw data.
    trans : dict | str | None
        Either a transformation filename (usually made using mne_analyze)
        or an info dict (usually opened using read_trans()).
        If string, an ending of `.fif` or `.fif.gz` will be assumed to
        be in FIF format, any other ending will be assumed to be a text
        file with a 4x4 transformation matrix (like the `--trans` MNE-C
        option). If trans is None, an identity transform will be used.
    src : str | instance of SourceSpaces
        Source space corresponding to the stc. If string, should be a source
        space filename. Can also be an instance of loaded or generated
        SourceSpaces.
    bem : str | dict
        BEM solution  corresponding to the stc. If string, should be a BEM
        solution filename (e.g., "sample-5120-5120-5120-bem-sol.fif").
    cov : instance of Covariance | str | None
        The sensor covariance matrix used to generate noise. If None,
        no noise will be added. If 'simple', a basic (diagonal) ad-hoc
        noise covariance will be used. If a string, then the covariance
        will be loaded.
    blink : bool
        If true, add simulated blink artifacts. See Notes for details.
    ecg : bool
        If true, add simulated ECG artifacts. See Notes for details.
    chpi : bool
        If true, simulate continuous head position indicator information.
        Valid cHPI information must encoded in ``raw.info['hpi_meas']``
        to use this option.
    head_pos : None | str | dict | tuple | array
        Name of the position estimates file. Should be in the format of
        the files produced by maxfilter. If dict, keys should
        be the time points and entries should be 4x4 ``dev_head_t``
        matrices. If None, the original head position (from
        ``info['dev_head_t']``) will be used. If tuple, should have the
        same format as data returned by `head_pos_to_trans_rot_t`.
        If array, should be of the form returned by `read_head_pos`.
    mindist : float
        Minimum distance between sources and the inner skull boundary
        to use during forward calculation.
    interp : str
        Either 'cos2', 'linear', or 'zero', the type of forward-solution
        interpolation to use between forward solutions at different
        head positions.
    iir_filter : None | array
        IIR filter coefficients (denominator) e.g. [1, -1, 0.2].
    n_jobs : int
        Number of jobs to use.
    random_state : None | int | np.random.RandomState
        The random generator state used for blink, ECG, and sensor
        noise randomization.
    verbose : bool, str, int, or None
        If not None, override default verbose level (see mne.verbose).

    Returns
    -------
    raw : instance of Raw
        The simulated raw file.

    See Also
    --------
    read_head_pos

    Notes
    -----
    Events coded with the position number (starting at 1) will be stored
    in the trigger channel (if available) at times corresponding to t=0
    in the ``stc``.

    The resulting SNR will be determined by the structure of the noise
    covariance, the amplitudes of ``stc``, and the head position(s) provided.

    The blink and ECG artifacts are generated by 1) placing impulses at
    random times of activation, and 2) convolving with activation kernel
    functions. In both cases, the scale-factors of the activation functions
    (and for the resulting EOG and ECG channel traces) were chosen based on
    visual inspection to yield amplitudes generally consistent with those
    seen in experimental data. Noisy versions of the blink and ECG
    activations will be stored in the first EOG and ECG channel in the
    raw file, respectively, if they exist.

    For blink artifacts:

        1. Random activation times are drawn from an inhomogeneous poisson
           process whose blink rate oscillates between 4.5 blinks/minute
           and 17 blinks/minute based on the low (reading) and high (resting)
           blink rates from [1]_.
        2. The activation kernel is a 250 ms Hanning window.
        3. Two activated dipoles are located in the z=0 plane (in head
           coordinates) at ±30 degrees away from the y axis (nasion).
        4. Activations affect MEG and EEG channels.

    For ECG artifacts:

        1. Random inter-beat intervals are drawn from a uniform distribution
           of times corresponding to 40 and 80 beats per minute.
        2. The activation function is the sum of three Hanning windows with
           varying durations and scales to make a more complex waveform.
        3. The activated dipole is located one (estimated) head radius to
           the left (-x) of head center and three head radii below (+z)
           head center; this dipole is oriented in the +x direction.
        4. Activations only affect MEG channels.

    .. versionadded:: 0.10.0

    References
    ----------
    .. [1] Bentivoglio et al. "Analysis of blink rate patterns in normal
           subjects" Movement Disorders, 1997 Nov;12(6):1028-34.
    """
    if not isinstance(raw, _BaseRaw):
        raise TypeError('raw should be an instance of Raw')
    times, info, first_samp = raw.times, raw.info, raw.first_samp
    raw_verbose = raw.verbose

    # Check for common flag errors and try to override
    if not isinstance(stc, _BaseSourceEstimate):
        raise TypeError('stc must be a SourceEstimate')
    if not np.allclose(info['sfreq'], 1. / stc.tstep):
        raise ValueError('stc and info must have same sample rate')
    if len(stc.times) <= 2:  # to ensure event encoding works
        raise ValueError('stc must have at least three time points')

    stim = False if len(pick_types(info, meg=False, stim=True)) == 0 else True
    n_jobs = check_n_jobs(n_jobs)

    rng = check_random_state(random_state)
    if interp not in ('cos2', 'linear', 'zero'):
        raise ValueError('interp must be "cos2", "linear", or "zero"')

    if head_pos is None:  # use pos from file
        dev_head_ts = [info['dev_head_t']] * 2
        offsets = np.array([0, len(times)])
        interp = 'zero'
    # Use position data to simulate head movement
    else:
        if isinstance(head_pos, string_types):
            head_pos = read_head_pos(head_pos)
        if isinstance(head_pos, np.ndarray):
            head_pos = head_pos_to_trans_rot_t(head_pos)
        if isinstance(head_pos, tuple):  # can be an already-loaded pos file
            transs, rots, ts = head_pos
            ts -= first_samp / info['sfreq']  # MF files need reref
            dev_head_ts = [np.r_[np.c_[r, t[:, np.newaxis]], [[0, 0, 0, 1]]]
                           for r, t in zip(rots, transs)]
            del transs, rots
        elif isinstance(head_pos, dict):
            ts = np.array(list(head_pos.keys()), float)
            ts.sort()
            dev_head_ts = [head_pos[float(tt)] for tt in ts]
        else:
            raise TypeError('unknown head_pos type %s' % type(head_pos))
        bad = ts < 0
        if bad.any():
            raise RuntimeError('All position times must be >= 0, found %s/%s'
                               '< 0' % (bad.sum(), len(bad)))
        bad = ts > times[-1]
        if bad.any():
            raise RuntimeError('All position times must be <= t_end (%0.1f '
                               'sec), found %s/%s bad values (is this a split '
                               'file?)' % (times[-1], bad.sum(), len(bad)))
        if ts[0] > 0:
            ts = np.r_[[0.], ts]
            dev_head_ts.insert(0, info['dev_head_t']['trans'])
        dev_head_ts = [{'trans': d, 'to': info['dev_head_t']['to'],
                        'from': info['dev_head_t']['from']}
                       for d in dev_head_ts]
        if ts[-1] < times[-1]:
            dev_head_ts.append(dev_head_ts[-1])
            ts = np.r_[ts, [times[-1]]]
        offsets = raw.time_as_index(ts)
        offsets[-1] = len(times)  # fix for roundoff error
        assert offsets[-2] != offsets[-1]
        del ts

    src = _ensure_src(src, verbose=False)
    if isinstance(bem, string_types):
        bem = read_bem_solution(bem, verbose=False)
    if isinstance(cov, string_types):
        if cov == 'simple':
            cov = make_ad_hoc_cov(info, verbose=False)
        else:
            cov = read_cov(cov, verbose=False)
    assert np.array_equal(offsets, np.unique(offsets))
    assert len(offsets) == len(dev_head_ts)
    approx_events = int((len(times) / info['sfreq']) /
                        (stc.times[-1] - stc.times[0]))
    logger.info('Provided parameters will provide approximately %s event%s'
                % (approx_events, '' if approx_events == 1 else 's'))

    # Extract necessary info
    meeg_picks = pick_types(info, meg=True, eeg=True, exclude=[])  # for sim
    meg_picks = pick_types(info, meg=True, eeg=False, exclude=[])  # for CHPI
    fwd_info = pick_info(info, meeg_picks)
    fwd_info['projs'] = []  # Ensure no 'projs' applied
    logger.info('Setting up raw simulation: %s position%s, "%s" interpolation'
                % (len(dev_head_ts), 's' if len(dev_head_ts) != 1 else '',
                   interp))

    verts = stc.vertices
    verts = [verts] if isinstance(stc, VolSourceEstimate) else verts
    src = _restrict_source_space_to(src, verts)

    # array used to store result
    raw_data = np.zeros((len(info['ch_names']), len(times)))

    # figure out our cHPI, ECG, and blink dipoles
    R, r0 = fit_sphere_to_headshape(info, units='m', verbose=False)[:2]
    ecg_rr = blink_rrs = exg_bem = hpi_rrs = None
    ecg = ecg and len(meg_picks) > 0
    chpi = chpi and len(meg_picks) > 0
    if chpi:
        hpi_freqs, hpi_rrs, hpi_pick, hpi_ons = _get_hpi_info(info)[:4]
        hpi_nns = hpi_rrs / np.sqrt(np.sum(hpi_rrs * hpi_rrs,
                                           axis=1))[:, np.newaxis]
        # turn on cHPI in file
        raw_data[hpi_pick, :] = hpi_ons.sum()
        _log_ch('cHPI status bits enbled and', info, hpi_pick)
    if blink or ecg:
        exg_bem = make_sphere_model(r0, head_radius=R,
                                    relative_radii=(0.97, 0.98, 0.99, 1.),
                                    sigmas=(0.33, 1.0, 0.004, 0.33),
                                    verbose=False)
    if blink:
        # place dipoles at 45 degree angles in z=0 plane
        blink_rrs = np.array([[np.cos(np.pi / 3.), np.sin(np.pi / 3.), 0.],
                              [-np.cos(np.pi / 3.), np.sin(np.pi / 3), 0.]])
        blink_rrs /= np.sqrt(np.sum(blink_rrs *
                                    blink_rrs, axis=1))[:, np.newaxis]
        blink_rrs *= 0.96 * R
        blink_rrs += r0
        # oriented upward
        blink_nns = np.array([[0., 0., 1.], [0., 0., 1.]])
        # Blink times drawn from an inhomogeneous poisson process
        # by 1) creating the rate and 2) pulling random numbers
        blink_rate = (1 + np.cos(2 * np.pi * 1. / 60. * times)) / 2.
        blink_rate *= 12.5 / 60.
        blink_rate += 4.5 / 60.
        blink_data = rng.rand(len(times)) < blink_rate / info['sfreq']
        blink_data = blink_data * (rng.rand(len(times)) + 0.5)  # varying amps
        # Activation kernel is a simple hanning window
        blink_kernel = np.hanning(int(0.25 * info['sfreq']))
        blink_data = np.convolve(blink_data, blink_kernel,
                                 'same')[np.newaxis, :] * 1e-7
        # Add rescaled noisy data to EOG ch
        ch = pick_types(info, meg=False, eeg=False, eog=True)
        noise = rng.randn(blink_data.shape[1]) * 5e-6
        if len(ch) >= 1:
            ch = ch[-1]
            raw_data[ch, :] = blink_data * 1e3 + noise
        else:
            ch = None
        _log_ch('Blinks simulated and trace', info, ch)
        del blink_kernel, blink_rate, noise
    if ecg:
        ecg_rr = np.array([[-R, 0, -3 * R]])
        max_beats = int(np.ceil(times[-1] * 80. / 60.))
        # activation times with intervals drawn from a uniform distribution
        # based on activation rates between 40 and 80 beats per minute
        cardiac_idx = np.cumsum(rng.uniform(60. / 80., 60. / 40., max_beats) *
                                info['sfreq']).astype(int)
        cardiac_idx = cardiac_idx[cardiac_idx < len(times)]
        cardiac_data = np.zeros(len(times))
        cardiac_data[cardiac_idx] = 1
        # kernel is the sum of three hanning windows
        cardiac_kernel = np.concatenate([
            2 * np.hanning(int(0.04 * info['sfreq'])),
            -0.3 * np.hanning(int(0.05 * info['sfreq'])),
            0.2 * np.hanning(int(0.26 * info['sfreq']))], axis=-1)
        ecg_data = np.convolve(cardiac_data, cardiac_kernel,
                               'same')[np.newaxis, :] * 15e-8
        # Add rescaled noisy data to ECG ch
        ch = pick_types(info, meg=False, eeg=False, ecg=True)
        noise = rng.randn(ecg_data.shape[1]) * 1.5e-5
        if len(ch) >= 1:
            ch = ch[-1]
            raw_data[ch, :] = ecg_data * 2e3 + noise
        else:
            ch = None
        _log_ch('ECG simulated and trace', info, ch)
        del cardiac_data, cardiac_kernel, max_beats, cardiac_idx

    stc_event_idx = np.argmin(np.abs(stc.times))
    if stim:
        event_ch = pick_channels(info['ch_names'],
                                 _get_stim_channel(None, info))[0]
        raw_data[event_ch, :] = 0.
    else:
        event_ch = None
    _log_ch('Event information', info, event_ch)
    used = np.zeros(len(times), bool)
    stc_indices = np.arange(len(times)) % len(stc.times)
    raw_data[meeg_picks, :] = 0.
    hpi_mag = 70e-9
    last_fwd = last_fwd_chpi = last_fwd_blink = last_fwd_ecg = src_sel = None
    zf = None  # final filter conditions for the noise
    # don't process these any more if no MEG present
    for fi, (fwd, fwd_blink, fwd_ecg, fwd_chpi) in \
        enumerate(_iter_forward_solutions(
            fwd_info, trans, src, bem, exg_bem, dev_head_ts, mindist,
            hpi_rrs, blink_rrs, ecg_rr, n_jobs)):
        # must be fixed orientation
        # XXX eventually we could speed this up by allowing the forward
        # solution code to only compute the normal direction
        fwd = convert_forward_solution(fwd, surf_ori=True,
                                       force_fixed=True, verbose=False)
        if blink:
            fwd_blink = fwd_blink['sol']['data']
            for ii in range(len(blink_rrs)):
                fwd_blink[:, ii] = np.dot(fwd_blink[:, 3 * ii:3 * (ii + 1)],
                                          blink_nns[ii])
            fwd_blink = fwd_blink[:, :len(blink_rrs)]
            fwd_blink = fwd_blink.sum(axis=1)[:, np.newaxis]
        # just use one arbitrary direction
        if ecg:
            fwd_ecg = fwd_ecg['sol']['data'][:, [0]]

        # align cHPI magnetic dipoles in approx. radial direction
        if chpi:
            for ii in range(len(hpi_rrs)):
                fwd_chpi[:, ii] = np.dot(fwd_chpi[:, 3 * ii:3 * (ii + 1)],
                                         hpi_nns[ii])
            fwd_chpi = fwd_chpi[:, :len(hpi_rrs)].copy()

        if src_sel is None:
            src_sel = _stc_src_sel(fwd['src'], stc)
            verts = stc.vertices
            verts = [verts] if isinstance(stc, VolSourceEstimate) else verts
            diff_ = sum([len(v) for v in verts]) - len(src_sel)
            if diff_ != 0:
                warn('%s STC vertices omitted due to fwd calculation' % diff_)
        if last_fwd is None:
            last_fwd, last_fwd_blink, last_fwd_ecg, last_fwd_chpi = \
                fwd, fwd_blink, fwd_ecg, fwd_chpi
            continue

        # set up interpolation
        n_pts = offsets[fi] - offsets[fi - 1]
        if interp == 'zero':
            interps = None
        else:
            if interp == 'linear':
                interps = np.linspace(1, 0, n_pts, endpoint=False)
            else:  # interp == 'cos2':
                interps = np.cos(0.5 * np.pi * np.arange(n_pts)) ** 2
            interps = np.array([interps, 1 - interps])

        assert not used[offsets[fi - 1]:offsets[fi]].any()
        event_idxs = np.where(stc_indices[offsets[fi - 1]:offsets[fi]] ==
                              stc_event_idx)[0] + offsets[fi - 1]
        if stim:
            raw_data[event_ch, event_idxs] = fi

        logger.info('  Simulating data for %0.3f-%0.3f sec with %s event%s'
                    % (tuple(offsets[fi - 1:fi + 1] / info['sfreq']) +
                       (len(event_idxs), '' if len(event_idxs) == 1 else 's')))

        # Process data in large chunks to save on memory
        chunk_size = 10000
        chunks = np.concatenate((np.arange(offsets[fi - 1], offsets[fi],
                                           chunk_size), [offsets[fi]]))
        for start, stop in zip(chunks[:-1], chunks[1:]):
            assert stop - start <= chunk_size

            used[start:stop] = True
            if interp == 'zero':
                this_interp = None
            else:
                this_interp = interps[:, start - chunks[0]:stop - chunks[0]]
            time_sl = slice(start, stop)
            this_t = np.arange(start, stop) / info['sfreq']
            stc_idxs = stc_indices[time_sl]

            # simulate brain data
            raw_data[meeg_picks, time_sl] = \
                _interp(last_fwd['sol']['data'], fwd['sol']['data'],
                        stc.data[:, stc_idxs][src_sel], this_interp)

            # add sensor noise, ECG, blink, cHPI
            if cov is not None:
                noise, zf = _generate_noise(fwd_info, cov, iir_filter, rng,
                                            len(stc_idxs), zi=zf)
                raw_data[meeg_picks, time_sl] += noise
            if blink:
                raw_data[meeg_picks, time_sl] += \
                    _interp(last_fwd_blink, fwd_blink, blink_data[:, time_sl],
                            this_interp)
            if ecg:
                raw_data[meg_picks, time_sl] += \
                    _interp(last_fwd_ecg, fwd_ecg, ecg_data[:, time_sl],
                            this_interp)
            if chpi:
                sinusoids = np.zeros((len(hpi_freqs), len(stc_idxs)))
                for fidx, freq in enumerate(hpi_freqs):
                    sinusoids[fidx] = 2 * np.pi * freq * this_t
                    sinusoids[fidx] = hpi_mag * np.sin(sinusoids[fidx])
                raw_data[meg_picks, time_sl] += \
                    _interp(last_fwd_chpi, fwd_chpi, sinusoids, this_interp)

        assert used[offsets[fi - 1]:offsets[fi]].all()

        # prepare for next iteration
        last_fwd, last_fwd_blink, last_fwd_ecg, last_fwd_chpi = \
            fwd, fwd_blink, fwd_ecg, fwd_chpi
    assert used.all()
    raw = RawArray(raw_data, info, first_samp=first_samp, verbose=False)
    raw.verbose = raw_verbose
    logger.info('Done')
    return raw

def _iter_forward_solutions(info, trans, src, bem, exg_bem, dev_head_ts,
                            mindist, hpi_rrs, blink_rrs, ecg_rrs, n_jobs):
    """Calculate a forward solution for a subject"""
    mri_head_t, trans = _get_trans(trans)
    logger.info('Setting up forward solutions')
    megcoils, meg_info, compcoils, megnames, eegels, eegnames, rr, info, \
        update_kwargs, bem = _prepare_for_forward(
            src, mri_head_t, info, bem, mindist, n_jobs, verbose=False)
    del (src, mindist)

    eegfwd = _compute_forwards(rr, bem, [eegels], [None],
                               [None], ['eeg'], n_jobs, verbose=False)[0]
    eegfwd = _to_forward_dict(eegfwd, eegnames)
    if blink_rrs is not None:
        eegblink = _compute_forwards(blink_rrs, exg_bem, [eegels], [None],
                                     [None], ['eeg'], n_jobs,
                                     verbose=False)[0]
        eegblink = _to_forward_dict(eegblink, eegnames)

    # short circuit here if there are no MEG channels (don't need to iterate)
    if len(pick_types(info, meg=True)) == 0:
        eegfwd.update(**update_kwargs)
        for _ in dev_head_ts:
            yield eegfwd, eegblink, None, None
        return

    coord_frame = FIFF.FIFFV_COORD_HEAD
    if not bem['is_sphere']:
        idx = np.where(np.array([s['id'] for s in bem['surfs']]) ==
                       FIFF.FIFFV_BEM_SURF_ID_BRAIN)[0]
        assert len(idx) == 1
        bem_surf = transform_surface_to(bem['surfs'][idx[0]], coord_frame,
                                        mri_head_t)
    for ti, dev_head_t in enumerate(dev_head_ts):
        # Could be *slightly* more efficient not to do this N times,
        # but the cost here is tiny compared to actual fwd calculation
        logger.info('Computing gain matrix for transform #%s/%s'
                    % (ti + 1, len(dev_head_ts)))
        _transform_orig_meg_coils(megcoils, dev_head_t)
        _transform_orig_meg_coils(compcoils, dev_head_t)

        # Make sure our sensors are all outside our BEM
        coil_rr = [coil['r0'] for coil in megcoils]
        if not bem['is_sphere']:
            outside = _points_outside_surface(coil_rr, bem_surf, n_jobs,
                                              verbose=False)
        else:
            d = coil_rr - bem['r0']
            outside = np.sqrt(np.sum(d * d, axis=1)) > bem.radius
        if not outside.all():
            raise RuntimeError('%s MEG sensors collided with inner skull '
                               'surface for transform %s'
                               % (np.sum(~outside), ti))

        # Compute forward
        megfwd = _compute_forwards(rr, bem, [megcoils], [compcoils],
                                   [meg_info], ['meg'], n_jobs,
                                   verbose=False)[0]
        megfwd = _to_forward_dict(megfwd, megnames)
        fwd = _merge_meg_eeg_fwds(megfwd, eegfwd, verbose=False)
        fwd.update(**update_kwargs)

        fwd_blink = fwd_ecg = fwd_chpi = None
        if blink_rrs is not None:
            megblink = _compute_forwards(blink_rrs, exg_bem, [megcoils],
                                         [compcoils], [meg_info], ['meg'],
                                         n_jobs, verbose=False)[0]
            megblink = _to_forward_dict(megblink, megnames)
            fwd_blink = _merge_meg_eeg_fwds(megblink, eegblink, verbose=False)
        if ecg_rrs is not None:
            megecg = _compute_forwards(ecg_rrs, exg_bem, [megcoils],
                                       [compcoils], [meg_info], ['meg'],
                                       n_jobs, verbose=False)[0]
            fwd_ecg = _to_forward_dict(megecg, megnames)
        if hpi_rrs is not None:
            fwd_chpi = _magnetic_dipole_field_vec(hpi_rrs, megcoils).T
        yield fwd, fwd_blink, fwd_ecg, fwd_chpi

def _restrict_source_space_to(src, vertices):
    """Helper to trim down a source space"""
    assert len(src) == len(vertices)
    src = deepcopy(src)
    for s, v in zip(src, vertices):
        s['inuse'].fill(0)
        s['nuse'] = len(v)
        s['vertno'] = v
        s['inuse'][s['vertno']] = 1
        del s['pinfo']
        del s['nuse_tri']
        del s['use_tris']
        del s['patch_inds']
    return src

def _interp(data_1, data_2, stc_data, interps):
    """Helper to interpolate"""
    out_data = np.dot(data_1, stc_data)
    if interps is not None:
        out_data *= interps[0]
        data_1 = np.dot(data_1, stc_data)
        data_1 *= interps[1]
        out_data += data_1
        del data_1
    return out_data