<commit_before>'use strict';

/*
* The original C++ code and copyright notice is from the [Boost library]{http://www.boost.org/doc/libs/1_52_0/boost/math/special_functions/beta.hpp}.
*
* The implementation has been modified for JavaScript.
*/

/*
* (C) Copyright John Maddock 2006.
* Use, modification and distribution are subject to the
* Boost Software License, Version 1.0. (See accompanying file
* LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt)
*/

// MODULES //

var abs = require( '@stdlib/math/base/special/abs' );
var exp = require( '@stdlib/math/base/special/exp' );
var evalrational = require( '@stdlib/math/base/tools/evalrational' ).factory;
var gamma = require( '@stdlib/math/base/special/gamma' );
var log1p = require( '@stdlib/math/base/special/log1p' );
var pow = require( '@stdlib/math/base/special/pow' );
var sqrt = require( '@stdlib/math/base/special/sqrt' );
var isnan = require( '@stdlib/math/base/utils/is-nan' );

// CONSTANTS //

var E = require( '@stdlib/math/constants/float64-e' );
var EPSILON = require( '@stdlib/math/constants/float64-eps' );

// LANCZOS APPROXIMATION CONSTANTS //

var G = 10.90051099999999983936049829935654997826;
var NUM = [
	709811.662581657956893540610814842699825,
	679979.847415722640161734319823103390728,
	293136.785721159725251629480984140341656,
	74887.5403291467179935942448101441897121,
	12555.29058241386295096255111537516768137,
	1443.42992444170669746078056942194198252,
	115.2419459613734722083208906727972935065,
	6.30923920573262762719523981992008976989,
	0.2266840463022436475495508977579735223818,
	0.004826466289237661857584712046231435101741,
	0.4624429436045378766270459638520555557321e-4
];
var DENOM = [
	0,
	362880,
	1026576,
	1172700,
	723680,
	269325,
	63273,
	9450,
	870,
	45,
	1
];

// FUNCTIONS //

/**
* Calculate the Lanczos approximation scaled by exp(G).
*
* @private
* @param {number} z - input value
* @returns {number} Lanczos approximation
*/
var lanczos_sum_expG_scaled = evalrational( NUM, DENOM );

// BETA //

/**
* Evaluate the beta function.
*
* @param {NonNegativeNumber} x - input value
* @param {NonNegativeNumber} y - input value
* @returns {number} evaluated beta function
*
* @example
* var v = beta( 0, 0 );
* // returns Number.POSITIVE_INFINITY
* @example
* var v = beta( 1, 1 );
* // returns 1
* @example
* var v = beta( -1, 2 );
* // return NaN
* @example
* var v = beta( 5, 0.2 );
* // returns ~3.382
* @example
* var v = beta( 4, 1 );
* // returns 0.25
* @example
* var v = beta( NaN, 2 );
* // returns NaN
*/
function beta( a, b ) {
	var prefix = 1;
	var result;
	var ambh;
	var tmp;
	var agh;
	var bgh;
	var cgh;
	var c;

	c = a + b;
	if ( isnan( a ) || isnan( b ) ) {
		return NaN;
	}
	if ( a < 0.0 || b < 0.0 ) {
		return NaN;
	}
	if ( b === 1.0 ) {
		return 1.0 / a;
	} else if( a === 1.0 ) {
		return 1.0 / b;
	}

	// Special cases:
	if ( (c === a) && (b < EPSILON) ) {
		return gamma( b );
	} else if ( (c === b) && (a < EPSILON) ) {
		return gamma( a );
	}

	// Shift to a and b > 1 if required:
	if ( a < 1.0 ) {
		prefix *= c / a;
		c += 1.0;
		a += 1.0;
	}
	if ( b < 1.0 ) {
		prefix *= c / b;
		c += 1.0;
		b += 1.0;
	}
	if ( a < b ) {
		// Swap a and b:
		tmp = b;
		b = a;
		a = tmp;
	}

	// Lanczos calculation:
	agh = a + G - 0.5;
	bgh = b + G - 0.5;
	cgh = c + G - 0.5;
	result = lanczos_sum_expG_scaled( a ) * lanczos_sum_expG_scaled( b ) / lanczos_sum_expG_scaled( c );
	ambh = a - 0.5 - b;
	if( ( abs( b * ambh ) < (cgh * 100) ) && (a > 100) ) {
	// Special case where the base of the power term is close to 1
	// compute (1+x)^y instead:
	result *= exp( ambh * log1p( -b / cgh ) );
	} else {
		result *= pow( agh / cgh, a - 0.5 - b );
	}
	if ( cgh > 1e10 ) {
		// This avoids possible overflow, but appears to be marginally less accurate:
		result *= pow( (agh / cgh) * (bgh / cgh), b);
	} else {
		result *= pow((agh * bgh) / (cgh * cgh), b);
	}
	result *= sqrt( E / bgh);

	// If a and b were originally less than 1 we need to scale the result:
	result *= prefix;
	return result;
} // end FUNCTION beta()

// EXPORTS //

module.exports = beta;
<commit_msg>Improve code style<commit_after>'use strict';

/*
* The original C++ code and copyright notice is from the [Boost library]{http://www.boost.org/doc/libs/1_52_0/boost/math/special_functions/beta.hpp}.
*
* The implementation has been modified for JavaScript.
*/

/*
* (C) Copyright John Maddock 2006.
* Use, modification and distribution are subject to the
* Boost Software License, Version 1.0. (See accompanying file
* LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt)
*/

// MODULES //

var evalrational = require( '@stdlib/math/base/tools/evalrational' ).factory;
var gamma = require( '@stdlib/math/base/special/gamma' );
var isnan = require( '@stdlib/math/base/utils/is-nan' );
var log1p = require( '@stdlib/math/base/special/log1p' );
var sqrt = require( '@stdlib/math/base/special/sqrt' );
var abs = require( '@stdlib/math/base/special/abs' );
var exp = require( '@stdlib/math/base/special/exp' );
var pow = require( '@stdlib/math/base/special/pow' );

// CONSTANTS //

var E = require( '@stdlib/math/constants/float64-e' );
var EPSILON = require( '@stdlib/math/constants/float64-eps' );

// LANCZOS APPROXIMATION CONSTANTS //

var G = 10.90051099999999983936049829935654997826;
var NUM = [
	709811.662581657956893540610814842699825,
	679979.847415722640161734319823103390728,
	293136.785721159725251629480984140341656,
	74887.5403291467179935942448101441897121,
	12555.29058241386295096255111537516768137,
	1443.42992444170669746078056942194198252,
	115.2419459613734722083208906727972935065,
	6.30923920573262762719523981992008976989,
	0.2266840463022436475495508977579735223818,
	0.004826466289237661857584712046231435101741,
	0.4624429436045378766270459638520555557321e-4
];
var DENOM = [
	0,
	362880,
	1026576,
	1172700,
	723680,
	269325,
	63273,
	9450,
	870,
	45,
	1
];

// FUNCTIONS //

/**
* Calculate the Lanczos approximation scaled by exp(G).
*
* @private
* @param {number} z - input value
* @returns {number} Lanczos approximation
*/
var lanczos_sum_expG_scaled = evalrational( NUM, DENOM );

// BETA //

/**
* Evaluate the beta function.
*
* @param {NonNegativeNumber} x - input value
* @param {NonNegativeNumber} y - input value
* @returns {number} evaluated beta function
*
* @example
* var v = beta( 0, 0 );
* // returns Number.POSITIVE_INFINITY
* @example
* var v = beta( 1, 1 );
* // returns 1
* @example
* var v = beta( -1, 2 );
* // return NaN
* @example
* var v = beta( 5, 0.2 );
* // returns ~3.382
* @example
* var v = beta( 4, 1 );
* // returns 0.25
* @example
* var v = beta( NaN, 2 );
* // returns NaN
*/
function beta( a, b ) {
	var prefix;
	var ambh;
	var agh;
	var bgh;
	var cgh;
	var res;
	var tmp;
	var c;

	prefix = 1;
	c = a + b;
	if ( isnan( a ) || isnan( b ) ) {
		return NaN;
	}
	if ( a < 0.0 || b < 0.0 ) {
		return NaN;
	}
	if ( b === 1.0 ) {
		return 1.0 / a;
	} else if( a === 1.0 ) {
		return 1.0 / b;
	}

	// Special cases:
	if ( c === a && b < EPSILON ) {
		return gamma( b );
	} else if ( c === b && a < EPSILON ) {
		return gamma( a );
	}

	// Shift to a and b > 1 if required:
	if ( a < 1.0 ) {
		prefix *= c / a;
		c += 1.0;
		a += 1.0;
	}
	if ( b < 1.0 ) {
		prefix *= c / b;
		c += 1.0;
		b += 1.0;
	}
	if ( a < b ) {
		// Swap a and b:
		tmp = b;
		b = a;
		a = tmp;
	}

	// Lanczos calculation:
	agh = a + G - 0.5;
	bgh = b + G - 0.5;
	cgh = c + G - 0.5;
	res = lanczos_sum_expG_scaled( a ) * lanczos_sum_expG_scaled( b ) / lanczos_sum_expG_scaled( c );
	ambh = a - 0.5 - b;
	if ( abs( b * ambh ) < ( cgh * 100 ) && a > 100 ) {
		// Special case where the base of the power term is close to 1
		// compute (1+x)^y instead:
		res *= exp( ambh * log1p( -b / cgh ) );
	} else {
		res *= pow( agh / cgh, a - 0.5 - b );
	}
	if ( cgh > 1e10 ) {
		// This avoids possible overflow, but appears to be marginally less accurate:
		res *= pow( (agh / cgh) * (bgh / cgh), b);
	} else {
		res *= pow((agh * bgh) / (cgh * cgh), b);
	}
	res *= sqrt( E / bgh);
	// If a and b were originally less than 1 we need to scale the result:
	res *= prefix;
	return res;
} // end FUNCTION beta()

// EXPORTS //

module.exports = beta;
<|endoftext|>


<commit_before>// aurelia-i18n-loader
// an implementation of an i18next Backend that uses the aurelia loader to load the json translation files
// based on i18next-xhr-backend
//
// usage:
// aurelia.use.plugin('aurelia-i18n', (instance) => {
//    // register backend plugin
//    instance.i18next.use(Backend.with(aurelia.loader));

export class Backend {
  static loader = null; // static loader to support passing the aurelia-loader

  static with(loader) {
    this.loader = loader;
    return this;
  }

  constructor(services, options = {}) {
    this.init(services, options);
    this.type = 'backend';
  }

  init(services, options = {}) {
    this.services = services;
    this.options = defaults(options, this.options || {}, getDefaults());
  }

  readMulti(languages, namespaces, callback) {
    let loadPath = this.options.loadPath;

    if (typeof this.options.loadPath === 'function') {
      loadPath = this.options.loadPath(languages, namespaces);
    }

    let url = this.services.interpolator.interpolate(loadPath, { lng: languages.join('+'), ns: namespaces.join('+') });

    this.loadUrl(url, callback);
  }

  read(language, namespace, callback) {
    let loadPath = this.options.loadPath;

    if (typeof this.options.loadPath === 'function') {
      loadPath = this.options.loadPath([language], [namespace]);
    }

    let url = this.services.interpolator.interpolate(loadPath, { lng: language, ns: namespace });

    this.loadUrl(url, callback);
  }

  loadUrl(url, callback) {
    this.constructor.loader.loadText(url)
    .then(response=>{
      let ret;
      let err;
      try {
        ret = this.options.parse(response, url);
      } catch (e) {
        err = 'failed parsing ' + url + ' to json';
      }
      if (err) return callback(err, false);
      callback(null, ret);
    },
    response=>{
      return callback('failed loading ' + url, false /* no retry */);
    });
  }

  create(languages, namespace, key, fallbackValue) {
    // create is not (yet) supported
  }
}

Backend.type = 'backend';
export default Backend;

// helper functions
let arr = [];
let each = arr.forEach;
let slice = arr.slice;

function getDefaults() {
  return {
    loadPath: '/locales/{{lng}}/{{ns}}.json',
    addPath: 'locales/add/{{lng}}/{{ns}}',
    allowMultiLoading: false,
    parse: JSON.parse
  };
}

