<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * Icon of the video player.
 * TODO(yoshiki): Consider providing an exact size icon, instead of relying
 * on downsampling by ash.
 *
 * @type {string}
 * @const
 */
var ICON_IMAGE = 'images/icon/video-player-64.png';

/**
 * Configuration of the video player panel.
 * @type {Object}
 */
var windowCreateOptions = {
  id: 'video',
  frame: 'none',
  minWidth: 480,
  minHeight: 270
};

/**
 * Backgound object. This is necessary for AppWindowWrapper.
 * @type {BackgroundBase}
 */
var background = new BackgroundBase();

/**
 * Queue to serialize initialization.
 * @type {AsyncUtil.Queue}
 */
var initializeQueue = new AsyncUtil.Queue();

// Initializes the strings. This needs for the volume manager.
initializeQueue.run(function(fulfill) {
  chrome.fileManagerPrivate.getStrings(function(stringData) {
    loadTimeData.data = stringData;
    fulfill();
  }.wrap());
}.wrap());

// Initializes the volume manager. This needs for isolated entries.
initializeQueue.run(function(fulfill) {
  VolumeManager.getInstance(fulfill);
}.wrap());

// Registers the handlers.
chrome.app.runtime.onLaunched.addListener(onLaunched);

/**
 * Called when an app is launched.
 * @param {Object} launchData Launch data.
 */
function onLaunched(launchData) {
  if (!launchData || !launchData.items || launchData.items.length == 0)
    return;

  var playlist = {};

  initializeQueue.run(function(fulfill) {
    var isolatedEntries = launchData.items.map(function(item) {
      return item.entry;
    }.wrap());

    chrome.fileManagerPrivate.resolveIsolatedEntries(isolatedEntries,
        function(externalEntries) {
          var urls = util.entriesToURLs(externalEntries);
          playlist = {items: urls, position: 0};
          fulfill();
        }.wrap());
  }.wrap());

  initializeQueue.run(function(fulfill) {
    openVideoPlayerWindow(playlist, false);
    fulfill();
  }.wrap());
}

var generateWindowId = (function() {
  var seq = 0;
  return function() {
    return 'VIDEO_PLAYER_APP_' + seq++;
  }.wrap();
}.wrap())();

/**
 * Opens player window.
 * @param {Object} playlist List of videos to play and index to start playing.
 * @param {boolean} reopen True if reopen, false otherwise.
 * @return {Promise} Promise to be fulfilled on success, or rejected on error.
 */
function openVideoPlayerWindow(playlist, reopen) {
  var items = playlist.items;
  var position = playlist.position;
  var startUrl = (position < items.length) ? items[position] : '';
  var windowId = null;

  return new Promise(function(fulfill, reject) {
    util.URLsToEntries(items).then(function(result) {
      fulfill(result.entries);
    }.wrap()).catch(reject);
  }.wrap()).then(function(entries) {
    if (entries.length === 0)
      return Promise.reject('No file to open.');

    // Adjusts the position to start playing.
    var maybePosition = util.entriesToURLs(entries).indexOf(startUrl);
    if (maybePosition !== -1)
      position = maybePosition;

    windowId = generateWindowId();

    // Opens the video player window.
    return new Promise(function(fulfill, reject) {
      var urls = util.entriesToURLs(entries);
      var videoPlayer = new AppWindowWrapper('video_player.html',
          windowId,
          windowCreateOptions);

      videoPlayer.launch(
          {items: urls, position: position},
          reopen,
          fulfill.bind(null, videoPlayer));
    }.wrap());
  }.wrap()).then(function(videoPlayer) {
    var appWindow = videoPlayer.rawAppWindow;

    if (chrome.test)
      appWindow.contentWindow.loadMockCastExtensionForTest = true;

    videoPlayer.setIcon(ICON_IMAGE);
    AppWindowWrapper.focusOnDesktop(appWindow);

    return windowId;
  }.wrap()).catch(function(error) {
    console.error('Launch failed' + error.stack || error);
    return Promise.reject(error);
  }.wrap());
}
<commit_msg>[Video Player] Remove the default id of the video player<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * Icon of the video player.
 * TODO(yoshiki): Consider providing an exact size icon, instead of relying
 * on downsampling by ash.
 *
 * @type {string}
 * @const
 */
var ICON_IMAGE = 'images/icon/video-player-64.png';

/**
 * Configuration of the video player panel.
 * @type {Object}
 */
var windowCreateOptions = {
  frame: 'none',
  minWidth: 480,
  minHeight: 270
};

/**
 * Backgound object. This is necessary for AppWindowWrapper.
 * @type {BackgroundBase}
 */
var background = new BackgroundBase();

/**
 * Queue to serialize initialization.
 * @type {AsyncUtil.Queue}
 */
var initializeQueue = new AsyncUtil.Queue();

// Initializes the strings. This needs for the volume manager.
initializeQueue.run(function(fulfill) {
  chrome.fileManagerPrivate.getStrings(function(stringData) {
    loadTimeData.data = stringData;
    fulfill();
  }.wrap());
}.wrap());

// Initializes the volume manager. This needs for isolated entries.
initializeQueue.run(function(fulfill) {
  VolumeManager.getInstance(fulfill);
}.wrap());

// Registers the handlers.
chrome.app.runtime.onLaunched.addListener(onLaunched);

/**
 * Called when an app is launched.
 * @param {Object} launchData Launch data.
 */
function onLaunched(launchData) {
  if (!launchData || !launchData.items || launchData.items.length == 0)
    return;

  var playlist = {};

  initializeQueue.run(function(fulfill) {
    var isolatedEntries = launchData.items.map(function(item) {
      return item.entry;
    }.wrap());

    chrome.fileManagerPrivate.resolveIsolatedEntries(isolatedEntries,
        function(externalEntries) {
          var urls = util.entriesToURLs(externalEntries);
          playlist = {items: urls, position: 0};
          fulfill();
        }.wrap());
  }.wrap());

  initializeQueue.run(function(fulfill) {
    openVideoPlayerWindow(playlist, false);
    fulfill();
  }.wrap());
}

var generateWindowId = (function() {
  var seq = 0;
  return function() {
    return 'VIDEO_PLAYER_APP_' + seq++;
  }.wrap();
}.wrap())();

/**
 * Opens player window.
 * @param {Object} playlist List of videos to play and index to start playing.
 * @param {boolean} reopen True if reopen, false otherwise.
 * @return {Promise} Promise to be fulfilled on success, or rejected on error.
 */
function openVideoPlayerWindow(playlist, reopen) {
  var items = playlist.items;
  var position = playlist.position;
  var startUrl = (position < items.length) ? items[position] : '';
  var windowId = null;

  return new Promise(function(fulfill, reject) {
    util.URLsToEntries(items).then(function(result) {
      fulfill(result.entries);
    }.wrap()).catch(reject);
  }.wrap()).then(function(entries) {
    if (entries.length === 0)
      return Promise.reject('No file to open.');

    // Adjusts the position to start playing.
    var maybePosition = util.entriesToURLs(entries).indexOf(startUrl);
    if (maybePosition !== -1)
      position = maybePosition;

    windowId = generateWindowId();

    // Opens the video player window.
    return new Promise(function(fulfill, reject) {
      var urls = util.entriesToURLs(entries);
      var videoPlayer = new AppWindowWrapper('video_player.html',
          windowId,
          windowCreateOptions);

      videoPlayer.launch(
          {items: urls, position: position},
          reopen,
          fulfill.bind(null, videoPlayer));
    }.wrap());
  }.wrap()).then(function(videoPlayer) {
    var appWindow = videoPlayer.rawAppWindow;

    if (chrome.test)
      appWindow.contentWindow.loadMockCastExtensionForTest = true;

    videoPlayer.setIcon(ICON_IMAGE);
    AppWindowWrapper.focusOnDesktop(appWindow);

    return windowId;
  }.wrap()).catch(function(error) {
    console.error('Launch failed' + error.stack || error);
    return Promise.reject(error);
  }.wrap());
}
<|endoftext|>


<commit_before>var Devices = L.layerGroup();

function init_map(){
        window.map = new L.map('map');
        var OSMBase = L.tileLayer(
                'https://{s}.tiles.mapbox.com/v3/geoprism.h4g8f1k5/{z}/{x}/{y}.png', {
                maxZoom: 18
                }).addTo(map);
var currentLat = $("input[name=device_latitude]").val();
var currentLng = $("input[name=device_longitude]").val();
var latlng = L.latLng(currentLat,currentLng);
        Device = L.marker(latlng,{
        draggable: true
        });
        Devices.addLayer(Device).addTo(map);
        Device.on('dragend', onDrag);
map.setView(latlng,9);
}

function onDrag(e){

        map.panTo(e.target.getLatLng());
        $("input[name=device_longitude]").val(e.target.getLatLng().lng)
        $("input[name=device_latitude]").val(e.target.getLatLng().lat)
        }

function updateMap(){
var newlat = $("input[name=device_latitude]").val();
var newlng = $("input[name=device_longitude]").val();
var newLatLng = L.latLng(newlat,newlng);
        Devices.removeLayer(Device);
        Device = L.marker(newLatLng,{draggable: true});
        Device.on('dragend', onDrag);
        Devices.addLayer(Device).addTo(map);
        map.panTo(newLatLng,9);
}
<commit_msg>~1m to 2m coordinate precision<commit_after>var Devices = L.layerGroup();

function init_map(){
        window.map = new L.map('map');
        var OSMBase = L.tileLayer(
                'https://{s}.tiles.mapbox.com/v3/geoprism.h4g8f1k5/{z}/{x}/{y}.png', {
                maxZoom: 18
                }).addTo(map);
var currentLat = $("input[name=device_latitude]").val();
var currentLng = $("input[name=device_longitude]").val();
var latlng = L.latLng(currentLat,currentLng);
        Device = L.marker(latlng,{
        draggable: true
        });
        Devices.addLayer(Device).addTo(map);
        Device.on('dragend', onDrag);
map.setView(latlng,9);
}

function onDrag(e){

        map.panTo(e.target.getLatLng());
        $("input[name=device_longitude]").val(e.target.getLatLng().lng.toFixed(5))
        $("input[name=device_latitude]").val(e.target.getLatLng().lat.toFixed(5))
        }

function updateMap(){
var newlat = $("input[name=device_latitude]").val();
var newlng = $("input[name=device_longitude]").val();
var newLatLng = L.latLng(newlat,newlng);
        Devices.removeLayer(Device);
        Device = L.marker(newLatLng,{draggable: true});
        Device.on('dragend', onDrag);
        Devices.addLayer(Device).addTo(map);
        map.panTo(newLatLng,9);
}
<|endoftext|>


<commit_before>/**
 * Layout component that queries for data
 * with Gatsby's useStaticQuery component
 *
 * See: https://www.gatsbyjs.org/docs/use-static-query/
 */

import React from "react"
import Helmet from "react-helmet"
import PropTypes from "prop-types"
import { useStaticQuery, graphql } from "gatsby"
import '../styles/base.sass'
import styles from './page-layout.module.sass'

import Header from "../components/header"
import Footer from "../components/footer"

const Layout = ({ children }) => {
  const data = useStaticQuery(graphql`
    query SiteTitleQuery {
      site {
        siteMetadata {
          title
        }
      }
    }
  `)

  return (
    <>
      <Helmet>

      </Helmet>

            {children}

    </>
  )
}

Layout.propTypes = {
  children: PropTypes.node.isRequired,
}

