<commit_before>'use babel'
/** @jsx etch.dom */

import etch from 'etch'

import { TextEditor, CompositeDisposable } from 'atom'
import PaneItem from '../util/pane-item'
import { toView, Toolbar, Button, Icon, makeicon, Etch } from '../util/etch'

export default class DocPane extends PaneItem {
  constructor () {
    super()

    this.setTitle('Documentation')
    this.content = []
    this.items = []
    this.mode = 'empty'
    this.exportedOnly = false
    this.allPackages = false
    this.namesOnly = false
    this.searchEd = new TextEditor({mini: true, placeholderText: "Search Documentation"})
    this.modEd = new TextEditor({mini: true, placeholderText: "in all modules"})

    this.subs = new CompositeDisposable()
    this.subs.add(atom.commands.add('.docpane .header .editor', {
      'docpane:search': () => this._search()
    }))

    etch.initialize(this)
    this.element.setAttribute('tabindex', -1)
  }

  open(opts) {
    return super.open(opts).then(docPane => {
      docPane.searchEd.getElement().focus()
    })
  }

  _search (query = this.searchEd.getText(), mod = this.modEd.getText(),
           eo = this.exportedOnly, ap = this.allPackages, np = this.namesOnly) {
    this.setContent('loading')
    this.search(query, mod || "Main", eo, ap, np)
      .then((res) => {
        if (res.error) {
          this.setContent('error', {content: res.errmsg})
        } else {
          this.setContent('search', {items: res.items})
        }
      })
  }

  search () {
    console.error('`search` must be overwritten with something useful')
  }

  // search for query without changing any other options
  kwsearch (query) {
    this.searchEd.setText(query)
    this._search(query)
  }

  showDocument (doc, items) {
    this.setContent('document', {content: doc, items: items})
  }

  setContent (mode, obj = {content: [], items: []}) {
    this.mode = mode
    this.content = obj.content
    this.items = obj.items
    etch.update(this)
  }

  toggleExported () {
    this.exportedOnly = !this.exportedOnly
    this.refs.toggleExported.element.classList.toggle("selected")
  }

  toggleAllLoaded () {
    this.allPackages = !this.allPackages
    this.refs.toggleLoaded.element.classList.toggle("selected")
  }

  toggleLocation () {
    this.namesOnly = !this.namesOnly
    this.refs.toggleLocation.element.classList.toggle("selected")
  }

  toggleOptions () {
    this.refs.headerOptions.classList.toggle('hidden')
    this.refs.options.element.classList.toggle("selected")
  }

  headerView () {
    return

        {toView(this.searchEd.element)}
        <Button alt='Search documentation' icon="search" onclick={() => this._search()}/>
        <Button alt='Show search options' ref="options" icon="three-bars" onclick={() => this.toggleOptions()}/>

        {toView(this.modEd.element)}

            <Button ref="toggleLocation" alt='Search in variable names only' onclick={() => this.toggleLocation()}>names</Button>
            <Button ref="toggleExported" alt='Search in exported variables only' onclick={() => this.toggleExported()}>exported</Button>
            <Button ref="toggleLoaded" alt='Search in loaded modules only' icon="foo selected" onclick={() => this.toggleAllLoaded()}>loaded</Button>

  }

  contentView () {
    let content
    switch (this.mode) {
      case 'loading':
        content =

        break
      case 'search':
        content =

          {this.items.map((item) => toView(new DocItem({item})))}

        break
      case 'document':
        content =

          {toView(this.content)}
          {this.items.map((item) => toView(new DocItem({item})))}

        break
      case 'error':
        content =
{toView(this.content)}

        break
      default:
        content =

    }
    return content
  }

  update () {}

  render () {
    return

      {this.headerView()}
      {this.contentView()}

  }

  getIconName () {
    return 'info'
  }

  deactivate () {
    this.subs.dispose()
    this.subs = null
  }
}

function icon (item) {
  switch (item.typ) {
    case "Function": return {item.name.startsWith("@") ? "m" : "λ"}
    case "Module": return
    case "DataType": return T
    case "Keyword": return k
    default: return c
  }
}

class DocItem extends Etch {
  render () {
    return

               {icon(this.props.item)}
               {this.props.item.name}
               <span
                 className={`exported icon icon-eye ${this.props.item.exported ? "is-exported" : ""}`}
                 title={this.props.item.exported ? "exported" : "not exported"}
               />
               {this.props.item.mod}

{toView(this.props.item.html)}

                this.expand()}>...

  }

  expand () {
    this.refs.itemBody.classList.toggle('collapsed')
  }
}

DocPane.registerView()
<commit_msg>Make macro type icon consistent with workspace/autocompletion<commit_after>'use babel'
/** @jsx etch.dom */

import etch from 'etch'

import { TextEditor, CompositeDisposable } from 'atom'
import PaneItem from '../util/pane-item'
import { toView, Toolbar, Button, Icon, makeicon, Etch } from '../util/etch'

export default class DocPane extends PaneItem {
  constructor () {
    super()

    this.setTitle('Documentation')
    this.content = []
    this.items = []
    this.mode = 'empty'
    this.exportedOnly = false
    this.allPackages = false
    this.namesOnly = false
    this.searchEd = new TextEditor({mini: true, placeholderText: "Search Documentation"})
    this.modEd = new TextEditor({mini: true, placeholderText: "in all modules"})

    this.subs = new CompositeDisposable()
    this.subs.add(atom.commands.add('.docpane .header .editor', {
      'docpane:search': () => this._search()
    }))

    etch.initialize(this)
    this.element.setAttribute('tabindex', -1)
  }

  open(opts) {
    return super.open(opts).then(docPane => {
      docPane.searchEd.getElement().focus()
    })
  }

  _search (query = this.searchEd.getText(), mod = this.modEd.getText(),
           eo = this.exportedOnly, ap = this.allPackages, np = this.namesOnly) {
    this.setContent('loading')
    this.search(query, mod || "Main", eo, ap, np)
      .then((res) => {
        if (res.error) {
          this.setContent('error', {content: res.errmsg})
        } else {
          this.setContent('search', {items: res.items})
        }
      })
  }

  search () {
    console.error('`search` must be overwritten with something useful')
  }

  // search for query without changing any other options
  kwsearch (query) {
    this.searchEd.setText(query)
    this._search(query)
  }

  showDocument (doc, items) {
    this.setContent('document', {content: doc, items: items})
  }

  setContent (mode, obj = {content: [], items: []}) {
    this.mode = mode
    this.content = obj.content
    this.items = obj.items
    etch.update(this)
  }

  toggleExported () {
    this.exportedOnly = !this.exportedOnly
    this.refs.toggleExported.element.classList.toggle("selected")
  }

  toggleAllLoaded () {
    this.allPackages = !this.allPackages
    this.refs.toggleLoaded.element.classList.toggle("selected")
  }

  toggleLocation () {
    this.namesOnly = !this.namesOnly
    this.refs.toggleLocation.element.classList.toggle("selected")
  }

  toggleOptions () {
    this.refs.headerOptions.classList.toggle('hidden')
    this.refs.options.element.classList.toggle("selected")
  }

  headerView () {
    return

        {toView(this.searchEd.element)}
        <Button alt='Search documentation' icon="search" onclick={() => this._search()}/>
        <Button alt='Show search options' ref="options" icon="three-bars" onclick={() => this.toggleOptions()}/>

        {toView(this.modEd.element)}

            <Button ref="toggleLocation" alt='Search in variable names only' onclick={() => this.toggleLocation()}>names</Button>
            <Button ref="toggleExported" alt='Search in exported variables only' onclick={() => this.toggleExported()}>exported</Button>
            <Button ref="toggleLoaded" alt='Search in loaded modules only' icon="foo selected" onclick={() => this.toggleAllLoaded()}>loaded</Button>

  }

  contentView () {
    let content
    switch (this.mode) {
      case 'loading':
        content =

        break
      case 'search':
        content =

          {this.items.map((item) => toView(new DocItem({item})))}

        break
      case 'document':
        content =

          {toView(this.content)}
          {this.items.map((item) => toView(new DocItem({item})))}

        break
      case 'error':
        content =
{toView(this.content)}

        break
      default:
        content =

    }
    return content
  }

  update () {}

  render () {
    return

      {this.headerView()}
      {this.contentView()}

  }

  getIconName () {
    return 'info'
  }

  deactivate () {
    this.subs.dispose()
    this.subs = null
  }
}

function icon (item) {
  switch (item.typ) {
    case "Function": return {item.name.startsWith("@") ? "@" : "λ"}
    case "Module": return
    case "DataType": return T
    case "Keyword": return k
    default: return c
  }
}

class DocItem extends Etch {
  render () {
    return

               {icon(this.props.item)}
               {this.props.item.name}
               <span
                 className={`exported icon icon-eye ${this.props.item.exported ? "is-exported" : ""}`}
                 title={this.props.item.exported ? "exported" : "not exported"}
               />
               {this.props.item.mod}

{toView(this.props.item.html)}

                this.expand()}>...

  }

  expand () {
    this.refs.itemBody.classList.toggle('collapsed')
  }
}

DocPane.registerView()
<|endoftext|>


<commit_before>var internals = {};

