<commit_before>/**
 * @license
 * Copyright 2013 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// TODO: standardize on either get()/set() or .value
CLASS({
  name: 'SimpleValue',
  properties: [ { name: 'value' } ],

  constants: {
    __isValue__: true
  },

  methods: [
    function init(value) { this.value = value || ''; },
    function get() { return this.value; },
    function set(val) { this.value = val; },
    function toString() { return 'SimpleValue(' + this.value + ')'; },
    function follow(srcValue) { Events.follow(srcValue, this); }
  ]
});

CLASS({
  name: 'FunctionValue',
  extends: 'SimpleValue',

  properties: [
    { name: 'values', factory: function() { return []; } },
    { name: 'valueFactory' }
  ],

  methods: [
    function init() {
      this.SUPER();

      // Call once before capture to pre-latch lazy values
      this.valueFactory();

      var f = this.valueFactory;
      this.startRecordingDependencies();
        this.value = f();
      this.endRecordingDependencies();

      for ( var i = 0 ; i < this.values.length ; i++ )
        this.values[i].addListener(this.onSubValueChange);
      console.log('**** ', this.values.join(','));
    },
    function destroy() {
      for ( var i = 0 ; i < this.values.length ; i++ )
        this.values[i].removeListener(this.onSubValueChange);
    },
    function startRecordingDependencies() {
      var values = this.values;
      var onSubValueChange = this.onSubValueChange;
      Events.onGet.push(function(obj, name, value) {
        var l = obj.propertyValue(name);
        if ( values.indexOf(l) == -1 ) {
          values.push(l);
          l.addListener(onSubValueChange);
        }
      });
    },
    function endRecordingDependencies() {
      Events.onGet.pop();
    },
    function get() { return this.value; },
    function set(val) { },
    function toString() { return 'FunctionValue(' + this.value + ')'; }
  ],

  listeners: [
    function onSubValueChange_() { this.value = this.valueFactory(); },
    {
      name: 'onSubValueChange',
      isFramed: true,
      code: function() { this.onSubValueChange_(); }
    }
  ]
});

CLASS({
  name: 'OrValue',
  extends: 'SimpleValue',

  properties: [
    { name: 'values' },
    { name: 'valueFactory', defaultValue: function() { return arguments; } }
  ],

  methods: [
    function init() {
      this.SUPER();
      for ( var i = 0 ; i < this.values.length ; i++ )
        this.values[i].addListener(this.onSubValueChange);
      this.onSubValueChange_();
    },
    function destroy() {
      for ( var i = 0 ; i < this.values.length ; i++ )
        this.values[i].removeListener(this.onSubValueChange);
    },
    function get() { return this.value; },
    function set(val) { },
    function toString() { return 'OrValue(' + this.value + ')'; }
  ],

  listeners: [
    function onSubValueChange_() {
      var args = new Array(this.values.length);
      for ( var i = 0 ; i < this.values.length ; i++ )
        args[i] = this.values[i].get();
      this.value = this.valueFactory.apply(this, args);
    },
    {
      name: 'onSubValueChange',
      isFramed: true,
      code: function() { this.onSubValueChange_(); }
    }
  ]
});

function or$(values, factory, opt_X) {
  return OrValue.create({
    values: values,
    valueFactory: factory,
  }, opt_X);
}

CLASS({
  name: 'SimpleReadOnlyValue',
  extends: 'SimpleValue',

  documentation: 'A simple value that can only be set during initialization.',

  properties: [
    {
      name: 'value',
      preSet: function(old, nu) {
        return ( typeof this.instance_.value == 'undefined' ) ? nu : old ;
      }
    }
  ],

  methods: {
    set: function(val) {
      /* Only allow set once. The first initialized value is the only one. */
      if ( typeof this.instance_.value == 'undefined' ) {
        this.SUPER(val);
      }
    },
    toString: function() { return 'SimpleReadOnlyValue(' + this.value + ')'; }
  }
});
<commit_msg>Removed stale console.log.<commit_after>/**
 * @license
 * Copyright 2013 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// TODO: standardize on either get()/set() or .value
CLASS({
  name: 'SimpleValue',
  properties: [ { name: 'value' } ],

  constants: {
    __isValue__: true
  },

  methods: [
    function init(value) { this.value = value || ''; },
    function get() { return this.value; },
    function set(val) { this.value = val; },
    function toString() { return 'SimpleValue(' + this.value + ')'; },
    function follow(srcValue) { Events.follow(srcValue, this); }
  ]
});

CLASS({
  name: 'FunctionValue',
  extends: 'SimpleValue',

  properties: [
    { name: 'values', factory: function() { return []; } },
    { name: 'valueFactory' }
  ],

  methods: [
    function init() {
      this.SUPER();

      // Call once before capture to pre-latch lazy values
      this.valueFactory();

      var f = this.valueFactory;
      this.startRecordingDependencies();
        this.value = f();
      this.endRecordingDependencies();

      for ( var i = 0 ; i < this.values.length ; i++ )
        this.values[i].addListener(this.onSubValueChange);
    },
    function destroy() {
      for ( var i = 0 ; i < this.values.length ; i++ )
        this.values[i].removeListener(this.onSubValueChange);
    },
    function startRecordingDependencies() {
      var values = this.values;
      var onSubValueChange = this.onSubValueChange;
      Events.onGet.push(function(obj, name, value) {
        var l = obj.propertyValue(name);
        if ( values.indexOf(l) == -1 ) {
          values.push(l);
          l.addListener(onSubValueChange);
        }
      });
    },
    function endRecordingDependencies() {
      Events.onGet.pop();
    },
    function get() { return this.value; },
    function set(val) { },
    function toString() { return 'FunctionValue(' + this.value + ')'; }
  ],

  listeners: [
    function onSubValueChange_() { this.value = this.valueFactory(); },
    {
      name: 'onSubValueChange',
      isFramed: true,
      code: function() { this.onSubValueChange_(); }
    }
  ]
});

CLASS({
  name: 'OrValue',
  extends: 'SimpleValue',

  properties: [
    { name: 'values' },
    { name: 'valueFactory', defaultValue: function() { return arguments; } }
  ],

  methods: [
    function init() {
      this.SUPER();
      for ( var i = 0 ; i < this.values.length ; i++ )
        this.values[i].addListener(this.onSubValueChange);
      this.onSubValueChange_();
    },
    function destroy() {
      for ( var i = 0 ; i < this.values.length ; i++ )
        this.values[i].removeListener(this.onSubValueChange);
    },
    function get() { return this.value; },
    function set(val) { },
    function toString() { return 'OrValue(' + this.value + ')'; }
  ],

  listeners: [
    function onSubValueChange_() {
      var args = new Array(this.values.length);
      for ( var i = 0 ; i < this.values.length ; i++ )
        args[i] = this.values[i].get();
      this.value = this.valueFactory.apply(this, args);
    },
    {
      name: 'onSubValueChange',
      isFramed: true,
      code: function() { this.onSubValueChange_(); }
    }
  ]
});

function or$(values, factory, opt_X) {
  return OrValue.create({
    values: values,
    valueFactory: factory,
  }, opt_X);
}

CLASS({
  name: 'SimpleReadOnlyValue',
  extends: 'SimpleValue',

  documentation: 'A simple value that can only be set during initialization.',

  properties: [
    {
      name: 'value',
      preSet: function(old, nu) {
        return ( typeof this.instance_.value == 'undefined' ) ? nu : old ;
      }
    }
  ],

  methods: {
    set: function(val) {
      /* Only allow set once. The first initialized value is the only one. */
      if ( typeof this.instance_.value == 'undefined' ) {
        this.SUPER(val);
      }
    },
    toString: function() { return 'SimpleReadOnlyValue(' + this.value + ')'; }
  }
});
<|endoftext|>


<commit_before>/*******************************************************************************
 *
 * Copyright (c) 2012 ObjectLabs Corporation
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:

 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.

 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
var Module = require('module')
var argparser = require('nomnom')
var inherits = require('util').inherits
var _o = require('bond')._o

/*******************************************************************************
 * CONSTANTS
 */
var TYPE_FIELD = '_type'
var PROPERTY_FIELD = '$property'
var __DEEP_MODE__ = false

/*******************************************************************************
 * @class Atom
 * @ignore
 */
function Atom(typeResolver) {
  this._typeResolver = typeResolver || _o;
};