export default Layout
<commit_msg>page-layoutのclassをclassNameに修正<commit_after>/**
 * Layout component that queries for data
 * with Gatsby's useStaticQuery component
 *
 * See: https://www.gatsbyjs.org/docs/use-static-query/
 */

import React from "react"
import Helmet from "react-helmet"
import PropTypes from "prop-types"
import { useStaticQuery, graphql } from "gatsby"
import '../styles/base.sass'
import styles from './page-layout.module.sass'

import Header from "../components/header"
import Footer from "../components/footer"

const Layout = ({ children }) => {
  const data = useStaticQuery(graphql`
    query SiteTitleQuery {
      site {
        siteMetadata {
          title
        }
      }
    }
  `)

  return (
    <>
      <Helmet>

      </Helmet>

            {children}

    </>
  )
}

Layout.propTypes = {
  children: PropTypes.node.isRequired,
}

export default Layout
<|endoftext|>


<commit_before>var chromeCapabilities = {
    browserName: 'chrome'
};

var phantomJSCapabilities = {
    browserName: 'phantomjs',
    'phantomjs.binary.path': 'node_modules/phantomjs/bin/phantomjs'
};

var invalidBrowserCapabilities = {
    browserName: "Invalid Browser name provided: " + process.env.browser
};

function getBrowserCapabilities() {
    var desiredCapabilities;
    if ((process.env.browser === undefined) || (process.env.browser === "phantomjs")) {
        desiredCapabilities = phantomJSCapabilities;
    } else if (process.env.browser === "chrome") {
        desiredCapabilities = chromeCapabilities;
    } else {
        desiredCapabilities = invalidBrowserCapabilities;
    }
    console.log("-> Using " + desiredCapabilities.browserName + " browser for execution");
    return desiredCapabilities;
}

exports.config = {
    framework: 'jasmine',
    seleniumAddress: 'http://localhost:4444/wd/hub',
    specs: ['./specs/organization_spec.js', './specs/collections_reference_spec.js', './specs/user_source_spec.js', './specs/collections_spec.js', './specs/user_source_validation_spec.js', './specs/concept_spec.js', './specs/search_spec.js', './specs/mapping_spec.js'],
    capabilities: getBrowserCapabilities(),

    jasmineNodeOpts: {
        defaultTimeoutInterval: 100000,
        silent: true,
        print: function () {
        }
    },

    'onPrepare': function () {
        browser.driver.manage().window().setSize(1280, 1024);
        var SpecReporter = require('jasmine-spec-reporter');
        jasmine.getEnv().addReporter(new SpecReporter({displayStacktrace: 'all'}));
    }
};

<commit_msg>exclude mapping e2e test (#319)<commit_after>var chromeCapabilities = {
    browserName: 'chrome'
};

var phantomJSCapabilities = {
    browserName: 'phantomjs',
    'phantomjs.binary.path': 'node_modules/phantomjs/bin/phantomjs'
};

var invalidBrowserCapabilities = {
    browserName: "Invalid Browser name provided: " + process.env.browser
};

function getBrowserCapabilities() {
    var desiredCapabilities;
    if ((process.env.browser === undefined) || (process.env.browser === "phantomjs")) {
        desiredCapabilities = phantomJSCapabilities;
    } else if (process.env.browser === "chrome") {
        desiredCapabilities = chromeCapabilities;
    } else {
        desiredCapabilities = invalidBrowserCapabilities;
    }
    console.log("-> Using " + desiredCapabilities.browserName + " browser for execution");
    return desiredCapabilities;
}

exports.config = {
    framework: 'jasmine',
    seleniumAddress: 'http://localhost:4444/wd/hub',
    specs: ['./specs/organization_spec.js', './specs/collections_reference_spec.js', './specs/user_source_spec.js', './specs/collections_spec.js', './specs/user_source_validation_spec.js', './specs/concept_spec.js', './specs/search_spec.js'],
    capabilities: getBrowserCapabilities(),

    jasmineNodeOpts: {
        defaultTimeoutInterval: 100000,
        silent: true,
        print: function () {
        }
    },

    'onPrepare': function () {
        browser.driver.manage().window().setSize(1280, 1024);
        var SpecReporter = require('jasmine-spec-reporter');
        jasmine.getEnv().addReporter(new SpecReporter({displayStacktrace: 'all'}));
    }
};

<|endoftext|>


<commit_before>// Hated the old tests. TODO
var test = require('tape')
,   Api = require('../index')
,   config = require('../lib/config')
,   utils = require('../lib/utils')

test("Throw an error if key is not supplied.", function(t){
    t.plan(1)
    t.throws(function(){
        new Api()
    }, config.ERRORS.KEY_MISSING)
})

test("Creates the proper methods on initialization.", function(t){
    var api = new Api("key")
    ,   movieKeys = utils.without('movie', Object.keys(config.endpoints.movie))
    ,   movieMethods = movieKeys.map(methodPrefixer.bind(null,'movie'))
    ,   collectionKeys = utils.without('collection', Object.keys(config.endpoints.collection))
    ,   collectionMethods = collectionKeys.map(methodPrefixer.bind(null,'collection'))
    ,   companyKeys = utils.without('company', Object.keys(config.endpoints.company))
    ,   companyMethods = companyKeys.map(methodPrefixer.bind(null,'company'))

    movieMethods.forEach(function(val){
        t.equal(typeof api[val], 'function', "Testing movie method : " + val)
    })
    collectionMethods.forEach(function(val){
        t.equal(typeof api[val], 'function', "Testing collection method : " + val)
    })
    companyMethods.forEach(function(val){
        t.equal(typeof api[val], 'function', "Testing company method : " + val)
    })
    t.end()
})

function methodPrefixer(prefix, val){
    return prefix + utils.normalize(val)
}<commit_msg>More tests!<commit_after>// Hated the old tests. TODO
var test = require('tape')
,   Api = require('../index')
,   config = require('../lib/config')
,   utils = require('../lib/utils')
,   nock = require('nock')

test("Throw an error if key is not supplied.", function(t){
    t.plan(1)
    t.throws(function(){
        new Api()
    }, config.ERRORS.KEY_MISSING)
})

test("Creates the proper methods on initialization.", function(t){
    var api = new Api("key")
    ,   movieKeys = utils.without('movie', Object.keys(config.endpoints.movie))
    ,   movieMethods = movieKeys.map(methodPrefixer.bind(null,'movie'))
    ,   collectionKeys = utils.without('collection', Object.keys(config.endpoints.collection))
    ,   collectionMethods = collectionKeys.map(methodPrefixer.bind(null,'collection'))
    ,   companyKeys = utils.without('company', Object.keys(config.endpoints.company))
    ,   companyMethods = companyKeys.map(methodPrefixer.bind(null,'company'))

    movieMethods.forEach(function(val){
        t.equal(typeof api[val], 'function', "Testing movie method : " + val)
    })
    collectionMethods.forEach(function(val){
        t.equal(typeof api[val], 'function', "Testing collection method : " + val)
    })
    companyMethods.forEach(function(val){
        t.equal(typeof api[val], 'function', "Testing company method : " + val)
    })
    t.end()
})

test("Calls the genre endpoints", function(t){
    t.plan(3)
    var api = new Api('key')

    nock('http://api.themoviedb.org')
        .get('/3/genre/movie/list?api_key=key')
        .reply(200, {works : 'yes'})
    api.genres(function(err,data,res,opts){
        t.equal(data.works,'yes', 'Getting Genre List')
    })

    nock('http://api.themoviedb.org')
        .get('/3/genre/28/movies?api_key=key')
        .reply(200, {genre : 'action'})
    api.genres(28, function(err,data,opts,dd,res){
        t.equal(data.genre, 'action', 'Getting Genre List')
    })

    nock('http://api.themoviedb.org')
        .get('/3/genre/28/movies?page=2&api_key=key')
        .reply(200, {genre : 'action'})
    api.genres(28, {page : 2}, function(err,data,opts,dd,res){
        console.log(err)
        t.equal(data.genre, 'action', 'Getting Genre List')
    })
})

test("Calls the changes endpoints", function(t){
    t.plan(1)
    var api = new Api("key")
    nock('http://api.themoviedb.org')
        .get('/3/movie/changes?api_key=key')
        .reply(200, {changed : true})
    api.changes(function(err,data,opts,dd,res){
        console.log(err)
        t.equal(data.changed, true, 'Endpoint : Changes with default param')
    })
})

function methodPrefixer(prefix, val){
    return prefix + utils.normalize(val)
}<|endoftext|>


<commit_before>'use strict';

const assert = require('assert');
const SqlToJs = require('../../src/SqlToJs');
const RuntimeContext = require('../../src/RuntimeContext');
const FunctionsMap = require('../../src/FunctionsMap');
const SqlNodes = require('../../src/sql/Nodes');

describe('SqlToJs', () => {
	const sqlToJs = new SqlToJs(new FunctionsMap, new RuntimeContext(new FunctionsMap));

	describe('operators', () => {
		describe('`+`', () => {
			const node = new SqlNodes.BinaryArithmeticOperation(
				'+',
				new SqlNodes.ColumnIdent(['@', 'a']),
				new SqlNodes.ColumnIdent(['@', 'b'])
			);

			const generatedFunction = sqlToJs.nodeToFunction(node);
			const plus = (a, b) => {
				return generatedFunction({sources: {'@': {a: a, b: b}}});
			};

			it('number and number', () => {
				assert.strictEqual(plus(1, 150), 151);
			});

			it('string and number', () => {
				assert.strictEqual(plus(1, '150'), 151);
				assert.strictEqual(plus('150', 1), 151);
			});

			it('string and string', () => {
				assert.strictEqual(plus('1', '150'), 151);
			});

			it('invalid string', () => {
				assert.ok(isNaN(plus('1', '150hello')));
			});
		});
	});

	describe('IN()', () => {
		const testIn = (testValue, ctor = SqlNodes.UnstrictIn) => {
			let node;

			if (typeof(testValue) === 'number') {
				node = new SqlNodes.Number(testValue);
				node.value = testValue;
			} else if (typeof(testValue) === 'string') {
				node = new SqlNodes.String('""');
				node.value = testValue;
			} else {
				node = testValue;
			}

			return sqlToJs.nodeToFunction(new ctor(
				node,
				new SqlNodes.ExpressionsList([
					new SqlNodes.String('"11"'),
					new SqlNodes.Number(10),
					new SqlNodes.Number(9)
				])
			))(testValue);
		};

		const strictTestIn = (testValue) => {
			return testIn(testValue, SqlNodes.StrictIn);
		};

		it('unstrict', () => {
			assert.strictEqual(testIn(11), true);
			assert.strictEqual(testIn('11'), true);
			assert.strictEqual(testIn(9), true);
			assert.strictEqual(testIn('9'), true);
			assert.strictEqual(testIn(10), true);
			assert.strictEqual(testIn('10'), true);
			assert.strictEqual(testIn(8), false);
			assert.strictEqual(testIn('8'), false);
		});

		it('strict', () => {
			assert.strictEqual(strictTestIn(11), false);
			assert.strictEqual(strictTestIn('11'), true);
			assert.strictEqual(strictTestIn(9), true);
			assert.strictEqual(strictTestIn('9'), false);
			assert.strictEqual(strictTestIn(10), true);
			assert.strictEqual(strictTestIn('10'), false);
			assert.strictEqual(strictTestIn(8), false);
			assert.strictEqual(strictTestIn('8'), false);
		});
	});§
});
<commit_msg>Typo: sadly hotkey during commit<commit_after>'use strict';

