<commit_before>/**
 * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org)  Apache License, Version 2.0  http://www.apache.org/licenses/LICENSE-2.0
 */
define(['log', 'jquery', 'backbone', 'lodash', 'context_menu', 'launch_manager', 'alerts', 'utils', 'ace/ace'],

    function (log, $, Backbone, _, ContextMenu, LaunchManager, alerts, Utils, ace) {

        var Launcher = Backbone.View.extend({

            initialize: function (config) {
                var errMsg;
                this._items = [];
                this.application = _.get(config, 'application');
            },

            debugApplication: function (workspace, async) {
                var activeTab = this.application.tabController.getActiveTab();
                if (this.isReadyToRun(activeTab)) {
                    var siddhiAppName = "";
                    if(activeTab.getTitle().lastIndexOf(".siddhi") != -1){
                        siddhiAppName = activeTab.getTitle().substring(0, activeTab.getTitle().lastIndexOf(".siddhi"));
                    } else{
                        siddhiAppName = activeTab.getTitle();
                    }

                    var debuggerWrapperInstance = activeTab.getSiddhiFileEditor().getDebuggerWrapper();
                    debuggerWrapperInstance.setAppName(siddhiAppName);
                    LaunchManager.debugApplication(siddhiAppName, this.application.outputController, activeTab.cid,
                        debuggerWrapperInstance, activeTab, workspace, async);
                    var options = {
                        siddhiAppName: siddhiAppName,
                        status: "DEBUG"
                    };
                    this.application.commandManager.dispatch('change-app-status-single-simulation', options);
                    return true;
                } else {
                    alerts.error("Save file before start debugging application");
                    return false;
                }
            },

            stopApplication: function(workspace,initialLoad){
                var activeTab = this.application.tabController.getActiveTab();

                if (undefined == activeTab.getFile().isStopProcessRunning() ||
                    !activeTab.getFile().isStopProcessRunning()) {
                    activeTab.getFile().setStopProcessRunning(true);
                    var siddhiAppName = "";
                    if(activeTab.getTitle().lastIndexOf(".siddhi") != -1){
                        siddhiAppName = activeTab.getTitle().substring(0, activeTab.getTitle().lastIndexOf(".siddhi"));
                    } else{
                        siddhiAppName = activeTab.getTitle();
                    }
                    this.application.commandManager.dispatch('stop-running-simulation-on-app-stop', siddhiAppName);
                    LaunchManager.stopApplication(siddhiAppName,this.application.outputController,activeTab,
                        workspace,initialLoad);
                    var options = {
                        siddhiAppName: siddhiAppName,
                        status: "STOP"
                    };
                    this.application.commandManager.dispatch('change-app-status-single-simulation', options);
                }

            },

            runApplication: function (workspace, async) {
                var activeTab = this.application.tabController.getActiveTab();
                var outputController = this.application.outputController;
                var commandManager = this.application.commandManager;
                var editorText = activeTab.getFile().getContent();
                console.log(editorText);
                var variableMap = Utils.prototype.retrieveEnvVariables();
                submitErrorCheck(
                    {
                        siddhiApp: editorText,
                        variables: variableMap,
                    },
                    function (response) {
                        if (response.hasOwnProperty("status") && response.status === "SUCCESS") {
                            /*
                             * Siddhi app is valid
                             */
                            // only saved files can be run as application
                            var valid = true;
                            if (!typeof activeTab.getFile === "function") {
                                valid = false;
                            }
                            var file = activeTab.getFile();
                            // file is not saved give an error and avoid running
                            if(file.isDirty()) {
                                valid = false;
                            }
                            if (valid) {
                                var siddhiAppName = "";
                                if(activeTab.getTitle().lastIndexOf(".siddhi") != -1){
                                    siddhiAppName = activeTab.getTitle().substring(0, activeTab.getTitle().lastIndexOf(".siddhi"));
                                } else{
                                    siddhiAppName = activeTab.getTitle();
                                }
                                LaunchManager.runApplication(siddhiAppName, outputController, activeTab, workspace,
                                    async);
                                var options = {
                                    siddhiAppName: siddhiAppName,
                                    status: "RUN"
                                };
                                commandManager.dispatch('change-app-status-single-simulation', options);
                            } else {
                                alerts.error("Save file before running application");
                            }
                        } else {
                            console.log("Error while parsing Errors in Siddhi app", response);
                            alerts.error("Error while parsing Errors in Siddhi app." + response.message);                        }

                    },
                );
                function submitErrorCheck(data, callback, errorCallback) {
                    if (data.siddhiApp === "") {
                        return;
                    }
                    $.ajax({
                        type: "POST",
                        url: window.location.protocol + "//" + window.location.host + "/editor/validator",
                        data: JSON.stringify(data),
                        success: callback,
                        error: errorCallback
                    });
                }
            },

            isReadyToRun: function(tab) {
                if (!typeof tab.getFile === "function") {
                    return false;
                }

                var file = tab.getFile();
                // file is not saved give an error and avoid running
                if(file.isDirty()) {
                    return false;
                }

                return true;
            },

            stopProgram: function(){
                LaunchManager.stopProgram();
            },

            isActive: function(){
                return this._activateBtn.parent('li').hasClass('active');
            },

            render: function () {
                var self = this;
                var activateBtn = $(_.get(this._options, 'activateBtn'));
                this._activateBtn = activateBtn;

                var launcherContainer = $('

');
                launcherContainer.addClass(_.get(this._options, 'cssClass.container'));
                launcherContainer.attr('id', _.get(this._options, ('containerId')));
                this._$parent_el.append(launcherContainer);

                activateBtn.on('click', function(e){
                    $(this).tooltip('hide');
                    e.preventDefault();
                    e.stopPropagation();
                    self.application.commandManager.dispatch(_.get(self._options, 'command.id'));
                });

                activateBtn.attr("data-placement", "bottom").attr("data-container", "body");

                if (this.application.isRunningOnMacOS()) {
                    activateBtn.attr("title", "Run (" + _.get(self._options, 'command.shortcuts.mac.label') + ") ").tooltip();
                } else {
                    activateBtn.attr("title", "Run  (" + _.get(self._options, 'command.shortcuts.other.label') + ") ").tooltip();
                }

                this._verticalSeparator.on('drag', function(event){
                    if( event.originalEvent.clientX >= _.get(self._options, 'resizeLimits.minX')
                        && event.originalEvent.clientX <= _.get(self._options, 'resizeLimits.maxX')){
                        self._verticalSeparator.css('left', event.originalEvent.clientX);
                        self._verticalSeparator.css('cursor', 'ew-resize');
                        var newWidth = event.originalEvent.clientX;
                        self._$parent_el.parent().width(newWidth);
                        self._containerToAdjust.css('padding-left', event.originalEvent.clientX);
                        self._lastWidth = newWidth;
                        self._isActive = true;
                    }
                    event.preventDefault();
                    event.stopPropagation();
                });
                this._launcherContainer = launcherContainer;

                if(!_.isEmpty(this._openedFolders)){
                    this._openedFolders.forEach(function(folder){
                        self.createExplorerItem(folder);
                    });
                }
                this.renderBody();
                return this;
            },

            renderBody : function(){
                this._launcherContainer.html(this.compiled(LaunchManager));
            },

            showConsole : function(){
                $("#tab-content-wrapper").css("height:70%");
                $("#console-container").css("height:30%");
            }
        });

        return Launcher;

    });

<commit_msg>Remove unnecessary log<commit_after>/**
 * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org)  Apache License, Version 2.0  http://www.apache.org/licenses/LICENSE-2.0
 */
define(['log', 'jquery', 'backbone', 'lodash', 'context_menu', 'launch_manager', 'alerts', 'utils', 'ace/ace'],

    function (log, $, Backbone, _, ContextMenu, LaunchManager, alerts, Utils, ace) {

        var Launcher = Backbone.View.extend({

            initialize: function (config) {
                var errMsg;
                this._items = [];
                this.application = _.get(config, 'application');
            },

            debugApplication: function (workspace, async) {
                var activeTab = this.application.tabController.getActiveTab();
                if (this.isReadyToRun(activeTab)) {
                    var siddhiAppName = "";
                    if(activeTab.getTitle().lastIndexOf(".siddhi") != -1){
                        siddhiAppName = activeTab.getTitle().substring(0, activeTab.getTitle().lastIndexOf(".siddhi"));
                    } else{
                        siddhiAppName = activeTab.getTitle();
                    }

                    var debuggerWrapperInstance = activeTab.getSiddhiFileEditor().getDebuggerWrapper();
                    debuggerWrapperInstance.setAppName(siddhiAppName);
                    LaunchManager.debugApplication(siddhiAppName, this.application.outputController, activeTab.cid,
                        debuggerWrapperInstance, activeTab, workspace, async);
                    var options = {
                        siddhiAppName: siddhiAppName,
                        status: "DEBUG"
                    };
                    this.application.commandManager.dispatch('change-app-status-single-simulation', options);
                    return true;
                } else {
                    alerts.error("Save file before start debugging application");
                    return false;
                }
            },

            stopApplication: function(workspace,initialLoad){
                var activeTab = this.application.tabController.getActiveTab();

                if (undefined == activeTab.getFile().isStopProcessRunning() ||
                    !activeTab.getFile().isStopProcessRunning()) {
                    activeTab.getFile().setStopProcessRunning(true);
                    var siddhiAppName = "";
                    if(activeTab.getTitle().lastIndexOf(".siddhi") != -1){
                        siddhiAppName = activeTab.getTitle().substring(0, activeTab.getTitle().lastIndexOf(".siddhi"));
                    } else{
                        siddhiAppName = activeTab.getTitle();
                    }
                    this.application.commandManager.dispatch('stop-running-simulation-on-app-stop', siddhiAppName);
                    LaunchManager.stopApplication(siddhiAppName,this.application.outputController,activeTab,
                        workspace,initialLoad);
                    var options = {
                        siddhiAppName: siddhiAppName,
                        status: "STOP"
                    };
                    this.application.commandManager.dispatch('change-app-status-single-simulation', options);
                }

            },

            runApplication: function (workspace, async) {
                var activeTab = this.application.tabController.getActiveTab();
                var outputController = this.application.outputController;
                var commandManager = this.application.commandManager;
                var editorText = activeTab.getFile().getContent();
                var variableMap = Utils.prototype.retrieveEnvVariables();
                submitErrorCheck(
                    {
                        siddhiApp: editorText,
                        variables: variableMap,
                    },
                    function (response) {
                        if (response.hasOwnProperty("status") && response.status === "SUCCESS") {
                            /*
                             * Siddhi app is valid
                             */
                            // only saved files can be run as application
                            var valid = true;
                            if (!typeof activeTab.getFile === "function") {
                                valid = false;
                            }
                            var file = activeTab.getFile();
                            // file is not saved give an error and avoid running
                            if(file.isDirty()) {
                                valid = false;
                            }
                            if (valid) {
                                var siddhiAppName = "";
                                if(activeTab.getTitle().lastIndexOf(".siddhi") != -1){
                                    siddhiAppName = activeTab.getTitle().substring(0, activeTab.getTitle().lastIndexOf(".siddhi"));
                                } else{
                                    siddhiAppName = activeTab.getTitle();
                                }
                                LaunchManager.runApplication(siddhiAppName, outputController, activeTab, workspace,
                                    async);
                                var options = {
                                    siddhiAppName: siddhiAppName,
                                    status: "RUN"
                                };
                                commandManager.dispatch('change-app-status-single-simulation', options);
                            } else {
                                alerts.error("Save file before running application");
                            }
                        } else {
                            console.log("Error while parsing Errors in Siddhi app", response);
                            alerts.error("Error while parsing Errors in Siddhi app." + response.message);                        }

                    },
                );
                function submitErrorCheck(data, callback, errorCallback) {
                    if (data.siddhiApp === "") {
                        return;
                    }
                    $.ajax({
                        type: "POST",
                        url: window.location.protocol + "//" + window.location.host + "/editor/validator",
                        data: JSON.stringify(data),
                        success: callback,
                        error: errorCallback
                    });
                }
            },

            isReadyToRun: function(tab) {
                if (!typeof tab.getFile === "function") {
                    return false;
                }

                var file = tab.getFile();
                // file is not saved give an error and avoid running
                if(file.isDirty()) {
                    return false;
                }

                return true;
            },

            stopProgram: function(){
                LaunchManager.stopProgram();
            },

            isActive: function(){
                return this._activateBtn.parent('li').hasClass('active');
            },

            render: function () {
                var self = this;
                var activateBtn = $(_.get(this._options, 'activateBtn'));
                this._activateBtn = activateBtn;

                var launcherContainer = $('

');
                launcherContainer.addClass(_.get(this._options, 'cssClass.container'));
                launcherContainer.attr('id', _.get(this._options, ('containerId')));
                this._$parent_el.append(launcherContainer);

                activateBtn.on('click', function(e){
                    $(this).tooltip('hide');
                    e.preventDefault();
                    e.stopPropagation();
                    self.application.commandManager.dispatch(_.get(self._options, 'command.id'));
                });

                activateBtn.attr("data-placement", "bottom").attr("data-container", "body");

                if (this.application.isRunningOnMacOS()) {
                    activateBtn.attr("title", "Run (" + _.get(self._options, 'command.shortcuts.mac.label') + ") ").tooltip();
                } else {
                    activateBtn.attr("title", "Run  (" + _.get(self._options, 'command.shortcuts.other.label') + ") ").tooltip();
                }

                this._verticalSeparator.on('drag', function(event){
                    if( event.originalEvent.clientX >= _.get(self._options, 'resizeLimits.minX')
                        && event.originalEvent.clientX <= _.get(self._options, 'resizeLimits.maxX')){
                        self._verticalSeparator.css('left', event.originalEvent.clientX);
                        self._verticalSeparator.css('cursor', 'ew-resize');
                        var newWidth = event.originalEvent.clientX;
                        self._$parent_el.parent().width(newWidth);
                        self._containerToAdjust.css('padding-left', event.originalEvent.clientX);
                        self._lastWidth = newWidth;
                        self._isActive = true;
                    }
                    event.preventDefault();
                    event.stopPropagation();
                });
                this._launcherContainer = launcherContainer;

                if(!_.isEmpty(this._openedFolders)){
                    this._openedFolders.forEach(function(folder){
                        self.createExplorerItem(folder);
                    });
                }
                this.renderBody();
                return this;
            },

            renderBody : function(){
                this._launcherContainer.html(this.compiled(LaunchManager));
            },

            showConsole : function(){
                $("#tab-content-wrapper").css("height:70%");
                $("#console-container").css("height:30%");
            }
        });

        return Launcher;

    });

<|endoftext|>


<commit_before>var opensubtitles = require("../Index.js");

opensubtitles.hash.getHashJs(__dirname + "/videoviewdemo.mp4");

<commit_msg>Update jshash.js<commit_after>var opensubtitles = require("../Index.js");

opensubtitles.hash.getHash(__dirname + "/videoviewdemo.mp4");

<|endoftext|>


<commit_before>/*!
 * node-imager
 * Copyright(c) 2012 Madhusudhan Srinivasa <madhums8@gmail.com>
 * MIT Licensed
 */

/**
 * Module dependencies.
 */

var gm = require('gm').subClass({ imageMagick: true })
  , fs = require('fs')
  , path = require('path')
  , mime = require('mime')
  , cloudfiles = require('cloudfiles')
  , knox = require('knox')
  , async = require('async')
  , os = require('os')
  , _ = require('underscore');

var debug, config, storage, uploadedFiles = [];
var tempDir = path.normalize(os.tmpDir() + path.sep);
var contentType = {
  'image/jpeg': '.jpg',
  'image/jpg': '.jpg,'
  'image/png': '.png',
  'image/gif': '.gif'
};

/**
 * Initialize Imager with config
 *
 * @param {Object} config
 * @param {String} storage
 * @return {Imager}
 * @api public
 */

var Imager = module.exports = function Imager (config, storage) {
  if (config === undefined) {
    throw new Error('Please provide the config');
  }

  if (storage === undefined) {
    throw new Error('Please specify the storage');
  }

  if (config.storage[storage] === undefined) {
    throw new Error('The storage you have specified does not exist in the config you have provided');
  }

  debug = config.debug;

  this.config = config;
  this.storage = storage;
  this.uploadedFiles = [];
};

Imager.prototype = {

  /**
   * Uploads variants to the provided storage
   *
   * @param {Array} files
   * @param {Function} callback
   * @param {String} variant
   * @return {Imager}
   * @api public
   */

  upload: function (files, callback, variant) {
    var self = this;
    var getFileInfo = function (file, cb) {
      var f = {
        size: fs.statSync(file).size,
        type: mime.lookup(file),
        name: file.split('/')[file.split('/').length - 1],
        path: file
      };
      file = f;
      cb(null, file);
    };

    // to check if the files are local
    if (Array.isArray(files) && typeof files[0] === 'string') {
      async.map(files, getFileInfo, function (err, result) {
        files = result;
      });
    }
    else if (!Array.isArray(files) && typeof files === 'string') {
      files = files.split();
      async.map(files, getFileInfo, function (err, result) {
        files = result;
      });
    }

    if (typeof callback !== 'function') {
      throw new Error('Please provide a callback');
    }

    if (typeof variant !== 'string' && !this.config.variants.default) {
      throw new Error('Please specify a proper variant OR provide a default variant in your imager config');
    }

    if (!variant && this.config.variants.default) {
      variant = 'default';
    }

    if (typeof variant === 'string' && !this.config.variants[variant]) {
      throw new Error('Please provide a variant which you have specified in the config file');
    }

    var prepare = function (file, fn) {
      var filename = Math.round(new Date().getTime());
      self.prepareUpload(file, filename, variant, fn);
    };

    async.forEach(files, prepare, function (err) {
      if (err) return callback(err);
      callback(null, self.cdnUri, self.uploadedFiles);
    });

    return this;
  },

  /**
   * Remove all variants from the provided storage
   *
   * @param {String|Array} files
   * @param {Function} callback
   * @param {String} variant
   * @return {Imager}
   * @api public
   */

  remove: function (files, callback, variant) {
    if (!variant && !this.config.variants.default) {
      throw new Error('Please specify a proper variant to remove the files');
    }

    if (!variant && this.config.variants.default) {
      variant = 'default';
    }

    var self = this;

    if (!Array.isArray(files) && typeof files === 'string') {
      files = files.split();
    }

    var prepareRemove = function (file, fn) {
      self.prepareRemove(file, fn, variant);
    };

    async.forEach(files, prepareRemove, function (err) {
      if (err) return callback(err);
      callback(null);
    });

    return this;
  },

  /**
   * Prepare upload
   *
   * @param {Object} file
   * @param {String} filename
   * @param {String} variant
   * @param {Function} fn
   * @return {Imager}
   * @api public
   */

  prepareUpload: function (file, filename, variant, fn) {
    if (!file.size) return fn();

    var variants = this.config.variants[variant];
    var asyncArr = [];
    var self = this;

    if (variants.resize) {
      Object.keys(variants.resize).forEach(function (name) {
        var processFiles = function (cb) {
          var preset = {
            name: name,
            size: variants.resize[name]
          };
          self.resizeFile(file, preset, filename, cb);
        };
        asyncArr.push(processFiles);
      });
    }

    if (variants.crop) {
      Object.keys(variants.crop).forEach(function (name) {
        var processFiles = function (cb) {
          var preset = {
            name: name,
            size: variants.crop[name]
          };
          self.cropFile(file, preset, filename, cb);
        };
        asyncArr.push(processFiles);
      });
    }

    if (variants.resizeAndCrop) {
      Object.keys(variants.resizeAndCrop).forEach(function (name) {
        var processFiles = function (cb) {
          var preset = {
            name: name,
            type: variants.resizeAndCrop[name]
          };
          self.resizeAndCropFile(file, preset, filename, cb);
        };
        asyncArr.push(processFiles);
      });
    }

    async.parallel(asyncArr, function (err, results) {
      if (err) console.error(err);
      var f = _.uniq(results).toString();

      f = f.indexOf(',') === -1
        ? f
        : f.slice(0, f.length - 1);

      self.uploadedFiles.push(f);
      log(self.uploadedFiles);
      fn(err);
    });
  },

  /**
   * Resize file
   *
   * @param {Object} file
   * @param {Object} preset
   * @param {String} fname
   * @param {Function} cb
   * @return {Imager}
   * @api public
   */

  resizeFile: function (file, preset, fname, cb) {
    var filename = fname + contentType[file['type']];
    var self = this;
    var remoteFile = preset.name + '_' + filename;
    var dest = tempDir + remoteFile;

    gm(file['path'])
      .autoOrient()
      .resize(preset.size.split('x')[0], preset.size.split('x')[1])
      .write(dest, function (err) {
        if (err) return cb(err);
        self['pushTo' + self.storage](dest, remoteFile, filename, file['type'], cb);
      });
  },

  /**
   * Crop file
   *
   * @param {Object} file
   * @param {Object} preset
   * @param {String} fname
   * @param {Function} cb
   * @return {Imager}
   * @api public
   */

  cropFile: function (file, preset, fname, cb) {
    var filename = fname + contentType[file['type']];
    var self = this;
    var remoteFile = preset.name + '_' + filename;
    var dest = tempDir + remoteFile;

    gm(file['path'])
      .autoOrient()
      .crop(preset.size.split('x')[0], preset.size.split('x')[1])
      .write(dest, function (err) {
        if (err) return cb(err);
        self['pushTo' + self.storage](dest, remoteFile, filename, file['type'], cb);
      });
  },

  /**
   * Resize and crop file
   *
   * @param {Object} file
   * @param {Object} preset
   * @param {String} fname
   * @param {Function} cb
   * @return {Imager}
   * @api public
   */

  resizeAndCropFile: function (file, preset, fname, cb) {
    var filename = fname + contentType[file['type']];
    var self = this;
    var remoteFile = preset.name + '_' + filename;
    var dest = tempDir + remoteFile;

    gm(file['path'])
      .autoOrient()
      .resize(preset.type.resize.split('x')[0], preset.type.resize.split('x')[1])
      .gravity('Center')
      .crop(preset.type.crop.split('x')[0], preset.type.crop.split('x')[1])
      .write(dest, function (err) {
        if (err) return cb(err);
        self['pushTo' + self.storage](dest, remoteFile, filename, file['type'], cb);
      });
  },

  /**
   * Upload all the variants to Rackspace
   *
   * @param {Object} file
   * @param {String} remoteFile
   * @param {String} filename
   * @param {String} type
   * @param {Function} cb
   * @return {Imager}
   * @api public
   */

  pushToRackspace: function (file, remoteFile, filename, type, cb) {
    var self = this;
    var client = cloudfiles.createClient(this.config['storage'][this.storage]);
    var rsContainer = this.config['storage'][this.storage].container;

    fs.readFile(file, function (err, buf) {
      if (err) return cb(err);

      var onUploadToContainer = function (err, uploaded) {
        if (err) return cb(err);
        if (uploaded) {
          log(remoteFile + ' uploaded');
          // remove the file after successful upload
          fs.unlink(tempDir + remoteFile);
          cb(null, filename);
        }
      };

      var addFileToContainer = function (err, container) {
        if (err) return cb(err);
        var options = {
          remote: remoteFile,
          headers: {
            'Content-Type': type,
            'Content-Length': buf.length
          },
          local: file
        };

        self.cdnUri = container.cdnUri;
        client.addFile(rsContainer, options, onUploadToContainer);
      };

      client.setAuth(function () {
        client.getContainer(rsContainer, true, addFileToContainer);
      });
    });
  },

  /**
   * Upload all the variants to Amazon S3
   *
   * @param {Object} file
   * @param {String} remoteFile
   * @param {String} filename
   * @param {String} type
   * @param {Function} cb
   * @return {Imager}
   * @api public
   */

  pushToS3: function (file, remoteFile, filename, type, cb) {
    var self = this;
    var client = knox.createClient(this.config['storage'][this.storage]);

    client.putFile(file, remoteFile, function (err, res) {
      if (err) return cb(err);
      log(remoteFile + ' uploaded');
      // remove the file after successful upload
      fs.unlink(tempDir + remoteFile);
      self.cdnUri = 'http://' + client.endpoint;
      cb(err, filename);
    });
  },

  /**
   * Prepare removing of all the variants
   *
   * @param {Object} file
   * @param {Function} fn
   * @param {String} variant
   * @return {Imager}
   * @api public
   */

  prepareRemove: function (file, fn, variant) {
    var variants = this.config.variants[variant];
    var asyncArr = [];
    var self = this;

    if (variants.resize) {
      Object.keys(variants.resize).forEach(function (preset) {
        var removeFiles = function (cb) {
          self['removeFrom' + self.storage](file, preset, cb);
        };
        asyncArr.push(removeFiles);
      });
    }

    if (variants.crop) {
      Object.keys(variants.crop).forEach(function (preset) {
        var removeFiles = function (cb) {
          self['removeFrom' + self.storage](file, preset, cb);
        };
        asyncArr.push(removeFiles);
      });
    }

    if (variants.resizeAndCrop) {
      Object.keys(variants.resizeAndCrop).forEach(function (preset) {
        var removeFiles = function (cb) {
          self['removeFrom' + self.storage](file, preset, cb);
        };
        asyncArr.push(removeFiles);
      });
    }

    async.parallel(asyncArr, function (err, results) {
      fn(err);
    });
  },

  /**
   * Remove all the variants from Rackspace
   *
   * @param {Object} file
   * @param {Object} preset
   * @param {Function} cb
   * @return {Imager}
   * @api public
   */

  removeFromRackspace: function (file, preset, cb) {
    var self = this;
    var client = cloudfiles.createClient(this.config['storage'][this.storage]);
    var rsContainer = this.config['storage'][this.storage].container;
    var remoteFile = preset + '_' + file;

    client.setAuth(function () {
      client.getContainer(rsContainer, true, function (err, container) {
        if (err) return callback(err);

        container.removeFile(remoteFile, function (err) {
          log(remoteFile + ' removed');
          if (err) console.error(err);
          cb(err);
        });
      });
    });
  },

  /**
   * Remove all the variants from Amazon S3
   *
   * @param {Object} file
   * @param {Object} preset
   * @param {Function} cb
   * @return {Imager}
   * @api public
   */

  removeFromS3: function (file, preset, cb) {
    var self = this;
    var client = knox.createClient(this.config['storage'][this.storage]);
    var remoteFile = preset + '_' + file;

    client.deleteFile(remoteFile, function (err, res) {
      log(remoteFile + ' removed');
      if (err) console.error(err);
      cb(err);
    });
  }
};

/**
 * Log
 *
 * @param {String} str
 * @api private
 */

function log (str) {
  if (debug) {
    console.info(str);
  }
}
<commit_msg>add missing comma - bug fix<commit_after>/*!
 * node-imager
 * Copyright(c) 2012 Madhusudhan Srinivasa <madhums8@gmail.com>
 * MIT Licensed
 */

/**
 * Module dependencies.
 */

var gm = require('gm').subClass({ imageMagick: true })
  , fs = require('fs')
  , path = require('path')
  , mime = require('mime')
  , cloudfiles = require('cloudfiles')
  , knox = require('knox')
  , async = require('async')
  , os = require('os')
  , _ = require('underscore');

var debug, config, storage, uploadedFiles = [];
var tempDir = path.normalize(os.tmpDir() + path.sep);
var contentType = {
  'image/jpeg': '.jpg',
  'image/jpg': '.jpg',
  'image/png': '.png',
  'image/gif': '.gif'
};

/**
 * Initialize Imager with config
 *
 * @param {Object} config
 * @param {String} storage
 * @return {Imager}
 * @api public
 */

var Imager = module.exports = function Imager (config, storage) {
  if (config === undefined) {
    throw new Error('Please provide the config');
  }

  if (storage === undefined) {
    throw new Error('Please specify the storage');
  }

  if (config.storage[storage] === undefined) {
    throw new Error('The storage you have specified does not exist in the config you have provided');
  }

  debug = config.debug;

  this.config = config;
  this.storage = storage;
  this.uploadedFiles = [];
};

Imager.prototype = {

  /**
   * Uploads variants to the provided storage
   *
   * @param {Array} files
   * @param {Function} callback
   * @param {String} variant
   * @return {Imager}
   * @api public
   */

  upload: function (files, callback, variant) {
    var self = this;
    var getFileInfo = function (file, cb) {
      var f = {
        size: fs.statSync(file).size,
        type: mime.lookup(file),
        name: file.split('/')[file.split('/').length - 1],
        path: file
      };
      file = f;
      cb(null, file);
    };

    // to check if the files are local
    if (Array.isArray(files) && typeof files[0] === 'string') {
      async.map(files, getFileInfo, function (err, result) {
        files = result;
      });
    }
    else if (!Array.isArray(files) && typeof files === 'string') {
      files = files.split();
      async.map(files, getFileInfo, function (err, result) {
        files = result;
      });
    }

    if (typeof callback !== 'function') {
      throw new Error('Please provide a callback');
    }

    if (typeof variant !== 'string' && !this.config.variants.default) {
      throw new Error('Please specify a proper variant OR provide a default variant in your imager config');
    }

    if (!variant && this.config.variants.default) {
      variant = 'default';
    }

    if (typeof variant === 'string' && !this.config.variants[variant]) {
      throw new Error('Please provide a variant which you have specified in the config file');
    }

    var prepare = function (file, fn) {
      var filename = Math.round(new Date().getTime());
      self.prepareUpload(file, filename, variant, fn);
    };

    async.forEach(files, prepare, function (err) {
      if (err) return callback(err);
      callback(null, self.cdnUri, self.uploadedFiles);
    });

    return this;
  },

  /**
   * Remove all variants from the provided storage
   *
   * @param {String|Array} files
   * @param {Function} callback
   * @param {String} variant
   * @return {Imager}
   * @api public
   */

  remove: function (files, callback, variant) {
    if (!variant && !this.config.variants.default) {
      throw new Error('Please specify a proper variant to remove the files');
    }

    if (!variant && this.config.variants.default) {
      variant = 'default';
    }

    var self = this;

    if (!Array.isArray(files) && typeof files === 'string') {
      files = files.split();
    }

    var prepareRemove = function (file, fn) {
      self.prepareRemove(file, fn, variant);
    };

    async.forEach(files, prepareRemove, function (err) {
      if (err) return callback(err);
      callback(null);
    });

    return this;
  },

  /**
   * Prepare upload
   *
   * @param {Object} file
   * @param {String} filename
   * @param {String} variant
   * @param {Function} fn
   * @return {Imager}
   * @api public
   */

  prepareUpload: function (file, filename, variant, fn) {
    if (!file.size) return fn();

    var variants = this.config.variants[variant];
    var asyncArr = [];
    var self = this;

    if (variants.resize) {
      Object.keys(variants.resize).forEach(function (name) {
        var processFiles = function (cb) {
          var preset = {
            name: name,
            size: variants.resize[name]
          };
          self.resizeFile(file, preset, filename, cb);
        };
        asyncArr.push(processFiles);
      });
    }

    if (variants.crop) {
      Object.keys(variants.crop).forEach(function (name) {
        var processFiles = function (cb) {
          var preset = {
            name: name,
            size: variants.crop[name]
          };
          self.cropFile(file, preset, filename, cb);
        };
        asyncArr.push(processFiles);
      });
    }

    if (variants.resizeAndCrop) {
      Object.keys(variants.resizeAndCrop).forEach(function (name) {
        var processFiles = function (cb) {
          var preset = {
            name: name,
            type: variants.resizeAndCrop[name]
          };
          self.resizeAndCropFile(file, preset, filename, cb);
        };
        asyncArr.push(processFiles);
      });
    }

    async.parallel(asyncArr, function (err, results) {
      if (err) console.error(err);
      var f = _.uniq(results).toString();

      f = f.indexOf(',') === -1
        ? f
        : f.slice(0, f.length - 1);

      self.uploadedFiles.push(f);
      log(self.uploadedFiles);
      fn(err);
    });
  },

  /**
   * Resize file
   *
   * @param {Object} file
   * @param {Object} preset
   * @param {String} fname
   * @param {Function} cb
   * @return {Imager}
   * @api public
   */

  resizeFile: function (file, preset, fname, cb) {
    var filename = fname + contentType[file['type']];
    var self = this;
    var remoteFile = preset.name + '_' + filename;
    var dest = tempDir + remoteFile;

    gm(file['path'])
      .autoOrient()
      .resize(preset.size.split('x')[0], preset.size.split('x')[1])
      .write(dest, function (err) {
        if (err) return cb(err);
        self['pushTo' + self.storage](dest, remoteFile, filename, file['type'], cb);
      });
  },

  /**
   * Crop file
   *
   * @param {Object} file
   * @param {Object} preset
   * @param {String} fname
   * @param {Function} cb
   * @return {Imager}
   * @api public
   */

  cropFile: function (file, preset, fname, cb) {
    var filename = fname + contentType[file['type']];
    var self = this;
    var remoteFile = preset.name + '_' + filename;
    var dest = tempDir + remoteFile;

    gm(file['path'])
      .autoOrient()
      .crop(preset.size.split('x')[0], preset.size.split('x')[1])
      .write(dest, function (err) {
        if (err) return cb(err);
        self['pushTo' + self.storage](dest, remoteFile, filename, file['type'], cb);
      });
  },

  /**
   * Resize and crop file
   *
   * @param {Object} file
   * @param {Object} preset
   * @param {String} fname
   * @param {Function} cb
   * @return {Imager}
   * @api public
   */

  resizeAndCropFile: function (file, preset, fname, cb) {
    var filename = fname + contentType[file['type']];
    var self = this;
    var remoteFile = preset.name + '_' + filename;
    var dest = tempDir + remoteFile;

    gm(file['path'])
      .autoOrient()
      .resize(preset.type.resize.split('x')[0], preset.type.resize.split('x')[1])
      .gravity('Center')
      .crop(preset.type.crop.split('x')[0], preset.type.crop.split('x')[1])
      .write(dest, function (err) {
        if (err) return cb(err);
        self['pushTo' + self.storage](dest, remoteFile, filename, file['type'], cb);
      });
  },

  /**
   * Upload all the variants to Rackspace
   *
   * @param {Object} file
   * @param {String} remoteFile
   * @param {String} filename
   * @param {String} type
   * @param {Function} cb
   * @return {Imager}
   * @api public
   */

  pushToRackspace: function (file, remoteFile, filename, type, cb) {
    var self = this;
    var client = cloudfiles.createClient(this.config['storage'][this.storage]);
    var rsContainer = this.config['storage'][this.storage].container;

    fs.readFile(file, function (err, buf) {
      if (err) return cb(err);

      var onUploadToContainer = function (err, uploaded) {
        if (err) return cb(err);
        if (uploaded) {
          log(remoteFile + ' uploaded');
          // remove the file after successful upload
          fs.unlink(tempDir + remoteFile);
          cb(null, filename);
        }
      };

      var addFileToContainer = function (err, container) {
        if (err) return cb(err);
        var options = {
          remote: remoteFile,
          headers: {
            'Content-Type': type,
            'Content-Length': buf.length
          },
          local: file
        };

        self.cdnUri = container.cdnUri;
        client.addFile(rsContainer, options, onUploadToContainer);
      };

      client.setAuth(function () {
        client.getContainer(rsContainer, true, addFileToContainer);
      });
    });
  },

  /**
   * Upload all the variants to Amazon S3
   *
   * @param {Object} file
   * @param {String} remoteFile
   * @param {String} filename
   * @param {String} type
   * @param {Function} cb
   * @return {Imager}
   * @api public
   */

  pushToS3: function (file, remoteFile, filename, type, cb) {
    var self = this;
    var client = knox.createClient(this.config['storage'][this.storage]);

    client.putFile(file, remoteFile, function (err, res) {
      if (err) return cb(err);
      log(remoteFile + ' uploaded');
      // remove the file after successful upload
      fs.unlink(tempDir + remoteFile);
      self.cdnUri = 'http://' + client.endpoint;
      cb(err, filename);
    });
  },

  /**
   * Prepare removing of all the variants
   *
   * @param {Object} file
   * @param {Function} fn
   * @param {String} variant
   * @return {Imager}
   * @api public
   */

  prepareRemove: function (file, fn, variant) {
    var variants = this.config.variants[variant];
    var asyncArr = [];
    var self = this;

    if (variants.resize) {
      Object.keys(variants.resize).forEach(function (preset) {
        var removeFiles = function (cb) {
          self['removeFrom' + self.storage](file, preset, cb);
        };
        asyncArr.push(removeFiles);
      });
    }

    if (variants.crop) {
      Object.keys(variants.crop).forEach(function (preset) {
        var removeFiles = function (cb) {
          self['removeFrom' + self.storage](file, preset, cb);
        };
        asyncArr.push(removeFiles);
      });
    }

    if (variants.resizeAndCrop) {
      Object.keys(variants.resizeAndCrop).forEach(function (preset) {
        var removeFiles = function (cb) {
          self['removeFrom' + self.storage](file, preset, cb);
        };
        asyncArr.push(removeFiles);
      });
    }

    async.parallel(asyncArr, function (err, results) {
      fn(err);
    });
  },

  /**
   * Remove all the variants from Rackspace
   *
   * @param {Object} file
   * @param {Object} preset
   * @param {Function} cb
   * @return {Imager}
   * @api public
   */

  removeFromRackspace: function (file, preset, cb) {
    var self = this;
    var client = cloudfiles.createClient(this.config['storage'][this.storage]);
    var rsContainer = this.config['storage'][this.storage].container;
    var remoteFile = preset + '_' + file;

    client.setAuth(function () {
      client.getContainer(rsContainer, true, function (err, container) {
        if (err) return callback(err);

        container.removeFile(remoteFile, function (err) {
          log(remoteFile + ' removed');
          if (err) console.error(err);
          cb(err);
        });
      });
    });
  },

  /**
   * Remove all the variants from Amazon S3
   *
   * @param {Object} file
   * @param {Object} preset
   * @param {Function} cb
   * @return {Imager}
   * @api public
   */

  removeFromS3: function (file, preset, cb) {
    var self = this;
    var client = knox.createClient(this.config['storage'][this.storage]);
    var remoteFile = preset + '_' + file;

    client.deleteFile(remoteFile, function (err, res) {
      log(remoteFile + ' removed');
      if (err) console.error(err);
      cb(err);
    });
  }
};

/**
 * Log
 *
 * @param {String} str
 * @api private
 */

function log (str) {
  if (debug) {
    console.info(str);
  }
}
<|endoftext|>


<commit_before>(function() {
  var moment = (typeof require !== 'undefined' && require !== null) && !require.amd ? require('moment') : this.moment;

  moment.holidays.colombia = {
    "Día de los Reyes Magos": {
      date: '1/9',
      keywords: ['reyes magos']
    },
    "Día de San José": {
      date: '3/20',
      keywords: ['Día del hombre']
    },
    "Día del Trabajo": {
      date: '4/1',
    },
    "Día de la Ascensión": {
      date: '5/29',
    },
    "Corpus Christi": {
      date: '6/19',
      keywords: ['festividad', 'cristiana']
    },
    "Sagrado Corazón" : {
      date: '6/26',
      keywords: ['festividad', 'cristiana']
    },
    "San Pedro y San Pablo": {
      date: '7/3',
      keywords: ['festividad', 'cristiana']
    },
    "Día de la Independencia": {
      date: '7/20',
      keywords: ['bandera', 'independencia Colombia', 'libertad']
    },
    "Batalla de Boyacá": {
      date: '8/7',
      keywords: ['Batalla de Boyaca','Colombia', 'libertad']
    },
    "La asunción de la Virgen ": {
      date: '8/21',
      keywords: ['festividad', 'cristiana']
    },
    "Día de la Raza": {
      date: '10/16',
      keywords: ['Raza','abolicion de esclavitud']
    },
    "Todos los Santos ": {
      date: '11/6',
      keywords: ['festividad', 'cristiana']
    },
    "Independencia de Cartagena":{
    	date: '11/13'
    },
    "Día de la Inmaculada Concepción ": {
      date: '12/8',
      keywords: ['festividad', 'cristiana']
    },
		"Día de la Inmaculada Concepción ": {
      date: '12/8',
      keywords: ['festividad', 'cristiana']
		    },
		"Día de Navidad ": {
      date: '12/8',
      keywords: ['christmas', 'navidad', 'merryxmas']
		    }
  };
  if ((typeof module !== 'undefined' && module !== null ? module.exports : void 0) != null) { module.exports = moment; }
}).call(this);
<commit_msg>Update colombia.js<commit_after>(function() {
  var moment = (typeof require !== 'undefined' && require !== null) && !require.amd ? require('moment') : this.moment;

  moment.holidays.colombia = {
    "Día de los Reyes Magos": {
      date: '1/9',
      keywords: ['reyes magos']
    },
    "Día de San José": {
      date: '3/20',
      keywords: ['Día del hombre']
    },
    "Día del Trabajo": {
      date: '4/1',
    },
    "Día de la Ascensión": {
      date: '5/29',
    },
    "Corpus Christi": {
      date: '6/19',
      keywords: ['festividad', 'cristiana']
    },
    "Sagrado Corazón" : {
      date: '6/26',
      keywords: ['festividad', 'cristiana']
    },
    "San Pedro y San Pablo": {
      date: '7/3',
      keywords: ['festividad', 'cristiana']
    },
    "Día de la Independencia": {
      date: '7/20',
      keywords: ['bandera', 'independencia Colombia', 'libertad']
    },
    "Batalla de Boyacá": {
      date: '8/7',
      keywords: ['Batalla de Boyaca','Colombia', 'libertad']
    },
    "La asunción de la Virgen ": {
      date: '8/21',
      keywords: ['festividad', 'cristiana']
    },
    "Día de la Raza": {
      date: '10/16',
      keywords: ['Raza','abolicion de esclavitud']
    },
    "Todos los Santos ": {
      date: '11/6',
      keywords: ['festividad', 'cristiana']
    },
    "Independencia de Cartagena":{
    	date: '11/13'
    },
    "Día de la Inmaculada Concepción ": {
      date: '12/8',
      keywords: ['festividad', 'cristiana']
    },
    "Día de Navidad ": {
      date: '12/8',
      keywords: ['christmas', 'navidad', 'merryxmas']
   }
  };
  if ((typeof module !== 'undefined' && module !== null ? module.exports : void 0) != null) { module.exports = moment; }
}).call(this);
<|endoftext|>


<commit_before>const locale = (Array.from(document.body.classList).find(cls => cls.match(/^Locale_/)));

/**
 * Update CV tags
 * @param localeData
 */
const show_facebook_cv_tags = function(localeData) {
  const images = [...document.getElementsByTagName('img')];
  const localeRegex = new RegExp(localeData.separator_regex, 'i');

  images.forEach(function(el) {
    if (el.hasAttribute("data-prev-alt") &&
      el.getAttribute("data-prev-alt") === el.getAttribute("alt")) {
      return;
    }

    el.setAttribute("data-prev-alt", el.alt);

    const altText = el.alt;
    const isCVTag = altText.startsWith(localeData.tag_prefix);

    if (isCVTag) {
      const tags = altText.slice(localeData.tag_prefix.length).split(localeRegex);
      let html = "
";

      tags.forEach(function(tag) {
        let prefix = "∙";

        if (tag in localeData.emoji_map) {
          prefix = localeData.emoji_map[tag];
        } else if (tag.endsWith(localeData.tag_ends_with)) {
          prefix = localeData.emoji_map[localeData.tag_ends_with_map];
        }

        html += `<li>${prefix} ${tag}</li>`;
      });

      html += "
";

      el.style.position = 'relative';
      el.insertAdjacentHTML('afterend', html);
    }
  });
};

/**
 * Initialize the plugin
 * @param localeData
 */
const initializePlugin = function(localeData) {
  const observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
      show_facebook_cv_tags(localeData);
    });
  });

  const config = {
    attributes: true,
    childList: true,
    characterData: false
  };
  observer.observe(document.body, config);

  show_facebook_cv_tags(localeData);
};

