<commit_before>'use strict'

/**
 * Dependencies
 * @ignore
 */
const {spawn} = require('child_process')
const KeyPair = require('./KeyPair')

/**
 * ECKeyPair
 *
 * @class
 * ECKeyPair represents an Elliptic Curve cryptographic keypair in memory.
 * It maintains both PEM and JWK representations.
 */
class ECKeyPair extends KeyPair {

  /**
   * Generate
   */
  static generate () {
    return new Promise((resolve, reject) => {
      let keypair = {}
      let ecparam = spawn('openssl', ['ecparam', '-name', 'secp256k1', '-genkey'])
      let ec = spawn('openssl', ['ec', '-pubout'])

      ecparam.stdout.on('data', (data) => {
        keypair.prv = data.toString('ascii')
        ec.stdin.write(data)
      })

      ec.stdout.on('data', (data) => {
        keypair.pub = data.toString('ascii')
      })

      ec.on('close', (code) => {
        resolve(new ECKeyPair(keypair))
      })
    })
  }

  /**
   * Constructor
   */
  constructor (data) {
    super(data)
    Object.assign(this, data)
  }

}

/**
 * Export
 */
module.exports = ECKeyPair
<commit_msg>refactor(ECKeyPair): inherit KeyPair constructor<commit_after>'use strict'

/**
 * Dependencies
 * @ignore
 */
const {spawn} = require('child_process')
const KeyPair = require('./KeyPair')

/**
 * ECKeyPair
 *
 * @class
 * ECKeyPair represents an Elliptic Curve cryptographic keypair in memory.
 * It maintains both PEM and JWK representations.
 */
class ECKeyPair extends KeyPair {

  /**
   * Generate
   */
  static generate () {
    return new Promise((resolve, reject) => {
      let keypair = {}
      let ecparam = spawn('openssl', ['ecparam', '-name', 'secp256k1', '-genkey'])
      let ec = spawn('openssl', ['ec', '-pubout'])

      // store private key pem on the keypair
      // and pipe stdout to the public key process
      ecparam.stdout.on('data', (data) => {
        keypair.prv = data.toString('ascii')
        ec.stdin.write(data)
      })

      // store public key pem on the keypair
      ec.stdout.on('data', (data) => {
        keypair.pub = data.toString('ascii')
      })

      // cast the keypair to ECKeyPair
      // and resolve the promise
      ec.on('close', (code) => {
        resolve(new ECKeyPair(keypair))
      })
    })
  }
}

/**
 * Export
 */
module.exports = ECKeyPair
<|endoftext|>


<commit_before>import React from 'react';
import Icon from '@economist/component-icon';
import StickyPosition from 'react-sticky-position';
import AutoHide from './autohide';
import Button from '@economist/component-link-button';
import GoogleSearch from '@economist/component-google-search';
import Balloon from '@economist/component-balloon';
import SectionsCard from '@economist/component-sections-card';
import context from '@economist/component-sections-card/context';
import Accordion from '@economist/component-accordion';
const accordionContext = [
  {
    title: 'Sections',
    href: 'http://www.economist.com/sections',
    children: context.sections,
  },
  {
    title: 'Blogs',
    href: 'http://www.economist.com/blogs',
    children: context.blogs,
  },
  ...context.media,
  {
    title: 'Print Edition',
    href: 'http://www.economist.com/printedition/',
  },
  {
    title: 'Products',
    href: 'http://www.economist.com/digital',
  },
];
export default class Navigation extends React.Component {

  static get propTypes() {
    return {
      className: React.PropTypes.string,
      children: React.PropTypes.oneOfType([
        React.PropTypes.arrayOf(React.PropTypes.element),
        React.PropTypes.element,
      ]),
      links: React.PropTypes.arrayOf(React.PropTypes.object),
      autohide: React.PropTypes.bool,
      svgUri: React.PropTypes.string,
    };
  }

  static get defaultProps() {
    return {
      autohide: true,
    };
  }

  render() {
    const svgUri = { uri: this.props.svgUri } || {};
    const primaryNavigation = (

            <Icon icon="economist" size="64px" {...svgUri}/>

          <Balloon
            className="navigation__main-navigation-link navigation__mobile-accordion"
          >

              <Icon icon="hamburger" size="28px" color="white" />
              <Icon icon="close" size="28px" color="white" />

            <Accordion list={accordionContext}/>
          </Balloon>
          <Balloon className="navigation__main-navigation-link navigation__main-sections-card">

              Sections<Icon icon="down" size="28px" color="white" />

              <SectionsCard data={context} />

          </Balloon>

            Print edition

            Products

            <Balloon>
              <Button
                href="https://www.economist.com/user/login"
                className="navigation__user-menu-link"
                icon={{ icon: 'user', size: '28px' }}
                unstyled
              >Log in</Button>

                <Button
                  shadow
                  href="https://www.economist.com/user/login"
                  className="navigation__user-menu-log-in-button"
                >
                  Log in to The Economist
                </Button>

                  New to The Economist?
                  Register now

            </Balloon>

            <GoogleSearch/>

    );
    const children = [ primaryNavigation ];
    let autohide = '';
    let bottomBar = '';
    if (this.props.autohide) {
      autohide = ' navigation--autohide';
      bottomBar = (<AutoHide className="navigation__secondary" key="secondary-autohide">
          {this.props.children}
        </AutoHide>);
    } else {
      bottomBar = (

          {this.props.children}

);
    }
    children.push(bottomBar);
    return (
      <StickyPosition className={`${this.props.className} ${autohide}`}>
         {children}
      </StickyPosition>
    );
  }
}
<commit_msg>Removed unwanted attributes<commit_after>import React from 'react';
import Icon from '@economist/component-icon';
import StickyPosition from 'react-sticky-position';
import AutoHide from './autohide';
import Button from '@economist/component-link-button';
import GoogleSearch from '@economist/component-google-search';
import Balloon from '@economist/component-balloon';
import SectionsCard from '@economist/component-sections-card';
import context from '@economist/component-sections-card/context';
import Accordion from '@economist/component-accordion';
const accordionContext = [
  {
    title: 'Sections',
    href: 'http://www.economist.com/sections',
    children: context.sections,
  },
  {
    title: 'Blogs',
    href: 'http://www.economist.com/blogs',
    children: context.blogs,
  },
  ...context.media,
  {
    title: 'Print Edition',
    href: 'http://www.economist.com/printedition/',
  },
  {
    title: 'Products',
    href: 'http://www.economist.com/digital',
  },
];
export default class Navigation extends React.Component {

  static get propTypes() {
    return {
      className: React.PropTypes.string,
      children: React.PropTypes.oneOfType([
        React.PropTypes.arrayOf(React.PropTypes.element),
        React.PropTypes.element,
      ]),
      links: React.PropTypes.arrayOf(React.PropTypes.object),
      autohide: React.PropTypes.bool,
      svgUri: React.PropTypes.string,
    };
  }

  static get defaultProps() {
    return {
      autohide: true,
    };
  }

  render() {
    const svgUri = { uri: this.props.svgUri } || {};
    const primaryNavigation = (

            <Icon icon="economist" size="64px" {...svgUri}/>

          <Balloon
            className="navigation__main-navigation-link navigation__mobile-accordion"
          >

              <Icon icon="hamburger" size="28px" color="white" />
              <Icon icon="close" size="28px" color="white" />

            <Accordion list={accordionContext}/>
          </Balloon>
          <Balloon className="navigation__main-navigation-link navigation__main-sections-card">

              Sections<Icon icon="down" size="28px" color="white" />

              <SectionsCard data={context} />

          </Balloon>

            Print edition

            Products

            <Balloon>
              <Button
                href="https://www.economist.com/user/login"
                className="navigation__user-menu-link"
                icon={{ icon: 'user', size: '28px' }}
                unstyled
              >Log in</Button>

                <Button
                  shadow
                  href="https://www.economist.com/user/login"
                  className="navigation__user-menu-log-in-button"
                >
                  Log in to The Economist
                </Button>

                  New to The Economist?
                  Register now

            </Balloon>

            <GoogleSearch/>

    );
    const children = [ primaryNavigation ];
    let autohide = '';
    let bottomBar = '';
    if (this.props.autohide) {
      autohide = ' navigation--autohide';
      bottomBar = (<AutoHide className="navigation__secondary" key="secondary-autohide">
          {this.props.children}
        </AutoHide>);
    } else {
      bottomBar = (

          {this.props.children}

);
    }
    children.push(bottomBar);
    return (
      <StickyPosition className={`${this.props.className} ${autohide}`}>
         {children}
      </StickyPosition>
    );
  }
}
<|endoftext|>


<commit_before>'use strict';

angular.module('<%=angularAppName%>')
    .controller('AuditsController', function ($scope, $filter, AuditsService) {
        $scope.onChangeDate = function () {
            var dateFormat = 'yyyy-MM-dd';
            var fromDate = $filter('date')($scope.fromDate, dateFormat);
            var toDate = $filter('date')($scope.toDate, dateFormat);

            AuditsService.findByDates(fromDate, toDate).then(function (data) {
                $scope.audits = data;
            });
        };

        // Date picker configuration
        $scope.today = function () {
            // Today + 1 day - needed if the current day must be included
            var today = new Date();
            $scope.toDate = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1);
        };

        $scope.previousMonth = function () {
            var fromDate = new Date();
            if (fromDate.getMonth() === 0) {
                fromDate = new Date(fromDate.getFullYear() - 1, 0, fromDate.getDate());
            } else {
                fromDate = new Date(fromDate.getFullYear(), fromDate.getMonth() - 1, fromDate.getDate());
            }

            $scope.fromDate = fromDate;
        };

        $scope.today();
        $scope.previousMonth();
        $scope.onChangeDate();
    });
<commit_msg>return the correct date from the previousMonth function during January<commit_after>'use strict';

angular.module('<%=angularAppName%>')
    .controller('AuditsController', function ($scope, $filter, AuditsService) {
        $scope.onChangeDate = function () {
            var dateFormat = 'yyyy-MM-dd';
            var fromDate = $filter('date')($scope.fromDate, dateFormat);
            var toDate = $filter('date')($scope.toDate, dateFormat);

            AuditsService.findByDates(fromDate, toDate).then(function (data) {
                $scope.audits = data;
            });
        };

        // Date picker configuration
        $scope.today = function () {
            // Today + 1 day - needed if the current day must be included
            var today = new Date();
            $scope.toDate = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1);
        };

        $scope.previousMonth = function () {
            var fromDate = new Date();
            if (fromDate.getMonth() === 0) {
                fromDate = new Date(fromDate.getFullYear() - 1, 11, fromDate.getDate());
            } else {
                fromDate = new Date(fromDate.getFullYear(), fromDate.getMonth() - 1, fromDate.getDate());
            }

            $scope.fromDate = fromDate;
        };

        $scope.today();
        $scope.previousMonth();
        $scope.onChangeDate();
    });
<|endoftext|>


<commit_before>/*
Language: Ruby
Author: Anton Kovalyov <anton@kovalyov.net>
Contributors: Peter Leonov <gojpeg@yandex.ru>
*/

