<commit_before>'use strict';

const Filter = require('broccoli-persistent-filter');
const CLIEngine = require('eslint').CLIEngine;
const defaultsDeep = require('lodash.defaultsdeep');
const md5Hex = require('md5-hex');
const stringify = require('json-stable-stringify');
const path = require('path');
const concat = require('broccoli-concat');

const isString = require('./is-string');
const getResultSeverity = require('./get-result-severity');
const testGenerators = require('./test-generators');
const testGeneratorNames = Object.keys(testGenerators);

const FACTORY_METHOD_USED = Symbol('create() factory method was used');

function resolveInputDirectory(inputNode) {
  if (typeof inputNode === 'string') {
    return inputNode;
  }

  // eslint-disable-next-line no-underscore-dangle
  const nodeInfo = inputNode.__broccoliGetInfo__();

  if (nodeInfo.nodeType === 'source') {
    return nodeInfo.sourceDirectory;
  }

  if (nodeInfo.inputNodes.length > 1) {
    // eslint-disable-next-line max-len
    throw new Error('EslintValidationFilter can only handle one:* broccoli nodes, but part of the given input pipeline is a many:* node. (broccoli-merge-trees is an example of a many:* node) Please perform many:* operations after linting.');
  }

  return resolveInputDirectory(nodeInfo.inputNodes[0]);
}

/**
 * Uses the content of each file in a given node and runs eslint validation on it.
 * @param {Object} inputNode Node from broccoli.makeTree
 * @param {{config: String, rulesdir: String, format: String}} options Filter options
 * @returns {EslintValidationFilter} Filter obconfig @constructor
 */
function EslintValidationFilter(inputNode, options) {
  if (!(this instanceof EslintValidationFilter)) {
    return new EslintValidationFilter(inputNode, options);
  }

  let _console = options.console || console;

  if (!options[FACTORY_METHOD_USED]) {
    _console.log('[broccoli-lint-eslint] DEPRECATION: Please use the create() factory method instead of ' +
      'calling ESLint() directly or using new ESLint()');
  }

  options = defaultsDeep({}, options, {
    persist: true,
    extensions: ['js'],
    options: {
      ignore: true,
    },
  });

  this.extensions = options.extensions;

  // call base class constructor
  Filter.call(this, inputNode, options);

  this.internalOptions = options;

  // set formatter
  if (typeof this.internalOptions.format === 'function') {
    this.formatter = this.internalOptions.format;
  } else {
    // eslint-disable-next-line global-require
    this.formatter = require(this.internalOptions.format || 'eslint/lib/formatters/stylish');
  }

  this.console = _console;

  this.cli = new CLIEngine(options.options);

  this.eslintrc = resolveInputDirectory(inputNode);

  if (isString(this.internalOptions.testGenerator)) {
    this.testGenerator = testGenerators[this.internalOptions.testGenerator];
    if (this.internalOptions.group && this.testGenerator) {
      this.testGenerator = this.testGenerator.testOnly;
    }
    if (!this.testGenerator) {
      throw new Error(`Could not find '${this.internalOptions.testGenerator}' test generator.`);
    }
  } else {
    this.testGenerator = this.internalOptions.testGenerator;
  }

  if (this.testGenerator) {
    this.targetExtension = 'lint-test.js';
  }
}

module.exports = EslintValidationFilter;
EslintValidationFilter.prototype = Object.create(Filter.prototype);
EslintValidationFilter.prototype.constructor = EslintValidationFilter;
EslintValidationFilter.prototype.targetExtension = 'js';

EslintValidationFilter.prototype.baseDir = function baseDir() {
  return path.join(__dirname, '..');
};

EslintValidationFilter.prototype.cacheKeyProcessString = function cacheKeyProcessString(content, relativePath) {
  function functionStringifier(key, value) {
    if (typeof value === 'function') {
      return value.toString();
    }
    return value;
  }

  const filePath = path.join(this.eslintrc, relativePath);
  const isIgnoredFile = this.cli.isPathIgnored(filePath);

  return md5Hex([
    content,
    relativePath,
    isIgnoredFile.toString(),
    stringify(this.internalOptions, { replacer: functionStringifier }),
    stringify(this.cli.getConfigForFile(filePath))
  ]);
};

EslintValidationFilter.prototype.getDestFilePath = function getDestFilePath(relativePath) {
  //This method gets called for all files in the tree, so we call the superclass to filter
  //based on the extensions property.
  const filterPath = Filter.prototype.getDestFilePath.call(this, relativePath);
  const fullPath = path.join(this.eslintrc, relativePath);

  if (filterPath && !this.cli.isPathIgnored(fullPath)) {
    return filterPath;
  } else {
    return null;
  }
};

EslintValidationFilter.prototype.processString = function processString(content, relativePath) {
  // verify file content
  const configPath = path.join(this.eslintrc, relativePath);
  const report = this.cli.executeOnText(content, configPath);

  const toCache = { report, output: content };

  if (this.testGenerator && Array.isArray(report.results)) {
    const result = report.results[0] || {};
    const messages = result.messages || [];

    toCache.output = this.testGenerator(relativePath, messages, result);
  }

  return toCache;
};

/**
 * Post-process the filtered output, calculating the result severity from the report
 * if the option to `throwOnError` has been set
 *
 * @param {Object} results A results object returned from `processString`
 * @param {Object} results.report The report returned from this.cli.executeOnText()
 * @param {string} results.output The original file content passed to `processString` -- or the
 *      result of executing the a provided `testGenerator` function on the `report`
 *
 * @returns {Object} An object with an `.output` property, which will be
 *    used as the emitted file contents
 */
EslintValidationFilter.prototype.postProcess = function postProcess(results /* , relativePath */) {
  let report = results.report;

  // if verification has result
  if (report.results.length &&
      report.results[0].messages.length) {

    // log formatter output
    this.console.log(this.formatter(report.results));

    const throwOnWarn = !!this.internalOptions.throwOnWarn;
    const throwOnError = !!this.internalOptions.throwOnError;

    if (throwOnWarn || throwOnError) {
      const resultSeverity = getResultSeverity(report.results[0].messages);

      if (resultSeverity === 1 && throwOnWarn) {
        throw new Error('rules violation with `warn` severity level');
      }

      if (resultSeverity >= 2 && (throwOnWarn || throwOnError)) {
        throw new Error('rules violation with `error` severity level');
      }
    }
  }

  return { output: results.output };
};

/**
 * Factory function that allows to return something different
 * instead of a single EslintValidationFilter.
 *
 * @experimental
 */
EslintValidationFilter.create = function(inputNode, options) {
  options = options || {};
  options[FACTORY_METHOD_USED] = true;

  if (!options.group) {
    return new EslintValidationFilter(inputNode, options);
  }

  if (typeof options.testGenerator !== 'string' || testGeneratorNames.indexOf(options.testGenerator) === -1) {
    throw new Error(`The "group" options can only be used with a "testGenerator" option of: ${testGeneratorNames}`);
  }

  let testGenerator = testGenerators[options.testGenerator];

  let header = testGenerator.header(options.group);
  let footer = testGenerator.footer();

  let eslint = new EslintValidationFilter(inputNode, options);

  return concat(eslint, {
    outputFile: `/${options.group}.lint-test.js`,
    header,
    inputFiles: ['**/*.lint-test.js'],
    footer,
    sourceMapConfig: { enabled: false },
    allowNone: true,
  });
};
<commit_msg>Prevent FACTORY_METHOD_USED Symbol from leaking<commit_after>'use strict';

const Filter = require('broccoli-persistent-filter');
const CLIEngine = require('eslint').CLIEngine;
const defaultsDeep = require('lodash.defaultsdeep');
const md5Hex = require('md5-hex');
const stringify = require('json-stable-stringify');
const path = require('path');
const concat = require('broccoli-concat');

const isString = require('./is-string');
const getResultSeverity = require('./get-result-severity');
const testGenerators = require('./test-generators');
const testGeneratorNames = Object.keys(testGenerators);

const FACTORY_METHOD_USED = Symbol('create() factory method was used');

function resolveInputDirectory(inputNode) {
  if (typeof inputNode === 'string') {
    return inputNode;
  }

  // eslint-disable-next-line no-underscore-dangle
  const nodeInfo = inputNode.__broccoliGetInfo__();

  if (nodeInfo.nodeType === 'source') {
    return nodeInfo.sourceDirectory;
  }

  if (nodeInfo.inputNodes.length > 1) {
    // eslint-disable-next-line max-len
    throw new Error('EslintValidationFilter can only handle one:* broccoli nodes, but part of the given input pipeline is a many:* node. (broccoli-merge-trees is an example of a many:* node) Please perform many:* operations after linting.');
  }

  return resolveInputDirectory(nodeInfo.inputNodes[0]);
}

/**
 * Uses the content of each file in a given node and runs eslint validation on it.
 * @param {Object} inputNode Node from broccoli.makeTree
 * @param {{config: String, rulesdir: String, format: String}} options Filter options
 * @returns {EslintValidationFilter} Filter obconfig @constructor
 */
