<commit_before>/*jshint node: true, -W106 */
'use strict';

/*
* Name : networkHandlerSpec.js
* Module : UnitTest
* Location : /test/businessTier/networkHandler
*
* History :
*
* Version   Date         Programmer         Description
* =========================================================
* 0.0.1     2015-05-29   Samuele Zanella    Initial code
* =========================================================
*/

var NetworkHandler = require('../../../lib/businessTier/networkHandler/networkHandler.js');
var Socket=require('../../../lib/presentationTier/socket.js');
var assert = require('assert');
var request = require('superagent');

var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io')(server);
io.listen(5000);
var Routes=require('../../../lib/presentationTier/routes.js');

describe('NetworkHandler', function() {

    it('returns null when there are no params', function() {
        assert.strictEqual((new NetworkHandler()).hasOwnProperty('_app'), false);
    });

    it('returns null when passed invalid parameters', function() {
        assert.strictEqual((new NetworkHandler('abc', 'def', 2)).hasOwnProperty('_app'), false);
    });

    it('set param values to properties', function() {
        var nh1=new NetworkHandler(app, io, '/norris');
        assert.deepEqual(nh1._app, app);
        assert.deepEqual(nh1._io, io);
        assert.deepEqual(nh1._norrisNamespace, '/norris');
        assert.strictEqual(nh1._routes, new Routes(app, '/norris'));
    });

    describe('#createSocket', function() {
        it('returns the created socket object', function() {
            var nh1=new NetworkHandler(app, io, '/norris');
            assert.deepEqual(nh1.createSocket('/page1'), new Socket(io, '/page1'));
        });
    });
    describe('#addPageToRouting', function() {
        it('adds the given page to the application routing', function() {
            var nh1=new NetworkHandler(app, io, '/norris');
            nh1.addPageToRouting('/page1');
            request.post('localhost:3000/page').end(function(res){
                assert.strictEqual(res.status,200);
            });
        });
    });
});<commit_msg>continue with networkHandler tests<commit_after>/*jshint node: true, -W106 */
'use strict';

/*
* Name : networkHandlerSpec.js
* Module : UnitTest
* Location : /test/businessTier/networkHandler
*
* History :
*
* Version   Date         Programmer         Description
* =========================================================
* 0.0.1     2015-05-29   Samuele Zanella    Initial code
* =========================================================
*/

var NetworkHandler = require('../../../lib/businessTier/networkHandler/networkHandler.js');
var Socket=require('../../../lib/presentationTier/socket.js');
var assert = require('assert');
var request = require('superagent');

var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io')(server);
io.listen(5000);
var Routes=require('../../../lib/presentationTier/routes.js');

describe('NetworkHandler', function() {

    it('returns null when there are no params', function() {
        assert.strictEqual((new NetworkHandler()).hasOwnProperty('_app'), false);
    });

    it('returns null when passed invalid parameters', function() {
        assert.strictEqual((new NetworkHandler('abc', 'def', 2)).hasOwnProperty('_app'), false);
    });

    it('set param values to properties', function() {
        var nh1=new NetworkHandler(app, io, '/norris');
        assert.deepEqual(nh1._app, app);
        assert.deepEqual(nh1._io, io);
        assert.deepEqual(nh1._norrisNamespace, '/norris');
        assert.strictEqual(nh1._routes, new Routes(app, '/norris'));
    });

    describe('#createSocket', function() {
        it('returns the created socket object', function() {
            var nh1=new NetworkHandler(app, io, '/norris');
            assert.deepEqual(nh1.createSocket('/page1'), new Socket(io, '/page1'));
        });
    });
    describe('#addPageToRouting', function() {
        it('does nothing when given a non-string parameter', function() {
            var nh1=new NetworkHandler(app, io, '/norris');
            assert.strictEqual(nh1.addPageToRouting(123), false);
        });
        it('does nothing when given an empty string as a parameter', function() {
            var nh1=new NetworkHandler(app, io, '/norris');
            assert.strictEqual(nh1.addPageToRouting(''), false);
        });
        it('does nothing when given an incorrect string as a parameter', function() {
            var nh1=new NetworkHandler(app, io, '/norris');
            assert.strictEqual(nh1.addPageToRouting('noslash'), false);
        });
        it('adds the given page to the application routing', function() {
            var nh1=new NetworkHandler(app, io, '/norris');
            assert.strictEqual(nh1.addPageToRouting('/page1'), true);
            request.post('localhost:3000/page').end(function(res){
                assert.strictEqual(res.status,200);
            });
        });
    });
    describe('#addGraphToRouting', function() {
        it('does nothing when given a non-string parameter', function() {
            var nh1=new NetworkHandler(app, io, '/norris');
            assert.strictEqual(nh1.addGraphToRouting(123), false);
        });
        it('does nothing when given an empty string as a parameter', function() {
            var nh1=new NetworkHandler(app, io, '/norris');
            assert.strictEqual(nh1.addGraphToRouting(''), false);
        });
        it('does nothing when given an incorrect string as a parameter', function() {
            var nh1=new NetworkHandler(app, io, '/norris');
            assert.strictEqual(nh1.addGraphToRouting('noslash'), false);
        });
        it('adds the given page to the application routing', function() {
            var nh1=new NetworkHandler(app, io, '/norris');
            assert.strictEqual(nh1.addGraphToRouting('/page1'), true);
            request.post('localhost:3000/page').end(function(res){
                assert.strictEqual(res.status,200);
            });
        });
    });
});<|endoftext|>


<commit_before>/**
 * Client tests
 */
import React from "react";
import { shallow, render } from "enzyme";
import VictoryLegend from "src/victory-legend/victory-legend";

const initialData = [{
  name: "Series 1",
  symbol: {
    type: "circle"
  }
}, {
  name: "Series 2",
  labels: {
    fill: "red"
  },
  symbol: {
    type: "triangleUp",
    fill: "blue"
  }
}];

describe("components/victory-legend", () => {
  let wrapper = shallow(<VictoryLegend data={initialData} />);

  it("has expected content with shallow render", () => {
    const output = wrapper.find("VictoryLabel");
    expect(output.length).to.equal(2);
  });

  it("has expected horizontal symbol position", () => {
    const wrappedLegend = shallow(<VictoryLegend data={initialData} orientation="horizontal" />);
    const output = wrappedLegend.find("Point");

    expect(output.at(0).prop("x")).to.equal(7);
    expect(output.at(1).prop("x")).to.equal(95.68016194331983);
    expect(output.at(0).prop("y")).to.equal(7);
    expect(output.at(1).prop("y")).to.equal(7);
  });

  it("has expected vertical symbol position", () => {
    const wrappedLegend = shallow(<VictoryLegend data={initialData} orientation="vertical" />);
    const output = wrappedLegend.find("Point");

    expect(output.at(0).prop("x")).to.equal(7);
    expect(output.at(1).prop("x")).to.equal(7);
    expect(output.at(0).prop("y")).to.equal(7);
    expect(output.at(1).prop("y")).to.equal(31);
  });

  it("has expected horizontal legend labels position", () => {
    const wrappedLegend = render(<VictoryLegend data={initialData} orientation="horizontal" />);
    const output = wrappedLegend.find("text");

    expect(output.eq(0).prop("x")).to.equal("22");
    expect(output.eq(1).prop("x")).to.equal("110.68016194331983");
    expect(output.eq(0).prop("y")).to.equal("7");
    expect(output.eq(1).prop("y")).to.equal("7");
  });

  it("has expected vertical legend labels position", () => {
    const wrappedLegend = render(<VictoryLegend data={initialData} orientation="vertical" />);
    const output = wrappedLegend.find("text");

    expect(output.eq(0).prop("x")).to.equal("22");
    expect(output.eq(1).prop("x")).to.equal("22");
    expect(output.eq(0).prop("y")).to.equal("7");
    expect(output.eq(1).prop("y")).to.equal("31");
  });

  describe("symbols", () => {
    const legendData = [{
      name: "Series 1",
      labels: {
        fontSize: 10
      },
      symbol: {
        type: "circle",
        fill: "red"
      }
    }, {
      name: "Long Series Name",
      labels: {
        fontSize: 12
      },
      symbol: {
        type: "triangleUp",
        fill: "blue"
      }
    }];

    wrapper = shallow(<VictoryLegend data={legendData} />);
    const output = wrapper.find("Point");

    it("has expected symbols length", () => {
      expect(output.length).to.equal(2);
    });

    it("has expected symbol colors", () => {
      expect(output.get(0).props.style.fill).to.equal("red");
      expect(output.get(1).props.style.fill).to.equal("blue");
    });

    it("has expected symbol type", () => {
      expect(output.get(0).props.symbol).to.equal("circle");
      expect(output.get(1).props.symbol).to.equal("triangleUp");
    });
  });

  describe("legend style prop", () => {
    const legendData = [{
      name: "Thing 1"
    }, {
      name: "Thing 2"
    }];

    const styleObject = {
      data: {
        type: "triangleUp",
        fill: "green"
      },
      labels: {
        fontSize: 16
      }
    };

    wrapper = shallow(<VictoryLegend data={legendData} style={styleObject} />);
    const outputPoints = wrapper.find("Point");
    const outputLabels = wrapper.find("VictoryLabel");

    it("has expected symbol type", () => {
      expect(outputPoints.at(0).prop("symbol")).to.equal("triangleUp");
      expect(outputPoints.at(1).prop("symbol")).to.equal("triangleUp");
    });

    it("has expected symbol colors", () => {
      expect(outputPoints.get(0).props.style.fill).to.equal("green");
      expect(outputPoints.get(1).props.style.fill).to.equal("green");
    });

    it("has expected label colors", () => {
      expect(outputLabels.get(0).props.style.fill).to.equal("#252525");
      expect(outputLabels.get(1).props.style.fill).to.equal("#252525");
    });
  });
});
<commit_msg>add itemsPerRow tests<commit_after>/**
 * Client tests
 */
import React from "react";
import { shallow, render } from "enzyme";
import VictoryLegend from "src/victory-legend/victory-legend";

const initialData = [{
  name: "Series 1",
  symbol: {
    type: "circle"
  }
}, {
  name: "Series 2",
  labels: {
    fill: "red"
  },
  symbol: {
    type: "triangleUp",
    fill: "blue"
  }
}];

