<commit_before>
var   fs = require('graceful-fs')
    , path = require('path')
    , wrench = require('wrench')
    , fse = require('fs-extra')
    , cmd = require('./process')

exports.object_size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

exports.array_union = function(a,b) {
    var r = a.slice(0);
    b.forEach(function(i) { if (r.indexOf(i) < 0) r.push(i); });
    return r;
}

exports.array_diff = function(a,b) {
    return a.filter(function(i) {return b.indexOf(i) < 0;});
}

exports.deep_copy = function deep_copy(obj) {
  return JSON.parse(JSON.stringify(obj));
}

  //copy all of obj_src onto obj_dest overriding existing values
exports.merge_combine = function merge_combine(obj_src, obj_dest) {
  if(!obj_src) return obj_dest;
  for (var p in obj_src) {
    if(obj_dest[p]) {
      if ( obj_src[p].constructor == Object ) {
        obj_dest[p] = merge_combine(obj_src[p], obj_dest[p]);
      } else {
        obj_dest[p] = obj_src[p];
      }
    } else {
      obj_dest[p] = obj_src[p];
    }
  } //each value
  return obj_dest;
} //merge_combine

  //copy all of obj_src onto obj_dest only if the value doesn't exist already
exports.merge_unique = function merge_unique(obj_src, obj_dest) {
  if(!obj_src) return obj_dest;
  for (var p in obj_src) {
    if(obj_dest[p]) {
      if ( obj_src[p].constructor == Object ) {
        obj_dest[p] = merge_unique(obj_src[p], obj_dest[p]);
      }
    } else {
      obj_dest[p] = obj_src[p];
    }
  } //each value
  return obj_dest;
} //merge_unique

//sourced https://github.com/arturadib/shelljs
exports.random_file = function random_file() {

  function random_hash(count) {
    if (count === 1)
      return parseInt(16*Math.random(), 10).toString(16);
    else {
      var hash = '';
      for (var i=0; i<count; i++)
        hash += random_hash(1);
      return hash;
    }
  }

  return 'flow_'+random_hash(20);

} //random_file

exports.pad = function pad(width, string, padding) {
  return (width <= string.length) ? string : exports.pad(width, padding + string, padding)
}

exports.openurl = function(flow, url) {

    if(flow.system == 'windows') {
      cmd.exec(flow, 'start', [ url ]);
    } else if(flow.system == 'mac') {
      cmd.exec(flow, 'open', [ url ]);
    } else {
      cmd.exec(flow, 'xdg-open', [ url, "&" ]);
    }

} //openurl

//file stuff

exports.copy_path = function(flow, source, dest) {

    if(fs.statSync(source).isDirectory()) {
        flow.log(5, '     util - copying folder from %s to %s', source, dest);
        return exports.copy_folder_recursively(flow, source, dest);
    } else {
        flow.log(5, '     util - copying file from %s to %s', source, dest);
        wrench.mkdirSyncRecursive(path.dirname(dest), 0755);
        fse.copySync(source, dest);
        return [ dest ];
    }
}

exports.copy_folder_recursively = function(flow, _source, _dest, _overwrite) {

    var copied_list = [];

    if(_overwrite == undefined) _overwrite = true;

        //make sure the destination exists
        //before copying any files to the location
    wrench.mkdirSyncRecursive(_dest, 0755);

        //obtain a list of items from the source
    var _source_list = wrench.readdirSyncRecursive(path.resolve(flow.run_path, _source));

        //for each source item, check if it's a directory
    var _source_file_list = [];

    for(var i = 0; i < _source_list.length; ++i) {
        var _is_dir = fs.statSync( path.join(_source, _source_list[i]) ).isDirectory();
        if(!_is_dir) {
            var allow = _source_list[i].charAt(0) != '.' || !flow.config.build.files_ignore_dotfiles;
            if(allow) {
              _source_file_list.push(_source_list[i]);
            }
        }
    }

        //for each file only, copy it across
    for(var i = 0; i < _source_file_list.length; ++i) {
        var _dest_file = path.join(_dest,_source_file_list[i]);
        fse.ensureFileSync(_dest_file);
        var source_path = path.join(_source, _source_file_list[i]);
        flow.log(3,'        - copying ' + source_path + ' to ' + _dest_file );
        fse.copySync( source_path, _dest_file );
        copied_list.push( _dest_file );
    }

    return copied_list;

} //copy_folder_recursively
<commit_msg>fixing command for linux web running<commit_after>
var   fs = require('graceful-fs')
    , path = require('path')
    , wrench = require('wrench')
    , fse = require('fs-extra')
    , cmd = require('./process')

exports.object_size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

exports.array_union = function(a,b) {
    var r = a.slice(0);
    b.forEach(function(i) { if (r.indexOf(i) < 0) r.push(i); });
    return r;
}

exports.array_diff = function(a,b) {
    return a.filter(function(i) {return b.indexOf(i) < 0;});
}

exports.deep_copy = function deep_copy(obj) {
  return JSON.parse(JSON.stringify(obj));
}

  //copy all of obj_src onto obj_dest overriding existing values
exports.merge_combine = function merge_combine(obj_src, obj_dest) {
  if(!obj_src) return obj_dest;
  for (var p in obj_src) {
    if(obj_dest[p]) {
      if ( obj_src[p].constructor == Object ) {
        obj_dest[p] = merge_combine(obj_src[p], obj_dest[p]);
      } else {
        obj_dest[p] = obj_src[p];
      }
    } else {
      obj_dest[p] = obj_src[p];
    }
  } //each value
  return obj_dest;
} //merge_combine

  //copy all of obj_src onto obj_dest only if the value doesn't exist already
exports.merge_unique = function merge_unique(obj_src, obj_dest) {
  if(!obj_src) return obj_dest;
  for (var p in obj_src) {
    if(obj_dest[p]) {
      if ( obj_src[p].constructor == Object ) {
        obj_dest[p] = merge_unique(obj_src[p], obj_dest[p]);
      }
    } else {
      obj_dest[p] = obj_src[p];
    }
  } //each value
  return obj_dest;
} //merge_unique

//sourced https://github.com/arturadib/shelljs
exports.random_file = function random_file() {

  function random_hash(count) {
    if (count === 1)
      return parseInt(16*Math.random(), 10).toString(16);
    else {
      var hash = '';
      for (var i=0; i<count; i++)
        hash += random_hash(1);
      return hash;
    }
  }

  return 'flow_'+random_hash(20);

} //random_file

exports.pad = function pad(width, string, padding) {
  return (width <= string.length) ? string : exports.pad(width, padding + string, padding)
}

exports.openurl = function(flow, url) {

    if(flow.system == 'windows') {
      cmd.exec(flow, 'start', [ url ]);
    } else if(flow.system == 'mac') {
      cmd.exec(flow, 'open', [ url ]);
    } else {
      cmd.exec(flow, 'xdg-open', [ url ]);
    }

} //openurl

//file stuff

exports.copy_path = function(flow, source, dest) {

    if(fs.statSync(source).isDirectory()) {
        flow.log(5, '     util - copying folder from %s to %s', source, dest);
        return exports.copy_folder_recursively(flow, source, dest);
    } else {
        flow.log(5, '     util - copying file from %s to %s', source, dest);
        wrench.mkdirSyncRecursive(path.dirname(dest), 0755);
        fse.copySync(source, dest);
        return [ dest ];
    }
}

exports.copy_folder_recursively = function(flow, _source, _dest, _overwrite) {

    var copied_list = [];

    if(_overwrite == undefined) _overwrite = true;

        //make sure the destination exists
        //before copying any files to the location
    wrench.mkdirSyncRecursive(_dest, 0755);

        //obtain a list of items from the source
    var _source_list = wrench.readdirSyncRecursive(path.resolve(flow.run_path, _source));

        //for each source item, check if it's a directory
    var _source_file_list = [];

    for(var i = 0; i < _source_list.length; ++i) {
        var _is_dir = fs.statSync( path.join(_source, _source_list[i]) ).isDirectory();
        if(!_is_dir) {
            var allow = _source_list[i].charAt(0) != '.' || !flow.config.build.files_ignore_dotfiles;
            if(allow) {
              _source_file_list.push(_source_list[i]);
            }
        }
    }

        //for each file only, copy it across
    for(var i = 0; i < _source_file_list.length; ++i) {
        var _dest_file = path.join(_dest,_source_file_list[i]);
        fse.ensureFileSync(_dest_file);
        var source_path = path.join(_source, _source_file_list[i]);
        flow.log(3,'        - copying ' + source_path + ' to ' + _dest_file );
        fse.copySync( source_path, _dest_file );
        copied_list.push( _dest_file );
    }

    return copied_list;

} //copy_folder_recursively
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2016 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(adamvy):
- Only serialize the ordinal?
- Freeze the instances?
*/

/**
 * For those familiar with Java, FOAM Enums are very similar to Java enums in design.
 *
 * An Enum is essentially a class with a fixed number of named instances.  The instances
 * are frequently referred to as Enum Values, or the 'values' of an Enum.
 *
 * Enums have most of the features available to FOAM classes, including properties, methods,
 * constants, templates, and listeners.
 *
 * Enums extend from FObject, so they inherit FObject features such as pub/sub events,
 * diffing, hashCode, etc.
 *
 * Enums also have a few built-in properties by default.  Every Enum has an 'ordinal'
 * property, which is a integer unique to all the Enum Values of a a particular Enum.  Each
 * enum also has a 'name' property, which is the name given to each Enum Value.
 *
 *
 * Example usage:
 *

 * // To define an enum we use the foam.ENUM() function.
 * foam.ENUM({
 *   name: 'IssueStatus',
 *
 *   // Enums share many features with regular classes, the properties
 *   // and methods we want our enums to have are defined as follows.
 *   properties: [
 *     {
 *       class: 'Boolean',
 *       name: 'consideredOpen',
 *       value: true
 *     }
 *   ],
 *   methods: [
 *     function foo() {
 *       return this.label + ( this.consideredOpen ? ' is' : ' is not' ) +
 *           ' considered open.';
 *     }
 *   ],
 *
 *   // Use the values: key to define the actual Enum Values that we want to exist.
 *   values: [
 *     {
 *       name: 'OPEN',
 *     },
 *     {
 *       // The ordinal can be specified explicitly.
 *       name: 'CLOSED',
 *       ordinal: 100,
 *     },
 *     {
 *       // If the ordinal isn't given explicitly it is auto assigned as the previous
 *       // ordinal + 1
 *       name: 'ASSIGNED',
 *     },
 *     {
 *       // You can specify the label, which will be used when rendering in a
 *       // combo box or similar
 *       name: 'UNVERIFIED',
 *       label: 'Unverified'
 *     },
 *     {
 *       // Values for additional properties to your enum are also defined
 *       // inline.
 *       name: 'FIXED',
 *       label: 'Fixed',
 *       consideredOpen: false
 *     }
 *   ]
 * });
 *
 * console.log(IssueStatus.OPEN.name); // outputs "OPEN"
 * console.log(IssueStatus.ASSIGNED.consideredOpen); // outputs "true"
 *
 * // Enum value ordinals can be specified.
 * console.log(IssueStatus.CLOSED.ordinal); // outputs 100
 * // values without specified ordinals get auto assigned.
 * console.log(IssueStatus.ASSIGNED.ordinal); // outputs 101
 *
 * // Methods can be called on the enum values.
 * console.log(IssueStatus.FIXED.foo()); // outputs "Fixed is not considered open.")
 *
 * // To store enums on a class, it is recommended to use the Enum property
 * // type.
 * foam.CLASS({
 *   name: 'Issue',
 *   properties: [
 *     {
 *       class: 'Enum',
 *       of: 'Status',
 *       name: 'status'
 *     }
 *   ]
 * });
 *
 * var issue = Issue.create({ status: IssueStatus.UNVERIFIED });
 * console.log(issue.status.label); // outputs "Unverified"
 *
 * // Enum properties give you some convenient adapting.
 * // You can set the property to the ordinal or the
 * // name of an enum, and it will set the property
 * // to the correct Enum value.
 *
 * issue.status = 100;
 *
 * issue.status === IssueStatus.CLOSED; // is true
 *
 * // Enum properties also allow you to assign them via the name
 * // of the enum.
 *
 * issue.status = "ASSIGNED"
 *
 * issue.status === IssueStatus.ASSIGNED; // is true
 *

 */