const assert = require('assert');
const SqlToJs = require('../../src/SqlToJs');
const RuntimeContext = require('../../src/RuntimeContext');
const FunctionsMap = require('../../src/FunctionsMap');
const SqlNodes = require('../../src/sql/Nodes');

describe('SqlToJs', () => {
	const sqlToJs = new SqlToJs(new FunctionsMap, new RuntimeContext(new FunctionsMap));

	describe('operators', () => {
		describe('`+`', () => {
			const node = new SqlNodes.BinaryArithmeticOperation(
				'+',
				new SqlNodes.ColumnIdent(['@', 'a']),
				new SqlNodes.ColumnIdent(['@', 'b'])
			);

			const generatedFunction = sqlToJs.nodeToFunction(node);
			const plus = (a, b) => {
				return generatedFunction({sources: {'@': {a: a, b: b}}});
			};

			it('number and number', () => {
				assert.strictEqual(plus(1, 150), 151);
			});

			it('string and number', () => {
				assert.strictEqual(plus(1, '150'), 151);
				assert.strictEqual(plus('150', 1), 151);
			});

			it('string and string', () => {
				assert.strictEqual(plus('1', '150'), 151);
			});

			it('invalid string', () => {
				assert.ok(isNaN(plus('1', '150hello')));
			});
		});
	});

	describe('IN()', () => {
		const testIn = (testValue, ctor = SqlNodes.UnstrictIn) => {
			let node;

			if (typeof(testValue) === 'number') {
				node = new SqlNodes.Number(testValue);
				node.value = testValue;
			} else if (typeof(testValue) === 'string') {
				node = new SqlNodes.String('""');
				node.value = testValue;
			} else {
				node = testValue;
			}

			return sqlToJs.nodeToFunction(new ctor(
				node,
				new SqlNodes.ExpressionsList([
					new SqlNodes.String('"11"'),
					new SqlNodes.Number(10),
					new SqlNodes.Number(9)
				])
			))(testValue);
		};

		const strictTestIn = (testValue) => {
			return testIn(testValue, SqlNodes.StrictIn);
		};

		it('unstrict', () => {
			assert.strictEqual(testIn(11), true);
			assert.strictEqual(testIn('11'), true);
			assert.strictEqual(testIn(9), true);
			assert.strictEqual(testIn('9'), true);
			assert.strictEqual(testIn(10), true);
			assert.strictEqual(testIn('10'), true);
			assert.strictEqual(testIn(8), false);
			assert.strictEqual(testIn('8'), false);
		});

		it('strict', () => {
			assert.strictEqual(strictTestIn(11), false);
			assert.strictEqual(strictTestIn('11'), true);
			assert.strictEqual(strictTestIn(9), true);
			assert.strictEqual(strictTestIn('9'), false);
			assert.strictEqual(strictTestIn(10), true);
			assert.strictEqual(strictTestIn('10'), false);
			assert.strictEqual(strictTestIn(8), false);
			assert.strictEqual(strictTestIn('8'), false);
		});
	});
});
<|endoftext|>


<commit_before>'use strict';

var expect   = require('chai').expect;
var sinon    = require('sinon');
var UserBase = require('../mocks/user');
var Builder  = require('../../lib/builder');

describe('Builder', function () {

  var builder, rules;
  beforeEach(function () {
    rules = [];
    builder = new Builder(rules);
  });

  describe('Builder#create', function () {

    it('creates a new Builder', function () {
      var b = Builder.create(rules);
      expect(b)
        .to.be.an.instanceOf(Builder)
        .and.have.property('_rules', rules);
    });

  });

  describe('constructor', function () {

    it('stores the target for new rules', function () {
      expect(builder)
        .to.have.property('_rules')
        .that.equals(rules);
    });

  });

  describe('#a / #an', function () {
    ['a', 'an'].forEach(function (method) {

      it('checks that the User is a ctor w/ #can', function () {
        expect(builder[method]).to.throw(/Invalid user/);
        expect(builder[method].bind(builder, new UserBase())).to.throw(/Invalid user/);
      });

      it('stores the User', function () {
        expect(builder.a(UserBase)).to.have.property('_user', UserBase);
      });

    });
  });

  describe('#anyone (getter)', function () {

    it('passes through the builder (sugar)', function () {
      expect(builder.anyone).to.equal(builder);
    });

  });

  describe('#to', function () {

    it('sets the method', function () {
      expect(builder.to('write')).to.have.property('_method', 'write');
    });

    it('returns the builder for chaining', function () {
      expect(builder.to()).to.be.an.instanceOf(Builder);
    });

    it('has method properties for extra sugar', function () {
      expect(builder.to.write)
        .to.be.an.instanceOf(Builder)
        .and.have.property('_method', 'write');
    });

  });

  describe('rule setters', function () {

    describe('#always', function () {

      it('pushes a new rule with test = true', function () {
        builder.always();
        expect(rules)
          .to.have.property(0)
          .with.property('test', true);
      });

    });

    describe('#never', function () {

      it('pushes a new rule with test = false', function () {
        builder.never();
        expect(rules)
          .to.have.property(0)
          .with.property('test', false);
      });

    });

    describe('#when', function () {

      it('pushes a new rule with test = fn', function () {
        var fn = function () {};
        builder.when(fn);
        expect(rules)
          .to.have.property(0)
          .with.property('test', fn);
      });

    });

  });

});<commit_msg>Replace instanceOf tests with direct equality on instance<commit_after>'use strict';

var expect   = require('chai').expect;
var sinon    = require('sinon');
var UserBase = require('../mocks/user');
var Builder  = require('../../lib/builder');

describe('Builder', function () {

  var builder, rules;
  beforeEach(function () {
    rules = [];
    builder = new Builder(rules);
  });

  describe('Builder#create', function () {

    it('creates a new Builder', function () {
      var b = Builder.create(rules);
      expect(b)
        .to.be.an.instanceOf(Builder)
        .and.have.property('_rules', rules);
    });

  });

  describe('constructor', function () {

    it('stores the target for new rules', function () {
      expect(builder)
        .to.have.property('_rules')
        .that.equals(rules);
    });

  });

  describe('#a / #an', function () {
    ['a', 'an'].forEach(function (method) {

      it('checks that the User is a ctor w/ #can', function () {
        expect(builder[method]).to.throw(/Invalid user/);
        expect(builder[method].bind(builder, new UserBase())).to.throw(/Invalid user/);
      });

      it('stores the User', function () {
        expect(builder.a(UserBase)).to.have.property('_user', UserBase);
      });

    });
  });

  describe('#anyone (getter)', function () {

    it('passes through the builder (sugar)', function () {
      expect(builder.anyone).to.equal(builder);
    });

  });

  describe('#to', function () {

    it('sets the method', function () {
      expect(builder.to('write')).to.have.property('_method', 'write');
    });

    it('returns the builder for chaining', function () {
      expect(builder.to()).to.equal(builder);
    });

    it('has method properties for extra sugar', function () {
      expect(builder.to.write)
        .to.equal(builder)
        .and.have.property('_method', 'write');
    });

  });

  describe('rule setters', function () {

    describe('#always', function () {

      it('pushes a new rule with test = true', function () {
        builder.always();
        expect(rules)
          .to.have.property(0)
          .with.property('test', true);
      });

    });

    describe('#never', function () {

      it('pushes a new rule with test = false', function () {
        builder.never();
        expect(rules)
          .to.have.property(0)
          .with.property('test', false);
      });

    });

    describe('#when', function () {

      it('pushes a new rule with test = fn', function () {
        var fn = function () {};
        builder.when(fn);
        expect(rules)
          .to.have.property(0)
          .with.property('test', fn);
      });

    });

  });

});<|endoftext|>


<commit_before>var async = require('async')
var chai = require('chai')
var expect = chai.expect

var sessionStore = require('../session-store.js')
var TestManager = require('../test-manager.js')

describe('SessionStore#destroy(session_id, cb)', function() {

	before(TestManager.tearDown)
	before(TestManager.setUp)
	after(TestManager.tearDown)

	var fixtures = require('../fixtures/sessions')

	describe('when the session exists', function() {

		before(TestManager.populateSessions)

		it('should delete the session', function(done) {

			async.each(fixtures, function(fixture, nextFixture) {

				var session_id = fixture.session_id
				var data = fixture.data

				sessionStore.destroy(session_id, function(error) {

					expect(error).to.equal(undefined)

					sessionStore.get(session_id, function(error, session) {

						if (error)
							return nextFixture(new Error(error))

						expect(session).to.equal(null)

						nextFixture()

					})

				})

			}, done)

		})

	})

	describe('when the session does not exist,', function() {

		before(TestManager.clearSessions)

		it('should do nothing', function(done) {

			async.each(fixtures, function(fixture, nextFixture) {

				var session_id = fixture.session_id
				var data = fixture.data

				sessionStore.destroy(session_id, function(error) {

					expect(error).to.equal(undefined)

					nextFixture()

				})

			}, done)

		})

	})

})<commit_msg>Removed unnecessary comma in test description<commit_after>var async = require('async')
var chai = require('chai')
var expect = chai.expect

var sessionStore = require('../session-store.js')
var TestManager = require('../test-manager.js')

describe('SessionStore#destroy(session_id, cb)', function() {

	before(TestManager.tearDown)
	before(TestManager.setUp)
	after(TestManager.tearDown)

	var fixtures = require('../fixtures/sessions')

	describe('when the session exists', function() {

		before(TestManager.populateSessions)

		it('should delete the session', function(done) {

			async.each(fixtures, function(fixture, nextFixture) {

				var session_id = fixture.session_id
				var data = fixture.data

				sessionStore.destroy(session_id, function(error) {

					expect(error).to.equal(undefined)

					sessionStore.get(session_id, function(error, session) {

						if (error)
							return nextFixture(new Error(error))

						expect(session).to.equal(null)

						nextFixture()

					})

				})

			}, done)

		})

	})

	describe('when the session does not exist', function() {

		before(TestManager.clearSessions)

		it('should do nothing', function(done) {

			async.each(fixtures, function(fixture, nextFixture) {

				var session_id = fixture.session_id
				var data = fixture.data

				sessionStore.destroy(session_id, function(error) {

					expect(error).to.equal(undefined)

					nextFixture()

				})

			}, done)

		})

	})

})<|endoftext|>


<commit_before>module("support", { teardown: moduleTeardown });

var computedSupport = getComputedSupport( jQuery.support );

function getComputedSupport( support ) {
	var prop,
		result = {};

	for ( prop in support ) {
		if ( typeof support[ prop ] === "function" ) {
			result[ prop ] = support[ prop ]();
		} else {
			result[ prop ] = support[ prop ];
		}
	}

	return result;
}

if ( jQuery.css ) {
	testIframeWithCallback( "body background is not lost if set prior to loading jQuery (#9239)", "support/bodyBackground.html", function( color, support ) {
		expect( 2 );
		var okValue = {
			"#000000": true,
			"rgb(0, 0, 0)": true
		};
		ok( okValue[ color ], "color was not reset (" + color + ")" );

		deepEqual( jQuery.extend( {}, support ), computedSupport, "Same support properties" );
	});
}

// This test checkes CSP only for browsers with "Content-Security-Policy" header support
// i.e. no old WebKit or old Firefox
testIframeWithCallback( "Check CSP (https://developer.mozilla.org/en-US/docs/Security/CSP) restrictions",
	"support/csp.php",
	function( support ) {
		expect( 2 );
		deepEqual( jQuery.extend( {}, support ), computedSupport, "No violations of CSP polices" );

		stop();

		supportjQuery.get( "data/support/csp.log" ).done(function( data ) {
			equal( data, "", "No log request should be sent" );
			supportjQuery.get( "data/support/csp-clean.php" ).done( start );
		});
	}
);

