text:
A simple configurable tool for manipulating dependency trees.

DepEdit reads and writes files encoded in the CoNLL-U or CoNLL-X dependency format (10 columns).  It's a simple Python script which can change token attributes, token text, part of speech dependency function and other columns, as well as rewiring dependency graphs based on rules. You can also use it to add annotations to each sentence based on properties of the subgraph (see the English example of tagging rough sentence type in examples/)

To use the script, either copy the file `depedit/depedit.py` into your project, or install it from PyPI:

```
pip install depedit
```

You can then run it directly or as a module:

```
If depedit is in the current directory:

> python depedit.py -c CONFIG.ini INFILE.conllu

Or if installed via pip or setup.py, then in any directory:

> python -m depedit -c CONFIG.ini INFILE.conllu
```

## Basic usage

```
usage: depedit.py [-h] [-c CONFIG] [-d] [-s] [-k {supertoks,comments,both}]
                  [-q] [--stepwise] [-o OUTDIR] [-e EXTENSION] [-i INFIX]
                  [--version]
                  file

positional arguments:
  file                  Input single file name or glob pattern to process a
                        batch (e.g. *.conllu)

optional arguments:
  -h, --help            show this help message and exit
  -c CONFIG, --config CONFIG
                        Configuration file defining transformation
  -d, --docname         Begin output with # newdoc id =...
  -s, --sent_id         Add running sentence ID comments
  -t, --text            Add # text =...
  -k {supertoks,comments,both}, --kill {supertoks,comments,both}
                        Remove supertokens or commments from output
  -q, --quiet           Do not output warnings and messages
  --stepwise            Output sentence repeatedly after each step (useful for
                        debugging)
  --version             show program's version number and exit

Batch mode options:
  -o OUTDIR, --outdir OUTDIR
                        Output directory in batch mode
  -e EXTENSION, --extension EXTENSION
                        Extension for output files in batch mode
  -i INFIX, --infix INFIX
                        Infix to denote edited files in batch mode (default:
                        .depedit)
```

For more information see https://gucorpling.org/depedit/ and read the included User Guide PDF in doc/.

## Citing

If you are using DepEdit in a scholarly paper, please cite the following reference:

```
 @InProceedings{PengZeldes2020,
   author    = {Siyao Peng and Amir Zeldes},
   title     = {All Roads Lead to {UD}: Converting {S}tanford and {P}enn Parses to {E}nglish {U}niversal {D}ependencies with Multilayer Annotations},
   booktitle = {Proceedings of the Joint Workshop on Linguistic Annotation, Multiword Expressions and Constructions ({LAW}-{MWE}-{C}x{G}-2018)},
   year      = {2018},
   pages     = {167--177},
   address   = {Santa Fe, NM},
   url       = {https://www.aclweb.org/anthology/W18-4918}
 }
 ```


text:
import sys

import mock
from mock import patch
from pytest import raises

from paasta_tools.cli.cmds import sysdig

@patch("paasta_tools.cli.cmds.sysdig.get_subparser", autospec=True)
def test_add_subparser(mock_get_subparser):
    mock_subparsers = mock.Mock()
    sysdig.add_subparser(mock_subparsers)
    assert mock_get_subparser.called

@patch("paasta_tools.cli.cmds.sysdig.client", autospec=True)
def test_get_status_for_instance(mock_client):
    mock_client.get_paasta_oapi_client.return_value = None
    with raises(SystemExit):
        sysdig.get_status_for_instance("cluster1", "my-service", "main")
    mock_client.get_paasta_oapi_client.assert_called_with(cluster="cluster1")

    mock_api = mock.Mock()
    mock_client.get_paasta_oapi_client.return_value = mock.Mock(service=mock_api)
    mock_api.status_instance.return_value = mock.Mock(marathon=False)
    with raises(SystemExit):
        sysdig.get_status_for_instance("cluster1", "my-service", "main")

    mock_api.status_instance.assert_called_with(service="my-service", instance="main")

@patch.object(sys, "argv", ["paasta", "sysdig", "blah", "blah"])
@patch("paasta_tools.cli.cmds.sysdig.load_marathon_service_config", autospec=True)
@patch("paasta_tools.cli.cmds.sysdig.load_system_paasta_config", autospec=True)
@patch("paasta_tools.cli.cmds.sysdig.format_mesos_command", autospec=True)
@patch("paasta_tools.cli.cmds.sysdig.get_mesos_master", autospec=True)
@patch("paasta_tools.cli.cmds.sysdig._run", autospec=True)
@patch("paasta_tools.cli.cmds.sysdig.get_any_mesos_master", autospec=True)
@patch("paasta_tools.cli.cmds.sysdig.subprocess", autospec=True)
@patch("paasta_tools.cli.cmds.sysdig.pick_slave_from_status", autospec=True)
@patch("paasta_tools.cli.cmds.sysdig.get_status_for_instance", autospec=True)
def test_paasta_sysdig(
    mock_get_status_for_instance,
    mock_pick_slave_from_status,
    mock_subprocess,
    mock_get_any_mesos_master,
    mock__run,
    mock_get_mesos_master,
    mock_format_mesos_command,
    mock_load_system_paasta_config,
    mock_load_marathon_service_config,
):

    mock_status = mock.Mock(marathon=mock.Mock(app_id="appID1"))
    mock_get_status_for_instance.return_value = mock_status
    mock_args = mock.Mock(
        cluster="cluster1",
        service="mock_service",
        instance="mock_instance",
        host="host1",
        mesos_id=None,
        local=False,
    )
    mock_pick_slave_from_status.return_value = "host1"
    mock_get_any_mesos_master.return_value = "master1"
    mock__run.return_value = (0, "slave:command123")

    sysdig.paasta_sysdig(mock_args)
    mock_get_any_mesos_master.assert_called_with(
        cluster="cluster1",
        system_paasta_config=mock_load_system_paasta_config.return_value,
    )
    mock__run.assert_called_with(
        "ssh -At -o StrictHostKeyChecking=no -o LogLevel=QUIET master1 "
        '"sudo paasta sysdig blah blah --local"'
    )
    mock_subprocess.call.assert_called_with(["ssh", "-tA", "slave", "command123"])

    mock__run.return_value = (1, "slave:command123")
    with raises(SystemExit):
        sysdig.paasta_sysdig(mock_args)

    mock_args = mock.Mock(
        cluster="cluster1",
        service="mock_service",
        instance="mock_instance",
        host="host1",
        mesos_id=None,
        local=True,
    )
    mock_pick_slave_from_status.return_value = "slave1"
    fake_server_config = {"url": ["http://blah"], "user": "user", "password": "pass"}
    mock_load_system_paasta_config.return_value.get_marathon_servers = mock.Mock(
        return_value=[fake_server_config]
    )
    mock_load_system_paasta_config.return_value.get_previous_marathon_servers = (
        mock.Mock(return_value=[fake_server_config])
    )
    mock_load_marathon_service_config().get_marathon_shard.return_value = None

    mock_get_mesos_master.return_value = mock.Mock(host="http://foo")
    sysdig.paasta_sysdig(mock_args)
    mock_get_status_for_instance.assert_called_with(
        cluster="cluster1", service="mock_service", instance="mock_instance"
    )
    mock_pick_slave_from_status.assert_called_with(status=mock_status, host="host1")
    mock_format_mesos_command.assert_called_with(
        "slave1", "appID1", "http://foo", "http://user:pass@blah"
    )

def test_format_mesos_command():
    ret = sysdig.format_mesos_command(
        "slave1", "appID1", "http://foo", "http://user:pass@blah"
    )
    expected = 'slave1:sudo csysdig -m http://foo,http://user:pass@blah marathon.app.id="/appID1" -v mesos_tasks'
    assert ret == expected

@patch("paasta_tools.cli.cmds.sysdig.calculate_remote_masters", autospec=True)
@patch("paasta_tools.cli.cmds.sysdig.find_connectable_master", autospec=True)
def test_get_any_mesos_master(
    mock_find_connectable_master, mock_calculate_remote_masters, system_paasta_config
):
    mock_calculate_remote_masters.return_value = ([], "fakeERROR")

    with raises(SystemExit):
        sysdig.get_any_mesos_master("cluster1", system_paasta_config)
    mock_calculate_remote_masters.assert_called_with("cluster1", system_paasta_config)

    mock_masters = mock.Mock()
    mock_calculate_remote_masters.return_value = (mock_masters, "fake")
    mock_find_connectable_master.return_value = (False, "fakeERROR")
    with raises(SystemExit):
        sysdig.get_any_mesos_master("cluster1", system_paasta_config)

    mock_master = mock.Mock()
    mock_find_connectable_master.return_value = (mock_master, "fake")
    assert sysdig.get_any_mesos_master("cluster1", system_paasta_config) == mock_master

redpajama_set_name: RedPajamaGithub


