<commit_before>// Part of <http://miracle.systems/p/h5.modbus> licensed under <MIT>

'use strict';

const buffers = require('h5.buffers');
const helpers = require('../helpers');
const FunctionCode = require('../FunctionCode');
const Response = require('../Response');

/**
 * The read discrete inputs response (code 0x02).
 *
 * A binary representation of the this response varies in length and consists of:
 *
 *   - a function code (1 byte),
 *   - a byte count `n` (1 byte),
 *   - coil states (`n` bytes).
 */
class ReadDiscreteInputsResponse extends Response
{
  /**
   * @param {Array<boolean>} states States of the inputs. An array of 1 to 2000 truthy or falsy elements.
   * @throws {Error} If the `states` array is empty or has more than 2000 elements.
   */
  constructor(states)
  {
    super(FunctionCode.ReadDiscreteInputs);

    if (states.length === 0 || states.length > 2000)
    {
      throw new Error(`Invalid states array. Expected length between 1 and 2000, got [${states.length}].`);
    }

    /**
     * States of the inputs. An array of 1 to 2000 truthy or falsy elements.
     *
     * @readonly
     * @type {Array<boolean>}
     */
    this.states = states;

    /**
     * A number of inputs.
     *
     * @readonly
     * @type {number}
     */
    this.quantity = states.length;
  }

  /**
   * Creates a new response from the specified `options`.
   *
   * @param {Object} options
   * @param {Array<boolean>} options.states An array of input states. Must have between 1 and 2000 elements.
   * @returns {ReadDiscreteInputsResponse}
   * @throws {Error} If any of the specified `options` are invalid.
   */
  static fromOptions(options)
  {
    return new ReadDiscreteInputsResponse(options.states);
  }

  /**
   * Creates a new response from its binary representation.
   *
   * @param {Buffer} buffer A binary representation of this response.
   * @returns {ReadDiscreteInputsResponse}
   * @throws {Error} If the specified `buffer` is not a valid binary representation of this response.
   */
  static fromBuffer(buffer)
  {
    helpers.assertFunctionCode(buffer[0], FunctionCode.ReadDiscreteInputs);

    const states = helpers.toBitArray(buffer, 2, buffer[1] * 8);

    return new ReadDiscreteInputsResponse(states);
  }

  /**
   * Returns a binary representation of this response.
   *
   * @returns {Buffer}
   */
  toBuffer()
  {
    return new buffers.BufferBuilder()
      .pushByte(this.functionCode)
      .pushByte(Math.ceil(this.states.length / 8))
      .pushBits(this.states)
      .toBuffer();
  }

  /**
   * Returns a string representation of this response.
   *
   * @returns {string}
   */
  toString()
  {
    return helpers.formatResponse(this, `${this.quantity} inputs: ${this.states.map(Number).join(', ')}`);
  }

  /**
   * Determines whether a input at the specified `offset` is on (i.e. has a truthy values).
   *
   * @param {number} offset
   * @returns {boolean}
   * @throws {Error} If the specified `offset` is out of bounds.
   */
  isOn(offset)
  {
    if (offset < 0 || offset >= this.quantity)
    {
      throw new RangeError(`Offset out of bounds: ${offset}`);
    }

    return !!this.states[offset];
  }

  /**
   * Determines whether a input at the specified `offset` is off (i.e. has a falsy values).
   *
   * @param {number} offset
   * @returns {boolean}
   * @throws {Error} If the specified `offset` is out of bounds.
   */
  isOff(offset)
  {
    if (offset < 0 || offset >= this.quantity)
    {
      throw new RangeError(`Offset out of bounds: ${offset}`);
    }

    return !this.states[offset];
  }
}

module.exports = ReadDiscreteInputsResponse;
<commit_msg>ReadDiscreteInputsResponse: changed the `quantity` field to property.<commit_after>// Part of <http://miracle.systems/p/h5.modbus> licensed under <MIT>

'use strict';

const buffers = require('h5.buffers');
const helpers = require('../helpers');
const FunctionCode = require('../FunctionCode');
const Response = require('../Response');

/**
 * The read discrete inputs response (code 0x02).
 *
 * A binary representation of the this response varies in length and consists of:
 *
 *   - a function code (1 byte),
 *   - a byte count `n` (1 byte),
 *   - coil states (`n` bytes).
 */
class ReadDiscreteInputsResponse extends Response
{
  /**
   * @param {Array<boolean>} states States of the inputs. An array of 1 to 2000 truthy or falsy elements.
   * @throws {Error} If the `states` array is empty or has more than 2000 elements.
   */
  constructor(states)
  {
    super(FunctionCode.ReadDiscreteInputs);

    if (states.length === 0 || states.length > 2000)
    {
      throw new Error(`Invalid states array. Expected length between 1 and 2000, got [${states.length}].`);
    }

    /**
     * States of the inputs. An array of 1 to 2000 truthy or falsy elements.
     *
     * @readonly
     * @type {Array<boolean>}
     */
    this.states = states;
  }

  /**
   * Creates a new response from the specified `options`.
   *
   * @param {Object} options
   * @param {Array<boolean>} options.states An array of input states. Must have between 1 and 2000 elements.
   * @returns {ReadDiscreteInputsResponse}
   * @throws {Error} If any of the specified `options` are invalid.
   */
  static fromOptions(options)
  {
    return new ReadDiscreteInputsResponse(options.states);
  }

  /**
   * Creates a new response from its binary representation.
   *
   * @param {Buffer} buffer A binary representation of this response.
   * @returns {ReadDiscreteInputsResponse}
   * @throws {Error} If the specified `buffer` is not a valid binary representation of this response.
   */
  static fromBuffer(buffer)
  {
    helpers.assertFunctionCode(buffer[0], FunctionCode.ReadDiscreteInputs);

    const states = helpers.toBitArray(buffer, 2, buffer[1] * 8);

    return new ReadDiscreteInputsResponse(states);
  }

  /**
   * A number of inputs.
   *
   * @type {number}
   */
  get quantity()
  {
    return this.states.length;
  }

  /**
   * Returns a binary representation of this response.
   *
   * @returns {Buffer}
   */
  toBuffer()
  {
    return new buffers.BufferBuilder()
      .pushByte(this.functionCode)
      .pushByte(Math.ceil(this.states.length / 8))
      .pushBits(this.states)
      .toBuffer();
  }

  /**
   * Returns a string representation of this response.
   *
   * @returns {string}
   */
  toString()
  {
    return helpers.formatResponse(this, `${this.quantity} inputs: ${this.states.map(Number).join(', ')}`);
  }

  /**
   * Determines whether a input at the specified `offset` is on (i.e. has a truthy values).
   *
   * @param {number} offset
   * @returns {boolean}
   * @throws {Error} If the specified `offset` is out of bounds.
   */
  isOn(offset)
  {
    if (offset < 0 || offset >= this.quantity)
    {
      throw new RangeError(`Offset out of bounds: ${offset}`);
    }

    return !!this.states[offset];
  }

  /**
   * Determines whether a input at the specified `offset` is off (i.e. has a falsy values).
   *
   * @param {number} offset
   * @returns {boolean}
   * @throws {Error} If the specified `offset` is out of bounds.
   */
  isOff(offset)
  {
    if (offset < 0 || offset >= this.quantity)
    {
      throw new RangeError(`Offset out of bounds: ${offset}`);
    }

    return !this.states[offset];
  }
}

module.exports = ReadDiscreteInputsResponse;
<|endoftext|>


<commit_before><commit_msg>Added a reset to the timeline selection after the window size or the orientation changed.<commit_after><|endoftext|>


<commit_before>var child = require('child_process');
var path = require('path');
var os = require('os');
var fs = require('fs');
var Heroku = require('heroku-client');
var request = require('request');
var agent = require('superagent');
var cli = require('heroku-cli-util');
var _ = require('lodash');
var ProgressBar = require('progress');

var directory = require('../lib/directory');
var docker = require('../lib/docker');
var safely = require('../lib/safely');

const ADDONS = require('../lib/addons');

module.exports = function(topic) {
  return {
    topic: topic,
    command: 'release',
    description: 'create and release slug to app',
    help: 'Create slug tarball from Docker image and release it to Heroku app',
    needsApp: true,
    needsAuth: true,
    run: safely(release)
  };
};

function release(context) {
  var procfile = directory.readProcfile(context.cwd);
  var mountDir = directory.determineMountDir(context.cwd);
  var modifiedProc = _.mapValues(procfile, prependMountDir(mountDir));
  var heroku = context.heroku || new Heroku({ token: context.auth.password });
  var app = context.heroku ? context.app : heroku.apps(context.app);
  var appJSONLocation = path.join(context.cwd, 'app.json');
  var appJSON = JSON.parse(fs.readFileSync(appJSONLocation, { encoding: 'utf8' }));

  request = context.request || request;

  if (!procfile) throw new Error('Procfile required. Aborting');

  return app.info()
    .then(readRemoteAddons)
    .then(compareLocalAddons)
    .then(addMissingAddons)
    .then(createLocalSlug)
    .then(createRemoteSlug)
    .then(uploadSlug)
    .then(releaseSlug)
    .then(showMessage);

  function prependMountDir(mountDir) {
    return function(cmd) {
      return `cd ${ mountDir } && ${ cmd }`
    }
  }

  function readRemoteAddons() {
    return app.addons().list();
  }

  function compareLocalAddons(remoteAddons) {
    var remoteNames = _.map(remoteAddons, getServiceName);
    var localNames = appJSON.addons || [];
    var missingAddons = _.filter(localNames, isMissingFrom.bind(this, remoteNames));

    console.log(`Remote addons: ${ remoteNames.join(', ')} (${ remoteNames.length })`);
    console.log(`Local addons: ${ localNames.join(', ') } (${ localNames.length })`);
    console.log(`Missing addons: ${ missingAddons.join(', ') } (${ missingAddons.length })`);

    return Promise.resolve(missingAddons);

    function getServiceName(addon) {
      return addon.addon_service.name;
    }

    function isMissingFrom(list, addon) {
      var name = addon.split(':')[0];
      return list.indexOf(name) === -1;
    }
  }

  function addMissingAddons(addons) {
    return Promise.all(addons.map(createAddon));

    function createAddon(name) {
      console.log(`Provisioning ${ name }...`)
      return app.addons().create({
        plan: name
      });
    }
  }

  function createLocalSlug() {
    cli.log('Creating local slug...');

    return new Promise(function(resolve, reject) {
      var slugPath = os.tmpdir();
      var output = '';
      var build = child.spawn('docker-compose', ['build', 'web']);

      build.stdout.pipe(process.stdout);
      build.stderr.pipe(process.stderr);
      build.stdout.on('data', saveOutput);
      build.on('exit', onBuildExit);

      function saveOutput(data) {
        output += data;
      }

      function onBuildExit(code) {
        if (code !== 0) throw new Error('Build failed');
        var tokens = output.match(/\S+/g);
        var imageId = tokens[tokens.length - 1];
        tar(imageId);
      }

      function tar(imageId) {
        cli.log('extracting slug from container...');
        var containerId = child.execSync(`docker run -d ${imageId} tar cfvz /tmp/slug.tgz -C / --exclude=.git --exclude=.cache --exclude=.buildpack ./app`, {
          encoding: 'utf8'
        }).trim();
        child.execSync(`docker wait ${containerId}`);
        child.execSync(`docker cp ${containerId}:/tmp/slug.tgz ${slugPath}`);
        child.execSync(`docker rm -f ${containerId}`);
        resolve(path.join(slugPath, 'slug.tgz'));
      }
    });
  }

  function createRemoteSlug(slugPath) {
    console.log('path:', slugPath);
    cli.log('creating remote slug...');
    cli.log('remote process types:', modifiedProc);
    var slugInfo = app.slugs().create({
      process_types: modifiedProc,
      buildpack_provided_description: appJSON.image || 'docker (unknown)'
    });
    return Promise.all([slugPath, slugInfo])
  }

  function uploadSlug(slug) {
    var slugPath = slug[0];
    var slugInfo = slug[1];
    var size = fs.statSync(slugPath).size;
    var mbs = Math.round(size / 1024 / 1024)
    var bar = new ProgressBar(`uploading slug [:bar] :percent of ${ mbs } MB, :etas`, {
      width: 20,
      total: size
    });

    return new Promise(function(resolve, reject) {
      var outStream = request({
        method: 'PUT',
        url: slugInfo.blob.url,
        headers: {
          'content-type': '',
          'content-length': size
        }
      });

      fs.createReadStream(slugPath)
        .on('error', reject)
        .on('data', updateProgress)
        .pipe(outStream)
        .on('error', reject)
        .on('response', resolve.bind(this, slugInfo.id));

      function updateProgress(chunk) {
        bar.tick(chunk.length);
      }
    });
  }

  function releaseSlug(id) {
    cli.log('releasing slug...');

    return heroku.request({
      method: 'POST',
      path: `${ app.path }/releases`,
      headers: {
        'Heroku-Deploy-Type': 'heroku-docker'
      },
      body: {
        slug: id
      }
    });
  }

  function showMessage(results) {
    console.log(`Successfully released ${ results.app.name }!`);
  }
}
<commit_msg>extract image name from build output (FROM)<commit_after>var child = require('child_process');
var path = require('path');
var os = require('os');
var fs = require('fs');
var Heroku = require('heroku-client');
var request = require('request');
var agent = require('superagent');
var cli = require('heroku-cli-util');
var _ = require('lodash');
var ProgressBar = require('progress');