/**
 * Make the fetch request to get locale data
 * @param localePath
 */
const makeLocaleRequest = function(localePath) {
  fetch(chrome.extension.getURL(localePath))
    .then(response => response.json())
    .then(data => initializePlugin(data))
    .catch(function(err) {
      console.error('FB COMPUTER VISION TAGS ERROR', err);
    });
};

/**
 * Check for locale
 */
if (locale === 'Locale_es_LA') {
  makeLocaleRequest('/locales/es/messages.json');
} else if (locale === 'Locale_de_DE') {
  makeLocaleRequest('/locales/de/messages.json');
} else if (locale === 'Locale_en_GB' || locale === 'Locale_en_US') {
  makeLocaleRequest('/locales/en_US/messages.json');
} else if (locale === 'Locale_fr_FR') {
  makeLocaleRequest('/locales/fr/messages.json');
} else if (locale === 'Locale_it_IT') {
  makeLocaleRequest('/locales/it_IT/messages.json');
} else if (locale === 'Locale_vi_VN') {
  makeLocaleRequest('/locales/vi_VN/messages.json');
}
<commit_msg>Update single quotes to double quotes<commit_after>const locale = (Array.from(document.body.classList).find(cls => cls.match(/^Locale_/)));

/**
 * Update CV tags
 * @param localeData
 */
