<commit_before>/**
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you 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.
*/
var cordova = require('../cordova'),
    shell = require('shelljs'),
    plugman = require('plugman'),
    path = require('path'),
    fs = require('fs'),
    util = require('../src/util'),
    lazy_load = require('../src/lazy_load'),
    platforms = require('../platforms'),
    hooker = require('../src/hooker'),
    fixtures = path.join(__dirname, 'fixtures'),
    hooks = path.join(fixtures, 'hooks');

var project_dir = '/some/path';
var supported_platforms = Object.keys(platforms).filter(function(p) { return p != 'www'; });
var supported_platforms_paths = supported_platforms.map(function(p) { return path.join(project_dir, 'platforms', p, 'www'); });

describe('prepare command', function() {
    var is_cordova, list_platforms, fire, config_parser, parsers = {}, plugman_prepare, find_plugins, plugman_get_json, load;
    beforeEach(function() {
        is_cordova = spyOn(util, 'isCordova').andReturn(project_dir);
        list_platforms = spyOn(util, 'listPlatforms').andReturn(supported_platforms);
        fire = spyOn(hooker.prototype, 'fire').andCallFake(function(e, opts, cb) {
            cb(false);
        });
        config_parser = spyOn(util, 'config_parser');
        supported_platforms.forEach(function(p) {
            parsers[p] = jasmine.createSpy(p + ' update_project').andCallFake(function(cfg, cb) {
                cb();
            });
            spyOn(platforms[p], 'parser').andReturn({
                update_project:parsers[p],
                www_dir:function() { return path.join(project_dir, 'platforms', p, 'www'); }
            });
        });
        plugman_prepare = spyOn(plugman, 'prepare');
        find_plugins = spyOn(util, 'findPlugins').andReturn([]);
        plugman_get_json = spyOn(plugman.config_changes, 'get_platform_json').andReturn({});
        load = spyOn(lazy_load, 'based_on_config').andCallFake(function(root, platform, cb) { cb(); });
    });

    describe('failure', function() {
        it('should not run outside of a cordova-based project by calling util.isCordova', function() {
            is_cordova.andReturn(false);
            expect(function() {
                cordova.prepare();
                expect(is_cordova).toHaveBeenCalled();
            }).toThrow('Current working directory is not a Cordova-based project.');
        });
        it('should not run inside a cordova-based project with no platforms', function() {
            list_platforms.andReturn([]);
            expect(function() {
                cordova.prepare();
            }).toThrow('No platforms added to this project. Please use `cordova platform add <platform>`.');
        });
    });

    describe('success', function() {
        it('should run inside a Cordova-based project by calling util.isCordova', function() {
            cordova.prepare();
            expect(is_cordova).toHaveBeenCalled();
        });
        it('should parse user\'s config.xml by calling instantiating a config_parser', function() {
            cordova.prepare();
            expect(config_parser).toHaveBeenCalledWith(path.join(project_dir, 'www', 'config.xml'));
        });
        it('should invoke each platform\'s parser\'s update_project method', function() {
            cordova.prepare();
            supported_platforms.forEach(function(p) {
                expect(parsers[p]).toHaveBeenCalled();
            });
        });
        it('should invoke lazy_load for each platform to make sure platform libraries are loaded', function() {
            cordova.prepare();
            supported_platforms.forEach(function(p) {
                expect(load).toHaveBeenCalledWith(project_dir, p, jasmine.any(Function));
            });
        });
        describe('plugman integration', function() {
            it('should invoke plugman.prepare after update_project', function() {
                cordova.prepare();
                var plugins_dir = path.join(project_dir, 'plugins');
                supported_platforms.forEach(function(p) {
                    var platform_path = path.join(project_dir, 'platforms', p);
                    expect(plugman_prepare).toHaveBeenCalledWith(platform_path, (p=='blackberry'?'blackberry10':p), plugins_dir);
                });
            });
            it('should invoke add_plugin_changes for any added plugins to verify configuration changes for plugins are in place', function() {
                var plugins_dir = path.join(project_dir, 'plugins');
                find_plugins.andReturn(['testPlugin']);
                plugman_get_json.andReturn({
                    installed_plugins:{
                        'testPlugin':'plugin vars'
                    }
                });
                var add_plugin_changes = spyOn(plugman.config_changes, 'add_plugin_changes');
                cordova.prepare();
                supported_platforms.forEach(function(p) {
                    var platform_path = path.join(project_dir, 'platforms', p);
                    expect(add_plugin_changes).toHaveBeenCalledWith((p=='blackberry'?'blackberry10':p), platform_path, plugins_dir, 'testPlugin', 'plugin vars', true, false);
                });
            });
        });
    });

    describe('hooks', function() {
        describe('when platforms are added', function() {
            it('should fire before hooks through the hooker module, and pass in platforms and paths as data object', function() {
                cordova.prepare();
                expect(fire).toHaveBeenCalledWith('before_prepare', {platforms:supported_platforms, paths:supported_platforms_paths}, jasmine.any(Function));
            });
            it('should fire after hooks through the hooker module, and pass in platforms and paths as data object', function(done) {
                cordova.prepare('android', function() {
                     expect(fire).toHaveBeenCalledWith('after_prepare', {platforms:['android'], paths:[path.join(project_dir, 'platforms', 'android', 'www')]}, jasmine.any(Function));
                     done();
                });
            });
        });

        describe('with no platforms added', function() {
            beforeEach(function() {
                list_platforms.andReturn([]);
            });
            it('should not fire the hooker', function() {
                expect(function() {
                    cordova.prepare();
                }).toThrow();
                expect(fire).not.toHaveBeenCalledWith('before_prepare');
                expect(fire).not.toHaveBeenCalledWith('after_prepare');
            });
        });
    });
});
<commit_msg>Added a spec for [CB-4376].<commit_after>/**
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you 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.
*/
var cordova = require('../cordova'),
    shell = require('shelljs'),
    plugman = require('plugman'),
    path = require('path'),
    fs = require('fs'),
    util = require('../src/util'),
    lazy_load = require('../src/lazy_load'),
    platforms = require('../platforms'),
    hooker = require('../src/hooker'),
    fixtures = path.join(__dirname, 'fixtures'),
    hooks = path.join(fixtures, 'hooks');

var project_dir = '/some/path';
var supported_platforms = Object.keys(platforms).filter(function(p) { return p != 'www'; });
var supported_platforms_paths = supported_platforms.map(function(p) { return path.join(project_dir, 'platforms', p, 'www'); });

