<commit_before>// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
const vscode = require('vscode');
const shell = require('node-powershell');

// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
function activate(context) {
    // Use the console to output diagnostic information (console.log) and errors (console.error)
    // This line of code will only be executed once when your extension is activated
    console.log('Congratulations, your extension "GlassIt VSC" is now active!');

    function setAlpha(alpha) {
        if (alpha < 1) alpha = 1;
        if (alpha > 255) alpha = 255;

        const path = context.asAbsolutePath('./SetTransparency.cs');
        const ps = new shell();
        ps.addCommand(`Add-Type  -Path '${path}'`)
        ps.addCommand(`[CS]::SetTransParency(${process.pid}, ${alpha})`);
        ps.invoke().then(res => {
            console.log(res);
            console.log(`GlassIt: set alpha ${alpha}`);
            config.update('alpha', alpha, true);
        }).catch(err => {
            console.error(err);
            vscode.window.showErrorMessage(`GlassIt Error: ${err}`);
        }).then(() => {
            ps.dispose();
        });
    }

    // The command has been defined in the package.json file
    // Now provide the implementation of the command with  registerCommand
    // The commandId parameter must match the command field in package.json
    context.subscriptions.push(vscode.commands.registerCommand('glassit.increase', () => {
        // The code you place here will be executed every time your command is executed
        const config = vscode.workspace.getConfiguration('glassit');
        const alpha = config.get('alpha') - config.get('step');
        setAlpha(alpha);
    }));

    context.subscriptions.push(vscode.commands.registerCommand('glassit.decrease', () => {
        // The code you place here will be executed every time your command is executed
        const config = vscode.workspace.getConfiguration('glassit');
        const alpha = config.get('alpha') + config.get('step');
        setAlpha(alpha);
    }));

    const config = vscode.workspace.getConfiguration('glassit');
    const alpha = config.get('alpha');
    setAlpha(alpha);
}
exports.activate = activate;

// this method is called when your extension is deactivated
function deactivate() {
}
exports.deactivate = deactivate;
<commit_msg>psプロセスを使いまわす<commit_after>// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
const vscode = require('vscode');
const shell = require('node-powershell');

// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
function activate(context) {
    // Use the console to output diagnostic information (console.log) and errors (console.error)
    // This line of code will only be executed once when your extension is activated
    console.log('Congratulations, your extension "GlassIt VSC" is now active!');

    const path = context.asAbsolutePath('./SetTransparency.cs');
    const ps = new shell();
    context.subscriptions.push(ps);
    ps.addCommand(`Add-Type  -Path '${path}'`);

    function setAlpha(alpha) {
        if (alpha < 1) alpha = 1;
        if (alpha > 255) alpha = 255;

        ps.addCommand(`[CS]::SetTransParency(${process.pid}, ${alpha})`);
        ps.invoke().then(res => {
            console.log(res);
            console.log(`GlassIt: set alpha ${alpha}`);
            config.update('alpha', alpha, true);
        }).catch(err => {
            console.error(err);
            vscode.window.showErrorMessage(`GlassIt Error: ${err}`);
        });
    }

    // The command has been defined in the package.json file
    // Now provide the implementation of the command with  registerCommand
    // The commandId parameter must match the command field in package.json
    context.subscriptions.push(vscode.commands.registerCommand('glassit.increase', () => {
        // The code you place here will be executed every time your command is executed
        const config = vscode.workspace.getConfiguration('glassit');
        const alpha = config.get('alpha') - config.get('step');
        setAlpha(alpha);
    }));

    context.subscriptions.push(vscode.commands.registerCommand('glassit.decrease', () => {
        // The code you place here will be executed every time your command is executed
        const config = vscode.workspace.getConfiguration('glassit');
        const alpha = config.get('alpha') + config.get('step');
        setAlpha(alpha);
    }));

    const config = vscode.workspace.getConfiguration('glassit');
    const alpha = config.get('alpha');
    setAlpha(alpha);
}
exports.activate = activate;

// this method is called when your extension is deactivated
function deactivate() {
}
exports.deactivate = deactivate;
<|endoftext|>


<commit_before>'use strict';

var
  _ = require('lodash'),
  path = require('path'),
  Promise = require('bluebird'),
  HTTP_STATUSES = require('http-statuses'),

  mmm = require('mmmagic'),
  Magic = mmm.Magic,

  RestifizerScope = require('./restifizer-scope'),
  utils = require('./utils');

var
  extend = utils.extend,
  requireOptions = utils.requireOptions,
  CommonController = utils.CommonController,
  setResError = utils.setResError,
  setResOk = utils.setResOk;

function FileDataService(options) {

  _.extend(this, options);

  var requiredOptions = ['dataSource', 'path', 'fileField'];
  requireOptions(this, requiredOptions);

  this.provider = this.provider || 'gridfs';
  this._provider = require('../storages/' + this.provider);

  if (_.isFunction(this.dataSource.initialize)) {
    this.dataSource.initialize.call(this.dataSource, this);
  }
  this.initialize.apply(this, arguments);
  this._provider.initialize.call(this._provider, this);
}

_.extend(FileDataService.prototype, {

  initialize: function() {
    Promise.promisifyAll(this);
  },

  selectOne: function (req, res, next) {
    req.restifizer = new RestifizerScope(RestifizerScope.ACTIONS.SELECT_ONE);

    Promise
      .bind(this)
      .then(function () {
        if (this.preAsync) {
          return this.preAsync(req, res);
        }
      })
      .then(function () {
        return this.locateModelAsync(req);
      })
      .spread(function (model, fileField) {
        if (!model) {
          throw HTTP_STATUSES.NOT_FOUND.createError();
        } else {
          return [model, fileField];
        }
      })
      .spread(function (model, fileField) {
        return this.getFileFieldAsync(fileField, model);
      })
      .then(function (fileData) {
        if (this.postAsync) {
          return this.postAsync(fileData, req, res);
        } else {
          return fileData;
        }
      })
      .then(function (fileData) {
        if (fileData.stream) {
          var _this = this;
          res.header('Content-Type', fileData.contentType);
          res.header('Content-Length', fileData.contentLength);
          fileData.stream.on('error', function (error) {
            if (_this.log) {
              _this.log.error('Stream error', error);
            } else {
              console.log('Stream error', error);
            }
          });
          fileData.stream.pipe(res);
        } else {
          throw HTTP_STATUSES.NOT_FOUND.createError();
        }
      })
      .catch(function (err) {
          setResError(err, res, this.log);
          next();
        }
      );
  },

  replace: function (req, res, next) {
    req.restifizer = new RestifizerScope(RestifizerScope.ACTIONS.REPLACE);

    Promise
      .bind(this)
      .then(function () {
        if (this.preAsync) {
          return this.preAsync(req, res);
        }
      })
      .then(function () {
        return this.locateModelAsync(req);
      })
      .spread(function (model, fileField) {
        if (!model) {
          throw HTTP_STATUSES.NOT_FOUND.createError();
        } else {
          return this.setFileFieldAsync(fileField, model, req);
        }
      })
      .then(function(model) {
        return this.dataSource.save(model);
      })
      .then(function (model) {
        if (this.postAsync) {
          return this.postAsync(model, req, res);
        } else {
          return model;
        }
      })
      .then(function () {
        setResOk(res);
        next();
      })
      .catch(function (err) {
        setResError(err, res, this.log);
        next();
      });
  },

  delete: function (req, res, next) {
    req.restifizer = new RestifizerScope(RestifizerScope.ACTIONS.DELETE);

    Promise
      .bind(this)
      .then(function () {
        if (this.preAsync) {
          return this.preAsync(req, res);
        }
      })
      .then(function () {
        return this.locateModelAsync(req);
      })
      .spread(function (model, fileField) {
        if (!model) {
          throw HTTP_STATUSES.NOT_FOUND.createError();
        } else {
          return this.cleanFileField(fileField, model);
        }
      })
      .then(function(model) {
        return this.dataSource.save(model);
      })
      .then(function (model) {
        if (this.postAsync) {
          return this.postAsync(model, req, res);
        } else {
          return model;
        }
      })
      .then(function () {
        setResOk(res, HTTP_STATUSES.NO_CONTENT.code);
        next();
      })
      .catch(function (err) {
        setResError(err, res, this.log);
        next();
      });
  },

  /**
   * Get metadata of file with stream data. {contentType, contentLength, stream}
   * @param fieldName
   * @param model
   * @returns {*|Promise.<T>}
   */
  getFileFieldAsync: function (fieldName, model) {
    return Promise
      .bind(this)
      .then(function () {
        var fileMeta = this.dataSource.getFieldValue(model, fieldName);
        if (fileMeta) {
          return Promise
            .bind(this)
            .then(function () {
              return this._provider.getStreamAsync(fileMeta);
            })
            .then(function (fileData) {
              return fileData;
            });
        } else {
          throw HTTP_STATUSES.NOT_FOUND.createError();
        }
      });
  },

  setFileFieldAsync: function (fieldName, model, req) {
    return Promise
      .bind(this)
      .then(function() {
        var file = req.files && req.files[fieldName];
        if (file) {
          return Promise
            .bind(this)
            .then(function () {
              var magic = new Magic(mmm.MAGIC_MIME_TYPE);
              Promise.promisifyAll(magic);
              return magic.detectFileAsync(file.path);
            })
            .then(function (mimeType) {
              var options = {mimeType: mimeType, path: file.path};
              if (this.converterAsync) {
                return this.converterAsync(options)
              } else {
                return options;
              }
            })
            .then(function (result) {
              var options = {content_type: result.mimeType};
              var fileMeta = this.dataSource.getFieldValue(model, fieldName);
              if (fileMeta) {
                return this._provider.replaceFileAsync(fileMeta, result.path, options);
              } else {
                return this._provider.putFileAsync(result.path, options);
              }
            })
            .then(function (result) {
              this.dataSource.setFieldValue(model, fieldName, result);
              return model;
            })
            ;
        } else {
          return model;
        }
      });
  },

  cleanFileField: function (fieldName, model, callback) {
    var fileMeta = this.dataSource.getFieldValue(model, fieldName);
    if (fileMeta) {
      Promise
        .bind(this)
        .then(function () {
          return this._provider.deleteFileAsync(fileMeta);
        })
        .then(function () {
          this.dataSource.setFieldValue(model, fieldName, undefined);
          callback(null, model);
        })
        .catch(function (err) {
          callback(err);
        })
      ;
    } else {
      callback(HTTP_STATUSES.NOT_FOUND.createError());
    }
  },

  locateModelAsync: function (req) {
    var fileField;
    if (this.fileField.type === 'function') {
      fileField = this.fileField();
    } else {
      fileField = this.fileField;
    }
    // fill params
    _.each(_.keys(req.params), function(key) {
      fileField = fileField.replace(':' + key, req.params[key]);
    });
    return Promise
      .bind(this)
      .then(function () {
        return this.buildConditionsAsync(req);
      })
      .then(function (conditions) {
        return this.dataSource.findOne({filter: conditions, fields: [fileField]});
      })
      .then(function (model) {
        return [model, fileField];
      });
  },

  buildConditionsAsync: function (req) {
    return _.pick(req.params, _.keys(req.params));
  }
});