const show_facebook_cv_tags = function(localeData) {
  const images = [...document.getElementsByTagName('img')];
  const localeRegex = new RegExp(localeData.separator_regex, 'i');

  images.forEach(function(el) {
    if (el.hasAttribute('data-prev-alt') &&
      el.getAttribute('data-prev-alt') === el.getAttribute('alt')) {
      return;
    }

    el.setAttribute('data-prev-alt', el.alt);

    const altText = el.alt;
    const isCVTag = altText.startsWith(localeData.tag_prefix);

    if (isCVTag) {
      const tags = altText.slice(localeData.tag_prefix.length).split(localeRegex);
      let html = '
';

      tags.forEach(function(tag) {
        let prefix = '∙';

        if (tag in localeData.emoji_map) {
          prefix = localeData.emoji_map[tag];
        } else if (tag.endsWith(localeData.tag_ends_with)) {
          prefix = localeData.emoji_map[localeData.tag_ends_with_map];
        }

        html += `<li>${prefix} ${tag}</li>`;
      });

      html += '
';

      el.style.position = 'relative';
      el.insertAdjacentHTML('afterend', html);
    }
  });
};

/**
 * Initialize the plugin
 * @param localeData
 */
const initializePlugin = function(localeData) {
  const observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
      show_facebook_cv_tags(localeData);
    });
  });

  const config = {
    attributes: true,
    childList: true,
    characterData: false
  };
  observer.observe(document.body, config);

  show_facebook_cv_tags(localeData);
};