(function() {
	var expected, version,
		userAgent = window.navigator.userAgent;

	if ( /chrome/i.test( userAgent ) ) {
		version = userAgent.match( /chrome\/(\d+)/i )[ 1 ];
		expected = {
			"ajax": true,
			"boxSizingReliable": true,
			"checkClone": true,
			"checkOn": true,
			"clearCloneStyle": true,
			"cors": true,
			"focusinBubbles": false,
			"noCloneChecked": true,
			"optDisabled": true,
			"optSelected": true,
			"pixelPosition": version >= 28,
			"radioValue": true,
			"reliableMarginRight": true
		};
	} else if ( /opera.*version\/12\.1/i.test( userAgent ) ) {
		expected = {
			"ajax": true,
			"boxSizingReliable": true,
			"checkClone": true,
			"checkOn": true,
			"clearCloneStyle": true,
			"cors": true,
			"focusinBubbles": false,
			"noCloneChecked": true,
			"optDisabled": true,
			"optSelected": true,
			"pixelPosition": true,
			"radioValue": false,
			"reliableMarginRight": true
		};
	} else if ( /msie 10\.0/i.test( userAgent ) ) {
		expected = {
			"ajax": true,
			"boxSizingReliable": false,
			"checkClone": true,
			"checkOn": true,
			"clearCloneStyle": false,
			"cors": true,
			"focusinBubbles": true,
			"noCloneChecked": false,
			"optDisabled": true,
			"optSelected": false,
			"pixelPosition": true,
			"radioValue": false,
			"reliableMarginRight": true
		};
	} else if ( /msie 9\.0/i.test( userAgent ) ) {
		expected = {
			"ajax": true,
			"boxSizingReliable": false,
			"checkClone": true,
			"checkOn": true,
			"clearCloneStyle": false,
			"cors": false,
			"focusinBubbles": true,
			"noCloneChecked": false,
			"optDisabled": true,
			"optSelected": false,
			"pixelPosition": true,
			"radioValue": false,
			"reliableMarginRight": true
		};
	} else if ( /6\.0\.\d+ safari/i.test( userAgent ) ) {
		expected = {
			"ajax": true,
			"boxSizingReliable": true,
			"checkClone": true,
			"checkOn": true,
			"clearCloneStyle": true,
			"cors": true,
			"focusinBubbles": false,
			"noCloneChecked": true,
			"optDisabled": true,
			"optSelected": true,
			"pixelPosition": false,
			"radioValue": true,
			"reliableMarginRight": true
		};
	} else if ( /5\.1\.\d+ safari/i.test( userAgent ) ) {
		expected = {
			"ajax":true,
			"boxSizingReliable": true,
			"checkClone":false,
			"checkOn":false,
			"clearCloneStyle": true,
			"cors":true,
			"focusinBubbles":false,
			"noCloneChecked":true,
			"optDisabled":true,
			"optSelected":true,
			"pixelPosition": false,
			"radioValue":true,
			"reliableMarginRight":true
		};
	} else if ( /firefox/i.test( userAgent ) ) {
		version = userAgent.match( /firefox\/(\d+)/i )[ 1 ];
		expected = {
			"ajax": true,
			"boxSizingReliable": version >= 23,
			"checkClone": true,
			"checkOn": true,
			"clearCloneStyle": true,
			"cors": true,
			"focusinBubbles": false,
			"noCloneChecked": true,
			"optDisabled": true,
			"optSelected": true,
			"pixelPosition": true,
			"radioValue": true,
			"reliableMarginRight": true
		};
	}

	if ( expected ) {
		test("Verify that the support tests resolve as expected per browser", function() {
			var i, prop,
				j = 0;

			for ( prop in computedSupport ) {
				j++;
			}

			expect( j );

			for ( i in expected ) {
				// TODO check for all modules containing support properties
				if ( jQuery.ajax || i !== "ajax" && i !== "cors" ) {
					equal( computedSupport[ i ], expected[ i ],
						"jQuery.support['" + i + "']: " + computedSupport[ i ] +
							", expected['" + i + "']: " + expected[ i ]);
				} else {
					ok( true, "no ajax; skipping jQuery.support[' " + i + " ']" );
				}
			}
		});
	}

})();
<commit_msg>No ticket. Remove version sniffing from test/unit/support.js, browsers got updated.<commit_after>module("support", { teardown: moduleTeardown });

var computedSupport = getComputedSupport( jQuery.support );

function getComputedSupport( support ) {
	var prop,
		result = {};

	for ( prop in support ) {
		if ( typeof support[ prop ] === "function" ) {
			result[ prop ] = support[ prop ]();
		} else {
			result[ prop ] = support[ prop ];
		}
	}

	return result;
}

if ( jQuery.css ) {
	testIframeWithCallback( "body background is not lost if set prior to loading jQuery (#9239)", "support/bodyBackground.html", function( color, support ) {
		expect( 2 );
		var okValue = {
			"#000000": true,
			"rgb(0, 0, 0)": true
		};
		ok( okValue[ color ], "color was not reset (" + color + ")" );

		deepEqual( jQuery.extend( {}, support ), computedSupport, "Same support properties" );
	});
}

// This test checkes CSP only for browsers with "Content-Security-Policy" header support
// i.e. no old WebKit or old Firefox
testIframeWithCallback( "Check CSP (https://developer.mozilla.org/en-US/docs/Security/CSP) restrictions",
	"support/csp.php",
	function( support ) {
		expect( 2 );
		deepEqual( jQuery.extend( {}, support ), computedSupport, "No violations of CSP polices" );

		stop();

		supportjQuery.get( "data/support/csp.log" ).done(function( data ) {
			equal( data, "", "No log request should be sent" );
			supportjQuery.get( "data/support/csp-clean.php" ).done( start );
		});
	}
);

(function() {
	var expected,
		userAgent = window.navigator.userAgent;

	if ( /chrome/i.test( userAgent ) ) {
		expected = {
			"ajax": true,
			"boxSizingReliable": true,
			"checkClone": true,
			"checkOn": true,
			"clearCloneStyle": true,
			"cors": true,
			"focusinBubbles": false,
			"noCloneChecked": true,
			"optDisabled": true,
			"optSelected": true,
			"pixelPosition": true,
			"radioValue": true,
			"reliableMarginRight": true
		};
	} else if ( /opera.*version\/12\.1/i.test( userAgent ) ) {
		expected = {
			"ajax": true,
			"boxSizingReliable": true,
			"checkClone": true,
			"checkOn": true,
			"clearCloneStyle": true,
			"cors": true,
			"focusinBubbles": false,
			"noCloneChecked": true,
			"optDisabled": true,
			"optSelected": true,
			"pixelPosition": true,
			"radioValue": false,
			"reliableMarginRight": true
		};
	} else if ( /msie 10\.0/i.test( userAgent ) ) {
		expected = {
			"ajax": true,
			"boxSizingReliable": false,
			"checkClone": true,
			"checkOn": true,
			"clearCloneStyle": false,
			"cors": true,
			"focusinBubbles": true,
			"noCloneChecked": false,
			"optDisabled": true,
			"optSelected": false,
			"pixelPosition": true,
			"radioValue": false,
			"reliableMarginRight": true
		};
	} else if ( /msie 9\.0/i.test( userAgent ) ) {
		expected = {
			"ajax": true,
			"boxSizingReliable": false,
			"checkClone": true,
			"checkOn": true,
			"clearCloneStyle": false,
			"cors": false,
			"focusinBubbles": true,
			"noCloneChecked": false,
			"optDisabled": true,
			"optSelected": false,
			"pixelPosition": true,
			"radioValue": false,
			"reliableMarginRight": true
		};
	} else if ( /6\.0\.\d+ safari/i.test( userAgent ) ) {
		expected = {
			"ajax": true,
			"boxSizingReliable": true,
			"checkClone": true,
			"checkOn": true,
			"clearCloneStyle": true,
			"cors": true,
			"focusinBubbles": false,
			"noCloneChecked": true,
			"optDisabled": true,
			"optSelected": true,
			"pixelPosition": false,
			"radioValue": true,
			"reliableMarginRight": true
		};
	} else if ( /5\.1\.\d+ safari/i.test( userAgent ) ) {
		expected = {
			"ajax":true,
			"boxSizingReliable": true,
			"checkClone":false,
			"checkOn":false,
			"clearCloneStyle": true,
			"cors":true,
			"focusinBubbles":false,
			"noCloneChecked":true,
			"optDisabled":true,
			"optSelected":true,
			"pixelPosition": false,
			"radioValue":true,
			"reliableMarginRight":true
		};
	} else if ( /firefox/i.test( userAgent ) ) {
		expected = {
			"ajax": true,
			"boxSizingReliable": true,
			"checkClone": true,
			"checkOn": true,
			"clearCloneStyle": true,
			"cors": true,
			"focusinBubbles": false,
			"noCloneChecked": true,
			"optDisabled": true,
			"optSelected": true,
			"pixelPosition": true,
			"radioValue": true,
			"reliableMarginRight": true
		};
	}

	if ( expected ) {
		test("Verify that the support tests resolve as expected per browser", function() {
			var i, prop,
				j = 0;

			for ( prop in computedSupport ) {
				j++;
			}

			expect( j );

			for ( i in expected ) {
				// TODO check for all modules containing support properties
				if ( jQuery.ajax || i !== "ajax" && i !== "cors" ) {
					equal( computedSupport[ i ], expected[ i ],
						"jQuery.support['" + i + "']: " + computedSupport[ i ] +
							", expected['" + i + "']: " + expected[ i ]);
				} else {
					ok( true, "no ajax; skipping jQuery.support[' " + i + " ']" );
				}
			}
		});
	}

})();
<|endoftext|>


<commit_before>module("support", { teardown: moduleTeardown });

var computedSupport = getComputedSupport( jQuery.support );

function getComputedSupport( support ) {
	var prop,
		result = {};

	for ( prop in support ) {
		if ( typeof support[ prop ] === "function" ) {
			result[ prop ] = support[ prop ]();
		} else {
			result[ prop ] = support[ prop ];
		}
	}

	return result;
}

if ( jQuery.css ) {
	testIframeWithCallback( "body background is not lost if set prior to loading jQuery (#9239)", "support/bodyBackground.html", function( color, support ) {
		expect( 2 );
		var okValue = {
			"#000000": true,
			"rgb(0, 0, 0)": true
		};
		ok( okValue[ color ], "color was not reset (" + color + ")" );

		deepEqual( jQuery.extend( {}, support ), computedSupport, "Same support properties" );
	});
}

