<commit_before>import { mergeObjects, deepClone, getWatcher } from './util'
import devtoolMiddleware from './middlewares/devtool'
import override from './override'

let Vue
let uid = 0

class Store {

  /**
   * @param {Object} options
   *        - {Object} state
   *        - {Object} actions
   *        - {Object} mutations
   *        - {Array} middlewares
   *        - {Boolean} strict
   */

  constructor ({
    state = {},
    mutations = {},
    modules = {},
    middlewares = [],
    strict = false
  } = {}) {
    this._getterCacheId = 'vuex_store_' + uid++
    this._dispatching = false
    this._rootMutations = this._mutations = mutations
    this._modules = modules
    // bind dispatch to self
    const dispatch = this.dispatch
    this.dispatch = (...args) => {
      dispatch.apply(this, args)
    }
    // use a Vue instance to store the state tree
    // suppress warnings just in case the user has added
    // some funky global mixins
    if (!Vue) {
      throw new Error(
        '[vuex] must call Vue.use(Vuex) before creating a store instance.'
      )
    }
    const silent = Vue.config.silent
    Vue.config.silent = true
    this._vm = new Vue({
      data: {
        state
      }
    })
    Vue.config.silent = silent
    this._setupModuleState(state, modules)
    this._setupModuleMutations(modules)
    this._setupMiddlewares(middlewares, state)
    // add extra warnings in strict mode
    if (strict) {
      this._setupMutationCheck()
    }
  }

  /**
   * Getter for the entire state tree.
   * Read only.
   *
   * @return {Object}
   */

  get state () {
    return this._vm.state
  }

  set state (v) {
    throw new Error('[vuex] Vuex root state is read only.')
  }

  /**
   * Dispatch an action.
   *
   * @param {String} type
   */

  dispatch (type, ...payload) {
    let silent = false
    // compatibility for object actions, e.g. FSA
    if (typeof type === 'object' && type.type && arguments.length === 1) {
      payload = [type.payload]
      if (type.silent) silent = true
      type = type.type
    }
    const mutation = this._mutations[type]
    const state = this.state
    if (mutation) {
      this._dispatching = true
      // apply the mutation
      if (Array.isArray(mutation)) {
        mutation.forEach(m => m(state, ...payload))
      } else {
        mutation(state, ...payload)
      }
      this._dispatching = false
      if (!silent) this._applyMiddlewares(type, payload)
    } else {
      console.warn(`[vuex] Unknown mutation: ${type}`)
    }
  }

  /**
   * Watch state changes on the store.
   * Same API as Vue's $watch, except when watching a function,
   * the function gets the state as the first argument.
   *
   * @param {Function} fn
   * @param {Function} cb
   * @param {Object} [options]
   */

  watch (fn, cb, options) {
    if (typeof fn !== 'function') {
      console.error('Vuex store.watch only accepts function.')
      return
    }
    return this._vm.$watch(() => fn(this.state), cb, options)
  }

  /**
   * Hot update mutations & modules.
   *
   * @param {Object} options
   *        - {Object} [mutations]
   *        - {Object} [modules]
   */

  hotUpdate ({ mutations, modules } = {}) {
    this._rootMutations = this._mutations = mutations || this._rootMutations
    this._setupModuleMutations(modules || this._modules)
  }

  /**
   * Attach sub state tree of each module to the root tree.
   *
   * @param {Object} state
   * @param {Object} modules
   */

  _setupModuleState (state, modules) {
    Object.keys(modules).forEach(key => {
      Vue.set(state, key, modules[key].state || {})
    })
  }

  /**
   * Bind mutations for each module to its sub tree and
   * merge them all into one final mutations map.
   *
   * @param {Object} updatedModules
   */

  _setupModuleMutations (updatedModules) {
    const modules = this._modules
    const allMutations = [this._rootMutations]
    Object.keys(updatedModules).forEach(key => {
      modules[key] = updatedModules[key]
    })
    Object.keys(modules).forEach(key => {
      const module = modules[key]
      if (!module || !module.mutations) return
      // bind mutations to sub state tree
      const mutations = {}
      Object.keys(module.mutations).forEach(name => {
        const original = module.mutations[name]
        mutations[name] = (state, ...args) => {
          original(state[key], ...args)
        }
      })
      allMutations.push(mutations)
    })
    this._mutations = mergeObjects(allMutations)
  }

  /**
   * Setup mutation check: if the vuex instance's state is mutated
   * outside of a mutation handler, we throw en error. This effectively
   * enforces all mutations to the state to be trackable and hot-reloadble.
   * However, this comes at a run time cost since we are doing a deep
   * watch on the entire state tree, so it is only enalbed with the
   * strict option is set to true.
   */

  _setupMutationCheck () {
    const Watcher = getWatcher(this._vm)
    /* eslint-disable no-new */
    new Watcher(this._vm, 'state', () => {
      if (!this._dispatching) {
        throw new Error(
          '[vuex] Do not mutate vuex store state outside mutation handlers.'
        )
      }
    }, { deep: true, sync: true })
    /* eslint-enable no-new */
  }

  /**
   * Setup the middlewares. The devtools middleware is always
   * included, since it does nothing if no devtool is detected.
   *
   * A middleware can demand the state it receives to be
   * "snapshots", i.e. deep clones of the actual state tree.
   *
   * @param {Array} middlewares
   * @param {Object} state
   */

  _setupMiddlewares (middlewares, state) {
    this._middlewares = [devtoolMiddleware].concat(middlewares)
    this._needSnapshots = middlewares.some(m => m.snapshot)
    if (this._needSnapshots) {
      console.log(
        '[vuex] One or more of your middlewares are taking state snapshots ' +
        'for each mutation. Make sure to use them only during development.'
      )
    }
    const initialSnapshot = this._prevSnapshot = this._needSnapshots
      ? deepClone(state)
      : null
    // call init hooks
    this._middlewares.forEach(m => {
      if (m.onInit) {
        m.onInit(m.snapshot ? initialSnapshot : state, this)
      }
    })
  }

  /**
   * Apply the middlewares on a given mutation.
   *
   * @param {String} type
   * @param {Array} payload
   */

  _applyMiddlewares (type, payload) {
    const state = this.state
    const prevSnapshot = this._prevSnapshot
    let snapshot, clonedPayload
    if (this._needSnapshots) {
      snapshot = this._prevSnapshot = deepClone(state)
      clonedPayload = deepClone(payload)
    }
    this._middlewares.forEach(m => {
      if (m.onMutation) {
        if (m.snapshot) {
          m.onMutation({ type, payload: clonedPayload }, snapshot, prevSnapshot, this)
        } else {
          m.onMutation({ type, payload }, state, this)
        }
      }
    })
  }
}

function install (_Vue) {
  if (Vue) {
    console.warn(
      '[vuex] already installed. Vue.use(Vuex) should be called only once.'
    )
    return
  }
  Vue = _Vue
  override(Vue)
}

// auto install in dist mode
if (typeof window !== 'undefined' && window.Vue) {
  install(window.Vue)
}

function createLogger () {
  console.warn(
    '[vuex] Vuex.createLogger has been deprecated.' +
    'Use `import createLogger from \'vuex/logger\' instead.'
  )
}

export default {
  Store,
  install,
  createLogger
}
<commit_msg>remove createLogger<commit_after>import { mergeObjects, deepClone, getWatcher } from './util'
import devtoolMiddleware from './middlewares/devtool'
import override from './override'

let Vue
let uid = 0

class Store {

  /**
   * @param {Object} options
   *        - {Object} state
   *        - {Object} actions
   *        - {Object} mutations
   *        - {Array} middlewares
   *        - {Boolean} strict
   */

  constructor ({
    state = {},
    mutations = {},
    modules = {},
    middlewares = [],
    strict = false
  } = {}) {
    this._getterCacheId = 'vuex_store_' + uid++
    this._dispatching = false
    this._rootMutations = this._mutations = mutations
    this._modules = modules
    // bind dispatch to self
    const dispatch = this.dispatch
    this.dispatch = (...args) => {
      dispatch.apply(this, args)
    }
    // use a Vue instance to store the state tree
    // suppress warnings just in case the user has added
    // some funky global mixins
    if (!Vue) {
      throw new Error(
        '[vuex] must call Vue.use(Vuex) before creating a store instance.'
      )
    }
    const silent = Vue.config.silent
    Vue.config.silent = true
    this._vm = new Vue({
      data: {
        state
      }
    })
    Vue.config.silent = silent
    this._setupModuleState(state, modules)
    this._setupModuleMutations(modules)
    this._setupMiddlewares(middlewares, state)
    // add extra warnings in strict mode
    if (strict) {
      this._setupMutationCheck()
    }
  }

  /**
   * Getter for the entire state tree.
   * Read only.
   *
   * @return {Object}
   */

  get state () {
    return this._vm.state
  }

  set state (v) {
    throw new Error('[vuex] Vuex root state is read only.')
  }

  /**
   * Dispatch an action.
   *
   * @param {String} type
   */

  dispatch (type, ...payload) {
    let silent = false
    // compatibility for object actions, e.g. FSA
    if (typeof type === 'object' && type.type && arguments.length === 1) {
      payload = [type.payload]
      if (type.silent) silent = true
      type = type.type
    }
    const mutation = this._mutations[type]
    const state = this.state
    if (mutation) {
      this._dispatching = true
      // apply the mutation
      if (Array.isArray(mutation)) {
        mutation.forEach(m => m(state, ...payload))
      } else {
        mutation(state, ...payload)
      }
      this._dispatching = false
      if (!silent) this._applyMiddlewares(type, payload)
    } else {
      console.warn(`[vuex] Unknown mutation: ${type}`)
    }
  }

  /**
   * Watch state changes on the store.
   * Same API as Vue's $watch, except when watching a function,
   * the function gets the state as the first argument.
   *
   * @param {Function} fn
   * @param {Function} cb
   * @param {Object} [options]
   */

  watch (fn, cb, options) {
    if (typeof fn !== 'function') {
      console.error('Vuex store.watch only accepts function.')
      return
    }
    return this._vm.$watch(() => fn(this.state), cb, options)
  }

  /**
   * Hot update mutations & modules.
   *
   * @param {Object} options
   *        - {Object} [mutations]
   *        - {Object} [modules]
   */

  hotUpdate ({ mutations, modules } = {}) {
    this._rootMutations = this._mutations = mutations || this._rootMutations
    this._setupModuleMutations(modules || this._modules)
  }

  /**
   * Attach sub state tree of each module to the root tree.
   *
   * @param {Object} state
   * @param {Object} modules
   */

