<commit_before>#!/usr/bin/env node
'use strict';

var path = require('path');
var spawn = require('child_process').spawn;

var wd = require('wd');
var sauceConnectLauncher = require('sauce-connect-launcher');
var querystring = require("querystring");
var request = require('request').defaults({json: true});

var devserver = require('./dev-server.js');

var SELENIUM_PATH = '../vendor/selenium-server-standalone-2.38.0.jar';
var SELENIUM_HUB = 'http://localhost:4444/wd/hub/status';

var testTimeout = 30 * 60 * 1000;

var username = process.env.SAUCE_USERNAME;
var accessKey = process.env.SAUCE_ACCESS_KEY;

// process.env.CLIENT is a colon seperated list of
// (saucelabs|selenium):browserName:browserVerion:platform
var tmp = (process.env.CLIENT || 'selenium:firefox').split(':');
var client = {
  runner: tmp[0] || 'selenium',
  browser: tmp[1] || 'firefox',
  version: tmp[2] || null, // Latest
  platform: tmp[3] || null
};

var testUrl = 'http://127.0.0.1:8001/test/index.html';
var qs = {};

var sauceClient;
var sauceConnectProcess;
var tunnelId = process.env.TRAVIS_JOB_NUMBER || 'tunnel-' + Date.now();

if (client.runner === 'saucelabs') {
  qs.saucelabs = true;
}
if (process.env.GREP) {
  qs.grep = process.env.GREP;
}
if (process.env.ADAPTERS) {
  qs.adapters = process.env.ADAPTERS;
}
if (process.env.ES5_SHIM || process.env.ES5_SHIMS) {
  qs.es5shim = true;
}
testUrl += '?';
testUrl += querystring.stringify(qs);

if (process.env.TRAVIS &&
    client.browser !== 'firefox' &&
    process.env.TRAVIS_SECURE_ENV_VARS === 'false') {
  console.error('Not running test, cannot connect to saucelabs');
  process.exit(0);
  return;
}

function testError(e) {
  console.error(e);
  console.error('Doh, tests failed');
  sauceClient.quit();
  process.exit(3);
}

function postResult(result) {
  process.exit(!process.env.PERF && result.failed ? 1 : 0);
}

function testComplete(result) {
  console.log(result);

  sauceClient.quit().then(function () {
    if (sauceConnectProcess) {
      sauceConnectProcess.close(function () {
        postResult(result);
      });
    } else {
      postResult(result);
    }
  });
}

function startSelenium(callback) {

  // Start selenium
  spawn('java', ['-jar', path.resolve(__dirname, SELENIUM_PATH)], {});

  var retries = 0;
  var started = function () {

    if (++retries > 30) {
      console.error('Unable to connect to selenium');
      process.exit(1);
      return;
    }

    request(SELENIUM_HUB, function (err, resp) {
      if (resp && resp.statusCode === 200) {
        sauceClient = wd.promiseChainRemote();
        callback();
      } else {
        setTimeout(started, 1000);
      }
    });
  };

  started();

}

function startSauceConnect(callback) {

  var options = {
    username: username,
    accessKey: accessKey,
    tunnelIdentifier: tunnelId
  };

  sauceConnectLauncher(options, function (err, process) {
    if (err) {
      console.error('Failed to connect to saucelabs');
      console.error(err);
      return process.exit(1);
    }
    sauceConnectProcess = process;
    sauceClient = wd.promiseChainRemote("localhost", 4445, username, accessKey);
    callback();
  });
}

function startTest() {

  console.log('Starting', client);

  var opts = {
    browserName: client.browser,
    version: client.version,
    platform: client.platform,
    tunnelTimeout: testTimeout,
    name: client.browser + ' - ' + tunnelId,
    'max-duration': 60 * 30,
    'command-timeout': 599,
    'idle-timeout': 599,
    'tunnel-identifier': tunnelId
  };

  sauceClient.init(opts).get(testUrl, function () {

    /* jshint evil: true */
    var interval = setInterval(function () {
      sauceClient.eval('window.results', function (err, results) {
        if (err) {
          clearInterval(interval);
          testError(err);
        } else if (results.completed || results.failures.length) {
          clearInterval(interval);
          testComplete(results);
        } else {
          console.log('=> ', results);
        }
      });
    }, 10 * 1000);
  });
}

