text:
import sinon from 'sinon';
import assert from 'assert';
import { Keyboard } from '../lib/keyboard';
import { KeyCombo } from '../lib/key-combo';
import { Locale } from '../lib/locale';
import { document as doc } from './fixtures/document';
import { window as win } from './fixtures/window';

describe('Keyboard', () => {

  let keyboard;
  beforeEach(() => {
    keyboard = new Keyboard(win, doc);
  });

  describe('#setLocale', () => {

    it('creates and sets a locale', () => {
      keyboard.setLocale('testName', (locale, platform, userAgent) => {
        assert.equal(platform,  'test-platform');
        assert.equal(userAgent, 'test-user-agent');

        locale.test = 1;
      });

      assert.equal(keyboard._locale.test, 1);
      assert.equal(keyboard._locales.testName.test, 1);
    });

    it('sets a locale', () => {
      keyboard._locales.testName = { test: 2 };

      keyboard.setLocale('testName');

      assert.equal(keyboard._locale.test, 2);
    });

    it('accepts locale instance and sets it', () => {
      keyboard.setLocale({
        localeName: 'testName',
        test: 3
      });

      assert.equal(keyboard._locale.test, 3);
    });
  });

  describe('#getLocale', () => {

    it('returns the current locale', () => {
      keyboard._locales.testName = { test: 4, localeName: 'testName' };
      keyboard._locale = keyboard._locales.testName;

      const locale = keyboard.getLocale();

      assert.equal(locale.test, 4);
    });

    it('returns the a locale by name', () => {
      keyboard._locales.testName = { test: 5 };
      keyboard._locale = keyboard._locales.testName;

      const locale = keyboard.getLocale('testName');

      assert.equal(locale.test, 5);
    });
  });

  describe('#bind', () => {

    it('binds a combo to press handler and release handlers', () => {
      const pressHandler = () => {};
      const releaseHandler = () => {};

      keyboard.bind('a', pressHandler, releaseHandler);

      assert.equal(keyboard._listeners[0].keyCombo.sourceStr, 'a');
      assert.equal(keyboard._listeners[0].pressHandler, pressHandler);
      assert.equal(keyboard._listeners[0].releaseHandler, releaseHandler);
    });

    it('binds a combo to a press handler', () => {
      const pressHandler = () => {};

      keyboard.bind('a', pressHandler);

      assert.equal(keyboard._listeners[0].keyCombo.sourceStr, 'a');
      assert.equal(keyboard._listeners[0].pressHandler, pressHandler);
      assert.equal(keyboard._listeners[0].releaseHandler, null);
    });

    it('binds a combo to a release handler', () => {
      const releaseHandler = () => {};

      keyboard.bind('a', null, releaseHandler);

      assert.equal(keyboard._listeners[0].keyCombo.sourceStr, 'a');
      assert.equal(keyboard._listeners[0].pressHandler, null);
      assert.equal(keyboard._listeners[0].releaseHandler, releaseHandler);
    });

    it('binds several combos to press and release handlers', () => {
      const pressHandler = () => {};
      const releaseHandler = () => {};

      keyboard.bind(['a', 'b'], pressHandler, releaseHandler);

      assert.equal(keyboard._listeners[0].keyCombo.sourceStr, 'a');
      assert.equal(keyboard._listeners[1].keyCombo.sourceStr, 'b');
      assert.equal(keyboard._listeners[0].pressHandler, pressHandler);
      assert.equal(keyboard._listeners[1].pressHandler, pressHandler);
      assert.equal(keyboard._listeners[0].releaseHandler, releaseHandler);
      assert.equal(keyboard._listeners[1].releaseHandler, releaseHandler);
    });

    it('binds press and release handlers to any keypress', () => {
      const pressHandler = () => {};
      const releaseHandler = () => {};

      keyboard.bind(pressHandler, releaseHandler);

      assert.equal(keyboard._listeners[0].keyCombo, null);
      assert.equal(keyboard._listeners[0].pressHandler, pressHandler);
      assert.equal(keyboard._listeners[0].releaseHandler, releaseHandler);
    });

    it('accepts preventRepeat as a final argument', () => {
      const pressHandler = () => {};
      const releaseHandler = () => {};

      keyboard.bind('a', pressHandler, releaseHandler, true);
      keyboard.bind(pressHandler, releaseHandler, true);

      assert.equal(keyboard._listeners[0].keyCombo.sourceStr, 'a');
      assert.equal(keyboard._listeners[0].pressHandler, pressHandler);
      assert.equal(keyboard._listeners[0].releaseHandler, releaseHandler);
      assert.equal(keyboard._listeners[0].preventRepeat, true);
      assert.equal(keyboard._listeners[1].keyCombo, null);
      assert.equal(keyboard._listeners[1].pressHandler, pressHandler);
      assert.equal(keyboard._listeners[1].releaseHandler, releaseHandler);
      assert.equal(keyboard._listeners[1].preventRepeat, true);
    });
  });

  describe('#addListener', () => {

    it('is an alias for bind', () => {
      sinon.stub(keyboard, 'bind');
      const fn = () => {};
      keyboard.addListener('a', fn);
      sinon.assert.calledOnce(keyboard.bind);
      sinon.assert.calledWith(keyboard.bind, 'a', fn);
      keyboard.bind.restore();
    });
  });

  describe('#on', () => {

    it('is an alias for bind', () => {
      sinon.stub(keyboard, 'bind');
      const fn = () => {};
      keyboard.on('a', fn);
      sinon.assert.calledOnce(keyboard.bind);
      sinon.assert.calledWith(keyboard.bind, 'a', fn);
      keyboard.bind.restore();
    });
  });

  describe('#unbind', () => {

    const pressHandler = () => {};
    const releaseHandler = () => {};
    beforeEach(() => {
      keyboard._listeners.push({
        keyCombo: new KeyCombo('a'),
        pressHandler: pressHandler,
        releaseHandler: releaseHandler,
        preventRepeat: false
      });
      keyboard._listeners.push({
        keyCombo: new KeyCombo('a'),
        pressHandler: null,
        releaseHandler: releaseHandler,
        preventRepeat: false
      });
      keyboard._listeners.push({
        keyCombo: new KeyCombo('a'),
        pressHandler: pressHandler,
        releaseHandler: null,
        preventRepeat: false
      });
    });

    afterEach(() => {
      keyboard._listeners.length = 0;
    });

    it('unbinds a combo from press handler and release handlers', () => {
      keyboard.unbind('a', pressHandler, releaseHandler);

      assert.equal(keyboard._listeners.length, 2);
      assert.equal(keyboard._listeners[0].pressHandler, null);
      assert.equal(keyboard._listeners[0].releaseHandler, releaseHandler);
      assert.equal(keyboard._listeners[1].pressHandler, pressHandler);
      assert.equal(keyboard._listeners[1].releaseHandler, null);
    });

    it('unbinds a combo from a press handler', () => {
      keyboard.unbind('a', pressHandler);

      assert.equal(keyboard._listeners.length, 2);
      assert.equal(keyboard._listeners[0].pressHandler, pressHandler);
      assert.equal(keyboard._listeners[0].releaseHandler, releaseHandler);
      assert.equal(keyboard._listeners[1].pressHandler, null);
      assert.equal(keyboard._listeners[1].releaseHandler, releaseHandler);
    });

    it('unbinds a combo from a release handler', () => {
      keyboard.unbind('a', null, releaseHandler);

      assert.equal(keyboard._listeners.length, 2);
      assert.equal(keyboard._listeners[0].pressHandler, pressHandler);
      assert.equal(keyboard._listeners[0].releaseHandler, releaseHandler);
      assert.equal(keyboard._listeners[1].pressHandler, pressHandler);
      assert.equal(keyboard._listeners[1].releaseHandler, null);
    });

    it('unbinds a several combos from press and release handlers', () => {
      keyboard._listeners.push({
        keyCombo: new KeyCombo('b'),
        pressHandler: pressHandler,
        releaseHandler: releaseHandler,
        preventRepeat: false
      });

      keyboard.unbind(['a', 'b'], pressHandler, releaseHandler);

      assert.equal(keyboard._listeners.length, 2);
      assert.equal(keyboard._listeners[0].pressHandler, null);
      assert.equal(keyboard._listeners[0].releaseHandler, releaseHandler);
      assert.equal(keyboard._listeners[1].pressHandler, pressHandler);
      assert.equal(keyboard._listeners[1].releaseHandler, null);
    });

    it('unbinds press and release handlers bound to any key press', () => {
      keyboard._listeners.push({
        keyCombo: null,
        pressHandler: pressHandler,
        releaseHandler: releaseHandler,
        preventRepeat: false
      });

      keyboard.unbind(pressHandler, releaseHandler);

      assert.equal(keyboard._listeners.length, 3);
      assert.equal(keyboard._listeners[0].pressHandler, pressHandler);
      assert.equal(keyboard._listeners[0].releaseHandler, releaseHandler);
      assert.equal(keyboard._listeners[1].pressHandler, null);
      assert.equal(keyboard._listeners[1].releaseHandler, releaseHandler);
      assert.equal(keyboard._listeners[2].pressHandler, pressHandler);
      assert.equal(keyboard._listeners[2].releaseHandler, null);
    });
  });

  describe('#removeListener', () => {

    it('is an alias for unbind', () => {
      sinon.stub(keyboard, 'unbind');
      const fn = () => {};
      keyboard.removeListener('a', fn);
      sinon.assert.calledOnce(keyboard.unbind);
      sinon.assert.calledWith(keyboard.unbind, 'a', fn);
      keyboard.unbind.restore();
    });
  });

  describe('#off', () => {

    it('is an alias for unbind', () => {
      sinon.stub(keyboard, 'unbind');
      const fn = () => {};
      keyboard.off('a', fn);
      sinon.assert.calledOnce(keyboard.unbind);
      sinon.assert.calledWith(keyboard.unbind, 'a', fn);
      keyboard.unbind.restore();
    });
  });

  describe('#setContext', () => {

    it('releases all keys before setting the context', () => {
      keyboard._locale = {};
      sinon.stub(keyboard, 'releaseAllKeys');

      keyboard.setContext('myContext');

      assert.ok(keyboard.releaseAllKeys.calledOnce);

      keyboard.releaseAllKeys.restore();
    });

    it('creates a new context with the given name if it doesn\'t exist.', () => {
      keyboard.setContext('myContext');

      assert.ok(keyboard._contexts.myContext);
      assert.equal(keyboard._currentContext, 'myContext');
    });

    it('applies an existing context if one with the given name already exists', () => {
      keyboard._contexts.myContext = {
        listeners: [1],
        targetWindow: keyboard._targetWindow,
        targetElement: keyboard._targetElement,
        targetPlatform: keyboard._targetPlatform,
        targetUserAgent: keyboard._targetUserAgent
      };

      keyboard.setContext('myContext');

      assert.equal(keyboard._currentContext, 'myContext');
      assert.equal(keyboard._contexts[keyboard._currentContext].listeners[0], 1);
    });

    it('watches the targets set in the context', () => {
      const targetWindow = {
        addEventListener: sinon.stub(),
        removeEventListener: sinon.stub()
      };
      const targetElement = {
        addEventListener: sinon.stub(),
        removeEventListener: sinon.stub()
      };

      keyboard._contexts.myContext = {
        listeners: [1],
        targetWindow,
        targetElement,
        targetPlatform: 'test-platform',
        targetUserAgent: 'test-user-agent'
      };

      keyboard.setContext('myContext');

      assert.equal(keyboard._targetWindow, targetWindow);
      assert.equal(keyboard._targetElement, targetElement);
      assert.equal(keyboard._targetPlatform, 'test-platform');
      assert.equal(keyboard._targetUserAgent, 'test-user-agent');

      sinon.assert.calledTwice(targetWindow.addEventListener);
      sinon.assert.calledTwice(targetElement.addEventListener);
    });
  });

  describe('#getContext', () => {

    it('returns the current context', () => {
      keyboard._currentContext = 'myContext';

      assert.equal(keyboard.getContext(), 'myContext');
    });
  });

  describe('#watch', () => {

    it('calls stop', () => {
      sinon.stub(keyboard, 'stop');

      keyboard.watch(win, doc);

      assert.ok(keyboard.stop.calledOnce);
      keyboard.stop.restore();
    });

    it('attaches to a given window and document', () => {
      const win = { addEventListener: sinon.stub() };
      const doc = { addEventListener: sinon.stub() };

      keyboard.watch(win, doc);

      assert.equal(keyboard._isModernBrowser, true);
      assert.equal(keyboard._targetWindow, win);
      assert.equal(keyboard._targetElement, doc);
      assert.ok(win.addEventListener.firstCall.args[0], 'focus');
      assert.ok(win.addEventListener.secondCall.args[0], 'blur');
      assert.ok(doc.addEventListener.firstCall.args[0], 'keydown');
      assert.ok(doc.addEventListener.secondCall.args[0], 'keyup');
    });

    it('attaches to a given window and document (Legacy IE)', () => {
      const win = { attachEvent: sinon.stub() };
      const doc = { attachEvent: sinon.stub() };

      keyboard.watch(win, doc);

      assert.equal(keyboard._isModernBrowser, false);
      assert.equal(keyboard._targetWindow, win);
      assert.equal(keyboard._targetElement, doc);
      assert.ok(win.attachEvent.firstCall.args[0], 'onfocus');
      assert.ok(win.attachEvent.secondCall.args[0], 'onblur');
      assert.ok(doc.attachEvent.firstCall.args[0], 'onkeydown');
      assert.ok(doc.attachEvent.secondCall.args[0], 'onkeyup');
    });

    it('attaches to the global namespace if a window and document is not given', () => {
      global.addEventListener = sinon.stub();
      global.document         = { addEventListener: sinon.stub() };

      keyboard.watch();

      assert.equal(keyboard._isModernBrowser, true);
      assert.equal(keyboard._targetWindow, global);
      assert.equal(keyboard._targetElement, global.document);
      assert.ok(global.addEventListener.firstCall.args[0], 'focus');
      assert.ok(global.addEventListener.secondCall.args[0], 'blur');
      assert.ok(global.document.addEventListener.firstCall.args[0], 'keydown');
      assert.ok(global.document.addEventListener.secondCall.args[0], 'keyup');

      delete global.addEventListener;
      delete global.document;
    });

    it('throws is error if the target window does not have the nessisary methods', () => {
      const win = {};
      const doc = {};

      assert.throws(() => {
        keyboard.watch(win, doc);
      }, /^(?=.*targetWindow)(?=.*addEventListener)(?=.*attachEvent).*$/);
    });

    it('throws is error a target window was not given and if the global does contain the nessisary functions', () => {
      assert.throws(() => {
        keyboard.watch();
      }, /^(?=.*window)(?=.*addEventListener)(?=.*attachEvent).*$/);
    });
  });

  describe('#stop', () => {

    it('dettaches from the currently attached window and document', () => {
      const doc = keyboard._targetElement = { removeEventListener: sinon.stub() };
      const win = keyboard._targetWindow  = { removeEventListener: sinon.stub() };

      keyboard.stop();

      assert.equal(keyboard._targetWindow, null);
      assert.equal(keyboard._targetElement, null);
      assert.ok(win.removeEventListener.firstCall.args[0], 'focus');
      assert.ok(win.removeEventListener.secondCall.args[0], 'blur');
      assert.ok(doc.removeEventListener.firstCall.args[0], 'keydown');
      assert.ok(doc.removeEventListener.secondCall.args[0], 'keyup');
    });

    it('dettaches from the currently attached window and document (Legacy IE)', () => {
      const doc = { detachEvent: sinon.stub() };
      const win = { detachEvent: sinon.stub() };

      keyboard._isModernBrowser = false;
      keyboard._targetElement   = doc;
      keyboard._targetWindow    = win;

      keyboard.stop();

      assert.equal(keyboard._targetWindow, null);
      assert.equal(keyboard._targetElement, null);
      assert.ok(win.detachEvent.firstCall.args[0], 'onfocus');
      assert.ok(win.detachEvent.secondCall.args[0], 'onblur');
      assert.ok(doc.detachEvent.firstCall.args[0], 'onkeydown');
      assert.ok(doc.detachEvent.secondCall.args[0], 'onkeyup');
    });
  });

  describe('#pressKey', () => {

    let locale;
    beforeEach(() => {
      locale = new Locale('test');
      locale.bindKeyCode(0, 'a');
      locale.bindKeyCode(1, 'b');
      keyboard._locale = locale;
    });

    it('calls pressKey on the locale', () => {
      sinon.stub(locale, 'pressKey');

      keyboard.pressKey('a');

      assert.equal(locale.pressKey.lastCall.args[0], 'a');

      locale.pressKey.restore();
    });

    it('executes bindings with a combo matching the pressed keys within the locale', () => {
      const pressHandler = sinon.stub();
      keyboard._listeners.push({
        keyCombo: new KeyCombo('a'),
        pressHandler: pressHandler,
        releaseHandler: null,
        preventRepeat: false
      });

      keyboard.pressKey('a');

      assert.ok(pressHandler.calledOnce);
    });

    it('executes bindings without a combo', () => {
      const pressHandler = sinon.stub();
      keyboard._listeners.push({
        keyCombo: null,
        pressHandler: pressHandler,
        releaseHandler: null,
        preventRepeat: false
      });

      keyboard.pressKey('a');
      keyboard.pressKey('b');

      assert.ok(pressHandler.calledTwice);
    });

    it('prevents combo overlap by marking off keys once they have been used by a combo', () => {
      const aPressHandler  = sinon.stub();
      const aBPressHandler = sinon.stub();
      keyboard._listeners.push({
        keyCombo: new KeyCombo('a'),
        pressHandler: aPressHandler,
        releaseHandler: null,
        preventRepeat: false
      });
      keyboard._listeners.push({
        keyCombo: new KeyCombo('a + b'),
        pressHandler: aBPressHandler,
        releaseHandler: null,
        preventRepeat: false
      });

      keyboard.pressKey('a'); // combo a fires
      keyboard.pressKey('b'); // combo a + b fires, but not combo a because the
                              // a key has been consumed by combo a + b

      assert.ok(aPressHandler.calledOnce);
      assert.ok(aBPressHandler.calledOnce);
    });

    it('allows any number of identical bindings to fire without inhibiting each other', () => {
      const a1PressHandler = sinon.stub();
      const a2PressHandler = sinon.stub();
      keyboard._listeners.push({
        keyCombo: new KeyCombo('a'),
        pressHandler: a1PressHandler,
        releaseHandler: null,
        preventRepeat: false
      });
      keyboard._listeners.push({
        keyCombo: new KeyCombo('a'),
        pressHandler: a2PressHandler,
        releaseHandler: null,
        preventRepeat: false
      });

      keyboard.pressKey('a'); // combo a1 and a2 fires

      assert.ok(a1PressHandler.calledOnce);
      assert.ok(a2PressHandler.calledOnce);
    });

    it('does nothing when paused', () => {
      sinon.stub(locale, 'pressKey');
      keyboard._paused = true;

      keyboard.pressKey('a');

      assert.equal(locale.pressKey.called, false);
      assert.equal(locale.pressedKeys.length, 0);

      locale.pressKey.restore();
    });

    it('will trigger bindings each time press key is executed', () => {
      const pressHandler = sinon.stub();
      keyboard._listeners.push({
        keyCombo: new KeyCombo('a'),
        pressHandler: pressHandler,
        releaseHandler: null,
        preventRepeat: false
      });

      keyboard.pressKey('a');
      keyboard.pressKey('a');

      sinon.assert.calledTwice(pressHandler);
    });

    it('will only trigger bindings that use preventRepeat once', () => {
      const pressHandler = sinon.spy((e) => { e.preventRepeat() });
      keyboard._listeners.push({
        keyCombo: new KeyCombo('a'),
        pressHandler: pressHandler,
        releaseHandler: null,
        preventRepeat: false
      });

      keyboard.pressKey('a');
      keyboard.pressKey('a');

      sinon.assert.calledOnce(pressHandler);
    });

    it('will trigger bindings that use preventRepeat again once the binding\'s combo is released', () => {
      const pressHandler = sinon.spy((e) => { e.preventRepeat() });
      keyboard._listeners.push({
        keyCombo: new KeyCombo('a'),
        pressHandler: pressHandler,
        releaseHandler: null,
        preventRepeat: false
      });

      keyboard.pressKey('a');
      keyboard.pressKey('a');

      keyboard.releaseKey('a');

      keyboard.pressKey('a');
      keyboard.pressKey('a');

      sinon.assert.calledTwice(pressHandler);
    });

    it('will not trigger bindings that caused it to be executed in the same tick', () => {
      const pressHandler = sinon.spy(() => { keyboard.pressKey('a') });
      keyboard._listeners.push({
        keyCombo: new KeyCombo('a'),
        pressHandler: pressHandler,
        releaseHandler: null,
        preventRepeat: false
      });

      keyboard.pressKey('a');
      keyboard.releaseKey('a');

      sinon.assert.calledOnce(pressHandler);
    });

    it('will not trigger bindings when an unbound key is pressed', () => {
      const pressHandler = sinon.stub();
      keyboard._listeners.push({
        keyCombo: new KeyCombo('a'),
        pressHandler: pressHandler,
        releaseHandler: null,
        preventRepeat: false
      });

      keyboard.pressKey('a');
      keyboard.pressKey('b');

      sinon.assert.calledOnce(pressHandler);
    });
  });

  describe('#releaseKey', () => {

    let locale;
    beforeEach(() => {
      locale = new Locale('test');
      locale.bindKeyCode(0, 'a');
      locale.bindKeyCode(1, 'b');
      keyboard._locale = locale;
    });

    it('calls releaseKey on the locale', () => {
      sinon.stub(locale, 'releaseKey');

      keyboard.releaseKey('a');

      assert.equal(locale.releaseKey.lastCall.args[0], 'a');

      locale.releaseKey.restore();
    });

    it('will not execute a binding\'s releaseHandler unless it was triggered first by a press', () => {
      const releaseHandler = sinon.stub();
      keyboard.pressKey('a');
      keyboard._listeners.push({
        keyCombo: new KeyCombo('a'),
        pressHandler: null,
        releaseHandler: releaseHandler,
        preventRepeat: false
      });

      keyboard.releaseKey('a');

      assert.equal(releaseHandler.calledOnce, false);
    });

    it('executes the releaseHandler of active bindings that no longer match the pressed keys', () => {
      const releaseHandler = sinon.stub();
      keyboard._listeners.push({
        keyCombo: new KeyCombo('a'),
        pressHandler: null,
        releaseHandler: releaseHandler,
        preventRepeat: false
      });
      keyboard.pressKey('a');

      keyboard.releaseKey('a');

      assert.ok(releaseHandler.calledOnce);
    });

    it('executes the releaseHandler without a combo', () => {
      const releaseHandler = sinon.stub();
      keyboard._listeners.push({
        keyCombo: null,
        pressHandler: null,
        releaseHandler: releaseHandler,
        preventRepeat: false
      });
      keyboard.pressKey('a');
      keyboard.pressKey('b');

      keyboard.releaseKey('a');
      keyboard.releaseKey('b');

      assert.ok(releaseHandler.calledTwice);
    });
  });

  describe('#releaseAllKeys', () => {

    let locale;
    beforeEach(() => {
      locale = new Locale('test');
      locale.bindKeyCode(0, 'a');
      keyboard._locale = locale;
    });

    it('clears pressedKeys on the locale', () => {
      keyboard.releaseAllKeys();

      assert.equal(locale.pressedKeys.length, 0);
    });

    it('will not execute a binding\'s releaseHandler unless it was triggered first by a press', () => {
      const releaseHandler = sinon.stub();
      keyboard.pressKey('a');
      keyboard._listeners.push({
        keyCombo: new KeyCombo('a'),
        pressHandler: null,
        releaseHandler: releaseHandler,
        preventRepeat: false
      });

      keyboard.releaseAllKeys();

      assert.equal(releaseHandler.calledOnce, false);
    });

    it('executes the releaseHandler of active bindings that no longer match the pressed keys', () => {
      const releaseHandler = sinon.stub();
      keyboard._listeners.push({
        keyCombo: new KeyCombo('a'),
        pressHandler: null,
        releaseHandler: releaseHandler,
        preventRepeat: false
      });
      keyboard.pressKey('a');

      keyboard.releaseAllKeys();

      assert.ok(releaseHandler.calledOnce);
    });
  });

  describe('#pause', () => {

    it('pauses the instance', () => {
      keyboard.pause();

      assert.ok(keyboard._paused);
    });
  });

  describe('#resume', () => {

    it('resumes the instance', () => {
      keyboard.resume();

      assert.equal(keyboard._paused, false);
    });
  });

  describe('#reset', () => {

    it('calls releaseAllKeys', () => {
      sinon.stub(keyboard, 'releaseAllKeys');

      keyboard.reset();

      assert.ok(keyboard.releaseAllKeys.calledOnce);

      keyboard.releaseAllKeys.reset();
    });

    it('clears all listeners', () => {
      sinon.stub(keyboard, 'releaseAllKeys');
      keyboard._listeners = [1];

      keyboard.reset();

      assert.equal(keyboard._listeners.length, 0);

      keyboard.releaseAllKeys.reset();
    });
  });
});