  _setupModuleState (state, modules) {
    Object.keys(modules).forEach(key => {
      Vue.set(state, key, modules[key].state || {})
    })
  }

  /**
   * Bind mutations for each module to its sub tree and
   * merge them all into one final mutations map.
   *
   * @param {Object} updatedModules
   */

  _setupModuleMutations (updatedModules) {
    const modules = this._modules
    const allMutations = [this._rootMutations]
    Object.keys(updatedModules).forEach(key => {
      modules[key] = updatedModules[key]
    })
    Object.keys(modules).forEach(key => {
      const module = modules[key]
      if (!module || !module.mutations) return
      // bind mutations to sub state tree
      const mutations = {}
      Object.keys(module.mutations).forEach(name => {
        const original = module.mutations[name]
        mutations[name] = (state, ...args) => {
          original(state[key], ...args)
        }
      })
      allMutations.push(mutations)
    })
    this._mutations = mergeObjects(allMutations)
  }

  /**
   * Setup mutation check: if the vuex instance's state is mutated
   * outside of a mutation handler, we throw en error. This effectively
   * enforces all mutations to the state to be trackable and hot-reloadble.
   * However, this comes at a run time cost since we are doing a deep
   * watch on the entire state tree, so it is only enalbed with the
   * strict option is set to true.
   */

  _setupMutationCheck () {
    const Watcher = getWatcher(this._vm)
    /* eslint-disable no-new */
    new Watcher(this._vm, 'state', () => {
      if (!this._dispatching) {
        throw new Error(
          '[vuex] Do not mutate vuex store state outside mutation handlers.'
        )
      }
    }, { deep: true, sync: true })
    /* eslint-enable no-new */
  }

  /**
   * Setup the middlewares. The devtools middleware is always
   * included, since it does nothing if no devtool is detected.
   *
   * A middleware can demand the state it receives to be
   * "snapshots", i.e. deep clones of the actual state tree.
   *
   * @param {Array} middlewares
   * @param {Object} state
   */

  _setupMiddlewares (middlewares, state) {
    this._middlewares = [devtoolMiddleware].concat(middlewares)
    this._needSnapshots = middlewares.some(m => m.snapshot)
    if (this._needSnapshots) {
      console.log(
        '[vuex] One or more of your middlewares are taking state snapshots ' +
        'for each mutation. Make sure to use them only during development.'
      )
    }
    const initialSnapshot = this._prevSnapshot = this._needSnapshots
      ? deepClone(state)
      : null
    // call init hooks
    this._middlewares.forEach(m => {
      if (m.onInit) {
        m.onInit(m.snapshot ? initialSnapshot : state, this)
      }
    })
  }

  /**
   * Apply the middlewares on a given mutation.
   *
   * @param {String} type
   * @param {Array} payload
   */

  _applyMiddlewares (type, payload) {
    const state = this.state
    const prevSnapshot = this._prevSnapshot
    let snapshot, clonedPayload
    if (this._needSnapshots) {
      snapshot = this._prevSnapshot = deepClone(state)
      clonedPayload = deepClone(payload)
    }
    this._middlewares.forEach(m => {
      if (m.onMutation) {
        if (m.snapshot) {
          m.onMutation({ type, payload: clonedPayload }, snapshot, prevSnapshot, this)
        } else {
          m.onMutation({ type, payload }, state, this)
        }
      }
    })
  }
}

function install (_Vue) {
  if (Vue) {
    console.warn(
      '[vuex] already installed. Vue.use(Vuex) should be called only once.'
    )
    return
  }
  Vue = _Vue
  override(Vue)
}

// auto install in dist mode
if (typeof window !== 'undefined' && window.Vue) {
  install(window.Vue)
}

export default {
  Store,
  install
}
<|endoftext|>


<commit_before>module.exports = {
    AkairoClient: require('./struct/AkairoClient'),
    AkairoHandler: require('./struct/AkairoHandler'),
    AkairoModule: require('./struct/AkairoModule'),
    Argument: require('./struct/Argument'),
    ClientUtil: require('./struct/ClientUtil'),
    Command: require('./struct/Command'),
    CommandHandler: require('./struct/CommandHandler'),
    CommandUtil: require('./struct/CommandUtil'),
    Inhibitor: require('./struct/Inhibitor'),
    InhibitorHandler: require('./struct/InhibitorHandler'),
    Listener: require('./struct/Listener'),
    ListenerHandler: require('./struct/ListenerHandler'),
    SQLiteHandler: require('./struct/SQLiteHandler'),
    TypeResolver: require('./struct/TypeResolver'),
    Category: require('./util/Category'),
    Constants: require('./util/Constants'),
    version: require('../package.json').version
};
<commit_msg>Organize index.js<commit_after>module.exports = {
    // Core
    AkairoClient: require('./struct/AkairoClient'),
    AkairoHandler: require('./struct/AkairoHandler'),
    AkairoModule: require('./struct/AkairoModule'),

    // Commands
    Argument: require('./struct/Argument'),
    Command: require('./struct/Command'),
    CommandHandler: require('./struct/CommandHandler'),
    CommandUtil: require('./struct/CommandUtil'),
    TypeResolver: require('./struct/TypeResolver'),

    // Inhibitors
    Inhibitor: require('./struct/Inhibitor'),
    InhibitorHandler: require('./struct/InhibitorHandler'),

    // Listeners
    Listener: require('./struct/Listener'),
    ListenerHandler: require('./struct/ListenerHandler'),

    // Providers
    Provider: require('./providers/Provider'),
    SequelizeProvider: require('./providers/SequelizeProvider'),
    SQLiteHandler: require('./struct/SQLiteHandler'),
    SQLiteProvider: require('./providers/SQLiteProvider'),

    // Utilities
    Category: require('./util/Category'),
    ClientUtil: require('./struct/ClientUtil'),
    Constants: require('./util/Constants'),
    version: require('../package.json').version
};
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import store from './store';
import AppContainer from './containers/appContainer';
import registerServiceWorker from './registerServiceWorker';
import "bootstrap/dist/css/bootstrap.css";
import './index.css';

ReactDOM.render(
    <Provider store={store}>
        <AppContainer />
    </Provider>,
    document.getElementById('root'));

registerServiceWorker();<commit_msg>Updates to the index<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import store from './store';
import AppContainer from './containers/appContainer';
import AdminContainer from './containers/adminContainer';
import registerServiceWorker from './registerServiceWorker';
import history from './history';
import { Route } from 'react-router'
import { ConnectedRouter } from 'react-router-redux'

import "bootstrap/dist/css/bootstrap.css";
import './index.css';

ReactDOM.render(
    <Provider store={store}>
      <ConnectedRouter history={history}>
        <div>
          <Route exact path="/" component={AppContainer}/>
          <Route exact path="/admin" component={AdminContainer}/>
        </div>
      </ConnectedRouter>
    </Provider>,
    document.getElementById('root'));

registerServiceWorker();<|endoftext|>


<commit_before>import path from 'path'
import {safelyRemoveCache, wipe} from './wipeCache';
import {_clearPlugins} from './plugins';
import plugins from './plugins/index';
import {getModuleName, getModuleParent} from './module';
import {setExtensions as resolveExtensions} from './constants';

const moduleName = getModuleName(module);
if (!moduleName) {
  throw new Error('Rewiremock: there is no "module name". If you are using Jest - disable automocking.');
}

if (!getModuleParent(module)) {
  throw new Error('Rewiremock: there is no "parent module". Is there two HotModuleReplacementPlugins?');
}

// delete core
safelyRemoveCache(path.join(path.dirname(__filename), './mockModule.js'));
// delete self
safelyRemoveCache(moduleName.replace('index.js', 'mockModule.js'));

import * as API from './mockModule';
import applyDefaultConfig from "./plugins/defaultConfig";

export const cleanup = () => {
  const wipeAll = (stubs, moduleName) => moduleName.indexOf(stubs) === 0;
  wipe(path.dirname(__filename), wipeAll);
};

export const overrideEntryPoint = (module) => {
  safelyRemoveCache(getModuleName(module));
  API.mockModule.overrideEntryPoint(getModuleParent(module));
  //API.cleanup();
};

overrideEntryPoint(module);

// instance must be clean
API.mockModule.clear();
_clearPlugins();

const addPlugin = API.addPlugin;
const removePlugin = API.removePlugin;

//addPlugin(plugins.nodejs);

addPlugin(plugins.toBeUsed);
addPlugin(plugins.directChild);

addPlugin(plugins.__mock__);

if (typeof __webpack_require__ !== "undefined") {
  addPlugin(plugins.nodeLibBrowser);
}

applyDefaultConfig(API.mockModule);

if (global['_REWIREMOCK_HOISTED_']) {
  global['_REWIREMOCK_HOISTED_'].forEach(cb => {
    cb(API.mockModule, {plugins, overrideEntryPoint})
  });
  global['_REWIREMOCK_HOISTED_'] = [];
}

export {
  addPlugin,
  removePlugin,
  plugins,
  resolveExtensions
};

export default API.mockModule;<commit_msg>update initial wiping<commit_after>import path from 'path'
import {safelyRemoveCache, wipe} from './wipeCache';
import {_clearPlugins} from './plugins';
import plugins from './plugins/index';
import {getModuleName, getModuleParent} from './module';
import {setExtensions as resolveExtensions} from './constants';
import * as API from './mockModule';
import applyDefaultConfig from "./plugins/defaultConfig";

const moduleName = getModuleName(module);
if (!moduleName) {
  throw new Error('Rewiremock: there is no "module name". If you are using Jest - disable automocking.');
}

if (!getModuleParent(module)) {
  throw new Error('Rewiremock: there is no "parent module". Is there two HotModuleReplacementPlugins?');
}

// delete core
API.cleanup();
// delete self
safelyRemoveCache(getModuleName(module));

export const cleanup = () => {
  const wipeAll = (stubs, moduleName) => moduleName.indexOf(stubs) === 0;
  wipe(path.dirname(__filename), wipeAll);
};

/**
 * override "parent" for rewiremock. Will wipe given parent from a cache
 * by default parent for rewiremock is rewiremock entrypoont, once wrapped - wrapper should set itself as a parent.
 * @param {Module} parentModule
 */
export const overrideEntryPoint = (parentModule) => {
  safelyRemoveCache(getModuleName(parentModule));
  API.mockModule.overrideEntryPoint(getModuleParent(parentModule));
};

overrideEntryPoint(module);

// instance must be clean
API.mockModule.clear();
_clearPlugins();

const addPlugin = API.addPlugin;
const removePlugin = API.removePlugin;

//addPlugin(plugins.nodejs);

addPlugin(plugins.toBeUsed);
addPlugin(plugins.directChild);

