<commit_before>var stateProvider = require("./stateProvider");
var constants = require('../constants');
var lim = constants.lameLimit;

module.exports = (function(){
	//TODO:

	this.getBetAmount = function() {
		var bet = 500;
		//get bet amount
		//calculation and some calculation logic goes here
		return bet;
	};

	this.getCheckAmount = function() {
		//TODO:
		//return stateProvider.getCheckAmount()
		return 10;
	};

  //check my card are good enought to keep or raise
  //preflop tactic
  this.cardRankGood = function(){
    var my_cards = stateProvider.getMyCards();
    var flop_cards = stateProvider.getFlopCards();
    console.log(my_cards);
    console.log(flop_cards);
    console.log("cards", my_cards);
    console.log("cards", flop_cards);
    if((isCardsGoodBySuit(my_cards[0],my_cards[1]) || isCardsGoodByRank(my_cards[0], my_cards[1])) && !lameCards(my_cards)){
      console.log("my cards GOOD");
      return true;
    }
    console.log("my cards BAD");
    return false;
  };

	return this;
})();

function isCardsGoodBySuit(card1, card2) {
  if (card1.suit == card2.suit) {
    return true;
  }
  return false;
}

function isCardsGoodByRank(card1, card2) {
  if (card1.rank == card2.rank) {
    return true;
  }
  return false;
}

function toNum(c) {
    switch (c) {
        case 'J':
            return 11;
        case 'Q':
            return 12;
        case 'K':
            return 13;
        case 'A':
            return 14;

        default:
            return parseInt(c);
    }
}

function lameCards(cards) {
    // returns true if either card below lame limit and they are not a pair
    if (lowCards() && !isPair()){
        return true
    } else {
        return false
    }
}

function lowCards(cards) {
    // returns true if both cards below lame limit
    if (toNum(cards[0].rank) < lim && toNum(cards[1].rank) < lim) {
        return true
    } else {
        return false
    }
}

function isPair(cards){
  // returns true if the hand cards are pair
  if(cards[0].rank == cards[1].rank){
    return true;
  } else {
    return false;
  }
}

<commit_msg>fix fix<commit_after>var stateProvider = require("./stateProvider");
var constants = require('../constants');
var lim = constants.lameLimit;

module.exports = (function(){
	//TODO:

	this.getBetAmount = function() {
		var bet = 500;
		//get bet amount
		//calculation and some calculation logic goes here
		return bet;
	};

	this.getCheckAmount = function() {
		//TODO:
		//return stateProvider.getCheckAmount()
		return 10;
	};

  //check my card are good enought to keep or raise
  //preflop tactic
  this.cardRankGood = function(){
    var my_cards = stateProvider.getMyCards();
    var flop_cards = stateProvider.getFlopCards();
    console.log(my_cards);
    console.log(flop_cards);
    console.log("cards", my_cards);
    console.log("cards", flop_cards);
    if((isCardsGoodBySuit(my_cards[0],my_cards[1]) || isCardsGoodByRank(my_cards[0], my_cards[1])) && !lameCards(my_cards)){
      console.log("my cards GOOD");
      return true;
    }
    console.log("my cards BAD");
    return false;
  };

	return this;
})();

function isCardsGoodBySuit(card1, card2) {
  if (card1.suit == card2.suit) {
    return true;
  }
  return false;
}

function isCardsGoodByRank(card1, card2) {
  if (card1.rank == card2.rank) {
    return true;
  }
  return false;
}

function toNum(c) {
    switch (c) {
        case 'J':
            return 11;
        case 'Q':
            return 12;
        case 'K':
            return 13;
        case 'A':
            return 14;

        default:
            return parseInt(c);
    }
}

function lameCards(cards) {
    // returns true if either card below lame limit and they are not a pair
    if (lowCards(cards) && !isPair(cards)){
        return true
    } else {
        return false
    }
}

function lowCards(cards) {
    // returns true if both cards below lame limit
    if (toNum(cards[0].rank) < lim && toNum(cards[1].rank) < lim) {
        return true
    } else {
        return false
    }
}

function isPair(cards){
  // returns true if the hand cards are pair
  if(cards[0].rank == cards[1].rank){
    return true;
  } else {
    return false;
  }
}

<|endoftext|>


<commit_before>'use strict';
var path = require('path');
var fs = require('fs');
var _ = require('lodash');
var Minimatch = require('minimatch').Minimatch;

/**
 * Helper for mapping include file paths to karma file patterns - served, included, but not watched
 * @param path {string}
 * @returns {object}
 */
var createIncludePattern = function(path) {
  return {
    pattern: path,
    included: true,
    served: true,
    watched: false
  };
};

/**
 * Resolve paths for dependencies now
 * @param moduleName {string}
 * @param relativePath {string}
 * @returns {string}
 */
var getDependencyPath = function(moduleName, relativePath) {
  try {
    return path.dirname(require.resolve(moduleName)) + relativePath;
  } catch (e) {
    if (e.code === 'MODULE_NOT_FOUND' && e.message.indexOf(moduleName) !== -1) {
      console.warn('Cannot find "%s".\n  Did you forget to install it ?\n' +
        '  npm install %s --save-dev', moduleName, moduleName);
    } else {
      console.warn('Error during loading "%s":\n  %s', moduleName, e.message);
    }
  }
};

/**
 * Loads up a SystemJS config file and returns the configuration
 * Taken from how systemjs-builder loads config files inside node
 * @param filePath {string}
 * @returns {object}
 */
var readConfigFile = function(filePath) {
  var curSystem = global.System;
  var fileConfig = {};
  global.System = {
    config: function(cfg) {
      _.merge(fileConfig, cfg);
    }
  };
  // jshint evil:true
  new Function(fs.readFileSync(filePath).toString()).call(global);
  global.System = curSystem;
  return fileConfig;
};

/**
 * Returns a dependency path based on 'paths' configuration, or node_modules/ lookup
 * @param systemjsConfig {object} The SystemJS config object
 * @param basePath {string} Path that SystemJS paths are relative to
 * @param systemModuleName {string} Name of the module as the SystemJS config knows it.
 * @param npmModuleName {string} Name of module as npm knows it.
 * @param npmPath {string} Path to use relative to a `require.resolve()` call
 * @returns {string}
 */
var pathOrNpm = function(systemjsConfig, basePath, systemModuleName, npmModuleName, npmPath) {
  var filePath = systemjsConfig.paths && systemjsConfig.paths[systemModuleName];
  if (filePath) {
    return path.join(basePath, systemjsConfig.baseURL || '', filePath);
  } else {
    console.warn('[WARNING] Looking up paths with require.resolve() is deprecated.\n' +
      'Please add "' + systemModuleName + '" to your SystemJS config paths.');
    return getDependencyPath(npmModuleName, npmPath);
  }
};

/**
 * Returns the path to the transpiler.
 * @param config {object} SystemJS config
 * @param basePath {string}
 * @returns {string}
 */
var getTranspilerPath = function(config, basePath) {
  // Path should come from SystemJS, but for backwards compatibility will also check for a known npm path
  switch (config.transpiler) {
  case null: // If null, no transpiler in use
    return '';
  case 'babel':
    return pathOrNpm(config, basePath, 'babel', 'babel-core', '/../../../browser.js');
  case undefined: // Traceur is still the default transpiler if undefined
  case 'traceur':
    return pathOrNpm(config, basePath, 'traceur', 'traceur', '/../../bin/traceur.js');
  case 'typescript':
    return pathOrNpm(config, basePath, 'typescript', 'typescript', '/typescript.js');
  default:
    return pathOrNpm(config, basePath, config.transpiler, config.transpiler, config.transpiler + '.js');
  }
};

/**
 * Returns the list of '{included: true}' file patterns before setting them to '{included: false}'
 * @param fileList {object[]}
 * @param basePath {string}
 * @returns {string[]}
 */
var processIncludedPatterns = function(fileList, basePath) {
  var included = _.filter(fileList, {included: true});
  _.forEach(included, function (file) {
    file.included = false;
  });
  return _.map(included, function(file) {
    // Rather than make Minimatch available in the browser,
    // it's simpler to use it within Karma and extract the RegExps as strings.
    // Also take into account the '/base' or '/absolute' path that Karma serves files from
    var path = !basePath || file.pattern.indexOf(basePath) === 0 ?
        '/base' + file.pattern.replace(basePath, '') :
        '/absolute' + file.pattern;
    var regexString = (new Minimatch(path)).makeRe().toString();
    return regexString.substring(1, regexString.length - 1); // Remove the "/" from the start and end, so it'll fit into 'new RegExp()'
  });
};

/**
 * Run during karma initialisation.
 * Alters the karma configuration to use SystemJS.
 * @param config {object}
 */
