<commit_before>(function(){
  'use strict';

  angular.module('cla.controllers')
    .controller('OutcomesModalCtl',
      ['$scope', 'case', 'event_key', 'outcome_codes', 'notes', 'tplVars', '$modalInstance', '$timeout', 'Feedback',
        function($scope, _case, event_key, outcome_codes, notes, tplVars, $modalInstance, $timeout, Feedback) {
          // template vars
          tplVars = angular.extend({
            'title': 'Outcome code'
          }, tplVars);
          tplVars.buttonText = tplVars.buttonText || tplVars.title;
          $scope.tplVars = tplVars;
          $scope.outcome_codes = outcome_codes;
          $scope.selected = {};
          $scope.selected.notes = notes || '';
          $scope.feedback_allowed = (event_key === 'reject_case');

          // focus on search field on open
          $modalInstance.opened.then(function () {
            $timeout(function () {
              angular.element('[name="outcome-modal-code-search"]').focus();
            }, 50);
          });

          // on save event
          var onSuccess = function () {
            $scope.$close(true);
          };
          var onFail = function (response) {
            $scope.errors = {};
            angular.forEach(response.data, function (errors, field) {
              if (Array.isArray(errors)) {
                $scope.errors[field] = errors.join(', ');
              } else {
                $scope.errors[field] = errors;
              }
            });
          };
          var saveEvent = function () {
            _case['$' + event_key]({
              'event_code': $scope.selected.outcome_code,
              'notes': $scope.selected.notes
            }).then(onSuccess, onFail);
          };

          $scope.submit = function(isValid) {
            if (isValid) {
              if ($scope.selected.issue) {
                var feedback_resource = new Feedback({
                  case: _case.reference,
                  issue: $scope.selected.issue,
                  comment: $scope.selected.notes
                });

                feedback_resource.$save(function () {
                  saveEvent();
                }, onFail);
              } else {
                saveEvent();
              }
            }
          };

          $scope.cancel = function () {
            $scope.$dismiss('cancel');
          };
        }
      ]
    );
})();
<commit_msg>Pass response back to modal success method<commit_after>(function(){
  'use strict';

  angular.module('cla.controllers')
    .controller('OutcomesModalCtl',
      ['$scope', 'case', 'event_key', 'outcome_codes', 'notes', 'tplVars', '$modalInstance', '$timeout', 'Feedback',
        function($scope, _case, event_key, outcome_codes, notes, tplVars, $modalInstance, $timeout, Feedback) {
          // template vars
          tplVars = angular.extend({
            'title': 'Outcome code'
          }, tplVars);
          tplVars.buttonText = tplVars.buttonText || tplVars.title;
          $scope.tplVars = tplVars;
          $scope.outcome_codes = outcome_codes;
          $scope.selected = {};
          $scope.selected.notes = notes || '';
          $scope.feedback_allowed = (event_key === 'reject_case');

          // focus on search field on open
          $modalInstance.opened.then(function () {
            $timeout(function () {
              angular.element('[name="outcome-modal-code-search"]').focus();
            }, 50);
          });

          // on save event
          var onSuccess = function (response) {
            // console.log(response);
            $scope.$close(response);
          };
          var onFail = function (response) {
            $scope.errors = {};
            angular.forEach(response.data, function (errors, field) {
              if (Array.isArray(errors)) {
                $scope.errors[field] = errors.join(', ');
              } else {
                $scope.errors[field] = errors;
              }
            });
          };
          var saveEvent = function () {
            _case['$' + event_key]({
              event_code: $scope.selected.outcome_code,
              notes: $scope.selected.notes
            }).then(onSuccess, onFail);
          };

          $scope.submit = function(isValid) {
            if (isValid) {
              if ($scope.selected.issue) {
                var feedback_resource = new Feedback({
                  case: _case.reference,
                  issue: $scope.selected.issue,
                  comment: $scope.selected.notes
                });

                feedback_resource.$save(function () {
                  saveEvent();
                }, onFail);
              } else {
                saveEvent();
              }
            }
          };

          $scope.cancel = function () {
            $scope.$dismiss('cancel');
          };
        }
      ]
    );
})();
<|endoftext|>


<commit_before>var fs = require('fs');
var util = require('util');
var path = require('path');
var events = require('events');
var _ = require('lodash');

var engines = require('./util/engines');
var conflicter = require('./util/conflicter');
var actions = path.join(__dirname, 'actions');

// TOOD(mklabs): flesh out api, remove config (merge with options, or just remove the
// grunt config handling)

// The `Base` object provides the common API shared by all generators,
// defining options, arguments, hooks, file / prompt / log API etc.
//
// Evevy Generator should extend from this object.
//
// - args - A String or Array of arguments to init the generator with.
// - opts - A Hash of options to init the generator with.
var Base = module.exports = function Base(args, options) {
  events.EventEmitter.call(this);

  if (!Array.isArray(args)) {
    options = args;
    args = [];
  }

  this.args = this.arguments = args || [];
  this.options = options || {};

  // checks required paramaters
  if (!this.options.env) {
    throw new Error('You must provide the environment object. Use env#create() to create a new generator.');
  }

  if (!this.options.resolved) {
    throw new Error('You must provide the resolved path value. Use env#create() to create a new generator.');
  }

  this.env = this.options.env;
  this.resolved = this.options.resolved;
  this.fallbacks = this.options.generators || this.options.generator || {};
  this.generatorName = this.options.name || '';

  this.description = '';

  this.async = function () {
    return function () {};
  };

  _.defaults(this.options, this.fallbacks, {
    engine: engines.underscore
  });

  this._engine = this.options.engine;

  // cleanup options hash from default engine, if users didn't provided one.
  if (!options.engine) {
    delete this.options.engine;
  }

  this.conflicter = conflicter;
  this.conflicter.force = this.options.force;

  this._arguments = [];
  this._options = [];
  this._hooks = [];
  this._conflicts = [];
  this.appname = path.basename(process.cwd()).replace(/[^\w\s]+?/g, ' ');

  this.option('help', {
    alias: 'h',
    desc: 'Print generator\'s options and usage'
  });

  // ensure source / destination path, can be configured from subclasses
  this.sourceRoot(path.join(path.dirname(this.resolved), 'templates'));
};

util.inherits(Base, events.EventEmitter);

// "include" the actions modules
_.extend(Base.prototype, require('./actions/actions'));
_.extend(Base.prototype, require('./actions/fetch'));
_.extend(Base.prototype, require('./actions/file'));
_.extend(Base.prototype, require('./actions/install'));
_.extend(Base.prototype, require('./actions/string'));
_.extend(Base.prototype, require('./actions/wiring'));
Base.prototype.prompt = require('./actions/prompt');
Base.prototype.invoke = require('./actions/invoke');
Base.prototype.spawnCommand = require('./actions/spawn_command');

// Adds an option to the set of generator expected options, only used to
// generate generator usage. By default, generators get all the cli option
// parsed by nopt as a this.options Hash object.
//
// - name       - The name of the argument
// - options    - Hash of configuration values where:
//   - desc     - Description for the argument.
//   - type     - Type for this argument, either Boolean, String or Number.
//   - default  - Default value for this argument.
//   - banner   - String to show on usage notes.
//   - hide     - If you want to hide this option from the help.
//
Base.prototype.option = function option(name, config) {
  config = config || {};
  _.defaults(config, {
    name: name,
    desc: 'Description for ' + name,
    type: Boolean,
    defaults: false,
    hide: false
  });

  var opt = this._options.filter(function (el) {
    return el.name === name;
  })[0];

  if (!opt) {
    this._options.push(config);
  } else {
    opt = config;
  }

  if (!this.options[name]) {
    this.options[name] = config.defaults;
  }

  return this;
};

// Adds an argument to the class and creates an attribute getter for it.
//
// Arguments are different from options in several aspects. The first one
// is how they are parsed from the command line, arguments are retrieved
// from position.
//
// Examples
//
//    yeoman generate NAME
//    # Instead of:
//    yeoman generate --name NAME
//
// Besides, arguments are used inside your code as a property (this.argument),
// while options are all kept in a hash (this.options).
//
// - name         - The argument String name to use
// - config       - The Hash of congiguration values
//    - desc      - Description for the argument.
//    - required  - If the argument is required or not.
//    - optional  - If the argument is optional or not.
//    - type      - The type of the argument, can be String, Number,
//                  Array, Object (in which case considered as an Hash
//                  object, key:value).
//    - defaults  - Default value for this argument. It cannot be required
//                  and have default values.
//    - banner    - String to show on usage notes.
//
// Returns the generator instance
Base.prototype.argument = function argument(name, config) {
  config = config || {};
  _.defaults(config, {
    name: name,
    required: config.defaults == null ? true : false,
    type: String
  });

  config.banner = config.banner || this.bannerFor(config);

  this._arguments.push({
    name: name,
    config: config
  });

  var position = -1;
  this._arguments.forEach(function (arg, i) {
    if (position !== -1) {
      return;
    }

    if (arg.name === name) {
      position = i;
    }
  });

  // a bit of coercion and type handling, to be improved (just dealing
  // with Array / String, default is assumed to be String.)

  var value = config.type === Array ? this.args.slice(position) : this.args[position];
  value = position >= this.args.length ? config.defaults : value;

  if (config.required && value === undefined) {
    return this.emit('error', new Error('Did not provide required argument ' + name.bold + '!'));
  }

  this[name] = value;
  return this;
};

// Runs the generator, executing top-level methods in the order they
// were defined.
//
// Special named method like `constructor` and `initialize` are skipped
// (CoffeeScript, Backbone like inheritence), or any method prefixed by
// a `_`.
//
// You can also supply the arguments for the method to be invoked, if
// none is given, the same values used to initialize the invoker are
// used to initialize the invoked.
//
// - args - The Array of arguments to invoke the generator with
//          (defaults: `this.args`)
// - cb   - The callback Function to invoke on completion.
//          (defaults: noop)
//
// Returns the generator instance.
Base.prototype.run = function run(args, cb) {
  if (!cb) {
    cb = args;
    args = this.args;
  }

  cb = cb || function () {};

  var self = this;
  this._running = true;
  this.emit('start');
  this.emit('run');

  var methods = Object.keys(Object.getPrototypeOf(this));
  // As the end of the methods list processing has a signification and trigger a dedicated
  // process (runHooks), and as Array.shift will always return undefined whatever the number
  // of time we call it, we need to have a marker for the end of the list (this will help
  // us to perform test in a synchronous way -- i.e. without prompting user)
  methods.push(-1);

  var waiter = 0;
  (function next(method) {
    if (!method) {
      return;
    }

    if (method === -1) {
      return self.runHooks(cb);
    }

    if (method.charAt(0) === '_') {
      return next(methods.shift());
    }

    if (/^(constructor|initialize)$/.test(method)) {
      return next(methods.shift());
    }

    // very very basic async management, could be done better using event and
    // EventEmitter ability of Generators.

    self.async = function async() {
      waiter++;
      return function (err) {
        waiter--;
        if (err) {
          self.emit('error', err);
        }

        if (waiter) {
          return;
        }

        conflicter.resolve(function (err) {
          if (err) {
            return self.emit('error', err);
          }

          next(methods.shift());
        });
      };
    };

    self.emit(method);
    self.emit('method', method);

    self[method].apply(self, args);

    // async was called, assume asynchronous behaviour, and wait for completion
    if (waiter) {
      return;
    }

    conflicter.resolve(function (err) {
      if (err) {
        return self.emit('error', err);
      }
      next(methods.shift());
    });

  }(methods.shift()));

  return this;
};