internals.mod = internals.mod || {};
internals.mod.log = require('../log');
internals.mod.type = require('../data_type');
internals.mod.Class = require('../class');
var Shadow = require('./shadow');
var log = internals.mod.log;
var tunnel = require('tunnel-ssh'),
    Promise = require('bluebird'),
    SeederInterface = require('../interface/seederInterface.js');

var ShadowProto = {

  createTable: function() { return Promise.resolve(); },
  addForeignKey: function() { return Promise.resolve(); },
  createCollection: function() { return Promise.resolve(); }
};

exports.connect = function (config, intern, callback) {
  var driver, req;

  var mod = internals.mod;
  internals = intern;
  internals.mod = mod;
  internals.interfaces = {

    SeederInterface: SeederInterface
  };

  if ( !config.user && config.username )
    config.user = config.username;

  if (config.driver === undefined) {
    throw new Error(
      'config must include a driver key specifing which driver to use');
  }

  if (config.driver && typeof (config.driver) === 'object') {

    log.verbose('require:', config.driver.require);
    driver = require(config.driver.require);

  }
  else {
    try {

      req = 'db-migrate-' + config.driver;
      log.verbose('require:', req);

      try {

        driver = require(req);
      }
      catch (Exception) {

        driver = require('../../../' + req);
      }
    }
    catch (Exception) {

      //Fallback to internal drivers, while moving drivers to new repos
      req = './' + config.driver;
      log.verbose('require:', req);
      driver = require(req);
    }
  }

  log.verbose('connecting');

  var connect = function(config) {
    driver.connect(config, intern, function (err, db) {

      if (err) {

        callback(err);
        return;
      }
      log.verbose('connected');

      if (!global.immunity)
        db = Shadow.infect(db, internals, ShadowProto);

      callback(null, db);
    });
  };

  if (config.tunnel) {
    var tunnelConfig = JSON.parse(JSON.stringify(config.tunnel));
    tunnelConfig.dstHost = config.host;
    tunnelConfig.dstPort = config.port;

    if (tunnelConfig.privateKeyPath) {
      tunnelConfig.privateKey = require('fs').readFileSync(tunnelConfig.privateKeyPath);
    }

    // Reassign the db host/port to point to our local ssh tunnel
    config.host = '127.0.0.1';
    config.port = tunnelConfig.localPort;

    tunnel(tunnelConfig, function (err) {

      if (err) {
        callback(err);
        return;
      }
      log.verbose('SSH tunnel connected on port ', tunnelConfig.localPort);

      connect(config);
    });
  }
  else {
    connect(config);
  }
};<commit_msg>add migrator interface to internals<commit_after>var internals = {};

internals.mod = internals.mod || {};
internals.mod.log = require('../log');
internals.mod.type = require('../data_type');
internals.mod.Class = require('../class');
var Shadow = require('./shadow');
var log = internals.mod.log;
var tunnel = require('tunnel-ssh'),
    Promise = require('bluebird'),
    SeederInterface = require('../interface/seederInterface.js'),
    MigratorInterface = require('../interface/migratorInterface.js');

var ShadowProto = {

  createTable: function() { return Promise.resolve(); },
  addForeignKey: function() { return Promise.resolve(); },
  createCollection: function() { return Promise.resolve(); }
};

exports.connect = function (config, intern, callback) {
  var driver, req;

  var mod = internals.mod;
  internals = intern;
  internals.mod = mod;
  internals.interfaces = {

    SeederInterface: SeederInterface,
    MigratorInterface: MigratorInterface
  };

  if ( !config.user && config.username )
    config.user = config.username;

  if (config.driver === undefined) {
    throw new Error(
      'config must include a driver key specifing which driver to use');
  }

  if (config.driver && typeof (config.driver) === 'object') {

    log.verbose('require:', config.driver.require);
    driver = require(config.driver.require);

  }
  else {
    try {

      req = 'db-migrate-' + config.driver;
      log.verbose('require:', req);

      try {

        driver = require(req);
      }
      catch (Exception) {

        driver = require('../../../' + req);
      }
    }
    catch (Exception) {

      //Fallback to internal drivers, while moving drivers to new repos
      req = './' + config.driver;
      log.verbose('require:', req);
      driver = require(req);
    }
  }

  log.verbose('connecting');

  var connect = function(config) {
    driver.connect(config, intern, function (err, db) {

      if (err) {

        callback(err);
        return;
      }
      log.verbose('connected');

      if (!global.immunity)
        db = Shadow.infect(db, internals, ShadowProto);

      callback(null, db);
    });
  };

  if (config.tunnel) {
    var tunnelConfig = JSON.parse(JSON.stringify(config.tunnel));
    tunnelConfig.dstHost = config.host;
    tunnelConfig.dstPort = config.port;

    if (tunnelConfig.privateKeyPath) {
      tunnelConfig.privateKey = require('fs').readFileSync(tunnelConfig.privateKeyPath);
    }

    // Reassign the db host/port to point to our local ssh tunnel
    config.host = '127.0.0.1';
    config.port = tunnelConfig.localPort;

    tunnel(tunnelConfig, function (err) {

      if (err) {
        callback(err);
        return;
      }
      log.verbose('SSH tunnel connected on port ', tunnelConfig.localPort);

      connect(config);
    });
  }
  else {
    connect(config);
  }
};
<|endoftext|>


<commit_before>'use strict';

const path = require('path');
const blueprintHelpers = require('ember-cli-blueprint-test-helpers/helpers');
let setupTestHooks = blueprintHelpers.setupTestHooks;
let emberNew = blueprintHelpers.emberNew;
let emberGenerate = blueprintHelpers.emberGenerate;
let modifyPackages = blueprintHelpers.modifyPackages;

const chai = require('ember-cli-blueprint-test-helpers/chai');
let expect = chai.expect;
let file = chai.file;