function EslintValidationFilter(inputNode, options) {
  if (!(this instanceof EslintValidationFilter)) {
    return new EslintValidationFilter(inputNode, options);
  }

  let _console = options.console || console;

  if (!options[FACTORY_METHOD_USED]) {
    _console.log('[broccoli-lint-eslint] DEPRECATION: Please use the create() factory method instead of ' +
      'calling ESLint() directly or using new ESLint()');
  }

  options = defaultsDeep({}, options, {
    persist: true,
    extensions: ['js'],
    options: {
      ignore: true,
    },
  });

  this.extensions = options.extensions;

  // call base class constructor
  Filter.call(this, inputNode, options);

  this.internalOptions = options;

  // set formatter
  if (typeof this.internalOptions.format === 'function') {
    this.formatter = this.internalOptions.format;
  } else {
    // eslint-disable-next-line global-require
    this.formatter = require(this.internalOptions.format || 'eslint/lib/formatters/stylish');
  }

  this.console = _console;

  this.cli = new CLIEngine(options.options);

  this.eslintrc = resolveInputDirectory(inputNode);

  if (isString(this.internalOptions.testGenerator)) {
    this.testGenerator = testGenerators[this.internalOptions.testGenerator];
    if (this.internalOptions.group && this.testGenerator) {
      this.testGenerator = this.testGenerator.testOnly;
    }
    if (!this.testGenerator) {
      throw new Error(`Could not find '${this.internalOptions.testGenerator}' test generator.`);
    }
  } else {
    this.testGenerator = this.internalOptions.testGenerator;
  }

  if (this.testGenerator) {
    this.targetExtension = 'lint-test.js';
  }
}

module.exports = EslintValidationFilter;
EslintValidationFilter.prototype = Object.create(Filter.prototype);
EslintValidationFilter.prototype.constructor = EslintValidationFilter;
EslintValidationFilter.prototype.targetExtension = 'js';

EslintValidationFilter.prototype.baseDir = function baseDir() {
  return path.join(__dirname, '..');
};

EslintValidationFilter.prototype.cacheKeyProcessString = function cacheKeyProcessString(content, relativePath) {
  function functionStringifier(key, value) {
    if (typeof value === 'function') {
      return value.toString();
    }
    return value;
  }

  const filePath = path.join(this.eslintrc, relativePath);
  const isIgnoredFile = this.cli.isPathIgnored(filePath);

  return md5Hex([
    content,
    relativePath,
    isIgnoredFile.toString(),
    stringify(this.internalOptions, { replacer: functionStringifier }),
    stringify(this.cli.getConfigForFile(filePath))
  ]);
};

EslintValidationFilter.prototype.getDestFilePath = function getDestFilePath(relativePath) {
  //This method gets called for all files in the tree, so we call the superclass to filter
  //based on the extensions property.
  const filterPath = Filter.prototype.getDestFilePath.call(this, relativePath);
  const fullPath = path.join(this.eslintrc, relativePath);

  if (filterPath && !this.cli.isPathIgnored(fullPath)) {
    return filterPath;
  } else {
    return null;
  }
};

EslintValidationFilter.prototype.processString = function processString(content, relativePath) {
  // verify file content
  const configPath = path.join(this.eslintrc, relativePath);
  const report = this.cli.executeOnText(content, configPath);

  const toCache = { report, output: content };

  if (this.testGenerator && Array.isArray(report.results)) {
    const result = report.results[0] || {};
    const messages = result.messages || [];

    toCache.output = this.testGenerator(relativePath, messages, result);
  }

  return toCache;
};

/**
 * Post-process the filtered output, calculating the result severity from the report
 * if the option to `throwOnError` has been set
 *
 * @param {Object} results A results object returned from `processString`
 * @param {Object} results.report The report returned from this.cli.executeOnText()
 * @param {string} results.output The original file content passed to `processString` -- or the
 *      result of executing the a provided `testGenerator` function on the `report`
 *
 * @returns {Object} An object with an `.output` property, which will be
 *    used as the emitted file contents
 */
EslintValidationFilter.prototype.postProcess = function postProcess(results /* , relativePath */) {
  let report = results.report;

  // if verification has result
  if (report.results.length &&
      report.results[0].messages.length) {

    // log formatter output
    this.console.log(this.formatter(report.results));

    const throwOnWarn = !!this.internalOptions.throwOnWarn;
    const throwOnError = !!this.internalOptions.throwOnError;

    if (throwOnWarn || throwOnError) {
      const resultSeverity = getResultSeverity(report.results[0].messages);

      if (resultSeverity === 1 && throwOnWarn) {
        throw new Error('rules violation with `warn` severity level');
      }

      if (resultSeverity >= 2 && (throwOnWarn || throwOnError)) {
        throw new Error('rules violation with `error` severity level');
      }
    }
  }

  return { output: results.output };
};

/**
 * Factory function that allows to return something different
 * instead of a single EslintValidationFilter.
 *
 * @experimental
 */
EslintValidationFilter.create = function(inputNode, _options) {
  let options = Object.assign({}, _options, {
    [FACTORY_METHOD_USED]: true
  });

  if (!options.group) {
    return new EslintValidationFilter(inputNode, options);
  }

  if (typeof options.testGenerator !== 'string' || testGeneratorNames.indexOf(options.testGenerator) === -1) {
    throw new Error(`The "group" options can only be used with a "testGenerator" option of: ${testGeneratorNames}`);
  }

  let testGenerator = testGenerators[options.testGenerator];

  let header = testGenerator.header(options.group);
  let footer = testGenerator.footer();

  let eslint = new EslintValidationFilter(inputNode, options);

  return concat(eslint, {
    outputFile: `/${options.group}.lint-test.js`,
    header,
    inputFiles: ['**/*.lint-test.js'],
    footer,
    sourceMapConfig: { enabled: false },
    allowNone: true,
  });
};
<|endoftext|>


<commit_before>/*jslint indent: 2*/
/*global require: true, module: true*/
(function () {
  'use strict';

  var InvalidInputError = require('./input-error.js'),
    transformationFunctions = require('./transforms'),
    transformationKeys = require('./keys'),
    regex = /^(\d*)d(\d+|\%)(([\+\-\/\*bw])(\d+))?$/,
    roll;

  roll = function (random) {
    this.random = random || function () {
      return Math.random();
    };
  };

  roll.prototype.validate = function (s) {
    return regex.test(s);
  };

  roll.prototype.parse = function (s) {
    if (!this.validate(s)) {
      throw new InvalidInputError(s);
    }

    var match = regex.exec(s),
      quantity = match[1], // 2d20+3 => 2
      sides = match[2], // 2d20+3 => 20
      hasTransformation = !!match[3], // 2d20+3 => true
      operator,
      transformationParameter,
      transforms = [],
      opIndex = 0,
      segments = s.split(/[\+\-]/);

    if (segments[0].indexOf('b') > -1) {
      transforms.push(transformationKeys[match[4]](parseInt(match[5], 10)));
    }
    for (var seg = 1; seg < segments.length; seg++) {
      opIndex += segments[seg - 1].length;
      operator = s[opIndex]; // 2d20+3 => "+"
      opIndex += 1;
      transformationParameter = segments[seg]; // 2d20+3 => 3
      if (transformationParameter.indexOf('d') > -1) {
        transforms.push(transformationKeys[operator](parseInt(this.roll(transformationParameter).result, 10)));
      } else {
        transforms.push(transformationKeys[operator](parseInt(transformationParameter, 10)));
      }
    }

    return {
      quantity: quantity ? parseInt(quantity, 10) : 1,
      sides: sides === '%' ? 100 : parseInt(sides, 10),
      transformations: hasTransformation || transforms.length > 0 ? transforms.length > 0 ? transforms : transformationKeys[match[4]](parseInt(match[5], 10)) : ['sum'],
      toString: function () {
        return s;
      }
    };
  };

  roll.prototype.roll = function (input) {
    if (!input) {
      throw new InvalidInputError();
    } else if (typeof input === 'string') {
      input = this.parse(input);
    }

    var rolled = [],
     calculations = [];

    while (rolled.length < input.quantity) {
      rolled.push(Math.floor((this.random() * input.sides) + 1));
    }

    calculations = input.transformations.reduce(function (previous, transformation) {
      var transformationFunction,
        transformationAdditionalParameter;

      if (typeof transformation === 'function') { // lets you pass something custom in
        transformationFunction = transformation;
      } else if (typeof transformation === 'string') { // "sum"
        transformationFunction = transformationFunctions[transformation];
      } else if (transformation instanceof Array) { // ["add", 3]
        transformationFunction = transformationFunctions[transformation[0]]; // fn for "add"
        transformationAdditionalParameter = transformation[1]; // 3
      }

      previous.unshift(transformationFunction(previous[0], transformationAdditionalParameter));
      return previous;
    }, [rolled]);

    return {
      input: input,
      calculations: calculations,
      rolled: calculations[calculations.length - 1],
      result: calculations[0]
    };
  };

  module.exports = roll;
  module.exports.InvalidInputError = InvalidInputError;

}());

