<commit_before>'use strict';

var docBuilder = require('../../../src/lib/docBuilder.js'),
    chai = require('chai'),
    expect = chai.expect,
    config = require('../../../src/config/config'),
    assert = chai.assert;

var getPhraseWithoutDoc = function() {
    return {
    	url: 'url',
        get: {
            code: 'res.render(\'index\', {title: \'test\'});'
        }
    };
};

var getPhrase = function() {
    var phrase = getPhraseWithoutDoc();
    phrase.get.doc = {
        'description': 'This method will get all songs',
        'queryParameters': {
            'genre': {
                'description': 'filter the songs by genre'
            }
        },
        'responses': {
            '200': {
                'body': {
                    'application/json': {
                        'schema': '{ "$schema": "http://json-schema.org/schema"}'
                    },
                    'application/xml': null
                }
            }
        }
    };

    return phrase;
};

describe('in docBuilder', function() {

    var baseUri = config['corbel.driver.options'].urlBase.replace('{{module}}', 'composr');

    it('is defined and is an object', function() {
        expect(docBuilder).to.be.an('object');
    });

    it('expected methods are available', function() {
        expect(docBuilder).to.respondTo('load');
        expect(docBuilder).to.respondTo('buildDefinition');
    });

    describe('when building a raml definition from a phrase', function() {

        it('doc inside a method is required', function() {
            expect(function() {
                docBuilder.buildDefinition('domain', [getPhraseWithoutDoc()]);
            }).to.throw('undefined:phrase:get:doc');
        });

        it('it builds the expected definition', function() {
            var expected = '#%RAML 0.8\n---\ntitle: domain\nbaseUri: https://composr-int.bqws.io/v1.0/domain\nsecuritySchemes:\n    - oauth_2_0:\n        description: Corbel supports OAuth 2.0 for authenticating all API requests.\n        type: OAuth 2.0\n        describedBy:\n            headers:\n                Authorization:\n                    description: Used to send a valid OAuth 2 access token.\n                    type: string\n            responses:\n                401:\n                    description: Bad or expired token. To fix, you should re-authenticate the user.\n        settings:\n            authorizationUri: https://oauth.corbel.io/v1.0/oauth/authorize\n            accessTokenUri: https://iam.corbel.io/v1.0/oauth/token\n            authorizationGrants: [ code, token ]\nresourceTypes:\n    - secured:\n        get?: &common\n            headers:\n                Authorization:\n                    description: Token to access secured resources\n                    type: string\n                    required: true\n        post?: *common\n        patch?: *common\n        put?: *common\n        delete?: *common\n/url:\n    get:\n        description: \'This method will get all songs\'\n        queryParameters:\n            genre: {description: \'filter the songs by genre\'}\n        responses:\n            \'200\': {body: {application/json: {schema: \'{ "$schema": "http://json-schema.org/schema"}\'}, application/xml: null}}\n';
            assert.equal(expected, docBuilder.buildDefinition('domain', [getPhrase()]));
        });
    });

    describe('when loading a raml definition from a phrase', function() {

        it('domain is required', function() {
            expect(function() {
                docBuilder.load();
            }).to.throw('undefined:domain');
        });

        it('phrase is required', function() {
            expect(function() {
                docBuilder.load('domain');
            }).to.throw('undefined:phrase');
        });

        it('the built definition can be loaded by raml', function(done) {
            docBuilder.load('domain', [getPhrase()]).then(function(result) {
            	assert.equal('domain', result.title);
            	assert.equal(baseUri + 'domain', result.baseUri);
            	assert.include('HTTPS', result.protocols);
            	assert.equal('get', result.resources[0].methods[0].method);
            	done();
            }, function(error) {
            	done(error);
            }).done();
        });
    });
});
<commit_msg>doc test updated<commit_after>'use strict';

var docBuilder = require('../../../src/lib/docBuilder.js'),
    chai = require('chai'),
    expect = chai.expect,
    config = require('../../../src/config/config'),
    assert = chai.assert;

var getPhraseWithoutDoc = function() {
    return {
    	url: 'url',
        get: {
            code: 'res.render(\'index\', {title: \'test\'});'
        }
    };
};

var getPhrase = function() {
    var phrase = getPhraseWithoutDoc();
    phrase.get.doc = {
        'description': 'This method will get all songs',
        'queryParameters': {
            'genre': {
                'description': 'filter the songs by genre'
            }
        },
        'responses': {
            '200': {
                'body': {
                    'application/json': {
                        'schema': '{ "$schema": "http://json-schema.org/schema"}'
                    },
                    'application/xml': null
                }
            }
        }
    };

    return phrase;
};

describe('in docBuilder', function() {

    var baseUri = config['corbel.driver.options'].urlBase.replace('{{module}}', 'composr');

    it('is defined and is an object', function() {
        expect(docBuilder).to.be.an('object');
    });

    it('expected methods are available', function() {
        expect(docBuilder).to.respondTo('load');
        expect(docBuilder).to.respondTo('buildDefinition');
    });

    describe('when building a raml definition from a phrase', function() {

        it('doc inside a method is required', function() {
            expect(function() {
                docBuilder.buildDefinition('domain', [getPhraseWithoutDoc()]);
            }).to.throw('undefined:phrase:get:doc');
        });

        it('it builds the expected definition', function() {
            var expected = '#%RAML 0.8\n---\ntitle: domain\nbaseUri: https://composr-qa.bqws.io/v1.0/domain\nsecuritySchemes:\n    - oauth_2_0:\n        description: Corbel supports OAuth 2.0 for authenticating all API requests.\n        type: OAuth 2.0\n        describedBy:\n            headers:\n                Authorization:\n                    description: Used to send a valid OAuth 2 access token.\n                    type: string\n            responses:\n                401:\n                    description: Bad or expired token. To fix, you should re-authenticate the user.\n        settings:\n            authorizationUri: https://oauth.corbel.io/v1.0/oauth/authorize\n            accessTokenUri: https://iam.corbel.io/v1.0/oauth/token\n            authorizationGrants: [ code, token ]\nresourceTypes:\n    - secured:\n        get?: &common\n            headers:\n                Authorization:\n                    description: Token to access secured resources\n                    type: string\n                    required: true\n        post?: *common\n        patch?: *common\n        put?: *common\n        delete?: *common\n/url:\n    get:\n        description: \'This method will get all songs\'\n        queryParameters:\n            genre: {description: \'filter the songs by genre\'}\n        responses:\n            \'200\': {body: {application/json: {schema: \'{ "$schema": "http://json-schema.org/schema"}\'}, application/xml: null}}\n';
            assert.equal(expected, docBuilder.buildDefinition('domain', [getPhrase()]));
        });
    });

    describe('when loading a raml definition from a phrase', function() {

        it('domain is required', function() {
            expect(function() {
                docBuilder.load();
            }).to.throw('undefined:domain');
        });

        it('phrase is required', function() {
            expect(function() {
                docBuilder.load('domain');
            }).to.throw('undefined:phrase');
        });

        it('the built definition can be loaded by raml', function(done) {
            docBuilder.load('domain', [getPhrase()]).then(function(result) {
            	assert.equal('domain', result.title);
            	assert.equal(baseUri + 'domain', result.baseUri);
            	assert.include('HTTPS', result.protocols);
            	assert.equal('get', result.resources[0].methods[0].method);
            	done();
            }, function(error) {
            	done(error);
            }).done();
        });
    });
});
<|endoftext|>


<commit_before>"use strict";

var jsonfile = require('jsonfile'),
	file = './lights.config',
	lights = jsonfile.readFileSync(file);

function Switchery(name) {

	this.name = name;
	this.status = lights[name].status;

	this.changeStatus = function () {
		if (this.status) {
			this.status = false;
			lights[name].status = this.status;
		}
		else {
			this.status = true;
			lights[name].status =this.status;
		}
		jsonfile.writeFileSync(file,lights);
	}
}

function Switches() {

}

module.exports = {
        Switchery: Switchery,
        Switches: Switches
    };<commit_msg>add gpiostatus change numeric<commit_after>"use strict";

var jsonfile = require('jsonfile'),
	file = './lights.config',
	lights = jsonfile.readFileSync(file);

function Switchery(name) {

	this.name = name;
	this.status = lights[name].status;
	this.gpiostatus = lights[name].gpiostatus;

	this.changeStatus = function () {
		if (this.status) {
			this.status = false;
			this.gpiostatus = 0;
			lights[name].status = this.status;
			lights[name].gpiostatus = this.gpiostatus;
		}
		else {
			this.status = true;
			this.gpiostatus = 1;
			lights[name].status =this.status;
			lights[name].gpiostatus = this.gpiostatus;
		}
		jsonfile.writeFileSync(file,lights);
	}
}

function Switches() {

}

module.exports = {
        Switchery: Switchery,
        Switches: Switches
    };<|endoftext|>


<commit_before>import Ember from 'ember';
import { module, test } from 'qunit';
import startApp from 'ember-twiddle/tests/helpers/start-app';
import { findMapText } from 'ember-twiddle/tests/helpers/util';
import ErrorMessages from 'ember-twiddle/helpers/error-messages';
import { stubValidSession } from 'ember-twiddle/tests/helpers/torii';

const firstColumn = '.code:first-of-type';
const firstFilePicker = firstColumn + ' .dropdown-toggle';
const secondFile = firstColumn + ' .dropdown-menu li:nth-child(2) a';
const anyFile = firstColumn + ' .dropdown-menu li:nth-child(1) a';
const fileMenu = '.file-menu .dropdown-toggle';
const deleteAction = '.file-menu a:contains(Delete)';
const addTemplateAction = '.test-template-action';
const firstFilePickerFiles = firstColumn + ' .dropdown-menu>li';
const firstColumnTextarea = firstColumn + ' .CodeMirror textarea';
const displayedFiles = '.file-picker > li > a';

let promptValue = '';

module('Acceptance | gist', {
  beforeEach: function() {
    this.application = startApp();
    this.cacheConfirm = window.confirm;
    this.cachePrompt = window.prompt;
    this.cacheAlert = window.alert;
    window.confirm = () => true;
    window.prompt = () => promptValue;

    server.create('user', 'octocat');
  },

  afterEach: function() {
    Ember.run(this.application, 'destroy');
    window.confirm = this.cacheConfirm;
    window.prompt = this.cachePrompt;
    window.alert = this.cacheAlert;
  }
});

test('deleting a gist loaded in two columns', function(assert) {
  visit('/');

  andThen(function() {
    assert.equal(currentURL(), '/', 'We are on the correct route');
    click(firstFilePicker);
    click(secondFile);
    click(firstFilePicker);
    click(fileMenu);
    click(deleteAction);
    andThen(function() {
      assert.equal(find('.code .CodeMirror').length, 0, 'No code mirror editors active');
      assert.equal(find('.dropdown-toggle:contains(No file selected)').length, 2, 'Shows message when no file is selected.');
      assert.equal(find('.file-menu .test-remove-action').length, 0, 'There no longer is a selected file to delete');
    });

    // TODO: Replace brittle for loop test code with "while there are files left..."
    for (var i = 0; i < 2; ++i) {
      click(firstFilePicker);
      click(anyFile);
      click(fileMenu);
      click(deleteAction);
    }

    andThen(function() {
      click(firstFilePicker);
      assert.ok(find(anyFile).text().indexOf('twiddle.json')!==-1, 'twiddle.json remains');
    });
  });
});

test('can add two templates with different names', function(assert) {
  visit('/');
  let origFiles;

  andThen(function() {
    click(firstFilePicker);
  });

  andThen(function() {
    origFiles = find(firstFilePickerFiles).length;
    promptValue = "foo/template.hbs";
    click(fileMenu);
    click(addTemplateAction);
    click(firstFilePicker);
  });

  let numFiles;

  andThen(function() {
    numFiles = find(firstFilePickerFiles).length;
    assert.equal(numFiles, origFiles + 1, 'Added first file');
    promptValue = "bar/template.hbs";
    click(fileMenu);
    click(addTemplateAction);
    click(firstFilePicker);
  });

  andThen(function() {
    numFiles = find(firstFilePickerFiles).length;
    assert.equal(numFiles, origFiles + 2, 'Added second file');
  });
});