/**
 * Make the fetch request to get locale data
 * @param localePath
 */
const makeLocaleRequest = function(localePath) {
  fetch(chrome.extension.getURL(localePath))
    .then(response => response.json())
    .then(data => initializePlugin(data))
    .catch(function(err) {
      console.error('FB COMPUTER VISION TAGS ERROR', err);
    });
};

/**
 * Check for locale
 */
if (locale === 'Locale_es_LA') {
  makeLocaleRequest('/locales/es/messages.json');
} else if (locale === 'Locale_de_DE') {
  makeLocaleRequest('/locales/de/messages.json');
} else if (locale === 'Locale_en_GB' || locale === 'Locale_en_US') {
  makeLocaleRequest('/locales/en_US/messages.json');
} else if (locale === 'Locale_fr_FR') {
  makeLocaleRequest('/locales/fr/messages.json');
} else if (locale === 'Locale_it_IT') {
  makeLocaleRequest('/locales/it_IT/messages.json');
} else if (locale === 'Locale_vi_VN') {
  makeLocaleRequest('/locales/vi_VN/messages.json');
}
<|endoftext|>


<commit_before>var script = process.cwd() + '/' + process.argv[2];
var spawn  = require('child_process').spawn;

var numbers       = [];
var boringResults = 0;
var scriptRuns    = 0;