text:
<?php
test git desde  ubuntuserver

Otro cambio
	define('DS',DIRECTORY_SEPARATOR);
	define('ROOT',realpath(dirname(__FILE__)) . DS);

	define('URL','http://localhost/cursophp/phpsenasoft/pro_estudiantes/');
	define('MEDIA','http://localhost/cursophp/phpsenasoft/pro_estudiantes/media');

	require_once "Config/Autoload.php";

	Config\Autoload::run();
	// new Config\Request()
	require_once "Views/Template.php";
	Config\Enrutador::run(new Config\Request());

//Un Comentario para senasoft

echo "Hola mundo";

Este es un comentario desde la rama backend

holqa test

maira lo mejorcito.com
	/*******************************/
	// tphpinfo();				       //
	/*******************************/
 ?>

redpajama_set_name: RedPajamaGithub


text:
require 'fog/openstack'
require 'time'

auth_url = "http://10.0.0.101:5000/v2.0/tokens"
username = 'admin'
password = 'D78JVyRnzJG8j7Mb6fgpeUMp7'

@connection_params = {
    :openstack_auth_url     => auth_url,
    :openstack_username     => username,
    :openstack_api_key      => password,
}

puts "### SERVICE CONNECTION ###"

event_service = Fog::Event::OpenStack.new(@connection_params)

