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

'use strict';

/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );

// MAIN //

/**
* Top-level namespace.
*
* @namespace ns
*/
var ns = {};

/**
* @name dists
* @memberof ns
* @readonly
* @type {Namespace}
* @see {@link module:@stdlib/stats/base/dists}
*/
setReadOnly( ns, 'dists', require( '@stdlib/stats/base/dists' ) );

/**
* @name dmax
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dmax}
*/
setReadOnly( ns, 'dmax', require( '@stdlib/stats/base/dmax' ) );

/**
* @name dmaxabs
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dmaxabs}
*/
setReadOnly( ns, 'dmaxabs', require( '@stdlib/stats/base/dmaxabs' ) );

/**
* @name dmean
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dmean}
*/
setReadOnly( ns, 'dmean', require( '@stdlib/stats/base/dmean' ) );

/**
* @name dmeanors
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dmeanors}
*/
setReadOnly( ns, 'dmeanors', require( '@stdlib/stats/base/dmeanors' ) );

/**
* @name dmeanpw
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dmeanpw}
*/
setReadOnly( ns, 'dmeanpw', require( '@stdlib/stats/base/dmeanpw' ) );

/**
* @name dmeanwd
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dmeanwd}
*/
setReadOnly( ns, 'dmeanwd', require( '@stdlib/stats/base/dmeanwd' ) );

/**
* @name dmin
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dmin}
*/
setReadOnly( ns, 'dmin', require( '@stdlib/stats/base/dmin' ) );

/**
* @name dminabs
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dminabs}
*/
setReadOnly( ns, 'dminabs', require( '@stdlib/stats/base/dminabs' ) );

/**
* @name dnanmax
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dnanmax}
*/
setReadOnly( ns, 'dnanmax', require( '@stdlib/stats/base/dnanmax' ) );

/**
* @name dnanmaxabs
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dnanmaxabs}
*/
setReadOnly( ns, 'dnanmaxabs', require( '@stdlib/stats/base/dnanmaxabs' ) );

/**
* @name dnanmean
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dnanmean}
*/
setReadOnly( ns, 'dnanmean', require( '@stdlib/stats/base/dnanmean' ) );

/**
* @name dnanmeanwd
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dnanmeanwd}
*/
setReadOnly( ns, 'dnanmeanwd', require( '@stdlib/stats/base/dnanmeanwd' ) );

/**
* @name dnanmin
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dnanmin}
*/
setReadOnly( ns, 'dnanmin', require( '@stdlib/stats/base/dnanmin' ) );

/**
* @name dnanminabs
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dnanminabs}
*/
setReadOnly( ns, 'dnanminabs', require( '@stdlib/stats/base/dnanminabs' ) );

/**
* @name dnanrange
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dnanrange}
*/
setReadOnly( ns, 'dnanrange', require( '@stdlib/stats/base/dnanrange' ) );

/**
* @name drange
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/drange}
*/
setReadOnly( ns, 'drange', require( '@stdlib/stats/base/drange' ) );

/**
* @name dsmean
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dsmean}
*/
setReadOnly( ns, 'dsmean', require( '@stdlib/stats/base/dsmean' ) );

/**
* @name dsnanmean
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dsnanmean}
*/
setReadOnly( ns, 'dsnanmean', require( '@stdlib/stats/base/dsnanmean' ) );

/**
* @name max
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/max}
*/
setReadOnly( ns, 'max', require( '@stdlib/stats/base/max' ) );

/**
* @name maxabs
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/maxabs}
*/
setReadOnly( ns, 'maxabs', require( '@stdlib/stats/base/maxabs' ) );

/**
* @name mean
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/mean}
*/
setReadOnly( ns, 'mean', require( '@stdlib/stats/base/mean' ) );

/**
* @name min
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/min}
*/
setReadOnly( ns, 'min', require( '@stdlib/stats/base/min' ) );

/**
* @name minabs
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/minabs}
*/
setReadOnly( ns, 'minabs', require( '@stdlib/stats/base/minabs' ) );

/**
* @name nanmax
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/nanmax}
*/
setReadOnly( ns, 'nanmax', require( '@stdlib/stats/base/nanmax' ) );

/**
* @name nanmaxabs
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/nanmaxabs}
*/
setReadOnly( ns, 'nanmaxabs', require( '@stdlib/stats/base/nanmaxabs' ) );

/**
* @name nanmean
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/nanmean}
*/
setReadOnly( ns, 'nanmean', require( '@stdlib/stats/base/nanmean' ) );

/**
* @name nanmin
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/nanmin}
*/
setReadOnly( ns, 'nanmin', require( '@stdlib/stats/base/nanmin' ) );

/**
* @name nanminabs
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/nanminabs}
*/
setReadOnly( ns, 'nanminabs', require( '@stdlib/stats/base/nanminabs' ) );

/**
* @name nanrange
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/nanrange}
*/
setReadOnly( ns, 'nanrange', require( '@stdlib/stats/base/nanrange' ) );

/**
* @name range
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/range}
*/
setReadOnly( ns, 'range', require( '@stdlib/stats/base/range' ) );

/**
* @name sdsmean
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/sdsmean}
*/
setReadOnly( ns, 'sdsmean', require( '@stdlib/stats/base/sdsmean' ) );

/**
* @name sdsnanmean
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/sdsnanmean}
*/
setReadOnly( ns, 'sdsnanmean', require( '@stdlib/stats/base/sdsnanmean' ) );

/**
* @name smax
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/smax}
*/
setReadOnly( ns, 'smax', require( '@stdlib/stats/base/smax' ) );

/**
* @name smaxabs
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/smaxabs}
*/
setReadOnly( ns, 'smaxabs', require( '@stdlib/stats/base/smaxabs' ) );

/**
* @name smean
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/smean}
*/
setReadOnly( ns, 'smean', require( '@stdlib/stats/base/smean' ) );

/**
* @name smin
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/smin}
*/
setReadOnly( ns, 'smin', require( '@stdlib/stats/base/smin' ) );

/**
* @name sminabs
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/sminabs}
*/
setReadOnly( ns, 'sminabs', require( '@stdlib/stats/base/sminabs' ) );

/**
* @name snanmax
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/snanmax}
*/
setReadOnly( ns, 'snanmax', require( '@stdlib/stats/base/snanmax' ) );

/**
* @name snanmaxabs
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/snanmaxabs}
*/
setReadOnly( ns, 'snanmaxabs', require( '@stdlib/stats/base/snanmaxabs' ) );

/**
* @name snanmean
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/snanmean}
*/
setReadOnly( ns, 'snanmean', require( '@stdlib/stats/base/snanmean' ) );

/**
* @name snanmin
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/snanmin}
*/
setReadOnly( ns, 'snanmin', require( '@stdlib/stats/base/snanmin' ) );

/**
* @name snanminabs
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/snanminabs}
*/
setReadOnly( ns, 'snanminabs', require( '@stdlib/stats/base/snanminabs' ) );

/**
* @name snanrange
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/snanrange}
*/
setReadOnly( ns, 'snanrange', require( '@stdlib/stats/base/snanrange' ) );

/**
* @name srange
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/srange}
*/
setReadOnly( ns, 'srange', require( '@stdlib/stats/base/srange' ) );

// EXPORTS //

module.exports = ns;
<commit_msg>Update namespace<commit_after>/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*    http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );

// MAIN //

/**
* Top-level namespace.
*
* @namespace ns
*/
var ns = {};

/**
* @name dists
* @memberof ns
* @readonly
* @type {Namespace}
* @see {@link module:@stdlib/stats/base/dists}
*/
setReadOnly( ns, 'dists', require( '@stdlib/stats/base/dists' ) );

/**
* @name dmax
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dmax}
*/
setReadOnly( ns, 'dmax', require( '@stdlib/stats/base/dmax' ) );

/**
* @name dmaxabs
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dmaxabs}
*/
setReadOnly( ns, 'dmaxabs', require( '@stdlib/stats/base/dmaxabs' ) );

/**
* @name dmean
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dmean}
*/
setReadOnly( ns, 'dmean', require( '@stdlib/stats/base/dmean' ) );

/**
* @name dmeanors
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dmeanors}
*/
setReadOnly( ns, 'dmeanors', require( '@stdlib/stats/base/dmeanors' ) );

/**
* @name dmeanpw
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dmeanpw}
*/
setReadOnly( ns, 'dmeanpw', require( '@stdlib/stats/base/dmeanpw' ) );

/**
* @name dmeanwd
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dmeanwd}
*/
setReadOnly( ns, 'dmeanwd', require( '@stdlib/stats/base/dmeanwd' ) );

/**
* @name dmin
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dmin}
*/
setReadOnly( ns, 'dmin', require( '@stdlib/stats/base/dmin' ) );

/**
* @name dminabs
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dminabs}
*/
setReadOnly( ns, 'dminabs', require( '@stdlib/stats/base/dminabs' ) );

/**
* @name dnanmax
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dnanmax}
*/
setReadOnly( ns, 'dnanmax', require( '@stdlib/stats/base/dnanmax' ) );

/**
* @name dnanmaxabs
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dnanmaxabs}
*/
setReadOnly( ns, 'dnanmaxabs', require( '@stdlib/stats/base/dnanmaxabs' ) );

/**
* @name dnanmean
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dnanmean}
*/
setReadOnly( ns, 'dnanmean', require( '@stdlib/stats/base/dnanmean' ) );

/**
* @name dnanmeanors
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dnanmeanors}
*/
setReadOnly( ns, 'dnanmeanors', require( '@stdlib/stats/base/dnanmeanors' ) );

/**
* @name dnanmeanwd
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dnanmeanwd}
*/
setReadOnly( ns, 'dnanmeanwd', require( '@stdlib/stats/base/dnanmeanwd' ) );

/**
* @name dnanmin
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dnanmin}
*/
setReadOnly( ns, 'dnanmin', require( '@stdlib/stats/base/dnanmin' ) );

/**
* @name dnanminabs
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dnanminabs}
*/
setReadOnly( ns, 'dnanminabs', require( '@stdlib/stats/base/dnanminabs' ) );

/**
* @name dnanrange
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dnanrange}
*/
setReadOnly( ns, 'dnanrange', require( '@stdlib/stats/base/dnanrange' ) );

/**
* @name drange
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/drange}
*/
setReadOnly( ns, 'drange', require( '@stdlib/stats/base/drange' ) );

/**
* @name dsmean
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dsmean}
*/
setReadOnly( ns, 'dsmean', require( '@stdlib/stats/base/dsmean' ) );

/**
* @name dsnanmean
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dsnanmean}
*/
setReadOnly( ns, 'dsnanmean', require( '@stdlib/stats/base/dsnanmean' ) );

/**
* @name max
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/max}
*/
setReadOnly( ns, 'max', require( '@stdlib/stats/base/max' ) );

/**
* @name maxabs
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/maxabs}
*/
setReadOnly( ns, 'maxabs', require( '@stdlib/stats/base/maxabs' ) );

/**
* @name mean
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/mean}
*/
setReadOnly( ns, 'mean', require( '@stdlib/stats/base/mean' ) );