test('can add component (js and hbs)', function(assert){

  let origFileCount;
  promptValue = "components/my-comp";
  visit('/');
  andThen(function(){
    origFileCount =  find(firstFilePickerFiles).length;
  });

  click(fileMenu);
  click('.add-component-link');
  click(firstFilePicker);
  andThen(function() {
    let numFiles = find(firstFilePickerFiles).length;
    assert.equal(numFiles, origFileCount + 2, 'Added component files');
    let fileNames = findMapText(`${firstFilePickerFiles}  a`);
    let jsFile = `${promptValue}.js`;
    let hbsFile = `templates/${promptValue}.hbs`;
    assert.equal(fileNames[3], jsFile);
    assert.equal(fileNames[4], hbsFile);
    let columnFiles = findMapText(displayedFiles);
    assert.deepEqual(columnFiles, [jsFile, hbsFile], 'Added files are displayed');

  });
});

test('can add component (js and hbs) using pod format', function(assert){

  let origFileCount;
  promptValue = "my-comp";
  visit('/');
  andThen(function(){
    origFileCount =  find(firstFilePickerFiles).length;
  });

  click(fileMenu);
  click('.add-component-link');
  click(firstFilePicker);
  andThen(function() {
    let numFiles = find(firstFilePickerFiles).length;
    assert.equal(numFiles, origFileCount + 2, 'Added component files');
    let fileNames = findMapText(`${firstFilePickerFiles}  a`);
    let jsFile = `${promptValue}/component.js`;
    let hbsFile = `${promptValue}/template.hbs`;
    assert.equal(fileNames[3], jsFile);
    assert.equal(fileNames[4], hbsFile);
    let columnFiles = findMapText(displayedFiles);
    assert.deepEqual(columnFiles, [jsFile, hbsFile], 'Added files are displayed');

  });
});

test('component without hyphen fails', function(assert){
  assert.expect(2);

  let called = false;
  window.alert = function(msg){
    called = true;
    assert.equal(msg, ErrorMessages.componentsNeedHyphens);
  };
  promptValue = "components/some-dir/mycomp";

  visit('/');
  click('.add-component-link');
  click(firstFilePicker);
  andThen(function(){
    assert.ok(called, "alert was called");
  });
});

test('can add service', function(assert){
  assert.expect(3);

  let origFileCount;
  promptValue = "my-service/service.js";
  visit('/');
  andThen(function(){
    origFileCount = find(firstFilePickerFiles).length;
  });

  click(fileMenu);
  click('.test-add-service-link');
  click(firstFilePicker);

  andThen(function() {
    let numFiles = find(firstFilePickerFiles).length;
    assert.equal(numFiles, origFileCount + 1, 'Added service file');

    let fileNames = findMapText(`${firstFilePickerFiles}  a`);
    assert.equal(fileNames[3], promptValue, 'Added the file with the right name');

    let columnFiles = findMapText(displayedFiles);
    assert.ok(columnFiles.contains(promptValue), 'Added file is displayed');
  });
});

test('unsaved indicator', function(assert) {
  const indicator = ".test-unsaved-indicator";

  visit('/');

  andThen(function() {
    assert.equal(find(indicator).length, 1, "Unsaved indicator appears when first loading");

    //TODO: implement helper
    //saveFile();
  });

  andThen(function() {
    //assert.equal(find(indicator).length, 0, "Unsaved indicator disappears after saving");

    click(firstColumnTextarea);
    fillIn(firstColumnTextarea, "some text");
    triggerEvent(firstColumnTextarea, "blur");
  });

  andThen(function() {
    assert.equal(find(indicator).length, 1, "Unsaved indicator reappears after editing");
  });
});

test('own gist can be copied into a new one', function(assert) {
  // set owner of gist as currently logged in user
  stubValidSession(this.application, {
    currentUser: { login: "Gaurav0" },
    "github-oauth2": {}
  });

  runGist([
    {
      filename: 'application.template.hbs',
      content: 'hello world!',
    }
  ]);

  fillIn('.title input', "my twiddle");
  andThen(function() {
    assert.equal(find('.title input').val(), "my twiddle");
    assert.equal(find('.test-unsaved-indicator').length, 0, "No unsaved indicator shown");
  });

  click('.test-copy-action');

  andThen(function() {
    assert.equal(find('.title input').val(), "New Twiddle", "Description is reset");
    assert.equal(find('.test-unsaved-indicator').length, 1, "Unsaved indicator appears when gist is copied");
    assert.equal(find('.test-copy-action').length, 0, "Menu item to copy gist is not shown anymore");
    assert.equal(outputContents('div'), 'hello world!');
  });
});

test('accessing /:gist/copy creates a new Twiddle with a copy of the gist', function(assert) {
  runGist([
    {
      filename: 'application.template.hbs',
      content: 'hello world!',
    }
  ]);

  fillIn('.title input', "my twiddle");
  andThen(function() {
    assert.equal(find('.title input').val(), "my twiddle");
    assert.equal(find('.test-unsaved-indicator').length, 0, "No unsaved indicator shown");
  });

  visit('/35de43cb81fc35ddffb2/copy');

  andThen(function() {
    assert.equal(currentURL(), '/');
    assert.equal(find('.title input').val(), "New Twiddle", "Description is reset");
    assert.equal(find('.test-unsaved-indicator').length, 1, "Unsaved indicator appears when gist is copied");
    assert.equal(outputContents('div'), 'hello world!');
  });
});
<commit_msg>Fix failing tests which copy a Twiddle<commit_after>import Ember from 'ember';
import { module, test } from 'qunit';
import startApp from 'ember-twiddle/tests/helpers/start-app';
import { findMapText } from 'ember-twiddle/tests/helpers/util';
import ErrorMessages from 'ember-twiddle/helpers/error-messages';
import { stubValidSession } from 'ember-twiddle/tests/helpers/torii';

const firstColumn = '.code:first-of-type';
const firstFilePicker = firstColumn + ' .dropdown-toggle';
const secondFile = firstColumn + ' .dropdown-menu li:nth-child(2) a';
const anyFile = firstColumn + ' .dropdown-menu li:nth-child(1) a';
const fileMenu = '.file-menu .dropdown-toggle';
const deleteAction = '.file-menu a:contains(Delete)';
const addTemplateAction = '.test-template-action';
const firstFilePickerFiles = firstColumn + ' .dropdown-menu>li';
const firstColumnTextarea = firstColumn + ' .CodeMirror textarea';
const displayedFiles = '.file-picker > li > a';

let promptValue = '';

module('Acceptance | gist', {
  beforeEach: function() {
    this.application = startApp();
    this.cacheConfirm = window.confirm;
    this.cachePrompt = window.prompt;
    this.cacheAlert = window.alert;
    window.confirm = () => true;
    window.prompt = () => promptValue;

    server.create('user', 'octocat');
  },

  afterEach: function() {
    Ember.run(this.application, 'destroy');
    window.confirm = this.cacheConfirm;
    window.prompt = this.cachePrompt;
    window.alert = this.cacheAlert;
  }
});

test('deleting a gist loaded in two columns', function(assert) {
  visit('/');

  andThen(function() {
    assert.equal(currentURL(), '/', 'We are on the correct route');
    click(firstFilePicker);
    click(secondFile);
    click(firstFilePicker);
    click(fileMenu);
    click(deleteAction);
    andThen(function() {
      assert.equal(find('.code .CodeMirror').length, 0, 'No code mirror editors active');
      assert.equal(find('.dropdown-toggle:contains(No file selected)').length, 2, 'Shows message when no file is selected.');
      assert.equal(find('.file-menu .test-remove-action').length, 0, 'There no longer is a selected file to delete');
    });

    // TODO: Replace brittle for loop test code with "while there are files left..."
    for (var i = 0; i < 2; ++i) {
      click(firstFilePicker);
      click(anyFile);
      click(fileMenu);
      click(deleteAction);
    }

    andThen(function() {
      click(firstFilePicker);
      assert.ok(find(anyFile).text().indexOf('twiddle.json')!==-1, 'twiddle.json remains');
    });
  });
});

test('can add two templates with different names', function(assert) {
  visit('/');
  let origFiles;

  andThen(function() {
    click(firstFilePicker);
  });

  andThen(function() {
    origFiles = find(firstFilePickerFiles).length;
    promptValue = "foo/template.hbs";
    click(fileMenu);
    click(addTemplateAction);
    click(firstFilePicker);
  });

  let numFiles;

  andThen(function() {
    numFiles = find(firstFilePickerFiles).length;
    assert.equal(numFiles, origFiles + 1, 'Added first file');
    promptValue = "bar/template.hbs";
    click(fileMenu);
    click(addTemplateAction);
    click(firstFilePicker);
  });

  andThen(function() {
    numFiles = find(firstFilePickerFiles).length;
    assert.equal(numFiles, origFiles + 2, 'Added second file');
  });
});

test('can add component (js and hbs)', function(assert){

  let origFileCount;
  promptValue = "components/my-comp";
  visit('/');
  andThen(function(){
    origFileCount =  find(firstFilePickerFiles).length;
  });

  click(fileMenu);
  click('.add-component-link');
  click(firstFilePicker);
  andThen(function() {
    let numFiles = find(firstFilePickerFiles).length;
    assert.equal(numFiles, origFileCount + 2, 'Added component files');
    let fileNames = findMapText(`${firstFilePickerFiles}  a`);
    let jsFile = `${promptValue}.js`;
    let hbsFile = `templates/${promptValue}.hbs`;
    assert.equal(fileNames[3], jsFile);
    assert.equal(fileNames[4], hbsFile);
    let columnFiles = findMapText(displayedFiles);
    assert.deepEqual(columnFiles, [jsFile, hbsFile], 'Added files are displayed');

  });
});

test('can add component (js and hbs) using pod format', function(assert){

  let origFileCount;
  promptValue = "my-comp";
  visit('/');
  andThen(function(){
    origFileCount =  find(firstFilePickerFiles).length;
  });

  click(fileMenu);
  click('.add-component-link');
  click(firstFilePicker);
  andThen(function() {
    let numFiles = find(firstFilePickerFiles).length;
    assert.equal(numFiles, origFileCount + 2, 'Added component files');
    let fileNames = findMapText(`${firstFilePickerFiles}  a`);
    let jsFile = `${promptValue}/component.js`;
    let hbsFile = `${promptValue}/template.hbs`;
    assert.equal(fileNames[3], jsFile);
    assert.equal(fileNames[4], hbsFile);
    let columnFiles = findMapText(displayedFiles);
    assert.deepEqual(columnFiles, [jsFile, hbsFile], 'Added files are displayed');

  });
});

test('component without hyphen fails', function(assert){
  assert.expect(2);

  let called = false;
  window.alert = function(msg){
    called = true;
    assert.equal(msg, ErrorMessages.componentsNeedHyphens);
  };
  promptValue = "components/some-dir/mycomp";

  visit('/');
  click('.add-component-link');
  click(firstFilePicker);
  andThen(function(){
    assert.ok(called, "alert was called");
  });
});

test('can add service', function(assert){
  assert.expect(3);

  let origFileCount;
  promptValue = "my-service/service.js";
  visit('/');
  andThen(function(){
    origFileCount = find(firstFilePickerFiles).length;
  });

  click(fileMenu);
  click('.test-add-service-link');
  click(firstFilePicker);

  andThen(function() {
    let numFiles = find(firstFilePickerFiles).length;
    assert.equal(numFiles, origFileCount + 1, 'Added service file');

    let fileNames = findMapText(`${firstFilePickerFiles}  a`);
    assert.equal(fileNames[3], promptValue, 'Added the file with the right name');

    let columnFiles = findMapText(displayedFiles);
    assert.ok(columnFiles.contains(promptValue), 'Added file is displayed');
  });
});

test('unsaved indicator', function(assert) {
  const indicator = ".test-unsaved-indicator";

  visit('/');

  andThen(function() {
    assert.equal(find(indicator).length, 1, "Unsaved indicator appears when first loading");

    //TODO: implement helper
    //saveFile();
  });

  andThen(function() {
    //assert.equal(find(indicator).length, 0, "Unsaved indicator disappears after saving");

    click(firstColumnTextarea);
    fillIn(firstColumnTextarea, "some text");
    triggerEvent(firstColumnTextarea, "blur");
  });

  andThen(function() {
    assert.equal(find(indicator).length, 1, "Unsaved indicator reappears after editing");
  });
});

