text:
import { expect } from 'chai';

(async () => {
    await t
        .expect({a: 2}).eql({a: 2})
        .expect('hey').eql('yo', 'testMessage');
})();

(async () => {
    await t
        .expect({b: 3}).notEql({b: 4})
        .expect(2).notEql(2);
})();

(async () => {
    await t
        .expect({}).ok()
        .expect(false).ok();
})();

(async () => {
    await t
        .expect(false).notOk()
        .expect(1).notOk();
})();

(async () => {
    await t
        .expect('heyyo').contains('hey')
        .expect([1, 2, 3]).contains([4]);
})();

(async () => {
    await t
        .expect([1, 2, 3]).notContains([4])
        .expect('answer42').notContains('42');
})();

(async () => {
    await t
        .expect(() => true).typeOf('function')
        .expect({}).typeOf('object')
        .expect(1).typeOf('number')
        .expect('string').typeOf('string')
        .expect(true).typeOf('boolean')
        .expect(void 0).typeOf('undefined')
        .expect(null).typeOf('null')
        .expect(new RegExp('regex')).typeOf('regexp')
        .expect(42).typeOf('function');
})();

(async () => {
    await t
        .expect('function').notTypeOf('function')
        .expect('object').notTypeOf('object')
        .expect('number').notTypeOf('number')
        .expect(1).notTypeOf('string')
        .expect('boolean').notTypeOf('boolean')
        .expect('undefined').notTypeOf('undefined')
        .expect('null').notTypeOf('null')
        .expect('regex').notTypeOf('regexp')
        .expect(42).notTypeOf('number');
})();

(async () => {
    await t
        .expect(42).gt(32)
        .expect(42).gt(42);
})();

(async () => {
    await t
        .expect(42).gte(32)
        .expect(42).gte(42)
        .expect(42).gte(53);
})();

(async () => {
    await t
        .expect(32).lt(42)
        .expect(42).lt(42);
})();

(async () => {
    await t
        .expect(32).lte(42)
        .expect(42).lte(42)
        .expect(42).lte(12);
})();

(async () => {
    await t
        .expect(2.3).within(2, 3)
        .expect(4.5).within(4.6, 7);
})();

(async () => {
    await t
        .expect(4.5).notWithin(4.6, 7)
        .expect(2.3).notWithin(2, 3);
})();

(async () => {
    const el = Selector('#el1');

    await t
        .click('#makeFloat')
        .expect(el.getStyleProperty('float')).eql('left')
        .click('#setClass')
        .expect(el.hasClass('hey')).ok()
        .click('#setAttr')
        .expect(el.getAttribute('checked')).ok()
        .click('#setTextContent')
        .expect(el.textContent).eql('42');
})();

(async () => {
    const el = Selector('#el1');

    await t
        .click('#makeFloat')
        .expect(el.getStyleProperty('float')).eql('left');
})();

(async () => {
    t.expect(42).eql(43);
})();

(async () => {
    const el = Selector('#el1');

    await t
        .click('#makeFloat')
        .expect(el.getStyleProperty('float')).eql('left', {timeout: 500})
        .click('#setClass')
        .expect(el.hasClass('hey')).ok('message', {timeout: 500});
})();

(async () => {
    await t
        .expect('42 hey').match(/\d+ hey/)
        .expect('yo').match(/[x,z]o/);
})();

(async () => {
    await t
        .expect('yo').notMatch(/[x,z]o/)
        .expect('42 hey').notMatch(/\d+ hey/);
})();

(async () => {
    const getSomeVar = ClientFunction(() => window.location.toString());

    await t.expect(getSomeVar()).eql('https://example.com');
})();

(async () => {
    await t.click('#btn', {offsetX: -3.5});
})();

(async () => {
    await t.click('#btn');
})();

(async () => {
    await t.click('#div');
})();

(async () => {
    await t.click(() => {
        throw new Error('yo');
    });
})();

(async () => {
    await t.doubleClick('#button');
})();

(async () => {
    await t.drag('#draggable-div-1', 10, 20, {
        'offsetX': 10,
        'offsetY': 10,
    });
})();

(async () => {
    await t.drag('#draggable-div-1', NaN, 20);
})();

(async () => {
    await t.drag('#draggable-div-1', 10, 3.14);
})();

(async () => {
    await t.dragToElement('#draggable-div-2', '#destination-div', {
        'offsetX': 10,
        'offsetY': 10,
    });
})();

(async () => {
    await t.dragToElement(void 0, '#destination-div');
})();

(async () => {
    await t.dragToElement('#draggable-div-2', null);
})();

(async () => {
    await t.dragToElement('#draggable-div-2', '#destination-div', {destinationOffsetX: 0, destinationOffsetY: 0})
})();

(async () => {
    const getDocument = Selector(() => document);

    await t.dragToElement('#draggable-div-2', getDocument);
})();

(async () => {
    throw await t.eval(() => navigator.userAgent);
})();

const getById = ClientFunction((id: string) => document.getElementById(id));

(async () => {
    const answer = await t.eval(() => getById('answer'), {dependencies: {getById}});

    expect(answer).eql('42');
})();

(async () => {
    await t.eval(() => {
        throw new Error('Hi there!');
    });
})();

(async () => {
    await t.hover('#container1');
    await t.hover('#container2');
})();

const getBtnClickCount = ClientFunction(() => window);
const getIframeBtnClickCount = ClientFunction(() => window);
const getNestedIframeBtnClickCount = ClientFunction(() => window);

(async () => {
    await t
        .switchToIframe('#iframe')
        .click('#btn')
        .switchToMainWindow()
        .click('#btn');

    const btnClickCount = await getBtnClickCount();
    const iframeBtnClickCount = await getIframeBtnClickCount();

    expect(btnClickCount).eql(1);
    expect(iframeBtnClickCount).eql(1);
})();

(async () => {
    await t
        .switchToIframe('#iframe')
        .switchToIframe('#iframe')
        .click('#btn')
        .switchToMainWindow()
        .click('#btn');

    var btnClickCount = await getBtnClickCount();
    const nestedIframeBtnClickCount = await getNestedIframeBtnClickCount();

    expect(btnClickCount).eql(1);
    expect(nestedIframeBtnClickCount).eql(1);

    await t
        .switchToIframe('#iframe')
        .click('#btn')
        .switchToMainWindow()
        .click('#btn');

    btnClickCount = await getBtnClickCount();
    const iframeBtnClickCount = await getIframeBtnClickCount();

    expect(btnClickCount).eql(2);
    expect(iframeBtnClickCount).eql(1);
})();

(async () => {
    await t.switchToIframe('#non-existent');
})();

(async () => {
    await t
        .switchToIframe('#slowly-loading-iframe')
        .click('#btn');

    const iframeBtnClickCount = await ClientFunction(() => window.top)();

    expect(iframeBtnClickCount).eql(1);
})();

(async () => {
    await t.switchToIframe('body');
})();

(async () => {
    await t
        .switchToIframe('#iframe')
        .click('#remove-from-parent-btn')
        .switchToMainWindow()
        .click('#btn');

    const btnClickCount = await getBtnClickCount();

    expect(btnClickCount).eql(1);
})();

(async () => {
    await t
        .switchToIframe('#iframe')
        .click('#remove-from-parent-btn')
        .click('#btn');
})();

(async () => {
    const getSecondPageBtnClickCount = ClientFunction(() => window);
    const getNestedSecondPageBtnClickCount = ClientFunction(() => window);

    await t
        .switchToIframe('#iframe')
        .switchToIframe('#iframe')
        .click('#link')
        .click('#nested-second-page-btn');

    const nestedSecondPageBtnClickCount = await getNestedSecondPageBtnClickCount();

    await t
        .switchToMainWindow()
        .switchToIframe('#iframe')
        .click('#link')
        .click('#second-page-btn');

    const secondPageBtnClickCount = await getSecondPageBtnClickCount();

    expect(nestedSecondPageBtnClickCount).eql(1);
    expect(secondPageBtnClickCount).eql(1);
})();

(async () => {
    await t
        .switchToIframe('#iframe')
        .click('#reload-top-page-btn')
        .click('#btn')
        .switchToMainWindow();

    const iframeBtnClickCount = await getIframeBtnClickCount();

    expect(iframeBtnClickCount).eql(1);
})();

(async () => {
    await t
        .switchToIframe('#iframe')
        .switchToIframe('#iframe')
        .click('#remove-parent-iframe-btn')
        .switchToMainWindow()
        .click('#btn');

    const btnClickCount = await getBtnClickCount();

    expect(btnClickCount).eql(1);
})();

(async () => {
    const getIframeWithoutSrcBtnClickCount = ClientFunction(() => window.top);

    await t
        .click('#fill-iframe-without-src')
        .switchToIframe('#iframe-without-src')
        .click('#btn')
        .switchToMainWindow()
        .click('#btn');

    const btnClickCount = await getBtnClickCount();
    const iframeWithoutSrcBtnClickCount = await getIframeWithoutSrcBtnClickCount();

    expect(btnClickCount).eql(1);
    expect(iframeWithoutSrcBtnClickCount).eql(1);
})();

(async () => {
    const getSecondPageBtnClickCount = ClientFunction(() => window);

    await t
        .switchToIframe('#cross-domain-iframe')
        .click('#link')
        .click('#second-page-btn');

    const secondPageBtnClickCount = await getSecondPageBtnClickCount();

    await t
        .switchToMainWindow()
        .click('#btn');

    const btnClickCount = await getBtnClickCount();

    expect(btnClickCount).eql(1);
    expect(secondPageBtnClickCount).eql(1);
})();

(async () => {
    await t
        .switchToIframe('#too-slowly-loading-iframe')
        .click('#btn');

    const iframeBtnClickCount = await ClientFunction(() => window.top)();

    expect(iframeBtnClickCount).eql(1);
})();

(async () => {
    await t
        .switchToIframe('#iframe')
        .click('#hide-iframe-btn')
        .click('#btn');
})();

(async () => {
    await t
        .switchToIframe('#iframe')
        .click('#too-long-loading-page-link')
        .wait(3000)
        .click('#second-page-btn');
})();

(async () => {
    await t.maximizeWindow();
})();

const getResult = ClientFunction(() => document.getElementById('result').textContent);
const pageUrl = 'http://localhost:3000/fixtures/api/es-next/native-dialogs-handling/pages/index.html';
const promptPageUrl = 'http://localhost:3000/fixtures/api/es-next/native-dialogs-handling/pages/prompt.html';

(async () => {
    var info = await t.getNativeDialogHistory();

    expect(info.length).equals(0);

    await t.click('#buttonConfirm');
})();

(async () => {
    await t
        .setNativeDialogHandler((type, text) => {
            if (type === 'confirm' && text === 'Confirm?')
                return true;

            return null;
        })
        .click('#buttonConfirm');

    expect(await getResult()).equals('true');
})();

(async () => {
    var dialogHandler = ClientFunction((type: string, text: string) => {
        if (type === 'confirm' && text === 'Confirm?')
            return true;

        return null;
    });

    await t
        .setNativeDialogHandler((type, text) => dialogHandler(type, text), {dependencies: {dialogHandler}})
        .click('#buttonConfirm');

    expect(await getResult()).equals('true');
})();

(async () => {
    var dialogHandler = ClientFunction((type: string, text: string) => {
        if (type === 'confirm' && text === 'Confirm?')
            return true;

        return null;
    });

    await t
        .setNativeDialogHandler(dialogHandler)
        .click('#buttonConfirm');

    expect(await getResult()).equals('true');
})();

(async () => {
    await t
        .setNativeDialogHandler(type => {
            if (type === 'confirm')
                throw new Error('Wrong dialog type');
        })
        .click('#buttonAlert')
        .setNativeDialogHandler(type => {
            if (type === 'alert')
                throw new Error('Wrong dialog type');
        })
        .click('#buttonConfirm');
})();

(async () => {
    await t
        .setNativeDialogHandler(() => {
            throw new Error('Wrong dialog text');
        })
        .click('#buttonConfirm');

    expect(await getResult()).equals('true');
})();

(async () => {
    await t
        .click('#withoutDialog')
        .setNativeDialogHandler(() => true);

    var info = await t.getNativeDialogHistory();

    expect(info.length).equals(1);
})();

