<commit_before>var BaseController = require('./baseController').BaseController;
var ConfigureController = function(helpers, arguments, environment, mainController) {
    BaseController.call(this, helpers, arguments, environment);
    this.route = "configure";
    this.mainController = mainController;
};

ConfigureController.prototype = Object.create(BaseController.prototype);
ConfigureController.prototype.constructor = ConfigureController;

ConfigureController.prototype.elasticsearch = function(callback) {
    console.log("configuring");
    var post_options = {
        host: this.environment.elasticsearch_host===undefined?'127.0.0.1':this.environment.elasticsearch_host,
        port: this.environment.elasticsearch_port===undefined?'9200':this.environment.elasticsearch_port,
        path: '/default',
        method: 'POST'
    };
    var post_data = JSON.stringify({
        "mappings": {
            "_default_": {
                "dynamic_templates": [
                    {
                        "string_template": {
                            "mapping": {
                                "index": "not_analyzed",
                                "type": "string"
                            },
                            "match_mapping_type": "string",
                            "match": "*"
                        }
                    }
                ]
            }
        },
        "settings": {
            "index": {
                "number_of_replicas": "1",
                "number_of_shards": "1"
            }
        }
    });
    this.helpers.doRequest(post_options,post_data, function(chunk) {
        console.log('Response: ' + JSON.stringify(chunk));
        if(callback!==undefined) callback();
    });
};

exports.ConfigureController = ConfigureController;<commit_msg>Updated elasticsearch index configuration<commit_after>var BaseController = require('./baseController').BaseController;
var ConfigureController = function(helpers, arguments, environment, mainController) {
    BaseController.call(this, helpers, arguments, environment);
    this.route = "configure";
    this.mainController = mainController;
};

ConfigureController.prototype = Object.create(BaseController.prototype);
ConfigureController.prototype.constructor = ConfigureController;

ConfigureController.prototype.elasticsearch = function(callback) {
    console.log("Configuring elasticsearch...");
    var post_options = {
        host: this.environment.elasticsearch_host===undefined?'127.0.0.1':this.environment.elasticsearch_host,
        port: this.environment.elasticsearch_port===undefined?'9200':this.environment.elasticsearch_port,
        path: '/default',
        method: 'POST'
    };
    var post_data = JSON.stringify({
        "mappings": {
            "_default_": {
                "dynamic_templates": [
                    {
                    geolocation_template: {
                        mapping: {
                        type: "geo_point"
                        },
                        match: "*_geolocation",
                        match_mappping_type: "geo_point"
                        }
                    },
                    {
                        "string_template": {
                            "mapping": {
                                "index": "not_analyzed",
                                "type": "string"
                            },
                            "match_mapping_type": "string",
                            "match": "*"
                        }
                    },
                    {
                    object_template: {
                        mapping: {
                        index: "not_analyzed",
                        type: "object"
                        },
                        match: "*",
                        match_mapping_type: "object"
                        }
                    }
                ]
            }
        },
        "settings": {
            "index": {
                "number_of_replicas": "1",
                "number_of_shards": "1"
            }
        }
    });
    this.helpers.doRequest(post_options,post_data, function(chunk) {
        console.log('Response: ' + JSON.stringify(chunk));
        if(callback!==undefined) callback();
    });
};

exports.ConfigureController = ConfigureController;<|endoftext|>


<commit_before>"use strict"

const math = require("mathjs")
const sigmoid = require("./sigmoid")
const deriv = require("./deriv")
const multiplyElements = require("./multiply-elements")

// must be vertical matrix
function getAveError(m1) {
    let sum = 0
    m1 = math.transpose(m1)
    let len = (m1.size())[1]

    for (let i = 0; i < len; i++) {
        sum += math.abs(m1.subset(math.index(0,i)))
    }
    return math.abs(sum / len)
}
// TODO: make a function that sets x and y

// Input Data
function train(inputData, inputResults) {
    const x = math.matrix(inputData)
    const y = math.transpose(math.matrix([inputResults]))

    const layer0 = x
    let layer1
    let layer1_error
    let layer1_delta
    let layer2
    let layer2_error
    let layer2_delta
    let hiddenLayerSize
    let error
    let minError = 100
    let synapse0
    let synapse1
    let minSynapse0
    let minSynapse1

    // Gradient descent and dropout optimization variables
    const hlSizes = [(x.size())[1], (x.size())[1] - 1, (x.size())[1] + 1]
    const alphas = [0.1, 1, 10]
    const dropout_percent = 0.2

    for (let alphaIndex = 0; alphaIndex < 3; alphaIndex++) {

        // Iterate over 3 hidden layer sizes to get the best one
        for (let hlSizeIndex = 0; hlSizeIndex < 3; hlSizeIndex++) {

            // Weights
            hiddenLayerSize = hlSizes[hlSizeIndex]
            synapse0 = math.random([(x.size())[1], hiddenLayerSize], -1, 1)
            synapse1 = math.random([hiddenLayerSize, 1], -1, 1)

            for (let i = 0; i < 40000; i++) {
                // forward propagation
                layer1 = math.multiply(layer0, synapse0).map(sigmoid)
                // dropout
                layer1.forEach(index => {
                    let rand = math.random()
                    if (rand < dropout_percent) {
                        layer1[index] = 0
                        layer1[index] *= 1.0/(1-dropout_percent)
                    }
                })
                layer2 = math.multiply(layer1, synapse1).map(sigmoid)
                // compare estimate with actual output
                layer2_error = math.subtract(y, layer2)
                // use slope of sigmoid to update values
                layer2_delta = multiplyElements(layer2_error, layer2.map(deriv))
                // distribute error over synapse 1
                layer1_error = math.multiply(layer2_delta, math.transpose(synapse1))
                // use slope of sigmoid to update values
                layer1_delta = multiplyElements(layer1_error, layer1.map(deriv))
                // compare estimate with actual output
                // update weights
                synapse0 = math.add(synapse0, math.multiply(math.transpose(layer0), layer1_delta))
                synapse1 = math.add(synapse1, math.multiply(math.transpose(layer1), layer2_delta))
            }
            let currentError = getAveError(layer2_error)
            if (currentError < minError) {
                minError = currentError
                minSynapse1 = synapse1
                minSynapse0 = synapse0
            }
        }
    }
    return {
        synapse0: minSynapse0,
        synapse1: minSynapse1
    }
}

function get(input, w0, w1) {
    let synapse0 = math.matrix(w0)
    let synapse1 = math.matrix(w1)
    let x = math.matrix(input)
    let testl1 = math.multiply(x, synapse0).map(sigmoid)
    return math.multiply(testl1, synapse1).map(sigmoid)
}

module.exports = {train, get}
<commit_msg>fix a {}<commit_after>"use strict"

const math = require("mathjs")
const sigmoid = require("./sigmoid")
const deriv = require("./deriv")
const multiplyElements = require("./multiply-elements")

// must be vertical matrix
function getAveError(m1) {
    let sum = 0
    m1 = math.transpose(m1)
    let len = (m1.size())[1]

    for (let i = 0; i < len; i++) {
        sum += math.abs(m1.subset(math.index(0,i)))
    }
    return math.abs(sum / len)
}
// TODO: make a function that sets x and y

// Input Data
function train(inputData, inputResults) {
    const x = math.matrix(inputData)
    const y = math.transpose(math.matrix([inputResults]))

    const layer0 = x
    let layer1
    let layer1_error
    let layer1_delta
    let layer2
    let layer2_error
    let layer2_delta
    let hiddenLayerSize
    let error
    let minError = 100
    let synapse0
    let synapse1
    let minSynapse0
    let minSynapse1

    // Gradient descent and dropout optimization variables
    const hlSizes = [(x.size())[1], (x.size())[1] - 1, (x.size())[1] + 1]
    const alphas = [0.1, 1, 10]
    const dropout_percent = 0.2

    for (let alphaIndex = 0; alphaIndex < 3; alphaIndex++) {

        // Iterate over 3 hidden layer sizes to get the best one
        for (let hlSizeIndex = 0; hlSizeIndex < 3; hlSizeIndex++) {

            // Weights
            hiddenLayerSize = hlSizes[hlSizeIndex]
            synapse0 = math.random([(x.size())[1], hiddenLayerSize], -1, 1)
            synapse1 = math.random([hiddenLayerSize, 1], -1, 1)

            for (let i = 0; i < 40000; i++) {
                // forward propagation
                layer1 = math.multiply(layer0, synapse0).map(sigmoid)
                // dropout
                layer1.forEach(index => {
                    let rand = math.random()
                    if (rand < dropout_percent) {
                        layer1[index] = 0
                    }
                    layer1[index] *= 1.0/(1-dropout_percent)
                })
                layer2 = math.multiply(layer1, synapse1).map(sigmoid)
                // compare estimate with actual output
                layer2_error = math.subtract(y, layer2)
                // use slope of sigmoid to update values
                layer2_delta = multiplyElements(layer2_error, layer2.map(deriv))
                // distribute error over synapse 1
                layer1_error = math.multiply(layer2_delta, math.transpose(synapse1))
                // use slope of sigmoid to update values
                layer1_delta = multiplyElements(layer1_error, layer1.map(deriv))
                // compare estimate with actual output
                // update weights
                synapse0 = math.add(synapse0, math.multiply(math.transpose(layer0), layer1_delta))
                synapse1 = math.add(synapse1, math.multiply(math.transpose(layer1), layer2_delta))
            }
            let currentError = getAveError(layer2_error)
            if (currentError < minError) {
                minError = currentError
                minSynapse1 = synapse1
                minSynapse0 = synapse0
            }
        }
    }
    return {
        synapse0: minSynapse0,
        synapse1: minSynapse1
    }
}

function get(input, w0, w1) {
    let synapse0 = math.matrix(w0)
    let synapse1 = math.matrix(w1)
    let x = math.matrix(input)
    let testl1 = math.multiply(x, synapse0).map(sigmoid)
    return math.multiply(testl1, synapse1).map(sigmoid)
}

module.exports = {train, get}
<|endoftext|>


<commit_before>const bluebird = require('bluebird')
const path = require('path')
const cozy = require('./cozyclient')
const request = require('./request')
const rq = request()
const log = require('./logger').namespace('saveFiles')

// Saves the files given in the fileurl attribute of each entries
module.exports = (entries, fields, options = {}) => {
  if (typeof fields === 'string') {
    fields = { folderPath: fields }
  }
  const remainingTime = Math.floor((options.timeout - Date.now()) / 1000)
  if (options.timeout) log('info', `${remainingTime}s remaining for ${fields.folderPath}`)

  return bluebird.mapSeries(entries, entry => {
    if (!entry.fileurl && !entry.requestOptions) return false

    if (options.timeout && Date.now() > options.timeout) {
      log('info', `${remainingTime}s timeout finished for ${fields.folderPath}`)
      throw new Error('TIMEOUT')
    }

    const filepath = path.join(fields.folderPath, sanitizeFileName(getFileName(entry)))
    return cozy.files.statByPath(filepath)
    .then(() => {
      // the file is already present then get out of here
      return entry
    })
    .catch(err => {
      log('debug', entry)
      log('debug', `File ${filepath} does not exist yet`, err.message)
      return cozy.files.statByPath(fields.folderPath)
      .then(folder => {
        const options = {
          uri: entry.fileurl,
          method: 'GET',
          jar: true
        }
        if (entry.requestOptions) {
          Object.assign(options, entry.requestOptions)
        }
        return cozy.files.create(rq(options), {name: sanitizeFileName(getFileName(entry)), dirID: folder._id})
        .then(fileobject => {
          entry.fileobject = fileobject
          return entry
        })
      })
    })
    .catch(err => {
      // if error is timeout, do not continue
      if (err.message === 'TIMEOUT') throw err
      // console.log(err, 'err')
      log('error', err.message, `Error caught while trying to save the file ${entry.fileurl}`)
      return entry
    })
  })
  .catch(err => {
    // do not count TIMEOUT error as an error outside
    if (err.message !== 'TIMEOUT') throw err
  })
}