describe('Acceptance: ember generate and destroy server', function() {
  setupTestHooks(this, {
    cliPath: path.resolve(`${__dirname}/../../..`),
  });

  it('server', function() {
    let args = ['server'];

    return emberNew()
      .then(() => emberGenerate(args))
      .then(() => {
        expect(file('server/index.js')).to.contain('module.exports = function(app) {');
        expect(file('server/.jshintrc')).to.not.exist;

        // TODO: assert that `morgan` and `glob` dependencies were installed
      });
  });

  it('server with ember-cli-jshint', function() {
    let args = ['server'];

    return emberNew()
      .then(() => modifyPackages([{ name: 'ember-cli-jshint', dev: true }]))
      .then(() => emberGenerate(args))
      .then(() => {
        expect(file('server/.jshintrc')).to.exist;
      });
  });
});
<commit_msg>Modernizes unit/blueprint/server-test.js (#8583)<commit_after>'use strict';

const path = require('path');
const blueprintHelpers = require('ember-cli-blueprint-test-helpers/helpers');
let setupTestHooks = blueprintHelpers.setupTestHooks;
let emberNew = blueprintHelpers.emberNew;
let emberGenerate = blueprintHelpers.emberGenerate;
let modifyPackages = blueprintHelpers.modifyPackages;

const chai = require('ember-cli-blueprint-test-helpers/chai');
let expect = chai.expect;
let file = chai.file;

describe('Acceptance: ember generate and destroy server', function() {
  setupTestHooks(this, {
    cliPath: path.resolve(`${__dirname}/../../..`),
  });

  it('server', async function() {
    let args = ['server'];

    await emberNew();
    await emberGenerate(args);
    expect(file('server/index.js')).to.contain('module.exports = function(app) {');
    expect(file('server/.jshintrc')).to.not.exist;
    // TODO: assert that `morgan` and `glob` dependencies were installed
  });

  it('server with ember-cli-jshint', async function() {
    let args = ['server'];

    await emberNew();
    await modifyPackages([{ name: 'ember-cli-jshint', dev: true }]);
    await emberGenerate(args);
    expect(file('server/.jshintrc')).to.exist;
  });
});
<|endoftext|>


<commit_before>function selectElementsStartingWithA(n) {
  var array = [];
  for (var i = 0; i < n.length; i++) {
    var a = n[i].split('');
    if (a[0] == 'a') {
      array.push(n[i]);
    }
  }
  return array;
}

function selectElementsStartingWithAVowel(vowel) {
  array = [];
  volArr = ['a', 'e', 'i', 'o', 'u']

  for (var i = 0; i < vowel.length; i++) {
    var a = vowel[i].split('');
    for (var j = 0; j < volArr.length; j++) {
      if (a[0] === volArr[j]) {
        array.push(vowel[i]);
      }
    }
  }
  return array;
}

function removeNullsFromArray(array) {
  for (var i = 0; i < array.length; i++) {
    if (array[i] === null) array.splice(i, 2);
  }
  return array;
}

function removeNilsAndFalseFromAnArray(array) {
  for (var i = 0; i < array.length; i++) {
    if (array[i] == null || array[i] == false) array.splice(i, 3);
  }
  return array;
}

function reverseElementsInArray(array) {
  var arr = []
  for (var i = 0; i < array.length; i++) {
    var a = array[i].split("").reverse().join("");
    arr.push(a);
  }
  return arr;
}

function allElementsExceptFirstThree(array) {
  return array.splice(-4);
}

function addElementsToBeginningOfArray(array) {
  array.unshift(1);
  return array
}

function sortWordsByLastLetter() {
  // code here
}

function getFirstHalfOfString() {
  // code here
}

function makeNumberNegative(a) {
  return Math.abs(a);
}

function separateNumbersIntoEvenAndOdd(array) {
  var evens = []
  var odds = []
  for (var i = 0; i < array.length; i++) {
    if ((array[i] % 2) === 1) {
        odds.push(array[i]);
      } else {
        evens.push(array[i]);
      }
    }
    return ([evens, odds]);
  }

  function countNumberOfPalindromes() {
    // code here
  }

  function shortestWordInArray() {
    // code here
  }

  function longestWordInArray() {
    // code here
  }

  function totalOfNumbers(arr) {
    var i = arr.length;
    var sum = 0;
    while (--i) sum += arr[i];
    return arr;
  }

  function doubleArray() {
    // code here
  }

  function getElementsUntilGreaterThanFive() {
    // code here
  }

  function getAllLetters() {
    // code here
  }

  function removeCapitaLetters() {
    // code here
  }

  function roundUp(number) {
    return Math.round(number);
  }

  function roundDown() {
    // code here
  }

  function formatDateNicely() {
    // code here
  }

  function getDomainName() {
    // code here
  }

  function titleizeString() {
    // code here
  }

  function getSquareRoot() {
    // code here
  }
<commit_msg>sortWordsByLastLetter<commit_after>function selectElementsStartingWithA(n) {
  var array = [];
  for (var i = 0; i < n.length; i++) {
    var a = n[i].split('');
    if (a[0] == 'a') {
      array.push(n[i]);
    }
  }
  return array;
}

function selectElementsStartingWithAVowel(vowel) {
  array = [];
  volArr = ['a', 'e', 'i', 'o', 'u']

  for (var i = 0; i < vowel.length; i++) {
    var a = vowel[i].split('');
    for (var j = 0; j < volArr.length; j++) {
      if (a[0] === volArr[j]) {
        array.push(vowel[i]);
      }
    }
  }
  return array;
}

function removeNullsFromArray(array) {
  for (var i = 0; i < array.length; i++) {
    if (array[i] === null) array.splice(i, 2);
  }
  return array;
}

function removeNilsAndFalseFromAnArray(array) {
  for (var i = 0; i < array.length; i++) {
    if (array[i] == null || array[i] == false) array.splice(i, 3);
  }
  return array;
}

function reverseElementsInArray(array) {
  var arr = []
  for (var i = 0; i < array.length; i++) {
    var a = array[i].split("").reverse().join("");
    arr.push(a);
  }
  return arr;
}

function allElementsExceptFirstThree(array) {
  return array.splice(-4);
}

function addElementsToBeginningOfArray(array) {
  array.unshift(1);
  return array
}

function sortWordsByLastLetter(array) {
  var arr = [];
  var arrTwo = [];

  for (var i = 0; i < array.length; i++) {
    var a = array[i].split("").reverse().join("");
    arr.push(a);
    arr.sort();
  }

  for (var j = 0; j < arr.length; j++) {
    var b = arr[j].split("").reverse().join("");
    arrTwo.push(b);
  }
  return arrTwo;
}

function getFirstHalfOfString(string) {

}

function makeNumberNegative(a) {
  return Math.abs(a);
}

function separateNumbersIntoEvenAndOdd(array) {

}

function countNumberOfPalindromes(array) {

}

function shortestWordInArray() {
  // code here
}

function longestWordInArray() {
  // code here
}

function totalOfNumbers(arr) {
  var i = arr.length;
  var sum = 0;
  while (--i) sum += arr[i];
  return arr;
}

function doubleArray() {
  // code here
}

function getElementsUntilGreaterThanFive() {
  // code here
}

function getAllLetters() {
  // code here
}

function removeCapitaLetters() {
  // code here
}

function roundUp(number) {

}

function roundDown(number) {

}

function formatDateNicely() {
  // code here
}

function getDomainName() {
  // code here
}

function titleizeString() {
  // code here
}

function getSquareRoot(number) {

}
<|endoftext|>


<commit_before>// Prepare http request for server chain
// - fetch POST data
// - unwrap payload (extract CSRF, method, params)

'use strict';

var qs = require('qs');
var _  = require('lodash');

var MAX_POST_DATA = 10 * 1000 * 1024; // Max post data in bytes

module.exports = function (N) {

  var logger = N.logger.getLogger('rpc');

  function log(env) {
    var err = env.err
      , req = env.origin.req
      , message = ''
      , level;

    if (N.io.APP_ERROR <= env.status) {
      message = err.stack || err.message || JSON.stringify(err);
      level   = 'fatal';
    } else if (N.io.BAD_REQUEST <= env.status && N.io.APP_ERROR > env.status) {
      level = 'error';
    } else {
      level = 'info';
    }

    logger[level]('%s - %s() - "%s" - %s',
                  req.connection.remoteAddress,
                  req.method,
                  req.headers['user-agent'],
                  message);
  }

  N.wire.before('responder:rpc', function rpc_prepare(env, callback) {
    var req = env.origin.req
      , data = '';

    env.log_request = log;

    //
    // invalid request
    //

    if ('POST' !== req.method) {
      env.err = N.io.BAD_REQUEST;
      callback();
      return;
    }

    //
    // Set encoding, to glue data chunks as strings.
    // In other case you need to work with buffer, to avoid
    // breaking unicode characters.
    //
    // We don't expect rpc to work with big uploads, so, strings are enougth
    //

    req.setEncoding('utf8');

    //
    // start harvesting POST data
    //

    req.on('data', function (chunk) {
      if (MAX_POST_DATA < Buffer.byteLength(data += chunk)) {
        // max allowed post data reached, drop request.
        req.removeAllListeners('data');
        req.removeAllListeners('end');

        env.err = { code: N.io.BAD_REQUEST, message: 'Too big post data' };

        // Force destroy incoming connection
        req.connection.destroy();

        callback();
      }
    });

    //
    // when done (on success) process POST data and handle request
    //

    req.on('end', function () {
      var payload = _.defaults(qs.parse(data), req.query)
        , params  = payload.params || {};

      env.params = params;

      // save CSRF token if it was sent
      req.csrf = payload.csrf;

      // invalid payload
      if (!payload.version || !payload.method) {
        env.err = N.io.BAD_REQUEST;
        callback();
        return;
      }

      env.method = payload.method;

      // invalid client version.
      // client will check server version by it's own,
      // so in fact this error is not used by client
      if (payload.version !== N.runtime.version) {
        env.err = N.io.BAD_REQUEST;
        callback();
        return;
      }

      callback();
    });
  });
};
<commit_msg>Fix/improve RPC logger.<commit_after>// Prepare http request for server chain
// - fetch POST data
// - unwrap payload (extract CSRF, method, params)

'use strict';

var _ = require('lodash');
var qs = require('qs');
var http = require('http');

var MAX_POST_DATA = 10 * 1000 * 1024; // Max post data in bytes

module.exports = function (N) {

  var logger = N.logger.getLogger('rpc');

  function formatParams(params, max) {
    var length = 0
      , result = [];

    function makePair(value, key) {
      return key + '=' + JSON.stringify(value);
    }

    _(params || {}).map(makePair).sortBy('length').forEach(function (pair) {
      if (!max || max > length + pair.length) {
        length += pair.length;
        result.push(pair);
      } else {
        result.push('...');
        return false;
      }
    });

    if (0 !== result.length) {
      return '?' + result.join('&');
    } else {
      return '';
    }
  }

  function log(env) {
    var err = env.err
      , req = env.origin.req
      , message = http.STATUS_CODES[env.status]
      , level = 'info';

    if (err) {
      if (N.io.APP_ERROR <= err.code) {
        message = err.stack || err.message || JSON.stringify(err);
        level = 'fatal';
      } else if (N.io.BAD_REQUEST <= err.code && N.io.APP_ERROR > err.code) {
        message = http.STATUS_CODES[err.code];
        level = 'error';
      }
    }

    logger[level]('%s - %s%s - "%s" - %s',
                  req.connection.remoteAddress,
                  env.method,
                  formatParams(env.params, 60),
                  req.headers['user-agent'],
                  message);
  }

  N.wire.before('responder:rpc', function rpc_prepare(env, callback) {
    var req = env.origin.req
      , data = '';

    env.log_request = log;

    //
    // invalid request
    //

    if ('POST' !== req.method) {
      env.err = N.io.BAD_REQUEST;
      callback();
      return;
    }

    //
    // Set encoding, to glue data chunks as strings.
    // In other case you need to work with buffer, to avoid
    // breaking unicode characters.
    //
    // We don't expect rpc to work with big uploads, so, strings are enougth
    //

    req.setEncoding('utf8');

    //
    // start harvesting POST data
    //

    req.on('data', function (chunk) {
      if (MAX_POST_DATA < Buffer.byteLength(data += chunk)) {
        // max allowed post data reached, drop request.
        req.removeAllListeners('data');
        req.removeAllListeners('end');

        env.err = { code: N.io.BAD_REQUEST, message: 'Too big post data' };

        // Force destroy incoming connection
        req.connection.destroy();

        callback();
      }
    });

    //
    // when done (on success) process POST data and handle request
    //

    req.on('end', function () {
      var payload = _.defaults(qs.parse(data), req.query)
        , params  = payload.params || {};

      env.params = params;

      // save CSRF token if it was sent
      req.csrf = payload.csrf;

      // invalid payload
      if (!payload.version || !payload.method) {
        env.err = N.io.BAD_REQUEST;
        callback();
        return;
      }

      env.method = payload.method;

      // invalid client version.
      // client will check server version by it's own,
      // so in fact this error is not used by client
      if (payload.version !== N.runtime.version) {
        env.err = N.io.BAD_REQUEST;
        callback();
        return;
      }

      callback();
    });
  });
};
<|endoftext|>


<commit_before>
const CACHE_NAME = 'oec-review-site';
const urlsToCache = [
  '/',
  '/styles/style.css',
];

self.addEventListener('install', event => {
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(cache => {
        console.log('opened cache');
        return cache.addAll(urlsToCache);
      })
  );
});