addPlugin(plugins.__mock__);

if (typeof __webpack_require__ !== "undefined") {
  addPlugin(plugins.nodeLibBrowser);
}

applyDefaultConfig(API.mockModule);

if (global['_REWIREMOCK_HOISTED_']) {
  global['_REWIREMOCK_HOISTED_'].forEach(cb => {
    cb(API.mockModule, {plugins, overrideEntryPoint})
  });
  global['_REWIREMOCK_HOISTED_'] = [];
}

export {
  addPlugin,
  removePlugin,
  plugins,
  resolveExtensions
};

export default API.mockModule;<|endoftext|>


<commit_before>import { scaleOrdinal,
         schemeCategory20 } from 'd3-scale';
import { select } from 'd3-selection';

import { action,
         store,
         observeStore } from '~/redux';
import { start,
         stop } from '~/dataControl';
import Table from '~/vis/Table';
import Chart from '~/vis/Chart';
import Bubble from '~/vis/Bubble';
import DataWindow from '~/util/DataWindow';

import dataRaw from '../data/streaming_output.json';

import 'bootstrap/dist/js/bootstrap';
import './index.less';
import './index.styl';
import content from './index.jade';

// Install the main page content.
select(document.body).html(content());

// Convert the raw data into JSON records.
const data = dataRaw.split('\n')
  .filter(x => x.length > 0)
  .map(x => JSON.parse(x));

// Kick off the application by installing the data to the store.
store.dispatch(action.setDataStream(data));

// Install action handlers
//
// Play button.
select('#play').on('click', () => {
  store.dispatch(action.start());
});

// Stop button.
select('#stop').on('click', () => {
  store.dispatch(action.stop());
});

// Rewind button.
select('#rewind').on('click', () => {
  store.dispatch(action.setDataPointer(0));
});

// Slower button.
select('#slower').on('click', () => {
  store.dispatch(action.decreaseSpeed());
});

// Faster button.
select('#faster').on('click', () => {
  store.dispatch(action.increaseSpeed());
});

// Create a data window object.
let dataWindow = new DataWindow({
  size: 100
});
let bigDataWindow = new DataWindow({
  size: 100
});

// Instantiate table view.
const color = scaleOrdinal(schemeCategory20);
let table = new Table(select('#table').node(), {
  dataWindow,
  headers: [
    'TTLs',
    'proto',
    'anomalous',
    'cluster'
  ],
  color
});
table.render();

const interval = () => store.getState().getIn(['playback', 'interval']);

// Instantiate bubble view.
let bubble = new Bubble(select('#bubble').node(), {
  dataWindow,
  interval,
  color
});
bubble.render();

// Instantiate chart view.
let chart = new Chart(select('#chart').node(), {
  dataWindow: bigDataWindow,
  interval,
  color
});
chart.render();

// Install reactive actions to changes in the store.
//
// When the data pointer changes.
observeStore(next => {
  const index = next.getIn(['datastream', 'index']);
  const data = next.getIn(['datastream', 'data'])[index];

  console.log(index, data);

  // Add the new data item to the data window.
  const datum = Object.assign({
    index
  }, data);
  dataWindow.add(datum);
  bigDataWindow.add(datum);

  // Re-render the table view.
  table.render();

  // Re-render the bubble view.
  bubble.render();

  // Re-render the chart view.
  chart.render();

  // Disable the rewind button whenever playback is at the very start of the
  // data.
  select('#rewind').attr('disabled', index === 0 ? true : null);
}, s => s.getIn(['datastream', 'index']));

// When the playback speed changes.
observeStore(next => {
  const interval = next.getIn(['playback', 'interval']);
  if (next.getIn(['playback', 'running'])) {
    start(interval);
  }

  // Disable the speed change buttons if the speed reaches the ends of the
  // range.
  if (interval === next.getIn(['playback', 'intervalHigh'])) {
    select('#slower').attr('disabled', true);
  } else if (interval === next.getIn(['playback', 'intervalLow'])) {
    select('#faster').attr('disabled', true);
  } else {
    select('#slower').attr('disabled', null);
    select('#faster').attr('disabled', null);
  }
}, s => s.getIn(['playback', 'interval']));

// When the playback state changes.
observeStore(next => {
  const running = next.getIn(['playback', 'running']);

  // Start/stop playback as needed.
  if (running) {
    start(next.getIn(['playback', 'interval']));
  } else {
    stop();
  }

  // Disable the play/stop buttons to reflect the playback state.
  select('#play').attr('disabled', running ? true : null);
  select('#stop').attr('disabled', running ? null : true);
}, s => s.getIn(['playback', 'running']));
<commit_msg>Remove a console.log statement<commit_after>import { scaleOrdinal,
         schemeCategory20 } from 'd3-scale';
import { select } from 'd3-selection';

import { action,
         store,
         observeStore } from '~/redux';
import { start,
         stop } from '~/dataControl';
import Table from '~/vis/Table';
import Chart from '~/vis/Chart';
import Bubble from '~/vis/Bubble';
import DataWindow from '~/util/DataWindow';

import dataRaw from '../data/streaming_output.json';

import 'bootstrap/dist/js/bootstrap';
import './index.less';
import './index.styl';
import content from './index.jade';

// Install the main page content.
select(document.body).html(content());

// Convert the raw data into JSON records.
const data = dataRaw.split('\n')
  .filter(x => x.length > 0)
  .map(x => JSON.parse(x));

// Kick off the application by installing the data to the store.
store.dispatch(action.setDataStream(data));

// Install action handlers
//
// Play button.
select('#play').on('click', () => {
  store.dispatch(action.start());
});

// Stop button.
select('#stop').on('click', () => {
  store.dispatch(action.stop());
});

// Rewind button.
select('#rewind').on('click', () => {
  store.dispatch(action.setDataPointer(0));
});

// Slower button.
select('#slower').on('click', () => {
  store.dispatch(action.decreaseSpeed());
});

// Faster button.
select('#faster').on('click', () => {
  store.dispatch(action.increaseSpeed());
});

// Create a data window object.
let dataWindow = new DataWindow({
  size: 100
});
let bigDataWindow = new DataWindow({
  size: 100
});

// Instantiate table view.
const color = scaleOrdinal(schemeCategory20);
let table = new Table(select('#table').node(), {
  dataWindow,
  headers: [
    'TTLs',
    'proto',
    'anomalous',
    'cluster'
  ],
  color
});
table.render();

const interval = () => store.getState().getIn(['playback', 'interval']);

// Instantiate bubble view.
let bubble = new Bubble(select('#bubble').node(), {
  dataWindow,
  interval,
  color
});
bubble.render();

// Instantiate chart view.
let chart = new Chart(select('#chart').node(), {
  dataWindow: bigDataWindow,
  interval,
  color
});
chart.render();

// Install reactive actions to changes in the store.
//
// When the data pointer changes.
observeStore(next => {
  const index = next.getIn(['datastream', 'index']);
  const data = next.getIn(['datastream', 'data'])[index];

  // Add the new data item to the data window.
  const datum = Object.assign({
    index
  }, data);
  dataWindow.add(datum);
  bigDataWindow.add(datum);

  // Re-render the table view.
  table.render();

  // Re-render the bubble view.
  bubble.render();

  // Re-render the chart view.
  chart.render();

  // Disable the rewind button whenever playback is at the very start of the
  // data.
  select('#rewind').attr('disabled', index === 0 ? true : null);
}, s => s.getIn(['datastream', 'index']));

// When the playback speed changes.
observeStore(next => {
  const interval = next.getIn(['playback', 'interval']);
  if (next.getIn(['playback', 'running'])) {
    start(interval);
  }

  // Disable the speed change buttons if the speed reaches the ends of the
  // range.
  if (interval === next.getIn(['playback', 'intervalHigh'])) {
    select('#slower').attr('disabled', true);
  } else if (interval === next.getIn(['playback', 'intervalLow'])) {
    select('#faster').attr('disabled', true);
  } else {
    select('#slower').attr('disabled', null);
    select('#faster').attr('disabled', null);
  }
}, s => s.getIn(['playback', 'interval']));

// When the playback state changes.
observeStore(next => {
  const running = next.getIn(['playback', 'running']);

  // Start/stop playback as needed.
  if (running) {
    start(next.getIn(['playback', 'interval']));
  } else {
    stop();
  }

  // Disable the play/stop buttons to reflect the playback state.
  select('#play').attr('disabled', running ? true : null);
  select('#stop').attr('disabled', running ? null : true);
}, s => s.getIn(['playback', 'running']));
<|endoftext|>


<commit_before>const defaultBeforeFetch = ({ action }) => Promise.resolve({ action });
const defaultAfterFetch = ({ action, result }) => Promise.resolve({ action, result });
const rejectHandler = ({ action, error }) => Promise.reject({ action, error });

function hasOwn(obj, ...properties) {
  return properties.every(p => obj.hasOwnProperty(p));
}

/**
 * Create a fetch middleware
 *
 * @param {object} options Options for creating fetch middleware
 *   @param  {function} beforeFetch Injection point before sending request, it should return a Promise
 *   @param  {function} afterFetch  Injection point after receive response, it should return a Promise
 *   @param  {function} onReject    Injection point when anything goes wrong, it should return a Promise
 * @return {function}
 */