describe("components/victory-legend", () => {
  let wrapper = shallow(<VictoryLegend data={initialData} />);

  it("has expected content with shallow render", () => {
    const output = wrapper.find("VictoryLabel");
    expect(output.length).to.equal(2);
  });

  it("has expected horizontal symbol position", () => {
    const wrappedLegend = shallow(<VictoryLegend data={initialData} orientation="horizontal" />);
    const output = wrappedLegend.find("Point");

    expect(output.at(0).prop("x")).to.equal(7);
    expect(output.at(1).prop("x")).to.equal(95.68016194331983);
    expect(output.at(0).prop("y")).to.equal(7);
    expect(output.at(1).prop("y")).to.equal(7);
  });

  it("has expected vertical symbol position", () => {
    const wrappedLegend = shallow(<VictoryLegend data={initialData} orientation="vertical" />);
    const output = wrappedLegend.find("Point");

    expect(output.at(0).prop("x")).to.equal(7);
    expect(output.at(1).prop("x")).to.equal(7);
    expect(output.at(0).prop("y")).to.equal(7);
    expect(output.at(1).prop("y")).to.equal(31);
  });

  it("has expected horizontal legend labels position", () => {
    const wrappedLegend = render(<VictoryLegend data={initialData} orientation="horizontal" />);
    const output = wrappedLegend.find("text");

    expect(output.eq(0).prop("x")).to.equal("22");
    expect(output.eq(1).prop("x")).to.equal("110.68016194331983");
    expect(output.eq(0).prop("y")).to.equal("7");
    expect(output.eq(1).prop("y")).to.equal("7");
  });

  it("has expected vertical legend labels position", () => {
    const wrappedLegend = render(<VictoryLegend data={initialData} orientation="vertical" />);
    const output = wrappedLegend.find("text");

    expect(output.eq(0).prop("x")).to.equal("22");
    expect(output.eq(1).prop("x")).to.equal("22");
    expect(output.eq(0).prop("y")).to.equal("7");
    expect(output.eq(1).prop("y")).to.equal("31");
  });

  describe("symbols", () => {
    const legendData = [{
      name: "Series 1",
      labels: {
        fontSize: 10
      },
      symbol: {
        type: "circle",
        fill: "red"
      }
    }, {
      name: "Long Series Name",
      labels: {
        fontSize: 12
      },
      symbol: {
        type: "triangleUp",
        fill: "blue"
      }
    }];

    wrapper = shallow(<VictoryLegend data={legendData} />);
    const output = wrapper.find("Point");

    it("has expected symbols length", () => {
      expect(output.length).to.equal(2);
    });

    it("has expected symbol colors", () => {
      expect(output.get(0).props.style.fill).to.equal("red");
      expect(output.get(1).props.style.fill).to.equal("blue");
    });

    it("has expected symbol type", () => {
      expect(output.get(0).props.symbol).to.equal("circle");
      expect(output.get(1).props.symbol).to.equal("triangleUp");
    });
  });

  describe("legend style prop", () => {
    const legendData = [{
      name: "Thing 1"
    }, {
      name: "Thing 2"
    }];

    const styleObject = {
      data: {
        type: "triangleUp",
        fill: "green"
      },
      labels: {
        fontSize: 16
      }
    };

    wrapper = shallow(<VictoryLegend data={legendData} style={styleObject} />);
    const outputPoints = wrapper.find("Point");
    const outputLabels = wrapper.find("VictoryLabel");

    it("has expected symbol type", () => {
      expect(outputPoints.at(0).prop("symbol")).to.equal("triangleUp");
      expect(outputPoints.at(1).prop("symbol")).to.equal("triangleUp");
    });

    it("has expected symbol colors", () => {
      expect(outputPoints.get(0).props.style.fill).to.equal("green");
      expect(outputPoints.get(1).props.style.fill).to.equal("green");
    });

    it("has expected label colors", () => {
      expect(outputLabels.get(0).props.style.fill).to.equal("#252525");
      expect(outputLabels.get(1).props.style.fill).to.equal("#252525");
    });
  });

  describe("itemsPerRow", () => {
    const legendData = [{
      name: "Thing 1"
    }, {
      name: "Thing 2"
    }, {
      name: "Thing 3"
    }, {
      name: "Thing 4"
    }, {
      name: "Thing 5"
    }, {
      name: "Thing 6"
    }];

    it("displays items in columns", () => {
      wrapper = shallow(<VictoryLegend data={legendData} itemsPerRow={3} />);
      const outputLabels = wrapper.find("VictoryLabel");
      const outputPoints = wrapper.find("Point");

      // items line up between columns
      expect(outputPoints.get(0).props.y).to.equal(outputPoints.get(3).props.y);
      expect(outputLabels.get(0).props.y).to.equal(outputLabels.get(3).props.y);
      expect(outputPoints.get(1).props.y).to.equal(outputPoints.get(4).props.y);
      expect(outputLabels.get(1).props.y).to.equal(outputLabels.get(4).props.y);
      expect(outputPoints.get(2).props.y).to.equal(outputPoints.get(5).props.y);
      expect(outputLabels.get(2).props.y).to.equal(outputLabels.get(2).props.y);

      // columns are the same distance apart
      expect(outputPoints.get(0).props.x - outputPoints.get(3).props.x)
        .to.equal(outputPoints.get(1).props.x - outputPoints.get(4).props.x).and
        .to.equal(outputPoints.get(2).props.x - outputPoints.get(5).props.x);
    });

    it("displays items in rows", () => {
      wrapper = shallow(
        <VictoryLegend
          data={legendData}
          itemsPerRow={3}
          orientation="horizontal"
        />
      );
      const outputLabels = wrapper.find("VictoryLabel");
      const outputPoints = wrapper.find("Point");

      // items line up between rows
      expect(outputPoints.get(0).props.x).to.equal(outputPoints.get(3).props.x);
      expect(outputLabels.get(0).props.x).to.equal(outputLabels.get(3).props.x);
      expect(outputPoints.get(1).props.x).to.equal(outputPoints.get(4).props.x);
      expect(outputLabels.get(1).props.x).to.equal(outputLabels.get(4).props.x);
      expect(outputPoints.get(2).props.x).to.equal(outputPoints.get(5).props.x);
      expect(outputLabels.get(2).props.x).to.equal(outputLabels.get(2).props.x);

      // rows are the same distance apart
      expect(outputPoints.get(0).props.y - outputPoints.get(3).props.y)
        .to.equal(outputPoints.get(1).props.y - outputPoints.get(4).props.y).and
        .to.equal(outputPoints.get(2).props.y - outputPoints.get(5).props.y);
    });
  });
});
<|endoftext|>


<commit_before>var adminUI = require('../adminUI');

module.exports = {
	before: function (browser) {
		browser
			.url(adminUI.url)
			.waitForElementVisible(adminUI.cssSelector.signinView.id)
			.setValue(adminUI.cssSelector.signinView.emailInput, adminUI.login.email)
			.setValue(adminUI.cssSelector.signinView.passwordInput, adminUI.login.password)
			.pause(browser.globals.defaultPauseTimeout)
			.click(adminUI.cssSelector.signinView.submitButton)
			.pause(browser.globals.defaultPauseTimeout)
			.url(adminUI.url)
			.waitForElementVisible(adminUI.cssSelector.homeView.id)
			.pause(browser.globals.defaultPauseTimeout);
	},
	after: function (browser) {
		browser
			.click(adminUI.cssSelector.allView.logoutIconLink)
			.pause(browser.globals.defaultPauseTimeout)
			.end();
	},
	'TODO': function (browser) {
		browser
			.click(adminUI.cssSelector.homeView.plusIconLinkForEmailsTabUnderDashboardFieldsSubheading)
			.waitForElementVisible(adminUI.cssSelector.initialModalView.id)
			.pause(browser.globals.defaultPauseTimeout)
	},
};
<commit_msg>test(e2e): add email ux test coverage.<commit_after>var adminUI = require('../adminUI');

module.exports = {
	before: function (browser) {
		browser
			.url(adminUI.url)
			.waitForElementVisible(adminUI.cssSelector.signinView.id)
			.setValue(adminUI.cssSelector.signinView.emailInput, adminUI.login.email)
			.setValue(adminUI.cssSelector.signinView.passwordInput, adminUI.login.password)
			.pause(browser.globals.defaultPauseTimeout)
			.click(adminUI.cssSelector.signinView.submitButton)
			.pause(browser.globals.defaultPauseTimeout)
			.url(adminUI.url)
			.waitForElementVisible(adminUI.cssSelector.homeView.id)
			.pause(browser.globals.defaultPauseTimeout);
	},
	after: function (browser) {
		browser
			.click(adminUI.cssSelector.allView.logoutIconLink)
			.pause(browser.globals.defaultPauseTimeout)
			.end();
	},
	'Email field can be created via the initial modal': function (browser) {
		browser
			.click(adminUI.cssSelector.homeView.plusIconLinkForEmailsTabUnderDashboardFieldsSubheading)
			.waitForElementVisible(adminUI.cssSelector.initialModalView.id)
			.pause(browser.globals.defaultPauseTimeout)
			.setValue(adminUI.cssSelector.initialModalView.fieldType.email.email.name.value, 'Email Field Test')
			.setValue(adminUI.cssSelector.initialModalView.fieldType.email.email.fieldA.value, 'email1@test.e2e')
			.pause(browser.globals.defaultPauseTimeout)
			.click(adminUI.cssSelector.initialModalView.buttonCreate)
			.waitForElementVisible(adminUI.cssSelector.itemView.id)
			.pause(browser.globals.defaultPauseTimeout);

		browser.expect.element(adminUI.cssSelector.itemView.flashMessage)
			.text.to.equal('New Email Email Field Test created.');

		browser.getValue(adminUI.cssSelector.itemView.fieldType.email.email.name.value, function(result) {
			this.assert.equal(typeof result, "object");
			this.assert.equal(result.status, 0);
			this.assert.equal(result.value, "Email Field Test");
		});

		browser.expect.element(adminUI.cssSelector.itemView.fieldType.email.email.fieldA.value)
			.to.have.value.that.equals('email1@test.e2e');
	},
	'Email field can be created via the edit form': function (browser) {
		browser
			.setValue(adminUI.cssSelector.itemView.fieldType.email.email.fieldB.value, 'email2@test.e2e')
			.pause(browser.globals.defaultPauseTimeout)
			.click(adminUI.cssSelector.itemView.itemSaveButton)
			.waitForElementVisible(adminUI.cssSelector.itemView.id)
			.pause(browser.globals.defaultPauseTimeout);

		browser.expect.element(adminUI.cssSelector.itemView.flashMessage)
			.text.to.equal('Your changes have been saved.');

		browser.getValue(adminUI.cssSelector.itemView.fieldType.email.email.name.value, function(result) {
			this.assert.equal(typeof result, "object");
			this.assert.equal(result.status, 0);
			this.assert.equal(result.value, "Email Field Test");
		});

		browser.expect.element(adminUI.cssSelector.itemView.fieldType.email.email.fieldB.value)
			.to.have.value.that.equals('email2@test.e2e');
	},
};
<|endoftext|>


