text:
import unittest

from aiorest_ws.auth.exceptions import PermissionDeniedException
from aiorest_ws.auth.permissions import AbstractPermission, IsAuthenticated
from aiorest_ws.auth.token.exceptions import TokenNotProvidedException
from aiorest_ws.auth.token.middlewares import BaseTokenMiddleware, \
    JSONWebTokenMiddleware
from aiorest_ws.auth.user.abstractions import User
from aiorest_ws.conf import settings
from aiorest_ws.views import MethodBasedView
from aiorest_ws.wrappers import Request
from aiorest_ws.utils.modify import add_property

from tests.fixtures.fakes import FakeGetView
from tests.fixtures.example_settings import DATABASES

class BaseTokenMiddlewareTestCase(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.middleware = BaseTokenMiddleware()

    def test_init_credentials(self):
        request = Request()
        self.assertIsNone(self.middleware.init_credentials(request))

    def test_authenticate(self):
        request = Request()
        handler = FakeGetView()
        self.assertIsNone(self.middleware.authenticate(request, handler))

    def test_process_request(self):
        request = Request()
        handler = FakeGetView()
        self.assertIsNone(self.middleware.process_request(request, handler))

class JSONWebTokenMiddlewareTestCase(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        settings.DATABASES = DATABASES
        settings._create_database_managers()
        cls.middleware = JSONWebTokenMiddleware()

    def _create_simple_user(self, user_model, **kwargs):
        username = kwargs.get('username', None) or 'testuser'
        user_data = {
            'username': username,
            'password': kwargs.get('password', None) or '123456',
            'first_name': kwargs.get('first_name', None) or 'test',
            'last_name': kwargs.get('last_name', None) or 'user',
            'is_active': kwargs.get('is_active', None) or True,
            'is_superuser': kwargs.get('is_superuser', None) or False,
            'is_staff': kwargs.get('is_staff', None) or False,
            'is_user': kwargs.get('is_user', None) or True,
        }
        user_model.create_user(**user_data)
        user = user_model.get_user_by_username(username, with_id=True)
        return user

    def test_get_user_by_token(self):
        user = self._create_simple_user(self.middleware.user_model)
        token_data = {
            'name': 'api',
            'token': 'my_test_token',
            'user_id': user.id
        }
        self.middleware.storage_backend.save(
            token_data['name'],
            token_data['token'],
            user_id=token_data['user_id']
        )
        user = self.middleware.get_user_by_token(token_data['token'])
        self.assertIsInstance(user, User)
        self.assertTrue(user.is_user)

    def test_get_anonymous_user_by_not_existed_token(self):
        user = self.middleware.get_user_by_token('unknown')
        self.assertIsInstance(user, User)
        self.assertTrue(user.is_anonymous)

    def test_init_credentials(self):
        user = self._create_simple_user(self.middleware.user_model)
        token_data = {'key': 'value'}
        raw_token = self.middleware.manager.generate(token_data)
        init_data = {
            'name': 'api',
            'token': raw_token,
            'user_id': user.id
        }
        self.middleware.storage_backend.save(
            init_data['name'],
            init_data['token'],
            user_id=init_data['user_id']
        )

        request = Request()
        add_property(request, 'token', raw_token)
        self.middleware.init_credentials(request)
        self.assertIsInstance(request.user, User)
        self.assertTrue(request.user.is_user)
        self.assertIsNotNone(request.token_payload)

    def test_init_credentials_without_token(self):
        request = Request()
        self.middleware.init_credentials(request)
        self.assertIsInstance(request.user, User)
        self.assertTrue(request.user.is_anonymous)
        self.assertIsNone(request.token_payload)

    def test_authenticate(self):
        class TestView(MethodBasedView):
            auth_required = True

        user = User(is_user=True)
        token_data = {'key': 'value'}
        raw_token = self.middleware.manager.generate(token_data)

        request = Request()
        add_property(request, 'user', user)
        add_property(request, 'token', raw_token)
        view = TestView()
        self.assertIsNone(self.middleware.authenticate(request, view))

    def test_authenticate_with_permissions(self):
        class ViewWithIsAuthenticatedPermission(MethodBasedView):
            auth_required = True
            permission_classes = (IsAuthenticated, )

        user = User(is_user=True)
        token_data = {'key': 'value'}
        raw_token = self.middleware.manager.generate(token_data)

        request = Request()
        add_property(request, 'user', user)
        add_property(request, 'token', raw_token)
        view = ViewWithIsAuthenticatedPermission()
        self.assertIsNone(self.middleware.authenticate(request, view))

    def test_authenticate_with_permissions_and_raise_exception(self):
        class CustomPermission(AbstractPermission):
            @staticmethod
            def check(request, handler):
                raise PermissionDeniedException

        class ViewWithPermissions(MethodBasedView):
            auth_required = True
            permission_classes = (CustomPermission, )

        user = User(is_user=True)
        token_data = {'key': 'value'}
        raw_token = self.middleware.manager.generate(token_data)

        request = Request()
        add_property(request, 'user', user)
        add_property(request, 'token', raw_token)
        view = ViewWithPermissions()
        self.assertRaises(
            PermissionDeniedException,
            self.middleware.authenticate, request, view
        )

    def test_authenticate_for_view_without_auth_required_pass(self):
        class TestView(MethodBasedView):
            pass

        request = Request()
        view = TestView()
        self.assertIsNone(self.middleware.authenticate(request, view))

    def test_raised_token_not_provided_exception_in_authenticate(self):
        class ViewWithTokenCheck(MethodBasedView):
            auth_required = True

        request = Request()
        view = ViewWithTokenCheck()
        self.assertRaises(
            TokenNotProvidedException,
            self.middleware.authenticate, request, view
        )


text:
/*  NOTE: This file is automatically generated from several different
    script components via a build process utilizing `make' and `m4'.

    TODO: Stop using `make' and `m4'. It's seems like its more trouble
    than it's worth, and I don't think most people will care about having
    different versions (with different parsers).
*/

(function (window)
{
    //:m4_include(`nabtext.core.js')

    Gettext.prototype.initAliases = function (context)
    {
        // TODO - This blows away any existing top-level functions with these
        // names. We should store any originals, and provide a `noconflict()'
        // method (a la jQuery) for restoring them.

        // TODO - There's got to be a better way to wrap the functions to
        // work in the proper scope.
        function amap (args) { return Array.prototype.slice.call(args); }

        var gt = this;

        context.sprintf     = function () { return gt.sprintf.apply(gt, amap(arguments)); };
        context.gettext     = function () { return gt.gettext.apply(gt, amap(arguments)); };
        context.ngettext    = function () { return gt.ngettext.apply(gt, amap(arguments)); };
        context.dgettext    = function () { return gt.dgettext.apply(gt, amap(arguments)); };
        context.dcgettext   = function () { return gt.dcgettext.apply(gt, amap(arguments)); };
        context.dngettext   = function () { return gt.dngettext.apply(gt, amap(arguments)); };
        context.dcngettext  = function () { return gt.dcngettext.apply(gt, amap(arguments)); };
        context.pgettext    = function () { return gt.pgettext.apply(gt, amap(arguments)); };
        context.dpgettext   = function () { return gt.dpgettext.apply(gt, amap(arguments)); };
        context.dcpgettext  = function () { return gt.dcpgettext.apply(gt, amap(arguments)); };
        context.npgettext   = function () { return gt.npgettext.apply(gt, amap(arguments)); };
        context.dnpgettext  = function () { return gt.dnpgettext.apply(gt, amap(arguments)); };
        context.dcnpgettext = function () { return gt.dcnpgettext.apply(gt, amap(arguments)); };

        // Convenience aliases.
        context.Gettext = gt;
        context._       = context.gettext;
    };

    // Initializes a global Gettext object using any files specified in
    // <link> tags.
    (function ()
    {
        // Sets up the global Gettext object, and global aliases to the
        // Gettext API.
        var gt = new Gettext();

        gt.initAliases(window);

        // Gets all gettext link tags and loads the specified resources.
        var links = document.getElementsByTagName("LINK");

        for (var i = 0; i < links.length; ++i) {
            var link = links[i];

            if ("gettext" == link.getAttribute("rel")) {
                gt.load({
                    url      : link.getAttribute("href"),
                    mimeType : link.getAttribute("type"),
                    locale   : link.getAttribute("hreflang")
                });
            }
        }
    })();

})(window);

redpajama_set_name: RedPajamaGithub


text:
title: Touch Hold Directive
desc: Vue directive which triggers an event when the user touches and holds on a component or element for a specified amount of time.
related:
  - /vue-directives/touch-pan
  - /vue-directives/touch-swipe
---
Quasar offers full-featured Vue directives that can totally replace libraries like Hammerjs: `v-touch-pan`, `v-touch-swipe`, `v-touch-hold` and even `v-touch-repeat`.

> **These directives also work with mouse events, not only touch events**, so you are able to build cool functionality for your App on desktops too.

We will be describing `v-touch-hold` directive on the lines below.

## Installation
<doc-installation directives="TouchHold" />

## Usage
<doc-example title="Basic" file="TouchHold/Basic" />

The default wait time is 600ms, but you can change it:

<doc-example title="Custom wait time" file="TouchHold/CustomTimer" />

::: tip
TouchHold also has a default sensitivity of 5px for touch events and 7px for mouse events, which means that it allows a slight movement of the finger or mouse without aborting, improving the user experience.
:::

However, you can change this sensitivity too (notice the directive argument below - `600:12:15` - 600ms wait time, 12px sensitivity for touch events, 15px sensitivity for mouse events):

<doc-example title="Custom sensitivity" file="TouchHold/CustomSensitivity" />

### Handling Mouse Events
When you want to also handle mouse events too, use the `mouse` modifier:

``` html
<div v-touch-hold.mouse="userHasHold">...</div>
```

### Inhibiting TouchHold
When you want to inhibit TouchHold, you can do so by stopping propagation of the `touchstart`/`mousedown` events from the inner content:

``` html
<div v-touch-hold.mouse="userHasHold">
  <!-- ...content -->
  <div @touchstart.stop @mousedown.stop>
    <!--
      TouchHold will not apply here because
      we are calling stopPropagation() on touchstart
      and mousedown events
    -->
  </div>
  <!-- ...content -->
</div>
```

However, if you are using `capture` or `mouseCapture` modifiers then events will first reach the TouchHold directive then the inner content, so TouchHold will still trigger.

## Note on HMR
Due to performance reasons, not all of the modifiers are reactive. Some require a window/page/component refresh to get updated. Please check the API card for the modifiers which are not marked as reactive.

## TouchHold API
<doc-api file="TouchHold" />


text:
import { translate } from '@waldur/i18n';
import { activateBackupSchedule } from '@waldur/openstack/api';
import { AsyncActionItem } from '@waldur/resource/actions/AsyncActionItem';

const validators = [
  ({ resource }) => {
    if (resource.is_active) {
      return translate('Resource schedule is already activated.');
    }
  },
];

export const ActivateAction = ({ resource }) => (
  <AsyncActionItem
    title={translate('Activate')}
    apiMethod={activateBackupSchedule}
    resource={resource}
    validators={validators}
  />
);


text:
#include <jni.h>

/*
 * Method: org.apache.harmony.vts.test.vm.jni.string_operations.GetReleaseStringCriticalTest.nativeExecute(Ljava/lang/String;)[C
 */
JNIEXPORT jcharArray JNICALL
Java_org_apache_harmony_vts_test_vm_jni_string_1operations_GetReleaseStringCriticalTest_nativeExecute
    (JNIEnv *env, jobject this_object, jstring str)
{
    jcharArray result;
    jchar *elements;
    const jchar *telements;
    jsize length;
    int iii;

    length = (*env)->GetStringLength(env, str);
    result = (*env)->NewCharArray(env, length);
    if (NULL == result)
        return NULL;

    elements = (*env)->GetCharArrayElements(env, result, NULL);
    if (NULL == elements)
        return NULL;

    telements = (*env)->GetStringCritical(env, str, NULL);
    if (NULL == telements)
        return NULL;

    for (iii = 0; iii < length; iii++)
        elements[iii] = telements[iii];

    (*env)->ReleaseStringCritical(env, str, telements);
    (*env)->ReleaseCharArrayElements(env, result, elements, 0);

    return result;
}


text:
import Ember from 'ember';
import { module, test } from 'qunit';
import startApp from '../../tests/helpers/start-app';

var application;

module('Acceptance | Basic smoke test', {
  beforeEach: function() {
    application = startApp();
  },

  afterEach: function() {
    Ember.run(application, 'destroy');
  }
});

test('render ok', function(assert) {
  visit('/');

  andThen(function() {
    assert.ok(Ember.$('body').text().indexOf('ember-ika-components'));
  });
});


text:
Reports enhanced switch statements and expressions. Suggests replacing them with regular switch
statements.

Example:

  boolean even = switch (condition) {
    case 1, 3, 5, 7, 9 -> false;
    default -> true;
  };

After the quick-fix is applied:

  boolean even;
  switch (condition) {
    case 1:
    case 3:
    case 5:
    case 7:
    case 9:
      even = false;
      break;
    default:
      even = true;
      break;
}

  Enhanced switch appeared in Java 14.
  This inspection can help to downgrade for backward compatibility with earlier Java versions.

New in 2019.1


text:
import beaglebone_pru_adc as adc
import time

numsamples = 10000 # how many samples to capture

capture = adc.Capture()

capture.oscilloscope_init(adc.OFF_VALUES, numsamples) # captures AIN0 - the first elt in AIN array
#capture.oscilloscope_init(adc.OFF_VALUES+8, numsamples) # captures AIN2 - the third elt in AIN array
capture.start()

for _ in range(10):
    if capture.oscilloscope_is_complete():
        break
    print '.'
    time.sleep(0.1)

capture.stop()
capture.wait()

print 'Saving oscilloscope values to "data.csv"'

with open('data.csv', 'w') as f:
    for x in capture.oscilloscope_data(numsamples):
        f.write(str(x) + '\n')

print 'done'

capture.close()


text:
SakurraForm::Plans = Chamber.load files: ['plan/network.yml', 'plan/server.yml']
ENV['FOG_RC'] = '.sakuracloud/credentials'


text:
<?php

namespace Genesis\API\Traits\Request\Financial;

/**
 * Trait PaymentAttributes
 *
 * Trait for all AmountBased Financial Requests
 *
 * @package Genesis\API\Traits\Request\Financial
 *
 * @method $this setAmount($value) Set the amount of transaction in minor currency unit
 * @method $this setCurrency($value) Set the currency code in ISO-4217
 */
trait PaymentAttributes
{
    /**
     * Amount of transaction in minor currency unit
     *
     * @var int|float|double
     */
    protected $amount;

    /**
     * Currency code in ISO-4217
     *
     * @var string
     */
    protected $currency;

    protected function getPaymentAttributesStructure()
    {
        return [
            'amount'   => $this->transformAmount($this->amount, $this->currency),
            'currency' => $this->currency
        ];
    }
}


text:
[![Greenkeeper badge](https://badges.greenkeeper.io/stefanwalther/extinfo.svg)](https://greenkeeper.io/)

> Small library to fetch meta data from Qlik Sense extensions.

## Install with [npm](npmjs.org)

```bash
npm i extinfo --save
```

## Usage

```js
var extinfo = require('extinfo');
```

<!--## API-->
<!-- add a path or glob pattern for files with code comments to use for docs  -->
<!---->

<!--## Related projects-->

<!-- add an array of related projects, then un-escape the helper -->
<!--[extloc](https://github.com/stefanwalther/extloc): Get the location where Qlik Sense Desktop loads extensions from.-->

## Running tests

Install dev dependencies:

```bash
npm i -d && npm test
```

## Contributing

Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/stefanwalther/extinfo/issues)

## Author

**Stefan Walther**

<!-- `github`, `github.username`, and `username` variables are undefined -->
<!-- `twitter`, `twitter.username`, and `username` variables are undefined -->

## License

Copyright (c) 2015 Stefan Walther
Released under the  license.

***

_This file was generated by [verb-cli](https://github.com/assemble/verb-cli) on May 03, 2015._


text:
var databaseUrl = "mongodb://admin:admin@ds033069.mongolab.com:33069/heroku_app22105721";

//var databaseUrl = "mongodb://localhost:27017/mydb"
var collections = ["tresfit", "arrgym"];
var db = require("mongojs").connect(databaseUrl, collections);
var items;

exports.markStationAsFinished = function(req, res) {
	var url = require('url');
	var url_parts = url.parse(req.url, true);
	var query = url_parts.query;
	var d = new Date();
	var n = d.getTime()/1000;
	var minutes;
	var seconds;
	if (query["gym"] === "tresfit") {
		db.tresfit.find({name:query["machine"]}).toArray(function(err, items){
			var oldtime = items[0].time;
			var changed = n-oldtime;
			minutes = Math.floor(changed/60);
			seconds = Math.floor(changed%60);
			db.tresfit.update({name:query["machine"]}, {$set:{occupied: 'Available', time:n}})
			res.render('station-finished', {'min': minutes, 'sec':seconds});
		});
	} else if (query["gym"] === "arrgym") {
		db.arrgym.find({name:query["machine"]}).toArray(function(err, items){
			var oldtime = items[0].time;
			var changed = n-oldtime;
			minutes = Math.floor(changed/60);
			seconds = Math.floor(changed%60);
			db.arrgym.update({name:query["machine"]}, {$set:{occupied: 'Available', time:n}})
			res.render('station-finished', {'min': minutes, 'sec':seconds});
		});
	}
}


text:
using System;
using FluentAssertions;
using InfluxDB.WriteOnly.Tests.Helpers;
using Xunit;

namespace InfluxDB.WriteOnly.Tests
{
    public class DateTimeExtensionsTests
    {
        [Theory]
        [EnumTheory(typeof(TimeUnitPrecision))]
        public void UnixEpochGivesUnixTimestampOfZero(TimeUnitPrecision precision)
        {
            var unixEpoch = 1.January(1970);

            var timestamp = unixEpoch.ToUnixTime(precision);

            timestamp.Should().Be(0);
        }

        [Theory]
        [InlineData(TimeUnitPrecision.Millisecond, 1501545600000)]
        [InlineData(TimeUnitPrecision.Second, 1501545600)]
        [InlineData(TimeUnitPrecision.Minute, 25025760)]
        [InlineData(TimeUnitPrecision.Hour, 417096)]
        public void FirstOfAugust2017NoonGivesCorrectUnixTimestamp(TimeUnitPrecision precision, long expectedTimestamp)
        {
            var dateTime = 1.August(2017);

            var timestamp = dateTime.ToUnixTime(precision);

            timestamp.Should().Be(expectedTimestamp);
        }
    }
}


text:
const should = require('should'),
    sinon = require('sinon'),
    rewire = require('rewire'),
    templates = rewire('../../../../../server/services/routing/helpers/templates'),
    themes = require('../../../../../server/services/themes'),
    sandbox = sinon.sandbox.create();

describe('templates', function () {
    let getActiveThemeStub, hasTemplateStub,
        _private = templates.__get__('_private');

    afterEach(function () {
        sandbox.restore();
    });

    describe('[private fn] getEntriesTemplateHierarchy', function () {
        it('should return just index for empty options', function () {
            _private.getEntriesTemplateHierarchy({}).should.eql(['index']);
        });

        it('should return just index if collection name is index', function () {
            _private.getEntriesTemplateHierarchy({name: 'index'}).should.eql(['index']);
        });

        it('should return custom templates even if the collection is index', function () {
            _private.getEntriesTemplateHierarchy({name: 'index', templates: ['something']}).should.eql(['something', 'index']);
        });

        it('should return collection name', function () {
            _private.getEntriesTemplateHierarchy({name: 'podcast'}).should.eql(['podcast', 'index']);
        });

        it('should return custom templates', function () {
            _private.getEntriesTemplateHierarchy({name: 'podcast', templates: ['mozart']}).should.eql(['mozart', 'podcast', 'index']);
        });

        it('should return just index if collection name is index even if slug is set', function () {
            _private.getEntriesTemplateHierarchy({name: 'index', slugTemplate: true}, {slugParam: 'test'}).should.eql(['index']);
        });

        it('should return collection, index if collection has name', function () {
            _private.getEntriesTemplateHierarchy({name: 'tag'}).should.eql(['tag', 'index']);
        });

        it('should return collection-slug, collection, index if collection has name & slug + slugTemplate set', function () {
            _private.getEntriesTemplateHierarchy({
                name: 'tag',
                slugTemplate: true
            }, {slugParam: 'test'}).should.eql(['tag-test', 'tag', 'index']);
        });

        it('should return front, collection-slug, collection, index if name, slugParam+slugTemplate & frontPageTemplate+pageParam=1 is set', function () {
            _private.getEntriesTemplateHierarchy({
                name: 'tag',
                slugTemplate: true,
                frontPageTemplate: 'front-tag'
            }, {page: 1, path: '/', slugParam: 'test'}).should.eql(['front-tag', 'tag-test', 'tag', 'index']);
        });

        it('should return home, index for index collection if front is set and pageParam = 1', function () {
            _private.getEntriesTemplateHierarchy({
                name: 'index',
                frontPageTemplate: 'home'
            }, {path: '/'}).should.eql(['home', 'index']);
        });

        it('should not use frontPageTemplate if not / collection', function () {
            _private.getEntriesTemplateHierarchy({
                name: 'index',
                frontPageTemplate: 'home'
            }, {path: '/magic/'}).should.eql(['index']);
        });
    });

    describe('[private fn] pickTemplate', function () {
        beforeEach(function () {
            hasTemplateStub = sandbox.stub().returns(false);

            getActiveThemeStub = sandbox.stub(themes, 'getActive').returns({
                hasTemplate: hasTemplateStub
            });
        });

        it('returns fallback if there is no active_theme', function () {
            getActiveThemeStub.returns(undefined);

            _private.pickTemplate(['tag-test', 'tag', 'index'], 'fallback').should.eql('fallback');
            _private.pickTemplate(['page-my-post', 'page', 'post'], 'fallback').should.eql('fallback');
        });

        it('returns fallback if active_theme has no templates', function () {
            _private.pickTemplate(['tag-test', 'tag', 'index'], 'fallback').should.eql('fallback');
            _private.pickTemplate(['page-about', 'page', 'post'], 'fallback').should.eql('fallback');
        });

        describe('with many templates', function () {
            beforeEach(function () {
                // Set available Templates
                hasTemplateStub.withArgs('default').returns(true);
                hasTemplateStub.withArgs('index').returns(true);
                hasTemplateStub.withArgs('page').returns(true);
                hasTemplateStub.withArgs('page-about').returns(true);
                hasTemplateStub.withArgs('post').returns(true);
                hasTemplateStub.withArgs('amp').returns(true);
            });

            it('returns first matching template', function () {
                _private.pickTemplate(['page-about', 'page', 'post'], 'fallback').should.eql('page-about');
                _private.pickTemplate(['page-magic', 'page', 'post'], 'fallback').should.eql('page');
                _private.pickTemplate(['page', 'post'], 'fallback').should.eql('page');
            });

            it('returns correctly if template list is a string', function () {
                _private.pickTemplate('amp', 'fallback').should.eql('amp');
                _private.pickTemplate('subscribe', 'fallback').should.eql('fallback');
                _private.pickTemplate('post', 'fallback').should.eql('post');
            });
        });
    });

    describe('[private fn] getTemplateForEntry', function () {
        beforeEach(function () {
            hasTemplateStub = sandbox.stub().returns(false);

            getActiveThemeStub = sandbox.stub(themes, 'getActive').returns({
                hasTemplate: hasTemplateStub
            });
        });

        it('will fall back to post even if no index.hbs', function () {
            hasTemplateStub.returns(false);

            var view = _private.getTemplateForEntry({page: 1});
            should.exist(view);
            view.should.eql('post');
        });

        describe('with many templates', function () {
            beforeEach(function () {
                // Set available Templates
                hasTemplateStub.withArgs('default').returns(true);
                hasTemplateStub.withArgs('index').returns(true);
                hasTemplateStub.withArgs('page').returns(true);
                hasTemplateStub.withArgs('page-about').returns(true);
                hasTemplateStub.withArgs('post').returns(true);
            });

            it('post without custom slug template', function () {
                var view = _private.getTemplateForEntry({
                    page: 0,
                    slug: 'test-post'
                });
                should.exist(view);
                view.should.eql('post');
            });

            it('post with custom slug template', function () {
                hasTemplateStub.withArgs('post-welcome-to-ghost').returns(true);
                var view = _private.getTemplateForEntry({
                    page: 0,
                    slug: 'welcome-to-ghost'
                });
                should.exist(view);
                view.should.eql('post-welcome-to-ghost');
            });

            it('page without custom slug template', function () {
                var view = _private.getTemplateForEntry({
                    page: 1,
                    slug: 'contact'
                });
                should.exist(view);
                view.should.eql('page');
            });

            it('page with custom slug template', function () {
                var view = _private.getTemplateForEntry({
                    page: 1,
                    slug: 'about'
                });
                should.exist(view);
                view.should.eql('page-about');
            });

            it('post with custom template', function () {
                hasTemplateStub.withArgs('custom-about').returns(true);

                var view = _private.getTemplateForEntry({
                    page: 0,
                    custom_template: 'custom-about'
                });
                should.exist(view);
                view.should.eql('custom-about');
            });

            it('page with custom template', function () {
                hasTemplateStub.withArgs('custom-about').returns(true);

                var view = _private.getTemplateForEntry({
                    page: 1,
                    custom_template: 'custom-about'
                });
                should.exist(view);
                view.should.eql('custom-about');
            });

            it('post with custom template configured, but the template is missing', function () {
                hasTemplateStub.withArgs('custom-about').returns(false);

                var view = _private.getTemplateForEntry({
                    page: 0,
                    custom_template: 'custom-about'
                });
                should.exist(view);
                view.should.eql('post');
            });

            it('page with custom template configured, but the template is missing', function () {
                hasTemplateStub.withArgs('custom-about').returns(false);

                var view = _private.getTemplateForEntry({
                    page: 1,
                    custom_template: 'custom-about'
                });
                should.exist(view);
                view.should.eql('page');
            });

            it('post with custom template configured, but slug template exists', function () {
                hasTemplateStub.withArgs('custom-about').returns(true);
                hasTemplateStub.withArgs('post-about').returns(true);

                var view = _private.getTemplateForEntry({
                    page: 0,
                    slug: 'about',
                    custom_template: 'custom-about'
                });
                should.exist(view);
                view.should.eql('post-about');
            });

            it('post with custom template configured, but slug template exists, but can\'t be found', function () {
                hasTemplateStub.withArgs('custom-about').returns(false);
                hasTemplateStub.withArgs('post-about').returns(false);

                var view = _private.getTemplateForEntry({
                    page: 0,
                    slug: 'about',
                    custom_template: 'custom-about'
                });
                should.exist(view);
                view.should.eql('post');
            });
        });
    });

    describe('[private fn] getTemplateForEntries', function () {
        beforeEach(function () {
            hasTemplateStub = sandbox.stub().returns(false);

            getActiveThemeStub = sandbox.stub(themes, 'getActive').returns({
                hasTemplate: hasTemplateStub
            });
        });

        describe('without tag templates', function () {
            beforeEach(function () {
                hasTemplateStub.withArgs('default').returns(true);
                hasTemplateStub.withArgs('index').returns(true);
            });

            it('will return correct view for a tag', function () {
                var view = _private.getTemplateForEntries({name: 'tag', slugTemplate: true}, {slugParam: 'development'});
                should.exist(view);
                view.should.eql('index');
            });
        });

        describe('with tag templates', function () {
            beforeEach(function () {
                hasTemplateStub.withArgs('default').returns(true);
                hasTemplateStub.withArgs('index').returns(true);
                hasTemplateStub.withArgs('tag').returns(true);
                hasTemplateStub.withArgs('tag-design').returns(true);
            });

            it('will return correct view for a tag', function () {
                var view = _private.getTemplateForEntries({name: 'tag', slugTemplate: true}, {slugParam: 'design'});
                should.exist(view);
                view.should.eql('tag-design');
            });

            it('will return correct view for a tag', function () {
                var view = _private.getTemplateForEntries({name: 'tag', slugTemplate: true}, {slugParam: 'development'});
                should.exist(view);
                view.should.eql('tag');
            });
        });

        it('will fall back to index even if no index.hbs', function () {
            var view = _private.getTemplateForEntries({name: 'tag', slugTemplate: true}, {slugParam: 'development'});
            should.exist(view);
            view.should.eql('index');
        });
    });

    describe('[private fn] getTemplateForError', function () {
        beforeEach(function () {
            hasTemplateStub = sandbox.stub().returns(false);

            getActiveThemeStub = sandbox.stub(themes, 'getActive').returns({
                hasTemplate: hasTemplateStub
            });
        });

        it('will fall back to default if there is no active_theme', function () {
            getActiveThemeStub.returns(undefined);

            _private.getTemplateForError(500).should.match(/core\/server\/views\/error.hbs$/);
        });

        it('will fall back to default for all statusCodes with no custom error templates', function () {
            _private.getTemplateForError(500).should.match(/core\/server\/views\/error.hbs$/);
            _private.getTemplateForError(503).should.match(/core\/server\/views\/error.hbs$/);
            _private.getTemplateForError(422).should.match(/core\/server\/views\/error.hbs$/);
            _private.getTemplateForError(404).should.match(/core\/server\/views\/error.hbs$/);
        });

        it('will use custom error.hbs for all statusCodes if there are no other templates', function () {
            hasTemplateStub.withArgs('error').returns(true);

            _private.getTemplateForError(500).should.eql('error');
            _private.getTemplateForError(503).should.eql('error');
            _private.getTemplateForError(422).should.eql('error');
            _private.getTemplateForError(404).should.eql('error');
        });

        it('will use more specific error-4xx.hbs for all 4xx statusCodes if available', function () {
            hasTemplateStub.withArgs('error').returns(true);
            hasTemplateStub.withArgs('error-4xx').returns(true);

            _private.getTemplateForError(500).should.eql('error');
            _private.getTemplateForError(503).should.eql('error');
            _private.getTemplateForError(422).should.eql('error-4xx');
            _private.getTemplateForError(404).should.eql('error-4xx');
        });

        it('will use explicit error-404.hbs for 404 statusCode if available', function () {
            hasTemplateStub.withArgs('error').returns(true);
            hasTemplateStub.withArgs('error-4xx').returns(true);
            hasTemplateStub.withArgs('error-404').returns(true);

            _private.getTemplateForError(500).should.eql('error');
            _private.getTemplateForError(503).should.eql('error');
            _private.getTemplateForError(422).should.eql('error-4xx');
            _private.getTemplateForError(404).should.eql('error-404');
        });

        it('cascade works the same for 500 errors', function () {
            hasTemplateStub.withArgs('error').returns(true);
            hasTemplateStub.withArgs('error-5xx').returns(true);
            hasTemplateStub.withArgs('error-503').returns(true);

            _private.getTemplateForError(500).should.eql('error-5xx');
            _private.getTemplateForError(503).should.eql('error-503');
            _private.getTemplateForError(422).should.eql('error');
            _private.getTemplateForError(404).should.eql('error');
        });

        it('cascade works with many specific templates', function () {
            hasTemplateStub.withArgs('error').returns(true);
            hasTemplateStub.withArgs('error-5xx').returns(true);
            hasTemplateStub.withArgs('error-503').returns(true);
            hasTemplateStub.withArgs('error-4xx').returns(true);
            hasTemplateStub.withArgs('error-404').returns(true);

            _private.getTemplateForError(500).should.eql('error-5xx');
            _private.getTemplateForError(503).should.eql('error-503');
            _private.getTemplateForError(422).should.eql('error-4xx');
            _private.getTemplateForError(404).should.eql('error-404');
            _private.getTemplateForError(401).should.eql('error-4xx');
            _private.getTemplateForError(501).should.eql('error-5xx');
        });
    });

    describe('fn: setTemplate', function () {
        var stubs = {}, req, res, data;

        beforeEach(function () {
            req = {};
            res = {
                locals: {}
            };
            data = {};

            stubs.pickTemplate = sandbox.stub(_private, 'pickTemplate').returns('testFromPickTemplate');
            stubs.getTemplateForEntry = sandbox.stub(_private, 'getTemplateForEntry').returns('testFromEntry');
            stubs.getTemplateForEntries = sandbox.stub(_private, 'getTemplateForEntries').returns('testFromEntries');
            stubs.getTemplateForError = sandbox.stub(_private, 'getTemplateForError').returns('testFromError');
        });

        it('does nothing if template is already set', function () {
            // Pre-set template
            res._template = 'thing';

            // Call setTemplate
            templates.setTemplate(req, res, data);

            // It hasn't changed
            res._template.should.eql('thing');

            // And nothing got called
            stubs.pickTemplate.called.should.be.false();
            stubs.getTemplateForEntry.called.should.be.false();
            stubs.getTemplateForEntries.called.should.be.false();
            stubs.getTemplateForError.called.should.be.false();
        });

        it('defaults to index', function () {
            // No route or template config here!!!

            // Call setTemplate
            templates.setTemplate(req, res, data);

            // It should be index
            res._template.should.eql('index');

            // And nothing got called
            stubs.pickTemplate.called.should.be.false();
            stubs.getTemplateForEntry.called.should.be.false();
            stubs.getTemplateForEntries.called.should.be.false();
            stubs.getTemplateForError.called.should.be.false();
        });

        it('calls pickTemplate for custom routes', function () {
            res._route = {
                type: 'custom',
                templates: 'test',
                defaultTemplate: 'path/to/local/test.hbs'
            };

            // Call setTemplate
            templates.setTemplate(req, res, data);

            // should be testFromPickTemplate
            res._template.should.eql('testFromPickTemplate');

            // Only pickTemplate got called
            stubs.pickTemplate.called.should.be.true();
            stubs.getTemplateForEntry.called.should.be.false();
            stubs.getTemplateForEntries.called.should.be.false();
            stubs.getTemplateForError.called.should.be.false();

            stubs.pickTemplate.calledWith('test', 'path/to/local/test.hbs').should.be.true();
        });

        it('calls pickTemplate for custom routes', function () {
            res._route = {
                type: 'custom',
                templates: 'test',
                defaultTemplate: 'path/to/local/test.hbs'
            };

            // Call setTemplate
            templates.setTemplate(req, res, data);

            // should be testFromPickTemplate
            res._template.should.eql('testFromPickTemplate');

            // Only pickTemplate got called
            stubs.pickTemplate.called.should.be.true();
            stubs.getTemplateForEntry.called.should.be.false();
            stubs.getTemplateForEntries.called.should.be.false();
            stubs.getTemplateForError.called.should.be.false();

            stubs.pickTemplate.calledWith('test', 'path/to/local/test.hbs').should.be.true();
        });

        it('calls getTemplateForEntry for entry routes', function () {
            res._route = {
                type: 'entry'
            };

            // Requires a post to be set
            data = {post: {slug: 'test'}};

            // Call setTemplate
            templates.setTemplate(req, res, data);

            // should be getTemplateForEntry
            res._template.should.eql('testFromEntry');

            // Only pickTemplate got called
            stubs.pickTemplate.called.should.be.false();
            stubs.getTemplateForEntry.called.should.be.true();
            stubs.getTemplateForEntries.called.should.be.false();
            stubs.getTemplateForError.called.should.be.false();

            stubs.getTemplateForEntry.calledWith({slug: 'test'}).should.be.true();
        });

        it('calls getTemplateForEntries for type collection', function () {
            req.url = '/';
            req.params = {};

            res._route = {
                type: 'collection'
            };

            res.locals.routerOptions = {testCollection: 'test'};

            // Call setTemplate
            templates.setTemplate(req, res, data);

            res._template.should.eql('testFromEntries');

            // Only pickTemplate got called
            stubs.pickTemplate.called.should.be.false();
            stubs.getTemplateForEntry.called.should.be.false();
            stubs.getTemplateForEntries.called.should.be.true();
            stubs.getTemplateForError.called.should.be.false();

            stubs.getTemplateForEntries.calledWith({testCollection: 'test'}).should.be.true();
        });

        it('calls getTemplateForEntries for type channel', function () {
            req.url = '/';
            req.params = {};

            res._route = {
                type: 'channel'
            };

            res.locals.routerOptions = {testChannel: 'test'};

            // Call setTemplate
            templates.setTemplate(req, res, data);

            res._template.should.eql('testFromEntries');

            // Only pickTemplate got called
            stubs.pickTemplate.called.should.be.false();
            stubs.getTemplateForEntry.called.should.be.false();
            stubs.getTemplateForEntries.called.should.be.true();
            stubs.getTemplateForError.called.should.be.false();

            stubs.getTemplateForEntries.calledWith({testChannel: 'test'}).should.be.true();
        });

        it('calls getTemplateForError if there is an error', function () {
            // Make the config look like a custom route
            res._route = {
                type: 'custom',
                templateName: 'test',
                defaultTemplate: 'path/to/local/test.hbs'
            };

            // Setup an error
            res.statusCode = 404;
            req.err = new Error();

            // Call setTemplate
            templates.setTemplate(req, res, data);

            // should be testFromError
            res._template.should.eql('testFromError');

            // Only pickTemplate got called
            stubs.pickTemplate.called.should.be.false();
            stubs.getTemplateForEntry.called.should.be.false();
            stubs.getTemplateForEntries.called.should.be.false();
            stubs.getTemplateForError.called.should.be.true();

            stubs.getTemplateForError.calledWith(404).should.be.true();
        });
    });
});


text:
package com.dianping.cosmos;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import backtype.storm.metric.api.CountMetric;
import backtype.storm.spout.SpoutOutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.IRichSpout;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Values;

import com.dianping.cosmos.util.CatMetricUtil;
import com.dianping.cosmos.util.Constants;
import com.dianping.lion.client.LionException;
import com.dp.blackhole.consumer.Consumer;
import com.dp.blackhole.consumer.ConsumerConfig;
import com.dp.blackhole.consumer.MessageStream;

@SuppressWarnings({"rawtypes"})
public class BlackholeSpout implements IRichSpout {
    private static final long serialVersionUID = 1L;

    public static final Logger LOG = LoggerFactory.getLogger(BlackholeSpout.class);

    private SpoutOutputCollector collector;
    private String topic;
    private String group;
    private MessageStream stream;
    private Consumer consumer;
    private transient CountMetric _spoutMetric;

    public BlackholeSpout(String topic, String group) {
        this.topic = topic;
        this.group = group;
    }

    @Override
    public void open(Map conf, TopologyContext context,
            SpoutOutputCollector _collector) {
        collector = _collector;
        _spoutMetric = new CountMetric();
        context.registerMetric(CatMetricUtil.getSpoutMetricName(topic, group),
                _spoutMetric, Constants.EMIT_FREQUENCY_IN_SECONDS);

        ConsumerConfig config = new ConsumerConfig();
        try {
            consumer = new Consumer(topic, group, config);
        } catch (LionException e) {
            throw new RuntimeException(e);
        }
        consumer.start();
        stream = consumer.getStream();
    }

    @Override
    public void close() {
    }

    @Override
    public void activate() {
    }

    @Override
    public void deactivate() {
    }

    @Override
    public void nextTuple() {
        for (String message : stream) {
            collector.emit(topic, new Values(message));
            _spoutMetric.incr();
        }
    }

    @Override
    public void ack(Object msgId) {
        LOG.debug("ack: " + msgId);

    }

    @Override
    public void fail(Object msgId) {
        LOG.info("fail: " + msgId);
    }

    @Override
    public void declareOutputFields(OutputFieldsDeclarer declarer) {
        declarer.declareStream(topic, new Fields("event"));
    }

    @Override
    public Map<String, Object> getComponentConfiguration() {
        // TODO Auto-generated method stub
        return null;
    }

}


text:
#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIASTREAM_NAVIGATOR_MEDIA_STREAM_H_
#define THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIASTREAM_NAVIGATOR_MEDIA_STREAM_H_

#include "base/memory/scoped_refptr.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"

namespace blink {

class ExceptionState;
class MediaStreamConstraints;
class Navigator;
class V8NavigatorUserMediaErrorCallback;
class V8NavigatorUserMediaSuccessCallback;

class NavigatorMediaStream {
  STATIC_ONLY(NavigatorMediaStream);

 public:
  static void getUserMedia(Navigator&,
                           const MediaStreamConstraints*,
                           V8NavigatorUserMediaSuccessCallback*,
                           V8NavigatorUserMediaErrorCallback*,
                           ExceptionState&);
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIASTREAM_NAVIGATOR_MEDIA_STREAM_H_


text:
<dom-module id="hero-block">
    <template>

                <paper-toolbar>
                    <paper-icon-button class="menu-toggle" icon="menu" on-tap="togglePanel"></paper-icon-button>

                    <paper-tabs class="hidden-xs" attr-for-selected="data-route" selected="{{route}}">
                        <paper-tab class="text-u-c">
                            Home
                        </paper-tab>
                        <paper-tab class="text-u-c" link>

                                Schedule

                        </paper-tab>
                        <paper-tab class="text-u-c" link>

                                Speakers

                        </paper-tab>

                    </paper-tabs>
                </paper-toolbar>
                <content></content>

    </template>
</dom-module>


text:
import {mount} from 'enzyme'
import {mountToJson} from 'enzyme-to-json'
import React from 'react'
import {Provider} from 'react-redux'
import configureStore from 'redux-mock-store'
import thunkMiddleware from 'redux-thunk'
import {TextEncoder} from 'util'
import {constructor as XorShift} from 'xorshift'

import {MINIMUM_R5_VERSION} from 'lib/modules/r5-version/constants'

import {responseToSurface} from '../actions/analysis'
import {ADD_TRIP_PATTERN, TRAVEL_TIME_PERCENTILES} from '../constants'

import multi from './multi'

// Create a random number generator that is seeded
const seededRandom = new XorShift([1, 2, 3, 4])

export const makeMockStore = configureStore([multi, thunkMiddleware])

export const mockWithProvider = (children, mockData = mockStores.init) => {
  const store = makeMockStore(mockData)
  const wrapper = mount(<Provider store={store}>{children}</Provider>)

  return {
    snapshot: () => mountToJson(wrapper),
    store,
    wrapper
  }
}

export const mockModel = {
  accessGroup: 'accessGroupName',
  createdAt: '2017-11-08T12:30:50.133Z',
  createdBy: 'person@gmail.com',
  nonce: '12345',
  updatedAt: '2017-11-08T12:31:19.602Z',
  updatedBy: 'person@gmail.com'
}

export const mockSegmentGeom: GeoJSON.LineString = {
  type: 'LineString',
  coordinates: [
    [-122.0246, 36.9707],
    [-122.0279, 37.049],
    [-121.9799, 37.2299],
    [-121.9445, 37.324],
    [-121.936, 37.353],
    [-121.924, 37.365]
  ]
}

export const mockSegment: CL.ModificationSegment = {
  fromStopId: '1',
  toStopId: null,
  geometry: mockSegmentGeom,
  spacing: 3000,
  stopAtEnd: false,
  stopAtStart: false
}

export const mockStop1 = {
  autoCreated: false,
  bearing: 0,
  center: [36.9707, -122.0246],
  distanceFromStart: 0,
  index: 0,
  lat: 36.9707,
  lon: -122.0246,
  stopId: '1'
}

export const mockGtfsStop1 = {
  stop_id: '1',
  stop_lat: 36.9707,
  stop_lon: -122.0246,
  stop_name: 'Santa Cruz'
}

const mockGtfsStop2 = {
  stop_id: '2',
  stop_lat: 37.049,
  stop_lon: -122.0279,
  stop_name: 'Scotts Valley'
}

export const mockGtfsStops = [mockGtfsStop1, mockGtfsStop2]

export const mockPattern = {
  geometry: mockSegmentGeom,
  name: 'Mock Pattern',
  pattern_id: 'mock-pattern-id',
  stops: mockGtfsStops,
  trips: [
    {
      duration: 1234,
      end_time: 13579,
      start_time: 12345,
      trip_headsign: 'To Downtown',
      trip_id: 'abcd',
      trip_short_name: 'The Express'
    }
  ]
}

export const mockRoute = {
  label: 'mock-route-label',
  patterns: [mockPattern],
  route_id: 'route1'
}

export const mockFeed = {
  checksum: 'MOCK',
  id: '1',
  routes: [mockRoute],
  stopsById: {
    1: mockGtfsStop1,
    2: mockGtfsStop2
  },
  stops: [mockGtfsStop1, mockGtfsStop2]
}

export const mockMapState = {
  allowExtend: true,
  extendFromEnd: true,
  followRoad: true,
  state: 'add-trip-pattern',
  modificationId: '1234'
}

export const mockTimetable = {
  _id: 'timetable-id',
  name: 'Test timetable',
  segmentSpeeds: [],
  dwellTime: 10,
  dwellTimes: [12],
  monday: true,
  tuesday: true,
  wednesday: true,
  thursday: true,
  friday: true,
  saturday: false,
  sunday: false,
  headwaySecs: 900, // 15 minutes
  startTime: 28800, // 8am
  endTime: 57600, // 4pm
  patternTrips: ['abcd'],
  sourceTrip: 'abcd',
  phaseFromTimetable: '',
  phaseFromStop: '',
  phaseAtStop: '',
  phaseSeconds: 300,
  exactTimes: false,
  modificationId: '1234',
  modificationName: 'Test Modification'
}

export const mockOpportunityDataset = {
  sourceName: 'lodes-data-2014',
  name: 'Workers total',
  _id: 'Workers_total'
}

const regionId = '1'

export const mockBundle = {
  ...mockModel,
  errorCode: '',
  name: 'Mock Bundle',
  _id: '1',
  centerLat: 38.90124,
  centerLon: -77.015615,
  feeds: [],
  regionId,
  serviceStart: '2018-09-27',
  serviceEnd: '2018-09-28',
  status: 'DONE',
  totalFeeds: 0
}

export const mockRegion = {
  ...mockModel,
  bounds: {
    north: 39,
    east: -76,
    south: 38,
    west: -77
  },
  description: 'Region description',
  _id: regionId,
  name: 'Mock Region',
  opportunityDatasets: [mockOpportunityDataset],
  statusCode: 'DONE'
}

export const mockProject = {
  ...mockModel,
  bundleId: '1',
  _id: '1',
  name: 'Mock Project',
  regionId: mockRegion._id,
  variants: ['Default']
}

export const mockModification = {
  ...mockModel,
  bidirectional: false,
  description: 'Mock description',
  entries: [],
  feed: mockFeed.id,
  _id: '1234',
  name: 'Test Modification',
  routes: [mockRoute.route_id],
  projectId: mockProject._id,
  segments: [mockSegment],
  timetables: [mockTimetable],
  trips: ['abcd'],
  type: ADD_TRIP_PATTERN,
  variants: [true]
}

export const mockProfileRequest = {
  accessModes: 'WALK',
  bikeSafe: 1,
  bikeSlope: 1,
  bikeSpeed: 4.166666666666667,
  bikeTime: 1,
  bounds: mockRegion.bounds,
  bundleId: mockBundle._id,
  date: '2016-01-16',
  defaultExpanded: true,
  directModes: 'WALK',
  egressModes: 'WALK',
  fromLat: 12,
  fromLon: 34,
  fromTime: 25200,
  maxBikeTime: 20,
  maxRides: 4,
  maxTripDurationMinutes: 60,
  maxWalkTime: 20,
  monteCarloDraws: 200,
  name: 'Profile Request Test',
  projectId: mockProject._id,
  reachabilityThreshold: 0,
  regionId: mockRegion._id,
  toTime: 32400,
  transitModes: 'BUS,TRAM,RAIL,SUBWAY',
  travelTimePercentile: 50,
  variantIndex: 0,
  walkSpeed: 1.3888888888888888,
  workerVersion: MINIMUM_R5_VERSION
}

export const mockRegionalAnalyses = [
  {
    ...mockModel,
    zoom: 9,
    bounds: {},
    complete: true,
    deleted: false,
    destinationPointSetIds: ['Jobs_total'],
    status: 'DONE',
    workerVersion: 'v3.2.0',
    width: 300,
    height: 300,
    north: 20024,
    west: 20015,
    name: 'ANALYSIS 1',
    grid: 'Jobs_total',
    projectId: '1',
    variant: 0,
    bundleId: '1',
    cutoffMinutes: 60,
    cutoffsMinutes: [60],
    _id: 'abcd',
    request: mockProfileRequest,
    // percentile -1 indicates this analysis was done using Andrew Owen-style average instantaneous accessibility
    travelTimePercentile: -1,
    travelTimePercentiles: [50]
  },
  {
    ...mockModel,
    zoom: 9,
    bounds: {},
    complete: true,
    deleted: false,
    destinationPointSetIds: ['Jobs_total'],
    status: 'DONE',
    workerVersion: 'v3.2.0',
    width: 300,
    height: 300,
    north: 20024,
    west: 20015,
    name: 'ANALYSIS 2',
    grid: 'Jobs_total',
    projectId: '1',
    variant: 1,
    bundleId: '1',
    cutoffMinutes: 60,
    cutoffsMinutes: [60],
    _id: 'efgh',
    request: mockProfileRequest,
    travelTimePercentile: 50,
    travelTimePercentiles: [50]
  }
]

const GRID_SIZE = 300
const GRID_MAX = 2000
export const mockGrids = mockRegionalAnalyses.map((ra) => ({
  analysisId: ra._id,
  percentile: 50,
  cutoff: 60,
  zoom: 9,
  width: GRID_SIZE,
  height: GRID_SIZE,
  north: 20024,
  west: 20015,
  data: Array(GRID_SIZE * GRID_SIZE)
    .fill(0)
    .map(() => Math.floor(seededRandom.random() * GRID_MAX)),
  min: 0,
  max: GRID_MAX,
  contains: () => true
}))

export const mockGrid = mockGrids[0]

export const mockStores = {
  init: {
    analysis: {
      copyRequestSettings: true,
      isochroneFetchStatus: false,
      regional: {
        bounds: mockRegion.bounds
      },
      requestsSettings: [mockProfileRequest],
      resultsSettings: [],
      maxTripDurationMinutes: 60,
      travelTimePercentile: 50
    },
    network: {
      error: null,
      outstandingRequests: 0
    },
    opportunityDatasets: {
      active: mockOpportunityDataset._id,
      datasets: mockRegion.opportunityDatasets,
      uploadStatuses: []
    },
    queryString: {
      analysisId: mockRegionalAnalyses[0]._id,
      cutoff: 60,
      percentile: 50,
      modificationId: mockModification._id,
      projectId: mockProject._id,
      regionId: mockRegion._id
    },
    region: {
      aggregationAreas: [],
      bundles: [mockBundle],
      regions: [mockRegion]
    },
    regionalAnalyses: {
      analyses: mockRegionalAnalyses,
      grids: mockGrids
    },
    project: {
      activeModificationId: mockModification._id,
      currentProject: mockProject,
      feeds: [mockFeed],
      modifications: [mockModification],
      projects: [mockProject]
    },
    user: {
      idToken: null
    }
  }
}

export const mockScenarioApplicationError = {
  modificationId: 'Add Trip Pattern',
  title: "Error while applying the modification entitled 'Add Trip Pattern'.",
  messages: ['Headway is not greater than zero.']
}

export const mockSurfaceParameters = {
  width: 5,
  height: 5,
  depth: 5,
  zoom: 9,
  north: 40000,
  west: 40000
}

/**
 * This is a function because responseToSurface is destructive and can lead to
 * test leakage if we don't have a brand-new surface each time.
 */
export const createMockSurfaceData = () => {
  const {width, height, depth, zoom, north, west} = mockSurfaceParameters

  const metadata = {
    scenarioApplicationWarnings: [mockScenarioApplicationError]
  }

  const metadataEncoded = new TextEncoder().encode(JSON.stringify(metadata))
  const bufSize =
    9 * 4 + // header
    width * height * depth * 4 + // data
    metadataEncoded.length // metadata

  const buffer = new ArrayBuffer(bufSize)
  const surfaceData = new Int32Array(buffer, 0, 9 + width * height * depth)

  // text header ("ACCESSGR")
  surfaceData[0] = 1162036033 // ACCE
  surfaceData[1] = 1380406099 // SSGR

  // version
  surfaceData[2] = 0

  surfaceData[3] = zoom
  surfaceData[4] = west
  surfaceData[5] = north
  surfaceData[6] = width
  surfaceData[7] = height
  surfaceData[8] = depth

  // phew, header is done
  for (let z = 0, position = 9; z < depth; z++) {
    let prev = 0
    for (let y = 0; y < height; y++) {
      for (let x = 0; x < width; x++, position++) {
        const pixelVal = getMockSurfaceValue(x, y, z)
        surfaceData[position] = pixelVal - prev // values are delta-coded within each depth
        prev = pixelVal
      }
    }
  }

  // copy metadata
  const metadataBuffer = new Uint8Array(
    buffer,
    buffer.byteLength - metadataEncoded.byteLength,
    metadataEncoded.length
  )
  for (let i = 0; i < metadataEncoded.length; i++) {
    metadataBuffer[i] = metadataEncoded[i]
  }

  return buffer
}

export const mockSurface = responseToSurface(createMockSurfaceData())

/**
 * Return the value stored in sample z of pixel x, y of the mock surface
 */
export function getMockSurfaceValue(x, y, z) {
  // This used to simply return z, 2 * z and 3 * z when we had an array of
  // [5, 10, 15 . . . 95]th percentiles. However, when we switched to
  // requesting specific percentiles that stopped working. This translates the
  // position in the access grid into a percentile, then subtracts five and
  // divides by five to get the position in the old array, so that tests
  // written assuming the old structure continue to pass.
  if (x < 2 && y < 2) return (TRAVEL_TIME_PERCENTILES[z] - 5) / 5
  if (x >= 2 && y >= 2) return (TRAVEL_TIME_PERCENTILES[z] - 5) / 5
  if (x >= 2 && y < 2) return (2 * (TRAVEL_TIME_PERCENTILES[z] - 5)) / 5
  if (x < 2 && y >= 2) return (3 * (TRAVEL_TIME_PERCENTILES[z] - 5)) / 5
  return 0
}

const opportunityDatasetGridData = new Int32Array(
  mockSurfaceParameters.width * mockSurfaceParameters.height
)
// top half of grid is 1, bottom half is 2
for (let i = 0; i < 3 * mockSurfaceParameters.width; i++) {
  opportunityDatasetGridData[i] = 1
}
for (
  let i = 3 * mockSurfaceParameters.width;
  i < opportunityDatasetGridData.length;
  i++
) {
  opportunityDatasetGridData[i] = 2
}

export const mockDestinationGrid = {
  ...mockSurfaceParameters,
  west: mockSurfaceParameters.west - 1, // shift slightly so that we are testing misaligned grids
  north: mockSurfaceParameters.north - 1,
  data: opportunityDatasetGridData,
  getValue(x, y) {
    return opportunityDatasetGridData[y * mockSurfaceParameters.width + x]
  }
}

export const releaseVersions = ['v3.0.0', 'v2.2.0', 'v2.0.0']
export const allVersions = [
  'v3.0.0',
  'v2.2.0-2-g789df3e',
  'v2.2.0',
  'v2.0.0-19-g589f32f',
  'v2.0.0'
]


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.dataflow.model;

/**
 * JobMetrics contains a collection of metrics describing the detailed progress of a Dataflow job.
 * Metrics correspond to user-defined and system-defined metrics in the job.
 *
 * This resource captures only the most recent values of each metric; time-series data can be
 * queried for them (under the same metric names) from Cloud Monitoring.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Dataflow API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class JobMetrics extends com.google.api.client.json.GenericJson {

  /**
   * Timestamp as of which metric values are current.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private String metricTime;

  /**
   * All metrics for this job.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.List<MetricUpdate> metrics;

  /**
   * Timestamp as of which metric values are current.
   * @return value or {@code null} for none
   */
  public String getMetricTime() {
    return metricTime;
  }

  /**
   * Timestamp as of which metric values are current.
   * @param metricTime metricTime or {@code null} for none
   */
  public JobMetrics setMetricTime(String metricTime) {
    this.metricTime = metricTime;
    return this;
  }

  /**
   * All metrics for this job.
   * @return value or {@code null} for none
   */
  public java.util.List<MetricUpdate> getMetrics() {
    return metrics;
  }

  /**
   * All metrics for this job.
   * @param metrics metrics or {@code null} for none
   */
  public JobMetrics setMetrics(java.util.List<MetricUpdate> metrics) {
    this.metrics = metrics;
    return this;
  }

  @Override
  public JobMetrics set(String fieldName, Object value) {
    return (JobMetrics) super.set(fieldName, value);
  }

  @Override
  public JobMetrics clone() {
    return (JobMetrics) super.clone();
  }

}


text:
"""
Django settings for config project.

Generated by 'django-admin startproject' using Django 1.8.14.

For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os

BASE_DIR = os.path.dirname(
    os.path.dirname(
        os.path.dirname(
            os.path.abspath(__file__)
        )
    )
)

APPS_DIR = os.path.join(BASE_DIR, 'askfmclone')

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '7$d9c4gf#)csyxewx48(!)ygq*iy%%d30m$2o=1*wa5kdc)%j2'

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'apps.question',
    'apps.askfm',
    'widget_tweaks',
    'django_pydenticon',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
)

ROOT_URLCONF = 'config.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'config.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases

DATABASES = dict()

# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Asia/Dhaka'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/

# Static Files Settings
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'

# Login URL specific settings
LOGIN_URL = '/auth/login/'
LOGOUT_URL = '/auth/logout/'

# django_pydenticon settings
PYDENTICON_ROWS = 6
PYDENTICON_COLUMNS = 6
PYDENTICON_BACKGROUND = 'rgb(250,250,250)'


text:
package org.slf4j.impl;

import org.apache.tools.ant.Task;
import org.owasp.dependencycheck.ant.logging.AntLoggerFactory;
import org.slf4j.ILoggerFactory;
import org.slf4j.spi.LoggerFactoryBinder;

/**
 * The binding of {@link LoggerFactory} class with an actual instance of {@link ILoggerFactory} is performed using information
 * returned by this class.
 *
 * @author colezlaw
 */
public class StaticLoggerBinder implements LoggerFactoryBinder {

    /**
     * The unique instance of this class
     *
     */
    private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder();

    /**
     * Return the singleton of this class.
     *
     * @return the StaticLoggerBinder singleton
     */
    public static final StaticLoggerBinder getSingleton() {
        return SINGLETON;
    }

    /**
     * Ant tasks have the log method we actually want to call. So we hang onto the task as a delegate
     */
    private Task task = null;

    /**
     * Set the Task which will this is to log through.
     *
     * @param task the task through which to log
     */
    public void setTask(Task task) {
        this.task = task;
        loggerFactory = new AntLoggerFactory(task);
    }

    /**
     * Declare the version of the SLF4J API this implementation is compiled against. The value of this filed is usually modified
     * with each release.
     */
    // to avoid constant folding by the compiler, this field must *not* be final
    public static String REQUESTED_API_VERSION = "1.7.12"; // final

    private static final String LOGGER_FACTORY_CLASS = AntLoggerFactory.class.getName();

    /**
     * The ILoggerFactory instance returned by the {@link #getLoggerFactory} method should always be the smae object
     */
    private ILoggerFactory loggerFactory;

    /**
     * Constructs a new static logger binder.
     */
    private StaticLoggerBinder() {
        loggerFactory = new AntLoggerFactory(task);
    }

    /**
     * Returns the logger factory.
     *
     * @return the logger factory
     */
    @Override
    public ILoggerFactory getLoggerFactory() {
        return loggerFactory;
    }

    /**
     * Returns the logger factory class string.
     *
     * @return the logger factory class string
     */
    @Override
    public String getLoggerFactoryClassStr() {
        return LOGGER_FACTORY_CLASS;
    }
}


text:
package hu.akarnokd.reactive4javaflow.tck;

import hu.akarnokd.reactive4javaflow.*;
import org.testng.annotations.Test;

import java.util.concurrent.*;

@Test
public class IntervalRangeTckTest extends BaseTck<Long> {

    @Override
    public Flow.Publisher<Long> createFlowPublisher(long elements) {
        return
            Folyam.intervalRange(0, elements, 0, 1, TimeUnit.MILLISECONDS, SchedulerServices.single())
            //.onBackpressureBuffer()
        ;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:opacity="opaque">
    <item>
        <shape android:shape="rectangle" >
            <solid android:color="@android:color/white" />
            <size android:width="360dp" android:height="640dp"/>
        </shape>
    </item>
    <item
        android:width="72dp"
        android:height="72dp"
        android:bottom="40dp"
        android:drawable="@drawable/ic_launcher"
        android:gravity="center"/>

    <item
        android:bottom="60dp"
        android:drawable="@drawable/ic_cm"
        android:gravity="bottom|center_horizontal"/>
</layer-list>


text:
'use strict';

/**
 * Websocket transport
 */

const EventEmitter = require('eventemitter3');

module.exports = class Connection extends EventEmitter {
    constructor(options) {
        super();

        this.options = options || {};

        this.socket = null;
        this.connected = false;
        this.last_socket_error = null;

        this.encoding = 'utf8';
        this.incoming_buffer = '';

        this.protocol_fallback = false;

        // JSON does not allow undefined and websocket protocol does not allow falsy
        // if the protocol is falsy then the user intends no protocol, so set to undefined
        this.protocol = options.websocket_protocol ?
            options.websocket_protocol :
            undefined;
    }

    isConnected() {
        return this.connected;
    }

    writeLine(line, cb) {
        this.debugOut('writeLine() socket=' + (this.socket ? 'yes' : 'no') + ' connected=' + this.connected);

        if (this.socket && this.connected) {
            this.socket.send(line);
        }

        // Websocket.send() does not support callbacks
        // call the callback in the next tick instead
        if (cb) {
            setTimeout(cb, 0);
        }
    }

    debugOut(out) {
        this.emit('debug', out);
    }

    connect() {
        const that = this;
        const options = this.options;
        let socket = null;
        let ws_addr = '';

        this.debugOut('Connection.connect()');

        this.disposeSocket();
        this.requested_disconnect = false;

        // Build the websocket address. eg. ws://ws.rizon.net:8080
        ws_addr += (options.tls || options.ssl) ? 'wss://' : 'ws://';
        ws_addr += options.host;
        ws_addr += options.port ? ':' + options.port : '';
        ws_addr += options.path ? options.path : '';

        socket = this.socket = new WebSocket(ws_addr, this.protocol);

        socket.onopen = function() {
            that.onSocketFullyConnected();
        };
        socket.onclose = function(event) {
            that.onSocketClose(event);
        };
        socket.onmessage = function(event) {
            that.onSocketMessage(event.data);
        };
        socket.onerror = function(err) {
            that.debugOut('socketError() ' + err.message);
            that.last_socket_error = err;
        };
    }

    // Called when the socket is connected and ready to start sending/receiving data.
    onSocketFullyConnected() {
        this.debugOut('socketFullyConnected()');
        this.last_socket_error = null;
        this.connected = true;
        this.emit('open');
    }

    onSocketClose(event) {
        const possible_protocol_error = !this.connected && event.code === 1006;
        if (possible_protocol_error && !this.protocol_fallback && this.protocol !== undefined) {
            // First connection attempt failed possibly due to mismatched protocol,
            //  retry the connection with undefined protocol
            // After this attempt, normal reconnect functions apply which will
            //  reconstruct this websocket, resetting these variables
            this.debugOut('socketClose() possible protocol error, retrying with no protocol');
            this.protocol_fallback = true;
            this.protocol = undefined;
            this.connect();
            return;
        }

        this.debugOut('socketClose()');
        this.connected = false;
        this.emit('close', this.last_socket_error ? this.last_socket_error : false);
    }

    onSocketMessage(data) {
        if (typeof data !== 'string') {
            this.last_socket_error = new Error('Websocket received unexpected binary data, closing the connection');
            this.debugOut('socketData() ' + this.last_socket_error.message);
            this.close();
            return;
        }

        this.debugOut('socketData() ' + JSON.stringify(data));

        const that = this;
        let lines = null;

        this.incoming_buffer += data + '\n';

        lines = this.incoming_buffer.split('\n');
        if (lines[lines.length - 1] !== '') {
            this.incoming_buffer = lines.pop();
        } else {
            lines.pop();
            this.incoming_buffer = '';
        }

        lines.forEach(function(line) {
            that.emit('line', line);
        });
    }

    disposeSocket() {
        this.debugOut('Connection.disposeSocket() connected=' + this.connected);

        if (this.socket && this.connected) {
            this.socket.close();
        }

        if (this.socket) {
            this.socket.onopen = null;
            this.socket.onclose = null;
            this.socket.onmessage = null;
            this.socket.onerror = null;
            this.socket = null;
        }
    }

    close() {
        if (this.socket && this.connected) {
            this.socket.close();
        }
    }

    setEncoding(encoding) {
    }
};


text:
import * as Core from "../../src/core"
import { TsChildDecoratorTransformer } from "../../src/transformers/ts-child-decorator"
import { JsParser } from "../helper"
import * as Chai from "chai"

describe("TsChildDecoratorTransformer", () => {

    it("Should identify parameter decorator properly", () => {
        let ast = JsParser.getAst(`tslib_1.__param(0, decoOne("param"))`)
        let dummy = new TsChildDecoratorTransformer("ASTree");
        let parent = <Core.MethodMetaData>{
            type: "Method",
            name: "myMethod",
            analysis: Core.AnalysisType.Valid,
            parameters: [<Core.ParameterMetaData>{
                type: "Parameter",
                name: "par1"
            }]
        }
        dummy.transform(ast.expression, parent);
        Chai.expect(parent.parameters[0].decorators[0]).deep.eq(<Core.DecoratorMetaData>{
            type: "Decorator",
            name: "decoOne",
            analysis: Core.AnalysisType.Valid,
            location: {
                start: 0, end: 36
            },
            parameters: [<Core.PrimitiveValueMetaData>{
                type: "String",
                value: "param"
            }]
        });
    })

    it("Should return Unknown if provided variable", () => {
        let ast = JsParser.getAst(`tslib_1.__param(0, decoOne(variableValue))`)
        let dummy = new TsChildDecoratorTransformer("ASTree");
        let parent = <Core.MethodMetaData>{
            type: "Method",
            name: "myMethod",
            analysis: Core.AnalysisType.Valid,
            parameters: [<Core.ParameterMetaData>{
                type: "Parameter",
                name: "par1"
            }]
        }
        dummy.transform(ast.expression, parent);
        Chai.expect(parent.parameters[0].decorators[0].parameters[0].type).eq("Unknown")
    })

    it("Should merge existing parameter decorator", () => {
        let ast = JsParser.getAst(`tslib_1.__param(0, decoOne("param"))`)
        let dummy = new TsChildDecoratorTransformer("ASTree");
        let parent = <Core.MethodMetaData>{
            type: "Method",
            name: "myMethod",
            analysis: Core.AnalysisType.Valid,
            parameters: [<Core.ParameterMetaData>{
                decorators: [<Core.DecoratorMetaData>{
                    type: "Decorator",
                    name: "justName",
                    parameters: []
                }],
                type: "Parameter",
                name: "par1"
            }]
        }
        dummy.transform(ast.expression, parent);
        Chai.expect(parent.parameters[0].decorators[1]).deep.eq(<Core.DecoratorMetaData>{
            type: "Decorator",
            name: "decoOne",
            analysis: Core.AnalysisType.Valid,
            location: {
                start: 0, end: 36
            },
            parameters: [<Core.PrimitiveValueMetaData>{
                type: "String",
                value: "param"
            }]
        });
    })

    it("Should identify method decorator properly", () => {
        let ast = JsParser.getAst(`decoOne("param")`)
        let dummy = new TsChildDecoratorTransformer("ASTree");
        let parent = <Core.MethodMetaData>{
            type: "Method",
            name: "myMethod",
            analysis: Core.AnalysisType.Valid,
            parameters: [<Core.ParameterMetaData>{
                type: "Parameter",
                name: "par1"
            }]
        }
        dummy.transform(ast.expression, parent);
        Chai.expect(parent.decorators[0]).deep.eq(<Core.DecoratorMetaData>{
            type: "Decorator",
            name: "decoOne",
            analysis: Core.AnalysisType.Valid,
            location: {
                start: 0, end: 16
            },
            parameters: [<Core.PrimitiveValueMetaData>{
                type: "String",
                value: "param"
            }]
        });
    })

    it("Should merge with existing method decorator", () => {
        let ast = JsParser.getAst(`decoOne("param")`)
        let dummy = new TsChildDecoratorTransformer("ASTree");
        let parent = <Core.MethodMetaData>{
            decorators: [<Core.DecoratorMetaData>{
                type: "Decorator",
                name: "justName",
                parameters: []
            }],
            type: "Method",
            name: "myMethod",
            analysis: Core.AnalysisType.Valid,
            parameters: [<Core.ParameterMetaData>{
                type: "Parameter",
                name: "par1"
            }]
        }
        dummy.transform(ast.expression, parent);
        Chai.expect(parent.decorators[1]).deep.eq(<Core.DecoratorMetaData>{
            type: "Decorator",
            name: "decoOne",
            analysis: Core.AnalysisType.Valid,
            location: {
                start: 0, end: 16
            },
            parameters: [<Core.PrimitiveValueMetaData>{
                type: "String",
                value: "param"
            }]
        });
    })

    it("Should identify method decorator with member access", () => {
        let ast = JsParser.getAst(`theModule.decoOne("param")`)
        let dummy = new TsChildDecoratorTransformer("ASTree");
        let parent = <Core.MethodMetaData>{
            type: "Method",
            name: "myMethod",
            analysis: Core.AnalysisType.Valid,
            parameters: [<Core.ParameterMetaData>{
                type: "Parameter",
                name: "par1"
            }]
        }
        dummy.transform(ast.expression, parent);
        Chai.expect(parent.decorators[0]).deep.eq(<Core.DecoratorMetaData>{
            type: "Decorator",
            name: "decoOne",
            analysis: Core.AnalysisType.Valid,
            location: {
                start: 0, end: 26
            },
            parameters: [<Core.PrimitiveValueMetaData>{
                type: "String",
                value: "param"
            }]
        });
    })

    it("Should not error if provided __metadata", () => {
        let ast = JsParser.getAst(`tslib_1.__metadata("design:type", Function)`)
        let dummy = new TsChildDecoratorTransformer("ASTree");
        let parent = <Core.MethodMetaData>{
            type: "Method",
            name: "myMethod",
            analysis: Core.AnalysisType.Valid,
            parameters: [<Core.ParameterMetaData>{
                type: "Parameter",
                name: "par1"
            }]
        }
        dummy.transform(ast.expression, parent);
        Chai.expect(parent.decorators).undefined;
        Chai.expect(parent.parameters[0].decorators).undefined
    })
})


text:
export declare function async(fn: Function): (done: any) => any;

export declare class ComponentFixture<T> {
    changeDetectorRef: ChangeDetectorRef;
    componentInstance: T;
    componentRef: ComponentRef<T>;
    debugElement: DebugElement;
    elementRef: ElementRef;
    nativeElement: any;
    ngZone: NgZone | null;
    constructor(componentRef: ComponentRef<T>, ngZone: NgZone | null, _autoDetect: boolean);
    autoDetectChanges(autoDetect?: boolean): void;
    checkNoChanges(): void;
    destroy(): void;
    detectChanges(checkNoChanges?: boolean): void;
    isStable(): boolean;
    whenRenderingDone(): Promise<any>;
    whenStable(): Promise<any>;
}

export declare const ComponentFixtureAutoDetect: InjectionToken<boolean[]>;

export declare const ComponentFixtureNoNgZone: InjectionToken<boolean[]>;

export declare function discardPeriodicTasks(): void;

export declare function fakeAsync(fn: Function): (...args: any[]) => any;

export declare function flush(maxTurns?: number): number;

export declare function flushMicrotasks(): void;

export declare const getTestBed: () => TestBed;

export declare function inject(tokens: any[], fn: Function): () => any;

export declare class InjectSetupWrapper {
    constructor(_moduleDef: () => TestModuleMetadata);
    inject(tokens: any[], fn: Function): () => any;
}

export declare type MetadataOverride<T> = {
    add?: Partial<T>;
    remove?: Partial<T>;
    set?: Partial<T>;
};

export declare function resetFakeAsyncZone(): void;

export interface TestBed {
    ngModule: Type<any> | Type<any>[];
    platform: PlatformRef;
    compileComponents(): Promise<any>;
    configureCompiler(config: {
        providers?: any[];
        useJit?: boolean;
    }): void;
    configureTestingModule(moduleDef: TestModuleMetadata): void;
    createComponent<T>(component: Type<T>): ComponentFixture<T>;
    execute(tokens: any[], fn: Function, context?: any): any;
    /** @deprecated */ get(token: any, notFoundValue?: any): any;
    /** @deprecated */ get<T>(token: Type<T> | InjectionToken<T>, notFoundValue?: T, flags?: InjectFlags): any;
    initTestEnvironment(ngModule: Type<any> | Type<any>[], platform: PlatformRef, aotSummaries?: () => any[]): void;
    inject<T>(token: Type<T> | InjectionToken<T> | AbstractType<T>, notFoundValue?: T, flags?: InjectFlags): T;
    inject<T>(token: Type<T> | InjectionToken<T> | AbstractType<T>, notFoundValue: null, flags?: InjectFlags): T | null;
    overrideComponent(component: Type<any>, override: MetadataOverride<Component>): void;
    overrideDirective(directive: Type<any>, override: MetadataOverride<Directive>): void;
    overrideModule(ngModule: Type<any>, override: MetadataOverride<NgModule>): void;
    overridePipe(pipe: Type<any>, override: MetadataOverride<Pipe>): void;
    overrideProvider(token: any, provider: {
        useFactory: Function;
        deps: any[];
    }): void;
    overrideProvider(token: any, provider: {
        useValue: any;
    }): void;
    overrideProvider(token: any, provider: {
        useFactory?: Function;
        useValue?: any;
        deps?: any[];
    }): void;
    overrideTemplateUsingTestingModule(component: Type<any>, template: string): void;
    resetTestEnvironment(): void;
    resetTestingModule(): void;
}

export declare const TestBed: TestBedStatic;

export interface TestBedStatic {
    new (...args: any[]): TestBed;
    compileComponents(): Promise<any>;
    configureCompiler(config: {
        providers?: any[];
        useJit?: boolean;
    }): TestBedStatic;
    configureTestingModule(moduleDef: TestModuleMetadata): TestBedStatic;
    createComponent<T>(component: Type<T>): ComponentFixture<T>;
    /** @deprecated */ get(token: any, notFoundValue?: any): any;
    /** @deprecated */ get<T>(token: Type<T> | InjectionToken<T>, notFoundValue?: T, flags?: InjectFlags): any;
    initTestEnvironment(ngModule: Type<any> | Type<any>[], platform: PlatformRef, aotSummaries?: () => any[]): TestBed;
    inject<T>(token: Type<T> | InjectionToken<T> | AbstractType<T>, notFoundValue: null, flags?: InjectFlags): T | null;
    inject<T>(token: Type<T> | InjectionToken<T> | AbstractType<T>, notFoundValue?: T, flags?: InjectFlags): T;
    overrideComponent(component: Type<any>, override: MetadataOverride<Component>): TestBedStatic;
    overrideDirective(directive: Type<any>, override: MetadataOverride<Directive>): TestBedStatic;
    overrideModule(ngModule: Type<any>, override: MetadataOverride<NgModule>): TestBedStatic;
    overridePipe(pipe: Type<any>, override: MetadataOverride<Pipe>): TestBedStatic;
    overrideProvider(token: any, provider: {
        useValue: any;
    }): TestBedStatic;
    overrideProvider(token: any, provider: {
        useFactory?: Function;
        useValue?: any;
        deps?: any[];
    }): TestBedStatic;
    overrideProvider(token: any, provider: {
        useFactory: Function;
        deps: any[];
    }): TestBedStatic;
    overrideTemplate(component: Type<any>, template: string): TestBedStatic;
    overrideTemplateUsingTestingModule(component: Type<any>, template: string): TestBedStatic;
    resetTestEnvironment(): void;
    resetTestingModule(): TestBedStatic;
}

export declare class TestComponentRenderer {
    insertRootElement(rootElementId: string): void;
}

export declare type TestModuleMetadata = {
    providers?: any[];
    declarations?: any[];
    imports?: any[];
    schemas?: Array<SchemaMetadata | any[]>;
    aotSummaries?: () => any[];
};

export declare function tick(millis?: number): void;

export declare function withModule(moduleDef: TestModuleMetadata): InjectSetupWrapper;
export declare function withModule(moduleDef: TestModuleMetadata, fn: Function): () => any;


text:
import { JSONObject } from "../../../index";

import { RoleDefinition, ProfileDefinition } from "../index";

export type SecurityConfiguration = {
  /**
   * Debugger configuration
   */
  debug: {
    /**
     * Allow to use the Chrome DevTools Protocol directly
     * through `debug:post`
     */
    native_debug_protocol: boolean;
  };

  /**
   * The profileIds applied to a user created with the API action
   * `security:createRestrictedUser`.
   *
   * @default ["default"]
   */
  restrictedProfileIds: string[];

  /**
   * @deprecated Use `security.authToken` instead.
   */
  jwt?: JSONObject;

  /**
   * Configuration for the npm package jsonwebtoken
   * who handle Kuzzle Authentication Token.
   *
   * @see https://github.com/auth0/node-jsonwebtoken
   */
  authToken: {
    /**
     * Hash/encryption method used to sign the token.
     *
     * @default "HS256"
     */
    algorithm: string;

    /**
     * Token default expiration time.
     *
     * @see https://www.npmjs.com/package/ms
     *
     * @default "1h"
     */
    expiresIn: string;

    /**
     * Duration in ms during which a renewed token is still considered valid.
     *
     * @default 1000
     */
    gracePeriod: number;

    /**
     * Maximum duration in milliseconds a token can be requested to be valid.
     *
     * If set to -1, no maximum duration is set.
     *
     * @default -1
     */
    maxTTL: number;

    /**
     * String or buffer data containing either the secret for HMAC
     * algorithms, or the PEM encoded private key for RSA and ECDSA.
     *
     * If left to null, Kuzzle will autogenerate a random
     * seed (can only be used with HMAC algorithms).
     *
     * @default null
     */
    secret: string | Buffer;
  };

  apiKey: {
    /**
     * Maximum duration in milliseconds a token can be requested to be valid.
     *
     * If set to -1, no maximum duration is set.
     *
     * @default -1
     */
    maxTTL: number;
  };

  /**
   * The default role defines permissions for all users,
   * until an administrator configures the backend rights.
   *
   * By default, all users are granted all permissions.
   *
   * @default
   *
   * {
   *   "role": {
   *      "controllers": {
   *        "*": {
   *          "actions": {
   *            "*": true
   *          }
   *        }
   *      }
   *    }
   *  }
   */
  default: {
    role: RoleDefinition;
  };

  /**
  * Permissions used when creating an administrator user.
  *
  * By default, the admin user is granted all permissions.
  *
  * Anonymous and non-administrator users have their rights restricted.
  *
  * @default
  *
  * {
        "roles": {
          "admin": {
            "controllers": {
              "*": {
                "actions": {
                  "*": true
                }
              }
            }
          },
          "default": {
            "controllers": {
              "auth": {
                "actions": {
                  "checkToken": true,
                  "getCurrentUser": true,
                  "getMyRights": true,
                  "logout": true,
                  "updateSelf": true
                }
              },
              "server": {
                "actions": {
                  "publicApi": true
                }
              }
            }
          },
          "anonymous": {
            "controllers": {
              "auth": {
                "actions": {
                  "checkToken": true,
                  "getCurrentUser": true,
                  "getMyRights": true,
                  "login": true
                }
              },
              "server": {
                "actions": {
                  "publicApi": true,
                  "openapi": true
                }
              }
            }
          }
        },
        "profiles": {
          "admin": {
            "rateLimit": 0,
            "policies": [ {"roleId": "admin"} ]
          },
          "default": {
            "rateLimit": 10,
            "policies": [ {"roleId": "default"} ]
          },
          "anonymous": {
            "rateLimit": 200,
            "policies": [ {"roleId": "anonymous"} ]
          }
        }
      }
  */

  standard: {
    roles: {
      admin: RoleDefinition;
      default: RoleDefinition;
      anonymous: RoleDefinition;
      [roleName: string]: RoleDefinition;
    };
    profiles: {
      admin: ProfileDefinition;
      default: ProfileDefinition;
      anonymous: ProfileDefinition;
      [profileName: string]: ProfileDefinition;
    };
  };
};


text:
namespace rt  = riakboost::runtime;
namespace env = riakboost::runtime::env;

// STL
#include <iostream>

int main() {
    std::cout << env::get<int>("NUMBER_OF_PROCESSORS") << '\n' << env::get<rt::cstring>("TEMP") << std::endl;

    riakboost::optional<int> n;

    env::get( "NUMBER_OF_PROCESSORS", n );

    if( n )
        std::cout << n << std::endl;

    return 0;
}

// EOF


text:
using System.Reflection;

[assembly: AssemblyTitle("SignalR.SelfHost")]
[assembly: AssemblyDescription("HttpListener host for SignalR")]
[assembly: AssemblyVersion("0.4.0")]


text:
package de.digitalcollections.iiif.presentation.model.impl.v2;

import de.digitalcollections.iiif.presentation.model.api.v2.IiifResource;
import de.digitalcollections.iiif.presentation.model.api.v2.PropertyValue;
import de.digitalcollections.iiif.presentation.model.api.v2.Rendering;
import de.digitalcollections.iiif.presentation.model.api.v2.SeeAlso;
import de.digitalcollections.iiif.presentation.model.api.v2.Service;
import java.net.URI;
import java.util.List;

public abstract class AbstractIiifResourceImpl implements IiifResource {

  protected PropertyValue attribution; // optional
  protected String license; // optional
  protected String logo; // optional
  protected String type; // required
  protected String related; // optional
  protected List<Service> services; // optional
  protected List<SeeAlso> seeAlso; // optional
  protected URI within; // optional
  protected URI id; // optional
  protected List<Rendering> rendering; // optional

  @Override
  public PropertyValue getAttribution() {
    return attribution;
  }

  @Override
  public String getLicense() {
    return license;
  }

  @Override
  public String getLogo() {
    return logo;
  }

  @Override
  public void setAttribution(PropertyValue attribution) {
    this.attribution = attribution;
  }

  @Override
  public void setLicense(String license) {
    this.license = license;
  }

  @Override
  public void setLogo(String logo) {
    this.logo = logo;
  }

  @Override
  public String getType() {
    return type;
  }

  @Override
  public String getRelated() {
    return related;
  }

  @Override
  public void setRelated(String related) {
    this.related = related;
  }

  @Override
  public List<Service> getServices() {
    return services;
  }

  @Override
  public void setServices(List<Service> service) {
    this.services = service;
  }

  @Override
  public List<SeeAlso> getSeeAlso() {
    return seeAlso;
  }

  @Override
  public void setSeeAlso(List<SeeAlso> seeAlso) {
    this.seeAlso = seeAlso;
  }

  @Override
  public URI getWithin() {
    return within;
  }

  @Override
  public void setWithin(URI within) {
    this.within = within;
  }

  @Override
  public List<Rendering> getRendering() {
    return rendering;
  }

  @Override
  public void setRendering(List<Rendering> rendering) {
this.rendering = rendering;
  }

  @Override
  public URI getId() {
    return id;
  }

  @Override
  public void setId(URI id) {
    this.id = id;
  }

  @Override
  public void setId(String id) {
    this.id = URI.create(id);
  }

}


text:
const getComponentProperty = AFRAME.utils.entity.getComponentProperty;
const setComponentProperty = AFRAME.utils.entity.setComponentProperty;

AFRAME.registerComponent('daydream-pointer', {
    schema: {
    },

    init: function() {

    },

    play: function() {
        let cone = document.createElement('a-cone');
        cone.className = "ray";
        cone.setAttribute("position", "0 0 -0.44");
        cone.setAttribute("rotation", "-90 0 0");
        cone.setAttribute("radius-bottom", "0.001");
        cone.setAttribute("radius-top", "0.005");
        cone.setAttribute("height", "1.0");
        cone.setAttribute("color", "#FFF");
        cone.setAttribute("shader", "flat");
        this.el.appendChild(cone);

        let ball = document.createElement('a-sphere');
        ball.className = "ball";
        ball.setAttribute("segments-width", "8");
        ball.setAttribute("segments-height", "8");
        ball.setAttribute("position", "0 0.50 0");
        ball.setAttribute("radius", "0.01");
        cone.setAttribute("color", "#FFF");
        cone.setAttribute("shader", "flat");
        cone.appendChild(ball);
    },

    pause: function() {

    },

    tick: function() {

    },
});