<commit_msg>experimental final sum for transforms array<commit_after>/*jslint indent: 2*/
/*global require: true, module: true*/
(function () {
  'use strict';

  var InvalidInputError = require('./input-error.js'),
    transformationFunctions = require('./transforms'),
    transformationKeys = require('./keys'),
    regex = /^(\d*)d(\d+|\%)(([\+\-\/\*bw])(\d+))?$/,
    roll;

  roll = function (random) {
    this.random = random || function () {
      return Math.random();
    };
  };

  roll.prototype.validate = function (s) {
    return regex.test(s);
  };

  roll.prototype.parse = function (s) {
    if (!this.validate(s)) {
      throw new InvalidInputError(s);
    }

    var match = regex.exec(s),
      quantity = match[1], // 2d20+3 => 2
      sides = match[2], // 2d20+3 => 20
      hasTransformation = !!match[3], // 2d20+3 => true
      operator,
      transformationParameter,
      transforms = [],
      opIndex = 0,
      segments = s.split(/[\+\-]/);

    if (segments[0].indexOf('b') > -1) {
      transforms.push(transformationKeys[match[4]](parseInt(match[5], 10)));
    }
    for (var seg = 1; seg < segments.length; seg++) {
      opIndex += segments[seg - 1].length;
      operator = s[opIndex]; // 2d20+3 => "+"
      opIndex += 1;
      transformationParameter = segments[seg]; // 2d20+3 => 3
      if (transformationParameter.indexOf('d') > -1) {
        transforms.push(transformationKeys[operator](parseInt(this.roll(transformationParameter).result, 10)));
      } else {
        transforms.push(transformationKeys[operator](parseInt(transformationParameter, 10)));
      }
    }
    if (transforms.length > 0){
      transforms.push('sum');
    }
    return {
      quantity: quantity ? parseInt(quantity, 10) : 1,
      sides: sides === '%' ? 100 : parseInt(sides, 10),
      transformations: hasTransformation || transforms.length > 0 ? transforms.length > 0 ? transforms : transformationKeys[match[4]](parseInt(match[5], 10)) : ['sum'],
      toString: function () {
        return s;
      }
    };
  };

  roll.prototype.roll = function (input) {
    if (!input) {
      throw new InvalidInputError();
    } else if (typeof input === 'string') {
      input = this.parse(input);
    }

    var rolled = [],
     calculations = [];

    while (rolled.length < input.quantity) {
      rolled.push(Math.floor((this.random() * input.sides) + 1));
    }

    calculations = input.transformations.reduce(function (previous, transformation) {
      var transformationFunction,
        transformationAdditionalParameter;

      if (typeof transformation === 'function') { // lets you pass something custom in
        transformationFunction = transformation;
      } else if (typeof transformation === 'string') { // "sum"
        transformationFunction = transformationFunctions[transformation];
      } else if (transformation instanceof Array) { // ["add", 3]
        transformationFunction = transformationFunctions[transformation[0]]; // fn for "add"
        transformationAdditionalParameter = transformation[1]; // 3
      }

      previous.unshift(transformationFunction(previous[0], transformationAdditionalParameter));
      return previous;
    }, [rolled]);

    return {
      input: input,
      calculations: calculations,
      rolled: calculations[calculations.length - 1],
      result: calculations[0]
    };
  };

  module.exports = roll;
  module.exports.InvalidInputError = InvalidInputError;

}());

<|endoftext|>


<commit_before>/*
 * NTwitBot - index.js
 * Copyright (C) 2016 Jordan Sne
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/* jshint esversion:6, node: true */

const TwitterModule  = require("twitter");
      action_handler = require('action.js');
      data_handler   = require('data.js');
      event_handler  = require('event.js');

const secretData = JSON.parse('config/secret.json');
      twitterPkg = new TwitterModule(secretData);

<commit_msg>Correct require statements<commit_after>/*
 * NTwitBot - index.js
 * Copyright (C) 2016 Jordan Sne
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/* jshint esversion:6, node: true */

const TwitterModule  = require('twitter'),
      Action         = require('./action.js'),
      Data           = require('./data.js'),
      Event          = require('./event.js');

const secretData = JSON.parse('config/secret.json');
      twitterPkg = new TwitterModule(secretData);

<|endoftext|>


<commit_before>/*
 * catbox-couchbase
 * Copyright (c) 2015 Fatih Cetinkaya (http://github.com/cmfatih/catbox-couchbase)
 * For the full copyright and license information, please view the LICENSE.txt file.
 */

/* jslint node: true */
'use strict';

var couchbase    = require('couchbase'),
    util         = require('util'),
    EventEmitter = require('events').EventEmitter;

// Init the module
module.exports = function(options) {

  var serverOptions    = options || {},
      serverLocations  = '127.0.0.1:8091', // cluster locations
      serverBucket     = 'default',        // bucket name
      serverPartition, // bucket name
      cluster,         // cluster object
      bucket,          // bucket object
      eEmitter,        // event emitter
      flags;           // flags (e.g. `{flags: {debug: ['events']}}`)

  var TTL_MAX = 1000*60*60*24*30; // 2592000000 milliseconds = 30 days

  // Initialize event emitter
  var EEmitter = function EEmitter() { EventEmitter.call(this); };
  util.inherits(EEmitter, EventEmitter);
  eEmitter = new EEmitter();
  eEmitter.on('error', function() { }); // prevent unhandled error event

  // Server options
  // REF: http://docs.couchbase.com/sdk-api/couchbase-node-client-2.0.8/index.html
  //      http://docs.couchbase.com/developer/dev-guide-3.0/doc-expiration.html
  if(serverOptions.location) {
    serverLocations = (serverOptions.location instanceof Array) ? serverOptions.location.join(',') : ''+serverOptions.location;
  }

  if(typeof serverOptions.bucket === 'string' && serverOptions.bucket) {
    serverBucket = serverOptions.bucket;
  }

  if(typeof serverOptions.partition === 'string' && serverOptions.partition !== 'NONE') {
    serverPartition = serverOptions.partition;
  }

  // Flags
  flags = (serverOptions.flags && typeof serverOptions.flags === 'object' && serverOptions.flags) || {};

  // Creates a connection to the cache server
  var start = function start(callback) {

    if(typeof callback !== 'function') {
      throw new Error('invalid callback function');
    }

    // If there is an instance then
    if(bucket) {
      return callback();
    }

    // Create instance
    cluster = new couchbase.Cluster(util.format('couchbase://%s', serverLocations));
    bucket  = cluster.openBucket(serverBucket, function(err) {
      if(err) {
        throw new Error(util.format('bucket %s/pools/default/buckets/%s could not be opened', serverLocations, serverBucket));
      }

      // Set events
      bucket.on('connect', function() {
        eEmitter.emit('connect', util.format('connected to %s bucket', serverBucket));
      });
      bucket.on('error', function(err) {
        eEmitter.emit('error', err);
      });
      eEmitter.emit('start', util.format('started for %s/pools/default/buckets/%s', serverLocations, serverBucket));

      return callback();
    });
  };

  // Ends the cache server connection
  var stop = function stop() {
    if(bucket) {
      bucket.disconnect(); // end connection
      bucket = null;       // cleanup

      eEmitter.emit('stop', util.format('stopped for %s/pools/default/buckets/%s', serverLocations, serverBucket));
    }
  };

  // Returns whether the cache server is ready or not
  var isReady = function isReady() {
    return (!!bucket);
  };

  // Validates segment name
  var validateSegmentName = function validateSegmentName(name) {
    if(!name || name.indexOf('\n') !== -1 || name.indexOf('\0') !== -1 || name.indexOf('\t') !== -1 || name.indexOf(' ') !== -1) {
      return new Error('invalid segment name');
    }
    return null; // catbox wants null
  };

  // Gets a value for the given key
  var get = function get(key, callback) {

    if(typeof callback !== 'function') {
      throw new Error('invalid callback function');
    }
    else if(!isReady()) {
      return callback(new Error('cache server is not ready'));
    }

    // Get cache value
    var keyF = generateKey(key);

    bucket.get(keyF, function(err, result) {

      if(err) {
        // If error code is not;
        // 13 (The key does not exist on the server)
        // 53 (An empty key was passed to an operation)
        // then
        if(err.code !== 13 && err.code !== 53) {
          return callback(err);
        }
      }

      eEmitter.emit('get', keyF);

      // No result then no cache
      if(!result || !result.value) {
        return callback(null, null);
      }

      // Parse cache content
      var envelope = null;
      try {
        envelope = JSON.parse(result.value);
      }
      catch(e) {
        eEmitter.emit('error', e);
        return callback(e);
      }

      // Check cache content
      if(!envelope || !envelope.item || !envelope.stored) {
        return callback(new Error('invalid cache content'));
      }

      return callback(null, envelope);
    });
  };

  // Sets a value for the given key
  var set = function set(key, value, ttl, callback) {

    if(typeof callback !== 'function') {
      throw new Error('invalid callback function');
    }
    else if(!key) {
      return callback(new Error('invalid cache key'));
    }
    else if(typeof ttl !== 'number') {
      return callback(new Error('invalid ttl'));
    }
    else if(!isReady()) {
      return callback(new Error('cache server is not ready'));
    }

    // Prepare cache content
    var envelope = {item: value, stored: Date.now(), ttl: ttl},
        envelopeStr;

    try {
      envelopeStr = JSON.stringify(envelope);
    }
    catch(e) {
      eEmitter.emit('error', e);
      return callback(e);
    }

    // Set cache
    var keyF   = generateKey(key),
        expiry = Math.max(1, Math.floor(envelope.ttl / 1000)); // min is 1 sec

    // If ttl is greater than max ttl
    if(envelope.ttl > TTL_MAX) {
      // Calculate timestamp
      // REF: http://docs.couchbase.com/developer/dev-guide-3.0/doc-expiration.html
      expiry = Math.max(1, Math.floor((new Date(envelope.stored + envelope.ttl).getTime()) / 1000)); // min is 1 sec
    }

    bucket.upsert(keyF, envelopeStr, {expiry: expiry}, function(err) {
      if(err) {
        return callback(err);
      }

      eEmitter.emit('set', keyF);

      return callback();
    });
  };

  // Remove the given key
  var drop = function drop(key, callback) {

    if(typeof callback !== 'function') {
      throw new Error('invalid callback function');
    }
    else if(!key) {
      return callback(new Error('invalid cache key'));
    }
    else if(!isReady()) {
      return callback(new Error('cache server is not ready'));
    }

    // Drop cache
    var keyF = generateKey(key);

    bucket.remove(keyF, function(err, res) {
      if(err) {
        if(err.code !== 13) {
          return callback(err);
        }
      }

      eEmitter.emit('drop', keyF, res);

      return callback();
    });
  };

  // Generates keys
  var generateKey = function generateKey(key) {
    return (serverPartition ? encodeURI(serverPartition)+':' : '') + (key && key.segment ? encodeURI(key.segment) : '') + (key && key.id ? ':'+encodeURI(key.id) : '');
  };

  // Allows hook on events
  var on = function on(event, callback) {
    eEmitter.addListener(event, callback);
  };

  // Debug
  //flags = {debug: ['events']}; // for debug
  if(flags.debug instanceof Array) {
    // If events in debug flags
    if(flags.debug.indexOf('events') !== -1) {
      // Log all the events
      ['start', 'stop', 'get', 'set', 'drop', 'connect', 'error'].forEach(function(event) {
        on(event, function(data) {
          console.log('\nDebug: ' + JSON.stringify({event: event, data:data}) + '\n');
        });
      });
    }
  }

  // Return
  return {
    start:               start,
    stop:                stop,
    isReady:             isReady,
    validateSegmentName: validateSegmentName,
    get:                 get,
    set:                 set,
    drop:                drop,
    generateKey:         generateKey,
    settings:            serverOptions,
    on:                  on
  };
};<commit_msg>Add isMock flag and key checks<commit_after>/*
 * catbox-couchbase
 * Copyright (c) 2015 Fatih Cetinkaya (http://github.com/cmfatih/catbox-couchbase)
 * For the full copyright and license information, please view the LICENSE.txt file.
 */