test('own gist can be copied into a new one', function(assert) {
  // set owner of gist as currently logged in user
  stubValidSession(this.application, {
    currentUser: { login: "Gaurav0" },
    "github-oauth2": {}
  });

  runGist([
    {
      filename: 'application.template.hbs',
      content: 'hello world!',
    }
  ]);

  fillIn('.title input', "my twiddle");
  andThen(function() {
    assert.equal(find('.title input').val(), "my twiddle");
    assert.equal(find('.test-unsaved-indicator').length, 0, "No unsaved indicator shown");
  });

  click('.test-copy-action');

  andThen(function() {
    waitForLoadedIFrame();
  });

  andThen(function() {
    assert.equal(find('.title input').val(), "New Twiddle", "Description is reset");
    assert.equal(find('.test-unsaved-indicator').length, 1, "Unsaved indicator appears when gist is copied");
    assert.equal(find('.test-copy-action').length, 0, "Menu item to copy gist is not shown anymore");
    assert.equal(outputContents('div'), 'hello world!');
  });
});

test('accessing /:gist/copy creates a new Twiddle with a copy of the gist', function(assert) {
  runGist([
    {
      filename: 'application.template.hbs',
      content: 'hello world!',
    }
  ]);

  fillIn('.title input', "my twiddle");
  andThen(function() {
    assert.equal(find('.title input').val(), "my twiddle");
    assert.equal(find('.test-unsaved-indicator').length, 0, "No unsaved indicator shown");
  });

  visit('/35de43cb81fc35ddffb2/copy');

  andThen(function() {
    waitForLoadedIFrame();
  });

  andThen(function() {
    assert.equal(currentURL(), '/');
    assert.equal(find('.title input').val(), "New Twiddle", "Description is reset");
    assert.equal(find('.test-unsaved-indicator').length, 1, "Unsaved indicator appears when gist is copied");
    assert.equal(outputContents('div'), 'hello world!');
  });
});
<|endoftext|>


<commit_before>import { timeout } from 'ember-concurrency';
import { test } from '../../tests/helpers/generator-tests';
import { module } from 'qunit';
import { setupApplicationTest } from 'ember-qunit';

import DocsController from 'dummy/docs/controller';

module('Acceptance | root', function(hooks) {
  setupApplicationTest(hooks);

  DocsController.proto().get('flatContents').forEach(page => {
    if (!page.route) { return; }
    test(`visiting ${page.route}`, function * (assert) {
      assert.expect(0);
      let url = page.route.replace(/\./g, '/');
      this.visit(url);
      yield timeout(500);
    });
  });
});
<commit_msg>Cherry-pick less flaky root acceptance test from v2<commit_after>import { module, test, skip } from 'qunit';
import { setupApplicationTest } from 'ember-qunit';
import { visit } from '@ember/test-helpers';
import { run } from '@ember/runloop';
import { gte } from 'ember-compatibility-helpers';
import RSVP from 'rsvp';
import DocsController from 'dummy/docs/controller';

let Promise = RSVP.Promise;

if (gte("3.4.0")) {
  Promise = window.Promise;
}

module('Acceptance | root', function(hooks) {
  setupApplicationTest(hooks);

  DocsController.proto().get('flatContents').forEach(page => {
    if (!page.route) { return; }
    let testMethod = page.skipTest ? skip : test;
    testMethod(`visiting ${page.route}`, async function(assert) {
      assert.expect(0);
      let url = page.route.replace(/\./g, '/');

      visit(url);
      await new Promise(r => {
        setTimeout(() => {
          run.cancelTimers();
          r();
        }, 200);
      });
      run.cancelTimers();
    });
  });
});
<|endoftext|>


<commit_before>/*global System, beforeEach, afterEach, describe, it*/

import { expect } from "mocha-es6";
import { removeDir, createFiles, inspect as i } from "./helpers.js";

import { getSystem, removeSystem, moduleEnv } from "../src/system.js";

var dir = System.normalizeSync("lively.modules/tests/"),
    testProjectDir = dir + "test-project-dir/",
    testProjectSpec = {
      "file1.js": "import { y } from './file2.js'; export var x = y + 2;",
      "file2.js": "export var y = 1;",
      "file3.js": "var zzz = 4; System.global.z = zzz / 2;",
      "file4.js": "export default class Foo { static bar() {} }; Foo.bar();",
      "package.json": JSON.stringify({
                        "name": "test-project-1",
                        "main": "file1.js",
                        "systemjs": {"meta": {"file3.js": {format: "global", exports: "z"}}}
                      })
    }

describe("instrumentation", () => {

  var S;
  beforeEach(() => {
    S = getSystem("test", {baseURL: dir});
    try { delete S.global.z; } catch (e) {}
    try { delete S.global.zzz; } catch (e) {}
    return createFiles(testProjectDir, testProjectSpec)
      .then(() => S.import(testProjectDir + "file1.js"));
  });

  afterEach(() => {
    removeSystem("test");
    return removeDir(testProjectDir);
  });

  it("gets access to internal module state", () => {
    var env = moduleEnv(S, testProjectDir + "file1.js");
    expect(env).to.have.deep.property("recorder.y", 1);
    expect(env).to.have.deep.property("recorder.x", 3);
  });

  describe("of global modules", () => {

    it("can access local state", () =>
      S.import(`${testProjectDir}file3.js`)
        .then(() => {
          var env = moduleEnv(S, `${testProjectDir}file3.js`);
          expect(env).to.have.deep.property("recorder.zzz", 4);
          expect(S.get(testProjectDir + "file3.js")).to.have.property("z", 2);
        }))

  });

  describe("of export default", function() {

    it("class export is recorded", () =>
      S.import(`${testProjectDir}file4.js`)
        .then(() => {
          var env = moduleEnv(S, `${testProjectDir}file4.js`);
          inspect(env)
          expect(env).to.have.deep.property("recorder.Foo");
        }));
  });

});
<commit_msg>cleanup<commit_after>/*global System, beforeEach, afterEach, describe, it*/

import { expect } from "mocha-es6";
import { removeDir, createFiles, inspect as i } from "./helpers.js";

import { getSystem, removeSystem, moduleEnv } from "../src/system.js";

var dir = System.normalizeSync("lively.modules/tests/"),
    testProjectDir = dir + "test-project-dir/",
    testProjectSpec = {
      "file1.js": "import { y } from './file2.js'; export var x = y + 2;",
      "file2.js": "export var y = 1;",
      "file3.js": "var zzz = 4; System.global.z = zzz / 2;",
      "file4.js": "export default class Foo { static bar() {} }; Foo.bar();",
      "package.json": JSON.stringify({
                        "name": "test-project-1",
                        "main": "file1.js",
                        "systemjs": {"meta": {"file3.js": {format: "global", exports: "z"}}}
                      })
    }

describe("instrumentation", () => {

  var S;
  beforeEach(() => {
    S = getSystem("test", {baseURL: dir});
    try { delete S.global.z; } catch (e) {}
    try { delete S.global.zzz; } catch (e) {}
    return createFiles(testProjectDir, testProjectSpec)
      .then(() => S.import(testProjectDir + "file1.js"));
  });

  afterEach(() => {
    removeSystem("test");
    return removeDir(testProjectDir);
  });

  it("gets access to internal module state", () => {
    var env = moduleEnv(S, testProjectDir + "file1.js");
    expect(env).to.have.deep.property("recorder.y", 1);
    expect(env).to.have.deep.property("recorder.x", 3);
  });

  describe("of global modules", () => {

    it("can access local state", () =>
      S.import(`${testProjectDir}file3.js`)
        .then(() => {
          var env = moduleEnv(S, `${testProjectDir}file3.js`);
          expect(env).to.have.deep.property("recorder.zzz", 4);
          expect(S.get(testProjectDir + "file3.js")).to.have.property("z", 2);
        }))

  });

  describe("of export default", function() {

    it("class export is recorded", () =>
      S.import(`${testProjectDir}file4.js`)
        .then(() => {
          var env = moduleEnv(S, `${testProjectDir}file4.js`);
          expect(env).to.have.deep.property("recorder.Foo");
        }));
  });

});
<|endoftext|>


<commit_before>var util = require('../lib/test-utils.js');
var expect = require('chai').expect;

describe('fs.symlink', function() {
  beforeEach(util.setup);
  afterEach(util.cleanup);

  it('should be a function', function() {
    var fs = util.fs();
    expect(fs.symlink).to.be.a('function');
  });

  it('should return an error if part of the parent destination path does not exist', function(done) {
    var fs = util.fs();

    fs.symlink('/', '/tmp/mydir', function(error) {
      expect(error).to.exist;
      expect(error.code).to.equal('ENOENT');
      done();
    });
  });

  it('should return an error if the destination path already exists', function(done) {
    var fs = util.fs();

    fs.symlink('/tmp', '/', function(error) {
      expect(error).to.exist;
      expect(error.code).to.equal('EEXIST');
      done();
    });
  });

  it('should create a symlink', function(done) {
    var fs = util.fs();

    fs.symlink('/', '/myfile', function(error) {
      expect(error).not.to.exist;

      fs.stat('/myfile', function(err, stats) {
        expect(error).not.to.exist;
        expect(stats.type).to.equal('DIRECTORY');
        done();
      });
    });
  });
});
<commit_msg>fix for #542 for fsPromises.symlink(target, path[, type]) (#543)<commit_after>var util = require('../lib/test-utils.js');
var expect = require('chai').expect;

describe('fs.symlink', function() {
  beforeEach(util.setup);
  afterEach(util.cleanup);

  it('should be a function', function() {
    var fs = util.fs();
    expect(fs.symlink).to.be.a('function');
  });

  it('should return an error if part of the parent destination path does not exist', function(done) {
    var fs = util.fs();

    fs.symlink('/', '/tmp/mydir', function(error) {
      expect(error).to.exist;
      expect(error.code).to.equal('ENOENT');
      done();
    });
  });

  it('should return an error if the destination path already exists', function(done) {
    var fs = util.fs();

    fs.symlink('/tmp', '/', function(error) {
      expect(error).to.exist;
      expect(error.code).to.equal('EEXIST');
      done();
    });
  });

  it('should create a symlink', function(done) {
    var fs = util.fs();

    fs.symlink('/', '/myfile', function(error) {
      expect(error).not.to.exist;

      fs.stat('/myfile', function(err, stats) {
        expect(error).not.to.exist;
        expect(stats.type).to.equal('DIRECTORY');
        done();
      });
    });
  });
});

describe('fsPromises.symlink', function () {
  beforeEach(util.setup);
  afterEach(util.cleanup);

  it('should return an error if part of the parent destination path does not exist', () => {
    var fsPromises = util.fs().promises;

    return fsPromises.symlink('/', '/tmp/mydir')
      .catch(error => {
        expect(error).to.exist;
        expect(error.code).to.equal('ENOENT');
      });
  });
});
<|endoftext|>