var directory = require('../lib/directory');
var docker = require('../lib/docker');
var safely = require('../lib/safely');

const ADDONS = require('../lib/addons');

module.exports = function(topic) {
  return {
    topic: topic,
    command: 'release',
    description: 'create and release slug to app',
    help: 'Create slug tarball from Docker image and release it to Heroku app',
    needsApp: true,
    needsAuth: true,
    run: safely(release)
  };
};

function release(context) {
  var procfile = directory.readProcfile(context.cwd);
  var mountDir = directory.determineMountDir(context.cwd);
  var modifiedProc = _.mapValues(procfile, prependMountDir(mountDir));
  var heroku = context.heroku || new Heroku({ token: context.auth.password });
  var app = context.heroku ? context.app : heroku.apps(context.app);
  var appJSONLocation = path.join(context.cwd, 'app.json');
  var appJSON = JSON.parse(fs.readFileSync(appJSONLocation, { encoding: 'utf8' }));

  request = context.request || request;

  if (!procfile) throw new Error('Procfile required. Aborting');

  return app.info()
    .then(readRemoteAddons)
    .then(compareLocalAddons)
    .then(addMissingAddons)
    .then(createLocalSlug)
    .then(createRemoteSlug)
    .then(uploadSlug)
    .then(releaseSlug)
    .then(showMessage);

  function prependMountDir(mountDir) {
    return function(cmd) {
      return `cd ${ mountDir } && ${ cmd }`
    }
  }

  function readRemoteAddons() {
    return app.addons().list();
  }

  function compareLocalAddons(remoteAddons) {
    var remoteNames = _.map(remoteAddons, getServiceName);
    var localNames = appJSON.addons || [];
    var missingAddons = _.filter(localNames, isMissingFrom.bind(this, remoteNames));

    console.log(`Remote addons: ${ remoteNames.join(', ')} (${ remoteNames.length })`);
    console.log(`Local addons: ${ localNames.join(', ') } (${ localNames.length })`);
    console.log(`Missing addons: ${ missingAddons.join(', ') } (${ missingAddons.length })`);

    return Promise.resolve(missingAddons);

    function getServiceName(addon) {
      return addon.addon_service.name;
    }

    function isMissingFrom(list, addon) {
      var name = addon.split(':')[0];
      return list.indexOf(name) === -1;
    }
  }

  function addMissingAddons(addons) {
    return Promise.all(addons.map(createAddon));

    function createAddon(name) {
      console.log(`Provisioning ${ name }...`)
      return app.addons().create({
        plan: name
      });
    }
  }

  function createLocalSlug() {
    cli.log('Creating local slug...');

    return new Promise(function(resolve, reject) {
      var slugPath = os.tmpdir();
      var output = '';
      var build = child.spawn('docker-compose', ['build', 'web']);

      build.stdout.pipe(process.stdout);
      build.stderr.pipe(process.stderr);
      build.stdout.on('data', saveOutput);
      build.on('exit', onBuildExit);

      function saveOutput(data) {
        output += data;
      }

      function onBuildExit(code) {
        if (code !== 0) throw new Error('Build failed');
        var tokens = output.match(/\S+/g);
        var fromMatch = output.match(/FROM ([^\s]+)/) || [];
        var imageName = fromMatch[1];
        var imageId = tokens[tokens.length - 1];
        tar(imageName, imageId);
      }

      function tar(imageName, imageId) {
        cli.log('extracting slug from container...');
        var containerId = child.execSync(`docker run -d ${imageId} tar cfvz /tmp/slug.tgz -C / --exclude=.git --exclude=.cache --exclude=.buildpack ./app`, {
          encoding: 'utf8'
        }).trim();
        child.execSync(`docker wait ${containerId}`);
        child.execSync(`docker cp ${containerId}:/tmp/slug.tgz ${slugPath}`);
        child.execSync(`docker rm -f ${containerId}`);
        resolve({
          path: path.join(slugPath, 'slug.tgz'),
          name: imageName
        });
      }
    });
  }

  function createRemoteSlug(slug) {
    var lang = `heroku-docker (${ slug.name || 'unknown'})`;
    cli.log(`creating remote slug...`);
    cli.log(`language-pack: ${ lang }`);
    cli.log('remote process types:', modifiedProc);
    var slugInfo = app.slugs().create({
      process_types: modifiedProc,
      buildpack_provided_description: lang
    });
    return Promise.all([slug.path, slugInfo])
  }

  function uploadSlug(slug) {
    var slugPath = slug[0];
    var slugInfo = slug[1];
    var size = fs.statSync(slugPath).size;
    var mbs = Math.round(size / 1024 / 1024)
    var bar = new ProgressBar(`uploading slug [:bar] :percent of ${ mbs } MB, :etas`, {
      width: 20,
      total: size
    });

    return new Promise(function(resolve, reject) {
      var outStream = request({
        method: 'PUT',
        url: slugInfo.blob.url,
        headers: {
          'content-type': '',
          'content-length': size
        }
      });

      fs.createReadStream(slugPath)
        .on('error', reject)
        .on('data', updateProgress)
        .pipe(outStream)
        .on('error', reject)
        .on('response', resolve.bind(this, slugInfo.id));

      function updateProgress(chunk) {
        bar.tick(chunk.length);
      }
    });
  }

  function releaseSlug(id) {
    cli.log('releasing slug...');

    return heroku.request({
      method: 'POST',
      path: `${ app.path }/releases`,
      headers: {
        'Heroku-Deploy-Type': 'heroku-docker'
      },
      body: {
        slug: id
      }
    });
  }

  function showMessage(results) {
    console.log(`Successfully released ${ results.app.name }!`);
  }
}
<|endoftext|>