function defaults(obj) {
  each.call(slice.call(arguments, 1), function(source) {
    if (source) {
      for (let prop in source) {
        if (obj[prop] === undefined) obj[prop] = source[prop];
      }
    }
  });
  return obj;
}
<commit_msg>fix(aurelia-loader): don't try to parse translation json if already parsed<commit_after>// aurelia-i18n-loader
// an implementation of an i18next Backend that uses the aurelia loader to load the json translation files
// based on i18next-xhr-backend
//
// usage:
// aurelia.use.plugin('aurelia-i18n', (instance) => {
//    // register backend plugin
//    instance.i18next.use(Backend.with(aurelia.loader));

export class Backend {
  static loader = null; // static loader to support passing the aurelia-loader

  static with(loader) {
    this.loader = loader;
    return this;
  }

  constructor(services, options = {}) {
    this.init(services, options);
    this.type = 'backend';
  }

  init(services, options = {}) {
    this.services = services;
    this.options = defaults(options, this.options || {}, getDefaults());
  }

  readMulti(languages, namespaces, callback) {
    let loadPath = this.options.loadPath;

    if (typeof this.options.loadPath === 'function') {
      loadPath = this.options.loadPath(languages, namespaces);
    }

    let url = this.services.interpolator.interpolate(loadPath, { lng: languages.join('+'), ns: namespaces.join('+') });

    this.loadUrl(url, callback);
  }

  read(language, namespace, callback) {
    let loadPath = this.options.loadPath;

    if (typeof this.options.loadPath === 'function') {
      loadPath = this.options.loadPath([language], [namespace]);
    }

    let url = this.services.interpolator.interpolate(loadPath, { lng: language, ns: namespace });

    this.loadUrl(url, callback);
  }

  loadUrl(url, callback) {
    this.constructor.loader.loadText(url)
    .then(response=>{
      let ret;
      let err;
      try {
        ret = (response instanceof Object) ? response : this.options.parse(response, url);
      } catch (e) {
        err = 'failed parsing ' + url + ' to json';
      }
      if (err) return callback(err, false);
      callback(null, ret);
    },
    response=>{
      return callback('failed loading ' + url, false /* no retry */);
    });
  }

  create(languages, namespace, key, fallbackValue) {
    // create is not (yet) supported
  }
}

Backend.type = 'backend';
export default Backend;

// helper functions
let arr = [];
let each = arr.forEach;
let slice = arr.slice;

function getDefaults() {
  return {
    loadPath: '/locales/{{lng}}/{{ns}}.json',
    addPath: 'locales/add/{{lng}}/{{ns}}',
    allowMultiLoading: false,
    parse: JSON.parse
  };
}

function defaults(obj) {
  each.call(slice.call(arguments, 1), function(source) {
    if (source) {
      for (let prop in source) {
        if (obj[prop] === undefined) obj[prop] = source[prop];
      }
    }
  });
  return obj;
}
<|endoftext|>


<commit_before>// @flow
/*
 * The main renderer. Holds the global store. When it changes we send it to the main thread which then sends it out to subscribers
 */

import Main from '../../main.desktop'
import React from 'react'
import ReactDOM from 'react-dom'
import RemoteManager from './remote-manager'
import Root from './container'
import configureStore from '../../store/configure-store'
import electron, {ipcRenderer} from 'electron'
import engine, {makeEngine} from '../../engine'
import hello from '../../util/hello'
import injectTapEventPlugin from 'react-tap-event-plugin'
import loadPerf from '../../util/load-perf'
import routeDefs from '../../routes'
import {AppContainer} from 'react-hot-loader'
import {bootstrap} from '../../actions/config'
import {changedFocus} from '../../actions/window'
import {devEditAction} from '../../reducers/dev-edit'
import {disable as disableDragDrop} from '../../util/drag-drop'
import {getUserImageMap, loadUserImageMap} from '../../util/pictures'
import {GlobalEscapeHandler} from '../../util/escape-handler'
import {initAvatarLookup, initAvatarLoad} from '../../common-adapters'
import {listenForNotifications} from '../../actions/notifications'
import {merge, throttle} from 'lodash'
import {reduxDevToolsEnable, devStoreChangingFunctions, resetEngineOnHMR} from '../../local-debug.desktop'
import {selector as menubarSelector} from '../../menubar'
import {selector as pineentrySelector} from '../../pinentry'
import {selector as remotePurgeMessageSelector} from '../../pgp/container.desktop'
import {selector as unlockFoldersSelector} from '../../unlock-folders'
import {setRouteDef} from '../../actions/route-tree'
import {setupContextMenu} from '../app/menu-helper'
import {setupSource} from '../../util/forward-logs'
import {updateDebugConfig} from '../../actions/dev'
import {updateReloading} from '../../constants/dev'

let _store
function setupStore () {
  if (!_store) {
    _store = configureStore()
  }
  return _store
}

function setupAvatar () {
  initAvatarLookup(getUserImageMap)
  initAvatarLoad(loadUserImageMap)
}

function setupApp (store) {
  setupSource()
  disableDragDrop()
  makeEngine()
  loadPerf()
  setupAvatar()

  if (devStoreChangingFunctions) {
    window.devEdit = (path, value) => store.dispatch(devEditAction(path, value))
  }

  if (__DEV__ && process.env.KEYBASE_LOCAL_DEBUG) {
    require('devtron').install()
  }

  setupContextMenu(electron.remote.getCurrentWindow())

  // Used by material-ui widgets.
  if (module.hot) {
    // Don't reload this thing if we're hot reloading
    if (module.hot.data === undefined) {
      injectTapEventPlugin()
    }
  } else {
    injectTapEventPlugin()
  }

  ipcRenderer.on('dispatchAction', (event, action) => {
    // we MUST convert this else we'll run into issues with redux. See https://github.com/rackt/redux/issues/830
    // This is because this is touched due to the remote proxying. We get a __proto__ which causes the _.isPlainObject check to fail. We use
    // _.merge() to get a plain object back out which we can send
    setImmediate(() => {
      try {
        store.dispatch(merge({}, action))
      } catch (_) {
      }
    })
  })

  // Run installer
  ipcRenderer.on('installed', (event, message) => {
    store.dispatch({payload: undefined, type: 'config:readyForBootstrap'})
    store.dispatch(bootstrap())
  })
  ipcRenderer.send('install-check')

  const currentWindow = electron.remote.getCurrentWindow()
  currentWindow.on('focus', () => { store.dispatch(changedFocus(true)) })
  currentWindow.on('blur', () => { store.dispatch(changedFocus(false)) })

  const _menubarSelector = menubarSelector()
  const _unlockFoldersSelector = unlockFoldersSelector()
  const _pineentrySelector = pineentrySelector()
  const _remotePurgeMessageSelector = remotePurgeMessageSelector()

  const subsetsRemotesCareAbout = (store) => {
    return {
      tracker: store.tracker,
      menu: _menubarSelector(store),
      unlockFolder: _unlockFoldersSelector(store),
      pinentry: _pineentrySelector(store),
      pgpPurgeMessage: _remotePurgeMessageSelector(store),
    }
  }

  let _currentStore
  store.subscribe(throttle(() => {
    let previousStore = _currentStore
    _currentStore = subsetsRemotesCareAbout(store.getState())

    if (JSON.stringify(previousStore) !== JSON.stringify(_currentStore)) {
      ipcRenderer.send('stateChange', store.getState())
    }
  }, 1000))

  // Handle notifications from the service
  store.dispatch(listenForNotifications())

  // Introduce ourselves to the service
  hello(process.pid, 'Main Renderer', process.argv, __VERSION__, true) // eslint-disable-line no-undef

  store.dispatch(updateDebugConfig(require('../../local-debug-live')))
}

const FontLoader = () => (

kb

source code pro 400

source code pro 600

open sans 400

open sans 400 i

open sans 600

open sans 600 i

open sans 700

)

function render (store, MainComponent) {
  let dt
  if (__DEV__ && reduxDevToolsEnable) { // eslint-disable-line no-undef
    const DevTools = require('./redux-dev-tools').default
    dt = <DevTools />
  }

  ReactDOM.render((
    <AppContainer>
      <Root store={store}>
        <GlobalEscapeHandler>

            <RemoteManager />
            <FontLoader />
            <MainComponent />
            {dt}

        </GlobalEscapeHandler>
      </Root>
    </AppContainer>), document.getElementById('root'))
}

function setupRoutes (store) {
  store.dispatch(setRouteDef(routeDefs))
}

function setupHMR (store) {
  if (!module || !module.hot || typeof module.hot.accept !== 'function') {
    return
  }

  module.hot && module.hot.accept(['../../main.desktop', '../../routes'], () => {
    store.dispatch(setRouteDef(require('../../routes').default))
    try {
      store.dispatch({type: updateReloading, payload: {reloading: true}})
      const NewMain = require('../../main.desktop').default
      render(store, NewMain)
      if (resetEngineOnHMR) {
        engine().reset()
      }
    } finally {
      setTimeout(() => store.dispatch({type: updateReloading, payload: {reloading: false}}), 10e3)
    }
  })

  module.hot && module.hot.accept('../../local-debug-live', () => {
    store.dispatch(updateDebugConfig(require('../../local-debug-live')))
  })
}

function load () {
  const store = setupStore()
  setupRoutes(store)
  setupApp(store)
  setupHMR(store)
  render(store, Main)
}