self.addEventListener('fetch', event => {
  event.respondWith(
    caches.match(event.request)
      .then(response => {
        // Cache hit - return response
        if (response) {
          return response;
        }

        const fetchRequest = event.request.clone();

        return fetch(fetchRequest).then(
          function (response) {
            // Check if we received a valid response
            if (!response || response.status !== 200 || response.type !== 'basic') {
              return response;
            }

            // IMPORTANT: Clone the response. A response is a stream
            // and because we want the browser to consume the response
            // as well as the cache consuming the response, we need
            // to clone it so we have two streams.
            var responseToCache = response.clone();

            caches.open(CACHE_NAME)
              .then(function (cache) {
                cache.put(event.request, responseToCache);
              });

            return response;
          }
        );
      })
  );
});<commit_msg>filepath in dist<commit_after>
const CACHE_NAME = 'oec-review-site';
const urlsToCache = [
  '/',
  '/static/styles/style.css',
];

self.addEventListener('install', event => {
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(cache => {
        console.log('opened cache');
        return cache.addAll(urlsToCache);
      })
  );
});

self.addEventListener('fetch', event => {
  event.respondWith(
    caches.match(event.request)
      .then(response => {
        // Cache hit - return response
        if (response) {
          return response;
        }

        const fetchRequest = event.request.clone();

        return fetch(fetchRequest).then(
          function (response) {
            // Check if we received a valid response
            if (!response || response.status !== 200 || response.type !== 'basic') {
              return response;
            }

            // IMPORTANT: Clone the response. A response is a stream
            // and because we want the browser to consume the response
            // as well as the cache consuming the response, we need
            // to clone it so we have two streams.
            var responseToCache = response.clone();

            caches.open(CACHE_NAME)
              .then(function (cache) {
                cache.put(event.request, responseToCache);
              });

            return response;
          }
        );
      })
  );
});<|endoftext|>


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

/**
 * This module contains the handlers for native platform events.
 * From here, the dispatcher is called to create unified pointer events.
 * Included are touch events (v1), mouse events, and MSPointerEvents.
 */
(function(scope) {
  var dispatcher = scope.dispatcher;
  var installer = scope.installer;

  // only activate if this platform does not have pointer events
  if (window.navigator.pointerEnabled === undefined) {
    Object.defineProperty(window.navigator, 'pointerEnabled', {value: true, enumerable: true});

    if (window.navigator.msPointerEnabled) {
      var tp = window.navigator.msMaxTouchPoints;
      Object.defineProperty(window.navigator, 'maxTouchPoints', {
        value: tp,
        enumerable: true
      });
      dispatcher.registerSource('ms', scope.msEvents);
    } else {
      dispatcher.registerSource('mouse', scope.mouseEvents);
      if (window.ontouchstart !== undefined) {
        // dispatcher.registerSource('touch', scope.touchEvents);
      }
    }

    dispatcher.register(document);
  }
})(window.PointerEventsPolyfill);
<commit_msg>turn on new touch system<commit_after>/*
 * Copyright 2013 The Polymer Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style
 * license that can be found in the LICENSE file.
 */

/**
 * This module contains the handlers for native platform events.
 * From here, the dispatcher is called to create unified pointer events.
 * Included are touch events (v1), mouse events, and MSPointerEvents.
 */
(function(scope) {
  var dispatcher = scope.dispatcher;
  var installer = scope.installer;

  // only activate if this platform does not have pointer events
  if (window.navigator.pointerEnabled === undefined) {
    Object.defineProperty(window.navigator, 'pointerEnabled', {value: true, enumerable: true});

    if (window.navigator.msPointerEnabled) {
      var tp = window.navigator.msMaxTouchPoints;
      Object.defineProperty(window.navigator, 'maxTouchPoints', {
        value: tp,
        enumerable: true
      });
      dispatcher.registerSource('ms', scope.msEvents);
    } else {
      dispatcher.registerSource('mouse', scope.mouseEvents);
      if (window.ontouchstart !== undefined) {
        dispatcher.registerSource('touch', scope.touchEvents);
      }
    }

    dispatcher.register(document);
  }
})(window.PointerEventsPolyfill);
<|endoftext|>


<commit_before>'use strict';

// MODULES //

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

// STDMATH //

var stdmath = {};
setReadOnly( stdmath, 'base', {} );

// Constants:
setReadOnly( stdmath, 'FLOAT64_PI', require( '@stdlib/math/constants/float64-pi' ) );
setReadOnly( stdmath, 'FLOAT64_TWO_PI', require( '@stdlib/math/constants/float64-two-pi' ) );
setReadOnly( stdmath, 'FLOAT64_PI_SQUARED', require( '@stdlib/math/constants/float64-pi-squared' ) );
setReadOnly( stdmath, 'FLOAT64_E', require( '@stdlib/math/constants/float64-e' ) );
setReadOnly( stdmath, 'FLOAT64_PHI', require( '@stdlib/math/constants/float64-phi' ) );
setReadOnly( stdmath, 'FLOAT64_SQRT_PHI', require( '@stdlib/math/constants/float64-sqrt-phi' ) );
setReadOnly( stdmath, 'FLOAT64_EULERGAMMA', require( '@stdlib/math/constants/float64-eulergamma' ) );
setReadOnly( stdmath, 'FLOAT64_GLAISHER', require( '@stdlib/math/constants/float64-glaisher-kinkelin' ) );
setReadOnly( stdmath, 'FLOAT64_CATALAN', require( '@stdlib/math/constants/float64-catalan' ) );
setReadOnly( stdmath, 'FLOAT64_LN2', require( '@stdlib/math/constants/float64-ln2' ) );
setReadOnly( stdmath, 'FLOAT64_LN_SQRT_TWO_PI', require( '@stdlib/math/constants/float64-ln-sqrt-two-pi' ) );

setReadOnly( stdmath, 'FLOAT32_PINF', require( '@stdlib/math/constants/float32-pinf' ) );
setReadOnly( stdmath, 'FLOAT32_NINF', require( '@stdlib/math/constants/float32-ninf' ) );
setReadOnly( stdmath, 'FLOAT64_PINF', require( '@stdlib/math/constants/float64-pinf' ) );
setReadOnly( stdmath, 'FLOAT64_NINF', require( '@stdlib/math/constants/float64-ninf' ) );

setReadOnly( stdmath, 'INT8_MAX', require( '@stdlib/math/constants/int8-max' ) );
setReadOnly( stdmath, 'INT8_MIN', require( '@stdlib/math/constants/int8-min' ) );
setReadOnly( stdmath, 'INT16_MAX', require( '@stdlib/math/constants/int16-max' ) );
setReadOnly( stdmath, 'INT16_MIN', require( '@stdlib/math/constants/int16-min' ) );
setReadOnly( stdmath, 'INT32_MAX', require( '@stdlib/math/constants/int32-max' ) );
setReadOnly( stdmath, 'INT32_MIN', require( '@stdlib/math/constants/int32-min' ) );
setReadOnly( stdmath, 'UINT32_MAX', require( '@stdlib/math/constants/uint32-max' ) );
setReadOnly( stdmath, 'FLOAT64_MAX', require( '@stdlib/math/constants/float64-max' ) );
setReadOnly( stdmath, 'FLOAT64_MAX_SAFE_INTEGER', require( '@stdlib/math/constants/float64-max-safe-integer' ) );
setReadOnly( stdmath, 'FLOAT64_MIN_SAFE_INTEGER', require( '@stdlib/math/constants/float64-min-safe-integer' ) );

setReadOnly( stdmath, 'FLOAT64_EPSILON', require( '@stdlib/math/constants/float64-eps' ) );
setReadOnly( stdmath, 'FLOAT64_SQRT_EPSILON', require( '@stdlib/math/constants/float64-sqrt-eps' ) );

setReadOnly( stdmath, 'FLOAT16_PRECISION', require( '@stdlib/math/constants/float16-precision' ) );
setReadOnly( stdmath, 'FLOAT32_PRECISION', require( '@stdlib/math/constants/float32-precision' ) );
setReadOnly( stdmath, 'FLOAT64_PRECISION', require( '@stdlib/math/constants/float64-precision' ) );

// Special functions (base):
setReadOnly( stdmath.base, 'round', require( '@stdlib/math/base/special/round' ) );
setReadOnly( stdmath.base, 'roundn', require( '@stdlib/math/base/special/roundn' ) );
setReadOnly( stdmath.base, 'floor', require( '@stdlib/math/base/special/floor' ) );
setReadOnly( stdmath.base, 'ceil', require( '@stdlib/math/base/special/ceil' ) );
setReadOnly( stdmath.base, 'abs', require( '@stdlib/math/base/special/abs' ) );
setReadOnly( stdmath.base, 'pow', require( '@stdlib/math/base/special/pow' ) );
setReadOnly( stdmath.base, 'sqrt', require( '@stdlib/math/base/special/sqrt' ) );
setReadOnly( stdmath.base, 'ln', require( '@stdlib/math/base/special/ln' ) );
setReadOnly( stdmath.base, 'signum', require( '@stdlib/math/base/special/signum' ) );
setReadOnly( stdmath.base, 'truncate', require( '@stdlib/math/base/special/truncate' ) );