<commit_before>module.exports = {
  rules: {
    // enforce spacing inside array brackets
    'array-bracket-spacing': ['error', 'never'],

    // enforce spacing inside single-line blocks
    // http://eslint.org/docs/rules/block-spacing
    'block-spacing': ['error', 'always'],

    // enforce one true brace style
    'brace-style': ['error', '1tbs', { allowSingleLine: true }],

    // require camel case names
    camelcase: ['error', { properties: 'never' }],

    // enforce spacing before and after comma
    'comma-spacing': ['error', { before: false, after: true }],

    // enforce one true comma style
    'comma-style': ['error', 'last'],

    // disallow padding inside computed properties
    'computed-property-spacing': ['error', 'never'],

    // enforces consistent naming when capturing the current execution context
    'consistent-this': 'off',

    // enforce newline at the end of file, with no multiple empty lines
    'eol-last': 'error',

    // enforce spacing between functions and their invocations
    // http://eslint.org/docs/rules/func-call-spacing
    // TODO: enable, semver-minor
    'func-call-spacing': ['off', 'never'],

    // require function expressions to have a name
    'func-names': 'warn',

    // enforces use of function declarations or expressions
    'func-style': 'off',

    // Blacklist certain identifiers to prevent them being used
    // http://eslint.org/docs/rules/id-blacklist
    'id-blacklist': 'off',

    // this option enforces minimum and maximum identifier lengths
    // (variable names, property names etc.)
    'id-length': 'off',

    // require identifiers to match the provided regular expression
    'id-match': 'off',

    // this option sets a specific tab width for your code
    // http://eslint.org/docs/rules/indent
    indent: ['error', 2, { SwitchCase: 1, VariableDeclarator: 1, outerIIFEBody: 1 }],

    // specify whether double or single quotes should be used in JSX attributes
    // http://eslint.org/docs/rules/jsx-quotes
    'jsx-quotes': ['off', 'prefer-double'],

    // enforces spacing between keys and values in object literal properties
    'key-spacing': ['error', { beforeColon: false, afterColon: true }],

    // require a space before & after certain keywords
    'keyword-spacing': ['error', {
      before: true,
      after: true,
      overrides: {
        return: { after: true },
        throw: { after: true },
        case: { after: true }
      }
    }],

    // disallow mixed 'LF' and 'CRLF' as linebreaks
    // http://eslint.org/docs/rules/linebreak-style
    'linebreak-style': ['error', 'unix'],

    // enforces empty lines around comments
    'lines-around-comment': 'off',

    // specify the maximum depth that blocks can be nested
    'max-depth': ['off', 4],

    // specify the maximum length of a line in your program
    // http://eslint.org/docs/rules/max-len
    'max-len': ['error', 100, 2, {
      ignoreUrls: true,
      ignoreComments: false
    }],

    // specify the max number of lines in a file
    // http://eslint.org/docs/rules/max-lines
    'max-lines': ['off', {
      max: 300,
      skipBlankLines: true,
      skipComments: true
    }],

    // specify the maximum depth callbacks can be nested
    'max-nested-callbacks': 'off',

    // limits the number of parameters that can be used in the function declaration.
    'max-params': ['off', 3],

    // specify the maximum number of statement allowed in a function
    'max-statements': ['off', 10],

    // restrict the number of statements per line
    // http://eslint.org/docs/rules/max-statements-per-line
    'max-statements-per-line': ['off', { max: 1 }],

    // require multiline ternary
    // http://eslint.org/docs/rules/multiline-ternary
    'multiline-ternary': 'off',

    // require a capital letter for constructors
    'new-cap': ['error', { newIsCap: true }],

    // disallow the omission of parentheses when invoking a constructor with no arguments
    // http://eslint.org/docs/rules/new-parens
    'new-parens': 'error',

    // allow/disallow an empty newline after var statement
    'newline-after-var': 'off',

    // http://eslint.org/docs/rules/newline-before-return
    'newline-before-return': 'off',

    // enforces new line after each method call in the chain to make it
    // more readable and easy to maintain
    // http://eslint.org/docs/rules/newline-per-chained-call
    'newline-per-chained-call': ['error', { ignoreChainWithDepth: 4 }],

    // disallow use of the Array constructor
    'no-array-constructor': 'error',

    // disallow use of bitwise operators
    // http://eslint.org/docs/rules/no-bitwise
    // TODO: enable
    'no-bitwise': 'off',

    // disallow use of the continue statement
    // http://eslint.org/docs/rules/no-continue
    'no-continue': 'error',

    // disallow comments inline after code
    'no-inline-comments': 'off',

    // disallow if as the only statement in an else block
    // http://eslint.org/docs/rules/no-lonely-if
    'no-lonely-if': 'error',

    // disallow un-paren'd mixes of different operators
    // http://eslint.org/docs/rules/no-mixed-operators
    'no-mixed-operators': ['error', {
      groups: [
        ['+', '-', '*', '/', '%', '**'],
        ['&', '|', '^', '~', '<<', '>>', '>>>'],
        ['==', '!=', '===', '!==', '>', '>=', '<', '<='],
        ['&&', '||'],
        ['in', 'instanceof']
      ],
      allowSamePrecedence: false
    }],

    // disallow mixed spaces and tabs for indentation
    'no-mixed-spaces-and-tabs': 'error',

    // disallow multiple empty lines and only one newline at the end
    'no-multiple-empty-lines': ['error', { max: 2, maxEOF: 1 }],

    // disallow negated conditions
    // http://eslint.org/docs/rules/no-negated-condition
    'no-negated-condition': 'off',

    // disallow nested ternary expressions
    'no-nested-ternary': 'error',

    // disallow use of the Object constructor
    'no-new-object': 'error',

    // disallow use of unary operators, ++ and --
    'no-plusplus': 'off',

    // disallow certain syntax forms
    // http://eslint.org/docs/rules/no-restricted-syntax
    'no-restricted-syntax': [
      'error',
      'DebuggerStatement',
      'ForInStatement',
      'LabeledStatement',
      'WithStatement',
    ],

    // disallow space between function identifier and application
    'no-spaced-func': 'error',

    // disallow tab characters entirely
    // TODO: enable
    'no-tabs': 'off',

    // disallow the use of ternary operators
    'no-ternary': 'off',

    // disallow trailing whitespace at the end of lines
    'no-trailing-spaces': 'error',

    // disallow dangling underscores in identifiers
    'no-underscore-dangle': ['error', { allowAfterThis: false }],

    // disallow the use of Boolean literals in conditional expressions
    // also, prefer `a || b` over `a ? a : b`
    // http://eslint.org/docs/rules/no-unneeded-ternary
    'no-unneeded-ternary': ['error', { defaultAssignment: false }],

    // disallow whitespace before properties
    // http://eslint.org/docs/rules/no-whitespace-before-property
    'no-whitespace-before-property': 'error',

    // require padding inside curly braces
    'object-curly-spacing': ['error', 'always'],

    // enforce line breaks between braces
    // http://eslint.org/docs/rules/object-curly-newline
    // TODO: enable once https://github.com/eslint/eslint/issues/6488 is resolved
    'object-curly-newline': ['off', {
      ObjectExpression: { minProperties: 0, multiline: true },
      ObjectPattern: { minProperties: 0, multiline: true }
    }],

    // enforce "same line" or "multiple line" on object properties.
    // http://eslint.org/docs/rules/object-property-newline
    'object-property-newline': ['error', {
      allowMultiplePropertiesPerLine: true,
    }],

    // allow just one var statement per function
    'one-var': ['error', 'never'],

    // require a newline around variable declaration
    // http://eslint.org/docs/rules/one-var-declaration-per-line
    'one-var-declaration-per-line': ['error', 'always'],

    // require assignment operator shorthand where possible or prohibit it entirely
    // http://eslint.org/docs/rules/operator-assignment
    'operator-assignment': ['error', 'always'],

    // enforce operators to be placed before or after line breaks
    'operator-linebreak': 'off',

    // enforce padding within blocks
    'padded-blocks': ['error', 'never'],

    // require quotes around object literal property names
    // http://eslint.org/docs/rules/quote-props.html
    'quote-props': ['error', 'as-needed', { keywords: false, unnecessary: true, numbers: false }],

    // specify whether double or single quotes should be used
    quotes: ['error', 'single', { avoidEscape: true }],

    // do not require jsdoc
    // http://eslint.org/docs/rules/require-jsdoc
    'require-jsdoc': 'off',

    // require or disallow use of semicolons instead of ASI
    semi: ['error', 'always'],

    // enforce spacing before and after semicolons
    'semi-spacing': ['error', { before: false, after: true }],

    // requires object keys to be sorted
    'sort-keys': ['off', 'asc', { caseSensitive: false, natural: true }],

    // sort variables within the same declaration block
    'sort-vars': 'off',

    // require or disallow space before blocks
    'space-before-blocks': 'error',

    // require or disallow space before function opening parenthesis
    // http://eslint.org/docs/rules/space-before-function-paren
    'space-before-function-paren': ['error', { anonymous: 'always', named: 'never' }],

    // require or disallow spaces inside parentheses
    'space-in-parens': ['error', 'never'],

    // require spaces around operators
    'space-infix-ops': 'error',

    // Require or disallow spaces before/after unary operators
    // http://eslint.org/docs/rules/space-unary-ops
    'space-unary-ops': ['error', {
      words: true,
      nonwords: false,
      overrides: {
      },
    }],

    // require or disallow a space immediately following the // or /* in a comment
    'spaced-comment': ['error', 'always', {
      exceptions: ['-', '+'],
      markers: ['=', '!']           // space here to support sprockets directives
    }],

    // require or disallow the Unicode Byte Order Mark
    // http://eslint.org/docs/rules/unicode-bom
    'unicode-bom': ['error', 'never'],

    // require regex literals to be wrapped in parentheses
    'wrap-regex': 'off'
  }
};
<commit_msg>[eslint config] [base] [patch] remove redundant `DebuggerStatement` from `no-restricted-syntax`<commit_after>module.exports = {
  rules: {
    // enforce spacing inside array brackets
    'array-bracket-spacing': ['error', 'never'],

    // enforce spacing inside single-line blocks
    // http://eslint.org/docs/rules/block-spacing
    'block-spacing': ['error', 'always'],

    // enforce one true brace style
    'brace-style': ['error', '1tbs', { allowSingleLine: true }],

    // require camel case names
    camelcase: ['error', { properties: 'never' }],

    // enforce spacing before and after comma
    'comma-spacing': ['error', { before: false, after: true }],

    // enforce one true comma style
    'comma-style': ['error', 'last'],

    // disallow padding inside computed properties
    'computed-property-spacing': ['error', 'never'],

    // enforces consistent naming when capturing the current execution context
    'consistent-this': 'off',

    // enforce newline at the end of file, with no multiple empty lines
    'eol-last': 'error',

    // enforce spacing between functions and their invocations
    // http://eslint.org/docs/rules/func-call-spacing
    // TODO: enable, semver-minor
    'func-call-spacing': ['off', 'never'],

    // require function expressions to have a name
    'func-names': 'warn',

    // enforces use of function declarations or expressions
    'func-style': 'off',

    // Blacklist certain identifiers to prevent them being used
    // http://eslint.org/docs/rules/id-blacklist
    'id-blacklist': 'off',

    // this option enforces minimum and maximum identifier lengths
    // (variable names, property names etc.)
    'id-length': 'off',

    // require identifiers to match the provided regular expression
    'id-match': 'off',

    // this option sets a specific tab width for your code
    // http://eslint.org/docs/rules/indent
    indent: ['error', 2, { SwitchCase: 1, VariableDeclarator: 1, outerIIFEBody: 1 }],

    // specify whether double or single quotes should be used in JSX attributes
    // http://eslint.org/docs/rules/jsx-quotes
    'jsx-quotes': ['off', 'prefer-double'],

    // enforces spacing between keys and values in object literal properties
    'key-spacing': ['error', { beforeColon: false, afterColon: true }],

    // require a space before & after certain keywords
    'keyword-spacing': ['error', {
      before: true,
      after: true,
      overrides: {
        return: { after: true },
        throw: { after: true },
        case: { after: true }
      }
    }],

    // disallow mixed 'LF' and 'CRLF' as linebreaks
    // http://eslint.org/docs/rules/linebreak-style
    'linebreak-style': ['error', 'unix'],

    // enforces empty lines around comments
    'lines-around-comment': 'off',

    // specify the maximum depth that blocks can be nested
    'max-depth': ['off', 4],

    // specify the maximum length of a line in your program
    // http://eslint.org/docs/rules/max-len
    'max-len': ['error', 100, 2, {
      ignoreUrls: true,
      ignoreComments: false
    }],

    // specify the max number of lines in a file
    // http://eslint.org/docs/rules/max-lines
    'max-lines': ['off', {
      max: 300,
      skipBlankLines: true,
      skipComments: true
    }],

    // specify the maximum depth callbacks can be nested
    'max-nested-callbacks': 'off',

    // limits the number of parameters that can be used in the function declaration.
    'max-params': ['off', 3],

    // specify the maximum number of statement allowed in a function
    'max-statements': ['off', 10],

    // restrict the number of statements per line
    // http://eslint.org/docs/rules/max-statements-per-line
    'max-statements-per-line': ['off', { max: 1 }],

    // require multiline ternary
    // http://eslint.org/docs/rules/multiline-ternary
    'multiline-ternary': 'off',

    // require a capital letter for constructors
    'new-cap': ['error', { newIsCap: true }],

    // disallow the omission of parentheses when invoking a constructor with no arguments
    // http://eslint.org/docs/rules/new-parens
    'new-parens': 'error',

    // allow/disallow an empty newline after var statement
    'newline-after-var': 'off',

    // http://eslint.org/docs/rules/newline-before-return
    'newline-before-return': 'off',

    // enforces new line after each method call in the chain to make it
    // more readable and easy to maintain
    // http://eslint.org/docs/rules/newline-per-chained-call
    'newline-per-chained-call': ['error', { ignoreChainWithDepth: 4 }],

    // disallow use of the Array constructor
    'no-array-constructor': 'error',

    // disallow use of bitwise operators
    // http://eslint.org/docs/rules/no-bitwise
    // TODO: enable
    'no-bitwise': 'off',

    // disallow use of the continue statement
    // http://eslint.org/docs/rules/no-continue
    'no-continue': 'error',

    // disallow comments inline after code
    'no-inline-comments': 'off',

    // disallow if as the only statement in an else block
    // http://eslint.org/docs/rules/no-lonely-if
    'no-lonely-if': 'error',

    // disallow un-paren'd mixes of different operators
    // http://eslint.org/docs/rules/no-mixed-operators
    'no-mixed-operators': ['error', {
      groups: [
        ['+', '-', '*', '/', '%', '**'],
        ['&', '|', '^', '~', '<<', '>>', '>>>'],
        ['==', '!=', '===', '!==', '>', '>=', '<', '<='],
        ['&&', '||'],
        ['in', 'instanceof']
      ],
      allowSamePrecedence: false
    }],

    // disallow mixed spaces and tabs for indentation
    'no-mixed-spaces-and-tabs': 'error',

    // disallow multiple empty lines and only one newline at the end
    'no-multiple-empty-lines': ['error', { max: 2, maxEOF: 1 }],

    // disallow negated conditions
    // http://eslint.org/docs/rules/no-negated-condition
    'no-negated-condition': 'off',

    // disallow nested ternary expressions
    'no-nested-ternary': 'error',

    // disallow use of the Object constructor
    'no-new-object': 'error',

    // disallow use of unary operators, ++ and --
    'no-plusplus': 'off',

    // disallow certain syntax forms
    // http://eslint.org/docs/rules/no-restricted-syntax
    'no-restricted-syntax': [
      'error',
      'ForInStatement',
      'LabeledStatement',
      'WithStatement',
    ],

    // disallow space between function identifier and application
    'no-spaced-func': 'error',

    // disallow tab characters entirely
    // TODO: enable
    'no-tabs': 'off',

    // disallow the use of ternary operators
    'no-ternary': 'off',

    // disallow trailing whitespace at the end of lines
    'no-trailing-spaces': 'error',

    // disallow dangling underscores in identifiers
    'no-underscore-dangle': ['error', { allowAfterThis: false }],

    // disallow the use of Boolean literals in conditional expressions
    // also, prefer `a || b` over `a ? a : b`
    // http://eslint.org/docs/rules/no-unneeded-ternary
    'no-unneeded-ternary': ['error', { defaultAssignment: false }],

    // disallow whitespace before properties
    // http://eslint.org/docs/rules/no-whitespace-before-property
    'no-whitespace-before-property': 'error',

    // require padding inside curly braces
    'object-curly-spacing': ['error', 'always'],

    // enforce line breaks between braces
    // http://eslint.org/docs/rules/object-curly-newline
    // TODO: enable once https://github.com/eslint/eslint/issues/6488 is resolved
    'object-curly-newline': ['off', {
      ObjectExpression: { minProperties: 0, multiline: true },
      ObjectPattern: { minProperties: 0, multiline: true }
    }],

    // enforce "same line" or "multiple line" on object properties.
    // http://eslint.org/docs/rules/object-property-newline
    'object-property-newline': ['error', {
      allowMultiplePropertiesPerLine: true,
    }],

    // allow just one var statement per function
    'one-var': ['error', 'never'],

    // require a newline around variable declaration
    // http://eslint.org/docs/rules/one-var-declaration-per-line
    'one-var-declaration-per-line': ['error', 'always'],

    // require assignment operator shorthand where possible or prohibit it entirely
    // http://eslint.org/docs/rules/operator-assignment
    'operator-assignment': ['error', 'always'],

    // enforce operators to be placed before or after line breaks
    'operator-linebreak': 'off',

    // enforce padding within blocks
    'padded-blocks': ['error', 'never'],

    // require quotes around object literal property names
    // http://eslint.org/docs/rules/quote-props.html
    'quote-props': ['error', 'as-needed', { keywords: false, unnecessary: true, numbers: false }],

    // specify whether double or single quotes should be used
    quotes: ['error', 'single', { avoidEscape: true }],

    // do not require jsdoc
    // http://eslint.org/docs/rules/require-jsdoc
    'require-jsdoc': 'off',

    // require or disallow use of semicolons instead of ASI
    semi: ['error', 'always'],

    // enforce spacing before and after semicolons
    'semi-spacing': ['error', { before: false, after: true }],

    // requires object keys to be sorted
    'sort-keys': ['off', 'asc', { caseSensitive: false, natural: true }],

    // sort variables within the same declaration block
    'sort-vars': 'off',

    // require or disallow space before blocks
    'space-before-blocks': 'error',

    // require or disallow space before function opening parenthesis
    // http://eslint.org/docs/rules/space-before-function-paren
    'space-before-function-paren': ['error', { anonymous: 'always', named: 'never' }],

    // require or disallow spaces inside parentheses
    'space-in-parens': ['error', 'never'],

    // require spaces around operators
    'space-infix-ops': 'error',

    // Require or disallow spaces before/after unary operators
    // http://eslint.org/docs/rules/space-unary-ops
    'space-unary-ops': ['error', {
      words: true,
      nonwords: false,
      overrides: {
      },
    }],

    // require or disallow a space immediately following the // or /* in a comment
    'spaced-comment': ['error', 'always', {
      exceptions: ['-', '+'],
      markers: ['=', '!']           // space here to support sprockets directives
    }],

    // require or disallow the Unicode Byte Order Mark
    // http://eslint.org/docs/rules/unicode-bom
    'unicode-bom': ['error', 'never'],

    // require regex literals to be wrapped in parentheses
    'wrap-regex': 'off'
  }
};
<|endoftext|>