window.load = load
<commit_msg>Add DEBUGstore so we can inspect the store in devtools (#6358)<commit_after>// @flow
/*
 * The main renderer. Holds the global store. When it changes we send it to the main thread which then sends it out to subscribers
 */

import Main from '../../main.desktop'
import React from 'react'
import ReactDOM from 'react-dom'
import RemoteManager from './remote-manager'
import Root from './container'
import configureStore from '../../store/configure-store'
import electron, {ipcRenderer} from 'electron'
import engine, {makeEngine} from '../../engine'
import hello from '../../util/hello'
import injectTapEventPlugin from 'react-tap-event-plugin'
import loadPerf from '../../util/load-perf'
import routeDefs from '../../routes'
import {AppContainer} from 'react-hot-loader'
import {bootstrap} from '../../actions/config'
import {changedFocus} from '../../actions/window'
import {devEditAction} from '../../reducers/dev-edit'
import {disable as disableDragDrop} from '../../util/drag-drop'
import {getUserImageMap, loadUserImageMap} from '../../util/pictures'
import {GlobalEscapeHandler} from '../../util/escape-handler'
import {initAvatarLookup, initAvatarLoad} from '../../common-adapters'
import {listenForNotifications} from '../../actions/notifications'
import {merge, throttle} from 'lodash'
import {reduxDevToolsEnable, devStoreChangingFunctions, resetEngineOnHMR} from '../../local-debug.desktop'
import {selector as menubarSelector} from '../../menubar'
import {selector as pineentrySelector} from '../../pinentry'
import {selector as remotePurgeMessageSelector} from '../../pgp/container.desktop'
import {selector as unlockFoldersSelector} from '../../unlock-folders'
import {setRouteDef} from '../../actions/route-tree'
import {setupContextMenu} from '../app/menu-helper'
import {setupSource} from '../../util/forward-logs'
import flags from '../../util/feature-flags'
import {updateDebugConfig} from '../../actions/dev'
import {updateReloading} from '../../constants/dev'

let _store
function setupStore () {
  if (!_store) {
    _store = configureStore()

    if (flags.admin) {
      window.DEBUGStore = _store
    }
  }

  return _store
}

function setupAvatar () {
  initAvatarLookup(getUserImageMap)
  initAvatarLoad(loadUserImageMap)
}

function setupApp (store) {
  setupSource()
  disableDragDrop()
  makeEngine()
  loadPerf()
  setupAvatar()

  if (devStoreChangingFunctions) {
    window.devEdit = (path, value) => store.dispatch(devEditAction(path, value))
  }

  if (__DEV__ && process.env.KEYBASE_LOCAL_DEBUG) {
    require('devtron').install()
  }

  setupContextMenu(electron.remote.getCurrentWindow())

  // Used by material-ui widgets.
  if (module.hot) {
    // Don't reload this thing if we're hot reloading
    if (module.hot.data === undefined) {
      injectTapEventPlugin()
    }
  } else {
    injectTapEventPlugin()
  }

  ipcRenderer.on('dispatchAction', (event, action) => {
    // we MUST convert this else we'll run into issues with redux. See https://github.com/rackt/redux/issues/830
    // This is because this is touched due to the remote proxying. We get a __proto__ which causes the _.isPlainObject check to fail. We use
    // _.merge() to get a plain object back out which we can send
    setImmediate(() => {
      try {
        store.dispatch(merge({}, action))
      } catch (_) {
      }
    })
  })

  // Run installer
  ipcRenderer.on('installed', (event, message) => {
    store.dispatch({payload: undefined, type: 'config:readyForBootstrap'})
    store.dispatch(bootstrap())
  })
  ipcRenderer.send('install-check')

  const currentWindow = electron.remote.getCurrentWindow()
  currentWindow.on('focus', () => { store.dispatch(changedFocus(true)) })
  currentWindow.on('blur', () => { store.dispatch(changedFocus(false)) })

  const _menubarSelector = menubarSelector()
  const _unlockFoldersSelector = unlockFoldersSelector()
  const _pineentrySelector = pineentrySelector()
  const _remotePurgeMessageSelector = remotePurgeMessageSelector()

  const subsetsRemotesCareAbout = (store) => {
    return {
      tracker: store.tracker,
      menu: _menubarSelector(store),
      unlockFolder: _unlockFoldersSelector(store),
      pinentry: _pineentrySelector(store),
      pgpPurgeMessage: _remotePurgeMessageSelector(store),
    }
  }

  let _currentStore
  store.subscribe(throttle(() => {
    let previousStore = _currentStore
    _currentStore = subsetsRemotesCareAbout(store.getState())

    if (JSON.stringify(previousStore) !== JSON.stringify(_currentStore)) {
      ipcRenderer.send('stateChange', store.getState())
    }
  }, 1000))

  // Handle notifications from the service
  store.dispatch(listenForNotifications())

  // Introduce ourselves to the service
  hello(process.pid, 'Main Renderer', process.argv, __VERSION__, true) // eslint-disable-line no-undef

  store.dispatch(updateDebugConfig(require('../../local-debug-live')))
}

const FontLoader = () => (

kb

source code pro 400

source code pro 600

open sans 400

open sans 400 i

open sans 600

open sans 600 i

open sans 700

)

function render (store, MainComponent) {
  let dt
  if (__DEV__ && reduxDevToolsEnable) { // eslint-disable-line no-undef
    const DevTools = require('./redux-dev-tools').default
    dt = <DevTools />
  }

  ReactDOM.render((
    <AppContainer>
      <Root store={store}>
        <GlobalEscapeHandler>

            <RemoteManager />
            <FontLoader />
            <MainComponent />
            {dt}

        </GlobalEscapeHandler>
      </Root>
    </AppContainer>), document.getElementById('root'))
}

function setupRoutes (store) {
  store.dispatch(setRouteDef(routeDefs))
}

function setupHMR (store) {
  if (!module || !module.hot || typeof module.hot.accept !== 'function') {
    return
  }

  module.hot && module.hot.accept(['../../main.desktop', '../../routes'], () => {
    store.dispatch(setRouteDef(require('../../routes').default))
    try {
      store.dispatch({type: updateReloading, payload: {reloading: true}})
      const NewMain = require('../../main.desktop').default
      render(store, NewMain)
      if (resetEngineOnHMR) {
        engine().reset()
      }
    } finally {
      setTimeout(() => store.dispatch({type: updateReloading, payload: {reloading: false}}), 10e3)
    }
  })

  module.hot && module.hot.accept('../../local-debug-live', () => {
    store.dispatch(updateDebugConfig(require('../../local-debug-live')))
  })
}

function load () {
  const store = setupStore()
  setupRoutes(store)
  setupApp(store)
  setupHMR(store)
  render(store, Main)
}

window.load = load
<|endoftext|>


<commit_before>define([],function(){
    var KEY = "_id";
    var BID = "*#*";
    var ClientCommitInfo = function(parameters){
        var refreshId = setInterval(refreshCommits,parameters.refreshrate),
            storage = parameters.storage,
            commits = {};

        var getCommitList = function(){
            var returnlist = [];
            for(var i in commits){
                returnlist.push(i);
            }
            return returnlist;
        };
        var getCommitObj = function(commitid){
            return commits[commitid];
        };
        var getAllCommits = function(){
            var returnlist = [];
            for(var i in commits){
                returnlist.push(commits[i]);
            }
            return returnlist;
        };

        var refreshCommits = function(callback){
            callback = callback || function(){};
            storage.find({type:'commit'},function(err,findobjects){
                if(err){
                    console.log("cannot update commit list due to: "+err);
                } else {
                    commits={};
                    for(var i=0;i<findobjects.length;i++){
                        commits[findobjects[i][KEY]] = findobjects[i];
                    }
                }
                callback(err);
            });
        };

        var getAllCommitsNow = function(callback){
            callback = callback || function(){};
            refreshCommits(function(err){
                if(err){
                    callback(err,getAllCommits());
                } else {
                    callback(null,getAllCommits());
                }
            })
        };

        var produceCommitTimeline = function(commitid){
            var timeline = {};
            timeline[commitid] = 0;
            if(commits[commitid]){
                for(var i=0;i<commits[commitid].parents.length;i++){
                    var parentline = produceCommitTimeline(commits[commitid].parents[i]);
                    for(var j in parentline){
                        timeline[j] = parentline[j]+1;
                    }
                }
            }

            return timeline;
        };
        var getCommitDifference = function(commitid,callback){
            getAllCommitsNow(function(err,commitobjects){
                if(commits[commitid]){
                    storage.load(BID+commits[commitid].name,function(err,branch){
                       if(!err && branch){
                           //here comes the real counting
                           if(branch.commit === commitid){
                               callback(null,0);
                           } else {
                               //ok here comes the real counting...
                               var myline = produceCommitTimeline(commitid);
                               var serverline = produceCommitTimeline(branch.commit);
                               if(myline[branch.commit]){
                                   //we are ahead of the server
                                   callback(null,myline[branch.commit]);
                               } else {
                                   var mindist = null;
                                   var mincommit = null;
                                   for(var i in myline){
                                       if(serverline[i]){
                                           if(mindist === null || serverline[i]<mindist){
                                               mindist = serverline[i];
                                               mincommit = i;
                                           }
                                       }
                                   }
                                   //we are behind the server...
                                   callback(null,(-1)*mindist);
                               }
                           }
                       } else {
                           callback('no branch info is available');
                       }
                    });
                } else {
                    callback('commit not found');
                }
            });
        };

        return {
            getCommitList : getCommitList,
            getCommitObj : getCommitObj,
            getAllCommits : getAllCommits,
            getAllCommitsNow : getAllCommitsNow,
            getCommitDifference : getCommitDifference
        }
    };
    return ClientCommitInfo;
});
<commit_msg>refreshing have been corrected<commit_after>define([],function(){
    var KEY = "_id";
    var BID = "*#*";
    var ClientCommitInfo = function(parameters){
        var refreshId = null,
            storage = parameters.storage,
            commits = {};

        var getCommitList = function(){
            var returnlist = [];
            for(var i in commits){
                returnlist.push(i);
            }
            return returnlist;
        };
        var getCommitObj = function(commitid){
            return commits[commitid];
        };
        var getAllCommits = function(){
            var returnlist = [];
            for(var i in commits){
                returnlist.push(commits[i]);
            }
            return returnlist;
        };

        var refreshCommits = function(callback){
            callback = callback || function(){};
            storage.find({type:'commit'},function(err,findobjects){
                if(err){
                    console.log("cannot update commit list due to: "+err);
                } else {
                    commits={};
                    for(var i=0;i<findobjects.length;i++){
                        commits[findobjects[i][KEY]] = findobjects[i];
                    }
                }
                callback(err);
            });
        };

        var getAllCommitsNow = function(callback){
            callback = callback || function(){};
            refreshCommits(function(err){
                if(err){
                    callback(err,getAllCommits());
                } else {
                    callback(null,getAllCommits());
                }
            })
        };

        var produceCommitTimeline = function(commitid){
            var timeline = {};
            timeline[commitid] = 0;
            if(commits[commitid]){
                for(var i=0;i<commits[commitid].parents.length;i++){
                    var parentline = produceCommitTimeline(commits[commitid].parents[i]);
                    for(var j in parentline){
                        timeline[j] = parentline[j]+1;
                    }
                }
            }

            return timeline;
        };
        var getCommitDifference = function(commitid,callback){
            getAllCommitsNow(function(err,commitobjects){
                if(commits[commitid]){
                    storage.load(BID+commits[commitid].name,function(err,branch){
                       if(!err && branch){
                           //here comes the real counting
                           if(branch.commit === commitid){
                               callback(null,0);
                           } else {
                               //ok here comes the real counting...
                               var myline = produceCommitTimeline(commitid);
                               var serverline = produceCommitTimeline(branch.commit);
                               if(myline[branch.commit]){
                                   //we are ahead of the server
                                   callback(null,myline[branch.commit]);
                               } else {
                                   var mindist = null;
                                   var mincommit = null;
                                   for(var i in myline){
                                       if(serverline[i]){
                                           if(mindist === null || serverline[i]<mindist){
                                               mindist = serverline[i];
                                               mincommit = i;
                                           }
                                       }
                                   }
                                   //we are behind the server...
                                   callback(null,(-1)*mindist);
                               }
                           }
                       } else {
                           callback('no branch info is available');
                       }
                    });
                } else {
                    callback('commit not found');
                }
            });
        };

        refreshId = setInterval(refreshCommits,parameters.refreshrate);

        return {
            getCommitList : getCommitList,
            getCommitObj : getCommitObj,
            getAllCommits : getAllCommits,
            getAllCommitsNow : getAllCommitsNow,
            getCommitDifference : getCommitDifference
        }
    };
    return ClientCommitInfo;
});
<|endoftext|>


<commit_before>'use strict';

let checkInput = require('../bin/validator_tool').checkInput;
const UNKNOWN = 'Unknown';
const FASTA_MET_DEC_DATE_RE = /^\d{4}(\.\d{1,4})?$/;
const SOURCE_GENBANK = 1;
const SOURCE_FASTA = 2;

function stringifyGenes(geneList) {
  if (geneList && geneList.length > 0) {
    let genes = '';
    for (let i = 0; i < geneList.length; i++) {
      let gene = String(geneList[i].name).trim();
      genes += gene;
      if (i < geneList.length-1) {
        genes += ', ';
      }
    }
    return genes.trim();
  }
  else {
    return 'None';
  }
};

function humanizeLuceneDate(luceneDate) {
  if (luceneDate) {
    let date = String(luceneDate);
    if (date != "10000101") {
      if (date.length === 8) {
        let month = getMonth(date.substring(4,6));
        return  date.substring(6) + "-" + month + "-" + date.substring(0,4);
      }
      else if (date.length === 6) {
        let month = getMonth(date.substring(4));
        return month + "-" + date.substring(0,4);
      }
      else if (date.length === 4) {
        return date;
      }
      return date;
    }
  }
  return UNKNOWN;
};

function leapYear(year) {
  return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
};

function convertDecimalDate(decimalDate) {
  var year = parseInt(decimalDate);
  var reminder = decimalDate - year;
  if (reminder > 0){
    var daysPerYear = leapYear(year) ? 366 : 365;
    var miliseconds = reminder * daysPerYear * 24 * 60 * 60 * 1000;
    var yearDate = new Date(year, 0, 1);
    yearDate = new Date(yearDate.getTime() + miliseconds)
    var date = ("0" + yearDate.getDate()).slice(-2);
    return date + "-" + getMonth(yearDate.getMonth()+1) + "-" + year;
  } else {
    return "01" + "-" + "Jan" + "-" + year;
  }
}

function getMonth(numMonth) {
  numMonth = Number(numMonth);
  switch (numMonth) {
    case 1:
			return "Jan";
		case 2:
			return "Feb";
		case 3:
			return "Mar";
		case 4:
			return "Apr";
		case 5:
			return "May";
		case 6:
			return "Jun";
		case 7:
			return "Jul";
		case 8:
			return "Aug";
		case 9:
			return "Sep";
		case 10:
			return "Oct";
		case 11:
			return "Nov";
		case 12:
			return "Dec";
		default:
			return "__";
	}
};

function simplifyOrganism(rawOrganism) {
  let organism;
  if (rawOrganism) {
    organism = String(rawOrganism);
		let cutoff = organism.indexOf(";");
		if (cutoff === -1 || (organism.indexOf("/") < cutoff && organism.indexOf("/") > 0)) {
			cutoff = organism.indexOf("/");
		}
		if (cutoff === -1 || (organism.indexOf("Viruses") < cutoff && organism.indexOf("Viruses") > 0)) {
			cutoff = organism.indexOf("Viruses");
		}
		if (cutoff === -1 || (organism.indexOf(" virus") < cutoff && organism.indexOf(" virus") > 0)) {
			cutoff = organism.indexOf(" virus");
		}
		if (cutoff > 0) {
			return organism.substring(0, cutoff);
		}
	}
	return String(organism || UNKNOWN);
};

class LuceneRecord {

  constructor(searchApiRecord) {
    this.accession = String(searchApiRecord.accession);
    this.genes = stringifyGenes(searchApiRecord.genes);
    this.virus = simplifyOrganism(searchApiRecord.sequence.organism);
    this.luceneDate = String(searchApiRecord.sequence.collectionDate);
    this.date = humanizeLuceneDate(searchApiRecord.sequence.collectionDate);
    if(String(searchApiRecord.sequence.collectionDate) === String(searchApiRecord.sequence.date)){
      this.isCompleteDate = true;
    }else if(searchApiRecord.sequence.collectionDate != null){
      this.isCompleteDate = false;
    }else{
      this.isCompleteDate = true;
    }
    if (searchApiRecord.host) {
      this.host = String(searchApiRecord.host.name || UNKNOWN);
    }
    else {
      this.host = UNKNOWN;
    }
    if (searchApiRecord.geonameLocation) {
      this.country = String(searchApiRecord.geonameLocation.country || UNKNOWN);
      this.state = String(searchApiRecord.geonameLocation.state || UNKNOWN);
      this.location = String(searchApiRecord.geonameLocation.location || UNKNOWN);
      if((this.location.toLocaleLowerCase()) === (this.country.toLocaleLowerCase())){
        this.location = "Unknown";
      }
      this.geonameid = String(searchApiRecord.geonameLocation.geonameID || UNKNOWN);
      this.latitude = String(searchApiRecord.geonameLocation.latitude || UNKNOWN);
      this.longitude = String(searchApiRecord.geonameLocation.longitude || UNKNOWN);
    }
    else {
      this.country = UNKNOWN;
      this.state = UNKNOWN;
      this.location = UNKNOWN;
      this.geonameid = UNKNOWN;
      this.latitude = UNKNOWN;
      this.longitude = UNKNOWN;
    }
    this.segmentLength = Number(searchApiRecord.sequence.segmentLength);
    this.includeInJob = false;
    this.resourceSource = SOURCE_GENBANK;
  };

};

class SQLRecord {

  constructor(recordApiRecord) {
    this.accession = String(recordApiRecord.accession);
    this.date = String(recordApiRecord.sequence.collectionDate || UNKNOWN);
    if (recordApiRecord.publication) {
      this.pubmedID = String(recordApiRecord.publication.pubMedID || 'n/a');
    }
    else {
      this.pubmedID = 'n/a';
    }
    this.virus = String(recordApiRecord.sequence.organism || UNKNOWN);
    this.taxon = Number(recordApiRecord.sequence.taxID);
    this.strain = String(recordApiRecord.sequence.strain || UNKNOWN);
    this.isolate = String(recordApiRecord.sequence.isolate || UNKNOWN)
    if (recordApiRecord.host) {
      this.host = String(recordApiRecord.host.name || UNKNOWN);
      this.hostId = String(recordApiRecord.host.taxon || UNKNOWN);
    }
    else {
      this.host = UNKNOWN;
      this.hostId = UNKNOWN
    }
    if (recordApiRecord.geonameLocation) {
      this.geonameID = String(recordApiRecord.geonameLocation.geonameID || UNKNOWN);
      this.location = String(recordApiRecord.geonameLocation.location || UNKNOWN);
      this.latitude = String(recordApiRecord.geonameLocation.latitude || UNKNOWN);
      this.longitude = String(recordApiRecord.geonameLocation.longitude || UNKNOWN);
    }
    else {
        this.location = UNKNOWN;
    }
    this.genes = stringifyGenes(recordApiRecord.genes);
    this.definition = String(recordApiRecord.sequence.definition || UNKNOWN)
    if (recordApiRecord.possibleLocations) {
      var possibleLocations = [];
      for(var i=0; i<recordApiRecord.possibleLocations.length; i++){
        var possibleLocation = new PossibleLocation(recordApiRecord.possibleLocations[i]);
        possibleLocations.push(possibleLocation);
      }
      this.possibleLocations = possibleLocations;
    } else {
        this.possibleLocations = [];
    }
  };

};

class CustomRecord {
  constructor(searchApiRecord) {
    this.accession = String(searchApiRecord.accession);
    this.genes = UNKNOWN;
    this.virus = UNKNOWN;
    this.luceneDate = UNKNOWN;
    this.host = UNKNOWN;
    if(checkInput(searchApiRecord.collectionDate, 'string', FASTA_MET_DEC_DATE_RE)){
      this.date = convertDecimalDate(searchApiRecord.collectionDate);
    } else {
      this.date = searchApiRecord.collectionDate;
    }
    if (searchApiRecord.geonameLocation) {
      this.state = String(searchApiRecord.geonameLocation.state || UNKNOWN);
      this.country = String(searchApiRecord.geonameLocation.country || UNKNOWN);
      this.location = String(searchApiRecord.geonameLocation.location || UNKNOWN);
      this.geonameid = String(searchApiRecord.geonameLocation.geonameID || UNKNOWN);
      this.latitude = String(searchApiRecord.geonameLocation.latitude || UNKNOWN);
      this.longitude = String(searchApiRecord.geonameLocation.longitude || UNKNOWN);
    } else {
      this.state = UNKNOWN;
      this.country = UNKNOWN;
      this.location = UNKNOWN;
      this.geonameid = UNKNOWN;
      this.latitude = UNKNOWN;
      this.longitude = UNKNOWN;
    }
    this.segmentLength = Number(searchApiRecord.rawSequence.length);
    this.sequence =searchApiRecord.rawSequence;
    this.includeInJob = false;
    this.resourceSource = SOURCE_FASTA;
  };
};

class PossibleLocation {

  constructor(recordPossibleLocation) {
    this.geonameID = String(recordPossibleLocation.geonameID || UNKNOWN);
    this.location = String(recordPossibleLocation.location || UNKNOWN);
    this.latitude = String(recordPossibleLocation.latitude || UNKNOWN);
    this.longitude = String(recordPossibleLocation.longitude || UNKNOWN);
    this.probability = String(recordPossibleLocation.probability || UNKNOWN);
  };

};

module.exports = {
  LuceneRecord: LuceneRecord,
  SQLRecord: SQLRecord,
  CustomRecord: CustomRecord,
  PossibleLocation: PossibleLocation
};
<commit_msg>refactor date<commit_after>'use strict';

let checkInput = require('../bin/validator_tool').checkInput;
const UNKNOWN = 'Unknown';
const FASTA_MET_DEC_DATE_RE = /^\d{4}(\.\d{1,4})?$/;
const SOURCE_GENBANK = 1;
const SOURCE_FASTA = 2;

function stringifyGenes(geneList) {
  if (geneList && geneList.length > 0) {
    let genes = '';
    for (let i = 0; i < geneList.length; i++) {
      let gene = String(geneList[i].name).trim();
      genes += gene;
      if (i < geneList.length-1) {
        genes += ', ';
      }
    }
    return genes.trim();
  }
  else {
    return 'None';
  }
};

function humanizeLuceneDate(luceneDate) {
  if (luceneDate) {
    let date = String(luceneDate);
    if (date != "10000101") {
      if (date.length === 8) {
        let month = getMonth(date.substring(4,6));
        return  date.substring(6) + "-" + month + "-" + date.substring(0,4);
      }
      else if (date.length === 6) {
        let month = getMonth(date.substring(4));
        return month + "-" + date.substring(0,4);
      }
      else if (date.length === 4) {
        return date;
      }
      return date;
    }
  }
  return UNKNOWN;
};

function leapYear(year) {
  return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
};

function convertDecimalDate(decimalDate) {
  var year = parseInt(decimalDate);
  var reminder = decimalDate - year;
  if (reminder > 0){
    var daysPerYear = leapYear(year) ? 366 : 365;
    var miliseconds = reminder * daysPerYear * 24 * 60 * 60 * 1000;
    var yearDate = new Date(year, 0, 1);
    yearDate = new Date(yearDate.getTime() + miliseconds)
    var date = ("0" + yearDate.getDate()).slice(-2);
    return date + "-" + getMonth(yearDate.getMonth()+1) + "-" + year;
  } else {
    return "01" + "-" + "Jan" + "-" + year;
  }
}

function getMonth(numMonth) {
  numMonth = Number(numMonth);
  switch (numMonth) {
    case 1:
			return "Jan";
		case 2:
			return "Feb";
		case 3:
			return "Mar";
		case 4:
			return "Apr";
		case 5:
			return "May";
		case 6:
			return "Jun";
		case 7:
			return "Jul";
		case 8:
			return "Aug";
		case 9:
			return "Sep";
		case 10:
			return "Oct";
		case 11:
			return "Nov";
		case 12:
			return "Dec";
		default:
			return "__";
	}
};

function simplifyOrganism(rawOrganism) {
  let organism;
  if (rawOrganism) {
    organism = String(rawOrganism);
		let cutoff = organism.indexOf(";");
		if (cutoff === -1 || (organism.indexOf("/") < cutoff && organism.indexOf("/") > 0)) {
			cutoff = organism.indexOf("/");
		}
		if (cutoff === -1 || (organism.indexOf("Viruses") < cutoff && organism.indexOf("Viruses") > 0)) {
			cutoff = organism.indexOf("Viruses");
		}
		if (cutoff === -1 || (organism.indexOf(" virus") < cutoff && organism.indexOf(" virus") > 0)) {
			cutoff = organism.indexOf(" virus");
		}
		if (cutoff > 0) {
			return organism.substring(0, cutoff);
		}
	}
	return String(organism || UNKNOWN);
};

class LuceneRecord {

  constructor(searchApiRecord) {
    this.accession = String(searchApiRecord.accession);
    this.genes = stringifyGenes(searchApiRecord.genes);
    this.virus = simplifyOrganism(searchApiRecord.sequence.organism);
    this.luceneDate = String(searchApiRecord.sequence.collectionDate);
    this.date = humanizeLuceneDate(searchApiRecord.sequence.collectionDate);
    if(String(searchApiRecord.sequence.collectionDate) === String(searchApiRecord.sequence.unNormalizedDate)){
      this.isCompleteDate = true;
    }else if(searchApiRecord.sequence.collectionDate != null){
      this.isCompleteDate = false;
    }else{
      this.isCompleteDate = true;
    }
    if (searchApiRecord.host) {
      this.host = String(searchApiRecord.host.name || UNKNOWN);
    }
    else {
      this.host = UNKNOWN;
    }
    if (searchApiRecord.geonameLocation) {
      this.country = String(searchApiRecord.geonameLocation.country || UNKNOWN);
      this.state = String(searchApiRecord.geonameLocation.state || UNKNOWN);
      this.location = String(searchApiRecord.geonameLocation.location || UNKNOWN);
      if((this.location.toLocaleLowerCase()) === (this.country.toLocaleLowerCase())){
        this.location = "Unknown";
      }
      this.geonameid = String(searchApiRecord.geonameLocation.geonameID || UNKNOWN);
      this.latitude = String(searchApiRecord.geonameLocation.latitude || UNKNOWN);
      this.longitude = String(searchApiRecord.geonameLocation.longitude || UNKNOWN);
    }
    else {
      this.country = UNKNOWN;
      this.state = UNKNOWN;
      this.location = UNKNOWN;
      this.geonameid = UNKNOWN;
      this.latitude = UNKNOWN;
      this.longitude = UNKNOWN;
    }
    this.segmentLength = Number(searchApiRecord.sequence.segmentLength);
    this.includeInJob = false;
    this.resourceSource = SOURCE_GENBANK;
  };

};

class SQLRecord {

  constructor(recordApiRecord) {
    this.accession = String(recordApiRecord.accession);
    this.date = String(recordApiRecord.sequence.collectionDate || UNKNOWN);
    if (recordApiRecord.publication) {
      this.pubmedID = String(recordApiRecord.publication.pubMedID || 'n/a');
    }
    else {
      this.pubmedID = 'n/a';
    }
    this.virus = String(recordApiRecord.sequence.organism || UNKNOWN);
    this.taxon = Number(recordApiRecord.sequence.taxID);
    this.strain = String(recordApiRecord.sequence.strain || UNKNOWN);
    this.isolate = String(recordApiRecord.sequence.isolate || UNKNOWN)
    if (recordApiRecord.host) {
      this.host = String(recordApiRecord.host.name || UNKNOWN);
      this.hostId = String(recordApiRecord.host.taxon || UNKNOWN);
    }
    else {
      this.host = UNKNOWN;
      this.hostId = UNKNOWN
    }
    if (recordApiRecord.geonameLocation) {
      this.geonameID = String(recordApiRecord.geonameLocation.geonameID || UNKNOWN);
      this.location = String(recordApiRecord.geonameLocation.location || UNKNOWN);
      this.latitude = String(recordApiRecord.geonameLocation.latitude || UNKNOWN);
      this.longitude = String(recordApiRecord.geonameLocation.longitude || UNKNOWN);
    }
    else {
        this.location = UNKNOWN;
    }
    this.genes = stringifyGenes(recordApiRecord.genes);
    this.definition = String(recordApiRecord.sequence.definition || UNKNOWN)
    if (recordApiRecord.possibleLocations) {
      var possibleLocations = [];
      for(var i=0; i<recordApiRecord.possibleLocations.length; i++){
        var possibleLocation = new PossibleLocation(recordApiRecord.possibleLocations[i]);
        possibleLocations.push(possibleLocation);
      }
      this.possibleLocations = possibleLocations;
    } else {
        this.possibleLocations = [];
    }
  };

};

class CustomRecord {
  constructor(searchApiRecord) {
    this.accession = String(searchApiRecord.accession);
    this.genes = UNKNOWN;
    this.virus = UNKNOWN;
    this.luceneDate = UNKNOWN;
    this.host = UNKNOWN;
    if(checkInput(searchApiRecord.collectionDate, 'string', FASTA_MET_DEC_DATE_RE)){
      this.date = convertDecimalDate(searchApiRecord.collectionDate);
    } else {
      this.date = searchApiRecord.collectionDate;
    }
    if (searchApiRecord.geonameLocation) {
      this.state = String(searchApiRecord.geonameLocation.state || UNKNOWN);
      this.country = String(searchApiRecord.geonameLocation.country || UNKNOWN);
      this.location = String(searchApiRecord.geonameLocation.location || UNKNOWN);
      this.geonameid = String(searchApiRecord.geonameLocation.geonameID || UNKNOWN);
      this.latitude = String(searchApiRecord.geonameLocation.latitude || UNKNOWN);
      this.longitude = String(searchApiRecord.geonameLocation.longitude || UNKNOWN);
    } else {
      this.state = UNKNOWN;
      this.country = UNKNOWN;
      this.location = UNKNOWN;
      this.geonameid = UNKNOWN;
      this.latitude = UNKNOWN;
      this.longitude = UNKNOWN;
    }
    this.segmentLength = Number(searchApiRecord.rawSequence.length);
    this.sequence =searchApiRecord.rawSequence;
    this.includeInJob = false;
    this.resourceSource = SOURCE_FASTA;
  };
};

class PossibleLocation {

  constructor(recordPossibleLocation) {
    this.geonameID = String(recordPossibleLocation.geonameID || UNKNOWN);
    this.location = String(recordPossibleLocation.location || UNKNOWN);
    this.latitude = String(recordPossibleLocation.latitude || UNKNOWN);
    this.longitude = String(recordPossibleLocation.longitude || UNKNOWN);
    this.probability = String(recordPossibleLocation.probability || UNKNOWN);
  };

};

module.exports = {
  LuceneRecord: LuceneRecord,
  SQLRecord: SQLRecord,
  CustomRecord: CustomRecord,
  PossibleLocation: PossibleLocation
};
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var applicationConfiguration = require('./config/config');

// Karma configuration
module.exports = function(config) {
	config.set({
		// Frameworks to use
		frameworks: ['jasmine', 'jasmine-matchers'],

		// List of files / patterns to load in the browser
		files: applicationConfiguration.assets.lib.js.concat(applicationConfiguration.assets.js, applicationConfiguration.assets.tests),

		// Test results reporter to use
		// Possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
		reporters: ['progress'],

		// Web server port
		port: 9876,

		// Enable / disable colors in the output (reporters and logs)
		colors: true,

		// Level of logging
		// Possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
		logLevel: config.LOG_INFO,

		// Enable / disable watching file and executing tests whenever any file changes
		autoWatch: true,

		// Start these browsers, currently available:
		// - Chrome
		// - ChromeCanary
		// - Firefox
		// - Opera
		// - Safari (only Mac)
		// - PhantomJS
		// - IE (only Windows)
		browsers: ['Chrome'],

		// If browser does not capture in given timeout [ms], kill it
		captureTimeout: 60000,

		// Continuous Integration mode
		// If true, it capture browsers, run tests and exit
		singleRun: true
	});
};
<commit_msg>add firefox test as well<commit_after>'use strict';

/**
 * Module dependencies.
 */
var applicationConfiguration = require('./config/config');

// Karma configuration
module.exports = function(config) {
	config.set({
		// Frameworks to use
		frameworks: ['jasmine', 'jasmine-matchers'],

		// List of files / patterns to load in the browser
		files: applicationConfiguration.assets.lib.js.concat(applicationConfiguration.assets.js, applicationConfiguration.assets.tests),

		// Test results reporter to use
		// Possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
		reporters: ['progress'],

		// Web server port
		port: 9876,

		// Enable / disable colors in the output (reporters and logs)
		colors: true,

		// Level of logging
		// Possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
		logLevel: config.LOG_INFO,

		// Enable / disable watching file and executing tests whenever any file changes
		autoWatch: true,

		// Start these browsers, currently available:
		// - Chrome
		// - ChromeCanary
		// - Firefox
		// - Opera
		// - Safari (only Mac)
		// - PhantomJS
		// - IE (only Windows)
		browsers: ['Chrome', 'Firefox'],

		// If browser does not capture in given timeout [ms], kill it
		captureTimeout: 60000,

		// Continuous Integration mode
		// If true, it capture browsers, run tests and exit
		singleRun: true
	});
};
<|endoftext|>


<commit_before>import { createSelector, createStructuredSelector } from 'reselect';
import isEmpty from 'lodash/isEmpty';
import { reverseLatLng } from 'utils/geoms';

import {
  getActiveDatasetsFromState,
  filterInteractions,
  getSelectedInteraction
} from 'components/maps/map/selectors';

const getSearch = state => state.location && state.location.search;
const getLatLng = state => state.popup && state.popup.latlng;

export const getIsBoundary = createSelector(
  getSelectedInteraction,
  interaction => interaction && interaction.isBoundary
);

export const getCardData = createSelector(
  [getSelectedInteraction],
  interaction => {
    if (isEmpty(interaction) || !interaction.article) return null;
    const { data, config } = interaction;
    const articleData = config.reduce((obj, param) => {
      const { prefix, renderKey } = param;
      const value = data[param.column || param.key];
      const newObj = {
        ...obj,
        ...(renderKey &&
          value && {
            [renderKey]: `${prefix || ''}${value}`
          })
      };
      return newObj;
    }, {});
    const { readMoreLink } = articleData || {};

    const readMoreBtn = {
      text: 'READ MORE',
      extLink: readMoreLink,
      theme: `theme-button-small ${data.bbox ? 'theme-button-light' : ''}`
    };

    const buttons = data.bbox
      ? [readMoreBtn].concat([
        {
          text: 'ZOOM',
          theme: 'theme-button-small'
        }
      ])
      : [readMoreBtn];

    return {
      ...articleData,
      ...(data.bbox && {
        bbox: reverseLatLng(JSON.parse(data.bbox).coordinates[0])
      }),
      buttons
    };
  }
);

export const getTableData = createSelector(
  [getSelectedInteraction, getIsBoundary],
  (interaction, isBoundary) => {
    console.log(interaction);
    if (isEmpty(interaction) || interaction.article) return null;
    const { config, data } = interaction;
    if (isBoundary) {
      return config.reduce(
        (obj, c) => ({
          ...obj,
          [c.column]: data[c.column]
        }),
        {}
      );
    }

    return Object.keys(interaction).map(i => ({
      label: i,
      value: interaction[i]
    }));
  }
);

export const getPopupProps = createStructuredSelector({
  interactions: filterInteractions,
  selected: getSelectedInteraction,
  tableData: getTableData,
  cardData: getCardData,
  latlng: getLatLng,
  activeDatasets: getActiveDatasetsFromState,
  search: getSearch,
  isBoundary: getIsBoundary
});
<commit_msg>fix interactions<commit_after>import { createSelector, createStructuredSelector } from 'reselect';
import isEmpty from 'lodash/isEmpty';
import { reverseLatLng } from 'utils/geoms';

import {
  getActiveDatasetsFromState,
  filterInteractions,
  getSelectedInteraction
} from 'components/maps/map/selectors';

const getSearch = state => state.location && state.location.search;
const getLatLng = state => state.popup && state.popup.latlng;

export const getIsBoundary = createSelector(
  getSelectedInteraction,
  interaction => interaction && interaction.isBoundary
);

export const getCardData = createSelector(
  [getSelectedInteraction],
  interaction => {
    if (isEmpty(interaction) || !interaction.article) return null;
    const { data, config } = interaction;
    const articleData = config.reduce((obj, param) => {
      const { prefix, renderKey } = param;
      const value = data[param.column || param.key];
      const newObj = {
        ...obj,
        ...(renderKey &&
          value && {
            [renderKey]: `${prefix || ''}${value}`
          })
      };
      return newObj;
    }, {});
    const { readMoreLink } = articleData || {};

    const readMoreBtn = {
      text: 'READ MORE',
      extLink: readMoreLink,
      theme: `theme-button-small ${data.bbox ? 'theme-button-light' : ''}`
    };

    const buttons = data.bbox
      ? [readMoreBtn].concat([
        {
          text: 'ZOOM',
          theme: 'theme-button-small'
        }
      ])
      : [readMoreBtn];

    return {
      ...articleData,
      ...(data.bbox && {
        bbox: reverseLatLng(JSON.parse(data.bbox).coordinates[0])
      }),
      buttons
    };
  }
);

export const getTableData = createSelector(
  [getSelectedInteraction, getIsBoundary],
  (interaction, isBoundary) => {
    if (isEmpty(interaction) || interaction.article) return null;
    const { config, data } = interaction;
    if (isBoundary) {
      return config.reduce(
        (obj, c) => ({
          ...obj,
          [c.column]: data[c.column]
        }),
        {}
      );
    }

    return Object.keys(interaction).map(i => ({
      label: i,
      value: interaction[i]
    }));
  }
);

export const getPopupProps = createStructuredSelector({
  interactions: filterInteractions,
  selected: getSelectedInteraction,
  tableData: getTableData,
  cardData: getCardData,
  latlng: getLatLng,
  activeDatasets: getActiveDatasetsFromState,
  search: getSearch,
  isBoundary: getIsBoundary
});
<|endoftext|>


<commit_before>//@flow

import componentQueries from "react-component-queries";

export default componentQueries({
  queries: [
    ({ width }) => {
      const w = width < 500 ? "s" : width < 900 ? "m" : "l";

      return {
        compWidth: w
      };
    }
  ]
});
<commit_msg>Amend HeaderMain container query to pass queries object<commit_after>//@flow

import componentQueries from "react-component-queries";

export const detectWidth = componentQueries({
  queries: [
    ({ width }) => ({
      queries: {
        width: width < 728 ? "mobile" : "desktop"
      }
    })
  ]
});

//always wrap result in a queries object.
<|endoftext|>


<commit_before>import Ember from 'ember';

export default Ember.Route.extend({
  model() {
    return this.modelFor('profile');
  },
  mapState: Ember.inject.service(),
  actions: {
    didTransition() {
      let { cd, boro, borocd, neighborhoods } = this.controller.get('model.properties');
      let mapState = this.get('mapState');

      if (neighborhoods) {
        neighborhoods = neighborhoods.join(',  ');
      }

      // reset Ember's internals on route change
      Ember.run.next(this, () => {
        let mapInstance = this.get('mapState.mapInstance');
        mapInstance.on('moveend', function() {
          mapInstance.invalidateSize();
        });
      });

      // seeing async issues - putting inside run loop to stagger
      Ember.run.next(this, () => {
        mapState.set('currentlySelected', {
          cd,
          boro,
          borocd,
          neighborhoods,
        });
      });
    }
  }
});
<commit_msg>Remove invalidate size<commit_after>import Ember from 'ember';

export default Ember.Route.extend({
  model() {
    return this.modelFor('profile');
  },
  mapState: Ember.inject.service(),
  actions: {
    didTransition() {
      let { cd, boro, borocd, neighborhoods } = this.controller.get('model.properties');
      let mapState = this.get('mapState');

      if (neighborhoods) {
        neighborhoods = neighborhoods.join(',  ');
      }

      // seeing async issues - putting inside run loop to stagger
      Ember.run.next(this, () => {
        mapState.set('currentlySelected', {
          cd,
          boro,
          borocd,
          neighborhoods,
        });
      });
    }
  }
});
<|endoftext|>


<commit_before>var exec, should, blog, mongoose;

mongoose  = require('mongoose');
should = require('should');
blog = require('../src/blog');

describe("blog", function() {

  before(function() {
    if(!mongoose.connection.readyState){
      mongoose.connect('mongodb://localhost/fluiddb');
    }
  })

  after(function() {
    mongoose.disconnect();
  });

  it("save, get & delete an entry", function(next) {
    var entry = {
      title: "This is a test entry",
      author: "root",
      url: "this-is-a-test-entry",
      body: "This is me writing my first blog post",
      tags: [{name: 'tag'}],
      category: 'category',
      comments: [{body: "this is a comment", date: new Date()}],
      date: new Date(),
      published: true
    };

    return blog.createEntry(entry, function(err, data) {
      if(err) {
        console.log(err);
        return next(err);
      }
      // console.log('create: ' + data);
      blog.getEntry("This is a test entry", function(err, retrievedEntry) {
        if(err) {
          console.log(err);
          return next(err);
        }
        // console.log('get 1: ' + retrievedEntry);
        retrievedEntry[0].body.should.be.eql("This is me writing my first blog post");

        blog.removeEntry(retrievedEntry[0]._id, function(err, deletedEntry) {
          if(err) {
            console.log(err);
            return next(err);
          }
          // console.log('remove: ' + deletedEntry);
          blog.getEntry("This is a test entry", function(err, data) {
            if(err) {
              console.log(err);
              return next(err);
            }
            // console.log("get 2: " + data);
            data.should.be.empty;
            next();
          })
        });
      });
    });
  });

  it("edit an entry", function(next) {
    var entry = {
      title: "This is a test entry 2",
      author: "root",
      url: "this-is-a-test-entry",
      body: "This is me writing my first blog post",
      tags: [{name: 'tag'}],
      category: 'category',
      comments: [{body: "this is a comment", date: new Date()}],
      date: new Date(),
      published: true
    };

    return blog.createEntry(entry, function(err, data) {
      if(err) {
        console.log(err);
        return next(err);
      }
      // console.log('create: ' + data);
      blog.getEntry("This is a test entry 2", function(err, retrievedEntry) {
        if(err) {
          console.log(err);
          return next(err);
        }
        // console.log('get 1: ' + retrievedEntry);
        retrievedEntry[0].body.should.be.eql("This is me writing my first blog post");

        blog.editEntry(retrievedEntry[0]._id, {title: 'This is a modified entry 2'}, function(err, data) {

          blog.getEntry('This is a modified entry 2', function(err, data) {
            console.log(data);
            data[0].title.should.be.eql('This is a modified entry 2');
            blog.removeEntry(data[0]._id, function(err, deletedEntry) {
              if(err) {
                console.log(err);
                return next(err);
              }
              // console.log('remove: ' + deletedEntry);
              blog.getEntry("This is a modified entry", function(err, data) {
                if(err) {
                  console.log(err);
                  return next(err);
                }
                // console.log("get 2: " + data);
                data.should.be.empty;
                next();
              })
            });
          });
        });
      });
    });
  });

  // it("create, get & save a category", function(next) {

  // });

  // it("edit a category", function(next) {

  // });
});<commit_msg>unit test upgrade<commit_after>var exec, should, blog, mongoose;

mongoose  = require('mongoose');
should = require('should');
blog = require('../src/blog');

describe("blog", function() {

  before(function() {
    if(!mongoose.connection.readyState){
      mongoose.connect('mongodb://localhost/fluiddb');
    }
  })

  after(function() {
    mongoose.disconnect();
  });

  it("create an entry", function(next) {
    var entry = {
      title: "test1",
      author: "root",
      url: "this-is-a-test-entry",
      body: "This is me writing my first blog post",
      tags: [{name: 'tag'}],
      category: 'category',
      comments: [{body: "this is a comment", date: new Date()}],
      date: new Date(),
      published: true
    };

    return blog.createEntry(entry, function(err, data) {
      if(err) {
        console.log(err);
        return next(err);
      }
      data.body.should.be.eql("This is me writing my first blog post");

      blog.removeEntry(data._id, function(err, deletedEntry) {
        if(err) {
          console.log(err);
          return next(err);
        }
        next();
      });
    });
  });

  it("get an entry", function(next) {
    var entry = {
      title: "test2",
      author: "root",
      url: "this-is-a-test-entry",
      body: "This is me writing my first blog post",
      tags: [{name: 'tag'}],
      category: 'category',
      comments: [{body: "this is a comment", date: new Date()}],
      date: new Date(),
      published: true
    };

    return blog.createEntry(entry, function(err, data) {
      if(err) {
        console.log(err);
        return next(err);
      }
      // console.log('create: ' + data);
      blog.getEntry("test2", function(err, retrievedEntry) {
        if(err) {
          console.log(err);
          return next(err);
        }
        // console.log('get 1: ' + retrievedEntry);
        retrievedEntry[0].body.should.be.eql("This is me writing my first blog post");

        blog.removeEntry(retrievedEntry[0]._id, function(err, deletedEntry) {
          if(err) {
            console.log(err);
            return next(err);
          }
          next();
        });
      });
    });
  });

  it("delete an entry", function(next) {
    var entry = {
      title: "test3",
      author: "root",
      url: "this-is-a-test-entry",
      body: "This is me writing my first blog post",
      tags: [{name: 'tag'}],
      category: 'category',
      comments: [{body: "this is a comment", date: new Date()}],
      date: new Date(),
      published: true
    };

    return blog.createEntry(entry, function(err, data) {
      if(err) {
        console.log(err);
        return next(err);
      }
      blog.removeEntry(data._id, function(err, deletedEntry) {
        if(err) {
          console.log(err);
          return next(err);
        }
        // console.log('remove: ' + deletedEntry);
        blog.getEntry("test3", function(err, data) {
          if(err) {
            console.log(err);
            return next(err);
          }
          // console.log("get 2: " + data);
          data.should.be.empty;
          next();
        })
      });
    });
  });

  it("edit an entry", function(next) {
    var entry = {
      title: "This is a test entry 2",
      author: "root",
      url: "this-is-a-test-entry",
      body: "This is me writing my first blog post",
      tags: [{name: 'tag'}],
      category: 'category',
      comments: [{body: "this is a comment", date: new Date()}],
      date: new Date(),
      published: true
    };

    return blog.createEntry(entry, function(err, data) {
      if(err) {
        console.log(err);
        return next(err);
      }
      // console.log('create: ' + data);
      blog.getEntry("This is a test entry 2", function(err, retrievedEntry) {
        if(err) {
          console.log(err);
          return next(err);
        }
        // console.log('get 1: ' + retrievedEntry);
        retrievedEntry[0].body.should.be.eql("This is me writing my first blog post");

        blog.editEntry(retrievedEntry[0]._id, {title: 'This is a modified entry 2'}, function(err, data) {

          blog.getEntry('This is a modified entry 2', function(err, data) {
            console.log(data);
            data[0].title.should.be.eql('This is a modified entry 2');
            blog.removeEntry(data[0]._id, function(err, deletedEntry) {
              if(err) {
                console.log(err);
                return next(err);
              }
              // console.log('remove: ' + deletedEntry);
              blog.getEntry("This is a modified entry", function(err, data) {
                if(err) {
                  console.log(err);
                  return next(err);
                }
                // console.log("get 2: " + data);
                data.should.be.empty;
                next();
              })
            });
          });
        });
      });
    });
  });

  // it("create, get & delete a category", function(next) {

  // });

  // it("edit a category", function(next) {

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


<commit_before>var AdditionalTaskView = Backbone.View.extend({
  el: '#additional-task-view',
  additionalTaskContainerView: null,
  events: {
    'hide': 'onHide'
  },
  initialize: function(additionalTaskSequenceID)
  {
    this.additionalTaskContainerView = new AdditionalTaskContainerView(additionalTaskSequenceID);
  },
  onHide: function()
  {
    var taskAppView = this.additionalTaskContainerView.additionalTaskApp_view;
    if (taskAppView && taskAppView.customTempView) {
      customView.stopListening();
    }
  }
});

var AdditionalTaskContainerView = Backbone.View.extend({
  el: '#additional-task-app-container',
  additionalTaskApp: null,
  additionalTaskApp_view: null,
  initialize: function(additionalTaskSequenceID)
  {
    if (app.router.additionalTasksView) {
      this.additionalTaskApp = app.router.additionalTasksView.additionalTasksListView.additionalTaskCollection.findWhere({ id: additionalTaskSequenceID });
      this.render();
    } else {
      this.getSequence(additionalTaskSequenceID).then(
        success => {
          this.render();
        },
        error => {
          console.error('error', error);
          this.render();
        }
      );
    }
  },

  getSequence(additionalTaskSequenceID)
  {
    return $.getJSON(API_BASEURL + 'additional-tasks', null, _.bind(function(data) {
      if (data.utilities && data.utilities.length) {
        for (var i = 0; i < data.utilities.length; i++) {
          var ca = data.utilities[i];
          if (ca.id == additionalTaskSequenceID && ca.visibility) {
            this.additionalTaskApp = new AdditionalTask(ca);
          }
        }
      }
    }, this))
    .fail(function() {
      noty({text: "There was an error getting additional task.", timeout: 3000});
    })
  },

  render: function()
  {
    var actionEl = this.$el.find('.additional-tasks-app');
    var noActionEl = this.$el.find('#additional-task');

    actionEl.empty();
    noActionEl.hide();

    if (this.additionalTaskApp) {
      var row = new AdditionalTaskAppView({ additionalTaskApp: this.additionalTaskApp});
      actionEl.append(row.render().el);
      this.additionalTaskApp_view = row;
    } else {
      noActionEl.show();
      setTimeout(() => {
        window.location.href = window.location.origin+"/#additional-tasks"
      }, 2500);
    }
  }
});

var AdditionalTaskAppView = Backbone.View.extend({
  className: 'additional-task-row',
  additionalTaskApp: null,
  currentIndexStep: 1,
  currentStep: null,
  customTempView: null,
  events: {
    "click .close": "closeClicked",
    "click .next": "nextClicked",
    "click .action": "actionClicked",
    "click .repeat": "repeatClicked"
  },
  template: _.template($("#additional-task-app-template").html()),
  initialize: function (params)
  {
    this.additionalTaskApp = params.additionalTaskApp;
    this.currentStep = this.additionalTaskApp.get('steps')[this.currentIndexStep-1]

    this.$el.attr('id', this.additionalTaskApp.get('id'));
  },
  closeClicked: function (e)
  {
    e.preventDefault();
    this.doClose();
  },

  doClose()
  {
    var currentLocation = window.location
    currentLocation.href = currentLocation.origin+"/#custom"

    if (this.currentStep.type == "set_temperature") {
      this.customTempView.stopListening();
    }
  },
  nextClicked: function (e)
  {
    e.preventDefault();
    this.doNext();
  },
  doNext()
  {
    var loadingBtn = this.$('button.next').closest('.loading-button');

    switch (this.currentStep.type) {
      case "set_extruder":
        // Change active extruder
        this._sendChangeToolCommand(this.$('#extruder-count').val())
          .done(() => {
            loadingBtn.removeClass('loading');
            this.checkNextStep();
          })
          .fail(() => {
            loadingBtn.addClass('failed');
            noty({ text: "There was an error sending a command.", timeout: 3000 });
            setTimeout(function () {
              loadingBtn.removeClass('failed');
            }, 3000);
          });
        break;
      case "set_temperature":
        this.customTempView.stopListening();
        this.checkNextStep();
        break;
      case "action":
        loadingBtn.addClass('loading');
        if (this.currentStep.commands_on_next) {
          this.sendCommands("next")
            .done(() => {
              console.info('All the commands have been sent');
              loadingBtn.removeClass('loading');
              this.checkNextStep();
            })
            .fail(() => {
              loadingBtn.addClass('failed');
              noty({ text: "There was an error sending a command.", timeout: 3000 });
              setTimeout(function () {
                loadingBtn.removeClass('failed');
              }, 3000);
            });
        } else {
          this.checkNextStep();
        }

        break;
      case "information":
        this.checkNextStep();
        break;
    }
  },

  actionClicked: function (e)
  {
    e.preventDefault();
    this.doAction();
  },

  doAction: function()
  {
    this.sendCommands("action");
  },

  repeatClicked: function (e)
  {
    e.preventDefault();
    this.doRepeat();
  },

  doRepeat: function()
  {
    this.currentIndexStep = 1;
    this.currentStep = this.additionalTaskApp.get('steps')[this.currentIndexStep-1]
    this.render();
  },

  checkNextStep: function()
  {

    // If no Last step
    if (this.currentIndexStep < this.additionalTaskApp.get('steps').length) {
      this.currentIndexStep++;
      this.currentStep = this.additionalTaskApp.get('steps')[this.currentIndexStep-1]
      this.render();
      // If Show temp view
      if (this.currentStep.type == "set_temperature") {
        var loadingBtn = this.$('button.next').closest('.loading-button');
        loadingBtn.addClass('inactive');
        this.customTempView = new CustomTempView();
      }
    // If Last step
    } else {
      this.doClose();
    }
  },

  sendCommands: function(type, commandsIndex, promise)
  {
    if (!commandsIndex) {
      var commandsIndex = 0;
    }
    if (!promise) {
      var promise = $.Deferred();
    }

    var arrayCommands = type == "action" ? this.currentStep.commands_on_action : this.currentStep.commands_on_next;
     $.ajax({

      url: API_BASEURL + 'printer/comm/send',
      method: 'POST',
      data: {
        command: arrayCommands[commandsIndex]
      }
    })
      .success(( () => {
        if (arrayCommands[commandsIndex + 1]) {
          this.sendCommands(type, ++commandsIndex, promise);
        } else {
          promise.resolve();
        }
      }))

      .fail(_.bind(function () {
        promise.reject()
      }, this))

      return promise;
  },

  _sendChangeToolCommand: function(tool)
  {
    var data = {
      command: "select",
      tool: 'tool'+tool
    }

    return $.ajax({
      url: API_BASEURL + "printer/tool",
      type: "POST",
      dataType: "json",
      contentType: "application/json; charset=UTF-8",
      data: JSON.stringify(data)
    });
  },

  render: function ()
  {
    this.$el.empty();
    this.$el.html(this.template({currentStep: this.currentStep, currentIndexStep: this.currentIndexStep, additionalTaskApp: this.additionalTaskApp.toJSON() }));
    return this;
  },
});

var CustomTempView = Backbone.View.extend({
  className: 'control-temps small-12 columns',
  el: '#custom-temp-control-template',
  semiCircleTempView: null,
  currentExtruder: null,
  socketTemps: null,
  initialize: function()
  {
    new SemiCircleProgress();
    var profile = app.printerProfile.toJSON();
    this.currentExtruder = app.socketData.attributes.tool;
    this.renderCircleTemps();

    this.listenTo(app.socketData, 'change:temps', this.updateTemps);
    this.listenTo(app.socketData, 'change:paused', this.onPausedChanged);
    this.listenTo(app.socketData, 'change:tool', this.onToolChanged);
  },
  renderCircleTemps: function() {
    if (app.socketData.attributes.temps != this.socketTemps) {
      this.socketTemps = app.socketData.attributes.temps;
    }
    var temps = null;

    this.$el.find('#slider-nav').empty();
    this.$el.find('#slider').empty();
    this.$el.find('.bed').empty();

    this.semiCircleTempView = new TempSemiCircleView({'tool': this.currentExtruder, enableOff: false, hideBed: true, preHeat: true});

    this.$el.find('#slider').append(this.semiCircleTempView.render().el);

    if (this.socketTemps.lenght > 0) {
      temps = {
        current: this.socketTemps.extruders[this.currentExtruder].current,
        target: this.socketTemps.extruders[this.currentExtruder].target
      };
    } else {
      temps = {current: null, target: null};
    }

    this.semiCircleTempView.setTemps(temps.current, temps.target);

    // Draw circle
    this.$el.find("#"+this.semiCircleTempView.el.id+" .progress-temp-circle").circleProgress({
      arcCoef: 0.55,
      size: 180,
      thickness: 20,
      fill: { gradient: ['#60D2E5', '#E8A13A', '#F02E19'] }
    });

    if (this.socketTemps.length > 0) {
      this.updateTemps(this.socketTemps);
    }
  },
  updateTemps: function(value)
  {
    var temp_values = value.get('temps');
    var temps = { 'current': temp_values.extruders[this.currentExtruder].current, 'target': temp_values.extruders[this.currentExtruder].target };

    (this.semiCircleTempView).updateValues(temps);

    if (this.semiCircleTempView.type == 'tool') {

      var tempValue = '- -';
      if (this.semiCircleTempView.actual != null) {
        tempValue = Math.round(this.semiCircleTempView.actual) + 'º';
      }
      this.$el.find("#tool"+this.currentExtruder).find('.all-temps').text(tempValue);
    }

    this.$("#"+this.semiCircleTempView.el.id+" .progress-temp-circle").circleProgress({
      arcCoef: 0.55,
      size: 180,
      thickness: 20,
      fill: { gradient: ['#60D2E5', '#E8A13A', '#F02E19'] }
    });

    if (temp_values.extruders[this.currentExtruder].current > 180 && temp_values.extruders[this.currentExtruder].current >= temp_values.extruders[this.currentExtruder].target ) {
      var loadingBtn = $('button.next').closest('.loading-button');
      loadingBtn.removeClass('inactive');
    }

  }
});
<commit_msg>Fixed close task<commit_after>var AdditionalTaskView = Backbone.View.extend({
  el: '#additional-task-view',
  additionalTaskContainerView: null,
  events: {
    'hide': 'onHide'
  },
  initialize: function(additionalTaskSequenceID)
  {
    this.additionalTaskContainerView = new AdditionalTaskContainerView(additionalTaskSequenceID);
  },
  onHide: function()
  {
    var taskAppView = this.additionalTaskContainerView.additionalTaskApp_view;
    if (taskAppView && taskAppView.customTempView) {
      customView.stopListening();
    }
  }
});

var AdditionalTaskContainerView = Backbone.View.extend({
  el: '#additional-task-app-container',
  additionalTaskApp: null,
  additionalTaskApp_view: null,
  initialize: function(additionalTaskSequenceID)
  {
    if (app.router.additionalTasksView) {
      this.additionalTaskApp = app.router.additionalTasksView.additionalTasksListView.additionalTaskCollection.findWhere({ id: additionalTaskSequenceID });
      this.render();
    } else {
      this.getSequence(additionalTaskSequenceID).then(
        success => {
          this.render();
        },
        error => {
          console.error('error', error);
          this.render();
        }
      );
    }
  },

  getSequence(additionalTaskSequenceID)
  {
    return $.getJSON(API_BASEURL + 'additional-tasks', null, _.bind(function(data) {
      if (data.utilities && data.utilities.length) {
        for (var i = 0; i < data.utilities.length; i++) {
          var ca = data.utilities[i];
          if (ca.id == additionalTaskSequenceID && ca.visibility) {
            this.additionalTaskApp = new AdditionalTask(ca);
          }
        }
      }
    }, this))
    .fail(function() {
      noty({text: "There was an error getting additional task.", timeout: 3000});
    })
  },

  render: function()
  {
    var actionEl = this.$el.find('.additional-tasks-app');
    var noActionEl = this.$el.find('#additional-task');

    actionEl.empty();
    noActionEl.hide();

    if (this.additionalTaskApp) {
      var row = new AdditionalTaskAppView({ additionalTaskApp: this.additionalTaskApp});
      actionEl.append(row.render().el);
      this.additionalTaskApp_view = row;
    } else {
      noActionEl.show();
      setTimeout(() => {
        window.location.href = window.location.origin+"/#additional-tasks"
      }, 2500);
    }
  }
});

var AdditionalTaskAppView = Backbone.View.extend({
  className: 'additional-task-row',
  additionalTaskApp: null,
  currentIndexStep: 1,
  currentStep: null,
  customTempView: null,
  events: {
    "click .close": "closeClicked",
    "click .next": "nextClicked",
    "click .action": "actionClicked",
    "click .repeat": "repeatClicked"
  },
  template: _.template($("#additional-task-app-template").html()),
  initialize: function (params)
  {
    this.additionalTaskApp = params.additionalTaskApp;
    this.currentStep = this.additionalTaskApp.get('steps')[this.currentIndexStep-1]

    this.$el.attr('id', this.additionalTaskApp.get('id'));
  },
  closeClicked: function (e)
  {
    e.preventDefault();
    this.doClose();
  },

  doClose()
  {
    var currentLocation = window.location
    currentLocation.href = currentLocation.origin+"/#additional-tasks"

    if (this.currentStep.type == "set_temperature") {
      this.customTempView.stopListening();
    }
  },
  nextClicked: function (e)
  {
    e.preventDefault();
    this.doNext();
  },
  doNext()
  {
    var loadingBtn = this.$('button.next').closest('.loading-button');

    switch (this.currentStep.type) {
      case "set_extruder":
        // Change active extruder
        this._sendChangeToolCommand(this.$('#extruder-count').val())
          .done(() => {
            loadingBtn.removeClass('loading');
            this.checkNextStep();
          })
          .fail(() => {
            loadingBtn.addClass('failed');
            noty({ text: "There was an error sending a command.", timeout: 3000 });
            setTimeout(function () {
              loadingBtn.removeClass('failed');
            }, 3000);
          });
        break;
      case "set_temperature":
        this.customTempView.stopListening();
        this.checkNextStep();
        break;
      case "action":
        loadingBtn.addClass('loading');
        if (this.currentStep.commands_on_next) {
          this.sendCommands("next")
            .done(() => {
              console.info('All the commands have been sent');
              loadingBtn.removeClass('loading');
              this.checkNextStep();
            })
            .fail(() => {
              loadingBtn.addClass('failed');
              noty({ text: "There was an error sending a command.", timeout: 3000 });
              setTimeout(function () {
                loadingBtn.removeClass('failed');
              }, 3000);
            });
        } else {
          this.checkNextStep();
        }

        break;
      case "information":
        this.checkNextStep();
        break;
    }
  },

  actionClicked: function (e)
  {
    e.preventDefault();
    this.doAction();
  },

  doAction: function()
  {
    this.sendCommands("action");
  },

  repeatClicked: function (e)
  {
    e.preventDefault();
    this.doRepeat();
  },

  doRepeat: function()
  {
    this.currentIndexStep = 1;
    this.currentStep = this.additionalTaskApp.get('steps')[this.currentIndexStep-1]
    this.render();
  },

  checkNextStep: function()
  {

    // If no Last step
    if (this.currentIndexStep < this.additionalTaskApp.get('steps').length) {
      this.currentIndexStep++;
      this.currentStep = this.additionalTaskApp.get('steps')[this.currentIndexStep-1]
      this.render();
      // If Show temp view
      if (this.currentStep.type == "set_temperature") {
        var loadingBtn = this.$('button.next').closest('.loading-button');
        loadingBtn.addClass('inactive');
        this.customTempView = new CustomTempView();
      }
    // If Last step
    } else {
      this.doClose();
    }
  },

  sendCommands: function(type, commandsIndex, promise)
  {
    if (!commandsIndex) {
      var commandsIndex = 0;
    }
    if (!promise) {
      var promise = $.Deferred();
    }

    var arrayCommands = type == "action" ? this.currentStep.commands_on_action : this.currentStep.commands_on_next;
     $.ajax({

      url: API_BASEURL + 'printer/comm/send',
      method: 'POST',
      data: {
        command: arrayCommands[commandsIndex]
      }
    })
      .success(( () => {
        if (arrayCommands[commandsIndex + 1]) {
          this.sendCommands(type, ++commandsIndex, promise);
        } else {
          promise.resolve();
        }
      }))

      .fail(_.bind(function () {
        promise.reject()
      }, this))

      return promise;
  },

  _sendChangeToolCommand: function(tool)
  {
    var data = {
      command: "select",
      tool: 'tool'+tool
    }

    return $.ajax({
      url: API_BASEURL + "printer/tool",
      type: "POST",
      dataType: "json",
      contentType: "application/json; charset=UTF-8",
      data: JSON.stringify(data)
    });
  },

  render: function ()
  {
    this.$el.empty();
    this.$el.html(this.template({currentStep: this.currentStep, currentIndexStep: this.currentIndexStep, additionalTaskApp: this.additionalTaskApp.toJSON() }));
    return this;
  },
});

var CustomTempView = Backbone.View.extend({
  className: 'control-temps small-12 columns',
  el: '#custom-temp-control-template',
  semiCircleTempView: null,
  currentExtruder: null,
  socketTemps: null,
  initialize: function()
  {
    new SemiCircleProgress();
    var profile = app.printerProfile.toJSON();
    this.currentExtruder = app.socketData.attributes.tool;
    this.renderCircleTemps();

    this.listenTo(app.socketData, 'change:temps', this.updateTemps);
    this.listenTo(app.socketData, 'change:paused', this.onPausedChanged);
    this.listenTo(app.socketData, 'change:tool', this.onToolChanged);
  },
  renderCircleTemps: function() {
    if (app.socketData.attributes.temps != this.socketTemps) {
      this.socketTemps = app.socketData.attributes.temps;
    }
    var temps = null;

    this.$el.find('#slider-nav').empty();
    this.$el.find('#slider').empty();
    this.$el.find('.bed').empty();

    this.semiCircleTempView = new TempSemiCircleView({'tool': this.currentExtruder, enableOff: false, hideBed: true, preHeat: true});

    this.$el.find('#slider').append(this.semiCircleTempView.render().el);

    if (this.socketTemps.lenght > 0) {
      temps = {
        current: this.socketTemps.extruders[this.currentExtruder].current,
        target: this.socketTemps.extruders[this.currentExtruder].target
      };
    } else {
      temps = {current: null, target: null};
    }

    this.semiCircleTempView.setTemps(temps.current, temps.target);

    // Draw circle
    this.$el.find("#"+this.semiCircleTempView.el.id+" .progress-temp-circle").circleProgress({
      arcCoef: 0.55,
      size: 180,
      thickness: 20,
      fill: { gradient: ['#60D2E5', '#E8A13A', '#F02E19'] }
    });

    if (this.socketTemps.length > 0) {
      this.updateTemps(this.socketTemps);
    }
  },
  updateTemps: function(value)
  {
    var temp_values = value.get('temps');
    var temps = { 'current': temp_values.extruders[this.currentExtruder].current, 'target': temp_values.extruders[this.currentExtruder].target };

    (this.semiCircleTempView).updateValues(temps);

    if (this.semiCircleTempView.type == 'tool') {

      var tempValue = '- -';
      if (this.semiCircleTempView.actual != null) {
        tempValue = Math.round(this.semiCircleTempView.actual) + 'º';
      }
      this.$el.find("#tool"+this.currentExtruder).find('.all-temps').text(tempValue);
    }

    this.$("#"+this.semiCircleTempView.el.id+" .progress-temp-circle").circleProgress({
      arcCoef: 0.55,
      size: 180,
      thickness: 20,
      fill: { gradient: ['#60D2E5', '#E8A13A', '#F02E19'] }
    });

    if (temp_values.extruders[this.currentExtruder].current > 180 && temp_values.extruders[this.currentExtruder].current >= temp_values.extruders[this.currentExtruder].target ) {
      var loadingBtn = $('button.next').closest('.loading-button');
      loadingBtn.removeClass('inactive');
    }

  }
});
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies
 */
import * as mongo from 'mongodb';
import Following from '../../models/following';
import serialize from '../../serializers/user';

/**
 * Get following users of a user
 *
 * @param {Object} params
 * @param {Object} reply
 * @param {Object} me
 * @return {void}
 */
module.exports = async (params, reply, me) =>
{
	// Init 'user' parameter
	const userId = params.user;
	if (userId === undefined || userId === null) {
		return reply(400, 'user is required');
	}

	// Init 'limit' parameter
	let limit = params.limit;
	if (limit !== undefined && limit !== null) {
		limit = parseInt(limit, 10);

		// 1 ~ 100 まで
		if (!(1 <= limit && limit <= 100)) {
			return reply(400, 'invalid limit range');
		}
	} else {
		limit = 10;
	}

	// Init 'offset' parameter
	let offset = params.offset;
	if (offset !== undefined && offset !== null) {
		offset = parseInt(offset, 10);
	} else {
		offset = 0;
	}

	// Init 'sort' parameter
	let sort = params.sort || 'desc';

	// Lookup user
	const user = await User.findOne({_id: new mongo.ObjectID(userId)});

	if (user === null) {
		return reply(404, 'user not found');
	}

	// Get following
	const following = await Following
		.find({
			follower: user._id
		}, {}, {
			limit: limit,
			skip: offset,
			sort: {
				_id: sort == 'asc' ? 1 : -1
			}
		})

	if (following.length === 0) {
		return reply([]);
	}

	// serialize
	reply(await Promise.all(following.map(async f =>
		await serialize(f.followee, me))));
};
<commit_msg>Fix bug<commit_after>'use strict';

/**
 * Module dependencies
 */
import * as mongo from 'mongodb';
import Following from '../../models/following';
import serialize from '../../serializers/user';

/**
 * Get following users of a user
 *
 * @param {Object} params
 * @param {Object} reply
 * @param {Object} me
 * @return {void}
 */
module.exports = async (params, reply, me) =>
{
	// Init 'user' parameter
	const userId = params.user;
	if (userId === undefined || userId === null) {
		return reply(400, 'user is required');
	}

	// Init 'limit' parameter
	let limit = params.limit;
	if (limit !== undefined && limit !== null) {
		limit = parseInt(limit, 10);

		// 1 ~ 100 まで
		if (!(1 <= limit && limit <= 100)) {
			return reply(400, 'invalid limit range');
		}
	} else {
		limit = 10;
	}

	// Init 'offset' parameter
	let offset = params.offset;
	if (offset !== undefined && offset !== null) {
		offset = parseInt(offset, 10);
	} else {
		offset = 0;
	}

	// Init 'sort' parameter
	let sort = params.sort || 'desc';

	// Lookup user
	const user = await User.findOne({_id: new mongo.ObjectID(userId)});

	if (user === null) {
		return reply(404, 'user not found');
	}

	// Get following
	const following = await Following
		.find({
			follower: user._id
		}, {}, {
			limit: limit,
			skip: offset,
			sort: {
				_id: sort == 'asc' ? 1 : -1
			}
		})
		.toArray();

	if (following.length === 0) {
		return reply([]);
	}

	// serialize
	reply(await Promise.all(following.map(async f =>
		await serialize(f.followee, me))));
};
<|endoftext|>


<commit_before>describe('the stack spec', () => {
  it('shows the infrastructure works', () => {
    true.should.be.true();
  });

  const makeStack = (capacity = 2) => {
    let size = 0;

    return {
      pop: () => size--,

      push: () => {
        if (size === capacity) throw new Error('Error: overflow.');
        size++;
      },

      isEmpty: () => size === 0,
      size: () => size
    };
  };

  let stack;

  describe('a stack should', () => {
    beforeEach(() => {
      stack = makeStack();
    });

    it('start empty', () => {
      stack.isEmpty().should.be.true();
    });

    it('start with stack size 0', () => {
      stack.size().should.equal(0);
    });

    it('not be empty when pushed', () => {
      stack.push();
      stack.isEmpty().should.be.false();
    });

    it('leave stack size 1 when pushed', () => {
      stack.push();
      stack.size().should.equal(1);
    });

    it('leave stack empty when pushed and popped', () => {
      stack.push();
      stack.pop();
      stack.isEmpty().should.be.true();
    });

    it('leave stack size 0 when pushed and popped', () => {
      stack.push();
      stack.pop();
      stack.size().should.equal(0);
    });

    it('overflow', () => {
      stack.push();
      stack.push();

      (() => {
        stack.push();
      }).should.throw('Error: overflow.');
    });

    it('underflow', () => {
      stack.push();
      stack.push();
      stack.pop();
      stack.pop();

      (() => {
        stack.pop();
      }).should.throw('Error: overflow.');
    });

    it('underflow');

    it('pop the same one pushed');

    it('pop the same two pushed');

    it('accept only positive capacity');
  });
}
);
<commit_msg>change message to AssertionError: expected Function { name: '' } to throw exception with a message matching 'Error: underflow.', but got 'Error: overflow.'<commit_after>describe('the stack spec', () => {
  it('shows the infrastructure works', () => {
    true.should.be.true();
  });

  const makeStack = (capacity = 2) => {
    let size = 0;

    return {
      pop: () => {
        if (size === 0) throw new Error('Error: overflow.');
        size--;
      },

      push: () => {
        if (size === capacity) throw new Error('Error: overflow.');
        size++;
      },

      isEmpty: () => size === 0,
      size: () => size
    };
  };

  let stack;

  describe('a stack should', () => {
    beforeEach(() => {
      stack = makeStack();
    });

    it('start empty', () => {
      stack.isEmpty().should.be.true();
    });

    it('start with stack size 0', () => {
      stack.size().should.equal(0);
    });

    it('not be empty when pushed', () => {
      stack.push();
      stack.isEmpty().should.be.false();
    });

    it('leave stack size 1 when pushed', () => {
      stack.push();
      stack.size().should.equal(1);
    });

    it('leave stack empty when pushed and popped', () => {
      stack.push();
      stack.pop();
      stack.isEmpty().should.be.true();
    });

    it('leave stack size 0 when pushed and popped', () => {
      stack.push();
      stack.pop();
      stack.size().should.equal(0);
    });

    it('overflow', () => {
      stack.push();
      stack.push();

      (() => {
        stack.push();
      }).should.throw('Error: overflow.');
    });

    it('underflow', () => {
      stack.push();
      stack.push();
      stack.pop();
      stack.pop();

      (() => {
        stack.pop();
      }).should.throw('Error: underflow.');
    });

    it('underflow');

    it('pop the same one pushed');

    it('pop the same two pushed');

    it('accept only positive capacity');
  });
}
);
<|endoftext|>