FileDataService.extend = extend;

var FileFieldController = FileDataService.extend(_.extend(CommonController, {

  supportedMethod: 'put',
  supportedMethods: null,

  constructor: function(options) {

    FileDataService.apply(this, arguments);

    _.extend(this, options);

    var requiredOptions = ['path', 'fileField'];
    requireOptions(this, requiredOptions);

    this.actions = this.actions || [];

    // init

    this.actions.default = this.actions.default || {};

    this.defaultOptions = _.assign(
      {
        enabled: true,
        method: 'get'
      },
      this.actions.default
    );

    this.restActions = {};

    this.actions.selectOne = _.defaults(this.actions.selectOne || {}, this.actions.default);
    this.restActions.selectOne = _.assign(
      {
        method: 'get',
        handler: 'selectOne',
        path: ''
      },
      this.actions.selectOne
    );

    this.actions.replace = _.defaults(this.actions.replace || {}, this.actions.default);
    this.restActions.replace = _.assign(
      {
        method: this.supportedMethods || [this.supportedMethod],
        handler: 'replace',
        path: ''
      },
      this.actions.replace
    );

    this.actions.delete = _.defaults(this.actions.delete || {}, this.actions.default);
    this.restActions.delete = _.assign(
      {
        method: 'delete',
        handler: 'delete',
        path: ''
      },
      this.actions.delete
    );

    this.actions = _.omit(this.actions, 'default', 'selectOne', 'replace', 'delete');
    _.forEach(this.actions, function (action, actionKey) {
      if (typeof(action) !== 'object') {
        // interpret it as bool
        action = {
          enabled: !!action
        };
        this.actions[actionKey] = action;
      }
      _.defaults(action, this.defaultOptions);
      action.path = action.path || actionKey;
      action.handler = action.handler || actionKey;
      action.name = actionKey;
    }, this);

  },

  initialize: function() {
    FileDataService.prototype.initialize.apply(this, arguments);
  },

  bind: function (app) {
    var _this = this;
    if (typeof(this.path) === 'string') {
      this.path = [this.path];
    }
    _.forEach(this.path, _.bind(function (path) {
      _.forEach(_.union(_.values(this.actions), _.values(this.restActions)), function (action) {
        try {
          if (action.enabled) {
            if (typeof(action.method) === 'string') {
              action.method = [action.method];
            }
            _.forEach(action.method, _.bind(function (method) {
              app[method](path + '/' + action.path,
                this.getAuth(action),
                function (req, res, next) {
                  _this[action.handler].apply(_this, arguments);
                },
                this.resultSender
              );
            }, this));
          }
        } catch (err) {
          if (this.log) {
            this.log.error('Set route for action: ' + action.name + ' and path ' + path + '/' + action.path);
            this.log.error('Error', err);
          } else {
            console.log('Set route for action: ' + action.name + ' and path ' + path + '/' + action.path);
            console.log('Error', err);
          }

          throw err;
        }
      }, this);
    }, this));
  },
  resultSender: function(req, res) {
    res.send(res.restfulResult);
  }
}));

FileFieldController.extend = extend;
FileFieldController.ACTIONS = RestifizerScope.ACTIONS;

module.exports = FileFieldController;
<commit_msg>fix removing<commit_after>'use strict';

var
  _ = require('lodash'),
  path = require('path'),
  Promise = require('bluebird'),
  HTTP_STATUSES = require('http-statuses'),

  mmm = require('mmmagic'),
  Magic = mmm.Magic,

  RestifizerScope = require('./restifizer-scope'),
  utils = require('./utils');

var
  extend = utils.extend,
  requireOptions = utils.requireOptions,
  CommonController = utils.CommonController,
  setResError = utils.setResError,
  setResOk = utils.setResOk;

function FileDataService(options) {

  _.extend(this, options);

  var requiredOptions = ['dataSource', 'path', 'fileField'];
  requireOptions(this, requiredOptions);

  this.provider = this.provider || 'gridfs';
  this._provider = require('../storages/' + this.provider);

  if (_.isFunction(this.dataSource.initialize)) {
    this.dataSource.initialize.call(this.dataSource, this);
  }
  this.initialize.apply(this, arguments);
  this._provider.initialize.call(this._provider, this);
}

_.extend(FileDataService.prototype, {

  initialize: function() {
    Promise.promisifyAll(this);
  },

  selectOne: function (req, res, next) {
    req.restifizer = new RestifizerScope(RestifizerScope.ACTIONS.SELECT_ONE);

    Promise
      .bind(this)
      .then(function () {
        if (this.preAsync) {
          return this.preAsync(req, res);
        }
      })
      .then(function () {
        return this.locateModelAsync(req);
      })
      .spread(function (model, fileField) {
        if (!model) {
          throw HTTP_STATUSES.NOT_FOUND.createError();
        } else {
          return [model, fileField];
        }
      })
      .spread(function (model, fileField) {
        return this.getFileFieldAsync(fileField, model);
      })
      .then(function (fileData) {
        if (this.postAsync) {
          return this.postAsync(fileData, req, res);
        } else {
          return fileData;
        }
      })
      .then(function (fileData) {
        if (fileData.stream) {
          var _this = this;
          res.header('Content-Type', fileData.contentType);
          res.header('Content-Length', fileData.contentLength);
          fileData.stream.on('error', function (error) {
            if (_this.log) {
              _this.log.error('Stream error', error);
            } else {
              console.log('Stream error', error);
            }
          });
          fileData.stream.pipe(res);
        } else {
          throw HTTP_STATUSES.NOT_FOUND.createError();
        }
      })
      .catch(function (err) {
          setResError(err, res, this.log);
          next();
        }
      );
  },

  replace: function (req, res, next) {
    req.restifizer = new RestifizerScope(RestifizerScope.ACTIONS.REPLACE);

    Promise
      .bind(this)
      .then(function () {
        if (this.preAsync) {
          return this.preAsync(req, res);
        }
      })
      .then(function () {
        return this.locateModelAsync(req);
      })
      .spread(function (model, fileField) {
        if (!model) {
          throw HTTP_STATUSES.NOT_FOUND.createError();
        } else {
          return this.setFileFieldAsync(fileField, model, req);
        }
      })
      .then(function(model) {
        return this.dataSource.save(model);
      })
      .then(function (model) {
        if (this.postAsync) {
          return this.postAsync(model, req, res);
        } else {
          return model;
        }
      })
      .then(function () {
        setResOk(res);
        next();
      })
      .catch(function (err) {
        setResError(err, res, this.log);
        next();
      });
  },

  delete: function (req, res, next) {
    req.restifizer = new RestifizerScope(RestifizerScope.ACTIONS.DELETE);

    Promise
      .bind(this)
      .then(function () {
        if (this.preAsync) {
          return this.preAsync(req, res);
        }
      })
      .then(function () {
        return this.locateModelAsync(req);
      })
      .spread(function (model, fileField) {
        if (!model) {
          throw HTTP_STATUSES.NOT_FOUND.createError();
        } else {
          return this.cleanFileField(fileField, model);
        }
      })
      .then(function(model) {
        return this.dataSource.save(model);
      })
      .then(function (model) {
        if (this.postAsync) {
          return this.postAsync(model, req, res);
        } else {
          return model;
        }
      })
      .then(function () {
        setResOk(res, HTTP_STATUSES.NO_CONTENT.code);
        next();
      })
      .catch(function (err) {
        setResError(err, res, this.log);
        next();
      });
  },

  /**
   * Get metadata of file with stream data. {contentType, contentLength, stream}
   * @param fieldName
   * @param model
   * @returns {*|Promise.<T>}
   */
  getFileFieldAsync: function (fieldName, model) {
    return Promise
      .bind(this)
      .then(function () {
        var fileMeta = this.dataSource.getFieldValue(model, fieldName);
        if (fileMeta) {
          return Promise
            .bind(this)
            .then(function () {
              return this._provider.getStreamAsync(fileMeta);
            })
            .then(function (fileData) {
              return fileData;
            });
        } else {
          throw HTTP_STATUSES.NOT_FOUND.createError();
        }
      });
  },

  setFileFieldAsync: function (fieldName, model, req) {
    return Promise
      .bind(this)
      .then(function() {
        var file = req.files && req.files[fieldName];
        if (file) {
          return Promise
            .bind(this)
            .then(function () {
              var magic = new Magic(mmm.MAGIC_MIME_TYPE);
              Promise.promisifyAll(magic);
              return magic.detectFileAsync(file.path);
            })
            .then(function (mimeType) {
              var options = {mimeType: mimeType, path: file.path};
              if (this.converterAsync) {
                return this.converterAsync(options)
              } else {
                return options;
              }
            })
            .then(function (result) {
              var options = {content_type: result.mimeType};
              var fileMeta = this.dataSource.getFieldValue(model, fieldName);
              if (fileMeta) {
                return this._provider.replaceFileAsync(fileMeta, result.path, options);
              } else {
                return this._provider.putFileAsync(result.path, options);
              }
            })
            .then(function (result) {
              this.dataSource.setFieldValue(model, fieldName, result);
              return model;
            })
            ;
        } else {
          return model;
        }
      });
  },

  cleanFileField: function (fieldName, model) {
    var fileMeta = this.dataSource.getFieldValue(model, fieldName);
    if (fileMeta) {
      return Promise
        .bind(this)
        .then(function() {
          return this._provider.deleteFileAsync(fileMeta);
        })
        .then(function() {
          this.dataSource.setFieldValue(model, fieldName, undefined);
          return model;
        })
        ;
    } else {
      throw HTTP_STATUSES.NOT_FOUND.createError();
    }
  },

  locateModelAsync: function (req) {
    var fileField;
    if (this.fileField.type === 'function') {
      fileField = this.fileField();
    } else {
      fileField = this.fileField;
    }
    // fill params
    _.each(_.keys(req.params), function(key) {
      fileField = fileField.replace(':' + key, req.params[key]);
    });
    return Promise
      .bind(this)
      .then(function () {
        return this.buildConditionsAsync(req);
      })
      .then(function (conditions) {
        return this.dataSource.findOne({filter: conditions, fields: [fileField]});
      })
      .then(function (model) {
        return [model, fileField];
      });
  },

  buildConditionsAsync: function (req) {
    return _.pick(req.params, _.keys(req.params));
  }
});

FileDataService.extend = extend;