// Goes through all registered hooks, invoking them in series.
//
// - cb - Function to be called on completion
//
// Returns the generator instance.
Base.prototype.runHooks = function runHooks(cb) {
  var self = this;
  var hooks = this._hooks;

  (function next(hook) {
    if (!hook) {
      process.nextTick(function () {
        self.emit('end');
        cb();
      });
      return;
    }

    var resolved = self.defaultFor(hook.name);
    var options = hook.options || self.options;
    var context = hook.as || self.resolved || self.generateName;
    options.args = hook.args || self.args;

    self.invoke(resolved + (context ? ':' + context : ''), options, function (err) {
      if (err) {
        return cb(err);
      }

      next(hooks.shift());
    });

  }(hooks.shift()));

  return this;
};

// Registers a hook to invoke when this generator runs.
//
// A generator with a namespace based on the value supplied by the user
// to the given option named "name".
//
// Example
//
//    // with `--test-framework jasmine` from CLI
//    this.hookFor('test-framework');
//    // => registers the `jasmine` hook
//
// An option is created when this method is invoked and you can set a
// hash to customize it.
//
// Must be called prior to the generator run (shouldn't be called within
// a generator "step" - top-level methods)
//
// - name       - The hook value to look for
// - config     - The Hash of configuration options
//    - as      - The context value to use when runing the hooked
//                generator (defaults: the invoker generator name)
//    - args    - The array of positional arguments to init and run the
//                generator with.
//    - options - The hash of options to use to init and run the
//                generator with.
//
// Returns the generator instance.
Base.prototype.hookFor = function hookFor(name, config) {
  config = config || {};

  // enforce use of hookFor during instantiation
  if (this._running) {
    return this.emit('error', new Error(
      'hookFor must be used within the constructor only'
    ));
  }

  // add the corresponding option to this class, so that we output these hooks
  // in help
  this.option(name, {
    desc: this._.humanize(name) + ' to be invoked',
    defaults: this.options[name] || ''
  });

  this._hooks.push(_.defaults(config, {
    name: name
  }));

  return this;
};

// Return the default value for the option name.
//
// Also performs a lookup in CLI options and the `this.fallbacks`
// property.
//
// - name - The String name to look for.
//
// Returns the resolved value.
Base.prototype.defaultFor = function defaultFor(name) {
  var config = this.fallbacks;

  if (this.options[name]) {
    name = this.options[name];
  } else if (config && config[name]) {
    name = config[name];
  }

  return name;
};

// Generate the default banner for help output, adjusting output to
// argument type.
//
// - config   - A hash of options with the following properties:
//    - name  - The String value to display, uppercased (only relevant
//              with `String` type)
//    - type  - The argument type. This is the constructor Function (eg.
//              `String`, `Number`, `Object` or `Array`) used to init
//              the argument.
//
// Returns the banner.
Base.prototype.bannerFor = function bannerFor(config) {
  return config.type === Boolean ? '' :
    config.type === String ? config.name.toUpperCase() :
    config.type === Number ? 'N' :
    config.type === Object ? 'key:value' :
    config.type === Array ? 'one two three' :
    '';
};

// Tries to get the description from a USAGE file one folder above the
// source root otherwise uses a default description.
//
// Returns the usage output.
Base.prototype.help = function help() {
  var filepath = path.join(this.sourceRoot(), '../USAGE');
  var exists = fs.existsSync(filepath);

  var out = [
    'Usage:',
    '  ' + this.usage(),
    ''
  ];

  // build options
  if (this._options.length) {
    out = out.concat([
      'Options:',
      this.optionsHelp(),
      ''
    ]);
  }

  // append USAGE file is any
  if (exists) {
    out.push(fs.readFileSync(filepath, 'utf8'));
  }

  return out.join('\n');
};

// Output usage information for this given generator, depending on its arguments /
// options / hooks.
//
// Returns the usge output.
Base.prototype.usage = function usage() {
  var args = this._arguments.map(function (arg) {
    return arg.config.banner;
  }).join(' ');

  var options = this._options.length ? '[options]' : '',
    name = (this.namespace === 'yeoman:app' || !this.namespace) ? '' : this.namespace + ' ',
    cmd = 'init';

  name = name.replace(/^yeoman:/, '');

  var out = 'yeoman ' + cmd + ' ' + name + args + ' ' + options;

  if (this.description) {
    out += '\n\n' + this.description;
  }

  return out;
};

// Simple setter for custom `description` to append on help output.
//
// Returns the generator instance.
Base.prototype.desc = function desc(description) {
  this.description = description || '';
  return this;
};

// Returns the list of options in formatted table.
Base.prototype.optionsHelp = function optionsHelp() {
  var options = this._options.filter(function (el) {
    return !el.hide;
  });

  var hookOpts = this._hooks.map(function (hook) {
    return hook.generator && hook.generator._options;
  }).reduce(function (a, b) {
    a = a.concat(b);
    return a;
  }, []).filter(function (opts) {
    return opts && opts.name !== 'help';
  });

  var rows = options.concat(hookOpts).map(function (o) {
    return [
      '',
      o.alias ? '-' + o.alias + ', ' : '',
      '--' + o.name,
      o.desc ? '# ' + o.desc : '',
      o.defaults == null ? '' : 'Default: ' + o.defaults
    ];
  });

  return this.log.table({
    rows: rows
  });
};
<commit_msg>async used in Base.run.<commit_after>var fs = require('fs');
var util = require('util');
var path = require('path');
var events = require('events');
var _ = require('lodash');
var async = require('async');

var engines = require('./util/engines');
var conflicter = require('./util/conflicter');
var actions = path.join(__dirname, 'actions');

// TOOD(mklabs): flesh out api, remove config (merge with options, or just remove the
// grunt config handling)

// The `Base` object provides the common API shared by all generators,
// defining options, arguments, hooks, file / prompt / log API etc.
//
// Evevy Generator should extend from this object.
//
// - args - A String or Array of arguments to init the generator with.
// - opts - A Hash of options to init the generator with.
var Base = module.exports = function Base(args, options) {
  events.EventEmitter.call(this);

  if (!Array.isArray(args)) {
    options = args;
    args = [];
  }

  this.args = this.arguments = args || [];
  this.options = options || {};

  // checks required paramaters
  if (!this.options.env) {
    throw new Error('You must provide the environment object. Use env#create() to create a new generator.');
  }

  if (!this.options.resolved) {
    throw new Error('You must provide the resolved path value. Use env#create() to create a new generator.');
  }

  this.env = this.options.env;
  this.resolved = this.options.resolved;
  this.fallbacks = this.options.generators || this.options.generator || {};
  this.generatorName = this.options.name || '';

  this.description = '';

  this.async = function () {
    return function () {};
  };

  _.defaults(this.options, this.fallbacks, {
    engine: engines.underscore
  });

  this._engine = this.options.engine;

  // cleanup options hash from default engine, if users didn't provided one.
  if (!options.engine) {
    delete this.options.engine;
  }

  this.conflicter = conflicter;
  this.conflicter.force = this.options.force;

  this._arguments = [];
  this._options = [];
  this._hooks = [];
  this._conflicts = [];
  this.appname = path.basename(process.cwd()).replace(/[^\w\s]+?/g, ' ');

  this.option('help', {
    alias: 'h',
    desc: 'Print generator\'s options and usage'
  });

  // ensure source / destination path, can be configured from subclasses
  this.sourceRoot(path.join(path.dirname(this.resolved), 'templates'));
};

util.inherits(Base, events.EventEmitter);

// "include" the actions modules
_.extend(Base.prototype, require('./actions/actions'));
_.extend(Base.prototype, require('./actions/fetch'));
_.extend(Base.prototype, require('./actions/file'));
_.extend(Base.prototype, require('./actions/install'));
_.extend(Base.prototype, require('./actions/string'));
_.extend(Base.prototype, require('./actions/wiring'));
Base.prototype.prompt = require('./actions/prompt');
Base.prototype.invoke = require('./actions/invoke');
Base.prototype.spawnCommand = require('./actions/spawn_command');

// Adds an option to the set of generator expected options, only used to
// generate generator usage. By default, generators get all the cli option
// parsed by nopt as a this.options Hash object.
//
// - name       - The name of the argument
// - options    - Hash of configuration values where:
//   - desc     - Description for the argument.
//   - type     - Type for this argument, either Boolean, String or Number.
//   - default  - Default value for this argument.
//   - banner   - String to show on usage notes.
//   - hide     - If you want to hide this option from the help.
//
Base.prototype.option = function option(name, config) {
  config = config || {};
  _.defaults(config, {
    name: name,
    desc: 'Description for ' + name,
    type: Boolean,
    defaults: false,
    hide: false
  });

  var opt = this._options.filter(function (el) {
    return el.name === name;
  })[0];

  if (!opt) {
    this._options.push(config);
  } else {
    opt = config;
  }

  if (!this.options[name]) {
    this.options[name] = config.defaults;
  }

  return this;
};

// Adds an argument to the class and creates an attribute getter for it.
//
// Arguments are different from options in several aspects. The first one
// is how they are parsed from the command line, arguments are retrieved
// from position.
//
// Examples
//
//    yeoman generate NAME
//    # Instead of:
//    yeoman generate --name NAME
//
// Besides, arguments are used inside your code as a property (this.argument),
// while options are all kept in a hash (this.options).
//
// - name         - The argument String name to use
// - config       - The Hash of congiguration values
//    - desc      - Description for the argument.
//    - required  - If the argument is required or not.
//    - optional  - If the argument is optional or not.
//    - type      - The type of the argument, can be String, Number,
//                  Array, Object (in which case considered as an Hash
//                  object, key:value).
//    - defaults  - Default value for this argument. It cannot be required
//                  and have default values.
//    - banner    - String to show on usage notes.
//
// Returns the generator instance
Base.prototype.argument = function argument(name, config) {
  config = config || {};
  _.defaults(config, {
    name: name,
    required: config.defaults == null ? true : false,
    type: String
  });

  config.banner = config.banner || this.bannerFor(config);

  this._arguments.push({
    name: name,
    config: config
  });

  var position = -1;
  this._arguments.forEach(function (arg, i) {
    if (position !== -1) {
      return;
    }

    if (arg.name === name) {
      position = i;
    }
  });

  // a bit of coercion and type handling, to be improved (just dealing
  // with Array / String, default is assumed to be String.)

  var value = config.type === Array ? this.args.slice(position) : this.args[position];
  value = position >= this.args.length ? config.defaults : value;

  if (config.required && value === undefined) {
    return this.emit('error', new Error('Did not provide required argument ' + name.bold + '!'));
  }

  this[name] = value;
  return this;
};

// Runs the generator, executing top-level methods in the order they
// were defined.
//
// Special named method like `constructor` and `initialize` are skipped
// (CoffeeScript, Backbone like inheritence), or any method prefixed by
// a `_`.
//
// You can also supply the arguments for the method to be invoked, if
// none is given, the same values used to initialize the invoker are
// used to initialize the invoked.
//
// - args - The Array of arguments to invoke the generator with
//          (defaults: `this.args`)
// - cb   - The callback Function to invoke on completion.
//          (defaults: noop)
//
// Returns the generator instance.
Base.prototype.run = function run(args, cb) {
  var self = this;
  this._running = true;
  this.emit('start');
  this.emit('run');

  if (!cb) {
    cb = args;
    args = this.args;
  }

  cb = cb || function () {};

  var runHooks = function () {
    self.runHooks(cb);
  };

  var methods = Object.keys(Object.getPrototypeOf(this));

  var resolve = function (method) {
    var rules = {
      underscore: method.charAt(0) !== '_',
      initialize: !/^(constructor|initialize)$/.test(method),
      isValid: function () {
        return this.underscore && this.initialize;
      }
    };

    return function (next) {
      if (!rules.isValid(method)) {
        return next();
      }

      self.async = function () {
        self.async.running = true;
        return next;
      };

      self.emit(method);
      self.emit('method', method);
      self[method].apply(self, args);

      conflicter.resolve(function (err) {
        if (err) {
          return self.emit('error', err);
        }
      });

      if (!self.async.running) {
        next();
      }
    };
  };

  async.series(methods.map(resolve), runHooks);

  return this;
};