devserver.start(function () {
  if (client.runner === 'saucelabs') {
    startSauceConnect(startTest);
  } else {
    startSelenium(startTest);
  }
});
<commit_msg>(pouchdb/mapreduce#228) - actually test in phantom<commit_after>#!/usr/bin/env node
'use strict';

var path = require('path');
var spawn = require('child_process').spawn;

var wd = require('wd');
var sauceConnectLauncher = require('sauce-connect-launcher');
var querystring = require("querystring");
var request = require('request').defaults({json: true});

var devserver = require('./dev-server.js');

var SELENIUM_PATH = '../vendor/selenium-server-standalone-2.38.0.jar';
var SELENIUM_HUB = 'http://localhost:4444/wd/hub/status';

var testTimeout = 30 * 60 * 1000;

var username = process.env.SAUCE_USERNAME;
var accessKey = process.env.SAUCE_ACCESS_KEY;

// process.env.CLIENT is a colon seperated list of
// (saucelabs|selenium):browserName:browserVerion:platform
var tmp = (process.env.CLIENT || 'selenium:firefox').split(':');
var client = {
  runner: tmp[0] || 'selenium',
  browser: tmp[1] || 'firefox',
  version: tmp[2] || null, // Latest
  platform: tmp[3] || null
};

var testUrl = 'http://127.0.0.1:8001/test/index.html';
var qs = {};

var sauceClient;
var sauceConnectProcess;
var tunnelId = process.env.TRAVIS_JOB_NUMBER || 'tunnel-' + Date.now();

if (client.runner === 'saucelabs') {
  qs.saucelabs = true;
}
if (process.env.GREP) {
  qs.grep = process.env.GREP;
}
if (process.env.ADAPTERS) {
  qs.adapters = process.env.ADAPTERS;
}
if (process.env.ES5_SHIM || process.env.ES5_SHIMS) {
  qs.es5shim = true;
}
testUrl += '?';
testUrl += querystring.stringify(qs);

if (process.env.TRAVIS &&
    client.browser !== 'firefox' &&
    client.browser !== 'phantomjs' &&
    process.env.TRAVIS_SECURE_ENV_VARS === 'false') {
  console.error('Not running test, cannot connect to saucelabs');
  process.exit(1);
  return;
}

function testError(e) {
  console.error(e);
  console.error('Doh, tests failed');
  sauceClient.quit();
  process.exit(3);
}

function postResult(result) {
  process.exit(!process.env.PERF && result.failed ? 1 : 0);
}

function testComplete(result) {
  console.log(result);

  sauceClient.quit().then(function () {
    if (sauceConnectProcess) {
      sauceConnectProcess.close(function () {
        postResult(result);
      });
    } else {
      postResult(result);
    }
  });
}

function startSelenium(callback) {

  // Start selenium
  spawn('java', ['-jar', path.resolve(__dirname, SELENIUM_PATH)], {});

  var retries = 0;
  var started = function () {

    if (++retries > 30) {
      console.error('Unable to connect to selenium');
      process.exit(1);
      return;
    }

    request(SELENIUM_HUB, function (err, resp) {
      if (resp && resp.statusCode === 200) {
        sauceClient = wd.promiseChainRemote();
        callback();
      } else {
        setTimeout(started, 1000);
      }
    });
  };

  started();

}

function startSauceConnect(callback) {

  var options = {
    username: username,
    accessKey: accessKey,
    tunnelIdentifier: tunnelId
  };

  sauceConnectLauncher(options, function (err, process) {
    if (err) {
      console.error('Failed to connect to saucelabs');
      console.error(err);
      return process.exit(1);
    }
    sauceConnectProcess = process;
    sauceClient = wd.promiseChainRemote("localhost", 4445, username, accessKey);
    callback();
  });
}

function startTest() {

  console.log('Starting', client);

  var opts = {
    browserName: client.browser,
    version: client.version,
    platform: client.platform,
    tunnelTimeout: testTimeout,
    name: client.browser + ' - ' + tunnelId,
    'max-duration': 60 * 30,
    'command-timeout': 599,
    'idle-timeout': 599,
    'tunnel-identifier': tunnelId
  };

  sauceClient.init(opts).get(testUrl, function () {

    /* jshint evil: true */
    var interval = setInterval(function () {
      sauceClient.eval('window.results', function (err, results) {
        if (err) {
          clearInterval(interval);
          testError(err);
        } else if (results.completed || results.failures.length) {
          clearInterval(interval);
          testComplete(results);
        } else {
          console.log('=> ', results);
        }
      });
    }, 10 * 1000);
  });
}

devserver.start(function () {
  if (client.runner === 'saucelabs') {
    startSauceConnect(startTest);
  } else {
    startSelenium(startTest);
  }
});
<|endoftext|>


<commit_before>var nodemon = require('nodemon')
var clc = require('cli-color')

// NODE_ENV=development nodemon --exec npm run babel-app src/server/app.js --kill-others
// ROOT=/path/to/my/abesite node src/tasks/nodemon.js

nodemon({
  script: __dirname + '/../../src/server/app.js',
  options: {
    exec: __dirname + '/../../node_modules/.bin/babel-node --presets es2015'
  },
  nodeArgs: ['--debug'],
  restartable: 'rs',
  colours: true,
  execMap: {
    js: __dirname + '/../../node_modules/.bin/babel-node --presets es2015'
  },
  env: {
    'NODE_ENV': 'development'
  },
  ignore: [
    // 'docs/*'
  ],
  watch: [
    'src/cli/*',
    'src/hooks/*',
    'src/server/routes/*',
    'src/server/helpers/*',
    'src/server/middlewares/*',
    'src/server/controllers/*',
    'src/server/app.js',
    'src/server/index.js',
    process.env.ROOT + '/scripts/**/**/*.js',
    process.env.ROOT + '/abe.json',
    process.env.ROOT + '/locales/*',
    process.env.ROOT + '/hooks/**/*.js',
    process.env.ROOT + '/reference/**/*.json'
  ],
  stdin: true,
  runOnChangeOnly: false,
  verbose: true,
  // 'stdout' refers to the default behaviour of a required nodemon's child,
  // but also includes stderr. If this is false, data is still dispatched via
  // nodemon.on('stdout/stderr')
  stdout: true
})

nodemon.on('start', function () {
}).on('quit', function () {
  console.log(clc.green('Kill process nodemon'))
  process.exit()
}).on('restart', function (files) {
  console.log('------------------------------------------------------------')
  console.log(clc.green('App restarted due to: '), files[0])
})<commit_msg>uncomment docs<commit_after>var nodemon = require('nodemon')
var clc = require('cli-color')

// NODE_ENV=development nodemon --exec npm run babel-app src/server/app.js --kill-others
// ROOT=/path/to/my/abesite node src/tasks/nodemon.js

nodemon({
  script: __dirname + '/../../src/server/app.js',
  options: {
    exec: __dirname + '/../../node_modules/.bin/babel-node --presets es2015'
  },
  nodeArgs: ['--debug'],
  restartable: 'rs',
  colours: true,
  execMap: {
    js: __dirname + '/../../node_modules/.bin/babel-node --presets es2015'
  },
  env: {
    'NODE_ENV': 'development'
  },
  ignore: [
    'docs/*'
  ],
  watch: [
    'src/cli/*',
    'src/hooks/*',
    'src/server/routes/*',
    'src/server/helpers/*',
    'src/server/middlewares/*',
    'src/server/controllers/*',
    'src/server/app.js',
    'src/server/index.js',
    process.env.ROOT + '/scripts/**/**/*.js',
    process.env.ROOT + '/abe.json',
    process.env.ROOT + '/locales/*',
    process.env.ROOT + '/hooks/**/*.js',
    process.env.ROOT + '/reference/**/*.json'
  ],
  stdin: true,
  runOnChangeOnly: false,
  verbose: true,
  // 'stdout' refers to the default behaviour of a required nodemon's child,
  // but also includes stderr. If this is false, data is still dispatched via
  // nodemon.on('stdout/stderr')
  stdout: true
})

nodemon.on('start', function () {
}).on('quit', function () {
  console.log(clc.green('Kill process nodemon'))
  process.exit()
}).on('restart', function (files) {
  console.log('------------------------------------------------------------')
  console.log(clc.green('App restarted due to: '), files[0])
})<|endoftext|>


<commit_before>import path from 'path';
import notify from 'gulp-notify';
import plumber from 'gulp-plumber';
import sourcemaps from 'gulp-sourcemaps';
import browserSync from 'browser-sync';

// PostCSS and plugins
import postcss from 'gulp-postcss';
import postcssImport from 'postcss-import';
import postcssCopy from 'postcss-copy';

/**
 * Gulp task to process the css files usign PostCSS and cssnext
 * @param  {object} config Global configuration
 * @return {function}       Function task
 */
export default function postcssTask(userConfig) {
    const gulp = this.gulp;
    const config = userConfig || this.config;
    const plumberOptions = {};
    if (config.notify.onError) {
        plumberOptions.errorHandler = notify.onError('PostCSS Error: <%= error.message %>');
    }

    // PostCSS plugins configuration
    let plugins = config.postcssPlugins.before || [];
    plugins.push(postcssImport());
    plugins.push(postcssCopy({
        src: config.sourcePath,
        dest: config.destPath,
        keepRelativePath: false,
        template: 'assets/[hash].[ext]'
    }));
    if (config.postcssPlugins.after) {
        plugins = plugins.concat(config.postcssPlugins.after);
    }

    return () => {
        let stream = gulp.src(path.join(config.sourcePath, config.entryCss))
            .pipe(plumber(plumberOptions))
            .pipe(postcss(plugins, {
                map: !(config.isProduction),
                to: path.join(config.destPath, config.entryCss)
            }));

        if (!(config.isProduction)) {
            stream = stream
                .pipe(sourcemaps.init({
                    loadMaps: true
                }))
                .pipe(sourcemaps.write('./', {
                    sourceRoot: '/' + path.basename(config.sourcePath)
                }));
        }

        stream = stream.pipe(gulp.dest(config.destPath));

        if (config.watch) {
            stream = stream.pipe(browserSync.stream({match: '**/*.{css,scss,less}'}));
        }

        if (config.notify.onUpdated) {
            return stream.pipe(notify('PostCSS Bundle - Updated'));
        }

        return stream;
    };
}
<commit_msg>add node_modules to the postcss-copy multiple src<commit_after>import path from 'path';
import notify from 'gulp-notify';
import plumber from 'gulp-plumber';
import sourcemaps from 'gulp-sourcemaps';
import browserSync from 'browser-sync';

// PostCSS and plugins
import postcss from 'gulp-postcss';
import postcssImport from 'postcss-import';
import postcssCopy from 'postcss-copy';

/**
 * Gulp task to process the css files usign PostCSS and cssnext
 * @param  {object} config Global configuration
 * @return {function}       Function task
 */
export default function postcssTask(userConfig) {
    const gulp = this.gulp;
    const config = userConfig || this.config;
    const plumberOptions = {};
    if (config.notify.onError) {
        plumberOptions.errorHandler = notify.onError('PostCSS Error: <%= error.message %>');
    }

    // PostCSS plugins configuration
    let plugins = config.postcssPlugins.before || [];
    plugins.push(postcssImport());
    plugins.push(postcssCopy({
        src: [config.sourcePath, path.join(config.basePath, 'node_modules')],
        dest: config.destPath,
        keepRelativePath: false,
        template: 'assets/[hash].[ext]'
    }));
    if (config.postcssPlugins.after) {
        plugins = plugins.concat(config.postcssPlugins.after);
    }

    return () => {
        let stream = gulp.src(path.join(config.sourcePath, config.entryCss))
            .pipe(plumber(plumberOptions))
            .pipe(postcss(plugins, {
                map: !(config.isProduction),
                to: path.join(config.destPath, config.entryCss)
            }));

        if (!(config.isProduction)) {
            stream = stream
                .pipe(sourcemaps.init({
                    loadMaps: true
                }))
                .pipe(sourcemaps.write('./', {
                    sourceRoot: '/' + path.basename(config.sourcePath)
                }));
        }

        stream = stream.pipe(gulp.dest(config.destPath));

        if (config.watch) {
            stream = stream.pipe(browserSync.stream({match: '**/*.{css,scss,less}'}));
        }

        if (config.notify.onUpdated) {
            return stream.pipe(notify('PostCSS Bundle - Updated'));
        }

        return stream;
    };
}
<|endoftext|>


<commit_before>'use strict';

var consul = require('consul')({host: 'consul'});
var express = require('express');
var _ = require('lodash');

var app = express();

var PORT = 3000;

var os = require('os');
var ifaces = os.networkInterfaces();

var x = _.filter(ifaces, function (o, item) {
  return item !== 'lo';
});

var y = _.filter(x[0], function (el) {
  return el.family === 'IPv4';
});

var HOST = y[0].address;

var TAGS = process.env.TAGS;
var tags = TAGS.split(',');

consul.agent.service.register({
  tags: tags,
  name: 'rest-ip',
  address: HOST,
  port: PORT,
  id: 'worker-' + HOST,
  check: {
    http: 'http://' + HOST + ':' + PORT + '/api/v1/health',
    interval: '1s'
  }
});

app.get('/api/v1/ip', function (req, res) {
  res.send({version: 2.1, kind: TAGS, last_ip: '0.0.0.0', time: 'foo'});
});

app.get('/api/v1/health', function (req, res) {
  res.send({health: true});
});

var server = app.listen(PORT);

process.on('SIGTERM', function() {
  consul.agent.service.deregister('worker-' + HOST, function (a,b,c) {
    setTimeout(function() {
      process.exit(0);
    }, 5000);
  });
});
<commit_msg>refactoring<commit_after>'use strict';

var consul = require('consul')({host: 'consul'});
var express = require('express');
var _ = require('lodash');
var os = require('os');

var app = express();

var PORT = 3000;
var TAGS = process.env.TAGS;

app.get('/api/v1/ip', function (req, res) {
  res.send({version: 0.1, kind: TAGS, last_ip: '0.0.0.0', time: 'foo'});
});

app.get('/api/v1/health', function (req, res) {
  res.send({health: true});
});

var server = app.listen(PORT);

require('dns').lookup(os.hostname(), function (err, add) {
  console.log('addr: '+add);
  consul.agent.service.register({
    tags: TAGS.split(','),
    name: 'rest-ip',
    address: add,
    port: PORT,
    id: 'worker-' + add,
    check: {
      http: 'http://' + add + ':' + PORT + '/api/v1/health',
      interval: '1s'
    }
  }, function () {
    console.log('registration done');
    process.on('SIGTERM', function() {
    console.log('deregistering');
      consul.agent.service.deregister('worker-' + add, function () {
        console.log('deregistered');
        setTimeout(function() {
          console.log('shutting down server');
          server.close();
        }, 5000);
      });
    });
  });

});

<|endoftext|>


<commit_before>// Define a simple Car constructor
var Car = function(settings) {
  this.model = settings.model || "no model provided";
  this.color = settings.color || "no colour provided";
};

// Mixin
var Mixin = function() {};

Mixin.prototype = {

  driveForward: function () {
    console.log( "drive forward" );
  },

  driveBackward: function() {
    console.log( "drive backward" );
  },

  driveSideways: function () {
    console.log( "drive sideways" );
  }

};

// Extend an existing object with a method from another
function augment(receivingClass, givingClass) {

  // only provide certain methods
  if (arguments[2]) {
    for(var i = 2, len = arguments.length; i < len; i++) {
      receivingClass.prototype[arguments[i]] = givingClass.prototype[arguments[i]];
    }
  }
  // provide all methods
  else {
    for (var methodName in givingClass.prototype) {

      // check to make sure the receiving class doesn't
      // have a method of the same name as the one currently
      // being processed
      if (!Object.hasOwnProperty.call(receivingClass.prototype, methodName)) {
        receivingClass.prototype[methodName] = givingClass.prototype[methodName];
      }

      // Alternatively (check prototype chain as well):
      // if (!receivingClass.prototype[methodName]) {
      //   receivingClass.prototype[methodName] = givingClass.prototype[methodName];
      // }
    }
  }
}

// Augment the Car constructor to include "driveForward" and "driveBackward"
augment( Car, Mixin, "driveForward", "driveBackward" );

// Create a new Car
var myCar = new Car({
  model: "Ford Escort",
  color: "blue"
});

// Test to make sure we now have access to the methods
myCar.driveForward();
myCar.driveBackward();

// Outputs:
// drive forward
// drive backward

// We can also augment Car to include all functions from our mixin
// by not explicitly listing a selection of them
augment( Car, Mixin );

var mySportsCar = new Car({
  model: "Porsche",
  color: "red"
});

mySportsCar.driveSideways();

// Outputs:
// drive sideways
<commit_msg>Upate mixin remove spaces<commit_after>// Define a simple Car constructor
var Car = function(settings) {
  this.model = settings.model || "no model provided";
  this.color = settings.color || "no colour provided";
};

// Mixin
var Mixin = function() {};

Mixin.prototype = {

  driveForward: function() {
    console.log("drive forward");
  },

  driveBackward: function() {
    console.log("drive backward");
  },

  driveSideways: function() {
    console.log("drive sideways");
  }

};

// Extend an existing object with a method from another
function augment(receivingClass, givingClass) {

  // only provide certain methods
  if (arguments[2]) {
    for(var i = 2, len = arguments.length; i < len; i++) {
      receivingClass.prototype[arguments[i]] = givingClass.prototype[arguments[i]];
    }
  }
  // provide all methods
  else {
    for (var methodName in givingClass.prototype) {

      // check to make sure the receiving class doesn't
      // have a method of the same name as the one currently
      // being processed
      if (!Object.hasOwnProperty.call(receivingClass.prototype, methodName)) {
        receivingClass.prototype[methodName] = givingClass.prototype[methodName];
      }

      // Alternatively (check prototype chain as well):
      // if (!receivingClass.prototype[methodName]) {
      //   receivingClass.prototype[methodName] = givingClass.prototype[methodName];
      // }
    }
  }
}

// Augment the Car constructor to include "driveForward" and "driveBackward"
augment(Car, Mixin, "driveForward", "driveBackward");

// Create a new Car
var myCar = new Car({
  model: "Ford Escort",
  color: "blue"
});

// Test to make sure we now have access to the methods
myCar.driveForward();
myCar.driveBackward();

// Outputs:
// drive forward
// drive backward

// We can also augment Car to include all functions from our mixin
// by not explicitly listing a selection of them
augment(Car, Mixin);

var mySportsCar = new Car({
  model: "Porsche",
  color: "red"
});

mySportsCar.driveSideways();

// Outputs:
// drive sideways
<|endoftext|>


<commit_before>import PropTypes from 'prop-types';
import React, { Component } from 'react';
import Button from 'components/Button';
import Loading from 'components/Loading';
import SearchInput from 'components/Texts/SearchInput';
import Input from 'components/Texts/Input';
import { addEmoji, stringIsEmpty } from 'helpers/stringHelpers';
import { borderRadius, Color, mobileMaxWidth } from 'constants/css';
import { css } from 'emotion';

export default class SectionPanel extends Component {
  static propTypes = {
    canEdit: PropTypes.bool,
    title: PropTypes.string,
    button: PropTypes.node,
    emptyMessage: PropTypes.string,
    inverted: PropTypes.bool,
    isEmpty: PropTypes.bool,
    isSearching: PropTypes.bool,
    headerTheme: PropTypes.object,
    loaded: PropTypes.bool,
    loadMore: PropTypes.func,
    children: PropTypes.node,
    loadMoreButtonShown: PropTypes.bool,
    onEditTitle: PropTypes.func,
    onSearch: PropTypes.func,
    placeholder: PropTypes.string,
    searchPlaceholder: PropTypes.string,
    searchQuery: PropTypes.string,
    style: PropTypes.object
  };

  constructor({ title }) {
    super();
    this.state = {
      loading: false,
      onEdit: false,
      editedTitle: title
    };
  }

  render() {
    const {
      canEdit,
      headerTheme = { color: '#fff', background: Color.logoBlue() },
      inverted,
      title,
      button,
      loadMoreButtonShown,
      onEditTitle,
      onSearch,
      placeholder = 'Enter Title',
      searchPlaceholder,
      searchQuery = '',
      style = {}
    } = this.props;
    const { loading, onEdit, editedTitle } = this.state;
    return (

 header {
            display: grid;
            width: 100%;
            grid-template-areas: 'title search buttons';
            grid-template-columns: auto ${onSearch ? '40%' : 'auto'} auto;
            background: ${inverted
              ? headerTheme.color
              : headerTheme.background};
            color: ${inverted ? headerTheme.background : headerTheme.color};
            border-top-left-radius: ${borderRadius};
            border-top-right-radius: ${borderRadius};
            padding: ${inverted ? '2rem' : '1rem'};
            font-weight: ${inverted ? 'bold' : ''};
            font-size: 2.5rem;
            align-items: center;
          }
          > main {
            position: relative;
            display: flex;
            flex-direction: column;
            padding: 1rem;
            width: 100%;
            justify-content: center;
            min-height: 15rem;
          }
          @media (max-width: ${mobileMaxWidth}) {
            border-radius: 0;
            border: 0;
            > header {
              border-radius: 0;
            }
          }
        `}
      >

            {onEdit ? (
              <Input
                maxLength={100}
                placeholder={placeholder}
                autoFocus
                onChange={text =>
                  this.setState({ editedTitle: addEmoji(text) })
                }
                onKeyPress={event => {
                  if (!stringIsEmpty(editedTitle) && event.key === 'Enter') {
                    this.onChangeTitle(editedTitle);
                  }
                }}
                value={editedTitle}
              />
            ) : (

{title}

            )}
            {canEdit && onEditTitle ? (

                  this.setState({ onEdit: !onEdit, editedTitle: title })
                }
              >
                {onEdit ? 'cancel' : 'change'}

            ) : (
              ''
            )}

          {onSearch && (
            <SearchInput
              style={{
                color: Color.black(),
                gridArea: 'search',
                width: '100%',
                justifySelf: 'center',
                zIndex: 0
              }}
              onChange={this.onSearch}
              placeholder={searchPlaceholder}
              value={searchQuery}
            />
          )}

            {button}

          {this.renderContent()}
          {loadMoreButtonShown && (

              <Button
                transparent
                disabled={loading}
                onClick={this.onLoadMore}
                style={{ fontSize: '2rem' }}
              >
                Load More
              </Button>

          )}

    );
  }

  onChangeTitle = async title => {
    const { onEditTitle } = this.props;
    await onEditTitle(title);
    this.setState({ onEdit: false });
  };

  onSearch = text => {
    const { onSearch } = this.props;
    onSearch(text);
  };

  onLoadMore = async() => {
    const { loadMore } = this.props;
    const { loading } = this.state;
    if (!loading) {
      this.setState({ loading: true });
      await loadMore();
      this.setState({ loading: false });
    }
  };

  renderContent = () => {
    const {
      children,
      emptyMessage,
      isEmpty,
      isSearching,
      loaded,
      searchQuery
    } = this.props;
    return loaded ? (
      (!stringIsEmpty(searchQuery) && isSearching) || isEmpty ? (

          {searchQuery && isSearching
            ? 'Searching...'
            : searchQuery
              ? 'No Results'
              : emptyMessage}

      ) : (
        children
      )
    ) : (
      <Loading />
    );
  };

  statusMsg = css`
    font-size: 3rem;
    font-weight: bold;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    position: absolute;
    display: flex;
    justify-content: center;
    align-items: center;
  `;
}
<commit_msg>underline off<commit_after>import PropTypes from 'prop-types';
import React, { Component } from 'react';
import Button from 'components/Button';
import Loading from 'components/Loading';
import SearchInput from 'components/Texts/SearchInput';
import Input from 'components/Texts/Input';
import { addEmoji, stringIsEmpty } from 'helpers/stringHelpers';
import { borderRadius, Color, mobileMaxWidth } from 'constants/css';
import { css } from 'emotion';

export default class SectionPanel extends Component {
  static propTypes = {
    canEdit: PropTypes.bool,
    title: PropTypes.string,
    button: PropTypes.node,
    emptyMessage: PropTypes.string,
    inverted: PropTypes.bool,
    isEmpty: PropTypes.bool,
    isSearching: PropTypes.bool,
    headerTheme: PropTypes.object,
    loaded: PropTypes.bool,
    loadMore: PropTypes.func,
    children: PropTypes.node,
    loadMoreButtonShown: PropTypes.bool,
    onEditTitle: PropTypes.func,
    onSearch: PropTypes.func,
    placeholder: PropTypes.string,
    searchPlaceholder: PropTypes.string,
    searchQuery: PropTypes.string,
    style: PropTypes.object
  };

  constructor({ title }) {
    super();
    this.state = {
      loading: false,
      onEdit: false,
      editedTitle: title
    };
  }

  render() {
    const {
      canEdit,
      headerTheme = { color: '#fff', background: Color.logoBlue() },
      inverted,
      title,
      button,
      loadMoreButtonShown,
      onEditTitle,
      onSearch,
      placeholder = 'Enter Title',
      searchPlaceholder,
      searchQuery = '',
      style = {}
    } = this.props;
    const { loading, onEdit, editedTitle } = this.state;
    return (

 header {
            display: grid;
            width: 100%;
            grid-template-areas: 'title search buttons';
            grid-template-columns: auto ${onSearch ? '40%' : 'auto'} auto;
            background: ${inverted
              ? headerTheme.color
              : headerTheme.background};
            color: ${inverted ? headerTheme.background : headerTheme.color};
            border-top-left-radius: ${borderRadius};
            border-top-right-radius: ${borderRadius};
            padding: ${inverted ? '2rem' : '1rem'};
            font-weight: ${inverted ? 'bold' : ''};
            font-size: 2.5rem;
            align-items: center;
          }
          > main {
            position: relative;
            display: flex;
            flex-direction: column;
            padding: 1rem;
            width: 100%;
            justify-content: center;
            min-height: 15rem;
          }
          @media (max-width: ${mobileMaxWidth}) {
            border-radius: 0;
            border: 0;
            > header {
              border-radius: 0;
            }
          }
        `}
      >

            {onEdit ? (
              <Input
                maxLength={100}
                placeholder={placeholder}
                autoFocus
                onChange={text =>
                  this.setState({ editedTitle: addEmoji(text) })
                }
                onKeyPress={event => {
                  if (!stringIsEmpty(editedTitle) && event.key === 'Enter') {
                    this.onChangeTitle(editedTitle);
                  }
                }}
                value={editedTitle}
              />
            ) : (

{title}

            )}
            {canEdit && onEditTitle ? (

                  this.setState({ onEdit: !onEdit, editedTitle: title })
                }
              >
                {onEdit ? 'cancel' : 'change'}

            ) : (
              ''
            )}

          {onSearch && (
            <SearchInput
              style={{
                color: Color.black(),
                gridArea: 'search',
                width: '100%',
                justifySelf: 'center',
                zIndex: 0
              }}
              onChange={this.onSearch}
              placeholder={searchPlaceholder}
              value={searchQuery}
            />
          )}

            {button}

          {this.renderContent()}
          {loadMoreButtonShown && (

              <Button
                transparent
                disabled={loading}
                onClick={this.onLoadMore}
                style={{ fontSize: '2rem' }}
              >
                Load More
              </Button>

          )}

    );
  }

  onChangeTitle = async title => {
    const { onEditTitle } = this.props;
    await onEditTitle(title);
    this.setState({ onEdit: false });
  };

  onSearch = text => {
    const { onSearch } = this.props;
    onSearch(text);
  };

  onLoadMore = async() => {
    const { loadMore } = this.props;
    const { loading } = this.state;
    if (!loading) {
      this.setState({ loading: true });
      await loadMore();
      this.setState({ loading: false });
    }
  };

  renderContent = () => {
    const {
      children,
      emptyMessage,
      isEmpty,
      isSearching,
      loaded,
      searchQuery
    } = this.props;
    return loaded ? (
      (!stringIsEmpty(searchQuery) && isSearching) || isEmpty ? (

          {searchQuery && isSearching
            ? 'Searching...'
            : searchQuery
              ? 'No Results'
              : emptyMessage}

      ) : (
        children
      )
    ) : (
      <Loading />
    );
  };

  statusMsg = css`
    font-size: 3rem;
    font-weight: bold;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    position: absolute;
    display: flex;
    justify-content: center;
    align-items: center;
  `;
}
<|endoftext|>