text:
(function (flow, _, Backbone, d3, girder) {
    "use strict";

    // The main app view
    flow.App = Backbone.View.extend({
        el: 'body',

        visualizationDescriptors: [
            {
                name: "table",
                inputs: [
                    {name: "data", id: "data", type: "table", format: "rows", inputMode: "dataset"}
                ]
            },
            {
                name: "timeline",
                inputs: [
                    {name: "data", id: "data", type: "table", format: "objectlist"},
                    {name: "x", id: "x", type: "accessor", format: "text", domain: {input: "data", format: "column.names"}},
                    {name: "y", id: "x", type: "accessor", format: "text", domain: {input: "data", format: "column.names"}}
                ]
            },
            {
                name: "scatterplot",
                inputs: [
                    {name: "data", id: "data", type: "table", format: "objectlist"},
                    {name: "x", id: "x", type: "accessor", format: "text", domain: {input: "data", format: "column.names"}},
                    {name: "y", id: "y", type: "accessor", format: "text", domain: {input: "data", format: "column.names"}}
                ]
            },
            {
                name: "dendrogram",
                inputs: [
                    {name: "data", id: "data", type: "tree", format: "nested"},
                    {name: "distance", id: "distance", type: "accessor", format: "text", default: {format: "text", data: "edge_data.weight"}},
                    {name: "label", id: "label", type: "accessor", format: "text", default: {format: "text", data: "node_data.node name"}},
                    {name: "lineStyle", id: "lineStyle", type: "string", format: "text", domain: ["axisAligned", "curved"]},
                    {name: "orientation", id: "orientation", type: "string", format: "text", domain: ["horizontal", "vertical"]}
                ]
            },
            {
                name: "tablelink",
                inputs: [
                    {name: "data", id: "data", type: "table", format: "rows"},
                    {name: "source", id: "source", type: "string", format: "text", domain: {input: "data", format: "column.names"}},
                    {name: "target", id: "target", type: "string", format: "text", domain: {input: "data", format: "column.names"}}
                ]
            },
            {
                name: "image",
                inputs: [
                    {name: "data", id: "data", type: "image", format: "png.base64"}
                ]
            },
            {
                name: "string",
                inputs: [
                    {name: "data", id: "data", type: "string", format: "text", inputMode: "dataset"}
                ]
            },
            {
                name: "treeHeatmap",
                inputs: [
                    {
                        name: "tree",
                        id: "tree",
                        type: "tree",
                        format: "vtktree.serialized",
                        dataIsURI: true
                    },
                    {
                        name: "table",
                        id: "table",
                        type: "table",
                        format: "vtktable.serialized",
                        dataIsURI: true
                    }
                ]
            },
            {
                name: "tanglegram",
                inputs: [
                    {
                        name: "tree1",
                        id: "tree1",
                        type: "tree",
                        format: "vtktree.serialized",
                        dataIsURI: true
                    },
                    {
                        name: "tree2",
                        id: "tree2",
                        type: "tree",
                        format: "vtktree.serialized",
                        dataIsURI: true
                    },
                    {
                        name: "table",
                        id: "table",
                        type: "table",
                        format: "csv",
                        dataIsURI: true
                    }
                ]
            },
            {
                name: "edgebundling",
                inputs: [
                    {name: "data", id: "data", type: "table", format: "rows"}
                ]
            },
            {
                name: "interactiveheatmap",
                inputs: [
                    {name: "data", id: "data", type: "table", format: "rows"}
                ]
            },
            {
                name: "scatterplotmatrix",
                inputs: [
                    {
                        name: "data",
                        id: "data",
                        type: "table",
                        format: "rows"
                    },
                    {
                        name: "y",
                        id: "y",
                        type: "accessor",
                        domain: {input: "data", format: "column.names"}
                    }
                ]
            },
            {
                name: "spaceMap",
                inputs: [
                    {
                        name: "data",
                        id: "data",
                        type: "table",
                        format: "objectlist"
                    },
                    {
                        name: "charge",
                        id: "charge",
                        type: "number",
                        format: "number",
                        default: {format: "number", data: -30}
                    },
                    {
                        name: "gravity",
                        id: "gravity",
                        type: "number",
                        format: "number",
                        default: {format: "number", data: 0.1}
                    },
                    {
                        name: "constraints",
                        id: "constraints",
                        type: "array",
                        components: [
                            {
                                name: "accessor",
                                id: "accessor",
                                type: "accessor",
                                domain: {input: "data", format: "column.names"}
                            },
                            {
                                name: "type",
                                id: "type",
                                type: "string",
                                domain: [
                                    'link-bin',
                                    'link',
                                    'link-closest',
                                    'x',
                                    'y',
                                    'ordinalx',
                                    'ordinaly',
                                    'xy',
                                    'map',
                                    'binx',
                                    'biny',
                                    'linex',
                                    'liney',
                                    'radius'
                                ]
                            }
                        ]
                    }
                ]
            },
            {
                name: "geojsMap",
                inputs: [
                    {
                        name: "data",
                        type: "table",
                        format: "objectlist"
                    },
                    {
                        name: "tileUrl",
                        type: "string",
                        domain: [
                            'http://otile1.mqcdn.com/tiles/1.0.0/map/<zoom>/<x>/<y>.png',
                            'http://otile1.mqcdn.com/tiles/1.0.0/sat/<zoom>/<x>/<y>.png',
                            'http://tile.openstreetmap.org/<zoom>/<x>/<y>.png',
                            'http://tile.stamen.com/toner-lite/<zoom>/<x>/<y>.png'
                        ]
                    },
                    {
                        name: "layers",
                        type: "array",
                        components: [
                            {
                                name: "renderer",
                                type: "string",
                                domain: ["d3", "vgl"]
                            },
                            {
                                name: "features",
                                type: "array",
                                components: [
                                    {
                                        name: "type",
                                        type: "string",
                                        domain: ["point"]
                                    },
                                    {
                                        name: "position",
                                        type: "coordinate",
                                        domain: {input: "data", format: "column.names"}
                                    },
                                    {
                                        name: "size",
                                        type: "accessor",
                                        domain: {input: "data", format: "column.names"}
                                    },
                                    {
                                        name: "fillColor",
                                        type: "accessor",
                                        domain: {input: "data", format: "column.names"}
                                    },
                                    {
                                        name: "strokeColor",
                                        type: "accessor",
                                        domain: {input: "data", format: "column.names"}
                                    }
                                ]
                            }
                        ]
                    }
                ]
            }
        ],

        events: {
            'click #login': function () {
                girder.events.trigger('g:loginUi');
            },

            'click #logout': function () {
                girder.restRequest({
                    path: 'user/authentication',
                    type: 'DELETE'
                }).done(_.bind(function () {
                    girder.currentUser = null;
                    girder.events.trigger('g:login');
                }, this));
            },

            'click #register': function () {
                girder.events.trigger('g:registerUi');
            },

            'click .new-collection': function () {
                var name = $('.new-collection-name').val(),
                    isPublic = $('.new-collection-public').is(':checked');

                girder.restRequest({
                    path: 'collection/romanesco/module',
                    type: 'post',
                    data: {
                        name: name,
                        description: '',
                        public: isPublic
                    }
                }).done(_.bind(function (collection) {
                    $('.new-collection-name').val('');
                    this.collection.fetch({}, true);
                }, this)).error(_.bind(function (xhr, status, message) {
                    $('.new-collection-name').val('');
                    console.error(message);
                }, this));
            }
        },

        initialize: function () {
            girder.restRequest({
                path: 'user/authentication',
                error: null
            }).done(_.bind(function (resp) {
                if (resp) {
                    resp.user.token = resp.authToken.token;
                    girder.currentUser = new girder.models.UserModel(resp.user);
                }
                this.render();
            }, this)).error(_.bind(function () {
                this.render();
            }, this));

            this.$("#control-panel").controlPanel();

            // Keep a mapping from folders to collections
            flow.collectionForFolder = {};

            this.collection = new girder.collections.CollectionCollection();
            this.collection.append = false;
            this.collection.pageLimit = 100;

            this.view = new flow.CollectionsView({
                el: this.$('#collections'),
                itemView: flow.CollectionView,
                itemOptions: {collection: this.collection},
                collection: this.collection
            });
            this.view.on('flow:change-active', this.collectionVisibilityChange, this);
            this.view.render();
            this.collection.fetch();

            this.datasets = new flow.DatasetCollection();
            this.datasets.append = true;
            this.datasets.pageLimit = 100;
            this.datasets.on('add', function (item) {
                item.set({collection: flow.collectionForFolder[item.get('folderId')]});
            });

            this.datasetsView = new flow.DatasetManagementView({
                el: this.$('#dataset-management'),
                datasets: this.datasets
            });
            this.datasetsView.render();

            this.visualizations = new Backbone.Collection();
            this.visualizationDescriptors.forEach(_.bind(function (vis) {
                vis.visualization = true;
                vis.outputs = [];
                this.visualizations.add({
                    name: vis.name,
                    meta: {
                        visualization: vis
                    }
                });
            }, this));

            this.presets = new girder.collections.ItemCollection();
            this.presets.append = true;
            this.presets.pageLimit = 100;
            this.presets.on('add', function (item) {
                item.set({collection: flow.collectionForFolder[item.get('folderId')]});
            });

            this.analyses = new girder.collections.ItemCollection();
            this.analyses.append = true;
            this.analyses.pageLimit = 100;
            this.analyses.on('add', function (item) {
                item.set({collection: flow.collectionForFolder[item.get('folderId')]});
            });

            this.analysesView = new flow.AnalysisManagementView({
                el: this.$('#analysis-management'),
                analyses: this.analyses,
                datasets: this.datasets,
                visualizations: this.visualizations,
                presets: this.presets
            });
            this.analysesView.render();

            this.visualizationsView = new flow.VisualizationManagementView({
                el: this.$('#visualization-management'),
                datasets: this.datasets,
                visualizations: this.visualizations,
                presets: this.presets
            });
            this.visualizationsView.render();

            girder.events.on('g:loginUi', this.loginDialog, this);
            girder.events.on('g:registerUi', this.registerDialog, this);
            girder.events.on('g:login', this.login, this);
        },

        render: function () {
            if (girder.currentUser) {
                this.$("#logged-in").removeClass("hidden");
                this.$("#logged-out").addClass("hidden");
                this.$("#name").text("Logged in as " + girder.currentUser.get('firstName') + " " + girder.currentUser.get('lastName'));
            } else {
                this.$("#logged-in").addClass("hidden");
                this.$("#logged-out").removeClass("hidden");
            }
            this.$('.new-collection-form').toggleClass('hidden', girder.currentUser === null);
        },

        /**
         * Show a dialog allowing a user to login or register.
         */
        loginDialog: function () {
            if (!this.loginView) {
                this.loginView = new girder.views.LoginView({
                    el: this.$('#g-dialog-container')
                });
            }
            this.loginView.render();
        },

        registerDialog: function () {
            if (!this.registerView) {
                this.registerView = new girder.views.RegisterView({
                    el: this.$('#g-dialog-container')
                });
            }
            this.registerView.render();
        },

        collectionVisibilityChange: function (collection) {
            if (collection.get('active')) {

                girder.restRequest({
                    path: 'folder?parentType=collection&parentId=' + collection.id,
                    error: null
                }).done(_.bind(function (folders) {
                    folders.forEach(function (f) {
                        if (f.name === "Analyses") {
                            collection.set({analysisFolder: f._id});
                        } else if (f.name === "Data") {
                            collection.set({dataFolder: f._id});
                        } else if (f.name === "Visualizations") {
                            collection.set({visualizationFolder: f._id});
                        }
                    });

                    if (collection.get('analysisFolder')) {
                        flow.collectionForFolder[collection.get('analysisFolder')] = collection;
                        this.analyses.offset = 0;
                        this.analyses.fetch({
                            folderId: collection.get('analysisFolder')
                        });
                    }

                    if (collection.get('dataFolder')) {
                        flow.collectionForFolder[collection.get('dataFolder')] = collection;
                        this.datasets.offset = 0;
                        this.datasets.fetch({
                            folderId: collection.get('dataFolder')
                        });
                    }

                    if (collection.get('visualizationFolder')) {
                        flow.collectionForFolder[collection.get('visualizationFolder')] = collection;
                        this.presets.offset = 0;
                        this.presets.fetch({
                            folderId: collection.get('visualizationFolder')
                        });
                    }
                }, this)).error(_.bind(function () {
                    // TODO error message
                }, this));
            } else {
                this.analyses.remove(this.analyses.where({collection: collection}));
                this.datasets.remove(this.datasets.where({collection: collection}));
            }
        },

        login: function () {
            this.render();
            this.collection.fetch({}, true);
        }
    });

}(window.flow, window._, window.Backbone, window.d3, window.girder));


text:
import logging
import os
import sched
import sys
import time

import redis

import redis_lock

try:
    import termios
    import tty