var FileFieldController = FileDataService.extend(_.extend(CommonController, {

  supportedMethod: 'put',
  supportedMethods: null,

  constructor: function(options) {

    FileDataService.apply(this, arguments);

    _.extend(this, options);

    var requiredOptions = ['path', 'fileField'];
    requireOptions(this, requiredOptions);

    this.actions = this.actions || [];

    // init

    this.actions.default = this.actions.default || {};

    this.defaultOptions = _.assign(
      {
        enabled: true,
        method: 'get'
      },
      this.actions.default
    );

    this.restActions = {};

    this.actions.selectOne = _.defaults(this.actions.selectOne || {}, this.actions.default);
    this.restActions.selectOne = _.assign(
      {
        method: 'get',
        handler: 'selectOne',
        path: ''
      },
      this.actions.selectOne
    );

    this.actions.replace = _.defaults(this.actions.replace || {}, this.actions.default);
    this.restActions.replace = _.assign(
      {
        method: this.supportedMethods || [this.supportedMethod],
        handler: 'replace',
        path: ''
      },
      this.actions.replace
    );

    this.actions.delete = _.defaults(this.actions.delete || {}, this.actions.default);
    this.restActions.delete = _.assign(
      {
        method: 'delete',
        handler: 'delete',
        path: ''
      },
      this.actions.delete
    );

    this.actions = _.omit(this.actions, 'default', 'selectOne', 'replace', 'delete');
    _.forEach(this.actions, function (action, actionKey) {
      if (typeof(action) !== 'object') {
        // interpret it as bool
        action = {
          enabled: !!action
        };
        this.actions[actionKey] = action;
      }
      _.defaults(action, this.defaultOptions);
      action.path = action.path || actionKey;
      action.handler = action.handler || actionKey;
      action.name = actionKey;
    }, this);

  },

  initialize: function() {
    FileDataService.prototype.initialize.apply(this, arguments);
  },

  bind: function (app) {
    var _this = this;
    if (typeof(this.path) === 'string') {
      this.path = [this.path];
    }
    _.forEach(this.path, _.bind(function (path) {
      _.forEach(_.union(_.values(this.actions), _.values(this.restActions)), function (action) {
        try {
          if (action.enabled) {
            if (typeof(action.method) === 'string') {
              action.method = [action.method];
            }
            _.forEach(action.method, _.bind(function (method) {
              app[method](path + '/' + action.path,
                this.getAuth(action),
                function (req, res, next) {
                  _this[action.handler].apply(_this, arguments);
                },
                this.resultSender
              );
            }, this));
          }
        } catch (err) {
          if (this.log) {
            this.log.error('Set route for action: ' + action.name + ' and path ' + path + '/' + action.path);
            this.log.error('Error', err);
          } else {
            console.log('Set route for action: ' + action.name + ' and path ' + path + '/' + action.path);
            console.log('Error', err);
          }

          throw err;
        }
      }, this);
    }, this));
  },
  resultSender: function(req, res) {
    res.send(res.restfulResult);
  }
}));

FileFieldController.extend = extend;
FileFieldController.ACTIONS = RestifizerScope.ACTIONS;

module.exports = FileFieldController;
<|endoftext|>


<commit_before>// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
var vscode = require('vscode');
const SvnSpawn = require('svn-spawn');
const path = require('path');

const createStatusBar = () => {
  const statusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
  statusBarItem.command = 'vscode-svn.showOutputChannel';

  return statusBarItem;
};

const createClient = (rootPath) => {
  return new SvnSpawn({
    cwd: rootPath,
    noAuthCache: true,
  });
};

const createChannel = () => {
  return vscode.window.createOutputChannel('vscode-svn');
};

const svnStatus = (client) => {
  return new Promise((resolve, reject) => {
    client.getStatus((err, data) => err ? reject(err) : resolve(data));
  });
};

const updateStatusBar = (data, statusBar) => {
  return new Promise((resolve) => {
    statusBar.text = `${data.length} changes`;
    statusBar.show();

    resolve(data);
  });
};

const checkAllFiles = (client) => {
  return new Promise((resolve, reject) => {
    svnStatus(client)
    .then((data) => resolve(data))
    .catch((err) => reject(err));
  });
};

const updateOutputChannel = (data, outputChannel) => {
  outputChannel.clear();

  data.forEach((item) => {
    const document = vscode.Uri.file(path.join(vscode.workspace.rootPath, item.$.path));
    outputChannel.appendLine(document);
  });
};

function createResourceUri(relativePath) {
	const absolutePath = path.join(vscode.workspace.rootPath, relativePath);
	return vscode.Uri.file(absolutePath);
  }

const updateResourceGroup = (data, type) => {
	var matches = [];

	data.forEach(item => {
	  if (item['wc-status'].$.item == type) {
		matches.push({resourceUri: createResourceUri(item.$.path)});
	  }
	});

	return matches;
}

// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
function activate(context) {

    // Use the console to output diagnostic information (console.log) and errors (console.error)
    // This line of code will only be executed once when your extension is activated
    console.log('Congratulations, your extension "svn-scm" is now active!');

    // The command has been defined in the package.json file
    // Now provide the implementation of the command with  registerCommand
    // The commandId parameter must match the command field in package.json
    var disposable = vscode.commands.registerCommand('extension.sayHello', function () {
        // The code you place here will be executed every time your command is executed

        // Display a message box to the user
        vscode.window.showInformationMessage('Hello World!');
    });

	const rootPath = vscode.workspace.rootPath;
	const outputChannel = createChannel();
	vscode.commands.registerCommand('vscode-svn.showOutputChannel', () => outputChannel.show());

	const statusBar = createStatusBar();
	const client = createClient(rootPath);
	const watcher = vscode.workspace.createFileSystemWatcher(`${rootPath}/**/*`);

	const sourceControl = vscode.scm.createSourceControl('svn', 'svn');

	const modified = sourceControl.createResourceGroup('modified', 'Modified');
	const removed = sourceControl.createResourceGroup('removed', 'Removed');
	const notTracked = sourceControl.createResourceGroup('unversioned', 'Not Tracked');

	const QuickDiffProvider = {
		provideOriginalResource(uri) {
			if (uri.scheme !== 'file') {
				return;
			}

			// As a mitigation for extensions like ESLint showing warnings and errors
			// for hg URIs, let's change the file extension of these uris to .hg.
			return new Uri().with({ scheme: 'svn-original', query: uri.path, path: uri.path});
		}
	}

	sourceControl.quickDiffProvider = QuickDiffProvider;

	modified.hideWhenEmpty = true;
	removed.hideWhenEmpty = true;
	notTracked.hideWhenEmpty = true;

	const main = () => {
		console.log('ran main')
	  return checkAllFiles(client, statusBar)
		.then((data) => {
			modified.resourceStates = updateResourceGroup(data, 'modified');
			removed.resourceStates = updateResourceGroup(data, 'removed');
			notTracked.resourceStates = updateResourceGroup(data, 'unversioned');
		})
	  .catch((err) => vscode.window.showErrorMessage(err));
	};

	watcher.onDidChange(main);
	watcher.onDidCreate(main);
	watcher.onDidDelete(main);

  	main();

    context.subscriptions.push(disposable);
}
exports.activate = activate;

// this method is called when your extension is deactivated
function deactivate() {
}
exports.deactivate = deactivate;<commit_msg>fixed SVN not loading as a SCM<commit_after>// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
var vscode = require('vscode');
const SvnSpawn = require('svn-spawn');
const path = require('path');

const createStatusBar = () => {
  const statusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
  statusBarItem.command = 'vscode-svn.showOutputChannel';

  return statusBarItem;
};

const createClient = (rootPath) => {
  return new SvnSpawn({
    cwd: rootPath,
    noAuthCache: true,
  });
};

const createChannel = () => {
  return vscode.window.createOutputChannel('vscode-svn');
};

const svnStatus = (client) => {
  return new Promise((resolve, reject) => {
    client.getStatus((err, data) => err ? reject(err) : resolve(data));
  });
};

const updateStatusBar = (data, statusBar) => {
  return new Promise((resolve) => {
    statusBar.text = `${data.length} changes`;
    statusBar.show();

    resolve(data);
  });
};

const checkAllFiles = (client) => {
  return new Promise((resolve, reject) => {
    svnStatus(client)
    .then((data) => resolve(data))
    .catch((err) => reject(err));
  });
};

const updateOutputChannel = (data, outputChannel) => {
  outputChannel.clear();

  data.forEach((item) => {
    const document = vscode.Uri.file(path.join(vscode.workspace.rootPath, item.$.path));
    outputChannel.appendLine(document);
  });
};

function createResourceUri(relativePath) {
	const absolutePath = path.join(vscode.workspace.rootPath, relativePath);
	return vscode.Uri.file(absolutePath);
  }

const updateResourceGroup = (data, type) => {
	var matches = [];

	data.forEach(item => {
	  if (item['wc-status'].$.item == type) {
		matches.push({resourceUri: createResourceUri(item.$.path)});
	  }
	});

	return matches;
}

// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
function activate(context) {

    // Use the console to output diagnostic information (console.log) and errors (console.error)
    // This line of code will only be executed once when your extension is activated
    console.log('Congratulations, your extension "svn-scm" is now active!');

    // The command has been defined in the package.json file
    // Now provide the implementation of the command with  registerCommand
    // The commandId parameter must match the command field in package.json
    var disposable = vscode.commands.registerCommand('extension.sayHello', function () {
        // The code you place here will be executed every time your command is executed

        // Display a message box to the user
        vscode.window.showInformationMessage('Hello World!');
    });

	const rootPath = vscode.workspace.rootPath;
	const outputChannel = createChannel();
	vscode.commands.registerCommand('vscode-svn.showOutputChannel', () => outputChannel.show());

	const statusBar = createStatusBar();
	const client = createClient(rootPath);
	const watcher = vscode.workspace.createFileSystemWatcher(`${rootPath}/**/*`);

	const sourceControl = vscode.scm.createSourceControl('svn', 'svn');

	const modified = sourceControl.createResourceGroup('modified', 'Modified');
	const removed = sourceControl.createResourceGroup('removed', 'Removed');
	const notTracked = sourceControl.createResourceGroup('unversioned', 'Not Tracked');

	const QuickDiffProvider = {
		provideOriginalResource(uri) {
			if (uri.scheme !== 'file') {
				return;
			}

			// As a mitigation for extensions like ESLint showing warnings and errors
			// for hg URIs, let's change the file extension of these uris to .hg.
			return new Uri().with({ scheme: 'svn-original', query: uri.path, path: uri.path});
		}
	}

	sourceControl.quickDiffProvider = QuickDiffProvider;

	modified.hideWhenEmpty = true;
	removed.hideWhenEmpty = true;
	notTracked.hideWhenEmpty = true;

	const main = () => {
	  return checkAllFiles(client, statusBar)
		.then((data) => {
			modified.resourceStates = updateResourceGroup(data, 'modified');
			removed.resourceStates = updateResourceGroup(data, 'removed');
			notTracked.resourceStates = updateResourceGroup(data, 'unversioned');
		})
	  .catch((err) => vscode.window.showErrorMessage(err));
	};

	watcher.onDidChange(main);
	watcher.onDidCreate(main);
	watcher.onDidDelete(main);

  	main();

    context.subscriptions.push(disposable);
}
exports.activate = activate;