<commit_before>// adopted from: wordwrapjs <https://github.com/75lb/wordwrapjs>
// Copyright (c) 2015 Lloyd Brookes <75pound@gmail.com> (MIT)

// differs from orginal by:
// adding indent option,
// declaring a wrapLines function as opposed to variable assignment,
// removing option settings inside wrapLines function,
// removing os.EOL setting (using a string),
// no input text validation,

// [opts] {object} -- optional config
// [opts.width=50] {number} -- max column width in characters
// [opts.break] {boolean} -- if true, words exceeding the specified width will
// be forcefully broken.
// [opts.ignore] {RegExp | RegExp[]} -- one or more patterns to be ignored when
// sizing the newly wrapped line. For example `ignore: /\u001b.*?m/g`
// will ignore unprintable ansi escape sequences.
// [opts.eol='\n'] {string} -- the desired new line character to use.
// [opts.indent=''] {string} -- the desired number of spaces/tabs character to use
// for indenting the given text.

var forEach = require('../array/forEach')
var toArray = require('../lang/toArray')

var re = {
  nonWhitespaceCharsOrNewLine:  /[^\s-]+?-\b|\S+|\r\n?|\n/g,
  singleNewLine: /^(\r\n?|\n)$/
}

function wrap (text, opts) {
  opts = defaultOpts(opts)

  var lines = wrapLines(text, opts)
  return lines.join(opts.eol)
}