except ImportError:
    # Probably Windows.
    try:
        import msvcrt
    except ImportError:
        # FIXME what to do on other platforms?
        # Just give up here.
        raise ImportError('getch not available')
    else:
        getch = msvcrt.getch
else:

    def getch():
        """getch() -> key character

        Read a single keypress from stdin and return the resulting character.
        Nothing is echoed to the console. This call will block if a keypress
        is not already available, but will not wait for Enter to be pressed.

        If the pressed key was a modifier key, nothing will be detected; if
        it were a special function key, it may return the first character of
        of an escape sequence, leaving additional characters in the buffer.
        """
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(fd)
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch

logging.basicConfig(level="DEBUG", format="%(asctime)s | %(process)6s | %(message)s")

c = redis.StrictRedis()
pid = os.getpid()
lock = redis_lock.Lock(c, sys.argv[1], expire=5)

def run():
    with lock:
        logging.debug("GOT LOCK. WAITING ...")
        time.sleep(0.05)
        logging.debug("DONE. Press any key to exit.")

    getch()

if __name__ == "__main__":
    s = sched.scheduler(time.time, time.sleep)
    now = int(time.time()) / 10
    t = (now + 1) * 10
    logging.debug("Running in %s seconds ...", t - time.time())
    s.enterabs(t, 0, run, ())
    s.run()


text:
import Lab from 'lab';
var lab = exports.lab = Lab.script();

import Code from 'code';
var describe = lab.describe;
var it = lab.it;
var beforeEach = lab.beforeEach;
var expect = Code.expect;

import eureka from '../../lib';
import config from '../config';
import fixtures from '../utils/fixtures';

const jsonApiMime = 'application/vnd.api+json';

describe('Route [find]', function() {

    /** load the server **/
    var server;
    lab.before(function(done) {
        eureka(config).compose(function(err, s) {
            expect(err).to.not.exists();
            server = s;
            done();
        });
    });

     /** load the fixtures **/
    beforeEach(function(done){
        fixtures.clear(server).then(() => {
            return fixtures.genericDocuments(server);
        }).then(() => {
            done();
        }).catch((error) => {
            console.log(error);
        });
    });

    it('should return all documents', function(done){
        let options = {
            method: 'GET',
            url: '/api/1/generics'
        };

        server.inject(options, function(response) {
            expect(response.statusCode).to.equal(200);
            expect(response.headers['content-type']).to.include(jsonApiMime);

            var data = response.result.data;
            expect(data).to.be.an.array();
            expect(data.length).to.be.equal(10);
            expect(data[0].type).to.equal('Generic');

            done();
        });
    });

    it('should filter by id', function(done){
        let options = {
            method: 'GET',
            url: '/api/1/generics?filter[id]=generic3'
        };

        server.inject(options, function(response) {
            expect(response.statusCode).to.equal(200);
            expect(response.headers['content-type']).to.include(jsonApiMime);

            var data = response.result.data;
            expect(data).to.be.an.array();
            expect(data.length).to.be.equal(1);
            expect(data[0].id).to.equal('generic3');
            expect(data[0].type).to.equal('Generic');
            expect(data[0].attributes).to.exist();
            done();
        });
    });

    it('should filter by ids', function(done){
        let options = {
            method: 'GET',
            url: '/api/1/generics?filter[id][$in]=["generic3","generic2"]'
        };

        server.inject(options, function(response) {
            expect(response.statusCode).to.equal(200);
            expect(response.headers['content-type']).to.include(jsonApiMime);

            var data = response.result.data;
            expect(data).to.be.an.array();
            expect(data.length).to.be.equal(2);
            expect(data[0].id).to.equal('generic3');
            expect(data[0].attributes).to.exist();
            expect(data[1].id).to.equal('generic2');
            expect(data[1].attributes).to.exist();
            done();
        });
    });

    it('should sort the documents', function(done){

        let options = {
            method: 'GET',
            url: `/api/1/generics?sort=-integer`
        };

        server.inject(options, function(response) {
            expect(response.statusCode).to.equal(200);
            expect(response.headers['content-type']).to.include(jsonApiMime);

            let data = response.result.data;
            expect(data).to.be.an.array();
            expect(data.length).to.be.equal(10);
            expect(data.map((o) => {
                return o.attributes.integer;
            })).to.deep.equal([10, 9, 8, 7, 6, 5, 4, 3, 2, 1]);
            done();
        });
    });

    it('should limit the documents', function(done){

        let options = {
            method: 'GET',
            url: `/api/1/generics?limit=5`
        };

        server.inject(options, function(response) {
            expect(response.statusCode).to.equal(200);
            expect(response.headers['content-type']).to.include(jsonApiMime);

            let data = response.result.data;
            expect(data).to.be.an.array();
            expect(data.length).to.be.equal(5);
            done();
        });
    });

    it('should return only the specified fields in array', function(done){
        let options = {
            method: 'GET',
            url: `/api/1/generics?fields=["integer","text"]`
        };

        server.inject(options, function(response) {
            expect(response.statusCode).to.equal(200);
            expect(response.headers['content-type']).to.include(jsonApiMime);

            let data = response.result.data;
            expect(data).to.be.an.array();
            data.forEach(function(item) {
                expect(item.attributes).to.only.include(['integer', 'text']);
                expect(item.relationships).to.not.exist();
            });
            done();
        });
    });

    it('should return only the specified comma separated fields', function(done){
        let options = {
            method: 'GET',
            url: `/api/1/generics?fields=integer,text`
        };

        server.inject(options, function(response) {
            expect(response.statusCode).to.equal(200);
            expect(response.headers['content-type']).to.include(jsonApiMime);

            let data = response.result.data;
            expect(data).to.be.an.array();
            data.forEach(function(item) {
                expect(item.attributes).to.only.include(['integer', 'text']);
                expect(item.relationships).to.not.exist();
            });
            done();
        });
    });

    it('should include all relations of a collection', function(done){

        let options = {
            method: 'GET',
            url: `/api/1/generics?include=1`
        };

        server.inject(options, function(response) {
            expect(response.statusCode).to.equal(200);
            expect(response.headers['content-type']).to.include(jsonApiMime);

            var included = response.result.included;
            expect(included).to.be.an.array();
            expect(included.length).to.equal(5);
            expect(included.map((item) => item.id)).to.only.include([
                'relation0',
                'relation1',
                'relation2',
                'relation3',
                'relation4'
            ]);
            done();
        });
    });

    it('should include a specified relation of a collection', function(done){

        let options = {
            method: 'GET',
            url: `/api/1/generics?include=relation`
        };

        server.inject(options, function(response) {
            expect(response.statusCode).to.equal(200);
            expect(response.headers['content-type']).to.include(jsonApiMime);

            var included = response.result.included;
            expect(included).to.be.an.array();
            expect(included.length).to.equal(2);
            expect(included.map((item) => item.id)).to.only.include([
                'relation0', 'relation1']);
            done();
        });
    });

    it('should include multiple specified relations of a collection', function(done){

        let options = {
            method: 'GET',
            url: `/api/1/generics?limit=1&include=relation,relations`
        };

        server.inject(options, function(response) {
            expect(response.statusCode).to.equal(200);
            expect(response.headers['content-type']).to.include(jsonApiMime);

            var included = response.result.included;
            expect(included).to.be.an.array();
            expect(included.length).to.equal(3);
            expect(included.map((item) => item.id)).to.only.include([
                'relation0', 'relation1', 'relation2']);
            done();
        });
    });

    it('should include all relations of a document', function(done){

        let options = {
            method: 'GET',
            url: `/api/1/generics?filter[id]=generic1&include=1`
        };

        server.inject(options, function(response) {
            expect(response.statusCode).to.equal(200);
            expect(response.headers['content-type']).to.include(jsonApiMime);
            var included = response.result.included;
            expect(included).to.be.an.array();
            expect(included.map((item) => item.id)).to.only.include([
                'relation0', 'relation1', 'relation2']);
            done();
        });
    });

    it('should allow $in operator', function(done){

        let options = {
            method: 'GET',
            url: `/api/1/generics?filter[integer][$in]=[2,4,6]`
        };

        server.inject(options, function(response) {
            expect(response.statusCode).to.equal(200);
            expect(response.headers['content-type']).to.include(jsonApiMime);

            var data = response.result.data;
            expect(data).to.be.an.array();
            expect(data.length).to.be.equal(3);
            data.forEach(function(item) {
                expect(item.attributes.integer).to.satisfy((num) => [2, 4, 6].indexOf(num) > -1);
            });

            done();
        });
    });

    it('should query relations', function(done){

        let options = {
            method: 'GET',
            url: `/api/1/generics?filter[relation.text]=relation 1`
        };

        server.inject(options, function(response) {
            expect(response.statusCode).to.equal(200);
            expect(response.headers['content-type']).to.include(jsonApiMime);

            var data = response.result.data;
            expect(data).to.be.an.array();
            expect(data.length).to.be.equal(5);
            data.forEach(function(item) {
                expect(item.attributes.integer).to.satisfy((num) => [1, 3, 7, 5, 9].indexOf(num) > -1);
            });

            done();
        });
    });

    it('should return an error if a field in query is not specified in schema', function(done){

        let options = {
            method: 'GET',
            url: `/api/1/generics?filter[unknwonField]=3`
        };

        server.inject(options, function(response) {
            expect(response.statusCode).to.equal(400);
            expect(response.headers['content-type']).to.include(jsonApiMime);

            let error = response.result.errors[0];
            expect(error.status).to.equal(400);
            expect(error.title).to.equal('Bad Request');
            expect(error.detail).to.equal('ValidationError: malformed query');
            expect(error.meta.infos).to.equal('unknown property "unknwonField" on model "Generic"');

            done();
        });
    });

    it('should return an error when query with a bad operator', function(done){

        let options = {
            method: 'GET',
            url: `/api/1/generics?filter[integer][$arf]=3`
        };

        server.inject(options, function(response) {
            expect(response.statusCode).to.equal(400);
            expect(response.headers['content-type']).to.include(jsonApiMime);

            let error = response.result.errors[0];
            expect(error.status).to.equal(400);
            expect(error.title).to.equal('Bad Request');
            expect(error.detail).to.equal('ValidationError: malformed query');
            expect(error.meta.infos).to.equal('unknown operator "$arf"');

            done();
        });
    });

    it('should return an error when query with a bad type', function(done){

        let options = {
            method: 'GET',
            url: `/api/1/generics?filter[integer]=bla&filter[boolean]=arf`
        };

        server.inject(options, function(response) {
            expect(response.statusCode).to.equal(400);
            expect(response.headers['content-type']).to.include(jsonApiMime);

            let error = response.result.errors[0];
            expect(error.status).to.equal(400);
            expect(error.title).to.equal('Bad Request');
            expect(error.detail).to.equal('ValidationError: malformed query');
            expect(error.meta.infos).to.equal('"integer" must be a number');

            done();
        });
    });

    it('should return an error when query with a bad relation type', function(done){

        let options = {
            method: 'GET',
            url: `/api/1/generics?filter[relation.related]=bla`
        };

        server.inject(options, function(response) {
            expect(response.statusCode).to.equal(400);
            expect(response.headers['content-type']).to.include(jsonApiMime);

            let error = response.result.errors[0];
            expect(error.status).to.equal(400);
            expect(error.title).to.equal('Bad Request');
            expect(error.detail).to.equal('ValidationError: malformed query');
            expect(error.meta.infos).to.equal('"related" must be a boolean');

            done();
        });

    });

    it('should return an error when specified a bad property in array', function(done){

        let options = {
            method: 'GET',
            url: `/api/1/generics?fields=["boolean","unknownProperty"]`
        };

        server.inject(options, function(response) {
            expect(response.statusCode).to.equal(400);
            expect(response.headers['content-type']).to.include(jsonApiMime);

            let error = response.result.errors[0];
            expect(error.status).to.equal(400);
            expect(error.title).to.equal('Bad Request');
            expect(error.detail).to.equal('ValidationError: malformed options');
            expect(error.meta.infos).to.equal('fields: unknown property "unknownProperty" on model "Generic"');

            done();
        });
    });

    it('should return an error when specified a bad property as string', function(done){

        let options = {
            method: 'GET',
            url: `/api/1/generics?fields=boolean,unknownProperty`
        };

        server.inject(options, function(response) {
            expect(response.statusCode).to.equal(400);
            expect(response.headers['content-type']).to.include(jsonApiMime);

            let error = response.result.errors[0];
            expect(error.status).to.equal(400);
            expect(error.title).to.equal('Bad Request');
            expect(error.detail).to.equal('ValidationError: malformed options');
            expect(error.meta.infos).to.equal('fields: unknown property "unknownProperty" on model "Generic"');

            done();
        });
    });

    it('should return an error when sorting with an unknown property as array', function(done){

        let options = {
            method: 'GET',
            url: `/api/1/generics?sort=["boolean","unknownProperty"]`
        };

        server.inject(options, function(response) {
            expect(response.statusCode).to.equal(400);
            expect(response.headers['content-type']).to.include(jsonApiMime);

            let error = response.result.errors[0];
            expect(error.status).to.equal(400);
            expect(error.title).to.equal('Bad Request');
            expect(error.detail).to.equal('ValidationError: malformed options');
            expect(error.meta.infos).to.equal('sort: unknown property "unknownProperty" on model "Generic"');

            done();
        });

    });

    it('should return an error when sorting with an unknown property as string', function(done){

        let options = {
            method: 'GET',
            url: `/api/1/generics?sort=boolean,unknownProperty`
        };

        server.inject(options, function(response) {
            expect(response.statusCode).to.equal(400);
            expect(response.headers['content-type']).to.include(jsonApiMime);

            let error = response.result.errors[0];
            expect(error.status).to.equal(400);
            expect(error.title).to.equal('Bad Request');
            expect(error.detail).to.equal('ValidationError: malformed options');
            expect(error.meta.infos).to.equal('sort: unknown property "unknownProperty" on model "Generic"');

            done();
        });

    });

});