describe('prepare command', function() {
    var is_cordova, list_platforms, fire, config_parser, parsers = {}, plugman_prepare, find_plugins, plugman_get_json, load;
    beforeEach(function() {
        is_cordova = spyOn(util, 'isCordova').andReturn(project_dir);
        list_platforms = spyOn(util, 'listPlatforms').andReturn(supported_platforms);
        fire = spyOn(hooker.prototype, 'fire').andCallFake(function(e, opts, cb) {
            cb(false);
        });
        config_parser = spyOn(util, 'config_parser');
        supported_platforms.forEach(function(p) {
            parsers[p] = jasmine.createSpy(p + ' update_project').andCallFake(function(cfg, cb) {
                cb();
            });
            spyOn(platforms[p], 'parser').andReturn({
                update_project:parsers[p],
                www_dir:function() { return path.join(project_dir, 'platforms', p, 'www'); }
            });
        });
        plugman_prepare = spyOn(plugman, 'prepare');
        find_plugins = spyOn(util, 'findPlugins').andReturn([]);
        plugman_get_json = spyOn(plugman.config_changes, 'get_platform_json').andReturn({});
        load = spyOn(lazy_load, 'based_on_config').andCallFake(function(root, platform, cb) { cb(); });
    });

    describe('failure', function() {
        it('should not run outside of a cordova-based project by calling util.isCordova', function() {
            is_cordova.andReturn(false);
            expect(function() {
                cordova.prepare();
                expect(is_cordova).toHaveBeenCalled();
            }).toThrow('Current working directory is not a Cordova-based project.');
        });
        it('should not run inside a cordova-based project with no platforms', function() {
            list_platforms.andReturn([]);
            expect(function() {
                cordova.prepare();
            }).toThrow('No platforms added to this project. Please use `cordova platform add <platform>`.');
        });
    });

    describe('success', function() {
        it('should run inside a Cordova-based project by calling util.isCordova', function() {
            cordova.prepare();
            expect(is_cordova).toHaveBeenCalled();
        });
        it('should parse user\'s config.xml by instantiating a config_parser only _after_ before_prepare is called', function() {
            var before_prep, after_prep, cont;
            fire.andCallFake(function(e, opts, cb) {
                if (e == 'before_prepare') {
                    before_prep = true;
                }
                cont = cb;
            });
            runs(function() {
                cordova.prepare();
            });
            waitsFor(function() { return before_prep; });
            runs(function() {
                expect(config_parser).not.toHaveBeenCalled();
                cont();
                expect(config_parser).toHaveBeenCalledWith(path.join(project_dir, 'www', 'config.xml'));
            });
        });
        it('should invoke each platform\'s parser\'s update_project method', function() {
            cordova.prepare();
            supported_platforms.forEach(function(p) {
                expect(parsers[p]).toHaveBeenCalled();
            });
        });
        it('should invoke lazy_load for each platform to make sure platform libraries are loaded', function() {
            cordova.prepare();
            supported_platforms.forEach(function(p) {
                expect(load).toHaveBeenCalledWith(project_dir, p, jasmine.any(Function));
            });
        });
        describe('plugman integration', function() {
            it('should invoke plugman.prepare after update_project', function() {
                cordova.prepare();
                var plugins_dir = path.join(project_dir, 'plugins');
                supported_platforms.forEach(function(p) {
                    var platform_path = path.join(project_dir, 'platforms', p);
                    expect(plugman_prepare).toHaveBeenCalledWith(platform_path, (p=='blackberry'?'blackberry10':p), plugins_dir);
                });
            });
            it('should invoke add_plugin_changes for any added plugins to verify configuration changes for plugins are in place', function() {
                var plugins_dir = path.join(project_dir, 'plugins');
                find_plugins.andReturn(['testPlugin']);
                plugman_get_json.andReturn({
                    installed_plugins:{
                        'testPlugin':'plugin vars'
                    }
                });
                var add_plugin_changes = spyOn(plugman.config_changes, 'add_plugin_changes');
                cordova.prepare();
                supported_platforms.forEach(function(p) {
                    var platform_path = path.join(project_dir, 'platforms', p);
                    expect(add_plugin_changes).toHaveBeenCalledWith((p=='blackberry'?'blackberry10':p), platform_path, plugins_dir, 'testPlugin', 'plugin vars', true, false);
                });
            });
        });
    });

    describe('hooks', function() {
        describe('when platforms are added', function() {
            it('should fire before hooks through the hooker module, and pass in platforms and paths as data object', function() {
                cordova.prepare();
                expect(fire).toHaveBeenCalledWith('before_prepare', {platforms:supported_platforms, paths:supported_platforms_paths}, jasmine.any(Function));
            });
            it('should fire after hooks through the hooker module, and pass in platforms and paths as data object', function(done) {
                cordova.prepare('android', function() {
                     expect(fire).toHaveBeenCalledWith('after_prepare', {platforms:['android'], paths:[path.join(project_dir, 'platforms', 'android', 'www')]}, jasmine.any(Function));
                     done();
                });
            });
        });

        describe('with no platforms added', function() {
            beforeEach(function() {
                list_platforms.andReturn([]);
            });
            it('should not fire the hooker', function() {
                expect(function() {
                    cordova.prepare();
                }).toThrow();
                expect(fire).not.toHaveBeenCalledWith('before_prepare');
                expect(fire).not.toHaveBeenCalledWith('after_prepare');
            });
        });
    });
});
<|endoftext|>


<commit_before>/**
 * Data Descriptor
 * Used to facilitate ZIP file streaming.
 * @return {DataDescriptor}
 */
function DataDescriptor() {

  if( !(this instanceof DataDescriptor) )
    return new DataDescriptor()

  this.signature = DataDescriptor.SIGNATURE
  this.crc32 = 0x00000000
  this.compressedSize = 0x00000000
  this.size = 0x00000000

}

/**
 * Although not originally assigned a signature,
 * this value has commonly been adopted as a
 * signature value for the data descriptor record.
 * @type {Number}
 */
DataDescriptor.SIGNATURE = 0x08074B50

/**
 * DataDescriptor prototype
 * @type {Object}
 */
DataDescriptor.prototype = {

  constructor: DataDescriptor,

  parse: function( buffer ) {
    // TODO
  },

  toBuffer: function() {
    // TODO
  },

}

// Exports
module.exports = DataDescriptor
<commit_msg>Update data-descriptor: Add impl notes<commit_after>/**
 * Data Descriptor
 * Used to facilitate ZIP file streaming.
 * NOTE: This descriptor MUST exist if bit 3 of
 * the general purpose bit flag is set.
 * @return {DataDescriptor}
 */
function DataDescriptor() {

  if( !(this instanceof DataDescriptor) )
    return new DataDescriptor()

  this.signature = DataDescriptor.SIGNATURE

  // NOTE: For ZIP64(tm) format archives,
  // the compressed and uncompressed sizes are 8 bytes each.
  this.crc32 = 0x00000000
  this.compressedSize = 0x00000000
  this.size = 0x00000000

}

/**
 * Data Descriptor Signature
 *
 * Although not originally assigned a signature,
 * this value has commonly been adopted as a
 * signature value for the data descriptor record.
 *
 * NOTE: Implementers should be aware that ZIP files
 * may be encountered with or without this
 * signature marking data descriptors.
 *
 * @type {Number}
 */
DataDescriptor.SIGNATURE = 0x08074B50

/**
 * DataDescriptor prototype
 * @type {Object}
 */
DataDescriptor.prototype = {

  constructor: DataDescriptor,

  parse: function( buffer ) {
    // TODO
  },

  toBuffer: function() {

    // NOTE: When compressing files, compressed and uncompressed sizes
    // should be stored in ZIP64 format (as 8 byte values) when a
    // file's size exceeds 0xFFFFFFFF

    // NOTE: When writing ZIP files, implementors SHOULD include the
    // signature value marking the data descriptor record.

    // NOTE: When the Central Directory Encryption method is used,
    // the data descriptor record is not required, but MAY be used.
    // If present, and bit 3 of the general purpose bit field is set to
    // indicate its presence, the values in fields of the data descriptor
    // record MUST be set to binary zeros.

    // TODO

  },

}

// Exports
module.exports = DataDescriptor
<|endoftext|>


<commit_before>var nativeNroonga = require('nroonga');
var nroonga = require('../wrapped-nroonga');
var IndexField = require('./index-field').IndexField;

exports.MINIMUM_NAME_LENGTH = 3;
exports.MAXIMUM_NAME_LENGTH = 28;
exports.INVALID_NAME_CHARACTER_PATTERN = /[^\-a-z0-9]/g;
exports.INVALID_TABLE_NAME_CHARACTER_PATTERN = /[^_a-z0-9]/g;

var DEFAULT_ID =
      exports.DEFAULT_ID =
      Domain.DEFAULT_ID = '00000000000000000000000000';

var DOMAIN_TABLE_PREFIX =
      exports.DOMAIN_TABLE_PREFIX =
      Domain.DOMAIN_TABLE_PREFIX = 'domain';

var REFERENCE_TABLE_PREFIX =
      exports.REFERENCE_TABLE_PREFIX =
      Domain.REFERENCE_TABLE_PREFIX = 'reference';

function assertValidDomainName(domain) {
  if (typeof domain != 'string')
    throw new Error('domain name must be a string');

  if (domain.length < exports.MINIMUM_NAME_LENGTH)
    throw new Error('too short domain name (minimum length = ' +
                    exports.MINIMUM_NAME_LENGTH + ')');

  if (domain.length > exports.MAXIMUM_NAME_LENGTH)
    throw new Error('too long domain name (max length = ' +
                   exports.MAXIMUM_NAME_LENGTH + ')');

  var invalidCharacter = domain.match(exports.INVALID_NAME_CHARACTER_PATTERN) ||
                         domain.match(exports.INVALID_TABLE_NAME_CHARACTER_PATTERN);
  if (invalidCharacter) {
    var characters = Array.prototype.map.call(invalidCharacter, function(aCharacter) {
                       return '"' + aCharacter + '"';
                     });
    throw new Error(characters.join(', ') + ' cannot appear in a domain name');
  }
}