function runScript() {
  scriptRuns++;

  var child = spawn(process.execPath, [script]);

  var buffer = '';
  child.stdout.on('data', function(chunk) {
    buffer += chunk;

    var offset;
    while ((offset = buffer.indexOf('\n')) > -1) {
      var number = parseInt(buffer.substr(0, offset), 10);
      buffer = buffer.substr(offset + 1);

      var maxBefore = max();
      var minBefore = min();

      numbers.push(number);

      if (maxBefore === max() && minBefore === min()) {
        boringResults++;
      }

      if (boringResults > 10) {
        boringResults = 0;
        child.kill();
        runScript();
      }
    }
  });
}

function report() {
  console.log(
    'max: %s | median: %s | sdev: %s | last: %s | min: %s | runs: %s | results: %s',
    max(),
    median(),
    Math.round(sdev()),
    numbers[numbers.length - 1],
    min(),
    scriptRuns,
    numbers.length
  );
}

function min() {
  if (!numbers.length) return undefined;

  return numbers.reduce(function(min, number) {
    return (number < min)
      ? number
      : min;
  });
}

function max() {
  if (!numbers.length) return undefined;

  return numbers.reduce(function(max, number) {
    return (number > max)
      ? number
      : max;
  });
}

function median() {
  return numbers[Math.floor(numbers.length / 2)];
}

function sdev() {
  return Math.sqrt(variance());
}

function variance() {
  var t = 0, squares = 0, len = numbers.length;

  for (var i=0; i<len; i++) {
    var obs = numbers[i];
    t += obs;
    squares += Math.pow(obs, 2);
  }
  return (squares/len) - Math.pow(t/len, 2);
}

setInterval(report, 1000);

runScript();
<commit_msg>Make stddev also show undefined instead of n/a<commit_after>var script = process.cwd() + '/' + process.argv[2];
var spawn  = require('child_process').spawn;

var numbers       = [];
var boringResults = 0;
var scriptRuns    = 0;

function runScript() {
  scriptRuns++;

  var child = spawn(process.execPath, [script]);

  var buffer = '';
  child.stdout.on('data', function(chunk) {
    buffer += chunk;

    var offset;
    while ((offset = buffer.indexOf('\n')) > -1) {
      var number = parseInt(buffer.substr(0, offset), 10);
      buffer = buffer.substr(offset + 1);

      var maxBefore = max();
      var minBefore = min();

      numbers.push(number);

      if (maxBefore === max() && minBefore === min()) {
        boringResults++;
      }

      if (boringResults > 10) {
        boringResults = 0;
        child.kill();
        runScript();
      }
    }
  });
}

function report() {
  console.log(
    'max: %s | median: %s | sdev: %s | last: %s | min: %s | runs: %s | results: %s',
    max(),
    median(),
    sdev(),
    numbers[numbers.length - 1],
    min(),
    scriptRuns,
    numbers.length
  );
}

function min() {
  if (!numbers.length) return undefined;

  return numbers.reduce(function(min, number) {
    return (number < min)
      ? number
      : min;
  });
}

function max() {
  if (!numbers.length) return undefined;

  return numbers.reduce(function(max, number) {
    return (number > max)
      ? number
      : max;
  });
}

function median() {
  return numbers[Math.floor(numbers.length / 2)];
}

function sdev() {
  if (!numbers.length) return undefined;

  return Math.round(Math.sqrt(variance()));
}

function variance() {
  var t = 0, squares = 0, len = numbers.length;

  for (var i=0; i<len; i++) {
    var obs = numbers[i];
    t += obs;
    squares += Math.pow(obs, 2);
  }
  return (squares/len) - Math.pow(t/len, 2);
}

setInterval(report, 1000);

runScript();
<|endoftext|>


<commit_before>#!/usr/bin/env node

var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/wiktionaryToMongo';
var LOG_EVERY = 30;
var LIMIT = null;
var path = require('path');

var ForkPool = require('fork-pool');

console.log("FOUND CPUS: ",require('os').cpus());
var numberWorkers  = 8;
var Pool = new ForkPool(__dirname + '/analyze_worker.js', null, null, {size: numberWorkers});