(function() {
	var expected,
		userAgent = window.navigator.userAgent;

	if ( /chrome/i.test( userAgent ) ) {
		expected = {
			"ajax": true,
			"boxSizingReliable": true,
			"checkClone": true,
			"checkOn": true,
			"clearCloneStyle": true,
			"cors": true,
			"focusinBubbles": false,
			"noCloneChecked": true,
			"optDisabled": true,
			"optSelected": true,
			"pixelPosition": true,
			"radioValue": true,
			"reliableMarginRight": true
		};
	} else if ( /opera.*version\/12\.1/i.test( userAgent ) ) {
		expected = {
			"ajax": true,
			"boxSizingReliable": true,
			"checkClone": true,
			"checkOn": true,
			"clearCloneStyle": true,
			"cors": true,
			"focusinBubbles": false,
			"noCloneChecked": true,
			"optDisabled": true,
			"optSelected": true,
			"pixelPosition": true,
			"radioValue": false,
			"reliableMarginRight": true
		};
	} else if ( /msie 10\.0/i.test( userAgent ) ) {
		expected = {
			"ajax": true,
			"boxSizingReliable": false,
			"checkClone": true,
			"checkOn": true,
			"clearCloneStyle": false,
			"cors": true,
			"focusinBubbles": true,
			"noCloneChecked": false,
			"optDisabled": true,
			"optSelected": false,
			"pixelPosition": true,
			"radioValue": false,
			"reliableMarginRight": true
		};
	} else if ( /msie 9\.0/i.test( userAgent ) ) {
		expected = {
			"ajax": true,
			"boxSizingReliable": false,
			"checkClone": true,
			"checkOn": true,
			"clearCloneStyle": false,
			"cors": false,
			"focusinBubbles": true,
			"noCloneChecked": false,
			"optDisabled": true,
			"optSelected": false,
			"pixelPosition": true,
			"radioValue": false,
			"reliableMarginRight": true
		};
	} else if ( /6\.0\.\d+ safari/i.test( userAgent ) ) {
		expected = {
			"ajax": true,
			"boxSizingReliable": true,
			"checkClone": true,
			"checkOn": true,
			"clearCloneStyle": true,
			"cors": true,
			"focusinBubbles": false,
			"noCloneChecked": true,
			"optDisabled": true,
			"optSelected": true,
			"pixelPosition": false,
			"radioValue": true,
			"reliableMarginRight": true
		};
	} else if ( /firefox/i.test( userAgent ) ) {
		expected = {
			"ajax": true,
			"boxSizingReliable": true,
			"checkClone": true,
			"checkOn": true,
			"clearCloneStyle": true,
			"cors": true,
			"focusinBubbles": false,
			"noCloneChecked": true,
			"optDisabled": true,
			"optSelected": true,
			"pixelPosition": true,
			"radioValue": true,
			"reliableMarginRight": true
		};
	}

	if ( expected ) {
		test("Verify that the support tests resolve as expected per browser", function() {
			var i, prop,
				j = 0;

			for ( prop in computedSupport ) {
				j++;
			}

			expect( j );

			for ( i in expected ) {
				// TODO check for all modules containing support properties
				if ( jQuery.ajax || i !== "ajax" && i !== "cors" ) {
					equal( computedSupport[ i ], expected[ i ],
						"jQuery.support['" + i + "']: " + computedSupport[ i ] +
							", expected['" + i + "']: " + expected[ i ]);
				} else {
					ok( true, "no ajax; skipping jQuery.support[' " + i + " ']" );
				}
			}
		});
	}

})();

// Support: Safari 5.1
// Shameless browser-sniff, but Safari 5.1 mishandles CSP
if ( !( typeof navigator !== "undefined" &&
	(/ AppleWebKit\/\d.*? Version\/(\d+)/.exec(navigator.userAgent) || [])[1] < 6 ) ) {

	testIframeWithCallback( "Check CSP (https://developer.mozilla.org/en-US/docs/Security/CSP) restrictions",
		"support/csp.php",
		function( support ) {
			expect( 1 );
			deepEqual( jQuery.extend( {}, support ), computedSupport, "No violations of CSP polices" );
		}
	);
}
<commit_msg>Restore support for Firefox < 23, Chrome < 28 and Safari 5.1.<commit_after>module("support", { teardown: moduleTeardown });

var computedSupport = getComputedSupport( jQuery.support );

function getComputedSupport( support ) {
	var prop,
		result = {};

	for ( prop in support ) {
		if ( typeof support[ prop ] === "function" ) {
			result[ prop ] = support[ prop ]();
		} else {
			result[ prop ] = support[ prop ];
		}
	}

	return result;
}

if ( jQuery.css ) {
	testIframeWithCallback( "body background is not lost if set prior to loading jQuery (#9239)", "support/bodyBackground.html", function( color, support ) {
		expect( 2 );
		var okValue = {
			"#000000": true,
			"rgb(0, 0, 0)": true
		};
		ok( okValue[ color ], "color was not reset (" + color + ")" );

		deepEqual( jQuery.extend( {}, support ), computedSupport, "Same support properties" );
	});
}

(function() {
	var expected, version,
		userAgent = window.navigator.userAgent;

	if ( /chrome/i.test( userAgent ) ) {
		version = userAgent.match( /chrome\/(\d+)/i )[ 1 ];
		expected = {
			"ajax": true,
			"boxSizingReliable": true,
			"checkClone": true,
			"checkOn": true,
			"clearCloneStyle": true,
			"cors": true,
			"focusinBubbles": false,
			"noCloneChecked": true,
			"optDisabled": true,
			"optSelected": true,
			"pixelPosition": version >= 28,
			"radioValue": true,
			"reliableMarginRight": true
		};
	} else if ( /opera.*version\/12\.1/i.test( userAgent ) ) {
		expected = {
			"ajax": true,
			"boxSizingReliable": true,
			"checkClone": true,
			"checkOn": true,
			"clearCloneStyle": true,
			"cors": true,
			"focusinBubbles": false,
			"noCloneChecked": true,
			"optDisabled": true,
			"optSelected": true,
			"pixelPosition": true,
			"radioValue": false,
			"reliableMarginRight": true
		};
	} else if ( /msie 10\.0/i.test( userAgent ) ) {
		expected = {
			"ajax": true,
			"boxSizingReliable": false,
			"checkClone": true,
			"checkOn": true,
			"clearCloneStyle": false,
			"cors": true,
			"focusinBubbles": true,
			"noCloneChecked": false,
			"optDisabled": true,
			"optSelected": false,
			"pixelPosition": true,
			"radioValue": false,
			"reliableMarginRight": true
		};
	} else if ( /msie 9\.0/i.test( userAgent ) ) {
		expected = {
			"ajax": true,
			"boxSizingReliable": false,
			"checkClone": true,
			"checkOn": true,
			"clearCloneStyle": false,
			"cors": false,
			"focusinBubbles": true,
			"noCloneChecked": false,
			"optDisabled": true,
			"optSelected": false,
			"pixelPosition": true,
			"radioValue": false,
			"reliableMarginRight": true
		};
	} else if ( /6\.0\.\d+ safari/i.test( userAgent ) ) {
		expected = {
			"ajax": true,
			"boxSizingReliable": true,
			"checkClone": true,
			"checkOn": true,
			"clearCloneStyle": true,
			"cors": true,
			"focusinBubbles": false,
			"noCloneChecked": true,
			"optDisabled": true,
			"optSelected": true,
			"pixelPosition": false,
			"radioValue": true,
			"reliableMarginRight": true
		};
	} else if ( /5\.1\.\d+ safari/i.test( userAgent ) ) {
		expected = {
			"ajax":true,
			"boxSizingReliable": true,
			"checkClone":false,
			"checkOn":false,
			"clearCloneStyle": true,
			"cors":true,
			"focusinBubbles":false,
			"noCloneChecked":true,
			"optDisabled":true,
			"optSelected":true,
			"pixelPosition": false,
			"radioValue":true,
			"reliableMarginRight":true
		};
	} else if ( /firefox/i.test( userAgent ) ) {
		version = userAgent.match( /firefox\/(\d+)/i )[ 1 ];
		expected = {
			"ajax": true,
			"boxSizingReliable": version >= 23,
			"checkClone": true,
			"checkOn": true,
			"clearCloneStyle": true,
			"cors": true,
			"focusinBubbles": false,
			"noCloneChecked": true,
			"optDisabled": true,
			"optSelected": true,
			"pixelPosition": true,
			"radioValue": true,
			"reliableMarginRight": true
		};
	}

	if ( expected ) {
		test("Verify that the support tests resolve as expected per browser", function() {
			var i, prop,
				j = 0;

			for ( prop in computedSupport ) {
				j++;
			}

			expect( j );

			for ( i in expected ) {
				// TODO check for all modules containing support properties
				if ( jQuery.ajax || i !== "ajax" && i !== "cors" ) {
					equal( computedSupport[ i ], expected[ i ],
						"jQuery.support['" + i + "']: " + computedSupport[ i ] +
							", expected['" + i + "']: " + expected[ i ]);
				} else {
					ok( true, "no ajax; skipping jQuery.support[' " + i + " ']" );
				}
			}
		});
	}

})();

// Support: Safari 5.1
// Shameless browser-sniff, but Safari 5.1 mishandles CSP
if ( !( typeof navigator !== "undefined" &&
	(/ AppleWebKit\/\d.*? Version\/(\d+)/.exec(navigator.userAgent) || [])[1] < 6 ) ) {

	testIframeWithCallback( "Check CSP (https://developer.mozilla.org/en-US/docs/Security/CSP) restrictions",
		"support/csp.php",
		function( support ) {
			expect( 1 );
			deepEqual( jQuery.extend( {}, support ), computedSupport, "No violations of CSP polices" );
		}
	);
}
<|endoftext|>


<commit_before>var test = require('tap').test;
var trumpet = require('../');
var fs = require('fs');