// returns the wrapped output as an array of lines, rather than a single string
function wrapLines (text, opts) {
  opts = opts || defaultOpts(opts)

  var words = getWords(text)

  var lineLength = 0
  var lines = []
  var line = ''

  if (opts.break) {
    var broken = []
    forEach(words, function (word) {
      var wordLength = opts.ignore
        ? replaceIgnored(word, opts.ignore).length
        : word.length

      if (wordLength > opts.width) {
        var letters = word.split('')
        var section

        while ((section = letters.splice(0, opts.width)).length) {
          broken.push(section.join(''))
        }
      } else {
        broken.push(word)
      }
    })

    words = broken
  }

  // for each word, either extend the current `line` or create a new one
  forEach(words, function (word) {
    if (re.singleNewLine.test(word)) {
      lines.push(line ? opts.indent + line : '')
      line = ''
      lineLength = 0
    } else {
      var wordLength = opts.ignore
        ? replaceIgnored(word, opts.ignore).length
        : word.length

      lineLength += wordLength + (line ? 1 : 0)

      if (lineLength > opts.width) {
        // Can't fit word on line, cache line and create new one
        if (line) lines.push(opts.indent + line)
        line = word
        lineLength = wordLength
      } else {
        if (/-$/.test(line)) line = word
        else line += (line ? ' ' : '') + word
      }
    }
  })

  if (line) lines.push(opts.indent + line)

  return lines
}

// splits the input text returning an array of words
function getWords (text) {
  return text.match(re.nonWhitespaceCharsOrNewLine) || []
}

function replaceIgnored (string, ignore) {
  toArray(ignore).forEach(function (pattern) {
    string = string.replace(pattern, '')
  })
  return string
}

function defaultOpts (opts) {
  opts = opts || {}
  opts.width = opts.width || 50
  opts.break = opts.break || false
  opts.indent = opts.indent || ''
  opts.eol = opts.eol || '\n'
  return opts
}

module.exports = wrap
module.exports.lines = wrapLines
module.exports.getWords = getWords
<commit_msg>update text/wordwrap<commit_after>// adopted from: wordwrapjs <https://github.com/75lb/wordwrapjs>
// Copyright (c) 2015 Lloyd Brookes <75pound@gmail.com> (MIT)

// differs from orginal by:
// adding indent option,
// declaring a wrapLines function as opposed to variable assignment,
// removing option settings inside wrapLines function,
// removing os.EOL setting (using a string),
// no input text validation,

// [opts] {object} -- optional config
// [opts.width=50] {number} -- max column width in characters
// [opts.break] {boolean} -- if true, words exceeding the specified width will
// be forcefully broken.
// [opts.ignore] {RegExp | RegExp[]} -- one or more patterns to be ignored when
// sizing the newly wrapped line. For example `ignore: /\u001b.*?m/g`
// will ignore unprintable ansi escape sequences.
// [opts.eol='\n'] {string} -- the desired new line character to use.
// [opts.indent=''] {string} -- the desired number of spaces/tabs character to use
// for indenting the given text.

var forEach = require('../array/forEach')
var toArray = require('../lang/toArray')

var re = {
  nonWhitespaceCharsOrNewLine:  /[^\s-]+?-\b|\S+|\r\n?|\n/g,
  singleNewLine: /^(\r\n?|\n)$/
}

function wrap (text, opts) {
  opts = defaultOpts(opts)

  var lines = wrapLines(text, opts)
  return lines.join(opts.eol)
}

// returns the wrapped output as an array of lines, rather than a single string
function wrapLines (text, opts) {
  opts = opts || defaultOpts(opts)

  var words = getWords(text)

  var lineLength = 0
  var lines = []
  var line = ''

  if (opts.break) {
    var broken = []
    forEach(words, function (word) {
      var wordLength = opts.ignore
        ? replaceIgnored(word, opts.ignore).length
        : word.length

      if (wordLength > opts.width) {
        var letters = word.split('')
        var section

        while ((section = letters.splice(0, opts.width)).length) {
          broken.push(section.join(''))
        }
      } else {
        broken.push(word)
      }
    })

    words = broken
  }

  // for each word, either extend the current `line` or create a new one
  forEach(words, function (word) {
    if (re.singleNewLine.test(word)) {
      lines.push(line ? opts.indent + line : '')
      line = ''
      lineLength = 0
    } else {
      var wordLength = opts.ignore
        ? replaceIgnored(word, opts.ignore).length
        : word.length

      var offset
      if (lineLength > options.width) {
        offset = 0
      } else {
        if (/-$/.test(line)) {
          offset = 0
        } else {
          offset = line ? 1 : 0
        }
      }

      lineLength += wordLength + offset

      if (lineLength > opts.width) {
        // Can't fit word on line, cache line and create new one
        if (line) lines.push(opts.indent + line)
        line = word
        lineLength = wordLength
      } else {
        if (/-$/.test(line)) line = word
        else line += (line ? ' ' : '') + word
      }
    }
  })

  if (line) lines.push(opts.indent + line)

  return lines
}

// splits the input text returning an array of words
function getWords (text) {
  return text.match(re.nonWhitespaceCharsOrNewLine) || []
}

function replaceIgnored (string, ignore) {
  toArray(ignore).forEach(function (pattern) {
    string = string.replace(pattern, '')
  })
  return string
}

function defaultOpts (opts) {
  opts = opts || {}
  opts.width = opts.width || 50
  opts.break = opts.break || false
  opts.indent = opts.indent || ''
  opts.eol = opts.eol || '\n'
  return opts
}

module.exports = wrap
module.exports.lines = wrapLines
module.exports.getWords = getWords
<|endoftext|>


<commit_before>'use strict';

function getEnv() {
  if (process.env.NODE_ENV) {
    return process.env.NODE_ENV;
  }
  if (process.env.AWS_LAMBDA_FUNCTION_NAME) {
    // TODO put your own lambda function name here
    if (process.env.AWS_LAMBDA_FUNCTION_NAME === '') {
      return 'production';
    }
    return 'staging';
  }

  return 'local';
}

module.exports = getEnv();
<commit_msg>Improve config to be easy readable closes mediarain/generator-voxa-skill#3<commit_after>'use strict';

const _ = require('lodash');

function getEnv() {
  const NODE_ENV = process.env.NODE_ENV;
  const AWS_LAMBDA_FUNCTION_NAME = process.env.AWS_LAMBDA_FUNCTION_NAME;

  // Environment base on lambda function name
  // TODO put your own lambda function name here

  const AWS_LAMBDA_PRODUCTION_ENV = ['LAMBDA_FUNCTION_NAME_PROD']; // production
  const AWS_LAMBDA_STAGING_ENV = ['LAMBDA_FUNCTION_NAME_STAGE'];  // staging

  if (NODE_ENV) {
    return NODE_ENV;
  }

  if (AWS_LAMBDA_FUNCTION_NAME) {
    if (_.includes(AWS_LAMBDA_PRODUCTION_ENV, AWS_LAMBDA_FUNCTION_NAME)) return 'production';
    if (_.includes(AWS_LAMBDA_STAGING_ENV, AWS_LAMBDA_FUNCTION_NAME)) return 'staging';
  }

  // Default local
  return 'local';
}

module.exports = getEnv();
<|endoftext|>


<commit_before>var bcv_parser = require("./en_bcv_parser.js").bcv_parser;
var bcv = new bcv_parser;

var MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server,
    db;

var mongoClient = new MongoClient(new Server('localhost', 27017));
mongoClient.open(function(err, mongoClient) {
    db = mongoClient.db("bible-api");
    db.collection('bible', {strict:true}, function(err, collection) {
        if (err) {
            console.log("Error!");
        }
    });
});

var fetchBcv = function(passage, res) {
  var pTranslation = 'RST';
  if (passage.translations != null) {
    pTranslation = passage.translations[0].osis;
  }
  db.collection('bible', function(err, collection) {
    collection.find({
      'tran':pTranslation,
      'bookRef':passage.start.b,
      'chapter':passage.start.c,
      'verse':passage.start.v
    }).toArray(function(err, items) {
      res.jsonp(items);
    });
  });
};