// Accepts two arguments: source and context.
// You can give them in the reversed order, like:
// new Domain("source", context) or new Domain(context, "source")
function Domain() {
  var source, context;
  for (var i = 0, maxi = arguments.length, argument; i < maxi; i++) {
    argument = arguments[i];
    if (!argument) continue;
    if (argument instanceof nroonga.Context ||
        argument instanceof nativeNroonga.Database) {
      context = argument;
    } else if (argument) {
      source = argument;
    }
  }

  if (source instanceof Domain)
    return source;

  this.initialize(source, context);
}
Domain.prototype = {
  initialize: function(source, context) {
    this.cachedIndexFields = {};

    this.context = context && new nroonga.Context(context);
    this.initializeNameAndId(source);

    // for validation
    this.tableName;
    this.termsTableName;
  },
  initializeNameAndId: function(source) {
    if (typeof source == 'string') {
      this.name = source;
      this.initializeId();
      return;
    }

    if (source.headers && source.headers.host) {
      var host = source.headers.host;
      var nameAndIdFromHost = Domain.getNameAndIdFromHost(host);
      if (nameAndIdFromHost.name) {
        this.name = nameAndIdFromHost.name;
        this.id = nameAndIdFromHost.id;
        return;
      }
    }

    if (source.url) {
      var nameAndIdFromPath = Domain.getNameAndIdFromPath(source.url);
      if (nameAndIdFromPath.name) {
        this.name = nameAndIdFromPath.name;
        this.id = nameAndIdFromPath.id;
        return;
      }
    }

    throw new Error('no domain name');
  },
  initializeId: function() {
    this.id = this.getIdFromDatabase() || this.createNewId();
  },
  getIdFromDatabase: function() {
    if (this.context) {
      var tableName = Domain.toTableNamePart(this.name);
      var tables = this.context.tableListSync();
      var tableIdMatcher = new RegExp('^' + DOMAIN_TABLE_PREFIX + '_' + tableName + '_([^_]+)$');
      var id;
      if (tables.some(function(table) {
            var match = table.name.match(tableIdMatcher);
            if (match) {
              id = match[1];
              return true;
            }
            return false;
          }, this))
        return id;
    }
    return null;
  },
  createNewId: function() {
    var size = 26;
    var characters = '0123456789abcdefghijklmnopqrstuvwxyz'.split('');
    var lastIndex = characters.length;
    var id = '';
    while (id.length < size) {
      id += characters[Math.round(Math.random() * lastIndex)];
    }
    return id;
  },

  get tableName() {
    if (!this._tableName) {
      assertValidDomainName(this.name);
      this._tableName = DOMAIN_TABLE_PREFIX + '_' +
                        Domain.toTableNamePart(this.name) + '_' + this.id;
    }
    return this._tableName;
  },

  get referenceTableBaseName() {
    if (!this._referenceTableBaseName)
      this._referenceTableBaseName = REFERENCE_TABLE_PREFIX + '_' +
                             Domain.toTableNamePart(this.name) + '_' + this.id;
    return this._referenceTableBaseName;
  },

  get termsTableName() {
    return this.referenceTableBaseName + '_BigramTerms';
  },

  get synonymTableName() {
    return this.referenceTableBaseName + '_synonyms';
  },

  getIndexField: function(field) {
    return this.cachedIndexFields[field] ||
           (this.cachedIndexFields[field] = new IndexField(field, this));
  },
  get indexFields() {
    if (!this.context)
      throw new Error('no context');
    var columns = this.context.ordinalColumnsSync(this.tableName);
    var fields = columns.map(function(column) {
                   // XXX The "name" must be the field name given by the user,
                   // not normalized. Because there is no such information in the
                   // context and currently the column name is luckily equals to the
                   // given field name, we can use the column name.
                   var name = column.name;
                   return this.getIndexField(name);
                 }, this);
    return fields;
  },

  get id() {
    return this._id === undefined ? DEFAULT_ID : this._id ;
  },
  set id(value) {
    this._id = value;
    // clear caches
    delete this._tableName;
    delete this._referenceTableBaseName;
    return value;
  },

  get domainId() {
    return this.id + '/' + this.name;
  },

  get searchableDocumentsCount() {
    return 0;
  },
  get requiresIndexDocuments() {
    return false;
  },
  get searchInstanceCount() {
    return 0;
  },
  get searchPartitionCount() {
    return 0;
  },

  getDocumentsEndpoint: function(hostname) {
    if (hostname[0] != '.')
      hostname = '.' + hostname;
    return 'doc-' + this.name + '-' + this.id + hostname;
  },
  getSearchEndpoint: function(hostname) {
    if (hostname[0] != '.')
      hostname = '.' + hostname;
    return 'search-' + this.name + '-' + this.id + hostname;
  },

  createSync: function() {
    if (!this.context)
      throw new Error('no context');

    this.context.commandSync('table_create', {
      name: this.tableName,
      flags: nroonga.TABLE_HASH_KEY,
      key_type: nroonga.ShortText
    });
    this.context.commandSync('table_create', {
      name: this.termsTableName,
      flags: nroonga.TABLE_PAT_KEY + '|' + nroonga.KEY_NORMALIZE,
      key_type: nroonga.ShortText,
      default_tokenizer: nroonga.TokenBigram
    });
  },

  deleteSync: function() {
    if (!this.context)
      throw new Error('no context');

    this.context.commandSync('table_remove', {
      name: this.tableName
    });
    this.context.commandSync('table_remove', {
      name: this.termsTableName
    });
  },

  reindexSync: function() {
    this.indexFields.forEach(function(field) {
      field.reindexSync();
    });
  },

  updateSynonymsSync: function(synonymOptions) {
    if (!this.context)
      throw new Error('no context');
    var synonyms = synonymOptions.synonyms;

    try {
      this.context.commandSync('table_remove', {
        table: this.synonymTableName
      });
    } catch (error) {
      // The synonym table should be inexistent. Do nothing.
    }

    this.context.commandSync('table_create', {
      name: this.synonymTableName,
      flags: nroonga.TABLE_HASH_KEY,
      key_type: nroonga.ShortText,
      flags: nroonga.KEY_NORMALIZE
    });
    this.context.commandSync('column_create', {
      table: this.synonymTableName,
      name: 'synonyms',
      type: nroonga.ShortText,
      flags: nroonga.COLUMN_VECTOR
    });

    var load = Object.keys(synonyms).map(function(key) {
      return {_key: key, synonyms: synonyms[key]};
    });
    this.context.commandSync('load', {
      table: this.synonymTableName,
      values: JSON.stringify(load)
    });
  },

  isSynonymTableAvailableSync: function() {
    var tables = this.context.tableListSync();
    return tables.some(function(table) {
      return table.name === this.synonymTableName;
    }, this);
  },

  exists: function() {
    return !!this.getIdFromDatabase();
  }
};

exports.Domain = Domain;

Domain.getNameAndIdFromHost = function(host) {
  var domainMatcher = /^(?:doc|search)-([^\.]+)-([^\.\-]+)\./;
  var match = host.match(domainMatcher);
  if (match)
    return { name: match[1], id: match[2] };

  return { name: '', id: '' };
};

Domain.getNameAndIdFromPath = function(path) {
  var domainMatcher = /^\/gcs\/([^\/]+)-([^\/\-]+)/;

  var match = path.match(domainMatcher);
  if (match)
    return { name: match[1], id: match[2] };

  return { name: '', id: '' };
};

Domain.toTableNamePart = function(domainName) {
  return domainName;
};
Domain.toDonamName = function(tableNamePart) {
  return tableNamePart;
};

Domain.getAll = function(context) {
  context = context && new nroonga.Context(context);

  var tables = context.tableListSync();
  var tableMatcher = new RegExp('^' + DOMAIN_TABLE_PREFIX + '_([^_]+)_([^_]+)$');
  var domains = [];
  tables.forEach(function(table) {
    var match = table.name.match(tableMatcher);
    if (match) {
      var name = Domain.toDonamName(match[1]);
      domains.push(new Domain(name, context));
    }
  });
  domains.sort(function(a, b) { return a.name - b.name; });
  return domains;
};
<commit_msg>Return sorted index fields<commit_after>var nativeNroonga = require('nroonga');
var nroonga = require('../wrapped-nroonga');
var IndexField = require('./index-field').IndexField;

exports.MINIMUM_NAME_LENGTH = 3;
exports.MAXIMUM_NAME_LENGTH = 28;
exports.INVALID_NAME_CHARACTER_PATTERN = /[^\-a-z0-9]/g;
exports.INVALID_TABLE_NAME_CHARACTER_PATTERN = /[^_a-z0-9]/g;

var DEFAULT_ID =
      exports.DEFAULT_ID =
      Domain.DEFAULT_ID = '00000000000000000000000000';

var DOMAIN_TABLE_PREFIX =
      exports.DOMAIN_TABLE_PREFIX =
      Domain.DOMAIN_TABLE_PREFIX = 'domain';

var REFERENCE_TABLE_PREFIX =
      exports.REFERENCE_TABLE_PREFIX =
      Domain.REFERENCE_TABLE_PREFIX = 'reference';

function assertValidDomainName(domain) {
  if (typeof domain != 'string')
    throw new Error('domain name must be a string');

  if (domain.length < exports.MINIMUM_NAME_LENGTH)
    throw new Error('too short domain name (minimum length = ' +
                    exports.MINIMUM_NAME_LENGTH + ')');

  if (domain.length > exports.MAXIMUM_NAME_LENGTH)
    throw new Error('too long domain name (max length = ' +
                   exports.MAXIMUM_NAME_LENGTH + ')');

  var invalidCharacter = domain.match(exports.INVALID_NAME_CHARACTER_PATTERN) ||
                         domain.match(exports.INVALID_TABLE_NAME_CHARACTER_PATTERN);
  if (invalidCharacter) {
    var characters = Array.prototype.map.call(invalidCharacter, function(aCharacter) {
                       return '"' + aCharacter + '"';
                     });
    throw new Error(characters.join(', ') + ' cannot appear in a domain name');
  }
}