<commit_before>/**
 * Author: Damian Szymczuk
 * Website: http://dszymczuk.pl
 * Version: 0.1
 * GitHub: https://github.com/dszymczuk/JSONEventCalendar
 */

(function( $ ) {
    $.fn.JSONEventCalendar = function(events,options) {

        var settings = $.extend($.fn.JSONEventCalendar.settings, options );

        var initMoment = moment();
        initMoment.locale(settings.lang);

        var names = {
            monthNames: initMoment._locale._months,
            dayNames: initMoment._locale._weekdays,
            dayNamesShort: initMoment._locale._weekdaysShort,
            dayNamesMin: initMoment._locale._weekdaysMin
        };

        return this.each( function() {
            var that = $(this);
//            var m = moment();

//            m.locale(settings.lang);
//            m.format(settings.format);

            var year = moment().get('year');
            var month = moment().get('month');

            that.html(draw(that,options.mode,{
                formatTitle: settings.formatTitle,
                lang: settings.lang
                ,year: year
                ,month: month
            }));
            _refreshDayHeight(that);

            //next month
            that.on('click','.ds-next-month',function(){
                if(month > 10)
                {
                    month = 0;
                    year++;
                }
                else
                    month++;

//                console.warn(month,year);

                that.html(draw(that,options.mode,{
                    formatTitle: settings.formatTitle,
                    lang: settings.lang
                    ,year: year
                    ,month: month
                }));
                _refreshDayHeight(that);
            });

            //prev month
            that.on('click','.ds-prev-month',function(){
//                console.log("jer: ",year);
                if(month < 1)
                {
                    month=11;
                    year--;
                }
                else
                    month--;

//                console.warn(month,year);
                that.html(draw(that,options.mode,{
                    formatTitle: settings.formatTitle,
                    lang: settings.lang
                    ,year: year
                    ,month: month
                }));
                _refreshDayHeight(that);
            });

            //event click
            that.on('click','.ds-event',function(){
                var elem = $(this);
                var id = elem[0].id;

                var event =  _.find(events, function(e) {
                    return e.id == id;
                });

//                console.warn(event);
                $(".ds-calendar").append(_drawModalEvent(event));
//                $(".ds-event-modal").css('visibility', 'visible');
            });

            that.on('click','.ds-event-modal .close-button',function(){
//                console.log("modal click");
                var elem = $(this);
//                console.log(elem);
//               elem.css('visibility', 'hidden');
                $(".ds-event-modal").remove();
               //elem.css('display', 'none');
            });

        });

        function draw(element$,mode,options) {
            if(typeof mode === 'undefined')
                mode = 'both';

            if(typeof options === 'undefined')
                return "Can't draw calendar - options in draw is undefined";

            var html = "";
//            html += '
';

            switch (mode) {
                case 'calendar':
                    html += _drawCalendar(options);
                    break;
                case 'list':
//                    html += _drawModalEvent(options);
                    break;
                default :
                    html += _drawCalendar(options);
//                    html += _drawModalEvent(options);
                    break;
            }

//            html += _drawModalEvent();
//            html += '
';
            return html;
        }

        /**
         * Refresh height of element to equal size
         *
         * @param element
         * @private
         */
        function _refreshDayHeight(element) {
            var maxHeight = 0;
            element.find('.ds-events').each(function(){
                var that = $(this);
                if(that.height() > maxHeight)
                    maxHeight = that.height();
            }).each(function(){
                var that = $(this);
                that.css('height',maxHeight + "px");
            });
        }

        function _drawCalendar(options) {
            var year, month;
            var mom = moment();
            if(options.hasOwnProperty('year'))
                year = options.year;
            else
                year = mom.get('year');

            if(options.hasOwnProperty('month'))
                month = options.month;
            else
                month = mom.get('month');

//            month = 5;

            mom.set('year',year);
            mom.set('month',month);
//            console.info(year,month,monthDays(year,month));
            mom.locale(settings.lang);

            var before = {
                month: month,
                year: year
            };
            before.month--;
            var after = {
                month: month,
                year: year
            };

            /*---------------------------*\
                CALCUALTE BEFORE MONTH
            \*---------------------------*/
            if(month < 0)
            {
                before.month=11;
                before.year--;
            }

            /*---------------------------*\
                CALCUALTE AFTER MONTH
            \*---------------------------*/
            if(month+1 > 11)
            {
                after.month = 0;
                after.year++;
            }

            var calendar = '
';

//            console.log(options);

            //header
            calendar += '
';
            calendar += '
';
            calendar += '
<
';
            calendar += '
'+mom.format(settings.formatTitle)+'
';
            calendar += '
>
';
            calendar += '
';
            calendar += '
';

            // name of days
            calendar += '
';

            var offset = settings.startFrom;

//            console.log(mom._locale);

//            calendar += '
'+settings.dayNames[offset]+'
';
            calendar += '
'+names.dayNames[offset]+'
';
            for(var i = 1 + offset ; i < 7 + offset ; i++)
                calendar += '
'+names.dayNames[i%7]+'
';

            calendar += '
';

            /*-----------*\
                MONTH -1
            \*-----------*/

//            var monthBefore = monthDays(year,month);
            var daysBefore = monthDays(before.year,before.month);
            var calcBefore = _calcBefore(year,month);
            daysBefore = daysBefore - calcBefore+1;

            for(var b = 0 ; b < calcBefore ; b++)
            {
                calendar += drawDay(daysBefore+b,'before');
            }

            /*-----------------*\
                CUREENT MONTH
            \*-----------------*/
            var currDaysInMonth = monthDays(year,month);
            console.warn(month,year,currDaysInMonth);
            for(var c = 1 ; c <= currDaysInMonth ; c++)
            {
                calendar += drawDay(c,'current',true);
            }

            /*------------*\
                MONTH +1
            \*------------*/

            var nextMonth = 0;

            var cA = _calcAfter(year,month);

            if(cA !== 1)
            {
                for(var a = 0 ; a <= 7-cA ; a++)
                {
                    nextMonth++;
                    calendar += drawDay(nextMonth,'after');
                }
            }

            //to have 6 rows in calendar
//            if(cA !== 2 && cA !== 0)
//            {
//                for(var a = 0 ; a < 7 ; a++)
//                {
//                    nextMonth++;
//                    calendar += drawDay(nextMonth,'super after');
//                }
//            }

            calendar += '';
            calendar += '';
            calendar += '';
            calendar += '';
            calendar += '';

            calendar += '
';
            return calendar;

            function drawDay(day,elementClass,drawEvents){
                drawEvents = typeof drawEvents !== 'undefined' ? drawEvents : false;

                if(typeof elementClass === 'undefined')
                    elementClass = '';
                var dD = '';
                dD += '
';
                dD += '
'+day+'
';
                dD += '
';

                if(drawEvents)
                {
                    var events = _getEvents(day,month,year);
                    for(var e = 0 ; e < events.length ; e++)
                    {
                        dD += '
'+events[e].title+'
';
                    }

                }

                dD += '
';
                dD += '
';
                return dD;
            }

            function _calcBefore(year,month){
//                console.log("Before: ",month,year);

//                if(month < 0)
//                {
//                    month=11;
//                    year--;
//                }

                var f = firstDayPosition(year,month,0)-1;

                if(f < 0)
                    return 6;
                else
                    return f;
            }

            function _calcAfter(year,month){
//                console.log("After: ",month,year);

                month++;
//                if(month > 11)
//                {
//                    month = 0;
//                    year++;
//                }

                return firstDayPosition(year,month,0);
            }

            function _getEvents(day,month,year){
                return _.filter(sampleEvents, function (sE) {
                    return moment(new Date(year, month, day)) < new Date(sE.date)
                        && new Date(sE.date) < moment(new Date(year, month, day)).add(1, 'd');
                });
            }

            function monthDays(year,month) {
                month++;
                var d = new Date(year,month, 0);
//                console.log(d.getDate());
                return d.getDate();
            }

            function firstDayPosition(year,month,offset) {
                var mom = moment();
                mom.set('year',year);
                mom.set('month',month);
                mom.date(1);
//                console.log(mom.format('DD MM YYYY'));
                return mom.day()+offset;
            }
        }

        function _drawModalEvent(event){
            console.warn(event);
            var eventDetails = "";

            eventDetails += '
';
            eventDetails += '
';
            eventDetails += '
';
            eventDetails += '
'+event.title+'
';
            eventDetails += '
'+moment(event.date).locale(settings.lang).format(settings.formatEvent)+'
';
            eventDetails += '
';
            eventDetails += '
';
            eventDetails += '
'+event.type+'
';
            eventDetails += '
'+event.description+'
';
            eventDetails += '
'+event.url+'
';
            eventDetails += '
';
            eventDetails += '
';
            eventDetails += '
';
            eventDetails += settings.closeText;
            eventDetails += '
';
            eventDetails += '
';
            eventDetails += '
';
            eventDetails += '
';

            return eventDetails;
        }
    }
}( jQuery ));