var fetchRange = function(passage, res) {
  var pTranslation = 'RST';
  if (passage.translations != null) {
    pTranslation = passage.translations[0].osis;
  }

  // passage of the same book
  if (passage.start.b === passage.end.b) {
    // passage of one chapter
    if (passage.start.c === passage.end.c) {
      db.collection('bible', function(err, collection) {
        collection.find({
          'tran':pTranslation,
          'bookRef':passage.start.b,
          'chapter':passage.start.c,
          'verse':{$gte:passage.start.v, $lte:passage.end.v}
        }).toArray(function(err, items) {
          res.jsonp(items);
        });
      });
    }
    else { // passage of many chapters
      var chapters = [];
      for (var ch=passage.start.c; ch<=passage.end.c; ch++) {
        var startVerse = 1;
        var endVerse = translationInfo.chapters[passage.start.b][ch-1];

        if (ch === passage.start.c) {
          startVerse = passage.start.v;
        }
        if (ch === passage.end.c) {
          endVerse = passage.end.v;
        }

        chapters.push({
          'tran':pTranslation,
          'bookRef':passage.start.b,
          'chapter':ch,
          'verse':{$gte:startVerse, $lte:endVerse}
        });
      }

      db.collection('bible', function(err, collection) {
        collection.find({
          $or: chapters
        }).toArray(function(err, items) {
          res.jsonp(items);
        });
      });
    }
  } // passage of many books
  else {
    var chapters = [];
    var startBook = translationInfo.order[passage.start.b];
    var endBook = translationInfo.order[passage.end.b];

    for (var b=startBook; b<=endBook; b++) {
      var bookRef = translationInfo.books[b-1];

      // passage includes the whole book in the middle
      if (b != startBook && b != endBook) {
        chapters.push({
          'tran':pTranslation,
          'bookRef':bookRef
        });
      }
      else { // other half-books parts
        var startChapter = 1;
        var endChapter = translationInfo.chapters[bookRef].length;

        if (b === startBook) {
          startChapter = passage.start.c;
        }
        if (b === endBook) {
          endChapter = passage.end.c;
        }

        for (var ch=startChapter; ch<=endChapter; ch++) {
          var startVerse = 1;
          var endVerse = translationInfo.chapters[bookRef][ch-1];

          // first chapter, first verse in range
          if (b === startBook && ch === startChapter) {
            startVerse = passage.start.v;
            chapters.push({
              'tran':pTranslation,
              'bookRef':bookRef,
              'chapter':startChapter,
              'verse':{$gte:startVerse, $lte:endVerse}
            });
          } // last chapter, last verse in range
          else if (b === endBook && ch === endChapter) {
            endVerse = passage.end.v;
            chapters.push({
              'tran':pTranslation,
              'bookRef':bookRef,
              'chapter':ch,
              'verse':{$gte:startVerse, $lte:endVerse}
            });
          }
          else { // other whole chapters in range
            chapters.push({
              'tran':pTranslation,
              'bookRef':bookRef,
              'chapter':ch
            });
          }
        }
      }
    }

    db.collection('bible', function(err, collection) {
      collection.find({
        $or: chapters
      }).toArray(function(err, items) {
        res.jsonp(items);
      });
    });
  }
};

exports.findAll = function(req, res) {
  var translationInfo = bcv.translation_info("");
  var entities = bcv.parse(req.params.passage).entities;

  for (var i=0; i<entities.length; i++) {
    var entity = entities[i];

    // only one verse
    if (entity.type === 'bcv') {
      // bcv has only one passage
      fetchBcv(entity.passages[0], res);
    } // range of verses
    else if (entity.type === 'range') {
      // range has only one passage
      fetchRange(entity.passages[0], res);
    }
    else if(entity.type === 'sequence') {
      for (var j=0; j<entity.passages.length; j++) {
        var passage = entity.passages[j];
        // passage sequence includes bcv
        if (passage.type === 'bcv' || passage.type === 'integer') {
          fetchBcv(passage, res);
        } // passage sequence includes range
        else if(passage.type === 'range') {
          fetchRange(passage, res);
        }
      }
    }
  }
};

exports.findById = function(req, res) {
    console.log(req.params);
    var id = parseInt(req.params.id);
    console.log('findById: ' + id);
    db.collection('employees', function(err, collection) {
        collection.findOne({'id': id}, function(err, item) {
            console.log(item);
            res.jsonp(item);
        });
    });
};

exports.findByManager = function(req, res) {
    var id = parseInt(req.params.id);
    console.log('findByManager: ' + id);
    db.collection('employees', function(err, collection) {
        collection.find({'managerId': id}).toArray(function(err, items) {
            console.log(items);
            res.jsonp(items);
        });
    });
};
<commit_msg>basic queries fixed<commit_after>var bcv_parser = require("./en_bcv_parser.js").bcv_parser;
var bcv = new bcv_parser;

var MongoClient = require('mongodb').MongoClient;
var Server = require('mongodb').Server;
var db;

var mongoClient = new MongoClient(new Server('localhost', 27017));
mongoClient.open(function(err, mongoClient) {
    db = mongoClient.db("bible-api");
    db.collection('bible', {strict:true}, function(err, collection) {
        if (err) {
            console.log("Error!");
        }
    });
});

var mongoQuery = [];

var fetchBcv = function(passage, res) {
  var pTranslation = 'RST';
  if (passage.translations != null) {
    pTranslation = passage.translations[0].osis;
  }
  mongoQuery.push({
    'tran':pTranslation,
    'bookRef':passage.start.b,
    'chapter':passage.start.c,
    'verse':passage.start.v
  });
};

var fetchRange = function(passage) {
  var translationInfo = bcv.translation_info("");

  var pTranslation = 'RST';
  if (passage.translations != null) {
    pTranslation = passage.translations[0].osis;
  }

  // passage of the same book
  if (passage.start.b === passage.end.b) {
    // passage of one chapter
    if (passage.start.c === passage.end.c) {
      mongoQuery.push({
        'tran':pTranslation,
        'bookRef':passage.start.b,
        'chapter':passage.start.c,
        'verse':{$gte:passage.start.v, $lte:passage.end.v}
      });
    }
    else { // passage of many chapters
      var chapters = [];
      for (var ch=passage.start.c; ch<=passage.end.c; ch++) {
        var startVerse = 1;
        var endVerse = translationInfo.chapters[passage.start.b][ch-1];

        if (ch === passage.start.c) {
          startVerse = passage.start.v;
        }
        if (ch === passage.end.c) {
          endVerse = passage.end.v;
        }

        chapters.push({
          'tran':pTranslation,
          'bookRef':passage.start.b,
          'chapter':ch,
          'verse':{$gte:startVerse, $lte:endVerse}
        });
      }

      mongoQuery.push({
        $or: chapters
      });
    }
  } // passage of many books
  else {
    var chapters = [];
    var startBook = translationInfo.order[passage.start.b];
    var endBook = translationInfo.order[passage.end.b];

    for (var b=startBook; b<=endBook; b++) {
      var bookRef = translationInfo.books[b-1];

      // passage includes the whole book in the middle
      if (b != startBook && b != endBook) {
        chapters.push({
          'tran':pTranslation,
          'bookRef':bookRef
        });
      }
      else { // other half-books parts
        var startChapter = 1;
        var endChapter = translationInfo.chapters[bookRef].length;

        if (b === startBook) {
          startChapter = passage.start.c;
        }
        if (b === endBook) {
          endChapter = passage.end.c;
        }

        for (var ch=startChapter; ch<=endChapter; ch++) {
          var startVerse = 1;
          var endVerse = translationInfo.chapters[bookRef][ch-1];

          // first chapter, first verse in range
          if (b === startBook && ch === startChapter) {
            startVerse = passage.start.v;
            chapters.push({
              'tran':pTranslation,
              'bookRef':bookRef,
              'chapter':startChapter,
              'verse':{$gte:startVerse, $lte:endVerse}
            });
          } // last chapter, last verse in range
          else if (b === endBook && ch === endChapter) {
            endVerse = passage.end.v;
            chapters.push({
              'tran':pTranslation,
              'bookRef':bookRef,
              'chapter':ch,
              'verse':{$gte:startVerse, $lte:endVerse}
            });
          }
          else { // other whole chapters in range
            chapters.push({
              'tran':pTranslation,
              'bookRef':bookRef,
              'chapter':ch
            });
          }
        }
      }
    }

    mongoQuery.push({
      $or: chapters
    });
  }
};

exports.findAll = function(req, res) {
  mongoQuery = [];
  var entities = bcv.parse(req.params.passage).entities;

  for (var i=0; i<entities.length; i++) {
    var entity = entities[i];

    // only one verse
    if (entity.type === 'bcv') {
      // bcv has only one passage
      fetchBcv(entity.passages[0]);
    } // range of verses
    else if (entity.type === 'range') {
      // range has only one passage
      fetchRange(entity.passages[0]);
    }
    else if(entity.type === 'sequence') {
      for (var j=0; j<entity.passages.length; j++) {
        var passage = entity.passages[j];
        // passage sequence includes bcv
        if (passage.type === 'bcv' || passage.type === 'integer') {
          fetchBcv(passage);
        } // passage sequence includes range
        else if(passage.type === 'range') {
          fetchRange(passage);
        }
      }
    }
  }

  db.collection('bible', function(err, collection) {
    collection.find({
      $or: mongoQuery
    }).toArray(function(err, items) {
      res.jsonp(items);
    });
  });
};

exports.findById = function(req, res) {
    console.log(req.params);
    var id = parseInt(req.params.id);
    console.log('findById: ' + id);
    db.collection('employees', function(err, collection) {
        collection.findOne({'id': id}, function(err, item) {
            console.log(item);
            res.jsonp(item);
        });
    });
};

exports.findByManager = function(req, res) {
    var id = parseInt(req.params.id);
    console.log('findByManager: ' + id);
    db.collection('employees', function(err, collection) {
        collection.find({'managerId': id}).toArray(function(err, items) {
            console.log(items);
            res.jsonp(items);
        });
    });
};
<|endoftext|>


<commit_before>import React, { Suspense, useEffect, useRef, useState } from 'react';
import PropTypes from 'prop-types';
import LoadMoreButton from 'components/Buttons/LoadMoreButton';
import FilterBar from 'components/FilterBar';
import ContentPanel from 'components/ContentPanel';
import { css } from 'emotion';
import { mobileMaxWidth } from 'constants/css';
import { useInfiniteScroll } from 'helpers/hooks';
import { loadFeeds } from 'helpers/requestHelpers';
import { queryStringForArray } from 'helpers/stringHelpers';
import {
  addTags,
  addTagToContents,
  attachStar,
  changeByUserStatus,
  contentFeedLike,
  feedCommentDelete,
  feedCommentEdit,
  feedContentDelete,
  feedContentEdit,
  feedRewardCommentEdit,
  fetchFeed,
  fetchFeeds,
  fetchMoreFeeds,
  loadMoreFeedComments,
  loadMoreFeedReplies,
  loadRepliesOfReply,
  loadTags,
  setCurrentSection,
  setDifficulty,
  showFeedComments,
  uploadFeedComment,
  uploadTargetContentComment
} from 'redux/actions/FeedActions';
import { connect } from 'react-redux';
import Loading from 'components/Loading';
const SideMenu = React.lazy(() => import('./SideMenu'));