// Accepts two arguments: source and context.
// You can give them in the reversed order, like:
// new Domain("source", context) or new Domain(context, "source")
function Domain() {
  var source, context;
  for (var i = 0, maxi = arguments.length, argument; i < maxi; i++) {
    argument = arguments[i];
    if (!argument) continue;
    if (argument instanceof nroonga.Context ||
        argument instanceof nativeNroonga.Database) {
      context = argument;
    } else if (argument) {
      source = argument;
    }
  }

  if (source instanceof Domain)
    return source;

  this.initialize(source, context);
}
Domain.prototype = {
  initialize: function(source, context) {
    this.cachedIndexFields = {};

    this.context = context && new nroonga.Context(context);
    this.initializeNameAndId(source);

    // for validation
    this.tableName;
    this.termsTableName;
  },
  initializeNameAndId: function(source) {
    if (typeof source == 'string') {
      this.name = source;
      this.initializeId();
      return;
    }

    if (source.headers && source.headers.host) {
      var host = source.headers.host;
      var nameAndIdFromHost = Domain.getNameAndIdFromHost(host);
      if (nameAndIdFromHost.name) {
        this.name = nameAndIdFromHost.name;
        this.id = nameAndIdFromHost.id;
        return;
      }
    }

    if (source.url) {
      var nameAndIdFromPath = Domain.getNameAndIdFromPath(source.url);
      if (nameAndIdFromPath.name) {
        this.name = nameAndIdFromPath.name;
        this.id = nameAndIdFromPath.id;
        return;
      }
    }

    throw new Error('no domain name');
  },
  initializeId: function() {
    this.id = this.getIdFromDatabase() || this.createNewId();
  },
  getIdFromDatabase: function() {
    if (this.context) {
      var tableName = Domain.toTableNamePart(this.name);
      var tables = this.context.tableListSync();
      var tableIdMatcher = new RegExp('^' + DOMAIN_TABLE_PREFIX + '_' + tableName + '_([^_]+)$');
      var id;
      if (tables.some(function(table) {
            var match = table.name.match(tableIdMatcher);
            if (match) {
              id = match[1];
              return true;
            }
            return false;
          }, this))
        return id;
    }
    return null;
  },
  createNewId: function() {
    var size = 26;
    var characters = '0123456789abcdefghijklmnopqrstuvwxyz'.split('');
    var lastIndex = characters.length;
    var id = '';
    while (id.length < size) {
      id += characters[Math.round(Math.random() * lastIndex)];
    }
    return id;
  },

  get tableName() {
    if (!this._tableName) {
      assertValidDomainName(this.name);
      this._tableName = DOMAIN_TABLE_PREFIX + '_' +
                        Domain.toTableNamePart(this.name) + '_' + this.id;
    }
    return this._tableName;
  },

  get referenceTableBaseName() {
    if (!this._referenceTableBaseName)
      this._referenceTableBaseName = REFERENCE_TABLE_PREFIX + '_' +
                             Domain.toTableNamePart(this.name) + '_' + this.id;
    return this._referenceTableBaseName;
  },

  get termsTableName() {
    return this.referenceTableBaseName + '_BigramTerms';
  },

  get synonymTableName() {
    return this.referenceTableBaseName + '_synonyms';
  },

  getIndexField: function(field) {
    return this.cachedIndexFields[field] ||
           (this.cachedIndexFields[field] = new IndexField(field, this));
  },
  get indexFields() {
    if (!this.context)
      throw new Error('no context');
    var columns = this.context.ordinalColumnsSync(this.tableName);
    columns = columns.sort(function(a, b) { return a.name - b.name; });
    var fields = columns.map(function(column) {
                   // XXX The "name" must be the field name given by the user,
                   // not normalized. Because there is no such information in the
                   // context and currently the column name is luckily equals to the
                   // given field name, we can use the column name.
                   var name = column.name;
                   return this.getIndexField(name);
                 }, this);
    return fields;
  },

  get id() {
    return this._id === undefined ? DEFAULT_ID : this._id ;
  },
  set id(value) {
    this._id = value;
    // clear caches
    delete this._tableName;
    delete this._referenceTableBaseName;
    return value;
  },

  get domainId() {
    return this.id + '/' + this.name;
  },

  get searchableDocumentsCount() {
    return 0;
  },
  get requiresIndexDocuments() {
    return false;
  },
  get searchInstanceCount() {
    return 0;
  },
  get searchPartitionCount() {
    return 0;
  },

  getDocumentsEndpoint: function(hostname) {
    if (hostname[0] != '.')
      hostname = '.' + hostname;
    return 'doc-' + this.name + '-' + this.id + hostname;
  },
  getSearchEndpoint: function(hostname) {
    if (hostname[0] != '.')
      hostname = '.' + hostname;
    return 'search-' + this.name + '-' + this.id + hostname;
  },

  createSync: function() {
    if (!this.context)
      throw new Error('no context');

    this.context.commandSync('table_create', {
      name: this.tableName,
      flags: nroonga.TABLE_HASH_KEY,
      key_type: nroonga.ShortText
    });
    this.context.commandSync('table_create', {
      name: this.termsTableName,
      flags: nroonga.TABLE_PAT_KEY + '|' + nroonga.KEY_NORMALIZE,
      key_type: nroonga.ShortText,
      default_tokenizer: nroonga.TokenBigram
    });
  },

  deleteSync: function() {
    if (!this.context)
      throw new Error('no context');

    this.context.commandSync('table_remove', {
      name: this.tableName
    });
    this.context.commandSync('table_remove', {
      name: this.termsTableName
    });
  },

  reindexSync: function() {
    this.indexFields.forEach(function(field) {
      field.reindexSync();
    });
  },

  updateSynonymsSync: function(synonymOptions) {
    if (!this.context)
      throw new Error('no context');
    var synonyms = synonymOptions.synonyms;

    try {
      this.context.commandSync('table_remove', {
        table: this.synonymTableName
      });
    } catch (error) {
      // The synonym table should be inexistent. Do nothing.
    }

    this.context.commandSync('table_create', {
      name: this.synonymTableName,
      flags: nroonga.TABLE_HASH_KEY,
      key_type: nroonga.ShortText,
      flags: nroonga.KEY_NORMALIZE
    });
    this.context.commandSync('column_create', {
      table: this.synonymTableName,
      name: 'synonyms',
      type: nroonga.ShortText,
      flags: nroonga.COLUMN_VECTOR
    });

    var load = Object.keys(synonyms).map(function(key) {
      return {_key: key, synonyms: synonyms[key]};
    });
    this.context.commandSync('load', {
      table: this.synonymTableName,
      values: JSON.stringify(load)
    });
  },

  isSynonymTableAvailableSync: function() {
    var tables = this.context.tableListSync();
    return tables.some(function(table) {
      return table.name === this.synonymTableName;
    }, this);
  },

  exists: function() {
    return !!this.getIdFromDatabase();
  }
};

exports.Domain = Domain;

Domain.getNameAndIdFromHost = function(host) {
  var domainMatcher = /^(?:doc|search)-([^\.]+)-([^\.\-]+)\./;
  var match = host.match(domainMatcher);
  if (match)
    return { name: match[1], id: match[2] };

  return { name: '', id: '' };
};

Domain.getNameAndIdFromPath = function(path) {
  var domainMatcher = /^\/gcs\/([^\/]+)-([^\/\-]+)/;

  var match = path.match(domainMatcher);
  if (match)
    return { name: match[1], id: match[2] };

  return { name: '', id: '' };
};

Domain.toTableNamePart = function(domainName) {
  return domainName;
};
Domain.toDonamName = function(tableNamePart) {
  return tableNamePart;
};

Domain.getAll = function(context) {
  context = context && new nroonga.Context(context);

  var tables = context.tableListSync();
  var tableMatcher = new RegExp('^' + DOMAIN_TABLE_PREFIX + '_([^_]+)_([^_]+)$');
  var domains = [];
  tables.forEach(function(table) {
    var match = table.name.match(tableMatcher);
    if (match) {
      var name = Domain.toDonamName(match[1]);
      domains.push(new Domain(name, context));
    }
  });
  domains.sort(function(a, b) { return a.name - b.name; });
  return domains;
};
<|endoftext|>