// Utilities (base):
setReadOnly( stdmath.base, 'isNaN', require( '@stdlib/math/base/utils/is-nan' ) );
setReadOnly( stdmath.base, 'isFinite', require( '@stdlib/math/base/utils/is-finite' ) );
setReadOnly( stdmath.base, 'isInfinite', require( '@stdlib/math/base/utils/is-infinite' ) );
setReadOnly( stdmath.base, 'isNegativeZero', require( '@stdlib/math/base/utils/is-negative-zero' ) );
setReadOnly( stdmath.base, 'isPositiveZero', require( '@stdlib/math/base/utils/is-positive-zero' ) );
setReadOnly( stdmath.base, 'isInteger', require( '@stdlib/math/base/utils/is-integer' ) );
setReadOnly( stdmath.base, 'absoluteDifference', require( '@stdlib/math/base/utils/absolute-difference' ) );

// Tools (base):
setReadOnly( stdmath.base, 'evalpoly', require( '@stdlib/math/base/tools/evalpoly' ) );
setReadOnly( stdmath.base, 'evalrational', require( '@stdlib/math/base/tools/evalrational' ) );

// Utilities (generics):
setReadOnly( stdmath, 'linspace', require( '@stdlib/math/generics/utils/linspace' ) );
setReadOnly( stdmath, 'logspace', require( '@stdlib/math/generics/utils/logspace' ) );
setReadOnly( stdmath, 'incrspace', require( '@stdlib/math/generics/utils/incrspace' ) );

// EXPORTS //

module.exports = stdmath;
<commit_msg>Export relative difference util<commit_after>'use strict';

// MODULES //

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

// STDMATH //

var stdmath = {};
setReadOnly( stdmath, 'base', {} );

// Constants:
setReadOnly( stdmath, 'FLOAT64_PI', require( '@stdlib/math/constants/float64-pi' ) );
setReadOnly( stdmath, 'FLOAT64_TWO_PI', require( '@stdlib/math/constants/float64-two-pi' ) );
setReadOnly( stdmath, 'FLOAT64_PI_SQUARED', require( '@stdlib/math/constants/float64-pi-squared' ) );
setReadOnly( stdmath, 'FLOAT64_E', require( '@stdlib/math/constants/float64-e' ) );
setReadOnly( stdmath, 'FLOAT64_PHI', require( '@stdlib/math/constants/float64-phi' ) );
setReadOnly( stdmath, 'FLOAT64_SQRT_PHI', require( '@stdlib/math/constants/float64-sqrt-phi' ) );
setReadOnly( stdmath, 'FLOAT64_EULERGAMMA', require( '@stdlib/math/constants/float64-eulergamma' ) );
setReadOnly( stdmath, 'FLOAT64_GLAISHER', require( '@stdlib/math/constants/float64-glaisher-kinkelin' ) );
setReadOnly( stdmath, 'FLOAT64_CATALAN', require( '@stdlib/math/constants/float64-catalan' ) );
setReadOnly( stdmath, 'FLOAT64_LN2', require( '@stdlib/math/constants/float64-ln2' ) );
setReadOnly( stdmath, 'FLOAT64_LN_SQRT_TWO_PI', require( '@stdlib/math/constants/float64-ln-sqrt-two-pi' ) );

setReadOnly( stdmath, 'FLOAT32_PINF', require( '@stdlib/math/constants/float32-pinf' ) );
setReadOnly( stdmath, 'FLOAT32_NINF', require( '@stdlib/math/constants/float32-ninf' ) );
setReadOnly( stdmath, 'FLOAT64_PINF', require( '@stdlib/math/constants/float64-pinf' ) );
setReadOnly( stdmath, 'FLOAT64_NINF', require( '@stdlib/math/constants/float64-ninf' ) );

setReadOnly( stdmath, 'INT8_MAX', require( '@stdlib/math/constants/int8-max' ) );
setReadOnly( stdmath, 'INT8_MIN', require( '@stdlib/math/constants/int8-min' ) );
setReadOnly( stdmath, 'INT16_MAX', require( '@stdlib/math/constants/int16-max' ) );
setReadOnly( stdmath, 'INT16_MIN', require( '@stdlib/math/constants/int16-min' ) );
setReadOnly( stdmath, 'INT32_MAX', require( '@stdlib/math/constants/int32-max' ) );
setReadOnly( stdmath, 'INT32_MIN', require( '@stdlib/math/constants/int32-min' ) );
setReadOnly( stdmath, 'UINT32_MAX', require( '@stdlib/math/constants/uint32-max' ) );
setReadOnly( stdmath, 'FLOAT64_MAX', require( '@stdlib/math/constants/float64-max' ) );
setReadOnly( stdmath, 'FLOAT64_MAX_SAFE_INTEGER', require( '@stdlib/math/constants/float64-max-safe-integer' ) );
setReadOnly( stdmath, 'FLOAT64_MIN_SAFE_INTEGER', require( '@stdlib/math/constants/float64-min-safe-integer' ) );

setReadOnly( stdmath, 'FLOAT64_EPSILON', require( '@stdlib/math/constants/float64-eps' ) );
setReadOnly( stdmath, 'FLOAT64_SQRT_EPSILON', require( '@stdlib/math/constants/float64-sqrt-eps' ) );

setReadOnly( stdmath, 'FLOAT16_PRECISION', require( '@stdlib/math/constants/float16-precision' ) );
setReadOnly( stdmath, 'FLOAT32_PRECISION', require( '@stdlib/math/constants/float32-precision' ) );
setReadOnly( stdmath, 'FLOAT64_PRECISION', require( '@stdlib/math/constants/float64-precision' ) );

// Special functions (base):
setReadOnly( stdmath.base, 'round', require( '@stdlib/math/base/special/round' ) );
setReadOnly( stdmath.base, 'roundn', require( '@stdlib/math/base/special/roundn' ) );
setReadOnly( stdmath.base, 'floor', require( '@stdlib/math/base/special/floor' ) );
setReadOnly( stdmath.base, 'ceil', require( '@stdlib/math/base/special/ceil' ) );
setReadOnly( stdmath.base, 'abs', require( '@stdlib/math/base/special/abs' ) );
setReadOnly( stdmath.base, 'pow', require( '@stdlib/math/base/special/pow' ) );
setReadOnly( stdmath.base, 'sqrt', require( '@stdlib/math/base/special/sqrt' ) );
setReadOnly( stdmath.base, 'ln', require( '@stdlib/math/base/special/ln' ) );
setReadOnly( stdmath.base, 'signum', require( '@stdlib/math/base/special/signum' ) );
setReadOnly( stdmath.base, 'truncate', require( '@stdlib/math/base/special/truncate' ) );

// Utilities (base):
setReadOnly( stdmath.base, 'isNaN', require( '@stdlib/math/base/utils/is-nan' ) );
setReadOnly( stdmath.base, 'isFinite', require( '@stdlib/math/base/utils/is-finite' ) );
setReadOnly( stdmath.base, 'isInfinite', require( '@stdlib/math/base/utils/is-infinite' ) );
setReadOnly( stdmath.base, 'isNegativeZero', require( '@stdlib/math/base/utils/is-negative-zero' ) );
setReadOnly( stdmath.base, 'isPositiveZero', require( '@stdlib/math/base/utils/is-positive-zero' ) );
setReadOnly( stdmath.base, 'isInteger', require( '@stdlib/math/base/utils/is-integer' ) );

setReadOnly( stdmath.base, 'absoluteDifference', require( '@stdlib/math/base/utils/absolute-difference' ) );
setReadOnly( stdmath.base, 'relativeDifference', require( '@stdlib/math/base/utils/relative-difference' ) );

// Tools (base):
setReadOnly( stdmath.base, 'evalpoly', require( '@stdlib/math/base/tools/evalpoly' ) );
setReadOnly( stdmath.base, 'evalrational', require( '@stdlib/math/base/tools/evalrational' ) );

// Utilities (generics):
setReadOnly( stdmath, 'linspace', require( '@stdlib/math/generics/utils/linspace' ) );
setReadOnly( stdmath, 'logspace', require( '@stdlib/math/generics/utils/logspace' ) );
setReadOnly( stdmath, 'incrspace', require( '@stdlib/math/generics/utils/incrspace' ) );

// EXPORTS //

module.exports = stdmath;
<|endoftext|>


<commit_before>// Given an integer, write a function to determine if it is a power of two.
<commit_msg>add solution<commit_after>// Given an integer, write a function to determine if it is a power of two.

var isPowerOfTwo = function(n) {
    if(n < 1){
        return false;
    }
        return (0 === ((n - 1) & n));
};
<|endoftext|>


<commit_before>var PythonShell = require('python-shell');
var Parser = require('../parse.js');
var pyshell = new PythonShell('./app/services/doc2vec/doc2vec.py',{ mode: 'json', pythonPath:'/usr/local/bin/python3'});
var fs = require('fs');
// sends a message to the Python script via stdin
var chunkSize = 10000;
var chunks = 24;
var c = 0;
var model_path = "";
var size = 239932;
var busy = false;
var firstTopN = true;
//pyshell.send({command:"build_vocab"})