Posts.propTypes = {
  addTags: PropTypes.func.isRequired,
  addTagToContents: PropTypes.func.isRequired,
  attachStar: PropTypes.func.isRequired,
  changeByUserStatus: PropTypes.func.isRequired,
  chatMode: PropTypes.bool.isRequired,
  contentFeedLike: PropTypes.func.isRequired,
  fetchFeed: PropTypes.func.isRequired,
  feedCommentDelete: PropTypes.func.isRequired,
  feedContentDelete: PropTypes.func.isRequired,
  feedCommentEdit: PropTypes.func.isRequired,
  feedContentEdit: PropTypes.func.isRequired,
  feedRewardCommentEdit: PropTypes.func.isRequired,
  fetchFeeds: PropTypes.func.isRequired,
  fetchMoreFeeds: PropTypes.func.isRequired,
  history: PropTypes.object.isRequired,
  loaded: PropTypes.bool.isRequired,
  loadMoreButton: PropTypes.bool.isRequired,
  loadMoreFeedComments: PropTypes.func.isRequired,
  loadMoreFeedReplies: PropTypes.func.isRequired,
  loadRepliesOfReply: PropTypes.func.isRequired,
  loadTags: PropTypes.func.isRequired,
  location: PropTypes.object.isRequired,
  match: PropTypes.object.isRequired,
  myId: PropTypes.number,
  profileFeeds: PropTypes.array.isRequired,
  searchMode: PropTypes.bool.isRequired,
  selectedTheme: PropTypes.string,
  setCurrentSection: PropTypes.func.isRequired,
  setDifficulty: PropTypes.func,
  showFeedComments: PropTypes.func.isRequired,
  uploadTargetContentComment: PropTypes.func.isRequired,
  uploadFeedComment: PropTypes.func.isRequired
};

const filterTable = {
  all: 'all',
  comments: 'comment',
  posts: 'post',
  videos: 'video',
  links: 'url'
};

function Posts({
  addTags,
  addTagToContents,
  attachStar,
  changeByUserStatus,
  chatMode,
  contentFeedLike,
  feedCommentDelete,
  feedContentDelete,
  feedCommentEdit,
  feedContentEdit,
  feedRewardCommentEdit,
  fetchFeed,
  fetchFeeds,
  fetchMoreFeeds,
  history,
  loadMoreFeedComments,
  loadMoreFeedReplies,
  loaded,
  loadMoreButton,
  loadRepliesOfReply,
  loadTags,
  location,
  match,
  match: {
    params: { section, username }
  },
  myId,
  profileFeeds,
  searchMode,
  selectedTheme,
  setCurrentSection,
  showFeedComments,
  uploadFeedComment,
  uploadTargetContentComment,
  setDifficulty
}) {
  const [loading, setLoading] = useState(false);
  const [loadingFeeds, setLoadingFeeds] = useState(false);
  const mounted = useRef(true);
  const selectedFilter = useRef('all');

  const [setScrollHeight] = useInfiniteScroll({
    scrollable: !chatMode && !searchMode && profileFeeds.length > 0,
    loadable: loadMoreButton,
    loading,
    onScrollToBottom: () => setLoading(true),
    onLoad: loadMoreFeeds
  });

  useEffect(() => {
    mounted.current = true;
    setCurrentSection('profileFeeds');
    return function cleanUp() {
      mounted.current = false;
    };
  }, []);

  useEffect(() => {
    if (history.action === 'PUSH' || profileFeeds.length === 0) {
      loadTab(match.params.section);
    }
  }, [location]);

  return !loaded ? (
    <Loading style={{ marginBottom: '50vh' }} text="Loading..." />
  ) : (

      <FilterBar
        color={selectedTheme}
        style={{ height: '5rem' }}
        className="mobile"
      >
        {[
          { key: 'all', label: 'All' },
          { key: 'post', label: 'Subjects' },
          { key: 'video', label: 'Videos' },
          { key: 'url', label: 'Links' }
        ].map(type => {
          return (
             onClickPostsMenu({ item: type.key })}
            >
              {type.label}

          );
        })}
      </FilterBar>

        {loadingFeeds ? (
          <Loading style={{ width: 'CALC(100% - 25rem)' }} text="Loading..." />
        ) : (

            {profileFeeds.length > 0 &&
              profileFeeds.map((feed, index) => {
                return (
                  <ContentPanel
                    key={filterTable[match.params.section] + feed.feedId}
                    style={{
                      marginBottom: '1rem',
                      zIndex: profileFeeds.length - index
                    }}
                    commentsLoadLimit={5}
                    contentObj={feed}
                    inputAtBottom={feed.type === 'comment'}
                    onInitContent={fetchFeed}
                    onAddTags={addTags}
                    onAddTagToContents={addTagToContents}
                    onAttachStar={attachStar}
                    onByUserStatusChange={changeByUserStatus}
                    onCommentSubmit={data =>
                      handleUploadFeedComment({ feed, data })
                    }
                    onDeleteComment={feedCommentDelete}
                    onDeleteContent={feedContentDelete}
                    onEditComment={feedCommentEdit}
                    onEditContent={feedContentEdit}
                    onEditRewardComment={feedRewardCommentEdit}
                    onLikeContent={contentFeedLike}
                    onLoadMoreComments={loadMoreFeedComments}
                    onLoadMoreReplies={loadMoreFeedReplies}
                    onLoadRepliesOfReply={loadRepliesOfReply}
                    onLoadTags={loadTags}
                    onReplySubmit={data =>
                      handleUploadFeedComment({ feed, data })
                    }
                    onSetDifficulty={setDifficulty}
                    onShowComments={showFeedComments}
                    onTargetCommentSubmit={uploadTargetContentComment}
                    userId={myId}
                  />
                );
              })}
            {profileFeeds.length === 0 && (

{onNoFeed(username)}

            )}
            {loadMoreButton && (
              <LoadMoreButton
                style={{ marginBottom: '1rem' }}
                onClick={loadMoreFeeds}
                loading={loading}
                color="lightBlue"
                filled
              />
            )}

        )}
        <Suspense fallback={<Loading />}>
          <SideMenu
            className={`desktop ${css`
              width: 30rem;
            `}`}
            menuItems={[
              { key: 'all', label: 'All' },
              { key: 'comment', label: 'Comments' },
              { key: 'post', label: 'Subjects' },
              { key: 'video', label: 'Videos' },
              { key: 'url', label: 'Links' }
            ]}
            onMenuClick={onClickPostsMenu}
            selectedKey={filterTable[match.params.section]}
          />
        </Suspense>

  );

  async function loadMoreFeeds() {
    try {
      await fetchMoreFeeds({
        shownFeeds: queryStringForArray({
          array: profileFeeds,
          originVar: 'feedId',
          destinationVar: 'shownFeeds'
        }),
        filter: filterTable[section],
        username
      });
      if (mounted.current) {
        setLoading(false);
      }
    } catch (error) {
      console.error(error);
    }
  }

  async function loadTab(tabName) {
    selectedFilter.current = filterTable[tabName];
    setLoadingFeeds(true);
    const { data, filter: loadedFilter } = await loadFeeds({
      username,
      filter: filterTable[tabName]
    });
    if (loadedFilter === selectedFilter.current) {
      fetchFeeds(data);
      setScrollHeight(0);
      setLoadingFeeds(false);
    }
  }

  function onClickPostsMenu({ item }) {
    history.push(
      `/users/${username}/${item === 'url' ? 'link' : item}${
        item === 'all' ? '' : 's'
      }`
    );
  }

  function onNoFeed(username) {
    switch (match.params.section) {
      case 'all':
        return `${username} has not uploaded anything, yet`;
      case 'posts':
        return `${username} has not uploaded a post, yet`;
      case 'comments':
        return `${username} has not uploaded a comment, yet`;
      case 'links':
        return `${username} has not uploaded a link, yet`;
      case 'videos':
        return `${username} has not uploaded a video, yet`;
    }
  }

  function handleUploadFeedComment({ feed, data }) {
    uploadFeedComment({
      data,
      type: feed.type,
      contentId: feed.contentId
    });
  }
}

export default connect(
  state => ({
    chatMode: state.ChatReducer.chatMode,
    profileFeeds: state.FeedReducer.profileFeeds,
    loaded: state.FeedReducer.loaded,
    myId: state.UserReducer.userId,
    loadMoreButton: state.FeedReducer.profileFeedsLoadMoreButton,
    homeComponentConnected: state.FeedReducer.homeComponentConnected,
    searchMode: state.SearchReducer.searchMode
  }),
  {
    addTags,
    addTagToContents,
    attachStar,
    changeByUserStatus,
    contentFeedLike,
    fetchFeed,
    fetchFeeds,
    fetchMoreFeeds,
    feedCommentDelete,
    feedContentDelete,
    feedCommentEdit,
    feedContentEdit,
    feedRewardCommentEdit,
    loadMoreFeedComments,
    loadMoreFeedReplies,
    loadRepliesOfReply,
    loadTags,
    setCurrentSection,
    setDifficulty,
    showFeedComments,
    uploadFeedComment,
    uploadTargetContentComment
  }
)(Posts);
<commit_msg>remove unnecessary lazy load<commit_after>import React, { Suspense, useEffect, useRef, useState } from 'react';
import PropTypes from 'prop-types';
import LoadMoreButton from 'components/Buttons/LoadMoreButton';
import FilterBar from 'components/FilterBar';
import ContentPanel from 'components/ContentPanel';
import { css } from 'emotion';
import { mobileMaxWidth } from 'constants/css';
import { useInfiniteScroll } from 'helpers/hooks';
import { loadFeeds } from 'helpers/requestHelpers';
import { queryStringForArray } from 'helpers/stringHelpers';
import {
  addTags,
  addTagToContents,
  attachStar,
  changeByUserStatus,
  contentFeedLike,
  feedCommentDelete,
  feedCommentEdit,
  feedContentDelete,
  feedContentEdit,
  feedRewardCommentEdit,
  fetchFeed,
  fetchFeeds,
  fetchMoreFeeds,
  loadMoreFeedComments,
  loadMoreFeedReplies,
  loadRepliesOfReply,
  loadTags,
  setCurrentSection,
  setDifficulty,
  showFeedComments,
  uploadFeedComment,
  uploadTargetContentComment
} from 'redux/actions/FeedActions';
import { connect } from 'react-redux';
import Loading from 'components/Loading';
import SideMenu from './SideMenu';