// this method is called when your extension is deactivated
function deactivate() {
}
exports.deactivate = deactivate;<|endoftext|>


<commit_before>'use strict';

angular.module('myApp.view1', ['ngRoute', 'ngFileUpload'])
  .config(['$routeProvider', function($routeProvider) {
    $routeProvider.when('/view1', {
      templateUrl: 'view1/view1.html',
      controller: 'View1Ctrl'
    })
    .when('/view2', {
      templateUrl: 'view2/view2.html',
      controller: 'View2Ctrl'
    });
  }])

.controller('View1Ctrl', function($scope, fileReader, pdfReader, lemma, cvTokenizer, jobDescTokenizer, jobDescriptionParser, storageAccess) {
    $scope.page1content = "No file opened.";
    $scope.fileNames = "";
    $scope.jobDescript = null;

    // TODO: Remove testing code
    var education = ["(Phd.) Neuroscience, Nanyang Technological University, Singapore Jan 2014- Nov 2014 \
      MSc Biomedical Engineering Nanyang Technological University, Singapore Aug 2010- July 2012 \
      BE Biomedical Engineering Anna University, India Aug 2006 - May 2010"];
    $scope.testEducation = lemma.find_and_parse_education(education);
    var languages = ["Chinese Tamil Japanese"];
    $scope.testLanguages = lemma.parse_language(languages);
    var workExperience = ["Technical papers /Projects First place in paper presentation organized by Anna university Second place in the paper presentation at the inter-collegiate symposium Designed a system to use brain signals to control motor functions. Created a motion capture system for upper limb movement analysis for stroke patients"];
    $scope.testWork = lemma.parse_work(workExperience);
    console.log("education", $scope.testEducation);
    console.log("languages", $scope.testLanguages);
    console.log("work", $scope.testWork);
      $scope.testJob = jobDescriptionParser.find_and_parse_work_time(["blah blah blah", "5 years experience"]);
      console.log("job", $scope.testJob);

  $scope.$watch('file', function () {
    if ($scope.file != null) {
      $scope.files = [$scope.file];
    }
  });

  $scope.$on("fileProgress", function(e, progress) {
    $scope.progress = (progress.loaded / progress.total) * 100;
  });

  var processFiles = function (files) {
    $scope.fileNames = "";
    if (files && files.length) {
      for (var i = 0; i < files.length; i++) {
        console.log(files[i]);
        $scope.fileNames += files[i].name + "\n";
        $scope.showProgressBar = true;
        fileReader.readAsDataUrl(files[i], $scope)
          .then(function(result) {
            pdfReader.getAllTextFromPdf(result).then(function(result) {
              console.log("final array of string", result);
              $scope.$apply(function() {
                result.forEach(function(line) {
                  $scope.page1content += line + '\n';
                });
              });
              var tokens = cvTokenizer.tokenizeCv(result);
              console.log("tokens", tokens);

              // TODO: Factor into CV handler method
              var educationParsed = lemma.find_and_parse_education(tokens.education);
              var languageParsed = lemma.parse_language(tokens.language);
              var interestParsed = lemma.parse_interest(tokens.interest);
              var skillParsed = lemma.parse_skills(tokens.skill);
              var experienceParsed = lemma.parse_work(tokens.experience);
              console.log("education", educationParsed);
              console.log("language", languageParsed);
              console.log("interest", interestParsed);
              console.log("skill", skillParsed);
              console.log("experience", experienceParsed);
            });
          });
      }
    }
  };

  var processJobDesc = function(jobDesc) {
    var tokens = jobDescTokenizer.tokenizeJobDesc(jobDesc);
    console.log("job desc processed", tokens);
  };

  $scope.doProcess = function () {
    $scope.page1content = "";
    processFiles($scope.files);
    processJobDesc($scope.jobDescript);
  };
});<commit_msg>Job Description Parser: Parse job description, prints out to console for now.<commit_after>'use strict';

angular.module('myApp.view1', ['ngRoute', 'ngFileUpload'])
  .config(['$routeProvider', function($routeProvider) {
    $routeProvider.when('/view1', {
      templateUrl: 'view1/view1.html',
      controller: 'View1Ctrl'
    })
    .when('/view2', {
      templateUrl: 'view2/view2.html',
      controller: 'View2Ctrl'
    });
  }])

.controller('View1Ctrl', function($scope, fileReader, pdfReader, lemma, cvTokenizer, jobDescTokenizer, jobDescriptionParser, storageAccess) {
    $scope.page1content = "No file opened.";
    $scope.fileNames = "";
    $scope.jobDescript = null;

    // TODO: Remove testing code
    var education = ["(Phd.) Neuroscience, Nanyang Technological University, Singapore Jan 2014- Nov 2014 \
      MSc Biomedical Engineering Nanyang Technological University, Singapore Aug 2010- July 2012 \
      BE Biomedical Engineering Anna University, India Aug 2006 - May 2010"];
    $scope.testEducation = lemma.find_and_parse_education(education);
    var languages = ["Chinese Tamil Japanese"];
    $scope.testLanguages = lemma.parse_language(languages);
    var workExperience = ["Technical papers /Projects First place in paper presentation organized by Anna university Second place in the paper presentation at the inter-collegiate symposium Designed a system to use brain signals to control motor functions. Created a motion capture system for upper limb movement analysis for stroke patients"];
    $scope.testWork = lemma.parse_work(workExperience);
    console.log("education", $scope.testEducation);
    console.log("languages", $scope.testLanguages);
    console.log("work", $scope.testWork);
      $scope.testJob = jobDescriptionParser.find_and_parse_work_time(["blah blah blah", "5 years experience"]);
      console.log("job", $scope.testJob);

  $scope.$watch('file', function () {
    if ($scope.file != null) {
      $scope.files = [$scope.file];
    }
  });

  $scope.$on("fileProgress", function(e, progress) {
    $scope.progress = (progress.loaded / progress.total) * 100;
  });

  var processFiles = function (files) {
    $scope.fileNames = "";
    if (files && files.length) {
      for (var i = 0; i < files.length; i++) {
        console.log(files[i]);
        $scope.fileNames += files[i].name + "\n";
        $scope.showProgressBar = true;
        fileReader.readAsDataUrl(files[i], $scope)
          .then(function(result) {
            pdfReader.getAllTextFromPdf(result).then(function(result) {
              console.log("final array of string", result);
              $scope.$apply(function() {
                result.forEach(function(line) {
                  $scope.page1content += line + '\n';
                });
              });
              var tokens = cvTokenizer.tokenizeCv(result);
              console.log("cv tokens", tokens);

              // TODO: Factor into CV handler method
              var educationParsed = lemma.find_and_parse_education(tokens.education);
              var languageParsed = lemma.parse_language(tokens.language);
              var interestParsed = lemma.parse_interest(tokens.interest);
              var skillParsed = lemma.parse_skills(tokens.skill);
              var experienceParsed = lemma.parse_work(tokens.experience);
              console.log("education", educationParsed);
              console.log("language", languageParsed);
              console.log("interest", interestParsed);
              console.log("skill", skillParsed);
              console.log("experience", experienceParsed);
            });
          });
      }
    }
  };

  var processJobDesc = function(jobDesc) {
    var tokens = jobDescTokenizer.tokenizeJobDesc(jobDesc);
    console.log("job desc tokens", tokens);
    var minReqParsed = jobDescriptionParser.parse_min_req(tokens.minimumRequirement);
    var skillsParsed = jobDescriptionParser.parse_skills(tokens.preferredQualification); // TODO: parse from minreq as well
    var locationParsed = jobDescriptionParser.parse_location(tokens.location);
    var educationParsed = jobDescriptionParser.find_and_parse_education(tokens.minimumRequirement);
    var workTimeParsed = jobDescriptionParser.find_and_parse_work_time(tokens.minimumRequirement);
    console.log("minimum requirements", minReqParsed);
    console.log("preferred qualifications", skillsParsed);
    console.log("location", locationParsed);
    console.log("education", educationParsed);
    console.log("worktime", workTimeParsed);
  };

  $scope.doProcess = function () {
    $scope.page1content = "";
    processFiles($scope.files);
    processJobDesc($scope.jobDescript);
  };
});<|endoftext|>


<commit_before>// -*- mode: js; js-indent-level: 4; indent-tabs-mode: nil -*-

const Lang = imports.lang;
const Gio = imports.gi.Gio;
const St = imports.gi.St;
const Main = imports.ui.main;
const PanelMenu = imports.ui.panelMenu;
const PopupMenu = imports.ui.popupMenu;
const Slider = imports.ui.slider;

const DEFAULT_VALUE = 1.00;
const MIN_VALUE = 0.50;
const MAX_VALUE = 3.00;

const NUM_DECIMALS = 2;

const TEXT_SCALING_FACTOR_KEY = 'text-scaling-factor';

// Makes sure that the value is in [MIN_VALUE, MAX_VALUE].
function _normalizeValue(value) {
    return Math.max(MIN_VALUE, Math.min(value, MAX_VALUE));
}

// Translates a value in [MIN_VALUE, MAX_VALUE] to [0.00, 1.00].
function _textScalingToSliderValue(textScaling) {
    return (textScaling - MIN_VALUE) / (MAX_VALUE - MIN_VALUE);
}

// Translates a value in [0.00, 1.00] to [MIN_VALUE, MAX_VALUE].
function _sliderValueToTextScaling(sliderValue) {
    return sliderValue * (MAX_VALUE - MIN_VALUE) + MIN_VALUE;
}

// Checks if a given float number matches the default one using NUM_DECIMALS.
function _isDefaultFloatValue(value) {
    return Math.abs(value - DEFAULT_VALUE) < (Math.pow(10, -NUM_DECIMALS) / 2);
}