/**
* @name min
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/min}
*/
setReadOnly( ns, 'min', require( '@stdlib/stats/base/min' ) );

/**
* @name minabs
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/minabs}
*/
setReadOnly( ns, 'minabs', require( '@stdlib/stats/base/minabs' ) );

/**
* @name nanmax
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/nanmax}
*/
setReadOnly( ns, 'nanmax', require( '@stdlib/stats/base/nanmax' ) );

/**
* @name nanmaxabs
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/nanmaxabs}
*/
setReadOnly( ns, 'nanmaxabs', require( '@stdlib/stats/base/nanmaxabs' ) );

/**
* @name nanmean
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/nanmean}
*/
setReadOnly( ns, 'nanmean', require( '@stdlib/stats/base/nanmean' ) );

/**
* @name nanmin
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/nanmin}
*/
setReadOnly( ns, 'nanmin', require( '@stdlib/stats/base/nanmin' ) );

/**
* @name nanminabs
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/nanminabs}
*/
setReadOnly( ns, 'nanminabs', require( '@stdlib/stats/base/nanminabs' ) );

/**
* @name nanrange
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/nanrange}
*/
setReadOnly( ns, 'nanrange', require( '@stdlib/stats/base/nanrange' ) );

/**
* @name range
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/range}
*/
setReadOnly( ns, 'range', require( '@stdlib/stats/base/range' ) );

/**
* @name sdsmean
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/sdsmean}
*/
setReadOnly( ns, 'sdsmean', require( '@stdlib/stats/base/sdsmean' ) );

/**
* @name sdsnanmean
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/sdsnanmean}
*/
setReadOnly( ns, 'sdsnanmean', require( '@stdlib/stats/base/sdsnanmean' ) );

/**
* @name smax
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/smax}
*/
setReadOnly( ns, 'smax', require( '@stdlib/stats/base/smax' ) );

/**
* @name smaxabs
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/smaxabs}
*/
setReadOnly( ns, 'smaxabs', require( '@stdlib/stats/base/smaxabs' ) );

/**
* @name smean
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/smean}
*/
setReadOnly( ns, 'smean', require( '@stdlib/stats/base/smean' ) );

/**
* @name smin
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/smin}
*/
setReadOnly( ns, 'smin', require( '@stdlib/stats/base/smin' ) );

/**
* @name sminabs
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/sminabs}
*/
setReadOnly( ns, 'sminabs', require( '@stdlib/stats/base/sminabs' ) );

/**
* @name snanmax
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/snanmax}
*/
setReadOnly( ns, 'snanmax', require( '@stdlib/stats/base/snanmax' ) );

/**
* @name snanmaxabs
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/snanmaxabs}
*/
setReadOnly( ns, 'snanmaxabs', require( '@stdlib/stats/base/snanmaxabs' ) );

/**
* @name snanmean
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/snanmean}
*/
setReadOnly( ns, 'snanmean', require( '@stdlib/stats/base/snanmean' ) );

/**
* @name snanmin
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/snanmin}
*/
setReadOnly( ns, 'snanmin', require( '@stdlib/stats/base/snanmin' ) );

/**
* @name snanminabs
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/snanminabs}
*/
setReadOnly( ns, 'snanminabs', require( '@stdlib/stats/base/snanminabs' ) );

/**
* @name snanrange
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/snanrange}
*/
setReadOnly( ns, 'snanrange', require( '@stdlib/stats/base/snanrange' ) );

/**
* @name srange
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/srange}
*/
setReadOnly( ns, 'srange', require( '@stdlib/stats/base/srange' ) );

// EXPORTS //

module.exports = ns;
<|endoftext|>


<commit_before>const sendEvent = require("../../browser-send-event.js");
const page = require("./page").page;
const { AbstractShot } = require("../../../shared/shot");

const FIVE_SECONDS = 5 * 1000;

let model;

let firstRun = true;

exports.launch = function(m) {
  if (m.hasDeviceId) {
    if (m.shots) {
      m.shots = m.shots.map((shot) => new AbstractShot(m.backend, shot.id, shot.json));
    }
    let match = /[?&]q=([^&]{1,4000})/.exec(location.href);
    if (match) {
      m.defaultSearch = decodeURIComponent(match[1]);
    }
    model = m;
    render();
    if (firstRun && m.shots === null) {
      // The actual shot data hasn't been loaded yet, so we'll immediately request it:
      refreshModel();
    }
    firstRun = false;
    return;
  }
  if (window.wantsauth) {
    if (window.wantsauth.getAuthData() && location.search.indexOf("reloaded") === -1) {
      location.search = "reloaded";
      return;
    }
    let authTimeout = setTimeout(() => {
      // eslint-disable-next-line no-global-assign
      location = location.origin;
    }, FIVE_SECONDS);
    window.wantsauth.addAuthDataListener((data) => {
      if (location.search.indexOf("reloaded") > -1) {
        return;
      }
      clearTimeout(authTimeout);
      location.search = "reloaded";
    });
  }
};

function render() {
  page.render(model);
}

exports.onChangeSearch = function(query) {
  model.defaultSearch = query;
  let url = `/shots?q=${encodeURIComponent(query)}`;
  if (!query) {
    url = "/shots";
  }
  window.history.pushState(null, "", url);
  refreshModel();
};

// FIXME: copied from shot/controller.js
exports.deleteShot = function(shot) {
  let url = model.backend + "/api/delete-shot";
  let req = new XMLHttpRequest();
  req.open("POST", url);
  req.setRequestHeader("content-type", "application/x-www-form-urlencoded");
  req.onload = function() {
    if (req.status >= 300) {
      // FIXME: a lame way to do an error message
      let errorMessage = document.getElementById("shotIndexPageErrorDeletingShot").textContent;
      errorMessage = errorMessage.replace('{status}', req.status);
      errorMessage = errorMessage.replace('{statusText}', req.statusText);
      window.alert(errorMessage);
      window.Raven.captureException(new Error(`Error calling /api/delete-shot: ${req.status} ${req.statusText}`));
    } else {
      refreshModel();
    }
  };
  req.send(`id=${encodeURIComponent(shot.id)}&_csrf=${encodeURIComponent(model.csrfToken)}`);
};

window.addEventListener("popstate", () => {
  let match = /[?&]q=([^&]{0,4000})/.exec(location.search);
  if (!match) {
    model.defaultSearch = "";
  } else {
    model.defaultSearch = decodeURIComponent(match[1]);
  }
  // FIXME: this isn't the "right" way to research the search box, but given that
  // it's an uncontrolled field it doesn't seem to be reset in this case otherwise:
  let el = document.getElementById("search");
  if (el) {
    el.value = model.defaultSearch;
  }
  refreshModel();
});

function refreshModel() {
  let req = new XMLHttpRequest();
  let url = "/shots?withdata=true&data=json";
  if (model.defaultSearch) {
    url += "&q=" + encodeURIComponent(model.defaultSearch);
  }
  req.open("GET", url);
  req.onload = function() {
    document.body.classList.remove("search-results-loading");
    if (req.status != 200) {
      console.warn("Error refreshing:", req.status, req);
      return;
    }
    let data = JSON.parse(req.responseText);
    if (data.shots && !data.shots.length) {
      sendEvent("no-search-results");
    }
    exports.launch(data);
  };
  req.send();
}

document.addEventListener("contextmenu", (event) => {
  let place = "background";
  let node = event.target;
  while (node) {
    if (node.nodeType != document.ELEMENT_NODE) {
      node = node.parentNode;
      continue;
    }
    if (node.classList.contains("shot")) {
      place = "shot-tile";
      break;
    }
    if (node.tagName == "FORM") {
      place = "search";
      break;
    }
    if (node.classList.contains("header")) {
      place = "header";
      break;
    }
    node = node.parentNode;
  }
  sendEvent("contextmenu", place);
});

window.controller = exports;
<commit_msg>Fix #3493, send unauth'd /shots to /#tour<commit_after>const sendEvent = require("../../browser-send-event.js");
const page = require("./page").page;
const { AbstractShot } = require("../../../shared/shot");

const FIVE_SECONDS = 5 * 1000;

let model;

let firstRun = true;

exports.launch = function(m) {
  if (m.hasDeviceId) {
    if (m.shots) {
      m.shots = m.shots.map((shot) => new AbstractShot(m.backend, shot.id, shot.json));
    }
    let match = /[?&]q=([^&]{1,4000})/.exec(location.href);
    if (match) {
      m.defaultSearch = decodeURIComponent(match[1]);
    }
    model = m;
    render();
    if (firstRun && m.shots === null) {
      // The actual shot data hasn't been loaded yet, so we'll immediately request it:
      refreshModel();
    }
    firstRun = false;
    return;
  }
  if (window.wantsauth) {
    if (window.wantsauth.getAuthData() && location.search.indexOf("reloaded") === -1) {
      location.search = "reloaded";
      return;
    }
    let authTimeout = setTimeout(() => {
      // eslint-disable-next-line no-global-assign
      location = location.origin + "/#tour";
    }, FIVE_SECONDS);
    window.wantsauth.addAuthDataListener((data) => {
      if (location.search.indexOf("reloaded") > -1) {
        return;
      }
      clearTimeout(authTimeout);
      location.search = "reloaded";
    });
  }
};

function render() {
  page.render(model);
}

exports.onChangeSearch = function(query) {
  model.defaultSearch = query;
  let url = `/shots?q=${encodeURIComponent(query)}`;
  if (!query) {
    url = "/shots";
  }
  window.history.pushState(null, "", url);
  refreshModel();
};

// FIXME: copied from shot/controller.js
exports.deleteShot = function(shot) {
  let url = model.backend + "/api/delete-shot";
  let req = new XMLHttpRequest();
  req.open("POST", url);
  req.setRequestHeader("content-type", "application/x-www-form-urlencoded");
  req.onload = function() {
    if (req.status >= 300) {
      // FIXME: a lame way to do an error message
      let errorMessage = document.getElementById("shotIndexPageErrorDeletingShot").textContent;
      errorMessage = errorMessage.replace('{status}', req.status);
      errorMessage = errorMessage.replace('{statusText}', req.statusText);
      window.alert(errorMessage);
      window.Raven.captureException(new Error(`Error calling /api/delete-shot: ${req.status} ${req.statusText}`));
    } else {
      refreshModel();
    }
  };
  req.send(`id=${encodeURIComponent(shot.id)}&_csrf=${encodeURIComponent(model.csrfToken)}`);
};

window.addEventListener("popstate", () => {
  let match = /[?&]q=([^&]{0,4000})/.exec(location.search);
  if (!match) {
    model.defaultSearch = "";
  } else {
    model.defaultSearch = decodeURIComponent(match[1]);
  }
  // FIXME: this isn't the "right" way to research the search box, but given that
  // it's an uncontrolled field it doesn't seem to be reset in this case otherwise:
  let el = document.getElementById("search");
  if (el) {
    el.value = model.defaultSearch;
  }
  refreshModel();
});