Posts.propTypes = {
  addTags: PropTypes.func.isRequired,
  addTagToContents: PropTypes.func.isRequired,
  attachStar: PropTypes.func.isRequired,
  changeByUserStatus: PropTypes.func.isRequired,
  chatMode: PropTypes.bool.isRequired,
  contentFeedLike: PropTypes.func.isRequired,
  fetchFeed: PropTypes.func.isRequired,
  feedCommentDelete: PropTypes.func.isRequired,
  feedContentDelete: PropTypes.func.isRequired,
  feedCommentEdit: PropTypes.func.isRequired,
  feedContentEdit: PropTypes.func.isRequired,
  feedRewardCommentEdit: PropTypes.func.isRequired,
  fetchFeeds: PropTypes.func.isRequired,
  fetchMoreFeeds: PropTypes.func.isRequired,
  history: PropTypes.object.isRequired,
  loaded: PropTypes.bool.isRequired,
  loadMoreButton: PropTypes.bool.isRequired,
  loadMoreFeedComments: PropTypes.func.isRequired,
  loadMoreFeedReplies: PropTypes.func.isRequired,
  loadRepliesOfReply: PropTypes.func.isRequired,
  loadTags: PropTypes.func.isRequired,
  location: PropTypes.object.isRequired,
  match: PropTypes.object.isRequired,
  myId: PropTypes.number,
  profileFeeds: PropTypes.array.isRequired,
  searchMode: PropTypes.bool.isRequired,
  selectedTheme: PropTypes.string,
  setCurrentSection: PropTypes.func.isRequired,
  setDifficulty: PropTypes.func,
  showFeedComments: PropTypes.func.isRequired,
  uploadTargetContentComment: PropTypes.func.isRequired,
  uploadFeedComment: PropTypes.func.isRequired
};

const filterTable = {
  all: 'all',
  comments: 'comment',
  posts: 'post',
  videos: 'video',
  links: 'url'
};

function Posts({
  addTags,
  addTagToContents,
  attachStar,
  changeByUserStatus,
  chatMode,
  contentFeedLike,
  feedCommentDelete,
  feedContentDelete,
  feedCommentEdit,
  feedContentEdit,
  feedRewardCommentEdit,
  fetchFeed,
  fetchFeeds,
  fetchMoreFeeds,
  history,
  loadMoreFeedComments,
  loadMoreFeedReplies,
  loaded,
  loadMoreButton,
  loadRepliesOfReply,
  loadTags,
  location,
  match,
  match: {
    params: { section, username }
  },
  myId,
  profileFeeds,
  searchMode,
  selectedTheme,
  setCurrentSection,
  showFeedComments,
  uploadFeedComment,
  uploadTargetContentComment,
  setDifficulty
}) {
  const [loading, setLoading] = useState(false);
  const [loadingFeeds, setLoadingFeeds] = useState(false);
  const mounted = useRef(true);
  const selectedFilter = useRef('all');

  const [setScrollHeight] = useInfiniteScroll({
    scrollable: !chatMode && !searchMode && profileFeeds.length > 0,
    loadable: loadMoreButton,
    loading,
    onScrollToBottom: () => setLoading(true),
    onLoad: loadMoreFeeds
  });

  useEffect(() => {
    mounted.current = true;
    setCurrentSection('profileFeeds');
    return function cleanUp() {
      mounted.current = false;
    };
  }, []);

  useEffect(() => {
    if (history.action === 'PUSH' || profileFeeds.length === 0) {
      loadTab(match.params.section);
    }
  }, [location]);

  return !loaded ? (
    <Loading style={{ marginBottom: '50vh' }} text="Loading..." />
  ) : (

      <FilterBar
        color={selectedTheme}
        style={{ height: '5rem' }}
        className="mobile"
      >
        {[
          { key: 'all', label: 'All' },
          { key: 'post', label: 'Subjects' },
          { key: 'video', label: 'Videos' },
          { key: 'url', label: 'Links' }
        ].map(type => {
          return (
             onClickPostsMenu({ item: type.key })}
            >
              {type.label}

          );
        })}
      </FilterBar>

        {loadingFeeds ? (
          <Loading style={{ width: 'CALC(100% - 25rem)' }} text="Loading..." />
        ) : (

            {profileFeeds.length > 0 &&
              profileFeeds.map((feed, index) => {
                return (
                  <ContentPanel
                    key={filterTable[match.params.section] + feed.feedId}
                    style={{
                      marginBottom: '1rem',
                      zIndex: profileFeeds.length - index
                    }}
                    commentsLoadLimit={5}
                    contentObj={feed}
                    inputAtBottom={feed.type === 'comment'}
                    onInitContent={fetchFeed}
                    onAddTags={addTags}
                    onAddTagToContents={addTagToContents}
                    onAttachStar={attachStar}
                    onByUserStatusChange={changeByUserStatus}
                    onCommentSubmit={data =>
                      handleUploadFeedComment({ feed, data })
                    }
                    onDeleteComment={feedCommentDelete}
                    onDeleteContent={feedContentDelete}
                    onEditComment={feedCommentEdit}
                    onEditContent={feedContentEdit}
                    onEditRewardComment={feedRewardCommentEdit}
                    onLikeContent={contentFeedLike}
                    onLoadMoreComments={loadMoreFeedComments}
                    onLoadMoreReplies={loadMoreFeedReplies}
                    onLoadRepliesOfReply={loadRepliesOfReply}
                    onLoadTags={loadTags}
                    onReplySubmit={data =>
                      handleUploadFeedComment({ feed, data })
                    }
                    onSetDifficulty={setDifficulty}
                    onShowComments={showFeedComments}
                    onTargetCommentSubmit={uploadTargetContentComment}
                    userId={myId}
                  />
                );
              })}
            {profileFeeds.length === 0 && (

{onNoFeed(username)}

            )}
            {loadMoreButton && (
              <LoadMoreButton
                style={{ marginBottom: '1rem' }}
                onClick={loadMoreFeeds}
                loading={loading}
                color="lightBlue"
                filled
              />
            )}

        )}
        <Suspense fallback={<Loading />}>
          <SideMenu
            className={`desktop ${css`
              width: 30rem;
            `}`}
            menuItems={[
              { key: 'all', label: 'All' },
              { key: 'comment', label: 'Comments' },
              { key: 'post', label: 'Subjects' },
              { key: 'video', label: 'Videos' },
              { key: 'url', label: 'Links' }
            ]}
            onMenuClick={onClickPostsMenu}
            selectedKey={filterTable[match.params.section]}
          />
        </Suspense>

  );

  async function loadMoreFeeds() {
    try {
      await fetchMoreFeeds({
        shownFeeds: queryStringForArray({
          array: profileFeeds,
          originVar: 'feedId',
          destinationVar: 'shownFeeds'
        }),
        filter: filterTable[section],
        username
      });
      if (mounted.current) {
        setLoading(false);
      }
    } catch (error) {
      console.error(error);
    }
  }

  async function loadTab(tabName) {
    selectedFilter.current = filterTable[tabName];
    setLoadingFeeds(true);
    const { data, filter: loadedFilter } = await loadFeeds({
      username,
      filter: filterTable[tabName]
    });
    if (loadedFilter === selectedFilter.current) {
      fetchFeeds(data);
      setScrollHeight(0);
      setLoadingFeeds(false);
    }
  }

  function onClickPostsMenu({ item }) {
    history.push(
      `/users/${username}/${item === 'url' ? 'link' : item}${
        item === 'all' ? '' : 's'
      }`
    );
  }

  function onNoFeed(username) {
    switch (match.params.section) {
      case 'all':
        return `${username} has not uploaded anything, yet`;
      case 'posts':
        return `${username} has not uploaded a post, yet`;
      case 'comments':
        return `${username} has not uploaded a comment, yet`;
      case 'links':
        return `${username} has not uploaded a link, yet`;
      case 'videos':
        return `${username} has not uploaded a video, yet`;
    }
  }

  function handleUploadFeedComment({ feed, data }) {
    uploadFeedComment({
      data,
      type: feed.type,
      contentId: feed.contentId
    });
  }
}

export default connect(
  state => ({
    chatMode: state.ChatReducer.chatMode,
    profileFeeds: state.FeedReducer.profileFeeds,
    loaded: state.FeedReducer.loaded,
    myId: state.UserReducer.userId,
    loadMoreButton: state.FeedReducer.profileFeedsLoadMoreButton,
    homeComponentConnected: state.FeedReducer.homeComponentConnected,
    searchMode: state.SearchReducer.searchMode
  }),
  {
    addTags,
    addTagToContents,
    attachStar,
    changeByUserStatus,
    contentFeedLike,
    fetchFeed,
    fetchFeeds,
    fetchMoreFeeds,
    feedCommentDelete,
    feedContentDelete,
    feedCommentEdit,
    feedContentEdit,
    feedRewardCommentEdit,
    loadMoreFeedComments,
    loadMoreFeedReplies,
    loadRepliesOfReply,
    loadTags,
    setCurrentSection,
    setDifficulty,
    showFeedComments,
    uploadFeedComment,
    uploadTargetContentComment
  }
)(Posts);
<|endoftext|>


<commit_before>/**
 * Created by truthlighting on 9/14/2016.
 */
