text:
from __future__ import absolute_import,print_function

import os
import sys
import code
import warnings
import string
import inspect

import argparse

from flask import _request_ctx_stack

from .cli import prompt, prompt_pass, prompt_bool, prompt_choices
from ._compat import izip, text_type

class InvalidCommand(Exception):
    """\
        This is a generic error for "bad" commands.
        It is not used in Flask-Script itself, but you should throw
        this error (or one derived from it) in your command handlers,
        and your main code should display this error's message without
        a stack trace.

        This way, we maintain interoperability if some other plug-in code
        supplies Flask-Script hooks.
        """
    pass

class Group(object):
    """
    Stores argument groups and mutually exclusive groups for
    `ArgumentParser.add_argument_group <http://argparse.googlecode.com/svn/trunk/doc/other-methods.html#argument-groups>`
    or `ArgumentParser.add_mutually_exclusive_group <http://argparse.googlecode.com/svn/trunk/doc/other-methods.html#add_mutually_exclusive_group>`.

    Note: The title and description params cannot be used with the exclusive
    or required params.

    :param options: A list of Option classes to add to this group
    :param title: A string to use as the title of the argument group
    :param description: A string to use as the description of the argument
                        group
    :param exclusive: A boolean indicating if this is an argument group or a
                      mutually exclusive group
    :param required: A boolean indicating if this mutually exclusive group
                     must have an option selected
    """

    def __init__(self, *options, **kwargs):
        self.option_list = options

        self.title = kwargs.pop("title", None)
        self.description = kwargs.pop("description", None)
        self.exclusive = kwargs.pop("exclusive", None)
        self.required = kwargs.pop("required", None)

        if ((self.title or self.description) and
                (self.required or self.exclusive)):
            raise TypeError("title and/or description cannot be used with "
                            "required and/or exclusive.")

        super(Group, self).__init__(**kwargs)

    def get_options(self):
        """
        By default, returns self.option_list. Override if you
        need to do instance-specific configuration.
        """
        return self.option_list

class Option(object):
    """
    Stores positional and optional arguments for `ArgumentParser.add_argument
    <http://argparse.googlecode.com/svn/trunk/doc/add_argument.html>`_.

    :param name_or_flags: Either a name or a list of option strings,
                          e.g. foo or -f, --foo
    :param action: The basic type of action to be taken when this argument
                   is encountered at the command-line.
    :param nargs: The number of command-line arguments that should be consumed.
    :param const: A constant value required by some action and nargs selections.
    :param default: The value produced if the argument is absent from
                    the command-line.
    :param type: The type to which the command-line arg should be converted.
    :param choices: A container of the allowable values for the argument.
    :param required: Whether or not the command-line option may be omitted
                     (optionals only).
    :param help: A brief description of what the argument does.
    :param metavar: A name for the argument in usage messages.
    :param dest: The name of the attribute to be added to the object
                 returned by parse_args().
    """

    def __init__(self, *args, **kwargs):
        self.args = args
        self.kwargs = kwargs

class Command(object):
    """
    Base class for creating commands.

    :param func:  Initialize this command by introspecting the function.
    """

    option_list = ()
    help_args = None

    def __init__(self, func=None):
        if func is None:
            if not self.option_list:
                self.option_list = []
            return

        args, varargs, keywords, defaults = inspect.getargspec(func)
        if inspect.ismethod(func):
            args = args[1:]

        options = []

        # first arg is always "app" : ignore

        defaults = defaults or []
        kwargs = dict(izip(*[reversed(l) for l in (args, defaults)]))

        for arg in args:

            if arg in kwargs:

                default = kwargs[arg]

                if isinstance(default, bool):
                    options.append(Option('-%s' % arg[0],
                                          '--%s' % arg,
                                          action="store_true",
                                          dest=arg,
                                          required=False,
                                          default=default))
                else:
                    options.append(Option('-%s' % arg[0],
                                          '--%s' % arg,
                                          dest=arg,
                                          type=text_type,
                                          required=False,
                                          default=default))

            else:
                options.append(Option(arg, type=text_type))

        self.run = func
        self.__doc__ = func.__doc__
        self.option_list = options

    @property
    def description(self):
        description = self.__doc__ or ''
        return description.strip()

    def add_option(self, option):
        """
        Adds Option to option list.
        """
        self.option_list.append(option)

    def get_options(self):
        """
        By default, returns self.option_list. Override if you
        need to do instance-specific configuration.
        """
        return self.option_list

    def create_parser(self, *args, **kwargs):
        func_stack = kwargs.pop('func_stack',())
        parent = kwargs.pop('parent',None)
        parser = argparse.ArgumentParser(*args, add_help=False, **kwargs)
        help_args = self.help_args
        while help_args is None and parent is not None:
            help_args = parent.help_args
            parent = getattr(parent,'parent',None)

        if help_args:
            from flask_script import add_help
            add_help(parser,help_args)

        for option in self.get_options():
            if isinstance(option, Group):
                if option.exclusive:
                    group = parser.add_mutually_exclusive_group(
                        required=option.required,
                    )
                else:
                    group = parser.add_argument_group(
                        title=option.title,
                        description=option.description,
                    )
                for opt in option.get_options():
                    group.add_argument(*opt.args, **opt.kwargs)
            else:
                parser.add_argument(*option.args, **option.kwargs)

        parser.set_defaults(func_stack=func_stack+(self,))

        self.parser = parser
        self.parent = parent
        return parser

    def __call__(self, app=None, *args, **kwargs):
        """
        Handles the command with the given app.
        Default behaviour is to call ``self.run`` within a test request context.
        """
        with app.test_request_context():
            return self.run(*args, **kwargs)

    def run(self):
        """
        Runs a command. This must be implemented by the subclass. Should take
        arguments as configured by the Command options.
        """
        raise NotImplementedError

class Shell(Command):
    """
    Runs a Python shell inside Flask application context.

    :param banner: banner appearing at top of shell when started
    :param make_context: a callable returning a dict of variables
                         used in the shell namespace. By default
                         returns a dict consisting of just the app.
    :param use_bpython: use BPython shell if available, ignore if not.
                        The BPython shell can be turned off in command
                        line by passing the **--no-bpython** flag.
    :param use_ipython: use IPython shell if available, ignore if not.
                        The IPython shell can be turned off in command
                        line by passing the **--no-ipython** flag.
    """

    banner = ''

    help = description = 'Runs a Python shell inside Flask application context.'

    def __init__(self, banner=None, make_context=None, use_ipython=True,
                use_bpython=True):

        self.banner = banner or self.banner
        self.use_ipython = use_ipython
        self.use_bpython = use_bpython

        if make_context is None:
            make_context = lambda: dict(app=_request_ctx_stack.top.app)

        self.make_context = make_context

    def get_options(self):
        return (
            Option('--no-ipython',
                action="store_true",
                dest='no_ipython',
                default=not(self.use_ipython),
                help="Do not use the IPython shell"),
            Option('--no-bpython',
                action="store_true",
                dest='no_bpython',
                default=not(self.use_bpython),
                help="Do not use the BPython shell"),
        )

    def get_context(self):
        """
        Returns a dict of context variables added to the shell namespace.
        """
        return self.make_context()

    def run(self, no_ipython, no_bpython):
        """
        Runs the shell.  If no_bpython is False or use_bpython is True, then
        a BPython shell is run (if installed).  Else, if no_ipython is False or
        use_python is True then a IPython shell is run (if installed).
        """

        context = self.get_context()

        if not no_bpython:
            # Try BPython
            try:
                from bpython import embed
                embed(banner=self.banner, locals_=context)
                return
            except ImportError:
                pass

        if not no_ipython:
            # Try IPython
            try:
                try:
                    # 0.10.x
                    from IPython.Shell import IPShellEmbed
                    ipshell = IPShellEmbed(banner=self.banner)
                    ipshell(global_ns=dict(), local_ns=context)
                except ImportError:
                    # 0.12+
                    from IPython import embed
                    embed(banner1=self.banner, user_ns=context)
                return
            except ImportError:
                pass

        # Use basic python shell
        code.interact(self.banner, local=context)

class Server(Command):
    """
    Runs the Flask development server i.e. app.run()

    :param host: server host
    :param port: server port
    :param use_debugger: Flag whether to default to using the Werkzeug debugger.
                         This can be overriden in the command line
                         by passing the **-d** or **-D** flag.
                         Defaults to False, for security.

    :param use_reloader: Flag whether to use the auto-reloader.
                         Default to True when debugging.
                         This can be overriden in the command line by
                         passing the **-r**/**-R** flag.
    :param threaded: should the process handle each request in a separate
                     thread?
    :param processes: number of processes to spawn
    :param passthrough_errors: disable the error catching. This means that the server will die on errors but it can be useful to hook debuggers in (pdb etc.)
    :param options: :func:`werkzeug.run_simple` options.
    """

    help = description = 'Runs the Flask development server i.e. app.run()'

    def __init__(self, host='127.0.0.1', port=5000, use_debugger=None,
                 use_reloader=None, threaded=False, processes=1,
                 passthrough_errors=False, **options):

        self.port = port
        self.host = host
        self.use_debugger = use_debugger
        self.use_reloader = use_reloader if use_reloader is not None else use_debugger
        self.server_options = options
        self.threaded = threaded
        self.processes = processes
        self.passthrough_errors = passthrough_errors

    def get_options(self):

        options = (
            Option('-h', '--host',
                   dest='host',
                   default=self.host),

            Option('-p', '--port',
                   dest='port',
                   type=int,
                   default=self.port),

            Option('--threaded',
                   dest='threaded',
                   action='store_true',
                   default=self.threaded),

            Option('--processes',
                   dest='processes',
                   type=int,
                   default=self.processes),

            Option('--passthrough-errors',
                   action='store_true',
                   dest='passthrough_errors',
                   default=self.passthrough_errors),

            Option('-d', '--debug',
                   action='store_true',
                   dest='use_debugger',
                   help='enable the Werkzeug debugger (DO NOT use in production code)',
                   default=self.use_debugger),
            Option('-D', '--no-debug',
                   action='store_false',
                   dest='use_debugger',
                   help='disable the Werkzeug debugger',
                   default=self.use_debugger),

            Option('-r', '--reload',
                   action='store_true',
                   dest='use_reloader',
                   help='monitor Python files for changes (not 100%% safe for production use)',
                   default=self.use_reloader),
            Option('-R', '--no-reload',
                   action='store_false',
                   dest='use_reloader',
                   help='do not monitor Python files for changes',
                   default=self.use_reloader),
            )

        return options

    def __call__(self, app, host, port, use_debugger, use_reloader,
               threaded, processes, passthrough_errors):
        # we don't need to run the server in request context
        # so just run it directly

        if use_debugger is None:
            use_debugger = app.debug
            if use_debugger is None:
                use_debugger = True
                if sys.stderr.isatty():
                    print("Debugging is on. DANGER: Do not allow random users to connect to this server.", file=sys.stderr)
        if use_reloader is None:
            use_reloader = app.debug
        app.run(host=host,
                port=port,
                debug=use_debugger,
                use_debugger=use_debugger,
                use_reloader=use_reloader,
                threaded=threaded,
                processes=processes,
                passthrough_errors=passthrough_errors,
                **self.server_options)