hljs.LANGUAGES.ruby = function(){
  var RUBY_IDENT_RE = '[a-zA-Z_][a-zA-Z0-9_]*(\\!|\\?)?';
  var RUBY_DEFAULT_CONTAINS = ['comment', 'string', 'char', 'class', 'function', 'symbol', 'number', 'variable', 'regexp_container']
  var RUBY_KEYWORDS = {
    'keyword': {'and': 1, 'false': 1, 'then': 1, 'defined': 1, 'module': 1, 'in': 1, 'return': 1, 'redo': 1, 'if': 1, 'BEGIN': 1, 'retry': 1, 'end': 1, 'for': 1, 'true': 1, 'self': 1, 'when': 1, 'next': 1, 'until': 1, 'do': 1, 'begin': 1, 'unless': 1, 'END': 1, 'rescue': 1, 'nil': 1, 'else': 1, 'break': 1, 'undef': 1, 'not': 1, 'super': 1, 'class': 1, 'case': 1, 'require': 1, 'yield': 1, 'alias': 1, 'while': 1, 'ensure': 1, 'elsif': 1, 'or': 1, 'def': 1},
    'keymethods': {'__id__': 1, '__send__': 1, 'abort': 1, 'abs': 1, 'all?': 1, 'allocate': 1, 'ancestors': 1, 'any?': 1, 'arity': 1, 'assoc': 1, 'at': 1, 'at_exit': 1, 'autoload': 1, 'autoload?': 1, 'between?': 1, 'binding': 1, 'binmode': 1, 'block_given?': 1, 'call': 1, 'callcc': 1, 'caller': 1, 'capitalize': 1, 'capitalize!': 1, 'casecmp': 1, 'catch': 1, 'ceil': 1, 'center': 1, 'chomp': 1, 'chomp!': 1, 'chop': 1, 'chop!': 1, 'chr': 1, 'class': 1, 'class_eval': 1, 'class_variable_defined?': 1, 'class_variables': 1, 'clear': 1, 'clone': 1, 'close': 1, 'close_read': 1, 'close_write': 1, 'closed?': 1, 'coerce': 1, 'collect': 1, 'collect!': 1, 'compact': 1, 'compact!': 1, 'concat': 1, 'const_defined?': 1, 'const_get': 1, 'const_missing': 1, 'const_set': 1, 'constants': 1, 'count': 1, 'crypt': 1, 'default': 1, 'default_proc': 1, 'delete': 1, 'delete!': 1, 'delete_at': 1, 'delete_if': 1, 'detect': 1, 'display': 1, 'div': 1, 'divmod': 1, 'downcase': 1, 'downcase!': 1, 'downto': 1, 'dump': 1, 'dup': 1, 'each': 1, 'each_byte': 1, 'each_index': 1, 'each_key': 1, 'each_line': 1, 'each_pair': 1, 'each_value': 1, 'each_with_index': 1, 'empty?': 1, 'entries': 1, 'eof': 1, 'eof?': 1, 'eql?': 1, 'equal?': 1, 'eval': 1, 'exec': 1, 'exit': 1, 'exit!': 1, 'extend': 1, 'fail': 1, 'fcntl': 1, 'fetch': 1, 'fileno': 1, 'fill': 1, 'find': 1, 'find_all': 1, 'first': 1, 'flatten': 1, 'flatten!': 1, 'floor': 1, 'flush': 1, 'for_fd': 1, 'foreach': 1, 'fork': 1, 'format': 1, 'freeze': 1, 'frozen?': 1, 'fsync': 1, 'getc': 1, 'gets': 1, 'global_variables': 1, 'grep': 1, 'gsub': 1, 'gsub!': 1, 'has_key?': 1, 'has_value?': 1, 'hash': 1, 'hex': 1, 'id': 1, 'include?': 1, 'included_modules': 1, 'index': 1, 'indexes': 1, 'indices': 1, 'induced_from': 1, 'inject': 1, 'insert': 1, 'inspect': 1, 'instance_eval': 1, 'instance_method': 1, 'instance_methods': 1, 'instance_of?': 1, 'instance_variable_defined?': 1, 'instance_variable_get': 1, 'instance_variable_set': 1, 'instance_variables': 1, 'integer?': 1, 'intern': 1, 'invert': 1, 'ioctl': 1, 'is_a?': 1, 'isatty': 1, 'iterator?': 1, 'join': 1, 'key?': 1, 'keys': 1, 'kind_of?': 1, 'lambda': 1, 'last': 1, 'length': 1, 'lineno': 1, 'ljust': 1, 'load': 1, 'local_variables': 1, 'loop': 1, 'lstrip': 1, 'lstrip!': 1, 'map': 1, 'map!': 1, 'match': 1, 'max': 1, 'member?': 1, 'merge': 1, 'merge!': 1, 'method': 1, 'method_defined?': 1, 'method_missing': 1, 'methods': 1, 'min': 1, 'module_eval': 1, 'modulo': 1, 'name': 1, 'nesting': 1, 'new': 1, 'next': 1, 'next!': 1, 'nil?': 1, 'nitems': 1, 'nonzero?': 1, 'object_id': 1, 'oct': 1, 'open': 1, 'pack': 1, 'partition': 1, 'pid': 1, 'pipe': 1, 'pop': 1, 'popen': 1, 'pos': 1, 'prec': 1, 'prec_f': 1, 'prec_i': 1, 'print': 1, 'printf': 1, 'private_class_method': 1, 'private_instance_methods': 1, 'private_method_defined?': 1, 'private_methods': 1, 'proc': 1, 'protected_instance_methods': 1, 'protected_method_defined?': 1, 'protected_methods': 1, 'public_class_method': 1, 'public_instance_methods': 1, 'public_method_defined?': 1, 'public_methods': 1, 'push': 1, 'putc': 1, 'puts': 1, 'quo': 1, 'raise': 1, 'rand': 1, 'rassoc': 1, 'read': 1, 'read_nonblock': 1, 'readchar': 1, 'readline': 1, 'readlines': 1, 'readpartial': 1, 'rehash': 1, 'reject': 1, 'reject!': 1, 'remainder': 1, 'reopen': 1, 'replace': 1, 'require': 1, 'respond_to?': 1, 'reverse': 1, 'reverse!': 1, 'reverse_each': 1, 'rewind': 1, 'rindex': 1, 'rjust': 1, 'round': 1, 'rstrip': 1, 'rstrip!': 1, 'scan': 1, 'seek': 1, 'select': 1, 'send': 1, 'set_trace_func': 1, 'shift': 1, 'singleton_method_added': 1, 'singleton_methods': 1, 'size': 1, 'sleep': 1, 'slice': 1, 'slice!': 1, 'sort': 1, 'sort!': 1, 'sort_by': 1, 'split': 1, 'sprintf': 1, 'squeeze': 1, 'squeeze!': 1, 'srand': 1, 'stat': 1, 'step': 1, 'store': 1, 'strip': 1, 'strip!': 1, 'sub': 1, 'sub!': 1, 'succ': 1, 'succ!': 1, 'sum': 1, 'superclass': 1, 'swapcase': 1, 'swapcase!': 1, 'sync': 1, 'syscall': 1, 'sysopen': 1, 'sysread': 1, 'sysseek': 1, 'system': 1, 'syswrite': 1, 'taint': 1, 'tainted?': 1, 'tell': 1, 'test': 1, 'throw': 1, 'times': 1, 'to_a': 1, 'to_ary': 1, 'to_f': 1, 'to_hash': 1, 'to_i': 1, 'to_int': 1, 'to_io': 1, 'to_proc': 1, 'to_s': 1, 'to_str': 1, 'to_sym': 1, 'tr': 1, 'tr!': 1, 'tr_s': 1, 'tr_s!': 1, 'trace_var': 1, 'transpose': 1, 'trap': 1, 'truncate': 1, 'tty?': 1, 'type': 1, 'ungetc': 1, 'uniq': 1, 'uniq!': 1, 'unpack': 1, 'unshift': 1, 'untaint': 1, 'untrace_var': 1, 'upcase': 1, 'upcase!': 1, 'update': 1, 'upto': 1, 'value?': 1, 'values': 1, 'values_at': 1, 'warn': 1, 'write': 1, 'write_nonblock': 1, 'zero?': 1, 'zip': 1}
  }
  return {
    defaultMode: {
      lexems: [RUBY_IDENT_RE],
      contains: RUBY_DEFAULT_CONTAINS,
      keywords: RUBY_KEYWORDS
    },
    modes: [
      hljs.HASH_COMMENT_MODE,
      {
        className: 'comment',
        begin: '^\\=begin', end: '^\\=end',
        relevance: 10
      },
      {
        className: 'comment',
        begin: '^__END__', end: '\\n$'
      },
      {
        className: 'params',
        begin: '\\(', end: '\\)',
        lexems: [RUBY_IDENT_RE],
        keywords: RUBY_KEYWORDS,
        contains: RUBY_DEFAULT_CONTAINS
      },
      {
        className: 'function',
        begin: '\\bdef\\b', end: '$|;',
        lexems: [RUBY_IDENT_RE],
        keywords: RUBY_KEYWORDS,
        contains: ['title', 'params', 'comment']
      },
      {
        className: 'class',
        begin: '\\b(class|module)\\b', end: '$',
        lexems: [hljs.UNDERSCORE_IDENT_RE],
        keywords: RUBY_KEYWORDS,
        contains: ['title', 'inheritance', 'comment'],
        keywords: {'class': 1, 'module': 1}
      },
      {
        className: 'title',
        begin: '[A-Za-z_]\\w*(::\\w+)*(\\?|\\!)?', end: '^',
        relevance: 0
      },
      {
        className: 'inheritance',
        begin: '<\\s*', end: '^',
        contains: ['parent']
      },
      {
        className: 'parent',
        begin: '(' + hljs.IDENT_RE + '::)?' + hljs.IDENT_RE, end: '^'
      },
      {
        className: 'number',
        begin: '(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b', end: '^',
        relevance: 0
      },
      {
        className: 'number',
        begin: '\\?\\w', end: '^'
      },
      {
        className: 'string',
        begin: '\'', end: '\'',
        contains: ['escape', 'subst'],
        relevance: 0
      },
      {
        className: 'string',
        begin: '"', end: '"',
        contains: ['escape', 'subst'],
        relevance: 0
      },
      {
        className: 'string',
        begin: '%[qw]?\\(', end: '\\)',
        contains: ['escape', 'subst'],
        relevance: 10
      },
      {
        className: 'string',
        begin: '%[qw]?\\[', end: '\\]',
        contains: ['escape', 'subst'],
        relevance: 10
      },
      {
        className: 'string',
        begin: '%[qw]?{', end: '}',
        contains: ['escape', 'subst'],
        relevance: 10
      },
      {
        className: 'string',
        begin: '%[qw]?<', end: '>',
        contains: ['escape', 'subst'],
        relevance: 10
      },
      {
        className: 'string',
        begin: '%[qw]?/', end: '/',
        contains: ['escape', 'subst'],
        relevance: 10
      },
      {
        className: 'string',
        begin: '%[qw]?%', end: '%',
        contains: ['escape', 'subst'],
        relevance: 10
      },
      {
        className: 'string',
        begin: '%[qw]?-', end: '-',
        contains: ['escape', 'subst'],
        relevance: 10
      },
      {
        className: 'string',
        begin: '%[qw]?\\|', end: '\\|',
        contains: ['escape', 'subst'],
        relevance: 10
      },
      {
        className: 'symbol',
        begin: ':' + RUBY_IDENT_RE, end: '^'
      },
      hljs.BACKSLASH_ESCAPE,
      {
        className: 'subst',
        begin: '#\\{', end: '}',
        lexems: [RUBY_IDENT_RE],
        keywords: RUBY_KEYWORDS,
        contains: RUBY_DEFAULT_CONTAINS
      },
      {
        className: 'regexp_container',
        begin: '(' + hljs.RE_STARTERS_RE + ')\\s*', end: '^', noMarkup: true,
        contains: ['comment', 'regexp'],
        relevance: 0
      },
      {
        className: 'regexp',
        begin: '/', end: '/[a-z]*',
        illegal: '\\n',
        contains: ['escape']
      },
      {
        className: 'variable',
        begin: '(\\$\\W)|((\\$|\\@\\@?)(\\w+))', end: '^'
      }
    ]
  };
}();
<commit_msg>ruby :"string" literals syntax, Module::Path::Is::Not::Symbol fix<commit_after>/*
Language: Ruby
Author: Anton Kovalyov <anton@kovalyov.net>
Contributors: Peter Leonov <gojpeg@yandex.ru>
*/