function refreshModel() {
  let req = new XMLHttpRequest();
  let url = "/shots?withdata=true&data=json";
  if (model.defaultSearch) {
    url += "&q=" + encodeURIComponent(model.defaultSearch);
  }
  req.open("GET", url);
  req.onload = function() {
    document.body.classList.remove("search-results-loading");
    if (req.status != 200) {
      console.warn("Error refreshing:", req.status, req);
      return;
    }
    let data = JSON.parse(req.responseText);
    if (data.shots && !data.shots.length) {
      sendEvent("no-search-results");
    }
    exports.launch(data);
  };
  req.send();
}

document.addEventListener("contextmenu", (event) => {
  let place = "background";
  let node = event.target;
  while (node) {
    if (node.nodeType != document.ELEMENT_NODE) {
      node = node.parentNode;
      continue;
    }
    if (node.classList.contains("shot")) {
      place = "shot-tile";
      break;
    }
    if (node.tagName == "FORM") {
      place = "search";
      break;
    }
    if (node.classList.contains("header")) {
      place = "header";
      break;
    }
    node = node.parentNode;
  }
  sendEvent("contextmenu", place);
});

window.controller = exports;
<|endoftext|>


<commit_before>'use strict'

var React = require('react')
var ReactBootstrap = require('react-bootstrap')
var Alert = ReactBootstrap.Alert
var TagSelect = require('./tagSelect')
var TemplateSelect = require('./templateSelect')
var $ = require('jquery')

var AssessmentCreationForm = React.createClass({
  propTypes: {
    initialTags: React.PropTypes.array,
    team: React.PropTypes.object
  },
  getInitialState: function () {
    return {
      template: '',
      tags: '',
      formError: ''
    }
  },
  componentDidMount: function () {
    this.setState({
      tags: this.props.initialTags
    })
  },
  changeHandlerTemplate: function (val) {
    this.setState({
      template: val.value
    })
  },
  changeHandlerTags: function (val) {
    this.setState({
      tags: val
    })
  },
  handleSubmit: function (e) {
    e.preventDefault()
    if (this.state.template && this.state.tags) {
      var template = this.state.template
      var tags = this.state.tags.map(function (value) {
        return (
          value.value
        )
      })
      var teamId = this.props.team ? this.props.team.id : ''
      this.createAssessment(template, tags, teamId)
    } else {
      var message = 'Template & tag/s required.'
      this.showError(message)
    }
  },

  showError: function (message) {
    this.setState({
      formError: message
    })
  },

  createAssessment: function (template, tags, teamId) {
    var data = {
      team: teamId,
      template: template,
      tags: tags
    }
    $.ajax({
      context: this,
      url: '/api/assessments/',
      contentType: 'application/json; charset=utf-8',
      dataType: 'json',
      data: JSON.stringify(data),
      type: 'POST',
      cache: true,
      success: function (output) {
        window.location = '/#/assessment/' + output.id + '/'
      },
      error: function (xhr, status, err) {
        var message = 'Launch failed due to unknown reason. Try again later.'
        this.showError(message)
      }
    })
  },

  render: function () {
    return (
      <form className='form-horizontal'>
        <Alert bsStyle='danger' className={this.state.formError ? '' : 'hidden'}>
          {this.state.formError}
        </Alert>

          <TemplateSelect
            label='Template'
            ref='template'
            {...this.props}
            value={this.state.template}
            onChange={this.changeHandlerTemplate}
          />

          <TagSelect
            label='Tags'
            ref='tags'
            {...this.props}
            value={this.state.tags}
            onChange={this.changeHandlerTags}
          />

          <input className='btn btn-default' type='submit' value='Launch' onClick={this.handleSubmit}/>

      </form>
    )
  }
})

module.exports = AssessmentCreationForm
<commit_msg>eliminate double rendering<commit_after>'use strict'

var React = require('react')
var ReactBootstrap = require('react-bootstrap')
var Alert = ReactBootstrap.Alert
var TagSelect = require('./tagSelect')
var TemplateSelect = require('./templateSelect')
var $ = require('jquery')

var AssessmentCreationForm = React.createClass({
  propTypes: {
    initialTags: React.PropTypes.array,
    team: React.PropTypes.object
  },
  getInitialState: function () {
    return {
      template: '',
      tags: '',
      formError: ''
    }
  },
  componentWillMount: function () {
    this.setState({
      tags: this.props.initialTags
    })
  },
  changeHandlerTemplate: function (val) {
    this.setState({
      template: val.value
    })
  },
  changeHandlerTags: function (val) {
    this.setState({
      tags: val
    })
  },
  handleSubmit: function (e) {
    e.preventDefault()
    if (this.state.template && this.state.tags) {
      var template = this.state.template
      var tags = this.state.tags.map(function (value) {
        return (
          value.value
        )
      })
      var teamId = this.props.team ? this.props.team.id : ''
      this.createAssessment(template, tags, teamId)
    } else {
      var message = 'Template & tag/s required.'
      this.showError(message)
    }
  },

  showError: function (message) {
    this.setState({
      formError: message
    })
  },

  createAssessment: function (template, tags, teamId) {
    var data = {
      team: teamId,
      template: template,
      tags: tags
    }
    $.ajax({
      context: this,
      url: '/api/assessments/',
      contentType: 'application/json; charset=utf-8',
      dataType: 'json',
      data: JSON.stringify(data),
      type: 'POST',
      cache: true,
      success: function (output) {
        window.location = '/#/assessment/' + output.id + '/'
      },
      error: function (xhr, status, err) {
        var message = 'Launch failed due to unknown reason. Try again later.'
        this.showError(message)
      }
    })
  },

  render: function () {
    return (
      <form className='form-horizontal'>
        <Alert bsStyle='danger' className={this.state.formError ? '' : 'hidden'}>
          {this.state.formError}
        </Alert>

          <TemplateSelect
            label='Template'
            ref='template'
            {...this.props}
            value={this.state.template}
            onChange={this.changeHandlerTemplate}
          />

          <TagSelect
            label='Tags'
            ref='tags'
            {...this.props}
            value={this.state.tags}
            onChange={this.changeHandlerTags}
          />

          <input className='btn btn-default' type='submit' value='Launch' onClick={this.handleSubmit}/>

      </form>
    )
  }
})

module.exports = AssessmentCreationForm
<|endoftext|>