<commit_before>import { Observable } from 'rx';
import { Schema, valuesOf, arrayOf, normalize } from 'normalizr';
import debug from 'debug';
import { nameify, dasherize, unDasherize } from '../utils';
import supportedLanguages from '../../common/utils/supported-languages';

const isDev = process.env.NODE_ENV !== 'production';
const isBeta = !!process.env.BETA;
const challengesRegex = /^(bonfire|waypoint|zipline|basejump|checkpoint)/i;
const log = debug('fcc:services:challenges');
const challenge = new Schema('challenge', { idAttribute: 'dashedName' });
const block = new Schema('block', { idAttribute: 'dashedName' });
const superBlock = new Schema('superBlock', { idAttribute: 'dashedName' });

block.define({
  challenges: arrayOf(challenge)
});

superBlock.define({
  blocks: arrayOf(block)
});

const mapSchema = valuesOf(superBlock);

/*
 * interface ChallengeMap {
 *   result: [superBlockDashedName: String]
 *   entities: {
 *     superBlock: {
 *       [superBlockDashedName: String]: {
 *          blocks: [blockDashedName: String]
 *        }
 *     },
 *     block: {
 *       [blockDashedName: String]: {
 *         challenges: [challengeDashedName: String]
 *       }
 *     },
 *     challenge: {
 *       [challengeDashedName: String]: Challenge
 *     }
 *   }
 * }
 */
function cachedMap(Block) {
  const query = {
    include: 'challenges',
    order: ['superOrder ASC', 'order ASC']
  };
  return Block.find$(query)
    .flatMap(blocks => Observable.from(blocks.map(block => block.toJSON())))
    .reduce((map, block) => {
      if (map[block.superBlock]) {
        map[block.superBlock].blocks.push(block);
      } else {
        map[block.superBlock] = {
          title: block.superBlock,
          order: block.superOrder,
          name: nameify(block.superBlock),
          dashedName: dasherize(block.superBlock),
          blocks: [block]
        };
      }
      return map;
    }, {})
    .map(map => normalize(map, mapSchema))
    .map(map => {
      // make sure challenges are in the right order
      map.entities.block = Object.keys(map.entities.block)
        // turn map into array
        .map(key => map.entities.block[key])
        // perform re-order
        .map(block => {
          block.challenges = block.challenges.reduce((accu, dashedName) => {
            const index = map.entities.challenge[dashedName].suborder;
            accu[index - 1] = dashedName;
            return accu;
          }, []);
          return block;
        })
        // turn back into map
        .reduce((blockMap, block) => {
          blockMap[block.dashedName] = block;
          return blockMap;
        }, {});
      return map;
    })
    .map(map => {
      // re-order superBlocks result
      const result = Object.keys(map.result).reduce((result, supName) => {
        const index = map.entities.superBlock[supName].order;
        result[index] = supName;
        return result;
      }, []);
      return {
        ...map,
        result
      };
    })
    .shareReplay();
}

function mapChallengeToLang({ translations = {}, ...challenge }, lang) {
  if (!supportedLanguages[lang]) {
    lang = 'en';
  }
  if (lang !== 'en') {
    challenge.title =
      translations[lang] && translations[lang].title ||
      challenge.title;

    challenge.description =
      translations[lang] && translations[lang].description ||
      challenge.description;
  }
  return challenge;
}

function getMapForLang(lang) {
  return ({ entities: { challenge: challengeMap, ...entities }, result }) => {
    entities.challenge = Object.keys(challengeMap)
      .reduce((translatedChallengeMap, key) => {
        translatedChallengeMap[key] =
          mapChallengeToLang(challengeMap[key], lang);
        return translatedChallengeMap;
      }, {});
    return { result, entities };
  };
}

function shouldNotFilterComingSoon({ isComingSoon, isBeta: challengeIsBeta }) {
  return isDev ||
    !isComingSoon ||
    (isBeta && challengeIsBeta);
}

function getFirstChallenge(challengeMap$) {
  return challengeMap$
    .map(({ entities: { superBlock, block, challenge }, result }) => {
      return challenge[
        block[
          superBlock[
            result[0]
          ].blocks[0]
        ].challenges[0]
      ];
    });
}

// this is a hard search
// falls back to soft search
function getChallengeAndBlock(
  challengeDashedName,
  blockDashedName,
  challengeMap$,
  lang
) {
  return challengeMap$
    .flatMap(({ entities }) => {
      const block = entities.block[blockDashedName];
      const challenge = entities.challenge[challengeDashedName];
      if (
        !block ||
        !challenge ||
        !shouldNotFilterComingSoon(challenge)
      ) {
        return getChallengeByDashedName(
          challengeDashedName,
          challengeMap$,
          lang
        );
      }
      return Observable.just({
        redirect: block.dashedName !== blockDashedName ?
          `/challenges/${block.dashedName}/${challenge.dashedName}` :
          false,
        entities: {
          challenge: {
            [challenge.dashedName]: mapChallengeToLang(challenge, lang)
          }
        },
        result: {
          block: block.dashedName,
          challenge: challenge.dashedName
        }
      });
    });
}

function getChallengeByDashedName(dashedName, challengeMap$, lang) {
  const challengeName = unDasherize(dashedName)
    .replace(challengesRegex, '');
  const testChallengeName = new RegExp(challengeName, 'i');
  log('looking for %s', testChallengeName);

  return challengeMap$
    .map(({ entities }) => entities.challenge)
    .flatMap(challengeMap => {
      return Observable.from(Object.keys(challengeMap))
        .map(key => challengeMap[key]);
    })
    .filter(challenge => {
      return shouldNotFilterComingSoon(challenge) &&
        testChallengeName.test(challenge.name);
    })
    .last({ defaultValue: null })
    .flatMap(challengeOrNull => {
      if (challengeOrNull) {
        return Observable.just(challengeOrNull);
      }
      return getFirstChallenge(challengeMap$);
    })
    .map(challenge => ({
      redirect:
        `/challenges/${challenge.block}/${challenge.dashedName}`,
      entities: {
        challenge: {
          [challenge.dashedName]: mapChallengeToLang(challenge, lang)
        }
      },
      result: {
        challenge: challenge.dashedName,
        block: challenge.block
      }
    }));
}

export default function mapService(app) {
  const Block = app.models.Block;
  const challengeMap$ = cachedMap(Block);
  return {
    name: 'map',
    read: (req, resource, { lang, block, dashedName } = {}, config, cb) => {
      log(`${lang} language requested`);
      if (block && dashedName) {
        return getChallengeAndBlock(dashedName, block, challengeMap$, lang)
          .subscribe(challenge => cb(null, challenge), cb);
      }
      if (dashedName) {
        return getChallengeByDashedName(dashedName, challengeMap$, lang)
          .subscribe(challenge => cb(null, challenge), cb);
      }
      return challengeMap$
        .map(getMapForLang(lang))
        .subscribe(map => cb(null, map), cb);
    }
  };
}
<commit_msg>Feature(vim): add libs to tern Refactor map services;<commit_after>import { Observable } from 'rx';
import { Schema, valuesOf, arrayOf, normalize } from 'normalizr';
import debug from 'debug';
import { nameify, dasherize, unDasherize } from '../utils';
import supportedLanguages from '../../common/utils/supported-languages';

const isDev = process.env.NODE_ENV !== 'production';
const isBeta = !!process.env.BETA;
const challengesRegex = /^(bonfire|waypoint|zipline|basejump|checkpoint)/i;
const log = debug('fcc:services:challenges');
const challenge = new Schema('challenge', { idAttribute: 'dashedName' });
const block = new Schema('block', { idAttribute: 'dashedName' });
const superBlock = new Schema('superBlock', { idAttribute: 'dashedName' });

block.define({
  challenges: arrayOf(challenge)
});

superBlock.define({
  blocks: arrayOf(block)
});

const mapSchema = valuesOf(superBlock);

/*
 * interface ChallengeMap {
 *   result: [superBlockDashedName: String]
 *   entities: {
 *     superBlock: {
 *       [superBlockDashedName: String]: {
 *          blocks: [blockDashedName: String]
 *        }
 *     },
 *     block: {
 *       [blockDashedName: String]: {
 *         challenges: [challengeDashedName: String]
 *       }
 *     },
 *     challenge: {
 *       [challengeDashedName: String]: Challenge
 *     }
 *   }
 * }
 */
function cachedMap(Block) {
  const query = {
    include: 'challenges',
    order: ['superOrder ASC', 'order ASC']
  };
  return Block.find$(query)
    .flatMap(blocks => Observable.from(blocks.map(block => block.toJSON())))
    .reduce((map, block) => {
      if (map[block.superBlock]) {
        map[block.superBlock].blocks.push(block);
      } else {
        map[block.superBlock] = {
          title: block.superBlock,
          order: block.superOrder,
          name: nameify(block.superBlock),
          dashedName: dasherize(block.superBlock),
          blocks: [block]
        };
      }
      return map;
    }, {})
    .map(map => normalize(map, mapSchema))
    .map(map => {
      // make sure challenges are in the right order
      map.entities.block = Object.keys(map.entities.block)
        // turn map into array
        .map(key => map.entities.block[key])
        // perform re-order
        .map(block => {
          block.challenges = block.challenges.reduce((accu, dashedName) => {
            const index = map.entities.challenge[dashedName].suborder;
            accu[index - 1] = dashedName;
            return accu;
          }, []);
          return block;
        })
        // turn back into map
        .reduce((blockMap, block) => {
          blockMap[block.dashedName] = block;
          return blockMap;
        }, {});
      return map;
    })
    .map(map => {
      // re-order superBlocks result
      const result = Object.keys(map.result).reduce((result, supName) => {
        const index = map.entities.superBlock[supName].order;
        result[index] = supName;
        return result;
      }, []);
      return {
        ...map,
        result
      };
    })
    .shareReplay();
}

function mapChallengeToLang({ translations = {}, ...challenge }, lang) {
  if (!supportedLanguages[lang]) {
    lang = 'en';
  }
  const translation = translations[lang] || {};
  if (lang !== 'en') {
    challenge = {
      ...challenge,
      ...translation
    };
  }
  return challenge;
}

function getMapForLang(lang) {
  return ({ entities: { challenge: challengeMap, ...entities }, result }) => {
    entities.challenge = Object.keys(challengeMap)
      .reduce((translatedChallengeMap, key) => {
        translatedChallengeMap[key] = mapChallengeToLang(
          challengeMap[key],
          lang
        );
        return translatedChallengeMap;
      }, {});
    return { result, entities };
  };
}

function shouldNotFilterComingSoon({ isComingSoon, isBeta: challengeIsBeta }) {
  return isDev ||
    !isComingSoon ||
    (isBeta && challengeIsBeta);
}

function getFirstChallenge(challengeMap$) {
  return challengeMap$
    .map(({ entities: { superBlock, block, challenge }, result }) => {
      return challenge[
        block[
          superBlock[
            result[0]
          ].blocks[0]
        ].challenges[0]
      ];
    });
}