(async () => {
    await t
        .setNativeDialogHandler(() => {
        })
        .click('#enableBeforeUnload')
        .click('#linkToThisPage');

    var info = await t.getNativeDialogHistory();

    expect(info).to.deep.equal([{type: 'beforeunload', text: 'Before unload', url: pageUrl}]);
})();

(async () => {
    await t
        .setNativeDialogHandler((type, text, url) => {
            if (type === 'prompt' && text === 'Prompt:' &&
                url === 'http://localhost:3000/fixtures/api/es-next/native-dialogs-handling/pages/prompt.html')
                return 'prompt result';

            return null;
        })
        .click('#buttonRedirectPrompt');

    expect(await getResult()).equals('prompt result');

    var info = await t.getNativeDialogHistory();

    expect(info).to.deep.equal([
        {
            type: 'prompt',
            text: 'Prompt:',
            url: promptPageUrl,
        },
        {
            type: 'alert',
            text: 'Alert!',
            url: pageUrl,
        },
    ]);
})();

(async () => {
    await t.click('#linkToPromptPage');
})();

//Dialogs during wait command execution
(async () => {
    await t
        .setNativeDialogHandler(() => null)
        .click('#buttonDialogAfterTimeout')
        .wait(2000);

    var info = await t.getNativeDialogHistory();

    expect(info).to.deep.equal([{type: 'alert', text: 'Alert!', url: pageUrl}]);
})();

(async () => {
    await t
        .setNativeDialogHandler(() => null)
        .click('#buttonDialogAfterTimeout')
        .wait(10);

    var info = await t.getNativeDialogHistory();

    expect(info.length).equals(1);
})();

(async () => {
    await t
        .click('#buttonDialogAfterTimeout')
        .wait(2000);
})();

(async () => {
    var dialogHandler = Selector(() => document.body);

    await t.setNativeDialogHandler(dialogHandler);
})();

(async () => {
    await t
        .setNativeDialogHandler(() => true)
        .click('#buttonAlert')
        .setNativeDialogHandler(null)
        .click('#buttonAlert');
})();