<commit_before>describe('get_max_profit()', function() {
  describe('returns the minimal loss', function() {
    it('returns -2 for [10, 7, 6, 5, 3, 1]', function() {
      var array = [12, 9, 7, 5, 3, 1];
      expect(get_max_profit(array)).toEqual(-2); // returns 0
    });
    it('returns -1 for [10, 9, 8, 7, 6, 5]', function() {
      var array1 = [10, 9, 8, 7, 6, 4];
      expect(get_max_profit(array1)).toEqual(-1); // returns 0
    });
    it('returns 0 for [9, 8, 7, 7, 7, 6]', function() {
      var array2 = [9, 8, 7, 7, 7, 6];
      expect(get_max_profit(array2)).toEqual(0);
    });
  });

  describe('returns the highest profit', function() {
    it('returns 7 for [10, 4, 5, 6, 7, 2, 9]', function() {
      var array3 = [10, 4, 5, 6, 7, 2, 9];
      expect(get_max_profit(array3)).toEqual(7);
    })
    it('returns 6 for [10, 7, 5, 8, 11, 9]', function() {
      var array2 = [10, 7, 5, 15, 11, 9];
      expect(get_max_profit(array2)).toEqual(10);
    });
  });
});
<commit_msg>change it statement to reflect expect<commit_after>describe('get_max_profit()', function() {
  describe('returns the minimal loss', function() {
    it('returns -2 for [10, 7, 6, 5, 3, 1]', function() {
      var array = [12, 9, 7, 5, 3, 1];
      expect(get_max_profit(array)).toEqual(-2); // returns 0
    });
    it('returns -1 for [10, 9, 8, 7, 6, 5]', function() {
      var array1 = [10, 9, 8, 7, 6, 4];
      expect(get_max_profit(array1)).toEqual(-1); // returns 0
    });
    it('returns 0 for [9, 8, 7, 7, 7, 6]', function() {
      var array2 = [9, 8, 7, 7, 7, 6];
      expect(get_max_profit(array2)).toEqual(0);
    });
  });

// use const i/o var
  describe('returns the highest profit', function() {
    it('returns 7 for [10, 4, 5, 6, 7, 2, 9]', function() {
      var array3 = [10, 4, 5, 6, 7, 2, 9];
      expect(get_max_profit(array3)).toEqual(7);
    })
    it('returns 10 for [10, 7, 5, 15, 11, 9]', function() {
      varc array4 = [10, 7, 5, 15, 11, 9];
      expect(get_max_profit(array4)).toEqual(10);
    });
  });
});
<|endoftext|>


<commit_before>test('watcher/Watcher', [

  '../../lib/watcher/Watcher',
  '../../lib/core/Model'

], function (test) {

  var instance;

  test.beforeEach(function () {
    instance = new test.deps.Watcher(null, {
      'paths': {
        'styles': ['tests/mocks/styles']
      }
    });
  });

  test.afterEach(function () {
    instance.destroy();
  });

  test.spec('startWatching (string path)', function () {

    test.when('path is NOT a string', function () {

      test.it('should throw an error', function () {

        expect(function () {

          instance.startWatching(null);
        }).to.throw(Error);
      });
    });

    test.when('path is a string', function () {

      test.when('a file in the path is added', function () {

        test.it('should call self.handleChange', function (done) {

          var filename = test.getTempFilename();
          var content = '7s89d7a9sd7';

          instance.handleChange = function (changed) {
            if (changed.indexOf(filename) >= 0) {
              done();
            }
          };

          instance.startWatching(test.options.tempPath);
          test.writeTempFile(filename, content);
        });
      });

      test.when('a file in the path is removed', function () {

        test.it('should call self.handleChange', function (done) {

          var filename = test.getTempFilename();
          var content = 'foo';

          instance.handleChange = function (changed) {
            if (changed.indexOf(filename) >= 0) {
              done();
            }
          };

          test.writeTempFile(filename, content);
          instance.startWatching(test.options.tempPath);
          test.removeTempFile(filename);
        });
      });

      test.when('a file in the path is changed', function () {

        test.it('should call self.handleChange', function () {

          var filename = test.getTempFilename();
          var content1 = 'foo';
          var content2 = 'barbaz';

          instance.handleChange = function (changed) {
            if (changed.indexOf(filename) >= 0) {
              done();
            }
          };

          test.writeTempFile(filename, content1);
          instance.startWatching(test.options.tempPath);
          test.writeTempFile(filename, content2);
        });
      });
    });
  });

  test.spec('watch (object model)', function () {

    test.when('model.attributes.type is not defined', function () {

      test.it('should throw an error', function () {

        var model = new test.deps.Model({
          'path': 'foo',
          'raw': 'bar'
        });

        expect(function () {
          instance.watch(model);
        }).to.throw(Error);
      });
    });

    test.when('model.attributes.path is not defined', function () {

      test.it('should throw an error', function () {

        var model = new test.deps.Model({
          'type': 'foo',
          'raw': 'bar'
        });

        expect(function () {
          instance.watch(model);
        }).to.throw(Error);
      });
    });

    test.when('model.attributes.raw is not defined', function () {

      test.it('should throw an error', function () {

        var model = new test.deps.Model({
          'path': 'foo',
          'type': 'bar'
        });

        expect(function () {
          instance.watch(model);
        }).to.throw(Error);
      });
    });

    test.when('a page file is added', function () {
      test.it('should trigger fetch on self.options.pages');
    });

    test.when('a page file is changed', function () {
      test.it('should trigger fetch on all its dependencies');
    });

    test.when('a page file is removed', function () {
      test.it('should trigger fetch on all its dependencies');
    });

    test.when('a content/ subfolder name is changed', function () {
      test.it('should update the url on any page within folder');
      test.it('should update the path on any page within folder');
    });

    test.when('a data textile is added', function () {
      test.it('should trigger fetch on self.options.pages');
    });

    test.when('a data textile is changed', function () {
      test.it('should trigger fetch on all its dependencies');
    });

    test.when('a data textile is removed', function () {
      test.it('should trigger fetch on all its dependencies');
    });

    test.when('a template file is changed', function () {
      test.it('should trigger fetch on all its dependencies');
    });

    test.when('a template file is removed', function () {
      test.it('should trigger fetch on all its dependencies');
    });

    test.when('a stylesheet file is changed', function () {
      test.it('should trigger fetch on all its dependencies');
    });

    test.when('a stylesheet file is removed', function () {
      test.it('should trigger fetch on all its dependencies');
    });

    test.when('a javascript file is changed', function () {
      test.it('should trigger fetch on all its dependencies');
    });

    test.when('a javascript file is removed', function () {
      test.it('should trigger fetch on all its dependencies');
    });

    test.when('a config file is changed', function () {
      test.when('that config file is loaded', function () {
        test.itShouldThrowError();
      });
    });

    test.when('a config file is removed', function () {
      test.when('that config file is loaded', function () {
        test.itShouldThrowError();
      });
    });
  });

  test.spec('parseDependencies (object model)', function () {

    test.when('there is no matching parser for model.attributes.type', function () {

      test.it('should throw an error', function () {

        var model = new test.deps.Model({
          'path': 'foo',
          'type': 'bar',
          'raw': 'baz'
        });

        expect(function () {
          instance.parseDependencies(model);
        }).to.throw(Error);
      });
    });

    test.when('there is a matching parser for model.attributes.type', function () {

      test.it('should pass model as first argument', function () {

        var model = new test.deps.Model({
          'path': 'foo',
          'type': 'styleSheet',
          'raw': 'baz'
        });

        var spy = sinon.spy(instance._parsers.styleSheet, 'parse');

        instance.parseDependencies(model);
        expect(spy).to.have.been.calledWith(model);
        instance._parsers.styleSheet.parse.restore();
      });

      test.it('should pass itself as third argument', function () {

        var model = new test.deps.Model({
          'path': 'foo',
          'type': 'styleSheet',
          'raw': 'baz'
        });

        var spy = sinon.spy(instance._parsers.styleSheet, 'parse');

        instance.parseDependencies(model);
        expect(spy).to.have.been.calledWith(model, null, instance);
        instance._parsers.styleSheet.parse.restore();
      });
    });
  });
});<commit_msg>better watcher test<commit_after>test('watcher/Watcher', [

  '../../lib/watcher/Watcher',
  '../../lib/core/Model'

], function (test) {

  var instance;

  test.beforeEach(function () {
    instance = new test.deps.Watcher(null, {
      'paths': {
        'styles': ['tests/mocks/styles']
      }
    });
  });

  test.afterEach(function () {
    instance.destroy();
  });

  test.spec('startWatching (string path)', function () {

    test.when('path is NOT a string', function () {

      test.it('should throw an error', function () {

        expect(function () {

          instance.startWatching(null);
        }).to.throw(Error);
      });
    });

    test.when('path is a string', function () {

      test.when('a file in the path is added', function () {

        test.it('should call self.handleChange', function (done) {

          this.timeout(5000);

          var filename = test.getTempFilename();
          var content = '7s89d7a9sd7';

          instance.handleChange = function (changed) {
            if (changed.indexOf(filename) >= 0) {
              done();
            }
          };

          instance.startWatching(test.options.tempPath);

          setTimeout(function () {
            test.writeTempFile(filename, content);
          }, 10);
        });
      });

      test.when('a file in the path is removed', function () {

        test.it('should call self.handleChange', function (done) {

          var filename = test.getTempFilename();
          var content = 'foo';

          instance.handleChange = function (changed) {
            if (changed.indexOf(filename) >= 0) {
              done();
            }
          };

          test.writeTempFile(filename, content);
          instance.startWatching(test.options.tempPath);
          test.removeTempFile(filename);
        });
      });

      test.when('a file in the path is changed', function () {

        test.it('should call self.handleChange', function () {

          var filename = test.getTempFilename();
          var content1 = 'foo';
          var content2 = 'barbaz';

          instance.handleChange = function (changed) {
            if (changed.indexOf(filename) >= 0) {
              done();
            }
          };

          test.writeTempFile(filename, content1);
          instance.startWatching(test.options.tempPath);
          test.writeTempFile(filename, content2);
        });
      });
    });
  });

  test.spec('watch (object model)', function () {

    test.when('model.attributes.type is not defined', function () {

      test.it('should throw an error', function () {

        var model = new test.deps.Model({
          'path': 'foo',
          'raw': 'bar'
        });

        expect(function () {
          instance.watch(model);
        }).to.throw(Error);
      });
    });

    test.when('model.attributes.path is not defined', function () {

      test.it('should throw an error', function () {

        var model = new test.deps.Model({
          'type': 'foo',
          'raw': 'bar'
        });

        expect(function () {
          instance.watch(model);
        }).to.throw(Error);
      });
    });

    test.when('model.attributes.raw is not defined', function () {

      test.it('should throw an error', function () {

        var model = new test.deps.Model({
          'path': 'foo',
          'type': 'bar'
        });

        expect(function () {
          instance.watch(model);
        }).to.throw(Error);
      });
    });

    test.when('a page file is added', function () {
      test.it('should trigger fetch on self.options.pages');
    });

    test.when('a page file is changed', function () {
      test.it('should trigger fetch on all its dependencies');
    });

    test.when('a page file is removed', function () {
      test.it('should trigger fetch on all its dependencies');
    });

    test.when('a content/ subfolder name is changed', function () {
      test.it('should update the url on any page within folder');
      test.it('should update the path on any page within folder');
    });

    test.when('a data textile is added', function () {
      test.it('should trigger fetch on self.options.pages');
    });

    test.when('a data textile is changed', function () {
      test.it('should trigger fetch on all its dependencies');
    });

    test.when('a data textile is removed', function () {
      test.it('should trigger fetch on all its dependencies');
    });

    test.when('a template file is changed', function () {
      test.it('should trigger fetch on all its dependencies');
    });

    test.when('a template file is removed', function () {
      test.it('should trigger fetch on all its dependencies');
    });

    test.when('a stylesheet file is changed', function () {
      test.it('should trigger fetch on all its dependencies');
    });

    test.when('a stylesheet file is removed', function () {
      test.it('should trigger fetch on all its dependencies');
    });

    test.when('a javascript file is changed', function () {
      test.it('should trigger fetch on all its dependencies');
    });

    test.when('a javascript file is removed', function () {
      test.it('should trigger fetch on all its dependencies');
    });

    test.when('a config file is changed', function () {
      test.when('that config file is loaded', function () {
        test.itShouldThrowError();
      });
    });

    test.when('a config file is removed', function () {
      test.when('that config file is loaded', function () {
        test.itShouldThrowError();
      });
    });
  });

  test.spec('parseDependencies (object model)', function () {

    test.when('there is no matching parser for model.attributes.type', function () {

      test.it('should throw an error', function () {

        var model = new test.deps.Model({
          'path': 'foo',
          'type': 'bar',
          'raw': 'baz'
        });

        expect(function () {
          instance.parseDependencies(model);
        }).to.throw(Error);
      });
    });

    test.when('there is a matching parser for model.attributes.type', function () {

      test.it('should pass model as first argument', function () {

        var model = new test.deps.Model({
          'path': 'foo',
          'type': 'styleSheet',
          'raw': 'baz'
        });

        var spy = sinon.spy(instance._parsers.styleSheet, 'parse');

        instance.parseDependencies(model);
        expect(spy).to.have.been.calledWith(model);
        instance._parsers.styleSheet.parse.restore();
      });

      test.it('should pass itself as third argument', function () {

        var model = new test.deps.Model({
          'path': 'foo',
          'type': 'styleSheet',
          'raw': 'baz'
        });

        var spy = sinon.spy(instance._parsers.styleSheet, 'parse');

        instance.parseDependencies(model);
        expect(spy).to.have.been.calledWith(model, null, instance);
        instance._parsers.styleSheet.parse.restore();
      });
    });
  });
});<|endoftext|>