// this is a hard search
// falls back to soft search
function getChallengeAndBlock(
  challengeDashedName,
  blockDashedName,
  challengeMap$,
  lang
) {
  return challengeMap$
    .flatMap(({ entities }) => {
      const block = entities.block[blockDashedName];
      const challenge = entities.challenge[challengeDashedName];
      if (
        !block ||
        !challenge ||
        !shouldNotFilterComingSoon(challenge)
      ) {
        return getChallengeByDashedName(
          challengeDashedName,
          challengeMap$,
          lang
        );
      }
      return Observable.just({
        redirect: block.dashedName !== blockDashedName ?
          `/challenges/${block.dashedName}/${challenge.dashedName}` :
          false,
        entities: {
          challenge: {
            [challenge.dashedName]: mapChallengeToLang(challenge, lang)
          }
        },
        result: {
          block: block.dashedName,
          challenge: challenge.dashedName
        }
      });
    });
}

function getChallengeByDashedName(dashedName, challengeMap$, lang) {
  const challengeName = unDasherize(dashedName)
    .replace(challengesRegex, '');
  const testChallengeName = new RegExp(challengeName, 'i');
  log('looking for %s', testChallengeName);

  return challengeMap$
    .map(({ entities }) => entities.challenge)
    .flatMap(challengeMap => {
      return Observable.from(Object.keys(challengeMap))
        .map(key => challengeMap[key]);
    })
    .filter(challenge => {
      return shouldNotFilterComingSoon(challenge) &&
        testChallengeName.test(challenge.name);
    })
    .last({ defaultValue: null })
    .flatMap(challengeOrNull => {
      if (challengeOrNull) {
        return Observable.just(challengeOrNull);
      }
      return getFirstChallenge(challengeMap$);
    })
    .map(challenge => ({
      redirect:
        `/challenges/${challenge.block}/${challenge.dashedName}`,
      entities: {
        challenge: {
          [challenge.dashedName]: mapChallengeToLang(challenge, lang)
        }
      },
      result: {
        challenge: challenge.dashedName,
        block: challenge.block
      }
    }));
}

export default function mapService(app) {
  const Block = app.models.Block;
  const challengeMap$ = cachedMap(Block);
  return {
    name: 'map',
    read: (req, resource, { lang, block, dashedName } = {}, config, cb) => {
      log(`${lang} language requested`);
      if (block && dashedName) {
        return getChallengeAndBlock(dashedName, block, challengeMap$, lang)
          .subscribe(challenge => cb(null, challenge), cb);
      }
      if (dashedName) {
        return getChallengeByDashedName(dashedName, challengeMap$, lang)
          .subscribe(challenge => cb(null, challenge), cb);
      }
      return challengeMap$
        .map(getMapForLang(lang))
        .subscribe(map => cb(null, map), cb);
    }
  };
}
<|endoftext|>


<commit_before>var $ = require('jquery');
var _ = require('underscore');
var Backbone = require('backbone');
var CoreView = require('backbone/core-view');
require('bootstrap-colorpicker');
var template = require('./template.tpl');
var colorPickerTemplate = require('./color-picker-template.tpl');
var Utils = require('../../../../../helpers/utils');

var ESCAPE_KEY_CODE = 27;

module.exports = CoreView.extend({
  events: {
    'blur .js-hex': '_onChangeHex',
    'blur .js-inputColor': '_onChangeColorValue',
    'blur .js-a': '_onChangeOpacity'
  },

  initialize: function (opts) {
    var opacity = opts.opacity != null ? opts.opacity : 1;

    this.model = new Backbone.Model({
      hex: opts.value,
      opacity: opacity
    });

    this._onEscape = this._onEscapePressed.bind(this);
    this._initBinds();
  },

  render: function () {
    var rgb = Utils.hexToRGB(this.model.get('hex'));

    var color = _.extend(rgb, {
      hex: this.model.get('hex'),
      opacity: this.model.get('opacity'),
      opacityDisabled: this.options.disableOpacity
    });

    this.$el.append(template(color));

    var rgbaTemplate = _.template('rgba(<%- r %>, <%- g %>, <%- b %>, <%- opacity %>)');

    this.$('.js-colorPicker').colorpicker({
      color: rgbaTemplate(color),
      format: 'rgba',
      container: true,
      horizontal: true,
      inline: true,
      customClass: 'ColorPicker',
      template: colorPickerTemplate(),
      slidersHorz: {
        saturation: {
          maxLeft: 206,
          maxTop: 95,
          callLeft: 'setSaturation',
          callTop: 'setBrightness'
        },
        hue: {
          maxLeft: 180,
          maxTop: 0,
          callLeft: 'setHue',
          callTop: false
        },
        alpha: {
          maxLeft: 180,
          maxTop: 0,
          callLeft: 'setAlpha',
          callTop: false
        }
      }
    });

    if (this.options.disableOpacity) {
      this.$('.js-colorPicker .js-alpha').addClass('is-hidden');
    }

    var setNewColor = function (e) {
      var rgb = e.color.toRGB();
      var hex = e.color.toHex();
      this.model.set({ hex: hex, r: rgb.r, g: rgb.g, b: rgb.b, opacity: rgb.a });
      this.$('.js-color').css('opacity', rgb.a);
    }.bind(this);

    this.$('.js-colorPicker').colorpicker().on('changeColor', _.debounce(setNewColor, 250));

    this._initDocumentBinds();
    return this;
  },

  _initBinds: function () {
    this.model.bind('change:hex', this._onChangeColor, this);
    this.model.bind('change:r', this._onChangeColor, this);
    this.model.bind('change:g', this._onChangeColor, this);
    this.model.bind('change:b', this._onChangeColor, this);
    this.model.bind('change:opacity', this._onChangeColor, this);
  },

  _onEscapePressed: function (ev) {
    if (ev.which === ESCAPE_KEY_CODE) {
      this.remove();
    }
  },

  _initDocumentBinds: function () {
    $(document).on('keydown', this._onEscape);
  },

  _destroyDocumentBinds: function () {
    $(document).off('keydown', this._onEscape);
  },

  _onChangeColor: function () {
    this.trigger('change', {
      opacity: this.model.get('opacity'),
      hex: this.model.get('hex')
    }, this);

    this.$('.js-hex').val(this.model.get('hex'));
    this.$('.js-r').val(this.model.get('r'));
    this.$('.js-g').val(this.model.get('g'));
    this.$('.js-b').val(this.model.get('b'));
    this.$('.js-a').val(this.model.get('opacity'));
  },

  _onChangeOpacity: function () {
    var opacity = +this.$('.js-a').val();
    if (_.isNumber(opacity) && opacity >= 0 && opacity <= 1) {
      this.setColor(this.model.get('hex'), opacity);
    }
  },

  _onChangeColorValue: function (e) {
    this.$(e.target).removeClass('has-error');

    var r = +this.$('.js-r').val();
    var g = +this.$('.js-g').val();
    var b = +this.$('.js-b').val();

    var hex = Utils.rgbToHex(r, g, b);

    if (Utils.isValidHex(hex)) {
      this.setColor(hex);
    } else {
      this.$(e.target).addClass('has-error');
    }
  },

  _onChangeHex: function (e) {
    this.$(e.target).removeClass('has-error');

    var hex = this.$('.js-hex').val();

    if (Utils.isValidHex(hex)) {
      this.setColor(hex);
    } else {
      this.$(e.target).addClass('has-error');
    }
  },

  setColor: function (hex, opacity) {
    if (opacity === undefined) {
      opacity = this.model.get('opacity') || 1;
    }

    this.$('.js-colorPicker').colorpicker('setValue', Utils.hexToRGBA(hex, opacity));
  },

  clean: function () {
    this._destroyDocumentBinds();
    CoreView.prototype.clean.apply(this);
  }
});
<commit_msg>No need for debounce.<commit_after>var $ = require('jquery');
var _ = require('underscore');
var Backbone = require('backbone');
var CoreView = require('backbone/core-view');
require('bootstrap-colorpicker');
var template = require('./template.tpl');
var colorPickerTemplate = require('./color-picker-template.tpl');
var Utils = require('../../../../../helpers/utils');

var ESCAPE_KEY_CODE = 27;

module.exports = CoreView.extend({
  events: {
    'blur .js-hex': '_onChangeHex',
    'blur .js-inputColor': '_onChangeColorValue',
    'blur .js-a': '_onChangeOpacity'
  },

  initialize: function (opts) {
    var opacity = opts.opacity != null ? opts.opacity : 1;

    this.model = new Backbone.Model({
      hex: opts.value,
      opacity: opacity
    });

    this._onEscape = this._onEscapePressed.bind(this);
    this._initBinds();
  },

  render: function () {
    var rgb = Utils.hexToRGB(this.model.get('hex'));

    var color = _.extend(rgb, {
      hex: this.model.get('hex'),
      opacity: this.model.get('opacity'),
      opacityDisabled: this.options.disableOpacity
    });

    this.$el.append(template(color));

    var rgbaTemplate = _.template('rgba(<%- r %>, <%- g %>, <%- b %>, <%- opacity %>)');

    this.$('.js-colorPicker').colorpicker({
      color: rgbaTemplate(color),
      format: 'rgba',
      container: true,
      horizontal: true,
      inline: true,
      customClass: 'ColorPicker',
      template: colorPickerTemplate(),
      slidersHorz: {
        saturation: {
          maxLeft: 206,
          maxTop: 95,
          callLeft: 'setSaturation',
          callTop: 'setBrightness'
        },
        hue: {
          maxLeft: 180,
          maxTop: 0,
          callLeft: 'setHue',
          callTop: false
        },
        alpha: {
          maxLeft: 180,
          maxTop: 0,
          callLeft: 'setAlpha',
          callTop: false
        }
      }
    });

    if (this.options.disableOpacity) {
      this.$('.js-colorPicker .js-alpha').addClass('is-hidden');
    }

    var setNewColor = function (e) {
      var rgb = e.color.toRGB();
      var hex = e.color.toHex();
      this.model.set({ hex: hex, r: rgb.r, g: rgb.g, b: rgb.b, opacity: rgb.a });
      this.$('.js-color').css('opacity', rgb.a);
    }.bind(this);

    this.$('.js-colorPicker').colorpicker().on('changeColor', setNewColor);

    this._initDocumentBinds();
    return this;
  },

  _initBinds: function () {
    this.model.bind('change:hex', this._onChangeColor, this);
    this.model.bind('change:r', this._onChangeColor, this);
    this.model.bind('change:g', this._onChangeColor, this);
    this.model.bind('change:b', this._onChangeColor, this);
    this.model.bind('change:opacity', this._onChangeColor, this);
  },

  _onEscapePressed: function (ev) {
    if (ev.which === ESCAPE_KEY_CODE) {
      this.remove();
    }
  },

  _initDocumentBinds: function () {
    $(document).on('keydown', this._onEscape);
  },

  _destroyDocumentBinds: function () {
    $(document).off('keydown', this._onEscape);
  },

  _onChangeColor: function () {
    this.trigger('change', {
      opacity: this.model.get('opacity'),
      hex: this.model.get('hex')
    }, this);

    this.$('.js-hex').val(this.model.get('hex'));
    this.$('.js-r').val(this.model.get('r'));
    this.$('.js-g').val(this.model.get('g'));
    this.$('.js-b').val(this.model.get('b'));
    this.$('.js-a').val(this.model.get('opacity'));
  },

  _onChangeOpacity: function () {
    var opacity = +this.$('.js-a').val();
    if (_.isNumber(opacity) && opacity >= 0 && opacity <= 1) {
      this.setColor(this.model.get('hex'), opacity);
    }
  },

  _onChangeColorValue: function (e) {
    this.$(e.target).removeClass('has-error');

    var r = +this.$('.js-r').val();
    var g = +this.$('.js-g').val();
    var b = +this.$('.js-b').val();

    var hex = Utils.rgbToHex(r, g, b);

    if (Utils.isValidHex(hex)) {
      this.setColor(hex);
    } else {
      this.$(e.target).addClass('has-error');
    }
  },

  _onChangeHex: function (e) {
    this.$(e.target).removeClass('has-error');

    var hex = this.$('.js-hex').val();

    if (Utils.isValidHex(hex)) {
      this.setColor(hex);
    } else {
      this.$(e.target).addClass('has-error');
    }
  },

  setColor: function (hex, opacity) {
    if (opacity === undefined) {
      opacity = this.model.get('opacity') || 1;
    }

    this.$('.js-colorPicker').colorpicker('setValue', Utils.hexToRGBA(hex, opacity));
  },

  clean: function () {
    this._destroyDocumentBinds();
    CoreView.prototype.clean.apply(this);
  }
});
<|endoftext|>