hljs.LANGUAGES.ruby = function(){
  var RUBY_IDENT_RE = '[a-zA-Z_][a-zA-Z0-9_]*(\\!|\\?)?';
  var RUBY_DEFAULT_CONTAINS = ['comment', 'string', 'char', 'class', 'function', 'module_name', 'symbol', 'number', 'variable', 'regexp_container']
  var RUBY_KEYWORDS = {
    'keyword': {'and': 1, 'false': 1, 'then': 1, 'defined': 1, 'module': 1, 'in': 1, 'return': 1, 'redo': 1, 'if': 1, 'BEGIN': 1, 'retry': 1, 'end': 1, 'for': 1, 'true': 1, 'self': 1, 'when': 1, 'next': 1, 'until': 1, 'do': 1, 'begin': 1, 'unless': 1, 'END': 1, 'rescue': 1, 'nil': 1, 'else': 1, 'break': 1, 'undef': 1, 'not': 1, 'super': 1, 'class': 1, 'case': 1, 'require': 1, 'yield': 1, 'alias': 1, 'while': 1, 'ensure': 1, 'elsif': 1, 'or': 1, 'def': 1},
    'keymethods': {'__id__': 1, '__send__': 1, 'abort': 1, 'abs': 1, 'all?': 1, 'allocate': 1, 'ancestors': 1, 'any?': 1, 'arity': 1, 'assoc': 1, 'at': 1, 'at_exit': 1, 'autoload': 1, 'autoload?': 1, 'between?': 1, 'binding': 1, 'binmode': 1, 'block_given?': 1, 'call': 1, 'callcc': 1, 'caller': 1, 'capitalize': 1, 'capitalize!': 1, 'casecmp': 1, 'catch': 1, 'ceil': 1, 'center': 1, 'chomp': 1, 'chomp!': 1, 'chop': 1, 'chop!': 1, 'chr': 1, 'class': 1, 'class_eval': 1, 'class_variable_defined?': 1, 'class_variables': 1, 'clear': 1, 'clone': 1, 'close': 1, 'close_read': 1, 'close_write': 1, 'closed?': 1, 'coerce': 1, 'collect': 1, 'collect!': 1, 'compact': 1, 'compact!': 1, 'concat': 1, 'const_defined?': 1, 'const_get': 1, 'const_missing': 1, 'const_set': 1, 'constants': 1, 'count': 1, 'crypt': 1, 'default': 1, 'default_proc': 1, 'delete': 1, 'delete!': 1, 'delete_at': 1, 'delete_if': 1, 'detect': 1, 'display': 1, 'div': 1, 'divmod': 1, 'downcase': 1, 'downcase!': 1, 'downto': 1, 'dump': 1, 'dup': 1, 'each': 1, 'each_byte': 1, 'each_index': 1, 'each_key': 1, 'each_line': 1, 'each_pair': 1, 'each_value': 1, 'each_with_index': 1, 'empty?': 1, 'entries': 1, 'eof': 1, 'eof?': 1, 'eql?': 1, 'equal?': 1, 'eval': 1, 'exec': 1, 'exit': 1, 'exit!': 1, 'extend': 1, 'fail': 1, 'fcntl': 1, 'fetch': 1, 'fileno': 1, 'fill': 1, 'find': 1, 'find_all': 1, 'first': 1, 'flatten': 1, 'flatten!': 1, 'floor': 1, 'flush': 1, 'for_fd': 1, 'foreach': 1, 'fork': 1, 'format': 1, 'freeze': 1, 'frozen?': 1, 'fsync': 1, 'getc': 1, 'gets': 1, 'global_variables': 1, 'grep': 1, 'gsub': 1, 'gsub!': 1, 'has_key?': 1, 'has_value?': 1, 'hash': 1, 'hex': 1, 'id': 1, 'include?': 1, 'included_modules': 1, 'index': 1, 'indexes': 1, 'indices': 1, 'induced_from': 1, 'inject': 1, 'insert': 1, 'inspect': 1, 'instance_eval': 1, 'instance_method': 1, 'instance_methods': 1, 'instance_of?': 1, 'instance_variable_defined?': 1, 'instance_variable_get': 1, 'instance_variable_set': 1, 'instance_variables': 1, 'integer?': 1, 'intern': 1, 'invert': 1, 'ioctl': 1, 'is_a?': 1, 'isatty': 1, 'iterator?': 1, 'join': 1, 'key?': 1, 'keys': 1, 'kind_of?': 1, 'lambda': 1, 'last': 1, 'length': 1, 'lineno': 1, 'ljust': 1, 'load': 1, 'local_variables': 1, 'loop': 1, 'lstrip': 1, 'lstrip!': 1, 'map': 1, 'map!': 1, 'match': 1, 'max': 1, 'member?': 1, 'merge': 1, 'merge!': 1, 'method': 1, 'method_defined?': 1, 'method_missing': 1, 'methods': 1, 'min': 1, 'module_eval': 1, 'modulo': 1, 'name': 1, 'nesting': 1, 'new': 1, 'next': 1, 'next!': 1, 'nil?': 1, 'nitems': 1, 'nonzero?': 1, 'object_id': 1, 'oct': 1, 'open': 1, 'pack': 1, 'partition': 1, 'pid': 1, 'pipe': 1, 'pop': 1, 'popen': 1, 'pos': 1, 'prec': 1, 'prec_f': 1, 'prec_i': 1, 'print': 1, 'printf': 1, 'private_class_method': 1, 'private_instance_methods': 1, 'private_method_defined?': 1, 'private_methods': 1, 'proc': 1, 'protected_instance_methods': 1, 'protected_method_defined?': 1, 'protected_methods': 1, 'public_class_method': 1, 'public_instance_methods': 1, 'public_method_defined?': 1, 'public_methods': 1, 'push': 1, 'putc': 1, 'puts': 1, 'quo': 1, 'raise': 1, 'rand': 1, 'rassoc': 1, 'read': 1, 'read_nonblock': 1, 'readchar': 1, 'readline': 1, 'readlines': 1, 'readpartial': 1, 'rehash': 1, 'reject': 1, 'reject!': 1, 'remainder': 1, 'reopen': 1, 'replace': 1, 'require': 1, 'respond_to?': 1, 'reverse': 1, 'reverse!': 1, 'reverse_each': 1, 'rewind': 1, 'rindex': 1, 'rjust': 1, 'round': 1, 'rstrip': 1, 'rstrip!': 1, 'scan': 1, 'seek': 1, 'select': 1, 'send': 1, 'set_trace_func': 1, 'shift': 1, 'singleton_method_added': 1, 'singleton_methods': 1, 'size': 1, 'sleep': 1, 'slice': 1, 'slice!': 1, 'sort': 1, 'sort!': 1, 'sort_by': 1, 'split': 1, 'sprintf': 1, 'squeeze': 1, 'squeeze!': 1, 'srand': 1, 'stat': 1, 'step': 1, 'store': 1, 'strip': 1, 'strip!': 1, 'sub': 1, 'sub!': 1, 'succ': 1, 'succ!': 1, 'sum': 1, 'superclass': 1, 'swapcase': 1, 'swapcase!': 1, 'sync': 1, 'syscall': 1, 'sysopen': 1, 'sysread': 1, 'sysseek': 1, 'system': 1, 'syswrite': 1, 'taint': 1, 'tainted?': 1, 'tell': 1, 'test': 1, 'throw': 1, 'times': 1, 'to_a': 1, 'to_ary': 1, 'to_f': 1, 'to_hash': 1, 'to_i': 1, 'to_int': 1, 'to_io': 1, 'to_proc': 1, 'to_s': 1, 'to_str': 1, 'to_sym': 1, 'tr': 1, 'tr!': 1, 'tr_s': 1, 'tr_s!': 1, 'trace_var': 1, 'transpose': 1, 'trap': 1, 'truncate': 1, 'tty?': 1, 'type': 1, 'ungetc': 1, 'uniq': 1, 'uniq!': 1, 'unpack': 1, 'unshift': 1, 'untaint': 1, 'untrace_var': 1, 'upcase': 1, 'upcase!': 1, 'update': 1, 'upto': 1, 'value?': 1, 'values': 1, 'values_at': 1, 'warn': 1, 'write': 1, 'write_nonblock': 1, 'zero?': 1, 'zip': 1}
  }
  return {
    defaultMode: {
      lexems: [RUBY_IDENT_RE],
      contains: RUBY_DEFAULT_CONTAINS,
      keywords: RUBY_KEYWORDS
    },
    modes: [
      hljs.HASH_COMMENT_MODE,
      {
        className: 'comment',
        begin: '^\\=begin', end: '^\\=end',
        relevance: 10
      },
      {
        className: 'comment',
        begin: '^__END__', end: '\\n$'
      },
      {
        className: 'params',
        begin: '\\(', end: '\\)',
        lexems: [RUBY_IDENT_RE],
        keywords: RUBY_KEYWORDS,
        contains: RUBY_DEFAULT_CONTAINS
      },
      {
        className: 'function',
        begin: '\\bdef\\b', end: '$|;',
        lexems: [RUBY_IDENT_RE],
        keywords: RUBY_KEYWORDS,
        contains: ['title', 'params', 'comment']
      },
      {
        className: 'class',
        begin: '\\b(class|module)\\b', end: '$',
        lexems: [hljs.UNDERSCORE_IDENT_RE],
        keywords: RUBY_KEYWORDS,
        contains: ['title', 'inheritance', 'comment'],
        keywords: {'class': 1, 'module': 1}
      },
      {
        className: 'title',
        begin: '[A-Za-z_]\\w*(::\\w+)*(\\?|\\!)?', end: '^',
        relevance: 0
      },
      {
        className: 'inheritance',
        begin: '<\\s*', end: '^',
        contains: ['parent']
      },
      {
        className: 'parent',
        begin: '(' + hljs.IDENT_RE + '::)?' + hljs.IDENT_RE, end: '^'
      },
      {
        className: 'number',
        begin: '(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b', end: '^',
        relevance: 0
      },
      {
        className: 'number',
        begin: '\\?\\w', end: '^'
      },
      {
        className: 'string',
        begin: '\'', end: '\'',
        contains: ['escape', 'subst'],
        relevance: 0
      },
      {
        className: 'string',
        begin: '"', end: '"',
        contains: ['escape', 'subst'],
        relevance: 0
      },
      {
        className: 'string',
        begin: '%[qw]?\\(', end: '\\)',
        contains: ['escape', 'subst'],
        relevance: 10
      },
      {
        className: 'string',
        begin: '%[qw]?\\[', end: '\\]',
        contains: ['escape', 'subst'],
        relevance: 10
      },
      {
        className: 'string',
        begin: '%[qw]?{', end: '}',
        contains: ['escape', 'subst'],
        relevance: 10
      },
      {
        className: 'string',
        begin: '%[qw]?<', end: '>',
        contains: ['escape', 'subst'],
        relevance: 10
      },
      {
        className: 'string',
        begin: '%[qw]?/', end: '/',
        contains: ['escape', 'subst'],
        relevance: 10
      },
      {
        className: 'string',
        begin: '%[qw]?%', end: '%',
        contains: ['escape', 'subst'],
        relevance: 10
      },
      {
        className: 'string',
        begin: '%[qw]?-', end: '-',
        contains: ['escape', 'subst'],
        relevance: 10
      },
      {
        className: 'string',
        begin: '%[qw]?\\|', end: '\\|',
        contains: ['escape', 'subst'],
        relevance: 10
      },
      {
        className: 'module_name',
        begin: ':{2}' + RUBY_IDENT_RE, end: '^',
        noMarkup: true
      },
      {
        className: 'symbol',
        begin: ':' + RUBY_IDENT_RE, end: '^'
      },
      {
        className: 'symbol',
        begin: ':', end: '^',
        contains: ['string']
      },
      hljs.BACKSLASH_ESCAPE,
      {
        className: 'subst',
        begin: '#\\{', end: '}',
        lexems: [RUBY_IDENT_RE],
        keywords: RUBY_KEYWORDS,
        contains: RUBY_DEFAULT_CONTAINS
      },
      {
        className: 'regexp_container',
        begin: '(' + hljs.RE_STARTERS_RE + ')\\s*', end: '^', noMarkup: true,
        contains: ['comment', 'regexp'],
        relevance: 0
      },
      {
        className: 'regexp',
        begin: '/', end: '/[a-z]*',
        illegal: '\\n',
        contains: ['escape']
      },
      {
        className: 'variable',
        begin: '(\\$\\W)|((\\$|\\@\\@?)(\\w+))', end: '^'
      }
    ]
  };
}();
<|endoftext|>


<commit_before>var https = require('https')

var app = {}

app.api = {
  hostname: 'pointhq.com',
  username: null,
  apitoken: null,
  timeout: 10000,
}

function validate(callback, params, list){
  for (key in list) {
    if (!(list[key] in params)){
      callback(new Error('param not found: ' + list[key]))
      return false
    }
  }
  return true
}

app.zones = {
  list: function(callback, params) {
    var query = ''
    if (typeof params !== 'undefined' && 'group' in params) {
      query = '?group=' + params['group']
    }
    app.call(200, 'GET', '/zones' + query, callback, {'list_escape': 'zone'})
  },
}

app.zone = {
  add: function(callback, fields) {
    app.call(201, 'POST', '/zones', callback, {'escape': 'zone', 'fields': {'zone': fields}})
  },
  update: function(callback, params, fields) {
    if (!(validate(callback, params, ['zone_id']))) {
       return
    }
    app.call(202, 'PUT', '/zones' + params['zone_id'], callback, {'escape': 'zone', 'fields': {'zone': fields}})
  },
  get: function(callback, params) {
    if (!(validate(callback, params, ['zone_id']))) {
       return
    }
    app.call(200, 'GET', '/zones/' + params['zone_id'], callback, {'escape': 'zone'})
  },
  del: function(callback, params) {
    if (!(validate(callback, params, ['zone_id']))) {
       return
    }
    app.call(202, 'DELETE', '/zones/' + params['zone_id'], callback, {'escape': 'zone'})
  },
}

app.records = {
  list: function(callback, params) {
    if (!(validate(callback, params, ['zone_id']))) {
       return
    }
    app.call(200, 'GET', '/zones/' + params['zone_id'] + '/records/', callback, {'list_escape': 'zone_record'})
  },
}

app.record = {
  add: function(callback, params, fields) { // zone_record
    if (!(validate(callback, params, ['zone_id']))) {
       return
    }
    app.call(201, 'POST', '/zones/' + params['zone_id'] + '/records', callback, { 'escape': 'zone_record', 'fields':{'zone_record': fields} })
  },
  update: function(callback, params, fields) {  // zone_record
    if (!(validate(callback, params, ['zone_id', 'record_id']))) {
       return
    }
    app.call(202, 'PUT', '/zones/' + params['zone_id'] + '/records' + params['record_id'], callback, { 'escape': 'zone_record', 'fields':{'zone_record': fields} })
  },
  get: function(callback, params) {  // zone_record
    if (!(validate(callback, params, ['zone_id', 'record_id']))) {
       return
    }
    app.call(200, 'GET', '/zones/' + params['zone_id'] + '/records/' + params['record_id'], callback, {'escape': 'zone_record'})
  },
  del: function(callback, params) {  //  zone_record
    if (!(validate(callback, params, ['zone_id', 'record_id']))) {
       return
    }
    app.call(202, 'DELETE', '/zones/' + params['zone_id'] + '/records' + params['record_id'], callback, {'escape': 'zone_record'})
  },
}