text:
package uk.org.cowgill.james.jircd;

import uk.org.cowgill.james.jircd.util.ModeUtils;

/**
 * An abstract servlet helper class
 *
 * @author James
 */
public abstract class AbstractServlet extends Client
{
	/**
	 * Event occurs when a message is received by this servlet
	 *
	 * @param msg message received
	 */
	public abstract void messageReceived(Message msg);

	/**
	 * Creates a new servlet with the given ID
	 *
	 * To avoid confusion - servlets should use either 127.0.0.1 or localhost as the hostname
	 *
	 * @param id ID of this servlet
	 * @throws ModuleLoadException thrown if the nickname already exists
	 */
	protected AbstractServlet(IRCMask id) throws ModuleLoadException
	{
		//Set ID
		super(id, ModeUtils.setMode(0, 'B'));

		//Validate nickname
		Server server = Server.getServer();
		if(server.clientsByNick.containsKey(id.nick))
		{
			//Error
			server.clients.remove(this);
			throw new ModuleLoadException("Nickname for servlet already registered");
		}

		//Register
		this.setRegistrationFlag(RegistrationFlags.AllFlags);
		server.clientsByNick.put(id.nick, this);
	}

	@Override
	public final void send(Object data)
	{
		Message msg;

		//Redirect to received message
		if(data instanceof Message)
		{
			msg = (Message) data;
		}
		else
		{
			msg = Message.parse(data.toString());
		}

		messageReceived(msg);
	}

	@Override
	protected boolean changeClass(ConnectionClass clazz, boolean defaultClass)
	{
		//Fake good class change
		return true;
	}

	@Override
	public void restoreClass()
	{
	}

	@Override
	public String getIpAddress()
	{
		return "127.0.0.1";
	}

	@Override
	public boolean isRemote()
	{
		return false;
	}

	@Override
	public long getIdleTime()
	{
		return 0;
	}
}


text:
class ItemView < ApplicationRecord
  belongs_to :item_type

  validates_presence_of :item_type
  validates_presence_of :name

  serialize :template, HashSerializer

  after_save :remove_default_list_view_from_other_views, if: :default_for_list_view?
  after_save :remove_default_item_view_from_other_views, if: :default_for_item_view?

  def remove_default_item_view_from_other_views
    item_type.item_views.where("item_views.id != ?", id).update_all(:default_for_item_view => false)
  end

  def remove_default_list_view_from_other_views
    item_type.item_views.where("item_views.id != ?", id).update_all(:default_for_list_view => false)
  end

  def render(item, locale)
    presenter = ItemViewPresenter.new(self, self, item, locale, strip_p: true)
    presenter.render
  end

  def template_json
    JSON.parse template
  end

  def describe
    as_json(only: %i(name default_for_display_name default_for_item_view default_for_list_view)).merge(
      "item_type": item_type.slug,
      "template": template_json
    )
  end
end


text:
#include "config.h"
#include "core/layout/LayoutReplica.h"

#include "core/paint/ReplicaPainter.h"

namespace blink {

LayoutReplica::LayoutReplica()
    : LayoutBox(nullptr)
{
    // This is a hack. Replicas are synthetic, and don't pick up the attributes of the
    // layoutObjects being replicated, so they always report that they are inline, non-replaced.
    // However, we need transforms to be applied to replicas for reflections, so have to pass
    // the if (!isInline() || isReplaced()) check before setHasTransform().
    setReplaced(true);
}

LayoutReplica* LayoutReplica::createAnonymous(Document* document)
{
    LayoutReplica* layoutObject = new LayoutReplica();
    layoutObject->setDocumentForAnonymous(document);
    return layoutObject;
}

LayoutReplica::~LayoutReplica()
{
}

void LayoutReplica::layout()
{
    setFrameRect(parentBox()->borderBoxRect());
    addVisualOverflow(parentBox()->visualOverflowRect());
    updateLayerTransformAfterLayout();
    clearNeedsLayout();
}

void LayoutReplica::computePreferredLogicalWidths()
{
    m_minPreferredLogicalWidth = parentBox()->size().width();
    m_maxPreferredLogicalWidth = m_minPreferredLogicalWidth;
    clearPreferredLogicalWidthsDirty();
}

void LayoutReplica::paint(const PaintInfo& paintInfo, const LayoutPoint& paintOffset)
{
    ReplicaPainter(*this).paint(paintInfo, paintOffset);
}

} // namespace blink


text:
from pysnmp import debug
from pysnmp.proto import errind
from pysnmp.proto import error
from pysnmp.smi.error import NoSuchInstanceError