export default function createFetchMiddleware(options = {}) {
  const { beforeFetch = defaultBeforeFetch, afterFetch = defaultAfterFetch, onReject = rejectHandler } = options;
  return () => next => action => {
    if (!action.url || !action.types) {
      return next(action);
    }

    const [loadingType, successType, failureType] = action.types;

    if (loadingType) {
      try {
        next({
          ...action,
          type: loadingType,
        });
      } catch (err) {
        console.error(`[fetch-middleware] Uncaught error while dispatching \`${loadingType}\`\n`, err.stack);
      }
    }

    let beforeFetchResult;
    try {
      beforeFetchResult = beforeFetch({ action });
    } catch (err) {
      throw new Error('[fetch-middleware] Uncaught error in `beforeFetch` middleware', err.stack);
    }

    if (!(beforeFetchResult instanceof Promise)) {
      throw new TypeError('[fetch-middleware] `beforeFetch` middleware returned a non-Promise object, instead got:',
                          beforeFetchResult);
    }

    return beforeFetchResult
    .then(args => {
      if (!args || typeof args !== 'object' || !hasOwn(args, 'action')) {
        console.error('[fetch-middleware] `beforeFetch` should resolve an object containing `action` key, instead got:',
                      args);
        return Promise.reject(args);
      }
      return args;
    })
    .then(
      ({ action }) => {
        const { url, types, ...options } = action; // eslint-disable-line
        return fetch(url, options).then(
          result => {
            return Promise.resolve({
              action,
              result,
            });
          },
          err => {
            return Promise.reject({
              action,
              error: err,
            });
          }
        );
      }
    )
    .then(
      ({ action, result }) => {
        let afterFetchResult;
        try {
          afterFetchResult = afterFetch({ action, result });
        } catch (err) {
          console.error('[fetch-middleware] Uncaught error in `afterFetch` middleware\n', err.stack);
        }

        if (!(afterFetchResult instanceof Promise)) {
          console.error('[fetch-middleware] `afterFetch` middleware returned a non-Promise object');
          return Promise.reject();
        }

        return afterFetchResult;
      }
    )
    .then(args => {
      if (!args || typeof args !== 'object' || !hasOwn(args, 'action', 'result')) {
        console.error('[fetch-middleware] `afterFetch` should resolve an object ' +
                      'containing `action` and `result` key, instead got',
                      args);
        return Promise.reject(args);
      }
      return args;
    })
    .catch(err => {
      if (err instanceof Error || typeof err !== 'object' || !hasOwn(err, 'action', 'error')) {
        return onReject({
          action,
          error: err,
        });
      }

      return onReject(err);
    })
    .then(
      ({ action, result }) => {
        try {
          next({
            ...action,
            payload: result,
            type: successType,
          });
        } catch (err) {
          console.error(`[fetch-middleware] Uncaught error while dispatching \`${successType}\`\n`, err.stack);
        }

        return Promise.resolve(result);
      }
    )
    .catch(
      ({ action, error }) => {
        if (failureType) {
          try {
            next({
              ...action,
              type: failureType,
              error,
            });
          } catch (err) {
            console.error(`[fetch-middleware] Uncaught error while dispatching \`${failureType}\`\n`, err.stack);
          }
        } else {
          // only reject when no `failureType` is provided, which means errors
          // are probably not handled in reducer
          return Promise.reject(error);
        }
      }
    );
  };
}

export { applyFetchMiddleware } from './applyFetchMiddleware';
<commit_msg>feat: add promise mode<commit_after>const defaultBeforeFetch = ({ action }) => Promise.resolve({ action });
const defaultAfterFetch = ({ action, result }) => Promise.resolve({ action, result });
const rejectHandler = ({ action, error }) => Promise.reject({ action, error });

function hasOwn(obj, ...properties) {
  return properties.every(p => obj.hasOwnProperty(p));
}

function noop() {}

/**
 * Create a fetch middleware
 *
 * @param {object} options     Options for creating fetch middleware
 *   @param  {function} beforeFetch Injection point before sending request, it should return a Promise
 *   @param  {function} afterFetch  Injection point after receive response, it should return a Promise
 *   @param  {function} onReject    Injection point when anything goes wrong, it should return a Promise
 * @param {bool}   promiseMode Enable promise mode, will not check action have certain keys
 * @return {function}
 */
export default function createFetchMiddleware(options = {}, promiseMode = false) {
  const { beforeFetch = defaultBeforeFetch, afterFetch = defaultAfterFetch, onReject = rejectHandler } = options;
  return () => (next = noop) => action => {
    if (!promiseMode && (!action.url || !action.types)) {
      return next(action);
    }

    if (promiseMode && !action.url) {
      throw new Error('[fetch-middleware] Missing required key: `url`');
    }

    const [loadingType, successType, failureType] = action.types;

    if (loadingType) {
      try {
        next({
          ...action,
          type: loadingType,
        });
      } catch (err) {
        console.error(`[fetch-middleware] Uncaught error while dispatching \`${loadingType}\`\n`, err.stack);
      }
    }

    let beforeFetchResult;
    try {
      beforeFetchResult = beforeFetch({ action });
    } catch (err) {
      throw new Error('[fetch-middleware] Uncaught error in `beforeFetch` middleware', err.stack);
    }

    if (!(beforeFetchResult instanceof Promise)) {
      throw new TypeError('[fetch-middleware] `beforeFetch` middleware returned a non-Promise object, instead got:',
                          beforeFetchResult);
    }

    return beforeFetchResult
    .then(args => {
      if (!args || typeof args !== 'object' || !hasOwn(args, 'action')) {
        console.error('[fetch-middleware] `beforeFetch` should resolve an object containing `action` key, instead got:',
                      args);
        return Promise.reject(args);
      }
      return args;
    })
    .then(
      ({ action }) => {
        const { url, types, ...options } = action; // eslint-disable-line
        return fetch(url, options).then(
          result => {
            return Promise.resolve({
              action,
              result,
            });
          },
          err => {
            return Promise.reject({
              action,
              error: err,
            });
          }
        );
      }
    )
    .then(
      ({ action, result }) => {
        let afterFetchResult;
        try {
          afterFetchResult = afterFetch({ action, result });
        } catch (err) {
          console.error('[fetch-middleware] Uncaught error in `afterFetch` middleware\n', err.stack);
        }

        if (!(afterFetchResult instanceof Promise)) {
          console.error('[fetch-middleware] `afterFetch` middleware returned a non-Promise object');
          return Promise.reject();
        }

        return afterFetchResult;
      }
    )
    .then(args => {
      if (!args || typeof args !== 'object' || !hasOwn(args, 'action', 'result')) {
        console.error('[fetch-middleware] `afterFetch` should resolve an object ' +
                      'containing `action` and `result` key, instead got',
                      args);
        return Promise.reject(args);
      }
      return args;
    })
    .catch(err => {
      if (err instanceof Error || typeof err !== 'object' || !hasOwn(err, 'action', 'error')) {
        return onReject({
          action,
          error: err,
        });
      }

      return onReject(err);
    })
    .then(
      ({ action, result }) => {
        try {
          next({
            ...action,
            payload: result,
            type: successType,
          });
        } catch (err) {
          console.error(`[fetch-middleware] Uncaught error while dispatching \`${successType}\`\n`, err.stack);
        }

        return Promise.resolve(result);
      }
    )
    .catch(
      ({ action, error }) => {
        if (failureType) {
          try {
            next({
              ...action,
              type: failureType,
              error,
            });
          } catch (err) {
            console.error(`[fetch-middleware] Uncaught error while dispatching \`${failureType}\`\n`, err.stack);
          }
        } else {
          // only reject when no `failureType` is provided, which means errors
          // are probably not handled in reducer
          return Promise.reject(error);
        }
      }
    );
  };
}

export { applyFetchMiddleware } from './applyFetchMiddleware';
<|endoftext|>


<commit_before>/*global module:false, require:false */
'use strict';

// start build pattern: <!-- build:[target] output -->
// $1 is the type, $2 is the alternate search path, $3 is the destination file name $4 extra attributes
var regbuild = /<!--\s*build:(\w+)(?:\(([^\)]+)\))?\s*([^\s]+)?\s*(?:(.*))?\s*-->/;

// end build pattern -- <!-- endbuild -->
var regend = /<!--\s*endbuild\s*-->/;

// IE conditional comment pattern: $1 is the start tag and $2 is the end tag
var regcc = /(<!--\[if\s.*?\]>)[\s\S]*?(<!\[endif\]-->)/i;

// Character used to create key for the `sections` object. This should probably be done more elegantly.
var sectionsJoinChar = '\ue000';

module.exports = function (content) {
  var blocks = getBlocks(content);

  content = updateReferences(blocks, content);

  var replaced = compactContent(blocks);

  return [ content, replaced ];
};

// Returns a hash object of all the directives for the given html. Results is
// of the following form:
//
//     {
//        'css/site.css ':[
//          '  <!-- build:css css/site.css -->',
//          '  <link rel="stylesheet" href="css/style.css">',
//          '  <!-- endbuild -->'
//        ],
//        'js/head.js ': [
//          '  <!-- build:js js/head.js -->',
//          '  <script src="js/libs/modernizr-2.5.3.min.js"></script>',
//          '  <!-- endbuild -->'
//        ],
//        'js/site.js ': [
//          '  <!-- build:js js/site.js -->',
//          '  <script src="js/plugins.js"></script>',
//          '  <script src="js/script.js"></script>',
//          '  <!-- endbuild -->'
//        ]
//     }
//
function getBlocks(body) {
  var lines = body.replace(/\r\n/g, '\n').split(/\n/),
    block = false,
    sections = {},
    last,
    removeBlockIndex = 0;

  lines.forEach(function (l) {
    var build = l.match(regbuild),
      endbuild = regend.test(l);

    if (build) {
      block = true;

      if(build[1] === 'remove') { build[3] = String(removeBlockIndex++); }
      if(build[4]) {
        sections[[build[1], build[3].trim(), build[4].trim()].join(sectionsJoinChar)] = last = [];
      } else {
        sections[[build[1], build[3].trim()].join(sectionsJoinChar)] = last = [];
      }
    }

    // switch back block flag when endbuild
    if (block && endbuild) {
      last.push(l);
      block = false;
    }

    if (block && last) {
      last.push(l);
    }
  });

  // sections is an array of lines starting with the build block comment opener,
  // including all the references and including the build block comment closer.
  return sections;
}

// Helpers
// -------
var helpers = {
  // useref and useref:* are used with the blocks parsed from directives
  useref: function (content, block, target, type, attbs) {
    var linefeed = /\r\n/g.test(content) ? '\r\n' : '\n',
        lines = block.split(linefeed),
        refs = lines.slice(1, -1),
        ref = '',
        indent = (lines[0].match(/^\s*/) || [])[0],
        ccmatches = block.match(regcc);

    target = target || 'replace';

    if (refs.length) {
      if (type === 'css') {
        if(attbs) {
          ref = '<link rel="stylesheet" href="' + target + '" ' + attbs + '>';
        } else {
          ref = '<link rel="stylesheet" href="' + target + '">';
        }
      } else if (type === 'js') {
        if(attbs) {
          ref = '<script src="' + target + '" ' + attbs + '></script>';
        } else {
          ref = '<script src="' + target + '"></script>';
        }
      } else if (type === 'remove') {
        ref = '';
      }
    }

    ref = indent + ref;

    // Reserve IE conditional comment if exist
    if (ccmatches) {
      ref = indent + ccmatches[1] + '\n' + ref + '\n' + indent + ccmatches[2];
    }

    return content.replace(block, ref);
  }
};

function updateReferences(blocks, content) {

  // Determine the linefeed from the content
  var linefeed = /\r\n/g.test(content) ? '\r\n' : '\n';

  // handle blocks
  Object.keys(blocks).forEach(function (key) {
    var block = blocks[key].join(linefeed),
      parts = key.split(sectionsJoinChar),
      type = parts[0],
      target = parts[1],
      attbs =  parts[2];

    content = helpers.useref(content, block, target, type, attbs);
  });

  return content;
}