var initSystemjs = function(config) {
  // Final files array should look like this:
  // - SystemJS libraries - included
  // - SystemJS config - included & watched
  // - 'files' - served, watched, and marked to be called with 'System.import()' (if {included: true})
  // - 'systemjs.serveFiles' - served only
  // - Plugin adapter - included

  // Create list of file patterns to load with 'System.import()'
  var importPatterns = processIncludedPatterns(config.files, config.basePath);

  var kSystemjsConfig = config.systemjs || {};
  kSystemjsConfig.config = kSystemjsConfig.config || {};
  var basePath = (config.basePath || '.') + '/';

  // If there's an external SystemJS configuration file...
  if (kSystemjsConfig.configFile) {
    // Load it, and merge it with the config
    // karma-systemjs.config should take precedence over external SystemJS configuration file
    var cfgPath = basePath + kSystemjsConfig.configFile;
    var kConfig = readConfigFile(cfgPath);

    // Absolute paths for modules should be moved to /base, where Karma serves them
    ['map', 'paths'].forEach(function(cfgKey) {
      if (typeof kConfig[cfgKey] === 'object') {
        Object.keys(kConfig[cfgKey]).forEach(function(module) {
          if (kConfig[cfgKey][module][0] === '/') {
            kConfig[cfgKey][module] = '/base' + kConfig[cfgKey][module];
          }
        });
      }
    });

    // Merge the SystemJS config file with the SystemJS config in the karma config
    _.merge(kConfig, kSystemjsConfig.config, function(objectValue, sourceValue) {
      // Overwrite array values - don't merge them
      if (_.isArray(sourceValue)) {
        return sourceValue;
      }
    });

    kSystemjsConfig.config = kConfig;
  }

  // Resolve the paths for es6-module-loader and systemjs
  // Check the System config for the paths, or revert to looking them up in node_modules/
  var es6LoaderPath = pathOrNpm(kSystemjsConfig.config, basePath,
    'es6-module-loader', 'es6-module-loader', '/dist/es6-module-loader.src.js');
  var systemjsPath = pathOrNpm(kSystemjsConfig.config, basePath,
    'systemjs', 'systemjs', '/dist/system.src.js');
  var polyfillsPath = pathOrNpm(kSystemjsConfig.config, basePath,
    'system-polyfills', 'systemjs', '/dist/system-polyfills.js');

  // Adds dependencies to start of config.files: es6-module-loader, and system.js
  // Don't watch, since these files should never change
  config.files.unshift(
    createIncludePattern(es6LoaderPath),
    createIncludePattern(polyfillsPath),
    createIncludePattern(systemjsPath)
  );

  // If a transpiler is being used, include it in the files
  var transpilerPath = getTranspilerPath(kSystemjsConfig.config, basePath);
  if (transpilerPath) {
    // Don't watch, since this file should never change
    config.files.unshift(
      createIncludePattern(transpilerPath)
    );
  }

  // system.js-0.16+ uses Function.prototype.bind, which PhantomJS does not support.
  if (config.browsers && config.browsers.indexOf('PhantomJS') !== -1) {
    var phantomjsPolyfillPath = pathOrNpm(kSystemjsConfig.config, basePath,
      'phantomjs-polyfill', 'phantomjs-polyfill', '/bind-polyfill.js');
    config.files.unshift(
      createIncludePattern(phantomjsPolyfillPath)
    );
  }

  // Adds file patterns from config.systemjs.serveFiles to config.files, set to be served but not included
  if (kSystemjsConfig.serveFiles) {
    kSystemjsConfig.serveFiles.forEach(function(pathOrPattern) {
      if (typeof pathOrPattern === 'object') {
        config.files.push(pathOrPattern);
      } else {
        config.files.push({
          pattern: basePath + pathOrPattern,
          included: false,
          served: true,
          watched: true
        });
      }
    });
  }

  // Add file patterns to always be included back into files
  if (kSystemjsConfig.includeFiles) {
    kSystemjsConfig.includeFiles.forEach(function(pathOrPattern) {

	  var fileToInclude;

	  if (typeof pathOrPattern === 'object') {
        fileToInclude = pathOrPattern;
      } else {
		fileToInclude = createIncludePattern(basePath + pathOrPattern);
	  }

	  config.files.push(fileToInclude);
    });
  }

  // Adds karma-systemjs adapter.js to end of config.files
  config.files.push(createIncludePattern(__dirname + '/adapter.js'));

  // Adding configuration to be passed to the adapter running on the browser
  config.client.systemjs = {
    // SystemJS config needs to be converted to JSON to guarantee arrays are encoded correctly
    // https://github.com/rolaveric/karma-systemjs/issues/44
    config: JSON.stringify(kSystemjsConfig.config),
    importPatterns: importPatterns
  };
};
initSystemjs.$inject = ['config'];

module.exports = initSystemjs;
<commit_msg>Maintain spec.<commit_after>'use strict';
var path = require('path');
var fs = require('fs');
var _ = require('lodash');
var Minimatch = require('minimatch').Minimatch;

/**
 * Helper for mapping include file paths to karma file patterns - served, included, but not watched
 * @param path {string}
 * @returns {object}
 */
var createIncludePattern = function(path) {
  return {
    pattern: path,
    included: true,
    served: true,
    watched: false
  };
};

/**
 * Resolve paths for dependencies now
 * @param moduleName {string}
 * @param relativePath {string}
 * @returns {string}
 */
var getDependencyPath = function(moduleName, relativePath) {
  try {
    return path.dirname(require.resolve(moduleName)) + relativePath;
  } catch (e) {
    if (e.code === 'MODULE_NOT_FOUND' && e.message.indexOf(moduleName) !== -1) {
      console.warn('Cannot find "%s".\n  Did you forget to install it ?\n' +
        '  npm install %s --save-dev', moduleName, moduleName);
    } else {
      console.warn('Error during loading "%s":\n  %s', moduleName, e.message);
    }
  }
};

/**
 * Loads up a SystemJS config file and returns the configuration
 * Taken from how systemjs-builder loads config files inside node
 * @param filePath {string}
 * @returns {object}
 */
var readConfigFile = function(filePath) {
  var curSystem = global.System;
  var fileConfig = {};
  global.System = {
    config: function(cfg) {
      _.merge(fileConfig, cfg);
    }
  };
  // jshint evil:true
  new Function(fs.readFileSync(filePath).toString()).call(global);
  global.System = curSystem;
  return fileConfig;
};

/**
 * Returns a dependency path based on 'paths' configuration, or node_modules/ lookup
 * @param systemjsConfig {object} The SystemJS config object
 * @param basePath {string} Path that SystemJS paths are relative to
 * @param systemModuleName {string} Name of the module as the SystemJS config knows it.
 * @param npmModuleName {string} Name of module as npm knows it.
 * @param npmPath {string} Path to use relative to a `require.resolve()` call
 * @returns {string}
 */
var pathOrNpm = function(systemjsConfig, basePath, systemModuleName, npmModuleName, npmPath) {
  var filePath = systemjsConfig.paths && systemjsConfig.paths[systemModuleName];
  if (filePath) {
    return path.join(basePath, systemjsConfig.baseURL || '', filePath);
  } else {
    console.warn('[WARNING] Looking up paths with require.resolve() is deprecated.\n' +
      'Please add "' + systemModuleName + '" to your SystemJS config paths.');
    return getDependencyPath(npmModuleName, npmPath);
  }
};

/**
 * Returns the path to the transpiler.
 * @param config {object} SystemJS config
 * @param basePath {string}
 * @returns {string}
 */
var getTranspilerPath = function(config, basePath) {
  // Path should come from SystemJS, but for backwards compatibility will also check for a known npm path
  switch (config.transpiler) {
  case null: // If null, no transpiler in use
    return '';
  case 'babel':
    return pathOrNpm(config, basePath, 'babel', 'babel-core', '/../../../browser.js');
  case undefined: // Traceur is still the default transpiler if undefined
  case 'traceur':
    return pathOrNpm(config, basePath, 'traceur', 'traceur', '/../../bin/traceur.js');
  case 'typescript':
    return pathOrNpm(config, basePath, 'typescript', 'typescript', '/typescript.js');
  default:
    return pathOrNpm(config, basePath, config.transpiler, config.transpiler, config.transpiler + '.js');
  }
};

/**
 * Returns the list of '{included: true}' file patterns before setting them to '{included: false}'
 * @param fileList {object[]}
 * @param basePath {string}
 * @returns {string[]}
 */
var processIncludedPatterns = function(fileList, basePath) {
  var included = _.filter(fileList, {included: true});
  _.forEach(included, function (file) {
    file.included = false;
  });
  return _.map(included, function(file) {
    // Rather than make Minimatch available in the browser,
    // it's simpler to use it within Karma and extract the RegExps as strings.
    // Also take into account the '/base' or '/absolute' path that Karma serves files from
    var path = !basePath || file.pattern.indexOf(basePath) === 0 ?
        '/base' + file.pattern.replace(basePath, '') :
        '/absolute' + file.pattern;
    var regexString = (new Minimatch(path)).makeRe().toString();
    return regexString.substring(1, regexString.length - 1); // Remove the "/" from the start and end, so it'll fit into 'new RegExp()'
  });
};

/**
 * Run during karma initialisation.
 * Alters the karma configuration to use SystemJS.
 * @param config {object}
 */
var initSystemjs = function(config) {
  // Final files array should look like this:
  // - SystemJS libraries - included
  // - SystemJS config - included & watched
  // - 'files' - served, watched, and marked to be called with 'System.import()' (if {included: true})
  // - 'systemjs.serveFiles' - served only
  // - Plugin adapter - included

  // Create list of file patterns to load with 'System.import()'
  var importPatterns = processIncludedPatterns(config.files, config.basePath);

  var kSystemjsConfig = config.systemjs || {};
  kSystemjsConfig.config = kSystemjsConfig.config || {};
  var basePath = (config.basePath || '.') + '/';

  // If there's an external SystemJS configuration file...
  if (kSystemjsConfig.configFile) {
    // Load it, and merge it with the config
    // karma-systemjs.config should take precedence over external SystemJS configuration file
    var cfgPath = basePath + kSystemjsConfig.configFile;
    var kConfig = readConfigFile(cfgPath);

    // Absolute paths for modules should be moved to /base, where Karma serves them
    ['map', 'paths'].forEach(function(cfgKey) {
      if (typeof kConfig[cfgKey] === 'object') {
        Object.keys(kConfig[cfgKey]).forEach(function(module) {
          if (kConfig[cfgKey][module][0] === '/') {
            kConfig[cfgKey][module] = '/base' + kConfig[cfgKey][module];
          }
        });
      }
    });

    // Merge the SystemJS config file with the SystemJS config in the karma config
    _.merge(kConfig, kSystemjsConfig.config, function(objectValue, sourceValue) {
      // Overwrite array values - don't merge them
      if (_.isArray(sourceValue)) {
        return sourceValue;
      }
    });

    kSystemjsConfig.config = kConfig;
  }

  // Resolve the paths for es6-module-loader and systemjs
  // Check the System config for the paths, or revert to looking them up in node_modules/
  var es6LoaderPath = pathOrNpm(kSystemjsConfig.config, basePath,
    'es6-module-loader', 'es6-module-loader', '/dist/es6-module-loader.src.js');
  var systemjsPath = pathOrNpm(kSystemjsConfig.config, basePath,
    'systemjs', 'systemjs', '/dist/system.src.js');
  var polyfillsPath = pathOrNpm(kSystemjsConfig.config, basePath,
    'system-polyfills', 'systemjs', '/dist/system-polyfills.js');

  // Adds dependencies to start of config.files: es6-module-loader, and system.js
  // Don't watch, since these files should never change
  config.files.unshift(
    createIncludePattern(es6LoaderPath),
    createIncludePattern(polyfillsPath),
    createIncludePattern(systemjsPath)
  );

  // If a transpiler is being used, include it in the files
  var transpilerPath = getTranspilerPath(kSystemjsConfig.config, basePath);
  if (transpilerPath) {
    // Don't watch, since this file should never change
    config.files.unshift(
      createIncludePattern(transpilerPath)
    );
  }

  // system.js-0.16+ uses Function.prototype.bind, which PhantomJS does not support.
  if (config.browsers && config.browsers.indexOf('PhantomJS') !== -1) {
    var phantomjsPolyfillPath = pathOrNpm(kSystemjsConfig.config, basePath,
      'phantomjs-polyfill', 'phantomjs-polyfill', '/bind-polyfill.js');
    config.files.unshift(
      createIncludePattern(phantomjsPolyfillPath)
    );
  }

  // Adds file patterns from config.systemjs.serveFiles to config.files, set to be served but not included
  if (kSystemjsConfig.serveFiles) {
    kSystemjsConfig.serveFiles.forEach(function(pathOrPattern) {
      if (typeof pathOrPattern === 'object') {
        config.files.push(pathOrPattern);
      } else {
        config.files.push({
          pattern: basePath + pathOrPattern,
          included: false,
          served: true,
          watched: true
        });
      }
    });
  }

  // Add file patterns to always be included back into files
  if (kSystemjsConfig.includeFiles) {
    var filesToInclude = kSystemjsConfig.includeFiles.map(function(pathOrPattern) {
  	if (typeof pathOrPattern === 'object') {
           return pathOrPattern;
      	} else {
	   return createIncludePattern(basePath + pathOrPattern);
  	}
    });

    config.files.unshift(fileToInclude);
  }

  // Adds karma-systemjs adapter.js to end of config.files
  config.files.push(createIncludePattern(__dirname + '/adapter.js'));

  // Adding configuration to be passed to the adapter running on the browser
  config.client.systemjs = {
    // SystemJS config needs to be converted to JSON to guarantee arrays are encoded correctly
    // https://github.com/rolaveric/karma-systemjs/issues/44
    config: JSON.stringify(kSystemjsConfig.config),
    importPatterns: importPatterns
  };
};
initSystemjs.$inject = ['config'];