# 3.2
class Vacm(object):
    """View-based Access Control Model"""
    ACCESS_MODEL_ID = 3

    _powOfTwoSeq = (128, 64, 32, 16, 8, 4, 2, 1)

    def __init__(self):
        self._contextBranchId = -1
        self._groupNameBranchId = -1
        self._accessBranchId = -1
        self._viewTreeBranchId = -1

        self._contextMap = {}
        self._groupNameMap = {}
        self._accessMap = {}
        self._viewTreeMap = {}

    def _addAccessEntry(self, groupName, contextPrefix, securityModel,
                        securityLevel, prefixMatch, readView, writeView,
                        notifyView):
        if not groupName:
            return

        groups = self._accessMap

        try:
            views = groups[groupName]

        except KeyError:
            views = groups[groupName] = {}

        for viewType, viewName in (
                ('read', readView), ('write', writeView),
                ('notify', notifyView)):

            try:
                matches = views[viewType]

            except KeyError:
                matches = views[viewType] = {}

            try:
                contexts = matches[prefixMatch]

            except KeyError:
                contexts = matches[prefixMatch] = {}

            try:
                models = contexts[contextPrefix]

            except KeyError:
                models = contexts[contextPrefix] = {}

            try:
                levels = models[securityModel]

            except KeyError:
                levels = models[securityModel] = {}

            levels[securityLevel] = viewName

    def _getFamilyViewName(self, groupName, contextName, securityModel, securityLevel, viewType):
        groups = self._accessMap

        try:
            views = groups[groupName]

        except KeyError:
            raise error.StatusInformation(errorIndication=errind.noGroupName)

        try:
            matches = views[viewType]

        except KeyError:
            raise error.StatusInformation(errorIndication=errind.noAccessEntry)

        try:
            # vacmAccessTable #2: exact match shortcut
            return matches[1][contextName][securityModel][securityLevel]

        except KeyError:
            pass

        # vacmAccessTable #2: fuzzy look-up

        candidates = []

        for match, names in matches.items():

            for context, models in names.items():

                if match == 1 and contextName != context:
                    continue

                if match == 2 and contextName[:len(context)] != context:
                    continue

                for model, levels in models.items():
                    for level, viewName in levels.items():

                        # priorities:
                        # - matching securityModel
                        # - exact context name match
                        # - longer partial match
                        # - highest securityLevel
                        rating = securityModel == model, match == 1, len(context), level

                        candidates.append((rating, viewName))

        if not candidates:
            raise error.StatusInformation(errorIndication=errind.notInView)

        candidates.sort()

        rating, viewName = candidates[0]
        return viewName

    def isAccessAllowed(self,
                        snmpEngine,
                        securityModel,
                        securityName,
                        securityLevel,
                        viewType,
                        contextName,
                        variableName):

        mibInstrumController = snmpEngine.msgAndPduDsp.mibInstrumController
        mibBuilder = mibInstrumController.mibBuilder

        debug.logger & debug.FLAG_ACL and debug.logger(
            'isAccessAllowed: securityModel %s, securityName %s, '
            'securityLevel %s, viewType %s, contextName %s for '
            'variableName %s' % (securityModel, securityName,
                                 securityLevel, viewType, contextName,
                                 variableName))

        # Rebuild contextName map if changed

        vacmContextName, = mibInstrumController.mibBuilder.importSymbols(
            'SNMP-VIEW-BASED-ACM-MIB', 'vacmContextName')

        if self._contextBranchId != vacmContextName.branchVersionId:

            self._contextMap.clear()

            nextMibNode = vacmContextName

            while True:
                try:
                    nextMibNode = vacmContextName.getNextNode(nextMibNode.name)

                except NoSuchInstanceError:
                    break

                self._contextMap[nextMibNode.syntax] = True

            self._contextBranchId = vacmContextName.branchVersionId

        # 3.2.1
        if contextName not in self._contextMap:
            raise error.StatusInformation(errorIndication=errind.noSuchContext)

        # Rebuild groupName map if changed

        vacmGroupName, = mibInstrumController.mibBuilder.importSymbols(
            'SNMP-VIEW-BASED-ACM-MIB', 'vacmGroupName')

        if self._groupNameBranchId != vacmGroupName.branchVersionId:

            vacmSecurityToGroupEntry, = mibInstrumController.mibBuilder.importSymbols(
                'SNMP-VIEW-BASED-ACM-MIB', 'vacmSecurityToGroupEntry')

            self._groupNameMap.clear()

            nextMibNode = vacmGroupName

            while True:
                try:
                    nextMibNode = vacmGroupName.getNextNode(nextMibNode.name)

                except NoSuchInstanceError:
                    break

                instId = nextMibNode.name[len(vacmGroupName.name):]

                indices = vacmSecurityToGroupEntry.getIndicesFromInstId(instId)

                self._groupNameMap[indices] = nextMibNode.syntax

            self._groupNameBranchId = vacmGroupName.branchVersionId

        # 3.2.2
        indices = securityModel, securityName

        try:
            groupName = self._groupNameMap[indices]

        except KeyError:
            raise error.StatusInformation(errorIndication=errind.noGroupName)

        # Rebuild access map if changed

        vacmAccessStatus, = mibInstrumController.mibBuilder.importSymbols(
            'SNMP-VIEW-BASED-ACM-MIB', 'vacmAccessStatus')

        if self._accessBranchId != vacmAccessStatus.branchVersionId:

            (vacmAccessEntry,
             vacmAccessContextPrefix,
             vacmAccessSecurityModel,
             vacmAccessSecurityLevel,
             vacmAccessContextMatch,
             vacmAccessReadViewName,
             vacmAccessWriteViewName,
             vacmAccessNotifyViewName) = mibInstrumController.mibBuilder.importSymbols(
                'SNMP-VIEW-BASED-ACM-MIB',
                'vacmAccessEntry',
                'vacmAccessContextPrefix',
                'vacmAccessSecurityModel',
                'vacmAccessSecurityLevel',
                'vacmAccessContextMatch',
                'vacmAccessReadViewName',
                'vacmAccessWriteViewName',
                'vacmAccessNotifyViewName')

            self._accessMap.clear()

            nextMibNode = vacmAccessStatus

            while True:
                try:
                    nextMibNode = vacmAccessStatus.getNextNode(nextMibNode.name)

                except NoSuchInstanceError:
                    break

                if nextMibNode.syntax != 1:  # active row
                    continue

                instId = nextMibNode.name[len(vacmAccessStatus.name):]

                indices = vacmAccessEntry.getIndicesFromInstId(instId)

                vacmGroupName = indices[0]

                self._addAccessEntry(
                    vacmGroupName,
                    vacmAccessContextPrefix.getNode(
                        vacmAccessContextPrefix.name + instId).syntax,
                    vacmAccessSecurityModel.getNode(
                        vacmAccessSecurityModel.name + instId).syntax,
                    vacmAccessSecurityLevel.getNode(
                        vacmAccessSecurityLevel.name + instId).syntax,
                    vacmAccessContextMatch.getNode(
                        vacmAccessContextMatch.name + instId).syntax,
                    vacmAccessReadViewName.getNode(
                        vacmAccessReadViewName.name + instId).syntax,
                    vacmAccessWriteViewName.getNode(
                        vacmAccessWriteViewName.name + instId).syntax,
                    vacmAccessNotifyViewName.getNode(
                        vacmAccessNotifyViewName.name + instId).syntax
                )

            self._accessBranchId = vacmAccessStatus.branchVersionId

        viewName = self._getFamilyViewName(
            groupName, contextName, securityModel, securityLevel, viewType)

        # Rebuild family subtree map if changed

        vacmViewTreeFamilyViewName, = mibInstrumController.mibBuilder.importSymbols(
            'SNMP-VIEW-BASED-ACM-MIB', 'vacmViewTreeFamilyViewName')

        if self._viewTreeBranchId != vacmViewTreeFamilyViewName.branchVersionId:

            (vacmViewTreeFamilySubtree,
             vacmViewTreeFamilyMask,
             vacmViewTreeFamilyType) = mibInstrumController.mibBuilder.importSymbols(
                'SNMP-VIEW-BASED-ACM-MIB',
                'vacmViewTreeFamilySubtree',
                'vacmViewTreeFamilyMask',
                'vacmViewTreeFamilyType')

            self._viewTreeMap.clear()

            powerOfTwo = [2 ** exp for exp in range(7, -1, -1)]

            nextMibNode = vacmViewTreeFamilyViewName

            while True:
                try:
                    nextMibNode = vacmViewTreeFamilyViewName.getNextNode(
                        nextMibNode.name)

                except NoSuchInstanceError:
                    break

                if nextMibNode.syntax not in self._viewTreeMap:
                    self._viewTreeMap[nextMibNode.syntax] = []

                instId = nextMibNode.name[len(vacmViewTreeFamilyViewName.name):]

                subtree = vacmViewTreeFamilySubtree.getNode(
                    vacmViewTreeFamilySubtree.name + instId).syntax

                mask = vacmViewTreeFamilyMask.getNode(
                    vacmViewTreeFamilyMask.name + instId).syntax

                mode = vacmViewTreeFamilyType.getNode(
                    vacmViewTreeFamilyType.name + instId).syntax

                mask = mask.asNumbers()
                maskLength = min(len(mask) * 8, len(subtree))

                ignoredSubOids = [
                    i * 8 + j for i, octet in enumerate(mask)
                    for j, bit in enumerate(powerOfTwo)
                    if not (bit & octet) and i * 8 + j < maskLength
                ]

                if ignoredSubOids:
                    pattern = list(subtree)

                    for ignoredSubOid in ignoredSubOids:
                        pattern[ignoredSubOid] = 0

                    subtree = subtree.clone(pattern)

                entry = subtree, ignoredSubOids, mode == 1

                self._viewTreeMap[nextMibNode.syntax].append(entry)

            for entries in self._viewTreeMap.values():
                entries.sort(key=lambda x: (len(x[0]), x[0]))

            self._viewTreeBranchId = vacmViewTreeFamilyViewName.branchVersionId

        # 3.2.5a
        indices = viewName

        try:
            entries = self._viewTreeMap[indices]

        except KeyError:
            return error.StatusInformation(errorIndication=errind.notInView)

        accessAllowed = False

        for entry in entries:
            subtree, ignoredSubOids, included = entry

            if ignoredSubOids:
                subOids = list(variableName)

                for ignoredSubOid in ignoredSubOids:
                    subOids[ignoredSubOid] = 0

                normalizedVariableName = subtree.clone(subOids)

            else:
                normalizedVariableName = variableName

            if subtree.isPrefixOf(normalizedVariableName):
                accessAllowed = included

        # 3.2.5c
        if not accessAllowed:
            raise error.StatusInformation(errorIndication=errind.notInView)