<commit_before>(function() {
  "use strict";

  App.register('component').enter(function() {

    var template = '
<slot></slot>
';

    Vue.component('vue-transition', {
      props: {
        transitionName: {
          type: String,
          default: "v-fade-up",
      },
      template: template,
      data: function() {
        return {
          pageTransitionFinished: false
        }
      },
      ready: function() {
        var self = this;
        this.$nextTick(function() {
          self.pageTransitionFinished = true;
        });
      }
    });
  });
})();
<commit_msg>Update transition.js<commit_after>(function() {
  "use strict";

  App.register('component').enter(function() {

    var template = '
<slot></slot>
';

    Vue.component('vue-transition', {
      props: {
        transitionName: {
          type: String,
          default: "v-fade-up",
      },
      template: template,
      data: function() {
        return {
          pageTransitionFinished: false
        }
      },
      ready: function() {
        var self = this;
        this.$nextTick(function() {
          self.pageTransitionFinished = true;
        });
      }
    });
  });
})();
<|endoftext|>


<commit_before>describe("luga.data.xml", function(){

	"use strict";

	var employeesStr, employeesDoc;
	beforeEach(function(){
		employeesStr = jasmineFixtures.read("xml/employees.txt");
		employeesDoc = luga.data.xml.parseFromString(employeesStr);
	});

	it("Contains XML-related API", function(){
		expect(luga.data.xml).toBeDefined();
	});

	describe(".evaluateXPath()", function(){

		it("Evaluate an XPath expression against a given node", function(){
			expect(luga.data.xml.evaluateXPath(employeesDoc, "/employees/employee").length).toEqual(3);
		});

		it("Results are returned as an array of nodes", function(){
			var result = luga.data.xml.evaluateXPath(employeesDoc, "//employee");
			expect(luga.type(result)).toEqual("array");
		});

		it("An empty array is returned in case there is no match", function(){
			expect(luga.data.xml.evaluateXPath(employeesDoc, "/missing").length).toEqual(0);
		});

	});

	describe(".nodeToHash()", function(){

		describe("Convert an XML node into a JavaScript object", function(){

			describe("Mapping:", function(){

				it("Attributes to properties. Prefixed by '_'", function(){
					var node = document.createElement("test");
					node.setAttribute("name", "Ciccio");
					node.setAttribute("lastname", "Pasticcio");
					var obj = luga.data.xml.nodeToHash(node);
					expect(obj["_name"]).toEqual("Ciccio");
					expect(obj["_lastname"]).toEqual("Pasticcio");
				});

				it("Child nodes to properties", function(){
					// Quite an hack to get the employees Node
					var employeesDoc = luga.data.xml.parseFromString(employeesStr);
					var rootNode = luga.data.xml.evaluateXPath(employeesDoc, "//employees");

					var obj = luga.data.xml.nodeToHash(rootNode[0]);
					expect(obj["employee"].length).toEqual(3);
					expect(obj["employee"][0].firstname).toEqual("Edward");
					expect(obj["employee"][0].lastname).toEqual("Smith");
					expect(obj["employee"][0].phone).toEqual("(415) 333-0235");
					expect(obj["employee"][0].username).toEqual("esmith");
				});

			});

			describe("Return an empty object if:", function(){

				it("The given node has no attributes and no children", function(){
					var node = document.createElement("test");
					var obj = luga.data.xml.nodeToHash(node);
					expect(obj).toEqual({});
				});

			});

		});

	});

	describe(".nodeToString()", function(){

		it("Serialize a DOM Node into a string", function(){

			var xmlStr = "";
			xmlStr += "<artists>";
			xmlStr += "<player instrument=\"tenor sax\" name=\"Dexter Gordon\"/>";
			xmlStr += "<player instrument=\"tenor sax\" name=\"Sonny Rollins\"/>";
			xmlStr += "<player instrument=\"trumpet\" name=\"Thad Jones\"/>";
			xmlStr += "<player instrument=\"trumpet\" name=\"Lee Morgan\"/>";
			xmlStr += "<player instrument=\"piano\" name=\"Bill Evans\"/>";
			xmlStr += "</artists>";
			var xmlNode = luga.data.xml.parseFromString(xmlStr);

			// Need to use "toMatch" instead of "toEqual" to keep IE happy
			expect(luga.data.xml.nodeToString(xmlNode)).toMatch(xmlStr);
		});

	});

	describe(".parseFromString()", function(){

		it("Create a DOM Document out of a string", function(){
			expect(employeesDoc.getElementsByTagName("employee").length).toEqual(3);
		});

	});

});<commit_msg>Test: Equalize XML strings across browsers just for testing<commit_after>describe("luga.data.xml", function(){

	"use strict";

	var employeesStr, employeesDoc;
	beforeEach(function(){
		employeesStr = jasmineFixtures.read("xml/employees.txt");
		employeesDoc = luga.data.xml.parseFromString(employeesStr);
	});

	it("Contains XML-related API", function(){
		expect(luga.data.xml).toBeDefined();
	});

	describe(".evaluateXPath()", function(){

		it("Evaluate an XPath expression against a given node", function(){
			expect(luga.data.xml.evaluateXPath(employeesDoc, "/employees/employee").length).toEqual(3);
		});

		it("Results are returned as an array of nodes", function(){
			var result = luga.data.xml.evaluateXPath(employeesDoc, "//employee");
			expect(luga.type(result)).toEqual("array");
		});

		it("An empty array is returned in case there is no match", function(){
			expect(luga.data.xml.evaluateXPath(employeesDoc, "/missing").length).toEqual(0);
		});

	});

	describe(".nodeToHash()", function(){

		describe("Convert an XML node into a JavaScript object", function(){

			describe("Mapping:", function(){

				it("Attributes to properties. Prefixed by '_'", function(){
					var node = document.createElement("test");
					node.setAttribute("name", "Ciccio");
					node.setAttribute("lastname", "Pasticcio");
					var obj = luga.data.xml.nodeToHash(node);
					expect(obj["_name"]).toEqual("Ciccio");
					expect(obj["_lastname"]).toEqual("Pasticcio");
				});

				it("Child nodes to properties", function(){
					// Quite an hack to get the employees Node
					var employeesDoc = luga.data.xml.parseFromString(employeesStr);
					var rootNode = luga.data.xml.evaluateXPath(employeesDoc, "//employees");

					var obj = luga.data.xml.nodeToHash(rootNode[0]);
					expect(obj["employee"].length).toEqual(3);
					expect(obj["employee"][0].firstname).toEqual("Edward");
					expect(obj["employee"][0].lastname).toEqual("Smith");
					expect(obj["employee"][0].phone).toEqual("(415) 333-0235");
					expect(obj["employee"][0].username).toEqual("esmith");
				});

			});

			describe("Return an empty object if:", function(){

				it("The given node has no attributes and no children", function(){
					var node = document.createElement("test");
					var obj = luga.data.xml.nodeToHash(node);
					expect(obj).toEqual({});
				});

			});

		});

	});

	describe(".nodeToString()", function(){

		it("Serialize a DOM Node into a string", function(){

			/**
			 * Remove whitespace to equalize serialized XML across browsers
			 * @param {String} str
			 * @return {String}
			 */
			var equalizeXmlString = function(str){
				return str.replace(/\s/g, "");
			};

			var xmlStr = "";
			xmlStr += "<artists>";
			xmlStr += "<player name=\"Dexter Gordon\" instrument=\"tenor sax\" />";
			xmlStr += "<player name=\"Sonny Rollins\" instrument=\"tenor sax\" />";
			xmlStr += "<player name=\"Thad Jones\" instrument=\"trumpet\" />";
			xmlStr += "<player name=\"Lee Morgan\" instrument=\"trumpet\" />";
			xmlStr += "<player name=\"Bill Evans\" instrument=\"piano\" />";
			xmlStr += "</artists>";
			var xmlNode = luga.data.xml.parseFromString(xmlStr);

			expect(equalizeXmlString(luga.data.xml.nodeToString(xmlNode))).toEqual(equalizeXmlString(xmlStr));
		});

	});

	describe(".parseFromString()", function(){

		it("Create a DOM Document out of a string", function(){
			expect(employeesDoc.getElementsByTagName("employee").length).toEqual(3);
		});

	});

});<|endoftext|>


<commit_before>module.exports = function(grunt) {
    'use strict';

    grunt.initConfig({

        watch: {
            coffeeSrc: {
                tasks: ['coffee:compileSrc'],
                files: [
                    'coffee/**/**/**/**/*.coffee',
                    'templates/**/**/*.html'
                ]
            },

            buildRunner: {
                tasks: ['jasmine:tests:build'],
                files: ['spec/**/**/*.js']
            },

            sass: {
                tasks: ['sass'],
                files: ['scss/**/**/*.scss']
            }
        },

        coffee: {
            compileSrc: {
                options: {
                    bare: true
                },
                expand: true,
                cwd: 'coffee/',
                src: '**/**/**/**/*.coffee',
                dest: 'build',
                rename: function(dest, src) {
                    return dest + '/' + src.replace('.coffee', '.js');
                },
            }
        },

        sass: {
            dist: {
                files: {
                    'css/style.css': 'scss/style.scss'
                },
                options: {
                    style: 'compressed',
                    quiet: true,
                    unixNewlines: true
                }
            }
        },

        requirejs: {
            distSrc: {
                options: {
                    baseUrl: '.',
                    appDir: 'build',
                    dir: 'dist/src',

                    optimize: 'none',
                    optimizeCss: 'none',
                    removeCombined: true,
                    preserveLicenseComments: false,

                    config: {
                        tpl: {
                            variable: 'data'
                        }
                    },

                    modules: [{
                        name: 'cilantro'
                    }, {
                        name: 'cilantro.ui'
                    }]
                }
            },

            distMin: {
                options: {
                    baseUrl: '.',
                    appDir: 'build',
                    dir: 'dist/min',

                    optimize: 'uglify2',
                    optimizeCss: 'none',
                    removeCombined: true,
                    preserveLicenseComments: false,

                    config: {
                        tpl: {
                            variable: 'data'
                        }
                    },

                    modules: [{
                        name: 'cilantro'
                    }, {
                        name: 'cilantro.ui'
                    }]
                }
            }
        },

        jasmine : {
            tests: {
                src : 'build/**/*.js',
                options : {
                    specs : 'spec/**/*Spec.js',
                    vendor: [
                        '/build/jquery.js',
                        '/spec/lib/jasmine-jquery.js',
                        '/spec/lib/jasmine.async.js',
                        '/spec/lib/mock-ajax.js'
                    ],
                    host: 'http://127.0.0.1:8125/',
                    template:'spec/runner.tmpl',
                    outfile: 'spec-runner.html',
                    keepRunner: true,
                    templateOptions: {
                        requireConfig: {
                            baseUrl: 'build/',
                            config: {
                                tpl: {
                                    variable: 'data'
                                }
                            }
                        }
                    }
                }
            }
        }

    });

    grunt.loadNpmTasks('grunt-contrib-jasmine');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-contrib-coffee');
    grunt.loadNpmTasks('grunt-contrib-sass');
    grunt.loadNpmTasks('grunt-contrib-requirejs');

    grunt.registerTask('default', ['jasmine', 'watch']);
};
<commit_msg>Fix paths in Grunfile, enable CoffeeScript source maps<commit_after>module.exports = function(grunt) {
    'use strict';

    grunt.initConfig({

        watch: {
            coffee: {
                tasks: ['coffee:compile'],
                files: [
                    'coffee/**/*.coffee',
                    'templates/**/*.html'
                ]
            },

            buildRunner: {
                tasks: ['jasmine:tests:build'],
                files: ['spec/**/*.js']
            },

            sass: {
                tasks: ['sass'],
                files: ['scss/**/*.scss']
            }
        },

        coffee: {
            compile: {
                options: {
                    bare: true,
                    sourceMap: true
                },
                expand: true,
                cwd: 'coffee/',
                src: '**/*.coffee',
                dest: 'build',
                rename: function(dest, src) {
                    return dest + '/' + src.replace('.coffee', '.js');
                },
            }
        },

        sass: {
            dist: {
                files: {
                    'css/style.css': 'scss/style.scss'
                },
                options: {
                    //style: 'compressed',
                    quiet: true,
                    unixNewlines: true,
                    debugInfo: true
                }
            }
        },

        requirejs: {
            distSrc: {
                options: {
                    baseUrl: '.',
                    appDir: 'build',
                    dir: 'dist/src',

                    optimize: 'none',
                    optimizeCss: 'none',
                    removeCombined: true,
                    preserveLicenseComments: false,

                    config: {
                        tpl: {
                            variable: 'data'
                        }
                    },

                    modules: [{
                        name: 'cilantro'
                    }, {
                        name: 'cilantro.ui'
                    }]
                }
            },

            distMin: {
                options: {
                    baseUrl: '.',
                    appDir: 'build',
                    dir: 'dist/min',

                    optimize: 'uglify2',
                    optimizeCss: 'none',
                    removeCombined: true,
                    preserveLicenseComments: false,

                    config: {
                        tpl: {
                            variable: 'data'
                        }
                    },

                    modules: [{
                        name: 'cilantro'
                    }, {
                        name: 'cilantro.ui'
                    }]
                }
            }
        },

        jasmine : {
            tests: {
                src : 'build/**/*.js',
                options : {
                    specs : 'spec/**/*Spec.js',
                    vendor: [
                        '/build/jquery.js',
                        '/spec/lib/jasmine-jquery.js',
                        '/spec/lib/jasmine.async.js',
                        '/spec/lib/mock-ajax.js'
                    ],
                    host: 'http://127.0.0.1:8125/',
                    template:'spec/runner.tmpl',
                    outfile: 'spec-runner.html',
                    keepRunner: true,
                    templateOptions: {
                        requireConfig: {
                            baseUrl: 'build/',
                            config: {
                                tpl: {
                                    variable: 'data'
                                }
                            }
                        }
                    }
                }
            }
        }

    });

    grunt.loadNpmTasks('grunt-contrib-jasmine');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-contrib-coffee');
    grunt.loadNpmTasks('grunt-contrib-sass');
    grunt.loadNpmTasks('grunt-contrib-requirejs');

    grunt.registerTask('default', ['jasmine', 'watch']);
};
<|endoftext|>


<commit_before>'use strict';

const _ = require('lodash');
const crypto = require('crypto');
const compose = require('koa-compose');

const errors = require('../helpers/errors');
const JWT = require('../helpers/jwt');
const redirectUri = require('../helpers/redirect_uri');
const instance = require('../helpers/weak_cache');

const rejectDupes = require('../shared/check_dupes');
const bodyParser = require('../shared/conditional_body');
const paramsMiddleware = require('../shared/get_params');

const parseBody = bodyParser('application/x-www-form-urlencoded');
const STATES = /_state\.(\S+)=/g;

module.exports = function endSessionAction(provider) {
  const loadClient = function* loadClient(clientId) {
    // Validate: client_id param
    const client = yield provider.Client.find(clientId);

    this.assert(client, new errors.InvalidClientError('unrecognized azp or aud claims'));

    return client;
  };

  return {
    get: compose([
      paramsMiddleware(['id_token_hint', 'post_logout_redirect_uri', 'state']),

      rejectDupes,

      function* endSessionChecks(next) {
        const params = this.oidc.params;

        if (params.id_token_hint) {
          let client;

          const clientId = (() => {
            try {
              const jot = JWT.decode(params.id_token_hint);
              return jot.payload.azp || jot.payload.aud;
            } catch (err) {
              return this.throw(new errors.InvalidRequestError(
                `could not decode id_token_hint (${err.message})`));
            }
          })();

          try {
            client = yield loadClient.call(this, clientId);
            yield provider.IdToken.validate(params.id_token_hint, client);
          } catch (err) {
            this.throw(new errors.InvalidRequestError(
              `could not validate id_token_hint (${err.message})`));
          }

          if (params.post_logout_redirect_uri) {
            this.assert(client.postLogoutRedirectUriAllowed(params.post_logout_redirect_uri),
              new errors.InvalidRequestError('post_logout_redirect_uri not registered'));
          }

          this.oidc.client = client;
        } else {
          params.post_logout_redirect_uri = undefined;
        }

        yield next;
      },

      function* renderLogout(next) {
        const secret = crypto.randomBytes(24).toString('hex');

        this.oidc.session.logout = {
          secret,
          clientId: this.oidc.client ? this.oidc.client.clientId : undefined,
          postLogoutRedirectUri: this.oidc.params.post_logout_redirect_uri ||
            instance(provider).configuration('postLogoutRedirectUri'),
        };

        this.type = 'html';
        this.status = 200;

        const formhtml = `<form id="op.logoutForm" method="post" action="${provider.pathFor('end_session')}"><input type="hidden" name="xsrf" value="${secret}"/></form>`;
        instance(provider).configuration('logoutSource').call(this, formhtml);

        yield next;
      },
    ]),

    post: compose([
      parseBody,

      paramsMiddleware(['xsrf', 'logout']),

      rejectDupes,

      function* checkLogoutToken(next) {
        this.assert(this.oidc.session.logout, new errors.InvalidRequestError(
          'could not find logout details'));
        this.assert(this.oidc.session.logout.secret === this.oidc.params.xsrf,
          new errors.InvalidRequestError('xsrf token invalid'));
        yield next;
      },

      function* endSession(next) {
        const params = this.oidc.session.logout;

        const cookieOpts = _.omit(instance(provider).configuration('cookies.long'), 'maxAge', 'signed');

        if (this.oidc.params.logout) {
          if (instance(provider).configuration('features.backchannelLogout')) {
            try {
              const Client = provider.Client;
              const clientIds = Object.keys(this.oidc.session.authorizations);
              const logouts = clientIds.map(visitedClientId => Client.find(visitedClientId)
                .then((visitedClient) => {
                  if (visitedClient && visitedClient.backchannelLogoutUri) {
                    return visitedClient.backchannelLogout(this.oidc.session.accountId(),
                      this.oidc.session.sidFor(visitedClient.clientId));
                  }
                  return undefined;
                }));

              yield logouts;
            } catch (err) {}
          }

          yield this.oidc.session.destroy();

          // get all cookies matching _state.[clientId](.sig) and drop them
          const cookies = this.get('cookie').match(STATES);
          if (cookies) cookies.forEach(val => this.cookies.set(val.slice(0, -1), null, cookieOpts));

          this.cookies.set('_session', null, cookieOpts);
          this.cookies.set('_session.sig', null, cookieOpts);
        } else if (params.clientId) {
          delete this.oidc.session.authorizations[params.clientId];
          this.cookies.set(`_state.${params.clientId}`, null, cookieOpts);
          this.cookies.set(`_state.${params.clientId}.sig`, null, cookieOpts);
        }

        const uri = redirectUri(params.postLogoutRedirectUri,
          params.state != null ? { state: params.state } : undefined); // eslint-disable-line eqeqeq

        this.redirect(uri);

        yield next;
      },
    ]),
  };
};
<commit_msg>mount-save logout form action<commit_after>'use strict';

const _ = require('lodash');
const crypto = require('crypto');
const compose = require('koa-compose');

const errors = require('../helpers/errors');
const JWT = require('../helpers/jwt');
const redirectUri = require('../helpers/redirect_uri');
const instance = require('../helpers/weak_cache');

const rejectDupes = require('../shared/check_dupes');
const bodyParser = require('../shared/conditional_body');
const paramsMiddleware = require('../shared/get_params');

const parseBody = bodyParser('application/x-www-form-urlencoded');
const STATES = /_state\.(\S+)=/g;

module.exports = function endSessionAction(provider) {
  const loadClient = function* loadClient(clientId) {
    // Validate: client_id param
    const client = yield provider.Client.find(clientId);

    this.assert(client, new errors.InvalidClientError('unrecognized azp or aud claims'));

    return client;
  };

  return {
    get: compose([
      paramsMiddleware(['id_token_hint', 'post_logout_redirect_uri', 'state']),

      rejectDupes,

      function* endSessionChecks(next) {
        const params = this.oidc.params;

        if (params.id_token_hint) {
          let client;

          const clientId = (() => {
            try {
              const jot = JWT.decode(params.id_token_hint);
              return jot.payload.azp || jot.payload.aud;
            } catch (err) {
              return this.throw(new errors.InvalidRequestError(
                `could not decode id_token_hint (${err.message})`));
            }
          })();

          try {
            client = yield loadClient.call(this, clientId);
            yield provider.IdToken.validate(params.id_token_hint, client);
          } catch (err) {
            this.throw(new errors.InvalidRequestError(
              `could not validate id_token_hint (${err.message})`));
          }

          if (params.post_logout_redirect_uri) {
            this.assert(client.postLogoutRedirectUriAllowed(params.post_logout_redirect_uri),
              new errors.InvalidRequestError('post_logout_redirect_uri not registered'));
          }

          this.oidc.client = client;
        } else {
          params.post_logout_redirect_uri = undefined;
        }

        yield next;
      },

      function* renderLogout(next) {
        const secret = crypto.randomBytes(24).toString('hex');

        this.oidc.session.logout = {
          secret,
          clientId: this.oidc.client ? this.oidc.client.clientId : undefined,
          postLogoutRedirectUri: this.oidc.params.post_logout_redirect_uri ||
            instance(provider).configuration('postLogoutRedirectUri'),
        };

        this.type = 'html';
        this.status = 200;

        const formhtml = `<form id="op.logoutForm" method="post" action="${this.oidc.urlFor('end_session')}"><input type="hidden" name="xsrf" value="${secret}"/></form>`;
        instance(provider).configuration('logoutSource').call(this, formhtml);

        yield next;
      },
    ]),

    post: compose([
      parseBody,

      paramsMiddleware(['xsrf', 'logout']),

      rejectDupes,

      function* checkLogoutToken(next) {
        this.assert(this.oidc.session.logout, new errors.InvalidRequestError(
          'could not find logout details'));
        this.assert(this.oidc.session.logout.secret === this.oidc.params.xsrf,
          new errors.InvalidRequestError('xsrf token invalid'));
        yield next;
      },

      function* endSession(next) {
        const params = this.oidc.session.logout;

        const cookieOpts = _.omit(instance(provider).configuration('cookies.long'), 'maxAge', 'signed');

        if (this.oidc.params.logout) {
          if (instance(provider).configuration('features.backchannelLogout')) {
            try {
              const Client = provider.Client;
              const clientIds = Object.keys(this.oidc.session.authorizations);
              const logouts = clientIds.map(visitedClientId => Client.find(visitedClientId)
                .then((visitedClient) => {
                  if (visitedClient && visitedClient.backchannelLogoutUri) {
                    return visitedClient.backchannelLogout(this.oidc.session.accountId(),
                      this.oidc.session.sidFor(visitedClient.clientId));
                  }
                  return undefined;
                }));

              yield logouts;
            } catch (err) {}
          }

          yield this.oidc.session.destroy();

          // get all cookies matching _state.[clientId](.sig) and drop them
          const cookies = this.get('cookie').match(STATES);
          if (cookies) cookies.forEach(val => this.cookies.set(val.slice(0, -1), null, cookieOpts));

          this.cookies.set('_session', null, cookieOpts);
          this.cookies.set('_session.sig', null, cookieOpts);
        } else if (params.clientId) {
          delete this.oidc.session.authorizations[params.clientId];
          this.cookies.set(`_state.${params.clientId}`, null, cookieOpts);
          this.cookies.set(`_state.${params.clientId}.sig`, null, cookieOpts);
        }

        const uri = redirectUri(params.postLogoutRedirectUri,
          params.state != null ? { state: params.state } : undefined); // eslint-disable-line eqeqeq

        this.redirect(uri);

        yield next;
      },
    ]),
  };
};
<|endoftext|>


<commit_before>var path = require('path');
var Database = require('../../database').Database;
var Domain = require('../../domain').Domain;
var Deferred = require('jsdeferred').Deferred;

exports.version = path.basename(__dirname);

var handlers = Object.create(null);

handlers.CreateDomain = function(database, request, response) {
  // FIXME just an example
  var domain = new Domain(request.query.DomainName || '');
  var options = {
        name: domain.tableName,
        flags: Database.TABLE_HASH_KEY,
        key_type: Database.ShortText
      };
  database.commandDeferred('table_create', options)
    .next(function(data) {
      var termsOptions = {
            name: domain.termsTableName,
            flags: Database.TABLE_PAT_KEY + '|' + Database.KEY_NORMALIZE,
            key_type: Database.ShortText,
            default_tokenizer: Database.TokenBigram
          };
      return database.commandDeferred('table_create', termsOptions);
    })
    .next(function(data) {
      response.send('created ' + domain.name);
    })
    .error(function(error) {
      return response.send(error.message, 400);
    });
};

handlers.DefineIndexField = function(database, request, response) {
  var domain = new Domain(request.query.DomainName || '');

  var fieldName = request.query['IndexField.IndexFieldName'] || '';
  var field = domain.getIndexField(fieldName);

  var options = {
        table: domain.tableName,
        name: field.columnName,
        flags: Database.COLUMN_SCALAR,
        type: Database.ShortText
      };
  database.commandDeferred('column_create', options)
    .next(function(data) {
      var termsOptions = {
            table: domain.termsTableName,
            name: field.indexColumnName,
            flags: Database.COLUMN_INDEX + '|' + Database.WITH_POSITION,
            type: domain.tableName,
            source: field.columnName
          };
      return database.commandDeferred('column_create', termsOptions)
               .next(function() {
                 response.send('created index field "' + field + '" ' +
                               'for the domain "' + domain.name + '"');
               });
    })
    .error(function(error) {
      return response.send(error.message, 400);
    });
};

exports.createHandler = function(database) {
  return function(request, response) {
    var version = request.query.Version;
    if (!version)
      return response.send('API version must be given as the parameter "Version".', 400);

    if (version != exports.version)
      return response.send('API version "' + version + '" is not supported.', 400);

    var action = request.query.Action || '';
    if (!action)
      return response.send('Action must be given as the parameter "Action".', 400);

    if (!(action in handlers))
      return response.send('Action "' + action + '" is not supported.', 400);

    var handler = handlers[action];
    handler(database, request, response);
  };
};
<commit_msg>Reduce indent level<commit_after>var path = require('path');
var Database = require('../../database').Database;
var Domain = require('../../domain').Domain;
var Deferred = require('jsdeferred').Deferred;

exports.version = path.basename(__dirname);

var handlers = Object.create(null);

handlers.CreateDomain = function(database, request, response) {
  // FIXME just an example
  var domain = new Domain(request.query.DomainName || '');
  var options = {
        name: domain.tableName,
        flags: Database.TABLE_HASH_KEY,
        key_type: Database.ShortText
      };
  database.commandDeferred('table_create', options)
    .next(function(data) {
      var termsOptions = {
            name: domain.termsTableName,
            flags: Database.TABLE_PAT_KEY + '|' + Database.KEY_NORMALIZE,
            key_type: Database.ShortText,
            default_tokenizer: Database.TokenBigram
          };
      return database.commandDeferred('table_create', termsOptions);
    })
    .next(function(data) {
      response.send('created ' + domain.name);
    })
    .error(function(error) {
      return response.send(error.message, 400);
    });
};

handlers.DefineIndexField = function(database, request, response) {
  var domain = new Domain(request.query.DomainName || '');

  var fieldName = request.query['IndexField.IndexFieldName'] || '';
  var field = domain.getIndexField(fieldName);

  var options = {
        table: domain.tableName,
        name: field.columnName,
        flags: Database.COLUMN_SCALAR,
        type: Database.ShortText
      };
  database.commandDeferred('column_create', options)
    .next(function(data) {
      var termsOptions = {
            table: domain.termsTableName,
            name: field.indexColumnName,
            flags: Database.COLUMN_INDEX + '|' + Database.WITH_POSITION,
            type: domain.tableName,
            source: field.columnName
          };
      return database.commandDeferred('column_create', termsOptions);
    })
    .next(function() {
      response.send('created index field "' + field + '" ' +
                    'for the domain "' + domain.name + '"');
    })
    .error(function(error) {
      return response.send(error.message, 400);
    });
};

exports.createHandler = function(database) {
  return function(request, response) {
    var version = request.query.Version;
    if (!version)
      return response.send('API version must be given as the parameter "Version".', 400);

    if (version != exports.version)
      return response.send('API version "' + version + '" is not supported.', 400);

    var action = request.query.Action || '';
    if (!action)
      return response.send('Action must be given as the parameter "Action".', 400);

    if (!(action in handlers))
      return response.send('Action "' + action + '" is not supported.', 400);

    var handler = handlers[action];
    handler(database, request, response);
  };
};
<|endoftext|>


<commit_before>define([],
    function( ){
        'use strict';
        var ClientNode = function(node,core,meta){
            var self = this,
                ownpath = core.getStringPath(node),
                ownpathpostfix = ownpath === "" ? "" : "/";

            var getParentId = function(){
                var parent = core.getParent(node);
                if(parent){
                    var parentpath = core.getStringPath(parent);
                    if(parentpath === ""){
                        parentpath = "root";
                    }
                    return parentpath;
                } else {
                    return null;
                }
            };
            var getId = function(){
                return getClientNodePath(node);
            };
            var getChildrenIds = function(){
                var children = core.getChildrenRelids(node);
                for(var i=0;i<children.length;i++){
                    children[i]=ownpath+ownpathpostfix+children[i];
                }
                return children;
            };
            var getBaseId = function(){
                if(core.getRegistry(node,"isConnection") === true){
                    return "connection";
                } else {
                    return "object";
                }
            };
            var getInheritorIds = function(){
                return null;
            };
            var getAttribute = function(name){
                return core.getAttribute(node,name);
            };
            var getRegistry = function(name){
                return core.getRegistry(node,name);
            };
            var getPointer = function(name){
                return {to:core.getPointerPath(node,name),from:[]};
            };
            var getPointerNames = function(){
                return core.getPointerNames(node);
            };
            var getAttributeNames = function(){
                return core.getAttributeNames(node);
            };
            var getRegistryNames = function(){
                return core.getRegistryNames(node);
            };

            var getClientNodePath = function(){
                var path = ownpath;
                if(path === ""){
                    path = "root";
                }
                return path;
            };

            //META
            var getValidChildrenTypes = function(){
                return meta.getValidChildrenTypes(self);
            };

            return {
                getParentId : getParentId,
                getId       : getId,
                getChildrenIds : getChildrenIds,
                getBaseId : getBaseId,
                getInheritorIds : getInheritorIds,
                getAttribute : getAttribute,
                getRegistry : getRegistry,
                getPointer : getPointer,
                getPointerNames : getPointerNames,
                getAttributeNames : getAttributeNames,
                getRegistryNames : getRegistryNames,
                //META functions
                getValidChildrenTypes : getValidChildrenTypes
            }
        };
        return ClientNode;
    });
<commit_msg>printData function now prints the data of a node to the console<commit_after>define([],
    function( ){
        'use strict';
        var ClientNode = function(node,core,meta){
            var self = this,
                ownpath = core.getStringPath(node),
                ownpathpostfix = ownpath === "" ? "" : "/";

            var getParentId = function(){
                var parent = core.getParent(node);
                if(parent){
                    var parentpath = core.getStringPath(parent);
                    if(parentpath === ""){
                        parentpath = "root";
                    }
                    return parentpath;
                } else {
                    return null;
                }
            };
            var getId = function(){
                return getClientNodePath(node);
            };
            var getChildrenIds = function(){
                var children = core.getChildrenRelids(node);
                for(var i=0;i<children.length;i++){
                    children[i]=ownpath+ownpathpostfix+children[i];
                }
                return children;
            };
            var getBaseId = function(){
                if(core.getRegistry(node,"isConnection") === true){
                    return "connection";
                } else {
                    return "object";
                }
            };
            var getInheritorIds = function(){
                return null;
            };
            var getAttribute = function(name){
                return core.getAttribute(node,name);
            };
            var getRegistry = function(name){
                return core.getRegistry(node,name);
            };
            var getPointer = function(name){
                return {to:core.getPointerPath(node,name),from:[]};
            };
            var getPointerNames = function(){
                return core.getPointerNames(node);
            };
            var getAttributeNames = function(){
                return core.getAttributeNames(node);
            };
            var getRegistryNames = function(){
                return core.getRegistryNames(node);
            };

            var getClientNodePath = function(){
                var path = ownpath;
                if(path === ""){
                    path = "root";
                }
                return path;
            };

            //META
            var getValidChildrenTypes = function(){
                return meta.getValidChildrenTypes(self);
            };

            var printData = function(){
                //TODO it goes to console now...
                console.log("nodeprint###\n"+JSON.stringify(node)+"\nendnodeprint###\n");
            };

            return {
                getParentId : getParentId,
                getId       : getId,
                getChildrenIds : getChildrenIds,
                getBaseId : getBaseId,
                getInheritorIds : getInheritorIds,
                getAttribute : getAttribute,
                getRegistry : getRegistry,
                getPointer : getPointer,
                getPointerNames : getPointerNames,
                getAttributeNames : getAttributeNames,
                getRegistryNames : getRegistryNames,
                //helping functions
                printData : printData,
                //META functions
                getValidChildrenTypes : getValidChildrenTypes
            }
        };
        return ClientNode;
    });
<|endoftext|>


<commit_before>// tinix.js
//
// Copyright 2013 - Santosh Rajan - santoshrajan.com
//

Element.prototype.on = Element.prototype.addEventListener

var tinix = function(id) {
    return document.querySelector(id)
}

tinix.version = "0.0.1"

tinix.all = function(id) {
    return document.querySelectorAll(id)
}

tinix.ready = function(f) {
    if (document.readyState != "loading") {
        document.onreadystatechange = function() {
            if (document.readyState == "interactive") f()
        }
    } else {
        f()
    }
}

tinix.getR = function(s, f) {
    var r = new XMLHttpRequest()
    r.onload = function() {
        if (r.status == 200) {
            if (r.getResponseHeader("Content-Type") == "application/json") {
                s(JSON.parse(r.responseText))
            } else {
                s(r.responseText)
            }
        } else {
            f(r)
        }
    }
    return r
}

// get(url, success, failure)
tinix.get = function(u, s, f) {
    var r = this.getR(s, f)
    r.open("GET", u, true)
    r.send()
}

// postJSON(url, body, success, failure)
tinix.postJSON = function(u, b, s, f) {
    var r = this.getR(s, f)
    r.open("POST", u, true)
    r.setRequestHeader("Content-type", "application/json")
    r.send(JSON.stringify(b))
}

/*\
|*|
|*|  :: cookies.js ::
|*|
|*|  A complete cookies reader/writer framework with full unicode support.
|*|
|*|  https://developer.mozilla.org/en-US/docs/DOM/document.cookie
|*|
|*|  This framework is released under the GNU Public License, version 3 or later.
|*|  http://www.gnu.org/licenses/gpl-3.0-standalone.html
|*|
|*|  Syntaxes:
|*|
|*|  * docCookies.setItem(name, value[, end[, path[, domain[, secure]]]])
|*|  * docCookies.getItem(name)
|*|  * docCookies.removeItem(name[, path])
|*|  * docCookies.hasItem(name)
|*|  * docCookies.keys()
|*|
\*/

tinix.cookies = {
  getItem: function (sKey) {
    return unescape(document.cookie.replace(new RegExp("(?:(?:^|.*;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*)|.*"), "$1")) || null;
  },
  setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
    if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
    var sExpires = "";
    if (vEnd) {
      switch (vEnd.constructor) {
        case Number:
          sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
          break;
        case String:
          sExpires = "; expires=" + vEnd;
          break;
        case Date:
          sExpires = "; expires=" + vEnd.toGMTString();
          break;
      }
    }
    document.cookie = escape(sKey) + "=" + escape(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
    return true;
  },
  removeItem: function (sKey, sPath) {
    if (!sKey || !this.hasItem(sKey)) { return false; }
    document.cookie = escape(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sPath ? "; path=" + sPath : "");
    return true;
  },
  hasItem: function (sKey) {
    return (new RegExp("(?:^|;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
  }
};

module.exports = tinix

<commit_msg>Version 0.0.1<commit_after>// tinix.js
//
// Copyright 2013 - Santosh Rajan - santoshrajan.com
//

Element.prototype.on = Element.prototype.addEventListener

var tinix = function(id) {
    return document.querySelector(id)
}

tinix.version = "0.0.1"

tinix.all = function(id) {
    return document.querySelectorAll(id)
}

tinix.ready = function(f) {
    if (document.readyState == "loading") {
        document.onreadystatechange = function() {
            if (document.readyState == "interactive") f()
        }
    } else {
        f()
    }
}

tinix.getR = function(s, f) {
    var r = new XMLHttpRequest()
    r.onload = function() {
        if (r.status == 200) {
            if (r.getResponseHeader("Content-Type") == "application/json") {
                s(JSON.parse(r.responseText))
            } else {
                s(r.responseText)
            }
        } else {
            f(r)
        }
    }
    return r
}

// get(url, success, failure)
tinix.get = function(u, s, f) {
    var r = this.getR(s, f)
    r.open("GET", u, true)
    r.send()
}

// postJSON(url, body, success, failure)
tinix.postJSON = function(u, b, s, f) {
    var r = this.getR(s, f)
    r.open("POST", u, true)
    r.setRequestHeader("Content-type", "application/json")
    r.send(JSON.stringify(b))
}

/*\
|*|
|*|  :: cookies.js ::
|*|
|*|  A complete cookies reader/writer framework with full unicode support.
|*|
|*|  https://developer.mozilla.org/en-US/docs/DOM/document.cookie
|*|
|*|  This framework is released under the GNU Public License, version 3 or later.
|*|  http://www.gnu.org/licenses/gpl-3.0-standalone.html
|*|
|*|  Syntaxes:
|*|
|*|  * docCookies.setItem(name, value[, end[, path[, domain[, secure]]]])
|*|  * docCookies.getItem(name)
|*|  * docCookies.removeItem(name[, path])
|*|  * docCookies.hasItem(name)
|*|  * docCookies.keys()
|*|
\*/

tinix.cookies = {
  getItem: function (sKey) {
    return unescape(document.cookie.replace(new RegExp("(?:(?:^|.*;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*)|.*"), "$1")) || null;
  },
  setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
    if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
    var sExpires = "";
    if (vEnd) {
      switch (vEnd.constructor) {
        case Number:
          sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
          break;
        case String:
          sExpires = "; expires=" + vEnd;
          break;
        case Date:
          sExpires = "; expires=" + vEnd.toGMTString();
          break;
      }
    }
    document.cookie = escape(sKey) + "=" + escape(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
    return true;
  },
  removeItem: function (sKey, sPath) {
    if (!sKey || !this.hasItem(sKey)) { return false; }
    document.cookie = escape(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sPath ? "; path=" + sPath : "");
    return true;
  },
  hasItem: function (sKey) {
    return (new RegExp("(?:^|;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
  }
};

module.exports = tinix

<|endoftext|>


<commit_before>'use strict';

module.exports = function(grunt) {
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),

        /** GENERATE JSON PATTERNS LIBRARY **/
        dir2strings: {
          options: {
            exclude: '**/*.md'
          },
          data: {
            root: 'public/patternlab/sources/_patterns',
            dest: 'public/patternlab/sources/patterns.json'
          },
        },

        sass: {
          options: {
            // includePaths: [''],
            outputStyle: 'compressed', // 'nested' (default), 'expanded', 'compact', 'compressed'
            sourceComments: 'map',
            // sourceMap: 'app/css/app.css.map'
          },
          dist: {
            files: {
              'public/css/main.css': 'public/scss/main.scss'
            }
          }
        },

        /** Warch for files modification **/
        watch: {
          grunt: {
            files: ['Gruntfile.js'],
            tasks: ['sass']
          },
          sass: {
            files: 'public/scss/{,**/}*.scss',
            tasks: ['sass']
          },
          livereload: {
            // files: ['public/*.html', 'public/js/{,**/}*.js', 'public/css/{,*/}*.css', 'public/images/{,*/}*.{jpg,gif,svg,jpeg,png}'],
            files: [
              'public/patternlab/{,**/}*.{js, mustache}',
              'public/*.html',
              'public/js/{,**/}*.js',
              'public/css/{,*/}*.css',
              'public/images/{,*/}*.{jpg,gif,svg,jpeg,png}'
            ],
            options: {
              livereload: true
            }
          }
        },

        /** Create servers **/
        connect: {
          app: {
            options: {
              hostname: 'patternlab.dev',
              port: 9000,
              base: 'public/',
              livereload: true
            }
          },
          dist: {
            options: {
              hostname: 'patternlab.dev',
              port: 9001,
              base: 'dist/',
              keepalive: true
            }
          }
        },

        /** OPEN BROWER **/
        open: {
          app: {
            path: 'http://patternlab.dev:9000/',
            app: 'Google Chrome'
          },
          dist: {
            path: 'http://patternlab.dev:9001/',
            app: 'Google Chrome'
          }
        }

    });

    grunt.loadNpmTasks('grunt-dir2strings');
    grunt.loadNpmTasks('grunt-sass');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-contrib-connect');
    grunt.loadNpmTasks('grunt-open');

    grunt.registerTask('build', ['sass']);
    grunt.registerTask('generateJson', ['dir2strings']);
    grunt.registerTask('default', ['connect:app', 'open:app', 'watch']);

};
<commit_msg>develop: add livreload on scss files<commit_after>'use strict';

module.exports = function(grunt) {
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),

        /** GENERATE JSON PATTERNS LIBRARY **/
        dir2strings: {
          options: {
            exclude: '**/*.md'
          },
          data: {
            root: 'public/patternlab/sources/_patterns',
            dest: 'public/patternlab/sources/patterns.json'
          },
        },

        sass: {
          options: {
            // includePaths: [''],
            outputStyle: 'compressed', // 'nested' (default), 'expanded', 'compact', 'compressed'
            sourceComments: 'map',
            // sourceMap: 'app/css/app.css.map'
          },
          dist: {
            files: {
              'public/css/main.css': 'public/scss/main.scss'
            }
          }
        },

        /** Warch for files modification **/
        watch: {
          grunt: {
            files: ['Gruntfile.js'],
            tasks: ['sass']
          },
          sass: {
            files: 'public/scss/{,**/}*.scss',
            tasks: ['sass']
          },
          livereload: {
            // files: ['public/*.html', 'public/js/{,**/}*.js', 'public/css/{,*/}*.css', 'public/images/{,*/}*.{jpg,gif,svg,jpeg,png}'],
            files: [
              'public/patternlab/{,**/}*.{js, mustache}',
              'public/*.html',
              'public/js/{,**/}*.js',
              'public/css/{,*/}*.css',
              'public/scss/{,*/}*.scss',
              'public/images/{,*/}*.{jpg,gif,svg,jpeg,png}'
            ],
            options: {
              livereload: true
            }
          }
        },

        /** Create servers **/
        connect: {
          app: {
            options: {
              hostname: 'patternlab.dev',
              port: 9000,
              base: 'public/',
              livereload: true
            }
          },
          dist: {
            options: {
              hostname: 'patternlab.dev',
              port: 9001,
              base: 'dist/',
              keepalive: true
            }
          }
        },

        /** OPEN BROWER **/
        open: {
          app: {
            path: 'http://patternlab.dev:9000/',
            app: 'Google Chrome'
          },
          dist: {
            path: 'http://patternlab.dev:9001/',
            app: 'Google Chrome'
          }
        }

    });

    grunt.loadNpmTasks('grunt-dir2strings');
    grunt.loadNpmTasks('grunt-sass');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-contrib-connect');
    grunt.loadNpmTasks('grunt-open');

    grunt.registerTask('build', ['sass']);
    grunt.registerTask('generateJson', ['dir2strings']);
    grunt.registerTask('default', ['connect:app', 'open:app', 'watch']);

};
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { Link } from 'react-router';
import { connect } from 'react-redux';
import styles from './Sidebar.css';
import Project_List from './Project_List';
import {fetchUserProjects} from '../reducers/projects_list';