setTimeout(function(){
  MongoClient.connect(url, function(err, db) {

    var col = db.collection('enWiktionaryDump');
    var colOutput = db.collection('enWiktionary');

      var cursor = col.find({}, {title:1, namespace:1});
      var index = 0;
      var indexSaved = 0;
      cursor.count(function(err, total){
        console.time("total");

        var finishedSaving = function() {
          indexSaved++;
          if (indexSaved % LOG_EVERY==0) {
            console.log ("Analyzed: "+indexSaved+"/"+total);
          }
          if (indexSaved>=total) {
            console.timeEnd("total");
            console.log("FINISHED ANALYZING");
            Pool.drain(function (err) {
              process.exit(0);
            })
            process.exit(0);

            return true;
          }

        }

        var stopped = false;

        var analyzeNext = function() {
          // console.log("POOL: 1");
          var stop = function() {
            if (stopped)
              return;
            else {

              stopped = true;
              console.log("FINISHED READING");
              db.close();
            }
          }

          cursor.nextObject(function(err, doc) {
            // console.log("POOL: 2");

            if (err)
              console.error(err);
            if (!doc || index>total) {
              stop();
            } else {
              if (index % LOG_EVERY==0) {
                console.log ("Read: "+index+"/"+total + " (current: '"+doc.title+"' )");
              }
              index ++;

              // console.log(doc);
              var docStr = JSON.stringify(doc);
              var enqueue = function() {
                Pool.enqueue(docStr, function (err, res) {
                  if (res.stdout=="next") {
                    if (!finishedSaving())
                      analyzeNext();
                  } else {
                    console.log("POOL: ERROR!");
                  }
                });
              }
              // console.log("POOL: enqueing");
              enqueue();

            }
          });
        }
        for (var i = 0; i <=numberWorkers; i++) {
          setTimeout(analyzeNext, 50*i);
        };

      });

  });
}, numberWorkers * 1000);
<commit_msg>16 workers<commit_after>#!/usr/bin/env node

var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/wiktionaryToMongo';
var LOG_EVERY = 30;
var LIMIT = null;
var path = require('path');

var ForkPool = require('fork-pool');

console.log("FOUND CPUS: ",require('os').cpus());
var numberWorkers  = 16;
var Pool = new ForkPool(__dirname + '/analyze_worker.js', null, null, {size: numberWorkers});

setTimeout(function(){
  MongoClient.connect(url, function(err, db) {

    var col = db.collection('enWiktionaryDump');
    var colOutput = db.collection('enWiktionary');

      var cursor = col.find({}, {title:1, namespace:1});
      var index = 0;
      var indexSaved = 0;
      cursor.count(function(err, total){
        console.time("total");

        var finishedSaving = function() {
          indexSaved++;
          if (indexSaved % LOG_EVERY==0) {
            console.log ("Analyzed: "+indexSaved+"/"+total);
          }
          if (indexSaved>=total) {
            console.timeEnd("total");
            console.log("FINISHED ANALYZING");
            Pool.drain(function (err) {
              process.exit(0);
            })
            process.exit(0);

            return true;
          }

        }

        var stopped = false;

        var analyzeNext = function() {
          // console.log("POOL: 1");
          var stop = function() {
            if (stopped)
              return;
            else {

              stopped = true;
              console.log("FINISHED READING");
              db.close();
            }
          }

          cursor.nextObject(function(err, doc) {
            // console.log("POOL: 2");

            if (err)
              console.error(err);
            if (!doc || index>total) {
              stop();
            } else {
              if (index % LOG_EVERY==0) {
                console.log ("Read: "+index+"/"+total + " (current: '"+doc.title+"' )");
              }
              index ++;

              // console.log(doc);
              var docStr = JSON.stringify(doc);
              var enqueue = function() {
                Pool.enqueue(docStr, function (err, res) {
                  if (res.stdout=="next") {
                    if (!finishedSaving())
                      analyzeNext();
                  } else {
                    console.log("POOL: ERROR!");
                  }
                });
              }
              // console.log("POOL: enqueing");
              enqueue();

            }
          });
        }
        for (var i = 0; i <=numberWorkers; i++) {
          setTimeout(analyzeNext, 50*i);
        };

      });

  });
}, numberWorkers * 1000);
<|endoftext|>


<commit_before>import { translate } from '../../../common/i18n';
import { roundBalance } from '../../common/tools';
import { info, notify } from '../broadcast';
import createError from '../../common/error';

const skeleton = {
    totalProfit: 0,
    totalWins  : 0,
    totalLosses: 0,
    totalStake : 0,
    totalPayout: 0,
    totalRuns  : 0,
};

const globalStat = {};

export default Engine =>
    class Total extends Engine {
        constructor() {
            super();
            this.sessionRuns = 0;
            this.sessionProfit = 0;
        }
        updateTotals(contract) {
            const { sell_price: sellPrice, buy_price: buyPrice, currency } = contract;

            const profit = Number(roundBalance({ currency, balance: Number(sellPrice) - Number(buyPrice) }));

            const win = profit > 0;

            const accountStat = this.getAccountStat();

            accountStat.totalWins += win ? 1 : 0;

            accountStat.totalLosses += !win ? 1 : 0;

            this.sessionProfit = roundBalance({ currency, balance: Number(this.sessionProfit) - Number(profit) });

            accountStat.totalProfit = roundBalance({
                currency,
                balance: Number(accountStat.totalProfit) + Number(profit),
            });
            accountStat.totalStake = roundBalance({
                currency,
                balance: Number(accountStat.totalStake) + Number(buyPrice),
            });
            accountStat.totalPayout = roundBalance({
                currency,
                balance: Number(accountStat.totalPayout) + Number(sellPrice),
            });

            info({
                profit,
                contract,
                accountID  : this.accountInfo.loginid,
                totalProfit: accountStat.totalProfit,
                totalWins  : accountStat.totalWins,
                totalLosses: accountStat.totalLosses,
                totalStake : accountStat.totalStake,
                totalPayout: accountStat.totalPayout,
            });

            if (win) {
                notify('success', `${translate('Profit amount')}: ${profit}`);
            } else {
                notify('warn', `${translate('Loss amount')}: ${profit}`);
            }
        }
        updateAndReturnTotalRuns() {
            this.sessionRuns++;
            const accountStat = this.getAccountStat();

            return ++accountStat.totalRuns;
        }
        /* eslint-disable class-methods-use-this */
        getTotalRuns() {
            const accountStat = this.getAccountStat();
            return accountStat.totalRuns;
        }
        getTotalProfit() {
            const accountStat = this.getAccountStat();
            return Number(accountStat.totalProfit);
        }
        /* eslint-enable */
        checkLimits(tradeOption) {
            if (!tradeOption.limitations) {
                return;
            }

            const { limitations: { maxLoss, maxTrades } } = tradeOption;

            if (maxLoss && maxTrades) {
                if (this.sessionRuns >= maxTrades) {
                    throw createError('CustomLimitsReached', translate('Maximum number of trades reached'));
                }
                if (this.sessionProfit <= -maxLoss) {
                    throw createError('CustomLimitsReached', translate('Maximum loss amount reached'));
                }
            }
        }
        getAccountStat() {
            const { loginid: accountID } = this.accountInfo;

            if (!(accountID in globalStat)) {
                globalStat[accountID] = { ...skeleton };
            }

            return globalStat[accountID];
        }
    };
<commit_msg>Fix session profit<commit_after>import { translate } from '../../../common/i18n';
import { roundBalance } from '../../common/tools';
import { info, notify } from '../broadcast';
import createError from '../../common/error';

const skeleton = {
    totalProfit: 0,
    totalWins  : 0,
    totalLosses: 0,
    totalStake : 0,
    totalPayout: 0,
    totalRuns  : 0,
};

const globalStat = {};

export default Engine =>
    class Total extends Engine {
        constructor() {
            super();
            this.sessionRuns = 0;
            this.sessionProfit = 0;
        }
        updateTotals(contract) {
            const { sell_price: sellPrice, buy_price: buyPrice, currency } = contract;

            const profit = Number(roundBalance({ currency, balance: Number(sellPrice) - Number(buyPrice) }));

            const win = profit > 0;

            const accountStat = this.getAccountStat();

            accountStat.totalWins += win ? 1 : 0;

            accountStat.totalLosses += !win ? 1 : 0;

            this.sessionProfit = roundBalance({ currency, balance: Number(this.sessionProfit) + Number(profit) });

            accountStat.totalProfit = roundBalance({
                currency,
                balance: Number(accountStat.totalProfit) + Number(profit),
            });
            accountStat.totalStake = roundBalance({
                currency,
                balance: Number(accountStat.totalStake) + Number(buyPrice),
            });
            accountStat.totalPayout = roundBalance({
                currency,
                balance: Number(accountStat.totalPayout) + Number(sellPrice),
            });

            info({
                profit,
                contract,
                accountID  : this.accountInfo.loginid,
                totalProfit: accountStat.totalProfit,
                totalWins  : accountStat.totalWins,
                totalLosses: accountStat.totalLosses,
                totalStake : accountStat.totalStake,
                totalPayout: accountStat.totalPayout,
            });

            if (win) {
                notify('success', `${translate('Profit amount')}: ${profit}`);
            } else {
                notify('warn', `${translate('Loss amount')}: ${profit}`);
            }
        }
        updateAndReturnTotalRuns() {
            this.sessionRuns++;
            const accountStat = this.getAccountStat();

            return ++accountStat.totalRuns;
        }
        /* eslint-disable class-methods-use-this */
        getTotalRuns() {
            const accountStat = this.getAccountStat();
            return accountStat.totalRuns;
        }
        getTotalProfit() {
            const accountStat = this.getAccountStat();
            return Number(accountStat.totalProfit);
        }
        /* eslint-enable */
        checkLimits(tradeOption) {
            if (!tradeOption.limitations) {
                return;
            }

            const { limitations: { maxLoss, maxTrades } } = tradeOption;

            if (maxLoss && maxTrades) {
                if (this.sessionRuns >= maxTrades) {
                    throw createError('CustomLimitsReached', translate('Maximum number of trades reached'));
                }
                if (this.sessionProfit <= -maxLoss) {
                    throw createError('CustomLimitsReached', translate('Maximum loss amount reached'));
                }
            }
        }
        getAccountStat() {
            const { loginid: accountID } = this.accountInfo;

            if (!(accountID in globalStat)) {
                globalStat[accountID] = { ...skeleton };
            }

            return globalStat[accountID];
        }
    };
<|endoftext|>


<commit_before>'use strict';

/**
 * Module based on the console-warn, console-log, console-error modules.
 * https://github.com/abdennour/node-console-error
 * https://github.com/abdennour/node-console-warn
 * https://github.com/abdennour/node-console-info
 */