app.call = function(status, method, path, callback, data) {

  // credentials
  if( ! (app.api.username && app.api.apitoken) ) {
    callback( new Error('credentials missing') )
    return
  }

  var querystr = JSON.stringify(data['fields'])
  var auth = 'Basic ' + new Buffer(app.api.username + ':' + app.api.apitoken).toString('base64');
  var headers = {
    'Accept': 'application/json',
    'User-Agent': 'Nodejs-pointDNS',
    'Authorization': auth,
  }

  if( method.match( /(POST|PUT)/ ) ) {
    headers['Content-Type'] = 'application/json'
    headers['Content-Length'] = querystr.length
  }

  var options = {
    host: app.api.hostname,
    port: 443,
    path: path,
    method: method,
    headers: headers,
  }

  //request
  var req = https.request(options, function(res) {
    if (res.statusCode != status) {
      callback( new Error('http error') )
      return
    }

    res.on('data', function(d) {
      result = JSON.parse( d )
      if ('escape' in data) {
        result = result[data['escape']]
      } else if ('list_escape' in data) {
        tmp = []
        result.forEach(function(entry) {
          tmp.push(entry[data['list_escape']])
        })
        result = tmp
      }
      callback(null, result)
    });
  });

  // timeout
  req.on( 'socket', function( socket ) {
    if( app.api.timeout ) {
      socket.setTimeout( app.api.timeout )
      socket.on( 'timeout', function() {
        req.abort()
      })
    }
  })

  req.on('error', function(e) {
    console.error(e);
    callback(e)
    return
  });

  if( method.match( /(POST|PUT)/ ) ) {
    req.end( querystr )
  } else {
    req.end()
  }

}

module.exports = function( setup ) {
  for( var k in setup ) {
    app.api[ k ] = setup[ k ]
  }
  return app
}

<commit_msg>prevent errors on larger responses<commit_after>var https = require('https')

var app = {}

app.api = {
  hostname: 'pointhq.com',
  username: null,
  apitoken: null,
  timeout: 10000,
}

function validate(callback, params, list){
  for (key in list) {
    if (!(list[key] in params)){
      callback(new Error('param not found: ' + list[key]))
      return false
    }
  }
  return true
}

app.zones = {
  list: function(callback, params) {
    var query = ''
    if (typeof params !== 'undefined' && 'group' in params) {
      query = '?group=' + params['group']
    }
    app.call(200, 'GET', '/zones' + query, callback, {'list_escape': 'zone'})
  },
}

app.zone = {
  add: function(callback, fields) {
    app.call(201, 'POST', '/zones', callback, {'escape': 'zone', 'fields': {'zone': fields}})
  },
  update: function(callback, params, fields) {
    if (!(validate(callback, params, ['zone_id']))) {
       return
    }
    app.call(202, 'PUT', '/zones' + params['zone_id'], callback, {'escape': 'zone', 'fields': {'zone': fields}})
  },
  get: function(callback, params) {
    if (!(validate(callback, params, ['zone_id']))) {
       return
    }
    app.call(200, 'GET', '/zones/' + params['zone_id'], callback, {'escape': 'zone'})
  },
  del: function(callback, params) {
    if (!(validate(callback, params, ['zone_id']))) {
       return
    }
    app.call(202, 'DELETE', '/zones/' + params['zone_id'], callback, {'escape': 'zone'})
  },
}

app.records = {
  list: function(callback, params) {
    if (!(validate(callback, params, ['zone_id']))) {
       return
    }
    app.call(200, 'GET', '/zones/' + params['zone_id'] + '/records/', callback, {'list_escape': 'zone_record'})
  },
}

app.record = {
  add: function(callback, params, fields) { // zone_record
    if (!(validate(callback, params, ['zone_id']))) {
       return
    }
    app.call(201, 'POST', '/zones/' + params['zone_id'] + '/records', callback, { 'escape': 'zone_record', 'fields':{'zone_record': fields} })
  },
  update: function(callback, params, fields) {  // zone_record
    if (!(validate(callback, params, ['zone_id', 'record_id']))) {
       return
    }
    app.call(202, 'PUT', '/zones/' + params['zone_id'] + '/records' + params['record_id'], callback, { 'escape': 'zone_record', 'fields':{'zone_record': fields} })
  },
  get: function(callback, params) {  // zone_record
    if (!(validate(callback, params, ['zone_id', 'record_id']))) {
       return
    }
    app.call(200, 'GET', '/zones/' + params['zone_id'] + '/records/' + params['record_id'], callback, {'escape': 'zone_record'})
  },
  del: function(callback, params) {  //  zone_record
    if (!(validate(callback, params, ['zone_id', 'record_id']))) {
       return
    }
    app.call(202, 'DELETE', '/zones/' + params['zone_id'] + '/records' + params['record_id'], callback, {'escape': 'zone_record'})
  },
}

app.call = function(status, method, path, callback, data) {

  // credentials
  if( ! (app.api.username && app.api.apitoken) ) {
    callback( new Error('credentials missing') )
    return
  }

  var querystr = JSON.stringify(data['fields'])
  var auth = 'Basic ' + new Buffer(app.api.username + ':' + app.api.apitoken).toString('base64');
  var headers = {
    'Accept': 'application/json',
    'User-Agent': 'Nodejs-pointDNS',
    'Authorization': auth,
  }

  if( method.match( /(POST|PUT)/ ) ) {
    headers['Content-Type'] = 'application/json'
    headers['Content-Length'] = querystr.length
  }

  var options = {
    host: app.api.hostname,
    port: 443,
    path: path,
    method: method,
    headers: headers,
  }

  //request
  var req = https.request(options, function(res) {
    if (res.statusCode != status) {
      callback( new Error('http error') )
      return
    }
    var responseData = '';
    res.on('data', function(chunk) {
      responseData += chunk;
    });
    res.on('end', function(){
      result = JSON.parse( responseData )
      if ('escape' in data) {
        result = result[data['escape']]
      } else if ('list_escape' in data) {
        tmp = []
        result.forEach(function(entry) {
          tmp.push(entry[data['list_escape']])
        })
        result = tmp
      }
      req.end();
      callback(null, result)
    });
  });

  // timeout
  req.on( 'socket', function( socket ) {
    if( app.api.timeout ) {
      socket.setTimeout( app.api.timeout )
      socket.on( 'timeout', function() {
        req.abort()
      })
    }
  })

  req.on('error', function(e) {
    console.error(e);
    callback(e)
    return
  });

  if( method.match( /(POST|PUT)/ ) ) {
    req.end( querystr )
  } else {
    req.end()
  }

}

module.exports = function( setup ) {
  for( var k in setup ) {
    app.api[ k ] = setup[ k ]
  }
  return app
}
<|endoftext|>


<commit_before>/**
 * @class Random dungeon generator using human-like digging patterns.
 * Heavily based on Mike Anderson's ideas from the "Tyrant" algo, mentioned at
 * http://www.roguebasin.roguelikedevelopment.org/index.php?title=Dungeon-Building_Algorithm.
 * @augments ROT.Map.Dungeon
 */
ROT.Map.Digger = function(width, height, options) {
	ROT.Map.Dungeon.call(this, width, height);

	this._options = {
		roomWidth: [3, 9], /* room minimum and maximum width */
		roomHeight: [3, 5], /* room minimum and maximum height */
		corridorLength: [3, 10], /* corridor minimum and maximum length */
		dugPercentage: 0.2, /* we stop after this percentage of level area has been dug out */
		timeLimit: 1000 /* we stop after this much time has passed (msec) */
	}
	for (var p in options) { this._options[p] = options[p]; }

	this._features = {
		"Room": 4,
		"Corridor": 4
	}
	this._featureAttempts = 20; /* how many times do we try to create a feature on a suitable wall */
	this._walls = {}; /* these are available for digging */

	this._digCallback = this._digCallback.bind(this);
	this._canBeDugCallback = this._canBeDugCallback.bind(this);
	this._isWallCallback = this._isWallCallback.bind(this);
	this._priorityWallCallback = this._priorityWallCallback.bind(this);
}
ROT.Map.Digger.extend(ROT.Map.Dungeon);

/**
 * Create a map
 * @see ROT.Map#create
 */
ROT.Map.Digger.prototype.create = function(callback) {
	this._rooms = [];
	this._corridors = [];
	this._map = this._fillMap(1);
	this._walls = {};
	this._dug = 0;
	var area = (this._width-2) * (this._height-2);

	this._firstRoom();

	var t1 = Date.now();

	do {
		var t2 = Date.now();
		if (t2 - t1 > this._options.timeLimit) { break; }

		/* find a good wall */
		var wall = this._findWall();
		if (!wall) { break; } /* no more walls */

		var parts = wall.split(",");
		var x = parseInt(parts[0]);
		var y = parseInt(parts[1]);
		var dir = this._getDiggingDirection(x, y);
		if (!dir) { continue; } /* this wall is not suitable */

//		console.log("wall", x, y);

		/* try adding a feature */
		var featureAttempts = 0;
		do {
			featureAttempts++;
			if (this._tryFeature(x, y, dir[0], dir[1])) { /* feature added */
				//if (this._rooms.length + this._corridors.length == 2) { this._rooms[0].addDoor(x, y); } /* first room oficially has doors */
				this._removeSurroundingWalls(x, y);
				this._removeSurroundingWalls(x-dir[0], y-dir[1]);
				break;
			}
		} while (featureAttempts < this._featureAttempts);

		var priorityWalls = 0;
		for (var id in this._walls) {
			if (this._walls[id] > 1) { priorityWalls++; }
		}

	} while (this._dug/area < this._options.dugPercentage || priorityWalls); /* fixme number of priority walls */

	this._addDoors();

	if (callback) {
		for (var i=0;i<this._width;i++) {
			for (var j=0;j<this._height;j++) {
				callback(i, j, this._map[i][j]);
			}
		}
	}

	this._walls = {};
	this._map = null;

	return this;
}

ROT.Map.Digger.prototype._digCallback = function(x, y, value) {
	if (value == 0 || value == 2) { /* empty */
		this._map[x][y] = 0;
		this._dug++;
	} else { /* wall */
		this._walls[x+","+y] = 1;
	}
}

ROT.Map.Digger.prototype._isWallCallback = function(x, y) {
	if (x < 0 || y < 0 || x >= this._width || y >= this._height) { return false; }
	return (this._map[x][y] == 1);
}

ROT.Map.Digger.prototype._canBeDugCallback = function(x, y) {
	if (x < 1 || y < 1 || x+1 >= this._width || y+1 >= this._height) { return false; }
	return (this._map[x][y] == 1);
}

ROT.Map.Digger.prototype._priorityWallCallback = function(x, y) {
	this._walls[x+","+y] = 2;
}

ROT.Map.Digger.prototype._firstRoom = function() {
	var cx = Math.floor(this._width/2);
	var cy = Math.floor(this._height/2);
	var room = ROT.Map.Feature.Room.createRandomCenter(cx, cy, this._options);
	this._rooms.push(room);
	room.create(this._digCallback);
}

/**
 * Get a suitable wall
 */
ROT.Map.Digger.prototype._findWall = function() {
	var prio1 = [];
	var prio2 = [];
	for (var id in this._walls) {
		var prio = this._walls[id];
		if (prio == 2) {
			prio2.push(id);
		} else {
			prio1.push(id);
		}
	}

	var arr = (prio2.length ? prio2 : prio1);
	if (!arr.length) { return null; } /* no walls :/ */

	var id = arr.random();
	delete this._walls[id];

	return id;
}

/**
 * Tries adding a feature
 * @returns {bool} was this a successful try?
 */
ROT.Map.Digger.prototype._tryFeature = function(x, y, dx, dy) {
	var feature = ROT.RNG.getWeightedValue(this._features);
	feature = ROT.Map.Feature[feature].createRandomAt(x, y, dx, dy, this._options);

	if (!feature.isValid(this._isWallCallback, this._canBeDugCallback)) {
//		console.log("not valid");
//		feature.debug();
		return false;
	}

	feature.create(this._digCallback);
//	feature.debug();

	if (feature instanceof ROT.Map.Feature.Room) { this._rooms.push(feature); }
	if (feature instanceof ROT.Map.Feature.Corridor) {
		feature.createPriorityWalls(this._priorityWallCallback);
		this._corridors.push(feature);
	}

	return true;
}

ROT.Map.Digger.prototype._removeSurroundingWalls = function(cx, cy) {
	var deltas = ROT.DIRS[4];

	for (var i=0;i<deltas.length;i++) {
		var delta = deltas[i];
		var x = cx + delta[0];
		var y = cy + delta[1];
		delete this._walls[x+","+y];
		var x = cx + 2*delta[0];
		var y = cy + 2*delta[1];
		delete this._walls[x+","+y];
	}
}