<commit_before>define(function (require, exports, module) {
    //requirements
    var get = require('bower_components/get/get'),
        set = require('bower_components/set/set'),
        deepExtend = require('bower_components/deepExtend/deepExtend'),
        makeClass = require('bower_components/makeClass/makeClass'),

        Backbone = require('bower_components/backbone/backbone'),
        _ = require('bower_components/lodash/lodash'),
        $ = require('jquery');

    var View = Backbone.View;

    /**
     * расширенный класс Backbone.View
     * @class Block
     * @param {Object} opt block options
     * @param {String | HTMLElement} opt.el элемент к которому будет привязан блок
     * @param {Function} opt.template шаблон, который будет использован для формирования DOM элемента блока
     */
    return makeClass(View, {

        constructor: function () {

            var block = this;

            var initialize = block.initialize;

            block.cid = _.uniqueId('block');

            block.initialize = function (data) {

                block.stopListening();

                deepExtend(block, block.defaults, data);

                block.initCollections();
                block.initModels();

                block._ensureElement();

                block.trigger('initializing');

                return $.when(initialize.apply(block, arguments)).then(function () {

                    block.render();

                    block.startListening();

                    block.trigger('initialized');
                });
            };

            block.initialize.apply(this, arguments);

            block.delegateGlobalEvents();
        },

        globalEvents: {},
        listeners: {},
        events: {},
        defaults: {},
        children: {},
        template: null,

        render: function () {

            var block = this,
                id = block.get('id'),
                $el = block.$el;

            block.removeBlocks();

            if (block.template) {
                block.setElement(block.template());
                $el && $el.replaceWith(block.el);
            }

            if (id){
                block.el.id = id
            }

            block.el.block = block;

            block.initBlocks();
        },

        initCollections: function () {

            var block = this;

            block.collections = _.mapValues(block.collections, function (constructor, collectionName) {
                return block.get('collections.' + collectionName);
            });

            block.collection = block.get('collection');
        },

        initModels: function () {

            var block = this;

            block.models = _.mapValues(block.models, function (constructor, modelName) {
                return block.get('models.' + modelName);
            });

            block.model = block.get('model');
        },

        get: function () {

            var block = this,
                args = [block].concat([].slice.call(arguments));

            return get.apply(null, args);
        },

        set: function () {

            var block = this,
                args = [block].concat([].slice.call(arguments)),
                changed = set.apply(null, args);

            var triggerChanges = function (path, data) {

                if (_.isPlainObject(data)) {
                    _.forEach(data, function (data, key) {
                        triggerChanges(path ? (path + '.' + key) : key, data);
                    });
                }

                block.trigger(path ? ('change:' + path) : 'change', data);
            };

            triggerChanges('', changed);

            return changed;
        },

        include: function (constructor, params) {

            var block = this,
                include = block.initBlock(constructor, params);

            if (constructor.extend) {
                include = block.initBlock(constructor, params);
                include = '<' + include.el.tagName + ' block-cid="' + include.cid + '"></' + include.el.tagName + '>';
            } else {
                include = constructor.call(block, params);
            }

            return include;
        },

        initBlocks: function () {

            var block = this,
                $blocks = block.$('[block-cid]');

            $blocks.each(function () {

                var placeholder = this,
                    blockCid = placeholder.getAttribute('block-cid'),
                    child = block.children[blockCid];

                $(placeholder).replaceWith(child.el);

            });
        },

        initBlock: function (constructor, params) {

            var block = this,
                child = constructor.call(block, _.extend({}, params, {
                    parent: block
                }));

            block.children[child.cid] = child;

            return child;
        },

        remove: function () {

            var block = this;

            block.stopListening();
            block.undelegateEvents();
            $(document).off('.' + block.cid);

            block.removeBlocks();

            block.parent && delete block.parent[block.cid];

            View.prototype.remove.apply(block, arguments);
        },

        removeBlocks: function () {

            var block = this;

            _.each(block.children, function (blockToRemove) {

                if (blockToRemove && typeof blockToRemove.remove === 'function') {
                    blockToRemove.remove();
                }

            });

            block.children = {};
        },

        trigger: function (event, data) {

            var block = this;

            block.$el.trigger(event, data);

            return View.prototype.trigger.apply(block, arguments);
        },

        delegateGlobalEvents: function () {

            var block = this;

            $(document).off('.' + block.cid);

            _.each(block.globalEvents, function (handler, event) {
                var path = event.split(' '),
                    eventName = path.shift();

                if (path.length) {
                    $(document).on(eventName + '.' + block.cid, path.join(' '), handler.bind(block));
                } else {
                    $(document).on(eventName + '.' + block.cid, handler.bind(block));
                }

            });
        },

        startListening: function () {

            var block = this,
                listeners = block.get('listeners');

            _.forEach(listeners, function (listener, path) {

                var normalizedListener;

                if (_.isPlainObject(listener)) {

                    normalizedListener = _.mapValues(listener, function (value) {

                        if (typeof value === 'string') {
                            return function () {
                                block[value].apply(block, arguments);
                            }
                        } else {
                            return value;
                        }
                    });

                    block.get(path) && block.listenTo(block.get(path), normalizedListener);

                } else {

                    if (typeof listener === 'string') {
                        normalizedListener = function () {
                            block[listener].apply(block, arguments);
                        };
                    } else {
                        normalizedListener = listener;
                    }

                    block.listenTo(block, path, normalizedListener);

                }

            });
        }
    });
});
<commit_msg>fix duplicate function in include method<commit_after>define(function (require, exports, module) {
    //requirements
    var get = require('bower_components/get/get'),
        set = require('bower_components/set/set'),
        deepExtend = require('bower_components/deepExtend/deepExtend'),
        makeClass = require('bower_components/makeClass/makeClass'),

        Backbone = require('bower_components/backbone/backbone'),
        _ = require('bower_components/lodash/lodash'),
        $ = require('jquery');

    var View = Backbone.View;

    /**
     * расширенный класс Backbone.View
     * @class Block
     * @param {Object} opt block options
     * @param {String | HTMLElement} opt.el элемент к которому будет привязан блок
     * @param {Function} opt.template шаблон, который будет использован для формирования DOM элемента блока
     */
    return makeClass(View, {

        constructor: function () {

            var block = this;

            var initialize = block.initialize;

            block.cid = _.uniqueId('block');

            block.initialize = function (data) {

                block.stopListening();

                deepExtend(block, block.defaults, data);

                block.initCollections();
                block.initModels();

                block._ensureElement();

                block.trigger('initializing');

                return $.when(initialize.apply(block, arguments)).then(function () {

                    block.render();

                    block.startListening();

                    block.trigger('initialized');
                });
            };

            block.initialize.apply(this, arguments);

            block.delegateGlobalEvents();
        },

        globalEvents: {},
        listeners: {},
        events: {},
        defaults: {},
        children: {},
        template: null,

        render: function () {

            var block = this,
                id = block.get('id'),
                $el = block.$el;

            block.removeBlocks();

            if (block.template) {
                block.setElement(block.template());
                $el && $el.replaceWith(block.el);
            }

            if (id){
                block.el.id = id
            }

            block.el.block = block;

            block.initBlocks();
        },

        initCollections: function () {

            var block = this;

            block.collections = _.mapValues(block.collections, function (constructor, collectionName) {
                return block.get('collections.' + collectionName);
            });

            block.collection = block.get('collection');
        },

        initModels: function () {

            var block = this;

            block.models = _.mapValues(block.models, function (constructor, modelName) {
                return block.get('models.' + modelName);
            });

            block.model = block.get('model');
        },

        get: function () {

            var block = this,
                args = [block].concat([].slice.call(arguments));

            return get.apply(null, args);
        },

        set: function () {

            var block = this,
                args = [block].concat([].slice.call(arguments)),
                changed = set.apply(null, args);

            var triggerChanges = function (path, data) {

                if (_.isPlainObject(data)) {
                    _.forEach(data, function (data, key) {
                        triggerChanges(path ? (path + '.' + key) : key, data);
                    });
                }

                block.trigger(path ? ('change:' + path) : 'change', data);
            };

            triggerChanges('', changed);

            return changed;
        },

        include: function (constructor, params) {

            var block = this,
                include;

            if (constructor.extend) {
                include = block.initBlock(constructor, params);
                include = '<' + include.el.tagName + ' block-cid="' + include.cid + '"></' + include.el.tagName + '>';
            } else {
                include = constructor.call(block, params);
            }

            return include;
        },

        initBlocks: function () {

            var block = this,
                $blocks = block.$('[block-cid]');

            $blocks.each(function () {

                var placeholder = this,
                    blockCid = placeholder.getAttribute('block-cid'),
                    child = block.children[blockCid];

                $(placeholder).replaceWith(child.el);

            });
        },

        initBlock: function (constructor, params) {

            var block = this,
                child = constructor.call(block, _.extend({}, params, {
                    parent: block
                }));

            block.children[child.cid] = child;

            return child;
        },

        remove: function () {

            var block = this;

            block.stopListening();
            block.undelegateEvents();
            $(document).off('.' + block.cid);

            block.removeBlocks();

            block.parent && delete block.parent[block.cid];

            View.prototype.remove.apply(block, arguments);
        },

        removeBlocks: function () {

            var block = this;

            _.each(block.children, function (blockToRemove) {

                if (blockToRemove && typeof blockToRemove.remove === 'function') {
                    blockToRemove.remove();
                }

            });

            block.children = {};
        },

        trigger: function (event, data) {

            var block = this;

            block.$el.trigger(event, data);

            return View.prototype.trigger.apply(block, arguments);
        },

        delegateGlobalEvents: function () {

            var block = this;

            $(document).off('.' + block.cid);

            _.each(block.globalEvents, function (handler, event) {
                var path = event.split(' '),
                    eventName = path.shift();

                if (path.length) {
                    $(document).on(eventName + '.' + block.cid, path.join(' '), handler.bind(block));
                } else {
                    $(document).on(eventName + '.' + block.cid, handler.bind(block));
                }

            });
        },

        startListening: function () {

            var block = this,
                listeners = block.get('listeners');

            _.forEach(listeners, function (listener, path) {

                var normalizedListener;

                if (_.isPlainObject(listener)) {

                    normalizedListener = _.mapValues(listener, function (value) {

                        if (typeof value === 'string') {
                            return function () {
                                block[value].apply(block, arguments);
                            }
                        } else {
                            return value;
                        }
                    });

                    block.get(path) && block.listenTo(block.get(path), normalizedListener);

                } else {

                    if (typeof listener === 'string') {
                        normalizedListener = function () {
                            block[listener].apply(block, arguments);
                        };
                    } else {
                        normalizedListener = listener;
                    }

                    block.listenTo(block, path, normalizedListener);

                }

            });
        }
    });
});
<|endoftext|>