/* jslint node: true */
'use strict';

var couchbase    = require('couchbase'),
    util         = require('util'),
    EventEmitter = require('events').EventEmitter;

// Init the module
module.exports = function(options) {

  var serverOptions    = options || {},
      serverLocations  = '127.0.0.1:8091', // cluster locations
      serverBucket     = 'default',        // bucket name
      serverPartition, // bucket name
      cluster,         // cluster object
      bucket,          // bucket object
      eEmitter,        // event emitter
      flags;           // flags (e.g. `{flags: {debug: ['events']}}`)

  var TTL_MAX = 1000*60*60*24*30; // 2592000000 milliseconds = 30 days

  // Initialize event emitter
  var EEmitter = function EEmitter() { EventEmitter.call(this); };
  util.inherits(EEmitter, EventEmitter);
  eEmitter = new EEmitter();
  eEmitter.on('error', function() { }); // prevent unhandled error event

  // Server options
  // REF: http://docs.couchbase.com/sdk-api/couchbase-node-client-2.0.8/index.html
  //      http://docs.couchbase.com/developer/dev-guide-3.0/doc-expiration.html
  if(serverOptions.location) {
    serverLocations = (serverOptions.location instanceof Array) ? serverOptions.location.join(',') : ''+serverOptions.location;
  }

  if(typeof serverOptions.bucket === 'string' && serverOptions.bucket) {
    serverBucket = serverOptions.bucket;
  }

  if(typeof serverOptions.partition === 'string' && serverOptions.partition !== 'NONE') {
    serverPartition = serverOptions.partition;
  }

  // Flags
  flags = (serverOptions.flags && typeof serverOptions.flags === 'object' && serverOptions.flags) || {};

  // If mock flag is true then
  if(flags.isMock) {
    couchbase = require('couchbase').Mock; // use mock
  }

  // Creates a connection to the cache server
  var start = function start(callback) {

    if(typeof callback !== 'function') {
      throw new Error('invalid callback function');
    }

    // If there is an instance then
    if(bucket) {
      return callback();
    }

    // Create instance
    cluster = new couchbase.Cluster(util.format('couchbase://%s', serverLocations));
    bucket  = cluster.openBucket(serverBucket, function(err) {
      if(err) {
        throw new Error(util.format('bucket %s/pools/default/buckets/%s could not be opened', serverLocations, serverBucket));
      }

      // Set events
      bucket.on('connect', function() {
        eEmitter.emit('connect', util.format('connected to %s bucket', serverBucket));
      });
      bucket.on('error', function(err) {
        eEmitter.emit('error', err);
      });
      eEmitter.emit('start', util.format('started for %s/pools/default/buckets/%s', serverLocations, serverBucket));

      return callback();
    });
  };

  // Ends the cache server connection
  var stop = function stop() {
    if(bucket) {
      bucket.disconnect(); // end connection
      bucket = null;       // cleanup

      eEmitter.emit('stop', util.format('stopped for %s/pools/default/buckets/%s', serverLocations, serverBucket));
    }
  };

  // Returns whether the cache server is ready or not
  var isReady = function isReady() {
    return (!!bucket);
  };

  // Validates segment name
  var validateSegmentName = function validateSegmentName(name) {
    if(!name || name.indexOf('\n') !== -1 || name.indexOf('\0') !== -1 || name.indexOf('\t') !== -1 || name.indexOf(' ') !== -1) {
      return new Error('invalid segment name');
    }
    return null; // catbox wants null
  };

  // Gets a value for the given key
  var get = function get(key, callback) {

    if(typeof callback !== 'function') {
      throw new Error('invalid callback function');
    }
    else if(!isReady()) {
      return callback(new Error('cache server is not ready'));
    }

    // If key is falsy then
    if(!key) {
      return callback(null, null); // return null like catbox
    }

    // Get cache value
    var keyF = generateKey(key);

    if(!keyF) {
      return callback(new Error('invalid key'));
    }

    bucket.get(keyF, function(err, result) {

      if(err) {
        // If error code is not 13 (The key does not exist on the server) then
        if(err.code !== 13) {
          return callback(err);
        }
      }

      eEmitter.emit('get', keyF);

      // No result then no cache
      if(!result || !result.value) {
        return callback(null, null);
      }

      // Parse cache content
      var envelope = null;
      try {
        envelope = JSON.parse(result.value);
      }
      catch(e) {
        eEmitter.emit('error', e);
        return callback(e);
      }

      // Check cache content
      if(!envelope || !envelope.item || !envelope.stored) {
        return callback(new Error('invalid cache content'));
      }

      return callback(null, envelope);
    });
  };

  // Sets a value for the given key
  var set = function set(key, value, ttl, callback) {

    if(typeof callback !== 'function') {
      throw new Error('invalid callback function');
    }
    else if(!key) {
      return callback(new Error('invalid key'));
    }
    else if(typeof ttl !== 'number') {
      return callback(new Error('invalid ttl'));
    }
    else if(!isReady()) {
      return callback(new Error('cache server is not ready'));
    }

    // Prepare cache content
    var envelope = {item: value, stored: Date.now(), ttl: ttl},
        envelopeStr;

    try {
      envelopeStr = JSON.stringify(envelope);
    }
    catch(e) {
      eEmitter.emit('error', e);
      return callback(e);
    }

    // Set cache
    var keyF = generateKey(key);

    if(!keyF) {
      return callback(new Error('invalid key'));
    }

    // Expiry
    var expiry = Math.max(1, Math.floor(envelope.ttl / 1000)); // min is 1 sec
    // If ttl is greater than max ttl
    if(envelope.ttl > TTL_MAX) {
      // Calculate timestamp
      // REF: http://docs.couchbase.com/developer/dev-guide-3.0/doc-expiration.html
      expiry = Math.max(1, Math.floor((new Date(envelope.stored + envelope.ttl).getTime()) / 1000)); // min is 1 sec
    }

    bucket.upsert(keyF, envelopeStr, {expiry: expiry}, function(err) {
      if(err) {
        return callback(err);
      }

      eEmitter.emit('set', keyF);

      return callback();
    });
  };

  // Remove the given key
  var drop = function drop(key, callback) {

    if(typeof callback !== 'function') {
      throw new Error('invalid callback function');
    }
    else if(!isReady()) {
      return callback(new Error('cache server is not ready'));
    }

    // Drop cache
    var keyF = generateKey(key);

    if(!keyF) {
      return callback(new Error('invalid key'));
    }

    bucket.remove(keyF, function(err, res) {
      if(err) {
        if(err.code !== 13) {
          return callback(err);
        }
      }

      eEmitter.emit('drop', keyF, res);

      return callback();
    });
  };

  // Generates keys
  var generateKey = function generateKey(key) {
    return (serverPartition ? encodeURI(serverPartition)+':' : '') + (key && key.segment ? encodeURI(key.segment) : '') + (key && key.id ? ':'+encodeURI(key.id) : '');
  };

  // Allows hook on events
  var on = function on(event, callback) {
    eEmitter.addListener(event, callback);
  };

  // Debug
  //flags = {debug: ['events']}; // for debug
  if(flags.debug instanceof Array) {
    // If events in debug flags
    if(flags.debug.indexOf('events') !== -1) {
      // Log all the events
      ['start', 'stop', 'get', 'set', 'drop', 'connect', 'error'].forEach(function(event) {
        on(event, function(data) {
          console.log('\nDebug: ' + JSON.stringify({event: event, data:data}) + '\n');
        });
      });
    }
  }

  // Return
  return {
    start:               start,
    stop:                stop,
    isReady:             isReady,
    validateSegmentName: validateSegmentName,
    get:                 get,
    set:                 set,
    drop:                drop,
    generateKey:         generateKey,
    settings:            serverOptions,
    on:                  on
  };
};<|endoftext|>


<commit_before>import angular from 'angular';
import getUniqueName from './getUniqueName';
import DI from './DependencyManager';
import Provider from './AutoLookupProvider';

let stringOfClass = x => typeof x === 'function' ? x.$name : x;
let crawlPrototypes = clazz => {
  let classes = [];
  while (clazz.$name) {
    classes.push(clazz);
    clazz = Object.getPrototypeOf(clazz);
  }
  return classes;
};

export let Name = name => clazz => { clazz.$name = name; return clazz; };