// pyshell.on('message', function (message) {
//   command = mes      if(firstTopN){sage['command']
//   switch (command) {
//     case "build_vocab":
//       var posts = []
//       if(c < chunks){
//         //We simulate DB reading from chunk files
//         fs.readFile('posts/'+c+'.txt', 'utf8', function (err,data) {
//           if (err) {
//             return console.log(err)
//           }
//           console.log(c)
//           posts = JSON.parse(data)
//           c++
//           console.log("sending")
//           pyshell.send({command:"build_vocab",finished:false,posts:posts})
//         });
//       }
//       else {
//         pyshell.send({command:"build_vocab",finished:true,posts:[]})
//       }
//       break;
//
//     case "train":
//       var finished = message['finished']
//       if(!finished){
//         var posts = []
//         var chunk = message['chunk']
//         console.log(chunk)
//         fs.readFile('posts/'+chunk+'.txt', 'utf8', function (err,data) {
//           if (err) {
//             return console.log(err)
//           }
//           posts = JSON.parse(data)
//           c++
//           pyshell.send({command:"train",posts:posts})
//         });
//       }
//
//       break;
//
//     default:
//
//   }
//
// });
pyshell.on('error',function(err){console.log(err)})

module.exports = {
  train: function(givePathCallback){
    if(!busy){
      busy = true;
      pyshell.send({command:"build_vocab"});
      pyshell.on('message', function(message){
        if(message['command'] == 'train'){
            if(message['finished']){
            model_path = message['model_path'];
            givePathCallback(model_path);
            busy = false
            }
        }
      });
    }
  },
  load_model: function(path,okCallBack){
    if(!busy){
      busy = true;
      pyshell.send({command:"load_model",path:path});
      pyshell.on('message',function(message){
          if(message['command'] == 'load_model'){
              if(!message['ok']) console.log(message['err']);
              busy = false;
              console.log("model loaded");
              okCallBack()
            }
      });
    }
  },
  vectors: function(topn,fillVectorCallback){
    if(!busy){
      busy = true;
      pyshell.on('message',function(message){
        command = message['command'];
        if(command == "get_vectors"){
          fillVectorCallback({id:message['id'],vector:message['vector'],topn:message['topn']});
          if(message['finish']){
             busy = false;
             console.log("I finnished");
           }
        }
      });
      pyshell.send({command:"get_vectors",topn:topn});
    }
  },

  topn_similar: function(id,topn,fillIdCallback){
    if(!busy){
      busy = true
      var pyCallBack = function(message){
        command = message['command']
        if(command == "topn"){
          busy = false
          fillIdCallback(message['ids'])
          pyshell.removeListener('message',pyCallBack)
        }
      }

      pyshell.on('message',pyCallBack);
      pyshell.send({command:"topn",n:topn,id:id})

    }
  }

}

/*
Commands used:
  build_vocab: {command: "build_vocab", finished: TRUE/FALSE, posts:[]}
    python-shell: {dommand: "build_vocab", text:"next", finished:"True/False"}
  train: {command: "train", finished: TRUE/FALSE, posts:[]}
    python-shell: {dommand: "train", chunk:chunk_number, finished:"True/False", model_path:path}
  InferVectors: {command: "infer", finished: TRUE/FALSE}
    python-shell: {command: "infer",vectors:[]}
  load_model:{command: "load_model", path:path/to/model}
    python-shell: {command: "load_model", ok:True/False, err:"error msg"}

  finish: {command: "finish", p}
*/
<commit_msg>change py path<commit_after>var PythonShell = require('python-shell');
var Parser = require('../parse.js');
var pyshell = new PythonShell('./app/services/doc2vec/doc2vec.py',{ mode: 'json', pythonPath:'/usr/bin/python3.5'});
var fs = require('fs');
// sends a message to the Python script via stdin
var chunkSize = 10000;
var chunks = 24;
var c = 0;
var model_path = "";
var size = 239932;
var busy = false;
var firstTopN = true;
//pyshell.send({command:"build_vocab"})

// pyshell.on('message', function (message) {
//   command = mes      if(firstTopN){sage['command']
//   switch (command) {
//     case "build_vocab":
//       var posts = []
//       if(c < chunks){
//         //We simulate DB reading from chunk files
//         fs.readFile('posts/'+c+'.txt', 'utf8', function (err,data) {
//           if (err) {
//             return console.log(err)
//           }
//           console.log(c)
//           posts = JSON.parse(data)
//           c++
//           console.log("sending")
//           pyshell.send({command:"build_vocab",finished:false,posts:posts})
//         });
//       }
//       else {
//         pyshell.send({command:"build_vocab",finished:true,posts:[]})
//       }
//       break;
//
//     case "train":
//       var finished = message['finished']
//       if(!finished){
//         var posts = []
//         var chunk = message['chunk']
//         console.log(chunk)
//         fs.readFile('posts/'+chunk+'.txt', 'utf8', function (err,data) {
//           if (err) {
//             return console.log(err)
//           }
//           posts = JSON.parse(data)
//           c++
//           pyshell.send({command:"train",posts:posts})
//         });
//       }
//
//       break;
//
//     default:
//
//   }
//
// });
pyshell.on('error',function(err){console.log(err)})

module.exports = {
  train: function(givePathCallback){
    if(!busy){
      busy = true;
      pyshell.send({command:"build_vocab"});
      pyshell.on('message', function(message){
        if(message['command'] == 'train'){
            if(message['finished']){
            model_path = message['model_path'];
            givePathCallback(model_path);
            busy = false
            }
        }
      });
    }
  },
  load_model: function(path,okCallBack){
    if(!busy){
      busy = true;
      pyshell.send({command:"load_model",path:path});
      pyshell.on('message',function(message){
          if(message['command'] == 'load_model'){
              if(!message['ok']) console.log(message['err']);
              busy = false;
              console.log("model loaded");
              okCallBack()
            }
      });
    }
  },
  vectors: function(topn,fillVectorCallback){
    if(!busy){
      busy = true;
      pyshell.on('message',function(message){
        command = message['command'];
        if(command == "get_vectors"){
          fillVectorCallback({id:message['id'],vector:message['vector'],topn:message['topn']});
          if(message['finish']){
             busy = false;
             console.log("I finnished");
           }
        }
      });
      pyshell.send({command:"get_vectors",topn:topn});
    }
  },

  topn_similar: function(id,topn,fillIdCallback){
    if(!busy){
      busy = true
      var pyCallBack = function(message){
        command = message['command']
        if(command == "topn"){
          busy = false
          fillIdCallback(message['ids'])
          pyshell.removeListener('message',pyCallBack)
        }
      }

      pyshell.on('message',pyCallBack);
      pyshell.send({command:"topn",n:topn,id:id})

    }
  }

}

/*
Commands used:
  build_vocab: {command: "build_vocab", finished: TRUE/FALSE, posts:[]}
    python-shell: {dommand: "build_vocab", text:"next", finished:"True/False"}
  train: {command: "train", finished: TRUE/FALSE, posts:[]}
    python-shell: {dommand: "train", chunk:chunk_number, finished:"True/False", model_path:path}
  InferVectors: {command: "infer", finished: TRUE/FALSE}
    python-shell: {command: "infer",vectors:[]}
  load_model:{command: "load_model", path:path/to/model}
    python-shell: {command: "load_model", ok:True/False, err:"error msg"}

  finish: {command: "finish", p}
*/
<|endoftext|>


<commit_before>import alt from "alt-instance"
import WalletActions from "actions/WalletActions"
import WalletCreateActions from "actions/WalletCreateActions"
import BaseStore from "stores/BaseStore"
import iDB from "idb-instance"
import Immutable from "immutable"

class WalletStore extends BaseStore {

    constructor() {
        super()
        this.state = this._getInitialState()
        this.bindListeners({
            onRestore: WalletActions.restore,
            onDefaultWalletCreated: WalletCreateActions.defaultWalletCreated
        })
        super._export("init")
    }

    _getInitialState() {
        return {
            current_wallet: undefined,
            wallet_names: Immutable.Set()
        }
    }

    init() {
        return Promise.all([
            iDB.root.getProperty("current_wallet").then( current_wallet => {
                this.setState({ current_wallet })
            }),
            iDB.root.getProperty("wallet_names", []).then( wallet_names => {
                this.setState({
                    wallet_names: Immutable.Set(wallet_names)
                })
            })
        ])
    }

    onDefaultWalletCreated() {
        Promise.all([
            iDB.root.setProperty("current_wallet", "default"),
            iDB.root.setProperty("wallet_names", ["default"])
        ]).then(()=>{
            this.setState({
                current_wallet: "default",
                wallet_names: Immutable.Set(["default"])
            })
        })
    }

    onRestore({wallet_name, wallet_object}) {
        return iDB.restore(wallet_name, wallet_object).then( () => {
            var wallet_names = this.state.wallet_names.add(wallet_name)
            iDB.root.setProperty("wallet_names", wallet_names).then( ()=> {
                this.setState({wallet_names})
            })
        }).catch( event => {
            var error = event.target.error
            console.error("Error saving wallet to database",
                error.name, error.message, error)
            throw new Error("Error saving wallet to database")
        })
    }

}