const TextScalerButton = new Lang.Class({
    Name: 'TextScalerButton',
    Extends: PanelMenu.Button,

    _init: function() {
        this.parent(0.0, "Text Scaler Button");
        this.setSensitive(true);

        // GSettings to change the text-scaling factor.
        this._settings = new Gio.Settings({ schema_id: 'org.gnome.desktop.interface' });
        this._settings.connect('changed::text-scaling-factor', Lang.bind(this, this._onSettingsChanged));

        // The actual text scaling factor, as a float.
        this._currentValue = this._settings.get_double(TEXT_SCALING_FACTOR_KEY);

        // The value currently displayed by the slider, normalized to [0.00, 1.00].
        this._sliderValue = _textScalingToSliderValue(this._currentValue);

        // Panel menu icon.
        this._hbox = new St.BoxLayout({ style_class: 'panel-status-menu-box' });
        this._hbox.add_child(new St.Icon({ style_class: 'system-status-icon',
                                           icon_name: 'preferences-desktop-font' }));
        this._hbox.add_child(PopupMenu.arrowIcon(St.Side.BOTTOM));
        this.actor.add_child(this._hbox);

        // Popup Menu.
        this._menu = new PopupMenu.PopupMenu(this.actor, 0.0, St.Side.BOTTOM);
        this.setMenu(this._menu);

        this._menuItem = new PopupMenu.PopupBaseMenuItem({ activate: true });
        this._menuItem.actor.connect('key-press-event', Lang.bind(this, this._onMenuItemKeyPressed));
        this._menu.addMenuItem(this._menuItem);

        this._entry = new St.Entry();
        this._entry.clutter_text.connect('activate', Lang.bind(this, this._onEntryActivated));
        this._entry.clutter_text.connect('key-focus-out', Lang.bind(this, this._onEntryKeyFocusOut));
        this._menuItem.actor.add_child(this._entry);

        this._slider = new Slider.Slider(this._sliderValue);
        this._slider.connect('value-changed', Lang.bind(this, this._onSliderValueChanged));
        this._slider.connect('drag-end', Lang.bind(this, this._onSliderDragEnded));
        this._slider.actor.x_expand = true;
        this._menuItem.actor.add_actor(this._slider.actor);

        this._separatorItem = new PopupMenu.PopupSeparatorMenuItem();
        this._menu.addMenuItem(this._separatorItem);

        this._resetValueItem = new PopupMenu.PopupMenuItem("Reset to default value");
        this._resetValueItem.connect('activate', Lang.bind(this, this._onResetValueActivate));
        this._menu.addMenuItem(this._resetValueItem);

        // Make sure we first update the UI with the current state.
        this._updateUI();
    },

    _onSettingsChanged: function(settings, key) {
        this._updateValue(this._settings.get_double(TEXT_SCALING_FACTOR_KEY), false);
    },

    _onMenuItemKeyPressed: function(actor, event) {
        return this._slider.onKeyPressEvent(actor, event);
    },

    _onEntryActivated: function(entry) {
        this._updateValueFromTextEntry(entry);
    },

    _onEntryKeyFocusOut: function(entry) {
        this._updateValueFromTextEntry(entry);
    },

    _onSliderValueChanged: function(slider, value) {
        this._sliderValue = value;

        // The following call only updates the text in the entry but does
        // not change the actual current value, which we'll do on drag ended.
        this._updateEntry(_sliderValueToTextScaling(value));
    },

    _onSliderDragEnded: function(slider) {
        this._updateValue(_sliderValueToTextScaling(this._sliderValue));
    },

    _onResetValueActivate: function(menuItem, event) {
        this._updateValue(DEFAULT_VALUE);
    },

    _updateValueFromTextEntry: function(entry) {
        let currentText = entry.get_text();
        let value = parseFloat(currentText);

        // Only update the value if it's a valid one, otherwise
        // simply reset the UI to show the current status again.
        if (isFinite(currentText) && !isNaN(currentText) && !isNaN(value)) {
            this._updateValue(value);
        }

        // Force to always update the UI to make sure that whatever
        // value gets actually applied is displayed as it should be.
        this._updateUI();
    },

    _updateSettings: function() {
        this._settings.set_double(TEXT_SCALING_FACTOR_KEY, this._currentValue);
    },

    _updateValue: function(value, updateSettings=false) {
        if (this._currentValue == value)
            return;

        // Need to keep the value between the valid limits.
        this._currentValue = _normalizeValue(value);

        // We don't always want to update the GSettings (e.g. external change).
        if (!updateSettings) {
            this._updateSettings();
        }

        // Always affect the UI to reflect changes.
        this._updateUI();
    },

    _updateUI: function() {
        this._updateEntry();
        this._updateSlider();
        this._updateResetValueItem();
    },

    _updateEntry: function(value=null) {
        let valueToDisplay = (value != null) ? value : this._currentValue;

        // We only show NUM_DECIMALS decimals on the text entry widget.
        this._entry.set_text(valueToDisplay.toFixed(NUM_DECIMALS));
    },

    _updateSlider: function() {
        this._slider.setValue(_textScalingToSliderValue(this._currentValue));
    },

    _updateResetValueItem: function() {
        this._resetValueItem.setSensitive(!_isDefaultFloatValue(this._currentValue));
    }
});

let _button = null;

function init() {
}

function enable() {
    _button = new TextScalerButton();
    Main.panel.addToStatusArea('text-scaler-button', _button);
}

function disable() {
    _button.destroy();
}
<commit_msg>Update scaling factor on 'value-changed' when not explicitly dragging<commit_after>// -*- mode: js; js-indent-level: 4; indent-tabs-mode: nil -*-

const Lang = imports.lang;
const Gio = imports.gi.Gio;
const St = imports.gi.St;
const Main = imports.ui.main;
const PanelMenu = imports.ui.panelMenu;
const PopupMenu = imports.ui.popupMenu;
const Slider = imports.ui.slider;

const DEFAULT_VALUE = 1.00;
const MIN_VALUE = 0.50;
const MAX_VALUE = 3.00;

const NUM_DECIMALS = 2;

const TEXT_SCALING_FACTOR_KEY = 'text-scaling-factor';

// Makes sure that the value is in [MIN_VALUE, MAX_VALUE].
function _normalizeValue(value) {
    return Math.max(MIN_VALUE, Math.min(value, MAX_VALUE));
}

// Translates a value in [MIN_VALUE, MAX_VALUE] to [0.00, 1.00].
function _textScalingToSliderValue(textScaling) {
    return (textScaling - MIN_VALUE) / (MAX_VALUE - MIN_VALUE);
}

// Translates a value in [0.00, 1.00] to [MIN_VALUE, MAX_VALUE].
function _sliderValueToTextScaling(sliderValue) {
    return sliderValue * (MAX_VALUE - MIN_VALUE) + MIN_VALUE;
}

// Checks if a given float number matches the default one using NUM_DECIMALS.
function _isDefaultFloatValue(value) {
    return Math.abs(value - DEFAULT_VALUE) < (Math.pow(10, -NUM_DECIMALS) / 2);
}

const TextScalerButton = new Lang.Class({
    Name: 'TextScalerButton',
    Extends: PanelMenu.Button,

    _init: function() {
        this.parent(0.0, "Text Scaler Button");
        this.setSensitive(true);

        // GSettings to change the text-scaling factor.
        this._settings = new Gio.Settings({ schema_id: 'org.gnome.desktop.interface' });
        this._settings.connect('changed::text-scaling-factor', Lang.bind(this, this._onSettingsChanged));

        // The actual text scaling factor, as a float.
        this._currentValue = this._settings.get_double(TEXT_SCALING_FACTOR_KEY);

        // The value currently displayed by the slider, normalized to [0.00, 1.00].
        this._sliderValue = _textScalingToSliderValue(this._currentValue);

        // Panel menu icon.
        this._hbox = new St.BoxLayout({ style_class: 'panel-status-menu-box' });
        this._hbox.add_child(new St.Icon({ style_class: 'system-status-icon',
                                           icon_name: 'preferences-desktop-font' }));
        this._hbox.add_child(PopupMenu.arrowIcon(St.Side.BOTTOM));
        this.actor.add_child(this._hbox);

        // Popup Menu.
        this._menu = new PopupMenu.PopupMenu(this.actor, 0.0, St.Side.BOTTOM);
        this.setMenu(this._menu);

        this._menuItem = new PopupMenu.PopupBaseMenuItem({ activate: true });
        this._menuItem.actor.connect('key-press-event', Lang.bind(this, this._onMenuItemKeyPressed));
        this._menu.addMenuItem(this._menuItem);

        this._entry = new St.Entry();
        this._entry.clutter_text.connect('activate', Lang.bind(this, this._onEntryActivated));
        this._entry.clutter_text.connect('key-focus-out', Lang.bind(this, this._onEntryKeyFocusOut));
        this._menuItem.actor.add_child(this._entry);

        this._slider = new Slider.Slider(this._sliderValue);
        this._slider.connect('value-changed', Lang.bind(this, this._onSliderValueChanged));
        this._slider.connect('drag-begin', Lang.bind(this, this._onSliderDragBegan));
        this._slider.connect('drag-end', Lang.bind(this, this._onSliderDragEnded));
        this._slider.actor.x_expand = true;
        this._menuItem.actor.add_actor(this._slider.actor);

        this._sliderIsDragging = false;

        this._separatorItem = new PopupMenu.PopupSeparatorMenuItem();
        this._menu.addMenuItem(this._separatorItem);

        this._resetValueItem = new PopupMenu.PopupMenuItem("Reset to default value");
        this._resetValueItem.connect('activate', Lang.bind(this, this._onResetValueActivate));
        this._menu.addMenuItem(this._resetValueItem);

        // Make sure we first update the UI with the current state.
        this._updateUI();
    },

    _onSettingsChanged: function(settings, key) {
        this._updateValue(this._settings.get_double(TEXT_SCALING_FACTOR_KEY), false);
    },

    _onMenuItemKeyPressed: function(actor, event) {
        return this._slider.onKeyPressEvent(actor, event);
    },

    _onEntryActivated: function(entry) {
        this._updateValueFromTextEntry(entry);
    },

    _onEntryKeyFocusOut: function(entry) {
        this._updateValueFromTextEntry(entry);
    },

    _onSliderValueChanged: function(slider, value) {
        this._sliderValue = value;
        this._updateEntry(_sliderValueToTextScaling(value));

        // We don't want to update the value when the user is explicitly
        // dragging the slider by clicking on the handle and moving it
        // around to avoid the unpredictable (and very confusing) behaviour
        // that would happen due to the mouse pointer being on a different
        // area of the screen right after updating the scaling factor.
        if (!this._sliderIsDragging)
            this._updateValue(_sliderValueToTextScaling(this._sliderValue));
    },

    _onSliderDragBegan: function(slider) {
        this._sliderIsDragging = true;
    },

    _onSliderDragEnded: function(slider) {
        // We don't update the scaling factor on 'value-changed'
        // when explicitly dragging, so we need to do it here too.
        this._updateValue(_sliderValueToTextScaling(this._sliderValue));
        this._sliderIsDragging = false;
    },

    _onResetValueActivate: function(menuItem, event) {
        this._updateValue(DEFAULT_VALUE);
    },

    _updateValueFromTextEntry: function(entry) {
        let currentText = entry.get_text();
        let value = parseFloat(currentText);

        // Only update the value if it's a valid one, otherwise
        // simply reset the UI to show the current status again.
        if (isFinite(currentText) && !isNaN(currentText) && !isNaN(value)) {
            this._updateValue(value);
        }

        // Force to always update the UI to make sure that whatever
        // value gets actually applied is displayed as it should be.
        this._updateUI();
    },

    _updateSettings: function() {
        this._settings.set_double(TEXT_SCALING_FACTOR_KEY, this._currentValue);
    },

    _updateValue: function(value, updateSettings=false) {
        if (this._currentValue == value)
            return;

        // Need to keep the value between the valid limits.
        this._currentValue = _normalizeValue(value);

        // We don't always want to update the GSettings (e.g. external change).
        if (!updateSettings) {
            this._updateSettings();
        }

        // Always affect the UI to reflect changes.
        this._updateUI();
    },

    _updateUI: function() {
        this._updateEntry();
        this._updateSlider();
        this._updateResetValueItem();
    },

    _updateEntry: function(value=null) {
        let valueToDisplay = (value != null) ? value : this._currentValue;

        // We only show NUM_DECIMALS decimals on the text entry widget.
        this._entry.set_text(valueToDisplay.toFixed(NUM_DECIMALS));
    },

    _updateSlider: function() {
        this._slider.setValue(_textScalingToSliderValue(this._currentValue));
    },

    _updateResetValueItem: function() {
        this._resetValueItem.setSensitive(!_isDefaultFloatValue(this._currentValue));
    }
});