export function Service(input = []) {
  let func = dependencies => clazz => {
    clazz.$name = clazz.$name || getUniqueName() + clazz.name;   // name leading to a proxy provider
    clazz.$internal = getUniqueName();   // name that actually leads to the instance

    clazz.$inject = dependencies.map(stringOfClass);
    clazz.$overrides = crawlPrototypes(clazz);
    clazz.$applyOverride = module => {
      clazz.$overrides.forEach(iface => {
        DI.bind(iface).to(clazz);
        // Register every interface/implementation in angular
        // Will figure out exact implementation later
        module.provider(iface.$name, new Provider(module, iface));
      });
      // Register real instance with internal name
      module.service(clazz.$internal, clazz);
    };
    clazz.$registerOn = clazz.$applyOverride;
    return clazz;
  };
  // Unwrapping
  if (input.constructor !== Array) {
    return func([])(input);
  } else {
    return func(input);
  }
}

export let Default = defVal => clazz => { clazz.$default = defVal; return clazz; };

export function Value(clazz) {
  clazz.$name = clazz.$name || getUniqueName() + clazz.name;
  if (clazz.$default) DI.bind(clazz).toValue(clazz.$default);
}

export function Controller(input = []) {
  let func = dependencies => clazz => {
    clazz.$name = clazz.$name || getUniqueName() + clazz.name;
    clazz.$inject = dependencies.map(stringOfClass);
    clazz.$registerOn = module =>
      module.config(['$controllerProvider', x => x.register(clazz.$name, clazz)]);
    return clazz;
  };
  // Unwrapping
  if (input.constructor !== Array) {
    return func([])(input);
  } else {
    return func(input);
  }
}

export function Directive(input = []) {
  let func = dependencies => clazz => {
    clazz.$name = clazz.$name || clazz.name;
    clazz.$inject = dependencies.map(stringOfClass);
    clazz.$registerOn = module =>
      module.directive(clazz.$name, ['$injector', x => x.instantiate(clazz)]);
    // Provide lexical binding if compile() returns a function
    if (clazz.prototype.compile) {
      let originalCompile = clazz.prototype.compile;
      clazz.prototype.compile = function () {
        let retn = originalCompile.apply(this, arguments);
        if (typeof retn === 'function') retn = retn.bind(this);
        return retn;
      };
    }
  };
  // Unwrapping
  if (input.constructor !== Array) {
    return func([])(input);
  } else {
    return func(input);
  }
}

// Extend Angular modules with `.use`
let origModuleCall = angular.module;
angular.module = function () {
  let module = origModuleCall.apply(angular, arguments);
  module.use = (...components) =>
    components.forEach(component => component.$registerOn(module));
  // Add in our module for default values
  module.requires.push(DI.getDefaultModuleName());
  // Extend Angular `.value` calls to process annotated values
  let origValueCall = module.value;
  module.value = function () {
    // Calling with annotated value class?
    if (arguments[0].constructor !== String) arguments[0] = arguments[0].$name;
    return origValueCall.apply(module, arguments);
  };
  return module;
};
<commit_msg>Return module from user function<commit_after>import angular from 'angular';
import getUniqueName from './getUniqueName';
import DI from './DependencyManager';
import Provider from './AutoLookupProvider';

let stringOfClass = x => typeof x === 'function' ? x.$name : x;
let crawlPrototypes = clazz => {
  let classes = [];
  while (clazz.$name) {
    classes.push(clazz);
    clazz = Object.getPrototypeOf(clazz);
  }
  return classes;
};

export let Name = name => clazz => { clazz.$name = name; return clazz; };

export function Service(input = []) {
  let func = dependencies => clazz => {
    clazz.$name = clazz.$name || getUniqueName() + clazz.name;   // name leading to a proxy provider
    clazz.$internal = getUniqueName();   // name that actually leads to the instance

    clazz.$inject = dependencies.map(stringOfClass);
    clazz.$overrides = crawlPrototypes(clazz);
    clazz.$applyOverride = module => {
      clazz.$overrides.forEach(iface => {
        DI.bind(iface).to(clazz);
        // Register every interface/implementation in angular
        // Will figure out exact implementation later
        module.provider(iface.$name, new Provider(module, iface));
      });
      // Register real instance with internal name
      module.service(clazz.$internal, clazz);
    };
    clazz.$registerOn = clazz.$applyOverride;
    return clazz;
  };
  // Unwrapping
  if (input.constructor !== Array) {
    return func([])(input);
  } else {
    return func(input);
  }
}

export let Default = defVal => clazz => { clazz.$default = defVal; return clazz; };

export function Value(clazz) {
  clazz.$name = clazz.$name || getUniqueName() + clazz.name;
  if (clazz.$default) DI.bind(clazz).toValue(clazz.$default);
}

export function Controller(input = []) {
  let func = dependencies => clazz => {
    clazz.$name = clazz.$name || getUniqueName() + clazz.name;
    clazz.$inject = dependencies.map(stringOfClass);
    clazz.$registerOn = module =>
      module.config(['$controllerProvider', x => x.register(clazz.$name, clazz)]);
    return clazz;
  };
  // Unwrapping
  if (input.constructor !== Array) {
    return func([])(input);
  } else {
    return func(input);
  }
}

export function Directive(input = []) {
  let func = dependencies => clazz => {
    clazz.$name = clazz.$name || clazz.name;
    clazz.$inject = dependencies.map(stringOfClass);
    clazz.$registerOn = module =>
      module.directive(clazz.$name, ['$injector', x => x.instantiate(clazz)]);
    // Provide lexical binding if compile() returns a function
    if (clazz.prototype.compile) {
      let originalCompile = clazz.prototype.compile;
      clazz.prototype.compile = function () {
        let retn = originalCompile.apply(this, arguments);
        if (typeof retn === 'function') retn = retn.bind(this);
        return retn;
      };
    }
  };
  // Unwrapping
  if (input.constructor !== Array) {
    return func([])(input);
  } else {
    return func(input);
  }
}

// Extend Angular modules with `.use`
let origModuleCall = angular.module;
angular.module = function () {
  let module = origModuleCall.apply(angular, arguments);
  module.use = (...components) => {
    components.forEach(component => component.$registerOn(module));
    return module;
  }
  // Add in our module for default values
  module.requires.push(DI.getDefaultModuleName());
  // Extend Angular `.value` calls to process annotated values
  let origValueCall = module.value;
  module.value = function () {
    // Calling with annotated value class?
    if (arguments[0].constructor !== String) arguments[0] = arguments[0].$name;
    return origValueCall.apply(module, arguments);
  };
  return module;
};
<|endoftext|>


<commit_before>'use strict';

//  ---------------------------------------------------------------------------

const Exchange = require ('./base/Exchange');
const { ExchangeError, AuthenticationError, DDoSProtection } = require ('./base/errors');

//  ---------------------------------------------------------------------------