/**
 * Returns vector in "digging" direction, or false, if this does not exist (or is not unique)
 */
ROT.Map.Digger.prototype._getDiggingDirection = function(cx, cy) {
	var result = null;
	var deltas = ROT.DIRS[4];

	for (var i=0;i<deltas.length;i++) {
		var delta = deltas[i];
		var x = cx + delta[0];
		var y = cy + delta[1];

		if (x < 0 || y < 0 || x >= this._width || y >= this._width) { return null; }

		if (!this._map[x][y]) { /* there already is another empty neighbor! */
			if (result) { return null; }
			result = delta;
		}
	}

	/* no empty neighbor */
	if (!result) { return null; }

	return [-result[0], -result[1]];
}

/**
 * Find empty spaces surrounding rooms, and apply doors.
 */
ROT.Map.Digger.prototype._addDoors = function() {
	var data = this._map;
	var isWallCallback = function(x, y) {
		return (data[x][y] == 1);
	}
	for (var i = 0; i < this._rooms.length; i++ ) {
		var room = this._rooms[i];
		room.clearDoors();
		room.addDoors(isWallCallback);
	}
}
<commit_msg>Logic fix in Map.Digger._getDiggingDirection.<commit_after>/**
 * @class Random dungeon generator using human-like digging patterns.
 * Heavily based on Mike Anderson's ideas from the "Tyrant" algo, mentioned at
 * http://www.roguebasin.roguelikedevelopment.org/index.php?title=Dungeon-Building_Algorithm.
 * @augments ROT.Map.Dungeon
 */
ROT.Map.Digger = function(width, height, options) {
	ROT.Map.Dungeon.call(this, width, height);

	this._options = {
		roomWidth: [3, 9], /* room minimum and maximum width */
		roomHeight: [3, 5], /* room minimum and maximum height */
		corridorLength: [3, 10], /* corridor minimum and maximum length */
		dugPercentage: 0.2, /* we stop after this percentage of level area has been dug out */
		timeLimit: 1000 /* we stop after this much time has passed (msec) */
	}
	for (var p in options) { this._options[p] = options[p]; }

	this._features = {
		"Room": 4,
		"Corridor": 4
	}
	this._featureAttempts = 20; /* how many times do we try to create a feature on a suitable wall */
	this._walls = {}; /* these are available for digging */

	this._digCallback = this._digCallback.bind(this);
	this._canBeDugCallback = this._canBeDugCallback.bind(this);
	this._isWallCallback = this._isWallCallback.bind(this);
	this._priorityWallCallback = this._priorityWallCallback.bind(this);
}
ROT.Map.Digger.extend(ROT.Map.Dungeon);

/**
 * Create a map
 * @see ROT.Map#create
 */
ROT.Map.Digger.prototype.create = function(callback) {
	this._rooms = [];
	this._corridors = [];
	this._map = this._fillMap(1);
	this._walls = {};
	this._dug = 0;
	var area = (this._width-2) * (this._height-2);

	this._firstRoom();

	var t1 = Date.now();

	do {
		var t2 = Date.now();
		if (t2 - t1 > this._options.timeLimit) { break; }

		/* find a good wall */
		var wall = this._findWall();
		if (!wall) { break; } /* no more walls */

		var parts = wall.split(",");
		var x = parseInt(parts[0]);
		var y = parseInt(parts[1]);
		var dir = this._getDiggingDirection(x, y);
		if (!dir) { continue; } /* this wall is not suitable */

//		console.log("wall", x, y);

		/* try adding a feature */
		var featureAttempts = 0;
		do {
			featureAttempts++;
			if (this._tryFeature(x, y, dir[0], dir[1])) { /* feature added */
				//if (this._rooms.length + this._corridors.length == 2) { this._rooms[0].addDoor(x, y); } /* first room oficially has doors */
				this._removeSurroundingWalls(x, y);
				this._removeSurroundingWalls(x-dir[0], y-dir[1]);
				break;
			}
		} while (featureAttempts < this._featureAttempts);

		var priorityWalls = 0;
		for (var id in this._walls) {
			if (this._walls[id] > 1) { priorityWalls++; }
		}

	} while (this._dug/area < this._options.dugPercentage || priorityWalls); /* fixme number of priority walls */

	this._addDoors();

	if (callback) {
		for (var i=0;i<this._width;i++) {
			for (var j=0;j<this._height;j++) {
				callback(i, j, this._map[i][j]);
			}
		}
	}

	this._walls = {};
	this._map = null;

	return this;
}

ROT.Map.Digger.prototype._digCallback = function(x, y, value) {
	if (value == 0 || value == 2) { /* empty */
		this._map[x][y] = 0;
		this._dug++;
	} else { /* wall */
		this._walls[x+","+y] = 1;
	}
}

ROT.Map.Digger.prototype._isWallCallback = function(x, y) {
	if (x < 0 || y < 0 || x >= this._width || y >= this._height) { return false; }
	return (this._map[x][y] == 1);
}

ROT.Map.Digger.prototype._canBeDugCallback = function(x, y) {
	if (x < 1 || y < 1 || x+1 >= this._width || y+1 >= this._height) { return false; }
	return (this._map[x][y] == 1);
}

ROT.Map.Digger.prototype._priorityWallCallback = function(x, y) {
	this._walls[x+","+y] = 2;
}

ROT.Map.Digger.prototype._firstRoom = function() {
	var cx = Math.floor(this._width/2);
	var cy = Math.floor(this._height/2);
	var room = ROT.Map.Feature.Room.createRandomCenter(cx, cy, this._options);
	this._rooms.push(room);
	room.create(this._digCallback);
}

/**
 * Get a suitable wall
 */
ROT.Map.Digger.prototype._findWall = function() {
	var prio1 = [];
	var prio2 = [];
	for (var id in this._walls) {
		var prio = this._walls[id];
		if (prio == 2) {
			prio2.push(id);
		} else {
			prio1.push(id);
		}
	}

	var arr = (prio2.length ? prio2 : prio1);
	if (!arr.length) { return null; } /* no walls :/ */

	var id = arr.random();
	delete this._walls[id];

	return id;
}

/**
 * Tries adding a feature
 * @returns {bool} was this a successful try?
 */
ROT.Map.Digger.prototype._tryFeature = function(x, y, dx, dy) {
	var feature = ROT.RNG.getWeightedValue(this._features);
	feature = ROT.Map.Feature[feature].createRandomAt(x, y, dx, dy, this._options);

	if (!feature.isValid(this._isWallCallback, this._canBeDugCallback)) {
//		console.log("not valid");
//		feature.debug();
		return false;
	}

	feature.create(this._digCallback);
//	feature.debug();

	if (feature instanceof ROT.Map.Feature.Room) { this._rooms.push(feature); }
	if (feature instanceof ROT.Map.Feature.Corridor) {
		feature.createPriorityWalls(this._priorityWallCallback);
		this._corridors.push(feature);
	}

	return true;
}

ROT.Map.Digger.prototype._removeSurroundingWalls = function(cx, cy) {
	var deltas = ROT.DIRS[4];

	for (var i=0;i<deltas.length;i++) {
		var delta = deltas[i];
		var x = cx + delta[0];
		var y = cy + delta[1];
		delete this._walls[x+","+y];
		var x = cx + 2*delta[0];
		var y = cy + 2*delta[1];
		delete this._walls[x+","+y];
	}
}

/**
 * Returns vector in "digging" direction, or false, if this does not exist (or is not unique)
 */
ROT.Map.Digger.prototype._getDiggingDirection = function(cx, cy) {
	if (cx <= 0 || cy <= 0 || cx >= this._width - 1 || cy >= this._height - 1) { return null; }

	var result = null;
	var deltas = ROT.DIRS[4];

	for (var i=0;i<deltas.length;i++) {
		var delta = deltas[i];
		var x = cx + delta[0];
		var y = cy + delta[1];

		if (!this._map[x][y]) { /* there already is another empty neighbor! */
			if (result) { return null; }
			result = delta;
		}
	}

	/* no empty neighbor */
	if (!result) { return null; }

	return [-result[0], -result[1]];
}

/**
 * Find empty spaces surrounding rooms, and apply doors.
 */
ROT.Map.Digger.prototype._addDoors = function() {
	var data = this._map;
	var isWallCallback = function(x, y) {
		return (data[x][y] == 1);
	}
	for (var i = 0; i < this._rooms.length; i++ ) {
		var room = this._rooms[i];
		room.clearDoors();
		room.addDoors(isWallCallback);
	}
}
<|endoftext|>


<commit_before>/*
Language: Haxe
Author: Christopher Kaster <ikasoki@gmail.com> (Based on the actionscript.js language file by Alexander Myadzel)
*/

function(hljs) {
  var IDENT_RE = '[a-zA-Z_$][a-zA-Z0-9_$]*';
  var IDENT_FUNC_RETURN_TYPE_RE = '([*]|[a-zA-Z_$][a-zA-Z0-9_$]*)';

  var HAXE_BASIC_TYPES = 'Int Float String Bool Dynamic Void Array ';

  return {
    aliases: ['hx'],
    keywords: {
      keyword: 'break callback case cast catch continue default do dynamic else enum extern ' +
               'for function here if import in inline never new override package private get set ' +
               'public return static super switch this throw trace try typedef untyped using var while ',
               HAXE_BASIC_TYPES,
      built_in:
        'trace this',
      literal:
        'true false null _',
    },
    contains: [
      { className: 'string', // interpolate-able strings
        begin: '\'', end: '\'',
        contains: [
          hljs.BACKSLASH_ESCAPE,
          { className: 'subst', // interpolation
            begin: '\\$\\{', end: '\\}'
          },
          { className: 'subst', // interpolation
            begin: '\\$', end: '\\W}'
          }
        ]
      },
      hljs.QUOTE_STRING_MODE,
      hljs.C_LINE_COMMENT_MODE,
      hljs.C_BLOCK_COMMENT_MODE,
      hljs.C_NUMBER_MODE,
      { className: 'meta', // compiler meta
        begin: '@:', end: '$'
      },
      { className: 'meta', // compiler conditionals
        begin: '#', end: '$',
        keywords: {'meta-keyword': 'if else elseif end error'}
      },
      { className: 'type', // function types
        begin: ':[ \t]*', end: '[^A-Za-z0-9_ \t\\->]',
        excludeBegin: true, excludeEnd: true,
      },
      { className: 'type', // types
        begin: ':[ \t]*', end: '\\W',
        excludeBegin: true, excludeEnd: true,
      },
      { className: 'type', // instantiation
        begin: 'new *', end: '\\W',
        excludeBegin: true, excludeEnd: true,
      },
      { className: 'class', // enums
        beginKeywords: 'enum', end: '\\{'
      },
      { className: 'class', // abstracts
        begin: 'abstract', end: '[\\{$]',
        contains: [
          { className: 'type',
            begin: '\\(', end: '\\)',
            excludeBegin: true, excludeEnd: true,
          },
          { className: 'type',
            begin: 'from *', end: '\\W',
            excludeBegin: true, excludeEnd: true,
          },
          { className: 'type',
            begin: 'to *', end: '\\W',
            excludeBegin: true, excludeEnd: true,
          }
        ],
        keywords: {
          keyword: 'abstract from to'
        }
      },
      { className: 'class', // classes
        beginKeywords: 'class interface', end: '{', excludeEnd: true,
        keywords: {
          keyword: 'class interface extends implements'
        }
      }
    ]
  };
}
<commit_msg>Added title modes to enums and abstracts<commit_after>/*
Language: Haxe
Author: Christopher Kaster <ikasoki@gmail.com> (Based on the actionscript.js language file by Alexander Myadzel)
*/