// Goes through all registered hooks, invoking them in series.
//
// - cb - Function to be called on completion
//
// Returns the generator instance.
Base.prototype.runHooks = function runHooks(cb) {
  var self = this;
  var hooks = this._hooks;

  (function next(hook) {
    if (!hook) {
      process.nextTick(function () {
        self.emit('end');
        cb();
      });
      return;
    }

    var resolved = self.defaultFor(hook.name);
    var options = hook.options || self.options;
    var context = hook.as || self.resolved || self.generateName;
    options.args = hook.args || self.args;

    self.invoke(resolved + (context ? ':' + context : ''), options, function (err) {
      if (err) {
        return cb(err);
      }

      next(hooks.shift());
    });

  }(hooks.shift()));

  return this;
};

// Registers a hook to invoke when this generator runs.
//
// A generator with a namespace based on the value supplied by the user
// to the given option named "name".
//
// Example
//
//    // with `--test-framework jasmine` from CLI
//    this.hookFor('test-framework');
//    // => registers the `jasmine` hook
//
// An option is created when this method is invoked and you can set a
// hash to customize it.
//
// Must be called prior to the generator run (shouldn't be called within
// a generator "step" - top-level methods)
//
// - name       - The hook value to look for
// - config     - The Hash of configuration options
//    - as      - The context value to use when runing the hooked
//                generator (defaults: the invoker generator name)
//    - args    - The array of positional arguments to init and run the
//                generator with.
//    - options - The hash of options to use to init and run the
//                generator with.
//
// Returns the generator instance.
Base.prototype.hookFor = function hookFor(name, config) {
  config = config || {};

  // enforce use of hookFor during instantiation
  if (this._running) {
    return this.emit('error', new Error(
      'hookFor must be used within the constructor only'
    ));
  }

  // add the corresponding option to this class, so that we output these hooks
  // in help
  this.option(name, {
    desc: this._.humanize(name) + ' to be invoked',
    defaults: this.options[name] || ''
  });

  this._hooks.push(_.defaults(config, {
    name: name
  }));

  return this;
};

// Return the default value for the option name.
//
// Also performs a lookup in CLI options and the `this.fallbacks`
// property.
//
// - name - The String name to look for.
//
// Returns the resolved value.
Base.prototype.defaultFor = function defaultFor(name) {
  var config = this.fallbacks;

  if (this.options[name]) {
    name = this.options[name];
  } else if (config && config[name]) {
    name = config[name];
  }

  return name;
};

// Generate the default banner for help output, adjusting output to
// argument type.
//
// - config   - A hash of options with the following properties:
//    - name  - The String value to display, uppercased (only relevant
//              with `String` type)
//    - type  - The argument type. This is the constructor Function (eg.
//              `String`, `Number`, `Object` or `Array`) used to init
//              the argument.
//
// Returns the banner.
Base.prototype.bannerFor = function bannerFor(config) {
  return config.type === Boolean ? '' :
    config.type === String ? config.name.toUpperCase() :
    config.type === Number ? 'N' :
    config.type === Object ? 'key:value' :
    config.type === Array ? 'one two three' :
    '';
};

// Tries to get the description from a USAGE file one folder above the
// source root otherwise uses a default description.
//
// Returns the usage output.
Base.prototype.help = function help() {
  var filepath = path.join(this.sourceRoot(), '../USAGE');
  var exists = fs.existsSync(filepath);

  var out = [
    'Usage:',
    '  ' + this.usage(),
    ''
  ];

  // build options
  if (this._options.length) {
    out = out.concat([
      'Options:',
      this.optionsHelp(),
      ''
    ]);
  }

  // append USAGE file is any
  if (exists) {
    out.push(fs.readFileSync(filepath, 'utf8'));
  }

  return out.join('\n');
};

// Output usage information for this given generator, depending on its arguments /
// options / hooks.
//
// Returns the usge output.
Base.prototype.usage = function usage() {
  var args = this._arguments.map(function (arg) {
    return arg.config.banner;
  }).join(' ');

  var options = this._options.length ? '[options]' : '',
    name = (this.namespace === 'yeoman:app' || !this.namespace) ? '' : this.namespace + ' ',
    cmd = 'init';

  name = name.replace(/^yeoman:/, '');

  var out = 'yeoman ' + cmd + ' ' + name + args + ' ' + options;

  if (this.description) {
    out += '\n\n' + this.description;
  }

  return out;
};

// Simple setter for custom `description` to append on help output.
//
// Returns the generator instance.
Base.prototype.desc = function desc(description) {
  this.description = description || '';
  return this;
};

// Returns the list of options in formatted table.
Base.prototype.optionsHelp = function optionsHelp() {
  var options = this._options.filter(function (el) {
    return !el.hide;
  });

  var hookOpts = this._hooks.map(function (hook) {
    return hook.generator && hook.generator._options;
  }).reduce(function (a, b) {
    a = a.concat(b);
    return a;
  }, []).filter(function (opts) {
    return opts && opts.name !== 'help';
  });

  var rows = options.concat(hookOpts).map(function (o) {
    return [
      '',
      o.alias ? '-' + o.alias + ', ' : '',
      '--' + o.name,
      o.desc ? '# ' + o.desc : '',
      o.defaults == null ? '' : 'Default: ' + o.defaults
    ];
  });

  return this.log.table({
    rows: rows
  });
};
<|endoftext|>


<commit_before>
var gett = function(url){
    console.log('invoking ' + url);
    return $.getJSON(url, function (data) {
        console.log('URL: ' + url + '; SUCCESS: ' + JSON.stringify(data));
        data.filippo = 12;
        return data;
    })
    .fail(function(error){console.log('FAIL: ' + error)});
}

var getUrlFromData = function(v){
  var url = v.data.url;
  console.log('invoking ' + url);
  $.ajax({
    url: url,
    dataType: 'json',
    type: 'GET',
    cache: true,
    async: false,
    contentType: 'application/json',
    success: function (data) {
      console.log('URL: ' + url + '; SUCCESS: ' + data);
      jsonResult = data;
    },
    error: function(error){console.log('ERR: ' + error)}
  })
  return ajax({ acc: v.acc + ' --> ' + url, data: jsonResult });
}

var ajax = MONAD()
  .lift('getUrl',getUrlFromData)
  // monad.value will be a plain value
  .lift_value('value', function (s) {
      return s;
  });

var get = function(url){
  return function(v){
    var jsonResult = null;
    console.log('invoking ' + url);
    $.ajax({
      url: url,
      dataType: 'json',
      type: 'GET',
      cache: true,
      async: false,
      contentType: 'application/json',
      success: function (data) {
        console.log('URL: ' + url + '; SUCCESS: ' + data);
        jsonResult = data;
      },
      error: function(error){console.log('ERR: ' + error)}
    })
    return ajax({ acc: v.acc + ' --> ' + url, data: jsonResult });
  }
}

var getUrlFromChain = function(){
  return function(v){
    var url = v.data.url;
    console.log('invoking ' + url);
    $.ajax({
      url: url,
      dataType: 'json',
      type: 'GET',
      cache: true,
      async: false,
      contentType: 'application/json',
      success: function (data) {
        console.log('URL: ' + url + '; SUCCESS: ' + data);
        jsonResult = data;
      },
      error: function(error){console.log('ERR: ' + error)}
    })
    return ajax({ acc: v.acc + ' --> ' + url, data: jsonResult });
  }
}

$(document).ready(function(){

  var result0 = ajax({ acc: 'START', data: {}});

  var result1 = result0
    .bind(get('remote/first.json'));

  var result2 = result1
    .bind(getUrlFromChain());

  var result10 = ajax({ acc: 'START', data: {}})
    .bind(get('remote/first.json'))
    .getUrl() // gets second.json
    .getUrl() // gets third.json
  ;

//debugger;
  alert(result10.value().acc);

/*
$.ajax({
      url: 'remote/first.json',
      dataType: 'json',
      type: 'GET',
      cache: true,
      contentType: 'application/json',
      success: function (data, textStatus) {
        console.log("RECV: " + data);
        debugger;
        return ajax({ acc: v.acc + ' --> ' + url, data: data });
      },
      error: function(error){console.log('ERR: ' + error)}
    })
*/

/* this bugger works
  var resultXXX = gett('remote/first.json')
                  .then(function(data){
                    console.log('data is now' + JSON.stringify(data));
                    gett(data.url)
                    .then(function(data){
                      console.log('data is now' + JSON.stringify(data));
                      gett(data.url)
                    })
                  });

*/
});<commit_msg>synch chain and async pyramid both working<commit_after>// ASYNC stuff
var gett = function(url){
  console.log('invoking ' + url);
  return $.getJSON(url, function (data) {
      console.log('URL: ' + url + '; SUCCESS: ' + JSON.stringify(data));
      data.filippo = 12;
      return data;
  })
  .fail(function(error){console.log('FAIL: ' + error)});
}

// SYNC stuff
var getUrlFromData = function(v){
  var url = v.data.url;
  console.log('invoking ' + url);
  $.ajax({
    url: url,
    dataType: 'json',
    type: 'GET',
    cache: true,
    async: false,
    contentType: 'application/json',
    success: function (data) {
      console.log('URL: ' + url + '; SUCCESS: ' + data);
      jsonResult = data;
    },
    error: function(error){console.log('ERR: ' + error)}
  })
  return ajax({ acc: v.acc + ' --> ' + url, data: jsonResult });
}

var ajax = MONAD()
  .lift('getUrl',getUrlFromData)
  // monad.value will be a plain value
  .lift_value('value', function (s) {
      return s;
  });

var get = function(url){
  return function(v){
    var jsonResult = null;
    console.log('invoking ' + url);
    $.ajax({
      url: url,
      dataType: 'json',
      type: 'GET',
      cache: true,
      async: false,
      contentType: 'application/json',
      success: function (data) {
        console.log('URL: ' + url + '; SUCCESS: ' + data);
        jsonResult = data;
      },
      error: function(error){console.log('ERR: ' + error)}
    })
    return ajax({ acc: v.acc + ' --> ' + url, data: jsonResult });
  }
}

var getUrlFromChain = function(){
  return function(v){
    var url = v.data.url;
    console.log('invoking ' + url);
    $.ajax({
      url: url,
      dataType: 'json',
      type: 'GET',
      cache: true,
      async: false,
      contentType: 'application/json',
      success: function (data) {
        console.log('URL: ' + url + '; SUCCESS: ' + data);
        jsonResult = data;
      },
      error: function(error){console.log('ERR: ' + error)}
    })
    return ajax({ acc: v.acc + ' --> ' + url, data: jsonResult });
  }
}

$(document).ready(function(){

  var result0 = ajax({ acc: 'START', data: {}});

  var result1 = result0
    .bind(get('remote/first.json'));

  var result2 = result1
    .bind(getUrlFromChain());

  var result10 = ajax({ acc: 'START', data: {}})
    .bind(get('remote/first.json'))
    .getUrl() // gets second.json
    .getUrl() // gets third.json
  ;
  alert(result10.value().acc);

  // promises --> callback hell
  var resultXXX = gett('remote/first.json')
    .then(function(data){
      console.log('data is now' + JSON.stringify(data));
      gett(data.url)
      .then(function(data){
        console.log('data is now' + JSON.stringify(data));
        gett(data.url)
        .then(function(data){alert(data.value)});
      })
    });
});