module.exports = class coinfalcon extends Exchange {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'coinfalcon',
            'name': 'CoinFalcon',
            'countries': [ 'GB' ],
            'rateLimit': 1000,
            'version': 'v1',
            'has': {
                'fetchTickers': true,
                'fetchOpenOrders': true,
                'fetchMyTrades': true,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/41822275-ed982188-77f5-11e8-92bb-496bcd14ca52.jpg',
                'api': 'https://coinfalcon.com',
                'www': 'https://coinfalcon.com',
                'doc': 'https://docs.coinfalcon.com',
                'fees': 'https://coinfalcon.com/fees',
                'referral': 'https://coinfalcon.com/?ref=CFJSVGTUPASB',
            },
            'api': {
                'public': {
                    'get': [
                        'markets',
                        'markets/{market}/orders',
                        'markets/{market}/trades',
                    ],
                },
                'private': {
                    'get': [
                        'user/accounts',
                        'user/orders',
                        'user/orders/{id}',
                        'user/trades',
                    ],
                    'post': [
                        'user/orders',
                    ],
                    'delete': [
                        'user/orders/{id}',
                    ],
                },
            },
            'fees': {
                'trading': {
                    'tierBased': true,
                    'maker': 0.0,
                    'taker': 0.002, // tiered fee starts at 0.2%
                },
            },
            'precision': {
                'amount': 8,
                'price': 8,
            },
        });
    }

    async fetchMarkets (params = {}) {
        let response = await this.publicGetMarkets ();
        let markets = response['data'];
        let result = [];
        for (let i = 0; i < markets.length; i++) {
            let market = markets[i];
            let [ baseId, quoteId ] = market['name'].split ('-');
            let base = this.commonCurrencyCode (baseId);
            let quote = this.commonCurrencyCode (quoteId);
            let symbol = base + '/' + quote;
            let precision = {
                'amount': this.safeInteger (market, 'size_precision'),
                'price': this.safeInteger (market, 'price_precision'),
            };
            result.push ({
                'id': market['name'],
                'symbol': symbol,
                'base': base,
                'quote': quote,
                'baseId': baseId,
                'quoteId': quoteId,
                'active': true,
                'precision': precision,
                'limits': {
                    'amount': {
                        'min': Math.pow (10, -precision['amount']),
                        'max': undefined,
                    },
                    'price': {
                        'min': Math.pow (10, -precision['price']),
                        'max': undefined,
                    },
                    'cost': {
                        'min': undefined,
                        'max': undefined,
                    },
                },
                'info': market,
            });
        }
        return result;
    }

    parseTicker (ticker, market = undefined) {
        if (market === undefined) {
            let marketId = this.safeString (ticker, 'name');
            market = this.safeValue (this.markets_by_id, marketId, market);
        }
        let symbol = undefined;
        if (market !== undefined) {
            symbol = market['symbol'];
        }
        let timestamp = this.milliseconds ();
        let last = parseFloat (ticker['last_price']);
        return {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'high': undefined,
            'low': undefined,
            'bid': undefined,
            'bidVolume': undefined,
            'ask': undefined,
            'askVolume': undefined,
            'vwap': undefined,
            'open': undefined,
            'close': last,
            'last': last,
            'previousClose': undefined,
            'change': parseFloat (ticker['change_in_24h']),
            'percentage': undefined,
            'average': undefined,
            'baseVolume': undefined,
            'quoteVolume': parseFloat (ticker['volume']),
            'info': ticker,
        };
    }

    async fetchTicker (symbol, params = {}) {
        let tickers = await this.fetchTickers (params);
        return tickers[symbol];
    }

    async fetchTickers (symbols = undefined, params = {}) {
        await this.loadMarkets ();
        let response = await this.publicGetMarkets ();
        let tickers = response['data'];
        let result = {};
        for (let i = 0; i < tickers.length; i++) {
            let ticker = this.parseTicker (tickers[i]);
            let symbol = ticker['symbol'];
            result[symbol] = ticker;
        }
        return result;
    }

    async fetchOrderBook (symbol, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let response = await this.publicGetMarketsMarketOrders (this.extend ({
            'market': this.marketId (symbol),
            'level': '3',
        }, params));
        return this.parseOrderBook (response['data'], undefined, 'bids', 'asks', 'price', 'size');
    }

    parseTrade (trade, market = undefined) {
        let timestamp = this.parse8601 (trade['created_at']);
        let price = parseFloat (trade['price']);
        let amount = parseFloat (trade['size']);
        let symbol = market['symbol'];
        let cost = parseFloat (this.costToPrecision (symbol, price * amount));
        let tradeId = this.safeString (trade, 'id');
        let side = this.safeString (trade, 'side');
        let orderId = this.safeString (trade, 'order_id');
        let fee = undefined;
        let feeCost = this.safeFloat (trade, 'fee');
        if (feeCost !== undefined) {
            let feeCurrencyCode = undefined;
            fee = {
                'cost': feeCost,
                'currency': feeCurrencyCode,
            };
        }
        return {
            'info': trade,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': symbol,
            'id': tradeId,
            'order': orderId,
            'type': undefined,
            'side': side,
            'price': price,
            'amount': amount,
            'cost': cost,
            'fee': fee,
        };
    }

    async fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        if (symbol === undefined)
            throw new ArgumentsRequired (this.id + ' fetchMyTrades requires a symbol argument');
        await this.loadMarkets ();
        let market = this.market (symbol);
        let request = {
            'market': market['id'],
        };
        if (since !== undefined) {
            request['start_time'] = this.iso8601(since);
        }
        if (limit !== undefined) {
            request['limit'] = limit;
        }
        let response = await this.privateGetUserTrades (this.extend (request, params));
        return this.parseTrades (response['data'], market, since, limit);
    }

    async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let request = {
            'market': market['id'],
        };
        if (since !== undefined) {
            request['since'] = this.iso8601 (since);
        }
        let response = await this.publicGetMarketsMarketTrades (this.extend (request, params));
        return this.parseTrades (response['data'], market, since, limit);
    }

    async fetchBalance (params = {}) {
        await this.loadMarkets ();
        let response = await this.privateGetUserAccounts (params);
        let result = { 'info': response };
        let balances = response['data'];
        for (let i = 0; i < balances.length; i++) {
            let balance = balances[i];
            let currencyId = this.safeString (balance, 'currency_code');
            let uppercase = currencyId.toUpperCase ();
            let code = this.commonCurrencyCode (uppercase);
            if (uppercase in this.currencies_by_id) {
                code = this.currencies_by_id[uppercase]['code'];
            }
            let account = {
                'free': parseFloat (balance['available_balance']),
                'used': parseFloat (balance['hold_balance']),
                'total': parseFloat (balance['balance']),
            };
            result[code] = account;
        }
        return this.parseBalance (result);
    }

    parseOrder (order, market = undefined) {
        if (market === undefined) {
            let marketId = this.safeString (order, 'market');
            if (marketId in this.markets_by_id)
                market = this.markets_by_id[marketId];
        }
        let symbol = undefined;
        if (market !== undefined) {
            symbol = market['symbol'];
        }
        let timestamp = this.parse8601 (order['created_at']);
        let price = this.safeFloat (order, 'price');
        let amount = this.safeFloat (order, 'size');
        let filled = this.safeFloat (order, 'size_filled');
        let remaining = parseFloat (this.amountToPrecision (symbol, amount - filled));
        let cost = parseFloat (this.priceToPrecision (symbol, amount * price));
        // pending, open, partially_filled, fullfilled, canceled
        let status = order['status'];
        if (status === 'fulfilled') {
            status = 'closed';
        } else if (status === 'canceled') {
            status = 'canceled';
        } else {
            status = 'open';
        }
        let type = order['operation_type'].split ('_');
        return {
            'id': this.safeString (order, 'id'),
            'datetime': this.iso8601 (timestamp),
            'timestamp': timestamp,
            'status': status,
            'symbol': symbol,
            'type': type[0],
            'side': order['order_type'],
            'price': price,
            'cost': cost,
            'amount': amount,
            'filled': filled,
            'remaining': remaining,
            'trades': undefined,
            'fee': undefined,
            'info': order,
        };
    }

    async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        // price/size must be string
        amount = this.amountToPrecision (symbol, amount);
        let request = {
            'market': market['id'],
            'size': amount,
            'order_type': side,
        };
        if (type === 'limit') {
            price = this.priceToPrecision (symbol, price);
            request['price'] = price.toString ();
        }
        request['operation_type'] = type + '_order';
        let response = await this.privatePostUserOrders (this.extend (request, params));
        let order = this.parseOrder (response['data'], market);
        let id = order['id'];
        this.orders[id] = order;
        return order;
    }

    async cancelOrder (id, symbol = undefined, params = {}) {
        await this.loadMarkets ();
        let response = await this.privateDeleteUserOrdersId (this.extend ({
            'id': id,
        }, params));
        let market = this.market (symbol);
        return this.parseOrder (response['data'], market);
    }

    async fetchOrder (id, symbol = undefined, params = {}) {
        await this.loadMarkets ();
        let response = await this.privateGetUserOrdersId (this.extend ({
            'id': id,
        }, params));
        return this.parseOrder (response['data']);
    }

    async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let request = {};
        if (symbol !== undefined) {
            request['market'] = this.marketId (symbol);
        }
        if (since !== undefined) {
            request['since_time'] = this.iso8601 (this.milliseconds ());
        }
        // TODO: test status=all if it works for closed orders too
        let response = await this.privateGetUserOrders (this.extend (request, params));
        return this.parseOrders (response['data']);
    }

    nonce () {
        return this.milliseconds ();
    }

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let request = '/api/' + this.version + '/' + this.implodeParams (path, params);
        let query = this.omit (params, this.extractParams (path));
        if (api === 'public') {
            if (Object.keys (query).length) {
                request += '?' + this.urlencode (query);
            }
        } else {
            this.checkRequiredCredentials ();
            if (method === 'GET') {
                if (Object.keys (query).length) {
                    request += '?' + this.urlencode (query);
                }
            } else {
                body = this.json (query);
            }
            let seconds = this.seconds ().toString ();
            let payload = [ seconds, method, request ].join ('|');
            if (body) {
                payload += '|' + body;
            }
            let signature = this.hmac (this.encode (payload), this.encode (this.secret));
            headers = {
                'CF-API-KEY': this.apiKey,
                'CF-API-TIMESTAMP': seconds,
                'CF-API-SIGNATURE': signature,
                'Content-Type': 'application/json',
            };
        }
        let url = this.urls['api'] + request;
        return { 'url': url, 'method': method, 'body': body, 'headers': headers };
    }

    handleErrors (code, reason, url, method, headers, body, response) {
        if (code < 400) {
            return;
        }
        let ErrorClass = this.safeValue ({
            '401': AuthenticationError,
            '429': DDoSProtection,
        }, code, ExchangeError);
        throw new ErrorClass (body);
    }
};
<commit_msg>coinfalcon linting, missing ArgumentsRequired import<commit_after>'use strict';

//  ---------------------------------------------------------------------------

const Exchange = require ('./base/Exchange');
const { ExchangeError, AuthenticationError, DDoSProtection, ArgumentsRequired } = require ('./base/errors');

//  ---------------------------------------------------------------------------