<commit_before>/*
 *  Copyright 2014 TWO SIGMA OPEN SOURCE, LLC
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

var BeakerPageObject = require('../../beaker.po.js');
var path = require('path');
var beakerPO;

describe('Python Tutorial', function (done) {

    beakerPO = new BeakerPageObject();
    browser.get(beakerPO.baseURL + "beaker/#/open?uri=file:config%2Ftutorials%2Fipython-examples.bkr&readOnly=true").then(done);

    var start = new Date().getTime();
    beakerPO.waitUntilLoadingFinished().then(function() {
        var stop = new Date().getTime();
        var len = stop - start;
        console.log('Starting IPython language: ' + len + ' milliSeconds');
    });

    it('IPython can load', function () {
        element(by.css('.modal-body .bkr')).isPresent().then(function(present){
            if(present){
                expect(element(by.css('.modal-body .bkr')).getText()).toBe('IPython have loaded');
            }
        });
    });

    it('IPython Examples', function () {
        var idCell = "codeK0EmdK";
        beakerPO.scrollToCodeCellOutputByIdCell(idCell);
        expect(beakerPO.getCodeCellOutputByIdCell(idCell).element(by.css('simple-layout')).isPresent()).toBe(true);
        beakerPO.checkCellOutputSubTextByIdCell(idCell, '[<matplotlib.lines.Line2D', 0, 25);
        beakerPO.checkImageByIdCell(idCell);

        idCell = "codeqPMAfv";
        beakerPO.scrollToCodeCellOutputByIdCell(idCell);
        beakerPO.checkDtContainerByIdCell(idCell);
        var arrStrHead = beakerPO.getDataTablesTHeadByIdCell(idCell).get(0).all(by.css('th'));
        expect(arrStrHead.count()).toBe(10);
        beakerPO.checkSubString(arrStrHead.get(0), 'Index', 0, 5);
        beakerPO.checkSubString(arrStrHead.get(1), '3 mo', 0, 4);
        beakerPO.checkSubString(arrStrHead.get(2), '6 mo', 0, 4);
        beakerPO.checkSubString(arrStrHead.get(3), '1 yr', 0, 4);
        beakerPO.checkSubString(arrStrHead.get(4), '2 yr', 0, 4);
        beakerPO.checkSubString(arrStrHead.get(5), '3 yr', 0, 4);
        beakerPO.checkSubString(arrStrHead.get(6), '5 yr', 0, 4);
        beakerPO.checkSubString(arrStrHead.get(7), '7 yr', 0, 4);
        beakerPO.checkSubString(arrStrHead.get(8), '10 yr', 0, 5);
        beakerPO.checkSubString(arrStrHead.get(9), '30 yr', 0, 5);

        var tBody = beakerPO.getDataTablesTBodyByIdCell(idCell);
        expect(tBody.count()).toBe(5);
        var arrStr = tBody.get(0).all(by.css('td'));
        expect(arrStr.count()).toBe(10);
        beakerPO.checkSubString(arrStr.get(0), '19900130', 0, 8);
        beakerPO.checkSubString(arrStr.get(1), '7.898', 0, 5);
        beakerPO.checkSubString(arrStr.get(2), '7.956', 0, 5);
        beakerPO.checkSubString(arrStr.get(3), '7.921', 0, 5);
        beakerPO.checkSubString(arrStr.get(4), '8.085', 0, 5);
        beakerPO.checkSubString(arrStr.get(5), '8.132', 0, 5);
        beakerPO.checkSubString(arrStr.get(6), '8.119', 0, 5);
        beakerPO.checkSubString(arrStr.get(7), '8.196', 0, 5);
        beakerPO.checkSubString(arrStr.get(8), '8.206', 0, 5);
        beakerPO.checkSubString(arrStr.get(9), '8.258', 0, 5);

        idCell = "codeZxPm5k";
        beakerPO.scrollToCodeCellOutputByIdCell(idCell);
        beakerPO.checkImageByIdCell(idCell);
    });

});<commit_msg>change ipython test<commit_after>/*
 *  Copyright 2014 TWO SIGMA OPEN SOURCE, LLC
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

var BeakerPageObject = require('../../beaker.po.js');
var path = require('path');
var beakerPO;

describe('Python Tutorial', function (done) {

    beakerPO = new BeakerPageObject();
    browser.get(beakerPO.baseURL + "beaker/#/open?uri=file:config%2Ftutorials%2Fipython-examples.bkr&readOnly=true").then(done);

    var start = new Date().getTime();
    beakerPO.waitUntilLoadingFinished().then(function() {
        var stop = new Date().getTime();
        var len = stop - start;
        console.log('Starting IPython language: ' + len + ' milliSeconds');
    });

    it('IPython can load', function () {
        element(by.css('div.modal-body')).isPresent().then(function(present){
            if(present){
                expect(element.all(by.css('div.modal-body > p')).get(0).getText()).toBe('IPython have loaded');
            }
        });
    });

    it('IPython Examples', function () {
        var idCell = "codeK0EmdK";
        beakerPO.scrollToCodeCellOutputByIdCell(idCell);
        expect(beakerPO.getCodeCellOutputByIdCell(idCell).element(by.css('simple-layout')).isPresent()).toBe(true);
        beakerPO.checkCellOutputSubTextByIdCell(idCell, '[<matplotlib.lines.Line2D', 0, 25);
        beakerPO.checkImageByIdCell(idCell);

        idCell = "codeqPMAfv";
        beakerPO.scrollToCodeCellOutputByIdCell(idCell);
        beakerPO.checkDtContainerByIdCell(idCell);
        var arrStrHead = beakerPO.getDataTablesTHeadByIdCell(idCell).get(0).all(by.css('th'));
        expect(arrStrHead.count()).toBe(10);
        beakerPO.checkSubString(arrStrHead.get(0), 'Index', 0, 5);
        beakerPO.checkSubString(arrStrHead.get(1), '3 mo', 0, 4);
        beakerPO.checkSubString(arrStrHead.get(2), '6 mo', 0, 4);
        beakerPO.checkSubString(arrStrHead.get(3), '1 yr', 0, 4);
        beakerPO.checkSubString(arrStrHead.get(4), '2 yr', 0, 4);
        beakerPO.checkSubString(arrStrHead.get(5), '3 yr', 0, 4);
        beakerPO.checkSubString(arrStrHead.get(6), '5 yr', 0, 4);
        beakerPO.checkSubString(arrStrHead.get(7), '7 yr', 0, 4);
        beakerPO.checkSubString(arrStrHead.get(8), '10 yr', 0, 5);
        beakerPO.checkSubString(arrStrHead.get(9), '30 yr', 0, 5);

        var tBody = beakerPO.getDataTablesTBodyByIdCell(idCell);
        expect(tBody.count()).toBe(5);
        var arrStr = tBody.get(0).all(by.css('td'));
        expect(arrStr.count()).toBe(10);
        beakerPO.checkSubString(arrStr.get(0), '19900130', 0, 8);
        beakerPO.checkSubString(arrStr.get(1), '7.898', 0, 5);
        beakerPO.checkSubString(arrStr.get(2), '7.956', 0, 5);
        beakerPO.checkSubString(arrStr.get(3), '7.921', 0, 5);
        beakerPO.checkSubString(arrStr.get(4), '8.085', 0, 5);
        beakerPO.checkSubString(arrStr.get(5), '8.132', 0, 5);
        beakerPO.checkSubString(arrStr.get(6), '8.119', 0, 5);
        beakerPO.checkSubString(arrStr.get(7), '8.196', 0, 5);
        beakerPO.checkSubString(arrStr.get(8), '8.206', 0, 5);
        beakerPO.checkSubString(arrStr.get(9), '8.258', 0, 5);

        idCell = "codeZxPm5k";
        beakerPO.scrollToCodeCellOutputByIdCell(idCell);
        beakerPO.checkImageByIdCell(idCell);
    });

});<|endoftext|>


<commit_before>/**
 * Created by mitch on 2/20/2014.
 */

var Transactions = require('./db').collection('transactions');

var self = {};

self.insertWithdraw = function (username, amount, toAddress, txId) {
   console.log("Withdrew Ð" + amount + " from " + username + " to " + toAddress);
   Transactions.insert({
      type: "withdraw",
      date: new Date().getTime(),
      owner: username,
      toAddress: toAddress,
      amount: amount,
      transactionHash: txId
   });
};

self.insertDeposit = function (username, amount) {
   console.log("Deposited Ð" + amount + " into " + username + "'s wallet");
   Transactions.insert({
      type: "deposit",
      date: new Date().getTime(),
      owner: username,
      amount: amount
   });
};