Atom.prototype = { // XXX did we just overwrite Atom.prototype.constructor? Yes but we fix below (decide)

  /***************************************************************************
   * ignoreFields
   */
  ignoreFields : [],

  /***************************************************************************
   * _typeResolver
   */
  _typeResolver : null,

  /***************************************************************************
   * make
   *
   * @param {Object} datum
   * @param {Object|string} targetType
   * @param {boolean} isClass
   * @param {Object} mod - module
   * @param {Object} result
   */
  make: function(datum, targetType, args, isClass, mod, result) { // XXX seems like result not used? Maybe for when instantiate type first? hmmm
    // primitives
    if (datum === null) {
      return null;
    }

    if (datum === undefined) {
      return undefined;
    }

    dtype = typeof(datum);
    if (dtype === 'string') {
      return datum;
    }

    if (dtype === 'boolean') {
      return datum;
    }

    if (dtype === 'number') {
      return datum;
    }

    if (dtype === 'function') {
      return datum;
    }

    // arrays
    if (datum.constructor === Array) {
      if (__DEEP_MODE__) {
        return this._makeArray(datum, mod);
      } else {
        return datum
      }
    }

    // objects
    if (dtype === 'object') {
      var value = this._makeObject(datum, targetType, args, isClass, mod, result);
      return value
    }

    throw new Error("Unable to make from datum: " + datum);
  },

  /***************************************************************************
   * _makeArray
   *
   * @param prototype
   */
  _makeArray : function(datum, mod) {
    var self = this;
    return datum.map(function(elem) { return self.make(elem, null, null, false, mod); });
  },

  /***************************************************************************
   * _makeObject
   *
   * @param {Object} datum
   * @param {boolean} [isClass]
   * @param {Object} [result]
   */
  _makeObject: function(datum, targetType, args, isClass, mod, result) {
    if (datum._ref) {
      return _o(mod)(datum._ref); // XXX is this still in play?
    }

    // instantiate object
    result = result || this.instantiate(datum, targetType, args, isClass, mod);

    // define properties
    this._defineProperties(datum, isClass, mod, result)

    if (!isClass) { // only applies to objects not classes
      // initialize
      this._initializeObject(result, args)
      // run main (will only run in right conditions)
      this._runMain(result, mod)
    }

    return result;
  },

  /***************************************************************************
   * _defineProperties
   *
   * @param {Object} datum
   * @param {boolean} [isClass]
   * @param {Object} [result]
   */
  _defineProperties: function(datum, isClass, mod, result) {
    for (var property in datum) {
      if ((this.ignoreFields.indexOf(property) === -1) &&
          property !== TYPE_FIELD &&
          datum.hasOwnProperty(property))
      {
        var value = datum[property]
        if (__DEEP_MODE__) {
          value = this.make(value, null, null, false, mod);
        }

        if (isClass) {
          this._defineProperty(result.prototype, property, value);
        } else {
          this._defineProperty(result, property, value);
        }
      }
    }
  },

  /***************************************************************************
   * _defineProperty
   *
   * @param {Object} obj
   * @param {String} property
   * @param {Object} value
   *
   * @ignore
   */
  _defineProperty : function(obj, property, value) {
    // obj[property] = value
    // obj[property] = { "$property" : <property-def> }
    // XXX this should probably be o({$property: <property-def>}) ??

    if (value != null && typeof(value) === 'object' && value[PROPERTY_FIELD]) {
      // $property case
      Object.defineProperty(obj, property, value[PROPERTY_FIELD])
    } else {
      // XXX was doing this but don't think that is quite right. Just setting works much better in
      //  the case where you want to have a non-shared property redefined in the obj not in proto
      // XXX maybe skip _C? Do this upstairs

      Object.defineProperty(obj, property, {
        enumerable: true,
        configurable: true,
        writable: true,
        value: value
      })
    }
  },

  /***************************************************************************
   * instantiate
   *
   * @param {Object} datum
   * @param {boolean} isClass
   *
   * @returns {Object} The object or class (Function) instantiated from datum
   */
  instantiate: function(datum, targetType, args, isClass, mod) {
    var self = this
    var type = targetType || datum[TYPE_FIELD] || Object

    if (typeof(type) === 'string') {
      var resolver = this._typeResolver;
      if (resolver) {
        var typeName = type;
        try {
          type = resolver(mod)(typeName);
        } catch (e) {
          throw new Error("Could not resolve _type: '" + typeName + "' from module " + mod.filename + " -- " + e.message)
        }
        if (!type) {
          throw new Error("Could not resolve _type: '" + typeName + "' from module " + mod.filename)
        }
      } else {
        throw new Error("Could not resolve _type: " + type + " . Could not find resolver")
      }
    }

    var initSuppressionArg = { __supressInit__: true }

    // helper function
    var makeConstructor = function() {
      var C = function() {
        // automatically chain with init suppression (_init definition should chain if desired)
        C.super_.apply(this, [initSuppressionArg])  // XXX chain rest of args or no?

        if (C.prototype._C) { // call _C as defined
          // pass through args but also deal with __supressInit__
          var cArgs = arguments
          var suppressInit = false
          if (cArgs && cArgs.length > 0) {
            var lastArg = arguments[cArgs.length - 1]
            if (lastArg.__supressInit__) {
              suppressInit = true
              delete cArgs[cArgs.length - 1]
            }
          }
          C.prototype._C.apply(this, cArgs)
        }

        // call _init unless supressed
        if (!suppressInit) {
          self._initializeObject(this, cArgs)
        }
      }

      // mark as defined by Atom
      C.__isAtomDefined__ = true

      return C
    }

    if (typeof(type) === 'function') { // constructor
      var result = null
      if (isClass) {
        // our constructor
        var C = makeConstructor()
        // link superclass
        inherits(C, type)
        // define _super method
        Object.defineProperty(C.prototype, '_super', {
          enumerable: false,
          configurable: false,
          writable: false,
          value: function(methodName) {
            if (type.prototype[methodName]) {
              return type.prototype[methodName].bind(this)
            }
                                 // XXX
            return function() {} // just so clients don't have to check if the superclass has method
          }
        })
        // define _type method XXX
        Object.defineProperty(C.prototype, '_type', {
          enumerable: false,
          configurable: false,
          writable: false,
          value: function(methodName) {
            if (C.prototype[methodName]) {
              return C.prototype[methodName].bind(this)
            }
                                 // XXX
            return function() {} // just so clients don't have to check if the superclass has method
          }
        })
        result = C
      } else {
        args = args || []
        if (type.__isAtomDefined__) {
          // Supress the atom-defined constructor from calling _init. Will be called
          // after define-properties in make()
          args.push(initSuppressionArg)
        }

        // Can we optimize by calling new directly if no args (e.g result = new type(args)) ?
        // Dynamically call new type with variable args. This is hairy. Found solution here
        // http://jsperf.com/dynamic-arguments-to-the-constructor
        result = new (Function.prototype.bind.apply(type, [null].concat(args)))
      }

      return result
    }

    // otherwise assume it is an object
    var result
    if (isClass) { // XXX is this a case we want to support ( oo where type is object )?
      // our constructor
      var C = makeConstructor()
      C.prototype = type
      C.prototype.constructor = C
      result = C
    } else {
      result = Object.create(type)
      // XXX define _type?
      Object.defineProperty(result, '_type', {
        enumerable: false,
        configurable: false,
        writable: false,
        value: function(methodName) {
          if (type[methodName]) {
            return type[methodName].bind(this)
          }
          // XXX
          return function() {} // just so clients don't have to check if the superclass has method
        }
      })
    }

    return result
  },

  /***************************************************************************
   * _initializeObject
   */
  _initializeObject: function(obj, args) {
    if (obj._init) {
      obj._init.apply(obj, args)
    }
  },

  /***************************************************************************
   * _runMain
   */
  _runMain: function(obj, mod) {
    if (obj._main && require.main && (require.main == mod)) {
      // if cmdargs are defined use them
      var cmdargs = obj.cmdargs
      if (cmdargs) {
        argparser.options(cmdargs)
      }

      var options = argparser.parse(process.argv.slice(2))
      delete options._ // kill the _ args since we don't want them

      // configure option properties
      this._configureOptionProperties(obj, cmdargs, options)

      // do it
      obj._main(options)
    }
  },

  /***************************************************************************
   * configureOptionProperties
   */
  _configureOptionProperties: function(obj, optionDefinitions, options) {
    if (optionDefinitions) {
      for (var option in options) {
        if (optionDefinitions[option] && optionDefinitions[option].property) {
          var optionValue = options[option]
          obj[option] = optionValue
        }
      }
    }
  }

};

Atom.prototype.constructor = Atom; // very important this is here

/*******************************************************************************
 * atom
 */
var atom = new Atom();

/*******************************************************************************
 * o
 *
 * @param {Object} module
 */
function o(mod) {
  if (!(mod instanceof Module)) {
    throw(Error("Must supply a module to o: " + JSON.stringify(mod)))
  }
  return function() { // takes (datum, targetType, args...)
    var datum = arguments[0]
    var targetType
    var args
    if (arguments.length > 1) {
      targetType = arguments[1]
    }
    if (arguments.length > 2) { // the rest are constructor args
      var argumentsArray = Array.prototype.slice.call(arguments);
      args = argumentsArray.slice(2)
    }
    return atom.make(datum, targetType, args, false, mod);
  }
}

/*******************************************************************************
 * oo
 *
 * @param {Object} datum
 */
function oo(mod) {
  if (!(mod instanceof Module)) {
    throw(Error("Must supply a module to oo: " + JSON.stringify(mod)))
  }
  return function(datum) {
    return atom.make(datum, null, null, true, mod);
  }
}

/*******************************************************************************
 * exports
 */
if (typeof(exports) != "undefined") {
  exports.Atom = Atom;
  exports.o = o;
  exports.oo = oo;
}
<commit_msg>remove logging<commit_after>/*******************************************************************************
 *
 * Copyright (c) 2012 ObjectLabs Corporation
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:

 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.

 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
var Module = require('module')
var argparser = require('nomnom')
var inherits = require('util').inherits
var _o = require('bond')._o

/*******************************************************************************
 * CONSTANTS
 */