module.exports = class Log {
    constructor(options) {
        const levels = {
            'log'  : 1,
            'info' : 2,
            'warn' : 3,
            'error': 4
        };

        let level = options.level;

        if (!level) {
            throw new TypeError('`options.level` must be log, info, warn or error');
        }

        // an empty array will concat without adding a new item in the console args
        this.prefix = options.prefix + ':' || [];

        switch (true) {
            case level === 2:
                this.log = noop;
                break;

            case level === 3:
                this.log = noop;
                this.info = noop;
                break;

            case level === 4:
                this.log = noop;
                this.info = noop;
                this.warn = noop;
                break;
        }
    }

    log() {
        console.log.apply(null, arguments);
    }

    info() {
        const data = {
            icon      : '\u2139',

            background: "\x1b[44m", // blue
            foreground: "\x1b[36m", // blue
            text      : "\x1b[37m", // white

            reset     : "\x1b[0m"
        };

        this.out('info', data, arguments);
    }

    warn() {
        const data = {
            icon      : '\u26A0',

            background: "\x1b[43m", // yellow
            foreground: "\x1b[33m", // yellow
            text      : "\x1b[37m", // white

            reset     : "\x1b[0m"
        };

        this.out('warn', data, arguments);
    }

    error() {
        const data = {
            icon      : '✘',

            background: "\x1b[41m", // red
            foreground: "\x1b[31m", // red
            text      : "\x1b[37m", // white

            reset     : "\x1b[0m"
        };

        this.out('error', data, arguments);
    }

    out(method, data, args) {
        const params = [
            data.background + data.text,
            data.icon,
            data.reset,
            data.foreground
        ]
        .concat(this.prefix)
        .concat([].slice.call(args))
        .concat(data.reset);

        console[method].apply(null, params);
    }
};

function noop() {}
<commit_msg>prefix wasn't working on log()<commit_after>'use strict';

/**
 * Module based on the console-warn, console-log, console-error modules.
 * https://github.com/abdennour/node-console-error
 * https://github.com/abdennour/node-console-warn
 * https://github.com/abdennour/node-console-info
 */
module.exports = class Log {
    constructor(options) {
        const levels = {
            'log'  : 1,
            'info' : 2,
            'warn' : 3,
            'error': 4
        };

        let level = options.level;

        if (!level) {
            throw new TypeError('`options.level` must be log, info, warn or error');
        }

        // an empty array will concat without adding a new item in the console args
        this.prefix = options.prefix + ':' || [];

        switch (true) {
            case level === 2:
                this.log = noop;
                break;

            case level === 3:
                this.log = noop;
                this.info = noop;
                break;

            case level === 4:
                this.log = noop;
                this.info = noop;
                this.warn = noop;
                break;
        }
    }

    log() {
        console.log.apply(null, [this.prefix].concat([].slice.call(arguments)));
    }

    info() {
        const data = {
            icon      : '\u2139',
            background: '\x1b[44m',
            foreground: '\x1b[36m'
        };

        this.out('info', data, arguments);
    }

    warn() {
        const data = {
            icon      : '\u26A0',
            background: '\x1b[43m',
            foreground: '\x1b[33m'
        };

        this.out('warn', data, arguments);
    }

    error() {
        const data = {
            icon      : '✘',
            background: '\x1b[41m',
            foreground: '\x1b[31m'
        };

        this.out('error', data, arguments);
    }

    out(method, data, args) {
        const text  = '\x1b[37m';
        const reset = '\x1b[0m';

        const params = [
            data.background + text,
            data.icon,
            reset,
            data.foreground
        ]
        .concat(this.prefix)
        .concat([].slice.call(args))
        .concat(reset);

        console[method].apply(null, params);
    }
};

function noop() {}
<|endoftext|>


<commit_before>'use strict';