var roleHauler = {

    /** @param {Creep} creep **/

    run: function(creep) {

        var energyStorageStructures = creep.room.find(FIND_STRUCTURES, {
                    filter: (structure) => {
                        return (structure.structureType == STRUCTURE_EXTENSION ||
                        structure.structureType == STRUCTURE_SPAWN) &&
                        (structure.energy < structure.energyCapacity);
                    }
        })
        //energyStorageStructure = _.head(energyStorageStructures.sortBy('energy'));
        //console.log(energyStorageStructure);
        var towers = creep.room.find(FIND_STRUCTURES, {
                    filter: (structure) => {
                    return (structure.structureType == STRUCTURE_TOWER) &&
                        (structure.energy < structure.energyCapacity);
                    }
        })
        if (energyStorageStructures.length == 0) {
            var notEmptyContainers = creep.room.find(FIND_STRUCTURES, {
                    filter: (structure) => structure.structureType == STRUCTURE_CONTAINER &&
                    structure.store[RESOURCE_ENERGY] > 0
            })
        } else {
            var notEmptyContainers = creep.room.find(FIND_STRUCTURES, {
                    filter: (structure) => {
                        return (structure.structureType == STRUCTURE_CONTAINER ||
                                structure.structureType == STRUCTURE_STORAGE) &&
                                structure.store[RESOURCE_ENERGY] > 0
                    }
            })
        }
        var notFullStoragePlaces = creep.room.find(FIND_STRUCTURES, {
                    filter: (structure) => structure.structureType == STRUCTURE_STORAGE &&
                                           _.sum(structure.store) < structure.storeCapacity

        })

        if(creep.memory.transporting && creep.carry.energy == 0 || (notEmptyContainers.length > 0 && creep.memory.idling == true)) {
            creep.memory.transporting = false;
            creep.memory.idling = false;
            creep.say("C-Travelling");
        } else if (!creep.memory.transporting && creep.carry.energy == creep.carryCapacity || ((creep.pos.findClosestByPath(notFullStoragePlaces)) && creep.carry.energy > 0)) {
            creep.memory.transporting = true;
            creep.memory.idling = false;
            creep.say("C-Xporting");
        } else if (notEmptyContainers.length == 0) {
            creep.memory.idling = true;
            creep.say("C-Idling")
        }

        if (creep.memory.transporting) {
            if (energyStorageStructures.length > 0) {
                var energyStorageStructure = creep.pos.findClosestByPath(energyStorageStructures);
                if (creep.transfer(energyStorageStructure, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                    creep.moveTo(energyStorageStructure);
                }
            } else if (towers.length > 0) {
                var tower = creep.pos.findClosestByPath(towers);
                if (creep.transfer(tower, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                    creep.moveTo(tower);
                }
            } else if (notFullStoragePlaces.length > 0) {
                var notFullStorage = creep.pos.findClosestByPath(notFullStoragePlaces);
                if (creep.transfer(notFullStorage, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                    creep.moveTo(notFullStorage);
                }
            }
        } else if (!creep.memory.idling) {
            if(notEmptyContainers.length > 0) {
                var notEmptyContainer = _.head(_.sortBy(notEmptyContainers, ('energy')));
                console.log(notEmptyContainer);
                //var notEmptyContainer = creep.pos.findClosestByPath(notEmptyContainers);
                if (creep.withdraw(notEmptyContainer, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                    creep.moveTo(notEmptyContainer);
                }
            }
        } else {
            //idle
            var targetFlag = creep.pos.findClosestByPath([Game.flags.Flag1,Game.flags.Flag2]);
            creep.moveTo(targetFlag);
        }
    }
};

module.exports = roleHauler;<commit_msg>cleaning hauler<commit_after>/**
 * Created by truthlighting on 9/14/2016.
 */
var roleHauler = {

    /** @param {Creep} creep **/

    run: function(creep) {

        var energyStorageStructures = creep.room.find(FIND_STRUCTURES, {
                    filter: (structure) => {
                        return (structure.structureType == STRUCTURE_EXTENSION ||
                        structure.structureType == STRUCTURE_SPAWN) &&
                        (structure.energy < structure.energyCapacity);
                    }
        })
        //energyStorageStructure = _.head(energyStorageStructures.sortBy('energy'));
        //console.log(energyStorageStructure);
        var towers = creep.room.find(FIND_STRUCTURES, {
                    filter: (structure) => {
                    return (structure.structureType == STRUCTURE_TOWER) &&
                        (structure.energy < structure.energyCapacity);
                    }
        })
        if (energyStorageStructures.length == 0) {
            var notEmptyContainers = creep.room.find(FIND_STRUCTURES, {
                    filter: (structure) => structure.structureType == STRUCTURE_CONTAINER &&
                    structure.store[RESOURCE_ENERGY] > 0
            })
        } else {
            var notEmptyContainers = creep.room.find(FIND_STRUCTURES, {
                    filter: (structure) => {
                        return (structure.structureType == STRUCTURE_CONTAINER ||
                                structure.structureType == STRUCTURE_STORAGE) &&
                                structure.store[RESOURCE_ENERGY] > 0
                    }
            })
        }
        var notFullStoragePlaces = creep.room.find(FIND_STRUCTURES, {
                    filter: (structure) => structure.structureType == STRUCTURE_STORAGE &&
                                           _.sum(structure.store) < structure.storeCapacity

        })

        if(creep.memory.transporting && creep.carry.energy == 0 || (notEmptyContainers.length > 0 && creep.memory.idling == true)) {
            creep.memory.transporting = false;
            creep.memory.idling = false;
            creep.say("C-Travelling");
        } else if (!creep.memory.transporting && creep.carry.energy == creep.carryCapacity || ((creep.pos.findClosestByPath(notFullStoragePlaces)) && creep.carry.energy > 0)) {
            creep.memory.transporting = true;
            creep.memory.idling = false;
            creep.say("C-Xporting");
        } else if (notEmptyContainers.length == 0) {
            creep.memory.idling = true;
            creep.say("C-Idling")
        }

        if (creep.memory.transporting) {
            if (energyStorageStructures.length > 0) {
                var energyStorageStructure = creep.pos.findClosestByPath(energyStorageStructures);
                if (creep.transfer(energyStorageStructure, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                    creep.moveTo(energyStorageStructure);
                }
            } else if (towers.length > 0) {
                var tower = creep.pos.findClosestByPath(towers);
                if (creep.transfer(tower, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                    creep.moveTo(tower);
                }
            } else if (notFullStoragePlaces.length > 0) {
                var notFullStorage = creep.pos.findClosestByPath(notFullStoragePlaces);
                if (creep.transfer(notFullStorage, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                    creep.moveTo(notFullStorage);
                }
            }
        } else if (!creep.memory.idling) {
            if(notEmptyContainers.length > 0) {
                var notEmptyContainer = _.head(_.sortBy(notEmptyContainers, ('energy')));
                //console.log(notEmptyContainer);
                //var notEmptyContainer = creep.pos.findClosestByPath(notEmptyContainers);
                if (creep.withdraw(notEmptyContainer, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                    creep.moveTo(notEmptyContainer);
                }
            }
        } else {
            //idle
            var targetFlag = creep.pos.findClosestByPath([Game.flags.Flag1,Game.flags.Flag2]);
            creep.moveTo(targetFlag);
        }
    }
};

module.exports = roleHauler;<|endoftext|>


<commit_before>var http = require('https'),
    app = {}

<commit_msg>Added the code<commit_after>var http = require('https')

module.exports = {
    create:     function( callback ) { talk( 'POST', 'bins', callback ) },
    get:        function( bin, callback ) { talk( 'GET', 'bins/'+ bin, callback ) },
    requests:   function( bin, callback ) { talk( 'GET', 'bins/'+ bin +'/requests', callback ) },
    request:    function( bin, request, callback ) { talk( 'GET', 'bins/'+ bin +'/requests/'+ request, callback ) }
}

function talk( method, path, callback ) {
    var options = {
        host:   'requestb.in',
        path:   '/'+ path,
        method: method
    }

    var req = http.request( options )

    req.on( 'response', function( res ) {
        var data = ''
        res.on( 'data', function( ch ) { data += ch })
        res.on( 'close', function() { callback( new Error('disconnected') ) })
        res.on( 'end', function() {
            data = data.toString('utf8').trim()
            if( response.statusCode >= 300 ) {
                var err = new Error('HTTP error')
                err.request = options
                err.response = {
                    headers: res.headers,
                    body: data
                }
                callback( err )
            } else if( !data.match( /^(\{.*\}|\[.*\])$/ ) ) {
                var err = new Error('invalid response')
                err.request = options
                err.response = {
                    headers: res.headers,
                    body: data
                }
                callback( err )
            } else {
                data = JSON.parse( data )
                callback( null, data )
            }
        })
    })

    req.on( 'error', function( error ) {
        var err = new Error('request failed')
        err/details = error
        callback( err )
    })

    req.end()
}
<|endoftext|>


<commit_before>
export default function lazyLoader (images: NodeList<HTMLElement>): void {
  const callback = function(entries, observer) {
    for (let entry of entries) {
      if (entry.isIntersecting && !entry.target.src) {
        let target = entry.target
        target.setAttribute('src', target.getAttribute('data-src'))
      }
    }
  }
  const options: IntersectionObserverInit = {
    root: null,
    rootMargin: '200px'
  }
  const observer: IntersectionObserver = new IntersectionObserver(callback, options)

  images.forEach(el => observer.observe(el))
}
<commit_msg>feat: Remove style after image loaded<commit_after>
export default function lazyLoader (images: NodeList<HTMLElement>): void {
  const callback = function(entries, observer) {
    for (let entry of entries) {
      if (entry.isIntersecting && !entry.target.src) {
        let target = entry.target
        target.setAttribute('src', target.getAttribute('data-src'))
        target.addEventListener('load', () => {
          target.removeAttribute('style')
        })
      }
    }
  }
  const options: IntersectionObserverInit = {
    root: null,
    rootMargin: '200px'
  }
  const observer: IntersectionObserver = new IntersectionObserver(callback, options)

  images.forEach(el => observer.observe(el))
}
<|endoftext|>


<commit_before>var s = require('shared');

var getTarget = function getTarget(creep) {
    let target;
    let targets = [];

    targets = creep.room.find(FIND_HOSTILE_CREEPS);
    if (targets.length === 0) {
        targets = creep.room.find(FIND_HOSTILE_STRUCTURES, {filter: (str) => str.structureType == STRUCTURE_TOWER});
    }
    target = creep.pos.findClosestByRange(targets);
    return target;
}

var raider = {
    run: function(creep, stageC) {
        var err = OK;
        var m = creep.memory;
        var target;
        var destination = new RoomPosition(22, 32, Memory.attack);
        var path = {visualizePathStyle: {stroke: '#ff3322', opacity: 1.0}};
        if (creep.room.name == Memory.attack) {
            //creep.moveTo(creep.room.controller);
            //err = creep.signController(creep.room.controller, 'Kilroy was here.');
            target = getTarget(creep);
            creep.moveTo(target, path);
            err = creep.attack(target);
        } else {
            err = creep.moveTo(destination, path);
        }

        switch (err) {
            case ERR_FULL:
            case ERR_NOT_ENOUGH_ENERGY:
        //    case ERR_NOT_ENOUGH_RESOURCES:
            case ERR_TIRED:
            case OK:
                break;
            case ERR_NOT_IN_RANGE:
                break;
            default:
                s.creepErr(creep, err);
            break;
        }
        return OK;
    }
};

module.exports = raider;<commit_msg>lint.<commit_after>var s = require('shared');

var getTarget = function getTarget(creep) {
    let target;
    let targets = [];

    targets = creep.room.find(FIND_HOSTILE_CREEPS);
    if (targets.length === 0) {
        targets = creep.room.find(FIND_HOSTILE_STRUCTURES, {filter: (str) => str.structureType == STRUCTURE_TOWER});
    }
    target = creep.pos.findClosestByRange(targets);
    return target;
};

var raider = {
    run: function(creep, stageC) {
        var err = OK;
        var m = creep.memory;
        var target;
        var destination = new RoomPosition(22, 32, Memory.attack);
        var path = {visualizePathStyle: {stroke: '#ff3322', opacity: 1.0}};
        if (creep.room.name == Memory.attack) {
            //creep.moveTo(creep.room.controller);
            //err = creep.signController(creep.room.controller, 'Kilroy was here.');
            target = getTarget(creep);
            creep.moveTo(target, path);
            err = creep.attack(target);
        } else {
            err = creep.moveTo(destination, path);
        }

        switch (err) {
            case ERR_FULL:
            case ERR_NOT_ENOUGH_ENERGY:
        //    case ERR_NOT_ENOUGH_RESOURCES:
            case ERR_TIRED:
            case OK:
                break;
            case ERR_NOT_IN_RANGE:
                break;
            default:
                s.creepErr(creep, err);
            break;
        }
        return OK;
    }
};

module.exports = raider;<|endoftext|>