foam.CLASS({
  package: 'foam.core.internal',
  name: 'EnumValue',

  properties: [
    {
      class: 'String',
      name: 'name',
      preSet: function(_, s) {
        return foam.String.constantize(s);
      }
    },
    {
      class: 'String',
      name: 'label'
    },
    {
      class: 'Int',
      name: 'ordinal'
    },
    {
      name: 'values'
    }
  ],

  methods: [
    function installInClass(cls) {
      var name    = this.name;
      var ordinal = this.ordinal;

      Object.defineProperty(
        cls,
        name,
        {
          configurable: true,
          get: function() {
            return cls.create({ ordinal: ordinal });
          }
        });
    },

    function installInProto(proto) {
      this.installInClass(proto);
    },

    function initArgs(args, ctx) {
      this.values = args;
      this.SUPER(args, ctx);
    }
  ]
});

foam.CLASS({
  package: 'foam.core',
  name: 'EnumModel',

  properties: [
    {
      name: 'axioms_',
      transient: true,
      factory: function() {
        return [
          foam.core.Int.create({
            name: 'ordinal',
            final: true
          }),
          foam.core.String.create({
            name: 'name',
            final: true
          }),
          foam.core.String.create({
            name: 'label',
            final: true
          }),
          foam.core.Method.create({
            name: 'toString',
            code: function() {
              return this.name;
            }
          }),
          {
            name: 'enum_create',
            installInClass: function(cls) {
              var instances = {};
              var oldCreate = cls.create;

              cls.create = function(args, ctx) {
                var key = args.ordinal || 0; // use default if not specified

                // Short-circuit if we already create the instance for this ordinal.
                if ( instances[key] ) return instances[key];

                var enumValue = cls.model_.values.find(function(o) {
                  return o.ordinal === key;
                });

                foam.__context__.assert(enumValue, 'No enum value found with ordinal', key);
                var args = enumValue.values;
                args.ordinal = key;
                args.name = enumValue.name;

                return instances[key] = oldCreate.call(this, args, ctx);
              };
            }
          }
        ];
      }
    },
    {
      class: 'String',
      name: 'name'
    },
    {
      class: 'String',
      name: 'package'
    },
    {
      class: 'String',
      name: 'id',
      expression: function(name, package) {
        return package ? package + '.' + name : name;
      }
    },
    {
      class: 'AxiomArray',
      of: 'foam.core.Property',
      name: 'properties',
      adaptArrayElement: function(o) {
        if ( typeof o === 'string' ) {
          var p = foam.core.Property.create();
          p.name = o;
          return p;
        }

        if ( Array.isArray(o) ) {
          var p = foam.core.Property.create();
          p.name  = o[0];
          p.value = o[1];
          return p;
        }

        if ( o.class ) {
          var m = foam.lookup(o.class);
          if ( ! m ) throw 'Unknown class : ' + o.class;
          return m.create(o);
        }

        return foam.core.Property.create(o);
      }
    },
    {
      class: 'AxiomArray',
      of: 'foam.core.Method',
      name: 'methods',
      adaptArrayElement: function(o) {
        if ( typeof o === 'function' ) {
          console.assert(o.name, 'Method must be named');
          var m = foam.core.Method.create();
          m.name = o.name;
          m.code = o;
          return m;
        }
        return foam.core.Method.create(o);
      }
    },
    {
      class: 'AxiomArray',
      of: 'foam.core.Constant',
      name: 'constants'
    },
    {
      class: 'AxiomArray',
      of: 'foam.core.Listener',
      name: 'listeners'
    },
    {
      class: 'AxiomArray',
      of: 'foam.core.Action',
      name: 'actions'
    },
    {
      class: 'AxiomArray',
      of: 'foam.core.internal.EnumValue',
      name: 'values',
      preSet: function(_, v) {
        var used = {};

        var next = 0;
        for ( var i = 0 ; i < v.length ; i++ ) {
          if ( ! v[i].hasOwnProperty('ordinal') ) v[i].ordinal = next++;
          else next = v[i].ordinal + 1;
          this.assert(
            ! used[v[i].ordinal],
            this.id,
            'Enum error: duplicate ordinal found', v[i].name,
            used[v[i].ordinal], 'both have an ordinal of', v[i].ordinal);

          used[v[i].ordinal] = v[i].name;
        }

        return v;
      }
    }
  ],

  methods: [
    function buildClass() {
      var cls;

      var parent = foam.core.FObject;

      cls = Object.create(parent);
      cls.prototype = Object.create(parent.prototype);
      cls.prototype.cls_ = cls;
      cls.prototype.model_ = this;
      cls.private_ = { axiomCache: {} };
      cls.axiomMap_ = Object.create(parent.axiomMap_);
      cls.id = this.id;
      cls.package = this.package;
      cls.name = this.name;
      cls.model_ = this;

      cls.installModel(this);

      var values;
      var model = this;

      cls.getValues = function() {
        if ( ! values ) {
          values = model.values.map(function(m) {
            return cls[m.name];
          });
        }
        return values;
      }

      return cls;
    }
  ]
});

// TODO(adamvy): Support default values.
foam.CLASS({
  package: 'foam.core',
  name: 'Enum',
  extends: 'Property',

  properties: [
    { name: 'of', required: true },
    [
      'adapt',
      function(old, nu, prop) {
        var type = foam.typeOf(nu);
        if ( type === foam.FObject ) {
          return nu;
        }

        var e = this.__context__.lookup(prop.of);

        if ( type === foam.String ) {
          return e[foam.String.constantize(nu)];
        } else if ( type === foam.Number ) {
          return e.create({ ordinal: nu });
        }
      }
    ]
  ]
});

foam.LIB({
  name: 'foam',

  methods: [
    function ENUM(m) {
      var model = foam.core.EnumModel.create(m);
      model.validate();
      var cls = model.buildClass();
      cls.validate();

      foam.register(cls);
      foam.package.registerClass(cls);

      return cls;
    }
  ]
});
<commit_msg>Cleanup Enum Property adapt method.<commit_after>/**
 * @license
 * Copyright 2016 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(adamvy):
- Only serialize the ordinal?
- Freeze the instances?
*/

/**
 * For those familiar with Java, FOAM Enums are very similar to Java enums in design.
 *
 * An Enum is essentially a class with a fixed number of named instances.  The instances
 * are frequently referred to as Enum Values, or the 'values' of an Enum.
 *
 * Enums have most of the features available to FOAM classes, including properties, methods,
 * constants, templates, and listeners.
 *
 * Enums extend from FObject, so they inherit FObject features such as pub/sub events,
 * diffing, hashCode, etc.
 *
 * Enums also have a few built-in properties by default.  Every Enum has an 'ordinal'
 * property, which is a integer unique to all the Enum Values of a a particular Enum.  Each
 * enum also has a 'name' property, which is the name given to each Enum Value.
 *
 *
 * Example usage:
 *

 * // To define an enum we use the foam.ENUM() function.
 * foam.ENUM({
 *   name: 'IssueStatus',
 *
 *   // Enums share many features with regular classes, the properties
 *   // and methods we want our enums to have are defined as follows.
 *   properties: [
 *     {
 *       class: 'Boolean',
 *       name: 'consideredOpen',
 *       value: true
 *     }
 *   ],
 *   methods: [
 *     function foo() {
 *       return this.label + ( this.consideredOpen ? ' is' : ' is not' ) +
 *           ' considered open.';
 *     }
 *   ],
 *
 *   // Use the values: key to define the actual Enum Values that we want to exist.
 *   values: [
 *     {
 *       name: 'OPEN',
 *     },
 *     {
 *       // The ordinal can be specified explicitly.
 *       name: 'CLOSED',
 *       ordinal: 100,
 *     },
 *     {
 *       // If the ordinal isn't given explicitly it is auto assigned as the previous
 *       // ordinal + 1
 *       name: 'ASSIGNED',
 *     },
 *     {
 *       // You can specify the label, which will be used when rendering in a
 *       // combo box or similar
 *       name: 'UNVERIFIED',
 *       label: 'Unverified'
 *     },
 *     {
 *       // Values for additional properties to your enum are also defined
 *       // inline.
 *       name: 'FIXED',
 *       label: 'Fixed',
 *       consideredOpen: false
 *     }
 *   ]
 * });
 *
 * console.log(IssueStatus.OPEN.name); // outputs "OPEN"
 * console.log(IssueStatus.ASSIGNED.consideredOpen); // outputs "true"
 *
 * // Enum value ordinals can be specified.
 * console.log(IssueStatus.CLOSED.ordinal); // outputs 100
 * // values without specified ordinals get auto assigned.
 * console.log(IssueStatus.ASSIGNED.ordinal); // outputs 101
 *
 * // Methods can be called on the enum values.
 * console.log(IssueStatus.FIXED.foo()); // outputs "Fixed is not considered open.")
 *
 * // To store enums on a class, it is recommended to use the Enum property
 * // type.
 * foam.CLASS({
 *   name: 'Issue',
 *   properties: [
 *     {
 *       class: 'Enum',
 *       of: 'Status',
 *       name: 'status'
 *     }
 *   ]
 * });
 *
 * var issue = Issue.create({ status: IssueStatus.UNVERIFIED });
 * console.log(issue.status.label); // outputs "Unverified"
 *
 * // Enum properties give you some convenient adapting.
 * // You can set the property to the ordinal or the
 * // name of an enum, and it will set the property
 * // to the correct Enum value.
 *
 * issue.status = 100;
 *
 * issue.status === IssueStatus.CLOSED; // is true
 *
 * // Enum properties also allow you to assign them via the name
 * // of the enum.
 *
 * issue.status = "ASSIGNED"
 *
 * issue.status === IssueStatus.ASSIGNED; // is true
 *

 */