p event_service

puts "### LIST EVENTS ###"

p event_service.events.all


text:
package com.example.akashdeepsingh.myapplication;

import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;

public class MainActivity extends FragmentActivity {

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

       setUpMapIfNeeded();
    }

    private void setUpMapIfNeeded() {
        if(mMap==null){
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
            if(mMap!=null){
               setUpMap();
            }
        }
    }
    private void setUpMap() {
      //  mMap.addMarker(new MarkerOptions().position(new LatLng(30, 0)).title("Marker"));
    }

    @Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}


text:
using namespace std;

namespace schedule {

	// For Convolution neural network.
	CREATE_SIMPLE_CLASS_GET_3(ImageDataParam, root_folder, string, source, string, batch_size, size_t)
	CREATE_SIMPLE_CLASS_GET_3(TransformParam, crop_size, size_t, mirror, bool, scale, float)
	CREATE_SIMPLE_CLASS_GET_1(WeightFiller, type, string)
	CREATE_SIMPLE_CLASS_GET_2(BiasFiller, type, string, value, float)
	CREATE_SIMPLE_CLASS_GET_1(Include, phase, string)
	CREATE_SIMPLE_CLASS_GET_6(ConvolutionParam, num_output, size_t, kernel_size, size_t,
		pad, size_t, stride, size_t, weight_filler, WeightFiller, bias_term, bool)
	CREATE_SIMPLE_CLASS_GET_3(PoolingParam, pool, string, kernel_size, size_t, stride, size_t)
	CREATE_SIMPLE_CLASS_GET_3(BatchNormParam, moving_average_fraction, float, eps, float, scale_bias, bool)
	CREATE_SIMPLE_CLASS_GET_3(InnerProductParam, num_output, size_t, weight_filler, WeightFiller, bias_filler, BiasFiller)
	CREATE_SIMPLE_CLASS_GET_1(EltwiseParam, operation, string)
	CREATE_SIMPLE_CLASS_GET_1(AccuracyParam, top_k, size_t)

	class Node {
	protected:
	public:
		Node(string name, string type, vector<string>& bottom, vector<string>& top) {
			m_name = name;
			m_type = type;
			m_bottom.swap(bottom);
			m_top.swap(top);
		};
		virtual ~Node() {};

		string GetName() { return m_name; };
		string GetType() { return m_type; };
		vector<string>& GetBottom() { return m_bottom; };
		vector<string>& GetTop() { return m_top; };

	private:
		string m_name;
		string m_type;
		vector<string> m_bottom;
		vector<string> m_top;
	};

	CREATE_NODE_CLASS_3(ImageDataNode, image_data_param, ImageDataParam,
		transform_param, TransformParam, include, Include)
	CREATE_NODE_CLASS_1(ConvolutionNode, param, ConvolutionParam)
	CREATE_NODE_CLASS_1(PoolingNode, param, PoolingParam)
	CREATE_NODE_CLASS_1(BatchNormNode, param, BatchNormParam)
	CREATE_NODE_CLASS_0(ReluNode)
	CREATE_NODE_CLASS_1(InnerProductNode, param, InnerProductParam)
	CREATE_NODE_CLASS_1(EltwiseNode, param, EltwiseParam)
	CREATE_NODE_CLASS_0(SoftmaxNode)
	CREATE_NODE_CLASS_2(AccuracyNode, param, AccuracyParam, include, Include)

}

#endif // !__NODE_H__


text:
    <meta http-equiv="content-type" content="text/html">
    <title>Base16 Melanite</title>

Base16 Melanite

lpm11 (https://github.com/lpm11/melanite)

00

01

02

03

04

05

06

07

08

09

0A

0B

0C

0D

0E

0F

require "gem"

string = "base16"
symbol = :base16
fixnum = 0
float  = 0.00
array  = Array.new
array  = ['chris', 85]
hash   = {"test" => "test"}
regexp = /[abc]/

# This is a comment
class Person

  attr_accessor :name

  def initialize(attributes = {})
    @name = attributes[:name]
  end

  def self.greet
    "hello"
  end
end

person1 = Person.new(:name => "Chris")
print Person::greet, " ", person1.name, "\n"
puts "another #{Person::greet} #{person1.name}"


text:
package org.apache.camel.component.file.remote;

import java.net.ServerSocket;

import org.apache.camel.CamelExecutionException;
import org.apache.camel.RoutesBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.JndiRegistry;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.apache.commons.net.ftp.FTPClient;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

/**
 * Test class used to demonstrate the problematic disconnect sequence of the {@link FtpOperations}.
 * <p>
 * Setting the logging level of {@code org.apache.camel.file.remote} to {@code TRACE} will provide useful information
 *
 * @author l.chiarello
 *
 */
public class FtpSoTimeoutTest extends CamelTestSupport {

    private ServerSocket serverSocket;

    // --- Set up

    @Override
    @Before
    public void setUp() throws Exception {
        // the created server socket makes it possible for the FTP client to establish the socket connection.
        // However, no message will ever be sent back, thus a read timeout should occur within FTPClient#__getReply()
        serverSocket = new ServerSocket(0);
        super.setUp();
    }

    @Override
    @After
    public void tearDown() throws Exception {
        super.tearDown();
        if (serverSocket != null) {
            serverSocket.close();
        }
    }

    @Override
    protected int getShutdownTimeout() {
        return 5; // speedup graceful shutdown
    }

    @Override
    protected RoutesBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:with")
                    .to("ftp://localhost:" + serverSocket.getLocalPort()
                        + "?ftpClient=#myftpclient&connectTimeout=300&soTimeout=300&reconnectDelay=100");

                from("direct:without")
                    .to("ftp://localhost:" + serverSocket.getLocalPort()
                        + "?connectTimeout=300&soTimeout=300&reconnectDelay=100");
            }
        };
    }

    @Override
    protected JndiRegistry createRegistry() throws Exception {
        FTPClient ftpClient = new FTPClient();
        ftpClient.setDefaultTimeout(300);
        JndiRegistry registry = super.createRegistry();
        registry.bind("myftpclient", ftpClient);
        return registry;
    }

    // --- Tests

    @Test(timeout = 10000, expected = CamelExecutionException.class)
    public void testWithDefaultTimeout() throws Exception {
        // send exchange to the route using the custom FTPClient (with a default timeout)
        // the soTimeout triggers in time and test is successful
        template.sendBody("direct:with", "");
    }

    @Test(timeout = 10000, expected = CamelExecutionException.class)
    public void testWithoutDefaultTimeout() throws Exception {
        // send exchange to the route using the default FTPClient (without a default timeout)
        // the soTimeout never triggers and test fails after its own timeout
        template.sendBody("direct:without", "");
    }
}


text:
package ua.com.fielden.platform.web.centre.api.dynamic_columns;

import ua.com.fielden.platform.web.centre.api.IDynamicColumnConfig;

/**
 * A contract that completes configuration of dynamic columns and returns it for further use.
 *
 * @author TG Team
 *
 */
public interface IDynamicColumnBuilderDone extends IDynamicColumnBuilderAddProp {

    IDynamicColumnConfig done();

}


text:
layout: article
title: "She said yes"
excerpt: "Engagement PaperFaces portrait of @theBrady and @khollybell drawn with Paper by 53 on an iPad."
image:
  feature: paperfaces-thebrady-khollybell-2-twitter-lg.jpg
  thumb: paperfaces-thebrady-khollybell-2-twitter-150.jpg
category: paperfaces
tags: [portrait, illustration, paper by 53, time lapse]
---