/*
mode - calendar, list, both
 */
$.fn.JSONEventCalendar.settings = {
    lang: "pl",
//    format: "DD-MM-YYYY",
    formatTitle: "MMMM YYYY",
    formatEvent: "DD MMMM YYYY",
    startFrom: 1, //0 - Sunday, 1 - Monday etc.
    eventsInDay: 3,
    mode: 'calendar',
    closeText: 'close'
};

var data = [];<commit_msg>remove some console logs<commit_after>/**
 * Author: Damian Szymczuk
 * Website: http://dszymczuk.pl
 * Version: 0.1
 * GitHub: https://github.com/dszymczuk/JSONEventCalendar
 */

(function( $ ) {
    $.fn.JSONEventCalendar = function(events,options) {

        var settings = $.extend($.fn.JSONEventCalendar.settings, options );

        var initMoment = moment();
        initMoment.locale(settings.lang);

        var names = {
            monthNames: initMoment._locale._months,
            dayNames: initMoment._locale._weekdays,
            dayNamesShort: initMoment._locale._weekdaysShort,
            dayNamesMin: initMoment._locale._weekdaysMin
        };

        return this.each( function() {
            var that = $(this);
//            var m = moment();

//            m.locale(settings.lang);
//            m.format(settings.format);

            var year = moment().get('year');
            var month = moment().get('month');

            that.html(draw(that,options.mode,{
                formatTitle: settings.formatTitle,
                lang: settings.lang
                ,year: year
                ,month: month
            }));
            _refreshDayHeight(that);

            //next month
            that.on('click','.ds-next-month',function(){
                if(month > 10)
                {
                    month = 0;
                    year++;
                }
                else
                    month++;

//                console.warn(month,year);

                that.html(draw(that,options.mode,{
                    formatTitle: settings.formatTitle,
                    lang: settings.lang
                    ,year: year
                    ,month: month
                }));
                _refreshDayHeight(that);
            });

            //prev month
            that.on('click','.ds-prev-month',function(){
//                console.log("jer: ",year);
                if(month < 1)
                {
                    month=11;
                    year--;
                }
                else
                    month--;

//                console.warn(month,year);
                that.html(draw(that,options.mode,{
                    formatTitle: settings.formatTitle,
                    lang: settings.lang
                    ,year: year
                    ,month: month
                }));
                _refreshDayHeight(that);
            });

            //event click
            that.on('click','.ds-event',function(){
                var elem = $(this);
                var id = elem[0].id;

                var event =  _.find(events, function(e) {
                    return e.id == id;
                });

//                console.warn(event);
                $(".ds-calendar").append(_drawModalEvent(event));
//                $(".ds-event-modal").css('visibility', 'visible');
            });

            that.on('click','.ds-event-modal .close-button',function(){
//                console.log("modal click");
                var elem = $(this);
//                console.log(elem);
//               elem.css('visibility', 'hidden');
                $(".ds-event-modal").remove();
               //elem.css('display', 'none');
            });

        });

        function draw(element$,mode,options) {
            if(typeof mode === 'undefined')
                mode = 'both';

            if(typeof options === 'undefined')
                return "Can't draw calendar - options in draw is undefined";

            var html = "";
//            html += '
';

            switch (mode) {
                case 'calendar':
                    html += _drawCalendar(options);
                    break;
                case 'list':
//                    html += _drawModalEvent(options);
                    break;
                default :
                    html += _drawCalendar(options);
//                    html += _drawModalEvent(options);
                    break;
            }

//            html += _drawModalEvent();
//            html += '
';
            return html;
        }

        /**
         * Refresh height of element to equal size
         *
         * @param element
         * @private
         */
        function _refreshDayHeight(element) {
            var maxHeight = 0;
            element.find('.ds-events').each(function(){
                var that = $(this);
                if(that.height() > maxHeight)
                    maxHeight = that.height();
            }).each(function(){
                var that = $(this);
                that.css('height',maxHeight + "px");
            });
        }

        function _drawCalendar(options) {
            var year, month;
            var mom = moment();
            if(options.hasOwnProperty('year'))
                year = options.year;
            else
                year = mom.get('year');

            if(options.hasOwnProperty('month'))
                month = options.month;
            else
                month = mom.get('month');

//            month = 5;

            mom.set('year',year);
            mom.set('month',month);
//            console.info(year,month,monthDays(year,month));
            mom.locale(settings.lang);

            var before = {
                month: month,
                year: year
            };
            before.month--;
            var after = {
                month: month,
                year: year
            };

            /*---------------------------*\
                CALCUALTE BEFORE MONTH
            \*---------------------------*/
            if(month < 0)
            {
                before.month=11;
                before.year--;
            }

            /*---------------------------*\
                CALCUALTE AFTER MONTH
            \*---------------------------*/
            if(month+1 > 11)
            {
                after.month = 0;
                after.year++;
            }

            var calendar = '
';

//            console.log(options);

            //header
            calendar += '
';
            calendar += '
';
            calendar += '
<
';
            calendar += '
'+mom.format(settings.formatTitle)+'
';
            calendar += '
>
';
            calendar += '
';
            calendar += '
';

            // name of days
            calendar += '
';

            var offset = settings.startFrom;

//            console.log(mom._locale);

//            calendar += '
'+settings.dayNames[offset]+'
';
            calendar += '
'+names.dayNames[offset]+'
';
            for(var i = 1 + offset ; i < 7 + offset ; i++)
                calendar += '
'+names.dayNames[i%7]+'
';

            calendar += '
';

            /*-----------*\
                MONTH -1
            \*-----------*/
            var daysBefore = monthDays(before.year,before.month);
            var calcBefore = _calcBefore(year,month);
            daysBefore = daysBefore - calcBefore+1;

            for(var b = 0 ; b < calcBefore ; b++)
            {
                calendar += drawDay(daysBefore+b,'before');
            }

            /*-----------------*\
                CUREENT MONTH
            \*-----------------*/
            var currDaysInMonth = monthDays(year,month);
            for(var c = 1 ; c <= currDaysInMonth ; c++)
            {
                calendar += drawDay(c,'current',true);
            }

            /*------------*\
                MONTH +1
            \*------------*/
            var nextMonth = 0;
            var cA = _calcAfter(year,month);
            if(cA !== 1)
            {
                for(var a = 0 ; a <= 7-cA ; a++)
                {
                    nextMonth++;
                    calendar += drawDay(nextMonth,'after');
                }
            }

            //to have 6 rows in calendar
            //@todo to think
//            if(cA !== 2 && cA !== 0)
//            {
//                for(var a = 0 ; a < 7 ; a++)
//                {
//                    nextMonth++;
//                    calendar += drawDay(nextMonth,'super after');
//                }
//            }

            calendar += '';
            calendar += '';
            calendar += '';
            calendar += '';
            calendar += '';

            calendar += '
';
            return calendar;

            function drawDay(day,elementClass,drawEvents){
                drawEvents = typeof drawEvents !== 'undefined' ? drawEvents : false;

                if(typeof elementClass === 'undefined')
                    elementClass = '';
                var dD = '';
                dD += '
';
                dD += '
'+day+'
';
                dD += '
';

                if(drawEvents)
                {
                    var events = _getEvents(day,month,year);
                    for(var e = 0 ; e < events.length ; e++)
                    {
                        dD += '
'+events[e].title+'
';
                    }

                }

                dD += '
';
                dD += '
';
                return dD;
            }

            function _calcBefore(year,month){
//                console.log("Before: ",month,year);

//                if(month < 0)
//                {
//                    month=11;
//                    year--;
//                }

                var f = firstDayPosition(year,month,0)-1;

                if(f < 0)
                    return 6;
                else
                    return f;
            }

            function _calcAfter(year,month){
//                console.log("After: ",month,year);

                month++;
//                if(month > 11)
//                {
//                    month = 0;
//                    year++;
//                }

                return firstDayPosition(year,month,0);
            }

            function _getEvents(day,month,year){
                return _.filter(sampleEvents, function (sE) {
                    return moment(new Date(year, month, day)) < new Date(sE.date)
                        && new Date(sE.date) < moment(new Date(year, month, day)).add(1, 'd');
                });
            }

            function monthDays(year,month) {
                month++;
                var d = new Date(year,month, 0);
//                console.log(d.getDate());
                return d.getDate();
            }

            function firstDayPosition(year,month,offset) {
                var mom = moment();
                mom.set('year',year);
                mom.set('month',month);
                mom.date(1);
//                console.log(mom.format('DD MM YYYY'));
                return mom.day()+offset;
            }
        }

        function _drawModalEvent(event){
            console.warn(event);
            var eventDetails = "";

            eventDetails += '
';
            eventDetails += '
';
            eventDetails += '
';
            eventDetails += '
'+event.title+'
';
            eventDetails += '
'+moment(event.date).locale(settings.lang).format(settings.formatEvent)+'
';
            eventDetails += '
';
            eventDetails += '
';
            eventDetails += '
'+event.type+'
';
            eventDetails += '
'+event.description+'
';
            eventDetails += '
'+event.url+'
';
            eventDetails += '
';
            eventDetails += '
';
            eventDetails += '
';
            eventDetails += settings.closeText;
            eventDetails += '
';
            eventDetails += '
';
            eventDetails += '
';
            eventDetails += '
';

            return eventDetails;
        }
    }
}( jQuery ));