text:
[![npm version](https://badge.fury.io/js/camera-angulara.svg)](https://badge.fury.io/js/camera-angulara)

Camera Angulara (inspired by the term _camera obscura_) is an Angular 4+ camera module that allows for pictures
to be taken, uploaded with a lot of customizable settings. It uses different browser's native `getUserMedia()` methods
to get the video from the web-camera meaning that this does not have a flash dependency like a lot of the other camera
libraries in JavaScript. This being said, this is not compatible with pre-HTML5 browsers.

## Installation

To install this package you can pick 1 of 3 options

1. Stable build:

```bash
yarn add camera-angulara
```

2. Nightly build

```bash
yarn add https://gitlab.com/snood1205/camera-angulara#staging
```

3. Edge build (will break a lot do not use for production)

```bash
yarn add https://gitlab.com/snood1205/camera-angulara#edge
```

## Usage

[//]: # "Complete"

## Contributing

Feel free to report issues and complete pull requests using GitLab.


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <title>Spread Operators2</title>

Write a function called addOnlyNums that can take in any number of arguments
        (including numbers or strings), and returns the sum of only the numbers.


text:
<?php

use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use Slim\Views\PhpRenderer;

require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/data/config.php';
require_once __DIR__ . '/Locory.php';
require_once __DIR__ . '/LocoryDbMigrator.php';
require_once __DIR__ . '/LocoryDemoDataGenerator.php';

$app = new \Slim\App;

if (PHP_SAPI !== 'cli')
{
	$app = new \Slim\App(new \Slim\Container([
		'settings' => [
			'displayErrorDetails' => true,
			'determineRouteBeforeAppMiddleware' => true
		],
	]));
	$container = $app->getContainer();
	$container['renderer'] = new PhpRenderer('./views');
}

if (PHP_SAPI === 'cli')
{
	$app->add(new \pavlakis\cli\CliRequest());
}

if (!Locory::IsDemoInstallation() && PHP_SAPI !== 'cli')
{
	$sessionMiddleware = function(Request $request, Response $response, callable $next)
	{
		$route = $request->getAttribute('route');
		$routeName = $route->getName();

		if (!Locory::IsValidSession($_COOKIE['locory_session']) && $routeName !== 'login')
		{
			//Allow also authentication by headers
			if ($request->hasHeader('Locory-Username') && $request->hasHeader('Locory-Password'))
			{
				if ($request->getHeaderLine('Locory-Username') === HTTP_USER && $request->getHeaderLine('Locory-Password') === HTTP_PASSWORD)
				{
					$response = $next($request, $response);
				}
			}
			else
			{
				$response = $response->withRedirect('/login');
			}
		}
		else
		{
			$response = $next($request, $response);
		}

		return $response;
	};

	$app->add($sessionMiddleware);
}

$app->get('/login', function(Request $request, Response $response)
{
	return $this->renderer->render($response, '/layout.php', [
		'title' => 'Login',
		'contentPage' => 'login.php'
	]);
})->setName('login');

$app->post('/login', function(Request $request, Response $response)
{
	$postParams = $request->getParsedBody();
	if (isset($postParams['username']) && isset($postParams['password']))
	{
		if ($postParams['username'] === HTTP_USER && $postParams['password'] === HTTP_PASSWORD)
		{
			$sessionKey = Locory::CreateSession();
			setcookie('locory_session', $sessionKey, time()+2592000); //30 days

			return $response->withRedirect('/');
		}
		else
		{
			return $response->withRedirect('/login?invalid=true');
		}
	}
	else
	{
		return $response->withRedirect('/login?invalid=true');
	}
})->setName('login');

$app->get('/logout', function(Request $request, Response $response)
{
	Locory::RemoveSession($_COOKIE['locory_session']);
	return $response->withRedirect('/');
});

$app->get('/', function(Request $request, Response $response)
{
	Locory::GetDbConnection(true); //For database schema migration

	return $this->renderer->render($response, '/layout.php', [
		'title' => 'Dashboard',
		'contentPage' => 'dashboard.php'
	]);
});

$app->group('/api', function()
{
	$this->post('/add/csv', function(Request $request, Response $response)
	{
		Locory::AddCsvData($request->getBody()->getContents());
		echo json_encode(array('success' => true));
	});

	$this->get('/get/locationpoints/{from}/{to}', function(Request $request, Response $response, $args)
	{
		echo json_encode(Locory::GetLocationPoints($args['from'] . ' 00:00:00', $args['to'] . ' 23:59:59'));
	});

	$this->get('/get/statistics/{from}/{to}', function(Request $request, Response $response, $args)
	{
		echo json_encode(Locory::GetLocationPointStatistics($args['from'] . ' 00:00:00', $args['to'] . ' 23:59:59'));
	});
})->add(function($request, $response, $next)
{
	$response = $next($request, $response);
	return $response->withHeader('Content-Type', 'application/json');
});

$app->group('/cli', function()
{
	$this->get('/calculate/distance', function(Request $request, Response $response)
	{
		Locory::CalculateLocationPointDistances();
	});

	$this->get('/recreatedemo', function(Request $request, Response $response)
	{
		if (Locory::IsDemoInstallation())
		{
			LocoryDemoDataGenerator::RecreateDemo();
		}
	});
})->add(function($request, $response, $next)
{
	$response = $next($request, $response);

	if (PHP_SAPI !== 'cli')
	{
		echo 'Please call this only from CLI';
		return $response->withHeader('Content-Type', 'text/plain')->withStatus(400);
	}

	return $response->withHeader('Content-Type', 'text/plain');
});

$app->run();


text:
#import <React/RCTViewManager.h>

@interface AMapManager : RCTViewManager

@end


text:
"use strict";

import * as http from 'http';
import * as chai from 'chai';
const assert = chai.assert;
import Util from '../../../Util';
import Server from '../../../../Server';
import Configuration from '../../../../Configuration';
import ModelFactory from '../../../../Model/ModelFactory';
import LiveProgramController from '../../../../Controller/Api/Live/LiveProgramController';
import DummyApiModel from '../DummyApiModel';

describe('LiveProgramController', () => {
    let server: Server;
    let modelFactory: ModelFactory;
    let port: number;

    before(() => {
        modelFactory = ModelFactory.getInstance()

        server = Util.createServer({
            "/:GET": new LiveProgramController()
        });
        server.start();

        port = Configuration.getInstance().getConfig()["serverPort"];
    });

    after(() => {
        server.stop();
    });

    it('check option1', (done) => {
        //dummy model をセット
        modelFactory.add("LiveProgramModel", () => {
            return new DummyApiModel((option: { [key: string]: any }) => {
                assert.isString(option["type"]);
                assert.equal(option["type"], "GR");
                assert.isNumber(option["time"]);
                assert.equal(option["time"], 0);
            });
        });

        http.get('http://localhost:' + port + "?type=GR", (res) => {
            assert.equal(200, res.statusCode);
            done();
        });
    });

    it('check option2', (done) => {
        //dummy model をセット
        modelFactory.add("LiveProgramModel", () => {
            return new DummyApiModel((option: { [key: string]: any }) => {
                assert.isString(option["type"]);
                assert.equal(option["type"], "GR");
                assert.isNumber(option["time"]);
                assert.equal(option["time"], 10);
            });
        });

        http.get('http://localhost:' + port + "?type=GR&time=10", (res) => {
            assert.equal(200, res.statusCode);
            done();
        });
    });
});


text:
```javascript
import React, { Component, PropTypes } from 'react';

export default class TestComponent extends Component {

  static propTypes = {
    value: PropTypes.string.isRequired
  };

  constructor() {
    this.state = {name: 'This is a test component'};
  }

  componentWillMount() {}

  componentDidMount() {}

  componentWillReceiveProps(nextProps) {}

  shouldComponentUpdate() {}

  componentWillUpdate() {}

  componentDidUpdate() {}

  componentWillUnmount() {}

  render() {
    const {value} = this.props;
    return (
      <div>
        <label>{ this.state.name }</label>
        <label>{ value }</label>
      </div>
    );
  }
}
```

### Using bind() to bind arguments ###

```javascript
import React, { Component, PropTypes } from 'react';

export default class TestComponent extends Component {

  onClickEvent(type) {
    console.log(type); // option
  }

  render() {
    const type = 'option';
    return (
      <button onClick={this.onClickEvent.bind(this, type)}>Click me</button>);
  }
}
```

### Dispatch All actions function to component ###

```javascript
import React, { Component, PropTypes } from 'react';

import { myActions } from './actions';

class TestComponent extends Component {

  static propTypes = {
    myActions: PropTypes.object.isRequired
  }

  componentWillMount() {
    const { doSomething } = this.props.myActions;
    doSomething();
  }

  render() {
    const type = 'option';
    return (<div />);
  }
}

function mapStateToProps(state) {
    return {};
}

function mapDispatchToProps(dispatch) {
  return {
    myActions: bindActionCreators(myActions, dispatch),
  };
}

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(TestComponent);
```

### Using expression in JSX ###

```javascript
export default class CodeBlock extends Component {
  render() {
    const { language, literal } = this.props;
    return (
      <Highlight
        className={`${language} component-codeblock`}>
        {literal}
      </Highlight>
    );
  }
}

CodeBlock.propTypes = {
  literal      : PropTypes.string,
  language     : PropTypes.string
};
```

### Using jQuery in React Component ###

```javascript
import $ from 'jquery';

```

### Using ReactDom set input value ###

```javascript
componentDidUpdate() {
  var date = this.state.date;
  const { dateField } = this.refs;
  const dateDom = ReactDOM.findDOMNode(dateField);
  dateDom.getElementsByTagName('input')[0].value = date;
}
```


text:
package org.openstack4j.openstack.internal;

import com.google.common.base.*;
import org.openstack4j.api.client.*;
import org.openstack4j.api.exceptions.*;
import org.openstack4j.api.types.*;
import org.openstack4j.core.transport.*;
import org.openstack4j.core.transport.HttpRequest.*;
import org.openstack4j.core.transport.internal.*;
import org.openstack4j.model.*;
import org.openstack4j.model.common.*;
import org.openstack4j.model.identity.*;
import org.openstack4j.model.identity.v2.*;
import org.openstack4j.model.identity.v3.Service;

import java.util.*;

import static org.openstack4j.core.transport.ClientConstants.*;

/**
 * TODO remove once openstack4j 3.0.3 is released
 */
public class BaseOpenStackService {

    ServiceType serviceType = ServiceType.IDENTITY;
    Function<String, String> endpointFunc;

    private static ThreadLocal<String> reqIdContainer = new ThreadLocal<String>();

    public String getXOpenstackRequestId() {
    	return reqIdContainer.get();
    }

    protected BaseOpenStackService() {
    }

    protected BaseOpenStackService(ServiceType serviceType) {
        this(serviceType, null);
    }

    protected BaseOpenStackService(ServiceType serviceType, Function<String, String> endpointFunc) {
        this.serviceType = serviceType;
        this.endpointFunc = endpointFunc;
    }

    protected <R> Invocation<R> get(Class<R> returnType, String... path) {
        return builder(returnType, path, HttpMethod.GET);
    }

    protected <R> Invocation<R> post(Class<R> returnType, String... path) {
        return builder(returnType, path, HttpMethod.POST);
    }

    protected <R> Invocation<ActionResponse> postWithResponse(String... path) {
        return builder(ActionResponse.class, path, HttpMethod.POST);
    }

    protected <R> Invocation<R> put(Class<R> returnType, String... path) {
        return builder(returnType, path, HttpMethod.PUT);
    }

    protected <R> Invocation<R> patch(Class<R> returnType, String... path) {
        return builder(returnType, path, HttpMethod.PATCH);
    }

    protected <R> Invocation<ActionResponse> patchWithResponse(String... path) {
        return builder(ActionResponse.class, path, HttpMethod.PATCH);
    }

    protected <R> Invocation<R> delete(Class<R> returnType, String... path) {
        return builder(returnType, path, HttpMethod.DELETE);
    }

    protected <R> Invocation<ActionResponse> deleteWithResponse(String... path) {
        return builder(ActionResponse.class, path, HttpMethod.DELETE);
    }

    protected <R> Invocation<R> head(Class<R> returnType, String... path) {
        return builder(returnType, path, HttpMethod.HEAD);
    }

    protected <R> Invocation<R> request(HttpMethod method, Class<R> returnType, String path) {
        return builder(returnType, path, method);
    }

    protected String uri(String path, Object... params) {
        if (params.length == 0)
            return path;
        return String.format(path, params);
    }

    private <R> Invocation<R> builder(Class<R> returnType, String[] path, HttpMethod method) {
        return builder(returnType, Joiner.on("").join(path), method);
    }

    @SuppressWarnings("rawtypes")
    private <R> Invocation<R> builder(Class<R> returnType, String path, HttpMethod method) {
        OSClientSession ses = OSClientSession.getCurrent();
        if (ses == null) {
            throw new OS4JException(
                    "Unable to retrieve current session. Please verify thread has a current session available.");
        }
        RequestBuilder<R> req = HttpRequest.builder(returnType).endpointTokenProvider(ses).config(ses.getConfig())
                .method(method).path(path);
        return new Invocation<R>(req, serviceType, endpointFunc);
    }

    protected static class Invocation<R> {
        RequestBuilder<R> req;

        protected Invocation(RequestBuilder<R> req, ServiceType serviceType, Function<String, String> endpointFunc) {
            this.req = req;
            req.serviceType(serviceType);
            req.endpointFunction(endpointFunc);
        }

        public HttpRequest<R> getRequest() {
            return req.build();
        }

        public Invocation<R> param(String name, Object value) {
            req.queryParam(name, value);
            return this;
        }

        public Invocation<R> updateParam(String name, Object value) {
            req.updateQueryParam(name, value);
            return this;
        }

        public Invocation<R> params(Map<String, ? extends Object> params) {
            if (params != null) {
                for (String name : params.keySet())
                    req.queryParam(name, params.get(name));
            }
            return this;
        }

        public Invocation<R> param(boolean condition, String name, Object value) {
            if (condition)
                req.queryParam(name, value);
            return this;
        }

        public Invocation<R> paramLists(Map<String, ? extends Iterable<? extends Object>> params) {
            if (params != null) {
                for (Map.Entry<String, ? extends Iterable<? extends Object>> pair : params.entrySet())
                    for (Object value : pair.getValue())
                        req.queryParam(pair.getKey(), value);
            }
            return this;
        }

        public Invocation<R> serviceType(ServiceType serviceType) {
            req.serviceType(serviceType);
            return this;
        }

        public Invocation<R> entity(ModelEntity entity) {
            req.entity(entity);
            return this;
        }

        public Invocation<R> entity(Payload<?> entity) {
            req.entity(entity);
            req.contentType(ClientConstants.CONTENT_TYPE_OCTECT_STREAM);
            return this;
        }

        public Invocation<R> contentType(String contentType) {
            req.contentType(contentType);
            return this;
        }

        public Invocation<R> json(String json) {
            req.json(json);
            return this;
        }

        public Invocation<R> headers(Map<String, ? extends Object> headers) {
            if (headers != null)
                req.headers(headers);
            return this;
        }

        public Invocation<R> header(String name, Object value) {
            req.header(name, value);
            return this;
        }

        public R execute() {
            return execute(null);
        }

        public R execute(ExecutionOptions<R> options) {
            header(HEADER_USER_AGENT, USER_AGENT);
            HttpRequest<R> request = req.build();
            HttpResponse res = HttpExecutor.create().execute(request);

            reqIdContainer.remove();

            String reqId = null;
            if(res.headers().containsKey(ClientConstants.X_COMPUTE_REQUEST_ID)) {
            	reqId = res.header(ClientConstants.X_COMPUTE_REQUEST_ID);
            } else {
            	reqId = res.header(ClientConstants.X_OPENSTACK_REQUEST_ID);
            }

            reqIdContainer.set(reqId);
            return res.getEntity(request.getReturnType(), options);
        }

        public HttpResponse executeWithResponse() {
            return HttpExecutor.create().execute(req.build());
        }

    }

    @SuppressWarnings("rawtypes")
    protected int getServiceVersion() {
        OSClientSession session = OSClientSession.getCurrent();
        if (session.getAuthVersion() == AuthVersion.V3) {
            SortedSet<? extends Service> services = ((OSClientSession.OSClientSessionV3) session).getToken().getAggregatedCatalog().get(serviceType.getType());
            Service service = ((OSClientSession.OSClientSessionV3) session).getToken().getAggregatedCatalog().get(serviceType.getType()).first();

            if (services.isEmpty()) {
                return 1;
            }

            return service.getVersion();

        } else {
            SortedSet<? extends Access.Service> services = ((OSClientSession.OSClientSessionV2) session).getAccess().getAggregatedCatalog().get(serviceType.getType());
            Access.Service service = ((OSClientSession.OSClientSessionV2) session).getAccess().getAggregatedCatalog().get(serviceType.getType()).first();

            if (services.isEmpty()) {
                return 1;
            }

            return service.getVersion();
        }

    }

    protected <T> List<T> toList(T[] arr) {
        if (arr == null)
            return Collections.emptyList();
        return Arrays.asList(arr);
    }

    protected CloudProvider getProvider() {
        return OSClientSession.getCurrent().getProvider();
    }
}


text:
import sbt._
import Keys._
import sbtassembly.Plugin._
import AssemblyKeys._
import sbtrelease.ReleasePlugin._
import com.typesafe.sbt.SbtScalariform._
import net.virtualvoid.sbt.graph.Plugin.graphSettings
import ohnosequences.sbt.SbtS3Resolver.S3Resolver
import ohnosequences.sbt.SbtS3Resolver.{ s3, s3resolver }
import org.scalastyle.sbt.ScalastylePlugin.{ Settings => styleSettings }
import scalariform.formatter.preferences._
import sbtbuildinfo.Plugin._
import spray.revolver.RevolverPlugin.Revolver.{settings => revolverSettings}

object MarathonBuild extends Build {
  lazy val root = Project(
    id = "marathon",
    base = file("."),
    settings = baseSettings ++
               asmSettings ++
               releaseSettings ++
               publishSettings ++
               formatSettings ++
               styleSettings ++
               revolverSettings ++
               graphSettings ++
      Seq(
        libraryDependencies ++= Dependencies.root,
        parallelExecution in Test := false,
        fork in Test := true
      )
    )
    .configs(IntegrationTest)
    .settings(inConfig(IntegrationTest)(Defaults.testTasks): _*)
    .settings(testOptions in Test := Seq(Tests.Argument("-l", "integration")))
    .settings(testOptions in IntegrationTest := Seq(Tests.Argument("-n", "integration")))

  lazy val testScalaStyle = taskKey[Unit]("testScalaStyle")

  lazy val IntegrationTest = config("integration") extend Test

  lazy val baseSettings = Defaults.defaultSettings ++ buildInfoSettings ++ Seq (
    organization := "mesosphere",
    scalaVersion := "2.11.5",
    scalacOptions in Compile ++= Seq(
      "-encoding", "UTF-8",
      "-target:jvm-1.6",
      "-deprecation",
      "-feature",
      "-unchecked",
      "-Xlog-reflective-calls",
      "-Xlint",
      "-Ywarn-unused-import",
      "-Xfatal-warnings",
      "-Yno-adapted-args",
      "-Ywarn-numeric-widen"
    ),
    javacOptions in Compile ++= Seq("-encoding", "UTF-8", "-source", "1.6", "-target", "1.6", "-Xlint:unchecked", "-Xlint:deprecation"),
    resolvers ++= Seq(
      "Mesosphere Public Repo"    at "http://downloads.mesosphere.io/maven",
      "Twitter Maven2 Repository" at "http://maven.twttr.com/",
      "Typesafe Releases" at "http://repo.typesafe.com/typesafe/releases/",
      "Spray Maven Repository"    at "http://repo.spray.io/"
    ),
    sourceGenerators in Compile <+= buildInfo,
    fork in Test := true,
    buildInfoKeys := Seq[BuildInfoKey](name, version, scalaVersion),
    buildInfoPackage := "mesosphere.marathon",
    testScalaStyle := {
      org.scalastyle.sbt.PluginKeys.scalastyle.toTask("").value
    },
    (test in Test) <<= (test in Test) dependsOn testScalaStyle
  )

  lazy val asmSettings = assemblySettings ++ Seq(
    mergeStrategy in assembly <<= (mergeStrategy in assembly) { old =>
      {
        case "application.conf"                                             => MergeStrategy.concat
        case "META-INF/jersey-module-version"                               => MergeStrategy.first
        case "log4j.properties"                                             => MergeStrategy.concat
        case "org/apache/hadoop/yarn/util/package-info.class"               => MergeStrategy.first
        case "org/apache/hadoop/yarn/factories/package-info.class"          => MergeStrategy.first
        case "org/apache/hadoop/yarn/factory/providers/package-info.class"  => MergeStrategy.first
        case x                                                              => old(x)
      }
    },
    excludedJars in assembly <<= (fullClasspath in assembly) map { cp =>
      val exclude = Set(
        "commons-beanutils-1.7.0.jar",
        "stax-api-1.0.1.jar",
        "commons-beanutils-core-1.8.0.jar",
        "servlet-api-2.5.jar",
        "jsp-api-2.1.jar"
      )
      cp filter { x => exclude(x.data.getName) }
    }
  )

  lazy val publishSettings = S3Resolver.defaults ++ Seq(
    publishTo := Some(s3resolver.value(
      "Mesosphere Public Repo (S3)",
      s3("downloads.mesosphere.com/maven")
    ))
  )

  lazy val formatSettings = scalariformSettings ++ Seq(
    ScalariformKeys.preferences := FormattingPreferences()
      .setPreference(IndentWithTabs, false)
      .setPreference(IndentSpaces, 2)
      .setPreference(AlignParameters, true)
      .setPreference(DoubleIndentClassDeclaration, true)
      .setPreference(MultilineScaladocCommentsStartOnFirstLine, false)
      .setPreference(PlaceScaladocAsterisksBeneathSecondAsterisk, true)
      .setPreference(PreserveDanglingCloseParenthesis, true)
      .setPreference(CompactControlReadability, true) //MV: should be false!
      .setPreference(AlignSingleLineCaseStatements, true)
      .setPreference(PreserveSpaceBeforeArguments, true)
      .setPreference(SpaceBeforeColon, false)
      .setPreference(SpaceInsideBrackets, false)
      .setPreference(SpaceInsideParentheses, false)
      .setPreference(SpacesWithinPatternBinders, true)
      .setPreference(FormatXml, true)
    )
}

object Dependencies {
  import Dependency._

  val root = Seq(
    // runtime
    akkaActor % "compile",
    akkaSlf4j % "compile",
    sprayClient % "compile",
    sprayHttpx % "compile",
    chaos % "compile",
    mesosUtils % "compile",
    jacksonCaseClass % "compile",
    twitterCommons % "compile",
    twitterZkClient % "compile",
    jodaTime % "compile",
    jodaConvert % "compile",
    jerseyServlet % "compile",
    jerseyMultiPart % "compile",
    uuidGenerator % "compile",
    jGraphT % "compile",
    hadoopHdfs % "compile",
    hadoopCommon % "compile",
    beanUtils % "compile",
    scallop % "compile",
    playJson % "compile",

    // test
    Test.scalatest % "test",
    Test.mockito % "test",
    Test.akkaTestKit % "test"
  )
}

object Dependency {
  object V {
    // runtime deps versions
    val Chaos = "0.6.1"
    val JacksonCCM = "0.1.2"
    val MesosUtils = "0.21.0-1"
    val Akka = "2.3.9"
    val Spray = "1.3.2"
    val TwitterCommons = "0.0.76"
    val TwitterZKClient = "0.0.70"
    val Jersey = "1.18.1"
    val JodaTime = "2.3"
    val JodaConvert = "1.6"
    val UUIDGenerator = "3.1.3"
    val JGraphT = "0.9.1"
    val Hadoop = "2.4.1"
    val Scallop = "0.9.5"
    val PlayJson = "2.3.7"

    // test deps versions
    val Mockito = "1.9.5"
    val ScalaTest = "2.1.7"
  }

  val excludeMortbayJetty = ExclusionRule(organization = "org.mortbay.jetty")
  val excludeJavaxServlet = ExclusionRule(organization = "javax.servlet")

  val akkaActor = "com.typesafe.akka" %% "akka-actor" % V.Akka
  val akkaSlf4j = "com.typesafe.akka" %% "akka-slf4j" % V.Akka
  val sprayClient = "io.spray" %% "spray-client" % V.Spray
  val sprayHttpx = "io.spray" %% "spray-httpx" % V.Spray
  val playJson = "com.typesafe.play" %% "play-json" % V.PlayJson
  val chaos = "mesosphere" %% "chaos" % V.Chaos
  val mesosUtils = "mesosphere" %% "mesos-utils" % V.MesosUtils
  val jacksonCaseClass = "mesosphere" %% "jackson-case-class-module" % V.JacksonCCM
  val jerseyServlet =  "com.sun.jersey" % "jersey-servlet" % V.Jersey
  val jerseyMultiPart =  "com.sun.jersey.contribs" % "jersey-multipart" % V.Jersey
  val jodaTime = "joda-time" % "joda-time" % V.JodaTime
  val jodaConvert = "org.joda" % "joda-convert" % V.JodaConvert
  val twitterCommons = "com.twitter.common.zookeeper" % "candidate" % V.TwitterCommons
  val twitterZkClient = "com.twitter.common.zookeeper" % "client" % V.TwitterZKClient
  val uuidGenerator = "com.fasterxml.uuid" % "java-uuid-generator" % V.UUIDGenerator
  val jGraphT = "org.javabits.jgrapht" % "jgrapht-core" % V.JGraphT
  val hadoopHdfs = "org.apache.hadoop" % "hadoop-hdfs" % V.Hadoop excludeAll(excludeMortbayJetty, excludeJavaxServlet)
  val hadoopCommon = "org.apache.hadoop" % "hadoop-common" % V.Hadoop excludeAll(excludeMortbayJetty, excludeJavaxServlet)
  val beanUtils = "commons-beanutils" % "commons-beanutils" % "1.9.2"
  val scallop = "org.rogach" %% "scallop" % V.Scallop

  object Test {
    val scalatest = "org.scalatest" %% "scalatest" % V.ScalaTest
    val mockito = "org.mockito" % "mockito-all" % V.Mockito
    val akkaTestKit = "com.typesafe.akka" %% "akka-testkit" % V.Akka
  }
}


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Composition;
using Microsoft.CodeAnalysis.Host.Mef;

namespace Microsoft.CodeAnalysis.Host
{
    [ExportWorkspaceServiceFactory(typeof(IFrameworkAssemblyPathResolver), ServiceLayer.Default), Shared]
    internal sealed class FrameworkAssemblyPathResolverFactory : IWorkspaceServiceFactory
    {
        [ImportingConstructor]
        public FrameworkAssemblyPathResolverFactory()
        {
        }

        public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
        {
            return new Service();
        }

        private sealed class Service : IFrameworkAssemblyPathResolver
        {
            public Service()
            {
            }

            //public bool CanResolveType(ProjectId projectId, string assemblyName, string fullyQualifiedTypeName)
            //{
            //    return false;
            //}

            public string ResolveAssemblyPath(ProjectId projectId, string assemblyName, string fullyQualifiedTypeName = null)
            {
                // Assembly path resolution not supported at the default workspace level.
                return null;
            }
        }
    }
}


text:
package com.ZombieRun.game;

import java.util.List;

import org.newdawn.slick.BasicGame;
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;

import com.ZombieRun.audio.Audio;
import com.ZombieRun.audio.AudioContainer;
import com.ZombieRun.audio.AudioContainer.AudioName;
import com.ZombieRun.client.GameClient;
import com.ZombieRun.constants.Static;
import com.ZombieRun.game.settings.UserSettings;
import com.ZombieRun.gameplay.model.Camera;
import com.ZombieRun.gameplay.model.Map;
import com.ZombieRun.input.InputContainer;
import com.ZombieRun.interactive.screen.ScreenController;
import com.ZombieRun.load.Loader;
import com.ZombieRun.logger.Log;
import com.ZombieRun.render.Rain;
import com.ZombieRun.render.Render;
import com.ZombieRun.render.Thunder;
import com.ZombieRun.serialized.Player;
import com.ZombieRun.shared.message.ConnectMessage;
import com.ZombieRun.shared.message.JoinGameMessage;
import com.ZombieRun.shared.message.PlayerInfectedMessage;
import com.ZombieRun.shared.message.PlayerJoinedMessage;
import com.ZombieRun.shared.message.PlayerLeftMessage;
import com.ZombieRun.shared.message.UpdatePlayerMovementMessage;

public class Game extends BasicGame {

	private GameClient client;

	private static InputContainer ic;
	private static Render render;
	private static boolean renderFlag;
	private static boolean debug;
	private static Status status;
	private static long time;

	private static Rain rain;
	private static Thunder thunder;

	private static Map map;
	private static Player player;
	private static int players = 0;
	private static int zombies = 0;
	private static int min = 2;
	private static boolean gameReady = false;

	private static long rrTime = 0;
	//private ArrayList<com.ZombieRun.shared.model.Player> players2 = new ArrayList<com.ZombieRun.shared.model.Player>();

	private Camera camera;

	private boolean isPlaying = false;

	public enum Status {
		RUNNING, PAUSED, CLOSE;
	}

	public Game(String title) {
		super(title);
	}

	public void init(GameContainer gc) throws SlickException {
		try {
			Loader.loadCharacters();
			Loader.loadAudio();
			Loader.loadScreens(gc);

			//ScreenController.switchTo("Main");
			ScreenController.switchTo("Login");
			Audio.setTracksOn(true);
			Audio.setSoundsOn(true);
			AudioContainer.setTrackDefaultVolumen(1.0f);
			AudioContainer.setSoundDefaultVolumen(1.0f);
			Audio.loop(AudioContainer.getTracks().get(AudioName.TRACK01));

			ic = new InputContainer(this, gc.getInput());
			render = new Render();
			renderFlag = true;
			debug = false;
			status = Status.RUNNING;
			rain = new Rain(gc.getWidth());
			thunder = new Thunder();
			player = new Player("type", "unknown", "Red", 50, 50);
			map = new Map(player);

			client = new GameClient("localhost", 8121).run();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void pollMessages() {
		for (int i = 0; i < GameClient.getMessages().size(); i++) {
			Object msg = GameClient.getMessages().poll();
			if (msg instanceof List) {
				map.setObstacles(msg);
			} else if (msg instanceof ConnectMessage) {
				ConnectMessage m = (ConnectMessage) msg;
				System.out.println("ConnectMessage: " + m.getUsername());
			} else if (msg instanceof PlayerJoinedMessage) {
				PlayerJoinedMessage m = (PlayerJoinedMessage) msg;
				map.insertOnlinePlayer(m.getPlayer());
				GameClient.write(new UpdatePlayerMovementMessage(player.getPlayer()));
				System.out.println("PlayerJoinedMessage: " + m.getPlayer().getUsername());
				players++;
				System.out.println(players);
				if (players == min) {
					gameReady = true;
				} else if (players < min) {
					gameReady = false;
				}

			} else if (msg instanceof UpdatePlayerMovementMessage) {
				UpdatePlayerMovementMessage m = (UpdatePlayerMovementMessage) msg;
				map.updatePlayer(m.getPlayer());
				//System.out.println("UpdatePlayerMovementMessage: " + m.getPlayer().getUsername());
			} else if (msg instanceof PlayerLeftMessage) {
				PlayerLeftMessage m = (PlayerLeftMessage) msg;
				map.removePlayerByUsername(m.getUsername());
				System.out.println("PlayerLeftMessage: " + m.getUsername());
				players--;
			} else if (msg instanceof PlayerInfectedMessage) {
				PlayerInfectedMessage m = (PlayerInfectedMessage) msg;
				map.infectPlayer(m.getUsername());
				System.out.println("UpdatePlayerMovementMessage: " + m.getUsername());
			}
		}
	}

	public void update(GameContainer gc, int delta) throws SlickException {
		if (status == Status.RUNNING) {
			zombies = 0;
			players = 1;
			for (com.ZombieRun.shared.model.Player p : map.getOnlinePlayers()) {
				players++;
				if (p.getCharacterModelName().equals("Zombie")) {
					zombies++;
				}
			}
			if (player.getPlayer().getCharacterModelName().equals("Zombie"))
				zombies++;

			//System.out.println("PLAYERS: " + zombies);
			time++;
			pollMessages();
			if (!ScreenController.getCurrentScreen().getName().equals("Game")) {
				isPlaying = false;
				rain.update(gc);
			}
			rain.update(gc);
			thunder.update(gc);
			if (ScreenController.getCurrentScreen().getName().equals("Game")) {
				if (!isPlaying) {
					player.setUsername(UserSettings.getUsername());
					player.getPlayer().setUsername(UserSettings.getUsername());
					player.getPlayer().setCharacterModelName(UserSettings.getCharacter());
					player.setCharacter(UserSettings.getCharacter());
					GameClient.write(new JoinGameMessage(UserSettings.getUsername(), player.getPlayer()));
				}
				isPlaying = true;
				map.update(gc);
				/*
								if (players - zombies == 0 && zombies > 1) {
									if (rrTime == 0)
										rrTime = System.currentTimeMillis();
									if (System.currentTimeMillis() - rrTime > 5000) {
										try {
											rrTime = 0;
											ScreenController.switchTo("Main");
											GameClient.write(new PlayerLeftMessage(UserSettings.getUsername()));
										} catch (Exception e) {
											e.printStackTrace();
										}
									}
								}*/

			}
		}

		if (status == Status.PAUSED) {

		}
	}

	public void render(GameContainer gc, Graphics g) throws SlickException {
		if (renderFlag) {
			render.setDefaultConfiguration(gc, g);
			Log.log4("Default render configuration loaded.");
			renderFlag = false;
		}

		render.drawBackground(gc, g, gc.getWidth(), gc.getHeight(), Color.darkGray);

		if (!ScreenController.getCurrentScreen().getName().equals("Game")) {
			rain.render(gc, g);
		}
		ScreenController.render(gc, g);
		if (ScreenController.getCurrentScreen().getName().equals("Game")) {
			g.fillRect(0, 0, Static.Screen.WIDTH, Static.Screen.HEIGHT);
			g.setColor(new Color(.4f, .3f, .4f));
			thunder.render(gc, g);
			map.render(gc, g);
			render.drawGameInfo(gc, g, new Object[] { (players - zombies), zombies });
			//render.drawStatus(gc, g, new Object[] { gameReady, (min - players) });

			if (players - zombies == 0 && zombies > 1) {
				render.drawFinnish(gc, g);
			}
		}

		rain.render(gc, g);

		if (debug) {
			render.drawInfo(gc, g, new Object[] { players, ScreenController.getCurrentScreen().getName(),
					Audio.getTrackVolume(AudioContainer.getTracks().get(AudioName.TRACK01)) * 100 });
		}
	}

	private boolean isGameReady() {
		return gameReady;
	}

	private void setGameReady(boolean ready) {
		gameReady = ready;
	}

	public void debug() {
		debug = !debug;
		if (debug) {
			Log.setLevel(6);
			Log.log4(String.format("Debug mode: %s", "on"));
		} else {
			Log.log4(String.format("Debug mode: %s", "off"));
			Log.setLevel(0);
		}
	}

	public void pause() {
		if (status == Status.RUNNING) {
			status = Status.PAUSED;
			// Audio.pause(AudioContainer.getTracks().);
		} else {
			status = Status.RUNNING;
		}
		Log.log4(String.format("Game status: %s", status));
	}

	public boolean getDebug() {
		return debug;
	}

	public Status getStatus() {
		return status;
	}

	public static Player getPlayer() {
		return player;
	}
}