foam.CLASS({
  package: 'foam.core.internal',
  name: 'EnumValue',

  properties: [
    {
      class: 'String',
      name: 'name',
      preSet: function(_, s) {
        return foam.String.constantize(s);
      }
    },
    {
      class: 'String',
      name: 'label'
    },
    {
      class: 'Int',
      name: 'ordinal'
    },
    {
      name: 'values'
    }
  ],

  methods: [
    function installInClass(cls) {
      var name    = this.name;
      var ordinal = this.ordinal;

      Object.defineProperty(
        cls,
        name,
        {
          configurable: true,
          get: function() {
            return cls.create({ ordinal: ordinal });
          }
        });
    },

    function installInProto(proto) {
      this.installInClass(proto);
    },

    function initArgs(args, ctx) {
      this.values = args;
      this.SUPER(args, ctx);
    }
  ]
});

foam.CLASS({
  package: 'foam.core',
  name: 'EnumModel',

  properties: [
    {
      name: 'axioms_',
      transient: true,
      factory: function() {
        return [
          foam.core.Int.create({
            name: 'ordinal',
            final: true
          }),
          foam.core.String.create({
            name: 'name',
            final: true
          }),
          foam.core.String.create({
            name: 'label',
            final: true
          }),
          foam.core.Method.create({
            name: 'toString',
            code: function() {
              return this.name;
            }
          }),
          {
            name: 'enum_create',
            installInClass: function(cls) {
              var instances = {};
              var oldCreate = cls.create;

              cls.create = function(args, ctx) {
                var key = args.ordinal || 0; // use default if not specified

                // Short-circuit if we already create the instance for this ordinal.
                if ( instances[key] ) return instances[key];

                var enumValue = cls.model_.values.find(function(o) {
                  return o.ordinal === key;
                });

                foam.__context__.assert(enumValue, 'No enum value found with ordinal', key);
                var args = enumValue.values;
                args.ordinal = key;
                args.name = enumValue.name;

                return instances[key] = oldCreate.call(this, args, ctx);
              };
            }
          }
        ];
      }
    },
    {
      class: 'String',
      name: 'name'
    },
    {
      class: 'String',
      name: 'package'
    },
    {
      class: 'String',
      name: 'id',
      expression: function(name, package) {
        return package ? package + '.' + name : name;
      }
    },
    {
      class: 'AxiomArray',
      of: 'foam.core.Property',
      name: 'properties',
      adaptArrayElement: function(o) {
        if ( typeof o === 'string' ) {
          var p = foam.core.Property.create();
          p.name = o;
          return p;
        }

        if ( Array.isArray(o) ) {
          var p = foam.core.Property.create();
          p.name  = o[0];
          p.value = o[1];
          return p;
        }

        if ( o.class ) {
          var m = foam.lookup(o.class);
          if ( ! m ) throw 'Unknown class : ' + o.class;
          return m.create(o);
        }

        return foam.core.Property.create(o);
      }
    },
    {
      class: 'AxiomArray',
      of: 'foam.core.Method',
      name: 'methods',
      adaptArrayElement: function(o) {
        if ( typeof o === 'function' ) {
          console.assert(o.name, 'Method must be named');
          var m = foam.core.Method.create();
          m.name = o.name;
          m.code = o;
          return m;
        }
        return foam.core.Method.create(o);
      }
    },
    {
      class: 'AxiomArray',
      of: 'foam.core.Constant',
      name: 'constants'
    },
    {
      class: 'AxiomArray',
      of: 'foam.core.Listener',
      name: 'listeners'
    },
    {
      class: 'AxiomArray',
      of: 'foam.core.Action',
      name: 'actions'
    },
    {
      class: 'AxiomArray',
      of: 'foam.core.internal.EnumValue',
      name: 'values',
      preSet: function(_, v) {
        var used = {};

        var next = 0;
        for ( var i = 0 ; i < v.length ; i++ ) {
          if ( ! v[i].hasOwnProperty('ordinal') ) v[i].ordinal = next++;
          else next = v[i].ordinal + 1;
          this.assert(
            ! used[v[i].ordinal],
            this.id,
            'Enum error: duplicate ordinal found', v[i].name,
            used[v[i].ordinal], 'both have an ordinal of', v[i].ordinal);

          used[v[i].ordinal] = v[i].name;
        }

        return v;
      }
    }
  ],

  methods: [
    function buildClass() {
      var cls;

      var parent = foam.core.FObject;

      cls = Object.create(parent);
      cls.prototype = Object.create(parent.prototype);
      cls.prototype.cls_ = cls;
      cls.prototype.model_ = this;
      cls.private_ = { axiomCache: {} };
      cls.axiomMap_ = Object.create(parent.axiomMap_);
      cls.id = this.id;
      cls.package = this.package;
      cls.name = this.name;
      cls.model_ = this;

      cls.installModel(this);

      var values;
      var model = this;

      cls.getValues = function() {
        if ( ! values ) {
          values = model.values.map(function(m) {
            return cls[m.name];
          });
        }
        return values;
      }

      return cls;
    }
  ]
});

// TODO(adamvy): Support default values.
foam.CLASS({
  package: 'foam.core',
  name: 'Enum',
  extends: 'Property',

  properties: [
    { name: 'of', required: true },
    [
      'adapt',
      function(o, n, prop) {
        if ( foam.core.FObject.isInstance(n) ) return n;

        var type = foam.typeOf(nu);
        var e    = this.__context__.lookup(prop.of);

        if ( type === foam.String ) return e[foam.String.constantize(n)];
        if ( type === foam.Number ) return e.create({ordinal: n});
      }
    ]
  ]
});

foam.LIB({
  name: 'foam',

  methods: [
    function ENUM(m) {
      var model = foam.core.EnumModel.create(m);
      model.validate();
      var cls = model.buildClass();
      cls.validate();

      foam.register(cls);
      foam.package.registerClass(cls);

      return cls;
    }
  ]
});
<|endoftext|>


<commit_before>function Mode() {
    this.ID = -1;
    this.name = "Blank";
    this.decayMod = 1.0; // Modifier for decay rate (Multiplier)
    this.packetLB = 49; // Packet id for leaderboard packet (48 = Text List, 49 = List, 50 = Pie chart)
    this.haveTeams = false; // True = gamemode uses teams, false = gamemode doesnt use teams
    this.specByLeaderboard = false; // false = spectate from player list instead of leaderboard
}

module.exports = Mode;

// Override these

Mode.prototype.onServerInit = function (gameServer) {
    // Called when the server starts
    gameServer.run = true;
};

Mode.prototype.onTick = function (gameServer) {
    // Called on every game tick
};

Mode.prototype.onPlayerInit = function (player) {
    // Called after a player object is constructed
};

Mode.prototype.onPlayerSpawn = function (gameServer, player) {
    // Called when a player is spawned
    player.setColor(gameServer.getRandomColor()); // Random color
    gameServer.spawnPlayer(player, gameServer.randomPos());
};

Mode.prototype.onCellAdd = function (cell) {
    // Called when a player cell is added
};

Mode.prototype.onCellRemove = function (cell) {
    // Called when a player cell is removed
};

Mode.prototype.onCellMove = function (cell, gameServer) {
    // Called when a player cell is moved
};

Mode.prototype.updateLB = function (gameServer) {
    // Called when the leaderboard update function is called
    gameServer.leaderboardType = this.packetLB;
};
<commit_msg>Update Mode.js<commit_after>function Mode() {
    this.ID = -1;
    this.name = "Blank";
    this.decayMod = 1.0; // Modifier for decay rate (Multiplier)
    this.packetLB = 49; // Packet id for leaderboard packet (48 = Text List, 49 = List, 50 = Pie chart)
    this.haveTeams = false; // True = gamemode uses teams, false = gamemode doesnt use teams
    this.specByLeaderboard = false; // false = spectate from player list instead of leaderboard
    this.lastmanStanding = false;
}

module.exports = Mode;

// Override these

Mode.prototype.onServerInit = function (gameServer) {
    // Called when the server starts
    gameServer.run = true;
       if (gameServer.config.lastManStanding == 1) {
        var short = 15 * 60000; // 15 Minutes
        var long = 60 * 60000; // 60 Minutes
        var time = Math.floor((Math.random() * (long - short)) + short);
        var shortreset = 15;
        var longreset = 30;
        var resetTime = (Math.floor((Math.random() * (longreset - shortreset)) + shortreset)) + time;
        var startInt = setInterval(function() {self.lastManStandingstart()}, time);
        var endInt = setInterval(function() {self.lastManStandingend()}, resetTime);
     }
};

Mode.prototype.lastManStandingstart = function(gameServer) {
     this.lastManStandingStart = true;
 };

 Mode.prototype.lastManStandingend = function(gameServer) {
     this.lastManStandingStart = false;
 };

Mode.prototype.onTick = function (gameServer) {
    // Called on every game tick
};

Mode.prototype.onPlayerInit = function (player) {
    // Called after a player object is constructed
};

Mode.prototype.onPlayerSpawn = function (gameServer, player) {
    // Called when a player is spawned
    if (!this.lastmanstanding){
    player.setColor(gameServer.getRandomColor()); // Random color
    gameServer.spawnPlayer(player, gameServer.randomPos());
    }
    };

Mode.prototype.onCellAdd = function (cell) {
    // Called when a player cell is added
};

Mode.prototype.onCellRemove = function (cell) {
    // Called when a player cell is removed
};

Mode.prototype.onCellMove = function (cell, gameServer) {
    // Called when a player cell is moved
};

Mode.prototype.updateLB = function (gameServer) {
    // Called when the leaderboard update function is called
    gameServer.leaderboardType = this.packetLB;
};
<|endoftext|>


<commit_before>// declare our dependencies
const entries = require('object.entries');
const natural = require('natural');

class Index {
  constructor() {
    this.invertedIndexObj = { };
    this.invertedIndex = { };
  }

 /**
  * Takes data from a JSON file an returns the JSON object
  * @param {string} content,
  * @returns {} the file content as JSON
  */
  readJsonFile(content) {
    this.file = content;
    if (Object.keys(this.file).length === 0) {
      throw new Error('the file is empty');
    }
    try {
      this.jsonContent = JSON.parse(this.file);
    } catch (e) {
      throw new Error('Invalid json file');
    }
    for (let i = 0; i < this.jsonContent.length; i += 1) {
      if (!('title' in this.jsonContent[i] && 'text' in this.jsonContent[i])) {
        throw new Error('Bad JSON format');
      }
    }
    return this.jsonContent;
  }

  /**
  * Takes a JSON filename and creates an Inverted Index
  * @param {string} content - the JSON file content
  * @param {string} filename
  */
  createIndex(content, filename) {
    let term = [];
    this.invertedIndex = {};
    // get json file content assign to index
    const index = this.readJsonFile(content);
    for (let i = 0; i < index.length; i += 1) {
      term = index[i];
      let terms = `${term.title} ${term.text}`;
      // process text to remove repetition, special characters & (lower case)
      terms = this.processText(terms);
      for (let j = 0; j < terms.length; j += 1) {
        if (!(terms[j] in this.invertedIndex)) {
          this.invertedIndex[terms[j]] = [i];
        } else if (!(i in this.invertedIndex[terms[j]])) {
          this.invertedIndex[terms[j]].push(i);
        }
      }
    }
    // assign filename as the key & inverted index object as value
    this.invertedIndexObj[filename] = this.invertedIndex;
  }