/*
$.ajax({
      url: 'remote/first.json',
      dataType: 'json',
      type: 'GET',
      cache: true,
      //async: false,
      contentType: 'application/json',
      success: function (data, textStatus) {
        console.log("RECV: " + data);
        debugger;
        return ajax({ acc: v.acc + ' --> ' + url, data: data });
      },
      error: function(error){console.log('ERR: ' + error)}
    })
*/
<|endoftext|>


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

// Copyright (C) 2014, Microsoft Corporation. All rights reserved.
// This code is governed by the BSD License found in the LICENSE file.

var args = require('minimist')(process.argv.slice(2), {
    alias: {
        consoleCommand: 'e',
        consolePrintCommand: 'p',
        runner: 'r',
        reporter: 'R',
        threads: 't',
        batch: 'b',
        config: 'c'
    }
});

var parser = require('test262-parser');
var tapify = require('../lib/tapify');
var simpleReporter = require('../lib/simpleReporter.js');
var _ = require('highland');
var glob = require('glob');
var fs = require('fs');
var path = require('path');
var jss = require('JSONStream').stringify();
var Tributary = require('stream-bifurcate')
var scenarios = require('../lib/scenarios');
var readFile = _.wrapCallback(fs.readFile);
var DEFAULT_BATCH_SIZE = 75;
var t262 = require('../index');

if(args.config) require(path.join(process.cwd(), args.config));
t262.useConfig(args);

var Runner = t262.loadRunner();

// apply defaults
if(t262.config.batch === true) t262.config.batch = DEFAULT_BATCH_SIZE;
if(!t262.config.threads) t262.config.threads = 4;
if(!t262.config.reporter) t262.config.reporter = 'simple';

var start = Date.now();

var files = _(t262.config._.map(globStream)).merge();
var contents = files.fork().map(readFile).sequence();
var tests = contents.zip(files.fork()).map(function(d) {
    return parser.parseFile({ contents: d[0].toString('utf8'), file: d[1]});
});
var getScenarios = scenarios(t262.config);
var scenarios = tests.flatMap(scenarioStream);
if(t262.config.batch) scenarios = _(scenarios).batch(t262.config.batch);

var trb = scenarios.pipe(new Tributary());
var results = _(function(push) {
    for(var i = 0; i < t262.config.threads; i++) push(null, run(trb.fork()));
    push(null, _.nil);
}).merge();

results.on('end', function() {
    console.log("Took " + ((Date.now() - start) / 1000) + " seconds");
})

if(t262.config.reporter === 'json') {
    results.pipe(jss).pipe(process.stdout);
} else if(t262.config.reporter === 'tap') {
    results.pipe(tapify).pipe(process.stdout);
} else if(t262.config.reporter === 'simple') {
    results.pipe(simpleReporter);
}

// takes a test collateral stream.
// Returns test results stream.
function run(tests) {
    var runner = new Runner(t262.config);

    var results = _(tests).map(function(test) {
        return _(function(push) {
            if(t262.config.batch) {
                runner.runBatch(test, function() {
                    test.forEach(function(t) {
                        push(null, t);
                    })
                    push(null, _.nil);
                });
            } else {
                runner.run(test, function() {
                    push(null, test);
                    push(null, _.nil);
                });
            }
        });
    }).sequence();

    results.on('end', function() {
        runner.end();
    });

    return results;
}

// takes a file path and returns a stream of filenames
// that match it
function globStream(p) {
    var mg = glob(p);
    var source = _('match', mg);
    mg.on('end', function() { source.end() })

    return source;
}

// takes a test and returns a stream of all the scenarios
function scenarioStream(test) {
    var iter = getScenarios(test);
    return _(function(push) {
        var rec = iter.next();
        while(!rec.done) {
            push(null, rec.value);
            rec = iter.next();
        }

        push(null, _.nil);
    })
}
<commit_msg>Only log duration with simple reporter<commit_after>#!/usr/bin/env node

// Copyright (C) 2014, Microsoft Corporation. All rights reserved.
// This code is governed by the BSD License found in the LICENSE file.

var args = require('minimist')(process.argv.slice(2), {
    alias: {
        consoleCommand: 'e',
        consolePrintCommand: 'p',
        runner: 'r',
        reporter: 'R',
        threads: 't',
        batch: 'b',
        config: 'c'
    }
});

var parser = require('test262-parser');
var tapify = require('../lib/tapify');
var simpleReporter = require('../lib/simpleReporter.js');
var _ = require('highland');
var glob = require('glob');
var fs = require('fs');
var path = require('path');
var jss = require('JSONStream').stringify();
var Tributary = require('stream-bifurcate')
var scenarios = require('../lib/scenarios');
var readFile = _.wrapCallback(fs.readFile);
var DEFAULT_BATCH_SIZE = 75;
var t262 = require('../index');

if(args.config) require(path.join(process.cwd(), args.config));
t262.useConfig(args);

var Runner = t262.loadRunner();

// apply defaults
if(t262.config.batch === true) t262.config.batch = DEFAULT_BATCH_SIZE;
if(!t262.config.threads) t262.config.threads = 4;
if(!t262.config.reporter) t262.config.reporter = 'simple';

var start = Date.now();

var files = _(t262.config._.map(globStream)).merge();
var contents = files.fork().map(readFile).sequence();
var tests = contents.zip(files.fork()).map(function(d) {
    return parser.parseFile({ contents: d[0].toString('utf8'), file: d[1]});
});
var getScenarios = scenarios(t262.config);
var scenarios = tests.flatMap(scenarioStream);
if(t262.config.batch) scenarios = _(scenarios).batch(t262.config.batch);

var trb = scenarios.pipe(new Tributary());
var results = _(function(push) {
    for(var i = 0; i < t262.config.threads; i++) push(null, run(trb.fork()));
    push(null, _.nil);
}).merge();

if(t262.config.reporter === 'json') {
    results.pipe(jss).pipe(process.stdout);
} else if(t262.config.reporter === 'tap') {
    results.pipe(tapify).pipe(process.stdout);
} else if(t262.config.reporter === 'simple') {
    results.pipe(simpleReporter);

    results.on('end', function() {
        console.log("Took " + ((Date.now() - start) / 1000) + " seconds");
    })
}

// takes a test collateral stream.
// Returns test results stream.
function run(tests) {
    var runner = new Runner(t262.config);

    var results = _(tests).map(function(test) {
        return _(function(push) {
            if(t262.config.batch) {
                runner.runBatch(test, function() {
                    test.forEach(function(t) {
                        push(null, t);
                    })
                    push(null, _.nil);
                });
            } else {
                runner.run(test, function() {
                    push(null, test);
                    push(null, _.nil);
                });
            }
        });
    }).sequence();

    results.on('end', function() {
        runner.end();
    });

    return results;
}

// takes a file path and returns a stream of filenames
// that match it
function globStream(p) {
    var mg = glob(p);
    var source = _('match', mg);
    mg.on('end', function() { source.end() })

    return source;
}

// takes a test and returns a stream of all the scenarios
function scenarioStream(test) {
    var iter = getScenarios(test);
    return _(function(push) {
        var rec = iter.next();
        while(!rec.done) {
            push(null, rec.value);
            rec = iter.next();
        }

        push(null, _.nil);
    })
}
<|endoftext|>


<commit_before>/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

let err = false;

const majorNodeVersion = parseInt(/^(\d+)\./.exec(process.versions.node)[1]);

if (majorNodeVersion < 10 || majorNodeVersion >= 17) {
	console.error('\033[1;31m*** Please use node.js versions >=10 and <=17.\033[0;0m');
	err = true;
}

const cp = require('child_process');
const yarnVersion = cp.execSync('yarn -v', { encoding: 'utf8' }).trim();
const parsedYarnVersion = /^(\d+)\.(\d+)\./.exec(yarnVersion);
const majorYarnVersion = parseInt(parsedYarnVersion[1]);
const minorYarnVersion = parseInt(parsedYarnVersion[2]);

if (majorYarnVersion < 1 || minorYarnVersion < 10) {
	console.error('\033[1;31m*** Please use yarn >=1.10.1.\033[0;0m');
	err = true;
}

if (!/yarn[\w-.]*\.js$|yarnpkg$/.test(process.env['npm_execpath'])) {
	console.error('\033[1;31m*** Please use yarn to install dependencies.\033[0;0m');
	err = true;
}

if (process.platform === 'win32') {
	if (!hasSupportedVisualStudioVersion()) {
		console.error('\033[1;31m*** Invalid C/C++ Compiler Toolchain. Please check https://github.com/microsoft/vscode/wiki/How-to-Contribute.\033[0;0m');
		err = true;
	}
}

if (err) {
	console.error('');
	process.exit(1);
}

function hasSupportedVisualStudioVersion() {
	const fs = require('fs');
	const path = require('path');
	// Translated over from
	// https://source.chromium.org/chromium/chromium/src/+/master:build/vs_toolchain.py;l=140-175
	const supportedVersions = ['2019', '2017'];

	const availableVersions = [];
	for (const version of supportedVersions) {
		let vsPath = process.env[`vs${version}_install`];
		if (vsPath && fs.existsSync(vsPath)) {
			availableVersions.push(version);
			break;
		}
		const programFiles86Path = process.env['ProgramFiles(x86)'];
		if (programFiles86Path) {
			vsPath = `${programFiles86Path}/Microsoft Visual Studio/${version}`;
			const vsTypes = ['Enterprise', 'Professional', 'Community', 'Preview', 'BuildTools'];
			if (vsTypes.some(vsType => fs.existsSync(path.join(vsPath, vsType)))) {
				availableVersions.push(version);
				break;
			}
		}
	}
	return availableVersions.length;
}
<commit_msg>update nodejs requirement, https://github.com/microsoft/vscode/issues/121144<commit_after>/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

let err = false;

const majorNodeVersion = parseInt(/^(\d+)\./.exec(process.versions.node)[1]);

if (majorNodeVersion < 14 || majorNodeVersion >= 17) {
	console.error('\033[1;31m*** Please use node.js versions >=14 and <=17.\033[0;0m');
	err = true;
}

const cp = require('child_process');
const yarnVersion = cp.execSync('yarn -v', { encoding: 'utf8' }).trim();
const parsedYarnVersion = /^(\d+)\.(\d+)\./.exec(yarnVersion);
const majorYarnVersion = parseInt(parsedYarnVersion[1]);
const minorYarnVersion = parseInt(parsedYarnVersion[2]);

if (majorYarnVersion < 1 || minorYarnVersion < 10) {
	console.error('\033[1;31m*** Please use yarn >=1.10.1.\033[0;0m');
	err = true;
}

if (!/yarn[\w-.]*\.js$|yarnpkg$/.test(process.env['npm_execpath'])) {
	console.error('\033[1;31m*** Please use yarn to install dependencies.\033[0;0m');
	err = true;
}

if (process.platform === 'win32') {
	if (!hasSupportedVisualStudioVersion()) {
		console.error('\033[1;31m*** Invalid C/C++ Compiler Toolchain. Please check https://github.com/microsoft/vscode/wiki/How-to-Contribute.\033[0;0m');
		err = true;
	}
}

if (err) {
	console.error('');
	process.exit(1);
}

function hasSupportedVisualStudioVersion() {
	const fs = require('fs');
	const path = require('path');
	// Translated over from
	// https://source.chromium.org/chromium/chromium/src/+/master:build/vs_toolchain.py;l=140-175
	const supportedVersions = ['2019', '2017'];

	const availableVersions = [];
	for (const version of supportedVersions) {
		let vsPath = process.env[`vs${version}_install`];
		if (vsPath && fs.existsSync(vsPath)) {
			availableVersions.push(version);
			break;
		}
		const programFiles86Path = process.env['ProgramFiles(x86)'];
		if (programFiles86Path) {
			vsPath = `${programFiles86Path}/Microsoft Visual Studio/${version}`;
			const vsTypes = ['Enterprise', 'Professional', 'Community', 'Preview', 'BuildTools'];
			if (vsTypes.some(vsType => fs.existsSync(path.join(vsPath, vsType)))) {
				availableVersions.push(version);
				break;
			}
		}
	}
	return availableVersions.length;
}
<|endoftext|>