let _button = null;

function init() {
}

function enable() {
    _button = new TextScalerButton();
    Main.panel.addToStatusArea('text-scaler-button', _button);
}

function disable() {
    _button.destroy();
}
<|endoftext|>


<commit_before>// opt => {channel,room, socket, io, auto:t/f}

// fnc =>  joinroom(room, cb),
//         leaveroom(room, cb),
//         changeroom(room, cb),
//         watchallroom,
//         watchoneroom(room),
//         sID,
//         FileBOT(data, cb) => data={fileid, body, kind }
//         EncryptBOT(data, cb) => data={messageid, method, body}

var fs = require('fs');
var crypto = require('crypto');

module.exports = function (opt) {
    var init = function (opt) {
        this.io = opt.io || null;
        this.channel = opt.channel || null;
        this.room = opt.room || 'default';
        this.socket = opt.socket || null;
        if (opt.auto == true) {
            return auto(this);
        } else {
            return this;
        };
    };

    //start
    var auto = function (object) {
        var socket = object.socket;
        var room = object.room;
        socket.join(room);
        return object;
    };

    //join room
    var joinroom = function (room, cb) {
        var socket = this.socket;
        socket.join(room, function () {
            cb(true);
        });
    };

    //leave room
    var leaveroom = function (room, cb) {
        var socket = this.socket;
        socket.leave(room, function () {
            cb(true);
        });
    };

    //change room will leave old room first
    var changeroom = function (room, cb) {
        var socket = this.socket;
        var oldroom = this.room;
        var newroom = room;
        socket.leave(oldroom, function () {
            socket.join(newroom, function () {
                cb(true);
            });
        });
    };

    //watch all room and users list from socket.io namespace
    var watchallroom = function () {
        var io = this.io;
        var socket = this.socket;
        var name = io.sockets.name;
        return io.nsps[name].adapter.rooms;
    };

    //watch one room and users list from socket.io namespace
    var watchoneroom = function (room) {
        var io = this.io;
        var socket = this.socket;
        var name = io.sockets.name;
        return io.nsps[name].adapter.rooms[room];
    };

    //watch the sessionID from socket.io
    var sID = function () {
        var socket = this.socket;
        return socket.handshake.sessionID;
    };

    //File System BOT Fnc
    function base64_encode(file) {
        var f = fs.readFileSync(file);
        return new Buffer(f).toString('base64');
    };
    function base64_decode(base64str, file, cb) {
        var f = new Buffer(base64str, 'base64');
        fs.writeFile(file, f, function (error) {
            if (error) {
                cb({ result: 0, info: file });
            } else {
                cb({ result: 1, info: file });
            };
        });
    };
    var FileBOT = function (data, cb) {
        var fileid = data.fileid;
        var body = data.body;
        var kind = data.kind;
        base64_decode(body, './files/' + kind, function (data) {
            data['fileid'] = fileid;
            data['response'] = 'FileBOT';
            cb(data);
        });
    };

    //Encrypt BOT Fnc
    var EncryptBOT = function (data, cb) {
        var messageid = data.messageid;
        var method = data.method || 'MD5';
        var encrypt = data.encrypt;
        var body = data.body;
        var response = 'EncryptBOT';

        if (typeof encrypt == 'undefined') {
            switch (method) {
                case 'MD5':
                    data.body = crypto.createHash('md5').update(body).digest('hex');
                    data['encrypt'] = 'MD5';
                    data['response'] = 'EncryptBOT';
                    data['result'] = 1;
                    data['info'] = '';
                    cb(data);
                case 'SHA1':
            };

        } else {
            //decrypt
        };
    };

    var channel = {
        init: init,
        joinroom: joinroom,
        leaveroom: leaveroom,
        changeroom: changeroom,
        watchallroom: watchallroom,
        watchoneroom: watchoneroom,
        sID: sID,
        FileBOT: FileBOT,
        EncryptBOT: EncryptBOT
    };

    return channel.init(opt);
};<commit_msg>Add SHA1<commit_after>// opt => {channel,room, socket, io, auto:t/f}

// fnc =>  joinroom(room, cb),
//         leaveroom(room, cb),
//         changeroom(room, cb),
//         watchallroom,
//         watchoneroom(room),
//         sID,
//         FileBOT(data, cb) => data={fileid, body, kind }
//         EncryptBOT(data, cb) => data={messageid, method, body}

var fs = require('fs');
var crypto = require('crypto');

module.exports = function (opt) {
    var init = function (opt) {
        this.io = opt.io || null;
        this.channel = opt.channel || null;
        this.room = opt.room || 'default';
        this.socket = opt.socket || null;
        if (opt.auto == true) {
            return auto(this);
        } else {
            return this;
        };
    };

    //start
    var auto = function (object) {
        var socket = object.socket;
        var room = object.room;
        socket.join(room);
        return object;
    };

    //join room
    var joinroom = function (room, cb) {
        var socket = this.socket;
        socket.join(room, function () {
            cb(true);
        });
    };

    //leave room
    var leaveroom = function (room, cb) {
        var socket = this.socket;
        socket.leave(room, function () {
            cb(true);
        });
    };

    //change room will leave old room first
    var changeroom = function (room, cb) {
        var socket = this.socket;
        var oldroom = this.room;
        var newroom = room;
        socket.leave(oldroom, function () {
            socket.join(newroom, function () {
                cb(true);
            });
        });
    };

    //watch all room and users list from socket.io namespace
    var watchallroom = function () {
        var io = this.io;
        var socket = this.socket;
        var name = io.sockets.name;
        return io.nsps[name].adapter.rooms;
    };

    //watch one room and users list from socket.io namespace
    var watchoneroom = function (room) {
        var io = this.io;
        var socket = this.socket;
        var name = io.sockets.name;
        return io.nsps[name].adapter.rooms[room];
    };

    //watch the sessionID from socket.io
    var sID = function () {
        var socket = this.socket;
        return socket.handshake.sessionID;
    };

    //File System BOT Fnc
    function base64_encode(file) {
        var f = fs.readFileSync(file);
        return new Buffer(f).toString('base64');
    };
    function base64_decode(base64str, file, cb) {
        var f = new Buffer(base64str, 'base64');
        fs.writeFile(file, f, function (error) {
            if (error) {
                cb({ result: 0, info: file });
            } else {
                cb({ result: 1, info: file });
            };
        });
    };
    var FileBOT = function (data, cb) {
        var fileid = data.fileid;
        var body = data.body;
        var kind = data.kind;
        base64_decode(body, './files/' + kind, function (data) {
            data['fileid'] = fileid;
            data['response'] = 'FileBOT';
            cb(data);
        });
    };

    //Encrypt BOT Fnc
    var EncryptBOT = function (data, cb) {
        var messageid = data.messageid;
        var method = data.method || 'MD5';
        var encrypt = data.encrypt;
        var body = data.body;
        var response = 'EncryptBOT';

        if (typeof encrypt == 'undefined') {
            switch (method) {
                case 'MD5':
                    data.body = crypto.createHash('md5').update(body).digest('hex');
                    data['encrypt'] = 'MD5';
                    data['result'] = 1;
                    data['info'] = '';
                    break;
                case 'SHA1':
                    data.body = crypto.createHash('sha1').update(body).digest('hex');
                    data['encrypt'] = 'SHA1';
                    data['result'] = 1;
                    data['info'] = '';
                    break;
            };
            data['response'] = response;
            delete data.method;
            cb(data);
        } else {
            //decrypt
        };
    };

    var channel = {
        init: init,
        joinroom: joinroom,
        leaveroom: leaveroom,
        changeroom: changeroom,
        watchallroom: watchallroom,
        watchoneroom: watchoneroom,
        sID: sID,
        FileBOT: FileBOT,
        EncryptBOT: EncryptBOT
    };

    return channel.init(opt);
};<|endoftext|>


<commit_before>'use strict';

const POLL_INTERVAL = 30*1000;

function Followers(nodecg) {
  this.nodecg = nodecg;
  this.twitch = nodecg.extensions['lfg-twitchapi'];
  this.latestFollower = nodecg.Replicant("latestFollower", {defaultValue: null, persistent: false});

  this._scheduleFollowers();
}

Followers.prototype._scheduleFollowers = function() {
  this.nodecg.log.debug("Polling for TwitchTV Followers.");
  this.twitch.get('/channels/{{username}}/follows', { limit: 1, direction: 'desc' }, (err, code, body) => {
    if (err) {
      this.nodecg.log.error(err);
      setTimeout(() => { this._scheduleFollowers() }, POLL_INTERVAL);
      return;
    }

    if (code != 200) {
      this.nodecg.log.error("Unknown response code: "+code);
      setTimeout(() => { this._scheduleFollowers() }, POLL_INTERVAL);
      return;
    }

    if (body.follows.length > 0) {
      this.nodecg.log.debug("Discovered " + body.follows.length + " followers.");
      this.latestFollower.value = body.follows[0].user.display_name;
    }

    setTimeout(() => { this._scheduleFollowers() }, POLL_INTERVAL);
  });
}

module.exports = function(api) {
  return new Followers(api);
};
<commit_msg>Emit all follower events<commit_after>'use strict';

const POLL_INTERVAL = 30*1000;

function Followers(nodecg) {
  this.nodecg = nodecg;
  this.twitch = nodecg.extensions['lfg-twitchapi'];
  this.latestFollower = nodecg.Replicant("latestFollower", { defaultValue: null, persistent: true });

  this._scheduleFollowers();
}

Followers.prototype._scheduleFollowers = function() {
  this.nodecg.log.debug("Polling for TwitchTV Followers.");
  this.twitch.get('/channels/{{username}}/follows', { limit: 50, direction: 'desc' }, (err, code, body) => {
    if (err) {
      this.nodecg.log.error(err);
      setTimeout(() => { this._scheduleFollowers() }, POLL_INTERVAL);
      return;
    }

    if (code != 200) {
      this.nodecg.log.error("Unknown response code: "+code);
      setTimeout(() => { this._scheduleFollowers() }, POLL_INTERVAL);
      return;
    }

    var lastFollowerTs = 0;
    if (this.latestFollower.value) {
      lastFollowerTs = Date.parse(this.latestFollower.value.created_at);
    }

    if (body.follows.length > 0) {
      this.nodecg.log.debug("Discovered " + body.follows.length + " followers.");
      this.latestFollower.value = body.follows[0];

      for (var follower of body.follows.reverse()) {
        var parsedTs = Date.parse(follower.created_at);
        if (parsedTs > lastFollowerTs) {
          this.nodecg.sendMessage('follower', follower);
        }
      }
    }

    setTimeout(() => { this._scheduleFollowers() }, POLL_INTERVAL);
  });
};