class Clean(Command):
    "Remove *.pyc and *.pyo files recursively starting at current directory"
    def run(self):
        for dirpath, dirnames, filenames in os.walk('.'):
            for filename in filenames:
                if filename.endswith('.pyc') or filename.endswith('.pyo'):
                    full_pathname = os.path.join(dirpath, filename)
                    print('Removing %s' % full_pathname)
                    os.remove(full_pathname)

class ShowUrls(Command):
    """
        Displays all of the url matching routes for the project
    """
    def __init__(self, order='rule'):
        self.order = order

    def get_options(self):
        return (
            Option('url',
                   nargs='?',
                   help='Url to test (ex. /static/image.png)'),
            Option('--order',
                   dest='order',
                   default=self.order,
                   help='Property on Rule to order by (default: %s)' % self.order)
        )

        return options

    def run(self, url, order):
        from flask import current_app
        from werkzeug.exceptions import NotFound, MethodNotAllowed

        rows = []
        column_length = 0
        column_headers = ('Rule', 'Endpoint', 'Arguments')

        if url:
            try:
                rule, arguments = current_app.url_map \
                                             .bind('localhost') \
                                             .match(url, return_rule=True)
                rows.append((rule.rule, rule.endpoint, arguments))
                column_length = 3
            except (NotFound, MethodNotAllowed) as e:
                rows.append(("<%s>" % e, None, None))
                column_length = 1
        else:
            rules = sorted(current_app.url_map.iter_rules(), key=lambda rule: getattr(rule, order))
            for rule in rules:
                rows.append((rule.rule, rule.endpoint, None))
            column_length = 2

        str_template = ''
        table_width = 0

        if column_length >= 1:
            max_rule_length = max(len(r[0]) for r in rows)
            max_rule_length = max_rule_length if max_rule_length > 4 else 4
            str_template += '%-' + str(max_rule_length) + 's'
            table_width += max_rule_length

        if column_length >= 2:
            max_endpoint_length = max(len(str(r[1])) for r in rows)
            # max_endpoint_length = max(rows, key=len)
            max_endpoint_length = max_endpoint_length if max_endpoint_length > 8 else 8
            str_template += '  %-' + str(max_endpoint_length) + 's'
            table_width += 2 + max_endpoint_length

        if column_length >= 3:
            max_arguments_length = max(len(str(r[2])) for r in rows)
            max_arguments_length = max_arguments_length if max_arguments_length > 9 else 9
            str_template += '  %-' + str(max_arguments_length) + 's'
            table_width += 2 + max_arguments_length

        print(str_template % (column_headers[:column_length]))
        print('-' * table_width)

        for row in rows:
            print(str_template % row[:column_length])


text:
package app.preview

import utils.pageobjects.{PageObjectsContext, TestData}
import org.openqa.selenium.By
import play.api.Logger
import scala.language.implicitConversions

case class Data(toReviewData:Seq[(String,Seq[Object])]){

  def assertReview(claim: TestData, context: PageObjectsContext,trace:Boolean = false):Boolean = {
    toReviewData.foreach {
      t =>
        import scala.collection.JavaConverters._
        var matchesAny = false
        val elems = context.browser.webDriver.findElements(By.xpath( s"""//td[@class="review-label" and contains(.,"${t._1}")]/following-sibling::td[1]""")).asScala

        if(trace) {
          Logger("PageObject").debug("")
          Logger("PageObject").debug(s"Checking for ${t._1} and found ${elems.size} elems")
        }

        elems.foreach {
          webElem =>
            val elemValue = webElem.getText.toLowerCase.replaceAll(" ", "")
            t._2.foreach {
              fieldId =>
                val claimValue = fieldId match {
                  case id: String => claim.selectDynamic(id)
                  case transformer: Transformer => transformer.transform()
                }

                if (claimValue != null && claimValue.length > 0) {
                  val modifiedClaimValue = claimValue.toLowerCase.replaceAll(" ", "")
                  if(trace) Logger.debug(s"$modifiedClaimValue in $elemValue ? ${elemValue.contains(modifiedClaimValue)}")
                  if (elemValue.contains(modifiedClaimValue)) matchesAny = true
                }

            }
        }

        if (!matchesAny){
          Logger("PageObject").error(s"${t._1} does not match its value ${t._2}")
          return false
        }

    }
    true
  }

}
object Data{
  def build(tuples: (String,Seq[Object])*) = new Data(tuples)