const getLocation = ClientFunction(() => window.location.toString().toLowerCase().replace(/\/\/\//g, '//'));

(async () => {
    await t
        .navigateTo('http://localhost:3000/fixtures/api/es-next/navigate-to-and-test-page/pages/navigation.html')
        .click('#button')
        .expect(getLocation()).eql('http://localhost:3000/fixtures/api/es-next/navigate-to-and-test-page/pages/navigation.html');
})();

(async () => {
    await t
        .navigateTo('navigation.html')
        .click('#button')
        .expect(getLocation()).eql('http://localhost:3000/fixtures/api/es-next/navigate-to-and-test-page/pages/navigation.html');
})();

(async () => {
    await t
        .navigateTo('//localhost:3000/fixtures/api/es-next/navigate-to-and-test-page/pages/navigation.html')
        .click('#button')
        .expect(getLocation()).eql('http://localhost:3000/fixtures/api/es-next/navigate-to-and-test-page/pages/navigation.html');
})();

const focusInput = ClientFunction(() => document.getElementById('input').focus());
const getInputValue = ClientFunction(() => (<HTMLInputElement>document.getElementById('input')).value);

(async () => {
    await focusInput();
    await t.pressKey('right shift+right shift+right delete');
    expect(await getInputValue()).equals('vue');
})();

(async () => {
    await t.resizeWindow(150, 300);
})();

(async () => {
    await t.resizeWindow(500, -5);
})();

(async () => {
    await t.resizeWindowToFitDevice('iPhone');
})();

(async () => {
    await t.resizeWindowToFitDevice('iPhone', {portraitOrientation: true});
})();

(async () => {
    await t.rightClick('#button');
})();

(async () => {
    await t
        .selectText('#input', 2, 4)
        .selectText('#input', 2)
        .selectText('#input');
})();

(async () => {
    await t
        .selectTextAreaContent('#textarea', 0, 2, 1, 3)
        .selectTextAreaContent('#textarea', 0, 2, 1)
        .selectTextAreaContent('#textarea', 0, 2)
        .selectTextAreaContent('#textarea', 1)
        .selectTextAreaContent('#textarea');
})();

(async () => {
    await t.selectEditableContent('#p1', '#p2');
})();

(async () => {

    await t.takeScreenshot('custom\\' + 123 + '.png');
})();

(async () => {
    await t
        .takeScreenshot()
        .click('.notExist');
})();

(async () => {
    await t.typeText('#input', 'a', {replace: true});
})();

(async () => {
    await t
        .setFilesToUpload('#file', '../test-data/file1.txt')
        .click('#submit');
})();

(async () => {
    await t
        .setFilesToUpload('#file', '../test-data/file1.txt')
        .clearUpload('#file')
        .click('#submit');
})();

(async () => {
    await t
        .click('#button1')
        .wait(2000)
        .click('#button2');
})();

(async () => {
    await t
        .click('#btn1')
        .click('#btn2');

    await t
        .click('#btn3')
        .click('#page2-btn1')
        .click('#page2-btn2');
})();

(async () => {
    await t
        .click('#btn1')
        .click('#btn2')
        .click('#error')
        .click('#btn3');
})();

(async () => {
    let messages = await t.getBrowserConsoleMessages();

    await t
        .expect(messages.error).eql(['error1'])
        .expect(messages.warn).eql(['warn1'])
        .expect(messages.log).eql(['log1'])
        .expect(messages.info).eql(['info1'])

        .click('#trigger-messages')

        // Check the driver keeps the messages between page reloads
        .click('#reload');

    messages = await t.getBrowserConsoleMessages();

    await t
        .expect(messages.error).eql(['error1', 'error2'])
        .expect(messages.warn).eql(['warn1', 'warn2'])
        .expect(messages.log).eql(['log1', 'log2'])
        .expect(messages.info).eql(['info1', 'info2']);
})();

(async () => {
    // Several arguments
    await t.eval(() => console.log('a', 1, null, void 0, ['b', 2], {c: 3}));

    const messages = await t.getBrowserConsoleMessages();

    await t
        .expect(messages.log[0]).eql('a 1 null undefined b,2 [object Object]')
        .expect(messages.info.length).eql(0)
        .expect(messages.warn.length).eql(0)
        .expect(messages.error.length).eql(0);
})();

(async () => {
    function test (): Promise<void> {
        return t.expect(1).ok();
    }

    test();
})();


text:
import calendar
from datetime import datetime
import logging
import os
import re
from tempfile import gettempdir, NamedTemporaryFile
import time
import unittest

# project
from checks.datadog import Dogstreams, EventDefaults

log = logging.getLogger('datadog.test')

def parse_ancient_function_plugin(logger, line):
    """Ancient stateless parser"""
    res = line.split()
    res[3] = {'metric_type': 'gauge'}

def parse_function_plugin(logger, line, state):
    """Simple stateful parser"""
    try:
        acc = state["test_acc"] + 1
    except KeyError:
        acc = 1
    state["test_acc"] = acc
    res = line.split()
    res[2] = acc
    res[3] = {'metric_type': 'counter'}
    return tuple(res)

class ParseClassPlugin(object):
    """Class-based stateful parser"""
    def __init__(self, logger=None, user_args=(), **kwargs):
        self.logger = logger
        self.args = '.'.join(user_args)
        self.acc = 0
        self.logger.info('Completed initialization')

    def parse_line(self, line):
        self.logger.info('Parsing line %r; counter is %r', line, self.acc)
        self.acc += 1
        res = line.split()
        res[0] = self.args + ':' + res[0]
        res[2] = self.acc
        res[3] = {'metric_type': 'counter'}
        return tuple(res)

log_event_pattern = re.compile("".join([
    r"(?P<timestamp>\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) ",  # iso timestamp
    r"\[(?P<alert_type>(ERROR)|(RECOVERY))\] - ",  # alert type
    r"(?P<msg_title>(?P<host>[^ ]*).*)"
]))
alert_types = {
    "ERROR": "error",
    "RECOVERY": "success"
}

def parse_events(logger, line):
    """ Expecting lines like this:
        2012-05-14 12:46:01 [ERROR] - host0 is down (broke its collarbone)
    """
    match = log_event_pattern.match(line)
    if match:
        groups = match.groupdict()
        groups.update({
            'alert_type': alert_types.get(groups['alert_type'], ''),
            'timestamp':  calendar.timegm(datetime.strptime(groups['timestamp'], '%Y-%m-%d %H:%M:%S').timetuple()),
            'msg_text': line
        })

        return groups
    else:
        return None

def repr_event_parser(logger, line):
    return eval(line)

class TailTestCase(unittest.TestCase):
    def setUp(self):
        self.log_file = NamedTemporaryFile()
        self.logger = logging.getLogger('test.dogstream')

    def _write_log(self, log_data):
        for data in log_data:
            print >> self.log_file, data
        self.log_file.flush()

    def tearDown(self):
        self.log_file.close()

class TestDogstream(TailTestCase):
    gauge = {'metric_type': 'gauge'}
    counter = {'metric_type': 'counter'}

    def setUp(self):
        TailTestCase.setUp(self)

        self.config = {
            'dogstreams': self.log_file.name,
            'check_freq': 5,
        }
        log.info("Test config: %s" % self.config)
        self.dogstream = Dogstreams.init(self.logger, self.config)
        self.maxDiff = None

    def test_dogstream_gauge(self):
        log_data = [
            # bucket 0
            ('test.metric.a', '1000000000', '10', 'metric_type=gauge'),
            ('test.metric.a', '1000000001', '20', 'metric_type=gauge'),
            ('test.metric.a', '1000000002', '3', 'metric_type=gauge'),
            ('test.metric.a', '1000000003', '4', 'metric_type=gauge'),
            ('test.metric.a', '1000000004', '5', 'metric_type=gauge'),

            # bucket 1
            ('test.metric.a', '1000000005', '12', 'metric_type=gauge'),
            ('test.metric.a', '1000000006', '7', 'metric_type=gauge'),
            ('test.metric.a', '1000000007', '8', 'metric_type=gauge'),
        ]

        expected_output = {
            "dogstream": [
                ('test.metric.a', 1000000000, 5.0, self.gauge),
                ('test.metric.a', 1000000005, 8.0, self.gauge),
            ]
        }

        self._write_log((' '.join(data) for data in log_data))

        actual_output = self.dogstream.check(self.config, move_end=False)
        self.assertEquals(expected_output, actual_output)
        for metric, timestamp, val, attr in expected_output['dogstream']:
            assert isinstance(val, float)

    def test_dogstream_counter(self):
        log_data = [
            # bucket 0
            ('test.metric.a', '1000000000', '10', 'metric_type=counter'),
            ('test.metric.a', '1000000001', '20', 'metric_type=counter'),
            ('test.metric.a', '1000000002', '3', 'metric_type=counter'),
            ('test.metric.a', '1000000003', '4', 'metric_type=counter'),
            ('test.metric.a', '1000000004', '5', 'metric_type=counter'),

            # bucket 1
            ('test.metric.a', '1000000005', '12', 'metric_type=counter'),
            ('test.metric.a', '1000000006', '7', 'metric_type=counter'),
            ('test.metric.a', '1000000007', '8', 'metric_type=counter'),
        ]

        expected_output = {
            "dogstream": [
                ('test.metric.a', 1000000000, 42, self.counter),
                ('test.metric.a', 1000000005, 27, self.counter),
            ]
        }

        self._write_log((' '.join(data) for data in log_data))

        actual_output = self.dogstream.check(self.config, move_end=False)
        self.assertEquals(expected_output, actual_output)
        for metric, timestamp, val, attr in expected_output['dogstream']:
            assert isinstance(val, (int, long))

    def test_dogstream_bad_input(self):
        log_data = [
            ('test.metric.e1000000000 1metric_type=gauge'),
            ('1000000001 1 metric_type=gauge tag=staging'),
            ('test_metric.e 1 1000000002 metric_type=gauge'),
            ('test_metric.e 1000000002 10 metric_type=gauge'),
        ]
        expected_output = {"dogstream":
            [('test_metric.e', 1000000000, 10, self.gauge)]
        }

        self._write_log(log_data)

        actual_output = self.dogstream.check(self.config, move_end=False)
        self.assertEquals(expected_output, actual_output)

    def test_dogstream_log_path_globbing(self):
        """Make sure that globbed dogstream logfile matching works."""
        # Create a tmpfile to serve as a prefix for the other temporary
        # files we'll be globbing.
        first_tmpfile = NamedTemporaryFile()
        tmp_fprefix = os.path.basename(first_tmpfile.name)
        all_tmp_filenames = set([first_tmpfile.name])
        # We stick the file objects in here to avoid garbage collection (and
        # tmpfile deletion). Not sure why this was happening, but it's working
        # with this hack in.
        avoid_gc = []
        for i in range(3):
            new_tmpfile = NamedTemporaryFile(prefix=tmp_fprefix)
            all_tmp_filenames.add(new_tmpfile.name)
            avoid_gc.append(new_tmpfile)
        dogstream_glob = os.path.join(gettempdir(), tmp_fprefix + '*')
        paths = Dogstreams._get_dogstream_log_paths(dogstream_glob)
        self.assertEqual(set(paths), all_tmp_filenames)

    def test_dogstream_function_plugin(self):
        """Ensure that non-class-based stateful plugins work"""
        log_data = [
            'test.metric.accumulator 1000000000 1 metric_type=counter',
            'test.metric.accumulator 1100000000 1 metric_type=counter'
        ]
        expected_output = {
            "dogstream": [
                ('test.metric.accumulator', 1000000000, 1, self.counter),
                ('test.metric.accumulator', 1100000000, 2, self.counter)]
        }
        self._write_log(log_data)

        statedog = Dogstreams.init(self.logger, {'dogstreams': '{0}:{1}:parse_function_plugin'.format(self.log_file.name, __name__)})
        actual_output = statedog.check(self.config, move_end=False)
        self.assertEquals(expected_output, actual_output)

    def test_dogstream_new_plugin(self):
        """Ensure that class-based stateful plugins work"""
        log_data = [
            'test.metric.accumulator 1000000000 1 metric_type=counter',
            'test.metric.accumulator 1100000000 1 metric_type=counter'
        ]
        expected_output = {
            "dogstream": [
                ('foo.bar:test.metric.accumulator', 1000000000, 1, self.counter),
                ('foo.bar:test.metric.accumulator', 1100000000, 2, self.counter)]
        }
        self._write_log(log_data)

        statedog = Dogstreams.init(self.logger, {'dogstreams': '{0}:{1}:ParseClassPlugin:foo:bar'.format(self.log_file.name, __name__)})
        actual_output = statedog.check(self.config, move_end=False)
        self.assertEquals(expected_output, actual_output)

    def test_dogstream_events(self):
        log_data = [
            '2012-05-14 12:46:01 [ERROR] - host0 is down (broke its collarbone)',
            '2012-05-14 12:48:07 [ERROR] - host1 is down (got a bloody nose)',
            '2012-05-14 12:52:03 [RECOVERY] - host0 is up (collarbone healed)',
            '2012-05-14 12:59:09 [RECOVERY] - host1 is up (nose stopped bleeding)',
        ]
        expected_output = {
            "dogstreamEvents": [
                {
                    "timestamp": 1336999561,
                    "alert_type": "error",
                    "host": "host0",
                    "msg_title": "host0 is down (broke its collarbone)",
                    "msg_text": "2012-05-14 12:46:01 [ERROR] - host0 is down (broke its collarbone)",
                    "event_type": EventDefaults.EVENT_TYPE,
                    "aggregation_key": EventDefaults.EVENT_OBJECT,
                    "event_object": EventDefaults.EVENT_OBJECT,
                },

                {
                    "timestamp": 1336999687,
                    "alert_type": "error",
                    "host": "host1",
                    "msg_title": "host1 is down (got a bloody nose)",
                    "msg_text": "2012-05-14 12:48:07 [ERROR] - host1 is down (got a bloody nose)",
                    "event_type": EventDefaults.EVENT_TYPE,
                    "aggregation_key": EventDefaults.EVENT_OBJECT,
                    "event_object": EventDefaults.EVENT_OBJECT,
                },

                {
                    "timestamp": 1336999923,
                    "alert_type": "success",
                    "host": "host0",
                    "msg_title": "host0 is up (collarbone healed)",
                    "msg_text": "2012-05-14 12:52:03 [RECOVERY] - host0 is up (collarbone healed)",
                    "event_type": EventDefaults.EVENT_TYPE,
                    "aggregation_key": EventDefaults.EVENT_OBJECT,
                    "event_object": EventDefaults.EVENT_OBJECT,
                },

                {
                    "timestamp": 1337000349,
                    "alert_type": "success",
                    "host": "host1",
                    "msg_title": "host1 is up (nose stopped bleeding)",
                    "msg_text": "2012-05-14 12:59:09 [RECOVERY] - host1 is up (nose stopped bleeding)",
                    "event_type": EventDefaults.EVENT_TYPE,
                    "aggregation_key": EventDefaults.EVENT_OBJECT,
                    "event_object": EventDefaults.EVENT_OBJECT,
                },

            ]
        }
        self._write_log(log_data)

        dogstream = Dogstreams.init(self.logger, {'dogstreams': '{0}:{1}:parse_events'.format(self.log_file.name, __name__)})
        actual_output = dogstream.check(self.config, move_end=False)
        self.assertEquals(expected_output, actual_output)

    def test_dogstream_events_validation(self):
        log_data = [
            {"msg_title": "title", "timestamp": 1336999561},
            {"msg_text": "body", "timestamp": 1336999561},
            {"none of the above": "should get filtered out", "timestamp": 1336999561},
        ]

        expected_output = {
            "dogstreamEvents": [
                {
                    "timestamp": 1336999561,
                    "msg_title": "title",
                    "event_type": EventDefaults.EVENT_TYPE,
                    "aggregation_key": EventDefaults.EVENT_OBJECT,
                    "event_object": EventDefaults.EVENT_OBJECT,
                },

                {
                    "timestamp": 1336999561,
                    "msg_text": "body",
                    "event_type": EventDefaults.EVENT_TYPE,
                    "aggregation_key": EventDefaults.EVENT_OBJECT,
                    "event_object": EventDefaults.EVENT_OBJECT,
                },

            ]
        }

        self._write_log([repr(d) for d in log_data])

        dogstream = Dogstreams.init(self.logger, {'dogstreams': '{0}:{1}:repr_event_parser'.format(self.log_file.name, __name__)})
        actual_output = dogstream.check(self.config, move_end=False)
        self.assertEquals(expected_output, actual_output)

    def test_cassandra_parser(self):
        from dogstream import cassandra, common

        log_data = """ INFO [CompactionExecutor:1594] 2012-05-12 21:05:12,924 Saved test_data-Encodings-KeyCache (86400 items) in 85 ms
 INFO [CompactionExecutor:1595] 2012-05-12 21:05:15,144 Saved test_data-Metrics-KeyCache (86400 items) in 96 ms
 INFO [CompactionExecutor:1596] 2012-05-12 21:10:48,058 Compacting [SSTableReader(path='/var/cassandra/data/test_data/series-hc-6528-Data.db'), SSTableReader(path='/var/cassandra/data/test_data/series-hc-6531-Data.db'), SSTableReader(path='/var/cassandra/data/test_data/series-hc-6529-Data.db'), SSTableReader(path='/var/cassandra/data/test_data/series-hc-6530-Data.db')]
 INFO [CompactionExecutor:1596] 2012-05-12 21:10:54,851 Compacted to [/var/cassandra/a-hc-65-Data.db,].  102,079,134 to 101,546,397
 INFO [CompactionExecutor:1598] 2012-05-12 22:05:04,313 Saved test_data-ResourcesMetadata-KeyCache (1 items) in 10 ms
 INFO [CompactionExecutor:1599] 2012-05-12 22:05:14,813 Saved test_data-Encodings-KeyCache (86400 items) in 83 ms
 INFO [CompactionExecutor:1630] 2012-05-13 13:05:44,963 Saved test_data-Metrics-KeyCache (86400 items) in 77 ms
 INFO [CompactionExecutor:1631] 2012-05-13 13:15:01,923 Nothing to compact in data_log.  Use forceUserDefinedCompaction if you wish to force compaction of single sstables (e.g. for tombstone collection)
 INFO [CompactionExecutor:1632] 2012-05-13 13:15:01,927 Compacting [SSTableReader(path='/var/cassandra/data/test_data/series-hc-6527-Data.db'), SSTableReader(path='/var/cassandra/data/test_data/series-hc-6522-Data.db'), SSTableReader(path='/var/cassandra/data/test_data/series-hc-6532-Data.db'), SSTableReader(path='/var/cassandra/data/test_data/series-hc-6517-Data.db')]
 INFO [CompactionExecutor:1632] 2012-05-13 13:27:17,685 Compacting large row test_data/series:6c6f677c32 (782001077 bytes) incrementally
 INFO [CompactionExecutor:34] 2012-05-14 18:00:41,281 Saved test_data-Encodings-KeyCache (86400 items) in 78 ms
 INFO 13:27:17,685 Compacting large row test_data/series:6c6f677c32 (782001077 bytes) incrementally
"""
        alert_type = cassandra.ALERT_TYPES["INFO"]
        event_type = cassandra.EVENT_TYPE
        event_object = EventDefaults.EVENT_OBJECT

        expected_output = {
            "dogstreamEvents": [
                {
                    "timestamp": cassandra.parse_date("2012-05-12 21:10:48,058"),
                    "msg_title": "Compacting [SSTableReader(path='/var/cassandra/data/test_data/series-hc-6528-Data.db'), SSTableReader(path='/var/cassandra/data/test_data/series-hc-6531-Data.db'), SSTableReader(path='/var/cassandra/data/test_data/series-hc-6529-Data.db'), SSTableReader(path='/var/cassandra/data/test_data/series-hc-6530-Data.db')]"[0:common.MAX_TITLE_LEN],
                    "msg_text": "Compacting [SSTableReader(path='/var/cassandra/data/test_data/series-hc-6528-Data.db'), SSTableReader(path='/var/cassandra/data/test_data/series-hc-6531-Data.db'), SSTableReader(path='/var/cassandra/data/test_data/series-hc-6529-Data.db'), SSTableReader(path='/var/cassandra/data/test_data/series-hc-6530-Data.db')]",
                    "alert_type": alert_type,
                    "auto_priority": 0,
                    "event_type": event_type,
                    "aggregation_key": event_object,
                    "event_object": event_object,
                },  {
                    "timestamp": cassandra.parse_date("2012-05-12 21:10:54,851"),
                    "msg_title": "Compacted to [/var/cassandra/a-hc-65-Data.db,].  102,079,134 to 101,546,397",
                    "alert_type": alert_type,
                    "auto_priority": 0,
                    "event_type": event_type,
                    "aggregation_key": event_object,
                    "event_object": event_object,
                },  {
                    "timestamp": cassandra.parse_date("2012-05-13 13:15:01,927"),
                    "msg_title": "Compacting [SSTableReader(path='/var/cassandra/data/test_data/series-hc-6527-Data.db'), SSTableReader(path='/var/cassandra/data/test_data/series-hc-6522-Data.db'), SSTableReader(path='/var/cassandra/data/test_data/series-hc-6532-Data.db'), SSTableReader(path='/var/cassandra/data/test_data/series-hc-6517-Data.db')]"[0:common.MAX_TITLE_LEN],
                    "msg_text": "Compacting [SSTableReader(path='/var/cassandra/data/test_data/series-hc-6527-Data.db'), SSTableReader(path='/var/cassandra/data/test_data/series-hc-6522-Data.db'), SSTableReader(path='/var/cassandra/data/test_data/series-hc-6532-Data.db'), SSTableReader(path='/var/cassandra/data/test_data/series-hc-6517-Data.db')]",
                    "alert_type": alert_type,
                    "event_type": event_type,
                    "auto_priority": 0,
                    "aggregation_key": event_object,
                    "event_object": event_object,
                },  {
                    "timestamp": cassandra.parse_date("2012-05-13 13:27:17,685"),
                    "msg_title": "Compacting large row test_data/series:6c6f677c32 (782001077 bytes) incrementally",
                    "alert_type": alert_type,
                    "event_type": event_type,
                    "auto_priority": 0,
                    "aggregation_key": event_object,
                    "event_object": event_object,
                },  {
                    "timestamp": cassandra.parse_date(datetime.utcnow().strftime("%Y-%m-%d") + " 13:27:17,685"),
                    "msg_title": "Compacting large row test_data/series:6c6f677c32 (782001077 bytes) incrementally",
                    "alert_type": alert_type,
                    "event_type": event_type,
                    "auto_priority": 0,
                    "aggregation_key": event_object,
                    "event_object": event_object,
                },
            ]
        }

        self._write_log(log_data.split("\n"))

        dogstream = Dogstreams.init(self.logger, {'dogstreams': '%s:dogstream.cassandra:parse_cassandra' % self.log_file.name})
        actual_output = dogstream.check(self.config, move_end=False)
        self.assertEquals(expected_output, actual_output)

    def test_supervisord_parser(self):
        from dogstream import supervisord_log
        log_data = """2012-07-16 22:30:48,335 INFO spawned: 'monitor' with pid 20216
2012-07-14 03:02:47,325 INFO success: foo_bar entered RUNNING state, process has stayed up for > than 2 seconds (startsecs)
2012-07-17 02:53:04,600 CRIT Server 'inet_http_server' running without any HTTP authentication checking
2012-07-14 04:54:34,193 WARN received SIGTERM indicating exit request
"""
        event_type = supervisord_log.EVENT_TYPE

        expected_output = {
            "dogstreamEvents": [
                {
                    "alert_type": "info", "event_type": event_type,
                    "aggregation_key": "monitor",
                    "event_object": "monitor",
                    "msg_title": "spawned: 'monitor' with pid 20216",
                    "timestamp": int(time.mktime(datetime(2012, 7, 16, 22, 30, 48).timetuple())),
                }, {
                    "alert_type": "success", "event_type": event_type,
                    "aggregation_key": "foo_bar",
                    "event_object": "foo_bar",
                    "msg_title": "success: foo_bar entered RUNNING state, "
                    "process has stayed up for > than 2 seconds (startsecs)",
                    "timestamp": int(time.mktime(datetime(2012, 7, 14, 3, 2, 47).timetuple())),
                }, {
                    "alert_type": "error", "event_type": event_type,
                    "aggregation_key": "inet_http_server",
                    "event_object": "inet_http_server",
                    "msg_title": "Server 'inet_http_server' running without any HTTP authentication checking",
                    "timestamp": int(time.mktime(datetime(2012, 7, 17, 2, 53, 4).timetuple())),
                }, {
                    "alert_type": "warning", "event_type": event_type,
                    "aggregation_key": "SIGTERM",
                    "event_object": "SIGTERM",
                    "msg_title": "received SIGTERM indicating exit request",
                    "timestamp": int(time.mktime(datetime(2012, 7, 14, 4, 54, 34).timetuple())),
                },
            ]
        }
        self._write_log(log_data.split("\n"))

        dogstream = Dogstreams.init(self.logger, {'dogstreams': '%s:dogstream.supervisord_log:parse_supervisord' % self.log_file.name})
        actual_output = dogstream.check(self.config, move_end=False)
        self.assertEquals(expected_output, actual_output)

redpajama_set_name: RedPajamaGithub


text:
namespace ozonewayland {
// This number should be equal to size of array defined in WaylandCursorData
// constructor.
const unsigned TotalCursorTypes = 12;

class WaylandCursorData {
 public:
  explicit WaylandCursorData(wl_shm* shm);
  ~WaylandCursorData();

  static WaylandCursorData* GetInstance() {
    return impl_;
  }

  static void InitializeCursorData(wl_shm* shm) {
    if (!impl_)
      impl_ = new WaylandCursorData(shm);
  }

  static void DestroyCursorData() {
    if (impl_) {
      delete impl_;
      impl_ = NULL;
    }
  }

  struct wl_cursor_image* GetCursorImage(int index);

 private:
  wl_cursor_theme* cursor_theme_;
  // All supported Cursor types.
  std::vector<wl_cursor*> cursors_;
  static WaylandCursorData* impl_;
  DISALLOW_COPY_AND_ASSIGN(WaylandCursorData);
};

WaylandCursorData* WaylandCursorData::impl_ = NULL;

WaylandCursorData::WaylandCursorData(wl_shm* shm)
    : cursor_theme_(NULL),
      cursors_(std::vector<wl_cursor*>(TotalCursorTypes)) {
  // This list should be always in sync with WaylandCursor::CursorType
  const char* cursor_names[] = {
    "bottom_left_corner",
    "bottom_right_corner",
    "bottom_side",
    "grabbing",
    "left_ptr",
    "left_side",
    "right_side",
    "top_left_corner",
    "top_right_corner",
    "top_side",
    "xterm",
    "hand1",
  };

  // (kalyan) We should be able to configure the size of cursor and theme name.
  cursor_theme_ = wl_cursor_theme_load(NULL, 24, shm);
  DCHECK(cursor_theme_);

  for (unsigned i = 0; i < TotalCursorTypes; i++)
    cursors_[i] = wl_cursor_theme_get_cursor(cursor_theme_, cursor_names[i]);
}

struct wl_cursor_image* WaylandCursorData::GetCursorImage(int index) {
  const struct wl_cursor* cursor = cursors_.at(index);
  if (!cursor)
    return NULL;

  return cursor->images[0];
}

WaylandCursorData::~WaylandCursorData() {
  wl_cursor_theme_destroy(cursor_theme_);

  if (!cursors_.empty())
    cursors_.clear();
}

WaylandCursor::WaylandCursor(wl_shm* shm) : input_pointer_(NULL),
    pointer_surface_(new WaylandSurface()) {
  WaylandCursorData::InitializeCursorData(shm);
}

WaylandCursor::~WaylandCursor() {
  delete pointer_surface_;
}

void WaylandCursor::Clear() {
  WaylandCursorData::DestroyCursorData();
}

void WaylandCursor::Update(CursorType type, uint32_t serial) {
  if (!input_pointer_)
    return;

  struct wl_cursor_image* image = WaylandCursorData::GetInstance()->
      GetCursorImage(type - 1);
  struct wl_buffer* buffer = wl_cursor_image_get_buffer(image);
  int width = image->width;
  int height = image->height;
  wl_pointer_set_cursor(input_pointer_,
                        serial,
                        pointer_surface_->wlSurface(),
                        image->hotspot_x,
                        image->hotspot_y);

  struct wl_surface* surface = pointer_surface_->wlSurface();
  wl_surface_attach(surface, buffer, 0, 0);
  wl_surface_damage(surface, 0, 0, width, height);
  wl_surface_commit(surface);
}

void WaylandCursor::SetInputPointer(wl_pointer* pointer) {
  if (input_pointer_ == pointer)
    return;

  if (input_pointer_)
    wl_pointer_destroy(input_pointer_);

  input_pointer_ = pointer;
}

}  // namespace ozonewayland


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="../../favicon.ico">

    <title>Install fleet</title>

    <link href="bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">

Test page

Help

Fleet

      <?php
      if (isset($_GET['success'])) :
      ?>

Installation performed successfully! 😎 Go to the test page to see your app live.

      <?php endif; ?>
      <?php
      if (isset($_GET['error'])) :
      ?>

Error occurred during installation! See here.

      <?php endif; ?>
      <?php
        $ROOT = dirname(dirname(__FILE__));
        if(!is_writeable($ROOT)) :
      ?>

Your app directory is not writeable. See here.

      <?php endif; ?>

Install Fleet, now, here...

Fill up this form and your installation of fleet will be ready in seconds...

        <form id="installForm" action="installer.php" role="form" method="POST">

            App name
            <input name="appName" type="text" class="form-control" id="appName" placeholder="John's mega app">

            Author name
            <input name="authorName" type="text" class="form-control" id="authorName" placeholder="John Doe">

            App URL
            <input name="appURL" type="text" class="form-control" id="appURL" placeholder="http://youfleetapp.com">

                  <input name="needsDBMS" id="needsDBMS" type="checkbox"> My app needs DBMS

              DBMS type
              <input name="dbType" type="text" class="form-control" id="dbType" placeholder="mysql">

              DBMS host
              <input name="dbHost" type="text" class="form-control" id="dbHost" placeholder="127.0.0.1">

              DBMS username
              <input name="dbUser" type="text" class="form-control" id="dbUser" placeholder="root">

              DBMS password
              <input name="dbPass" type="password" class="form-control" id="dbPass" placeholder="asljfa-af787-sadjfa">

              Database name
              <input name="dbName" type="text" class="form-control" id="dbName" placeholder="myappdbname">

<button class="btn btn-lg btn-success" role="button" type="submit">Install</button>

        </form>

+w

In order to be able to write into your app directory you must set ownership of this directory to the user who's running apache.

Tip

I usually add my user to the same group of apache's user. Doing this I can modify any file belonging to apache easily and without sudo.

0775

It is useful to set permission to 775 in order to avoid writing with sudo and stupid alerts popping up.

What this page does

This page simply writes for you the app.ini file. This file is used by fleet as a configuration file. You can edit app.ini file using this page or any other text editor.

All rights reserved © Matteo Merola 2014


text:
H5.Bootstrapper = (function ($) {
    'use strict';

    var Bootstrapper = {
        build: buildApp,

        // controls - choose [0...n]
        keyBoard: addKeyBoard,
        gamePad: addGamePad,
        pointer: addPointer,
        wheel: addWheel,

        // system-services / device-events - choose [0...n]
        orientation: addScreenOrientation,
        visibility: addPageVisibility,
        fullScreen: addFullScreen,

        // rendering - choose [1]
        atlas: useAtlasRendering,
        fixedRezAtlas: useFixedRezAtlasRendering,
        image: useImageRendering,

        // screen (size) - choose [0...n]
        responsive: addResize,
        lowRez: addLowResolutionRendering,

        // font - choose [0|1]
        font: useFont,
        ejectaFont: useEjectaFont,

        // framework services - choose [0...n]
        analytics: addAnalytics,
        locales: useLocales,
        scenes: useH5Scenes,

        // audio - choose [0|1]
        webAudioSprite: useWebAudioSprite,
        htmlAudio: useHtmlAudio,
        htmlAudioSprite: useHtmlAudioSprite
    };

    // dependencies on screen, therefore flags because you need a screen first (build: screen -> features: with screen)
    var lowRezWidth;
    var lowRezHeight;
    var useLowRez = false;
    var useFullScreen = false;
    var usePointer = false;

    var events;
    var device;
    var removeKeyListener;
    var removeWheelListener;
    var noOneDidAnInit = true;
    var resourceLoadingQueue;

    function initBootstrap() {
        noOneDidAnInit = false;
        useLowRez = false;
        useFullScreen = false;
        usePointer = false;

        events = new $.EventBus();
        device = new $.Device($.userAgent, $.width, $.height, $.getDevicePixelRatio(), $.screenWidth, $.screenHeight);

        resourceLoadingQueue = [];
    }

    function buildApp(installMyScenes, optionalMyCustomResources, optionalCanvas) {
        if (noOneDidAnInit) {
            initBootstrap();
        }

        var screen = useLowRez ?
            $.installCanvas(events, device, optionalCanvas, $.width, $.height, $.getDevicePixelRatio(), lowRezWidth,
                lowRezHeight) :
            $.installCanvas(events, device, optionalCanvas, $.width, $.height, $.getDevicePixelRatio());

        if (useLowRez) {
            device.width = lowRezWidth;
            device.height = lowRezHeight;
            device.isLowRez = true;
        }

        if (useFullScreen) {
            var fs = $.installFullScreen(useLowRez ? screen.scaledScreen : screen.screen, events);
            device.requestFullScreen = fs.request.bind(fs);
            device.isFullScreen = fs.isFullScreen.bind(fs);
            device.isFullScreenSupported = fs.__isSupported.bind(fs);
            device.exitFullScreen = fs.exit.bind(device);
        }

        if (usePointer) {
            $.installPointer(events, device, useLowRez ? screen.scaledScreen : screen.screen);
        }

        var globalServices = {
            screen: screen.screen,
            events: events,
            device: device,
            scaledScreen: screen.scaledScreen
        };

        noOneDidAnInit = true;

        if (optionalMyCustomResources) {
            resourceLoadingQueue.push(optionalMyCustomResources);
        }

        return new $.App(globalServices, resourceLoadingQueue, installMyScenes, removeKeyListener, removeWheelListener);
    }

    function addLowResolutionRendering(width, height) {
        if (noOneDidAnInit) {
            initBootstrap();
        }

        lowRezWidth = width;
        lowRezHeight = height;
        useLowRez = true;
        return Bootstrapper;
    }

    function addScreenOrientation() {
        if (noOneDidAnInit) {
            initBootstrap();
        }

        $.installOrientation(events, device);
        device.lockOrientation = $.OrientationLock.lock;
        device.unlockOrientation = $.OrientationLock.unlock;
        return Bootstrapper;
    }

    function addPageVisibility() {
        if (noOneDidAnInit) {
            initBootstrap();
        }

        $.installVisibility(events, device);
        return Bootstrapper;
    }

    function addFullScreen() {
        if (noOneDidAnInit) {
            initBootstrap();
        }

        useFullScreen = true;
        return Bootstrapper;
    }

    /**
     * @callback mapResize
     * @param {Event} event
     * @returns {Promise} has to be called with adapted data
     */

    /**
     * @param {mapResize} [mapCanvasDimensions] resize callback function
     * @return {Bootstrapper} return this to chain calls
     */
    function addResize(mapCanvasDimensions) {
        if (noOneDidAnInit) {
            initBootstrap();
        }

        $.installResize(events, device, mapCanvasDimensions);
        return Bootstrapper;
    }

    function addKeyBoard() {
        if (noOneDidAnInit) {
            initBootstrap();
        }

        removeKeyListener = $.installKeyBoard(events);
        return Bootstrapper;
    }

    function addWheel() {
        if (noOneDidAnInit) {
            initBootstrap();
        }

        removeWheelListener = $.installWheel(events);
        return Bootstrapper;
    }

    function addGamePad() {
        if (noOneDidAnInit) {
            initBootstrap();
        }

        $.installGamePad(events);
        return Bootstrapper;
    }

    function addPointer() {
        if (noOneDidAnInit) {
            initBootstrap();
        }

        usePointer = true;
        return Bootstrapper;
    }

    function addAnalytics(url, tenantCode, appKeyCode) {
        if (noOneDidAnInit) {
            initBootstrap();
        }

        $.installAnalytics(url, tenantCode, appKeyCode, events);
        return Bootstrapper;
    }

    function useAtlasRendering(registerPaths) {
        if (noOneDidAnInit) {
            initBootstrap();
        }
        $.AtlasLoader.register(registerPaths);
        resourceLoadingQueue.push($.AtlasLoader);
        return Bootstrapper;
    }

    function useEjectaFont(path, name) {
        if (noOneDidAnInit) {
            initBootstrap();
        }
        $.EjectaFontLoader.register(path, name);
        resourceLoadingQueue.push($.EjectaFontLoader);
        return Bootstrapper;
    }

    function useFixedRezAtlasRendering(width, height, optionalBaseName, optionalGfxPath, optionalDataPath,
        optionalGfxExtension, optionalDataExtension) {
        if (noOneDidAnInit) {
            initBootstrap();
        }
        $.FixedRezAtlasLoader.register(width, height, optionalBaseName, optionalGfxPath, optionalDataPath,
            optionalGfxExtension, optionalDataExtension);
        resourceLoadingQueue.push($.FixedRezAtlasLoader);
        return Bootstrapper;
    }

    function useFont(path, name) {
        if (noOneDidAnInit) {
            initBootstrap();
        }
        $.FontLoader.register(path, name);
        resourceLoadingQueue.push($.FontLoader);
        return Bootstrapper;
    }

    function useHtmlAudio(soundNamesToPathsDict, optionalPath, optionalExtension) {
        if (noOneDidAnInit) {
            initBootstrap();
        }
        $.HtmlAudioLoader.register(soundNamesToPathsDict, optionalPath, optionalExtension);
        resourceLoadingQueue.push($.HtmlAudioLoader);
        return Bootstrapper;
    }

    function useHtmlAudioSprite(musicInfoPath, musicPath, sfxInfoPath, sfxPath, sfxTrackCount) {
        if (noOneDidAnInit) {
            initBootstrap();
        }
        $.HtmlAudioSpriteLoader.register(musicInfoPath, musicPath, sfxInfoPath, sfxPath, sfxTrackCount);
        resourceLoadingQueue.push($.HtmlAudioSpriteLoader);
        return Bootstrapper;
    }

    function useImageRendering(notImplementedYet) {
        if (noOneDidAnInit) {
            initBootstrap();
        }
        $.ImageLoader.register(notImplementedYet);
        resourceLoadingQueue.push($.ImageLoader);
        return Bootstrapper;
    }

    function useLocales(path) {
        if (noOneDidAnInit) {
            initBootstrap();
        }
        $.LocalesLoader.register(path);
        resourceLoadingQueue.push($.LocalesLoader);
        return Bootstrapper;
    }

    function useH5Scenes(path) {
        if (noOneDidAnInit) {
            initBootstrap();
        }
        $.SceneLoader.register(path);
        resourceLoadingQueue.push($.SceneLoader);
        return Bootstrapper;
    }

    function useWebAudioSprite(musicInfoPath, musicPath, sfxInfoPath, sfxPath) {
        if (noOneDidAnInit) {
            initBootstrap();
        }
        $.WebAudioSpriteLoader.register(musicInfoPath, musicPath, sfxInfoPath, sfxPath);
        resourceLoadingQueue.push($.WebAudioSpriteLoader);
        return Bootstrapper;
    }

    return Bootstrapper;
})({
    installCanvas: H5.installCanvas,
    installResize: H5.installResize,
    installKeyBoard: H5.installKeyBoard,
    installWheel: H5.installWheel,
    installGamePad: H5.installGamePad,
    installOrientation: H5.installOrientation,
    installFullScreen: H5.installFullScreen,
    installPointer: H5.installPointer,
    installVisibility: H5.installVisibility,
    installAnalytics: H5.installHolmes,
    App: H5.App,
    EventBus: H5.EventBus,
    Device: H5.Device,
    width: window.innerWidth,
    height: window.innerHeight,
    screenWidth: window.screen.availWidth,
    screenHeight: window.screen.availHeight,
    getDevicePixelRatio: H5.getDevicePixelRatio,
    OrientationLock: H5.OrientationLock,
    userAgent: window.navigator.userAgent,
    AtlasLoader: H5.AtlasLoader,
    EjectaFontLoader: H5.EjectaFontLoader,
    FixedRezAtlasLoader: H5.FixedRezAtlasLoader,
    FontLoader: H5.FontLoader,
    HtmlAudioLoader: H5.HtmlAudioLoader,
    HtmlAudioSpriteLoader: H5.HtmlAudioSpriteLoader,
    ImageLoader: H5.ImageLoader,
    LocalesLoader: H5.LocalesLoader,
    SceneLoader: H5.SceneLoader,
    WebAudioSpriteLoader: H5.WebAudioSpriteLoader,
    Error: Error
});


text:
import {BaseHarnessFilters, ContentContainerComponentHarness, HarnessPredicate} from '@angular/cdk/testing';

/** Filters used when searching for the harness component. */
export interface ResultAccordionHarnessFilters extends BaseHarnessFilters {}

/** Harness used for tests involving the result-accordion component. */
export class ResultAccordionHarness extends ContentContainerComponentHarness {
  static hostSelector = 'result-accordion';

  private readonly getHeader = this.locatorFor('.header');

  static with(options: ResultAccordionHarnessFilters):
      HarnessPredicate<ResultAccordionHarness> {
    return new HarnessPredicate(ResultAccordionHarness, options);
  }

  async toggle(): Promise<void> {
    const header = await this.getHeader();
    await header.click();
  }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Lecaniocola putnamii Brain

### Remarks
null


text:
<!DOCTYPE html>

    <link rel="stylesheet" type="text/css" href="./bower_components/bootstrap-css-only/css/bootstrap.css">
    <link rel="stylesheet" type="text/css" href="./src/style.css">
    <meta charset='UTF-8'>

    <title>ng-Fx</title>

Animations

              {{ animation }}

Scott Moss

ng-Fx

options

                Easings

                    {{ ease }}

                  Speed

                      {{ speed }} ms

              <card class='col-xs-6 col-md-1 {{ "fx-"+demo.mainAnimation }} fx-speed-{{ demo.speed || 500 }} fx-trigger fx-easing-{{ demo.ease }}' ng-repeat='card in demo.cards | filter:search' ng-click='demo.removeCard($index)'title='{{ card.header }}'>

                  Animation: {{ card.type }}

              </card>


text:
import React from 'react';
import { View } from 'react-native';

const CardSection = (props) => (
  <View style={styles.containerStyle}>
    {props.children}
  </View>
);

const styles = {
  containerStyle: {
    borderBottomWidth: 1,
    padding: 5,
    backgroundColor: '#fff',
    justifyContent: 'flex-start',
    flexDirection: 'row',
    borderColor: '#ddd',
    position: 'relative'
  }
};

export { CardSection };


text:
from iptest.assert_util import *
skiptest("win32")

# our built in types shouldn't show CLS methods

AreEqual(hasattr(object, 'ToString'), False)
AreEqual(dir(object).count('ToString'), 0)
AreEqual(vars(object).keys().count('ToString'), 0)

AreEqual(hasattr('abc', 'ToString'), False)
AreEqual(dir('abc').count('ToString'), 0)
AreEqual(vars(str).keys().count('ToString'), 0)

AreEqual(hasattr([], 'ToString'), False)
AreEqual(dir([]).count('ToString'), 0)
AreEqual(vars(list).keys().count('ToString'), 0)

import System

if not is_silverlight:
    # but CLS types w/o the attribute should....
    AreEqual(hasattr(System.Environment, 'ToString'), True)
    AreEqual(dir(System.Environment).count('ToString'), 1)
    # vars only shows members declared in the type, so it won't be there either
    AreEqual(vars(System.Environment).keys().count('ToString'), 0)

# and importing clr should show them all...
import clr

AreEqual(hasattr(object, 'ToString'), True)
AreEqual(dir(object).count('ToString'), 1)
AreEqual(vars(object).keys().count('ToString'), 1)

AreEqual(hasattr('abc', 'ToString'), True)
AreEqual(dir('abc').count('ToString'), 1)
AreEqual(vars(str).keys().count('ToString'), 1) # string overrides ToString

AreEqual(hasattr([], 'ToString'), True)
AreEqual(dir([]).count('ToString'), 1)
AreEqual(vars(list).keys().count('ToString'), 0) # list doesn't override ToString

if not is_silverlight:
    # and they should still show up on system.
    AreEqual(hasattr(System.Environment, 'ToString'), True)
    AreEqual(dir(System.Environment).count('ToString'), 1)
    AreEqual(vars(System.Environment).keys().count('ToString'), 0)

# eval should flow it's context
a = "hello world"
c = compile("x = a.Split(' ')", "<string>", "single")
eval(c)
AreEqual(x[0], "hello")
AreEqual(x[1], "world")

y = eval("a.Split(' ')")
AreEqual(y[0], "hello")
AreEqual(y[1], "world")


text:
<?php
use Casperlaitw\LaravelFbMessenger\Exceptions\UnknownTypeException;
use Casperlaitw\LaravelFbMessenger\Messages\Button;

/**
 * User: casperlai
 * Date: 2016/9/16
 * Time: 上午12:51
 */
class ButtonTest extends TestCase
{
    public function test_share_button()
    {
        $button = new Button(Button::TYPE_SHARE, '');
        $expected = [
            'type' => 'element_share',
        ];
        $this->assertEquals($expected, $button->toData());
    }

    public function test_unknown_type_button()
    {
        $this->expectException(UnknownTypeException::class);

        $button = new Button('unknown', '');
        $button->toData();
    }

    public function test_set_extra()
    {
        $button = new Button(Button::TYPE_WEB, 'title', 'url');
        $button->setExtra(['extra' => 'test']);

        $expected = [
            'type' => 'web_url',
            'title' => 'title',
            'url' => 'url',
            'extra' => 'test',
        ];

        $this->assertEquals($expected, $button->toData());
    }

    public function test_get_type()
    {
        $button = new Button(Button::TYPE_POSTBACK, 'title', 'payload');

        $this->assertEquals('postback', $button->getType());
    }

    public function test_account_type_button()
    {
        $url = 'https://www.example.com/authorize';
        $button = new Button(Button::TYPE_ACCOUNT_LINK, null, $url);
        $expected = [
            'type' => 'account_link',
            'url' => $url,
        ];

        $this->assertEquals($expected, $button->toData());
    }
}


text:
<Record>
<Term>Bibenzonium</Term>
<SemanticType>Pharmacologic Substance</SemanticType>
<ParentTerm>Antitussive Agent</ParentTerm>
<ClassificationPath>Chemicals_and_Drugs_Kind/Drug, Food, Chemical or Biomedical Material/Pharmacologic Substance/Adjuvant/Antitussive Agent/Bibenzonium Bromide</ClassificationPath>
<ClassificationPath>Chemicals_and_Drugs_Kind/Drug, Food, Chemical or Biomedical Material/Pharmacologic Substance/Adjuvant/Antitussive Agent/Bibenzonium</ClassificationPath>
<BroaderTerm>Chemicals_and_Drugs_Kind</BroaderTerm>
<BroaderTerm>Pharmacologic Substance</BroaderTerm>
<BroaderTerm>Adjuvant</BroaderTerm>
<BroaderTerm>Bibenzonium Bromide</BroaderTerm>
<BroaderTerm>Antitussive Agent</BroaderTerm>
<BroaderTerm>Bibenzonium</BroaderTerm>
<BroaderTerm>Drug, Food, Chemical or Biomedical Material</BroaderTerm>
<Synonym>BIBENZONIUM</Synonym>
<Synonym>BIBENZONIUM BROMIDE</Synonym>
<Synonym>Bibenzonium Bromide</Synonym>
<Synonym>Bibenzonium</Synonym>
<Source>NCI Thesaurus</Source>
</Record>


text:
namespace aura {
class Window;
}  // namespace aura

namespace ui {
class ImplicitAnimationObserver;
class LayerAnimator;
class ScopedLayerAnimationSettings;
}  // namespace ui

namespace ash {

// ScopedOverviewAnimationSettings correctly configures the animation
// settings for an aura::Window or ui::LayerAnimator given an
// OverviewAnimationType.
class ScopedOverviewAnimationSettings {
 public:
  ScopedOverviewAnimationSettings(OverviewAnimationType animation_type,
                                  aura::Window* window);
  ScopedOverviewAnimationSettings(OverviewAnimationType animation_type,
                                  ui::LayerAnimator* animator);

  ScopedOverviewAnimationSettings(const ScopedOverviewAnimationSettings&) =
      delete;
  ScopedOverviewAnimationSettings& operator=(
      const ScopedOverviewAnimationSettings&) = delete;

  ~ScopedOverviewAnimationSettings();
  void AddObserver(ui::ImplicitAnimationObserver* observer);
  void CacheRenderSurface();
  void DeferPaint();
  void TrilinearFiltering();
  ui::LayerAnimator* GetAnimator();

 private:
  // The managed animation settings.
  std::unique_ptr<ui::ScopedLayerAnimationSettings> animation_settings_;

  // Report smoothness of close animation.
  absl::optional<ui::AnimationThroughputReporter> close_reporter_;
};

}  // namespace ash

#endif  // ASH_WM_OVERVIEW_SCOPED_OVERVIEW_ANIMATION_SETTINGS_H_


text:
@protocol ComGoodowRealtimeChannelBus;
@protocol ComGoodowRealtimeCoreHandler;

#include "J2ObjC_header.h"

@protocol ComGoodowRealtimeStoreStore < NSObject, JavaObject >

- (void)close;

- (id<ComGoodowRealtimeChannelBus>)getBus;

- (void)load__WithNSString:(NSString *)id_
withComGoodowRealtimeCoreHandler:(id<ComGoodowRealtimeCoreHandler>)onLoaded
withComGoodowRealtimeCoreHandler:(id<ComGoodowRealtimeCoreHandler>)opt_initializer
withComGoodowRealtimeCoreHandler:(id<ComGoodowRealtimeCoreHandler>)opt_error;

@end

J2OBJC_EMPTY_STATIC_INIT(ComGoodowRealtimeStoreStore)

J2OBJC_TYPE_LITERAL_HEADER(ComGoodowRealtimeStoreStore)

#endif // _ComGoodowRealtimeStoreStore_H_


text:
from openerp.osv import fields, osv
from openerp.tools.translate import _

from openerp.tools import DEFAULT_SERVER_DATE_FORMAT, DEFAULT_SERVER_DATETIME_FORMAT, float_compare, float_round
from openerp import SUPERUSER_ID
from dateutil.relativedelta import relativedelta
from datetime import datetime
from psycopg2 import OperationalError
import openerp

class procurement_group(osv.osv):
    _inherit = 'procurement.group'
    _columns = {
        'partner_id': fields.many2one('res.partner', 'Partner')
    }

class procurement_rule(osv.osv):
    _inherit = 'procurement.rule'

    def _get_action(self, cr, uid, context=None):
        result = super(procurement_rule, self)._get_action(cr, uid, context=context)
        return result + [('move', _('Move From Another Location'))]

    def _get_rules(self, cr, uid, ids, context=None):
        res = []
        for route in self.browse(cr, uid, ids):
            res += [x.id for x in route.pull_ids]
        return res

    _columns = {
        'location_id': fields.many2one('stock.location', 'Procurement Location'),
        'location_src_id': fields.many2one('stock.location', 'Source Location',
            help="Source location is action=move"),
        'route_id': fields.many2one('stock.location.route', 'Route',
            help="If route_id is False, the rule is global"),
        'procure_method': fields.selection([('make_to_stock', 'Take From Stock'), ('make_to_order', 'Create Procurement')], 'Move Supply Method', required=True,
                                           help="""Determines the procurement method of the stock move that will be generated: whether it will need to 'take from the available stock' in its source location or needs to ignore its stock and create a procurement over there."""),
        'route_sequence': fields.related('route_id', 'sequence', string='Route Sequence',
            store={
                'stock.location.route': (_get_rules, ['sequence'], 10),
                'procurement.rule': (lambda self, cr, uid, ids, c={}: ids, ['route_id'], 10),
        }),
        'picking_type_id': fields.many2one('stock.picking.type', 'Picking Type',
            help="Picking Type determines the way the picking should be shown in the view, reports, ..."),
        'delay': fields.integer('Number of Days'),
        'partner_address_id': fields.many2one('res.partner', 'Partner Address'),
        'propagate': fields.boolean('Propagate cancel and split', help='If checked, when the previous move of the move (which was generated by a next procurement) is cancelled or split, the move generated by this move will too'),
        'warehouse_id': fields.many2one('stock.warehouse', 'Served Warehouse', help='The warehouse this rule is for'),
        'propagate_warehouse_id': fields.many2one('stock.warehouse', 'Warehouse to Propagate', help="The warehouse to propagate on the created move/procurement, which can be different of the warehouse this rule is for (e.g for resupplying rules from another warehouse)"),
    }

    _defaults = {
        'procure_method': 'make_to_stock',
        'propagate': True,
        'delay': 0,
    }

class procurement_order(osv.osv):
    _inherit = "procurement.order"
    _columns = {
        'location_id': fields.many2one('stock.location', 'Procurement Location'),  # not required because task may create procurements that aren't linked to a location with sale_service
        'partner_dest_id': fields.many2one('res.partner', 'Customer Address', help="In case of dropshipping, we need to know the destination address more precisely"),
        'move_ids': fields.one2many('stock.move', 'procurement_id', 'Moves', help="Moves created by the procurement"),
        'move_dest_id': fields.many2one('stock.move', 'Destination Move', help="Move which caused (created) the procurement"),
        'route_ids': fields.many2many('stock.location.route', 'stock_location_route_procurement', 'procurement_id', 'route_id', 'Preferred Routes', help="Preferred route to be followed by the procurement order. Usually copied from the generating document (SO) but could be set up manually."),
        'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse', help="Warehouse to consider for the route selection"),
        'orderpoint_id': fields.many2one('stock.warehouse.orderpoint', 'Minimum Stock Rule'),
    }

    def propagate_cancel(self, cr, uid, procurement, context=None):
        if procurement.rule_id.action == 'move' and procurement.move_ids:
            self.pool.get('stock.move').action_cancel(cr, uid, [m.id for m in procurement.move_ids], context=context)

    def cancel(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        to_cancel_ids = self.get_cancel_ids(cr, uid, ids, context=context)
        ctx = context.copy()
        #set the context for the propagation of the procurement cancelation
        ctx['cancel_procurement'] = True
        for procurement in self.browse(cr, uid, to_cancel_ids, context=ctx):
            self.propagate_cancel(cr, uid, procurement, context=ctx)
        return super(procurement_order, self).cancel(cr, uid, to_cancel_ids, context=ctx)

    def _find_parent_locations(self, cr, uid, procurement, context=None):
        location = procurement.location_id
        res = [location.id]
        while location.location_id:
            location = location.location_id
            res.append(location.id)
        return res

    def change_warehouse_id(self, cr, uid, ids, warehouse_id, context=None):
        if warehouse_id:
            warehouse = self.pool.get('stock.warehouse').browse(cr, uid, warehouse_id, context=context)
            return {'value': {'location_id': warehouse.lot_stock_id.id}}
        return {}

    def _search_suitable_rule(self, cr, uid, procurement, domain, context=None):
        '''we try to first find a rule among the ones defined on the procurement order group and if none is found, we try on the routes defined for the product, and finally we fallback on the default behavior'''
        pull_obj = self.pool.get('procurement.rule')
        warehouse_route_ids = []
        if procurement.warehouse_id:
            domain += ['|', ('warehouse_id', '=', procurement.warehouse_id.id), ('warehouse_id', '=', False)]
            warehouse_route_ids = [x.id for x in procurement.warehouse_id.route_ids]
        product_route_ids = [x.id for x in procurement.product_id.route_ids + procurement.product_id.categ_id.total_route_ids]
        procurement_route_ids = [x.id for x in procurement.route_ids]
        res = pull_obj.search(cr, uid, domain + [('route_id', 'in', procurement_route_ids)], order='route_sequence, sequence', context=context)
        if not res:
            res = pull_obj.search(cr, uid, domain + [('route_id', 'in', product_route_ids)], order='route_sequence, sequence', context=context)
            if not res:
                res = warehouse_route_ids and pull_obj.search(cr, uid, domain + [('route_id', 'in', warehouse_route_ids)], order='route_sequence, sequence', context=context) or []
                if not res:
                    res = pull_obj.search(cr, uid, domain + [('route_id', '=', False)], order='sequence', context=context)
        return res

    def _find_suitable_rule(self, cr, uid, procurement, context=None):
        rule_id = super(procurement_order, self)._find_suitable_rule(cr, uid, procurement, context=context)
        if not rule_id:
            #a rule defined on 'Stock' is suitable for a procurement in 'Stock\Bin A'
            all_parent_location_ids = self._find_parent_locations(cr, uid, procurement, context=context)
            rule_id = self._search_suitable_rule(cr, uid, procurement, [('location_id', 'in', all_parent_location_ids)], context=context)
            rule_id = rule_id and rule_id[0] or False
        return rule_id

    def _run_move_create(self, cr, uid, procurement, context=None):
        ''' Returns a dictionary of values that will be used to create a stock move from a procurement.
        This function assumes that the given procurement has a rule (action == 'move') set on it.

        :param procurement: browse record
        :rtype: dictionary
        '''
        newdate = (datetime.strptime(procurement.date_planned, '%Y-%m-%d %H:%M:%S') - relativedelta(days=procurement.rule_id.delay or 0)).strftime('%Y-%m-%d %H:%M:%S')
        group_id = False
        if procurement.rule_id.group_propagation_option == 'propagate':
            group_id = procurement.group_id and procurement.group_id.id or False
        elif procurement.rule_id.group_propagation_option == 'fixed':
            group_id = procurement.rule_id.group_id and procurement.rule_id.group_id.id or False
        #it is possible that we've already got some move done, so check for the done qty and create
        #a new move with the correct qty
        already_done_qty = 0
        already_done_qty_uos = 0
        for move in procurement.move_ids:
            already_done_qty += move.product_uom_qty if move.state == 'done' else 0
            already_done_qty_uos += move.product_uos_qty if move.state == 'done' else 0
        qty_left = max(procurement.product_qty - already_done_qty, 0)
        qty_uos_left = max(procurement.product_uos_qty - already_done_qty_uos, 0)
        vals = {
            'name': procurement.name,
            'company_id': procurement.rule_id.company_id.id or procurement.rule_id.location_src_id.company_id.id or procurement.rule_id.location_id.company_id.id or procurement.company_id.id,
            'product_id': procurement.product_id.id,
            'product_uom': procurement.product_uom.id,
            'product_uom_qty': qty_left,
            'product_uos_qty': (procurement.product_uos and qty_uos_left) or qty_left,
            'product_uos': (procurement.product_uos and procurement.product_uos.id) or procurement.product_uom.id,
            'partner_id': procurement.rule_id.partner_address_id.id or (procurement.group_id and procurement.group_id.partner_id.id) or False,
            'location_id': procurement.rule_id.location_src_id.id,
            'location_dest_id': procurement.location_id.id,
            'move_dest_id': procurement.move_dest_id and procurement.move_dest_id.id or False,
            'procurement_id': procurement.id,
            'rule_id': procurement.rule_id.id,
            'procure_method': procurement.rule_id.procure_method,
            'origin': procurement.origin,
            'picking_type_id': procurement.rule_id.picking_type_id.id,
            'group_id': group_id,
            'route_ids': [(4, x.id) for x in procurement.route_ids],
            'warehouse_id': procurement.rule_id.propagate_warehouse_id.id or procurement.rule_id.warehouse_id.id,
            'date': newdate,
            'date_expected': newdate,
            'propagate': procurement.rule_id.propagate,
            'priority': procurement.priority,
        }
        return vals

    def _run(self, cr, uid, procurement, context=None):
        if procurement.rule_id and procurement.rule_id.action == 'move':
            if not procurement.rule_id.location_src_id:
                self.message_post(cr, uid, [procurement.id], body=_('No source location defined!'), context=context)
                return False
            move_obj = self.pool.get('stock.move')
            move_dict = self._run_move_create(cr, uid, procurement, context=context)
            #create the move as SUPERUSER because the current user may not have the rights to do it (mto product launched by a sale for example)
            move_obj.create(cr, SUPERUSER_ID, move_dict, context=context)
            return True
        return super(procurement_order, self)._run(cr, uid, procurement, context=context)

    def run(self, cr, uid, ids, autocommit=False, context=None):
        new_ids = [x.id for x in self.browse(cr, uid, ids, context=context) if x.state not in ('running', 'done', 'cancel')]
        res = super(procurement_order, self).run(cr, uid, new_ids, autocommit=autocommit, context=context)

        #after all the procurements are run, check if some created a draft stock move that needs to be confirmed
        #(we do that in batch because it fasts the picking assignation and the picking state computation)
        move_to_confirm_ids = []
        for procurement in self.browse(cr, uid, new_ids, context=context):
            if procurement.state == "running" and procurement.rule_id and procurement.rule_id.action == "move":
                move_to_confirm_ids += [m.id for m in procurement.move_ids if m.state == 'draft']
        if move_to_confirm_ids:
            self.pool.get('stock.move').action_confirm(cr, uid, move_to_confirm_ids, context=context)
        return res

    def _check(self, cr, uid, procurement, context=None):
        ''' Implement the procurement checking for rules of type 'move'. The procurement will be satisfied only if all related
            moves are done/cancel and if the requested quantity is moved.
        '''
        if procurement.rule_id and procurement.rule_id.action == 'move':
            uom_obj = self.pool.get('product.uom')
            # In case Phantom BoM splits only into procurements
            if not procurement.move_ids:
                return True
            cancel_test_list = [x.state == 'cancel' for x in procurement.move_ids]
            done_cancel_test_list = [x.state in ('done', 'cancel') for x in procurement.move_ids]
            at_least_one_cancel = any(cancel_test_list)
            all_done_or_cancel = all(done_cancel_test_list)
            all_cancel = all(cancel_test_list)
            if not all_done_or_cancel:
                return False
            elif all_done_or_cancel and not all_cancel:
                return True
            elif all_cancel:
                self.message_post(cr, uid, [procurement.id], body=_('All stock moves have been cancelled for this procurement.'), context=context)
            self.write(cr, uid, [procurement.id], {'state': 'cancel'}, context=context)
            return False

        return super(procurement_order, self)._check(cr, uid, procurement, context)

    def do_view_pickings(self, cr, uid, ids, context=None):
        '''
        This function returns an action that display the pickings of the procurements belonging
        to the same procurement group of given ids.
        '''
        mod_obj = self.pool.get('ir.model.data')
        act_obj = self.pool.get('ir.actions.act_window')
        result = mod_obj.get_object_reference(cr, uid, 'stock', 'do_view_pickings')
        id = result and result[1] or False
        result = act_obj.read(cr, uid, [id], context=context)[0]
        group_ids = set([proc.group_id.id for proc in self.browse(cr, uid, ids, context=context) if proc.group_id])
        result['domain'] = "[('group_id','in',[" + ','.join(map(str, list(group_ids))) + "])]"
        return result

    def run_scheduler(self, cr, uid, use_new_cursor=False, company_id=False, context=None):
        '''
        Call the scheduler in order to check the running procurements (super method), to check the minimum stock rules
        and the availability of moves. This function is intended to be run for all the companies at the same time, so
        we run functions as SUPERUSER to avoid intercompanies and access rights issues.

        @param self: The object pointer
        @param cr: The current row, from the database cursor,
        @param uid: The current user ID for security checks
        @param ids: List of selected IDs
        @param use_new_cursor: if set, use a dedicated cursor and auto-commit after processing each procurement.
            This is appropriate for batch jobs only.
        @param context: A standard dictionary for contextual values
        @return:  Dictionary of values
        '''
        super(procurement_order, self).run_scheduler(cr, uid, use_new_cursor=use_new_cursor, company_id=company_id, context=context)
        if context is None:
            context = {}
        try:
            if use_new_cursor:
                cr = openerp.registry(cr.dbname).cursor()

            move_obj = self.pool.get('stock.move')

            #Minimum stock rules
            self._procure_orderpoint_confirm(cr, SUPERUSER_ID, use_new_cursor=use_new_cursor, company_id=company_id, context=context)

            #Search all confirmed stock_moves and try to assign them
            confirmed_ids = move_obj.search(cr, uid, [('state', '=', 'confirmed')], limit=None, order='priority desc, date_expected asc', context=context)
            for x in xrange(0, len(confirmed_ids), 100):
                move_obj.action_assign(cr, uid, confirmed_ids[x:x + 100], context=context)
                if use_new_cursor:
                    cr.commit()

            if use_new_cursor:
                cr.commit()
        finally:
            if use_new_cursor:
                try:
                    cr.close()
                except Exception:
                    pass
        return {}

    def _get_orderpoint_date_planned(self, cr, uid, orderpoint, start_date, context=None):
        date_planned = start_date + relativedelta(days=orderpoint.product_id.seller_delay or 0.0)
        return date_planned.strftime(DEFAULT_SERVER_DATE_FORMAT)

    def _prepare_orderpoint_procurement(self, cr, uid, orderpoint, product_qty, context=None):
        return {
            'name': orderpoint.name,
            'date_planned': self._get_orderpoint_date_planned(cr, uid, orderpoint, datetime.today(), context=context),
            'product_id': orderpoint.product_id.id,
            'product_qty': product_qty,
            'company_id': orderpoint.company_id.id,
            'product_uom': orderpoint.product_uom.id,
            'location_id': orderpoint.location_id.id,
            'origin': orderpoint.name,
            'warehouse_id': orderpoint.warehouse_id.id,
            'orderpoint_id': orderpoint.id,
            'group_id': orderpoint.group_id.id,
        }

    def _product_virtual_get(self, cr, uid, order_point):
        product_obj = self.pool.get('product.product')
        return product_obj._product_available(cr, uid,
                [order_point.product_id.id],
                context={'location': order_point.location_id.id})[order_point.product_id.id]['virtual_available']

    def _procure_orderpoint_confirm(self, cr, uid, use_new_cursor=False, company_id = False, context=None):
        '''
        Create procurement based on Orderpoint

        :param bool use_new_cursor: if set, use dedicated cursors and auto-commit after processing
            100 orderpoints.
            This is appropriate for batch jobs only.
        '''
        if context is None:
            context = {}
        orderpoint_obj = self.pool.get('stock.warehouse.orderpoint')

        procurement_obj = self.pool.get('procurement.order')
        dom = company_id and [('company_id', '=', company_id)] or []
        orderpoint_ids = orderpoint_obj.search(cr, uid, dom, context=context)
        prev_ids = []
        while orderpoint_ids:
            ids = orderpoint_ids[:100]
            del orderpoint_ids[:100]
            if use_new_cursor:
                cr = openerp.registry(cr.dbname).cursor()
            for op in orderpoint_obj.browse(cr, uid, ids, context=context):
                try:
                    prods = self._product_virtual_get(cr, uid, op)
                    if prods is None:
                        continue
                    if float_compare(prods, op.product_min_qty, precision_rounding=op.product_uom.rounding) < 0:
                        qty = max(op.product_min_qty, op.product_max_qty) - prods
                        reste = op.qty_multiple > 0 and qty % op.qty_multiple or 0.0
                        if float_compare(reste, 0.0, precision_rounding=op.product_uom.rounding) > 0:
                            qty += op.qty_multiple - reste

                        if float_compare(qty, 0.0, precision_rounding=op.product_uom.rounding) <= 0:
                            continue

                        qty -= orderpoint_obj.subtract_procurements(cr, uid, op, context=context)

                        qty_rounded = float_round(qty, precision_rounding=op.product_uom.rounding)
                        if qty_rounded > 0:
                            proc_id = procurement_obj.create(cr, uid,
                                                             self._prepare_orderpoint_procurement(cr, uid, op, qty_rounded, context=context),
                                                             context=context)
                            self.check(cr, uid, [proc_id], context=context)
                            self.run(cr, uid, [proc_id], context=context)
                    if use_new_cursor:
                        cr.commit()
                except OperationalError:
                    if use_new_cursor:
                        orderpoint_ids.append(op.id)
                        cr.rollback()
                        continue
                    else:
                        raise
            if use_new_cursor:
                cr.commit()
                cr.close()
            if prev_ids == ids:
                break
            else:
                prev_ids = ids

        return {}


text:
package com.violetgo.jediscli;

/**
 * @author weigao
 * @since 15/8/18
 */
public class JedisCliException extends Exception {
    public JedisCliException(String message) {
        super(message);
    }

    public JedisCliException(String message, Throwable throwable) {
        super(message, throwable);
    }
}


text:
<?php

/**
 * The "managedZones" collection of methods.
 * Typical usage is:
 *  <code>
 *   $dnsService = new Google_Service_Dns(...);
 *   $managedZones = $dnsService->managedZones;
 *  </code>
 */
class Google_Service_Dns_Resource_ManagedZones extends Google_Service_Resource
{
  /**
   * (managedZones.create)
   *
   * @param string $project
   * @param Google_Service_Dns_ManagedZone $postBody
   * @param array $optParams Optional parameters.
   *
   * @opt_param string clientOperationId
   * @return Google_Service_Dns_ManagedZone
   */
  public function create($project, Google_Service_Dns_ManagedZone $postBody, $optParams = array())
  {
    $params = array('project' => $project, 'postBody' => $postBody);
    $params = array_merge($params, $optParams);
    return $this->call('create', array($params), "Google_Service_Dns_ManagedZone");
  }
  /**
   * (managedZones.delete)
   *
   * @param string $project
   * @param string $managedZone
   * @param array $optParams Optional parameters.
   *
   * @opt_param string clientOperationId
   */
  public function delete($project, $managedZone, $optParams = array())
  {
    $params = array('project' => $project, 'managedZone' => $managedZone);
    $params = array_merge($params, $optParams);
    return $this->call('delete', array($params));
  }
  /**
   * (managedZones.get)
   *
   * @param string $project
   * @param string $managedZone
   * @param array $optParams Optional parameters.
   *
   * @opt_param string clientOperationId
   * @return Google_Service_Dns_ManagedZone
   */
  public function get($project, $managedZone, $optParams = array())
  {
    $params = array('project' => $project, 'managedZone' => $managedZone);
    $params = array_merge($params, $optParams);
    return $this->call('get', array($params), "Google_Service_Dns_ManagedZone");
  }
  /**
   * (managedZones.listManagedZones)
   *
   * @param string $project
   * @param array $optParams Optional parameters.
   *
   * @opt_param string dnsName
   * @opt_param int maxResults
   * @opt_param string pageToken
   * @return Google_Service_Dns_ManagedZonesListResponse
   */
  public function listManagedZones($project, $optParams = array())
  {
    $params = array('project' => $project);
    $params = array_merge($params, $optParams);
    return $this->call('list', array($params), "Google_Service_Dns_ManagedZonesListResponse");
  }
  /**
   * (managedZones.patch)
   *
   * @param string $project
   * @param string $managedZone
   * @param Google_Service_Dns_ManagedZone $postBody
   * @param array $optParams Optional parameters.
   *
   * @opt_param string clientOperationId
   * @return Google_Service_Dns_Operation
   */
  public function patch($project, $managedZone, Google_Service_Dns_ManagedZone $postBody, $optParams = array())
  {
    $params = array('project' => $project, 'managedZone' => $managedZone, 'postBody' => $postBody);
    $params = array_merge($params, $optParams);
    return $this->call('patch', array($params), "Google_Service_Dns_Operation");
  }
  /**
   * (managedZones.update)
   *
   * @param string $project
   * @param string $managedZone
   * @param Google_Service_Dns_ManagedZone $postBody
   * @param array $optParams Optional parameters.
   *
   * @opt_param string clientOperationId
   * @return Google_Service_Dns_Operation
   */
  public function update($project, $managedZone, Google_Service_Dns_ManagedZone $postBody, $optParams = array())
  {
    $params = array('project' => $project, 'managedZone' => $managedZone, 'postBody' => $postBody);
    $params = array_merge($params, $optParams);
    return $this->call('update', array($params), "Google_Service_Dns_Operation");
  }
}


text:
ReactionCore.MethodHooks.beforeMethods({
  "orders/inventoryAdjust": function (options) {
    check(options.arguments, [Match.Any]);
    const orderId = options.arguments[0];
    if (!orderId) { return true; }

    Meteor.call("rentalProducts/inventoryAdjust", orderId);

    return options;
    // Returned false before, but there is no longer an `adjust inventory method in core`
    // so this is probably never called any more.
  }
});

ReactionCore.MethodHooks.afterMethods({
  "cart/addToCart": function (options) {
    check(options.arguments[0], String);
    check(options.arguments[1], String);
    const variantId = options.arguments[1];
    const cart = ReactionCore.Collections.Cart.findOne({ userId: Meteor.userId() });
    if (!cart) {
      return options;
    }
    if (cart.items && cart.items.length > 0) {
      _.map(cart.items, function (item) {
        if (item.variants._id === variantId
          && (item.variants.functionalType === "rentalVariant"
            || item.variants.functionalType === "bundleVariant") // TODO: future if item.type === rental
          && cart.rentalDays) {
            // TODO: update qty to verified rental qty available
          // Set price to calculated rental price;
          let priceBucket = _.find(item.variants.rentalPriceBuckets, (bucket) => {
            return bucket.duration === cart.rentalDays;
          });
          if (priceBucket) {
            item.variants.price = priceBucket.price;
          } else {
            // remove from cart
            // Throw error
          }
        }
        return item;
      });
    } else {
      cart.items = [];
    }

    ReactionCore.Collections.Cart.update({
      _id: cart._id
    }, {
      $set: {
        items: cart.items
      }
    });
    return options; // Continue with other hooks;
    // was returning true before. After chatting with @paulgrever we decided it was proabably better to return
    // the options object
  }
});


text:
final project for udacity ud858 course

## Products
- [App Engine][1]

## Language
- [Python][2]

## APIs
- [Google Cloud Endpoints][3]

## Setup Instructions
1. Update the value of `application` in `app.yaml` to the app ID you
   have registered in the App Engine admin console and would like to use to host
   your instance of this sample.
1. Update the values at the top of `settings.py` to
   reflect the respective client IDs you have registered in the
   [Developer Console][4].
1. Update the value of CLIENT_ID in `static/js/app.js` to the Web client ID
1. (Optional) Mark the configuration files as unchanged as follows:
   `$ git update-index --assume-unchanged app.yaml settings.py static/js/app.js`
1. Run the app with the devserver using `dev_appserver.py DIR`, and ensure it's running by visiting your local server's address (by default [localhost:8080][5].)
1. (Optional) Generate your client library(ies) with [the endpoints tool][6].
1. Deploy your application.

## Task 1: Add Sessions to a Conference
####Explain your design choices
For session implementation I largely follow the instruction by defining a Session ndb.Model and a SessionForm message object. I also wrote several helper functions similar to help retrieving and creating session and speaker records

For speaker implementation I decided to use speaker name as a string to represent a speaker, so no speaker model is created. This approach has several severe flaws such as name collision and you can't store additional info about the speaker. The biggest advantage is that it is dead simple to implement, and this is why i am taking this approach. Should this approach really become a problem, we can always change it in V2.

##Task 3: Work on indexes and queries
####Come up with 2 additional queries
```
# conference that took place in SF or Tokyo
conferences = Conference.query(ndb.OR(Conference.city == 'Tokyo',
                                      Conference.city == 'Paris'))
```

```
# top 5 most anticipated conferences (by # of wishlisted sessions)
@ndb.tasklet
def callback(conference):
    count = yield WishlistSession.query(WishlistSession.sessionConferenceKey == conference.key.urlsafe()).count_async()
    raise ndb.Return((count, conference))

for count, conf in sorted(Conference.query().map(callback), key=lambda tup: tup[0], reverse=True)[:5]:
    print '{} - ({})'.format(conf.name, count)
```

####Solve the following query related problem
```
seven_pm = datetime.datetime.strptime("19:00", "%H:%M").time()
anything_but_workshop = ['NOT_SPECIFIED', 'LECTURE', 'KEYNOTE']
for session in Session.query(ndb.AND(Session.typeOfSession.IN(anything_but_workshop),
                                     Session.startTime < seven_pm)):
    print '{} - {} - {}'.format(session.name, session.typeOfSession,
                                session.startTime.strftime("%H:%M"))
```
This is one way I can think of to accomplish said requirement. The main obstacle is that this query requires two inequalities comparsion that is not allowed by ndb api.

I would also try just filter out sessions after 7pm, and then iterate the results to remove any WORKSHOP sessions. I would then use benchmark tools like AppStats to compare the performance.

This kind of complexity queries with multiple inequality operators and/or groups, is probably best to use MapReduce to solve.

[1]: https://developers.google.com/appengine
[2]: http://python.org
[3]: https://developers.google.com/appengine/docs/python/endpoints/
[4]: https://console.developers.google.com/
[5]: https://localhost:8080/
[6]: https://developers.google.com/appengine/docs/python/endpoints/endpoints_tool


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Agronomía trop. 9: 293 (1954)

#### Original name
Physalospora sorghiphila Saccas

### Remarks
null


text:
package array

import (
	"sync/atomic"

	"github.com/apache/arrow/go/arrow"
	"github.com/apache/arrow/go/arrow/bitutil"
	"github.com/apache/arrow/go/arrow/float16"
	"github.com/apache/arrow/go/arrow/internal/debug"
	"github.com/apache/arrow/go/arrow/memory"
)

type Float16Builder struct {
	builder

	data    *memory.Buffer
	rawData []float16.Num
}

func NewFloat16Builder(mem memory.Allocator) *Float16Builder {
	return &Float16Builder{builder: builder{refCount: 1, mem: mem}}
}

// Release decreases the reference count by 1.
// When the reference count goes to zero, the memory is freed.
func (b *Float16Builder) Release() {
	debug.Assert(atomic.LoadInt64(&b.refCount) > 0, "too many releases")

	if atomic.AddInt64(&b.refCount, -1) == 0 {
		if b.nullBitmap != nil {
			b.nullBitmap.Release()
			b.nullBitmap = nil
		}
		if b.data != nil {
			b.data.Release()
			b.data = nil
			b.rawData = nil
		}
	}
}

func (b *Float16Builder) Append(v float16.Num) {
	b.Reserve(1)
	b.UnsafeAppend(v)
}

func (b *Float16Builder) UnsafeAppend(v float16.Num) {
	bitutil.SetBit(b.nullBitmap.Bytes(), b.length)
	b.rawData[b.length] = v
	b.length++
}

func (b *Float16Builder) AppendNull() {
	b.Reserve(1)
	b.UnsafeAppendBoolToBitmap(false)
}

func (b *Float16Builder) UnsafeAppendBoolToBitmap(isValid bool) {
	if isValid {
		bitutil.SetBit(b.nullBitmap.Bytes(), b.length)
	} else {
		b.nulls++
	}
	b.length++
}

// AppendValues will append the values in the v slice. The valid slice determines which values
// in v are valid (not null). The valid slice must either be empty or be equal in length to v. If empty,
// all values in v are appended and considered valid.
func (b *Float16Builder) AppendValues(v []float16.Num, valid []bool) {
	if len(v) != len(valid) && len(valid) != 0 {
		panic("len(v) != len(valid) && len(valid) != 0")
	}

	if len(v) == 0 {
		return
	}

	b.Reserve(len(v))
	if len(v) > 0 {
		arrow.Float16Traits.Copy(b.rawData[b.length:], v)
	}
	b.builder.unsafeAppendBoolsToBitmap(valid, len(v))
}

func (b *Float16Builder) init(capacity int) {
	b.builder.init(capacity)

	b.data = memory.NewResizableBuffer(b.mem)
	bytesN := arrow.Uint16Traits.BytesRequired(capacity)
	b.data.Resize(bytesN)
	b.rawData = arrow.Float16Traits.CastFromBytes(b.data.Bytes())
}

// Reserve ensures there is enough space for appending n elements
// by checking the capacity and calling Resize if necessary.
func (b *Float16Builder) Reserve(n int) {
	b.builder.reserve(n, b.Resize)
}

// Resize adjusts the space allocated by b to n elements. If n is greater than b.Cap(),
// additional memory will be allocated. If n is smaller, the allocated memory may reduced.
func (b *Float16Builder) Resize(n int) {
	nBuilder := n
	if n < minBuilderCapacity {
		n = minBuilderCapacity
	}

	if b.capacity == 0 {
		b.init(n)
	} else {
		b.builder.resize(nBuilder, b.init)
		b.data.Resize(arrow.Float16Traits.BytesRequired(n))
		b.rawData = arrow.Float16Traits.CastFromBytes(b.data.Bytes())
	}
}

// NewArray creates a Float16 array from the memory buffers used by the builder and resets the Float16Builder
// so it can be used to build a new array.
func (b *Float16Builder) NewArray() Interface {
	return b.NewFloat16Array()
}

// NewFloat16Array creates a Float16 array from the memory buffers used by the builder and resets the Float16Builder
// so it can be used to build a new array.
func (b *Float16Builder) NewFloat16Array() (a *Float16) {
	data := b.newData()
	a = NewFloat16Data(data)
	data.Release()
	return
}

func (b *Float16Builder) newData() (data *Data) {
	bytesRequired := arrow.Float16Traits.BytesRequired(b.length)
	if bytesRequired > 0 && bytesRequired < b.data.Len() {
		// trim buffers
		b.data.Resize(bytesRequired)
	}
	data = NewData(arrow.FixedWidthTypes.Float16, b.length, []*memory.Buffer{b.nullBitmap, b.data}, nil, b.nulls, 0)
	b.reset()

	if b.data != nil {
		b.data.Release()
		b.data = nil
		b.rawData = nil
	}

	return
}