function(hljs) {
  var IDENT_RE = '[a-zA-Z_$][a-zA-Z0-9_$]*';
  var IDENT_FUNC_RETURN_TYPE_RE = '([*]|[a-zA-Z_$][a-zA-Z0-9_$]*)';

  var HAXE_BASIC_TYPES = 'Int Float String Bool Dynamic Void Array ';

  return {
    aliases: ['hx'],
    keywords: {
      keyword: 'break callback case cast catch continue default do dynamic else enum extern ' +
               'for function here if import in inline never new override package private get set ' +
               'public return static super switch this throw trace try typedef untyped using var while ',
               HAXE_BASIC_TYPES,
      built_in:
        'trace this',
      literal:
        'true false null _',
    },
    contains: [
      { className: 'string', // interpolate-able strings
        begin: '\'', end: '\'',
        contains: [
          hljs.BACKSLASH_ESCAPE,
          { className: 'subst', // interpolation
            begin: '\\$\\{', end: '\\}'
          },
          { className: 'subst', // interpolation
            begin: '\\$', end: '\\W}'
          }
        ]
      },
      hljs.QUOTE_STRING_MODE,
      hljs.C_LINE_COMMENT_MODE,
      hljs.C_BLOCK_COMMENT_MODE,
      hljs.C_NUMBER_MODE,
      { className: 'meta', // compiler meta
        begin: '@:', end: '$'
      },
      { className: 'meta', // compiler conditionals
        begin: '#', end: '$',
        keywords: {'meta-keyword': 'if else elseif end error'}
      },
      { className: 'type', // function types
        begin: ':[ \t]*', end: '[^A-Za-z0-9_ \t\\->]',
        excludeBegin: true, excludeEnd: true,
      },
      { className: 'type', // types
        begin: ':[ \t]*', end: '\\W',
        excludeBegin: true, excludeEnd: true,
      },
      { className: 'type', // instantiation
        begin: 'new *', end: '\\W',
        excludeBegin: true, excludeEnd: true,
      },
      { className: 'class', // enums
        beginKeywords: 'enum', end: '\\{',
        contains: [
          hljs.TITLE_MODE
        ]
      },
      { className: 'class', // abstracts
        beginKeywords: 'abstract', end: '[\\{$]',
        contains: [
          { className: 'type',
            begin: '\\(', end: '\\)',
            excludeBegin: true, excludeEnd: true,
          },
          { className: 'type',
            begin: 'from *', end: '\\W',
            excludeBegin: true, excludeEnd: true,
          },
          { className: 'type',
            begin: 'to *', end: '\\W',
            excludeBegin: true, excludeEnd: true,
          },
          hljs.TITLE_MODE
        ],
        keywords: {
          keyword: 'abstract from to'
        }
      },
      { className: 'class', // classes
        beginKeywords: 'class interface', end: '{', excludeEnd: true,
        keywords: {
          keyword: 'class interface extends implements'
        }
      }
    ]
  };
}
<|endoftext|>


<commit_before>import '@polymer/polymer/polymer-legacy.js';
import './d2l-table-observer-behavior.js';
import './d2l-tspan-resize-observer-polyfill.js';
import './d2l-td.js';
import { Polymer } from '@polymer/polymer/lib/legacy/polymer-fn.js';
import { dom } from '@polymer/polymer/lib/legacy/polymer.dom.js';
import { afterNextRender } from '@polymer/polymer/lib/utils/render-status.js';
const $_documentContainer = document.createElement('template');

$_documentContainer.innerHTML = `<dom-module id="d2l-tspan">
	<template strip-whitespace="">

		<d2l-td id="cell">

				<slot></slot>

		</d2l-td>
	</template>

</dom-module>`;

document.head.appendChild($_documentContainer.content);
Polymer({
	is: 'd2l-tspan',
	behaviors: [
		D2L.PolymerBehaviors.Table.LocalObserverBehavior
	],
	properties: {
		role: {
			type: String,
			value: 'row',
			readonly: true,
			reflectToAttribute: true
		},
		selected: {
			type: Boolean,
			value: false,
			reflectToAttribute: true,
			observer: '_selectedChanged'
		},
		_boundFocusOutHandler: {
			type: Function,
			value: function() {
				return this._focusOutHandler.bind(this);
			}
		},
		_boundFocusInHandler: {
			type: Function,
			value: function() {
				return this._focusInHandler.bind(this);
			}
		},
		focusedStyling: {
			type: Boolean,
			value: false,
			reflectToAttribute: true
		},
		_feedbackInFocus: {
			type: Boolean,
			value: false,
			reflectToAttribute: true
		}
	},
	ready: function() {
		this._sizeObserver = new ResizeObserver(this._onSizeChanged.bind(this));
	},
	attached: function() {
		var slot = dom(this.root).querySelector('#float');
		this._sizeObserver.observe(slot);
		afterNextRender(this, function() {
			slot.addEventListener('focusout', this._boundFocusOutHandler);
			slot.addEventListener('focusin', this._boundFocusInHandler);
		}.bind(this));
	},
	detached: function() {
		var slot = dom(this.root).querySelector('#float');
		this._sizeObserver.unobserve(slot);
		slot.removeEventListener('focusout', this._boundFocusOutHandler);
		slot.removeEventListener('focusin', this._boundFocusInHandler);
	},
	_selectedChanged: function(selected) {
		this.setAttribute('aria-selected', selected.toString());
	},
	_onSizeChanged: function() {
		if (this.root.host) {
			this.root.host.style.height = this.$.float.offsetHeight + 'px';
		}
	},
	_focusInHandler: function() {
		if (this.focusedStyling && !this._feedbackInFocus) {
			this._feedbackInFocus = true;
		}
	},
	_focusOutHandler: function() {
		if (this.focusedStyling) {
			this._feedbackInFocus = false;
		}
	}
});
<commit_msg>remove afterNextRender from tspan when adding listeners<commit_after>import '@polymer/polymer/polymer-legacy.js';
import './d2l-table-observer-behavior.js';
import './d2l-tspan-resize-observer-polyfill.js';
import './d2l-td.js';
import { Polymer } from '@polymer/polymer/lib/legacy/polymer-fn.js';
import { dom } from '@polymer/polymer/lib/legacy/polymer.dom.js';
import { afterNextRender } from '@polymer/polymer/lib/utils/render-status.js';
const $_documentContainer = document.createElement('template');

$_documentContainer.innerHTML = `<dom-module id="d2l-tspan">
	<template strip-whitespace="">

		<d2l-td id="cell">

				<slot></slot>

		</d2l-td>
	</template>

</dom-module>`;

document.head.appendChild($_documentContainer.content);
Polymer({
	is: 'd2l-tspan',
	behaviors: [
		D2L.PolymerBehaviors.Table.LocalObserverBehavior
	],
	properties: {
		role: {
			type: String,
			value: 'row',
			readonly: true,
			reflectToAttribute: true
		},
		selected: {
			type: Boolean,
			value: false,
			reflectToAttribute: true,
			observer: '_selectedChanged'
		},
		_boundFocusOutHandler: {
			type: Function,
			value: function() {
				return this._focusOutHandler.bind(this);
			}
		},
		_boundFocusInHandler: {
			type: Function,
			value: function() {
				return this._focusInHandler.bind(this);
			}
		},
		focusedStyling: {
			type: Boolean,
			value: false,
			reflectToAttribute: true
		},
		_feedbackInFocus: {
			type: Boolean,
			value: false,
			reflectToAttribute: true
		}
	},
	ready: function() {
		this._sizeObserver = new ResizeObserver(this._onSizeChanged.bind(this));
	},
	attached: function() {
		var slot = dom(this.root).querySelector('#float');
		this._sizeObserver.observe(slot);
		if (this.focusedStyling) {
			slot.addEventListener('focusout', this._boundFocusOutHandler);
			slot.addEventListener('focusin', this._boundFocusInHandler);
		}
	},
	detached: function() {
		var slot = dom(this.root).querySelector('#float');
		this._sizeObserver.unobserve(slot);
		if (this.focusedStyling) {
			slot.removeEventListener('focusout', this._boundFocusOutHandler);
			slot.removeEventListener('focusin', this._boundFocusInHandler);
		}
	},
	_selectedChanged: function(selected) {
		this.setAttribute('aria-selected', selected.toString());
	},
	_onSizeChanged: function() {
		if (this.root.host) {
			this.root.host.style.height = this.$.float.offsetHeight + 'px';
		}
	},
	_focusInHandler: function() {
		if (this.focusedStyling && !this._feedbackInFocus) {
			this._feedbackInFocus = true;
		}
	},
	_focusOutHandler: function() {
		if (this.focusedStyling) {
			this._feedbackInFocus = false;
		}
	}
});
<|endoftext|>


<commit_before>/*
Language: Ruby
Author: Anton Kovalyov <anton@kovalyov.net>
Contributors: Peter Leonov <gojpeg@yandex.ru>, Vasily Polovnyov <vast@whiteants.net>, Loren Segal <lsegal@soen.ca>
*/

function(hljs) {
  var RUBY_IDENT_RE = '[a-zA-Z_][a-zA-Z0-9_]*(\\!|\\?)?';
  var RUBY_METHOD_RE = '[a-zA-Z_]\\w*[!?=]?|[-+~]\\@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?';
  var RUBY_KEYWORDS = {
    keyword:
      'and false then defined module in return redo if BEGIN retry end for true self when ' +
      'next until do begin unless END rescue nil else break undef not super class case ' +
      'require yield alias while ensure elsif or include'
  };
  var YARDOCTAG = {
    className: 'yardoctag',
    begin: '@[A-Za-z]+'
  };
  var COMMENTS = [
    {
      className: 'comment',
      begin: '#', end: '$',
      contains: [YARDOCTAG]
    },
    {
      className: 'comment',
      begin: '^\\=begin', end: '^\\=end',
      contains: [YARDOCTAG],
      relevance: 10
    },
    {
      className: 'comment',
      begin: '^__END__', end: '\\n$'
    }
  ];
  var SUBST = {
    className: 'subst',
    begin: '#\\{', end: '}',
    lexems: RUBY_IDENT_RE,
    keywords: RUBY_KEYWORDS
  };
  var STR_CONTAINS = [hljs.BACKSLASH_ESCAPE, SUBST];
  var STRINGS = [
    {
      className: 'string',
      begin: '\'', end: '\'',
      contains: STR_CONTAINS,
      relevance: 0
    },
    {
      className: 'string',
      begin: '"', end: '"',
      contains: STR_CONTAINS,
      relevance: 0
    },
    {
      className: 'string',
      begin: '%[qw]?\\(', end: '\\)',
      contains: STR_CONTAINS
    },
    {
      className: 'string',
      begin: '%[qw]?\\[', end: '\\]',
      contains: STR_CONTAINS
    },
    {
      className: 'string',
      begin: '%[qw]?{', end: '}',
      contains: STR_CONTAINS
    },
    {
      className: 'string',
      begin: '%[qw]?<', end: '>',
      contains: STR_CONTAINS,
      relevance: 10
    },
    {
      className: 'string',
      begin: '%[qw]?/', end: '/',
      contains: STR_CONTAINS,
      relevance: 10
    },
    {
      className: 'string',
      begin: '%[qw]?%', end: '%',
      contains: STR_CONTAINS,
      relevance: 10
    },
    {
      className: 'string',
      begin: '%[qw]?-', end: '-',
      contains: STR_CONTAINS,
      relevance: 10
    },
    {
      className: 'string',
      begin: '%[qw]?\\|', end: '\\|',
      contains: STR_CONTAINS,
      relevance: 10
    }
  ];
  var FUNCTION = {
    className: 'function',
    beginWithKeyword: true, end: ' |$|;',
    keywords: 'def',
    contains: [
      {
        className: 'title',
        begin: RUBY_METHOD_RE,
        lexems: RUBY_IDENT_RE,
        keywords: RUBY_KEYWORDS
      },
      {
        className: 'params',
        begin: '\\(', end: '\\)',
        lexems: RUBY_IDENT_RE,
        keywords: RUBY_KEYWORDS
      }
    ].concat(COMMENTS)
  };

  var RUBY_DEFAULT_CONTAINS = COMMENTS.concat(STRINGS.concat([
    {
      className: 'class',
      beginWithKeyword: true, end: '$|;',
      keywords: 'class module',
      contains: [
        {
          className: 'title',
          begin: '[A-Za-z_]\\w*(::\\w+)*(\\?|\\!)?',
          relevance: 0
        },
        {
          className: 'inheritance',
          begin: '<\\s*',
          contains: [{
            className: 'parent',
            begin: '(' + hljs.IDENT_RE + '::)?' + hljs.IDENT_RE
          }]
        }
      ].concat(COMMENTS)
    },
    FUNCTION,
    {
      className: 'constant',
      begin: '(::)?(\\b[A-Z]\\w*(::)?)+',
      relevance: 0
    },
    {
      className: 'symbol',
      begin: ':',
      contains: STRINGS.concat([{begin: RUBY_IDENT_RE, relevance: 0}]),
      relevance: 0
    },
    {
      className: 'number',
      begin: '(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b',
      relevance: 0
    },
    {
      className: 'number',
      begin: '\\?\\w'
    },
    {
      className: 'variable',
      begin: '(\\$\\W)|((\\$|\\@\\@?)(\\w+))'
    },
    { // regexp container
      begin: '(' + hljs.RE_STARTERS_RE + ')\\s*',
      contains: COMMENTS.concat([
        {
          className: 'regexp',
          begin: '/', end: '/[a-z]*',
          illegal: '\\n',
          contains: [hljs.BACKSLASH_ESCAPE]
        }
      ]),
      relevance: 0
    }
  ]));
  SUBST.contains = RUBY_DEFAULT_CONTAINS;
  FUNCTION.contains[1].contains = RUBY_DEFAULT_CONTAINS;

  return {
    defaultMode: {
      lexems: RUBY_IDENT_RE,
      keywords: RUBY_KEYWORDS,
      contains: RUBY_DEFAULT_CONTAINS
    }
  };
}
<commit_msg>Count :identifier symbols toward Ruby relevance<commit_after>/*
Language: Ruby
Author: Anton Kovalyov <anton@kovalyov.net>
Contributors: Peter Leonov <gojpeg@yandex.ru>, Vasily Polovnyov <vast@whiteants.net>, Loren Segal <lsegal@soen.ca>
*/