<commit_before>/** The most common candidate for a section's super class.
 * This class should be extended by the section classes
 * which you define for single form which has just one group of fields.
 */

'use strict';

var memoize               = require('memoizee/plain')
  , validDb               = require('dbjs/valid-dbjs')
  , defineStringLine      = require('dbjs-ext/string/string-line')
  , defineFormSectionBase = require('./form-section-base');

module.exports = memoize(function (db) {
	var StringLine, FormSectionBase;
	validDb(db);
	StringLine      = defineStringLine(db);
	FormSectionBase = defineFormSectionBase(db);
	FormSectionBase.extend('FormSection', {
		// Only for internal usage
		resolvedPropertyNames: {
			type: StringLine,
			multiple: true,
			value: function (_observe) {
				var props, resolved, masterPrefix, propertyMaster = this.propertyMaster;
				props = [];
				if (propertyMaster !== this.master) {
					if (propertyMaster.master !== this.master) {
						throw new Error("Defined propertyMaster must share master with defined formSection");
					}
					masterPrefix = propertyMaster.__id__.slice(this.master.__id__.length + 1) + '/';
				} else {
					masterPrefix = '';
				}
				this.propertyNames.forEach(function (name) {
					resolved = propertyMaster.resolveSKeyPath(name, _observe);
					if (!resolved) {
						return;
					}
					if (!resolved.object.hasPropertyDefined(resolved.key)) {
						throw new Error('Could not find property: ' + name);
					}
					props.push(masterPrefix + name);
				}, this);

				return props;
			}
		},
		// Only for internal usage
		formApplicablePropertyNames: { type: StringLine, multiple: true, value: function (_observe) {
			var result = [], resolved;

			this.resolvedPropertyNames.forEach(function (name) {
				resolved = this.master.resolveSKeyPath(name, _observe);
				if (!resolved) {
					return;
				}
				if (_observe(resolved.object['_' +
						this.database.Object.getFormApplicablePropName(resolved.key)])
						!== false) {
					result.push(name);
				}
			}, this);

			return result;
		} },
		// Only for internal usage
		applicablePropertyNames: { type: StringLine, multiple: true, value: function (_observe) {
			var props, resolved;
			props = this.formApplicablePropertyNames.copy();
			props.forEach(function (name) {
				resolved = this.master.resolveSKeyPath(name, _observe);
				if (!resolved) {
					return;
				}
				if (_observe(resolved.object['_' +
						this.database.Object.getApplicablePropName(resolved.key)])
						=== false) {
					props.delete(name);
				}
			}, this);

			return props;
		} },
		status: { value: function (_observe) {
			var resolved, invalid = _observe(this.missingRequiredPropertyNames).size, total = 0;

			if (this.resolventProperty) {
				resolved = this.master.resolveSKeyPath(this.resolventProperty, _observe);
				if (!resolved) {
					return 0;
				}
				if (_observe(resolved.observable) !== _observe(this.resolventValue)) {
					return invalid === 0 ? 1 : 0;
				}
			}

			this.applicablePropertyNames.forEach(function (name) {
				resolved = this.master.resolveSKeyPath(name, _observe);

				if (!resolved) {
					++total;
					return;
				}

				if (this.isPropertyExcludedFromStatus(resolved, _observe)) return;

				++total;
			}, this);

			return total === 0 ? 1 : (total - invalid) / total;
		} },
		missingRequiredPropertyNames: {
			type: StringLine,
			multiple: true,
			value: function (_observe) {
				var resolved, isResolventExcluded, isOwn, db = this.database, File = db.File,
					NestedMap = db.NestedMap, result = [];

				if (this.resolventProperty) {
					resolved = this.master.resolveSKeyPath(this.resolventProperty, _observe);

					if (!resolved) return result;

					isResolventExcluded = this.isPropertyExcludedFromStatus(resolved, _observe);

					if (_observe(resolved.observable) !== _observe(this.resolventValue)) {
						if (isResolventExcluded) return result;

						if (resolved.descriptor.multiple) {
							if (_observe(resolved.observable).size) return result;
						} else {
							if (_observe(resolved.observable) != null) return result;
						}

						return [this.resolventProperty];
					}
				}

				this.applicablePropertyNames.forEach(function (name) {
					var value;
					resolved = this.master.resolveSKeyPath(name, _observe);

					if (!resolved) return;
					if (this.isPropertyExcludedFromStatus(resolved, _observe)) return;

					if (resolved.object && NestedMap && (resolved.key === 'map')
							&& (resolved.object instanceof NestedMap)) {
						if (!_observe(resolved.object.ordered._size)) result.push(name);

						return;
					}

					if (resolved.descriptor.requireOwn) {
						_observe(resolved.observable);

						if (resolved.descriptor.multiple) {
							isOwn = typeof resolved.descriptor._value_ !== 'function';
						} else {
							isOwn = resolved.descriptor._hasOwnValue_(resolved.object);
						}

						if (!isOwn) {
							result.push(name);
							return;
						}
					}

					if (resolved.descriptor.multiple && !_observe(resolved.observable).size) {
						result.push(name);
						return;
					}

					value = _observe(resolved.observable);

					if (value != null) {
						if (File && (value instanceof File)) {
							value = _observe(value._path);

							if (value == null) result.push(name);
						}
					} else {
						result.push(name);
					}
				}, this);

				return result;
			}
		},
		weight: { value: function (_observe) {
			var resolved, total = 0, isResolventExcluded;
			if (this.resolventProperty) {
				resolved = this.master.resolveSKeyPath(this.resolventProperty, _observe);
				if (!resolved) {
					return 0;
				}
				isResolventExcluded = this.isPropertyExcludedFromStatus(resolved, _observe);
				if (_observe(resolved.observable) !== _observe(this.resolventValue)) {
					return isResolventExcluded ? 0 : 1;
				}
				if (!isResolventExcluded) {
					++total;
				}
			}
			this.applicablePropertyNames.forEach(function (name) {
				resolved = this.master.resolveSKeyPath(name, _observe);
				if (!resolved) {
					++total;
					return;
				}
				if (this.isPropertyExcludedFromStatus(resolved, _observe)) {
					return;
				}
				++total;
			}, this);
			return total;
		} },
		// Used to set input options for form.
		// Note that in order to use it, you need to set every option separately i.e:
		// db.SomeFormClass.prototype.inputOptions.get('someProperty').set('disabled', true)
		inputOptions: {
			type: db.Object,
			nested: true
		},
		lastEditStamp: {
			value: function (_observe) {
				var res = 0, resolved, lastModified, propertiesToCheck;
				propertiesToCheck = this.resolvedPropertyNames.copy();
				if (this.resolventProperty) {
					propertiesToCheck.add(this.resolventProperty);
				}

				propertiesToCheck.forEach(function (name) {
					resolved = this.master.resolveSKeyPath(name, _observe);
					if (!resolved) {
						return;
					}
					lastModified = _observe(resolved.object['_' + resolved.key]._lastModified);
					if (lastModified > res) res = lastModified;
				}, this);

				return res;
			}
		},
		// The names of the model fields which should be handled by this section.
		// Remember to write full property paths relative to the section's master object.
		// value example: ["name", "lastName", "address/street"]
		propertyNames: { type: StringLine, multiple: true }
	});
	db.FormSection.prototype.inputOptions._descriptorPrototype_.nested = true;
	db.FormSection.prototype.inputOptions._descriptorPrototype_.type   = db.Object;

	return db.FormSection;
}, { normalizer: require('memoizee/normalizers/get-1')() });
<commit_msg>Issue #860. Simplified FormSection.status function.<commit_after>/** The most common candidate for a section's super class.
 * This class should be extended by the section classes
 * which you define for single form which has just one group of fields.
 */

'use strict';

var memoize               = require('memoizee/plain')
  , validDb               = require('dbjs/valid-dbjs')
  , defineStringLine      = require('dbjs-ext/string/string-line')
  , defineFormSectionBase = require('./form-section-base');

module.exports = memoize(function (db) {
	var StringLine, FormSectionBase;
	validDb(db);
	StringLine      = defineStringLine(db);
	FormSectionBase = defineFormSectionBase(db);
	FormSectionBase.extend('FormSection', {
		// Only for internal usage
		resolvedPropertyNames: {
			type: StringLine,
			multiple: true,
			value: function (_observe) {
				var props, resolved, masterPrefix, propertyMaster = this.propertyMaster;
				props = [];
				if (propertyMaster !== this.master) {
					if (propertyMaster.master !== this.master) {
						throw new Error("Defined propertyMaster must share master with defined formSection");
					}
					masterPrefix = propertyMaster.__id__.slice(this.master.__id__.length + 1) + '/';
				} else {
					masterPrefix = '';
				}
				this.propertyNames.forEach(function (name) {
					resolved = propertyMaster.resolveSKeyPath(name, _observe);
					if (!resolved) {
						return;
					}
					if (!resolved.object.hasPropertyDefined(resolved.key)) {
						throw new Error('Could not find property: ' + name);
					}
					props.push(masterPrefix + name);
				}, this);

				return props;
			}
		},
		// Only for internal usage
		formApplicablePropertyNames: { type: StringLine, multiple: true, value: function (_observe) {
			var result = [], resolved;

			this.resolvedPropertyNames.forEach(function (name) {
				resolved = this.master.resolveSKeyPath(name, _observe);
				if (!resolved) {
					return;
				}
				if (_observe(resolved.object['_' +
						this.database.Object.getFormApplicablePropName(resolved.key)])
						!== false) {
					result.push(name);
				}
			}, this);

			return result;
		} },
		// Only for internal usage
		applicablePropertyNames: { type: StringLine, multiple: true, value: function (_observe) {
			var props, resolved;
			props = this.formApplicablePropertyNames.copy();
			props.forEach(function (name) {
				resolved = this.master.resolveSKeyPath(name, _observe);
				if (!resolved) {
					return;
				}
				if (_observe(resolved.object['_' +
						this.database.Object.getApplicablePropName(resolved.key)])
						=== false) {
					props.delete(name);
				}
			}, this);

			return props;
		} },
		status: { value: function (_observe) {
			var resolved, invalid = _observe(this.missingRequiredPropertyNames).size, total = 0;

			if (!this.resolventStatus) return 0;

			this.applicablePropertyNames.forEach(function (name) {
				resolved = this.master.resolveSKeyPath(name, _observe);

				if (!resolved) {
					++total;
					return;
				}

				if (this.isPropertyExcludedFromStatus(resolved, _observe)) return;

				++total;
			}, this);

			return total === 0 ? 1 : (total - invalid) / total;
		} },
		missingRequiredPropertyNames: {
			type: StringLine,
			multiple: true,
			value: function (_observe) {
				var resolved, isResolventExcluded, isOwn, db = this.database, File = db.File,
					NestedMap = db.NestedMap, result = [];

				if (this.resolventProperty) {
					resolved = this.ensureResolvent(_observe);

					if (!resolved) return result;

					isResolventExcluded = this.isPropertyExcludedFromStatus(resolved, _observe);

					if (_observe(resolved.observable) !== _observe(this.resolventValue)) {
						if (isResolventExcluded) return result;

						if (resolved.descriptor.multiple) {
							if (_observe(resolved.observable).size) return result;
						} else {
							if (_observe(resolved.observable) != null) return result;
						}

						return [this.resolventProperty];
					}
				}

				this.applicablePropertyNames.forEach(function (name) {
					var value;
					resolved = this.master.resolveSKeyPath(name, _observe);

					if (!resolved) return;
					if (this.isPropertyExcludedFromStatus(resolved, _observe)) return;

					if (resolved.object && NestedMap && (resolved.key === 'map')
							&& (resolved.object instanceof NestedMap)) {
						if (!_observe(resolved.object.ordered._size)) result.push(name);

						return;
					}

					if (resolved.descriptor.requireOwn) {
						_observe(resolved.observable);

						if (resolved.descriptor.multiple) {
							isOwn = typeof resolved.descriptor._value_ !== 'function';
						} else {
							isOwn = resolved.descriptor._hasOwnValue_(resolved.object);
						}

						if (!isOwn) {
							result.push(name);
							return;
						}
					}

					if (resolved.descriptor.multiple && !_observe(resolved.observable).size) {
						result.push(name);
						return;
					}

					value = _observe(resolved.observable);

					if (value != null) {
						if (File && (value instanceof File)) {
							value = _observe(value._path);

							if (value == null) result.push(name);
						}
					} else {
						result.push(name);
					}
				}, this);

				return result;
			}
		},
		weight: { value: function (_observe) {
			var resolved, total = 0, isResolventExcluded;
			if (this.resolventProperty) {
				resolved = this.master.resolveSKeyPath(this.resolventProperty, _observe);
				if (!resolved) {
					return 0;
				}
				isResolventExcluded = this.isPropertyExcludedFromStatus(resolved, _observe);
				if (_observe(resolved.observable) !== _observe(this.resolventValue)) {
					return isResolventExcluded ? 0 : 1;
				}
				if (!isResolventExcluded) {
					++total;
				}
			}
			this.applicablePropertyNames.forEach(function (name) {
				resolved = this.master.resolveSKeyPath(name, _observe);
				if (!resolved) {
					++total;
					return;
				}
				if (this.isPropertyExcludedFromStatus(resolved, _observe)) {
					return;
				}
				++total;
			}, this);
			return total;
		} },
		// Used to set input options for form.
		// Note that in order to use it, you need to set every option separately i.e:
		// db.SomeFormClass.prototype.inputOptions.get('someProperty').set('disabled', true)
		inputOptions: {
			type: db.Object,
			nested: true
		},
		lastEditStamp: {
			value: function (_observe) {
				var res = 0, resolved, lastModified, propertiesToCheck;
				propertiesToCheck = this.resolvedPropertyNames.copy();
				if (this.resolventProperty) {
					propertiesToCheck.add(this.resolventProperty);
				}

				propertiesToCheck.forEach(function (name) {
					resolved = this.master.resolveSKeyPath(name, _observe);
					if (!resolved) {
						return;
					}
					lastModified = _observe(resolved.object['_' + resolved.key]._lastModified);
					if (lastModified > res) res = lastModified;
				}, this);

				return res;
			}
		},
		// The names of the model fields which should be handled by this section.
		// Remember to write full property paths relative to the section's master object.
		// value example: ["name", "lastName", "address/street"]
		propertyNames: { type: StringLine, multiple: true }
	});
	db.FormSection.prototype.inputOptions._descriptorPrototype_.nested = true;
	db.FormSection.prototype.inputOptions._descriptorPrototype_.type   = db.Object;

	return db.FormSection;
}, { normalizer: require('memoizee/normalizers/get-1')() });
<|endoftext|>