/*
mode - calendar, list, both
 */
$.fn.JSONEventCalendar.settings = {
    lang: "pl",
//    format: "DD-MM-YYYY",
    formatTitle: "MMMM YYYY",
    formatEvent: "DD MMMM YYYY",
    startFrom: 1, //0 - Sunday, 1 - Monday etc.
    eventsInDay: 3,
    mode: 'calendar',
    closeText: 'close'
};

var data = [];<|endoftext|>


<commit_before>var client = require('../');
var ui = require('../lib/ui');
var parse = require('../lib/parse-env');
var fs = require('fs');

module.exports = function(remote, id, opts) {
	if (!id) return ui.error('Service name required');

	var c = client(remote);
	var tar = c.tarball(id);

	tar.on('error', function(err) {
		ui.error(err);
	});

	tar.pipe(opts.out ? fs.createWriteStream(opts.out) : process.stdout);
};
<commit_msg>removed bad ref to env parser<commit_after>var client = require('../');
var ui = require('../lib/ui');
var fs = require('fs');

module.exports = function(remote, id, opts) {
	if (!id) return ui.error('Service name required');

	var c = client(remote);
	var tar = c.tarball(id);

	tar.on('error', function(err) {
		ui.error(err);
	});

	tar.pipe(opts.out ? fs.createWriteStream(opts.out) : process.stdout);
};
<|endoftext|>


<commit_before>// @flow
/**
 * Part of GDL gdl-frontend.
 * Copyright (C) 2017 GDL
 *
 * See LICENSE
 */

import * as React from 'react';
import styled from 'react-emotion';
import { Trans } from '@lingui/react';

import config from '../../config';
import Container from '../../elements/Container';
import CCLogo from './cc-logo.svg';
import { colors } from '../../style/theme';
import media from '../../style/media';

import FaFacebookSquare from 'react-icons/lib/fa/facebook-square';
import FaTwitterSquare from 'react-icons/lib/fa/twitter-square';
import FaYoutubeSquare from 'react-icons/lib/fa/youtube-square';

const FooterStyle = styled('footer')`
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: center;
  margin-top: 40px;
  margin-bottom: 50px;
  a {
    text-decoration: none;
    color: ${colors.text.default};
    &:hover {
      text-decoration: underline;
    }
  }
`;

const WrappingList = styled('ul')`
  display: flex;
  justify-content: space-between;
  flex-grow: 3;
  flex-wrap: wrap;
  order: 2;
  font-size: 0.8rem;
  padding: 0;
  margin-left: 28px;
  list-style: none;
  li {
    padding: 8px;
  }
  ${media.tablet`
    li {
      width: 33%;
     }
  `} ${media.mobile`
    li {
      width: 50%;
    }
      margin-top: 20px;mh
  `};
`;

const SocialMediaIcons = styled('div')`
  display: flex;
  justify-content: space-between;
  flex-grow: 1;
  margin: 14px 36px 20px 36px;
  a {
    font-size: 2.25rem;
    color: ${colors.text.subtle};
    &:hover {
      color: ${colors.default};
    }
  }
  ${media.tablet`
    order: 4;
  `};
  ${media.mobile`
    order: 1;
  `};
`;

const CreativeCommons = styled('div')`
  order: 3;
  flex-grow: 1;
  text-align: center;
  a {
    &:hover {
    fill: ${colors.default};
    }
  ${media.mobile`
    width: 100%;
  `}
`;

const Footer = () => {
  return (
    <Container
      size="large"
      stickToEdgeOnLargeScreens
      width="100%"
      // https://philipwalton.com/articles/normalizing-cross-browser-flexbox-bugs/
      css={{ flexShrink: '0' }}
    >
      <FooterStyle>
        <div
          css={[
            {
              order: 2,
              width: '100%',
              borderBottom: `1px solid ${colors.base.grayLight}`,
              margin: '10px'
            },
            media.tablet({ display: 'none' })
          ]}
        />

        <WrappingList>

              <Trans>Cookie policy</Trans>

              <Trans>Privacy policy</Trans>

              <Trans>Licensing and reuse</Trans>

              <Trans>Report issues</Trans>

              <Trans>About</Trans>

              <Trans>Blog</Trans>

        </WrappingList>

        <CreativeCommons>

            <CCLogo css={{ width: '100px' }} />

        </CreativeCommons>

        <SocialMediaIcons>

            <FaFacebookSquare />

            <FaTwitterSquare />

            <FaYoutubeSquare />

        </SocialMediaIcons>
      </FooterStyle>
    </Container>
  );
};

export default Footer;
<commit_msg>Fix social links in footer<commit_after>// @flow
/**
 * Part of GDL gdl-frontend.
 * Copyright (C) 2017 GDL
 *
 * See LICENSE
 */

import * as React from 'react';
import styled from 'react-emotion';
import { Trans } from '@lingui/react';

import config from '../../config';
import Container from '../../elements/Container';
import CCLogo from './cc-logo.svg';
import { colors } from '../../style/theme';
import media from '../../style/media';

import FaFacebookSquare from 'react-icons/lib/fa/facebook-square';
import FaTwitterSquare from 'react-icons/lib/fa/twitter-square';
import FaYoutubeSquare from 'react-icons/lib/fa/youtube-square';

const FooterStyle = styled('footer')`
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: center;
  margin-top: 40px;
  margin-bottom: 50px;
  a {
    text-decoration: none;
    color: ${colors.text.default};
    &:hover {
      text-decoration: underline;
    }
  }
`;

const WrappingList = styled('ul')`
  display: flex;
  justify-content: space-between;
  flex-grow: 3;
  flex-wrap: wrap;
  order: 2;
  font-size: 0.8rem;
  padding: 0;
  margin-left: 28px;
  list-style: none;
  li {
    padding: 8px;
  }
  ${media.tablet`
    li {
      width: 33%;
     }
  `} ${media.mobile`
    li {
      width: 50%;
    }
      margin-top: 20px;mh
  `};
`;

const SocialMediaIcons = styled('div')`
  display: flex;
  justify-content: space-between;
  flex-grow: 1;
  margin: 14px 36px 20px 36px;
  a {
    font-size: 2.25rem;
    color: ${colors.text.subtle};
    &:hover {
      color: ${colors.default};
    }
  }
  ${media.tablet`
    order: 4;
  `};
  ${media.mobile`
    order: 1;
  `};
`;

const CreativeCommons = styled('div')`
  order: 3;
  flex-grow: 1;
  text-align: center;
  a {
    &:hover {
    fill: ${colors.default};
    }
  ${media.mobile`
    width: 100%;
  `}
`;

const Footer = () => {
  return (
    <Container
      size="large"
      stickToEdgeOnLargeScreens
      width="100%"
      // https://philipwalton.com/articles/normalizing-cross-browser-flexbox-bugs/
      css={{ flexShrink: '0' }}
    >
      <FooterStyle>
        <div
          css={[
            {
              order: 2,
              width: '100%',
              borderBottom: `1px solid ${colors.base.grayLight}`,
              margin: '10px'
            },
            media.tablet({ display: 'none' })
          ]}
        />

        <WrappingList>

              <Trans>Cookie policy</Trans>

              <Trans>Privacy policy</Trans>

              <Trans>Licensing and reuse</Trans>

              <Trans>Report issues</Trans>

              <Trans>About</Trans>

              <Trans>Blog</Trans>

        </WrappingList>

        <CreativeCommons>

            <CCLogo css={{ width: '100px' }} />

        </CreativeCommons>

        <SocialMediaIcons>

            <FaFacebookSquare />

            <FaTwitterSquare />

            <FaYoutubeSquare />

        </SocialMediaIcons>
      </FooterStyle>
    </Container>
  );
};

export default Footer;
<|endoftext|>


<commit_before>/*Project aria2-WIOW
 *
 * Copyright (c) 2014, multiSnow <infinity.blick.winkel@gmail.com>
 *
 *Permission to use, copy, modify, and/or distribute this software for
 *any purpose with or without fee is hereby granted, provided that the
 *above copyright notice and this permission notice appear in all
 *copies.
 *
 *THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
 *WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
 *WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
 *AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
 *DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
 *PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
 *TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 *PERFORMANCE OF THIS SOFTWARE.
 */

function connect(){
    var url=(document.getElementById('wss_scheme').checked===true?'wss://':'ws://')
        +document.getElementById('wshost').value
        +':'+document.getElementById('wsport').value+'/jsonrpc';
    ws=new WebSocket(url);
    ws.onerror=function(message){
        alert('Failed to open '+ws.url)
        return 0;
    };

    ws.onclose=function(message){
        clearInterval(autorefresh);
        var nsidetags=document.getElementById('sidetags');
        var nmain=document.getElementById('main')
        var idl=['mainactive','mainstopped','mainwaiting'];
        for(var n in idl){
            document.getElementById(idl[n]).innerHTML='';
        };
        document.getElementById(nsidetags.getAttribute('crtshow')).style.display='none';
        nsidetags.removeAttribute('crtshow');
        nsidetags.removeAttribute('tagshow');
        nsidetags.style.display='none';
        nmain.style.display='none';
        document.getElementById('sideinfo_static').innerHTML='Disconnected!';
        document.getElementById('sideinfo_dynamic').style.display='none';
        document.getElementById('shutdown_button').style.display='none';
        document.getElementById('disconnect').style.display='none';
        document.getElementById('ws_address').style.display='block';
        document.getElementById('connect').style.display='block';
        document.title='aria2 WIOW';
        if(message.code!==1005){
            alert(message.code+' '+message.reason+' '+message.wasClean);
        };
        return 0;
    };

    ws.onmessage=function(message){
        var idfunc_dict={'mainactive':showactive,'mainstopped':showstopped,'mainwaiting':showwaiting};
        var msg_data=JSON.parse(message.data);
        if('id' in msg_data){
            if(!('error' in msg_data)){
                try{
                    func[msg_data.id](msg_data);
                }catch(e){
                    console.log(msg_data.id);
                };
            };
        }else{
            if(msg_data.method in func){
                func[msg_data.method](msg_data);
                if(document.getElementById('sidetags').getAttribute('crtshow') in idfunc_dict){
                    idfunc_dict[document.getElementById('sidetags').getAttribute('crtshow')]();
                };
            };
        };
        return 0;
    };

    ws.onopen=function(message){
        document.getElementById('sideinfo_dynamic').style.display='inline';
        document.getElementById('sidetags').style.display='block';
        document.getElementById('shutdown_button').style.display='block';
        document.getElementById('main').style.display='block';
        getversion();topage('start');default_option();
        document.getElementById('disconnect').style.display='block';
        document.getElementById('ws_address').style.display='none';
        document.getElementById('connect').style.display='none';
        autorefresh=start_autorefresh()
	return 0;
    };
    return 0;
};

function disconnect(){
    ws.close();
    return 0;
};