self.insertSend = function (from, to, amount) {
   console.log("Send Ð" + amount + " from " + from + " to " + to);
   Transactions.insert({
      type: "send",
      date: new Date().getTime(),
      owner: from,
      to: to,
      amount: amount
   });
};

self.getTransactions = function (username, limit, callback) {
   Transactions.find({
      $or: [
         {
            owner: username
         },
         {
            to: username
         }
      ]
   }).limit(limit).sort({date: -1}).toArray(callback)
};

module.exports = self;<commit_msg>Dat english<commit_after>/**
 * Created by mitch on 2/20/2014.
 */

var Transactions = require('./db').collection('transactions');

var self = {};

self.insertWithdraw = function (username, amount, toAddress, txId) {
   console.log("Withdrew Ð" + amount + " from " + username + " to " + toAddress);
   Transactions.insert({
      type: "withdraw",
      date: new Date().getTime(),
      owner: username,
      toAddress: toAddress,
      amount: amount,
      transactionHash: txId
   });
};

self.insertDeposit = function (username, amount) {
   console.log("Deposited Ð" + amount + " into " + username + "'s wallet");
   Transactions.insert({
      type: "deposit",
      date: new Date().getTime(),
      owner: username,
      amount: amount
   });
};

self.insertSend = function (from, to, amount) {
   console.log("Sent Ð" + amount + " from " + from + " to " + to);
   Transactions.insert({
      type: "send",
      date: new Date().getTime(),
      owner: from,
      to: to,
      amount: amount
   });
};

self.getTransactions = function (username, limit, callback) {
   Transactions.find({
      $or: [
         {
            owner: username
         },
         {
            to: username
         }
      ]
   }).limit(limit).sort({date: -1}).toArray(callback)
};

module.exports = self;<|endoftext|>


<commit_before>"use strict"

let dogs = [
  {name: "laddie", breed: "yorkie"},
  {name: "harvey", breed: "pug"},
  {name: "freckles", breed: "rottweiller"},
  {name: "ben", breed: "labrador"},
  {name: "patch", breed: "cockerspaniel"},
  {name: "reggie", breed: "great dane"},
  {name: "bonnie", breed: "labrador"},
  {name: "fluffy", breed: "poodle"}
]

let labradors = dogs.filter(dog => {
  return dog.breed === "labrador"
})

console.log(JSON.stringify(labradors, null, 2))
<commit_msg>Reduced code footprint<commit_after>"use strict"

let dogs = [
  {name: "laddie", breed: "yorkie"},
  {name: "harvey", breed: "pug"},
  {name: "freckles", breed: "rottweiller"},
  {name: "ben", breed: "labrador"},
  {name: "patch", breed: "cockerspaniel"},
  {name: "reggie", breed: "great dane"},
  {name: "bonnie", breed: "labrador"},
  {name: "fluffy", breed: "poodle"}
]

let labradors = dogs.filter(x => x.breed === "labrador")

console.log(JSON.stringify(labradors, null, 2))
<|endoftext|>


<commit_before>var u = require('./util')
var isBasic = u.isBasic
var isRange = u.isRange
var isString = u.isString
var isLtgt = u.isLtgt
var isObject = u.isObject
var has = u.has
var map = u.map

function exact(q) {
  console.log('Exact', q)
  return function (v) {
    return q === v
  }
}
function prefix(p) {
  return function (v) {
    return isString(v) && v.substring(0, p.length) === p
  }
}

function lt (q) {
  return function (v) { return v < q }
}
function gt (q) {
  return function (v) { return v > q }
}
function lte (q) {
  return function (v) { return v <= q }
}
function gte (q) {
  return function (v) { return v >= q }
}

function combine(f, g) {
  if(!g) return f
  return function (v) {
    return f(v) && g(v)
  }
}

function ltgt (q) {
  var filter = null
  if(has(q, '$lt'))  filter = lt(q.$lt)
  if(has(q, '$lte')) filter = combine(lte(q.$lte), filter)
  if(has(q, '$gt'))  filter = combine(gt(q.$gt), filter)
  if(has(q, '$gte')) filter = combine(gte(q.$gte), filter)
  return filter
}

function all (q) {
  return function (v) {
    if(v == null) return false
    for(var k in q) if(!q[k](v[k])) return false
    return true
  }
}

function absent (v) {
  return v == null
}

function never () { return false }

function make (q) {
  console.log('Make', q)
  return (
    isBasic(q)        ? exact(q)
  : has(q, '$prefix') ? prefix(q.$prefix)
  : isLtgt(q)         ? ltgt(q)
  : u.isObject(q)
    || u.isArray(q)   ? all(map(q, make))
  : isNullish(q)      ? absent
  :                     never
  )
}

module.exports = make

<commit_msg>prefix can take arrays<commit_after>var u = require('./util')
var isBasic = u.isBasic
var isRange = u.isRange
var isString = u.isString
var isLtgt = u.isLtgt
var isObject = u.isObject
var isArray = u.isArray
var has = u.has
var map = u.map

function exact(q) {
  return function (v) {
    return q === v
  }
}
function prefix(p) {
  if(isString(p))
    return function (v) {
      return isString(v) && v.substring(0, p.length) === p
    }
  if(isArray(p)) {
    if(!p.every(isBasic))
      throw new Error('{$prefix: array} must have exact elements in the array')
    return function (v) {
      if(!isArray(v) || v.length < p.length) return false
      for(var i = 0; i < p.length; i++)
        if(v[i] !== p[i]) return false
      return true
    }
  }
}

function lt (q) {
  return function (v) { return v < q }
}
function gt (q) {
  return function (v) { return v > q }
}
function lte (q) {
  return function (v) { return v <= q }
}
function gte (q) {
  return function (v) { return v >= q }
}

function combine(f, g) {
  if(!g) return f
  return function (v) {
    return f(v) && g(v)
  }
}

function ltgt (q) {
  var filter = null
  if(has(q, '$lt'))  filter = lt(q.$lt)
  if(has(q, '$lte')) filter = combine(lte(q.$lte), filter)
  if(has(q, '$gt'))  filter = combine(gt(q.$gt), filter)
  if(has(q, '$gte')) filter = combine(gte(q.$gte), filter)
  return filter
}

function all (q) {
  return function (v) {
    if(v == null) return false
    for(var k in q) if(!q[k](v[k])) return false
    return true
  }
}

function absent (v) {
  return v == null
}

function never () { return false }

function make (q) {
  return (
    isBasic(q)        ? exact(q)
  : has(q, '$prefix') ? prefix(q.$prefix)
  : isLtgt(q)         ? ltgt(q)
  : u.isObject(q)
    || u.isArray(q)   ? all(map(q, make))
  : isNullish(q)      ? absent
  :                     never
  )
}

module.exports = make

<|endoftext|>


<commit_before>/* eslint unicorn/filename-case: "off", func-names: "off", camelcase: "off", no-unused-vars: "off" */