<commit_before>'use strict';
import GenBase from '../genBase';

export default class Generator extends GenBase {
  constructor(...args) {
    super(...args);
  }

  get prompting() {
    return function () {
      this.askForModuleName();
    };
  }

  get writing() {
    return function () {
      const done = this.async();

      Promise.all([
        this.copySrcFile('decorator'),
        this.copyUnitTest('decorator')
      ]).then(() => {
        done();
      });
    };
  }
}
<commit_msg>refactor(decorator): use async/await<commit_after>'use strict';
import GenBase from '../genBase';

export default class Generator extends GenBase {
  constructor(...args) {
    super(...args);
  }

  get prompting() {
    return function () {
      this.askForModuleName();
    };
  }

  get writing() {
    return async function () {
      const done = this.async();

      await Promise.all([
        this.copySrcFile('decorator'),
        this.copyUnitTest('decorator')
      ]);

      done();
    };
  }
}
<|endoftext|>


<commit_before>"use strict";
/*global escape, unescape*/

var isNode = typeof process === 'object' &&
             typeof process.versions === 'object' &&
             process.versions.node &&
             process.__atom_type !== "renderer";

if (isNode) {
  var nodeRequire = require; // Prevent mine.js from seeing this require
  module.exports = nodeRequire('./bodec-node.js');
}
else {

  // This file must be served with UTF-8 encoding for the utf8 codec to work.
  module.exports = {
    Binary: Uint8Array,
    // Utility functions
    isBinary: isBinary,
    create: create,
    join: join,

    // Binary input and output
    copy: copy,
    slice: slice,

    // String input and output
    toRaw: toRaw,
    fromRaw: fromRaw,
    toUnicode: toUnicode,
    fromUnicode: fromUnicode,
    toHex: toHex,
    fromHex: fromHex,
    toBase64: toBase64,
    fromBase64: fromBase64,

    // Array input and output
    toArray: toArray,
    fromArray: fromArray,

    // Raw <-> Hex-encoded codec
    decodeHex: decodeHex,
    encodeHex: encodeHex,

    decodeBase64: decodeBase64,
    encodeBase64: encodeBase64,

    // Unicode <-> Utf8-encoded-raw codec
    encodeUtf8: encodeUtf8,
    decodeUtf8: decodeUtf8,

    // Hex <-> Nibble codec
    nibbleToCode: nibbleToCode,
    codeToNibble: codeToNibble
  };
}

function isBinary(value) {
  return value &&
      typeof value === "object" &&
      value instanceof Uint8Array || value.constructor.name === "Uint8Array";
}

function create(length) {
  return new Uint8Array(length);
}

function join(chunks) {
  var length = chunks.length;
  var total = 0;
  for (var i = 0; i < length; i++) {
    total += chunks[i].length;
  }
  var binary = create(total);
  var offset = 0;
  for (i = 0; i < length; i++) {
    var chunk = chunks[i];
    copy(chunk, binary, offset);
    offset += chunk.length;
  }
  return binary;
}

function slice(binary, start, end) {
  if (end === undefined) {
    end = binary.length;
    if (start === undefined) start = 0;
  }
  return binary.subarray(start, end);
}

function copy(source, binary, offset) {
  var length = source.length;
  if (offset === undefined) {
    offset = 0;
    if (binary === undefined) binary = create(length);
  }
  for (var i = 0; i < length; i++) {
    binary[i + offset] = source[i];
  }
  return binary;
}

// Like slice, but encode as a hex string
function toHex(binary, start, end) {
  var hex = "";
  if (end === undefined) {
    end = binary.length;
    if (start === undefined) start = 0;
  }
  for (var i = start; i < end; i++) {
    var byte = binary[i];
    hex += String.fromCharCode(nibbleToCode(byte >> 4)) +
           String.fromCharCode(nibbleToCode(byte & 0xf));
  }
  return hex;
}

// Like copy, but decode from a hex string
function fromHex(hex, binary, offset) {
  var length = hex.length / 2;
  if (offset === undefined) {
    offset = 0;
    if (binary === undefined) binary = create(length);
  }
  var j = 0;
  for (var i = 0; i < length; i++) {
    binary[offset + i] = (codeToNibble(hex.charCodeAt(j++)) << 4)
                       |  codeToNibble(hex.charCodeAt(j++));
  }
  return binary;
}

function toBase64(binary, start, end) {
  return btoa(toRaw(binary, start, end));
}

function fromBase64(base64, binary, offset) {
  return fromRaw(atob(base64), binary, offset);
}

function nibbleToCode(nibble) {
  nibble |= 0;
  return (nibble + (nibble < 10 ? 0x30 : 0x57))|0;
}

function codeToNibble(code) {
  code |= 0;
  return (code - ((code & 0x40) ? 0x57 : 0x30))|0;
}

function toUnicode(binary, start, end) {
  return decodeUtf8(toRaw(binary, start, end));
}

function fromUnicode(unicode, binary, offset) {
  return fromRaw(encodeUtf8(unicode), binary, offset);
}

function decodeHex(hex) {
  var j = 0, l = hex.length;
  var raw = "";
  while (j < l) {
    raw += String.fromCharCode(
       (codeToNibble(hex.charCodeAt(j++)) << 4)
      | codeToNibble(hex.charCodeAt(j++))
    );
  }
  return raw;
}

function encodeHex(raw) {
  var hex = "";
  var length = raw.length;
  for (var i = 0; i < length; i++) {
    var byte = raw.charCodeAt(i);
    hex += String.fromCharCode(nibbleToCode(byte >> 4)) +
           String.fromCharCode(nibbleToCode(byte & 0xf));
  }
  return hex;
}

function decodeBase64(base64) {
  return atob(base64);
}

function encodeBase64(raw) {
  return btoa(raw);
}

function decodeUtf8(utf8) {
  return decodeURIComponent(escape(utf8));
}

function encodeUtf8(unicode) {
  return unescape(encodeURIComponent(unicode));
}

function toRaw(binary, start, end) {
  var raw = "";
  if (end === undefined) {
    end = binary.length;
    if (start === undefined) start = 0;
  }
  for (var i = start; i < end; i++) {
    raw += String.fromCharCode(binary[i]);
  }
  return raw;
}

function fromRaw(raw, binary, offset) {
  var length = raw.length;
  if (offset === undefined) {
    offset = 0;
    if (binary === undefined) binary = create(length);
  }
  for (var i = 0; i < length; i++) {
    binary[offset + i] = raw.charCodeAt(i);
  }
  return binary;
}

function toArray(binary, start, end) {
  if (end === undefined) {
    end = binary.length;
    if (start === undefined) start = 0;
  }
  var length = end - start;
  var array = new Array(length);
  for (var i = 0; i < length; i++) {
    array[i] = binary[i + start];
  }
  return array;
}