function wsreq(id,method,params){
    if(ws.readyState!==1){
        alert('Connection lost or not yet open!');
        return 1;
    };
    var json={jsonrpc:'2.0',
              id:id,
              method:method,
              params:(typeof params===typeof undefined)?[]:params};
    if(document.getElementById('rpctoken').value){
        json.params.unshift('token:'+document.getElementById('rpctoken').value);
    };
    ws.send(JSON.stringify(json));
    return 0;
};
<commit_msg>reset sidetag class<commit_after>/*Project aria2-WIOW
 *
 * Copyright (c) 2014, multiSnow <infinity.blick.winkel@gmail.com>
 *
 *Permission to use, copy, modify, and/or distribute this software for
 *any purpose with or without fee is hereby granted, provided that the
 *above copyright notice and this permission notice appear in all
 *copies.
 *
 *THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
 *WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
 *WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
 *AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
 *DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
 *PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
 *TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 *PERFORMANCE OF THIS SOFTWARE.
 */

function connect(){
    var url=(document.getElementById('wss_scheme').checked===true?'wss://':'ws://')
        +document.getElementById('wshost').value
        +':'+document.getElementById('wsport').value+'/jsonrpc';
    ws=new WebSocket(url);
    ws.onerror=function(message){
        alert('Failed to open '+ws.url)
        return 0;
    };

    ws.onclose=function(message){
        clearInterval(autorefresh);
        var nsidetags=document.getElementById('sidetags');
        var nmain=document.getElementById('main')
        var idl=['mainactive','mainstopped','mainwaiting'];
        for(var n in idl){
            document.getElementById(idl[n]).innerHTML='';
        };
        document.getElementById(nsidetags.getAttribute('crtshow')).style.display='none';
        document.getElementById(nsidetags.getAttribute('tagshow')).classList.remove('side_clicked');
        nsidetags.removeAttribute('crtshow');
        nsidetags.removeAttribute('tagshow');
        nsidetags.style.display='none';
        nmain.style.display='none';
        document.getElementById('sideinfo_static').innerHTML='Disconnected!';
        document.getElementById('sideinfo_dynamic').style.display='none';
        document.getElementById('shutdown_button').style.display='none';
        document.getElementById('disconnect').style.display='none';
        document.getElementById('ws_address').style.display='block';
        document.getElementById('connect').style.display='block';
        document.title='aria2 WIOW';
        if(message.code!==1005){
            alert(message.code+' '+message.reason+' '+message.wasClean);
        };
        return 0;
    };

    ws.onmessage=function(message){
        var idfunc_dict={'mainactive':showactive,'mainstopped':showstopped,'mainwaiting':showwaiting};
        var msg_data=JSON.parse(message.data);
        if('id' in msg_data){
            if(!('error' in msg_data)){
                try{
                    func[msg_data.id](msg_data);
                }catch(e){
                    console.log(msg_data.id);
                };
            };
        }else{
            if(msg_data.method in func){
                func[msg_data.method](msg_data);
                if(document.getElementById('sidetags').getAttribute('crtshow') in idfunc_dict){
                    idfunc_dict[document.getElementById('sidetags').getAttribute('crtshow')]();
                };
            };
        };
        return 0;
    };

    ws.onopen=function(message){
        document.getElementById('sideinfo_dynamic').style.display='inline';
        document.getElementById('sidetags').style.display='block';
        document.getElementById('shutdown_button').style.display='block';
        document.getElementById('main').style.display='block';
        getversion();topage('start');default_option();
        document.getElementById('disconnect').style.display='block';
        document.getElementById('ws_address').style.display='none';
        document.getElementById('connect').style.display='none';
        autorefresh=start_autorefresh()
	return 0;
    };
    return 0;
};

function disconnect(){
    ws.close();
    return 0;
};

function wsreq(id,method,params){
    if(ws.readyState!==1){
        alert('Connection lost or not yet open!');
        return 1;
    };
    var json={jsonrpc:'2.0',
              id:id,
              method:method,
              params:(typeof params===typeof undefined)?[]:params};
    if(document.getElementById('rpctoken').value){
        json.params.unshift('token:'+document.getElementById('rpctoken').value);
    };
    ws.send(JSON.stringify(json));
    return 0;
};
<|endoftext|>


<commit_before>'use strict';

$(document).ready(function() {
  var leap = new Leap.Controller();
  var socket = io.connect('http://localhost');

  leap.on('connect', function() {
    console.log('device connected');
  });

  leap.on('frame', function(frame) {
    // console.log(frame);
    socket.emit('leap-data', {leapData: frame.fingers});
  });

  leap.connect();
});
<commit_msg>Added way to get x position from the leap motion<commit_after>$(document).ready(function() {
  var leap = new Leap.Controller();
  var socket = io.connect('http://localhost');

  leap.on('connect', function() {
    console.log('device connected');
  });

  leap.on('frame', function(frame) {
    var fingers = frame.fingers;
    if (fingers.length) {
      var position = fingers[0].tipPosition;
      var x = position[0];
    }
    // socket.emit('leap-data', {leapData: frame.fingers});
  });

  leap.connect();
});<|endoftext|>


<commit_before>var l10n_file = __dirname + '/../l10n/commands/whisper.yml';
var l10n = require('../src/l10n')(l10n_file);
var CommandUtil = require('../src/command_util').CommandUtil;
exports.command = function(rooms, items, players, npcs, Commands) {
  return function(args, player) {
    console.log(args);
    args = args.split(' ');
    console.log(args);
    var target = args.shift().toLowerCase();
    var msg = args.join(' ');
    var targetFound = true;

    if (args.length > 0) {
      targetFound = false;
      player.sayL10n(l10n, 'YOU_WHISPER', target, msg);
      players.eachIf(function(p) {
        return otherPlayersInRoom(p);
      }, function(p) {
        if (p.getName().toLowerCase() == target) {
          p.sayL10n(l10n, 'THEY_WHISPER', player.getName(), msg);
          targetFound = true;
        } else
          p.sayL10n(l10n, 'OTHERS_WHISPER', player.getName(), target);
      });
      if (targetFound) return;
    }

    if (!targetFound)
      player.sayL10n(l10n, 'NO_TARGET_FOUND');
    player.sayL10n(l10n, 'NOTHING_SAID');

    return;
  }

  function otherPlayersInRoom(p) {
    if (p)
      return (p.getName() !== player.getName() && p.getLocation() === player.getLocation());
  };

};<commit_msg>Fix logic for determining if target is found and displaying proper messages to player.<commit_after>var l10n_file = __dirname + '/../l10n/commands/whisper.yml';
var l10n = require('../src/l10n')(l10n_file);
var CommandUtil = require('../src/command_util').CommandUtil;
exports.command = function(rooms, items, players, npcs, Commands) {
  return function(args, player) {
    console.log(args);
    args = args.split(' ');
    console.log(args);
    var target = args.shift();
    var msg = args.join(' ');
    var targetFound = true;

    if (args.length > 0) {
      targetFound = false;
      players.eachIf(function(p) {
        return otherPlayersInRoom(p);
      }, function(p) {
        if (p.getName().toLowerCase() == target.toLowerCase()) {
          p.sayL10n(l10n, 'THEY_WHISPER', player.getName(), msg);
          targetFound = true;
        } else
          p.sayL10n(l10n, 'OTHERS_WHISPER', player.getName(), target);
      });
      if (targetFound) {
        player.sayL10n(l10n, 'YOU_WHISPER', target, msg);
        return;
      }
    }

    if (!targetFound)
      player.sayL10n(l10n, 'NO_TARGET_FOUND');
    player.sayL10n(l10n, 'NOTHING_SAID');

    return;
  }

  function otherPlayersInRoom(p) {
    if (p)
      return (p.getName() !== player.getName() && p.getLocation() === player.getLocation());
  };

};<|endoftext|>


<commit_before>/*jshint esversion: 5, browser: true, jquery: true */

//module.exports for usa of node like files in browser
var module = { exports: {} };

//navigation collapse
$(document).ready(function() {
  //init collapsable navbar
  $(".button-collapse").sideNav();
});
<commit_msg>old browser alert<commit_after>/*jshint esversion: 5, browser: true, jquery: true */

//module.exports for usa of node like files in browser
var module = { exports: {} };

//navigation collapse
$(document).ready(function() {
  //init collapsable navbar
  $(".button-collapse").sideNav();
});

//check for old browser and alert
if (typeof Array.prototype.map !== "function") {
  alert("You are using an severely outdated browser and we strongly encourage you to update" +
        "it immediately. Because of that, his website may not work as expected and you may face" +
        "security issues.");
}
<|endoftext|>


<commit_before>'use strict';

function popupView(details) {
    var popUpCtrl = this;
    var modalInstance = popUpCtrl.$uibModal.open({
        component: 'newPurchaserModal',
        windowClass: 'app-modal-window-small',
        keyboard: false,
        resolve: {
            details: function() {
                return (details || {});
            }
        },
        backdrop: 'static'
    });

    modalInstance.result.then(function(data) {
            //data passed when pop up closed.
            if (data && data.action == 'update') {
                console.log(data)
                popUpCtrl.onSelectCallback(data)

            }

        }),
        function(err) {
            console.log('Error in add-brand Modal');
            console.log(err);
        }
}