module.exports = function (iface) {
    const {mqttPub, mqttSub, mqttStatus, log, Service, Characteristic} = iface;

    return function createService_Thermostat(acc, settings, subtype) {
        acc.addService(Service.Thermostat, settings.name, subtype)
            .getCharacteristic(Characteristic.TargetTemperature)
            .on('set', (value, callback) => {
                log.debug('< hap set', settings.name, 'TargetTemperature', value);
                log.debug('> mqtt', settings.topic.setTargetTemperature, value);
                mqttPub(settings.topic.setTargetTemperature, value, settings.mqttPublishOptions);
                callback();
            });

        if (settings.topic.statusCurrentHeatingCoolingState) {
            mqttSub(settings.topic.statusCurrentHeatingCoolingState, val => {
                log.debug('> hap update', settings.name, 'CurrentHeatingCoolingState', val);
                acc.getService(subtype)
                    .updateCharacteristic(Characteristic.CurrentHeatingCoolingState, val);
            });
            acc.getService(subtype)
                .getCharacteristic(Characteristic.CurrentHeatingCoolingState)
                .on('get', callback => {
                    log.debug('< hap get', settings.name, 'CurrentHeatingCoolingState');
                    log.debug('> hap re_get', settings.name, 'CurrentHeatingCoolingState', mqttStatus[settings.topic.statusCurrentHeatingCoolingState]);
                    callback(null, mqttStatus[settings.topic.statusCurrentHeatingCoolingState]);
                });
        } else {
            const state = 1; // HEATING as default
            acc.getService(subtype)
                .getCharacteristic(Characteristic.CurrentHeatingCoolingState)
                .on('get', callback => {
                    log.debug('< hap get', settings.name, 'CurrentHeatingCoolingState');
                    log.debug('> hap re_get', settings.name, 'CurrentHeatingCoolingState', state);
                    callback(null, state);
                });
            log.debug('> hap set', settings.name, 'CurrentHeatingCoolingState', state);
            acc.getService(subtype)
                .setCharacteristic(Characteristic.CurrentHeatingCoolingState, state);
        }

        if (settings.topic.statusTargetHeatingCoolingState) {
            mqttSub(settings.topic.statusTargetHeatingCoolingState, val => {
                log.debug('> hap update', settings.name, 'TargetHeatingCoolingState', val);
                acc.getService(subtype)
                    .updateCharacteristic(Characteristic.TargetHeatingCoolingState, val);
            });
            acc.getService(subtype)
                .getCharacteristic(Characteristic.TargetHeatingCoolingState)
                .setProps((settings.props || {}).TargetHeatingCoolingState || {})
                .on('get', callback => {
                    log.debug('< hap get', settings.name, 'TargetHeatingCoolingState');
                    log.debug('> hap re_get', settings.name, 'TargetHeatingCoolingState', mqttStatus[settings.topic.statusTargetHeatingCoolingState]);
                    callback(null, mqttStatus[settings.topic.statusTargetHeatingCoolingState]);
                });
        } else {
            const state = 1; // HEATING as default
            acc.getService(subtype)
                .getCharacteristic(Characteristic.TargetHeatingCoolingState)
                .setProps((settings.props || {}).TargetHeatingCoolingState || {})
                .on('get', callback => {
                    log.debug('< hap get', settings.name, 'TargetHeatingCoolingState');
                    log.debug('> hap re_get', settings.name, 'TargetHeatingCoolingState', state);
                    callback(null, state);
                });
            log.debug('> hap set', settings.name, 'TargetHeatingCoolingState', state);
            acc.getService(subtype)
                .setCharacteristic(Characteristic.TargetHeatingCoolingState, state);
        }

        /* istanbul ignore else */
        if (settings.topic.setTargetHeatingCoolingState) {
            acc.getService(subtype)
                .getCharacteristic(Characteristic.TargetHeatingCoolingState)
                .on('set', (value, callback) => {
                    log.debug('< hap set', settings.name, 'TargetHeatingCoolingState', value);
                    if (settings.topic.setTargetHeatingCoolingState) {
                        if (settings.payload && settings.payload.TargetHeatingCoolingState &&
                            settings.payload.TargetHeatingCoolingState[String(value)] !== 'undefined') {
                            value = settings.payload.TargetHeatingCoolingState[value];
                        }
                        log.debug('> mqtt', settings.topic.setTargetHeatingCoolingState, value);
                        mqttPub(settings.topic.setTargetHeatingCoolingState, value, settings.mqttPublishOptions);
                    }
                    callback();
                });
        }

        mqttSub(settings.topic.statusTargetTemperature, val => {
            log.debug('> hap update', settings.name, 'TargetTemperature', val);
            acc.getService(subtype)
                .updateCharacteristic(Characteristic.TargetTemperature, val);
        });

        acc.getService(subtype)
            .getCharacteristic(Characteristic.TargetTemperature)
            .setProps((settings.props || {}).TargetTemperature || {minValue: 4})
            .on('get', callback => {
                log.debug('< hap get', settings.name, 'TargetTemperature');
                log.debug('> hap re_get', settings.name, 'TargetTemperature', mqttStatus[settings.topic.statusTargetTemperature]);
                callback(null, mqttStatus[settings.topic.statusTargetTemperature]);
            });

        /* istanbul ignore else */
        if (settings.topic.statusTargetRelativeHumidity) {
            mqttSub(settings.topic.statusTargetRelativeHumidity, val => {
                log.debug('> hap update', settings.name, 'TargetRelativeHumidity', val);
                acc.getService(subtype)
                    .updateCharacteristic(Characteristic.TargetRelativeHumidity, val);
            });
            acc.getService(subtype)
                .getCharacteristic(Characteristic.TargetRelativeHumidity)
                .on('get', callback => {
                    log.debug('< hap get', settings.name, 'TargetRelativeHumidity');
                    log.debug('> hap re_get', settings.name, 'TargetRelativeHumidity', mqttStatus[settings.topic.statusTargetRelativeHumidity]);
                    callback(null, mqttStatus[settings.topic.statusTargetRelativeHumidity]);
                });
        }

        /* istanbul ignore else */
        if (settings.topic.setTargetRelativeHumidity) {
            acc.getService(subtype)
                .getCharacteristic(Characteristic.TargetRelativeHumidity)
                .on('set', (value, callback) => {
                    log.debug('< hap set', settings.name, 'TargetRelativeHumidity', value);
                    log.debug('> mqtt', settings.topic.setTargetRelativeHumidity, value);
                    mqttPub(settings.topic.setTargetRelativeHumidity, value);
                    callback();
                });
        }

        const obj = {acc, settings, subtype};

        require('../characteristics')('HeatingThresholdTemperature', obj, iface);
        require('../characteristics')('CoolingThresholdTemperature', obj, iface);

        require('../characteristics/CurrentTemperature')(obj, iface);
        require('../characteristics/TemperatureDisplayUnits')(obj, iface);
        require('../characteristics/CurrentRelativeHumidity')(obj, iface);
    };
};
<commit_msg>refactor TargetRelativeHumidity (#126)<commit_after>/* eslint unicorn/filename-case: "off", func-names: "off", camelcase: "off", no-unused-vars: "off" */

module.exports = function (iface) {
    const {mqttPub, mqttSub, mqttStatus, log, Service, Characteristic} = iface;

    return function createService_Thermostat(acc, settings, subtype) {
        acc.addService(Service.Thermostat, settings.name, subtype)
            .getCharacteristic(Characteristic.TargetTemperature)
            .on('set', (value, callback) => {
                log.debug('< hap set', settings.name, 'TargetTemperature', value);
                log.debug('> mqtt', settings.topic.setTargetTemperature, value);
                mqttPub(settings.topic.setTargetTemperature, value, settings.mqttPublishOptions);
                callback();
            });

        mqttSub(settings.topic.statusTargetTemperature, val => {
            log.debug('> hap update', settings.name, 'TargetTemperature', val);
            acc.getService(subtype)
                .updateCharacteristic(Characteristic.TargetTemperature, val);
        });

        acc.getService(subtype)
            .getCharacteristic(Characteristic.TargetTemperature)
            .setProps((settings.props || {}).TargetTemperature || {minValue: 4})
            .on('get', callback => {
                log.debug('< hap get', settings.name, 'TargetTemperature');
                log.debug('> hap re_get', settings.name, 'TargetTemperature', mqttStatus[settings.topic.statusTargetTemperature]);
                callback(null, mqttStatus[settings.topic.statusTargetTemperature]);
            });

        if (settings.topic.statusCurrentHeatingCoolingState) {
            mqttSub(settings.topic.statusCurrentHeatingCoolingState, val => {
                log.debug('> hap update', settings.name, 'CurrentHeatingCoolingState', val);
                acc.getService(subtype)
                    .updateCharacteristic(Characteristic.CurrentHeatingCoolingState, val);
            });
            acc.getService(subtype)
                .getCharacteristic(Characteristic.CurrentHeatingCoolingState)
                .on('get', callback => {
                    log.debug('< hap get', settings.name, 'CurrentHeatingCoolingState');
                    log.debug('> hap re_get', settings.name, 'CurrentHeatingCoolingState', mqttStatus[settings.topic.statusCurrentHeatingCoolingState]);
                    callback(null, mqttStatus[settings.topic.statusCurrentHeatingCoolingState]);
                });
        } else {
            const state = 1; // HEATING as default
            acc.getService(subtype)
                .getCharacteristic(Characteristic.CurrentHeatingCoolingState)
                .on('get', callback => {
                    log.debug('< hap get', settings.name, 'CurrentHeatingCoolingState');
                    log.debug('> hap re_get', settings.name, 'CurrentHeatingCoolingState', state);
                    callback(null, state);
                });
            log.debug('> hap set', settings.name, 'CurrentHeatingCoolingState', state);
            acc.getService(subtype)
                .setCharacteristic(Characteristic.CurrentHeatingCoolingState, state);
        }

        if (settings.topic.statusTargetHeatingCoolingState) {
            mqttSub(settings.topic.statusTargetHeatingCoolingState, val => {
                log.debug('> hap update', settings.name, 'TargetHeatingCoolingState', val);
                acc.getService(subtype)
                    .updateCharacteristic(Characteristic.TargetHeatingCoolingState, val);
            });
            acc.getService(subtype)
                .getCharacteristic(Characteristic.TargetHeatingCoolingState)
                .setProps((settings.props || {}).TargetHeatingCoolingState || {})
                .on('get', callback => {
                    log.debug('< hap get', settings.name, 'TargetHeatingCoolingState');
                    log.debug('> hap re_get', settings.name, 'TargetHeatingCoolingState', mqttStatus[settings.topic.statusTargetHeatingCoolingState]);
                    callback(null, mqttStatus[settings.topic.statusTargetHeatingCoolingState]);
                });
        } else {
            const state = 1; // HEATING as default
            acc.getService(subtype)
                .getCharacteristic(Characteristic.TargetHeatingCoolingState)
                .setProps((settings.props || {}).TargetHeatingCoolingState || {})
                .on('get', callback => {
                    log.debug('< hap get', settings.name, 'TargetHeatingCoolingState');
                    log.debug('> hap re_get', settings.name, 'TargetHeatingCoolingState', state);
                    callback(null, state);
                });
            log.debug('> hap set', settings.name, 'TargetHeatingCoolingState', state);
            acc.getService(subtype)
                .setCharacteristic(Characteristic.TargetHeatingCoolingState, state);
        }

        /* istanbul ignore else */
        if (settings.topic.setTargetHeatingCoolingState) {
            acc.getService(subtype)
                .getCharacteristic(Characteristic.TargetHeatingCoolingState)
                .on('set', (value, callback) => {
                    log.debug('< hap set', settings.name, 'TargetHeatingCoolingState', value);
                    if (settings.topic.setTargetHeatingCoolingState) {
                        if (settings.payload && settings.payload.TargetHeatingCoolingState &&
                            settings.payload.TargetHeatingCoolingState[String(value)] !== 'undefined') {
                            value = settings.payload.TargetHeatingCoolingState[value];
                        }
                        log.debug('> mqtt', settings.topic.setTargetHeatingCoolingState, value);
                        mqttPub(settings.topic.setTargetHeatingCoolingState, value, settings.mqttPublishOptions);
                    }
                    callback();
                });
        }

        const obj = {acc, settings, subtype};

        require('../characteristics')('TargetRelativeHumidity', obj, iface);
        require('../characteristics')('HeatingThresholdTemperature', obj, iface);
        require('../characteristics')('CoolingThresholdTemperature', obj, iface);

        require('../characteristics/CurrentTemperature')(obj, iface);
        require('../characteristics/TemperatureDisplayUnits')(obj, iface);
        require('../characteristics/CurrentRelativeHumidity')(obj, iface);
    };
};
<|endoftext|>


<commit_before>
MODEL({
  name: 'IssueLabelView',
  extendsModel: 'AutocompleteListView',
  properties: [
    {
      name: 'srcDAO',
      factory: function() { return this.X.LabelDAO; }
    },
    {
      name: 'queryFactory',
      defaultValue: function(data) {
        return CONTAINS_IC(QIssueLabel.LABEL, data);
      }
    },
    {
      name: 'rowView',
      defaultValue: 'LabelCitationView'
    },
    {
      name: 'acRowView',
      defaultValue: 'LabelView'
    }
  ]
});

MODEL({
  name: 'LabelCitationView',
  extendsModel: 'DefaultRowView',
  traits: ['ColoredBackgroundTrait'],
  properties: [ { name: 'className', defaultValue: 'LabelCitationView' } ],
  templates: [
    function CSS() {/*
      .IssueLabel {
        flex-direction: row;
        align-items: center;
        display: flex;

        border-radius: 50px;
        color: white;
        font-size: 14px;
        margin-right: 12px;
        margin-top: 12px;
        padding: 10px;
        padding-left: 28px;
border: 1px solid rgba(0,0,0,.1);
      }
      .IssueLabel canvas {
        background: rgba(0,0,0,0);
      }
    */},
    function toInnerHTML() {/*
      <div class="IssueLabel" <%= this.generateColorStyle(this.data.match(/[^-]+/)[0]) %>>

{{ this.data }}

        $$removeRow{width: 20, height: 20, iconUrl: 'images/ic_clear_24dp.png'}

    */}
  ]
});

MODEL({
  name: 'LabelView',
  extendsModel: 'DetailView',
  traits: ['ColoredBackgroundTrait'],
  templates: [ function toHTML() {/*

{{ this.data.label }}

  */} ]
});
<commit_msg>MBug: CSS cleanup.<commit_after>
MODEL({
  name: 'IssueLabelView',
  extendsModel: 'AutocompleteListView',
  properties: [
    {
      name: 'srcDAO',
      factory: function() { return this.X.LabelDAO; }
    },
    {
      name: 'queryFactory',
      defaultValue: function(data) {
        return CONTAINS_IC(QIssueLabel.LABEL, data);
      }
    },
    {
      name: 'rowView',
      defaultValue: 'LabelCitationView'
    },
    {
      name: 'acRowView',
      defaultValue: 'LabelView'
    }
  ]
});

MODEL({
  name: 'LabelCitationView',
  extendsModel: 'DefaultRowView',
  traits: ['ColoredBackgroundTrait'],
  properties: [ { name: 'className', defaultValue: 'LabelCitationView' } ],
  templates: [
    function CSS() {/*
      .IssueLabel {
        align-items: center;
        border-radius: 50px;
        border: 1px solid rgba(0,0,0,.1);
        color: white;
        display: flex;
        flex-direction: row;
        font-size: 14px;
        margin-right: 12px;
        margin-top: 12px;
        padding: 10px;
        padding-left: 28px;
      }
      .IssueLabel canvas {
        background: rgba(0,0,0,0);
      }
    */},
    function toInnerHTML() {/*
      <div class="IssueLabel" <%= this.generateColorStyle(this.data.match(/[^-]+/)[0]) %>>

{{ this.data }}

        $$removeRow{width: 20, height: 20, iconUrl: 'images/ic_clear_24dp.png'}

    */}
  ]
});

MODEL({
  name: 'LabelView',
  extendsModel: 'DetailView',
  traits: ['ColoredBackgroundTrait'],
  templates: [ function toHTML() {/*

{{ this.data.label }}

  */} ]
});
<|endoftext|>


<commit_before>/**
 * Created by shawnsandy on 11/6/16.
 */

gulp = require('gulp');

gulp.task('copy:js', function () {
    gulp.src(['/node'])
        .pipe(gulp.dest('./src/public/assets/'));
});

gulp.task('build', function () {
    gulp.src([
        './node_modules/font-awesome/css/**/*.*',
        './node_modules/font-awesome/fonts/**/*.*'
    ], {'base': 'node_modules'})
        .pipe(gulp.dest('src/public/assets/'))
});

gulp.task('sass', function () {
    return gulp.src('./src/resources/assets/**/*.scss', {'base': './src/resources/assets/'})
        .pipe(changed('./src/resources/assets/**/*.scss'))
        .pipe(sass().on('error', sass.logError))
        .pipe(gulp.dest('./src/resources/assets'))
        .pipe(notify({
            title: "Pages Notification",
            message: "SCSS files compiled, enjoy",
            onLast: true
        }))
});
<commit_msg>Add sass/watch:sass task<commit_after>/**
 * Created by shawnsandy on 11/6/16.
 */

var gulp = require('gulp');
var q = require('q');
var path = require('path');
var fs = require('fs');
var _ = require('underscore');
var imagemin = require('gulp-imagemin');
var sass = require('gulp-sass');
var notify = require('gulp-notify');
var changed = require('gulp-changed');
var toast = require('node-notifier');

gulp.task('copy:js', function () {
    gulp.src(['/node'])
        .pipe(gulp.dest('./src/public/assets/'));
});

gulp.task('build', function () {
    gulp.src([
        './node_modules/font-awesome/css/**/*.*',
        './node_modules/font-awesome/fonts/**/*.*'
    ], {'base': 'node_modules'})
        .pipe(gulp.dest('src/public/assets/'))
});

gulp.task('sass', function () {
    return gulp.src('./src/resources/assets/css/**/*.scss', {'base': './src/resources/assets/'})
        .pipe(sass().on('error', notify.onError('Error processing')))
        .pipe(gulp.dest('./src/resources/assets'))

});

gulp.task('watch:sass', function () {
    gulp.watch('./src/resources/assets/css/**/*.scss', ['sass']);
});
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp');
var sourcemaps = require('gulp-sourcemaps');
var transform = require('vinyl-transform');
var rename = require('gulp-rename');
var browserify = require('browserify');
var mocha = require('gulp-mocha');
var sass = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
var jshint = require('gulp-jshint');
var uglify = require('gulp-uglify');
var karma = require('karma');
var protractor = require('gulp-protractor').protractor;
var webdriver = require('gulp-protractor').webdriver;
var webdriverUpdate = require('gulp-protractor').webdriver_update;

var nodeFilesToWatch = ['app.js', 'api/**/*.js'];
var nodeTestFiles = ['api/**/test/*.js'];

/*
    Api tasks
*/
gulp.task('mocha', function () {
    return gulp.src(nodeTestFiles, {read: false})
        .pipe(mocha({reporter: 'spec'}));
});

gulp.task('lint-api', function() {
    return gulp.src(['app.js', './api/**/*.js'])
        .pipe(jshint())
        .pipe(jshint.reporter('default'));
});

/*
    Client tasks
*/
gulp.task('browserify', function() {
    var bundle = transform(function(filename) {
        var b = browserify({
            entries: filename,
            debug: true,
            insertGlobals: true
        });
        return b.bundle();
    });

    return gulp.src(['./client/main.js'])
        .pipe(bundle)
        // .pipe(uglify())
        .pipe(sourcemaps.init({loadMaps: true}))
        .pipe(rename('bundle.js'))
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest('./public'));
});