function fromArray(array, binary, offset) {
  var length = array.length;
  if (offset === undefined) {
    offset = 0;
    if (binary === undefined) binary = create(length);
  }
  for (var i = 0; i < length; i++) {
    binary[offset + i] = array[i];
  }
  return binary;
}
<commit_msg>Wrap bodec module<commit_after>
( // Module boilerplate to support cjs and browser globals.
  (typeof module === "object" && typeof module.exports === "object" && function (m) { module.exports = m(); }) ||
  (function (m) { window.bodec = m(); })
)(function () {
"use strict";

var isNode = typeof process === 'object' &&
             typeof process.versions === 'object' &&
             process.versions.node &&
             process.__atom_type !== "renderer";

if (isNode) {
  var nodeRequire = require; // Prevent mine.js from seeing this require
  return nodeRequire('./bodec-node.js');
}
else {

  // This file must be served with UTF-8 encoding for the utf8 codec to work.
  return {
    Binary: Uint8Array,
    // Utility functions
    isBinary: isBinary,
    create: create,
    join: join,

    // Binary input and output
    copy: copy,
    slice: slice,

    // String input and output
    toRaw: toRaw,
    fromRaw: fromRaw,
    toUnicode: toUnicode,
    fromUnicode: fromUnicode,
    toHex: toHex,
    fromHex: fromHex,
    toBase64: toBase64,
    fromBase64: fromBase64,

    // Array input and output
    toArray: toArray,
    fromArray: fromArray,

    // Raw <-> Hex-encoded codec
    decodeHex: decodeHex,
    encodeHex: encodeHex,

    decodeBase64: decodeBase64,
    encodeBase64: encodeBase64,

    // Unicode <-> Utf8-encoded-raw codec
    encodeUtf8: encodeUtf8,
    decodeUtf8: decodeUtf8,

    // Hex <-> Nibble codec
    nibbleToCode: nibbleToCode,
    codeToNibble: codeToNibble
  };
}

function isBinary(value) {
  return value &&
      typeof value === "object" &&
      value instanceof Uint8Array || value.constructor.name === "Uint8Array";
}

function create(length) {
  return new Uint8Array(length);
}

function join(chunks) {
  var length = chunks.length;
  var total = 0;
  for (var i = 0; i < length; i++) {
    total += chunks[i].length;
  }
  var binary = create(total);
  var offset = 0;
  for (i = 0; i < length; i++) {
    var chunk = chunks[i];
    copy(chunk, binary, offset);
    offset += chunk.length;
  }
  return binary;
}

function slice(binary, start, end) {
  if (end === undefined) {
    end = binary.length;
    if (start === undefined) start = 0;
  }
  return binary.subarray(start, end);
}

function copy(source, binary, offset) {
  var length = source.length;
  if (offset === undefined) {
    offset = 0;
    if (binary === undefined) binary = create(length);
  }
  for (var i = 0; i < length; i++) {
    binary[i + offset] = source[i];
  }
  return binary;
}

// Like slice, but encode as a hex string
function toHex(binary, start, end) {
  var hex = "";
  if (end === undefined) {
    end = binary.length;
    if (start === undefined) start = 0;
  }
  for (var i = start; i < end; i++) {
    var byte = binary[i];
    hex += String.fromCharCode(nibbleToCode(byte >> 4)) +
           String.fromCharCode(nibbleToCode(byte & 0xf));
  }
  return hex;
}

// Like copy, but decode from a hex string
function fromHex(hex, binary, offset) {
  var length = hex.length / 2;
  if (offset === undefined) {
    offset = 0;
    if (binary === undefined) binary = create(length);
  }
  var j = 0;
  for (var i = 0; i < length; i++) {
    binary[offset + i] = (codeToNibble(hex.charCodeAt(j++)) << 4)
                       |  codeToNibble(hex.charCodeAt(j++));
  }
  return binary;
}

function toBase64(binary, start, end) {
  return btoa(toRaw(binary, start, end));
}

function fromBase64(base64, binary, offset) {
  return fromRaw(atob(base64), binary, offset);
}

function nibbleToCode(nibble) {
  nibble |= 0;
  return (nibble + (nibble < 10 ? 0x30 : 0x57))|0;
}

function codeToNibble(code) {
  code |= 0;
  return (code - ((code & 0x40) ? 0x57 : 0x30))|0;
}

function toUnicode(binary, start, end) {
  return decodeUtf8(toRaw(binary, start, end));
}

function fromUnicode(unicode, binary, offset) {
  return fromRaw(encodeUtf8(unicode), binary, offset);
}

function decodeHex(hex) {
  var j = 0, l = hex.length;
  var raw = "";
  while (j < l) {
    raw += String.fromCharCode(
       (codeToNibble(hex.charCodeAt(j++)) << 4)
      | codeToNibble(hex.charCodeAt(j++))
    );
  }
  return raw;
}

function encodeHex(raw) {
  var hex = "";
  var length = raw.length;
  for (var i = 0; i < length; i++) {
    var byte = raw.charCodeAt(i);
    hex += String.fromCharCode(nibbleToCode(byte >> 4)) +
           String.fromCharCode(nibbleToCode(byte & 0xf));
  }
  return hex;
}

function decodeBase64(base64) {
  return atob(base64);
}

function encodeBase64(raw) {
  return btoa(raw);
}

function decodeUtf8(utf8) {
  return decodeURIComponent(window.escape(utf8));
}

function encodeUtf8(unicode) {
  return window.unescape(encodeURIComponent(unicode));
}

function toRaw(binary, start, end) {
  var raw = "";
  if (end === undefined) {
    end = binary.length;
    if (start === undefined) start = 0;
  }
  for (var i = start; i < end; i++) {
    raw += String.fromCharCode(binary[i]);
  }
  return raw;
}

function fromRaw(raw, binary, offset) {
  var length = raw.length;
  if (offset === undefined) {
    offset = 0;
    if (binary === undefined) binary = create(length);
  }
  for (var i = 0; i < length; i++) {
    binary[offset + i] = raw.charCodeAt(i);
  }
  return binary;
}

function toArray(binary, start, end) {
  if (end === undefined) {
    end = binary.length;
    if (start === undefined) start = 0;
  }
  var length = end - start;
  var array = new Array(length);
  for (var i = 0; i < length; i++) {
    array[i] = binary[i + start];
  }
  return array;
}

function fromArray(array, binary, offset) {
  var length = array.length;
  if (offset === undefined) {
    offset = 0;
    if (binary === undefined) binary = create(length);
  }
  for (var i = 0; i < length; i++) {
    binary[offset + i] = array[i];
  }
  return binary;
}

});<|endoftext|>


<commit_before>let config = require('./config');
let request = require('request-promise');
let prev_img_id = null;

/**
 * @param {string[]} cmds
 * @return {string}
 */
function cleanGet(cmds) {
  let tagArr = [];
  for (let val of cmds.slice(1)) {
    tagArr.push(encodeURIComponent(val));
  }
  return String(tagArr.join('+'));
}

/**
 * @param {string} hostname
 * @param {string} path
 * @param {string} tags The parameter and value
 * @return {options} The options used in sending a Request
 */
function getOptions(hostname, path, tags) {
  /** Do NOT use qs: { ... }, it replaces '+' with '%20' */
  let options = {
    method: 'GET',
    uri: hostname + path + tags,
    json: true,
  }
  console.log('Recieved request for: ' + path + tags);
  return options;
}

/**
 * @param {message} message A message object as defined in discord.js
 * @param {string} text The text portion of the reply
 * @param {string} imgUrl The complete URL to the desired image link
 * @return {string} A shortened version of the URL via Google
 */
function sendGoogleShortenerRequest(message, text, imgUrl) {
  let options = {
    method: 'POST',
    uri: config.google_url_shortener_url + "?key=" + config.google_api_key,
    body: {
      'longUrl': imgUrl
    },
    headers: {
      'Content-Type': 'application/json'
    },
    json: true
  };

  request(options)
    .then(function (body) {
      if (body.id != null) {
        console.log('Shortened url to ' + body.id);
        message.channel.send(text + body.id)
          .catch( reason => { console.log("Rejected Google Short URL for " + reason); });
      } else {
        message.channel.send(text + imgUrl)
          .catch( reason => { console.log("Rejected Google Full URL Promise for " + reason); });
      }
    })
    .catch(function (err) {
      console.log('Unable to shorten url, returning long form');
      message.channel.send(text + imgUrl)
        .catch( reason => { console.log("Rejected Google Initial Promise for " + reason); });
    });
}

/**
 * @param {message} message A message object as defined in discord.js
 * @param {string[]} cmds
 */
function getDanbooru(message, cmds) {
  let tagList = cleanGet(cmds);
  let options = getOptions(config.danbooru_auth, config.danbooru_get, tagList);

  request(options)
    .then(function (body) {
      let selected_idx = Math.floor(Math.random() * (body.length));

      let tagStr = '**Tags:** ' + tagList.split('+').join(', ');
      let imgUrl;

      if (body != null && body[selected_idx] != null) {
        imgUrl = config.danbooru_url + body[selected_idx].file_url;
      } else {
        message.channel.send('No picture found')
          .catch( reason => { console.log("Rejected Booru Null Promise for " + reason); });
        return console.error('Bad File Get at Index ' +
         selected_idx + ' on data:\n' + JSON.stringify(body));
      }

      if (config.use_shortener === true) {
        sendGoogleShortenerRequest(message, decodeURIComponent(tagStr) + '\n', imgUrl);
      } else {
        message.channel.send(decodeURIComponent(tagStr) + '\n' + imgUrl)
          .catch( reason => { console.log("Rejected Booru URL Promise for " + reason); });
      }
  })
  .catch(function (err) {
    return console.error('Request Failed: ' + err);
    message.channel.send('Request Failed. Try again.')
      .catch( reason => { console.log("Rejected Booru Reject Promise for " + reason); });
  });
}

/**
 * @param {message} message A message object as defined in discord.js
 * @param {string[]} cmds
 */