test('update', function (t) {
    t.plan(6);
    var html = fs.readFileSync(__dirname + '/update_target.html', 'utf8');

    var tr = trumpet();
    fs.createReadStream(__dirname + '/update.html').pipe(tr);

    var spans = [ 'tacos', 'y', 'burritos' ];

    tr.update('.b span', function (html, node) {
        t.equal(node.name, 'span');
        return html.toUpperCase();
    });

    tr.update('.c', '---');
    tr.remove('.d');
    tr.remove('.e');
    tr.replace('.f', 'NOTHING TO SEE HERE');

    tr.replace('.g', function (html, node) {
        t.equal(node.name, 'div');
        t.same(node.attributes, { class : 'g' });
        t.equal(html, '
EVERYTHING IS TERRIBLE
');
        return '<blink>TERRIBLE</blink>';
    });

    var data = '';
    tr.on('data', function (buf) { data += buf });

    tr.on('end', function () {
        t.equal(data, html);
    });
});
<commit_msg>plan the correct number of tests this time<commit_after>var test = require('tap').test;
var trumpet = require('../');
var fs = require('fs');

test('update', function (t) {
    t.plan(7);
    var html = fs.readFileSync(__dirname + '/update_target.html', 'utf8');

    var tr = trumpet();
    fs.createReadStream(__dirname + '/update.html').pipe(tr);

    var spans = [ 'tacos', 'y', 'burritos' ];

    tr.update('.b span', function (html, node) {
        t.equal(node.name, 'span');
        return html.toUpperCase();
    });

    tr.update('.c', '---');
    tr.remove('.d');
    tr.remove('.e');
    tr.replace('.f', 'NOTHING TO SEE HERE');

    tr.replace('.g', function (html, node) {
        t.equal(node.name, 'div');
        t.same(node.attributes, { class : 'g' });
        t.equal(html, '
EVERYTHING IS TERRIBLE
');
        return '<blink>TERRIBLE</blink>';
    });

    var data = '';
    tr.on('data', function (buf) { data += buf });

    tr.on('end', function () {
        t.equal(data, html);
        t.end();
    });
});
<|endoftext|>


<commit_before>var fs = require('fs')

  , mime = require('mime')
  , paramify = require('paramify')
  , serveBrowserify = require('serve-browserify')({
        root: __dirname
      , debug: true
      , gzip: true
    })
  , count = 0
  , headers = [
        'eventName', 'windowWidth', 'windowHeight', 'scrollX', 'scrollY'
      , 'location' , 'duration', 'timestamp', 'timezone', 'referrer', 'path'
      , 'clickX', 'clickY', 'href', 'target', 'visibility', 'name'
      , 'trackableType', 'trackableValue'
    ].join(',')

    // serve the file, default to index.html
  , serveStatic = function (filename, res) {
      fs.readFile(__dirname + '/static/' + filename, function (err, file) {
        if (err) {
          serveStatic('index.html', res)
        } else {
          res.setHeader('content-type', mime.lookup(filename))
          res.end(file)
        }
      })
    }

  , createServer = function () {
      var server = require('http').createServer(function (req, res) {
          var match = paramify(req.url)

          if (req.method === 'POST') {
            req.on('data', function (chunk) {
              server.eventStream.write(chunk)
              server.eventStream.write(new Buffer('\n'))
            })
            req.once('end', res.end.bind(res))
          } else if (match('client.js')) {
            serveBrowserify(req, res)
          } else {
            serveStatic(req.url, res)
          }
        })

      server.eventStream = require('csv-parser')()
      server.eventStream.write(new Buffer(headers + '\n'))

      return server
    }

module.exports = createServer
<commit_msg>add new columns to test server<commit_after>var fs = require('fs')

  , mime = require('mime')
  , paramify = require('paramify')
  , serveBrowserify = require('serve-browserify')({
        root: __dirname
      , debug: true
      , gzip: true
    })
  , count = 0
  , headers = [
        'client', 'clientVersion'
      , 'eventName', 'windowWidth', 'windowHeight', 'scrollX', 'scrollY'
      , 'location' , 'duration', 'timestamp', 'timezone', 'referrer', 'path'
      , 'clickX', 'clickY', 'href', 'target', 'visibility', 'name'
      , 'trackableType', 'trackableValue'
    ].join(',')

    // serve the file, default to index.html
  , serveStatic = function (filename, res) {
      fs.readFile(__dirname + '/static/' + filename, function (err, file) {
        if (err) {
          serveStatic('index.html', res)
        } else {
          res.setHeader('content-type', mime.lookup(filename))
          res.end(file)
        }
      })
    }

  , createServer = function () {
      var server = require('http').createServer(function (req, res) {
          var match = paramify(req.url)

          if (req.method === 'POST') {
            req.on('data', function (chunk) {
              server.eventStream.write(chunk)
              server.eventStream.write(new Buffer('\n'))
            })
            req.once('end', res.end.bind(res))
          } else if (match('client.js')) {
            serveBrowserify(req, res)
          } else {
            serveStatic(req.url, res)
          }
        })

      server.eventStream = require('csv-parser')()
      server.eventStream.write(new Buffer(headers + '\n'))

      return server
    }

module.exports = createServer
<|endoftext|>


<commit_before>/*
 * Copyright 2015 Telefonica Investigación y Desarrollo, S.A.U
 *
 * This file is part of perseo-fe
 *
 * perseo-fe is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * perseo-fe is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with perseo-fe.
 * If not, see http://www.gnu.org/licenses/.
 *
 * For those usages not covered by the GNU Affero General Public License
 * please contact with iot_support at tid dot es
 */

'use strict';

var fs = require('fs'),
    path = require('path'),
    MongoClient = require('mongodb').MongoClient,
    config = require('../../config'),
    fakeServerPort = 9753,
    fakeServerCode = 200,
    fakeServerMessage = 'All right',
    fakeServerCallback;

function loadExample(fileName) {
    var f = fs.readFileSync(fileName);
    return JSON.parse(f);
}

function loadDirExamples(filepath) {
    var files = fs.readdirSync(filepath),
        objects = [],
        elementPath;

    files.forEach(function(element) {
        elementPath = path.join(filepath, element);
        objects.push({filename: elementPath, object: loadExample(elementPath)});
    });
    return objects;
}

function remove(collection, callback) {
    MongoClient.connect(config.mongo.url, function(err, db) {
        if (err) {
            return callback(err);
        }
        db.collection(collection, {}, function(err, coll) {
            if (err) {
                return callback(err);
            }
            coll.remove({}, function(err, result) {
                if (err) {
                    return callback(err);
                }
                db.close();
                return callback(null, result);
            });
        });
    });
}

function dropRules(callback) {
    remove(config.collections.rules, callback);
}
function dropExecutions(callback) {
    remove(config.collections.executions, callback);
}
function dropEntities(callback) {
    MongoClient.connect(config.orion.url, function(err, db) {
        if (err) {
            return callback(err);
        }
        db.collection(config.orionDb.collection, {}, function(err, coll) {
            if (err) {
                return callback(err);
            }
            coll.remove({}, function(err, result) {
                if (err) {
                    return callback(err);
                }
                db.close();
                return callback(null, result);
            });
        });
    });
}

function dropCollection(collection, callback) {
    MongoClient.connect(config.mongo.url, function(err, db) {
        if (err) {
            return callback(err);
        }
        db.collection(collection, {}, function(err, col) {
            if (err) {
                return callback(err);
            }
            col.drop(function(err, result) {
                if (err) {
                    return callback(err);
                }
                db.close();
                return callback(null, result);
            });
        });
    });
}
function dropRulesCollection(callback) {
    dropCollection(config.collections.rules, callback);
}
function dropExecutionsCollection(callback) {
    dropCollection(config.collections.executions, callback);
}

function createRulesCollection(callback) {
    MongoClient.connect(config.mongo.url, function(err, db) {
        if (err) {
            return callback(err);
        }
        db.collection(config.collections.rules, {}, function(err, rules) {
            if (err) {
                return callback(err);
            }
            rules.ensureIndex({name: 1}, {unique: true, w: 'majority'}, function(err, indexName) {
                db.close();
                return callback(err, indexName);
            });
        });
    });
}

function addRule(rule, callback) {
    MongoClient.connect(config.mongo.url, function(err, db) {
        if (err) {
            return callback(err);
        }
        db.collection(config.collections.rules, {}, function(err, rules) {
            if (err) {
                return callback(err);
            }
            rules.save(rule, function(err, result) {
                if (err) {
                    return callback(err);
                }
                db.close();
                return callback(null, result);
            });
        });
    });
}

function createEntitiesCollection(tenant, callback) {
    MongoClient.connect(config.orionDb.url, function(err, db) {
        var db2 = db.db(config.orionDb.prefix + '-' + tenant);
        if (err) {
            return callback(err);
        }
        db2.collection(config.orionDb.collection, {}, function(err, rules) {
            if (err) {
                return callback(err);
            }
            // We don't mind what fields have index in that collection
            rules.ensureIndex({modDate: 1}, {unique: true, w: 'majority'}, function(err, indexName) {
                db2.close();
                return callback(err, indexName);
            });
        });
    });
}
function dropEntities(callback) {
    MongoClient.connect(config.orionDb.url, function(err, db) {
        var db2 = db.db(config.orionDb.prefix + '-' + config.DEFAULT_TENANT);
        if (err) {
            return callback(err);
        }
        db2.collection(config.orionDb.collection, {}, function(err, coll) {
            if (err) {
                return callback(err);
            }
            coll.remove({}, function(err, result) {
                if (err) {
                    return callback(err);
                }
                db2.close();
                return callback(null, result);
            });
        });
    });
}
function addEntity(tenant, entity, callback) {
    MongoClient.connect(config.orionDb.url, function(err, db) {
        var db2;
        if (err) {
            return callback(err);
        }
        db2 = db.db(config.orionDb.prefix + '-' + tenant);
        db2.collection(config.orionDb.collection, {}, function(err, entities) {
            if (err) {
                return callback(err);
            }
            entities.save(entity, function(err, result) {
                if (err) {
                    return callback(err);
                }
                db2.close();
                return callback(null, result);
            });
        });
    });
}
function configTest() {
    config.mongo.url = 'mongodb://localhost:27017/perseo_testing';
    config.endpoint.port = 9182;
    config.perseoCore.noticesURL = 'http://localhost:' + fakeServerPort;
    config.perseoCore.rulesURL = 'http://localhost:' + fakeServerPort;
    config.logLevel = 'error';
    config.nextCore = {};
    config.orionDb.url = 'mongodb://localhost:27017/test';
    config.orionDb.prefix = 'oriontest';
    config.perseoCore.interval = 10 * 60e3; //Do not refresh in the middle of a long test
}
function getConfig() {
    return config;
}

function fakeHttpServer(cb) {
    var server = require('http').createServer(function(req, res) {
        var body;
        req.on('data', function(data) {
            body += data;
        });
        req.on('end', function() {
            if (fakeServerCallback) {
                fakeServerCallback(req, res, body);
            } else {
                res.writeHead(fakeServerCode, {'Content-Type': 'text/plain'});
                res.end(fakeServerMessage);
            }
        });
    }).listen(fakeServerPort, function() {
        cb(null, server);
    });
}

module.exports.loadExample = loadExample;
module.exports.loadDirExamples = loadDirExamples;
module.exports.addRule = addRule;
module.exports.dropRules = dropRules;
module.exports.dropExecutions = dropExecutions;
module.exports.dropRulesCollection = dropRulesCollection;
module.exports.dropExecutionsCollection = dropExecutionsCollection;
module.exports.createRulesCollection = createRulesCollection;
module.exports.createEntitiesCollection = createEntitiesCollection;
module.exports.addEntity = addEntity;
module.exports.dropEntities = dropEntities;
module.exports.configTest = configTest;
module.exports.fakeHttpServer = fakeHttpServer;
module.exports.fakeHttpServerPort = fakeServerPort;
module.exports.setServerCode = function(code) {
    fakeServerCode = code;
};
module.exports.setServerMessage = function(msg) {
    fakeServerMessage = msg;
};
module.exports.setServerCallback = function(fxn) {
    fakeServerCallback = fxn;
};
module.exports.getConfig = getConfig;

<commit_msg>Restore log level for tests<commit_after>/*
 * Copyright 2015 Telefonica Investigación y Desarrollo, S.A.U
 *
 * This file is part of perseo-fe
 *
 * perseo-fe is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * perseo-fe is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with perseo-fe.
 * If not, see http://www.gnu.org/licenses/.
 *
 * For those usages not covered by the GNU Affero General Public License
 * please contact with iot_support at tid dot es
 */

'use strict';

var fs = require('fs'),
    path = require('path'),
    MongoClient = require('mongodb').MongoClient,
    config = require('../../config'),
    fakeServerPort = 9753,
    fakeServerCode = 200,
    fakeServerMessage = 'All right',
    fakeServerCallback;

function loadExample(fileName) {
    var f = fs.readFileSync(fileName);
    return JSON.parse(f);
}

function loadDirExamples(filepath) {
    var files = fs.readdirSync(filepath),
        objects = [],
        elementPath;

    files.forEach(function(element) {
        elementPath = path.join(filepath, element);
        objects.push({filename: elementPath, object: loadExample(elementPath)});
    });
    return objects;
}

function remove(collection, callback) {
    MongoClient.connect(config.mongo.url, function(err, db) {
        if (err) {
            return callback(err);
        }
        db.collection(collection, {}, function(err, coll) {
            if (err) {
                return callback(err);
            }
            coll.remove({}, function(err, result) {
                if (err) {
                    return callback(err);
                }
                db.close();
                return callback(null, result);
            });
        });
    });
}

function dropRules(callback) {
    remove(config.collections.rules, callback);
}
function dropExecutions(callback) {
    remove(config.collections.executions, callback);
}
function dropEntities(callback) {
    MongoClient.connect(config.orion.url, function(err, db) {
        if (err) {
            return callback(err);
        }
        db.collection(config.orionDb.collection, {}, function(err, coll) {
            if (err) {
                return callback(err);
            }
            coll.remove({}, function(err, result) {
                if (err) {
                    return callback(err);
                }
                db.close();
                return callback(null, result);
            });
        });
    });
}

function dropCollection(collection, callback) {
    MongoClient.connect(config.mongo.url, function(err, db) {
        if (err) {
            return callback(err);
        }
        db.collection(collection, {}, function(err, col) {
            if (err) {
                return callback(err);
            }
            col.drop(function(err, result) {
                if (err) {
                    return callback(err);
                }
                db.close();
                return callback(null, result);
            });
        });
    });
}
function dropRulesCollection(callback) {
    dropCollection(config.collections.rules, callback);
}
function dropExecutionsCollection(callback) {
    dropCollection(config.collections.executions, callback);
}

function createRulesCollection(callback) {
    MongoClient.connect(config.mongo.url, function(err, db) {
        if (err) {
            return callback(err);
        }
        db.collection(config.collections.rules, {}, function(err, rules) {
            if (err) {
                return callback(err);
            }
            rules.ensureIndex({name: 1}, {unique: true, w: 'majority'}, function(err, indexName) {
                db.close();
                return callback(err, indexName);
            });
        });
    });
}

function addRule(rule, callback) {
    MongoClient.connect(config.mongo.url, function(err, db) {
        if (err) {
            return callback(err);
        }
        db.collection(config.collections.rules, {}, function(err, rules) {
            if (err) {
                return callback(err);
            }
            rules.save(rule, function(err, result) {
                if (err) {
                    return callback(err);
                }
                db.close();
                return callback(null, result);
            });
        });
    });
}

function createEntitiesCollection(tenant, callback) {
    MongoClient.connect(config.orionDb.url, function(err, db) {
        var db2 = db.db(config.orionDb.prefix + '-' + tenant);
        if (err) {
            return callback(err);
        }
        db2.collection(config.orionDb.collection, {}, function(err, rules) {
            if (err) {
                return callback(err);
            }
            // We don't mind what fields have index in that collection
            rules.ensureIndex({modDate: 1}, {unique: true, w: 'majority'}, function(err, indexName) {
                db2.close();
                return callback(err, indexName);
            });
        });
    });
}
function dropEntities(callback) {
    MongoClient.connect(config.orionDb.url, function(err, db) {
        var db2 = db.db(config.orionDb.prefix + '-' + config.DEFAULT_TENANT);
        if (err) {
            return callback(err);
        }
        db2.collection(config.orionDb.collection, {}, function(err, coll) {
            if (err) {
                return callback(err);
            }
            coll.remove({}, function(err, result) {
                if (err) {
                    return callback(err);
                }
                db2.close();
                return callback(null, result);
            });
        });
    });
}
function addEntity(tenant, entity, callback) {
    MongoClient.connect(config.orionDb.url, function(err, db) {
        var db2;
        if (err) {
            return callback(err);
        }
        db2 = db.db(config.orionDb.prefix + '-' + tenant);
        db2.collection(config.orionDb.collection, {}, function(err, entities) {
            if (err) {
                return callback(err);
            }
            entities.save(entity, function(err, result) {
                if (err) {
                    return callback(err);
                }
                db2.close();
                return callback(null, result);
            });
        });
    });
}
function configTest() {
    config.mongo.url = 'mongodb://localhost:27017/perseo_testing';
    config.endpoint.port = 9182;
    config.perseoCore.noticesURL = 'http://localhost:' + fakeServerPort;
    config.perseoCore.rulesURL = 'http://localhost:' + fakeServerPort;
    config.logLevel = 'fatal';
    config.nextCore = {};
    config.orionDb.url = 'mongodb://localhost:27017/test';
    config.orionDb.prefix = 'oriontest';
    config.perseoCore.interval = 10 * 60e3; //Do not refresh in the middle of a long test
}
function getConfig() {
    return config;
}

function fakeHttpServer(cb) {
    var server = require('http').createServer(function(req, res) {
        var body;
        req.on('data', function(data) {
            body += data;
        });
        req.on('end', function() {
            if (fakeServerCallback) {
                fakeServerCallback(req, res, body);
            } else {
                res.writeHead(fakeServerCode, {'Content-Type': 'text/plain'});
                res.end(fakeServerMessage);
            }
        });
    }).listen(fakeServerPort, function() {
        cb(null, server);
    });
}

module.exports.loadExample = loadExample;
module.exports.loadDirExamples = loadDirExamples;
module.exports.addRule = addRule;
module.exports.dropRules = dropRules;
module.exports.dropExecutions = dropExecutions;
module.exports.dropRulesCollection = dropRulesCollection;
module.exports.dropExecutionsCollection = dropExecutionsCollection;
module.exports.createRulesCollection = createRulesCollection;
module.exports.createEntitiesCollection = createEntitiesCollection;
module.exports.addEntity = addEntity;
module.exports.dropEntities = dropEntities;
module.exports.configTest = configTest;
module.exports.fakeHttpServer = fakeHttpServer;
module.exports.fakeHttpServerPort = fakeServerPort;
module.exports.setServerCode = function(code) {
    fakeServerCode = code;
};
module.exports.setServerMessage = function(msg) {
    fakeServerMessage = msg;
};
module.exports.setServerCallback = function(fxn) {
    fakeServerCallback = fxn;
};
module.exports.getConfig = getConfig;

<|endoftext|>


<commit_before>/**
 * @file BaseButton component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';

import CircularLoading from '../CircularLoading';
import TipProvider from '../TipProvider';
import TouchRipple from '../TouchRipple';
import Theme from '../Theme';

import Util from '../_vendors/Util';
import Position from '../_statics/Position';

class BaseButton extends Component {

    static Theme = Theme;
    static TipPosition = Position;

    constructor(props, ...restArgs) {
        super(props, ...restArgs);
    }

    clickHandler = e => {
        e.preventDefault();
        const {disabled, isLoading, onClick} = this.props;
        !disabled && !isLoading && onClick && onClick(e);
    };

    startRipple = e => {
        !this.props.disableTouchRipple && this.refs.touchRipple.addRipple(e);
    };

    endRipple = () => {
        !this.props.disableTouchRipple && this.refs.touchRipple.removeRipple();
    };

    render() {

        const {

                children, className, style, theme, isRounded, isCircular, disableTouchRipple,
                iconCls, rightIconCls, type, value, disabled, readOnly, isLoading, rippleDisplayCenter,
                tip, tipPosition, renderer,

                ...restProps

            } = this.props,

            buttonClassName = classNames('base-button', {
                [`theme-${theme}`]: theme,
                'button-circular': isCircular,
                'button-rounded': isRounded,
                [className]: className
            }),

            loadingIconPosition = (rightIconCls && !iconCls) ? 'right' : 'left';

        return (
            <TipProvider text={tip}
                         position={tipPosition}>

                <button {...restProps}
                        className={buttonClassName}
                        style={style}
                        type={type}
                        disabled={disabled || isLoading}
                        readOnly={readOnly}
                        onClick={this.clickHandler}>

                    {
                        isLoading && loadingIconPosition === 'left' ?
                            <CircularLoading className="button-icon button-icon-left button-loading-icon"
                                             size="small"/>
                            :
                            (
                                iconCls ?
                                    <i className={`button-icon button-icon-left ${iconCls}`}
                                       aria-hidden="true">
                                    :
                                    null
                            )
                    }

                    {
                        renderer && typeof renderer === 'function' ?
                            renderer(this.props)
                            :
                            (
                                value ?
                                    {value}
                                    :
                                    null
                            )
                    }

                    {
                        isLoading && loadingIconPosition === 'right' ?
                            <CircularLoading className="button-icon button-icon-right button-loading-icon"
                                             size="small"/>
                            :
                            (
                                rightIconCls ?
                                    <i className={`button-icon button-icon-right ${rightIconCls}`}
                                       aria-hidden="true">
                                    :
                                    null
                            )
                    }

                    {children}

                    {
                        disableTouchRipple ?
                            null
                            :
                            <TouchRipple ref="touchRipple"
                                         className={disabled || isLoading ? 'hidden' : ''}
                                         displayCenter={rippleDisplayCenter}/>
                    }

                </button>

            </TipProvider>
        );

    }
}

BaseButton.propTypes = {

    className: PropTypes.string,
    style: PropTypes.object,
    theme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    isRounded: PropTypes.bool,
    isCircular: PropTypes.bool,

    value: PropTypes.any,
    type: PropTypes.string,
    disabled: PropTypes.bool,
    readOnly: PropTypes.bool,
    isLoading: PropTypes.bool,
    disableTouchRipple: PropTypes.bool,

    iconCls: PropTypes.string,
    rightIconCls: PropTypes.string,

    tip: PropTypes.string,
    tipPosition: PropTypes.oneOf(Util.enumerateValue(Position)),

    rippleDisplayCenter: PropTypes.bool,

    renderer: PropTypes.func,
    onClick: PropTypes.func

};

BaseButton.defaultProps = {

    theme: Theme.DEFAULT,

    isRounded: false,
    isCircular: false,

    disabled: false,
    readOnly: false,
    type: 'button',
    isLoading: false,
    disableTouchRipple: false,

    rippleDisplayCenter: false,

    tipPosition: Position.BOTTOM

};

export default BaseButton;<commit_msg>update BaseButton<commit_after>/**
 * @file BaseButton component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';

import CircularLoading from '../CircularLoading';
import TipProvider from '../TipProvider';
import TouchRipple from '../TouchRipple';
import Theme from '../Theme';

import Util from '../_vendors/Util';
import Position from '../_statics/Position';

class BaseButton extends Component {

    static Theme = Theme;
    static TipPosition = Position;

    constructor(props, ...restArgs) {
        super(props, ...restArgs);
    }

    clickHandler = e => {
        const {disabled, isLoading, onClick} = this.props;
        !disabled && !isLoading && onClick && onClick(e);
    };

    startRipple = e => {
        !this.props.disableTouchRipple && this.refs.touchRipple.addRipple(e);
    };

    endRipple = () => {
        !this.props.disableTouchRipple && this.refs.touchRipple.removeRipple();
    };

    render() {

        const {

                children, className, style, theme, isRounded, isCircular, disableTouchRipple,
                iconCls, rightIconCls, type, value, disabled, readOnly, isLoading, rippleDisplayCenter,
                tip, tipPosition, renderer,

                ...restProps

            } = this.props,

            buttonClassName = classNames('base-button', {
                [`theme-${theme}`]: theme,
                'button-circular': isCircular,
                'button-rounded': isRounded,
                [className]: className
            }),

            loadingIconPosition = (rightIconCls && !iconCls) ? 'right' : 'left';

        return (
            <TipProvider text={tip}
                         position={tipPosition}>

                <button {...restProps}
                        className={buttonClassName}
                        style={style}
                        type={type}
                        disabled={disabled || isLoading}
                        readOnly={readOnly}
                        onClick={this.clickHandler}>

                    {
                        isLoading && loadingIconPosition === 'left' ?
                            <CircularLoading className="button-icon button-icon-left button-loading-icon"
                                             size="small"/>
                            :
                            (
                                iconCls ?
                                    <i className={`button-icon button-icon-left ${iconCls}`}
                                       aria-hidden="true">
                                    :
                                    null
                            )
                    }

                    {
                        renderer && typeof renderer === 'function' ?
                            renderer(this.props)
                            :
                            (
                                value ?
                                    {value}
                                    :
                                    null
                            )
                    }

                    {
                        isLoading && loadingIconPosition === 'right' ?
                            <CircularLoading className="button-icon button-icon-right button-loading-icon"
                                             size="small"/>
                            :
                            (
                                rightIconCls ?
                                    <i className={`button-icon button-icon-right ${rightIconCls}`}
                                       aria-hidden="true">
                                    :
                                    null
                            )
                    }

                    {children}

                    {
                        disableTouchRipple ?
                            null
                            :
                            <TouchRipple ref="touchRipple"
                                         className={disabled || isLoading ? 'hidden' : ''}
                                         displayCenter={rippleDisplayCenter}/>
                    }

                </button>

            </TipProvider>
        );

    }
}

BaseButton.propTypes = {

    className: PropTypes.string,
    style: PropTypes.object,
    theme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    isRounded: PropTypes.bool,
    isCircular: PropTypes.bool,

    value: PropTypes.any,
    type: PropTypes.string,
    disabled: PropTypes.bool,
    readOnly: PropTypes.bool,
    isLoading: PropTypes.bool,
    disableTouchRipple: PropTypes.bool,

    iconCls: PropTypes.string,
    rightIconCls: PropTypes.string,

    tip: PropTypes.string,
    tipPosition: PropTypes.oneOf(Util.enumerateValue(Position)),

    rippleDisplayCenter: PropTypes.bool,

    renderer: PropTypes.func,
    onClick: PropTypes.func

};

BaseButton.defaultProps = {

    theme: Theme.DEFAULT,

    isRounded: false,
    isCircular: false,

    disabled: false,
    readOnly: false,
    type: 'button',
    isLoading: false,
    disableTouchRipple: false,

    rippleDisplayCenter: false,

    tipPosition: Position.BOTTOM

};

export default BaseButton;<|endoftext|>


<commit_before>var DateUtil = require('dateutil');

function Programme(programme) {

    var self = this;

    this.getCurrentTargetTemperature = function(date) {
        if(!self.isHeatingEnabled()) {
            return programme.frostProtectTemp;
        }
        return getOverriddenTemperature(date) || getProgrammeTemperature(date);
    }

    this.isHeatingEnabled = function() {
        return programme.heatingOn;
    }

    this.isInComfortMode = function(date) {
        if(self.inOverridePeriod(date)) {
            return programme.override.comfortState;
        }
        else {
            return inAnyComfortPeriodForDate(date);
        }
    }

    this.inOverridePeriod = function(date) {
        return programme.override && programme.override.until && beforeOverrideEnd(date, programme.override.until);
    }

    function getOverriddenTemperature(date) {
        if(self.inOverridePeriod(date)) {
            return getTemperatureForComfortState(programme.override.comfortState);
        }
        return NaN;
    }

    function beforeOverrideEnd(date, overrideEndTimeMs) {
        return date.getTime() < overrideEndTimeMs;
    }

    function getProgrammeTemperature(date) {
        return getTemperatureForComfortState(inAnyComfortPeriodForDate(date));
    }

    function getTemperatureForComfortState(comfortState) {
        return comfortState ? programme.comfortTemp : programme.setbackTemp;
    }

    function laterThanComfortPeriodStart(date, period) {
        var start = DateUtil.getDateFromTimeStr(date, period.startTime);
        return DateUtil.isFirstDateBeforeSecondDate(start, date);
    }

    function earlierThanComfortPeriodEnd(date, period) {
        var end = DateUtil.getDateFromTimeStr(date, period.endTime);
        return DateUtil.isFirstDateBeforeSecondDate(date, end);
    }

    function inComfortPeriod(date, comfortPeriod) {
        return laterThanComfortPeriodStart(date, comfortPeriod) && earlierThanComfortPeriodEnd(date, comfortPeriod);
    }

    function inAnyComfortPeriodForDate(date) {
        var periodsForToday = programme.schedule[DateUtil.getDayOfWeek(date)].comfortPeriods;
        for(var i = 0; i < periodsForToday.length; ++i) {
            if(inComfortPeriod(date, periodsForToday[i])) {
                return true;
            }
        }
        return false;
    }
}

module.exports = {
    Programme : Programme
}
<commit_msg>changed method names<commit_after>var DateUtil = require('dateutil');

function Programme(programme) {

    var self = this;

    this.getCurrentTargetTemperature = function(date) {
        if(!self.isHeatingEnabled()) {
            return programme.frostProtectTemp;
        }
        return getOverriddenTemperature(date) || getProgrammeTemperature(date);
    }

    this.isHeatingEnabled = function() {
        return programme.heatingOn;
    }

    this.isInComfortMode = function(date) {
        if(self.isInOverridePeriod(date)) {
            return programme.override.comfortState;
        }
        else {
            return isInAnyComfortPeriodForDate(date);
        }
    }

    this.isInOverridePeriod = function(date) {
        return programme.override && programme.override.until && beforeOverrideEnd(date, programme.override.until);
    }

    function getOverriddenTemperature(date) {
        if(self.isInOverridePeriod(date)) {
            return getTemperatureForComfortState(programme.override.comfortState);
        }
        return NaN;
    }

    function beforeOverrideEnd(date, overrideEndTimeMs) {
        return date.getTime() < overrideEndTimeMs;
    }

    function getProgrammeTemperature(date) {
        return getTemperatureForComfortState(isInAnyComfortPeriodForDate(date));
    }

    function getTemperatureForComfortState(comfortState) {
        return comfortState ? programme.comfortTemp : programme.setbackTemp;
    }

    function laterThanComfortPeriodStart(date, period) {
        var start = DateUtil.getDateFromTimeStr(date, period.startTime);
        return DateUtil.isFirstDateBeforeSecondDate(start, date);
    }

    function earlierThanComfortPeriodEnd(date, period) {
        var end = DateUtil.getDateFromTimeStr(date, period.endTime);
        return DateUtil.isFirstDateBeforeSecondDate(date, end);
    }

    function isInComfortPeriod(date, comfortPeriod) {
        return laterThanComfortPeriodStart(date, comfortPeriod) && earlierThanComfortPeriodEnd(date, comfortPeriod);
    }

    function isInAnyComfortPeriodForDate(date) {
        var periodsForToday = programme.schedule[DateUtil.getDayOfWeek(date)].comfortPeriods;
        for(var i = 0; i < periodsForToday.length; ++i) {
            if(isInComfortPeriod(date, periodsForToday[i])) {
                return true;
            }
        }
        return false;
    }
}

module.exports = {
    Programme : Programme
}
<|endoftext|>


<commit_before>// TODO:
// 1. Enable mirror option
// 2. Improve options handling
// 3. Error handling

import Vue from 'vue';

const WebcamComponent = Vue.extend({
  render: function (h) {
    return h('video', {
      ref: 'video',
      attrs: {
        width: this.width,
        height: this.height,
        src: this.src,
        autoplay: this.autoplay
      }
    });
  },
  props: {
    autoplay: {
      type: Boolean,
      default: true
    },
    width: {
      type: Number,
      default: 400
    },
    height: {
      type: Number,
      default: 300
    },
    mirror: {
      type: Boolean,
      default: true
    },
    screenshotFormat: {
      type: String,
      default: 'image/jpeg'
    }
  },
  data () {
    return {
      video: '',
      src: '',
      stream: '',
      hasUserMedia: false,
      styleObject: {
        transform: 'scale(-1, 1)',
        filter: 'FlipH'
      }
    };
  },
  methods: {
    getPhoto () {
      if (!this.hasUserMedia) return null;

      const canvas = this.getCanvas();
      return canvas.toDataURL(this.screenshotFormat);
    },
    getCanvas () {
      if (!this.hasUserMedia) return null;

      const video = this.$refs.video;
      if (!this.ctx) {
        const canvas = document.createElement('canvas');
        canvas.height = video.clientHeight;
        canvas.width = video.clientWidth;
        this.canvas = canvas;

        this.ctx = canvas.getContext('2d');

          /*if (this.mirror) {
           const context = canvas.getContext('2d');
           context.translate(canvas.width, 0);
           context.scale(-1, 1);
           this.ctx = context;
           } else {
           this.ctx = canvas.getContext('2d');
           }*/
      }

      const { ctx, canvas } = this;
      ctx.drawImage(video, 0, 0, canvas.width, canvas.height);

      return canvas;
    }

  },
  mounted: function () {
    this.video = this.$refs.video;
    navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia || navigator.oGetUserMedia;

    if (navigator.getUserMedia) {
      navigator.getUserMedia({ video: true }, (stream) => {
        this.src = window.URL.createObjectURL(stream);
      this.stream = stream;
      this.hasUserMedia = true;
    }, (error) => {
        console.log(error);
      });
    }
  },
  beforeDestroy: function () {
    this.video.pause();
    this.src = '';
    this.stream.getTracks()[0].stop();
  },
  destroyed: function () {
    console.log('Destroyed');
  }
});
const VueWebcam = Vue.component('vue-webcam', WebcamComponent);
export default VueWebcam;<commit_msg>Bug fix<commit_after>// TODO:
// 1. Enable mirror option
// 2. Improve options handling
// 3. Error handling