var TYPE_FIELD = '_type'
var PROPERTY_FIELD = '$property'
var __DEEP_MODE__ = false

/*******************************************************************************
 * @class Atom
 * @ignore
 */
function Atom(typeResolver) {
  this._typeResolver = typeResolver || _o;
};

Atom.prototype = { // XXX did we just overwrite Atom.prototype.constructor? Yes but we fix below (decide)

  /***************************************************************************
   * ignoreFields
   */
  ignoreFields : [],

  /***************************************************************************
   * _typeResolver
   */
  _typeResolver : null,

  /***************************************************************************
   * make
   *
   * @param {Object} datum
   * @param {Object|string} targetType
   * @param {boolean} isClass
   * @param {Object} mod - module
   * @param {Object} result
   */
  make: function(datum, targetType, args, isClass, mod, result) { // XXX seems like result not used? Maybe for when instantiate type first? hmmm
    // primitives
    if (datum === null) {
      return null;
    }

    if (datum === undefined) {
      return undefined;
    }

    dtype = typeof(datum);
    if (dtype === 'string') {
      return datum;
    }

    if (dtype === 'boolean') {
      return datum;
    }

    if (dtype === 'number') {
      return datum;
    }

    if (dtype === 'function') {
      return datum;
    }

    // arrays
    if (datum.constructor === Array) {
      if (__DEEP_MODE__) {
        return this._makeArray(datum, mod);
      } else {
        return datum
      }
    }

    // objects
    if (dtype === 'object') {
      var value = this._makeObject(datum, targetType, args, isClass, mod, result);
      return value
    }

    throw new Error("Unable to make from datum: " + datum);
  },

  /***************************************************************************
   * _makeArray
   *
   * @param prototype
   */
  _makeArray : function(datum, mod) {
    var self = this;
    return datum.map(function(elem) { return self.make(elem, null, null, false, mod); });
  },

  /***************************************************************************
   * _makeObject
   *
   * @param {Object} datum
   * @param {boolean} [isClass]
   * @param {Object} [result]
   */
  _makeObject: function(datum, targetType, args, isClass, mod, result) {
    if (datum._ref) {
      return _o(mod)(datum._ref); // XXX is this still in play?
    }

    // instantiate object
    result = result || this.instantiate(datum, targetType, args, isClass, mod);

    // define properties
    this._defineProperties(datum, isClass, mod, result)

    if (!isClass) { // only applies to objects not classes
      // initialize
      this._initializeObject(result, args)
      // run main (will only run in right conditions)
      this._runMain(result, mod)
    }

    return result;
  },

  /***************************************************************************
   * _defineProperties
   *
   * @param {Object} datum
   * @param {boolean} [isClass]
   * @param {Object} [result]
   */
  _defineProperties: function(datum, isClass, mod, result) {
    for (var property in datum) {
      if ((this.ignoreFields.indexOf(property) === -1) &&
          property !== TYPE_FIELD &&
          datum.hasOwnProperty(property))
      {
        var value = datum[property]
        if (__DEEP_MODE__) {
          value = this.make(value, null, null, false, mod);
        }

        if (isClass) {
          this._defineProperty(result.prototype, property, value);
        } else {
          this._defineProperty(result, property, value);
        }
      }
    }
  },

  /***************************************************************************
   * _defineProperty
   *
   * @param {Object} obj
   * @param {String} property
   * @param {Object} value
   *
   * @ignore
   */
  _defineProperty : function(obj, property, value) {
    // obj[property] = value
    // obj[property] = { "$property" : <property-def> }
    // XXX this should probably be o({$property: <property-def>}) ??

    if (value != null && typeof(value) === 'object' && value[PROPERTY_FIELD]) {
      // $property case
      Object.defineProperty(obj, property, value[PROPERTY_FIELD])
    } else {
      // XXX was doing this but don't think that is quite right. Just setting works much better in
      //  the case where you want to have a non-shared property redefined in the obj not in proto
      // XXX maybe skip _C? Do this upstairs

      Object.defineProperty(obj, property, {
        enumerable: true,
        configurable: true,
        writable: true,
        value: value
      })
    }
  },

  /***************************************************************************
   * instantiate
   *
   * @param {Object} datum
   * @param {boolean} isClass
   *
   * @returns {Object} The object or class (Function) instantiated from datum
   */
  instantiate: function(datum, targetType, args, isClass, mod) {
    var self = this
    var type = targetType || datum[TYPE_FIELD] || Object

    if (typeof(type) === 'string') {
      var resolver = this._typeResolver;
      if (resolver) {
        var typeName = type;
        try {
          type = resolver(mod)(typeName);
        } catch (e) {
          throw new Error("Could not resolve _type: '" + typeName + "' from module " + mod.filename + " -- " + e.message)
        }
        if (!type) {
          throw new Error("Could not resolve _type: '" + typeName + "' from module " + mod.filename)
        }
      } else {
        throw new Error("Could not resolve _type: " + type + " . Could not find resolver")
      }
    }

    var initSuppressionArg = { __supressInit__: true }

    // helper function
    var makeConstructor = function() {
      var C = function() {
        // automatically chain with init suppression (_init definition should chain if desired)
        C.super_.apply(this, [initSuppressionArg])  // XXX chain rest of args or no?

        if (C.prototype._C) { // call _C as defined
          // pass through args but also deal with __supressInit__
          var cArgs = arguments
          var suppressInit = false
          if (cArgs && cArgs.length > 0) {
            var lastArg = arguments[cArgs.length - 1]
            if (lastArg.__supressInit__) {
              suppressInit = true
              delete cArgs[cArgs.length - 1]
            }
          }
          C.prototype._C.apply(this, cArgs)
        }

        // call _init unless supressed
        if (!suppressInit) {
          self._initializeObject(this, cArgs)
        }
      }

      // mark as defined by Atom
      C.__isAtomDefined__ = true

      return C
    }

    if (typeof(type) === 'function') { // constructor
      var result = null
      if (isClass) {
        // our constructor
        var C = makeConstructor()
        // link superclass
        inherits(C, type)
        // define _super method
        Object.defineProperty(C.prototype, '_super', { // XXX this is not right in all cases should remove
          enumerable: false,
          configurable: false,
          writable: false,
          value: function(methodName) {
            if (type.prototype[methodName]) {
              return type.prototype[methodName].bind(this)
            }
                                 // XXX
            return function() {} // just so clients don't have to check if the superclass has method
          }
        })
        // define _type method XXX
        Object.defineProperty(C.prototype, '_type', {
          enumerable: false,
          configurable: false,
          writable: false,
          value: function(methodName) {
            if (C.prototype[methodName]) {
              return C.prototype[methodName].bind(this)
            }
                                 // XXX
            return function() {} // just so clients don't have to check if the superclass has method
          }
        })
        result = C
      } else {
        args = args || []
        if (type.__isAtomDefined__) {
          // Supress the atom-defined constructor from calling _init. Will be called
          // after define-properties in make()
          args.push(initSuppressionArg)
        }

        // Can we optimize by calling new directly if no args (e.g result = new type(args)) ?
        // Dynamically call new type with variable args. This is hairy. Found solution here
        // http://jsperf.com/dynamic-arguments-to-the-constructor
        result = new (Function.prototype.bind.apply(type, [null].concat(args)))
      }

      return result
    }

    // otherwise assume it is an object
    var result
    if (isClass) { // XXX is this a case we want to support ( oo where type is object )?
      // our constructor
      var C = makeConstructor()
      C.prototype = type
      C.prototype.constructor = C
      result = C
    } else {
      result = Object.create(type)
      // XXX define _type?
      Object.defineProperty(result, '_type', {
        enumerable: false,
        configurable: false,
        writable: false,
        value: function(methodName) {
          if (type[methodName]) {
            return type[methodName].bind(this)
          }
          // XXX
          return function() {} // just so clients don't have to check if the superclass has method
        }
      })
    }

    return result
  },

  /***************************************************************************
   * _initializeObject
   */
  _initializeObject: function(obj, args) {
    if (obj._init) {
      obj._init.apply(obj, args)
    }
  },

  /***************************************************************************
   * _runMain
   */
  _runMain: function(obj, mod) {
    if (obj._main && require.main && (require.main == mod)) {
      // if cmdargs are defined use them
      var cmdargs = obj.cmdargs
      if (cmdargs) {
        argparser.options(cmdargs)
      }

      var options = argparser.parse(process.argv.slice(2))
      delete options._ // kill the _ args since we don't want them

      // configure option properties
      this._configureOptionProperties(obj, cmdargs, options)

      // do it
      obj._main(options)
    }
  },

  /***************************************************************************
   * configureOptionProperties
   */
  _configureOptionProperties: function(obj, optionDefinitions, options) {
    if (optionDefinitions) {
      for (var option in options) {
        if (optionDefinitions[option] && optionDefinitions[option].property) {
          var optionValue = options[option]
          obj[option] = optionValue
        }
      }
    }
  }

};

Atom.prototype.constructor = Atom; // very important this is here

/*******************************************************************************
 * atom
 */
var atom = new Atom();

/*******************************************************************************
 * o
 *
 * @param {Object} module
 */