module.exports = class coinfalcon extends Exchange {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'coinfalcon',
            'name': 'CoinFalcon',
            'countries': [ 'GB' ],
            'rateLimit': 1000,
            'version': 'v1',
            'has': {
                'fetchTickers': true,
                'fetchOpenOrders': true,
                'fetchMyTrades': true,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/41822275-ed982188-77f5-11e8-92bb-496bcd14ca52.jpg',
                'api': 'https://coinfalcon.com',
                'www': 'https://coinfalcon.com',
                'doc': 'https://docs.coinfalcon.com',
                'fees': 'https://coinfalcon.com/fees',
                'referral': 'https://coinfalcon.com/?ref=CFJSVGTUPASB',
            },
            'api': {
                'public': {
                    'get': [
                        'markets',
                        'markets/{market}/orders',
                        'markets/{market}/trades',
                    ],
                },
                'private': {
                    'get': [
                        'user/accounts',
                        'user/orders',
                        'user/orders/{id}',
                        'user/trades',
                    ],
                    'post': [
                        'user/orders',
                    ],
                    'delete': [
                        'user/orders/{id}',
                    ],
                },
            },
            'fees': {
                'trading': {
                    'tierBased': true,
                    'maker': 0.0,
                    'taker': 0.002, // tiered fee starts at 0.2%
                },
            },
            'precision': {
                'amount': 8,
                'price': 8,
            },
        });
    }

    async fetchMarkets (params = {}) {
        let response = await this.publicGetMarkets ();
        let markets = response['data'];
        let result = [];
        for (let i = 0; i < markets.length; i++) {
            let market = markets[i];
            let [ baseId, quoteId ] = market['name'].split ('-');
            let base = this.commonCurrencyCode (baseId);
            let quote = this.commonCurrencyCode (quoteId);
            let symbol = base + '/' + quote;
            let precision = {
                'amount': this.safeInteger (market, 'size_precision'),
                'price': this.safeInteger (market, 'price_precision'),
            };
            result.push ({
                'id': market['name'],
                'symbol': symbol,
                'base': base,
                'quote': quote,
                'baseId': baseId,
                'quoteId': quoteId,
                'active': true,
                'precision': precision,
                'limits': {
                    'amount': {
                        'min': Math.pow (10, -precision['amount']),
                        'max': undefined,
                    },
                    'price': {
                        'min': Math.pow (10, -precision['price']),
                        'max': undefined,
                    },
                    'cost': {
                        'min': undefined,
                        'max': undefined,
                    },
                },
                'info': market,
            });
        }
        return result;
    }

    parseTicker (ticker, market = undefined) {
        if (market === undefined) {
            let marketId = this.safeString (ticker, 'name');
            market = this.safeValue (this.markets_by_id, marketId, market);
        }
        let symbol = undefined;
        if (market !== undefined) {
            symbol = market['symbol'];
        }
        let timestamp = this.milliseconds ();
        let last = parseFloat (ticker['last_price']);
        return {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'high': undefined,
            'low': undefined,
            'bid': undefined,
            'bidVolume': undefined,
            'ask': undefined,
            'askVolume': undefined,
            'vwap': undefined,
            'open': undefined,
            'close': last,
            'last': last,
            'previousClose': undefined,
            'change': parseFloat (ticker['change_in_24h']),
            'percentage': undefined,
            'average': undefined,
            'baseVolume': undefined,
            'quoteVolume': parseFloat (ticker['volume']),
            'info': ticker,
        };
    }

    async fetchTicker (symbol, params = {}) {
        let tickers = await this.fetchTickers (params);
        return tickers[symbol];
    }

    async fetchTickers (symbols = undefined, params = {}) {
        await this.loadMarkets ();
        let response = await this.publicGetMarkets ();
        let tickers = response['data'];
        let result = {};
        for (let i = 0; i < tickers.length; i++) {
            let ticker = this.parseTicker (tickers[i]);
            let symbol = ticker['symbol'];
            result[symbol] = ticker;
        }
        return result;
    }

    async fetchOrderBook (symbol, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let response = await this.publicGetMarketsMarketOrders (this.extend ({
            'market': this.marketId (symbol),
            'level': '3',
        }, params));
        return this.parseOrderBook (response['data'], undefined, 'bids', 'asks', 'price', 'size');
    }

    parseTrade (trade, market = undefined) {
        let timestamp = this.parse8601 (trade['created_at']);
        let price = parseFloat (trade['price']);
        let amount = parseFloat (trade['size']);
        let symbol = market['symbol'];
        let cost = parseFloat (this.costToPrecision (symbol, price * amount));
        let tradeId = this.safeString (trade, 'id');
        let side = this.safeString (trade, 'side');
        let orderId = this.safeString (trade, 'order_id');
        let fee = undefined;
        let feeCost = this.safeFloat (trade, 'fee');
        if (feeCost !== undefined) {
            let feeCurrencyCode = undefined;
            fee = {
                'cost': feeCost,
                'currency': feeCurrencyCode,
            };
        }
        return {
            'info': trade,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': symbol,
            'id': tradeId,
            'order': orderId,
            'type': undefined,
            'side': side,
            'price': price,
            'amount': amount,
            'cost': cost,
            'fee': fee,
        };
    }

    async fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        if (symbol === undefined)
            throw new ArgumentsRequired (this.id + ' fetchMyTrades requires a symbol argument');
        await this.loadMarkets ();
        let market = this.market (symbol);
        let request = {
            'market': market['id'],
        };
        if (since !== undefined) {
            request['start_time'] = this.iso8601 (since);
        }
        if (limit !== undefined) {
            request['limit'] = limit;
        }
        let response = await this.privateGetUserTrades (this.extend (request, params));
        return this.parseTrades (response['data'], market, since, limit);
    }

    async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let request = {
            'market': market['id'],
        };
        if (since !== undefined) {
            request['since'] = this.iso8601 (since);
        }
        let response = await this.publicGetMarketsMarketTrades (this.extend (request, params));
        return this.parseTrades (response['data'], market, since, limit);
    }

    async fetchBalance (params = {}) {
        await this.loadMarkets ();
        let response = await this.privateGetUserAccounts (params);
        let result = { 'info': response };
        let balances = response['data'];
        for (let i = 0; i < balances.length; i++) {
            let balance = balances[i];
            let currencyId = this.safeString (balance, 'currency_code');
            let uppercase = currencyId.toUpperCase ();
            let code = this.commonCurrencyCode (uppercase);
            if (uppercase in this.currencies_by_id) {
                code = this.currencies_by_id[uppercase]['code'];
            }
            let account = {
                'free': parseFloat (balance['available_balance']),
                'used': parseFloat (balance['hold_balance']),
                'total': parseFloat (balance['balance']),
            };
            result[code] = account;
        }
        return this.parseBalance (result);
    }

    parseOrder (order, market = undefined) {
        if (market === undefined) {
            let marketId = this.safeString (order, 'market');
            if (marketId in this.markets_by_id)
                market = this.markets_by_id[marketId];
        }
        let symbol = undefined;
        if (market !== undefined) {
            symbol = market['symbol'];
        }
        let timestamp = this.parse8601 (order['created_at']);
        let price = this.safeFloat (order, 'price');
        let amount = this.safeFloat (order, 'size');
        let filled = this.safeFloat (order, 'size_filled');
        let remaining = parseFloat (this.amountToPrecision (symbol, amount - filled));
        let cost = parseFloat (this.priceToPrecision (symbol, amount * price));
        // pending, open, partially_filled, fullfilled, canceled
        let status = order['status'];
        if (status === 'fulfilled') {
            status = 'closed';
        } else if (status === 'canceled') {
            status = 'canceled';
        } else {
            status = 'open';
        }
        let type = order['operation_type'].split ('_');
        return {
            'id': this.safeString (order, 'id'),
            'datetime': this.iso8601 (timestamp),
            'timestamp': timestamp,
            'status': status,
            'symbol': symbol,
            'type': type[0],
            'side': order['order_type'],
            'price': price,
            'cost': cost,
            'amount': amount,
            'filled': filled,
            'remaining': remaining,
            'trades': undefined,
            'fee': undefined,
            'info': order,
        };
    }

    async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        // price/size must be string
        amount = this.amountToPrecision (symbol, amount);
        let request = {
            'market': market['id'],
            'size': amount,
            'order_type': side,
        };
        if (type === 'limit') {
            price = this.priceToPrecision (symbol, price);
            request['price'] = price.toString ();
        }
        request['operation_type'] = type + '_order';
        let response = await this.privatePostUserOrders (this.extend (request, params));
        let order = this.parseOrder (response['data'], market);
        let id = order['id'];
        this.orders[id] = order;
        return order;
    }

    async cancelOrder (id, symbol = undefined, params = {}) {
        await this.loadMarkets ();
        let response = await this.privateDeleteUserOrdersId (this.extend ({
            'id': id,
        }, params));
        let market = this.market (symbol);
        return this.parseOrder (response['data'], market);
    }

    async fetchOrder (id, symbol = undefined, params = {}) {
        await this.loadMarkets ();
        let response = await this.privateGetUserOrdersId (this.extend ({
            'id': id,
        }, params));
        return this.parseOrder (response['data']);
    }

    async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let request = {};
        if (symbol !== undefined) {
            request['market'] = this.marketId (symbol);
        }
        if (since !== undefined) {
            request['since_time'] = this.iso8601 (this.milliseconds ());
        }
        // TODO: test status=all if it works for closed orders too
        let response = await this.privateGetUserOrders (this.extend (request, params));
        return this.parseOrders (response['data']);
    }

    nonce () {
        return this.milliseconds ();
    }

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let request = '/api/' + this.version + '/' + this.implodeParams (path, params);
        let query = this.omit (params, this.extractParams (path));
        if (api === 'public') {
            if (Object.keys (query).length) {
                request += '?' + this.urlencode (query);
            }
        } else {
            this.checkRequiredCredentials ();
            if (method === 'GET') {
                if (Object.keys (query).length) {
                    request += '?' + this.urlencode (query);
                }
            } else {
                body = this.json (query);
            }
            let seconds = this.seconds ().toString ();
            let payload = [ seconds, method, request ].join ('|');
            if (body) {
                payload += '|' + body;
            }
            let signature = this.hmac (this.encode (payload), this.encode (this.secret));
            headers = {
                'CF-API-KEY': this.apiKey,
                'CF-API-TIMESTAMP': seconds,
                'CF-API-SIGNATURE': signature,
                'Content-Type': 'application/json',
            };
        }
        let url = this.urls['api'] + request;
        return { 'url': url, 'method': method, 'body': body, 'headers': headers };
    }

    handleErrors (code, reason, url, method, headers, body, response) {
        if (code < 400) {
            return;
        }
        let ErrorClass = this.safeValue ({
            '401': AuthenticationError,
            '429': DDoSProtection,
        }, code, ExchangeError);
        throw new ErrorClass (body);
    }
};
<|endoftext|>


<commit_before>var mongoose = require('mongoose');
var mubsub = require('mubsub');