<commit_before>// http://gamedev.stackexchange.com/a/42047

//DOM
var canvas = document.getElementById ( 'canvas' );
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var context = canvas.getContext ( '2d' );

//CONSTS
var RIGHT_KEY_CODE = 68;
var LEFT_KEY_CODE = 65;
var UP_KEY_CODE = 87;
var DOWN_KEY_CODE = 83;

var TILE_TYPE_WATER = 0;
var TILE_TYPE_GRASS = 1;
var TILE_TYPE_MOUNTAIN = 2;
var TILE_TYPE_MUD = 3;
var NUM_TILE_TYPES = 4;
var TILE_COLORS = [ '#0000DD', '#00CC00', '#AAAAAA', '#773300' ];

var TILE_SIZE = 50;
var WORLD_SIZE = 2000;
var TILES_IN_A_LINE = Math.floor ( WORLD_SIZE/TILE_SIZE );

//INITIALIZATION
var keysPressed = {};
keysPressed[RIGHT_KEY_CODE] = false;
keysPressed[LEFT_KEY_CODE] = false;
keysPressed[UP_KEY_CODE] = false;
keysPressed[DOWN_KEY_CODE] = false;

var playerX = WORLD_SIZE/2; //center
var playerY = WORLD_SIZE/2; //center

var tileGrid = [];
var tiles = [];

for ( x = 0; x < TILES_IN_A_LINE; x++ ) {
    var collumn = new Array();
    for ( y = 0; y < TILES_IN_A_LINE; y++ ) {
        collumn[y] = Math.floor ( Math.random() * NUM_TILE_TYPES );
    }
    tileGrid[x] = collumn;
}

document.addEventListener ( 'keydown', keyDown, false );
document.addEventListener ( 'keyup', keyUp, false );
//setInterval ( onEnterFrame, 1000 / 30 ); //30 FPS
requestAnimationFrame(onEnterFrame);

var VIEW_HEIGHT, VIEW_TILE_HEIGHT, VIEW_TILE_WIDTH, VIEW_WIDTH;
function setCanvasSize() {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    VIEW_WIDTH = canvas.width;
    VIEW_HEIGHT = canvas.height;
    VIEW_TILE_WIDTH = Math.floor ( VIEW_WIDTH / TILE_SIZE ) + 2;
    VIEW_TILE_HEIGHT = Math.floor ( VIEW_HEIGHT / TILE_SIZE ) + 2;
}
setCanvasSize();

function onEnterFrame() {
    if (keysPressed[RIGHT_KEY_CODE]) playerX = playerX + 20;
    if (keysPressed[LEFT_KEY_CODE]) playerX = playerX - 20;
    if (keysPressed[UP_KEY_CODE]) playerY = playerY - 20;
    if (keysPressed[DOWN_KEY_CODE]) playerY = playerY + 20;

    var top = playerY - VIEW_HEIGHT/2;
    var right = playerX + VIEW_WIDTH/2;
    var bottom = playerY + VIEW_HEIGHT/2;
    var left = playerX - VIEW_WIDTH/2;

    if (top < -TILE_SIZE) {
        playerY += 20;
        return;
    }
    if (right > WORLD_SIZE + TILE_SIZE) {
        playerX -= 20;
        return;
    }
    if (bottom > WORLD_SIZE + TILE_SIZE) {
        playerY -= 20;
        return;
    }
    if (left < -TILE_SIZE) {
        playerX += 20;
        return;
    }

    var leftTile = Math.floor ( left / TILE_SIZE );
    var topTile = Math.floor ( top / TILE_SIZE );

    var tileOffsetX = left % TILE_SIZE;
    var tileOffsetY = top % TILE_SIZE;

    // Fix top and left limits
    if (tileOffsetY < 0) {
        tileOffsetY += TILE_SIZE;
    }
    if (tileOffsetX < 0) {
        tileOffsetX += TILE_SIZE;
    }

    //var playerLocalX = Math.floor ( playerX / TILE_SIZE ) + tileOffsetX;
    //var playerLocalY = Math.floor ( playerY / TILE_SIZE ) + tileOffsetY;
    context.clearRect(0, 0, canvas.width, canvas.height);

    for ( x = 0; x < VIEW_TILE_WIDTH; x++ ) {
        for ( y = 0; y < VIEW_TILE_HEIGHT; y++ ) {
            if (leftTile+x >= 0 && topTile + y >= 0 && leftTile + x < TILES_IN_A_LINE && topTile + y < TILES_IN_A_LINE) {
                var tileColor = tileGrid[leftTile+x][topTile+y];
                context.fillStyle = TILE_COLORS[tileColor];
                context.fillRect ( x * TILE_SIZE - tileOffsetX, y * TILE_SIZE - tileOffsetY, TILE_SIZE, TILE_SIZE );
            }
        }
    }
}

function keyDown(e) {
    if ( e.keyCode in keysPressed ) keysPressed[e.keyCode] = true;
    requestAnimationFrame(onEnterFrame);
}

function keyUp(e) {
    if ( e.keyCode in keysPressed ) keysPressed[e.keyCode] = false;
    requestAnimationFrame(onEnterFrame);
}

window.addEventListener("resize", function () {
    requestAnimationFrame(function () {
        setCanvasSize();
        onEnterFrame();
    });
});<commit_msg>Nicer scroll bounds<commit_after>// http://gamedev.stackexchange.com/a/42047

//DOM
var canvas = document.getElementById ( 'canvas' );
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var context = canvas.getContext ( '2d' );

//CONSTS
var RIGHT_KEY_CODE = 68;
var LEFT_KEY_CODE = 65;
var UP_KEY_CODE = 87;
var DOWN_KEY_CODE = 83;

var TILE_TYPE_WATER = 0;
var TILE_TYPE_GRASS = 1;
var TILE_TYPE_MOUNTAIN = 2;
var TILE_TYPE_MUD = 3;
var NUM_TILE_TYPES = 4;
var TILE_COLORS = [ '#0000DD', '#00CC00', '#AAAAAA', '#773300' ];

var TILE_SIZE = 50;
var WORLD_SIZE = 2000;
var TILES_IN_A_LINE = Math.floor ( WORLD_SIZE/TILE_SIZE );

//INITIALIZATION
var keysPressed = {};
keysPressed[RIGHT_KEY_CODE] = false;
keysPressed[LEFT_KEY_CODE] = false;
keysPressed[UP_KEY_CODE] = false;
keysPressed[DOWN_KEY_CODE] = false;

var playerX = WORLD_SIZE/2; //center
var playerY = WORLD_SIZE/2; //center

var tileGrid = [];
var tiles = [];

for ( x = 0; x < TILES_IN_A_LINE; x++ ) {
    var collumn = new Array();
    for ( y = 0; y < TILES_IN_A_LINE; y++ ) {
        collumn[y] = Math.floor ( Math.random() * NUM_TILE_TYPES );
    }
    tileGrid[x] = collumn;
}

document.addEventListener ( 'keydown', keyDown, false );
document.addEventListener ( 'keyup', keyUp, false );
//setInterval ( onEnterFrame, 1000 / 30 ); //30 FPS
requestAnimationFrame(onEnterFrame);

var VIEW_HEIGHT, VIEW_TILE_HEIGHT, VIEW_TILE_WIDTH, VIEW_WIDTH;
function setCanvasSize() {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    VIEW_WIDTH = canvas.width;
    VIEW_HEIGHT = canvas.height;
    VIEW_TILE_WIDTH = Math.floor ( VIEW_WIDTH / TILE_SIZE ) + 2;
    VIEW_TILE_HEIGHT = Math.floor ( VIEW_HEIGHT / TILE_SIZE ) + 2;
}
setCanvasSize();

function onEnterFrame() {
    if (keysPressed[RIGHT_KEY_CODE]) playerX = playerX + 20;
    if (keysPressed[LEFT_KEY_CODE]) playerX = playerX - 20;
    if (keysPressed[UP_KEY_CODE]) playerY = playerY - 20;
    if (keysPressed[DOWN_KEY_CODE]) playerY = playerY + 20;

    var top = playerY - VIEW_HEIGHT/2;
    var right = playerX + VIEW_WIDTH/2;
    var bottom = playerY + VIEW_HEIGHT/2;
    var left = playerX - VIEW_WIDTH/2;

    if (top < -TILE_SIZE) {
        playerY = VIEW_HEIGHT / 2 - TILE_SIZE;
        //playerY += 20;
        //return;
    }
    if (right > WORLD_SIZE + TILE_SIZE) {
        playerX = WORLD_SIZE + TILE_SIZE - VIEW_WIDTH / 2;
        //playerX -= 20;
        //return;
    }
    if (bottom > WORLD_SIZE + TILE_SIZE) {
        playerY = WORLD_SIZE + TILE_SIZE - VIEW_HEIGHT / 2;
        //playerY -= 20;
        //return;
    }
    if (left < -TILE_SIZE) {
        playerX = VIEW_WIDTH / 2 - TILE_SIZE;
        //playerX += 20;
        //return;
    }

    var leftTile = Math.floor ( left / TILE_SIZE );
    var topTile = Math.floor ( top / TILE_SIZE );

    var tileOffsetX = left % TILE_SIZE;
    var tileOffsetY = top % TILE_SIZE;

    // Fix top and left limits
    if (tileOffsetY < 0) {
        tileOffsetY += TILE_SIZE;
    }
    if (tileOffsetX < 0) {
        tileOffsetX += TILE_SIZE;
    }

    //var playerLocalX = Math.floor ( playerX / TILE_SIZE ) + tileOffsetX;
    //var playerLocalY = Math.floor ( playerY / TILE_SIZE ) + tileOffsetY;
    context.clearRect(0, 0, canvas.width, canvas.height);

    for ( x = 0; x < VIEW_TILE_WIDTH; x++ ) {
        for ( y = 0; y < VIEW_TILE_HEIGHT; y++ ) {
            if (leftTile+x >= 0 && topTile + y >= 0 && leftTile + x < TILES_IN_A_LINE && topTile + y < TILES_IN_A_LINE) {
                var tileColor = tileGrid[leftTile+x][topTile+y];
                context.fillStyle = TILE_COLORS[tileColor];
                context.fillRect ( x * TILE_SIZE - tileOffsetX, y * TILE_SIZE - tileOffsetY, TILE_SIZE, TILE_SIZE );
            }
        }
    }
}

function keyDown(e) {
    if ( e.keyCode in keysPressed ) keysPressed[e.keyCode] = true;
    requestAnimationFrame(onEnterFrame);
}

function keyUp(e) {
    if ( e.keyCode in keysPressed ) keysPressed[e.keyCode] = false;
    requestAnimationFrame(onEnterFrame);
}

window.addEventListener("resize", function () {
    requestAnimationFrame(function () {
        setCanvasSize();
        onEnterFrame();
    });
});<|endoftext|>