module.exports = function(api) {
  return new Followers(api);
};
<|endoftext|>


<commit_before>var tor2web_list = []
var clicks_list = []
var backlinks_list = []

// downloads JSON stats from the JSON API
function getStats(order_by, list){
  var limit = 100;
  var url = "/stats/popularity?limit=" + limit + "&order_by="+order_by
  $.getJSON( url, function( json ) {
    var ol_list_element = $("#"+order_by);
    $.each(json, function (index, result) {
      item = {y: result.fields[order_by], label: result.fields.about+".onion"}
      list.push(item);
      // show the first 10
      if(index < 10){
	var content = '
' + item.y;
	content = content + ' ' + item.label + '
';
	ol_list_element.append(content);
      }
    });
    // wait until every list is ready
    if(tor2web_list.length == limit &&
      clicks_list.length == limit &&
      backlinks_list.length == limit){
      //show the results
      viewer();
    }
  });
}

// download the JSON stats
getStats("tor2web", tor2web_list);
getStats("clicks", clicks_list);
getStats("public_backlinks", backlinks_list);

function viewer(){
  // calculate the intersection between these three lists
  var new_tor2web_list = [];
  var new_backlinks_list = [];
  var new_clicks_list = [];
  var intersection_size = 0;
  $.each(tor2web_list, function(t_index, tor2web) {
    if(intersection_size == 30){
      return false;
    }
    $.each(backlinks_list, function(b_index, backlinks) {
      if(backlinks.label == tor2web.label){
	$.each(clicks_list, function(c_index, clicks) {
	  if(clicks.label == tor2web.label){
	    new_tor2web_list.push(tor2web);
	    new_backlinks_list.push(backlinks);
	    new_clicks_list.push(clicks);
	    ++intersection_size;
	  }
	});
      }
    });
  });
  tor2web_list = new_tor2web_list;
  backlinks_list = new_backlinks_list;
  clicks_list = new_clicks_list;
  show_bars();
}

// viewer function
function show_bars(){
  var chart = new CanvasJS.Chart("chartContainer", {
    title:{
      text:"Intersection of the different popularity sources"
    },
    axisX:{
      interval: 1,
      labelFontSize: 10,
      lineThickness: 0
    },
    axisY2:{
      valueFormatString: "0",
      lineThickness: 0
    },
    toolTip: {
      shared: true
    },
    legend:{
      verticalAlign: "top",
      horizontalAlign: "center"
    },
    data: [
    {
      type: "stackedBar",
      showInLegend: true,
      name: "Tor2web average visits",
      axisYType: "secondary",
      color: "#7E8F74",
      dataPoints: tor2web_list
    },
    {
      type: "stackedBar",
      showInLegend: true,
      name: "Public WWW backlinks",
      axisYType: "secondary",
      color: "#FF9900",
      dataPoints: backlinks_list
    },
    {
      type: "stackedBar",
      showInLegend: true,
      name: "Total search results clicks",
      axisYType: "secondary",
      color: "#6699FF",
      dataPoints: clicks_list
    }
    ]
  });
  chart.render();
}<commit_msg>Visualization is now re-ordered.<commit_after>var tor2web_list = []
var clicks_list = []
var backlinks_list = []

// downloads JSON stats from the JSON API
function getStats(order_by, list){
  var limit = 100;
  var url = "/stats/popularity?limit=" + limit + "&order_by="+order_by
  $.getJSON( url, function( json ) {
    var ol_list_element = $("#"+order_by);
    $.each(json, function (index, result) {
      item = {y: result.fields[order_by], label: result.fields.about+".onion"}
      list.push(item);
      // show the first 10
      if(index < 10){
	var content = '
' + item.y;
	content = content + ' ' + item.label + '
';
	ol_list_element.append(content);
      }
    });
    // wait until every list is ready
    if(tor2web_list.length == limit &&
      clicks_list.length == limit &&
      backlinks_list.length == limit){
      //show the results
      viewer();
    }
  });
}

function viewer(){
  // calculate the intersection between these three lists
  var new_tor2web_list = [];
  var new_backlinks_list = [];
  var new_clicks_list = [];
  var intersection_size = 0;
  $.each(tor2web_list, function(t_index, tor2web) {
    if(intersection_size == 30){
      return false;
    }
    $.each(backlinks_list, function(b_index, backlinks) {
      if(backlinks.label == tor2web.label){
	$.each(clicks_list, function(c_index, clicks) {
	  if(clicks.label == tor2web.label){
	    var place = backlinks_list.length;
	    for(var i = 0; i<new_tor2web_list.length; ++i){
	      var sum1 = new_tor2web_list[i].y + new_backlinks_list[i].y + new_clicks_list[i].y;
	      var sum2 = tor2web.y + backlinks.y + clicks.y;
	      if(sum1 > sum2){
		place = i;
		break;
	      }
	    }
	    new_tor2web_list.splice(place, 0, tor2web);
	    new_backlinks_list.splice(place, 0, backlinks);
	    new_clicks_list.splice(place, 0, clicks);
	    ++intersection_size;
	  }
	});
      }
    });
  });
  tor2web_list = new_tor2web_list;
  backlinks_list = new_backlinks_list;
  clicks_list = new_clicks_list;
  show_bars();
}

// download the JSON stats
getStats("tor2web", tor2web_list);
getStats("clicks", clicks_list);
getStats("public_backlinks", backlinks_list);

// viewer function
function show_bars(){
  var chart = new CanvasJS.Chart("chartContainer", {
    title:{
      text:"Intersection of the different popularity sources"
    },
    axisX:{
      interval: 1,
      labelFontSize: 10,
      lineThickness: 0
    },
    axisY2:{
      valueFormatString: "0",
      lineThickness: 0
    },
    toolTip: {
      shared: true
    },
    legend:{
      verticalAlign: "top",
      horizontalAlign: "center"
    },
    data: [
    {
      type: "stackedBar",
      showInLegend: true,
      name: "Tor2web average visits",
      axisYType: "secondary",
      color: "#7E8F74",
      dataPoints: tor2web_list
    },
    {
      type: "stackedBar",
      showInLegend: true,
      name: "Public WWW backlinks",
      axisYType: "secondary",
      color: "#FF9900",
      dataPoints: backlinks_list
    },
    {
      type: "stackedBar",
      showInLegend: true,
      name: "Total search results clicks",
      axisYType: "secondary",
      color: "#6699FF",
      dataPoints: clicks_list
    }
    ]
  });
  chart.render();
}<|endoftext|>


<commit_before>'use strict';

var categoryMenu = require('../services/response/categoryMenuResponse').getInstance();
var productMenu = require('../services/response/productMenuResponse').getInstance();
var checkoutMenu = require('../services/response/checkoutResponse').getInstance();
var orderMenu = require('../services/response/orderResponse').getInstance();

const MENU = 'menu';
const ALL = 'all';
const CATEGORY = 'category';
const PRODUCT = 'product';
const ORDER_PRODUCT = 'order';

function ResponseFactory() {
}

ResponseFactory.prototype = {
    getResponse: function (message) {
        var messages = message.split('#');
        var data = messages[1];
        var type = messages[0];

        console.info("type ", type);
        console.info("id ", data);

        switch (type) {
            case MENU:
                break;
            case ALL:
                return categoryMenu.getResponse();
                break;
            case CATEGORY:
                return productMenu.getResponse();
                break;
            case PRODUCT:
                console.log("GOT PRODUCT!");
                return checkoutMenu.getResponse(data[0]);
                break;
            case ORDER_PRODUCT:
                return orderMenu.getResponse(data[0]);
                break;
        }
    }
};

/**
 * @returns {ResponseFactory}
 */
module.exports.getInstance = function () {
    return new ResponseFactory();
};
<commit_msg>change categories url<commit_after>'use strict';

var categoryMenu = require('../services/response/categoryMenuResponse').getInstance();
var productMenu = require('../services/response/productMenuResponse').getInstance();
var checkoutMenu = require('../services/response/checkoutResponse').getInstance();
var orderMenu = require('../services/response/orderResponse').getInstance();

const MENU = 'menu';
const ALL = 'all';
const CATEGORY = 'category';
const PRODUCT = 'product';
const ORDER_PRODUCT = 'order';

function ResponseFactory() {
}

ResponseFactory.prototype = {
    getResponse: function (message) {
        var messages = message.split('#');
        var data = messages[1] !== undefined ? messages[1] : null;
        var type = messages[0] !== undefined ? messages[1] : null;

        console.info("type ", type);
        console.info("id ", data);

        switch (type) {
            case MENU:
                break;
            case ALL:
                console.info("step:", ALL)
                return categoryMenu.getResponse();
                break;
            case CATEGORY:
                return productMenu.getResponse();
                break;
            case PRODUCT:
                console.log("GOT PRODUCT!");
                return checkoutMenu.getResponse(data[0]);
                break;
            case ORDER_PRODUCT:
                return orderMenu.getResponse(data[0]);
                break;
        }
    }
};

/**
 * @returns {ResponseFactory}
 */
module.exports.getInstance = function () {
    return new ResponseFactory();
};
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import CircularProgress from '../CircularProgress/CircularProgress'
import { Link } from 'react-router'
import SearchInput from '../SearchInput/SearchInput'
import Counter from '../Statistics/Counter/Counter'
import { theme  } from '../../tools';
import { fetchGlobalMetrics  } from '../../fetch/fetch';
import { waitForDataAndSetState, cancelAllPromises } from '../../helpers/components';

const styles = {
  masthead: {
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'space-around',
    padding: '8%',
  },
  stats: {
    display: 'flex',
    flexWrap: 'wrap',
    alignItems: 'center',
    justifyContent: 'space-around',
  },
  paper: {
    display: 'flex',
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
    padding: '1em',
    color: theme.white,
  },
  catalogLinks: {
    fontSize: '1.5em',
  },
  datagouv: {
    borderTop: `1px solid ${theme.darkblue}`,
    backgroundColor: theme.blue,
    color: '#FFF',
    width: '100%',
    padding: 40,
    marginTop: '4em',
  },
  datagouvIntro: {
    fontSize: '1.2em',
    fontWeight: 'lighter',
    textAlign: 'center',
    fontVariant: 'small-caps',
  },
  datagouvLink: {
    color: '#FFF',
    fontWeight: 'bolder',
    fontSize: '1.3em',
    fontVariant: 'normal',
  },
}

class Home extends Component {
  constructor(props) {
    super(props)
    this.state = {errors: []}
  }

  componentWillMount() {
    return waitForDataAndSetState(fetchGlobalMetrics(), this, 'datasets');
  }

  componentWillUnmount() {
    return cancelAllPromises(this)
  }