export var WalletStoreWrapped = alt.createStore(WalletStore)
export default WalletStoreWrapped
<commit_msg>Adds getMyAuthorityForAccount<commit_after>import alt from "alt-instance"
import PrivateKeyStore from "stores/PrivateKeyStore"
import WalletActions from "actions/WalletActions"
import WalletCreateActions from "actions/WalletCreateActions"
import BaseStore from "stores/BaseStore"
import iDB from "idb-instance"
import Immutable from "immutable"

class WalletStore extends BaseStore {

    constructor() {
        super()
        this.state = this._getInitialState()
        this.bindListeners({
            onRestore: WalletActions.restore,
            onDefaultWalletCreated: WalletCreateActions.defaultWalletCreated
        })
        super._export("init","getMyAuthorityForAccount")
    }

    _getInitialState() {
        return {
            current_wallet: undefined,
            wallet_names: Immutable.Set()
        }
    }

    init() {
        return Promise.all([
            iDB.root.getProperty("current_wallet").then( current_wallet => {
                this.setState({ current_wallet })
            }),
            iDB.root.getProperty("wallet_names", []).then( wallet_names => {
                this.setState({
                    wallet_names: Immutable.Set(wallet_names)
                })
            })
        ])
    }

    /**
        @todo "partial"
        @return string "none", "full", "partial"
    */
    getMyAuthorityForAccount(account) {
        if(account === undefined) return undefined
        if( ! account) return null
        let my_authority = "none";
        if (account) {
            for (let k of account.owner.key_auths) {
                if (PrivateKeyStore.hasKey(k[0])) {
                    my_authority = "full";
                    break;
                }
            }
            for (let k of account.active.key_auths) {
                if (PrivateKeyStore.hasKey(k[0])) {
                    my_authority = "full";
                    break;
                }
            }
        }
        return my_authority;
    }

    onDefaultWalletCreated() {
        Promise.all([
            iDB.root.setProperty("current_wallet", "default"),
            iDB.root.setProperty("wallet_names", ["default"])
        ]).then(()=>{
            this.setState({
                current_wallet: "default",
                wallet_names: Immutable.Set(["default"])
            })
        })
    }

    onRestore({wallet_name, wallet_object}) {
        return iDB.restore(wallet_name, wallet_object).then( () => {
            var wallet_names = this.state.wallet_names.add(wallet_name)
            iDB.root.setProperty("wallet_names", wallet_names).then( ()=> {
                this.setState({wallet_names})
            })
        }).catch( event => {
            var error = event.target.error
            console.error("Error saving wallet to database",
                error.name, error.message, error)
            throw new Error("Error saving wallet to database")
        })
    }

}

export var WalletStoreWrapped = alt.createStore(WalletStore)
export default WalletStoreWrapped
<|endoftext|>


<commit_before>/* global define */

define([
  'underscore',
  'backbone',
  'buses/event-bus'
], function (_, Backbone, EventBus) {
  'use strict';

  var BaseCollection = Backbone.Collection.extend({
    constructor: function () {
      Backbone.Collection.prototype.constructor.apply(this, arguments);
      this.startHeartbeat(this.heartbeat);
    },

    startHeartbeat: function (heartbeat) {
      this.heartbeat = heartbeat;
      if (this.heartbeat) {
        EventBus.on(this.heartbeat, this.onHeartbeat, this);
      }
    },

    onHeartbeat: function (options) {
      if (!this.hasAll(options)) {
        this.fetch({ reset: true });
      }
    },

    stopHeartbeat: function () {
      if (this.heartbeat) {
        EventBus.off(this.heartbeat, this.onHeartbeat, this);
      }
    },

    hasAll: function (data) {
      return _.all(data, function (el) {
        return !_.isEmpty(this.findWhere(this._findFilter(el)));
      }.bind(this));
    },

    _findFilter: function (el) {
      if (_.isUndefined(el.modified)) {
        return { ID: el.ID };
      }

      return _.isUndefined(this.model.prototype.defaults.modified) ? { ID: el.ID } : { ID: el.ID, modified: new Date(el.modified) };
    }
  });

  return BaseCollection;
});<commit_msg>Fix problem with unneedless fetchings and mark the new posts<commit_after>/* global define */

define([
  'underscore',
  'backbone',
  'buses/event-bus'
], function (_, Backbone, EventBus) {
  'use strict';

  var BaseCollection = Backbone.Collection.extend({
    constructor: function () {
      Backbone.Collection.prototype.constructor.apply(this, arguments);
      this.startHeartbeat(this.heartbeat);
    },

    startHeartbeat: function (heartbeat) {
      this.heartbeat = heartbeat;
      if (this.heartbeat) {
        EventBus.on(this.heartbeat, this.onHeartbeat, this);
      }
    },

    onHeartbeat: function (options) {
      if (!this.hasAll(options)) {
        this.fetch({ reset: true }).done(function () {
          var entry;
          _.each(options, function (el) {
            entry = this.findWhere({ ID: el.ID });
            entry.set({ 'new': true });
          }.bind(this));
        }.bind(this));
      }
    },

    stopHeartbeat: function () {
      if (this.heartbeat) {
        EventBus.off(this.heartbeat, this.onHeartbeat, this);
      }
    },

    hasAll: function (data) {
      return _.all(data, function (el) {
        return !_.isEmpty(this.find(function (model) {
          if (_.isUndefined(el.modified)) {
            return el.ID === model.get('ID');
          }

          if (_.isUndefined(model.get('modified'))) {
            return el.ID === model.get('ID');
          } else {
            var modified = new Date(Date.parse(el.modified)).toISOString();
            return el.ID === model.get('ID') &&
                    modified === model.get('modified').toISOString();
          }
        }));
      }.bind(this));
    }
  });

  return BaseCollection;
});<|endoftext|>


<commit_before>import Ember from 'ember';

export default Ember.Component.extend({
  i18n: Ember.inject.service(),
  isMenuVisible: false,
  menuItems: Ember.computed(function(){
    return [
      {
        'icon': 'home',
        'route': 'dashboard',
        'name': this.get('i18n').t('navigation.dashboard')
      },
      {
        'icon': 'book',
        'route': 'courses',
        'name': this.get('i18n').t('navigation.courses')
      },
      {
        'icon': 'mortar-board',
        'route': 'learnerGroups',
        'name': this.get('i18n').t('navigation.learnerGroups')
      },
      {
        'icon': 'user-md',
        'route': 'instructorGroups',
        'name': this.get('i18n').t('navigation.instructorGroups')
      },
      {
        'icon': 'list-alt',
        'route': 'programs',
        'name': this.get('i18n').t('navigation.programs')
      },
    ];
  }),
  actions: {
    toggleMenuVisibility: function(){
      this.toggleProperty('isMenuVisible');
    }
  }
});
<commit_msg>Re-compute navigation when locale changes<commit_after>import Ember from 'ember';

export default Ember.Component.extend({
  i18n: Ember.inject.service(),
  isMenuVisible: false,
  menuItems: Ember.computed('i18n.locale', function(){
    return [
      {
        'icon': 'home',
        'route': 'dashboard',
        'name': this.get('i18n').t('navigation.dashboard')
      },
      {
        'icon': 'book',
        'route': 'courses',
        'name': this.get('i18n').t('navigation.courses')
      },
      {
        'icon': 'mortar-board',
        'route': 'learnerGroups',
        'name': this.get('i18n').t('navigation.learnerGroups')
      },
      {
        'icon': 'user-md',
        'route': 'instructorGroups',
        'name': this.get('i18n').t('navigation.instructorGroups')
      },
      {
        'icon': 'list-alt',
        'route': 'programs',
        'name': this.get('i18n').t('navigation.programs')
      },
    ];
  }),
  actions: {
    toggleMenuVisibility: function(){
      this.toggleProperty('isMenuVisible');
    }
  }
});
<|endoftext|>


<commit_before>var RSVP = require('rsvp'),
    request = RSVP.denodeify(require('request')),
    _ = require('lodash'),

    registry = require('npm-registry'),
    npm = new registry(),

    EMBER_OBSERVER_API_URL = 'http://emberobserver.com/api/addons',
    EMBER_ADDON_KEYWORD = 'ember-addon',
    IGNORE_ADDON_PATTERNS = [/ember-cli-fill-murray-.*/],

    RETRY_ATTEMPTS = 10;

var EmberAddons = function(options) {
  this.options = options || {};
  this.debug = this.options.debug || false;
};

EmberAddons.prototype.log = function() {
  if (this.debug) {
    console.log.apply(this, arguments);
  }
};

EmberAddons.prototype.get = function(name) {
  var self = this;
  var promise = new RSVP.Promise(function(resolve, reject) {
    self.log('--> Getting details:', name);

    function makeRequest(name, attempts, callback) {
      if (attempts > RETRY_ATTEMPTS) callback(new Error('Too many attempts:' + name));
      npm.packages.get(name, function(err, data) {
        if (err) {
          self.log('--> Retry get ['+ attempts +'/'+ RETRY_ATTEMPTS +']:', name);
          makeRequest(name, attempts + 1, callback);
        } else {
          callback(null, data);
        }
      });
    }

    makeRequest(name, 1, function(err, data) {
      if (err) reject(err);
      self.log('--> Got details for:', data[0].name);
      resolve(data[0]);
    });
  });

  return promise;
};