<commit_before>Imcms.define("imcms-time-picker", ["imcms", "jquery"], function (imcms, $) {
    var TIME_PICKER_CLASS = "imcms-time-picker",
        TIME_PICKER_CLASS_SELECTOR = ".imcms-time-picker"
    ;

    function optionalAddZeroBeforeNumber(numberStr) {
        if (numberStr === "" || numberStr === null || numberStr === undefined) { // without 0
            return numberStr;
        }

        var result = +numberStr;

        if (result < 10) {
            result = "0" + result;
        }

        return result.toString();
    }

    function getCurrentTimeObj() {
        var currentDate = new Date();
        return {
            hours: optionalAddZeroBeforeNumber(currentDate.getHours()),
            minutes: optionalAddZeroBeforeNumber(currentDate.getMinutes())
        }
    }

    function getDateObjValidated($inputTime) {
        var inputVal = $inputTime.val().split(":"),
            currentTime = getCurrentTimeObj(),
            currentHours = currentTime.hours.toString(),
            currentMinutes = currentTime.minutes.toString(),
            hours = inputVal[0],
            minutes = inputVal[1],
            hasErrorClass = false;

        if (!hours || +hours > 23 || hours.length > 2) {
            hours = currentHours;
            hasErrorClass = true;
        }

        if (!minutes || +minutes > 59 || minutes.length > 2) {
            minutes = currentMinutes;
            hasErrorClass = true;
        }

        if (hasErrorClass) {
            $inputTime.addClass("imcms-current-time__input--error");

        } else {
            $inputTime.removeClass("imcms-current-time__input--error");
        }

        return {
            hours: hours,
            minutes: minutes
        }
    }

    function getTimePicker($timePickerContainer) {
        return $timePickerContainer.hasClass(TIME_PICKER_CLASS)
            ? $timePickerContainer
            : $timePickerContainer.find(TIME_PICKER_CLASS_SELECTOR);
    }

    function apiSetTime($timePickerContainer) {
        return function (time) {
            return $timePickerContainer.find(".imcms-current-time__input")
                .val(time)
                .end();
        }
    }

    function allowNumbersAndColons() {
        var pressedButton = event.key,
            result = true;

        if (pressedButton.length === 1) {
            result = /^[0-9:]$/.test(pressedButton);
        }

        return result;
    }

    function addValuesWithShift(timeValue, value, limit) {
        var result = timeValue + value;

        if (result > limit) {
            result = result - (limit + 1);
        }

        if (result < 0) {
            result = limit;
        }

        result = optionalAddZeroBeforeNumber(result);
        return result;
    }

    function initTimePicker($timePicker, $inputTime) {
        var parsedDate = getDateObjValidated($inputTime);

        $timePicker.find(".imcms-time-picker__time").css("display", "block");

        var hours = +parsedDate.hours,
            minutes = +parsedDate.minutes,
            hoursContainers = $timePicker.find(".imcms-time-picker__hour"),
            minutesContainers = $timePicker.find(".imcms-time-picker__minute");

        hoursContainers.each(function (index) {
            $(this).text(addValuesWithShift(hours, index, 23));
        });

        minutesContainers.each(function (index) {
            $(this).text(addValuesWithShift(minutes, index, 59));
        });
    }

    function arrowButtonsClick() {
        var $clickedArrow = $(this),
            addValue = $clickedArrow.hasClass("imcms-button--increment") ? -1 : 1,
            $timeContainers = $clickedArrow.parent().find("div"),
            limit = $timeContainers.first().hasClass("imcms-time-picker__hour") ? 23 : 59;

        $timeContainers.each(function () {
            var $timeContainer = $(this);
            $timeContainer.text(addValuesWithShift(+$timeContainer.text(), addValue, limit));
        });
    }

    function minutesAndHoursContainersMouseWheel(e) {
        var event = window.event || e;
        event = event.originalEvent ? event.originalEvent : event;

        var delta = event.detail ? event.detail * (-40) : event.wheelDelta,
            mousewheelUp = delta > 0,
            incrementOrDecrementBtnSelector = ".imcms-button--" + ((mousewheelUp) ? "increment" : "decrement");

        $(this).find(incrementOrDecrementBtnSelector).click();

        return false;
    }

    function optionalHighlight(e) {
        var $selectedTimeUnit = $(this),
            isMouseLeaveEvent = e.type === "mouseleave",
            selectedTimeUnitChooseClassName = getChooseClassName($selectedTimeUnit);

        if (!isMouseLeaveEvent) {
            $selectedTimeUnit.addClass(selectedTimeUnitChooseClassName);

        } else {
            $selectedTimeUnit.removeClass(selectedTimeUnitChooseClassName);
        }

        $selectedTimeUnit.siblings().removeClass(selectedTimeUnitChooseClassName);

        function getChooseClassName($timeUnit) {
            return $timeUnit.hasClass("imcms-time-picker__hour")
                ? "imcms-time-picker__hour--choose" : "imcms-time-picker__minute--choose";
        }
    }

    function pickTime() {
        var $selectedTimeUnit = $(this),
            $pickerHourOrMinute = $selectedTimeUnit.parent(),
            hoursPosition = 0,
            minutesPosition = 1,
            $timeInput = $pickerHourOrMinute.parent().siblings().find(".imcms-current-time__input");

        var time = ($timeInput.val() || "00:00").split(":");

        var changedPosition = ($selectedTimeUnit.hasClass("imcms-time-picker__minute"))
            ? minutesPosition : hoursPosition;

        time[changedPosition] = $selectedTimeUnit.text();

        $timeInput.val(time.join(":"));
    }

    function closeTimePickerFunction(e) {
        var className = e.target.className;

        if (className
            && className.indexOf("imcms-time-picker") === -1
            && className.indexOf("imcms-current-time") === -1)
        {
            $(".imcms-time-picker__time").css("display", "none");
        }

        $(".imcms-current-time__input--error").each(function () {
            var currentTime = getCurrentTimeObj();
            var $this = $(this);

            $this.val(currentTime.hours + ":" + currentTime.minutes);
            $this.removeClass("imcms-current-time__input--error")
        });
    }

    $(document).click(closeTimePickerFunction);

    return function ($timePickerContainer, withClock) {
        $timePickerContainer.setTime = apiSetTime($timePickerContainer);

        if (!withClock) {
            return $timePickerContainer;
        }

        var $timePicker = getTimePicker($timePickerContainer),
            $inputTime = $timePicker.find(".imcms-current-time__input"),
            mousewheelEvent = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel";

        $inputTime.click(initTimePicker.bindArgs($timePicker, $inputTime))
            .keydown(allowNumbersAndColons)
            .on("input", initTimePicker.bindArgs($timePicker, $inputTime));

        $timePicker.find(".imcms-time-picker__button")
            .click(arrowButtonsClick)
            .end()
            .find(".imcms-time-picker__hours,.imcms-time-picker__minutes")
            .bind(mousewheelEvent, minutesAndHoursContainersMouseWheel)
            .end()
            .find(".imcms-time-picker__minute,.imcms-time-picker__hour")
            .click(pickTime)
            .mouseenter(optionalHighlight)
            .mouseleave(optionalHighlight);

        return $timePickerContainer;
    };
});
<commit_msg>IMCMS-233 - Upgrade server side to work with new client: - No more setting current time to empty time input.<commit_after>Imcms.define("imcms-time-picker", ["imcms", "jquery"], function (imcms, $) {
    var TIME_PICKER_CLASS = "imcms-time-picker",
        TIME_PICKER_CLASS_SELECTOR = ".imcms-time-picker"
    ;

    function optionalAddZeroBeforeNumber(numberStr) {
        if (numberStr === "" || numberStr === null || numberStr === undefined) { // without 0
            return numberStr;
        }

        var result = +numberStr;

        if (result < 10) {
            result = "0" + result;
        }

        return result.toString();
    }

    function getCurrentTimeObj() {
        var currentDate = new Date();
        return {
            hours: optionalAddZeroBeforeNumber(currentDate.getHours()),
            minutes: optionalAddZeroBeforeNumber(currentDate.getMinutes())
        }
    }

    function getDateObjValidated($inputTime) {
        var time = $inputTime.val(),
            currentTime = getCurrentTimeObj();

        if (!time) {
            return currentTime;
        }

        var inputVal = time.split(":"),
            currentHours = currentTime.hours.toString(),
            currentMinutes = currentTime.minutes.toString(),
            hours = inputVal[0],
            minutes = inputVal[1],
            hasErrorClass = false;

        if (!hours || +hours > 23 || hours.length > 2) {
            hours = currentHours;
            hasErrorClass = true;
        }

        if (!minutes || +minutes > 59 || minutes.length > 2) {
            minutes = currentMinutes;
            hasErrorClass = true;
        }

        $inputTime.toggleClass("imcms-current-time__input--error", hasErrorClass);

        return {
            hours: hours,
            minutes: minutes
        }
    }

    function getTimePicker($timePickerContainer) {
        return $timePickerContainer.hasClass(TIME_PICKER_CLASS)
            ? $timePickerContainer
            : $timePickerContainer.find(TIME_PICKER_CLASS_SELECTOR);
    }

    function apiSetTime($timePickerContainer) {
        return function (time) {
            return $timePickerContainer.find(".imcms-current-time__input")
                .val(time)
                .end();
        }
    }

    function allowNumbersAndColons() {
        var pressedButton = event.key,
            result = true;

        if (pressedButton.length === 1) {
            result = /^[0-9:]$/.test(pressedButton);
        }

        return result;
    }

    function addValuesWithShift(timeValue, value, limit) {
        var result = timeValue + value;

        if (result > limit) {
            result = result - (limit + 1);
        }

        if (result < 0) {
            result = limit;
        }

        result = optionalAddZeroBeforeNumber(result);
        return result;
    }

    function initTimePicker($timePicker, $inputTime) {
        var parsedDate = getDateObjValidated($inputTime);

        $timePicker.find(".imcms-time-picker__time").css("display", "block");

        var hours = +parsedDate.hours,
            minutes = +parsedDate.minutes,
            hoursContainers = $timePicker.find(".imcms-time-picker__hour"),
            minutesContainers = $timePicker.find(".imcms-time-picker__minute");

        hoursContainers.each(function (index) {
            $(this).text(addValuesWithShift(hours, index, 23));
        });

        minutesContainers.each(function (index) {
            $(this).text(addValuesWithShift(minutes, index, 59));
        });
    }

    function arrowButtonsClick() {
        var $clickedArrow = $(this),
            addValue = $clickedArrow.hasClass("imcms-button--increment") ? -1 : 1,
            $timeContainers = $clickedArrow.parent().find("div"),
            limit = $timeContainers.first().hasClass("imcms-time-picker__hour") ? 23 : 59;

        $timeContainers.each(function () {
            var $timeContainer = $(this);
            $timeContainer.text(addValuesWithShift(+$timeContainer.text(), addValue, limit));
        });
    }

    function minutesAndHoursContainersMouseWheel(e) {
        var event = window.event || e;
        event = event.originalEvent ? event.originalEvent : event;

        var delta = event.detail ? event.detail * (-40) : event.wheelDelta,
            mousewheelUp = delta > 0,
            incrementOrDecrementBtnSelector = ".imcms-button--" + ((mousewheelUp) ? "increment" : "decrement");

        $(this).find(incrementOrDecrementBtnSelector).click();

        return false;
    }

    function optionalHighlight(e) {
        var $selectedTimeUnit = $(this),
            isMouseLeaveEvent = e.type === "mouseleave",
            selectedTimeUnitChooseClassName = getChooseClassName($selectedTimeUnit);

        if (!isMouseLeaveEvent) {
            $selectedTimeUnit.addClass(selectedTimeUnitChooseClassName);

        } else {
            $selectedTimeUnit.removeClass(selectedTimeUnitChooseClassName);
        }

        $selectedTimeUnit.siblings().removeClass(selectedTimeUnitChooseClassName);

        function getChooseClassName($timeUnit) {
            return $timeUnit.hasClass("imcms-time-picker__hour")
                ? "imcms-time-picker__hour--choose" : "imcms-time-picker__minute--choose";
        }
    }

    function pickTime() {
        var $selectedTimeUnit = $(this),
            $pickerHourOrMinute = $selectedTimeUnit.parent(),
            hoursPosition = 0,
            minutesPosition = 1,
            $timeInput = $pickerHourOrMinute.parent().siblings().find(".imcms-current-time__input");

        var time = ($timeInput.val() || "00:00").split(":");

        var changedPosition = ($selectedTimeUnit.hasClass("imcms-time-picker__minute"))
            ? minutesPosition : hoursPosition;

        time[changedPosition] = $selectedTimeUnit.text();

        $timeInput.val(time.join(":"));
    }

    function closeTimePickerFunction(e) {
        var className = e.target.className;

        if (className
            && className.indexOf("imcms-time-picker") === -1
            && className.indexOf("imcms-current-time") === -1)
        {
            $(".imcms-time-picker__time").css("display", "none");
        }

        $(".imcms-current-time__input--error").each(function () {
            var currentTime = getCurrentTimeObj();
            var $this = $(this);

            $this.val(currentTime.hours + ":" + currentTime.minutes);
            $this.removeClass("imcms-current-time__input--error")
        });
    }

    $(document).click(closeTimePickerFunction);

    return function ($timePickerContainer, withClock) {
        $timePickerContainer.setTime = apiSetTime($timePickerContainer);

        if (!withClock) {
            return $timePickerContainer;
        }

        var $timePicker = getTimePicker($timePickerContainer),
            $inputTime = $timePicker.find(".imcms-current-time__input"),
            mousewheelEvent = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel";

        $inputTime.click(initTimePicker.bindArgs($timePicker, $inputTime))
            .keydown(allowNumbersAndColons)
            .on("input", initTimePicker.bindArgs($timePicker, $inputTime));

        $timePicker.find(".imcms-time-picker__button")
            .click(arrowButtonsClick)
            .end()
            .find(".imcms-time-picker__hours,.imcms-time-picker__minutes")
            .bind(mousewheelEvent, minutesAndHoursContainersMouseWheel)
            .end()
            .find(".imcms-time-picker__minute,.imcms-time-picker__hour")
            .click(pickTime)
            .mouseenter(optionalHighlight)
            .mouseleave(optionalHighlight);

        return $timePickerContainer;
    };
});
<|endoftext|>