function(hljs) {
  var RUBY_IDENT_RE = '[a-zA-Z_][a-zA-Z0-9_]*(\\!|\\?)?';
  var RUBY_METHOD_RE = '[a-zA-Z_]\\w*[!?=]?|[-+~]\\@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?';
  var RUBY_KEYWORDS = {
    keyword:
      'and false then defined module in return redo if BEGIN retry end for true self when ' +
      'next until do begin unless END rescue nil else break undef not super class case ' +
      'require yield alias while ensure elsif or include'
  };
  var YARDOCTAG = {
    className: 'yardoctag',
    begin: '@[A-Za-z]+'
  };
  var COMMENTS = [
    {
      className: 'comment',
      begin: '#', end: '$',
      contains: [YARDOCTAG]
    },
    {
      className: 'comment',
      begin: '^\\=begin', end: '^\\=end',
      contains: [YARDOCTAG],
      relevance: 10
    },
    {
      className: 'comment',
      begin: '^__END__', end: '\\n$'
    }
  ];
  var SUBST = {
    className: 'subst',
    begin: '#\\{', end: '}',
    lexems: RUBY_IDENT_RE,
    keywords: RUBY_KEYWORDS
  };
  var STR_CONTAINS = [hljs.BACKSLASH_ESCAPE, SUBST];
  var STRINGS = [
    {
      className: 'string',
      begin: '\'', end: '\'',
      contains: STR_CONTAINS,
      relevance: 0
    },
    {
      className: 'string',
      begin: '"', end: '"',
      contains: STR_CONTAINS,
      relevance: 0
    },
    {
      className: 'string',
      begin: '%[qw]?\\(', end: '\\)',
      contains: STR_CONTAINS
    },
    {
      className: 'string',
      begin: '%[qw]?\\[', end: '\\]',
      contains: STR_CONTAINS
    },
    {
      className: 'string',
      begin: '%[qw]?{', end: '}',
      contains: STR_CONTAINS
    },
    {
      className: 'string',
      begin: '%[qw]?<', end: '>',
      contains: STR_CONTAINS,
      relevance: 10
    },
    {
      className: 'string',
      begin: '%[qw]?/', end: '/',
      contains: STR_CONTAINS,
      relevance: 10
    },
    {
      className: 'string',
      begin: '%[qw]?%', end: '%',
      contains: STR_CONTAINS,
      relevance: 10
    },
    {
      className: 'string',
      begin: '%[qw]?-', end: '-',
      contains: STR_CONTAINS,
      relevance: 10
    },
    {
      className: 'string',
      begin: '%[qw]?\\|', end: '\\|',
      contains: STR_CONTAINS,
      relevance: 10
    }
  ];
  var FUNCTION = {
    className: 'function',
    beginWithKeyword: true, end: ' |$|;',
    keywords: 'def',
    contains: [
      {
        className: 'title',
        begin: RUBY_METHOD_RE,
        lexems: RUBY_IDENT_RE,
        keywords: RUBY_KEYWORDS
      },
      {
        className: 'params',
        begin: '\\(', end: '\\)',
        lexems: RUBY_IDENT_RE,
        keywords: RUBY_KEYWORDS
      }
    ].concat(COMMENTS)
  };

  var RUBY_DEFAULT_CONTAINS = COMMENTS.concat(STRINGS.concat([
    {
      className: 'class',
      beginWithKeyword: true, end: '$|;',
      keywords: 'class module',
      contains: [
        {
          className: 'title',
          begin: '[A-Za-z_]\\w*(::\\w+)*(\\?|\\!)?',
          relevance: 0
        },
        {
          className: 'inheritance',
          begin: '<\\s*',
          contains: [{
            className: 'parent',
            begin: '(' + hljs.IDENT_RE + '::)?' + hljs.IDENT_RE
          }]
        }
      ].concat(COMMENTS)
    },
    FUNCTION,
    {
      className: 'constant',
      begin: '(::)?(\\b[A-Z]\\w*(::)?)+',
      relevance: 0
    },
    {
      className: 'symbol',
      begin: ':',
      contains: STRINGS.concat([{begin: RUBY_IDENT_RE}]),
      relevance: 0
    },
    {
      className: 'number',
      begin: '(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b',
      relevance: 0
    },
    {
      className: 'number',
      begin: '\\?\\w'
    },
    {
      className: 'variable',
      begin: '(\\$\\W)|((\\$|\\@\\@?)(\\w+))'
    },
    { // regexp container
      begin: '(' + hljs.RE_STARTERS_RE + ')\\s*',
      contains: COMMENTS.concat([
        {
          className: 'regexp',
          begin: '/', end: '/[a-z]*',
          illegal: '\\n',
          contains: [hljs.BACKSLASH_ESCAPE]
        }
      ]),
      relevance: 0
    }
  ]));
  SUBST.contains = RUBY_DEFAULT_CONTAINS;
  FUNCTION.contains[1].contains = RUBY_DEFAULT_CONTAINS;

  return {
    defaultMode: {
      lexems: RUBY_IDENT_RE,
      keywords: RUBY_KEYWORDS,
      contains: RUBY_DEFAULT_CONTAINS
    }
  };
}
<|endoftext|>


<commit_before>/*
Language: VHDL
Author: Igor Kalnitsky <igor@kalnitsky.org>
Contributors: Daniel C.K. Kho <daniel.kho@gmail.com>
Description: VHDL is a hardware description language used in electronic design automation to describe digital and mixed-signal systems.
*/

hljs.LANGUAGES.vhdl = function() {
  return {
    case_insensitive: true,
    defaultMode: {
      keywords: {
        'keyword': {
            'abs': 1,               'access': 1,            'after': 1,
            'alias': 1,             'all': 1,               'and': 1,
            'architecture': 2,      'array': 1,             'assert': 1,
            'attribute': 1,         'begin': 1,             'block': 1,
            'body': 1,              'buffer': 1,            'bus': 1,
            'case': 1,              'component': 2,         'configuration': 1,
            'constant': 1,          'context': 1,           'cover': 1,
            'disconnect': 2,        'downto': 2,            'default': 1,
            'else': 1,              'elsif': 1,             'end': 1,
            'entity': 2,            'exit': 1,              'fairness': 1,
            'file': 1,              'for': 1,               'force': 1,
            'function': 1,          'generate': 2,          'generic': 2,
            'group': 1,             'guarded': 2,           'if': 0,
            'impure': 2,            'in': 1,                'inertial': 1,
            'inout': 1,             'is': 1,                'label': 1,
            'library': 1,           'linkage': 1,           'literal': 1,
            'loop': 1,              'map': 1,               'mod': 1,
            'nand': 1,              'new': 1,               'next': 1,
            'nor': 1,               'not': 1,               'null': 1,
            'of': 1,                'on': 1,                'open': 1,
            'or': 1,                'others': 1,            'out': 1,
            'package': 1,           'port': 2,              'postponed': 1,
            'procedure': 1,         'process': 1,           'property': 1,
            'protected':1,          'pure': 2,              'range': 1,
            'record': 1,            'register': 1,          'reject': 1,
            'release':1,            'rem':1,                'report': 1,
            'restrict':1,           'restrict_guarantee':1, 'return': 1,
            'rol': 1,               'ror': 1,               'select': 1,
            'sequence':1,           'severity': 1,          'shared': 1,
            'signal': 1,            'sla': 1,               'sll': 1,
            'sra': 1,               'srl': 1,               'strong':1,
            'subtype': 2,           'then': 1,              'to': 1,
            'transport': 1,         'type': 1,              'unaffected': 1,
            'units': 1,             'until': 1,             'use': 1,
            'variable': 1,          'vmode':1,              'vprop': 1,
            'vunit':1,              'wait': 1,              'when': 1,
            'while': 1,             'with': 1,              'xnor': 1,
            'xor': 1
        },

        'typename': {
            'boolean': 1,           'bit': 1,               'character': 1,
            'severity_level': 2,    'integer': 1,           'time': 1,
            'delay_length': 2,      'natural': 1,           'positive': 1,
            'string': 1,            'bit_vector': 2,        'file_open_kind': 2,
            'file_open_status': 2,  'std_ulogic': 2,        'std_ulogic_vector': 2,
            'std_logic': 2,         'std_logic_vector': 2,  'unsigned': 1,
            'signed': 1,            'boolean_vector': 1,    'integer_vector': 1,
            'real_vector': 1,       'time_vector': 1
        }
      },
      illegal: '{',
      contains: [
        hljs.C_BLOCK_COMMENT_MODE,        // VHDL-2008 block commenting.
        {
          className: 'comment',
          begin: '--', end: '$'
        },
        hljs.QUOTE_STRING_MODE,
        hljs.C_NUMBER_MODE,
        {
          className: 'literal',
          begin: '\'(U|X|0|1|Z|W|L|H|-)', end: '\'',
          contains: [hljs.BACKSLASH_ESCAPE]
        },
        {
          className: 'attribute',
          begin: '\'[A-Za-z](_?[A-Za-z0-9])*',
          contains: [hljs.BACKSLASH_ESCAPE]
        }
      ]
    } // defaultMode
  } // return;
}();
<commit_msg>Change to 1 all relevance values in VHDL lexer.<commit_after>/*
Language: VHDL
Author: Igor Kalnitsky <igor@kalnitsky.org>
Contributors: Daniel C.K. Kho <daniel.kho@gmail.com>
Description: VHDL is a hardware description language used in electronic design automation to describe digital and mixed-signal systems.
*/

hljs.LANGUAGES.vhdl = function() {
  return {
    case_insensitive: true,
    defaultMode: {
      keywords: {
        'keyword': {
            'abs': 1,               'access': 1,            'after': 1,
            'alias': 1,             'all': 1,               'and': 1,
            'architecture': 1,      'array': 1,             'assert': 1,
            'attribute': 1,         'begin': 1,             'block': 1,
            'body': 1,              'buffer': 1,            'bus': 1,
            'case': 1,              'component': 1,         'configuration': 1,
            'constant': 1,          'context': 1,           'cover': 1,
            'disconnect': 1,        'downto': 2,            'default': 1,
            'else': 1,              'elsif': 1,             'end': 1,
            'entity': 1,            'exit': 1,              'fairness': 1,
            'file': 1,              'for': 1,               'force': 1,
            'function': 1,          'generate': 1,          'generic': 1,
            'group': 1,             'guarded': 1,           'if': 1,
            'impure': 1,            'in': 1,                'inertial': 1,
            'inout': 1,             'is': 1,                'label': 1,
            'library': 1,           'linkage': 1,           'literal': 1,
            'loop': 1,              'map': 1,               'mod': 1,
            'nand': 1,              'new': 1,               'next': 1,
            'nor': 1,               'not': 1,               'null': 1,
            'of': 1,                'on': 1,                'open': 1,
            'or': 1,                'others': 1,            'out': 1,
            'package': 1,           'port': 1,              'postponed': 1,
            'procedure': 1,         'process': 1,           'property': 1,
            'protected':1,          'pure': 1,              'range': 1,
            'record': 1,            'register': 1,          'reject': 1,
            'release':1,            'rem':1,                'report': 1,
            'restrict':1,           'restrict_guarantee':1, 'return': 1,
            'rol': 1,               'ror': 1,               'select': 1,
            'sequence':1,           'severity': 1,          'shared': 1,
            'signal': 1,            'sla': 1,               'sll': 1,
            'sra': 1,               'srl': 1,               'strong':1,
            'subtype': 1,           'then': 1,              'to': 1,
            'transport': 1,         'type': 1,              'unaffected': 1,
            'units': 1,             'until': 1,             'use': 1,
            'variable': 1,          'vmode': 1,             'vprop': 1,
            'vunit':1,              'wait': 1,              'when': 1,
            'while': 1,             'with': 1,              'xnor': 1,
            'xor': 1
        },

        'typename': {
            'boolean': 1,           'bit': 1,               'character': 1,
            'severity_level': 1,    'integer': 1,           'time': 1,
            'delay_length': 1,      'natural': 1,           'positive': 1,
            'string': 1,            'bit_vector': 1,        'file_open_kind': 1,
            'file_open_status': 1,  'std_ulogic': 1,        'std_ulogic_vector': 1,
            'std_logic': 1,         'std_logic_vector': 1,  'unsigned': 1,
            'signed': 1,            'boolean_vector': 1,    'integer_vector': 1,
            'real_vector': 1,       'time_vector': 1
        }
      },
      illegal: '{',
      contains: [
        hljs.C_BLOCK_COMMENT_MODE,        // VHDL-2008 block commenting.
        {
          className: 'comment',
          begin: '--', end: '$'
        },
        hljs.QUOTE_STRING_MODE,
        hljs.C_NUMBER_MODE,
        {
          className: 'literal',
          begin: '\'(U|X|0|1|Z|W|L|H|-)', end: '\'',
          contains: [hljs.BACKSLASH_ESCAPE]
        },
        {
          className: 'attribute',
          begin: '\'[A-Za-z](_?[A-Za-z0-9])*',
          contains: [hljs.BACKSLASH_ESCAPE]
        }
      ]
    } // defaultMode
  } // return;
}();
<|endoftext|>