PaperFaces portrait of project donators [@theBrady](http://twitter.com/theBrady) and [@khollybell](http://twitter.com/khollybell).

Broke in a [Pogo Connect stylus](http://www.amazon.com/gp/product/B009K448L4/ref=as_li_ss_tl?ie=UTF8&camp=1789&creative=390957&creativeASIN=B009K448L4&linkCode=as2&tag=mademist-20) drawing this illustration and so far really enjoy it. There are some hinky issues with it losing connection or freezing up Paper by 53, but for the most part it works flawlessly. Being able to control the thickness of watercolor strokes is a major plus, as is the dedicated undo button[^1].

{% include paperfaces-boilerplate-2.html %}

<iframe width="560" height="315" src="http://www.youtube.com/embed/SqYiglufb8Y" frameborder="0"> </iframe>

[^1]: Those of you who have problems with or hate the rewind gesture will love the Pogo Connect. Just push the button on the stylus and it undos your most recent marks.


text:
'use strict';

// Convenient setup of Express that uses the most popular and useful Express
// middleware handlers from the Express community.

// We're using process.exit() intentionally here
/* eslint no-process-exit: 1 */

const _ = require('underscore');
const path = require('path');
const fs = require('fs');
const express = require('express');
// const domain = require('domain');
const http = require('http');
const https = require('https');
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
const morgan = require('morgan');
const responseTime = require('response-time');
const statics = require('serve-static');
const compression = require('compression');
const events = require('abacus-events');
const cp = require('child_process');
const commander = require('commander');
const vcapenv = require('abacus-vcapenv');
const rc = require('abacus-rc');
const oauth = require('abacus-oauth');

const map = _.map;
const keys = _.keys;
const noop = _.noop;
const memoize = _.memoize;
const extend = _.extend;

// Setup debug log
const adebug = require('abacus-debug');
const debug = require('abacus-debug')('abacus-express');
const edebug = require('abacus-debug')('e-abacus-express');

// Load optional dev dependency
/* eslint no-extra-parens: 1 */
const inspector = (() => {
  try {
    return require('express-inspector');
  }
  catch (e) {
    return undefined;
  }
})();

// Set up an event emitter
const emitter = events.emitter('abacus-express/emitter');
const on = (e, l) => {
  emitter.on(e, l);
};

// Return an Express middleware that returns the CORS headers
const cors = () => {
  return (req, res, next) => {
    if(req.headers.origin) {
      res.header('Access-Control-Allow-Credentials', 'true');
      res.header('Access-Control-Allow-Origin', req.headers.origin);
      res.header('Access-Control-Allow-Methods',
        'GET,HEAD,PUT,POST,DELETE,OPTIONS,PATCH');
      res.header('Access-Control-Allow-Headers',
        'Content-Type, Authorization, Content-Length, ' +
        'apiKey, X-Requested-With');
      res.header('Access-Control-Max-Age', '1728000');
    }
    next();
  };
};

// Return an Express middleware that responds to (CORS) OPTIONS requests
const options = () => {
  return (req, res, next) => {
    if(req.method === 'OPTIONS')
      res.status(200).end();
    else
      next();
  };
};

// Accumulate chunks of a request or response body, up to a given length
const accumulate = (accum, length, chunk, encoding) => {
  return chunk && accum.length < length ?
    accum + chunk.toString(encoding ?
    encoding : 'utf8', 0, length - accum.length) : accum;
};

// Truncate a string to a given length and add ... to indicate it
const truncate = (s, length) => {
  return s.length > length ? s.substring(0, length) + '...' : s;
};

// Return true if a mime type identifies text content, recognizes the most
// common text-based mime types
const isText = (mime) => {
  return new RegExp('css|form-data|html|javascript|json|perl|postscript|rdf|' +
    'rtf|sgml|svg|text|urlencoded|xml').test(mime);
};

// Return an Express middleware that logs HTTP request text bodies
const requestLogger = () => {
  if(debug.enabled())
    return (req, res, next) => {
      // Limit log output to 1024 characters
      const max = 1024;

      // Warning: capture is a mutable variable
      let capture = '';

      req.on('data', (chunk) => {
        if(isText(req.get('Content-Type')))
          // Accumulate chunks of the request up to the max number
          // of characters we want to log
          // Warning mutating variable capture
          capture = accumulate(capture, max + 1, chunk, 'utf-8');
      });

      req.on('end', () => {
        // Log the request body
        if(capture.length !== 0)
          debug(
            'Received %s request body\n%s', req.method, truncate(capture, max));
      });

      next();
    };

  return (req, res, next) => {
    next();
  };
};

// Return an Express middleware that logs HTTP response text bodies
const responseLogger = () => {
  if(debug.enabled())
    return (req, res, next) => {
      // Limit log output to 1024 characters
      const max = 1024;

      // Warning: capture is a mutable variable
      let capture = '';

      // Monkey patch res.end and res.write to capture and log the
      // response body string
      const write = res.write;
      res.write = function(chunk, encoding) {
        write.apply(res, arguments);
        if(isText(res.get('Content-Type')))
          // Accumulate chunks of the response up to the max number
          // of characters we want to log
          // Warning mutating variable capture
          capture = accumulate(capture, max + 1, chunk, encoding);
      };

      const end = res.end;
      res.end = function(chunk, encoding) {
        end.apply(res, arguments);
        // Log the response body
        if(capture.length !== 0)
          debug(
            'Sent %s response body\n%s', req.method, truncate(capture, max));
      };

      // Monkey patch res.send to capture the response body as an object
      // before it's stringified to JSON (if it's an object) as that'll
      // give us a cleaner log
      const send = res.send;
      res.send = function() {
        // Handle the various optional argument combinations that can
        // be passed to send
        const body = arguments.length === 2 ?
          typeof arguments[0] !== 'number' && typeof arguments[1] ===
          'number' ? arguments[0] : arguments[1] : arguments[0];
        if(typeof body === 'object') {
          // Restore the original res methods as we're going to log
          // the object right away here, we don't need to capture its
          // JSON representation
          res.write = write;
          res.end = end;
        }

        // Call the original send method
        send.apply(res, arguments);
      };

      next();
    };

  return (req, res, next) => {
    next();
  };
};

// Return configured Express morgan logger middleware
const beforeLogger = () => {
  const morg = morgan(
    ':remote-addr - - :method :url HTTP/:http-version :status ' +
    ':res[content-length] :referrer :user-agent - :response-time ms', {
      immediate: true,
      stream: {
        write: (msg, encoding) => {
          debug('Received request %s', msg.replace(/\n/g, ''));
        }
      }
    });
  return (req, res, next) => {
    return debug.enabled() ? morg(req, res, next) : next();
  };
};

const afterLogger = () => {
  const morg = morgan(
    ':remote-addr - - :method :url HTTP/:http-version :status ' +
    ':res[content-length] :referrer :user-agent - :response-time ms', {
      stream: {
        write: (msg, encoding) => {
          debug('Processed request %s', msg.replace(/\n/g, ''));
        }
      }
    });
  return (req, res, next) => {
    return debug.enabled() ? morg(req, res, next) : next();
  };
};

// Send a redirect header
const sendRedirect = (redirect, res) => {
  if(typeof redirect === 'object')
    if(redirect.status)
      res.redirect(redirect.status, redirect.url);
    else
      res.redirect(redirect.url);
  else
    res.redirect(redirect);
};

// Send the headers found in the given value
const sendHeaders = (value, res) => {
  // Headers
  map(keys(value.header), (k) => res.header(k, value.header[k]));
  if(value.type)
    res.type(value.type);

  // Cookies
  map(keys(value.cookie), (k) => {
    const c = value.cookie[k];
    if(typeof c === 'object')
      if(c.options) res.cookie(k, c.value, c.options);
      else res.cookie(k, c.value);
    else
      res.cookie(k, c);
  });

  // Redirect
  if(value.redirect)
    sendRedirect(value.redirect, res);

  // Location
  if(value.location)
    res.location(value.location);

  // Links
  if(value.links)
    res.links(value.links);
};

// Render and send the template found in the given value
const sendTemplate = (value, res) => {
  // Template local variables
  if(value.locals)
    res.locals = value.locals;
  if(value.props)
    res.props = value.props;

  // Render the template
  res.render(value.template);
};

// Send the body found in the given value
const sendBody = (value, res) => {
  if(value.template)
    sendTemplate(value, res);
  else if(value.body)
    res.send(value.body);
  else if(value.json)
    res.json(value.json);
  else if(value.jsonp)
    res.jsonp(value.jsonp);
  else
    // Default to just send a status code
    res.status(res.statusCode).end();
};

// Return an Express middleware that sends what it finds in res.value
const sendValue = () => {
  return (req, res, next) => {
    if(!res.value) {
      next();
      return;
    }

    // Status code
    res.statusCode = res.value.statusCode || res.value.status || 200;

    // Send the headers found in res.value
    sendHeaders(res.value, res);

    // Send the body found in res.value
    sendBody(res.value, res);

    // The following functions are not yet supported here, instead just
    // call the regular Express response methods if you need
    // res.format(object)
    // res.attachment([filename])
    // res.sendfile(path, [options], [fn]])
    // res.download(path, [filename], [fn])
  };
};

// Return an Express middleware that reports the current process info
const processInfo = () => {
  return (req, res, next) => {
    res.header('X-Process-Id', process.pid);
    res.header('X-Uptime', process.uptime());
    res.header('X-Heap-Used', process.memoryUsage().heapUsed);
    res.header('X-Node-Version', process.version);
    next();
  };
};

// Return an Express middleware for dynamic log config, use like this:
// curl http://localhost:9080/debug?config=disabled or
// curl http://localhost:9080/debug?config=enabled or
// curl http://localhost:9080/debug?config=* or
// curl http://localhost:9080/debug?config=<your log config>
const cdebug = () => {
  const secured = process.env.SECURED === 'true';
  return (req, res, next) => {
    if(req.query.config) {
      if(secured)
        oauth.authorize(req.headers && req.headers.authorization, {
          system: ['abacus.debug.write']
        });
      if(req.query.config === 'disabled')
        adebug.disable();
      else
        adebug.enable(req.query.config);
    }
    res.status(200).send({
      config: process.env.DEBUG
    });
  };
};

// Return an Express middlware that counts concurrent inflight requests
const inflight = () => {
  // Warning: inflight is a mutable variable
  return (req, res, next) => {
    const server = req.client.server ? req.client.server : req.client.socket
      .server;

    // Increment our count of inflight requests when we get a request
    // Warning: mutating variable server.inflight
    server.inflight = server.inflight ? server.inflight + 1 : 1;

    const done = () => {
      // Decrement our count when we're done with the response
      // Warning: mutating variable server.inflight
      server.inflight--;

      // Signal any listeners that the server got quiet
      if(server.inflight === 0)
        server.emit('quiet');
    };
    res.on('finish', done);
    res.on('close', done);
    next();
  };
};

// Return an Express middleware that uses a Node domain to run the middleware
// stack and catch any errors not caught in async callbacks
const catchall = () => {
  return (req, res, next) => {
    // TODO Re-enable this after we understand why unrelated contexts are
    // incorrectly captured by this domain
    /*
    const d = domain.create();
    d.on('error', (err) => {
        debug('Middleware domain error %o', err);

        // Pass the error down the middleware stack.
        next(err);
    });

    // Because req and res were created before this domain existed,
    // we need to explicitly add them.  See the explanation of implicit
    // vs explicit binding in the Node domain docs.
    d.add(req);
    d.add(res);

    // Run the middleware stack in our new domain
    d.run(next);
    */
    next();
  };
};

// Return an Express middleware function used to handle uncaught exceptions
const uncaught = (bailcb) => {

  // Call the given bailout callback after returning a 500 error to the client
  return (err, req, res, next) => {
    edebug('Middleware error %o', err);
    debug('Middleware error %o', err);

    // Report the error to the client
    try {
      debug('Sending error %o', err);
      res.status(err.status || err.statusCode || 500).send(extend({
        message: debug.externalize(err)
      }, typeof err === 'object' ? err : {}));
    }
    catch (exc) {
      edebug('Exception sending error %o', exc);
      debug('Exception sending error %o', exc);
    }

    // Call the bailout callback if the error has a bailout flag
    if(err.bailout && bailcb)
      bailcb(err);
  };
};

// Bailout shutdown
const bailout = (err, server, quiesce) => {
  edebug('Bailing out %o', err);
  debug('Bailing out %o', err);

  // Signal that we're exiting soon
  emitter.emit('message', {
    server: {
      exiting: err
    }
  });

  try {
    // Stop accepting any new requests
    try {
      server.close();
    }
    catch (exc) {
      noop();
    }

    // Quiesce if necessary by letting the server finish processing in-flight
    // requests, but don't wait more than 30 seconds, or exit right away
    const exit = () => {
      process.exit(1);
    };
    if(quiesce) {
      debug('Quiescing %d inflight requests', server.inflight);
      if(server.inflight) {
        server.on('quiet', exit);
        const t = setTimeout(exit, 30000);
        if(t.unref) t.unref();
      }
      else exit();
    }
    else exit();

  }
  catch (exc) {
    // Looks like we're pretty messed up here, exit
    edebug('Exception trying to bail out %o', exc);
    debug('Exception trying to bail out %o', exc);
    process.exit(2);
  }
};

// Return the configured port
const defaultPort = memoize(() => {
  return process.env.PORT ? parseInt(process.env.PORT) : 9080;
});

// Return the configured host
const defaultHost = memoize(() => {
  return process.env.HOST;
});

// Return the configured SSL key
const defaultKey = memoize(() => {
  return process.env.KEY;
});

// Return the configured SSL cert
const defaultCert = memoize(() => {
  return process.env.CERT;
});

// Return the contents of a PEM file
const pem = (file, def) => {
  return file || def ? fs.readFileSync(file || def, 'utf8') : undefined;
};

// Configure the listen options
const lconf = (opt) => {
  if(opt !== undefined)
    debug('Listen options %o', opt);
  return typeof opt === 'object' ? {
    hostname: opt.hostname !== undefined ? opt.hostname : defaultHost(),
    port: opt.port !== undefined ? opt.port : defaultPort(),
    key: pem(opt.key, defaultKey()),
    cert: pem(opt.cert, defaultCert())
  } : {
    hostname: defaultHost(),
    port: opt !== undefined ? opt : defaultPort(),
    key: pem(defaultKey()),
    cert: pem(defaultCert())
  };
};

// An implementation of app.listen() that uses our Express handler middleware,
// and the port configured in the app's environment
const listen = function(opt) {
  const app = this;

  // Configure the listen options
  const conf = lconf(opt);

  // Set the process title
  process.title = 'node ' +
    (process.env.TITLE || [vcapenv.appname(), vcapenv.appindex()].join('-')) +
    ' express';

  app.use(catchall());

  if(!app.basic) {
    // Register some of our middleware after the routes
    app.use(sendValue());
    app.use(options());

    // Register debug config middleware
    if(process.env.SECURED === 'true')
      app.use('/debug',
        oauth.validator(process.env.JWTKEY, process.env.JWTALGO));
    app.use('/debug', cdebug());

    // Serve public static resources under the app public dir as well as this
    // module's public dir
    app.use(statics(path.join(process.cwd(), 'public')));
    app.use(statics(path.join(__dirname, 'public')));
  }

  // Catch 404 errors
  app.use((req, res, next) => {
    res.status(404).send({
      error: 'notfound',
      message: 'Not found'
    });
  });

  // Create an HTTP or HTTPS server
  const server = conf.key && conf.cert ? https.createServer({
    key: conf.key,
    cert: conf.cert
  }, app) : http.createServer(app);

  // Handle middleware errors
  app.use(uncaught((err) => {

    // This will be invoked if the err has a bailout flag
    return bailout(err, server, true);
  }));

  // Listen on the configured port
  server.on('error', (err) => {
    // Signal that we encountered a no-retryable error
    emitter.emit('message', {
      server: {
        noretry: err
      }
    });

    edebug('Server error %o', err);
    debug('Server error %o', err);
    return bailout(err, server, false);
  });

  // Log HTTP ugrades to Web sockets
  server.on('upgrade', (req, socket, head) => {
    debug('Server upgrade request %s', req.url);
  });

  // Listen on the configured port
  server.listen(conf.port, conf.hostname, undefined, () => {
    debug('Server listening on %d', server.address().port);

    // Signal that we're listening
    emitter.emit('message', {
      server: {
        listening: server.address().port
      }
    });
  });

  // Return the server we're using
  return server;
};

// Return an Express app configured with our selection of middleware.
const expressApp = () => {

  // Create the Express app
  const app = express();

  // Use most popular Express middleware and our own as well
  // Handle middleware errors
  app.use(catchall());
  app.use(inflight());
  app.set('trust proxy', true);
  app.use(beforeLogger());
  app.use(requestLogger());
  app.use(afterLogger());
  app.use(compression({
    threshold: 150
  }));
  app.use(responseLogger());
  app.use(methodOverride());
  app.use(bodyParser.json({
    limit: '10mb',
    strict: false
  }));
  app.use(bodyParser.json({
    type: 'application/vnd.api+json',
    limit: '10mb',
    strict: false
  }));
  app.use(bodyParser.urlencoded({
    extended: true,
    limit: '10mb'
  }));
  app.use(responseTime());
  app.use(cors());
  app.use(processInfo());
  if(inspector)
    app.use(inspector());

  // Monkey patch app.listen to plug in our additional behavior
  app.listen = listen;

  return app;
};

// Return an Express app configured with a basic minimum selection of
// middleware.
const basicApp = () => {

  // Create the Express app
  const app = express();

  // Indicate that this is a basic app
  app.basic = true;

  // Use most popular Express middleware and our own as well
  // Handle middleware errors
  app.use(catchall());
  app.use(inflight());
  app.set('trust proxy', true);
  app.use(beforeLogger());
  app.use(afterLogger());

  // Monkey patch app.listen to plug in our additional behavior
  app.listen = listen;

  return app;
};

// Set default port and host name, command line has higher priority then
// the existing env, then rc files
const conf = () => {
  process.env.PORT = commander.port || process.env.PORT || 9080;
  if(commander.host)
    process.env.HOST = commander.host;
};

// Command line interface
const runCLI = () => {
  // Parse command line options
  commander
    .option('-p, --port <port>', 'port number [9080]', '9080')
    .option('-h, --host <hostname>', 'host name [*]')
    .option('start', 'start the server')
    .option('stop', 'stop the server')
    .parse(process.argv);

  // Load env from rc file
  rc();

  // Start a Webapp
  if(commander.start) {
    conf();

    // Run the app CLI
    const app = require(process.cwd());
    if(app && app.runCLI)
      app.runCLI();
  }
  else if(commander.stop)
    // Stop the Webapp
    cp.exec('pkill -f "node ' + vcapenv.appname() + '.* express"',
      (err, stdout, stderr) => {
        if(err) debug('Stop error %o', err);
      });
};

// Export our public functions
module.exports = expressApp;
module.exports.basic = basicApp;
module.exports.on = on;
module.exports.runCLI = runCLI;


text:
BEGIN_INANITY

const Platform::NpapiPlugin::Info& Platform::NpapiPlugin::GetInfo()
{
	// information about plugin
	// should be in sync with Windows resource file
	static const Platform::NpapiPlugin::Info info =
	{
		// version
		"1.0.0.1",
		// mime
		"application/x-inanityoil::Inanity Oil NPAPI Plugin",
		// "name"
		"Inanity Oil NPAPI Plugin",
		 // description
		"Inanity Oil NPAPI Plugin"
	};
	return info;
}

ptr<Platform::NpapiPluginInstance> Platform::NpapiPlugin::CreateInstance(int argc, char* argn[], char* argv[])
{
	BEGIN_TRY();

	String instanceType;

	for(int i = 0; i < argc; ++i)
	{
		const char* argName = argn[i];
		const char* argValue = argv[i];

		if(strcmp(argName, "oiltype") == 0)
			instanceType = argValue;
	}

	if(instanceType.empty())
		THROW("No instance type is given");

	if(instanceType == "main")
		return NEW(Oil::MainPluginInstance());
	if(instanceType == "view")
		return NEW(Oil::ViewPluginInstance());

	THROW("Unknown instance type");

	END_TRY("Can't create Oil plugin instance");
}

END_INANITY


text:
import {
  heFengURL,
  heFengKey,
  heFengApiType,
} from '../constants/config';

const fetch = window.fetch;

const generateQuery = (data) => {
  const keys = Object.keys(data);
  let query = '';
  keys.forEach((item) => {
    query += `&${item}=${data[item]}`;
  });
  return `?${query.substr(1)}`;
};

class Request {
  constructor() {
    this.prefix = heFengURL;
    this.key = heFengKey;
    this.requestTypes = heFengApiType;
    this.data = {
      key: heFengKey,
    };
  }
  _fetchData(method, params, success, fail) {
    const isGet = method === 'GET';
    const data = Object.assign({}, this.data, params.data);
    const body = isGet ? {} : JSON.stringify(data);
    const query = isGet ? generateQuery(data) : '';
    const headers = params.header || {};
    const url = `${this.prefix}${params.url}${query}`;
    const requestInfo = {
      method,
      headers,
    };
    if (!isGet) requestInfo.body = body;
    fetch(url, requestInfo)
      .then(res => res.json())
      .then(res => success(res))
      .catch(error => fail(error));
  }
  /*
  ** @params params(Object)
      params: {
        url: '',
        data: {
          city:
        },
      }
  */
  get(params, success, fail) {
    this._fetchData('GET', params, success, fail);
  }
  post(params, success, fail) {
    this._fetchData('POST', params, success, fail);
  }
}

export default Request;


text:
<fold text='h1: # Simage Plugins'># Si<fold text='...'>mage Plugins

The repository contains sources code of SimagePlugins as well as demo maya project.

<!-- TOC depthFrom:2 </fold>-->

[W<fold text='...'>hat is this repository for](#what-is-this-repository-for)

<fold text='unordered list: - [What is this reposi...k-to)'>- [What is this repository for](#what-is-this-repository-for)
- [How do I get set up](#how-do-i-get-set-up)
  <fold text='unordered list:   - [Requirements](#re...bles)'>  - [Requirements](#requirements)
    - [Environment Variables](#environment-variables)</fold>
- [Plugin List](#plugin-list)
  <fold text='unordered list:   - [MxBezier3scalar](...rmer)'>  - [MxBezier3scalar](#mxbezier3scalar)
    - [PushDeformer](#pushdeformer)
    - [NoiseDeformer](#noisedeformer)
    - [SmoothDeformer](#smoothdeformer)</fold>
- [Who do I talk to](#who-do-i-talk-to)</fold>

<!-- /TOC </fold>-->

<fold text='h2: ## What is this repository for'><fold text='h2: ## What is this repository for'>## What is this repository for

<fold text='unordered list: - Maya plugins for Sim... beta'>- Maya plugins for Simage Animation & Media Limited
- Version: 0.0.1 beta</fold></fold>

<fold text='h2: ## How do I get set up'>## How do I get set up

You need to install Maya 2017 as well as Visual Studio 2017 first. After that, setup your [environment variables](#enviroment-variables). It is essential because Visual Studio need these variables to be able to compile successfully. The deliverable is called "SimagePlugins.mll" which contains several plugins (please check out [Plugin List](#plugin-list) below for more details).

<fold text='h3: ### Requirements'>### Requirements

<fold text='unordered list: - Maya 2017
- Visual S... 2017'>- Maya 2017
- Visual Studio 2017</fold></fold>

<fold text='h3: ### Environment Variables'>### Environment Variables

<fold text='table: Name | Description | E...g-ins'>Name | Description | Example
---------|----------|---------
 MAYA_PATH | your install directory of Maya 2017 | C:\Program Files\Autodesk\Maya2017
 MAYA_PLUGIN_PATH | the desitnation folder of Maya plugin |  %USERPROFILE%\Documents\maya\2017\plug-ins</fold></fold></fold>

<fold text='h2: ## Plugin List'>## Plugin List

<fold text='h3: ### MxBezier3scalar'>### MxBezier3scalar

<fold text='unordered list: - A simple node that t...3.mb"'>- A simple node that take a float number (w) as input and generates 3 float numbers (p1, p2, p3) as outputs. You can use this node together with maya's build-in blend shape by driving 3 different blend-shapes' weight with these three outputs. The math is based on Bezier-3 with slight modification in order to make p2 = 1, p1 = 0, p3 = 0 when w = 0.5.
- please see "./MayaProject/scenes/MxBezier3.mb"</fold>

<fold text='table: Parameters | Short Nam...value'>Parameters | Short Name | In/Out | Type | Default Value | Description
---|---|---|---|---|---
 W  | w | In | float | 0 | driving value (from 0 to 1)
 P1 | p1 | Out | float | NA | first component's value
 P2 | p2 | Out | float | NA | second component's value
 P3 | p3 | Out | float | NA | third component's value</fold>

- MEL example

<fold text='code fence: ```mel

//create a Sim...

```'>```mel

//create a Simage_MxBezier3scalar node and name it "SMB3_1"
createNode "Simage_MxBezier3scalar" -n "SMB3_1"

```</fold></fold>

<fold text='h3: ### PushDeformer'>### PushDeformer

<fold text='unordered list: - Push vertex in its n...r.mb"'>- Push vertex in its normal direction.
- please see "./MayaProject/scenes/PushDeformer.mb"</fold>

<fold text='table: Parameters | Short Nam...plier'>Parameters | Short Name | In/Out | Type | Default Value | Description
---|---|---|---|---|---
 amplitude | amp | In | float | 1 | displacement length
 multiplier | mult | In | float | 1 | displacement multiplier</fold>

- MEL example

<fold text='code fence: ```mel

//select a geo...

```'>```mel

//select a geometry first and then run the following script
deformer -type "Simage_PushDeformer"

```</fold></fold>

<fold text='h3: ### NoiseDeformer'>### NoiseDeformer

<fold text='unordered list: - Perform Perlin Noise...r.mb"'>- Perform Perlin Noise deform on geometry.
- please see "./MayaProject/scenes/NoiseDeformer.mb"</fold>

<fold text='table: Parameters | Short Nam...rator'>Parameters | Short Name | In/Out | Type | Default Value | Description
---|---|---|---|---|---
 amplitude | amp | In | float | 1 | the displacement strength
 scale | sc | In | float | 0.01 | noise frequency (the larger the value, the higher the frequency)
 displace X | disx | In | float | 0 | noise displacement in X axis
 displace Y | disy | In | float | 0 | noise displacement in Y axis
 displace Z | disz | In | float | 0 | noise displacement in Z axis
 octave | oct | In | integer | 1 | noise complexity (at least 1)
 seed | seed | In | integer | 123456 | seed for random generator</fold>

- MEL example

<fold text='code fence: ```mel

//select a geo...

```'>```mel

//select a geometry first and then run the following script
deformer -type "Simage_NoiseDeformer"

```</fold></fold>

<fold text='h3: ### SmoothDeformer'>### SmoothDeformer

- Perform smooth deform on geometry.

<fold text='table: Parameters | Short Nam...st 1)'>Parameters | Short Name | In/Out | Type | Default Value | Description
---|---|---|---|---|---
 weight by distance | wbd | In | boolean | false | smooth algorithm will consider the distance between adjacent vertex if this value is set to true
 multiplier | mult | In | float | 1 | the effectiveness of each smoothing step (from 0 to 1)
 iteration | iter | In | integer | 1 | number of smoothing steps (at least 1)</fold>

- MEL example

<fold text='code fence: ```mel

//select a geo...

```'>```mel

//select a geometry first and then run the following script
deformer -type "Simage_SmoothDeformer"

```</fold></fold></fold>

<fold text='h2: ## Who do I talk to'>## Who do I talk to

<fold text='unordered list: - Max Tong: maxtong198...e.hk>'>- Max Tong: maxtong198776@gmail.com

- Simage Animation and Media Limited: <https://www.simage.hk></fold></fold></fold></fold>


text:
"""Test that type checker correcly computes types
   for expressions.
"""
import pytest
import tvm

from tvm import IRModule, te, relay, parser
from tvm.relay import op, transform, analysis

def infer_mod(mod, annotate_spans=True):
    if annotate_spans:
        mod = relay.transform.AnnotateSpans()(mod)

    mod = transform.InferType()(mod)
    return mod

def infer_expr(expr, annotate_spans=True):
    mod = IRModule.from_expr(expr)
    mod = infer_mod(mod, annotate_spans)
    mod = transform.InferType()(mod)
    entry = mod["main"]
    return entry if isinstance(expr, relay.Function) else entry.body

def assert_has_type(expr, typ, mod=None):
    if not mod:
        mod = tvm.IRModule({})

    mod["main"] = expr
    mod = infer_mod(mod)
    checked_expr = mod["main"]
    checked_type = checked_expr.checked_type
    if checked_type != typ:
        raise RuntimeError("Type mismatch %s vs %s" % (checked_type, typ))

def initialize_box_adt(mod):
    # initializes simple ADT for tests
    box = relay.GlobalTypeVar("box")
    tv = relay.TypeVar("tv")
    constructor = relay.Constructor("constructor", [tv], box)
    data = relay.TypeData(box, [tv], [constructor])
    mod[box] = data
    return box, constructor

def test_monomorphic_let():
    "Program: let %x = 1; %x"
    # TODO(@jroesch): this seems whack.
    sb = relay.ScopeBuilder()
    x = relay.var("x", dtype="float64", shape=())
    x = sb.let("x", relay.const(1.0, "float64"))
    sb.ret(x)
    xchecked = infer_expr(sb.get())
    assert xchecked.checked_type == relay.scalar_type("float64")

def test_single_op():
    "Program: fn (%x : float32) { let %t1 = f(%x); %t1 }"
    x = relay.var("x", shape=[])
    func = relay.Function([x], op.log(x))
    ttype = relay.TensorType([], dtype="float32")
    assert_has_type(func, relay.FuncType([ttype], ttype))

def test_add_broadcast_op():
    """
    Program:
        fn (%x: Tensor[(10, 4), float32], %y: Tensor[(5, 10, 1), float32])
            -> Tensor[(5, 10, 4), float32] {
            %x + %y
        }
    """
    x = relay.var("x", shape=(10, 4))
    y = relay.var("y", shape=(5, 10, 1))
    z = x + y
    func = relay.Function([x, y], z)
    t1 = relay.TensorType((10, 4), "float32")
    t2 = relay.TensorType((5, 10, 1), "float32")
    t3 = relay.TensorType((5, 10, 4), "float32")
    expected_ty = relay.FuncType([t1, t2], t3)
    assert_has_type(func, expected_ty)

def test_dual_op():
    """Program:
    fn (%x : Tensor[(10, 10), float32]) {
      let %t1 = log(x);
      let %t2 = add(%t1, %x);
      %t1
    }
    """
    tp = relay.TensorType((10, 10), "float32")
    x = relay.var("x", tp)
    sb = relay.ScopeBuilder()
    t1 = sb.let("t1", relay.log(x))
    t2 = sb.let("t2", relay.add(t1, x))
    sb.ret(t2)
    f = relay.Function([x], sb.get())
    fchecked = infer_expr(f)
    assert fchecked.checked_type == relay.FuncType([tp], tp)

def test_decl():
    """Program:
    def @f(%x : Tensor[(10, 10), float32]) {
        log(%x)
    }
    """
    tp = relay.TensorType((10, 10))
    x = relay.var("x", tp)
    f = relay.Function([x], relay.log(x))
    fchecked = infer_expr(f)
    assert fchecked.checked_type == relay.FuncType([tp], tp)

def test_recursion():
    """
    Program:
       def @f(%n: int32, %data: float32) -> float32 {
          if (%n == 0) {
              %data
          } else {
              @f(%n - 1, log(%data))
          }
       }
    """
    sb = relay.ScopeBuilder()
    f = relay.GlobalVar("f")
    ti32 = relay.scalar_type("int32")
    tf32 = relay.scalar_type("float32")
    n = relay.var("n", ti32)
    data = relay.var("data", tf32)

    with sb.if_scope(relay.equal(n, relay.const(0, ti32))):
        sb.ret(data)
    with sb.else_scope():
        sb.ret(f(relay.subtract(n, relay.const(1, ti32)), relay.log(data)))
    mod = tvm.IRModule()
    mod[f] = relay.Function([n, data], sb.get())
    mod = infer_mod(mod)
    assert "@f(%1, %2)" in mod.astext()
    assert mod["f"].checked_type == relay.FuncType([ti32, tf32], tf32)

def test_incomplete_call():
    tt = relay.scalar_type("int32")
    x = relay.var("x", tt)
    f = relay.var("f")
    func = relay.Function([x, f], relay.Call(f, [x]), tt)

    ft = infer_expr(func)
    f_type = relay.FuncType([tt], tt)
    assert ft.checked_type == relay.FuncType([tt, f_type], tt)

def test_higher_order_argument():
    a = relay.TypeVar("a")
    x = relay.Var("x", a)
    id_func = relay.Function([x], x, a, [a])

    b = relay.TypeVar("b")
    f = relay.Var("f", relay.FuncType([b], b))
    y = relay.Var("y", b)
    ho_func = relay.Function([f, y], f(y), b, [b])

    # id func should be an acceptable argument to the higher-order
    # function even though id_func takes a type parameter
    ho_call = ho_func(id_func, relay.const(0, "int32"))

    hc = infer_expr(ho_call)
    expected = relay.scalar_type("int32")
    assert hc.checked_type == expected

def test_higher_order_return():
    a = relay.TypeVar("a")
    x = relay.Var("x", a)
    id_func = relay.Function([x], x, a, [a])

    b = relay.TypeVar("b")
    nested_id = relay.Function([], id_func, relay.FuncType([b], b), [b])

    ft = infer_expr(nested_id)
    assert ft.checked_type == relay.FuncType([], relay.FuncType([b], b), [b])

def test_higher_order_nested():
    a = relay.TypeVar("a")
    x = relay.Var("x", a)
    id_func = relay.Function([x], x, a, [a])

    choice_t = relay.FuncType([], relay.scalar_type("bool"))
    f = relay.Var("f", choice_t)

    b = relay.TypeVar("b")
    z = relay.Var("z")
    top = relay.Function(
        [f], relay.If(f(), id_func, relay.Function([z], z)), relay.FuncType([b], b), [b]
    )

    expected = relay.FuncType([choice_t], relay.FuncType([b], b), [b])
    ft = infer_expr(top)
    assert ft.checked_type == expected

def test_tuple():
    tp = relay.TensorType((10,))
    x = relay.var("x", tp)
    res = relay.Tuple([x, x])
    assert infer_expr(res).checked_type == relay.TupleType([tp, tp])

def test_ref():
    x = relay.var("x", "float32")
    y = relay.var("y", "float32")
    r = relay.RefCreate(x)
    st = relay.scalar_type("float32")
    assert infer_expr(r).checked_type == relay.RefType(st)
    g = relay.RefRead(r)
    assert infer_expr(g).checked_type == st
    w = relay.RefWrite(r, y)
    assert infer_expr(w).checked_type == relay.TupleType([])

def test_free_expr():
    x = relay.var("x", "float32")
    y = relay.add(x, x)
    yy = infer_expr(y, annotate_spans=False)
    assert tvm.ir.structural_equal(yy.args[0], x, map_free_vars=True)
    assert yy.checked_type == relay.scalar_type("float32")
    assert x.vid.same_as(yy.args[0].vid)

def test_type_args():
    x = relay.var("x", shape=(10, 10))
    y = relay.var("y", shape=(1, 10))
    z = relay.add(x, y)
    ty_z = infer_expr(z)
    ty_args = ty_z.type_args
    assert len(ty_args) == 2
    assert ty_args[0].dtype == "float32"
    assert ty_args[1].dtype == "float32"
    sh1 = ty_args[0].shape
    sh2 = ty_args[1].shape
    assert sh1[0].value == 10
    assert sh1[1].value == 10
    assert sh2[0].value == 1
    assert sh2[1].value == 10

def test_global_var_recursion():
    mod = tvm.IRModule({})
    gv = relay.GlobalVar("main")
    x = relay.var("x", shape=[])
    tt = relay.scalar_type("float32")

    func = relay.Function([x], relay.Call(gv, [x]), tt)
    mod[gv] = func
    mod = infer_mod(mod)
    func_ty = mod["main"].checked_type

    assert func_ty == relay.FuncType([tt], tt)

def test_equal():
    i = relay.var("i", shape=[], dtype="int32")
    eq = op.equal(i, relay.const(0, dtype="int32"))
    func = relay.Function([i], eq)
    ft = infer_expr(func)
    expected = relay.FuncType([relay.scalar_type("int32")], relay.scalar_type("bool"))
    assert ft.checked_type == expected

    assert ft.checked_type == relay.FuncType(
        [relay.scalar_type("int32")], relay.scalar_type("bool")
    )

def test_constructor_type():
    mod = tvm.IRModule()
    box, constructor = initialize_box_adt(mod)

    a = relay.TypeVar("a")
    x = relay.Var("x", a)
    func = relay.Function([x], constructor(x), box(a), [a])
    mod["main"] = func
    mod = infer_mod(mod)
    func_ty = mod["main"].checked_type
    box = mod.get_global_type_var("box")
    expected = relay.FuncType([a], box(a), [a])
    assert func_ty == expected

def test_constructor_call():
    mod = tvm.IRModule()
    box, constructor = initialize_box_adt(mod)

    box_unit = constructor(relay.Tuple([]))
    box_constant = constructor(relay.const(0, "float32"))

    func = relay.Function([], relay.Tuple([box_unit, box_constant]))
    mod["main"] = func
    mod = infer_mod(mod)
    ret_type = mod["main"].checked_type.ret_type.fields
    # NB(@jroesch): when we annotate spans the ast fragments before
    # annotation the previous fragments will no longer be directly equal.
    box = mod.get_global_type_var("box")
    expected1 = box(relay.TupleType([]))
    expected2 = box(relay.TensorType((), "float32"))
    assert ret_type[0] == expected1
    assert ret_type[1] == expected2

def test_adt_match():
    mod = tvm.IRModule()
    box, constructor = initialize_box_adt(mod)

    v = relay.Var("v", relay.TensorType((), "float32"))
    match = relay.Match(
        constructor(relay.const(0, "float32")),
        [
            relay.Clause(
                relay.PatternConstructor(constructor, [relay.PatternVar(v)]), relay.Tuple([])
            ),
            # redundant but shouldn't matter to typechecking
            relay.Clause(relay.PatternWildcard(), relay.Tuple([])),
        ],
    )

    func = relay.Function([], match)
    mod["main"] = func
    mod = infer_mod(mod)
    actual = mod["main"].checked_type.ret_type
    assert actual == relay.TupleType([])

def test_adt_match_type_annotations():
    mod = tvm.IRModule()
    box, constructor = initialize_box_adt(mod)

    # the only type annotation is inside the match pattern var
    # but that should be enough info
    tt = relay.TensorType((2, 2), "float32")
    x = relay.Var("x")
    mv = relay.Var("mv", tt)
    match = relay.Match(
        constructor(x),
        [
            relay.Clause(
                relay.PatternConstructor(constructor, [relay.PatternVar(mv)]), relay.Tuple([])
            )
        ],
    )

    mod["main"] = relay.Function([x], match)
    mod = infer_mod(mod)
    ft = mod["main"].checked_type
    assert ft == relay.FuncType([tt], relay.TupleType([]))

def test_let_polymorphism():
    id = relay.Var("id")
    xt = relay.TypeVar("xt")
    x = relay.Var("x", xt)
    body = relay.Tuple([id(relay.const(1)), id(relay.Tuple([]))])
    body = relay.Let(id, relay.Function([x], x, xt, [xt]), body)
    body = infer_expr(body)
    int32 = relay.TensorType((), "int32")
    tvm.ir.assert_structural_equal(body.checked_type, relay.TupleType([int32, relay.TupleType([])]))

def test_type_arg_infer():
    code = """
#[version = "0.0.5"]
def @id[A](%x: A) -> A {
  %x
}
def @main(%f: float32) -> float32 {
  @id(%f)
}
"""
    mod = tvm.parser.fromtext(code)
    mod = transform.InferType()(mod)
    tvm.ir.assert_structural_equal(mod["main"].body.type_args, [relay.TensorType((), "float32")])

if __name__ == "__main__":
    import sys

    pytest.main(sys.argv)


text:
<?php

class Google_Service_DLP_GooglePrivacyDlpV2InspectResult extends Google_Collection
{
  protected $collection_key = 'findings';
  protected $findingsType = 'Google_Service_DLP_GooglePrivacyDlpV2Finding';
  protected $findingsDataType = 'array';
  public $findingsTruncated;

  /**
   * @param Google_Service_DLP_GooglePrivacyDlpV2Finding
   */
  public function setFindings($findings)
  {
    $this->findings = $findings;
  }
  /**
   * @return Google_Service_DLP_GooglePrivacyDlpV2Finding
   */
  public function getFindings()
  {
    return $this->findings;
  }
  public function setFindingsTruncated($findingsTruncated)
  {
    $this->findingsTruncated = $findingsTruncated;
  }
  public function getFindingsTruncated()
  {
    return $this->findingsTruncated;
  }
}


text:
Train Data Generation
=====================

.. automodule:: yalign.train_data_generation
    :members:
    :undoc-members:
    :show-inheritance:


text:
import _extends from "@babel/runtime/helpers/extends";
import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties";
var _excluded = ["isActive", "editLabel", "doneLabel"];
import { createScopedElement } from "../../lib/jsxRuntime";
import { PanelHeaderButton } from "../PanelHeaderButton/PanelHeaderButton";
import { ANDROID, VKCOM } from "../../lib/platform";
import { Icon28EditOutline, Icon28DoneOutline } from '@vkontakte/icons';
import { usePlatform } from "../../hooks/usePlatform";

var PanelHeaderEdit = function PanelHeaderEdit(_ref) {
  var isActive = _ref.isActive,
      editLabel = _ref.editLabel,
      doneLabel = _ref.doneLabel,
      restProps = _objectWithoutProperties(_ref, _excluded);

  var iOSText = isActive ? doneLabel : editLabel;
  var AndroidIcon = isActive ? Icon28DoneOutline : Icon28EditOutline;
  var platform = usePlatform();
  return createScopedElement(PanelHeaderButton, _extends({
    "aria-label": iOSText
  }, restProps), platform === ANDROID || platform === VKCOM ? createScopedElement(AndroidIcon, null) : iOSText);
};

PanelHeaderEdit.defaultProps = {
  isActive: false,
  editLabel: 'Редактировать',
  doneLabel: 'Готово'
};
export default PanelHeaderEdit;
//# sourceMappingURL=PanelHeaderEdit.js.map


text:
use strict;
use Warnings::Version 'all';

my $foo = 'foo';
my $bar = substr($foo, 4);


text:
package org.ovirt.engine.core.compat;

import org.junit.Test;
import static org.junit.Assert.assertEquals;

public class LogCompatTest {
    LogCompat log = LogFactoryCompat.getLog(LogCompatTest.class);

    @Test
    public void testSimple() {
        assertEquals("Value is 1", log.transform("Value is 1"));
    }

    @Test
    public void testOne() {
        assertEquals("Value is 1", log.transform("Value is {0}", "1"));
    }

    @Test
    public void testTwo() {
        assertEquals("Value is 1,2", log.transform("Value is {0},{1}", "1", "2"));
    }

}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using HtmlAgilityPack;
using MikrainService;

namespace AppleTvLiar.AppleChannels.HtmlManager
{
    public class OnlyMults : AppleBase
    {
        public XDocument GetCategories(string url, string cacheName)
        {
            var cacheDoc = ReadDoc(cacheName);
            if (cacheDoc != null)
            {
                return cacheDoc;
            }

            XDocument xDocument =
              XDocument.Load(Path.Combine(MikrainProgramm._xmlPath, @"Content\categories.xml"));
            var items = xDocument.Descendants(XName.Get("items"));
            var elements = new Dictionary<int, List<XElement>>();

            for (int i = 1; i < 15; i++)
            {
                AddContentInThread(url, i, elements);
            }

            //foreach (var thread in threads)
            //{
            //    thread.Join();
            //}

            for (int i = 1; i < elements.Count; i++)
            {
                if (elements.ContainsKey(i))
                {
                    items.First().Add(elements[i][0]);
                    items.First().Add(elements[i][1]);
                }
            }

            //  threads.Clear();
            elements.Clear();
            SaveDoc(cacheName, xDocument);
            // AddPages(page != null ? int.Parse(page) : 1, items, count);
            return xDocument;
        }

        private void AddContentInThread(string url, int i, Dictionary<int, List<XElement>> elements)
        {
            //var th1 = new Thread(() =>
            //              {
            int count = 0;

            var collectionDividerElement = new XElement(XName.Get("collectionDivider"));
            collectionDividerElement.SetAttributeValue(XName.Get("alignment"), "left");
            collectionDividerElement.SetAttributeValue(XName.Get("accessibilityLabel"), i);
            collectionDividerElement.Add(new XElement(XName.Get("title"), string.Format("Page number {0}", i)));
            var shelfElement = new XElement(XName.Get("shelf"));
            shelfElement.SetAttributeValue(XName.Get("id"), string.Format("shelf_{0}", i));

            var sectionsElement = new XElement(XName.Get("sections"));
            var shelfSectionElement = new XElement(XName.Get("shelfSection"));
            var itemsElement = new XElement(XName.Get("items"));

            shelfSectionElement.Add(itemsElement);
            sectionsElement.Add(shelfSectionElement);
            shelfElement.Add(sectionsElement);

            var html = HttpRequestsString(string.Format("{1}/{0}/", i, url));
            var doc = new HtmlDocument();
            doc.LoadHtml(html);
            var sortNode = doc.GetElementbyId("dle-content");

            if (i == 1)
            {
                CreateElementList(count++, string.Format(
                    "atv.loadURL('http://trailers.apple.com/findMovie?movie={0}')",
                    Uri.EscapeDataString("search")), "search", "http://www.kudoschatsearch.com/images/search.png", itemsElement);
            }

            foreach (var child in sortNode.ChildNodes)
            {
                if (child.Name == "div")
                {
                    var classAttr = child.Attributes["class"].Value;
                    if (classAttr == "post")
                    {
                        var a = child.Element("a");
                        var href = a.Attributes["href"];
                        var div = child.Element("div");
                        var src = div.Element("img").GetAttributeValue("src", "");
                        var title = a.Element("titl").InnerText;
                        var hrefValue = href.Value;

                        src = src.StartsWith("http") ? src : "http://www.onlymults.ru" + src;
                        CreateElementList(count++,
                       string.Format(
                           "atv.loadURL('http://trailers.apple.com/getOnlyMult?movie={0}&imageUrl={1}&movieTitle={2}')",
                           Uri.EscapeDataString(hrefValue), Uri.EscapeDataString(src), Uri.EscapeDataString(title)), title,
                        src, itemsElement);

                    }
                }

            }

            if (elements != null)
                if (!elements.ContainsKey(i))
                    elements.Add(i, new List<XElement>() { collectionDividerElement, shelfElement });
        }

        public async Task<XDocument> GetMovie(string url, string imageUrl, string movieTitle)
        {
            var cacheDoc = ReadDoc(movieTitle);
            if (cacheDoc != null)
            {
                return cacheDoc;
            }

            if (url == "search")
            {
                XDocument searchDoc =
                    XDocument.Load(Path.Combine(MikrainProgramm._xmlPath, @"Content\searchtrailers.xml"));
                var baseUrl = searchDoc.Descendants(XName.Get("baseURL"));
                var firstOrDefault = baseUrl.FirstOrDefault();
                if (firstOrDefault != null)
                    firstOrDefault.SetValue("http://trailers.apple.com/UcozSearch?query=");
                return searchDoc;
            }

            var html = HttpRequests("http://moonwalk.co/api/iframe/?type=film&name=" + movieTitle + "&w=640&h=480&s=moonwalkco&enc=utf-8&nb&nsor&rd=onlymults.ru");

            try
            {
                var doc = new HtmlDocument();
                doc.LoadHtml(html);

                XDocument xDocument =
        XDocument.Load(Path.Combine(MikrainProgramm._xmlPath, @"Content\movieNoBottom.xml"));
                var element = xDocument.Descendants(XName.Get("image"));
                var elementDesc = xDocument.Descendants(XName.Get("summary"));
                var elementName = xDocument.Descendants(XName.Get("title"));
                var actionButtonElement = xDocument.Descendants("actionButton");
                actionButtonElement.Remove();

                var frames = doc.DocumentNode.Descendants("iframe");
                foreach (var htmlNode in frames)
                {
                    try
                    {
                        var source = htmlNode.GetAttributeValue("src", "");

                        string videoSource = source;// source.Replace("iframe", "index.m3u8");

                        if (videoSource.Contains("moonwalk.cc") || true)
                        {
                            var htmlSources = HttpRequestsString(source);
                            var document = new HtmlDocument();
                            document.LoadHtml(htmlSources);

                            var link = await GetLink(document);
                            if (string.IsNullOrEmpty(link)) continue;

                            if (link != null)
                            {
                                videoSource = link;
                            }
                        }

                        CreateActionButton(videoSource, xDocument, "hd");
                        break;
                    }
                    catch (Exception)
                    {

                    }
                }

                element.First().SetValue(imageUrl);
                elementName.First().SetValue(movieTitle);

                elementDesc.First().SetValue("");

                //SaveDoc(movieTitle, xDocument);
                return xDocument;
            }
            catch (Exception exc)
            {

            }

            return null;
        }

        public string HttpRequests(string url)
        {

            var request = (HttpWebRequest)WebRequest.Create(url);
            request.UserAgent = "Mozilla/5.0 (iPad; CPU OS 5_1 like Mac OS X; en-us) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B176 Safari/7534.48.3";
            request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
            request.Headers.Add("DNT", "1");
            //request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate,sdch");
            //request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate,sdch");
            request.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-US,en;q=0.8,he;q=0.6,ru;q=0.4");
            using (var response = (HttpWebResponse)request.GetResponse())
            {

                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    string result = reader.ReadToEnd();
                    return result;
                }
            }
        }
    }
}


text:
Library for integrating secure and easy server side OAuth authentication in Android and (hopefully) IOS applications

#DISCLAIMER
This is my first proper project and I'm developing it as part of a bigger one (so don't expect perfect code), I'll add features when my main project needs them for now, but feel free to tinker with it and if you develop a feature I'll gladly take a look at it and add it in.
Constructive criticism is very appreciated :)

#Why?
The objective of this project is not putting the consumer keys and secrets for the different OAuth apis in the apk because I feel like it is too much of a security hole.


text:
package org.hillview.maps;

import jdk.nashorn.api.scripting.ScriptObjectMirror;
import org.hillview.table.ColumnDescription;
import org.hillview.table.Schema;
import org.hillview.table.api.*;
import org.hillview.table.columns.BaseArrayColumn;
import org.hillview.table.rows.JSVirtualRowSnapshot;
import org.hillview.utils.Converters;

import javax.annotation.Nullable;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.time.Instant;
import java.util.HashMap;

/**
 * This map creates a new column by running a JavaScript
 * function over a set of columns.
 */
public class CreateColumnJSMap extends AppendColumnMap {
    /**
     * A JavaScript function named 'map' that computes the value in the new column.
     * It has a single input, which is a row in the table, and it produces a single output,
     * a value that is written to the destination column.
     */
    private final String jsFunction;
    /**
     * Set of columns that the function can access.
     */
    private final Schema inputColumns;
    /**
     * Description of the output column to produce.
     */
    private final ColumnDescription outputColumn;
    /**
     * A map describing columns that have been renamed by the user
     * mapping the original name to the currently visible name.
     */
    @Nullable
    private final HashMap<String, String> columnRenameMap;

    public CreateColumnJSMap(
            String jsFunction, Schema inputColumns,
            @Nullable
            HashMap<String, String> columnRenameMap,
            ColumnDescription outputColumn) {
        super(outputColumn.name, -1);
        this.jsFunction = jsFunction;
        this.inputColumns = inputColumns;
        this.outputColumn = outputColumn;
        this.columnRenameMap = columnRenameMap;
    }

    @Override
    IColumn createColumn(ITable table) {
        try {
            ScriptEngineManager factory = new ScriptEngineManager();
            ScriptEngine engine = factory.getEngineByName("nashorn");
            // Compiles the JS function
            engine.eval(this.jsFunction);
            Invocable invocable = (Invocable)engine;

            IMutableColumn col = BaseArrayColumn.create(this.outputColumn,
                    table.getMembershipSet().getMax());
            // TODO: ensure that the input columns are loaded.
            ContentsKind kind = this.outputColumn.kind;

            JSVirtualRowSnapshot vrs = new JSVirtualRowSnapshot(
                    table, this.inputColumns, this.columnRenameMap, engine);
            IRowIterator it = table.getMembershipSet().getIterator();
            int r = it.getNextRow();
            while (r >= 0) {
                vrs.setRow(r);
                Object value = invocable.invokeFunction("map", vrs);
                if (value == null)
                    col.setMissing(r);
                else {
                    switch (kind) {
                        case None:
                            col.set(r, value);
                        case String:
                        case Json:
                            col.set(r, value.toString());
                            break;
                        case Date:
                            ScriptObjectMirror jsDate = (ScriptObjectMirror)value;
                            double timestampLocal = (double)jsDate.callMember("getTime");
                            Instant instant = Converters.toDate(timestampLocal);
                            col.set(r, instant);
                            break;
                        case Integer:
                            if (value instanceof Double)
                                col.set(r, (int)(double)value);
                            else if (value instanceof Integer)
                                col.set(r, (int)value);
                            else
                                throw new RuntimeException("Expected a number for Javascript not " +
                                        value.getClass().toString());
                            break;
                        case Double:
                            if (value instanceof Double)
                                col.set(r, (double)value);
                            else if (value instanceof Integer)
                                col.set(r, (double)(int)value);
                            else
                                throw new RuntimeException("Expected a number for Javascript not " +
                                        value.getClass().toString());
                            break;
                        case Duration:
                            // TODO
                            col.set(r, value);
                            break;
                    }
                }
                r = it.getNextRow();
            }
            return col;
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }
}


text:
const test = require('ava');

const Suite = require('../helpers/suite');

test.beforeEach(async t => {
  t.context = new Suite();
  await t.context.init(t);
});

test.afterEach(async t => {
  t.context.passed(t);
});

test.afterEach.always(async t => {
  await t.context.finish(t);
});

test('running pipelines', async t => {
  await t.context.fly.run('set-pipeline -n -p some-pipeline -c fixtures/smoke-pipeline.yml');
  await t.context.fly.run('unpause-pipeline -p some-pipeline');

  await t.context.fly.run('check-resource -r some-pipeline/mockery');

  var result = await t.context.fly.run('trigger-job -j some-pipeline/say-hello -w');
  t.regex(result.stdout, /Hello, world!/);
  t.regex(result.stdout, /pushing version: put-version/);

  await t.context.web.page.goto(t.context.web.route(`/`));
  const group = `.dashboard-team-group[data-team-name="${t.context.teamName}"]`;
  await t.context.web.scrollIntoView(group);
  await t.context.web.waitForText('some-pipeline');

  await t.context.web.page.goto(t.context.web.route(`/teams/${t.context.teamName}/pipelines/some-pipeline`));
  await t.context.web.waitForText('say-hello');

  await t.context.web.page.goto(t.context.web.route(`/teams/${t.context.teamName}/pipelines/some-pipeline/jobs/say-hello/builds/1`));
  await t.context.web.page.waitForSelector('.build-header[style*="rgb(28, 189, 99)"]'); // green
  await t.context.web.clickAndWait('[data-step-name="hello"] .header', '[data-step-name="hello"] .step-body:not(.step-collapsed)');
  await t.context.web.waitForText('Hello, world!');

  t.true(true);
});

test('running one-off builds', async t => {
  var result = await t.context.fly.run('execute -c fixtures/smoke-task.yml -i some-input=fixtures/some-input');
  t.regex(result.stdout, /Hello, world!/);
});

test('reaching the internet', async t => {
  await t.context.fly.run('set-pipeline -n -p some-pipeline -c fixtures/smoke-internet-pipeline.yml');
  await t.context.fly.run('unpause-pipeline -p some-pipeline');

  var result = await t.context.fly.run('trigger-job -j some-pipeline/use-the-internet -w');
  t.regex(result.stdout, /'index.html' saved/);
});


text:
layout: post
title:  "Amanda Murray"
date:   2015-10-23 17:40:06
categories: jekyll update
image: default-image.jpg
description: This is the first Demo post. Click to see full content.
position: Director of Marketing
permalink: /AmandaMurray/
---

![alt text](http://127.0.0.1:4000/assets/images/default-image.jpg)


text:
<?php
namespace Codeception\Command\Shared;
use Codeception\Util\Shared\Namespaces;

trait FileSystem
{
    use Namespaces;

    protected function buildPath($basePath, $testName)
    {
        $basePath = rtrim($basePath, DIRECTORY_SEPARATOR);
        $testName = str_replace(['/','\\'],[DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR], $testName);
        $path = $basePath.DIRECTORY_SEPARATOR.$testName;
        $path = pathinfo($path, PATHINFO_DIRNAME).DIRECTORY_SEPARATOR;
        if (!file_exists($path)) {
            // Second argument should be mode. Well, umask() doesn't seem to return any if not set. Config may fix this.
            mkdir($path, 0775, true); // Third parameter commands to create directories recursively
        }
        return $path;
    }

    protected function getClassName($class)
    {
        $namespaces = $this->breakParts($class);
        return array_pop($namespaces);
    }

    protected function completeSuffix($filename, $suffix)
    {
        if (strpos(strrev($filename), strrev($suffix)) === 0) {
            $filename .= '.php';
        }
        if (strpos(strrev($filename), strrev($suffix . '.php')) !== 0) {
            $filename .= $suffix . '.php';
        }
        if (strpos(strrev($filename), strrev('.php')) !== 0) {
            $filename .= '.php';
        }

        return $filename;
    }

    protected function removeSuffix($classname, $suffix)
    {
        $classname = preg_replace('~\.php$~', '', $classname);
        return preg_replace("~$suffix$~", '', $classname);
    }

    protected function save($filename, $contents, $force = false, $flags = null)
    {
        if (file_exists($filename) && !$force) {
            return false;
        }
        file_put_contents($filename, $contents, $flags);
        return true;
    }

    protected function introduceAutoloader($file, $suffix, $relativePath)
    {
        $line = sprintf(
            '\Codeception\Util\Autoload::registerSuffix(\'%s\', __DIR__.DIRECTORY_SEPARATOR.\'%s\');',
            $suffix,
            $relativePath
        );

        if (!file_exists($file)) {
            return $this->save($file, "<?php \n" . $line);
        }

        $contents = file_get_contents($file);
        if (preg_match('~Autoload::registerSuffix\([\'"]' . $suffix . '[\'"]~', $contents)) {
            return false;
        }
        $contents .= "\n" . $line;

        return $this->save($file, $contents, true);
    }

}