<commit_before>$("#main-menu").hide();
$("#skins-panel").hide();
$("#quick-menu").hide();
$("#exp-bar").hide();
$("#menu-footer").after('
'+
	'
'+ //margin-left: 10px"
	'

'+
    '
Your browser does not support iframes.
'+
	''	+
											'

'+
											    '<button id= "Backtomenu" onclick="closecustomskinsIframe(); return false" style="margin-left: 10px;" class="btn btn-danger"  data-original-title="" title="">CLOSE</button>'+
												'<button id= "SendAFileform" onclick="SendAFileform(); return false" style="margin-left: 10px;" class="btn btn-success"  data-original-title="" title="">SEND CODE TO DEVELOPERS</button>
');

function closecustomskinsIframe(){
$("#main-menu").show();
$("#skins-panel").show();
$("#quick-menu").show();
$("#exp-bar").show();
$("#legendformIframe").remove();
}
function SendAFileform(){

window.open('https://docs.google.com/forms/d/e/1FAIpQLSckM3CTsmly0Ugw_kLQuiXS5AoSzwTfc5sj1czmo4bbzrDdBA/viewform');
}
<commit_msg>Update fzogarOgarIframe.js<commit_after>$("#main-menu").hide();
$("#skins-panel").hide();
$("#quick-menu").hide();
$("#exp-bar").hide();
$("#menu-footer").after('
'+
	'
'+ //margin-left: 10px"
	'

'+
    '
Your browser does not support iframes.
'+
	''	+
											'

'+
											    '<button id= "Backtomenu" onclick="closecustomskinsIframe(); return false" style="margin-left: 10px;" class="btn btn-danger"  data-original-title="" title="">CLOSE</button>'+
												'<button id= "SendAFileform" onclick="SendAFileform(); return false" style="margin-left: 10px;" class="btn btn-success"  data-original-title="" title="">SEND CODE TO DEVELOPERS</button>
');

function closecustomskinsIframe(){
$("#main-menu").show();
$("#skins-panel").show();
$("#quick-menu").show();
$("#exp-bar").show();
$("#legendformIframe").remove();
}
function SendAFileform(){

window.open('https://docs.google.com/forms/d/e/1FAIpQLSckM3CTsmly0Ugw_kLQuiXS5AoSzwTfc5sj1czmo4bbzrDdBA/viewform');
}
<|endoftext|>


<commit_before>'use strict';

var utils = require('./e2e-tools');
var request = require('supertest');
var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
var expect = chai.expect;
var promise = protractor.promise;

describe('test duplication of reports with different settings', function() {
  before(utils.initDb);
  after(utils.disconnectDropDb);

  beforeEach(utils.resetDb);
  beforeEach(utils.initAdmin.bind({}, 'asdfasdf'));
  afterEach(utils.resetBrowser);
  var reqParams = {
  from: '9845098450',
  fulltext: 'lorem ipsum dolor',
  date: '2016-09-01',
  keyword: 'test'
  };

  it('should add SMS Ghana source with keyword: test', function(done) {
    utils.addSource('SMS GH', { nickname: 'hello', keywords: 'test' });
    done();
  });
  it('should listen with fetching:on and source:enabled', function(done) {
    utils.addSource('SMS GH', { nickname: 'hello', keywords: 'test' });
    utils.toggleFetching('On');
    utils.toggleSource('SMS GH', 'On');
    request('http://localhost:1111')
      .get('/smsghana')
      .query(reqParams)
      .expect(200)
      .end(function(err, res) {
        if (err) {
          return done(err);
        }
      });
    browser.get(browser.baseUrl + 'reports');
    done();
  });
/*
  it('should not listen with fetching:on and source:disabled', function() {
    utils.addSource('SMS GH', { nickname: 'hello', keywords: 'test' });
  });
  it('should not listen with fetching:off and source:disabled', function() {
    utils.addSource('SMS GH', { nickname: 'hello', keywords: 'test' });
  });
  it('should not listening wtih fetching:off and source:enabled', function() {
    utils.addSource('SMS GH', { nickname: 'hello', keywords: 'test' });
  });
*/
});
<commit_msg>Semi-complete tests: need to check correct generation of reports<commit_after>'use strict';

var utils = require('./e2e-tools');
var request = require('supertest');
var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
var expect = chai.expect;
// var promise = protractor.promise;

describe('test duplication of reports with different settings', function() {
  before(utils.initDb);
  after(utils.disconnectDropDb);

  beforeEach(utils.resetDb);
  beforeEach(utils.initAdmin.bind({}, 'asdfasdf'));
  afterEach(utils.resetBrowser);
  var reqParams = {
  from: '9845098450',
  fulltext: 'lorem ipsum dolor',
  date: '2016-09-01',
  keyword: 'test'
  };

/*
  it('should add SMS Ghana source with keyword: test', function(done) {
    utils.addSource('SMS GH', { nickname: 'hello', keywords: 'test' });
    utils.toggleSource('SMS GH', 'Off');
    done();
  });
*/
  it('should listen with fetching:on and source:enabled', function(done) {
    utils.addSource('SMS GH', { nickname: 'hello', keywords: 'test' });
    utils.toggleFetching('On');
    utils.toggleSource('SMS GH', 'On');
    // Sleep before this is sent.
    request('http://localhost:1111')
      .get('/smsghana')
      .query(reqParams)
      .expect(200)
      .end(function(err, res) {
        if (err) {
          return done(err);
        }
      });
    browser.get(browser.baseUrl + 'reports');
    // Check if there is only one. If not, throw error.
    utils.toggleSource('SMS GH', 'Off');
    utils.toggleFetching('Off');
    done();
  });

  it('should not listen with fetching:on and source:disabled', function(done) {
    utils.addSource('SMS GH', { nickname: 'hello', keywords: 'test' });
    utils.toggleFetching('On');
    utils.toggleSource('SMS GH', 'Off');
    // Sleep before this is sent.
    request('http://localhost:1111')
      .get('/smsghana')
      .query(reqParams)
      .expect(200)
      .end(function(err, res) {
        if (err) {
          return done(err);
        }
      });
    browser.get(browser.baseUrl + 'reports');
    // Check if there is any report. If there is, throw error.
    utils.toggleFetching('Off');
    done();
  });

  it('should not listening wtih fetching:off and source:enabled', function(done) {
    utils.addSource('SMS GH', { nickname: 'hello', keywords: 'test' });
    utils.toggleFetching('Off');
    utils.toggleSource('SMS GH', 'On');
    // Sleep before this is sent.
    request('http://localhost:1111')
      .get('/smsghana')
      .query(reqParams)
      .expect(200)
      .end(function(err, res) {
        if (err) {
          return done(err);
        }
      });
    browser.get(browser.baseUrl + 'reports');
    // Check if there is any report. If there is, throw error.
    utils.toggleSource('SMS GH', 'Off');
    done();
  });

  it('should not listen with fetching:off and source:disabled', function(done) {
    utils.addSource('SMS GH', { nickname: 'hello', keywords: 'test' });
    utils.toggleFetching('Off');
    utils.toggleSource('SMS GH', 'Off');
    // Sleep before this is sent.
    request('http://localhost:1111')
      .get('/smsghana')
      .query(reqParams)
      .expect(200)
      .end(function(err, res) {
        if (err) {
          return done(err);
        }
      });
    browser.get(browser.baseUrl + 'reports');
    // Check if there is any report. If there is, throw error.
    done();
  });
});
<|endoftext|>


<commit_before>var _ = require('underscore')

// escape all single-quotes on strings...
function quote(s){
    if (typeof(s) === 'string') {
        if (s.indexOf("\\'") == -1){
            s = s.replace(/'/g, "\\'");
        }
        s = "'" + s + "'";
    } else if (s instanceof Array) {
        var temp = [];
        _.each(s, function(v){
            temp.push(quote(v));
        })
        s = temp.join(', ');
    }

    return s;
}

var CQL = function(name){
    this.name = name;
    this._queries=[];
}

CQL.prototype = {
    name:null,
    _cmd:null,
    _first:null,
    _limit:null,
    _reversed:null,
    _cf:null,
    _col:null,
    _cols:null,
    _consistency:null,
    _where:null,
    _set:null,
    _ttl:null,
    _timestamp:null,
    _indexName:null,
    _counter:null,
    _range:null,
    _queries:null,
}

CQL.prototype.first = function(num){
    this._first = num;
}
CQL.prototype.limit = function(num){
    this._limit = num;
}
CQL.prototype.reversed = function(b){
    this._reversed = b;
}

CQL.prototype.from = function(cf){
    this._cf = cf;
}

CQL.prototype.set = function(args){
    this._set = args;
}

CQL.prototype.into = function(into){
    this._into = _.map(into, function(v){
        return quote(v);
    });

}

CQL.prototype.values = function(values){
    this._values = _.map(values, function(v){
        return quote(v);
    });
}

CQL.prototype.counter = function(args){
    this._counter = args;
}

CQL.prototype.range = function(start, end){
    start = quote(start);
    end = quote(end);
    this._cols = [[start, end].join('..')]
}

CQL.prototype.ttl = function(num){
    this._ttl = num;
}

CQL.prototype.timestamp = function(num){
    this._timestamp = num;
}

CQL.prototype.query = function(cql){
    if (cql instanceof CQL){
        this._queries.push(cql.statement());
    } else if(cql.constructor===String){
        this._queries.push(cql);
    }

}

CQL.prototype.consistency = function(s){
    /*
    ZERO
    ONE
    QUORUM
    ALL
    DCQUORUM
    DCQUORUMSYNC
    */
    this._consistency = s;
}

CQL.prototype.where = function(s, args){
    if (args !== undefined){
        var v
        for (var p in args){
            v = args[p];
            s = s.replace(new RegExp(':' + p), quote(v))
        }
    }
    this._where = s;
}

CQL.prototype.select = function(cols){
    this._cmd = 'SELECT';
    if (cols instanceof String){
        cols = [cols];
    }
    this._cols = cols;
}

CQL.prototype.update = function(cf){
    this._cmd = 'UPDATE';
    this._cf = cf;
}

CQL.prototype.insert = function(cf){
    this._cmd = 'INSERT';
    this._cf = cf;
}

CQL.prototype.delete = function(cols){
    this.select(cols);
    this._cmd = 'DELETE';
}

CQL.prototype.batch = function(c){
    this._cmd = 'BEGIN BATCH';
    if(c !== undefined){
        this.consistency(c);
    }
}

CQL.prototype.createIndex = function(cf, col){
    this._cmd = 'CREATE INDEX';
    this._indexName = cf + '_' + col;
    this._cf = cf;
    this._col = col;
}

CQL.prototype.count = function(){

}

CQL.prototype.statement = function(){
    var cql = []
    var cmd = this._cmd;

    cql.push(cmd);

    if (cmd === 'SELECT') {
        // SELECT [FIRST N] [REVERSED] <SELECT EXPR> FROM <COLUMN FAMILY> [consistency <CONSISTENCY>] [WHERE <CLAUSE>] [LIMIT N];

        if (this._first) {
            cql.push('FIRST');
            cql.push(this._first);
        }
        if (this._reversed) {
            cql.push('REVERSED');
        }

        cql.push(this._cols.join(', '));

        if (this._cf){
            cql.push('FROM');
            cql.push(this._cf)
        }

        if (this._consistency){
            cql.push('USING CONSISTENCY');
            cql.push(this._consistency)
        }

        if (this._where){
            cql.push('WHERE');
            cql.push(this._where)
        }

        if (this._limit){
            cql.push('LIMIT');
            cql.push(this._limit)
        }
    } else if (cmd === 'INSERT') {
        // INSERT INTO (KEY, v1, v2, …) VALUES (, , ,) [consistency CONSISTENCY [AND TIMESTAMP ] [AND TTL]];

        cql.push('INTO');
        cql.push(this._cf);
        cql.push('(' + this._into.join(', ') + ')');

        cql.push('VALUES');
        cql.push('(' + this._values.join(', ') + ')');

        var using = [];
        if (this._consistency){
            using.push('CONSISTENCY ' + this._consistency);
        }

        if (this._timestamp){
            using.push('TIMESTAMP ' + this._timestamp);
        }
        if (this._ttl){
            using.push('TTL ' + this._ttl);
        }
        if (using.length){
            cql.push('USING')
            cql.push(using.join(' AND '));
        }

    } else if (cmd === 'UPDATE') {

        // UPDATE <COLUMN FAMILY>
        //  [consistency <CONSISTENCY> [AND TIMESTAMP <timestamp>] [AND TTL <timeToLive>]]
        //  SET name1 = value1, name2 = value2 WHERE KEY = keyname;

        cql.push(this._cf);

        var using = [];
        if (this._consistency){
            using.push('CONSISTENCY ' + this._consistency);
        }

        if (this._timestamp){
            using.push('TIMESTAMP ' + this._timestamp);
        }
        if (this._ttl){
            using.push('TTL ' + this._ttl);
        }
        if (using.length){
            cql.push('USING')
            cql.push(using.join(' AND '));
        }
        cql.push('SET');

        var values = [];
        for (var p in this._set){
            values.push(quote(p) + '=' + quote(this._set[p]));
        }
        for (var p in this._counter){
            var num = this._counter[p];
            var dir = (num > -1) ? '+' : ''; // ignore negative number dir
            values.push(quote(p) + '=' + quote(p) + dir + num);
        }
        cql.push(values.join(', '))

        if (this._where){
            cql.push('WHERE');
            cql.push(this._where)
        }
    } else if (cmd==='DELETE'){
        // DELETE [COLUMNS] FROM <COLUMN FAMILY> [consistency <CONSISTENCY>] WHERE KEY = keyname1
        // DELETE [COLUMNS] FROM <COLUMN FAMILY> [consistency <CONSISTENCY>] WHERE KEY IN (keyname1, keyname2);
        cql.push(this._cols.join(', '));

        if (this._cf){
            cql.push('FROM');
            cql.push(this._cf)
        }

        var using = [];
        if (this._consistency){
            using.push('CONSISTENCY ' + this._consistency);
        }

        if (this._timestamp){
            using.push('TIMESTAMP ' + this._timestamp);
        }
        if (using.length){
            cql.push('USING')
            cql.push(using.join(' AND '));
        }

        if (this._where){
            cql.push('WHERE');
            cql.push(this._where)
        }

    } else if (cmd==='CREATE INDEX'){
        // CREATE INDEX [index_name] ON <column_family> (column_name);
        cql.push(this._indexName);
        cql.push('ON');
        cql.push(this._cf);
        cql.push('(' + this._col + ')');

    } else if (cmd==='BEGIN BATCH'){

        var using = [];
        if (this._consistency){
            using.push('CONSISTENCY ' + this._consistency);
        }

        if (this._timestamp){
            using.push('TIMESTAMP ' + this._timestamp);
        }
        if (using.length){
            cql[0] += ' USING ' + using.join(' AND ');
        }
        // cql[0] += '\n';
        // BEGIN BATCH [consistency]
        //  UPDATE CF1 SET name1 = value1, name2 = value2 WHERE KEY = keyname1;
        //  UPDATE CF1 SET name3 = value3 WHERE KEY = keyname2;
        //  UPDATE CF2 SET name4 = value4, name5 = value5 WHERE KEY = keyname3;
        // APPLY BATCH

        this._queries.push('')
        cql.push(this._queries.join(';  '))
        cql.push('APPLY BATCH')
    }

    return cql.join(' ');
}

exports.CQL = CQL;

//////// SELECT

// var q = new CQL('selecting something');
//
// q.select(['first_name', 'birth_year'])
// q.from('users');
// q.first(10);
// q.reversed(true);
// q.limit(10);
//
// q.where('full_name = :full_name', {full_name:"Greg Melton's"})
//
// console.log(q.statement());
//
//
// var q = new CQL('selecting something');
// q.select();
// q.range('0', 'Z');
// q.from('users');
// q.where('key = :key', {key:1})
//
// console.log(q.statement());

//////// UPDATE

// var q = new CQL('update something');
//
// q.update('users');
// q.consistency('QUORUM');
// q.timestamp(123345);
// q.ttl(86400);
// q.set({full_name:'Willard Hill'});
// q.where('KEY=:key', {key:1})
//
// console.log(q.statement());
//
//
// var q = new CQL('update something2');
//
// q.update('users');
// q.consistency('QUORUM');
// q.timestamp(123345);
// q.ttl(86400);
// q.set({full_name:'Pitty da Fool'});
// q.where('KEY IN (:keys)', {keys:['1', '2', '3', '4']})
//
// console.log(q.statement());

//////// INSERT

// var q = new CQL('insert something');
// q.insert('users');
// q.into(['key', 'full_name', 'birth_year'])
// q.values(['2', 'Sam the Butcher', 2000])
// q.consistency('QUORUM');
// q.timestamp(123345);
// q.ttl(86400);
//
// console.log(q.statement());

//////// DELETE

// var q = new CQL('insert something');
//
// q.delete(['*']); // columns
// q.from('users');
// q.where('KEY=:key', {key:1})
// q.consistency('QUORUM');
// q.timestamp(123345);
// console.log(q.statement());
//
// var q = new CQL('delete something');
// q.delete(['first_name', '']); // columns
// q.from('users');
// q.where('KEY IN (:keys)', {keys:[1,2,3,4]})
// q.consistency('QUORUM');
// q.timestamp(123345);
// console.log(q.statement());

//////// CREATE INDEX

// var q = new CQL('create index');
// q.createIndex('users', 'birth_year');
// console.log(q.statement());

//////// BATCH

// var q1 = new CQL('q1');
// q1.select(['*'])
// q1.from('User')
//
// var q2 = new CQL('q2');
// q2.select(['*'])
// q2.from('Pet')
//
// var cql = new CQL('batch');
// cql.batch();
// cql.query(q1);
// cql.query(q2);
// console.log(cql.statement());

<commit_msg>Make query generator chainable<commit_after>var _ = require('underscore')

// escape all single-quotes on strings...
function quote(s){
    if (typeof(s) === 'string') {
        if (s.indexOf("\\'") == -1){
            s = s.replace(/'/g, "\\'");
        }
        s = "'" + s + "'";
    } else if (s instanceof Array) {
        var temp = [];
        _.each(s, function(v){
            temp.push(quote(v));
        })
        s = temp.join(', ');
    }

    return s;
}

var CQL = function(name){
    this.name = name;
    this._queries=[];
}

CQL.prototype = {
    name:null,
    _cmd:null,
    _first:null,
    _limit:null,
    _reversed:null,
    _cf:null,
    _col:null,
    _cols:null,
    _consistency:null,
    _where:null,
    _set:null,
    _ttl:null,
    _timestamp:null,
    _indexName:null,
    _counter:null,
    _range:null,
    _queries:null,
}

CQL.prototype.first = function(num){
    this._first = num;
    return this;
}
CQL.prototype.limit = function(num){
    this._limit = num;
    return this;
}
CQL.prototype.reversed = function(b){
    this._reversed = b;
    return this;
}

CQL.prototype.from = function(cf){
    this._cf = cf;
    return this;
}

CQL.prototype.set = function(args){
    this._set = args;
    return this;
}

CQL.prototype.into = function(into){
    this._into = _.invoke(into, quote);
    return this;
}

CQL.prototype.values = function(values){
    this._values = _.invoke(values, quote);
    return this;
}

CQL.prototype.counter = function(args){
    this._counter = args;
    return this;
}

CQL.prototype.range = function(start, end){
    start = quote(start);
    end = quote(end);
    this._cols = [[start, end].join('..')]
    return this;
}

CQL.prototype.ttl = function(num){
    this._ttl = num;
    return this;
}

CQL.prototype.timestamp = function(num){
    this._timestamp = num;
    return this;
}

CQL.prototype.query = function(cql){
    if (cql instanceof CQL){
        this._queries.push(cql.statement());
    } else if(cql.constructor===String){
        this._queries.push(cql);
    }
    return this;
}

CQL.prototype.consistency = function(s){
    /*
    ZERO
    ONE
    QUORUM
    ALL
    DCQUORUM
    DCQUORUMSYNC
    */
    this._consistency = s;
    return this;
}

CQL.prototype.where = function(s, args){
    if (args !== undefined){
        var v
        for (var p in args){
            v = args[p];
            s = s.replace(new RegExp(':' + p), quote(v))
        }
    }
    this._where = s;
    return this;
}

CQL.prototype.select = function(cols){
    this._cmd = 'SELECT';
    if (cols instanceof String){
        cols = [cols];
    }
    this._cols = cols;
    return this;
}

CQL.prototype.update = function(cf){
    this._cmd = 'UPDATE';
    this._cf = cf;
    return this;
}

CQL.prototype.insert = function(cf){
    this._cmd = 'INSERT';
    this._cf = cf;
    return this;
}

CQL.prototype.delete = function(cols){
    this.select(cols);
    this._cmd = 'DELETE';
    return this;
}

CQL.prototype.batch = function(c){
    this._cmd = 'BEGIN BATCH';
    if(c !== undefined){
        this.consistency(c);
    }
    return this;
}

CQL.prototype.createIndex = function(cf, col){
    this._cmd = 'CREATE INDEX';
    this._indexName = cf + '_' + col;
    this._cf = cf;
    this._col = col;
    return this;
}

CQL.prototype.count = function(){

    return this;
}

CQL.prototype.statement = function(){
    var cql = []
    var cmd = this._cmd;

    cql.push(cmd);

    if (cmd === 'SELECT') {
        // SELECT [FIRST N] [REVERSED] <SELECT EXPR> FROM <COLUMN FAMILY> [consistency <CONSISTENCY>] [WHERE <CLAUSE>] [LIMIT N];

        if (this._first) {
            cql.push('FIRST');
            cql.push(this._first);
        }
        if (this._reversed) {
            cql.push('REVERSED');
        }

        cql.push(this._cols.join(', '));

        if (this._cf){
            cql.push('FROM');
            cql.push(this._cf)
        }

        if (this._consistency){
            cql.push('USING CONSISTENCY');
            cql.push(this._consistency)
        }

        if (this._where){
            cql.push('WHERE');
            cql.push(this._where)
        }

        if (this._limit){
            cql.push('LIMIT');
            cql.push(this._limit)
        }
    } else if (cmd === 'INSERT') {
        // INSERT INTO (KEY, v1, v2, …) VALUES (, , ,) [consistency CONSISTENCY [AND TIMESTAMP ] [AND TTL]];

        cql.push('INTO');
        cql.push(this._cf);
        cql.push('(' + this._into.join(', ') + ')');

        cql.push('VALUES');
        cql.push('(' + this._values.join(', ') + ')');

        var using = [];
        if (this._consistency){
            using.push('CONSISTENCY ' + this._consistency);
        }

        if (this._timestamp){
            using.push('TIMESTAMP ' + this._timestamp);
        }
        if (this._ttl){
            using.push('TTL ' + this._ttl);
        }
        if (using.length){
            cql.push('USING')
            cql.push(using.join(' AND '));
        }

    } else if (cmd === 'UPDATE') {

        // UPDATE <COLUMN FAMILY>
        //  [consistency <CONSISTENCY> [AND TIMESTAMP <timestamp>] [AND TTL <timeToLive>]]
        //  SET name1 = value1, name2 = value2 WHERE KEY = keyname;

        cql.push(this._cf);

        var using = [];
        if (this._consistency){
            using.push('CONSISTENCY ' + this._consistency);
        }

        if (this._timestamp){
            using.push('TIMESTAMP ' + this._timestamp);
        }
        if (this._ttl){
            using.push('TTL ' + this._ttl);
        }
        if (using.length){
            cql.push('USING')
            cql.push(using.join(' AND '));
        }
        cql.push('SET');

        var values = [];
        for (var p in this._set){
            values.push(quote(p) + '=' + quote(this._set[p]));
        }
        for (var p in this._counter){
            var num = this._counter[p];
            var dir = (num > -1) ? '+' : ''; // ignore negative number dir
            values.push(quote(p) + '=' + quote(p) + dir + num);
        }
        cql.push(values.join(', '))

        if (this._where){
            cql.push('WHERE');
            cql.push(this._where)
        }
    } else if (cmd==='DELETE'){
        // DELETE [COLUMNS] FROM <COLUMN FAMILY> [consistency <CONSISTENCY>] WHERE KEY = keyname1
        // DELETE [COLUMNS] FROM <COLUMN FAMILY> [consistency <CONSISTENCY>] WHERE KEY IN (keyname1, keyname2);
        cql.push(this._cols.join(', '));

        if (this._cf){
            cql.push('FROM');
            cql.push(this._cf)
        }

        var using = [];
        if (this._consistency){
            using.push('CONSISTENCY ' + this._consistency);
        }

        if (this._timestamp){
            using.push('TIMESTAMP ' + this._timestamp);
        }
        if (using.length){
            cql.push('USING')
            cql.push(using.join(' AND '));
        }

        if (this._where){
            cql.push('WHERE');
            cql.push(this._where)
        }

    } else if (cmd==='CREATE INDEX'){
        // CREATE INDEX [index_name] ON <column_family> (column_name);
        cql.push(this._indexName);
        cql.push('ON');
        cql.push(this._cf);
        cql.push('(' + this._col + ')');

    } else if (cmd==='BEGIN BATCH'){

        var using = [];
        if (this._consistency){
            using.push('CONSISTENCY ' + this._consistency);
        }

        if (this._timestamp){
            using.push('TIMESTAMP ' + this._timestamp);
        }
        if (using.length){
            cql[0] += ' USING ' + using.join(' AND ');
        }
        // cql[0] += '\n';
        // BEGIN BATCH [consistency]
        //  UPDATE CF1 SET name1 = value1, name2 = value2 WHERE KEY = keyname1;
        //  UPDATE CF1 SET name3 = value3 WHERE KEY = keyname2;
        //  UPDATE CF2 SET name4 = value4, name5 = value5 WHERE KEY = keyname3;
        // APPLY BATCH

        this._queries.push('')
        cql.push(this._queries.join(';  '))
        cql.push('APPLY BATCH')
    }

    return cql.join(' ');
}

exports.CQL = CQL;

//////// SELECT

// var q = new CQL('selecting something');
//
// q.select(['first_name', 'birth_year'])
// q.from('users');
// q.first(10);
// q.reversed(true);
// q.limit(10);
//
// q.where('full_name = :full_name', {full_name:"Greg Melton's"})
//
// console.log(q.statement());
//
//
// var q = new CQL('selecting something');
// q.select();
// q.range('0', 'Z');
// q.from('users');
// q.where('key = :key', {key:1})
//
// console.log(q.statement());

//////// UPDATE

// var q = new CQL('update something');
//
// q.update('users');
// q.consistency('QUORUM');
// q.timestamp(123345);
// q.ttl(86400);
// q.set({full_name:'Willard Hill'});
// q.where('KEY=:key', {key:1})
//
// console.log(q.statement());
//
//
// var q = new CQL('update something2');
//
// q.update('users');
// q.consistency('QUORUM');
// q.timestamp(123345);
// q.ttl(86400);
// q.set({full_name:'Pitty da Fool'});
// q.where('KEY IN (:keys)', {keys:['1', '2', '3', '4']})
//
// console.log(q.statement());

//////// INSERT

// var q = new CQL('insert something');
// q.insert('users');
// q.into(['key', 'full_name', 'birth_year'])
// q.values(['2', 'Sam the Butcher', 2000])
// q.consistency('QUORUM');
// q.timestamp(123345);
// q.ttl(86400);
//
// console.log(q.statement());

//////// DELETE

// var q = new CQL('insert something');
//
// q.delete(['*']); // columns
// q.from('users');
// q.where('KEY=:key', {key:1})
// q.consistency('QUORUM');
// q.timestamp(123345);
// console.log(q.statement());
//
// var q = new CQL('delete something');
// q.delete(['first_name', '']); // columns
// q.from('users');
// q.where('KEY IN (:keys)', {keys:[1,2,3,4]})
// q.consistency('QUORUM');
// q.timestamp(123345);
// console.log(q.statement());

//////// CREATE INDEX

// var q = new CQL('create index');
// q.createIndex('users', 'birth_year');
// console.log(q.statement());

//////// BATCH

// var q1 = new CQL('q1');
// q1.select(['*'])
// q1.from('User')
//
// var q2 = new CQL('q2');
// q2.select(['*'])
// q2.from('Pet')
//
// var cql = new CQL('batch');
// cql.batch();
// cql.query(q1);
// cql.query(q2);
// console.log(cql.statement());

<|endoftext|>


<commit_before>import SourceFile from './SourceFile';
import configs from './configs';

export default class ConfigFile extends SourceFile {

  static defaultProps = {
    type: 'application/json',
    text: '{}',
    json: {},
  };

  static defaultOptions = {
    isEntryPoint: false,
    isReadOnly: false,
    isTrashed: false,
    noBabel: false,
  }

  static defaultAuthor = {
    name: '',
    url: '',
  };

  static visible = SourceFile.visible;

  model = Array.from(configs.values())
    .find((config) => config.test.test(this.name));

  get json() {
    if (!this._json) {
      const { defaultValue } = this.model;
      this._json = Object.assign({}, defaultValue, JSON.parse(this.text));
    }
    return this._json;
  }

  /**
   * @param file File|Blob
   * @return Promise gives ConfigFile
   */
  static load(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = (e) => {
        resolve(
          new ConfigFile({
            type: file.type,
            name: file.name,
            text: e.data.result,
          })
        );
      };
      reader.readAsText(file);
    });
  }

  static get(files, key) {
    if (!configs.has(key)) {
      throw new Error(`${key} is not exist in ConfigFiles`);
    }

    const { test, multiple, defaultValue } = configs.get(key);

    if (!multiple) {
      const file = files.find((file) => (
        !file.options.isTrashed && test.test(file.name)
      ));
      return Object.assign({}, defaultValue, file ? file.json : {});
    } else {
      return files.filter((file) => (
        !file.options.isTrashed && test.test(file.name)
      )).reduce((p, c) => {
        return Object.assign(p, c);
      }, Object.assign({}, defaultValue));
    }
  }

}
<commit_msg>ConfigFile static methods<commit_after>import SourceFile from './SourceFile';
import configs from './configs';

export default class ConfigFile extends SourceFile {

  static defaultProps = {
    type: 'application/json',
    text: '{}',
    json: {},
  };

  static defaultOptions = {
    isEntryPoint: false,
    isReadOnly: false,
    isTrashed: false,
    noBabel: false,
  }

  static defaultAuthor = {
    name: '',
    url: '',
  };

  static visible = SourceFile.visible;

  model = Array.from(configs.values())
    .find((config) => config.test.test(this.name));

  get json() {
    if (!this._json) {
      const { defaultValue } = this.model;
      this._json = Object.assign({}, defaultValue, JSON.parse(this.text));
    }
    return this._json;
  }

  /**
   * @param file File|Blob
   * @return Promise gives ConfigFile
   */
  static load(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = (e) => {
        resolve(
          new ConfigFile({
            type: file.type,
            name: file.name,
            text: e.data.result,
          })
        );
      };
      reader.readAsText(file);
    });
  }

  static get (key) {
    if (!configs.has(key)) {
      throw new Error(`${key} is not exist in ConfigFiles`);
    }
    return configs.get(key);
  }

  static getFile(files, key) {
    const { test, multiple } = ConfigFile.get(key);

    const predicate = (file) => (
      !file.options.isTrashed && test.test(file.name)
    );

    return multiple ?
      files.filter(predicate) :
      files.find(predicate);
  }

  static getValue(files, key) {
    const target = ConfigFile.getFile(files, key);

    if (!target) {
      const { defaultValue } = ConfigFile.get(key);
      return defaultValue;
    }

    return target instanceof Array ?
      target.reduce((p, c) => Object.assign(p, c.json), {}) :
      target.json;
  }

}
<|endoftext|>