function o(mod) {
  if (!(mod instanceof Module)) {
    throw(Error("Must supply a module to o: " + JSON.stringify(mod)))
  }
  return function() { // takes (datum, targetType, args...)
    var datum = arguments[0]
    var targetType
    var args
    if (arguments.length > 1) {
      targetType = arguments[1]
    }
    if (arguments.length > 2) { // the rest are constructor args
      var argumentsArray = Array.prototype.slice.call(arguments);
      args = argumentsArray.slice(2)
    }
    return atom.make(datum, targetType, args, false, mod);
  }
}

/*******************************************************************************
 * oo
 *
 * @param {Object} datum
 */
function oo(mod) {
  if (!(mod instanceof Module)) {
    throw(Error("Must supply a module to oo: " + JSON.stringify(mod)))
  }
  return function(datum) {
    return atom.make(datum, null, null, true, mod);
  }
}

/*******************************************************************************
 * exports
 */
if (typeof(exports) != "undefined") {
  exports.Atom = Atom;
  exports.o = o;
  exports.oo = oo;
}
<|endoftext|>


<commit_before>const GROUPS_SCROLL_DELAY = 5;
$(function() {

/*
 *  Groups bar caret scrolling
 */

  $(document).on('mousedown', '.overflow-up', function() {
    var bar = $('.groups-bar')[0];
    var heightToScroll = bar.scrollTop;
    var delay = heightToScroll * GROUPS_SCROLL_DELAY;

    $('.groups-bar').animate({scrollTop: 0}, delay);
  });

  $(document).on('mouseup', '.overflow-up', function() {
    $('.groups-bar').stop(true);
  });

  $(document).on('mousedown', '.overflow-down', function() {
    var bar = $('.groups-bar')[0];
    var totalHeight = bar.scrollHeight - bar.clientHeight;
    var heightToScroll = totalHeight - bar.scrollTop;
    var delay = heightToScroll * GROUPS_SCROLL_DELAY;

    $('.groups-bar').animate({scrollTop: bar.scrollHeight}, delay);
  });

  $(document).on('mouseup', '.overflow-down', function() {
    $('.groups-bar').stop(true);
  });

  $(document).on('mouseenter', '.group-block', function(event) {
    var block = $(event.target);
    var key = block.data('key');
    var value = block.data('value');
    var num = block.data('num');

    var top = block.offset().top - $($('.groups-bar-container')[0]).offset().top;
    top += (block.height() / 2 - 20);

    var id = $('body').data('id');

    // if grouping by experiment, additionally fetch the description
    if (key == "Experiment ID" || key == "Experiment Run ID") {
      $.ajax({
        url: '/projects/' + id + '/experiments',
        type: "GET",
        success: function(response) {
          var description = null;
          if (key == "Experiment ID") {
            for (var i=0; i<response.experiments.length; i++) {
              if (response.experiments[i].id == value) {
                description = response.experiments[i].description;
              }
            }
          } else if (key == "Experiment Run ID") {
            for (var i=0; i<response.experimentRuns.length; i++) {
              if (response.experimentRuns[i].id == value) {
                description = response.experimentRuns[i].description;
              }
            }
          }

          var obj = {
            'key': key,
            'value': value,
            'num': num,
            'description': description
          };

          var tooltip = $(new EJS({url: '/ejs/group-tooltip.ejs'}).render(obj));
          tooltip.css({'top': top + 'px'});
          $('.groups-bar-container').append(tooltip);
        }
      });
    } else {
      // otherwise, just show tooltip normally
      var obj = {
        'key': key,
        'value': value,
        'num': num,
        'description': null
      };

      var tooltip = $(new EJS({url: '/ejs/group-tooltip.ejs'}).render(obj));
      tooltip.css({'top': top + 'px'});
      $('.groups-bar-container').append(tooltip);
    }
  });

  $(document).on('mouseleave', '.group-block', function() {
    $('.group-tooltip').remove();
  });

  // Model see more listener
  $(document).on('click', '.model-see-more', function(event) {
    var elt = $(event.target);
    var info = elt.parent().find('.model-additional-info');
    var show = elt.data('show');
    if (show) {
      elt.data('show', false);
      elt.html("See More");
      info.slideUp();
      info.animate(
        { opacity: 0 },
        { queue: false, duration: 'slow' }
      );
    } else {
      elt.data('show', true);
      elt.html("See Less");
      info.slideDown();
      info.animate(
        { opacity: 1 },
        { queue: false, duration: 'slow' }
      );
    }
  });

  // filter toggle options
  $(document).on('click', '.filter-expand', function(event) {
    var elt = $(event.target);
    var filter = elt.closest('.filter');
    var options = elt.next('.filter-options');
    if (elt.data('show')) {
      // hide options
      options.slideUp();
      elt.html("▼");
      elt.data('show', false);
    } else {
      // show options
      options.slideDown();
      options.find('input[type="text"]').val(filter.data('val').join(', '));
      options.find('input[type="text"]').focus();
      elt.html("▲");
      elt.data('show', true);
    }
  });

  // show json modal
  $(document).on('click', '.json-md-trigger', function(event) {
    // TODO: duplicate call; avoid
    var modelId = $(event.target).data('id');
    $.ajax({
      url: '/models/' + modelId + '/metadata',
      type: "GET",
      success: function(response) {
        var node = new PrettyJSON.view.Node({
          el:$('#md-json'),
          data:JSON.parse(response)
        });
        node.expandAll();
        var saveButton = $('<button class="save-button" disabled>Save Changes</button>');
        $('#md-json').append(saveButton);
        $('#md-json').data('modelId', modelId);
        $('#modal-2').addClass('md-show');
        attachModalListeners();
        node.collapseAll();
      }
    });
  });

  $(document).on('click', '.md-close, .md-overlay', function(event) {
    $('.md-modal').removeClass('md-show');
  });

  // close modal with escape key
  $(document).keyup(function(event) {
    if (event.which == 27) {
      $('.md-modal').removeClass('md-show');
    }
  });

  function attachModalListeners() {
    var json = $('#md-json');
    var leaves = $('#md-json .leaf-container');
    for (var i=0; i<leaves.length; i++) {
      leaves[i] = leaves[i].closest('li');
      var leaf = $(leaves[i]);
      leaf.data('json', true);

      // figure out key value
      var key = leaf.children().html().split(" ")[0];
      var value = leaf.find('.leaf-container span').html().trim();
      var valueWithoutQuotes = value.replace(/"/g,"");
      value = (valueWithoutQuotes == value) ? parseFloat(value) : valueWithoutQuotes;

      var parent = leaf.parent().closest('li');

      while (parent.length != 0) {
        var split = parent.children().html().split(" ");

        // can't flatten arrays well
        if (split[0].match("node-top node-bracket")) {
          leaf.addClass('nkv');
          parent.length = 0;
        } else {
          key = split[0] + "." + key;
          parent = parent.parent().closest('li');
        }
      }
      if (key === '_id.$oid') {
        leaf.parent().closest('li').remove();
      }
      leaf.data('key', "md." + key);
      leaf.data('val', value);
    }

    leaves.addClass('kv');
    leaves.addClass('json-kv');

    // make metadata field editable
    $(document).on('click', '.leaf-container .string, .leaf-container .number', function(event) {
      var leaf = $(this).closest('.ui-draggable');
      if (leaf.data('key') !== 'md.MODELDB_model_id') {
        $(this).attr('contenteditable', 'true');
        leaf.draggable('disable');
        leaf.addClass('editable-content');
        $('.save-button').removeAttr('disabled');
        $('.save-button').text('Save Changes')
      }
    });

    $(document).on('click', '.save-button', function(event) {
      event.stopImmediatePropagation();

      // update the data for each edited field
      $('.editable-content').each(function () {
        $(this).addClass('edited-content');
        var value = $(this).find('.leaf-container span').html().trim();
        var valueWithoutQuotes = value.replace(/"/g,'').replace(' ', ' ');
        value = (valueWithoutQuotes == value) ? parseFloat(value) : valueWithoutQuotes;
        $(this).data('val', value);
      });

      var modelId = $('#md-json').data('modelId');
      var kvPairs = {};
      $('.edited-content').each(function () {
        var key = $(this).data('key').replace('md.', '');
        kvPairs[key] = $(this).data('val');
      });
      editMetadata(modelId, kvPairs);
    });

  }

  function editMetadata(modelId, kvPairs) {
    var data = [];
    data.push({name: 'kvPairs', value: JSON.stringify(kvPairs)});
    $.ajax({
      url: '/models/' + modelId + '/metadata',
      type: "POST",
      data: data,
      dataType: "json",
      success: function(response) {
        $('.save-button').text('Saved');
      },
    });
  };
});<commit_msg>Make array ui editable<commit_after>const GROUPS_SCROLL_DELAY = 5;
$(function() {

/*
 *  Groups bar caret scrolling
 */

  $(document).on('mousedown', '.overflow-up', function() {
    var bar = $('.groups-bar')[0];
    var heightToScroll = bar.scrollTop;
    var delay = heightToScroll * GROUPS_SCROLL_DELAY;

    $('.groups-bar').animate({scrollTop: 0}, delay);
  });

  $(document).on('mouseup', '.overflow-up', function() {
    $('.groups-bar').stop(true);
  });

  $(document).on('mousedown', '.overflow-down', function() {
    var bar = $('.groups-bar')[0];
    var totalHeight = bar.scrollHeight - bar.clientHeight;
    var heightToScroll = totalHeight - bar.scrollTop;
    var delay = heightToScroll * GROUPS_SCROLL_DELAY;

    $('.groups-bar').animate({scrollTop: bar.scrollHeight}, delay);
  });

  $(document).on('mouseup', '.overflow-down', function() {
    $('.groups-bar').stop(true);
  });

  $(document).on('mouseenter', '.group-block', function(event) {
    var block = $(event.target);
    var key = block.data('key');
    var value = block.data('value');
    var num = block.data('num');

    var top = block.offset().top - $($('.groups-bar-container')[0]).offset().top;
    top += (block.height() / 2 - 20);

    var id = $('body').data('id');

    // if grouping by experiment, additionally fetch the description
    if (key == "Experiment ID" || key == "Experiment Run ID") {
      $.ajax({
        url: '/projects/' + id + '/experiments',
        type: "GET",
        success: function(response) {
          var description = null;
          if (key == "Experiment ID") {
            for (var i=0; i<response.experiments.length; i++) {
              if (response.experiments[i].id == value) {
                description = response.experiments[i].description;
              }
            }
          } else if (key == "Experiment Run ID") {
            for (var i=0; i<response.experimentRuns.length; i++) {
              if (response.experimentRuns[i].id == value) {
                description = response.experimentRuns[i].description;
              }
            }
          }

          var obj = {
            'key': key,
            'value': value,
            'num': num,
            'description': description
          };

          var tooltip = $(new EJS({url: '/ejs/group-tooltip.ejs'}).render(obj));
          tooltip.css({'top': top + 'px'});
          $('.groups-bar-container').append(tooltip);
        }
      });
    } else {
      // otherwise, just show tooltip normally
      var obj = {
        'key': key,
        'value': value,
        'num': num,
        'description': null
      };

      var tooltip = $(new EJS({url: '/ejs/group-tooltip.ejs'}).render(obj));
      tooltip.css({'top': top + 'px'});
      $('.groups-bar-container').append(tooltip);
    }
  });

  $(document).on('mouseleave', '.group-block', function() {
    $('.group-tooltip').remove();
  });

  // Model see more listener
  $(document).on('click', '.model-see-more', function(event) {
    var elt = $(event.target);
    var info = elt.parent().find('.model-additional-info');
    var show = elt.data('show');
    if (show) {
      elt.data('show', false);
      elt.html("See More");
      info.slideUp();
      info.animate(
        { opacity: 0 },
        { queue: false, duration: 'slow' }
      );
    } else {
      elt.data('show', true);
      elt.html("See Less");
      info.slideDown();
      info.animate(
        { opacity: 1 },
        { queue: false, duration: 'slow' }
      );
    }
  });

  // filter toggle options
  $(document).on('click', '.filter-expand', function(event) {
    var elt = $(event.target);
    var filter = elt.closest('.filter');
    var options = elt.next('.filter-options');
    if (elt.data('show')) {
      // hide options
      options.slideUp();
      elt.html("▼");
      elt.data('show', false);
    } else {
      // show options
      options.slideDown();
      options.find('input[type="text"]').val(filter.data('val').join(', '));
      options.find('input[type="text"]').focus();
      elt.html("▲");
      elt.data('show', true);
    }
  });

  // show json modal
  $(document).on('click', '.json-md-trigger', function(event) {
    // TODO: duplicate call; avoid
    var modelId = $(event.target).data('id');
    $.ajax({
      url: '/models/' + modelId + '/metadata',
      type: "GET",
      success: function(response) {
        var node = new PrettyJSON.view.Node({
          el:$('#md-json'),
          data:JSON.parse(response)
        });
        node.expandAll();
        var saveButton = $('<button class="save-button" disabled>Save Changes</button>');
        $('#md-json').append(saveButton);
        $('#md-json').data('modelId', modelId);
        $('#modal-2').addClass('md-show');
        attachModalListeners();
        node.collapseAll();
      }
    });
  });

  $(document).on('click', '.md-close, .md-overlay', function(event) {
    $('.md-modal').removeClass('md-show');
  });

  // close modal with escape key
  $(document).keyup(function(event) {
    if (event.which == 27) {
      $('.md-modal').removeClass('md-show');
    }
  });

  function attachModalListeners() {
    var json = $('#md-json');
    var leaves = $('#md-json .leaf-container');
    for (var i=0; i<leaves.length; i++) {
      leaves[i] = leaves[i].closest('li');
      var leaf = $(leaves[i]);
      leaf.data('json', true);

      // figure out key value
      var key = leaf.children().html().split(" ")[0];
      var value = leaf.find('.leaf-container span').html().trim();
      var valueWithoutQuotes = value.replace(/"/g,"");
      value = (valueWithoutQuotes == value) ? parseFloat(value) : valueWithoutQuotes;

      var parent = leaf.parent().closest('li');

      while (parent.length != 0) {
        var split = parent.children().html().split(" ");

        // can't flatten arrays well
        if (split[0].match("node-top node-bracket")) {
          leaf.addClass('nkv');
          parent.length = 0;
        } else {
          key = split[0] + "." + key;
          parent = parent.parent().closest('li');
        }
      }
      if (key === '_id.$oid') {
        leaf.parent().closest('li').remove();
      }
      leaf.data('key', "md." + key);
      leaf.data('val', value);
    }

    leaves.addClass('kv');
    leaves.addClass('json-kv');

    // make metadata field editable
    $(document).on('click', '.leaf-container .string, .leaf-container .number', function(event) {
      var leaf = $(this).closest('.json-kv');
      if (leaf.data('key') !== 'md.MODELDB_model_id') {
        $(this).attr('contenteditable', 'true');
        if (leaf.hasClass('ui-draggable')) {
          leaf.draggable('disable');
        }
        leaf.addClass('editable-content');
        $('.save-button').removeAttr('disabled');
        $('.save-button').text('Save Changes')
      }
    });

    $(document).on('click', '.save-button', function(event) {
      event.stopImmediatePropagation();

      // update the data for each edited field
      $('.editable-content').each(function () {
        $(this).addClass('edited-content');
        var value = $(this).find('.leaf-container span').html().trim();
        var valueWithoutQuotes = value.replace(/"/g,'').replace(' ', ' ');
        value = (valueWithoutQuotes == value) ? parseFloat(value) : valueWithoutQuotes;
        $(this).data('val', value);
      });

      var modelId = $('#md-json').data('modelId');
      var kvPairs = {};
      $('.edited-content').each(function () {
        var key = $(this).data('key').replace('md.', '');
        kvPairs[key] = $(this).data('val');
      });
      console.log('kvPairs', kvPairs)
      editMetadata(modelId, kvPairs);
    });

  }

  function editMetadata(modelId, kvPairs) {
    var data = [];
    data.push({name: 'kvPairs', value: JSON.stringify(kvPairs)});
    $.ajax({
      url: '/models/' + modelId + '/metadata',
      type: "POST",
      data: data,
      dataType: "json",
      success: function(response) {
        $('.save-button').text('Saved');
      },
    });
  };
});<|endoftext|>


<commit_before>var CLOSURE_UNCOMPILED_DEFINES = null;
if(typeof goog == "undefined") document.write('<script src="Scripts/out/goog/base.js"></script>');
document.write('<script src="Scripts/out/cljs_deps.js"></script>');
document.write('<script>if (typeof goog == "undefined") console.warn("ClojureScript could not load :main, did you forget to specify :asset-path?");</script>');
document.write('<script>goog.require("devtools.preload");</script>');

document.write("<script>if (typeof goog != \"undefined\") { goog.require(\"figwheel.connect.build_dev\"); }</script>");
document.write('<script>goog.require("mba.core");</script>');<commit_msg>removed debug js<commit_after><|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commi<commit_msg>Really commit all the required changes<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit<|endoftext|>


<commit_before>/*global define*/
define(
	[ 'config', 'util/dom', 'util/object', 'util/string', 'util/addpublishers', 'lib/reqwest' ],
	function ( config, domHelper, objectHelper, stringHelper, addPublishers, reqwest ) {
		function LocalisationModel () {
			if ( ! ( this instanceof LocalisationModel ) ) {
				return new LocalisationModel();
			}

			var self = this;

			var publishers = addPublishers( self, 'update', 'error' );

			var textElData = [ ];
			var texts = '';
			var currentLanguage = '';

			var animationFrameId = NaN;
			var languageWasLoaded = false;

			var linkOptions = { links: { newTab: true } };

			function setLanguage ( newLanguage ) {
				if ( newLanguage !== currentLanguage && newLanguage in config.availableLanguages ) {
					loadLanguage( newLanguage );
				}
			}

			function loadLanguage ( languageName ) {
				languageWasLoaded = false;

				reqwest( {
					url: config.language.dir + '/' + languageName + '.json',
					type: 'json',
					method: 'get',
					error: function ( err, one, two ) {
						// if this is the first language to load, that's really bad.
						languageWasLoaded = true;
						publishers.error.dispatch( 'I\'m really sorry. I failed to load the language file for ' + languageName + '. This is a serious error that makes the app very hard to use. Maybe you can try reloading?' );
					},
					success: function ( res ) {
						languageLoaded( languageName, res );
					}
				} );
			}

			function languageLoaded ( newLanguageName, newTexts ) {
				currentLanguage = newLanguageName;
				languageWasLoaded = true;
				texts = newTexts;
				resetAllTexts();
				updateAllTexts();
			}

			function updateAllTexts () {
				if ( languageWasLoaded ) {
					cancelAnimationFrame( animationFrameId );

					animationFrameId = requestAnimationFrame( function () {
						var item;
						var args;

						for ( var i = textElData.length - 1; i >= 0; i-- ) {
							item = textElData[i];

							if ( domHelper.isElement( item.el ) ) {
								if ( ! item.wasUpdated ) {
									if ( item.attribute === 'innerHTML' ) {
										item.el.innerHTML = stringHelper.markdownToHtml( getTextForKey( item.key, item.args ), linkOptions );
									} else {
										item.el[item.attribute] = getTextForKey( item.key, item.args );
									}

									item.wasUpdated = true;
								}
							} else {
								textElData.splice( i, 1 );
							}
						}

						publishers.update.dispatch();
					} );
				}
			}

			function resetAllTexts () {
				textElData.forEach( function ( item ) {
					item.wasUpdated = false;
				} );
			}

			function getTextForKey ( key, args ) {
				var result = '';

				try {
					result = objectHelper.getObjectByString( key, texts );
				} catch ( e ) {
					if ( languageWasLoaded ) {
						result = key
					}
				};

				if ( args && args.length ) {
					var regex;

					args.forEach( function ( arg, index ) {
						regex = new RegExp( '{\\$' + ( index + 1 ) + '}' );
						result = result.replace( regex, arg );
					} );
				}

				return result;
			}

			// http://mzl.la/1RDxjVO
			function getArgs ( args, firstIndex ) {
				firstIndex = firstIndex || 3;
				var result;

				if ( args.length > firstIndex ) {
					result = [ ];
				}

				for ( var i = firstIndex, len = args.length; i < len; i++ ) {
					result[result.length] = args[i];
				}

				return result;
			}

			function settingUpdated ( name, value ) {
				if ( name === 'language' && value !== currentLanguage ) {
					loadLanguage( value );
				}
			}

			function localizeText ( el, attribute, key ) {
				if ( el && attribute && key ) {
					textElData.push( { el: el, attribute: attribute, key: key, wasUpdated: false, args: getArgs( arguments ) } );
				} else {
					if ( typeof el === 'string' ) {
						return getTextForKey( el, getArgs( arguments, 1 ) );
					}
				}

				updateAllTexts();
			}

			self.setLanguage = setLanguage;
			self.localizeText = localizeText;
			self.settingUpdated = settingUpdated;
		}

		LocalisationModel.sharedInstance = LocalisationModel();

		return LocalisationModel;
	}
);<commit_msg>move functions<commit_after>/*global define*/
define(
	[ 'config', 'util/dom', 'util/object', 'util/string', 'util/addpublishers', 'lib/reqwest' ],
	function ( config, domHelper, objectHelper, stringHelper, addPublishers, reqwest ) {
		function LocalisationModel () {
			if ( ! ( this instanceof LocalisationModel ) ) {
				return new LocalisationModel();
			}

			var self = this;

			var publishers = addPublishers( self, 'update', 'error' );

			var textElData = [ ];
			var texts = '';
			var currentLanguage = '';

			var animationFrameId = NaN;
			var languageWasLoaded = false;

			var linkOptions = { links: { newTab: true } };

			function setLanguage ( newLanguage ) {
				if ( newLanguage !== currentLanguage && newLanguage in config.availableLanguages ) {
					loadLanguage( newLanguage );
				}
			}

			function settingUpdated ( name, value ) {
				if ( name === 'language' && value !== currentLanguage ) {
					loadLanguage( value );
				}
			}

			function localizeText ( el, attribute, key ) {
				if ( el && attribute && key ) {
					textElData.push( { el: el, attribute: attribute, key: key, wasUpdated: false, args: getArgs( arguments ) } );
				} else {
					if ( typeof el === 'string' ) {
						return getTextForKey( el, getArgs( arguments, 1 ) );
					}
				}

				updateAllTexts();
			}

			function loadLanguage ( languageName ) {
				languageWasLoaded = false;

				reqwest( {
					url: config.language.dir + '/' + languageName + '.json',
					type: 'json',
					method: 'get',
					error: function ( err, one, two ) {
						// if this is the first language to load, that's really bad.
						languageWasLoaded = true;
						publishers.error.dispatch( 'I\'m really sorry. I failed to load the language file for ' + languageName + '. This is a serious error that makes the app very hard to use. Maybe you can try reloading?' );
					},
					success: function ( res ) {
						languageLoaded( languageName, res );
					}
				} );
			}

			function languageLoaded ( newLanguageName, newTexts ) {
				currentLanguage = newLanguageName;
				languageWasLoaded = true;
				texts = newTexts;
				resetAllTexts();
				updateAllTexts();
			}

			function updateAllTexts () {
				if ( languageWasLoaded ) {
					cancelAnimationFrame( animationFrameId );

					animationFrameId = requestAnimationFrame( function () {
						var item;
						var args;

						for ( var i = textElData.length - 1; i >= 0; i-- ) {
							item = textElData[i];

							if ( domHelper.isElement( item.el ) ) {
								if ( ! item.wasUpdated ) {
									if ( item.attribute === 'innerHTML' ) {
										item.el.innerHTML = stringHelper.markdownToHtml( getTextForKey( item.key, item.args ), linkOptions );
									} else {
										item.el[item.attribute] = getTextForKey( item.key, item.args );
									}

									item.wasUpdated = true;
								}
							} else {
								textElData.splice( i, 1 );
							}
						}

						publishers.update.dispatch();
					} );
				}
			}

			function resetAllTexts () {
				textElData.forEach( function ( item ) {
					item.wasUpdated = false;
				} );
			}

			function getTextForKey ( key, args ) {
				var result = '';

				try {
					result = objectHelper.getObjectByString( key, texts );
				} catch ( e ) {
					if ( languageWasLoaded ) {
						result = key
					}
				};

				if ( args && args.length ) {
					var regex;

					args.forEach( function ( arg, index ) {
						regex = new RegExp( '{\\$' + ( index + 1 ) + '}' );
						result = result.replace( regex, arg );
					} );
				}

				return result;
			}

			// http://mzl.la/1RDxjVO
			function getArgs ( args, firstIndex ) {
				firstIndex = firstIndex || 3;
				var result;

				if ( args.length > firstIndex ) {
					result = [ ];
				}

				for ( var i = firstIndex, len = args.length; i < len; i++ ) {
					result[result.length] = args[i];
				}

				return result;
			}

			self.setLanguage = setLanguage;
			self.localizeText = localizeText;
			self.settingUpdated = settingUpdated;
		}

		LocalisationModel.sharedInstance = LocalisationModel();

		return LocalisationModel;
	}
);<|endoftext|>


<commit_before>import api from '../../data/context-api';
import { dispatchAndThrow } from '../util';

export const RECEIVE_CONTEXT = 'RECEIVE_CONTEXT';
export const ERROR_RECEIVE_CONTEXT = 'ERROR_RECEIVE_CONTEXT';
export const REMOVE_CONTEXT = 'REMOVE_CONTEXT';
export const ERROR_REMOVING_CONTEXT = 'ERROR_REMOVING_CONTEXT';
export const ADD_CONTEXT_FIELD = 'ADD_CONTEXT_FIELD';
export const ERROR_ADD_CONTEXT_FIELD = 'ERROR_ADD_CONTEXT_FIELD';
export const UPDATE_CONTEXT_FIELD = 'UPDATE_CONTEXT_FIELD';
export const ERROR_UPDATE_CONTEXT_FIELD = 'ERROR_UPDATE_CONTEXT_FIELD';

const receiveContext = value => ({ type: RECEIVE_CONTEXT, value });
const addContextField = context => ({ type: ADD_CONTEXT_FIELD, context });
const upContextField = context => ({ type: UPDATE_CONTEXT_FIELD, context });
const createRemoveContext = context => ({ type: REMOVE_CONTEXT, context });

export function fetchContext() {
    return dispatch =>
        api
            .fetchAll()
            .then(json => dispatch(receiveContext(json)))
            .catch(dispatchAndThrow(dispatch, ERROR_RECEIVE_CONTEXT));
}

export function removeContextField(context) {
    return dispatch =>
        api
            .remove(context)
            .then(() => dispatch(createRemoveContext(context)))
            .catch(dispatchAndThrow(dispatch, ERROR_REMOVING_CONTEXT));
}

export function createContextField(context) {
    return dispatch =>
        api
            .create(context)
            .then(() => dispatch(addContextField(context)))
            .catch(dispatchAndThrow(dispatch, ERROR_ADD_CONTEXT_FIELD));
}

export function updateContextField(context) {
    return dispatch =>
        api
            .update(context)
            .then(() => dispatch(upContextField(context)))
            .catch(dispatchAndThrow(dispatch, ERROR_UPDATE_CONTEXT_FIELD));
}

export function validateName(name) {
    return api.validate({ name });
}
<commit_msg>fix: fix sort-order<commit_after>import api from '../../data/context-api';
import { dispatchAndThrow } from '../util';

export const RECEIVE_CONTEXT = 'RECEIVE_CONTEXT';
export const ERROR_RECEIVE_CONTEXT = 'ERROR_RECEIVE_CONTEXT';
export const REMOVE_CONTEXT = 'REMOVE_CONTEXT';
export const ERROR_REMOVING_CONTEXT = 'ERROR_REMOVING_CONTEXT';
export const ADD_CONTEXT_FIELD = 'ADD_CONTEXT_FIELD';
export const ERROR_ADD_CONTEXT_FIELD = 'ERROR_ADD_CONTEXT_FIELD';
export const UPDATE_CONTEXT_FIELD = 'UPDATE_CONTEXT_FIELD';
export const ERROR_UPDATE_CONTEXT_FIELD = 'ERROR_UPDATE_CONTEXT_FIELD';

const receiveContext = value => ({ type: RECEIVE_CONTEXT, value });
const addContextField = context => ({ type: ADD_CONTEXT_FIELD, context });
const upContextField = context => ({ type: UPDATE_CONTEXT_FIELD, context });
const createRemoveContext = context => ({ type: REMOVE_CONTEXT, context });

export function fetchContext() {
    return dispatch =>
        api
            .fetchAll()
            .then(json => {
                json.sort((a, b) => a.sortOrder - b.sortOrder);
                dispatch(receiveContext(json))
            })
            .catch(dispatchAndThrow(dispatch, ERROR_RECEIVE_CONTEXT));
}

export function removeContextField(context) {
    return dispatch =>
        api
            .remove(context)
            .then(() => dispatch(createRemoveContext(context)))
            .catch(dispatchAndThrow(dispatch, ERROR_REMOVING_CONTEXT));
}

export function createContextField(context) {
    return dispatch =>
        api
            .create(context)
            .then(() => dispatch(addContextField(context)))
            .catch(dispatchAndThrow(dispatch, ERROR_ADD_CONTEXT_FIELD));
}

export function updateContextField(context) {
    return dispatch =>
        api
            .update(context)
            .then(() => dispatch(upContextField(context)))
            .catch(dispatchAndThrow(dispatch, ERROR_UPDATE_CONTEXT_FIELD));
}

export function validateName(name) {
    return api.validate({ name });
}
<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the int<commit_msg>Ooops!<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the inte<|endoftext|>


<commit_before>var express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors');
var mbaasApi = require('fh-mbaas-api');
var mbaasExpress = mbaasApi.mbaasExpress();
var queryString = require('querystring');
var request = require('request');

function auth() {
  var router = express.Router();

  router.all('/init', function(req, res) {
        var params = req.body; // params.userId params.password
        if (params && params.username) {
          console.log('Checking credentials for user ' + params.username);
          initSession(params.username, function(err, result){
            if (err) {
              console.log('Invalid credentials for user ' + params.username);
              res.status(400);
              res.json({message: 'Invalid credentials'});
              return;
            } else {
              res.json({
                status: 'ok',
                userId: params.username,
                sessionToken: params.username + '_sessiontoken',
                authResponse: result
              });
              return;
            }
          });

        } else {
          res.status(400);
          res.json({message: params.username});
        }

  });

  /**
   * Validate the user's session info with Google, and create a session object.
   * This will also create a account object if necessary.
   *
   * @param {String} idToken an idToken provided by an Android Client (see : https://developers.google.com/identity/sign-in/android/backend-auth)
   * @param {Callback} nodeCallback a node callback
   */
  function initSession(idToken, nodeCallback) {
      //validate with google
      var options = {

          url: 'https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=' + (idToken),
          method: 'GET'
      };

      request(options, handleGoogleResponse(idToken, nodeCallback)).end();

  }

  /**
   *
   * This callback consumes Google's response, and performs the appropriate
   * actions on the session. (Set session optionally creating the account).
   *
   * @param {type} idToken an idToken received from Android
   * @param {type} nodeCallback
   * @returns session Data on callback if successful, error on callback otherwise
   */
  function handleGoogleResponse(idToken, nodeCallback) {
      return function (error, response, body) {

          //the whole response has been recieved, so we just print it out here
          if (error) {
           return nodeCallback(e);
          } else {
            var resObject = JSON.parse(body);
            return checkAccount(resObject, idToken, nodeCallback);
          }

      };
  }

  /**
   * Creates a user if one does not exist
   *
   * @param {Object}  Google user Token response (see : https://developers.google.com/identity/sign-in/android/backend-auth#calling-the-tokeninfo-endpoint)
   * @param {Sting} sessionToken
   * @param {NodeCallback} nodeCallback
   * @returns session Data on callback if successful, error on callback otherwise
   */
  function checkAccount(googleUserToken, sessionToken, nodeCallback) {
      console.log('checkAccountAndCreateSession');
      var handleResults = function (error, responseData) {
        console.log('checkAccountAndCreateSession_callback');
          if (error) {
              return nodeCallback(error, null);
          } else {
              if (!responseData || responseData.count === 0) {
                  //no account, must create.
                  return createAccount(googleUserToken, nodeCallback);
              } else if (responseData.count > 1) {
                  return nodeCallback("error : Too many accounts returned", null);
              } else {
                  return nodeCallback(null, googleUserToken);
              }
          }
      };

      mbaasApi.db({
          "act": "list",
          "type": 'account',
          "eq": {"id": googleUserToken.sub},
      }, handleResults);
  }

  /**
   *  Creates an account and sets the session to that account.
   * @param {Object}  Google user Token response (see : https://developers.google.com/identity/sign-in/android/backend-auth#calling-the-tokeninfo-endpoint)
   * @param {NodeCallback} nodeCallback
   * @returns session Data on callback if successful, error on callback otherwise
   */
  function createAccount(googleUserToken, nodeCallback) {
    authResponse.authToken = '';
      mbaasApi.db({
          "act": "create",
          "type": 'account',
          "fields": [googleUserToken]
      }, function (error, data) {
        console.log('createAccountAndSetSession_cb');
          if (error) {
              return nodeCallback(error);
          } else {
              return nodeCallback(null, googleUserToken);
          }
      });
  }

  return router;

}

module.exports = auth;
<commit_msg>update file /lib/auth.js<commit_after>var express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors');
var mbaasApi = require('fh-mbaas-api');
var mbaasExpress = mbaasApi.mbaasExpress();
var queryString = require('querystring');
var request = require('request');

function auth() {
  var router = express.Router();

  router.all('/init', function(req, res) {
        var params = req.body; // params.userId params.password
        if (params && params.username) {
          console.log('Checking credentials for user ' + params.username);
          initSession(params.username, function(err, result){
            if (err) {
              console.log('Invalid credentials for user ' + params.username);
              res.status(400);
              res.json({message: 'Invalid credentials'});
              return;
            } else {
              res.json({
                status: 'ok',
                userId: params.username,
                sessionToken: params.username + '_sessiontoken',
                authResponse: result
              });
              return;
            }
          });

        } else {
          res.status(400);
          res.json({message: params.username});
        }

  });

  /**
   * Validate the user's session info with Google, and create a session object.
   * This will also create a account object if necessary.
   *
   * @param {String} idToken an idToken provided by an Android Client (see : https://developers.google.com/identity/sign-in/android/backend-auth)
   * @param {Callback} nodeCallback a node callback
   */
  function initSession(idToken, nodeCallback) {
      //validate with google
      var options = {

          url: 'https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=' + (idToken),
          method: 'GET'
      };

      request(options, handleGoogleResponse(idToken, nodeCallback)).end();

  }

  /**
   *
   * This callback consumes Google's response, and performs the appropriate
   * actions on the session. (Set session optionally creating the account).
   *
   * @param {type} idToken an idToken received from Android
   * @param {type} nodeCallback
   * @returns session Data on callback if successful, error on callback otherwise
   */
  function handleGoogleResponse(idToken, nodeCallback) {
      return function (error, response, body) {

          //the whole response has been recieved, so we just print it out here
          if (error) {
           nodeCallback(e);
          } else {
            var resObject = JSON.parse(body);
            checkAccount(resObject, idToken, nodeCallback);
          }

      };
  }

  /**
   * Creates a user if one does not exist
   *
   * @param {Object}  Google user Token response (see : https://developers.google.com/identity/sign-in/android/backend-auth#calling-the-tokeninfo-endpoint)
   * @param {Sting} sessionToken
   * @param {NodeCallback} nodeCallback
   * @returns session Data on callback if successful, error on callback otherwise
   */
  function checkAccount(googleUserToken, sessionToken, nodeCallback) {
      console.log('checkAccountAndCreateSession');
      var handleResults = function (error, responseData) {
        console.log('checkAccountAndCreateSession_callback');
          if (error) {
              nodeCallback(error, null);
          } else {
              if (!responseData || responseData.count === 0) {
                  //no account, must create.
                  createAccount(googleUserToken, nodeCallback);
              } else if (responseData.count > 1) {
                  nodeCallback("error : Too many accounts returned", null);
              } else {
                  nodeCallback(null, googleUserToken);
              }
          }
      };

      mbaasApi.db({
          "act": "list",
          "type": 'account',
          "eq": {"id": googleUserToken.sub},
      }, handleResults);
  }

  /**
   *  Creates an account and sets the session to that account.
   * @param {Object}  Google user Token response (see : https://developers.google.com/identity/sign-in/android/backend-auth#calling-the-tokeninfo-endpoint)
   * @param {NodeCallback} nodeCallback
   * @returns session Data on callback if successful, error on callback otherwise
   */
  function createAccount(googleUserToken, nodeCallback) {
    authResponse.authToken = '';
      mbaasApi.db({
          "act": "create",
          "type": 'account',
          "fields": [googleUserToken]
      }, function (error, data) {
        console.log('createAccountAndSetSession_cb');
          if (error) {
               nodeCallback(error);
          } else {
               nodeCallback(null, googleUserToken);
          }
      });
  }

  return router;

}

module.exports = auth;
<|endoftext|>


<commit_before>'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});
/** Returns an array with the names of the direct names of a function (e.g. for the function a = (b, c) => {}
 *  getFunctionArgNames(a) will return ["b", "c"]).
 *
 *  Credit: https://davidwalsh.name/javascript-arguments
 */
var getFunctionArgNames = function getFunctionArgNames(func) {
    var args = func.toString().match(/function\s.*?\(([^)]*)\)/)[1];
    return args.split(',').map(function (arg) {
        return arg.replace(/\/\*.*\*\//, '').trim();
    }).filter(function (arg) {
        return arg;
    });
};

/** Returns an array with the names of the INDIRECT names of the fields of a function's argument object
 *  (e.g. for the function a = (b, c) => {}
  */
var getFunctionRefsNames = function getFunctionRefsNames(func, ref) {
    var pattern = new RegExp(ref + "\\.([a-zA-Z0-9_]+)[\\,\\;]", 'g');
    var args = func.toString().match(pattern);
    return args && args.map(function (arg) {
        return arg.slice(ref.length + 1, arg.length - 1);
    });
};

exports.default = {
    getArgs: getFunctionArgNames,
    getRefs: getFunctionRefsNames
};<commit_msg>Recompiled lib<commit_after>'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});

var _stringify = require('babel-runtime/core-js/json/stringify');

var _stringify2 = _interopRequireDefault(_stringify);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/** Returns an array with the names of the direct names of a function (e.g. for the function a = (b, c) => {}
 *  getFunctionArgNames(a) will return ["b", "c"]).
 *
 *  Credit: https://davidwalsh.name/javascript-arguments
 */
var getFunctionArgNames = function getFunctionArgNames(func) {
    var args = func.toString().match(/function\s.*?\(([^)]*)\)/)[1];
    return args.split(',').map(function (arg) {
        return arg.replace(/\/\*.*\*\//, '').trim();
    }).filter(function (arg) {
        return arg;
    });
};

/** Returns an array with the names of the INDIRECT names of the fields of a function's argument object
 *  (e.g. for the function a = (b, c) => {}
  */
var getFunctionRefsNames = function getFunctionRefsNames(func, ref) {
    console.log("func:", func.toString);
    console.log("ref:", (0, _stringify2.default)(ref));
    var pattern = new RegExp(ref + "\\.([a-zA-Z0-9_]+)[\\,\\;]", 'g');
    var args = func.toString().match(pattern);
    console.log("args:", (0, _stringify2.default)(args));
    return args && args.map(function (arg) {
        return arg.slice(ref.length + 1, arg.length - 1);
    });
};

exports.default = {
    getArgs: getFunctionArgNames,
    getRefs: getFunctionRefsNames
};<|endoftext|>


<commit_before>'use strict';
/*eslint no-restricted-modules: [0]*/

const fs = require('fs');
const path = require('path');
const request = require('request');

const AVATAR_PATH = path.join(__dirname, '../config/avatars/');

function download_image(image_url, name, extension) {
	request
		.get(image_url)
		.on('error', function (err) {
			console.error(err);
		})
		.on('response', function (response) {
			if (response.statusCode !== 200) return;
			const type = response.headers['content-type'].split('/');
			if (type[0] !== 'image') return;

			response.pipe(fs.createWriteStream(AVATAR_PATH + name + extension));
		});
}

function load_custom_avatars() {
	fs.readdir(AVATAR_PATH, function (err, files) {
		if (!files) files = [];
		files
			.filter(function (file) {
				return ['.jpg', '.png', '.gif'].indexOf(path.extname(file)) >= 0;
			})
			.forEach(function (file) {
				const name = path.basename(file, path.extname(file));
				Config.customavatars[name] = file;
			});
	});
}

load_custom_avatars();

exports.commands = {
	customavatar: {
		set: function (target, room, user) {
			if (!this.can('customavatar')) return false;

			const parts = target.split(',');

			if (parts.length < 2) return this.parse('/help customavatar');

			const name = toId(parts[0]);
			let image_url = parts[1];
			if (image_url.match(/^https?:\/\//i)) image_url = 'http://' + image_url;
			const ext = path.extname(image_url);

			if (!name || !image_url) return this.parse('/help customavatar');
			if (['.jpg', '.png', '.gif'].indexOf(ext) < 0) {
				return this.errorReply("Image url must have .jpg, .png, or .gif extension.");
			}

			Config.customavatars[name] = name + ext;

			download_image(image_url, name, ext);
			this.sendReply(parts[0] + "'s avatar has been set.");
			Users.get(name).popup(user.name + " set's your custom avatar. Refresh your page if you don\'t see it.");
		},

		delete: function (target, room, user) {
			if (!this.can('customavatar')) return false;

			const userid = toId(target);
			const image = Config.customavatars[userid];

			if (!image) {
				return this.errorReply("This user does not have a custom avatar");
			}

			delete Config.customavatars[userid];

			fs.unlink(AVATAR_PATH + image, function (err) {
				if (err && err.code === 'ENOENT') {
					this.errorReply("This user's avatar does not exist.");
				} else if (err) {
					console.error(err);
				}
				this.sendReply("This user's avatar has been successfully removed.");
			}.bind(this));
		},

		'': 'help',
		help: function (target, room, user) {
			this.parse('/help customavatar');
		},
	},
	customavatarhelp: ["Commands for /customavatar are:",
	"/customavatar set [username], [image link] - Set a user's avatar.",
	"/customavatar delete [username] - Delete a user's avatar."],
};
<commit_msg>Fixed crash while setting custom avatars to offline users<commit_after>'use strict';
/*eslint no-restricted-modules: [0]*/

const fs = require('fs');
const path = require('path');
const request = require('request');

const AVATAR_PATH = path.join(__dirname, '../config/avatars/');

function download_image(image_url, name, extension) {
	request
		.get(image_url)
		.on('error', function (err) {
			console.error(err);
		})
		.on('response', function (response) {
			if (response.statusCode !== 200) return;
			const type = response.headers['content-type'].split('/');
			if (type[0] !== 'image') return;

			response.pipe(fs.createWriteStream(AVATAR_PATH + name + extension));
		});
}

function load_custom_avatars() {
	fs.readdir(AVATAR_PATH, function (err, files) {
		if (!files) files = [];
		files
			.filter(function (file) {
				return ['.jpg', '.png', '.gif'].indexOf(path.extname(file)) >= 0;
			})
			.forEach(function (file) {
				const name = path.basename(file, path.extname(file));
				Config.customavatars[name] = file;
			});
	});
}

load_custom_avatars();

exports.commands = {
	customavatar: {
		set: function (target, room, user) {
			if (!this.can('customavatar')) return false;

			const parts = target.split(',');

			if (parts.length < 2) return this.parse('/help customavatar');

			const name = toId(parts[0]);
			let image_url = parts[1];
			if (image_url.match(/^https?:\/\//i)) image_url = 'http://' + image_url;
			const ext = path.extname(image_url);

			if (!name || !image_url) return this.parse('/help customavatar');
			if (['.jpg', '.png', '.gif'].indexOf(ext) < 0) {
				return this.errorReply("Image url must have .jpg, .png, or .gif extension.");
			}

			Config.customavatars[name] = name + ext;

			download_image(image_url, name, ext);
			this.sendReply(parts[0] + "'s avatar has been set.");
			if (Users.get(name) && Users.get(name).connected){
			Users.get(name).popup(user.name + " set's your custom avatar. Refresh your page if you don\'t see it.");
			}
		},

		delete: function (target, room, user) {
			if (!this.can('customavatar')) return false;

			const userid = toId(target);
			const image = Config.customavatars[userid];

			if (!image) {
				return this.errorReply("This user does not have a custom avatar");
			}

			delete Config.customavatars[userid];

			fs.unlink(AVATAR_PATH + image, function (err) {
				if (err && err.code === 'ENOENT') {
					this.errorReply("This user's avatar does not exist.");
				} else if (err) {
					console.error(err);
				}
				this.sendReply("This user's avatar has been successfully removed.");
			}.bind(this));
		},

		'': 'help',
		help: function (target, room, user) {
			this.parse('/help customavatar');
		},
	},
	customavatarhelp: ["Commands for /customavatar are:",
	"/customavatar set [username], [image link] - Set a user's avatar.",
	"/customavatar delete [username] - Delete a user's avatar."],
};
<|endoftext|>


<commit_before><commit_msg>Should work now<commit_after><|endoftext|>