  /**
  * Takes text and processes to lowercase, removes non-alphanumeric characters,
  * and removes dublicate words
  * @param {string} text
  * @returns array normalised Text
  */
  processText(text) {
    const normalised = text.replace(/[^a-z0-9 ]/gi, '').toLowerCase().split(' ');
    let normalisedText = new Set(normalised);
    normalisedText = Array.from(normalisedText);
    return normalisedText;
  }
  /**
   * Normalizes Data
   * @param {terms} a word to normalize.
   * @returns string  - normalized word.
   */
  search(term) {
    return natural.PorterStemmer.stem(term);
  }
  /**
  * Searches inverted index
  * @param {words} title - extended parameters.
  * @returns { } searchresults - Object of search results.
  */
  searchIndex(...words) {
    let file = [];
    this.searchResults = {};
    let terms = words.toString().split(',').join(' ');
    terms = this.processText(terms);
    for (const [key, value] of entries(this.invertedIndexObj)) {
      const termResults = {};
      for (const term of terms) {
        if (this.search(term) in value) {
          termResults[this.search(term)] = value[this.search(term)];
        } else if (term in value) {
          termResults[term] = value[term];
        }
      }
      if (Object.keys(termResults).length === 0 && termResults.constructor === Object) {
        termResults.Results = `No records found for: ${terms.toString().split(',').join(' ')}`;
      }
      this.searchResults[key] = termResults;
    }
    if (words[0] === undefined || words[0] === null) {
      return this.searchResults;
    } else if (words[0].toString().match(/^.*json$/)) {
      file = words[0].toString().match(/^.*json$/);
      if (file in this.searchResults) {
        const tempResults = this.searchResults;
        this.searchResults = {};
        this.searchResults[file] = tempResults[file];
      }
    }
    return this.searchResults;
  }

  /**
   * Returns Inverted index object.
   */
  getIndex() {
    return this.invertedIndexObj;
  }
}

// export values
exports.Index = Index;
<commit_msg>removes let, use const instead<commit_after>// declare our dependencies
const entries = require('object.entries');
const natural = require('natural');

class Index {
  constructor() {
    this.invertedIndexObj = { };
    this.invertedIndex = { };
  }

 /**
  * Takes data from a JSON file an returns the JSON object
  * @param {string} content,
  * @returns {} the file content as JSON
  */
  readJsonFile(content) {
    this.file = content;
    if (Object.keys(this.file).length === 0) {
      throw new Error('the file is empty');
    }
    try {
      this.jsonContent = JSON.parse(this.file);
    } catch (e) {
      throw new Error('Invalid json file');
    }
    for (let i = 0; i < this.jsonContent.length; i += 1) {
      if (!('title' in this.jsonContent[i] && 'text' in this.jsonContent[i])) {
        throw new Error('Bad JSON format');
      }
    }
    return this.jsonContent;
  }

  /**
  * Takes a JSON filename and creates an Inverted Index
  * @param {string} content - the JSON file content
  * @param {string} filename
  */
  createIndex(content, filename) {
    this.invertedIndex = {};
    // get json file content assign to index
    const index = this.readJsonFile(content);
    for (let i = 0; i < index.length; i += 1) {
      const term = index[i];
      let terms = `${term.title} ${term.text}`;
      // process text to remove repetition, special characters & (lower case)
      terms = this.processText(terms);
      for (let j = 0; j < terms.length; j += 1) {
        if (!(terms[j] in this.invertedIndex)) {
          this.invertedIndex[terms[j]] = [i];
        } else if (!(i in this.invertedIndex[terms[j]])) {
          this.invertedIndex[terms[j]].push(i);
        }
      }
    }
    // assign filename as the key & inverted index object as value
    this.invertedIndexObj[filename] = this.invertedIndex;
  }

  /**
  * Takes text and processes to lowercase, removes non-alphanumeric characters,
  * and removes dublicate words
  * @param {string} text
  * @returns array normalised Text
  */
  processText(text) {
    const normalised = text.replace(/[^a-z0-9 ]/gi, '').toLowerCase().split(' ');
    let normalisedText = new Set(normalised);
    normalisedText = Array.from(normalisedText);
    return normalisedText;
  }
  /**
   * Normalizes Data
   * @param {terms} a word to normalize.
   * @returns string  - normalized word.
   */
  search(term) {
    return natural.PorterStemmer.stem(term);
  }
  /**
  * Searches inverted index
  * @param {words} title - extended parameters.
  * @returns { } searchresults - Object of search results.
  */
  searchIndex(...words) {
    this.searchResults = {};
    let terms = words.toString().split(',').join(' ');
    terms = this.processText(terms);
    for (const [key, value] of entries(this.invertedIndexObj)) {
      // using const - no reassignment
      const termResults = {};
      for (const term of terms) {
        if (this.search(term) in value) {
          termResults[this.search(term)] = value[this.search(term)];
        } else if (term in value) {
          termResults[term] = value[term];
        }
      }
      if (Object.keys(termResults).length === 0 && termResults.constructor === Object) {
        termResults.Results = `No records found for: ${terms.toString().split(',').join(' ')}`;
      }
      this.searchResults[key] = termResults;
    }
    if (words[0] === undefined || words[0] === null) {
      return this.searchResults;
    } else if (words[0].toString().match(/^.*json$/)) {
      const file = words[0].toString().match(/^.*json$/);
      if (file in this.searchResults) {
        const tempResults = this.searchResults;
        this.searchResults = {};
        this.searchResults[file] = tempResults[file];
      }
    }
    return this.searchResults;
  }

  /**
  * Returns Inverted index object.
  */
  getIndex() {
    return this.invertedIndexObj;
  }
}

// export values
exports.Index = Index;
<|endoftext|>


<commit_before>/**
 * Index Class
 *
 * Creates an Index Class
 * @class
 */
class Index {
  /**
   *
   *
   * @constructor
   */
  constructor() {
    this.index = {};
    this.files = {};
  }

  /**
   * checkJSON
   *
   * Checks whether the file is a JSON file
   *
   * @param {object} responseFile - Content of the file
   * @returns {bool} | {object} A false boolean if file is not valid
   *
   * or a JSON object if valid file
   */
  static checkJSON(responseFile) {
    if (responseFile.length > 0
      && responseFile[0].title && responseFile[0].text) {
      return responseFile;
    }
    return false;
  }

  /**
   * tidyText
   *
   * Removes punctuation and whitespace
   *
   * @param {string} values - String of words in file as a value
   * @returns {array} An array of words with no whitespace or punctuation
   */
  static tidyText(values) {
    const words = values.toLowerCase()
      .replace(/\W+/g, ' ')
      .trim()
      .split(' ');
    return this.arrangeWords(words);
  }

  /**
   * arrangeWords
   *
   * bring out an array the contain properly arranged words
   * @param {array} words words in each file
   * @returns {array} returns an array of arranged words
   *
   */
  static arrangeWords(words) {
    return words.filter((item, position) => words.indexOf(item) === position);
  }

  /**
   * createIndex
   *
   * Creates the index from the file passed
   *
   * @param {string} fileName - Name of the file
   * @param {object} file - Content of the file
   * @returns {object} An object of created indices
   */
  createIndex(fileName, file) {
    file = Index.checkJSON(file);
    if (!file) {
      return false;
    }

    const wordsIndex = {};
    file.forEach((document, index) => {
      const fileString = Index.tidyText(document.text);
      fileString.forEach((word) => {
        if (wordsIndex[word]) {
          wordsIndex[word].push(index);
        } else {
          wordsIndex[word] = [index];
        }
      });
    });
    if (!this.index[fileName]) {
      this.index[fileName] = wordsIndex;
    }
    return this.index;
  }

  /**
   * getIndex
   *
   * Returns the index
   *
   * @param {string} fileName - Name to the file
   * @returns {object} An object of indices
   */
  getIndex(fileName) {
    return this.index[fileName];
  }

  /**
   * searchIndex
   * Search for terms in a file
   * @param {String} terms word(s) to be searched in the index
   * @param {String} filename file to search for words
   * @return {Object} words and their index
   */
  static searchWords(...terms) {
    let toSearch = '';

    for (let word = 0; word < terms.length; word += 1) {
      if (Array.isArray(...[word])) {
        terms[word].join(' ');
      }
      toSearch += `${terms[word]} `;
    }
    return toSearch;
  }

  /**
   * searchIndex
   *
   * Checks whether searched terms are in the created index
   *
   * @param {string} fileName
   * @param {string} terms
   * @returns {object} An object of the results
   */
  searchIndex(fileName, ...terms) {
    const results = {};
    let searchTerms = [];
    const toSearch = Index.searchWords(...terms);
    searchTerms = Index.tidyText(toSearch.toLowerCase());

    if (!fileName) {
      Object.keys(this.index).forEach((file) => {
        // for (const file in this.index) {
        results[file] = Index.searchResult(searchTerms, this.index[file]);
      });
    } else {
      const searchFile = this.index[fileName];
      results[fileName] = Index.searchResult(searchTerms, searchFile);
    }
    return results;
  }

  /**
   * searchResult
   *
   * Returns the search results
   *
   * @param {array} searchTerms
   * @param {object} file
   * @returns {object} results
   */
  static searchResult(searchTerms, file) {
    const results = {};
    searchTerms.forEach((term, index) => {
      if (file[term]) {
        results[searchTerms[index]] = file[term];
      }
    });
    return results;
  }
}
<commit_msg>Removing comment from codebase<commit_after>/**
 * Index Class
 *
 * Creates an Index Class
 * @class
 */
class Index {
  /**
   *
   *
   * @constructor
   */
  constructor() {
    this.index = {};
    this.files = {};
  }

  /**
   * checkJSON
   *
   * Checks whether the file is a JSON file
   *
   * @param {object} responseFile - Content of the file
   * @returns {bool} | {object} A false boolean if file is not valid
   *
   * or a JSON object if valid file
   */
  static checkJSON(responseFile) {
    if (responseFile.length > 0
      && responseFile[0].title && responseFile[0].text) {
      return responseFile;
    }
    return false;
  }

  /**
   * tidyText
   *
   * Removes punctuation and whitespace
   *
   * @param {string} values - String of words in file as a value
   * @returns {array} An array of words with no whitespace or punctuation
   */
  static tidyText(values) {
    const words = values.toLowerCase()
      .replace(/\W+/g, ' ')
      .trim()
      .split(' ');
    return this.arrangeWords(words);
  }

  /**
   * arrangeWords
   *
   * bring out an array the contain properly arranged words
   * @param {array} words words in each file
   * @returns {array} returns an array of arranged words
   *
   */
  static arrangeWords(words) {
    return words.filter((item, position) => words.indexOf(item) === position);
  }

  /**
   * createIndex
   *
   * Creates the index from the file passed
   *
   * @param {string} fileName - Name of the file
   * @param {object} file - Content of the file
   * @returns {object} An object of created indices
   */
  createIndex(fileName, file) {
    file = Index.checkJSON(file);
    if (!file) {
      return false;
    }

    const wordsIndex = {};
    file.forEach((document, index) => {
      const fileString = Index.tidyText(document.text);
      fileString.forEach((word) => {
        if (wordsIndex[word]) {
          wordsIndex[word].push(index);
        } else {
          wordsIndex[word] = [index];
        }
      });
    });
    if (!this.index[fileName]) {
      this.index[fileName] = wordsIndex;
    }
    return this.index;
  }