<commit_before>var daemonize = function ( method, period, reinitializer ) {
	var delayedFunction = null,
		keepRunning = true,
		postStop = null;

	if ( typeof method !== 'function' ) {
		throw new TypeError( 'Argument 0 ( Method ) should be a function' );
	}

	if ( typeof period !== 'number' ) {
		throw new TypeError( 'Argument 1 ( Period ) should be a number' );
	}

    if (typeof reinitalizer !== "undefined") {
        if (typeof reinitializer !== 'function' ) {
		    throw new TypeError( 'Argument 2 ( Method ) should be a function' );
        }
    } else {
        var reinitializer = reinitializer || function (){};
    }

    /**
     * Public functions
     */
	return {

        /**
		 * Start running the function. Run it 'numRuns' times. If no 'numRuns' value is
		 * given, run until 'stop' is called.
		 */
		start: function( numRuns ) {
			var me = this;
			if ( keepRunning ) {
				postStop = null;
				method();
                if (typeof numRuns === 'undefined' || typeof numRuns != 'number') {
   					delayedFunction = setTimeout( me['start'].bind(me), period);
                } else if (typeof numRuns === 'number'){
                    if ( numRuns > 1 ) {
                        delayedFunction = setTimeout( me['start'].bind( me, (--numRuns) ),
                           							  period );
                    } else {
                        keepRunning = false;
                        return true;
                    }
                }
			} else {
				if ( postStop ) setTimeout( postStop(), period );
			}
		},

        /**
		 * Stop running the function.
		 */
		stop: function () {
			keepRunning = false;
		},

 		/**
		 * Start running the function again. If a number of runs was initially given, it
		 * is ignored. On restart, the function runs either indefinitely, or the number of
         * times passed into this function (numRuns).
		 */
		restart: function ( numRuns ) {
			var me = this;
			if ( !keepRunning ) {
    			keepRunning = true;
   				if ( numRuns && typeof numRuns === "number" ) me.start( numRuns )
                else me.start();
			} else {
				postStop = function () {
					reinitializer();
					keepRunning = true;
                    if ( typeof numRuns !== 'undefined' && typeof numRuns === 'number' ) {
                        me['start'].bind( me )( numRuns );
                    } else {
                        me['start'].bind( me )();
                    }
				};
				me.stop();
			}
		},

        /**
         * Return whether or not the function is currently running.
         */
		status: function () {
			return keepRunning;
		}
	};
};
<commit_msg>Added 'addRepeats' function<commit_after>var daemonize = function ( method, period, reinitializer ) {
		var
            delayedFunction = null,
			keepRunning = true,
			postStop = null,
            moreRepeats = 0;

		if ( typeof method !== 'function' ) {
			throw new TypeError( 'Argument 0 ( Method ) should be a function' );
		}

		if ( typeof period !== 'number' ) {
			throw new TypeError( 'Argument 1 ( Period ) should be a number' );
		}

        if (typeof reinitalizer !== "undefined") {
            if (typeof reinitializer !== 'function' ) {
			    throw new TypeError( 'Argument 2 ( Method ) should be a function' );
            }
        } else {
            var reinitializer = reinitializer || function (){};
        }

        /**
         * Public functions
         */
		return {

            /**
			 * Start running the function. Run it 'numRuns' times. If no 'numRuns' value is
			 * given, run until 'stop' is called.
			 */
			start: function( numRuns ) {
				var me = this;
				if ( keepRunning ) {
					postStop = null;
					method();
                    if (typeof numRuns === 'undefined' || typeof numRuns != 'number') {
    					delayedFunction = setTimeout( me['start'].bind(me), period);
                    } else if (typeof numRuns === 'number'){
                        if ( numRuns > 1 ) {
                            delayedFunction = setTimeout( me['start'].bind( me, (--numRuns) ),
                            							  period );
                        } else {
                            if (moreRepeats > 0) {
                                var repeats = moreRepeats;
                                moreRepeats = me.moreRepeats = 0;
                            delayedFunction = setTimeout( me['start'].bind( me, repeats ),
                            							  period );
                            } else {
                                keepRunning = false;
                                return true;
                            }
                        }
                    }
				} else {
					if ( postStop ) setTimeout( postStop(), period );
				}
			},

            /**
			 * Stop running the function.
			 */
			stop: function () {
				keepRunning = false;
			},

 			/**
			 * Start running the function again. If a number of runs was initially given, it
			 * is ignored. On restart, the function runs either indefinitely, or the number of
             * times passed into this function (numRuns).
			 */
			restart: function ( numRuns ) {
				var me = this;
				if ( !keepRunning ) {
    				keepRunning = true;
   					if ( numRuns && typeof numRuns === "number" ) me.start( numRuns )
                    else me.start();
				} else {
					postStop = function () {
						reinitializer();
						keepRunning = true;
                        if ( typeof numRuns !== 'undefined' && typeof numRuns === 'number' ) {
                            me['start'].bind( me )( numRuns );
                        } else {
                            me['start'].bind( me )();
                        }
					};
					me.stop();
				}
			},

            /**
             * Add numToAdd to the number of times the function will run. If doRunImmediately,
             * instantly launch not running. Otherwise just add it to a cumulative # of times
             * it will run once it's launched. If the function is already running and non-infinite,
             * add numToAdd to the number of times it will run.
             */
            addRepeats: function(numToAdd, doRunImmediately) {
				var me = this,
                    newNum;
                moreRepeats = me.moreRepeats = moreRepeats + numToAdd;
                if (keepRunning === false) {
                    if (doRunImmediately !== "undefined" && doRunImmediately === true) {
                        newNum = moreRepeats;
                        moreRepeats = me.moreRepeats = 0;
						keepRunning = true;
                        me['start'].bind( me )( newNum );
                    }
                }
            },

            /**
             * Return whether or not the function is currently running.
             */
			status: function () {
				return keepRunning;
			},
		};
};
<|endoftext|>


<commit_before>function setModel(options) {
  return options.map(n => {
    const { name, query } = n;
    return {
      name,
      query
    };
  });
}

function setState(model, handleChange) {
  return model.map(({ name, query }) => {
    const match = window.matchMedia(query);
    match.add = () => match.addListener(handleChange);
    match.add();
    match.remove = () => match.removeListener(handleChange);

    return {
      name,
      match
    };
  });
}

class MatchMedia {
  constructor(list) {
    this.listeners = [];
    this.state = [];
    this.model = setModel(list.slice());

    return this.updateState();
  }

  handleChange() {
    this.state.slice().forEach(({ match }) => match.remove());

    return this.updateState();
  }

  updateState() {
    this.state =
      setState(this.model, this.handleChange.bind(this));

    return this.dispatchUpdate();
  }

  getCurrentName() {
    const current =
      this.state.filter(({ match }) => match.matches);

    const { name } =
      (current.length > 0)
        ? current[0]
        : this.model[0];

    return name;
  }

  dispatchUpdate() {
    const current = this.getCurrentName();
    return this.listeners
      .slice()
      .forEach(listener => listener(current));
  }

  subscribe(listener) {
    this.listeners.push(listener);

    return function unsubscribe() {
      const index = this.listeners.indexOf(listener);
      this.listeners = this.listeners.slice(index, 1);
    };
  }
}

export default function matchMedia(list) {
  const mM = new MatchMedia(list);

  return {
    subscribe: mM.subscribe.bind(mM),
    getCurrentName: mM.getCurrentName()
  };
}
<commit_msg>Only unsubscribe if we have an array of listeners.<commit_after>function setModel(options) {
  return options.map(n => {
    const { name, query } = n;
    return {
      name,
      query
    };
  });
}

function setState(model, handleChange) {
  return model.map(({ name, query }) => {
    const match = window.matchMedia(query);
    match.add = () => match.addListener(handleChange);
    match.add();
    match.remove = () => match.removeListener(handleChange);

    return {
      name,
      match
    };
  });
}

class MatchMedia {
  constructor(list) {
    this.listeners = [];
    this.state = [];
    this.model = setModel(list.slice());

    return this.updateState();
  }

  handleChange() {
    this.state.slice().forEach(({ match }) => match.remove());

    return this.updateState();
  }

  updateState() {
    this.state =
      setState(this.model, this.handleChange.bind(this));

    return this.dispatchUpdate();
  }

  getCurrentName() {
    const current =
      this.state.filter(({ match }) => match.matches);

    const { name } =
      (current.length > 0)
        ? current[0]
        : this.model[0];

    return name;
  }

  dispatchUpdate() {
    const current = this.getCurrentName();
    return this.listeners
      .slice()
      .forEach(listener => listener(current));
  }

  subscribe(listener) {
    this.listeners.push(listener);

    return function unsubscribe() {
      if (this.listeners != null) {
        const index = this.listeners.indexOf(listener);
        this.listeners = this.listeners.slice(index, 1);
      }
    };
  }
}

export default function matchMedia(list) {
  const mM = new MatchMedia(list);

  return {
    subscribe: mM.subscribe.bind(mM),
    getCurrentName: mM.getCurrentName()
  };
}
<|endoftext|>


<commit_before>
var Diff = require('./diff');
var Equality = require('./equality');
var Search = require('./search');

exports.addAssertionsTo = function (expect) {

    expect.addAssertion('ReactElement', 'to have [exactly] rendered', function (expect, subject, renderOutput) {

        var exactly = this.flags.exactly;

        expect.withError(function () {
            return Equality.assertElementsMatch(subject, renderOutput, expect, {
                exactly: exactly
            });
        }, function (e) {
            return expect.fail({
                diff : function (output, diff, inspect, equal) {
                    return Diff.diffElements(subject, renderOutput, output, diff, inspect, equal, {
                        exactly: exactly
                    });
                }
            });
        });
    });

    expect.addAssertion('ReactElement', 'to contain', function (expect, subject, expected) {

        if (!Search.findElementIn(subject, expected, expect, {
                exactly: false
            })) {
            expect.fail();
        }
    });

    expect.addAssertion('ReactElement', 'to contain exactly', function (expect, subject, expected) {

        if (!Search.findElementIn(subject, expected, expect, {
                exactly: true
            })) {
            expect.fail();
        }
    });

    expect.addAssertion('ReactElement', 'to satisfy', function (expect, subject, expected) {

        return expect(subject, 'to have rendered', expected);
    });

    expect.addAssertion('ReactShallowRenderer', 'to have [exactly] rendered', function (expect, subject, renderOutput) {

        var actual = subject.getRenderOutput();
        return expect(actual, 'to have ' + (this.flags.exactly ? 'exactly ' : '') + 'rendered', renderOutput);
    });

    expect.addAssertion('ReactShallowRenderer', 'to contain', function (expect, subject, expected) {

        var actual = subject.getRenderOutput();
        return expect(actual, 'to contain', expected);
    });

    expect.addAssertion('ReactShallowRenderer', 'to contain exactly', function (expect, subject, expected) {

        var actual = subject.getRenderOutput();
        return expect(actual, 'to contain exactly', expected);
    });

};<commit_msg>Make [exactly] a flag for `to contain`<commit_after>
var Diff = require('./diff');
var Equality = require('./equality');
var Search = require('./search');

exports.addAssertionsTo = function (expect) {

    expect.addAssertion('ReactElement', 'to have [exactly] rendered', function (expect, subject, renderOutput) {

        var exactly = this.flags.exactly;

        expect.withError(function () {
            return Equality.assertElementsMatch(subject, renderOutput, expect, {
                exactly: exactly
            });
        }, function (e) {
            return expect.fail({
                diff : function (output, diff, inspect, equal) {
                    return Diff.diffElements(subject, renderOutput, output, diff, inspect, equal, {
                        exactly: exactly
                    });
                }
            });
        });
    });

    expect.addAssertion('ReactElement', 'to contain [exactly]', function (expect, subject, expected) {

        if (!Search.findElementIn(subject, expected, expect, {
                exactly: this.flags.exactly
            })) {
            expect.fail();
        }
    });

    expect.addAssertion('ReactElement', 'to satisfy', function (expect, subject, expected) {

        return expect(subject, 'to have rendered', expected);
    });

    expect.addAssertion('ReactShallowRenderer', 'to have [exactly] rendered', function (expect, subject, renderOutput) {

        var actual = subject.getRenderOutput();
        return expect(actual, 'to have ' + (this.flags.exactly ? 'exactly ' : '') + 'rendered', renderOutput);
    });

    expect.addAssertion('ReactShallowRenderer', 'to contain', function (expect, subject, expected) {

        var actual = subject.getRenderOutput();
        return expect(actual, 'to contain', expected);
    });

    expect.addAssertion('ReactShallowRenderer', 'to contain exactly', function (expect, subject, expected) {

        var actual = subject.getRenderOutput();
        return expect(actual, 'to contain exactly', expected);
    });

};<|endoftext|>