export class Sidebar extends Component {

 componentDidUpdate(){
    if (this.props.loginUser.id && !Object.keys(this.props.projects).length){
      this.props.onLoadProjects(this.props.loginUser.id);
    }
  }

  render() {
    console.log("THIS DOT PROPS", this.props)
    return (

                <Link to="/">
                  <button className="btn-floating btn-large waves-effect waves-light cyan left">
                    chevron_left
                  </button>
                </Link>

                assignment_ind

Settings

Logout

                <Project_List/>

    );
  }
}

/* ---------------- CONTAINER --------------------*/
function mapStateToProps(state){
  return {
    loginUser: state.login,
    projects: state.projects
  }
}

function mapDispatchToProps(dispatch) {
  return {
     onLoadProjects: function (user){
      dispatch(fetchUserProjects(user));
    }
  }
}

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(Sidebar);
<commit_msg>commit to show issues<commit_after>import React, { Component } from 'react';
import { Link } from 'react-router';
import { connect } from 'react-redux';
import styles from './Sidebar.css';
import Project_List from './Project_List';
import { fetchUserProjects } from '../reducers/projects_list';
import * as Actions from '../../utilities/actions';

export class Sidebar extends Component {

  constructor(props) {
    super(props);
    this.onClickArchiveUpdate = this.onClickArchiveUpdate.bind(this);
  }