function compactContent(blocks) {

  var result = {};

  Object.keys(blocks).forEach(function (dest) {
    // Lines are the included scripts w/o the use blocks
    var lines = blocks[dest].slice(1, -1),
      parts = dest.split(sectionsJoinChar),
      type = parts[0],
      // output is the useref block file
      output = parts[1],
      build = String.prototype.match.apply( blocks[dest][0], [regbuild] );

    // parse out the list of assets to handle, and update the grunt config accordingly
    var assets = lines.map(function (tag) {

      // The asset is the string of the referenced source file
      var asset = (tag.match(/(href|src)=["']([^'"]+)["']/) || [])[2];

      // Allow white space and comment in build blocks by checking if this line has an asset or not
      if (asset) {
        return asset;
      }

    }).reduce(function (a, b) {
      b = (b ? b.split(',') : '');
      return b ? a.concat(b) : a;
    }, []);

    result[type] = result[type] || {};
    result[type][output] = { 'assets': assets };
    if (build[2]) {
      // Alternate search path
      result[type][output].searchPaths = build[2];
    }
  });

  return result;
}

<commit_msg>Preserve line endings in IE conditional comments. The test for IE conditional comments was failing on Windows due to the line endings changing. This patch fixes that issue.<commit_after>/*global module:false, require:false */
'use strict';

// start build pattern: <!-- build:[target] output -->
// $1 is the type, $2 is the alternate search path, $3 is the destination file name $4 extra attributes
var regbuild = /<!--\s*build:(\w+)(?:\(([^\)]+)\))?\s*([^\s]+)?\s*(?:(.*))?\s*-->/;

// end build pattern -- <!-- endbuild -->
var regend = /<!--\s*endbuild\s*-->/;

// IE conditional comment pattern: $1 is the start tag and $2 is the end tag
var regcc = /(<!--\[if\s.*?\]>)[\s\S]*?(<!\[endif\]-->)/i;

// Character used to create key for the `sections` object. This should probably be done more elegantly.
var sectionsJoinChar = '\ue000';

module.exports = function (content) {
  var blocks = getBlocks(content);

  content = updateReferences(blocks, content);

  var replaced = compactContent(blocks);

  return [ content, replaced ];
};

// Returns a hash object of all the directives for the given html. Results is
// of the following form:
//
//     {
//        'css/site.css ':[
//          '  <!-- build:css css/site.css -->',
//          '  <link rel="stylesheet" href="css/style.css">',
//          '  <!-- endbuild -->'
//        ],
//        'js/head.js ': [
//          '  <!-- build:js js/head.js -->',
//          '  <script src="js/libs/modernizr-2.5.3.min.js"></script>',
//          '  <!-- endbuild -->'
//        ],
//        'js/site.js ': [
//          '  <!-- build:js js/site.js -->',
//          '  <script src="js/plugins.js"></script>',
//          '  <script src="js/script.js"></script>',
//          '  <!-- endbuild -->'
//        ]
//     }
//
function getBlocks(body) {
  var lines = body.replace(/\r\n/g, '\n').split(/\n/),
    block = false,
    sections = {},
    last,
    removeBlockIndex = 0;

  lines.forEach(function (l) {
    var build = l.match(regbuild),
      endbuild = regend.test(l);

    if (build) {
      block = true;

      if(build[1] === 'remove') { build[3] = String(removeBlockIndex++); }
      if(build[4]) {
        sections[[build[1], build[3].trim(), build[4].trim()].join(sectionsJoinChar)] = last = [];
      } else {
        sections[[build[1], build[3].trim()].join(sectionsJoinChar)] = last = [];
      }
    }

    // switch back block flag when endbuild
    if (block && endbuild) {
      last.push(l);
      block = false;
    }

    if (block && last) {
      last.push(l);
    }
  });

  // sections is an array of lines starting with the build block comment opener,
  // including all the references and including the build block comment closer.
  return sections;
}

// Helpers
// -------
var helpers = {
  // useref and useref:* are used with the blocks parsed from directives
  useref: function (content, block, target, type, attbs) {
    var linefeed = /\r\n/g.test(content) ? '\r\n' : '\n',
        lines = block.split(linefeed),
        refs = lines.slice(1, -1),
        ref = '',
        indent = (lines[0].match(/^\s*/) || [])[0],
        ccmatches = block.match(regcc);

    target = target || 'replace';

    if (refs.length) {
      if (type === 'css') {
        if(attbs) {
          ref = '<link rel="stylesheet" href="' + target + '" ' + attbs + '>';
        } else {
          ref = '<link rel="stylesheet" href="' + target + '">';
        }
      } else if (type === 'js') {
        if(attbs) {
          ref = '<script src="' + target + '" ' + attbs + '></script>';
        } else {
          ref = '<script src="' + target + '"></script>';
        }
      } else if (type === 'remove') {
        ref = '';
      }
    }

    ref = indent + ref;

    // Reserve IE conditional comment if exist
    if (ccmatches) {
      ref = indent + ccmatches[1] + linefeed + ref + linefeed + indent + ccmatches[2];
    }

    return content.replace(block, ref);
  }
};

function updateReferences(blocks, content) {

  // Determine the linefeed from the content
  var linefeed = /\r\n/g.test(content) ? '\r\n' : '\n';

  // handle blocks
  Object.keys(blocks).forEach(function (key) {
    var block = blocks[key].join(linefeed),
      parts = key.split(sectionsJoinChar),
      type = parts[0],
      target = parts[1],
      attbs =  parts[2];

    content = helpers.useref(content, block, target, type, attbs);
  });

  return content;
}

function compactContent(blocks) {

  var result = {};

  Object.keys(blocks).forEach(function (dest) {
    // Lines are the included scripts w/o the use blocks
    var lines = blocks[dest].slice(1, -1),
      parts = dest.split(sectionsJoinChar),
      type = parts[0],
      // output is the useref block file
      output = parts[1],
      build = String.prototype.match.apply( blocks[dest][0], [regbuild] );

    // parse out the list of assets to handle, and update the grunt config accordingly
    var assets = lines.map(function (tag) {

      // The asset is the string of the referenced source file
      var asset = (tag.match(/(href|src)=["']([^'"]+)["']/) || [])[2];

      // Allow white space and comment in build blocks by checking if this line has an asset or not
      if (asset) {
        return asset;
      }

    }).reduce(function (a, b) {
      b = (b ? b.split(',') : '');
      return b ? a.concat(b) : a;
    }, []);

    result[type] = result[type] || {};
    result[type][output] = { 'assets': assets };
    if (build[2]) {
      // Alternate search path
      result[type][output].searchPaths = build[2];
    }
  });

  return result;
}

<|endoftext|>


<commit_before>import defaults from './defaults'
import * as constants from './constants'
import * as helpers from './helpers'

import utils from './utils/utils'
import Storage from './utils/storage'
import Http from './utils/http'
import interceptors from './utils/interceptors'
import Socket from './utils/socket'
import detect from './utils/detector'
import { __dispatchEvent__, __generateFakeResponse__ } from './utils/fns'

import auth from './services/auth'
import object from './services/object'
import file from './services/file'
import query from './services/query'
import offline from './services/offline'
import user from './services/user'
import analytics from './services/analytics'
import fn from './services/function'
import bulk from './services/bulk'

// Task: Polyfills
import { Promise } from 'es6-promise'
(function(local) {
  if (local.Promise) {
   return
 }
  local.Promise = Promise;
})(typeof self !== 'undefined' ? self : new Function('return this')())
// TASK: run tests to identify the runtime environment
var detector = detect();

// TASK: set first defaults base on detector results
defaults["storage"]  = (detector.env === 'browser') ? window.localStorage : new helpers.MemoryStorage();
defaults["isMobile"] = (detector.device === 'mobile' || detector.device === 'tablet');

if(detector.env === 'browser') {
  // TASK: get data from url in social sign-in popup
  if(window.location) {
    let dataMatch = /(data|error)=(.+)/.exec(window.location.href);
    if (dataMatch && dataMatch[1] && dataMatch[2]) {
      let data = {
        data: JSON.parse(decodeURIComponent(dataMatch[2].replace(/#.*/, '')))
      }
      data.status = (dataMatch[1] === 'data') ? 200 : 0;
      if (detector.type !== 'Internet Explorer') {
        window.opener.postMessage(JSON.stringify(data), location.origin);
      }
      else {
        localStorage.setItem('SOCIAL_DATA', JSON.stringify(data));
      }
    }
  }

  // TASK: add segment analytics to head tag
  // if(document) {
  //   var script = document.createElement('script');
  //   script.type = 'text/javascript';
  //   script.innerText = analytics;
  //   document.getElementsByTagName('head')[0].appendChild(script);
  // }
}

let backand = {
  constants,
  helpers,
}
backand.init = (config = {}) => {

  // TASK: combine defaults with user config
  Object.assign(defaults, config);

  // TASK: verify new defaults
  if (!defaults.appName)
    throw new Error('appName is missing');
  if (!defaults.anonymousToken)
    defaults.useAnonymousTokenByDefault = false;
  if (defaults.externalStorage)
    defaults.storage = new helpers.MemoryStorage(defaults.externalStorage);

  // TASK: init utils
  Object.assign(utils, {
    storage: new Storage(defaults.storage, defaults.storagePrefix),
    http: Http.create({
      baseURL: defaults.apiUrl
    }),
    offline: (typeof navigator != 'undefined') ? !navigator.onLine : false,
    forceOffline: false,
    offlineAt: null,
    detector,
  });

    if(defaults.masterToken && defaults.userToken){
        auth.useBasicAuth();
    }
  if (defaults.runSocket) {
    Object.assign(utils, {
      socket: new Socket(defaults.socketUrl)
    });
  }
  // TASK: sets http interceptors for authorization header & refresh tokens
  utils.http.config.interceptors = {
    request: interceptors.requestInterceptor,
    response: interceptors.responseInterceptor,
    responseError: interceptors.responseErrorInterceptor,
  }

  // TASK: clean cache if needed
  let storeUser = utils.storage.get('user');
  if (storeUser && storeUser.token["AnonymousToken"] && (storeUser.token["AnonymousToken"] !== defaults.anonymousToken || !defaults.useAnonymousTokenByDefault)) {
    utils.storage.remove('user');
  }
  if (storeUser && storeUser.details.token_type && (storeUser.details.token_type === "Basic" && storeUser.token['Authorization'] !== 'Basic ' + auth.createBasicToken(defaults.masterToken, defaults.userToken))){
    utils.storage.remove('user');
  }

  if (storeUser && storeUser.details.access_token && storeUser.details.appName !== defaults.appName) {
    utils.storage.remove('user');
  }
  // TASK: set offline events
  function afterProcessReq(request, response) {
    defaults.afterExecuteOfflineItem(response, request.payload);
    return processReqs(utils.storage.get('queue'));
  }

  function processReqs(requests) {
    if(utils.offline) {
      // When enter offline mode during the process
      return;
    }
    let request = requests.shift();
    utils.storage.set('queue', requests);
    if(!request) {
      return;
    }
    if(defaults.beforeExecuteOfflineItem(request.payload)) {
      if(request.action === 'create') {
        object[request.action].apply(null, request.params)
          .then(afterProcessReq.bind(null, request)).catch(afterProcessReq.bind(null, request));
      }
      else {
        object.getOne(request.params[0], request.params[1]).then((response) => {
          if(!response.data.updatedAt) {
            return Promise.reject(__generateFakeResponse__(0, '', {}, 'Cannot update this object, object is missing updatedAt property', {}));
          }
          if(new Date(response.data.updatedAt) > utils.offlineAt) {
            return Promise.reject(__generateFakeResponse__(0, '', {}, 'Cannot update this object, object was updated after you entered offline mode', {}));
          }
          return object[request.action].apply(null, request.params);
        }).then(afterProcessReq.bind(null, request)).catch(afterProcessReq.bind(null, request));
      }
    }
    else {
      return processReqs(utils.storage.get('queue'));
    }
  }
  function __updateOnlineStatus__(event) {
    if(utils.offline) {
      utils.offlineAt = new Date();
      __dispatchEvent__('startOfflineMode');
      console.info('SDK started offline mode')
    }
    else {
      __dispatchEvent__('endOfflineMode');
      console.info('SDK finished offline mode');
      processReqs(utils.storage.get('queue'));
    }
  }
  if (defaults.runOffline && utils.detector.env === 'browser') {
    window.addEventListener('online',  __updateOnlineStatus__);
    window.addEventListener('offline', __updateOnlineStatus__);
  }
  // TASK: set offline storage
  if (defaults.runOffline) {
    if (!utils.storage.get('cache')) {
      utils.storage.set('cache', {});
    }
    if (!utils.storage.get('queue')) {
      utils.storage.set('queue', []);
    }
  }

  // TASK: expose backand namespace to window
  delete backand.init;
  Object.assign(
    backand,
    auth,
    {
      invoke: utils.http,
      defaults,
      object,
      file,
      query,
      user,
      offline,
      fn,
      bulk
    }
  );
  if(defaults.runSocket) {
    storeUser = utils.storage.get('user');
    storeUser && utils.socket.connect(
      storeUser.token.Authorization || null,
      defaults.anonymousToken,
      defaults.appName
    );
    Object.assign(backand, {
      on: Socket.prototype.on.bind(utils.socket),
    });
  }
  if(defaults.exportUtils) {
    Object.assign(backand, { utils });
  }

}

module.exports = backand
<commit_msg>fix socket for anonymus users<commit_after>import defaults from './defaults'
import * as constants from './constants'
import * as helpers from './helpers'

import utils from './utils/utils'
import Storage from './utils/storage'
import Http from './utils/http'
import interceptors from './utils/interceptors'
import Socket from './utils/socket'
import detect from './utils/detector'
import { __dispatchEvent__, __generateFakeResponse__ } from './utils/fns'

import auth from './services/auth'
import object from './services/object'
import file from './services/file'
import query from './services/query'
import offline from './services/offline'
import user from './services/user'
import analytics from './services/analytics'
import fn from './services/function'
import bulk from './services/bulk'

// Task: Polyfills
import { Promise } from 'es6-promise'
(function(local) {
  if (local.Promise) {
   return
 }
  local.Promise = Promise;
})(typeof self !== 'undefined' ? self : new Function('return this')())
// TASK: run tests to identify the runtime environment
var detector = detect();

// TASK: set first defaults base on detector results
defaults["storage"]  = (detector.env === 'browser') ? window.localStorage : new helpers.MemoryStorage();
defaults["isMobile"] = (detector.device === 'mobile' || detector.device === 'tablet');

if(detector.env === 'browser') {
  // TASK: get data from url in social sign-in popup
  if(window.location) {
    let dataMatch = /(data|error)=(.+)/.exec(window.location.href);
    if (dataMatch && dataMatch[1] && dataMatch[2]) {
      let data = {
        data: JSON.parse(decodeURIComponent(dataMatch[2].replace(/#.*/, '')))
      }
      data.status = (dataMatch[1] === 'data') ? 200 : 0;
      if (detector.type !== 'Internet Explorer') {
        window.opener.postMessage(JSON.stringify(data), location.origin);
      }
      else {
        localStorage.setItem('SOCIAL_DATA', JSON.stringify(data));
      }
    }
  }

  // TASK: add segment analytics to head tag
  // if(document) {
  //   var script = document.createElement('script');
  //   script.type = 'text/javascript';
  //   script.innerText = analytics;
  //   document.getElementsByTagName('head')[0].appendChild(script);
  // }
}

let backand = {
  constants,
  helpers,
}
backand.init = (config = {}) => {

  // TASK: combine defaults with user config
  Object.assign(defaults, config);

  // TASK: verify new defaults
  if (!defaults.appName)
    throw new Error('appName is missing');
  if (!defaults.anonymousToken)
    defaults.useAnonymousTokenByDefault = false;
  if (defaults.externalStorage)
    defaults.storage = new helpers.MemoryStorage(defaults.externalStorage);

  // TASK: init utils
  Object.assign(utils, {
    storage: new Storage(defaults.storage, defaults.storagePrefix),
    http: Http.create({
      baseURL: defaults.apiUrl
    }),
    offline: (typeof navigator != 'undefined') ? !navigator.onLine : false,
    forceOffline: false,
    offlineAt: null,
    detector,
  });

    if(defaults.masterToken && defaults.userToken){
        auth.useBasicAuth();
    }
  if (defaults.runSocket) {
    Object.assign(utils, {
      socket: new Socket(defaults.socketUrl)
    });
  }
  // TASK: sets http interceptors for authorization header & refresh tokens
  utils.http.config.interceptors = {
    request: interceptors.requestInterceptor,
    response: interceptors.responseInterceptor,
    responseError: interceptors.responseErrorInterceptor,
  }

  // TASK: clean cache if needed
  let storeUser = utils.storage.get('user');
  if (storeUser && storeUser.token["AnonymousToken"] && (storeUser.token["AnonymousToken"] !== defaults.anonymousToken || !defaults.useAnonymousTokenByDefault)) {
    utils.storage.remove('user');
  }
  if (storeUser && storeUser.details.token_type && (storeUser.details.token_type === "Basic" && storeUser.token['Authorization'] !== 'Basic ' + auth.createBasicToken(defaults.masterToken, defaults.userToken))){
    utils.storage.remove('user');
  }

  if (storeUser && storeUser.details.access_token && storeUser.details.appName !== defaults.appName) {
    utils.storage.remove('user');
  }
  // TASK: set offline events
  function afterProcessReq(request, response) {
    defaults.afterExecuteOfflineItem(response, request.payload);
    return processReqs(utils.storage.get('queue'));
  }

  function processReqs(requests) {
    if(utils.offline) {
      // When enter offline mode during the process
      return;
    }
    let request = requests.shift();
    utils.storage.set('queue', requests);
    if(!request) {
      return;
    }
    if(defaults.beforeExecuteOfflineItem(request.payload)) {
      if(request.action === 'create') {
        object[request.action].apply(null, request.params)
          .then(afterProcessReq.bind(null, request)).catch(afterProcessReq.bind(null, request));
      }
      else {
        object.getOne(request.params[0], request.params[1]).then((response) => {
          if(!response.data.updatedAt) {
            return Promise.reject(__generateFakeResponse__(0, '', {}, 'Cannot update this object, object is missing updatedAt property', {}));
          }
          if(new Date(response.data.updatedAt) > utils.offlineAt) {
            return Promise.reject(__generateFakeResponse__(0, '', {}, 'Cannot update this object, object was updated after you entered offline mode', {}));
          }
          return object[request.action].apply(null, request.params);
        }).then(afterProcessReq.bind(null, request)).catch(afterProcessReq.bind(null, request));
      }
    }
    else {
      return processReqs(utils.storage.get('queue'));
    }
  }
  function __updateOnlineStatus__(event) {
    if(utils.offline) {
      utils.offlineAt = new Date();
      __dispatchEvent__('startOfflineMode');
      console.info('SDK started offline mode')
    }
    else {
      __dispatchEvent__('endOfflineMode');
      console.info('SDK finished offline mode');
      processReqs(utils.storage.get('queue'));
    }
  }
  if (defaults.runOffline && utils.detector.env === 'browser') {
    window.addEventListener('online',  __updateOnlineStatus__);
    window.addEventListener('offline', __updateOnlineStatus__);
  }
  // TASK: set offline storage
  if (defaults.runOffline) {
    if (!utils.storage.get('cache')) {
      utils.storage.set('cache', {});
    }
    if (!utils.storage.get('queue')) {
      utils.storage.set('queue', []);
    }
  }

  // TASK: expose backand namespace to window
  delete backand.init;
  Object.assign(
    backand,
    auth,
    {
      invoke: utils.http,
      defaults,
      object,
      file,
      query,
      user,
      offline,
      fn,
      bulk
    }
  );
  if(defaults.runSocket) {
    storeUser = utils.storage.get('user');
    var authToken = (storeUser) ? storeUser.token.Authorization : null;
    storeUser && utils.socket.connect(
      authToken,
      defaults.anonymousToken,
      defaults.appName
    );
    Object.assign(backand, {
      on: Socket.prototype.on.bind(utils.socket),
    });
  }
  if(defaults.exportUtils) {
    Object.assign(backand, { utils });
  }

}

module.exports = backand
<|endoftext|>


<commit_before>"use strict";

var extract = require("./extract");
var linter = require("eslint").linter;

var htmlExtensions = [
  ".erb",
  ".handelbars",
  ".hbs",
  ".htm",
  ".html",
  ".mustache",
  ".php",
  ".tag",
  ".twig",
  ".vue",
  ".we",
];

var xmlExtensions = [
  ".xhtml",
  ".xml",
];

// Disclaimer:
//
// This is not a long term viable solution. ESLint needs to improve its processor API to
// provide access to the configuration before actually preprocess files, but it's not
// planed yet. This solution is quite ugly but shouldn't alter eslint process.
//
// Related github issues:
// https://github.com/eslint/eslint/issues/3422
// https://github.com/eslint/eslint/issues/4153

function createProcessor(defaultXMLMode) {
  var verify = linter.verify;
  var reportBadIndent;

  var currentInfos;

  function patch() {
    linter.verify = function (textOrSourceCode, config, filenameOrOptions, saveState) {
      var indentDescriptor = config.settings && config.settings["html/indent"];
      var xmlMode = config.settings && config.settings["html/xml-mode"];
      reportBadIndent = config.settings && config.settings["html/report-bad-indent"];

      if (typeof xmlMode !== "boolean") {
        xmlMode = defaultXMLMode;
      }

      currentInfos = extract(textOrSourceCode, {
        indent: indentDescriptor,
        reportBadIndent: Boolean(reportBadIndent),
        xmlMode: xmlMode,
      });
      return verify.call(this, currentInfos.code, config, filenameOrOptions, saveState);
    };
  }

  function unpatch() {
    linter.verify = verify;
  }
  return {

    preprocess: function (content) {
      patch();
      return [content];
    },

    postprocess: function (messages) {
      unpatch();

      messages[0].forEach(function (message) {
        message.column += currentInfos.map[message.line] || 0;
      });

      currentInfos.badIndentationLines.forEach(function (line) {
        messages[0].push({
          message: "Bad line indentation.",
          line: line,
          column: 1,
          ruleId: "(html plugin)",
          severity: reportBadIndent === true ? 2 : reportBadIndent,
        });
      });

      messages[0].sort(function (ma, mb) {
        return ma.line - mb.line || ma.column - mb.column;
      });

      return messages[0];
    },

  };

}

var htmlProcessor = createProcessor(false);
var xmlProcessor = createProcessor(true);

var processors = {};

htmlExtensions.forEach(function(ext) {
  processors[ext] = htmlProcessor;
});

xmlExtensions.forEach(function(ext) {
  processors[ext] = xmlProcessor;
});

exports.processors = processors;
<commit_msg>restore eslint package discovery<commit_after>"use strict";

var path = require("path");
var extract = require("./extract");

var htmlExtensions = [
  ".erb",
  ".handelbars",
  ".hbs",
  ".htm",
  ".html",
  ".mustache",
  ".php",
  ".tag",
  ".twig",
  ".vue",
  ".we",
];

var xmlExtensions = [
  ".xhtml",
  ".xml",
];

// Disclaimer:
//
// This is not a long term viable solution. ESLint needs to improve its processor API to
// provide access to the configuration before actually preprocess files, but it's not
// planed yet. This solution is quite ugly but shouldn't alter eslint process.
//
// Related github issues:
// https://github.com/eslint/eslint/issues/3422
// https://github.com/eslint/eslint/issues/4153

var needle = path.join("lib", "eslint.js");
var eslint;
for (var key in require.cache) {
  if (key.indexOf(needle, key.length - needle.length) >= 0) {
    eslint = require(key);
    if (typeof eslint.verify === "function") {
      break;
    }
  }
}

if (!eslint) {
  throw new Error("eslint-plugin-html error: It seems that eslint is not loaded. " +
                  "If you think it is a bug, please file a report at " +
                  "https://github.com/BenoitZugmeyer/eslint-plugin-html/issues");
}

function createProcessor(defaultXMLMode) {
  var verify = eslint.verify;
  var reportBadIndent;

  var currentInfos;

  function patch() {
    eslint.verify = function (textOrSourceCode, config, filenameOrOptions, saveState) {
      var indentDescriptor = config.settings && config.settings["html/indent"];
      var xmlMode = config.settings && config.settings["html/xml-mode"];
      reportBadIndent = config.settings && config.settings["html/report-bad-indent"];

      if (typeof xmlMode !== "boolean") {
        xmlMode = defaultXMLMode;
      }

      currentInfos = extract(textOrSourceCode, {
        indent: indentDescriptor,
        reportBadIndent: Boolean(reportBadIndent),
        xmlMode: xmlMode,
      });
      return verify.call(this, currentInfos.code, config, filenameOrOptions, saveState);
    };
  }

  function unpatch() {
    eslint.verify = verify;
  }
  return {

    preprocess: function (content) {
      patch();
      return [content];
    },

    postprocess: function (messages) {
      unpatch();

      messages[0].forEach(function (message) {
        message.column += currentInfos.map[message.line] || 0;
      });

      currentInfos.badIndentationLines.forEach(function (line) {
        messages[0].push({
          message: "Bad line indentation.",
          line: line,
          column: 1,
          ruleId: "(html plugin)",
          severity: reportBadIndent === true ? 2 : reportBadIndent,
        });
      });

      messages[0].sort(function (ma, mb) {
        return ma.line - mb.line || ma.column - mb.column;
      });

      return messages[0];
    },

  };

}

var htmlProcessor = createProcessor(false);
var xmlProcessor = createProcessor(true);

var processors = {};

htmlExtensions.forEach(function(ext) {
  processors[ext] = htmlProcessor;
});

xmlExtensions.forEach(function(ext) {
  processors[ext] = xmlProcessor;
});

exports.processors = processors;
<|endoftext|>


<commit_before>import {BindingLanguage} from 'aurelia-templating';
import {TemplatingBindingLanguage} from './binding-language';
import {SyntaxInterpreter} from './syntax-interpreter';

function install(aurelia){
  var instance,
      getInstance = c => instance || instance = c.invoke(TemplatingBindingLanguage);

  if(aurelia.container.hasHandler(TemplatingBindingLanguage)){
    instance = aurelia.container.get(TemplatingBindingLanguage);
  }else{
    aurelia.container.registerHandler(TemplatingBindingLanguage, getInstance);
  }

  aurelia.container.registerHandler(BindingLanguage, getInstance);
}

export {
  TemplatingBindingLanguage,
  SyntaxInterpreter,
  install
};<commit_msg>fix(index): fix compiler error in plugin install function<commit_after>import {BindingLanguage} from 'aurelia-templating';
import {TemplatingBindingLanguage} from './binding-language';
import {SyntaxInterpreter} from './syntax-interpreter';

function install(aurelia){
  var instance,
      getInstance = function (c){
        return instance || (instance = c.invoke(TemplatingBindingLanguage));
      };

  if(aurelia.container.hasHandler(TemplatingBindingLanguage)){
    instance = aurelia.container.get(TemplatingBindingLanguage);
  }else{
    aurelia.container.registerHandler(TemplatingBindingLanguage, getInstance);
  }

  aurelia.container.registerHandler(BindingLanguage, getInstance);
}

export {
  TemplatingBindingLanguage,
  SyntaxInterpreter,
  install
};<|endoftext|>


<commit_before>'use strict';

module.exports = tileReduce;

var EventEmitter = require('events').EventEmitter;
var cpus = require('os').cpus().length;
var fork = require('child_process').fork;
var path = require('path');
var fs = require('fs');
var split = require('split');
var binarysplit = require('binary-split');
var cover = require('./cover');
var streamArray = require('stream-array');

var tileTransform = split(function(line) {
  return line.split(' ').map(Number);
});

function tileReduce(options) {
  var workers = [];
  var workersReady = 0;
  var tileStream = null;
  var tilesDone = 0;
  var tilesSent = 0;
  var pauseLimit = 5000;
  var start = Date.now();

  // Suppress listener warnings for pipes to stdout
  process.stdout.setMaxListeners(cpus);

  for (var i = 0; i < cpus; i++) {
    var worker = fork(path.join(__dirname, 'worker.js'), [options.map, JSON.stringify(options.sources)], {silent: true});
    worker.stdout.pipe(binarysplit('\x1e')).pipe(process.stdout);
    worker.on('message', handleMessage);
    workers.push(worker);
  }

  function handleMessage(message) {
    if (message.reduce) reduce(message.value);
    else if (message.ready && ++workersReady === workers.length) run();
  }

  var ee = new EventEmitter();
  var tiles = typeof options.tiles === 'string' ? null : cover(options);

  var timer = setInterval(updateStatus, 64);

  function run() {
    ee.emit('start');

    if (tiles) {
      tileStream = streamArray(tiles).on('data', handleTile);
    } else {
      tileStream = fs.createReadStream(options.tiles);
      tileStream.pipe(tileTransform).on('data', handleTile);
    }
  }

  var paused = false;

  function handleTile(tile) {
    workers[tilesSent++ % workers.length].send(tile);
    if (!paused && tilesSent - tilesDone > pauseLimit) {
      paused = true;
      tileStream.pause();
    }
  }

  function reduce(value) {
    if (value !== null && value !== undefined) ee.emit('reduce', value);
    if (paused && tilesSent - tilesDone < (pauseLimit / 2)) {
      paused = false;
      tileStream.resume();
    }
    if (++tilesDone === tilesSent) shutdown();
  }

  function shutdown() {
    while (workers.length) workers.pop().kill();

    clearTimeout(timer);
    updateStatus();
    process.stderr.write('.\n');

    ee.emit('end');
  }

  function updateStatus() {
    var s = Math.floor((Date.now() - start) / 1000);
    var h = Math.floor(s / 3600);
    var m = Math.floor((s - h * 3600) / 60);
    var time = (h ? h + 'h ' : '') + (h || m ? m + 'm ' : '') + (s % 60) + 's';

    process.stderr.cursorTo(0);
    process.stderr.write(tilesDone + ' tiles processed in ' + time);
    process.stderr.clearLine(1);
  }

  return ee;
}
<commit_msg>pipe child stderr<commit_after>'use strict';

module.exports = tileReduce;

var EventEmitter = require('events').EventEmitter;
var cpus = require('os').cpus().length;
var fork = require('child_process').fork;
var path = require('path');
var fs = require('fs');
var split = require('split');
var binarysplit = require('binary-split');
var cover = require('./cover');
var streamArray = require('stream-array');

var tileTransform = split(function(line) {
  return line.split(' ').map(Number);
});

function tileReduce(options) {
  var workers = [];
  var workersReady = 0;
  var tileStream = null;
  var tilesDone = 0;
  var tilesSent = 0;
  var pauseLimit = 5000;
  var start = Date.now();

  // Suppress max listener warnings. We need 1 pipe per worker
  process.stdout.setMaxListeners(cpus);
  process.stderr.setMaxListeners(cpus);

  for (var i = 0; i < cpus; i++) {
    var worker = fork(path.join(__dirname, 'worker.js'), [options.map, JSON.stringify(options.sources)], {silent: true});
    worker.stdout.pipe(binarysplit('\x1e')).pipe(process.stdout);
    worker.stderr.pipe(process.stderr);
    worker.on('message', handleMessage);
    workers.push(worker);
  }

  function handleMessage(message) {
    if (message.reduce) reduce(message.value);
    else if (message.ready && ++workersReady === workers.length) run();
  }

  var ee = new EventEmitter();
  var tiles = typeof options.tiles === 'string' ? null : cover(options);

  var timer = setInterval(updateStatus, 64);

  function run() {
    ee.emit('start');

    if (tiles) {
      tileStream = streamArray(tiles).on('data', handleTile);
    } else {
      tileStream = fs.createReadStream(options.tiles);
      tileStream.pipe(tileTransform).on('data', handleTile);
    }
  }

  var paused = false;

  function handleTile(tile) {
    workers[tilesSent++ % workers.length].send(tile);
    if (!paused && tilesSent - tilesDone > pauseLimit) {
      paused = true;
      tileStream.pause();
    }
  }

  function reduce(value) {
    if (value !== null && value !== undefined) ee.emit('reduce', value);
    if (paused && tilesSent - tilesDone < (pauseLimit / 2)) {
      paused = false;
      tileStream.resume();
    }
    if (++tilesDone === tilesSent) shutdown();
  }

  function shutdown() {
    while (workers.length) workers.pop().kill();

    clearTimeout(timer);
    updateStatus();
    process.stderr.write('.\n');

    ee.emit('end');
  }

  function updateStatus() {
    var s = Math.floor((Date.now() - start) / 1000);
    var h = Math.floor(s / 3600);
    var m = Math.floor((s - h * 3600) / 60);
    var time = (h ? h + 'h ' : '') + (h || m ? m + 'm ' : '') + (s % 60) + 's';

    process.stderr.cursorTo(0);
    process.stderr.write(tilesDone + ' tiles processed in ' + time);
    process.stderr.clearLine(1);
  }

  return ee;
}
<|endoftext|>


<commit_before>export const BATCH = 'BATCHING_REDUCER.BATCH';

export function batchActions(actions, type = BATCH) {
	return {type, meta: { batch: true }, payload: actions}
}

export function enableBatching(reduce) {
	return function batchingReducer(state, action) {
		if (action && action.meta && action.meta.batch) {
			return action.payload.reduce(batchingReducer, state);
		}
		return reduce(state, action);
	}
}

export function batchDispatchMiddleware(store) {
	function dispatchChildActions(store, action) {
		if(action.meta && action.meta.batch) {
			action.payload.map(function(childAction) {
				dispatchChildActions(store, childAction)
			})
		} else {
			store.dispatch(action)
		}
	}

	return function(next) {
		return function(action) {
			dispatchChildActions(store, action)
			next(action)
		}
	}
}
<commit_msg>Use forEach instead of map<commit_after>export const BATCH = 'BATCHING_REDUCER.BATCH';

export function batchActions(actions, type = BATCH) {
	return {type, meta: { batch: true }, payload: actions}
}

export function enableBatching(reduce) {
	return function batchingReducer(state, action) {
		if (action && action.meta && action.meta.batch) {
			return action.payload.reduce(batchingReducer, state);
		}
		return reduce(state, action);
	}
}

export function batchDispatchMiddleware(store) {
	function dispatchChildActions(store, action) {
		if(action.meta && action.meta.batch) {
			action.payload.forEach(function(childAction) {
				dispatchChildActions(store, childAction)
			})
		} else {
			store.dispatch(action)
		}
	}

	return function(next) {
		return function(action) {
			dispatchChildActions(store, action)
			next(action)
		}
	}
}
<|endoftext|>


<commit_before>import React from 'react';
import {render} from 'react-dom';
import HardCoded from './containers/HardCoded';
import App from './containers/App';

import './styles/styles.scss'; //Yep, that's right. You can import SASS/CSS files too! Webpack will run the associated loader and plug this into the page.

render(
  <HardCoded/>, document.getElementById('app')
);
<commit_msg>App Container<commit_after>import React from 'react';
import {render} from 'react-dom';
import HardCoded from './containers/HardCoded';
//import App from './containers/App';

import './styles/styles.scss'; //Yep, that's right. You can import SASS/CSS files too! Webpack will run the associated loader and plug this into the page.

render(
  <HardCoded/>, document.getElementById('app')
);

//render(
//  <App/>, document.getElementById('app')
//);
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2017 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

// enable FOAM java support.
global.FOAM_FLAGS = { 'java': true, 'debug': true };

require('../src/foam.js');

if ( process.argv.length != 4 ) {
  console.log("USAGE: genjava.js input-path output-path");
  process.exit(1);
}

var indir = process.argv[2];
indir = require('path').resolve(require('path').normalize(indir));

var externalFile = require(indir);
var classes = externalFile.classes;
var abstractClasses = externalFile.abstractClasses;
var skeletons = externalFile.skeletons;
var proxies = externalFile.proxies;

var outdir = process.argv[3];
outdir = require('path').resolve(require('path').normalize(outdir));

function ensurePath(p) {
  var i = 1 ;
  var parts = p.split(require('path').sep);
  var path = '/' + parts[0];

  while ( i < parts.length ) {
    try {
      var stat = require('fs').statSync(path);
      if ( ! stat.isDirectory() ) throw path + 'is not a directory';
    } catch(e) {
      require('fs').mkdirSync(path);
    }

    path += require('path').sep + parts[i++];
  }
}

function loadClass(c) {
  if ( ! foam.lookup(c, true) ) require('../src/' + c.replace(/\./g, '/') + '.js');
  return foam.lookup(c);
}

function generateClass(cls) {
  if ( typeof cls === 'string' )
    cls = foam.lookup(cls);

  var outfile = outdir + require('path').sep +
    cls.id.replace(/\./g, require('path').sep) + '.java';

  ensurePath(outfile);

  require('fs').writeFileSync(outfile, cls.buildJavaClass().toJavaSource());
}

function generateAbstractClass(cls) {
  cls = foam.lookup(cls);

  var outfile = outdir + require('path').sep +
    cls.id.replace(/\./g, require('path').sep) + '.java';

  ensurePath(outfile);

  var javaclass = cls.buildJavaClass();
  javaclass.abstract = true;

  require('fs').writeFileSync(outfile, javaclass.toJavaSource());
}

function generateSkeleton(cls) {
  cls = foam.lookup(cls);

  var outfile = outdir + require('path').sep +
    cls.package.replace(/\./g, require('path').sep) +
    require('path').sep + cls.name + 'Skeleton.java';

  ensurePath(outfile);

  require('fs').writeFileSync(
    outfile,
    foam.java.Skeleton.create({ of: cls }).buildJavaClass().toJavaSource());
}

function generateProxy(intf) {
  intf = foam.lookup(intf);

  var existing = foam.lookup(intf.package + '.Proxy' + intf.name, true);

  if ( existing ) {
    generateClass(existing.id);
    return;
  }

  var proxy = foam.core.Model.create({
    package: intf.package,
    name: 'Proxy' + intf.name,
    implements: [intf.id],
    properties: [
      {
        class: 'Proxy',
        of: intf.id,
        name: 'delegate'
      }
    ]
  });

  generateClass(proxy.buildClass());
}

classes.forEach(loadClass);
abstractClasses.forEach(loadClass);
skeletons.forEach(loadClass);
proxies.forEach(loadClass);

classes.forEach(generateClass);
abstractClasses.forEach(generateAbstractClass);
skeletons.forEach(generateSkeleton);
proxies.forEach(generateProxy);
<commit_msg>genjava now also loads nanos.js.<commit_after>/**
 * @license
 * Copyright 2017 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

// enable FOAM java support.
global.FOAM_FLAGS = { 'java': true, 'debug': true };

require('../src/foam.js');
require('../src/foam/nanos/nanos.js');

if ( process.argv.length != 4 ) {
  console.log("USAGE: genjava.js input-path output-path");
  process.exit(1);
}

var indir = process.argv[2];
indir = require('path').resolve(require('path').normalize(indir));

var externalFile = require(indir);
var classes = externalFile.classes;
var abstractClasses = externalFile.abstractClasses;
var skeletons = externalFile.skeletons;
var proxies = externalFile.proxies;

var outdir = process.argv[3];
outdir = require('path').resolve(require('path').normalize(outdir));

function ensurePath(p) {
  var i = 1 ;
  var parts = p.split(require('path').sep);
  var path = '/' + parts[0];

  while ( i < parts.length ) {
    try {
      var stat = require('fs').statSync(path);
      if ( ! stat.isDirectory() ) throw path + 'is not a directory';
    } catch(e) {
      require('fs').mkdirSync(path);
    }

    path += require('path').sep + parts[i++];
  }
}

function loadClass(c) {
  if ( ! foam.lookup(c, true) ) require('../src/' + c.replace(/\./g, '/') + '.js');
  return foam.lookup(c);
}

function generateClass(cls) {
  if ( typeof cls === 'string' )
    cls = foam.lookup(cls);

  var outfile = outdir + require('path').sep +
    cls.id.replace(/\./g, require('path').sep) + '.java';

  ensurePath(outfile);

  require('fs').writeFileSync(outfile, cls.buildJavaClass().toJavaSource());
}

function generateAbstractClass(cls) {
  cls = foam.lookup(cls);

  var outfile = outdir + require('path').sep +
    cls.id.replace(/\./g, require('path').sep) + '.java';

  ensurePath(outfile);

  var javaclass = cls.buildJavaClass();
  javaclass.abstract = true;

  require('fs').writeFileSync(outfile, javaclass.toJavaSource());
}

function generateSkeleton(cls) {
  cls = foam.lookup(cls);

  var outfile = outdir + require('path').sep +
    cls.package.replace(/\./g, require('path').sep) +
    require('path').sep + cls.name + 'Skeleton.java';

  ensurePath(outfile);

  require('fs').writeFileSync(
    outfile,
    foam.java.Skeleton.create({ of: cls }).buildJavaClass().toJavaSource());
}

function generateProxy(intf) {
  intf = foam.lookup(intf);

  var existing = foam.lookup(intf.package + '.Proxy' + intf.name, true);

  if ( existing ) {
    generateClass(existing.id);
    return;
  }

  var proxy = foam.core.Model.create({
    package: intf.package,
    name: 'Proxy' + intf.name,
    implements: [intf.id],
    properties: [
      {
        class: 'Proxy',
        of: intf.id,
        name: 'delegate'
      }
    ]
  });

  generateClass(proxy.buildClass());
}

classes.forEach(loadClass);
abstractClasses.forEach(loadClass);
skeletons.forEach(loadClass);
proxies.forEach(loadClass);

classes.forEach(generateClass);
abstractClasses.forEach(generateAbstractClass);
skeletons.forEach(generateSkeleton);
proxies.forEach(generateProxy);
<|endoftext|>