import Vue from 'vue';

const WebcamComponent = Vue.extend({
  render: function (h) {
    return h('video', {
      ref: 'video',
      attrs: {
        width: this.width,
        height: this.height,
        src: this.src,
        autoplay: this.autoplay
      }
    });
  },

  props: {
    autoplay: {
      type: Boolean,
      default: true
    },
    width: {
      type: Number,
      default: 400
    },
    height: {
      type: Number,
      default: 300
    },
    mirror: {
      type: Boolean,
      default: true
    },
    screenshotFormat: {
      type: String,
      default: 'image/jpeg'
    }
  },

  data () {
    return {
      video: '',
      src: '',
      stream: '',
      hasUserMedia: false,
      styleObject: {
        transform: 'scale(-1, 1)',
        filter: 'FlipH'
      }
    };
  },

  methods: {
    getPhoto () {
      if (!this.hasUserMedia) return null;

      const canvas = this.getCanvas();
      return canvas.toDataURL(this.screenshotFormat);
    },
    getCanvas () {
      if (!this.hasUserMedia) return null;

      const video = this.$refs.video;
      if (!this.ctx) {
        const canvas = document.createElement('canvas');
        canvas.height = video.clientHeight;
        canvas.width = video.clientWidth;
        this.canvas = canvas;

        this.ctx = canvas.getContext('2d');

          /*if (this.mirror) {
           const context = canvas.getContext('2d');
           context.translate(canvas.width, 0);
           context.scale(-1, 1);
           this.ctx = context;
           } else {
           this.ctx = canvas.getContext('2d');
           }*/
      }

      const { ctx, canvas } = this;
      ctx.drawImage(video, 0, 0, canvas.width, canvas.height);

      return canvas;
    }
  },

  mounted: function () {
    this.video = this.$refs.video;
    navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia || navigator.oGetUserMedia;

    if (navigator.getUserMedia) {
      navigator.getUserMedia({ video: true }, (stream) => {
        this.src = window.URL.createObjectURL(stream);
      this.stream = stream;
      this.hasUserMedia = true;
    }, (error) => {
        console.log(error);
      });
    }
  },

  beforeDestroy: function () {
    this.video.pause();
    this.src = '';
    this.stream.getTracks()[0].stop();
  },

  destroyed: function () {
    console.log('Destroyed');
  }
});

const VueWebcam = Vue.component('vue-webcam', WebcamComponent);
export default VueWebcam;
<|endoftext|>