  onClickArchiveUpdate(event) {

  }

  componentDidUpdate() {
    if (this.props.loginUser.id && !Object.keys(this.props.projects).length) {
      this.props.onLoadProjects(this.props.loginUser.id);
    }
  }

  render() {
    console.log("THIS DOT PROPS", this.props)
    return (

            <Link to="/">
              <button className="btn-floating btn-large waves-effect waves-light cyan left">
                chevron_left
              </button>
            </Link>
            <button className="btn-floating btn-large waves-effect waves-light cyan left"
              onClick={this.onClickArchiveUpdate}>
              queue
            </button>

            assignment_ind

Settings

Logout

            <Project_List />

    );
  }
}

/* ---------------- CONTAINER --------------------*/
function mapStateToProps(state) {
  return {
    loginUser: state.login,
    projects: state.projects
  }
}

function mapDispatchToProps(dispatch) {
  return {
    onLoadProjects: function (user) {
      dispatch(fetchUserProjects(user));
    }
  }
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Sidebar);
<|endoftext|>


<commit_before>//List of Colors
var colorName = "lime";
var colors = {
    "aliceblue": "#f0f8ff",
    "antiquewhite": "#faebd7",
    "aqua": "#00ffff",
    "aquamarine": "#7fffd4",
    "azure": "#f0ffff",
    "beige": "#f5f5dc",
    "bisque": "#ffe4c4",
    "black": "#000000",
    "blanchedalmond": "#ffebcd",
    "blue": "#0000ff",
    "blueviolet": "#8a2be2",
    "brown": "#a52a2a",
    "burlywood": "#deb887",
    "cadetblue": "#5f9ea0",
    "chartreuse": "#7fff00",
    "chocolate": "#d2691e",
    "coral": "#ff7f50",
    "cornflowerblue": "#6495ed",
    "cornsilk": "#fff8dc",
    "crimson": "#dc143c",
    "cyan": "#00ffff",
    "darkblue": "#00008b",
    "darkcyan": "#008b8b",
    "darkgoldenrod": "#b8860b",
    "darkgray": "#a9a9a9",
    "darkgreen": "#006400",
    "darkgrey": "#a9a9a9",
    "darkkhaki": "#bdb76b",
    "darkmagenta": "#8b008b",
    "darkolivegreen": "#556b2f",
    "darkorange": "#ff8c00",
    "darkorchid": "#9932cc",
    "darkred": "#8b0000",
    "darksalmon": "#e9967a",
    "darkseagreen": "#8fbc8f",
    "darkslateblue": "#483d8b",
    "darkslategray": "#2f4f4f",
    "darkslategrey": "#2f4f4f",
    "darkturquoise": "#00ced1",
    "darkviolet": "#9400d3",
    "deeppink": "#ff1493",
    "deepskyblue": "#00bfff",
    "dimgray": "#696969",
    "dimgrey": "#696969",
    "dodgerblue": "#1e90ff",
    "firebrick": "#b22222",
    "floralwhite": "#fffaf0",
    "forestgreen": "#228b22",
    "fuchsia": "#ff00ff",
    "gainsboro": "#dcdcdc",
    "ghostwhite": "#f8f8ff",
    "gold": "#ffd700",
    "goldenrod": "#daa520",
    "gray": "#808080",
    "green": "#008000",
    "greenyellow": "#adff2f",
    "grey": "#808080",
    "honeydew": "#f0fff0",
    "hotpink": "#ff69b4",
    "indianred": "#cd5c5c",
    "indigo": "#4b0082",
    "ivory": "#fffff0",
    "khaki": "#f0e68c",
    "lavender": "#e6e6fa",
    "lavenderblush": "#fff0f5",
    "lawngreen": "#7cfc00",
    "lemonchiffon": "#fffacd",
    "lightblue": "#add8e6",
    "lightcoral": "#f08080",
    "lightcyan": "#e0ffff",
    "lightgoldenrodyellow": "#fafad2",
    "lightgray": "#d3d3d3",
    "lightgreen": "#90ee90",
    "lightgrey": "#d3d3d3",
    "lightpink": "#ffb6c1",
    "lightsalmon": "#ffa07a",
    "lightseagreen": "#20b2aa",
    "lightskyblue": "#87cefa",
    "lightslategray": "#778899",
    "lightslategrey": "#778899",
    "lightsteelblue": "#b0c4de",
    "lightyellow": "#ffffe0",
    "lime": "#00ff00",
    "limegreen": "#32cd32",
    "linen": "#faf0e6",
    "magenta": "#ff00ff",
    "maroon": "#800000",
    "mediumaquamarine": "#66cdaa",
    "mediumblue": "#0000cd",
    "mediumorchid": "#ba55d3",
    "mediumpurple": "#9370db",
    "mediumseagreen": "#3cb371",
    "mediumslateblue": "#7b68ee",
    "mediumspringgreen": "#00fa9a",
    "mediumturquoise": "#48d1cc",
    "mediumvioletred": "#c71585",
    "midnightblue": "#191970",
    "mintcream": "#f5fffa",
    "mistyrose": "#ffe4e1",
    "moccasin": "#ffe4b5",
    "navajowhite": "#ffdead",
    "navy": "#000080",
    "oldlace": "#fdf5e6",
    "olive": "#808000",
    "olivedrab": "#6b8e23",
    "orange": "#ffa500",
    "orangered": "#ff4500",
    "orchid": "#da70d6",
    "palegoldenrod": "#eee8aa",
    "palegreen": "#98fb98",
    "paleturquoise": "#afeeee",
    "palevioletred": "#db7093",
    "papayawhip": "#ffefd5",
    "peachpuff": "#ffdab9",
    "peru": "#cd853f",
    "pink": "#ffc0cb",
    "plum": "#dda0dd",
    "powderblue": "#b0e0e6",
    "purple": "#800080",
    "rebeccapurple": "#663399",
    "red": "#ff0000",
    "rosybrown": "#bc8f8f",
    "royalblue": "#4169e1",
    "saddlebrown": "#8b4513",
    "salmon": "#fa8072",
    "sandybrown": "#f4a460",
    "seagreen": "#2e8b57",
    "seashell": "#fff5ee",
    "sienna": "#a0522d",
    "silver": "#c0c0c0",
    "skyblue": "#87ceeb",
    "slateblue": "#6a5acd",
    "slategray": "#708090",
    "slategrey": "#708090",
    "snow": "#fffafa",
    "springgreen": "#00ff7f",
    "steelblue": "#4682b4",
    "tan": "#d2b48c",
    "teal": "#008080",
    "thistle": "#d8bfd8",
    "tomato": "#ff6347",
    "turquoise": "#40e0d0",
    "violet": "#ee82ee",
    "wheat": "#f5deb3",
    "whitesmoke": "#f5f5f5",
    "yellow": "#ffff00",
    "yellowgreen": "#9acd32"
}