EmberAddons.prototype.downloads = function(item) {
  var self = this;
  var promise = new RSVP.Promise(function(resolve, reject) {
    self.log('--> Getting downloads for:', item.name);

    function makeRequest(name, attempts, callback) {
      if (attempts > RETRY_ATTEMPTS) callback(new Error('Too many attempts:', name));
      npm.downloads.totals('last-month', name, function(err, data) {
        if (err) {
          self.log('--> Retry downloads ['+ attempts +'/'+ RETRY_ATTEMPTS +']:', name);
          makeRequest(name, attempts + 1, callback);
        } else {
          callback(null, data);
        }
      });
    }

    makeRequest(item.name, 1, function(err, data) {
      if (err) reject(err);
      self.log('--> Got downloads for:', item.name);
      item.downloads = data[0];
      resolve(item);
    });

  });
  return promise;
};

EmberAddons.prototype.fetchAll = function fetchAll() {
  var self = this;

  function isNotIgnored(addon) {
    // Returns true if addon.name does not match
    // any of the IGNORE_ADDON_PATTERNS
    return IGNORE_ADDON_PATTERNS.every(function(pattern) {
      if (addon.name.search(pattern) < 0) {
        return true;
      } else {
        self.log('--> Skip:', addon.name);
        return false;
      }
    });
  }

  var promise = new RSVP.Promise(function(resolve, reject) {
    npm.packages.keyword(EMBER_ADDON_KEYWORD, function(err, data) {
      if (err) reject(err);

      self.log('--> All addons:', data.length);

      var filtered = data.filter(isNotIgnored);
      self.log('--> Filtered addons:', filtered.length);

      resolve(filtered);
    });

  });
  return promise;
};

EmberAddons.prototype.fetchAllWithDetails = function() {
  var self = this;
  var promise = new RSVP.Promise(function(resolve, reject) {
    self.fetchAll()
      .then(function(addons) {

        var promises = addons.map(function(item) {
          if (item.name) {
            return self.get(item.name);
          }
        });
        resolve(RSVP.all(promises));
      })
      .catch(function(err) {
        reject(err);
      });
  });
  return promise;
};

EmberAddons.prototype.fetchAllWithDetailsAndDownloads = function() {
  var self = this;
  var promise = new RSVP.Promise(function(resolve, reject) {
    self.fetchAllWithDetails()
      .then(function(addons) {

        var promises = addons.map(function(item) {
          return self.downloads(item);
        });
        resolve(RSVP.all(promises));
      })
      .catch(function(err) {
        reject(err);
      });
  });
  return promise;
};

/**
 * Fetch data and sort from newest to oldest updated.
 * @return {Array} Returns an array of Object
 */
EmberAddons.prototype.fetchAllWithDetailsAndDownloadsSorted = function() {
  var self = this;
  var promise = new RSVP.Promise(function(resolve, reject) {
    self.fetchAllWithDetailsAndDownloads().then(function(result) {
      self.log('--> Sorting...');
      result.sort(function(a, b) {
        // from newest to oldest
        return b.time.modified - a.time.modified;
      });
      resolve(result);
    })
    .catch(reject);
  });
  return promise;
};

EmberAddons.prototype.fetch = function() {
  var self = this;
  var promise = new RSVP.Promise(function(resolve) {
    self.fetchAllWithDetailsAndDownloadsSorted().then(function(addons) {
      self.log('--> Getting scores...');

      request(EMBER_OBSERVER_API_URL).then(function(response) {
        var observerData = JSON.parse(response.body).addons;

        addons.forEach(function(addon) {
          var eoData = _.findWhere(observerData, {name: addon.name});

          if (eoData) {
            addon.emberObserver = {
              score: eoData.score,
              isWIP: eoData.is_wip,
              note: eoData.note
            };
          }
        });

        resolve(addons);
      });

    });
  });
  return promise;
};

module.exports = EmberAddons;
<commit_msg>Stop using nodejitsu mirror (it's super outdated)<commit_after>var RSVP = require('rsvp'),
    request = RSVP.denodeify(require('request')),
    _ = require('lodash'),

    Registry = require('npm-registry'),
    npm = new Registry({
      registry: 'http://registry.npmjs.org/'
    }),

    EMBER_OBSERVER_API_URL = 'http://emberobserver.com/api/addons',
    EMBER_ADDON_KEYWORD = 'ember-addon',
    IGNORE_ADDON_PATTERNS = [/ember-cli-fill-murray-.*/],

    RETRY_ATTEMPTS = 10;

var EmberAddons = function(options) {
  this.options = options || {};
  this.debug = this.options.debug || false;
};

EmberAddons.prototype.log = function() {
  if (this.debug) {
    console.log.apply(this, arguments);
  }
};

EmberAddons.prototype.get = function(name) {
  var self = this;
  var promise = new RSVP.Promise(function(resolve, reject) {
    self.log('--> Getting details:', name);

    function makeRequest(name, attempts, callback) {
      if (attempts > RETRY_ATTEMPTS) callback(new Error('Too many attempts:' + name));
      npm.packages.get(name, function(err, data) {
        if (err) {
          self.log('--> Retry get ['+ attempts +'/'+ RETRY_ATTEMPTS +']:', name);
          makeRequest(name, attempts + 1, callback);
        } else {
          callback(null, data);
        }
      });
    }

    makeRequest(name, 1, function(err, data) {
      if (err) reject(err);
      self.log('--> Got details for:', data[0].name);
      resolve(data[0]);
    });
  });

  return promise;
};

EmberAddons.prototype.downloads = function(item) {
  var self = this;
  var promise = new RSVP.Promise(function(resolve, reject) {
    self.log('--> Getting downloads for:', item.name);

    function makeRequest(name, attempts, callback) {
      if (attempts > RETRY_ATTEMPTS) callback(new Error('Too many attempts:', name));
      npm.downloads.totals('last-month', name, function(err, data) {
        if (err) {
          self.log('--> Retry downloads ['+ attempts +'/'+ RETRY_ATTEMPTS +']:', name);
          makeRequest(name, attempts + 1, callback);
        } else {
          callback(null, data);
        }
      });
    }

    makeRequest(item.name, 1, function(err, data) {
      if (err) reject(err);
      self.log('--> Got downloads for:', item.name);
      item.downloads = data[0];
      resolve(item);
    });

  });
  return promise;
};

EmberAddons.prototype.fetchAll = function fetchAll() {
  var self = this;

  function isNotIgnored(addon) {
    // Returns true if addon.name does not match
    // any of the IGNORE_ADDON_PATTERNS
    return IGNORE_ADDON_PATTERNS.every(function(pattern) {
      if (addon.name.search(pattern) < 0) {
        return true;
      } else {
        self.log('--> Skip:', addon.name);
        return false;
      }
    });
  }

  var promise = new RSVP.Promise(function(resolve, reject) {
    npm.packages.keyword(EMBER_ADDON_KEYWORD, function(err, data) {
      if (err) reject(err);

      self.log('--> All addons:', data.length);

      var filtered = data.filter(isNotIgnored);
      self.log('--> Filtered addons:', filtered.length);

      resolve(filtered);
    });

  });
  return promise;
};

EmberAddons.prototype.fetchAllWithDetails = function() {
  var self = this;
  var promise = new RSVP.Promise(function(resolve, reject) {
    self.fetchAll()
      .then(function(addons) {

        var promises = addons.map(function(item) {
          if (item.name) {
            return self.get(item.name);
          }
        });
        resolve(RSVP.all(promises));
      })
      .catch(function(err) {
        reject(err);
      });
  });
  return promise;
};

EmberAddons.prototype.fetchAllWithDetailsAndDownloads = function() {
  var self = this;
  var promise = new RSVP.Promise(function(resolve, reject) {
    self.fetchAllWithDetails()
      .then(function(addons) {

        var promises = addons.map(function(item) {
          return self.downloads(item);
        });
        resolve(RSVP.all(promises));
      })
      .catch(function(err) {
        reject(err);
      });
  });
  return promise;
};

/**
 * Fetch data and sort from newest to oldest updated.
 * @return {Array} Returns an array of Object
 */
EmberAddons.prototype.fetchAllWithDetailsAndDownloadsSorted = function() {
  var self = this;
  var promise = new RSVP.Promise(function(resolve, reject) {
    self.fetchAllWithDetailsAndDownloads().then(function(result) {
      self.log('--> Sorting...');
      result.sort(function(a, b) {
        // from newest to oldest
        return b.time.modified - a.time.modified;
      });
      resolve(result);
    })
    .catch(reject);
  });
  return promise;
};

EmberAddons.prototype.fetch = function() {
  var self = this;
  var promise = new RSVP.Promise(function(resolve) {
    self.fetchAllWithDetailsAndDownloadsSorted().then(function(addons) {
      self.log('--> Getting scores...');

      request(EMBER_OBSERVER_API_URL).then(function(response) {
        var observerData = JSON.parse(response.body).addons;

        addons.forEach(function(addon) {
          var eoData = _.findWhere(observerData, {name: addon.name});

          if (eoData) {
            addon.emberObserver = {
              score: eoData.score,
              isWIP: eoData.is_wip,
              note: eoData.note
            };
          }
        });

        resolve(addons);
      });

    });
  });
  return promise;
};

module.exports = EmberAddons;
<|endoftext|>