<commit_before><commit_msg>HYD-1297 Relative zoom button.<commit_after><|endoftext|>


<commit_before>/**
 * Russian translation for bootstrap-datepicker
 * Victor Taranenko <darwin@snowdale.com>
 */
;
(function ($) {
	$.fn.datepicker.dates['ru'] = {
		days: ["Воскресенье", "Понедельник", "Вторник", "Среда", "Четверг", "Пятница", "Суббота", "Воскресенье"],
		daysShort: ["Вск", "Пнд", "Втр", "Срд", "Чтв", "Птн", "Суб", "Вск"],
		daysMin: ["Вс", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб", "Вс"],
		months: ["Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь"],
		monthsShort: ["Янв", "Фев", "Мар", "Апр", "Май", "Июн", "Июл", "Авг", "Сен", "Окт", "Ноя", "Дек"],
		today: "Сегодня",
		weekStart: 1
	};
}(jQuery));
<commit_msg>Fix #162: Russian translation enh for DatePicker plugin<commit_after>/**
 * Russian translation for bootstrap-datepicker
 * Victor Taranenko <darwin@snowdale.com>
 */
;
(function ($) {
	$.fn.datepicker.dates['ru'] = {
		days: ["Воскресенье", "Понедельник", "Вторник", "Среда", "Четверг", "Пятница", "Суббота", "Воскресенье"],
		daysShort: ["Вск", "Пнд", "Втр", "Срд", "Чтв", "Птн", "Суб", "Вск"],
		daysMin: ["Вс", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб", "Вс"],
		months: ["Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь"],
		monthsShort: ["Янв", "Фев", "Мар", "Апр", "Май", "Июн", "Июл", "Авг", "Сен", "Окт", "Ноя", "Дек"],
		today: "Сегодня",
		weekStart: 1,
		clear: "Закрыть"
	};
}(jQuery));
<|endoftext|>


<commit_before><commit_msg>reset typehead in ConvertMultisigModal.resetDefaultData (typing is still wrong...)<commit_after><|endoftext|>


<commit_before><commit_msg>chore(tests :rotating_light:) - trying to debug e2e tests in CI<commit_after><|endoftext|>


<commit_before>'use strict';

angular.module('reports').directive('boxPlot', ['D3', '$window',
	function(D3, $window) {
		return {
			restrict : 'EA',
			scope : {},
			link : function(scope, element, attrs) {
				D3.d3().then(function(d3) {
					scope.$parent.report.$promise.then(function() {
						var project = scope.$parent.report.project;
						// d3 is the raw d3 object
						var body = d3.select(element[0]).append('p');
						//.attr('width', 50)
						//.attr('height', 50);
						//d3.select("body").node().getBoundingClientRect().width
						var bodyWidth = body.node().getBoundingClientRect().width;
						var bodyHeight = 50;
						var body = d3.select(element[0]);
						body.append('p').text('Box plot!');

						var createBox = function(_range, _minOutlier, _minStdDeviation, _median, _maxStdDeviation, _maxOutlier) {
							var svg = body.append('svg')
							.attr('width', bodyWidth)
							.attr('height', bodyHeight);
							var middleHeight = (bodyHeight / 2);
							var middleWidht = (bodyWidth / 2);
							var range = _range;
							var ratio = parseInt(bodyWidth / range);
							var strokeWidth = 30;
							var minOutlier = _minOutlier * ratio;
							var minStdDeviation = _minStdDeviation * ratio;
							var median = _median * ratio;
							var maxStdDeviation = _maxStdDeviation * ratio;
							var maxOutlier = _maxOutlier * ratio;
							/*
							Creating the left line
							*/
							svg.append('line')
							.attr('x1', 0 + minOutlier)
							.attr('y1', middleHeight)
							.attr('x2', maxOutlier)
							.attr('y2', middleHeight)
							.style('stroke', 'black')
							.style('stroke-dasharray', ('3, 3'));

							var boxWidth = 200;
							var boxHeight = bodyHeight - strokeWidth;
							/*
							Creating the first wisker
							*/
							var boxUpDownLength = boxHeight / 2;
							svg.append('line')
							.attr('x1', minOutlier)
							.attr('y1', middleHeight + boxUpDownLength)
							.attr('x2', minOutlier)
							.attr('y2', middleHeight - boxUpDownLength)
							.style('stroke', 'black');

							/*
							Creating the second wisker
							*/
							svg.append('line')
							.attr('x1', maxOutlier)
							.attr('y1', middleHeight + boxUpDownLength)
							.attr('x2', maxOutlier)
							.attr('y2', middleHeight - boxUpDownLength)
							.style('stroke', 'black');

							/*
							Creating the square
							 */

							var box = svg.append('rect')
							.attr('width', maxStdDeviation - minStdDeviation)
							.attr('height', boxHeight)
							.attr('x', minStdDeviation)
							.attr('y', (bodyHeight / 2) - (boxHeight / 2))
							.attr('rx', 5)
							.attr('rx', 5)
							.style('fill', 'lightblue')
							.style('stroke', 'black');

							/*
							Creating the median
							*/
							svg.append('line')
							.attr('x1', median)
							.attr('y1', middleHeight + boxUpDownLength)
							.attr('x2', median)
							.attr('y2', middleHeight - boxUpDownLength)
							.style('stroke', 'black');
						};

						createBox(100, 10, 20, 30, 40, 50);
						createBox(100, 20, 30, 40, 50, 60);
						createBox(200, 30, 40, 50, 60, 70);

						var visit = function(node, project, data) {
							for (var i = 0; i < node.estimations.length; ++i) {
								var estimationMean = parseFloat((parseInt(node.minestimations[i]) + 4 * parseInt(node.estimations[i]) + parseInt(node.maxestimations[i])) / 6).toFixed(2);
								var stdDeviation = parseFloat((parseInt(node.minestimations[i]) - parseInt(node.maxestimations[i])) / 6).toFixed(2);

								var minOutlier;
								var minStdDeviation = parseFloat((parseFloat(estimationMean) + parseFloat(stdDeviation)));
								if (node.minestimations[i] < minStdDeviation) {
									minOutlier = parseInt(node.minestimations[i]);
								} else {
									minOutlier = parseFloat(minStdDeviation);
								}
								var maxOutlier;
								var maxStdDeviation = parseFloat((parseFloat(estimationMean) - parseFloat(stdDeviation)));
								if (node.maxestimations[i] > maxStdDeviation) {
									maxOutlier = parseInt(node.maxestimations[i]);
								} else {
									maxOutlier = parseFloat(maxStdDeviation);
								}
								console.log(40 + '}{' + minOutlier + '}{' + minStdDeviation + '}{' + estimationMean + '}{' + maxStdDeviation + '}{' + maxOutlier);
								createBox(50, minOutlier, minStdDeviation, estimationMean, maxStdDeviation, maxOutlier);
							}
						};

						var traverseTree = function(node, project, data) {
							if (node === null) {
								return;
							}
							visit(node, project, data);
							for (var i = 0; i < node.nodes.length; ++i) {
								traverseTree(node.nodes[i], project, data);
							}
						};

						var generateReport = function(project, data) {
							var projectTree = project.children[0];
							traverseTree(projectTree, project, data);
						};

						scope.data = [];

						generateReport(project, scope.data);

						/*
						var circle = svg.append('circle')
						.attr('cx', 25)
						.attr('cy', 25)
						.attr('r', 25)
						.style('fill', 'purple');

						//var svg = body.append('circle')
						//.attr('cx', 25)
						//.attr('cy', 25)
						//.attr('r', 25)
						//.style('fill', 'purple');
						var theData = [1, 2, 3, 4];
						body.selectAll('p')
						.data(theData)
						.enter()
						.append('p')
						.text(function(d , i) {
							return d + 'I will cahnge you forever' + 'index is ' + i;
						});

						var xdir = 0;
						var circleRadii = [40, 20, 10];
						svg.selectAll('circle')
						.data(circleRadii)
						.enter()
						.append('circle')
						.attr('cx', function(x) {
							xdir = xdir + 100;
							return xdir;
						})
						.attr('cy', 50)
						.attr('r', 25)
						.style('fill', function(d) {
							var color;
							if (d === 40) {
								color = 'green';
							}
							if (d === 20) {
								color = 'red';
							}
							return color;
						});
						*/

					});
				});
				//element.text('this is the boxPlot directive');
			}
		};
	}
]);
<commit_msg>added some text to the box plot<commit_after>'use strict';

angular.module('reports').directive('boxPlot', ['D3', '$window',
	function(D3, $window) {
		return {
			restrict : 'EA',
			scope : {},
			link : function(scope, element, attrs) {
				D3.d3().then(function(d3) {
					scope.$parent.report.$promise.then(function() {
						var project = scope.$parent.report.project;
						// d3 is the raw d3 object
						var body = d3.select(element[0]).append('p');
						//.attr('width', 50)
						//.attr('height', 50);
						//d3.select("body").node().getBoundingClientRect().width
						var bodyWidth = body.node().getBoundingClientRect().width;
						var bodyHeight = 30;
						var body = d3.select(element[0]);
						body.append('p').text('Box plot!');

						var createBox = function(_range, _minOutlier, _minStdDeviation, _median, _maxStdDeviation, _maxOutlier) {
							var strokeWidth = 2;
							var bar = body.append('svg')
							.attr('width', bodyWidth + strokeWidth)
							.attr('height', bodyHeight + strokeWidth);

							var svg = body.append('svg')
							.attr('width', bodyWidth + strokeWidth)
							.attr('height', bodyHeight + strokeWidth);

							var middleHeight = (bodyHeight / 2);
							var middleWidht = (bodyWidth / 2);
							var range = _range;
							var ratio = parseInt(bodyWidth / range);
							var strokeWidth = 2;
							var minOutlier = _minOutlier * ratio;
							var minStdDeviation = _minStdDeviation * ratio;
							var median = _median * ratio;
							var maxStdDeviation = _maxStdDeviation * ratio;
							var maxOutlier = _maxOutlier * ratio;
							/*
							Creating the left line
							*/
							svg.append('line')
							.attr('x1', 0 + minOutlier)
							.attr('y1', middleHeight)
							.attr('x2', maxOutlier)
							.attr('y2', middleHeight)
							.style('stroke', 'black')
							.style('stroke-dasharray', ('3, 3'));

							var boxWidth = 200;
							var boxHeight = bodyHeight - strokeWidth;
							/*
							Creating the first wisker
							*/
							var boxUpDownLength = boxHeight / 2;
							svg.append('line')
							.attr('x1', minOutlier)
							.attr('y1', middleHeight + boxUpDownLength)
							.attr('x2', minOutlier)
							.attr('y2', middleHeight - boxUpDownLength)
							.style('stroke', 'black');

							/*
							Creating the second wisker
							*/
							svg.append('line')
							.attr('x1', maxOutlier)
							.attr('y1', middleHeight + boxUpDownLength)
							.attr('x2', maxOutlier)
							.attr('y2', middleHeight - boxUpDownLength)
							.style('stroke', 'black');

							/*
							Creating the square
							 */

							var box = svg.append('rect')
							.attr('width', maxStdDeviation - minStdDeviation)
							.attr('height', boxHeight - strokeWidth)
							.attr('x', minStdDeviation)
							.attr('y', (bodyHeight / 2) - (boxHeight / 2))
							.attr('rx', 5)
							.attr('rx', 5)
							.style('fill', 'lightblue')
							.style('stroke', 'black');

							/*
							Creating the median
							*/
							svg.append('line')
							.attr('x1', median)
							.attr('y1', middleHeight + boxUpDownLength - strokeWidth)
							.attr('x2', median)
							.attr('y2', middleHeight - boxUpDownLength - strokeWidth)
							.style('stroke', 'black');

							/*
							Creating the
							*/
							bar.append('rect')
							.attr('width', maxOutlier)
							.attr('height', boxHeight)
							.attr('x', 0)
							.attr('y', 0)
							.attr('rx', 5)
							.attr('rx', 5)
							.style('fill', 'lightblue')
							.style('stroke', 'black');

							bar.append('text')         // append text
						    .style('fill', 'black')   // fill the text with the colour black
						    .attr('x', 10)           // set x position of left side of text
						    .attr('y', middleHeight+5)           // set y position of bottom of text
						    .text("Total Units: " + _maxOutlier);

						    bar.append('text')         // append text
						    .style('fill', 'black')   // fill the text with the colour black
						    .attr('x', median)           // set x position of left side of text
						    .attr('y', middleHeight+5)           // set y position of bottom of text
						    .text("Median: " + parseInt(_median));
						};

						//createBox(100, 10, 20, 30, 40, 50);
						//createBox(100, 20, 30, 40, 50, 60);
						//createBox(200, 30, 40, 50, 60, 70);
						//
						var maxRange = 0;
						var minRange = 999999999;
						var visitRange = function(node, project, data) {
							for (var i = 0; i < node.estimations.length; ++i) {
								var estimationMean = parseFloat((parseInt(node.minestimations[i]) + 4 * parseInt(node.estimations[i]) + parseInt(node.maxestimations[i])) / 6).toFixed(2);
								var stdDeviation = parseFloat((parseInt(node.minestimations[i]) - parseInt(node.maxestimations[i])) / 6).toFixed(2);

								var minOutlier;
								var minStdDeviation = parseFloat((parseFloat(estimationMean) + parseFloat(stdDeviation)));
								if (node.minestimations[i] < minStdDeviation) {
									minOutlier = parseInt(node.minestimations[i]);
								} else {
									minOutlier = parseFloat(minStdDeviation);
								}
								var maxOutlier;
								var maxStdDeviation = parseFloat((parseFloat(estimationMean) - parseFloat(stdDeviation)));
								if (node.maxestimations[i] > maxStdDeviation) {
									maxOutlier = parseInt(node.maxestimations[i]);
								} else {
									maxOutlier = parseFloat(maxStdDeviation);
								}
								if (minOutlier < minRange) {
									minRange = minOutlier;
								}
								if (maxOutlier > maxRange) {
									maxRange = maxOutlier;
								}

							}
						};

						var visitCalc = function(node, project, data) {
							for (var i = 0; i < node.estimations.length; ++i) {
								var estimationMean = parseFloat((parseInt(node.minestimations[i]) + 4 * parseInt(node.estimations[i]) + parseInt(node.maxestimations[i])) / 6).toFixed(2);
								var stdDeviation = parseFloat((parseInt(node.minestimations[i]) - parseInt(node.maxestimations[i])) / 6).toFixed(2);

								var minOutlier;
								var minStdDeviation = parseFloat((parseFloat(estimationMean) + parseFloat(stdDeviation)));
								if (node.minestimations[i] < minStdDeviation) {
									minOutlier = parseInt(node.minestimations[i]);
								} else {
									minOutlier = parseFloat(minStdDeviation);
								}
								var maxOutlier;
								var maxStdDeviation = parseFloat((parseFloat(estimationMean) - parseFloat(stdDeviation)));
								if (node.maxestimations[i] > maxStdDeviation) {
									maxOutlier = parseInt(node.maxestimations[i]);
								} else {
									maxOutlier = parseFloat(maxStdDeviation);
								}
								//console.log(40 + '}{' + minOutlier + '}{' + minStdDeviation + '}{' + estimationMean + '}{' + maxStdDeviation + '}{' + maxOutlier);
								createBox(maxRange - minRange, minOutlier - minRange, minStdDeviation - minRange, estimationMean - minRange, maxStdDeviation - minRange, maxOutlier - minRange);
							}
						};

						var traverseTree = function(node, project, data, visit) {
							if (node === null) {
								return;
							}
							visit(node, project, data);
							for (var i = 0; i < node.nodes.length; ++i) {
								traverseTree(node.nodes[i], project, data, visit);
							}
						};

						var generateReport = function(project, data , visit) {
							var projectTree = project.children[0];
							traverseTree(projectTree, project, data, visit);
						};

						scope.data = [];
						generateReport(project, scope.data, visitRange);
						generateReport(project, scope.data, visitCalc);

						/*
						var circle = svg.append('circle')
						.attr('cx', 25)
						.attr('cy', 25)
						.attr('r', 25)
						.style('fill', 'purple');

						//var svg = body.append('circle')
						//.attr('cx', 25)
						//.attr('cy', 25)
						//.attr('r', 25)
						//.style('fill', 'purple');
						var theData = [1, 2, 3, 4];
						body.selectAll('p')
						.data(theData)
						.enter()
						.append('p')
						.text(function(d , i) {
							return d + 'I will cahnge you forever' + 'index is ' + i;
						});

						var xdir = 0;
						var circleRadii = [40, 20, 10];
						svg.selectAll('circle')
						.data(circleRadii)
						.enter()
						.append('circle')
						.attr('cx', function(x) {
							xdir = xdir + 100;
							return xdir;
						})
						.attr('cy', 50)
						.attr('r', 25)
						.style('fill', function(d) {
							var color;
							if (d === 40) {
								color = 'green';
							}
							if (d === 20) {
								color = 'red';
							}
							return color;
						});
						*/

					});
				});
				//element.text('this is the boxPlot directive');
			}
		};
	}
]);
<|endoftext|>


<commit_before>var addCollectionMethods = require('./lib/add-collection-methods')
var computed = require('./computed')
var KeyValue = require('./lib/key-value')
var resolve = require('./resolve')
var isObservable = require('./is-observable')

module.exports = function DictToCollection (obs) {
  var value = []
  var raw = []

  var instance = computed.extended(obs, function () {
    var keys = getKeys(obs)
    var length = keys.length

    for (var i = 0; i < length; i++) {
      var key = keys[i]
      var item = obs.get(key)
      if (shouldUpdate(item, raw[i])) {
        if (raw[i].value !== item) {
          raw[i].value.set(item)
        }
      } else {
        raw[i] = KeyValue(key, item)
      }
      value[i] = resolve(raw[i])
    }

    raw.length = value.length = length
    return value
  })

  var result = function MutantDictToCollection (listener) {
    return instance(listener)
  }

  // getLength, get, indexOf, etc
  addCollectionMethods(result, raw, instance.checkUpdated)

  return result
}

function shouldUpdate (newItem, keyValue) {
  if (!keyValue) {
    return false
  } else if (isObservable(newItem) && keyValue.value === newItem) {
    return true
  } else {
    return !keyValue.isBound
  }
}

function getKeys (value) {
  if (isObservable(value) && value.keys) {
    return resolve(value.keys)
  } else {
    return Object.keys(resolve(value))
  }
}
<commit_msg>dict-to-collection: fix updating of keys<commit_after>var addCollectionMethods = require('./lib/add-collection-methods')
var computed = require('./computed')
var KeyValue = require('./lib/key-value')
var resolve = require('./resolve')
var isObservable = require('./is-observable')

module.exports = function DictToCollection (obs) {
  var value = []
  var raw = []

  var instance = computed.extended(obs, function () {
    var keys = getKeys(obs)
    var length = keys.length

    for (var i = 0; i < length; i++) {
      var key = keys[i]
      var item = obs.get(key)
      if (shouldUpdate(item, raw[i])) {
        if (raw[i].key() !== key) {
          raw[i].key.set(key)
        }
        if (raw[i].value !== item) {
          raw[i].value.set(item)
        }
      } else {
        raw[i] = KeyValue(key, item)
      }
      value[i] = resolve(raw[i])
    }

    raw.length = value.length = length
    return value
  })

  var result = function MutantDictToCollection (listener) {
    return instance(listener)
  }

  // getLength, get, indexOf, etc
  addCollectionMethods(result, raw, instance.checkUpdated)

  return result
}

function shouldUpdate (newItem, keyValue) {
  if (!keyValue) {
    return false
  } else if (isObservable(newItem) && keyValue.value === newItem) {
    return true
  } else {
    return !keyValue.isBound
  }
}

function getKeys (value) {
  if (isObservable(value) && value.keys) {
    return resolve(value.keys)
  } else {
    return Object.keys(resolve(value))
  }
}
<|endoftext|>


<commit_before>function FeedbackControl($scope, FeedbackControlService, FeedbackSignal) {

    $scope.selected = [];

    $scope.feedback_status = function(id, feed_status) {
        console.log(feed_status + " id: " + id);
        FeedbackSignal.prep_status_message(feed_status)
        FeedbackControlService.change_status(id, feed_status);
    }

    $scope.reply_feedback = function(id) {
        console.log("reply id:" + id);
    }

    $scope.is_selected = function(id) {
        return $scope.selected.indexOf(id) >= 0;
    }

    $scope.update_selected = function(action, id) {
        if (action == 'add' && $scope.selected.indexOf(id) == -1) {
            $scope.selected.push(id);
        }

        if (action == 'remove' && $scope.selected.indexOf(id) != -1) {
            $scope.selected.splice($scope.selected.indexOf(id), 1);
        }
    }

    $scope.update_selection = function($event, feed) {

        var checkbox = $event.target;
        var action = (checkbox.checked ? 'add' : 'remove');
        console.log($(checkbox).val());
        //$scope.update_selected(action, feed);
        //console.log($scope.selected);

        if(checkbox.checked) {
            $(checkbox).parents('.dashboard-feedback').css({'background-color': '#F1F1f1'});
        } else {
            $(checkbox).parents('.dashboard-feedback').css({'background-color': '#FFF'});
        }

    }
}

function CheckyBox($scope, FeedbackSignal) {
    $scope.$on('checkFeedbackStatus', function() {
        $scope.status_selection = FeedbackSignal.feed_status;
    });
}
<commit_msg>not talking<commit_after>function FeedbackControl($scope, FeedbackControlService, FeedbackSignal) {

    $scope.selected = [];

    $scope.feedback_status = function(id, feed_status) {
        console.log(feed_status + " id: " + id);
        FeedbackSignal.prep_status_message(feed_status)
        FeedbackControlService.change_status(id, feed_status);
    }

    $scope.reply_feedback = function(id) {
        console.log("reply id:" + id);
    }

    $scope.is_selected = function(id) {
        return $scope.selected.indexOf(id) >= 0;
    }

    $scope.update_selected = function(action, id) {
        if (action == 'add' && $scope.selected.indexOf(id) == -1) {
            $scope.selected.push(id);
        }

        if (action == 'remove' && $scope.selected.indexOf(id) != -1) {
            $scope.selected.splice($scope.selected.indexOf(id), 1);
        }
    }

    $scope.update_selection = function($event, feed) {

        var checkbox = $event.target;
        var action = (checkbox.checked ? 'add' : 'remove');

        console.log(checkbox.checked);
        console.log($(checkbox).val());
        //$scope.update_selected(action, feed);
        //console.log($scope.selected);

        if(checkbox.checked) {
            $(checkbox).parents('.dashboard-feedback').css({'background-color': '#F1F1f1'});
        } else {
            $(checkbox).parents('.dashboard-feedback').css({'background-color': '#FFF'});
        }

    }
}

function CheckyBox($scope, FeedbackSignal) {
    $scope.$on('checkFeedbackStatus', function() {
        $scope.status_selection = FeedbackSignal.feed_status;
    });
}
<|endoftext|>