//Setup

function setupGame() {
    setActiveColor();
}

//Scripts

function getRandomColor() {
    var color;
    var count = 0;
    for (var prop in colors)
        if (Math.random() < 1 / ++count)
            color = prop;
    return color;
}

function setActiveColor() {
    colorName = getRandomColor();
    document.getElementById("user-guess").value = "";
    document.getElementById("game-canvas").style.backgroundColor = colors[colorName];
    document.getElementById("confirm-btn").style.backgroundColor = colors[colorName];
    document.getElementById("color-hex").innerHTML = colors[colorName];
}

function goodGuess() {
    console.log("success!");
}

function badGuess() {
    console.log("fail!");
}

function checkGuess() {
    var userGuess = String(document.getElementById("user-guess").value);
    userGuess = userGuess.toLowerCase().replace(/\s/g,'');
    console.log(userGuess);
    if (userGuess === colorName) {
        goodGuess();
    }
    else {
        badGuess();
    }
    setActiveColor();
}<commit_msg>Remove black color<commit_after>//List of Colors
var colorName = "lime";
var colors = {
    "aliceblue": "#f0f8ff",
    "antiquewhite": "#faebd7",
    "aqua": "#00ffff",
    "aquamarine": "#7fffd4",
    "azure": "#f0ffff",
    "beige": "#f5f5dc",
    "bisque": "#ffe4c4",
    "blanchedalmond": "#ffebcd",
    "blue": "#0000ff",
    "blueviolet": "#8a2be2",
    "brown": "#a52a2a",
    "burlywood": "#deb887",
    "cadetblue": "#5f9ea0",
    "chartreuse": "#7fff00",
    "chocolate": "#d2691e",
    "coral": "#ff7f50",
    "cornflowerblue": "#6495ed",
    "cornsilk": "#fff8dc",
    "crimson": "#dc143c",
    "cyan": "#00ffff",
    "darkblue": "#00008b",
    "darkcyan": "#008b8b",
    "darkgoldenrod": "#b8860b",
    "darkgray": "#a9a9a9",
    "darkgreen": "#006400",
    "darkgrey": "#a9a9a9",
    "darkkhaki": "#bdb76b",
    "darkmagenta": "#8b008b",
    "darkolivegreen": "#556b2f",
    "darkorange": "#ff8c00",
    "darkorchid": "#9932cc",
    "darkred": "#8b0000",
    "darksalmon": "#e9967a",
    "darkseagreen": "#8fbc8f",
    "darkslateblue": "#483d8b",
    "darkslategray": "#2f4f4f",
    "darkslategrey": "#2f4f4f",
    "darkturquoise": "#00ced1",
    "darkviolet": "#9400d3",
    "deeppink": "#ff1493",
    "deepskyblue": "#00bfff",
    "dimgray": "#696969",
    "dimgrey": "#696969",
    "dodgerblue": "#1e90ff",
    "firebrick": "#b22222",
    "floralwhite": "#fffaf0",
    "forestgreen": "#228b22",
    "fuchsia": "#ff00ff",
    "gainsboro": "#dcdcdc",
    "ghostwhite": "#f8f8ff",
    "gold": "#ffd700",
    "goldenrod": "#daa520",
    "gray": "#808080",
    "green": "#008000",
    "greenyellow": "#adff2f",
    "grey": "#808080",
    "honeydew": "#f0fff0",
    "hotpink": "#ff69b4",
    "indianred": "#cd5c5c",
    "indigo": "#4b0082",
    "ivory": "#fffff0",
    "khaki": "#f0e68c",
    "lavender": "#e6e6fa",
    "lavenderblush": "#fff0f5",
    "lawngreen": "#7cfc00",
    "lemonchiffon": "#fffacd",
    "lightblue": "#add8e6",
    "lightcoral": "#f08080",
    "lightcyan": "#e0ffff",
    "lightgoldenrodyellow": "#fafad2",
    "lightgray": "#d3d3d3",
    "lightgreen": "#90ee90",
    "lightgrey": "#d3d3d3",
    "lightpink": "#ffb6c1",
    "lightsalmon": "#ffa07a",
    "lightseagreen": "#20b2aa",
    "lightskyblue": "#87cefa",
    "lightslategray": "#778899",
    "lightslategrey": "#778899",
    "lightsteelblue": "#b0c4de",
    "lightyellow": "#ffffe0",
    "lime": "#00ff00",
    "limegreen": "#32cd32",
    "linen": "#faf0e6",
    "magenta": "#ff00ff",
    "maroon": "#800000",
    "mediumaquamarine": "#66cdaa",
    "mediumblue": "#0000cd",
    "mediumorchid": "#ba55d3",
    "mediumpurple": "#9370db",
    "mediumseagreen": "#3cb371",
    "mediumslateblue": "#7b68ee",
    "mediumspringgreen": "#00fa9a",
    "mediumturquoise": "#48d1cc",
    "mediumvioletred": "#c71585",
    "midnightblue": "#191970",
    "mintcream": "#f5fffa",
    "mistyrose": "#ffe4e1",
    "moccasin": "#ffe4b5",
    "navajowhite": "#ffdead",
    "navy": "#000080",
    "oldlace": "#fdf5e6",
    "olive": "#808000",
    "olivedrab": "#6b8e23",
    "orange": "#ffa500",
    "orangered": "#ff4500",
    "orchid": "#da70d6",
    "palegoldenrod": "#eee8aa",
    "palegreen": "#98fb98",
    "paleturquoise": "#afeeee",
    "palevioletred": "#db7093",
    "papayawhip": "#ffefd5",
    "peachpuff": "#ffdab9",
    "peru": "#cd853f",
    "pink": "#ffc0cb",
    "plum": "#dda0dd",
    "powderblue": "#b0e0e6",
    "purple": "#800080",
    "rebeccapurple": "#663399",
    "red": "#ff0000",
    "rosybrown": "#bc8f8f",
    "royalblue": "#4169e1",
    "saddlebrown": "#8b4513",
    "salmon": "#fa8072",
    "sandybrown": "#f4a460",
    "seagreen": "#2e8b57",
    "seashell": "#fff5ee",
    "sienna": "#a0522d",
    "silver": "#c0c0c0",
    "skyblue": "#87ceeb",
    "slateblue": "#6a5acd",
    "slategray": "#708090",
    "slategrey": "#708090",
    "snow": "#fffafa",
    "springgreen": "#00ff7f",
    "steelblue": "#4682b4",
    "tan": "#d2b48c",
    "teal": "#008080",
    "thistle": "#d8bfd8",
    "tomato": "#ff6347",
    "turquoise": "#40e0d0",
    "violet": "#ee82ee",
    "wheat": "#f5deb3",
    "whitesmoke": "#f5f5f5",
    "yellow": "#ffff00",
    "yellowgreen": "#9acd32"
}

//Setup

function setupGame() {
    setActiveColor();
}

//Scripts

function getRandomColor() {
    var color;
    var count = 0;
    for (var prop in colors)
        if (Math.random() < 1 / ++count)
            color = prop;
    return color;
}

function setActiveColor() {
    colorName = getRandomColor();
    document.getElementById("user-guess").value = "";
    document.getElementById("game-canvas").style.backgroundColor = colors[colorName];
    document.getElementById("confirm-btn").style.backgroundColor = colors[colorName];
    document.getElementById("color-hex").innerHTML = colors[colorName];
}

function goodGuess() {
    console.log("success!");
}

function badGuess() {
    console.log("fail!");
}

function checkGuess() {
    var userGuess = String(document.getElementById("user-guess").value);
    userGuess = userGuess.toLowerCase().replace(/\s/g,'');
    console.log(userGuess);
    if (userGuess === colorName) {
        goodGuess();
    }
    else {
        badGuess();
    }
    setActiveColor();
}<|endoftext|>