  implicit def displaying(s:String) = new {
    def displays(s2:String) = s -> Seq(s2)

    def displays(s2:Object*) = s -> s2

    def displays(t:Transformer) = s -> Seq(t)
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
 * ProductAlert for changed price model
 *
 * @method Mage_ProductAlert_Model_Resource_Price _getResource()
 * @method Mage_ProductAlert_Model_Resource_Price getResource()
 * @method int getCustomerId()
 * @method Mage_ProductAlert_Model_Price setCustomerId(int $value)
 * @method int getProductId()
 * @method Mage_ProductAlert_Model_Price setProductId(int $value)
 * @method float getPrice()
 * @method Mage_ProductAlert_Model_Price setPrice(float $value)
 * @method int getWebsiteId()
 * @method Mage_ProductAlert_Model_Price setWebsiteId(int $value)
 * @method string getAddDate()
 * @method Mage_ProductAlert_Model_Price setAddDate(string $value)
 * @method string getLastSendDate()
 * @method Mage_ProductAlert_Model_Price setLastSendDate(string $value)
 * @method int getSendCount()
 * @method Mage_ProductAlert_Model_Price setSendCount(int $value)
 * @method int getStatus()
 * @method Mage_ProductAlert_Model_Price setStatus(int $value)
 *
 * @category    Mage
 * @package     Mage_ProductAlert
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_ProductAlert_Model_Price extends Mage_Core_Model_Abstract
{
    protected function _construct()
    {
        $this->_init('productalert/price');
    }

    public function getCustomerCollection()
    {
        return Mage::getResourceModel('productalert/price_customer_collection');
    }

    public function loadByParam()
    {
        if (!is_null($this->getProductId()) && !is_null($this->getCustomerId()) && !is_null($this->getWebsiteId())) {
            $this->getResource()->loadByParam($this);
        }
        return $this;
    }

    public function deleteCustomer($customerId, $websiteId = 0)
    {
        $this->getResource()->deleteCustomer($this, $customerId, $websiteId);
        return $this;
    }
}


text:
var gulp = require('gulp');
var jshint = require('gulp-jshint');
var jscs = require('gulp-jscs');
var nodemon = require('gulp-nodemon');

var jsFiles = ['*.js', 'src/**/*.js'];

gulp.task('style', function () {
    return gulp.src(jsFiles)
        .pipe(jshint())
        .pipe(jshint.reporter('jshint-stylish', {
            verbose: true
        }))
        .pipe(jscs())
        .pipe(jscs.reporter());
});

gulp.task('inject', function () {
    var wiredep = require('wiredep').stream;
    var inject = require('gulp-inject');

    var injectSrc = gulp.src(['./public/css/*.css', './public/js/*.js'], {read: false});
    var injectOptions = {
        ignorePath: '/public'
    };
    var options = {
        bowerJson: require('./bower.json'),
        directory: 'public/lib',
        ignorePath: '../../public'
    };

    return gulp.src('./src/views/*.html')
        .pipe(wiredep(options))
        .pipe(inject(injectSrc, injectOptions))
        .pipe(gulp.dest('./src/views'));
});

gulp.task('serve', ['style', 'inject'], function() {
    var options = {
        script: 'app.js',
        delayTime: 1,
        env: {
            'PORT': 4500
        },
        watch: jsFiles
    };

    return nodemon(options)
        .on('restart', function(ev) {
            console.log('Restarting...');
        });
});


text:
WorldQ is a set of SQL queries to search world database.
________________________________________________________
World database has three tables,
1. City
2. Country
3. Country Language


text:
package brooklyn.networking.sdn.calico;

import org.apache.brooklyn.api.entity.ImplementedBy;
import org.apache.brooklyn.config.ConfigKey;
import org.apache.brooklyn.core.config.ConfigKeys;
import org.apache.brooklyn.core.sensor.AttributeSensorAndConfigKey;
import org.apache.brooklyn.entity.software.base.SoftwareProcess;
import org.apache.brooklyn.util.core.flags.SetFromFlag;

import brooklyn.entity.nosql.etcd.EtcdNode;
import brooklyn.networking.sdn.SdnAgent;

/**
 * The Calico plugin
 */
@ImplementedBy(CalicoNodeImpl.class)
public interface CalicoNode extends SdnAgent {

    @SetFromFlag("version")
    ConfigKey<String> SUGGESTED_VERSION = ConfigKeys.newConfigKeyWithDefault(SoftwareProcess.SUGGESTED_VERSION, "0.4.8");

    @SetFromFlag("downloadUrl")
    ConfigKey<String> DOWNLOAD_URL = ConfigKeys.newConfigKeyWithDefault(SoftwareProcess.DOWNLOAD_URL.getConfigKey(),
            "https://github.com/Metaswitch/calico-docker/releases/download/v${version}/calicoctl");

    @SetFromFlag("etcdNode")
    AttributeSensorAndConfigKey<EtcdNode, EtcdNode> ETCD_NODE = ConfigKeys.newSensorAndConfigKey(EtcdNode.class,
            "sdn.calico.etcd.node", "The EtcdNode attached to the same DockerHost as the plugin");

    @SetFromFlag("powerstripPort")
    ConfigKey<Integer> POWERSTRIP_PORT = ConfigKeys.newIntegerConfigKey("powerstrip.port", "Powerstrip port", 2377);

}


text:
        {{ site.title }}

    {% if site.subtitle %}{{ site.subtitle }}{% endif %}


text:
package ch.heigvd.amt.gamification.services.dao;

import ch.heigvd.amt.gamification.model.ApiKey;
import java.util.UUID;
import javax.ejb.Stateless;

/**
 *
 * @author parfait
 *
 */
@Stateless
public class ApiKeyDAO extends GenericDAO<ApiKey, Long> implements ApiKeyDAOLocal {

    @Override
    public ApiKey getNewApiKey() {

        String generated = UUID.randomUUID().toString();

        while (keyExists(generated)) {
            generated = UUID.randomUUID().toString();
        }

        ApiKey key = new ApiKey();
        key.setKey(generated);
        return key;
    }

    @Override
    public boolean keyExists(String key) {
        return em.createNamedQuery("ApiKey.findByKey")
                .setParameter("key", key)
                .getResultList().size() > 0;
    }
}


text:
'use strict';

exports.__esModule = true;
exports.default = void 0;

var _AnimatedNode2 = _interopRequireDefault(require("./AnimatedNode"));

var _NativeAnimatedHelper = _interopRequireDefault(require("../NativeAnimatedHelper"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } it = o[Symbol.iterator](); return it.next.bind(it); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

var AnimatedWithChildren =
/*#__PURE__*/
function (_AnimatedNode) {
  _inheritsLoose(AnimatedWithChildren, _AnimatedNode);

  function AnimatedWithChildren() {
    var _this;

    _this = _AnimatedNode.call(this) || this;
    _this._children = [];
    return _this;
  }

  var _proto = AnimatedWithChildren.prototype;

  _proto.__makeNative = function __makeNative() {
    if (!this.__isNative) {
      this.__isNative = true;

      for (var _iterator = _createForOfIteratorHelperLoose(this._children), _step; !(_step = _iterator()).done;) {
        var child = _step.value;

        child.__makeNative();

        _NativeAnimatedHelper.default.API.connectAnimatedNodes(this.__getNativeTag(), child.__getNativeTag());
      }
    }

    _AnimatedNode.prototype.__makeNative.call(this);
  };

  _proto.__addChild = function __addChild(child) {
    if (this._children.length === 0) {
      this.__attach();
    }

    this._children.push(child);

    if (this.__isNative) {
      // Only accept "native" animated nodes as children
      child.__makeNative();

      _NativeAnimatedHelper.default.API.connectAnimatedNodes(this.__getNativeTag(), child.__getNativeTag());
    }
  };

  _proto.__removeChild = function __removeChild(child) {
    var index = this._children.indexOf(child);

    if (index === -1) {
      console.warn("Trying to remove a child that doesn't exist");
      return;
    }

    if (this.__isNative && child.__isNative) {
      _NativeAnimatedHelper.default.API.disconnectAnimatedNodes(this.__getNativeTag(), child.__getNativeTag());
    }

    this._children.splice(index, 1);

    if (this._children.length === 0) {
      this.__detach();
    }
  };

  _proto.__getChildren = function __getChildren() {
    return this._children;
  };

  _proto.__callListeners = function __callListeners(value) {
    _AnimatedNode.prototype.__callListeners.call(this, value);

    if (!this.__isNative) {
      for (var _iterator2 = _createForOfIteratorHelperLoose(this._children), _step2; !(_step2 = _iterator2()).done;) {
        var child = _step2.value;

        if (child.__getValue) {
          child.__callListeners(child.__getValue());
        }
      }
    }
  };

  return AnimatedWithChildren;
}(_AnimatedNode2.default);

var _default = AnimatedWithChildren;
exports.default = _default;
module.exports = exports.default;


text:
package org.kie.workbench.common.stunner.bpmn.backend.converters;

import java.util.function.Function;

import org.eclipse.bpmn2.Bpmn2Factory;
import org.eclipse.bpmn2.EventSubprocess;
import org.eclipse.bpmn2.FlowElement;
import org.eclipse.bpmn2.ManualTask;
import org.eclipse.bpmn2.ReceiveTask;
import org.eclipse.bpmn2.StartEvent;
import org.eclipse.bpmn2.SubProcess;
import org.eclipse.bpmn2.impl.UserTaskImpl;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kie.workbench.common.stunner.bpmn.backend.converters.tostunner.BpmnNode;
import org.kie.workbench.common.stunner.core.marshaller.MarshallingRequest;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class MatchTest {

    @Mock
    private BpmnNode defaultValue;

    @Mock
    private Function<UserTaskImpl, BpmnNode> assertUserTask;

    @Mock
    private Function<FlowElement, BpmnNode> fallback;

    @Mock
    private Function<SubProcess, BpmnNode> assertSubProcess;

    @Mock
    private BpmnNode fallbackNode;

    @Before
    public void setUp() {
        when(fallback.apply(any())).thenReturn(fallbackNode);
    }

    @Test
    public void whenExactlyTest() {
        UserTaskImpl element = (UserTaskImpl) Bpmn2Factory.eINSTANCE.createUserTask();
        Result<BpmnNode> result = match().apply(element);
        verify(assertUserTask).apply(element);
        assertTrue(result.isSuccess());
    }

    @Test
    public void whenTest() {
        EventSubprocess element = Bpmn2Factory.eINSTANCE.createEventSubprocess();
        Result<BpmnNode> result = match().apply(element);
        verify(assertSubProcess).apply(element);
        assertNotEquals(result.value(), defaultValue);
        assertTrue(result.isSuccess());
    }

    @Test
    public void testFallback() {
        StartEvent element = Bpmn2Factory.eINSTANCE.createStartEvent();
        Result<BpmnNode> result = match()
                .orElse(fallback)
                .apply(element);
        verify(fallback).apply(element);
        assertNotEquals(result.value(), defaultValue);
        assertEquals(result.value(), fallbackNode);
        assertTrue(result.isSuccess());
    }

    @Test
    public void ignoreTestAuto() {
        ManualTask element = Bpmn2Factory.eINSTANCE.createManualTask();
        Result<BpmnNode> result = match().apply(element);
        assertEquals(result.value(), defaultValue);
        assertTrue(result.isIgnored());
        assertFalse(result.isFailure());
    }

    @Test
    public void ignoreTestIgnore() {
        ManualTask element = Bpmn2Factory.eINSTANCE.createManualTask();
        Result<BpmnNode> result = match()
                .mode(MarshallingRequest.Mode.IGNORE)
                .apply(element);
        assertEquals(result.value(), defaultValue);
        assertTrue(result.isIgnored());
        assertFalse(result.isFailure());
    }

    @Test
    public void ignoreTestError() {
        ManualTask element = Bpmn2Factory.eINSTANCE.createManualTask();
        Result<BpmnNode> result = match()
                .mode(MarshallingRequest.Mode.ERROR)
                .apply(element);
        assertEquals(result.value(), defaultValue);
        assertFalse(result.isIgnored());
        assertTrue(result.isFailure());
    }

    @Test
    public void missingTest() {
        ReceiveTask element = Bpmn2Factory.eINSTANCE.createReceiveTask();
        Result<BpmnNode> result = match().apply(element);
        assertEquals(result.value(), defaultValue);
        assertTrue(result.isFailure());
    }

    private Match<FlowElement, BpmnNode> match() {
        return Match.of(FlowElement.class, BpmnNode.class)
                .whenExactly(UserTaskImpl.class, assertUserTask)
                .when(SubProcess.class, assertSubProcess)
                .ignore(ManualTask.class)
                .missing(ReceiveTask.class)
                .defaultValue(defaultValue)
                .mode(MarshallingRequest.Mode.AUTO);
    }
}


text:
<?php
namespace Terminus;

use Terminus\User;
use Terminus\Site;

class Organization {

  public function __construct( $org ) {
    // if the org id is passed in then we need to fetch it from the user object
    if (is_string($org)) {
      $user = User::instance();
      $orgs = $user->organizations();
      $org = $orgs->$org;
    }

    // hydrate the object
    $properties = get_object_vars($org);
    foreach (get_object_vars($org) as $key => $value) {
      if(!property_exists($this,$key)) {
        $this->$key = $properties[$key];
      }
    }

    return $this;
  }

  public function addSite( Site $site ) {
    $path = sprintf("organizations/%s/sites/%s", $this->id, $site->getId());
    $method = 'PUT';
    $user = User::id();
    $response = \Terminus_Command::request('users', $user, $path, $method);
    return $response['data'];
  }

  public function removeSite( Site $site ) {
    $path = sprintf("organizations/%s/sites/%s", $this->id, $site->getId());
    $method = 'DELETE';
    $user = User::id();
    $response = \Terminus_Command::request('users', $user, $path, $method);
    return $response['data'];
  }

}


text:
package com.javanag.accel20xx;

/**
 * Bullet that ships will shoot, travel in a straight line along y axis, x origin
 * depends on the location of the ship at time of shooting.
 * <p>
 * Just a colored, untextured, quad.
 */
public class Bullet extends GLObject {

    private boolean active = false;

    /**
     * Makes a new Bullet, taking in color value (Player/Enemy have different colors)
     *
     * @param color Float array of length 4, {red, green, blue, alpha}
     */
    public Bullet(float[] color) {
        super(0, 0, 0.09f, 0.09f, 0.0625f / 4, 0.0625f / 4, 1f, RenderType.UNTEXTURED, null);
        setColor(color);
    }

    public void update() {
        y += dy;

        if (dy >= 0) {
            if (y >= 1.5f) {//Offscreen
                recycle();
            }
        } else {
            if (y <= -1.5f) {//Offscreen
                recycle();
            }
        }
    }

    public void shoot(float x, float y) {
        active = true;
        this.x = x;
        this.y = y;
    }

    public void recycle() {
        active = false;
    }

    public boolean isActive() {
        return active;
    }

    public void flip() {
        this.dy = -this.dy;
        this.dx = -this.dx;
    }

}


text:
clear all; clc;

path(pathdef);
warning('off','YALMIP:strict');

clc
QT=dynamics();
save export.mat

Simulink.Bus.createObject(QT.ctes);
%Simulink.Bus.createObject(QT.ctes);


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

package com.google.devtools.build.lib.worker;

import com.google.common.collect.ImmutableList;
import com.google.common.flogger.GoogleLogger;
import com.google.devtools.build.lib.shell.Subprocess;
import com.google.devtools.build.lib.shell.SubprocessBuilder;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.worker.WorkerProtocol.WorkRequest;
import com.google.devtools.build.lib.worker.WorkerProtocol.WorkResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Semaphore;

/** An intermediate worker that sends request and receives response from the worker process. */
public class WorkerMultiplexer extends Thread {
  private static final GoogleLogger logger = GoogleLogger.forEnclosingClass();
  /**
   * WorkerMultiplexer is running as a thread on its own. When worker process returns the
   * WorkResponse, it is stored in this map and wait for WorkerProxy to retrieve the response.
   */
  private Map<Integer, InputStream> workerProcessResponse;
  /** A semaphore to protect workerProcessResponse object. */
  private Semaphore semWorkerProcessResponse;
  /**
   * After sending the WorkRequest, WorkerProxy will wait on a semaphore to be released.
   * WorkerMultiplexer is responsible to release the corresponding semaphore in order to signal
   * WorkerProxy that the WorkerResponse has been received.
   */
  private Map<Integer, Semaphore> responseChecker;
  /** A semaphore to protect responseChecker object. */
  private Semaphore semResponseChecker;
  /** The worker process that this WorkerMultiplexer should be talking to. */
  private Subprocess process;
  /**
   * If one of the worker processes returns unparseable response, discard all the responses from
   * other worker processes.
   */
  private boolean isUnparseable;
  /** InputStream from worker process. */
  private RecordingInputStream recordingStream;
  /** If worker process returns null, return null to WorkerProxy and discard all the responses. */
  private boolean isNull;
  /** A flag to stop multiplexer thread. */
  private boolean isInterrupted;

  WorkerMultiplexer() {
    semWorkerProcessResponse = new Semaphore(1);
    semResponseChecker = new Semaphore(1);
    responseChecker = new HashMap<>();
    workerProcessResponse = new HashMap<>();
    isUnparseable = false;
    isNull = false;
    isInterrupted = false;
  }

  /** Only start one worker process for each WorkerMultiplexer, if it hasn't. */
  public synchronized void createProcess(WorkerKey workerKey, Path workDir, Path logFile)
      throws IOException {
    if (this.process == null) {
      ImmutableList<String> args = workerKey.getArgs();
      File executable = new File(args.get(0));
      if (!executable.isAbsolute() && executable.getParent() != null) {
        List<String> newArgs = new ArrayList<>(args);
        newArgs.set(0, new File(workDir.getPathFile(), newArgs.get(0)).getAbsolutePath());
        args = ImmutableList.copyOf(newArgs);
      }
      SubprocessBuilder processBuilder = new SubprocessBuilder();
      processBuilder.setArgv(args);
      processBuilder.setWorkingDirectory(workDir.getPathFile());
      processBuilder.setStderr(logFile.getPathFile());
      processBuilder.setEnv(workerKey.getEnv());
      this.process = processBuilder.start();
    }
    if (!this.isAlive()) {
      this.start();
    }
  }

  public synchronized void destroyMultiplexer() {
    if (this.process != null) {
      destroyProcess(this.process);
    }
    isInterrupted = true;
  }

  private void destroyProcess(Subprocess process) {
    boolean wasInterrupted = false;
    try {
      process.destroy();
      while (true) {
        try {
          process.waitFor();
          return;
        } catch (InterruptedException ie) {
          wasInterrupted = true;
        }
      }
    } finally {
      // Read this for detailed explanation: http://www.ibm.com/developerworks/library/j-jtp05236/
      if (wasInterrupted) {
        Thread.currentThread().interrupt(); // preserve interrupted status
      }
    }
  }

  public boolean isProcessAlive() {
    return !this.process.finished();
  }

  /** Send the WorkRequest to worker process. */
  public synchronized void putRequest(WorkRequest request) throws IOException {
    request.writeDelimitedTo(process.getOutputStream());
    process.getOutputStream().flush();
  }

  /** Wait on a semaphore for the WorkResponse returned from worker process. */
  public InputStream getResponse(Integer workerId) throws IOException, InterruptedException {
    semResponseChecker.acquire();
    Semaphore waitForResponse = responseChecker.get(workerId);
    semResponseChecker.release();

    if (waitForResponse == null) {
      /**
       * If multiplexer is interrupted when WorkerProxy is trying to send request, request is not
       * sent so no need to wait for response.
       */
      return null;
    }

    // The semaphore will throw InterruptedException when the multiplexer is terminated.
    waitForResponse.acquire();

    if (isNull) {
      return null;
    }

    if (isUnparseable) {
      recordingStream.readRemaining();
      throw new IOException(recordingStream.getRecordedDataAsString());
    }

    semWorkerProcessResponse.acquire();
    InputStream response = workerProcessResponse.get(workerId);
    semWorkerProcessResponse.release();
    return response;
  }

  /** Reset the semaphore map before sending request to worker process. */
  public void resetResponseChecker(Integer workerId) throws InterruptedException {
    semResponseChecker.acquire();
    responseChecker.put(workerId, new Semaphore(0));
    semResponseChecker.release();
  }

  /**
   * When it gets a WorkResponse from worker process, put that WorkResponse in workerProcessResponse
   * and signal responseChecker.
   */
  private void waitResponse() throws InterruptedException, IOException {
    recordingStream = new RecordingInputStream(process.getInputStream());
    recordingStream.startRecording(4096);
    WorkResponse parsedResponse = WorkResponse.parseDelimitedFrom(recordingStream);

    if (parsedResponse == null) {
      isNull = true;
      releaseAllSemaphores();
      return;
    }

    Integer workerId = parsedResponse.getRequestId();
    ByteArrayOutputStream tempOs = new ByteArrayOutputStream();
    parsedResponse.writeDelimitedTo(tempOs);

    semWorkerProcessResponse.acquire();
    workerProcessResponse.put(workerId, new ByteArrayInputStream(tempOs.toByteArray()));
    semWorkerProcessResponse.release();

    semResponseChecker.acquire();
    responseChecker.get(workerId).release();
    semResponseChecker.release();
  }

  /** A multiplexer thread that listens to the WorkResponse from worker process. */
  @Override
  public void run() {
    while (!isInterrupted) {
      try {
        waitResponse();
      } catch (IOException e) {
        isUnparseable = true;
        releaseAllSemaphores();
        logger.atWarning().withCause(e).log(
            "IOException was caught while waiting for worker response. "
                + "It could because the worker returned unparseable response.");
      } catch (InterruptedException e) {
        logger.atWarning().withCause(e).log(
            "InterruptedException was caught while waiting for worker response. "
                + "It could because the multiplexer was interrupted.");
      }
    }
    logger.atWarning().log(
        "Multiplexer thread has been terminated. It could because the memory is running low on"
            + " your machine. There may be other reasons.");
  }

  /** Release all the semaphores */
  private void releaseAllSemaphores() {
    try {
      semResponseChecker.acquire();
      for (Integer workerId : responseChecker.keySet()) {
        responseChecker.get(workerId).release();
      }
    } catch (InterruptedException e) {
      // Do nothing
    } finally {
      semResponseChecker.release();
    }
  }
}


text:
thing is largely a work in progress

__TL;DR: [main notebook](https://github.com/yandexdataschool/gumbel_lstm/blob/master/binary_lstm.ipynb)__

[![Binder](http://mybinder.org/badge.svg)](http://mybinder.org:/repo/yandexdataschool/gumbel_lstm) (may be off sometimes)

# Main idea:

There's currently many recurrent neural network architectures that utilize gates: versions of LSTM, GRU, residual RNN with forget gate, etc.

Most popular (and far from the easiest) one of them is __LSTM__
![img](http://colah.github.io/images/post-covers/lstm.png)
(more info on how it works: http://colah.github.io/posts/2015-08-Understanding-LSTMs/)

Such architectures usually take advantage of gates. For example, the LSTM above has three gates:
- _input gate_ - network decides whether each cell (individually) is going to observe input (or ignore it)
- _forget gate_ - network decides for each cell whether it should be kept or forgotten (set to 0)
- _output gate_ - network decides whether a cell should be shown to other cells and to the next layer.

These gates are represented by a sigmoid of a weighted combination of input and LSTM hidden state. If you multiply e.g. cell by sigmoid in an elementwise manner, the outcome will be between 0 (if sigmoid ~ 0) and the cell itself (if sigmoid ~ 1).

In other words, the network can choose at which points of time does it wish to keep or erase the stored cell value. However, in order to train such gates with gradient descent along with the rest of the network, they have to be differentiable, thus necessarily continuous.

Thus, network is able to e.g. multiply one of it's stored cell values by 0.7324 by producing such value out of forgetgate sigmoid. This may be useful in some cases, but most of the time forgetgate is meant to be either 0 or 1.

There has recently been a trick that allows train networks with quasi-discrete categorical activations via gumbel-softmax or gumbel-sigmoid nonlinearity. A great explaination of how it works can be found [here](http://blog.evjang.com/2016/11/tutorial-categorical-variational.html).

The trick is to add a special noize to the softmax distribution that favors almost-1-hot outcomes. Such noize can be obtained from gumbel distribution. Since sigmoid can be viewed as a special case of softmax of 2 classes(logit and 0), we can use the same technique to implement an LSTM network with gates that will ultimately be forced to converge to 0 or 1. Here's a [demo](https://github.com/yandexdataschool/gumbel_lstm/blob/master/demo_gumbel_sigmoid.ipynb) of gumbel-sigmoid on a toy task.

Such network can then be binarized: multiplication can be replaced with if/else operations and fp16 operations to drastically improve execution speed, especially when implemented in a special-purpose device, [see here](https://www.engadget.com/2016/04/28/movidius-fathom-neural-compute-stick/ ) and [here](https://arxiv.org/abs/1602.02830).

# TODO
- moar experiments
- moar gated architectures
- multilayer stuff
- other temperature regimes
- converting pretrained rnn to binary

# Contributors so far
- Lambda Lab
- Arseniy Ashukha (advice & useful comments)


text:
[![Build Status](https://travis-ci.org/Ticketpark/TicketparkDoctrineFixturesAutoloader.svg?branch=master)](https://travis-ci.org/Ticketpark/TicketparkDoctrineFixturesAutoloader)

This library simplifies loading Doctrine fixtures.

## Installation

Add TicketparkDoctrineFixturesAutoloader to your composer.json:

```js
{
    "require": {
        "ticketpark/doctrine-fixtures-autoloader"
    }
}
```

## Usage

``` php
<?php

namespace Acme\Bundle\SomeBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Ticketpark\Doctrine\DataFixtures\Autoloader\Autoloader;

class LoadCountryData extends AutoLoader implements FixtureInterface
{
    public function load(ObjectManager $manager)
    {
        $data = array(
            array(
                '_reference'    => 'CH',
                'shortCode'     => 'CH',
                'name'          => 'Switzerland'
            ),
            array(
                '_reference'    => 'AT',
                'shortCode'     => 'AT',
                'name'          => 'Austria'
            ),
        );

        $this->autoload($data, $manager);
    }
}
```

In a second fixture class, references will be available based on the entity name and the optional `_reference` value:

``` php
<?php

namespace Acme\Bundle\SomeBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\DataFixtures\DependentFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Ticketpark\Doctrine\DataFixtures\Autoloader\Autoloader;

class LoadUserData extends AutoLoader implements FixtureInterface, DependentFixtureInterface
{
    public function getDependencies()
    {
        return array(
            'Acme\Bundle\SomeBundle\DataFixtures\ORM\LoadCountryData'
        );
    }

    public function load(ObjectManager $manager)
    {
        $data = array(
            array(
                // The string `country_CH` references the element
                // created in the 'Country' entity with 'CH' as its
                // _reference value.
                'country' => $this->getReference('country_CH'),
                'name'    => 'Tom Swissman'
            )
        );

        $this->autoload($data, $manager);
    }
}
```

### Overwriting setter method names
In some cases you might want to override the setter methods. for instance because your method is named `addCurrency` instead of `addCurrencie` as the autoloader by default would asume. In this case, simply use the additional `setterMethods` parameter:

``` php
<?php

namespace Acme\Bundle\SomeBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Ticketpark\Doctrine\DataFixtures\Autoloader\Autoloader;

class LoadCurrencyData extends AutoLoader implements FixtureInterface
{
    public function load(ObjectManager $manager)
    {
        $data = array(
            array(
                'currencies' => array(
                    'USD', 'EUR', 'CHF'
                )
            ),
        );

        $setterMethods = array(
            'currencies' => 'addCurrency'
        );

        $this->autoload($data, $manager, $setterMethods);
    }
}
```

### Treat arrays as singles
Another option to treat an array like a single element and inject the full array into a setter is by using the `$treatAsSingle` method parameter.

``` php
<?php

namespace Acme\Bundle\SomeBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Ticketpark\Doctrine\DataFixtures\Autoloader\Autoloader;

class LoadCurrencyData extends AutoLoader implements FixtureInterface
{
    public function load(ObjectManager $manager)
    {
        $data = array(
            array(
                'currencies' => array(
                    'USD', 'EUR', 'CHF'
                )
            ),
        );

        // this will cause a call to setCurrencies() with the full currencies array
        $treatAsSingles = array('currencies');
        $this->autoload($data, $manager, array(), $treatAsSingles);
    }
}
```

### Provide class name
By default, the library tries to guess your entity namespace based on standard data fixture naming conventions. However, you can also define the namespace of your entity manually:

``` php
<?php

namespace Acme\Bundle\SomeBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Ticketpark\Doctrine\DataFixtures\Autoloader\Autoloader;

class LoadCountryData extends AutoLoader implements FixtureInterface
{
    public function load(ObjectManager $manager)
    {
        $data = array(
            array(
                'shortCode'     => 'CH',
                'name'          => 'Switzerland'
            ),
        );
        $this->setEntityClass('My\Custom\Namespace\Country');
        $this->autoload($data, $manager);
    }
}
```

## License
This bundle is under the MIT license. See the complete license in the bundle:

    Resources/meta/LICENSE


text:
export * from './databaseConnection';
export * from './googleOAuthServer';


text:
* {
    -webkit-tap-highlight-color: rgba(0,0,0,0); /* make transparent link selection, adjust last value opacity 0 to 1.0 */
}

body {
    -webkit-touch-callout: none;                /* prevent callout to copy image, etc when tap to hold */
    -webkit-text-size-adjust: none;             /* prevent webkit from resizing text to fit */
    -webkit-user-select: none;                  /* prevent copy paste, to allow, change 'none' to 'text' */
    background-color:#E4E4E4;
    background-image:linear-gradient(top, #A7A7A7 0%, #E4E4E4 51%);
    background-image:-webkit-linear-gradient(top, #A7A7A7 0%, #E4E4E4 51%);
    background-image:-ms-linear-gradient(top, #A7A7A7 0%, #E4E4E4 51%);
    background-image:-webkit-gradient(
        linear,
        left top,
        left bottom,
        color-stop(0, #A7A7A7),
        color-stop(0.51, #E4E4E4)
    );
    background-attachment:fixed;
    font-family:'HelveticaNeue-Light', 'HelveticaNeue', Helvetica, Arial, sans-serif;
    font-size:12px;
    height:100%;
    margin:0px;
    padding:0px;
    text-transform:uppercase;
    width:100%;
}

/* Portrait layout (default) */
.app {
    background:url(../img/logo.png) no-repeat center top; /* 170px x 200px */
    position:absolute;             /* position in the center of the screen */
    left:50%;
    top:50%;
    height:50px;                   /* text area height */
    width:225px;                   /* text area width */
    text-align:center;
    padding:180px 0px 0px 0px;     /* image height is 200px (bottom 20px are overlapped with text) */
    margin:-115px 0px 0px -112px;  /* offset vertical: half of image height and text area height */
                                   /* offset horizontal: half of text area width */
}

/* Landscape layout (with min-width) */
@media screen and (min-aspect-ratio: 1/1) and (min-width:400px) {
    .app {
        background-position:left center;
        padding:75px 0px 75px 170px;  /* padding-top + padding-bottom + text area = image height */
        margin:-90px 0px 0px -198px;  /* offset vertical: half of image height */
                                      /* offset horizontal: half of image width and text area width */
    }
}

h1 {
    font-size:24px;
    font-weight:normal;
    margin:0px;
    overflow:visible;
    padding:0px;
    text-align:center;
}

.event {
    border-radius:4px;
    -webkit-border-radius:4px;
    color:#FFFFFF;
    font-size:12px;
    margin:0px 30px;
    padding:2px 0px;
}

.event.listening {
    background-color:#333333;
    display:block;
}

.event.received {
    background-color:#4B946A;
    display:none;
}

@keyframes fade {
    from { opacity: 1.0; }
    50% { opacity: 0.4; }
    to { opacity: 1.0; }
}

@-webkit-keyframes fade {
    from { opacity: 1.0; }
    50% { opacity: 0.4; }
    to { opacity: 1.0; }
}

.blink {
    animation:fade 3000ms infinite;
    -webkit-animation:fade 3000ms infinite;
}

#botoesMapa{
    z-index: 100;
    width:80%;
    height:8em;
    float:right;
    position: absolute;
     bottom: 0;
    left: 0; right: 0;
    margin: auto;
}

#botoesMapa button{
    width:30%;
    float:left;
    margin-left: 1%;
    position:relative;
    padding:0.2em;
}

#botoesMapa a p{
   padding-top:0.3em;
}

.imagemBotao
{
    width:4em;
    padding:0;

}

.botaoMapa{
    font-size:2.5em;
    margin:0.1em;
}

#conteudoMapa{
   width:100%;
}

#compartilhar{
    position:absolute;
    z-index: 100;
    top:20%;
    right:0.5em;
}

#compartilhar a{
    display: block;
    cursor:pointer;
    padding:none;
}

.logoConsulta img{
   display: block; margin-left: auto; margin-right: auto
}

.botaoSocial
{
   text-shadow: 0 1px 0 #f3f3f3;
   text-align: center;
   text-decoration: none;
   padding:0.5em;
   margin-bottom:2em;
   border:1px solid #ccc;
   -moz-border-radius: 0.6em;
   -o-border-radius: 0.6em;
   -webkit-border-radius: 0.6em;
   -ms-border-radius: 0.6em;
   border-radius: 0.6em;
    background-image: -webkit-gradient(
             linear,
             left bottom,
             right top,
             color-stop(0.34, #D9E0D9),
             color-stop(1, #FFFFFF)
     );
     background-image: -o-linear-gradient(right top, #D9E0D9 34%, #FFFFFF 100%);
     background-image: -moz-linear-gradient(right top, #D9E0D9 34%, #FFFFFF 100%);
     background-image: -webkit-linear-gradient(right top, #D9E0D9 34%, #FFFFFF 100%);
     background-image: -ms-linear-gradient(right top, #D9E0D9 34%, #FFFFFF 100%);
     background-image: linear-gradient(to right top, #D9E0D9 34%, #FFFFFF 100%);
}


text:
BEGIN_NAMESPACE_CA_UI

ProgressBar::ProgressBar()
	: Control(false)

	, m_value(0)
	, m_minValue(0)
	, m_maxValue(100)

	, m_barColor(Color(0, 122, 204))
{

}

ProgressBar::~ProgressBar()
{

}

//###########################################################################

void ProgressBar::onMaxValue(const ValueFEventArgs& args)
{
	if (WhenMaxValue)
	{
		WhenMaxValue(args);
	}
}

void ProgressBar::onMinValue(const ValueFEventArgs& args)
{
	if (WhenMinValue)
	{
		WhenMinValue(args);
	}
}

//###########################################################################

void ProgressBar::onUpdateControl(const Transform& parentTransform, const PointF& parentCursor,
	const Transform& localTransform, const PointF& localCursor)
{
	// Empty
}

void ProgressBar::onDrawControl(Graphics& g, const Transform& parentTransform)
{
	const auto& position = getPosition();
	const auto& size = getSize();

	auto& rectArtist = g.rectangleArtist;

	const f32 barStand = m_value - m_minValue;
	const f32 barUnder = m_maxValue - m_minValue;

	f32 barWidth = size.width;

	if (std::abs(barUnder) > std::numeric_limits<f32>::epsilon())
		barWidth = barStand / barUnder * size.width;

	rectArtist->beginFillRectangle();
	rectArtist->fillRectangle(position, SizeF(barWidth, size.height), m_barColor);
	rectArtist->endFillRectangle();

	auto font = m_font.lock();
	if (font)
	{
		auto& textArtist = g.textArtist;

		textArtist->beginDrawString(*font);
		textArtist->drawString(getText(),
			position.x + size.width / 2,
			position.y + size.height / 2,
			m_foreColor, Drawing::TextAligns::Center);
		textArtist->endDrawString();
	}
}

//###########################################################################

f32 ProgressBar::getValue() const noexcept
{
	return m_value;
}

void ProgressBar::setValue(f32 value)
{
	if (value < m_minValue)
		value = m_minValue;
	else if (value > m_maxValue)
		value = m_maxValue;

	if (value >= m_maxValue && m_value < m_maxValue)
	{
		m_value = value;

		ValueFEventArgs args{ value };
		onMaxValue(args);
	}
	else if (value <= m_minValue && m_value > m_minValue)
	{
		m_value = value;

		ValueFEventArgs args{ value };
		onMinValue(args);
	}
	else
	{
		m_value = value;
	}
}

void ProgressBar::addValue(f32 delta)
{
	setValue(m_value + delta);
}

f32 ProgressBar::getMinValue() const noexcept
{
	return m_minValue;
}

void ProgressBar::setMinValue(f32 minValue)
{
	if (minValue > m_maxValue)
		minValue = m_maxValue;

	m_minValue = minValue;

	// °ª ¹üÀ§ ÀçÆò°¡
	setValue(m_value);
}

f32 ProgressBar::getMaxValue() const noexcept
{
	return m_maxValue;
}

void ProgressBar::setMaxValue(f32 maxValue)
{
	if (maxValue < m_minValue)
		maxValue = m_minValue;

	m_maxValue = maxValue;

	// °ª ¹üÀ§ ÀçÆò°¡
	setValue(m_value);
}

auto ProgressBar::getBarColor() const noexcept -> const Color&
{
	return m_barColor;
}

void ProgressBar::setBarColor(const Color& barColor)
{
	m_barColor = barColor;
}

END_NAMESPACE_CA_UI


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ECommon.IO;
using ECommon.Logging;
using ECommon.Scheduling;
using ECommon.Serializing;
using ENode.Commanding;
using ENode.Configurations;
using ENode.Domain;
using ENode.Infrastructure;
using ENode.Messaging;

namespace ENode.Eventing.Impl
{
    public class DefaultEventCommittingService : IEventCommittingService
    {
        #region Private Variables

        private readonly int _eventMailboxCount;
        private readonly IList<EventCommittingContextMailBox> _eventCommittingContextMailBoxList;
        private readonly IMemoryCache _memoryCache;
        private readonly IEventStore _eventStore;
        private readonly IMessagePublisher<DomainEventStreamMessage> _domainEventPublisher;
        private readonly IOHelper _ioHelper;
        private readonly IJsonSerializer _jsonSerializer;
        private readonly ILogger _logger;
        private readonly int _batchSize;

        #endregion

        #region Constructors

        public DefaultEventCommittingService(
            IMemoryCache memoryCache,
            IEventStore eventStore,
            IMessagePublisher<DomainEventStreamMessage> domainEventPublisher,
            IOHelper ioHelper,
            IJsonSerializer jsonSerializer,
            ILoggerFactory loggerFactory)
        {
            _eventCommittingContextMailBoxList = new List<EventCommittingContextMailBox>();
            _ioHelper = ioHelper;
            _memoryCache = memoryCache;
            _eventStore = eventStore;
            _domainEventPublisher = domainEventPublisher;
            _jsonSerializer = jsonSerializer;
            _logger = loggerFactory.Create(GetType().FullName);
            _eventMailboxCount = ENodeConfiguration.Instance.Setting.EventMailBoxCount;
            _batchSize = ENodeConfiguration.Instance.Setting.EventMailBoxPersistenceMaxBatchSize;

            for (var i = 0; i < _eventMailboxCount; i++)
            {
                _eventCommittingContextMailBoxList.Add(new EventCommittingContextMailBox(i, _batchSize, x => BatchPersistEventAsync(x, 0), _jsonSerializer, _logger));
            }
        }

        #endregion

        #region Public Methods

        public void CommitDomainEventAsync(EventCommittingContext eventCommittingContext)
        {
            var eventMailboxIndex = GetEventMailBoxIndex(eventCommittingContext.EventStream.AggregateRootId);
            var eventMailbox = _eventCommittingContextMailBoxList[eventMailboxIndex];
            eventMailbox.EnqueueMessage(eventCommittingContext);
        }
        public void PublishDomainEventAsync(ProcessingCommand processingCommand, DomainEventStream eventStream)
        {
            eventStream.MergeItems(processingCommand.Items);
            var eventStreamMessage = new DomainEventStreamMessage(processingCommand.Message.Id, eventStream.AggregateRootId, eventStream.Version, eventStream.AggregateRootTypeName, eventStream.Events, eventStream.Items);
            PublishDomainEventAsync(processingCommand, eventStreamMessage, 0);
        }

        #endregion

        #region Private Methods

        private int GetEventMailBoxIndex(string aggregateRootId)
        {
            unchecked
            {
                int hash = 23;
                foreach (char c in aggregateRootId)
                {
                    hash = (hash << 5) - hash + c;
                }
                if (hash < 0)
                {
                    hash = Math.Abs(hash);
                }
                return hash % _eventMailboxCount;
            }
        }
        private void BatchPersistEventAsync(IList<EventCommittingContext> committingContexts, int retryTimes)
        {
            if (committingContexts == null || committingContexts.Count == 0)
            {
                return;
            }

            _ioHelper.TryAsyncActionRecursively("BatchPersistEventAsync",
            () => _eventStore.BatchAppendAsync(committingContexts.Select(x => x.EventStream)),
            currentRetryTimes => BatchPersistEventAsync(committingContexts, currentRetryTimes),
            async result =>
            {
                var eventMailBox = committingContexts.First().MailBox;

                if (result == null)
                {
                    _logger.FatalFormat("BatchPersistAggregateEvents result is null, the current event committing mailbox should be pending, mailboxNumber: {0}", eventMailBox.Number);
                    return;
                }

                //针对持久化成功的聚合根,正常发布这些聚合根的事件到Q端
                if (result.SuccessAggregateRootIdList != null && result.SuccessAggregateRootIdList.Count > 0)
                {
                    foreach (var aggregateRootId in result.SuccessAggregateRootIdList)
                    {
                        var committingContextList = committingContexts.Where(x => x.EventStream.AggregateRootId == aggregateRootId).ToList();
                        if (committingContextList.Count > 0)
                        {
                            _logger.InfoFormat("BatchPersistAggregateEvents success, mailboxNumber: {0}, aggregateRootId: {1}, evnts: {2}",
                                eventMailBox.Number,
                                aggregateRootId,
                                string.Join(",", committingContextList.Select(x => x.EventStream.ToString())));

                            foreach (var committingContext in committingContextList)
                            {
                                PublishDomainEventAsync(committingContext.ProcessingCommand, committingContext.EventStream);
                            }
                        }
                    }
                }

                //针对持久化出现重复的命令ID,在命令MailBox中标记为已重复,在事件MailBox中清除对应聚合根产生的事件,且重新发布这些命令对应的领域事件到Q端
                if (result.DuplicateCommandAggregateRootIdList != null && result.DuplicateCommandAggregateRootIdList.Count > 0)
                {
                    foreach (var entry in result.DuplicateCommandAggregateRootIdList)
                    {
                        var committingContext = committingContexts.FirstOrDefault(x => x.EventStream.AggregateRootId == entry.Key);
                        if (committingContext != null)
                        {
                            _logger.WarnFormat("BatchPersistAggregateEvents has duplicate commandIds, mailboxNumber: {0}, aggregateRootId: {1}, commandIds: {2}",
                                eventMailBox.Number,
                                entry.Key,
                                string.Join(",", entry.Value));

                            if (committingContext.EventStream.Version == 1)
                            {
                                await HandleFirstEventDuplicationAsync(committingContext, 0);
                            }
                            else
                            {
                                await ResetCommandMailBoxConsumingSequence(committingContext, committingContext.ProcessingCommand.Sequence, entry.Value).ContinueWith(t => { }).ConfigureAwait(false);
                            }
                        }
                    }
                }

                //针对持久化出现版本冲突的聚合根,则自动处理每个聚合根的冲突
                if (result.DuplicateEventAggregateRootIdList != null && result.DuplicateEventAggregateRootIdList.Count > 0)
                {
                    foreach (var aggregateRootId in result.DuplicateEventAggregateRootIdList)
                    {
                        var committingContext = committingContexts.FirstOrDefault(x => x.EventStream.AggregateRootId == aggregateRootId);
                        if (committingContext != null)
                        {
                            _logger.WarnFormat("BatchPersistAggregateEvents has version confliction, mailboxNumber: {0}, aggregateRootId: {1}, conflictVersion: {2}",
                                eventMailBox.Number,
                                committingContext.EventStream.AggregateRootId,
                                committingContext.EventStream.Version);

                            if (committingContext.EventStream.Version == 1)
                            {
                                await HandleFirstEventDuplicationAsync(committingContext, 0);
                            }
                            else
                            {
                                await ResetCommandMailBoxConsumingSequence(committingContext, committingContext.ProcessingCommand.Sequence, null).ContinueWith(t => { }).ConfigureAwait(false);
                            }
                        }
                    }
                }

                committingContexts.First().MailBox.CompleteRun();
            },
            () => string.Format("[contextListCount:{0}]", committingContexts.Count),
            null,
            retryTimes, true);
        }
        private async Task ResetCommandMailBoxConsumingSequence(EventCommittingContext context, long consumingSequence, IList<string> duplicateCommandIdList)
        {
            var commandMailBox = context.ProcessingCommand.MailBox;
            var eventMailBox = context.MailBox;
            var aggregateRootId = context.EventStream.AggregateRootId;

            commandMailBox.Pause();

            try
            {
                eventMailBox.RemoveAggregateAllEventCommittingContexts(aggregateRootId);
                var refreshedAggregateRoot = await _memoryCache.RefreshAggregateFromEventStoreAsync(context.EventStream.AggregateRootTypeName, aggregateRootId).ConfigureAwait(false);
                if (duplicateCommandIdList != null)
                {
                    foreach (var commandId in duplicateCommandIdList)
                    {
                        commandMailBox.AddDuplicateCommandId(commandId);
                    }
                }
                commandMailBox.ResetConsumingSequence(consumingSequence);
            }
            catch (Exception ex)
            {
                _logger.Error(string.Format("ResetCommandMailBoxConsumingSequence has unknown exception, aggregateRootId: {0}", aggregateRootId), ex);
            }
            finally
            {
                commandMailBox.Resume();
                commandMailBox.TryRun();
            }
        }
        private void TryToRepublishEventAsync(EventCommittingContext context, int retryTimes)
        {
            var command = context.ProcessingCommand.Message;

            _ioHelper.TryAsyncActionRecursively("FindEventByCommandIdAsync",
            () => _eventStore.FindAsync(command.AggregateRootId, command.Id),
            currentRetryTimes => TryToRepublishEventAsync(context, currentRetryTimes),
            result =>
            {
                var existingEventStream = result;
                if (existingEventStream != null)
                {
                    //这里,我们需要再重新做一遍发布事件这个操作;
                    //之所以要这样做是因为虽然该command产生的事件已经持久化成功,但并不表示事件已经发布出去了;
                    //因为有可能事件持久化成功了,但那时正好机器断电了,则发布事件都没有做;
                    PublishDomainEventAsync(context.ProcessingCommand, existingEventStream);
                }
                else
                {
                    //到这里,说明当前command想添加到eventStore中时,提示command重复,但是尝试从eventStore中取出该command时却找不到该command。
                    //出现这种情况,我们就无法再做后续处理了,这种错误理论上不会出现,除非eventStore的Add接口和Get接口出现读写不一致的情况;
                    //框架会记录错误日志,让开发者排查具体是什么问题。
                    var errorMessage = string.Format("Command should be exist in the event store, but we cannot find it from the event store, this should not be happen, and we just complete the command. commandType:{0}, commandId:{1}, aggregateRootId:{2}",
                        command.GetType().Name,
                        command.Id,
                        command.AggregateRootId);
                    _logger.Fatal(errorMessage);
                    var commandResult = new CommandResult(CommandStatus.Failed, command.Id, command.AggregateRootId, "Command should be exist in the event store, but we cannot find it from the event store.", typeof(string).FullName);
                    CompleteCommand(context.ProcessingCommand, commandResult);
                }
            },
            () => string.Format("[aggregateRootId:{0}, commandId:{1}]", command.AggregateRootId, command.Id),
            null,
            retryTimes, true);
        }
        private Task HandleFirstEventDuplicationAsync(EventCommittingContext context, int retryTimes)
        {
            var taskCompletionSource = new TaskCompletionSource<bool>();

            _ioHelper.TryAsyncActionRecursively("FindFirstEventByVersion",
            () => _eventStore.FindAsync(context.EventStream.AggregateRootId, 1),
            currentRetryTimes => HandleFirstEventDuplicationAsync(context, currentRetryTimes),
            async result =>
            {
                if (result != null)
                {
                    var eventStream = result;
                    //判断是否是同一个command,如果是,则再重新做一遍发布事件;
                    //之所以要这样做,是因为虽然该command产生的事件已经持久化成功,但并不表示事件也已经发布出去了;
                    //有可能事件持久化成功了,但那时正好机器断电了,则发布事件都没有做;
                    if (context.ProcessingCommand.Message.Id == eventStream.CommandId)
                    {
                        await ResetCommandMailBoxConsumingSequence(context, context.ProcessingCommand.Sequence + 1, null).ConfigureAwait(false);
                        PublishDomainEventAsync(context.ProcessingCommand, eventStream);
                    }
                    else
                    {
                        //如果不是同一个command,则认为是两个不同的command重复创建ID相同的聚合根,我们需要记录错误日志,然后通知当前command的处理完成;
                        var errorMessage = string.Format("Duplicate aggregate creation. current commandId:{0}, existing commandId:{1}, aggregateRootId:{2}, aggregateRootTypeName:{3}",
                            context.ProcessingCommand.Message.Id,
                            eventStream.CommandId,
                            eventStream.AggregateRootId,
                            eventStream.AggregateRootTypeName);
                        _logger.Error(errorMessage);
                        await ResetCommandMailBoxConsumingSequence(context, context.ProcessingCommand.Sequence + 1, null).ConfigureAwait(false);
                        var commandResult = new CommandResult(CommandStatus.Failed, context.ProcessingCommand.Message.Id, context.EventStream.AggregateRootId, "Duplicate aggregate creation.", typeof(string).FullName);
                        await CompleteCommand(context.ProcessingCommand, commandResult);
                    }
                }
                else
                {
                    var errorMessage = string.Format("Duplicate aggregate creation, but we cannot find the existing eventstream from eventstore, this should not be happen, and we just complete the command. commandId:{0}, aggregateRootId:{1}, aggregateRootTypeName:{2}",
                        context.EventStream.CommandId,
                        context.EventStream.AggregateRootId,
                        context.EventStream.AggregateRootTypeName);
                    _logger.Fatal(errorMessage);
                    await ResetCommandMailBoxConsumingSequence(context, context.ProcessingCommand.Sequence + 1, null).ConfigureAwait(false);
                    var commandResult = new CommandResult(CommandStatus.Failed, context.ProcessingCommand.Message.Id, context.EventStream.AggregateRootId, "Duplicate aggregate creation, but we cannot find the existing eventstream from eventstore.", typeof(string).FullName);
                    await CompleteCommand(context.ProcessingCommand, commandResult);
                }

                taskCompletionSource.SetResult(true);
            },
            () => string.Format("[eventStream:{0}]", context.EventStream),
            null,
            retryTimes, true);

            return taskCompletionSource.Task;
        }
        private void PublishDomainEventAsync(ProcessingCommand processingCommand, DomainEventStreamMessage eventStream, int retryTimes)
        {
            _ioHelper.TryAsyncActionRecursivelyWithoutResult("PublishEventAsync",
            () => _domainEventPublisher.PublishAsync(eventStream),
            currentRetryTimes => PublishDomainEventAsync(processingCommand, eventStream, currentRetryTimes),
            () =>
            {
                _logger.InfoFormat("Publish event success, {0}", eventStream);
                var commandHandleResult = processingCommand.CommandExecuteContext.GetResult();
                var commandResult = new CommandResult(CommandStatus.Success, processingCommand.Message.Id, eventStream.AggregateRootId, commandHandleResult, typeof(string).FullName);
                CompleteCommand(processingCommand, commandResult);
            },
            () => string.Format("[eventStream:{0}]", eventStream),
            null,
            retryTimes, true);
        }
        private Task CompleteCommand(ProcessingCommand processingCommand, CommandResult commandResult)
        {
            return processingCommand.MailBox.CompleteMessage(processingCommand, commandResult);
        }

        #endregion
    }
}


text:
var requestAnimFrame = (function(){
    return window.requestAnimationFrame       ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame    ||
        window.oRequestAnimationFrame      ||
        window.msRequestAnimationFrame     ||
        function(callback){
            window.setTimeout(callback, 1000 / 60);
        };
})();

var resources = new sh.Resources();
var stats;
var w = window.innerWidth;
var h = window.innerHeight;
var renderer;
var scene;
var gl;
var server;
var player;
var game;

var canvas = document.getElementById('canvas');
canvas.width = w;
canvas.height = h;

function convertToWireframe(indices) {
    var arr = new Uint16Array(indices.length / 3 * 6);
    var idx = 0;

    for(var i=0; i<indices.length; i+=3) {
        arr[idx++] = indices[i];
        arr[idx++] = indices[i+1];
        arr[idx++] = indices[i+1];
        arr[idx++] = indices[i+2];
        arr[idx++] = indices[i+2];
        arr[idx++] = indices[i];
    }

    return arr;
}

function showInitialOverlay() {
    if(document.cookie.indexOf('seenOverlay') === -1) {
        document.cookie = 'seenOverlay=1;expires=0';
        $('#ingame .initialOverlay').show();
    }
    else {
        actuallyStart();
    }
}

function actuallyStart() {
    var el = $('#ingame')[0];
    $('.initialOverlay', el).hide();

    input.activate();
    messages.notify('Press F1 to toggle the chat window. ' +
                    'You can change your name there.');
}

function init() {
    renderer = new sh.Renderer(w, h);
    scene = new sh.Scene(255 * 4, 255 * 4);
    game = new Game();

    var room = window.location.pathname.slice(1);
    server = new ServerConnection(room);

    createLevel(scene);
    createOverlay(scene);

    player = new Player();
    scene.addObject(player);
    scene.setCamera(new sh.Camera(player));
    renderer.perspective(45, w / h, 1.0, 5000.0);

    var sky = new sh.Cube(null,
                          null,
                          [50, 50, 50],
                         { centered: true });
    sky.update = function(dt) {
        this.setPos(player.pos[0], player.pos[1], player.pos[2]);
    };
    sky.id = 'sky';
    sky.backface = true;
    sky.noZbuffer = true;
    sky.setMaterial(['sky.vsh', 'sky.fsh']);
    scene.addObject(sky);

    //var fork = new sh.Square([-10, 0, -10], null, [1, 200, 200]);
    // fork.setImage('img/fork.png');
    // forka.setMaterial(['ui.vsh', 'ui.fsh']);
    // fork.color = [0, 1, 0];
    // fork.backface = true;
    // scene.addObject(fork);

    var terrain = new Terrain(null, null, null,
                              scene.sceneWidth,
                              scene.sceneDepth);
    terrain.create();
    scene.addObject(terrain);

    serverEvents.init();
    messages.init();
    window.onresize = resize;

    if(!game.isFull()) {
        showInitialOverlay();
        heartbeat();
    }
}

var last = Date.now();
var stopped = false;
function heartbeat() {
    var now = Date.now();
    var dt = Math.min((now - last) / 1000., .1);

    scene.update(dt);

    gl.clearColor(0.0, 0.0, 0.0, 1.0);
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

    renderer.render(scene);
    renderer.render2d(scene.getOverlay());

    input.reset();

    if(stats) {
        stats.update();
    }

    if(!stopped) {
        last = now;
        requestAnimFrame(heartbeat);
    }
}

function resize() {
    var w = window.innerWidth;
    var h = window.innerHeight;

    canvas.width = w;
    canvas.height = h;

    // !@$#!@$#$$!@#!
    gl.viewport(0, 0, canvas.width, canvas.height);

    renderer.resize(w, h);
    renderer.perspective(45, w / h, 1.0, 5000.0);

    $('#messages').height(renderer.height - $('#chat .type').height());
}

function load() {
    gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');

    // stats = new Stats();
    // //stats.setMode(1);
    // stats.domElement.style.position = 'absolute';
    // stats.domElement.style.right = '0px';
    // stats.domElement.style.top = '0px';
    // document.body.appendChild(stats.domElement);

    resources.load([
        'shaders/default.fsh',
        'shaders/default.vsh',
        'shaders/debug.fsh',
        'shaders/debug.vsh',
        'shaders/ui.fsh',
        'shaders/ui.vsh',
        'shaders/sky.fsh',
        'shaders/sky.vsh',
        'shaders/terrain.fsh',
        'shaders/terrain.vsh',
        'shaders/textured.fsh',
        'shaders/textured.vsh',
        'img/octo.png',
        'img/crosshair.png',
        'img/heart.png',
        'img/heart-grey.png',
        //'img/fork.png',
        'img/grass.jpg',
        'sounds/laser.wav',
        'sounds/hurt.wav',
        'sounds/hit.wav',
        'sounds/die.wav'
    ]);

    resources.onReady(init);
}

function initPage() {
    $('#ingame button.start').click(function() {
        actuallyStart();
        goFullscreen();
    });

    $('#ingame button.no').click(function() {
        actuallyStart();
    });

    $('#ingame button.fullscreen').click(function() {
        goFullscreen();
    });

    function goFullscreen() {
        var el = $('#ingame')[0];
        el.requestFullscreen = el.requestFullscreen ||
            el.mozRequestFullscreen ||
            el.mozRequestFullScreen || // Older API upper case 'S'.
            el.webkitRequestFullscreen;

        el.requestFullscreen();
    }

    function onFullscreenChange() {
        var el = document.webkitFullscreenElement ||
            document.mozFullscreenElement ||
            document.mozFullScreenElement;

        if(el) {
            el.requestPointerLock = el.requestPointerLock ||
                el.mozRequestPointerLock ||
                el.webkitRequestPointerLock;
            el.requestPointerLock();
            renderer.fullscreen = true;
            $('button.fullscreen').hide();
        }
        else {
            renderer.fullscreen = false;
            $('button.fullscreen').show();
        }

        resize();
    }

    function onPointerLockChange() {
        if (document.mozPointerLockElement ||
            document.webkitPointerLockElement) {
            console.log("Pointer Lock was successful.");
        } else {
            console.log("Pointer Lock was lost.");
        }
    }

    function onPointerLockError() {
        alert('error locking');
    }

    document.addEventListener('fullscreenchange', onFullscreenChange, false);
    document.addEventListener('mozfullscreenchange', onFullscreenChange, false);
    document.addEventListener('webkitfullscreenchange', onFullscreenChange, false);

    document.addEventListener('pointerlockchange', onPointerLockChange, false);
    document.addEventListener('mozpointerlockchange', onPointerLockChange, false);
    document.addEventListener('webkitpointerlockchange', onPointerLockChange, false);

    document.addEventListener('pointerlockerror', onPointerLockError, false);
    document.addEventListener('mozpointerlockerror', onPointerLockError, false);
    document.addEventListener('webkitpointerlockerror', onPointerLockError, false);
}

$(function() {
    initPage();
    load();
});


text:
from nevow import athena

from xmantissa.fragmentutils import dictFillSlots
from xmantissa.webtheme import getLoader

class SenderPersonFragment(athena.LiveFragment):
    """
    Fragment which renders the email address and name of a person who is not
    in the address book, but could be added
    """
    # FIXME this thing should be renamed and moved out of this module
    jsClass = u'Quotient.Common.SenderPerson'

    def __init__(self, email):
        """
        @param email: an email address
        @type email: L{xquotient.mimeutil.EmailAddress}
        """
        self.email = email
        athena.LiveFragment.__init__(
            self, docFactory=getLoader('sender-person'))

    def render_senderPerson(self, ctx, data):
        return dictFillSlots(
                ctx.tag, dict(name=self.email.anyDisplayName(),
                              identifier=self.email.email))


text:
using System;

namespace SharpSenses {
    public class RotationablePart : FlexiblePart {
        private Rotation _rotation;

        public Rotation Rotation {
            get { return _rotation; }
            set {
                if (Equals(_rotation, value)) {
                    return;
                }
                _rotation = value;
                OnRotationChanged();
                RaisePropertyChanged(() => Rotation);
            }
        }

        public event EventHandler RotationChanged;

        protected virtual void OnRotationChanged() {
            var handler = RotationChanged;
            if (handler != null) {
                handler(this, EventArgs.Empty);
            }
        }
    }
}


text:
<?php namespace Queni\DLearning\Updates;

use Schema;
use October\Rain\Database\Schema\Blueprint;
use October\Rain\Database\Updates\Migration;

class CreateCategoriesTable extends Migration
{
    public function up()
    {
        Schema::create('queni_dlearning_categories', function(Blueprint $table)
        {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->string('title')->unique();
            $table->string('slug')->index();
            $table->integer('parent_category_id')->unsigned()->nullable();
            $table->timestamps();

            $table->foreign('parent_category_id')
                    ->references('id')->on('queni_dlearning_categories')
                    ->onUpdate('cascade')->onDelete('cascade');
        });
    }

    public function down()
    {
        Schema::dropIfExists('queni_dlearning_categories');
    }
}