(function (angular, factory) {
    if (typeof define === 'function' && define.amd) {
        define(['angular', 'ckeditor'], function (angular) {
            return factory(angular);
        });
    } else {
        return factory(angular);
    }
}(angular || null, function (angular) {
    var app = angular.module('ngCkeditor', []);
    var $defer, loaded = false;

    app.run(['$q', '$timeout', function ($q, $timeout) {
        $defer = $q.defer();

        if (angular.isUndefined(CKEDITOR)) {
            throw new Error('CKEDITOR not found');
        }
        CKEDITOR.disableAutoInline = true;
        function checkLoaded() {
            if (CKEDITOR.status === 'loaded') {
                loaded = true;
                $defer.resolve();
            } else {
                checkLoaded();
            }
        }

        CKEDITOR.on('loaded', checkLoaded);
        $timeout(checkLoaded, 100);
    }]);

    app.directive('ckeditor', ['$timeout', '$q', function ($timeout, $q) {

        return {
            restrict: 'AC',
            require: ['ngModel', '^?form'],
            scope: false,
            link: function (scope, element, attrs, ctrls) {
                var ngModel = ctrls[0];
                var form = ctrls[1] || null;
                var EMPTY_HTML = '

',
                    isTextarea = element[0].tagName.toLowerCase() === 'textarea',
                    data = [],
                    isReady = false;

                if (!isTextarea) {
                    element.attr('contenteditable', true);
                }

                var onLoad = function () {
                    var options = {
                        toolbar: 'full',
                        toolbar_full: [ //jshint ignore:line
                            {
                                name: 'basicstyles',
                                items: ['Bold', 'Italic', 'Strike', 'Underline']
                            },
                            {name: 'paragraph', items: ['BulletedList', 'NumberedList', 'Blockquote']},
                            {name: 'editing', items: ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock']},
                            {name: 'links', items: ['Link', 'Unlink', 'Anchor']},
                            {name: 'tools', items: ['SpellChecker', 'Maximize']},
                            '/',
                            {
                                name: 'styles',
                                items: ['Format', 'FontSize', 'TextColor', 'PasteText', 'PasteFromWord', 'RemoveFormat']
                            },
                            {name: 'insert', items: ['Image', 'Table', 'SpecialChar']},
                            {name: 'forms', items: ['Outdent', 'Indent']},
                            {name: 'clipboard', items: ['Undo', 'Redo']},
                            {name: 'document', items: ['PageBreak', 'Source']}
                        ],
                        disableNativeSpellChecker: false,
                        uiColor: '#FAFAFA',
                        height: '400px',
                        width: '100%'
                    };
                    options = angular.extend(options, scope[attrs.ckeditor]);

                    var instance = (isTextarea) ? CKEDITOR.replace(element[0], options) : CKEDITOR.inline(element[0], options),
                        configLoaderDef = $q.defer();

                    element.bind('$destroy', function () {
                        if (instance && CKEDITOR.instances[instance.name]) {
                            CKEDITOR.instances[instance.name].destroy();
                        }
                    });
                    var setModelData = function (setPristine) {
                        var data = instance.getData();
                        if (data === '') {
                            data = null;
                        }
                        $timeout(function () { // for key up event
                            if (setPristine !== true || data !== ngModel.$viewValue) {
                                ngModel.$setViewValue(data);
                            }

                            if (setPristine === true && form) {
                                form.$setPristine();
                            }
                        }, 0);
                    }, onUpdateModelData = function (setPristine) {
                        if (!data.length) {
                            return;
                        }

                        var item = data.pop() || EMPTY_HTML;
                        isReady = false;
                        instance.setData(item, function () {
                            setModelData(setPristine);
                            isReady = true;
                        });
                    };

                    //instance.on('pasteState',   setModelData);
                    instance.on('change', setModelData);
                    instance.on('blur', setModelData);
                    //instance.on('key',          setModelData); // for source view

                    instance.on('instanceReady', function () {
                        scope.$broadcast('ckeditor.ready');
                        scope.$apply(function () {
                            onUpdateModelData(true);
                        });

                        instance.document.on('keyup', setModelData);
                    });
                    instance.on('customConfigLoaded', function () {
                        configLoaderDef.resolve();
                    });

                    ngModel.$render = function () {
                        data.push(ngModel.$viewValue);
                        if (isReady) {
                            onUpdateModelData();
                        }
                    };
                };

                if (CKEDITOR.status === 'loaded') {
                    loaded = true;
                }
                if (loaded) {
                    onLoad();
                } else {
                    $defer.promise.then(onLoad);
                }
            }
        };
    }]);

    return app;
}));<commit_msg>Call instance.resetUndo(); on load so undo doesn't clear everythng<commit_after>'use strict';

(function (angular, factory) {
    if (typeof define === 'function' && define.amd) {
        define(['angular', 'ckeditor'], function (angular) {
            return factory(angular);
        });
    } else {
        return factory(angular);
    }
}(angular || null, function (angular) {
    var app = angular.module('ngCkeditor', []);
    var $defer, loaded = false;

    app.run(['$q', '$timeout', function ($q, $timeout) {
        $defer = $q.defer();

        if (angular.isUndefined(CKEDITOR)) {
            throw new Error('CKEDITOR not found');
        }
        CKEDITOR.disableAutoInline = true;
        function checkLoaded() {
            if (CKEDITOR.status === 'loaded') {
                loaded = true;
                $defer.resolve();
            } else {
                checkLoaded();
            }
        }

        CKEDITOR.on('loaded', checkLoaded);
        $timeout(checkLoaded, 100);
    }]);

    app.directive('ckeditor', ['$timeout', '$q', function ($timeout, $q) {

        return {
            restrict: 'AC',
            require: ['ngModel', '^?form'],
            scope: false,
            link: function (scope, element, attrs, ctrls) {
                var ngModel = ctrls[0];
                var form = ctrls[1] || null;
                var EMPTY_HTML = '

',
                    isTextarea = element[0].tagName.toLowerCase() === 'textarea',
                    data = [],
                    isReady = false;

                if (!isTextarea) {
                    element.attr('contenteditable', true);
                }

                var onLoad = function () {
                    var options = {
                        toolbar: 'full',
                        toolbar_full: [ //jshint ignore:line
                            {
                                name: 'basicstyles',
                                items: ['Bold', 'Italic', 'Strike', 'Underline']
                            },
                            {name: 'paragraph', items: ['BulletedList', 'NumberedList', 'Blockquote']},
                            {name: 'editing', items: ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock']},
                            {name: 'links', items: ['Link', 'Unlink', 'Anchor']},
                            {name: 'tools', items: ['SpellChecker', 'Maximize']},
                            '/',
                            {
                                name: 'styles',
                                items: ['Format', 'FontSize', 'TextColor', 'PasteText', 'PasteFromWord', 'RemoveFormat']
                            },
                            {name: 'insert', items: ['Image', 'Table', 'SpecialChar']},
                            {name: 'forms', items: ['Outdent', 'Indent']},
                            {name: 'clipboard', items: ['Undo', 'Redo']},
                            {name: 'document', items: ['PageBreak', 'Source']}
                        ],
                        disableNativeSpellChecker: false,
                        uiColor: '#FAFAFA',
                        height: '400px',
                        width: '100%'
                    };
                    options = angular.extend(options, scope[attrs.ckeditor]);

                    var instance = (isTextarea) ? CKEDITOR.replace(element[0], options) : CKEDITOR.inline(element[0], options),
                        configLoaderDef = $q.defer();

                    element.bind('$destroy', function () {
                        if (instance && CKEDITOR.instances[instance.name]) {
                            CKEDITOR.instances[instance.name].destroy();
                        }
                    });
                    var setModelData = function (setPristine) {
                        var data = instance.getData();
                        if (data === '') {
                            data = null;
                        }
                        $timeout(function () { // for key up event
                            if (setPristine !== true || data !== ngModel.$viewValue) {
                                ngModel.$setViewValue(data);
                            }

                            if (setPristine === true) {
                                instance.resetUndo();
                            }

                            if (setPristine === true && form) {
                                form.$setPristine();
                            }
                        }, 0);
                    }, onUpdateModelData = function (setPristine) {
                        if (!data.length) {
                            return;
                        }

                        var item = data.pop() || EMPTY_HTML;
                        isReady = false;
                        instance.setData(item, function () {
                            setModelData(setPristine);
                            isReady = true;
                        });
                    };

                    //instance.on('pasteState',   setModelData);
                    instance.on('change', setModelData);
                    instance.on('blur', setModelData);
                    //instance.on('key',          setModelData); // for source view

                    instance.on('instanceReady', function () {
                        scope.$broadcast('ckeditor.ready');
                        scope.$apply(function () {
                            onUpdateModelData(true);
                        });

                        instance.document.on('keyup', setModelData);
                    });
                    instance.on('customConfigLoaded', function () {
                        configLoaderDef.resolve();
                    });

                    ngModel.$render = function () {
                        data.push(ngModel.$viewValue);
                        if (isReady) {
                            onUpdateModelData();
                        }
                    };
                };

                if (CKEDITOR.status === 'loaded') {
                    loaded = true;
                }
                if (loaded) {
                    onLoad();
                } else {
                    $defer.promise.then(onLoad);
                }
            }
        };
    }]);

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


<commit_before>const Canvas = require('canvas');
const w = 300; const h = 100;
const canvas = new Canvas(w, h);
const ctx = canvas.getContext('2d');

const botUtil = require('../util/botUtil');
const CommandHandler = require('../util/msgUtil');

const config = require('../config');

/**
 * Primary message listener
 * @param  {IMessage} msg Message object to be used
 * @param  {Discordie} client Bot client object
 */
function respond (msg, client) {
	const msgText = msg.content;
	const sender = msg.member || msg.author; // IUser as a substitute for DMs
	const msgChannel = msg.channel;
	const msgGuild = msg.guild;

	const botUser = msg.isPrivate ? client.User : client.User.memberOf(msgGuild);

	const sendMessage = (s, e) => msgChannel.sendMessage(s, false, e);
	const uploadFile = (s, n) => msgChannel.uploadFile(s, n || "drawing.png");

	const command = msgText.slice(config.prefix.length);
	const handler = new CommandHandler(command);

	if (!msgText.startsWith(config.prefix)) return;

	const addCommand = (c, f) => handler.addCommand(c, f);
	const addCommandSentence = (c, f) => handler.addCommandSentence(c, f);
	const addCommandArgs = (c, f) => handler.addCommandArgs(c, f);

	const senderIsOwner = botUtil.senderIsOwner(msg);

	addCommandSentence('evalC', a => {
		if (!senderIsOwner || a === 'e.message.content' || a === 'msgText') return;
		let result;
		return new Promise(resolve => {
			result = eval(a);
			resolve('Success');
		}).catch(e => {
			// sendMessage('\u{1F52B}'); // Peestol
			console.log(e);
			sendMessage('It didn\'t work.');
		}).then(v => {
			if (v === 'Success') {
				if (typeof result === 'string' || typeof result === 'number' || typeof result === 'boolean') sendMessage(result);
				else if (Array.isArray(result)) sendMessage(result.join(', '));
				// else sendMessage('\u{1F44C}'); // Ok hand sign
			}
		});
	});

	addCommand('testDraw', () => {
		ctx.fillStyle = '#FFB2C5';
		ctx.fillRect(0, 0, w, h);
		ctx.fillStyle = 'white';
		ctx.font = '48px serif';
		ctx.fillText('Hello, ' + (sender.nick || sender.username), 10, 50);
		const imgBuffer = canvas.toBuffer();
		uploadFile(imgBuffer);
	});
}

exports.respond = respond;
<commit_msg>add draw command method<commit_after>const Canvas = require('canvas');

const botUtil = require('../util/botUtil');
const CommandHandler = require('../util/msgUtil');

const config = require('../config');

/**
 * Primary message listener
 * @param  {IMessage} msg Message object to be used
 * @param  {Discordie} client Bot client object
 */
function respond (msg, client) {
	const msgText = msg.content;
	const sender = msg.member || msg.author; // IUser as a substitute for DMs
	const msgChannel = msg.channel;
	const msgGuild = msg.guild;

	const botUser = msg.isPrivate ? client.User : client.User.memberOf(msgGuild);

	const sendMessage = (s, e) => msgChannel.sendMessage(s, false, e);
	const uploadFile = (s, n) => msgChannel.uploadFile(s, n || "drawing.png");

	const command = msgText.slice(config.prefix.length);
	const handler = new CommandHandler(command);

	if (!msgText.startsWith(config.prefix)) return;

	const addCommand = (c, f) => handler.addCommand(c, f);
	const addDrawCommand = (c, f, w, h) => addCommand(c, () => {
		const canvas = new Canvas(w || 640, h || 480);
		const ctx = canvas.getContext('2d');
		f(ctx, canvas, w, h);
		const imgBuffer = canvas.toBuffer();
		uploadFile(imgBuffer);
	});
	const addCommandSentence = (c, f) => handler.addCommandSentence(c, f);
	const addCommandArgs = (c, f) => handler.addCommandArgs(c, f);

	const senderIsOwner = botUtil.senderIsOwner(msg);

	addCommandSentence('evalC', a => {
		if (!senderIsOwner || a === 'e.message.content' || a === 'msgText') return;
		let result;
		return new Promise(resolve => {
			result = eval(a);
			resolve('Success');
		}).catch(e => {
			// sendMessage('\u{1F52B}'); // Peestol
			console.log(e);
			sendMessage('It didn\'t work.');
		}).then(v => {
			if (v === 'Success') {
				if (typeof result === 'string' || typeof result === 'number' || typeof result === 'boolean') sendMessage(result);
				else if (Array.isArray(result)) sendMessage(result.join(', '));
				// else sendMessage('\u{1F44C}'); // Ok hand sign
			}
		});
	});

	addDrawCommand('testDraw', (ctx, canvas, w, h) => {
		ctx.fillStyle = '#FFB2C5';
		ctx.fillRect(0, 0, w, h);
		ctx.fillStyle = 'white';
		ctx.font = '48px serif';
		ctx.fillText('Hello, ' + (sender.nick || sender.username), 10, 50);
	}, 300, 100);
}

exports.respond = respond;
<|endoftext|>


<commit_before>module.exports = {
  SERVER_PORT: 8000,
  IS_DEBUG: (process.env.NODE_ENV === 'development'),
  USE_HTTPS: (process.env.USE_HTTPS == 1),
  ENABLE_PONTOON: (process.env.ENABLE_PONTOON === '1'),
  AVAILABLE_LOCALES: (process.env.ENABLE_DEV_LOCALES === '1') ?
    // All locales on Pontoon for local & dev
    'en-US,zh-CN,de,ja,fy-NL,fa,zh-TW,ast,uk,fr,sv-SE,bn-BD,pt-BR,tr,kab,es-ES,sl,cs,ru,bs,es-CL' :
    // Enabled locales for stage & production - update as they reach 100%
    'en-US,zh-CN,de',

  // TODO: Move addon build to a better path
  ADDON_SRC_PATH: './addon/',

  SRC_PATH: './frontend/src/',
  DEST_PATH: './frontend/build/',
  DIST_PATH: './dist/',
  DJANGO_OLD_STATIC:  './testpilot/frontend/static/',
  CONTENT_SRC_PATH: './content-src/',

  PRODUCTION_EXPERIMENTS_URL: 'https://testpilot.firefox.com/api/experiments',
  IMAGE_NEW_BASE_PATH: 'frontend/src/images/experiments/',
  IMAGE_NEW_BASE_URL: '/static/images/experiments/',

  'sass-lint': true,
  'js-lint': true
};

// Pull in local debug-config.json overrides
const tryRequire = require('try-require');
Object.assign(module.exports, tryRequire('../debug-config.json') || {});
<commit_msg>Update list of locales enabled on DEV and PROD<commit_after>module.exports = {
  SERVER_PORT: 8000,
  IS_DEBUG: (process.env.NODE_ENV === 'development'),
  USE_HTTPS: (process.env.USE_HTTPS == 1),
  ENABLE_PONTOON: (process.env.ENABLE_PONTOON === '1'),
  AVAILABLE_LOCALES: (process.env.ENABLE_DEV_LOCALES === '1') ?
    // All locales on Pontoon for local & dev
    'en-US,ast,bn-BD,cs,de,es-ES,fa,fr,fy-NL,hu,it,ja,kab,pt-BR,ru,sk,sl,sv-SE,tr,uk,zh-CN,zh-TW' :
    // Enabled locales for stage & production - update as they reach 100%
    'en-US,de,it,zh-CN',

  // TODO: Move addon build to a better path
  ADDON_SRC_PATH: './addon/',

  SRC_PATH: './frontend/src/',
  DEST_PATH: './frontend/build/',
  DIST_PATH: './dist/',
  DJANGO_OLD_STATIC:  './testpilot/frontend/static/',
  CONTENT_SRC_PATH: './content-src/',

  PRODUCTION_EXPERIMENTS_URL: 'https://testpilot.firefox.com/api/experiments',
  IMAGE_NEW_BASE_PATH: 'frontend/src/images/experiments/',
  IMAGE_NEW_BASE_URL: '/static/images/experiments/',

  'sass-lint': true,
  'js-lint': true
};

// Pull in local debug-config.json overrides
const tryRequire = require('try-require');
Object.assign(module.exports, tryRequire('../debug-config.json') || {});
<|endoftext|>