function getSafebooru(message, cmds) {
  let tagList = cleanGet(cmds);
  let options = getOptions(config.sbooru_url, config.sbooru_get, tagList);
  message.channel.send('fixme')
    .catch( reason => { console.log("Rejected SafeBooru Msg Promise for " + reason); });
}

module.exports = {getDanbooru, getSafebooru};
<commit_msg>Duplication Fix<commit_after>let config = require('./config');
let request = require('request-promise');
let prev_img_id = null;

/**
 * @param {string[]} cmds
 * @return {string}
 */
function cleanGet(cmds) {
  let tagArr = [];
  for (let val of cmds.slice(1)) {
    tagArr.push(encodeURIComponent(val));
  }
  return String(tagArr.join('+'));
}

/**
 * @param {string} hostname
 * @param {string} path
 * @param {string} tags The parameter and value
 * @return {options} The options used in sending a Request
 */
function getOptions(hostname, path, tags) {
  /** Do NOT use qs: { ... }, it replaces '+' with '%20' */
  let options = {
    method: 'GET',
    uri: hostname + path + tags,
    json: true,
  }
  console.log('Recieved request for: ' + path + tags);
  return options;
}

/**
 * @param {message} message A message object as defined in discord.js
 * @param {string} text The text portion of the reply
 * @param {string} imgUrl The complete URL to the desired image link
 * @return {string} A shortened version of the URL via Google
 */
function sendGoogleShortenerRequest(message, text, imgUrl) {
  let options = {
    method: 'POST',
    uri: config.google_url_shortener_url + "?key=" + config.google_api_key,
    body: {
      'longUrl': imgUrl
    },
    headers: {
      'Content-Type': 'application/json'
    },
    json: true
  };

  request(options)
    .then(function (body) {
      if (body.id != null) {
        console.log('Shortened url to ' + body.id);
        message.channel.send(text + body.id)
          .catch( reason => { console.log("Rejected Google Short URL for " + reason); });
      } else {
        message.channel.send(text + imgUrl)
          .catch( reason => { console.log("Rejected Google Full URL Promise for " + reason); });
      }
    })
    .catch(function (err) {
      console.log('Unable to shorten url, returning long form');
      message.channel.send(text + imgUrl)
        .catch( reason => { console.log("Rejected Google Initial Promise for " + reason); });
    });
}

/**
 * @param {message} message A message object as defined in discord.js
 * @param {string[]} cmds
 */
function getDanbooru(message, cmds) {
  let tagList = cleanGet(cmds);
  tagList.push("-id:" + prev_img_id);
  let options = getOptions(config.danbooru_auth, config.danbooru_get, tagList);

  request(options)
    .then(function (body) {
      let selected_idx = Math.floor(Math.random() * (body.length));

      let tagStr = '**Tags:** ' + tagList.split('+').join(', ');
      let imgUrl;

      if (body != null && body[selected_idx] != null) {
        imgUrl = config.danbooru_url + body[selected_idx].file_url;
        prev_img_id = body[selected_idx].id;
      } else {
        message.channel.send('No picture found')
          .catch( reason => { console.log("Rejected Booru Null Promise for " + reason); });
        return console.error('Bad File Get at Index ' +
         selected_idx + ' on data:\n' + JSON.stringify(body));
      }

      if (config.use_shortener === true) {
        sendGoogleShortenerRequest(message, decodeURIComponent(tagStr) + '\n', imgUrl);
      } else {
        message.channel.send(decodeURIComponent(tagStr) + '\n' + imgUrl)
          .catch( reason => { console.log("Rejected Booru URL Promise for " + reason); });
      }
  })
  .catch(function (err) {
    return console.error('Request Failed: ' + err);
    message.channel.send('Request Failed. Try again.')
      .catch( reason => { console.log("Rejected Booru Reject Promise for " + reason); });
  });
}

/**
 * @param {message} message A message object as defined in discord.js
 * @param {string[]} cmds
 */
function getSafebooru(message, cmds) {
  let tagList = cleanGet(cmds);
  let options = getOptions(config.sbooru_url, config.sbooru_get, tagList);
  message.channel.send('fixme')
    .catch( reason => { console.log("Rejected SafeBooru Msg Promise for " + reason); });
}

module.exports = {getDanbooru, getSafebooru};
<|endoftext|>


<commit_before>var React = require('react');
var Select = require('react-select');
var Field = require('../field');

module.exports = function(attr, value, onChange) {
  var options = attr.options.map((option) => ({
    value: option[attr.select_value],
    label: option[attr.select_label]
  }));

  function handleChange(value) {
    onChange(value.split(','));
  }

  return (
    <Field label={attr.label}>
      <Select
        name={attr.name}
        value={value}
        options={options}
        multi={attr.multiple}
        onChange={handleChange}
      />
    </Field>
  );
};
<commit_msg>select default<commit_after>var React = require('react');
var Select = require('react-select');
var Field = require('../field');

module.exports = function(attr, value, onChange) {
  var options = attr.options.map((option) => ({
    value: option[attr.select_value || 'id'],
    label: option[attr.select_label || 'name']
  }));

  function handleChange(value) {
    onChange(value.split(','));
  }

  return (
    <Field label={attr.label}>
      <Select
        name={attr.name}
        value={value}
        options={options}
        multi={attr.multiple}
        onChange={handleChange}
      />
    </Field>
  );
};
<|endoftext|>


<commit_before>(function() {

    Ecore.Editor = {};

    var label = function() {
        var label = this.has('name') ? this.get('name') : this.get('uri');
        return this.eClass.get('name') + label ? ' ' + label : '';
    };

    var eClassLabel = function() {
        var supers = [];
        if (this.isSet('eSuperTypes')) {
            supers = this.get('eSuperTypes').map(function(s) { return s.get('name'); });
        }
        return this.get('name') + (supers.length ? ' > ' + supers.join(' , ') : '');
    };

    Ecore.EObject.get('eOperations').add(
        Ecore.EOperation.create({
            name: 'label',
            eType: Ecore.EString,
            upperBound: 1,
            lowerBound: 0,
            _: label
        }));

    Ecore.EClass.get('eOperations').add(
        Ecore.EOperation.create({
            name: 'label',
            eType: Ecore.EString,
            _: eClassLabel
        }));

    Ecore.EStructuralFeature.get('eOperations').add(
        Ecore.EOperation.create({
            name: 'label',
            eType: Ecore.EString,
            _: function() {
                return this.get('name') + ' : ' + this.get('eType').get('name');
            }
        }));

    _.each(Ecore.EPackage.Registry.ePackages(), function(p) {
        p.label = label;
        p.get('eClassifiers').each(function(c) {
            c.label = eClassLabel;

            if (c.has('eStructuralFeatures')) {
                c.get('eStructuralFeatures').each(function(f) {
                    f.label = function() {
                        return this.get('name') + ' : ' + this.get('eType').get('name');
                    };
                });
                c.get('eOperations').each(function(f) {
                    f.label = function() {
                        return this.get('name') + '()' + (this.isSet('eType') ? ' : ' + this.get('eType').get('name') : '');
                    };
                });
            }
        });
    });

<commit_msg>moved Ecore.Editor to Ecore.Edit added LabelProvider<commit_after>
//
// Ecore.Edit
//

var Edit = Ecore.Edit = {
    version: '0.3.0'
};

//
// LabelProvider
//
// Provides labels for EObjects.
//
// It can be extended to provide labels to different kind of EObject by
// using the extend method provided by underscore:
//
//      _.extend(Ecore.Edit.LabelProvider, {
//          FooClass: function(eObject) { return eObject.get('bar'); }
//      });
//

Edit.LabelProvider = {
    getLabel: function(eObject) {
        var eClass = eObject.eClass.get('name');
        if (this[eClass])
            return this[eClass](eObject);
        else
            return eObject.eClass.get('name');
    },

    // Labels for Ecore classes

    EClass: function(eObject) { return eObject.get('name'); },
    EDataType: function(eObject) { return eObject.get('name'); },
    EEnum: function(eObject) { return eObject.get('name'); },
    EEnumLiteral: function(eObject) { return eObject.get('name') + ' = ' + eObject.get('value'); },
    EAttribute: function(eObject) {
        var type = eObject.isSet('eType') ? ' : ' + eObject.get('eType').get('name') : '';
        return eObject.get('name') + type;
    },
    EReference: function(eObject) {
        var type = eObject.isSet('eType') ? ' : ' + eObject.get('eType').get('name') : '';
        return eObject.get('name') + type;
    },
    EOperation: function(eObject) {
        var returnType = eObject.isSet('eType') ? ' : ' + eObject.get('eType').get('name') : '';
        return eObject.get('name') + '()' + returnType;
    },
    EPackage: function(eObject) { return eObject.get('name'); },
    ResourceSet: function(eObject) { return 'resourceSet'; },
    Resource: function(eObject) { return eObject.get('uri'); }
};

<|endoftext|>