  /**
   * getIndex
   *
   * Returns the index
   *
   * @param {string} fileName - Name to the file
   * @returns {object} An object of indices
   */
  getIndex(fileName) {
    return this.index[fileName];
  }

  /**
   * searchIndex
   * Search for terms in a file
   * @param {String} terms word(s) to be searched in the index
   * @param {String} filename file to search for words
   * @return {Object} words and their index
   */
  static searchWords(...terms) {
    let toSearch = '';

    for (let word = 0; word < terms.length; word += 1) {
      if (Array.isArray(...[word])) {
        terms[word].join(' ');
      }
      toSearch += `${terms[word]} `;
    }
    return toSearch;
  }

  /**
   * searchIndex
   *
   * Checks whether searched terms are in the created index
   *
   * @param {string} fileName
   * @param {string} terms
   * @returns {object} An object of the results
   */
  searchIndex(fileName, ...terms) {
    const results = {};
    let searchTerms = [];
    const toSearch = Index.searchWords(...terms);
    searchTerms = Index.tidyText(toSearch.toLowerCase());

    if (!fileName) {
      Object.keys(this.index).forEach((file) => {
        results[file] = Index.searchResult(searchTerms, this.index[file]);
      });
    } else {
      const searchFile = this.index[fileName];
      results[fileName] = Index.searchResult(searchTerms, searchFile);
    }
    return results;
  }

  /**
   * searchResult
   *
   * Returns the search results
   *
   * @param {array} searchTerms
   * @param {object} file
   * @returns {object} results
   */
  static searchResult(searchTerms, file) {
    const results = {};
    searchTerms.forEach((term, index) => {
      if (file[term]) {
        results[searchTerms[index]] = file[term];
      }
    });
    return results;
  }
}
<|endoftext|>


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

    var HiddenRedirectComponent;
    var $ = require('jquery');
    var __ = require('orotranslation/js/translator');
    var mediator = require('oroui/js/mediator');
    var Modal = require('oroui/js/modal');
    var BaseComponent = require('oroui/js/app/components/base/component');

    /**
     * @export oroui/js/app/components/hidden-redirect-component
     * @extends oroui.app.components.base.Component
     * @class oroui.app.components.HiddenRedirectComponent
     */
    HiddenRedirectComponent = BaseComponent.extend({
        /**
         * @property {Object}
         */
        element: null,

        /**
         * @property {string}
         */
        type: 'info',

        /**
         * @property {Boolean}
         */
        showLoading: false,

        /**
         * @inheritDoc
         */
        constructor: function HiddenRedirectComponent() {
            HiddenRedirectComponent.__super__.constructor.apply(this, arguments);
        },

        /**
         * @inheritDoc
         */
        initialize: function(options) {
            this.element = options._sourceElement;
            if (!this.element) {
                return;
            }

            if (options.type) {
                this.type = options.type;
            }

            if (options.showLoading) {
                this.showLoading = options.showLoading;
            }

            var self = this;
            this.element.on('click.' + this.cid, function(e) {
                self._showLoading();

                e.preventDefault();
                var pageStateView = mediator.execute('composer:retrieve', 'pageState', true);

                if (pageStateView.isStateChanged()) {
                    var confirmModal = self.createModal();
                    confirmModal.once('ok', function() {
                        self.saveAndRedirect();
                        setTimeout(function() {
                            confirmModal.dispose();
                        }, 0);
                    });
                    confirmModal.once('cancel', function() {
                        setTimeout(function() {
                            confirmModal.dispose();
                        }, 0);
                    });
                    confirmModal.once('buttonClick', function(id) {
                        if (id === 'secondary') {
                            self.startRedirect();
                        }
                        setTimeout(function() {
                            confirmModal.dispose();
                        }, 0);
                    });
                    confirmModal.open();
                    return false;
                }
                self.startRedirect();
                return false;
            });
        },

        saveAndRedirect: function() {
            var form = $('form[data-collect=true]');
            var actionInput = form.find('input[name="input_action"]');
            var _this = this;
            $.ajax({
                url: this.element.attr('href'),
                type: 'GET',
                success: function(response) {
                    _this._hideLoading();
                    actionInput.val(JSON.stringify({
                        redirectUrl: response.url
                    }));
                    form.trigger('submit');
                },
                error: function(xhr) {
                    _this._hideLoading();
                }
            });
        },

        startRedirect: function() {
            mediator.execute('showLoading');
            var _this = this;
            $.ajax({
                url: this.element.attr('href'),
                type: 'GET',
                success: function(response) {
                    _this._hideLoading();
                    _this._processResponse(response.url, response.message);
                },
                error: function(xhr) {
                    _this._hideLoading();
                }
            });
        },

        createModal: function() {
            return new Modal({
                title: __('oro.ui.leave_page_save_data_or_discard_title'),
                content: __('oro.ui.leave_page_save_data_or_discard'),
                okText: __('Save'),
                secondaryText: __('Discard'),
                className: 'modal modal-primary',
                cancelText: __('Cancel'),
                template: require('tpl!oroui/templates/three-buttons-modal.html')
            });
        },

        /**
         * @inheritDoc
         */
        dispose: function() {
            if (this.disposed || !this.element) {
                return;
            }

            this.element.off('.' + this.cid);

            HiddenRedirectComponent.__super__.dispose.call(this);
        },

        /**
         * @param {string|null} url
         * @param {string|null} message
         */
        _processResponse: function(url, message) {
            if (url) {
                if (message) {
                    var self = this;
                    mediator.once('page:afterChange', function() {
                        self._showMessage(self.type, message);
                    });
                }

                if (mediator.execute('compareUrl', url)) {
                    mediator.execute('refreshPage');
                } else {
                    mediator.execute('redirectTo', {url: url});
                }
            } else if (message) {
                this._showMessage(this.type, message);
            }
        },

        /**
         * @param {string} type
         * @param {string} message
         */
        _showMessage: function(type, message) {
            mediator.execute('showFlashMessage', type, message);
        },

        _showLoading: function() {
            if (!this.showLoading) {
                return;
            }

            mediator.execute('showLoading');
        },

        _hideLoading: function() {
            if (!this.showLoading) {
                return;
            }

            mediator.execute('hideLoading');
        }
    });

    return HiddenRedirectComponent;
});
<commit_msg>BAP-16833: Record pagination in mobile view (#18267)<commit_after>define(function(require) {
    'use strict';

    var HiddenRedirectComponent;
    var $ = require('jquery');
    var __ = require('orotranslation/js/translator');
    var mediator = require('oroui/js/mediator');
    var Modal = require('oroui/js/modal');
    var BaseComponent = require('oroui/js/app/components/base/component');

    /**
     * @export oroui/js/app/components/hidden-redirect-component
     * @extends oroui.app.components.base.Component
     * @class oroui.app.components.HiddenRedirectComponent
     */
    HiddenRedirectComponent = BaseComponent.extend({
        /**
         * @property {Object}
         */
        element: null,

        /**
         * @property {string}
         */
        type: 'info',

        /**
         * @property {Boolean}
         */
        showLoading: false,

        /**
         * @inheritDoc
         */
        constructor: function HiddenRedirectComponent() {
            HiddenRedirectComponent.__super__.constructor.apply(this, arguments);
        },

        /**
         * @inheritDoc
         */
        initialize: function(options) {
            this.element = options._sourceElement;
            if (!this.element) {
                return;
            }

            if (options.type) {
                this.type = options.type;
            }

            if (options.showLoading) {
                this.showLoading = options.showLoading;
            }

            var self = this;
            this.element.on('click.' + this.cid, function(e) {
                self._showLoading();

                e.preventDefault();
                var pageStateView = mediator.execute('composer:retrieve', 'pageState', true);

                if (pageStateView && pageStateView.isStateChanged()) {
                    var confirmModal = self.createModal();
                    confirmModal.once('ok', function() {
                        self.saveAndRedirect();
                        setTimeout(function() {
                            confirmModal.dispose();
                        }, 0);
                    });
                    confirmModal.once('cancel', function() {
                        setTimeout(function() {
                            confirmModal.dispose();
                        }, 0);
                    });
                    confirmModal.once('buttonClick', function(id) {
                        if (id === 'secondary') {
                            self.startRedirect();
                        }
                        setTimeout(function() {
                            confirmModal.dispose();
                        }, 0);
                    });
                    confirmModal.open();
                    return false;
                }
                self.startRedirect();
                return false;
            });
        },

        saveAndRedirect: function() {
            var form = $('form[data-collect=true]');
            var actionInput = form.find('input[name="input_action"]');
            var _this = this;
            $.ajax({
                url: this.element.attr('href'),
                type: 'GET',
                success: function(response) {
                    _this._hideLoading();
                    actionInput.val(JSON.stringify({
                        redirectUrl: response.url
                    }));
                    form.trigger('submit');
                },
                error: function(xhr) {
                    _this._hideLoading();
                }
            });
        },

        startRedirect: function() {
            mediator.execute('showLoading');
            var _this = this;
            $.ajax({
                url: this.element.attr('href'),
                type: 'GET',
                success: function(response) {
                    _this._hideLoading();
                    _this._processResponse(response.url, response.message);
                },
                error: function(xhr) {
                    _this._hideLoading();
                }
            });
        },

        createModal: function() {
            return new Modal({
                title: __('oro.ui.leave_page_save_data_or_discard_title'),
                content: __('oro.ui.leave_page_save_data_or_discard'),
                okText: __('Save'),
                secondaryText: __('Discard'),
                className: 'modal modal-primary',
                cancelText: __('Cancel'),
                template: require('tpl!oroui/templates/three-buttons-modal.html')
            });
        },

        /**
         * @inheritDoc
         */
        dispose: function() {
            if (this.disposed || !this.element) {
                return;
            }

            this.element.off('.' + this.cid);

            HiddenRedirectComponent.__super__.dispose.call(this);
        },

        /**
         * @param {string|null} url
         * @param {string|null} message
         */
        _processResponse: function(url, message) {
            if (url) {
                if (message) {
                    var self = this;
                    mediator.once('page:afterChange', function() {
                        self._showMessage(self.type, message);
                    });
                }

                if (mediator.execute('compareUrl', url)) {
                    mediator.execute('refreshPage');
                } else {
                    mediator.execute('redirectTo', {url: url});
                }
            } else if (message) {
                this._showMessage(this.type, message);
            }
        },

        /**
         * @param {string} type
         * @param {string} message
         */
        _showMessage: function(type, message) {
            mediator.execute('showFlashMessage', type, message);
        },

        _showLoading: function() {
            if (!this.showLoading) {
                return;
            }

            mediator.execute('showLoading');
        },

        _hideLoading: function() {
            if (!this.showLoading) {
                return;
            }

            mediator.execute('hideLoading');
        }
    });

    return HiddenRedirectComponent;
});
<|endoftext|>