function getFileName (entry) {
  if (entry.filename) return entry.filename

  // try to get the file name from the url
  const parsed = require('url').parse(entry.fileurl)
  return path.basename(parsed.pathname)
}

function sanitizeFileName (filename) {
  return filename.replace(/^\.+$/, '').replace(/[/?<>\\:*|":]/g, '')
}
<commit_msg>fix: delete requestOptions from entry<commit_after>const bluebird = require('bluebird')
const path = require('path')
const cozy = require('./cozyclient')
const request = require('./request')
const rq = request()
const log = require('./logger').namespace('saveFiles')

// Saves the files given in the fileurl attribute of each entries
module.exports = (entries, fields, options = {}) => {
  if (typeof fields === 'string') {
    fields = { folderPath: fields }
  }
  const remainingTime = Math.floor((options.timeout - Date.now()) / 1000)
  if (options.timeout) log('info', `${remainingTime}s remaining for ${fields.folderPath}`)

  return bluebird.mapSeries(entries, entry => {
    if (!entry.fileurl && !entry.requestOptions) return false

    if (options.timeout && Date.now() > options.timeout) {
      log('info', `${remainingTime}s timeout finished for ${fields.folderPath}`)
      throw new Error('TIMEOUT')
    }

    const filepath = path.join(fields.folderPath, sanitizeFileName(getFileName(entry)))
    return cozy.files.statByPath(filepath)
    .then(() => {
      // the file is already present then get out of here
      return entry
    })
    .catch(err => {
      log('debug', entry)
      log('debug', `File ${filepath} does not exist yet`, err.message)
      return cozy.files.statByPath(fields.folderPath)
      .then(folder => {
        const reqOptions = {
          uri: entry.fileurl,
          method: 'GET',
          jar: true
        }
        if (entry.requestOptions) {
          Object.assign(options, entry.requestOptions)
          delete entry.requestOptions
        }
        return cozy.files.create(rq(reqOptions), {name: sanitizeFileName(getFileName(entry)), dirID: folder._id})
        .then(fileobject => {
          entry.fileobject = fileobject
          return entry
        })
      })
    })
    .catch(err => {
      // if error is timeout, do not continue
      if (err.message === 'TIMEOUT') throw err
      // console.log(err, 'err')
      log('error', err.message, `Error caught while trying to save the file ${entry.fileurl}`)
      return entry
    })
  })
  .catch(err => {
    // do not count TIMEOUT error as an error outside
    if (err.message !== 'TIMEOUT') throw err
  })
}

function getFileName (entry) {
  if (entry.filename) return entry.filename

  // try to get the file name from the url
  const parsed = require('url').parse(entry.fileurl)
  return path.basename(parsed.pathname)
}

function sanitizeFileName (filename) {
  return filename.replace(/^\.+$/, '').replace(/[/?<>\\:*|":]/g, '')
}
<|endoftext|>


<commit_before>import clone from 'lodash/clone';
import request from 'request';

import RestfulModel from './models/restful-model';
import RestfulModelCollection from './models/restful-model-collection';
import RestfulModelInstance from './models/restful-model-instance';
import Account from './models/account';
import ManagementAccount from './models/management-account';
import ManagementModelCollection from './models/management-model-collection';
import Thread from './models/thread';
import Contact from './models/contact';
import Message from './models/message';
import Draft from './models/draft';
import File from './models/file';
import Calendar from './models/calendar';
import Event from './models/event';
import Delta from './models/delta';
import { Label, Folder } from './models/folder';

const PACKAGE_JSON = require('../package.json');
const SDK_VERSION = PACKAGE_JSON.version;
const SUPPORTED_API_VERSION = '2.0';

module.exports = class NylasConnection {
  constructor(accessToken, { clientId }) {
    this.accessToken = accessToken;
    this.clientId = clientId;
    this.threads = new RestfulModelCollection(Thread, this);
    this.contacts = new RestfulModelCollection(Contact, this);
    this.messages = new RestfulModelCollection(Message, this);
    this.drafts = new RestfulModelCollection(Draft, this);
    this.files = new RestfulModelCollection(File, this);
    this.calendars = new RestfulModelCollection(Calendar, this);
    this.events = new RestfulModelCollection(Event, this);
    this.deltas = new Delta(this);
    this.labels = new RestfulModelCollection(Label, this);
    this.folders = new RestfulModelCollection(Folder, this);
    this.account = new RestfulModelInstance(Account, this);
  }

  requestOptions(options) {
    if (!options) {
      options = {};
    }
    options = clone(options);
    const Nylas = require('./nylas');
    if (!options.method) {
      options.method = 'GET';
    }
    if (options.path) {
      if (!options.url) {
        options.url = `${Nylas.apiServer}${options.path}`;
      }
    }
    if (!options.formData) {
      if (!options.body) {
        options.body = {};
      }
    }
    if (options.json == null) {
      options.json = true;
    }
    if (!options.downloadRequest) {
      options.downloadRequest = false;
    }

    // For convenience, If `expanded` param is provided, convert to view:
    // 'expanded' api option
    if (options.qs && options.qs.expanded) {
      if (options.qs.expanded === true) {
        options.qs.view = 'expanded';
      }
      delete options.qs.expanded;
    }

    const user =
      options.path.substr(0, 3) === '/a/'
        ? Nylas.clientSecret
        : this.accessToken;

    if (user) {
      options.auth = {
        user: user,
        pass: '',
        sendImmediately: true,
      };
    }

    if (options.headers == null) {
      options.headers = {};
    }
    if (options.headers['User-Agent'] == null) {
      options.headers['User-Agent'] = `Nylas Node SDK v${SDK_VERSION}`;
    }

    options.headers['Nylas-SDK-API-Version'] = SUPPORTED_API_VERSION;
    options.headers['X-Nylas-Client-Id'] = this.clientId;

    return options;
  }
  _getWarningForVersion(sdkApiVersion = null, apiVersion = null) {
    let warning = '';

    if (sdkApiVersion != apiVersion) {
      if (sdkApiVersion && apiVersion) {
        warning +=
          `WARNING: SDK version may not support your Nylas API version.` +
          ` SDK supports version ${sdkApiVersion} of the API and your application` +
          ` is currently running on version ${apiVersion} of the API.`;

        const apiNum = parseInt(apiVersion.split('-')[0]);
        const sdkNum = parseInt(sdkApiVersion.split('-')[0]);

        if (sdkNum > apiNum) {
          warning += ` Please update the version of the API that your application is using through the developer dashboard.`;
        } else if (apiNum > sdkNum) {
          warning += ` Please update the sdk to ensure it works properly.`;
        }
      }
    }
    return warning;
  }
  request(options) {
    if (!options) {
      options = {};
    }
    options = this.requestOptions(options);

    return new Promise((resolve, reject) => {
      return request(options, (error, response, body = {}) => {
        // node headers are lowercase so this refers to `Nylas-Api-Version`
        const apiVersion = response.headers['nylas-api-version'];

        const warning = this._getWarningForVersion(
          SUPPORTED_API_VERSION,
          apiVersion
        );
        if (warning) {
          console.warn(warning);
        }

        // raw MIMI emails have json === false and the body is a string so
        // we need to turn into JSON before we can access fields
        if (options.json === false) {
          body = JSON.parse(body);
        }

        if (error || response.statusCode > 299) {
          if (!error) {
            error = new Error(body.message);
          }
          if (body.missing_fields) {
            error.message = `${body.message}: ${body.missing_fields}`;
          }
          if (body.server_error) {
            error.message = `${error.message} (Server Error:
              ${body.server_error}
            )`;
          }
          if (response.statusCode) {
            error.statusCode = response.statusCode;
          }
          return reject(error);
        } else {
          if (options.downloadRequest) {
            return resolve(response);
          } else {
            return resolve(body);
          }
        }
      });
    });
  }
};
<commit_msg>Also pass error message instead of only error status code<commit_after>import clone from 'lodash/clone';
import request from 'request';

import RestfulModel from './models/restful-model';
import RestfulModelCollection from './models/restful-model-collection';
import RestfulModelInstance from './models/restful-model-instance';
import Account from './models/account';
import ManagementAccount from './models/management-account';
import ManagementModelCollection from './models/management-model-collection';
import Thread from './models/thread';
import Contact from './models/contact';
import Message from './models/message';
import Draft from './models/draft';
import File from './models/file';
import Calendar from './models/calendar';
import Event from './models/event';
import Delta from './models/delta';
import { Label, Folder } from './models/folder';

const PACKAGE_JSON = require('../package.json');
const SDK_VERSION = PACKAGE_JSON.version;
const SUPPORTED_API_VERSION = '2.0';

module.exports = class NylasConnection {
  constructor(accessToken, { clientId }) {
    this.accessToken = accessToken;
    this.clientId = clientId;
    this.threads = new RestfulModelCollection(Thread, this);
    this.contacts = new RestfulModelCollection(Contact, this);
    this.messages = new RestfulModelCollection(Message, this);
    this.drafts = new RestfulModelCollection(Draft, this);
    this.files = new RestfulModelCollection(File, this);
    this.calendars = new RestfulModelCollection(Calendar, this);
    this.events = new RestfulModelCollection(Event, this);
    this.deltas = new Delta(this);
    this.labels = new RestfulModelCollection(Label, this);
    this.folders = new RestfulModelCollection(Folder, this);
    this.account = new RestfulModelInstance(Account, this);
  }

  requestOptions(options) {
    if (!options) {
      options = {};
    }
    options = clone(options);
    const Nylas = require('./nylas');
    if (!options.method) {
      options.method = 'GET';
    }
    if (options.path) {
      if (!options.url) {
        options.url = `${Nylas.apiServer}${options.path}`;
      }
    }
    if (!options.formData) {
      if (!options.body) {
        options.body = {};
      }
    }
    if (options.json == null) {
      options.json = true;
    }
    if (!options.downloadRequest) {
      options.downloadRequest = false;
    }

    // For convenience, If `expanded` param is provided, convert to view:
    // 'expanded' api option
    if (options.qs && options.qs.expanded) {
      if (options.qs.expanded === true) {
        options.qs.view = 'expanded';
      }
      delete options.qs.expanded;
    }

    const user =
      options.path.substr(0, 3) === '/a/'
        ? Nylas.clientSecret
        : this.accessToken;

    if (user) {
      options.auth = {
        user: user,
        pass: '',
        sendImmediately: true,
      };
    }

    if (options.headers == null) {
      options.headers = {};
    }
    if (options.headers['User-Agent'] == null) {
      options.headers['User-Agent'] = `Nylas Node SDK v${SDK_VERSION}`;
    }

    options.headers['Nylas-SDK-API-Version'] = SUPPORTED_API_VERSION;
    options.headers['X-Nylas-Client-Id'] = this.clientId;

    return options;
  }
  _getWarningForVersion(sdkApiVersion = null, apiVersion = null) {
    let warning = '';

    if (sdkApiVersion != apiVersion) {
      if (sdkApiVersion && apiVersion) {
        warning +=
          `WARNING: SDK version may not support your Nylas API version.` +
          ` SDK supports version ${sdkApiVersion} of the API and your application` +
          ` is currently running on version ${apiVersion} of the API.`;

        const apiNum = parseInt(apiVersion.split('-')[0]);
        const sdkNum = parseInt(sdkApiVersion.split('-')[0]);

        if (sdkNum > apiNum) {
          warning += ` Please update the version of the API that your application is using through the developer dashboard.`;
        } else if (apiNum > sdkNum) {
          warning += ` Please update the sdk to ensure it works properly.`;
        }
      }
    }
    return warning;
  }
  request(options) {
    if (!options) {
      options = {};
    }
    options = this.requestOptions(options);

    return new Promise((resolve, reject) => {
      return request(options, (error, response, body = {}) => {
        // node headers are lowercase so this refers to `Nylas-Api-Version`
        const apiVersion = response.headers['nylas-api-version'];

        const warning = this._getWarningForVersion(
          SUPPORTED_API_VERSION,
          apiVersion
        );
        if (warning) {
          console.warn(warning);
        }

        // raw MIMI emails have json === false and the body is a string so
        // we need to turn into JSON before we can access fields
        if (options.json === false) {
          body = JSON.parse(body);
        }

        if (error || response.statusCode > 299) {
          if (!error) {
            error = new Error(body.message);
          }
          if (body.missing_fields) {
            error.message = `${body.message}: ${body.missing_fields}`;
          }
          if (body.server_error) {
            error.message = `${error.message} (Server Error:
              ${body.server_error}
            )`;
          }
          if (response.statusCode) {
            error.statusCode = response.statusCode;
            if(!('message' in error)){
              error.message = response.message;
            }
          }
          return reject(error);
        } else {
          if (options.downloadRequest) {
            return resolve(response);
          } else {
            return resolve(body);
          }
        }
      });
    });
  }
};
<|endoftext|>


<commit_before>var interval_to_cancel;

function set_interval_cancel(handle) {
    interval_to_cancel = handle;
}

function work_callback(data) {
    var host_id = get_host_id_from_scheduler_request(data);
    if (host_id != null) update_request_xml(standard_request, host_id);
    if (has_work(data)) {
        console.log("got work, canceling interval");
        clearInterval(interval_to_cancel);
        do_work(data);
    } else {
        console.log("got no work");
    }
}

function do_work(data) {
    console.log("data");
}

var standard_request = ['<scheduler_request>',
                        '    <authenticator>cd83b81e4874b95c24a26b44ef1a73e8</authenticator>',
                        '    <core_client_major_version>6</core_client_major_version>',
                        '    <core_client_minor_version>10</core_client_minor_version>',
                        '    <core_client_release>59</core_client_release>',
                        '    <resource_share_fraction>1.000000</resource_share_fraction>',
                        '    <rrs_fraction>1.000000</rrs_fraction>',
                        '    <prrs_fraction>1.000000</prrs_fraction>',
                        '    <duration_correction_factor>1.000000</duration_correction_factor>',
                        '    <sandbox>0</sandbox>',
                        '    <work_req_seconds>60480.000000</work_req_seconds>',
                        '    <cpu_req_secs>60480.000000</cpu_req_secs>',
                        '    <cpu_req_instances>2.000000</cpu_req_instances>',
                        '    <estimated_delay>0.000000</estimated_delay>',
                        '    <client_cap_plan_class>1</client_cap_plan_class>',
                        '    <platform_name>x86_64-pc-linux-gnu</platform_name>',
                        '    <alt_platform>',
                        '        <name>i686-pc-linux-gnu</name>',
                        '    </alt_platform>',
                        '    <code_sign_key>',
                        '1024',
                        'caf9ff3c57c08e2779720b5fc72e25f28c62add28866d3035e5e87eb5bd49a1d',
                        '0afe7bb84ea624cce42a581a6ce232dc7dd7dad2d2ea5ed6609bec8c41785f05',
                        '145df8814b3bd4258b12f0df53206f25ba89645a9c34c8e0e18773cbb761cbce',
                        '70fcd4061ff066829327c357fefcc2a01275d810b282cd83cf2b9de7ab78bc47',
                        '0000000000000000000000000000000000000000000000000000000000000000',
                        '0000000000000000000000000000000000000000000000000000000000000000',
                        '0000000000000000000000000000000000000000000000000000000000000000',
                        '0000000000000000000000000000000000000000000000000000000000010001',
                        '.',
                        '</code_sign_key>',
                        '<host_info>',
                        '   <d_total>155416956928.000000</d_total>',
                        '   <d_free>115370192896.000000</d_free>',
                        '</host_info>',
                        '<other_results>',
                        '</other_results>',
                        '<in_progress_results>',
                        '</in_progress_results>',
                        '</scheduler_request>', '',''].join("\n");
function schedule_request(authtoken) {
    $.post(CGI_ROOT + "/cgi", standard_request, work_callback);
}
<commit_msg>changed the platform name on our scheduler request to javascript<commit_after>var interval_to_cancel;

function set_interval_cancel(handle) {
    interval_to_cancel = handle;
}

function work_callback(data) {
    var host_id = get_host_id_from_scheduler_request(data);
    if (host_id != null) update_request_xml(standard_request, host_id);
    if (has_work(data)) {
        console.log("got work, canceling interval");
        clearInterval(interval_to_cancel);
        do_work(data);
    } else {
        console.log("got no work");
    }
}

function do_work(data) {
    console.log("data");
}

var standard_request = ['<scheduler_request>',
                        '    <authenticator>cd83b81e4874b95c24a26b44ef1a73e8</authenticator>',
                        '    <core_client_major_version>6</core_client_major_version>',
                        '    <core_client_minor_version>10</core_client_minor_version>',
                        '    <core_client_release>59</core_client_release>',
                        '    <resource_share_fraction>1.000000</resource_share_fraction>',
                        '    <rrs_fraction>1.000000</rrs_fraction>',
                        '    <prrs_fraction>1.000000</prrs_fraction>',
                        '    <duration_correction_factor>1.000000</duration_correction_factor>',
                        '    <sandbox>0</sandbox>',
                        '    <work_req_seconds>60480.000000</work_req_seconds>',
                        '    <cpu_req_secs>60480.000000</cpu_req_secs>',
                        '    <cpu_req_instances>2.000000</cpu_req_instances>',
                        '    <estimated_delay>0.000000</estimated_delay>',
                        '    <client_cap_plan_class>1</client_cap_plan_class>',
                        '    <platform_name>javascript</platform_name>',
                        '    <code_sign_key>',
                        '1024',
                        'caf9ff3c57c08e2779720b5fc72e25f28c62add28866d3035e5e87eb5bd49a1d',
                        '0afe7bb84ea624cce42a581a6ce232dc7dd7dad2d2ea5ed6609bec8c41785f05',
                        '145df8814b3bd4258b12f0df53206f25ba89645a9c34c8e0e18773cbb761cbce',
                        '70fcd4061ff066829327c357fefcc2a01275d810b282cd83cf2b9de7ab78bc47',
                        '0000000000000000000000000000000000000000000000000000000000000000',
                        '0000000000000000000000000000000000000000000000000000000000000000',
                        '0000000000000000000000000000000000000000000000000000000000000000',
                        '0000000000000000000000000000000000000000000000000000000000010001',
                        '.',
                        '</code_sign_key>',
                        '<host_info>',
                        '   <d_total>155416956928.000000</d_total>',
                        '   <d_free>115370192896.000000</d_free>',
                        '</host_info>',
                        '<other_results>',
                        '</other_results>',
                        '<in_progress_results>',
                        '</in_progress_results>',
                        '</scheduler_request>', '',''].join("\n");
function schedule_request(authtoken) {
    $.post(CGI_ROOT + "/cgi", standard_request, work_callback);
}
<|endoftext|>


<commit_before>/* global self */

self.lib= self.lib || {};

self.lib.zipper= {
	unzip : function(file, callback){
		var fileReader= new self.FileReader();
		fileReader.onloadend= function(){
			var buffer= this.result;
			var viewer= new self.Uint8Array(buffer);
			var cursor= -1;
			var readBytes= function(count){
				var result= 0;
				for(var i= 0; i < count; i++){
					cursor++;
					result= result | (parseInt(intToHex(viewer[cursor]).substr(-2), 16) << (i * 8));
					}
				return result;
			};
			var copyBytes= function(count){
				var result= new self.Uint8Array(count);
				for(var i= 0; i < count; i++){
					cursor++;
					result[i]= viewer[cursor];
					}
				return result;
				};

			var intToHex= function(int){
				return(int+0x10000).toString(16).substr(-4).toUpperCase();
				};

			var decodeAsString= function(buffer){
				return String.fromCharCode.apply(null, new self.Uint8Array(buffer));
				};

			var zip= {
				files : [],
				file_headers : [],
				extra_data : [],
				signatures : [],
				zip64_end_record : [],
				end_record : []
				};

			while(cursor < viewer.length-1){
				var signature= readBytes(4); // 0 - 3

//				File
				if(signature == 0x04034b50){
					var uncompressed_size, name_length, extra_length, compression;
					zip.files.push({
						version_a : readBytes(2),
						flag : readBytes(2),
						compression : (compression= readBytes(2)),
						time : readBytes(2),
						date : readBytes(2),
						crc : readBytes(4),
						compressed_size : readBytes(4),
						uncompressed_size : (uncompressed_size= readBytes(4)),
						name_length : (name_length= readBytes(2)),
						extra_length : (extra_length= readBytes(2)),

						name : decodeAsString(copyBytes(name_length).buffer),
						extra : decodeAsString(copyBytes(extra_length).buffer),

						data : (compression === 0) ? copyBytes(uncompressed_size).buffer : self.ArrayBuffer(0)
						});

//				Archive extra Data
				}else if(signature == 0x08064b50){
					zip.extra_data.push({
						extra_length : readBytes(4),
						extra : decodeAsString(copyBytes(this.extra_length).buffer)
						});

//				File Header
				}else if(signature == 0x02014b50){
					var name_length, extra_length, comment_length;
					zip.file_headers.push({
						version_made : readBytes(2),
						version_needed : readBytes(2),
						flag : readBytes(2),
						compression : readBytes(2),
						time : readBytes(2),
						date : readBytes(2),
						crc : readBytes(4),
						compressed_size : readBytes(4),
						uncompressed_size : readBytes(4),
						name_length : (name_length= readBytes(2), name_length),
						extra_lenghth : (extra_length= readBytes(2), extra_length),
						comment_length : (comment_length= readBytes(2), comment_length),
						diskNumbeStart : readBytes(2),
						internal_attributes : readBytes(2),
						external_attributes : readBytes(4),
						relative_offset : readBytes(4),

						name : decodeAsString(copyBytes(name_length).buffer),
						extra : copyBytes(extra_length).buffer,
						comment : decodeAsString(copyBytes(comment_length).buffer)
						});

//				Digital signature
				}else if(signature == 0x05054b50){
					var size;
					zip.sigantures.push({
						size : (size= readBytes(2), size),
						data : copyBytes(this.size)
						});

//				zip64 end of central directory record
				}else if(signature == 0x06064b50){
					zip.zip64_end_record.push({
						record_size : readBytes(8),
						version_made : readBytes(2),
						version_needed : readBytes(2),
						disk : readBytes(4),
						dir_start_disk : readBytes(4),
						dir_entry_count : readBytes(8),
						size_central_dir : readBytes(8),
						offset : readBytes(8)
						});

//				End of central directory record
				}else if(signature == 0x06054b50){
					var comment_length;
					zip.end_record.push({
						disk : readBytes(2),
						start_disk : readBytes(2),
						entries : readBytes(2),
						total_entries : readBytes(2),
						size : readBytes(4),
						start_offset : readBytes(4),
						comment_length : (comment_length= readBytes(2), comment_length),
						comment : decodeAsString(copyBytes(comment_length).buffer)
						});
					}
				}

			callback(zip);
			};
		fileReader.readAsArrayBuffer(file);
		},

	zip : function(fileList){

		}
	};<commit_msg>restructuring and impelmentation of zip file writer<commit_after>/* global self */

this.$$= this;
$$.lib= $$.lib || {};

this.lib.zipper= {
	unzip : function(file, callback){
		if($$.FileReader){
			var fileReader= new $$.FileReader();
			var self= this;

			fileReader.onloadend= function(){
				var reader= new self.ZipReader(this.result);
				var zip= new self.ZipRecord();

				while(reader.bytesLeft()){
					self.readNextBySignature(self.readSignature(reader), reader, zip);
				}
				callback(zip);
			};
			fileReader.readAsArrayBuffer(file);
		}else if($$.FileReaderSync){
			var fileReader= new $$.FileReaderSync();
			var reader= new this.ZipReader( fileReader.readAsArrayBuffer(file) );
			var zip= new this.ZipRecord();

			while(reader.bytesLeft()){
				this.readNextBySignature(this.readSignature(reader), reader, zip);
			}
			callback(zip);
		}else{
			console.error('no FileReader available in this context!');
		}
	},

	createBlob : function(zipRecord, onProgress){
		var writer= new this.ZipWriter();
		var self= this;
		var p= 100 / (zipRecord.files.length + zipRecord.file_headers.length + zipRecord.extra_data.length + zipRecord.signatures.length + zipRecord.zip64_end_record.length + zipRecord.end_record.length);
		var count= 0;

		zipRecord.files.forEach(function(item){
			self.writeFile(item, writer);
			onProgress(Math.round(++count * p));
		});
		zipRecord.file_headers.forEach(function(item){
			self.writeFileHader(item, writer);
			onProgress(Math.round(++count * p));
		});
		zipRecord.extra_data.forEach(function(item){
			self.writeExtraData(item, writer);
			onProgress(Math.round(++count * p));
		});
		zipRecord.signatures.forEach(function(item){
			self.writeDigitalSignature(item, writer);
			onProgress(Math.round(++count * p));
		});
		zipRecord.zip64_end_record.forEach(function(item){
			self.writeZip64EndOfCentralDirectory(item, writer);
			onProgress(Math.round(++count * p));
		});
		zipRecord.end_record.forEach(function(item){
			self.writeEndOfCentralDirectory(item, writer);
			onProgress(Math.round(++count * p));
		});

		return new $$.Blob([writer.buffer], { type : 'application/zip' });
	},

	readFileHeader : function(reader, zipRecord){
		var name_length, extra_length, comment_length;
		zipRecord.file_headers.push({
			version_made : reader.readBytes(2),
			version_needed : reader.readBytes(2),
			flag : reader.readBytes(2),
			compression : reader.readBytes(2),
			time : reader.readBytes(2),
			date : reader.readBytes(2),
			crc : reader.readBytes(4),
			compressed_size : reader.readBytes(4),
			uncompressed_size : reader.readBytes(4),
			name_length : (name_length= reader.readBytes(2), name_length),
			extra_length : (extra_length= reader.readBytes(2), extra_length),
			comment_length : (comment_length= reader.readBytes(2), comment_length),
			diskNumbeStart : reader.readBytes(2),
			internal_attributes : reader.readBytes(2),
			external_attributes : reader.readBytes(4),
			relative_offset : reader.readBytes(4),

			name : this.decodeAsString(reader.copyBytes(name_length).buffer),
			extra : reader.copyBytes(extra_length).buffer,
			comment : this.decodeAsString(reader.copyBytes(comment_length).buffer)
		});
	},

	writeFileHader : function(fileHeader, writer){
		writer.centralDirectorySize+= writer.writeBytes([0x02014b50, 4], [fileHeader.version_made, 2], [fileHeader.version_needed, 2],
						  [fileHeader.flag, 2], [fileHeader.compression, 2], [fileHeader.time, 2],
						  [fileHeader.date, 2], [fileHeader.crc, 4], [fileHeader.compressed_size, 4],
						  [fileHeader.uncompressed_size, 4], [fileHeader.name_length, 2], [fileHeader.extra_length, 2],
						  [fileHeader.comment_length, 2], [fileHeader.diskNumbeStart, 2], [fileHeader.internal_attributes, 2],
						  [fileHeader.external_attributes, 4], [fileHeader.relative_offset, 4]);
		writer.centralDirectorySize+= writer.writeBuffer(this.encodeFromString(fileHeader.name), fileHeader.extra, this.encodeFromString(fileHeader.comment));

	},

	readFile : function(reader, zipRecord){
		var uncompressed_size, compressed_size, name_length, extra_length, compression;
		zipRecord.files.push({
			version_a : reader.readBytes(2),
			flag : reader.readBytes(2),
			compression : (compression= reader.readBytes(2)),
			time : reader.readBytes(2),
			date : reader.readBytes(2),
			crc : reader.readBytes(4),
			compressed_size : (compressed_size= reader.readBytes(4)),
			uncompressed_size : (uncompressed_size= reader.readBytes(4)),
			name_length : (name_length= reader.readBytes(2)),
			extra_length : (extra_length= reader.readBytes(2)),

			name : this.decodeAsString(reader.copyBytes(name_length).buffer),
			extra : reader.copyBytes(extra_length).buffer,
			data : ((compression == 0) ? reader.copyBytes(uncompressed_size).buffer : reader.copyBytes(compressed_size).buffer)
		});
	},

	writeFile : function(file, writer){
		writer.writeBytes([0x04034b50, 4], [file.version_a, 2], [file.flag, 2],
						  [file.compression, 2], [file.time, 2], [file.date, 2],
						  [file.crc, 4], [file.compressed_size, 4], [file.uncompressed_size, 4],
						  [file.name_length, 2], [file.extra_length, 2]);
		writer.writeBuffer(this.encodeFromString(file.name), file.extra, file.data);
	},

	readExtraData : function(reader, zipRecord){
		var extra_length;
		zipRecord.extra_data.push({
			extra_length : (extra_length= reader.readBytes(4), extra_length),
			extra : reader.copyBytes(extra_length).buffer
		});
	},

	writeExtraData : function(extraData, writer){
		writer.writeBytes([0x08064b50, 4], [extraData.extra_length, 4]);
		writer.writeBuffer(extraData.extra);
	},

	readDigitalSignature : function(reader, zipRecord){
		var size;
		zipRecord.sigantures.push({
			size : (size= reader.readBytes(2), size),
			data : reader.copyBytes(size).buffer
		});
	},

	writeDigitalSignature : function(digitalSignature, writer){
		writer.writeBytes([0x05054b50, 4], [digitalSignature.size, 2]);
		writer.writeBuffer(digitalSignature.data);
	},

	readZip64EndOfCentralDirectory : function(reader, zipRecord){
		zipRecord.zip64_end_record.push({
			record_size : reader.readBytes(8),
			version_made : reader.readBytes(2),
			version_needed : reader.readBytes(2),
			disk : reader.readBytes(4),
			dir_start_disk : reader.readBytes(4),
			dir_entry_count : reader.readBytes(8),
			size_central_dir : reader.readBytes(8),
			offset : reader.readBytes(8)
		});
	},

	writeZip64EndOfCentralDirectory : function(ecd, writer){
		writer.writeBytes([0x06064b50, 4], [ecd.record_size, 8], [ecd.version_made, 2],
						  [ecd.version_needed, 2], [ecd.disk, 4], [ecd.dir_start_disk, 4],
						  [ecd.dir_entry_count, 8], [ecd.size_central_dir, 8], [ecd.offset, 8]);
	},

	readEndOfCentralDirectory : function(reader, zipRecord){
		var comment_length;
		zipRecord.end_record.push({
			disk : reader.readBytes(2),
			start_disk : reader.readBytes(2),
			entries : reader.readBytes(2),
			total_entries : reader.readBytes(2),
			size : reader.readBytes(4),
			start_offset : reader.readBytes(4),
			comment_length : (comment_length= reader.readBytes(2), comment_length),
			comment : this.decodeAsString(reader.copyBytes(comment_length).buffer)
		});
	},

	writeEndOfCentralDirectory : function(ecd, writer){
		writer.writeBytes([0x06054b50, 4], [ecd.disk, 2], [ecd.start_disk, 2],
						  [ecd.entries, 2], [ecd.total_entries, 2], [writer.centralDirectorySize , 4],
						  [ecd.start_offset, 4], [ecd.comment_length, 4]);
		writer.writeBuffer(this.encodeFromString(ecd.comment));
	},

	readSignature : function(reader){
		return reader.readBytes(4);
	},

	readNextBySignature : function(signature, reader, zipRecord){
		if(signature == 0x04034b50){
			this.readFile(reader, zipRecord);

		}else if(signature == 0x08064b50){
			this.readExtraData(reader, zipRecord);

		}else if(signature == 0x02014b50){
			this.readFileHeader(reader, zipRecord);

		}else if(signature == 0x05054b50){
			this.readDigitalSignature(reader, zipRecord);

		}else if(signature == 0x06064b50){
			this.readZip64EndOfCentralDirectory(reader, zipRecord);

		}else if(signature == 0x06054b50){
			this.readEndOfCentralDirectory(reader, zipRecord);
		}
	},

	ZipReader : function(buffer){
		this.buffer= buffer;
		this.viewer= new $$.Uint8Array(buffer);
		var cursor= -1;

		this.readBytes= function(count){
			var result= 0;
			for(var i= 0; i < count; i++){
				cursor++;
				result= result | ($$.parseInt($$.lib.zipper.intToHexString(this.viewer[cursor]).substr(-2), 16) << (i * 8));
			}
			return result;
		};
		this.copyBytes= function(count){
			var result= new self.Uint8Array(count);
			for(var i= 0; i < count; i++){
				cursor++;
				result[i]= this.viewer[cursor];
			}
			return result;
		};
		this.bytesLeft= function(){
			return cursor < this.viewer.length-1;
		};
	},

	ZipWriter : function(){
		this.buffer= new $$.ArrayBuffer(0);
		this.viewer= new $$.Uint8Array(this.buffer);
		this.centralDirectorySize= 0;

		this.writeBytes= function(d){
			var bufferLength= this.viewer.length;
			var nLength= 0;
			var cursor= 0;

			for(var i= 0; i < arguments.length; i++){
				var data= arguments[i];
				if($$.Array.isArray(data)){
					nLength+= data[1];
				}else{
					var length= data.toString(16).length;
					length= ((length % 2 === 0) ? length/2 : (length+1)/2);
					nLength+= length;
				}
			}
			bufferLength+= nLength;
			var newViewer= new $$.Uint8Array(bufferLength);

			for(var i= 0; i < this.viewer.length; i++){
				newViewer[i]= this.viewer[i];
			}

			cursor= this.viewer.length;

			for(var y= 0; y < arguments.length; y++){
				var data= arguments[y];

				if($$.Array.isArray(data)){
					var length= data[1];
					data= data[0];
				}else{
					var length= data.toString(16).length;
					length= ((length % 2 === 0) ? length/2 : (length+1)/2);
				}

				for(var i= 0; i < length; i++){
					newViewer[(length-i-1) + cursor]= ( data >> ((length - i - 1) * 8) );
				}
				cursor+= length;
			}

			this.viewer= newViewer;
			this.buffer= newViewer.buffer;
			return nLength;
		};

		this.writeBuffer= function(buffer){
			var bufferLength= this.viewer.length;
			var nLength= 0;
			var cursor= 0;

			for(var i= 0; i < arguments.length; i++){
				var length= (new $$.Uint8Array(arguments[i])).length;
				nLength+= length;
			}
			bufferLength+= nLength;

			var newViewer= new $$.Uint8Array(bufferLength);
			for(var i= 0; i < this.viewer.length; i++){
				newViewer[i]= this.viewer[i];
			}

			cursor= this.viewer.length;

			for(var y= 0; y < arguments.length; y++){
				var data= new Uint8Array(arguments[y]);
				var length= data.length;

				for(var i= 0; i < length; i++){
					newViewer[i + cursor]= data[i];
				}
				cursor+= length;
			}

			this.viewer= newViewer;
			this.buffer= newViewer.buffer;
			return nLength;
		};
	},

	ZipRecord : function(){
		this.files= [];
		this.file_headers= [];
		this.extra_data= [];
		this.signatures= [];
		this.zip64_end_record= [];
		this.end_record= [];
	},

	intToHexString : function(int){
		return(int+0x10000).toString(16).substr(-4).toUpperCase();
	},

	decodeAsString : function(buffer){
		return String.fromCharCode.apply(null, new $$.Uint8Array(buffer));
	},

	encodeFromString : function(string){
		var buffer= new $$.Uint8Array(string.length);
		for(var i= 0; i < string.length; i++){
			buffer[i]= string.charCodeAt(i);
		}
		return buffer.buffer;
	}
};<|endoftext|>


<commit_before>(function(exports){
exports.neatJSON = neatJSON;

function neatJSON(value,opts){
	opts = opts || {}
	if (!('wrap'          in opts)) opts.wrap = 80;
	if (opts.wrap==true) opts.wrap = -1;
	if (!('indent'        in opts)) opts.indent = '  ';
	if (!('arrayPadding'  in opts)) opts.arrayPadding  = ('padding' in opts) ? opts.padding : 0;
	if (!('objectPadding' in opts)) opts.objectPadding = ('padding' in opts) ? opts.padding : 0;
	if (!('beforeComma'   in opts)) opts.beforeComma   = ('aroundComma' in opts) ? opts.aroundComma : 0;
	if (!('afterComma'    in opts)) opts.afterComma    = ('aroundComma' in opts) ? opts.aroundComma : 0;
	if (!('beforeColon'   in opts)) opts.beforeColon   = ('aroundColon' in opts) ? opts.aroundColon : 0;
	if (!('afterColon'    in opts)) opts.afterColon    = ('aroundColon' in opts) ? opts.aroundColon : 0;
	if (!('beforeColon1'  in opts)) opts.beforeColon1  = ('aroundColon1' in opts) ? opts.aroundColon1 : ('beforeColon' in opts) ? opts.beforeColon : 0;
	if (!('afterColon1'   in opts)) opts.afterColon1   = ('aroundColon1' in opts) ? opts.aroundColon1 : ('afterColon'  in opts) ? opts.afterColon  : 0;
	if (!('beforeColonN'  in opts)) opts.beforeColonN  = ('aroundColonN' in opts) ? opts.aroundColonN : ('beforeColon' in opts) ? opts.beforeColon : 0;
	if (!('afterColonN'   in opts)) opts.afterColonN   = ('aroundColonN' in opts) ? opts.aroundColonN : ('afterColon'  in opts) ? opts.afterColon  : 0;

	var apad   = repeat(' ',opts.arrayPadding),
	    opad   = repeat(' ',opts.objectPadding),
	    comma  = repeat(' ',opts.beforeComma)+','+repeat(' ',opts.afterComma),
	    colon1 = repeat(' ',opts.beforeColon1)+':'+repeat(' ',opts.afterColon1),
	    colonN = repeat(' ',opts.beforeColonN)+':'+repeat(' ',opts.afterColonN);

	return build(value,'');

	function build(o,indent){
		if (o===null || o===undefined) return indent+'null';
		else{
			switch(o.constructor){
				case Number:
					var isFloat = (o === +o && o !== (o|0));
					return indent + ((isFloat && ('decimals' in opts)) ? o.toFixed(opts.decimals) : (o+''));

				case Array:
					if (!o.length) return indent+"[]";
					var pieces  = o.map(function(v){ return build(v,'') });
					var oneLine = indent+'['+apad+pieces.join(comma)+apad+']';
					if (opts.wrap===false || oneLine.length<=opts.wrap) return oneLine;
					if (opts.short){
						var indent2 = indent+' '+apad;
						pieces = o.map(function(v){ return build(v,indent2) });
						pieces[0] = pieces[0].replace(indent2,indent+'['+apad);
						pieces[pieces.length-1] = pieces[pieces.length-1]+apad+']';
						return pieces.join(',\n');
					}else{
						var indent2 = indent+opts.indent;
						return indent+'[\n'+o.map(function(v){ return build(v,indent2) }).join(',\n')+'\n'+indent+']';
					}

				case Object:
					var keyvals=[],i=0;
					for (var k in o) keyvals[i++] = [JSON.stringify(k), build(o[k],'')];
					if (!keyvals.length) return indent+'{}';
					if (opts.sorted) keyvals = keyvals.sort(function(kv1,kv2){ kv1=kv1[0]; kv2=kv2[0]; return kv1<kv2?-1:kv1>kv2?1:0 });
					keyvals = keyvals.map(function(kv){ return kv.join(colon1) }).join(comma);
					var oneLine = indent+"{"+opad+keyvals+opad+"}";
					if (opts.wrap===false || oneLine.length<opts.wrap) return oneLine;
					if (opts.short){
						var keyvals=[],i=0;
						for (var k in o) keyvals[i++] = [indent+' '+opad+JSON.stringify(k),o[k]];
						if (opts.sorted) keyvals = keyvals.sort(function(kv1,kv2){ kv1=kv1[0]; kv2=kv2[0]; return kv1<kv2?-1:kv1>kv2?1:0 });
						keyvals[0][0] = keyvals[0][0].replace(indent+' ',indent+'{');
						if (opts.aligned){
							var longest = 0;
							for (var i=keyvals.length;i--;) if (keyvals[i][0].length>longest) longest = keyvals[i][0].length;
							var padding = repeat(' ',longest);
							for (var i=keyvals.length;i--;) keyvals[i][0] = padRight(padding,keyvals[i][0]);
						}
						for (var i=keyvals.length;i--;){
							var k=keyvals[i][0], v=keyvals[i][1];
							var indent2 = repeat(' ',(k+colonN).length);
							var oneLine = k+colonN+build(v,'');
							keyvals[i] = (opts.wrap===false || oneLine.length<=opts.wrap || !v || typeof v!="object") ? oneLine : (k+colonN+build(v,indent2).replace(/^\s+/,''));
						}
						return keyvals.join(',\n') + opad + '}';
					}else{
						var keyvals=[],i=0;
						for (var k in o) keyvals[i++] = [indent+opts.indent+JSON.stringify(k),o[k]];
						if (opts.sorted) keyvals = keyvals.sort(function(kv1,kv2){ kv1=kv1[0]; kv2=kv2[0]; return kv1<kv2?-1:kv1>kv2?1:0 });
						if (opts.aligned){
							var longest = 0;
							for (var i=keyvals.length;i--;) if (keyvals[i][0].length>longest) longest = keyvals[i][0].length;
							var padding = repeat(' ',longest);
							for (var i=keyvals.length;i--;) keyvals[i][0] = padRight(padding,keyvals[i][0]);
						}
						var indent2 = indent+opts.indent;
						for (var i=keyvals.length;i--;){
							var k=keyvals[i][0], v=keyvals[i][1];
							var oneLine = k+colonN+build(v,'');
							keyvals[i] = (opts.wrap===false || oneLine.length<=opts.wrap || !v || typeof v!="object") ? oneLine : (k+colonN+build(v,indent2).replace(/^\s+/,''));
						}
						return indent+'{\n'+keyvals.join(',\n')+'\n'+indent+'}'
					}

				default:
					return indent+JSON.stringify(o);
			}
		}
	}

	function repeat(str,times){ // http://stackoverflow.com/a/17800645/405017
		var result = '';
		while(true){
			if (times & 1) result += str;
			times >>= 1;
			if (times) str += str;
			else break;
		}
		return result;
	}
	function padRight(pad, str){
		return (str + pad).substring(0, pad.length);
	}
}
neatJSON.version = "0.6";

})(typeof exports === 'undefined' ? this : exports);
<commit_msg>Bump version identifier in the JS library<commit_after>(function(exports){
exports.neatJSON = neatJSON;

function neatJSON(value,opts){
	opts = opts || {}
	if (!('wrap'          in opts)) opts.wrap = 80;
	if (opts.wrap==true) opts.wrap = -1;
	if (!('indent'        in opts)) opts.indent = '  ';
	if (!('arrayPadding'  in opts)) opts.arrayPadding  = ('padding' in opts) ? opts.padding : 0;
	if (!('objectPadding' in opts)) opts.objectPadding = ('padding' in opts) ? opts.padding : 0;
	if (!('beforeComma'   in opts)) opts.beforeComma   = ('aroundComma' in opts) ? opts.aroundComma : 0;
	if (!('afterComma'    in opts)) opts.afterComma    = ('aroundComma' in opts) ? opts.aroundComma : 0;
	if (!('beforeColon'   in opts)) opts.beforeColon   = ('aroundColon' in opts) ? opts.aroundColon : 0;
	if (!('afterColon'    in opts)) opts.afterColon    = ('aroundColon' in opts) ? opts.aroundColon : 0;
	if (!('beforeColon1'  in opts)) opts.beforeColon1  = ('aroundColon1' in opts) ? opts.aroundColon1 : ('beforeColon' in opts) ? opts.beforeColon : 0;
	if (!('afterColon1'   in opts)) opts.afterColon1   = ('aroundColon1' in opts) ? opts.aroundColon1 : ('afterColon'  in opts) ? opts.afterColon  : 0;
	if (!('beforeColonN'  in opts)) opts.beforeColonN  = ('aroundColonN' in opts) ? opts.aroundColonN : ('beforeColon' in opts) ? opts.beforeColon : 0;
	if (!('afterColonN'   in opts)) opts.afterColonN   = ('aroundColonN' in opts) ? opts.aroundColonN : ('afterColon'  in opts) ? opts.afterColon  : 0;

	var apad   = repeat(' ',opts.arrayPadding),
	    opad   = repeat(' ',opts.objectPadding),
	    comma  = repeat(' ',opts.beforeComma)+','+repeat(' ',opts.afterComma),
	    colon1 = repeat(' ',opts.beforeColon1)+':'+repeat(' ',opts.afterColon1),
	    colonN = repeat(' ',opts.beforeColonN)+':'+repeat(' ',opts.afterColonN);

	return build(value,'');

	function build(o,indent){
		if (o===null || o===undefined) return indent+'null';
		else{
			switch(o.constructor){
				case Number:
					var isFloat = (o === +o && o !== (o|0));
					return indent + ((isFloat && ('decimals' in opts)) ? o.toFixed(opts.decimals) : (o+''));

				case Array:
					if (!o.length) return indent+"[]";
					var pieces  = o.map(function(v){ return build(v,'') });
					var oneLine = indent+'['+apad+pieces.join(comma)+apad+']';
					if (opts.wrap===false || oneLine.length<=opts.wrap) return oneLine;
					if (opts.short){
						var indent2 = indent+' '+apad;
						pieces = o.map(function(v){ return build(v,indent2) });
						pieces[0] = pieces[0].replace(indent2,indent+'['+apad);
						pieces[pieces.length-1] = pieces[pieces.length-1]+apad+']';
						return pieces.join(',\n');
					}else{
						var indent2 = indent+opts.indent;
						return indent+'[\n'+o.map(function(v){ return build(v,indent2) }).join(',\n')+'\n'+indent+']';
					}

				case Object:
					var keyvals=[],i=0;
					for (var k in o) keyvals[i++] = [JSON.stringify(k), build(o[k],'')];
					if (!keyvals.length) return indent+'{}';
					if (opts.sorted) keyvals = keyvals.sort(function(kv1,kv2){ kv1=kv1[0]; kv2=kv2[0]; return kv1<kv2?-1:kv1>kv2?1:0 });
					keyvals = keyvals.map(function(kv){ return kv.join(colon1) }).join(comma);
					var oneLine = indent+"{"+opad+keyvals+opad+"}";
					if (opts.wrap===false || oneLine.length<opts.wrap) return oneLine;
					if (opts.short){
						var keyvals=[],i=0;
						for (var k in o) keyvals[i++] = [indent+' '+opad+JSON.stringify(k),o[k]];
						if (opts.sorted) keyvals = keyvals.sort(function(kv1,kv2){ kv1=kv1[0]; kv2=kv2[0]; return kv1<kv2?-1:kv1>kv2?1:0 });
						keyvals[0][0] = keyvals[0][0].replace(indent+' ',indent+'{');
						if (opts.aligned){
							var longest = 0;
							for (var i=keyvals.length;i--;) if (keyvals[i][0].length>longest) longest = keyvals[i][0].length;
							var padding = repeat(' ',longest);
							for (var i=keyvals.length;i--;) keyvals[i][0] = padRight(padding,keyvals[i][0]);
						}
						for (var i=keyvals.length;i--;){
							var k=keyvals[i][0], v=keyvals[i][1];
							var indent2 = repeat(' ',(k+colonN).length);
							var oneLine = k+colonN+build(v,'');
							keyvals[i] = (opts.wrap===false || oneLine.length<=opts.wrap || !v || typeof v!="object") ? oneLine : (k+colonN+build(v,indent2).replace(/^\s+/,''));
						}
						return keyvals.join(',\n') + opad + '}';
					}else{
						var keyvals=[],i=0;
						for (var k in o) keyvals[i++] = [indent+opts.indent+JSON.stringify(k),o[k]];
						if (opts.sorted) keyvals = keyvals.sort(function(kv1,kv2){ kv1=kv1[0]; kv2=kv2[0]; return kv1<kv2?-1:kv1>kv2?1:0 });
						if (opts.aligned){
							var longest = 0;
							for (var i=keyvals.length;i--;) if (keyvals[i][0].length>longest) longest = keyvals[i][0].length;
							var padding = repeat(' ',longest);
							for (var i=keyvals.length;i--;) keyvals[i][0] = padRight(padding,keyvals[i][0]);
						}
						var indent2 = indent+opts.indent;
						for (var i=keyvals.length;i--;){
							var k=keyvals[i][0], v=keyvals[i][1];
							var oneLine = k+colonN+build(v,'');
							keyvals[i] = (opts.wrap===false || oneLine.length<=opts.wrap || !v || typeof v!="object") ? oneLine : (k+colonN+build(v,indent2).replace(/^\s+/,''));
						}
						return indent+'{\n'+keyvals.join(',\n')+'\n'+indent+'}'
					}

				default:
					return indent+JSON.stringify(o);
			}
		}
	}

	function repeat(str,times){ // http://stackoverflow.com/a/17800645/405017
		var result = '';
		while(true){
			if (times & 1) result += str;
			times >>= 1;
			if (times) str += str;
			else break;
		}
		return result;
	}
	function padRight(pad, str){
		return (str + pad).substring(0, pad.length);
	}
}
neatJSON.version = "0.6.1";

})(typeof exports === 'undefined' ? this : exports);
<|endoftext|>


<commit_before>
$(document).ready(function() {

$('.mytoggle button').click(function(){
    var ix = $(this).index();

    $('.barcode-checker').toggle( ix === 0 );
    $('.sioc-checker').toggle( ix === 1 );
      // document.getElementById("barcode-checker").blur();
});

// *******SUBMIT BARCODE BUTTON*******
$('#check').click(function() {
	JsBarcode("#barcode", $('#userInput').val());
	return false;
});
// ********END SUBMIT BARCODE BUTTON******

// ******PREFIX BUTTONS******
$("#ambient").click(function() {
	$("#userInput").val("P-1-A").focus();
});

$("#chilled").click(function() {
	$("#userInput").val("P-1-C").focus();
});

$("#freezer").click(function() {
	$("#userInput").val("P-1-F").focus();
});

$("#bigs").click(function() {
	$("#userInput").val("P-1-B").focus();
});

$("#p-cart").click(function() {
				// if
				// 	(document.getElementById("fcLfocation").value == "ONT4")
				// {$("#userInput").val("rbONT40").focus();}
				// else if
				// 	(document.getElementById("fcLocation").value == "OAK4")
				// {$("#userInput").val("rbOAK40").focus();}
				// else
				// {
					$("#userInput").val("rbLAX6").focus();
				// }
			});

$("#oneway").click(function() {
	$("#userInput").val("sp1WAY").focus();
});

$("#s-cart").click(function() {
	$("#userInput").val("SCFRSH0").focus();
});
// ******END PREFIX BUTTONS******

var newBarcode = function() {
	var windowSize = $(window).width();
    //Convert to boolean
    if ($("#userInput").val().charAt(0) == "P" && $("#userInput").val().charAt(1) == "-" && windowSize > 401)
    {
    	$("#barcode").JsBarcode(
    		$("#userInput").val().toUpperCase()
    		)
    }
    else if ($("#userInput").val().charAt(0) == "P" && $("#userInput").val().charAt(1) == "-" && windowSize < 400)
    {
    	$("#barcode").JsBarcode(
    		$("#userInput").val().toUpperCase(), {width: 1}
    		)
    }
    else if ( windowSize < 400)
    {
    	$("#barcode").JsBarcode(
    		$("#userInput").val(), {width: 1}
    		)
    }
    else {
    	$("#barcode").JsBarcode(
    		$("#userInput").val()
    		)}
    };

//<!--  selecting a random array item
-->

function randomWorkstation(listOfStations)
{
	return listOfStations[Math.floor(Math.random()*listOfStations.length)];
}
// $('#randstation').click(function() {
// 	JsBarcode("#barcode", randomWorkstation(listOfStations));
// });

$(function(){
            var hits = 0; //->variable
    //  binding handler to click event
    $('#randstation').click(function(){
                    if  (hits % 2 !== 0)
                    {
    JsBarcode("#barcode", randomWorkstation(listOfStations), {lineColor: "red"});

                    }
                    else
                    {
    JsBarcode("#barcode", randomWorkstation(listOfStations), {lineColor: "green"});

                    }
                   hits++;
        return false;
    });
});

$('#drop-ambient').click(function() {
	if ( $(window).width() < 400) {
		JsBarcode("#barcode", "dz-P-AMBIENT", {width: 1});
	} else {
		JsBarcode("#barcode", "dz-P-AMBIENT");
	}
});

$('#drop-chilled').click(function() {
	if ( $(window).width() < 400) {
		JsBarcode("#barcode", "dz-P-CHILLED", {width: 1});
	} else {
		JsBarcode("#barcode", "dz-P-CHILLED", {lineColor: ""});
	}
});

$('#drop-freezer').click(function() {
	if ( $(window).width() < 400) {
		JsBarcode("#barcode", "dz-P-FROZEN", {width: 1});
	} else {
		JsBarcode("#barcode", "dz-P-FROZEN", {lineColor: ""});
	}
});

	$("#userInput").on('input',newBarcode);
	// $("#userInput").on('input',checkISD);
	$("#barcodeType").change(function(){
	$("#userInput").val( defaultValues[$(this).val()] );
	});

    $('#scanner-button').magnificPopup({
    	items: {
    		src: '#scanner-pop',
    		type: 'inline'
    	},
    	closeBtnInside: true
    });

// *********TOGGLE FUNCTION*********
    $('.toggle-switch').click(function(){
    	$(this).toggleClass("amzorng")
    	$(this).next().slideToggle("fast", function(){
    		if($('.toggle-div').is(":visible")){
    			$('#more').text("less");
    		}else{
    			$('#more').text("more");
    		}
    	});
    });
// *********END TOGGLE FUNCTION*********

});

// **********REAL TIME BARCODE*********
// <script>
//     var checkISD = function() {
//     	if ($("#userInput").val().charAt(6) == "8" && $("#userInput").val().charAt(7) == "0" && $("#userInput").val().charAt(8) == "4" && $("#userInput").val().charAt(9) == "" ){
//     		$('#isd').css('visibility', 'visible');
//     	}
//     	else
//     	{
//     		$('#isd').css('visibility', 'hidden');
//     	}
//     }
//     </script>
//  *******END REAL TIME BARCODE******

// **********MOBILE ALERT*********
// if (screen.width <= 400) {
//     $(function() {
//     $("#mobilealert").show();
//   })
// }
// **********END MOBILE ALERT*********

// **********CHECK ISD*********
//     var checkISD = function() {
//     	if ($("#userInput").val().charAt(6) == "8" && $("#userInput").val().charAt(7) == "0" && $("#userInput").val().charAt(8) == "4" && $("#userInput").val().charAt(9) == "" ){
//     		$('#isd').css('visibility', 'visible');
//     	}
//     	else
//     	{
//     		$('#isd').css('visibility', 'hidden');
//     	}
//     }
// **********END CHECK ISD*********

<commit_msg>happy holidays message<commit_after>
$(document).ready(function() {

$('.mytoggle button').click(function(){
    var ix = $(this).index();

    $('.barcode-checker').toggle( ix === 0 );
    $('.sioc-checker').toggle( ix === 1 );
      // document.getElementById("barcode-checker").blur();
});

// *******SUBMIT BARCODE BUTTON*******
$('#check').click(function() {
	JsBarcode("#barcode", $('#userInput').val());
	return false;
});
// ********END SUBMIT BARCODE BUTTON******

// ******PREFIX BUTTONS******
$("#ambient").click(function() {
	$("#userInput").val("P-1-A").focus();
});

$("#chilled").click(function() {
	$("#userInput").val("P-1-C").focus();
});

$("#freezer").click(function() {
	$("#userInput").val("P-1-F").focus();
});

$("#bigs").click(function() {
	$("#userInput").val("P-1-B").focus();
});

$("#p-cart").click(function() {
				// if
				// 	(document.getElementById("fcLfocation").value == "ONT4")
				// {$("#userInput").val("rbONT40").focus();}
				// else if
				// 	(document.getElementById("fcLocation").value == "OAK4")
				// {$("#userInput").val("rbOAK40").focus();}
				// else
				// {
					$("#userInput").val("rbLAX6").focus();
				// }
			});

$("#oneway").click(function() {
	$("#userInput").val("sp1WAY").focus();
});

$("#s-cart").click(function() {
	$("#userInput").val("SCFRSH0").focus();
});
// ******END PREFIX BUTTONS******

var newBarcode = function() {
	var windowSize = $(window).width();
    //Convert to boolean
    if ($("#userInput").val().charAt(0) == "P" && $("#userInput").val().charAt(1) == "-" && windowSize > 401)
    {
    	$("#barcode").JsBarcode(
    		$("#userInput").val().toUpperCase()
    		)
    }
    else if ($("#userInput").val().charAt(0) == "P" && $("#userInput").val().charAt(1) == "-" && windowSize < 400)
    {
    	$("#barcode").JsBarcode(
    		$("#userInput").val().toUpperCase(), {width: 1}
    		)
    }
    else if ( windowSize < 400)
    {
    	$("#barcode").JsBarcode(
    		$("#userInput").val(), {width: 1}
    		)
    }
    else {
    	$("#barcode").JsBarcode(
    		$("#userInput").val()
    		)}
    };

//<!--  selecting a random array item
-->

function randomWorkstation(listOfStations)
{
	return listOfStations[Math.floor(Math.random()*listOfStations.length)];
}
// $('#randstation').click(function() {
// 	JsBarcode("#barcode", randomWorkstation(listOfStations));
// });

$(function(){
            var hits = 0; //->variable
    //  binding handler to click event
    $('#randstation').click(function(){
        if  (hits % 2 !== 0)
        {
            JsBarcode("#barcode", randomWorkstation(listOfStations), {background: "red", text: "Holidays"});
        }
        else
        {
            JsBarcode("#barcode", randomWorkstation(listOfStations), {background: "green", text: "Happy"});
        }
        hits++;
        return false;
    });
});

$('#drop-ambient').click(function() {
	if ( $(window).width() < 400) {
		JsBarcode("#barcode", "dz-P-AMBIENT", {width: 1});
	} else {
		JsBarcode("#barcode", "dz-P-AMBIENT");
	}
});

$('#drop-chilled').click(function() {
	if ( $(window).width() < 400) {
		JsBarcode("#barcode", "dz-P-CHILLED", {width: 1});
	} else {
		JsBarcode("#barcode", "dz-P-CHILLED", {lineColor: ""});
	}
});

$('#drop-freezer').click(function() {
	if ( $(window).width() < 400) {
		JsBarcode("#barcode", "dz-P-FROZEN", {width: 1});
	} else {
		JsBarcode("#barcode", "dz-P-FROZEN", {lineColor: ""});
	}
});

	$("#userInput").on('input',newBarcode);
	// $("#userInput").on('input',checkISD);
	$("#barcodeType").change(function(){
	$("#userInput").val( defaultValues[$(this).val()] );
	});

    $('#scanner-button').magnificPopup({
    	items: {
    		src: '#scanner-pop',
    		type: 'inline'
    	},
    	closeBtnInside: true
    });

// *********TOGGLE FUNCTION*********
    $('.toggle-switch').click(function(){
    	$(this).toggleClass("amzorng")
    	$(this).next().slideToggle("fast", function(){
    		if($('.toggle-div').is(":visible")){
    			$('#more').text("less");
    		}else{
    			$('#more').text("more");
    		}
    	});
    });
// *********END TOGGLE FUNCTION*********

});

// **********REAL TIME BARCODE*********
// <script>
//     var checkISD = function() {
//     	if ($("#userInput").val().charAt(6) == "8" && $("#userInput").val().charAt(7) == "0" && $("#userInput").val().charAt(8) == "4" && $("#userInput").val().charAt(9) == "" ){
//     		$('#isd').css('visibility', 'visible');
//     	}
//     	else
//     	{
//     		$('#isd').css('visibility', 'hidden');
//     	}
//     }
//     </script>
//  *******END REAL TIME BARCODE******

// **********MOBILE ALERT*********
// if (screen.width <= 400) {
//     $(function() {
//     $("#mobilealert").show();
//   })
// }
// **********END MOBILE ALERT*********

// **********CHECK ISD*********
//     var checkISD = function() {
//     	if ($("#userInput").val().charAt(6) == "8" && $("#userInput").val().charAt(7) == "0" && $("#userInput").val().charAt(8) == "4" && $("#userInput").val().charAt(9) == "" ){
//     		$('#isd').css('visibility', 'visible');
//     	}
//     	else
//     	{
//     		$('#isd').css('visibility', 'hidden');
//     	}
//     }
// **********END CHECK ISD*********

<|endoftext|>


<commit_before>/**
 * phaser <https://github.com/jonschlinkert/phaser>
 *
 * Copyright (c) 2014 Jon Schlinkert, contributors.
 * Licensed under the MIT license.
 */

'use strict';

var path = require('path');
var file = require('fs-utils');
var _ = require('lodash');

module.exports = function(phaser, patterns) {
  var obj = _.extend({}, obj);
  var cwd = phaser.cwd();

  // If patterns is defined as an object,
  // extend the context with it directly
  if(_.isPlainObject(patterns)) {
    obj = _.extend(obj, patterns || {});
  }

  // Else, if patterns is defined as a string,
  // assume it's a filepath or glob patterns and
  // and try to expand it
  if(_.isString(patterns) || _.isArray(patterns)) {
    try {
      file.expand(patterns, {cwd: cwd}).filter(function(filepath) {
        filepath = path.resolve(cwd, filepath);
        if (!file.exists(filepath)) {
          phaser.verbose.error('>> Source file "' + filepath + '" not found.');
          return false;
        } else {
          return true;
        }
      }).map(function(filepath) {
        filepath = path.resolve(cwd, filepath);

        // Prevent errors from non-requireable files.
        try {
          // Then try to require any valid files
          obj = _.extend(obj, require(filepath)(phaser));
          phaser.verbose.success('Registered', filepath);
        } catch(e) {
          phaser.verbose.warn(e);
        }
      });
    } catch (e) {
      e.origin = __filename;
      phaser.verbose.warn('No extensions found: (error code "' + e.code + '").', e);
    }
  }
  console.log(obj);
  return obj;
};

<commit_msg>remove console.log<commit_after>/**
 * phaser <https://github.com/jonschlinkert/phaser>
 *
 * Copyright (c) 2014 Jon Schlinkert, contributors.
 * Licensed under the MIT license.
 */

'use strict';

var path = require('path');
var file = require('fs-utils');
var _ = require('lodash');

module.exports = function(phaser, patterns) {
  var obj = _.extend({}, obj);
  var cwd = phaser.cwd();

  // If patterns is defined as an object,
  // extend the context with it directly
  if(_.isPlainObject(patterns)) {
    obj = _.extend(obj, patterns || {});
  }

  // Else, if patterns is defined as a string,
  // assume it's a filepath or glob patterns and
  // and try to expand it
  if(_.isString(patterns) || _.isArray(patterns)) {
    try {
      file.expand(patterns, {cwd: cwd}).filter(function(filepath) {
        filepath = path.resolve(cwd, filepath);
        if (!file.exists(filepath)) {
          phaser.verbose.error('>> Source file "' + filepath + '" not found.');
          return false;
        } else {
          return true;
        }
      }).map(function(filepath) {
        filepath = path.resolve(cwd, filepath);

        // Prevent errors from non-requireable files.
        try {
          // Then try to require any valid files
          obj = _.extend(obj, require(filepath)(phaser));
          phaser.verbose.success('Registered', filepath);
        } catch(e) {
          phaser.verbose.warn(e);
        }
      });
    } catch (e) {
      e.origin = __filename;
      phaser.verbose.warn('No extensions found: (error code "' + e.code + '").', e);
    }
  }
  return obj;
};

<|endoftext|>


<commit_before>/**
 * Created by sm on 26/05/16.
 */

import  { expect } from 'chai';

import Metadatio from '../../src';
import { Item } from '../../src/data';
import { Entity, Field, DataTypes } from '../../src/metadata';
import MetadatioActions from '../../src/actions/metadatio.actions';

const EXPECTING_ERROR = new Error('An exception was expected here');

describe('The Metadatio actions', () => {
    let entity = null;
    let store = null;
    let actions = null;
    let item = null;

    beforeEach(() => {
        Metadatio.mock();
        entity = new Entity({
            name: 'entity',
            fields: [
                new Field({
                    name: 'field',
                    dataType: DataTypes.string
                })
            ]
        });
        store = Metadatio.store;
        actions = new MetadatioActions(store);

        item = new Item(entity);
    });
    describe('upon item', () => {

        describe('creation', () => {
            it('should verify that an item is sent', (done) => {
                try {
                    actions.scaffold();
                    done(EXPECTING_ERROR);
                } catch(e) {
                    expect(e.className).to.equal('ActionException');
                    expect(e.code).to.equal('AMI001');
                    done();
                }
            });

            it('should verify that the item is an instance of Item', (done) => {
                try {
                    actions.scaffold('wrong');
                    done(EXPECTING_ERROR);
                } catch(e) {
                    expect(e.className).to.equal('ActionException');
                    expect(e.code).to.equal('AMI002');
                    done();
                }
            });

            it('should verify that an entity is sent', (done) => {
                try {
                    actions.scaffold(item);
                    done(EXPECTING_ERROR);
                } catch(e) {
                    expect(e.className).to.equal('ActionException');
                    expect(e.code).to.equal('AMI003');
                    done();
                }
            });

            it('should verify that the entity is an instance of Entity', (done) => {
                try {
                    actions.scaffold(item, 'wrong');
                    done(EXPECTING_ERROR);
                } catch(e) {
                    expect(e.className).to.equal('ActionException');
                    expect(e.code).to.equal('AMI004');
                    done();
                }
            });

            it.skip('should dispatch ITEM_CREATED when requested', () => {
                actions.scaffold(item, entity);

                expect(store.getActions()[1]).to.deep.equal({
                    type: MetadatioActions.ITEM_CREATED,
                    entity: entity,
                    item: {
                        uuid: item.uuid,
                        data: {
                            field: null
                        }
                    }
                });
            });
        });

        describe('removal', () => {
            it('should verify that an item is sent', (done) => {
                try {
                    actions.removeItem();
                    done(EXPECTING_ERROR);
                } catch(e) {
                    expect(e.className).to.equal('ActionException');
                    expect(e.code).to.equal('AMI005');
                    done();
                }
            });

            it('should verify that the item is an instance of Item', (done) => {
                try {
                    actions.removeItem('wrong');
                    done(EXPECTING_ERROR);
                } catch(e) {
                    expect(e.className).to.equal('ActionException');
                    expect(e.code).to.equal('AMI006');
                    done();
                }
            });

            it('should dispatch ITEM_REMOVED when requested', () => {
                actions.removeItem(item, entity);

                expect(store.getActions()[1]).to.deep.equal({
                    type: MetadatioActions.ITEM_REMOVED,
                    uuid: item.uuid
                });
            });
        });
    });

    describe('upon config management', () => {
        describe('for setting a value', () => {
            it('should verify that a key is sent', (done) => {
                try {
                    actions.setConfig();
                    done(EXPECTING_ERROR);
                } catch(e) {
                    expect(e.className).to.equal('ActionException');
                    expect(e.code).to.equal('AMC001');
                    done();
                }
            });

            it('should verify that the key sent is a string', (done) => {
                try {
                    actions.setConfig(123);
                    done(EXPECTING_ERROR);
                } catch(e) {
                    expect(e.className).to.equal('ActionException');
                    expect(e.code).to.equal('AMC002');
                    done();
                }
            });

            it('should verify that a value is sent', (done) => {
                try {
                    actions.setConfig('key');
                    done(EXPECTING_ERROR);
                } catch(e) {
                    expect(e.className).to.equal('ActionException');
                    expect(e.code).to.equal('AMC003');
                    done();
                }
            });

            it('should dispatch CONFIG_SET when requested', () => {
                actions.setConfig('key', 'value');

                expect(store.getActions()[1]).to.deep.equal({
                    type: MetadatioActions.CONFIG_SET,
                    key: 'key',
                    value: 'value'
                });
            });
        });

        describe('for deleting a value', () => {
            it('should verify that a key is sent', (done) => {
                try {
                    actions.deleteConfig();
                    done(EXPECTING_ERROR);
                } catch(e) {
                    expect(e.className).to.equal('ActionException');
                    expect(e.code).to.equal('AMC004');
                    done();
                }
            });

            it('should verify that the key sent is a string', (done) => {
                try {
                    actions.deleteConfig(123);
                    done(EXPECTING_ERROR);
                } catch(e) {
                    expect(e.className).to.equal('ActionException');
                    expect(e.code).to.equal('AMC005');
                    done();
                }
            });

            it('should dispatch CONFIG_DELETED when requested', () => {
                actions.deleteConfig('key');

                expect(store.getActions()[1]).to.deep.equal({
                    type: MetadatioActions.CONFIG_DELETED,
                    key: 'key'
                });
            });
        });
    });

    describe('upon data management', () => {
        describe('for setting a value', () => {
            it('should verify that a key is sent', (done) => {
                try {
                    actions.setData();
                    done(EXPECTING_ERROR);
                } catch(e) {
                    expect(e.className).to.equal('ActionException');
                    expect(e.code).to.equal('AMD001');
                    done();
                }
            });

            it('should verify that the key sent is a string', (done) => {
                try {
                    actions.setData(123);
                    done(EXPECTING_ERROR);
                } catch(e) {
                    expect(e.className).to.equal('ActionException');
                    expect(e.code).to.equal('AMD002');
                    done();
                }
            });

            it('should verify that a value is sent', (done) => {
                try {
                    actions.setData('key');
                    done(EXPECTING_ERROR);
                } catch(e) {
                    expect(e.className).to.equal('ActionException');
                    expect(e.code).to.equal('AMD003');
                    done();
                }
            });

            it('should dispatch DATA_SET when requested', () => {
                actions.setData('key', 'value');

                expect(store.getActions()[1]).to.deep.equal({
                    type: MetadatioActions.DATA_SET,
                    key: 'key',
                    value: 'value'
                });
            });
        });

        describe('for deleting a value', () => {
            it('should verify that a key is sent', (done) => {
                try {
                    actions.deleteData();
                    done(EXPECTING_ERROR);
                } catch(e) {
                    expect(e.className).to.equal('ActionException');
                    expect(e.code).to.equal('AMD004');
                    done();
                }
            });

            it('should verify that the key sent is a string', (done) => {
                try {
                    actions.deleteData(123);
                    done(EXPECTING_ERROR);
                } catch(e) {
                    expect(e.className).to.equal('ActionException');
                    expect(e.code).to.equal('AMD005');
                    done();
                }
            });

            it('should dispatch DATA_DELETED when requested', () => {
                actions.deleteData('key');

                expect(store.getActions()[1]).to.deep.equal({
                    type: MetadatioActions.DATA_DELETED,
                    key: 'key'
                });
            });
        });
    });
});<commit_msg>Fixing test failure upon action verification.<commit_after>/**
 * Created by sm on 26/05/16.
 */

import  { expect } from 'chai';

import Metadatio from '../../src';
import { Item } from '../../src/data';
import { Entity, Field, DataTypes } from '../../src/metadata';
import MetadatioActions from '../../src/actions/metadatio.actions';

const EXPECTING_ERROR = new Error('An exception was expected here');

describe('The Metadatio actions', () => {
    let entity = null;
    let store = null;
    let actions = null;
    let item = null;

    beforeEach(() => {
        Metadatio.mock();
        entity = new Entity({
            name: 'entity',
            fields: [
                new Field({
                    name: 'field',
                    dataType: DataTypes.string
                })
            ]
        });
        store = Metadatio.store;
        actions = new MetadatioActions(store);

        item = new Item(entity);
    });
    describe('upon item', () => {

        describe('creation', () => {
            it('should verify that an item is sent', (done) => {
                try {
                    actions.scaffold();
                    done(EXPECTING_ERROR);
                } catch(e) {
                    expect(e.className).to.equal('ActionException');
                    expect(e.code).to.equal('AMI001');
                    done();
                }
            });

            it('should verify that the item is an instance of Item', (done) => {
                try {
                    actions.scaffold('wrong');
                    done(EXPECTING_ERROR);
                } catch(e) {
                    expect(e.className).to.equal('ActionException');
                    expect(e.code).to.equal('AMI002');
                    done();
                }
            });

            it('should verify that an entity is sent', (done) => {
                try {
                    actions.scaffold(item);
                    done(EXPECTING_ERROR);
                } catch(e) {
                    expect(e.className).to.equal('ActionException');
                    expect(e.code).to.equal('AMI003');
                    done();
                }
            });

            it('should verify that the entity is an instance of Entity', (done) => {
                try {
                    actions.scaffold(item, 'wrong');
                    done(EXPECTING_ERROR);
                } catch(e) {
                    expect(e.className).to.equal('ActionException');
                    expect(e.code).to.equal('AMI004');
                    done();
                }
            });

            it('should dispatch ITEM_CREATED when requested', () => {
                actions.scaffold(item, entity);

                const action = store.getActions()[1];
                expect(action.type).to.equal(MetadatioActions.ITEM_CREATED);
                expect(action.entity).to.equal(entity);
                expect(action.item).to.equal(item);
            });
        });

        describe('removal', () => {
            it('should verify that an item is sent', (done) => {
                try {
                    actions.removeItem();
                    done(EXPECTING_ERROR);
                } catch(e) {
                    expect(e.className).to.equal('ActionException');
                    expect(e.code).to.equal('AMI005');
                    done();
                }
            });

            it('should verify that the item is an instance of Item', (done) => {
                try {
                    actions.removeItem('wrong');
                    done(EXPECTING_ERROR);
                } catch(e) {
                    expect(e.className).to.equal('ActionException');
                    expect(e.code).to.equal('AMI006');
                    done();
                }
            });

            it('should dispatch ITEM_REMOVED when requested', () => {
                actions.removeItem(item, entity);

                expect(store.getActions()[1]).to.deep.equal({
                    type: MetadatioActions.ITEM_REMOVED,
                    uuid: item.uuid
                });
            });
        });
    });

    describe('upon config management', () => {
        describe('for setting a value', () => {
            it('should verify that a key is sent', (done) => {
                try {
                    actions.setConfig();
                    done(EXPECTING_ERROR);
                } catch(e) {
                    expect(e.className).to.equal('ActionException');
                    expect(e.code).to.equal('AMC001');
                    done();
                }
            });

            it('should verify that the key sent is a string', (done) => {
                try {
                    actions.setConfig(123);
                    done(EXPECTING_ERROR);
                } catch(e) {
                    expect(e.className).to.equal('ActionException');
                    expect(e.code).to.equal('AMC002');
                    done();
                }
            });

            it('should verify that a value is sent', (done) => {
                try {
                    actions.setConfig('key');
                    done(EXPECTING_ERROR);
                } catch(e) {
                    expect(e.className).to.equal('ActionException');
                    expect(e.code).to.equal('AMC003');
                    done();
                }
            });

            it('should dispatch CONFIG_SET when requested', () => {
                actions.setConfig('key', 'value');

                expect(store.getActions()[1]).to.deep.equal({
                    type: MetadatioActions.CONFIG_SET,
                    key: 'key',
                    value: 'value'
                });
            });
        });

        describe('for deleting a value', () => {
            it('should verify that a key is sent', (done) => {
                try {
                    actions.deleteConfig();
                    done(EXPECTING_ERROR);
                } catch(e) {
                    expect(e.className).to.equal('ActionException');
                    expect(e.code).to.equal('AMC004');
                    done();
                }
            });

            it('should verify that the key sent is a string', (done) => {
                try {
                    actions.deleteConfig(123);
                    done(EXPECTING_ERROR);
                } catch(e) {
                    expect(e.className).to.equal('ActionException');
                    expect(e.code).to.equal('AMC005');
                    done();
                }
            });

            it('should dispatch CONFIG_DELETED when requested', () => {
                actions.deleteConfig('key');

                expect(store.getActions()[1]).to.deep.equal({
                    type: MetadatioActions.CONFIG_DELETED,
                    key: 'key'
                });
            });
        });
    });

    describe('upon data management', () => {
        describe('for setting a value', () => {
            it('should verify that a key is sent', (done) => {
                try {
                    actions.setData();
                    done(EXPECTING_ERROR);
                } catch(e) {
                    expect(e.className).to.equal('ActionException');
                    expect(e.code).to.equal('AMD001');
                    done();
                }
            });

            it('should verify that the key sent is a string', (done) => {
                try {
                    actions.setData(123);
                    done(EXPECTING_ERROR);
                } catch(e) {
                    expect(e.className).to.equal('ActionException');
                    expect(e.code).to.equal('AMD002');
                    done();
                }
            });

            it('should verify that a value is sent', (done) => {
                try {
                    actions.setData('key');
                    done(EXPECTING_ERROR);
                } catch(e) {
                    expect(e.className).to.equal('ActionException');
                    expect(e.code).to.equal('AMD003');
                    done();
                }
            });

            it('should dispatch DATA_SET when requested', () => {
                actions.setData('key', 'value');

                expect(store.getActions()[1]).to.deep.equal({
                    type: MetadatioActions.DATA_SET,
                    key: 'key',
                    value: 'value'
                });
            });
        });

        describe('for deleting a value', () => {
            it('should verify that a key is sent', (done) => {
                try {
                    actions.deleteData();
                    done(EXPECTING_ERROR);
                } catch(e) {
                    expect(e.className).to.equal('ActionException');
                    expect(e.code).to.equal('AMD004');
                    done();
                }
            });

            it('should verify that the key sent is a string', (done) => {
                try {
                    actions.deleteData(123);
                    done(EXPECTING_ERROR);
                } catch(e) {
                    expect(e.className).to.equal('ActionException');
                    expect(e.code).to.equal('AMD005');
                    done();
                }
            });

            it('should dispatch DATA_DELETED when requested', () => {
                actions.deleteData('key');

                expect(store.getActions()[1]).to.deep.equal({
                    type: MetadatioActions.DATA_DELETED,
                    key: 'key'
                });
            });
        });
    });
});<|endoftext|>