  render() {
    const loader =  <CircularProgress />
    const notPublishedYet = this.state.datasets ? <Counter value={this.state.datasets.notPublishedYet} label="" color="yellow" icon="hourglass half"/> : loader
    const published = this.state.datasets ? <Counter value={this.state.datasets.published.public + this.state.datasets.published.private} label="" color="green" icon="database"/> : loader

    return (

          <SearchInput />
          OR
          <Link style={styles.catalogLinks} to="catalogs">Explore the 106 catalogs</Link>

            Votre organisation gère des données géographiques avec des outils compatibles Inspire et souhaite les rendre disponibles sans effort sur data.gouv.fr

Not Yet Published

              {notPublishedYet}

Published Datasets

              {published}

    )
  }
}

export default Home
<commit_msg>Remove ugly border<commit_after>import React, { Component } from 'react'
import CircularProgress from '../CircularProgress/CircularProgress'
import { Link } from 'react-router'
import SearchInput from '../SearchInput/SearchInput'
import Counter from '../Statistics/Counter/Counter'
import { theme  } from '../../tools';
import { fetchGlobalMetrics  } from '../../fetch/fetch';
import { waitForDataAndSetState, cancelAllPromises } from '../../helpers/components';

const styles = {
  masthead: {
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'space-around',
    padding: '8%',
  },
  stats: {
    display: 'flex',
    flexWrap: 'wrap',
    alignItems: 'center',
    justifyContent: 'space-around',
  },
  paper: {
    display: 'flex',
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
    padding: '1em',
    color: theme.white,
  },
  catalogLinks: {
    fontSize: '1.5em',
  },
  datagouv: {
    backgroundColor: theme.blue,
    color: '#FFF',
    width: '100%',
    padding: 40,
    marginTop: '4em',
  },
  datagouvIntro: {
    fontSize: '1.2em',
    fontWeight: 'lighter',
    textAlign: 'center',
    fontVariant: 'small-caps',
  },
  datagouvLink: {
    color: '#FFF',
    fontWeight: 'bolder',
    fontSize: '1.3em',
    fontVariant: 'normal',
  },
}

class Home extends Component {
  constructor(props) {
    super(props)
    this.state = {errors: []}
  }

  componentWillMount() {
    return waitForDataAndSetState(fetchGlobalMetrics(), this, 'datasets');
  }

  componentWillUnmount() {
    return cancelAllPromises(this)
  }

  render() {
    const loader =  <CircularProgress />
    const notPublishedYet = this.state.datasets ? <Counter value={this.state.datasets.notPublishedYet} label="" color="yellow" icon="hourglass half"/> : loader
    const published = this.state.datasets ? <Counter value={this.state.datasets.published.public + this.state.datasets.published.private} label="" color="green" icon="database"/> : loader

    return (

          <SearchInput />
          OR
          <Link style={styles.catalogLinks} to="catalogs">Explore the 106 catalogs</Link>

            Votre organisation gère des données géographiques avec des outils compatibles Inspire et souhaite les rendre disponibles sans effort sur data.gouv.fr

Not Yet Published

              {notPublishedYet}

Published Datasets

              {published}

    )
  }
}

export default Home
<|endoftext|>


<commit_before>'use strict';

/**
 * Websocket transport
 */

const EventEmitter = require('eventemitter3');

module.exports = class Connection extends EventEmitter {
    constructor(options) {
        super();

        this.options = options || {};

        this.socket = null;
        this.connected = false;
        this.last_socket_error = null;

        this.encoding = 'utf8';
        this.incoming_buffer = '';

        this.protocol_fallback = false;
        this.protocol = options.websocket_protocol;
    }

    isConnected() {
        return this.connected;
    }

    writeLine(line, cb) {
        this.debugOut('writeLine() socket=' + (this.socket ? 'yes' : 'no') + ' connected=' + this.connected);

        if (this.socket && this.connected) {
            this.socket.send(line, cb);
        } else if (cb) {
            setTimeout(cb, 0);
        }
    }

    debugOut(out) {
        this.emit('debug', out);
    }

    connect() {
        const that = this;
        const options = this.options;
        let socket = null;
        let ws_addr = '';

        this.debugOut('Connection.connect()');

        this.disposeSocket();
        this.requested_disconnect = false;

        // Build the websocket address. eg. ws://ws.rizon.net:8080
        ws_addr += (options.tls || options.ssl) ? 'wss://' : 'ws://';
        ws_addr += options.host;
        ws_addr += options.port ? ':' + options.port : '';
        ws_addr += options.path ? options.path : '';

        socket = this.socket = new WebSocket(ws_addr, this.protocol);

        socket.onopen = function() {
            that.onSocketFullyConnected();
        };
        socket.onclose = function(event) {
            that.onSocketClose(event);
        };
        socket.onmessage = function(event) {
            that.onSocketMessage(event.data);
        };
        socket.onerror = function(err) {
            that.debugOut('socketError() ' + err.message);
            that.last_socket_error = err;
        };
    }

    // Called when the socket is connected and ready to start sending/receiving data.
    onSocketFullyConnected() {
        this.debugOut('socketFullyConnected()');
        this.last_socket_error = null;
        this.connected = true;
        this.emit('open');
    }

    onSocketClose(event) {
        const possible_protocol_error = !this.connected && event.code === 1006;
        if (possible_protocol_error && !this.protocol_fallback && this.protocol !== undefined) {
            // First connection attempt failed possibly due to mismatched protocol,
            //  retry the connection with undefined protocol
            // After this attempt, normal reconnect functions apply which will
            //  reconstruct this websocket, resetting these variables
            this.debugOut('socketClose() possible protocol error, retrying with no protocol');
            this.protocol_fallback = true;
            this.protocol = undefined;
            this.connect();
            return;
        }

        this.debugOut('socketClose()');
        this.connected = false;
        this.emit('close', this.last_socket_error ? this.last_socket_error : false);
    }

    onSocketMessage(data) {
        if (typeof data !== 'string') {
            this.last_socket_error = new Error('Websocket received unexpected binary data, closing the connection');
            this.debugOut('socketData() ' + this.last_socket_error.message);
            this.close();
            return;
        }

        this.debugOut('socketData() ' + JSON.stringify(data));

        const that = this;
        let lines = null;

        this.incoming_buffer += data + '\n';

        lines = this.incoming_buffer.split('\n');
        if (lines[lines.length - 1] !== '') {
            this.incoming_buffer = lines.pop();
        } else {
            lines.pop();
            this.incoming_buffer = '';
        }

        lines.forEach(function(line) {
            that.emit('line', line);
        });
    }

    disposeSocket() {
        this.debugOut('Connection.disposeSocket() connected=' + this.connected);

        if (this.socket && this.connected) {
            this.socket.close();
        }

        if (this.socket) {
            this.socket.onopen = null;
            this.socket.onclose = null;
            this.socket.onmessage = null;
            this.socket.onerror = null;
            this.socket = null;
        }
    }

    close() {
        if (this.socket && this.connected) {
            this.socket.close();
        }
    }

    setEncoding(encoding) {
    }
};
<commit_msg>Websocket.send() does not support callbacks (#305)<commit_after>'use strict';

/**
 * Websocket transport
 */

const EventEmitter = require('eventemitter3');

module.exports = class Connection extends EventEmitter {
    constructor(options) {
        super();

        this.options = options || {};

        this.socket = null;
        this.connected = false;
        this.last_socket_error = null;

        this.encoding = 'utf8';
        this.incoming_buffer = '';

        this.protocol_fallback = false;
        this.protocol = options.websocket_protocol;
    }

    isConnected() {
        return this.connected;
    }

    writeLine(line, cb) {
        this.debugOut('writeLine() socket=' + (this.socket ? 'yes' : 'no') + ' connected=' + this.connected);

        if (this.socket && this.connected) {
            this.socket.send(line);
        }

        // Websocket.send() does not support callbacks
        // call the callback in the next tick instead
        if (cb) {
            setTimeout(cb, 0);
        }
    }

    debugOut(out) {
        this.emit('debug', out);
    }

    connect() {
        const that = this;
        const options = this.options;
        let socket = null;
        let ws_addr = '';

        this.debugOut('Connection.connect()');

        this.disposeSocket();
        this.requested_disconnect = false;

        // Build the websocket address. eg. ws://ws.rizon.net:8080
        ws_addr += (options.tls || options.ssl) ? 'wss://' : 'ws://';
        ws_addr += options.host;
        ws_addr += options.port ? ':' + options.port : '';
        ws_addr += options.path ? options.path : '';

        socket = this.socket = new WebSocket(ws_addr, this.protocol);

        socket.onopen = function() {
            that.onSocketFullyConnected();
        };
        socket.onclose = function(event) {
            that.onSocketClose(event);
        };
        socket.onmessage = function(event) {
            that.onSocketMessage(event.data);
        };
        socket.onerror = function(err) {
            that.debugOut('socketError() ' + err.message);
            that.last_socket_error = err;
        };
    }

    // Called when the socket is connected and ready to start sending/receiving data.
    onSocketFullyConnected() {
        this.debugOut('socketFullyConnected()');
        this.last_socket_error = null;
        this.connected = true;
        this.emit('open');
    }

    onSocketClose(event) {
        const possible_protocol_error = !this.connected && event.code === 1006;
        if (possible_protocol_error && !this.protocol_fallback && this.protocol !== undefined) {
            // First connection attempt failed possibly due to mismatched protocol,
            //  retry the connection with undefined protocol
            // After this attempt, normal reconnect functions apply which will
            //  reconstruct this websocket, resetting these variables
            this.debugOut('socketClose() possible protocol error, retrying with no protocol');
            this.protocol_fallback = true;
            this.protocol = undefined;
            this.connect();
            return;
        }

        this.debugOut('socketClose()');
        this.connected = false;
        this.emit('close', this.last_socket_error ? this.last_socket_error : false);
    }

    onSocketMessage(data) {
        if (typeof data !== 'string') {
            this.last_socket_error = new Error('Websocket received unexpected binary data, closing the connection');
            this.debugOut('socketData() ' + this.last_socket_error.message);
            this.close();
            return;
        }

        this.debugOut('socketData() ' + JSON.stringify(data));

        const that = this;
        let lines = null;

        this.incoming_buffer += data + '\n';

        lines = this.incoming_buffer.split('\n');
        if (lines[lines.length - 1] !== '') {
            this.incoming_buffer = lines.pop();
        } else {
            lines.pop();
            this.incoming_buffer = '';
        }

        lines.forEach(function(line) {
            that.emit('line', line);
        });
    }

    disposeSocket() {
        this.debugOut('Connection.disposeSocket() connected=' + this.connected);

        if (this.socket && this.connected) {
            this.socket.close();
        }

        if (this.socket) {
            this.socket.onopen = null;
            this.socket.onclose = null;
            this.socket.onmessage = null;
            this.socket.onerror = null;
            this.socket = null;
        }
    }

    close() {
        if (this.socket && this.connected) {
            this.socket.close();
        }
    }

    setEncoding(encoding) {
    }
};
<|endoftext|>