<commit_before>/*
  jQuery strings - 0.1a
  http://code.google.com/p/jquery-utils/

  (c) Maxime Haineault <haineault@gmail.com>
  http://haineault.com

  MIT License (http://www.opensource.org/licenses/mit-license.php)

  Implementation of Python3K advanced string formatting
  http://www.python.org/dev/peps/pep-3101/

  Documentation: http://code.google.com/p/jquery-utils/wiki/StringFormat

*/
(function($){
    var conversion = {
        // tries to translate any objects type into string gracefully
        __repr: function(i){
            switch(this.__getType(i)) {
                case 'array':case 'date':case 'number':
                    return i.toString();
                case 'object':
                    var o = [];
                    for (x=0; x<i.length; i++) { o.push(i+': '+ this.__repr(i[x])); }
                    return o.join(', ');
                case 'string':
                    return i;
                default:
                    return i;
            }
        },
        // like typeof but less vague
        __getType: function(i) {
            if (!i || !i.constructor) { return typeof(i); }
            var match = i.constructor.toString().match(/Array|Number|String|Object|Date/);
            return match && match[0].toLowerCase() || typeof(i);
        },
        //+ Jonas Raoni Soares Silva
        //@ http://jsfromhell.com/string/pad [v1.0]
        __pad: function(str, l, s, t){
            return s || (s = " "), (l -= str.length) > 0 ? (s = new Array(Math.ceil(l / s.length)
                + 1).join(s)).substr(0, t = !t ? l : t == 1 ? 0 : Math.ceil(l / 2))
                + str + s.substr(0, l - t) : str;
        },
        __getInput: function(arg, args) {
            var key = arg.getKey();
            switch(this.__getType(args)){
                case 'object':
                    if (typeof(args[key]) != 'undefined') {
                        if (conversion.__getType(args[key]) == 'array') {
                            return arg.getFormat().match(/\.\*/) && args[key][1] || args[key];
                        }
                        return args[key];
                    }
                    else {
                        // TODO: try by numerical index
                    }
                break;
                case 'array':
                    key = parseInt(key, 10);
                    if (arg.getFormat().match(/\.\*/) && typeof(args[key+1]) != 'undefined') return args[key+1];
                    else if (typeof(args[key]) != 'undefined') return args[key];
                    else return key;
                break;
            }
            return '{'+key+'}';
        },
        __formatToken: function(token, args) {
            var arg   = new Argument(token, args);
            return conversion[arg.getFormat().slice(-1)](this.__getInput(arg, args), arg);
        },

        // Signed integer decimal.
        d: function(input, arg){
            var o = parseInt(input, 10); // enforce base 10
            var p = arg.getPaddingLength();
            if (p) return this.__pad(o.toString(), p, arg.getPaddingString(), 0);
            else return o;
        },
        // Signed integer decimal.
        i: function(input, args){
            return this.d(input, args);
        },
        // Unsigned octal
        o: function(input, arg){
            var o = input.toString(8);
            if (arg.isAlternate()) o = this.__pad(o, o.length+1, '0', 0);
            return this.__pad(o, arg.getPaddingLength(), arg.getPaddingString(), 0);
        },
        // Unsigned decimal
        u: function(input, args) {
            return Math.abs(this.d(input, args));
        },
        // Unsigned hexadecimal (lowercase)
        x: function(input, arg){
            var o = parseInt(input, 10).toString(16);
            o = this.__pad(o, arg.getPaddingLength(), arg.getPaddingString(),0);
            return (arg.isAlternate())? '0x'+o: o;
        },
        // Unsigned hexadecimal (uppercase)
        X: function(input, arg){
            return this.x(input, arg).toUpperCase();
        },
        // Floating point exponential format (lowercase)
        e: function(input, arg){
            return parseFloat(input, 10).toExponential(arg.getPrecision());
        },
        // Floating point exponential format (uppercase)
        E: function(input, arg){
            return this.e(input, arg).toUpperCase();
        },
        // Floating point decimal format
        f: function(input, arg){
            return this.__pad(parseFloat(input, 10).toFixed(arg.getPrecision()), arg.getPaddingLength(), arg.getPaddingString(),0);
        },
        // Floating point decimal format (alias)
        F: function(input, args){
            return this.f(input, args);
        },
        // Floating point format. Uses exponential format if exponent is greater than -4 or less than precision, decimal format otherwise
        g: function(input, arg){
            var o = parseFloat(input, 10);
            return (o.toString().length > 6) ? Math.round(o.toExponential(arg.getPrecision())): o;
        },
        // Floating point format. Uses exponential format if exponent is greater than -4 or less than precision, decimal format otherwise
        G: function(input, args){
            return this.g(input, args);
        },
        // Single character (accepts integer or single character string).
        c: function(input, args) {
            var match = input.match(/\w|\d/);
            return match && match[0] || '';
        },
        // String (converts any JavaScript object to anotated format)
        r: function(input, args) {
            return this.__repr(input);
        },
        // String (converts any JavaScript object using object.toString())
        s: function(input, args) {
            return input.toString && input.toString() || ''+input;
        }
    };

    var Argument = function(arg, args) {
        this.__arg  = arg;
        this.__args = args;
        this.__max_precision = parseFloat('1.'+ (new Array(32)).join('1'), 10).toString().length-3;
        this.__def_precision = 6;
        this.getString = function(){
            return this.__arg;
        };
        this.getKey = function(){
            return this.__arg.split(':')[0];
        };
        this.getFormat = function(){
            var match = this.getString().split(':');
            return (match && match[1])? match[1]: 's';
        };
        this.getPrecision = function(){
            var match = this.getFormat().match(/\.(\d+|\*)/g);
            if (!match) return this.__def_precision;
            else {
                match = match[0].slice(1);
                if (match != '*') return parseInt(match, 10);
                else if(conversion.__getType(this.__args) == 'array') {
                    return this.__args[1] && this.__args[0] || this.__def_precision;
                }
                else if(conversion.__getType(this.__args) == 'object') {
                    return this.__args[this.getKey()] && this.__args[this.getKey()][0] || this.__def_precision;
                }
                else return this.__def_precision;
            }
        };
        this.getPaddingLength = function(){
            if (this.isAlternate()) {
                var match = this.getString().match(/0?#0?(\d+)/);
                if (match && match[1]) return parseInt(match[1], 10);
            }
            var match = this.getString().match(/(0|\.)(\d+|\*)/g)
            return match && parseInt(match[0].slice(1), 10) || 0;
        };
        this.getPaddingString = function(){
            var o = '';
            if (this.isAlternate()) o = ' ';
            // 0 take precedence on alternate format
            if (this.getFormat().match(/#0|0#|^0|\.\d+/)) o = '0';
            return o;
        };
        this.getFlags = function(){
            var match = this.getString().match(/^(0|\#|\-|\+|\s)+/);
            return match && match[0].split('') || [];
        };
        this.isAlternate = function() {
            return !!this.getFormat().match(/^0?#/);
        };
    };

    var arguments2Array = function(args, shift) {
        var shift = shift || 0;
        var o = [];
        for (l=args.length, x=shift-1; x<l;x++) o.push(args[x]);
        return o;
    }

    var format = function(str, args) {
        var end    = 0;
        var start  = 0;
        var match  = false;
        var buffer = [];
        var token  = '';
        var args   = (typeof(arguments[1]) != 'object')? arguments2Array(arguments, 2): args || [];
        var tmp    = str.split('');
        for(start=0; start < tmp.length; start++) {
            if (tmp[start] == '{' && tmp[start+1] !='{') {
                end   = str.indexOf('}', start);
                token = tmp.slice(start+1, end).join('');
                buffer.push(conversion.__formatToken(token, args));
            }
            else if (start > end || buffer.length < 1)  buffer.push(tmp[start]);
        }
        return (buffer.length > 1)? buffer.join(''): buffer[0];
    };

    var calc = function(str, args) {
        return eval(format(str, args));
    };

    $.extend({
        // Format/sprintf functions
        format: format,
        calc:   calc,
        strConversion: conversion
    });

})(jQuery);
<commit_msg>- jquery.strings.js: added UTF8encode/decode methods<commit_after>/*
  jQuery strings - 0.1a
  http://code.google.com/p/jquery-utils/

  (c) Maxime Haineault <haineault@gmail.com>
  http://haineault.com

  MIT License (http://www.opensource.org/licenses/mit-license.php)

  Implementation of Python3K advanced string formatting
  http://www.python.org/dev/peps/pep-3101/

  Documentation: http://code.google.com/p/jquery-utils/wiki/StringFormat

*/
(function($){
    var conversion = {
        // tries to translate any objects type into string gracefully
        __repr: function(i){
            switch(this.__getType(i)) {
                case 'array':case 'date':case 'number':
                    return i.toString();
                case 'object':
                    var o = [];
                    for (x=0; x<i.length; i++) { o.push(i+': '+ this.__repr(i[x])); }
                    return o.join(', ');
                case 'string':
                    return i;
                default:
                    return i;
            }
        },
        // like typeof but less vague
        __getType: function(i) {
            if (!i || !i.constructor) { return typeof(i); }
            var match = i.constructor.toString().match(/Array|Number|String|Object|Date/);
            return match && match[0].toLowerCase() || typeof(i);
        },
        //+ Jonas Raoni Soares Silva
        //@ http://jsfromhell.com/string/pad [v1.0]
        __pad: function(str, l, s, t){
            return s || (s = " "), (l -= str.length) > 0 ? (s = new Array(Math.ceil(l / s.length)
                + 1).join(s)).substr(0, t = !t ? l : t == 1 ? 0 : Math.ceil(l / 2))
                + str + s.substr(0, l - t) : str;
        },
        __getInput: function(arg, args) {
            var key = arg.getKey();
            switch(this.__getType(args)){
                case 'object':
                    if (typeof(args[key]) != 'undefined') {
                        if (conversion.__getType(args[key]) == 'array') {
                            return arg.getFormat().match(/\.\*/) && args[key][1] || args[key];
                        }
                        return args[key];
                    }
                    else {
                        // TODO: try by numerical index
                    }
                break;
                case 'array':
                    key = parseInt(key, 10);
                    if (arg.getFormat().match(/\.\*/) && typeof(args[key+1]) != 'undefined') return args[key+1];
                    else if (typeof(args[key]) != 'undefined') return args[key];
                    else return key;
                break;
            }
            return '{'+key+'}';
        },
        __formatToken: function(token, args) {
            var arg   = new Argument(token, args);
            return conversion[arg.getFormat().slice(-1)](this.__getInput(arg, args), arg);
        },

        // Signed integer decimal.
        d: function(input, arg){
            var o = parseInt(input, 10); // enforce base 10
            var p = arg.getPaddingLength();
            if (p) return this.__pad(o.toString(), p, arg.getPaddingString(), 0);
            else return o;
        },
        // Signed integer decimal.
        i: function(input, args){
            return this.d(input, args);
        },
        // Unsigned octal
        o: function(input, arg){
            var o = input.toString(8);
            if (arg.isAlternate()) o = this.__pad(o, o.length+1, '0', 0);
            return this.__pad(o, arg.getPaddingLength(), arg.getPaddingString(), 0);
        },
        // Unsigned decimal
        u: function(input, args) {
            return Math.abs(this.d(input, args));
        },
        // Unsigned hexadecimal (lowercase)
        x: function(input, arg){
            var o = parseInt(input, 10).toString(16);
            o = this.__pad(o, arg.getPaddingLength(), arg.getPaddingString(),0);
            return (arg.isAlternate())? '0x'+o: o;
        },
        // Unsigned hexadecimal (uppercase)
        X: function(input, arg){
            return this.x(input, arg).toUpperCase();
        },
        // Floating point exponential format (lowercase)
        e: function(input, arg){
            return parseFloat(input, 10).toExponential(arg.getPrecision());
        },
        // Floating point exponential format (uppercase)
        E: function(input, arg){
            return this.e(input, arg).toUpperCase();
        },
        // Floating point decimal format
        f: function(input, arg){
            return this.__pad(parseFloat(input, 10).toFixed(arg.getPrecision()), arg.getPaddingLength(), arg.getPaddingString(),0);
        },
        // Floating point decimal format (alias)
        F: function(input, args){
            return this.f(input, args);
        },
        // Floating point format. Uses exponential format if exponent is greater than -4 or less than precision, decimal format otherwise
        g: function(input, arg){
            var o = parseFloat(input, 10);
            return (o.toString().length > 6) ? Math.round(o.toExponential(arg.getPrecision())): o;
        },
        // Floating point format. Uses exponential format if exponent is greater than -4 or less than precision, decimal format otherwise
        G: function(input, args){
            return this.g(input, args);
        },
        // Single character (accepts integer or single character string).
        c: function(input, args) {
            var match = input.match(/\w|\d/);
            return match && match[0] || '';
        },
        // String (converts any JavaScript object to anotated format)
        r: function(input, args) {
            return this.__repr(input);
        },
        // String (converts any JavaScript object using object.toString())
        s: function(input, args) {
            return input.toString && input.toString() || ''+input;
        }
    };

    var Argument = function(arg, args) {
        this.__arg  = arg;
        this.__args = args;
        this.__max_precision = parseFloat('1.'+ (new Array(32)).join('1'), 10).toString().length-3;
        this.__def_precision = 6;
        this.getString = function(){
            return this.__arg;
        };
        this.getKey = function(){
            return this.__arg.split(':')[0];
        };
        this.getFormat = function(){
            var match = this.getString().split(':');
            return (match && match[1])? match[1]: 's';
        };
        this.getPrecision = function(){
            var match = this.getFormat().match(/\.(\d+|\*)/g);
            if (!match) return this.__def_precision;
            else {
                match = match[0].slice(1);
                if (match != '*') return parseInt(match, 10);
                else if(conversion.__getType(this.__args) == 'array') {
                    return this.__args[1] && this.__args[0] || this.__def_precision;
                }
                else if(conversion.__getType(this.__args) == 'object') {
                    return this.__args[this.getKey()] && this.__args[this.getKey()][0] || this.__def_precision;
                }
                else return this.__def_precision;
            }
        };
        this.getPaddingLength = function(){
            if (this.isAlternate()) {
                var match = this.getString().match(/0?#0?(\d+)/);
                if (match && match[1]) return parseInt(match[1], 10);
            }
            var match = this.getString().match(/(0|\.)(\d+|\*)/g)
            return match && parseInt(match[0].slice(1), 10) || 0;
        };
        this.getPaddingString = function(){
            var o = '';
            if (this.isAlternate()) o = ' ';
            // 0 take precedence on alternate format
            if (this.getFormat().match(/#0|0#|^0|\.\d+/)) o = '0';
            return o;
        };
        this.getFlags = function(){
            var match = this.getString().match(/^(0|\#|\-|\+|\s)+/);
            return match && match[0].split('') || [];
        };
        this.isAlternate = function() {
            return !!this.getFormat().match(/^0?#/);
        };
    };

    var arguments2Array = function(args, shift) {
        var shift = shift || 0;
        var o = [];
        for (l=args.length, x=shift-1; x<l;x++) o.push(args[x]);
        return o;
    }

    var format = function(str, args) {
        var end    = 0;
        var start  = 0;
        var match  = false;
        var buffer = [];
        var token  = '';
        var args   = (typeof(arguments[1]) != 'object')? arguments2Array(arguments, 2): args || [];
        var tmp    = str.split('');
        for(start=0; start < tmp.length; start++) {
            if (tmp[start] == '{' && tmp[start+1] !='{') {
                end   = str.indexOf('}', start);
                token = tmp.slice(start+1, end).join('');
                buffer.push(conversion.__formatToken(token, args));
            }
            else if (start > end || buffer.length < 1)  buffer.push(tmp[start]);
        }
        return (buffer.length > 1)? buffer.join(''): buffer[0];
    };

    var calc = function(str, args) {
        return eval(format(str, args));
    };

    $.extend({
        // Format/sprintf functions
        format: format,
        calc:   calc,
        strConversion: conversion,
        UTF8encode: function(s) { return unescape(encodeURIComponent(s)); },
        UTF8decode: function(s) { return decodeURIComponent(escape(s)); }
    });

})(jQuery);
<|endoftext|>


<commit_before>/**
 * Contains the logic for the sidebar.
 *
 * @returns {{}}
 */
webvowlApp.sidebar = function () {

	var sidebar = {};

	/**
	 * Setup the menu bar.
	 */
	sidebar.setup = function () {
		setupCollapsing();
	};

	function setupCollapsing() {
		// adapted version of this example: http://www.normansblog.de/simple-jquery-accordion/
		function collapseContainers(containers) {
			containers.style("display", "none");
		}

		function expandContainers(containers) {
			containers.style("display", null);
		}

		var triggers = d3.selectAll(".accordion-trigger");

		// Collapse all inactive triggers on startup
		collapseContainers(d3.selectAll(".accordion-trigger:not(.accordion-trigger-active) + div"));

		triggers.on("click", function () {
			var selectedTrigger = d3.select(this),
				activeTriggers = d3.selectAll(".accordion-trigger-active");

			if (selectedTrigger.classed("accordion-trigger-active")) {
				// Collapse the active (which is also the selected) trigger
				collapseContainers(d3.select(selectedTrigger.node().nextElementSibling));
				selectedTrigger.classed("accordion-trigger-active", false);
			} else {
				// Collapse the other trigger ...
				collapseContainers(d3.selectAll(".accordion-trigger-active + div"));
				activeTriggers.classed("accordion-trigger-active", false);
				// ... and expand the selected one
				expandContainers(d3.select(selectedTrigger.node().nextElementSibling));
				selectedTrigger.classed("accordion-trigger-active", true);
			}
		});
	}

	/**
	 * Updates the information of the passed ontology.
	 * @param data the graph data
	 * @param statistics the statistics module
	 */
	sidebar.updateOntologyInformation = function (data, statistics) {
		displayGraphInformation(data);
		displayGraphStatistics(statistics);
	};

	function displayGraphInformation(data) {
		var header = data.header;

		d3.select("#title").text(header.title);
		d3.select("#about").attr("href", header.uri).attr("target", "_blank").text(header.uri);
		d3.select("#version").text(header.version);
		d3.select("#authors").text(header.author);
		d3.select("#description").text(header.description);
	}

	function displayGraphStatistics(statistics) {
		d3.select("#statNodes")
			.text(statistics.nodeCount());
		d3.select("#statClass")
			.text(statistics.classCount());
		d3.select("#statDatatypes")
			.text(statistics.datatypeCount());
		d3.select("#statProp")
			.text(statistics.propertyCount());
	}

	/**
	 * Update the information of the selected node.
	 * @param selectedElement the selection or null if nothing is selected
	 */
	sidebar.updateSelectionInformation = function (selectedElement) {
		// Click event was prevented when dragging
		if (d3.event.defaultPrevented) {
			return;
		}

		var isTriggerActive = d3.select("#selection-details-trigger").classed("accordion-trigger-active");
		if (selectedElement && !isTriggerActive) {
			d3.select("#selection-details-trigger").node().click();
		} else if (!selectedElement && isTriggerActive) {
			d3.select("#selection-details-trigger").node().click();
			showSelectionAdvice();
			return;
		}

		if (selectedElement instanceof webvowl.labels.BaseLabel) {
			displayLabelInformation(selectedElement);
		} else if (selectedElement instanceof webvowl.nodes.BaseNode) {
			displayNodeInformation(selectedElement);
		}
	};

	function showSelectionAdvice() {
		setSelectionInformationVisibility(false, false, true);
	}

	function setSelectionInformationVisibility(showClasses, showProperties, showAdvice) {
		d3.select("#classSelectionInformation").classed("hidden", !showClasses);
		d3.select("#propertySelectionInformation").classed("hidden", !showProperties);
		d3.select("#noSelectionInformation").classed("hidden", !showAdvice);
	}

	function displayLabelInformation(property) {
		showPropertyInformations();

		setUriLabel(d3.select("#propname"), property.label(), property.uri());
		d3.select("#typeProp").text(property.type());

		if (property.inverse() !== undefined) {
			d3.select("#inverse").style("display", "block");
			setUriLabel(d3.select("#inverse span"), property.inverse().label(), property.inverse().uri());
		} else {
			d3.select("#inverse").style("display", "none");
		}

		var equivalentUriSpan = d3.select("#propEquivUri");
		displayEquivalentElements(property.equivalent(), equivalentUriSpan);

		if (property.minCardinality() !== undefined) {
			d3.select("#infoCardinality").style("display", "none");
			d3.select("#minCardinality").style("display", "block");
			d3.select("#minCardinality span").text(property.minCardinality());
			d3.select("#maxCardinality").style("display", "block");

			if (property.maxCardinality() !== undefined) {
				d3.select("#maxCardinality span").text(property.maxCardinality());
			} else {
				d3.select("#maxCardinality span").text("*");
			}

		} else if (property.cardinality() !== undefined) {
			d3.select("#minCardinality").style("display", "none");
			d3.select("#maxCardinality").style("display", "none");
			d3.select("#infoCardinality").style("display", "block");
			d3.select("#infoCardinality span").text(property.cardinality());
		} else {
			d3.select("#infoCardinality").style("display", "none");
			d3.select("#minCardinality").style("display", "none");
			d3.select("#maxCardinality").style("display", "none");
		}

		setUriLabel(d3.select("#domain"), property.range().label(), property.range().uri());
		setUriLabel(d3.select("#range"), property.domain().label(), property.domain().uri());

		displayAttributes(property.attributes(), d3.select("#propAttributes"));
	}

	function showPropertyInformations() {
		setSelectionInformationVisibility(false, true, false);
	}

	function setUriLabel(element, name, uri) {
		element.selectAll("*").remove();
		appendUriLabel(element, name, uri);
	}

	function appendUriLabel(element, name, uri) {
		var tag;

		if (uri) {
			tag = element.append("a").attr("href", uri).attr("target", "_blank");
		} else {
			tag = element.append("span");
		}
		tag.text(name);
	}

	function displayAttributes(attributes, textSpan) {
		var spanParent = d3.select(textSpan.node().parentNode);

		if (attributes && attributes.length > 0) {
			textSpan.text(attributes.join(", "));

			spanParent.classed("hidden", false);
		} else {
			spanParent.classed("hidden", true);
		}
	}

	function displayNodeInformation(node) {
		showClassInformations();

		setUriLabel(d3.select("#name"), node.label(), node.uri());

		/* Equivalent stuff. */
		var equivalentUriSpan = d3.select("#classEquivUri");
		displayEquivalentElements(node.equivalent(), equivalentUriSpan);

		d3.select("#typeNode").text(node.type());

		/* Disjoint stuff. */
		var disjointNodes = d3.select("#disjointNodes");
		var disjointNodesParent = d3.select(disjointNodes.node().parentNode);

		if (node.disjointWith() !== undefined) {
			disjointNodes.selectAll("*").remove();

			node.disjointWith().forEach(function (element, index) {
				if (index > 0) {
					disjointNodes.append("span").text(", ");
				}
				appendUriLabel(disjointNodes, element.label(), element.uri());
			});

			disjointNodesParent.classed("hidden", false);
		} else {
			disjointNodesParent.classed("hidden", true);
		}

		displayAttributes(node.attributes(), d3.select("#classAttributes"));
	}

	function showClassInformations() {
		setSelectionInformationVisibility(true, false, false);
	}

	function displayEquivalentElements(equivalentElements, equivalentUriSpan) {
		var equivalentUriSpanParent = d3.select(equivalentUriSpan.node().parentNode);

		if (equivalentElements !== undefined) {
			equivalentUriSpan.selectAll("*").remove();
			equivalentElements.forEach(function (element, index) {
				if (index > 0) {
					equivalentUriSpan.append("span").text(", ");
				}
				appendUriLabel(equivalentUriSpan, element.label(), element.uri());
			});

			equivalentUriSpanParent.classed("hidden", false);
		} else {
			equivalentUriSpanParent.classed("hidden", true);
		}
	}

	return sidebar;
};
<commit_msg>Fix domain&range display in sidebar<commit_after>/**
 * Contains the logic for the sidebar.
 *
 * @returns {{}}
 */
webvowlApp.sidebar = function () {

	var sidebar = {};

	/**
	 * Setup the menu bar.
	 */
	sidebar.setup = function () {
		setupCollapsing();
	};

	function setupCollapsing() {
		// adapted version of this example: http://www.normansblog.de/simple-jquery-accordion/
		function collapseContainers(containers) {
			containers.style("display", "none");
		}

		function expandContainers(containers) {
			containers.style("display", null);
		}

		var triggers = d3.selectAll(".accordion-trigger");

		// Collapse all inactive triggers on startup
		collapseContainers(d3.selectAll(".accordion-trigger:not(.accordion-trigger-active) + div"));

		triggers.on("click", function () {
			var selectedTrigger = d3.select(this),
				activeTriggers = d3.selectAll(".accordion-trigger-active");

			if (selectedTrigger.classed("accordion-trigger-active")) {
				// Collapse the active (which is also the selected) trigger
				collapseContainers(d3.select(selectedTrigger.node().nextElementSibling));
				selectedTrigger.classed("accordion-trigger-active", false);
			} else {
				// Collapse the other trigger ...
				collapseContainers(d3.selectAll(".accordion-trigger-active + div"));
				activeTriggers.classed("accordion-trigger-active", false);
				// ... and expand the selected one
				expandContainers(d3.select(selectedTrigger.node().nextElementSibling));
				selectedTrigger.classed("accordion-trigger-active", true);
			}
		});
	}

	/**
	 * Updates the information of the passed ontology.
	 * @param data the graph data
	 * @param statistics the statistics module
	 */
	sidebar.updateOntologyInformation = function (data, statistics) {
		displayGraphInformation(data);
		displayGraphStatistics(statistics);
	};

	function displayGraphInformation(data) {
		var header = data.header;

		d3.select("#title").text(header.title);
		d3.select("#about").attr("href", header.uri).attr("target", "_blank").text(header.uri);
		d3.select("#version").text(header.version);
		d3.select("#authors").text(header.author);
		d3.select("#description").text(header.description);
	}

	function displayGraphStatistics(statistics) {
		d3.select("#statNodes")
			.text(statistics.nodeCount());
		d3.select("#statClass")
			.text(statistics.classCount());
		d3.select("#statDatatypes")
			.text(statistics.datatypeCount());
		d3.select("#statProp")
			.text(statistics.propertyCount());
	}

	/**
	 * Update the information of the selected node.
	 * @param selectedElement the selection or null if nothing is selected
	 */
	sidebar.updateSelectionInformation = function (selectedElement) {
		// Click event was prevented when dragging
		if (d3.event.defaultPrevented) {
			return;
		}

		var isTriggerActive = d3.select("#selection-details-trigger").classed("accordion-trigger-active");
		if (selectedElement && !isTriggerActive) {
			d3.select("#selection-details-trigger").node().click();
		} else if (!selectedElement && isTriggerActive) {
			d3.select("#selection-details-trigger").node().click();
			showSelectionAdvice();
			return;
		}

		if (selectedElement instanceof webvowl.labels.BaseLabel) {
			displayLabelInformation(selectedElement);
		} else if (selectedElement instanceof webvowl.nodes.BaseNode) {
			displayNodeInformation(selectedElement);
		}
	};

	function showSelectionAdvice() {
		setSelectionInformationVisibility(false, false, true);
	}

	function setSelectionInformationVisibility(showClasses, showProperties, showAdvice) {
		d3.select("#classSelectionInformation").classed("hidden", !showClasses);
		d3.select("#propertySelectionInformation").classed("hidden", !showProperties);
		d3.select("#noSelectionInformation").classed("hidden", !showAdvice);
	}

	function displayLabelInformation(property) {
		showPropertyInformations();

		setUriLabel(d3.select("#propname"), property.label(), property.uri());
		d3.select("#typeProp").text(property.type());

		if (property.inverse() !== undefined) {
			d3.select("#inverse").style("display", "block");
			setUriLabel(d3.select("#inverse span"), property.inverse().label(), property.inverse().uri());
		} else {
			d3.select("#inverse").style("display", "none");
		}

		var equivalentUriSpan = d3.select("#propEquivUri");
		displayEquivalentElements(property.equivalent(), equivalentUriSpan);

		if (property.minCardinality() !== undefined) {
			d3.select("#infoCardinality").style("display", "none");
			d3.select("#minCardinality").style("display", "block");
			d3.select("#minCardinality span").text(property.minCardinality());
			d3.select("#maxCardinality").style("display", "block");

			if (property.maxCardinality() !== undefined) {
				d3.select("#maxCardinality span").text(property.maxCardinality());
			} else {
				d3.select("#maxCardinality span").text("*");
			}

		} else if (property.cardinality() !== undefined) {
			d3.select("#minCardinality").style("display", "none");
			d3.select("#maxCardinality").style("display", "none");
			d3.select("#infoCardinality").style("display", "block");
			d3.select("#infoCardinality span").text(property.cardinality());
		} else {
			d3.select("#infoCardinality").style("display", "none");
			d3.select("#minCardinality").style("display", "none");
			d3.select("#maxCardinality").style("display", "none");
		}

		setUriLabel(d3.select("#domain"), property.domain().label(), property.domain().uri());
		setUriLabel(d3.select("#range"), property.range().label(), property.range().uri());

		displayAttributes(property.attributes(), d3.select("#propAttributes"));
	}

	function showPropertyInformations() {
		setSelectionInformationVisibility(false, true, false);
	}

	function setUriLabel(element, name, uri) {
		element.selectAll("*").remove();
		appendUriLabel(element, name, uri);
	}

	function appendUriLabel(element, name, uri) {
		var tag;

		if (uri) {
			tag = element.append("a").attr("href", uri).attr("target", "_blank");
		} else {
			tag = element.append("span");
		}
		tag.text(name);
	}

	function displayAttributes(attributes, textSpan) {
		var spanParent = d3.select(textSpan.node().parentNode);

		if (attributes && attributes.length > 0) {
			textSpan.text(attributes.join(", "));

			spanParent.classed("hidden", false);
		} else {
			spanParent.classed("hidden", true);
		}
	}

	function displayNodeInformation(node) {
		showClassInformations();

		setUriLabel(d3.select("#name"), node.label(), node.uri());

		/* Equivalent stuff. */
		var equivalentUriSpan = d3.select("#classEquivUri");
		displayEquivalentElements(node.equivalent(), equivalentUriSpan);

		d3.select("#typeNode").text(node.type());

		/* Disjoint stuff. */
		var disjointNodes = d3.select("#disjointNodes");
		var disjointNodesParent = d3.select(disjointNodes.node().parentNode);

		if (node.disjointWith() !== undefined) {
			disjointNodes.selectAll("*").remove();

			node.disjointWith().forEach(function (element, index) {
				if (index > 0) {
					disjointNodes.append("span").text(", ");
				}
				appendUriLabel(disjointNodes, element.label(), element.uri());
			});

			disjointNodesParent.classed("hidden", false);
		} else {
			disjointNodesParent.classed("hidden", true);
		}

		displayAttributes(node.attributes(), d3.select("#classAttributes"));
	}

	function showClassInformations() {
		setSelectionInformationVisibility(true, false, false);
	}

	function displayEquivalentElements(equivalentElements, equivalentUriSpan) {
		var equivalentUriSpanParent = d3.select(equivalentUriSpan.node().parentNode);

		if (equivalentElements !== undefined) {
			equivalentUriSpan.selectAll("*").remove();
			equivalentElements.forEach(function (element, index) {
				if (index > 0) {
					equivalentUriSpan.append("span").text(", ");
				}
				appendUriLabel(equivalentUriSpan, element.label(), element.uri());
			});

			equivalentUriSpanParent.classed("hidden", false);
		} else {
			equivalentUriSpanParent.classed("hidden", true);
		}
	}

	return sidebar;
};
<|endoftext|>


<commit_before>/* Licensed under the MIT license:
 * http://www.opensource.org/licenses/mit-license.php
 * Copyright (c) 2010 Mr.doob, rhyolight, bebraw
 */
function web() {
    this.init();
}
web.prototype = {
    init: function () {
        this.points = [];
    },
    destroy: function () {},
    stroke: function (canvas, cursor, color, opacity) {
        var e, b, a, g;

        this.points.push(cursor.current);
        count = this.points.length - 1;

        canvas.stroke(cursor.previous, cursor.current, color, opacity);

        for (e = 0; e < this.points.length; e++) {
            b = this.points[e].x - this.points[count].x;
            a = this.points[e].y - this.points[count].y;
            g = b * b + a * a;

            if (g < 2500 && Math.random() > 0.9) {
                canvas.stroke(this.points[count], this.points[e], color, 0.1); // XXX: derive based on opacity? (orig. 0.5)
            }
        }
    }
};
<commit_msg>Tidied up web brush and exposed opacity in a nicer way.<commit_after>/* Licensed under the MIT license:
 * http://www.opensource.org/licenses/mit-license.php
 * Copyright (c) 2010 Mr.doob, rhyolight, bebraw
 */
function web() {
    this.init();
}
web.prototype = {
    init: function () {
        this.points = [];
    },
    destroy: function () {},
    stroke: function (canvas, cursor, color, opacity) {
        this.points.push(cursor.current);

        canvas.stroke(cursor.previous, cursor.current, color, opacity);

        for (var e = 0; e < this.points.length; e++) {
            g = this.points[e].sub(cursor.current).toDist();

            if (g < 2500 && Math.random() > 0.9) {
                canvas.stroke(cursor.current, this.points[e], color,
                    opacity / 2);
            }
        }
    }
};
<|endoftext|>