gulp.task('views', function () {
    gulp.src('client/index.html')
        .pipe(gulp.dest('public/'));

    gulp.src('client/Login/*.html')
        .pipe(gulp.dest('public/Login/'));

    gulp.src('client/Dashboard/*.html')
        .pipe(gulp.dest('public/Dashboard/'));

    gulp.src('client/ToDo/*.html')
        .pipe(gulp.dest('public/ToDo/'));
});

gulp.task('sass', function () {
    gulp.src('client/sass/*.scss')
        .pipe(sass({ onError: function (err) {
            console.error(err);
        }}))
        .pipe(autoprefixer('last 2 versions', '> 1%', 'ie 8'))
        .pipe(gulp.dest('public/css/'));
});

gulp.task('lint-client', function() {
    return gulp.src(['client/**/*.js', '!client/test/*.js'])
        .pipe(jshint())
        .pipe(jshint.reporter('default'));
});

gulp.task('webdriver-update', webdriverUpdate);
gulp.task('webdriver', webdriver);

gulp.task('protractor', ['webdriver-update', 'webdriver'], function () {
    return gulp.src('client/**/test/*.e2e.js')
        .pipe(protractor({
            configFile: './protractor.conf.js',
            args: ['--baseUrl', 'http://127.0.0.1:3000']
        }))
        .on('error', function(err) {
            console.error(err);
        });
});

/*
    Watchers
*/
gulp.task('dev', function () {
    gulp.watch(['app.js', 'api/**/*.js'], ['lint-api']);
    gulp.watch(nodeFilesToWatch, ['mocha']);
    gulp.watch(['client/**/*.js', '!client/test/*.js'], ['lint-client', 'browserify', 'protractor']);
    gulp.watch(['client/**/*.html'], ['views']);
    gulp.watch(['client/sass/*.scss'], ['sass']);

    karma.server.start({
        configFile: __dirname + '/karma.conf.js'
    });
});
<commit_msg>added build and unit-tests tasks<commit_after>'use strict';

var gulp = require('gulp');
var sourcemaps = require('gulp-sourcemaps');
var transform = require('vinyl-transform');
var rename = require('gulp-rename');
var browserify = require('browserify');
var mocha = require('gulp-mocha');
var sass = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
var jshint = require('gulp-jshint');
var uglify = require('gulp-uglify');
var karma = require('karma');
var protractor = require('gulp-protractor').protractor;
var webdriver = require('gulp-protractor').webdriver;
var webdriverUpdate = require('gulp-protractor').webdriver_update;

var nodeFilesToWatch = ['app.js', 'api/**/*.js'];
var nodeTestFiles = ['api/**/test/*.js', 'client/**/test/*.spec.js'];

/*
    Api tasks
*/
gulp.task('mocha', function () {
    return gulp.src(nodeTestFiles, {read: false})
        .pipe(mocha({reporter: 'spec'}));
});

gulp.task('lint-api', function() {
    return gulp.src(['app.js', './api/**/*.js'])
        .pipe(jshint())
        .pipe(jshint.reporter('default'));
});

/*
    Client tasks
*/
gulp.task('browserify', function() {
    var bundle = transform(function(filename) {
        var b = browserify({
            entries: filename,
            debug: true,
            insertGlobals: true
        });
        return b.bundle();
    });

    return gulp.src(['./client/main.js'])
        .pipe(bundle)
        // .pipe(uglify())
        .pipe(sourcemaps.init({loadMaps: true}))
        .pipe(rename('bundle.js'))
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest('./public'));
});

gulp.task('views', function () {
    gulp.src('client/index.html')
        .pipe(gulp.dest('public/'));

    gulp.src('client/Login/*.html')
        .pipe(gulp.dest('public/Login/'));

    gulp.src('client/Dashboard/*.html')
        .pipe(gulp.dest('public/Dashboard/'));

    gulp.src('client/ToDo/*.html')
        .pipe(gulp.dest('public/ToDo/'));
});

gulp.task('sass', function () {
    gulp.src('client/sass/*.scss')
        .pipe(sass({ onError: function (err) {
            console.error(err);
        }}))
        .pipe(autoprefixer('last 2 versions', '> 1%', 'ie 8'))
        .pipe(gulp.dest('public/css/'));
});

gulp.task('lint-client', function() {
    return gulp.src(['client/**/*.js', '!client/test/*.js'])
        .pipe(jshint())
        .pipe(jshint.reporter('default'));
});

gulp.task('webdriver-update', webdriverUpdate);
gulp.task('webdriver', webdriver);

gulp.task('protractor', ['webdriver-update', 'webdriver'], function () {
    return gulp.src('client/**/test/*.e2e.js')
        .pipe(protractor({
            configFile: './protractor.conf.js',
            args: ['--baseUrl', 'http://127.0.0.1:3000']
        }))
        .on('error', function(err) {
            console.error(err);
        });
});

gulp.task('build', ['browserify', 'views', 'sass']);

/*
    Watchers
*/
gulp.task('unit-tests', function () {
    gulp.watch(nodeTestFiles, ['mocha']);
});

gulp.task('dev', function () {
    gulp.watch(['app.js', 'api/**/*.js'], ['lint-api']);
    gulp.watch(nodeFilesToWatch, ['mocha']);
    gulp.watch(['client/**/*.js', '!client/test/*.js'], ['lint-client', 'browserify', 'protractor']);
    gulp.watch(['client/**/*.html'], ['views']);
    gulp.watch(['client/sass/*.scss'], ['sass']);

    karma.server.start({
        configFile: __dirname + '/karma.conf.js'
    });
});
<|endoftext|>