function PurchaseDetailController($rootScope, $scope, $uibModal, $state, $http, $timeout, checkoutService, moveItemToSaleService) {
    var ctrl = this;
    ctrl.$uibModal = $uibModal;
    ctrl.$state = $state;
    ctrl.itemArr = [];
    ctrl.displayCartBtn = true;
    ctrl.itemCount = 0;
    ctrl.productArr = [];
    ctrl.purchaseDetail = {};
    ctrl.productDetail = {};
    ctrl.totalBill = 0;
    ctrl.totalAmt = 0;
    var totalSum = 0;

    ctrl.init = function() {

        //TODO: Move to run.
        $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
            // $timeout(function(){
            //     isDirty = ctrl.purchaseform.$dirty;

            //   });

            var isDirty = ctrl.purchaseform.$dirty;

            if (isDirty && toState.name != 'warehouse.checkout') {
                var isConfirm = confirm('You have unsaved changes, go back?');

                if (!isConfirm) {
                    event.preventDefault();
                }
            }
        });

        $http({
            url: "purchaser/getPurchasingRelatedInfo",
            method: "GET",
        }).then(function(response) {
            ctrl.productDetails = response.data.result.message.warehouseItems;
            ctrl.purchaseDetails = response.data.result.message.purchaserInfo;
        }).catch(function(err) {
            console.log("error while getting data in get purchaser info");
            console.log(err);
        })

    }

    $scope.$watch(angular.bind(ctrl, function() {
        return ctrl.paidByShop;
    }), function(value) {

        if (ctrl.paidByShop == undefined) {
            ctrl.paidByShop = 0;
        }
        if (ctrl.paidByPrateek == undefined) {
            ctrl.paidByPrateek = 0;
        }
        if (ctrl.paidByBharat == undefined) {
            ctrl.paidByBharat = 0;
        }

        sumOfPayies(ctrl.paidByShop, ctrl.paidByPrateek, ctrl.paidByBharat);
    });
    $scope.$watch(angular.bind(ctrl, function() {
        return ctrl.paidByPrateek;
    }), function(value) {
        if (ctrl.paidByShop == undefined) {
            ctrl.paidByShop = 0;
        }
        if (ctrl.paidByPrateek == undefined) {
            ctrl.paidByPrateek = 0;
        }
        if (ctrl.paidByBharat == undefined) {
            ctrl.paidByBharat = 0;
        }
        sumOfPayies(ctrl.paidByShop, ctrl.paidByPrateek, ctrl.paidByBharat);
    });
    $scope.$watch(angular.bind(ctrl, function() {
        return ctrl.paidByBharat;
    }), function(value) {
        if (ctrl.paidByShop == undefined) {
            ctrl.paidByShop = 0;
        }
        if (ctrl.paidByPrateek == undefined) {
            ctrl.paidByPrateek = 0;
        }
        if (ctrl.paidByBharat == undefined) {
            ctrl.paidByBharat = 0;
        }
        sumOfPayies(ctrl.paidByShop, ctrl.paidByPrateek, ctrl.paidByBharat);
    });
    $scope.$watch(angular.bind(ctrl, function() {
        return ctrl.totalBill;
    }), function(value) {
        if (ctrl.totalBill) {
            if (ctrl.purchaserPrevBal == undefined) {
                ctrl.purchaserPrevBal = 0;
            }
            calculateTotalBill(ctrl.totalBill, ctrl.purchaserPrevBal);
        }
    });
    $scope.$watch(angular.bind(ctrl, function() {
        return ctrl.purchaserPrevBal;
    }), function(value) {
        if (ctrl.purchaserPrevBal) {
            if (ctrl.totalBill == undefined) {
                ctrl.totalBill = 0;
            }
            calculateTotalBill(ctrl.totalBill, ctrl.purchaserPrevBal);
        }
    });

    ctrl.addProduct = function(seller, price, quantity) {

        ctrl.totalPrice = parseInt(quantity) * parseInt(price);
        ctrl.SelectedItem.price = price;
        ctrl.SelectedItem.quantity = quantity;
        ctrl.SelectedItem.totalPrice = ctrl.totalPrice;
        ctrl.productArr.push(ctrl.SelectedItem);
        ctrl.price = "";
        ctrl.qty = "";
        ctrl.productDetail = {};
        ctrl.totalBill = ctrl.totalBill + ctrl.totalPrice;

    };

    ctrl.deleteProduct = function(pdt) {

        ctrl.totalBill = ctrl.totalBill - pdt.totalPrice;
        ctrl.productArr.splice(ctrl.productArr.indexOf(pdt), 1)
    }

    ctrl.onSelectCallback = function(item, model) {

        switch (item.profile.phone.length) {
            case 0:
                ctrl.purchaserNumber1 = "";
                ctrl.purchaserNumber2 = "";
                break;
            case 1:
                ctrl.purchaserNumber1 = item.profile.phone[0] + ",";
                ctrl.purchaserNumber2 = "";
                break;
            case 2:
                ctrl.purchaserNumber1 = item.profile.phone[0] + ",";
                ctrl.purchaserNumber2 = item.profile.phone[1] + ",";
                break;

        }

        ctrl.purchaserName = item.profile.name;
        ctrl.purchaserAddress = item.profile.address + ",";
        ctrl.purchaserPrevBal = item.balance;
        ctrl.purchaserID = item._id;

    };

    ctrl.newPurchaser = function() {
        angular.bind(ctrl, popupView, null)();
    };

    ctrl.onSelectItem = function(item, model) {

        ctrl.SelectedItem = item;
    }

    ctrl.placeOrder = function() {

        ctrl.loader = true;

        ctrl.payment = {
            previousBalance: ctrl.purchaserPrevBal,
            totalAmount: ctrl.totalAmt,
            amountPaid: ctrl.amtPaid,
            currentBalance: ctrl.currentBal,
            paidByShop: ctrl.paidByShop,
            paidByPrateek: ctrl.paidByPrateek,
            paidByBharat: ctrl.paidByBharat
        }
        var obj = {
            purchaser: {id: ctrl.purchaserID, name: ctrl.purchaserName},
            Items: ctrl.productArr,
            payment: ctrl.payment
        }

        $http({
                url: "purchaser/placeOrder",
                method: "POST",
                data: JSON.stringify(obj),
                dataType: JSON

            }).then(function(response) {
                console.log(response)
                ctrl.loader = false;
                ctrl.productArr = [];
                ctrl.purchaserPrevBal = "";
                ctrl.totalAmt = 0;
                ctrl.amtPaid = 0;
                ctrl.currentBal = 0;
                ctrl.totalAmt = 0;
                ctrl.paidByShop = 0;
                ctrl.paidByPrateek = 0;
                ctrl.paidByBharat = 0;
                ctrl.totalBill = 0;
                ctrl.purchaserName = "";
                ctrl.purchaserAddress = "";
                ctrl.purchaserPrevBal = "";
                ctrl.purchaserNumber1 = "";
                ctrl.purchaserNumber2 = "";

            })
            .catch(function(error) {
                console.log("Error while adding brand's varient")
            })
    }

    function sumOfPayies(paidByShop, paidByPrateek, paidByBharat) {
        totalSum = parseInt(paidByShop) + parseInt(paidByPrateek) + parseInt(paidByBharat);
        ctrl.amtPaid = totalSum;
        ctrl.currentBal = ctrl.totalAmt - totalSum;
    }

    function calculateTotalBill(totalBill, purchaserPrevBal){

        ctrl.totalAmt = totalBill + purchaserPrevBal;
    }

    ctrl.init();
}

angular.module('purchaseDetail')
    .component('purchaseDetail', {
        templateUrl: 'warehouse/purchase-details/purchase-details.template.html',
        controller: ['$rootScope', '$scope', '$uibModal', '$state', '$http', '$timeout', 'checkoutService', 'moveItemToSaleService', PurchaseDetailController]
    });
<commit_msg>changes<commit_after>'use strict';

function popupView(details) {
    var popUpCtrl = this;
    var modalInstance = popUpCtrl.$uibModal.open({
        component: 'newPurchaserModal',
        windowClass: 'app-modal-window-small',
        keyboard: false,
        resolve: {
            details: function() {
                return (details || {});
            }
        },
        backdrop: 'static'
    });

    modalInstance.result.then(function(data) {
            //data passed when pop up closed.
            if (data && data.action == 'update') {
                console.log(data)
                popUpCtrl.onSelectCallback(data)

            }

        }),
        function(err) {
            console.log('Error in add-brand Modal');
            console.log(err);
        }
}

function PurchaseDetailController($rootScope, $scope, $uibModal, $state, $http, $timeout, checkoutService, moveItemToSaleService) {
    var ctrl = this;
    ctrl.$uibModal = $uibModal;
    ctrl.$state = $state;
    ctrl.itemArr = [];
    ctrl.displayCartBtn = true;
    ctrl.itemCount = 0;
    ctrl.productArr = [];
    ctrl.purchaseDetail = {};
    ctrl.productDetail = {};
    ctrl.totalBill = 0;
    ctrl.totalAmt = 0;
    ctrl.purchaserPrevBal = 0;
    ctrl.paidByShop = 0;
    ctrl.paidByPrateek = 0;
    ctrl.paidByBharat = 0;

    var totalSum = 0;

    ctrl.init = function() {

        //TODO: Move to run.
        $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
            var isDirty = ctrl.purchaseform.$dirty;

            if (isDirty && toState.name != 'warehouse.checkout') {
                var isConfirm = confirm('You have unsaved changes, go back?');

                if (!isConfirm) {
                    event.preventDefault();
                }
            }
        });

        $http({
            url: "purchaser/getPurchasingRelatedInfo",
            method: "GET",
        }).then(function(response) {
            ctrl.productDetails = response.data.result.message.warehouseItems;
            ctrl.purchaseDetails = response.data.result.message.purchaserInfo;
        }).catch(function(err) {
            console.log("error while getting data in get purchaser info");
            console.log(err);
        })

        // ES5 style property definition.
        Object.defineProperty(ctrl, 'amtPaid', {
         get() {
                return parseFloat(ctrl.paidByShop) + parseFloat(ctrl.paidByPrateek) + parseFloat(ctrl.paidByBharat);
            }
        });

        Object.defineProperty(ctrl, 'totalAmt', {
         get() {
                return parseFloat(ctrl.totalBill) - parseFloat(ctrl.purchaserPrevBal);
            }
        });

        Object.defineProperty(ctrl, 'currentBal', {
         get() {
                return parseFloat(ctrl.totalAmt) - parseFloat(ctrl.amtPaid);
            }
        });

    }

    ctrl.addProduct = function(seller, price, quantity) {

        ctrl.totalPrice = parseInt(quantity) * parseInt(price);
        ctrl.SelectedItem.price = price;
        ctrl.SelectedItem.quantity = quantity;
        ctrl.SelectedItem.totalPrice = ctrl.totalPrice;
        ctrl.productArr.push(ctrl.SelectedItem);
        ctrl.price = "";
        ctrl.qty = "";
        ctrl.productDetail = {};
        ctrl.totalBill = ctrl.totalBill + ctrl.totalPrice;

    };

    ctrl.deleteProduct = function(pdt) {

        ctrl.totalBill = ctrl.totalBill - pdt.totalPrice;
        ctrl.productArr.splice(ctrl.productArr.indexOf(pdt), 1)
    }

    ctrl.onSelectCallback = function(item, model) {

        switch (item.profile.phone.length) {
            case 0:
                ctrl.purchaserNumber1 = "";
                ctrl.purchaserNumber2 = "";
                break;
            case 1:
                ctrl.purchaserNumber1 = item.profile.phone[0] + ",";
                ctrl.purchaserNumber2 = "";
                break;
            case 2:
                ctrl.purchaserNumber1 = item.profile.phone[0] + ",";
                ctrl.purchaserNumber2 = item.profile.phone[1] + ",";
                break;

        }

        ctrl.purchaserName = item.profile.name;
        ctrl.purchaserAddress = item.profile.address + ",";
        ctrl.purchaserPrevBal = item.balance;
        ctrl.purchaserID = item._id;

    };

    ctrl.newPurchaser = function() {
        angular.bind(ctrl, popupView, null)();
    };

    ctrl.onSelectItem = function(item, model) {

        ctrl.SelectedItem = item;
    }

    ctrl.placeOrder = function() {

        ctrl.loader = true;

        ctrl.payment = {
            previousBalance: ctrl.purchaserPrevBal,
            totalAmount: ctrl.totalAmt,
            amountPaid: ctrl.amtPaid,
            currentBalance: ctrl.currentBal,
            paidByShop: ctrl.paidByShop,
            paidByPrateek: ctrl.paidByPrateek,
            paidByBharat: ctrl.paidByBharat
        }
        var obj = {
            purchaser: {id: ctrl.purchaserID, name: ctrl.purchaserName},
            Items: ctrl.productArr,
            payment: ctrl.payment
        }

        $http({
                url: "purchaser/placeOrder",
                method: "POST",
                data: JSON.stringify(obj),
                dataType: JSON

            }).then(function(response) {
                console.log(response)
                ctrl.loader = false;

            })
            .catch(function(error) {
                console.log("Error while adding brand's varient")
            })
    }

    function sumOfPayies(paidByShop, paidByPrateek, paidByBharat) {
    }

    function calculateTotalBill(totalBill, purchaserPrevBal){

        ctrl.totalAmt = totalBill + purchaserPrevBal;
    }

    ctrl.init();
}

angular.module('purchaseDetail')
    .component('purchaseDetail', {
        templateUrl: 'warehouse/purchase-details/purchase-details.template.html',
        controller: ['$rootScope', '$scope', '$uibModal', '$state', '$http', '$timeout', 'checkoutService', 'moveItemToSaleService', PurchaseDetailController]
    });
<|endoftext|>