module.exports = initSystemjs;
<|endoftext|>


<commit_before>!function ($) {

    "use strict";

    // TABCOLLAPSE CLASS DEFINITION
    // ======================

    var TabCollapse = function (el, options) {
        this.options   = options;
        this.$tabs  = $(el);

        this._accordionVisible = false; //content is attached to tabs at first
        this._initAccordion();
        this._checkStateOnResize();

        // checkState() has gone to setTimeout for making it possible to attach listeners to
        // shown-accordion.bs.tabcollapse event on page load.
        // See https://github.com/flatlogic/bootstrap-tabcollapse/issues/23
        var that = this;
        setTimeout(function() {
          that.checkState();
        }, 0);
    };

    TabCollapse.DEFAULTS = {
        accordionClass: 'visible-xs',
        tabsClass: 'hidden-xs',
        accordionTemplate: function(heading, groupId, parentId, active) {
            return  '
' +
                    '
' +
                    '
' +
                    '
' +
                    '
' +
                    '
' +
                    '
' +
                    '
' +
                    '
' +
                    '
'

        }
    };

    TabCollapse.prototype.checkState = function(){
        if (this.$tabs.is(':visible') && this._accordionVisible){
            this.showTabs();
            this._accordionVisible = false;
        } else if (this.$accordion.is(':visible') && !this._accordionVisible){
            this.showAccordion();
            this._accordionVisible = true;
        }
    };

    TabCollapse.prototype.showTabs = function(){
        var view = this;
        this.$tabs.trigger($.Event('show-tabs.bs.tabcollapse'));

        var $panelHeadings = this.$accordion.find('.js-tabcollapse-panel-heading').detach();

        $panelHeadings.each(function() {
            var $panelHeading = $(this),
            $parentLi = $panelHeading.data('bs.tabcollapse.parentLi');

            var $oldHeading = view._panelHeadingToTabHeading($panelHeading);

            $parentLi.removeClass('active');
            if ($parentLi.parent().hasClass('dropdown-menu') && !$parentLi.siblings('li').hasClass('active')) {
                $parentLi.parent().parent().removeClass('active');
            }

            if (!$oldHeading.hasClass('collapsed')) {
                $parentLi.addClass('active');
                if ($parentLi.parent().hasClass('dropdown-menu')) {
                    $parentLi.parent().parent().addClass('active');
                }
            } else {
                $oldHeading.removeClass('collapsed');
            }

            $parentLi.append($panelHeading);
        });

        if (!$('li').hasClass('active')) {
            $('li').first().addClass('active')
        }

        var $panelBodies = this.$accordion.find('.js-tabcollapse-panel-body');
        $panelBodies.each(function(){
            var $panelBody = $(this),
                $tabPane = $panelBody.data('bs.tabcollapse.tabpane');
            $tabPane.append($panelBody.contents().detach());
        });
        this.$accordion.html('');

        if(this.options.updateLinks) {
            var $tabContents = this.getTabContentElement();
            $tabContents.find('[data-toggle-was="tab"], [data-toggle-was="pill"]').each(function() {
                var $el = $(this);
                var href = $el.attr('href').replace(/-collapse$/g, '');
                $el.attr({
                    'data-toggle': $el.attr('data-toggle-was'),
                    'data-toggle-was': '',
                    'data-parent': '',
                    href: href
                });
            });
        }

        this.$tabs.trigger($.Event('shown-tabs.bs.tabcollapse'));
    };

    TabCollapse.prototype.getTabContentElement = function(){
        var $tabContents = $(this.options.tabContentSelector);
        if($tabContents.length === 0) {
            $tabContents = this.$tabs.siblings('.tab-content');
        }
        return $tabContents;
    };

    TabCollapse.prototype.showAccordion = function(){
        this.$tabs.trigger($.Event('show-accordion.bs.tabcollapse'));

        var $headings = this.$tabs.find('li:not(.dropdown) [data-toggle="tab"], li:not(.dropdown) [data-toggle="pill"]'),
            view = this;
        $headings.each(function(){
            var $heading = $(this),
                $parentLi = $heading.parent();
            $heading.data('bs.tabcollapse.parentLi', $parentLi);
            view.$accordion.append(view._createAccordionGroup(view.$accordion.attr('id'), $heading.detach()));
        });

        if(this.options.updateLinks) {
            var parentId = this.$accordion.attr('id');
            var $selector = this.$accordion.find('.js-tabcollapse-panel-body');
            $selector.find('[data-toggle="tab"], [data-toggle="pill"]').each(function() {
                var $el = $(this);
                var href = $el.attr('href') + '-collapse';
                $el.attr({
                    'data-toggle-was': $el.attr('data-toggle'),
                    'data-toggle': 'collapse',
                    'data-parent': '#' + parentId,
                    href: href
                });
            });
        }

        this.$tabs.trigger($.Event('shown-accordion.bs.tabcollapse'));
    };

    TabCollapse.prototype._panelHeadingToTabHeading = function($heading) {
        var href = $heading.attr('href').replace(/-collapse$/g, '');
        $heading.attr({
            'data-toggle': 'tab',
            'href': href,
            'data-parent': ''
        });
        return $heading;
    };

    TabCollapse.prototype._tabHeadingToPanelHeading = function($heading, groupId, parentId, active) {
        $heading.addClass('js-tabcollapse-panel-heading ' + (active ? '' : 'collapsed'));
        $heading.attr({
            'data-toggle': 'collapse',
            'data-parent': '#' + parentId,
            'href': '#' + groupId
        });
        return $heading;
    };

    TabCollapse.prototype._checkStateOnResize = function(){
        var view = this;
        $(window).resize(function(){
            clearTimeout(view._resizeTimeout);
            view._resizeTimeout = setTimeout(function(){
                view.checkState();
            }, 100);
        });
    };

    TabCollapse.prototype._initAccordion = function(){
        var randomString = function() {
            var result = "",
                possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
            for( var i=0; i < 5; i++ ) {
                result += possible.charAt(Math.floor(Math.random() * possible.length));
            }
            return result;
        };

        var srcId = this.$tabs.attr('id'),
            accordionId = (srcId ? srcId : randomString()) + '-accordion';

        this.$accordion = $('

');
        this.$tabs.after(this.$accordion);
        this.$tabs.addClass(this.options.tabsClass);
        this.getTabContentElement().addClass(this.options.tabsClass);
    };

    TabCollapse.prototype._createAccordionGroup = function(parentId, $heading){
        var tabSelector = $heading.attr('data-target'),
            active = $heading.data('bs.tabcollapse.parentLi').is('.active');

        if (!tabSelector) {
            tabSelector = $heading.attr('href');
            tabSelector = tabSelector && tabSelector.replace(/.*(?=#[^\s]*$)/, ''); //strip for ie7
        }

        var $tabPane = $(tabSelector),
            groupId = $tabPane.attr('id') + '-collapse',
            $panel = $(this.options.accordionTemplate($heading, groupId, parentId, active));
        $panel.find('.panel-heading > .panel-title').append(this._tabHeadingToPanelHeading($heading, groupId, parentId, active));
        $panel.find('.panel-body').append($tabPane.contents().detach())
            .data('bs.tabcollapse.tabpane', $tabPane);

        return $panel;
    };

    // TABCOLLAPSE PLUGIN DEFINITION
    // =======================

    $.fn.tabCollapse = function (option) {
        return this.each(function () {
            var $this   = $(this);
            var data    = $this.data('bs.tabcollapse');
            var options = $.extend({}, TabCollapse.DEFAULTS, $this.data(), typeof option === 'object' && option);

            if (!data) $this.data('bs.tabcollapse', new TabCollapse(this, options));
        });
    };

    $.fn.tabCollapse.Constructor = TabCollapse;

}(window.jQuery);
<commit_msg>added active header class event<commit_after>
!function ($) {

    "use strict";

    // TABCOLLAPSE CLASS DEFINITION
    // ======================

    var TabCollapse = function (el, options) {
        this.options   = options;
        this.$tabs  = $(el);

        this._accordionVisible = false; //content is attached to tabs at first
        this._initAccordion();
        this._checkStateOnResize();

        // checkState() has gone to setTimeout for making it possible to attach listeners to
        // shown-accordion.bs.tabcollapse event on page load.
        // See https://github.com/flatlogic/bootstrap-tabcollapse/issues/23
        var that = this;
        setTimeout(function() {
            that.checkState();
        }, 0);
    };

    TabCollapse.DEFAULTS = {
        accordionClass: 'visible-xs',
        tabsClass: 'hidden-xs',
        accordionTemplate: function(heading, groupId, parentId, active) {
            return  '
' +
                '
' +
                '
' +
                '
' +
                '
' +
                '
' +
                '
' +
                '
' +
                '
' +
                '
'

        }
    };

    TabCollapse.prototype.checkState = function(){
        if (this.$tabs.is(':visible') && this._accordionVisible){
            this.showTabs();
            this._accordionVisible = false;
        } else if (this.$accordion.is(':visible') && !this._accordionVisible){
            this.showAccordion();
            this._accordionVisible = true;
        }
    };

    TabCollapse.prototype.showTabs = function(){
        var view = this;
        this.$tabs.trigger($.Event('show-tabs.bs.tabcollapse'));

        var $panelHeadings = this.$accordion.find('.js-tabcollapse-panel-heading').detach();

        $panelHeadings.each(function() {
            var $panelHeading = $(this),
                $parentLi = $panelHeading.data('bs.tabcollapse.parentLi');

            var $oldHeading = view._panelHeadingToTabHeading($panelHeading);

            $parentLi.removeClass('active');
            if ($parentLi.parent().hasClass('dropdown-menu') && !$parentLi.siblings('li').hasClass('active')) {
                $parentLi.parent().parent().removeClass('active');
            }

            if (!$oldHeading.hasClass('collapsed')) {
                $parentLi.addClass('active');
                if ($parentLi.parent().hasClass('dropdown-menu')) {
                    $parentLi.parent().parent().addClass('active');
                }
            } else {
                $oldHeading.removeClass('collapsed');
            }

            $parentLi.append($panelHeading);
        });

        if (!$('li').hasClass('active')) {
            $('li').first().addClass('active')
        }

        var $panelBodies = this.$accordion.find('.js-tabcollapse-panel-body');
        $panelBodies.each(function(){
            var $panelBody = $(this),
                $tabPane = $panelBody.data('bs.tabcollapse.tabpane');
            $tabPane.append($panelBody.contents().detach());
        });
        this.$accordion.html('');

        if(this.options.updateLinks) {
            var $tabContents = this.getTabContentElement();
            $tabContents.find('[data-toggle-was="tab"], [data-toggle-was="pill"]').each(function() {
                var $el = $(this);
                var href = $el.attr('href').replace(/-collapse$/g, '');
                $el.attr({
                    'data-toggle': $el.attr('data-toggle-was'),
                    'data-toggle-was': '',
                    'data-parent': '',
                    href: href
                });
            });
        }

        this.$tabs.trigger($.Event('shown-tabs.bs.tabcollapse'));
    };

    TabCollapse.prototype.getTabContentElement = function(){
        var $tabContents = $(this.options.tabContentSelector);
        if($tabContents.length === 0) {
            $tabContents = this.$tabs.siblings('.tab-content');
        }
        return $tabContents;
    };

    TabCollapse.prototype.showAccordion = function(){
        this.$tabs.trigger($.Event('show-accordion.bs.tabcollapse'));

        var $headings = this.$tabs.find('li:not(.dropdown) [data-toggle="tab"], li:not(.dropdown) [data-toggle="pill"]'),
            view = this;
        $headings.each(function(){
            var $heading = $(this),
                $parentLi = $heading.parent();
            $heading.data('bs.tabcollapse.parentLi', $parentLi);
            view.$accordion.append(view._createAccordionGroup(view.$accordion.attr('id'), $heading.detach()));
        });

        if(this.options.updateLinks) {
            var parentId = this.$accordion.attr('id');
            var $selector = this.$accordion.find('.js-tabcollapse-panel-body');
            $selector.find('[data-toggle="tab"], [data-toggle="pill"]').each(function() {
                var $el = $(this);
                var href = $el.attr('href') + '-collapse';
                $el.attr({
                    'data-toggle-was': $el.attr('data-toggle'),
                    'data-toggle': 'collapse',
                    'data-parent': '#' + parentId,
                    href: href
                });
            });
        }

        this.$tabs.trigger($.Event('shown-accordion.bs.tabcollapse'));
    };

    TabCollapse.prototype._panelHeadingToTabHeading = function($heading) {
        var href = $heading.attr('href').replace(/-collapse$/g, '');
        $heading.attr({
            'data-toggle': 'tab',
            'href': href,
            'data-parent': ''
        });
        return $heading;
    };

    TabCollapse.prototype._tabHeadingToPanelHeading = function($heading, groupId, parentId, active) {
        $heading.addClass('js-tabcollapse-panel-heading ' + (active ? '' : 'collapsed'));
        $heading.attr({
            'data-toggle': 'collapse',
            'data-parent': '#' + parentId,
            'href': '#' + groupId
        });
        return $heading;
    };

    TabCollapse.prototype._checkStateOnResize = function(){
        var view = this;
        $(window).resize(function(){
            clearTimeout(view._resizeTimeout);
            view._resizeTimeout = setTimeout(function(){
                view.checkState();
            }, 100);
        });
    };

    TabCollapse.prototype._initAccordion = function(){
        var randomString = function() {
            var result = "",
                possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
            for( var i=0; i < 5; i++ ) {
                result += possible.charAt(Math.floor(Math.random() * possible.length));
            }
            return result;
        };

        var srcId = this.$tabs.attr('id'),
            accordionId = (srcId ? srcId : randomString()) + '-accordion';

        this.$accordion = $('

');
        this.$tabs.after(this.$accordion);
        this.$tabs.addClass(this.options.tabsClass);
        this.getTabContentElement().addClass(this.options.tabsClass);
    };

    TabCollapse.prototype._createAccordionGroup = function(parentId, $heading){
        var tabSelector = $heading.attr('data-target'),
            active = $heading.data('bs.tabcollapse.parentLi').is('.active');

        if (!tabSelector) {
            tabSelector = $heading.attr('href');
            tabSelector = tabSelector && tabSelector.replace(/.*(?=#[^\s]*$)/, ''); //strip for ie7
        }

        var activeHead = function(el){
            $('.panel-heading').removeClass('active');
            $(el).parents('.panel-heading').addClass('active');
        }

        var $tabPane = $(tabSelector),
            groupId = $tabPane.attr('id') + '-collapse',
            $panel = $(this.options.accordionTemplate($heading, groupId, parentId, active));
        $panel.find('.panel-heading h4').on('click', function() {
            $panel.trigger(activeHead($(this)));
        });
        $panel.find('.panel-heading > .panel-title').append(this._tabHeadingToPanelHeading($heading, groupId, parentId, active));
        $panel.find('.panel-body').append($tabPane.contents().detach())
            .data('bs.tabcollapse.tabpane', $tabPane);

        return $panel;
    };

    // TABCOLLAPSE PLUGIN DEFINITION
    // =======================

    $.fn.tabCollapse = function (option) {
        return this.each(function () {
            var $this   = $(this);
            var data    = $this.data('bs.tabcollapse');
            var options = $.extend({}, TabCollapse.DEFAULTS, $this.data(), typeof option === 'object' && option);

            if (!data) $this.data('bs.tabcollapse', new TabCollapse(this, options));
        });
    };

    $.fn.tabCollapse.Constructor = TabCollapse;

}(window.jQuery);
<|endoftext|>


<commit_before>'use strict';

const { MovieInfo, SearchResult } = require('../../models/types.js');
const leech = require('../leech-promise.js');
const util = require('../util.js');
const dict = require('../category-dictionary.js');

const NAME = 'tokyo-hot';
module.exports.name = function () {
    return NAME;
}

const TEMPLATE = {
    "search": "http://my.tokyo-hot.com/product/?q={qtext}&{lang}",
    "id": "http://my.tokyo-hot.com/product/{qtext}/",
}

const DOMAIN = 'my.tokyo-hot.com';
module.exports.domain = function () {
    return DOMAIN;
}

const BASE_URL = 'http://' + DOMAIN;

const LangMap = {
    'releasedate': { 'ja': '配信開始日', 'en': 'Release Date' },
    'duration': { 'ja': '収録時間', 'en': 'Duration' },
    'title': { 'ja': '作品番号', 'en': 'Product ID' },
    'actors': { 'ja': '出演者', 'en': 'Actress' },
    'series': { 'ja': 'シリーズ', 'en': 'Theme' },
    'label': { 'ja': 'レーベル', 'en': 'Label' },
    'play': { 'ja': 'プレイ内容', 'en': 'Play' },
    'tags': { 'ja': 'タグ', 'en': 'Tags' },
}

function getFootprint (data) {
    return {
        "crawler": NAME,
        "id": data.movid,
    };
}

function formatMovID (val) {
    var p = val.split('product/');
    var pp = p[1].split('/');
    return pp[0];
}

function crawl (opt) {
    let url = "";
    let lang = "en";
    if (typeof opt == 'string') {
        url = opt;
    }

    if (typeof opt == 'object') {
        let type = opt.type || '';
        let qtext = opt.qtext || '';
        if (type && qtext) {
            url = TEMPLATE[type].replace('{qtext}', qtext);
        }

        if (opt.lang == 'ja') {
            lang = 'ja';
            // url = url.replace('{lang}', 'lang=jp');
        }

        if (opt.lang == 'en') {
            lang = 'en';
            url = url + '?lang=en';
        }
    }

    if (url == "") {
        throw new Error("Invalid Arguments");
    }

    return new Promise((resolve, reject) => {
        leech.get(url)
        .then($ => {
            if ($('.list.slider').length == 0 &&
                $('.infowrapper').length == 0) {
                resolve(null);

            } else {
                if ($('.list.slider').length > 0) {
                    // Search result
                    let result = new SearchResult( {
                        url: url,
                        footprint: getFootprint,
                    } );
                    result.queryString = $('#key').attr('value');
                    $('.list.slider li.detail').each((i, el) => {
                        let ele = $(el);
                        let info = new MovieInfo({
                            country: 'Japan',
                            origlang: 'Japanese',
                        });
                        info.movid = ele.find('a').attr('href').replace('/product/', '');
                        info.movid = info.movid.substring(0, info.movid.length - 1);
                        info.url = BASE_URL + '/product/' + info.movid + '/';
                        info.posters.push({
                            url: ele.find('img').attr('src')
                        });
                        info.title = 'Tokyo-Hot ' + ele.find('img').attr('title');
                        if (lang == 'en') {
                            info.transtitle = ele.find('.title').text();
                        }
                        if (lang == 'ja') {
                            info.origtitle = ele.find('.title').text();
                        }
                        result.results.push(info);
                    });
                    result.more = $('div.navi').length > 0;

                    resolve(result);
                } else {
                    let info = new MovieInfo({
                        url: url,
                        country: 'Japan',
                        origlang: 'Japanese',
                    });
                    info.movid = formatMovID(url);
                    var title = $(`.infowrapper dt:contains("${LangMap['title'][lang]}")`)
                        .next().text();
                    info.title = 'Tokyo-Hot ' + title;
                    var jacket = $('.package a').first().attr('href') || ''
                    if (jacket.indexOf('jacket') > -1) {
                        info.covers.push({
                            url: jacket,
                        });
                    } else {
                        info.covers.push({
                            url: $('video').attr('poster'),
                        });
                    }
                    info.thumb.push({
                        url: `http://my.cdn.tokyo-hot.com/media/${info.movid}/package/_v.jpg`
                    })
                    if (lang == 'ja') {
                        info.origtitle = $('.contents > h2').text();
                    }
                    if (lang == 'en') {
                        info.transtitle = $('.contents > h2').text();
                    }
                    info.description = $('.contents > .sentence').text().trim();
                    info.releasedate = util.replaceAll(
                        $(`.infowrapper dt:contains("${LangMap['releasedate'][lang]}")`)
                            .next().text(),
                        '/', '-'
                    );
                    info.year = info.releasedate.substring(0, 4);
                    info.duration = $(`.infowrapper dt:contains("${LangMap['duration'][lang]}")`)
                        .next().text();
                    $(`.infowrapper dt:contains("${LangMap['actors'][lang]}")`)
                        .next().find('a').each((i, el) => {
                            let ele = $(el);
                            let actor = {
                                url: BASE_URL + ele.attr('href'),
                                text: ele.text(),
                            }
                            info.actors.push(actor);
                        });
                    var ele = $(`.infowrapper dt:contains("${LangMap['series'][lang]}")`)
                        .next().find('a');
                    if (ele.length > 0) {
                        info.series = {
                            url: BASE_URL + ele.attr('href'),
                            text: ele.text(),
                        };
                    }

                    $(`.infowrapper dt:contains("${LangMap['play'][lang]}")`)
                        .next().find('a').each((i, el) => {
                            let ele = $(el);
                            let genre = {
                                url: BASE_URL + ele.attr('href'),
                                text: util.formatProperCase(
                                    dict('ja', ele.text())
                                ),
                            }
                            info.genres.push(genre);
                        });

                    $(`.infowrapper dt:contains("${LangMap['tags'][lang]}")`)
                        .next().find('a').each((i, el) => {
                            let ele = $(el);
                            let genre = {
                                url: BASE_URL + ele.attr('href'),
                                text: util.formatProperCase(
                                    dict('ja', ele.text())
                                ),
                            }
                            info.genres.push(genre);
                        });

                    info.maker = 'TOKYO-HOT';

                    var ele = $(`.infowrapper dt:contains("${LangMap['label'][lang]}")`)
                        .next().find('a');
                    if (ele.length > 0) {
                        info.label = {
                            url: BASE_URL + ele.attr('href'),
                            text: ele.text(),
                        };
                    }

                    resolve(info);
                }
            }
        })
        .catch(err => util.catchURLError(url, err, resolve, reject));
    });
}

module.exports.crawl = crawl;
<commit_msg>update host<commit_after>'use strict';

const { MovieInfo, SearchResult } = require('../../models/types.js');
const leech = require('../leech-promise.js');
const util = require('../util.js');
const dict = require('../category-dictionary.js');

const NAME = 'tokyo-hot';
module.exports.name = function () {
    return NAME;
}

const TEMPLATE = {
    "search": "https://my.tokyo-hot.com/product/?q={qtext}",
    "id": "https://my.tokyo-hot.com/product/{qtext}/",
}

const DOMAIN = 'my.tokyo-hot.com';
module.exports.domain = function () {
    return DOMAIN;
}

const BASE_URL = 'https://' + DOMAIN;

const LangMap = {
    'releasedate': { 'ja': '配信開始日', 'en': 'Release Date' },
    'duration': { 'ja': '収録時間', 'en': 'Duration' },
    'title': { 'ja': '作品番号', 'en': 'Product ID' },
    'actors': { 'ja': '出演者', 'en': 'Actress' },
    'series': { 'ja': 'シリーズ', 'en': 'Theme' },
    'label': { 'ja': 'レーベル', 'en': 'Label' },
    'play': { 'ja': 'プレイ内容', 'en': 'Play' },
    'tags': { 'ja': 'タグ', 'en': 'Tags' },
}

function getFootprint (data) {
    return {
        "crawler": NAME,
        "id": data.movid,
    };
}

function formatMovID (val) {
    var p = val.split('product/');
    var pp = p[1].split('/');
    return pp[0];
}

function crawl (opt) {
    let url = "";
    let lang = "en";
    if (typeof opt == 'string') {
        url = opt;
    }

    if (typeof opt == 'object') {
        let type = opt.type || '';
        let qtext = opt.qtext || '';
        if (type && qtext) {
            url = TEMPLATE[type].replace('{qtext}', qtext);
        }

        if (opt.lang == 'ja') {
            lang = 'ja';
            // url = url.replace('{lang}', 'lang=jp');
        }

        if (opt.lang == 'en') {
            lang = 'en';
            url = url + '&lang=en';
        }
    }

    if (url == "") {
        throw new Error("Invalid Arguments");
    }

    return new Promise((resolve, reject) => {
        leech.get(url)
        .then($ => {
            if ($('.list.slider').length == 0 &&
                $('.infowrapper').length == 0) {
                resolve(null);

            } else {
                if ($('.list.slider').length > 0) {
                    // Search result
                    let result = new SearchResult( {
                        url: url,
                        footprint: getFootprint,
                    } );
                    result.queryString = $('#key').attr('value');
                    $('.list.slider li.detail').each((i, el) => {
                        let ele = $(el);
                        let info = new MovieInfo({
                            country: 'Japan',
                            origlang: 'Japanese',
                        });
                        info.movid = ele.find('a').attr('href').replace('/product/', '');
                        info.movid = info.movid.substring(0, info.movid.length - 1);
                        info.url = BASE_URL + '/product/' + info.movid + '/';
                        info.posters.push({
                            url: ele.find('img').attr('src')
                        });
                        info.title = 'Tokyo-Hot ' + ele.find('img').attr('title');
                        if (lang == 'en') {
                            info.transtitle = ele.find('.title').text();
                        }
                        if (lang == 'ja') {
                            info.origtitle = ele.find('.title').text();
                        }
                        result.results.push(info);
                    });
                    result.more = $('div.navi').length > 0;

                    resolve(result);
                } else {
                    let info = new MovieInfo({
                        url: url,
                        country: 'Japan',
                        origlang: 'Japanese',
                    });
                    info.movid = formatMovID(url);
                    var title = $(`.infowrapper dt:contains("${LangMap['title'][lang]}")`)
                        .next().text();
                    info.title = 'Tokyo-Hot ' + title;
                    var jacket = $('.package a').first().attr('href') || ''
                    if (jacket.indexOf('jacket') > -1) {
                        info.covers.push({
                            url: jacket,
                        });
                    } else {
                        info.covers.push({
                            url: $('video').attr('poster'),
                        });
                    }
                    info.thumb.push({
                        url: `http://my.cdn.tokyo-hot.com/media/${info.movid}/package/_v.jpg`
                    })
                    if (lang == 'ja') {
                        info.origtitle = $('.contents > h2').text();
                    }
                    if (lang == 'en') {
                        info.transtitle = $('.contents > h2').text();
                    }
                    info.description = $('.contents > .sentence').text().trim();
                    info.releasedate = util.replaceAll(
                        $(`.infowrapper dt:contains("${LangMap['releasedate'][lang]}")`)
                            .next().text(),
                        '/', '-'
                    );
                    info.year = info.releasedate.substring(0, 4);
                    info.duration = $(`.infowrapper dt:contains("${LangMap['duration'][lang]}")`)
                        .next().text();
                    $(`.infowrapper dt:contains("${LangMap['actors'][lang]}")`)
                        .next().find('a').each((i, el) => {
                            let ele = $(el);
                            let actor = {
                                url: BASE_URL + ele.attr('href'),
                                text: ele.text(),
                            }
                            info.actors.push(actor);
                        });
                    var ele = $(`.infowrapper dt:contains("${LangMap['series'][lang]}")`)
                        .next().find('a');
                    if (ele.length > 0) {
                        info.series = {
                            url: BASE_URL + ele.attr('href'),
                            text: ele.text(),
                        };
                    }

                    $(`.infowrapper dt:contains("${LangMap['play'][lang]}")`)
                        .next().find('a').each((i, el) => {
                            let ele = $(el);
                            let genre = {
                                url: BASE_URL + ele.attr('href'),
                                text: util.formatProperCase(
                                    dict('ja', ele.text())
                                ),
                            }
                            info.genres.push(genre);
                        });

                    $(`.infowrapper dt:contains("${LangMap['tags'][lang]}")`)
                        .next().find('a').each((i, el) => {
                            let ele = $(el);
                            let genre = {
                                url: BASE_URL + ele.attr('href'),
                                text: util.formatProperCase(
                                    dict('ja', ele.text())
                                ),
                            }
                            info.genres.push(genre);
                        });

                    info.maker = 'TOKYO-HOT';

                    var ele = $(`.infowrapper dt:contains("${LangMap['label'][lang]}")`)
                        .next().find('a');
                    if (ele.length > 0) {
                        info.label = {
                            url: BASE_URL + ele.attr('href'),
                            text: ele.text(),
                        };
                    }

                    resolve(info);
                }
            }
        })
        .catch(err => util.catchURLError(url, err, resolve, reject));
    });
}

module.exports.crawl = crawl;
<|endoftext|>


<commit_before>const Discord = require('discord.js');
module.exports = (message) => {
    let me = message.embeds.shift();
    const embed = new Discord.RichEmbed();
    embed.setAuthor(message.author.username,message.author.avatarURL)
    embed.setTitle(message.channel.name +" in "+message.guild.name)
    if(!message.content =="")
        embed.setDescription(message.content);
    else
        embed.setDescription("**"+me.author.name+" said in "+me.title+"**\n"+me.description+"\n *At "+me.footer+"*");
    embed.setFooter(message.createdAt)
    //embed.setTitle("Quote");
    return embed;
}
<commit_msg>footer is an object. get text field from it<commit_after>const Discord = require('discord.js');
module.exports = (message) => {
    let me = message.embeds.shift();
    const embed = new Discord.RichEmbed();
    embed.setAuthor(message.author.username,message.author.avatarURL)
    embed.setTitle(message.channel.name +" in "+message.guild.name)
    if(!message.content =="")
        embed.setDescription(message.content);
    else
        embed.setDescription("**"+me.author.name+" said in "+me.title+"**\n"+me.description+"\n *At "+me.footer.text+"*");
    embed.setFooter(message.createdAt)
    //embed.setTitle("Quote");
    return embed;
}
<|endoftext|>


<commit_before>import React from 'react'
import ReactDOM from 'react-dom'
import {
  renderIntoDocument,
  scryRenderedDOMComponentsWithTag,
  findRenderedDOMComponentWithTag,
  Simulate
} from 'react-addons-test-utils'

import RegistrationStatusInfo from './RegistrationStatusInfo'

describe('When rendering RegistrationStatusInfo', () => {

  it('should show a success message', () => {
    const state = {
      userName: 'John Doe',
    }
    const component = renderIntoDocument(
      <RegistrationStatusInfo state={state}/>
    )

    const renderedDOM = ReactDOM.findDOMNode(component)

    const title = renderedDOM.querySelector('#title')
    expect(title).not.toBeNull()
    expect(title.textContent).toEqual('Registration Status')

    const message = renderedDOM.querySelector('#message')
    expect(message).not.toBeNull()
    expect(message.textContent).toEqual('Thank you John Doe! You have successfully registered.')

  })

})
<commit_msg>Changes test to pass in message<commit_after>import React from 'react'
import ReactDOM from 'react-dom'
import {
  renderIntoDocument,
  scryRenderedDOMComponentsWithTag,
  findRenderedDOMComponentWithTag,
  Simulate
} from 'react-addons-test-utils'

import RegistrationStatusInfo from './RegistrationStatusInfo'

describe('When rendering RegistrationStatusInfo', () => {

  it('should show a success message', () => {
    const state = {
      userName: 'John Doe',
    }

    const successMessage = 'Thank you ' + state.userName
        + '! You have successfully registered.'

    const component = renderIntoDocument(
      <RegistrationStatusInfo state={state} message={successMessage} />
    )

    const renderedDOM = ReactDOM.findDOMNode(component)

    const title = renderedDOM.querySelector('#title')
    expect(title).not.toBeNull()
    expect(title.textContent).toEqual('Registration Status')

    const message = renderedDOM.querySelector('#message')
    expect(message).not.toBeNull()
    expect(message.textContent).toEqual('Thank you John Doe! You have successfully registered.')

  })

})
<|endoftext|>


<commit_before>var toc = [
  [
    "Quick start",
    "Seven principles",
    "Resources"
  ],
  "Concepts", [
    "What is Meteor?",
    "Structuring your app",
    "Data and security",
    "Reactivity",
    "Live HTML templates",
    "Using packages",
    "Namespacing",
    "Deploying",
    "Writing packages"
  ],

  "API", [
    "Core", [
      "Meteor.isClient",
      "Meteor.isServer",
      "Meteor.isCordova",
      "Meteor.startup",
      "Meteor.wrapAsync",
      "Meteor.absoluteUrl",
      "Meteor.settings",
      "Meteor.release"
    ],

    "Publish and subscribe", [
      "Meteor.publish", [
        {instance: "this", name: "userId", id: "publish_userId"},
        {instance: "this", name: "added", id: "publish_added"},
        {instance: "this", name: "changed", id: "publish_changed"},
        {instance: "this", name: "removed", id: "publish_removed"},
        {instance: "this", name: "ready", id: "publish_ready"},
        {instance: "this", name: "onStop", id: "publish_onstop"},
        {instance: "this", name: "error", id: "publish_error"},
        {instance: "this", name: "stop", id: "publish_stop"},
        {instance: "this", name: "connection", id: "publish_connection"}
      ],
      "Meteor.subscribe"
    ],

    {name: "Methods", id: "methods_header"}, [
      "Meteor.methods", [
        {instance: "this", name: "userId", id: "method_userId"},
        {instance: "this", name: "setUserId", id: "method_setUserId"},
        {instance: "this", name: "isSimulation", id: "method_issimulation"},
        {instance: "this", name: "unblock", id: "method_unblock"},
        {instance: "this", name: "connection", id: "method_connection"}
      ],
      "Meteor.Error",
      "Meteor.call",
      "Meteor.apply"
    ],

    {name: "Check", id: "check_package"}, [
      "check",
      "Match.test",
      {name: "Match patterns", style: "noncode"}
    ],

    {name: "Server connections", id: "connections"}, [
      "Meteor.status",
      "Meteor.reconnect",
      "Meteor.disconnect",
      "Meteor.onConnection",
      "DDP.connect"
    ],

    {name: "Collections", id: "collections"}, [
      "Mongo.Collection", [
        {instance: "collection", name: "find"},
        {instance: "collection", name: "findOne"},
        {instance: "collection", name: "insert"},
        {instance: "collection", name: "update"},
        {instance: "collection", name: "upsert"},
        {instance: "collection", name: "remove"},
        {instance: "collection", name: "allow"},
        {instance: "collection", name: "deny"}
      ],

      "Mongo.Cursor", [
        {instance: "cursor", name: "forEach"},
        {instance: "cursor", name: "map"},
        {instance: "cursor", name: "fetch"},
        {instance: "cursor", name: "count"},
        {instance: "cursor", name: "observe"},
        {instance: "cursor", name: "observeChanges", id: "observe_changes"}
      ],
      {type: "spacer"},
      {name: "Mongo.ObjectID", id: "mongo_object_id"},
      {type: "spacer"},
      {name: "Selectors", style: "noncode"},
      {name: "Modifiers", style: "noncode"},
      {name: "Sort specifiers", style: "noncode"},
      {name: "Field specifiers", style: "noncode"}
    ],

    "Session", [
      "Session.set",
      {name: "Session.setDefault", id: "session_set_default"},
      "Session.get",
      "Session.equals"
    ],

    {name: "Accounts", id: "accounts_api"}, [
      "Meteor.user",
      "Meteor.userId",
      "Meteor.users",
      "Meteor.loggingIn",
      "Meteor.logout",
      "Meteor.logoutOtherClients",
      "Meteor.loginWithPassword",
      {name: "Meteor.loginWith<Service>", id: "meteor_loginwithexternalservice"},
      {type: "spacer"},

      {name: "{{currentUser}}", id: "template_currentuser"},
      {name: "{{loggingIn}}", id: "template_loggingin"},
      {type: "spacer"},

      "Accounts.config",
      "Accounts.ui.config",
      "Accounts.validateNewUser",
      "Accounts.onCreateUser",
      "Accounts.validateLoginAttempt",
      "Accounts.onLogin",
      "Accounts.onLoginFailure"
    ],

    {name: "Passwords", id: "accounts_passwords"}, [
      "Accounts.createUser",
      "Accounts.changePassword",
      "Accounts.forgotPassword",
      "Accounts.resetPassword",
      "Accounts.setPassword",
      "Accounts.verifyEmail",
      {type: "spacer"},

      "Accounts.sendResetPasswordEmail",
      "Accounts.sendEnrollmentEmail",
      "Accounts.sendVerificationEmail",
      {type: "spacer"},

      {name: "Accounts.onResetPasswordLink", id: "Accounts-onResetPasswordLink"},
      {name: "Accounts.onEnrollmentLink", id: "Accounts-onEnrollmentLink"},
      {name: "Accounts.onEmailVerificationLink", id: "Accounts-onEmailVerificationLink"},
      {type: "spacer"},

      "Accounts.emailTemplates"
    ],

    {name: "Templates", id: "templates_api"}, [
      {prefix: "Template", instance: "myTemplate", id: "templates_api"}, [
        {name: "events", id: "template_events"},
        {name: "helpers", id: "template_helpers"},
        {name: "onRendered", id: "template_onRendered"},
        {name: "onCreated", id: "template_onCreated"},
        {name: "onDestroyed", id: "template_onDestroyed"}
      ],
      {name: "Template instances", id: "template_inst"}, [
        {instance: "template", name: "findAll", id: "template_findAll"},
        {instance: "template", name: "$", id: "template_$"},
        {instance: "template", name: "find", id: "template_find"},
        {instance: "template", name: "firstNode", id: "template_firstNode"},
        {instance: "template", name: "lastNode", id: "template_lastNode"},
        {instance: "template", name: "data", id: "template_data"},
        {instance: "template", name: "autorun", id: "template_autorun"},
        {instance: "template", name: "subscribe", id: "Blaze-TemplateInstance-subscribe"},
        {instance: "template", name: "view", id: "template_view"}
      ],
      "Template.registerHelper",
      "Template.instance",
      "Template.currentData",
      "Template.parentData",
      "Template.body",
      {name: "{{> Template.dynamic}}", id: "template_dynamic"},
      {type: "spacer"},
      {name: "Event maps", style: "noncode"}
    ],
    "Blaze", [
      "Blaze.render",
      "Blaze.renderWithData",
      "Blaze.remove",
      "Blaze.getData",
      "Blaze.toHTML",
      "Blaze.toHTMLWithData",
      "Blaze.View", [
        "Blaze.currentView",
        "Blaze.getView",
        "Blaze.With",
        "Blaze.If",
        "Blaze.Unless",
        "Blaze.Each"
      ],
      "Blaze.Template",
      "Blaze.isTemplate",
      {type: "spacer"},
      {name: "Renderable content", id: "renderable_content", style: "noncode"}
     ],

    "Timers", [
      "Meteor.setTimeout",
      "Meteor.setInterval",
      "Meteor.clearTimeout",
      "Meteor.clearInterval"
    ],

    "Tracker", [
      "Tracker.autorun",
      "Tracker.flush",
      "Tracker.nonreactive",
      "Tracker.active",
      "Tracker.currentComputation",
      "Tracker.onInvalidate",
      "Tracker.afterFlush",
      "Tracker.Computation", [
        {instance: "computation", name: "stop", id: "computation_stop"},
        {instance: "computation", name: "invalidate", id: "computation_invalidate"},
        {instance: "computation", name: "onInvalidate", id: "computation_oninvalidate"},
        {instance: "computation", name: "stopped", id: "computation_stopped"},
        {instance: "computation", name: "invalidated", id: "computation_invalidated"},
        {instance: "computation", name: "firstRun", id: "computation_firstrun"}
      ],
      "Tracker.Dependency", [
        {instance: "dependency", name: "changed", id: "dependency_changed"},
        {instance: "dependency", name: "depend", id: "dependency_depend"},
        {instance: "dependency", name: "hasDependents", id: "dependency_hasdependents"}
      ]
    ],

    {name: "ReactiveVar", id: "reactivevar_pkg"}, [
      "ReactiveVar",
      {instance: "reactiveVar", name: "get", id: "reactivevar_get"},
      {instance: "reactiveVar", name: "set", id: "reactivevar_set"}
    ],

    // "Environment Variables", [
    //   "Meteor.EnvironmentVariable", [
    //     {instance: "env_var", name: "get", id: "env_var_get"},
    //     {instance: "env_var", name: "withValue", id: "env_var_withvalue"},
    //     {instance: "env_var", name: "bindEnvironment", id: "env_var_bindenvironment"}
    //   ]
    //],

    {name: "EJSON", id: "ejson"}, [
      {name: "EJSON.parse", id: "ejson_parse"},
      {name: "EJSON.stringify", id: "ejson_stringify"},
      {name: "EJSON.fromJSONValue", id: "ejson_from_json_value"},
      {name: "EJSON.toJSONValue", id: "ejson_to_json_value"},
      {name: "EJSON.equals", id: "ejson_equals"},
      {name: "EJSON.clone", id: "ejson_clone"},
      {name: "EJSON.newBinary", id: "ejson_new_binary"},
      {name: "EJSON.isBinary", id: "ejson_is_binary"},
      {name: "EJSON.addType", id: "ejson_add_type"},
      [
        {instance: "customType", id: "ejson_type_typeName", name: "typeName"},
        {instance: "customType", id: "ejson_type_toJSONValue", name: "toJSONValue"},
        {instance: "customType", id: "ejson_type_clone", name: "clone"},
        {instance: "customType", id: "ejson_type_equals", name: "equals"}
      ]
    ],

    "HTTP", [
      "HTTP.call",
      {name: "HTTP.get"},
      {name: "HTTP.post"},
      {name: "HTTP.put"},
      {name: "HTTP.del"}
    ],
    "Email", [
      "Email.send"
    ],
    {name: "Assets", id: "assets"}, [
      {name: "Assets.getText", id: "assets_getText"},
      {name: "Assets.getBinary", id: "assets_getBinary"}
    ],

    {name: "package.js", id: "packagejs"}, [
      {name: "Package.describe", id: "packagedescription"},
      {name: "Package.onUse", id: "packagedefinition"}, [
        {name: "api.versionsFrom", id: "pack_versions"},
        {name: "api.use", id: "pack_use"},
        {name: "api.imply", id: "pack_api_imply"},
        {name: "api.export", id: "pack_export"},
        {name: "api.addFiles", id: "pack_addFiles"}
      ],
      {name: "Package.onTest", id: "packagetests"},
      {name: "Npm.depends", id: "Npm-depends"},
      {name: "Npm.require", id: "Npm-require"},
      {name: "Cordova.depends", id: "Cordova-depends"},
      {name: "Package.registerBuildPlugin", id: "Package-registerBuildPlugin"}, [
        {name: "Plugin.registerSourceHandler", id: "Plugin-registerSourceHandler"}
      ]
    ],

    {name: "mobile-config.js", id: "mobileconfigjs"}, [
      {name: "App.info", id: "App-info"},
      {name: "App.setPreference", id: "App-setPreference"},
      {name: "App.accessRule", id: "App-accessRule"},
      {name: "App.configurePlugin", id: "App-configurePlugin"},
      {name: "App.icons", id: "App-icons"},
      {name: "App.launchScreens", id: "App-launchScreens"}
    ]
  ],

  "Packages", [ [
    "appcache",
    "accounts-ui",
    "audit-argument-checks",
    "coffeescript",
    "jquery",
    "less",
    "markdown",
    "oauth-encryption",
    "random",
    "showdown",
    {name: "spiderable", link: "https://atmospherejs.com/meteor/spiderable"},
    "stylus",
    "underscore",
    "webapp"
  ] ],

  "Command line", [ [
    "meteor help",
    "meteor run",
    "meteor create",
    "meteor deploy",
    "meteor logs",
    "meteor update",
    "meteor add",
    "meteor remove",
    "meteor list",
    "meteor mongo",
    "meteor reset",
    "meteor build",
    "meteor search",
    "meteor show",
    "meteor publish",
    "meteor publish-for-arch",
    "meteor publish-release",
    "meteor test-packages",
    "meteor admin"
  ] ]
];

var name_to_id = function (name) {
  var x = name.toLowerCase().replace(/[^a-z0-9_,.]/g, '').replace(/[,.]/g, '_');
  return x;
};

Template.nav.helpers({
  sections: function () {
    var ret = [];
    var walk = function (items, depth) {
      _.each(items, function (item) {
        // Work around (eg) accidental trailing commas leading to spurious holes
        // in IE8.
        if (!item)
          return;
        if (item instanceof Array)
          walk(item, depth + 1);
        else {
          if (typeof(item) === "string")
            item = {name: item};

          var id = item.id || (item.name && name_to_id(item.name)) || "";

          ret.push(_.extend({
            type: "section",
            link: "#/full/" + id,
            depth: depth,
            style: ''
          }, item));
        }
      });
    };

    walk(toc, 1);
    return ret;
  },

  type: function (what) {
    return this.type === what;
  },

  maybe_current: function () {
    return Session.get('urlHash').split('/')[2] === this.id ? 'current' : '';
  }
});

Template.nav_section.helpers({
  depthIs: function (n) {
    return this.depth === n;
  }
});
<commit_msg>Removed broken stylus and showdown links from full-api docs packages menu.<commit_after>var toc = [
  [
    "Quick start",
    "Seven principles",
    "Resources"
  ],
  "Concepts", [
    "What is Meteor?",
    "Structuring your app",
    "Data and security",
    "Reactivity",
    "Live HTML templates",
    "Using packages",
    "Namespacing",
    "Deploying",
    "Writing packages"
  ],

  "API", [
    "Core", [
      "Meteor.isClient",
      "Meteor.isServer",
      "Meteor.isCordova",
      "Meteor.startup",
      "Meteor.wrapAsync",
      "Meteor.absoluteUrl",
      "Meteor.settings",
      "Meteor.release"
    ],

    "Publish and subscribe", [
      "Meteor.publish", [
        {instance: "this", name: "userId", id: "publish_userId"},
        {instance: "this", name: "added", id: "publish_added"},
        {instance: "this", name: "changed", id: "publish_changed"},
        {instance: "this", name: "removed", id: "publish_removed"},
        {instance: "this", name: "ready", id: "publish_ready"},
        {instance: "this", name: "onStop", id: "publish_onstop"},
        {instance: "this", name: "error", id: "publish_error"},
        {instance: "this", name: "stop", id: "publish_stop"},
        {instance: "this", name: "connection", id: "publish_connection"}
      ],
      "Meteor.subscribe"
    ],

    {name: "Methods", id: "methods_header"}, [
      "Meteor.methods", [
        {instance: "this", name: "userId", id: "method_userId"},
        {instance: "this", name: "setUserId", id: "method_setUserId"},
        {instance: "this", name: "isSimulation", id: "method_issimulation"},
        {instance: "this", name: "unblock", id: "method_unblock"},
        {instance: "this", name: "connection", id: "method_connection"}
      ],
      "Meteor.Error",
      "Meteor.call",
      "Meteor.apply"
    ],

    {name: "Check", id: "check_package"}, [
      "check",
      "Match.test",
      {name: "Match patterns", style: "noncode"}
    ],

    {name: "Server connections", id: "connections"}, [
      "Meteor.status",
      "Meteor.reconnect",
      "Meteor.disconnect",
      "Meteor.onConnection",
      "DDP.connect"
    ],

    {name: "Collections", id: "collections"}, [
      "Mongo.Collection", [
        {instance: "collection", name: "find"},
        {instance: "collection", name: "findOne"},
        {instance: "collection", name: "insert"},
        {instance: "collection", name: "update"},
        {instance: "collection", name: "upsert"},
        {instance: "collection", name: "remove"},
        {instance: "collection", name: "allow"},
        {instance: "collection", name: "deny"}
      ],

      "Mongo.Cursor", [
        {instance: "cursor", name: "forEach"},
        {instance: "cursor", name: "map"},
        {instance: "cursor", name: "fetch"},
        {instance: "cursor", name: "count"},
        {instance: "cursor", name: "observe"},
        {instance: "cursor", name: "observeChanges", id: "observe_changes"}
      ],
      {type: "spacer"},
      {name: "Mongo.ObjectID", id: "mongo_object_id"},
      {type: "spacer"},
      {name: "Selectors", style: "noncode"},
      {name: "Modifiers", style: "noncode"},
      {name: "Sort specifiers", style: "noncode"},
      {name: "Field specifiers", style: "noncode"}
    ],

    "Session", [
      "Session.set",
      {name: "Session.setDefault", id: "session_set_default"},
      "Session.get",
      "Session.equals"
    ],

    {name: "Accounts", id: "accounts_api"}, [
      "Meteor.user",
      "Meteor.userId",
      "Meteor.users",
      "Meteor.loggingIn",
      "Meteor.logout",
      "Meteor.logoutOtherClients",
      "Meteor.loginWithPassword",
      {name: "Meteor.loginWith<Service>", id: "meteor_loginwithexternalservice"},
      {type: "spacer"},

      {name: "{{currentUser}}", id: "template_currentuser"},
      {name: "{{loggingIn}}", id: "template_loggingin"},
      {type: "spacer"},

      "Accounts.config",
      "Accounts.ui.config",
      "Accounts.validateNewUser",
      "Accounts.onCreateUser",
      "Accounts.validateLoginAttempt",
      "Accounts.onLogin",
      "Accounts.onLoginFailure"
    ],

    {name: "Passwords", id: "accounts_passwords"}, [
      "Accounts.createUser",
      "Accounts.changePassword",
      "Accounts.forgotPassword",
      "Accounts.resetPassword",
      "Accounts.setPassword",
      "Accounts.verifyEmail",
      {type: "spacer"},

      "Accounts.sendResetPasswordEmail",
      "Accounts.sendEnrollmentEmail",
      "Accounts.sendVerificationEmail",
      {type: "spacer"},

      {name: "Accounts.onResetPasswordLink", id: "Accounts-onResetPasswordLink"},
      {name: "Accounts.onEnrollmentLink", id: "Accounts-onEnrollmentLink"},
      {name: "Accounts.onEmailVerificationLink", id: "Accounts-onEmailVerificationLink"},
      {type: "spacer"},

      "Accounts.emailTemplates"
    ],

    {name: "Templates", id: "templates_api"}, [
      {prefix: "Template", instance: "myTemplate", id: "templates_api"}, [
        {name: "events", id: "template_events"},
        {name: "helpers", id: "template_helpers"},
        {name: "onRendered", id: "template_onRendered"},
        {name: "onCreated", id: "template_onCreated"},
        {name: "onDestroyed", id: "template_onDestroyed"}
      ],
      {name: "Template instances", id: "template_inst"}, [
        {instance: "template", name: "findAll", id: "template_findAll"},
        {instance: "template", name: "$", id: "template_$"},
        {instance: "template", name: "find", id: "template_find"},
        {instance: "template", name: "firstNode", id: "template_firstNode"},
        {instance: "template", name: "lastNode", id: "template_lastNode"},
        {instance: "template", name: "data", id: "template_data"},
        {instance: "template", name: "autorun", id: "template_autorun"},
        {instance: "template", name: "subscribe", id: "Blaze-TemplateInstance-subscribe"},
        {instance: "template", name: "view", id: "template_view"}
      ],
      "Template.registerHelper",
      "Template.instance",
      "Template.currentData",
      "Template.parentData",
      "Template.body",
      {name: "{{> Template.dynamic}}", id: "template_dynamic"},
      {type: "spacer"},
      {name: "Event maps", style: "noncode"}
    ],
    "Blaze", [
      "Blaze.render",
      "Blaze.renderWithData",
      "Blaze.remove",
      "Blaze.getData",
      "Blaze.toHTML",
      "Blaze.toHTMLWithData",
      "Blaze.View", [
        "Blaze.currentView",
        "Blaze.getView",
        "Blaze.With",
        "Blaze.If",
        "Blaze.Unless",
        "Blaze.Each"
      ],
      "Blaze.Template",
      "Blaze.isTemplate",
      {type: "spacer"},
      {name: "Renderable content", id: "renderable_content", style: "noncode"}
     ],

    "Timers", [
      "Meteor.setTimeout",
      "Meteor.setInterval",
      "Meteor.clearTimeout",
      "Meteor.clearInterval"
    ],

    "Tracker", [
      "Tracker.autorun",
      "Tracker.flush",
      "Tracker.nonreactive",
      "Tracker.active",
      "Tracker.currentComputation",
      "Tracker.onInvalidate",
      "Tracker.afterFlush",
      "Tracker.Computation", [
        {instance: "computation", name: "stop", id: "computation_stop"},
        {instance: "computation", name: "invalidate", id: "computation_invalidate"},
        {instance: "computation", name: "onInvalidate", id: "computation_oninvalidate"},
        {instance: "computation", name: "stopped", id: "computation_stopped"},
        {instance: "computation", name: "invalidated", id: "computation_invalidated"},
        {instance: "computation", name: "firstRun", id: "computation_firstrun"}
      ],
      "Tracker.Dependency", [
        {instance: "dependency", name: "changed", id: "dependency_changed"},
        {instance: "dependency", name: "depend", id: "dependency_depend"},
        {instance: "dependency", name: "hasDependents", id: "dependency_hasdependents"}
      ]
    ],

    {name: "ReactiveVar", id: "reactivevar_pkg"}, [
      "ReactiveVar",
      {instance: "reactiveVar", name: "get", id: "reactivevar_get"},
      {instance: "reactiveVar", name: "set", id: "reactivevar_set"}
    ],

    // "Environment Variables", [
    //   "Meteor.EnvironmentVariable", [
    //     {instance: "env_var", name: "get", id: "env_var_get"},
    //     {instance: "env_var", name: "withValue", id: "env_var_withvalue"},
    //     {instance: "env_var", name: "bindEnvironment", id: "env_var_bindenvironment"}
    //   ]
    //],

    {name: "EJSON", id: "ejson"}, [
      {name: "EJSON.parse", id: "ejson_parse"},
      {name: "EJSON.stringify", id: "ejson_stringify"},
      {name: "EJSON.fromJSONValue", id: "ejson_from_json_value"},
      {name: "EJSON.toJSONValue", id: "ejson_to_json_value"},
      {name: "EJSON.equals", id: "ejson_equals"},
      {name: "EJSON.clone", id: "ejson_clone"},
      {name: "EJSON.newBinary", id: "ejson_new_binary"},
      {name: "EJSON.isBinary", id: "ejson_is_binary"},
      {name: "EJSON.addType", id: "ejson_add_type"},
      [
        {instance: "customType", id: "ejson_type_typeName", name: "typeName"},
        {instance: "customType", id: "ejson_type_toJSONValue", name: "toJSONValue"},
        {instance: "customType", id: "ejson_type_clone", name: "clone"},
        {instance: "customType", id: "ejson_type_equals", name: "equals"}
      ]
    ],

    "HTTP", [
      "HTTP.call",
      {name: "HTTP.get"},
      {name: "HTTP.post"},
      {name: "HTTP.put"},
      {name: "HTTP.del"}
    ],
    "Email", [
      "Email.send"
    ],
    {name: "Assets", id: "assets"}, [
      {name: "Assets.getText", id: "assets_getText"},
      {name: "Assets.getBinary", id: "assets_getBinary"}
    ],

    {name: "package.js", id: "packagejs"}, [
      {name: "Package.describe", id: "packagedescription"},
      {name: "Package.onUse", id: "packagedefinition"}, [
        {name: "api.versionsFrom", id: "pack_versions"},
        {name: "api.use", id: "pack_use"},
        {name: "api.imply", id: "pack_api_imply"},
        {name: "api.export", id: "pack_export"},
        {name: "api.addFiles", id: "pack_addFiles"}
      ],
      {name: "Package.onTest", id: "packagetests"},
      {name: "Npm.depends", id: "Npm-depends"},
      {name: "Npm.require", id: "Npm-require"},
      {name: "Cordova.depends", id: "Cordova-depends"},
      {name: "Package.registerBuildPlugin", id: "Package-registerBuildPlugin"}, [
        {name: "Plugin.registerSourceHandler", id: "Plugin-registerSourceHandler"}
      ]
    ],

    {name: "mobile-config.js", id: "mobileconfigjs"}, [
      {name: "App.info", id: "App-info"},
      {name: "App.setPreference", id: "App-setPreference"},
      {name: "App.accessRule", id: "App-accessRule"},
      {name: "App.configurePlugin", id: "App-configurePlugin"},
      {name: "App.icons", id: "App-icons"},
      {name: "App.launchScreens", id: "App-launchScreens"}
    ]
  ],

  "Packages", [ [
    "appcache",
    "accounts-ui",
    "audit-argument-checks",
    "coffeescript",
    "jquery",
    "less",
    "markdown",
    "oauth-encryption",
    "random",
    {name: "spiderable", link: "https://atmospherejs.com/meteor/spiderable"},
    "underscore",
    "webapp"
  ] ],

  "Command line", [ [
    "meteor help",
    "meteor run",
    "meteor create",
    "meteor deploy",
    "meteor logs",
    "meteor update",
    "meteor add",
    "meteor remove",
    "meteor list",
    "meteor mongo",
    "meteor reset",
    "meteor build",
    "meteor search",
    "meteor show",
    "meteor publish",
    "meteor publish-for-arch",
    "meteor publish-release",
    "meteor test-packages",
    "meteor admin"
  ] ]
];

var name_to_id = function (name) {
  var x = name.toLowerCase().replace(/[^a-z0-9_,.]/g, '').replace(/[,.]/g, '_');
  return x;
};

Template.nav.helpers({
  sections: function () {
    var ret = [];
    var walk = function (items, depth) {
      _.each(items, function (item) {
        // Work around (eg) accidental trailing commas leading to spurious holes
        // in IE8.
        if (!item)
          return;
        if (item instanceof Array)
          walk(item, depth + 1);
        else {
          if (typeof(item) === "string")
            item = {name: item};

          var id = item.id || (item.name && name_to_id(item.name)) || "";

          ret.push(_.extend({
            type: "section",
            link: "#/full/" + id,
            depth: depth,
            style: ''
          }, item));
        }
      });
    };

    walk(toc, 1);
    return ret;
  },

  type: function (what) {
    return this.type === what;
  },

  maybe_current: function () {
    return Session.get('urlHash').split('/')[2] === this.id ? 'current' : '';
  }
});

Template.nav_section.helpers({
  depthIs: function (n) {
    return this.depth === n;
  }
});
<|endoftext|>