var monq = module.exports = {};

monq.Job = require('./job');
monq.Queue = require('./queue');
monq.Worker = require('./worker');

monq.pubsub = mubsub.channel('events');

monq.worker = function(options) {
    options.pubsub || (options.pubsub = monq.pubsub);
    return new monq.Worker(options);
};

monq.queue = function(name) {
    return new monq.Queue(name);
};

monq.subscribe = function(job, callback) {
    monq.pubsub.subscribe({ 'job._id': job._id }, callback);
};

monq.connect = function(db) {
    mongoose.connect(db);
    mubsub.connect(db);
};<commit_msg>Return subscription object<commit_after>var mongoose = require('mongoose');
var mubsub = require('mubsub');

var monq = module.exports = {};

monq.Job = require('./job');
monq.Queue = require('./queue');
monq.Worker = require('./worker');

monq.pubsub = mubsub.channel('events');

monq.worker = function(options) {
    options.pubsub || (options.pubsub = monq.pubsub);
    return new monq.Worker(options);
};

monq.queue = function(name) {
    return new monq.Queue(name);
};

monq.subscribe = function(job, callback) {
    return monq.pubsub.subscribe({ 'job._id': job._id }, callback);
};

monq.connect = function(db) {
    mongoose.connect(db);
    mubsub.connect(db);
};<|endoftext|>


<commit_before>'use strict';

var merge = require('es5-ext/lib/Object/plain/merge').call;

module.exports = merge(require('./deferred'), {
	asyncToPromise: require('./async-to-promise'),
	syncToPromise:  require('./sync-to-promise'),
	delay:          require('./delay'),

	join:           require('./join/default'),
	all:            require('./join/all'),
	first:          require('./join/first')
});

require('./ext/all');
require('./ext/cb');
require('./ext/first');
require('./ext/invoke');
require('./ext/invoke-async');
require('./ext/join');
<commit_msg>Added missing 'get' extension to index.<commit_after>'use strict';

var merge = require('es5-ext/lib/Object/plain/merge').call;

module.exports = merge(require('./deferred'), {
	asyncToPromise: require('./async-to-promise'),
	syncToPromise:  require('./sync-to-promise'),
	delay:          require('./delay'),

	join:           require('./join/default'),
	all:            require('./join/all'),
	first:          require('./join/first')
});

require('./ext/all');
require('./ext/cb');
require('./ext/first');
require('./ext/get');
require('./ext/invoke');
require('./ext/invoke-async');
require('./ext/join');
<|endoftext|>


<commit_before>$(function() {

    $("#contactForm input,#contactForm textarea").jqBootstrapValidation({
        preventSubmit: true,
        submitError: function($form, event, errors) {
            // additional error messages or events
        },
        submitSuccess: function($form, event) {
            event.preventDefault(); // prevent default submit behaviour
            // get values from FORM
            var name = $("input#name").val();
            var email = $("input#email").val();
            var message = $("textarea#message").val();
            var _cc = "infokinly@gmail.com";
            var _gotcha = $("input#formspree-gotcha").val();
            var _subject = "Kinly Website Inquiry";
            var firstName = name; // For Success/Failure Message
            // Check for white space in name for Success/Fail message
            if (firstName.indexOf(' ') >= 0) {
                firstName = name.split(' ').slice(0, -1).join(' ');
            }
            $.ajax({
                url: 'https://formspree.io/info@kinly.io',
            		method: 'POST',
            		dataType: 'json',
                data: {
                    _subject: _subject,
                    name: name,
                    email: email,
                    _cc: _cc,
                    _gotcha: _gotcha,
                    message: message
                },
                success: function() {
                    // Success message
                    $('#success').html("
");
                    $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
                        .append("</button>");
                    $('#success > .alert-success')
                        .append("Thank you! Your message has been sent. ");
                    $('#success > .alert-success')
                        .append('
');

                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
                error: function() {
                    // Fail message
                    $('#success').html("
");
                    $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
                        .append("</button>");
                    $('#success > .alert-danger').append("Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
                    $('#success > .alert-danger').append('
');
                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
            })
        },
        filter: function() {
            return $(this).is(":visible");
        },
    });

    $("a[data-toggle=\"tab\"]").click(function(e) {
        e.preventDefault();
        $(this).tab("show");
    });
});

/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
    $('#success').html('');
});
<commit_msg>correct Kinly email (missing .)<commit_after>$(function() {

    $("#contactForm input,#contactForm textarea").jqBootstrapValidation({
        preventSubmit: true,
        submitError: function($form, event, errors) {
            // additional error messages or events
        },
        submitSuccess: function($form, event) {
            event.preventDefault(); // prevent default submit behaviour
            // get values from FORM
            var name = $("input#name").val();
            var email = $("input#email").val();
            var message = $("textarea#message").val();
            var _cc = "info.kinly@gmail.com";
            var _gotcha = $("input#formspree-gotcha").val();
            var _subject = "Kinly Website Inquiry";
            var firstName = name; // For Success/Failure Message
            // Check for white space in name for Success/Fail message
            if (firstName.indexOf(' ') >= 0) {
                firstName = name.split(' ').slice(0, -1).join(' ');
            }
            $.ajax({
                url: 'https://formspree.io/info@kinly.io',
            		method: 'POST',
            		dataType: 'json',
                data: {
                    _subject: _subject,
                    name: name,
                    email: email,
                    _cc: _cc,
                    _gotcha: _gotcha,
                    message: message
                },
                success: function() {
                    // Success message
                    $('#success').html("
");
                    $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
                        .append("</button>");
                    $('#success > .alert-success')
                        .append("Thank you! Your message has been sent. ");
                    $('#success > .alert-success')
                        .append('
');

                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
                error: function() {
                    // Fail message
                    $('#success').html("
");
                    $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
                        .append("</button>");
                    $('#success > .alert-danger').append("Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
                    $('#success > .alert-danger').append('
');
                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
            })
        },
        filter: function() {
            return $(this).is(":visible");
        },
    });

    $("a[data-toggle=\"tab\"]").click(function(e) {
        e.preventDefault();
        $(this).tab("show");
    });
});

/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
    $('#success').html('');
});
<|endoftext|>


<commit_before>$(function() {

    $("#contactForm input,#contactForm textarea").jqBootstrapValidation({
        preventSubmit: true,
        submitError: function($form, event, errors) {
            // additional error messages or events
        },
        submitSuccess: function($form, event) {
            event.preventDefault(); // prevent default submit behaviour
            // get values from FORM
            var name = $("input#name").val();
            var email = $("input#email").val();
            var phone = $("input#phone").val();
            var message = $("textarea#message").val();
            var firstName = name; // For Success/Failure Message
            // Check for white space in name for Success/Fail message
            if (firstName.indexOf(' ') >= 0) {
                firstName = name.split(' ').slice(0, -1).join(' ');
            }
            $.ajax({
				//url: "http://formspree.io/info@jts.services",
				url: "http://formspree.io/doug@mitchell.life",
				method: "POST",
                data: {
                    name: name,
                    phone: phone,
                    email: email,
                    message: message
                },
                dataType: "json",
                cache: false,
                success: function() {
                    // Success message
                    $('#success').html("
");
                    $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
                        .append("</button>");
                    $('#success > .alert-success')
                        .append("Thank you for contacting JTS Services. We will contact you soon. ");
                    $('#success > .alert-success')
                        .append('
');

                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
                error: function() {
                    // Fail message
                    $('#success').html("
");
                    $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
                        .append("</button>");
                    $('#success > .alert-danger').append("Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
                    $('#success > .alert-danger').append('
');
                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
            })
        },
        filter: function() {
            return $(this).is(":visible");
        },
    });

    $("a[data-toggle=\"tab\"]").click(function(e) {
        e.preventDefault();
        $(this).tab("show");
    });
});

/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
    $('#success').html('');
});
<commit_msg>Revert "Rollback"<commit_after>$(function() {

    $("#contactForm input,#contactForm textarea").jqBootstrapValidation({
        preventSubmit: true,
        submitError: function($form, event, errors) {
            // additional error messages or events
        },
        submitSuccess: function($form, event) {
            event.preventDefault(); // prevent default submit behaviour
            // get values from FORM
            var name = $("input#name").val();
            var email = $("input#email").val();
            var phone = $("input#phone").val();
            var message = $("textarea#message").val();
            var firstName = name; // For Success/Failure Message
            // Check for white space in name for Success/Fail message
            if (firstName.indexOf(' ') >= 0) {
                firstName = name.split(' ').slice(0, -1).join(' ');
            }
            $.ajax({
				//url: "http://formspree.io/info@jts.services",
				url: "http://formspree.io/doug@mitchell.life",
				method: "POST",
                data: {
                    name: name,
                    phone: phone,
                    email: email,
                    message: message
                },
                dataType: "json",
                cache: false,
                success: function() {
                    // Success message
                    $('#success').html("
");
                    $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
                        .append("</button>");
                    $('#success > .alert-success')
                        .append("Thank you for contacting JTS Services. We will contact you soon. ");
                    $('#success > .alert-success')
                        .append('
');

                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
                error: function() {
                    // Fail message
                    $('#success').html("
");
                    $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
                        .append("</button>");
                    $('#success > .alert-danger').append("Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
                    $('#success > .alert-danger').append('
');
                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
                ga('send', {
  hitType: 'event',
  eventAction: 'Send Message'
}),
            })
        },
        filter: function() {
            return $(this).is(":visible");
        },
    });

    $("a[data-toggle=\"tab\"]").click(function(e) {
        e.preventDefault();
        $(this).tab("show");
    });
});

/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
    $('#success').html('');
});
<|endoftext|>